@jmanuelcorral/bond-app 0.2.2 → 0.3.1

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.
@@ -1,6 +1,7 @@
1
1
  import type { DatabaseSync } from 'node:sqlite';
2
+ import type { LoopState } from '../core/loop.ts';
2
3
  import { randomUUID } from 'node:crypto';
3
- import { ACTIVE_TIMEOUT_STATES, type Run, type RunState, type FailureReason, type HubAnalysis, type RepoDelivery } from '../types.ts';
4
+ import { ACTIVE_TIMEOUT_STATES, type Run, type RunState, type FailureReason, type HubAnalysis, type RepoDelivery, type LoopConfig } from '../types.ts';
4
5
 
5
6
  export class RunRepository {
6
7
  private db: DatabaseSync;
@@ -87,7 +88,7 @@ export class RunRepository {
87
88
  const stmt = this.db.prepare(`
88
89
  UPDATE runs SET
89
90
  state = ?, failure_reason = ?, container_id = ?, container_name = ?,
90
- hc_machine = ?, hc_terminal = ?, cost_usd = ?, cleanup_pending = ?,
91
+ hc_machine = ?, hc_terminal = ?, agent_override = ?, model_override = ?, resume_at = ?, resume_agent = ?, loop_state = ?, loop_iteration = ?, loop_stalls = ?, loop_config = ?, cost_usd = ?, cleanup_pending = ?,
91
92
  verify_failures = ?, pr_url = ?, pr_number = ?, hub_analysis = ?, repo_states = ?,
92
93
  active_ms = ?, last_active_at = ?,
93
94
  started_at = ?, finished_at = ?, updated_at = ?, created_at = ?
@@ -101,6 +102,14 @@ export class RunRepository {
101
102
  merged.container_name || null,
102
103
  merged.hc_machine || null,
103
104
  merged.hc_terminal || null,
105
+ merged.agent_override || null,
106
+ merged.model_override || null,
107
+ merged.resume_at || null,
108
+ merged.resume_agent || null,
109
+ merged.loop_state || null,
110
+ merged.loop_iteration || 0,
111
+ merged.loop_stalls || 0,
112
+ merged.loop_config ? JSON.stringify(merged.loop_config) : null,
104
113
  merged.cost_usd,
105
114
  merged.cleanup_pending ? 1 : 0,
106
115
  merged.verify_failures || 0,
@@ -153,7 +162,7 @@ export class RunRepository {
153
162
  const stmt = this.db.prepare(`
154
163
  UPDATE runs SET
155
164
  state = ?, failure_reason = ?, container_id = ?, container_name = ?,
156
- hc_machine = ?, hc_terminal = ?, cost_usd = ?, cleanup_pending = ?,
165
+ hc_machine = ?, hc_terminal = ?, agent_override = ?, model_override = ?, resume_at = ?, resume_agent = ?, loop_state = ?, loop_iteration = ?, loop_stalls = ?, loop_config = ?, cost_usd = ?, cleanup_pending = ?,
157
166
  verify_failures = ?, pr_url = ?, pr_number = ?, hub_analysis = ?, repo_states = ?,
158
167
  active_ms = ?, last_active_at = ?,
159
168
  started_at = ?, finished_at = ?, updated_at = ?
@@ -167,6 +176,14 @@ export class RunRepository {
167
176
  merged.container_name || null,
168
177
  merged.hc_machine || null,
169
178
  merged.hc_terminal || null,
179
+ merged.agent_override || null,
180
+ merged.model_override || null,
181
+ merged.resume_at || null,
182
+ merged.resume_agent || null,
183
+ merged.loop_state || null,
184
+ merged.loop_iteration || 0,
185
+ merged.loop_stalls || 0,
186
+ merged.loop_config ? JSON.stringify(merged.loop_config) : null,
170
187
  merged.cost_usd,
171
188
  merged.cleanup_pending ? 1 : 0,
172
189
  merged.verify_failures || 0,
@@ -205,6 +222,14 @@ export class RunRepository {
205
222
  container_name: row.container_name ? String(row.container_name) : undefined,
206
223
  hc_machine: row.hc_machine ? String(row.hc_machine) : undefined,
207
224
  hc_terminal: row.hc_terminal ? String(row.hc_terminal) : undefined,
225
+ agent_override: row.agent_override ? String(row.agent_override) : undefined,
226
+ model_override: row.model_override ? String(row.model_override) : undefined,
227
+ resume_at: row.resume_at ? String(row.resume_at) : undefined,
228
+ resume_agent: row.resume_agent ? String(row.resume_agent) : undefined,
229
+ loop_state: row.loop_state ? (String(row.loop_state) as LoopState) : undefined,
230
+ loop_iteration: Number(row.loop_iteration || 0),
231
+ loop_stalls: Number(row.loop_stalls || 0),
232
+ loop_config: parseLoopConfig(row.loop_config),
208
233
  cost_usd: Number(row.cost_usd),
209
234
  cleanup_pending: Boolean(row.cleanup_pending),
210
235
  verify_failures: Number(row.verify_failures || 0),
@@ -222,6 +247,16 @@ export class RunRepository {
222
247
  }
223
248
  }
224
249
 
250
+ function parseLoopConfig(raw: unknown): LoopConfig | undefined {
251
+ if (!raw) return undefined;
252
+ try {
253
+ const parsed = JSON.parse(String(raw)) as LoopConfig;
254
+ return parsed && typeof parsed === 'object' ? parsed : undefined;
255
+ } catch {
256
+ return undefined;
257
+ }
258
+ }
259
+
225
260
  function parseAnalysis(raw: unknown): HubAnalysis | undefined {
226
261
  if (!raw) return undefined;
227
262
  try {
@@ -14,8 +14,12 @@ import {
14
14
  type AgentCredentialSummary,
15
15
  type GitHubCredentialSummary,
16
16
  type AzureDevOpsCredentialSummary,
17
+ type AzureLoginSummary,
17
18
  type JiraCredential,
18
19
  type JiraCredentialSummary,
20
+ LOOP_DEFAULT_MAX_ITERATIONS,
21
+ LOOP_DEFAULT_STALL_ITERATIONS,
22
+ LOOP_MAX_ITERATIONS_LIMIT,
19
23
  } from '../types.ts';
20
24
  import { APT_PACKAGE_RE, DEFAULT_TOOLS, TOOL_IDS } from '../runner/tool-catalog.ts';
21
25
 
@@ -56,6 +60,70 @@ export function credentialAccount(agent: string, config: string | null | undefin
56
60
  return undefined;
57
61
  }
58
62
 
63
+ /** Issue #4 (D3): the Azure session lives in agent_credentials under this key (not an agent). */
64
+ export const AZURE_LOGIN_KEY = 'azure-login';
65
+ /** About how long the refresh token of a device-code login lasts (Entra ID: 90 days). */
66
+ export const AZURE_LOGIN_DAYS = 90;
67
+
68
+ /** What bond-app keeps of an `az login`: the two files of ~/.azure, and the default subscription. */
69
+ export interface AzureLoginDoc {
70
+ version: 1;
71
+ /** ~/.azure/azureProfile.json, as az wrote it (without the BOM). */
72
+ profile: string;
73
+ /** ~/.azure/msal_token_cache.json (the tokens: never shown, never logged). */
74
+ msal: string;
75
+ subscription_id: string | null;
76
+ }
77
+
78
+ type AzureProfile = { subscriptions?: Array<{ id?: unknown; name?: unknown; tenantId?: unknown; isDefault?: unknown; user?: { name?: unknown } }> };
79
+
80
+ /** The subscriptions of an azureProfile.json ({id, name, tenant_id, default}); [] when unreadable. */
81
+ export function azureSubscriptions(profileText: string): Array<{ id: string; name: string; tenant_id: string; default: boolean; user: string }> {
82
+ try {
83
+ const doc = JSON.parse(profileText.replace(/^\uFEFF/, '')) as AzureProfile;
84
+ return (doc.subscriptions ?? [])
85
+ .filter((s) => typeof s?.id === 'string' && s.id)
86
+ .map((s) => ({
87
+ id: String(s.id),
88
+ name: typeof s.name === 'string' ? s.name : String(s.id),
89
+ tenant_id: typeof s.tenantId === 'string' ? s.tenantId : '',
90
+ default: s.isDefault === true,
91
+ user: typeof s.user?.name === 'string' ? s.user.name : '',
92
+ }));
93
+ } catch {
94
+ return [];
95
+ }
96
+ }
97
+
98
+ /** The stored Azure session as Ajustes shows it (no tokens). */
99
+ export function azureLoginSummary(configJson: string | null | undefined, updatedAt?: string, now = Date.now()): AzureLoginSummary {
100
+ if (!configJson) return { configured: false };
101
+ let doc: AzureLoginDoc;
102
+ try {
103
+ doc = JSON.parse(configJson) as AzureLoginDoc;
104
+ } catch {
105
+ return { configured: false };
106
+ }
107
+ const subs = azureSubscriptions(doc.profile ?? '');
108
+ const chosen = subs.find((s) => s.id === doc.subscription_id) ?? subs.find((s) => s.default) ?? subs[0] ?? null;
109
+ const out: AzureLoginSummary = {
110
+ configured: true,
111
+ user: chosen?.user || subs[0]?.user || undefined,
112
+ tenant_id: chosen?.tenant_id || undefined,
113
+ subscription: chosen ? { id: chosen.id, name: chosen.name } : null,
114
+ subscriptions: subs.map((s) => ({ id: s.id, name: s.name, tenant_id: s.tenant_id })),
115
+ };
116
+ if (updatedAt) {
117
+ out.updated_at = updatedAt;
118
+ const ends = Date.parse(updatedAt) + AZURE_LOGIN_DAYS * 24 * 3600 * 1000;
119
+ if (Number.isFinite(ends)) {
120
+ out.expires_at = new Date(ends).toISOString();
121
+ out.expired = ends <= now;
122
+ }
123
+ }
124
+ return out;
125
+ }
126
+
59
127
  /**
60
128
  * pi's models.json with every provider keyed: Ajustes never shows the saved key, so a provider
61
129
  * saved without one keeps the key it already had (same provider name), and one that never had
@@ -243,6 +311,49 @@ export class SettingsRepository {
243
311
  return res.changes > 0;
244
312
  }
245
313
 
314
+ /** Issue #4: keep the Azure session of a device-code login (replaces the previous one). */
315
+ setAzureLogin(doc: AzureLoginDoc): AzureLoginSummary {
316
+ const now = new Date().toISOString();
317
+ this.db.prepare(`
318
+ INSERT INTO agent_credentials (agent, provider, config_json, updated_at)
319
+ VALUES (?, ?, ?, ?)
320
+ ON CONFLICT(agent) DO UPDATE SET provider = excluded.provider, config_json = excluded.config_json, updated_at = excluded.updated_at
321
+ `).run(AZURE_LOGIN_KEY, 'device-code', JSON.stringify(doc), now);
322
+ return azureLoginSummary(JSON.stringify(doc), now);
323
+ }
324
+
325
+ /** The stored Azure session (files and subscription), or null. Only for injecting it in a run. */
326
+ getAzureLogin(): AzureLoginDoc | null {
327
+ const row = this.db.prepare('SELECT config_json FROM agent_credentials WHERE agent = ?').get(AZURE_LOGIN_KEY) as { config_json?: string } | undefined;
328
+ if (!row?.config_json) return null;
329
+ try {
330
+ return JSON.parse(String(row.config_json)) as AzureLoginDoc;
331
+ } catch {
332
+ return null;
333
+ }
334
+ }
335
+
336
+ getAzureLoginSummary(now = Date.now()): AzureLoginSummary {
337
+ const row = this.db.prepare('SELECT config_json, updated_at FROM agent_credentials WHERE agent = ?').get(AZURE_LOGIN_KEY) as { config_json?: string; updated_at?: string } | undefined;
338
+ return azureLoginSummary(row?.config_json ?? null, row?.updated_at ? String(row.updated_at) : undefined, now);
339
+ }
340
+
341
+ /** The default subscription for the runs: one of the session's. Keeps the login's date. */
342
+ setAzureSubscription(subscriptionId: string): AzureLoginSummary {
343
+ const doc = this.getAzureLogin();
344
+ if (!doc) throw new Error('No hay sesión de Azure: inicia sesión en Ajustes → Azure');
345
+ if (!azureSubscriptions(doc.profile).some((s) => s.id === subscriptionId)) {
346
+ throw new Error(`La suscripción '${subscriptionId}' no es de esta sesión de Azure`);
347
+ }
348
+ this.db.prepare('UPDATE agent_credentials SET config_json = ? WHERE agent = ?').run(JSON.stringify({ ...doc, subscription_id: subscriptionId }), AZURE_LOGIN_KEY);
349
+ return this.getAzureLoginSummary();
350
+ }
351
+
352
+ /** «Cerrar sesión de Azure»: forget the session. */
353
+ deleteAzureLogin(): boolean {
354
+ return this.db.prepare('DELETE FROM agent_credentials WHERE agent = ?').run(AZURE_LOGIN_KEY).changes > 0;
355
+ }
356
+
246
357
  /** D20: store (or replace) the GitHub credential taken from the user's gh session. */
247
358
  setGitHubCredential(token: string, login?: string | null): GitHubCredentialSummary {
248
359
  if (!validateGitHubToken(token)) {
@@ -420,6 +531,33 @@ export class SettingsRepository {
420
531
  // A small key/value store of the orchestrator's own configuration state. Only the
421
532
  // selection and the setup_done flag live here; credentials stay in their own tables.
422
533
 
534
+ /** LOOP P1 (issue #2): the loop defaults of Ajustes (a new ticket's iterations; stall rounds). */
535
+ getLoopDefaults(): { max_iterations: number; stall_iterations: number } {
536
+ const num = (key: string, fallback: number) => {
537
+ const v = Number(this.getSetting(key));
538
+ return Number.isInteger(v) && v >= 1 && v <= LOOP_MAX_ITERATIONS_LIMIT ? v : fallback;
539
+ };
540
+ return {
541
+ max_iterations: num('loop_default_max_iterations', LOOP_DEFAULT_MAX_ITERATIONS),
542
+ stall_iterations: num('loop_stall_iterations', LOOP_DEFAULT_STALL_ITERATIONS),
543
+ };
544
+ }
545
+
546
+ saveLoopDefaults(input: { max_iterations?: unknown; stall_iterations?: unknown }): { max_iterations: number; stall_iterations: number } {
547
+ const check = (name: string, v: unknown) => {
548
+ if (v === undefined) return undefined;
549
+ if (typeof v !== 'number' || !Number.isInteger(v) || v < 1 || v > LOOP_MAX_ITERATIONS_LIMIT) {
550
+ throw new Error(`Field '${name}' must be an integer from 1 to ${LOOP_MAX_ITERATIONS_LIMIT}`);
551
+ }
552
+ return v;
553
+ };
554
+ const max = check('max_iterations', input.max_iterations);
555
+ const stall = check('stall_iterations', input.stall_iterations);
556
+ if (max !== undefined) this.setSetting('loop_default_max_iterations', String(max));
557
+ if (stall !== undefined) this.setSetting('loop_stall_iterations', String(stall));
558
+ return this.getLoopDefaults();
559
+ }
560
+
423
561
  getSetting(key: string): string | null {
424
562
  const row = this.db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as
425
563
  | { value?: string }
@@ -9,6 +9,9 @@ import {
9
9
  SUPPORTED_AGENTS,
10
10
  validateBranchName,
11
11
  validateVerifyCommands,
12
+ LOOP_DEFAULT_MAX_ITERATIONS,
13
+ LOOP_MAX_ITERATIONS_LIMIT,
14
+ type TicketLoop,
12
15
  type Ticket,
13
16
  type CreateTicketInput,
14
17
  type RunState,
@@ -250,6 +253,8 @@ export class TicketRepository {
250
253
  if (input.docker !== undefined && typeof input.docker !== 'boolean') {
251
254
  throw new Error("Field 'docker' must be a boolean");
252
255
  }
256
+ validateAzureFields(input);
257
+ const loop = this.normalizeLoop(input.loop, Boolean(layout.hub_url) || (layout.repos?.length ?? 0) >= 2);
253
258
  if (layoutBases(layout).includes(targetBranch)) {
254
259
  throw new Error('target_branch must differ from base_branch: a run only pushes its own branch (P4)');
255
260
  }
@@ -260,8 +265,9 @@ export class TicketRepository {
260
265
  INSERT INTO tickets (
261
266
  id, title, description, repo_url, base_branch, target_branch,
262
267
  budget_usd, timeout_minutes, agent, model, prompt, verify_commands,
263
- hub_url, hub_base, repos, repo_agents, issue_url, story, source_pr_url, team_engine, bondify, docker, status, created_at, updated_at
264
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
268
+ hub_url, hub_base, repos, repo_agents, issue_url, story, source_pr_url, team_engine, bondify, docker,
269
+ azure_login, azure_subscription, loop_enabled, loop_max_iterations, status, created_at, updated_at
270
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
265
271
  `);
266
272
 
267
273
  const teamEngine = input.team_engine === 'herdr' ? 'herdr' : 'hc';
@@ -289,6 +295,10 @@ export class TicketRepository {
289
295
  teamEngine,
290
296
  bondify ? 1 : 0,
291
297
  input.docker === true ? 1 : 0,
298
+ input.azure_login === true ? 1 : 0,
299
+ input.azure_login === true && input.azure_subscription ? input.azure_subscription : null,
300
+ loop.enabled ? 1 : 0,
301
+ loop.max_iterations,
292
302
  status,
293
303
  now,
294
304
  now
@@ -297,6 +307,37 @@ export class TicketRepository {
297
307
  return this.get(id)!;
298
308
  }
299
309
 
310
+ /**
311
+ * LOOP P1: `{ enabled, max_iterations? }` → TicketLoop. Without max_iterations, the current
312
+ * one (an update) or Ajustes' default; null = no limit. Enabled only on hub tickets (v1, D7).
313
+ */
314
+ private normalizeLoop(raw: unknown, isHub: boolean, current?: TicketLoop): TicketLoop {
315
+ if (raw === undefined || raw === null) return current ?? { enabled: false, max_iterations: this.loopDefaultMax() };
316
+ if (typeof raw !== 'object' || Array.isArray(raw)) throw new Error("Field 'loop' must be an object { enabled, max_iterations? }");
317
+ const r = raw as { enabled?: unknown; max_iterations?: unknown };
318
+ if (r.enabled !== undefined && typeof r.enabled !== 'boolean') throw new Error("Field 'loop.enabled' must be a boolean");
319
+ const enabled = r.enabled === true;
320
+ if (enabled && !isHub) throw new Error('El modo loop solo está disponible en tickets de hub');
321
+ let max: number | null;
322
+ if (r.max_iterations === undefined) max = current ? current.max_iterations : this.loopDefaultMax();
323
+ else if (r.max_iterations === null) max = null;
324
+ else if (typeof r.max_iterations === 'number' && Number.isInteger(r.max_iterations) && r.max_iterations >= 1 && r.max_iterations <= LOOP_MAX_ITERATIONS_LIMIT) max = r.max_iterations;
325
+ else throw new Error(`Field 'loop.max_iterations' must be an integer from 1 to ${LOOP_MAX_ITERATIONS_LIMIT}, or null for no limit`);
326
+ return { enabled, max_iterations: max };
327
+ }
328
+
329
+ /** Ajustes' default iterations for a new loop (app_settings), or the built-in one. */
330
+ private loopDefaultMax(): number {
331
+ try {
332
+ const row = this.db.prepare("SELECT value FROM app_settings WHERE key = 'loop_default_max_iterations'").get() as { value?: string } | undefined;
333
+ const v = Number(row?.value);
334
+ if (Number.isInteger(v) && v >= 1 && v <= LOOP_MAX_ITERATIONS_LIMIT) return v;
335
+ } catch {
336
+ /* no settings table yet */
337
+ }
338
+ return LOOP_DEFAULT_MAX_ITERATIONS;
339
+ }
340
+
300
341
  get(id: string): Ticket | null {
301
342
  const stmt = this.db.prepare('SELECT * FROM tickets WHERE id = ?');
302
343
  const row = stmt.get(id) as unknown as Record<string, unknown> | undefined;
@@ -316,7 +357,7 @@ export class TicketRepository {
316
357
  stmt.run(status, now, id);
317
358
  }
318
359
 
319
- update(id: string, updates: Partial<Ticket> & Partial<LayoutInput>): Ticket | null {
360
+ update(id: string, updates: Partial<Omit<Ticket, 'loop'>> & Partial<LayoutInput> & { loop?: CreateTicketInput['loop'] | TicketLoop }): Ticket | null {
320
361
  const existing = this.get(id);
321
362
  if (!existing) return null;
322
363
 
@@ -397,16 +438,23 @@ export class TicketRepository {
397
438
  if (updates.docker !== undefined && typeof updates.docker !== 'boolean') {
398
439
  throw new Error("Field 'docker' must be a boolean");
399
440
  }
441
+ validateAzureFields(updates);
442
+ const isHub = Boolean(layout.hub_url) || (layout.repos?.length ?? 0) >= 2;
443
+ // A ticket that stops being a hub loses its loop (v1: hub only); otherwise it keeps it.
444
+ const loop = updates.loop !== undefined
445
+ ? this.normalizeLoop(updates.loop, isHub, existing.loop)
446
+ : isHub ? (existing.loop ?? { enabled: false, max_iterations: LOOP_DEFAULT_MAX_ITERATIONS }) : { enabled: false, max_iterations: existing.loop?.max_iterations ?? null };
400
447
 
401
448
  // Preserve status: status is managed via run lifecycle, not arbitrary ticket patch
402
- const merged = { ...existing, ...updates, status: existing.status, updated_at: new Date().toISOString() };
449
+ const merged = { ...existing, ...updates, loop, status: existing.status, updated_at: new Date().toISOString() };
403
450
  this.assertTeamAgents(layout, merged.agent, repoAgents);
404
451
  const stmt = this.db.prepare(`
405
452
  UPDATE tickets SET
406
453
  title = ?, description = ?, repo_url = ?, base_branch = ?, target_branch = ?,
407
454
  budget_usd = ?, timeout_minutes = ?, agent = ?, model = ?, prompt = ?,
408
455
  verify_commands = ?, hub_url = ?, hub_base = ?, repos = ?, repo_agents = ?,
409
- issue_url = ?, story = ?, team_engine = ?, bondify = ?, docker = ?, status = ?, updated_at = ?
456
+ issue_url = ?, story = ?, team_engine = ?, bondify = ?, docker = ?, azure_login = ?, azure_subscription = ?,
457
+ loop_enabled = ?, loop_max_iterations = ?, status = ?, updated_at = ?
410
458
  WHERE id = ?
411
459
  `);
412
460
 
@@ -431,6 +479,10 @@ export class TicketRepository {
431
479
  merged.team_engine === 'herdr' ? 'herdr' : 'hc',
432
480
  merged.bondify ? 1 : 0,
433
481
  merged.docker ? 1 : 0,
482
+ merged.azure_login ? 1 : 0,
483
+ merged.azure_login && merged.azure_subscription ? merged.azure_subscription : null,
484
+ loop.enabled ? 1 : 0,
485
+ loop.max_iterations,
434
486
  merged.status,
435
487
  merged.updated_at,
436
488
  id
@@ -476,6 +528,12 @@ export class TicketRepository {
476
528
  team_engine: (row.team_engine === 'hc' ? 'hc' : 'herdr') as 'hc' | 'herdr',
477
529
  bondify: row.bondify !== null && row.bondify !== undefined ? Number(row.bondify) !== 0 : true,
478
530
  docker: Number(row.docker ?? 0) !== 0,
531
+ azure_login: Number(row.azure_login ?? 0) !== 0,
532
+ azure_subscription: row.azure_subscription ? String(row.azure_subscription) : null,
533
+ loop: {
534
+ enabled: Number(row.loop_enabled ?? 0) !== 0,
535
+ max_iterations: row.loop_max_iterations === null || row.loop_max_iterations === undefined ? null : Number(row.loop_max_iterations),
536
+ },
479
537
  status: row.status as RunState,
480
538
  created_at: String(row.created_at),
481
539
  updated_at: String(row.updated_at),
@@ -512,3 +570,14 @@ function parseRepoAgents(raw: unknown): Record<string, string> {
512
570
  return {};
513
571
  }
514
572
  }
573
+
574
+ /** Issue #4 (P2): «Login de Azure» is a boolean; its subscription a GUID or null. */
575
+ function validateAzureFields(input: { azure_login?: unknown; azure_subscription?: unknown }): void {
576
+ if (input.azure_login !== undefined && typeof input.azure_login !== 'boolean') {
577
+ throw new Error("Field 'azure_login' must be a boolean");
578
+ }
579
+ const sub = input.azure_subscription;
580
+ if (sub !== undefined && sub !== null && sub !== '' && !(typeof sub === 'string' && /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(sub))) {
581
+ throw new Error("Field 'azure_subscription' must be a subscription id (GUID) or null");
582
+ }
583
+ }
package/src/index.ts CHANGED
@@ -30,6 +30,8 @@ export async function bootstrap(configOverrides = {}, hooks: ServerHooks = {}) {
30
30
  );
31
31
 
32
32
  await orchestrator.start();
33
+ // «Hay versión nueva»: ask npm now and once a day (BOND_APP_UPDATE_CHECK=0 turns it off).
34
+ if (config.updateCheck) orchestrator.updates.start();
33
35
 
34
36
  const server = createServer(orchestrator, hooks);
35
37
 
@@ -82,6 +82,8 @@ export interface HcTerminalDetails {
82
82
  turn?: number;
83
83
  labels?: Record<string, string>;
84
84
  agent?: string;
85
+ /** `hc get`: the command the terminal runs (issue #3 tells the agent kind from it). */
86
+ argv?: string[];
85
87
  }
86
88
 
87
89
  export class HcClient {
@@ -179,6 +181,24 @@ export class HcClient {
179
181
  return res.address;
180
182
  }
181
183
 
184
+ /**
185
+ * Issue #3: end a terminal's program (`hc kill`: hangup, then escalate) and remove it
186
+ * (`hc rm`), so its name is free for the agent that replaces it. Already finished or gone is
187
+ * fine; the session files stay in the container.
188
+ */
189
+ async killTerminal(address: string): Promise<void> {
190
+ try {
191
+ await this.call(['kill', address, '--json']);
192
+ } catch {
193
+ /* already finished */
194
+ }
195
+ try {
196
+ await this.call(['rm', address, '--json']);
197
+ } catch {
198
+ /* already removed */
199
+ }
200
+ }
201
+
182
202
  /** Set labels on a terminal (`hc label <address> <key>=<value>`). */
183
203
  async labelTerminal(address: string, labels: Record<string, string>): Promise<void> {
184
204
  const args = Object.entries(labels).map(([k, v]) => `${k}=${v}`);
@@ -201,6 +221,7 @@ export class HcClient {
201
221
  cwd?: string;
202
222
  labels?: Record<string, string>;
203
223
  foreground?: { name?: string };
224
+ argv?: unknown;
204
225
  };
205
226
  const rawAgent = (res as any).agent || res.name || res.foreground?.name;
206
227
  const isGeneric = rawAgent === 'agent' || rawAgent === 'gru' || (typeof rawAgent === 'string' && /^t\d+$/.test(rawAgent));
@@ -215,13 +236,14 @@ export class HcClient {
215
236
  turn: typeof res.turn === 'number' ? res.turn : 0,
216
237
  labels: res.labels ?? {},
217
238
  agent,
239
+ argv: Array.isArray(res.argv) ? res.argv.map(String) : undefined,
218
240
  };
219
241
  }
220
242
 
221
243
  /**
222
244
  * P9: List live terminals across machines, or only terminals on a specific machine.
223
245
  */
224
- async listTerminals(machine?: string): Promise<Array<{
246
+ async listTerminals(machine?: string, opts: { all?: boolean } = {}): Promise<Array<{
225
247
  address: string;
226
248
  name?: string;
227
249
  cwd?: string;
@@ -232,7 +254,8 @@ export class HcClient {
232
254
  labels?: Record<string, string>;
233
255
  agent?: string;
234
256
  }>> {
235
- const res = (await this.call(['ls', '--json'])) as {
257
+ // --all: finished terminals too (issue #3 relaunches an agent whose program has ended).
258
+ const res = (await this.call(['ls', '--json', ...(opts.all ? ['--all'] : [])])) as {
236
259
  terminals?: Array<{
237
260
  address: string;
238
261
  name?: string;
@@ -268,8 +291,8 @@ export class HcClient {
268
291
  * P1 criterion 3: obtains state from `hc ls --json` without N+1 `hc get` per terminal,
269
292
  * falling back to `getTerminal` only if the data is missing from ls.
270
293
  */
271
- async getMachineTerminals(machine: string): Promise<HcTerminalDetails[]> {
272
- const listed = await this.listTerminals(machine);
294
+ async getMachineTerminals(machine: string, opts: { all?: boolean } = {}): Promise<HcTerminalDetails[]> {
295
+ const listed = await this.listTerminals(machine, opts);
273
296
  const details = await Promise.all(
274
297
  listed.map(async (t) => {
275
298
  const hasStatus = t.status !== undefined;