@cloop/runner 0.2.10 → 0.3.1

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