@jmanuelcorral/bond-app 0.1.4 → 0.1.6

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.
Files changed (78) hide show
  1. package/README.md +241 -7
  2. package/app/brand/TOKENS.md +5 -5
  3. package/app/layouts/bond.json +10 -14
  4. package/app/mods/bond-agents/api.js +35 -0
  5. package/app/mods/bond-agents/branch.svg +1 -0
  6. package/app/mods/bond-agents/brand.js +53 -2
  7. package/app/mods/bond-agents/config.js +8 -0
  8. package/app/mods/bond-agents/eye-off.svg +1 -0
  9. package/app/mods/bond-agents/eye.svg +1 -0
  10. package/app/mods/bond-agents/main.js +316 -330
  11. package/app/mods/bond-agents/model.js +400 -6
  12. package/app/mods/bond-board/api.js +35 -0
  13. package/app/mods/bond-board/branch.svg +1 -0
  14. package/app/mods/bond-board/brand.js +53 -2
  15. package/app/mods/bond-board/config.js +8 -0
  16. package/app/mods/bond-board/main.js +1054 -366
  17. package/app/mods/bond-board/model.js +138 -17
  18. package/app/mods/bond-pane/close.svg +1 -0
  19. package/app/mods/bond-pane/hide.svg +1 -0
  20. package/app/mods/bond-pane/main.js +103 -0
  21. package/app/mods/bond-pane/mod.json +1 -0
  22. package/app/mods/bond-pane/model.js +18 -0
  23. package/app/mods/bond-pane/split-down.svg +1 -0
  24. package/app/mods/bond-pane/split-right.svg +1 -0
  25. package/app/mods/bond-pane/unzoom.svg +1 -0
  26. package/app/mods/bond-pane/zoom.svg +1 -0
  27. package/app/mods/bond-settings/api.js +35 -0
  28. package/app/mods/bond-settings/brand.js +53 -2
  29. package/app/mods/bond-settings/config.js +8 -0
  30. package/app/mods/bond-settings/main.js +1645 -87
  31. package/app/mods/bond-settings/mod.json +1 -1
  32. package/app/mods/bond-settings/pi-models.js +144 -0
  33. package/app/mods/bond-status/api.js +35 -0
  34. package/app/mods/bond-status/brand.js +53 -2
  35. package/app/mods/bond-status/config.js +8 -0
  36. package/app/mods/bond-status/main.js +37 -15
  37. package/app/mods/bond-status/model.js +19 -1
  38. package/app/mods/bond-tabs/brand.js +53 -2
  39. package/app/mods/bond-tabs/main.js +45 -3
  40. package/app/mods/bond-titlebar/brand.js +53 -2
  41. package/app/mods/bond-titlebar/main.js +115 -55
  42. package/app/mods/bond-titlebar/version.js +3 -0
  43. package/app/themes/bond-dark.json +5 -5
  44. package/app/themes/bond-light.json +5 -5
  45. package/package.json +1 -1
  46. package/runner/Dockerfile +58 -15
  47. package/runner/SPIKE-BOND.md +89 -0
  48. package/runner/build-config/.none +0 -0
  49. package/runner/build-creds/.none +0 -0
  50. package/runner/config.example/README.md +27 -0
  51. package/runner/config.example/pi/models.json +22 -0
  52. package/runner/credentials.example.env +27 -0
  53. package/runner/entrypoint.sh +16 -0
  54. package/runner/setup.sh +927 -0
  55. package/runner/versions.env +61 -0
  56. package/scripts/app-install.ts +64 -1
  57. package/src/cli.ts +53 -3
  58. package/src/config.ts +8 -0
  59. package/src/core/agy-login.ts +682 -0
  60. package/src/core/delivery.ts +3 -1
  61. package/src/core/hub-session.ts +9 -7
  62. package/src/core/orchestrator.ts +1186 -168
  63. package/src/core/repo-host.ts +60 -0
  64. package/src/core/setup.ts +239 -0
  65. package/src/core/watchdog.ts +6 -6
  66. package/src/db/database.ts +55 -1
  67. package/src/db/settings-repo.ts +440 -7
  68. package/src/db/ticket-repo.ts +73 -17
  69. package/src/index.ts +4 -4
  70. package/src/runner/azure-devops-client.ts +163 -0
  71. package/src/runner/docker-client.ts +84 -5
  72. package/src/runner/github-client.ts +146 -0
  73. package/src/runner/hc-client.ts +40 -5
  74. package/src/runner/image-builder.ts +268 -10
  75. package/src/runner/jira-client.ts +368 -0
  76. package/src/runner/tool-catalog.ts +84 -0
  77. package/src/server/app.ts +585 -9
  78. package/src/types.ts +168 -1
@@ -9,10 +9,11 @@ import { EventBus } from '../sse/event-bus.ts';
9
9
  import { DockerClient, type DockerContainerSummary } from '../runner/docker-client.ts';
10
10
  import { Watchdog } from './watchdog.ts';
11
11
  import { CostTracker } from './cost-tracker.ts';
12
- import { HcClient, HcError, machineNameForRun, type HcMachineInfo } from '../runner/hc-client.ts';
12
+ import { HcClient, HcError, machineNameForRun, type HcMachineInfo, type HcTerminalDetails } from '../runner/hc-client.ts';
13
13
  import { validateTransition, InvalidStateTransitionError } from './state-machine.ts';
14
- import { rebuildRunnerImage as rebuildRunnerImageImpl, type RunnerVersions } from '../runner/image-builder.ts';
14
+ import { rebuildRunnerImage as rebuildRunnerImageImpl, runnerRecipeHash, type RunnerBuildOptions, type RunnerVersions } from '../runner/image-builder.ts';
15
15
  import { GitHubClient, parseGitHubRepo } from '../runner/github-client.ts';
