@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,21 +1,20 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ localRunsFilePath,
4
+ readRunRecords
5
+ } from "./chunk-JFCEKATW.js";
2
6
  import {
3
7
  STOPPED_SUMMARY,
4
8
  isEndLogLine,
5
- localRunsFilePath,
6
- readRunRecords,
9
+ isLocal,
10
+ readRunnerConfig,
7
11
  runLogDir,
8
12
  runLogPath
9
- } from "./chunk-KOOAVO2C.js";
13
+ } from "./chunk-LNQLGVYC.js";
10
14
  import {
11
15
  sanitizeLabel,
12
16
  stripControl
13
17
  } from "./chunk-VK6GV757.js";
14
- import {
15
- isLocal,
16
- readRunnerConfig
17
- } from "./chunk-G6JAEE2Y.js";
18
- import "./chunk-3DIGCVL4.js";
19
18
 
20
19
  // src/commands/runs.ts
21
20
  import { spawnSync } from "child_process";
@@ -46,7 +45,7 @@ function resolved(deps) {
46
45
  function runState(r) {
47
46
  if (!r.end) return "running";
48
47
  if (r.end.kind === "settled") return "done";
49
- return r.end.summary === STOPPED_SUMMARY ? "stopped" : "failed";
48
+ return r.end.summary === STOPPED_SUMMARY || r.end.error === "taken_over" ? "stopped" : "failed";
50
49
  }
51
50
  function recentRuns(records, now) {
52
51
  const since = now - RECENT_MS;
@@ -111,7 +110,9 @@ function runsCommand(deps = {}) {
111
110
  if (last) out(` ${sanitizeLabel(last, 100)}`);
112
111
  }
113
112
  out("");
114
- out("Follow one with: cloop watch <id>. Open a finished one with: cloop resume <id>");
113
+ out(
114
+ "Follow one with: cloop watch <id>. Carry one on here with: cloop takeover <id>. Open a finished one with: cloop resume <id>"
115
+ );
115
116
  return 0;
116
117
  }
117
118
  function endLine(r) {
@@ -133,7 +134,9 @@ async function watchCommand(args, deps = {}) {
133
134
  const path = runLogPath(logDir, run.work_id);
134
135
  out(`Watching "${sanitizeLabel(run.title, 120)}"`);
135
136
  out(`Repository: ${sanitizeLabel(run.repo, 300)}`);
136
- out("Stop it from Threads.");
137
+ out(
138
+ `Stop it from Threads, or carry it on here with: cloop takeover ${run.work_id.slice(0, SHORT)}`
139
+ );
137
140
  out("");
138
141
  const print = (line) => {
139
142
  if (!isEndLogLine(line)) out(stripControl(line));
@@ -230,7 +233,9 @@ async function resumeCommand(args, deps = {}) {
230
233
  if ("run" in found) {
231
234
  const r = found.run;
232
235
  if (!r.end) {
233
- err(`It is still running. Follow it with: cloop watch ${r.work_id.slice(0, SHORT)}`);
236
+ err(
237
+ `It is still running. Follow it with: cloop watch ${r.work_id.slice(0, SHORT)}, or carry it on here with: cloop takeover ${r.work_id.slice(0, SHORT)}`
238
+ );
234
239
  return 1;
235
240
  }
236
241
  if (!existsSync(r.repo)) {
@@ -253,13 +258,14 @@ async function resumeCommand(args, deps = {}) {
253
258
  err(found.error);
254
259
  return 1;
255
260
  }
261
+
256
262
  export {
263
+ runState,
264
+ recentRuns,
257
265
  findRun,
258
266
  lastLines,
259
- recentRuns,
260
- resumeCommand,
261
- runState,
262
267
  runsCommand,
268
+ watchCommand,
263
269
  sessionFolder,
264
- watchCommand
270
+ resumeCommand
265
271
  };
@@ -0,0 +1,224 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ CONFIG_DIR
4
+ } from "./chunk-3DIGCVL4.js";
5
+
6
+ // src/box-watch.ts
7
+ import { randomUUID } from "crypto";
8
+ import { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "fs";
9
+ import { homedir } from "os";
10
+ import { dirname, join } from "path";
11
+ var KEEP_MS = 7 * 24 * 36e5;
12
+ function threadsFilePath() {
13
+ return process.env.CLOOP_BOX_THREADS_FILE ?? join(homedir(), CONFIG_DIR, "box-threads.json");
14
+ }
15
+ function runnerStatePath() {
16
+ return join(dirname(threadsFilePath()), "runner-state.json");
17
+ }
18
+ function writeRunnerState(state, path = runnerStatePath()) {
19
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
20
+ const tmp = `${path}.tmp`;
21
+ writeFileSync(tmp, `${JSON.stringify(state)}
22
+ `, { mode: 384 });
23
+ renameSync(tmp, path);
24
+ }
25
+ function readRunnerState(path = runnerStatePath()) {
26
+ try {
27
+ const raw = JSON.parse(readFileSync(path, "utf-8"));
28
+ return typeof raw.pid === "number" && typeof raw.connected_at === "string" ? { pid: raw.pid, connected_at: raw.connected_at } : null;
29
+ } catch {
30
+ return null;
31
+ }
32
+ }
33
+ function isAlive(pid) {
34
+ try {
35
+ process.kill(pid, 0);
36
+ return true;
37
+ } catch (err) {
38
+ return err.code === "EPERM";
39
+ }
40
+ }
41
+ function lockThreadsFile(file, pid = process.pid, alive = isAlive) {
42
+ const lock = `${file}.lock`;
43
+ mkdirSync(dirname(lock), { recursive: true, mode: 448 });
44
+ for (let attempt = 0; attempt < 2; attempt++) {
45
+ try {
46
+ writeFileSync(lock, String(pid), { flag: "wx", mode: 384 });
47
+ return {
48
+ ok: true,
49
+ release: () => {
50
+ try {
51
+ if (readFileSync(lock, "utf-8") === String(pid)) unlinkSync(lock);
52
+ } catch {
53
+ }
54
+ }
55
+ };
56
+ } catch (err) {
57
+ if (err.code !== "EEXIST") throw err;
58
+ let held = 0;
59
+ try {
60
+ held = Number(readFileSync(lock, "utf-8").trim());
61
+ } catch (readErr) {
62
+ if (readErr.code !== "ENOENT") throw readErr;
63
+ continue;
64
+ }
65
+ if (Number.isInteger(held) && held > 0 && held !== pid && alive(held)) {
66
+ return { ok: false, heldBy: held };
67
+ }
68
+ try {
69
+ unlinkSync(lock);
70
+ } catch (unlinkErr) {
71
+ if (unlinkErr.code !== "ENOENT") throw unlinkErr;
72
+ }
73
+ }
74
+ }
75
+ return { ok: false, heldBy: -1 };
76
+ }
77
+ var BoxWatch = class {
78
+ constructor(deps) {
79
+ this.deps = deps;
80
+ this.entries = this.load();
81
+ }
82
+ deps;
83
+ entries;
84
+ live = /* @__PURE__ */ new Map();
85
+ stopped = false;
86
+ list() {
87
+ return this.entries;
88
+ }
89
+ start() {
90
+ for (const e of this.entries) if (!e.settled_at) this.watch(e);
91
+ }
92
+ add(workId, threadId) {
93
+ if (this.entries.some((e) => e.work_id === workId)) return;
94
+ const entry = {
95
+ work_id: workId,
96
+ thread_id: threadId,
97
+ launched_at: new Date(this.now()).toISOString()
98
+ };
99
+ this.entries.push(entry);
100
+ this.save();
101
+ this.deps.log(`launch work=${workId} thread=${threadId}`);
102
+ this.watch(entry);
103
+ }
104
+ resume(threadId) {
105
+ const entry = this.entries.find((e) => e.thread_id === threadId);
106
+ if (!entry?.settled_at) return;
107
+ entry.settled_at = void 0;
108
+ entry.event = void 0;
109
+ entry.sent_at = void 0;
110
+ this.save();
111
+ this.watch(entry);
112
+ }
113
+ /** On every socket open and on a timer: send every event the mesh has not acked. */
114
+ flush() {
115
+ for (const e of this.entries) {
116
+ for (const q of e.questions ?? []) if (!q.sent_at) this.trySend(e, q.event);
117
+ if (e.event && !e.sent_at) this.trySend(e, e.event);
118
+ }
119
+ }
120
+ /** `ok` false: the app refused the event for good (unknown work_id, bad frame), so it is not sent again either. */
121
+ ack(eventId, ok = true) {
122
+ for (const e of this.entries) {
123
+ const held = [...e.questions ?? [], e].find((x) => x.event?.id === eventId && !x.sent_at);
124
+ if (!held) continue;
125
+ held.sent_at = new Date(this.now()).toISOString();
126
+ this.save();
127
+ this.deps.log(
128
+ `event ${ok ? "acked" : "refused by the app"} work=${e.work_id} kind=${held.event?.kind}`
129
+ );
130
+ return;
131
+ }
132
+ }
133
+ stop() {
134
+ this.stopped = true;
135
+ for (const unwatch of this.live.values()) unwatch();
136
+ this.live.clear();
137
+ }
138
+ now() {
139
+ return this.deps.now?.() ?? Date.now();
140
+ }
141
+ watch(e) {
142
+ if (this.stopped || e.settled_at || this.live.has(e.work_id)) return;
143
+ const unwatch = this.deps.watch(e.thread_id, (event) => this.onEvent(e, event));
144
+ if (e.settled_at) unwatch();
145
+ else this.live.set(e.work_id, unwatch);
146
+ }
147
+ onEvent(e, event) {
148
+ if (e.settled_at) return;
149
+ if (event.kind === "question") this.ask(e, event.question_id, event.summary);
150
+ else if (event.kind === "progress") this.trySend(e, this.frame(e, event));
151
+ else this.finish(e, event);
152
+ }
153
+ frame(e, event) {
154
+ const { kind, summary } = event;
155
+ return {
156
+ type: "event",
157
+ id: randomUUID(),
158
+ work_id: e.work_id,
159
+ thread_id: e.thread_id,
160
+ kind,
161
+ ...event.kind === "question" ? { question_id: event.question_id } : {},
162
+ ...summary ? { summary: summary.slice(0, 500) } : {},
163
+ ..."result" in event && event.result ? { result: event.result } : {},
164
+ ..."pr_url" in event && event.pr_url ? { pr_url: event.pr_url } : {},
165
+ ..."error" in event && event.error ? { error: event.error } : {},
166
+ at: new Date(this.now()).toISOString()
167
+ };
168
+ }
169
+ ask(e, questionId, summary) {
170
+ if (e.questions?.some((x) => x.event.question_id === questionId)) return;
171
+ const event = this.frame(e, { kind: "question", question_id: questionId, summary });
172
+ e.questions = [...e.questions ?? [], { event }];
173
+ this.save();
174
+ this.deps.log(`question work=${e.work_id} thread=${e.thread_id}`);
175
+ this.trySend(e, event);
176
+ }
177
+ finish(e, end) {
178
+ this.live.get(e.work_id)?.();
179
+ this.live.delete(e.work_id);
180
+ e.event = this.frame(e, end);
181
+ e.settled_at = e.event.at;
182
+ this.save();
183
+ this.deps.log(
184
+ `settle work=${e.work_id} thread=${e.thread_id} kind=${end.kind} pr=${end.pr_url ? "yes" : "no"}`
185
+ );
186
+ this.trySend(e, e.event);
187
+ }
188
+ trySend(e, event) {
189
+ const sent = this.deps.send(event);
190
+ this.deps.log(
191
+ `event ${sent ? "sent" : "held"} work=${e.work_id} kind=${event.kind}${sent ? "" : "; socket down"}`
192
+ );
193
+ }
194
+ load() {
195
+ let raw;
196
+ try {
197
+ raw = JSON.parse(readFileSync(this.deps.file, "utf-8"));
198
+ } catch {
199
+ return [];
200
+ }
201
+ if (!Array.isArray(raw)) return [];
202
+ const cutoff = this.now() - KEEP_MS;
203
+ return raw.filter(
204
+ (e) => typeof e?.work_id === "string" && typeof e?.thread_id === "string" && !(e.settled_at && Date.parse(e.settled_at) < cutoff)
205
+ );
206
+ }
207
+ save() {
208
+ mkdirSync(dirname(this.deps.file), { recursive: true, mode: 448 });
209
+ const tmp = `${this.deps.file}.tmp`;
210
+ writeFileSync(tmp, `${JSON.stringify(this.entries, null, 2)}
211
+ `, { mode: 384 });
212
+ chmodSync(tmp, 384);
213
+ renameSync(tmp, this.deps.file);
214
+ }
215
+ };
216
+
217
+ export {
218
+ threadsFilePath,
219
+ runnerStatePath,
220
+ writeRunnerState,
221
+ readRunnerState,
222
+ lockThreadsFile,
223
+ BoxWatch
224
+ };
@@ -5,7 +5,7 @@ import {
5
5
  } from "./chunk-AG6SI6I2.js";
6
6
  import {
7
7
  VERSION
8
- } from "./chunk-BFVL3E2C.js";
8
+ } from "./chunk-KH6FK6UQ.js";
9
9
  import {
10
10
  getOrigin,
11
11
  readCredentials,