@cloop/runner 0.2.5 → 0.2.7

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.
@@ -1,42 +1,48 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ serveTakeovers
4
+ } from "./chunk-DLFNATEZ.js";
5
+ import "./chunk-MC4DJ4LX.js";
2
6
  import {
3
7
  LocalDriver
4
- } from "./chunk-KOOAVO2C.js";
8
+ } from "./chunk-JFCEKATW.js";
5
9
  import {
6
10
  MeshSocket,
7
11
  defaultSocketFactory
8
12
  } from "./chunk-ZILLDYL4.js";
9
- import "./chunk-VK6GV757.js";
10
13
  import {
11
- BoxWatch,
12
14
  DEFAULT_FALLBACK_MODEL,
13
15
  T3Client,
14
16
  claudeDialect,
15
17
  codexDialect,
16
18
  connectCommand,
17
- lockThreadsFile,
18
19
  mintSession,
19
20
  probeClaude,
20
21
  probeClaudePermissions,
21
22
  probeCodex,
22
- runBoxTool,
23
+ runBoxTool
24
+ } from "./chunk-X7MNNKU3.js";
25
+ import {
26
+ BoxWatch,
27
+ lockThreadsFile,
23
28
  threadsFilePath,
24
29
  writeRunnerState
25
- } from "./chunk-2FLM3ESE.js";
30
+ } from "./chunk-MWWA2VH7.js";
26
31
  import {
27
32
  T3Driver,
28
33
  isLocal,
29
34
  readRunnerConfig,
30
35
  writeBoxConfig
31
- } from "./chunk-G6JAEE2Y.js";
36
+ } from "./chunk-LNQLGVYC.js";
32
37
  import {
33
38
  getMachine
34
39
  } from "./chunk-JX6VG5FE.js";
40
+ import "./chunk-VK6GV757.js";
35
41
  import "./chunk-R3CLO2FB.js";
36
- import "./chunk-53M5DK6D.js";
37
- import "./chunk-4XDYJZLF.js";
42
+ import "./chunk-JZNBZUPZ.js";
43
+ import "./chunk-SANEFNTU.js";
38
44
  import "./chunk-AG6SI6I2.js";
