@cloop/runner 0.3.23 → 0.3.24

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,1121 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- MeshSocket,
4
- defaultSocketFactory
5
- } from "./chunk-IJH4O27H.js";
6
- import {
7
- serveTakeovers
8
- } from "./chunk-H4WR3GSK.js";
9
- import "./chunk-A5SHBJHU.js";
10
- import {
11
- DEFAULT_FALLBACK_MODEL,
12
- awaitDaemon,
13
- claudeDialect,
14
- cmdWord,
15
- codexDialect,
16
- connectCommand,
17
- findNpx,
18
- installedService,
19
- legacyStagingRunner,
20
- mintSession,
21
- moveLegacyStagingRunner,
22
- moveRunnerFiles,
23
- pinExistingRunner,
24
- probeClaude,
25
- probeClaudePermissions,
26
- probeCodex,
27
- programFor,
28
- psQuote,
29
- runBoxTool,
30
- runSteps,
31
- serviceEnv,
32
- stopService,
33
- systemServices,
34
- unitFor,
35
- which
36
- } from "./chunk-IITOGOV7.js";
37
- import {
38
- BoxWatch,
39
- lockThreadsFile,
40
- readRunnerState,
41
- runnerStatePath,
42
- threadsFilePath,
43
- writeRunnerState
44
- } from "./chunk-Z7WF67JW.js";
45
- import {
46
- BackgroundReading,
47
- HARNESS_STALE_MS,
48
- LocalDriver,
49
- T3Client,
50
- T3Driver,
51
- TOKEN_DAYS,
52
- TOKEN_SCOPE,
53
- TOKEN_TTL_MS,
54
- addTokens,
55
- commandFor,
56
- isLocal,
57
- quotaFromClaude,
58
- quotaFromCodex,
59
- readRunnerConfig,
60
- runnerDir,
61
- runnerEnvironment,
62
- runnerPath,
63
- showsOtherThreads,
64
- sortedDays,
65
- sourceKey,
66
- utcWindow,
67
- windowsPowerShellEnv,
68
- writeBoxConfig
69
- } from "./chunk-TNNAPOD5.js";
70
- import {
71
- getMachine
72
- } from "./chunk-NTXQLEMQ.js";
73
- import "./chunk-VK6GV757.js";
74
- import {
75
- olderThan
76
- } from "./chunk-YEO27QQP.js";
77
- import "./chunk-R3CLO2FB.js";
78
- import "./chunk-OZN4V4GC.js";
79
- import "./chunk-RKR55PPC.js";
80
- import "./chunk-ES5BRAKJ.js";
81
- import {
82
- VERSION
83
- } from "./chunk-BKPSZTPK.js";
84
- import {
85
- getMeshUrl,
86
- getToken,
87
- readCredentials
88
- } from "./chunk-D5UZW42X.js";
89
-
90
- // src/drivers/local-usage.ts
91
- import { spawn } from "child_process";
92
- import { createReadStream } from "fs";
93
- import { readdir, realpath, stat } from "fs/promises";
94
- import { homedir, hostname, tmpdir } from "os";
95
- import { join } from "path";
96
- import { createInterface } from "readline";
97
- var PROBE_TIMEOUT_MS = 1e4;
98
- var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
99
- var count = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0;
100
- var parse = (line) => {
101
- try {
102
- return JSON.parse(line);
103
- } catch {
104
- return void 0;
105
- }
106
- };
107
- function askHarness(bin, args, requests, answer, timeoutMs = PROBE_TIMEOUT_MS) {
108
- const command = commandFor(bin, args);
109
- return new Promise((resolve, reject) => {
110
- const child = spawn(command.file, command.args, {
111
- cwd: tmpdir(),
112
- stdio: ["pipe", "pipe", "ignore"],
113
- env: process.env,
114
- windowsHide: true,
115
- ...command.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
116
- });
117
- let settled = false;
118
- const finish = (err, value) => {
119
- if (settled) return;
120
- settled = true;
121
- clearTimeout(timer);
122
- child.stdin?.end();
123
- child.kill();
124
- setTimeout(() => {
125
- if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
126
- }, 2e3).unref();
127
- if (err) reject(err);
128
- else resolve(value);
129
- };
130
- const timer = setTimeout(
131
- () => finish(new Error(`no answer in ${timeoutMs / 1e3} s`)),
132
- timeoutMs
133
- );
134
- child.on("error", (err) => finish(err));
135
- child.on("close", () => finish(new Error("it exited before it answered")));
136
- child.stdin?.on("error", () => {
137
- });
138
- createInterface({ input: child.stdout }).on("line", (line) => {
139
- const msg = parse(line);
140
- const value = isObject(msg) ? answer(msg) : void 0;
141
- if (value !== void 0) finish(null, value);
142
- });
143
- child.stdin?.write(requests.map((r) => `${JSON.stringify(r)}
144
- `).join(""));
145
- });
146
- }
147
- var reason = (err) => err?.message ?? "the probe failed";
148
- async function probeClaudeQuota(bin = "claude", timeoutMs = PROBE_TIMEOUT_MS) {
149
- const args = [
150
- "--print",
151
- "--verbose",
152
- "--output-format",
153
- "stream-json",
154
- "--input-format",
155
- "stream-json",
156
- "--settings",
157
- JSON.stringify({ disableAllHooks: true }),
158
- "--strict-mcp-config",
159
- "--no-session-persistence",
160
- "--disable-slash-commands"
161
- ];
162
- const request = (id, request2) => ({
163
- type: "control_request",
164
- request_id: id,
165
- request: request2
166
- });
167
- try {
168
- const response = await askHarness(
169
- bin,
170
- args,
171
- [
172
- request("cloop-init", { subtype: "initialize" }),
173
- request("cloop-usage", { subtype: "get_usage", skip_behaviors: true })
174
- ],
175
- (msg) => {
176
- const r = msg.type === "control_response" ? msg.response : void 0;
177
- return isObject(r) && r.request_id === "cloop-usage" ? r : void 0;
178
- },
179
- timeoutMs
180
- );
181
- return quotaFromClaude(response, (/* @__PURE__ */ new Date()).toISOString());
182
- } catch (err) {
183
- return quotaFromClaude({ subtype: "error", error: reason(err) }, (/* @__PURE__ */ new Date()).toISOString());
184
- }
185
- }
186
- async function probeCodexQuota(bin = "codex", timeoutMs = PROBE_TIMEOUT_MS) {
187
- try {
188
- const answer = await askHarness(
189
- bin,
190
- ["app-server"],
191
- [
192
- {
193
- id: 1,
194
- method: "initialize",
195
- params: { clientInfo: { name: "cloop-runner", version: VERSION } }
196
- },
197
- { method: "initialized" },
198
- { id: 2, method: "account/rateLimits/read" }
199
- ],
200
- (msg) => msg.id === 2 ? msg : void 0,
201
- timeoutMs
202
- );
203
- return quotaFromCodex(answer, (/* @__PURE__ */ new Date()).toISOString());
204
- } catch (err) {
205
- return quotaFromCodex({ error: { message: reason(err) } }, (/* @__PURE__ */ new Date()).toISOString());
206
- }
207
- }
208
- async function listLogs(dir, depth, match, found) {
209
- for (const entry of await readdir(dir, { withFileTypes: true })) {
210
- const path = join(dir, entry.name);
211
- if (entry.isFile() && match(entry.name)) found.files.push(path);
212
- else if (entry.isDirectory() && depth > 1)
213
- await listLogs(path, depth - 1, match, found).catch(() => {
214
- found.skipped++;
215
- });
216
- }
217
- }
218
- async function readLines(file, read) {
219
- let malformed = 0;
220
- let lastBad = false;
221
- const lines = createInterface({
222
- input: createReadStream(file, "utf-8"),
223
- crlfDelay: Number.POSITIVE_INFINITY
224
- });
225
- for await (const line of lines) {
226
- lastBad = !read(line);
227
- if (lastBad) malformed++;
228
- }
229
- return lastBad ? malformed - 1 : malformed;
230
- }
231
- function dayOf(v) {
232
- const ms = typeof v === "string" ? Date.parse(v) : Number.NaN;
233
- return Number.isFinite(ms) ? new Date(ms).toISOString().slice(0, 10) : null;
234
- }
235
- var inWindow = (day, w) => day >= w.sinceDay && day <= w.untilDay;
236
- function claudeReader(window, days) {
237
- const calls = /* @__PURE__ */ new Map();
238
- return {
239
- read: (line) => {
240
- if (!line.includes('"assistant"')) return true;
241
- const d = parse(line);
242
- if (d === void 0) return false;
243
- if (!isObject(d) || d.type !== "assistant") return true;
244
- const m = d.message;
245
- const u = isObject(m) ? m.usage : void 0;
246
- if (!isObject(m) || !isObject(u) || m.model === "<synthetic>") return true;
247
- const day = dayOf(d.timestamp);
248
- if (!day) return false;
249
- if (!inWindow(day, window)) return true;
250
- const details = isObject(u.output_tokens_details) ? u.output_tokens_details : {};
251
- const call = {
252
- day,
253
- uncached: count(u.input_tokens),
254
- cached: count(u.cache_read_input_tokens),
255
- creation: count(u.cache_creation_input_tokens),
256
- output: count(u.output_tokens),
257
- reasoning: count(details.thinking_tokens),
258
- records: 1
259
- };
260
- if (typeof m.id !== "string") addTokens(days, day, "claude", call);
261
- else {
262
- const key = `${m.id} ${String(d.requestId ?? "")}`;
263
- const seen2 = calls.get(key);
264
- if (!seen2 || call.output >= seen2.output) calls.set(key, call);
265
- }
266
- return true;
267
- },
268
- finish: () => {
269
- for (const call of calls.values()) addTokens(days, call.day, "claude", call);
270
- }
271
- };
272
- }
273
- function codexReader(window, days) {
274
- return () => {
275
- let prev = { input: 0, cached: 0, write: 0, output: 0, reasoning: 0 };
276
- return (line) => {
277
- if (!line.includes('"token_count"')) return true;
278
- const d = parse(line);
279
- if (d === void 0) return false;
280
- const p = isObject(d) ? d.payload : void 0;
281
- if (!isObject(p) || p.type !== "token_count") return true;
282
- if (p.info === null || p.info === void 0) return true;
283
- const t = isObject(p.info) ? p.info.total_token_usage : void 0;
284
- const day = isObject(d) ? dayOf(d.timestamp) : null;
285
- if (!isObject(t) || !day) return false;
286
- const cur = {
287
- input: count(t.input_tokens),
288
- cached: count(t.cached_input_tokens),
289
- write: count(t.cache_write_input_tokens),
290
- output: count(t.output_tokens),
291
- reasoning: count(t.reasoning_output_tokens)
292
- };
293
- if (cur.input + cur.output <= prev.input + prev.output) return true;
294
- const rise = (k) => Math.max(0, cur[k] - prev[k]);
295
- if (inWindow(day, window))
296
- addTokens(days, day, "codex", {
297
- uncached: Math.max(0, rise("input") - rise("cached") - rise("write")),
298
- cached: rise("cached"),
299
- creation: rise("write"),
300
- output: rise("output"),
301
- reasoning: rise("reasoning"),
302
- records: 1
303
- });
304
- prev = cur;
305
- return true;
306
- };
307
- };
308
- }
309
- async function scanSource(source, sinceMs) {
310
- const key = sourceKey([
311
- hostname(),
312
- source.provider,
313
- await realpath(source.home).catch(() => source.home)
314
- ]);
315
- const base = { source_key: key, provider: source.provider };
316
- const found = { files: [], skipped: 0 };
317
- for (const [i, root] of source.roots.entries()) {
318
- try {
319
- await listLogs(root.dir, root.depth, source.match, found);
320
- } catch (err) {
321
- const code = err.code;
322
- if (i > 0 && code === "ENOENT") continue;
323
- const empty = { scanned_files: 0, skipped_files: 0, malformed_records: 0 };
324
- return code === "ENOENT" ? { ...base, status: "missing", ...empty } : {
325
- ...base,
326
- status: "failed",
327
- ...empty,
328
- message: `The log folder could not be read (${code ?? "error"}).`
329
- };
330
- }
331
- }
332
- let scanned = 0;
333
- let skipped = found.skipped;
334
- let malformed = 0;
335
- for (const file of found.files) {
336
- try {
337
- if ((await stat(file)).mtimeMs < sinceMs) continue;
338
- malformed += await readLines(file, source.reader());
339
- scanned++;
340
- } catch {
341
- skipped++;
342
- }
343
- }
344
- return {
345
- ...base,
346
- status: skipped || malformed ? "partial" : "ok",
347
- scanned_files: scanned,
348
- skipped_files: skipped,
349
- malformed_records: malformed
350
- };
351
- }
352
- async function scanTokenUsage(opts = {}) {
353
- const window = utcWindow(opts.now ?? Date.now(), TOKEN_DAYS);
354
- const sinceMs = Date.parse(`${window.sinceDay}T00:00:00Z`);
355
- const days = /* @__PURE__ */ new Map();
356
- const claudeHome = opts.claudeHome ?? (process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"));
357
- const codexHome = opts.codexHome ?? (process.env.CODEX_HOME || join(homedir(), ".codex"));
358
- const claude = claudeReader(window, days);
359
- const sources = [
360
- await scanSource(
361
- {
362
- provider: "claude",
363
- home: claudeHome,
364
- // projects/<project>/<session>.jsonl and projects/<project>/<session>/subagents/agent-*.jsonl
365
- roots: [{ dir: join(claudeHome, "projects"), depth: 4 }],
366
- match: (name) => name.endsWith(".jsonl"),
367
- reader: () => claude.read
368
- },
369
- sinceMs
370
- ),
371
- await scanSource(
372
- {
373
- provider: "codex",
374
- home: codexHome,
375
- roots: [
376
- { dir: join(codexHome, "sessions"), depth: 4 },
377
- { dir: join(codexHome, "archived_sessions"), depth: 1 }
378
- ],
379
- match: (name) => name.startsWith("rollout-") && name.endsWith(".jsonl"),
380
- reader: codexReader(window, days)
381
- },
382
- sinceMs
383
- )
384
- ];
385
- claude.finish();
386
- const partial = sources.some((s) => s.status === "partial" || s.status === "failed");
387
- return {
388
- status: partial ? "partial" : "ok",
389
- scope: TOKEN_SCOPE,
390
- window: { since_day: window.sinceDay, until_day: window.untilDay, time_zone: "UTC" },
391
- read_at: (/* @__PURE__ */ new Date()).toISOString(),
392
- by_day: sortedDays(days),
393
- sources
394
- };
395
- }
396
- var LocalUsage = class {
397
- constructor(deps) {
398
- this.deps = deps;
399
- this.tokens = new BackgroundReading({
400
- ttlMs: TOKEN_TTL_MS,
401
- read: () => this.scan(),
402
- now: deps.now
403
- });
404
- }
405
- deps;
406
- quotas = /* @__PURE__ */ new Map();
407
- tokens;
408
- /** The quota of a signed-in harness, probed at most once per harness check period. */
409
- quota(harness) {
410
- const probe = this.deps.probes[harness];
411
- if (!probe) return { status: "not_reported" };
412
- let reading = this.quotas.get(harness);
413
- if (!reading) {
414
- reading = new BackgroundReading({
415
- ttlMs: HARNESS_STALE_MS,
416
- read: async () => {
417
- const q = await probe();
418
- if (q.status === "probe_failed")
419
- this.deps.log?.(`quota probe failed harness=${harness}: ${q.message ?? ""}`);
420
- return q;
421
- },
422
- now: this.deps.now
423
- });
424
- this.quotas.set(harness, reading);
425
- }
426
- return reading.get();
427
- }
428
- /** Token counts from the last log scan, rescanned at most every TOKEN_TTL_MS. */
429
- tokenUsage() {
430
- return this.tokens.get();
431
- }
432
- async scan() {
433
- const now = this.deps.now ?? Date.now;
434
- const started = now();
435
- try {
436
- const usage = await (this.deps.scan ?? scanTokenUsage)();
437
- this.deps.log?.(`token scan took ${now() - started} ms status=${usage.status}`);
438
- return usage;
439
- } catch (err) {
440
- this.deps.log?.(`token scan failed: ${err?.message}`);
441
- return { status: "unavailable", reason: "The agent logs could not be read" };
442
- }
443
- }
444
- };
445
-
446
- // src/outside-sessions.ts
447
- import { createReadStream as createReadStream2 } from "fs";
448
- import { readdir as readdir2, stat as stat2 } from "fs/promises";
449
- import { homedir as homedir2 } from "os";
450
- import { join as join2 } from "path";
451
- import { createInterface as createInterface2 } from "readline";
452
- var seen = /* @__PURE__ */ new Map();
453
- var UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
454
- async function listOutsideSessions(root = join2(homedir2(), ".claude", "projects"), own = /* @__PURE__ */ new Set(), now = Date.now()) {
455
- const files = [];
456
- for (const project of await readdir2(root, { withFileTypes: true }).catch(() => [])) {
457
- if (!project.isDirectory()) continue;
458
- for (const entry of await readdir2(join2(root, project.name), { withFileTypes: true }).catch(
459
- () => []
460
- )) {
461
- if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
462
- const id = entry.name.slice(0, -6);
463
- if (!UUID.test(id) || own.has(id)) continue;
464
- const path = join2(root, project.name, entry.name);
465
- const info = await stat2(path).catch(() => null);
466
- if (info && info.mtimeMs >= now - 7 * 864e5)
467
- files.push({ id, project: project.name.slice(0, 200), file: path, mtime: info.mtimeMs });
468
- }
469
- }
470
- const results = [];
471
- const newest = files.sort((a, b) => b.mtime - a.mtime).slice(0, 20);
472
- for (const path of seen.keys()) if (!newest.some((file) => file.file === path)) seen.delete(path);
473
- for (const file of newest) {
474
- const known = seen.get(file.file);
475
- let title = known?.mtime === file.mtime ? known.title : void 0;
476
- let cwd = known?.mtime === file.mtime ? known.cwd : void 0;
477
- if (known?.mtime !== file.mtime) {
478
- const stream = createReadStream2(file.file, { encoding: "utf8" });
479
- const lines = createInterface2({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });
480
- try {
481
- for await (const line of lines) {
482
- if (!cwd && line.includes('"cwd"')) {
483
- try {
484
- const record = JSON.parse(line);
485
- if (typeof record.cwd === "string" && record.cwd.startsWith("/") && record.cwd.length <= 500)
486
- cwd = record.cwd;
487
- } catch {
488
- }
489
- }
490
- if (!/^\s*\{\s*"type"\s*:\s*"(?:summary|custom-title|title)"/.test(line)) continue;
491
- try {
492
- const record = JSON.parse(line);
493
- const value = record.type === "summary" ? record.summary : record.type === "custom-title" ? record.customTitle : record.title;
494
- if (typeof value === "string" && value.trim()) title = value.trim().slice(0, 120);
495
- } catch {
496
- }
497
- }
498
- } finally {
499
- lines.close();
500
- stream.destroy();
501
- }
502
- seen.set(file.file, {
503
- mtime: file.mtime,
504
- ...title ? { title } : {},
505
- ...cwd ? { cwd } : {}
506
- });
507
- }
508
- results.push({
509
- id: file.id,
510
- project: file.project,
511
- updatedAt: new Date(file.mtime).toISOString(),
512
- status: "idle",
513
- ...cwd ? { cwd } : {},
514
- ...title ? { title } : {}
515
- });
516
- }
517
- return results;
518
- }
519
-
520
- // src/update.ts
521
- import { execFile, spawn as spawn2 } from "child_process";
522
- import {
523
- closeSync,
524
- mkdirSync,
525
- openSync,
526
- readFileSync,
527
- renameSync,
528
- rmSync,
529
- writeFileSync
530
- } from "fs";
531
- import { homedir as homedir3 } from "os";
532
- import { dirname, join as join3 } from "path";
533
- var REGISTRY_LATEST = "https://registry.npmjs.org/@cloop/runner/latest";
534
- var FIRST_CHECK_MS = 10 * 6e4;
535
- var CHECK_EVERY_MS = 6 * 36e5;
536
- var ADOPT_WAIT_MS = 3e4;
537
- var FETCH_WAIT_MS = 3 * 6e4;
538
- var RELEASE = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
539
- var log = (line) => console.error(`[workstation:update] ${line}`);
540
- function namesVersion(unitText, version) {
541
- const escaped = version.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
542
- return new RegExp(`(?:^|[\\s"'>])@cloop/runner@${escaped}(?=[\\s"'<]|$)`).test(unitText);
543
- }
544
- function updateDecision(input) {
545
- const stay = (why) => ({ kind: "stay", why });
546
- if (!input.latest) return stay("no_latest");
547
- if (!olderThan(input.current, input.latest)) return stay("current");
548
- if (input.latest === input.failed) return stay("failed_before");
549
- if (input.unitText === null || !namesVersion(input.unitText, input.current))
550
- return stay("not_our_service");
551
- if (!input.canDetach) return stay("no_detach");
552
- if (input.running > 0 || input.inFlight > 0) return stay("busy");
553
- return { kind: "hand_over", to: input.latest };
554
- }
555
- async function readLatest(get = fetch) {
556
- try {
557
- const res = await get(REGISTRY_LATEST, { signal: AbortSignal.timeout(5e3) });
558
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
559
- const version = (await res.json()).version;
560
- if (typeof version !== "string" || !RELEASE.test(version))
561
- throw new Error("no release version");
562
- return version;
563
- } catch (err) {
564
- log(`could not read latest from npm: ${err instanceof Error ? err.message : String(err)}`);
565
- return null;
566
- }
567
- }
568
- function updateDir(env) {
569
- return runnerPath(env, process.env.CLOOP_UPDATE_DIR, (dir) => dir);
570
- }
571
- function updateLogPath() {
572
- return join3(updateDir(), "update.log");
573
- }
574
- function statePath(env) {
575
- return join3(updateDir(env), "update.json");
576
- }
577
- function readFailed() {
578
- try {
579
- const failed = JSON.parse(readFileSync(statePath(), "utf-8")).failed;
580
- return typeof failed === "string" ? failed : null;
581
- } catch {
582
- return null;
583
- }
584
- }
585
- function recordFailed(version, env) {
586
- try {
587
- mkdirSync(updateDir(env), { recursive: true, mode: 448 });
588
- const temp = `${statePath(env)}.${process.pid}.tmp`;
589
- writeFileSync(temp, `${JSON.stringify({ failed: version })}
590
- `, { mode: 384 });
591
- renameSync(temp, statePath(env));
592
- } catch (err) {
593
- log(`could not record ${version} as failed: ${err.code ?? err}`);
594
- }
595
- }
596
- function handOverCommand(platform, npx, to, kind, script = adoptScriptPath()) {
597
- if (platform === "win32")
598
- return [
599
- "powershell",
600
- "-NoProfile",
601
- "-NonInteractive",
602
- "-Command",
603
- [
604
- "$ErrorActionPreference = 'Stop'",
605
- `Start-Process -WindowStyle Hidden -FilePath (Join-Path $env:WINDIR 'System32\\conhost.exe') -ArgumentList ('--headless ' + (Join-Path $env:WINDIR 'System32\\cmd.exe') + ' /d /c ' + [char]34 + ${psQuote(script)} + [char]34)`
606
- ].join("; ")
607
- ];
608
- const adopt2 = adoptWords(npx, to, kind);
609
- return platform === "linux" ? ["systemd-run", "--user", "--scope", "--quiet", "--collect", "--", ...adopt2] : adopt2;
610
- }
611
- var adoptWords = (npx, to, kind) => [
612
- npx,
613
- "-y",
614
- `@cloop/runner@${to}`,
615
- "box",
616
- "adopt",
617
- "--from",
618
- VERSION,
619
- "--kind",
620
- kind
621
- ];
622
- function adoptScriptPath() {
623
- return join3(updateDir(), "adopt.cmd");
624
- }
625
- function adoptScript(npx, to, kind, log3) {
626
- return [
627
- "@echo off",
628
- `call ${adoptWords(npx, to, kind).map(cmdWord).join(" ")} >> ${cmdWord(log3)} 2>&1`,
629
- ""
630
- ].join("\r\n");
631
- }
632
- function servicePath(kind, platform) {
633
- return installedService({
634
- platform,
635
- kind,
636
- environment: runnerEnvironment(),
637
- home: homedir3(),
638
- uid: process.getuid?.() ?? 0,
639
- ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
640
- }).path;
641
- }
642
- function readText(path) {
643
- try {
644
- return readFileSync(path, "utf-8");
645
- } catch {
646
- return null;
647
- }
648
- }
649
- function fetchVersion(npx, version) {
650
- const { file, args, windowsVerbatimArguments } = commandFor(npx, [
651
- "-y",
652
- `@cloop/runner@${version}`,
653
- "--help"
654
- ]);
655
- return new Promise((resolve) => {
656
- execFile(
657
- file,
658
- args,
659
- { timeout: FETCH_WAIT_MS, ...windowsVerbatimArguments ? { windowsVerbatimArguments } : {} },
660
- (err) => {
661
- if (err) log(`could not fetch ${version}: ${err.message.split("\n")[0]}`);
662
- resolve(!err);
663
- }
664
- );
665
- });
666
- }
667
- function selfUpdate(kind, platform = process.platform) {
668
- let latest = null;
669
- let handing = false;
670
- let lastWhy = null;
671
- const canDetach = platform === "darwin" || platform === "win32" || platform === "linux" && which("systemd-run") !== null;
672
- const check = async () => {
673
- const read = await readLatest();
674
- if (!read || read === latest || !olderThan(VERSION, read) || read === readFailed()) return;
675
- const npx = findNpx();
676
- if (npx && await fetchVersion(npx, read)) latest = read;
677
- };
678
- setTimeout(() => {
679
- void check();
680
- setInterval(() => void check(), CHECK_EVERY_MS).unref();
681
- }, FIRST_CHECK_MS).unref();
682
- const handOver = (to) => {
683
- const npx = findNpx();
684
- if (!npx) {
685
- log(`npx is not on PATH, so ${to} cannot start`);
686
- recordFailed(to);
687
- return;
688
- }
689
- const [command, ...args] = handOverCommand(platform, npx, to, kind);
690
- let fd;
691
- try {
692
- mkdirSync(updateDir(), { recursive: true, mode: 448 });
693
- if (platform === "win32")
694
- writeFileSync(adoptScriptPath(), adoptScript(npx, to, kind, updateLogPath()));
695
- fd = openSync(updateLogPath(), "a");
696
- } catch (err) {
697
- log(`could not open ${updateLogPath()}: ${err.code ?? err}`);
698
- return;
699
- }
700
- handing = true;
701
- log(`handing over ${VERSION} -> ${to}; its log is ${updateLogPath()}`);
702
- const child = spawn2(
703
- command,
704
- args,
705
- platform === "win32" ? { stdio: "ignore", windowsHide: true, env: windowsPowerShellEnv() } : { detached: true, stdio: ["ignore", fd, fd] }
706
- );
707
- closeSync(fd);
708
- child.unref();
709
- const failed = (why) => {
710
- handing = false;
711
- log(`${to} did not take over (${why}); staying on ${VERSION}`);
712
- recordFailed(to);
713
- };
714
- child.on("error", (err) => failed(err.message));
715
- child.on("exit", (code, signal) => {
716
- if (code !== 0) failed(signal ? `signal ${signal}` : `exit ${code}`);
717
- });
718
- };
719
- return {
720
- beat({ running, inFlight }) {
721
- if (handing) return;
722
- const decision = updateDecision({
723
- current: VERSION,
724
- latest,
725
- unitText: readText(servicePath(kind, platform)),
726
- running,
727
- inFlight,
728
- failed: readFailed(),
729
- canDetach
730
- });
731
- if (decision.kind === "hand_over") {
732
- lastWhy = null;
733
- handOver(decision.to);
734
- return;
735
- }
736
- if (decision.why !== lastWhy && latest) log(`staying on ${VERSION}: ${decision.why}`);
737
- lastWhy = decision.why;
738
- }
739
- };
740
- }
741
- function newDaemon(oldPid, read = readRunnerState) {
742
- const state = read();
743
- return state && state.pid !== oldPid ? state : null;
744
- }
745
- async function adopt(from, kind, { services: given, script = process.argv[1] ?? "cloop", npx = findNpx() } = {}) {
746
- const environment = runnerEnvironment();
747
- const legacy = legacyStagingRunner();
748
- const was = legacy ? "production" : environment;
749
- const oldPid = readRunnerState(runnerStatePath(was))?.pid;
750
- const services = {
751
- ...given ?? systemServices,
752
- awaitUp: given?.awaitUp ?? ((since2) => awaitDaemon(since2, () => newDaemon(oldPid), { timeoutMs: ADOPT_WAIT_MS }))
753
- };
754
- const refuse = (why2) => {
755
- log(`adopt ${from} -> ${VERSION} refused: ${why2}`);
756
- recordFailed(VERSION, was);
757
- return 1;
758
- };
759
- const program = programFor(script, process.execPath, npx, VERSION);
760
- if (typeof program === "string") return refuse(program);
761
- const where = {
762
- platform: services.platform,
763
- kind,
764
- home: homedir3(),
765
- uid: process.getuid?.() ?? 0,
766
- ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
767
- };
768
- const unit = unitFor({ ...where, environment, program, env: serviceEnv() });
769
- const back = legacy ? unitFor({ ...where, environment: was, program, env: {} }) : unit;
770
- const old = readText(back.path);
771
- if (old === null) return refuse(`${back.path} is missing`);
772
- if (!namesVersion(old, from)) return refuse(`${back.path} does not run ${from}`);
773
- const run2 = (command) => void services.run(command);
774
- const since = Date.now();
775
- let why;
776
- try {
777
- if (legacy) await moveLegacyStagingRunner(services);
778
- mkdirSync(dirname(unit.path), { recursive: true });
779
- writeFileSync(unit.path, unit.contents);
780
- await runSteps(unit.start, run2);
781
- if (await services.awaitUp(since)) {
782
- log(`adopt ${from} -> ${VERSION}: up`);
783
- return 0;
784
- }
785
- why = `the new daemon did not reach Cloop within ${ADOPT_WAIT_MS / 1e3} s`;
786
- } catch (err) {
787
- why = err instanceof Error ? err.message : String(err);
788
- }
789
- log(`adopt ${from} -> ${VERSION} failed: ${why}; putting ${from} back`);
790
- try {
791
- if (legacy) {
792
- const added = installedService({ ...where, environment });
793
- if (!await stopService(added, run2)) throw new Error(`${added.path} did not stop`);
794
- rmSync(added.path, { force: true });
795
- moveRunnerFiles(runnerDir(environment), runnerDir(was));
796
- }
797
- recordFailed(VERSION, was);
798
- writeFileSync(back.path, old);
799
- await runSteps(back.start, run2);
800
- } catch (err) {
801
- log(
802
- `ROLLBACK FAILED: could not restart ${from} from ${back.path}: ${err instanceof Error ? err.message : String(err)}. Run cloop connect on this machine.`
803
- );
804
- return 2;
805
- }
806
- log(`${from} is back`);
807
- return 1;
808
- }
809
-
810
- // src/commands/box.ts
811
- var BEAT_MS = 6e4;
812
- var RESEND_MS = 5 * 6e4;
813
- var REPAIR_BEFORE_MS = 2 * 24 * 36e5;
814
- var EXPIRING_BEFORE_MS = 3 * 24 * 36e5;
815
- var out = (line) => console.log(line);
816
- var red = (s) => `\x1B[31m${s}\x1B[0m`;
817
- var log2 = (line) => console.error(`[workstation:daemon] ${line}`);
818
- var REVOKED_CLOSE = 4001;
819
- var REFUSED_LINE = "refused: Cloop no longer accepts this runner. It was disconnected, or its login expired. Run `cloop connect` on it to connect it again.";
820
- async function awaitNewDeviceToken(current, read, { tries = 3, delayMs = 2e3 } = {}) {
821
- for (let i = 0; i < tries; i++) {
822
- const next = read();
823
- if (next && next !== current) return next;
824
- if (i < tries - 1) await new Promise((r) => setTimeout(r, delayMs));
825
- }
826
- return null;
827
- }
828
- function t3Presence(cfg, renewalFailed, now = Date.now()) {
829
- const left = Date.parse(cfg.expiresAt) - now;
830
- if (Number.isNaN(left)) return null;
831
- const state = left <= 0 ? "expired" : renewalFailed ? "renewal_failed" : left < EXPIRING_BEFORE_MS ? "expiring" : "ok";
832
- return { expiresAt: cfg.expiresAt, renewable: Boolean(cfg.t3Bin), state };
833
- }
834
- function boxPresence(beat) {
835
- return {
836
- session_key: beat.sessionKey,
837
- name: beat.driver === "t3" ? "Cloop box" : "Cloop runner",
838
- kind: "workstation",
839
- capabilities: [...beat.capabilities],
840
- platform: "workstation",
841
- machine: beat.machine,
842
- surface: {
843
- driver: beat.driver,
844
- version: VERSION,
845
- outsideThreads: beat.outsideThreads,
846
- otherThreads: beat.otherThreads,
847
- ...beat.t3 ? { t3: beat.t3 } : {}
848
- },
849
- status: beat.running > 0 ? "active" : "idle",
850
- event: beat.running > 0 ? `${beat.running} running` : ""
851
- };
852
- }
853
- async function machineHarnesses(cfg) {
854
- const [claude, codex] = await Promise.all([
855
- probeClaude(cfg.driver === "claude-code" ? cfg.bin : void 0),
856
- probeCodex(cfg.driver === "codex" ? cfg.bin : void 0)
857
- ]);
858
- return [claude, codex].filter((h) => h !== null);
859
- }
860
- async function localDriver(cfg, name) {
861
- const bin = cfg.driver === name ? cfg.bin : void 0;
862
- const claude = async (at) => claudeDialect(
863
- at,
864
- cfg.fallbackModels ?? DEFAULT_FALLBACK_MODEL,
865
- cfg.askEverything,
866
- await probeClaudePermissions(at)
867
- );
868
- const driver = new LocalDriver({
869
- dialect: name === "claude-code" ? await claude(bin) : codexDialect(bin),
870
- fallbackHarness: name === "claude-code" ? codexDialect() : await claude(),
871
- repos: cfg.repos,
872
- label: cfg.label,
873
- harnesses: () => machineHarnesses(cfg),
874
- usage: new LocalUsage({
875
- probes: {
876
- "claude-code": () => probeClaudeQuota(cfg.driver === "claude-code" ? cfg.bin : void 0),
877
- codex: () => probeCodexQuota(cfg.driver === "codex" ? cfg.bin : void 0)
878
- },
879
- log: log2
880
- }),
881
- log: log2
882
- });
883
- driver.warmHarnesses();
884
- return driver;
885
- }
886
- function recordConnected(logLine, write = writeRunnerState) {
887
- try {
888
- write({ pid: process.pid, connected_at: (/* @__PURE__ */ new Date()).toISOString() });
889
- } catch (err) {
890
- logLine(`state write failed: ${err.code ?? "unknown"}`);
891
- }
892
- }
893
- async function run() {
894
- let cfg = readRunnerConfig();
895
- let token = cfg?.deviceToken ?? getToken();
896
- if (!token || !cfg) {
897
- out(
898
- `${red("\u2717")} ${legacyStagingRunner() ? "This staging runner is still in ~/.cloop from before 0.3.9. Run `cloop connect --staging` to move it to ~/.cloop/staging." : "Not connected. Run `cloop connect` first."}`
899
- );
900
- process.exit(1);
901
- }
902
- if (!cfg.deviceToken) {
903
- log2("no runner device on this machine; run `cloop connect` so the Agent can reach it");
904
- }
905
- const name = process.env.CLOOP_DRIVER ?? cfg.driver ?? "t3";
906
- const local = isLocal(cfg) ? cfg : null;
907
- if (name === "t3" === Boolean(local)) {
908
- out(
909
- `${red("\u2717")} This machine is not connected for ${name}. Run \`cloop connect --driver ${name}\` first.`
910
- );
911
- process.exit(1);
912
- }
913
- const t3 = {
914
- client: isLocal(cfg) ? null : new T3Client(cfg.t3Url, cfg.token),
915
- renewalFailed: false
916
- };
917
- const machine = getMachine();
918
- const sessionKey = `box:${machine}`;
919
- const factory = await defaultSocketFactory();
920
- const lock = lockThreadsFile(threadsFilePath());
921
- if (!lock.ok) {
922
- out(`${red("\u2717")} Another \`cloop box run\` is running (pid ${lock.heldBy}). Stop it first.`);
923
- process.exit(1);
924
- }
925
- const driver = local && name !== "t3" ? await localDriver(local, name) : new T3Driver({
926
- client: () => t3.client,
927
- t3Bin: isLocal(cfg) ? null : cfg.t3Bin,
928
- scope: () => cfg && !isLocal(cfg) ? cfg.scope : void 0,
929
- log: log2,
930
- watched: ({ work_id, thread_id }) => {
931
- const e = watch.list().find((x) => work_id ? x.work_id === work_id : x.thread_id === thread_id);
932
- return e && { thread_id: e.thread_id, settled: Boolean(e.settled_at) };
933
- }
934
- });
935
- const watch = new BoxWatch({
936
- file: threadsFilePath(),
937
- watch: (id, onEvent) => driver.watch(id, onEvent),
938
- send: (frame) => socket.send({ ...frame }),
939
- log: log2
940
- });
941
- let inFlight = 0;
942
- let callsStarted = 0;
943
- const onCall = async (frame) => {
944
- const started = Date.now();
945
- inFlight++;
946
- callsStarted++;
947
- try {
948
- const result = await runBoxTool(
949
- {
950
- driver,
951
- onLaunch: (workId, threadId) => watch.add(workId, threadId),
952
- onResume: (threadId) => watch.resume(threadId)
953
- },
954
- frame.tool,
955
- frame.args
956
- );
957
- socket.send({ type: "result", id: frame.id, ...result });
958
- log2(
959
- `call tool=${frame.tool} ok=${result.ok} ms=${Date.now() - started}${result.ok ? "" : ` error=${result.error} detail=${result.detail.slice(0, 300)}`}`
960
- );
961
- } finally {
962
- inFlight--;
963
- }
964
- };
965
- const socket = new MeshSocket({
966
- meshUrl: getMeshUrl(),
967
- token,
968
- sessionKey,
969
- kind: "workstation",
970
- factory,
971
- onMessage: () => {
972
- },
973
- onCall: (frame) => void onCall(frame),
974
- onAck: (of, ok) => watch.ack(of, ok),
975
- onOpen: () => {
976
- log2(`connected to ${getMeshUrl()}`);
977
- recordConnected(log2);
978
- watch.flush();
979
- },
980
- onClose: (code) => log2(
981
- code === REVOKED_CLOSE ? "disconnected by Cloop (revoked), checking" : "disconnected, reconnecting"
982
- ),
983
- onRefused: () => void (async () => {
984
- const fresh = await awaitNewDeviceToken(token ?? "", () => readRunnerConfig()?.deviceToken);
985
- const next = fresh ? readRunnerConfig() : null;
986
- if (fresh && next) {
987
- log2("reconnecting with the device token `cloop connect` just wrote");
988
- token = fresh;
989
- cfg = next;
990
- if (!isLocal(next)) t3.client = new T3Client(next.t3Url, next.token);
991
- t3.renewalFailed = false;
992
- socket.restart(fresh);
993
- return;
994
- }
995
- log2(REFUSED_LINE);
996
- stop(1);
997
- })()
998
- });
999
- socket.start();
1000
- log2(
1001
- `connecting to ${getMeshUrl()} as ${sessionKey} (${readCredentials()?.deviceName ?? machine}) driver=${driver.name}`
1002
- );
1003
- watch.start();
1004
- setInterval(() => watch.flush(), RESEND_MS).unref();
1005
- if (driver instanceof LocalDriver) serveTakeovers(driver, log2);
1006
- const renewT3 = async () => {
1007
- if (!cfg || isLocal(cfg) || Date.parse(cfg.expiresAt) - Date.now() >= REPAIR_BEFORE_MS) return;
1008
- try {
1009
- const disk = readRunnerConfig();
1010
- const renewed = {
1011
- ...await mintSession(cfg.t3Url, { stored: cfg.t3Bin }),
1012
- // Read from disk: `cloop connect` may have replaced it since.
1013
- deviceToken: disk?.deviceToken ?? cfg.deviceToken,
1014
- hideOtherThreads: disk?.hideOtherThreads === true,
1015
- ...disk?.chosenDriver ? { chosenDriver: disk.chosenDriver } : {},
1016
- ...disk?.origin ?? cfg.origin ? { origin: disk?.origin ?? cfg.origin } : {}
1017
- };
1018
- cfg = renewed;
1019
- writeBoxConfig(renewed);
1020
- t3.client = new T3Client(renewed.t3Url, renewed.token);
1021
- t3.renewalFailed = false;
1022
- log2(`T3 session renewed until ${renewed.expiresAt}`);
1023
- } catch (err) {
1024
- t3.renewalFailed = true;
1025
- log2(`T3 session renewal failed: ${err instanceof Error ? err.message : String(err)}`);
1026
- }
1027
- };
1028
- const update = selfUpdate(driver.name === "t3" ? "workstation" : "local");
1029
- const beat = async () => {
1030
- await renewT3();
1031
- const callsBefore = callsStarted;
1032
- let running = 0;
1033
- let outsideThreads = [];
1034
- const shown = showsOtherThreads(readRunnerConfig());
1035
- try {
1036
- const own = shown && driver.name === "claude-code";
1037
- const listed = await driver.listThreads({
1038
- scope: own ? "all" : "unsettled",
1039
- limit: own ? 200 : 1
1040
- });
1041
- running = listed.running;
1042
- if (shown && driver instanceof T3Driver) outsideThreads = await driver.outsideThreads(20);
1043
- if (own)
1044
- outsideThreads = await listOutsideSessions(
1045
- void 0,
1046
- new Set(listed.threads.map((t) => t.id))
1047
- );
1048
- } catch (err) {
1049
- log2(`${driver.name} unreachable: ${err instanceof Error ? err.message : String(err)}`);
1050
- }
1051
- socket.sendPresence(
1052
- boxPresence({
1053
- sessionKey,
1054
- driver: driver.name,
1055
- capabilities: driver.capabilities,
1056
- machine,
1057
- outsideThreads,
1058
- otherThreads: shown,
1059
- running,
1060
- t3: cfg && !isLocal(cfg) ? t3Presence(cfg, t3.renewalFailed) : null
1061
- })
1062
- );
1063
- update.beat({ running, inFlight: inFlight + callsStarted - callsBefore });
1064
- };
1065
- void beat();
1066
- setInterval(() => void beat(), BEAT_MS);
1067
- const stop = (code = 0) => {
1068
- log2("stopping");
1069
- watch.stop();
1070
- if (driver instanceof LocalDriver) driver.stop();
1071
- lock.release();
1072
- socket.close();
1073
- process.exit(code);
1074
- };
1075
- process.on("SIGINT", () => stop());
1076
- process.on("SIGTERM", () => stop());
1077
- await new Promise(() => {
1078
- });
1079
- }
1080
- function flag(argv, name) {
1081
- const i = argv.indexOf(name);
1082
- return i >= 0 ? argv[i + 1] : void 0;
1083
- }
1084
- async function boxCommand(argv) {
1085
- switch (argv[0]) {
1086
- case "connect":
1087
- await connectCommand(["--driver", "t3", ...argv.slice(1)]);
1088
- break;
1089
- case "run":
1090
- pinExistingRunner();
1091
- await run();
1092
- break;
1093
- case "adopt": {
1094
- const from = flag(argv, "--from");
1095
- const kind = flag(argv, "--kind");
1096
- if (!from || kind !== "workstation" && kind !== "local") {
1097
- console.error("Usage: cloop box adopt --from <version> --kind workstation|local");
1098
- process.exit(1);
1099
- }
1100
- pinExistingRunner();
1101
- process.exit(await adopt(from, kind));
1102
- break;
1103
- }
1104
- default:
1105
- console.error(
1106
- "Usage: cloop box connect [--t3-url <url>] [--t3-bin <path>] [--no-service] | cloop box run"
1107
- );
1108
- process.exit(1);
1109
- }
1110
- }
1111
- export {
1112
- REFUSED_LINE,
1113
- awaitNewDeviceToken,
1114
- boxCommand,
1115
- boxPresence,
1116
- localDriver,
1117
- machineHarnesses,
1118
- recordConnected,
1119
- run,
1120
- t3Presence
1121
- };