duckhunt-runner 0.3.1 → 0.4.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.
- package/README.md +78 -3
- package/dist/claim.d.ts +86 -0
- package/dist/claim.d.ts.map +1 -0
- package/dist/claim.js +180 -0
- package/dist/claim.js.map +1 -0
- package/dist/claude-args.d.ts +23 -0
- package/dist/claude-args.d.ts.map +1 -0
- package/dist/claude-args.js +59 -0
- package/dist/claude-args.js.map +1 -0
- package/dist/claude.d.ts +22 -3
- package/dist/claude.d.ts.map +1 -1
- package/dist/claude.js +17 -6
- package/dist/claude.js.map +1 -1
- package/dist/config.d.ts +1 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +3 -1
- package/dist/config.js.map +1 -1
- package/dist/conversation-gc.d.ts +22 -0
- package/dist/conversation-gc.d.ts.map +1 -0
- package/dist/conversation-gc.js +72 -0
- package/dist/conversation-gc.js.map +1 -0
- package/dist/daemon.d.ts +16 -5
- package/dist/daemon.d.ts.map +1 -1
- package/dist/daemon.js +371 -171
- package/dist/daemon.js.map +1 -1
- package/dist/event-uploader.d.ts +31 -0
- package/dist/event-uploader.d.ts.map +1 -0
- package/dist/event-uploader.js +124 -0
- package/dist/event-uploader.js.map +1 -0
- package/dist/feed.d.ts +29 -0
- package/dist/feed.d.ts.map +1 -0
- package/dist/feed.js +142 -0
- package/dist/feed.js.map +1 -0
- package/dist/index.js +14 -4
- package/dist/index.js.map +1 -1
- package/dist/oauth.d.ts.map +1 -1
- package/dist/oauth.js +5 -2
- package/dist/oauth.js.map +1 -1
- package/dist/scrub-env.d.ts +3 -0
- package/dist/scrub-env.d.ts.map +1 -0
- package/dist/scrub-env.js +59 -0
- package/dist/scrub-env.js.map +1 -0
- package/dist/secret-mask.d.ts +4 -0
- package/dist/secret-mask.d.ts.map +1 -0
- package/dist/secret-mask.js +34 -0
- package/dist/secret-mask.js.map +1 -0
- package/dist/status-report.d.ts +30 -0
- package/dist/status-report.d.ts.map +1 -0
- package/dist/status-report.js +61 -0
- package/dist/status-report.js.map +1 -0
- package/dist/status.d.ts.map +1 -1
- package/dist/status.js +2 -0
- package/dist/status.js.map +1 -1
- package/dist/version.d.ts +3 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +21 -0
- package/dist/version.js.map +1 -0
- package/dist/worktree.d.ts +29 -0
- package/dist/worktree.d.ts.map +1 -0
- package/dist/worktree.js +190 -0
- package/dist/worktree.js.map +1 -0
- package/package.json +3 -2
package/dist/daemon.js
CHANGED
|
@@ -1,8 +1,20 @@
|
|
|
1
|
-
// loop del daemon (contrato 42): reclama runs por poll, lanza `claude -p`
|
|
2
|
-
// checkout del repo (o en el scratch dir si no hay repo) con el mcp de
|
|
3
|
-
// perfil de tools del claim,
|
|
4
|
-
// usuario. el server nunca ve paths ni perfiles — el mapa
|
|
5
|
-
// en la config local.
|
|
1
|
+
// loop del daemon (contrato 42 + prompts libres t#378): reclama runs por poll, lanza `claude -p`
|
|
2
|
+
// headless en un worktree del checkout del repo (o en el scratch dir si no hay repo) con el mcp de
|
|
3
|
+
// duckhunt adjunto y el perfil de tools del claim, sube el feed de progreso y reporta el cierre. un
|
|
4
|
+
// run a la vez: el cómputo es la máquina del usuario. el server nunca ve paths ni perfiles — el mapa
|
|
5
|
+
// repo→checkout y cuenta→perfil vive en la config local.
|
|
6
|
+
// decisiones:
|
|
7
|
+
// - claude corre en su PROPIO grupo de procesos (detached): cancelar, el timeout o parar el daemon
|
|
8
|
+
// matan también lo que lanzó la tool Bash (tests, servidores). por eso el daemon instala sus
|
|
9
|
+
// handlers de SIGINT/SIGTERM: ctrl-c ya no le llega al hijo por la terminal.
|
|
10
|
+
// - kind=prompt usa un worktree POR CONVERSACIÓN que sobrevive entre segmentos (worktree.ts); lo
|
|
11
|
+
// recoge conversation-gc.ts entre runs. los runs de reglas siguen con su worktree efímero.
|
|
12
|
+
// - el feed (event-uploader.ts) se vacía ANTES de reportar el status: el server rechaza eventos de
|
|
13
|
+
// un run cerrado.
|
|
14
|
+
// - el segmento del claim viaja en heartbeat/progress/events/status: es lo que distingue a ESTE
|
|
15
|
+
// proceso del siguiente turno de la misma fila. el latido mata claude en cuanto el run deja de ser
|
|
16
|
+
// suyo (cancelado, re-encolado tras detenerlo, dado por fallido, borrado → 404, reclamado por otro
|
|
17
|
+
// segmento), no solo con `cancel`: un proceso detenido no puede seguir 30 min con Bash.
|
|
6
18
|
import { execFile, spawn } from 'node:child_process';
|
|
7
19
|
import crypto from 'node:crypto';
|
|
8
20
|
import fs from 'node:fs';
|
|
@@ -13,22 +25,78 @@ import { promisify } from 'node:util';
|
|
|
13
25
|
import { refreshAccess } from './oauth.js';
|
|
14
26
|
import { logsDir, scratchDir } from './config.js';
|
|
15
27
|
import { consumeStreamLine, detectClaude, newStreamState } from './claude.js';
|
|
28
|
+
import { buildClaudeArgs, PROMPT_REQUIRED_FLAGS } from './claude-args.js';
|
|
29
|
+
import { claimRunId, EVENTS_DEFAULTS, parseClaim, RUN_KIND, RUNNER_CAPABILITY } from './claim.js';
|
|
30
|
+
import { EventUploader } from './event-uploader.js';
|
|
31
|
+
import { clip, feedEventsFromStream, systemEvent } from './feed.js';
|
|
32
|
+
import { scrubEnv } from './scrub-env.js';
|
|
33
|
+
import { clampReport, reportFor } from './status-report.js';
|
|
34
|
+
import { prepareConversationWorktree, prepareRunWorktree, removeRunWorktree, touchWorktree } from './worktree.js';
|
|
35
|
+
import { chunk, CONVERSATION_GC_INTERVAL_MS, listWorktreeCandidates, removeWorktrees, selectForRemoval } from './conversation-gc.js';
|
|
36
|
+
import { runnerVersion } from './version.js';
|
|
16
37
|
const execFileP = promisify(execFile);
|
|
17
38
|
const CLAIM_POLL_MS = 5_000;
|
|
18
39
|
// margen para refrescar el access token del daemon antes de que caduque.
|
|
19
40
|
const TOKEN_REFRESH_MARGIN_MS = 5 * 60_000;
|
|
20
|
-
// SIGTERM → SIGKILL si el proceso no muere en este margen.
|
|
41
|
+
// SIGTERM → SIGKILL (al grupo) si el proceso no muere en este margen.
|
|
21
42
|
const KILL_GRACE_MS = 10_000;
|
|
43
|
+
// tras la salida de claude, espera máxima a que se cierren sus pipes: un proceso en background que
|
|
44
|
+
// los heredó retendría el 'close' para siempre.
|
|
45
|
+
const EXIT_DRAIN_MS = 5_000;
|
|
22
46
|
// throttle del reporte de tool calls al server.
|
|
23
47
|
const PROGRESS_MIN_INTERVAL_MS = 5_000;
|
|
48
|
+
const PROGRESS_TICK_MS = 1_000;
|
|
49
|
+
const MIN_HEARTBEAT_MS = 5_000;
|
|
50
|
+
const MIN_RUN_TIMEOUT_MS = 60_000;
|
|
24
51
|
const STDERR_TAIL_LINES = 20;
|
|
25
52
|
const STDERR_TAIL_MAX_CHARS = 4000;
|
|
53
|
+
// toda llamada al server: sin respuesta en este plazo cuenta como fallo de red.
|
|
54
|
+
const API_TIMEOUT_MS = 30_000;
|
|
55
|
+
// POST /status: intentos con backoff exponencial (2 s, 4 s, 8 s, 16 s).
|
|
56
|
+
const STATUS_POST_ATTEMPTS = 5;
|
|
57
|
+
const STATUS_POST_BACKOFF_MS = 2_000;
|
|
58
|
+
// tras SIGINT/SIGTERM: margen para cerrar el run en curso antes de salir a la fuerza.
|
|
59
|
+
const SHUTDOWN_GRACE_MS = 20_000;
|
|
60
|
+
const EXIT_CODE_SIGINT = 130;
|
|
61
|
+
const EXIT_CODE_SIGTERM = 143;
|
|
62
|
+
// topes de lo que el claim anuncia (RUNNER_CLAUDE_VERSION_MAX_CHARS) y de la nota de workdir.
|
|
63
|
+
const CLAUDE_VERSION_MAX_CHARS = 80;
|
|
64
|
+
const WORKDIR_MAX_CHARS = 300;
|
|
65
|
+
const HTTP_CONFLICT = 409;
|
|
66
|
+
const HTTP_NOT_FOUND = 404;
|
|
67
|
+
const HTTP_TIMEOUT = 408;
|
|
68
|
+
// estado del run que el latido espera mientras el proceso es su dueño.
|
|
69
|
+
const RUN_STATUS_RUNNING = 'running';
|
|
70
|
+
const HTTP_TOO_MANY = 429;
|
|
71
|
+
const HTTP_SERVER_ERROR = 500;
|
|
72
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
73
|
+
const isTransient = (status) => status === HTTP_TIMEOUT || status === HTTP_TOO_MANY || status >= HTTP_SERVER_ERROR;
|
|
74
|
+
// señal a todo el grupo de procesos del hijo (spawn detached → pgid = pid del hijo).
|
|
75
|
+
function signalGroup(child, signal) {
|
|
76
|
+
if (child.pid === undefined)
|
|
77
|
+
return;
|
|
78
|
+
try {
|
|
79
|
+
process.kill(-child.pid, signal);
|
|
80
|
+
}
|
|
81
|
+
catch (err) {
|
|
82
|
+
// ESRCH: el grupo ya no existe. cualquier otro fallo: al menos al hijo directo.
|
|
83
|
+
if (err.code !== 'ESRCH')
|
|
84
|
+
child.kill(signal);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
26
87
|
export class RunnerDaemon {
|
|
27
88
|
cfg;
|
|
28
89
|
opts;
|
|
29
90
|
access = null;
|
|
30
91
|
claude = { version: null, supported: new Set() };
|
|
31
92
|
hasAws = false;
|
|
93
|
+
// hijo en curso (un run a la vez) y su kill con motivo.
|
|
94
|
+
active = null;
|
|
95
|
+
killActive = null;
|
|
96
|
+
stopping = false;
|
|
97
|
+
exitCode = 0;
|
|
98
|
+
wake = null;
|
|
99
|
+
lastGcAt = 0;
|
|
32
100
|
constructor(cfg, opts = {}) {
|
|
33
101
|
this.cfg = cfg;
|
|
34
102
|
this.opts = opts;
|
|
@@ -39,7 +107,7 @@ export class RunnerDaemon {
|
|
|
39
107
|
}
|
|
40
108
|
return this.access.token;
|
|
41
109
|
}
|
|
42
|
-
// fetch autenticado contra /api/runner con un reintento tras refresh en 401.
|
|
110
|
+
// fetch autenticado contra /api/runner con timeout y un reintento tras refresh en 401.
|
|
43
111
|
async api(pathname, body) {
|
|
44
112
|
const call = async () => fetch(`${this.cfg.baseUrl}/api/runner${pathname}`, {
|
|
45
113
|
method: 'POST',
|
|
@@ -48,6 +116,7 @@ export class RunnerDaemon {
|
|
|
48
116
|
'Content-Type': 'application/json',
|
|
49
117
|
},
|
|
50
118
|
body: body === undefined ? '{}' : JSON.stringify(body),
|
|
119
|
+
signal: AbortSignal.timeout(API_TIMEOUT_MS),
|
|
51
120
|
});
|
|
52
121
|
const first = await call();
|
|
53
122
|
if (first.status !== 401)
|
|
@@ -58,80 +127,185 @@ export class RunnerDaemon {
|
|
|
58
127
|
label() {
|
|
59
128
|
return this.cfg.label ?? os.hostname();
|
|
60
129
|
}
|
|
61
|
-
|
|
130
|
+
// capacidades que se anuncian: prompt solo si el cli puede cumplir su perfil (permission mode
|
|
131
|
+
// explícito, sin mcp del repo, deny list y settings solo del usuario en lectura).
|
|
132
|
+
capabilities() {
|
|
133
|
+
return [
|
|
134
|
+
...(this.hasAws ? [RUNNER_CAPABILITY.aws] : []),
|
|
135
|
+
...(PROMPT_REQUIRED_FLAGS.every((f) => this.claude.supported.has(f)) ? [RUNNER_CAPABILITY.prompt] : []),
|
|
136
|
+
RUNNER_CAPABILITY.events,
|
|
137
|
+
];
|
|
138
|
+
}
|
|
139
|
+
/** loop principal: gc → claim → ejecutar → repetir, hasta SIGINT/SIGTERM. devuelve el exit code. */
|
|
62
140
|
async run() {
|
|
63
141
|
this.claude = await detectClaude();
|
|
64
142
|
if (!this.claude.version) {
|
|
65
143
|
throw new Error('no se encuentra `claude` en el PATH: instala claude code y haz login antes de arrancar el daemon');
|
|
66
144
|
}
|
|
67
|
-
this.hasAws = await execFileP('aws', ['--version']).then(() => true
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
runnerLabel: this.label(),
|
|
74
|
-
repos: Object.keys(this.cfg.repos),
|
|
75
|
-
awsAccounts: Object.keys(this.cfg.aws),
|
|
76
|
-
capabilities: this.hasAws ? ['aws'] : [],
|
|
77
|
-
});
|
|
78
|
-
if (res.status === 200)
|
|
79
|
-
claim = (await res.json());
|
|
80
|
-
else if (res.status !== 204) {
|
|
81
|
-
console.error(`[runner] claim falló: http ${res.status} ${await res.text().catch(() => '')}`);
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
catch (err) {
|
|
85
|
-
console.error(`[runner] claim inaccesible: ${err.message}`);
|
|
86
|
-
}
|
|
145
|
+
this.hasAws = await execFileP('aws', ['--version']).then(() => true, () => false);
|
|
146
|
+
this.installSignalHandlers();
|
|
147
|
+
console.log(`[runner] duckhunt-runner ${runnerVersion() ?? '?'} · ${this.label()} → ${this.cfg.baseUrl} (claude ${this.claude.version}, aws cli ${this.hasAws ? 'sí' : 'no'}, ${Object.keys(this.cfg.repos).length} repos, ${Object.keys(this.cfg.aws).length} cuentas aws, capacidades ${this.capabilities().join(',')}, poll ${CLAIM_POLL_MS / 1000}s)`);
|
|
148
|
+
while (!this.stopping) {
|
|
149
|
+
await this.collectWorktrees();
|
|
150
|
+
const claim = this.stopping ? null : await this.claim();
|
|
87
151
|
if (claim) {
|
|
88
152
|
await this.executeRun(claim).catch((err) => {
|
|
89
153
|
console.error(`[runner] run ${claim.run.id} reventó: ${err.message}`);
|
|
90
154
|
});
|
|
91
155
|
}
|
|
92
|
-
else {
|
|
93
|
-
await
|
|
156
|
+
else if (!this.stopping) {
|
|
157
|
+
await this.idle(CLAIM_POLL_MS);
|
|
94
158
|
}
|
|
95
159
|
}
|
|
160
|
+
console.log('[runner] detenido');
|
|
161
|
+
return this.exitCode;
|
|
96
162
|
}
|
|
97
|
-
//
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
163
|
+
// espera interrumpible por una señal de parada.
|
|
164
|
+
idle(ms) {
|
|
165
|
+
return new Promise((resolve) => {
|
|
166
|
+
const timer = setTimeout(() => {
|
|
167
|
+
this.wake = null;
|
|
168
|
+
resolve();
|
|
169
|
+
}, ms);
|
|
170
|
+
this.wake = () => {
|
|
171
|
+
clearTimeout(timer);
|
|
172
|
+
this.wake = null;
|
|
173
|
+
resolve();
|
|
174
|
+
};
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
// primera señal: parar tras cerrar el run en curso (se mata su grupo y se reporta); segunda
|
|
178
|
+
// señal o margen agotado: salida inmediata matando el grupo.
|
|
179
|
+
installSignalHandlers() {
|
|
180
|
+
const onSignal = (signal, code) => {
|
|
181
|
+
const forceExit = () => {
|
|
182
|
+
if (this.active)
|
|
183
|
+
signalGroup(this.active, 'SIGKILL');
|
|
184
|
+
process.exit(code);
|
|
185
|
+
};
|
|
186
|
+
if (this.stopping)
|
|
187
|
+
forceExit();
|
|
188
|
+
this.stopping = true;
|
|
189
|
+
this.exitCode = code;
|
|
190
|
+
console.log(`[runner] ${signal}: deteniendo${this.killActive ? ' el run en curso' : ''} (otra señal fuerza la salida)`);
|
|
191
|
+
this.killActive?.('shutdown');
|
|
192
|
+
this.wake?.();
|
|
193
|
+
setTimeout(forceExit, SHUTDOWN_GRACE_MS).unref();
|
|
194
|
+
};
|
|
195
|
+
process.on('SIGINT', () => onSignal('SIGINT', EXIT_CODE_SIGINT));
|
|
196
|
+
process.on('SIGTERM', () => onSignal('SIGTERM', EXIT_CODE_SIGTERM));
|
|
197
|
+
}
|
|
198
|
+
// --- claim ---
|
|
199
|
+
async claim() {
|
|
200
|
+
let res;
|
|
201
|
+
try {
|
|
202
|
+
res = await this.api('/claim', {
|
|
203
|
+
runnerLabel: this.label(),
|
|
204
|
+
repos: Object.keys(this.cfg.repos),
|
|
205
|
+
awsAccounts: Object.keys(this.cfg.aws),
|
|
206
|
+
capabilities: this.capabilities(),
|
|
207
|
+
...(runnerVersion() ? { version: runnerVersion() } : {}),
|
|
208
|
+
...(this.claude.version ? { claudeVersion: this.claude.version.slice(0, CLAUDE_VERSION_MAX_CHARS) } : {}),
|
|
209
|
+
});
|
|
103
210
|
}
|
|
104
|
-
|
|
105
|
-
|
|
211
|
+
catch (err) {
|
|
212
|
+
console.error(`[runner] claim inaccesible: ${err.message}`);
|
|
213
|
+
return null;
|
|
106
214
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
215
|
+
// 204 = nada que hacer (o runner pausado desde /settings/agents).
|
|
216
|
+
if (res.status === 204)
|
|
217
|
+
return null;
|
|
218
|
+
if (res.status !== 200) {
|
|
219
|
+
console.error(`[runner] claim falló: http ${res.status} ${await res.text().catch(() => '')}`);
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
const raw = await res.json().catch((err) => {
|
|
223
|
+
console.error(`[runner] claim con json ilegible: ${err.message}`);
|
|
224
|
+
return null;
|
|
225
|
+
});
|
|
226
|
+
try {
|
|
227
|
+
return parseClaim(raw);
|
|
228
|
+
}
|
|
229
|
+
catch (err) {
|
|
230
|
+
// el run ya está reclamado (running): si su id es usable se cierra con el motivo; si no, lo
|
|
231
|
+
// cerrará el sweeper del server.
|
|
232
|
+
const message = err.message;
|
|
233
|
+
console.error(`[runner] ${message}`);
|
|
234
|
+
const id = claimRunId(raw);
|
|
235
|
+
if (id !== null)
|
|
236
|
+
await this.postStatus(id, { status: 'failed', error: message });
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
// --- gc de worktrees (entre runs, throttled) ---
|
|
241
|
+
// conversaciones abiertas según el server. si no contesta (o es anterior a t#378), todas se dan
|
|
242
|
+
// por abiertas: entonces solo actúa el ttl de inactividad, que nunca pierde trabajo.
|
|
243
|
+
async openConversations(runIds) {
|
|
244
|
+
const open = new Set();
|
|
245
|
+
// i/o secuencial: pocas llamadas, en orden.
|
|
246
|
+
for (const ids of chunk(runIds)) {
|
|
247
|
+
const res = await this.api('/conversations', { runIds: ids }).catch((err) => {
|
|
248
|
+
console.error(`[runner] gc: /conversations inaccesible: ${err.message}`);
|
|
249
|
+
return null;
|
|
250
|
+
});
|
|
251
|
+
const body = res?.ok ? (await res.json().catch(() => null)) : null;
|
|
252
|
+
if (!body || !Array.isArray(body.open)) {
|
|
253
|
+
if (res && !res.ok)
|
|
254
|
+
console.error(`[runner] gc: /conversations respondió http ${res.status}: solo se aplica el ttl`);
|
|
255
|
+
ids.forEach((id) => open.add(id));
|
|
256
|
+
continue;
|
|
122
257
|
}
|
|
258
|
+
body.open.filter((id) => Number.isSafeInteger(id)).forEach((id) => open.add(id));
|
|
123
259
|
}
|
|
124
|
-
|
|
260
|
+
return open;
|
|
125
261
|
}
|
|
126
|
-
async
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
262
|
+
async collectWorktrees() {
|
|
263
|
+
if (Date.now() - this.lastGcAt < CONVERSATION_GC_INTERVAL_MS)
|
|
264
|
+
return;
|
|
265
|
+
this.lastGcAt = Date.now();
|
|
266
|
+
try {
|
|
267
|
+
const candidates = listWorktreeCandidates(Object.values(this.cfg.repos).map((r) => r.path));
|
|
268
|
+
if (candidates.length === 0)
|
|
269
|
+
return;
|
|
270
|
+
const open = await this.openConversations(candidates.filter((c) => c.kind === 'conversation').map((c) => c.runId));
|
|
271
|
+
const targets = selectForRemoval(candidates, open, Date.now());
|
|
272
|
+
if (targets.length === 0)
|
|
273
|
+
return;
|
|
274
|
+
const removed = await removeWorktrees(targets, scrubEnv(process.env));
|
|
275
|
+
if (removed > 0)
|
|
276
|
+
console.log(`[runner] gc: ${removed} worktree(s) recogido(s)`);
|
|
277
|
+
}
|
|
278
|
+
catch (err) {
|
|
279
|
+
console.error(`[runner] gc de worktrees falló: ${err.message}`);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
// --- cwd del run: worktree de conversación, worktree por run, checkout o scratch ---
|
|
283
|
+
async prepareWorkdir(run, env) {
|
|
284
|
+
const repoCfg = run.repo && Object.hasOwn(this.cfg.repos, run.repo) ? this.cfg.repos[run.repo] : null;
|
|
285
|
+
const scratch = (note, warnings = []) => ({ workdir: scratchDir(), repoCfg: null, worktree: null, conversation: false, note, warnings });
|
|
286
|
+
if (!run.repo)
|
|
287
|
+
return scratch('scratch · sin repo');
|
|
288
|
+
if (!repoCfg)
|
|
289
|
+
return scratch('scratch · sin repo mapeado', [`repo ${run.repo} no mapeado en este runner: corriendo en scratch`]);
|
|
290
|
+
if (!fs.existsSync(repoCfg.path)) {
|
|
291
|
+
console.log(`[runner] run ${run.id}: el checkout ${repoCfg.path} no existe`);
|
|
292
|
+
return scratch('scratch · checkout no encontrado', [`el checkout de ${run.repo} no existe en este runner: corriendo en scratch`]);
|
|
293
|
+
}
|
|
294
|
+
if (run.kind === RUN_KIND.prompt) {
|
|
295
|
+
// worktree siempre: `worktree: false` y skip-permissions del repo son solo para runs de reglas.
|
|
296
|
+
const wt = await prepareConversationWorktree(repoCfg.path, run.id, run.branch, env);
|
|
297
|
+
return { ...wt, repoCfg, worktree: wt.workdir, conversation: true };
|
|
298
|
+
}
|
|
299
|
+
if (repoCfg.worktree === false)
|
|
300
|
+
return { workdir: repoCfg.path, repoCfg, worktree: null, conversation: false, note: 'checkout · sin worktree', warnings: [] };
|
|
301
|
+
const wt = await prepareRunWorktree(repoCfg.path, run.id, run.branch, env);
|
|
302
|
+
return { ...wt, repoCfg, worktree: wt.workdir, conversation: false };
|
|
130
303
|
}
|
|
131
|
-
// --- env del run: el del usuario + perfil aws mapeado ---
|
|
304
|
+
// --- env del run: el del usuario saneado + perfil aws mapeado ---
|
|
132
305
|
envFor(run) {
|
|
133
|
-
const env = { ...process.env, AWS_PAGER: '' };
|
|
134
|
-
const
|
|
306
|
+
const env = { ...scrubEnv(process.env), AWS_PAGER: '' };
|
|
307
|
+
const accountId = run.aws?.accountId;
|
|
308
|
+
const account = accountId && Object.hasOwn(this.cfg.aws, accountId) ? this.cfg.aws[accountId] : undefined;
|
|
135
309
|
if (account) {
|
|
136
310
|
env.AWS_PROFILE = account.profile;
|
|
137
311
|
const region = account.region ?? run.aws?.region ?? undefined;
|
|
@@ -143,122 +317,105 @@ export class RunnerDaemon {
|
|
|
143
317
|
}
|
|
144
318
|
return env;
|
|
145
319
|
}
|
|
146
|
-
// --- args de claude ---
|
|
147
|
-
claudeArgs(claim, prompt, mcpFile, repoCfg, resumeSessionId) {
|
|
148
|
-
const has = (f) => this.claude.supported.has(f);
|
|
149
|
-
const args = ['-p', prompt, '--output-format', 'stream-json'];
|
|
150
|
-
if (has('--verbose'))
|
|
151
|
-
args.push('--verbose');
|
|
152
|
-
args.push('--mcp-config', mcpFile);
|
|
153
|
-
if (has('--strict-mcp-config'))
|
|
154
|
-
args.push('--strict-mcp-config');
|
|
155
|
-
if (claim.tools.allowed.length > 0)
|
|
156
|
-
args.push('--allowedTools', claim.tools.allowed.join(','));
|
|
157
|
-
if (has('--disallowedTools') && claim.tools.disallowed.length > 0)
|
|
158
|
-
args.push('--disallowedTools', claim.tools.disallowed.join(','));
|
|
159
|
-
if (has('--permission-mode') && claim.permissionMode)
|
|
160
|
-
args.push('--permission-mode', claim.permissionMode);
|
|
161
|
-
if (has('--max-turns') && claim.maxTurns > 0)
|
|
162
|
-
args.push('--max-turns', String(claim.maxTurns));
|
|
163
|
-
// presupuesto: solo tiene sentido cuando el coste es REAL (api key). con login de
|
|
164
|
-
// suscripción el cli lo aplicaría sobre un coste nominal que nadie paga y mata runs
|
|
165
|
-
// legítimos (el guard contra loops es el timeout). config manda: número = forzar, 0 = nunca.
|
|
166
|
-
const payingWithApiKey = !!process.env.ANTHROPIC_API_KEY;
|
|
167
|
-
const budget = this.cfg.defaults.maxBudgetUsd ?? (payingWithApiKey ? claim.maxBudgetUsd : 0);
|
|
168
|
-
if (has('--max-budget-usd') && budget > 0)
|
|
169
|
-
args.push('--max-budget-usd', String(budget));
|
|
170
|
-
if (this.cfg.defaults.model)
|
|
171
|
-
args.push('--model', this.cfg.defaults.model);
|
|
172
|
-
if (repoCfg?.dangerouslySkipPermissions)
|
|
173
|
-
args.push('--dangerously-skip-permissions');
|
|
174
|
-
if (resumeSessionId)
|
|
175
|
-
args.push('--resume', resumeSessionId);
|
|
176
|
-
return args;
|
|
177
|
-
}
|
|
178
320
|
// --- ejecución ---
|
|
179
321
|
async executeRun(claim) {
|
|
180
322
|
const { run } = claim;
|
|
181
|
-
|
|
323
|
+
const tag = `run ${run.id}`;
|
|
324
|
+
console.log(`[runner] ${tag} reclamado (${run.kind}${run.profile ? `, perfil ${run.profile}` : ''}, entry ${run.entryId}${claim.tier ? `, tier ${claim.tier}` : ''}${run.repo ? `, repo ${run.repo}${run.branch ? `@${run.branch}` : ''}` : ''}${run.sessionId ? `, sesión ${run.sessionId}` : ''})`);
|
|
325
|
+
const env = this.envFor(run);
|
|
326
|
+
// identidad del proceso en cada llamada del run (servers anteriores a los segmentos: nada).
|
|
327
|
+
const seg = run.segment !== null ? { segment: run.segment } : {};
|
|
328
|
+
const feed = claim.events?.enabled ? new EventUploader((events) => this.postEvents(run.id, events, seg), claim.events, tag) : null;
|
|
182
329
|
let prepared;
|
|
183
330
|
try {
|
|
184
|
-
prepared = await this.prepareWorkdir(run);
|
|
331
|
+
prepared = await this.prepareWorkdir(run, env);
|
|
185
332
|
}
|
|
186
333
|
catch (err) {
|
|
187
|
-
await
|
|
334
|
+
await feed?.close();
|
|
335
|
+
await this.postStatus(run.id, { status: 'failed', error: `no se pudo preparar el directorio del run: ${err.message}`, ...seg });
|
|
188
336
|
return;
|
|
189
337
|
}
|
|
190
|
-
|
|
191
|
-
|
|
338
|
+
const ctx = {
|
|
339
|
+
cwd: prepared.workdir,
|
|
340
|
+
home: os.homedir(),
|
|
341
|
+
bodyMaxChars: claim.events?.bodyMaxChars ?? EVENTS_DEFAULTS.bodyMaxChars,
|
|
342
|
+
toolArgMaxChars: claim.events?.toolArgMaxChars ?? EVENTS_DEFAULTS.toolArgMaxChars,
|
|
343
|
+
};
|
|
344
|
+
const note = (text) => {
|
|
345
|
+
console.log(`[runner] ${tag}: ${text}`);
|
|
346
|
+
feed?.push(systemEvent(text, ctx));
|
|
347
|
+
};
|
|
348
|
+
note(prepared.note);
|
|
349
|
+
[...claim.warnings, ...prepared.warnings].forEach(note);
|
|
192
350
|
// mcp-config temporal con el token per-run (0600; se borra al terminar).
|
|
193
351
|
const mcpFile = path.join(os.tmpdir(), `duckhunt-runner-${run.id}-${crypto.randomBytes(4).toString('hex')}.json`);
|
|
194
|
-
fs.writeFileSync(mcpFile, JSON.stringify({
|
|
195
|
-
mcpServers: {
|
|
196
|
-
[claim.mcp.serverName]: { type: 'http', url: claim.mcp.url, headers: { Authorization: `Bearer ${claim.mcp.token}` } },
|
|
197
|
-
},
|
|
198
|
-
}), { mode: 0o600 });
|
|
199
|
-
const env = this.envFor(run);
|
|
200
352
|
let report;
|
|
201
353
|
try {
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
attempt = await this.spawnClaude(claim, this.claudeArgs(claim, claim.fallbackPrompt, mcpFile, prepared.repoCfg, null), prepared.workdir, env);
|
|
212
|
-
resumed = false;
|
|
213
|
-
}
|
|
214
|
-
report = this.reportFor(attempt, resumed);
|
|
354
|
+
fs.writeFileSync(mcpFile, JSON.stringify({
|
|
355
|
+
mcpServers: {
|
|
356
|
+
[claim.mcp.serverName]: { type: 'http', url: claim.mcp.url, headers: { Authorization: `Bearer ${claim.mcp.token}` } },
|
|
357
|
+
},
|
|
358
|
+
}), { mode: 0o600 });
|
|
359
|
+
report = await this.runAttempts(claim, prepared, env, mcpFile, feed, ctx, note);
|
|
360
|
+
}
|
|
361
|
+
catch (err) {
|
|
362
|
+
report = { status: 'failed', error: err.message };
|
|
215
363
|
}
|
|
216
364
|
finally {
|
|
217
365
|
fs.rmSync(mcpFile, { force: true });
|
|
218
366
|
}
|
|
219
|
-
await
|
|
220
|
-
|
|
367
|
+
await feed?.close();
|
|
368
|
+
await this.postStatus(run.id, { ...report, ...seg });
|
|
369
|
+
if (prepared.worktree && prepared.conversation) {
|
|
370
|
+
touchWorktree(prepared.worktree);
|
|
371
|
+
}
|
|
372
|
+
else if (prepared.worktree && prepared.repoCfg) {
|
|
221
373
|
if (report.status === 'done')
|
|
222
|
-
await
|
|
374
|
+
await removeRunWorktree(prepared.repoCfg.path, prepared.worktree, env);
|
|
223
375
|
else
|
|
224
376
|
console.log(`[runner] worktree conservado para autopsia: ${prepared.worktree}`);
|
|
225
377
|
}
|
|
226
|
-
console.log(`[runner]
|
|
378
|
+
console.log(`[runner] ${tag} terminado (${report.status}${report.error ? `: ${report.error}` : ''})`);
|
|
227
379
|
}
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
380
|
+
// uno o dos intentos: reanudación fallida antes de que el asistente hablara (sesión inexistente
|
|
381
|
+
// en esta máquina, borrada, de otro daemon) → un solo reintento desde cero con el prompt de respaldo.
|
|
382
|
+
async runAttempts(claim, prepared, env, mcpFile, feed, ctx, note) {
|
|
383
|
+
const { run } = claim;
|
|
384
|
+
const args = (prompt, resumeSessionId) => buildClaudeArgs({
|
|
385
|
+
claim,
|
|
386
|
+
prompt,
|
|
387
|
+
mcpConfigFile: mcpFile,
|
|
388
|
+
supported: this.claude.supported,
|
|
389
|
+
resumeSessionId,
|
|
390
|
+
model: this.cfg.defaults.model,
|
|
391
|
+
configBudgetUsd: this.cfg.defaults.maxBudgetUsd,
|
|
392
|
+
skipPermissions: prepared.repoCfg?.dangerouslySkipPermissions === true,
|
|
393
|
+
payingWithApiKey: !!process.env.ANTHROPIC_API_KEY,
|
|
394
|
+
});
|
|
395
|
+
// reanudar o no lo decide el server: manda sessionId solo cuando hay sesión que retomar.
|
|
396
|
+
const resume = run.sessionId;
|
|
397
|
+
let attempt = await this.spawnClaude(claim, args(claim.prompt, resume), prepared, env, feed, ctx);
|
|
398
|
+
let resumed = resume ? true : undefined;
|
|
399
|
+
if (resume && attempt.killedBy === null && attempt.exitCode !== 0 && !attempt.stream.sawAssistant && claim.fallbackPrompt) {
|
|
400
|
+
console.log(`[runner] run ${run.id}: la sesión ${resume} no se pudo reanudar`);
|
|
401
|
+
note('la sesión anterior no se pudo reanudar en este runner: reintento desde cero');
|
|
402
|
+
attempt = await this.spawnClaude(claim, args(claim.fallbackPrompt, null), prepared, env, feed, ctx);
|
|
403
|
+
resumed = false;
|
|
246
404
|
}
|
|
247
|
-
|
|
248
|
-
const reason = s.result?.isError
|
|
249
|
-
? `claude terminó con error (${s.result.subtype ?? 'error'})${budgetHit ? ' — presupuesto nominal agotado: sube defaults.maxBudgetUsd en ~/.duckhunt-runner.json (0 = sin límite)' : ''}${s.result.result ? `: ${s.result.result.slice(0, 500)}` : ''}`
|
|
250
|
-
: `claude terminó con exit code ${attempt.exitCode}`;
|
|
251
|
-
return { ...base, status: 'failed', error: reason };
|
|
405
|
+
return reportFor(attempt, resumed);
|
|
252
406
|
}
|
|
253
|
-
// spawnea claude, consume stdout (stream-json
|
|
254
|
-
// y progreso, y aplica el timeout wall-clock.
|
|
255
|
-
|
|
407
|
+
// spawnea claude en su propio grupo de procesos, consume stdout (stream-json → contadores + feed)
|
|
408
|
+
// y stderr (tail), bombea heartbeat (soft-cancel) y progreso, y aplica el timeout wall-clock.
|
|
409
|
+
// resuelve siempre (nunca rechaza).
|
|
410
|
+
spawnClaude(claim, args, prepared, env, feed, ctx) {
|
|
256
411
|
const runId = claim.run.id;
|
|
412
|
+
const seg = claim.run.segment !== null ? { segment: claim.run.segment } : {};
|
|
257
413
|
return new Promise((resolve) => {
|
|
258
414
|
const stream = newStreamState();
|
|
259
415
|
const stderrTail = [];
|
|
260
416
|
let killedBy = null;
|
|
261
417
|
let killTimer = null;
|
|
418
|
+
let drainTimer = null;
|
|
262
419
|
let logFile = null;
|
|
263
420
|
if (this.opts.verboseLog) {
|
|
264
421
|
try {
|
|
@@ -270,9 +427,11 @@ export class RunnerDaemon {
|
|
|
270
427
|
}
|
|
271
428
|
let child;
|
|
272
429
|
try {
|
|
273
|
-
child = spawn('claude', args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
430
|
+
child = spawn('claude', args, { cwd: prepared.workdir, env, stdio: ['ignore', 'pipe', 'pipe'], detached: true });
|
|
274
431
|
}
|
|
275
432
|
catch (err) {
|
|
433
|
+
if (logFile !== null)
|
|
434
|
+
fs.closeSync(logFile);
|
|
276
435
|
resolve({ exitCode: null, killedBy: null, stream, stderrTail: `no se pudo lanzar claude: ${err.message}` });
|
|
277
436
|
return;
|
|
278
437
|
}
|
|
@@ -280,14 +439,17 @@ export class RunnerDaemon {
|
|
|
280
439
|
if (killedBy)
|
|
281
440
|
return;
|
|
282
441
|
killedBy = reason;
|
|
283
|
-
child
|
|
284
|
-
killTimer = setTimeout(() =>
|
|
285
|
-
if (child.exitCode === null && child.signalCode === null)
|
|
286
|
-
child.kill('SIGKILL');
|
|
287
|
-
}, KILL_GRACE_MS);
|
|
442
|
+
signalGroup(child, 'SIGTERM');
|
|
443
|
+
killTimer = setTimeout(() => signalGroup(child, 'SIGKILL'), KILL_GRACE_MS);
|
|
288
444
|
};
|
|
445
|
+
this.active = child;
|
|
446
|
+
this.killActive = kill;
|
|
447
|
+
if (this.stopping)
|
|
448
|
+
kill('shutdown');
|
|
289
449
|
readline.createInterface({ input: child.stdout }).on('line', (line) => {
|
|
290
|
-
consumeStreamLine(stream, line);
|
|
450
|
+
const ev = consumeStreamLine(stream, line);
|
|
451
|
+
if (ev && feed)
|
|
452
|
+
feedEventsFromStream(ev, ctx).forEach((e) => feed.push(e));
|
|
291
453
|
if (logFile !== null)
|
|
292
454
|
fs.writeSync(logFile, `${line}\n`);
|
|
293
455
|
});
|
|
@@ -298,59 +460,97 @@ export class RunnerDaemon {
|
|
|
298
460
|
if (logFile !== null)
|
|
299
461
|
fs.writeSync(logFile, `${JSON.stringify({ type: 'stderr', line })}\n`);
|
|
300
462
|
});
|
|
301
|
-
// heartbeat: transporta el soft-cancel del server.
|
|
463
|
+
// heartbeat: transporta el soft-cancel del server (y refresca la presencia del runner). el
|
|
464
|
+
// proceso muere si el run ya no es suyo: cancel, un estado que no es running, o el run no existe.
|
|
302
465
|
const heartbeat = setInterval(() => {
|
|
303
|
-
void this.api(`/runs/${runId}/heartbeat
|
|
466
|
+
void this.api(`/runs/${runId}/heartbeat`, seg)
|
|
304
467
|
.then(async (res) => {
|
|
468
|
+
if (res.status === HTTP_NOT_FOUND) {
|
|
469
|
+
console.log(`[runner] run ${runId} ya no existe en el server; deteniendo claude`);
|
|
470
|
+
kill('cancel');
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
305
473
|
if (!res.ok)
|
|
306
474
|
return;
|
|
307
475
|
const body = (await res.json().catch(() => null));
|
|
308
|
-
if (body?.cancel) {
|
|
309
|
-
console.log(`[runner] run ${runId}
|
|
476
|
+
if (body?.cancel || (typeof body?.status === 'string' && body.status !== RUN_STATUS_RUNNING)) {
|
|
477
|
+
console.log(`[runner] run ${runId} ya no es de este proceso (${body?.status ?? 'cancelado'}); deteniendo claude`);
|
|
310
478
|
kill('cancel');
|
|
311
479
|
}
|
|
312
480
|
})
|
|
313
481
|
.catch((err) => console.error(`[runner] heartbeat falló: ${err.message}`));
|
|
314
|
-
}, Math.max(
|
|
315
|
-
// progreso: tool calls
|
|
482
|
+
}, Math.max(MIN_HEARTBEAT_MS, claim.heartbeatMs));
|
|
483
|
+
// progreso: tool calls del segmento (throttled) + la nota de workdir en el primer envío.
|
|
484
|
+
const postProgress = (toolCalls, workdir) => {
|
|
485
|
+
void this.api(`/runs/${runId}/progress`, { toolCalls, ...(workdir ? { workdir } : {}), ...seg }).catch((err) => console.error(`[runner] progress falló: ${err.message}`));
|
|
486
|
+
};
|
|
487
|
+
postProgress(0, clip(prepared.note, WORKDIR_MAX_CHARS));
|
|
316
488
|
let reportedToolCalls = 0;
|
|
317
|
-
let lastProgressAt =
|
|
489
|
+
let lastProgressAt = Date.now();
|
|
318
490
|
const progress = setInterval(() => {
|
|
319
491
|
const now = Date.now();
|
|
320
492
|
if (stream.toolCalls === reportedToolCalls || now - lastProgressAt < PROGRESS_MIN_INTERVAL_MS)
|
|
321
493
|
return;
|
|
322
494
|
reportedToolCalls = stream.toolCalls;
|
|
323
495
|
lastProgressAt = now;
|
|
324
|
-
|
|
325
|
-
},
|
|
496
|
+
postProgress(reportedToolCalls);
|
|
497
|
+
}, PROGRESS_TICK_MS);
|
|
326
498
|
const timeout = setTimeout(() => {
|
|
327
499
|
console.log(`[runner] run ${runId} superó ${Math.round(claim.timeoutMs / 1000)}s; deteniendo claude`);
|
|
328
500
|
kill('timeout');
|
|
329
|
-
}, Math.max(
|
|
501
|
+
}, Math.max(MIN_RUN_TIMEOUT_MS, claim.timeoutMs));
|
|
330
502
|
child.on('error', (err) => {
|
|
331
503
|
stderrTail.push(`[runner] no se pudo lanzar claude: ${err.message}`);
|
|
332
504
|
});
|
|
505
|
+
child.on('exit', () => {
|
|
506
|
+
// claude salió: si algo en background retiene sus pipes, se dejan de esperar.
|
|
507
|
+
drainTimer = setTimeout(() => {
|
|
508
|
+
child.stdout?.destroy();
|
|
509
|
+
child.stderr?.destroy();
|
|
510
|
+
}, EXIT_DRAIN_MS);
|
|
511
|
+
});
|
|
333
512
|
child.on('close', (code) => {
|
|
334
513
|
clearInterval(heartbeat);
|
|
335
514
|
clearInterval(progress);
|
|
336
515
|
clearTimeout(timeout);
|
|
337
516
|
if (killTimer)
|
|
338
517
|
clearTimeout(killTimer);
|
|
518
|
+
if (drainTimer)
|
|
519
|
+
clearTimeout(drainTimer);
|
|
339
520
|
if (logFile !== null)
|
|
340
521
|
fs.closeSync(logFile);
|
|
522
|
+
this.active = null;
|
|
523
|
+
this.killActive = null;
|
|
341
524
|
resolve({ exitCode: code, killedBy, stream, stderrTail: stderrTail.join('\n').slice(-STDERR_TAIL_MAX_CHARS) });
|
|
342
525
|
});
|
|
343
526
|
});
|
|
344
527
|
}
|
|
528
|
+
async postEvents(runId, events, seg) {
|
|
529
|
+
const res = await this.api(`/runs/${runId}/events`, { events, ...seg });
|
|
530
|
+
return res.status;
|
|
531
|
+
}
|
|
532
|
+
// cierre con reintento acotado: es lo único del run que el server no puede reconstruir.
|
|
345
533
|
async postStatus(runId, report) {
|
|
346
|
-
const
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
534
|
+
const body = clampReport(report);
|
|
535
|
+
// i/o secuencial con backoff exponencial.
|
|
536
|
+
for (let attempt = 1; attempt <= STATUS_POST_ATTEMPTS; attempt++) {
|
|
537
|
+
const res = await this.api(`/runs/${runId}/status`, body).catch((err) => {
|
|
538
|
+
console.error(`[runner] status post falló (intento ${attempt}/${STATUS_POST_ATTEMPTS}): ${err.message}`);
|
|
539
|
+
return null;
|
|
540
|
+
});
|
|
541
|
+
// 409 = el server ya cerró el run (cancel del usuario, sweeper): benigno.
|
|
542
|
+
if (res && (res.ok || res.status === HTTP_CONFLICT))
|
|
543
|
+
return;
|
|
544
|
+
if (res && !isTransient(res.status)) {
|
|
545
|
+
console.error(`[runner] status post rechazado: http ${res.status} ${await res.text().catch(() => '')}`);
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
if (res)
|
|
549
|
+
console.error(`[runner] status post: http ${res.status} (intento ${attempt}/${STATUS_POST_ATTEMPTS})`);
|
|
550
|
+
if (attempt < STATUS_POST_ATTEMPTS)
|
|
551
|
+
await sleep(STATUS_POST_BACKOFF_MS * 2 ** (attempt - 1));
|
|
353
552
|
}
|
|
553
|
+
console.error(`[runner] status del run ${runId} sin entregar: el server lo cerrará por inactividad`);
|
|
354
554
|
}
|
|
355
555
|
}
|
|
356
556
|
//# sourceMappingURL=daemon.js.map
|