@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.
@@ -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
+ }
@@ -126,6 +126,7 @@ function resolveServiceContext(options: ServiceOptions = {}) {
126
126
  const dataDir = path.resolve(options.dataDir ?? env.BOND_APP_DATA_DIR ?? path.join(homeDir, '.bond-app'));
127
127
  const runnerImage = options.runnerImage ?? (env.RUNNER_IMAGE || undefined);
128
128
  const nodePath = deps.nodePath ?? process.execPath;
129
+ const servicePath = servicePathFor(env.PATH, nodePath, homeDir, platform);
129
130
  const binPath = path.resolve(deps.binPath ?? stableBinPath(path.join(repoRoot, 'bin', 'bond-app.js'), deps.npmGlobalRoot));
130
131
  const runCommand = deps.runCommand ?? defaultRunCommand;
131
132
  const uid = deps.uid ?? (typeof process.getuid === 'function' ? process.getuid() : 501);
@@ -153,6 +154,7 @@ function resolveServiceContext(options: ServiceOptions = {}) {
153
154
  dataDir,
154
155
  runnerImage,
155
156
  nodePath,
157
+ servicePath,
156
158
  binPath,
157
159
  runCommand,
158
160
  uid,
@@ -182,6 +184,8 @@ export function renderSystemdUnit(params: {
182
184
  host?: string;
183
185
  dataDir: string;
184
186
  runnerImage?: string;
187
+ /** PATH for the service (launchd and systemd start it with a minimal one). */
188
+ servicePath?: string;
185
189
  }): string {
186
190
  const execParts = [
187
191
  quoteSystemdArg(params.nodePath),
@@ -197,6 +201,7 @@ export function renderSystemdUnit(params: {
197
201
  }
198
202
 
199
203
  const envLines = [`Environment=${quoteSystemdEnv('BOND_APP_DATA_DIR', params.dataDir)}`];
204
+ if (params.servicePath) envLines.push(`Environment=${quoteSystemdEnv('PATH', params.servicePath)}`);
200
205
  if (params.runnerImage) {
201
206
  envLines.push(`Environment=${quoteSystemdEnv('RUNNER_IMAGE', params.runnerImage)}`);
202
207
  }
@@ -241,6 +246,8 @@ export function renderLaunchdPlist(params: {
241
246
  host?: string;
242
247
  dataDir: string;
243
248
  runnerImage?: string;
249
+ /** PATH for the service: launchd starts it with /usr/bin:/bin:/usr/sbin:/sbin only. */
250
+ servicePath?: string;
244
251
  }): string {
245
252
  const args = [
246
253
  params.nodePath,
@@ -256,6 +263,7 @@ export function renderLaunchdPlist(params: {
256
263
  }
257
264
 
258
265
  const envEntries = [` <key>BOND_APP_DATA_DIR</key>`, ` <string>${escapeXml(params.dataDir)}</string>`];
266
+ if (params.servicePath) envEntries.push(` <key>PATH</key>`, ` <string>${escapeXml(params.servicePath)}</string>`);
259
267
  if (params.runnerImage) {
260
268
  envEntries.push(` <key>RUNNER_IMAGE</key>`, ` <string>${escapeXml(params.runnerImage)}</string>`);
261
269
  }
@@ -417,6 +425,7 @@ export async function installService(options: ServiceOptions = {}): Promise<Serv
417
425
  host: ctx.host,
418
426
  dataDir: ctx.dataDir,
419
427
  runnerImage: ctx.runnerImage,
428
+ servicePath: ctx.servicePath,
420
429
  });
421
430
  fs.writeFileSync(ctx.unitPath!, unitContent, { encoding: 'utf8', mode: 0o644 });
422
431
 
@@ -479,6 +488,7 @@ export async function installService(options: ServiceOptions = {}): Promise<Serv
479
488
  host: ctx.host,
480
489
  dataDir: ctx.dataDir,
481
490
  runnerImage: ctx.runnerImage,
491
+ servicePath: ctx.servicePath,
482
492
  });
483
493
  fs.writeFileSync(ctx.unitPath!, plistContent, { encoding: 'utf8', mode: 0o644 });
484
494
 
@@ -859,3 +869,27 @@ async function windowsAction(action: ServiceAction, ctx: ServiceCtx): Promise<Se
859
869
  detail: details.join('; '),
860
870
  };
861
871
  }
872
+
873
+ /**
874
+ * The PATH the orchestrator service runs with. launchd (and systemd --user) start it with a
875
+ * minimal PATH, without the folders where docker (OrbStack, Docker Desktop), hc, bond and
876
+ * herdr-app live: the orchestrator could not find them and did not start. The service keeps
877
+ * the PATH of whoever installs it, plus node's folder and the usual install folders.
878
+ */
879
+ export function servicePathFor(current: string | undefined, nodePath: string, homeDir: string, platform: NodeJS.Platform): string | undefined {
880
+ if (platform === 'win32') return undefined;
881
+ const extra = [
882
+ path.dirname(nodePath),
883
+ path.join(homeDir, '.local', 'bin'),
884
+ ...(platform === 'darwin' ? ['/opt/homebrew/bin', path.join(homeDir, '.orbstack', 'bin'), '/Applications/Docker.app/Contents/Resources/bin'] : []),
885
+ '/usr/local/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin',
886
+ ];
887
+ const seen = new Set<string>();
888
+ const out: string[] = [];
889
+ for (const dir of [...String(current ?? '').split(':'), ...extra]) {
890
+ if (!dir || !path.isAbsolute(dir) || seen.has(dir)) continue;
891
+ seen.add(dir);
892
+ out.push(dir);
893
+ }
894
+ return out.join(':');
895
+ }
@@ -1178,7 +1178,8 @@ export async function runUpdate(options: UpdateOptions = {}): Promise<UpdateResu
1178
1178
  }
1179
1179
  }
