@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
@@ -5,59 +5,341 @@
5
5
  // P6: a side panel of the bond layout that folds away (node `settings`, toggled from the
6
6
  // title bar or the status bar; its ✕ hides it). The versions moved to the status bar.
7
7
  //
8
- // Props: none (the panel), or { view: "credential", agent, provider } /
9
- // { view: "rebuild" } when this mod is opened as a dialog by the panel itself.
10
- import { View, div } from "gpui-kit";
8
+ // W-P2: the setup wizard lives here too (D-W1): { view: "wizard", step } opened as an
9
+ // overlay — 1 agents, 2 credentials, 3 GitHub, 4 image — and the panel gained a
10
+ // «Configuración» section (GET/PUT /setup) with «Reabrir asistente» (D-W2).
11
+ //
12
+ // W-P3: pi's credential dialog is a builder, not a JSON paste: «modelo local /
13
+ // OpenAI-compatible» asks provider name, base URL, optional API key and model ids and
14
+ // builds the models.json itself (pi-models.js); the full-JSON paste stays as «modo
15
+ // avanzado», and any pasted JSON is parsed before saving.
16
+ //
17
+ // W-P4: nobody types model ids. With a base URL, «Cargar del provider» asks the
18
+ // orchestrator to proxy GET {base}/models (POST /setup/models — the key never goes to
19
+ // the log) and the ids arrive as a checkbox list; if the network fails the textarea
20
+ // stays the way in. Among the checked ones one model is picked «para sugerencias»
21
+ // (heuristic free → cheap → first, or «sin sugerencias»); the choice is saved with
22
+ // PUT /setup { suggestions_model } and the orchestrator injects it per run as
23
+ // ~/.pi/agent/supi/config.json next to the models.json.
24
+ //
25
+ // Plan bond-app-ajustes-imagen P1: Ajustes is no longer a side panel of the layout but a
26
+ // modal dialog with a section list on the left (Orquestador · Agentes · GitHub · Imagen ·
27
+ // Avanzado), each with a mark when something needs the person. The wizard is the same
28
+ // dialog walked step by step (Agentes → GitHub → Imagen): one interface, not two.
29
+ //
30
+ // Props: { view: "settings", section? } (the dialog, the default), { view: "wizard", step }
31
+ // (first launch), { view: "credential", agent, provider } or { view: "agy-login", agent }
32
+ // for the dialogs each agent row opens on top.
33
+ import { View, div, svg, image } from "gpui-kit";
11
34
  import { v_flex, h_flex, InputState, Input, TextareaState, Textarea } from "gpui-base";
12
35
  import { props, theme, openOverlay, closeOverlay, notify, shared, setShared, exec, run } from "herdr";
13
- import { api } from "./api.js";
14
- import { UI } from "./brand.js";
36
+ import { api, diagnose, health, resetToken, startCommand, apiUrl } from "./api.js";
37
+ import { UI, stateColor } from "./brand.js";
38
+ import { buildPiModelsDoc, validateConfigJson, normalizeBaseUrl, parseModelIds, suggestSuggestionModel, suggestDefaultModel, toggleModelLine } from "./pi-models.js";
15
39
 
16
40
  const RELOAD_KEY = "bond.settings.reload";
17
41
 
