@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
package/src/server/app.ts CHANGED
@@ -12,11 +12,35 @@ import {
12
12
  JsonParseError,
13
13
  PayloadTooLargeError,
14
14
  } from '../core/orchestrator.ts';
15
- import { InvalidVersionError, type RunnerVersions } from '../runner/image-builder.ts';
15
+ import { InvalidBuildOptionsError, InvalidVersionError, type RunnerVersions } from '../runner/image-builder.ts';
16
+ import { GitHubApiError } from '../runner/github-client.ts';
17
+ import { JiraApiError } from '../runner/jira-client.ts';
18
+ import { validateAptExtra, validateToolGroups } from '../runner/tool-catalog.ts';
19
+ import { normalizeAzureOrgUrl } from '../runner/azure-devops-client.ts';
20
+ import { validateRepoUrl } from '../core/repo-host.ts';
21
+ import { keepPiKeys } from '../db/settings-repo.ts';
22
+ import { listProviderModels, normalizeProviderBase, ProviderModelsError } from '../core/setup.ts';
16
23
  import { InvalidStateTransitionError } from '../core/state-machine.ts';
17
- import { isValidAgent, validateGitHubLogin, validateGitHubToken, type CreateTicketInput, type RunState } from '../types.ts';
24
+ import {
25
+ isValidAgent,
26
+ isSetupAgent,
27
+ SETUP_AGENTS,
28
+ validateGitHubLogin,
29
+ validateGitHubToken,
30
+ validateJiraSite,
31
+ validateJiraEmail,
32
+ validateJiraToken,
33
+ type CreateTicketInput,
34
+ type RunState,
35
+ } from '../types.ts';
36
+
37
+ /** What the server can ask of the process that runs it. */
38
+ export interface ServerHooks {
39
+ /** Stop like Ctrl+C and start again with the same argv and environment (Ajustes «Reiniciar»). */
40
+ onRestart?: () => void;
41
+ }
18
42
 