39
- import "./chunk-BFVL3E2C.js";
45
+ import "./chunk-KH6FK6UQ.js";
40
46
  import {
41
47
  getMeshUrl,
42
48
  getToken,
@@ -275,6 +281,7 @@ async function run() {
275
281
  );
276
282
  watch.start();
277
283
  setInterval(() => watch.flush(), RESEND_MS).unref();
284
+ if (driver instanceof LocalDriver) serveTakeovers(driver, log);
278
285
  const renewT3 = async () => {
279
286
  if (!cfg || isLocal(cfg) || Date.parse(cfg.expiresAt) - Date.now() >= REPAIR_BEFORE_MS) return;
280
287
  try {
@@ -284,6 +291,7 @@ async function run() {
284
291
  // Read from disk: `cloop connect` may have replaced it since.
285
292
  deviceToken: disk?.deviceToken ?? cfg.deviceToken,
286
293
  showOtherThreads: disk?.showOtherThreads ?? false,
294
+ ...disk?.chosenDriver ? { chosenDriver: disk.chosenDriver } : {},
287
295
  ...disk?.origin ?? cfg.origin ? { origin: disk?.origin ?? cfg.origin } : {}
288
296
  };
289
297
  cfg = renewed;
@@ -0,0 +1,250 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ findRun
4
+ } from "./chunk-MC4DJ4LX.js";
5
+ import {
6
+ localRunsFilePath,
7
+ readRunRecords,
8
+ takeoverSummary
9
+ } from "./chunk-JFCEKATW.js";
10
+ import {
11
+ lockThreadsFile,
12
+ threadsFilePath
13
+ } from "./chunk-MWWA2VH7.js";
14
+ import {
15
+ isLocal,
16
+ readRunnerConfig
17
+ } from "./chunk-LNQLGVYC.js";
18
+ import {
19
+ shortMachineName
20
+ } from "./chunk-JX6VG5FE.js";
21
+ import {
22
+ sanitizeLabel
23
+ } from "./chunk-VK6GV757.js";
24
+
25
+ // src/commands/takeover.ts
26
+ import { spawnSync } from "child_process";
27
+ import {
28
+ chmodSync,
29
+ existsSync,
30
+ mkdirSync,
31
+ readFileSync,
32
+ readdirSync,
33
+ renameSync,
34
+ unlinkSync,
35
+ writeFileSync
36
+ } from "fs";
37
+ import { dirname, join } from "path";
38
+ var SAFE_ID = /^[\w-]{1,100}$/;
39
+ var SHORT = 8;
40
+ function takeoverDir(runsFile = localRunsFilePath()) {
41
+ return join(dirname(runsFile), "takeover");
42
+ }
43
+ function writeTakeoverRequest(dir, request) {
44
+ if (!SAFE_ID.test(request.work_id)) return;
45
+ mkdirSync(dir, { recursive: true, mode: 448 });
46
+ const path = join(dir, `${request.work_id}.json`);
47
+ const temp = `${path}.${process.pid}.tmp`;
48
+ writeFileSync(temp, `${JSON.stringify(request)}
49
+ `, { mode: 384 });
50
+ renameSync(temp, path);
51
+ }
52
+ function replyPath(dir, workId) {
53
+ return SAFE_ID.test(workId) ? join(dir, `${workId}.reply`) : null;
54
+ }
55
+ function writeTakeoverReply(dir, workId, error) {
56
+ const path = replyPath(dir, workId);
57
+ if (!path) return;
58
+ mkdirSync(dir, { recursive: true, mode: 448 });
59
+ writeFileSync(path, `${JSON.stringify({ error: error.slice(0, 200) })}
60
+ `, { mode: 384 });
61
+ }
62
+ function takeTakeoverReply(dir, workId) {
63
+ const path = replyPath(dir, workId);
64
+ if (!path) return null;
65
+ let raw;
66
+ try {
67
+ raw = readFileSync(path, "utf-8");
68
+ } catch {
69
+ return null;
70
+ }
71
+ try {
72
+ unlinkSync(path);
73
+ } catch {
74
+ }
75
+ try {
76
+ const error = JSON.parse(raw).error;
77
+ return typeof error === "string" && error ? sanitizeLabel(error, 200) : "unknown";
78
+ } catch {
79
+ return "unknown";
80
+ }
81
+ }
82
+ function takeTakeoverRequests(dir) {
83
+ let names;
84
+ try {
85
+ names = readdirSync(dir).filter((name) => name.endsWith(".json"));
86
+ } catch {
87
+ return [];
88
+ }
89
+ const requests = [];
90
+ for (const name of names) {
91
+ const path = join(dir, name);
92
+ try {
93
+ const raw = JSON.parse(readFileSync(path, "utf-8"));
94
+ if (typeof raw.work_id === "string" && SAFE_ID.test(raw.work_id))
95
+ requests.push({
96
+ work_id: raw.work_id,
97
+ machine: sanitizeLabel(String(raw.machine ?? "this machine"), 60),
98
+ at: String(raw.at ?? "")
99
+ });
100
+ } catch {
101
+ }
102
+ try {
103
+ unlinkSync(path);
104
+ } catch {
105
+ }
106
+ }
107
+ return requests;
108
+ }
109
+ function serveTakeovers(driver, log, { dir = takeoverDir(), everyMs = 1e3 } = {}) {
110
+ const tick = () => {
111
+ for (const request of takeTakeoverRequests(dir)) {
112
+ driver.takeOver(request.work_id, request.machine).then(
113
+ (r) => log(`takeover work=${request.work_id} was_running=${r.was_running}`),
114
+ (err) => {
115
+ const error = err instanceof Error ? err.message : String(err);
116
+ log(`takeover work=${request.work_id} refused: ${error}`);
117
+ writeTakeoverReply(dir, request.work_id, error);
118
+ }
119
+ );
120
+ }
121
+ };
122
+ tick();
123
+ const timer = setInterval(tick, everyMs);
124
+ timer.unref();
125
+ return () => clearInterval(timer);
126
+ }
127
+ function endInFile(file, workId, machine, now) {
128
+ const records = readRunRecords(file);
129
+ const run = records.find((r) => r.work_id === workId);
130
+ if (!run || run.end) return false;
131
+ run.end = {
132
+ kind: "failed",
133
+ summary: takeoverSummary(machine),
134
+ error: "taken_over",
135
+ at: new Date(now).toISOString()
136
+ };
137
+ run.pid = null;
138
+ const temp = `${file}.tmp`;
139
+ writeFileSync(temp, `${JSON.stringify(records, null, 2)}
140
+ `, { mode: 384 });
141
+ chmodSync(temp, 384);
142
+ renameSync(temp, file);
143
+ return true;
144
+ }
145
+ function processAlive(pid) {
146
+ try {
147
+ process.kill(pid, 0);
148
+ return true;
149
+ } catch (err) {
150
+ return err.code === "EPERM";
151
+ }
152
+ }
153
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
154
+ async function takeoverCommand(args, deps = {}) {
155
+ const file = deps.file ?? localRunsFilePath();
156
+ const dir = deps.dir ?? takeoverDir(file);
157
+ const out = deps.out ?? ((line) => console.log(line));
158
+ const err = deps.err ?? ((line) => console.error(line));
159
+ const log = deps.log ?? ((line) => console.error(line));
160
+ const now = deps.now ?? Date.now;
161
+ const started = now();
162
+ const found = findRun(readRunRecords(file), args[0]);
163
+ if ("error" in found) {
164
+ err(found.error);
165
+ return 1;
166
+ }
167
+ const run = found.run;
168
+ const short = run.work_id.slice(0, SHORT);
169
+ if (run.end) {
170
+ err(`This run has ended. Open it with: cloop resume ${short}`);
171
+ return 1;
172
+ }
173
+ const cfg = deps.harness ? null : readRunnerConfig();
174
+ const local = cfg && isLocal(cfg) ? cfg : null;
175
+ const harness = deps.harness ?? local?.driver ?? "claude-code";
176
+ const bin = deps.bin ?? local?.bin ?? (harness === "codex" ? "codex" : "claude");
177
+ const session = run.session_id ?? (harness === "claude-code" ? run.work_id : null);
178
+ if (!session) {
179
+ err("This run has no session yet. Try again in a few seconds.");
180
+ return 1;
181
+ }
182
+ if (!existsSync(run.repo)) {
183
+ err(`The repository ${run.repo} is not on this machine any more.`);
184
+ return 1;
185
+ }
186
+ const machine = deps.machine ?? shortMachineName();
187
+ const fail = (line, reason) => {
188
+ err(line);
189
+ log(`[runner:takeover] work=${run.work_id} outcome=failed reason=${reason}`);
190
+ return 1;
191
+ };
192
+ const lock = (deps.lock ?? (() => lockThreadsFile(threadsFilePath())))();
193
+ let via;
194
+ if (lock.ok) {
195
+ try {
196
+ if (run.pid !== null && (deps.alive ?? processAlive)(run.pid))
197
+ return fail(
198
+ `The runner is not running, but the run's process (pid ${run.pid}) is. Start the runner, or stop the process, then run this again.`,
199
+ "orphan"
200
+ );
201
+ endInFile(file, run.work_id, machine, now());
202
+ } finally {
203
+ lock.release();
204
+ }
205
+ via = "file";
206
+ } else {
207
+ out(`Stopping "${sanitizeLabel(run.title, 120)}" on this machine\u2026`);
208
+ takeTakeoverReply(dir, run.work_id);
209
+ writeTakeoverRequest(dir, {
210
+ work_id: run.work_id,
211
+ machine,
212
+ at: new Date(now()).toISOString()
213
+ });
214
+ const deadline = Date.now() + (deps.waitMs ?? 3e4);
215
+ for (; ; ) {
216
+ const current = readRunRecords(file).find((r) => r.work_id === run.work_id);
217
+ if (current?.end) break;
218
+ const refused = takeTakeoverReply(dir, run.work_id);
219
+ if (refused)
220
+ return fail(
221
+ `The runner could not stop the run (${refused}). Stop it from Threads, then run: cloop resume ${short}`,
222
+ `refused:${refused}`
223
+ );
224
+ if (Date.now() > deadline)
225
+ return fail(
226
+ `The runner did not stop the run. Stop it from Threads, then run: cloop resume ${short}`,
227
+ "daemon_silent"
228
+ );
229
+ await sleep(deps.pollMs ?? 250);
230
+ }
231
+ via = "daemon";
232
+ }
233
+ log(`[runner:takeover] work=${run.work_id} via=${via} ms=${now() - started} outcome=ok`);
234
+ out(`You took this over on ${machine}. Cloop shows the run as stopped.`);
235
+ out(`Opening "${sanitizeLabel(run.title, 120)}" in ${run.repo}`);
236
+ const spawn = deps.spawn ?? ((b, a, cwd) => spawnSync(b, a, { cwd, stdio: "inherit" }).status ?? 1);
237
+ return spawn(bin, harness === "codex" ? ["resume", session] : ["--resume", session], run.repo);
238
+ }
239
+
240
+ export {
241
+ takeoverDir,
242
+ writeTakeoverRequest,
243
+ replyPath,
244
+ writeTakeoverReply,
245
+ takeTakeoverReply,
246
+ takeTakeoverRequests,
247
+ serveTakeovers,
248
+ endInFile,
249
+ takeoverCommand
250
+ };
@@ -1,144 +1,35 @@
1
1
  #!/usr/bin/env node
2
- import {
3
- stripControl
4
- } from "./chunk-VK6GV757.js";
5
2
  import {
6
3
  BoxToolError,
7
4
  RESULT_INSTRUCTION,
5
+ STOPPED_SUMMARY,
6
+ appendRunLog,
7
+ endNote,
8
+ isProgressSentence,
9
+ logLineFor,
10
+ nextProgress,
8
11
  orderThreads,
9
- parseRunResult
10
- } from "./chunk-G6JAEE2Y.js";
12
+ parseRunResult,
13
+ prUrlIn,
14
+ pruneRunLogs,
15
+ resultPrUrl,
16
+ runLogDir
17
+ } from "./chunk-LNQLGVYC.js";
11
18
  import {
12
19
  CONFIG_DIR
13
20
  } from "./chunk-3DIGCVL4.js";
14
21
 
15
- // src/run-log.ts
16
- import {
17
- appendFileSync,
18
- chmodSync,
19
- mkdirSync,
20
- readdirSync,
21
- renameSync,
22
- statSync,
23
- unlinkSync
24
- } from "fs";
25
- import { dirname, join } from "path";
26
- var RUN_LOG_LINE_MAX = 500;
27
- var RUN_LOG_MAX_BYTES = 5 * 1024 * 1024;
28
- var RUN_LOG_KEEP_MS = 14 * 24 * 36e5;
29
- var SAFE_ID = /^[\w-]{1,100}$/;
30
- function runLogDir(runsFile) {
31
- return join(dirname(runsFile), "runs");
32
- }
33
- function runLogPath(dir, workId) {
34
- return SAFE_ID.test(workId) ? join(dir, `${workId}.log`) : null;
35
- }
36
- var SECRETS = [
37
- [/-----BEGIN [A-Z ]*PRIVATE KEY-----.*/g, "[redacted private key]"],
38
- [/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "$1 [redacted]"],
39
- [/(:\/\/)[^\s/@:]+:[^\s/@]+@/g, "$1[redacted]@"],
40
- [
41
- /([?&](?:access_token|token|key|api_key|apikey|secret|sig|signature|code|password)=)[^&\s"']+/gi,
42
- "$1[redacted]"
43
- ],
44
- [
45
- /(\b(?:[\w-]*(?:token|secret|passw(?:or)?d|pwd|api[_-]?key|apikey|credential|private[_-]?key)[\w-]*|authorization|auth)["']?\s*[=:]\s*["']?)(?!Bearer\b|Basic\b|\[redacted)[^\s"',;}]{4,}/gi,
46
- "$1[redacted]"
47
- ],
48
- [
49
- /(--?[\w-]*(?:token|secret|password|api-key|apikey)[\w-]*[ =])["']?[^\s"']{4,}["']?/gi,
50
- "$1[redacted]"
51
- ],
52
- [/\b(?:sk|pk|rk)-[A-Za-z0-9_-]{16,}/g, "[redacted]"],
53
- [/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})/g, "[redacted]"],
54
- [/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, "[redacted]"],
55
- [/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, "[redacted]"],
56
- [/\bAIza[0-9A-Za-z_-]{30,}/g, "[redacted]"],
57
- [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}/g, "[redacted]"]
58
- ];
59
- var OPAQUE = /[A-Za-z0-9_+=-]{32,}/g;
60
- function redactSecrets(text) {
61
- let out = text;
62
- for (const [pattern, replacement] of SECRETS) out = out.replace(pattern, replacement);
63
- return out.replace(
64
- OPAQUE,
65
- (run2) => /^[0-9a-f-]+$/i.test(run2) || !/\d/.test(run2) || !/[A-Za-z]/.test(run2) ? run2 : "[redacted]"
66
- );
67
- }
68
- function logText(text) {
69
- const flat = redactSecrets(stripControl(text).replace(/\s+/g, " ").trim());
70
- return flat.length > RUN_LOG_LINE_MAX ? `${flat.slice(0, RUN_LOG_LINE_MAX - 1)}\u2026` : flat;
71
- }
72
- function logLineFor(item) {
73
- switch (item.type) {
74
- case "text":
75
- return item.text;
76
- case "tool": {
77
- const input = item.detail ?? item.summary ?? item.target;
78
- return `> ${item.name}${input ? `: ${input}` : ""}`;
79
- }
80
- case "ask":
81
- return `? ${item.summary}`;
82
- case "result":
83
- return item.ok ? `= Result: ${item.text ?? "done"}` : `= Error: ${item.text ?? "no text"}`;
84
- default:
85
- return null;
86
- }
87
- }
88
- function appendRunLog(dir, workId, text, { now = Date.now(), maxBytes = RUN_LOG_MAX_BYTES } = {}) {
89
- const path = runLogPath(dir, workId);
90
- if (!path) return;
91
- const line = `${stamp(now)} ${logText(text)}
92
- `;
93
- mkdirSync(dir, { recursive: true, mode: 448 });
94
- const size = sizeOf(path);
95
- if (size > 0 && size + Buffer.byteLength(line) > maxBytes) renameSync(path, `${path}.1`);
96
- appendFileSync(path, line, { mode: 384 });
97
- }
98
- function pruneRunLogs(dir, now = Date.now(), keepMs = RUN_LOG_KEEP_MS) {
99
- mkdirSync(dir, { recursive: true, mode: 448 });
100
- chmodSync(dir, 448);
101
- let removed = 0;
102
- for (const name of readdirSync(dir)) {
103
- if (!/\.log(\.1)?$/.test(name)) continue;
104
- const path = join(dir, name);
105
- try {
106
- if (statSync(path).mtimeMs < now - keepMs) {
107
- unlinkSync(path);
108
- removed++;
109
- }
110
- } catch {
111
- }
112
- }
113
- return removed;
114
- }
115
- function sizeOf(path) {
116
- try {
117
- return statSync(path).size;
118
- } catch {
119
- return 0;
120
- }
121
- }
122
- var STOPPED_SUMMARY = "The run was stopped.";
123
- function endNote(end) {
124
- return `= ${end.kind === "settled" ? "Done" : "Ended"}: ${end.summary ?? end.kind}`;
125
- }
126
- function isEndLogLine(line) {
127
- return /^\S+ = (Done|Ended): /.test(line);
128
- }
129
- function stamp(now) {
130
- const d = new Date(now);
131
- return [d.getHours(), d.getMinutes(), d.getSeconds()].map((n) => String(n).padStart(2, "0")).join(":");
132
- }
133
-
134
22
  // src/drivers/local.ts