42
+ /** DOM-safe id fragment for a provider model id (they carry :, / and spaces). */
43
+ const slug = (s) => String(s).replace(/[^A-Za-z0-9_.-]/g, "_");
44
+
45
+ /**
46
+ * Agents whose credential comes from a login driven in a throwaway container (the
47
+ * orchestrator's /settings/<agent>/login/* API) instead of a pasted config.
48
+ */
49
+ const LOGIN_TEXT = {
50
+ agy: {
51
+ button: "Login OAuth…",
52
+ title: "Login OAuth de agy",
53
+ intro: "Login OAuth para agy en un contenedor efímero. Al autenticar, la sesión se guarda en el orquestador (0600) y se inyecta en cada run.",
54
+ starting: "Iniciando contenedor y agy…",
55
+ startingSub: "Generando la URL de autorización de Google…",
56
+ placeholder: "pega aquí el código de autorización",
57
+ step2: "2. Pega el código de autorización:",
58
+ authenticating: "Verificando código y autenticando con agy…",
59
+ success: (email) => `✓ Autenticado con éxito${email ? `: ${email}` : ""}`,
60
+ successSub: "La sesión ha quedado guardada en el orquestador (0600). El contenedor efímero se ha destruido.",
61
+ },
62
+ claude: {
63
+ button: "Login con Claude…",
64
+ title: "Login con Claude",
65
+ intro: "«claude setup-token» en un contenedor efímero: un token de un año que solo sirve para inferencia con tu suscripción. Se guarda en el orquestador (0600) y se inyecta en cada run. Se revoca en claude.ai/settings/claude-code.",
66
+ starting: "Iniciando contenedor y claude…",
67
+ startingSub: "Generando la URL de autorización de Anthropic…",
68
+ placeholder: "pega aquí el código que muestra la página",
69
+ step2: "2. Autoriza y pega el código que te muestra la página:",
70
+ authenticating: "Verificando código y obteniendo el token…",
71
+ success: () => `✓ Token guardado · caduca el ${new Date(Date.now() + 365 * 86400000).toISOString().slice(0, 10)}`,
72
+ successSub: "El token no sale del orquestador ni se muestra aquí. El contenedor efímero se ha destruido. Para revocarlo: claude.ai/settings/claude-code.",
73
+ },
74
+ codex: {
75
+ button: "Login con ChatGPT…",
76
+ title: "Login con ChatGPT (codex)",
77
+ intro: "codex usa tu cuenta de ChatGPT (también las personales, Plus o Pro). El login corre en un contenedor efímero; la sesión se guarda en el orquestador (0600) y llega a cada run por stdin.",
78
+ starting: "Iniciando contenedor y codex…",
79
+ startingSub: "Generando la URL de autorización de OpenAI…",
80
+ placeholder: "http://127.0.0.1:1455/auth/callback?code=…",
81
+ step2: "2. Al autorizar, el navegador acaba en una página que no carga (127.0.0.1:1455). Es lo esperado: copia la dirección completa de la barra y pégala aquí:",
82
+ authenticating: "Entregando la autorización a codex…",
83
+ success: (email) => `✓ Sesión de ChatGPT guardada${email ? `: ${email}` : ""}`,
84
+ successSub: "La sesión no sale del orquestador ni se muestra aquí. El contenedor efímero se ha destruido. Para cerrarla: ChatGPT → Ajustes → Seguridad → cerrar sesión en todos los dispositivos.",
85
+ },
86
+ copilot: {
87
+ button: "Login con Copilot…",
88
+ title: "Login con Copilot",
89
+ intro: "copilot inicia sesión con tu cuenta de GitHub (necesita Copilot). Ojo: su token lleva permiso «repo» y un agente del run puede leerlo. Se guarda en el orquestador (0600) y llega a cada run por stdin.",
90
+ starting: "Iniciando contenedor y copilot…",
91
+ startingSub: "Pidiendo un código de dispositivo a GitHub…",
92
+ placeholder: "",
93
+ step2: "2. Escribe este código en esa página y autoriza:",
94
+ authenticating: "Esperando a que autorices en GitHub…",
95
+ success: (email) => `✓ Sesión de copilot guardada${email ? `: ${email}` : ""}`,
96
+ successSub: "El token no sale del orquestador ni se muestra aquí. El contenedor efímero se ha destruido. Para revocarlo: github.com/settings/applications (GitHub Copilot CLI).",
97
+ },
98
+ };
99
+
100
+ /** « · caduca el AAAA-MM-DD» for credentials with a known expiry (claude's setup-token). */
101
+ const expiryText = (iso) => (iso ? ` · caduca el ${String(iso).slice(0, 10)}` : "");
102
+
103
+ /** The dialog's sections, in order; the wizard walks WIZARD_STEPS of them. */
104
+ export const SECTIONS = [
105
+ { id: "orchestrator", label: "Orquestador" },
106
+ { id: "agents", label: "Agentes" },
107
+ { id: "github", label: "GitHub" },
108
+ { id: "azure", label: "Azure DevOps" },
109
+ { id: "jira", label: "Jira" },
110
+ { id: "image", label: "Imagen" },
111
+ { id: "advanced", label: "Avanzado" },
112
+ ];
113
+ export const WIZARD_STEPS = ["agents", "github", "image"];
114
+
115
+ /** Agents whose tickets block without a credential (their login is driven here). */
116
+ const BLOCKING = new Set(["agy", "claude"]);
117
+ const DAY = 86400000;
118
+
119
+ /** Program icon of an agent (herdr's icons), as in the Agentes panel; null → initials. */
120
+ const AGENT_ICONS = { pi: true, antigravity: false, claude: false, codex: false, copilot: true };
121
+ const ICON_ALIASES = { agy: "antigravity" };
122
+ function agentIcon(agent) {
123
+ const name = ICON_ALIASES[agent] ?? agent;
124
+ return Object.prototype.hasOwnProperty.call(AGENT_ICONS, name) ? { icon: `icons/${name}.svg`, tint: AGENT_ICONS[name] } : null;
125
+ }
126
+
127
+ /** Debian package names, as the orchestrator and setup.sh accept them. */
128
+ const APT_RE = /^[a-z0-9][a-z0-9+.-]{1,62}$/;
129
+
130
+ /** Selected agents the image does not carry (the image needs a rebuild to run them). */
131
+ export function missingInImage(setup) {
132
+ const img = setup?.image;
133
+ if (!img?.present || !Array.isArray(img.agents)) return [];
134
+ return (setup.agents_selected ?? []).filter((a) => !img.agents.includes(a));
135
+ }
136
+
137
+ /** «⚠ n» / «⟳» marks of each section from the loaded state; null when nothing is pending. */
138
+ export function sectionMarks({ conn, setup, creds, jira, now = Date.now() }) {
139
+ const marks = {};
140
+ if (conn && conn.state !== "ok") marks.orchestrator = { mark: "⚠", tone: "error" };
141
+ if (setup) {
142
+ const byAgent = new Map((creds ?? []).map((c) => [c.agent, c]));
143
+ const pending = (setup.agents_selected ?? []).filter((a) => {
144
+ const st = (setup.agents ?? []).find((x) => x.agent === a);
145
+ const exp = byAgent.get(a)?.expires_at;
146
+ return !st?.configured || (exp && Date.parse(exp) - now < 30 * DAY);
147
+ }).length + missingInImage(setup).length;
148
+ if (!(setup.agents_selected ?? []).length) marks.agents = { mark: "⚠", tone: "error" };
149
+ else if (pending) marks.agents = { mark: `⚠ ${pending}`, tone: "waiting" };
150
+ if (!setup.github?.configured) marks.github = { mark: "⚠", tone: "error" };
151
+ if (!setup.image?.present) marks.image = { mark: "⚠", tone: "error" };
152
+ else if (setup.image.stale || missingInImage(setup).length) marks.image = { mark: "⟳", tone: "waiting" };
153
+ }
154
+ if (jira?.invalid) {
155
+ marks.jira = { mark: "⚠", tone: "error" };
156
+ }
157
+ return marks;
158
+ }
159
+
18
160
  export default class BondSettings extends View {
19
161
  init(_props, cx) {
20
162
  const p = props() ?? {};
21
- this.view = p.view ?? "panel";
163
+ this.view = p.view ?? "settings";
22
164
  this.busy = false;
23
165
  this.error = null;
24
166
  this.handle = cx.focus_handle();
25
167
  if (this.view === "credential") {
168
+ // W-P3: pi gets the provider builder by default (the user rejected making people
169
+ // hand-write models.json); the raw JSON paste stays as «modo avanzado». The other
170
+ // agents only have the paste, as before.
171
+ this.isPi = p.agent === "pi";
172
+ this.advanced = !this.isPi;
173
+ this.piName = InputState.new({ placeholder: "sin espacios; p. ej. lan u ollama", value: p.provider ?? "" });
174
+ this.piUrl = InputState.new({ placeholder: "p. ej. http://192.168.1.20:11434/v1" });
175
+ this.piKey = InputState.new({ placeholder: "vacío si el endpoint no la pide" });
176
+ this.piModels = TextareaState.new({ placeholder: "un id por línea; p. ej. qwen2.5-coder:7b" });
177
+ this.piModels.set_rows(4);
178
+ // W-P4: the model multiselector. The textarea stays the source of truth of the
179
+ // checked ids (criterion 2: only the marked models reach models.json); «Cargar del
180
+ // provider» fills the list through the orchestrator's proxy.
181
+ this.piModelList = null; // ids loaded from the provider
182
+ this.piListBusy = false;
183
+ this.piListError = null; // network problems: aviso, and manual entry stays open
184
+ this.piSuggest = undefined; // undefined = untouched (the heuristic proposes); "" = «sin sugerencias»
185
+ this.piSavedSuggestions = null; // suggestions_model as the orchestrator has it (GET /setup)
186
+ this.piDefault = undefined; // undefined = untouched; "" = «sin modelo por defecto»
187
+ this.piSavedDefault = null; // default_model as the orchestrator has it (GET /setup)
188
+ this.piProviderName = String(p.provider ?? "").trim(); // fallback prefix for full ids
189
+ // W-P5: the list loads by itself when the URL field loses focus (no button), and
190
+ // a small animated line marks the wait.
191
+ this.piLoadedUrl = null; // base URL the current list (or its error) reflects
192
+ this.piSpin = 0;
193
+ this.piUrl.on("blur", (_ev, cx) => {
194
+ const url = normalizeBaseUrl(this.piUrl.value());
195
+ if (!url || url === this.piLoadedUrl || this.piListBusy) return;
196
+ this.loadPiModels(cx);
197
+ });
198
+ cx.timer.every(220, (cx) => {
199
+ if (!this.piListBusy) return;
200
+ this.piSpin = (this.piSpin + 1) % 4;
201
+ cx.notify();
202
+ });
203
+ cx.spawn(async (cx) => {
204
+ try {
205
+ const s = await api("/setup");
206
+ if (typeof s?.suggestions_model === "string") this.piSavedSuggestions = s.suggestions_model;
207
+ if (typeof s?.default_model === "string") this.piSavedDefault = s.default_model;
208
+ if (Array.isArray(s?.models) && s.models.length > 0 && !this.piModels.value().trim()) {
209
+ let currentProv = this.piName.value().trim() || this.piProviderName;
210
+ if (!currentProv) {
211
+ const firstSlash = s.models[0].indexOf("/");
212
+ if (firstSlash > 0) {
213
+ currentProv = s.models[0].slice(0, firstSlash);
214
+ this.piName.set_value(currentProv);
215
+ this.piProviderName = currentProv;
216
+ }
217
+ }
218
+ const bareModels = s.models.map((m) => {
219
+ if (currentProv && m.startsWith(`${currentProv}/`)) {
220
+ return m.slice(currentProv.length + 1);
221
+ }
222
+ const slash = m.indexOf("/");
223
+ return slash >= 0 ? m.slice(slash + 1) : m;
224
+ });
225
+ this.piModels.set_value(bareModels.join("\n"));
226
+ }
227
+ cx.notify();
228
+ } catch {
229
+ /* orchestrator unreachable: the form works without the saved choice */
230
+ }
231
+ });
26
232
  this.provider = InputState.new({ placeholder: "proveedor (opcional)", value: p.provider ?? "" });
27
233
  this.config = TextareaState.new({ placeholder: "config JSON del agente: sustituye a la anterior" });
28
234
  this.config.set_rows(8);
29
- this.config.focus();
235
+ if (this.advanced) this.config.focus();
236
+ else this.piName.focus();
237
+ return;
238
+ }
239
+ if (this.view === "agy-login") {
240
+ this.loginAgent = LOGIN_TEXT[p.agent] ? p.agent : "agy";
241
+ this.agyUserCode = null;
242
+ this.agyDevice = false;
243
+ this.agyAuto = false; // codex: the orchestrator catches the browser's return
244
+ this.agyShowPaste = false; // the paste fallback, opened on demand
245
+ this.agyStatus = "starting";
246
+ this.agyUrl = null;
247
+ this.agyEmail = null;
248
+ this.agyError = null;
249
+ this.agyCode = InputState.new({ placeholder: LOGIN_TEXT[this.loginAgent].placeholder });
250
+ this.agyBusy = false;
251
+ this.startAgyLogin(cx);
252
+ cx.timer.every(800, (cx) => {
253
+ if (this.agyStatus === "success" || this.agyStatus === "error") return;
254
+ this.pollAgyStatus(cx);
255
+ });
30
256
  return;
31
257
  }
32
- if (this.view === "rebuild") return;
33
258
 
34
259
  this.creds = [];
260
+ this.toolSelection = null; // the tool groups while their PUT /setup is in flight
261
+ // Plan bond-app-azure-jira P1: Azure DevOps (Azure Repos). The PAT field never shows the
262
+ // stored one; an empty PAT with a stored credential only changes the switch.
263
+ this.azureDevOps = null;
264
+ this.azureOrg = InputState.new({ placeholder: "https://dev.azure.com/tu-organización" });
265
+ this.azurePat = InputState.new({ placeholder: "PAT con Code: read & write (y Pull requests si tus skills lo usan)" });
266
+ this.azurePat.set_masked(true);
267
+ this.azureAgents = true;
268
+ this.azureBusy = false;
269
+ this.azureOrgLoaded = false;
270
+ this.rbStatus = null; // GET /system/rebuild: { running, step, total, detail, ok, error }
271
+ this.aptInput = InputState.new({ placeholder: "p. ej. graphviz tmux (separados por espacios o comas)" });
272
+ this.aptLoaded = null; // what the field was filled with, so polling never overwrites typing
35
273
  this.loadError = null;
36
274
  this.github = null; // what the orchestrator has stored: { configured, login }
37
275
  this.ghLocal = null; // the host's gh session: { installed, login, ok }
38
276
  this.ghBusy = false;
277
+ this.jira = null;
278
+ this.favorites = null; // ★ repos of the new-ticket dialog (GET /repos/favorites)
279
+ this.favBusy = false;
280
+ this.jiraSite = InputState.new({ placeholder: "https://tu-organizacion.atlassian.net" });
281
+ this.jiraEmail = InputState.new({ placeholder: "tu-email@empresa.com" });
282
+ this.jiraToken = InputState.new({ placeholder: "API token de Jira Cloud (atlassian.com)" });
283
+ this.jiraAgentsEnabled = true;
284
+ this.jiraBusy = false;
285
+ this.jiraError = null;
286
+ this.setup = null; // W-P2 «Configuración»: el agregado de GET /setup
287
+ this.conn = null; // «Orquestador»: { state, detail } de diagnose()
288
+ this.connBusy = null; // "reconnect" | "restart" | "start" mientras dura la acción
289
+ // Every piece of progress lives in the orchestrator (selection, credentials, gh), so
290
+ // Esc never loses anything: the dialog reopens showing the real state (D-W2).
291
+ this.wizSelection = null; // the selection while its PUT /setup is in flight
292
+ this.rbBusy = false;
293
+ // Wizard: steps 1..3 over WIZARD_STEPS; settings: the asked section, else the first
294
+ // one with something pending once the state arrives (null until then).
295
+ this.step = Math.min(WIZARD_STEPS.length, Math.max(1, Number(p.step) || 1));
296
+ this.section = SECTIONS.some((x) => x.id === p.section) ? p.section : null;
39
297
  this.seenReload = shared(RELOAD_KEY) ?? null;
40
298
  this.load(cx);
41
299
  cx.timer.every(1000, (cx) => {
300
+ if (this.rbBusy || this.rbStatus?.running) this.loadRebuildStatus(cx);
42
301
  const marker = shared(RELOAD_KEY) ?? null;
43
302
  if (marker !== this.seenReload) {
44
303
  this.seenReload = marker;
45
304
  this.load(cx);
46
305
  }
47
306
  });
48
- cx.timer.every(15000, (cx) => this.load(cx));
307
+ cx.timer.every(5000, (cx) => this.load(cx));
49
308
  }
50
309
 
310
+ // Re-reads everything the dialog shows (the aggregate, the credential dates, gh), so a
311
+ // credential saved in its own dialog on top shows up here without reopening.
51
312
  load(cx) {
52
313
  cx.spawn(async (cx) => {
314
+ if (!this.connBusy) this.conn = await diagnose();
53
315
  try {
54
316
  this.creds = (await api("/settings/credentials")) ?? [];
55
317
  this.github = (await api("/settings/github")) ?? { configured: false };
318
+ this.azureDevOps = (await api("/settings/azure-devops")) ?? { configured: false };
319
+ this.jira = (await api("/settings/jira")) ?? { configured: false };
320
+ if (!this.favBusy) this.favorites = (await api("/repos/favorites"))?.favorites ?? [];
321
+ if (this.jira?.configured) {
322
+ if (!this.jiraSite.value()) this.jiraSite.set_value(this.jira.site ?? "");
323
+ if (!this.jiraEmail.value()) this.jiraEmail.set_value(this.jira.email ?? "");
324
+ this.jiraAgentsEnabled = this.jira.agents_enabled !== false;
325
+ }
326
+ if (!this.wizSelection && !this.toolSelection) this.setup = (await api("/setup")) ?? null;
327
+ if (this.setup && this.aptLoaded === null) {
328
+ this.aptLoaded = (this.setup.apt_extra ?? []).join(" ");
329
+ this.aptInput.set_value(this.aptLoaded);
330
+ }
56
331
  this.loadError = null;
57
332
  } catch (e) {
58
333
  this.loadError = String(e?.message ?? e);
59
334
  }
60
335
  this.ghLocal = await this.ghSession();
336
+ try {
337
+ this.rbStatus = (await api("/system/rebuild")) ?? null;
338
+ } catch {}
339
+ if (!this.section) {
340
+ const marks = sectionMarks({ conn: this.conn, setup: this.setup, creds: this.creds });
341
+ this.section = ["orchestrator", "agents", "github", "image"].find((id) => marks[id]) ?? "agents";
342
+ }
61
343
  cx.notify();
62
344
  });
63
345
  }
@@ -115,40 +397,42 @@ export default class BondSettings extends View {
115
397
  run("tab.new", { name: "gh auth login", argv: ["gh", "auth", "login", "--web"] });
116
398
  }
117
399
 
118
- githubSection() {
119
- const t = theme();
120
- const gh = this.github;
121
- const local = this.ghLocal;
122
- const stored = gh?.configured
123
- ? `credencial guardada${gh.login ? ` · ${gh.login}` : ""}`
124
- : "sin credencial: lanzar un run no funcionará";
125
- const localLine = !local
126
- ? "comprobando gh…"
127
- : !local.installed
128
- ? "gh no está instalado en este equipo"
129
- : local.ok
130
- ? `sesión de gh: ${local.login ?? "activa"}`
131
- : "gh no tiene sesión";
132
- return v_flex().gap(4)
133
- .child(div().pt(8).text_size(11).font_semibold().text_color(t.muted).child("GITHUB (D20)"))
134
- .child(div().text_size(11.5).text_color(gh?.configured ? t.working : t.blocked).child(stored))
135
- .child(div().text_size(11).text_color(t.dim).child(localLine))
136
- .child(h_flex().gap(6).flex_wrap()
137
- .when(Boolean(local?.ok), (el) => el.child(this.button("gh-use", this.ghBusy ? "Guardando…" : "Usar mi sesión de gh", true, (cx) => this.useGhSession(cx))))
138
- .when(Boolean(local?.installed) && !local?.ok, (el) => el.child(this.button("gh-login", "Iniciar sesión", true, () => this.ghLogin())))
139
- .when(Boolean(gh?.configured), (el) => el.child(this.button("gh-remove", "Quitar", false, (cx) => this.removeGithub(cx)))))
140
- .child(div().text_size(11).text_color(t.dim)
141
- .child("El token sale de `gh auth token` y lo guarda el orquestador; llega a cada run por stdin, nunca a la imagen."));
142
- }
143
-
144
400
  saveCredential(cx) {
145
401
  if (this.busy) return;
146
402
  const p = props();
147
- const configJson = this.config.value().trim();
148
- if (!configJson) {
149
- this.error = "La config no puede estar vacía.";
150
- cx.notify();
151
- return;
403
+ let configJson;
404
+ let provider;
405
+ if (this.isPi && !this.advanced) {
406
+ // W-P3: the builder produces the very document PUT /settings/credentials/pi
407
+ // already accepts; nothing goes to the network here — an unreachable LAN URL is
408
+ // saved as entered.
409
+ const built = buildPiModelsDoc({
410
+ name: this.piName.value(),
411
+ baseUrl: this.piUrl.value(),
412
+ apiKey: this.piKey.value(),
413
+ modelsText: this.piModels.value(),
414
+ });
415
+ if (built.error) {
416
+ this.error = built.error;
417
+ cx.notify();
418
+ return;
419
+ }
420
+ configJson = built.configJson;
421
+ provider = built.name;
422
+ } else {
423
+ configJson = this.config.value().trim();
424
+ if (!configJson) {
425
+ this.error = "La config no puede estar vacía.";
426
+ cx.notify();
427
+ return;
428
+ }
429
+ const badJson = validateConfigJson(configJson); // criterion 4: invalid JSON never leaves the dialog
430
+ if (badJson) {
431
+ this.error = badJson;
432
+ cx.notify();
433
+ return;
434
+ }
435
+ provider = this.provider.value().trim() || undefined;
152
436
  }
153
437
  this.busy = true;
154
438
  this.error = null;
@@ -157,8 +441,34 @@ export default class BondSettings extends View {
157
441
  try {
158
442
  await api(`/settings/credentials/${encodeURIComponent(p.agent)}`, {
159
443
  method: "PUT",
160
- body: { config_json: configJson, provider: this.provider.value().trim() || undefined },
444
+ body: { config_json: configJson, provider },
161
445
  });
446
+ // W-P4: the suggestions model travels in PUT /setup next to the credential. It
447
+ // is only sent when there is something to say (checked models or an explicit
448
+ // pick), so «Renovar» without touching the selector never erases the stored one.
449
+ if (this.isPi && !this.advanced && (this.checkedModels().length > 0 || this.piSuggest !== undefined)) {
450
+ const cur = this.currentSuggest();
451
+ try {
452
+ await api("/setup", { method: "PUT", body: { suggestions_model: cur ? this.piFullId(cur) : null } });
453
+ } catch (e) {
454
+ notify({ title: "Credencial guardada, pero no el modelo de sugerencias", body: String(e?.message ?? e), level: "warning" });
455
+ }
456
+ }
457
+ if (this.isPi && !this.advanced && (this.checkedModels().length > 0 || this.piDefault !== undefined)) {
458
+ const curDef = this.currentDefault();
459
+ const models = this.checkedModels().map((id) => this.piFullId(id));
460
+ try {
461
+ await api("/setup", {
462
+ method: "PUT",
463
+ body: {
464
+ default_model: curDef ? this.piFullId(curDef) : null,
465
+ models,
466
+ },
467
+ });
468
+ } catch (e) {
469
+ notify({ title: "Credencial guardada, pero no el modelo por defecto", body: String(e?.message ?? e), level: "warning" });
470
+ }
471
+ }
162
472
  notify({ title: `Credencial de ${p.agent} guardada`, level: "success" });
163
473
  setShared(RELOAD_KEY, Date.now());
164
474
  closeOverlay(p.overlay);
@@ -170,17 +480,219 @@ export default class BondSettings extends View {
170
480
  });
171
481
  }
172
482
 
173
- rebuild(cx) {
483
+ // ---- W-P4: model multiselector and suggestions pick (pi dialog) -----------------------
484
+
485
+ /** The checked model ids: the textarea lines, same list the builder will serialize. */
486
+ checkedModels() {
487
+ return parseModelIds(this.piModels.value());
488
+ }
489
+
490
+ // W-P5: pi habilita modelos como `<provider>/<id>` y supi espera ese id completo;
491
+ // el diálogo trabaja con ids pelados y aquí se prefija con el nombre del provider.
492
+ piFullId(id) {
493
+ const name = this.piName.value().trim() || this.piProviderName || "pi";
494
+ return `${name}/${id}`;
495
+ }
496
+
497
+ /** Current suggestions pick: the explicit one (only while its model stays checked),
498
+ * else the saved one if still checked, else the heuristic proposal
499
+ * (free → cheap → first) over the checked models. */
500
+ currentSuggest() {
501
+ const checked = this.checkedModels();
502
+ if (this.piSuggest !== undefined) {
503
+ if (!this.piSuggest) return null; // «sin sugerencias» explícito
504
+ // W-P5: la elección explícita manda sobre los marcados; si su modelo se desmarcó,
505
+ // se cae al guardado/heurística en vez de quedarse anclado en el primero.
506
+ if (checked.includes(this.piSuggest)) return this.piSuggest;
507
+ }
508
+ if (this.piSavedSuggestions) {
509
+ const saved = checked.find((id) => this.piFullId(id) === this.piSavedSuggestions || id === this.piSavedSuggestions);
510
+ if (saved) return saved;
511
+ }
512
+ return suggestSuggestionModel(checked);
513
+ }
514
+
515
+ /** D-M1: current default working model for pi: explicit choice if still checked,
516
+ * else saved choice if still checked, else heuristic (tools first, else first). */
517
+ currentDefault() {
518
+ const checked = this.checkedModels();
519
+ if (this.piDefault !== undefined) {
520
+ if (!this.piDefault) return null; // «sin modelo por defecto» explícito
521
+ if (checked.includes(this.piDefault)) return this.piDefault;
522
+ }
523
+ if (this.piSavedDefault) {
524
+ const saved = checked.find((id) => this.piFullId(id) === this.piSavedDefault || id === this.piSavedDefault);
525
+ if (saved) return saved;
526
+ }
527
+ return suggestDefaultModel(checked);
528
+ }
529
+
530
+ // Ask the orchestrator to proxy GET {base}/models (POST /setup/models). The provider
531
+ // is never reached from here directly, and a failure is only an aviso: the textarea
532
+ // stays the manual way in (criterion 1).
533
+ loadPiModels(cx) {
534
+ if (this.piListBusy) return;
535
+ const url = normalizeBaseUrl(this.piUrl.value());
536
+ if (!url) {
537
+ this.piListError = "Pon antes una base URL http(s) válida.";
538
+ cx.notify();
539
+ return;
540
+ }
541
+ this.piListBusy = true;
542
+ this.piListError = null;
543
+ this.piUrl.set_loading(true);
544
+ cx.notify();
545
+ cx.spawn(async (cx) => {
546
+ try {
547
+ const body = { base_url: url };
548
+ const key = this.piKey.value().trim();
549
+ if (key) body.api_key = key; // only in this request's body; never logged
550
+ const res = await api("/setup/models", { method: "POST", body });
551
+ this.piModelList = Array.isArray(res?.models) ? res.models : [];
552
+ if (this.piModelList.length === 0) this.piListError = "El provider no devolvió modelos: escríbelos a mano.";
553
+ } catch (e) {
554
+ this.piListError = `No se pudieron listar los modelos (${String(e?.message ?? e)}). Escribe los ids a mano, uno por línea:`;
555
+ this.piModelList = null;
556
+ } finally {
557
+ this.piLoadedUrl = url; // same URL blurring again must not nag-reload
558
+ this.piListBusy = false;
559
+ this.piUrl.set_loading(false);
560
+ cx.notify();
561
+ }
562
+ });
563
+ }
564
+
565
+ // A checkbox adds or removes the id's line in the textarea (source of truth).
566
+ togglePiModel(cx, id) {
567
+ this.piModels.set_value(toggleModelLine(this.piModels.value(), id));
568
+ cx.notify();
569
+ }
570
+
571
+ setPiSuggest(cx, id) {
572
+ this.piSuggest = id ?? "";
573
+ cx.notify();
574
+ // W-P5: la elección se persiste al hacer clic (no solo al Guardar), así al reabrir
575
+ // el diálogo sale marcada la misma y no la primera.
576
+ cx.spawn(async () => {
577
+ const cur = this.currentSuggest();
578
+ try {
579
+ await api("/setup", { method: "PUT", body: { suggestions_model: cur ? this.piFullId(cur) : null } });
580
+ } catch {
581
+ /* orquestador no alcanza: Guardar lo reintenta */
582
+ }
583
+ });
584
+ }
585
+
586
+ setPiDefault(cx, id) {
587
+ this.piDefault = id ?? "";
588
+ cx.notify();
589
+ cx.spawn(async () => {
590
+ const cur = this.currentDefault();
591
+ const models = this.checkedModels().map((m) => this.piFullId(m));
592
+ try {
593
+ await api("/setup", {
594
+ method: "PUT",
595
+ body: {
596
+ default_model: cur ? this.piFullId(cur) : null,
597
+ models,
598
+ },
599
+ });
600
+ } catch {
601
+ /* orquestador no alcanza: Guardar lo reintenta */
602
+ }
603
+ });
604
+ }
605
+
606
+ // ---- W-P2: wizard (D-W1) -----------------------------------------------------------
607
+
608
+ // What the orchestrator is missing; empty when complete. Used by the panel section and
609
+ // by step 4 so the person sees what «Finalizar» would be leaving pending.
610
+ pendingParts(s) {
611
+ if (!s) return ["sin datos del orquestador"];
612
+ const parts = [];
613
+ if (!s.agents_selected.length) parts.push("sin agentes elegidos");
614
+ if (!(s.agents ?? []).some((a) => a.configured)) parts.push("ningún agente con credencial");
615
+ if (!s.github?.configured) parts.push("GitHub");
616
+ if (!s.image?.present) parts.push("imagen del runner");
617
+ return parts;
618
+ }
619
+
620
+ selectedAgents() {
621
+ return this.wizSelection ?? (this.setup?.agents_selected ?? []);
622
+ }
623
+
624
+ anyCredential() {
625
+ return (this.setup?.agents ?? []).some((a) => a.configured);
626
+ }
627
+
628
+ toggleAgent(cx, name) {
629
+ const sel = [...this.selectedAgents()];
630
+ const i = sel.indexOf(name);
631
+ if (i >= 0) sel.splice(i, 1);
632
+ else sel.push(name);
633
+ this.wizSelection = sel;
634
+ this.error = null;
635
+ cx.notify();
636
+ // Criterio 2 del plan W-P2: cada clic guarda (PUT /setup), no esperar a finalizar;
637
+ // cerrar con Esc nunca pierde la selección.
638
+ if (!this.setup || this.busy) return;
639
+ this.busy = true;
640
+ cx.notify();
641
+ cx.spawn(async (cx) => {
642
+ try {
643
+ this.setup = await api("/setup", { method: "PUT", body: { agents_selected: sel } });
644
+ this.wizSelection = null;
645
+ } catch (e) {
646
+ this.error = String(e?.message ?? e);
647
+ }
648
+ this.busy = false;
649
+ cx.notify();
650
+ });
651
+ }
652
+
653
+ wizBack(cx) {
654
+ this.step = Math.max(1, this.step - 1);
655
+ this.error = null;
656
+ cx.notify();
657
+ }
658
+
659
+ /** Agentes needs a selection and one credential; GitHub and Imagen can stay pending. */
660
+ wizNext(cx) {
661
+ if (this.busy || !this.setup) return;
662
+ if (WIZARD_STEPS[this.step - 1] === "agents") {
663
+ if (!this.selectedAgents().length) {
664
+ this.error = "Añade al menos un agente para continuar.";
665
+ cx.notify();
666
+ return;
667
+ }
668
+ if (!this.anyCredential()) {
669
+ this.error = "Conecta al menos un agente: sin credencial ningún ticket puede arrancar.";
670
+ cx.notify();
671
+ return;
672
+ }
673
+ }
674
+ this.step = Math.min(WIZARD_STEPS.length, this.step + 1);
675
+ this.error = null;
676
+ cx.notify();
677
+ }
678
+
679
+ wizFinish(cx) {
174
680
  if (this.busy) return;
175
- const p = props();
681
+ if (!this.anyCredential()) {
682
+ this.error = "Finalizar exige al menos un agente con credencial.";
683
+ cx.notify();
684
+ return;
685
+ }
176
686
  this.busy = true;
177
687
  this.error = null;
178
688
  cx.notify();
179
689
  cx.spawn(async (cx) => {
180
690
  try {
181
- const res = await api("/system/rebuild", { method: "POST", body: {} });
182
- notify({ title: "Imagen reconstruida", body: String(res?.image ?? ""), level: "success" });
183
- closeOverlay(p.overlay);
691
+ // setup_done only via this explicit write (W-P1); the wizard never bothers again.
692
+ this.setup = await api("/setup", { method: "PUT", body: { setup_done: true } });
693
+ notify({ title: "Configuración guardada", body: "Puedes cambiarla cuando quieras en Ajustes.", level: "success" });
694
+ setShared(RELOAD_KEY, Date.now());
695
+ closeOverlay(props().overlay);
184
696
  } catch (e) {
185
697
  this.error = String(e?.message ?? e);
186
698
  this.busy = false;
@@ -189,9 +701,682 @@ export default class BondSettings extends View {
189
701
  });
190
702
  }
191
703
 
704
+ /** Rebuilds the runner image with the chosen agents (the orchestrator falls back to the
705
+ * same selection when the list is empty). Credentials are never touched. */
706
+ rebuildImage(cx) {
707
+ if (this.rbBusy) return;
708
+ const agents = this.selectedAgents();
709
+ this.rbBusy = true;
710
+ this.rbStatus = { running: true, step: 0, total: 0, detail: "Preparando el build…", started_at: new Date().toISOString() };
711
+ this.error = null;
712
+ cx.notify();
713
+ cx.spawn(async (cx) => {
714
+ try {
715
+ const res = await api("/system/rebuild", { method: "POST", body: agents.length ? { agents } : {} });
716
+ notify({ title: "Imagen reconstruida", body: String(res?.image ?? ""), level: "success" });
717
+ } catch (e) {
718
+ this.error = String(e?.message ?? e);
719
+ }
720
+ this.rbBusy = false;
721
+ try {
722
+ this.setup = (await api("/setup")) ?? this.setup;
723
+ this.rbStatus = (await api("/system/rebuild")) ?? this.rbStatus;
724
+ } catch {}
725
+ cx.notify();
726
+ });
727
+ }
728
+
729
+ /** Where the image build is (GET /system/rebuild): step, total and what it is doing. */
730
+ loadRebuildStatus(cx) {
731
+ cx.spawn(async (cx) => {
732
+ try {
733
+ this.rbStatus = (await api("/system/rebuild")) ?? null;
734
+ cx.notify();
735
+ } catch {}
736
+ });
737
+ }
738
+
739
+ /** The progress bar of a build in flight: «Paso 12 de 27 · instalando…». */
740
+ rebuildProgress() {
741
+ const t = theme();
742
+ const st = this.rbStatus ?? {};
743
+ const pct = st.total ? Math.max(2, Math.min(100, Math.round((st.step / st.total) * 100))) : 2;
744
+ const since = st.started_at ? Math.max(0, Math.round((Date.now() - Date.parse(st.started_at)) / 1000)) : 0;
745
+ const clock = `${Math.floor(since / 60)}:${String(since % 60).padStart(2, "0")}`;
746
+ return v_flex().id("image-progress").gap(6).p(10).rounded(UI.radius).border_1().border_color(t.border).bg(t.background)
747
+ .child(h_flex().gap(8).items_center()
748
+ .child(div().flex_1().text_size(UI.text.small).font_semibold().text_color(t.foreground)
749
+ .child(st.total ? `Paso ${st.step} de ${st.total}` : "Empezando…"))
750
+ .child(div().text_size(UI.text.small).text_color(t.dim).child(clock)))
751
+ .child(div().w_full().h(6).rounded(3).bg(t.raised).overflow_hidden()
752
+ .child(div().h_full().rounded(3).bg(t.accent).w(`${pct}%`)))
753
+ .child(div().id("image-progress-detail").text_size(UI.text.small).text_color(t.muted).truncate().child(st.detail || "…"));
754
+ }
755
+
756
+ /** Opens the credential or login dialog of an agent on top of this one. */
757
+ openCredential(agent) {
758
+ const c = (this.creds ?? []).find((x) => x.agent === agent);
759
+ openOverlay({
760
+ mod: "bond-settings", kind: "dialog", modal: true, width: 480, height: 0.92,
761
+ props: LOGIN_TEXT[agent] ? { view: "agy-login", agent } : { view: "credential", agent, provider: c?.provider ?? "" },
762
+ });
763
+ }
764
+
765
+ // ---- Plan bond-app-ajustes-imagen P1: the dialog ------------------------------------
766
+
767
+ tone(t, name) {
768
+ if (name === "ok") return stateColor(t, "running");
769
+ if (name === "waiting") return stateColor(t, "waiting");
770
+ if (name === "error") return t.blocked;
771
+ return t.dim;
772
+ }
773
+
774
+ /** A small «● text» status line. */
775
+ status(id, text, color) {
776
+ return h_flex().id(id).gap(6).items_center()
777
+ .child(div().w(7).h(7).rounded(4).bg(color))
778
+ .child(div().text_size(UI.text.body).font_semibold().text_color(color).child(text));
779
+ }
780
+
781
+ sectionTitle(title, subtitle) {
782
+ const t = theme();
783
+ return v_flex().gap(2)
784
+ .child(div().text_size(UI.text.title + 3).font_family(UI.fontSans).font_semibold().text_color(t.foreground).child(title))
785
+ .when(Boolean(subtitle), (el) => el.child(div().text_size(UI.text.small).font_family(UI.fontSans).text_color(t.muted).child(subtitle)));
786
+ }
787
+
788
+ note(text) {
789
+ return div().text_size(UI.text.small).font_family(UI.fontSans).text_color(theme().dim).child(text);
790
+ }
791
+
792
+ tipButton(id, text, primary, tip, action) {
793
+ return this.button(id, text, primary, action).tooltip(tip);
794
+ }
795
+
796
+ agentBadge(agent, size = 22) {
797
+ const t = theme();
798
+ const pic = agentIcon(agent);
799
+ const box = div().w(size).h(size).flex_none().rounded(6).bg(t.raised).border_1().border_color(t.border)
800
+ .flex().items_center().justify_center();
801
+ if (!pic) return box.child(div().text_size(UI.text.tiny).font_semibold().text_color(t.muted).child(agent.slice(0, 2)));
802
+ const s = Math.round(size * 0.62);
803
+ return box.child(pic.tint ? svg(pic.icon).size(s).text_color(t.foreground) : image(pic.icon).w(s).h(s));
804
+ }
805
+
806
+ orchestratorSection() {
807
+ const t = theme();
808
+ const c = this.conn;
809
+ const labels = { ok: "Conectado", down: "No responde", "no-token": "Sin fichero de token", "bad-token": "El token no es de este orquestador", error: "Error al hablar con la API" };
810
+ const busy = { reconnect: "Reconectando…", restart: "Reiniciando…", start: "Arrancando…" }[this.connBusy];
811
+ const text = busy ?? (!c ? "Comprobando…" : labels[c.state] ?? c.state);
812
+ const color = busy || !c ? t.dim : this.tone(t, c.state === "ok" ? "ok" : "error");
813
+ const canRestart = c?.state === "ok" || c?.state === "error";
814
+ const needsStart = c?.state === "down" || c?.state === "no-token";
815
+ return v_flex().gap(12)
816
+ .child(this.sectionTitle("Orquestador", "El proceso local que lanza los runs y guarda credenciales."))
817
+ .child(v_flex().gap(4)
818
+ .child(this.status("conn-status", text, color))
819
+ .child(div().text_size(UI.text.small).text_color(t.muted).child(apiUrl())))
820
+ .when(Boolean(c?.detail) && c?.state !== "ok" && !busy, (el) => el.child(this.note(c.detail)))
821
+ .when(c?.state === "bad-token", (el) => el.child(this.note("Reinstala apuntando a su token: npm run app:install -- --token-file <data-dir>/token")))
822
+ .child(h_flex().gap(6)
823
+ .when(needsStart, (el) => el.child(this.button("conn-start", "Arrancar", true, (cx) => this.startOrchestrator(cx))))
824
+ .child(this.tipButton("conn-reconnect", "Reconectar", false, "Vuelve a leer el token y comprueba la conexión", (cx) => this.reconnect(cx)))
825
+ .when(canRestart, (el) => el.child(this.tipButton("conn-restart", "Reiniciar", false,
826
+ "Para y arranca el orquestador con el mismo comando. Los runs con contenedor vivo siguen y se reconcilian al volver.",
827
+ (cx) => this.restartOrchestrator(cx)))));
828
+ }
829
+
830
+ /** One row of the Agentes section: icon, name, credential state and one action. */
831
+ agentRow(name) {
832
+ const t = theme();
833
+ const s = this.setup;
834
+ const configured = Boolean((s?.agents ?? []).find((a) => a.agent === name)?.configured);
835
+ const c = (this.creds ?? []).find((x) => x.agent === name);
836
+ const exp = c?.expires_at ? Date.parse(c.expires_at) : null;
837
+ const expired = exp !== null && exp < Date.now();
838
+ const soon = exp !== null && !expired && exp - Date.now() < 30 * DAY;
839
+ const inImage = !missingInImage(s).includes(name);
840
+ let text;
841
+ let color;
842
+ if (!configured) {
843
+ text = BLOCKING.has(name) ? "sin credencial · sus tickets se bloquean" : "sin credencial";
844
+ color = this.tone(t, BLOCKING.has(name) ? "error" : "waiting");
845
+ } else if (expired) {
846
+ text = `caducó el ${String(c.expires_at).slice(0, 10)}`;
847
+ color = this.tone(t, "error");
848
+ } else {
849
+ text = (c?.email || c?.provider || "credencial guardada") + expiryText(c?.expires_at);
850
+ color = soon ? this.tone(t, "waiting") : t.muted;
851
+ }
852
+ const action = name === "pi" ? (configured ? "Configurar" : "Conectar") : (configured ? "Renovar" : "Conectar");
853
+ return h_flex().id(`agent-row-${name}`).gap(10).items_center().px(10).py(8).rounded(UI.radius)
854
+ .border_1().border_color(t.border).bg(t.background)
855
+ .child(this.agentBadge(name))
856
+ .child(v_flex().flex_1().min_w(0).gap(1)
857
+ .child(div().text_size(UI.text.body).font_semibold().text_color(t.foreground).child(name))
858
+ .child(div().text_size(UI.text.small).text_color(color).truncate().child(text))
859
+ .when(!inImage, (el) => el.child(div().id(`agent-noimage-${name}`).text_size(UI.text.small).text_color(this.tone(t, "waiting"))
860
+ .cursor_pointer().on_click((_e, cx) => { this.goTo(cx, "image"); })
861
+ .child("⟳ no está en la imagen: reconstrúyela en Imagen"))))
862
+ .child(this.button(`agent-cred-${name}`, action, !configured || expired, () => this.openCredential(name))
863
+ .tooltip(name === "pi"
864
+ ? "Abre el formulario «modelo local / OpenAI-compatible» (nombre, URL, clave opcional); los modelos se cargan del provider."
865
+ : LOGIN_TEXT[name] ? `${LOGIN_TEXT[name].title} en un contenedor efímero` : "Pega la config del agente tras iniciar sesión"))
866
+ .child(div().id(`agent-remove-${name}`).w(22).h(22).rounded(UI.radius).flex().items_center().justify_center()
867
+ .text_color(t.dim).cursor_pointer().hover((st) => st.bg(t.hover).text_color(t.foreground))
868
+ .tooltip("Quitar de tus agentes (la credencial se conserva)")
869
+ .on_click((_e, cx) => this.toggleAgent(cx, name)).child("✕"));
870
+ }
871
+
872
+ agentsSection() {
873
+ const t = theme();
874
+ const s = this.setup;
875
+ if (!s) return v_flex().gap(12).child(this.sectionTitle("Agentes")).child(this.note("Cargando…"));
876
+ const sel = this.selectedAgents();
877
+ const others = (s.agents ?? []).map((a) => a.agent).filter((a) => !sel.includes(a));
878
+ return v_flex().gap(12)
879
+ .child(this.sectionTitle("Agentes", "Los agentes que pueden trabajar en tus tickets."))
880
+ .when(sel.length === 0, (el) => el.child(this.note("Aún no has elegido ninguno: añade al menos uno.")))
881
+ .child(v_flex().gap(6).children(sel.map((name) => this.agentRow(name))))
882
+ .when(others.length > 0, (el) => el.child(v_flex().gap(6)
883
+ .child(div().text_size(UI.text.small).font_semibold().text_color(t.muted).child("Añadir agente"))
884
+ .child(h_flex().gap(6).flex_wrap().children(others.map((name) =>
885
+ h_flex().id(`agent-add-${name}`).gap(6).items_center().h(UI.button).pl(4).pr(10).rounded(UI.radius)
886
+ .border_1().border_color(t.border).bg(t.raised).cursor_pointer()
887
+ .hover((st) => st.bg(t.hover))
888
+ .on_click((_e, cx) => this.toggleAgent(cx, name))
889
+ .child(this.agentBadge(name, 18))
890
+ .child(div().text_size(UI.text.small).text_color(t.foreground).child(`+ ${name}`)))))))
891
+ .child(this.note("Las credenciales se guardan en el orquestador y llegan a cada run por stdin; nunca van en la imagen."));
892
+ }
893
+
894
+ githubSection() {
895
+ const t = theme();
896
+ const gh = this.github;
897
+ const local = this.ghLocal;
898
+ const stored = Boolean(gh?.configured);
899
+ const localLine = !local
900
+ ? "Comprobando gh en este equipo…"
901
+ : !local.installed
902
+ ? "gh no está instalado en este equipo."
903
+ : local.ok
904
+ ? `gh en este equipo: sesión de ${local.login ?? "GitHub"}.`
905
+ : "gh en este equipo no tiene sesión.";
906
+ const canUse = Boolean(local?.ok) && (!stored || (local.login && local.login !== gh?.login));
907
+ return v_flex().gap(12)
908
+ .child(this.sectionTitle("GitHub", "Para clonar los repos de los tickets, crear ramas y abrir PR."))
909
+ .child(v_flex().gap(4)
910
+ .child(this.status("gh-status", stored ? `Conectado${gh.login ? ` como ${gh.login}` : ""}` : "Sin conectar",
911
+ this.tone(t, stored ? "ok" : "error")))
912
+ .when(!stored, (el) => el.child(this.note("Sin GitHub no se pueden lanzar tickets.")))
913
+ .child(this.note(localLine)))
914
+ .child(h_flex().gap(6).flex_wrap()
915
+ .when(canUse, (el) => el.child(this.tipButton("gh-use", this.ghBusy ? "Guardando…" : `Usar la sesión de gh${local?.login ? ` (${local.login})` : ""}`, true,
916
+ "Lee `gh auth token` y lo guarda el orquestador; llega a cada run por stdin, nunca a la imagen.", (cx) => this.useGhSession(cx))))
917
+ .when(Boolean(local?.installed) && !local?.ok, (el) => el.child(this.button("gh-login", "Iniciar sesión en gh", !stored, () => this.ghLogin())))
918
+ .when(stored, (el) => el.child(this.button("gh-remove", "Quitar", false, (cx) => this.removeGithub(cx)))));
919
+ }
920
+
921
+ // ---- Plan bond-app-azure-jira P1: Azure DevOps -----------------------------------------
922
+
923
+ saveAzure(cx) {
924
+ if (this.azureBusy) return;
925
+ const stored = Boolean(this.azureDevOps?.configured);
926
+ const org = String(this.azureOrg.value() ?? "").trim();
927
+ const pat = String(this.azurePat.value() ?? "").trim();
928
+ let body;
929
+ if (pat) body = { org_url: org, pat, agents_enabled: this.azureAgents };
930
+ else if (stored) body = { agents_enabled: this.azureAgents };
931
+ else {
932
+ this.error = "Escribe la URL de la organización y el PAT.";
933
+ cx.notify();
934
+ return;
935
+ }
936
+ this.azureBusy = true;
937
+ this.error = null;
938
+ cx.notify();
939
+ cx.spawn(async (cx) => {
940
+ try {
941
+ this.azureDevOps = await api("/settings/azure-devops", { method: "PUT", body });
942
+ this.azurePat.set_value("");
943
+ notify({ title: "Azure DevOps guardado", body: this.azureDevOps?.account ?? "", level: "success" });
944
+ } catch (e) {
945
+ this.error = `Azure DevOps: ${String(e?.message ?? e)}`;
946
+ }
947
+ this.azureBusy = false;
948
+ cx.notify();
949
+ });
950
+ }
951
+
952
+ removeAzure(cx) {
953
+ cx.spawn(async (cx) => {
954
+ try {
955
+ this.azureDevOps = await api("/settings/azure-devops", { method: "DELETE" });
956
+ this.azureOrgLoaded = false;
957
+ notify({ title: "Credencial de Azure DevOps quitada", level: "info" });
958
+ } catch (e) {
959
+ this.error = String(e?.message ?? e);
960
+ }
961
+ cx.notify();
962
+ });
963
+ }
964
+
965
+ azureSection() {
966
+ const t = theme();
967
+ const az = this.azureDevOps;
968
+ const stored = Boolean(az?.configured);
969
+ if (stored && !this.azureOrgLoaded) {
970
+ this.azureOrgLoaded = true;
971
+ this.azureOrg.set_value(az.org_url ?? "");
972
+ this.azureAgents = az.agents_enabled !== false;
973
+ }
974
+ const label = (text) => div().pt(2).text_size(UI.text.small).font_semibold().text_color(t.muted).child(text);
975
+ const input = (state) => Input.new(state).h(UI.button + 4).px(10).rounded(UI.radius).border_1().border_color(t.input).bg(t.background).text_size(12);
976
+ return v_flex().gap(12)
977
+ .child(this.sectionTitle("Azure DevOps", "Para tickets sobre repos de Azure Repos: clonar, crear ramas y abrir PR."))
978
+ .child(this.status("azure-status", stored ? `Conectado${az.account ? ` como ${az.account}` : ""}` : "Sin conectar",
979
+ stored ? this.tone(t, "ok") : t.dim))
980
+ .when(stored, (el) => el.child(this.note(`Organización: ${az.org_url}`)))
981
+ .when(!stored, (el) => el.child(this.note("Opcional: solo hace falta si tus tickets trabajan sobre Azure Repos.")))
982
+ .child(v_flex().gap(4)
983
+ .child(label("Organización"))
984
+ .child(input(this.azureOrg))
985
+ .child(label(stored ? "PAT (vacío: conserva el guardado)" : "PAT"))
986
+ .child(input(this.azurePat)))
987
+ .child(h_flex().id("azure-agents").gap(8).items_center().cursor_pointer()
988
+ .on_click((_e, cx) => { this.azureAgents = !this.azureAgents; cx.notify(); })
989
+ .child(this.checkbox(this.azureAgents))
990
+ .child(div().text_size(UI.text.body).text_color(t.foreground).child("Disponible para los agentes del run")))
991
+ .when(this.azureAgents, (el) => el.child(this.note("Los agentes reciben AZURE_DEVOPS_ORG_URL, AZURE_DEVOPS_PAT y AZURE_DEVOPS_EXT_PAT (az devops, skills de PR): pueden usar el PAT con todos sus permisos. Dale solo los que necesites.")))
992
+ .child(h_flex().gap(6)
993
+ .child(this.button("azure-save", this.azureBusy ? "Comprobando…" : "Guardar", true, (cx) => this.saveAzure(cx)))
994
+ .when(stored, (el) => el.child(this.button("azure-remove", "Quitar", false, (cx) => this.removeAzure(cx)))))
995
+ .child(this.note("Se comprueba contra la organización al guardar; el PAT se guarda en el orquestador y llega a cada run por stdin, nunca a la imagen."));
996
+ }
997
+
998
+ jiraSection() {
999
+ const t = theme();
1000
+ const j = this.jira;
1001
+ const configured = Boolean(j?.configured);
1002
+ const statusText = configured
1003
+ ? `Conectado como ${j.account_name ?? j.email} en ${j.site}`
1004
+ : "Sin conectar";
1005
+ const statusColor = configured ? this.tone(t, "ok") : t.muted;
1006
+
1007
+ return v_flex().gap(12)
1008
+ .child(this.sectionTitle("Jira", "Para enlazar issues como historia del ticket y dar acceso a los agentes."))
1009
+ .child(v_flex().gap(4)
1010
+ .child(this.status("jira-status", statusText, statusColor))
1011
+ .when(!configured, (el) => el.child(this.note("Jira es opcional: configúralo para buscar y enlazar issues de Jira Cloud como historias de tus tickets."))))
1012
+ .child(v_flex().gap(8)
1013
+ .child(v_flex().gap(3)
1014
+ .child(div().text_size(UI.text.small).font_medium().text_color(t.muted).child("Sitio de Jira Cloud"))
1015
+ .child(Input.new(this.jiraSite).h(UI.button + 4).px(10).rounded(UI.radius).border_1().border_color(t.input).bg(t.background).text_size(12)))
1016
+ .child(v_flex().gap(3)
1017
+ .child(div().text_size(UI.text.small).font_medium().text_color(t.muted).child("Email de la cuenta"))
1018
+ .child(Input.new(this.jiraEmail).h(UI.button + 4).px(10).rounded(UI.radius).border_1().border_color(t.input).bg(t.background).text_size(12)))
1019
+ .child(v_flex().gap(3)
1020
+ .child(div().text_size(UI.text.small).font_medium().text_color(t.muted).child("API token de Jira Cloud"))
1021
+ .child(Input.new(this.jiraToken).h(UI.button + 4).px(10).rounded(UI.radius).border_1().border_color(t.input).bg(t.background).text_size(12))
1022
+ .child(div().text_size(UI.text.tiny).text_color(t.dim).child("El token nunca se muestra tras guardarse y viaja a los agentes solo por stdin. Déjalo vacío para conservar el token guardado.")))
1023
+ .child(v_flex().gap(2)
1024
+ .child(h_flex().id("jira-agents-enabled").gap(7).items_center().px(2).py(3).cursor_pointer()
1025
+ .text_color(t.foreground).font_family(UI.fontSans).text_size(UI.text.small)
1026
+ .on_click((_e, cx) => {
1027
+ this.jiraAgentsEnabled = !this.jiraAgentsEnabled;
1028
+ cx.notify();
1029
+ })
1030
+ .child(div().w(13).h(13).rounded(3).border_1()
1031
+ .border_color(this.jiraAgentsEnabled ? t.accent : t.border)
1032
+ .bg(this.jiraAgentsEnabled ? t.accent : t.input)
1033
+ .child(div().text_size(10).text_center().text_color(t.chrome).child(this.jiraAgentsEnabled ? "✓" : "")))
1034
+ .child("Disponible para los agentes"))
1035
+ .when(this.jiraAgentsEnabled, (el) => el.child(div().pl(22).text_size(UI.text.tiny).font_family(UI.fontSans).text_color(t.dim)
1036
+ .child("Aviso de riesgo: con «Disponible para los agentes» activado, cualquier agente del run puede usar el API token con todos sus permisos (JIRA_URL, JIRA_USERNAME, JIRA_API_TOKEN por stdin).")))))
1037
+ .when(Boolean(this.jiraError), (el) => el.child(div().id("jira-error").text_size(UI.text.small).text_color(t.blocked).child(this.jiraError)))
1038
+ .child(h_flex().gap(6).flex_wrap()
1039
+ .child(this.button("jira-save", this.jiraBusy ? "Guardando…" : "Guardar", true, (cx) => this.saveJira(cx)))
1040
+ .when(configured, (el) => el.child(this.button("jira-remove", "Quitar", false, (cx) => this.removeJira(cx)))));
1041
+ }
1042
+
1043
+ saveJira(cx) {
1044
+ const site = this.jiraSite.value().trim();
1045
+ const email = this.jiraEmail.value().trim();
1046
+ const token = this.jiraToken.value().trim();
1047
+ if (!site) {
1048
+ this.jiraError = "Introduce la URL de tu sitio de Jira Cloud (https://<algo>.atlassian.net)";
1049
+ cx.notify();
1050
+ return;
1051
+ }
1052
+ if (!email) {
1053
+ this.jiraError = "Introduce el email de tu cuenta";
1054
+ cx.notify();
1055
+ return;
1056
+ }
1057
+ if (!token && !this.jira?.configured) {
1058
+ this.jiraError = "Introduce el API token de Jira";
1059
+ cx.notify();
1060
+ return;
1061
+ }
1062
+ this.jiraBusy = true;
1063
+ this.jiraError = null;
1064
+ cx.notify();
1065
+ cx.spawn(async (cx) => {
1066
+ try {
1067
+ const body = {
1068
+ site,
1069
+ email,
1070
+ token,
1071
+ agents_enabled: this.jiraAgentsEnabled,
1072
+ };
1073
+ const summary = await api("/settings/jira", { method: "PUT", body });
1074
+ this.jira = summary;
1075
+ this.jiraToken.set_value("");
1076
+ this.jiraError = null;
1077
+ } catch (e) {
1078
+ this.jiraError = String(e?.message ?? e);
1079
+ if (this.jira) this.jira.invalid = true;
1080
+ } finally {
1081
+ this.jiraBusy = false;
1082
+ cx.notify();
1083
+ }
1084
+ });
1085
+ }
1086
+
1087
+ removeJira(cx) {
1088
+ this.jiraBusy = true;
1089
+ this.jiraError = null;
1090
+ cx.notify();
1091
+ cx.spawn(async (cx) => {
1092
+ try {
1093
+ const summary = await api("/settings/jira", { method: "DELETE" });
1094
+ this.jira = summary;
1095
+ this.jiraToken.set_value("");
1096
+ this.jiraError = null;
1097
+ } catch (e) {
1098
+ this.jiraError = String(e?.message ?? e);
1099
+ } finally {
1100
+ this.jiraBusy = false;
1101
+ cx.notify();
1102
+ }
1103
+ });
1104
+ }
1105
+
1106
+ /** Tool groups as the person has them now (the pending PUT wins over the loaded state). */
1107
+ selectedTools() {
1108
+ return this.toolSelection ?? (this.setup?.tools_selected ?? []);
1109
+ }
1110
+
1111
+ /** Ticks a tool group on or off; each click is saved (PUT /setup), like the agents. */
1112
+ toggleTool(cx, id) {
1113
+ const catalog = (this.setup?.catalog ?? []).map((g) => g.id);
1114
+ const cur = new Set(this.selectedTools());
1115
+ if (cur.has(id)) cur.delete(id);
1116
+ else cur.add(id);
1117
+ const sel = catalog.filter((g) => cur.has(g));
1118
+ this.toolSelection = sel;
1119
+ this.error = null;
1120
+ cx.notify();
1121
+ cx.spawn(async (cx) => {
1122
+ try {
1123
+ this.setup = await api("/setup", { method: "PUT", body: { tools_selected: sel } });
1124
+ } catch (e) {
1125
+ this.error = String(e?.message ?? e);
1126
+ }
1127
+ this.toolSelection = null;
1128
+ cx.notify();
1129
+ });
1130
+ }
1131
+
1132
+ /** Saves the extra Debian packages typed in the field (comma or space separated). */
1133
+ saveAptExtra(cx) {
1134
+ const pkgs = [...new Set(String(this.aptInput.value() ?? "").split(/[\s,]+/).map((x) => x.trim()).filter(Boolean))];
1135
+ const bad = pkgs.filter((x) => !APT_RE.test(x));
1136
+ if (bad.length) {
1137
+ this.error = `Nombre de paquete no válido: ${bad.join(", ")}`;
1138
+ cx.notify();
1139
+ return;
1140
+ }
1141
+ this.error = null;
1142
+ cx.spawn(async (cx) => {
1143
+ try {
1144
+ this.setup = await api("/setup", { method: "PUT", body: { apt_extra: pkgs } });
1145
+ this.aptLoaded = (this.setup?.apt_extra ?? []).join(" ");
1146
+ this.aptInput.set_value(this.aptLoaded);
1147
+ notify({ title: "Paquetes guardados", body: pkgs.length ? pkgs.join(", ") : "ninguno", level: "success" });
1148
+ } catch (e) {
1149
+ this.error = String(e?.message ?? e);
1150
+ }
1151
+ cx.notify();
1152
+ });
1153
+ }
1154
+
1155
+ checkbox(on) {
1156
+ const t = theme();
1157
+ return div().w(16).h(16).flex_none().rounded(4).border_1().border_color(on ? t.accent : t.border)
1158
+ .bg(on ? t.accent : t.background).flex().items_center().justify_center()
1159
+ .text_size(11).font_semibold().text_color(t.accent_foreground ?? t.background).child(on ? "✓" : "");
1160
+ }
1161
+
1162
+ /** One tool group: checkbox, name, contents, rough size and how it stands in the image. */
1163
+ toolRow(g, img) {
1164
+ const t = theme();
1165
+ const on = this.selectedTools().includes(g.id);
1166
+ const inImage = (img.tools ?? []).includes(g.id);
1167
+ const state = !img.present ? null
1168
+ : on && !inImage ? { text: "falta", tone: "waiting" }
1169
+ : !on && inImage ? { text: "sobra", tone: "waiting" }
1170
+ : inImage ? { text: "en la imagen", tone: "ok" } : null;
1171
+ return h_flex().id(`tool-${g.id}`).gap(10).items_start().px(10).py(7).rounded(UI.radius).cursor_pointer()
1172
+ .border_1().border_color(on ? t.accent : t.border).bg(t.background)
1173
+ .hover((st) => st.bg(t.hover))
1174
+ .on_click((_e, cx) => this.toggleTool(cx, g.id))
1175
+ .child(div().pt(1).child(this.checkbox(on)))
1176
+ .child(v_flex().flex_1().min_w(0).gap(1)
1177
+ .child(h_flex().gap(8).items_center()
1178
+ .child(div().text_size(UI.text.body).font_semibold().text_color(t.foreground).child(g.label))
1179
+ .when(Boolean(state), (el) => el.child(div().id(`tool-state-${g.id}`).text_size(UI.text.tiny).text_color(this.tone(t, state.tone)).child(state.text))))
1180
+ .child(div().text_size(UI.text.small).font_family(UI.fontSans).text_color(t.muted).child(g.description)))
1181
+ .child(div().flex_none().text_size(UI.text.small).text_color(t.dim).child(`~${g.size_mb >= 1000 ? `${(g.size_mb / 1000).toFixed(1)} GB` : `${g.size_mb} MB`}`));
1182
+ }
1183
+
1184
+ imageSection() {
1185
+ const t = theme();
1186
+ const s = this.setup;
1187
+ const img = s?.image ?? {};
1188
+ const missing = missingInImage(s);
1189
+ const extra = (img.agents ?? []).filter((a) => !this.selectedAgents().includes(a));
1190
+ const stale = Boolean(img.stale) || missing.length > 0;
1191
+ const needs = !img.present || stale;
1192
+ const catalog = s?.catalog ?? [];
1193
+ const base = catalog.filter((g) => g.default);
1194
+ const sdks = catalog.filter((g) => !g.default);
1195
+ const total = catalog.filter((g) => this.selectedTools().includes(g.id)).reduce((n, g) => n + g.size_mb, 0);
1196
+ const changes = [];
1197
+ if (missing.length) changes.push(`añadir ${missing.join(", ")}`);
1198
+ if (img.missing_tools?.length) changes.push(`instalar ${img.missing_tools.join(", ")}`);
1199
+ if (img.extra_tools?.length) changes.push(`quitar ${img.extra_tools.join(", ")}`);
1200
+ if (img.apt_changed) changes.push("paquetes apt");
1201
+ if (img.recipe_changed) changes.push("receta de la imagen actualizada en bond-app (setup.sh, versiones…)");
1202
+ const label = (text) => div().pt(4).text_size(UI.text.small).font_semibold().text_color(t.muted).child(text);
1203
+ const building = this.rbBusy || Boolean(this.rbStatus?.running);
1204
+ return v_flex().gap(12)
1205
+ .child(this.sectionTitle("Imagen del runner", "La imagen Docker en la que corre cada run: agentes y herramientas."))
1206
+ .child(v_flex().gap(6)
1207
+ .child(this.status("image-status", !s ? "Comprobando…" : !img.present ? "No hay imagen" : stale ? "Desfasada" : "Al día",
1208
+ !s ? t.dim : this.tone(t, !img.present ? "error" : stale ? "waiting" : "ok")))
1209
+ .when(Boolean(img.present && img.agents?.length), (el) => el.child(h_flex().gap(6).flex_wrap().items_center()
1210
+ .child(div().text_size(UI.text.small).text_color(t.muted).child("Agentes:"))
1211
+ .children(img.agents.map((a) => h_flex().id(`image-agent-${a}`).gap(4).items_center()
1212
+ .child(this.agentBadge(a, 18)).child(div().text_size(UI.text.small).text_color(t.foreground).child(a))))))
1213
+ .when(changes.length > 0, (el) => el.child(div().id("image-stale").text_size(UI.text.small).text_color(this.tone(t, "waiting"))
1214
+ .child(`⟳ Cambios sin aplicar: ${changes.join(" · ")}. Reconstruye para aplicarlos.`)))
1215
+ .when(extra.length > 0, (el) => el.child(this.note(`También lleva ${extra.join(", ")}, que no tienes elegidos.`))))
1216
+ .when(catalog.length > 0, (el) => el
1217
+ .child(label("Herramientas"))
1218
+ .child(v_flex().gap(6).children(base.map((g) => this.toolRow(g, img))))
1219
+ .child(label("SDK y extras (opcionales: si tus repos traen devcontainer, no hacen falta)"))
1220
+ .child(v_flex().gap(6).children(sdks.map((g) => this.toolRow(g, img))))
1221
+ .child(label("Paquetes de Debian adicionales"))
1222
+ .child(h_flex().gap(6).items_center()
1223
+ .child(div().flex_1().child(Input.new(this.aptInput).h(UI.button + 4).px(10).rounded(UI.radius).border_1().border_color(t.input).bg(t.background).text_size(12)))
1224
+ .child(this.button("apt-save", "Guardar", false, (cx) => this.saveAptExtra(cx))))
1225
+ .child(this.note(`Herramientas elegidas: ~${(total / 1000).toFixed(1)} GB sobre la imagen base.`)))
1226
+ .when(building, (el) => el.child(this.rebuildProgress()))
1227
+ .when(!building && this.rbStatus?.ok === false, (el) => el.child(div().id("image-build-error").text_size(UI.text.small).text_color(t.blocked)
1228
+ .child(`El último build falló${this.rbStatus.error ? `: ${String(this.rbStatus.error).slice(0, 160)}` : ""}. El detalle está en el log del orquestador.`)))
1229
+ .child(h_flex().gap(6).items_center()
1230
+ .child(this.button("image-rebuild", building ? "Reconstruyendo…" : (img.present ? "Reconstruir" : "Construir"), needs && !building, (cx) => { if (!building) this.rebuildImage(cx); }))
1231
+ .when(building, (el) => el.child(this.note("Puede tardar varios minutos; puedes cerrar Ajustes, el build sigue."))))
1232
+ .child(this.note("Reconstruir trae las versiones fijadas de bond, hc, los agentes y las herramientas. No toca las credenciales."));
1233
+ }
1234
+
1235
+ advancedSection() {
1236
+ const t = theme();
1237
+ const s = this.setup;
1238
+ const row = (label, value) => h_flex().gap(10).items_start()
1239
+ .child(div().w(150).flex_none().text_size(UI.text.small).text_color(t.muted).child(label))
1240
+ .child(div().flex_1().min_w(0).text_size(UI.text.small).text_color(t.foreground).child(value));
1241
+ return v_flex().gap(12)
1242
+ .child(this.sectionTitle("Avanzado"))
1243
+ .child(v_flex().gap(8)
1244
+ .child(row("API", apiUrl()))
1245
+ .child(row("Asistente", s ? (s.setup_done ? "terminado" : "sin terminar") : "—"))
1246
+ .child(row("Credenciales", "En el orquestador, 0600; llegan a cada run por stdin.")))
1247
+ .child(this.favoritesBlock())
1248
+ .child(h_flex().child(this.button("wiz-reopen", "Abrir el asistente", false, (cx) => {
1249
+ this.view = "wizard";
1250
+ this.step = 1;
1251
+ this.error = null;
1252
+ cx.notify();
1253
+ })));
1254
+ }
1255
+
1256
+ /** The ★ repos of the new-ticket dialog («Dónde»): listed here to remove them. */
1257
+ favoritesBlock() {
1258
+ const t = theme();
1259
+ const favs = this.favorites ?? [];
1260
+ const label = (url) => {
1261
+ const az = /dev\.azure\.com\/([^/]+)\/([^/]+)\/_git\/([^/]+)/.exec(url);
1262
+ if (az) return `${az[1]}/${decodeURIComponent(az[2])}/${decodeURIComponent(az[3])}`;
1263
+ const gh = /github\.com\/([^/]+)\/([^/]+?)(?:\.git)?$/.exec(url);
1264
+ return gh ? `${gh[1]}/${gh[2]}` : url;
1265
+ };
1266
+ const slug = (url) => url.replace(/[^A-Za-z0-9.-]/g, "_");
1267
+ return v_flex().id("fav-repos").gap(6)
1268
+ .child(div().text_size(UI.text.body).font_semibold().text_color(t.foreground).child("Repos favoritos"))
1269
+ .child(favs.length === 0
1270
+ ? this.note("Sin favoritos. Márcalos con ★ en «Dónde» al crear un ticket.")
1271
+ : v_flex().gap(4).children(favs.map((url) => h_flex().id(`fav-${slug(url)}`).gap(8).items_center()
1272
+ .child(div().flex_1().min_w(0).truncate().text_size(UI.text.small).text_color(t.foreground).child(label(url)))
1273
+ .child(div().id(`fav-del-${slug(url)}`).px(6).rounded(UI.radius).cursor_pointer().text_size(UI.text.small)
1274
+ .text_color(t.muted).hover((st) => st.bg(t.hover)).child("✕")
1275
+ .on_click((_e, cx) => this.removeFavorite(cx, url))))))
1276
+ .when(favs.length > 0, (el) => el.child(this.note("Se marcan y desmarcan con ★ en el alta de ticket.")));
1277
+ }
1278
+
1279
+ removeFavorite(cx, url) {
1280
+ const next = (this.favorites ?? []).filter((u) => u !== url);
1281
+ this.favorites = next;
1282
+ this.favBusy = true;
1283
+ cx.notify();
1284
+ cx.spawn(async (cx) => {
1285
+ try {
1286
+ this.favorites = (await api("/repos/favorites", { method: "PUT", body: { favorites: next } }))?.favorites ?? next;
1287
+ } catch (e) {
1288
+ this.error = `No se pudo quitar el favorito: ${String(e?.message ?? e)}`;
1289
+ }
1290
+ this.favBusy = false;
1291
+ cx.notify();
1292
+ });
1293
+ }
1294
+
1295
+ goTo(cx, id) {
1296
+ if (this.view === "wizard") {
1297
+ const i = WIZARD_STEPS.indexOf(id);
1298
+ if (i >= 0) this.step = i + 1;
1299
+ } else {
1300
+ this.section = id;
1301
+ }
1302
+ this.error = null;
1303
+ cx.notify();
1304
+ }
1305
+
1306
+ /** The section shown: the wizard's step, or the chosen one (agents until loaded). */
1307
+ currentSection() {
1308
+ return this.view === "wizard" ? WIZARD_STEPS[this.step - 1] : (this.section ?? "agents");
1309
+ }
1310
+
1311
+ navItem(id, label, active, mark, onClick) {
1312
+ const t = theme();
1313
+ return h_flex().id(`nav-${id}`).h(30).px(10).gap(8).items_center().rounded(UI.radius).cursor_pointer()
1314
+ .bg(active ? t.selected : t.popover)
1315
+ .hover((st) => st.bg(active ? t.selected : t.hover))
1316
+ .on_click((_e, cx) => onClick(cx))
1317
+ .child(div().flex_1().min_w(0).truncate().text_size(UI.text.body).font_family(UI.fontSans)
1318
+ .font_weight(active ? 600 : 400).text_color(active ? t.foreground : t.muted).child(label))
1319
+ .when(Boolean(mark), (el) => el.child(div().id(`nav-mark-${id}`).text_size(UI.text.small).font_semibold()
1320
+ .text_color(this.tone(t, mark.tone)).child(mark.mark)));
1321
+ }
1322
+
1323
+ renderSettings() {
1324
+ const t = theme();
1325
+ const wizard = this.view === "wizard";
1326
+ const current = this.currentSection();
1327
+ const marks = sectionMarks({ conn: this.conn, setup: this.setup, creds: this.creds, jira: this.jira });
1328
+ const nav = wizard
1329
+ ? WIZARD_STEPS.map((id, i) => {
1330
+ const label = SECTIONS.find((x) => x.id === id).label;
1331
+ const mark = i + 1 < this.step ? { mark: "✓", tone: "ok" } : marks[id] ?? null;
1332
+ return this.navItem(id, `${i + 1} ${label}`, current === id, mark, (cx) => this.goTo(cx, id));
1333
+ })
1334
+ : SECTIONS.map((x) => this.navItem(x.id, x.label, current === x.id, marks[x.id] ?? null, (cx) => this.goTo(cx, x.id)));
1335
+ const body = {
1336
+ orchestrator: () => this.orchestratorSection(),
1337
+ agents: () => this.agentsSection(),
1338
+ github: () => this.githubSection(),
1339
+ azure: () => this.azureSection(),
1340
+ jira: () => this.jiraSection(),
1341
+ image: () => this.imageSection(),
1342
+ advanced: () => this.advancedSection(),
1343
+ }[current]();
1344
+ const actions = [];
1345
+ if (wizard) {
1346
+ if (this.step > 1) actions.push(this.button("wiz-back", "Atrás", false, (cx) => this.wizBack(cx)));
1347
+ actions.push(this.step < WIZARD_STEPS.length
1348
+ ? this.button("wiz-next", "Siguiente", true, (cx) => this.wizNext(cx))
1349
+ : this.button("wiz-finish", this.busy ? "Guardando…" : "Finalizar", true, (cx) => this.wizFinish(cx)));
1350
+ }
1351
+ const pending = wizard && this.step === WIZARD_STEPS.length && this.setup && !this.setup.complete ? this.pendingParts(this.setup) : [];
1352
+ return v_flex().id(wizard ? "bond-wizard" : "bond-settings-dialog").track_focus(this.handle).on_key_down((e, cx) => this.key(e, cx))
1353
+ .size_full().bg(t.popover).rounded(UI.radiusLg).border_1().border_color(t.border).text_color(t.foreground)
1354
+ .font_family("JetBrains Mono").overflow_hidden()
1355
+ .child(h_flex().h(46).flex_none().px(16).gap(10).items_center().border_b_1().border_color(t.border)
1356
+ .child(div().flex_1().text_size(UI.text.title + 2).font_family(UI.fontSans).font_semibold()
1357
+ .child(wizard ? "Configuración inicial" : "Ajustes"))
1358
+ .when(wizard, (el) => el.child(div().text_size(UI.text.small).text_color(t.dim).child(`Paso ${this.step} de ${WIZARD_STEPS.length}`)))
1359
+ .child(div().id("settings-close").w(24).h(24).rounded(UI.radius).flex().items_center().justify_center()
1360
+ .text_color(t.muted).cursor_pointer().hover((st) => st.bg(t.hover).text_color(t.foreground))
1361
+ .tooltip("Cerrar (Esc). Lo guardado no se pierde.")
1362
+ .on_click(() => closeOverlay(props().overlay)).child("✕")))
1363
+ .child(h_flex().flex_1().min_h(0).items_start()
1364
+ .child(v_flex().id("settings-nav").w(176).flex_none().h_full().p(8).gap(2).border_r_1().border_color(t.border).children(nav))
1365
+ .child(v_flex().id("settings-body").flex_1().min_w(0).h_full().p(20).gap(14).overflow_y_scrollbar()
1366
+ .when(Boolean(this.loadError), (el) => el.child(div().text_size(UI.text.small).text_color(t.blocked).child(`API: ${this.loadError}`)))
1367
+ .child(body)
1368
+ .when(Boolean(this.error), (el) => el.child(div().id("settings-error").text_size(UI.text.small).text_color(t.blocked).child(this.error)))
1369
+ .when(pending.length > 0, (el) => el.child(this.note(`Al finalizar quedará pendiente: ${pending.join(" · ")}. Podrás completarlo en Ajustes.`)))))
1370
+ .when(wizard, (el) => el.child(h_flex().h(52).flex_none().px(16).gap(8).items_center().justify_end().border_t_1().border_color(t.border)
1371
+ .children(actions)));
1372
+ }
1373
+
192
1374
  key(e, cx) {
193
1375
  if (e.key === "escape") {
194
1376
  closeOverlay(props().overlay);
1377
+ if (this.view === "agy-login") {
1378
+ this.cancelAgyLogin(cx, false);
1379
+ }
195
1380
  cx.stop_propagation();
196
1381
  }
197
1382
  }
@@ -204,67 +1389,440 @@ export default class BondSettings extends View {
204
1389
  .cursor_pointer().hover((s) => s.opacity(0.85)).on_click((_e, cx) => action(cx)).child(text);
205
1390
  }
206
1391
 
207
- renderPanel() {
1392
+ reconnect(cx) {
1393
+ if (this.connBusy) return;
1394
+ this.connBusy = "reconnect";
1395
+ resetToken();
1396
+ cx.notify();
1397
+ cx.spawn(async (cx) => {
1398
+ this.conn = await diagnose();
1399
+ this.connBusy = null;
1400
+ this.load(cx);
1401
+ notify({ title: "Orquestador", body: this.conn.state === "ok" ? "Conectado" : this.conn.detail, level: this.conn.state === "ok" ? "success" : "error" });
1402
+ cx.notify();
1403
+ });
1404
+ }
1405
+
1406
+ /** Waits until /health is `up` (true) or not (false), up to `ms`. */
1407
+ async waitHealth(cx, up, ms) {
1408
+ const until = Date.now() + ms;
1409
+ while (Date.now() < until) {
1410
+ let ok = false;
1411
+ try {
1412
+ await health();
1413
+ ok = true;
1414
+ } catch {}
1415
+ if (ok === up) return true;
1416
+ await cx.sleep(500);
1417
+ }
1418
+ return false;
1419
+ }
1420
+
1421
+ restartOrchestrator(cx) {
1422
+ if (this.connBusy) return;
1423
+ this.connBusy = "restart";
1424
+ cx.notify();
1425
+ cx.spawn(async (cx) => {
1426
+ try {
1427
+ await api("/system/restart", { method: "POST" });
1428
+ // It answers first and goes down right after; then the new process comes up.
1429
+ await this.waitHealth(cx, false, 10000);
1430
+ const back = await this.waitHealth(cx, true, 30000);
1431
+ if (!back) throw new Error(`no ha vuelto en 30 s: mira <data-dir>/orchestrator.log (${apiUrl()})`);
1432
+ resetToken();
1433
+ notify({ title: "Orquestador reiniciado", body: apiUrl(), level: "success" });
1434
+ } catch (e) {
1435
+ notify({ title: "No se pudo reiniciar", body: String(e?.message ?? e), level: "error" });
1436
+ }
1437
+ this.connBusy = null;
1438
+ this.load(cx);
1439
+ cx.notify();
1440
+ });
1441
+ }
1442
+
1443
+ startOrchestrator(cx) {
1444
+ if (this.connBusy) return;
1445
+ this.connBusy = "start";
1446
+ cx.notify();
1447
+ run("tab.new", { name: "bond-app", argv: startCommand(), focus: false });
1448
+ cx.spawn(async (cx) => {
1449
+ const up = await this.waitHealth(cx, true, 30000);
1450
+ resetToken();
1451
+ if (!up) notify({ title: "El orquestador no arranca", body: "Mira la pestaña «bond-app»", level: "error" });
1452
+ this.connBusy = null;
1453
+ this.load(cx);
1454
+ cx.notify();
1455
+ });
1456
+ }
1457
+
1458
+ startAgyLogin(cx) {
1459
+ this.agyStatus = "starting";
1460
+ this.agyUrl = null;
1461
+ this.agyEmail = null;
1462
+ this.agyError = null;
1463
+ this.agyBusy = true;
1464
+ cx.notify();
1465
+ cx.spawn(async (cx) => {
1466
+ try {
1467
+ const res = await api(`/settings/${this.loginAgent ?? "agy"}/login/start`, { method: "POST" });
1468
+ if (res?.status) this.agyStatus = res.status;
1469
+ if (res?.url) this.agyUrl = res.url;
1470
+ this.agyUserCode = res?.user_code ?? null;
1471
+ this.agyDevice = Boolean(res?.device);
1472
+ this.agyAuto = Boolean(res?.auto);
1473
+ if (res?.email) this.agyEmail = res.email;
1474
+ if (res?.error) this.agyError = res.error;
1475
+ } catch (e) {
1476
+ this.agyStatus = "error";
1477
+ this.agyError = String(e?.message ?? e);
1478
+ } finally {
1479
+ this.agyBusy = false;
1480
+ cx.notify();
1481
+ }
1482
+ });
1483
+ }
1484
+
1485
+ pollAgyStatus(cx) {
1486
+ cx.spawn(async (cx) => {
1487
+ try {
1488
+ const res = await api(`/settings/${this.loginAgent ?? "agy"}/login/status`);
1489
+ if (!res) return;
1490
+ let changed = false;
1491
+ if (res.status && res.status !== this.agyStatus) {
1492
+ this.agyStatus = res.status;
1493
+ changed = true;
1494
+ }
1495
+ if (res.url && res.url !== this.agyUrl) {
1496
+ this.agyUrl = res.url;
1497
+ changed = true;
1498
+ }
1499
+ if ((res.user_code ?? null) !== this.agyUserCode || Boolean(res.device) !== this.agyDevice || Boolean(res.auto) !== this.agyAuto) {
1500
+ this.agyUserCode = res.user_code ?? null;
1501
+ this.agyDevice = Boolean(res.device);
1502
+ this.agyAuto = Boolean(res.auto);
1503
+ changed = true;
1504
+ }
1505
+ if (res.email && res.email !== this.agyEmail) {
1506
+ this.agyEmail = res.email;
1507
+ changed = true;
1508
+ }
1509
+ if (res.error && res.error !== this.agyError) {
1510
+ this.agyError = res.error;
1511
+ changed = true;
1512
+ }
1513
+ if (changed) {
1514
+ if (this.agyStatus === "waiting_code" && !this.agyDevice) {
1515
+ this.agyCode.focus();
1516
+ }
1517
+ cx.notify();
1518
+ }
1519
+ } catch {}
1520
+ });
1521
+ }
1522
+
1523
+ submitAgyCode(cx) {
1524
+ const code = this.agyCode.value().trim();
1525
+ if (!code) {
1526
+ this.agyError = "El código no puede estar vacío.";
1527
+ cx.notify();
1528
+ return;
1529
+ }
1530
+ this.agyBusy = true;
1531
+ this.agyError = null;
1532
+ this.agyStatus = "authenticating";
1533
+ cx.notify();
1534
+ cx.spawn(async (cx) => {
1535
+ try {
1536
+ const res = await api(`/settings/${this.loginAgent ?? "agy"}/login/code`, {
1537
+ method: "POST",
1538
+ body: { code },
1539
+ });
1540
+ if (res?.status) this.agyStatus = res.status;
1541
+ if (res?.email) this.agyEmail = res.email;
1542
+ if (res?.error) this.agyError = res.error;
1543
+ } catch (e) {
1544
+ this.agyStatus = "error";
1545
+ this.agyError = String(e?.message ?? e);
1546
+ } finally {
1547
+ this.agyBusy = false;
1548
+ cx.notify();
1549
+ }
1550
+ });
1551
+ }
1552
+
1553
+ cancelAgyLogin(cx, close = true) {
1554
+ const p = props() ?? {};
1555
+ cx.spawn(async (cx) => {
1556
+ try {
1557
+ await api(`/settings/${this.loginAgent ?? "agy"}/login/cancel`, { method: "POST" });
1558
+ } catch {}
1559
+ if (close && p.overlay) {
1560
+ closeOverlay(p.overlay);
1561
+ }
1562
+ });
1563
+ }
1564
+
1565
+ copyToClipboard(text, cx) {
1566
+ if (!text) return;
1567
+ try {
1568
+ if (cx && typeof cx.write_to_clipboard === "function") {
1569
+ cx.write_to_clipboard(text);
1570
+ notify({ title: "URL copiada", body: "Pégala en tu navegador para autorizar", level: "info" });
1571
+ return;
1572
+ }
1573
+ } catch {}
1574
+ try {
1575
+ exec("wl-copy", [text]).catch(() => {
1576
+ exec("xclip", ["-selection", "clipboard"]).catch(() => {});
1577
+ });
1578
+ } catch {}
1579
+ notify({ title: "URL copiada", body: "Pégala en tu navegador para autorizar", level: "info" });
1580
+ }
1581
+
1582
+ finishAgyLogin(cx) {
1583
+ const p = props() ?? {};
1584
+ cx.spawn(async (cx) => {
1585
+ try {
1586
+ await api(`/settings/${this.loginAgent ?? "agy"}/login/finish`, { method: "POST" });
1587
+ } catch {}
1588
+ setShared(RELOAD_KEY, Date.now());
1589
+ if (p.overlay) {
1590
+ closeOverlay(p.overlay);
1591
+ }
1592
+ });
1593
+ }
1594
+
1595
+ renderAgyLogin(p) {
208
1596
  const t = theme();
209
- const row = (c) => h_flex().id(`cred-${c.agent}`).gap(8).items_center().py(4).font_family("JetBrains Mono")
210
- .child(div().w(70).text_size(UI.text.body).text_color(t.foreground).child(c.agent))
211
- .child(div().flex_1().text_size(UI.text.small).text_color(c.configured ? t.working : t.dim).truncate()
212
- .child(c.configured ? `credencial${c.provider ? ` · ${c.provider}` : ""}` : "sin credencial"))
213
- .child(this.button(`renew-${c.agent}`, c.configured ? "Renovar" : "Iniciar", false, () => openOverlay({
214
- mod: "bond-settings", kind: "dialog", modal: true, width: 480,
215
- props: { view: "credential", agent: c.agent, provider: c.provider ?? "" },
216
- })));
217
- return v_flex().id("bond-settings").size_full().p(10).gap(8).bg(t.chrome).text_color(t.foreground).font_family("JetBrains Mono").overflow_y_scrollbar()
218
- .child(h_flex().items_center()
219
- .child(div().flex_1().text_size(UI.text.title).font_semibold().child("Ajustes"))
220
- .child(div().id("settings-close").w(24).h(22).rounded(UI.radius).flex().items_center().justify_center()
221
- .text_color(t.muted).cursor_pointer().hover((s) => s.bg(t.hover).text_color(t.foreground))
222
- .on_click(() => run("layout.toggle", { id: "settings" })).child("✕")))
223
- .child(this.githubSection())
224
- .child(div().text_size(UI.text.small).font_semibold().text_color(t.muted).child("CREDENCIALES DE AGENTES (D7)"))
225
- .when(Boolean(this.loadError), (el) => el.child(div().text_size(UI.text.small).text_color(t.blocked).child(`API: ${this.loadError}`)))
226
- .children(this.creds.map(row))
227
- .child(div().text_size(UI.text.small).text_color(t.dim)
228
- .child("Los tickets de agentes sin credencial no se bloquean; si una caduca, renuévala aquí."))
229
- .child(div().pt(8).text_size(UI.text.small).font_semibold().text_color(t.muted).child("IMAGEN DEL RUNNER"))
230
- .child(this.button("rebuild", "Rebuild…", false, () => openOverlay({
231
- mod: "bond-settings", kind: "dialog", modal: true, width: 420, props: { view: "rebuild" },
232
- })))
233
- .child(div().text_size(UI.text.small).text_color(t.dim).child("El rebuild no toca ni renueva las credenciales."));
234
- }
235
-
236
- renderDialog(title, body, actions) {
1597
+ const L = LOGIN_TEXT[this.loginAgent ?? "agy"];
1598
+ const children = [];
1599
+
1600
+ children.push(div().text_size(11.5).text_color(t.dim).child(L.intro));
1601
+
1602
+ if (this.agyStatus === "starting") {
1603
+ children.push(
1604
+ v_flex().gap(6).py(12).items_center()
1605
+ .child(div().text_size(12).text_color(t.muted).child(L.starting))
1606
+ .child(div().text_size(11).text_color(t.dim).child(L.startingSub))
1607
+ );
1608
+ } else if (this.agyStatus === "waiting_code") {
1609
+ children.push(
1610
+ v_flex().gap(8)
1611
+ .child(div().text_size(12).font_semibold().text_color(t.foreground).child("1. Abre este enlace en tu navegador:"))
1612
+ .child(
1613
+ h_flex().gap(6).items_center()
1614
+ .child(
1615
+ div().flex_1().p(8).rounded(UI.radius).border_1().border_color(t.border).bg(t.background).text_size(11).truncate()
1616
+ .child(this.agyUrl || "Cargando URL…")
1617
+ )
1618
+ .when(Boolean(this.agyUrl), (el) =>
1619
+ el.child(
1620
+ this.button("agy-copy-url", "Copiar", false, (cx) => {
1621
+ this.copyToClipboard(this.agyUrl, cx);
1622
+ })
1623
+ )
1624
+ )
1625
+ )
1626
+ .when(!this.agyAuto, (el) => el.child(div().text_size(12).font_semibold().text_color(t.foreground).pt(4).child(L.step2)))
1627
+ // codex with the return caught by the orchestrator: nothing to paste unless it fails.
1628
+ .when(this.agyAuto, (el) => el
1629
+ .child(div().id("login-auto").text_size(12).font_semibold().text_color(t.foreground).pt(4)
1630
+ .child("2. Autoriza en el navegador: bond-app recoge la vuelta solo y este diálogo se cierra al terminar."))
1631
+ .when(!this.agyShowPaste, (x) => x.child(div().id("login-show-paste").text_size(11).text_color(t.dim).cursor_pointer()
1632
+ .hover((st) => st.text_color(t.foreground))
1633
+ .on_click((_e, cx) => { this.agyShowPaste = true; cx.notify(); this.agyCode.focus(); })
1634
+ .child("¿El navegador se queda en una página que no carga? Pega aquí su dirección")))
1635
+ .when(this.agyShowPaste, (x) => x.child(div().text_size(11.5).text_color(t.dim).child(L.step2))))
1636
+ .when(!this.agyDevice && (!this.agyAuto || this.agyShowPaste), (el) => el.child(
1637
+ Input.new(this.agyCode).h(32).px(10).rounded(8).border_1().border_color(t.input).bg(t.background).text_size(12.5)
1638
+ ))
1639
+ // Device flow (copilot): the code to type at the link; it finishes by itself.
1640
+ .when(this.agyDevice && Boolean(this.agyUserCode), (el) => el
1641
+ .child(h_flex().gap(8).items_center()
1642
+ .child(div().id("login-user-code").px(14).py(8).rounded(UI.radius).border_1().border_color(t.accent).bg(t.background)
1643
+ .text_size(20).font_semibold().text_color(t.foreground).child(this.agyUserCode))
1644
+ .child(this.button("login-copy-code", "Copiar código", false, (cx) => this.copyToClipboard(this.agyUserCode, cx))))
1645
+ .child(div().text_size(11.5).text_color(t.dim).child("Esperando a que autorices… se cierra solo al terminar.")))
1646
+ );
1647
+ } else if (this.agyStatus === "authenticating") {
1648
+ children.push(
1649
+ v_flex().gap(6).py(12).items_center()
1650
+ .child(div().text_size(12).text_color(t.muted).child(L.authenticating))
1651
+ .child(div().text_size(11).text_color(t.dim).child("Guardando sesión en el orquestador…"))
1652
+ );
1653
+ } else if (this.agyStatus === "success") {
1654
+ children.push(
1655
+ v_flex().gap(8).py(8)
1656
+ .child(div().text_size(13).font_semibold().text_color(t.working).child(L.success(this.agyEmail)))
1657
+ .child(div().text_size(11.5).text_color(t.dim).child(L.successSub))
1658
+ );
1659
+ }
1660
+
1661
+ if (this.agyError) {
1662
+ children.push(
1663
+ div().pt(4).text_size(11.5).text_color(t.blocked).child(`Error: ${this.agyError}`)
1664
+ );
1665
+ }
1666
+
1667
+ const actions = [];
1668
+ if (this.agyStatus === "success") {
1669
+ actions.push(this.button("agy-finish", "Listo", true, (cx) => this.finishAgyLogin(cx)));
1670
+ } else if (this.agyStatus === "waiting_code") {
1671
+ actions.push(this.button("agy-cancel", "Cancelar", false, (cx) => this.cancelAgyLogin(cx)));
1672
+ if (!this.agyDevice && (!this.agyAuto || this.agyShowPaste)) {
1673
+ actions.push(this.button("agy-submit", this.agyBusy ? "Enviando…" : (this.loginAgent === "codex" ? "Enviar dirección" : "Enviar código"), true, (cx) => this.submitAgyCode(cx)));
1674
+ }
1675
+ } else if (this.agyStatus === "error") {
1676
+ actions.push(this.button("agy-cancel", "Cerrar", false, (cx) => this.cancelAgyLogin(cx)));
1677
+ actions.push(this.button("agy-retry", "Reintentar", true, (cx) => this.startAgyLogin(cx)));
1678
+ } else {
1679
+ actions.push(this.button("agy-cancel", "Cancelar", false, (cx) => this.cancelAgyLogin(cx)));
1680
+ }
1681
+
1682
+ return this.renderDialog(L.title, children, actions, true);
1683
+ }
1684
+
1685
+ renderDialog(title, body, actions, fit = false) {
237
1686
  const t = theme();
1687
+ // W-P5: con `fit` el diálogo ocupa la altura acotada del overlay (height: 0.92)
1688
+ // y el cuerpo rota dentro de ella; sin `fit`, tope de 520 px y botones fijos.
1689
+ const bodyWrap = fit
1690
+ ? v_flex().flex_1().min_h(0).overflow_y_scrollbar()
1691
+ : v_flex().max_h(520).overflow_y_scrollbar();
238
1692
  return v_flex().id("bond-settings-dialog").track_focus(this.handle).on_key_down((e, cx) => this.key(e, cx))
239
1693
  .w_full().p(18).gap(10).bg(t.popover).rounded(UI.radiusLg).border_1().border_color(t.border).text_color(t.foreground).font_family("JetBrains Mono")
1694
+ .when(fit, (el) => el.h_full())
240
1695
  .child(h_flex().items_center().child(div().flex_1().text_size(UI.text.title + 2).font_semibold().child(title))
241
1696
  .child(div().text_size(UI.text.small).text_color(t.dim).child("Esc")))
242
- .children(body)
1697
+ .child(bodyWrap.gap(10).children(body))
243
1698
  .when(Boolean(this.error), (el) => el.child(div().text_size(UI.text.small).text_color(t.blocked).child(this.error)))
244
1699
  .child(h_flex().pt(8).gap(8).justify_end().children(actions));
245
1700
  }
246
1701
 
1702
+ // W-P3: the pi credential dialog, built from the four fields (pi-models.js makes the
1703
+ // models.json); «modo avanzado» swaps to the full-JSON paste from W-P2.
1704
+ renderPiCredential(p) {
1705
+ const t = theme();
1706
+ const label = (txt) => div().text_size(11).font_semibold().text_color(t.muted).child(txt);
1707
+ const input = (state) => Input.new(state).h(32).px(10).rounded(8).border_1().border_color(t.input).bg(t.background).text_size(12.5);
1708
+ if (this.advanced) {
1709
+ return this.renderDialog(`Credencial de ${p.agent}`, [
1710
+ div().text_size(11.5).text_color(t.dim).child("Modo avanzado: pega el models.json completo del agente. Se guarda en el orquestador y llega a cada run por stdin; no va en la imagen."),
1711
+ Input.new(this.provider).h(32).px(10).rounded(8).border_1().border_color(t.input).bg(t.background).text_size(12.5),
1712
+ Textarea.new(this.config).h(150).p(8).rounded(8).border_1().border_color(t.input).bg(t.background).text_size(12),
1713
+ ], [
1714
+ this.button("cred-back", "Volver", false, () => closeOverlay(p.overlay)),
1715
+ this.button("cred-mode", "Usar el formulario", false, (cx) => this.toggleMode(cx)),
1716
+ this.button("cred-save", this.busy ? "Guardando…" : "Guardar", true, (cx) => this.saveCredential(cx)),
1717
+ ], true);
1718
+ }
1719
+ return this.renderDialog("Credencial de pi · modelo local / OpenAI-compatible", [
1720
+ div().text_size(11.5).text_color(t.dim).child("Pi se conecta a un endpoint compatible (Ollama, LM Studio, vLLM, una LAN…). El wizard monta el models.json por ti; no se comprueba la red: se guarda tal cual. La lista de modelos se carga sola al salir del campo URL."),
1721
+ label("NOMBRE DEL PROVIDER"),
1722
+ input(this.piName),
1723
+ label("BASE URL"),
1724
+ input(this.piUrl),
1725
+ div().text_size(11).text_color(t.dim).child("Si no le pones ruta, se añade /v1 (donde suelen servir estos servidores)."),
1726
+ label("API KEY (OPCIONAL)"),
1727
+ input(this.piKey),
1728
+ div().text_size(11).text_color(t.dim).child("Vacía conserva la clave que ya tenía este provider (por seguridad no se muestra); si nunca tuvo, se guarda «none», que pi acepta con servidores que no la comprueban."),
1729
+ // W-P5: no «Cargar» button and no duplicated MODELOS field: the list loads on the
1730
+ // URL blur (tiny animated line while waiting) and the checkboxes are the only UI.
1731
+ ...(this.piListBusy
1732
+ ? [h_flex().id("pi-loading").gap(6).items_center().child(div().text_size(11).text_color(t.working)
1733
+ .child(`Cargando modelos del provider ${"·".repeat(this.piSpin + 1)}`))]
1734
+ : []),
1735
+ // Criterio 1: with an unreachable URL the only fallback is this compact manual field.
1736
+ ...(this.piListError
1737
+ ? [div().id("pi-list-error").text_size(11).text_color(t.blocked).child(this.piListError),
1738
+ label("MODELOS (IDS, UNO POR LÍNEA)"),
1739
+ Textarea.new(this.piModels).h(72).p(8).rounded(8).border_1().border_color(t.input).bg(t.background).text_size(12)]
1740
+ : []),
1741
+ ...(this.piModelList
1742
+ ? [div().text_size(11).text_color(t.dim)
1743
+ .child(`${this.piModelList.length} del provider: marca los que vayas a usar; solo esos entran en el models.json.`),
1744
+ ...[...new Set([...this.piModelList, ...this.checkedModels()])].map((id) => {
1745
+ const on = this.checkedModels().includes(id);
1746
+ return h_flex().id(`pi-model-${slug(id)}`).gap(8).items_center().px(4).py(2).rounded(UI.radius).cursor_pointer()
1747
+ .hover((s) => s.bg(t.hover))
1748
+ .on_click((_e, cx) => this.togglePiModel(cx, id))
1749
+ .child(div().w(34).text_size(UI.text.body).text_color(on ? t.working : t.dim).child(on ? "[x]" : "[ ]"))
1750
+ .child(div().flex_1().text_size(UI.text.small).text_color(t.foreground).truncate().child(id));
1751
+ })]
1752
+ : []),
1753
+ // Elegir modelo de trabajo por defecto y «para sugerencias» solo entre los marcados.
1754
+ ...(this.checkedModels().length > 0 ? [this.piDefaultModelArea(), this.piSuggestionsArea()] : []),
1755
+ ], [
1756
+ this.button("cred-back", "Volver", false, () => closeOverlay(p.overlay)),
1757
+ this.button("cred-mode", "Modo avanzado: pegar JSON", false, (cx) => this.toggleMode(cx)),
1758
+ this.button("cred-save", this.busy ? "Guardando…" : "Guardar", true, (cx) => this.saveCredential(cx)),
1759
+ ], true);
1760
+ }
1761
+
1762
+ toggleMode(cx) {
1763
+ this.advanced = !this.advanced;
1764
+ this.error = null;
1765
+ cx.notify();
1766
+ }
1767
+
1768
+ /** D-M1: «modelo por defecto» se elige entre los marcados; primero con tools si se puede. */
1769
+ piDefaultModelArea() {
1770
+ const t = theme();
1771
+ const cur = this.currentDefault();
1772
+ const row = (domId, value, text) => {
1773
+ const on = cur === value;
1774
+ return h_flex().id(domId).gap(8).items_center().px(4).py(2).rounded(UI.radius).cursor_pointer()
1775
+ .hover((s) => s.bg(t.hover))
1776
+ .on_click((_e, cx) => this.setPiDefault(cx, value))
1777
+ .child(div().w(34).text_size(UI.text.body).text_color(on ? t.working : t.dim).child(on ? "[•]" : "[ ]"))
1778
+ .child(div().flex_1().text_size(UI.text.small).text_color(t.foreground).truncate().child(text));
1779
+ };
1780
+ return v_flex().gap(2)
1781
+ .child(div().text_size(11).font_semibold().text_color(t.muted).child("MODELO DE TRABAJO POR DEFECTO"))
1782
+ .children(this.checkedModels().map((id) =>
1783
+ row(`pi-def-${slug(id)}`, id, id + (this.piDefault === undefined && cur === id ? " · sugerido" : ""))))
1784
+ .child(row("pi-def-none", null, "sin modelo por defecto"))
1785
+ .child(div().text_size(11).text_color(t.dim)
1786
+ .child("Se usa en los runs de tickets que no especifiquen modelo. Si el ticket trae uno explícito, manda el del ticket."));
1787
+ }
1788
+
1789
+ /** W-P4: «para sugerencias» se elige solo entre los marcados; la heurística propone
1790
+ * cuando nadie ha tocado todavía, y «sin sugerencias» guarda null. */
1791
+ piSuggestionsArea() {
1792
+ const t = theme();
1793
+ const cur = this.currentSuggest();
1794
+ const row = (domId, value, text) => {
1795
+ const on = cur === value;
1796
+ return h_flex().id(domId).gap(8).items_center().px(4).py(2).rounded(UI.radius).cursor_pointer()
1797
+ .hover((s) => s.bg(t.hover))
1798
+ .on_click((_e, cx) => this.setPiSuggest(cx, value))
1799
+ .child(div().w(34).text_size(UI.text.body).text_color(on ? t.working : t.dim).child(on ? "[•]" : "[ ]"))
1800
+ .child(div().flex_1().text_size(UI.text.small).text_color(t.foreground).truncate().child(text));
1801
+ };
1802
+ return v_flex().gap(2)
1803
+ .child(div().text_size(11).font_semibold().text_color(t.muted).child("MODELO PARA SUGERENCIAS"))
1804
+ .children(this.checkedModels().map((id) =>
1805
+ row(`pi-sug-${slug(id)}`, id, id + (this.piSuggest === undefined && cur === id ? " · sugerido" : ""))))
1806
+ .child(row("pi-sug-none", null, "sin sugerencias"))
1807
+ .child(div().text_size(11).text_color(t.dim)
1808
+ .child("Lo usa el paquete supi dentro del contenedor. Mientras la imagen del runner no lo incluya (P2 del plan de la imagen, pendiente), la elección se guarda y queda inactiva."));
1809
+ }
1810
+
247
1811
  render() {
248
1812
  const t = theme();
249
1813
  const p = props() ?? {};
1814
+ if (this.view === "credential" && this.isPi) return this.renderPiCredential(p);
250
1815
  if (this.view === "credential") {
251
1816
  return this.renderDialog(`Credencial de ${p.agent}`, [
252
- div().text_size(11.5).text_color(t.dim).child("Pega la config del agente tras iniciar sesión (D7). Se guarda en el orquestador y llega a cada run por stdin; no va en la imagen."),
1817
+ div().text_size(11.5).text_color(t.dim).child("Pega la config del agente tras iniciar sesión. Se guarda en el orquestador y llega a cada run por stdin; no va en la imagen."),
253
1818
  Input.new(this.provider).h(32).px(10).rounded(8).border_1().border_color(t.input).bg(t.background).text_size(12.5),
254
1819
  Textarea.new(this.config).h(150).p(8).rounded(8).border_1().border_color(t.input).bg(t.background).text_size(12),
255
1820
  ], [
256
1821
  this.button("cred-back", "Volver", false, () => closeOverlay(p.overlay)),
257
1822
  this.button("cred-save", this.busy ? "Guardando…" : "Guardar", true, (cx) => this.saveCredential(cx)),
258
- ]);
259
- }
260
- if (this.view === "rebuild") {
261
- return this.renderDialog("¿Reconstruir la imagen del runner?", [
262
- div().text_size(12.5).text_color(t.muted).child("Trae las versiones fijadas de bond, hc y los agentes. Puede tardar minutos. No toca las credenciales."),
263
- ], [
264
- this.button("rb-back", "Volver", false, () => closeOverlay(p.overlay)),
265
- this.button("rb-go", this.busy ? "Reconstruyendo…" : "Rebuild", true, (cx) => this.rebuild(cx)),
266
- ]);
1823
+ ], true);
267
1824
  }
268
- return this.renderPanel();
1825
+ if (this.view === "agy-login") return this.renderAgyLogin(p);
1826
+ return this.renderSettings();
269
1827
  }
270
1828
  }