@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
package/src/server/app.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  ValidationError,
7
7
  RebuildInProgressError,
8
8
  GitHubCredentialMissingError,
9
+ SourceError,
9
10
  UnmergedBranchError,
10
11
  NotFoundError,
11
12
  ConflictError,
@@ -14,11 +15,38 @@ import {
14
15
  } from '../core/orchestrator.ts';
15
16
  import { InvalidBuildOptionsError, InvalidVersionError, type RunnerVersions } from '../runner/image-builder.ts';
16
17
  import { GitHubApiError } from '../runner/github-client.ts';
18
+ import { JiraApiError } from '../runner/jira-client.ts';
19
+ import { validateAptExtra, validateToolGroups } from '../runner/tool-catalog.ts';
20
+ import { normalizeAzureOrgUrl } from '../runner/azure-devops-client.ts';
21
+ import { githubParts } from '../core/hub.ts';
22
+ import { azureRepoUrl, parseAzureRepoUrl, validateRepoUrl } from '../core/repo-host.ts';
23
+ import { keepPiKeys } from '../db/settings-repo.ts';
17
24
  import { listProviderModels, normalizeProviderBase, ProviderModelsError } from '../core/setup.ts';
25
+ import { runDoctor, type DoctorDeps, type DoctorOptions, type DoctorReport } from '../core/doctor.ts';
18
26
  import { InvalidStateTransitionError } from '../core/state-machine.ts';
19
- import { isValidAgent, isSetupAgent, SETUP_AGENTS, validateGitHubLogin, validateGitHubToken, type CreateTicketInput, type RunState } from '../types.ts';
27
+ import {
28
+ isValidAgent,
29
+ isSetupAgent,
30
+ SETUP_AGENTS,
31
+ validateGitHubLogin,
32
+ validateGitHubToken,
33
+ validateJiraSite,
34
+ validateJiraEmail,
35
+ validateJiraToken,
36
+ type CreateTicketInput,
37
+ type RunState,
38
+ } from '../types.ts';
39
+
40
+ /** What the server can ask of the process that runs it. */
41
+ export interface ServerHooks {
42
+ /** Stop like Ctrl+C and start again with the same argv and environment (Ajustes «Reiniciar»). */
43
+ onRestart?: () => void;
44
+ /** Injectable doctor runner / deps for tests. */
45
+ runDoctor?: (opts: DoctorOptions) => Promise<DoctorReport>;
46
+ doctorDeps?: DoctorDeps;
47
+ }
20
48
 
