@jmanuelcorral/bond-app 0.1.5 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +280 -23
  2. package/app/brand/TOKENS.md +5 -5
  3. package/app/layouts/bond.json +10 -14
  4. package/app/mods/bond-agents/api.js +35 -0
  5. package/app/mods/bond-agents/branch.svg +1 -0
  6. package/app/mods/bond-agents/brand.js +53 -2
  7. package/app/mods/bond-agents/config.js +4 -0
  8. package/app/mods/bond-agents/eye-off.svg +1 -0
  9. package/app/mods/bond-agents/eye.svg +1 -0
  10. package/app/mods/bond-agents/main.js +308 -327
  11. package/app/mods/bond-agents/model.js +376 -5
  12. package/app/mods/bond-board/api.js +35 -0
  13. package/app/mods/bond-board/branch.svg +1 -0
  14. package/app/mods/bond-board/brand.js +53 -2
  15. package/app/mods/bond-board/config.js +4 -0
  16. package/app/mods/bond-board/main.js +1000 -449
  17. package/app/mods/bond-board/model.js +170 -28
  18. package/app/mods/bond-pane/close.svg +1 -0
  19. package/app/mods/bond-pane/hide.svg +1 -0
  20. package/app/mods/bond-pane/main.js +103 -0
  21. package/app/mods/bond-pane/mod.json +1 -0
  22. package/app/mods/bond-pane/model.js +18 -0
  23. package/app/mods/bond-pane/split-down.svg +1 -0
  24. package/app/mods/bond-pane/split-right.svg +1 -0
  25. package/app/mods/bond-pane/unzoom.svg +1 -0
  26. package/app/mods/bond-pane/zoom.svg +1 -0
  27. package/app/mods/bond-settings/api.js +35 -0
  28. package/app/mods/bond-settings/brand.js +53 -2
  29. package/app/mods/bond-settings/config.js +4 -0
  30. package/app/mods/bond-settings/main.js +1216 -272
  31. package/app/mods/bond-settings/mod.json +1 -1
  32. package/app/mods/bond-status/api.js +35 -0
  33. package/app/mods/bond-status/brand.js +53 -2
  34. package/app/mods/bond-status/config.js +4 -0
  35. package/app/mods/bond-status/main.js +37 -15
  36. package/app/mods/bond-status/model.js +19 -1
  37. package/app/mods/bond-tabs/brand.js +53 -2
  38. package/app/mods/bond-tabs/main.js +45 -3
  39. package/app/mods/bond-titlebar/brand.js +53 -2
  40. package/app/mods/bond-titlebar/main.js +85 -29
  41. package/app/mods/bond-titlebar/version.js +3 -0
  42. package/app/themes/bond-dark.json +5 -5
  43. package/app/themes/bond-light.json +5 -5
  44. package/package.json +1 -1
  45. package/runner/Dockerfile +16 -2
  46. package/runner/SPIKE-BOND.md +6 -2
  47. package/runner/entrypoint.sh +16 -0
  48. package/runner/setup.sh +439 -8
  49. package/runner/versions.env +32 -1
  50. package/scripts/app-install.ts +322 -27
  51. package/src/cli.ts +562 -21
  52. package/src/config.ts +15 -3
  53. package/src/core/agy-login.ts +683 -0
  54. package/src/core/delivery.ts +125 -6
  55. package/src/core/doctor.ts +748 -0
  56. package/src/core/hub-session.ts +108 -91
  57. package/src/core/hub.ts +40 -8
  58. package/src/core/orchestrator.ts +1481 -187
  59. package/src/core/paths.ts +107 -0
  60. package/src/core/permissions.ts +143 -0
  61. package/src/core/pr-source.ts +147 -0
  62. package/src/core/repo-host.ts +60 -0
  63. package/src/core/service-windows.ts +180 -0
  64. package/src/core/service.ts +861 -0
  65. package/src/core/setup-install.ts +1380 -0
  66. package/src/core/setup.ts +62 -1
  67. package/src/core/watchdog.ts +6 -6
  68. package/src/db/database.ts +54 -7
  69. package/src/db/settings-repo.ts +332 -7
  70. package/src/db/ticket-repo.ts +73 -25
  71. package/src/index.ts +4 -4
  72. package/src/runner/azure-devops-client.ts +273 -0
  73. package/src/runner/docker-client.ts +93 -9
  74. package/src/runner/github-client.ts +148 -3
  75. package/src/runner/hc-client.ts +33 -5
  76. package/src/runner/image-builder.ts +123 -5
  77. package/src/runner/jira-client.ts +368 -0
  78. package/src/runner/tool-catalog.ts +84 -0
  79. package/src/server/app.ts +467 -8
  80. package/src/types.ts +140 -2
