@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
@@ -1,7 +1,8 @@
1
1
  import { execFile, spawn } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
3
  import type { RunnerImageInfo } from '../types.ts';
4
- import { parseRunnerManifest } from '../core/setup.ts';
4
+ import { parseRunnerManifest, parseRunnerManifestTools } from '../core/setup.ts';
5
+ import { LABEL_RECIPE } from './image-builder.ts';
5
6
 
6
7
  const execFileAsync = promisify(execFile);
7
8
 
@@ -16,6 +17,13 @@ export interface ContainerStartOptions {
16
17
  pidsLimit?: number;
17
18
  securityProfile?: boolean;
18
19
  extraMounts?: string[];
20
+ /**
21
+ * Plan bond-app-ajustes-imagen P4: «Docker en el run». The container runs --privileged
22
+ * with its own anonymous volume for /var/lib/docker (gone with `docker rm -v`, never
23
+ * shared) and BOND_DIND=1, a flag the entrypoint reads to start dockerd. Accepted risk:
24
+ * on Linux such a run can take over the host (decision 2026-11-24).
25
+ */
26
+ docker?: boolean;
19
27
  }
20
28
 
21
29
  export interface ContainerInfo {
@@ -40,6 +48,13 @@ export interface DockerNetworkSummary {
40
48
  instanceId?: string;
41
49
  }
42
50
 
51
+ export interface ExecStreamHandle {
52
+ stdout: NodeJS.ReadableStream;
53
+ stderr: NodeJS.ReadableStream;
54
+ kill: () => void;
55
+ done: Promise<number | null>;
56
+ }
57
+
43
58
  export class DockerClient {
44
59
  async createNetwork(runId: string, instanceId?: string): Promise<string> {
45
60
  const networkName = `bond-net-${runId}`;
@@ -133,9 +148,8 @@ export class DockerClient {
133
148
  });
134
149
  }
135
150
 
136
- async createAndStartContainer(options: ContainerStartOptions): Promise<ContainerInfo> {
151
+ buildRunArgs(options: ContainerStartOptions, network: string): string[] {
137
152
  const containerName = `bond-app-${options.runId}`;
138
- const network = options.network || (await this.createNetwork(options.runId, options.instanceId));
139
153
 
140
154
  const args: string[] = [
141
155
  'run',
@@ -157,10 +171,16 @@ export class DockerClient {
157
171
  // P3 (D19): no published ports. The host reaches the container only with docker exec
158
172
  // (hc machine --via). --init reaps the processes docker exec sessions leave behind.
159
173
  // P7 (Ampliación): BOND_TEAM_NO_TABLE=1 disables bond team's live table.
160
- args.push('--network', network, '--init', '-e', 'BOND_TEAM_NO_TABLE=1');
174
+ // P3 (D-BB): BOND_APP=1 selects hc transport in bond; passed defensively for older runner images.
175
+ args.push('--network', network, '--init', '-e', 'BOND_TEAM_NO_TABLE=1', '-e', 'BOND_APP=1');
176
+
177
+ if (options.docker) {
178
+ // dockerd needs the privileges the hardened profile drops; nothing else changes.
179
+ args.push('--privileged', '-v', '/var/lib/docker', '-e', 'BOND_DIND=1');
180
+ }
161
181
 
162
182
  // Security options: criterion 12
163
- if (options.securityProfile !== false) {
183
+ if (options.securityProfile !== false && !options.docker) {
164
184
  args.push(
165
185
  '--cap-drop=ALL',
166
186
  '--cap-add=CHOWN',
@@ -179,7 +199,8 @@ export class DockerClient {
179
199
  // Resource limits (M2)
180
200
  const cpus = options.cpus ?? 2;
181
201
  const memory = options.memory ?? '2g';
182
- const pidsLimit = options.pidsLimit ?? 200;
202
+ // dockerd and the containers it starts share the run's pid budget.
203
+ const pidsLimit = options.docker ? Math.max(options.pidsLimit ?? 200, 4096) : (options.pidsLimit ?? 200);
183
204
 
184
205
  args.push(`--cpus=${cpus}`, `--memory=${memory}`, `--pids-limit=${pidsLimit}`);
185
206
 
@@ -192,6 +213,15 @@ export class DockerClient {
192
213
  // Image
193
214
  args.push(options.image);
194
215
 
216
+ return args;
217
+ }
218
+
219
+ async createAndStartContainer(options: ContainerStartOptions): Promise<ContainerInfo> {
220
+ const containerName = `bond-app-${options.runId}`;
221
+ const network = options.network || (await this.createNetwork(options.runId, options.instanceId));
222
+
223
+ const args = this.buildRunArgs(options, network);
224
+
195
225
  const { stdout } = await execFileAsync('docker', args);
196
226
  const containerId = stdout.trim();
197
227
 
@@ -323,6 +353,33 @@ export class DockerClient {
323
353
  }
324
354
  }
325
355
 
356
+ execStream(containerName: string, command: string[], user?: string): ExecStreamHandle {
357
+ const args = ['exec'];
358
+ if (user) {
359
+ args.push('-u', user);
360
+ }
361
+ args.push(containerName, ...command);
362
+
363
+ const child = spawn('docker', args, { stdio: ['ignore', 'pipe', 'pipe'] });
364
+ const done = new Promise<number | null>((resolve) => {
365
+ child.on('close', (code) => resolve(code));
366
+ child.on('error', () => resolve(null));
367
+ });
368
+ const kill = () => {
369
+ try {
370
+ child.kill('SIGTERM');
371
+ } catch {
372
+ // ignore
373
+ }
374
+ };
375
+ return {
376
+ stdout: child.stdout,
377
+ stderr: child.stderr,
378
+ kill,
379
+ done,
380
+ };
381
+ }
382
+
326
383
  async stopAndRemoveContainer(containerName: string, networkName?: string): Promise<number> {
327
384
  const t0 = Date.now();
328
385
  try {
@@ -400,12 +457,36 @@ export class DockerClient {
400
457
  * An older image without the manifest reports present with no agents. Never logs the
401
458
  * manifest content; the manifest carries no secrets by design.
402
459
  */
460
+ /** The last manifest read, by image id: reading it costs a `docker run`, and Ajustes
461
+ * asks for the setup state every few seconds (plan bond-app-ajustes-imagen P2). */
462
+ private manifestCache: { id: string; info: RunnerImageInfo } | null = null;
463
+
403
464
  async inspectRunnerImage(image: string): Promise<RunnerImageInfo> {
465
+ let id: string;
466
+ let recipe: string | undefined;
404
467
  try {
405
- await execFileAsync('docker', ['image', 'inspect', image, '--format', '{{.Id}}'], { timeout: 20_000 });
468
+ const { stdout } = await execFileAsync(
469
+ 'docker',
470
+ // The whole Config as JSON: an image without labels has no Labels key at all, and a
471
+ // template that names it (`index`, `.Config.Labels`) fails instead of printing nothing.
472
+ ['image', 'inspect', image, '--format', '{{.Id}} {{json .Config}}'],
473
+ { timeout: 20_000 }
474
+ );
475
+ const out = String(stdout).trim();
476
+ const space = out.indexOf(' ');
477
+ id = space === -1 ? out : out.slice(0, space);
478
+ try {
479
+ const config = JSON.parse(space === -1 ? 'null' : out.slice(space + 1)) as { Labels?: Record<string, string> | null } | null;
480
+ recipe = config?.Labels?.[LABEL_RECIPE] || undefined;
481
+ } catch {
482
+ recipe = undefined;
483
+ }
406
484
  } catch {
407
485
  return { present: false };
408
486
  }
487
+ const withRecipe = (info: RunnerImageInfo): RunnerImageInfo =>
488
+ recipe ? { ...info, recipe } : { ...info };
489
+ if (this.manifestCache && this.manifestCache.id === id) return withRecipe(this.manifestCache.info);
409
490
  try {
410
491
  const { stdout } = await execFileAsync(
411
492
  'docker',
@@ -413,9 +494,12 @@ export class DockerClient {
413
494
  { timeout: 30_000, maxBuffer: 256 * 1024 }
414
495
  );
415
496
  const agents = parseRunnerManifest(stdout);
416
- return agents.length > 0 ? { present: true, agents } : { present: true };
497
+ const { tools, apt_extra } = parseRunnerManifestTools(stdout);
498
+ const info: RunnerImageInfo = { present: true, ...(agents.length > 0 ? { agents } : {}), tools, apt_extra };
499
+ this.manifestCache = { id, info };
500
+ return withRecipe(info);
417
501
  } catch {
418
- return { present: true };
502
+ return withRecipe({ present: true });
419
503
  }
420
504
  }
421
505
  }
@@ -133,6 +133,43 @@ export class GitHubClient {
133
133
  };
134
134
  }
135
135
 
136
+ /**
137
+ * Plan bond-app-ajustes-imagen P4: whether the repo carries a devcontainer
138
+ * (`.devcontainer/` or `.devcontainer.json`) at `ref` (default branch when omitted), so
139
+ * the new-ticket dialog can pre-tick «Docker en el run». Unreadable reads as false.
140
+ */
141
+ async hasDevcontainer(token: string, owner: string, repo: string, ref?: string): Promise<boolean> {
142
+ if (!/^[A-Za-z0-9_.-]+$/.test(owner) || !/^[A-Za-z0-9_.-]+$/.test(repo)) return false;
143
+ const q = ref ? `?ref=${encodeURIComponent(ref)}` : '';
144
+ for (const p of ['.devcontainer', '.devcontainer.json']) {
145
+ const res = await this.call(token, 'GET', `/repos/${owner}/${repo}/contents/${p}${q}`);
146
+ if (res.status === 200) return true;
147
+ }
148
+ return false;
149
+ }
150
+
151
+ /**
152
+ * Alta de ticket: whether the repo is a bond hub (`hub.toml` at its root, as `bond hub
153
+ * init` leaves it), so the dialog can switch the ticket to hub mode by itself.
154
+ */
155
+ async isHub(token: string, owner: string, repo: string, ref?: string): Promise<boolean> {
156
+ if (!/^[A-Za-z0-9_.-]+$/.test(owner) || !/^[A-Za-z0-9_.-]+$/.test(repo)) return false;
157
+ const q = ref ? `?ref=${encodeURIComponent(ref)}` : '';
158
+ const res = await this.call(token, 'GET', `/repos/${owner}/${repo}/contents/hub.toml${q}`);
159
+ return res.status === 200;
160
+ }
161
+
162
+ /** P5: read hub.toml at `ref` (or default branch), or null if absent/unreadable. */
163
+ async getHubToml(token: string, owner: string, repo: string, ref?: string): Promise<string | null> {
164
+ if (!/^[A-Za-z0-9_.-]+$/.test(owner) || !/^[A-Za-z0-9_.-]+$/.test(repo)) return null;
165
+ const q = ref ? `?ref=${encodeURIComponent(ref)}` : '';
166
+ const res = await this.call(token, 'GET', `/repos/${owner}/${repo}/contents/hub.toml${q}`);
167
+ if (res.status !== 200 || !res.data || typeof res.data !== 'object') return null;
168
+ const content = (res.data as { content?: unknown }).content;
169
+ if (typeof content !== 'string') return null;
170
+ return Buffer.from(content.replace(/\n/g, ''), 'base64').toString('utf8');
171
+ }
172
+
136
173
  /** P7: check if a remote branch exists on GitHub. */
137
174
  async remoteBranchExists(token: string, owner: string, repo: string, branch: string): Promise<boolean> {
138
175
  const res = await this.call(token, 'GET', `/repos/${owner}/${repo}/branches/${encodeURIComponent(branch)}`);
@@ -183,7 +220,7 @@ export class GitHubClient {
183
220
  * los privados accesibles con el token). La búsqueda es el buscador de GitHub sobre el
184
221
  * nombre/descripción; orden tal cual los devuelve GitHub (best match).
185
222
  */
186
- async searchRepos(token: string, term: string): Promise<Array<{ full_name: string; url: string }>> {
223
+ async searchRepos(token: string, term: string): Promise<Array<{ full_name: string; url: string; default_branch?: string }>> {
187
224
  const res = await this.call(token, 'GET', `/search/repositories?q=${encodeURIComponent(term)}&per_page=20`);
188
225
  if (res.status !== 200) {
189
226
  const msg = (res.data as { message?: string } | null)?.message || `HTTP ${res.status}`;
@@ -192,11 +229,12 @@ export class GitHubClient {
192
229
  const items = Array.isArray((res.data as { items?: unknown })?.items)
193
230
  ? ((res.data as { items: Array<Record<string, unknown>> }).items)
194
231
  : [];
195
- const repos: Array<{ full_name: string; url: string }> = [];
232
+ const repos: Array<{ full_name: string; url: string; default_branch?: string }> = [];
196
233
  for (const row of items) {
197
234
  const full = String(row?.full_name ?? '');
198
235
  if (!full || !String(row?.html_url ?? '').startsWith('https://github.com/')) continue;
199
- repos.push({ full_name: full, url: String(row.html_url) });
236
+ const branch = typeof row?.default_branch === 'string' ? row.default_branch : undefined;
237
+ repos.push({ full_name: full, url: String(row.html_url), ...(branch ? { default_branch: branch } : {}) });
200
238
  }
201
239
  return repos;
202
240
  }
@@ -257,6 +295,113 @@ export class GitHubClient {
257
295
  return false;
258
296
  }
259
297
 
298
+ /**
299
+ * Plan bond-app-ticket-desde-pr P1: one pull request, for a ticket that starts from it —
300
+ * its branches, state, whether it comes from a fork, and its title and description.
301
+ */
302
+ async getPullRequest(token: string, owner: string, repo: string, number: number): Promise<{
303
+ number: number; url: string; title: string; body: string; head: string; base: string;
304
+ state: 'open' | 'closed' | 'merged'; draft: boolean; is_fork: boolean; author?: string;
305
+ }> {
306
+ const res = await this.call(token, 'GET', `/repos/${owner}/${repo}/pulls/${number}`);
307
+ if (res.status !== 200) {
308
+ const msg = (res.data as { message?: string } | null)?.message || `HTTP ${res.status}`;
309
+ throw new GitHubApiError(`Failed to fetch GitHub pull request ${owner}/${repo}#${number}: ${msg}`, res.status);
310
+ }
311
+ const d = res.data as {
312
+ number: number; html_url: string; title?: string; body?: string | null; state?: string; merged?: boolean; merged_at?: string | null; draft?: boolean;
313
+ user?: { login?: string };
314
+ head?: { ref?: string; repo?: { full_name?: string } | null };
315
+ base?: { ref?: string; repo?: { full_name?: string } | null };
316
+ };
317
+ const headRepo = String(d.head?.repo?.full_name ?? '').toLowerCase();
318
+ const baseRepo = String(d.base?.repo?.full_name ?? `${owner}/${repo}`).toLowerCase();
319
+ return {
320
+ number: d.number,
321
+ url: d.html_url,
322
+ title: d.title || '',
323
+ body: String(d.body ?? '').slice(0, 8000),
324
+ head: String(d.head?.ref ?? ''),
325
+ base: String(d.base?.ref ?? ''),
326
+ state: d.merged || d.merged_at ? 'merged' : d.state === 'open' ? 'open' : 'closed',
327
+ draft: Boolean(d.draft),
328
+ // A deleted fork leaves head.repo null: still not a branch of this repo.
329
+ is_fork: headRepo !== baseRepo,
330
+ ...(d.user?.login ? { author: d.user.login } : {}),
331
+ };
332
+ }
333
+
334
+ /**
335
+ * P1: open pull requests — the ones that involve the token's owner (author, assignee,
336
+ * reviewer, mentioned) or, with `repo` (`owner/repo`), all open ones of that repo —
337
+ * narrowed by `q` (GitHub's search over title and body). Most recently updated first.
338
+ */
339
+ async searchPullRequests(token: string, q: string, repo?: { owner: string; repo: string }, mine?: 'assigned' | 'author'): Promise<Array<{
340
+ url: string; number: number; title: string; owner: string; repo: string; author?: string; updated_at?: string; draft: boolean;
341
+ }>> {
342
+ // «Asignadas a mí» = revisor pedido o asignado (dos búsquedas: GitHub no hace OR de
343
+ // calificadores); «Mías» = autor. Sin filtro: las que te implican, o todas las del repo.
344
+ if (mine === 'assigned') {
345
+ const [review, assignee] = await Promise.all([
346
+ this.searchPullRequestsWith(token, q, repo, 'review-requested:@me'),
347
+ this.searchPullRequestsWith(token, q, repo, 'assignee:@me'),
348
+ ]);
349
+ const seen = new Set<string>();
350
+ return [...review, ...assignee]
351
+ .filter((p) => (seen.has(p.url) ? false : (seen.add(p.url), true)))
352
+ .sort((a, b) => String(b.updated_at ?? '').localeCompare(String(a.updated_at ?? '')));
353
+ }
354
+ return this.searchPullRequestsWith(token, q, repo, mine === 'author' ? 'author:@me' : repo ? null : 'involves:@me');
355
+ }
356
+
357
+ private async searchPullRequestsWith(token: string, q: string, repo: { owner: string; repo: string } | undefined, who: string | null): Promise<Array<{
358
+ url: string; number: number; title: string; owner: string; repo: string; author?: string; updated_at?: string; draft: boolean;
359
+ }>> {
360
+ const terms = ['is:pr', 'is:open', ...(repo ? [`repo:${repo.owner}/${repo.repo}`] : []), ...(who ? [who] : []), ...q.trim().split(/\s+/).filter(Boolean).slice(0, 10)];
361
+ const res = await this.call(token, 'GET', `/search/issues?q=${encodeURIComponent(terms.join(' '))}&sort=updated&order=desc&per_page=30`);
362
+ if (res.status !== 200) {
363
+ const msg = (res.data as { message?: string } | null)?.message || `HTTP ${res.status}`;
364
+ throw new GitHubApiError(`Failed to search GitHub pull requests: ${msg}`, res.status);
365
+ }
366
+ const items = Array.isArray((res.data as { items?: unknown })?.items) ? (res.data as { items: Array<Record<string, unknown>> }).items : [];
367
+ const out: Array<{ url: string; number: number; title: string; owner: string; repo: string; author?: string; updated_at?: string; draft: boolean }> = [];
368
+ for (const row of items) {
369
+ const url = String(row?.html_url ?? '');
370
+ const m = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/pull\/([1-9][0-9]*)$/.exec(url);
371
+ if (!m) continue;
372
+ const author = String((row?.user as { login?: string } | undefined)?.login ?? '');
373
+ out.push({
374
+ url,
375
+ number: parseInt(m[3], 10),
376
+ title: String(row?.title ?? ''),
377
+ owner: m[1],
378
+ repo: m[2],
379
+ ...(author ? { author } : {}),
380
+ ...(row?.updated_at ? { updated_at: String(row.updated_at) } : {}),
381
+ draft: Boolean(row?.draft),
382
+ });
383
+ }
384
+ return out;
385
+ }
386
+
387
+ /** P1: the open PR whose head is `branch` in that repo (a branch URL that already has one). */
388
+ async findOpenPullRequestByHead(token: string, owner: string, repo: string, branch: string): Promise<number | null> {
389
+ const res = await this.call(token, 'GET', `/repos/${owner}/${repo}/pulls?head=${encodeURIComponent(`${owner}:${branch}`)}&state=open&per_page=5`);
390
+ if (res.status !== 200 || !Array.isArray(res.data)) return null;
391
+ const first = (res.data as Array<{ number?: number }>)[0];
392
+ return first?.number ?? null;
393
+ }
394
+
395
+ /** P1: the repo's default branch (the base of a ticket started from a bare branch). */
396
+ async getDefaultBranch(token: string, owner: string, repo: string): Promise<string> {
397
+ const res = await this.call(token, 'GET', `/repos/${owner}/${repo}`);
398
+ if (res.status !== 200) {
399
+ const msg = (res.data as { message?: string } | null)?.message || `HTTP ${res.status}`;
400
+ throw new GitHubApiError(`Failed to read GitHub repo ${owner}/${repo}: ${msg}`, res.status);
401
+ }
402
+ return String((res.data as { default_branch?: string }).default_branch || 'main');
403
+ }
404
+
260
405
  /** P7: delete a remote branch from GitHub. */
261
406
  async deleteRemoteBranch(token: string, owner: string, repo: string, branch: string): Promise<boolean> {
262
407
  const res = await this.call(token, 'DELETE', `/repos/${owner}/${repo}/git/refs/heads/${encodeURIComponent(branch)}`);
@@ -45,12 +45,24 @@ export function machineNameForRun(runId: string): string {
45
45
  return name;
46
46
  }
47
47
 
48
- /** The `--via` command that reaches a container as `runner`, like the hub spike (D19). */
48
+ /**
49
+ * The script that exports the credentials meant for the agents of the run (plan
50
+ * bond-app-azure-jira P0). Written by the orchestrator before the machine is added.
51
+ */
52
+ export const AGENT_ENV_SCRIPT = '/home/runner/.config/bond-app/agent-env.sh';
53
+
54
+ /**
55
+ * The `--via` command that reaches a container as `runner`, like the hub spike (D19). It
56
+ * loads AGENT_ENV_SCRIPT first (when present) and then runs what hc sends ($1): the hc core
57
+ * it starts, and so every terminal of the run (the agent, its delegates, their MCP
58
+ * servers), carries the agent credentials. Not BASH_ENV: bash ignores it when its stdin is
59
+ * a socket (it takes itself for an ssh shell). Checked with a real hc machine.
60
+ */
49
61
  export function viaCommandFor(containerName: string): string {
50
62
  if (!CONTAINER_RE.test(containerName)) {
51
63
  throw new HcError(`Invalid container name '${containerName}'`, 'usage');
52
64
  }
53
- return `docker exec -i -u runner -w /home/runner ${containerName} sh -c`;
65
+ return `docker exec -i -u runner -w /home/runner ${containerName} sh -c '[ -r ${AGENT_ENV_SCRIPT} ] && . ${AGENT_ENV_SCRIPT}; exec sh -c "$1"' bond-app-agent-env`;
54
66
  }
55
67
 
56
68
  export interface HcMachineInfo {
@@ -153,7 +165,7 @@ export class HcClient {
153
165
  machine: string,
154
166
  argv: string[],
155
167
  cwd: string,
156
- name = 'agent',
168
+ name = 'gru',
157
169
  labels: Record<string, string> = { 'herdr.space': 's1', 'herdr.tab': 't1' }
158
170
  ): Promise<string> {
159
171
  if (argv.length === 0) throw new HcError('Empty agent command', 'usage');
@@ -191,7 +203,7 @@ export class HcClient {
191
203
  foreground?: { name?: string };
192
204
  };
193
205
  const rawAgent = (res as any).agent || res.name || res.foreground?.name;
194
- const isGeneric = rawAgent === 'agent' || (typeof rawAgent === 'string' && /^t\d+$/.test(rawAgent));
206
+ const isGeneric = rawAgent === 'agent' || rawAgent === 'gru' || (typeof rawAgent === 'string' && /^t\d+$/.test(rawAgent));
195
207
  const agent = isGeneric ? undefined : rawAgent;
196
208
  return {
197
209
  address,
@@ -279,7 +291,7 @@ export class HcClient {
279
291
  const detail = await this.getTerminal(t.address);
280
292
  return {
281
293
  ...detail,
282
- agent: detail.agent && detail.agent !== 'agent' ? detail.agent : (t.agent || t.name),
294
+ agent: detail.agent && detail.agent !== 'agent' && detail.agent !== 'gru' ? detail.agent : (t.agent || t.name),
283
295
  };
284
296
  } catch {
285
297
  return {
@@ -308,6 +320,22 @@ export class HcClient {
308
320
  await this.call(['send', '--json', '--force', '--', address, text]);
309
321
  }
310
322
 
323
+ /**
324
+ * P2: Print terminal screen and history (`hc read <address>`).
325
+ */
326
+ async readTerminal(address: string, lines = 100): Promise<string> {
327
+ try {
328
+ const { stdout } = await this.exec(this.bin, ['read', address, '--lines', String(lines)], {
329
+ env: process.env,
330
+ timeout: HC_TIMEOUT_MS,
331
+ maxBuffer: 4 * 1024 * 1024,
332
+ });
333
+ return String(stdout);
334
+ } catch {
335
+ return '';
336
+ }
337
+ }
338
+
311
339
  /**
312
340
  * Review M1: a missing agent binary or one that rejects its argv exits at once. Give the
313
341
  * program a moment, then fail the start if its terminal already finished.
@@ -1,10 +1,10 @@
1
- import { execFile } from 'node:child_process';
2
- import { promisify } from 'node:util';
1
+ import { spawn } from 'node:child_process';
2
+ import crypto from 'node:crypto';
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
+ import { DEFAULT_TOOLS, validateAptExtra, validateToolGroups } from './tool-catalog.ts';
6
7
 
7
- const execFileAsync = promisify(execFile);
8
8
 
9
9
  // The runner image build context (Dockerfile with pinned bond/hc/agent versions).
10
10
  const runnerBuildContext = path.resolve(
@@ -41,10 +41,50 @@ export interface RunnerBuildOptions extends RunnerVersions {
41
41
  /** System CLIs (setup.sh --skip-gh / --skip-az); az is heavy and rarely needed. */
42
42
  skip_az?: boolean;
43
43
  skip_gh?: boolean;
44
+ /** Plan bond-app-ajustes-imagen P2: developer tool groups (default: the catalog's). */
45
+ tools?: string[];
46
+ /** Extra Debian packages (setup.sh --apt-extra). */
47
+ apt_extra?: string[];
44
48
  config_dir?: string;
45
49
  credentials_file?: string;
46
50
  /** Root the staged paths must resolve inside of (the orchestrator injects its data dir). */
47
51
  data_dir?: string;
52
+ /** Called as the build advances (steps and setup.sh's narration). */
53
+ on_progress?: (progress: BuildProgress) => void;
54
+ }
55
+
56
+ /**
57
+ * The recipe's fingerprint: sha256 over every file of the build context that shapes the
58
+ * image (Dockerfile, setup.sh, versions.env, the run scripts…), path and content, in a
59
+ * fixed order. Leaves out the staging dirs (build-config, build-creds) and the docs (*.md).
60
+ * Baked as the image label LABEL_RECIPE; a different value means the image is stale even
61
+ * when it carries the chosen agents and tools (a fixed setup.sh, a new pin).
62
+ */
63
+ export const LABEL_RECIPE = 'dev.bond-app.recipe';
64
+
65
+ export function runnerRecipeHash(context: string = runnerBuildContext): string {
66
+ const files: string[] = [];
67
+ const walk = (dir: string) => {
68
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
69
+ const full = path.join(dir, entry.name);
70
+ const rel = path.relative(context, full);
71
+ if (entry.isDirectory()) {
72
+ if (rel === 'build-config' || rel === 'build-creds') continue;
73
+ walk(full);
74
+ } else if (entry.isFile() && !entry.name.endsWith('.md')) {
75
+ files.push(rel);
76
+ }
77
+ }
78
+ };
79
+ walk(context);
80
+ const hash = crypto.createHash('sha256');
81
+ for (const rel of files.sort()) {
82
+ hash.update(rel.split(path.sep).join('/'));
83
+ hash.update('\0');
84
+ hash.update(fs.readFileSync(path.join(context, rel)));
85
+ hash.update('\0');
86
+ }
87
+ return hash.digest('hex').slice(0, 16);
48
88
  }
49
89
 
50
90
  /** The agent list runner/setup.sh accepts (kept in sync; setup.sh is still the judge). */
@@ -86,6 +126,62 @@ export type DockerExec = (
86
126
  options: Record<string, unknown>
87
127
  ) => Promise<unknown>;
88
128
 
129
+ /** Progress of a running build, parsed from docker's output (plan bond-app-ajustes-imagen). */
130
+ export interface BuildProgress {
131
+ /** «Step N/M» of the classic builder; 0 until the first step. */
132
+ step: number;
133
+ total: number;
134
+ /** What it is doing, in words: the last setup.sh line or the step's instruction. */
135
+ detail: string;
136
+ }
137
+
138
+ /**
139
+ * Reads one line of `docker build` output into the progress: «Step 12/27 : RUN …» moves the
140
+ * step, a «setup.sh: …» line (the installer narrating) becomes the detail. Other lines leave
141
+ * it as it was. Never returns secrets: setup.sh masks credential values itself.
142
+ */
143
+ export function parseBuildLine(line: string, prev: BuildProgress): BuildProgress {
144
+ const clean = line.replace(/\x1b\[[0-9;]*[A-Za-z]/g, '').trim();
145
+ const step = clean.match(/^Step (\d+)\/(\d+) : (.*)$/);
146
+ if (step) {
147
+ const instr = step[3].replace(/\s+/g, ' ');
148
+ return { step: Number(step[1]), total: Number(step[2]), detail: instr.length > 90 ? `${instr.slice(0, 89)}…` : instr };
149
+ }
150
+ const setup = clean.match(/^setup\.sh: (?!ERROR)(.*)$/);
151
+ if (setup) return { ...prev, detail: setup[1].slice(0, 120) };
152
+ return prev;
153
+ }
154
+
155
+ /**
156
+ * The default runner of `docker build`: like execFile (rejects on a non-zero exit or the
157
+ * timeout), but hands every output line to `options.onLine` as it arrives.
158
+ */
159
+ const spawnDocker: DockerExec = (file, args, options) =>
160
+ new Promise((resolve, reject) => {
161
+ const onLine = options.onLine as ((line: string) => void) | undefined;
162
+ const child = spawn(file, args, { env: options.env as NodeJS.ProcessEnv, stdio: ['ignore', 'pipe', 'pipe'] });
163
+ let tail = '';
164
+ let buf = '';
165
+ const feed = (chunk: Buffer) => {
166
+ const text = chunk.toString('utf8');
167
+ tail = (tail + text).slice(-8000);
168
+ buf += text;
169
+ const lines = buf.split(/\r?\n/);
170
+ buf = lines.pop() ?? '';
171
+ for (const l of lines) onLine?.(l);
172
+ };
173
+ child.stdout.on('data', feed);
174
+ child.stderr.on('data', feed);
175
+ const timer = setTimeout(() => child.kill('SIGTERM'), Number(options.timeout) || BUILD_TIMEOUT_MS);
176
+ child.on('error', (err) => { clearTimeout(timer); reject(err); });
177
+ child.on('close', (code, signal) => {
178
+ clearTimeout(timer);
179
+ if (buf) onLine?.(buf);
180
+ if (code === 0) resolve({ stdout: tail });
181
+ else reject(new Error(`docker build exited with ${code ?? signal}: ${tail.slice(-2000)}`));
182
+ });
183
+ });
184
+
89
185
  /** Validate the agent list: non-empty array of known names, no duplicates. */
90
186
  export function validateRunnerAgents(agents: unknown): string[] {
91
187
  if (!Array.isArray(agents) || agents.length === 0) {
@@ -192,9 +288,11 @@ export function stageBuildContext(
192
288
  export async function rebuildRunnerImage(
193
289
  image: string,
194
290
  options: RunnerBuildOptions = {},
195
- exec: DockerExec = execFileAsync as unknown as DockerExec
291
+ exec: DockerExec = spawnDocker,
292
+ onProgress?: (progress: BuildProgress) => void
196
293
  ): Promise<void> {
197
- const { agents, skip_az, skip_gh, config_dir, credentials_file, data_dir, ...versions } = options;
294
+ const { agents, skip_az, skip_gh, tools, apt_extra, config_dir, credentials_file, data_dir, on_progress, ...versions } = options;
295
+ onProgress = onProgress ?? on_progress;
198
296
  const args: string[] = ['build', '--pull'];
199
297
  if ((versions.hc === undefined) !== (versions.hc_sha256 === undefined)) {
200
298
  throw new InvalidVersionError("'hc' and 'hc_sha256' go together: a new hc version needs its checksum");
@@ -233,16 +331,36 @@ export async function rebuildRunnerImage(
233
331
  args.push('--build-arg', `AGENTS=${agentList.join(',')}`);
234
332
  if (skip_az !== undefined) args.push('--build-arg', `SKIP_AZ=${skip_az ? '1' : '0'}`);
235
333
  if (skip_gh !== undefined) args.push('--build-arg', `SKIP_GH=${skip_gh ? '1' : '0'}`);
334
+ let toolList: string[];
335
+ let aptList: string[];
336
+ try {
337
+ toolList = tools === undefined ? [...DEFAULT_TOOLS] : validateToolGroups(tools);
338
+ aptList = apt_extra === undefined ? [] : validateAptExtra(apt_extra);
339
+ } catch (err) {
340
+ throw new InvalidBuildOptionsError((err as Error).message);
341
+ }
342
+ args.push('--build-arg', `TOOLS=${toolList.join(',')}`);
343
+ args.push('--build-arg', `RECIPE=${runnerRecipeHash()}`);
344
+ args.push('--build-arg', `APT_EXTRA=${aptList.join(',')}`);
236
345
  if ((config_dir !== undefined || credentials_file !== undefined) && !data_dir) {
237
346
  throw new InvalidBuildOptionsError("'data_dir' is required to stage config or credentials");
238
347
  }
239
348
 
240
349
  const cleanup = stageBuildContext(runnerBuildContext, { config_dir, credentials_file, data_dir });
241
350
  try {
351
+ let progress: BuildProgress = { step: 0, total: 0, detail: 'Preparando el build…' };
352
+ onProgress?.(progress);
242
353
  await exec('docker', [...args, '-t', image, runnerBuildContext], {
243
354
  env: { ...process.env, DOCKER_BUILDKIT: '0' },
244
355
  timeout: BUILD_TIMEOUT_MS,
245
356
  maxBuffer: 32 * 1024 * 1024,
357
+ onLine: (line: string) => {
358
+ const next = parseBuildLine(line, progress);
359
+ if (next !== progress) {
360
+ progress = next;
361
+ onProgress?.(progress);
362
+ }
363
+ },
246
364
  });
247
365
  } catch (err) {
248
366
  const detail = err instanceof Error ? err.message : String(err);