@jmanuelcorral/bond-app 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +241 -7
  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 +8 -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 +316 -330
  11. package/app/mods/bond-agents/model.js +400 -6
  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 +8 -0
  16. package/app/mods/bond-board/main.js +1054 -366
  17. package/app/mods/bond-board/model.js +138 -17
  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 +8 -0
  30. package/app/mods/bond-settings/main.js +1645 -87
  31. package/app/mods/bond-settings/mod.json +1 -1
  32. package/app/mods/bond-settings/pi-models.js +144 -0
  33. package/app/mods/bond-status/api.js +35 -0
  34. package/app/mods/bond-status/brand.js +53 -2
  35. package/app/mods/bond-status/config.js +8 -0
  36. package/app/mods/bond-status/main.js +37 -15
  37. package/app/mods/bond-status/model.js +19 -1
  38. package/app/mods/bond-tabs/brand.js +53 -2
  39. package/app/mods/bond-tabs/main.js +45 -3
  40. package/app/mods/bond-titlebar/brand.js +53 -2
  41. package/app/mods/bond-titlebar/main.js +115 -55
  42. package/app/mods/bond-titlebar/version.js +3 -0
  43. package/app/themes/bond-dark.json +5 -5
  44. package/app/themes/bond-light.json +5 -5
  45. package/package.json +1 -1
  46. package/runner/Dockerfile +58 -15
  47. package/runner/SPIKE-BOND.md +89 -0
  48. package/runner/build-config/.none +0 -0
  49. package/runner/build-creds/.none +0 -0
  50. package/runner/config.example/README.md +27 -0
  51. package/runner/config.example/pi/models.json +22 -0
  52. package/runner/credentials.example.env +27 -0
  53. package/runner/entrypoint.sh +16 -0
  54. package/runner/setup.sh +927 -0
  55. package/runner/versions.env +61 -0
  56. package/scripts/app-install.ts +64 -1
  57. package/src/cli.ts +53 -3
  58. package/src/config.ts +8 -0
  59. package/src/core/agy-login.ts +682 -0
  60. package/src/core/delivery.ts +3 -1
  61. package/src/core/hub-session.ts +9 -7
  62. package/src/core/orchestrator.ts +1186 -168
  63. package/src/core/repo-host.ts +60 -0
  64. package/src/core/setup.ts +239 -0
  65. package/src/core/watchdog.ts +6 -6
  66. package/src/db/database.ts +55 -1
  67. package/src/db/settings-repo.ts +440 -7
  68. package/src/db/ticket-repo.ts +73 -17
  69. package/src/index.ts +4 -4
  70. package/src/runner/azure-devops-client.ts +163 -0
  71. package/src/runner/docker-client.ts +84 -5
  72. package/src/runner/github-client.ts +146 -0
  73. package/src/runner/hc-client.ts +40 -5
  74. package/src/runner/image-builder.ts +268 -10
  75. package/src/runner/jira-client.ts +368 -0
  76. package/src/runner/tool-catalog.ts +84 -0
  77. package/src/server/app.ts +585 -9
  78. package/src/types.ts +168 -1
@@ -29,6 +29,20 @@ export interface PullRequest {
29
29
  created: boolean;
30
30
  }
31
31
 
32
+ /** Plan bond-app-nuevo-ticket (P1): una issue asignada al dueño del token, para el diálogo. */
33
+ export interface AssignedIssue {
34
+ url: string;
35
+ number: number;
36
+ owner: string;
37
+ repo: string;
38
+ title: string;
39
+ labels: string[];
40
+ ready: boolean;
41
+ updated_at: string;
42
+ /** Cuerpo de la issue (la US); recortado. El alta de ticket lo lleva como historia. */
43
+ body?: string;
44
+ }
45
+
32
46
  export class GitHubClient {
33
47
  private fetchImpl: FetchLike;
34
48
  private apiBase: string;
@@ -119,12 +133,144 @@ export class GitHubClient {
119
133
  };
120
134
  }
121
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
+
122
162
  /** P7: check if a remote branch exists on GitHub. */
123
163
  async remoteBranchExists(token: string, owner: string, repo: string, branch: string): Promise<boolean> {
124
164
  const res = await this.call(token, 'GET', `/repos/${owner}/${repo}/branches/${encodeURIComponent(branch)}`);
125
165
  return res.status === 200;
126
166
  }
127
167
 
