@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.
@@ -1,10 +1,16 @@
1
1
  import fs from 'node:fs';
2
+ import { piCompactionCommand, piCompactionOverrides } from './pi-compaction.ts';
3
+ import { promptArgs, unattendedFlags } from './agent-flags.ts';
4
+ import { isHerdrAgentWaiting, isLeaderHerdrAgent, isLeaderTerminal, isTerminalWaiting } from './agent-waiting.ts';
5
+ import { PI_SESSION_TAIL_SCRIPT, budgetExhaustedIn, compactionFailedIn, piContextStuck, resumeTimeFrom, stuckReason, type PiSessionTail, type StuckKind } from './stuck.ts';
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
+ import { HANDOFF_GATHER_SCRIPT, buildHandoff, decisionsBy, parseGather, redactSecrets } from './handoff.ts';
2
8
  import os from 'node:os';
3
9
  import path from 'node:path';
4
10
  import crypto from 'node:crypto';
5
11
  import { TicketRepository } from '../db/ticket-repo.ts';
6
12
  import { RunRepository } from '../db/run-repo.ts';
7
- import { SettingsRepository } from '../db/settings-repo.ts';
13
+ import { SettingsRepository, azureSubscriptions } from '../db/settings-repo.ts';
8
14
  import { EventBus } from '../sse/event-bus.ts';
9
15
  import { DockerClient, type DockerContainerSummary } from '../runner/docker-client.ts';
10
16
  import { Watchdog } from './watchdog.ts';
@@ -34,8 +40,9 @@ import { HubMountError, HubSession, proposeUrls } from './hub-session.ts';
34
40
  import { AzureDevOpsApiError, AzureDevOpsClient } from '../runner/azure-devops-client.ts';
35
41
  import { azureRepoUrl, parseAzureRepoUrl, repoHostOf, repoLabel, validateRepoUrl } from './repo-host.ts';
36
42
  import { parseSourceUrl, type PullRequestHit, type SourceHubInfo, type SourceHubRef, type SourceHubRepoStatus, type SourceInfo, type SourceRef } from './pr-source.ts';
37
- import { AgyLoginManager, CLAUDE_LOGIN_SPEC, CODEX_LOGIN_SPEC, COPILOT_LOGIN_SPEC, type AgyLoginDriver } from './agy-login.ts';
38
- import { buildSetupState } from './setup.ts';
43
+ import { UpdateChecker } from './updates.ts';
44
+ import { AgyLoginManager, AZURE_LOGIN_SPEC, CLAUDE_LOGIN_SPEC, CODEX_LOGIN_SPEC, COPILOT_LOGIN_SPEC, type AgyLoginDriver } from './agy-login.ts';
45
+ import { buildSetupState, parseRunnerManifest } from './setup.ts';
39
46
  import { HUB_DIR, NAME_RE, agentGaps, analysisPrompt, buildAnalysis, fixedGaps, parseAgentAnswer, parseHubToml, repoNameFromUrl, teamAgentFor, teamAgents, type HubToml } from './hub.ts';
