@cloop/runner 0.3.38 → 0.3.41
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.
- package/dist/{box-TQJJ6EJK.js → box-G664ZM6O.js} +30 -12
- package/dist/{chunk-3WRLILTX.js → chunk-3XQ44U27.js} +5 -5
- package/dist/{chunk-43OQXKIP.js → chunk-4MMTNAPM.js} +1 -1
- package/dist/{chunk-Z3KDTCS6.js → chunk-ILLDES3M.js} +1 -1
- package/dist/{chunk-WWG6T3HW.js → chunk-LGKSLIU2.js} +1 -1
- package/dist/{chunk-HYYLDJ5K.js → chunk-LMW4JHRH.js} +3 -3
- package/dist/{chunk-PF6QW6CK.js → chunk-NPTLMG3V.js} +1 -1
- package/dist/{chunk-TQ2SCOKH.js → chunk-SDVTQCW7.js} +135 -66
- package/dist/chunk-WIAWWXGP.js +857 -0
- package/dist/{connect-CBWHDE5Y.js → connect-SFAOSHIO.js} +6 -6
- package/dist/{disconnect-POJACA2Q.js → disconnect-ERRRZY25.js} +6 -6
- package/dist/{existing-runner-XOCSW4F4.js → existing-runner-HI4DFKSW.js} +6 -6
- package/dist/index.js +14 -14
- package/dist/{login-JRAQBWSB.js → login-UURPRX5F.js} +2 -2
- package/dist/{mcp-server-N7WRPR77.js → mcp-server-MTDAMQ7C.js} +1 -1
- package/dist/{runner-KFEUMXMY.js → runner-GMHC5FE7.js} +3 -3
- package/dist/{runs-5YIEWOJM.js → runs-XR4MYK4X.js} +2 -2
- package/dist/{statusline-JYOI3SWJ.js → statusline-BV2IXFDB.js} +1 -1
- package/dist/{takeover-S3PBIUN5.js → takeover-H5YOSKV5.js} +4 -4
- package/dist/{use-BLFMGGRV.js → use-6OHXWE5L.js} +6 -6
- package/package.json +1 -1
- package/dist/chunk-OIZI3FXO.js +0 -254
|
@@ -0,0 +1,857 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
RUN_IMAGES_MAX,
|
|
4
|
+
RUN_IMAGE_MAX_BYTES,
|
|
5
|
+
RUN_IMAGE_TYPES,
|
|
6
|
+
RUN_PREVIEWS_MAX,
|
|
7
|
+
RUN_TEXT_MAX,
|
|
8
|
+
boxPath,
|
|
9
|
+
commandFor,
|
|
10
|
+
imageExt,
|
|
11
|
+
runnerPath
|
|
12
|
+
} from "./chunk-SDVTQCW7.js";
|
|
13
|
+
|
|
14
|
+
// src/run-previews.ts
|
|
15
|
+
import { execFile as execFile2, spawn } from "child_process";
|
|
16
|
+
import { createHash as createHash2 } from "crypto";
|
|
17
|
+
import { createWriteStream } from "fs";
|
|
18
|
+
import { mkdir as mkdir2, readFile as readFile3, rm as rm2, writeFile as writeFile2 } from "fs/promises";
|
|
19
|
+
import { basename, join as join3 } from "path";
|
|
20
|
+
|
|
21
|
+
// src/cloudflared.ts
|
|
22
|
+
import { execFile } from "child_process";
|
|
23
|
+
import { createHash } from "crypto";
|
|
24
|
+
import { chmod, mkdir, mkdtemp, readFile, rename, rm, writeFile } from "fs/promises";
|
|
25
|
+
import { homedir, tmpdir } from "os";
|
|
26
|
+
import { join } from "path";
|
|
27
|
+
var CLOUDFLARED_VERSION = "2026.10.7";
|
|
28
|
+
var ASSETS = {
|
|
29
|
+
"darwin-arm64": {
|
|
30
|
+
file: "cloudflared-darwin-arm64.tgz",
|
|
31
|
+
sha256: "3586ccf397e98e5f437e60e7c307ca6ac463e110580503af8bb8e6f9ebf831bd",
|
|
32
|
+
archive: true
|
|
33
|
+
},
|
|
34
|
+
"darwin-x64": {
|
|
35
|
+
file: "cloudflared-darwin-amd64.tgz",
|
|
36
|
+
sha256: "02f3edfd87684dd5b705607688e4eb4b323f6e777b81e7b3a85af556aa356848",
|
|
37
|
+
archive: true
|
|
38
|
+
},
|
|
39
|
+
"linux-x64": {
|
|
40
|
+
file: "cloudflared-linux-amd64",
|
|
41
|
+
sha256: "1f99fb518b83dec2ba8d870a7cc991d82a77e6196295a3d2754ba17ab9f91872",
|
|
42
|
+
archive: false
|
|
43
|
+
},
|
|
44
|
+
"linux-arm64": {
|
|
45
|
+
file: "cloudflared-linux-arm64",
|
|
46
|
+
sha256: "3df43aedc9ff291d1735b5cb576cb97e0b157488796db2e32b28aecabb445775",
|
|
47
|
+
archive: false
|
|
48
|
+
},
|
|
49
|
+
"win32-x64": {
|
|
50
|
+
file: "cloudflared-windows-amd64.exe",
|
|
51
|
+
sha256: "2493dbc168923bb3e59e5e7716f71deced92992eea9acd6e9d74f84ac7751343",
|
|
52
|
+
archive: false
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
function cloudflaredAsset(platform, arch) {
|
|
56
|
+
return ASSETS[`${platform}-${arch}`] ?? null;
|
|
57
|
+
}
|
|
58
|
+
var sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
59
|
+
function cloudflaredPath(home = homedir(), platform = process.platform) {
|
|
60
|
+
return join(
|
|
61
|
+
home,
|
|
62
|
+
".cloop",
|
|
63
|
+
"bin",
|
|
64
|
+
`cloudflared-${CLOUDFLARED_VERSION}${platform === "win32" ? ".exe" : ""}`
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
var IMAGE_CLOUDFLARED = "/usr/local/bin/cloudflared";
|
|
68
|
+
var digestOfFile = (path) => readFile(path).then(sha256, () => null);
|
|
69
|
+
var verified = /* @__PURE__ */ new Map();
|
|
70
|
+
var untarWithTar = (archive, into) => new Promise(
|
|
71
|
+
(done, fail) => execFile(
|
|
72
|
+
"tar",
|
|
73
|
+
["-xzf", archive, "-C", into],
|
|
74
|
+
{ timeout: 6e4 },
|
|
75
|
+
(err) => err ? fail(err) : done()
|
|
76
|
+
)
|
|
77
|
+
);
|
|
78
|
+
async function ensureCloudflared(deps) {
|
|
79
|
+
const platform = deps.platform ?? process.platform;
|
|
80
|
+
const asset = cloudflaredAsset(platform, deps.arch ?? process.arch);
|
|
81
|
+
if (!asset) throw new Error(`no pinned cloudflared for ${platform}-${deps.arch ?? process.arch}`);
|
|
82
|
+
const target = cloudflaredPath(deps.home, platform);
|
|
83
|
+
const known = verified.get(target);
|
|
84
|
+
if (known) return known;
|
|
85
|
+
const ready = await findPinned(target, asset, platform, deps.digestOf ?? digestOfFile);
|
|
86
|
+
if (ready) {
|
|
87
|
+
verified.set(target, ready);
|
|
88
|
+
return ready;
|
|
89
|
+
}
|
|
90
|
+
const url = `https://github.com/cloudflare/cloudflared/releases/download/${CLOUDFLARED_VERSION}/${asset.file}`;
|
|
91
|
+
deps.log(`[runner:preview] installing cloudflared ${CLOUDFLARED_VERSION}`);
|
|
92
|
+
const res = await (deps.fetchFn ?? fetch)(url, {
|
|
93
|
+
redirect: "follow",
|
|
94
|
+
signal: AbortSignal.timeout(12e4)
|
|
95
|
+
});
|
|
96
|
+
if (!res.ok) throw new Error(`cloudflared download answered ${res.status}`);
|
|
97
|
+
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
98
|
+
const got = sha256(bytes);
|
|
99
|
+
if (got !== asset.sha256)
|
|
100
|
+
throw new Error(`cloudflared download did not match its pin (got ${got.slice(0, 12)})`);
|
|
101
|
+
await mkdir(join(target, ".."), { recursive: true });
|
|
102
|
+
const staging = `${target}.new`;
|
|
103
|
+
if (asset.archive) {
|
|
104
|
+
const dir = await mkdtemp(join(tmpdir(), "cloudflared-"));
|
|
105
|
+
try {
|
|
106
|
+
const archive = join(dir, asset.file);
|
|
107
|
+
await writeFile(archive, bytes);
|
|
108
|
+
await (deps.untar ?? untarWithTar)(archive, dir);
|
|
109
|
+
await writeFile(staging, await readFile(join(dir, "cloudflared")));
|
|
110
|
+
} finally {
|
|
111
|
+
await rm(dir, { recursive: true, force: true });
|
|
112
|
+
}
|
|
113
|
+
} else {
|
|
114
|
+
await writeFile(staging, bytes);
|
|
115
|
+
}
|
|
116
|
+
await chmod(staging, 493);
|
|
117
|
+
await rename(staging, target);
|
|
118
|
+
deps.log(`[runner:preview] installed cloudflared ${CLOUDFLARED_VERSION}`);
|
|
119
|
+
verified.set(target, target);
|
|
120
|
+
return target;
|
|
121
|
+
}
|
|
122
|
+
async function findPinned(target, asset, platform, digestOf) {
|
|
123
|
+
const binaryDigest = asset.archive ? null : asset.sha256;
|
|
124
|
+
if (binaryDigest && platform === "linux" && await digestOf(IMAGE_CLOUDFLARED) === binaryDigest)
|
|
125
|
+
return IMAGE_CLOUDFLARED;
|
|
126
|
+
if (binaryDigest) return await digestOf(target) === binaryDigest ? target : null;
|
|
127
|
+
return readFile(target).then(
|
|
128
|
+
() => target,
|
|
129
|
+
() => null
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// src/run-media.ts
|
|
134
|
+
import { readFile as readFile2, stat } from "fs/promises";
|
|
135
|
+
import { homedir as homedir2 } from "os";
|
|
136
|
+
import { isAbsolute, join as join2, resolve } from "path";
|
|
137
|
+
var MEDIA_BUDGET_MS = 3e4;
|
|
138
|
+
function hasImages(result) {
|
|
139
|
+
return Boolean(result?.outputs.some((output) => output.kind === "image"));
|
|
140
|
+
}
|
|
141
|
+
function imageFile(path, cwd) {
|
|
142
|
+
if (isAbsolute(path)) return path;
|
|
143
|
+
if (path === "~" || path.startsWith("~/")) return join2(homedir2(), path.slice(2));
|
|
144
|
+
return cwd ? resolve(cwd, path) : null;
|
|
145
|
+
}
|
|
146
|
+
async function send(workId, file, deps, signal) {
|
|
147
|
+
try {
|
|
148
|
+
if ((await stat(file)).size > RUN_IMAGE_MAX_BYTES) return { media: null, reason: "too_large" };
|
|
149
|
+
const bytes = await readFile2(file, { signal });
|
|
150
|
+
const ext = imageExt(bytes);
|
|
151
|
+
if (!ext) return { media: null, reason: "not_an_image" };
|
|
152
|
+
const res = await (deps.fetchFn ?? fetch)(
|
|
153
|
+
`${deps.origin}/api/agent/runs/${encodeURIComponent(workId)}/media`,
|
|
154
|
+
{
|
|
155
|
+
method: "POST",
|
|
156
|
+
headers: {
|
|
157
|
+
"content-type": RUN_IMAGE_TYPES[ext],
|
|
158
|
+
authorization: `Bearer ${deps.deviceToken()}`
|
|
159
|
+
},
|
|
160
|
+
body: new Uint8Array(bytes),
|
|
161
|
+
signal
|
|
162
|
+
}
|
|
163
|
+
);
|
|
164
|
+
const body = await res.json().catch(() => null);
|
|
165
|
+
if (!res.ok || typeof body?.media !== "string") {
|
|
166
|
+
return {
|
|
167
|
+
media: null,
|
|
168
|
+
reason: `refused_${res.status}${typeof body?.error === "string" ? `_${body.error}` : ""}`
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
return { media: body.media };
|
|
172
|
+
} catch (err) {
|
|
173
|
+
const code = err.code;
|
|
174
|
+
return {
|
|
175
|
+
media: null,
|
|
176
|
+
reason: code === "ENOENT" ? "no_file" : signal.aborted ? "out_of_time" : code ?? (err instanceof Error ? err.name : "error")
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function applyPatches(result, ...patches) {
|
|
181
|
+
return {
|
|
182
|
+
...result,
|
|
183
|
+
outputs: result.outputs.map(
|
|
184
|
+
(output, i) => patches.find((patch) => patch.has(i))?.get(i) ?? output
|
|
185
|
+
)
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
async function imagePatches(workId, result, cwd, deps) {
|
|
189
|
+
const budget = deps.budgetMs ?? MEDIA_BUDGET_MS;
|
|
190
|
+
const clock = new AbortController();
|
|
191
|
+
const timer = setTimeout(() => clock.abort(), budget);
|
|
192
|
+
const outputs = result.outputs.map((output) => {
|
|
193
|
+
if (output.kind !== "image") return output;
|
|
194
|
+
const { media: _unsent, ...image } = output;
|
|
195
|
+
return image;
|
|
196
|
+
});
|
|
197
|
+
const work = (async () => {
|
|
198
|
+
let sent = 0;
|
|
199
|
+
for (const [i, output] of outputs.entries()) {
|
|
200
|
+
if (output.kind !== "image") continue;
|
|
201
|
+
if (sent >= RUN_IMAGES_MAX || clock.signal.aborted) {
|
|
202
|
+
deps.log(
|
|
203
|
+
`[runner:media] not sent work=${workId} reason=${clock.signal.aborted ? "out_of_time" : "too_many"}`
|
|
204
|
+
);
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
const file = imageFile(output.path, cwd);
|
|
208
|
+
const outcome = file ? await send(workId, file, deps, clock.signal) : { media: null, reason: "no_folder" };
|
|
209
|
+
if (outcome.media !== null) {
|
|
210
|
+
outputs[i] = { ...output, media: outcome.media };
|
|
211
|
+
sent++;
|
|
212
|
+
deps.log(`[runner:media] sent work=${workId}`);
|
|
213
|
+
} else deps.log(`[runner:media] not sent work=${workId} reason=${outcome.reason}`);
|
|
214
|
+
}
|
|
215
|
+
})();
|
|
216
|
+
await Promise.race([
|
|
217
|
+
work.catch(() => {
|
|
218
|
+
}),
|
|
219
|
+
new Promise((done) => clock.signal.addEventListener("abort", done))
|
|
220
|
+
]);
|
|
221
|
+
clearTimeout(timer);
|
|
222
|
+
return new Map(
|
|
223
|
+
outputs.flatMap(
|
|
224
|
+
(output, i) => output.kind === "image" ? [[i, output]] : []
|
|
225
|
+
)
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// src/run-previews.ts
|
|
230
|
+
function hasPreviews(result) {
|
|
231
|
+
return Boolean(result?.outputs.some((output) => output.kind === "preview"));
|
|
232
|
+
}
|
|
233
|
+
async function portAnswers(port, path, signal, ms, fetchFn = fetch) {
|
|
234
|
+
for (const host of ["127.0.0.1", "[::1]"]) {
|
|
235
|
+
try {
|
|
236
|
+
const res = await fetchFn(`http://${host}:${port}${path}`, {
|
|
237
|
+
redirect: "manual",
|
|
238
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(ms)])
|
|
239
|
+
});
|
|
240
|
+
await res.body?.cancel();
|
|
241
|
+
return true;
|
|
242
|
+
} catch {
|
|
243
|
+
if (signal.aborted) return false;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return false;
|
|
247
|
+
}
|
|
248
|
+
async function register(workId, output, deps, signal) {
|
|
249
|
+
try {
|
|
250
|
+
const res = await (deps.fetchFn ?? fetch)(
|
|
251
|
+
`${deps.origin}/api/agent/runs/${encodeURIComponent(workId)}/previews`,
|
|
252
|
+
{
|
|
253
|
+
method: "POST",
|
|
254
|
+
headers: {
|
|
255
|
+
"content-type": "application/json",
|
|
256
|
+
authorization: `Bearer ${deps.deviceToken()}`
|
|
257
|
+
},
|
|
258
|
+
body: JSON.stringify({
|
|
259
|
+
title: output.title,
|
|
260
|
+
port: output.port,
|
|
261
|
+
...output.path ? { path: output.path } : {}
|
|
262
|
+
}),
|
|
263
|
+
signal
|
|
264
|
+
}
|
|
265
|
+
);
|
|
266
|
+
const body = await res.json().catch(() => null);
|
|
267
|
+
const until = typeof body?.until === "string" ? Date.parse(body.until) : Number.NaN;
|
|
268
|
+
if (!res.ok || typeof body?.preview !== "string" || typeof body.tunnel?.token !== "string" || Number.isNaN(until)) {
|
|
269
|
+
return {
|
|
270
|
+
preview: null,
|
|
271
|
+
reason: `refused_${res.status}${typeof body?.error === "string" ? `_${body.error}` : ""}`
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
return { preview: body.preview, token: body.tunnel.token, until };
|
|
275
|
+
} catch (err) {
|
|
276
|
+
return {
|
|
277
|
+
preview: null,
|
|
278
|
+
reason: signal.aborted ? "out_of_time" : err instanceof Error ? err.name : "error"
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
async function previewPatches(workId, result, deps) {
|
|
283
|
+
const clock = new AbortController();
|
|
284
|
+
const timer = setTimeout(() => clock.abort(), deps.budgetMs ?? MEDIA_BUDGET_MS);
|
|
285
|
+
const outputs = result.outputs.map((output) => {
|
|
286
|
+
if (output.kind !== "preview") return output;
|
|
287
|
+
const { preview: _unregistered, ...listed } = output;
|
|
288
|
+
return listed;
|
|
289
|
+
});
|
|
290
|
+
let token = null;
|
|
291
|
+
let until = 0;
|
|
292
|
+
const work = (async () => {
|
|
293
|
+
let shared = 0;
|
|
294
|
+
for (const [i, output] of outputs.entries()) {
|
|
295
|
+
if (output.kind !== "preview") continue;
|
|
296
|
+
if (shared >= RUN_PREVIEWS_MAX || clock.signal.aborted) {
|
|
297
|
+
deps.log(
|
|
298
|
+
`[runner:preview] not shared work=${workId} port=${output.port} reason=${clock.signal.aborted ? "out_of_time" : "too_many"}`
|
|
299
|
+
);
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
if (!await portAnswers(
|
|
303
|
+
output.port,
|
|
304
|
+
output.path ?? "/",
|
|
305
|
+
clock.signal,
|
|
306
|
+
deps.probeMs ?? 3e3,
|
|
307
|
+
deps.fetchFn
|
|
308
|
+
)) {
|
|
309
|
+
deps.log(
|
|
310
|
+
`[runner:preview] not shared work=${workId} port=${output.port} reason=port_closed`
|
|
311
|
+
);
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
const done = await register(workId, output, deps, clock.signal);
|
|
315
|
+
if (done.preview === null) {
|
|
316
|
+
deps.log(
|
|
317
|
+
`[runner:preview] not shared work=${workId} port=${output.port} reason=${done.reason}`
|
|
318
|
+
);
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
outputs[i] = { ...output, preview: done.preview };
|
|
322
|
+
token = done.token;
|
|
323
|
+
until = Math.max(until, done.until);
|
|
324
|
+
shared++;
|
|
325
|
+
deps.log(
|
|
326
|
+
`[runner:preview] shared work=${workId} port=${output.port} preview=${done.preview}`
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
})();
|
|
330
|
+
await Promise.race([
|
|
331
|
+
work.catch(() => {
|
|
332
|
+
}),
|
|
333
|
+
new Promise((done) => clock.signal.addEventListener("abort", done))
|
|
334
|
+
]);
|
|
335
|
+
clearTimeout(timer);
|
|
336
|
+
if (token) void deps.connector?.ensure(token, until);
|
|
337
|
+
return new Map(
|
|
338
|
+
outputs.flatMap(
|
|
339
|
+
(output, i) => output.kind === "preview" ? [[i, output]] : []
|
|
340
|
+
)
|
|
341
|
+
);
|
|
342
|
+
}
|
|
343
|
+
function needsAttach(result) {
|
|
344
|
+
return hasImages(result) || hasPreviews(result);
|
|
345
|
+
}
|
|
346
|
+
async function attachRunOutputs(workId, result, cwd, deps) {
|
|
347
|
+
const none = /* @__PURE__ */ new Map();
|
|
348
|
+
const [images, previews] = await Promise.all([
|
|
349
|
+
hasImages(result) ? imagePatches(workId, result, cwd, deps).catch(() => none) : none,
|
|
350
|
+
hasPreviews(result) ? previewPatches(workId, result, deps).catch(() => none) : none
|
|
351
|
+
]);
|
|
352
|
+
return applyPatches(result, images, previews);
|
|
353
|
+
}
|
|
354
|
+
function runOutputs(deps) {
|
|
355
|
+
const connector = new PreviewConnector(deps);
|
|
356
|
+
const shared = {
|
|
357
|
+
origin: deps.origin,
|
|
358
|
+
deviceToken: deps.deviceToken,
|
|
359
|
+
log: deps.log,
|
|
360
|
+
connector,
|
|
361
|
+
...deps.fetchFn ? { fetchFn: deps.fetchFn } : {}
|
|
362
|
+
};
|
|
363
|
+
return {
|
|
364
|
+
connector,
|
|
365
|
+
attach: (workId, result, cwd) => attachRunOutputs(workId, result, cwd, shared)
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
var CONNECTOR_CHECK_MS = 10 * 6e4;
|
|
369
|
+
var LEASE_MAX_MS = 6 * 36e5;
|
|
370
|
+
var RESTART_FIRST_MS = 3e4;
|
|
371
|
+
var RESTART_MAX_MS = 10 * 6e4;
|
|
372
|
+
var STEADY_MS = 10 * 6e4;
|
|
373
|
+
var PIDFILE = "cloudflared.pid";
|
|
374
|
+
function restartDelayMs(crashes) {
|
|
375
|
+
return Math.min(RESTART_FIRST_MS * 2 ** crashes, RESTART_MAX_MS);
|
|
376
|
+
}
|
|
377
|
+
function isCloudflared(name) {
|
|
378
|
+
return basename(name.trim().replace(/\\/g, "/")).toLowerCase().startsWith("cloudflared");
|
|
379
|
+
}
|
|
380
|
+
function processNameOf(pid, platform = process.platform) {
|
|
381
|
+
return new Promise((done) => {
|
|
382
|
+
const [file, args] = platform === "win32" ? ["tasklist", ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"]] : ["ps", ["-p", String(pid), "-o", "comm="]];
|
|
383
|
+
execFile2(file, args, { timeout: 5e3, windowsHide: true }, (err, stdout) => {
|
|
384
|
+
if (err) return done(null);
|
|
385
|
+
const line = stdout.trim().split(/\r?\n/)[0] ?? "";
|
|
386
|
+
const name = platform === "win32" ? /^"([^"]+)"/.exec(line)?.[1] ?? "" : line;
|
|
387
|
+
done(name || null);
|
|
388
|
+
});
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
var PreviewConnector = class {
|
|
392
|
+
constructor(deps) {
|
|
393
|
+
this.deps = deps;
|
|
394
|
+
}
|
|
395
|
+
deps;
|
|
396
|
+
child = null;
|
|
397
|
+
token = null;
|
|
398
|
+
until = 0;
|
|
399
|
+
starting = null;
|
|
400
|
+
check = null;
|
|
401
|
+
stopped = false;
|
|
402
|
+
reaped = null;
|
|
403
|
+
crashes = 0;
|
|
404
|
+
startedAt = 0;
|
|
405
|
+
now() {
|
|
406
|
+
return (this.deps.now ?? Date.now)();
|
|
407
|
+
}
|
|
408
|
+
get pidfile() {
|
|
409
|
+
return join3(this.deps.dir, PIDFILE);
|
|
410
|
+
}
|
|
411
|
+
/** Run the connector with this token until `until` (ms). One already running with the token keeps running. */
|
|
412
|
+
async ensure(token, until) {
|
|
413
|
+
if (this.stopped) return;
|
|
414
|
+
this.until = Math.max(this.until, until);
|
|
415
|
+
await this.hold();
|
|
416
|
+
if (this.child && this.token === token) return;
|
|
417
|
+
if (this.starting) return this.starting;
|
|
418
|
+
this.starting = this.start(token).finally(() => {
|
|
419
|
+
this.starting = null;
|
|
420
|
+
});
|
|
421
|
+
return this.starting;
|
|
422
|
+
}
|
|
423
|
+
/** Once a daemon: stop the connector a dead daemon left behind, named by its pidfile. */
|
|
424
|
+
reap() {
|
|
425
|
+
this.reaped ??= (async () => {
|
|
426
|
+
const pid = Number.parseInt(await readFile3(this.pidfile, "utf8").catch(() => ""), 10);
|
|
427
|
+
if (!Number.isInteger(pid) || pid <= 0) return;
|
|
428
|
+
const name = await (this.deps.processName ?? processNameOf)(pid).catch(() => null);
|
|
429
|
+
if (name && isCloudflared(name)) {
|
|
430
|
+
try {
|
|
431
|
+
(this.deps.killPid ?? ((p) => process.kill(p, "SIGTERM")))(pid);
|
|
432
|
+
this.deps.log(`[runner:preview] stale connector stopped pid=${pid}`);
|
|
433
|
+
} catch (err) {
|
|
434
|
+
this.deps.log(
|
|
435
|
+
`[runner:preview] stale connector not stopped pid=${pid} reason=${err instanceof Error ? err.message : "error"}`
|
|
436
|
+
);
|
|
437
|
+
}
|
|
438
|
+
} else if (name)
|
|
439
|
+
this.deps.log(`[runner:preview] stale pidfile left pid=${pid} is not cloudflared`);
|
|
440
|
+
await rm2(this.pidfile, { force: true }).catch(() => {
|
|
441
|
+
});
|
|
442
|
+
})();
|
|
443
|
+
return this.reaped;
|
|
444
|
+
}
|
|
445
|
+
async start(token) {
|
|
446
|
+
this.kill();
|
|
447
|
+
await this.reap();
|
|
448
|
+
let bin;
|
|
449
|
+
try {
|
|
450
|
+
bin = await (this.deps.binary ?? (() => ensureCloudflared({ log: this.deps.log })))();
|
|
451
|
+
} catch (err) {
|
|
452
|
+
this.deps.log(
|
|
453
|
+
`[runner:preview] connector not started reason=${err instanceof Error ? err.message : "install_failed"}`
|
|
454
|
+
);
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
if (this.stopped) return;
|
|
458
|
+
const cmd = commandFor(bin, ["tunnel", "--no-autoupdate", "--protocol", "http2", "run"]);
|
|
459
|
+
await mkdir2(this.deps.dir, { recursive: true });
|
|
460
|
+
const logFile = createWriteStream(join3(this.deps.dir, "cloudflared.log"), { flags: "a" });
|
|
461
|
+
const child = (this.deps.spawnFn ?? spawn)(cmd.file, cmd.args, {
|
|
462
|
+
env: { ...process.env, TUNNEL_TOKEN: token },
|
|
463
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
464
|
+
windowsHide: true,
|
|
465
|
+
...cmd.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
|
|
466
|
+
});
|
|
467
|
+
child.stdout?.pipe(logFile);
|
|
468
|
+
child.stderr?.pipe(logFile);
|
|
469
|
+
this.child = child;
|
|
470
|
+
this.token = token;
|
|
471
|
+
this.startedAt = this.now();
|
|
472
|
+
if (child.pid) await writeFile2(this.pidfile, String(child.pid)).catch(() => {
|
|
473
|
+
});
|
|
474
|
+
this.deps.log(`[runner:preview] connector started pid=${child.pid ?? "none"}`);
|
|
475
|
+
child.on("exit", (code) => {
|
|
476
|
+
void this.forget(child.pid);
|
|
477
|
+
if (this.child !== child) return;
|
|
478
|
+
this.child = null;
|
|
479
|
+
if (this.now() - this.startedAt >= STEADY_MS) this.crashes = 0;
|
|
480
|
+
const retry = !this.stopped && this.now() < this.until;
|
|
481
|
+
const delay = restartDelayMs(this.crashes);
|
|
482
|
+
this.deps.log(
|
|
483
|
+
`[runner:preview] connector exited code=${code ?? "signal"}${retry ? ` retry_ms=${delay}` : ""}`
|
|
484
|
+
);
|
|
485
|
+
if (!retry) return;
|
|
486
|
+
this.crashes++;
|
|
487
|
+
(this.deps.schedule ?? ((fn, ms) => setTimeout(fn, ms).unref()))(
|
|
488
|
+
() => void this.resume(),
|
|
489
|
+
delay
|
|
490
|
+
);
|
|
491
|
+
});
|
|
492
|
+
if (!this.check) this.check = setInterval(() => void this.resume(), CONNECTOR_CHECK_MS);
|
|
493
|
+
this.check.unref?.();
|
|
494
|
+
}
|
|
495
|
+
/** The pidfile goes with its child; one naming a newer child stays. */
|
|
496
|
+
async forget(pid) {
|
|
497
|
+
if (!pid) return;
|
|
498
|
+
const held = await readFile3(this.pidfile, "utf8").catch(() => null);
|
|
499
|
+
if (held?.trim() === String(pid)) await rm2(this.pidfile, { force: true }).catch(() => {
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Ask the app what to run: on daemon start, on each check, after a crash.
|
|
504
|
+
* A connector that runs says so (`running=1`), and the app answers only
|
|
505
|
+
* whether to keep it and until when, with no token and no Cloudflare call.
|
|
506
|
+
*/
|
|
507
|
+
async resume(asRunning = true) {
|
|
508
|
+
if (this.stopped) return;
|
|
509
|
+
await this.reap();
|
|
510
|
+
const running = asRunning && Boolean(this.child && this.token);
|
|
511
|
+
let answer;
|
|
512
|
+
try {
|
|
513
|
+
const res = await (this.deps.fetchFn ?? fetch)(
|
|
514
|
+
`${this.deps.origin}/api/agent/previews/tunnel${running ? "?running=1" : ""}`,
|
|
515
|
+
{
|
|
516
|
+
headers: { authorization: `Bearer ${this.deps.deviceToken()}` },
|
|
517
|
+
signal: AbortSignal.timeout(15e3)
|
|
518
|
+
}
|
|
519
|
+
);
|
|
520
|
+
if (!res.ok) {
|
|
521
|
+
this.deps.log(`[runner:preview] tunnel ask refused status=${res.status}`);
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
answer = await res.json();
|
|
525
|
+
} catch (err) {
|
|
526
|
+
this.deps.log(
|
|
527
|
+
`[runner:preview] tunnel ask failed reason=${err instanceof Error ? err.name : "error"}`
|
|
528
|
+
);
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
if (!answer.live || !("until" in answer)) {
|
|
532
|
+
if (this.child || this.check)
|
|
533
|
+
this.deps.log("[runner:preview] no live preview; connector stops");
|
|
534
|
+
this.until = 0;
|
|
535
|
+
this.idle();
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
this.until = Date.parse(answer.until);
|
|
539
|
+
if (answer.tunnel) return this.ensure(answer.tunnel.token, this.until);
|
|
540
|
+
if (this.child) return this.hold();
|
|
541
|
+
if (asRunning) return this.resume(false);
|
|
542
|
+
}
|
|
543
|
+
/** The daemon is going: the connector goes with it. */
|
|
544
|
+
stop() {
|
|
545
|
+
this.stopped = true;
|
|
546
|
+
this.idle();
|
|
547
|
+
}
|
|
548
|
+
idle() {
|
|
549
|
+
if (this.check) clearInterval(this.check);
|
|
550
|
+
this.check = null;
|
|
551
|
+
this.kill();
|
|
552
|
+
void this.release();
|
|
553
|
+
}
|
|
554
|
+
kill() {
|
|
555
|
+
const child = this.child;
|
|
556
|
+
this.child = null;
|
|
557
|
+
this.token = null;
|
|
558
|
+
if (!child) return;
|
|
559
|
+
void this.forget(child.pid);
|
|
560
|
+
if (child.exitCode === null) child.kill();
|
|
561
|
+
}
|
|
562
|
+
/** Named after the runner, not the process: a restarted daemon rewrites or removes the same lease. */
|
|
563
|
+
leaseFile() {
|
|
564
|
+
if (!this.deps.awakeDir) return null;
|
|
565
|
+
const runner = createHash2("sha256").update(this.deps.dir).digest("hex").slice(0, 12);
|
|
566
|
+
return join3(this.deps.awakeDir, `cloop-preview-${runner}.json`);
|
|
567
|
+
}
|
|
568
|
+
/** On a Cloop Box, a lease (container/cloop-awake's format) keeps the box up while a preview is live. */
|
|
569
|
+
async hold() {
|
|
570
|
+
const file = this.leaseFile();
|
|
571
|
+
if (!file || !this.deps.awakeDir) return;
|
|
572
|
+
try {
|
|
573
|
+
await mkdir2(this.deps.awakeDir, { recursive: true });
|
|
574
|
+
await writeFile2(
|
|
575
|
+
file,
|
|
576
|
+
JSON.stringify({
|
|
577
|
+
label: "live preview",
|
|
578
|
+
until: Math.min(this.until, this.now() + LEASE_MAX_MS)
|
|
579
|
+
})
|
|
580
|
+
);
|
|
581
|
+
} catch (err) {
|
|
582
|
+
this.deps.log(
|
|
583
|
+
`[runner:preview] awake lease not written reason=${err instanceof Error ? err.message : "error"}`
|
|
584
|
+
);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
async release() {
|
|
588
|
+
const file = this.leaseFile();
|
|
589
|
+
if (file) await rm2(file, { force: true }).catch(() => {
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
};
|
|
593
|
+
|
|
594
|
+
// src/box-watch.ts
|
|
595
|
+
import { randomUUID } from "crypto";
|
|
596
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "fs";
|
|
597
|
+
import { dirname, join as join4 } from "path";
|
|
598
|
+
var KEEP_MS = 7 * 24 * 36e5;
|
|
599
|
+
function threadsFilePath(env) {
|
|
600
|
+
return runnerPath(
|
|
601
|
+
env,
|
|
602
|
+
process.env.CLOOP_BOX_THREADS_FILE,
|
|
603
|
+
(dir) => join4(dir, "box-threads.json")
|
|
604
|
+
);
|
|
605
|
+
}
|
|
606
|
+
function hostedThreadsFilePath(harness) {
|
|
607
|
+
return join4(dirname(boxPath()), `hosted-${harness}`, "box-threads.json");
|
|
608
|
+
}
|
|
609
|
+
function runnerStatePath(env, threadsFile = threadsFilePath(env)) {
|
|
610
|
+
return join4(dirname(threadsFile), "runner-state.json");
|
|
611
|
+
}
|
|
612
|
+
function writeRunnerState(state, path = runnerStatePath()) {
|
|
613
|
+
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
614
|
+
const tmp = `${path}.tmp`;
|
|
615
|
+
writeFileSync(tmp, `${JSON.stringify(state)}
|
|
616
|
+
`, { mode: 384 });
|
|
617
|
+
renameSync(tmp, path);
|
|
618
|
+
}
|
|
619
|
+
function readRunnerState(path = runnerStatePath()) {
|
|
620
|
+
try {
|
|
621
|
+
const raw = JSON.parse(readFileSync(path, "utf-8"));
|
|
622
|
+
return typeof raw.pid === "number" && typeof raw.connected_at === "string" ? { pid: raw.pid, connected_at: raw.connected_at } : null;
|
|
623
|
+
} catch {
|
|
624
|
+
return null;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
function isAlive(pid) {
|
|
628
|
+
try {
|
|
629
|
+
process.kill(pid, 0);
|
|
630
|
+
return true;
|
|
631
|
+
} catch (err) {
|
|
632
|
+
return err.code === "EPERM";
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
function lockThreadsFile(file, pid = process.pid, alive = isAlive) {
|
|
636
|
+
const lock = `${file}.lock`;
|
|
637
|
+
mkdirSync(dirname(lock), { recursive: true, mode: 448 });
|
|
638
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
639
|
+
try {
|
|
640
|
+
writeFileSync(lock, String(pid), { flag: "wx", mode: 384 });
|
|
641
|
+
return {
|
|
642
|
+
ok: true,
|
|
643
|
+
release: () => {
|
|
644
|
+
try {
|
|
645
|
+
if (readFileSync(lock, "utf-8") === String(pid)) unlinkSync(lock);
|
|
646
|
+
} catch {
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
} catch (err) {
|
|
651
|
+
if (err.code !== "EEXIST") throw err;
|
|
652
|
+
let held = 0;
|
|
653
|
+
try {
|
|
654
|
+
held = Number(readFileSync(lock, "utf-8").trim());
|
|
655
|
+
} catch (readErr) {
|
|
656
|
+
if (readErr.code !== "ENOENT") throw readErr;
|
|
657
|
+
continue;
|
|
658
|
+
}
|
|
659
|
+
if (Number.isInteger(held) && held > 0 && held !== pid && alive(held)) {
|
|
660
|
+
return { ok: false, heldBy: held };
|
|
661
|
+
}
|
|
662
|
+
try {
|
|
663
|
+
unlinkSync(lock);
|
|
664
|
+
} catch (unlinkErr) {
|
|
665
|
+
if (unlinkErr.code !== "ENOENT") throw unlinkErr;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
return { ok: false, heldBy: -1 };
|
|
670
|
+
}
|
|
671
|
+
var BoxWatch = class {
|
|
672
|
+
constructor(deps) {
|
|
673
|
+
this.deps = deps;
|
|
674
|
+
this.entries = this.load();
|
|
675
|
+
}
|
|
676
|
+
deps;
|
|
677
|
+
entries;
|
|
678
|
+
live = /* @__PURE__ */ new Map();
|
|
679
|
+
/** Runs whose images are going up; a second end for one waits on the first. */
|
|
680
|
+
attaching = /* @__PURE__ */ new Set();
|
|
681
|
+
stopped = false;
|
|
682
|
+
list() {
|
|
683
|
+
return this.entries;
|
|
684
|
+
}
|
|
685
|
+
start() {
|
|
686
|
+
for (const e of this.entries) if (!e.settled_at) this.watch(e);
|
|
687
|
+
}
|
|
688
|
+
add(workId, threadId, why = "launch") {
|
|
689
|
+
if (this.entries.some((e) => e.work_id === workId)) return;
|
|
690
|
+
const entry = {
|
|
691
|
+
work_id: workId,
|
|
692
|
+
thread_id: threadId,
|
|
693
|
+
launched_at: new Date(this.now()).toISOString()
|
|
694
|
+
};
|
|
695
|
+
this.entries.push(entry);
|
|
696
|
+
this.save();
|
|
697
|
+
this.deps.log(`${why} work=${workId} thread=${threadId}`);
|
|
698
|
+
this.watch(entry);
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* A send the thread took. A settled entry is watched again, so the turn
|
|
702
|
+
* the send started reports its own end. A thread with no entry, one the
|
|
703
|
+
* owner started outside Cloop, is watched from now under the app's
|
|
704
|
+
* `workId`; without one nobody would read its end, so it stays unwatched.
|
|
705
|
+
* A `workId` other than the entry's moves the entry to that row.
|
|
706
|
+
*/
|
|
707
|
+
follow(threadId, workId) {
|
|
708
|
+
const entry = this.entries.find((e) => e.thread_id === threadId);
|
|
709
|
+
if (!entry) {
|
|
710
|
+
if (workId) this.add(workId, threadId, "adopt");
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
if (workId && workId !== entry.work_id) {
|
|
714
|
+
const unwatch = this.live.get(entry.work_id);
|
|
715
|
+
this.live.delete(entry.work_id);
|
|
716
|
+
if (unwatch) this.live.set(workId, unwatch);
|
|
717
|
+
this.deps.log(`rebind thread=${threadId} work=${entry.work_id} to=${workId}`);
|
|
718
|
+
entry.work_id = workId;
|
|
719
|
+
entry.questions = void 0;
|
|
720
|
+
}
|
|
721
|
+
if (entry.settled_at) {
|
|
722
|
+
entry.settled_at = void 0;
|
|
723
|
+
entry.event = void 0;
|
|
724
|
+
entry.sent_at = void 0;
|
|
725
|
+
}
|
|
726
|
+
this.save();
|
|
727
|
+
this.watch(entry);
|
|
728
|
+
}
|
|
729
|
+
/** On every socket open and on a timer: send every event the mesh has not acked. */
|
|
730
|
+
flush() {
|
|
731
|
+
for (const e of this.entries) {
|
|
732
|
+
for (const q of e.questions ?? []) if (!q.sent_at) this.trySend(e, q.event);
|
|
733
|
+
if (e.event && !e.sent_at) this.trySend(e, e.event);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
/** `ok` false: the app refused the event for good (unknown work_id, bad frame), so it is not sent again either. */
|
|
737
|
+
ack(eventId, ok = true) {
|
|
738
|
+
for (const e of this.entries) {
|
|
739
|
+
const held = [...e.questions ?? [], e].find((x) => x.event?.id === eventId && !x.sent_at);
|
|
740
|
+
if (!held) continue;
|
|
741
|
+
held.sent_at = new Date(this.now()).toISOString();
|
|
742
|
+
this.save();
|
|
743
|
+
this.deps.log(
|
|
744
|
+
`event ${ok ? "acked" : "refused by the app"} work=${e.work_id} kind=${held.event?.kind}`
|
|
745
|
+
);
|
|
746
|
+
return;
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
stop() {
|
|
750
|
+
this.stopped = true;
|
|
751
|
+
for (const unwatch of this.live.values()) unwatch();
|
|
752
|
+
this.live.clear();
|
|
753
|
+
}
|
|
754
|
+
now() {
|
|
755
|
+
return this.deps.now?.() ?? Date.now();
|
|
756
|
+
}
|
|
757
|
+
watch(e) {
|
|
758
|
+
if (this.stopped || e.settled_at || this.live.has(e.work_id)) return;
|
|
759
|
+
const unwatch = this.deps.watch(e.thread_id, (event) => this.onEvent(e, event));
|
|
760
|
+
if (e.settled_at) unwatch();
|
|
761
|
+
else this.live.set(e.work_id, unwatch);
|
|
762
|
+
}
|
|
763
|
+
onEvent(e, event) {
|
|
764
|
+
if (e.settled_at) return;
|
|
765
|
+
if (event.kind === "question") this.ask(e, event.question_id, event.summary);
|
|
766
|
+
else if (event.kind === "progress") this.trySend(e, this.frame(e, event));
|
|
767
|
+
else this.finish(e, event);
|
|
768
|
+
}
|
|
769
|
+
frame(e, event) {
|
|
770
|
+
const { kind, summary } = event;
|
|
771
|
+
return {
|
|
772
|
+
type: "event",
|
|
773
|
+
id: randomUUID(),
|
|
774
|
+
work_id: e.work_id,
|
|
775
|
+
thread_id: e.thread_id,
|
|
776
|
+
kind,
|
|
777
|
+
...event.kind === "question" ? { question_id: event.question_id } : {},
|
|
778
|
+
...summary ? { summary: summary.slice(0, RUN_TEXT_MAX) } : {},
|
|
779
|
+
..."result" in event && event.result ? { result: event.result } : {},
|
|
780
|
+
..."pr_url" in event && event.pr_url ? { pr_url: event.pr_url } : {},
|
|
781
|
+
..."error" in event && event.error ? { error: event.error } : {},
|
|
782
|
+
..."harness" in event && event.harness ? { harness: event.harness } : {},
|
|
783
|
+
at: new Date(this.now()).toISOString()
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
ask(e, questionId, summary) {
|
|
787
|
+
if (e.questions?.some((x) => x.event.question_id === questionId)) return;
|
|
788
|
+
const event = this.frame(e, { kind: "question", question_id: questionId, summary });
|
|
789
|
+
e.questions = [...e.questions ?? [], { event }];
|
|
790
|
+
this.save();
|
|
791
|
+
this.deps.log(`question work=${e.work_id} thread=${e.thread_id}`);
|
|
792
|
+
this.trySend(e, event);
|
|
793
|
+
}
|
|
794
|
+
finish(e, end) {
|
|
795
|
+
this.live.get(e.work_id)?.();
|
|
796
|
+
this.live.delete(e.work_id);
|
|
797
|
+
const { attach } = this.deps;
|
|
798
|
+
if (attach && end.kind === "settled" && end.result && needsAttach(end.result)) {
|
|
799
|
+
if (this.attaching.has(e.work_id)) return;
|
|
800
|
+
this.attaching.add(e.work_id);
|
|
801
|
+
const listed = end.result;
|
|
802
|
+
void attach(e.work_id, listed, end.cwd).catch(() => listed).then((result) => {
|
|
803
|
+
this.attaching.delete(e.work_id);
|
|
804
|
+
if (!e.settled_at) this.settle(e, { ...end, result });
|
|
805
|
+
});
|
|
806
|
+
return;
|
|
807
|
+
}
|
|
808
|
+
this.settle(e, end);
|
|
809
|
+
}
|
|
810
|
+
settle(e, end) {
|
|
811
|
+
e.event = this.frame(e, end);
|
|
812
|
+
e.settled_at = e.event.at;
|
|
813
|
+
this.save();
|
|
814
|
+
this.deps.log(
|
|
815
|
+
`settle work=${e.work_id} thread=${e.thread_id} kind=${end.kind} pr=${end.pr_url ? "yes" : "no"}`
|
|
816
|
+
);
|
|
817
|
+
this.trySend(e, e.event);
|
|
818
|
+
}
|
|
819
|
+
trySend(e, event) {
|
|
820
|
+
const sent = this.deps.send(event);
|
|
821
|
+
this.deps.log(
|
|
822
|
+
`event ${sent ? "sent" : "held"} work=${e.work_id} kind=${event.kind}${sent ? "" : "; socket down"}`
|
|
823
|
+
);
|
|
824
|
+
}
|
|
825
|
+
load() {
|
|
826
|
+
let raw;
|
|
827
|
+
try {
|
|
828
|
+
raw = JSON.parse(readFileSync(this.deps.file, "utf-8"));
|
|
829
|
+
} catch {
|
|
830
|
+
return [];
|
|
831
|
+
}
|
|
832
|
+
if (!Array.isArray(raw)) return [];
|
|
833
|
+
const cutoff = this.now() - KEEP_MS;
|
|
834
|
+
return raw.filter(
|
|
835
|
+
(e) => typeof e?.work_id === "string" && typeof e?.thread_id === "string" && !(e.settled_at && Date.parse(e.settled_at) < cutoff)
|
|
836
|
+
);
|
|
837
|
+
}
|
|
838
|
+
save() {
|
|
839
|
+
mkdirSync(dirname(this.deps.file), { recursive: true, mode: 448 });
|
|
840
|
+
const tmp = `${this.deps.file}.tmp`;
|
|
841
|
+
writeFileSync(tmp, `${JSON.stringify(this.entries, null, 2)}
|
|
842
|
+
`, { mode: 384 });
|
|
843
|
+
chmodSync(tmp, 384);
|
|
844
|
+
renameSync(tmp, this.deps.file);
|
|
845
|
+
}
|
|
846
|
+
};
|
|
847
|
+
|
|
848
|
+
export {
|
|
849
|
+
runOutputs,
|
|
850
|
+
threadsFilePath,
|
|
851
|
+
hostedThreadsFilePath,
|
|
852
|
+
runnerStatePath,
|
|
853
|
+
writeRunnerState,
|
|
854
|
+
readRunnerState,
|
|
855
|
+
lockThreadsFile,
|
|
856
|
+
BoxWatch
|
|
857
|
+
};
|