135
23
  import { execFile, execFileSync, spawn } from "child_process";
136
- import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync, renameSync as renameSync2, writeFileSync } from "fs";
24
+ import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
137
25
  import { homedir, hostname } from "os";
138
- import { basename, dirname as dirname2, join as join2 } from "path";
26
+ import { basename, dirname, join } from "path";
139
27
  import { createInterface } from "readline";
28
+ var STOPPED = { kind: "failed", summary: STOPPED_SUMMARY };
29
+ function takeoverSummary(machine) {
30
+ return `You took this over on ${machine}.`;
31
+ }
140
32
  var CONTINUE_PROMPT = "Continue the work from where you stopped. If it is already done, say so in one sentence.";
141
- var PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
142
33
  var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master", "HEAD"]);
143
34
  var COMMANDS_KEPT = 50;
144
35
  var SUMMARY_MAX = 200;
@@ -161,7 +52,7 @@ function failedEnd(harness, run2) {
161
52
  return { summary: `${lead}${quoted}"`, ...error };
162
53
  }
163
54
  function localRunsFilePath() {
164
- return process.env.CLOOP_LOCAL_RUNS_FILE ?? join2(homedir(), CONFIG_DIR, "local-runs.json");
55
+ return process.env.CLOOP_LOCAL_RUNS_FILE ?? join(homedir(), CONFIG_DIR, "local-runs.json");
165
56
  }
