@cloop/runner 0.3.68 → 0.3.69

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 (30) hide show
  1. package/dist/{box-YFGM56QY.js → box-UOJ6ET2B.js} +156 -511
  2. package/dist/{chunk-7LPSTDZE.js → chunk-4JTIWZHB.js} +1 -1
  3. package/dist/{chunk-BVPS6DCH.js → chunk-57E5WOOP.js} +574 -1673
  4. package/dist/{chunk-TCNIRZLU.js → chunk-CLOYOD2X.js} +10 -6
  5. package/dist/{chunk-6LYMSWSB.js → chunk-DN6TQALA.js} +265 -1961
  6. package/dist/{chunk-HWNRORIZ.js → chunk-DTUNRKBC.js} +1 -1
  7. package/dist/chunk-EEG5JOZ7.js +939 -0
  8. package/dist/chunk-GAEZIKCK.js +626 -0
  9. package/dist/chunk-HIBAH65V.js +1178 -0
  10. package/dist/{chunk-7ZL3Z3IO.js → chunk-JI5FWLDU.js} +6 -6
  11. package/dist/chunk-JJWSPBM4.js +40 -0
  12. package/dist/{chunk-L7D3ANPW.js → chunk-KIYCULVE.js} +4 -2
  13. package/dist/{chunk-34VZ5LZI.js → chunk-SJAGZNFF.js} +3 -83
  14. package/dist/chunk-TPKYD3JF.js +43 -0
  15. package/dist/chunk-WCKW2Z2G.js +459 -0
  16. package/dist/chunk-ZHQSGJCE.js +85 -0
  17. package/dist/{connect-D2SXLADA.js → connect-HVOAYXWM.js} +11 -47
  18. package/dist/disconnect-DQ6WSDR7.js +163 -0
  19. package/dist/existing-runner-BSSRQFFP.js +15 -0
  20. package/dist/index.js +14 -14
  21. package/dist/{login-VNDFCJD4.js → login-4HWP4PF4.js} +3 -2
  22. package/dist/{mcp-server-XPHCDBFR.js → mcp-server-DTJVCFRG.js} +10 -10
  23. package/dist/{runner-A3HFZ727.js → runner-4XWS2RJL.js} +4 -3
  24. package/dist/{runs-DOFU45TW.js → runs-TWUGWGNU.js} +4 -2
  25. package/dist/{statusline-VA2DSWVT.js → statusline-C2FH3YQ4.js} +1 -1
  26. package/dist/{takeover-U2EHJ5GW.js → takeover-5QSP6YAG.js} +6 -4
  27. package/dist/{use-7D5GQFGB.js → use-U3E55XBK.js} +20 -13
  28. package/package.json +1 -1
  29. package/dist/disconnect-7SJKPYIN.js +0 -30
  30. package/dist/existing-runner-XT3HLIPM.js +0 -20
