@cloop/runner 0.2.4 → 0.2.6
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-ZUDKJY2F.js → box-Q5AA4S2T.js} +62 -22
- package/dist/{chunk-ZDUKQWKA.js → chunk-2SZUL2B6.js} +1 -1
- package/dist/{chunk-KHYA7GEH.js → chunk-52VJGOLJ.js} +1 -1
- package/dist/{chunk-5J4I7DAE.js → chunk-E3V2PRVS.js} +39 -11
- package/dist/{chunk-PBOQMFNN.js → chunk-GTE4QSTR.js} +1 -1
- package/dist/{chunk-M6U2YVEB.js → chunk-H7ZCXBNW.js} +86 -5
- package/dist/chunk-MWWA2VH7.js +224 -0
- package/dist/{chunk-VEVDJ3H3.js → chunk-SXV4JF5H.js} +258 -294
- package/dist/{runs-ZTLNHRRJ.js → chunk-UEV7ARIT.js} +17 -11
- package/dist/chunk-V4IYJUCC.js +250 -0
- package/dist/{connect-WXL6JWJN.js → connect-FG5VDH5N.js} +26 -5
- package/dist/{disconnect-ZAVMFITZ.js → disconnect-ZV32O475.js} +10 -8
- package/dist/index.js +31 -13
- package/dist/{login-MXIM6VMA.js → login-ZKPZEFCV.js} +2 -2
- package/dist/{mcp-server-ADCSP4SY.js → mcp-server-TINABFRL.js} +1 -1
- package/dist/{runner-OVRZFJIY.js → runner-VY3HK7L4.js} +3 -3
- package/dist/runs-QLO2XZVZ.js +25 -0
- package/dist/{statusline-ESZZVOBJ.js → statusline-BWUUERD5.js} +1 -1
- package/dist/takeover-TKQ5V4KV.js +31 -0
- package/dist/use-ALFEOPLY.js +51 -0
- package/package.json +1 -1
|
@@ -1,42 +1,48 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
serveTakeovers
|
|
4
|
+
} from "./chunk-V4IYJUCC.js";
|
|
5
|
+
import "./chunk-UEV7ARIT.js";
|
|
2
6
|
import {
|
|
3
7
|
LocalDriver
|
|
4
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-E3V2PRVS.js";
|
|
5
9
|
import {
|
|
6
10
|
MeshSocket,
|
|
7
11
|
defaultSocketFactory
|
|
8
12
|
} from "./chunk-ZILLDYL4.js";
|
|
9
13
|
import "./chunk-VK6GV757.js";
|
|
10
14
|
import {
|
|
11
|
-
BoxWatch,
|
|
12
15
|
DEFAULT_FALLBACK_MODEL,
|
|
13
16
|
T3Client,
|
|
14
17
|
claudeDialect,
|
|
15
18
|
codexDialect,
|
|
16
19
|
connectCommand,
|
|
17
|
-
lockThreadsFile,
|
|
18
20
|
mintSession,
|
|
19
21
|
probeClaude,
|
|
20
22
|
probeClaudePermissions,
|
|
21
23
|
probeCodex,
|
|
22
|
-
runBoxTool
|
|
24
|
+
runBoxTool
|
|
25
|
+
} from "./chunk-SXV4JF5H.js";
|
|
26
|
+
import {
|
|
27
|
+
BoxWatch,
|
|
28
|
+
lockThreadsFile,
|
|
23
29
|
threadsFilePath,
|
|
24
30
|
writeRunnerState
|
|
25
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-MWWA2VH7.js";
|
|
26
32
|
import {
|
|
27
33
|
T3Driver,
|
|
28
34
|
isLocal,
|
|
29
35
|
readRunnerConfig,
|
|
30
36
|
writeBoxConfig
|
|
31
|
-
} from "./chunk-
|
|
37
|
+
} from "./chunk-H7ZCXBNW.js";
|
|
32
38
|
import {
|
|
33
39
|
getMachine
|
|
34
40
|
} from "./chunk-JX6VG5FE.js";
|
|
35
41
|
import "./chunk-R3CLO2FB.js";
|
|
36
|
-
import "./chunk-
|
|
37
|
-
import "./chunk-
|
|
42
|
+
import "./chunk-52VJGOLJ.js";
|
|
43
|
+
import "./chunk-2SZUL2B6.js";
|
|
38
44
|
import "./chunk-AG6SI6I2.js";
|
|
39
|
-
import "./chunk-
|
|
45
|
+
import "./chunk-GTE4QSTR.js";
|
|
40
46
|
import {
|
|
41
47
|
getMeshUrl,
|
|
42
48
|
getToken,
|
|
@@ -110,6 +116,7 @@ async function listOutsideSessions(root = join(homedir(), ".claude", "projects")
|
|
|
110
116
|
var BEAT_MS = 6e4;
|
|
111
117
|
var RESEND_MS = 5 * 6e4;
|
|
112
118
|
var REPAIR_BEFORE_MS = 2 * 24 * 36e5;
|
|
119
|
+
var EXPIRING_BEFORE_MS = 3 * 24 * 36e5;
|
|
113
120
|
var out = (line) => console.log(line);
|
|
114
121
|
var red = (s) => `\x1B[31m${s}\x1B[0m`;
|
|
115
122
|
var log = (line) => console.error(`[workstation:daemon] ${line}`);
|
|
@@ -123,6 +130,29 @@ async function awaitNewDeviceToken(current, read, { tries = 3, delayMs = 2e3 } =
|
|
|
123
130
|
}
|
|
124
131
|
return null;
|
|
125
132
|
}
|
|
133
|
+
function t3Presence(cfg, renewalFailed, now = Date.now()) {
|
|
134
|
+
const left = Date.parse(cfg.expiresAt) - now;
|
|
135
|
+
if (Number.isNaN(left)) return null;
|
|
136
|
+
const state = left <= 0 ? "expired" : renewalFailed ? "renewal_failed" : left < EXPIRING_BEFORE_MS ? "expiring" : "ok";
|
|
137
|
+
return { expiresAt: cfg.expiresAt, renewable: Boolean(cfg.t3Bin), state };
|
|
138
|
+
}
|
|
139
|
+
function boxPresence(beat) {
|
|
140
|
+
return {
|
|
141
|
+
session_key: beat.sessionKey,
|
|
142
|
+
name: beat.driver === "t3" ? "Cloop box" : "Cloop runner",
|
|
143
|
+
kind: "workstation",
|
|
144
|
+
capabilities: [...beat.capabilities],
|
|
145
|
+
platform: "workstation",
|
|
146
|
+
machine: beat.machine,
|
|
147
|
+
surface: {
|
|
148
|
+
driver: beat.driver,
|
|
149
|
+
outsideThreads: beat.outsideThreads,
|
|
150
|
+
...beat.t3 ? { t3: beat.t3 } : {}
|
|
151
|
+
},
|
|
152
|
+
status: beat.running > 0 ? "active" : "idle",
|
|
153
|
+
event: beat.running > 0 ? `${beat.running} running` : ""
|
|
154
|
+
};
|
|
155
|
+
}
|
|
126
156
|
async function machineHarnesses(cfg) {
|
|
127
157
|
const [claude, codex] = await Promise.all([
|
|
128
158
|
probeClaude(cfg.driver === "claude-code" ? cfg.bin : void 0),
|
|
@@ -167,7 +197,10 @@ async function run() {
|
|
|
167
197
|
);
|
|
168
198
|
process.exit(1);
|
|
169
199
|
}
|
|
170
|
-
const t3 = {
|
|
200
|
+
const t3 = {
|
|
201
|
+
client: isLocal(cfg) ? null : new T3Client(cfg.t3Url, cfg.token),
|
|
202
|
+
renewalFailed: false
|
|
203
|
+
};
|
|
171
204
|
const machine = getMachine();
|
|
172
205
|
const sessionKey = `box:${machine}`;
|
|
173
206
|
const factory = await defaultSocketFactory();
|
|
@@ -234,6 +267,7 @@ async function run() {
|
|
|
234
267
|
token = fresh;
|
|
235
268
|
cfg = next;
|
|
236
269
|
if (!isLocal(next)) t3.client = new T3Client(next.t3Url, next.token);
|
|
270
|
+
t3.renewalFailed = false;
|
|
237
271
|
socket.restart(fresh);
|
|
238
272
|
return;
|
|
239
273
|
}
|
|
@@ -247,6 +281,7 @@ async function run() {
|
|
|
247
281
|
);
|
|
248
282
|
watch.start();
|
|
249
283
|
setInterval(() => watch.flush(), RESEND_MS).unref();
|
|
284
|
+
if (driver instanceof LocalDriver) serveTakeovers(driver, log);
|
|
250
285
|
const renewT3 = async () => {
|
|
251
286
|
if (!cfg || isLocal(cfg) || Date.parse(cfg.expiresAt) - Date.now() >= REPAIR_BEFORE_MS) return;
|
|
252
287
|
try {
|
|
@@ -256,13 +291,16 @@ async function run() {
|
|
|
256
291
|
// Read from disk: `cloop connect` may have replaced it since.
|
|
257
292
|
deviceToken: disk?.deviceToken ?? cfg.deviceToken,
|
|
258
293
|
showOtherThreads: disk?.showOtherThreads ?? false,
|
|
294
|
+
...disk?.chosenDriver ? { chosenDriver: disk.chosenDriver } : {},
|
|
259
295
|
...disk?.origin ?? cfg.origin ? { origin: disk?.origin ?? cfg.origin } : {}
|
|
260
296
|
};
|
|
261
297
|
cfg = renewed;
|
|
262
298
|
writeBoxConfig(renewed);
|
|
263
299
|
t3.client = new T3Client(renewed.t3Url, renewed.token);
|
|
300
|
+
t3.renewalFailed = false;
|
|
264
301
|
log(`T3 session renewed until ${renewed.expiresAt}`);
|
|
265
302
|
} catch (err) {
|
|
303
|
+
t3.renewalFailed = true;
|
|
266
304
|
log(`T3 session renewal failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
267
305
|
}
|
|
268
306
|
};
|
|
@@ -292,17 +330,17 @@ async function run() {
|
|
|
292
330
|
} catch (err) {
|
|
293
331
|
log(`${driver.name} unreachable: ${err instanceof Error ? err.message : String(err)}`);
|
|
294
332
|
}
|
|
295
|
-
socket.sendPresence(
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
333
|
+
socket.sendPresence(
|
|
334
|
+
boxPresence({
|
|
335
|
+
sessionKey,
|
|
336
|
+
driver: driver.name,
|
|
337
|
+
capabilities: driver.capabilities,
|
|
338
|
+
machine,
|
|
339
|
+
outsideThreads,
|
|
340
|
+
running,
|
|
341
|
+
t3: cfg && !isLocal(cfg) ? t3Presence(cfg, t3.renewalFailed) : null
|
|
342
|
+
})
|
|
343
|
+
);
|
|
306
344
|
};
|
|
307
345
|
void beat();
|
|
308
346
|
setInterval(() => void beat(), BEAT_MS);
|
|
@@ -338,6 +376,8 @@ export {
|
|
|
338
376
|
REFUSED_LINE,
|
|
339
377
|
awaitNewDeviceToken,
|
|
340
378
|
boxCommand,
|
|
379
|
+
boxPresence,
|
|
341
380
|
recordConnected,
|
|
342
|
-
run
|
|
381
|
+
run,
|
|
382
|
+
t3Presence
|
|
343
383
|
};
|
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
RESULT_INSTRUCTION,
|
|
8
8
|
orderThreads,
|
|
9
9
|
parseRunResult
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-H7ZCXBNW.js";
|
|
11
11
|
import {
|
|
12
12
|
CONFIG_DIR
|
|
13
13
|
} from "./chunk-3DIGCVL4.js";
|
|
@@ -137,6 +137,10 @@ import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync, renameS
|
|
|
137
137
|
import { homedir, hostname } from "os";
|
|
138
138
|
import { basename, dirname as dirname2, join as join2 } from "path";
|
|
139
139
|
import { createInterface } from "readline";
|
|
140
|
+
var STOPPED = { kind: "failed", summary: STOPPED_SUMMARY };
|
|
141
|
+
function takeoverSummary(machine) {
|
|
142
|
+
return `You took this over on ${machine}.`;
|
|
143
|
+
}
|
|
140
144
|
var CONTINUE_PROMPT = "Continue the work from where you stopped. If it is already done, say so in one sentence.";
|
|
141
145
|
var PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
|
|
142
146
|
var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master", "HEAD"]);
|
|
@@ -325,7 +329,8 @@ var LocalDriver = class {
|
|
|
325
329
|
return {
|
|
326
330
|
thread_id: a.work_id,
|
|
327
331
|
resumed: true,
|
|
328
|
-
permission: existing.used_permission
|
|
332
|
+
permission: existing.used_permission,
|
|
333
|
+
takeover: true
|
|
329
334
|
};
|
|
330
335
|
const { dialect } = this.deps;
|
|
331
336
|
if (a.harness && !dialect.aliases.includes(a.harness))
|
|
@@ -338,7 +343,12 @@ var LocalDriver = class {
|
|
|
338
343
|
const head = await this.repo.head(repo.path);
|
|
339
344
|
const concurrent = this.runs.get(a.work_id);
|
|
340
345
|
if (concurrent)
|
|
341
|
-
return {
|
|
346
|
+
return {
|
|
347
|
+
thread_id: a.work_id,
|
|
348
|
+
resumed: true,
|
|
349
|
+
permission: concurrent.used_permission,
|
|
350
|
+
takeover: true
|
|
351
|
+
};
|
|
342
352
|
this.refuseBusy(repo.path);
|
|
343
353
|
const record = {
|
|
344
354
|
work_id: a.work_id,
|
|
@@ -353,7 +363,12 @@ var LocalDriver = class {
|
|
|
353
363
|
};
|
|
354
364
|
this.runs.set(a.work_id, record);
|
|
355
365
|
this.spawnRun(record, a.prompt, false);
|
|
356
|
-
return {
|
|
366
|
+
return {
|
|
367
|
+
thread_id: a.work_id,
|
|
368
|
+
resumed: false,
|
|
369
|
+
permission: record.used_permission,
|
|
370
|
+
takeover: true
|
|
371
|
+
};
|
|
357
372
|
}
|
|
358
373
|
async send(a) {
|
|
359
374
|
const r = this.record(a.thread_id);
|
|
@@ -415,7 +430,7 @@ ${a.text}` : a.text;
|
|
|
415
430
|
this.log(`${delivered} work=${r.work_id}`);
|
|
416
431
|
return { delivered };
|
|
417
432
|
}
|
|
418
|
-
async interrupt(id) {
|
|
433
|
+
async interrupt(id, _commandId, stop = STOPPED) {
|
|
419
434
|
const r = this.record(id);
|
|
420
435
|
const live = this.lives.get(r.work_id);
|
|
421
436
|
if (!live) {
|
|
@@ -427,20 +442,32 @@ ${a.text}` : a.text;
|
|
|
427
442
|
} catch {
|
|
428
443
|
}
|
|
429
444
|
}
|
|
430
|
-
await this.end(r,
|
|
445
|
+
await this.end(r, stop);
|
|
431
446
|
return { ok: true, was_running: orphan };
|
|
432
447
|
}
|
|
433
|
-
live.interrupted =
|
|
448
|
+
live.interrupted = stop;
|
|
434
449
|
live.child.kill("SIGINT");
|
|
435
|
-
this.note(r, "= Stop requested.");
|
|
450
|
+
this.note(r, stop === STOPPED ? "= Stop requested." : `= ${stop.summary}`);
|
|
436
451
|
const timer = setTimeout(() => {
|
|
437
452
|
if (live.child.exitCode === null && live.child.signalCode === null)
|
|
438
453
|
live.child.kill("SIGTERM");
|
|
439
454
|
}, this.deps.interruptGraceMs ?? 1e4);
|
|
440
455
|
timer.unref();
|
|
441
|
-
this.log(`interrupt work=${r.work_id}`);
|
|
456
|
+
this.log(`interrupt work=${r.work_id}${stop.error ? ` reason=${stop.error}` : ""}`);
|
|
442
457
|
return { ok: true, was_running: true };
|
|
443
458
|
}
|
|
459
|
+
/**
|
|
460
|
+
* `cloop takeover`: stop the run so the owner can open its session in
|
|
461
|
+
* their own terminal. It ends as a stop, with the machine in its words, and
|
|
462
|
+
* never resumes by itself: two processes on one session would fight.
|
|
463
|
+
*/
|
|
464
|
+
takeOver(id, machine) {
|
|
465
|
+
return this.interrupt(id, void 0, {
|
|
466
|
+
kind: "failed",
|
|
467
|
+
summary: takeoverSummary(machine),
|
|
468
|
+
error: "taken_over"
|
|
469
|
+
});
|
|
470
|
+
}
|
|
444
471
|
watch(id, onEvent) {
|
|
445
472
|
const set = this.listeners.get(id) ?? /* @__PURE__ */ new Set();
|
|
446
473
|
set.add(onEvent);
|
|
@@ -510,7 +537,7 @@ ${a.text}` : a.text;
|
|
|
510
537
|
outstanding: 1,
|
|
511
538
|
asks: [],
|
|
512
539
|
lastProgressAt: 0,
|
|
513
|
-
interrupted:
|
|
540
|
+
interrupted: null,
|
|
514
541
|
stderr: ""
|
|
515
542
|
};
|
|
516
543
|
this.lives.set(r.work_id, live);
|
|
@@ -592,7 +619,7 @@ ${RESULT_INSTRUCTION}`));
|
|
|
592
619
|
`exit work=${r.work_id} ${exit} result=${live.result ? live.result.ok ? "ok" : "error" : "none"}`
|
|
593
620
|
);
|
|
594
621
|
if (live.interrupted) {
|
|
595
|
-
await this.end(r,
|
|
622
|
+
await this.end(r, live.interrupted);
|
|
596
623
|
return;
|
|
597
624
|
}
|
|
598
625
|
if (live.next) {
|
|
@@ -730,6 +757,7 @@ export {
|
|
|
730
757
|
runLogPath,
|
|
731
758
|
STOPPED_SUMMARY,
|
|
732
759
|
isEndLogLine,
|
|
760
|
+
takeoverSummary,
|
|
733
761
|
localRunsFilePath,
|
|
734
762
|
LocalDriver,
|
|
735
763
|
readRunRecords
|
|
@@ -49,6 +49,7 @@ function t3Candidates(serverVersion, sources) {
|
|
|
49
49
|
const ordered = [
|
|
50
50
|
sources.env.T3_BIN,
|
|
51
51
|
join(sources.home, ".t3", "runtime", "versions", serverVersion, "t3"),
|
|
52
|
+
join(sources.env.T3CODE_HOME || join(sources.home, ".t3"), "bin", "t3"),
|
|
52
53
|
...sources.appDirs.flatMap(bundleBinaries),
|
|
53
54
|
...sources.onPath(),
|
|
54
55
|
sources.stored
|
|
@@ -269,8 +270,10 @@ function outcomeOf(p) {
|
|
|
269
270
|
};
|
|
270
271
|
}
|
|
271
272
|
function pickProject(projects, repository) {
|
|
272
|
-
const only = projects.length === 1 ? projects[0] : void 0;
|
|
273
273
|
if (!repository) {
|
|
274
|
+
const repos = projects.filter((p) => p.repositoryIdentity);
|
|
275
|
+
const pool = repos.length > 0 ? repos : projects;
|
|
276
|
+
const only = pool.length === 1 ? pool[0] : void 0;
|
|
274
277
|
if (only) return only;
|
|
275
278
|
throw new BoxToolError("no_project");
|
|
276
279
|
}
|
|
@@ -305,6 +308,45 @@ function orderThreads(threads, limit) {
|
|
|
305
308
|
return [...running, ...rest].slice(0, limit);
|
|
306
309
|
}
|
|
307
310
|
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
311
|
+
function t3ThreadUrl(base, environmentId, threadId) {
|
|
312
|
+
return `${base.replace(/\/+$/, "")}/${encodeURIComponent(environmentId)}/${encodeURIComponent(threadId)}`;
|
|
313
|
+
}
|
|
314
|
+
var LOOPBACK_HOST = /^(127\.0\.0\.1|localhost|\[::1\])$/;
|
|
315
|
+
function isLoopback(url) {
|
|
316
|
+
try {
|
|
317
|
+
return LOOPBACK_HOST.test(new URL(url).hostname);
|
|
318
|
+
} catch {
|
|
319
|
+
return false;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
function tailscaleServed(statusJson, t3Url) {
|
|
323
|
+
let web;
|
|
324
|
+
let port;
|
|
325
|
+
try {
|
|
326
|
+
web = JSON.parse(statusJson).Web ?? {};
|
|
327
|
+
port = new URL(t3Url).port || "80";
|
|
328
|
+
} catch {
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
for (const [hostPort, served] of Object.entries(web)) {
|
|
332
|
+
const proxy = served?.Handlers?.["/"]?.Proxy;
|
|
333
|
+
if (!proxy) continue;
|
|
334
|
+
let target;
|
|
335
|
+
try {
|
|
336
|
+
target = new URL(proxy);
|
|
337
|
+
} catch {
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
if (!LOOPBACK_HOST.test(target.hostname) || (target.port || "80") !== port) continue;
|
|
341
|
+
return hostPort.endsWith(":443") ? `https://${hostPort.slice(0, -4)}` : `https://${hostPort}`;
|
|
342
|
+
}
|
|
343
|
+
return null;
|
|
344
|
+
}
|
|
345
|
+
function reachableBase(t3Url, direct, served) {
|
|
346
|
+
if (!isLoopback(t3Url)) return t3Url;
|
|
347
|
+
const endpoint = direct?.find((e) => e.kind === "tailnet") ?? direct?.find((e) => e.kind === "lan");
|
|
348
|
+
return endpoint?.httpBaseUrl ?? served;
|
|
349
|
+
}
|
|
308
350
|
var T3Driver = class {
|
|
309
351
|
constructor(deps) {
|
|
310
352
|
this.deps = deps;
|
|
@@ -528,10 +570,49 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
|
|
|
528
570
|
return { ok: true, was_running: true };
|
|
529
571
|
}
|
|
530
572
|
async readThread(id) {
|
|
531
|
-
const
|
|
532
|
-
|
|
533
|
-
);
|
|
534
|
-
return { status, settled, pr_url, last_assistant_text };
|
|
573
|
+
const projection = await this.readProjection(id);
|
|
574
|
+
const { status, settled, pr_url, last_assistant_text } = outcomeOf(projection);
|
|
575
|
+
const open = await this.openTarget(id, projection).catch(() => null);
|
|
576
|
+
return { status, settled, pr_url, last_assistant_text, open };
|
|
577
|
+
}
|
|
578
|
+
/** Where the owner opens this thread: the T3 web app's page for it, or its title and project. */
|
|
579
|
+
async openTarget(id, p) {
|
|
580
|
+
const [cfg, shell] = await this.readT3State();
|
|
581
|
+
const listed = shell.threads?.find((t) => t.id === id);
|
|
582
|
+
const title = p.thread.title ?? listed?.title;
|
|
583
|
+
if (!title) return null;
|
|
584
|
+
const base = this.t3.t3Url;
|
|
585
|
+
const projectId = p.thread.projectId;
|
|
586
|
+
const project = shell.projects?.find((x) => x.id === projectId)?.title ?? null;
|
|
587
|
+
const web = base ? reachableBase(base, cfg.directEndpoints, this.servedBase(base)) : null;
|
|
588
|
+
return {
|
|
589
|
+
url: web ? t3ThreadUrl(web, cfg.environment.environmentId, id) : null,
|
|
590
|
+
base,
|
|
591
|
+
title,
|
|
592
|
+
project
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
served = null;
|
|
596
|
+
/** `tailscale serve` changes rarely, and the CLI takes a moment, so its answer is kept 5 minutes. */
|
|
597
|
+
servedBase(t3Url) {
|
|
598
|
+
const kept = this.served;
|
|
599
|
+
if (kept && kept.base === t3Url && Date.now() - kept.at < SESSIONS_TTL_MS) return kept.value;
|
|
600
|
+
let value = null;
|
|
601
|
+
try {
|
|
602
|
+
value = tailscaleServed(
|
|
603
|
+
String(
|
|
604
|
+
(this.deps.exec ?? execFileSync2)("tailscale", ["serve", "status", "--json"], {
|
|
605
|
+
encoding: "utf-8",
|
|
606
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
607
|
+
timeout: 3e3
|
|
608
|
+
})
|
|
609
|
+
),
|
|
610
|
+
t3Url
|
|
611
|
+
);
|
|
612
|
+
} catch {
|
|
613
|
+
}
|
|
614
|
+
this.served = { base: t3Url, value, at: Date.now() };
|
|
615
|
+
return value;
|
|
535
616
|
}
|
|
536
617
|
/**
|
|
537
618
|
* Subscribe to the thread and resubscribe whenever the stream ends. A thread
|
|
@@ -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
|
+
};
|