166
57
  function pickRepo(repos, repository) {
167
58
  if (!repository) {
@@ -175,9 +66,6 @@ function pickRepo(repos, repository) {
175
66
  if (!found) throw new BoxToolError("no_project");
176
67
  return found;
177
68
  }
178
- function prUrlIn(text) {
179
- return text?.match(PR_URL)?.at(-1) ?? null;
180
- }
181
69
  function run(cmd, args, cwd) {
182
70
  return new Promise(
183
71
  (resolve, reject) => execFile(
@@ -325,7 +213,8 @@ var LocalDriver = class {
325
213
  return {
326
214
  thread_id: a.work_id,
327
215
  resumed: true,
328
- permission: existing.used_permission
216
+ permission: existing.used_permission,
217
+ takeover: true
329
218
  };
330
219
  const { dialect } = this.deps;
331
220
  if (a.harness && !dialect.aliases.includes(a.harness))
@@ -338,7 +227,12 @@ var LocalDriver = class {
338
227
  const head = await this.repo.head(repo.path);
339
228
  const concurrent = this.runs.get(a.work_id);
340
229
  if (concurrent)
341
- return { thread_id: a.work_id, resumed: true, permission: concurrent.used_permission };
230
+ return {
231
+ thread_id: a.work_id,
232
+ resumed: true,
233
+ permission: concurrent.used_permission,
234
+ takeover: true
235
+ };
342
236
  this.refuseBusy(repo.path);
343
237
  const record = {
344
238
  work_id: a.work_id,
@@ -353,7 +247,12 @@ var LocalDriver = class {
353
247
  };
354
248
  this.runs.set(a.work_id, record);
355
249
  this.spawnRun(record, a.prompt, false);
356
- return { thread_id: a.work_id, resumed: false, permission: record.used_permission };
250
+ return {
251
+ thread_id: a.work_id,
252
+ resumed: false,
253
+ permission: record.used_permission,
254
+ takeover: true
255
+ };
357
256
  }
358
257
  async send(a) {
359
258
  const r = this.record(a.thread_id);
@@ -415,7 +314,7 @@ ${a.text}` : a.text;
415
314
  this.log(`${delivered} work=${r.work_id}`);
416
315
  return { delivered };
417
316
  }
418
- async interrupt(id) {
317
+ async interrupt(id, _commandId, stop = STOPPED) {
419
318
  const r = this.record(id);
420
319
  const live = this.lives.get(r.work_id);
421
320
  if (!live) {
@@ -427,20 +326,32 @@ ${a.text}` : a.text;
427
326
  } catch {
428
327
  }
429
328
  }
430
- await this.end(r, { kind: "failed", summary: STOPPED_SUMMARY });
329
+ await this.end(r, stop);
431
330
  return { ok: true, was_running: orphan };
432
331
  }
433
- live.interrupted = true;
332
+ live.interrupted = stop;
434
333
  live.child.kill("SIGINT");
435
- this.note(r, "= Stop requested.");
334
+ this.note(r, stop === STOPPED ? "= Stop requested." : `= ${stop.summary}`);
436
335
  const timer = setTimeout(() => {
437
336
  if (live.child.exitCode === null && live.child.signalCode === null)
438
337
  live.child.kill("SIGTERM");
439
338
  }, this.deps.interruptGraceMs ?? 1e4);
440
339
  timer.unref();
441
- this.log(`interrupt work=${r.work_id}`);
340
+ this.log(`interrupt work=${r.work_id}${stop.error ? ` reason=${stop.error}` : ""}`);
442
341
  return { ok: true, was_running: true };
443
342
  }
343
+ /**
344
+ * `cloop takeover`: stop the run so the owner can open its session in
345
+ * their own terminal. It ends as a stop, with the machine in its words, and
346
+ * never resumes by itself: two processes on one session would fight.
347
+ */
348
+ takeOver(id, machine) {
349
+ return this.interrupt(id, void 0, {
350
+ kind: "failed",
351
+ summary: takeoverSummary(machine),
352
+ error: "taken_over"
353
+ });
354
+ }
444
355
  watch(id, onEvent) {
445
356
  const set = this.listeners.get(id) ?? /* @__PURE__ */ new Set();
446
357
  set.add(onEvent);
@@ -510,7 +421,7 @@ ${a.text}` : a.text;
510
421
  outstanding: 1,
511
422
  asks: [],
512
423
  lastProgressAt: 0,
513
- interrupted: false,
424
+ interrupted: null,
514
425
  stderr: ""
515
426
  };
516
427
  this.lives.set(r.work_id, live);
@@ -577,12 +488,8 @@ ${RESULT_INSTRUCTION}`));
577
488
  }
578
489
  }
579
490
  progress(r, live, line, force) {
580
- const summary = (parseRunResult(line)?.summary ?? line.split("```cloop-result")[0] ?? "").replace(/\s+/g, " ").trim().slice(0, 200);
581
- if (!isProgressSentence(summary)) return;
582
- const now = this.now();
583
- if (!force && now - live.lastProgressAt < (this.deps.progressMs ?? 3e4)) return;
584
- live.lastProgressAt = now;
585
- this.emit(r.work_id, { kind: "progress", summary });
491
+ const summary = nextProgress(live, line, this.now(), this.deps.progressMs, force);
492
+ if (summary) this.emit(r.work_id, { kind: "progress", summary });
586
493
  }
587
494
  async onExit(r, live, code, signal) {
588
495
  if (this.lives.get(r.work_id) === live) this.lives.delete(r.work_id);
@@ -592,7 +499,7 @@ ${RESULT_INSTRUCTION}`));
592
499
  `exit work=${r.work_id} ${exit} result=${live.result ? live.result.ok ? "ok" : "error" : "none"}`
593
500
  );
594
501
  if (live.interrupted) {
595
- await this.end(r, { kind: "failed", summary: STOPPED_SUMMARY });
502
+ await this.end(r, live.interrupted);
596
503
  return;
597
504
  }
598
505
  if (live.next) {
@@ -658,7 +565,7 @@ ${RESULT_INSTRUCTION}`));
658
565
  * work. A run that committed without pushing says so.