@@ -0,0 +1,683 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import crypto from 'node:crypto';
6
+ import http from 'node:http';
7
+ import type { AgyLoginSessionState, AgyLoginStatus } from '../types.ts';
8
+ import { credentialAccount } from '../db/settings-repo.ts';
9
+ import { restrictPathSync } from './permissions.ts';
10
+
11
+ const execFileAsync = promisify(execFile);
12
+
13
+ export interface AgyLoginDriver {
14
+ spawnContainer(containerName: string, image: string): Promise<void>;
15
+ removeContainer(containerName: string): Promise<void>;
16
+ /** `command` runs in the login container as runner (default: agy). */
17
+ startTmuxSession(sessionName: string, containerName: string, command?: string): Promise<void>;
18
+ captureTmuxPane(sessionName: string): Promise<string>;
19
+ sendTmuxKeys(sessionName: string, keys: string, literal?: boolean): Promise<void>;
20
+ killTmuxSession(sessionName: string): Promise<void>;
21
+ /** Reads a file in the login container (default: agy's token file); null when missing. */
22
+ readContainerTokenFile(containerName: string, filePath?: string): Promise<string | null>;
23
+ /** Runs argv in the login container as runner, no shell; never with secrets in argv. */
24
+ execInContainer?(containerName: string, argv: string[]): Promise<{ code: number; stdout: string }>;
25
+ }
26
+
27
+ export class DefaultAgyLoginDriver implements AgyLoginDriver {
28
+ async spawnContainer(containerName: string, image: string): Promise<void> {
29
+ await execFileAsync('docker', [
30
+ 'run',
31
+ '-d',
32
+ '--name',
33
+ containerName,
34
+ '--label',
35
+ 'bond-app=true',
36
+ '--label',
37
+ 'bond-app-agy-login=true',
38
+ '--network',
39
+ 'bridge',
40
+ image,
41
+ 'sleep',
42
+ '600',
43
+ ]);
44
+ }
45
+
46
+ async removeContainer(containerName: string): Promise<void> {
47
+ try {
48
+ await execFileAsync('docker', ['rm', '-f', containerName]);
49
+ } catch {
50
+ // Ignore if container is already gone
51
+ }
52
+ }
53
+
54
+ async startTmuxSession(sessionName: string, containerName: string, command = 'agy'): Promise<void> {
55
+ await execFileAsync('tmux', [
56
+ 'new-session',
57
+ '-d',
58
+ '-x',
59
+ '512',
60
+ '-y',
61
+ '60',
62
+ '-s',
63
+ sessionName,
64
+ `docker exec -it -u runner ${containerName} ${command}`,
65
+ ]);
66
+ try {
67
+ await execFileAsync('tmux', ['set-option', '-t', sessionName, 'window-size', 'manual']);
68
+ } catch {
69
+ // Ignore if set-option fails or older tmux
70
+ }
71
+ }
72
+
73
+ async captureTmuxPane(sessionName: string): Promise<string> {
74
+ try {
75
+ const { stdout } = await execFileAsync('tmux', [
76
+ 'capture-pane',
77
+ '-t',
78
+ sessionName,
79
+ '-p',
80
+ '-S',
81
+ '-1000',
82
+ ]);
83
+ return stdout;
84
+ } catch {
85
+ return '';
86
+ }
87
+ }
88
+
89
+ async sendTmuxKeys(sessionName: string, keys: string, literal = false): Promise<void> {
90
+ const args = ['send-keys', '-t', sessionName];
91
+ if (literal) {
92
+ args.push('-l', keys);
93
+ } else {
94
+ args.push(keys);
95
+ }
96
+ await execFileAsync('tmux', args);
97
+ }
98
+
99
+ async killTmuxSession(sessionName: string): Promise<void> {
100
+ try {
101
+ await execFileAsync('tmux', ['kill-session', '-t', sessionName]);
102
+ } catch {
103
+ // Ignore if session is already gone
104
+ }
105
+ }
106
+
107
+ async readContainerTokenFile(
108
+ containerName: string,
109
+ filePath = '/home/runner/.gemini/antigravity-cli/antigravity-oauth-token'
110
+ ): Promise<string | null> {
111
+ try {
112
+ const { stdout } = await execFileAsync('docker', ['exec', containerName, 'cat', filePath]);
113
+ return stdout.trim() || null;
114
+ } catch {
115
+ return null;
116
+ }
117
+ }
118
+
119
+ async execInContainer(containerName: string, argv: string[]): Promise<{ code: number; stdout: string }> {
120
+ try {
121
+ const { stdout } = await execFileAsync('docker', ['exec', '-u', 'runner', containerName, ...argv], { timeout: 30_000 });
122
+ return { code: 0, stdout };
123
+ } catch (err) {
124
+ const e = err as { code?: number; stdout?: string };
125
+ return { code: typeof e.code === 'number' ? e.code : 1, stdout: e.stdout ?? '' };
126
+ }
127
+ }
128
+ }
129
+
130
+ /** What a login is, per agent: the same container + tmux pilot, different CLI and result. */
131
+ /** What a spec may do in the login container besides reading its screen. */
132
+ export interface LoginContext {
133
+ exec(argv: string[]): Promise<{ code: number; stdout: string }>;
134
+ }
135
+
136
+ export interface AgentLoginSpec {
137
+ agent: 'agy' | 'claude' | 'codex' | 'copilot';
138
+ /** What runs in the login container's tmux session. */
139
+ command: string;
140
+ /** Before the URL shows: answer the CLI's menus (agy picks «Google OAuth»); throws to fail. */
141
+ onPane(pane: string, send: (keys: string, literal?: boolean) => Promise<void>, first: boolean): Promise<void>;
142
+ /** After the code: the result once ready ({content, email}), null while waiting; throws on failure. */
143
+ collect(pane: string, readTokenFile: () => Promise<string | null>): Promise<{ content: string; email?: string } | null>;
144
+ /** Ms between typing the code and Enter (claude's TUI takes a paste, then the key). */
145
+ enterDelayMs?: number;
146
+ /** The file `collect`'s readTokenFile reads in the container (default: agy's token). */
147
+ tokenPath?: string;
148
+ /** Before the CLI starts (copilot: settings so it never asks where to store the token). */
149
+ prepare?(ctx: LoginContext): Promise<void>;
150
+ /** Finds what to show the person; default: an OAuth URL with state=. */
151
+ extract?(pane: string): { url: string; user_code?: string } | null;
152
+ /** Device flow: nothing to submit, the result arrives once the person authorizes. */
153
+ device?: boolean;
154
+ /** What submitting does instead of typing the code into the TUI (codex: replay the
155
+ * browser's callback inside the container). Throws a message for the person. */
156
+ submit?(input: string, ctx: LoginContext): Promise<void>;
157
+ /** The browser comes back to this loopback port and path on this machine (codex's
158
+ * registered redirect): while waiting, the orchestrator listens there and hands the
159
+ * return to `submit` itself, so nothing has to be pasted. Paste stays as the fallback. */
160
+ callback?: { port: number; path: string };
161
+ }
162
+
163
+ /** agy (P1): its TUI's «Google OAuth», then the token file it writes. */
164
+ export const AGY_LOGIN_SPEC: AgentLoginSpec = {
165
+ agent: 'agy',
166
+ command: 'agy',
167
+ async onPane(pane, send, first) {
168
+ if (first) await send('Escape');
169
+ if (/google oauth/i.test(pane)) {
170
+ await send('1');
171
+ await send('Enter');
172
+ }
173
+ },
174
+ async collect(_pane, readTokenFile) {
175
+ const content = await readTokenFile();
176
+ if (!content) return null;
177
+ let parsed: { id_token_email?: string };
178
+ try {
179
+ parsed = JSON.parse(content);
180
+ } catch {
181
+ throw new Error('Invalid token file format received from container');
182
+ }
183
+ return { content, email: parsed.id_token_email || 'configured' };
184
+ },
185
+ };
186
+
187
+ const ANSI = /\x1b\[[0-9;?]*[a-zA-Z]|\x1b\][^\x07]*\x07|\x1b\([A-Z0-9]/g;
188
+
189
+ /**
190
+ * The token `claude setup-token` prints, from its screen: the lines between «valid for 1
191
+ * year):» and «Store this token» joined (the TUI wraps it), without the box drawing. Null
192
+ * when it is not there yet. Never logged: callers keep it only as the stored credential.
193
+ */
194
+ export function extractClaudeToken(pane: string): string | null {
195
+ const text = pane.replace(ANSI, '').replace(/\r/g, '');
196
+ const start = text.search(/valid\s*for\s*1\s*year\)?:/i);
197
+ if (start === -1) return null;
198
+ const rest = text.slice(start).replace(/^[^\n]*\n?/, '');
199
+ const end = rest.search(/Store\s*this\s*token/i);
200
+ const block = (end === -1 ? rest : rest.slice(0, end)).replace(/[\s│|]+/g, '');
201
+ const m = /sk-ant-oat[A-Za-z0-9_-]+/.exec(block);
202
+ return m ? m[0] : null;
203
+ }
204
+
205
+ /** claude (plan bond-app-claude-agente P2): `claude setup-token` (one-year, inference-only
206
+ * token, no refresh); the token comes from its screen. */
207
+ export const CLAUDE_LOGIN_SPEC: AgentLoginSpec = {
208
+ agent: 'claude',
209
+ command: 'claude setup-token',
210
+ enterDelayMs: 300,
211
+ async onPane(pane) {
212
+ if (/claude: (command )?not found|executable file not found/i.test(pane)) {
213
+ throw new Error('claude no está en la imagen del runner: elígelo en el asistente y reconstruye la imagen');
214
+ }
215
+ },
216
+ async collect(pane) {
217
+ if (/OAuth error|Invalid code|doesn't look like the full code/i.test(pane.replace(ANSI, ''))) {
218
+ throw new Error('Claude rechazó el código: vuelve a empezar el login y pega el código entero (lleva un # en medio)');
219
+ }
220
+ const token = extractClaudeToken(pane);
221
+ return token ? { content: token } : null;
222
+ },
223
+ };
224
+
225
+ /** The address the browser ends on after codex's OAuth: codex's own callback server in the
226
+ * login container (never published). Only 127.0.0.1/localhost:1455/auth/callback with a
227
+ * plain query string passes; the result always targets 127.0.0.1. Null otherwise. */
228
+ export function codexCallbackUrl(input: string): string | null {
229
+ const m = /^http:\/\/(?:127\.0\.0\.1|localhost):1455\/auth\/callback\?([A-Za-z0-9._~%&=+-]{1,4096})$/.exec(String(input ?? '').trim());
230
+ if (!m) return null;
231
+ const q = new URLSearchParams(m[1]);
232
+ if (!q.get('code') || !q.get('state')) return null;
233
+ return `http://127.0.0.1:1455/auth/callback?${m[1]}`;
234
+ }
235
+
236
+ /** codex (plan bond-app-codex-copilot): `codex login` with the browser flow, which works with
237
+ * personal ChatGPT accounts (the device flow needs a ChatGPT setting they may not have).
238
+ * The browser ends on 127.0.0.1:1455, unreachable from the host: the person pastes that
239
+ * address and it is replayed inside the container. The session is ~/.codex/auth.json. */
240
+ export const CODEX_LOGIN_SPEC: AgentLoginSpec = {
241
+ agent: 'codex',
242
+ command: 'env BROWSER=true codex login',
243
+ tokenPath: '/home/runner/.codex/auth.json',
244
+ callback: { port: 1455, path: '/auth/callback' },
245
+ async onPane(pane) {
246
+ if (/codex: (command )?not found|executable file not found/i.test(pane)) {
247
+ throw new Error('codex no está en la imagen del runner: añádelo en Ajustes → Agentes y reconstruye la imagen');
248
+ }
249
+ },
250
+ async submit(input, ctx) {
251
+ const url = codexCallbackUrl(input);
252
+ if (!url) {
253
+ throw new Error('Pega la dirección completa a la que te llevó el navegador: empieza por http://127.0.0.1:1455/auth/callback?code=');
254
+ }
255
+ const res = await ctx.exec(['curl', '-s', '-o', '/dev/null', '-w', '%{http_code}', '--max-time', '20', url]);
256
+ const status = Number(res.stdout.trim());
257
+ if (res.code !== 0 || !(status >= 200 && status < 400)) {
258
+ throw new Error('codex no aceptó esa dirección: puede haber caducado o ser de otro intento; vuelve a empezar el login');
259
+ }
260
+ },
261
+ async collect(pane, readTokenFile) {
262
+ if (/Error logging in|Login failed|state mismatch/i.test(pane.replace(ANSI, ''))) {
263
+ throw new Error('codex no pudo completar el login: vuelve a empezar');
264
+ }
265
+ const content = await readTokenFile();
266
+ if (!content) return null;
267
+ let doc: { tokens?: { refresh_token?: string } };
268
+ try {
269
+ doc = JSON.parse(content);
270
+ } catch {
271
+ return null;
272
+ }
273
+ if (!doc.tokens?.refresh_token) return null;
274
+ return { content, email: credentialAccount('codex', content) ?? 'ChatGPT' };
275
+ },
276
+ };
277
+
278
+ /** copilot (plan bond-app-codex-copilot): `copilot login --device-code`; the person types the
279
+ * code at github.com/login/device and the token lands in ~/.copilot/config.json (no keyring
280
+ * in the container, hence storeTokenPlaintext). The token carries the repo scope: accepted
281
+ * by the user (decision 2026-11-24), Ajustes says so. */
282
+ export const COPILOT_LOGIN_SPEC: AgentLoginSpec = {
283
+ agent: 'copilot',
284
+ command: 'copilot login --device-code',
285
+ tokenPath: '/home/runner/.copilot/config.json',
286
+ device: true,
287
+ async prepare(ctx) {
288
+ await ctx.exec(['sh', '-c', 'mkdir -p "$HOME/.copilot" && { [ -f "$HOME/.copilot/settings.json" ] || printf \'{"storeTokenPlaintext": true}\\n\' > "$HOME/.copilot/settings.json"; }']);
289
+ },
290
+ async onPane(pane) {
291
+ if (/copilot: (command )?not found|executable file not found/i.test(pane)) {
292
+ throw new Error('copilot no está en la imagen del runner: añádelo en Ajustes → Agentes y reconstruye la imagen');
293
+ }
294
+ },
295
+ extract(pane) {
296
+ const text = pane.replace(ANSI, '').replace(/\]52;[^\n]*?(?=Failed|To authenticate|$)/g, '');
297
+ const m = /(https:\/\/github\.com\/login\/device)\S*\s+and enter (?:the )?code ([A-Z0-9]{4}-[A-Z0-9]{4})/i.exec(text);
298
+ return m ? { url: m[1], user_code: m[2] } : null;
299
+ },
300
+ async collect(pane, readTokenFile) {
301
+ const text = pane.replace(ANSI, '');
302
+ if (/expired|access[_ ]denied|authorization (was )?denied|Error:/i.test(text) && !/Signed in successfully/i.test(text)) {
303
+ throw new Error('GitHub no autorizó el login de copilot (código caducado o denegado): vuelve a empezar');
304
+ }
305
+ // The token file is the proof: `copilot login` exits once signed in, and its tmux
306
+ // session (the pane) goes with it, so «Signed in successfully» may never be read.
307
+ const content = await readTokenFile();
308
+ if (!content || !/"authTokens"/.test(content)) return null;
309
+ return { content, email: credentialAccount('copilot', content) ?? 'GitHub' };
310
+ },
311
+ };
312
+
313
+ export interface AgyLoginManagerOptions {
314
+ driver?: AgyLoginDriver;
315
+ runnerImage: string;
316
+ dataDir: string;
317
+ maxDurationMs?: number;
318
+ /** Which agent this manager logs in (default: agy, as before). */
319
+ spec?: AgentLoginSpec;
320
+ /** Keeps the result for agents other than agy (agy writes its token file in dataDir). */
321
+ onToken?: (content: string) => void;
322
+ /** Overrides spec.callback.port (tests). */
323
+ callbackPort?: number;
324
+ }
325
+
326
+ export class AgyLoginManager {
327
+ private driver: AgyLoginDriver;
328
+ private runnerImage: string;
329
+ private dataDir: string;
330
+ private state: AgyLoginSessionState = { status: 'idle' };
331
+ private activeContainerName: string | null = null;
332
+ private activeSessionName: string | null = null;
333
+ private pollInterval: NodeJS.Timeout | null = null;
334
+ private timeoutTimer: NodeJS.Timeout | null = null;
335
+ private maxDurationMs: number;
336
+ private spec: AgentLoginSpec;
337
+ private onToken?: (content: string) => void;
338
+ private callbackServer: http.Server | null = null;
339
+ /** Port the callback listener uses (tests pick a free one). */
340
+ private callbackPort?: number;
341
+ public inMemoryToken: string | null = null;
342
+
343
+ constructor(options: AgyLoginManagerOptions) {
344
+ this.driver = options.driver || new DefaultAgyLoginDriver();
345
+ this.runnerImage = options.runnerImage;
346
+ this.dataDir = options.dataDir;
347
+ this.maxDurationMs = options.maxDurationMs ?? 300000; // 5 min default
348
+ this.spec = options.spec ?? AGY_LOGIN_SPEC;
349
+ this.onToken = options.onToken;
350
+ this.callbackPort = options.callbackPort;
351
+ }
352
+
353
+ getStatus(): AgyLoginSessionState {
354
+ return { ...this.state };
355
+ }
356
+
357
+ extractOAuthUrl(pane: string): string | null {
358
+ const clean = pane.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '');
359
+ const lines = clean.split(/\r?\n/);
360
+
361
+ for (let i = 0; i < lines.length; i++) {
362
+ const line = lines[i];
363
+ const httpIdx = line.indexOf('https://');
364
+ if (httpIdx === -1) continue;
365
+
366
+ let candidate = line.slice(httpIdx).trim().split(/\s+/)[0];
367
+ if (!candidate.includes('google.com') && !candidate.includes('oauth')) {
368
+ continue;
369
+ }
370
+
371
+ // When the URL fragment appears incomplete (does not contain state=),
372
+ // concatenate following contiguous lines while they contain non-empty content
373
+ let j = i + 1;
374
+ while (
375
+ !candidate.includes('state=') &&
376
+ j < lines.length &&
377
+ lines[j].trim().length > 0 &&
378
+ !lines[j].trim().startsWith('https://') &&
379
+ !lines[j].trim().startsWith('http://') &&
380
+ !/^(?:Enter|Please|Select|Choose|Input|1\.|2\.)/i.test(lines[j].trim())
381
+ ) {
382
+ const nextChunk = lines[j].trim().split(/\s+/)[0];
383
+ candidate += nextChunk;
384
+ j++;
385
+ }
386
+
387
+ // Return only complete URLs that contain state=
388
+ if (candidate.includes('state=')) {
389
+ return candidate;
390
+ }
391
+ }
392
+
393
+ return null;
394
+ }
395
+
396
+ async start(): Promise<AgyLoginSessionState> {
397
+ await this.cancel();
398
+
399
+ const id = crypto.randomBytes(4).toString('hex');
400
+ const containerName = `bond-app-${this.spec.agent}-login-${id}`;
401
+ const sessionName = `bond-${this.spec.agent}-login-${id}`;
402
+
403
+ this.activeContainerName = containerName;
404
+ this.activeSessionName = sessionName;
405
+ this.state = { status: 'starting' };
406
+
407
+ this.timeoutTimer = setTimeout(async () => {
408
+ if (this.state.status !== 'success' && this.state.status !== 'idle') {
409
+ await this.handleError(`Login ${this.spec.agent} timed out`);
410
+ }
411
+ }, this.maxDurationMs);
412
+
413
+ try {
414
+ await this.driver.spawnContainer(containerName, this.runnerImage);
415
+ if (this.spec.prepare) await this.spec.prepare(this.context(containerName));
416
+ await this.driver.startTmuxSession(sessionName, containerName, this.spec.command);
417
+ await this.startPaneWatcher(sessionName, containerName);
418
+ } catch (err: unknown) {
419
+ await this.handleError((err as Error).message);
420
+ }
421
+
422
+ return this.getStatus();
423
+ }
424
+
425
+ private context(containerName: string): LoginContext {
426
+ return {
427
+ exec: (argv) => {
428
+ if (!this.driver.execInContainer) throw new Error('this login driver cannot run commands in the container');
429
+ return this.driver.execInContainer(containerName, argv);
430
+ },
431
+ };
432
+ }
433
+
434
+ private async startPaneWatcher(sessionName: string, containerName: string): Promise<void> {
435
+ let first = true;
436
+ let attempts = 0;
437
+ const maxAttempts = 240; // ~120s at 500ms intervals
438
+
439
+ const checkPane = async () => {
440
+ attempts++;
441
+ if (attempts > maxAttempts && this.state.status === 'starting') {
442
+ await this.handleError(`Timeout waiting for ${this.spec.agent} OAuth URL`);
443
+ return;
444
+ }
445
+
446
+ try {
447
+ const pane = await this.driver.captureTmuxPane(sessionName);
448
+ if (first) {
449
+ first = false;
450
+ await this.spec.onPane(pane, (keys, literal) => this.driver.sendTmuxKeys(sessionName, keys, literal), true);
451
+ }
452
+ if (!pane) return;
453
+
454
+ const found: { url: string; user_code?: string } | null = this.spec.extract ? this.spec.extract(pane) : (() => {
455
+ const url = this.extractOAuthUrl(pane);
456
+ return url ? { url } : null;
457
+ })();
458
+ if (found) {
459
+ if (this.pollInterval) {
460
+ clearInterval(this.pollInterval);
461
+ this.pollInterval = null;
462
+ }
463
+ this.state = {
464
+ status: 'waiting_code',
465
+ url: found.url,
466
+ ...(found.user_code ? { user_code: found.user_code } : {}),
467
+ ...(this.spec.device ? { device: true } : {}),
468
+ };
469
+ // Device flow: nothing to paste back; watch for the result right away.
470
+ if (this.spec.device) await this.startTokenFileWatcher(containerName, sessionName);
471
+ // Loopback return (codex): catch it here so nothing has to be pasted.
472
+ if (this.spec.callback && !this.spec.device) {
473
+ const listening = await this.listenForCallback(found.url);
474
+ if (listening && this.state.status === 'waiting_code') this.state = { ...this.state, auto: true };
475
+ }
476
+ return;
477
+ }
478
+
479
+ await this.spec.onPane(pane, (keys, literal) => this.driver.sendTmuxKeys(sessionName, keys, literal), false);
480
+ } catch (err: unknown) {
481
+ if (err instanceof Error && this.spec.agent !== 'agy') await this.handleError(err.message);
482
+ }
483
+ };
484
+
485
+ await checkPane();
486
+ if (this.state.status === 'starting') {
487
+ this.pollInterval = setInterval(checkPane, 500);
488
+ }
489
+ }
490
+
491
+ /**
492
+ * Listens on 127.0.0.1:<callback port> for the browser's return (only the expected path
493
+ * and the `state` of our own authorize URL), answers the browser with a short page and
494
+ * submits it as if pasted. False when the port is taken: the person pastes instead.
495
+ */
496
+ private async listenForCallback(authorizeUrl: string): Promise<boolean> {
497
+ const cb = this.spec.callback!;
498
+ let expectedState: string | null = null;
499
+ try {
500
+ expectedState = new URL(authorizeUrl).searchParams.get('state');
501
+ } catch {}
502
+ if (!expectedState) return false;
503
+ const page = (title: string, body: string) =>
504
+ `<!doctype html><meta charset="utf-8"><title>${title}</title><body style="font-family:system-ui;margin:15vh auto;max-width:32rem;text-align:center"><h2>${title}</h2><p>${body}</p></body>`;
505
+ const server = http.createServer((req, res) => {
506
+ const url = new URL(req.url ?? '/', `http://127.0.0.1:${cb.port}`);
507
+ if (req.method !== 'GET' || url.pathname !== cb.path || url.searchParams.get('state') !== expectedState) {
508
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', Connection: 'close' }).end('not found');
509
+ return;
510
+ }
511
+ const full = `http://127.0.0.1:${cb.port}${url.pathname}${url.search}`;
512
+ this.submitCode(full).then((st) => {
513
+ const ok = st.status !== 'error';
514
+ res.writeHead(ok ? 200 : 400, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' }).end(ok
515
+ ? page('Listo', 'bond-app ha recibido la autorización. Puedes cerrar esta pestaña y volver a bond-app.')
516
+ : page('No se pudo completar', `Vuelve a bond-app y empieza el login otra vez. (${st.error ?? 'error'})`));
517
+ }, (err: unknown) => {
518
+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' }).end(page('No se pudo completar', String((err as Error).message)));
519
+ });
520
+ });
521
+ const port = this.callbackPort ?? cb.port;
522
+ const ok = await new Promise<boolean>((resolve) => {
523
+ server.once('error', () => resolve(false));
524
+ server.listen(port, '127.0.0.1', () => resolve(true));
525
+ });
526
+ if (!ok) return false;
527
+ this.callbackServer = server;
528
+ return true;
529
+ }
530
+
531
+ private stopCallbackServer(): void {
532
+ const s = this.callbackServer;
533
+ this.callbackServer = null;
534
+ if (s) {
535
+ // Stop accepting; the browser's request in flight still gets its «Listo» page.
536
+ s.close();
537
+ s.closeIdleConnections?.();
538
+ }
539
+ }
540
+
541
+ async submitCode(code: string): Promise<AgyLoginSessionState> {
542
+ if (this.state.status !== 'waiting_code' || !this.activeSessionName || !this.activeContainerName) {
543
+ throw new Error(`No active ${this.spec.agent} login session waiting for code`);
544
+ }
545
+ if (this.spec.device) {
546
+ throw new Error(`${this.spec.agent} no necesita código: autoriza en el enlace y espera`);
547
+ }
548
+
549
+ if (!code || typeof code !== 'string' || !code.trim()) {
550
+ throw new Error('Invalid authorization code');
551
+ }
552
+
553
+ this.state = {
554
+ status: 'authenticating',
555
+ url: this.state.url,
556
+ };
557
+
558
+ const sessionName = this.activeSessionName;
559
+ const containerName = this.activeContainerName;
560
+
561
+ try {
562
+ if (this.spec.submit) {
563
+ await this.spec.submit(code.trim(), this.context(containerName));
564
+ } else {
565
+ await this.driver.sendTmuxKeys(sessionName, code.trim(), true);
566
+ if (this.spec.enterDelayMs) await new Promise((r) => setTimeout(r, this.spec.enterDelayMs));
567
+ await this.driver.sendTmuxKeys(sessionName, 'Enter');
568
+ }
569
+ await this.startTokenFileWatcher(containerName, sessionName);
570
+ } catch (err: unknown) {
571
+ await this.handleError((err as Error).message);
572
+ }
573
+
574
+ return this.getStatus();
575
+ }
576
+
577
+ private async startTokenFileWatcher(containerName: string, sessionName: string): Promise<void> {
578
+ let attempts = 0;
579
+ // A device flow waits for the person (the overall timeout bounds it); a code is quick.
580
+ const maxAttempts = this.spec.device ? Number.POSITIVE_INFINITY : 60;
581
+
582
+ if (this.pollInterval) {
583
+ clearInterval(this.pollInterval);
584
+ this.pollInterval = null;
585
+ }
586
+
587
+ const checkToken = async () => {
588
+ if (this.state.status !== 'authenticating' && this.state.status !== 'waiting_code') return;
589
+ attempts++;
590
+ if (attempts > maxAttempts) {
591
+ await this.handleError(`Timeout waiting for ${this.spec.agent} authentication to complete`);
592
+ return;
593
+ }
594
+
595
+ try {
596
+ const pane = this.spec.agent === 'agy' ? '' : await this.driver.captureTmuxPane(sessionName);
597
+ let result: { content: string; email?: string } | null;
598
+ try {
599
+ result = await this.spec.collect(pane, () => this.driver.readContainerTokenFile(containerName, this.spec.tokenPath));
600
+ } catch (err: unknown) {
601
+ await this.handleError((err as Error).message);
602
+ return;
603
+ }
604
+ if (!result) return;
605
+ if (this.pollInterval) {
606
+ clearInterval(this.pollInterval);
607
+ this.pollInterval = null;
608
+ }
609
+
610
+ if (this.spec.agent === 'agy') {
611
+ const destPath = path.join(this.dataDir, 'antigravity-oauth-token');
612
+ if (this.dataDir !== ':memory:') {
613
+ fs.mkdirSync(this.dataDir, { recursive: true, mode: 0o700 });
614
+ fs.writeFileSync(destPath, result.content, { mode: 0o600 });
615
+ restrictPathSync(destPath, 0o600);
616
+ } else {
617
+ this.inMemoryToken = result.content;
618
+ }
619
+ } else if (this.onToken) {
620
+ this.onToken(result.content);
621
+ } else {
622
+ this.inMemoryToken = result.content;
623
+ }
624
+
625
+ await this.cleanupResources();
626
+
627
+ this.state = {
628
+ status: 'success',
629
+ email: result.email,
630
+ };
631
+ } catch {}
632
+ };
633
+
634
+ await checkToken();
635
+ if (this.state.status === 'authenticating' || (this.spec.device && this.state.status === 'waiting_code')) {
636
+ this.pollInterval = setInterval(checkToken, 500);
637
+ }
638
+ }
639
+
640
+ private async cleanupResources(): Promise<void> {
641
+ this.stopCallbackServer();
642
+ if (this.pollInterval) {
643
+ clearInterval(this.pollInterval);
644
+ this.pollInterval = null;
645
+ }
646
+ if (this.timeoutTimer) {
647
+ clearTimeout(this.timeoutTimer);
648
+ this.timeoutTimer = null;
649
+ }
650
+ const sess = this.activeSessionName;
651
+ const cont = this.activeContainerName;
652
+ this.activeSessionName = null;
653
+ this.activeContainerName = null;
654
+
655
+ if (sess) {
656
+ await this.driver.killTmuxSession(sess);
657
+ }
658
+ if (cont) {
659
+ await this.driver.removeContainer(cont);
660
+ }
661
+ }
662
+
663
+ async cancel(): Promise<AgyLoginSessionState> {
664
+ await this.cleanupResources();
665
+ this.state = { status: 'idle' };
666
+ return this.getStatus();
667
+ }
668
+
669
+ async finish(): Promise<AgyLoginSessionState> {
670
+ await this.cleanupResources();
671
+ const result = { ...this.state };
672
+ this.state = { status: 'idle' };
673
+ return result;
674
+ }
675
+
676
+ private async handleError(message: string): Promise<void> {
677
+ await this.cleanupResources();
678
+ this.state = {
679
+ status: 'error',
680
+ error: message,
681
+ };
682
+ }
683
+ }