@jmanuelcorral/bond-app 0.3.4 → 0.3.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.
@@ -27,7 +27,7 @@ import {
27
27
  deliverRun, nudgeRun, finishRun, approveHubFixes, proceedHub, deleteTicket, getDeletePreview,
28
28
  columnCounts, filterOptions, filterCards, issueChip, validateNewTicket, createTicket, AGENTS, TICKET_MODES, TEAM_ENGINES,
29
29
  cleanRepoChips, listAssignedIssues, issueTicketId, searchRepos, listRepoIssues, searchJiraIssues, resetIssueProviderState, needsWizard, timeoutLabel,
30
- searchPullRequests, resolvePullRequest, parsePrSearchInput, formatSourceError, INIT_ARGV, repoCheckQuery,
30
+ searchPullRequests, resolvePullRequest, parsePrSearchInput, formatSourceError, INIT_ARGV, azureChoices, repoCheckQuery,
31
31
  } from "./model.js";
32
32
  import { stateColor, UI, settingsOverlay, createOverlay, markColor } from "./brand.js";
33
33
 
@@ -164,6 +164,7 @@ export default class BondBoard extends View {
164
164
  this.azureLoginOn = false;
165
165
  this.azureTouched = false;
166
166
  this.azureSub = null; // null = the default subscription of Ajustes (D4)
167
+ this.azureTenantSel = null; // null = the tenant of that default subscription
167
168
  this.azureSession = null;
168
169
  cx.spawn(async (cx) => {
169
170
  try {
@@ -501,7 +502,7 @@ export default class BondBoard extends View {
501
502
  story: storyText.trim() ? storyText : this.pickedPr ? "" : undefined,
502
503
  bondify: this.bondify,
503
504
  docker: this.docker,
504
- azure_login: this.azureLoginOn && Boolean(this.azureSession?.configured), azure_subscription: this.azureSub,
505
+ azure_login: this.azureLoginOn && Boolean(this.azureSession?.configured), azure_subscription: azureChoices(this.azureSession, this.azureTenantSel ?? null, this.azureSub ?? null).subscription,
505
506
  loop: this.loop && this.loopAvailable(), loop_max: v("loopMax"), loop_unlimited: this.loopUnlimited,
506
507
  })
507
508
  : validateNewTicket({
@@ -514,7 +515,7 @@ export default class BondBoard extends View {
514
515
  story: storyText.trim() ? storyText : this.pickedIssue ? "" : undefined,
515
516
  bondify: this.bondify,
516
517
  docker: this.docker,
517
- azure_login: this.azureLoginOn && Boolean(this.azureSession?.configured), azure_subscription: this.azureSub,
518
+ azure_login: this.azureLoginOn && Boolean(this.azureSession?.configured), azure_subscription: azureChoices(this.azureSession, this.azureTenantSel ?? null, this.azureSub ?? null).subscription,
518
519
  loop: this.loop && this.loopAvailable(), loop_max: v("loopMax"), loop_unlimited: this.loopUnlimited,
519
520
  });
520
521
  this.errors = check.errors;
@@ -1445,8 +1446,7 @@ export default class BondBoard extends View {
1445
1446
  const az = this.azureSession;
1446
1447
  const usable = Boolean(az?.configured) && !az?.expired;
1447
1448
  const on = usable && this.azureLoginOn;
1448
- const subs = az?.subscriptions ?? [];
1449
- const chosen = this.azureSub ?? az?.subscription?.id ?? null;
1449
+ const pick = azureChoices(az, this.azureTenantSel ?? null, this.azureSub ?? null);
1450
1450
  const why = !az ? "comprobando la sesión de Azure…"
1451
1451
  : !az.configured ? "sin sesión de Azure: inicia sesión en Ajustes → Azure"
1452
1452
  : az.expired ? "la sesión de Azure ha caducado: vuelve a iniciarla en Ajustes → Azure" : null;
@@ -1465,11 +1465,18 @@ export default class BondBoard extends View {
1465
1465
  .when(on, (el) => el
1466
1466
  .child(div().pl(22).text_size(UI.text.tiny).font_family(UI.fontSans).text_color(t.dim)
1467
1467
  .child("Los agentes del run usan az con tu cuenta: tienen en Azure tus mismos permisos, producción incluida. La sesión va al run por stdin y se va con el contenedor."))
1468
- .when(subs.length > 1, (el2) => el2.child(h_flex().pl(22).gap(6).flex_wrap().items_center()
1468
+ // Tenant and subscription, among those the session sees (one session; decision 2026-11-27).
1469
+ .child(h_flex().id("azure-tenants").pl(22).gap(6).flex_wrap().items_center()
1470
+ .child(div().text_size(UI.text.tiny).text_color(t.muted).child("Tenant:"))
1471
+ .children(pick.tenants.length > 1
1472
+ ? pick.tenants.map((tn) => this.choice(`azure-tenant-${tn.id}`, tn.label, pick.tenant === tn.id,
1473
+ () => { this.azureTenantSel = tn.id; this.azureSub = null; }))
1474
+ : [div().text_size(UI.text.tiny).text_color(t.foreground).child(pick.tenants[0]?.label ?? "—")]))
1475
+ .child(h_flex().id("azure-subs").pl(22).gap(6).flex_wrap().items_center()
1469
1476
  .child(div().text_size(UI.text.tiny).text_color(t.muted).child("Suscripción:"))
1470
- .children(subs.map((sub) => this.choice(`azure-sub-${sub.id}`, sub.name, chosen === sub.id,
1471
- () => { this.azureSub = sub.id === az.subscription?.id ? null : sub.id; })))))
1472
- .when(subs.length === 1, (el2) => el2.child(div().pl(22).text_size(UI.text.tiny).text_color(t.muted).child(`Suscripción: ${subs[0].name}`))));
1477
+ .children(pick.subs.length > 1
1478
+ ? pick.subs.map((sub) => this.choice(`azure-sub-${sub.id}`, sub.name, pick.subscription === sub.id, () => { this.azureSub = sub.id; }))
1479
+ : [div().text_size(UI.text.tiny).text_color(t.foreground).child(pick.subs[0]?.name ?? "—")])));
1473
1480
  }
1474
1481
 
1475
1482
  /** LOOP P1: the loop is for hub tickets only (v1, decision D7). */
@@ -793,3 +793,25 @@ export const INIT_ARGV = ["sh", "-c", [
793
793
  "printf ' y esta pestaña se cierra sola. El estado está en el panel Agentes.\\n\\n'",
794
794
  "exec sh",
795
795
  ].join("; ")];
796
+
797
+ /**
798
+ * «Login de Azure» in a new ticket: the tenants the Azure session sees (by their name when az
799
+ * knows it), the chosen one (by default the tenant of the session's default subscription),
800
+ * its subscriptions and the chosen subscription (the default one when it is in that tenant,
801
+ * else the first). `tenantSel`/`subSel` are the person's picks, null for the defaults.
802
+ */
803
+ export function azureChoices(session, tenantSel = null, subSel = null) {
804
+ const subs = Array.isArray(session?.subscriptions) ? session.subscriptions : [];
805
+ const tenants = [];
806
+ for (const x of subs) {
807
+ if (!x?.tenant_id || tenants.some((t) => t.id === x.tenant_id)) continue;
808
+ tenants.push({ id: x.tenant_id, label: x.tenant_name || `tenant ${x.tenant_id.slice(0, 8)}` });
809
+ }
810
+ const defSub = subs.find((x) => x.id === session?.subscription?.id) ?? subs[0] ?? null;
811
+ const tenant = tenants.some((t) => t.id === tenantSel) ? tenantSel : defSub?.tenant_id ?? tenants[0]?.id ?? null;
812
+ const inTenant = subs.filter((x) => !tenant || x.tenant_id === tenant);
813
+ const subscription = inTenant.some((x) => x.id === subSel)
814
+ ? subSel
815
+ : (inTenant.find((x) => x.id === defSub?.id) ?? inTenant[0])?.id ?? null;
816
+ return { tenants, tenant, subs: inTenant, subscription };
817
+ }
@@ -274,6 +274,8 @@ export default class BondSettings extends View {
274
274
  // Plan bond-app-azure-jira P1: Azure DevOps (Azure Repos). The PAT field never shows the
275
275
  // stored one; an empty PAT with a stored credential only changes the switch.
276
276
  this.azureDevOps = null;
277
+ this.azureTenant = InputState.new({ placeholder: "id del tenant o dominio (contoso.onmicrosoft.com); vacío: el de tu cuenta" });
278
+ this.azureTenantLoaded = false;
277
279
  this.azureOrg = InputState.new({ placeholder: "https://dev.azure.com/tu-organización" });
278
280
  this.azurePat = InputState.new({ placeholder: "PAT con Code: read & write (y Pull requests si tus skills lo usan)" });
279
281
  this.azurePat.set_masked(true);
@@ -1105,7 +1107,8 @@ export default class BondSettings extends View {
1105
1107
 
1106
1108
  openAzureLogin() {
1107
1109
  if (this.imageMissing()) return;
1108
- openOverlay({ mod: "bond-settings", kind: "dialog", modal: true, width: 480, height: 0.92, props: { view: "agy-login", agent: "azure" } });
1110
+ const tenant = String(this.azureTenant?.value() ?? "").trim();
1111
+ openOverlay({ mod: "bond-settings", kind: "dialog", modal: true, width: 480, height: 0.92, props: { view: "agy-login", agent: "azure", ...(tenant ? { tenant } : {}) } });
1109
1112
  }
1110
1113
 
1111
1114
  setAzureSubscription(id, cx) {
@@ -1142,18 +1145,29 @@ export default class BondSettings extends View {
1142
1145
  const days = az.expires_at ? Math.floor((Date.parse(az.expires_at) - Date.now()) / 86_400_000) : null;
1143
1146
  const expiry = az.expired ? "caducada: vuelve a iniciar sesión" : days === null ? "" : `caduca en ~${days} días`;
1144
1147
  const subs = az.subscriptions ?? [];
1148
+ // Several tenants: each subscription says which one it lives in.
1149
+ const tenants = new Set(subs.map((x) => x.tenant_id).filter(Boolean));
1150
+ const subLabel = (sub) => (tenants.size > 1 && sub.tenant_id ? `${sub.name} · ${sub.tenant_name || `tenant ${sub.tenant_id.slice(0, 8)}`}` : sub.name);
1151
+ if (on && !this.azureTenantLoaded && az.tenant_id) {
1152
+ this.azureTenantLoaded = true;
1153
+ this.azureTenant.set_value(az.tenant_id);
1154
+ }
1145
1155
  const chip = (sub) => h_flex().id(`azure-sub-${sub.id}`).flex_none().h(24).px(9).items_center().rounded(UI.radius).border_1()
1146
1156
  .border_color(az.subscription?.id === sub.id ? t.accent : t.input).bg(az.subscription?.id === sub.id ? t.selected : t.surface)
1147
1157
  .text_size(12).text_color(az.subscription?.id === sub.id ? t.foreground : t.muted).tooltip(sub.id)
1148
1158
  .cursor_pointer().hover((st) => st.bg(t.hover)).on_click((_e, cx) => this.setAzureSubscription(sub.id, cx))
1149
- .child(sub.name);
1159
+ .child(subLabel(sub));
1150
1160
  return v_flex().gap(10)
1151
1161
  .child(this.sectionTitle("Sesión de Azure", "Para que los agentes de un run usen az (recursos, Key Vault, AKS…) sin hacer az login dentro."))
1152
- .child(this.status("azure-login-status", on ? `Sesión de ${az.user ?? "Azure"}${expiry ? ` · ${expiry}` : ""}` : "Sin sesión",
1162
+ .child(this.status("azure-login-status", on ? `Sesión de ${az.user ?? "Azure"}${az.tenant_name ? ` en ${az.tenant_name}` : ""}${expiry ? ` · ${expiry}` : ""}` : "Sin sesión",
1153
1163
  on ? (az.expired ? t.blocked : this.tone(t, "ok")) : t.dim))
1154
1164
  .when(on && subs.length > 0, (el) => el.child(v_flex().gap(4)
1155
1165
  .child(div().pt(2).text_size(UI.text.small).font_semibold().text_color(t.muted).child("Suscripción por defecto"))
1156
1166
  .child(h_flex().flex_wrap().gap(6).children(subs.map(chip)))))
1167
+ .child(v_flex().gap(4)
1168
+ .child(div().pt(2).text_size(UI.text.small).font_semibold().text_color(t.muted).child("Tenant (opcional)"))
1169
+ .child(Input.new(this.azureTenant).h(UI.button + 4).px(10).rounded(UI.radius).border_1().border_color(t.input).bg(t.background).text_size(12)))
1170
+ .child(this.note("Si tus suscripciones están en otro tenant que tu cuenta (eres invitado, o ese tenant pide su propio MFA), pon aquí ese tenant e inicia sesión. Azure DevOps va aparte: su PAT es de la organización y no depende de este tenant."))
1157
1171
  .child(this.note("Solo la reciben los tickets con «Login de Azure», que viene marcado mientras haya sesión (desmárcalo en el ticket que no la necesite). Con tu cuenta, el agente tiene en Azure tus mismos permisos, producción incluida: para el día a día, mejor un service principal con permisos acotados (fase siguiente)."))
1158
1172
  .child(h_flex().gap(6)
1159
1173
  .child(this.button("azure-login", on ? "Volver a iniciar sesión…" : "Iniciar sesión en Azure…", !on, () => this.openAzureLogin()))
@@ -1737,7 +1751,9 @@ export default class BondSettings extends View {
1737
1751
  cx.notify();
1738
1752
  cx.spawn(async (cx) => {
1739
1753
  try {
1740
- const res = await api(`/settings/${this.loginAgent ?? "agy"}/login/start`, { method: "POST" });
1754
+ // Azure: the tenant chosen in Ajustes (subscriptions in another tenant than the account's).
1755
+ const tenant = this.loginAgent === "azure" ? String(props()?.tenant ?? "").trim() : "";
1756
+ const res = await api(`/settings/${this.loginAgent ?? "agy"}/login/start`, { method: "POST", ...(tenant ? { body: { tenant } } : {}) });
1741
1757
  if (res?.status) this.agyStatus = res.status;
1742
1758
  if (res?.url) this.agyUrl = res.url;
1743
1759
  this.agyUserCode = res?.user_code ?? null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jmanuelcorral/bond-app",
3
- "version": "0.3.4",
3
+ "version": "0.3.6",
4
4
  "description": "Local orchestrator and hub-container runner for multi-agent tickets",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
package/src/cli.ts CHANGED
@@ -271,6 +271,27 @@ export function relaunchSelf(dataDir: string, spawnFn: typeof spawn = spawn): nu
271
271
  }
272
272
  }
273
273
 
274
+ /** Append console.log/error/warn to <dataDir>/orchestrator.log as well (0600); never throws. */
275
+ export function teeConsoleToLog(dataDir: string): void {
276
+ const logPath = path.join(dataDir, 'orchestrator.log');
277
+ try {
278
+ fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
279
+ fs.appendFileSync(logPath, `\n[bond-app] ${new Date().toISOString()} started by hand (bond-app start)\n`, { mode: 0o600 });
280
+ } catch {
281
+ return;
282
+ }
283
+ for (const level of ['log', 'error', 'warn'] as const) {
284
+ const original = console[level].bind(console);
285
+ console[level] = (...args: unknown[]) => {
286
+ original(...args);
287
+ try {
288
+ const text = args.map((a) => (typeof a === 'string' ? a : a instanceof Error ? a.stack ?? a.message : JSON.stringify(a))).join(' ');
289
+ fs.appendFileSync(logPath, `${text}\n`);
290
+ } catch {}
291
+ };
292
+ }
293
+ }
294
+
274
295
  export async function handleStart(
275
296
  args: string[],
276
297
  bootstrapFn: (overrides?: any, hooks?: ServerHooks) => Promise<{ server: any; orchestrator: any; port: number }> = bootstrap,
@@ -350,6 +371,11 @@ export async function handleStart(
350
371
  }
351
372
  }
352
373
 
374
+ // Started by hand (not the service, whose output launchd/systemd already send to the log):
375
+ // copy what the orchestrator says to <data dir>/orchestrator.log too, so bond-app diagnose
376
+ // sees it (issue #8: the errors were only on the terminal that ran `bond-app start`).
377
+ if (!asService && bootstrapFn === bootstrap) teeConsoleToLog(startDataDir);
378
+
353
379
  return new Promise<number>((resolve, reject) => {
354
380
  let shuttingDown = false;
355
381
  let restartRequested = false;
@@ -77,6 +77,11 @@ export class DefaultAgyLoginDriver implements AgyLoginDriver {
77
77
  } catch {
78
78
  // Ignore if set-option fails or older tmux
79
79
  }
80
+ // A command that exits at once (an agent missing from the image) leaves its error on the
81
+ // screen instead of closing the session: the login reads it rather than a blank pane.
82
+ try {
83
+ await execFileAsync('tmux', ['set-option', '-t', sessionName, 'remain-on-exit', 'on']);
84
+ } catch {}
80
85
  }
81
86
 
82
87
  async captureTmuxPane(sessionName: string): Promise<string> {
@@ -136,6 +141,16 @@ export class DefaultAgyLoginDriver implements AgyLoginDriver {
136
141
  }
137
142
  }
138
143
 
144
+ /** The program a login command runs (`env BROWSER=true codex login` → codex). */
145
+ export function loginBinary(command: string): string | null {
146
+ const words = command.trim().split(/\s+/);
147
+ let i = 0;
148
+ if (words[i] === 'env') i++;
149
+ while (i < words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i])) i++;
150
+ const w = words[i] ?? '';
151
+ return /^[a-z][a-z0-9_-]*$/.test(w) ? w : null;
152
+ }
153
+
139
154
  /** The logins run the agent's CLI in the runner image: it has to be built first. */
140
155
  export const RUNNER_IMAGE_MISSING = 'Falta la imagen del runner: los logins de los agentes se hacen dentro de ella. Constrúyela en Ajustes → Imagen (tarda unos minutos) y vuelve a iniciar sesión';
141
156
 
@@ -152,7 +167,7 @@ export interface AgentLoginSpec {
152
167
  /** Before the URL shows: answer the CLI's menus (agy picks «Google OAuth»); throws to fail. */
153
168
  onPane(pane: string, send: (keys: string, literal?: boolean) => Promise<void>, first: boolean): Promise<void>;
154
169
  /** After the code: the result once ready ({content, email}), null while waiting; throws on failure. */
155
- collect(pane: string, readTokenFile: () => Promise<string | null>, readFile?: (path: string) => Promise<string | null>): Promise<{ content: string; email?: string } | null>;
170
+ collect(pane: string, readTokenFile: () => Promise<string | null>, readFile?: (path: string) => Promise<string | null>, ctx?: LoginContext): Promise<{ content: string; email?: string } | null>;
156
171
  /** Ms between typing the code and Enter (claude's TUI takes a paste, then the key). */
157
172
  enterDelayMs?: number;
158
173
  /** The file `collect`'s readTokenFile reads in the container (default: agy's token). */
@@ -331,6 +346,29 @@ export const COPILOT_LOGIN_SPEC: AgentLoginSpec = {
331
346
  export const AZURE_PROFILE_PATH = '/home/runner/.azure/azureProfile.json';
332
347
  export const AZURE_MSAL_PATH = '/home/runner/.azure/msal_token_cache.json';
333
348
 
349
+ /**
350
+ * The Azure tenant to sign in to (`az login --tenant`): a GUID or a domain such as
351
+ * contoso.onmicrosoft.com. The subscriptions may live in another tenant than the account's
352
+ * own (a guest), and Azure DevOps' PAT is unrelated to it.
353
+ */
354
+ export const AZURE_TENANT_RE = /^(?:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+)$/;
355
+
356
+ /** `az account tenant list` → [{id, name, domain}] (name: displayName, else the domain). */
357
+ export function parseAzureTenants(json: string): Array<{ id: string; name: string; domain: string }> {
358
+ try {
359
+ const list = JSON.parse(json) as Array<{ tenantId?: unknown; displayName?: unknown; defaultDomain?: unknown }>;
360
+ return (Array.isArray(list) ? list : [])
361
+ .filter((t) => typeof t?.tenantId === 'string')
362
+ .map((t) => ({
363
+ id: String(t.tenantId),
364
+ name: typeof t.displayName === 'string' && t.displayName ? t.displayName : typeof t.defaultDomain === 'string' ? t.defaultDomain : '',
365
+ domain: typeof t.defaultDomain === 'string' ? t.defaultDomain : '',
366
+ }));
367
+ } catch {
368
+ return [];
369
+ }
370
+ }
371
+
334
372
  export const AZURE_LOGIN_SPEC: AgentLoginSpec = {
335
373
  agent: 'azure',
336
374
  command: 'az login --use-device-code --output none',
@@ -349,7 +387,7 @@ export const AZURE_LOGIN_SPEC: AgentLoginSpec = {
349
387
  const m = /(https:\/\/(?:microsoft\.com\/devicelogin|login\.microsoft(?:online)?\.com\/[\w/.-]*device[\w/.-]*))\S*\s+and enter the code ([A-Z0-9]{6,12})/i.exec(text);
350
388
  return m ? { url: m[1], user_code: m[2] } : null;
351
389
  },
352
- async collect(pane, readProfile, readFile) {
390
+ async collect(pane, readProfile, readFile, ctx) {
353
391
  const text = pane.replace(ANSI, '');
354
392
  if (/No subscriptions found/i.test(text)) {
355
393
  throw new Error('La cuenta no tiene suscripciones de Azure en ese tenant: bond-app necesita al menos una');
@@ -365,7 +403,15 @@ export const AZURE_LOGIN_SPEC: AgentLoginSpec = {
365
403
  const msal = await readFile(AZURE_MSAL_PATH);
366
404
  if (!msal || !/"RefreshToken"/.test(msal)) return null;
367
405
  const chosen = subs.find((x) => x.default) ?? subs[0];
368
- const doc: AzureLoginDoc = { version: 1, profile, msal, subscription_id: chosen.id };
406
+ // The tenants' names for people (the profile may carry only their ids): ask az once, here.
407
+ let tenants: AzureLoginDoc['tenants'];
408
+ if (ctx) {
409
+ try {
410
+ const res = await ctx.exec(['az', 'account', 'tenant', 'list', '--output', 'json', '--only-show-errors']);
411
+ if (res.code === 0) tenants = parseAzureTenants(res.stdout);
412
+ } catch {}
413
+ }
414
+ const doc: AzureLoginDoc = { version: 1, profile, msal, subscription_id: chosen.id, ...(tenants?.length ? { tenants } : {}) };
369
415
  return { content: JSON.stringify(doc), email: chosen.user || 'Azure' };
370
416
  },
371
417
  };
@@ -381,6 +427,8 @@ export interface AgyLoginManagerOptions {
381
427
  onToken?: (content: string) => void;
382
428
  /** Overrides spec.callback.port (tests). */
383
429
  callbackPort?: number;
430
+ /** The login's program is not in the image (az: the next rebuild should add azure-cli). */
431
+ onMissingBinary?: (bin: string) => void;
384
432
  }
385
433
 
386
434
  export class AgyLoginManager {
@@ -395,6 +443,7 @@ export class AgyLoginManager {
395
443
  private maxDurationMs: number;
396
444
  private spec: AgentLoginSpec;
397
445
  private onToken?: (content: string) => void;
446
+ private onMissingBinary?: (bin: string) => void;
398
447
  private callbackServer: http.Server | null = null;
399
448
  /** Port the callback listener uses (tests pick a free one). */
400
449
  private callbackPort?: number;
@@ -410,6 +459,7 @@ export class AgyLoginManager {
410
459
  this.spec = options.spec ?? AGY_LOGIN_SPEC;
411
460
  this.onToken = options.onToken;
412
461
  this.callbackPort = options.callbackPort;
462
+ this.onMissingBinary = options.onMissingBinary;
413
463
  }
414
464
 
415
465
  getStatus(): AgyLoginSessionState {
@@ -455,7 +505,11 @@ export class AgyLoginManager {
455
505
  return null;
456
506
  }
457
507
 
458
- async start(): Promise<AgyLoginSessionState> {
508
+ /**
509
+ * `extraArgs` go after the spec's command, already validated by the caller (the Azure
510
+ * login's `--tenant <id or domain>`): never anything the person typed unchecked.
511
+ */
512
+ async start(extraArgs: string[] = []): Promise<AgyLoginSessionState> {
459
513
  await this.cancel();
460
514
 
461
515
  const id = crypto.randomBytes(4).toString('hex');
@@ -476,8 +530,20 @@ export class AgyLoginManager {
476
530
 
477
531
  try {
478
532
  await this.driver.spawnContainer(containerName, this.runnerImage);
533
+ // The agent has to be in the image (Ajustes → Agentes picks which go in): say so now,
534
+ // not after two minutes of an empty screen (issue #7).
535
+ const bin = loginBinary(this.spec.command);
536
+ if (bin && this.driver.execInContainer) {
537
+ const has = await this.driver.execInContainer(containerName, ['sh', '-c', 'command -v "$1" >/dev/null 2>&1 || [ -x "$HOME/.local/bin/$1" ]', 'sh', bin]);
538
+ if (has.code !== 0) {
539
+ this.onMissingBinary?.(bin);
540
+ throw new Error(bin === 'az'
541
+ ? 'azure-cli no está en la imagen del runner: la próxima reconstrucción lo incluye. Reconstruye la imagen en Ajustes → Imagen y vuelve a iniciar sesión'
542
+ : `${bin} no está en la imagen del runner: márcalo en Ajustes → Agentes y reconstruye la imagen (Ajustes → Imagen)`);
543
+ }
544
+ }
479
545
  if (this.spec.prepare) await this.spec.prepare(this.context(containerName));
480
- await this.driver.startTmuxSession(sessionName, containerName, this.spec.command);
546
+ await this.driver.startTmuxSession(sessionName, containerName, [this.spec.command, ...extraArgs].join(' '));
481
547
  await this.startPaneWatcher(sessionName, containerName);
482
548
  } catch (err: unknown) {
483
549
  await this.handleError((err as Error).message);
@@ -667,6 +733,7 @@ export class AgyLoginManager {
667
733
  pane,
668
734
  () => this.driver.readContainerTokenFile(containerName, this.spec.tokenPath),
669
735
  (file) => this.driver.readContainerTokenFile(containerName, file),
736
+ this.driver.execInContainer ? this.context(containerName) : undefined,
670
737
  );
671
738
  } catch (err: unknown) {
672
739
  await this.handleError((err as Error).message);
@@ -241,9 +241,9 @@ export function tail(text: string, lines = 20, maxChars = 2000): string {
241
241
  * Decision 2026-11-25 (git en el run): runs inside the container as `runner` (node), with a
242
242
  * JSON object on stdin — { name, email, branch, repos: [{dir, base}], creds: [{host, token}] }.
243
243
  * Sets the person's identity and push defaults, writes each host's token to
244
- * ~/.config/bond-app/git-credentials.d/<host> (0600) behind a credential helper, and a
245
- * global pre-push hook that only lets the run's branch through (fast-forward, no deletion,
246
- * nothing under .github/workflows). Tokens only travel on stdin. Plain JS on purpose: it is
244
+ * ~/.config/bond-app/git-credentials.d/<host> (0600) behind a credential helper. No push
245
+ * restrictions inside the run (decision 2026-11-27): the pre-push hook older versions
246
+ * installed is removed. Tokens only travel on stdin. Plain JS on purpose: it is
247
247
  * serialised with toString() and run with `node -e`.
248
248
  */
249
249
  function gitSetupInContainer() {
@@ -261,8 +261,6 @@ function gitSetupInContainer() {
261
261
  git('config', '--global', 'user.email', String(cfg.email));
262
262
  git('config', '--global', 'push.default', 'current');
263
263
  git('config', '--global', 'push.autoSetupRemote', 'true');
264
- git('config', '--global', 'core.hooksPath', hookDir);
265
- fs.writeFileSync(path.join(dir, 'git-push-branch'), String(cfg.branch) + '\n', { mode: 0o600 });
266
264
  for (const r of cfg.repos || []) {
267
265
  try { git('-C', String(r.dir), 'config', 'bondapp.base', String(r.base)); } catch (e) { /* not a checkout yet */ }
268
266
  }
@@ -288,29 +286,15 @@ function gitSetupInContainer() {
288
286
  try { git('config', '--global', '--unset-all', 'credential.helper'); } catch (e) { /* none set */ }
289
287
  git('config', '--global', 'credential.helper', '!' + helper);
290
288
  }
291
- fs.writeFileSync(path.join(hookDir, 'pre-push'), [
292
- '#!/bin/sh',
293
- '# bond-app: a push from the run only updates the run branch, fast-forward, and never',
294
- '# touches .github/workflows (the same barriers as the delivery).',
295
- 'branch=$(cat "$HOME/.config/bond-app/git-push-branch" 2>/dev/null)',
296
- 'zero=0000000000000000000000000000000000000000',
297
- 'base=$(git config bondapp.base 2>/dev/null || true)',
298
- 'while read -r lref lsha rref rsha; do',
299
- ' [ -n "$rref" ] || continue',
300
- ' if [ "$rref" != "refs/heads/$branch" ]; then echo "bond-app: desde el run solo se hace push de su rama ($branch), no de $rref" >&2; exit 1; fi',
301
- ' if [ "$lsha" = "$zero" ]; then echo "bond-app: la rama del run no se borra" >&2; exit 1; fi',
302
- ' from=',
303
- ' if [ "$rsha" != "$zero" ]; then',
304
- ' if ! git cat-file -e "$rsha^{commit}" 2>/dev/null; then echo "bond-app: la rama remota tiene commits que no tienes; haz git fetch y unelos antes del push" >&2; exit 1; fi',
305
- ' if ! git merge-base --is-ancestor "$rsha" "$lsha"; then echo "bond-app: push que no es fast-forward rechazado (desde el run no se fuerza)" >&2; exit 1; fi',
306
- ' from=$rsha',
307
- ' elif [ -n "$base" ]; then',
308
- ' from=$(git merge-base "$lsha" "origin/$base" 2>/dev/null || true)',
309
- ' fi',
310
- ' if [ -n "$from" ] && [ -n "$(git diff --name-only "$from" "$lsha" -- .github/workflows)" ]; then echo "bond-app: el push cambia .github/workflows; eso no sale de un run" >&2; exit 1; fi',
311
- 'done',
312
- 'exit 0',
313
- ''].join('\n'), { mode: 0o700 });
289
+ // Decision 2026-11-27: no push restrictions from bond-app inside the run (the person's
290
+ // call). A run configured by an older bond-app had a global pre-push hook behind
291
+ // core.hooksPath, which also hid the repos' own hooks: both go.
292
+ try {
293
+ const current = execFileSync('git', ['config', '--global', '--get', 'core.hooksPath'], { encoding: 'utf8' }).trim();
294
+ if (current === hookDir) git('config', '--global', '--unset', 'core.hooksPath');
295
+ } catch (e) { /* not set */ }
296
+ fs.rmSync(path.join(hookDir, 'pre-push'), { force: true });
297
+ fs.rmSync(path.join(dir, 'git-push-branch'), { force: true });
314
298
  }
315
299
 
316
300
  /** The command that runs gitSetupInContainer (its config on stdin). */
@@ -208,6 +208,29 @@ export interface Diagnosis {
208
208
  summary: string;
209
209
  }
210
210
 
211
+ /**
212
+ * The end of each agent login's trace, for the issue's text: a login that fails is told by its
213
+ * last attempt (start, URL, error and the end of the screen), and the zip may not get attached.
214
+ */
215
+ export function loginTails(dataDir: string): string[] {
216
+ let names: string[] = [];
217
+ try {
218
+ names = fs.readdirSync(dataDir).filter((n) => /^login-[a-z]+\.log$/.test(n)).sort();
219
+ } catch {
220
+ return [];
221
+ }
222
+ const out: string[] = [];
223
+ for (const n of names) {
224
+ const text = tailFile(path.join(dataDir, n), 16 * 1024) ?? '';
225
+ // The last attempt: from its «start» line on.
226
+ const lines = text.split('\n');
227
+ let from = 0;
228
+ lines.forEach((l, i) => { if (/^\S+ [a-z]+ start/.test(l)) from = i; });
229
+ out.push(`## Login: ${n.replace(/^login-|\.log$/g, '')} (último intento)`, '', '```', lines.slice(from).join('\n').trim().split('\n').slice(-70).join('\n'), '```', '');
230
+ }
231
+ return out;
232
+ }
233
+
211
234
  export async function collectDiagnosis(o: DiagnoseOptions): Promise<Diagnosis> {
212
235
  const secrets = knownSecrets(o.dataDir);
213
236
  const clean = (s: string) => redactSecrets(s, secrets);
@@ -272,6 +295,7 @@ export async function collectDiagnosis(o: DiagnoseOptions): Promise<Diagnosis> {
272
295
  '',
273
296
  failing.length ? failing.join('\n') : 'Todo en orden.',
274
297
  '',
298
+ ...loginTails(o.dataDir),
275
299
  '## Final del log del orquestador',
276
300
  '',
277
301
  '```',
@@ -76,6 +76,9 @@ const HUB_OPINION_GAPS = new Set(['missing_repo', 'agent_not_ready']);
76
76
  /** A full context is relaunched on its own once in this window per agent; a second time waits for the person. */
77
77
  export const AUTO_RELAUNCH_WINDOW_MS = 30 * 60 * 1000;
78
78
 
79
+ /** Setting: azure-cli is wanted in the runner image (its login was tried without it). */
80
+ export const AZURE_CLI_WANTED = 'image_azure_cli';
81
+
79
82
  /** az's config in a run: no prompts about subscriptions, no telemetry. */
80
83
  const AZURE_RUN_CONFIG = '[core]\nlogin_experience_v2 = off\ncollect_telemetry = false\n';
81
84
 
@@ -406,6 +409,8 @@ export class Orchestrator {
406
409
  driver: agyLoginDriver,
407
410
  spec: AZURE_LOGIN_SPEC,
408
411
  maxDurationMs: 15 * 60 * 1000,
412
+ // az missing from the image: the next rebuild puts azure-cli in.
413
+ onMissingBinary: () => this.settingsRepo.setSetting(AZURE_CLI_WANTED, '1'),
409
414
  onToken: (content) => this.settingsRepo.setAzureLogin(JSON.parse(content)),
410
415
  });
411
416
  if (this.config.dataDir) {
@@ -415,6 +420,7 @@ export class Orchestrator {
415
420
 
416
421
  async start(): Promise<void> {
417
422
  await this.reconcile({ boot: true });
423
+ void this.refreshImageAgents();
418
424
  this.watchdog.start();
419
425
  // Periodic reconcile for retry of cleanup_pending and orphan collection (H-A, N3, M3)
420
426
  if (this.config.reconcileIntervalMs > 0) {
@@ -997,11 +1003,10 @@ export class Orchestrator {
997
1003
  /**
998
1004
  * Git inside the run (decision 2026-11-25): the person's identity, `push.default=current`
999
1005
  * with autoSetupRemote, and — with `withCredentials` — a credential helper reading each
1000
- * host's token from a 0600 file (written by stdin, never argv/env/image) plus a pre-push
1001
- * hook that only lets the run's branch through: no other branch, no deletion, no
1002
- * non-fast-forward, nothing under .github/workflows (the delivery's own barriers). The
1003
- * hook is a guardrail, not a lock: the delivery still checks everything on its push.
1004
- * `repos` are the run's checkouts with their base (the hook diffs against it).
1006
+ * host's token from a 0600 file (written by stdin, never argv/env/image). No push
1007
+ * restrictions inside the run (decision 2026-11-27, the person's): the agents push as the
1008
+ * person would; bond-app's own delivery keeps its checks on its push.
1009
+ * `repos` are the run's checkouts with their base (bondapp.base, read by the handoff).
1005
1010
  */
1006
1011
  async prepareGit(
1007
1012
  containerName: string,
@@ -5496,6 +5501,9 @@ export class Orchestrator {
5496
5501
  // Without an explicit list, the image keeps the agents chosen in the wizard: a bare
5497
5502
  // «Rebuild…» from Ajustes used to drop to the minimal image (pi), losing agy/claude.
5498
5503
  const agents = extras.agents ?? this.selectedImageAgents();
5504
+ // azure-cli is heavy and left out by default (SKIP_AZ=1), but Azure DevOps, the Azure
5505
+ // session in runs and its login need it: in when any of them is set up or was tried.
5506
+ if (extras.skip_az === undefined && this.wantsAzureCli()) extras = { ...extras, skip_az: false };
5499
5507
  // Same for the developer tools (plan bond-app-ajustes-imagen P2): the chosen groups
5500
5508
  // and extra packages unless the request names its own.
5501
5509
  const sel = this.settingsRepo?.getSetupSelection?.();
@@ -5513,6 +5521,7 @@ export class Orchestrator {
5513
5521
  },
5514
5522
  });
5515
5523
  this.rebuildStatus = { ...this.rebuildStatus, running: false, finished_at: new Date().toISOString(), ok: true, detail: 'Imagen lista' };
5524
+ await this.refreshImageAgents();
5516
5525
  return {
5517
5526
  image: this.config.runnerImage,
5518
5527
  rebuilt_at: new Date().toISOString(),
@@ -5526,6 +5535,28 @@ export class Orchestrator {
5526
5535
  }
5527
5536
  }
5528
5537
 
5538
+ /** azure-cli goes in the image: Azure DevOps or an Azure session configured, or its login tried (issue: Azure login timing out). */
5539
+ wantsAzureCli(): boolean {
5540
+ try {
5541
+ return Boolean(this.settingsRepo.getAzureDevOpsSummary()?.configured)
5542
+ || Boolean(this.settingsRepo.getAzureLogin())
5543
+ || this.settingsRepo.getSetting(AZURE_CLI_WANTED) === '1';
5544
+ } catch {
5545
+ return false;
5546
+ }
5547
+ }
5548
+
5549
+ /**
5550
+ * Tell the ticket checks which agents the runner image carries (its manifest; cached by
5551
+ * image id, so cheap). Before writing a ticket, at start and after a rebuild.
5552
+ */
5553
+ async refreshImageAgents(): Promise<void> {
5554
+ try {
5555
+ const info = await this.dockerClient.inspectRunnerImage(this.config.runnerImage);
5556
+ if (info.agents?.length) this.ticketRepo.setImageAgents(info.agents);
5557
+ } catch {}
5558
+ }
5559
+
5529
5560
  /** Where the image build is (or how the last one ended), for Ajustes' progress bar. */
5530
5561
  getRebuildStatus(): typeof this.rebuildStatus {
5531
5562
  return { ...this.rebuildStatus };
@@ -5553,6 +5584,7 @@ export class Orchestrator {
5553
5584
  } catch {
5554
5585
  image = { present: false };
5555
5586
  }
5587
+ if (image.agents?.length) this.ticketRepo.setImageAgents(image.agents);
5556
5588
  const selection = this.settingsRepo.getSetupSelection();
5557
5589
  return buildSetupState({
5558
5590
  setup_done: selection.setup_done,
@@ -73,12 +73,14 @@ export interface AzureLoginDoc {
73
73
  /** ~/.azure/msal_token_cache.json (the tokens: never shown, never logged). */
74
74
  msal: string;
75
75
  subscription_id: string | null;
76
+ /** The tenants' names (az account tenant list at login), for people: ids are not. */
77
+ tenants?: Array<{ id: string; name: string; domain: string }>;
76
78
  }
77
79
 
78
- type AzureProfile = { subscriptions?: Array<{ id?: unknown; name?: unknown; tenantId?: unknown; isDefault?: unknown; user?: { name?: unknown } }> };
80
+ type AzureProfile = { subscriptions?: Array<{ id?: unknown; name?: unknown; tenantId?: unknown; tenantDisplayName?: unknown; tenantDefaultDomain?: unknown; isDefault?: unknown; user?: { name?: unknown } }> };
79
81
 
80
82
  /** The subscriptions of an azureProfile.json ({id, name, tenant_id, default}); [] when unreadable. */
81
- export function azureSubscriptions(profileText: string): Array<{ id: string; name: string; tenant_id: string; default: boolean; user: string }> {
83
+ export function azureSubscriptions(profileText: string): Array<{ id: string; name: string; tenant_id: string; tenant_name: string; default: boolean; user: string }> {
82
84
  try {
83
85
  const doc = JSON.parse(profileText.replace(/^\uFEFF/, '')) as AzureProfile;
84
86
  return (doc.subscriptions ?? [])
@@ -87,6 +89,10 @@ export function azureSubscriptions(profileText: string): Array<{ id: string; nam
87
89
  id: String(s.id),
88
90
  name: typeof s.name === 'string' ? s.name : String(s.id),
89
91
  tenant_id: typeof s.tenantId === 'string' ? s.tenantId : '',
92
+ // az writes the tenant's name and domain in its profile: what the ticket's selector shows.
93
+ tenant_name: typeof s.tenantDisplayName === 'string' && s.tenantDisplayName
94
+ ? s.tenantDisplayName
95
+ : typeof s.tenantDefaultDomain === 'string' ? s.tenantDefaultDomain : '',
90
96
  default: s.isDefault === true,
91
97
  user: typeof s.user?.name === 'string' ? s.user.name : '',
92
98
  }));
@@ -104,14 +110,16 @@ export function azureLoginSummary(configJson: string | null | undefined, updated
104
110
  } catch {
105
111
  return { configured: false };
106
112
  }
107
- const subs = azureSubscriptions(doc.profile ?? '');
113
+ const names = new Map((doc.tenants ?? []).map((t) => [t.id, t.name || t.domain]));
114
+ const subs = azureSubscriptions(doc.profile ?? '').map((x) => (x.tenant_name ? x : { ...x, tenant_name: names.get(x.tenant_id) ?? '' }));
108
115
  const chosen = subs.find((s) => s.id === doc.subscription_id) ?? subs.find((s) => s.default) ?? subs[0] ?? null;
109
116
  const out: AzureLoginSummary = {
110
117
  configured: true,
111
118
  user: chosen?.user || subs[0]?.user || undefined,
112
119
  tenant_id: chosen?.tenant_id || undefined,
120
+ ...(chosen?.tenant_name ? { tenant_name: chosen.tenant_name } : {}),
113
121
  subscription: chosen ? { id: chosen.id, name: chosen.name } : null,
114
- subscriptions: subs.map((s) => ({ id: s.id, name: s.name, tenant_id: s.tenant_id })),
122
+ subscriptions: subs.map((s) => ({ id: s.id, name: s.name, tenant_id: s.tenant_id, ...(s.tenant_name ? { tenant_name: s.tenant_name } : {}) })),
115
123
  };
116
124
  if (updatedAt) {
117
125
  out.updated_at = updatedAt;
@@ -174,6 +174,18 @@ export class TicketRepository {
174
174
  this.available = opts.imageAgents ?? imageAgents();
175
175
  }
176
176
 
177
+ /**
178
+ * The agents the runner image really carries (its /opt/runner-agents manifest), as the
179
+ * orchestrator reads it: the hub-team check used BOND_APP_IMAGE_AGENTS, which defaults to
180
+ * pi only, and refused codex or claude in an image that carries them. That variable still
181
+ * wins when it is set (tests, a pinned setup).
182
+ */
183
+ setImageAgents(list: string[]): void {
184
+ if (process.env.BOND_APP_IMAGE_AGENTS) return;
185
+ const valid = list.filter((a) => isValidAgent(a));
186
+ if (valid.length > 0) this.available = valid;
187
+ }
188
+
177
189
  /**
178
190
  * P5 (user, 2026-11-11): a hub team only starts agents the image carries; refuse the
179
191
  * others when the ticket is written, not when the run fails.
package/src/server/app.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { AZURE_TENANT_RE } from '../core/agy-login.ts';
1
2
  import http, { IncomingMessage, ServerResponse, Server } from 'node:http';
2
3
  import { URL } from 'node:url';
3
4
  import crypto from 'node:crypto';
@@ -172,6 +173,8 @@ export function createServer(orchestrator: Orchestrator, hooks: ServerHooks = {}
172
173
  sendJson(400, { error: "Field 'title' and one of 'repo_url', 'repos' or 'hub_url' are required" });
173
174
  return;
174
175
  }
176
+ // The hub-team check needs the agents the image really carries.
177
+ await orchestrator.refreshImageAgents();
175
178
  try {
176
179
  // Plan bond-app-ticket-desde-pr P1: from a PR or branch, bond-app resolves it and
177
180
  // takes repo, branches, id (and title/story if missing) from it.
@@ -467,6 +470,7 @@ export function createServer(orchestrator: Orchestrator, hooks: ServerHooks = {}
467
470
  throw new ConflictError(`Cannot change ${pinned.join(', ')} while run '${active.id}' is active`);
468
471
  }
469
472
  try {
473
+ await orchestrator.refreshImageAgents();
470
474
  const updated = orchestrator.ticketRepo.update(ticketId, body);
471
475
  if (!updated) {
472
476
  sendJson(404, { error: 'Ticket not found' });
@@ -995,7 +999,17 @@ export function createServer(orchestrator: Orchestrator, hooks: ServerHooks = {}
995
999
  }
996
1000
  }
997
1001
  if (sub === '/start' && method === 'POST') {
998
- const status = await loginManager.start();
1002
+ // The Azure login may name its tenant (subscriptions in another tenant than the account's).
1003
+ const body = loginMatch[1] === 'azure' ? await readJson(4096) : {};
1004
+ const extra: string[] = [];
1005
+ if (loginMatch[1] === 'azure' && body.tenant !== undefined && body.tenant !== null && body.tenant !== '') {
1006
+ if (typeof body.tenant !== 'string' || !AZURE_TENANT_RE.test(body.tenant.trim())) {
1007
+ sendJson(400, { error: "'tenant' must be a tenant id (GUID) or domain (contoso.onmicrosoft.com)" });
1008
+ return;
1009
+ }
1010
+ extra.push('--tenant', body.tenant.trim());
1011
+ }
1012
+ const status = await loginManager.start(extra);
999
1013
  sendJson(200, status);
1000
1014
  return;
1001
1015
  }
package/src/types.ts CHANGED
@@ -404,9 +404,12 @@ export interface AzureLoginSummary {
404
404
  configured: boolean;
405
405
  user?: string;
406
406
  tenant_id?: string;
407
+ /** That tenant's name, when known (az's profile or its tenant list at login). */
408
+ tenant_name?: string;
407
409
  /** The default subscription for the runs (Ajustes; a ticket may pick another, P2). */
408
410
  subscription?: { id: string; name: string } | null;
409
- subscriptions?: Array<{ id: string; name: string; tenant_id: string }>;
411
+ /** Every subscription the session sees, with its tenant (and the tenant's name when az knows it). */
412
+ subscriptions?: Array<{ id: string; name: string; tenant_id: string; tenant_name?: string }>;
410
413
  updated_at?: string;
411
414
  /** The refresh token lapses about 90 days after the login (D5: runs never refresh the store). */
412
415
  expires_at?: string;