@@ -0,0 +1,1178 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ HarnessCheck,
4
+ STOPPED_SUMMARY,
5
+ appendRunLog,
6
+ attachedLine,
7
+ delivery,
8
+ endNote,
9
+ fetchImages,
10
+ logLineFor,
11
+ orderThreads,
12
+ pruneRunLogs,
13
+ repoName,
14
+ runLogDir,
15
+ saveImages
16
+ } from "./chunk-DN6TQALA.js";
17
+ import {
18
+ BoxToolError,
19
+ HARNESS_LIMIT,
20
+ LIMIT_HOLD_MS,
21
+ MACHINE_RESULT_INSTRUCTION,
22
+ RUN_TEXT_MAX,
23
+ apiErrorWords,
24
+ cloneLine,
25
+ commandFor,
26
+ droppedLine,
27
+ finalWords,
28
+ handoverPrompt,
29
+ hasResultBlock,
30
+ isProgressSentence,
31
+ limitedModel,
32
+ movedLine,
33
+ movingLine,
34
+ nextModel,
35
+ nextProgress,
36
+ prUrlIn,
37
+ readRunResult,
38
+ refusedModel,
39
+ refusedModelLine,
40
+ resultPrUrl,
41
+ resultText,
42
+ runnerPath,
43
+ windowsPowerShellEnv
44
+ } from "./chunk-GAEZIKCK.js";
45
+
46
+ // src/outside-sessions.ts
47
+ import { createReadStream } from "fs";
48
+ import { readFile, readdir, stat } from "fs/promises";
49
+ import { homedir } from "os";
50
+ import { dirname, join } from "path";
51
+ import { createInterface } from "readline";
52
+ var seen = /* @__PURE__ */ new Map();
53
+ var UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
54
+ async function listOutsideSessions(root = join(homedir(), ".claude", "projects"), own = /* @__PURE__ */ new Set(), now = Date.now()) {
55
+ const files = [];
56
+ for (const project of await readdir(root, { withFileTypes: true }).catch(() => [])) {
57
+ if (!project.isDirectory()) continue;
58
+ for (const entry of await readdir(join(root, project.name), { withFileTypes: true }).catch(
59
+ () => []
60
+ )) {
61
+ if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
62
+ const id = entry.name.slice(0, -6);
63
+ if (!UUID.test(id) || own.has(id)) continue;
64
+ const path = join(root, project.name, entry.name);
65
+ const info = await stat(path).catch(() => null);
66
+ if (info && info.mtimeMs >= now - 7 * 864e5)
67
+ files.push({ id, project: project.name.slice(0, 200), file: path, mtime: info.mtimeMs });
68
+ }
69
+ }
70
+ const results = [];
71
+ const newest = files.sort((a, b) => b.mtime - a.mtime).slice(0, 20);
72
+ for (const path of seen.keys()) if (!newest.some((file) => file.file === path)) seen.delete(path);
73
+ for (const file of newest) {
74
+ const { title, cwd } = await claudeMeta(file.file, file.mtime);
75
+ results.push({
76
+ id: file.id,
77
+ project: file.project,
78
+ updatedAt: new Date(file.mtime).toISOString(),
79
+ status: "idle",
80
+ ...cwd ? { cwd } : {},
81
+ ...title ? { title } : {}
82
+ });
83
+ }
84
+ return results;
85
+ }
86
+ async function claudeMeta(file, mtime) {
87
+ const known = seen.get(file);
88
+ if (known?.mtime === mtime) return known;
89
+ let title;
90
+ let cwd;
91
+ const stream = createReadStream(file, { encoding: "utf8" });
92
+ const lines = createInterface({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });
93
+ try {
94
+ for await (const line of lines) {
95
+ if (!cwd && line.includes('"cwd"')) {
96
+ try {
97
+ const record = JSON.parse(line);
98
+ if (typeof record.cwd === "string" && record.cwd.startsWith("/") && record.cwd.length <= 500)
99
+ cwd = record.cwd;
100
+ } catch {
101
+ }
102
+ }
103
+ if (!/^\s*\{\s*"type"\s*:\s*"(?:summary|custom-title|title)"/.test(line)) continue;
104
+ try {
105
+ const record = JSON.parse(line);
106
+ const value = record.type === "summary" ? record.summary : record.type === "custom-title" ? record.customTitle : record.title;
107
+ if (typeof value === "string" && value.trim()) title = value.trim().slice(0, 120);
108
+ } catch {
109
+ }
110
+ }
111
+ } finally {
112
+ lines.close();
113
+ stream.destroy();
114
+ }
115
+ const meta = { mtime, ...title ? { title } : {}, ...cwd ? { cwd } : {} };
116
+ seen.set(file, meta);
117
+ return meta;
118
+ }
119
+ function sessionRoots(home = homedir()) {
120
+ return { claude: join(home, ".claude", "projects"), codex: join(home, ".codex", "sessions") };
121
+ }
122
+ async function findSession(id, roots, harnesses) {
123
+ if (!UUID.test(id)) return null;
124
+ if (harnesses.includes("claude-code")) {
125
+ for (const project of await readdir(roots.claude, { withFileTypes: true }).catch(() => [])) {
126
+ if (!project.isDirectory()) continue;
127
+ const file = join(roots.claude, project.name, `${id}.jsonl`);
128
+ const info = await stat(file).catch(() => null);
129
+ if (!info?.isFile()) continue;
130
+ const meta = await claudeMeta(file, info.mtimeMs);
131
+ return {
132
+ harness: "claude-code",
133
+ id,
134
+ cwd: meta.cwd ?? null,
135
+ ...meta.title ? { title: meta.title } : {},
136
+ mtime: info.mtimeMs
137
+ };
138
+ }
139
+ }
140
+ if (harnesses.includes("codex")) {
141
+ const file = (await codexFiles(roots.codex)).find((f) => f.id === id);
142
+ if (file) {
143
+ const meta = await codexMeta(file.file, file.mtime);
144
+ if (meta?.id === id) {
145
+ const title = (await codexTitles(roots.codex)).get(id);
146
+ return {
147
+ harness: "codex",
148
+ id,
149
+ cwd: meta.cwd,
150
+ ...title ? { title } : {},
151
+ mtime: file.mtime
152
+ };
153
+ }
154
+ }
155
+ }
156
+ return null;
157
+ }
158
+ async function listCodexSessions(root, own = /* @__PURE__ */ new Set(), now = Date.now()) {
159
+ const files = (await codexFiles(root, now - 7 * 864e5)).filter((f) => !own.has(f.id)).slice(0, 20);
160
+ const titles = files.length ? await codexTitles(root) : /* @__PURE__ */ new Map();
161
+ const results = [];
162
+ for (const file of files) {
163
+ const meta = await codexMeta(file.file, file.mtime);
164
+ if (meta?.id !== file.id) continue;
165
+ const title = titles.get(file.id);
166
+ results.push({
167
+ id: file.id,
168
+ updatedAt: new Date(file.mtime).toISOString(),
169
+ status: "idle",
170
+ ...meta.cwd ? { cwd: meta.cwd } : {},
171
+ ...title ? { title } : {}
172
+ });
173
+ }
174
+ return results;
175
+ }
176
+ var ROLLOUT = /^rollout-.+-([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.jsonl$/i;
177
+ async function codexFiles(root, since = 0) {
178
+ const out = [];
179
+ const names = async (dir) => (await readdir(dir, { withFileTypes: true }).catch(() => [])).filter((d) => d.isDirectory() && /^\d+$/.test(d.name)).map((d) => d.name).sort().reverse();
180
+ for (const year of await names(root))
181
+ for (const month of await names(join(root, year)))
182
+ for (const day of await names(join(root, year, month))) {
183
+ const dir = join(root, year, month, day);
184
+ for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
185
+ const id = entry.isFile() ? ROLLOUT.exec(entry.name)?.[1] : void 0;
186
+ if (!id) continue;
187
+ const file = join(dir, entry.name);
188
+ const info = await stat(file).catch(() => null);
189
+ if (info && info.mtimeMs >= since) out.push({ id, file, mtime: info.mtimeMs });
190
+ }
191
+ }
192
+ return out.sort((a, b) => b.mtime - a.mtime);
193
+ }
194
+ var codexSeen = /* @__PURE__ */ new Map();
195
+ async function codexMeta(file, mtime) {
196
+ const known = codexSeen.get(file);
197
+ if (known?.mtime === mtime) return known.meta;
198
+ const stream = createReadStream(file, { encoding: "utf8" });
199
+ const lines = createInterface({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });
200
+ let meta = null;
201
+ try {
202
+ for await (const line of lines) {
203
+ try {
204
+ const record = JSON.parse(line);
205
+ const payload = record?.type === "session_meta" ? record.payload : null;
206
+ if (typeof payload?.id === "string") {
207
+ const cwd = payload.cwd;
208
+ meta = {
209
+ id: payload.id,
210
+ cwd: typeof cwd === "string" && cwd.startsWith("/") && cwd.length <= 500 ? cwd : null
211
+ };
212
+ }
213
+ } catch {
214
+ }
215
+ break;
216
+ }
217
+ } finally {
218
+ lines.close();
219
+ stream.destroy();
220
+ }
221
+ if (codexSeen.size > 200) codexSeen.clear();
222
+ codexSeen.set(file, { mtime, meta });
223
+ return meta;
224
+ }
225
+ async function codexTitles(root) {
226
+ const titles = /* @__PURE__ */ new Map();
227
+ const text = await readFile(join(dirname(root), "session_index.jsonl"), "utf8").catch(() => "");
228
+ for (const line of text.split("\n")) {
229
+ try {
230
+ const record = JSON.parse(line);
231
+ if (typeof record?.id === "string" && typeof record.thread_name === "string" && record.thread_name.trim())
232
+ titles.set(record.id, record.thread_name.trim().slice(0, 120));
233
+ } catch {
234
+ }
235
+ }
236
+ return titles;
237
+ }
238
+
239
+ // src/drivers/local.ts
240
+ import { execFile, execFileSync, spawn } from "child_process";
241
+ import { chmodSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "fs";
242
+ import { hostname } from "os";
243
+ import { basename, dirname as dirname2, join as join2 } from "path";
244
+ import { createInterface as createInterface2 } from "readline";
245
+ var STOPPED = { kind: "failed", summary: STOPPED_SUMMARY };
246
+ function takeoverSummary(machine) {
247
+ return `You took this over on ${machine}.`;
248
+ }
249
+ var ADOPT_QUIET_MS = 2 * 6e4;
250
+ var CONTINUE_PROMPT = "Continue the work from where you stopped. If it is already done, say so in one sentence.";
251
+ var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master", "HEAD"]);
252
+ var COMMANDS_KEPT = 50;
253
+ var SUMMARY_MAX = 200;
254
+ var HARNESS_NAMES = { "claude-code": "Claude Code", codex: "Codex" };
255
+ var harnessName = (name) => HARNESS_NAMES[name] ?? name;
256
+ function runHarness(run2, own) {
257
+ const driver = own?.driver === "codex" ? "codex" : "claude-code";
258
+ const harness = run2.harness ?? driver;
259
+ const bin = harness === driver && own?.bin ? own.bin : harness === "codex" ? "codex" : "claude";
260
+ return { harness, bin };
261
+ }
262
+ var switchedLine = (move, from, to) => movedLine(move.reason, harnessName(from), harnessName(to), move.at === "run" ? "was" : "is");
263
+ function failedEnd(harness, run2) {
264
+ const said = run2.result?.text?.trim() || run2.lastText;
265
+ const limited = HARNESS_LIMIT.test(run2.result?.text ?? "");
266
+ const words = said && apiErrorWords(said.trim()).replace(/\s+/g, " ").trim();
267
+ const error = limited ? { error: "harness_limit" } : {};
268
+ const opening = run2.switched ? `${run2.switched} ` : "";
269
+ if (!words)
270
+ return {
271
+ summary: `${opening}${run2.result ? "The run ended with an error." : `The run exited with ${run2.exit}.`}`,
272
+ ...error
273
+ };
274
+ const lead = `${opening}${harnessName(harness)} said: "`;
275
+ const room = SUMMARY_MAX - lead.length - 1;
276
+ const quoted = words.length > room ? `${words.slice(0, room - 1)}\u2026` : words;
277
+ return { summary: `${lead}${quoted}"`, ...error };
278
+ }
279
+ function localRunsFilePath(env) {
280
+ return runnerPath(env, process.env.CLOOP_LOCAL_RUNS_FILE, (dir) => join2(dir, "local-runs.json"));
281
+ }
282
+ function holdsRepository(r, repository) {
283
+ const want = repoName(repository);
284
+ return repoName(r.label) === want || repoName(basename(r.path)) === want;
285
+ }
286
+ function apartLine(busy) {
287
+ return `Another run is working in ${busy.label} (${busy.path}), so this run has a folder of its own. If this work needs that project's code, do not edit ${busy.path}: make a git worktree of it in this folder and work there. If you open a pull request, put its URL in your result.`;
288
+ }
289
+ function pruneApartFolders(dir, kept, repos) {
290
+ let names;
291
+ try {
292
+ names = readdirSync(dir);
293
+ } catch {
294
+ return 0;
295
+ }
296
+ const gone = names.filter((name) => !kept.has(name));
297
+ for (const name of gone) rmSync(join2(dir, name), { recursive: true, force: true });
298
+ if (gone.length)
299
+ for (const repo of repos) {
300
+ try {
301
+ execFileSync("git", ["worktree", "prune"], { cwd: repo.path, stdio: "ignore", timeout: 1e4 });
302
+ } catch {
303
+ }
304
+ }
305
+ return gone.length;
306
+ }
307
+ function pickRepo(repos, repository) {
308
+ const picked = repository && repos.find((r) => holdsRepository(r, repository)) || repos[0];
309
+ if (!picked) throw new BoxToolError("no_project");
310
+ return picked;
311
+ }
312
+ function withFolder(r, end) {
313
+ return end.kind === "settled" ? { ...end, cwd: r.repo } : end;
314
+ }
315
+ function run(cmd, args, cwd) {
316
+ return new Promise(
317
+ (resolve, reject) => execFile(
318
+ cmd,
319
+ args,
320
+ { cwd, timeout: 1e4, encoding: "utf-8" },
321
+ (err, out) => err ? reject(err) : resolve(String(out).trim())
322
+ )
323
+ );
324
+ }
325
+ var gitProbe = {
326
+ head: (repo) => run("git", ["rev-parse", "HEAD"], repo).catch(() => null),
327
+ pushed: (repo) => run("git", ["branch", "-r", "--contains", "HEAD"], repo).then(
328
+ (out) => out.length > 0,
329
+ () => false
330
+ ),
331
+ async branchPr(repo) {
332
+ try {
333
+ const branch = await run("git", ["rev-parse", "--abbrev-ref", "HEAD"], repo);
334
+ if (SHARED_BRANCHES.has(branch)) return null;
335
+ return prUrlIn(await run("gh", ["pr", "view", "--json", "url", "-q", ".url"], repo));
336
+ } catch {
337
+ return null;
338
+ }
339
+ }
340
+ };
341
+ function processCommandLine(pid, platform = process.platform) {
342
+ if (platform === "win32")
343
+ return [
344
+ "powershell",
345
+ "-NoProfile",
346
+ "-NonInteractive",
347
+ "-Command",
348
+ `(Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}').CommandLine`
349
+ ];
350
+ return ["ps", "-ww", "-o", "command=", "-p", String(pid)];
351
+ }
352
+ function harnessAlive(pid, r, dialect) {
353
+ try {
354
+ process.kill(pid, 0);
355
+ } catch (err) {
356
+ if (err.code !== "EPERM") return false;
357
+ }
358
+ try {
359
+ const [file, ...args] = processCommandLine(pid);
360
+ const command = execFileSync(file, args, {
361
+ encoding: "utf-8",
362
+ timeout: 2e3,
363
+ ...file === "powershell" ? { env: windowsPowerShellEnv() } : {}
364
+ });
365
+ return dialect.owns(r, command);
366
+ } catch {
367
+ return false;
368
+ }
369
+ }
370
+ var KEEP_MS = 7 * 24 * 36e5;
371
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
372
+ var LocalDriver = class {
373
+ constructor(deps) {
374
+ this.deps = deps;
375
+ this.name = deps.dialect.name;
376
+ this.harnessCheck = new HarnessCheck(
377
+ deps.harnesses ?? (async () => [await deps.dialect.probe()].filter((h) => h !== null)),
378
+ { now: () => this.now(), log: (line) => this.log(line) }
379
+ );
380
+ this.capabilities = deps.dialect.capabilities;
381
+ this.runs = new Map(this.load().map((r) => [r.work_id, r]));
382
+ this.logDir = deps.logDir ?? runLogDir(this.file);
383
+ try {
384
+ const removed = pruneRunLogs(this.logDir, this.now());
385
+ if (removed) this.log(`run logs removed=${removed} older than 14 days`);
386
+ } catch (err) {
387
+ this.log(`run log prune failed: ${err.code ?? "unknown"}`);
388
+ }
389
+ try {
390
+ const removed = pruneApartFolders(join2(dirname2(this.file), "work"), new Set(this.runs.keys()), deps.repos);
391
+ if (removed) this.log(`run folders removed=${removed} of runs no longer kept`);
392
+ } catch (err) {
393
+ this.log(`run folder prune failed: ${err.code ?? "unknown"}`);
394
+ }
395
+ }
396
+ deps;
397
+ name;
398
+ capabilities;
399
+ runs;
400
+ lives = /* @__PURE__ */ new Map();
401
+ listeners = /* @__PURE__ */ new Map();
402
+ recovering = /* @__PURE__ */ new Set();
403
+ stopping = false;
404
+ logDir;
405
+ logFailed = false;
406
+ harnessCheck;
407
+ /** Until then, the runner's own harness is at an account-wide limit and new runs start on the fallback. */
408
+ limitedUntil = 0;
409
+ get repo() {
410
+ return this.deps.repo ?? gitProbe;
411
+ }
412
+ get file() {
413
+ return this.deps.file ?? localRunsFilePath();
414
+ }
415
+ log(line) {
416
+ this.deps.log?.(line);
417
+ }
418
+ /** One line in the run's own log, for `cloop watch`. A full disk must not stop the run. */
419
+ note(r, text) {
420
+ try {
421
+ appendRunLog(this.logDir, r.work_id, text, { now: this.now() });
422
+ } catch (err) {
423
+ if (this.logFailed) return;
424
+ this.logFailed = true;
425
+ this.log(`run log write failed: ${err.code ?? "unknown"}`);
426
+ }
427
+ }
428
+ now() {
429
+ return this.deps.now?.() ?? Date.now();
430
+ }
431
+ /** Probes the harnesses now, so the first status after the daemon starts answers at once. */
432
+ warmHarnesses() {
433
+ void this.harnessCheck.refresh().then(() => this.status()).catch((err) => this.log(`usage warm failed: ${err?.message}`));
434
+ }
435
+ /** Its repository folders, by label and folder name, the names `pickRepo` matches. */
436
+ async checkouts() {
437
+ return [...new Set(this.deps.repos.flatMap((r) => [r.label, basename(r.path)]))];
438
+ }
439
+ async status() {
440
+ const { harnesses, checkedAt, probing } = await this.harnessCheck.read();
441
+ const all = [...this.runs.values()];
442
+ const unsettled = all.filter((r) => !r.end);
443
+ const usage = this.deps.usage;
444
+ return {
445
+ box: { label: this.deps.label ?? hostname(), driver: this.name },
446
+ harnesses: usage ? usage.withQuota(harnesses) : harnesses,
447
+ harnesses_checked_at: checkedAt,
448
+ ...probing ? { probing: true } : {},
449
+ clients: null,
450
+ projects: this.deps.repos.map((r) => r.label),
451
+ threads: {
452
+ unsettled: unsettled.length,
453
+ running: unsettled.filter((r) => this.lives.has(r.work_id)).length,
454
+ settled: all.length - unsettled.length,
455
+ cloop: unsettled.length
456
+ },
457
+ ...usage ? { token_usage: usage.tokenUsage() } : {}
458
+ };
459
+ }
460
+ async listThreads({
461
+ scope,
462
+ limit
463
+ }) {
464
+ const all = [...this.runs.values()];
465
+ const unsettled = all.filter((r) => !r.end);
466
+ const shown = (scope === "all" ? all : unsettled).map((r) => {
467
+ const asks = this.lives.get(r.work_id)?.asks ?? [];
468
+ return {
469
+ id: r.work_id,
470
+ title: r.title,
471
+ status: this.statusOf(r),
472
+ branch: null,
473
+ source: r.adopted ? this.dialectOf(r).name : "cloop",
474
+ cloop: !r.adopted,
475
+ settled: Boolean(r.end),
476
+ updatedAt: r.end?.at ?? r.started_at,
477
+ ...asks.length ? { asks: asks.map((a) => ({ question_id: a.request_id, question: a.summary })) } : {}
478
+ };
479
+ });
480
+ const running = shown.filter((t) => t.status === "running").length;
481
+ return {
482
+ scope,
483
+ unsettled: unsettled.length,
484
+ settled: all.length - unsettled.length,
485
+ running,
486
+ // The daemon owns every run's harness process here, the owner's adopted sessions too.
487
+ cloopRunning: running,
488
+ threads: orderThreads([...shown, ...await this.ownSessions()], limit)
489
+ };
490
+ }
491
+ /**
492
+ * The owner's own Claude Code and Codex sessions on this machine, the ones
493
+ * Cloop did not start, so a thread id from this list can be steered. Each
494
+ * is idle: a send resumes it.
495
+ */
496
+ async ownSessions() {
497
+ const known = new Set(
498
+ [...this.runs.values()].flatMap((r) => [r.work_id, ...r.session_id ? [r.session_id] : []])
499
+ );
500
+ const roots = this.deps.sessions ?? sessionRoots();
501
+ const harnesses = this.sessionHarnesses();
502
+ const [claude, codex] = await Promise.all([
503
+ harnesses.includes("claude-code") ? listOutsideSessions(roots.claude, known) : [],
504
+ harnesses.includes("codex") ? listCodexSessions(roots.codex, known) : []
505
+ ]);
506
+ const view = (source) => (t) => ({
507
+ id: t.id,
508
+ title: t.title ?? t.project ?? "Untitled session",
509
+ status: t.status,
510
+ branch: null,
511
+ source,
512
+ cloop: false,
513
+ settled: false,
514
+ updatedAt: t.updatedAt
515
+ });
516
+ return [...claude.map(view("claude-code")), ...codex.map(view("codex"))];
517
+ }
518
+ sessionHarnesses() {
519
+ return [this.deps.dialect, this.deps.fallbackHarness].flatMap(
520
+ (d) => d && (d.name === "claude-code" || d.name === "codex") ? [d.name] : []
521
+ );
522
+ }
523
+ /**
524
+ * A session the owner started outside Cloop, as a run, the first time Cloop
525
+ * sends it something. It keeps its own harness and folder, and a send
526
+ * resumes it there. Not registered here: the send that takes it does that.
527
+ */
528
+ async adopt(id) {
529
+ const found = await findSession(
530
+ id,
531
+ this.deps.sessions ?? sessionRoots(),
532
+ this.sessionHarnesses()
533
+ );
534
+ if (!found) throw new BoxToolError("bad_args");
535
+ if (!found.cwd) throw new BoxToolError("no_project");
536
+ const age = this.now() - found.mtime;
537
+ if (age < ADOPT_QUIET_MS) {
538
+ this.log(`adopt refused work=${id} reason=thread_busy age_ms=${Math.round(age)}`);
539
+ throw new BoxToolError("thread_busy");
540
+ }
541
+ this.refuseBusy(found.cwd);
542
+ const head = await this.repo.head(found.cwd).catch(() => null);
543
+ const raced = this.runs.get(id);
544
+ if (raced) return raced;
545
+ this.log(`adopt work=${id} harness=${found.harness}`);
546
+ return {
547
+ work_id: id,
548
+ session_id: id,
549
+ repo: found.cwd,
550
+ title: found.title ?? "Your session",
551
+ // A move to the other harness would leave the owner's session behind.
552
+ harness_named: true,
553
+ ...found.harness !== this.deps.dialect.name ? { harness: found.harness } : {},
554
+ adopted: true,
555
+ pid: null,
556
+ started_at: new Date(this.now()).toISOString(),
557
+ head_at_launch: head
558
+ };
559
+ }
560
+ async readThread(id) {
561
+ const r = this.record(id);
562
+ return {
563
+ status: this.statusOf(r),
564
+ settled: Boolean(r.end),
565
+ pr_url: r.end?.pr_url ?? null,
566
+ last_assistant_text: r.end?.summary ?? r.last_text ?? null,
567
+ resume: this.dialectOf(r).name === "claude-code" && r.session_id ? { cwd: r.repo, session_id: r.session_id } : null
568
+ };
569
+ }
570
+ async launch(a) {
571
+ const existing = this.runs.get(a.work_id);
572
+ if (existing)
573
+ return {
574
+ thread_id: a.work_id,
575
+ resumed: true,
576
+ permission: existing.used_permission,
577
+ takeover: true,
578
+ harness: this.dialectOf(existing).name
579
+ };
580
+ const own = this.deps.dialect;
581
+ if (a.harness && !own.aliases.includes(a.harness))
582
+ throw new BoxToolError("harness_unavailable");
583
+ const repo = pickRepo(this.deps.repos, a.repository);
584
+ const missing = a.repository && !holdsRepository(repo, a.repository) ? a.repository : null;
585
+ if (missing)
586
+ this.log(
587
+ `launch work=${a.work_id} has no ${missing}; starts in ${basename(repo.path)} to clone it`
588
+ );
589
+ else if (a.repository) this.refuseBusy(repo.path);
590
+ const { dialect, moved } = await this.route(a);
591
+ const head = await this.repo.head(repo.path);
592
+ const photos = await this.photos(a);
593
+ const concurrent = this.runs.get(a.work_id);
594
+ if (concurrent)
595
+ return {
596
+ thread_id: a.work_id,
597
+ resumed: true,
598
+ permission: concurrent.used_permission,
599
+ takeover: true,
600
+ harness: this.dialectOf(concurrent).name
601
+ };
602
+ if (!missing && a.repository) this.refuseBusy(repo.path);
603
+ const apart = !missing && !a.repository && this.busy(repo.path) ? join2(dirname2(this.file), "work", a.work_id) : null;
604
+ if (apart) {
605
+ mkdirSync(apart, { recursive: true, mode: 448 });
606
+ this.log(`launch work=${a.work_id} ${basename(repo.path)} is busy; starts in its own folder`);
607
+ }
608
+ const record = {
609
+ work_id: a.work_id,
610
+ session_id: dialect.name === "claude-code" ? a.work_id : null,
611
+ repo: apart ?? repo.path,
612
+ title: a.title,
613
+ prompt: [a.prompt, missing && cloneLine(missing), apart && apartLine(repo), photos.line].filter(Boolean).join("\n\n"),
614
+ ...photos.paths.length ? { images: photos.paths } : {},
615
+ ...a.model && !moved ? { model: a.model } : {},
616
+ ...a.runtime_mode ? { runtime_mode: a.runtime_mode } : {},
617
+ ...a.harness ? { harness_named: true } : {},
618
+ ...a.model ? { model_named: true } : {},
619
+ ...moved ? { harness: dialect.name, moved, switched: switchedLine(moved, own.name, dialect.name) } : {},
620
+ pid: null,
621
+ started_at: new Date(this.now()).toISOString(),
622
+ head_at_launch: apart ? null : head
623
+ };
624
+ this.runs.set(a.work_id, record);
625
+ if (moved)
626
+ this.log(`fallback work=${a.work_id} harness=${dialect.name} reason=${moved.reason}`);
627
+ this.spawnRun(record, record.prompt ?? a.prompt, false);
628
+ return {
629
+ thread_id: a.work_id,
630
+ resumed: false,
631
+ permission: record.used_permission,
632
+ takeover: true,
633
+ harness: dialect.name,
634
+ repository: basename(repo.path),
635
+ ...delivery(a.attachments, photos.paths.length)
636
+ };
637
+ }
638
+ async send(a) {
639
+ const r = this.runs.get(a.thread_id) ?? await this.adopt(a.thread_id);
640
+ const seen2 = r.commands?.find(([id]) => id === a.command_id);
641
+ if (seen2) return { delivered: seen2[1] };
642
+ const live = this.lives.get(r.work_id);
643
+ const ask = live?.asks[0];
644
+ if (a.answer && (!ask || ask.request_id !== a.question_id)) {
645
+ this.log(`question_changed work=${r.work_id}`);
646
+ return {
647
+ delivered: "question_changed",
648
+ question: ask?.summary ?? null,
649
+ question_id: ask?.request_id ?? null
650
+ };
651
+ }
652
+ if (live && ask) {
653
+ if (!a.answer) {
654
+ return {
655
+ delivered: "question_pending",
656
+ question: ask.summary,
657
+ questions: live.asks.length
658
+ };
659
+ }
660
+ const line2 = this.dialectOf(r).answerLine?.(ask, a.text);
661
+ if (!line2) throw new BoxToolError("cannot_steer");
662
+ live.asks = live.asks.slice(1);
663
+ this.write(live, line2);
664
+ this.note(r, `< You answered: ${a.text}`);
665
+ this.remember(r, a.command_id, "answer");
666
+ this.log(`answer work=${r.work_id}`);
667
+ this.askNext(r, live);
668
+ return { delivered: "answer", question_id: ask.request_id };
669
+ }
670
+ if (!live) {
671
+ if (r.end && !a.resume) throw new BoxToolError("already_finished");
672
+ if (r.end) {
673
+ this.refuseBusy(r.repo);
674
+ r.end = void 0;
675
+ r.last_text = void 0;
676
+ }
677
+ this.runs.set(r.work_id, r);
678
+ this.spawnRun(r, a.text, true);
679
+ this.remember(r, a.command_id, "start");
680
+ return { delivered: "start" };
681
+ }
682
+ if (live.child.stdin?.writableEnded) {
683
+ live.next = live.next ? `${live.next}
684
+
685
+ ${a.text}` : a.text;
686
+ this.remember(r, a.command_id, "queue");
687
+ return { delivered: "queue" };
688
+ }
689
+ const line = this.dialectOf(r).userLine?.(r, a.text, a.mode);
690
+ if (!line) throw new BoxToolError("cannot_steer");
691
+ live.outstanding++;
692
+ this.write(live, line);
693
+ this.note(r, `< You: ${a.text}`);
694
+ const delivered = a.mode === "queue" ? "queue" : "steer";
695
+ this.remember(r, a.command_id, delivered);
696
+ this.log(`${delivered} work=${r.work_id}`);
697
+ return { delivered };
698
+ }
699
+ async interrupt(id, _commandId, stop = STOPPED) {
700
+ const r = this.record(id);
701
+ const live = this.lives.get(r.work_id);
702
+ if (!live) {
703
+ if (r.end) return { ok: true, was_running: false };
704
+ const orphan = r.pid !== null && this.alive(r.pid, r);
705
+ if (orphan && r.pid !== null) {
706
+ try {
707
+ process.kill(r.pid, "SIGINT");
708
+ } catch {
709
+ }
710
+ }
711
+ await this.end(r, stop);
712
+ return { ok: true, was_running: orphan };
713
+ }
714
+ live.interrupted = stop;
715
+ live.child.kill("SIGINT");
716
+ this.note(r, stop === STOPPED ? "= Stop requested." : `= ${stop.summary}`);
717
+ const timer = setTimeout(() => {
718
+ if (live.child.exitCode === null && live.child.signalCode === null)
719
+ live.child.kill("SIGTERM");
720
+ }, this.deps.interruptGraceMs ?? 1e4);
721
+ timer.unref();
722
+ this.log(`interrupt work=${r.work_id}${stop.error ? ` reason=${stop.error}` : ""}`);
723
+ return { ok: true, was_running: true };
724
+ }
725
+ /**
726
+ * `cloop takeover`: stop the run so the owner can open its session in
727
+ * their own terminal. It ends as a stop, with the machine in its words, and
728
+ * never resumes by itself: two processes on one session would fight.
729
+ */
730
+ takeOver(id, machine) {
731
+ return this.interrupt(id, void 0, {
732
+ kind: "failed",
733
+ summary: takeoverSummary(machine),
734
+ error: "taken_over"
735
+ });
736
+ }
737
+ watch(id, onEvent) {
738
+ const set = this.listeners.get(id) ?? /* @__PURE__ */ new Set();
739
+ set.add(onEvent);
740
+ this.listeners.set(id, set);
741
+ const r = this.runs.get(id);
742
+ const unwatch = () => set.delete(onEvent);
743
+ if (!r) {
744
+ onEvent({ kind: "failed", summary: "This run is not on the machine any more." });
745
+ return unwatch;
746
+ }
747
+ if (r.end) {
748
+ const { at: _at, ...end } = r.end;
749
+ onEvent(withFolder(r, end));
750
+ return unwatch;
751
+ }
752
+ const live = this.lives.get(id);
753
+ const ask = live?.asks[0];
754
+ if (ask) onEvent({ kind: "question", question_id: ask.request_id, summary: ask.summary });
755
+ if (!live) void this.recover(r);
756
+ return unwatch;
757
+ }
758
+ /** On a daemon stop: end every process, and leave its run open so the next start resumes it. */
759
+ stop() {
760
+ this.stopping = true;
761
+ for (const live of this.lives.values()) live.child.kill("SIGTERM");
762
+ }
763
+ alive(pid, r) {
764
+ return this.deps.alive ? this.deps.alive(pid, r) : harnessAlive(pid, r, this.dialectOf(r));
765
+ }
766
+ /** The harness a run is on: the fallback once it took the run over. */
767
+ dialectOf(r) {
768
+ const fallback = this.deps.fallbackHarness;
769
+ return fallback && r.harness === fallback.name ? fallback : this.deps.dialect;
770
+ }
771
+ /**
772
+ * The fallback harness, when it may carry this run. A move never gives a
773
+ * run more access than its own harness would: a run that asks the owner
774
+ * does not go to a harness that asks nothing.
775
+ */
776
+ carrier(run2, own) {
777
+ const to = this.deps.fallbackHarness;
778
+ return to && (to.permission?.(run2) !== "full" || own === "full") ? to : null;
779
+ }
780
+ /**
781
+ * A Task that names its harness stays on it. Otherwise a run starts on the
782
+ * fallback while the runner's own harness is held at its limit, or when the
783
+ * own harness is signed out or not installed and the fallback is signed in,
784
+ * unless the Task named its model.
785
+ */
786
+ async route(a) {
787
+ const own = this.deps.dialect;
788
+ const mode = a.runtime_mode ? { runtime_mode: a.runtime_mode } : {};
789
+ const to = a.harness ? null : this.carrier(mode, own.permission?.(mode));
790
+ const ready = async () => Boolean(to && (await to.probe().catch(() => null))?.signedIn);
791
+ if (to && this.now() < this.limitedUntil && await ready())
792
+ return { dialect: to, moved: { reason: "limit", at: "launch" } };
793
+ const harness = await own.probe();
794
+ if (harness?.signedIn) return { dialect: own };
795
+ if (to && !a.model && await ready())
796
+ return {
797
+ dialect: to,
798
+ moved: { reason: harness ? "signed_out" : "missing", at: "launch" }
799
+ };
800
+ throw new BoxToolError(harness ? "harness_signed_out" : "harness_unavailable");
801
+ }
802
+ /**
803
+ * The Task's photos for this run, saved beside the runs file so a harness
804
+ * that takes the run over later attaches them too. `line` tells the agent
805
+ * they are attached, and how many could not be loaded.
806
+ */
807
+ async photos(a) {
808
+ if (!a.attachments?.length) return { paths: [], line: "" };
809
+ const log = (line) => this.log(`${line} work=${a.work_id}`);
810
+ const { images, missed } = await fetchImages(a.attachments, { log });
811
+ const paths = await saveImages(
812
+ images,
813
+ join2(dirname2(this.file), "attachments", a.work_id)
814
+ ).catch((err) => {
815
+ log(`attachments_unsaved reason=${err.message.slice(0, 120)}`);
816
+ return [];
817
+ });
818
+ this.log(
819
+ `attachments work=${a.work_id} attached=${paths.length} missed=${missed + images.length - paths.length}`
820
+ );
821
+ return { paths, line: attachedLine(paths.length, a.attachments.length - paths.length) };
822
+ }
823
+ /** One checkout, one run: two harnesses editing the same files at once would undo each other. */
824
+ refuseBusy(repo) {
825
+ if (this.busy(repo)) throw new BoxToolError("repo_busy");
826
+ }
827
+ busy(repo) {
828
+ return [...this.runs.values()].some((r) => r.repo === repo && !r.end);
829
+ }
830
+ /** One question at a time, oldest first, so a yes answers the prompt the owner read. */
831
+ askNext(r, live) {
832
+ const next = live.asks[0];
833
+ if (!next) return;
834
+ this.log(`question work=${r.work_id} tool=${next.tool}`);
835
+ this.emit(r.work_id, { kind: "question", question_id: next.request_id, summary: next.summary });
836
+ }
837
+ /** A run left open by a daemon that died: wait for its old process to go, then resume it once. */
838
+ async recover(r) {
839
+ if (this.recovering.has(r.work_id)) return;
840
+ this.recovering.add(r.work_id);
841
+ try {
842
+ while (r.pid !== null && this.alive(r.pid, r) && !r.end && !this.stopping) {
843
+ await sleep(this.deps.orphanPollMs ?? 2e3);
844
+ }
845
+ if (r.end || this.stopping || this.lives.has(r.work_id)) return;
846
+ this.log(`resume work=${r.work_id} after a restart`);
847
+ this.spawnRun(r, CONTINUE_PROMPT, true);
848
+ } finally {
849
+ this.recovering.delete(r.work_id);
850
+ }
851
+ }
852
+ spawnRun(r, prompt, resume) {
853
+ r.block_text = void 0;
854
+ const dialect = this.dialectOf(r);
855
+ r.used_permission = dialect.permission?.(r);
856
+ const images = resume ? [] : r.images ?? [];
857
+ const command = commandFor(dialect.bin, dialect.args(r, resume, images));
858
+ const child = spawn(command.file, command.args, {
859
+ cwd: r.repo,
860
+ stdio: ["pipe", "pipe", "pipe"],
861
+ env: { ...dialect.env, ...process.env },
862
+ ...command.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
863
+ });
864
+ const live = {
865
+ child,
866
+ outstanding: 1,
867
+ asks: [],
868
+ lastProgressAt: 0,
869
+ interrupted: null,
870
+ stderr: ""
871
+ };
872
+ this.lives.set(r.work_id, live);
873
+ r.pid = child.pid ?? null;
874
+ this.save();
875
+ this.log(`spawn work=${r.work_id} pid=${r.pid ?? "none"} ${resume ? "resume" : "new"}`);
876
+ this.note(r, resume ? "= Resumed." : `= Started "${r.title}" in ${r.repo}`);
877
+ child.stdin?.on("error", () => {
878
+ });
879
+ child.stdin?.write(dialect.opening(r, `${prompt}
880
+
881
+ ${MACHINE_RESULT_INSTRUCTION}`, images));
882
+ if (!dialect.keepsStdin) child.stdin?.end();
883
+ child.stderr?.on("data", (chunk) => {
884
+ live.stderr = (live.stderr + chunk.toString("utf-8")).slice(-2e3);
885
+ });
886
+ const lines = createInterface2({ input: child.stdout });
887
+ lines.on("line", (line) => {
888
+ for (const item of dialect.parse(line, r)) this.onItem(r, live, item);
889
+ });
890
+ child.on("error", (err) => {
891
+ this.log(`spawn failed work=${r.work_id}: ${err.message.slice(0, 200)}`);
892
+ });
893
+ child.on("close", (code, signal) => void this.onExit(r, live, code, signal));
894
+ }
895
+ onItem(r, live, item) {
896
+ const logged = logLineFor(item);
897
+ if (logged) this.note(r, logged);
898
+ switch (item.type) {
899
+ case "session":
900
+ if (r.session_id !== item.id) {
901
+ r.session_id = item.id;
902
+ this.save();
903
+ }
904
+ return;
905
+ case "text":
906
+ r.last_text = item.text.slice(0, 1e5);
907
+ if (hasResultBlock(item.text)) r.block_text = r.last_text;
908
+ this.progress(r, live, item.text, false);
909
+ return;
910
+ case "tool": {
911
+ const line = item.summary ?? (item.target ? `${item.name} ${item.target}` : item.name);
912
+ if (!isProgressSentence(line)) return;
913
+ const changed = item.name !== live.lastTool;
914
+ live.lastTool = item.name;
915
+ this.progress(r, live, line, changed);
916
+ return;
917
+ }
918
+ case "ask":
919
+ live.asks.push(item);
920
+ if (live.asks.length === 1) this.askNext(r, live);
921
+ return;
922
+ case "cancel": {
923
+ const wasAsked = live.asks[0]?.request_id === item.request_id;
924
+ live.asks = live.asks.filter((x) => x.request_id !== item.request_id);
925
+ if (wasAsked) this.askNext(r, live);
926
+ return;
927
+ }
928
+ case "signed_out":
929
+ live.signedOut = true;
930
+ return;
931
+ case "result":
932
+ live.outstanding--;
933
+ live.result = { ok: item.ok, ...item.text ? { text: item.text } : {} };
934
+ if (item.text) r.last_text = item.text.slice(0, 1e5);
935
+ if (live.outstanding <= 0 && live.asks.length === 0) live.child.stdin?.end();
936
+ return;
937
+ }
938
+ }
939
+ progress(r, live, line, force) {
940
+ const summary = nextProgress(live, line, this.now(), this.deps.progressMs, force);
941
+ if (summary) this.emit(r.work_id, { kind: "progress", summary });
942
+ }
943
+ async onExit(r, live, code, signal) {
944
+ if (this.lives.get(r.work_id) === live) this.lives.delete(r.work_id);
945
+ if (this.stopping || r.end) return;
946
+ const exit = signal ? `signal ${signal}` : `code ${code}`;
947
+ this.log(
948
+ `exit work=${r.work_id} ${exit} result=${live.result ? live.result.ok ? "ok" : "error" : "none"}`
949
+ );
950
+ if (live.interrupted) {
951
+ await this.end(r, live.interrupted);
952
+ return;
953
+ }
954
+ if (live.next) {
955
+ this.spawnRun(r, live.next, true);
956
+ return;
957
+ }
958
+ if (code === 0 && live.result?.ok) {
959
+ const text = live.result.text?.trim() || r.last_text;
960
+ const { result, dropped } = readRunResult(resultText(text, r.block_text));
961
+ const lost = droppedLine(dropped, r.work_id);
962
+ if (lost) this.log(lost);
963
+ const { pr, note } = await this.outcome(r, text);
964
+ const summary = finalWords([r.switched, note, text].filter(Boolean).join("\n\n"));
965
+ await this.end(r, {
966
+ kind: "settled",
967
+ ...result ? { result } : {},
968
+ ...summary ? { summary: summary.slice(0, RUN_TEXT_MAX) } : {},
969
+ ...pr ? { pr_url: pr } : {}
970
+ });
971
+ return;
972
+ }
973
+ if (live.stderr)
974
+ this.log(`stderr work=${r.work_id}: ${live.stderr.trim().split("\n").at(-1)?.slice(0, 200)}`);
975
+ const end = failedEnd(this.dialectOf(r).name, {
976
+ result: live.result,
977
+ lastText: r.last_text,
978
+ exit,
979
+ ...r.switched ? { switched: r.switched } : {}
980
+ });
981
+ if (await this.otherModel(r, live.result?.text)) return;
982
+ if (end.error) this.log(`limit work=${r.work_id} error=${end.error}`);
983
+ if (end.error === "harness_limit") {
984
+ if (this.fallBack(r, live.result?.text)) return;
985
+ if (await this.moveHarness(r, live.result?.text, "limit")) return;
986
+ }
987
+ if (live.signedOut) {
988
+ this.log(`signed_out work=${r.work_id} harness=${this.dialectOf(r).name}`);
989
+ if (await this.moveHarness(r, live.result?.text, "signed_out")) return;
990
+ }
991
+ const signedOut = !end.error && live.signedOut ? { error: "harness_signed_out" } : {};
992
+ await this.end(r, { kind: "failed", ...end, ...signedOut });
993
+ }
994
+ /**
995
+ * Once per run: a run stopped by its model's usage limit resumes its own
996
+ * session on the first fallback model, with the continue prompt, so its
997
+ * steers, answers and edits carry over. It does not when the Task named its
998
+ * model, when the limit is the fallback model's own or names no model, or
999
+ * after one switch. `--fallback-model` may already cover this; it is not
1000
+ * documented whether a plan's limit counts. The switch opens the end
1001
+ * summary, because a progress line is dropped while the socket is down.
1002
+ */
1003
+ fallBack(r, said) {
1004
+ const model = this.dialectOf(r).fallback?.split(",")[0]?.trim();
1005
+ if (!model || !r.session_id || r.switched || r.model) return false;
1006
+ const named = new RegExp(`\\b${model.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i");
1007
+ if (named.test(said ?? "")) return false;
1008
+ const from = limitedModel(said);
1009
+ if (!from) return false;
1010
+ const to = `${model.charAt(0).toUpperCase()}${model.slice(1)}`;
1011
+ r.switched = `${from} was at its usage limit, so this ran on ${to}.`;
1012
+ r.model = model;
1013
+ this.save();
1014
+ this.log(`fallback work=${r.work_id} model=${model}`);
1015
+ this.emit(r.work_id, {
1016
+ kind: "progress",
1017
+ summary: `${from} is at its usage limit, so I switched to ${to}`
1018
+ });
1019
+ this.spawnRun(r, CONTINUE_PROMPT, true);
1020
+ return true;
1021
+ }
1022
+ /**
1023
+ * A model the account cannot use refuses the run before it does any work,
1024
+ * as ChatGPT Free does for a model `config.toml` pins. The run starts again
1025
+ * on the next model the account lists, best first, until one takes it or
1026
+ * the list runs out. It does not when the Task named its model.
1027
+ */
1028
+ async otherModel(r, said) {
1029
+ const refused = refusedModel(said);
1030
+ const dialect = this.dialectOf(r);
1031
+ if (!refused || !dialect.models || !r.prompt || r.model && !r.refused) return false;
1032
+ const tried = [...r.refused ?? [], refused];
1033
+ this.recovering.add(r.work_id);
1034
+ let listed;
1035
+ try {
1036
+ listed = await dialect.models().catch(() => []);
1037
+ } finally {
1038
+ this.recovering.delete(r.work_id);
1039
+ }
1040
+ const next = nextModel(listed, tried);
1041
+ if (!next)
1042
+ this.log(`model work=${r.work_id} refused=${refused} next=none catalog=${listed.length}`);
1043
+ if (!next || this.stopping || r.end) return false;
1044
+ const moved = r.harness && r.moved ? switchedLine(r.moved, this.deps.dialect.name, r.harness) : null;
1045
+ r.refused = tried;
1046
+ r.model = next;
1047
+ r.session_id = null;
1048
+ r.switched = [moved, refusedModelLine(harnessName(dialect.name), tried[0] ?? refused, next)].filter(Boolean).join(" ");
1049
+ this.save();
1050
+ this.log(`model work=${r.work_id} refused=${refused} next=${next}`);
1051
+ this.spawnRun(
1052
+ r,
1053
+ r.moved?.at === "run" ? handoverPrompt(r.prompt, harnessName(this.deps.dialect.name), r.moved.reason) : r.prompt,
1054
+ false
1055
+ );
1056
+ return true;
1057
+ }
1058
+ /**
1059
+ * Once per run: a run its own harness cannot carry on, at its usage limit
1060
+ * or signed out, starts again on the fallback harness, in the same
1061
+ * checkout, so the edits so far carry over. The session does not: the
1062
+ * prompt goes again, with a note to read the checkout first. A limit that
1063
+ * names no model holds the account, so new runs start on the fallback for
1064
+ * LIMIT_HOLD_MS; a sign-in failure holds nothing, because the next run's
1065
+ * check may find the harness signed in again. It does not move a run whose
1066
+ * Task named its harness, a signed-out run whose Task named its model, nor
1067
+ * one the fallback may not carry.
1068
+ */
1069
+ async moveHarness(r, said, reason) {
1070
+ const to = this.deps.fallbackHarness;
1071
+ if (!to || r.harness) return false;
1072
+ if (reason === "limit" && !limitedModel(said)) this.limitedUntil = this.now() + LIMIT_HOLD_MS;
1073
+ if (r.harness_named || reason === "signed_out" && r.model_named) return false;
1074
+ if (!this.carrier(r, r.used_permission) || !r.prompt) return false;
1075
+ this.recovering.add(r.work_id);
1076
+ try {
1077
+ const probe = await to.probe().catch(() => null);
1078
+ if (!probe?.signedIn || this.stopping || r.end) return false;
1079
+ } finally {
1080
+ this.recovering.delete(r.work_id);
1081
+ }
1082
+ const from = this.deps.dialect.name;
1083
+ const move = { reason, at: "run" };
1084
+ r.harness = to.name;
1085
+ r.moved = move;
1086
+ r.session_id = null;
1087
+ r.model = void 0;
1088
+ r.switched = switchedLine(move, from, to.name);
1089
+ this.save();
1090
+ this.log(`fallback work=${r.work_id} harness=${to.name} reason=${reason}`);
1091
+ this.emit(r.work_id, {
1092
+ kind: "progress",
1093
+ summary: movingLine(reason, harnessName(from), harnessName(to.name))
1094
+ });
1095
+ this.spawnRun(r, handoverPrompt(r.prompt, harnessName(from), reason), false);
1096
+ return true;
1097
+ }
1098
+ /**
1099
+ * The PR a run produced: one its last text names, else the PR of the
1100
+ * branch, but only when the run moved HEAD. A run that left HEAD where it
1101
+ * started produced nothing, and the branch's PR belongs to someone else's
1102
+ * work. A run that committed without pushing says so.
1103
+ */
1104
+ async outcome(r, text) {
1105
+ const named = resultPrUrl(text);
1106
+ if (named) return { pr: named };
1107
+ if (!r.head_at_launch) return { pr: null };
1108
+ const head = await this.repo.head(r.repo);
1109
+ if (!head || head === r.head_at_launch) return { pr: null };
1110
+ const pr = await this.repo.branchPr(r.repo);
1111
+ if (pr) return { pr };
1112
+ return await this.repo.pushed(r.repo) ? { pr: null } : { pr: null, note: `Committed ${head.slice(0, 7)}, not pushed.` };
1113
+ }
1114
+ async end(r, ended) {
1115
+ if (r.end) return;
1116
+ const end = { ...ended, harness: this.dialectOf(r).name };
1117
+ r.end = { ...end, at: new Date(this.now()).toISOString() };
1118
+ r.pid = null;
1119
+ this.save();
1120
+ this.note(r, endNote(end));
1121
+ this.emit(r.work_id, withFolder(r, end));
1122
+ }
1123
+ emit(id, event) {
1124
+ for (const listener of [...this.listeners.get(id) ?? []]) listener(event);
1125
+ }
1126
+ write(live, line) {
1127
+ live.child.stdin?.write(line);
1128
+ }
1129
+ remember(r, commandId, delivered) {
1130
+ r.commands = [
1131
+ ...r.commands ?? [],
1132
+ [commandId, delivered]
1133
+ ].slice(-COMMANDS_KEPT);
1134
+ this.save();
1135
+ }
1136
+ record(id) {
1137
+ const r = this.runs.get(id);
1138
+ if (!r) throw new BoxToolError("bad_args");
1139
+ return r;
1140
+ }
1141
+ statusOf(r) {
1142
+ if (this.lives.has(r.work_id)) return "running";
1143
+ if (!r.end) return "pending";
1144
+ return r.end.kind === "settled" ? "completed" : "failed";
1145
+ }
1146
+ load() {
1147
+ const cutoff = this.now() - KEEP_MS;
1148
+ return readRunRecords(this.file).filter((r) => !(r.end && Date.parse(r.end.at) < cutoff));
1149
+ }
1150
+ save() {
1151
+ mkdirSync(dirname2(this.file), { recursive: true, mode: 448 });
1152
+ const tmp = `${this.file}.tmp`;
1153
+ writeFileSync(tmp, `${JSON.stringify([...this.runs.values()], null, 2)}
1154
+ `, { mode: 384 });
1155
+ chmodSync(tmp, 384);
1156
+ renameSync(tmp, this.file);
1157
+ }
1158
+ };
1159
+ function readRunRecords(file = localRunsFilePath()) {
1160
+ try {
1161
+ const raw = JSON.parse(readFileSync(file, "utf-8"));
1162
+ return Array.isArray(raw) ? raw.filter(
1163
+ (r) => typeof r?.work_id === "string" && typeof r?.repo === "string"
1164
+ ) : [];
1165
+ } catch {
1166
+ return [];
1167
+ }
1168
+ }
1169
+
1170
+ export {
1171
+ listOutsideSessions,
1172
+ takeoverSummary,
1173
+ runHarness,
1174
+ failedEnd,
1175
+ localRunsFilePath,
1176
+ LocalDriver,
1177
+ readRunRecords
1178
+ };