659
566
  */
660
567
  async outcome(r, text) {
661
- const named = prUrlIn(text);
568
+ const named = resultPrUrl(text);
662
569
  if (named) return { pr: named };
663
570
  if (!r.head_at_launch) return { pr: null };
664
571
  const head = await this.repo.head(r.repo);
@@ -703,12 +610,12 @@ ${RESULT_INSTRUCTION}`));
703
610
  return readRunRecords(this.file).filter((r) => !(r.end && Date.parse(r.end.at) < cutoff));
704
611
  }
705
612
  save() {
706
- mkdirSync2(dirname2(this.file), { recursive: true, mode: 448 });
613
+ mkdirSync(dirname(this.file), { recursive: true, mode: 448 });
707
614
  const tmp = `${this.file}.tmp`;
708
615
  writeFileSync(tmp, `${JSON.stringify([...this.runs.values()], null, 2)}
709
616
  `, { mode: 384 });
710
- chmodSync2(tmp, 384);
711
- renameSync2(tmp, this.file);
617
+ chmodSync(tmp, 384);
618
+ renameSync(tmp, this.file);
712
619
  }
713
620
  };
714
621
  function readRunRecords(file = localRunsFilePath()) {
@@ -721,15 +628,9 @@ function readRunRecords(file = localRunsFilePath()) {
721
628
  return [];
722
629
  }
723
630
  }
724
- function isProgressSentence(value) {
725
- return typeof value === "string" && /\S[ \t]+\S/.test(value.trim().split(/\r?\n/)[0] ?? "");
726
- }
727
631
 
728
632
  export {
729
- runLogDir,
730
- runLogPath,
731
- STOPPED_SUMMARY,
732
- isEndLogLine,
633
+ takeoverSummary,
733
634
  localRunsFilePath,
734
635
  LocalDriver,
735
636
  readRunRecords
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  ConnectFailure,
4
4
  deviceLogin
5
- } from "./chunk-4XDYJZLF.js";
5
+ } from "./chunk-SANEFNTU.js";
6
6
  import {
7
7
  ApiError,
8
8
  ReauthError,
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/version.ts
4
- var VERSION = true ? "0.2.5" : "0.0.0-dev";
4
+ var VERSION = true ? "0.2.7" : "0.0.0-dev";
5
5
 
6
6
  export {
7
7
  VERSION