@jmanuelcorral/bond-app 0.1.5 → 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 (70) hide show
  1. package/README.md +211 -17
  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 +4 -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 +308 -327
  11. package/app/mods/bond-agents/model.js +354 -5
  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 +4 -0
  16. package/app/mods/bond-board/main.js +686 -444
  17. package/app/mods/bond-board/model.js +99 -25
  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 +4 -0
  30. package/app/mods/bond-settings/main.js +1159 -278
  31. package/app/mods/bond-settings/mod.json +1 -1
  32. package/app/mods/bond-status/api.js +35 -0
  33. package/app/mods/bond-status/brand.js +53 -2
  34. package/app/mods/bond-status/config.js +4 -0
  35. package/app/mods/bond-status/main.js +37 -15
  36. package/app/mods/bond-status/model.js +19 -1
  37. package/app/mods/bond-tabs/brand.js +53 -2
  38. package/app/mods/bond-tabs/main.js +45 -3
  39. package/app/mods/bond-titlebar/brand.js +53 -2
  40. package/app/mods/bond-titlebar/main.js +85 -29
  41. package/app/mods/bond-titlebar/version.js +3 -0
  42. package/app/themes/bond-dark.json +5 -5
  43. package/app/themes/bond-light.json +5 -5
  44. package/package.json +1 -1
  45. package/runner/Dockerfile +16 -2
  46. package/runner/SPIKE-BOND.md +6 -2
  47. package/runner/entrypoint.sh +16 -0
  48. package/runner/setup.sh +439 -8
  49. package/runner/versions.env +32 -1
  50. package/scripts/app-install.ts +60 -1
  51. package/src/cli.ts +53 -3
  52. package/src/core/agy-login.ts +682 -0
  53. package/src/core/delivery.ts +3 -1
  54. package/src/core/orchestrator.ts +736 -78
  55. package/src/core/repo-host.ts +60 -0
  56. package/src/core/setup.ts +62 -1
  57. package/src/core/watchdog.ts +6 -6
  58. package/src/db/database.ts +41 -1
  59. package/src/db/settings-repo.ts +332 -7
  60. package/src/db/ticket-repo.ts +46 -20
  61. package/src/index.ts +4 -4
  62. package/src/runner/azure-devops-client.ts +163 -0
  63. package/src/runner/docker-client.ts +59 -9
  64. package/src/runner/github-client.ts +30 -3
  65. package/src/runner/hc-client.ts +33 -5
  66. package/src/runner/image-builder.ts +123 -5
  67. package/src/runner/jira-client.ts +368 -0
  68. package/src/runner/tool-catalog.ts +84 -0
  69. package/src/server/app.ts +377 -5
  70. package/src/types.ts +129 -2
@@ -11,8 +11,9 @@ import { Watchdog } from './watchdog.ts';
11
11
  import { CostTracker } from './cost-tracker.ts';
12
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 RunnerBuildOptions, 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,12 +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';
31
35
  import { buildSetupState } from './setup.ts';
32
36
  import { HUB_DIR, NAME_RE, agentGaps, analysisPrompt, buildAnalysis, fixedGaps, parseAgentAnswer, repoNameFromUrl, teamAgentFor, teamAgents, type HubToml } from './hub.ts';
