@cloop/runner 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.
Files changed (31) hide show
  1. package/dist/{box-7SVME4E5.js → box-VE2WJH3A.js} +14 -14
  2. package/dist/{chunk-34XAQRBL.js → chunk-23ZHP4EN.js} +181 -35
  3. package/dist/{chunk-NK6MHHYP.js → chunk-43GTYT5U.js} +3 -5
  4. package/dist/{chunk-J6AEO3GT.js → chunk-5FZAHWPX.js} +1 -1
  5. package/dist/{chunk-7CPNLUDI.js → chunk-6SRPPUR2.js} +8 -10
  6. package/dist/{chunk-3B5JV6ZP.js → chunk-CKFWWGDD.js} +2 -2
  7. package/dist/{chunk-AEWIRLRS.js → chunk-E5CKL2Q3.js} +1 -1
  8. package/dist/{chunk-3DIGCVL4.js → chunk-IKCGVBHA.js} +11 -0
  9. package/dist/{chunk-2PVKRGOX.js → chunk-LAQSZU6I.js} +3 -3
  10. package/dist/{chunk-3ITSIARB.js → chunk-LOSZGPY4.js} +3 -3
  11. package/dist/{chunk-EN3XHHWJ.js → chunk-NEGKYXHS.js} +783 -44
  12. package/dist/{chunk-JX6VG5FE.js → chunk-NUU4GXGV.js} +1 -1
  13. package/dist/{chunk-AG6SI6I2.js → chunk-NYGELUTR.js} +1 -1
  14. package/dist/{chunk-NOABXLW3.js → chunk-UIFPQQCQ.js} +1 -1
  15. package/dist/{connect-LLURHARY.js → connect-YCCLIBTL.js} +9 -9
  16. package/dist/disconnect-TVAN3LLV.js +28 -0
  17. package/dist/{hook-activity-LBYV4WJW.js → hook-activity-I7TV7YG7.js} +4 -4
  18. package/dist/{hook-session-start-YSEV5DCB.js → hook-session-start-MFX6HR3W.js} +3 -3
  19. package/dist/index.js +17 -17
  20. package/dist/{install-HTDTCELB.js → install-EMEZBBK7.js} +1 -1
  21. package/dist/{login-XS2IFIUX.js → login-OF62R2RQ.js} +4 -4
  22. package/dist/{mcp-server-R47CKE6A.js → mcp-server-V2M6VOQP.js} +6 -6
  23. package/dist/runner-64HZZDG6.js +13 -0
  24. package/dist/{runs-4ZJOIB5S.js → runs-4DXIUYDF.js} +3 -4
  25. package/dist/{statusline-RI62KCQX.js → statusline-354ALD5T.js} +3 -3
  26. package/dist/{takeover-F5SEY7WI.js → takeover-Y7ZKSHGQ.js} +7 -8
  27. package/dist/{use-2OOFS53J.js → use-AECELCU6.js} +14 -10
  28. package/package.json +1 -1
  29. package/dist/chunk-QLCIEJ4C.js +0 -696
  30. package/dist/disconnect-WAQTAXN3.js +0 -159
  31. package/dist/runner-R4Z62XVC.js +0 -13
