@jmanuelcorral/bond-app 0.3.3 → 0.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/core/agy-login.ts +64 -0
- package/src/core/diagnose.ts +29 -0
- package/src/core/orchestrator.ts +33 -0
- package/src/db/ticket-repo.ts +12 -0
- package/src/server/app.ts +3 -0
package/package.json
CHANGED
package/src/core/agy-login.ts
CHANGED
|
@@ -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
|
|
|
@@ -381,6 +396,8 @@ export interface AgyLoginManagerOptions {
|
|
|
381
396
|
onToken?: (content: string) => void;
|
|
382
397
|
/** Overrides spec.callback.port (tests). */
|
|
383
398
|
callbackPort?: number;
|
|
399
|
+
/** The login's program is not in the image (az: the next rebuild should add azure-cli). */
|
|
400
|
+
onMissingBinary?: (bin: string) => void;
|
|
384
401
|
}
|
|
385
402
|
|
|
386
403
|
export class AgyLoginManager {
|
|
@@ -395,10 +412,13 @@ export class AgyLoginManager {
|
|
|
395
412
|
private maxDurationMs: number;
|
|
396
413
|
private spec: AgentLoginSpec;
|
|
397
414
|
private onToken?: (content: string) => void;
|
|
415
|
+
private onMissingBinary?: (bin: string) => void;
|
|
398
416
|
private callbackServer: http.Server | null = null;
|
|
399
417
|
/** Port the callback listener uses (tests pick a free one). */
|
|
400
418
|
private callbackPort?: number;
|
|
401
419
|
public inMemoryToken: string | null = null;
|
|
420
|
+
/** The agent's last screen, for the trace of a failed login. */
|
|
421
|
+
private lastPane = '';
|
|
402
422
|
|
|
403
423
|
constructor(options: AgyLoginManagerOptions) {
|
|
404
424
|
this.driver = options.driver || new DefaultAgyLoginDriver();
|
|
@@ -408,6 +428,7 @@ export class AgyLoginManager {
|
|
|
408
428
|
this.spec = options.spec ?? AGY_LOGIN_SPEC;
|
|
409
429
|
this.onToken = options.onToken;
|
|
410
430
|
this.callbackPort = options.callbackPort;
|
|
431
|
+
this.onMissingBinary = options.onMissingBinary;
|
|
411
432
|
}
|
|
412
433
|
|
|
413
434
|
getStatus(): AgyLoginSessionState {
|
|
@@ -463,6 +484,8 @@ export class AgyLoginManager {
|
|
|
463
484
|
this.activeContainerName = containerName;
|
|
464
485
|
this.activeSessionName = sessionName;
|
|
465
486
|
this.state = { status: 'starting' };
|
|
487
|
+
this.lastPane = '';
|
|
488
|
+
this.trace('start', `imagen ${this.runnerImage}, contenedor ${containerName}, máquina ${process.platform}/${process.arch}`);
|
|
466
489
|
|
|
467
490
|
this.timeoutTimer = setTimeout(async () => {
|
|
468
491
|
if (this.state.status !== 'success' && this.state.status !== 'idle') {
|
|
@@ -472,6 +495,18 @@ export class AgyLoginManager {
|
|
|
472
495
|
|
|
473
496
|
try {
|
|
474
497
|
await this.driver.spawnContainer(containerName, this.runnerImage);
|
|
498
|
+
// The agent has to be in the image (Ajustes → Agentes picks which go in): say so now,
|
|
499
|
+
// not after two minutes of an empty screen (issue #7).
|
|
500
|
+
const bin = loginBinary(this.spec.command);
|
|
501
|
+
if (bin && this.driver.execInContainer) {
|
|
502
|
+
const has = await this.driver.execInContainer(containerName, ['sh', '-c', 'command -v "$1" >/dev/null 2>&1 || [ -x "$HOME/.local/bin/$1" ]', 'sh', bin]);
|
|
503
|
+
if (has.code !== 0) {
|
|
504
|
+
this.onMissingBinary?.(bin);
|
|
505
|
+
throw new Error(bin === 'az'
|
|
506
|
+
? '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'
|
|
507
|
+
: `${bin} no está en la imagen del runner: márcalo en Ajustes → Agentes y reconstruye la imagen (Ajustes → Imagen)`);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
475
510
|
if (this.spec.prepare) await this.spec.prepare(this.context(containerName));
|
|
476
511
|
await this.driver.startTmuxSession(sessionName, containerName, this.spec.command);
|
|
477
512
|
await this.startPaneWatcher(sessionName, containerName);
|
|
@@ -505,6 +540,7 @@ export class AgyLoginManager {
|
|
|
505
540
|
|
|
506
541
|
try {
|
|
507
542
|
const pane = await this.driver.captureTmuxPane(sessionName);
|
|
543
|
+
if (pane) this.lastPane = pane;
|
|
508
544
|
if (first) {
|
|
509
545
|
first = false;
|
|
510
546
|
await this.spec.onPane(pane, (keys, literal) => this.driver.sendTmuxKeys(sessionName, keys, literal), true);
|
|
@@ -526,6 +562,7 @@ export class AgyLoginManager {
|
|
|
526
562
|
...(found.user_code ? { user_code: found.user_code } : {}),
|
|
527
563
|
...(this.spec.device ? { device: true } : {}),
|
|
528
564
|
};
|
|
565
|
+
this.trace('url', `${(/^https?:\/\/([^/?#]+)/.exec(found.url) ?? [])[1] ?? '?'}${found.user_code ? ' (código de dispositivo)' : ''}`);
|
|
529
566
|
// Device flow: nothing to paste back; watch for the result right away.
|
|
530
567
|
if (this.spec.device) await this.startTokenFileWatcher(containerName, sessionName);
|
|
531
568
|
// Loopback return (codex): catch it here so nothing has to be pasted.
|
|
@@ -654,6 +691,7 @@ export class AgyLoginManager {
|
|
|
654
691
|
|
|
655
692
|
try {
|
|
656
693
|
const pane = this.spec.agent === 'agy' ? '' : await this.driver.captureTmuxPane(sessionName);
|
|
694
|
+
if (pane) this.lastPane = pane;
|
|
657
695
|
let result: { content: string; email?: string } | null;
|
|
658
696
|
try {
|
|
659
697
|
result = await this.spec.collect(
|
|
@@ -692,6 +730,7 @@ export class AgyLoginManager {
|
|
|
692
730
|
status: 'success',
|
|
693
731
|
email: result.email,
|
|
694
732
|
};
|
|
733
|
+
this.trace('success');
|
|
695
734
|
} catch {}
|
|
696
735
|
};
|
|
697
736
|
|
|
@@ -737,7 +776,32 @@ export class AgyLoginManager {
|
|
|
737
776
|
return result;
|
|
738
777
|
}
|
|
739
778
|
|
|
779
|
+
/**
|
|
780
|
+
* The login's trace for `bond-app diagnose` (issue: logins timing out on a Mac with no clue):
|
|
781
|
+
* <dataDir>/login-<agent>.log, 0600, appended. On a failure, the end of the agent's screen,
|
|
782
|
+
* without OAuth codes, tokens or keys. Never throws.
|
|
783
|
+
*/
|
|
784
|
+
private trace(event: string, detail = '', withPane = false): void {
|
|
785
|
+
if (!this.dataDir || this.dataDir === ':memory:') return;
|
|
786
|
+
try {
|
|
787
|
+
const lines = [`${new Date().toISOString()} ${this.spec.agent} ${event}${detail ? `: ${detail}` : ''}`];
|
|
788
|
+
if (withPane && this.lastPane) {
|
|
789
|
+
const screen = this.lastPane
|
|
790
|
+
.replace(/\x1b\[[0-9;?]*[a-zA-Z]|\x1b\][^\x07]*\x07/g, '')
|
|
791
|
+
.split('\n').slice(-60).join('\n')
|
|
792
|
+
.replace(/([?&](?:code|token|access_token|id_token|refresh_token)=)[^&\s]+/gi, '$1***')
|
|
793
|
+
.replace(/\b(?:sk-|gh[pousr]_|github_pat_|ya29\.)[A-Za-z0-9._-]{12,}/g, '***')
|
|
794
|
+
.replace(/\beyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g, '***');
|
|
795
|
+
lines.push('--- pantalla del agente (final) ---', screen, '---');
|
|
796
|
+
}
|
|
797
|
+
const file = path.join(this.dataDir, `login-${this.spec.agent}.log`);
|
|
798
|
+
fs.appendFileSync(file, lines.join('\n') + '\n', { mode: 0o600 });
|
|
799
|
+
restrictPathSync(file, 0o600);
|
|
800
|
+
} catch {}
|
|
801
|
+
}
|
|
802
|
+
|
|
740
803
|
private async handleError(message: string): Promise<void> {
|
|
804
|
+
this.trace('error', message, true);
|
|
741
805
|
await this.cleanupResources();
|
|
742
806
|
this.state = {
|
|
743
807
|
status: 'error',
|
package/src/core/diagnose.ts
CHANGED
|
@@ -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);
|
|
@@ -224,6 +247,7 @@ export async function collectDiagnosis(o: DiagnoseOptions): Promise<Diagnosis> {
|
|
|
224
247
|
`bond ${await cmd('bond', ['--version'])}`,
|
|
225
248
|
`hc ${await cmd('hc', ['--version'])}`,
|
|
226
249
|
`herdr-app ${await cmd('herdr-app', ['--version'])}`,
|
|
250
|
+
`tmux ${await cmd('tmux', ['-V'])}`,
|
|
227
251
|
'',
|
|
228
252
|
'## docker version',
|
|
229
253
|
await cmd('docker', ['version']),
|
|
@@ -247,6 +271,10 @@ export async function collectDiagnosis(o: DiagnoseOptions): Promise<Diagnosis> {
|
|
|
247
271
|
if (o.service.unitPath) add(`service/${path.basename(o.service.unitPath)}`, tailFile(o.service.unitPath, 64 * 1024));
|
|
248
272
|
}
|
|
249
273
|
add('runs.json', runsSummary(o.dataDir));
|
|
274
|
+
// The agents' logins (Ajustes): each attempt, and the end of the screen when one failed.
|
|
275
|
+
try {
|
|
276
|
+
for (const f of fs.readdirSync(o.dataDir).filter((n) => /^login-[a-z]+\.log$/.test(n))) add(`logins/${f}`, tailFile(path.join(o.dataDir, f), 256 * 1024));
|
|
277
|
+
} catch {}
|
|
250
278
|
const installed = path.join(o.herdrAppHome, 'installed.json');
|
|
251
279
|
add('herdr-app/installed.json', tailFile(installed, 64 * 1024));
|
|
252
280
|
|
|
@@ -267,6 +295,7 @@ export async function collectDiagnosis(o: DiagnoseOptions): Promise<Diagnosis> {
|
|
|
267
295
|
'',
|
|
268
296
|
failing.length ? failing.join('\n') : 'Todo en orden.',
|
|
269
297
|
'',
|
|
298
|
+
...loginTails(o.dataDir),
|
|
270
299
|
'## Final del log del orquestador',
|
|
271
300
|
'',
|
|
272
301
|
'```',
|
package/src/core/orchestrator.ts
CHANGED
|
@@ -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) {
|
|
@@ -5496,6 +5502,9 @@ export class Orchestrator {
|
|
|
5496
5502
|
// Without an explicit list, the image keeps the agents chosen in the wizard: a bare
|
|
5497
5503
|
// «Rebuild…» from Ajustes used to drop to the minimal image (pi), losing agy/claude.
|
|
5498
5504
|
const agents = extras.agents ?? this.selectedImageAgents();
|
|
5505
|
+
// azure-cli is heavy and left out by default (SKIP_AZ=1), but Azure DevOps, the Azure
|
|
5506
|
+
// session in runs and its login need it: in when any of them is set up or was tried.
|
|
5507
|
+
if (extras.skip_az === undefined && this.wantsAzureCli()) extras = { ...extras, skip_az: false };
|
|
5499
5508
|
// Same for the developer tools (plan bond-app-ajustes-imagen P2): the chosen groups
|
|
5500
5509
|
// and extra packages unless the request names its own.
|
|
5501
5510
|
const sel = this.settingsRepo?.getSetupSelection?.();
|
|
@@ -5513,6 +5522,7 @@ export class Orchestrator {
|
|
|
5513
5522
|
},
|
|
5514
5523
|
});
|
|
5515
5524
|
this.rebuildStatus = { ...this.rebuildStatus, running: false, finished_at: new Date().toISOString(), ok: true, detail: 'Imagen lista' };
|
|
5525
|
+
await this.refreshImageAgents();
|
|
5516
5526
|
return {
|
|
5517
5527
|
image: this.config.runnerImage,
|
|
5518
5528
|
rebuilt_at: new Date().toISOString(),
|
|
@@ -5526,6 +5536,28 @@ export class Orchestrator {
|
|
|
5526
5536
|
}
|
|
5527
5537
|
}
|
|
5528
5538
|
|
|
5539
|
+
/** azure-cli goes in the image: Azure DevOps or an Azure session configured, or its login tried (issue: Azure login timing out). */
|
|
5540
|
+
wantsAzureCli(): boolean {
|
|
5541
|
+
try {
|
|
5542
|
+
return Boolean(this.settingsRepo.getAzureDevOpsSummary()?.configured)
|
|
5543
|
+
|| Boolean(this.settingsRepo.getAzureLogin())
|
|
5544
|
+
|| this.settingsRepo.getSetting(AZURE_CLI_WANTED) === '1';
|
|
5545
|
+
} catch {
|
|
5546
|
+
return false;
|
|
5547
|
+
}
|
|
5548
|
+
}
|
|
5549
|
+
|
|
5550
|
+
/**
|
|
5551
|
+
* Tell the ticket checks which agents the runner image carries (its manifest; cached by
|
|
5552
|
+
* image id, so cheap). Before writing a ticket, at start and after a rebuild.
|
|
5553
|
+
*/
|
|
5554
|
+
async refreshImageAgents(): Promise<void> {
|
|
5555
|
+
try {
|
|
5556
|
+
const info = await this.dockerClient.inspectRunnerImage(this.config.runnerImage);
|
|
5557
|
+
if (info.agents?.length) this.ticketRepo.setImageAgents(info.agents);
|
|
5558
|
+
} catch {}
|
|
5559
|
+
}
|
|
5560
|
+
|
|
5529
5561
|
/** Where the image build is (or how the last one ended), for Ajustes' progress bar. */
|
|
5530
5562
|
getRebuildStatus(): typeof this.rebuildStatus {
|
|
5531
5563
|
return { ...this.rebuildStatus };
|
|
@@ -5553,6 +5585,7 @@ export class Orchestrator {
|
|
|
5553
5585
|
} catch {
|
|
5554
5586
|
image = { present: false };
|
|
5555
5587
|
}
|
|
5588
|
+
if (image.agents?.length) this.ticketRepo.setImageAgents(image.agents);
|
|
5556
5589
|
const selection = this.settingsRepo.getSetupSelection();
|
|
5557
5590
|
return buildSetupState({
|
|
5558
5591
|
setup_done: selection.setup_done,
|
package/src/db/ticket-repo.ts
CHANGED
|
@@ -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
|
@@ -172,6 +172,8 @@ export function createServer(orchestrator: Orchestrator, hooks: ServerHooks = {}
|
|
|
172
172
|
sendJson(400, { error: "Field 'title' and one of 'repo_url', 'repos' or 'hub_url' are required" });
|
|
173
173
|
return;
|
|
174
174
|
}
|
|
175
|
+
// The hub-team check needs the agents the image really carries.
|
|
176
|
+
await orchestrator.refreshImageAgents();
|
|
175
177
|
try {
|
|
176
178
|
// Plan bond-app-ticket-desde-pr P1: from a PR or branch, bond-app resolves it and
|
|
177
179
|
// takes repo, branches, id (and title/story if missing) from it.
|
|
@@ -467,6 +469,7 @@ export function createServer(orchestrator: Orchestrator, hooks: ServerHooks = {}
|
|
|
467
469
|
throw new ConflictError(`Cannot change ${pinned.join(', ')} while run '${active.id}' is active`);
|
|
468
470
|
}
|
|
469
471
|
try {
|
|
472
|
+
await orchestrator.refreshImageAgents();
|
|
470
473
|
const updated = orchestrator.ticketRepo.update(ticketId, body);
|
|
471
474
|
if (!updated) {
|
|
472
475
|
sendJson(404, { error: 'Ticket not found' });
|