21
- export function createServer(orchestrator: Orchestrator): Server {
49
+ export function createServer(orchestrator: Orchestrator, hooks: ServerHooks = {}): Server {
22
50
  return http.createServer(async (req: IncomingMessage, res: ServerResponse) => {
23
51
  const sendJson = (statusCode: number, data: unknown) => {
24
52
  res.writeHead(statusCode, { 'Content-Type': 'application/json' });
@@ -140,28 +168,62 @@ export function createServer(orchestrator: Orchestrator): Server {
140
168
  if (method === 'POST') {
141
169
  const body = (await readJson()) as unknown as CreateTicketInput;
142
170
  // P5: a ticket names one repo (repo_url), a list (repos) or an existing hub (hub_url).
143
- if (!body.title || (!body.repo_url && !body.repos && !body.hub_url)) {
171
+ if (!body.source_pr_url && (!body.title || (!body.repo_url && !body.repos && !body.hub_url))) {
144
172
  sendJson(400, { error: "Field 'title' and one of 'repo_url', 'repos' or 'hub_url' are required" });
145
173
  return;
146
174
  }
147
175
  try {
148
- const ticket = orchestrator.ticketRepo.create(body);
176
+ // Plan bond-app-ticket-desde-pr P1: from a PR or branch, bond-app resolves it and
177
+ // takes repo, branches, id (and title/story if missing) from it.
178
+ const ticket = body.source_pr_url
179
+ ? await orchestrator.createTicketFromSource(body)
180
+ : orchestrator.ticketRepo.create(body);
149
181
  sendJson(201, ticket);
150
182
  } catch (err: unknown) {
151
- sendJson(400, { error: (err as Error).message });
183
+ if (err instanceof SourceError) {
184
+ sendJson(err.status, { error: err.code === 'ticket_invalid' ? err.message : err.code, code: err.code, detail: err.message });
185
+ } else {
186
+ sendJson(400, { error: (err as Error).message });
187
+ }
152
188
  }
153
189
  return;
154
190
  }
155
191
  }
156
192
 
157
193
  // Plan bond-app-nuevo-ticket (P1, D2): issues to link a new ticket to — the ones
158
- // assigned to the user (GitHub session from Ajustes), open, `ready` first.
194
+ // assigned to the user (GitHub session from Ajustes, or Jira Cloud), open, `ready` first.
159
195
  if (pathname === '/api/v1/issues/assigned' && method === 'GET') {
160
196
  const provider = parsedUrl.searchParams.get('provider') || 'github';
161
- if (provider !== 'github') {
197
+ if (provider !== 'github' && provider !== 'jira') {
162
198
  sendJson(400, { error: `Unknown issue provider: ${provider}` });
163
199
  return;
164
200
  }
201
+ if (provider === 'jira') {
202
+ const jiraCred = orchestrator.settingsRepo.getJiraCredential();
203
+ if (!jiraCred) {
204
+ sendJson(409, { error: 'jira_not_configured' });
205
+ return;
206
+ }
207
+ try {
208
+ const issues = await orchestrator.jira.listAssigned(jiraCred.site, jiraCred.email, jiraCred.token);
209
+ const summary = orchestrator.settingsRepo.getJiraSummary();
210
+ sendJson(200, {
211
+ ok: true,
212
+ provider: 'jira',
213
+ login: summary.account_name ?? summary.email ?? null,
214
+ site: summary.site,
215
+ issues,
216
+ });
217
+ } catch (err: unknown) {
218
+ const status = err instanceof JiraApiError ? err.status : 0;
219
+ if (status === 401 || status === 403) {
220
+ sendJson(409, { error: 'jira_not_configured', detail: (err as Error).message });
221
+ } else {
222
+ sendJson(502, { error: 'jira_api_error', detail: (err as Error).message });
223
+ }
224
+ }
225
+ return;
226
+ }
165
227
  const ghToken = orchestrator.settingsRepo.getGitHubToken();
166
228
  if (!ghToken) {
167
229
  sendJson(409, { error: 'github_not_configured' });
@@ -182,6 +244,30 @@ export function createServer(orchestrator: Orchestrator): Server {
182
244
  return;
183
245
  }
184
246
 
247
+ // Plan bond-app-azure-jira (P2): búsqueda de issues de Jira por texto y/o proyecto
248
+ if (pathname === '/api/v1/issues/jira/search' && method === 'GET') {
249
+ const q = String(parsedUrl.searchParams.get('q') || '').trim();
250
+ const project = String(parsedUrl.searchParams.get('project') || '').trim();
251
+ const mine = parsedUrl.searchParams.get('mine') === '1';
252
+ const jiraCred = orchestrator.settingsRepo.getJiraCredential();
253
+ if (!jiraCred) {
254
+ sendJson(409, { error: 'jira_not_configured' });
255
+ return;
256
+ }
257
+ try {
258
+ const issues = await orchestrator.jira.search(jiraCred.site, jiraCred.email, jiraCred.token, { q, project, mine });
259
+ sendJson(200, { ok: true, provider: 'jira', issues });
260
+ } catch (err: unknown) {
261
+ const status = err instanceof JiraApiError ? err.status : 0;
262
+ if (status === 401 || status === 403) {
263
+ sendJson(409, { error: 'jira_not_configured', detail: (err as Error).message });
264
+ } else {
265
+ sendJson(502, { error: 'jira_api_error', detail: (err as Error).message });
266
+ }
267
+ }
268
+ return;
269
+ }
270
+
185
271
  // Plan bond-app-nuevo-ticket (P2): primer paso de la búsqueda combinada del diálogo —
186
272
  // repos por nombre (buscador de GitHub), con la misma sesión de gh de Ajustes.
187
273
  if (pathname === '/api/v1/repos/search' && method === 'GET') {
@@ -209,6 +295,112 @@ export function createServer(orchestrator: Orchestrator): Server {
209
295
  return;
210
296
  }
211
297
 
298
+ // Plan bond-app-ticket-desde-pr P1: PRs abiertas para empezar un ticket (GitHub: las que
299
+ // te implican o las de un repo; Azure: las activas del repo o de los proyectos de la org).
300
+ if (pathname === '/api/v1/prs/search' && method === 'GET') {
301
+ const q = String(parsedUrl.searchParams.get('q') || '').slice(0, 200);
302
+ const repo = String(parsedUrl.searchParams.get('repo') || '').slice(0, 500) || undefined;
303
+ // Filtros del alta: host (github | azure) y de quién (assigned = asignadas a mí, author = mías).
304
+ const hostParam = parsedUrl.searchParams.get('host');
305
+ const mineParam = parsedUrl.searchParams.get('mine');
306
+ const host = hostParam === 'github' || hostParam === 'azure' ? hostParam : undefined;
307
+ const mine = mineParam === 'assigned' || mineParam === 'author' ? mineParam : undefined;
308
+ sendJson(200, await orchestrator.searchPullRequests(q, repo, { host, mine }));
309
+ return;
310
+ }
311
+ // P1: qué hay detrás de la URL de una PR o rama (repo, ramas, estado, fork, hub, texto).
312
+ if (pathname === '/api/v1/prs/resolve' && method === 'GET') {
313
+ const url = String(parsedUrl.searchParams.get('url') || '').trim();
314
+ const hubUrl = String(parsedUrl.searchParams.get('hub_url') || '').trim() || undefined;
315
+ try {
316
+ sendJson(200, await orchestrator.resolveSource(url, hubUrl));
317
+ } catch (err: unknown) {
318
+ if (err instanceof SourceError) sendJson(err.status, { error: err.code, detail: err.message });
319
+ else throw err;
320
+ }
321
+ return;
322
+ }
323
+
324
+ // Alta de ticket (Dónde): favoritos, recientes, Azure Repos y GitHub en una lista.
325
+ if (pathname === '/api/v1/repos/suggest' && method === 'GET') {
326
+ const q = String(parsedUrl.searchParams.get('q') || '').slice(0, 100);
327
+ sendJson(200, await orchestrator.suggestRepos(q));
328
+ return;
329
+ }
330
+ if (pathname === '/api/v1/repos/favorites') {
331
+ if (method === 'GET') {
332
+ sendJson(200, { favorites: orchestrator.settingsRepo.getFavoriteRepos() });
333
+ return;
334
+ }
335
+ if (method === 'PUT') {
336
+ const body = await readJson();
337
+ const list: unknown = body.favorites;
338
+ if (!Array.isArray(list) || list.some((u) => typeof u !== 'string' || !validateRepoUrl(u))) {
339
+ sendJson(400, { error: "'favorites' must be a list of GitHub or Azure Repos URLs" });
340
+ return;
341
+ }
342
+ sendJson(200, { favorites: orchestrator.settingsRepo.setFavoriteRepos(list as string[]) });
343
+ return;
344
+ }
345
+ }
346
+
347
+ // Plan bond-app-ajustes-imagen P4: ¿trae el repo devcontainer? (pre-marca «Docker en el run»).
348
+ // Alta en tres bloques: y ¿es un hub (hub.toml)? (el alta pasa sola a modo hub).
349
+ if (pathname === '/api/v1/repos/devcontainer' && method === 'GET') {
350
+ const rawUrl = String(parsedUrl.searchParams.get('url') || '').trim();
351
+ const ref = String(parsedUrl.searchParams.get('ref') || '').trim() || undefined;
352
+ if (ref && !/^[A-Za-z0-9._\/-]{1,200}$/.test(ref)) {
353
+ sendJson(400, { error: 'repo_invalid' });
354
+ return;
355
+ }
356
+ let owner = String(parsedUrl.searchParams.get('owner') || '');
357
+ let repo = String(parsedUrl.searchParams.get('repo') || '');
358
+ if (rawUrl) {
359
+ const az = parseAzureRepoUrl(rawUrl);
360
+ if (az) {
361
+ const repoUrl = azureRepoUrl(az);
362
+ const access = orchestrator.repoAccessFor(repoUrl);
363
+ if (!access.token) {
364
+ sendJson(200, { devcontainer: false, hub: false, checked: false });
365
+ return;
366
+ }
367
+ try {
368
+ const hub = await orchestrator.azure.isHub(access.token, repoUrl, ref);
369
+ sendJson(200, { devcontainer: false, hub, checked: true });
370
+ } catch {
371
+ sendJson(200, { devcontainer: false, hub: false, checked: false });
372
+ }
373
+ return;
374
+ }
375
+ const gh = githubParts(rawUrl);
376
+ if (!gh) {
377
+ sendJson(400, { error: 'repo_invalid' });
378
+ return;
379
+ }
380
+ owner = gh.owner;
381
+ repo = gh.repo;
382
+ }
383
+ if (!/^[A-Za-z0-9_.-]+$/.test(owner) || !/^[A-Za-z0-9_.-]+$/.test(repo)) {
384
+ sendJson(400, { error: 'repo_invalid' });
385
+ return;
386
+ }
387
+ const ghToken = orchestrator.settingsRepo.getGitHubToken();
388
+ if (!ghToken) {
389
+ sendJson(200, { devcontainer: false, hub: false, checked: false });
390
+ return;
391
+ }
392
+ try {
393
+ const [devcontainer, hub] = await Promise.all([
394
+ orchestrator.github.hasDevcontainer(ghToken, owner, repo, ref),
395
+ orchestrator.github.isHub(ghToken, owner, repo, ref),
396
+ ]);
397
+ sendJson(200, { devcontainer, hub, checked: true });
398
+ } catch {
399
+ sendJson(200, { devcontainer: false, hub: false, checked: false });
400
+ }
401
+ return;
402
+ }
403
+
212
404
  // Segundo paso: issues abiertas de un repo (ready primero, las mías asignadas después).
213
405
  if (pathname === '/api/v1/issues/repo' && method === 'GET') {
214
406
  const owner = String(parsedUrl.searchParams.get('owner') || '');
@@ -496,6 +688,27 @@ export function createServer(orchestrator: Orchestrator): Server {
496
688
  return;
497
689
  }
498
690
 
691
+ // P4: endpoint GET /runs/:id/terminals (proxy hc ls for the run's machine)
692
+ const runTerminalsMatch = pathname.match(/^(?:\/api\/v1)?\/runs\/([^/]+)\/terminals$/);
693
+ if (runTerminalsMatch && method === 'GET') {
694
+ const runId = runTerminalsMatch[1];
695
+ if (!orchestrator.runRepo.get(runId)) {
696
+ sendJson(404, { error: `Run '${runId}' not found` });
697
+ return;
698
+ }
699
+ try {
700
+ const terminals = await orchestrator.getRunTerminals(runId);
701
+ sendJson(200, terminals);
702
+ } catch (err: unknown) {
703
+ if (err instanceof ValidationError) {
704
+ sendJson(400, { error: (err as Error).message });
705
+ return;
706
+ }
707
+ sendJson(500, { error: (err as Error).message });
708
+ }
709
+ return;
710
+ }
711
+
499
712
  const runTransitionMatch =pathname.match(/^\/api\/v1\/runs\/([^/]+)\/transition$/);
500
713
  if (runTransitionMatch && method === 'POST') {
501
714
  const runId = runTransitionMatch[1];
@@ -614,13 +827,81 @@ export function createServer(orchestrator: Orchestrator): Server {
614
827
  sendJson(400, { error: "'config_json' is required" });
615
828
  return;
616
829
  }
617
- orchestrator.settingsRepo.setCredential(agent, configJson, provider);
830
+ // pi: a provider saved without a key keeps the stored one (Ajustes never shows it).
831
+ const toStore = agent === 'pi' ? keepPiKeys(orchestrator.settingsRepo.getCredential('pi')?.config_json, configJson) : configJson;
832
+ orchestrator.settingsRepo.setCredential(agent, toStore, provider);
833
+ const summary = orchestrator.settingsRepo.getSummary(agent);
834
+ sendJson(200, summary);
835
+ return;
836
+ }
837
+ if (method === 'DELETE') {
838
+ orchestrator.settingsRepo.deleteCredential(agent);
618
839
  const summary = orchestrator.settingsRepo.getSummary(agent);
619
840
  sendJson(200, summary);
620
841
  return;
621
842
  }
622
843
  }
623
844
 
845
+ // OAuth login per agent: agy (P1), claude (`claude setup-token`, plan
846
+ // bond-app-claude-agente P2), codex (ChatGPT, browser callback replayed in the
847
+ // container) and copilot (device code), plan bond-app-codex-copilot P2. The API never
848
+ // returns a token, only the session state.
849
+ const loginMatch = pathname.match(/^\/api\/v1\/settings\/(agy|claude|codex|copilot)\/login(\/.*)?$/);
850
+ if (loginMatch) {
851
+ const loginManager = {
852
+ agy: orchestrator.agyLoginManager,
853
+ claude: orchestrator.claudeLoginManager,
854
+ codex: orchestrator.codexLoginManager,
855
+ copilot: orchestrator.copilotLoginManager,
856
+ }[loginMatch[1] as 'agy' | 'claude' | 'codex' | 'copilot'];
857
+ const sub = loginMatch[2] ?? '';
858
+ if (sub === '' || sub === '/status') {
859
+ if (method === 'GET') {
860
+ sendJson(200, loginManager.getStatus());
861
+ return;
862
+ }
863
+ if (method === 'POST') {
864
+ const status = await loginManager.start();
865
+ sendJson(200, status);
866
+ return;
867
+ }
868
+ }
869
+ if (sub === '/start' && method === 'POST') {
870
+ const status = await loginManager.start();
871
+ sendJson(200, status);
872
+ return;
873
+ }
874
+ if (sub === '/url' && method === 'GET') {
875
+ const status = loginManager.getStatus();
876
+ sendJson(200, { url: status.url ?? null });
877
+ return;
878
+ }
879
+ if (sub === '/code' && method === 'POST') {
880
+ const body = await readJson();
881
+ if (typeof body.code !== 'string' || !body.code.trim()) {
882
+ sendJson(400, { error: "'code' must be a non-empty string" });
883
+ return;
884
+ }
885
+ try {
886
+ const status = await loginManager.submitCode(body.code.trim());
887
+ sendJson(200, status);
888
+ } catch (err: unknown) {
889
+ sendJson(400, { error: (err as Error).message });
890
+ }
891
+ return;
892
+ }
893
+ if (sub === '/finish' && method === 'POST') {
894
+ const res = await loginManager.finish();
895
+ sendJson(200, res);
896
+ return;
897
+ }
898
+ if ((sub === '/cancel' && method === 'POST') || (sub === '' && method === 'DELETE')) {
899
+ const status = await loginManager.cancel();
900
+ sendJson(200, status);
901
+ return;
902
+ }
903
+ }
904
+
624
905
  // D20: the GitHub credential for the runs' clones (the user's gh session). The API
625
906
  // only ever says whether one is stored and for which login; never the token.
626
907
  if (pathname === '/api/v1/settings/github') {
@@ -649,6 +930,139 @@ export function createServer(orchestrator: Orchestrator): Server {
649
930
  }
650
931
  }
651
932
 
933
+ // Plan bond-app-azure-jira (P2): Jira Cloud credential (email + API token).
934
+ // The API only ever says whether one is stored, for which site, email and account; never the token.
935
+ if (pathname === '/api/v1/settings/jira') {
936
+ if (method === 'GET') {
937
+ sendJson(200, orchestrator.settingsRepo.getJiraSummary());
938
+ return;
939
+ }
940
+ if (method === 'PUT') {
941
+ const body = await readJson();
942
+ const site = typeof body.site === 'string' ? body.site.trim() : '';
943
+ const email = typeof body.email === 'string' ? body.email.trim() : '';
944
+ const agentsEnabled = body.agents_enabled !== false;
945
+
946
+ if (!validateJiraSite(site)) {
947
+ sendJson(400, { error: "'site' must be a Jira Cloud URL (https://<name>.atlassian.net)" });
948
+ return;
949
+ }
950
+ if (!validateJiraEmail(email)) {
951
+ sendJson(400, { error: "'email' is required and must be a valid email" });
952
+ return;
953
+ }
954
+ let token = typeof body.token === 'string' ? body.token.trim() : '';
955
+ if (!validateJiraToken(token)) {
956
+ // Empty token with a credential already stored: keep the stored one, so the
957
+ // site, the email or the «Disponible para los agentes» switch can be
958
+ // changed without retyping the token (the API never shows it).
959
+ const existing = orchestrator.settingsRepo.getJiraCredential();
960
+ if (!existing) {
961
+ sendJson(400, { error: "'token' is required" });
962
+ return;
963
+ }
964
+ token = existing.token;
965
+ }
966
+
967
+ let accountName: string | undefined;
968
+ try {
969
+ const user = await orchestrator.jira.myself(site, email, token);
970
+ accountName = user.displayName;
971
+ } catch (err: unknown) {
972
+ const status = err instanceof JiraApiError ? err.status : 0;
973
+ const msg = (err as Error).message;
974
+ if (status === 401 || status === 403) {
975
+ sendJson(409, { error: 'jira_authentication_failed', detail: msg });
976
+ } else {
977
+ sendJson(400, { error: 'jira_connection_failed', detail: msg });
978
+ }
979
+ return;
980
+ }
981
+
982
+ const summary = orchestrator.settingsRepo.setJiraCredential(
983
+ site,
984
+ email,
985
+ token,
986
+ agentsEnabled,
987
+ accountName
988
+ );
989
+ sendJson(200, summary);
990
+ return;
991
+ }
992
+ if (method === 'DELETE') {
993
+ orchestrator.settingsRepo.deleteJiraCredential();
994
+ sendJson(200, orchestrator.settingsRepo.getJiraSummary());
995
+ return;
996
+ }
997
+ }
998
+
999
+ // Plan bond-app-azure-jira P1: the Azure DevOps PAT (Azure Repos). PUT checks it against
1000
+ // the organization before storing it; the PAT never comes back.
1001
+ if (pathname === '/api/v1/settings/azure-devops') {
1002
+ const repo = orchestrator.settingsRepo;
1003
+ if (method === 'GET') {
1004
+ sendJson(200, repo.getAzureDevOpsSummary());
1005
+ return;
1006
+ }
1007
+ if (method === 'PUT') {
1008
+ const body = await readJson();
1009
+ const agents = body.agents_enabled === undefined ? undefined : body.agents_enabled;
1010
+ if (agents !== undefined && typeof agents !== 'boolean') {
1011
+ sendJson(400, { error: "'agents_enabled' must be a boolean" });
1012
+ return;
1013
+ }
1014
+ if (body.pat === undefined && body.org_url === undefined) {
1015
+ if (agents === undefined || !repo.getAzureDevOpsCredential()) {
1016
+ sendJson(400, { error: "'org_url' and 'pat' are required" });
1017
+ return;
1018
+ }
1019
+ sendJson(200, repo.setAzureDevOpsAgentsEnabled(agents));
1020
+ return;
1021
+ }
1022
+ const orgUrl = normalizeAzureOrgUrl(String(body.org_url ?? ''));
1023
+ if (!orgUrl) {
1024
+ sendJson(400, { error: "'org_url' must be https://dev.azure.com/<organización>" });
1025
+ return;
1026
+ }
1027
+ const pat = String(body.pat ?? '').trim();
1028
+ if (!/^[A-Za-z0-9]{20,200}$/.test(pat)) {
1029
+ sendJson(400, { error: "'pat' must be an Azure DevOps personal access token" });
1030
+ return;
1031
+ }
1032
+ let who: { name: string; email?: string };
1033
+ try {
1034
+ who = await orchestrator.azure.whoAmI(pat, orgUrl);
1035
+ } catch (err: unknown) {
1036
+ sendJson(409, { error: 'azure_devops_rejected', detail: (err as Error).message });
1037
+ return;
1038
+ }
1039
+ sendJson(200, repo.setAzureDevOpsCredential(orgUrl, pat, who.email ? `${who.name} <${who.email}>` : who.name, agents ?? true));
1040
+ return;
1041
+ }
1042
+ if (method === 'DELETE') {
1043
+ repo.deleteAzureDevOpsCredential();
1044
+ sendJson(200, repo.getAzureDevOpsSummary());
1045
+ return;
1046
+ }
1047
+ }
1048
+
1049
+ // P4 (instalador): installation diagnostics report (no secrets).
1050
+ if (pathname === '/api/v1/doctor' && method === 'GET') {
1051
+ const report = await (hooks.runDoctor ?? runDoctor)({
1052
+ port: orchestrator.config.port,
1053
+ host: orchestrator.config.host,
1054
+ dataDir: orchestrator.config.dataDir,
1055
+ runnerImage: orchestrator.config.runnerImage,
1056
+ deps: {
1057
+ checkHealth: async () => ({ ok: true, statusCode: 200 }),
1058
+ fetchSetupState: async () => await orchestrator.getSetupState(),
1059
+ ...hooks.doctorDeps,
1060
+ },
1061
+ });
1062
+ sendJson(200, report);
1063
+ return;
1064
+ }
1065
+
652
1066
  // W-P1 (wizard): aggregated setup state. GET says what is missing; PUT stores the
653
1067
  // agent selection and setup_done (only via an explicit write). No credentials here:
654
1068
  // the aggregate only says whether each piece is configured (D13 summaries).
@@ -665,6 +1079,8 @@ export function createServer(orchestrator: Orchestrator): Server {
665
1079
  suggestions_model?: string | null;
666
1080
  default_model?: string | null;
667
1081
  models?: string[];
1082
+ tools_selected?: string[];
1083
+ apt_extra?: string[];
668
1084
  } = {};
669
1085
  if (body.agents_selected !== undefined) {
670
1086
  const sel: unknown = body.agents_selected;
@@ -713,6 +1129,14 @@ export function createServer(orchestrator: Orchestrator): Server {
713
1129
  const sanitized = (m as string[]).map((x) => x.trim()).filter(Boolean);
714
1130
  selection.models = [...new Set(sanitized)];
715
1131
  }
1132
+ // Plan bond-app-ajustes-imagen P2: tool groups of the catalog and extra Debian packages.
1133
+ try {
1134
+ if (body.tools_selected !== undefined) selection.tools_selected = validateToolGroups(body.tools_selected);
1135
+ if (body.apt_extra !== undefined) selection.apt_extra = validateAptExtra(body.apt_extra);
1136
+ } catch (err: unknown) {
1137
+ sendJson(400, { error: (err as Error).message });
1138
+ return;
1139
+ }
716
1140
  orchestrator.saveSetup(selection);
717
1141
  sendJson(200, await orchestrator.getSetupState());
718
1142
  return;
@@ -749,6 +1173,25 @@ export function createServer(orchestrator: Orchestrator): Server {
749
1173
  // (non-empty string array) picks the agent list baked by runner/setup.sh. Optional
750
1174
  // config_dir / credentials_file name paths inside the data dir (validated by the
751
1175
  // builder; credentials must be 0600, and an image built with them is a local secret, D-A).
1176
+ // «Reiniciar orquestador» (Ajustes): answer first, then the process stops like Ctrl+C
1177
+ // and starts again with the same argv and environment (RUNNER_IMAGE, --data-dir...).
1178
+ if (pathname === '/api/v1/system/restart' && method === 'POST') {
1179
+ const onRestart = hooks.onRestart;
1180
+ if (!onRestart) {
1181
+ sendJson(501, { error: 'this orchestrator process cannot restart itself' });
1182
+ return;
1183
+ }
1184
+ res.once('finish', () => setImmediate(onRestart));
1185
+ sendJson(202, { restarting: true });
1186
+ return;
1187
+ }
1188
+
1189
+ // Progress of the image build in flight, or how the last one ended (Ajustes → Imagen).
1190
+ if (pathname === '/api/v1/system/rebuild' && method === 'GET') {
1191
+ sendJson(200, orchestrator.getRebuildStatus());
1192
+ return;
1193
+ }
1194
+
752
1195
  if (pathname === '/api/v1/system/rebuild' && method === 'POST') {
753
1196
  let body: Record<string, unknown> = {};
754
1197
  // Optional JSON body; readJson resolves {} on an empty body, and this keeps
@@ -763,6 +1206,8 @@ export function createServer(orchestrator: Orchestrator): Server {
763
1206
  agents?: string[];
764
1207
  skip_az?: boolean;
765
1208
  skip_gh?: boolean;
1209
+ tools?: string[];
1210
+ apt_extra?: string[];
766
1211
  config_dir?: string;
767
1212
  credentials_file?: string;
768
1213
  } = {};
@@ -773,6 +1218,20 @@ export function createServer(orchestrator: Orchestrator): Server {
773
1218
  }
774
1219
  extras.agents = body.agents.map((a) => String(a));
775
1220
  }
1221
+ if (body.tools !== undefined) {
1222
+ if (!Array.isArray(body.tools)) {
1223
+ sendJson(400, { error: "'tools' must be an array of tool group ids" });
1224
+ return;
1225
+ }
1226
+ extras.tools = body.tools.map((t) => String(t));
1227
+ }
1228
+ if (body.apt_extra !== undefined) {
1229
+ if (!Array.isArray(body.apt_extra)) {
1230
+ sendJson(400, { error: "'apt_extra' must be an array of Debian package names" });
1231
+ return;
1232
+ }
1233
+ extras.apt_extra = body.apt_extra.map((t) => String(t));
1234
+ }
776
1235
  for (const key of ['skip_az', 'skip_gh'] as const) {
777
1236
  const value = body[key];
778
1237
  if (typeof value === 'boolean') extras[key] = value;