33
37
  import {
34
38
  validateGitHubUrl,
35
39
  validateGitHubIssueUrl,
36
40
  parseGitHubIssueUrl,
41
+ validateJiraIssueUrl,
42
+ parseJiraIssueUrl,
43
+ normalizeJiraSite,
37
44
  isValidAgent,
38
45
  type HubAnalysis,
39
46
  type HubFix,
@@ -43,6 +50,7 @@ import {
43
50
  type RunState,
44
51
  type FailureReason,
45
52
  type TeamStatusRow,
53
+ type RunTerminal,
46
54
  type RunnerImageInfo,
47
55
  type SetupState,
48
56
  } from '../types.ts';
@@ -101,6 +109,15 @@ export class ValidationError extends Error {
101
109
  * D20: launching needs a GitHub credential (the user's gh session stored from Ajustes) or
102
110
  * an explicit token in the request. The message is shown as is by the launch dialog.
103
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
+
104
121
  export class GitHubCredentialMissingError extends ValidationError {
105
122
  code = 'github_credential_missing';
106
123
  constructor() {
@@ -132,6 +149,65 @@ export interface TestStartRunOptions extends StartRunOptions {
132
149
  gitInsteadOf?: Record<string, string>;
133
150
  }
134
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
+
135
211
  export class Orchestrator {
136
212
  public ticketRepo: TicketRepository;
137
213
  public runRepo: RunRepository;
@@ -145,6 +221,8 @@ export class Orchestrator {
145
221
  public hcClient: HcClient;
146
222
  // P4: opens the run's pull request with the GitHub REST API (token in the header only).
147
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();
148
226
 
149
227
  private reconcileTimer: NodeJS.Timeout | null = null;
150
228
  private inFlightTerminations = new Set<string>();
@@ -168,6 +246,17 @@ export class Orchestrator {
168
246
  private missingContainerStrikes = new Map<string, number>();
169
247
  // P2 criterion 7: guard against concurrent image rebuilds.
170
248
  private rebuildInFlight = false;
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 };
171
260
  private rebuildImpl: (image: string, options?: RunnerBuildOptions) => Promise<void>;
172
261
  // P4: deliveries in progress (verify, commit, push, PR), one per run.
173
262
  private deliveries = new Map<string, Promise<Run>>();
@@ -184,6 +273,12 @@ export class Orchestrator {
184
273
  private analysisNotes = new Map<string, string>();
185
274
  // P7: per-run local socket server for 'bond-app pr' channel
186
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;
187
282
 
188
283
  constructor(
189
284
  ticketRepo: TicketRepository,
@@ -195,9 +290,12 @@ export class Orchestrator {
195
290
  // P2 criterion 7: injectable for tests; the real docker build is never run in unit/UI tests.
196
291
  rebuildImpl: (image: string, options?: RunnerBuildOptions) => Promise<void> = rebuildRunnerImageImpl,
197
292
  hcClient: HcClient = new HcClient(),
198
- github: GitHubClient = new GitHubClient()
293
+ github: GitHubClient = new GitHubClient(),
294
+ agyLoginDriver?: AgyLoginDriver,
295
+ jira: JiraClient = new JiraClient()
199
296
  ) {
200
297
  this.github = github;
298
+ this.jira = jira;
201
299
  this.rebuildImpl = rebuildImpl;
202
300
  this.hcClient = hcClient;
203
301
  this.ticketRepo = ticketRepo;
@@ -209,6 +307,40 @@ export class Orchestrator {
209
307
  this.watchdog = new Watchdog(runRepo, ticketRepo, config.watchdogIntervalMs);
210
308
  this.watchdog.setOrchestrator(this);
211
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
+ }
212
344
  }
213
345
 
214
346
  async start(): Promise<void> {
@@ -230,6 +362,10 @@ export class Orchestrator {
230
362
  clearInterval(this.reconcileTimer);
231
363
  this.reconcileTimer = null;
232
364
  }
365
+ await this.agyLoginManager.cancel();
366
+ await this.claudeLoginManager.cancel();
367
+ await this.codexLoginManager.cancel();
368
+ await this.copilotLoginManager.cancel();
233
369
  for (const [, s] of this.runServers.entries()) {
234
370
  try { s.server.close(); } catch {}
235
371
  try { fs.rmSync(s.socketDir, { recursive: true, force: true }); } catch {}
@@ -249,17 +385,16 @@ export class Orchestrator {
249
385
  case 'pi':
250
386
  return '/home/runner/.pi/agent/models.json';
251
387
  case 'claude':
252
- 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';
253
390
  case 'codex':
254
- return '/home/runner/.codex/config.json';
255
- case 'opencode':
256
- 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';
257
393
  case 'copilot':
394
+ // `copilot login`'s token file (authTokens); its settings.json is baked, never overwritten.
258
395
  return '/home/runner/.copilot/config.json';
259
- case 'crush':
260
- return '/home/runner/.crush/config.json';
261
396
  case 'agy':
262
- return '/home/runner/.gemini/antigravity-cli/config.json';
397
+ return '/home/runner/.gemini/antigravity-cli/antigravity-oauth-token';
263
398
  }
264
399
  }
265
400
 
@@ -267,6 +402,178 @@ export class Orchestrator {
267
402
  * Write each agent's stored credential into the container as runner (0600), under
268
403
  * `home` (the runner's HOME, or the hub agent's throwaway one; review M-1).
269
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
+
270
577
  async injectCredentials(containerName: string, agents: string[], home = '/home/runner'): Promise<string[]> {
271
578
  const written: string[] = [];
272
579
  const wanted = new Set(agents);
@@ -779,8 +1086,10 @@ export class Orchestrator {
779
1086
 
780
1087
  /**
781
1088
  * P4 criterion 6 (P3 debt M-3): a `running` run whose agent terminal finished leaves
782
- * `running` at once: exit code 0 starts the verification and delivery; any other code
783
- * 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
784
1093
  * fixes) nothing is decided: the next sweep looks again.
785
1094
  */
786
1095
  async checkAgentExits(): Promise<string[]> {
@@ -806,12 +1115,13 @@ export class Orchestrator {
806
1115
  // The run transitions to 'finished'. Container and session stay alive.
807
1116
  if (this.setState(r.id, 'running', 'finished', null, { finished_at: new Date().toISOString() })) {
808
1117
  this.ticketRepo.updateStatus(r.ticket_id, 'finished');
1118
+ await this.syncAgyTokenFromContainer(r);
809
1119
  }
810
1120
  } else {
811
- try {
812
- await this.terminateRun(r.id, 'failed', 'agent_exited');
813
- } catch {
814
- // 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 });
815
1125
  }
816
1126
  }
817
1127
  }
@@ -840,6 +1150,7 @@ export class Orchestrator {
840
1150
 
841
1151
  let isBlocked = false;
842
1152
  let waitingAgentName: string | null = null;
1153
+ let notSignedInBlocked = false;
843
1154
 
844
1155
  if (ticket.mode === 'hub') {
845
1156
  if (ticket.team_engine === 'herdr') {
@@ -873,7 +1184,7 @@ export class Orchestrator {
873
1184
  }
874
1185
  const cleanCwd = a.cwd?.replace(/\/+$/, '');
875
1186
  if (cleanCwd === '/workspace/hub') return true;
876
- 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;
877
1188
  return false;
878
1189
  };
879
1190
  const waiting = agents.filter(isWaiting);
@@ -946,11 +1257,24 @@ export class Orchestrator {
946
1257
  if (!r.hc_terminal) continue;
947
1258
  try {
948
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;
949
1263
  if (t.state === 'live') {
950
- const isWaiting = t.status === 'blocked' || ((t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0);
951
- if (isWaiting) {
952
- isBlocked = true;
953
- 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
+ }
954
1278
  }
955
1279
  }
956
1280
  } catch {
@@ -961,6 +1285,16 @@ export class Orchestrator {
961
1285
  const latest = this.runRepo.get(r.id);
962
1286
  if (!latest || (latest.state !== 'running' && latest.state !== 'waiting')) continue;
963
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
+
964
1298
  if (isBlocked) {
965
1299
  const reason = `Esperando respuesta: ${waitingAgentName}`;
966
1300
  if (latest.state === 'running') {
@@ -1132,15 +1466,21 @@ export class Orchestrator {
1132
1466
  this.agentEvent(run, 'verification.passed', { commands: ticket.verify_commands.length });
1133
1467
 
1134
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).
1135
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';
1136
1476
  const commit = await this.dockerClient.exec(
1137
1477
  ctr,
1138
1478
  [
1139
1479
  'sh', '-c', COMMIT_SCRIPT, 'bond-commit',
1140
1480
  ticket.target_branch,
1141
1481
  `${ticket.title}\n\nbond-app run ${runId} (ticket ${ticket.id})`,
1142
- login || 'bond-app',
1143
- login ? `${login}@users.noreply.github.com` : 'bond-app@localhost',
1482
+ authorName,
1483
+ authorEmail,
1144
1484
  '/workspace/repo',
1145
1485
  BUNDLE_PATH,
1146
1486
  expectedTree,
@@ -1160,8 +1500,9 @@ export class Orchestrator {
1160
1500
  // on the exact object pushed: it is the committed head, adds commits to the real base
1161
1501
  // from GitHub and changes nothing under .github/workflows (review HIGH-1).
1162
1502
  // D2: push retries up to 3 times with growing backoff; exhausted -> blocked.
1163
- const token = this.runTokens.get(runId) || this.settingsRepo.getGitHubToken();
1164
- 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();
1165
1506
  const shouldRetryPush = (err: unknown) => {
1166
1507
  const msg = String((err as Error).message || err);
1167
1508
  return !msg.includes('nothing to deliver') && !msg.includes('.github/workflows') && !msg.includes('does not match the committed head');
@@ -1196,7 +1537,7 @@ export class Orchestrator {
1196
1537
  const pr = await this.retryDeliveryStep(
1197
1538
  'pr',
1198
1539
  run,
1199
- () => this.github.openPullRequest(token, ticket.repo_url, {
1540
+ () => access.openPullRequest({
1200
1541
  head: ticket.target_branch,
1201
1542
  base: ticket.base_branch,
1202
1543
  title: ticket.title,
@@ -1365,9 +1706,43 @@ export class Orchestrator {
1365
1706
  this.ticketRepo.updateStatus(run.ticket_id, 'finished');
1366
1707
  const updated = this.runRepo.get(runId)!;
1367
1708
  this.agentEvent(updated, 'agent.finished', { manual: true });
1709
+ await this.syncAgyTokenFromContainer(updated);
1368
1710
  return updated;
1369
1711
  }
1370
1712
 
1713
+ /**
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
+
1371
1746
  /**
1372
1747
  * P2: Build the orchestrator / leader row for a run, used in getRunTeamStatus.
1373
1748
  * Guarantees that any run (hub or single, running or waiting or queued,
@@ -1402,7 +1777,7 @@ export class Orchestrator {
1402
1777
  } catch {}
1403
1778
  }
1404
1779
 
1405
- const isGenericAgent = (name?: string) => !name || name === 'agent' || /^t\d+$/.test(name);
1780
+ const isGenericAgent = (name?: string) => !name || name === 'agent' || name === 'gru' || /^t\d+$/.test(name);
1406
1781
 
1407
1782
  let listedAgent: string | undefined;
1408
1783
  if (isGenericAgent(t?.agent) && (run.hc_machine || run.hc_terminal || t?.address)) {
@@ -1619,7 +1994,7 @@ export class Orchestrator {
1619
1994
  }
1620
1995
  const cleanCwd = a.cwd?.replace(/\/+$/, '');
1621
1996
  if (cleanCwd === '/workspace/hub') return true;
1622
- 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;
1623
1998
  return false;
1624
1999
  };
1625
2000
 
@@ -1718,6 +2093,65 @@ export class Orchestrator {
1718
2093
  }
1719
2094
  }
1720
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);
2151
+ return [];
2152
+ }
2153
+ }
2154
+
1721
2155
  /**
1722
2156
  * Criterion 2: push the run's bundled branch from the container, as root, with the token
1723
2157
  * on stdin (D8). Refuses (PushNotAllowedError) any repo or branch but the ticket's.
@@ -1736,8 +2170,9 @@ export class Orchestrator {
1736
2170
  assertPushTarget(ticket, repoUrl, branch);
1737
2171
  if (!/^[0-9a-f]{40}$/.test(expectedSha)) throw new Error('Invalid expected head sha');
1738
2172
  if (!run.container_name) throw new Error('The run has no container');
1739
- const secret = token || this.runTokens.get(runId) || this.settingsRepo.getGitHubToken();
1740
- if (!secret) throw new GitHubCredentialMissingError();
2173
+ const access = this.repoAccessFor(repoUrl, runId);
2174
+ const secret = token || access.token;
2175
+ if (!secret) throw access.missing();
1741
2176
  return this.pushBundle(run, repoUrl, branch, BUNDLE_PATH, expectedSha, ticket.base_branch, secret);
1742
2177
  }
1743
2178
 
@@ -2190,9 +2625,22 @@ export class Orchestrator {
2190
2625
  }
2191
2626
  // The hub covers the story: the team, one agent per repo, on the ticket's branch.
2192
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
+ }
2193
2634
  try {
2194
2635
  // Review M-1: the team's credentials go in only now, after the analysis.
2195
- 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!);
2196
2644
  if (!stillAnalyzing()) return current();
2197
2645
  const session = this.hubSessionOf(run);
2198
2646
  // Review L-2: a restart during the launch left the team open: keep it, do not relaunch.
@@ -2341,7 +2789,7 @@ export class Orchestrator {
2341
2789
  }
2342
2790
  const cleanCwd = a.cwd?.replace(/\/+$/, '');
2343
2791
  if (cleanCwd === '/workspace/hub') return true;
2344
- 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;
2345
2793
  return false;
2346
2794
  };
2347
2795
 
@@ -2580,15 +3028,20 @@ export class Orchestrator {
2580
3028
  // D20: an explicit token in the request wins; else the stored GitHub credential (the
2581
3029
  // user's gh session); without either the launch is refused (N4). It still reaches the
2582
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';
2583
3034
  const githubToken = options.skipClone
2584
3035
  ? undefined
2585
- : options.githubToken || this.settingsRepo.getGitHubToken() || undefined;
3036
+ : onAzure
3037
+ ? this.repoAccessFor(ticket.repo_url).token || undefined
3038
+ : options.githubToken || this.settingsRepo.getGitHubToken() || undefined;
2586
3039
  if (!options.skipClone) {
2587
3040
  if (!githubToken) {
2588
- throw new GitHubCredentialMissingError();
3041
+ throw onAzure ? new AzureDevOpsCredentialMissingError() : new GitHubCredentialMissingError();
2589
3042
  }
2590
- if (options.githubToken) this.runTokens.set(runId, options.githubToken);
2591
- 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))) {
2592
3045
  throw new ValidationError(`Invalid repo_url '${ticket.repo_url}'`);
2593
3046
  }
2594
3047
  } else if (ticket.mode === 'hub') {
@@ -2610,30 +3063,91 @@ export class Orchestrator {
2610
3063
 
2611
3064
  this.startingRuns.add(runId);
2612
3065
 
2613
- // 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)
2614
3067
  if (ticket.issue_url) {
2615
- if (!validateGitHubIssueUrl(ticket.issue_url)) {
3068
+ const isGh = validateGitHubIssueUrl(ticket.issue_url);
3069
+ const isJira = validateJiraIssueUrl(ticket.issue_url);
3070
+ if (!isGh && !isJira) {
2616
3071
  this.setState(run.id, 'queued', 'blocked', 'invalid_issue_url');
2617
3072
  this.startingRuns.delete(runId);
2618
3073
  return this.runRepo.get(run.id)!;
2619
3074
  }
2620
- const { owner, repo, issueNumber } = parseGitHubIssueUrl(ticket.issue_url);
2621
- 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;
2622
3134
  try {
2623
- const issue = await this.github.getIssue(token, owner, repo, issueNumber);
2624
- const updated = this.ticketRepo.update(ticket.id, {
2625
- story: issue.title + (issue.body ? '\n\n' + issue.body : ''),
2626
- title: ticket.title || issue.title,
2627
- });
2628
- if (updated) ticket = updated;
2629
- } catch (err) {
2630
- const msg = String((err as Error).message || err);
2631
- 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);
2632
3139
  this.startingRuns.delete(runId);
2633
3140
  return this.runRepo.get(run.id)!;
2634
3141
  }
2635
3142
  }
2636
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
+
2637
3151
  const assertQueued = () => {
2638
3152
  const current = this.runRepo.get(runId);
2639
3153
  if (!current || current.state !== 'queued') {
@@ -2670,6 +3184,7 @@ export class Orchestrator {
2670
3184
  memory: this.config.memory,
2671
3185
  pidsLimit: this.config.pidsLimit,
2672
3186
  extraMounts,
3187
+ docker: ticket.docker === true,
2673
3188
  });
2674
3189
 
2675
3190
  containerName = containerInfo.containerName;
@@ -2811,9 +3326,14 @@ fi
2811
3326
 
2812
3327
  // 5. Inject Agent credentials (D7, M7, L6). P5 review M-1: a hub run gets them only
2813
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.
2814
3331
  if (ticket.mode !== 'hub') {
2815
- await this.injectCredentials(containerInfo.containerName, [ticket.agent]);
3332
+ await this.injectCredentials(containerInfo.containerName, this.allConfiguredAgents());
2816
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');
2817
3337
 
2818
3338
  assertQueued();
2819
3339
 
@@ -2918,10 +3438,17 @@ fi
2918
3438
  ? 'validation_error'
2919
3439
  : startError instanceof HubMountError
2920
3440
  ? 'hub_mount_failed'
2921
- : 'container_error';
3441
+ : startError instanceof HcError && startError.kind === 'agent_exited'
3442
+ ? 'agent_exited'
3443
+ : 'container_error';
2922
3444
  if (startError instanceof HubMountError) {
2923
3445
  this.agentEvent(latest, 'hub.mount_failed', { error: startError.message.slice(0, 300) });
2924
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}`);
2925
3452
  const { updated } = this.runRepo.updateStateConditionally(
2926
3453
  runId,
2927
3454
  oldState,
@@ -2974,6 +3501,77 @@ fi
2974
3501
  return prompt ? [ticket.agent, prompt] : [ticket.agent];
2975
3502
  }
2976
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
+
2977
3575
  /**
2978
3576
  * P4 (D-U): Auto-bondify repository if it lacks .bond/bond.toml.
2979
3577
  * If config.runnerLauncher === 'bond' and ticket.bondify !== false:
@@ -3102,29 +3700,41 @@ fi
3102
3700
  ticket: Ticket,
3103
3701
  promptOverride?: string
3104
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);
3105
3706
  if (this.config.runnerLauncher !== 'bond' || this.config.agentCommand || !containerName) {
3106
- return this.agentCommandFor(ticket, promptOverride);
3707
+ return this.bareAgentCommand(ticket, promptArgv);
3107
3708
  }
3108
3709
  try {
3109
3710
  const probe = await this.dockerClient.exec(containerName, [
3110
3711
  'sh', '-c',
3111
3712
  'command -v bond >/dev/null 2>&1 && bond tui --help >/dev/null 2>&1 && [ -f "/workspace/repo/.bond/bond.toml" ]',
3112
3713
  ]);
3113
- if (probe.exitCode !== 0) return this.agentCommandFor(ticket, promptOverride);
3714
+ if (probe.exitCode !== 0) return this.bareAgentCommand(ticket, promptArgv);
3114
3715
  } catch {
3115
- return this.agentCommandFor(ticket, promptOverride);
3716
+ return this.bareAgentCommand(ticket, promptArgv);
3116
3717
  }
3117
3718
  if (!isValidAgent(ticket.agent)) {
3118
3719
  throw new ValidationError(`Unsupported agent '${ticket.agent}'`);
3119
3720
  }
3120
- const story = [ticket.story ?? '', ticket.prompt ?? ''].filter((s) => s.trim()).join('\n\n');
3121
- const prompt = (promptOverride ?? story).trim();
3122
3721
  const argv = ['bond', 'tui', '--agent', ticket.agent, '--'];
3123
3722
  // P4 (D-D) & D-M1: el modelo solo aplica a pi; default_model si el ticket no trae modelo.
3124
3723
  const defaultModel = ticket.agent === 'pi' ? this.settingsRepo?.getSetupSelection?.()?.default_model : null;
3125
3724
  const model = ticket.agent === 'pi' ? (ticket.model || defaultModel) : null;
3126
3725
  if (ticket.agent === 'pi' && model) argv.push('--model', model);
3127
- if (prompt) argv.push(prompt);
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);
3128
3738
  return argv;
3129
3739
  }
3130
3740
 
@@ -3244,24 +3854,19 @@ fi
3244
3854
  const branch = ticket.target_branch;
3245
3855
  const base = ticket.base_branch || 'main';
3246
3856
 
3247
- if (token) {
3857
+ {
3248
3858
  const unmerged: string[] = [];
3249
- const toDelete: Array<{ owner: string; repo: string }> = [];
3859
+ const toDelete: Array<ReturnType<Orchestrator['repoAccessFor']>> = [];
3250
3860
 
3251
3861
  for (const repoUrl of reposToCheck) {
3252
- let owner: string;
3253
- let repo: string;
3254
- try {
3255
- const parsed = parseGitHubRepo(repoUrl);
3256
- owner = parsed.owner;
3257
- repo = parsed.repo;
3258
- } catch {
3259
- continue;
3260
- }
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;
3261
3866
 
3262
3867
  let exists = false;
3263
3868
  try {
3264
- exists = await this.github.remoteBranchExists(token, owner, repo, branch);
3869
+ exists = await access.branchExists(branch);
3265
3870
  } catch {
3266
3871
  continue;
3267
3872
  }
@@ -3269,16 +3874,16 @@ fi
3269
3874
  if (exists) {
3270
3875
  let merged = false;
3271
3876
  try {
3272
- merged = await this.github.isBranchMerged(token, owner, repo, branch, base);
3877
+ merged = await access.branchMerged(branch, base);
3273
3878
  } catch {
3274
3879
  // Fail closed: if check fails or throws, treat as unmerged so user work is protected
3275
3880
  merged = false;
3276
3881
  }
3277
3882
 
3278
3883
  if (!merged) {
3279
- unmerged.push(`${owner}/${repo}`);
3884
+ unmerged.push(access.label);
3280
3885
  }
3281
- toDelete.push({ owner, repo });
3886
+ toDelete.push(access);
3282
3887
  }
3283
3888
  }
3284
3889
 
@@ -3286,9 +3891,9 @@ fi
3286
3891
  throw new UnmergedBranchError(unmerged.join(', '), branch, base);
3287
3892
  }
3288
3893
 
3289
- for (const { owner, repo } of toDelete) {
3894
+ for (const access of toDelete) {
3290
3895
  try {
3291
- await this.github.deleteRemoteBranch(token, owner, repo, branch);
3896
+ await access.deleteBranch(branch);
3292
3897
  } catch {
3293
3898
  // ignore API errors
3294
3899
  }
@@ -3357,26 +3962,28 @@ fi
3357
3962
  const branch = ticket.target_branch;
3358
3963
  const base = ticket.base_branch || 'main';
3359
3964
 
3360
- if (token) {
3965
+ {
3361
3966
  for (const repoUrl of reposToCheck) {
3362
3967
  try {
3363
- const { owner, repo } = parseGitHubRepo(repoUrl);
3968
+ if (!validateRepoUrl(repoUrl)) continue;
3969
+ const access = this.repoAccessFor(repoUrl);
3970
+ if (!access.token) continue;
3364
3971
  let exists = false;
3365
3972
  try {
3366
- exists = await this.github.remoteBranchExists(token, owner, repo, branch);
3973
+ exists = await access.branchExists(branch);
3367
3974
  } catch {
3368
3975
  exists = true;
3369
3976
  }
3370
3977
  let merged = false;
3371
3978
  if (exists) {
3372
3979
  try {
3373
- merged = await this.github.isBranchMerged(token, owner, repo, branch, base);
3980
+ merged = await access.branchMerged(branch, base);
3374
3981
  } catch {
3375
3982
  merged = false;
3376
3983
  }
3377
3984
  if (!merged) requiresForce = true;
3378
3985
  }
3379
- remoteBranches.push({ repo: `${owner}/${repo}`, branch, base, exists, merged });
3986
+ remoteBranches.push({ repo: access.label, branch, base, exists, merged });
3380
3987
  } catch {
3381
3988
  // ignore
3382
3989
  }
@@ -3438,6 +4045,7 @@ fi
3438
4045
  validateTransition(run.state, targetState);
3439
4046
 
3440
4047
  // Teardown resources
4048
+ await this.syncAgyTokenFromContainer(run);
3441
4049
  let teardownFailed = false;
3442
4050
  try {
3443
4051
  await this.teardownRunResources(runId, run.container_name);
@@ -3516,6 +4124,8 @@ fi
3516
4124
  agents?: string[];
3517
4125
  skip_az?: boolean;
3518
4126
  skip_gh?: boolean;
4127
+ tools?: string[];
4128
+ apt_extra?: string[];
3519
4129
  config_dir?: string;
3520
4130
  credentials_file?: string;
3521
4131
  } = {}
@@ -3524,22 +4134,56 @@ fi
3524
4134
  throw new RebuildInProgressError('A rebuild is already in progress');
3525
4135
  }
3526
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 };
3527
4138
  try {
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;
3528
4147
  await this.rebuildImpl(this.config.runnerImage, {
3529
4148
  ...versions,
3530
4149
  ...extras,
4150
+ ...(agents ? { agents } : {}),
4151
+ ...(tools ? { tools } : {}),
4152
+ ...(aptExtra ? { apt_extra: aptExtra } : {}),
3531
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
+ },
3532
4157
  });
4158
+ this.rebuildStatus = { ...this.rebuildStatus, running: false, finished_at: new Date().toISOString(), ok: true, detail: 'Imagen lista' };
3533
4159
  return {
3534
4160
  image: this.config.runnerImage,
3535
4161
  rebuilt_at: new Date().toISOString(),
3536
4162
  credentials_touched: extras.credentials_file !== undefined,
3537
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;
3538
4167
  } finally {
3539
4168
  this.rebuildInFlight = false;
3540
4169
  }
3541
4170
  }
3542
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
+
3543
4187
  /**
3544
4188
  * W-P1 (wizard): the aggregated setup state — selection, per-agent credentials, the gh
3545
4189
  * session and the runner image. Recomputed on every call (a stored credential shows up
@@ -3562,9 +4206,21 @@ fi
3562
4206
  suggestions_model: selection.suggestions_model,
3563
4207
  default_model: selection.default_model,
3564
4208
  models: selection.models,
4209
+ tools_selected: selection.tools_selected,
4210
+ apt_extra: selection.apt_extra,
4211
+ recipe: this.currentRecipe(),
3565
4212
  });
3566
4213
  }
3567
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
+
3568
4224
  /** W-P1: persists the wizard's selection; only the given fields change (validated by the API). */
3569
4225
  saveSetup(selection: {
3570
4226
  agents_selected?: string[];
@@ -3572,6 +4228,8 @@ fi
3572
4228
  suggestions_model?: string | null;
3573
4229
  default_model?: string | null;
3574
4230
  models?: string[];
4231
+ tools_selected?: string[];
4232
+ apt_extra?: string[];
3575
4233
  }): void {
3576
4234
  this.settingsRepo.saveSetupSelection(selection);
3577
4235
  }