19
- export function createServer(orchestrator: Orchestrator): Server {
43
+ export function createServer(orchestrator: Orchestrator, hooks: ServerHooks = {}): Server {
20
44
  return http.createServer(async (req: IncomingMessage, res: ServerResponse) => {
21
45
  const sendJson = (statusCode: number, data: unknown) => {
22
46
  res.writeHead(statusCode, { 'Content-Type': 'application/json' });
@@ -152,6 +176,189 @@ export function createServer(orchestrator: Orchestrator): Server {
152
176
  }
153
177
  }
154
178
 
179
+ // Plan bond-app-nuevo-ticket (P1, D2): issues to link a new ticket to — the ones
180
+ // assigned to the user (GitHub session from Ajustes, or Jira Cloud), open, `ready` first.
181
+ if (pathname === '/api/v1/issues/assigned' && method === 'GET') {
182
+ const provider = parsedUrl.searchParams.get('provider') || 'github';
183
+ if (provider !== 'github' && provider !== 'jira') {
184
+ sendJson(400, { error: `Unknown issue provider: ${provider}` });
185
+ return;
186
+ }
187
+ if (provider === 'jira') {
188
+ const jiraCred = orchestrator.settingsRepo.getJiraCredential();
189
+ if (!jiraCred) {
190
+ sendJson(409, { error: 'jira_not_configured' });
191
+ return;
192
+ }
193
+ try {
194
+ const issues = await orchestrator.jira.listAssigned(jiraCred.site, jiraCred.email, jiraCred.token);
195
+ const summary = orchestrator.settingsRepo.getJiraSummary();
196
+ sendJson(200, {
197
+ ok: true,
198
+ provider: 'jira',
199
+ login: summary.account_name ?? summary.email ?? null,
200
+ site: summary.site,
201
+ issues,
202
+ });
203
+ } catch (err: unknown) {
204
+ const status = err instanceof JiraApiError ? err.status : 0;
205
+ if (status === 401 || status === 403) {
206
+ sendJson(409, { error: 'jira_not_configured', detail: (err as Error).message });
207
+ } else {
208
+ sendJson(502, { error: 'jira_api_error', detail: (err as Error).message });
209
+ }
210
+ }
211
+ return;
212
+ }
213
+ const ghToken = orchestrator.settingsRepo.getGitHubToken();
214
+ if (!ghToken) {
215
+ sendJson(409, { error: 'github_not_configured' });
216
+ return;
217
+ }
218
+ try {
219
+ const issues = await orchestrator.github.listAssigned(ghToken);
220
+ const summary = orchestrator.settingsRepo.getGitHubSummary();
221
+ sendJson(200, { ok: true, provider: 'github', login: summary.login ?? null, issues });
222
+ } catch (err: unknown) {
223
+ const status = err instanceof GitHubApiError ? err.status : 0;
224
+ if (status === 401 || status === 403 || status === 404) {
225
+ sendJson(409, { error: 'github_not_configured' });
226
+ } else {
227
+ sendJson(502, { error: 'github_api_error', detail: (err as Error).message });
228
+ }
229
+ }
230
+ return;
231
+ }
232
+
233
+ // Plan bond-app-azure-jira (P2): búsqueda de issues de Jira por texto y/o proyecto
234
+ if (pathname === '/api/v1/issues/jira/search' && method === 'GET') {
235
+ const q = String(parsedUrl.searchParams.get('q') || '').trim();
236
+ const project = String(parsedUrl.searchParams.get('project') || '').trim();
237
+ const mine = parsedUrl.searchParams.get('mine') === '1';
238
+ const jiraCred = orchestrator.settingsRepo.getJiraCredential();
239
+ if (!jiraCred) {
240
+ sendJson(409, { error: 'jira_not_configured' });
241
+ return;
242
+ }
243
+ try {
244
+ const issues = await orchestrator.jira.search(jiraCred.site, jiraCred.email, jiraCred.token, { q, project, mine });
245
+ sendJson(200, { ok: true, provider: 'jira', issues });
246
+ } catch (err: unknown) {
247
+ const status = err instanceof JiraApiError ? err.status : 0;
248
+ if (status === 401 || status === 403) {
249
+ sendJson(409, { error: 'jira_not_configured', detail: (err as Error).message });
250
+ } else {
251
+ sendJson(502, { error: 'jira_api_error', detail: (err as Error).message });
252
+ }
253
+ }
254
+ return;
255
+ }
256
+
257
+ // Plan bond-app-nuevo-ticket (P2): primer paso de la búsqueda combinada del diálogo —
258
+ // repos por nombre (buscador de GitHub), con la misma sesión de gh de Ajustes.
259
+ if (pathname === '/api/v1/repos/search' && method === 'GET') {
260
+ const q = String(parsedUrl.searchParams.get('q') || '').trim();
261
+ if (!q) {
262
+ sendJson(400, { error: 'q_required' });
263
+ return;
264
+ }
265
+ const ghToken = orchestrator.settingsRepo.getGitHubToken();
266
+ if (!ghToken) {
267
+ sendJson(409, { error: 'github_not_configured' });
268
+ return;
269
+ }
270
+ try {
271
+ const repos = await orchestrator.github.searchRepos(ghToken, q);
272
+ sendJson(200, { ok: true, provider: 'github', repos });
273
+ } catch (err: unknown) {
274
+ const status = err instanceof GitHubApiError ? err.status : 0;
275
+ if (status === 401 || status === 403 || status === 404) {
276
+ sendJson(409, { error: 'github_not_configured' });
277
+ } else {
278
+ sendJson(502, { error: 'github_api_error', detail: (err as Error).message });
279
+ }
280
+ }
281
+ return;
282
+ }
283
+
284
+ // Alta de ticket (Dónde): favoritos, recientes, Azure Repos y GitHub en una lista.
285
+ if (pathname === '/api/v1/repos/suggest' && method === 'GET') {
286
+ const q = String(parsedUrl.searchParams.get('q') || '').slice(0, 100);
287
+ sendJson(200, await orchestrator.suggestRepos(q));
288
+ return;
289
+ }
290
+ if (pathname === '/api/v1/repos/favorites') {
291
+ if (method === 'GET') {
292
+ sendJson(200, { favorites: orchestrator.settingsRepo.getFavoriteRepos() });
293
+ return;
294
+ }
295
+ if (method === 'PUT') {
296
+ const body = await readJson();
297
+ const list: unknown = body.favorites;
298
+ if (!Array.isArray(list) || list.some((u) => typeof u !== 'string' || !validateRepoUrl(u))) {
299
+ sendJson(400, { error: "'favorites' must be a list of GitHub or Azure Repos URLs" });
300
+ return;
301
+ }
302
+ sendJson(200, { favorites: orchestrator.settingsRepo.setFavoriteRepos(list as string[]) });
303
+ return;
304
+ }
305
+ }
306
+
307
+ // Plan bond-app-ajustes-imagen P4: ¿trae el repo devcontainer? (pre-marca «Docker en el run»).
308
+ // Alta en tres bloques: y ¿es un hub (hub.toml)? (el alta pasa sola a modo hub).
309
+ if (pathname === '/api/v1/repos/devcontainer' && method === 'GET') {
310
+ const owner = String(parsedUrl.searchParams.get('owner') || '');
311
+ const repo = String(parsedUrl.searchParams.get('repo') || '');
312
+ const ref = String(parsedUrl.searchParams.get('ref') || '').trim() || undefined;
313
+ if (!/^[A-Za-z0-9_.-]+$/.test(owner) || !/^[A-Za-z0-9_.-]+$/.test(repo) || (ref && !/^[A-Za-z0-9._\/-]{1,200}$/.test(ref))) {
314
+ sendJson(400, { error: 'repo_invalid' });
315
+ return;
316
+ }
317
+ const ghToken = orchestrator.settingsRepo.getGitHubToken();
318
+ if (!ghToken) {
319
+ sendJson(200, { devcontainer: false, hub: false, checked: false });
320
+ return;
321
+ }
322
+ try {
323
+ const [devcontainer, hub] = await Promise.all([
324
+ orchestrator.github.hasDevcontainer(ghToken, owner, repo, ref),
325
+ orchestrator.github.isHub(ghToken, owner, repo, ref),
326
+ ]);
327
+ sendJson(200, { devcontainer, hub, checked: true });
328
+ } catch {
329
+ sendJson(200, { devcontainer: false, hub: false, checked: false });
330
+ }
331
+ return;
332
+ }
333
+
334
+ // Segundo paso: issues abiertas de un repo (ready primero, las mías asignadas después).
335
+ if (pathname === '/api/v1/issues/repo' && method === 'GET') {
336
+ const owner = String(parsedUrl.searchParams.get('owner') || '');
337
+ const repo = String(parsedUrl.searchParams.get('repo') || '');
338
+ if (!/^[A-Za-z0-9_.-]+$/.test(owner) || !/^[A-Za-z0-9_.-]+$/.test(repo)) {
339
+ sendJson(400, { error: 'repo_invalid' });
340
+ return;
341
+ }
342
+ const ghToken = orchestrator.settingsRepo.getGitHubToken();
343
+ if (!ghToken) {
344
+ sendJson(409, { error: 'github_not_configured' });
345
+ return;
346
+ }
347
+ try {
348
+ const summary = orchestrator.settingsRepo.getGitHubSummary();
349
+ const issues = await orchestrator.github.listRepoIssues(ghToken, owner, repo, summary.login ?? null);
350
+ sendJson(200, { ok: true, provider: 'github', owner, repo, issues });
351
+ } catch (err: unknown) {
352
+ const status = err instanceof GitHubApiError ? err.status : 0;
353
+ if (status === 401 || status === 403 || status === 404) {
354
+ sendJson(409, { error: 'github_not_configured' });
355
+ } else {
356
+ sendJson(502, { error: 'github_api_error', detail: (err as Error).message });
357
+ }
358
+ }
359
+ return;
360
+ }
361
+
155
362
  const ticketPreviewMatch = pathname.match(/^\/api\/v1\/tickets\/([^/]+)\/delete_preview$/);
156
363
  if (ticketPreviewMatch && method === 'GET') {
157
364
  const ticketId = ticketPreviewMatch[1];
@@ -411,6 +618,27 @@ export function createServer(orchestrator: Orchestrator): Server {
411
618
  return;
412
619
  }
413
620
 
621
+ // P4: endpoint GET /runs/:id/terminals (proxy hc ls for the run's machine)
622
+ const runTerminalsMatch = pathname.match(/^(?:\/api\/v1)?\/runs\/([^/]+)\/terminals$/);
623
+ if (runTerminalsMatch && method === 'GET') {
624
+ const runId = runTerminalsMatch[1];
625
+ if (!orchestrator.runRepo.get(runId)) {
626
+ sendJson(404, { error: `Run '${runId}' not found` });
627
+ return;
628
+ }
629
+ try {
630
+ const terminals = await orchestrator.getRunTerminals(runId);
631
+ sendJson(200, terminals);
632
+ } catch (err: unknown) {
633
+ if (err instanceof ValidationError) {
634
+ sendJson(400, { error: (err as Error).message });
635
+ return;
636
+ }
637
+ sendJson(500, { error: (err as Error).message });
638
+ }
639
+ return;
640
+ }
641
+
414
642
  const runTransitionMatch =pathname.match(/^\/api\/v1\/runs\/([^/]+)\/transition$/);
415
643
  if (runTransitionMatch && method === 'POST') {
416
644
  const runId = runTransitionMatch[1];
@@ -529,13 +757,81 @@ export function createServer(orchestrator: Orchestrator): Server {
529
757
  sendJson(400, { error: "'config_json' is required" });
530
758
  return;
531
759
  }
532
- orchestrator.settingsRepo.setCredential(agent, configJson, provider);
760
+ // pi: a provider saved without a key keeps the stored one (Ajustes never shows it).
761
+ const toStore = agent === 'pi' ? keepPiKeys(orchestrator.settingsRepo.getCredential('pi')?.config_json, configJson) : configJson;
762
+ orchestrator.settingsRepo.setCredential(agent, toStore, provider);
763
+ const summary = orchestrator.settingsRepo.getSummary(agent);
764
+ sendJson(200, summary);
765
+ return;
766
+ }
767
+ if (method === 'DELETE') {
768
+ orchestrator.settingsRepo.deleteCredential(agent);
533
769
  const summary = orchestrator.settingsRepo.getSummary(agent);
534
770
  sendJson(200, summary);
535
771
  return;
536
772
  }
537
773
  }
538
774
 
775
+ // OAuth login per agent: agy (P1), claude (`claude setup-token`, plan
776
+ // bond-app-claude-agente P2), codex (ChatGPT, browser callback replayed in the
777
+ // container) and copilot (device code), plan bond-app-codex-copilot P2. The API never
778
+ // returns a token, only the session state.
779
+ const loginMatch = pathname.match(/^\/api\/v1\/settings\/(agy|claude|codex|copilot)\/login(\/.*)?$/);
780
+ if (loginMatch) {
781
+ const loginManager = {
782
+ agy: orchestrator.agyLoginManager,
783
+ claude: orchestrator.claudeLoginManager,
784
+ codex: orchestrator.codexLoginManager,
785
+ copilot: orchestrator.copilotLoginManager,
786
+ }[loginMatch[1] as 'agy' | 'claude' | 'codex' | 'copilot'];
787
+ const sub = loginMatch[2] ?? '';
788
+ if (sub === '' || sub === '/status') {
789
+ if (method === 'GET') {
790
+ sendJson(200, loginManager.getStatus());
791
+ return;
792
+ }
793
+ if (method === 'POST') {
794
+ const status = await loginManager.start();
795
+ sendJson(200, status);
796
+ return;
797
+ }
798
+ }
799
+ if (sub === '/start' && method === 'POST') {
800
+ const status = await loginManager.start();
801
+ sendJson(200, status);
802
+ return;
803
+ }
804
+ if (sub === '/url' && method === 'GET') {
805
+ const status = loginManager.getStatus();
806
+ sendJson(200, { url: status.url ?? null });
807
+ return;
808
+ }
809
+ if (sub === '/code' && method === 'POST') {
810
+ const body = await readJson();
811
+ if (typeof body.code !== 'string' || !body.code.trim()) {
812
+ sendJson(400, { error: "'code' must be a non-empty string" });
813
+ return;
814
+ }
815
+ try {
816
+ const status = await loginManager.submitCode(body.code.trim());
817
+ sendJson(200, status);
818
+ } catch (err: unknown) {
819
+ sendJson(400, { error: (err as Error).message });
820
+ }
821
+ return;
822
+ }
823
+ if (sub === '/finish' && method === 'POST') {
824
+ const res = await loginManager.finish();
825
+ sendJson(200, res);
826
+ return;
827
+ }
828
+ if ((sub === '/cancel' && method === 'POST') || (sub === '' && method === 'DELETE')) {
829
+ const status = await loginManager.cancel();
830
+ sendJson(200, status);
831
+ return;
832
+ }
833
+ }
834
+
539
835
  // D20: the GitHub credential for the runs' clones (the user's gh session). The API
540
836
  // only ever says whether one is stored and for which login; never the token.
541
837
  if (pathname === '/api/v1/settings/github') {
@@ -564,9 +860,251 @@ export function createServer(orchestrator: Orchestrator): Server {
564
860
  }
565
861
  }
566
862
 
567
- // P2 criterion 7 (D7): rebuild the runner image without touching credentials.
568
- // Optional body {bond?, hc?, hc_sha256?, herdr?, herdr_sha256?, pi?} pins new versions via --build-arg (review M4);
569
- // a new hc version needs its checksum (P2 debt N1).
863
+ // Plan bond-app-azure-jira (P2): Jira Cloud credential (email + API token).
864
+ // The API only ever says whether one is stored, for which site, email and account; never the token.
865
+ if (pathname === '/api/v1/settings/jira') {
866
+ if (method === 'GET') {
867
+ sendJson(200, orchestrator.settingsRepo.getJiraSummary());
868
+ return;
869
+ }
870
+ if (method === 'PUT') {
871
+ const body = await readJson();
872
+ const site = typeof body.site === 'string' ? body.site.trim() : '';
873
+ const email = typeof body.email === 'string' ? body.email.trim() : '';
874
+ const agentsEnabled = body.agents_enabled !== false;
875
+
876
+ if (!validateJiraSite(site)) {
877
+ sendJson(400, { error: "'site' must be a Jira Cloud URL (https://<name>.atlassian.net)" });
878
+ return;
879
+ }
880
+ if (!validateJiraEmail(email)) {
881
+ sendJson(400, { error: "'email' is required and must be a valid email" });
882
+ return;
883
+ }
884
+ let token = typeof body.token === 'string' ? body.token.trim() : '';
885
+ if (!validateJiraToken(token)) {
886
+ // Empty token with a credential already stored: keep the stored one, so the
887
+ // site, the email or the «Disponible para los agentes» switch can be
888
+ // changed without retyping the token (the API never shows it).
889
+ const existing = orchestrator.settingsRepo.getJiraCredential();
890
+ if (!existing) {
891
+ sendJson(400, { error: "'token' is required" });
892
+ return;
893
+ }
894
+ token = existing.token;
895
+ }
896
+
897
+ let accountName: string | undefined;
898
+ try {
899
+ const user = await orchestrator.jira.myself(site, email, token);
900
+ accountName = user.displayName;
901
+ } catch (err: unknown) {
902
+ const status = err instanceof JiraApiError ? err.status : 0;
903
+ const msg = (err as Error).message;
904
+ if (status === 401 || status === 403) {
905
+ sendJson(409, { error: 'jira_authentication_failed', detail: msg });
906
+ } else {
907
+ sendJson(400, { error: 'jira_connection_failed', detail: msg });
908
+ }
909
+ return;
910
+ }
911
+
912
+ const summary = orchestrator.settingsRepo.setJiraCredential(
913
+ site,
914
+ email,
915
+ token,
916
+ agentsEnabled,
917
+ accountName
918
+ );
919
+ sendJson(200, summary);
920
+ return;
921
+ }
922
+ if (method === 'DELETE') {
923
+ orchestrator.settingsRepo.deleteJiraCredential();
924
+ sendJson(200, orchestrator.settingsRepo.getJiraSummary());
925
+ return;
926
+ }
927
+ }
928
+
929
+ // Plan bond-app-azure-jira P1: the Azure DevOps PAT (Azure Repos). PUT checks it against
930
+ // the organization before storing it; the PAT never comes back.
931
+ if (pathname === '/api/v1/settings/azure-devops') {
932
+ const repo = orchestrator.settingsRepo;
933
+ if (method === 'GET') {
934
+ sendJson(200, repo.getAzureDevOpsSummary());
935
+ return;
936
+ }
937
+ if (method === 'PUT') {
938
+ const body = await readJson();
939
+ const agents = body.agents_enabled === undefined ? undefined : body.agents_enabled;
940
+ if (agents !== undefined && typeof agents !== 'boolean') {
941
+ sendJson(400, { error: "'agents_enabled' must be a boolean" });
942
+ return;
943
+ }
944
+ if (body.pat === undefined && body.org_url === undefined) {
945
+ if (agents === undefined || !repo.getAzureDevOpsCredential()) {
946
+ sendJson(400, { error: "'org_url' and 'pat' are required" });
947
+ return;
948
+ }
949
+ sendJson(200, repo.setAzureDevOpsAgentsEnabled(agents));
950
+ return;
951
+ }
952
+ const orgUrl = normalizeAzureOrgUrl(String(body.org_url ?? ''));
953
+ if (!orgUrl) {
954
+ sendJson(400, { error: "'org_url' must be https://dev.azure.com/<organización>" });
955
+ return;
956
+ }
957
+ const pat = String(body.pat ?? '').trim();
958
+ if (!/^[A-Za-z0-9]{20,200}$/.test(pat)) {
959
+ sendJson(400, { error: "'pat' must be an Azure DevOps personal access token" });
960
+ return;
961
+ }
962
+ let who: { name: string; email?: string };
963
+ try {
964
+ who = await orchestrator.azure.whoAmI(pat, orgUrl);
965
+ } catch (err: unknown) {
966
+ sendJson(409, { error: 'azure_devops_rejected', detail: (err as Error).message });
967
+ return;
968
+ }
969
+ sendJson(200, repo.setAzureDevOpsCredential(orgUrl, pat, who.email ? `${who.name} <${who.email}>` : who.name, agents ?? true));
970
+ return;
971
+ }
972
+ if (method === 'DELETE') {
973
+ repo.deleteAzureDevOpsCredential();
974
+ sendJson(200, repo.getAzureDevOpsSummary());
975
+ return;
976
+ }
977
+ }
978
+
979
+ // W-P1 (wizard): aggregated setup state. GET says what is missing; PUT stores the
980
+ // agent selection and setup_done (only via an explicit write). No credentials here:
981
+ // the aggregate only says whether each piece is configured (D13 summaries).
982
+ if (pathname === '/api/v1/setup') {
983
+ if (method === 'GET') {
984
+ sendJson(200, await orchestrator.getSetupState());
985
+ return;
986
+ }
987
+ if (method === 'PUT') {
988
+ const body = await readJson();
989
+ const selection: {
990
+ agents_selected?: string[];
991
+ setup_done?: boolean;
992
+ suggestions_model?: string | null;
993
+ default_model?: string | null;
994
+ models?: string[];
995
+ tools_selected?: string[];
996
+ apt_extra?: string[];
997
+ } = {};
998
+ if (body.agents_selected !== undefined) {
999
+ const sel: unknown = body.agents_selected;
1000
+ if (!Array.isArray(sel) || sel.some((a) => typeof a !== 'string' || !isSetupAgent(a))) {
1001
+ sendJson(400, {
1002
+ error: `'agents_selected' must be a list of the agents the image supports: ${SETUP_AGENTS.join(', ')}`,
1003
+ });
1004
+ return;
1005
+ }
1006
+ selection.agents_selected = [...new Set(sel as string[])];
1007
+ }
1008
+ if (body.setup_done !== undefined) {
1009
+ if (typeof body.setup_done !== 'boolean') {
1010
+ sendJson(400, { error: "'setup_done' must be a boolean" });
1011
+ return;
1012
+ }
1013
+ selection.setup_done = body.setup_done;
1014
+ }
1015
+ if (body.suggestions_model !== undefined) {
1016
+ // W-P4: loose validation (the plan's contract): a string id or null; whether
1017
+ // the model still exists in the provider is not checked — a later PUT or run
1018
+ // simply stops using it. '' reads as «sin sugerencias».
1019
+ const v = body.suggestions_model;
1020
+ if (v === null) selection.suggestions_model = null;
1021
+ else if (typeof v === 'string') selection.suggestions_model = v.trim() || null;
1022
+ else {
1023
+ sendJson(400, { error: "'suggestions_model' must be a string or null" });
1024
+ return;
1025
+ }
1026
+ }
1027
+ if (body.default_model !== undefined) {
1028
+ const v = body.default_model;
1029
+ if (v === null) selection.default_model = null;
1030
+ else if (typeof v === 'string') selection.default_model = v.trim() || null;
1031
+ else {
1032
+ sendJson(400, { error: "'default_model' must be a string or null" });
1033
+ return;
1034
+ }
1035
+ }
1036
+ if (body.models !== undefined) {
1037
+ const m = body.models;
1038
+ if (!Array.isArray(m) || m.some((x) => typeof x !== 'string')) {
1039
+ sendJson(400, { error: "'models' must be an array of strings" });
1040
+ return;
1041
+ }
1042
+ const sanitized = (m as string[]).map((x) => x.trim()).filter(Boolean);
1043
+ selection.models = [...new Set(sanitized)];
1044
+ }
1045
+ // Plan bond-app-ajustes-imagen P2: tool groups of the catalog and extra Debian packages.
1046
+ try {
1047
+ if (body.tools_selected !== undefined) selection.tools_selected = validateToolGroups(body.tools_selected);
1048
+ if (body.apt_extra !== undefined) selection.apt_extra = validateAptExtra(body.apt_extra);
1049
+ } catch (err: unknown) {
1050
+ sendJson(400, { error: (err as Error).message });
1051
+ return;
1052
+ }
1053
+ orchestrator.saveSetup(selection);
1054
+ sendJson(200, await orchestrator.getSetupState());
1055
+ return;
1056
+ }
1057
+ }
1058
+
1059
+ // W-P4: model list of an OpenAI-compatible provider, proxied by the orchestrator
1060
+ // (the browser never talks to the provider and the API key never goes to the log).
1061
+ if (pathname === '/api/v1/setup/models' && method === 'POST') {
1062
+ const body = await readJson(16 * 1024);
1063
+ const baseUrl = typeof body.base_url === 'string' ? body.base_url.trim() : '';
1064
+ if (!baseUrl || !normalizeProviderBase(baseUrl)) {
1065
+ sendJson(400, { error: "'base_url' must be an http(s) URL" });
1066
+ return;
1067
+ }
1068
+ const apiKey = typeof body.api_key === 'string' && body.api_key.trim() ? body.api_key.trim() : undefined;
1069
+ try {
1070
+ const models = await listProviderModels({ baseUrl, apiKey });
1071
+ sendJson(200, { models });
1072
+ } catch (err) {
1073
+ // ProviderModelsError messages carry neither the key nor the URL.
1074
+ if (err instanceof ProviderModelsError) {
1075
+ sendJson(502, { error: err.message });
1076
+ } else {
1077
+ sendJson(502, { error: 'could not list the provider models' });
1078
+ }
1079
+ }
1080
+ return;
1081
+ }
1082
+
1083
+ // P2 criterion 7 (D7) + image plan P2: rebuild the runner image. Optional JSON body
1084
+ // {bond?, hc?, hc_sha256?, herdr?, herdr_sha256?, pi?} pins new versions via --build-arg
1085
+ // (review M4; a new hc version needs its checksum, P2 debt N1), and {agents?}
1086
+ // (non-empty string array) picks the agent list baked by runner/setup.sh. Optional
1087
+ // config_dir / credentials_file name paths inside the data dir (validated by the
1088
+ // builder; credentials must be 0600, and an image built with them is a local secret, D-A).
1089
+ // «Reiniciar orquestador» (Ajustes): answer first, then the process stops like Ctrl+C
1090
+ // and starts again with the same argv and environment (RUNNER_IMAGE, --data-dir...).
1091
+ if (pathname === '/api/v1/system/restart' && method === 'POST') {
1092
+ const onRestart = hooks.onRestart;
1093
+ if (!onRestart) {
1094
+ sendJson(501, { error: 'this orchestrator process cannot restart itself' });
1095
+ return;
1096
+ }
1097
+ res.once('finish', () => setImmediate(onRestart));
1098
+ sendJson(202, { restarting: true });
1099
+ return;
1100
+ }
1101
+
1102
+ // Progress of the image build in flight, or how the last one ended (Ajustes → Imagen).
1103
+ if (pathname === '/api/v1/system/rebuild' && method === 'GET') {
1104
+ sendJson(200, orchestrator.getRebuildStatus());
1105
+ return;
1106
+ }
1107
+
570
1108
  if (pathname === '/api/v1/system/rebuild' && method === 'POST') {
571
1109
  let body: Record<string, unknown> = {};
572
1110
  // Optional JSON body; readJson resolves {} on an empty body, and this keeps
@@ -577,7 +1115,45 @@ export function createServer(orchestrator: Orchestrator): Server {
577
1115
  const value = body[key];
578
1116
  if (value !== undefined) versions[key] = String(value);
579
1117
  }
580
- const result = await orchestrator.rebuildRunnerImage(versions);
1118
+ const extras: {
1119
+ agents?: string[];
1120
+ skip_az?: boolean;
1121
+ skip_gh?: boolean;
1122
+ tools?: string[];
1123
+ apt_extra?: string[];
1124
+ config_dir?: string;
1125
+ credentials_file?: string;
1126
+ } = {};
1127
+ if (body.agents !== undefined) {
1128
+ if (!Array.isArray(body.agents) || body.agents.length === 0) {
1129
+ sendJson(400, { error: "'agents' must be a non-empty array of agent names" });
1130
+ return;
1131
+ }
1132
+ extras.agents = body.agents.map((a) => String(a));
1133
+ }
1134
+ if (body.tools !== undefined) {
1135
+ if (!Array.isArray(body.tools)) {
1136
+ sendJson(400, { error: "'tools' must be an array of tool group ids" });
1137
+ return;
1138
+ }
1139
+ extras.tools = body.tools.map((t) => String(t));
1140
+ }
1141
+ if (body.apt_extra !== undefined) {
1142
+ if (!Array.isArray(body.apt_extra)) {
1143
+ sendJson(400, { error: "'apt_extra' must be an array of Debian package names" });
1144
+ return;
1145
+ }
1146
+ extras.apt_extra = body.apt_extra.map((t) => String(t));
1147
+ }
1148
+ for (const key of ['skip_az', 'skip_gh'] as const) {
1149
+ const value = body[key];
1150
+ if (typeof value === 'boolean') extras[key] = value;
1151
+ }
1152
+ for (const key of ['config_dir', 'credentials_file'] as const) {
1153
+ const value = body[key];
1154
+ if (typeof value === 'string' && value.trim()) extras[key] = value.trim();
1155
+ }
1156
+ const result = await orchestrator.rebuildRunnerImage(versions, extras);
581
1157
  sendJson(200, result);
582
1158
  return;
583
1159
  }
@@ -589,7 +1165,7 @@ export function createServer(orchestrator: Orchestrator): Server {
589
1165
  sendJson(409, { error: (err as Error).message });
590
1166
  return;
591
1167
  }
592
- if (err instanceof InvalidVersionError || err instanceof JsonParseError || err instanceof ValidationError) {
1168
+ if (err instanceof InvalidVersionError || err instanceof InvalidBuildOptionsError || err instanceof JsonParseError || err instanceof ValidationError) {
593
1169
  sendJson(400, { error: (err as Error).message });
594
1170
  return;
595
1171
  }