40
47
  import {
41
48
  validateGitHubUrl,
@@ -45,11 +52,14 @@ import {
45
52
  parseJiraIssueUrl,
46
53
  normalizeJiraSite,
47
54
  isValidAgent,
55
+ SUPPORTED_AGENTS,
56
+ type SupportedAgent,
48
57
  type HubAnalysis,
49
58
  type HubFix,
50
59
  type RepoDelivery,
51
60
  type Run,
52
61
  type Ticket,
62
+ type LoopConfig,
53
63
  type CreateTicketInput,
54
64
  type RunState,
55
65
  type FailureReason,
@@ -60,6 +70,27 @@ import {
60
70
  } from '../types.ts';
61
71
  import type { AppConfig } from '../config.ts';
62
72
 
73
+ /** Gaps that are the hub agent's opinion, which a person may overrule («Seguir sin ellos»). */
74
+ const HUB_OPINION_GAPS = new Set(['missing_repo', 'agent_not_ready']);
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
+
79
+ /** az's config in a run: no prompts about subscriptions, no telemetry. */
80
+ const AZURE_RUN_CONFIG = '[core]\nlogin_experience_v2 = off\ncollect_telemetry = false\n';
81
+
82
+ /** azureProfile.json with `subscriptionId` as the default subscription (the others stay). */
83
+ export function azureProfileWithDefault(profileText: string, subscriptionId: string): string {
84
+ const doc = JSON.parse(profileText.replace(/^\uFEFF/, '')) as { subscriptions?: Array<Record<string, unknown>> };
85
+ for (const sub of doc.subscriptions ?? []) sub.isDefault = sub.id === subscriptionId;
86
+ return JSON.stringify(doc);
87
+ }
88
+
89
+ /** The waits the loop puts the run in (loopWait): only the person ends them. */
90
+ export function isLoopWaitReason(reason: string | null | undefined): boolean {
91
+ return /^(gru necesita a una persona|Loop parado|Loop terminado con evaluación negativa)/.test(String(reason ?? ''));
92
+ }
93
+
63
94
  export class NotFoundError extends Error {
64
95
  constructor(message: string) {
65
96
  super(message);
@@ -244,6 +275,10 @@ export class Orchestrator {
244
275
  public azure: AzureDevOpsClient = new AzureDevOpsClient();
245
276
 
246
277
  private reconcileTimer: NodeJS.Timeout | null = null;
278
+ /** Issue #3 P3: the stuck-agent sweep, and what it found per run (its waiting reason). */
279
+ private stuckTimer: NodeJS.Timeout | null = null;
280
+ private stuckByRun = new Map<string, { name: string; kind: StuckKind; reason: string; resets?: string | null }>();
281
+ private checkingStuck = false;
247
282
  private inFlightTerminations = new Set<string>();
248
283
  private startingRuns = new Set<string>();
249
284
  private isReconciling = false;
@@ -279,6 +314,10 @@ export class Orchestrator {
279
314
  private rebuildImpl: (image: string, options?: RunnerBuildOptions) => Promise<void>;
280
315
  // P4: deliveries in progress (verify, commit, push, PR), one per run.
281
316
  private deliveries = new Map<string, Promise<Run>>();
317
+ /** Issue #3: runs with an agent relaunch in progress (one at a time per run). */
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>();
282
321
  // P4: a token given explicitly at start (not stored); delivery falls back to the stored one.
283
322
  private runTokens = new Map<string, string>();
284
323
  // P5: hub analyses in progress (fixed checks, hub agent, then the team), one per run.
@@ -297,6 +336,9 @@ export class Orchestrator {
297
336
  public claudeLoginManager: AgyLoginManager;
298
337
  public codexLoginManager: AgyLoginManager;
299
338
  public copilotLoginManager: AgyLoginManager;
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();
300
342
  public jira: JiraClient;
301
343
 
302
344
  constructor(
@@ -357,6 +399,15 @@ export class Orchestrator {
357
399
  maxDurationMs: 15 * 60 * 1000,
358
400
  onToken: (content) => this.settingsRepo.setCredential('copilot', content, 'copilot-login'),
359
401
  });
402
+ // Issue #4 (P1): the person's Azure session (device code), kept in the credential store (D3).
403
+ this.azureLoginManager = new AgyLoginManager({
404
+ runnerImage: config.runnerImage,
405
+ dataDir: config.dataDir,
406
+ driver: agyLoginDriver,
407
+ spec: AZURE_LOGIN_SPEC,
408
+ maxDurationMs: 15 * 60 * 1000,
409
+ onToken: (content) => this.settingsRepo.setAzureLogin(JSON.parse(content)),
410
+ });
360
411
  if (this.config.dataDir) {
361
412
  this.settingsRepo.setDataDir(this.config.dataDir);
362
413
  }
@@ -373,6 +424,11 @@ export class Orchestrator {
373
424
  });
374
425
  }, this.config.reconcileIntervalMs);
375
426
  }
427
+ if (this.config.stuckCheckIntervalMs > 0) {
428
+ this.stuckTimer = setInterval(() => {
429
+ this.checkStuckAgents().catch(() => {});
430
+ }, this.config.stuckCheckIntervalMs);
431
+ }
376
432
  }
377
433
 
378
434
  async stop(): Promise<void> {
@@ -381,10 +437,16 @@ export class Orchestrator {
381
437
  clearInterval(this.reconcileTimer);
382
438
  this.reconcileTimer = null;
383
439
  }
440
+ if (this.stuckTimer) {
441
+ clearInterval(this.stuckTimer);
442
+ this.stuckTimer = null;
443
+ }
384
444
  await this.agyLoginManager.cancel();
385
445
  await this.claudeLoginManager.cancel();
386
446
  await this.codexLoginManager.cancel();
387
447
  await this.copilotLoginManager.cancel();
448
+ await this.azureLoginManager.cancel();
449
+ this.updates.stop();
388
450
  for (const [, w] of this.runPrWatchers.entries()) {
389
451
  try { w.stop(); } catch {}
390
452
  }
@@ -974,6 +1036,48 @@ export class Orchestrator {
974
1036
  }
975
1037
  }
976
1038
 
1039
+ /**
1040
+ * Issue #4 (P2): why a ticket with «Login de Azure» cannot start (no session, expired, a
1041
+ * subscription the session does not have), or null when it can (or does not ask).
1042
+ */
1043
+ azureLoginProblem(ticket: Ticket): string | null {
1044
+ if (!ticket.azure_login) return null;
1045
+ const doc = this.settingsRepo.getAzureLogin();
1046
+ if (!doc) return 'el ticket pide «Login de Azure» y no hay sesión: inicia sesión en Ajustes → Azure';
1047
+ const summary = this.settingsRepo.getAzureLoginSummary();
1048
+ if (summary.expired) return 'la sesión de Azure ha caducado: vuelve a iniciar sesión en Ajustes → Azure';
1049
+ const sub = ticket.azure_subscription || doc.subscription_id;
1050
+ if (!sub || !azureSubscriptions(doc.profile).some((x) => x.id === sub)) {
1051
+ return `la suscripción de Azure del ticket (${sub ?? 'ninguna'}) no es de la sesión: elige otra en el ticket o en Ajustes → Azure`;
1052
+ }
1053
+ return null;
1054
+ }
1055
+
1056
+ /**
1057
+ * Issue #4 (P2): the person's Azure session in the run, when the ticket asks: az's two files
1058
+ * in /home/runner/.azure (0600, as runner, by stdin; never in -e, arguments or the image),
1059
+ * with the ticket's subscription (or the default) as the default one. D5: what az renews in
1060
+ * the run stays there and goes with the container.
1061
+ */
1062
+ async injectAzureLogin(containerName: string, ticket: Ticket): Promise<boolean> {
1063
+ if (!ticket.azure_login) return false;
1064
+ const problem = this.azureLoginProblem(ticket);
1065
+ if (problem) throw new Error(problem);
1066
+ const doc = this.settingsRepo.getAzureLogin()!;
1067
+ const sub = (ticket.azure_subscription || doc.subscription_id)!;
1068
+ const write = (file: string, content: string) => this.dockerClient.injectStdin(containerName, ['sh', '-c',
1069
+ `set -eu; umask 077; mkdir -p /home/runner/.azure; cat > /home/runner/.azure/${file}; chmod 600 /home/runner/.azure/${file}`], content, 'runner');
1070
+ for (const [file, content] of [
1071
+ ['msal_token_cache.json', doc.msal],
1072
+ ['azureProfile.json', azureProfileWithDefault(doc.profile, sub)],
1073
+ ['config', AZURE_RUN_CONFIG],
1074
+ ] as const) {
1075
+ const res = await write(file, content);
1076
+ if (res.exitCode !== 0) throw new Error(`No se pudo dejar la sesión de Azure en el run (${file}): ${res.stderr.trim()}`);
1077
+ }
1078
+ return true;
1079
+ }
1080
+
977
1081
  async prepareAgentEnv(containerName: string, home = '/home/runner', withSources = true): Promise<string[]> {
978
1082
  const write = async (dest: string, content: string) => {
979
1083
  const res = await this.dockerClient.injectStdin(
@@ -1013,6 +1117,17 @@ export class Orchestrator {
1013
1117
  }
1014
1118
  written.push(destPath);
1015
1119
  }
1120
+ // bond#92: tune pi's compaction for the small-window models of that models.json, in the
1121
+ // container's settings.json (entries already there win). Failing here never blocks the run.
1122
+ if (wanted.has('pi')) {
1123
+ const models = this.settingsRepo.getCredential('pi')?.config_json;
1124
+ const overrides = models ? piCompactionOverrides(models) : {};
1125
+ if (Object.keys(overrides).length) {
1126
+ const res = await this.dockerClient.injectStdin(containerName, piCompactionCommand(`${home}/.pi/agent/settings.json`), JSON.stringify(overrides), 'runner');
1127
+ if (res.exitCode === 0) written.push(`${home}/.pi/agent/settings.json`);
1128
+ else console.warn(`[bond-app] pi compaction tuning skipped (exit ${res.exitCode}): ${res.stderr.trim()}`);
1129
+ }
1130
+ }
1016
1131
  // W-P4: prompt-suggestions config for supi, written next to pi's models.json when a
1017
1132
  // suggestions model is stored (null = «sin sugerencias» writes nothing). The supi
1018
1133
  // package itself comes with the runner image (image plan P2); until then the file is
@@ -1595,21 +1710,8 @@ export class Orchestrator {
1595
1710
  if (anyWorking) {
1596
1711
  isBlocked = false;
1597
1712
  } else if (agents.length > 0) {
1598
- const isWaiting = (a: { agent_status?: string; completion_seq?: number; question?: unknown }) => {
1599
- if (a.agent_status === 'blocked' || a.agent_status === 'waiting') return true;
1600
- if (a.question) return true;
1601
- const seq = typeof a.completion_seq === 'number' ? a.completion_seq : Number(a.completion_seq || 0);
1602
- return (a.agent_status === 'idle' || a.agent_status === 'done') && seq > 0;
1603
- };
1604
- const isLeader = (a: { cwd?: string; pane_id?: string; name?: string }) => {
1605
- if (a.name === 'gru' || a.name === 'hub leader' || a.name === 'hub-leader' || a.name === 'leader' || a.name === 'orquestador') {
1606
- return true;
1607
- }
1608
- const cleanCwd = a.cwd?.replace(/\/+$/, '');
1609
- if (cleanCwd === '/workspace/hub') return true;
1610
- if (a.pane_id === 'w1:p1' && (!a.name || a.name === 'pi' || a.name === 'agent' || a.name === 'gru')) return true;
1611
- return false;
1612
- };
1713
+ const isWaiting = isHerdrAgentWaiting;
1714
+ const isLeader = isLeaderHerdrAgent;
1613
1715
  const waiting = agents.filter(isWaiting);
1614
1716
  const leader = agents.find(isLeader);
1615
1717
  const leaderWaiting = Boolean(leader && isWaiting(leader));
@@ -1643,19 +1745,8 @@ export class Orchestrator {
1643
1745
  if (anyWorking) {
1644
1746
  isBlocked = false;
1645
1747
  } else if (live.length > 0) {
1646
- const isWaiting = (t: { status: string | null; turn?: number }) => {
1647
- if (t.status === 'blocked' || t.status === 'waiting') return true;
1648
- return (t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0;
1649
- };
1650
- const isLeader = (t: { name?: string; cwd?: string; address?: string }) => {
1651
- if (t.name === 'gru' || t.name === 'hub leader' || t.name === 'hub-leader' || t.name === 'leader' || t.name === 'orquestador') {
1652
- return true;
1653
- }
1654
- const cleanCwd = t.cwd?.replace(/\/+$/, '');
1655
- if (cleanCwd === '/workspace/hub') return true;
1656
- if (t.address?.endsWith('/t1')) return true;
1657
- return false;
1658
- };
1748
+ const isWaiting = isTerminalWaiting;
1749
+ const isLeader = isLeaderTerminal;
1659
1750
  const waiting = live.filter(isWaiting);
1660
1751
  const leader = live.find(isLeader);
1661
1752
  const leaderWaiting = Boolean(leader && isWaiting(leader));
@@ -1693,7 +1784,7 @@ export class Orchestrator {
1693
1784
  } catch {}
1694
1785
  }
1695
1786
  if (!notSignedInBlocked) {
1696
- const isWaiting = t.status === 'blocked' || ((t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0);
1787
+ const isWaiting = isTerminalWaiting(t);
1697
1788
  if (isWaiting) {
1698
1789
  isBlocked = true;
1699
1790
  waitingAgentName = ticket.agent || 'agente';
@@ -1718,8 +1809,15 @@ export class Orchestrator {
1718
1809
  }
1719
1810
  }
1720
1811
 
1812
+ // The loop is waiting for the person (gru's needs-human, a stall, a negative evaluation):
1813
+ // that wait is the person's to end («Reanudar», «Iniciar loop»), not the agents' screens.
1814
+ if (latest.state === 'waiting' && isLoopWaitReason(latest.failure_reason)) continue;
1815
+
1721
1816
  if (isBlocked) {
1722
- const reason = `Esperando respuesta: ${waitingAgentName}`;
1817
+ // A stuck agent (issue #3 P3) has a more precise reason than «waiting for an answer».
1818
+ const reason = latest.resume_at && latest.failure_reason
1819
+ ? latest.failure_reason
1820
+ : this.stuckByRun.get(r.id)?.reason ?? `Esperando respuesta: ${waitingAgentName}`;
1723
1821
  if (latest.state === 'running') {
1724
1822
  if (this.setState(r.id, 'running', 'waiting', reason)) {
1725
1823
  this.ticketRepo.updateStatus(r.ticket_id, 'waiting');
@@ -1731,6 +1829,7 @@ export class Orchestrator {
1731
1829
  }
1732
1830
  } else if (latest.state === 'waiting') {
1733
1831
  // Every agent is working again (answered or resumed)
1832
+ this.stuckByRun.delete(r.id);
1734
1833
  if (this.setState(r.id, 'waiting', 'running', null)) {
1735
1834
  this.ticketRepo.updateStatus(r.ticket_id, 'running');
1736
1835
  this.agentEvent(latest, 'agent.resumed', {});
@@ -1742,6 +1841,480 @@ export class Orchestrator {
1742
1841
  return transitioned;
1743
1842
  }
1744
1843
 
1844
+ /**
1845
+ * Issue #3 P3: find the run agents that are stuck (a full context with compaction no longer
1846
+ * able to help, or an exhausted budget), never asking them anything: the screen and, for pi,
1847
+ * the tail of its session file. A finding becomes the run's waiting reason
1848
+ * («<name>: contexto lleno…»), on which the Agents panel offers «Relanzar con resumen». Only
1849
+ * agents that are not working are looked at. Returns the runs whose reason it set.
1850
+ */
1851
+ async checkStuckAgents(): Promise<string[]> {
1852
+ if (this.checkingStuck) return [];
1853
+ this.checkingStuck = true;
1854
+ const changed: string[] = [];
1855
+ try {
1856
+ changed.push(...(await this.runScheduledResumes()));
1857
+ for (const r of this.runRepo.listActive().filter((x) => x.state === 'running' || x.state === 'waiting')) {
1858
+ if (!r.hc_machine || !r.container_name) continue;
1859
+ // A resume is scheduled (P4): its reason says when; nothing to look at until then.
1860
+ if (r.resume_at) continue;
1861
+ if (this.startingRuns.has(r.id) || this.inFlightTerminations.has(r.id) || this.deliveries.has(r.id) || this.relaunching.has(r.id)) continue;
1862
+ let found: { name: string; kind: StuckKind; reason: string; resets?: string | null } | null = null;
1863
+ try {
1864
+ const terms = (await this.hcClient.getMachineTerminals(r.hc_machine)).filter(
1865
+ (t) => t.state === 'live' && t.status !== 'working' && Boolean(t.address) && /^[a-z][a-z0-9_-]{0,31}$/.test(String(t.name ?? ''))
1866
+ );
1867
+ for (const t of terms) {
1868
+ const name = String(t.name);
1869
+ let screen = '';
1870
+ try {
1871
+ screen = await this.hcClient.readTerminal(t.address!, 60);
1872
+ } catch {
1873
+ screen = '';
1874
+ }
1875
+ let finding = budgetExhaustedIn(screen) ?? compactionFailedIn(screen);
1876
+ if (!finding) {
1877
+ let argv: string[] | undefined;
1878
+ try {
1879
+ argv = (await this.hcClient.getTerminal(t.address!)).argv;
1880
+ } catch {
1881
+ argv = undefined;
1882
+ }
1883
+ if (agentKindOfArgv(argv) === 'pi') {
1884
+ const res = await this.dockerClient.exec(r.container_name, ['node', '-e', PI_SESSION_TAIL_SCRIPT, t.cwd || '/workspace/repo'], 'runner', 20_000);
1885
+ let tail: Partial<PiSessionTail> | null = null;
1886
+ try {
1887
+ tail = res.exitCode === 0 ? JSON.parse(res.stdout || '{}') : null;
1888
+ } catch {
1889
+ tail = null;
1890
+ }
1891
+ finding = piContextStuck(tail);
1892
+ }
1893
+ }
1894
+ if (finding) {
1895
+ found = { name, kind: finding.kind, reason: stuckReason(name, finding), resets: finding.resets ?? null };
1896
+ break;
1897
+ }
1898
+ }
1899
+ } catch {
1900
+ continue;
1901
+ }
1902
+ const previous = this.stuckByRun.get(r.id);
1903
+ if (!found) {
1904
+ this.stuckByRun.delete(r.id);
1905
+ continue;
1906
+ }
1907
+ this.stuckByRun.set(r.id, found);
1908
+ const latest = this.runRepo.get(r.id);
1909
+ if (!latest) continue;
1910
+ if (latest.state === 'running') {
1911
+ if (this.setState(r.id, 'running', 'waiting', found.reason)) {
1912
+ this.ticketRepo.updateStatus(r.ticket_id, 'waiting');
1913
+ changed.push(r.id);
1914
+ }
1915
+ } else if (latest.state === 'waiting' && latest.failure_reason !== found.reason) {
1916
+ this.runRepo.update(r.id, { failure_reason: found.reason });
1917
+ changed.push(r.id);
1918
+ }
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
+ }
1937
+ }
1938
+ } finally {
1939
+ this.checkingStuck = false;
1940
+ }
1941
+ return changed;
1942
+ }
1943
+
1944
+ /**
1945
+ * Issue #3 P4 «Reanudar al restablecerse»: keep the same agent and tell it to go on when its
1946
+ * budget comes back. The time comes from its screen («resets 3pm», «try again in 2 hours»)
1947
+ * or from `at` (ISO), within the next 7 days. Survives a restart (on the run).
1948
+ */
1949
+ async scheduleResume(runId: string, name: string, at?: unknown): Promise<Run> {
1950
+ const run = this.runRepo.get(runId);
1951
+ if (!run) throw new NotFoundError(`Run '${runId}' not found`);
1952
+ if (run.state !== 'waiting') throw new ValidationError(`Only a waiting run can schedule a resume (this one is '${run.state}')`);
1953
+ if (!/^[a-z][a-z0-9_-]{0,31}$/.test(name)) throw new ValidationError(`Invalid agent name '${name}'`);
1954
+ let when: Date | null = null;
1955
+ if (typeof at === 'string' && at.trim()) {
1956
+ when = new Date(at);
1957
+ if (Number.isNaN(when.getTime())) throw new ValidationError(`Invalid time '${at}'`);
1958
+ } else {
1959
+ const stuck = this.stuckByRun.get(runId);
1960
+ if (!stuck || stuck.name !== name || stuck.kind !== 'budget') {
1961
+ throw new ValidationError(`${name} is not waiting for its budget: give the time ('at')`);
1962
+ }
1963
+ when = resumeTimeFrom(stuck.resets);
1964
+ if (!when) throw new ValidationError(`Cannot tell when the budget of ${name} comes back: give the time ('at')`);
1965
+ }
1966
+ const now = Date.now();
1967
+ if (when.getTime() <= now || when.getTime() > now + 7 * 24 * 3_600_000) {
1968
+ throw new ValidationError('The resume time must be within the next 7 days');
1969
+ }
1970
+ const hhmm = when.toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' });
1971
+ const base = this.stuckByRun.get(runId)?.reason ?? `${name}: presupuesto agotado.`;
1972
+ const reason = `${base.replace(/ Relánzalo[^]*$/, '')} Se reanudará a las ${hhmm}.`;
1973
+ this.runRepo.update(runId, { resume_at: when.toISOString(), resume_agent: name, failure_reason: reason });
1974
+ this.agentEvent(run, 'agent.resume_scheduled', { agent: name, at: when.toISOString() });
1975
+ return this.runRepo.get(runId)!;
1976
+ }
1977
+
1978
+ /** P4: the scheduled resumes that are due: tell the agent to go on, the run runs again. */
1979
+ async runScheduledResumes(now: Date = new Date()): Promise<string[]> {
1980
+ const resumed: string[] = [];
1981
+ for (const r of this.runRepo.listActive()) {
1982
+ if (!r.resume_at || new Date(r.resume_at).getTime() > now.getTime()) continue;
1983
+ const name = r.resume_agent || 'gru';
1984
+ this.runRepo.update(r.id, { resume_at: null, resume_agent: null });
1985
+ this.stuckByRun.delete(r.id);
1986
+ let address: string | undefined;
1987
+ try {
1988
+ address = (await this.hcClient.getMachineTerminals(r.hc_machine!)).find((t) => t.name === name && t.state === 'live')?.address;
1989
+ } catch {
1990
+ address = undefined;
1991
+ }
1992
+ if (!address) {
1993
+ this.runRepo.update(r.id, { failure_reason: `${name}: no se pudo reanudar, el agente ya no está. Relánzalo con resumen.` });
1994
+ continue;
1995
+ }
1996
+ try {
1997
+ await this.hcClient.sendText(address, 'Tu presupuesto se ha restablecido: continúa con la tarea donde la dejaste.');
1998
+ } catch {
1999
+ this.runRepo.update(r.id, { failure_reason: `${name}: no se pudo reanudar (no acepta mensajes). Relánzalo con resumen.` });
2000
+ continue;
2001
+ }
2002
+ const latest = this.runRepo.get(r.id)!;
2003
+ this.agentEvent(latest, 'agent.resumed', { agent: name, after: 'budget' });
2004
+ if (latest.state === 'waiting' && this.setState(r.id, 'waiting', 'running', null)) {
2005
+ this.ticketRepo.updateStatus(r.ticket_id, 'running');
2006
+ }
2007
+ resumed.push(r.id);
2008
+ }
2009
+ return resumed;
2010
+ }
2011
+
2012
+ // ---- LOOP P3 (issue #2): the loop engine --------------------------------------------
2013
+
2014
+ /** Per run: the next question number and the questions waiting for gru's answer. */
2015
+ private loopAsks = new Map<string, { next: number; pending: Map<number, { agent: string; reply: (r: Record<string, unknown>) => Promise<void> }> }>();
2016
+
2017
+ /** gru's live terminal in the run, or null. */
2018
+ private async gruAddress(run: Run): Promise<string | null> {
2019
+ if (!run.hc_machine) return null;
2020
+ try {
2021
+ const terms = await this.hcClient.getMachineTerminals(run.hc_machine);
2022
+ const live = terms.filter((t) => t.state === 'live');
2023
+ return live.find((t) => t.name === 'gru')?.address ?? live.find((t) => t.address === run.hc_terminal)?.address ?? null;
2024
+ } catch {
2025
+ return null;
2026
+ }
2027
+ }
2028
+
2029
+ private loopRun(runId: string): { run: Run; ticket: Ticket } {
2030
+ const run = this.runRepo.get(runId);
2031
+ if (!run) throw new NotFoundError(`Run '${runId}' not found`);
2032
+ const ticket = this.ticketRepo.get(run.ticket_id);
2033
+ if (!ticket) throw new NotFoundError(`Ticket '${run.ticket_id}' not found`);
2034
+ return { run, ticket };
2035
+ }
2036
+
2037
+ /** Tell gru something about the loop (best effort: the loop state is what matters). */
2038
+ private async tellGru(run: Run, text: string): Promise<void> {
2039
+ const gru = await this.gruAddress(run);
2040
+ if (!gru) return;
2041
+ try {
2042
+ await this.hcClient.sendText(gru, text);
2043
+ } catch {
2044
+ /* gru will read the state with bond-app loop status */
2045
+ }
2046
+ }
2047
+
2048
+ /** The questions still waiting when the loop ends get an answer that says so. */
2049
+ private async dropLoopAsks(runId: string, why: string): Promise<void> {
2050
+ const asks = this.loopAsks.get(runId);
2051
+ this.loopAsks.delete(runId);
2052
+ for (const p of asks?.pending.values() ?? []) await p.reply({ ok: false, message: why }).catch(() => {});
2053
+ }
2054
+
2055
+ /**
2056
+ * D6: «Iniciar loop» from the run. The ticket must have the loop enabled (hub, D7) and gru must
2057
+ * be there. Installs the loop commands and skills in the run, turns on BOND_LOOP for every
2058
+ * agent (loop.env through agent-env.sh: running agents see it from their next command), and
2059
+ * tells gru to start with loop-lead.
2060
+ */
2061
+ async startLoop(runId: string, opts: { plan?: unknown; instructions?: unknown; max_iterations?: unknown } = {}): Promise<Run> {
2062
+ const { run, ticket } = this.loopRun(runId);
2063
+ if (!ticket.loop?.enabled) throw new ValidationError('Este ticket no tiene el modo loop activado');
2064
+ if (ticket.mode !== 'hub') throw new ValidationError('El modo loop solo está disponible en tickets de hub');
2065
+ if (run.state !== 'running' && run.state !== 'waiting') throw new ValidationError(`El loop arranca con el run en marcha o en espera (este está '${run.state}')`);
2066
+ if (run.loop_state === 'running' || run.loop_state === 'paused' || run.loop_state === 'finishing') throw new ValidationError('El loop ya está en marcha');
2067
+ if (!run.container_name || !run.hc_machine) throw new ValidationError('El run no tiene contenedor o sesión de hc');
2068
+ const instructions = opts.instructions === undefined || opts.instructions === null ? '' : String(opts.instructions).trim();
2069
+ if (instructions.length > LOOP_TEXT_MAX) throw new ValidationError(`Las instrucciones pasan de ${LOOP_TEXT_MAX} caracteres`);
2070
+ let max: number | null = ticket.loop.max_iterations;
2071
+ if (opts.max_iterations !== undefined) {
2072
+ const m = opts.max_iterations;
2073
+ if (m !== null && !(Number.isInteger(m) && (m as number) >= 1 && (m as number) <= 1000)) throw new ValidationError('Iteraciones: un entero de 1 a 1000, o null (sin límite)');
2074
+ max = m as number | null;
2075
+ }
2076
+ const gru = await this.gruAddress(run);
2077
+ if (!gru) throw new ValidationError('gru no está en marcha: relánzalo antes de iniciar el loop');
2078
+ // No plan file: the plan is the ticket's story (gru writes it in docs/plans/ first).
2079
+ let plan = '';
2080
+ if (opts.plan !== undefined && opts.plan !== null && opts.plan !== '') {
2081
+ plan = String(opts.plan);
2082
+ const plans = PLAN_PATH_RE.test(plan) ? await this.listLoopPlans(run.id) : [];
2083
+ if (!plans.includes(plan)) throw new ValidationError(`El plan '${plan.slice(0, 120)}' no está en docs/plans/ del hub`);
2084
+ }
2085
+
2086
+ await this.installBondAppCli(run.container_name);
2087
+ await this.ensureRunPrWatcher(run.id, run.container_name);
2088
+ const skills = await this.dockerClient.exec(run.container_name, ['sh', '-c', LOOP_SKILLS_SCRIPT, 'bond-loop-skills', HUB_DIR], 'runner', 60_000);
2089
+ if (skills.exitCode === 4) {
2090
+ throw new ValidationError('La imagen del run trae un bond sin las skills del loop (loop-lead, loop-member): reconstruye la imagen con un bond que las incluya');
2091
+ }
2092
+ if (skills.exitCode !== 0) throw new Error(`No se pudieron instalar las skills del loop: ${skills.stderr.trim() || skills.stdout.trim()}`);
2093
+ const env = await this.dockerClient.injectStdin(run.container_name, LOOP_ENV_ON_COMMAND, loopEnv(run.id), 'runner');
2094
+ if (env.exitCode !== 0) throw new Error(`No se pudo activar el entorno del loop: ${env.stderr.trim()}`);
2095
+ // The person's set-up at the top of the loop log: gru rereads it every round (it survives
2096
+ // a compaction or a relaunch, unlike the first message).
2097
+ await this.appendLoopLog(run, loopLogStart(new Date().toISOString(), plan, max, instructions));
2098
+
2099
+ const loopConfig: LoopConfig = { plan, instructions, max_iterations: max, messages: [] };
2100
+ this.runRepo.update(run.id, { loop_state: 'running', loop_iteration: 0, loop_stalls: 0, loop_config: loopConfig });
2101
+ this.loopAsks.set(run.id, { next: 1, pending: new Map() });
2102
+ // A run left waiting by the previous loop (a stall, a negative evaluation) goes on.
2103
+ const fresh = this.runRepo.get(run.id)!;
2104
+ if (fresh.state === 'waiting' && isLoopWaitReason(fresh.failure_reason) && this.setState(run.id, 'waiting', 'running', null)) {
2105
+ this.ticketRepo.updateStatus(fresh.ticket_id, 'running');
2106
+ }
2107
+ await this.hcClient.sendText(gru, loopStartMessage(run.id, max, plan, instructions));
2108
+ this.agentEvent(run, 'loop.started', { max_iterations: max, plan, instructions: Boolean(instructions) });
2109
+ return this.runRepo.get(run.id)!;
2110
+ }
2111
+
2112
+ /** The plans gru can carry out (docs/plans/*.md of the hub), newest first. */
2113
+ async listLoopPlans(runId: string): Promise<string[]> {
2114
+ const { run } = this.loopRun(runId);
2115
+ if (!run.container_name) return [];
2116
+ const res = await this.dockerClient.exec(run.container_name, ['sh', '-c', LOOP_PLANS_SCRIPT, 'bond-loop-plans', HUB_DIR], 'runner', 30_000);
2117
+ return res.exitCode === 0 ? sortPlans(res.stdout) : [];
2118
+ }
2119
+
2120
+ /**
2121
+ * «Mensaje a gru»: the person's instruction while the loop runs. It goes to the loop log
2122
+ * (so gru keeps it across rounds) and to gru's terminal.
2123
+ */
2124
+ async messageLoop(runId: string, textIn: unknown): Promise<Run> {
2125
+ const { run } = this.loopRun(runId);
2126
+ if (run.loop_state !== 'running' && run.loop_state !== 'paused' && run.loop_state !== 'finishing') {
2127
+ throw new ValidationError('No hay un loop en marcha al que mandar instrucciones');
2128
+ }
2129
+ const text = typeof textIn === 'string' ? textIn.trim() : '';
2130
+ if (!text) throw new ValidationError('El mensaje está vacío');
2131
+ if (text.length > LOOP_TEXT_MAX) throw new ValidationError(`El mensaje pasa de ${LOOP_TEXT_MAX} caracteres`);
2132
+ const gru = await this.gruAddress(run);
2133
+ if (!gru) throw new ValidationError('gru no está en marcha: relánzalo antes de mandarle instrucciones');
2134
+ const at = new Date().toISOString();
2135
+ await this.appendLoopLog(run, loopLogMessage(at, text));
2136
+ const cfg: LoopConfig = run.loop_config ?? { plan: '', instructions: '', max_iterations: null, messages: [] };
2137
+ this.runRepo.update(run.id, { loop_config: { ...cfg, messages: [...(cfg.messages ?? []), { at, text }].slice(-50) } });
2138
+ await this.hcClient.sendText(gru, loopMessageText(run.id, text));
2139
+ this.agentEvent(run, 'loop.message', { text });
2140
+ return this.runRepo.get(run.id)!;
2141
+ }
2142
+
2143
+ /** Append to the loop log in the hub (as runner). */
2144
+ private async appendLoopLog(run: Run, block: string): Promise<void> {
2145
+ const res = await this.dockerClient.injectStdin(run.container_name!, ['sh', '-c', LOOP_LOG_APPEND_SCRIPT, 'bond-loop-log', HUB_DIR, loopLogPath(run.id), run.id], block, 'runner');
2146
+ if (res.exitCode !== 0) throw new Error(`No se pudo escribir el registro del loop: ${res.stderr.trim()}`);
2147
+ }
2148
+
2149
+ /** The loop's iteration limit: the one chosen at «Iniciar loop», else the ticket's. */
2150
+ private loopMax(run: Run, ticket: Ticket): number | null {
2151
+ if (run.loop_config && run.loop_config.max_iterations !== undefined) return run.loop_config.max_iterations;
2152
+ return ticket.loop?.max_iterations ?? null;
2153
+ }
2154
+
2155
+ async pauseLoop(runId: string): Promise<Run> {
2156
+ const { run } = this.loopRun(runId);
2157
+ if (run.loop_state !== 'running' && run.loop_state !== 'finishing') throw new ValidationError('No hay un loop en marcha que pausar');
2158
+ this.runRepo.update(run.id, { loop_state: 'paused' });
2159
+ await this.tellGru(run, '[bond-app loop] Pausa: termina el paso en curso, no repartas más trabajo y espera.');
2160
+ this.agentEvent(run, 'loop.paused', { by: 'person' });
2161
+ return this.runRepo.get(run.id)!;
2162
+ }
2163
+
2164
+ async resumeLoop(runId: string): Promise<Run> {
2165
+ const { run } = this.loopRun(runId);
2166
+ if (run.loop_state !== 'paused') throw new ValidationError('El loop no está en pausa');
2167
+ this.runRepo.update(run.id, { loop_state: 'running' });
2168
+ if (!this.loopAsks.has(run.id)) this.loopAsks.set(run.id, { next: 1, pending: new Map() });
2169
+ await this.tellGru(run, '[bond-app loop] La persona ha reanudado el loop: sigue donde lo dejaste.');
2170
+ this.agentEvent(run, 'loop.resumed', {});
2171
+ const fresh = this.runRepo.get(run.id)!;
2172
+ if (fresh.state === 'waiting' && this.setState(run.id, 'waiting', 'running', null)) this.ticketRepo.updateStatus(fresh.ticket_id, 'running');
2173
+ return this.runRepo.get(run.id)!;
2174
+ }
2175
+
2176
+ /** Stop the loop (the person, or a stall): no more rounds; BOND_LOOP off; the run waits. */
2177
+ async stopLoop(runId: string, reason = 'la persona lo ha parado'): Promise<Run> {
2178
+ const { run } = this.loopRun(runId);
2179
+ if (!run.loop_state || run.loop_state === 'finished' || run.loop_state === 'stopped') throw new ValidationError('No hay un loop que parar');
2180
+ this.runRepo.update(run.id, { loop_state: 'stopped' });
2181
+ if (run.container_name) await this.dockerClient.exec(run.container_name, LOOP_ENV_OFF_COMMAND, 'runner').catch(() => undefined);
2182
+ await this.dropLoopAsks(run.id, 'El loop se ha parado: sigue sin gru y cuéntalo en tu informe.');
2183
+ await this.tellGru(run, `[bond-app loop] El loop se ha parado (${reason}): no repartas más trabajo, deja el registro del loop al día y espera a la persona.`);
2184
+ this.agentEvent(run, 'loop.stopped', { reason });
2185
+ // The person ended the loop: a wait the loop had put the run in is over (a stall sets its own after this).
2186
+ const fresh = this.runRepo.get(run.id)!;
2187
+ if (fresh.state === 'waiting' && isLoopWaitReason(fresh.failure_reason) && this.setState(run.id, 'waiting', 'running', null)) {
2188
+ this.ticketRepo.updateStatus(fresh.ticket_id, 'running');
2189
+ }
2190
+ return this.runRepo.get(run.id)!;
2191
+ }
2192
+
2193
+ /** The run waits for the person, with a reason (from running; or the reason changes). */
2194
+ private loopWait(runId: string, reason: string): void {
2195
+ const run = this.runRepo.get(runId);
2196
+ if (!run) return;
2197
+ if (run.state === 'running') {
2198
+ if (this.setState(runId, 'running', 'waiting', reason)) this.ticketRepo.updateStatus(run.ticket_id, 'waiting');
2199
+ } else if (run.state === 'waiting') {
2200
+ this.runRepo.update(runId, { failure_reason: reason });
2201
+ }
2202
+ }
2203
+
2204
+ /**
2205
+ * A request from the run's `bond-app ask|answer|loop` (FIFO). Returns the answer to write
2206
+ * back, or null when it comes later (a question waits for gru's answer).
2207
+ */
2208
+ async handleLoopRequest(runId: string, req: Record<string, unknown>, reply: (r: Record<string, unknown>) => Promise<void>): Promise<Record<string, unknown> | null> {
2209
+ const { run, ticket } = this.loopRun(runId);
2210
+ const state = run.loop_state ?? null;
2211
+ const active = state === 'running' || state === 'finishing';
2212
+ const agent = typeof req.agent === 'string' ? req.agent.slice(0, 64) : '';
2213
+ const text = (v: unknown) => (typeof v === 'string' ? v.trim().slice(0, LOOP_TEXT_MAX) : '');
2214
+ const max = this.loopMax(run, ticket);
2215
+ // The leader's commands: from gru (BOND_AGENT <kind>/gru), or with no identity at all.
2216
+ const isLead = !agent || agent.endsWith('/gru');
2217
+ const lead = () => (isLead ? null : { ok: false, message: 'Solo gru, el líder del loop, puede usar este comando.' });
2218
+
2219
+ switch (req.cmd) {
2220
+ case 'loop-status':
2221
+ return { ok: true, message: `loop: ${state ?? 'sin iniciar'} · iteración ${run.loop_iteration ?? 0}${max === null ? ' (sin límite)' : ` de ${max}`}` };
2222
+ case 'ask': {
2223
+ if (!active) return { ok: false, message: 'No hay un loop en marcha: no hay líder al que preguntar.' };
2224
+ const question = text(req.question);
2225
+ if (!question) return { ok: false, message: 'La pregunta está vacía.' };
2226
+ const gru = await this.gruAddress(run);
2227
+ if (!gru) return { ok: false, message: 'gru no está en marcha: no hay a quién preguntar.' };
2228
+ const asks = this.loopAsks.get(run.id) ?? { next: 1, pending: new Map() };
2229
+ this.loopAsks.set(run.id, asks);
2230
+ const n = asks.next++;
2231
+ const who = agent.split('/').pop() || 'agente';
2232
+ asks.pending.set(n, { agent: who, reply });
2233
+ await this.hcClient.sendText(gru, askMessage(n, who, question));
2234
+ this.agentEvent(run, 'loop.ask', { n, agent: who, question });
2235
+ return null;
2236
+ }
2237
+ case 'answer': {
2238
+ const denied = lead();
2239
+ if (denied) return denied;
2240
+ const n = Number(req.n);
2241
+ const p = this.loopAsks.get(run.id)?.pending.get(n);
2242
+ if (!p) return { ok: false, message: `No hay ninguna pregunta #${n} pendiente.` };
2243
+ const answer = text(req.text);
2244
+ if (!answer) return { ok: false, message: 'La respuesta está vacía.' };
2245
+ this.loopAsks.get(run.id)!.pending.delete(n);
2246
+ await p.reply({ ok: true, message: answer });
2247
+ this.agentEvent(run, 'loop.answer', { n, agent: p.agent, answer });
2248
+ return { ok: true, message: `Respuesta #${n} entregada a ${p.agent}.` };
2249
+ }
2250
+ case 'loop-next': {
2251
+ const denied = lead();
2252
+ if (denied) return denied;
2253
+ if (!active) return { ok: false, message: `El loop no está en marcha (${state ?? 'sin iniciar'}).` };
2254
+ const stallLimit = this.settingsRepo.getLoopDefaults().stall_iterations;
2255
+ const round = nextRound({ iteration: run.loop_iteration ?? 0, stalls: run.loop_stalls ?? 0 }, req.progress === true, max, stallLimit);
2256
+ this.runRepo.update(run.id, { loop_iteration: round.iteration, loop_stalls: round.stalls });
2257
+ this.agentEvent(run, 'loop.iteration', { iteration: round.iteration, progress: req.progress === true, summary: text(req.summary) });
2258
+ if (round.action === 'stall') {
2259
+ const why = `${round.stalls} vueltas seguidas sin avance`;
2260
+ await this.stopLoop(run.id, why);
2261
+ this.loopWait(run.id, `Loop parado: ${why}. gru necesita a una persona.`);
2262
+ return { ok: true, message: `Loop parado: ${why}. La persona decide cómo seguir.` };
2263
+ }
2264
+ if (round.action === 'finish') {
2265
+ this.runRepo.update(run.id, { loop_state: 'finishing' });
2266
+ return { ok: true, message: `Límite de ${max} iteraciones alcanzado: escribe la evaluación en el registro del loop y termina con bond-app loop finish --result pass|fail --report <ruta>.` };
2267
+ }
2268
+ return { ok: true, message: `Vuelta ${round.iteration}${max === null ? '' : ` de ${max}`} registrada. Sigue con la siguiente.` };
2269
+ }
2270
+ case 'loop-needs-human': {
2271
+ const denied = lead();
2272
+ if (denied) return denied;
2273
+ if (!active) return { ok: false, message: `El loop no está en marcha (${state ?? 'sin iniciar'}).` };
2274
+ const why = text(req.why) || 'sin motivo';
2275
+ this.runRepo.update(run.id, { loop_state: 'paused' });
2276
+ this.loopWait(run.id, `gru necesita a una persona: ${why}`);
2277
+ this.agentEvent(run, 'loop.needs_human', { why });
2278
+ return { ok: true, message: 'Avisada la persona: espera su respuesta (el loop queda en pausa).' };
2279
+ }
2280
+ case 'loop-finish': {
2281
+ const denied = lead();
2282
+ if (denied) return denied;
2283
+ if (!active) return { ok: false, message: `El loop no está en marcha (${state ?? 'sin iniciar'}).` };
2284
+ const result = req.result === 'pass' ? 'pass' : 'fail';
2285
+ const report = text(req.report);
2286
+ this.runRepo.update(run.id, { loop_state: 'finished' });
2287
+ if (run.container_name) await this.dockerClient.exec(run.container_name, LOOP_ENV_OFF_COMMAND, 'runner').catch(() => undefined);
2288
+ await this.dropLoopAsks(run.id, 'El loop ha terminado.');
2289
+ this.agentEvent(run, 'loop.finished', { result, report, iteration: run.loop_iteration ?? 0 });
2290
+ if (result === 'pass') {
2291
+ // D5: a positive evaluation delivers as usual (verification, push, PR).
2292
+ void this.deliverRun(run.id).catch(() => {});
2293
+ return { ok: true, message: 'Evaluación positiva: bond-app entrega el run (verificación, push y PR).' };
2294
+ }
2295
+ this.loopWait(run.id, `Loop terminado con evaluación negativa: revisa ${report || 'el registro del loop'}.`);
2296
+ return { ok: true, message: 'Evaluación negativa: el run espera a la persona.' };
2297
+ }
2298
+ default:
2299
+ return { ok: false, message: `Comando de loop desconocido: ${String(req.cmd)}` };
2300
+ }
2301
+ }
2302
+
2303
+ /**
2304
+ * The run's `bond-app` command (as root): the shell script (`pr`) and, for LOOP P3, the node
2305
+ * CLI it hands `ask`, `answer` and `loop` to. Installed at start, and again when a loop
2306
+ * starts on a run from before the loop existed.
2307
+ */
2308
+ async installBondAppCli(containerName: string): Promise<void> {
2309
+ await this.dockerClient.injectStdin(containerName, ['sh', '-c', 'cat > /usr/local/bin/bond-app && chmod 0755 /usr/local/bin/bond-app'], BOND_APP_SCRIPT, 'root');
2310
+ await this.dockerClient.injectStdin(
2311
+ containerName,
2312
+ ['sh', '-c', 'mkdir -p /usr/local/lib && cat > /usr/local/lib/bond-app-loop.js && chmod 0755 /usr/local/lib/bond-app-loop.js'],
2313
+ BOND_APP_LOOP_CLI,
2314
+ 'root'
2315
+ );
2316
+ }
2317
+
1745
2318
  /** A `verifying` run with no delivery in progress (e.g. after a restart): resume it. */
1746
2319
  private resumeStrandedDeliveries(): void {
1747
2320
  for (const r of this.runRepo.list({ state: 'verifying' })) {
@@ -2074,7 +2647,7 @@ export class Orchestrator {
2074
2647
  const n = Number(/\/t(\d+)$/.exec(run.hc_terminal || '')?.[1] || '1') + 1;
2075
2648
  const terminal = await this.hcClient.startTerminal(
2076
2649
  run.hc_machine,
2077
- await this.resolveAgentCommand(run.container_name, ticket, message),
2650
+ await this.resolveAgentCommand(run.container_name, this.effectiveTicket(run, ticket), message),
2078
2651
  '/workspace/repo',
2079
2652
  `agent-${n}`
2080
2653
  );
@@ -2110,6 +2683,181 @@ export class Orchestrator {
2110
2683
  return this.runRepo.get(runId)!;
2111
2684
  }
2112
2685
 
2686
+ /** Issue #3: the ticket as this run sees it (a relaunch may have changed agent and model). */
2687
+ effectiveTicket(run: Run, ticket: Ticket): Ticket {
2688
+ if (!run.agent_override || !isValidAgent(run.agent_override)) return ticket;
2689
+ return { ...ticket, agent: run.agent_override, model: run.model_override ?? undefined };
2690
+ }
2691
+
2692
+ /** Issue #3: which run terminal `name` is, its agent kind, cwd and leader. */
2693
+ private async relaunchTarget(runId: string, name: string) {
2694
+ const run = this.runRepo.get(runId);
2695
+ if (!run) throw new NotFoundError(`Run '${runId}' not found`);
2696
+ const ticket = this.ticketRepo.get(run.ticket_id);
2697
+ if (!ticket) throw new NotFoundError(`Ticket '${run.ticket_id}' not found`);
2698
+ if (!['running', 'waiting', 'blocked'].includes(run.state)) {
2699
+ throw new ValidationError(`Only a running, waiting or blocked run can relaunch an agent (this one is '${run.state}')`);
2700
+ }
2701
+ if (this.deliveries.has(runId)) throw new ValidationError('The run is being verified or delivered: wait for it to finish');
2702
+ if (!run.hc_machine || !run.container_name) throw new ValidationError('The run has no container or hc session');
2703
+ if (!/^[a-z][a-z0-9_-]{0,31}$/.test(name)) throw new ValidationError(`Invalid agent name '${name}'`);
2704
+ const terms = (await this.hcClient.getMachineTerminals(run.hc_machine, { all: true })).filter((t) => t.name === name);
2705
+ const term = terms.find((t) => t.state === 'live') ?? terms.at(-1);
2706
+ if (!term?.address) throw new NotFoundError(`No agent '${name}' in this run`);
2707
+ let argv: string[] | undefined;
2708
+ try {
2709
+ argv = (await this.hcClient.getTerminal(term.address)).argv;
2710
+ } catch {
2711
+ argv = undefined;
2712
+ }
2713
+ const eff = this.effectiveTicket(run, ticket);
2714
+ const fromKind = agentKindOfArgv(argv) ?? (name === 'gru' ? eff.agent : 'pi');
2715
+ const cwd = term.cwd || (ticket.mode === 'hub' ? HUB_DIR : '/workspace/repo');
2716
+ const leader = ticket.mode === 'hub' && name !== 'gru' ? 'gru' : null;
2717
+ return { run, ticket, term: { ...term, address: term.address }, fromKind, cwd, leader, container: run.container_name, machine: run.hc_machine };
2718
+ }
2719
+
2720
+ /** Issue #3: the agents a run can relaunch with (in its image and with credentials). */
2721
+ async relaunchOptions(runId: string, name: string): Promise<{
2722
+ name: string;
2723
+ from: string;
2724
+ cwd: string;
2725
+ agents: Array<{ agent: string; available: boolean; reason?: string }>;
2726
+ default_model: string | null;
2727
+ }> {
2728
+ const t = await this.relaunchTarget(runId, name);
2729
+ let installed: string[] | null = null;
2730
+ try {
2731
+ const res = await this.dockerClient.exec(t.container, ['cat', '/opt/runner-agents']);
2732
+ if (res.exitCode === 0) installed = parseRunnerManifest(res.stdout);
2733
+ } catch {
2734
+ installed = null;
2735
+ }
2736
+ const agents = SUPPORTED_AGENTS.map((agent) => {
2737
+ if (installed && !installed.includes(agent)) return { agent, available: false, reason: 'no está en la imagen del run' };
2738
+ if (!this.settingsRepo.getCredential(agent)) return { agent, available: false, reason: 'sin credenciales: configúralo en Ajustes' };
2739
+ return { agent, available: true };
2740
+ });
2741
+ return { name, from: t.fromKind, cwd: t.cwd, agents, default_model: this.settingsRepo?.getSetupSelection?.()?.default_model ?? null };
2742
+ }
2743
+
2744
+ /** The run's secrets that must never reach a handoff. */
2745
+ private runSecrets(ticket: Ticket, runId: string): string[] {
2746
+ const urls = [ticket.repo_url, ticket.hub_url, ...(ticket.repos ?? []).map((r) => r.url)].filter((u): u is string => Boolean(u));
2747
+ const out = new Set<string>();
2748
+ for (const url of urls) {
2749
+ try {
2750
+ const token = this.repoAccessFor(url, runId).token;
2751
+ if (token) out.add(token);
2752
+ } catch {
2753
+ /* no access configured */
2754
+ }
2755
+ }
2756
+ const gh = this.settingsRepo.getGitHubToken();
2757
+ if (gh) out.add(gh);
2758
+ return [...out];
2759
+ }
2760
+
2761
+ /** Issue #3: the handoff for relaunching `name` (preview for the dialog, or the real one). */
2762
+ async relaunchHandoff(runId: string, name: string, toKind: string, reason: string): Promise<string> {
2763
+ const t = await this.relaunchTarget(runId, name);
2764
+ const base = t.ticket.mode === 'hub' ? t.ticket.hub_base || 'main' : t.ticket.base_branch || 'main';
2765
+ let raw = '';
2766
+ try {
2767
+ const res = await this.dockerClient.exec(t.container, ['sh', '-c', HANDOFF_GATHER_SCRIPT, 'bond-handoff', t.cwd, t.fromKind, base], 'runner', 60_000);
2768
+ raw = res.stdout;
2769
+ } catch {
2770
+ raw = '';
2771
+ }
2772
+ const gather = parseGather(raw);
2773
+ const text = buildHandoff({
2774
+ ticketTitle: t.ticket.title,
2775
+ task: t.ticket.story || t.ticket.prompt || '',
2776
+ agentName: name,
2777
+ fromKind: t.fromKind,
2778
+ toKind,
2779
+ reason,
2780
+ cwd: t.cwd,
2781
+ leader: t.leader,
2782
+ gather,
2783
+ decisions: decisionsBy(gather.decisions, name, t.run.started_at ?? t.run.created_at),
2784
+ });
2785
+ return redactSecrets(text, this.runSecrets(t.ticket, runId));
2786
+ }
2787
+
2788
+ /**
2789
+ * Issue #3 «Relanzar con resumen»: replace a run's agent (gru or a team member) with a new
2790
+ * one, of the same kind or another, that starts from a handoff. The stuck agent is never
2791
+ * asked for anything: its session files, git and the run's decisions make the handoff, and it
2792
+ * is ended from outside (`hc kill`), so a Claude at its usage limit or a pi with a full
2793
+ * context can be replaced. The new agent keeps the name, folder and labels.
2794
+ */
2795
+ async relaunchAgent(
2796
+ runId: string,
2797
+ name: string,
2798
+ body: { agent?: unknown; model?: unknown; reason?: unknown; handoff?: unknown }
2799
+ ): Promise<Run> {
2800
+ const toKind = typeof body.agent === 'string' ? body.agent : '';
2801
+ if (!isValidAgent(toKind)) throw new ValidationError(`Unsupported agent '${toKind}'`);
2802
+ const reason = typeof body.reason === 'string' && body.reason.trim() ? body.reason.trim().slice(0, 200) : 'relanzado a mano';
2803
+ const model = toKind === 'pi' && typeof body.model === 'string' && body.model.trim() ? body.model.trim() : null;
2804
+ if (model && !/^[A-Za-z0-9_.:/@+-]{1,200}$/.test(model)) throw new ValidationError(`Invalid model '${model}'`);
2805
+ if (body.handoff !== undefined && (typeof body.handoff !== 'string' || body.handoff.length > 60_000)) {
2806
+ throw new ValidationError("'handoff' must be text up to 60000 characters");
2807
+ }
2808
+ if (this.relaunching.has(runId)) throw new ValidationError('An agent of this run is already being relaunched');
2809
+ this.relaunching.add(runId);
2810
+ try {
2811
+ const options = await this.relaunchOptions(runId, name);
2812
+ const choice = options.agents.find((a) => a.agent === toKind);
2813
+ if (!choice?.available) throw new ValidationError(`Cannot relaunch with ${toKind}: ${choice?.reason ?? 'not available'}`);
2814
+ const t = await this.relaunchTarget(runId, name);
2815
+ // Relaunching pi as pi without a model keeps the ticket's.
2816
+ const runModel = model ?? (toKind === 'pi' && t.ticket.agent === 'pi' ? t.ticket.model ?? null : null);
2817
+ const handoff = typeof body.handoff === 'string'
2818
+ ? redactSecrets(body.handoff, this.runSecrets(t.ticket, runId))
2819
+ : await this.relaunchHandoff(runId, name, toKind, reason);
2820
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
2821
+ const handoffPath = `/home/runner/.bond/handoff/${stamp}-${name}.md`;
2822
+ const wrote = await this.dockerClient.injectStdin(
2823
+ t.container,
2824
+ ['sh', '-c', 'umask 077; mkdir -p "$(dirname "$1")" && cat > "$1"', '--', handoffPath],
2825
+ handoff,
2826
+ 'runner'
2827
+ );
2828
+ if (wrote.exitCode !== 0) throw new Error(`Could not write the handoff: ${wrote.stderr.trim()}`);
2829
+ // The new agent's credentials (and pi's compaction tuning) in this container.
2830
+ await this.injectCredentials(t.container, [toKind]);
2831
+ await this.hcClient.killTerminal(t.term.address);
2832
+
2833
+ const prompt = `Retomas el trabajo de ${name}: lee el traspaso en ${handoffPath} antes de nada y continúa desde ahí.`;
2834
+ const inner = this.bareAgentCommand({ ...t.ticket, agent: toKind, model: runModel ?? undefined }, [prompt]);
2835
+ const hubEnv = t.ticket.mode === 'hub' ? 'export BOND_TEAM_ENGINE=hc BOND_TEAM_NO_TABLE=1 && ' : '';
2836
+ const argv = [
2837
+ 'sh', '-c', `cd "$1" && export BOND_AGENT="$2" && shift 2 && ${hubEnv}exec "$@"`,
2838
+ 'bond-relaunch', t.cwd, `${toKind}/${name}`, ...inner,
2839
+ ];
2840
+ const labels = Object.fromEntries(
2841
+ Object.entries(t.term.labels ?? {}).filter(([k]) => k.startsWith('bond.') || k === 'herdr.space' || k === 'herdr.tab' || k === 'role')
2842
+ );
2843
+ const address = await this.hcClient.startTerminal(t.machine, argv, t.cwd, name, labels);
2844
+
2845
+ this.stuckByRun.delete(runId);
2846
+ if (t.run.resume_at) this.runRepo.update(runId, { resume_at: null, resume_agent: null });
2847
+ const isMain = name === 'gru' || t.run.hc_terminal === t.term.address;
2848
+ if (isMain) this.runRepo.update(runId, { hc_terminal: address, agent_override: toKind, model_override: runModel });
2849
+ this.agentEvent(t.run, 'agent.relaunched', { name, from: t.fromKind, to: toKind, model: runModel, reason, handoff: handoffPath, terminal: address });
2850
+ const fresh = this.runRepo.get(runId)!;
2851
+ if (fresh.state === 'waiting' || fresh.state === 'blocked') {
2852
+ this.setState(runId, fresh.state, 'running', null, { verify_failures: 0 });
2853
+ this.ticketRepo.updateStatus(t.ticket.id, 'running');
2854
+ }
2855
+ return this.runRepo.get(runId)!;
2856
+ } finally {
2857
+ this.relaunching.delete(runId);
2858
+ }
2859
+ }
2860
+
2113
2861
  /**
2114
2862
  * P7: mark a running or waiting run as finished (keeping container and session alive).
2115
2863
  * Called by the user via the card action «Terminado» or POST /api/v1/runs/:id/finish.
@@ -2332,15 +3080,7 @@ export class Orchestrator {
2332
3080
  const machine = run.hc_machine || machineNameForRun(run.id);
2333
3081
  const terminals = await this.hcClient.getMachineTerminals(machine);
2334
3082
 
2335
- const isLeader = (t: { name?: string; cwd?: string; address?: string }) => {
2336
- if (t.name === 'gru' || t.name === 'hub leader' || t.name === 'hub-leader' || t.name === 'leader' || t.name === 'orquestador') {
2337
- return true;
2338
- }
2339
- const cleanCwd = t.cwd?.replace(/\/+$/, '');
2340
- if (cleanCwd === '/workspace/hub') return true;
2341
- if (t.address?.endsWith('/t1')) return true;
2342
- return false;
2343
- };
3083
+ const isLeader = isLeaderTerminal;
2344
3084
 
2345
3085
  const rows: TeamStatusRow[] = [];
2346
3086
  const leader = terminals.find(isLeader);
@@ -2412,15 +3152,7 @@ export class Orchestrator {
2412
3152
  }
2413
3153
 
2414
3154
  if (isHub) {
2415
- const isLeader = (a: { cwd?: string; pane_id?: string; name?: string }) => {
2416
- if (a.name === 'gru' || a.name === 'hub leader' || a.name === 'hub-leader' || a.name === 'leader' || a.name === 'orquestador') {
2417
- return true;
2418
- }
2419
- const cleanCwd = a.cwd?.replace(/\/+$/, '');
2420
- if (cleanCwd === '/workspace/hub') return true;
2421
- if (a.pane_id === 'w1:p1' && (!a.name || a.name === 'pi' || a.name === 'agent' || a.name === 'gru')) return true;
2422
- return false;
2423
- };
3155
+ const isLeader = isLeaderHerdrAgent;
2424
3156
 
2425
3157
  let leaderAgent: any = null;
2426
3158
  if (agentRes && agentRes.exitCode === 0) {
@@ -2521,6 +3253,31 @@ export class Orchestrator {
2521
3253
  * P4: Proxy hc ls for the run's machine, returning live terminals with agent, state,
2522
3254
  * turn, and where (cwd). Returns an empty list if machine is down or unreachable without breaking.
2523
3255
  */
3256
+ /**
3257
+ * Issue #3: the run's named agents whose program has ended and that no live terminal
3258
+ * replaced (NAV-4588's gru), so the Agents panel can offer «Relanzar con resumen» on them.
3259
+ */
3260
+ async getClosedAgents(runId: string): Promise<Array<{ name: string; address: string; exit_code: number | null }>> {
3261
+ const run = this.runRepo.get(runId);
3262
+ if (!run) throw new NotFoundError(`Run '${runId}' not found`);
3263
+ if (!run.hc_machine || !['running', 'waiting', 'blocked'].includes(run.state)) return [];
3264
+ let listed: Awaited<ReturnType<HcClient['listTerminals']>> = [];
3265
+ try {
3266
+ listed = await this.hcClient.listTerminals(run.hc_machine, { all: true });
3267
+ } catch {
3268
+ return [];
3269
+ }
3270
+ const named = (n?: string) => Boolean(n && n !== 'agent' && !/^t\d+$/.test(n));
3271
+ const isLive = (t: { state?: string; exit_code?: number | null }) => (!t.state || t.state === 'live') && (t.exit_code === null || t.exit_code === undefined);
3272
+ const liveNames = new Set(listed.filter(isLive).map((t) => t.name));
3273
+ const out = new Map<string, { name: string; address: string; exit_code: number | null }>();
3274
+ for (const t of listed) {
3275
+ if (isLive(t) || !named(t.name) || liveNames.has(t.name)) continue;
3276
+ out.set(t.name!, { name: t.name!, address: t.address, exit_code: t.exit_code ?? null });
3277
+ }
3278
+ return [...out.values()];
3279
+ }
3280
+
2524
3281
  async getRunTerminals(runId: string): Promise<RunTerminal[]> {
2525
3282
  const run = this.runRepo.get(runId);
2526
3283
  if (!run) throw new ValidationError(`Run '${runId}' not found`);
@@ -3090,7 +3847,42 @@ export class Orchestrator {
3090
3847
  this.setState(runId, 'analyzing', 'blocked', 'hub_incomplete');
3091
3848
  return current();
3092
3849
  }
3093
- // The hub covers the story: the team, one agent per repo, on the ticket's branch.
3850
+ return this.launchHubTeam(runId, analysis);
3851
+ }
3852
+
3853
+ /**
3854
+ * «Seguir sin ellos»: the person reads the hub analysis and starts the team anyway. Only
3855
+ * when every gap is the hub agent's opinion (a repo it thinks is missing, or "not ready");
3856
+ * a fixed check (a repo not mounted, a base missing…) still has to be fixed first.
3857
+ */
3858
+ async proceedHub(runId: string): Promise<Run> {
3859
+ const run = this.runRepo.get(runId);
3860
+ if (!run) throw new NotFoundError(`Run '${runId}' not found`);
3861
+ if (run.state !== 'blocked' || run.failure_reason !== 'hub_incomplete' || !run.hub_analysis) {
3862
+ throw new ValidationError('Solo se sigue adelante con un run bloqueado por un hub incompleto');
3863
+ }
3864
+ if (this.analyses.has(runId) || this.approving.has(runId)) throw new ValidationError('El hub ya se está analizando');
3865
+ const fixed = run.hub_analysis.gaps.filter((g) => !HUB_OPINION_GAPS.has(g.kind));
3866
+ if (fixed.length > 0) {
3867
+ throw new ValidationError(`El hub tiene problemas que hay que arreglar antes: ${fixed.map((g) => g.message).join('; ').slice(0, 300)}`);
3868
+ }
3869
+ this.approving.add(runId);
3870
+ try {
3871
+ if (!this.setState(runId, 'blocked', 'analyzing', null)) {
3872
+ throw new ValidationError('El run cambió de estado mientras se seguía adelante');
3873
+ }
3874
+ this.agentEvent(run, 'hub.proceed', { gaps: run.hub_analysis.gaps.map((g) => g.id) });
3875
+ return await this.launchHubTeam(runId, run.hub_analysis);
3876
+ } finally {
3877
+ this.approving.delete(runId);
3878
+ }
3879
+ }
3880
+
3881
+ /** The hub covers the story (or the person said to go on): the team, one agent per repo, on the ticket's branch. */
3882
+ private async launchHubTeam(runId: string, analysis: HubAnalysis): Promise<Run> {
3883
+ const current = () => this.runRepo.get(runId)!;
3884
+ const stillAnalyzing = () => this.runRepo.get(runId)?.state === 'analyzing';
3885
+ const run = current();
3094
3886
  const ticket = this.ticketRepo.get(run.ticket_id)!;
3095
3887
  const teamAgentsList = analysis.repos.map((r) => teamAgentFor(ticket, r.name));
3096
3888
  const missingLogin = teamAgentsList.find((a) => LOGIN_REQUIRED[a] && !this.settingsRepo.getCredential(a));
@@ -3108,6 +3900,8 @@ export class Orchestrator {
3108
3900
  // P0 (plan bond-app-azure-jira): the agent credentials arrive with the team too; every
3109
3901
  // bash of the run re-reads them through BASH_ENV.
3110
3902
  await this.prepareAgentEnv(run.container_name!);
3903
+ // Issue #4 (P2): the person's Azure session, with the team (M-1), when the ticket asks.
3904
+ await this.injectAzureLogin(run.container_name!, ticket);
3111
3905
  // Git with the person's identity and credentials for gru (the analysis is over, M-1).
3112
3906
  await this.prepareGit(run.container_name!, ticket, {
3113
3907
  repos: [{ dir: HUB_DIR, base: ticket.hub_base || 'main' }, ...analysis.repos.map((r) => ({ dir: `${HUB_DIR}/${r.path}`, base: r.base }))],
@@ -3215,20 +4009,8 @@ export class Orchestrator {
3215
4009
  const machine = run.hc_machine || machineNameForRun(run.id);
3216
4010
  try {
3217
4011
  const terminals = await this.hcClient.getMachineTerminals(machine);
3218
- const isWaiting = (t: { state: string | null; status: string | null; turn?: number }) => {
3219
- if (t.state !== 'live') return false;
3220
- if (t.status === 'blocked' || t.status === 'waiting') return true;
3221
- return (t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0;
3222
- };
3223
- const isLeader = (t: { name?: string; cwd?: string; address?: string }) => {
3224
- if (t.name === 'gru' || t.name === 'hub leader' || t.name === 'hub-leader' || t.name === 'leader' || t.name === 'orquestador') {
3225
- return true;
3226
- }
3227
- const cleanCwd = t.cwd?.replace(/\/+$/, '');
3228
- if (cleanCwd === '/workspace/hub') return true;
3229
- if (t.address?.endsWith('/t1')) return true;
3230
- return false;
3231
- };
4012
+ const isWaiting = (t: { state: string | null; status: string | null; turn?: number }) => t.state === 'live' && isTerminalWaiting(t);
4013
+ const isLeader = isLeaderTerminal;
3232
4014
  const waitingList = terminals.filter(isWaiting);
3233
4015
  if (waitingList.length > 0) {
3234
4016
  const target = waitingList.find(isLeader) || waitingList[0];
@@ -3251,23 +4033,9 @@ export class Orchestrator {
3251
4033
  agent?: string;
3252
4034
  completion_seq?: number;
3253
4035
  }>;
3254
- const waitingList = agents.filter((a) => {
3255
- if (!a.pane_id) return false;
3256
- if (a.agent_status === 'blocked' || a.agent_status === 'waiting') return true;
3257
- if ((a as any).question) return true;
3258
- const seq = typeof a.completion_seq === 'number' ? a.completion_seq : Number(a.completion_seq || 0);
3259
- return (a.agent_status === 'idle' || a.agent_status === 'done') && seq > 0;
3260
- });
4036
+ const waitingList = agents.filter((a) => Boolean(a.pane_id) && isHerdrAgentWaiting(a as Parameters<typeof isHerdrAgentWaiting>[0]));
3261
4037
  if (waitingList.length > 0) {
3262
- const isLeader = (a: { cwd?: string; pane_id?: string; name?: string }) => {
3263
- if (a.name === 'gru' || a.name === 'hub leader' || a.name === 'hub-leader' || a.name === 'leader' || a.name === 'orquestador') {
3264
- return true;
3265
- }
3266
- const cleanCwd = a.cwd?.replace(/\/+$/, '');
3267
- if (cleanCwd === '/workspace/hub') return true;
3268
- if (a.pane_id === 'w1:p1' && (!a.name || a.name === 'pi' || a.name === 'agent' || a.name === 'gru')) return true;
3269
- return false;
3270
- };
4038
+ const isLeader = isLeaderHerdrAgent;
3271
4039
 
3272
4040
  // M-4: deliver only to the single agent that is waiting (leader first if multiple)
3273
4041
  const target = waitingList.find(isLeader) || waitingList[0];
@@ -3502,11 +4270,43 @@ export class Orchestrator {
3502
4270
  let stopped = false;
3503
4271
  let buffer = '';
3504
4272
 
4273
+ const writeResult = async (reqId: string, result: Record<string, unknown>) => {
4274
+ if (stopped) return;
4275
+ const resultPath = `/var/run/bond-app/pr-${reqId}.json`;
4276
+ try {
4277
+ await this.dockerClient.injectStdin(
4278
+ containerName,
4279
+ ['sh', '-c', `cat > "${resultPath}.tmp" && chown runner:runner "${resultPath}.tmp" && chmod 0600 "${resultPath}.tmp" && mv "${resultPath}.tmp" "${resultPath}"`],
4280
+ JSON.stringify(result),
4281
+ 'root'
4282
+ );
4283
+ } catch {
4284
+ // the container may have stopped
4285
+ }
4286
+ };
4287
+
3505
4288
  const handleLine = async (rawLine: string) => {
3506
- const match = /^([a-f0-9]+)\s+([A-Za-z0-9_-]{1,64})$/.exec(rawLine.trim());
4289
+ // `<token> <reqId>` is `bond-app pr`; `<token> <reqId> <base64 json>` a LOOP P3 request.
4290
+ const match = /^([a-f0-9]+)\s+([A-Za-z0-9_-]{1,64})(?:\s+([A-Za-z0-9+/=]{1,8000}))?$/.exec(rawLine.trim());
3507
4291
  if (!match) return;
3508
- const [, providedToken, reqId] = match;
4292
+ const [, providedToken, reqId, payload] = match;
3509
4293
  if (!safeCompare(providedToken, token)) return;
4294
+ if (payload) {
4295
+ let req: Record<string, unknown>;
4296
+ try {
4297
+ req = JSON.parse(Buffer.from(payload, 'base64').toString('utf8'));
4298
+ } catch {
4299
+ return;
4300
+ }
4301
+ let out: Record<string, unknown> | null;
4302
+ try {
4303
+ out = await this.handleLoopRequest(runId, req, (r) => writeResult(reqId, r));
4304
+ } catch (err) {
4305
+ out = { ok: false, message: String((err as Error).message || err) };
4306
+ }
4307
+ if (out) await writeResult(reqId, out);
4308
+ return;
4309
+ }
3510
4310
 
3511
4311
  let result: Record<string, unknown>;
3512
4312
  try {
@@ -3693,6 +4493,14 @@ export class Orchestrator {
3693
4493
  }
3694
4494
  }
3695
4495
 
4496
+ // Issue #4 (P2): «Login de Azure» without a usable session: BLOCKED before launch.
4497
+ const azureProblem = this.azureLoginProblem(ticket);
4498
+ if (azureProblem) {
4499
+ this.setState(run.id, 'queued', 'blocked', azureProblem);
4500
+ this.startingRuns.delete(runId);
4501
+ return this.runRepo.get(run.id)!;
4502
+ }
4503
+
3696
4504
  // P2: an agent that needs its own login (agy, claude) without a stored one: BLOCKED before launch
3697
4505
  if (LOGIN_REQUIRED[ticket.agent] && !this.settingsRepo.getCredential(ticket.agent)) {
3698
4506
  this.setState(run.id, 'queued', 'blocked', LOGIN_REQUIRED[ticket.agent]);
@@ -3755,74 +4563,8 @@ export class Orchestrator {
3755
4563
  // P7 / D6-rev (2026-11-25): per-run docker exec FIFO watcher + 0600 token via stdin + CLI
3756
4564
  await this.ensureRunPrWatcher(run.id, containerInfo.containerName);
3757
4565
 
3758
- const bondAppScript = `#!/bin/sh
3759
- set -e
3760
4566
 
3761
- if [ "$1" != "pr" ]; then
3762
- echo "bond-app: unknown command '$1'. Available: pr" >&2
3763
- exit 1
3764
- fi
3765
-
3766
- if [ "$#" -gt 1 ]; then
3767
- echo "Error: bond-app pr takes no parameters (repo or branch). It delivers only the current run." >&2
3768
- exit 1
3769
- fi
3770
-
3771
- PR_ENV="/var/run/bond-app/pr.env"
3772
- FIFO="/var/run/bond-app/pr.fifo"
3773
- if [ ! -f "$PR_ENV" ]; then
3774
- echo "Error: bond-app PR channel not configured at $PR_ENV" >&2
3775
- exit 1
3776
- fi
3777
-
3778
- . "$PR_ENV"
3779
- if [ -z "$BOND_APP_PR_TOKEN" ]; then
3780
- echo "Error: bond-app PR token missing" >&2
3781
- exit 1
3782
- fi
3783
-
3784
- WAITED_FIFO=0
3785
- while [ ! -p "$FIFO" ] && [ "$WAITED_FIFO" -lt 10 ]; do
3786
- sleep 0.2
3787
- WAITED_FIFO=$((WAITED_FIFO + 1))
3788
- done
3789
- if [ ! -p "$FIFO" ]; then
3790
- echo "Error: bond-app PR FIFO not available at $FIFO" >&2
3791
- exit 1
3792
- fi
3793
-
3794
- REQ_ID="$(date +%s)-$$-$(head -c 6 /dev/urandom | od -An -tx1 | tr -d ' \\n')"
3795
- RES_FILE="/var/run/bond-app/pr-\${REQ_ID}.json"
3796
- rm -f "$RES_FILE"
3797
-
3798
- printf '%s %s\\n' "$BOND_APP_PR_TOKEN" "$REQ_ID" > "$FIFO"
3799
-
3800
- WAITED=0
3801
- while [ "$WAITED" -lt 600 ]; do
3802
- if [ -f "$RES_FILE" ]; then
3803
- RES=$(cat "$RES_FILE")
3804
- rm -f "$RES_FILE"
3805
- echo "$RES"
3806
- if echo "$RES" | grep -q '"ok":true' && echo "$RES" | grep -q '"pr_url"'; then
3807
- exit 0
3808
- else
3809
- exit 1
3810
- fi
3811
- fi
3812
- sleep 1
3813
- WAITED=$((WAITED + 1))
3814
- done
3815
-
3816
- echo "Error: timed out waiting for bond-app PR response after 600s" >&2
3817
- exit 1
3818
- `;
3819
-
3820
- await this.dockerClient.injectStdin(
3821
- containerInfo.containerName,
3822
- ['sh', '-c', 'cat > /usr/local/bin/bond-app && chmod 0755 /usr/local/bin/bond-app'],
3823
- bondAppScript,
3824
- 'root'
3825
- );
4567
+ await this.installBondAppCli(containerInfo.containerName);
3826
4568
 
3827
4569
  // Offline git rewrites for tests (L5), before any clone.
3828
4570
  if (!options.skipClone && options.gitInsteadOf) {
@@ -3909,6 +4651,8 @@ exit 1
3909
4651
  // another one inside the container (bond team panes), and they all belong to the user.
3910
4652
  if (ticket.mode !== 'hub') {
3911
4653
  await this.injectCredentials(containerInfo.containerName, this.allConfiguredAgents());
4654
+ // Issue #4 (P2): the person's Azure session, when the ticket asks («Login de Azure»).
4655
+ await this.injectAzureLogin(containerInfo.containerName, ticket);
3912
4656
  }
3913
4657
  // P0 (plan bond-app-azure-jira): the BASH_ENV script always (the hc core starts with
3914
4658
  // it); the agent credentials too, except in a hub before its team starts (M-1).
@@ -4154,23 +4898,11 @@ exit 1
4154
4898
  if (!isValidAgent(ticket.agent)) {
4155
4899
  throw new ValidationError(`Unsupported agent '${ticket.agent}'`);
4156
4900
  }
4157
- if (ticket.agent === 'agy') {
4158
- // `-i` takes the first message: without one (a ticket with no story nor prompt) agy
4159
- // prints its usage and exits 2, and the run died as container_error right at start.
4160
- return ['agy', '--dangerously-skip-permissions', ...(promptArgv.length ? ['-i', ...promptArgv] : [])];
4161
- }
4162
- if (ticket.agent === 'claude') {
4163
- // Unattended in the run's container, as agy (runs are `runner`, never root).
4164
- return ['claude', '--dangerously-skip-permissions', ...promptArgv];
4165
- }
4166
- if (ticket.agent === 'codex') {
4167
- // Interactive TUI with the ticket as its first message; the container is the sandbox.
4168
- // --dangerously-bypass-hook-trust: bond's agent-state hook would stop it at «Hooks need review».
4169
- return ['codex', '--dangerously-bypass-approvals-and-sandbox', '--dangerously-bypass-hook-trust', ...promptArgv];
4170
- }
4171
- if (ticket.agent === 'copilot') {
4172
- // `-i` starts the interactive session with a first message (as agy, only with one).
4173
- return ['copilot', '--yolo', ...(promptArgv.length ? ['-i', ...promptArgv] : [])];
4901
+ if (ticket.agent !== 'pi') {
4902
+ // Unattended in the run's container (LOOP P0: one table for every launch, agent-flags.ts).
4903
+ // agy and copilot take the first message after `-i`, and only with one: a bare `-i`
4904
+ // makes agy print its usage and exit 2.
4905
+ return [ticket.agent, ...unattendedFlags(ticket.agent).before, ...promptArgs(ticket.agent, promptArgv)];
4174
4906
  }
4175
4907
  const defaultModel = ticket.agent === 'pi' ? this.settingsRepo?.getSetupSelection?.()?.default_model : null;
4176
4908
  const model = ticket.agent === 'pi' ? (ticket.model || defaultModel) : null;
@@ -4360,18 +5092,7 @@ exit 1
4360
5092
  const defaultModel = ticket.agent === 'pi' ? this.settingsRepo?.getSetupSelection?.()?.default_model : null;
4361
5093
  const model = ticket.agent === 'pi' ? (ticket.model || defaultModel) : null;
4362
5094
  if (ticket.agent === 'pi' && model) argv.push('--model', model);
4363
- if (ticket.agent === 'agy') {
4364
- // `-i` only with a first message (see bareAgentCommand): agy exits 2 on a bare `-i`.
4365
- argv.push('--dangerously-skip-permissions');
4366
- if (promptArgv.length) argv.push('-i');
4367
- }
4368
- if (ticket.agent === 'claude') argv.push('--dangerously-skip-permissions');
4369
- if (ticket.agent === 'codex') argv.push('--dangerously-bypass-approvals-and-sandbox', '--dangerously-bypass-hook-trust');
4370
- if (ticket.agent === 'copilot') {
4371
- argv.push('--yolo');
4372
- if (promptArgv.length) argv.push('-i');
4373
- }
4374
- argv.push(...promptArgv);
5095
+ argv.push(...unattendedFlags(ticket.agent).before, ...promptArgs(ticket.agent, promptArgv));
4375
5096
  return argv;
4376
5097
  }
4377
5098
 
@@ -4916,3 +5637,88 @@ exit 1
4916
5637
  return this.runRepo.get(runId)!;
4917
5638
  }
4918
5639
  }
5640
+
5641
+ /**
5642
+ * Issue #3: the agent kind a terminal runs, from its argv (`bond tui --agent X`, a bare
5643
+ * `claude …`, or a `sh -c '… exec pi …'` launch), or null.
5644
+ */
5645
+ export function agentKindOfArgv(argv: string[] | undefined): SupportedAgent | null {
5646
+ if (!argv?.length) return null;
5647
+ const joined = argv.join(' ');
5648
+ const flag = /--agent\s+([a-z]+)/.exec(joined)?.[1];
5649
+ if (flag && isValidAgent(flag)) return flag;
5650
+ let best: { kind: SupportedAgent; at: number } | null = null;
5651
+ for (const kind of SUPPORTED_AGENTS) {
5652
+ const m = new RegExp(`(^|[\\s/"'])${kind}(?=$|[\\s"'])`).exec(joined);
5653
+ if (m && (!best || m.index < best.at)) best = { kind, at: m.index };
5654
+ }
5655
+ return best?.kind ?? null;
5656
+ }
5657
+
5658
+ /** The run's `bond-app` command (P7 `pr`; LOOP P3 `ask`, `answer`, `loop` via the node CLI). */
5659
+ const BOND_APP_SCRIPT = `#!/bin/sh
5660
+ set -e
5661
+
5662
+ case "$1" in
5663
+ pr) ;;
5664
+ # LOOP P3 (issue #2): the loop's commands go to the node CLI next to this script.
5665
+ ask|answer|loop) exec node /usr/local/lib/bond-app-loop.js "$@" ;;
5666
+ *)
5667
+ echo "bond-app: unknown command '$1'. Available: pr, ask, answer, loop" >&2
5668
+ exit 1
5669
+ ;;
5670
+ esac
5671
+
5672
+ if [ "$#" -gt 1 ]; then
5673
+ echo "Error: bond-app pr takes no parameters (repo or branch). It delivers only the current run." >&2
5674
+ exit 1
5675
+ fi
5676
+
5677
+ PR_ENV="/var/run/bond-app/pr.env"
5678
+ FIFO="/var/run/bond-app/pr.fifo"
5679
+ if [ ! -f "$PR_ENV" ]; then
5680
+ echo "Error: bond-app PR channel not configured at $PR_ENV" >&2
5681
+ exit 1
5682
+ fi
5683
+
5684
+ . "$PR_ENV"
5685
+ if [ -z "$BOND_APP_PR_TOKEN" ]; then
5686
+ echo "Error: bond-app PR token missing" >&2
5687
+ exit 1
5688
+ fi
5689
+
5690
+ WAITED_FIFO=0
5691
+ while [ ! -p "$FIFO" ] && [ "$WAITED_FIFO" -lt 10 ]; do
5692
+ sleep 0.2
5693
+ WAITED_FIFO=$((WAITED_FIFO + 1))
5694
+ done
5695
+ if [ ! -p "$FIFO" ]; then
5696
+ echo "Error: bond-app PR FIFO not available at $FIFO" >&2
5697
+ exit 1
5698
+ fi
5699
+
5700
+ REQ_ID="$(date +%s)-$$-$(head -c 6 /dev/urandom | od -An -tx1 | tr -d ' \\n')"
5701
+ RES_FILE="/var/run/bond-app/pr-\${REQ_ID}.json"
5702
+ rm -f "$RES_FILE"
5703
+
5704
+ printf '%s %s\\n' "$BOND_APP_PR_TOKEN" "$REQ_ID" > "$FIFO"
5705
+
5706
+ WAITED=0
5707
+ while [ "$WAITED" -lt 600 ]; do
5708
+ if [ -f "$RES_FILE" ]; then
5709
+ RES=$(cat "$RES_FILE")
5710
+ rm -f "$RES_FILE"
5711
+ echo "$RES"
5712
+ if echo "$RES" | grep -q '"ok":true' && echo "$RES" | grep -q '"pr_url"'; then
5713
+ exit 0
5714
+ else
5715
+ exit 1
5716
+ fi
5717
+ fi
5718
+ sleep 1
5719
+ WAITED=$((WAITED + 1))
5720
+ done
5721
+
5722
+ echo "Error: timed out waiting for bond-app PR response after 600s" >&2
5723
+ exit 1
5724
+ `;