@jmanuelcorral/bond-app 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/app/mods/bond-agents/main.js +446 -28
- package/app/mods/bond-agents/model.js +236 -0
- package/app/mods/bond-board/main.js +170 -16
- package/app/mods/bond-board/model.js +63 -2
- package/app/mods/bond-settings/main.js +128 -2
- package/package.json +1 -1
- package/runner/versions.env +1 -1
- package/src/config.ts +3 -0
- package/src/core/agent-flags.ts +38 -0
- package/src/core/agent-waiting.ts +38 -0
- package/src/core/agy-login.ts +56 -4
- package/src/core/doctor.ts +58 -12
- package/src/core/handoff.ts +161 -0
- package/src/core/hub-session.ts +14 -2
- package/src/core/hub.ts +3 -3
- package/src/core/loop.ts +241 -0
- package/src/core/orchestrator.ts +961 -181
- package/src/core/pi-compaction.ts +98 -0
- package/src/core/stuck.ts +192 -0
- package/src/db/database.ts +31 -1
- package/src/db/run-repo.ts +38 -3
- package/src/db/settings-repo.ts +138 -0
- package/src/db/ticket-repo.ts +74 -5
- package/src/runner/hc-client.ts +27 -4
- package/src/server/app.ts +175 -3
- package/src/types.ts +74 -0
package/src/core/orchestrator.ts
CHANGED
|
@@ -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, 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,8 @@ 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 { AgyLoginManager, AZURE_LOGIN_SPEC, CLAUDE_LOGIN_SPEC, CODEX_LOGIN_SPEC, COPILOT_LOGIN_SPEC, type AgyLoginDriver } from './agy-login.ts';
|
|
44
|
+
import { buildSetupState, parseRunnerManifest } from './setup.ts';
|
|
39
45
|
import { HUB_DIR, NAME_RE, agentGaps, analysisPrompt, buildAnalysis, fixedGaps, parseAgentAnswer, parseHubToml, repoNameFromUrl, teamAgentFor, teamAgents, type HubToml } from './hub.ts';
|
|
40
46
|
import {
|
|
41
47
|
validateGitHubUrl,
|
|
@@ -45,11 +51,14 @@ import {
|
|
|
45
51
|
parseJiraIssueUrl,
|
|
46
52
|
normalizeJiraSite,
|
|
47
53
|
isValidAgent,
|
|
54
|
+
SUPPORTED_AGENTS,
|
|
55
|
+
type SupportedAgent,
|
|
48
56
|
type HubAnalysis,
|
|
49
57
|
type HubFix,
|
|
50
58
|
type RepoDelivery,
|
|
51
59
|
type Run,
|
|
52
60
|
type Ticket,
|
|
61
|
+
type LoopConfig,
|
|
53
62
|
type CreateTicketInput,
|
|
54
63
|
type RunState,
|
|
55
64
|
type FailureReason,
|
|
@@ -60,6 +69,24 @@ import {
|
|
|
60
69
|
} from '../types.ts';
|
|
61
70
|
import type { AppConfig } from '../config.ts';
|
|
62
71
|
|
|
72
|
+
/** Gaps that are the hub agent's opinion, which a person may overrule («Seguir sin ellos»). */
|
|
73
|
+
const HUB_OPINION_GAPS = new Set(['missing_repo', 'agent_not_ready']);
|
|
74
|
+
|
|
75
|
+
/** az's config in a run: no prompts about subscriptions, no telemetry. */
|
|
76
|
+
const AZURE_RUN_CONFIG = '[core]\nlogin_experience_v2 = off\ncollect_telemetry = false\n';
|
|
77
|
+
|
|
78
|
+
/** azureProfile.json with `subscriptionId` as the default subscription (the others stay). */
|
|
79
|
+
export function azureProfileWithDefault(profileText: string, subscriptionId: string): string {
|
|
80
|
+
const doc = JSON.parse(profileText.replace(/^\uFEFF/, '')) as { subscriptions?: Array<Record<string, unknown>> };
|
|
81
|
+
for (const sub of doc.subscriptions ?? []) sub.isDefault = sub.id === subscriptionId;
|
|
82
|
+
return JSON.stringify(doc);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The waits the loop puts the run in (loopWait): only the person ends them. */
|
|
86
|
+
export function isLoopWaitReason(reason: string | null | undefined): boolean {
|
|
87
|
+
return /^(gru necesita a una persona|Loop parado|Loop terminado con evaluación negativa)/.test(String(reason ?? ''));
|
|
88
|
+
}
|
|
89
|
+
|
|
63
90
|
export class NotFoundError extends Error {
|
|
64
91
|
constructor(message: string) {
|
|
65
92
|
super(message);
|
|
@@ -244,6 +271,10 @@ export class Orchestrator {
|
|
|
244
271
|
public azure: AzureDevOpsClient = new AzureDevOpsClient();
|
|
245
272
|
|
|
246
273
|
private reconcileTimer: NodeJS.Timeout | null = null;
|
|
274
|
+
/** Issue #3 P3: the stuck-agent sweep, and what it found per run (its waiting reason). */
|
|
275
|
+
private stuckTimer: NodeJS.Timeout | null = null;
|
|
276
|
+
private stuckByRun = new Map<string, { name: string; kind: StuckKind; reason: string; resets?: string | null }>();
|
|
277
|
+
private checkingStuck = false;
|
|
247
278
|
private inFlightTerminations = new Set<string>();
|
|
248
279
|
private startingRuns = new Set<string>();
|
|
249
280
|
private isReconciling = false;
|
|
@@ -279,6 +310,8 @@ export class Orchestrator {
|
|
|
279
310
|
private rebuildImpl: (image: string, options?: RunnerBuildOptions) => Promise<void>;
|
|
280
311
|
// P4: deliveries in progress (verify, commit, push, PR), one per run.
|
|
281
312
|
private deliveries = new Map<string, Promise<Run>>();
|
|
313
|
+
/** Issue #3: runs with an agent relaunch in progress (one at a time per run). */
|
|
314
|
+
private relaunching = new Set<string>();
|
|
282
315
|
// P4: a token given explicitly at start (not stored); delivery falls back to the stored one.
|
|
283
316
|
private runTokens = new Map<string, string>();
|
|
284
317
|
// P5: hub analyses in progress (fixed checks, hub agent, then the team), one per run.
|
|
@@ -297,6 +330,7 @@ export class Orchestrator {
|
|
|
297
330
|
public claudeLoginManager: AgyLoginManager;
|
|
298
331
|
public codexLoginManager: AgyLoginManager;
|
|
299
332
|
public copilotLoginManager: AgyLoginManager;
|
|
333
|
+
public azureLoginManager: AgyLoginManager;
|
|
300
334
|
public jira: JiraClient;
|
|
301
335
|
|
|
302
336
|
constructor(
|
|
@@ -357,6 +391,15 @@ export class Orchestrator {
|
|
|
357
391
|
maxDurationMs: 15 * 60 * 1000,
|
|
358
392
|
onToken: (content) => this.settingsRepo.setCredential('copilot', content, 'copilot-login'),
|
|
359
393
|
});
|
|
394
|
+
// Issue #4 (P1): the person's Azure session (device code), kept in the credential store (D3).
|
|
395
|
+
this.azureLoginManager = new AgyLoginManager({
|
|
396
|
+
runnerImage: config.runnerImage,
|
|
397
|
+
dataDir: config.dataDir,
|
|
398
|
+
driver: agyLoginDriver,
|
|
399
|
+
spec: AZURE_LOGIN_SPEC,
|
|
400
|
+
maxDurationMs: 15 * 60 * 1000,
|
|
401
|
+
onToken: (content) => this.settingsRepo.setAzureLogin(JSON.parse(content)),
|
|
402
|
+
});
|
|
360
403
|
if (this.config.dataDir) {
|
|
361
404
|
this.settingsRepo.setDataDir(this.config.dataDir);
|
|
362
405
|
}
|
|
@@ -373,6 +416,11 @@ export class Orchestrator {
|
|
|
373
416
|
});
|
|
374
417
|
}, this.config.reconcileIntervalMs);
|
|
375
418
|
}
|
|
419
|
+
if (this.config.stuckCheckIntervalMs > 0) {
|
|
420
|
+
this.stuckTimer = setInterval(() => {
|
|
421
|
+
this.checkStuckAgents().catch(() => {});
|
|
422
|
+
}, this.config.stuckCheckIntervalMs);
|
|
423
|
+
}
|
|
376
424
|
}
|
|
377
425
|
|
|
378
426
|
async stop(): Promise<void> {
|
|
@@ -381,10 +429,15 @@ export class Orchestrator {
|
|
|
381
429
|
clearInterval(this.reconcileTimer);
|
|
382
430
|
this.reconcileTimer = null;
|
|
383
431
|
}
|
|
432
|
+
if (this.stuckTimer) {
|
|
433
|
+
clearInterval(this.stuckTimer);
|
|
434
|
+
this.stuckTimer = null;
|
|
435
|
+
}
|
|
384
436
|
await this.agyLoginManager.cancel();
|
|
385
437
|
await this.claudeLoginManager.cancel();
|
|
386
438
|
await this.codexLoginManager.cancel();
|
|
387
439
|
await this.copilotLoginManager.cancel();
|
|
440
|
+
await this.azureLoginManager.cancel();
|
|
388
441
|
for (const [, w] of this.runPrWatchers.entries()) {
|
|
389
442
|
try { w.stop(); } catch {}
|
|
390
443
|
}
|
|
@@ -974,6 +1027,48 @@ export class Orchestrator {
|
|
|
974
1027
|
}
|
|
975
1028
|
}
|
|
976
1029
|
|
|
1030
|
+
/**
|
|
1031
|
+
* Issue #4 (P2): why a ticket with «Login de Azure» cannot start (no session, expired, a
|
|
1032
|
+
* subscription the session does not have), or null when it can (or does not ask).
|
|
1033
|
+
*/
|
|
1034
|
+
azureLoginProblem(ticket: Ticket): string | null {
|
|
1035
|
+
if (!ticket.azure_login) return null;
|
|
1036
|
+
const doc = this.settingsRepo.getAzureLogin();
|
|
1037
|
+
if (!doc) return 'el ticket pide «Login de Azure» y no hay sesión: inicia sesión en Ajustes → Azure';
|
|
1038
|
+
const summary = this.settingsRepo.getAzureLoginSummary();
|
|
1039
|
+
if (summary.expired) return 'la sesión de Azure ha caducado: vuelve a iniciar sesión en Ajustes → Azure';
|
|
1040
|
+
const sub = ticket.azure_subscription || doc.subscription_id;
|
|
1041
|
+
if (!sub || !azureSubscriptions(doc.profile).some((x) => x.id === sub)) {
|
|
1042
|
+
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`;
|
|
1043
|
+
}
|
|
1044
|
+
return null;
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
/**
|
|
1048
|
+
* Issue #4 (P2): the person's Azure session in the run, when the ticket asks: az's two files
|
|
1049
|
+
* in /home/runner/.azure (0600, as runner, by stdin; never in -e, arguments or the image),
|
|
1050
|
+
* with the ticket's subscription (or the default) as the default one. D5: what az renews in
|
|
1051
|
+
* the run stays there and goes with the container.
|
|
1052
|
+
*/
|
|
1053
|
+
async injectAzureLogin(containerName: string, ticket: Ticket): Promise<boolean> {
|
|
1054
|
+
if (!ticket.azure_login) return false;
|
|
1055
|
+
const problem = this.azureLoginProblem(ticket);
|
|
1056
|
+
if (problem) throw new Error(problem);
|
|
1057
|
+
const doc = this.settingsRepo.getAzureLogin()!;
|
|
1058
|
+
const sub = (ticket.azure_subscription || doc.subscription_id)!;
|
|
1059
|
+
const write = (file: string, content: string) => this.dockerClient.injectStdin(containerName, ['sh', '-c',
|
|
1060
|
+
`set -eu; umask 077; mkdir -p /home/runner/.azure; cat > /home/runner/.azure/${file}; chmod 600 /home/runner/.azure/${file}`], content, 'runner');
|
|
1061
|
+
for (const [file, content] of [
|
|
1062
|
+
['msal_token_cache.json', doc.msal],
|
|
1063
|
+
['azureProfile.json', azureProfileWithDefault(doc.profile, sub)],
|
|
1064
|
+
['config', AZURE_RUN_CONFIG],
|
|
1065
|
+
] as const) {
|
|
1066
|
+
const res = await write(file, content);
|
|
1067
|
+
if (res.exitCode !== 0) throw new Error(`No se pudo dejar la sesión de Azure en el run (${file}): ${res.stderr.trim()}`);
|
|
1068
|
+
}
|
|
1069
|
+
return true;
|
|
1070
|
+
}
|
|
1071
|
+
|
|
977
1072
|
async prepareAgentEnv(containerName: string, home = '/home/runner', withSources = true): Promise<string[]> {
|
|
978
1073
|
const write = async (dest: string, content: string) => {
|
|
979
1074
|
const res = await this.dockerClient.injectStdin(
|
|
@@ -1013,6 +1108,17 @@ export class Orchestrator {
|
|
|
1013
1108
|
}
|
|
1014
1109
|
written.push(destPath);
|
|
1015
1110
|
}
|
|
1111
|
+
// bond#92: tune pi's compaction for the small-window models of that models.json, in the
|
|
1112
|
+
// container's settings.json (entries already there win). Failing here never blocks the run.
|
|
1113
|
+
if (wanted.has('pi')) {
|
|
1114
|
+
const models = this.settingsRepo.getCredential('pi')?.config_json;
|
|
1115
|
+
const overrides = models ? piCompactionOverrides(models) : {};
|
|
1116
|
+
if (Object.keys(overrides).length) {
|
|
1117
|
+
const res = await this.dockerClient.injectStdin(containerName, piCompactionCommand(`${home}/.pi/agent/settings.json`), JSON.stringify(overrides), 'runner');
|
|
1118
|
+
if (res.exitCode === 0) written.push(`${home}/.pi/agent/settings.json`);
|
|
1119
|
+
else console.warn(`[bond-app] pi compaction tuning skipped (exit ${res.exitCode}): ${res.stderr.trim()}`);
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1016
1122
|
// W-P4: prompt-suggestions config for supi, written next to pi's models.json when a
|
|
1017
1123
|
// suggestions model is stored (null = «sin sugerencias» writes nothing). The supi
|
|
1018
1124
|
// package itself comes with the runner image (image plan P2); until then the file is
|
|
@@ -1595,21 +1701,8 @@ export class Orchestrator {
|
|
|
1595
1701
|
if (anyWorking) {
|
|
1596
1702
|
isBlocked = false;
|
|
1597
1703
|
} else if (agents.length > 0) {
|
|
1598
|
-
const isWaiting =
|
|
1599
|
-
|
|
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
|
-
};
|
|
1704
|
+
const isWaiting = isHerdrAgentWaiting;
|
|
1705
|
+
const isLeader = isLeaderHerdrAgent;
|
|
1613
1706
|
const waiting = agents.filter(isWaiting);
|
|
1614
1707
|
const leader = agents.find(isLeader);
|
|
1615
1708
|
const leaderWaiting = Boolean(leader && isWaiting(leader));
|
|
@@ -1643,19 +1736,8 @@ export class Orchestrator {
|
|
|
1643
1736
|
if (anyWorking) {
|
|
1644
1737
|
isBlocked = false;
|
|
1645
1738
|
} else if (live.length > 0) {
|
|
1646
|
-
const isWaiting =
|
|
1647
|
-
|
|
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
|
-
};
|
|
1739
|
+
const isWaiting = isTerminalWaiting;
|
|
1740
|
+
const isLeader = isLeaderTerminal;
|
|
1659
1741
|
const waiting = live.filter(isWaiting);
|
|
1660
1742
|
const leader = live.find(isLeader);
|
|
1661
1743
|
const leaderWaiting = Boolean(leader && isWaiting(leader));
|
|
@@ -1693,7 +1775,7 @@ export class Orchestrator {
|
|
|
1693
1775
|
} catch {}
|
|
1694
1776
|
}
|
|
1695
1777
|
if (!notSignedInBlocked) {
|
|
1696
|
-
const isWaiting =
|
|
1778
|
+
const isWaiting = isTerminalWaiting(t);
|
|
1697
1779
|
if (isWaiting) {
|
|
1698
1780
|
isBlocked = true;
|
|
1699
1781
|
waitingAgentName = ticket.agent || 'agente';
|
|
@@ -1718,8 +1800,15 @@ export class Orchestrator {
|
|
|
1718
1800
|
}
|
|
1719
1801
|
}
|
|
1720
1802
|
|
|
1803
|
+
// The loop is waiting for the person (gru's needs-human, a stall, a negative evaluation):
|
|
1804
|
+
// that wait is the person's to end («Reanudar», «Iniciar loop»), not the agents' screens.
|
|
1805
|
+
if (latest.state === 'waiting' && isLoopWaitReason(latest.failure_reason)) continue;
|
|
1806
|
+
|
|
1721
1807
|
if (isBlocked) {
|
|
1722
|
-
|
|
1808
|
+
// A stuck agent (issue #3 P3) has a more precise reason than «waiting for an answer».
|
|
1809
|
+
const reason = latest.resume_at && latest.failure_reason
|
|
1810
|
+
? latest.failure_reason
|
|
1811
|
+
: this.stuckByRun.get(r.id)?.reason ?? `Esperando respuesta: ${waitingAgentName}`;
|
|
1723
1812
|
if (latest.state === 'running') {
|
|
1724
1813
|
if (this.setState(r.id, 'running', 'waiting', reason)) {
|
|
1725
1814
|
this.ticketRepo.updateStatus(r.ticket_id, 'waiting');
|
|
@@ -1731,6 +1820,7 @@ export class Orchestrator {
|
|
|
1731
1820
|
}
|
|
1732
1821
|
} else if (latest.state === 'waiting') {
|
|
1733
1822
|
// Every agent is working again (answered or resumed)
|
|
1823
|
+
this.stuckByRun.delete(r.id);
|
|
1734
1824
|
if (this.setState(r.id, 'waiting', 'running', null)) {
|
|
1735
1825
|
this.ticketRepo.updateStatus(r.ticket_id, 'running');
|
|
1736
1826
|
this.agentEvent(latest, 'agent.resumed', {});
|
|
@@ -1742,6 +1832,463 @@ export class Orchestrator {
|
|
|
1742
1832
|
return transitioned;
|
|
1743
1833
|
}
|
|
1744
1834
|
|
|
1835
|
+
/**
|
|
1836
|
+
* Issue #3 P3: find the run agents that are stuck (a full context with compaction no longer
|
|
1837
|
+
* able to help, or an exhausted budget), never asking them anything: the screen and, for pi,
|
|
1838
|
+
* the tail of its session file. A finding becomes the run's waiting reason
|
|
1839
|
+
* («<name>: contexto lleno…»), on which the Agents panel offers «Relanzar con resumen». Only
|
|
1840
|
+
* agents that are not working are looked at. Returns the runs whose reason it set.
|
|
1841
|
+
*/
|
|
1842
|
+
async checkStuckAgents(): Promise<string[]> {
|
|
1843
|
+
if (this.checkingStuck) return [];
|
|
1844
|
+
this.checkingStuck = true;
|
|
1845
|
+
const changed: string[] = [];
|
|
1846
|
+
try {
|
|
1847
|
+
changed.push(...(await this.runScheduledResumes()));
|
|
1848
|
+
for (const r of this.runRepo.listActive().filter((x) => x.state === 'running' || x.state === 'waiting')) {
|
|
1849
|
+
if (!r.hc_machine || !r.container_name) continue;
|
|
1850
|
+
// A resume is scheduled (P4): its reason says when; nothing to look at until then.
|
|
1851
|
+
if (r.resume_at) continue;
|
|
1852
|
+
if (this.startingRuns.has(r.id) || this.inFlightTerminations.has(r.id) || this.deliveries.has(r.id) || this.relaunching.has(r.id)) continue;
|
|
1853
|
+
let found: { name: string; kind: StuckKind; reason: string; resets?: string | null } | null = null;
|
|
1854
|
+
try {
|
|
1855
|
+
const terms = (await this.hcClient.getMachineTerminals(r.hc_machine)).filter(
|
|
1856
|
+
(t) => t.state === 'live' && t.status !== 'working' && Boolean(t.address) && /^[a-z][a-z0-9_-]{0,31}$/.test(String(t.name ?? ''))
|
|
1857
|
+
);
|
|
1858
|
+
for (const t of terms) {
|
|
1859
|
+
const name = String(t.name);
|
|
1860
|
+
let screen = '';
|
|
1861
|
+
try {
|
|
1862
|
+
screen = await this.hcClient.readTerminal(t.address!, 60);
|
|
1863
|
+
} catch {
|
|
1864
|
+
screen = '';
|
|
1865
|
+
}
|
|
1866
|
+
let finding = budgetExhaustedIn(screen);
|
|
1867
|
+
if (!finding) {
|
|
1868
|
+
let argv: string[] | undefined;
|
|
1869
|
+
try {
|
|
1870
|
+
argv = (await this.hcClient.getTerminal(t.address!)).argv;
|
|
1871
|
+
} catch {
|
|
1872
|
+
argv = undefined;
|
|
1873
|
+
}
|
|
1874
|
+
if (agentKindOfArgv(argv) === 'pi') {
|
|
1875
|
+
const res = await this.dockerClient.exec(r.container_name, ['node', '-e', PI_SESSION_TAIL_SCRIPT, t.cwd || '/workspace/repo'], 'runner', 20_000);
|
|
1876
|
+
let tail: Partial<PiSessionTail> | null = null;
|
|
1877
|
+
try {
|
|
1878
|
+
tail = res.exitCode === 0 ? JSON.parse(res.stdout || '{}') : null;
|
|
1879
|
+
} catch {
|
|
1880
|
+
tail = null;
|
|
1881
|
+
}
|
|
1882
|
+
finding = piContextStuck(tail);
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
if (finding) {
|
|
1886
|
+
found = { name, kind: finding.kind, reason: stuckReason(name, finding), resets: finding.resets ?? null };
|
|
1887
|
+
break;
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
} catch {
|
|
1891
|
+
continue;
|
|
1892
|
+
}
|
|
1893
|
+
const previous = this.stuckByRun.get(r.id);
|
|
1894
|
+
if (!found) {
|
|
1895
|
+
this.stuckByRun.delete(r.id);
|
|
1896
|
+
continue;
|
|
1897
|
+
}
|
|
1898
|
+
this.stuckByRun.set(r.id, found);
|
|
1899
|
+
const latest = this.runRepo.get(r.id);
|
|
1900
|
+
if (!latest) continue;
|
|
1901
|
+
if (latest.state === 'running') {
|
|
1902
|
+
if (this.setState(r.id, 'running', 'waiting', found.reason)) {
|
|
1903
|
+
this.ticketRepo.updateStatus(r.ticket_id, 'waiting');
|
|
1904
|
+
changed.push(r.id);
|
|
1905
|
+
}
|
|
1906
|
+
} else if (latest.state === 'waiting' && latest.failure_reason !== found.reason) {
|
|
1907
|
+
this.runRepo.update(r.id, { failure_reason: found.reason });
|
|
1908
|
+
changed.push(r.id);
|
|
1909
|
+
}
|
|
1910
|
+
if (previous?.reason !== found.reason) this.agentEvent(latest, 'agent.stuck', { agent: found.name, kind: found.kind, reason: found.reason });
|
|
1911
|
+
}
|
|
1912
|
+
} finally {
|
|
1913
|
+
this.checkingStuck = false;
|
|
1914
|
+
}
|
|
1915
|
+
return changed;
|
|
1916
|
+
}
|
|
1917
|
+
|
|
1918
|
+
/**
|
|
1919
|
+
* Issue #3 P4 «Reanudar al restablecerse»: keep the same agent and tell it to go on when its
|
|
1920
|
+
* budget comes back. The time comes from its screen («resets 3pm», «try again in 2 hours»)
|
|
1921
|
+
* or from `at` (ISO), within the next 7 days. Survives a restart (on the run).
|
|
1922
|
+
*/
|
|
1923
|
+
async scheduleResume(runId: string, name: string, at?: unknown): Promise<Run> {
|
|
1924
|
+
const run = this.runRepo.get(runId);
|
|
1925
|
+
if (!run) throw new NotFoundError(`Run '${runId}' not found`);
|
|
1926
|
+
if (run.state !== 'waiting') throw new ValidationError(`Only a waiting run can schedule a resume (this one is '${run.state}')`);
|
|
1927
|
+
if (!/^[a-z][a-z0-9_-]{0,31}$/.test(name)) throw new ValidationError(`Invalid agent name '${name}'`);
|
|
1928
|
+
let when: Date | null = null;
|
|
1929
|
+
if (typeof at === 'string' && at.trim()) {
|
|
1930
|
+
when = new Date(at);
|
|
1931
|
+
if (Number.isNaN(when.getTime())) throw new ValidationError(`Invalid time '${at}'`);
|
|
1932
|
+
} else {
|
|
1933
|
+
const stuck = this.stuckByRun.get(runId);
|
|
1934
|
+
if (!stuck || stuck.name !== name || stuck.kind !== 'budget') {
|
|
1935
|
+
throw new ValidationError(`${name} is not waiting for its budget: give the time ('at')`);
|
|
1936
|
+
}
|
|
1937
|
+
when = resumeTimeFrom(stuck.resets);
|
|
1938
|
+
if (!when) throw new ValidationError(`Cannot tell when the budget of ${name} comes back: give the time ('at')`);
|
|
1939
|
+
}
|
|
1940
|
+
const now = Date.now();
|
|
1941
|
+
if (when.getTime() <= now || when.getTime() > now + 7 * 24 * 3_600_000) {
|
|
1942
|
+
throw new ValidationError('The resume time must be within the next 7 days');
|
|
1943
|
+
}
|
|
1944
|
+
const hhmm = when.toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' });
|
|
1945
|
+
const base = this.stuckByRun.get(runId)?.reason ?? `${name}: presupuesto agotado.`;
|
|
1946
|
+
const reason = `${base.replace(/ Relánzalo[^]*$/, '')} Se reanudará a las ${hhmm}.`;
|
|
1947
|
+
this.runRepo.update(runId, { resume_at: when.toISOString(), resume_agent: name, failure_reason: reason });
|
|
1948
|
+
this.agentEvent(run, 'agent.resume_scheduled', { agent: name, at: when.toISOString() });
|
|
1949
|
+
return this.runRepo.get(runId)!;
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1952
|
+
/** P4: the scheduled resumes that are due: tell the agent to go on, the run runs again. */
|
|
1953
|
+
async runScheduledResumes(now: Date = new Date()): Promise<string[]> {
|
|
1954
|
+
const resumed: string[] = [];
|
|
1955
|
+
for (const r of this.runRepo.listActive()) {
|
|
1956
|
+
if (!r.resume_at || new Date(r.resume_at).getTime() > now.getTime()) continue;
|
|
1957
|
+
const name = r.resume_agent || 'gru';
|
|
1958
|
+
this.runRepo.update(r.id, { resume_at: null, resume_agent: null });
|
|
1959
|
+
this.stuckByRun.delete(r.id);
|
|
1960
|
+
let address: string | undefined;
|
|
1961
|
+
try {
|
|
1962
|
+
address = (await this.hcClient.getMachineTerminals(r.hc_machine!)).find((t) => t.name === name && t.state === 'live')?.address;
|
|
1963
|
+
} catch {
|
|
1964
|
+
address = undefined;
|
|
1965
|
+
}
|
|
1966
|
+
if (!address) {
|
|
1967
|
+
this.runRepo.update(r.id, { failure_reason: `${name}: no se pudo reanudar, el agente ya no está. Relánzalo con resumen.` });
|
|
1968
|
+
continue;
|
|
1969
|
+
}
|
|
1970
|
+
try {
|
|
1971
|
+
await this.hcClient.sendText(address, 'Tu presupuesto se ha restablecido: continúa con la tarea donde la dejaste.');
|
|
1972
|
+
} catch {
|
|
1973
|
+
this.runRepo.update(r.id, { failure_reason: `${name}: no se pudo reanudar (no acepta mensajes). Relánzalo con resumen.` });
|
|
1974
|
+
continue;
|
|
1975
|
+
}
|
|
1976
|
+
const latest = this.runRepo.get(r.id)!;
|
|
1977
|
+
this.agentEvent(latest, 'agent.resumed', { agent: name, after: 'budget' });
|
|
1978
|
+
if (latest.state === 'waiting' && this.setState(r.id, 'waiting', 'running', null)) {
|
|
1979
|
+
this.ticketRepo.updateStatus(r.ticket_id, 'running');
|
|
1980
|
+
}
|
|
1981
|
+
resumed.push(r.id);
|
|
1982
|
+
}
|
|
1983
|
+
return resumed;
|
|
1984
|
+
}
|
|
1985
|
+
|
|
1986
|
+
// ---- LOOP P3 (issue #2): the loop engine --------------------------------------------
|
|
1987
|
+
|
|
1988
|
+
/** Per run: the next question number and the questions waiting for gru's answer. */
|
|
1989
|
+
private loopAsks = new Map<string, { next: number; pending: Map<number, { agent: string; reply: (r: Record<string, unknown>) => Promise<void> }> }>();
|
|
1990
|
+
|
|
1991
|
+
/** gru's live terminal in the run, or null. */
|
|
1992
|
+
private async gruAddress(run: Run): Promise<string | null> {
|
|
1993
|
+
if (!run.hc_machine) return null;
|
|
1994
|
+
try {
|
|
1995
|
+
const terms = await this.hcClient.getMachineTerminals(run.hc_machine);
|
|
1996
|
+
const live = terms.filter((t) => t.state === 'live');
|
|
1997
|
+
return live.find((t) => t.name === 'gru')?.address ?? live.find((t) => t.address === run.hc_terminal)?.address ?? null;
|
|
1998
|
+
} catch {
|
|
1999
|
+
return null;
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
|
|
2003
|
+
private loopRun(runId: string): { run: Run; ticket: Ticket } {
|
|
2004
|
+
const run = this.runRepo.get(runId);
|
|
2005
|
+
if (!run) throw new NotFoundError(`Run '${runId}' not found`);
|
|
2006
|
+
const ticket = this.ticketRepo.get(run.ticket_id);
|
|
2007
|
+
if (!ticket) throw new NotFoundError(`Ticket '${run.ticket_id}' not found`);
|
|
2008
|
+
return { run, ticket };
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
/** Tell gru something about the loop (best effort: the loop state is what matters). */
|
|
2012
|
+
private async tellGru(run: Run, text: string): Promise<void> {
|
|
2013
|
+
const gru = await this.gruAddress(run);
|
|
2014
|
+
if (!gru) return;
|
|
2015
|
+
try {
|
|
2016
|
+
await this.hcClient.sendText(gru, text);
|
|
2017
|
+
} catch {
|
|
2018
|
+
/* gru will read the state with bond-app loop status */
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
|
|
2022
|
+
/** The questions still waiting when the loop ends get an answer that says so. */
|
|
2023
|
+
private async dropLoopAsks(runId: string, why: string): Promise<void> {
|
|
2024
|
+
const asks = this.loopAsks.get(runId);
|
|
2025
|
+
this.loopAsks.delete(runId);
|
|
2026
|
+
for (const p of asks?.pending.values() ?? []) await p.reply({ ok: false, message: why }).catch(() => {});
|
|
2027
|
+
}
|
|
2028
|
+
|
|
2029
|
+
/**
|
|
2030
|
+
* D6: «Iniciar loop» from the run. The ticket must have the loop enabled (hub, D7) and gru must
|
|
2031
|
+
* be there. Installs the loop commands and skills in the run, turns on BOND_LOOP for every
|
|
2032
|
+
* agent (loop.env through agent-env.sh: running agents see it from their next command), and
|
|
2033
|
+
* tells gru to start with loop-lead.
|
|
2034
|
+
*/
|
|
2035
|
+
async startLoop(runId: string, opts: { plan?: unknown; instructions?: unknown; max_iterations?: unknown } = {}): Promise<Run> {
|
|
2036
|
+
const { run, ticket } = this.loopRun(runId);
|
|
2037
|
+
if (!ticket.loop?.enabled) throw new ValidationError('Este ticket no tiene el modo loop activado');
|
|
2038
|
+
if (ticket.mode !== 'hub') throw new ValidationError('El modo loop solo está disponible en tickets de hub');
|
|
2039
|
+
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}')`);
|
|
2040
|
+
if (run.loop_state === 'running' || run.loop_state === 'paused' || run.loop_state === 'finishing') throw new ValidationError('El loop ya está en marcha');
|
|
2041
|
+
if (!run.container_name || !run.hc_machine) throw new ValidationError('El run no tiene contenedor o sesión de hc');
|
|
2042
|
+
const instructions = opts.instructions === undefined || opts.instructions === null ? '' : String(opts.instructions).trim();
|
|
2043
|
+
if (instructions.length > LOOP_TEXT_MAX) throw new ValidationError(`Las instrucciones pasan de ${LOOP_TEXT_MAX} caracteres`);
|
|
2044
|
+
let max: number | null = ticket.loop.max_iterations;
|
|
2045
|
+
if (opts.max_iterations !== undefined) {
|
|
2046
|
+
const m = opts.max_iterations;
|
|
2047
|
+
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)');
|
|
2048
|
+
max = m as number | null;
|
|
2049
|
+
}
|
|
2050
|
+
const gru = await this.gruAddress(run);
|
|
2051
|
+
if (!gru) throw new ValidationError('gru no está en marcha: relánzalo antes de iniciar el loop');
|
|
2052
|
+
// No plan file: the plan is the ticket's story (gru writes it in docs/plans/ first).
|
|
2053
|
+
let plan = '';
|
|
2054
|
+
if (opts.plan !== undefined && opts.plan !== null && opts.plan !== '') {
|
|
2055
|
+
plan = String(opts.plan);
|
|
2056
|
+
const plans = PLAN_PATH_RE.test(plan) ? await this.listLoopPlans(run.id) : [];
|
|
2057
|
+
if (!plans.includes(plan)) throw new ValidationError(`El plan '${plan.slice(0, 120)}' no está en docs/plans/ del hub`);
|
|
2058
|
+
}
|
|
2059
|
+
|
|
2060
|
+
await this.installBondAppCli(run.container_name);
|
|
2061
|
+
await this.ensureRunPrWatcher(run.id, run.container_name);
|
|
2062
|
+
const skills = await this.dockerClient.exec(run.container_name, ['sh', '-c', LOOP_SKILLS_SCRIPT, 'bond-loop-skills', HUB_DIR], 'runner', 60_000);
|
|
2063
|
+
if (skills.exitCode === 4) {
|
|
2064
|
+
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');
|
|
2065
|
+
}
|
|
2066
|
+
if (skills.exitCode !== 0) throw new Error(`No se pudieron instalar las skills del loop: ${skills.stderr.trim() || skills.stdout.trim()}`);
|
|
2067
|
+
const env = await this.dockerClient.injectStdin(run.container_name, LOOP_ENV_ON_COMMAND, loopEnv(run.id), 'runner');
|
|
2068
|
+
if (env.exitCode !== 0) throw new Error(`No se pudo activar el entorno del loop: ${env.stderr.trim()}`);
|
|
2069
|
+
// The person's set-up at the top of the loop log: gru rereads it every round (it survives
|
|
2070
|
+
// a compaction or a relaunch, unlike the first message).
|
|
2071
|
+
await this.appendLoopLog(run, loopLogStart(new Date().toISOString(), plan, max, instructions));
|
|
2072
|
+
|
|
2073
|
+
const loopConfig: LoopConfig = { plan, instructions, max_iterations: max, messages: [] };
|
|
2074
|
+
this.runRepo.update(run.id, { loop_state: 'running', loop_iteration: 0, loop_stalls: 0, loop_config: loopConfig });
|
|
2075
|
+
this.loopAsks.set(run.id, { next: 1, pending: new Map() });
|
|
2076
|
+
// A run left waiting by the previous loop (a stall, a negative evaluation) goes on.
|
|
2077
|
+
const fresh = this.runRepo.get(run.id)!;
|
|
2078
|
+
if (fresh.state === 'waiting' && isLoopWaitReason(fresh.failure_reason) && this.setState(run.id, 'waiting', 'running', null)) {
|
|
2079
|
+
this.ticketRepo.updateStatus(fresh.ticket_id, 'running');
|
|
2080
|
+
}
|
|
2081
|
+
await this.hcClient.sendText(gru, loopStartMessage(run.id, max, plan, instructions));
|
|
2082
|
+
this.agentEvent(run, 'loop.started', { max_iterations: max, plan, instructions: Boolean(instructions) });
|
|
2083
|
+
return this.runRepo.get(run.id)!;
|
|
2084
|
+
}
|
|
2085
|
+
|
|
2086
|
+
/** The plans gru can carry out (docs/plans/*.md of the hub), newest first. */
|
|
2087
|
+
async listLoopPlans(runId: string): Promise<string[]> {
|
|
2088
|
+
const { run } = this.loopRun(runId);
|
|
2089
|
+
if (!run.container_name) return [];
|
|
2090
|
+
const res = await this.dockerClient.exec(run.container_name, ['sh', '-c', LOOP_PLANS_SCRIPT, 'bond-loop-plans', HUB_DIR], 'runner', 30_000);
|
|
2091
|
+
return res.exitCode === 0 ? sortPlans(res.stdout) : [];
|
|
2092
|
+
}
|
|
2093
|
+
|
|
2094
|
+
/**
|
|
2095
|
+
* «Mensaje a gru»: the person's instruction while the loop runs. It goes to the loop log
|
|
2096
|
+
* (so gru keeps it across rounds) and to gru's terminal.
|
|
2097
|
+
*/
|
|
2098
|
+
async messageLoop(runId: string, textIn: unknown): Promise<Run> {
|
|
2099
|
+
const { run } = this.loopRun(runId);
|
|
2100
|
+
if (run.loop_state !== 'running' && run.loop_state !== 'paused' && run.loop_state !== 'finishing') {
|
|
2101
|
+
throw new ValidationError('No hay un loop en marcha al que mandar instrucciones');
|
|
2102
|
+
}
|
|
2103
|
+
const text = typeof textIn === 'string' ? textIn.trim() : '';
|
|
2104
|
+
if (!text) throw new ValidationError('El mensaje está vacío');
|
|
2105
|
+
if (text.length > LOOP_TEXT_MAX) throw new ValidationError(`El mensaje pasa de ${LOOP_TEXT_MAX} caracteres`);
|
|
2106
|
+
const gru = await this.gruAddress(run);
|
|
2107
|
+
if (!gru) throw new ValidationError('gru no está en marcha: relánzalo antes de mandarle instrucciones');
|
|
2108
|
+
const at = new Date().toISOString();
|
|
2109
|
+
await this.appendLoopLog(run, loopLogMessage(at, text));
|
|
2110
|
+
const cfg: LoopConfig = run.loop_config ?? { plan: '', instructions: '', max_iterations: null, messages: [] };
|
|
2111
|
+
this.runRepo.update(run.id, { loop_config: { ...cfg, messages: [...(cfg.messages ?? []), { at, text }].slice(-50) } });
|
|
2112
|
+
await this.hcClient.sendText(gru, loopMessageText(run.id, text));
|
|
2113
|
+
this.agentEvent(run, 'loop.message', { text });
|
|
2114
|
+
return this.runRepo.get(run.id)!;
|
|
2115
|
+
}
|
|
2116
|
+
|
|
2117
|
+
/** Append to the loop log in the hub (as runner). */
|
|
2118
|
+
private async appendLoopLog(run: Run, block: string): Promise<void> {
|
|
2119
|
+
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');
|
|
2120
|
+
if (res.exitCode !== 0) throw new Error(`No se pudo escribir el registro del loop: ${res.stderr.trim()}`);
|
|
2121
|
+
}
|
|
2122
|
+
|
|
2123
|
+
/** The loop's iteration limit: the one chosen at «Iniciar loop», else the ticket's. */
|
|
2124
|
+
private loopMax(run: Run, ticket: Ticket): number | null {
|
|
2125
|
+
if (run.loop_config && run.loop_config.max_iterations !== undefined) return run.loop_config.max_iterations;
|
|
2126
|
+
return ticket.loop?.max_iterations ?? null;
|
|
2127
|
+
}
|
|
2128
|
+
|
|
2129
|
+
async pauseLoop(runId: string): Promise<Run> {
|
|
2130
|
+
const { run } = this.loopRun(runId);
|
|
2131
|
+
if (run.loop_state !== 'running' && run.loop_state !== 'finishing') throw new ValidationError('No hay un loop en marcha que pausar');
|
|
2132
|
+
this.runRepo.update(run.id, { loop_state: 'paused' });
|
|
2133
|
+
await this.tellGru(run, '[bond-app loop] Pausa: termina el paso en curso, no repartas más trabajo y espera.');
|
|
2134
|
+
this.agentEvent(run, 'loop.paused', { by: 'person' });
|
|
2135
|
+
return this.runRepo.get(run.id)!;
|
|
2136
|
+
}
|
|
2137
|
+
|
|
2138
|
+
async resumeLoop(runId: string): Promise<Run> {
|
|
2139
|
+
const { run } = this.loopRun(runId);
|
|
2140
|
+
if (run.loop_state !== 'paused') throw new ValidationError('El loop no está en pausa');
|
|
2141
|
+
this.runRepo.update(run.id, { loop_state: 'running' });
|
|
2142
|
+
if (!this.loopAsks.has(run.id)) this.loopAsks.set(run.id, { next: 1, pending: new Map() });
|
|
2143
|
+
await this.tellGru(run, '[bond-app loop] La persona ha reanudado el loop: sigue donde lo dejaste.');
|
|
2144
|
+
this.agentEvent(run, 'loop.resumed', {});
|
|
2145
|
+
const fresh = this.runRepo.get(run.id)!;
|
|
2146
|
+
if (fresh.state === 'waiting' && this.setState(run.id, 'waiting', 'running', null)) this.ticketRepo.updateStatus(fresh.ticket_id, 'running');
|
|
2147
|
+
return this.runRepo.get(run.id)!;
|
|
2148
|
+
}
|
|
2149
|
+
|
|
2150
|
+
/** Stop the loop (the person, or a stall): no more rounds; BOND_LOOP off; the run waits. */
|
|
2151
|
+
async stopLoop(runId: string, reason = 'la persona lo ha parado'): Promise<Run> {
|
|
2152
|
+
const { run } = this.loopRun(runId);
|
|
2153
|
+
if (!run.loop_state || run.loop_state === 'finished' || run.loop_state === 'stopped') throw new ValidationError('No hay un loop que parar');
|
|
2154
|
+
this.runRepo.update(run.id, { loop_state: 'stopped' });
|
|
2155
|
+
if (run.container_name) await this.dockerClient.exec(run.container_name, LOOP_ENV_OFF_COMMAND, 'runner').catch(() => undefined);
|
|
2156
|
+
await this.dropLoopAsks(run.id, 'El loop se ha parado: sigue sin gru y cuéntalo en tu informe.');
|
|
2157
|
+
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.`);
|
|
2158
|
+
this.agentEvent(run, 'loop.stopped', { reason });
|
|
2159
|
+
// The person ended the loop: a wait the loop had put the run in is over (a stall sets its own after this).
|
|
2160
|
+
const fresh = this.runRepo.get(run.id)!;
|
|
2161
|
+
if (fresh.state === 'waiting' && isLoopWaitReason(fresh.failure_reason) && this.setState(run.id, 'waiting', 'running', null)) {
|
|
2162
|
+
this.ticketRepo.updateStatus(fresh.ticket_id, 'running');
|
|
2163
|
+
}
|
|
2164
|
+
return this.runRepo.get(run.id)!;
|
|
2165
|
+
}
|
|
2166
|
+
|
|
2167
|
+
/** The run waits for the person, with a reason (from running; or the reason changes). */
|
|
2168
|
+
private loopWait(runId: string, reason: string): void {
|
|
2169
|
+
const run = this.runRepo.get(runId);
|
|
2170
|
+
if (!run) return;
|
|
2171
|
+
if (run.state === 'running') {
|
|
2172
|
+
if (this.setState(runId, 'running', 'waiting', reason)) this.ticketRepo.updateStatus(run.ticket_id, 'waiting');
|
|
2173
|
+
} else if (run.state === 'waiting') {
|
|
2174
|
+
this.runRepo.update(runId, { failure_reason: reason });
|
|
2175
|
+
}
|
|
2176
|
+
}
|
|
2177
|
+
|
|
2178
|
+
/**
|
|
2179
|
+
* A request from the run's `bond-app ask|answer|loop` (FIFO). Returns the answer to write
|
|
2180
|
+
* back, or null when it comes later (a question waits for gru's answer).
|
|
2181
|
+
*/
|
|
2182
|
+
async handleLoopRequest(runId: string, req: Record<string, unknown>, reply: (r: Record<string, unknown>) => Promise<void>): Promise<Record<string, unknown> | null> {
|
|
2183
|
+
const { run, ticket } = this.loopRun(runId);
|
|
2184
|
+
const state = run.loop_state ?? null;
|
|
2185
|
+
const active = state === 'running' || state === 'finishing';
|
|
2186
|
+
const agent = typeof req.agent === 'string' ? req.agent.slice(0, 64) : '';
|
|
2187
|
+
const text = (v: unknown) => (typeof v === 'string' ? v.trim().slice(0, LOOP_TEXT_MAX) : '');
|
|
2188
|
+
const max = this.loopMax(run, ticket);
|
|
2189
|
+
// The leader's commands: from gru (BOND_AGENT <kind>/gru), or with no identity at all.
|
|
2190
|
+
const isLead = !agent || agent.endsWith('/gru');
|
|
2191
|
+
const lead = () => (isLead ? null : { ok: false, message: 'Solo gru, el líder del loop, puede usar este comando.' });
|
|
2192
|
+
|
|
2193
|
+
switch (req.cmd) {
|
|
2194
|
+
case 'loop-status':
|
|
2195
|
+
return { ok: true, message: `loop: ${state ?? 'sin iniciar'} · iteración ${run.loop_iteration ?? 0}${max === null ? ' (sin límite)' : ` de ${max}`}` };
|
|
2196
|
+
case 'ask': {
|
|
2197
|
+
if (!active) return { ok: false, message: 'No hay un loop en marcha: no hay líder al que preguntar.' };
|
|
2198
|
+
const question = text(req.question);
|
|
2199
|
+
if (!question) return { ok: false, message: 'La pregunta está vacía.' };
|
|
2200
|
+
const gru = await this.gruAddress(run);
|
|
2201
|
+
if (!gru) return { ok: false, message: 'gru no está en marcha: no hay a quién preguntar.' };
|
|
2202
|
+
const asks = this.loopAsks.get(run.id) ?? { next: 1, pending: new Map() };
|
|
2203
|
+
this.loopAsks.set(run.id, asks);
|
|
2204
|
+
const n = asks.next++;
|
|
2205
|
+
const who = agent.split('/').pop() || 'agente';
|
|
2206
|
+
asks.pending.set(n, { agent: who, reply });
|
|
2207
|
+
await this.hcClient.sendText(gru, askMessage(n, who, question));
|
|
2208
|
+
this.agentEvent(run, 'loop.ask', { n, agent: who, question });
|
|
2209
|
+
return null;
|
|
2210
|
+
}
|
|
2211
|
+
case 'answer': {
|
|
2212
|
+
const denied = lead();
|
|
2213
|
+
if (denied) return denied;
|
|
2214
|
+
const n = Number(req.n);
|
|
2215
|
+
const p = this.loopAsks.get(run.id)?.pending.get(n);
|
|
2216
|
+
if (!p) return { ok: false, message: `No hay ninguna pregunta #${n} pendiente.` };
|
|
2217
|
+
const answer = text(req.text);
|
|
2218
|
+
if (!answer) return { ok: false, message: 'La respuesta está vacía.' };
|
|
2219
|
+
this.loopAsks.get(run.id)!.pending.delete(n);
|
|
2220
|
+
await p.reply({ ok: true, message: answer });
|
|
2221
|
+
this.agentEvent(run, 'loop.answer', { n, agent: p.agent, answer });
|
|
2222
|
+
return { ok: true, message: `Respuesta #${n} entregada a ${p.agent}.` };
|
|
2223
|
+
}
|
|
2224
|
+
case 'loop-next': {
|
|
2225
|
+
const denied = lead();
|
|
2226
|
+
if (denied) return denied;
|
|
2227
|
+
if (!active) return { ok: false, message: `El loop no está en marcha (${state ?? 'sin iniciar'}).` };
|
|
2228
|
+
const stallLimit = this.settingsRepo.getLoopDefaults().stall_iterations;
|
|
2229
|
+
const round = nextRound({ iteration: run.loop_iteration ?? 0, stalls: run.loop_stalls ?? 0 }, req.progress === true, max, stallLimit);
|
|
2230
|
+
this.runRepo.update(run.id, { loop_iteration: round.iteration, loop_stalls: round.stalls });
|
|
2231
|
+
this.agentEvent(run, 'loop.iteration', { iteration: round.iteration, progress: req.progress === true, summary: text(req.summary) });
|
|
2232
|
+
if (round.action === 'stall') {
|
|
2233
|
+
const why = `${round.stalls} vueltas seguidas sin avance`;
|
|
2234
|
+
await this.stopLoop(run.id, why);
|
|
2235
|
+
this.loopWait(run.id, `Loop parado: ${why}. gru necesita a una persona.`);
|
|
2236
|
+
return { ok: true, message: `Loop parado: ${why}. La persona decide cómo seguir.` };
|
|
2237
|
+
}
|
|
2238
|
+
if (round.action === 'finish') {
|
|
2239
|
+
this.runRepo.update(run.id, { loop_state: 'finishing' });
|
|
2240
|
+
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>.` };
|
|
2241
|
+
}
|
|
2242
|
+
return { ok: true, message: `Vuelta ${round.iteration}${max === null ? '' : ` de ${max}`} registrada. Sigue con la siguiente.` };
|
|
2243
|
+
}
|
|
2244
|
+
case 'loop-needs-human': {
|
|
2245
|
+
const denied = lead();
|
|
2246
|
+
if (denied) return denied;
|
|
2247
|
+
if (!active) return { ok: false, message: `El loop no está en marcha (${state ?? 'sin iniciar'}).` };
|
|
2248
|
+
const why = text(req.why) || 'sin motivo';
|
|
2249
|
+
this.runRepo.update(run.id, { loop_state: 'paused' });
|
|
2250
|
+
this.loopWait(run.id, `gru necesita a una persona: ${why}`);
|
|
2251
|
+
this.agentEvent(run, 'loop.needs_human', { why });
|
|
2252
|
+
return { ok: true, message: 'Avisada la persona: espera su respuesta (el loop queda en pausa).' };
|
|
2253
|
+
}
|
|
2254
|
+
case 'loop-finish': {
|
|
2255
|
+
const denied = lead();
|
|
2256
|
+
if (denied) return denied;
|
|
2257
|
+
if (!active) return { ok: false, message: `El loop no está en marcha (${state ?? 'sin iniciar'}).` };
|
|
2258
|
+
const result = req.result === 'pass' ? 'pass' : 'fail';
|
|
2259
|
+
const report = text(req.report);
|
|
2260
|
+
this.runRepo.update(run.id, { loop_state: 'finished' });
|
|
2261
|
+
if (run.container_name) await this.dockerClient.exec(run.container_name, LOOP_ENV_OFF_COMMAND, 'runner').catch(() => undefined);
|
|
2262
|
+
await this.dropLoopAsks(run.id, 'El loop ha terminado.');
|
|
2263
|
+
this.agentEvent(run, 'loop.finished', { result, report, iteration: run.loop_iteration ?? 0 });
|
|
2264
|
+
if (result === 'pass') {
|
|
2265
|
+
// D5: a positive evaluation delivers as usual (verification, push, PR).
|
|
2266
|
+
void this.deliverRun(run.id).catch(() => {});
|
|
2267
|
+
return { ok: true, message: 'Evaluación positiva: bond-app entrega el run (verificación, push y PR).' };
|
|
2268
|
+
}
|
|
2269
|
+
this.loopWait(run.id, `Loop terminado con evaluación negativa: revisa ${report || 'el registro del loop'}.`);
|
|
2270
|
+
return { ok: true, message: 'Evaluación negativa: el run espera a la persona.' };
|
|
2271
|
+
}
|
|
2272
|
+
default:
|
|
2273
|
+
return { ok: false, message: `Comando de loop desconocido: ${String(req.cmd)}` };
|
|
2274
|
+
}
|
|
2275
|
+
}
|
|
2276
|
+
|
|
2277
|
+
/**
|
|
2278
|
+
* The run's `bond-app` command (as root): the shell script (`pr`) and, for LOOP P3, the node
|
|
2279
|
+
* CLI it hands `ask`, `answer` and `loop` to. Installed at start, and again when a loop
|
|
2280
|
+
* starts on a run from before the loop existed.
|
|
2281
|
+
*/
|
|
2282
|
+
async installBondAppCli(containerName: string): Promise<void> {
|
|
2283
|
+
await this.dockerClient.injectStdin(containerName, ['sh', '-c', 'cat > /usr/local/bin/bond-app && chmod 0755 /usr/local/bin/bond-app'], BOND_APP_SCRIPT, 'root');
|
|
2284
|
+
await this.dockerClient.injectStdin(
|
|
2285
|
+
containerName,
|
|
2286
|
+
['sh', '-c', 'mkdir -p /usr/local/lib && cat > /usr/local/lib/bond-app-loop.js && chmod 0755 /usr/local/lib/bond-app-loop.js'],
|
|
2287
|
+
BOND_APP_LOOP_CLI,
|
|
2288
|
+
'root'
|
|
2289
|
+
);
|
|
2290
|
+
}
|
|
2291
|
+
|
|
1745
2292
|
/** A `verifying` run with no delivery in progress (e.g. after a restart): resume it. */
|
|
1746
2293
|
private resumeStrandedDeliveries(): void {
|
|
1747
2294
|
for (const r of this.runRepo.list({ state: 'verifying' })) {
|
|
@@ -2074,7 +2621,7 @@ export class Orchestrator {
|
|
|
2074
2621
|
const n = Number(/\/t(\d+)$/.exec(run.hc_terminal || '')?.[1] || '1') + 1;
|
|
2075
2622
|
const terminal = await this.hcClient.startTerminal(
|
|
2076
2623
|
run.hc_machine,
|
|
2077
|
-
await this.resolveAgentCommand(run.container_name, ticket, message),
|
|
2624
|
+
await this.resolveAgentCommand(run.container_name, this.effectiveTicket(run, ticket), message),
|
|
2078
2625
|
'/workspace/repo',
|
|
2079
2626
|
`agent-${n}`
|
|
2080
2627
|
);
|
|
@@ -2110,6 +2657,181 @@ export class Orchestrator {
|
|
|
2110
2657
|
return this.runRepo.get(runId)!;
|
|
2111
2658
|
}
|
|
2112
2659
|
|
|
2660
|
+
/** Issue #3: the ticket as this run sees it (a relaunch may have changed agent and model). */
|
|
2661
|
+
effectiveTicket(run: Run, ticket: Ticket): Ticket {
|
|
2662
|
+
if (!run.agent_override || !isValidAgent(run.agent_override)) return ticket;
|
|
2663
|
+
return { ...ticket, agent: run.agent_override, model: run.model_override ?? undefined };
|
|
2664
|
+
}
|
|
2665
|
+
|
|
2666
|
+
/** Issue #3: which run terminal `name` is, its agent kind, cwd and leader. */
|
|
2667
|
+
private async relaunchTarget(runId: string, name: string) {
|
|
2668
|
+
const run = this.runRepo.get(runId);
|
|
2669
|
+
if (!run) throw new NotFoundError(`Run '${runId}' not found`);
|
|
2670
|
+
const ticket = this.ticketRepo.get(run.ticket_id);
|
|
2671
|
+
if (!ticket) throw new NotFoundError(`Ticket '${run.ticket_id}' not found`);
|
|
2672
|
+
if (!['running', 'waiting', 'blocked'].includes(run.state)) {
|
|
2673
|
+
throw new ValidationError(`Only a running, waiting or blocked run can relaunch an agent (this one is '${run.state}')`);
|
|
2674
|
+
}
|
|
2675
|
+
if (this.deliveries.has(runId)) throw new ValidationError('The run is being verified or delivered: wait for it to finish');
|
|
2676
|
+
if (!run.hc_machine || !run.container_name) throw new ValidationError('The run has no container or hc session');
|
|
2677
|
+
if (!/^[a-z][a-z0-9_-]{0,31}$/.test(name)) throw new ValidationError(`Invalid agent name '${name}'`);
|
|
2678
|
+
const terms = (await this.hcClient.getMachineTerminals(run.hc_machine, { all: true })).filter((t) => t.name === name);
|
|
2679
|
+
const term = terms.find((t) => t.state === 'live') ?? terms.at(-1);
|
|
2680
|
+
if (!term?.address) throw new NotFoundError(`No agent '${name}' in this run`);
|
|
2681
|
+
let argv: string[] | undefined;
|
|
2682
|
+
try {
|
|
2683
|
+
argv = (await this.hcClient.getTerminal(term.address)).argv;
|
|
2684
|
+
} catch {
|
|
2685
|
+
argv = undefined;
|
|
2686
|
+
}
|
|
2687
|
+
const eff = this.effectiveTicket(run, ticket);
|
|
2688
|
+
const fromKind = agentKindOfArgv(argv) ?? (name === 'gru' ? eff.agent : 'pi');
|
|
2689
|
+
const cwd = term.cwd || (ticket.mode === 'hub' ? HUB_DIR : '/workspace/repo');
|
|
2690
|
+
const leader = ticket.mode === 'hub' && name !== 'gru' ? 'gru' : null;
|
|
2691
|
+
return { run, ticket, term: { ...term, address: term.address }, fromKind, cwd, leader, container: run.container_name, machine: run.hc_machine };
|
|
2692
|
+
}
|
|
2693
|
+
|
|
2694
|
+
/** Issue #3: the agents a run can relaunch with (in its image and with credentials). */
|
|
2695
|
+
async relaunchOptions(runId: string, name: string): Promise<{
|
|
2696
|
+
name: string;
|
|
2697
|
+
from: string;
|
|
2698
|
+
cwd: string;
|
|
2699
|
+
agents: Array<{ agent: string; available: boolean; reason?: string }>;
|
|
2700
|
+
default_model: string | null;
|
|
2701
|
+
}> {
|
|
2702
|
+
const t = await this.relaunchTarget(runId, name);
|
|
2703
|
+
let installed: string[] | null = null;
|
|
2704
|
+
try {
|
|
2705
|
+
const res = await this.dockerClient.exec(t.container, ['cat', '/opt/runner-agents']);
|
|
2706
|
+
if (res.exitCode === 0) installed = parseRunnerManifest(res.stdout);
|
|
2707
|
+
} catch {
|
|
2708
|
+
installed = null;
|
|
2709
|
+
}
|
|
2710
|
+
const agents = SUPPORTED_AGENTS.map((agent) => {
|
|
2711
|
+
if (installed && !installed.includes(agent)) return { agent, available: false, reason: 'no está en la imagen del run' };
|
|
2712
|
+
if (!this.settingsRepo.getCredential(agent)) return { agent, available: false, reason: 'sin credenciales: configúralo en Ajustes' };
|
|
2713
|
+
return { agent, available: true };
|
|
2714
|
+
});
|
|
2715
|
+
return { name, from: t.fromKind, cwd: t.cwd, agents, default_model: this.settingsRepo?.getSetupSelection?.()?.default_model ?? null };
|
|
2716
|
+
}
|
|
2717
|
+
|
|
2718
|
+
/** The run's secrets that must never reach a handoff. */
|
|
2719
|
+
private runSecrets(ticket: Ticket, runId: string): string[] {
|
|
2720
|
+
const urls = [ticket.repo_url, ticket.hub_url, ...(ticket.repos ?? []).map((r) => r.url)].filter((u): u is string => Boolean(u));
|
|
2721
|
+
const out = new Set<string>();
|
|
2722
|
+
for (const url of urls) {
|
|
2723
|
+
try {
|
|
2724
|
+
const token = this.repoAccessFor(url, runId).token;
|
|
2725
|
+
if (token) out.add(token);
|
|
2726
|
+
} catch {
|
|
2727
|
+
/* no access configured */
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
const gh = this.settingsRepo.getGitHubToken();
|
|
2731
|
+
if (gh) out.add(gh);
|
|
2732
|
+
return [...out];
|
|
2733
|
+
}
|
|
2734
|
+
|
|
2735
|
+
/** Issue #3: the handoff for relaunching `name` (preview for the dialog, or the real one). */
|
|
2736
|
+
async relaunchHandoff(runId: string, name: string, toKind: string, reason: string): Promise<string> {
|
|
2737
|
+
const t = await this.relaunchTarget(runId, name);
|
|
2738
|
+
const base = t.ticket.mode === 'hub' ? t.ticket.hub_base || 'main' : t.ticket.base_branch || 'main';
|
|
2739
|
+
let raw = '';
|
|
2740
|
+
try {
|
|
2741
|
+
const res = await this.dockerClient.exec(t.container, ['sh', '-c', HANDOFF_GATHER_SCRIPT, 'bond-handoff', t.cwd, t.fromKind, base], 'runner', 60_000);
|
|
2742
|
+
raw = res.stdout;
|
|
2743
|
+
} catch {
|
|
2744
|
+
raw = '';
|
|
2745
|
+
}
|
|
2746
|
+
const gather = parseGather(raw);
|
|
2747
|
+
const text = buildHandoff({
|
|
2748
|
+
ticketTitle: t.ticket.title,
|
|
2749
|
+
task: t.ticket.story || t.ticket.prompt || '',
|
|
2750
|
+
agentName: name,
|
|
2751
|
+
fromKind: t.fromKind,
|
|
2752
|
+
toKind,
|
|
2753
|
+
reason,
|
|
2754
|
+
cwd: t.cwd,
|
|
2755
|
+
leader: t.leader,
|
|
2756
|
+
gather,
|
|
2757
|
+
decisions: decisionsBy(gather.decisions, name, t.run.started_at ?? t.run.created_at),
|
|
2758
|
+
});
|
|
2759
|
+
return redactSecrets(text, this.runSecrets(t.ticket, runId));
|
|
2760
|
+
}
|
|
2761
|
+
|
|
2762
|
+
/**
|
|
2763
|
+
* Issue #3 «Relanzar con resumen»: replace a run's agent (gru or a team member) with a new
|
|
2764
|
+
* one, of the same kind or another, that starts from a handoff. The stuck agent is never
|
|
2765
|
+
* asked for anything: its session files, git and the run's decisions make the handoff, and it
|
|
2766
|
+
* is ended from outside (`hc kill`), so a Claude at its usage limit or a pi with a full
|
|
2767
|
+
* context can be replaced. The new agent keeps the name, folder and labels.
|
|
2768
|
+
*/
|
|
2769
|
+
async relaunchAgent(
|
|
2770
|
+
runId: string,
|
|
2771
|
+
name: string,
|
|
2772
|
+
body: { agent?: unknown; model?: unknown; reason?: unknown; handoff?: unknown }
|
|
2773
|
+
): Promise<Run> {
|
|
2774
|
+
const toKind = typeof body.agent === 'string' ? body.agent : '';
|
|
2775
|
+
if (!isValidAgent(toKind)) throw new ValidationError(`Unsupported agent '${toKind}'`);
|
|
2776
|
+
const reason = typeof body.reason === 'string' && body.reason.trim() ? body.reason.trim().slice(0, 200) : 'relanzado a mano';
|
|
2777
|
+
const model = toKind === 'pi' && typeof body.model === 'string' && body.model.trim() ? body.model.trim() : null;
|
|
2778
|
+
if (model && !/^[A-Za-z0-9_.:/@+-]{1,200}$/.test(model)) throw new ValidationError(`Invalid model '${model}'`);
|
|
2779
|
+
if (body.handoff !== undefined && (typeof body.handoff !== 'string' || body.handoff.length > 60_000)) {
|
|
2780
|
+
throw new ValidationError("'handoff' must be text up to 60000 characters");
|
|
2781
|
+
}
|
|
2782
|
+
if (this.relaunching.has(runId)) throw new ValidationError('An agent of this run is already being relaunched');
|
|
2783
|
+
this.relaunching.add(runId);
|
|
2784
|
+
try {
|
|
2785
|
+
const options = await this.relaunchOptions(runId, name);
|
|
2786
|
+
const choice = options.agents.find((a) => a.agent === toKind);
|
|
2787
|
+
if (!choice?.available) throw new ValidationError(`Cannot relaunch with ${toKind}: ${choice?.reason ?? 'not available'}`);
|
|
2788
|
+
const t = await this.relaunchTarget(runId, name);
|
|
2789
|
+
// Relaunching pi as pi without a model keeps the ticket's.
|
|
2790
|
+
const runModel = model ?? (toKind === 'pi' && t.ticket.agent === 'pi' ? t.ticket.model ?? null : null);
|
|
2791
|
+
const handoff = typeof body.handoff === 'string'
|
|
2792
|
+
? redactSecrets(body.handoff, this.runSecrets(t.ticket, runId))
|
|
2793
|
+
: await this.relaunchHandoff(runId, name, toKind, reason);
|
|
2794
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
2795
|
+
const handoffPath = `/home/runner/.bond/handoff/${stamp}-${name}.md`;
|
|
2796
|
+
const wrote = await this.dockerClient.injectStdin(
|
|
2797
|
+
t.container,
|
|
2798
|
+
['sh', '-c', 'umask 077; mkdir -p "$(dirname "$1")" && cat > "$1"', '--', handoffPath],
|
|
2799
|
+
handoff,
|
|
2800
|
+
'runner'
|
|
2801
|
+
);
|
|
2802
|
+
if (wrote.exitCode !== 0) throw new Error(`Could not write the handoff: ${wrote.stderr.trim()}`);
|
|
2803
|
+
// The new agent's credentials (and pi's compaction tuning) in this container.
|
|
2804
|
+
await this.injectCredentials(t.container, [toKind]);
|
|
2805
|
+
await this.hcClient.killTerminal(t.term.address);
|
|
2806
|
+
|
|
2807
|
+
const prompt = `Retomas el trabajo de ${name}: lee el traspaso en ${handoffPath} antes de nada y continúa desde ahí.`;
|
|
2808
|
+
const inner = this.bareAgentCommand({ ...t.ticket, agent: toKind, model: runModel ?? undefined }, [prompt]);
|
|
2809
|
+
const hubEnv = t.ticket.mode === 'hub' ? 'export BOND_TEAM_ENGINE=hc BOND_TEAM_NO_TABLE=1 && ' : '';
|
|
2810
|
+
const argv = [
|
|
2811
|
+
'sh', '-c', `cd "$1" && export BOND_AGENT="$2" && shift 2 && ${hubEnv}exec "$@"`,
|
|
2812
|
+
'bond-relaunch', t.cwd, `${toKind}/${name}`, ...inner,
|
|
2813
|
+
];
|
|
2814
|
+
const labels = Object.fromEntries(
|
|
2815
|
+
Object.entries(t.term.labels ?? {}).filter(([k]) => k.startsWith('bond.') || k === 'herdr.space' || k === 'herdr.tab' || k === 'role')
|
|
2816
|
+
);
|
|
2817
|
+
const address = await this.hcClient.startTerminal(t.machine, argv, t.cwd, name, labels);
|
|
2818
|
+
|
|
2819
|
+
this.stuckByRun.delete(runId);
|
|
2820
|
+
if (t.run.resume_at) this.runRepo.update(runId, { resume_at: null, resume_agent: null });
|
|
2821
|
+
const isMain = name === 'gru' || t.run.hc_terminal === t.term.address;
|
|
2822
|
+
if (isMain) this.runRepo.update(runId, { hc_terminal: address, agent_override: toKind, model_override: runModel });
|
|
2823
|
+
this.agentEvent(t.run, 'agent.relaunched', { name, from: t.fromKind, to: toKind, model: runModel, reason, handoff: handoffPath, terminal: address });
|
|
2824
|
+
const fresh = this.runRepo.get(runId)!;
|
|
2825
|
+
if (fresh.state === 'waiting' || fresh.state === 'blocked') {
|
|
2826
|
+
this.setState(runId, fresh.state, 'running', null, { verify_failures: 0 });
|
|
2827
|
+
this.ticketRepo.updateStatus(t.ticket.id, 'running');
|
|
2828
|
+
}
|
|
2829
|
+
return this.runRepo.get(runId)!;
|
|
2830
|
+
} finally {
|
|
2831
|
+
this.relaunching.delete(runId);
|
|
2832
|
+
}
|
|
2833
|
+
}
|
|
2834
|
+
|
|
2113
2835
|
/**
|
|
2114
2836
|
* P7: mark a running or waiting run as finished (keeping container and session alive).
|
|
2115
2837
|
* Called by the user via the card action «Terminado» or POST /api/v1/runs/:id/finish.
|
|
@@ -2332,15 +3054,7 @@ export class Orchestrator {
|
|
|
2332
3054
|
const machine = run.hc_machine || machineNameForRun(run.id);
|
|
2333
3055
|
const terminals = await this.hcClient.getMachineTerminals(machine);
|
|
2334
3056
|
|
|
2335
|
-
const isLeader =
|
|
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
|
-
};
|
|
3057
|
+
const isLeader = isLeaderTerminal;
|
|
2344
3058
|
|
|
2345
3059
|
const rows: TeamStatusRow[] = [];
|
|
2346
3060
|
const leader = terminals.find(isLeader);
|
|
@@ -2412,15 +3126,7 @@ export class Orchestrator {
|
|
|
2412
3126
|
}
|
|
2413
3127
|
|
|
2414
3128
|
if (isHub) {
|
|
2415
|
-
const isLeader =
|
|
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
|
-
};
|
|
3129
|
+
const isLeader = isLeaderHerdrAgent;
|
|
2424
3130
|
|
|
2425
3131
|
let leaderAgent: any = null;
|
|
2426
3132
|
if (agentRes && agentRes.exitCode === 0) {
|
|
@@ -2521,6 +3227,31 @@ export class Orchestrator {
|
|
|
2521
3227
|
* P4: Proxy hc ls for the run's machine, returning live terminals with agent, state,
|
|
2522
3228
|
* turn, and where (cwd). Returns an empty list if machine is down or unreachable without breaking.
|
|
2523
3229
|
*/
|
|
3230
|
+
/**
|
|
3231
|
+
* Issue #3: the run's named agents whose program has ended and that no live terminal
|
|
3232
|
+
* replaced (NAV-4588's gru), so the Agents panel can offer «Relanzar con resumen» on them.
|
|
3233
|
+
*/
|
|
3234
|
+
async getClosedAgents(runId: string): Promise<Array<{ name: string; address: string; exit_code: number | null }>> {
|
|
3235
|
+
const run = this.runRepo.get(runId);
|
|
3236
|
+
if (!run) throw new NotFoundError(`Run '${runId}' not found`);
|
|
3237
|
+
if (!run.hc_machine || !['running', 'waiting', 'blocked'].includes(run.state)) return [];
|
|
3238
|
+
let listed: Awaited<ReturnType<HcClient['listTerminals']>> = [];
|
|
3239
|
+
try {
|
|
3240
|
+
listed = await this.hcClient.listTerminals(run.hc_machine, { all: true });
|
|
3241
|
+
} catch {
|
|
3242
|
+
return [];
|
|
3243
|
+
}
|
|
3244
|
+
const named = (n?: string) => Boolean(n && n !== 'agent' && !/^t\d+$/.test(n));
|
|
3245
|
+
const isLive = (t: { state?: string; exit_code?: number | null }) => (!t.state || t.state === 'live') && (t.exit_code === null || t.exit_code === undefined);
|
|
3246
|
+
const liveNames = new Set(listed.filter(isLive).map((t) => t.name));
|
|
3247
|
+
const out = new Map<string, { name: string; address: string; exit_code: number | null }>();
|
|
3248
|
+
for (const t of listed) {
|
|
3249
|
+
if (isLive(t) || !named(t.name) || liveNames.has(t.name)) continue;
|
|
3250
|
+
out.set(t.name!, { name: t.name!, address: t.address, exit_code: t.exit_code ?? null });
|
|
3251
|
+
}
|
|
3252
|
+
return [...out.values()];
|
|
3253
|
+
}
|
|
3254
|
+
|
|
2524
3255
|
async getRunTerminals(runId: string): Promise<RunTerminal[]> {
|
|
2525
3256
|
const run = this.runRepo.get(runId);
|
|
2526
3257
|
if (!run) throw new ValidationError(`Run '${runId}' not found`);
|
|
@@ -3090,7 +3821,42 @@ export class Orchestrator {
|
|
|
3090
3821
|
this.setState(runId, 'analyzing', 'blocked', 'hub_incomplete');
|
|
3091
3822
|
return current();
|
|
3092
3823
|
}
|
|
3093
|
-
|
|
3824
|
+
return this.launchHubTeam(runId, analysis);
|
|
3825
|
+
}
|
|
3826
|
+
|
|
3827
|
+
/**
|
|
3828
|
+
* «Seguir sin ellos»: the person reads the hub analysis and starts the team anyway. Only
|
|
3829
|
+
* when every gap is the hub agent's opinion (a repo it thinks is missing, or "not ready");
|
|
3830
|
+
* a fixed check (a repo not mounted, a base missing…) still has to be fixed first.
|
|
3831
|
+
*/
|
|
3832
|
+
async proceedHub(runId: string): Promise<Run> {
|
|
3833
|
+
const run = this.runRepo.get(runId);
|
|
3834
|
+
if (!run) throw new NotFoundError(`Run '${runId}' not found`);
|
|
3835
|
+
if (run.state !== 'blocked' || run.failure_reason !== 'hub_incomplete' || !run.hub_analysis) {
|
|
3836
|
+
throw new ValidationError('Solo se sigue adelante con un run bloqueado por un hub incompleto');
|
|
3837
|
+
}
|
|
3838
|
+
if (this.analyses.has(runId) || this.approving.has(runId)) throw new ValidationError('El hub ya se está analizando');
|
|
3839
|
+
const fixed = run.hub_analysis.gaps.filter((g) => !HUB_OPINION_GAPS.has(g.kind));
|
|
3840
|
+
if (fixed.length > 0) {
|
|
3841
|
+
throw new ValidationError(`El hub tiene problemas que hay que arreglar antes: ${fixed.map((g) => g.message).join('; ').slice(0, 300)}`);
|
|
3842
|
+
}
|
|
3843
|
+
this.approving.add(runId);
|
|
3844
|
+
try {
|
|
3845
|
+
if (!this.setState(runId, 'blocked', 'analyzing', null)) {
|
|
3846
|
+
throw new ValidationError('El run cambió de estado mientras se seguía adelante');
|
|
3847
|
+
}
|
|
3848
|
+
this.agentEvent(run, 'hub.proceed', { gaps: run.hub_analysis.gaps.map((g) => g.id) });
|
|
3849
|
+
return await this.launchHubTeam(runId, run.hub_analysis);
|
|
3850
|
+
} finally {
|
|
3851
|
+
this.approving.delete(runId);
|
|
3852
|
+
}
|
|
3853
|
+
}
|
|
3854
|
+
|
|
3855
|
+
/** The hub covers the story (or the person said to go on): the team, one agent per repo, on the ticket's branch. */
|
|
3856
|
+
private async launchHubTeam(runId: string, analysis: HubAnalysis): Promise<Run> {
|
|
3857
|
+
const current = () => this.runRepo.get(runId)!;
|
|
3858
|
+
const stillAnalyzing = () => this.runRepo.get(runId)?.state === 'analyzing';
|
|
3859
|
+
const run = current();
|
|
3094
3860
|
const ticket = this.ticketRepo.get(run.ticket_id)!;
|
|
3095
3861
|
const teamAgentsList = analysis.repos.map((r) => teamAgentFor(ticket, r.name));
|
|
3096
3862
|
const missingLogin = teamAgentsList.find((a) => LOGIN_REQUIRED[a] && !this.settingsRepo.getCredential(a));
|
|
@@ -3108,6 +3874,8 @@ export class Orchestrator {
|
|
|
3108
3874
|
// P0 (plan bond-app-azure-jira): the agent credentials arrive with the team too; every
|
|
3109
3875
|
// bash of the run re-reads them through BASH_ENV.
|
|
3110
3876
|
await this.prepareAgentEnv(run.container_name!);
|
|
3877
|
+
// Issue #4 (P2): the person's Azure session, with the team (M-1), when the ticket asks.
|
|
3878
|
+
await this.injectAzureLogin(run.container_name!, ticket);
|
|
3111
3879
|
// Git with the person's identity and credentials for gru (the analysis is over, M-1).
|
|
3112
3880
|
await this.prepareGit(run.container_name!, ticket, {
|
|
3113
3881
|
repos: [{ dir: HUB_DIR, base: ticket.hub_base || 'main' }, ...analysis.repos.map((r) => ({ dir: `${HUB_DIR}/${r.path}`, base: r.base }))],
|
|
@@ -3215,20 +3983,8 @@ export class Orchestrator {
|
|
|
3215
3983
|
const machine = run.hc_machine || machineNameForRun(run.id);
|
|
3216
3984
|
try {
|
|
3217
3985
|
const terminals = await this.hcClient.getMachineTerminals(machine);
|
|
3218
|
-
const isWaiting = (t: { state: string | null; status: string | null; turn?: number }) =>
|
|
3219
|
-
|
|
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
|
-
};
|
|
3986
|
+
const isWaiting = (t: { state: string | null; status: string | null; turn?: number }) => t.state === 'live' && isTerminalWaiting(t);
|
|
3987
|
+
const isLeader = isLeaderTerminal;
|
|
3232
3988
|
const waitingList = terminals.filter(isWaiting);
|
|
3233
3989
|
if (waitingList.length > 0) {
|
|
3234
3990
|
const target = waitingList.find(isLeader) || waitingList[0];
|
|
@@ -3251,23 +4007,9 @@ export class Orchestrator {
|
|
|
3251
4007
|
agent?: string;
|
|
3252
4008
|
completion_seq?: number;
|
|
3253
4009
|
}>;
|
|
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
|
-
});
|
|
4010
|
+
const waitingList = agents.filter((a) => Boolean(a.pane_id) && isHerdrAgentWaiting(a as Parameters<typeof isHerdrAgentWaiting>[0]));
|
|
3261
4011
|
if (waitingList.length > 0) {
|
|
3262
|
-
const isLeader =
|
|
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
|
-
};
|
|
4012
|
+
const isLeader = isLeaderHerdrAgent;
|
|
3271
4013
|
|
|
3272
4014
|
// M-4: deliver only to the single agent that is waiting (leader first if multiple)
|
|
3273
4015
|
const target = waitingList.find(isLeader) || waitingList[0];
|
|
@@ -3502,11 +4244,43 @@ export class Orchestrator {
|
|
|
3502
4244
|
let stopped = false;
|
|
3503
4245
|
let buffer = '';
|
|
3504
4246
|
|
|
4247
|
+
const writeResult = async (reqId: string, result: Record<string, unknown>) => {
|
|
4248
|
+
if (stopped) return;
|
|
4249
|
+
const resultPath = `/var/run/bond-app/pr-${reqId}.json`;
|
|
4250
|
+
try {
|
|
4251
|
+
await this.dockerClient.injectStdin(
|
|
4252
|
+
containerName,
|
|
4253
|
+
['sh', '-c', `cat > "${resultPath}.tmp" && chown runner:runner "${resultPath}.tmp" && chmod 0600 "${resultPath}.tmp" && mv "${resultPath}.tmp" "${resultPath}"`],
|
|
4254
|
+
JSON.stringify(result),
|
|
4255
|
+
'root'
|
|
4256
|
+
);
|
|
4257
|
+
} catch {
|
|
4258
|
+
// the container may have stopped
|
|
4259
|
+
}
|
|
4260
|
+
};
|
|
4261
|
+
|
|
3505
4262
|
const handleLine = async (rawLine: string) => {
|
|
3506
|
-
|
|
4263
|
+
// `<token> <reqId>` is `bond-app pr`; `<token> <reqId> <base64 json>` a LOOP P3 request.
|
|
4264
|
+
const match = /^([a-f0-9]+)\s+([A-Za-z0-9_-]{1,64})(?:\s+([A-Za-z0-9+/=]{1,8000}))?$/.exec(rawLine.trim());
|
|
3507
4265
|
if (!match) return;
|
|
3508
|
-
const [, providedToken, reqId] = match;
|
|
4266
|
+
const [, providedToken, reqId, payload] = match;
|
|
3509
4267
|
if (!safeCompare(providedToken, token)) return;
|
|
4268
|
+
if (payload) {
|
|
4269
|
+
let req: Record<string, unknown>;
|
|
4270
|
+
try {
|
|
4271
|
+
req = JSON.parse(Buffer.from(payload, 'base64').toString('utf8'));
|
|
4272
|
+
} catch {
|
|
4273
|
+
return;
|
|
4274
|
+
}
|
|
4275
|
+
let out: Record<string, unknown> | null;
|
|
4276
|
+
try {
|
|
4277
|
+
out = await this.handleLoopRequest(runId, req, (r) => writeResult(reqId, r));
|
|
4278
|
+
} catch (err) {
|
|
4279
|
+
out = { ok: false, message: String((err as Error).message || err) };
|
|
4280
|
+
}
|
|
4281
|
+
if (out) await writeResult(reqId, out);
|
|
4282
|
+
return;
|
|
4283
|
+
}
|
|
3510
4284
|
|
|
3511
4285
|
let result: Record<string, unknown>;
|
|
3512
4286
|
try {
|
|
@@ -3693,6 +4467,14 @@ export class Orchestrator {
|
|
|
3693
4467
|
}
|
|
3694
4468
|
}
|
|
3695
4469
|
|
|
4470
|
+
// Issue #4 (P2): «Login de Azure» without a usable session: BLOCKED before launch.
|
|
4471
|
+
const azureProblem = this.azureLoginProblem(ticket);
|
|
4472
|
+
if (azureProblem) {
|
|
4473
|
+
this.setState(run.id, 'queued', 'blocked', azureProblem);
|
|
4474
|
+
this.startingRuns.delete(runId);
|
|
4475
|
+
return this.runRepo.get(run.id)!;
|
|
4476
|
+
}
|
|
4477
|
+
|
|
3696
4478
|
// P2: an agent that needs its own login (agy, claude) without a stored one: BLOCKED before launch
|
|
3697
4479
|
if (LOGIN_REQUIRED[ticket.agent] && !this.settingsRepo.getCredential(ticket.agent)) {
|
|
3698
4480
|
this.setState(run.id, 'queued', 'blocked', LOGIN_REQUIRED[ticket.agent]);
|
|
@@ -3755,74 +4537,8 @@ export class Orchestrator {
|
|
|
3755
4537
|
// P7 / D6-rev (2026-11-25): per-run docker exec FIFO watcher + 0600 token via stdin + CLI
|
|
3756
4538
|
await this.ensureRunPrWatcher(run.id, containerInfo.containerName);
|
|
3757
4539
|
|
|
3758
|
-
const bondAppScript = `#!/bin/sh
|
|
3759
|
-
set -e
|
|
3760
|
-
|
|
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
4540
|
|
|
3798
|
-
|
|
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
|
-
);
|
|
4541
|
+
await this.installBondAppCli(containerInfo.containerName);
|
|
3826
4542
|
|
|
3827
4543
|
// Offline git rewrites for tests (L5), before any clone.
|
|
3828
4544
|
if (!options.skipClone && options.gitInsteadOf) {
|
|
@@ -3909,6 +4625,8 @@ exit 1
|
|
|
3909
4625
|
// another one inside the container (bond team panes), and they all belong to the user.
|
|
3910
4626
|
if (ticket.mode !== 'hub') {
|
|
3911
4627
|
await this.injectCredentials(containerInfo.containerName, this.allConfiguredAgents());
|
|
4628
|
+
// Issue #4 (P2): the person's Azure session, when the ticket asks («Login de Azure»).
|
|
4629
|
+
await this.injectAzureLogin(containerInfo.containerName, ticket);
|
|
3912
4630
|
}
|
|
3913
4631
|
// P0 (plan bond-app-azure-jira): the BASH_ENV script always (the hc core starts with
|
|
3914
4632
|
// it); the agent credentials too, except in a hub before its team starts (M-1).
|
|
@@ -4154,23 +4872,11 @@ exit 1
|
|
|
4154
4872
|
if (!isValidAgent(ticket.agent)) {
|
|
4155
4873
|
throw new ValidationError(`Unsupported agent '${ticket.agent}'`);
|
|
4156
4874
|
}
|
|
4157
|
-
if (ticket.agent
|
|
4158
|
-
//
|
|
4159
|
-
//
|
|
4160
|
-
|
|
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] : [])];
|
|
4875
|
+
if (ticket.agent !== 'pi') {
|
|
4876
|
+
// Unattended in the run's container (LOOP P0: one table for every launch, agent-flags.ts).
|
|
4877
|
+
// agy and copilot take the first message after `-i`, and only with one: a bare `-i`
|
|
4878
|
+
// makes agy print its usage and exit 2.
|
|
4879
|
+
return [ticket.agent, ...unattendedFlags(ticket.agent).before, ...promptArgs(ticket.agent, promptArgv)];
|
|
4174
4880
|
}
|
|
4175
4881
|
const defaultModel = ticket.agent === 'pi' ? this.settingsRepo?.getSetupSelection?.()?.default_model : null;
|
|
4176
4882
|
const model = ticket.agent === 'pi' ? (ticket.model || defaultModel) : null;
|
|
@@ -4360,18 +5066,7 @@ exit 1
|
|
|
4360
5066
|
const defaultModel = ticket.agent === 'pi' ? this.settingsRepo?.getSetupSelection?.()?.default_model : null;
|
|
4361
5067
|
const model = ticket.agent === 'pi' ? (ticket.model || defaultModel) : null;
|
|
4362
5068
|
if (ticket.agent === 'pi' && model) argv.push('--model', model);
|
|
4363
|
-
|
|
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);
|
|
5069
|
+
argv.push(...unattendedFlags(ticket.agent).before, ...promptArgs(ticket.agent, promptArgv));
|
|
4375
5070
|
return argv;
|
|
4376
5071
|
}
|
|
4377
5072
|
|
|
@@ -4916,3 +5611,88 @@ exit 1
|
|
|
4916
5611
|
return this.runRepo.get(runId)!;
|
|
4917
5612
|
}
|
|
4918
5613
|
}
|
|
5614
|
+
|
|
5615
|
+
/**
|
|
5616
|
+
* Issue #3: the agent kind a terminal runs, from its argv (`bond tui --agent X`, a bare
|
|
5617
|
+
* `claude …`, or a `sh -c '… exec pi …'` launch), or null.
|
|
5618
|
+
*/
|
|
5619
|
+
export function agentKindOfArgv(argv: string[] | undefined): SupportedAgent | null {
|
|
5620
|
+
if (!argv?.length) return null;
|
|
5621
|
+
const joined = argv.join(' ');
|
|
5622
|
+
const flag = /--agent\s+([a-z]+)/.exec(joined)?.[1];
|
|
5623
|
+
if (flag && isValidAgent(flag)) return flag;
|
|
5624
|
+
let best: { kind: SupportedAgent; at: number } | null = null;
|
|
5625
|
+
for (const kind of SUPPORTED_AGENTS) {
|
|
5626
|
+
const m = new RegExp(`(^|[\\s/"'])${kind}(?=$|[\\s"'])`).exec(joined);
|
|
5627
|
+
if (m && (!best || m.index < best.at)) best = { kind, at: m.index };
|
|
5628
|
+
}
|
|
5629
|
+
return best?.kind ?? null;
|
|
5630
|
+
}
|
|
5631
|
+
|
|
5632
|
+
/** The run's `bond-app` command (P7 `pr`; LOOP P3 `ask`, `answer`, `loop` via the node CLI). */
|
|
5633
|
+
const BOND_APP_SCRIPT = `#!/bin/sh
|
|
5634
|
+
set -e
|
|
5635
|
+
|
|
5636
|
+
case "$1" in
|
|
5637
|
+
pr) ;;
|
|
5638
|
+
# LOOP P3 (issue #2): the loop's commands go to the node CLI next to this script.
|
|
5639
|
+
ask|answer|loop) exec node /usr/local/lib/bond-app-loop.js "$@" ;;
|
|
5640
|
+
*)
|
|
5641
|
+
echo "bond-app: unknown command '$1'. Available: pr, ask, answer, loop" >&2
|
|
5642
|
+
exit 1
|
|
5643
|
+
;;
|
|
5644
|
+
esac
|
|
5645
|
+
|
|
5646
|
+
if [ "$#" -gt 1 ]; then
|
|
5647
|
+
echo "Error: bond-app pr takes no parameters (repo or branch). It delivers only the current run." >&2
|
|
5648
|
+
exit 1
|
|
5649
|
+
fi
|
|
5650
|
+
|
|
5651
|
+
PR_ENV="/var/run/bond-app/pr.env"
|
|
5652
|
+
FIFO="/var/run/bond-app/pr.fifo"
|
|
5653
|
+
if [ ! -f "$PR_ENV" ]; then
|
|
5654
|
+
echo "Error: bond-app PR channel not configured at $PR_ENV" >&2
|
|
5655
|
+
exit 1
|
|
5656
|
+
fi
|
|
5657
|
+
|
|
5658
|
+
. "$PR_ENV"
|
|
5659
|
+
if [ -z "$BOND_APP_PR_TOKEN" ]; then
|
|
5660
|
+
echo "Error: bond-app PR token missing" >&2
|
|
5661
|
+
exit 1
|
|
5662
|
+
fi
|
|
5663
|
+
|
|
5664
|
+
WAITED_FIFO=0
|
|
5665
|
+
while [ ! -p "$FIFO" ] && [ "$WAITED_FIFO" -lt 10 ]; do
|
|
5666
|
+
sleep 0.2
|
|
5667
|
+
WAITED_FIFO=$((WAITED_FIFO + 1))
|
|
5668
|
+
done
|
|
5669
|
+
if [ ! -p "$FIFO" ]; then
|
|
5670
|
+
echo "Error: bond-app PR FIFO not available at $FIFO" >&2
|
|
5671
|
+
exit 1
|
|
5672
|
+
fi
|
|
5673
|
+
|
|
5674
|
+
REQ_ID="$(date +%s)-$$-$(head -c 6 /dev/urandom | od -An -tx1 | tr -d ' \\n')"
|
|
5675
|
+
RES_FILE="/var/run/bond-app/pr-\${REQ_ID}.json"
|
|
5676
|
+
rm -f "$RES_FILE"
|
|
5677
|
+
|
|
5678
|
+
printf '%s %s\\n' "$BOND_APP_PR_TOKEN" "$REQ_ID" > "$FIFO"
|
|
5679
|
+
|
|
5680
|
+
WAITED=0
|
|
5681
|
+
while [ "$WAITED" -lt 600 ]; do
|
|
5682
|
+
if [ -f "$RES_FILE" ]; then
|
|
5683
|
+
RES=$(cat "$RES_FILE")
|
|
5684
|
+
rm -f "$RES_FILE"
|
|
5685
|
+
echo "$RES"
|
|
5686
|
+
if echo "$RES" | grep -q '"ok":true' && echo "$RES" | grep -q '"pr_url"'; then
|
|
5687
|
+
exit 0
|
|
5688
|
+
else
|
|
5689
|
+
exit 1
|
|
5690
|
+
fi
|
|
5691
|
+
fi
|
|
5692
|
+
sleep 1
|
|
5693
|
+
WAITED=$((WAITED + 1))
|
|
5694
|
+
done
|
|
5695
|
+
|
|
5696
|
+
echo "Error: timed out waiting for bond-app PR response after 600s" >&2
|
|
5697
|
+
exit 1
|
|
5698
|
+
`;
|