1180
1180
 
1181
- // 4. Restart user service if installed
1181
+ // 4. Rewrite the user service (if installed) with this version's unit/plist, then restart it:
1182
+ // fixes to the service itself (macOS PATH, 0.3.1) reach existing installs this way.
1182
1183
  const serviceDeps: ServiceDeps = {
1183
1184
  runCommand,
1184
1185
  platform,
@@ -1188,10 +1189,12 @@ export async function runUpdate(options: UpdateOptions = {}): Promise<UpdateResu
1188
1189
  const svcStatus = await getServiceStatus({ port, host, dataDir, deps: serviceDeps });
1189
1190
  if (svcStatus.supported && svcStatus.installed) {
1190
1191
  if (dryRun) {
1191
- const detail = `would restart user service (${svcStatus.serviceName})`;
1192
+ const detail = `would rewrite and restart user service (${svcStatus.serviceName})`;
1192
1193
  logStep('✓', 'User service', detail);
1193
1194
  steps.push({ id: 'service', ok: true, skipped: true, detail });
1194
1195
  } else {
1196
+ const reinstall = await (deps.installService ?? installService)({ port, host, dataDir, runnerImage: options.runnerImage, deps: serviceDeps });
1197
+ if (!reinstall.ok) logStep('!', 'User service', `could not rewrite it: ${reinstall.detail}`);
1195
1198
  const svcRes = await restartSvcFn({
1196
1199
  port,
1197
1200
  host,
@@ -0,0 +1,204 @@
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
+ /**
46
+ * pi says on its screen that compaction failed (the summary did not fit the model's output
47
+ * cap, NAV-5109): it goes on with a context it can no longer free, and stops when it is full.
48
+ * Only the bottom of the screen counts, like the budget notice.
49
+ */
50
+ export function compactionFailedIn(screen: string): StuckFinding | null {
51
+ const tail = screen.split('\n').slice(-25).join('\n');
52
+ return /Auto-compaction failed|Context overflow recovery failed|Truncated response recovery failed/.test(tail)
53
+ ? { kind: 'context', detail: 'la compactación falló' }
54
+ : null;
55
+ }
56
+
57
+ /** The last lines of an agent's screen tell an exhausted budget, and when it resets. */
58
+ export function budgetExhaustedIn(screen: string): StuckFinding | null {
59
+ // The bottom of the screen only: the notice is the agent's last word, and a limit mentioned
60
+ // earlier (in code or docs it read) is not a verdict.
61
+ const tail = screen.split('\n').slice(-25).join('\n');
62
+ if (!BUDGET_PATTERNS.some((re) => re.test(tail))) return null;
63
+ let resets: string | null = null;
64
+ for (const re of RESET_PATTERNS) {
65
+ const m = re.exec(tail);
66
+ if (m) {
67
+ resets = m[1].trim();
68
+ break;
69
+ }
70
+ }
71
+ return { kind: 'budget', detail: resets ? `se restablece a las ${resets}` : null, resets };
72
+ }
73
+
74
+ /** The wall-clock offset (ms) of an IANA zone at an instant, or null for an unknown zone. */
75
+ function zoneOffsetMs(at: Date, timeZone: string): number | null {
76
+ try {
77
+ const parts = Object.fromEntries(
78
+ 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' })
79
+ .formatToParts(at)
80
+ .map((x) => [x.type, x.value])
81
+ );
82
+ const wall = Date.UTC(+parts.year, +parts.month - 1, +parts.day, +parts.hour % 24, +parts.minute, +parts.second);
83
+ return wall - Math.floor(at.getTime() / 1000) * 1000;
84
+ } catch {
85
+ return null;
86
+ }
87
+ }
88
+
89
+ /**
90
+ * P4: the moment an exhausted budget comes back, from the screen's words: «2 hours», «30 min»
91
+ * (from now), or a clock time «3pm», «15:00», «3:30pm (Europe/Madrid)» (the next one after
92
+ * `now`, in that zone or the machine's). A minute later, so the limit is surely gone. Null when
93
+ * it cannot be told.
94
+ */
95
+ export function resumeTimeFrom(resets: string | null | undefined, now: Date = new Date()): Date | null {
96
+ const text = String(resets ?? '').trim();
97
+ if (!text) return null;
98
+ const rel = /^(?:in\s+)?(\d{1,3})\s*(hours?|hrs?|h|minutes?|mins?|m)\b/i.exec(text);
99
+ if (rel) {
100
+ const n = Number(rel[1]);
101
+ const ms = /^h/i.test(rel[2]) ? n * 3_600_000 : n * 60_000;
102
+ return new Date(now.getTime() + ms + 60_000);
103
+ }
104
+ const clock = /^(\d{1,2})(?::(\d{2}))?\s*(am|pm)?(?:\s*\(([^)]+)\))?/i.exec(text);
105
+ if (!clock) return null;
106
+ let hour = Number(clock[1]);
107
+ const minute = Number(clock[2] ?? 0);
108
+ const ampm = clock[3]?.toLowerCase();
109
+ if (ampm === 'pm' && hour < 12) hour += 12;
110
+ if (ampm === 'am' && hour === 12) hour = 0;
111
+ if (hour > 23 || minute > 59) return null;
112
+ const zone = clock[4]?.trim();
113
+ for (let day = 0; day <= 1; day++) {
114
+ let target: Date;
115
+ if (zone) {
116
+ const off = zoneOffsetMs(now, zone);
117
+ if (off === null) return null;
118
+ const wallNow = new Date(now.getTime() + off);
119
+ const guess = Date.UTC(wallNow.getUTCFullYear(), wallNow.getUTCMonth(), wallNow.getUTCDate() + day, hour, minute);
120
+ const off2 = zoneOffsetMs(new Date(guess - off), zone) ?? off;
121
+ target = new Date(guess - off2);
122
+ } else {
123
+ target = new Date(now.getFullYear(), now.getMonth(), now.getDate() + day, hour, minute);
124
+ }
125
+ if (target.getTime() > now.getTime()) return new Date(target.getTime() + 60_000);
126
+ }
127
+ return null;
128
+ }
129
+
130
+ /** What the session-tail script reports about a pi session. */
131
+ export interface PiSessionTail {
132
+ /** Tokens in context at the last answer (input + cache), and the model's window. */
133
+ lastContext: number | null;
134
+ contextWindow: number | null;
135
+ /** The last assistant answers, newest last: why they stopped and how much they wrote. */
136
+ stops: Array<{ reason: string; output: number }>;
137
+ }
138
+
139
+ /**
140
+ * Runs in the container as runner: `node -e <script> <cwd>`. It reads the newest session of
141
+ * `cwd` and pi's models.json, and prints a PiSessionTail as JSON (or `{}`).
142
+ */
143
+ export const PI_SESSION_TAIL_SCRIPT = `
144
+ const fs = require('fs'), p = require('path');
145
+ const home = process.env.HOME || '/home/runner';
146
+ const cwd = process.argv[1] || '';
147
+ const dir = p.join(home, '.pi/agent/sessions', '--' + cwd.replace(/^\\//, '').replace(/\\//g, '-') + '--');
148
+ let file;
149
+ try {
150
+ file = fs.readdirSync(dir).filter((x) => x.endsWith('.jsonl')).map((x) => p.join(dir, x))
151
+ .sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)[0];
152
+ } catch {}
153
+ if (!file) { process.stdout.write('{}'); process.exit(0); }
154
+ const st = fs.statSync(file);
155
+ const fd = fs.openSync(file, 'r');
156
+ const size = Math.min(st.size, 400000);
157
+ const buf = Buffer.alloc(size);
158
+ fs.readSync(fd, buf, 0, size, st.size - size);
159
+ const lines = buf.toString('utf8').split('\\n');
160
+ const stops = [];
161
+ let lastContext = null, provider = null, model = null;
162
+ for (const l of lines) {
163
+ let e; try { e = JSON.parse(l); } catch { continue; }
164
+ const m = e && e.type === 'message' && e.message;
165
+ if (!m || m.role !== 'assistant') continue;
166
+ const u = m.usage || {};
167
+ lastContext = (u.input || 0) + (u.cacheRead || 0) + (u.cacheWrite || 0);
168
+ stops.push({ reason: String(m.stopReason || ''), output: Number(u.output || 0) });
169
+ if (m.provider) provider = m.provider;
170
+ if (m.model) model = m.model;
171
+ }
172
+ let contextWindow = null;
173
+ try {
174
+ const models = JSON.parse(fs.readFileSync(p.join(home, '.pi/agent/models.json'), 'utf8'));
175
+ const found = (((models.providers || {})[provider] || {}).models || []).find((x) => x.id === model);
176
+ if (found && typeof found.contextWindow === 'number') contextWindow = found.contextWindow;
177
+ } catch {}
178
+ process.stdout.write(JSON.stringify({ lastContext, contextWindow, stops: stops.slice(-4) }));
179
+ `;
180
+
181
+ const k = (n: number) => `${Math.round(n / 1000)}K`;
182
+
183
+ /**
184
+ * A pi session is stuck on its context when two of its last three answers were cut by length
185
+ * with next to nothing written (NAV-4588: 667 tokens, then 1), or when the context is at 90 %
186
+ * of the window or more.
187
+ */
188
+ export function piContextStuck(tail: Partial<PiSessionTail> | null): StuckFinding | null {
189
+ if (!tail) return null;
190
+ const last = (tail.stops ?? []).slice(-3);
191
+ const cut = last.filter((s) => s.reason === 'length' && s.output <= 1000).length;
192
+ const ratio = tail.lastContext && tail.contextWindow ? tail.lastContext / tail.contextWindow : 0;
193
+ if (cut < 2 && ratio < 0.9) return null;
194
+ const detail = tail.lastContext && tail.contextWindow ? `${k(tail.lastContext)} de ${k(tail.contextWindow)}` : null;
195
+ return { kind: 'context', detail };
196
+ }
197
+
198
+ /** The run's waiting reason for a stuck agent: «<name>: contexto lleno (…)…», parseable by the panel. */
199
+ export function stuckReason(name: string, f: StuckFinding): string {
200
+ if (f.kind === 'context') {
201
+ return `${name}: contexto lleno${f.detail ? ` (${f.detail})` : ''}, la compactación no puede liberar sitio. Relánzalo con resumen.`;
202
+ }
203
+ return `${name}: presupuesto agotado${f.detail ? ` (${f.detail})` : ''}. Relánzalo con resumen con otro agente.`;
204
+ }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * «Hay versión nueva»: the orchestrator asks npm, at start and then once a day, for the latest
3
+ * bond-app and bond, and compares them with what is installed. The app shows it in the status
4
+ * bar and Ajustes → Avanzado, whose «Actualizar» runs `bond-app update`. The only network call
5
+ * is to registry.npmjs.org; without network it says nothing (no error to the person).
6
+ */
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { execFile } from 'node:child_process';
10
+ import { promisify } from 'node:util';
11
+ import { fileURLToPath } from 'node:url';
12
+
13
+ const execFileAsync = promisify(execFile);
14
+ const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
15
+
16
+ export const UPDATE_PACKAGES = { bond_app: '@jmanuelcorral/bond-app', bond: '@jmanuelcorral/bond' } as const;
17
+ export const UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
18
+
19
+ export interface PackageUpdate {
20
+ installed: string | null;
21
+ latest: string | null;
22
+ update: boolean;
23
+ }
24
+
25
+ export interface UpdateStatus {
26
+ bond_app: PackageUpdate;
27
+ bond: PackageUpdate;
28
+ /** Something to update. */
29
+ available: boolean;
30
+ checked_at: string | null;
31
+ /** Why the last check could not ask npm (no network...): for Ajustes, not an alarm. */
32
+ error: string | null;
33
+ }
34
+
35
+ /** a < b for plain x.y.z versions (pre-releases count as lower). */
36
+ export function isNewer(latest: string | null, installed: string | null): boolean {
37
+ if (!latest || !installed) return false;
38
+ const parse = (v: string) => {
39
+ const [core, pre] = v.replace(/^v/, '').split('-', 2);
40
+ return { nums: core.split('.').map((n) => Number.parseInt(n, 10) || 0), pre: pre ?? null };
41
+ };
42
+ const a = parse(latest);
43
+ const b = parse(installed);
44
+ for (let i = 0; i < 3; i++) {
45
+ if ((a.nums[i] ?? 0) !== (b.nums[i] ?? 0)) return (a.nums[i] ?? 0) > (b.nums[i] ?? 0);
46
+ }
47
+ return a.pre === null && b.pre !== null;
48
+ }
49
+
50
+ export interface UpdateDeps {
51
+ /** The latest version npm has for a package (registry.npmjs.org/<pkg>/latest). */
52
+ latestVersion?: (pkg: string) => Promise<string | null>;
53
+ /** The installed bond (`bond --version`). */
54
+ bondVersion?: () => Promise<string | null>;
55
+ /** This bond-app's version. */
56
+ appVersion?: string;
57
+ now?: () => number;
58
+ }
59
+
60
+ async function npmLatest(pkg: string): Promise<string | null> {
61
+ const ctrl = new AbortController();
62
+ const timer = setTimeout(() => ctrl.abort(), 8000);
63
+ try {
64
+ const res = await fetch(`https://registry.npmjs.org/${pkg.replace('/', '%2F')}/latest`, {
65
+ signal: ctrl.signal,
66
+ headers: { Accept: 'application/json' },
67
+ });
68
+ if (!res.ok) throw new Error(`npm respondió ${res.status}`);
69
+ const body = (await res.json()) as { version?: unknown };
70
+ return typeof body.version === 'string' ? body.version : null;
71
+ } finally {
72
+ clearTimeout(timer);
73
+ }
74
+ }
75
+
76
+ async function installedBond(): Promise<string | null> {
77
+ try {
78
+ const { stdout } = await execFileAsync('bond', ['--version'], { timeout: 10_000, shell: process.platform === 'win32' });
79
+ return /(\d+\.\d+\.\d+(?:-[\w.]+)?)/.exec(stdout)?.[1] ?? null;
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+
85
+ function ownVersion(): string {
86
+ try {
87
+ return (JSON.parse(fs.readFileSync(path.join(repoRoot, 'package.json'), 'utf8')) as { version: string }).version;
88
+ } catch {
89
+ return '0.0.0';
90
+ }
91
+ }
92
+
93
+ export class UpdateChecker {
94
+ private status: UpdateStatus;
95
+ private timer: NodeJS.Timeout | null = null;
96
+ private inFlight: Promise<UpdateStatus> | null = null;
97
+ private deps: Required<UpdateDeps>;
98
+
99
+ constructor(deps: UpdateDeps = {}) {
100
+ this.deps = {
101
+ latestVersion: deps.latestVersion ?? npmLatest,
102
+ bondVersion: deps.bondVersion ?? installedBond,
103
+ appVersion: deps.appVersion ?? ownVersion(),
104
+ now: deps.now ?? Date.now,
105
+ };
106
+ const empty = (installed: string | null): PackageUpdate => ({ installed, latest: null, update: false });
107
+ this.status = { bond_app: empty(this.deps.appVersion), bond: empty(null), available: false, checked_at: null, error: null };
108
+ }
109
+
110
+ get(): UpdateStatus {
111
+ return { ...this.status, bond_app: { ...this.status.bond_app }, bond: { ...this.status.bond } };
112
+ }
113
+
114
+ /** Ask npm now (one request at a time). Never throws: a failure is kept in `error`. */
115
+ check(): Promise<UpdateStatus> {
116
+ if (this.inFlight) return this.inFlight;
117
+ this.inFlight = (async () => {
118
+ const bondInstalled = await this.deps.bondVersion().catch(() => null);
119
+ try {
120
+ const [appLatest, bondLatest] = await Promise.all([
121
+ this.deps.latestVersion(UPDATE_PACKAGES.bond_app),
122
+ this.deps.latestVersion(UPDATE_PACKAGES.bond),
123
+ ]);
124
+ const app: PackageUpdate = { installed: this.deps.appVersion, latest: appLatest, update: isNewer(appLatest, this.deps.appVersion) };
125
+ const bond: PackageUpdate = { installed: bondInstalled, latest: bondLatest, update: isNewer(bondLatest, bondInstalled) };
126
+ this.status = { bond_app: app, bond, available: app.update || bond.update, checked_at: new Date(this.deps.now()).toISOString(), error: null };
127
+ } catch (err) {
128
+ this.status = {
129
+ ...this.status,
130
+ bond: { ...this.status.bond, installed: bondInstalled },
131
+ checked_at: new Date(this.deps.now()).toISOString(),
132
+ error: String((err as Error).message || err).slice(0, 200),
133
+ };
134
+ }
135
+ return this.get();
136
+ })().finally(() => {
137
+ this.inFlight = null;
138
+ });
139
+ return this.inFlight;
140
+ }
141
+
142
+ /** Check now and then every `intervalMs` (0: only now). */
143
+ start(intervalMs = UPDATE_CHECK_INTERVAL_MS): void {
144
+ void this.check();
145
+ if (intervalMs > 0) {
146
+ this.timer = setInterval(() => void this.check(), intervalMs);
147
+ this.timer.unref?.();
148
+ }
149
+ }
150
+
151
+ stop(): void {
152
+ if (this.timer) clearInterval(this.timer);
153
+ this.timer = null;
154
+ }
155
+ }
@@ -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(`