@jmanuelcorral/bond-app 0.3.0 → 0.3.2
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.
- package/app/mods/bond-agents/api.js +27 -0
- package/app/mods/bond-agents/model.js +3 -0
- package/app/mods/bond-board/api.js +27 -0
- package/app/mods/bond-settings/api.js +27 -0
- package/app/mods/bond-settings/main.js +72 -2
- package/app/mods/bond-status/api.js +27 -0
- package/app/mods/bond-status/main.js +14 -3
- package/app/mods/bond-status/model.js +13 -0
- package/package.json +1 -1
- package/src/cli.ts +110 -2
- package/src/config.ts +6 -0
- package/src/core/diagnose.ts +279 -0
- package/src/core/orchestrator.ts +28 -2
- package/src/core/service-windows.ts +1 -1
- package/src/core/service.ts +36 -0
- package/src/core/setup-install.ts +84 -26
- package/src/core/stuck.ts +12 -0
- package/src/core/updates.ts +155 -0
- package/src/index.ts +2 -0
- package/src/server/app.ts +6 -0
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `bond-app diagnose`: everything needed to understand why bond-app misbehaves on a machine,
|
|
3
|
+
* in one zip, without secrets. Works with the orchestrator down (it reads files and runs the
|
|
4
|
+
* same checks as doctor). `--issue` opens a GitHub issue with the summary (gh) and leaves the
|
|
5
|
+
* zip for the person to attach: GitHub's API cannot attach files to an issue.
|
|
6
|
+
*
|
|
7
|
+
* Everything that goes in passes through redactSecrets: the API token, the stored credentials
|
|
8
|
+
* (the values the DB keeps) and the usual token shapes become `***`.
|
|
9
|
+
*/
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import os from 'node:os';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import zlib from 'node:zlib';
|
|
14
|
+
import { execFile } from 'node:child_process';
|
|
15
|
+
import { promisify } from 'node:util';
|
|
16
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
17
|
+
import { redactSecrets } from './handoff.ts';
|
|
18
|
+
|
|
19
|
+
const execFileAsync = promisify(execFile);
|
|
20
|
+
|
|
21
|
+
export const ISSUE_REPO = 'jmanuelcorral/bond-app';
|
|
22
|
+
/** How much of each log goes in (its end). */
|
|
23
|
+
export const LOG_TAIL_BYTES = 1024 * 1024;
|
|
24
|
+
|
|
25
|
+
// --- zip (store + deflate, no dependency) ------------------------------------------------
|
|
26
|
+
|
|
27
|
+
const CRC_TABLE = (() => {
|
|
28
|
+
const t = new Uint32Array(256);
|
|
29
|
+
for (let n = 0; n < 256; n++) {
|
|
30
|
+
let c = n;
|
|
31
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
32
|
+
t[n] = c >>> 0;
|
|
33
|
+
}
|
|
34
|
+
return t;
|
|
35
|
+
})();
|
|
36
|
+
|
|
37
|
+
export function crc32(buf: Buffer): number {
|
|
38
|
+
let c = 0xffffffff;
|
|
39
|
+
for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
|
|
40
|
+
return (c ^ 0xffffffff) >>> 0;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A zip of text files (deflated), readable by any unzip. */
|
|
44
|
+
export function zipFiles(files: Array<{ name: string; content: string | Buffer }>, date = new Date()): Buffer {
|
|
45
|
+
const dosTime = ((date.getHours() << 11) | (date.getMinutes() << 5) | Math.floor(date.getSeconds() / 2)) & 0xffff;
|
|
46
|
+
const dosDate = (((date.getFullYear() - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate()) & 0xffff;
|
|
47
|
+
const locals: Buffer[] = [];
|
|
48
|
+
const centrals: Buffer[] = [];
|
|
49
|
+
let offset = 0;
|
|
50
|
+
for (const f of files) {
|
|
51
|
+
const name = Buffer.from(f.name, 'utf8');
|
|
52
|
+
const data = Buffer.isBuffer(f.content) ? f.content : Buffer.from(f.content, 'utf8');
|
|
53
|
+
const packed = zlib.deflateRawSync(data);
|
|
54
|
+
const crc = crc32(data);
|
|
55
|
+
const local = Buffer.alloc(30);
|
|
56
|
+
local.writeUInt32LE(0x04034b50, 0);
|
|
57
|
+
local.writeUInt16LE(20, 4);
|
|
58
|
+
local.writeUInt16LE(0x0800, 6); // UTF-8 names
|
|
59
|
+
local.writeUInt16LE(8, 8); // deflate
|
|
60
|
+
local.writeUInt16LE(dosTime, 10);
|
|
61
|
+
local.writeUInt16LE(dosDate, 12);
|
|
62
|
+
local.writeUInt32LE(crc, 14);
|
|
63
|
+
local.writeUInt32LE(packed.length, 18);
|
|
64
|
+
local.writeUInt32LE(data.length, 22);
|
|
65
|
+
local.writeUInt16LE(name.length, 26);
|
|
66
|
+
local.writeUInt16LE(0, 28);
|
|
67
|
+
locals.push(local, name, packed);
|
|
68
|
+
const central = Buffer.alloc(46);
|
|
69
|
+
central.writeUInt32LE(0x02014b50, 0);
|
|
70
|
+
central.writeUInt16LE(20, 4);
|
|
71
|
+
central.writeUInt16LE(20, 6);
|
|
72
|
+
central.writeUInt16LE(0x0800, 8);
|
|
73
|
+
central.writeUInt16LE(8, 10);
|
|
74
|
+
central.writeUInt16LE(dosTime, 12);
|
|
75
|
+
central.writeUInt16LE(dosDate, 14);
|
|
76
|
+
central.writeUInt32LE(crc, 16);
|
|
77
|
+
central.writeUInt32LE(packed.length, 20);
|
|
78
|
+
central.writeUInt32LE(data.length, 24);
|
|
79
|
+
central.writeUInt16LE(name.length, 28);
|
|
80
|
+
central.writeUInt32LE(offset, 42);
|
|
81
|
+
centrals.push(central, name);
|
|
82
|
+
offset += local.length + name.length + packed.length;
|
|
83
|
+
}
|
|
84
|
+
const centralSize = centrals.reduce((n, b) => n + b.length, 0);
|
|
85
|
+
const end = Buffer.alloc(22);
|
|
86
|
+
end.writeUInt32LE(0x06054b50, 0);
|
|
87
|
+
end.writeUInt16LE(files.length, 8);
|
|
88
|
+
end.writeUInt16LE(files.length, 10);
|
|
89
|
+
end.writeUInt32LE(centralSize, 12);
|
|
90
|
+
end.writeUInt32LE(offset, 16);
|
|
91
|
+
return Buffer.concat([...locals, ...centrals, end]);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// --- what goes in ------------------------------------------------------------------------
|
|
95
|
+
|
|
96
|
+
/** The end of a file (logs grow): at most `max` bytes, from a line start. */
|
|
97
|
+
export function tailFile(file: string, max = LOG_TAIL_BYTES): string | null {
|
|
98
|
+
try {
|
|
99
|
+
const size = fs.statSync(file).size;
|
|
100
|
+
const fd = fs.openSync(file, 'r');
|
|
101
|
+
try {
|
|
102
|
+
const len = Math.min(size, max);
|
|
103
|
+
const buf = Buffer.alloc(len);
|
|
104
|
+
fs.readSync(fd, buf, 0, len, size - len);
|
|
105
|
+
let text = buf.toString('utf8');
|
|
106
|
+
if (size > max) text = `[… ${size - max} bytes anteriores omitidos]\n${text.slice(text.indexOf('\n') + 1)}`;
|
|
107
|
+
return text;
|
|
108
|
+
} finally {
|
|
109
|
+
fs.closeSync(fd);
|
|
110
|
+
}
|
|
111
|
+
} catch {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Every value worth hiding that bond-app keeps: the API token and the stored credentials. */
|
|
117
|
+
export function knownSecrets(dataDir: string): string[] {
|
|
118
|
+
const out: string[] = [];
|
|
119
|
+
try {
|
|
120
|
+
out.push(fs.readFileSync(path.join(dataDir, 'token'), 'utf8').trim());
|
|
121
|
+
} catch {}
|
|
122
|
+
const db = path.join(dataDir, 'bond-app.sqlite');
|
|
123
|
+
if (!fs.existsSync(db)) return out;
|
|
124
|
+
try {
|
|
125
|
+
const conn = new DatabaseSync(db, { readOnly: true });
|
|
126
|
+
try {
|
|
127
|
+
// Every string inside, also inside JSON kept as a string (az's MSAL cache in the Azure login).
|
|
128
|
+
const strings = (v: unknown, acc: string[], depth = 0) => {
|
|
129
|
+
if (depth > 6) return;
|
|
130
|
+
if (typeof v === 'string') {
|
|
131
|
+
acc.push(v);
|
|
132
|
+
if (/^\s*[[{]/.test(v)) {
|
|
133
|
+
try {
|
|
134
|
+
strings(JSON.parse(v), acc, depth + 1);
|
|
135
|
+
} catch {}
|
|
136
|
+
}
|
|
137
|
+
} else if (v && typeof v === 'object') for (const x of Object.values(v)) strings(x, acc, depth + 1);
|
|
138
|
+
};
|
|
139
|
+
for (const table of ['agent_credentials', 'github_credential', 'azure_devops_credential', 'jira_credential']) {
|
|
140
|
+
let rows: Array<Record<string, unknown>> = [];
|
|
141
|
+
try {
|
|
142
|
+
rows = conn.prepare(`SELECT * FROM ${table}`).all() as Array<Record<string, unknown>>;
|
|
143
|
+
} catch {
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
for (const row of rows) {
|
|
147
|
+
for (const [k, v] of Object.entries(row)) {
|
|
148
|
+
if (typeof v !== 'string' || ['agent', 'provider', 'updated_at', 'created_at', 'login', 'site', 'email', 'org_url'].includes(k)) continue;
|
|
149
|
+
strings(v, out);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
} finally {
|
|
154
|
+
conn.close();
|
|
155
|
+
}
|
|
156
|
+
} catch {}
|
|
157
|
+
// Only what looks like a secret (long, no spaces): not every word of a JSON config.
|
|
158
|
+
return [...new Set(out.map((s) => s.trim()).filter((s) => s.length >= 12 && !/\s/.test(s) && !/^https?:\/\//.test(s)))];
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function cmd(bin: string, args: string[]): Promise<string> {
|
|
162
|
+
try {
|
|
163
|
+
const { stdout, stderr } = await execFileAsync(bin, args, { timeout: 15_000, shell: process.platform === 'win32' });
|
|
164
|
+
return `${stdout}${stderr}`.trim();
|
|
165
|
+
} catch (err) {
|
|
166
|
+
const e = err as { stdout?: string; stderr?: string; message?: string };
|
|
167
|
+
return `(falló: ${(e.stderr || e.stdout || e.message || String(err)).trim().slice(0, 500)})`;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** The last runs, without titles or stories (they may be private): state and why. */
|
|
172
|
+
export function runsSummary(dataDir: string): string {
|
|
173
|
+
const db = path.join(dataDir, 'bond-app.sqlite');
|
|
174
|
+
if (!fs.existsSync(db)) return 'sin base de datos';
|
|
175
|
+
try {
|
|
176
|
+
const conn = new DatabaseSync(db, { readOnly: true });
|
|
177
|
+
try {
|
|
178
|
+
const runs = conn.prepare(
|
|
179
|
+
`SELECT r.id, r.state, r.failure_reason, r.loop_state, r.created_at, r.updated_at, t.agent, t.hub_url IS NOT NULL AS hub
|
|
180
|
+
FROM runs r LEFT JOIN tickets t ON t.id = r.ticket_id ORDER BY r.created_at DESC LIMIT 20`
|
|
181
|
+
).all();
|
|
182
|
+
const events = conn.prepare(
|
|
183
|
+
`SELECT run_id, type, created_at, substr(payload, 1, 400) AS payload FROM events ORDER BY rowid DESC LIMIT 200`
|
|
184
|
+
).all();
|
|
185
|
+
return JSON.stringify({ runs, events }, null, 2);
|
|
186
|
+
} finally {
|
|
187
|
+
conn.close();
|
|
188
|
+
}
|
|
189
|
+
} catch (err) {
|
|
190
|
+
return `no se pudo leer: ${(err as Error).message}`;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export interface DiagnoseOptions {
|
|
195
|
+
dataDir: string;
|
|
196
|
+
herdrAppHome: string;
|
|
197
|
+
/** doctor's report as JSON (the caller runs it: it needs the same options as doctor). */
|
|
198
|
+
doctorJson: string;
|
|
199
|
+
/** The service's status and its unit/plist path. */
|
|
200
|
+
service?: { status: string; unitPath: string | null };
|
|
201
|
+
version: string;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export interface Diagnosis {
|
|
205
|
+
zip: Buffer;
|
|
206
|
+
files: string[];
|
|
207
|
+
/** The text for the issue: versions, doctor's failures and the end of the orchestrator log. */
|
|
208
|
+
summary: string;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export async function collectDiagnosis(o: DiagnoseOptions): Promise<Diagnosis> {
|
|
212
|
+
const secrets = knownSecrets(o.dataDir);
|
|
213
|
+
const clean = (s: string) => redactSecrets(s, secrets);
|
|
214
|
+
const files: Array<{ name: string; content: string }> = [];
|
|
215
|
+
const add = (name: string, content: string | null) => {
|
|
216
|
+
if (content !== null && content !== undefined) files.push({ name, content: clean(content) });
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
const info = [
|
|
220
|
+
`bond-app ${o.version}`,
|
|
221
|
+
`fecha ${new Date().toISOString()}`,
|
|
222
|
+
`sistema ${os.platform()} ${os.release()} ${os.arch()} (${os.type()})`,
|
|
223
|
+
`node ${process.version}`,
|
|
224
|
+
`bond ${await cmd('bond', ['--version'])}`,
|
|
225
|
+
`hc ${await cmd('hc', ['--version'])}`,
|
|
226
|
+
`herdr-app ${await cmd('herdr-app', ['--version'])}`,
|
|
227
|
+
'',
|
|
228
|
+
'## docker version',
|
|
229
|
+
await cmd('docker', ['version']),
|
|
230
|
+
'',
|
|
231
|
+
'## docker context ls',
|
|
232
|
+
await cmd('docker', ['context', 'ls']),
|
|
233
|
+
'',
|
|
234
|
+
'## Entorno',
|
|
235
|
+
`PATH=${process.env.PATH ?? ''}`,
|
|
236
|
+
...Object.entries(process.env)
|
|
237
|
+
.filter(([k]) => /^(BOND_APP_|RUNNER_IMAGE$|DOCKER_HOST$|DOCKER_CONTEXT$|HERDR_APP_HOME$|XDG_)/.test(k) && !/TOKEN|SECRET|PASS|KEY/i.test(k))
|
|
238
|
+
.map(([k, v]) => `${k}=${v}`),
|
|
239
|
+
].join('\n');
|
|
240
|
+
add('info.txt', info);
|
|
241
|
+
add('doctor.json', o.doctorJson);
|
|
242
|
+
add('orchestrator.log', tailFile(path.join(o.dataDir, 'orchestrator.log')));
|
|
243
|
+
add('app.log', tailFile(path.join(o.dataDir, 'app.log')));
|
|
244
|
+
for (const f of ['/tmp/herdr-app.log', path.join(o.herdrAppHome, 'herdr-app.log')]) add(`herdr-app/${path.basename(f)}`, tailFile(f, 512 * 1024));
|
|
245
|
+
if (o.service) {
|
|
246
|
+
add('service/status.txt', o.service.status);
|
|
247
|
+
if (o.service.unitPath) add(`service/${path.basename(o.service.unitPath)}`, tailFile(o.service.unitPath, 64 * 1024));
|
|
248
|
+
}
|
|
249
|
+
add('runs.json', runsSummary(o.dataDir));
|
|
250
|
+
const installed = path.join(o.herdrAppHome, 'installed.json');
|
|
251
|
+
add('herdr-app/installed.json', tailFile(installed, 64 * 1024));
|
|
252
|
+
|
|
253
|
+
let failing: string[] = [];
|
|
254
|
+
try {
|
|
255
|
+
const d = JSON.parse(o.doctorJson) as { checks?: Array<{ status: string; name: string; detail: string; fix?: string }> };
|
|
256
|
+
failing = (d.checks ?? []).filter((c) => c.status !== 'ok').map((c) => `- ${c.status === 'fail' ? '✗' : '!'} **${c.name}**: ${c.detail}${c.fix ? ` (arreglo: ${c.fix})` : ''}`);
|
|
257
|
+
} catch {}
|
|
258
|
+
const logTail = (tailFile(path.join(o.dataDir, 'orchestrator.log'), 8 * 1024) ?? 'sin log').split('\n').slice(-40).join('\n');
|
|
259
|
+
const summary = clean([
|
|
260
|
+
'## Entorno',
|
|
261
|
+
'',
|
|
262
|
+
'```',
|
|
263
|
+
info.split('\n## Entorno')[0].trim(),
|
|
264
|
+
'```',
|
|
265
|
+
'',
|
|
266
|
+
'## bond-app doctor',
|
|
267
|
+
'',
|
|
268
|
+
failing.length ? failing.join('\n') : 'Todo en orden.',
|
|
269
|
+
'',
|
|
270
|
+
'## Final del log del orquestador',
|
|
271
|
+
'',
|
|
272
|
+
'```',
|
|
273
|
+
logTail,
|
|
274
|
+
'```',
|
|
275
|
+
'',
|
|
276
|
+
'El zip con los logs completos (sin secretos) va adjunto.',
|
|
277
|
+
].join('\n'));
|
|
278
|
+
return { zip: zipFiles(files), files: files.map((f) => f.name), summary };
|
|
279
|
+
}
|
package/src/core/orchestrator.ts
CHANGED
|
@@ -2,7 +2,7 @@ import fs from 'node:fs';
|
|
|
2
2
|
import { piCompactionCommand, piCompactionOverrides } from './pi-compaction.ts';
|
|
3
3
|
import { promptArgs, unattendedFlags } from './agent-flags.ts';
|
|
4
4
|
import { isHerdrAgentWaiting, isLeaderHerdrAgent, isLeaderTerminal, isTerminalWaiting } from './agent-waiting.ts';
|
|
5
|
-
import { PI_SESSION_TAIL_SCRIPT, budgetExhaustedIn, piContextStuck, resumeTimeFrom, stuckReason, type PiSessionTail, type StuckKind } from './stuck.ts';
|
|
5
|
+
import { PI_SESSION_TAIL_SCRIPT, budgetExhaustedIn, compactionFailedIn, piContextStuck, resumeTimeFrom, stuckReason, type PiSessionTail, type StuckKind } from './stuck.ts';
|
|
6
6
|
import { BOND_APP_LOOP_CLI, LOOP_ENV_OFF_COMMAND, LOOP_ENV_ON_COMMAND, LOOP_LOG_APPEND_SCRIPT, LOOP_PLANS_SCRIPT, LOOP_SKILLS_SCRIPT, LOOP_TEXT_MAX, PLAN_PATH_RE, askMessage, loopEnv, loopLogMessage, loopLogPath, loopLogStart, loopMessageText, loopStartMessage, nextRound, sortPlans, type LoopState } from './loop.ts';
|
|
7
7
|
import { HANDOFF_GATHER_SCRIPT, buildHandoff, decisionsBy, parseGather, redactSecrets } from './handoff.ts';
|
|
8
8
|
import os from 'node:os';
|
|
@@ -40,6 +40,7 @@ import { HubMountError, HubSession, proposeUrls } from './hub-session.ts';
|
|
|
40
40
|
import { AzureDevOpsApiError, AzureDevOpsClient } from '../runner/azure-devops-client.ts';
|
|
41
41
|
import { azureRepoUrl, parseAzureRepoUrl, repoHostOf, repoLabel, validateRepoUrl } from './repo-host.ts';
|
|
42
42
|
import { parseSourceUrl, type PullRequestHit, type SourceHubInfo, type SourceHubRef, type SourceHubRepoStatus, type SourceInfo, type SourceRef } from './pr-source.ts';
|
|
43
|
+
import { UpdateChecker } from './updates.ts';
|
|
43
44
|
import { AgyLoginManager, AZURE_LOGIN_SPEC, CLAUDE_LOGIN_SPEC, CODEX_LOGIN_SPEC, COPILOT_LOGIN_SPEC, type AgyLoginDriver } from './agy-login.ts';
|
|
44
45
|
import { buildSetupState, parseRunnerManifest } from './setup.ts';
|
|
45
46
|
import { HUB_DIR, NAME_RE, agentGaps, analysisPrompt, buildAnalysis, fixedGaps, parseAgentAnswer, parseHubToml, repoNameFromUrl, teamAgentFor, teamAgents, type HubToml } from './hub.ts';
|
|
@@ -72,6 +73,9 @@ import type { AppConfig } from '../config.ts';
|
|
|
72
73
|
/** Gaps that are the hub agent's opinion, which a person may overrule («Seguir sin ellos»). */
|
|
73
74
|
const HUB_OPINION_GAPS = new Set(['missing_repo', 'agent_not_ready']);
|
|
74
75
|
|
|
76
|
+
/** A full context is relaunched on its own once in this window per agent; a second time waits for the person. */
|
|
77
|
+
export const AUTO_RELAUNCH_WINDOW_MS = 30 * 60 * 1000;
|
|
78
|
+
|
|
75
79
|
/** az's config in a run: no prompts about subscriptions, no telemetry. */
|
|
76
80
|
const AZURE_RUN_CONFIG = '[core]\nlogin_experience_v2 = off\ncollect_telemetry = false\n';
|
|
77
81
|
|
|
@@ -312,6 +316,8 @@ export class Orchestrator {
|
|
|
312
316
|
private deliveries = new Map<string, Promise<Run>>();
|
|
313
317
|
/** Issue #3: runs with an agent relaunch in progress (one at a time per run). */
|
|
314
318
|
private relaunching = new Set<string>();
|
|
319
|
+
/** When each run agent (`<run>/<name>`) was last relaunched on its own for a full context. */
|
|
320
|
+
private autoRelaunchedAt = new Map<string, number>();
|
|
315
321
|
// P4: a token given explicitly at start (not stored); delivery falls back to the stored one.
|
|
316
322
|
private runTokens = new Map<string, string>();
|
|
317
323
|
// P5: hub analyses in progress (fixed checks, hub agent, then the team), one per run.
|
|
@@ -331,6 +337,8 @@ export class Orchestrator {
|
|
|
331
337
|
public codexLoginManager: AgyLoginManager;
|
|
332
338
|
public copilotLoginManager: AgyLoginManager;
|
|
333
339
|
public azureLoginManager: AgyLoginManager;
|
|
340
|
+
/** «Hay versión nueva» (bond-app, bond): started by the real process (index.ts), not by tests. */
|
|
341
|
+
public updates = new UpdateChecker();
|
|
334
342
|
public jira: JiraClient;
|
|
335
343
|
|
|
336
344
|
constructor(
|
|
@@ -438,6 +446,7 @@ export class Orchestrator {
|
|
|
438
446
|
await this.codexLoginManager.cancel();
|
|
439
447
|
await this.copilotLoginManager.cancel();
|
|
440
448
|
await this.azureLoginManager.cancel();
|
|
449
|
+
this.updates.stop();
|
|
441
450
|
for (const [, w] of this.runPrWatchers.entries()) {
|
|
442
451
|
try { w.stop(); } catch {}
|
|
443
452
|
}
|
|
@@ -1863,7 +1872,7 @@ export class Orchestrator {
|
|
|
1863
1872
|
} catch {
|
|
1864
1873
|
screen = '';
|
|
1865
1874
|
}
|
|
1866
|
-
let finding = budgetExhaustedIn(screen);
|
|
1875
|
+
let finding = budgetExhaustedIn(screen) ?? compactionFailedIn(screen);
|
|
1867
1876
|
if (!finding) {
|
|
1868
1877
|
let argv: string[] | undefined;
|
|
1869
1878
|
try {
|
|
@@ -1908,6 +1917,23 @@ export class Orchestrator {
|
|
|
1908
1917
|
changed.push(r.id);
|
|
1909
1918
|
}
|
|
1910
1919
|
if (previous?.reason !== found.reason) this.agentEvent(latest, 'agent.stuck', { agent: found.name, kind: found.kind, reason: found.reason });
|
|
1920
|
+
// A full context (or a compaction that failed) is relaunched with a handoff on its own,
|
|
1921
|
+
// with the same kind; twice in AUTO_RELAUNCH_WINDOW_MS for the same agent waits for the person.
|
|
1922
|
+
if (found.kind === 'context' && this.config.autoRelaunchContext !== false) {
|
|
1923
|
+
const key = `${r.id}/${found.name}`;
|
|
1924
|
+
const last = this.autoRelaunchedAt.get(key) ?? 0;
|
|
1925
|
+
if (Date.now() - last >= AUTO_RELAUNCH_WINDOW_MS) {
|
|
1926
|
+
this.autoRelaunchedAt.set(key, Date.now());
|
|
1927
|
+
try {
|
|
1928
|
+
const from = (await this.relaunchOptions(r.id, found.name)).from;
|
|
1929
|
+
await this.relaunchAgent(r.id, found.name, { agent: from, reason: `automático: ${found.reason}` });
|
|
1930
|
+
this.agentEvent(this.runRepo.get(r.id) ?? latest, 'agent.auto_relaunched', { agent: found.name, kind: from, reason: found.reason });
|
|
1931
|
+
changed.push(r.id);
|
|
1932
|
+
} catch (err) {
|
|
1933
|
+
this.agentEvent(latest, 'agent.auto_relaunch_failed', { agent: found.name, error: String((err as Error).message || err).slice(0, 300) });
|
|
1934
|
+
}
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1911
1937
|
}
|
|
1912
1938
|
} finally {
|
|
1913
1939
|
this.checkingStuck = false;
|
|
@@ -59,7 +59,7 @@ function winQuote(arg: string): string {
|
|
|
59
59
|
export function buildTaskCommand(opts: WindowsServiceOptions = {}): string {
|
|
60
60
|
const nodePath = opts.nodePath ?? process.execPath;
|
|
61
61
|
const binPath = path.resolve(opts.binPath ?? path.join(repoRoot, 'bin', 'bond-app.js'));
|
|
62
|
-
const parts = [winQuote(nodePath), winQuote(binPath), 'start'];
|
|
62
|
+
const parts = [winQuote(nodePath), winQuote(binPath), 'start', '--as-service'];
|
|
63
63
|
if (opts.port !== undefined) {
|
|
64
64
|
parts.push('--port', String(opts.port));
|
|
65
65
|
}
|
package/src/core/service.ts
CHANGED
|
@@ -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,11 +184,14 @@ 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),
|
|
188
192
|
quoteSystemdArg(params.binPath),
|
|
189
193
|
'start',
|
|
194
|
+
'--as-service',
|
|
190
195
|
'--port',
|
|
191
196
|
String(params.port),
|
|
192
197
|
'--data-dir',
|
|
@@ -197,6 +202,7 @@ export function renderSystemdUnit(params: {
|
|
|
197
202
|
}
|
|
198
203
|
|
|
199
204
|
const envLines = [`Environment=${quoteSystemdEnv('BOND_APP_DATA_DIR', params.dataDir)}`];
|
|
205
|
+
if (params.servicePath) envLines.push(`Environment=${quoteSystemdEnv('PATH', params.servicePath)}`);
|
|
200
206
|
if (params.runnerImage) {
|
|
201
207
|
envLines.push(`Environment=${quoteSystemdEnv('RUNNER_IMAGE', params.runnerImage)}`);
|
|
202
208
|
}
|
|
@@ -241,11 +247,14 @@ export function renderLaunchdPlist(params: {
|
|
|
241
247
|
host?: string;
|
|
242
248
|
dataDir: string;
|
|
243
249
|
runnerImage?: string;
|
|
250
|
+
/** PATH for the service: launchd starts it with /usr/bin:/bin:/usr/sbin:/sbin only. */
|
|
251
|
+
servicePath?: string;
|
|
244
252
|
}): string {
|
|
245
253
|
const args = [
|
|
246
254
|
params.nodePath,
|
|
247
255
|
params.binPath,
|
|
248
256
|
'start',
|
|
257
|
+
'--as-service',
|
|
249
258
|
'--port',
|
|
250
259
|
String(params.port),
|
|
251
260
|
'--data-dir',
|
|
@@ -256,6 +265,7 @@ export function renderLaunchdPlist(params: {
|
|
|
256
265
|
}
|
|
257
266
|
|
|
258
267
|
const envEntries = [` <key>BOND_APP_DATA_DIR</key>`, ` <string>${escapeXml(params.dataDir)}</string>`];
|
|
268
|
+
if (params.servicePath) envEntries.push(` <key>PATH</key>`, ` <string>${escapeXml(params.servicePath)}</string>`);
|
|
259
269
|
if (params.runnerImage) {
|
|
260
270
|
envEntries.push(` <key>RUNNER_IMAGE</key>`, ` <string>${escapeXml(params.runnerImage)}</string>`);
|
|
261
271
|
}
|
|
@@ -417,6 +427,7 @@ export async function installService(options: ServiceOptions = {}): Promise<Serv
|
|
|
417
427
|
host: ctx.host,
|
|
418
428
|
dataDir: ctx.dataDir,
|
|
419
429
|
runnerImage: ctx.runnerImage,
|
|
430
|
+
servicePath: ctx.servicePath,
|
|
420
431
|
});
|
|
421
432
|
fs.writeFileSync(ctx.unitPath!, unitContent, { encoding: 'utf8', mode: 0o644 });
|
|
422
433
|
|
|
@@ -479,6 +490,7 @@ export async function installService(options: ServiceOptions = {}): Promise<Serv
|
|
|
479
490
|
host: ctx.host,
|
|
480
491
|
dataDir: ctx.dataDir,
|
|
481
492
|
runnerImage: ctx.runnerImage,
|
|
493
|
+
servicePath: ctx.servicePath,
|
|
482
494
|
});
|
|
483
495
|
fs.writeFileSync(ctx.unitPath!, plistContent, { encoding: 'utf8', mode: 0o644 });
|
|
484
496
|
|
|
@@ -859,3 +871,27 @@ async function windowsAction(action: ServiceAction, ctx: ServiceCtx): Promise<Se
|
|
|
859
871
|
detail: details.join('; '),
|
|
860
872
|
};
|
|
861
873
|
}
|
|
874
|
+
|
|
875
|
+
/**
|
|
876
|
+
* The PATH the orchestrator service runs with. launchd (and systemd --user) start it with a
|
|
877
|
+
* minimal PATH, without the folders where docker (OrbStack, Docker Desktop), hc, bond and
|
|
878
|
+
* herdr-app live: the orchestrator could not find them and did not start. The service keeps
|
|
879
|
+
* the PATH of whoever installs it, plus node's folder and the usual install folders.
|
|
880
|
+
*/
|
|
881
|
+
export function servicePathFor(current: string | undefined, nodePath: string, homeDir: string, platform: NodeJS.Platform): string | undefined {
|
|
882
|
+
if (platform === 'win32') return undefined;
|
|
883
|
+
const extra = [
|
|
884
|
+
path.dirname(nodePath),
|
|
885
|
+
path.join(homeDir, '.local', 'bin'),
|
|
886
|
+
...(platform === 'darwin' ? ['/opt/homebrew/bin', path.join(homeDir, '.orbstack', 'bin'), '/Applications/Docker.app/Contents/Resources/bin'] : []),
|
|
887
|
+
'/usr/local/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin',
|
|
888
|
+
];
|
|
889
|
+
const seen = new Set<string>();
|
|
890
|
+
const out: string[] = [];
|
|
891
|
+
for (const dir of [...String(current ?? '').split(':'), ...extra]) {
|
|
892
|
+
if (!dir || !path.isAbsolute(dir) || seen.has(dir)) continue;
|
|
893
|
+
seen.add(dir);
|
|
894
|
+
out.push(dir);
|
|
895
|
+
}
|
|
896
|
+
return out.join(':');
|
|
897
|
+
}
|
|
@@ -88,6 +88,8 @@ export interface SetupOptions {
|
|
|
88
88
|
export interface SetupDeps {
|
|
89
89
|
fetch?: FetchLike;
|
|
90
90
|
runCommand?: (cmd: string, args: string[], timeoutMs?: number) => Promise<CommandOutput>;
|
|
91
|
+
/** Where the installed bond comes from (npm, Homebrew, its own binary); tests fake it. */
|
|
92
|
+
bondOrigin?: (runCommand: (cmd: string, args: string[], timeoutMs?: number) => Promise<CommandOutput>, platform: NodeJS.Platform) => Promise<BondOrigin>;
|
|
91
93
|
homeDir?: string;
|
|
92
94
|
dataDir?: string;
|
|
93
95
|
herdrAppHome?: string;
|
|
@@ -757,13 +759,16 @@ export async function runSetup(options: SetupOptions = {}): Promise<SetupResult>
|
|
|
757
759
|
steps.push({ id: 'bond', ok: true, skipped: true, detail });
|
|
758
760
|
bondVersion = targetBondVersion;
|
|
759
761
|
} else {
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
762
|
+
// An old bond from Homebrew or its own binary is upgraded that way: npm would hit EEXIST.
|
|
763
|
+
const origin = bondRes.ok ? await (deps.bondOrigin ?? detectBondOrigin)(runCommand, platform) : { kind: 'none' as const, path: null };
|
|
764
|
+
const [bin, binArgs]: [string, string[]] = origin.kind === 'brew'
|
|
765
|
+
? ['brew', ['upgrade', BOND_BREW_FORMULA]]
|
|
766
|
+
: origin.kind === 'binary'
|
|
767
|
+
? ['bond', ['update']]
|
|
768
|
+
: ['npm', ['install', '-g', `@jmanuelcorral/bond@${targetBondVersion}`, NPM_PUBLIC_REGISTRY_ARG]];
|
|
769
|
+
const npmRes = await runCommand(bin, binArgs, 180_000);
|
|
765
770
|
if (!npmRes.ok) {
|
|
766
|
-
const fix =
|
|
771
|
+
const fix = `${bin} ${binArgs.join(' ')}`;
|
|
767
772
|
logStep('✗', 'bond CLI', npmRes.stderr.trim() || npmRes.error || 'npm install failed', fix);
|
|
768
773
|
steps.push({ id: 'bond', ok: false, detail: 'npm install failed' });
|
|
769
774
|
return { ok: false, dryRun, steps, record: null };
|
|
@@ -1099,29 +1104,34 @@ export async function runUpdate(options: UpdateOptions = {}): Promise<UpdateResu
|
|
|
1099
1104
|
|
|
1100
1105
|
log(`bond-app update (${normPlatform}${dryRun ? ', dry-run' : ''})`);
|
|
1101
1106
|
|
|
1102
|
-
// 1. Update
|
|
1103
|
-
//
|
|
1107
|
+
// 1. Update bond the way it was installed, first: up to 1.16.8 it shipped its own `bond-app`
|
|
1108
|
+
// bin, and npm would refuse to install bond-app over it (EEXIST). A bond from Homebrew
|
|
1109
|
+
// (jmanuelcorral/tap/bond) or bond's own binary is not npm's: `npm install -g` hits EEXIST
|
|
1110
|
+
// on its file. A failure here warns and goes on: bond-app still gets updated.
|
|
1111
|
+
const bondOrigin = await (deps.bondOrigin ?? detectBondOrigin)(runCommand, platform);
|
|
1112
|
+
const bondUpdate: [string, string[]] = bondOrigin.kind === 'brew'
|
|
1113
|
+
? ['brew', ['upgrade', BOND_BREW_FORMULA]]
|
|
1114
|
+
: bondOrigin.kind === 'binary'
|
|
1115
|
+
? ['bond', ['update']]
|
|
1116
|
+
: ['npm', ['install', '-g', '@jmanuelcorral/bond@latest', NPM_PUBLIC_REGISTRY_ARG]];
|
|
1117
|
+
const via = bondOrigin.kind === 'brew' ? 'Homebrew' : bondOrigin.kind === 'binary' ? `its own binary (${bondOrigin.path})` : 'npm';
|
|
1104
1118
|
if (dryRun) {
|
|
1105
|
-
const detail = `would run:
|
|
1119
|
+
const detail = `would run: ${bondUpdate[0]} ${bondUpdate[1].join(' ')} (bond from ${via})`;
|
|
1106
1120
|
logStep('✓', 'bond CLI', detail);
|
|
1107
1121
|
steps.push({ id: 'bond', ok: true, skipped: true, detail });
|
|
1108
1122
|
} else {
|
|
1109
|
-
const
|
|
1110
|
-
|
|
1111
|
-
[
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
const
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1123
|
+
const res = await runCommand(bondUpdate[0], bondUpdate[1], 180_000);
|
|
1124
|
+
if (!res.ok) {
|
|
1125
|
+
const fix = `${bondUpdate[0]} ${bondUpdate[1].join(' ')}`;
|
|
1126
|
+
logStep('!', 'bond CLI', `not updated (bond from ${via}): ${(res.stderr.trim() || res.error || 'failed').split('\n').slice(-3).join(' ')}`, fix);
|
|
1127
|
+
steps.push({ id: 'bond', ok: true, skipped: true, detail: `not updated (${via})` });
|
|
1128
|
+
} else {
|
|
1129
|
+
const verRes = await runCommand('bond', ['--version'], 10_000);
|
|
1130
|
+
const ver = verRes.ok ? extractSemver(verRes.stdout) : null;
|
|
1131
|
+
const detail = `${ver ? `updated to ${ver}` : 'updated'} (${via})`;
|
|
1132
|
+
logStep('✓', 'bond CLI', detail);
|
|
1133
|
+
steps.push({ id: 'bond', ok: true, detail });
|
|
1119
1134
|
}
|
|
1120
|
-
const verRes = await runCommand('bond', ['--version'], 10_000);
|
|
1121
|
-
const ver = verRes.ok ? extractSemver(verRes.stdout) : null;
|
|
1122
|
-
const detail = ver ? `updated to ${ver}` : 'updated';
|
|
1123
|
-
logStep('✓', 'bond CLI', detail);
|
|
1124
|
-
steps.push({ id: 'bond', ok: true, detail });
|
|
1125
1135
|
}
|
|
1126
1136
|
|
|
1127
1137
|
// 2. Update @jmanuelcorral/bond-app via npm (public registry)
|
|
@@ -1178,7 +1188,8 @@ export async function runUpdate(options: UpdateOptions = {}): Promise<UpdateResu
|
|
|
1178
1188
|
}
|
|
1179
1189
|
}
|
|
1180
1190
|
|
|
1181
|
-
// 4.
|
|
1191
|
+
// 4. Rewrite the user service (if installed) with this version's unit/plist, then restart it:
|
|
1192
|
+
// fixes to the service itself (macOS PATH, 0.3.1) reach existing installs this way.
|
|
1182
1193
|
const serviceDeps: ServiceDeps = {
|
|
1183
1194
|
runCommand,
|
|
1184
1195
|
platform,
|
|
@@ -1188,10 +1199,12 @@ export async function runUpdate(options: UpdateOptions = {}): Promise<UpdateResu
|
|
|
1188
1199
|
const svcStatus = await getServiceStatus({ port, host, dataDir, deps: serviceDeps });
|
|
1189
1200
|
if (svcStatus.supported && svcStatus.installed) {
|
|
1190
1201
|
if (dryRun) {
|
|
1191
|
-
const detail = `would restart user service (${svcStatus.serviceName})`;
|
|
1202
|
+
const detail = `would rewrite and restart user service (${svcStatus.serviceName})`;
|
|
1192
1203
|
logStep('✓', 'User service', detail);
|
|
1193
1204
|
steps.push({ id: 'service', ok: true, skipped: true, detail });
|
|
1194
1205
|
} else {
|
|
1206
|
+
const reinstall = await (deps.installService ?? installService)({ port, host, dataDir, runnerImage: options.runnerImage, deps: serviceDeps });
|
|
1207
|
+
if (!reinstall.ok) logStep('!', 'User service', `could not rewrite it: ${reinstall.detail}`);
|
|
1195
1208
|
const svcRes = await restartSvcFn({
|
|
1196
1209
|
port,
|
|
1197
1210
|
host,
|
|
@@ -1399,3 +1412,48 @@ export async function runUninstall(options: UninstallOptions = {}): Promise<Unin
|
|
|
1399
1412
|
log(' Note: herdr-app, hc and bond were not uninstalled (they may be used by other projects).');
|
|
1400
1413
|
return { ok: allOk, dryRun, purged, steps };
|
|
1401
1414
|
}
|
|
1415
|
+
|
|
1416
|
+
/** The Homebrew formula of bond (the jmanuelcorral tap). */
|
|
1417
|
+
export const BOND_BREW_FORMULA = 'jmanuelcorral/tap/bond';
|
|
1418
|
+
|
|
1419
|
+
export interface BondOrigin {
|
|
1420
|
+
kind: 'npm' | 'brew' | 'binary' | 'none';
|
|
1421
|
+
path: string | null;
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
/**
|
|
1425
|
+
* Where the `bond` on PATH comes from, by its real path: Homebrew's Cellar, npm's global
|
|
1426
|
+
* node_modules, or bond's own binary (install.sh); none when there is no bond.
|
|
1427
|
+
*/
|
|
1428
|
+
export async function detectBondOrigin(
|
|
1429
|
+
runCommand: (cmd: string, args: string[], timeoutMs?: number) => Promise<CommandOutput>,
|
|
1430
|
+
platform: NodeJS.Platform
|
|
1431
|
+
): Promise<BondOrigin> {
|
|
1432
|
+
const exe = platform === 'win32' ? ['bond.cmd', 'bond.exe', 'bond'] : ['bond'];
|
|
1433
|
+
let found: string | null = null;
|
|
1434
|
+
for (const dir of String(process.env.PATH ?? '').split(path.delimiter)) {
|
|
1435
|
+
for (const name of exe) {
|
|
1436
|
+
const p = path.join(dir, name);
|
|
1437
|
+
if (dir && fs.existsSync(p)) {
|
|
1438
|
+
found = p;
|
|
1439
|
+
break;
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
if (found) break;
|
|
1443
|
+
}
|
|
1444
|
+
if (!found) return { kind: 'none', path: null };
|
|
1445
|
+
let real = found;
|
|
1446
|
+
try {
|
|
1447
|
+
real = fs.realpathSync(found);
|
|
1448
|
+
} catch {}
|
|
1449
|
+
return { kind: classifyBondPath(real, (await runCommand('npm', ['root', '-g'], 15_000)).stdout.trim()), path: real };
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
/** brew when it lives in a Homebrew Cellar, npm when under npm's global root (or an npm package), else binary. */
|
|
1453
|
+
export function classifyBondPath(real: string, npmRoot: string): BondOrigin['kind'] {
|
|
1454
|
+
const r = real.replace(/\\/g, '/');
|
|
1455
|
+
if (/\/Cellar\/bond\//.test(r) || /\/homebrew\/Cellar\//i.test(r)) return 'brew';
|
|
1456
|
+
const root = npmRoot.replace(/\\/g, '/');
|
|
1457
|
+
if ((root && r.startsWith(`${root}/`)) || /\/node_modules\/@jmanuelcorral\/bond\//.test(r)) return 'npm';
|
|
1458
|
+
return 'binary';
|
|
1459
|
+
}
|
package/src/core/stuck.ts
CHANGED
|
@@ -42,6 +42,18 @@ const RESET_PATTERNS: RegExp[] = [
|
|
|
42
42
|
/try again (?:in|at)\s+([^.\n]{1,30})/i,
|
|
43
43
|
];
|
|
44
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
|
+
|
|
45
57
|
/** The last lines of an agent's screen tell an exhausted budget, and when it resets. */
|
|
46
58
|
export function budgetExhaustedIn(screen: string): StuckFinding | null {
|
|
47
59
|
// The bottom of the screen only: the notice is the agent's last word, and a limit mentioned
|