@jmanuelcorral/bond-app 0.1.5 → 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 (70) hide show
  1. package/README.md +211 -17
  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 +354 -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 +686 -444
  17. package/app/mods/bond-board/model.js +99 -25
  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 +1159 -278
  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 +60 -1
  51. package/src/cli.ts +53 -3
  52. package/src/core/agy-login.ts +682 -0
  53. package/src/core/delivery.ts +3 -1
  54. package/src/core/orchestrator.ts +736 -78
  55. package/src/core/repo-host.ts +60 -0
  56. package/src/core/setup.ts +62 -1
  57. package/src/core/watchdog.ts +6 -6
  58. package/src/db/database.ts +41 -1
  59. package/src/db/settings-repo.ts +332 -7
  60. package/src/db/ticket-repo.ts +46 -20
  61. package/src/index.ts +4 -4
  62. package/src/runner/azure-devops-client.ts +163 -0
  63. package/src/runner/docker-client.ts +59 -9
  64. package/src/runner/github-client.ts +30 -3
  65. package/src/runner/hc-client.ts +33 -5
  66. package/src/runner/image-builder.ts +123 -5
  67. package/src/runner/jira-client.ts +368 -0
  68. package/src/runner/tool-catalog.ts +84 -0
  69. package/src/server/app.ts +377 -5
  70. package/src/types.ts +129 -2
@@ -1,9 +1,11 @@
1
1
  import type { DatabaseSync } from 'node:sqlite';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { REPO_NAME_RE } from '../core/hub.ts';