@@ -1,696 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- BoxToolError,
4
- RESULT_INSTRUCTION,
5
- RUN_TEXT_MAX,
6
- STOPPED_SUMMARY,
7
- appendRunLog,
8
- droppedLine,
9
- endNote,
10
- isProgressSentence,
11
- logLineFor,
12
- nextProgress,
13
- orderThreads,
14
- prUrlIn,
15
- pruneRunLogs,
16
- readRunResult,
17
- resultPrUrl,
18
- runLogDir
19
- } from "./chunk-EN3XHHWJ.js";
20
- import {
21
- CONFIG_DIR
22
- } from "./chunk-3DIGCVL4.js";
23
-
24
- // src/drivers/local.ts
25
- import { execFile, execFileSync, spawn } from "child_process";
26
- import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
27
- import { homedir, hostname } from "os";
28
- import { basename, dirname, join } from "path";
29
- import { createInterface } from "readline";
30
-
31
- // src/drivers/harness-check.ts
32
- var HARNESS_STALE_MS = 5 * 6e4;
33
- var FIRST_CHECK_WAIT_MS = 3e3;
34
- var HarnessCheck = class {
35
- constructor(probe, opts) {
36
- this.probe = probe;
37
- this.opts = opts;
38
- }
39
- probe;
40
- opts;
41
- last = null;
42
- running = null;
43
- /** Starts a probe unless one is running. It never rejects. */
44
- refresh() {
45
- this.running ??= this.probe().then(
46
- (harnesses) => {
47
- this.last = { harnesses, at: this.opts.now() };
48
- },
49
- (err) => this.opts.log(`harness probe failed: ${err?.message}`)
50
- ).finally(() => {
51
- this.running = null;
52
- });
53
- return this.running;
54
- }
55
- async read() {
56
- if (!this.last) {
57
- let timer;
58
- await Promise.race([
59
- this.refresh(),
60
- new Promise((resolve) => {
61
- timer = setTimeout(resolve, FIRST_CHECK_WAIT_MS);
62
- })
63
- ]);
64
- clearTimeout(timer);
65
- } else if (this.opts.now() - this.last.at > HARNESS_STALE_MS) {
66
- void this.refresh();
67
- }
68
- const last = this.last;
69
- return last ? { harnesses: last.harnesses, checkedAt: new Date(last.at).toISOString(), probing: false } : { harnesses: [], checkedAt: null, probing: true };
70
- }
71
- };
72
-
73
- // src/drivers/local.ts
74
- var STOPPED = { kind: "failed", summary: STOPPED_SUMMARY };
75
- function takeoverSummary(machine) {
76
- return `You took this over on ${machine}.`;
77
- }
78
- var CONTINUE_PROMPT = "Continue the work from where you stopped. If it is already done, say so in one sentence.";
79
- var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master", "HEAD"]);
80
- var COMMANDS_KEPT = 50;
81
- var SUMMARY_MAX = 200;
82
- var HARNESS_NAMES = { "claude-code": "Claude Code", codex: "Codex" };
83
- var HARNESS_LIMIT = /usage limit|reached your [\w .-]{0,40}limit|hit your [\w .-]{0,40}limit|out of (usage )?credits/i;
84
- function failedEnd(harness, run2) {
85
- const said = run2.result?.text?.trim() || run2.lastText;
86
- const limited = HARNESS_LIMIT.test(run2.result?.text ?? "");
87
- const words = said?.replace(/\s+/g, " ").trim();
88
- const error = limited ? { error: "harness_limit" } : {};
89
- const opening = run2.switched ? `${run2.switched} ` : "";
90
- if (!words)
91
- return {
92
- summary: `${opening}${run2.result ? "The run ended with an error." : `The run exited with ${run2.exit}.`}`,
93
- ...error
94
- };
95
- const lead = `${opening}${HARNESS_NAMES[harness] ?? harness} said: "`;
96
- const room = SUMMARY_MAX - lead.length - 1;
97
- const quoted = words.length > room ? `${words.slice(0, room - 1)}\u2026` : words;
98
- return { summary: `${lead}${quoted}"`, ...error };
99
- }
100
- function localRunsFilePath() {
101
- return process.env.CLOOP_LOCAL_RUNS_FILE ?? join(homedir(), CONFIG_DIR, "local-runs.json");
102
- }
103
- function pickRepo(repos, repository) {
104
- if (!repository) {
105
- if (repos.length === 1 && repos[0]) return repos[0];
106
- throw new BoxToolError("no_project");
107
- }
108
- const want = repository.toLowerCase().split("/").at(-1) ?? "";
109
- const found = repos.find(
110
- (r) => r.label.toLowerCase() === want || basename(r.path).toLowerCase() === want
111
- );
112
- if (!found) throw new BoxToolError("no_project");
113
- return found;
114
- }
115
- function run(cmd, args, cwd) {
116
- return new Promise(
117
- (resolve, reject) => execFile(
118
- cmd,
119
- args,
120
- { cwd, timeout: 1e4, encoding: "utf-8" },
121
- (err, out) => err ? reject(err) : resolve(String(out).trim())
122
- )
123
- );
124
- }
125
- var gitProbe = {
126
- head: (repo) => run("git", ["rev-parse", "HEAD"], repo).catch(() => null),
127
- pushed: (repo) => run("git", ["branch", "-r", "--contains", "HEAD"], repo).then(
128
- (out) => out.length > 0,
129
- () => false
130
- ),
131
- async branchPr(repo) {
132
- try {
133
- const branch = await run("git", ["rev-parse", "--abbrev-ref", "HEAD"], repo);
134
- if (SHARED_BRANCHES.has(branch)) return null;
135
- return prUrlIn(await run("gh", ["pr", "view", "--json", "url", "-q", ".url"], repo));
136
- } catch {
137
- return null;
138
- }
139
- }
140
- };
141
- function harnessAlive(pid, r, dialect) {
142
- try {
143
- process.kill(pid, 0);
144
- } catch (err) {
145
- if (err.code !== "EPERM") return false;
146
- }
147
- try {
148
- const command = execFileSync("ps", ["-ww", "-o", "command=", "-p", String(pid)], {
149
- encoding: "utf-8",
150
- timeout: 2e3
151
- });
152
- return dialect.owns(r, command);
153
- } catch {
154
- return false;
155
- }
156
- }
157
- var KEEP_MS = 7 * 24 * 36e5;
158
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
159
- var LocalDriver = class {
160
- constructor(deps) {
161
- this.deps = deps;
162
- this.name = deps.dialect.name;
163
- this.harnessCheck = new HarnessCheck(
164
- deps.harnesses ?? (async () => [await deps.dialect.probe()].filter((h) => h !== null)),
165
- { now: () => this.now(), log: (line) => this.log(line) }
166
- );
167
- this.capabilities = deps.dialect.capabilities;
168
- this.runs = new Map(this.load().map((r) => [r.work_id, r]));
169
- this.logDir = deps.logDir ?? runLogDir(this.file);
170
- try {
171
- const removed = pruneRunLogs(this.logDir, this.now());
172
- if (removed) this.log(`run logs removed=${removed} older than 14 days`);
173
- } catch (err) {
174
- this.log(`run log prune failed: ${err.code ?? "unknown"}`);
175
- }
176
- }
177
- deps;
178
- name;
179
- capabilities;
180
- runs;
181
- lives = /* @__PURE__ */ new Map();
182
- listeners = /* @__PURE__ */ new Map();
183
- recovering = /* @__PURE__ */ new Set();
184
- stopping = false;
185
- logDir;
186
- logFailed = false;
187
- harnessCheck;
188
- get repo() {
189
- return this.deps.repo ?? gitProbe;
190
- }
191
- get file() {
192
- return this.deps.file ?? localRunsFilePath();
193
- }
194
- log(line) {
195
- this.deps.log?.(line);
196
- }
197
- /** One line in the run's own log, for `cloop watch`. A full disk must not stop the run. */
198
- note(r, text) {
199
- try {
200
- appendRunLog(this.logDir, r.work_id, text, { now: this.now() });
201
- } catch (err) {
202
- if (this.logFailed) return;
203
- this.logFailed = true;
204
- this.log(`run log write failed: ${err.code ?? "unknown"}`);
205
- }
206
- }
207
- now() {
208
- return this.deps.now?.() ?? Date.now();
209
- }
210
- /** Probes the harnesses now, so the first status after the daemon starts answers at once. */
211
- warmHarnesses() {
212
- void this.harnessCheck.refresh();
213
- }
214
- async status() {
215
- const { harnesses, checkedAt, probing } = await this.harnessCheck.read();
216
- const all = [...this.runs.values()];
217
- const unsettled = all.filter((r) => !r.end);
218
- return {
219
- box: { label: this.deps.label ?? hostname(), driver: this.name },
220
- harnesses,
221
- harnesses_checked_at: checkedAt,
222
- ...probing ? { probing: true } : {},
223
- clients: null,
224
- projects: this.deps.repos.map((r) => r.label),
225
- threads: {
226
- unsettled: unsettled.length,
227
- running: unsettled.filter((r) => this.lives.has(r.work_id)).length,
228
- settled: all.length - unsettled.length,
229
- cloop: unsettled.length
230
- }
231
- };
232
- }
233
- async listThreads({
234
- scope,
235
- limit
236
- }) {
237
- const all = [...this.runs.values()];
238
- const unsettled = all.filter((r) => !r.end);
239
- const shown = (scope === "all" ? all : unsettled).map((r) => ({
240
- id: r.work_id,
241
- title: r.title,
242
- status: this.statusOf(r),
243
- branch: null,
244
- source: "cloop",
245
- cloop: true,
246
- settled: Boolean(r.end),
247
- updatedAt: r.end?.at ?? r.started_at
248
- }));
249
- return {
250
- scope,
251
- unsettled: unsettled.length,
252
- settled: all.length - unsettled.length,
253
- running: shown.filter((t) => t.status === "running").length,
254
- threads: orderThreads(shown, limit)
255
- };
256
- }
257
- async readThread(id) {
258
- const r = this.record(id);
259
- return {
260
- status: this.statusOf(r),
261
- settled: Boolean(r.end),
262
- pr_url: r.end?.pr_url ?? null,
263
- last_assistant_text: r.end?.summary ?? r.last_text ?? null,
264
- resume: this.deps.dialect.name === "claude-code" && r.session_id ? { cwd: r.repo, session_id: r.session_id } : null
265
- };
266
- }
267
- async launch(a) {
268
- const existing = this.runs.get(a.work_id);
269
- if (existing)
270
- return {
271
- thread_id: a.work_id,
272
- resumed: true,
273
- permission: existing.used_permission,
274
- takeover: true
275
- };
276
- const { dialect } = this.deps;
277
- if (a.harness && !dialect.aliases.includes(a.harness))
278
- throw new BoxToolError("harness_unavailable");
279
- const repo = pickRepo(this.deps.repos, a.repository);
280
- this.refuseBusy(repo.path);
281
- const harness = await dialect.probe();
282
- if (!harness) throw new BoxToolError("harness_unavailable");
283
- if (!harness.signedIn) throw new BoxToolError("harness_signed_out");
284
- const head = await this.repo.head(repo.path);
285
- const concurrent = this.runs.get(a.work_id);
286
- if (concurrent)
287
- return {
288
- thread_id: a.work_id,
289
- resumed: true,
290
- permission: concurrent.used_permission,
291
- takeover: true
292
- };
293
- this.refuseBusy(repo.path);
294
- const record = {
295
- work_id: a.work_id,
296
- session_id: dialect.name === "claude-code" ? a.work_id : null,
297
- repo: repo.path,
298
- title: a.title,
299
- ...a.model ? { model: a.model } : {},
300
- ...a.runtime_mode ? { runtime_mode: a.runtime_mode } : {},
301
- pid: null,
302
- started_at: new Date(this.now()).toISOString(),
303
- head_at_launch: head
304
- };
305
- this.runs.set(a.work_id, record);
306
- this.spawnRun(record, a.prompt, false);
307
- return {
308
- thread_id: a.work_id,
309
- resumed: false,
310
- permission: record.used_permission,
311
- takeover: true
312
- };
313
- }
314
- async send(a) {
315
- const r = this.record(a.thread_id);
316
- const seen = r.commands?.find(([id]) => id === a.command_id);
317
- if (seen) return { delivered: seen[1] };
318
- const live = this.lives.get(r.work_id);
319
- const ask = live?.asks[0];
320
- if (a.answer && (!ask || ask.request_id !== a.question_id)) {
321
- this.log(`question_changed work=${r.work_id}`);
322
- return {
323
- delivered: "question_changed",
324
- question: ask?.summary ?? null,
325
- question_id: ask?.request_id ?? null
326
- };
327
- }
328
- if (live && ask) {
329
- if (!a.answer) {
330
- return {
331
- delivered: "question_pending",
332
- question: ask.summary,
333
- questions: live.asks.length
334
- };
335
- }
336
- const line2 = this.deps.dialect.answerLine?.(ask, a.text);
337
- if (!line2) throw new BoxToolError("cannot_steer");
338
- live.asks = live.asks.slice(1);
339
- this.write(live, line2);
340
- this.note(r, `< You answered: ${a.text}`);
341
- this.remember(r, a.command_id, "answer");
342
- this.log(`answer work=${r.work_id}`);
343
- this.askNext(r, live);
344
- return { delivered: "answer", question_id: ask.request_id };
345
- }
346
- if (!live) {
347
- if (r.end && !a.resume) throw new BoxToolError("already_finished");
348
- if (r.end) {
349
- this.refuseBusy(r.repo);
350
- r.end = void 0;
351
- r.last_text = void 0;
352
- }
353
- this.spawnRun(r, a.text, true);
354
- this.remember(r, a.command_id, "start");
355
- return { delivered: "start" };
356
- }
357
- if (live.child.stdin?.writableEnded) {
358
- live.next = live.next ? `${live.next}
359
-
360
- ${a.text}` : a.text;
361
- this.remember(r, a.command_id, "queue");
362
- return { delivered: "queue" };
363
- }
364
- const line = this.deps.dialect.userLine?.(r, a.text, a.mode);
365
- if (!line) throw new BoxToolError("cannot_steer");
366
- live.outstanding++;
367
- this.write(live, line);
368
- this.note(r, `< You: ${a.text}`);
369
- const delivered = a.mode === "queue" ? "queue" : "steer";
370
- this.remember(r, a.command_id, delivered);
371
- this.log(`${delivered} work=${r.work_id}`);
372
- return { delivered };
373
- }
374
- async interrupt(id, _commandId, stop = STOPPED) {
375
- const r = this.record(id);
376
- const live = this.lives.get(r.work_id);
377
- if (!live) {
378
- if (r.end) return { ok: true, was_running: false };
379
- const orphan = r.pid !== null && this.alive(r.pid, r);
380
- if (orphan && r.pid !== null) {
381
- try {
382
- process.kill(r.pid, "SIGINT");
383
- } catch {
384
- }
385
- }
386
- await this.end(r, stop);
387
- return { ok: true, was_running: orphan };
388
- }
389
- live.interrupted = stop;
390
- live.child.kill("SIGINT");
391
- this.note(r, stop === STOPPED ? "= Stop requested." : `= ${stop.summary}`);
392
- const timer = setTimeout(() => {
393
- if (live.child.exitCode === null && live.child.signalCode === null)
394
- live.child.kill("SIGTERM");
395
- }, this.deps.interruptGraceMs ?? 1e4);
396
- timer.unref();
397
- this.log(`interrupt work=${r.work_id}${stop.error ? ` reason=${stop.error}` : ""}`);
398
- return { ok: true, was_running: true };
399
- }
400
- /**
401
- * `cloop takeover`: stop the run so the owner can open its session in
402
- * their own terminal. It ends as a stop, with the machine in its words, and
403
- * never resumes by itself: two processes on one session would fight.
404
- */
405
- takeOver(id, machine) {
406
- return this.interrupt(id, void 0, {
407
- kind: "failed",
408
- summary: takeoverSummary(machine),
409
- error: "taken_over"
410
- });
411
- }
412
- watch(id, onEvent) {
413
- const set = this.listeners.get(id) ?? /* @__PURE__ */ new Set();
414
- set.add(onEvent);
415
- this.listeners.set(id, set);
416
- const r = this.runs.get(id);
417
- const unwatch = () => set.delete(onEvent);
418
- if (!r) {
419
- onEvent({ kind: "failed", summary: "This run is not on the runner any more." });
420
- return unwatch;
421
- }
422
- if (r.end) {
423
- const { at: _at, ...end } = r.end;
424
- onEvent(end);
425
- return unwatch;
426
- }
427
- const live = this.lives.get(id);
428
- const ask = live?.asks[0];
429
- if (ask) onEvent({ kind: "question", question_id: ask.request_id, summary: ask.summary });
430
- if (!live) void this.recover(r);
431
- return unwatch;
432
- }
433
- /** On a daemon stop: end every process, and leave its run open so the next start resumes it. */
434
- stop() {
435
- this.stopping = true;
436
- for (const live of this.lives.values()) live.child.kill("SIGTERM");
437
- }
438
- alive(pid, r) {
439
- return this.deps.alive ? this.deps.alive(pid, r) : harnessAlive(pid, r, this.deps.dialect);
440
- }
441
- /** One checkout, one run: two harnesses editing the same files at once would undo each other. */
442
- refuseBusy(repo) {
443
- if ([...this.runs.values()].some((r) => r.repo === repo && !r.end))
444
- throw new BoxToolError("repo_busy");
445
- }
446
- /** One question at a time, oldest first, so a yes answers the prompt the owner read. */
447
- askNext(r, live) {
448
- const next = live.asks[0];
449
- if (!next) return;
450
- this.log(`question work=${r.work_id} tool=${next.tool}`);
451
- this.emit(r.work_id, { kind: "question", question_id: next.request_id, summary: next.summary });
452
- }
453
- /** A run left open by a daemon that died: wait for its old process to go, then resume it once. */
454
- async recover(r) {
455
- if (this.recovering.has(r.work_id)) return;
456
- this.recovering.add(r.work_id);
457
- try {
458
- while (r.pid !== null && this.alive(r.pid, r) && !r.end && !this.stopping) {
459
- await sleep(this.deps.orphanPollMs ?? 2e3);
460
- }
461
- if (r.end || this.stopping || this.lives.has(r.work_id)) return;
462
- this.log(`resume work=${r.work_id} after a restart`);
463
- this.spawnRun(r, CONTINUE_PROMPT, true);
464
- } finally {
465
- this.recovering.delete(r.work_id);
466
- }
467
- }
468
- spawnRun(r, prompt, resume) {
469
- const { dialect } = this.deps;
470
- r.used_permission = dialect.permission?.(r);
471
- const child = spawn(dialect.bin, dialect.args(r, resume), {
472
- cwd: r.repo,
473
- stdio: ["pipe", "pipe", "pipe"],
474
- env: process.env
475
- });
476
- const live = {
477
- child,
478
- outstanding: 1,
479
- asks: [],
480
- lastProgressAt: 0,
481
- interrupted: null,
482
- stderr: ""
483
- };
484
- this.lives.set(r.work_id, live);
485
- r.pid = child.pid ?? null;
486
- this.save();
487
- this.log(`spawn work=${r.work_id} pid=${r.pid ?? "none"} ${resume ? "resume" : "new"}`);
488
- this.note(r, resume ? "= Resumed." : `= Started "${r.title}" in ${r.repo}`);
489
- child.stdin?.on("error", () => {
490
- });
491
- child.stdin?.write(dialect.opening(r, `${prompt}
492
-
493
- ${RESULT_INSTRUCTION}`));
494
- if (!dialect.keepsStdin) child.stdin?.end();
495
- child.stderr?.on("data", (chunk) => {
496
- live.stderr = (live.stderr + chunk.toString("utf-8")).slice(-2e3);
497
- });
498
- const lines = createInterface({ input: child.stdout });
499
- lines.on("line", (line) => {
500
- for (const item of dialect.parse(line, r)) this.onItem(r, live, item);
501
- });
502
- child.on("error", (err) => {
503
- this.log(`spawn failed work=${r.work_id}: ${err.message.slice(0, 200)}`);
504
- });
505
- child.on("close", (code, signal) => void this.onExit(r, live, code, signal));
506
- }
507
- onItem(r, live, item) {
508
- const logged = logLineFor(item);
509
- if (logged) this.note(r, logged);
510
- switch (item.type) {
511
- case "session":
512
- if (r.session_id !== item.id) {
513
- r.session_id = item.id;
514
- this.save();
515
- }
516
- return;
517
- case "text":
518
- r.last_text = item.text.slice(0, 1e5);
519
- this.progress(r, live, item.text, false);
520
- return;
521
- case "tool": {
522
- const line = item.summary ?? (item.target ? `${item.name} ${item.target}` : item.name);
523
- if (!isProgressSentence(line)) return;
524
- const changed = item.name !== live.lastTool;
525
- live.lastTool = item.name;
526
- this.progress(r, live, line, changed);
527
- return;
528
- }
529
- case "ask":
530
- live.asks.push(item);
531
- if (live.asks.length === 1) this.askNext(r, live);
532
- return;
533
- case "cancel": {
534
- const wasAsked = live.asks[0]?.request_id === item.request_id;
535
- live.asks = live.asks.filter((x) => x.request_id !== item.request_id);
536
- if (wasAsked) this.askNext(r, live);
537
- return;
538
- }
539
- case "result":
540
- live.outstanding--;
541
- live.result = { ok: item.ok, ...item.text ? { text: item.text } : {} };
542
- if (item.text) r.last_text = item.text.slice(0, 1e5);
543
- if (live.outstanding <= 0 && live.asks.length === 0) live.child.stdin?.end();
544
- return;
545
- }
546
- }
547
- progress(r, live, line, force) {
548
- const summary = nextProgress(live, line, this.now(), this.deps.progressMs, force);
549
- if (summary) this.emit(r.work_id, { kind: "progress", summary });
550
- }
551
- async onExit(r, live, code, signal) {
552
- if (this.lives.get(r.work_id) === live) this.lives.delete(r.work_id);
553
- if (this.stopping || r.end) return;
554
- const exit = signal ? `signal ${signal}` : `code ${code}`;
555
- this.log(
556
- `exit work=${r.work_id} ${exit} result=${live.result ? live.result.ok ? "ok" : "error" : "none"}`
557
- );
558
- if (live.interrupted) {
559
- await this.end(r, live.interrupted);
560
- return;
561
- }
562
- if (live.next) {
563
- this.spawnRun(r, live.next, true);
564
- return;
565
- }
566
- if (code === 0 && live.result?.ok) {
567
- const text = live.result.text?.trim() || r.last_text;
568
- const { result, dropped } = readRunResult(text);
569
- const lost = droppedLine(dropped, r.work_id);
570
- if (lost) this.log(lost);
571
- const { pr, note } = await this.outcome(r, text);
572
- const summary = [r.switched, note, text].filter(Boolean).join(" ").replace(/\s+/g, " ");
573
- await this.end(r, {
574
- kind: "settled",
575
- ...result ? { result } : {},
576
- ...summary ? { summary: summary.slice(0, RUN_TEXT_MAX) } : {},
577
- ...pr ? { pr_url: pr } : {}
578
- });
579
- return;
580
- }
581
- if (live.stderr)
582
- this.log(`stderr work=${r.work_id}: ${live.stderr.trim().split("\n").at(-1)?.slice(0, 200)}`);
583
- const end = failedEnd(this.name, {
584
- result: live.result,
585
- lastText: r.last_text,
586
- exit,
587
- ...r.switched ? { switched: r.switched } : {}
588
- });
589
- if (end.error) this.log(`limit work=${r.work_id} error=${end.error}`);
590
- if (end.error === "harness_limit" && this.fallBack(r, live.result?.text)) return;
591
- await this.end(r, { kind: "failed", ...end });
592
- }
593
- /**
594
- * Once per run: a run stopped by its model's usage limit resumes its own
595
- * session on the first fallback model, with the continue prompt, so its
596
- * steers, answers and edits carry over. It does not when the Task named its
597
- * model, when the limit is the fallback model's own, or after one switch.
598
- * `--fallback-model` may already cover this; it is not documented whether a
599
- * plan's limit counts. The switch opens the end summary, because a progress
600
- * line is dropped while the socket is down.
601
- */
602
- fallBack(r, said) {
603
- const model = this.deps.dialect.fallback?.split(",")[0]?.trim();
604
- if (!model || !r.session_id || r.switched || r.model) return false;
605
- const named = new RegExp(`\\b${model.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i");
606
- if (named.test(said ?? "")) return false;
607
- const from = /reached your ([\w .-]{1,40}?) limit/i.exec(said ?? "")?.[1] ?? "The default model";
608
- const to = `${model.charAt(0).toUpperCase()}${model.slice(1)}`;
609
- r.switched = `${from} was at its usage limit, so this ran on ${to}.`;
610
- r.model = model;
611
- this.save();
612
- this.log(`fallback work=${r.work_id} model=${model}`);
613
- this.emit(r.work_id, {
614
- kind: "progress",
615
- summary: `${from} is at its usage limit, so I switched to ${to}`
616
- });
617
- this.spawnRun(r, CONTINUE_PROMPT, true);
618
- return true;
619
- }
620
- /**
621
- * The PR a run produced: one its last text names, else the PR of the
622
- * branch, but only when the run moved HEAD. A run that left HEAD where it
623
- * started produced nothing, and the branch's PR belongs to someone else's
624
- * work. A run that committed without pushing says so.
625
- */
626
- async outcome(r, text) {
627
- const named = resultPrUrl(text);
628
- if (named) return { pr: named };
629
- if (!r.head_at_launch) return { pr: null };
630
- const head = await this.repo.head(r.repo);
631
- if (!head || head === r.head_at_launch) return { pr: null };
632
- const pr = await this.repo.branchPr(r.repo);
633
- if (pr) return { pr };
634
- return await this.repo.pushed(r.repo) ? { pr: null } : { pr: null, note: `Committed ${head.slice(0, 7)}, not pushed.` };
635
- }
636
- async end(r, end) {
637
- if (r.end) return;
638
- r.end = { ...end, at: new Date(this.now()).toISOString() };
639
- r.pid = null;
640
- this.save();
641
- this.note(r, endNote(end));
642
- this.emit(r.work_id, end);
643
- }
644
- emit(id, event) {
645
- for (const listener of [...this.listeners.get(id) ?? []]) listener(event);
646
- }
647
- write(live, line) {
648
- live.child.stdin?.write(line);
649
- }
650
- remember(r, commandId, delivered) {
651
- r.commands = [
652
- ...r.commands ?? [],
653
- [commandId, delivered]
654
- ].slice(-COMMANDS_KEPT);
655
- this.save();
656
- }
657
- record(id) {
658
- const r = this.runs.get(id);
659
- if (!r) throw new BoxToolError("bad_args");
660
- return r;
661
- }
662
- statusOf(r) {
663
- if (this.lives.has(r.work_id)) return "running";
664
- if (!r.end) return "pending";
665
- return r.end.kind === "settled" ? "completed" : "failed";
666
- }
667
- load() {
668
- const cutoff = this.now() - KEEP_MS;
669
- return readRunRecords(this.file).filter((r) => !(r.end && Date.parse(r.end.at) < cutoff));
670
- }
671
- save() {
672
- mkdirSync(dirname(this.file), { recursive: true, mode: 448 });
673
- const tmp = `${this.file}.tmp`;
674
- writeFileSync(tmp, `${JSON.stringify([...this.runs.values()], null, 2)}
675
- `, { mode: 384 });
676
- chmodSync(tmp, 384);
677
- renameSync(tmp, this.file);
678
- }
679
- };
680
- function readRunRecords(file = localRunsFilePath()) {
681
- try {
682
- const raw = JSON.parse(readFileSync(file, "utf-8"));
683
- return Array.isArray(raw) ? raw.filter(
684
- (r) => typeof r?.work_id === "string" && typeof r?.repo === "string"
685
- ) : [];
686
- } catch {
687
- return [];
688
- }
689
- }
690
-
691
- export {
692
- takeoverSummary,
693
- localRunsFilePath,
694
- LocalDriver,
695
- readRunRecords
696
- };