16
+ import { JiraClient } from '../runner/jira-client.ts';
16
17
  import {
17
18
  assertHubPushTarget,
18
19
  assertPushTarget,
@@ -28,11 +29,18 @@ import {
28
29
  TREE_SCRIPT,
29
30
  } from './delivery.ts';
30
31
  import { HubMountError, HubSession, proposeUrls } from './hub-session.ts';
32
+ import { AzureDevOpsClient } from '../runner/azure-devops-client.ts';
33
+ import { parseAzureRepoUrl, repoHostOf, repoLabel, validateRepoUrl } from './repo-host.ts';
34
+ import { AgyLoginManager, CLAUDE_LOGIN_SPEC, CODEX_LOGIN_SPEC, COPILOT_LOGIN_SPEC, type AgyLoginDriver } from './agy-login.ts';
35
+ import { buildSetupState } from './setup.ts';
31
36
  import { HUB_DIR, NAME_RE, agentGaps, analysisPrompt, buildAnalysis, fixedGaps, parseAgentAnswer, repoNameFromUrl, teamAgentFor, teamAgents, type HubToml } from './hub.ts';
32
37
  import {
33
38
  validateGitHubUrl,
34
39
  validateGitHubIssueUrl,
35
40
  parseGitHubIssueUrl,
41
+ validateJiraIssueUrl,
42
+ parseJiraIssueUrl,
43
+ normalizeJiraSite,
36
44
  isValidAgent,
37
45
  type HubAnalysis,
38
46
  type HubFix,
@@ -42,6 +50,9 @@ import {
42
50
  type RunState,
43
51
  type FailureReason,
44
52
  type TeamStatusRow,
53
+ type RunTerminal,
54
+ type RunnerImageInfo,
55
+ type SetupState,
45
56
  } from '../types.ts';
46
57
  import type { AppConfig } from '../config.ts';
47
58
 
@@ -98,6 +109,15 @@ export class ValidationError extends Error {
98
109
  * D20: launching needs a GitHub credential (the user's gh session stored from Ajustes) or
99
110
  * an explicit token in the request. The message is shown as is by the launch dialog.
100
111
  */
112
+ /** Plan bond-app-azure-jira P1: a ticket on Azure Repos with no Azure DevOps PAT stored. */
113
+ export class AzureDevOpsCredentialMissingError extends ValidationError {
114
+ code = 'azure_devops_credential_missing';
115
+ constructor() {
116
+ super('No hay credencial de Azure DevOps: añade la organización y el PAT en Ajustes → Azure DevOps antes de lanzar el run');
117
+ this.name = 'AzureDevOpsCredentialMissingError';
118
+ }
119
+ }
120
+
101
121
  export class GitHubCredentialMissingError extends ValidationError {
102
122
  code = 'github_credential_missing';
103
123
  constructor() {
@@ -129,6 +149,65 @@ export interface TestStartRunOptions extends StartRunOptions {
129
149
  gitInsteadOf?: Record<string, string>;
130
150
  }
131
151
 
152
+ /** E5: the notice of a run whose agent exited with a non-zero code (or was closed). */
153
+ /** Agents that need their own login in Ajustes, and the notice of a run without it. */
154
+ export const LOGIN_REQUIRED: Record<string, string> = {
155
+ agy: 'sin sesion agy: haz Login OAuth en Ajustes',
156
+ claude: 'sin sesión claude: haz «Login con Claude» en Ajustes',
157
+ codex: 'sin sesión codex: haz «Login con ChatGPT» en Ajustes → Agentes',
158
+ copilot: 'sin sesión copilot: haz «Login con Copilot» en Ajustes → Agentes',
159
+ };
160
+
161
+ /** The agent says it has no valid session (agy signed out; claude's token missing, expired
162
+ * or revoked). */
163
+ export function signedOutOn(agent: string, screen: string): boolean {
164
+ if (agent === 'agy') return screen.includes('You are currently not signed in');
165
+ if (agent === 'claude') {
166
+ return /Not logged in|Please run \/login|Invalid API key|OAuth token (has expired|has been revoked|revoked)|authentication_error|Failed to authenticate/i.test(screen);
167
+ }
168
+ if (agent === 'codex') {
169
+ // Its welcome screen without a session, or a session it could not refresh.
170
+ return /Sign in with ChatGPT|Please (log|sign) in again|could not be refreshed|refresh token (was )?(already used|revoked|expired)|Not logged in/i.test(screen);
171
+ }
172
+ if (agent === 'copilot') {
173
+ return /Please (run|use) \/login|No authentication information found|not (logged|signed) in to GitHub|Bad credentials|authentication failed/i.test(screen);
174
+ }
175
+ return false;
176
+ }
177
+
178
+ /** A ticket asks for Docker in the run and the runner image does not carry it. */
179
+ export const DOCKER_REQUIRED = 'el ticket pide Docker y la imagen no lo lleva: marca «Docker en el run» en Ajustes → Imagen y reconstruye';
180
+
181
+ /** What AGENT_ENV_SCRIPT holds: it exports every agent-env.d/*.env of the user. */
182
+ export const AGENT_ENV_SCRIPT_BODY = [
183
+ '# bond-app: credenciales para los agentes del run (plan bond-app-azure-jira P0).',
184
+ '# Lo carga el arranque del core de hc (viaCommandFor): lo heredan todas sus terminales.',
185
+ 'for _bond_env in "$HOME"/.config/bond-app/agent-env.d/*.env; do',
186
+ ' [ -r "$_bond_env" ] && . "$_bond_env"',
187
+ 'done',
188
+ 'unset _bond_env',
189
+ '',
190
+ ].join('\n');
191
+
192
+ /**
193
+ * One agent-env file: `export NAME='value'` lines, shell-quoted. Names are upper-case
194
+ * identifiers; values may not carry newlines or NUL (they would break the file).
195
+ */
196
+ export function agentEnvFile(source: string, vars: Record<string, string>): string {
197
+ if (!/^[a-z][a-z0-9-]{0,40}$/.test(source)) throw new ValidationError(`Invalid agent env source '${source}'`);
198
+ const lines = [`# bond-app: ${source} (no editar: se reescribe en cada run)`];
199
+ for (const [name, value] of Object.entries(vars)) {
200
+ if (!/^[A-Z_][A-Z0-9_]{0,63}$/.test(name)) throw new ValidationError(`Invalid variable name '${name}'`);
201
+ if (/[\n\r\0]/.test(value)) throw new ValidationError(`Variable '${name}' cannot contain line breaks`);
202
+ lines.push(`export ${name}='${value.replace(/'/g, `'\\''`)}'`);
203
+ }
204
+ return lines.join('\n') + '\n';
205
+ }
206
+
207
+ export function agentExitedReason(exitCode: number | null | undefined): string {
208
+ return `El agente se cerró (código ${exitCode ?? '?'}): escríbele para relanzarlo o márcalo terminado`;
209
+ }
210
+
132
211
  export class Orchestrator {
133
212
  public ticketRepo: TicketRepository;
134
213
  public runRepo: RunRepository;
@@ -142,6 +221,8 @@ export class Orchestrator {
142
221
  public hcClient: HcClient;
143
222
  // P4: opens the run's pull request with the GitHub REST API (token in the header only).
144
223
  public github: GitHubClient;
224
+ /** Plan bond-app-azure-jira P1: Azure Repos (PR and branches) with the stored PAT. */
225
+ public azure: AzureDevOpsClient = new AzureDevOpsClient();
145
226
 
146
227
  private reconcileTimer: NodeJS.Timeout | null = null;
147
228
  private inFlightTerminations = new Set<string>();
@@ -165,7 +246,18 @@ export class Orchestrator {
165
246
  private missingContainerStrikes = new Map<string, number>();
166
247
  // P2 criterion 7: guard against concurrent image rebuilds.
167
248
  private rebuildInFlight = false;
168
- private rebuildImpl: (image: string, versions?: RunnerVersions) => Promise<void>;
249
+ /** The current or last image build, for Ajustes' progress bar (GET /system/rebuild). */
250
+ private rebuildStatus: {
251
+ running: boolean;
252
+ started_at: string | null;
253
+ finished_at: string | null;
254
+ step: number;
255
+ total: number;
256
+ detail: string;
257
+ ok: boolean | null;
258
+ error: string | null;
259
+ } = { running: false, started_at: null, finished_at: null, step: 0, total: 0, detail: '', ok: null, error: null };
260
+ private rebuildImpl: (image: string, options?: RunnerBuildOptions) => Promise<void>;
169
261
  // P4: deliveries in progress (verify, commit, push, PR), one per run.
170
262
  private deliveries = new Map<string, Promise<Run>>();
171
263
  // P4: a token given explicitly at start (not stored); delivery falls back to the stored one.
@@ -181,6 +273,12 @@ export class Orchestrator {
181
273
  private analysisNotes = new Map<string, string>();
182
274
  // P7: per-run local socket server for 'bond-app pr' channel
183
275
  private runServers = new Map<string, { server: http.Server; socketDir: string }>();
276
+ public agyLoginManager: AgyLoginManager;
277
+ /** Plan bond-app-claude-agente P2: `claude setup-token` in a throwaway container. */
278
+ public claudeLoginManager: AgyLoginManager;
279
+ public codexLoginManager: AgyLoginManager;
280
+ public copilotLoginManager: AgyLoginManager;
281
+ public jira: JiraClient;
184
282
 
185
283
  constructor(
186
284
  ticketRepo: TicketRepository,
@@ -190,11 +288,14 @@ export class Orchestrator {
190
288
  dockerClient: DockerClient,
191
289
  config: AppConfig,
192
290
  // P2 criterion 7: injectable for tests; the real docker build is never run in unit/UI tests.
193
- rebuildImpl: (image: string, versions?: RunnerVersions) => Promise<void> = rebuildRunnerImageImpl,
291
+ rebuildImpl: (image: string, options?: RunnerBuildOptions) => Promise<void> = rebuildRunnerImageImpl,
194
292
  hcClient: HcClient = new HcClient(),
195
- github: GitHubClient = new GitHubClient()
293
+ github: GitHubClient = new GitHubClient(),
294
+ agyLoginDriver?: AgyLoginDriver,
295
+ jira: JiraClient = new JiraClient()
196
296
  ) {
197
297
  this.github = github;
298
+ this.jira = jira;
198
299
  this.rebuildImpl = rebuildImpl;
199
300
  this.hcClient = hcClient;
200
301
  this.ticketRepo = ticketRepo;
@@ -206,6 +307,40 @@ export class Orchestrator {
206
307
  this.watchdog = new Watchdog(runRepo, ticketRepo, config.watchdogIntervalMs);
207
308
  this.watchdog.setOrchestrator(this);
208
309
  this.costTracker = new CostTracker(runRepo, eventBus);
310
+ this.agyLoginManager = new AgyLoginManager({
311
+ runnerImage: config.runnerImage,
312
+ dataDir: config.dataDir,
313
+ driver: agyLoginDriver,
314
+ });
315
+ this.claudeLoginManager = new AgyLoginManager({
316
+ runnerImage: config.runnerImage,
317
+ dataDir: config.dataDir,
318
+ driver: agyLoginDriver,
319
+ spec: CLAUDE_LOGIN_SPEC,
320
+ // The one-year token is the credential: kept like any other, injected per run (D7).
321
+ onToken: (token) => this.settingsRepo.setCredential('claude', token, 'setup-token'),
322
+ });
323
+ // Plan bond-app-codex-copilot: the ChatGPT session and copilot's token, kept like any
324
+ // credential and injected per run by stdin (D7).
325
+ this.codexLoginManager = new AgyLoginManager({
326
+ runnerImage: config.runnerImage,
327
+ dataDir: config.dataDir,
328
+ driver: agyLoginDriver,
329
+ spec: CODEX_LOGIN_SPEC,
330
+ maxDurationMs: 15 * 60 * 1000,
331
+ onToken: (content) => this.settingsRepo.setCredential('codex', content, 'chatgpt'),
332
+ });
333
+ this.copilotLoginManager = new AgyLoginManager({
334
+ runnerImage: config.runnerImage,
335
+ dataDir: config.dataDir,
336
+ driver: agyLoginDriver,
337
+ spec: COPILOT_LOGIN_SPEC,
338
+ maxDurationMs: 15 * 60 * 1000,
339
+ onToken: (content) => this.settingsRepo.setCredential('copilot', content, 'copilot-login'),
340
+ });
341
+ if (this.config.dataDir) {
342
+ this.settingsRepo.setDataDir(this.config.dataDir);
343
+ }
209
344
  }
210
345
 
211
346
  async start(): Promise<void> {
@@ -227,6 +362,10 @@ export class Orchestrator {
227
362
  clearInterval(this.reconcileTimer);
228
363
  this.reconcileTimer = null;
229
364
  }
365
+ await this.agyLoginManager.cancel();
366
+ await this.claudeLoginManager.cancel();
367
+ await this.codexLoginManager.cancel();
368
+ await this.copilotLoginManager.cancel();
230
369
  for (const [, s] of this.runServers.entries()) {
231
370
  try { s.server.close(); } catch {}
232
371
  try { fs.rmSync(s.socketDir, { recursive: true, force: true }); } catch {}
@@ -246,17 +385,16 @@ export class Orchestrator {
246
385
  case 'pi':
247
386
  return '/home/runner/.pi/agent/models.json';
248
387
  case 'claude':
249
- return '/home/runner/.claude/config.json';
388
+ // The `claude setup-token` token; the image's claude wrapper reads it (decision 2026-11-23).
389
+ return '/home/runner/.claude/oauth-token';
250
390
  case 'codex':
251
- return '/home/runner/.codex/config.json';
252
- case 'opencode':
253
- return '/home/runner/.opencode/config.json';
391
+ // The ChatGPT session of `codex login` (plan bond-app-codex-copilot).
392
+ return '/home/runner/.codex/auth.json';
254
393
  case 'copilot':
394
+ // `copilot login`'s token file (authTokens); its settings.json is baked, never overwritten.
255
395
  return '/home/runner/.copilot/config.json';
256
- case 'crush':
257
- return '/home/runner/.crush/config.json';
258
396
  case 'agy':
259
- return '/home/runner/.gemini/antigravity-cli/config.json';
397
+ return '/home/runner/.gemini/antigravity-cli/antigravity-oauth-token';
260
398
  }
261
399
  }
262
400
 
@@ -264,9 +402,182 @@ export class Orchestrator {
264
402
  * Write each agent's stored credential into the container as runner (0600), under
265
403
  * `home` (the runner's HOME, or the hub agent's throwaway one; review M-1).
266
404
  */
405
+ /** Every agent with a stored credential (same user, same D7 regime). Runs inject all
406
+ * of them because an agent inside a run may delegate to another (bond team in-container). */
407
+ allConfiguredAgents(): string[] {
408
+ return this.settingsRepo.listSummaries()
409
+ .filter((s) => s.configured)
410
+ .map((s) => s.agent);
411
+ }
412
+
413
+ /**
414
+ * Plan bond-app-azure-jira P0: credentials meant for the agents of the run (their MCP
415
+ * servers, skills, delegates), as environment variables. Each source becomes
416
+ * `~/.config/bond-app/agent-env.d/<name>.env` (0600, by stdin) and the script BASH_ENV
417
+ * points at (AGENT_ENV_SCRIPT, the hc core starts with it) exports them all. Never
418
+ * through `docker -e`, arguments or the image (D7).
419
+ */
420
+ agentEnvSources(): Array<{ name: string; vars: Record<string, string> }> {
421
+ const sources: Array<{ name: string; vars: Record<string, string> }> = [];
422
+ // P1: the Azure DevOps PAT, for `az devops`/`az repos` and the user's PR skills.
423
+ const azure = this.settingsRepo.getAzureDevOpsCredential?.();
424
+ if (azure && azure.agents_enabled) {
425
+ sources.push({
426
+ name: 'azure-devops',
427
+ vars: { AZURE_DEVOPS_ORG_URL: azure.org_url, AZURE_DEVOPS_PAT: azure.pat, AZURE_DEVOPS_EXT_PAT: azure.pat },
428
+ });
429
+ }
430
+ // P2: the Jira API token, for the Jira MCP and skills.
431
+ const jiraCred = this.settingsRepo.getJiraCredential();
432
+ if (jiraCred && jiraCred.agents_enabled && jiraCred.site && jiraCred.email && jiraCred.token) {
433
+ sources.push({
434
+ name: 'jira',
435
+ vars: {
436
+ JIRA_URL: jiraCred.site,
437
+ JIRA_USERNAME: jiraCred.email,
438
+ JIRA_API_TOKEN: jiraCred.token,
439
+ },
440
+ });
441
+ }
442
+ return sources;
443
+ }
444
+
445
+ /** The org's Azure repos, cached a few minutes: the repo search asks on every keystroke. */
446
+ private azureReposCache: { org: string; at: number; repos: Array<{ url: string; project: string; name: string; default_branch?: string }> } | null = null;
447
+
448
+ /**
449
+ * Alta de ticket (Qué · Dónde · Quién): the repos to offer for «Dónde», in this order —
450
+ * favorites (★), recent ones (repos of the user's tickets, newest first), the Azure
451
+ * organization's repos and, with a query, GitHub's search. Each with its host, a label
452
+ * and the default branch when known; `q` filters by words (any order). A source that
453
+ * fails reports its error and the rest still answer.
454
+ */
455
+ async suggestRepos(q: string): Promise<{
456
+ repos: Array<{ url: string; label: string; host: 'github' | 'azure'; base?: string; favorite: boolean; recent: boolean; source: 'favorite' | 'recent' | 'azure' | 'github' }>;
457
+ errors: Record<string, string>;
458
+ }> {
459
+ const words = q.toLowerCase().split(/\s+/).filter(Boolean);
460
+ const matches = (text: string) => words.every((w) => text.toLowerCase().includes(w));
461
+ const key = (url: string) => url.trim().replace(/\.git$/, '').replace(/\/+$/, '').toLowerCase();
462
+ const favorites = this.settingsRepo.getFavoriteRepos();
463
+ const favKeys = new Set(favorites.map(key));
464
+ const recents: string[] = [];
465
+ for (const t of [...this.ticketRepo.list()].sort((a, b) => String(b.updated_at).localeCompare(String(a.updated_at)))) {
466
+ if (t.mode === 'hub' || !t.repo_url || !validateRepoUrl(t.repo_url)) continue;
467
+ if (!recents.some((r) => key(r) === key(t.repo_url))) recents.push(t.repo_url);
468
+ if (recents.length >= 10) break;
469
+ }
470
+ const recentKeys = new Set(recents.map(key));
471
+ const out = new Map<string, { url: string; label: string; host: 'github' | 'azure'; base?: string; favorite: boolean; recent: boolean; source: 'favorite' | 'recent' | 'azure' | 'github' }>();
472
+ const add = (url: string, source: 'favorite' | 'recent' | 'azure' | 'github', base?: string) => {
473
+ const host = repoHostOf(url);
474
+ if (!host) return;
475
+ const k = key(url);
476
+ const prev = out.get(k);
477
+ if (prev) {
478
+ if (base && !prev.base) prev.base = base;
479
+ return;
480
+ }
481
+ const label = repoLabel(url);
482
+ if (!matches(`${label} ${url}`)) return;
483
+ out.set(k, { url, label, host, ...(base ? { base } : {}), favorite: favKeys.has(k), recent: recentKeys.has(k), source });
484
+ };
485
+ for (const u of favorites) add(u, 'favorite');
486
+ for (const u of recents) add(u, 'recent');
487
+ const errors: Record<string, string> = {};
488
+ const azure = this.settingsRepo.getAzureDevOpsCredential();
489
+ if (azure) {
490
+ try {
491
+ if (!this.azureReposCache || this.azureReposCache.org !== azure.org_url || Date.now() - this.azureReposCache.at > 5 * 60_000) {
492
+ this.azureReposCache = { org: azure.org_url, at: Date.now(), repos: await this.azure.listRepositories(azure.pat, azure.org_url) };
493
+ }
494
+ for (const r of this.azureReposCache.repos) add(r.url, 'azure', r.default_branch);
495
+ } catch (err) {
496
+ errors.azure = (err as Error).message;
497
+ }
498
+ }
499
+ const gh = this.settingsRepo.getGitHubToken();
500
+ if (gh && q.trim().length >= 2) {
501
+ try {
502
+ for (const r of await this.github.searchRepos(gh, q.trim())) add(`${r.url}`, 'github', r.default_branch);
503
+ } catch (err) {
504
+ errors.github = (err as Error).message;
505
+ }
506
+ }
507
+ return { repos: [...out.values()].slice(0, 60), errors };
508
+ }
509
+
510
+ /**
511
+ * Plan bond-app-azure-jira P1: what bond-app needs to act on a repo's host — the token
512
+ * for its clone and push (stdin) and the API calls of the delivery and the ticket's
513
+ * deletion — whether the repo is on GitHub or on Azure Repos. Null token = no credential.
514
+ */
515
+ repoAccessFor(repoUrl: string, runId?: string): {
516
+ host: 'github' | 'azure';
517
+ label: string;
518
+ token: string | null;
519
+ missing: () => ValidationError;
520
+ branchExists: (branch: string) => Promise<boolean>;
521
+ branchMerged: (branch: string, base: string) => Promise<boolean>;
522
+ deleteBranch: (branch: string) => Promise<boolean>;
523
+ openPullRequest: (pr: { head: string; base: string; title: string; body: string }) => Promise<{ number: number; url: string; created: boolean }>;
524
+ } {
525
+ const label = repoLabel(repoUrl);
526
+ if (repoHostOf(repoUrl) === 'azure') {
527
+ const cred = this.settingsRepo.getAzureDevOpsCredential();
528
+ const ref = parseAzureRepoUrl(repoUrl)!;
529
+ // A PAT is per organization: a repo of another one gets none (it would leak).
530
+ const token = cred && cred.org_url.toLowerCase() === ref.orgUrl.toLowerCase() ? cred.pat : null;
531
+ return {
532
+ host: 'azure',
533
+ label,
534
+ token,
535
+ missing: () => new AzureDevOpsCredentialMissingError(),
536
+ branchExists: (b) => this.azure.remoteBranchExists(token!, repoUrl, b),
537
+ branchMerged: (b, base) => this.azure.isBranchMerged(token!, repoUrl, b, base),
538
+ deleteBranch: (b) => this.azure.deleteRemoteBranch(token!, repoUrl, b),
539
+ openPullRequest: (pr) => this.azure.openPullRequest(token!, repoUrl, pr),
540
+ };
541
+ }
542
+ const token = (runId ? this.runTokens.get(runId) : undefined) || this.settingsRepo.getGitHubToken() || null;
543
+ const gh = () => parseGitHubRepo(repoUrl);
544
+ return {
545
+ host: 'github',
546
+ label,
547
+ token,
548
+ missing: () => new GitHubCredentialMissingError(),
549
+ branchExists: (b) => this.github.remoteBranchExists(token!, gh().owner, gh().repo, b),
550
+ branchMerged: (b, base) => this.github.isBranchMerged(token!, gh().owner, gh().repo, b, base),
551
+ deleteBranch: (b) => this.github.deleteRemoteBranch(token!, gh().owner, gh().repo, b),
552
+ openPullRequest: (pr) => this.github.openPullRequest(token!, repoUrl, pr),
553
+ };
554
+ }
555
+
556
+ async prepareAgentEnv(containerName: string, home = '/home/runner', withSources = true): Promise<string[]> {
557
+ const write = async (dest: string, content: string) => {
558
+ const res = await this.dockerClient.injectStdin(
559
+ containerName,
560
+ ['sh', '-c', 'umask 077; mkdir -p "$(dirname "$1")" && cat > "$1"', '--', dest],
561
+ content,
562
+ 'runner'
563
+ );
564
+ if (res.exitCode !== 0) throw new Error(`Agent env injection failed with code ${res.exitCode}: ${res.stderr}`);
565
+ };
566
+ await write(`${home}/.config/bond-app/agent-env.sh`, AGENT_ENV_SCRIPT_BODY);
567
+ const written: string[] = [];
568
+ if (!withSources) return written;
569
+ for (const source of this.agentEnvSources()) {
570
+ const dest = `${home}/.config/bond-app/agent-env.d/${source.name}.env`;
571
+ await write(dest, agentEnvFile(source.name, source.vars));
572
+ written.push(dest);
573
+ }
574
+ return written;
575
+ }
576
+
267
577
  async injectCredentials(containerName: string, agents: string[], home = '/home/runner'): Promise<string[]> {
268
578
  const written: string[] = [];
269
- for (const agent of new Set(agents)) {
579
+ const wanted = new Set(agents);
580
+ for (const agent of wanted) {
270
581
  const credential = this.settingsRepo.getCredential(agent);
271
582
  if (!credential) continue;
272
583
  const destPath = home + this.getAgentConfigPath(agent).slice('/home/runner'.length);
@@ -281,6 +592,26 @@ export class Orchestrator {
281
592
  }
282
593
  written.push(destPath);
283
594
  }
595
+ // W-P4: prompt-suggestions config for supi, written next to pi's models.json when a
596
+ // suggestions model is stored (null = «sin sugerencias» writes nothing). The supi
597
+ // package itself comes with the runner image (image plan P2); until then the file is
598
+ // simply inert, so this never depends on the image's contents.
599
+ if (wanted.has('pi')) {
600
+ const model = this.settingsRepo.getSetupSelection().suggestions_model;
601
+ if (model) {
602
+ const destPath = `${home}/.pi/agent/supi/config.json`;
603
+ const res = await this.dockerClient.injectStdin(
604
+ containerName,
605
+ ['sh', '-c', 'umask 077; mkdir -p "$(dirname "$1")" && cat > "$1"', '--', destPath],
606
+ JSON.stringify({ promptSuggestions: { model } }, null, 2),
607
+ 'runner'
608
+ );
609
+ if (res.exitCode !== 0) {
610
+ throw new Error(`Supi suggestions config failed with code ${res.exitCode}: ${res.stderr}`);
611
+ }
612
+ written.push(destPath);
613
+ }
614
+ }
284
615
  return written;
285
616
  }
286
617
 
@@ -755,8 +1086,10 @@ export class Orchestrator {
755
1086
 
756
1087
  /**
757
1088
  * P4 criterion 6 (P3 debt M-3): a `running` run whose agent terminal finished leaves
758
- * `running` at once: exit code 0 starts the verification and delivery; any other code
759
- * fails the run with `agent_exited`. Without hc (or with the machine lost, which M-1
1089
+ * `running` at once: exit code 0 finishes it; any other code (a crash, or its tab closed
1090
+ * in herdr-app, which ends the terminal) moves it to `waiting` with a notice, keeping the
1091
+ * container and its work: a message (nudge) starts a new agent terminal (plan
1092
+ * bond-app-pestanas-paneles, E5). Without hc (or with the machine lost, which M-1
760
1093
  * fixes) nothing is decided: the next sweep looks again.
761
1094
  */
762
1095
  async checkAgentExits(): Promise<string[]> {
@@ -782,12 +1115,13 @@ export class Orchestrator {
782
1115
  // The run transitions to 'finished'. Container and session stay alive.
783
1116
  if (this.setState(r.id, 'running', 'finished', null, { finished_at: new Date().toISOString() })) {
784
1117
  this.ticketRepo.updateStatus(r.ticket_id, 'finished');
1118
+ await this.syncAgyTokenFromContainer(r);
785
1119
  }
786
1120
  } else {
787
- try {
788
- await this.terminateRun(r.id, 'failed', 'agent_exited');
789
- } catch {
790
- // retried on the next sweep
1121
+ const reason = agentExitedReason(t.exit_code);
1122
+ if (this.setState(r.id, 'running', 'waiting', reason)) {
1123
+ this.ticketRepo.updateStatus(r.ticket_id, 'waiting');
1124
+ this.agentEvent(latest, 'agent.waiting', { reason, exit_code: t.exit_code });
791
1125
  }
792
1126
  }
793
1127
  }
@@ -816,6 +1150,7 @@ export class Orchestrator {
816
1150
 
817
1151
  let isBlocked = false;
818
1152
  let waitingAgentName: string | null = null;
1153
+ let notSignedInBlocked = false;
819
1154
 
820
1155
  if (ticket.mode === 'hub') {
821
1156
  if (ticket.team_engine === 'herdr') {
@@ -849,7 +1184,7 @@ export class Orchestrator {
849
1184
  }
850
1185
  const cleanCwd = a.cwd?.replace(/\/+$/, '');
851
1186
  if (cleanCwd === '/workspace/hub') return true;
852
- if (a.pane_id === 'w1:p1' && (!a.name || a.name === 'pi' || a.name === 'agent')) return true;
1187
+ if (a.pane_id === 'w1:p1' && (!a.name || a.name === 'pi' || a.name === 'agent' || a.name === 'gru')) return true;
853
1188
  return false;
854
1189
  };
855
1190
  const waiting = agents.filter(isWaiting);
@@ -922,11 +1257,24 @@ export class Orchestrator {
922
1257
  if (!r.hc_terminal) continue;
923
1258
  try {
924
1259
  const t = await this.hcClient.getTerminal(r.hc_terminal);
1260
+ // E5: an agent that exited leaves the run waiting (checkAgentExits) until a nudge
1261
+ // starts a new one; it must not bounce back to running here.
1262
+ if (t.state === 'finished') continue;
925
1263
  if (t.state === 'live') {
926
- const isWaiting = t.status === 'blocked' || ((t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0);
927
- if (isWaiting) {
928
- isBlocked = true;
929
- waitingAgentName = ticket.agent || 'agente';
1264
+ if (LOGIN_REQUIRED[ticket.agent]) {
1265
+ try {
1266
+ const screen = await this.hcClient.readTerminal(r.hc_terminal);
1267
+ if (signedOutOn(ticket.agent, screen)) {
1268
+ notSignedInBlocked = true;
1269
+ }
1270
+ } catch {}
1271
+ }
1272
+ if (!notSignedInBlocked) {
1273
+ const isWaiting = t.status === 'blocked' || ((t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0);
1274
+ if (isWaiting) {
1275
+ isBlocked = true;
1276
+ waitingAgentName = ticket.agent || 'agente';
1277
+ }
930
1278
  }
931
1279
  }
932
1280
  } catch {
@@ -937,6 +1285,16 @@ export class Orchestrator {
937
1285
  const latest = this.runRepo.get(r.id);
938
1286
  if (!latest || (latest.state !== 'running' && latest.state !== 'waiting')) continue;
939
1287
 
1288
+ if (notSignedInBlocked) {
1289
+ const reason = LOGIN_REQUIRED[ticket.agent] ?? LOGIN_REQUIRED.agy;
1290
+ if (this.setState(r.id, latest.state, 'blocked', reason)) {
1291
+ this.ticketRepo.updateStatus(r.ticket_id, 'blocked');
1292
+ this.agentEvent(latest, 'agent.blocked', { reason });
1293
+ transitioned.push(r.id);
1294
+ continue;
1295
+ }
1296
+ }
1297
+
940
1298
  if (isBlocked) {
941
1299
  const reason = `Esperando respuesta: ${waitingAgentName}`;
942
1300
  if (latest.state === 'running') {
@@ -1108,15 +1466,21 @@ export class Orchestrator {
1108
1466
  this.agentEvent(run, 'verification.passed', { commands: ticket.verify_commands.length });
1109
1467
 
1110
1468
  // 2. Commit what the agent left on the run's branch and bundle it.
1469
+ // The commit's author: the GitHub login (noreply address) or, on Azure Repos, the
1470
+ // account the PAT belongs to (P1, plan bond-app-azure-jira).
1111
1471
  const login = this.settingsRepo.getGitHubSummary().login;
1472
+ const azureAccount = repoHostOf(ticket.repo_url) === 'azure' ? this.settingsRepo.getAzureDevOpsSummary().account : undefined;
1473
+ const azureMatch = azureAccount ? /^(.*?)\s*<([^<>\s]+@[^<>\s]+)>$/.exec(azureAccount) : null;
1474
+ const authorName = azureMatch ? azureMatch[1] : azureAccount || login || 'bond-app';
1475
+ const authorEmail = azureMatch ? azureMatch[2] : !azureAccount && login ? `${login}@users.noreply.github.com` : 'bond-app@localhost';
1112
1476
  const commit = await this.dockerClient.exec(
1113
1477
  ctr,
1114
1478
  [
1115
1479
  'sh', '-c', COMMIT_SCRIPT, 'bond-commit',
1116
1480
  ticket.target_branch,
1117
1481
  `${ticket.title}\n\nbond-app run ${runId} (ticket ${ticket.id})`,
1118
- login || 'bond-app',
1119
- login ? `${login}@users.noreply.github.com` : 'bond-app@localhost',
1482
+ authorName,
1483
+ authorEmail,
1120
1484
  '/workspace/repo',
1121
1485
  BUNDLE_PATH,
1122
1486
  expectedTree,
@@ -1136,8 +1500,9 @@ export class Orchestrator {
1136
1500
  // on the exact object pushed: it is the committed head, adds commits to the real base
1137
1501
  // from GitHub and changes nothing under .github/workflows (review HIGH-1).
1138
1502
  // D2: push retries up to 3 times with growing backoff; exhausted -> blocked.
1139
- const token = this.runTokens.get(runId) || this.settingsRepo.getGitHubToken();
1140
- if (!token) throw new GitHubCredentialMissingError();
1503
+ const access = this.repoAccessFor(ticket.repo_url, runId);
1504
+ const token = access.token;
1505
+ if (!token) throw access.missing();
1141
1506
  const shouldRetryPush = (err: unknown) => {
1142
1507
  const msg = String((err as Error).message || err);
1143
1508
  return !msg.includes('nothing to deliver') && !msg.includes('.github/workflows') && !msg.includes('does not match the committed head');
@@ -1172,7 +1537,7 @@ export class Orchestrator {
1172
1537
  const pr = await this.retryDeliveryStep(
1173
1538
  'pr',
1174
1539
  run,
1175
- () => this.github.openPullRequest(token, ticket.repo_url, {
1540
+ () => access.openPullRequest({
1176
1541
  head: ticket.target_branch,
1177
1542
  base: ticket.base_branch,
1178
1543
  title: ticket.title,
@@ -1285,7 +1650,7 @@ export class Orchestrator {
1285
1650
  const n = Number(/\/t(\d+)$/.exec(run.hc_terminal || '')?.[1] || '1') + 1;
1286
1651
  const terminal = await this.hcClient.startTerminal(
1287
1652
  run.hc_machine,
1288
- this.agentCommandFor(ticket, message),
1653
+ await this.resolveAgentCommand(run.container_name, ticket, message),
1289
1654
  '/workspace/repo',
1290
1655
  `agent-${n}`
1291
1656
  );
@@ -1341,107 +1706,258 @@ export class Orchestrator {
1341
1706
  this.ticketRepo.updateStatus(run.ticket_id, 'finished');
1342
1707
  const updated = this.runRepo.get(runId)!;
1343
1708
  this.agentEvent(updated, 'agent.finished', { manual: true });
1709
+ await this.syncAgyTokenFromContainer(updated);
1344
1710
  return updated;
1345
1711
  }
1346
1712
 
1347
1713
  /**
1348
- * P7 (criterion 8 & Ampliación): get the team status for a run.
1714
+ * P2: After agy run finishes, re-read token from container and sync to dataDir if changed.
1715
+ * Best-effort: catches and ignores all errors.
1716
+ */
1717
+ private async syncAgyTokenFromContainer(run: Run): Promise<void> {
1718
+ try {
1719
+ const ticket = this.ticketRepo.get(run.ticket_id);
1720
+ if (!ticket) return;
1721
+ const isAgy =
1722
+ ticket.agent === 'agy' ||
1723
+ (ticket.repos && ticket.repos.some((r: any) => teamAgentFor(ticket, r.name) === 'agy'));
1724
+ if (!isAgy || !run.container_name) return;
1725
+
1726
+ const containerTokenPath = this.getAgentConfigPath('agy');
1727
+ const execRes = await this.dockerClient.exec(run.container_name, ['cat', containerTokenPath], 'runner');
1728
+ if (execRes.exitCode !== 0 || !execRes.stdout.trim()) return;
1729
+
1730
+ const newContent = execRes.stdout.trim();
1731
+ try {
1732
+ JSON.parse(newContent);
1733
+ } catch {
1734
+ return;
1735
+ }
1736
+
1737
+ const currentCred = this.settingsRepo.getCredential('agy');
1738
+ if (!currentCred || currentCred.config_json.trim() !== newContent) {
1739
+ this.settingsRepo.setCredential('agy', newContent);
1740
+ }
1741
+ } catch {
1742
+ // Best-effort without propagating errors
1743
+ }
1744
+ }
1745
+
1746
+ /**
1747
+ * P2: Build the orchestrator / leader row for a run, used in getRunTeamStatus.
1748
+ * Guarantees that any run (hub or single, running or waiting or queued,
1749
+ * modern or legacy bare agent) returns an orchestrator row.
1750
+ */
1751
+ private async buildOrchestratorRow(
1752
+ run: Run,
1753
+ ticket: Ticket | null,
1754
+ terminalInfo?: HcTerminalDetails | null
1755
+ ): Promise<TeamStatusRow> {
1756
+ const isHub = ticket?.mode === 'hub';
1757
+ const agentKind = ticket?.agent || 'pi';
1758
+
1759
+ let t = terminalInfo ?? null;
1760
+ if (!t && run.hc_terminal) {
1761
+ try {
1762
+ t = await this.hcClient.getTerminal(run.hc_terminal);
1763
+ } catch {}
1764
+ }
1765
+ if (!t && run.hc_machine) {
1766
+ try {
1767
+ const terminals = await this.hcClient.getMachineTerminals(run.hc_machine);
1768
+ t =
1769
+ terminals.find(
1770
+ (x) =>
1771
+ x.name === 'hub leader' ||
1772
+ x.name === 'orquestador' ||
1773
+ x.address?.endsWith('/t1')
1774
+ ) ||
1775
+ terminals[0] ||
1776
+ null;
1777
+ } catch {}
1778
+ }
1779
+
1780
+ const isGenericAgent = (name?: string) => !name || name === 'agent' || name === 'gru' || /^t\d+$/.test(name);
1781
+
1782
+ let listedAgent: string | undefined;
1783
+ if (isGenericAgent(t?.agent) && (run.hc_machine || run.hc_terminal || t?.address)) {
1784
+ try {
1785
+ const listed = await this.hcClient.listTerminals(run.hc_machine || undefined);
1786
+ const match = listed.find(
1787
+ (x) => x.address === (t?.address || run.hc_terminal) || x.address?.endsWith('/t1')
1788
+ );
1789
+ if (match?.agent && !isGenericAgent(match.agent)) {
1790
+ listedAgent = match.agent;
1791
+ }
1792
+ } catch {}
1793
+ }
1794
+
1795
+ if (t && listedAgent && isGenericAgent(t.agent)) {
1796
+ t.agent = listedAgent;
1797
+ }
1798
+
1799
+ const detectedAgent =
1800
+ t?.agent && !isGenericAgent(t.agent)
1801
+ ? t.agent
1802
+ : listedAgent && !isGenericAgent(listedAgent)
1803
+ ? listedAgent
1804
+ : ticket?.agent || 'pi';
1805
+ const agentName = isHub ? 'hub leader' : detectedAgent;
1806
+ const pane =
1807
+ t?.address ||
1808
+ run.hc_terminal ||
1809
+ (run.hc_machine ? `${run.hc_machine}/t1` : undefined);
1810
+
1811
+ let state = 'trabajando';
1812
+ let status = 'working';
1813
+ let question: string | undefined = undefined;
1814
+
1815
+ if (run.state === 'queued' || run.state === 'ready') {
1816
+ state = 'arrancando';
1817
+ status = 'arrancando';
1818
+ } else if (run.state === 'waiting') {
1819
+ state = 'bloqueado';
1820
+ status = 'en espera';
1821
+ question = run.failure_reason || (agentName ? `Esperando respuesta: ${agentName}` : undefined);
1822
+ } else if (t) {
1823
+ const isWaiting =
1824
+ t.status === 'blocked' ||
1825
+ ((t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0);
1826
+
1827
+ if (isWaiting) {
1828
+ state = 'bloqueado';
1829
+ status = 'en espera';
1830
+ question = run.failure_reason || (agentName ? `Esperando respuesta: ${agentName}` : undefined);
1831
+ } else if (t.status === 'working') {
1832
+ state = 'trabajando';
1833
+ status = 'working';
1834
+ } else if (t.status === 'idle') {
1835
+ state = 'idle';
1836
+ status = 'idle';
1837
+ } else if (t.status === 'live') {
1838
+ state = 'live';
1839
+ status = 'live';
1840
+ } else if (t.status) {
1841
+ state = t.status;
1842
+ status = t.status;
1843
+ } else if (t.state === 'live') {
1844
+ // Live terminal without agent status hook (e.g. p6 with bond tui, or bare pi)
1845
+ state = 'live';
1846
+ status = 'live';
1847
+ } else {
1848
+ state = 'sin estado';
1849
+ status = 'sin estado';
1850
+ }
1851
+ } else {
1852
+ if (run.state === 'running') {
1853
+ state = 'arrancando';
1854
+ status = 'arrancando';
1855
+ } else if (run.state === 'finished') {
1856
+ state = 'lista';
1857
+ status = 'finished';
1858
+ } else if (run.state === 'failed') {
1859
+ state = 'bloqueado';
1860
+ status = 'failed';
1861
+ } else {
1862
+ state = 'sin estado';
1863
+ status = 'sin estado';
1864
+ }
1865
+ }
1866
+
1867
+ return {
1868
+ branch: ticket?.target_branch || '',
1869
+ path: isHub ? '/workspace/hub' : '/workspace/repo',
1870
+ repo: 'orquestador',
1871
+ state,
1872
+ ahead: 0,
1873
+ files: [],
1874
+ dirty: 0,
1875
+ integrated: false,
1876
+ agent: {
1877
+ name: agentName,
1878
+ kind: agentKind,
1879
+ status,
1880
+ question,
1881
+ pane,
1882
+ terminal: pane,
1883
+ },
1884
+ };
1885
+ }
1886
+
1887
+ /**
1888
+ * P7 (criterion 8 & Ampliación) & P2: get the team status for a run.
1349
1889
  * For hub runs, includes the hub orchestrator agent (pi in hub root) at the top,
1350
1890
  * labelled as «hub leader» (orquestador), merged with repo agents from `bond team status --json`.
1891
+ * For single runs, returns the orchestrator agent row.
1351
1892
  */
1352
1893
  async getRunTeamStatus(runId: string): Promise<TeamStatusRow[]> {
1353
1894
  const run = this.runRepo.get(runId);
1354
1895
  if (!run) throw new ValidationError(`Run '${runId}' not found`);
1355
- if (!run.container_name) return [];
1356
1896
 
1357
1897
  const ticket = this.ticketRepo.get(run.ticket_id);
1358
1898
  const isHub = ticket?.mode === 'hub';
1359
1899
 
1900
+ if (!run.container_name) {
1901
+ return [await this.buildOrchestratorRow(run, ticket)];
1902
+ }
1903
+
1360
1904
  // P9: HC engine - get status directly from hc, NO docker exec
1361
- if (isHub && ticket?.team_engine !== 'herdr') {
1362
- try {
1363
- const machine = run.hc_machine || machineNameForRun(run.id);
1364
- const terminals = await this.hcClient.getMachineTerminals(machine);
1905
+ if (ticket?.team_engine !== 'herdr') {
1906
+ if (isHub) {
1907
+ try {
1908
+ const machine = run.hc_machine || machineNameForRun(run.id);
1909
+ const terminals = await this.hcClient.getMachineTerminals(machine);
1365
1910
 
1366
- const isLeader = (t: { name?: string; cwd?: string; address?: string }) => {
1367
- if (t.name === 'hub leader' || t.name === 'hub-leader' || t.name === 'leader' || t.name === 'orquestador') {
1368
- return true;
1369
- }
1370
- const cleanCwd = t.cwd?.replace(/\/+$/, '');
1371
- if (cleanCwd === '/workspace/hub') return true;
1372
- if (t.address?.endsWith('/t1')) return true;
1373
- return false;
1374
- };
1911
+ const isLeader = (t: { name?: string; cwd?: string; address?: string }) => {
1912
+ if (t.name === 'hub leader' || t.name === 'hub-leader' || t.name === 'leader' || t.name === 'orquestador') {
1913
+ return true;
1914
+ }
1915
+ const cleanCwd = t.cwd?.replace(/\/+$/, '');
1916
+ if (cleanCwd === '/workspace/hub') return true;
1917
+ if (t.address?.endsWith('/t1')) return true;
1918
+ return false;
1919
+ };
1375
1920
 
1376
- const rows: TeamStatusRow[] = [];
1377
- const leader = terminals.find(isLeader);
1378
- if (leader) {
1379
- let leaderState = 'trabajando';
1380
- let leaderStatus = 'working';
1381
- if (leader.status === 'blocked') {
1382
- leaderState = 'bloqueado';
1383
- leaderStatus = 'blocked';
1384
- } else if ((leader.status === 'idle' || leader.status === 'done') && (leader.turn ?? 0) > 0) {
1385
- leaderState = 'bloqueado';
1386
- leaderStatus = 'en espera';
1387
- } else if (leader.status === 'working') {
1388
- leaderState = 'trabajando';
1389
- leaderStatus = 'working';
1390
- } else {
1391
- leaderState = 'trabajando';
1392
- leaderStatus = leader.status || 'working';
1921
+ const rows: TeamStatusRow[] = [];
1922
+ const leader = terminals.find(isLeader);
1923
+ if (leader) {
1924
+ rows.push(await this.buildOrchestratorRow(run, ticket, leader));
1393
1925
  }
1394
1926
 
1395
- rows.push({
1396
- branch: ticket?.target_branch || '',
1397
- path: '/workspace/hub',
1398
- repo: 'orquestador',
1399
- state: leaderState,
1400
- ahead: 0,
1401
- files: [],
1402
- dirty: 0,
1403
- integrated: false,
1404
- agent: {
1405
- name: 'hub leader',
1406
- kind: ticket?.agent || 'pi',
1407
- status: leaderStatus,
1408
- pane: leader.address || `${machine}/t1`,
1409
- terminal: leader.address || `${machine}/t1`,
1410
- },
1411
- });
1412
- }
1413
-
1414
- const repoRows: TeamStatusRow[] = terminals
1415
- .filter((t) => !isLeader(t))
1416
- .map((t) => {
1417
- const repoName = t.labels?.['bond.repo']?.replace(/^repos\//, '') || t.name || 'agente';
1418
- const branch = t.labels?.['bond.branch'] || ticket?.target_branch || '';
1419
- let state = 'trabajando';
1420
- if (t.status === 'blocked') state = 'bloqueado';
1421
- else if ((t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0) state = 'lista';
1422
- else if (t.status === 'working') state = 'trabajando';
1423
- return {
1424
- branch,
1425
- path: t.cwd || '',
1426
- repo: repoName,
1427
- state,
1428
- ahead: 0,
1429
- files: [],
1430
- dirty: 0,
1431
- integrated: false,
1432
- agent: {
1433
- name: t.name || repoName,
1434
- kind: t.agent || ticket?.agent || 'pi',
1435
- status: t.status || 'unknown',
1436
- pane: t.address,
1437
- terminal: t.address,
1438
- },
1439
- };
1440
- });
1927
+ const repoRows: TeamStatusRow[] = terminals
1928
+ .filter((t) => !isLeader(t))
1929
+ .map((t) => {
1930
+ const repoName = t.labels?.['bond.repo']?.replace(/^repos\//, '') || t.name || 'agente';
1931
+ const branch = t.labels?.['bond.branch'] || ticket?.target_branch || '';
1932
+ let state = 'trabajando';
1933
+ if (t.status === 'blocked') state = 'bloqueado';
1934
+ else if ((t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0) state = 'lista';
1935
+ else if (t.status === 'working') state = 'trabajando';
1936
+ return {
1937
+ branch,
1938
+ path: t.cwd || '',
1939
+ repo: repoName,
1940
+ state,
1941
+ ahead: 0,
1942
+ files: [],
1943
+ dirty: 0,
1944
+ integrated: false,
1945
+ agent: {
1946
+ name: t.name || repoName,
1947
+ kind: t.agent || ticket?.agent || 'pi',
1948
+ status: t.status || 'unknown',
1949
+ pane: t.address,
1950
+ terminal: t.address,
1951
+ },
1952
+ };
1953
+ });
1441
1954
 
1442
- return [...rows, ...repoRows];
1443
- } catch {
1444
- return [];
1955
+ return [...rows, ...repoRows];
1956
+ } catch {
1957
+ return [await this.buildOrchestratorRow(run, ticket)];
1958
+ }
1959
+ } else {
1960
+ return [await this.buildOrchestratorRow(run, ticket)];
1445
1961
  }
1446
1962
  }
1447
1963
 
@@ -1478,7 +1994,7 @@ export class Orchestrator {
1478
1994
  }
1479
1995
  const cleanCwd = a.cwd?.replace(/\/+$/, '');
1480
1996
  if (cleanCwd === '/workspace/hub') return true;
1481
- if (a.pane_id === 'w1:p1' && (!a.name || a.name === 'pi' || a.name === 'agent')) return true;
1997
+ if (a.pane_id === 'w1:p1' && (!a.name || a.name === 'pi' || a.name === 'agent' || a.name === 'gru')) return true;
1482
1998
  return false;
1483
1999
  };
1484
2000
 
@@ -1567,10 +2083,71 @@ export class Orchestrator {
1567
2083
  r.agent?.name !== 'hub leader'
1568
2084
  ),
1569
2085
  ];
2086
+ } else if (rows.length === 0) {
2087
+ rows = [await this.buildOrchestratorRow(run, ticket)];
1570
2088
  }
1571
2089
 
1572
2090
  return rows;
1573
2091
  } catch {
2092
+ return [await this.buildOrchestratorRow(run, ticket)];
2093
+ }
2094
+ }
2095
+
2096
+ /**
2097
+ * P4: Proxy hc ls for the run's machine, returning live terminals with agent, state,
2098
+ * turn, and where (cwd). Returns an empty list if machine is down or unreachable without breaking.
2099
+ */
2100
+ async getRunTerminals(runId: string): Promise<RunTerminal[]> {
2101
+ const run = this.runRepo.get(runId);
2102
+ if (!run) throw new ValidationError(`Run '${runId}' not found`);
2103
+
2104
+ const machine = run.hc_machine || (run.container_name ? machineNameForRun(run.id) : null);
2105
+ if (!machine || !this.hcClient) {
2106
+ return [];
2107
+ }
2108
+
2109
+ try {
2110
+ const listed = await this.hcClient.listTerminals(machine);
2111
+ const ticket = this.ticketRepo.get(run.ticket_id);
2112
+ const isLeaderTerminal = (t: { address?: string; name?: string }) =>
2113
+ t.address?.endsWith('/t1') || t.name === 'gru' || t.name === 'agent' || t.name === 'hub leader';
2114
+
2115
+ // Accept only live terminals: exit_code must be null/undefined, state not dead/exited/closed/inactive
2116
+ const live = (listed || []).filter((t) => {
2117
+ if (t.exit_code !== null && t.exit_code !== undefined) return false;
2118
+ if (t.state && t.state !== 'live') return false;
2119
+ return true;
2120
+ });
2121
+
2122
+ return live.map((t) => {
2123
+ let agent = t.agent;
2124
+ // The orchestrator's terminal is named gru (agent in older runs): a name, not a program.
2125
+ if (!agent || agent === 'agent' || agent === 'gru' || /^t\d+$/.test(agent)) {
2126
+ if (t.name && t.name !== 'agent' && t.name !== 'gru' && !/^t\d+$/.test(t.name)) {
2127
+ agent = t.name;
2128
+ } else if (isLeaderTerminal(t)) {
2129
+ agent = ticket?.mode === 'hub' ? 'hub leader' : (ticket?.agent || 'pi');
2130
+ } else {
2131
+ agent = t.name || 'agent';
2132
+ }
2133
+ }
2134
+
2135
+ const cwd = t.cwd || '';
2136
+ return {
2137
+ address: t.address,
2138
+ name: t.name || t.address.split('/').pop() || 'agent',
2139
+ agent,
2140
+ state: t.state || 'live',
2141
+ status: t.status ?? null,
2142
+ turn: typeof t.turn === 'number' ? t.turn : 0,
2143
+ where: cwd,
2144
+ cwd,
2145
+ labels: t.labels,
2146
+ exit_code: t.exit_code ?? null,
2147
+ };
2148
+ });
2149
+ } catch (err) {
2150
+ console.warn(`[bond-app] Warning: unable to list terminals for run '${runId}' on machine '${machine}':`, err);
1574
2151
  return [];
1575
2152
  }
1576
2153
  }
@@ -1593,8 +2170,9 @@ export class Orchestrator {
1593
2170
  assertPushTarget(ticket, repoUrl, branch);
1594
2171
  if (!/^[0-9a-f]{40}$/.test(expectedSha)) throw new Error('Invalid expected head sha');
1595
2172
  if (!run.container_name) throw new Error('The run has no container');
1596
- const secret = token || this.runTokens.get(runId) || this.settingsRepo.getGitHubToken();
1597
- if (!secret) throw new GitHubCredentialMissingError();
2173
+ const access = this.repoAccessFor(repoUrl, runId);
2174
+ const secret = token || access.token;
2175
+ if (!secret) throw access.missing();
1598
2176
  return this.pushBundle(run, repoUrl, branch, BUNDLE_PATH, expectedSha, ticket.base_branch, secret);
1599
2177
  }
1600
2178
 
@@ -2011,8 +2589,10 @@ export class Orchestrator {
2011
2589
  if (cmd) return [...cmd];
2012
2590
  // Hub agent runs read-only pi in print mode regardless of the ticket's agent (P3 criterion 5)
2013
2591
  const argv = ['pi', '-p', '--no-session', '--no-approve', '--tools', 'read,grep,find,ls'];
2014
- // Review L-4 / M-4: pass model only when ticket.agent is pi
2015
- if (ticket.agent === 'pi' && ticket.model && /^[A-Za-z0-9_./:@-]{1,120}$/.test(ticket.model)) argv.push('--model', ticket.model);
2592
+ // Review L-4 / M-4: pass model only when ticket.agent is pi; default_model applies if ticket has no model (D-M1)
2593
+ const defaultModel = ticket.agent === 'pi' ? this.settingsRepo?.getSetupSelection?.()?.default_model : null;
2594
+ const model = ticket.agent === 'pi' ? (ticket.model || defaultModel) : null;
2595
+ if (model && /^[A-Za-z0-9_./:@-]{1,120}$/.test(model)) argv.push('--model', model);
2016
2596
  return argv;
2017
2597
  }
2018
2598
 
@@ -2045,9 +2625,22 @@ export class Orchestrator {
2045
2625
  }
2046
2626
  // The hub covers the story: the team, one agent per repo, on the ticket's branch.
2047
2627
  const ticket = this.ticketRepo.get(run.ticket_id)!;
2628
+ const teamAgentsList = analysis.repos.map((r) => teamAgentFor(ticket, r.name));
2629
+ const missingLogin = teamAgentsList.find((a) => LOGIN_REQUIRED[a] && !this.settingsRepo.getCredential(a));
2630
+ if (missingLogin) {
2631
+ this.setState(runId, 'analyzing', 'blocked', LOGIN_REQUIRED[missingLogin]);
2632
+ return current();
2633
+ }
2048
2634
  try {
2049
2635
  // Review M-1: the team's credentials go in only now, after the analysis.
2050
- await this.injectCredentials(run.container_name!, analysis.repos.map((r) => teamAgentFor(ticket, r.name)));
2636
+ // A team member may delegate to another configured agent in-container, so every
2637
+ // configured credential goes in (same user, D7), not just the team's own agents.
2638
+ await this.injectCredentials(run.container_name!, [
2639
+ ...new Set([...teamAgentsList, ...this.allConfiguredAgents()]),
2640
+ ]);
2641
+ // P0 (plan bond-app-azure-jira): the agent credentials arrive with the team too; every
2642
+ // bash of the run re-reads them through BASH_ENV.
2643
+ await this.prepareAgentEnv(run.container_name!);
2051
2644
  if (!stillAnalyzing()) return current();
2052
2645
  const session = this.hubSessionOf(run);
2053
2646
  // Review L-2: a restart during the launch left the team open: keep it, do not relaunch.
@@ -2064,6 +2657,7 @@ export class Orchestrator {
2064
2657
  if (!reused) {
2065
2658
  const terminal = await session.launchTeam(this.hcClient, run.hc_machine!, ticket, analysis.repos, {
2066
2659
  onTerminal: (address) => this.runRepo.update(runId, { hc_terminal: address }),
2660
+ defaultModel: this.settingsRepo?.getSetupSelection?.()?.default_model,
2067
2661
  });
2068
2662
  this.runRepo.update(runId, { hc_terminal: terminal });
2069
2663
  } else {
@@ -2195,7 +2789,7 @@ export class Orchestrator {
2195
2789
  }
2196
2790
  const cleanCwd = a.cwd?.replace(/\/+$/, '');
2197
2791
  if (cleanCwd === '/workspace/hub') return true;
2198
- if (a.pane_id === 'w1:p1' && (!a.name || a.name === 'pi' || a.name === 'agent')) return true;
2792
+ if (a.pane_id === 'w1:p1' && (!a.name || a.name === 'pi' || a.name === 'agent' || a.name === 'gru')) return true;
2199
2793
  return false;
2200
2794
  };
2201
2795
 
@@ -2434,15 +3028,20 @@ export class Orchestrator {
2434
3028
  // D20: an explicit token in the request wins; else the stored GitHub credential (the
2435
3029
  // user's gh session); without either the launch is refused (N4). It still reaches the
2436
3030
  // container only on stdin (D8).
3031
+ // P1 (plan bond-app-azure-jira): the clone token is the one of the repo's host — the
3032
+ // GitHub token as always, or the Azure DevOps PAT for an Azure Repos ticket.
3033
+ const onAzure = ticket.mode !== 'hub' && repoHostOf(ticket.repo_url) === 'azure';
2437
3034
  const githubToken = options.skipClone
2438
3035
  ? undefined
2439
- : options.githubToken || this.settingsRepo.getGitHubToken() || undefined;
3036
+ : onAzure
3037
+ ? this.repoAccessFor(ticket.repo_url).token || undefined
3038
+ : options.githubToken || this.settingsRepo.getGitHubToken() || undefined;
2440
3039
  if (!options.skipClone) {
2441
3040
  if (!githubToken) {
2442
- throw new GitHubCredentialMissingError();
3041
+ throw onAzure ? new AzureDevOpsCredentialMissingError() : new GitHubCredentialMissingError();
2443
3042
  }
2444
- if (options.githubToken) this.runTokens.set(runId, options.githubToken);
2445
- if (!validateGitHubUrl(ticket.repo_url)) {
3043
+ if (options.githubToken && !onAzure) this.runTokens.set(runId, options.githubToken);
3044
+ if (!(ticket.mode === 'hub' ? validateGitHubUrl(ticket.repo_url) : validateRepoUrl(ticket.repo_url))) {
2446
3045
  throw new ValidationError(`Invalid repo_url '${ticket.repo_url}'`);
2447
3046
  }
2448
3047
  } else if (ticket.mode === 'hub') {
@@ -2464,30 +3063,91 @@ export class Orchestrator {
2464
3063
 
2465
3064
  this.startingRuns.add(runId);
2466
3065
 
2467
- // P7: Registration with linked GitHub issue URL (read on host with gh session, never in container)
3066
+ // P7 / P2: Registration with linked GitHub or Jira issue URL (read on host with session/credential, never in container)
2468
3067
  if (ticket.issue_url) {
2469
- if (!validateGitHubIssueUrl(ticket.issue_url)) {
3068
+ const isGh = validateGitHubIssueUrl(ticket.issue_url);
3069
+ const isJira = validateJiraIssueUrl(ticket.issue_url);
3070
+ if (!isGh && !isJira) {
2470
3071
  this.setState(run.id, 'queued', 'blocked', 'invalid_issue_url');
2471
3072
  this.startingRuns.delete(runId);
2472
3073
  return this.runRepo.get(run.id)!;
2473
3074
  }
2474
- const { owner, repo, issueNumber } = parseGitHubIssueUrl(ticket.issue_url);
2475
- const token = githubToken || this.settingsRepo.getGitHubToken() || '';
3075
+ if (isGh) {
3076
+ const { owner, repo, issueNumber } = parseGitHubIssueUrl(ticket.issue_url);
3077
+ // La historia solo se inyecta si el ticket no trae ya una (check del alta
3078
+ // <<Llevar el cuerpo de la issue>>): desmarcado = story vacía = sin re-fetch.
3079
+ // Solo re-fetch si no hay historia alguna (ticket antiguo o URL manual: null). Un ""
3080
+ // explícito significa «cuerpo desmarcado a propósito»: no se fetchea ni se inyecta.
3081
+ if (ticket.story === null || ticket.story === undefined) {
3082
+ const token = githubToken || this.settingsRepo.getGitHubToken() || '';
3083
+ try {
3084
+ const issue = await this.github.getIssue(token, owner, repo, issueNumber);
3085
+ const updated = this.ticketRepo.update(ticket.id, {
3086
+ story: issue.title + (issue.body ? '\n\n' + issue.body : ''),
3087
+ title: ticket.title || issue.title,
3088
+ });
3089
+ if (updated) ticket = updated;
3090
+ } catch (err) {
3091
+ const msg = String((err as Error).message || err);
3092
+ this.setState(run.id, 'queued', 'blocked', `issue_inaccessible: ${msg}`);
3093
+ this.startingRuns.delete(runId);
3094
+ return this.runRepo.get(run.id)!;
3095
+ }
3096
+ }
3097
+ } else if (isJira) {
3098
+ const { site, issueKey } = parseJiraIssueUrl(ticket.issue_url);
3099
+ const cred = this.settingsRepo.getJiraCredential();
3100
+ // P2 review: the stored token never travels to a site other than the configured
3101
+ // one (both normalized). A mismatch means the linked issue belongs to another
3102
+ // Jira Cloud site: block instead of sending credentials there.
3103
+ if (cred && normalizeJiraSite(cred.site) !== normalizeJiraSite(site)) {
3104
+ this.setState(run.id, 'queued', 'blocked', 'issue_inaccessible: jira_site_mismatch');
3105
+ this.startingRuns.delete(runId);
3106
+ return this.runRepo.get(run.id)!;
3107
+ }
3108
+ if (ticket.story === null || ticket.story === undefined) {
3109
+ if (!cred) {
3110
+ this.setState(run.id, 'queued', 'blocked', 'issue_inaccessible: jira_not_configured');
3111
+ this.startingRuns.delete(runId);
3112
+ return this.runRepo.get(run.id)!;
3113
+ }
3114
+ try {
3115
+ const issue = await this.jira.getIssue(site, cred.email, cred.token, issueKey);
3116
+ const updated = this.ticketRepo.update(ticket.id, {
3117
+ story: issue.summary + (issue.description ? '\n\n' + issue.description : ''),
3118
+ title: ticket.title || issue.summary,
3119
+ });
3120
+ if (updated) ticket = updated;
3121
+ } catch (err) {
3122
+ const msg = String((err as Error).message || err);
3123
+ this.setState(run.id, 'queued', 'blocked', `issue_inaccessible: ${msg}`);
3124
+ this.startingRuns.delete(runId);
3125
+ return this.runRepo.get(run.id)!;
3126
+ }
3127
+ }
3128
+ }
3129
+ }
3130
+
3131
+ // P4 (plan bond-app-ajustes-imagen): «Docker en el run» needs the image's docker group.
3132
+ if (ticket.docker === true) {
3133
+ let tools: string[] | undefined;
2476
3134
  try {
2477
- const issue = await this.github.getIssue(token, owner, repo, issueNumber);
2478
- const updated = this.ticketRepo.update(ticket.id, {
2479
- story: issue.title + (issue.body ? '\n\n' + issue.body : ''),
2480
- title: ticket.title || issue.title,
2481
- });
2482
- if (updated) ticket = updated;
2483
- } catch (err) {
2484
- const msg = String((err as Error).message || err);
2485
- this.setState(run.id, 'queued', 'blocked', `issue_inaccessible: ${msg}`);
3135
+ tools = (await this.dockerClient.inspectRunnerImage(this.config.runnerImage)).tools;
3136
+ } catch {}
3137
+ if (tools && !tools.includes('docker')) {
3138
+ this.setState(run.id, 'queued', 'blocked', DOCKER_REQUIRED);
2486
3139
  this.startingRuns.delete(runId);
2487
3140
  return this.runRepo.get(run.id)!;
2488
3141
  }
2489
3142
  }
2490
3143
 
3144
+ // P2: an agent that needs its own login (agy, claude) without a stored one: BLOCKED before launch
3145
+ if (LOGIN_REQUIRED[ticket.agent] && !this.settingsRepo.getCredential(ticket.agent)) {
3146
+ this.setState(run.id, 'queued', 'blocked', LOGIN_REQUIRED[ticket.agent]);
3147
+ this.startingRuns.delete(runId);
3148
+ return this.runRepo.get(run.id)!;
3149
+ }
3150
+
2491
3151
  const assertQueued = () => {
2492
3152
  const current = this.runRepo.get(runId);
2493
3153
  if (!current || current.state !== 'queued') {
@@ -2524,6 +3184,7 @@ export class Orchestrator {
2524
3184
  memory: this.config.memory,
2525
3185
  pidsLimit: this.config.pidsLimit,
2526
3186
  extraMounts,
3187
+ docker: ticket.docker === true,
2527
3188
  });
2528
3189
 
2529
3190
  containerName = containerInfo.containerName;
@@ -2665,9 +3326,14 @@ fi
2665
3326
 
2666
3327
  // 5. Inject Agent credentials (D7, M7, L6). P5 review M-1: a hub run gets them only
2667
3328
  // when its team starts, after the analysis (the hub agent reads untrusted content).
3329
+ // All configured credentials go into every run: the ticket's agent may delegate to
3330
+ // another one inside the container (bond team panes), and they all belong to the user.
2668
3331
  if (ticket.mode !== 'hub') {
2669
- await this.injectCredentials(containerInfo.containerName, [ticket.agent]);
3332
+ await this.injectCredentials(containerInfo.containerName, this.allConfiguredAgents());
2670
3333
  }
3334
+ // P0 (plan bond-app-azure-jira): the BASH_ENV script always (the hc core starts with
3335
+ // it); the agent credentials too, except in a hub before its team starts (M-1).
3336
+ await this.prepareAgentEnv(containerInfo.containerName, '/home/runner', ticket.mode !== 'hub');
2671
3337
 
2672
3338
  assertQueued();
2673
3339
 
@@ -2704,8 +3370,14 @@ fi
2704
3370
  return this.runRepo.get(run.id)!;
2705
3371
  }
2706
3372
 
3373
+ if (!options.skipClone) {
3374
+ await this.bondifyRepo(containerInfo.containerName, ticket, run.id);
3375
+ }
3376
+
3377
+ assertQueued();
3378
+
2707
3379
  const agentCwd = options.skipClone ? '/workspace' : '/workspace/repo';
2708
- const hcTerminal = await this.hcClient.startTerminal(hcMachine, this.agentCommandFor(ticket), agentCwd);
3380
+ const hcTerminal = await this.hcClient.startTerminal(hcMachine, await this.resolveAgentCommand(containerInfo.containerName, ticket), agentCwd);
2709
3381
  this.runRepo.update(run.id, { hc_terminal: hcTerminal });
2710
3382
  await this.hcClient.assertTerminalAlive(hcTerminal);
2711
3383
 
@@ -2766,10 +3438,17 @@ fi
2766
3438
  ? 'validation_error'
2767
3439
  : startError instanceof HubMountError
2768
3440
  ? 'hub_mount_failed'
2769
- : 'container_error';
3441
+ : startError instanceof HcError && startError.kind === 'agent_exited'
3442
+ ? 'agent_exited'
3443
+ : 'container_error';
2770
3444
  if (startError instanceof HubMountError) {
2771
3445
  this.agentEvent(latest, 'hub.mount_failed', { error: startError.message.slice(0, 300) });
2772
3446
  }
3447
+ // The start error used to be lost (only the launch dialog saw it): keep it as an
3448
+ // event and in the orchestrator's log, so a failed run says why.
3449
+ const message = startError instanceof Error ? startError.message : String(startError);
3450
+ this.agentEvent(latest, 'run.start_failed', { reason: failureReason, error: message.slice(0, 500) });
3451
+ console.error(`[bond-app] run ${runId} failed to start (${failureReason}): ${message}`);
2773
3452
  const { updated } = this.runRepo.updateStateConditionally(
2774
3453
  runId,
2775
3454
  oldState,
@@ -2813,13 +3492,252 @@ fi
2813
3492
  }
2814
3493
  const story = [ticket.story ?? '', ticket.prompt ?? ''].filter((s) => s.trim()).join('\n\n');
2815
3494
  const prompt = (promptOverride ?? story).trim();
2816
- // P4: the ticket's model for pi (`--model provider/id`), e.g. llamaswap/flash-halogen.
2817
- if (ticket.agent === 'pi' && ticket.model) {
2818
- return prompt ? ['pi', '--model', ticket.model, prompt] : ['pi', '--model', ticket.model];
3495
+ // P4 & D-M1: the ticket's model for pi (`--model provider/id`), or default_model if ticket has none.
3496
+ const defaultModel = ticket.agent === 'pi' ? this.settingsRepo?.getSetupSelection?.()?.default_model : null;
3497
+ const model = ticket.agent === 'pi' ? (ticket.model || defaultModel) : null;
3498
+ if (ticket.agent === 'pi' && model) {
3499
+ return prompt ? ['pi', '--model', model, prompt] : ['pi', '--model', model];
2819
3500
  }
2820
3501
  return prompt ? [ticket.agent, prompt] : [ticket.agent];
2821
3502
  }
2822
3503
 
3504
+ /**
3505
+ * Workaround (herdr 0.9.3, reportado upstream): `agent.start` falla si un elemento del
3506
+ * argv del agente contiene `\n`, y bond se queda en la shell sin agente. Un prompt
3507
+ * multilínea nunca viaja como argumento: para pi se escribe a TASK_FILE en el contenedor
3508
+ * y el agente arranca con `@fichero` + una instrucción de una línea; otros agentes
3509
+ * reciben el prompt con los saltos colapsados a espacios (mejor esfuerzo). Los prompts
3510
+ * de una línea viajan literales como siempre.
3511
+ */
3512
+ static readonly TASK_FILE = '/home/runner/.bond-task.md';
3513
+
3514
+ private async writeTaskFile(containerName: string, prompt: string): Promise<boolean> {
3515
+ try {
3516
+ const res = await this.dockerClient.injectStdin(
3517
+ containerName,
3518
+ ['sh', '-c', `cat > ${Orchestrator.TASK_FILE}`],
3519
+ prompt
3520
+ );
3521
+ return res.exitCode === 0;
3522
+ } catch {
3523
+ return false;
3524
+ }
3525
+ }
3526
+
3527
+ /** Elementos del argv con el prompt inicial, garantizados sin `\n`. */
3528
+ async promptArgvFor(
3529
+ containerName: string | null | undefined,
3530
+ ticket: Ticket,
3531
+ promptOverride?: string
3532
+ ): Promise<string[]> {
3533
+ const story = [ticket.story ?? '', ticket.prompt ?? ''].filter((s) => s.trim()).join('\n\n');
3534
+ const prompt = (promptOverride ?? story).trim();
3535
+ if (!prompt) return [];
3536
+ if (!prompt.includes('\n')) return [prompt];
3537
+ if (ticket.agent === 'pi' && containerName && (await this.writeTaskFile(containerName, prompt))) {
3538
+ return [`@${Orchestrator.TASK_FILE}`, 'Trabaja la tarea del ticket adjunta en el fichero.'];
3539
+ }
3540
+ return [prompt.replace(/\s*\n\s*/g, ' ')];
3541
+ }
3542
+
3543
+ /** Comando pelado (sin bond) a partir de los elementos de prompt ya resueltos. */
3544
+ bareAgentCommand(ticket: Ticket, promptArgv: string[]): string[] {
3545
+ if (this.config.agentCommand && this.config.agentCommand.length > 0) {
3546
+ return [...this.config.agentCommand];
3547
+ }
3548
+ if (!isValidAgent(ticket.agent)) {
3549
+ throw new ValidationError(`Unsupported agent '${ticket.agent}'`);
3550
+ }
3551
+ if (ticket.agent === 'agy') {
3552
+ // `-i` takes the first message: without one (a ticket with no story nor prompt) agy
3553
+ // prints its usage and exits 2, and the run died as container_error right at start.
3554
+ return ['agy', '--dangerously-skip-permissions', ...(promptArgv.length ? ['-i', ...promptArgv] : [])];
3555
+ }
3556
+ if (ticket.agent === 'claude') {
3557
+ // Unattended in the run's container, as agy (runs are `runner`, never root).
3558
+ return ['claude', '--dangerously-skip-permissions', ...promptArgv];
3559
+ }
3560
+ if (ticket.agent === 'codex') {
3561
+ // Interactive TUI with the ticket as its first message; the container is the sandbox.
3562
+ // --dangerously-bypass-hook-trust: bond's agent-state hook would stop it at «Hooks need review».
3563
+ return ['codex', '--dangerously-bypass-approvals-and-sandbox', '--dangerously-bypass-hook-trust', ...promptArgv];
3564
+ }
3565
+ if (ticket.agent === 'copilot') {
3566
+ // `-i` starts the interactive session with a first message (as agy, only with one).
3567
+ return ['copilot', '--yolo', ...(promptArgv.length ? ['-i', ...promptArgv] : [])];
3568
+ }
3569
+ const defaultModel = ticket.agent === 'pi' ? this.settingsRepo?.getSetupSelection?.()?.default_model : null;
3570
+ const model = ticket.agent === 'pi' ? (ticket.model || defaultModel) : null;
3571
+ const head = ticket.agent === 'pi' && model ? [ticket.agent, '--model', model] : [ticket.agent];
3572
+ return [...head, ...promptArgv];
3573
+ }
3574
+
3575
+ /**
3576
+ * P4 (D-U): Auto-bondify repository if it lacks .bond/bond.toml.
3577
+ * If config.runnerLauncher === 'bond' and ticket.bondify !== false:
3578
+ * Probes `command -v bond >/dev/null 2>&1 && [ ! -f /workspace/repo/.bond/bond.toml ]`.
3579
+ * If true, runs in /workspace/repo `bond init --yes --agents <ticket.agent>`, then commits
3580
+ * the MINIMAL bondification à la bond-hub: only `.bond/bond.toml` (and `AGENTS.md` when bond
3581
+ * init created or modified it). The runtime output of bond init (`.agents/`, `.pi/`, ...)
3582
+ * stays on disk for the agent but is appended to `.git/info/exclude` so neither this commit
3583
+ * nor the agent's own `git add -A` ever carries it into the PR.
3584
+ * Emits agentEvent on completion or failure.
3585
+ *
3586
+ * Pi non-interactive trust: /workspace is already trusted in /home/runner/.pi/agent/trust.json
3587
+ * (baked into the runner image in runner/Dockerfile via runner/pi-trust.json). Because pi and
3588
+ * bond match the nearest ancestor directory when checking trust, any path inside /workspace/repo
3589
+ * inherits project trust automatically without user prompts or confirmation dialogs.
3590
+ *
3591
+ * If .bond/bond.toml already exists, does nothing.
3592
+ * If ticket.bondify === false, does not probe at all.
3593
+ * If bond init or commit fails, logs and records an event, but continues without throwing.
3594
+ */
3595
+ async bondifyRepo(
3596
+ containerName: string | null | undefined,
3597
+ ticket: Ticket,
3598
+ runId: string
3599
+ ): Promise<boolean> {
3600
+ if (this.config.runnerLauncher !== 'bond' || ticket.bondify === false || !containerName) {
3601
+ return false;
3602
+ }
3603
+
3604
+ try {
3605
+ const probe = await this.dockerClient.exec(
3606
+ containerName,
3607
+ ['sh', '-c', 'command -v bond >/dev/null 2>&1 && [ ! -f /workspace/repo/.bond/bond.toml ]'],
3608
+ 'runner',
3609
+ 15000
3610
+ );
3611
+ if (probe.exitCode !== 0) {
3612
+ return false;
3613
+ }
3614
+
3615
+ const initRes = await this.dockerClient.exec(
3616
+ containerName,
3617
+ ['sh', '-c', `cd /workspace/repo && bond init --yes --agents ${ticket.agent}`],
3618
+ 'runner',
3619
+ 30000
3620
+ );
3621
+ if (initRes.exitCode !== 0) {
3622
+ if (this.eventBus) {
3623
+ const run = this.runRepo?.get?.(runId);
3624
+ if (run) {
3625
+ this.agentEvent(run, 'bond.init_failed', { exitCode: initRes.exitCode, stderr: initRes.stderr });
3626
+ } else {
3627
+ this.eventBus.publish(runId, ticket.id, 'agent.event', {
3628
+ run_id: runId,
3629
+ ticket_id: ticket.id,
3630
+ event: 'bond.init_failed',
3631
+ exitCode: initRes.exitCode,
3632
+ stderr: initRes.stderr,
3633
+ });
3634
+ }
3635
+ }
3636
+ return false;
3637
+ }
3638
+
3639
+ const commitRes = await this.dockerClient.exec(
3640
+ containerName,
3641
+ [
3642
+ 'sh',
3643
+ '-c',
3644
+ 'cd /workspace/repo && printf "%s\\n" /.agents/ /.pi/ /.claude/ /.codex/ >> .git/info/exclude'
3645
+ + ' && git add .bond/bond.toml'
3646
+ + ' && { git add AGENTS.md 2>/dev/null || true; }'
3647
+ + ' && { git diff --cached --quiet || git -c user.name=bond-app -c user.email=bond-app@localhost commit -q -m "chore: bond init"; }',
3648
+ ],
3649
+ 'runner',
3650
+ 15000
3651
+ );
3652
+ if (commitRes.exitCode !== 0) {
3653
+ if (this.eventBus) {
3654
+ const run = this.runRepo?.get?.(runId);
3655
+ if (run) {
3656
+ this.agentEvent(run, 'bond.commit_failed', { exitCode: commitRes.exitCode, stderr: commitRes.stderr });
3657
+ } else {
3658
+ this.eventBus.publish(runId, ticket.id, 'agent.event', {
3659
+ run_id: runId,
3660
+ ticket_id: ticket.id,
3661
+ event: 'bond.commit_failed',
3662
+ exitCode: commitRes.exitCode,
3663
+ stderr: commitRes.stderr,
3664
+ });
3665
+ }
3666
+ }
3667
+ return false;
3668
+ }
3669
+
3670
+ if (this.eventBus) {
3671
+ const run = this.runRepo?.get?.(runId);
3672
+ if (run) {
3673
+ this.agentEvent(run, 'bond.init_done', { agent: ticket.agent, commit: 'chore: bond init' });
3674
+ } else {
3675
+ this.eventBus.publish(runId, ticket.id, 'agent.event', {
3676
+ run_id: runId,
3677
+ ticket_id: ticket.id,
3678
+ event: 'bond.init_done',
3679
+ agent: ticket.agent,
3680
+ commit: 'chore: bond init',
3681
+ });
3682
+ }
3683
+ }
3684
+ return true;
3685
+ } catch {
3686
+ return false;
3687
+ }
3688
+ }
3689
+
3690
+ /**
3691
+ * D-G (image plan): the launch command is `bond tui --agent <agente>` - bond is the
3692
+ * harness (skills, AGENTS.md, sync, decisions, the rich agent bar); the ticket prompt
3693
+ * travels after `--` so it reaches the agent as its first message (runner/SPIKE-BOND.md).
3694
+ * Falls back to the bare launcher (agentCommandFor) when runner_launcher is "pi", an
3695
+ * explicit BOND_APP_AGENT_COMMAND wins, the image has no bond with `tui`, or the clone
3696
+ * is not a bond repo - there bond would stop to offer `bond init`.
3697
+ */
3698
+ async resolveAgentCommand(
3699
+ containerName: string | null | undefined,
3700
+ ticket: Ticket,
3701
+ promptOverride?: string
3702
+ ): Promise<string[]> {
3703
+ // Workaround herdr: el argv nunca lleva '\n' (ver promptArgvFor); se resuelve antes
3704
+ // porque escribir el fichero de tarea necesita el contenedor.
3705
+ const promptArgv = await this.promptArgvFor(containerName, ticket, promptOverride);
3706
+ if (this.config.runnerLauncher !== 'bond' || this.config.agentCommand || !containerName) {
3707
+ return this.bareAgentCommand(ticket, promptArgv);
3708
+ }
3709
+ try {
3710
+ const probe = await this.dockerClient.exec(containerName, [
3711
+ 'sh', '-c',
3712
+ 'command -v bond >/dev/null 2>&1 && bond tui --help >/dev/null 2>&1 && [ -f "/workspace/repo/.bond/bond.toml" ]',
3713
+ ]);
3714
+ if (probe.exitCode !== 0) return this.bareAgentCommand(ticket, promptArgv);
3715
+ } catch {
3716
+ return this.bareAgentCommand(ticket, promptArgv);
3717
+ }
3718
+ if (!isValidAgent(ticket.agent)) {
3719
+ throw new ValidationError(`Unsupported agent '${ticket.agent}'`);
3720
+ }
3721
+ const argv = ['bond', 'tui', '--agent', ticket.agent, '--'];
3722
+ // P4 (D-D) & D-M1: el modelo solo aplica a pi; default_model si el ticket no trae modelo.
3723
+ const defaultModel = ticket.agent === 'pi' ? this.settingsRepo?.getSetupSelection?.()?.default_model : null;
3724
+ const model = ticket.agent === 'pi' ? (ticket.model || defaultModel) : null;
3725
+ if (ticket.agent === 'pi' && model) argv.push('--model', model);
3726
+ if (ticket.agent === 'agy') {
3727
+ // `-i` only with a first message (see bareAgentCommand): agy exits 2 on a bare `-i`.
3728
+ argv.push('--dangerously-skip-permissions');
3729
+ if (promptArgv.length) argv.push('-i');
3730
+ }
3731
+ if (ticket.agent === 'claude') argv.push('--dangerously-skip-permissions');
3732
+ if (ticket.agent === 'codex') argv.push('--dangerously-bypass-approvals-and-sandbox', '--dangerously-bypass-hook-trust');
3733
+ if (ticket.agent === 'copilot') {
3734
+ argv.push('--yolo');
3735
+ if (promptArgv.length) argv.push('-i');
3736
+ }
3737
+ argv.push(...promptArgv);
3738
+ return argv;
3739
+ }
3740
+
2823
3741
  /**
2824
3742
  * Teardown the run's hc machine, container and network (N1, M3, M4, P3).
2825
3743
  * The hc machine is forgotten first; the container and network are removed even if
@@ -2936,24 +3854,19 @@ fi
2936
3854
  const branch = ticket.target_branch;
2937
3855
  const base = ticket.base_branch || 'main';
2938
3856
 
2939
- if (token) {
3857
+ {
2940
3858
  const unmerged: string[] = [];
2941
- const toDelete: Array<{ owner: string; repo: string }> = [];
3859
+ const toDelete: Array<ReturnType<Orchestrator['repoAccessFor']>> = [];
2942
3860
 
2943
3861
  for (const repoUrl of reposToCheck) {
2944
- let owner: string;
2945
- let repo: string;
2946
- try {
2947
- const parsed = parseGitHubRepo(repoUrl);
2948
- owner = parsed.owner;
2949
- repo = parsed.repo;
2950
- } catch {
2951
- continue;
2952
- }
3862
+ // P1 (plan bond-app-azure-jira): GitHub or Azure Repos, each with its own token.
3863
+ if (!validateRepoUrl(repoUrl)) continue;
3864
+ const access = this.repoAccessFor(repoUrl);
3865
+ if (!access.token) continue;
2953
3866
 
2954
3867
  let exists = false;
2955
3868
  try {
2956
- exists = await this.github.remoteBranchExists(token, owner, repo, branch);
3869
+ exists = await access.branchExists(branch);
2957
3870
  } catch {
2958
3871
  continue;
2959
3872
  }
@@ -2961,16 +3874,16 @@ fi
2961
3874
  if (exists) {
2962
3875
  let merged = false;
2963
3876
  try {
2964
- merged = await this.github.isBranchMerged(token, owner, repo, branch, base);
3877
+ merged = await access.branchMerged(branch, base);
2965
3878
  } catch {
2966
3879
  // Fail closed: if check fails or throws, treat as unmerged so user work is protected
2967
3880
  merged = false;
2968
3881
  }
2969
3882
 
2970
3883
  if (!merged) {
2971
- unmerged.push(`${owner}/${repo}`);
3884
+ unmerged.push(access.label);
2972
3885
  }
2973
- toDelete.push({ owner, repo });
3886
+ toDelete.push(access);
2974
3887
  }
2975
3888
  }
2976
3889
 
@@ -2978,9 +3891,9 @@ fi
2978
3891
  throw new UnmergedBranchError(unmerged.join(', '), branch, base);
2979
3892
  }
2980
3893
 
2981
- for (const { owner, repo } of toDelete) {
3894
+ for (const access of toDelete) {
2982
3895
  try {
2983
- await this.github.deleteRemoteBranch(token, owner, repo, branch);
3896
+ await access.deleteBranch(branch);
2984
3897
  } catch {
2985
3898
  // ignore API errors
2986
3899
  }
@@ -3049,26 +3962,28 @@ fi
3049
3962
  const branch = ticket.target_branch;
3050
3963
  const base = ticket.base_branch || 'main';
3051
3964
 
3052
- if (token) {
3965
+ {
3053
3966
  for (const repoUrl of reposToCheck) {
3054
3967
  try {
3055
- const { owner, repo } = parseGitHubRepo(repoUrl);
3968
+ if (!validateRepoUrl(repoUrl)) continue;
3969
+ const access = this.repoAccessFor(repoUrl);
3970
+ if (!access.token) continue;
3056
3971
  let exists = false;
3057
3972
  try {
3058
- exists = await this.github.remoteBranchExists(token, owner, repo, branch);
3973
+ exists = await access.branchExists(branch);
3059
3974
  } catch {
3060
3975
  exists = true;
3061
3976
  }
3062
3977
  let merged = false;
3063
3978
  if (exists) {
3064
3979
  try {
3065
- merged = await this.github.isBranchMerged(token, owner, repo, branch, base);
3980
+ merged = await access.branchMerged(branch, base);
3066
3981
  } catch {
3067
3982
  merged = false;
3068
3983
  }
3069
3984
  if (!merged) requiresForce = true;
3070
3985
  }
3071
- remoteBranches.push({ repo: `${owner}/${repo}`, branch, base, exists, merged });
3986
+ remoteBranches.push({ repo: access.label, branch, base, exists, merged });
3072
3987
  } catch {
3073
3988
  // ignore
3074
3989
  }
@@ -3130,6 +4045,7 @@ fi
3130
4045
  validateTransition(run.state, targetState);
3131
4046
 
3132
4047
  // Teardown resources
4048
+ await this.syncAgyTokenFromContainer(run);
3133
4049
  let teardownFailed = false;
3134
4050
  try {
3135
4051
  await this.teardownRunResources(runId, run.container_name);
@@ -3196,26 +4112,128 @@ fi
3196
4112
 
3197
4113
  /**
3198
4114
  * P2 criterion 7 (D7): rebuild the runner image with the new pinned versions of
3199
- * bond, hc and the agents. Credentials are never touched: they never live in
3200
- * the image and nothing secret is passed to the build.
4115
+ * bond, hc and the agents. Image plan P2: the body may also pick the agent list and
4116
+ * optional staged config/credentials; the data dir root for their validation is
4117
+ * injected here, never taken from the request.
4118
+ * Credentials are never touched by a plain rebuild: they never live in the image
4119
+ * unless explicitly staged (D-A) and nothing secret goes on the docker command line.
3201
4120
  */
3202
- async rebuildRunnerImage(versions: RunnerVersions = {}): Promise<{ image: string; rebuilt_at: string; credentials_touched: false }> {
4121
+ async rebuildRunnerImage(
4122
+ versions: RunnerVersions = {},
4123
+ extras: {
4124
+ agents?: string[];
4125
+ skip_az?: boolean;
4126
+ skip_gh?: boolean;
4127
+ tools?: string[];
4128
+ apt_extra?: string[];
4129
+ config_dir?: string;
4130
+ credentials_file?: string;
4131
+ } = {}
4132
+ ): Promise<{ image: string; rebuilt_at: string; credentials_touched: boolean }> {
3203
4133
  if (this.rebuildInFlight) {
3204
4134
  throw new RebuildInProgressError('A rebuild is already in progress');
3205
4135
  }
3206
4136
  this.rebuildInFlight = true;
4137
+ this.rebuildStatus = { running: true, started_at: new Date().toISOString(), finished_at: null, step: 0, total: 0, detail: 'Preparando el build…', ok: null, error: null };
3207
4138
  try {
3208
- await this.rebuildImpl(this.config.runnerImage, versions);
4139
+ // Without an explicit list, the image keeps the agents chosen in the wizard: a bare
4140
+ // «Rebuild…» from Ajustes used to drop to the minimal image (pi), losing agy/claude.
4141
+ const agents = extras.agents ?? this.selectedImageAgents();
4142
+ // Same for the developer tools (plan bond-app-ajustes-imagen P2): the chosen groups
4143
+ // and extra packages unless the request names its own.
4144
+ const sel = this.settingsRepo?.getSetupSelection?.();
4145
+ const tools = extras.tools ?? sel?.tools_selected;
4146
+ const aptExtra = extras.apt_extra ?? sel?.apt_extra;
4147
+ await this.rebuildImpl(this.config.runnerImage, {
4148
+ ...versions,
4149
+ ...extras,
4150
+ ...(agents ? { agents } : {}),
4151
+ ...(tools ? { tools } : {}),
4152
+ ...(aptExtra ? { apt_extra: aptExtra } : {}),
4153
+ data_dir: this.config.dataDir,
4154
+ on_progress: (p) => {
4155
+ this.rebuildStatus = { ...this.rebuildStatus, step: p.step, total: p.total, detail: p.detail };
4156
+ },
4157
+ });
4158
+ this.rebuildStatus = { ...this.rebuildStatus, running: false, finished_at: new Date().toISOString(), ok: true, detail: 'Imagen lista' };
3209
4159
  return {
3210
4160
  image: this.config.runnerImage,
3211
4161
  rebuilt_at: new Date().toISOString(),
3212
- credentials_touched: false,
4162
+ credentials_touched: extras.credentials_file !== undefined,
3213
4163
  };
4164
+ } catch (err) {
4165
+ this.rebuildStatus = { ...this.rebuildStatus, running: false, finished_at: new Date().toISOString(), ok: false, error: (err as Error).message };
4166
+ throw err;
3214
4167
  } finally {
3215
4168
  this.rebuildInFlight = false;
3216
4169
  }
3217
4170
  }
3218
4171
 
4172
+ /** Where the image build is (or how the last one ended), for Ajustes' progress bar. */
4173
+ getRebuildStatus(): typeof this.rebuildStatus {
4174
+ return { ...this.rebuildStatus };
4175
+ }
4176
+
4177
+ /** The wizard's agent selection, or undefined when nothing was chosen (setup.sh's default). */
4178
+ private selectedImageAgents(): string[] | undefined {
4179
+ try {
4180
+ const sel = this.settingsRepo?.getSetupSelection?.()?.agents_selected ?? [];
4181
+ return sel.length ? [...sel] : undefined;
4182
+ } catch {
4183
+ return undefined;
4184
+ }
4185
+ }
4186
+
4187
+ /**
4188
+ * W-P1 (wizard): the aggregated setup state — selection, per-agent credentials, the gh
4189
+ * session and the runner image. Recomputed on every call (a stored credential shows up
4190
+ * without a restart); a docker that is not there or fails reads as image absent.
4191
+ */
4192
+ async getSetupState(): Promise<SetupState> {
4193
+ let image: RunnerImageInfo;
4194
+ try {
4195
+ image = await this.dockerClient.inspectRunnerImage(this.config.runnerImage);
4196
+ } catch {
4197
+ image = { present: false };
4198
+ }
4199
+ const selection = this.settingsRepo.getSetupSelection();
4200
+ return buildSetupState({
4201
+ setup_done: selection.setup_done,
4202
+ agents_selected: selection.agents_selected,
4203
+ credentials: this.settingsRepo.listSummaries(),
4204
+ github: this.settingsRepo.getGitHubSummary(),
4205
+ image,
4206
+ suggestions_model: selection.suggestions_model,
4207
+ default_model: selection.default_model,
4208
+ models: selection.models,
4209
+ tools_selected: selection.tools_selected,
4210
+ apt_extra: selection.apt_extra,
4211
+ recipe: this.currentRecipe(),
4212
+ });
4213
+ }
4214
+
4215
+ /** The runner recipe's fingerprint; null when the build context is not readable here. */
4216
+ private currentRecipe(): string | undefined {
4217
+ try {
4218
+ return runnerRecipeHash();
4219
+ } catch {
4220
+ return undefined;
4221
+ }
4222
+ }
4223
+
4224
+ /** W-P1: persists the wizard's selection; only the given fields change (validated by the API). */
4225
+ saveSetup(selection: {
4226
+ agents_selected?: string[];
4227
+ setup_done?: boolean;
4228
+ suggestions_model?: string | null;
4229
+ default_model?: string | null;
4230
+ models?: string[];
4231
+ tools_selected?: string[];
4232
+ apt_extra?: string[];
4233
+ }): void {
4234
+ this.settingsRepo.saveSetupSelection(selection);
4235
+ }
4236
+
3219
4237
  /**
3220
4238
  * State transitions. Terminal transitions delegate directly to terminateRun (H4, N2).
3221
4239
  */