4
+ import { azureRepoUrl, parseAzureRepoUrl } from '../core/repo-host.ts';
4
5
  import {
5
6
  validateGitHubUrl,
6
7
  isValidAgent,
8
+ SUPPORTED_AGENTS,
7
9
  validateBranchName,
8
10
  validateVerifyCommands,
9
11
  type Ticket,
@@ -42,10 +44,20 @@ export function repoKey(url: string): string {
42
44
  export function issueTicketId(issueUrl?: string | null): string | null {
43
45
  const url = String(issueUrl ?? '').trim();
44
46
  const m = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/issues\/([1-9][0-9]*)(?:[#?].*)?$/.exec(url);
45
- if (!m) return null;
46
- const slug = (s: string) => s.replace(/[^A-Za-z0-9_.-]/g, '-').replace(/^[-.]+|[-.]+$/g, '');
47
- const id = `gh-${slug(m[1])}-${slug(m[2])}-${m[3]}`.replace(/\.{2,}/g, '-');
48
- return id.length <= 80 ? id : null;
47
+ if (m) {
48
+ const slug = (s: string) => s.replace(/[^A-Za-z0-9_.-]/g, '-').replace(/^[-.]+|[-.]+$/g, '');
49
+ const id = `gh-${slug(m[1])}-${slug(m[2])}-${m[3]}`.replace(/\.{2,}/g, '-');
50
+ return id.length <= 80 ? id : null;
51
+ }
52
+ const j = /^https:\/\/([a-zA-Z0-9_-]+)\.atlassian\.net\/browse\/([a-zA-Z0-9_-]+)(?:[#?].*)?$/.exec(url);
53
+ if (j) {
54
+ const slug = (s: string) => s.replace(/[^A-Za-z0-9_.-]/g, '-').replace(/^[-.]+|[-.]+$/g, '');
55
+ // The tenant is part of the id: two sites can share project keys (CORE-1 on two
56
+ // sites are different issues).
57
+ const id = `jira-${slug(j[1].toLowerCase())}-${slug(j[2].toLowerCase())}`.replace(/\.{2,}/g, '-');
58
+ return id.length <= 80 ? id : null;
59
+ }
60
+ return null;
49
61
  }
50
62
 
51
63
  /**
@@ -107,9 +119,13 @@ export function normalizeLayout(rawInput: LayoutInput): TicketLayout {
107
119
  return { repo_url: repos[0].url, base_branch: repos[0].base_branch, hub_url: null, hub_base: null, repos };
108
120
  }
109
121
 
110
- const repoUrl = String(input.repo_url).trim();
111
- if (!validateGitHubUrl(repoUrl)) {
112
- throw new Error(`Invalid repo_url '${repoUrl}'. Only https://github.com/<owner>/<repo>[.git] URLs are allowed.`);
122
+ // Plan bond-app-azure-jira P1: a single-repo ticket may live on GitHub or Azure Repos
123
+ // (kept in its canonical dev.azure.com form). Hubs and repo lists stay GitHub only.
124
+ const rawRepoUrl = String(input.repo_url).trim();
125
+ const azure = parseAzureRepoUrl(rawRepoUrl);
126
+ const repoUrl = azure ? azureRepoUrl(azure) : rawRepoUrl;
127
+ if (!validateGitHubUrl(repoUrl) && !azure) {
128
+ throw new Error(`Invalid repo_url '${repoUrl}'. Only https://github.com/<owner>/<repo>[.git] or https://dev.azure.com/<org>/<project>/_git/<repo> URLs are allowed.`);
113
129
  }
114
130
  const base = input.base_branch || 'main';
115
131
  if (!validateBranchName(base)) throw new Error(`Invalid base_branch '${base}'`);
@@ -192,14 +208,15 @@ export class TicketRepository {
192
208
  throw new Error("Field 'budget_usd' must be a positive finite number");
193
209
  }
194
210
 
195
- const timeoutMinutes = input.timeout_minutes !== undefined ? Number(input.timeout_minutes) : 20;
196
- if (isNaN(timeoutMinutes) || timeoutMinutes <= 0 || !isFinite(timeoutMinutes)) {
197
- throw new Error("Field 'timeout_minutes' must be a positive finite number");
211
+ // 0 (the default) means no timeout: the watchdog never terminates the run on time.
212
+ const timeoutMinutes = input.timeout_minutes !== undefined ? Number(input.timeout_minutes) : 0;
213
+ if (Number.isNaN(timeoutMinutes) || timeoutMinutes < 0 || !Number.isFinite(timeoutMinutes)) {
214
+ throw new Error("Field 'timeout_minutes' must be a finite number >= 0 (0 = no timeout)");
198
215
  }
199
216
 
200
217
  const agent = input.agent || 'pi';
201
218
  if (!isValidAgent(agent)) {
202
- throw new Error(`Invalid agent '${agent}'. Supported agents are: pi, claude, codex, opencode, copilot, crush, agy`);
219
+ throw new Error(`Invalid agent '${agent}'. Supported agents are: ${SUPPORTED_AGENTS.join(', ')}`);
203
220
  }
204
221
 
205
222
  const repoAgents = normalizeRepoAgents(input.repo_agents);
@@ -216,6 +233,9 @@ export class TicketRepository {
216
233
  throw new Error("Field 'bondify' must be a boolean");
217
234
  }
218
235
  const bondify = input.bondify !== false;
236
+ if (input.docker !== undefined && typeof input.docker !== 'boolean') {
237
+ throw new Error("Field 'docker' must be a boolean");
238
+ }
219
239
  if (layoutBases(layout).includes(targetBranch)) {
220
240
  throw new Error('target_branch must differ from base_branch: a run only pushes its own branch (P4)');
221
241
  }
@@ -226,8 +246,8 @@ export class TicketRepository {
226
246
  INSERT INTO tickets (
227
247
  id, title, description, repo_url, base_branch, target_branch,
228
248
  budget_usd, timeout_minutes, agent, model, prompt, verify_commands,
229
- hub_url, hub_base, repos, repo_agents, issue_url, story, team_engine, bondify, status, created_at, updated_at
230
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
249
+ hub_url, hub_base, repos, repo_agents, issue_url, story, team_engine, bondify, docker, status, created_at, updated_at
250
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
231
251
  `);
232
252
 
233
253
  const teamEngine = input.team_engine === 'herdr' ? 'herdr' : 'hc';
@@ -250,9 +270,10 @@ export class TicketRepository {
250
270
  layout.repos ? JSON.stringify(layout.repos) : null,
251
271
  Object.keys(repoAgents).length ? JSON.stringify(repoAgents) : null,
252
272
  input.issue_url ? String(input.issue_url).trim() : null,
253
- input.story || null,
273
+ input.story ?? null,
254
274
  teamEngine,
255
275
  bondify ? 1 : 0,
276
+ input.docker === true ? 1 : 0,
256
277
  status,
257
278
  now,
258
279
  now
@@ -326,7 +347,7 @@ export class TicketRepository {
326
347
  throw new Error("'repo_agents' is for an existing hub; in a list, give each repo its 'agent'");
327
348
  }
328
349
  if (updates.agent !== undefined && !isValidAgent(updates.agent)) {
329
- throw new Error(`Invalid agent '${updates.agent}'. Supported agents are: pi, claude, codex, opencode, copilot, crush, agy`);
350
+ throw new Error(`Invalid agent '${updates.agent}'. Supported agents are: ${SUPPORTED_AGENTS.join(', ')}`);
330
351
  }
331
352
  if (updates.target_branch !== undefined && !validateBranchName(updates.target_branch)) {
332
353
  throw new Error(`Invalid target_branch '${updates.target_branch}'`);
@@ -345,13 +366,16 @@ export class TicketRepository {
345
366
  }
346
367
  if (updates.timeout_minutes !== undefined) {
347
368
  const t = Number(updates.timeout_minutes);
348
- if (isNaN(t) || t <= 0 || !isFinite(t)) {
349
- throw new Error("Field 'timeout_minutes' must be a positive finite number");
369
+ if (Number.isNaN(t) || t < 0 || !Number.isFinite(t)) {
370
+ throw new Error("Field 'timeout_minutes' must be a finite number >= 0 (0 = no timeout)");
350
371
  }
351
372
  }
352
373
  if (updates.bondify !== undefined && typeof updates.bondify !== 'boolean') {
353
374
  throw new Error("Field 'bondify' must be a boolean");
354
375
  }
376
+ if (updates.docker !== undefined && typeof updates.docker !== 'boolean') {
377
+ throw new Error("Field 'docker' must be a boolean");
378
+ }
355
379
 
356
380
  // Preserve status: status is managed via run lifecycle, not arbitrary ticket patch
357
381
  const merged = { ...existing, ...updates, status: existing.status, updated_at: new Date().toISOString() };
@@ -361,7 +385,7 @@ export class TicketRepository {
361
385
  title = ?, description = ?, repo_url = ?, base_branch = ?, target_branch = ?,
362
386
  budget_usd = ?, timeout_minutes = ?, agent = ?, model = ?, prompt = ?,
363
387
  verify_commands = ?, hub_url = ?, hub_base = ?, repos = ?, repo_agents = ?,
364
- issue_url = ?, story = ?, team_engine = ?, bondify = ?, status = ?, updated_at = ?
388
+ issue_url = ?, story = ?, team_engine = ?, bondify = ?, docker = ?, status = ?, updated_at = ?
365
389
  WHERE id = ?
366
390
  `);
367
391
 
@@ -382,9 +406,10 @@ export class TicketRepository {
382
406
  layout.repos ? JSON.stringify(layout.repos) : null,
383
407
  Object.keys(repoAgents).length ? JSON.stringify(repoAgents) : null,
384
408
  merged.issue_url ? String(merged.issue_url).trim() : null,
385
- merged.story || null,
409
+ merged.story ?? null,
386
410
  merged.team_engine === 'herdr' ? 'herdr' : 'hc',
387
411
  merged.bondify ? 1 : 0,
412
+ merged.docker ? 1 : 0,
388
413
  merged.status,
389
414
  merged.updated_at,
390
415
  id
@@ -411,7 +436,7 @@ export class TicketRepository {
411
436
  title: String(row.title),
412
437
  description: row.description ? String(row.description) : undefined,
413
438
  issue_url: row.issue_url ? String(row.issue_url) : null,
414
- story: row.story ? String(row.story) : null,
439
+ story: row.story === null || row.story === undefined ? null : String(row.story),
415
440
  repo_url: repoUrl,
416
441
  base_branch: baseBranch,
417
442
  hub_url: hubUrl,
@@ -428,6 +453,7 @@ export class TicketRepository {
428
453
  verify_commands: parseVerifyCommands(row.verify_commands),
429
454
  team_engine: (row.team_engine === 'hc' ? 'hc' : 'herdr') as 'hc' | 'herdr',
430
455
  bondify: row.bondify !== null && row.bondify !== undefined ? Number(row.bondify) !== 0 : true,
456
+ docker: Number(row.docker ?? 0) !== 0,
431
457
  status: row.status as RunState,
432
458
  created_at: String(row.created_at),
433
459
  updated_at: String(row.updated_at),
package/src/index.ts CHANGED
@@ -7,16 +7,16 @@ import { SettingsRepository } from './db/settings-repo.ts';
7
7
  import { EventBus } from './sse/event-bus.ts';
8
8
  import { DockerClient } from './runner/docker-client.ts';
9
9
  import { Orchestrator } from './core/orchestrator.ts';
10
- import { createServer } from './server/app.ts';
10
+ import { createServer, type ServerHooks } from './server/app.ts';
11
11
 
12
- export async function bootstrap(configOverrides = {}) {
12
+ export async function bootstrap(configOverrides = {}, hooks: ServerHooks = {}) {
13
13
  const config = loadConfig(configOverrides);
14
14
  const db = initDatabase(config.dbPath);
15
15
 
16
16
  const ticketRepo = new TicketRepository(db);
17
17
  const runRepo = new RunRepository(db);
18
18
  const eventRepo = new EventRepository(db);
19
- const settingsRepo = new SettingsRepository(db);
19
+ const settingsRepo = new SettingsRepository(db, config.dataDir);
20
20
  const eventBus = new EventBus(eventRepo);
21
21
  const dockerClient = new DockerClient();
22
22
 
@@ -31,7 +31,7 @@ export async function bootstrap(configOverrides = {}) {
31
31
 
32
32
  await orchestrator.start();
33
33
 
34
- const server = createServer(orchestrator);
34
+ const server = createServer(orchestrator, hooks);
35
35
 
36
36
  return new Promise<{ server: typeof server; orchestrator: Orchestrator; port: number }>((resolve) => {
37
37
  server.listen(config.port, config.host, () => {
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Plan bond-app-azure-jira P1: the Azure DevOps REST calls bond-app makes from the host
3
+ * with the user's PAT (Basic auth, empty user): check the credential, open the pull
4
+ * request of a delivered branch, and check or delete that branch when the ticket goes.
5
+ * Never in argv, env or logs; the push itself happens in the container (delivery.ts).
6
+ */
7
+ import type { FetchLike, PullRequest } from './github-client.ts';
8
+ import { parseAzureRepoUrl, type AzureRepoRef } from '../core/repo-host.ts';
9
+
10
+ const API = 'api-version=7.1';
11
+
12
+ export class AzureDevOpsApiError extends Error {
13
+ status: number;
14
+ constructor(message: string, status: number) {
15
+ super(message);
16
+ this.name = 'AzureDevOpsApiError';
17
+ this.status = status;
18
+ }
19
+ }
20
+
21
+ /** https://dev.azure.com/<org> (trailing slash and the older visualstudio.com form accepted). */
22
+ export function normalizeAzureOrgUrl(raw: string): string | null {
23
+ const u = String(raw ?? '').trim().replace(/\/+$/, '');
24
+ const dev = /^https:\/\/dev\.azure\.com\/([A-Za-z0-9][A-Za-z0-9_.-]{0,99})$/.exec(u);
25
+ if (dev) return `https://dev.azure.com/${dev[1]}`;
26
+ const vs = /^https:\/\/([A-Za-z0-9][A-Za-z0-9_.-]{0,99})\.visualstudio\.com$/.exec(u);
27
+ if (vs) return `https://dev.azure.com/${vs[1]}`;
28
+ return null;
29
+ }
30
+
31
+ export class AzureDevOpsClient {
32
+ private fetchImpl: FetchLike;
33
+
34
+ constructor(fetchImpl: FetchLike = fetch as unknown as FetchLike) {
35
+ this.fetchImpl = fetchImpl;
36
+ }
37
+
38
+ private async call(pat: string, method: string, url: string, body?: unknown): Promise<{ status: number; data: unknown }> {
39
+ const res = await this.fetchImpl(url, {
40
+ method,
41
+ headers: {
42
+ Accept: 'application/json',
43
+ Authorization: `Basic ${Buffer.from(`:${pat}`).toString('base64')}`,
44
+ 'User-Agent': 'bond-app',
45
+ ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
46
+ },
47
+ body: body !== undefined ? JSON.stringify(body) : undefined,
48
+ });
49
+ const text = await res.text();
50
+ let data: unknown = null;
51
+ try {
52
+ data = text ? JSON.parse(text) : null;
53
+ } catch {
54
+ data = null;
55
+ }
56
+ return { status: res.status, data };
57
+ }
58
+
59
+ private repoApi(ref: AzureRepoRef, tail: string): string {
60
+ return `${ref.orgUrl}/${ref.project}/_apis/git/repositories/${ref.repo}${tail}`;
61
+ }
62
+
63
+ private ref(repoUrl: string): AzureRepoRef {
64
+ const ref = parseAzureRepoUrl(repoUrl);
65
+ if (!ref) throw new AzureDevOpsApiError(`Not an Azure Repos URL: '${repoUrl}'`, 400);
66
+ return ref;
67
+ }
68
+
69
+ /**
70
+ * Who the PAT belongs to in that organization (connectionData). Throws a clear error on
71
+ * a wrong PAT or organization: the caller shows it in Ajustes.
72
+ */
73
+ async whoAmI(pat: string, orgUrl: string): Promise<{ name: string; email?: string }> {
74
+ const res = await this.call(pat, 'GET', `${orgUrl}/_apis/connectionData?${API}-preview`);
75
+ const user = (res.data as { authenticatedUser?: { providerDisplayName?: string; properties?: { Account?: { $value?: string } } } } | null)?.authenticatedUser;
76
+ if (res.status !== 200 || !user || !user.providerDisplayName || user.providerDisplayName === 'Anonymous') {
77
+ throw new AzureDevOpsApiError(
78
+ res.status === 401 || res.status === 203 || !user || user?.providerDisplayName === 'Anonymous'
79
+ ? 'Azure DevOps no acepta ese PAT en esa organización'
80
+ : `Azure DevOps respondió ${res.status}`,
81
+ res.status === 200 ? 401 : res.status
82
+ );
83
+ }
84
+ const email = user.properties?.Account?.$value;
85
+ return { name: user.providerDisplayName, ...(email ? { email } : {}) };
86
+ }
87
+
88
+ /**
89
+ * Open the PR `head` -> `base`, or return the active one that already exists for that
90
+ * branch (a delivery retried after a crash must not fail on it).
91
+ */
92
+ async openPullRequest(pat: string, repoUrl: string, pr: { head: string; base: string; title: string; body: string }): Promise<PullRequest> {
93
+ const ref = this.ref(repoUrl);
94
+ const created = await this.call(pat, 'POST', this.repoApi(ref, `/pullrequests?${API}`), {
95
+ sourceRefName: `refs/heads/${pr.head}`,
96
+ targetRefName: `refs/heads/${pr.base}`,
97
+ title: pr.title,
98
+ // Azure caps the description at 4000 characters.
99
+ description: pr.body.length > 4000 ? `${pr.body.slice(0, 3990)}\n…` : pr.body,
100
+ });
101
+ const web = (id: number) => `${ref.orgUrl}/${ref.project}/_git/${ref.repo}/pullrequest/${id}`;
102
+ if (created.status === 201 || created.status === 200) {
103
+ const id = (created.data as { pullRequestId?: number }).pullRequestId!;
104
+ return { number: id, url: web(id), created: true };
105
+ }
106
+ if (created.status === 409) {
107
+ const q = `?searchCriteria.sourceRefName=${encodeURIComponent(`refs/heads/${pr.head}`)}&searchCriteria.targetRefName=${encodeURIComponent(`refs/heads/${pr.base}`)}&searchCriteria.status=active&${API}`;
108
+ const found = await this.call(pat, 'GET', this.repoApi(ref, `/pullrequests${q}`));
109
+ const first = (found.data as { value?: Array<{ pullRequestId: number }> } | null)?.value?.[0];
110
+ if (first) return { number: first.pullRequestId, url: web(first.pullRequestId), created: false };
111
+ }
112
+ const message = (created.data as { message?: string } | null)?.message || `HTTP ${created.status}`;
113
+ throw new AzureDevOpsApiError(`Azure DevOps refused the pull request: ${message}`, created.status);
114
+ }
115
+
116
+ /**
117
+ * The organization's repositories (all projects the PAT sees), for the new-ticket repo
118
+ * search: canonical clone URL, «org / project / repo» and the default branch.
119
+ */
120
+ async listRepositories(pat: string, orgUrl: string): Promise<Array<{ url: string; project: string; name: string; default_branch?: string }>> {
121
+ const res = await this.call(pat, 'GET', `${orgUrl}/_apis/git/repositories?${API}`);
122
+ if (res.status !== 200) throw new AzureDevOpsApiError(`Azure DevOps repositories: HTTP ${res.status}`, res.status);
123
+ const rows = (res.data as { value?: Array<{ name?: string; isDisabled?: boolean; defaultBranch?: string; project?: { name?: string } }> } | null)?.value ?? [];
124
+ const out: Array<{ url: string; project: string; name: string; default_branch?: string }> = [];
125
+ for (const r of rows) {
126
+ if (!r?.name || !r.project?.name || r.isDisabled) continue;
127
+ const url = `${orgUrl}/${encodeURIComponent(r.project.name)}/_git/${encodeURIComponent(r.name)}`;
128
+ const branch = typeof r.defaultBranch === 'string' ? r.defaultBranch.replace(/^refs\/heads\//, '') : undefined;
129
+ out.push({ url, project: r.project.name, name: r.name, ...(branch ? { default_branch: branch } : {}) });
130
+ }
131
+ return out.sort((a, b) => `${a.project}/${a.name}`.localeCompare(`${b.project}/${b.name}`));
132
+ }
133
+
134
+ private async branchSha(pat: string, ref: AzureRepoRef, branch: string): Promise<string | null> {
135
+ const res = await this.call(pat, 'GET', this.repoApi(ref, `/refs?filter=${encodeURIComponent(`heads/${branch}`)}&${API}`));
136
+ if (res.status !== 200) throw new AzureDevOpsApiError(`Azure DevOps refs: HTTP ${res.status}`, res.status);
137
+ const hit = (res.data as { value?: Array<{ name: string; objectId: string }> } | null)?.value?.find((r) => r.name === `refs/heads/${branch}`);
138
+ return hit ? hit.objectId : null;
139
+ }
140
+
141
+ async remoteBranchExists(pat: string, repoUrl: string, branch: string): Promise<boolean> {
142
+ return (await this.branchSha(pat, this.ref(repoUrl), branch)) !== null;
143
+ }
144
+
145
+ /** Whether every commit of `branch` is already in `base` (aheadCount 0). */
146
+ async isBranchMerged(pat: string, repoUrl: string, branch: string, base: string): Promise<boolean> {
147
+ const ref = this.ref(repoUrl);
148
+ const q = `?baseVersion=${encodeURIComponent(base)}&baseVersionType=branch&targetVersion=${encodeURIComponent(branch)}&targetVersionType=branch&$top=1&${API}`;
149
+ const res = await this.call(pat, 'GET', this.repoApi(ref, `/diffs/commits${q}`));
150
+ if (res.status !== 200) return false;
151
+ return (res.data as { aheadCount?: number } | null)?.aheadCount === 0;
152
+ }
153
+
154
+ async deleteRemoteBranch(pat: string, repoUrl: string, branch: string): Promise<boolean> {
155
+ const ref = this.ref(repoUrl);
156
+ const sha = await this.branchSha(pat, ref, branch);
157
+ if (!sha) return false;
158
+ const res = await this.call(pat, 'POST', this.repoApi(ref, `/refs?${API}`), [
159
+ { name: `refs/heads/${branch}`, oldObjectId: sha, newObjectId: '0000000000000000000000000000000000000000' },
160
+ ]);
161
+ return res.status === 200 && Boolean((res.data as { value?: Array<{ success?: boolean }> } | null)?.value?.[0]?.success);
162
+ }
163
+ }
@@ -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 {
@@ -133,9 +141,8 @@ export class DockerClient {
133
141
  });
134
142
  }
135
143
 
136
- async createAndStartContainer(options: ContainerStartOptions): Promise<ContainerInfo> {
144
+ buildRunArgs(options: ContainerStartOptions, network: string): string[] {
137
145
  const containerName = `bond-app-${options.runId}`;
138
- const network = options.network || (await this.createNetwork(options.runId, options.instanceId));
139
146
 
140
147
  const args: string[] = [
141
148
  'run',
@@ -157,10 +164,16 @@ export class DockerClient {
157
164
  // P3 (D19): no published ports. The host reaches the container only with docker exec
158
165
  // (hc machine --via). --init reaps the processes docker exec sessions leave behind.
159
166
  // 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');
167
+ // P3 (D-BB): BOND_APP=1 selects hc transport in bond; passed defensively for older runner images.
168
+ args.push('--network', network, '--init', '-e', 'BOND_TEAM_NO_TABLE=1', '-e', 'BOND_APP=1');
169
+
170
+ if (options.docker) {
171
+ // dockerd needs the privileges the hardened profile drops; nothing else changes.
172
+ args.push('--privileged', '-v', '/var/lib/docker', '-e', 'BOND_DIND=1');
173
+ }
161
174
 
162
175
  // Security options: criterion 12
163
- if (options.securityProfile !== false) {
176
+ if (options.securityProfile !== false && !options.docker) {
164
177
  args.push(
165
178
  '--cap-drop=ALL',
166
179
  '--cap-add=CHOWN',
@@ -179,7 +192,8 @@ export class DockerClient {
179
192
  // Resource limits (M2)
180
193
  const cpus = options.cpus ?? 2;
181
194
  const memory = options.memory ?? '2g';
182
- const pidsLimit = options.pidsLimit ?? 200;
195
+ // dockerd and the containers it starts share the run's pid budget.
196
+ const pidsLimit = options.docker ? Math.max(options.pidsLimit ?? 200, 4096) : (options.pidsLimit ?? 200);
183
197
 
184
198
  args.push(`--cpus=${cpus}`, `--memory=${memory}`, `--pids-limit=${pidsLimit}`);
185
199
 
@@ -192,6 +206,15 @@ export class DockerClient {
192
206
  // Image
193
207
  args.push(options.image);
194
208
 
209
+ return args;
210
+ }
211
+
212
+ async createAndStartContainer(options: ContainerStartOptions): Promise<ContainerInfo> {
213
+ const containerName = `bond-app-${options.runId}`;
214
+ const network = options.network || (await this.createNetwork(options.runId, options.instanceId));
215
+
216
+ const args = this.buildRunArgs(options, network);
217
+
195
218
  const { stdout } = await execFileAsync('docker', args);
196
219
  const containerId = stdout.trim();
197
220
 
@@ -400,12 +423,36 @@ export class DockerClient {
400
423
  * An older image without the manifest reports present with no agents. Never logs the
401
424
  * manifest content; the manifest carries no secrets by design.
402
425
  */
426
+ /** The last manifest read, by image id: reading it costs a `docker run`, and Ajustes
427
+ * asks for the setup state every few seconds (plan bond-app-ajustes-imagen P2). */
428
+ private manifestCache: { id: string; info: RunnerImageInfo } | null = null;
429
+
403
430
  async inspectRunnerImage(image: string): Promise<RunnerImageInfo> {
431
+ let id: string;
432
+ let recipe: string | undefined;
404
433
  try {
405
- await execFileAsync('docker', ['image', 'inspect', image, '--format', '{{.Id}}'], { timeout: 20_000 });
434
+ const { stdout } = await execFileAsync(
435
+ 'docker',
436
+ // The whole Config as JSON: an image without labels has no Labels key at all, and a
437
+ // template that names it (`index`, `.Config.Labels`) fails instead of printing nothing.
438
+ ['image', 'inspect', image, '--format', '{{.Id}} {{json .Config}}'],
439
+ { timeout: 20_000 }
440
+ );
441
+ const out = String(stdout).trim();
442
+ const space = out.indexOf(' ');
443
+ id = space === -1 ? out : out.slice(0, space);
444
+ try {
445
+ const config = JSON.parse(space === -1 ? 'null' : out.slice(space + 1)) as { Labels?: Record<string, string> | null } | null;
446
+ recipe = config?.Labels?.[LABEL_RECIPE] || undefined;
447
+ } catch {
448
+ recipe = undefined;
449
+ }
406
450
  } catch {
407
451
  return { present: false };
408
452
  }
453
+ const withRecipe = (info: RunnerImageInfo): RunnerImageInfo =>
454
+ recipe ? { ...info, recipe } : { ...info };
455
+ if (this.manifestCache && this.manifestCache.id === id) return withRecipe(this.manifestCache.info);
409
456
  try {
410
457
  const { stdout } = await execFileAsync(
411
458
  'docker',
@@ -413,9 +460,12 @@ export class DockerClient {
413
460
  { timeout: 30_000, maxBuffer: 256 * 1024 }
414
461
  );
415
462
  const agents = parseRunnerManifest(stdout);
416
- return agents.length > 0 ? { present: true, agents } : { present: true };
463
+ const { tools, apt_extra } = parseRunnerManifestTools(stdout);
464
+ const info: RunnerImageInfo = { present: true, ...(agents.length > 0 ? { agents } : {}), tools, apt_extra };
465
+ this.manifestCache = { id, info };
466
+ return withRecipe(info);
417
467
  } catch {
418
- return { present: true };
468
+ return withRecipe({ present: true });
419
469
  }
420
470
  }
421
471
  }
@@ -133,6 +133,32 @@ 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
+
136
162
  /** P7: check if a remote branch exists on GitHub. */
137
163
  async remoteBranchExists(token: string, owner: string, repo: string, branch: string): Promise<boolean> {
138
164
  const res = await this.call(token, 'GET', `/repos/${owner}/${repo}/branches/${encodeURIComponent(branch)}`);
@@ -183,7 +209,7 @@ export class GitHubClient {
183
209
  * los privados accesibles con el token). La búsqueda es el buscador de GitHub sobre el
184
210
  * nombre/descripción; orden tal cual los devuelve GitHub (best match).
185
211
  */
186
- async searchRepos(token: string, term: string): Promise<Array<{ full_name: string; url: string }>> {
212
+ async searchRepos(token: string, term: string): Promise<Array<{ full_name: string; url: string; default_branch?: string }>> {
187
213
  const res = await this.call(token, 'GET', `/search/repositories?q=${encodeURIComponent(term)}&per_page=20`);
188
214
  if (res.status !== 200) {
189
215
  const msg = (res.data as { message?: string } | null)?.message || `HTTP ${res.status}`;
@@ -192,11 +218,12 @@ export class GitHubClient {
192
218
  const items = Array.isArray((res.data as { items?: unknown })?.items)
193
219
  ? ((res.data as { items: Array<Record<string, unknown>> }).items)
194
220
  : [];
195
- const repos: Array<{ full_name: string; url: string }> = [];
221
+ const repos: Array<{ full_name: string; url: string; default_branch?: string }> = [];
196
222
  for (const row of items) {
197
223
  const full = String(row?.full_name ?? '');
198
224
  if (!full || !String(row?.html_url ?? '').startsWith('https://github.com/')) continue;
199
- repos.push({ full_name: full, url: String(row.html_url) });
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 } : {}) });
200
227
  }
201
228
  return repos;
202
229
  }
@@ -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.