@cloop/runner 0.2.1 → 0.2.3

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