168
+ /**
169
+ * Plan bond-app-nuevo-ticket (P1, D2): open issues assigned to the token's owner, across
170
+ * repos. Pull requests ride the /issues endpoints and are dropped here; `ready` is the
171
+ * label and sorts first, then most recently updated. 401/403 read as a credential problem.
172
+ */
173
+ async listAssigned(token: string): Promise<AssignedIssue[]> {
174
+ // REST root /issues: "issues assigned to the authenticated user" across repos
175
+ // (there is no /issues/assigned path on api.github.com; 404). PRs come mixed in
176
+ // and are filtered out below by the html_url shape.
177
+ const res = await this.call(token, 'GET', '/issues?state=open&per_page=100');
178
+ if (res.status !== 200) {
179
+ const msg = (res.data as { message?: string } | null)?.message || `HTTP ${res.status}`;
180
+ throw new GitHubApiError(`Failed to list assigned GitHub issues: ${msg}`, res.status);
181
+ }
182
+ const rows = Array.isArray(res.data) ? (res.data as Array<Record<string, unknown>>) : [];
183
+ const issues: AssignedIssue[] = [];
184
+ for (const row of rows) {
185
+ const url = String(row?.html_url ?? '');
186
+ const m = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/issues\/([1-9][0-9]*)$/.exec(url);
187
+ if (!m) continue; // pull requests and anything not a plain issue URL
188
+ const labels = Array.isArray(row?.labels)
189
+ ? (row.labels as Array<unknown>).map((l) => String((l as { name?: string })?.name ?? l ?? '')).filter(Boolean)
190
+ : [];
191
+ issues.push({
192
+ url,
193
+ number: parseInt(m[3], 10),
194
+ owner: m[1],
195
+ repo: m[2],
196
+ title: String(row?.title ?? ''),
197
+ labels,
198
+ ready: labels.some((l) => l.toLowerCase() === 'ready'),
199
+ updated_at: String(row?.updated_at ?? ''),
200
+ body: String(row?.body ?? '').slice(0, 8000),
201
+ });
202
+ }
203
+ issues.sort((a, b) => (Number(b.ready) - Number(a.ready)) || String(b.updated_at).localeCompare(String(a.updated_at)));
204
+ return issues;
205
+ }
206
+
207
+ /**
208
+ * Plan bond-app-nuevo-ticket (P2, búsqueda combinada): repos por nombre (los públicos y
209
+ * los privados accesibles con el token). La búsqueda es el buscador de GitHub sobre el
210
+ * nombre/descripción; orden tal cual los devuelve GitHub (best match).
211
+ */
212
+ async searchRepos(token: string, term: string): Promise<Array<{ full_name: string; url: string; default_branch?: string }>> {
213
+ const res = await this.call(token, 'GET', `/search/repositories?q=${encodeURIComponent(term)}&per_page=20`);
214
+ if (res.status !== 200) {
215
+ const msg = (res.data as { message?: string } | null)?.message || `HTTP ${res.status}`;
216
+ throw new GitHubApiError(`Failed to search GitHub repositories: ${msg}`, res.status);
217
+ }
218
+ const items = Array.isArray((res.data as { items?: unknown })?.items)
219
+ ? ((res.data as { items: Array<Record<string, unknown>> }).items)
220
+ : [];
221
+ const repos: Array<{ full_name: string; url: string; default_branch?: string }> = [];
222
+ for (const row of items) {
223
+ const full = String(row?.full_name ?? '');
224
+ if (!full || !String(row?.html_url ?? '').startsWith('https://github.com/')) continue;
225
+ const branch = typeof row?.default_branch === 'string' ? row.default_branch : undefined;
226
+ repos.push({ full_name: full, url: String(row.html_url), ...(branch ? { default_branch: branch } : {}) });
227
+ }
228
+ return repos;
229
+ }
230
+
231
+ /**
232
+ * Open issues of one repo (the second step of the combined search): all open issues,
233
+ * not only assigned ones — `ready` first, the ones assigned to `myLogin` next.
234
+ */
235
+ async listRepoIssues(token: string, owner: string, repo: string, myLogin?: string | null) {
236
+ const res = await this.call(token, 'GET', `/repos/${owner}/${repo}/issues?state=open&per_page=100`);
237
+ if (res.status !== 200) {
238
+ const msg = (res.data as { message?: string } | null)?.message || `HTTP ${res.status}`;
239
+ throw new GitHubApiError(`Failed to list repo issues: ${msg}`, res.status);
240
+ }
241
+ const rows = Array.isArray(res.data) ? (res.data as Array<Record<string, unknown>>) : [];
242
+ const login = String(myLogin ?? '').toLowerCase();
243
+ const issues: Array<AssignedIssue & { assigned_to_me: boolean }> = [];
244
+ for (const row of rows) {
245
+ const url = String(row?.html_url ?? '');
246
+ const m = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/issues\/([1-9][0-9]*)$/.exec(url);
247
+ if (!m) continue; // pull requests ride /repos/.../issues too
248
+ const labels = Array.isArray(row?.labels)
249
+ ? (row.labels as Array<unknown>).map((l) => String((l as { name?: string })?.name ?? l ?? '')).filter(Boolean)
250
+ : [];
251
+ const assignees = Array.isArray(row?.assignees)
252
+ ? (row.assignees as Array<Record<string, unknown>>).map((a) => String(a?.login ?? '').toLowerCase())
253
+ : [];
254
+ issues.push({
255
+ url,
256
+ number: parseInt(m[3], 10),
257
+ owner: m[1],
258
+ repo: m[2],
259
+ title: String(row?.title ?? ''),
260
+ labels,
261
+ ready: labels.some((l) => l.toLowerCase() === 'ready'),
262
+ updated_at: String(row?.updated_at ?? ''),
263
+ body: String(row?.body ?? '').slice(0, 8000),
264
+ assigned_to_me: Boolean(login) && assignees.includes(login),
265
+ });
266
+ }
267
+ issues.sort((a, b) =>
268
+ (Number(b.ready) - Number(a.ready))
269
+ || (Number(b.assigned_to_me) - Number(a.assigned_to_me))
270
+ || String(b.updated_at).localeCompare(String(a.updated_at)));
271
+ return issues;
272
+ }
273
+
128
274
  /**
129
275
  * P7: whether `branch` is merged into `base` in `owner/repo`.
130
276
  * Checks compare endpoint: status 'identical' or 'behind' (ahead_by === 0) means all commits in branch are in base.
@@ -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');
@@ -190,6 +202,9 @@ export class HcClient {
190
202
  labels?: Record<string, string>;
191
203
  foreground?: { name?: string };
192
204
  };
205
+ const rawAgent = (res as any).agent || res.name || res.foreground?.name;
206
+ const isGeneric = rawAgent === 'agent' || rawAgent === 'gru' || (typeof rawAgent === 'string' && /^t\d+$/.test(rawAgent));
207
+ const agent = isGeneric ? undefined : rawAgent;
193
208
  return {
194
209
  address,
195
210
  name: res.name,
@@ -199,7 +214,7 @@ export class HcClient {
199
214
  exit_code: res.exit_code ?? null,
200
215
  turn: typeof res.turn === 'number' ? res.turn : 0,
201
216
  labels: res.labels ?? {},
202
- agent: res.name || res.foreground?.name,
217
+ agent,
203
218
  };
204
219
  }
205
220
 
@@ -273,7 +288,11 @@ export class HcClient {
273
288
  };
274
289
  }
275
290
  try {
276
- return await this.getTerminal(t.address);
291
+ const detail = await this.getTerminal(t.address);
292
+ return {
293
+ ...detail,
294
+ agent: detail.agent && detail.agent !== 'agent' && detail.agent !== 'gru' ? detail.agent : (t.agent || t.name),
295
+ };
277
296
  } catch {
278
297
  return {
279
298
  address: t.address,
@@ -301,6 +320,22 @@ export class HcClient {
301
320
  await this.call(['send', '--json', '--force', '--', address, text]);
302
321
  }
303
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
+
304
339
  /**
305
340
  * Review M1: a missing agent binary or one that rejects its argv exits at once. Give the
306
341
  * program a moment, then fail the start if its terminal already finished.
@@ -1,9 +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
+ import fs from 'node:fs';
3
4
  import path from 'node:path';
4
5
  import { fileURLToPath } from 'node:url';
6
+ import { DEFAULT_TOOLS, validateAptExtra, validateToolGroups } from './tool-catalog.ts';
5
7
 
6
- const execFileAsync = promisify(execFile);
7
8
 
8
9
  // The runner image build context (Dockerfile with pinned bond/hc/agent versions).
9
10
  const runnerBuildContext = path.resolve(
@@ -29,6 +30,66 @@ export interface RunnerVersions {
29
30
  pi?: string;
30
31
  }
31
32
 
33
+ /**
34
+ * Image plan P2: what a rebuild bakes besides versions. `agents` is the setup.sh agent
35
+ * list (default ['pi'], parity with the current image). `config_dir` and `credentials_file`
36
+ * are absolute paths that must live inside `data_dir` (validated: no traversal, no
37
+ * symlink escape); they get staged into the build context for the duration of the build.
38
+ */
39
+ export interface RunnerBuildOptions extends RunnerVersions {
40
+ agents?: string[];
41
+ /** System CLIs (setup.sh --skip-gh / --skip-az); az is heavy and rarely needed. */
42
+ skip_az?: boolean;
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[];
48
+ config_dir?: string;
49
+ credentials_file?: string;
50
+ /** Root the staged paths must resolve inside of (the orchestrator injects its data dir). */
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);
88
+ }
89
+
90
+ /** The agent list runner/setup.sh accepts (kept in sync; setup.sh is still the judge). */
91
+ export const RUNNER_AGENT_NAMES = ['pi', 'claude', 'codex', 'copilot', 'agy'] as const;
92
+
32
93
  export class InvalidVersionError extends Error {
33
94
  constructor(message: string) {
34
95
  super(message);
@@ -36,6 +97,14 @@ export class InvalidVersionError extends Error {
36
97
  }
37
98
  }
38
99
 
100
+ /** P2 (image plan): bad agents/config_dir/credentials_file; the server maps it to 400. */
101
+ export class InvalidBuildOptionsError extends Error {
102
+ constructor(message: string) {
103
+ super(message);
104
+ this.name = 'InvalidBuildOptionsError';
105
+ }
106
+ }
107
+
39
108
  /** Sanitized build failure: the message never carries docker's stderr. */
40
109
  export class RunnerBuildError extends Error {
41
110
  constructor(message: string) {
@@ -57,16 +126,173 @@ export type DockerExec = (
57
126
  options: Record<string, unknown>
58
127
  ) => Promise<unknown>;
59
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
+
60
155
  /**
61
- * P2 criterion 7 (D7): rebuild the runner image to pick up new pinned versions of
62
- * bond, hc and the agents. Credentials are never part of the image, so a rebuild
63
- * never touches them; nothing secret is passed to `docker build`.
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
+
185
+ /** Validate the agent list: non-empty array of known names, no duplicates. */
186
+ export function validateRunnerAgents(agents: unknown): string[] {
187
+ if (!Array.isArray(agents) || agents.length === 0) {
188
+ throw new InvalidBuildOptionsError("'agents' must be a non-empty array of agent names");
189
+ }
190
+ const out: string[] = [];
191
+ for (const a of agents) {
192
+ if (typeof a !== 'string' || !a) {
193
+ throw new InvalidBuildOptionsError("'agents' must contain non-empty strings");
194
+ }
195
+ if (!(RUNNER_AGENT_NAMES as readonly string[]).includes(a)) {
196
+ throw new InvalidBuildOptionsError(
197
+ `unsupported agent '${a}': setup.sh installs ${RUNNER_AGENT_NAMES.join(', ')}`
198
+ );
199
+ }
200
+ if (out.includes(a)) {
201
+ throw new InvalidBuildOptionsError(`duplicate agent in 'agents': '${a}'`);
202
+ }
203
+ out.push(a);
204
+ }
205
+ return out;
206
+ }
207
+
208
+ /**
209
+ * A staged path (config_dir / credentials_file) must be absolute and resolve — following
210
+ * symlinks — inside data_dir. Rejects traversal ('..') and symlink escape (V).
211
+ */
212
+ function assertInsideDataDir(p: string, dataDir: string, label: string): string {
213
+ if (!path.isAbsolute(p)) {
214
+ throw new InvalidBuildOptionsError(`'${label}' must be an absolute path inside the data dir`);
215
+ }
216
+ const root = fs.realpathSync(dataDir);
217
+ let real: string;
218
+ try {
219
+ real = fs.realpathSync(p);
220
+ } catch {
221
+ throw new InvalidBuildOptionsError(`'${label}' does not exist: not a readable path`);
222
+ }
223
+ if (real !== root && !real.startsWith(root + path.sep)) {
224
+ throw new InvalidBuildOptionsError(`'${label}' must stay inside the data dir`);
225
+ }
226
+ return real;
227
+ }
228
+
229
+ /**
230
+ * Stage the optional config/credentials into the build context and return a cleanup that
231
+ * restores the empty (".none") state. The Dockerfile COPYs both directories unconditionally:
232
+ * build-config/.none / build-creds/.none mean "nothing staged".
233
+ */
234
+ export function stageBuildContext(
235
+ context: string,
236
+ options: Pick<RunnerBuildOptions, 'config_dir' | 'credentials_file' | 'data_dir'>
237
+ ): () => void {
238
+ const configDir = path.join(context, 'build-config');
239
+ const credsDir = path.join(context, 'build-creds');
240
+
241
+ const resetDir = (dir: string) => {
242
+ fs.rmSync(dir, { recursive: true, force: true });
243
+ fs.mkdirSync(dir, { recursive: true });
244
+ fs.writeFileSync(path.join(dir, '.none'), '');
245
+ };
246
+ resetDir(configDir);
247
+ resetDir(credsDir);
248
+
249
+ if (options.config_dir !== undefined) {
250
+ const src = assertInsideDataDir(options.config_dir, options.data_dir ?? '', 'config_dir');
251
+ if (!fs.statSync(src).isDirectory()) {
252
+ throw new InvalidBuildOptionsError("'config_dir' is not a directory");
253
+ }
254
+ fs.rmSync(configDir, { recursive: true, force: true });
255
+ fs.cpSync(src, configDir, { recursive: true });
256
+ fs.rmSync(path.join(configDir, '.none'), { force: true });
257
+ }
258
+ if (options.credentials_file !== undefined) {
259
+ const src = assertInsideDataDir(
260
+ options.credentials_file,
261
+ options.data_dir ?? '',
262
+ 'credentials_file'
263
+ );
264
+ const st = fs.statSync(src);
265
+ if (!st.isFile()) {
266
+ throw new InvalidBuildOptionsError("'credentials_file' is not a regular file");
267
+ }
268
+ if ((st.mode & 0o777) !== 0o600) {
269
+ throw new InvalidBuildOptionsError("'credentials_file' must have mode 0600");
270
+ }
271
+ fs.writeFileSync(path.join(credsDir, 'env'), fs.readFileSync(src), { mode: 0o600 });
272
+ fs.chmodSync(path.join(credsDir, 'env'), 0o600);
273
+ fs.rmSync(path.join(credsDir, '.none'), { force: true });
274
+ }
275
+
276
+ return () => {
277
+ resetDir(configDir);
278
+ resetDir(credsDir);
279
+ };
280
+ }
281
+
282
+ /**
283
+ * P2 criterion 7 (D7) + image plan P2: rebuild the runner image to pick up new pinned
284
+ * versions and a new agent list. Credentials only ever reach the build through the
285
+ * staged 0600 file when explicitly asked for (D-A: that image is a local secret);
286
+ * nothing secret is passed on the docker command line.
64
287
  */
65
288
  export async function rebuildRunnerImage(
66
289
  image: string,
67
- versions: RunnerVersions = {},
68
- exec: DockerExec = execFileAsync as unknown as DockerExec
290
+ options: RunnerBuildOptions = {},
291
+ exec: DockerExec = spawnDocker,
292
+ onProgress?: (progress: BuildProgress) => void
69
293
  ): Promise<void> {
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;
70
296
  const args: string[] = ['build', '--pull'];
71
297
  if ((versions.hc === undefined) !== (versions.hc_sha256 === undefined)) {
72
298
  throw new InvalidVersionError("'hc' and 'hc_sha256' go together: a new hc version needs its checksum");
@@ -98,18 +324,50 @@ export async function rebuildRunnerImage(
98
324
  }
99
325
  args.push('--build-arg', `${argName}=${value}`);
100
326
  }
101
- args.push('-t', image, runnerBuildContext);
102
327
 
328
+ // Image plan P2: the agent list (default pi = parity with the current image) and the
329
+ // optional staged config/credentials.
330
+ const agentList = agents === undefined ? ['pi'] : validateRunnerAgents(agents);
331
+ args.push('--build-arg', `AGENTS=${agentList.join(',')}`);
332
+ if (skip_az !== undefined) args.push('--build-arg', `SKIP_AZ=${skip_az ? '1' : '0'}`);
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(',')}`);
345
+ if ((config_dir !== undefined || credentials_file !== undefined) && !data_dir) {
346
+ throw new InvalidBuildOptionsError("'data_dir' is required to stage config or credentials");
347
+ }
348
+
349
+ const cleanup = stageBuildContext(runnerBuildContext, { config_dir, credentials_file, data_dir });
103
350
  try {
104
- await exec('docker', args, {
351
+ let progress: BuildProgress = { step: 0, total: 0, detail: 'Preparando el build…' };
352
+ onProgress?.(progress);
353
+ await exec('docker', [...args, '-t', image, runnerBuildContext], {
105
354
  env: { ...process.env, DOCKER_BUILDKIT: '0' },
106
355
  timeout: BUILD_TIMEOUT_MS,
107
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
+ },
108
364
  });
109
365
  } catch (err) {
110
366
  const detail = err instanceof Error ? err.message : String(err);
111
367
  // Full docker output stays in the orchestrator's log only, never in the HTTP body.
112
368
  console.error(`[bond-app] docker build failed for ${image}: ${detail}`);
113
369
  throw new RunnerBuildError(`Runner image build failed for ${image}`);
370
+ } finally {
371
+ cleanup();
114
372
  }
115
373
  }