@jmanuelcorral/bond-app 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,98 @@
1
+ /**
2
+ * jmanuelcorral/bond#92 (and bond-app#3): with a small context window, pi's default
3
+ * auto-compaction (start with 16384 tokens free) comes too late. One big tool result jumps
4
+ * over the threshold, and then the summary request, sent to the same model, no longer fits.
5
+ * The agent is then left idle without telling anyone (NAV-4588: flash-halogen at 131K stalled
6
+ * at ~126K).
7
+ *
8
+ * bond writes `compaction.modelOverrides` on the machine through `bond models`. In a run, pi's
9
+ * models.json comes from Ajustes (the stored credential), not from bond's config.toml. So
10
+ * bond-app derives the same overrides from that models.json and merges them into the
11
+ * container's ~/.pi/agent/settings.json. The formula is bond's `piCompactionFor`; keep the two
12
+ * in step.
13
+ */
14
+
15
+ /** Up to this contextWindow, compaction is tuned. */
16
+ export const PI_COMPACTION_MAX_CONTEXT = 200_000;
17
+ const PI_DEFAULT_RESERVE = 16_384;
18
+
19
+ export interface PiCompaction {
20
+ reserveTokens: number;
21
+ keepRecentTokens: number;
22
+ }
23
+
24
+ /** The tuning for a contextWindow, or null when it is large or unknown. */
25
+ export function piCompactionFor(context: unknown): PiCompaction | null {
26
+ if (typeof context !== 'number' || !Number.isFinite(context) || context <= 0 || context > PI_COMPACTION_MAX_CONTEXT) return null;
27
+ // Compact with 25 % free (never later than pi's default), but never past half the window.
28
+ const reserveTokens = Math.min(Math.max(PI_DEFAULT_RESERVE, Math.ceil(context * 0.25)), Math.floor(context / 2));
29
+ const keepRecentTokens = Math.min(20_000, Math.floor(context * 0.12));
30
+ return { reserveTokens, keepRecentTokens };
31
+ }
32
+
33
+ /** `provider/model` → tuning for every small-window model in a pi models.json; {} if unreadable. */
34
+ export function piCompactionOverrides(modelsJson: string): Record<string, PiCompaction> {
35
+ let parsed: unknown;
36
+ try {
37
+ parsed = JSON.parse(modelsJson);
38
+ } catch {
39
+ return {};
40
+ }
41
+ const providers = (parsed as { providers?: unknown })?.providers;
42
+ if (!providers || typeof providers !== 'object') return {};
43
+ const out: Record<string, PiCompaction> = {};
44
+ for (const [providerId, provider] of Object.entries(providers as Record<string, unknown>)) {
45
+ const models = (provider as { models?: unknown })?.models;
46
+ if (!Array.isArray(models)) continue;
47
+ for (const m of models) {
48
+ const id = (m as { id?: unknown })?.id;
49
+ const value = piCompactionFor((m as { contextWindow?: unknown })?.contextWindow);
50
+ if (typeof id === 'string' && value) out[`${providerId}/${id}`] = value;
51
+ }
52
+ }
53
+ return out;
54
+ }
55
+
56
+ /**
57
+ * Runs in the container (serialized, plain JS): merges the overrides read on stdin into
58
+ * ~/.pi/agent/settings.json and keeps every other key. An entry already there wins (it was set
59
+ * by hand or baked in the image). Prints how many it added.
60
+ */
61
+ function piCompactionMergeInContainer() {
62
+ const fs = require('node:fs');
63
+ const path = require('node:path');
64
+ const overrides: Record<string, unknown> = JSON.parse(fs.readFileSync(0, 'utf8'));
65
+ // `node -e <script> <file>`: argv[1] is the settings.json to merge into.
66
+ const file = process.argv[1] || path.join(process.env.HOME || '/home/runner', '.pi', 'agent', 'settings.json');
67
+ let settings: any = {};
68
+ try {
69
+ settings = JSON.parse(fs.readFileSync(file, 'utf8'));
70
+ } catch {
71
+ settings = {};
72
+ }
73
+ if (!settings || typeof settings !== 'object' || Array.isArray(settings)) settings = {};
74
+ const compaction = settings.compaction && typeof settings.compaction === 'object' ? settings.compaction : {};
75
+ const current = compaction.modelOverrides && typeof compaction.modelOverrides === 'object' ? compaction.modelOverrides : {};
76
+ let added = 0;
77
+ for (const key of Object.keys(overrides)) {
78
+ if (!(key in current)) {
79
+ current[key] = overrides[key];
80
+ added++;
81
+ }
82
+ }
83
+ if (!added) {
84
+ process.stdout.write('added=0\n');
85
+ return;
86
+ }
87
+ compaction.modelOverrides = current;
88
+ settings.compaction = compaction;
89
+ fs.mkdirSync(path.dirname(file), { recursive: true });
90
+ fs.writeFileSync(file + '.tmp', JSON.stringify(settings, null, 2) + '\n', { mode: 0o600 });
91
+ fs.renameSync(file + '.tmp', file);
92
+ process.stdout.write('added=' + added + '\n');
93
+ }
94
+
95
+ /** The command that merges the overrides (JSON on stdin) into `settingsPath`, as runner. */
96
+ export function piCompactionCommand(settingsPath: string): string[] {
97
+ return ['sh', '-c', 'set -eu; umask 077; exec node -e "$1" "$2"', 'bond-pi-compaction', `(${piCompactionMergeInContainer.toString()})()`, settingsPath];
98
+ }
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Issue #3 P3: telling that a run's agent is stuck, without its help. NAV-4588's gru sat idle
3
+ * for 22 hours with a full context and nobody noticed.
4
+ *
5
+ * - A full context (pi): the tail of its newest session file shows answers cut by length with
6
+ * next to no output, or the context near the model's window. Compaction no longer helps: the
7
+ * summary request goes to the same model, which has no room left.
8
+ * - An exhausted budget (any agent): its screen says so (Claude's usage limit, codex's, a
9
+ * quota…). Its window may accept nothing, so the screen is the only witness. The hooks behind
10
+ * `bond budget` are not known to work inside the container.
11
+ *
12
+ * Only for an agent that is not working. The verdict becomes the run's waiting reason, and the
13
+ * panel offers «Relanzar con resumen» on it.
14
+ */
15
+
16
+ export type StuckKind = 'context' | 'budget';
17
+
18
+ export interface StuckFinding {
19
+ kind: StuckKind;
20
+ /** Short facts for the reason: «126K de 131K», «se restablece a las 3pm». */
21
+ detail: string | null;
22
+ /** P4: when an exhausted budget comes back, as the screen says it («3pm (Europe/Madrid)»). */
23
+ resets?: string | null;
24
+ }
25
+
26
+ /** Messages agents print when their plan or quota is used up (lower-cased match). */
27
+ const BUDGET_PATTERNS: RegExp[] = [
28
+ /usage limit/i,
29
+ /hit your (usage )?limit/i,
30
+ /(5-hour|weekly|daily|monthly) limit reached/i,
31
+ /limit reached\b.*\bresets?\b/i,
32
+ /quota (exceeded|exhausted|reached)/i,
33
+ /exceeded your (current )?quota/i,
34
+ /out of (credits|tokens)/i,
35
+ /insufficient (credits|quota|balance)/i,
36
+ /rate limit exceeded.*(plan|upgrade)/i,
37
+ ];
38
+
39
+ /** When the screen says the budget comes back («resets 3pm», «resets at 15:00», «try again in 2h»). */
40
+ const RESET_PATTERNS: RegExp[] = [
41
+ /resets?\s+(?:at\s+)?([0-9]{1,2}(?::[0-9]{2})?\s*(?:am|pm)?(?:\s*\([^)]{1,40}\))?)/i,
42
+ /try again (?:in|at)\s+([^.\n]{1,30})/i,
43
+ ];
44
+
45
+ /** The last lines of an agent's screen tell an exhausted budget, and when it resets. */
46
+ export function budgetExhaustedIn(screen: string): StuckFinding | null {
47
+ // The bottom of the screen only: the notice is the agent's last word, and a limit mentioned
48
+ // earlier (in code or docs it read) is not a verdict.
49
+ const tail = screen.split('\n').slice(-25).join('\n');
50
+ if (!BUDGET_PATTERNS.some((re) => re.test(tail))) return null;
51
+ let resets: string | null = null;
52
+ for (const re of RESET_PATTERNS) {
53
+ const m = re.exec(tail);
54
+ if (m) {
55
+ resets = m[1].trim();
56
+ break;
57
+ }
58
+ }
59
+ return { kind: 'budget', detail: resets ? `se restablece a las ${resets}` : null, resets };
60
+ }
61
+
62
+ /** The wall-clock offset (ms) of an IANA zone at an instant, or null for an unknown zone. */
63
+ function zoneOffsetMs(at: Date, timeZone: string): number | null {
64
+ try {
65
+ const parts = Object.fromEntries(
66
+ new Intl.DateTimeFormat('en-US', { timeZone, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' })
67
+ .formatToParts(at)
68
+ .map((x) => [x.type, x.value])
69
+ );
70
+ const wall = Date.UTC(+parts.year, +parts.month - 1, +parts.day, +parts.hour % 24, +parts.minute, +parts.second);
71
+ return wall - Math.floor(at.getTime() / 1000) * 1000;
72
+ } catch {
73
+ return null;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * P4: the moment an exhausted budget comes back, from the screen's words: «2 hours», «30 min»
79
+ * (from now), or a clock time «3pm», «15:00», «3:30pm (Europe/Madrid)» (the next one after
80
+ * `now`, in that zone or the machine's). A minute later, so the limit is surely gone. Null when
81
+ * it cannot be told.
82
+ */
83
+ export function resumeTimeFrom(resets: string | null | undefined, now: Date = new Date()): Date | null {
84
+ const text = String(resets ?? '').trim();
85
+ if (!text) return null;
86
+ const rel = /^(?:in\s+)?(\d{1,3})\s*(hours?|hrs?|h|minutes?|mins?|m)\b/i.exec(text);
87
+ if (rel) {
88
+ const n = Number(rel[1]);
89
+ const ms = /^h/i.test(rel[2]) ? n * 3_600_000 : n * 60_000;
90
+ return new Date(now.getTime() + ms + 60_000);
91
+ }
92
+ const clock = /^(\d{1,2})(?::(\d{2}))?\s*(am|pm)?(?:\s*\(([^)]+)\))?/i.exec(text);
93
+ if (!clock) return null;
94
+ let hour = Number(clock[1]);
95
+ const minute = Number(clock[2] ?? 0);
96
+ const ampm = clock[3]?.toLowerCase();
97
+ if (ampm === 'pm' && hour < 12) hour += 12;
98
+ if (ampm === 'am' && hour === 12) hour = 0;
99
+ if (hour > 23 || minute > 59) return null;
100
+ const zone = clock[4]?.trim();
101
+ for (let day = 0; day <= 1; day++) {
102
+ let target: Date;
103
+ if (zone) {
104
+ const off = zoneOffsetMs(now, zone);
105
+ if (off === null) return null;
106
+ const wallNow = new Date(now.getTime() + off);
107
+ const guess = Date.UTC(wallNow.getUTCFullYear(), wallNow.getUTCMonth(), wallNow.getUTCDate() + day, hour, minute);
108
+ const off2 = zoneOffsetMs(new Date(guess - off), zone) ?? off;
109
+ target = new Date(guess - off2);
110
+ } else {
111
+ target = new Date(now.getFullYear(), now.getMonth(), now.getDate() + day, hour, minute);
112
+ }
113
+ if (target.getTime() > now.getTime()) return new Date(target.getTime() + 60_000);
114
+ }
115
+ return null;
116
+ }
117
+
118
+ /** What the session-tail script reports about a pi session. */
119
+ export interface PiSessionTail {
120
+ /** Tokens in context at the last answer (input + cache), and the model's window. */
121
+ lastContext: number | null;
122
+ contextWindow: number | null;
123
+ /** The last assistant answers, newest last: why they stopped and how much they wrote. */
124
+ stops: Array<{ reason: string; output: number }>;
125
+ }
126
+
127
+ /**
128
+ * Runs in the container as runner: `node -e <script> <cwd>`. It reads the newest session of
129
+ * `cwd` and pi's models.json, and prints a PiSessionTail as JSON (or `{}`).
130
+ */
131
+ export const PI_SESSION_TAIL_SCRIPT = `
132
+ const fs = require('fs'), p = require('path');
133
+ const home = process.env.HOME || '/home/runner';
134
+ const cwd = process.argv[1] || '';
135
+ const dir = p.join(home, '.pi/agent/sessions', '--' + cwd.replace(/^\\//, '').replace(/\\//g, '-') + '--');
136
+ let file;
137
+ try {
138
+ file = fs.readdirSync(dir).filter((x) => x.endsWith('.jsonl')).map((x) => p.join(dir, x))
139
+ .sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)[0];
140
+ } catch {}
141
+ if (!file) { process.stdout.write('{}'); process.exit(0); }
142
+ const st = fs.statSync(file);
143
+ const fd = fs.openSync(file, 'r');
144
+ const size = Math.min(st.size, 400000);
145
+ const buf = Buffer.alloc(size);
146
+ fs.readSync(fd, buf, 0, size, st.size - size);
147
+ const lines = buf.toString('utf8').split('\\n');
148
+ const stops = [];
149
+ let lastContext = null, provider = null, model = null;
150
+ for (const l of lines) {
151
+ let e; try { e = JSON.parse(l); } catch { continue; }
152
+ const m = e && e.type === 'message' && e.message;
153
+ if (!m || m.role !== 'assistant') continue;
154
+ const u = m.usage || {};
155
+ lastContext = (u.input || 0) + (u.cacheRead || 0) + (u.cacheWrite || 0);
156
+ stops.push({ reason: String(m.stopReason || ''), output: Number(u.output || 0) });
157
+ if (m.provider) provider = m.provider;
158
+ if (m.model) model = m.model;
159
+ }
160
+ let contextWindow = null;
161
+ try {
162
+ const models = JSON.parse(fs.readFileSync(p.join(home, '.pi/agent/models.json'), 'utf8'));
163
+ const found = (((models.providers || {})[provider] || {}).models || []).find((x) => x.id === model);
164
+ if (found && typeof found.contextWindow === 'number') contextWindow = found.contextWindow;
165
+ } catch {}
166
+ process.stdout.write(JSON.stringify({ lastContext, contextWindow, stops: stops.slice(-4) }));
167
+ `;
168
+
169
+ const k = (n: number) => `${Math.round(n / 1000)}K`;
170
+
171
+ /**
172
+ * A pi session is stuck on its context when two of its last three answers were cut by length
173
+ * with next to nothing written (NAV-4588: 667 tokens, then 1), or when the context is at 90 %
174
+ * of the window or more.
175
+ */
176
+ export function piContextStuck(tail: Partial<PiSessionTail> | null): StuckFinding | null {
177
+ if (!tail) return null;
178
+ const last = (tail.stops ?? []).slice(-3);
179
+ const cut = last.filter((s) => s.reason === 'length' && s.output <= 1000).length;
180
+ const ratio = tail.lastContext && tail.contextWindow ? tail.lastContext / tail.contextWindow : 0;
181
+ if (cut < 2 && ratio < 0.9) return null;
182
+ const detail = tail.lastContext && tail.contextWindow ? `${k(tail.lastContext)} de ${k(tail.contextWindow)}` : null;
183
+ return { kind: 'context', detail };
184
+ }
185
+
186
+ /** The run's waiting reason for a stuck agent: «<name>: contexto lleno (…)…», parseable by the panel. */
187
+ export function stuckReason(name: string, f: StuckFinding): string {
188
+ if (f.kind === 'context') {
189
+ return `${name}: contexto lleno${f.detail ? ` (${f.detail})` : ''}, la compactación no puede liberar sitio. Relánzalo con resumen.`;
190
+ }
191
+ return `${name}: presupuesto agotado${f.detail ? ` (${f.detail})` : ''}. Relánzalo con resumen con otro agente.`;
192
+ }
@@ -57,6 +57,8 @@ export function initDatabase(dbPath: string): DatabaseSync {
57
57
  team_engine TEXT DEFAULT 'hc',
58
58
  bondify INTEGER NOT NULL DEFAULT 1,
59
59
  docker INTEGER NOT NULL DEFAULT 0,
60
+ loop_enabled INTEGER NOT NULL DEFAULT 0,
61
+ loop_max_iterations INTEGER,
60
62
  status TEXT NOT NULL DEFAULT 'ready',
61
63
  created_at TEXT NOT NULL,
62
64
  updated_at TEXT NOT NULL
@@ -71,6 +73,14 @@ export function initDatabase(dbPath: string): DatabaseSync {
71
73
  container_name TEXT,
72
74
  hc_machine TEXT,
73
75
  hc_terminal TEXT,
76
+ agent_override TEXT,
77
+ model_override TEXT,
78
+ resume_at TEXT,
79
+ resume_agent TEXT,
80
+ loop_state TEXT,
81
+ loop_iteration INTEGER NOT NULL DEFAULT 0,
82
+ loop_stalls INTEGER NOT NULL DEFAULT 0,
83
+ loop_config TEXT,
74
84
  cost_usd REAL NOT NULL DEFAULT 0.0,
75
85
  cleanup_pending INTEGER NOT NULL DEFAULT 0,
76
86
  verify_failures INTEGER NOT NULL DEFAULT 0,
@@ -167,11 +177,17 @@ export function initDatabase(dbPath: string): DatabaseSync {
167
177
  db.exec(`ALTER TABLE runs DROP COLUMN ${col};`);
168
178
  }
169
179
  }
170
- for (const col of ['hc_machine', 'hc_terminal']) {
180
+ for (const col of ['hc_machine', 'hc_terminal', 'agent_override', 'model_override', 'resume_at', 'resume_agent', 'loop_state', 'loop_config']) {
171
181
  if (!colNames.has(col)) {
172
182
  db.exec(`ALTER TABLE runs ADD COLUMN ${col} TEXT;`);
173
183
  }
174
184
  }
185
+ // LOOP P3 (issue #2): the loop's counters (review rounds; rounds in a row without progress).
186
+ for (const col of ['loop_iteration', 'loop_stalls']) {
187
+ if (!colNames.has(col)) {
188
+ db.exec(`ALTER TABLE runs ADD COLUMN ${col} INTEGER NOT NULL DEFAULT 0;`);
189
+ }
190
+ }
175
191
  if (!colNames.has('cleanup_pending')) {
176
192
  db.exec('ALTER TABLE runs ADD COLUMN cleanup_pending INTEGER NOT NULL DEFAULT 0;');
177
193
  }
@@ -214,6 +230,20 @@ export function initDatabase(dbPath: string): DatabaseSync {
214
230
  if (!ticketCols.some((c) => c.name === 'docker')) {
215
231
  db.exec('ALTER TABLE tickets ADD COLUMN docker INTEGER NOT NULL DEFAULT 0;');
216
232
  }
233
+ // Issue #4 (P2): «Login de Azure» (the person's Azure session in the run; off) and its subscription.
234
+ if (!ticketCols.some((c) => c.name === 'azure_login')) {
235
+ db.exec('ALTER TABLE tickets ADD COLUMN azure_login INTEGER NOT NULL DEFAULT 0;');
236
+ }
237
+ if (!ticketCols.some((c) => c.name === 'azure_subscription')) {
238
+ db.exec('ALTER TABLE tickets ADD COLUMN azure_subscription TEXT;');
239
+ }
240
+ // LOOP P1 (issue #2): the ticket's autonomous mode; off. NULL iterations = no limit.
241
+ if (!ticketCols.some((c) => c.name === 'loop_enabled')) {
242
+ db.exec('ALTER TABLE tickets ADD COLUMN loop_enabled INTEGER NOT NULL DEFAULT 0;');
243
+ }
244
+ if (!ticketCols.some((c) => c.name === 'loop_max_iterations')) {
245
+ db.exec('ALTER TABLE tickets ADD COLUMN loop_max_iterations INTEGER;');
246
+ }
217
247
 
218
248
  // Plan bond-app-azure-jira P2: Jira Cloud credential table for pre-existing databases
219
249
  db.exec(`
@@ -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 }