@jmanuelcorral/bond-app 0.3.5 → 0.3.7

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.5",
3
+ "version": "0.3.7",
4
4
  "description": "Local orchestrator and hub-container runner for multi-agent tickets",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -24,7 +24,7 @@ SUPI_VERSION=11.0.1
24
24
  # 1.16.4: antes de esa versión bond no tiene comando `tui` (spike runner/SPIKE-BOND.md).
25
25
  # `bond-app setup` exige al menos esta versión en la máquina: hasta 1.16.8 bond traía su propio
26
26
  # bin `bond-app` (con una bond-app 0.1.x dentro) y npm no deja instalar bond-app encima.
27
- BOND_VERSION=1.17.0
27
+ BOND_VERSION=1.17.1
28
28
 
29
29
  # gh y azure-cli salen de los repos apt oficiales (GitHub y Microsoft); se dejan
30
30
  # en «latest» del repo. AZURE_CLI_VERSION admite el pin «2.xx.y» (sufijo ~bookworm
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;
@@ -167,7 +167,7 @@ export interface AgentLoginSpec {
167
167
  /** Before the URL shows: answer the CLI's menus (agy picks «Google OAuth»); throws to fail. */
168
168
  onPane(pane: string, send: (keys: string, literal?: boolean) => Promise<void>, first: boolean): Promise<void>;
169
169
  /** After the code: the result once ready ({content, email}), null while waiting; throws on failure. */
170
- 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>;
171
171
  /** Ms between typing the code and Enter (claude's TUI takes a paste, then the key). */
172
172
  enterDelayMs?: number;
173
173
  /** The file `collect`'s readTokenFile reads in the container (default: agy's token). */
@@ -346,6 +346,29 @@ export const COPILOT_LOGIN_SPEC: AgentLoginSpec = {
346
346
  export const AZURE_PROFILE_PATH = '/home/runner/.azure/azureProfile.json';
347
347
  export const AZURE_MSAL_PATH = '/home/runner/.azure/msal_token_cache.json';
348
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
+
349
372
  export const AZURE_LOGIN_SPEC: AgentLoginSpec = {
350
373
  agent: 'azure',
351
374
  command: 'az login --use-device-code --output none',
@@ -364,7 +387,7 @@ export const AZURE_LOGIN_SPEC: AgentLoginSpec = {
364
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);
365
388
  return m ? { url: m[1], user_code: m[2] } : null;
366
389
  },
367
- async collect(pane, readProfile, readFile) {
390
+ async collect(pane, readProfile, readFile, ctx) {
368
391
  const text = pane.replace(ANSI, '');
369
392
  if (/No subscriptions found/i.test(text)) {
370
393
  throw new Error('La cuenta no tiene suscripciones de Azure en ese tenant: bond-app necesita al menos una');
@@ -380,7 +403,15 @@ export const AZURE_LOGIN_SPEC: AgentLoginSpec = {
380
403
  const msal = await readFile(AZURE_MSAL_PATH);
381
404
  if (!msal || !/"RefreshToken"/.test(msal)) return null;
382
405
  const chosen = subs.find((x) => x.default) ?? subs[0];
383
- 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 } : {}) };
384
415
  return { content: JSON.stringify(doc), email: chosen.user || 'Azure' };
385
416
  },
386
417
  };
@@ -474,7 +505,11 @@ export class AgyLoginManager {
474
505
  return null;
475
506
  }
476
507
 
477
- 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> {
478
513
  await this.cancel();
479
514
 
480
515
  const id = crypto.randomBytes(4).toString('hex');
@@ -508,7 +543,7 @@ export class AgyLoginManager {
508
543
  }
509
544
  }
510
545
  if (this.spec.prepare) await this.spec.prepare(this.context(containerName));
511
- await this.driver.startTmuxSession(sessionName, containerName, this.spec.command);
546
+ await this.driver.startTmuxSession(sessionName, containerName, [this.spec.command, ...extraArgs].join(' '));
512
547
  await this.startPaneWatcher(sessionName, containerName);
513
548
  } catch (err: unknown) {
514
549
  await this.handleError((err as Error).message);
@@ -698,6 +733,7 @@ export class AgyLoginManager {
698
733
  pane,
699
734
  () => this.driver.readContainerTokenFile(containerName, this.spec.tokenPath),
700
735
  (file) => this.driver.readContainerTokenFile(containerName, file),
736
+ this.driver.execInContainer ? this.context(containerName) : undefined,
701
737
  );
702
738
  } catch (err: unknown) {
703
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). */
@@ -1003,11 +1003,10 @@ export class Orchestrator {
1003
1003
  /**
1004
1004
  * Git inside the run (decision 2026-11-25): the person's identity, `push.default=current`
1005
1005
  * with autoSetupRemote, and — with `withCredentials` — a credential helper reading each
1006
- * host's token from a 0600 file (written by stdin, never argv/env/image) plus a pre-push
1007
- * hook that only lets the run's branch through: no other branch, no deletion, no
1008
- * non-fast-forward, nothing under .github/workflows (the delivery's own barriers). The
1009
- * hook is a guardrail, not a lock: the delivery still checks everything on its push.
1010
- * `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).
1011
1010
  */
1012
1011
  async prepareGit(
1013
1012
  containerName: string,
@@ -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;
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';
@@ -998,7 +999,17 @@ export function createServer(orchestrator: Orchestrator, hooks: ServerHooks = {}
998
999
  }
999
1000
  }
1000
1001
  if (sub === '/start' && method === 'POST') {
1001
- 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);
1002
1013
  sendJson(200, status);
1003
1014
  return;
1004
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;