@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.
@@ -0,0 +1,2583 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ MeshSocket,
4
+ defaultSocketFactory
5
+ } from "./chunk-IJH4O27H.js";
6
+ import {
7
+ serveTakeovers
8
+ } from "./chunk-MHKSBXUD.js";
9
+ import "./chunk-F4UQ2H5F.js";
10
+ import {
11
+ DEFAULT_FALLBACK_MODEL,
12
+ SUBSCRIPTIONS,
13
+ awaitDaemon,
14
+ claudeDialect,
15
+ cmdWord,
16
+ codexDialect,
17
+ connectCommand,
18
+ findNpx,
19
+ installedService,
20
+ legacyStagingRunner,
21
+ mintSession,
22
+ moveLegacyStagingRunner,
23
+ moveRunnerFiles,
24
+ pinExistingRunner,
25
+ probeClaude,
26
+ probeClaudePermissions,
27
+ probeCodex,
28
+ programFor,
29
+ psQuote,
30
+ runBoxTool,
31
+ runSteps,
32
+ serviceEnv,
33
+ stopService,
34
+ systemServices,
35
+ unitFor,
36
+ which
37
+ } from "./chunk-PQPWITU3.js";
38
+ import {
39
+ BoxWatch,
40
+ hostedThreadsFilePath,
41
+ lockThreadsFile,
42
+ readRunnerState,
43
+ runnerStatePath,
44
+ threadsFilePath,
45
+ writeRunnerState
46
+ } from "./chunk-6F2ZM5H3.js";
47
+ import {
48
+ BackgroundReading,
49
+ BoxToolError,
50
+ HARNESS_LIMIT,
51
+ HARNESS_STALE_MS,
52
+ LocalDriver,
53
+ RESULT_INSTRUCTION,
54
+ RUN_TEXT_MAX,
55
+ STOPPED_SUMMARY,
56
+ T3Client,
57
+ T3Driver,
58
+ TOKEN_DAYS,
59
+ TOKEN_SCOPE,
60
+ TOKEN_TTL_MS,
61
+ addTokens,
62
+ commandFor,
63
+ failedEnd,
64
+ isHosted,
65
+ isLocal,
66
+ isT3,
67
+ nextProgress,
68
+ orderThreads,
69
+ quotaFromClaude,
70
+ quotaFromCodex,
71
+ readRunResult,
72
+ readRunnerConfig,
73
+ resultPrUrl,
74
+ runnerDir,
75
+ runnerEnvironment,
76
+ runnerPath,
77
+ showsOtherThreads,
78
+ sortedDays,
79
+ sourceKey,
80
+ utcWindow,
81
+ windowsPowerShellEnv,
82
+ writeBoxConfig
83
+ } from "./chunk-NVESLEXA.js";
84
+ import {
85
+ getMachine
86
+ } from "./chunk-NTXQLEMQ.js";
87
+ import "./chunk-VK6GV757.js";
88
+ import {
89
+ olderThan
90
+ } from "./chunk-YEO27QQP.js";
91
+ import "./chunk-R3CLO2FB.js";
92
+ import "./chunk-IXG4H623.js";
93
+ import "./chunk-UVB722OW.js";
94
+ import "./chunk-ES5BRAKJ.js";
95
+ import {
96
+ VERSION
97
+ } from "./chunk-VH7XVQFJ.js";
98
+ import {
99
+ getMeshUrl,
100
+ getOrigin,
101
+ getToken,
102
+ pinRunnerEnvironment,
103
+ readCredentials
104
+ } from "./chunk-D5UZW42X.js";
105
+
106
+ // src/cloudroom-core.ts
107
+ var CoreError = class extends Error {
108
+ constructor(status, code, message) {
109
+ super(message);
110
+ this.status = status;
111
+ this.code = code;
112
+ this.name = "CoreError";
113
+ }
114
+ status;
115
+ code;
116
+ };
117
+ var MESSAGE_ITEMS = /* @__PURE__ */ new Set(["text", "agentMessage"]);
118
+ var obj = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
119
+ var str = (v) => typeof v === "string" ? v : null;
120
+ var num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
121
+ function parseReceipt(raw) {
122
+ const r = obj(raw);
123
+ const request_id = str(r.request_id);
124
+ const command = str(r.command);
125
+ const state = str(r.state);
126
+ return request_id && command && state ? {
127
+ request_id,
128
+ command,
129
+ state,
130
+ error: str(r.error),
131
+ target: str(obj(r.input).target_request_id)
132
+ } : null;
133
+ }
134
+ function parseRecord(raw) {
135
+ const r = obj(raw);
136
+ const sequence = num(r.sequence);
137
+ if (sequence === null) return null;
138
+ const data = obj(r.data);
139
+ const request = str(data.request_id);
140
+ const item = str(data.item_id) ?? "";
141
+ switch (r.kind) {
142
+ case "receipt": {
143
+ const receipt = parseReceipt(data);
144
+ return receipt ? { sequence, kind: "receipt", receipt } : { sequence, kind: "other" };
145
+ }
146
+ case "state": {
147
+ const state = str(data.state);
148
+ return state ? { sequence, kind: "state", state } : { sequence, kind: "other" };
149
+ }
150
+ case "text_delta": {
151
+ const delta = str(data.delta);
152
+ return delta !== null ? { sequence, kind: "text", request, item, delta } : { sequence, kind: "other" };
153
+ }
154
+ case "item_completed": {
155
+ const text = str(data.text);
156
+ return text !== null && MESSAGE_ITEMS.has(str(data.item_type) ?? "") ? { sequence, kind: "message", request, item, text } : { sequence, kind: "other" };
157
+ }
158
+ case "usage_limited":
159
+ return { sequence, kind: "usage_limited" };
160
+ case "child_request":
161
+ return { sequence, kind: "child_request", child: str(data.id) };
162
+ default:
163
+ return { sequence, kind: "other" };
164
+ }
165
+ }
166
+ function parseSummary(raw) {
167
+ const s = obj(raw);
168
+ const session_id = str(s.session_id);
169
+ if (!session_id) return null;
170
+ return {
171
+ session_id,
172
+ harness: str(s.harness) ?? "",
173
+ state: str(s.state) ?? "",
174
+ workspace: str(obj(s.workspace).id),
175
+ workspace_path: str(obj(s.workspace).path),
176
+ parent_session: str(s.parent_session),
177
+ current_request: str(s.current_request),
178
+ queued: num(s.queued) ?? (Array.isArray(s.queue) ? s.queue.length : 0),
179
+ last_activity_ms: num(s.last_activity_ms),
180
+ last_sequence: num(s.last_sequence)
181
+ };
182
+ }
183
+ function parseSession(raw) {
184
+ const s = obj(raw);
185
+ const summary = parseSummary(s);
186
+ if (!summary) return null;
187
+ const receipts = {};
188
+ for (const value of Object.values(obj(s.receipts))) {
189
+ const receipt = parseReceipt(value);
190
+ if (receipt) receipts[receipt.request_id] = receipt;
191
+ }
192
+ const prompts = {};
193
+ for (const [id, value] of Object.entries(obj(s.prompts))) {
194
+ const text = str(obj(obj(value).input).text);
195
+ if (text !== null) prompts[id] = text;
196
+ }
197
+ return { ...summary, receipts, prompts, steer: obj(s.capabilities).steer === true };
198
+ }
199
+ var TIMEOUT_MS = 15e3;
200
+ var EVENTS_PAGE = 256;
201
+ var CoreClient = class {
202
+ constructor(base, token, fetchFn = fetch) {
203
+ this.base = base;
204
+ this.token = token;
205
+ this.fetchFn = fetchFn;
206
+ }
207
+ base;
208
+ token;
209
+ fetchFn;
210
+ async capabilities() {
211
+ const raw = obj(await this.json("GET", "/v1/capabilities"));
212
+ return (Array.isArray(raw.harnesses) ? raw.harnesses : []).flatMap((h) => {
213
+ const id = str(obj(h).id);
214
+ return id ? [{ id, model: str(obj(h).model) }] : [];
215
+ });
216
+ }
217
+ async account(kind) {
218
+ const raw = obj(await this.json("GET", `/v1/accounts/${kind}`));
219
+ return { state: str(raw.state) ?? "unavailable", plan: str(raw.plan) };
220
+ }
221
+ async sessions() {
222
+ const raw = obj(await this.json("GET", "/v1/sessions"));
223
+ return (Array.isArray(raw.sessions) ? raw.sessions : []).flatMap((s) => parseSummary(s) ?? []);
224
+ }
225
+ /** Null when core has no such session. */
226
+ async session(id) {
227
+ try {
228
+ const raw = obj(await this.json("GET", `/v1/sessions/${encodeURIComponent(id)}`));
229
+ return parseSession(raw.session);
230
+ } catch (err) {
231
+ if (err instanceof CoreError && err.status === 404) return null;
232
+ throw err;
233
+ }
234
+ }
235
+ /** One page of records after `after`. A short page is the end of the history. */
236
+ async events(id, after) {
237
+ const raw = obj(
238
+ await this.json("GET", `/v1/sessions/${encodeURIComponent(id)}/events?after=${after}`)
239
+ );
240
+ return (Array.isArray(raw.events) ? raw.events : []).flatMap((r) => parseRecord(r) ?? []);
241
+ }
242
+ async start(body) {
243
+ return parseReceipt(obj(await this.json("POST", "/v1/sessions", body)).receipt);
244
+ }
245
+ async command(id, command, body) {
246
+ return parseReceipt(
247
+ obj(await this.json("POST", `/v1/sessions/${encodeURIComponent(id)}/${command}`, body)).receipt
248
+ );
249
+ }
250
+ /** Answer a spawn core is waiting on: `{ error }` refuses it. */
251
+ async answerChild(session, child, answer) {
252
+ await this.json(
253
+ "POST",
254
+ `/v1/sessions/${encodeURIComponent(session)}/children/${encodeURIComponent(child)}`,
255
+ answer
256
+ );
257
+ }
258
+ /**
259
+ * Follow the session's live records after `after`, one call per record,
260
+ * until the stream ends or `signal` aborts. Core ends it when it stops.
261
+ */
262
+ async stream(id, after, onRecord, signal) {
263
+ const res = await this.fetchFn(
264
+ `${this.base}/v1/sessions/${encodeURIComponent(id)}/stream?after=${after}`,
265
+ {
266
+ headers: { authorization: `Bearer ${this.token}`, accept: "text/event-stream" },
267
+ signal
268
+ }
269
+ );
270
+ if (!res.ok) throw await coreError(res);
271
+ if (!res.body) throw new CoreError(res.status, null, "core stream has no body");
272
+ const reader = res.body.getReader();
273
+ const decoder = new TextDecoder();
274
+ let buffer = "";
275
+ for (; ; ) {
276
+ const { value, done } = await reader.read();
277
+ if (done) return;
278
+ buffer += decoder.decode(value, { stream: true });
279
+ let end = buffer.search(/\r?\n\r?\n/);
280
+ while (end >= 0) {
281
+ const block = buffer.slice(0, end);
282
+ buffer = buffer.slice(end).replace(/^\r?\n\r?\n/, "");
283
+ const record = sseRecord(block);
284
+ if (record) onRecord(record);
285
+ end = buffer.search(/\r?\n\r?\n/);
286
+ }
287
+ }
288
+ }
289
+ async json(method, path, body) {
290
+ const res = await this.fetchFn(`${this.base}${path}`, {
291
+ method,
292
+ headers: {
293
+ authorization: `Bearer ${this.token}`,
294
+ ...body === void 0 ? {} : { "content-type": "application/json" }
295
+ },
296
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
297
+ signal: AbortSignal.timeout(TIMEOUT_MS)
298
+ });
299
+ if (!res.ok) throw await coreError(res);
300
+ return res.json();
301
+ }
302
+ };
303
+ async function coreError(res) {
304
+ let raw = {};
305
+ try {
306
+ raw = obj(await res.json());
307
+ } catch {
308
+ }
309
+ return new CoreError(
310
+ res.status,
311
+ str(raw.code),
312
+ `core ${res.status}${raw.code ? ` ${raw.code}` : ""}: ${str(raw.error) ?? res.statusText}`
313
+ );
314
+ }
315
+ function sseRecord(block) {
316
+ let event = "message";
317
+ const data = [];
318
+ for (const line of block.split(/\r?\n/)) {
319
+ if (line.startsWith("event:")) event = line.slice(6).trim();
320
+ else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
321
+ }
322
+ if (event !== "record" || !data.length) return null;
323
+ try {
324
+ return parseRecord(JSON.parse(data.join("\n")));
325
+ } catch {
326
+ return null;
327
+ }
328
+ }
329
+
330
+ // src/drivers/cloudroom.ts
331
+ import { createHash } from "crypto";
332
+
333
+ // src/drivers/cloudroom-repos.ts
334
+ import { execFile, spawn } from "child_process";
335
+ import { existsSync, mkdirSync, renameSync, rmSync, statSync } from "fs";
336
+ import { join } from "path";
337
+ import { promisify } from "util";
338
+ var REPOS_ROOT = "/code/.repos";
339
+ var WORKTREE_ID = /^wt-([a-z0-9_-]+-[0-9a-f]{8})-([0-9a-f]{8})$/;
340
+ function worktreeOf(workspace) {
341
+ const m = workspace?.match(WORKTREE_ID);
342
+ return m?.[1] && m[2] ? { clone: m[1], branch: `cloop/${m[2]}` } : null;
343
+ }
344
+ function worktreeFate(f) {
345
+ if (f.busy) return "in_use";
346
+ if (!f.present) return "gone";
347
+ if (f.uncommitted) return "keep_uncommitted";
348
+ if (f.unpushed > 0) return "keep_unpushed";
349
+ return "remove";
350
+ }
351
+ function keptLine(fate, path, branch) {
352
+ if (fate === "keep_uncommitted")
353
+ return `The work is kept in ${path} on branch ${branch}: it has changes that are not committed.`;
354
+ if (fate === "keep_unpushed")
355
+ return `The work is kept in ${path} on branch ${branch}: it has commits that are not pushed.`;
356
+ return null;
357
+ }
358
+ var run = promisify(execFile);
359
+ var CLONE_MS = 15 * 6e4;
360
+ var GIT_MS = 2 * 6e4;
361
+ var FETCH_FRESH_MS = 6e4;
362
+ async function git(cwd, args, timeout = GIT_MS) {
363
+ const { stdout } = await run("git", args, { cwd, timeout, maxBuffer: 16 * 1024 * 1024 });
364
+ return stdout.trim();
365
+ }
366
+ var gitOk = (cwd, args) => git(cwd, args).then(
367
+ () => true,
368
+ () => false
369
+ );
370
+ async function withLock(file, fn) {
371
+ const holder = spawn("flock", ["-x", file, "sh", "-c", "echo locked; read _"], {
372
+ stdio: ["pipe", "pipe", "ignore"]
373
+ });
374
+ const exited = new Promise((resolve) => holder.once("close", () => resolve()));
375
+ await new Promise((resolve, reject) => {
376
+ holder.stdout.once("data", () => resolve());
377
+ holder.once("error", reject);
378
+ holder.once("close", (code) => reject(new Error(`flock ended before it locked: ${code}`)));
379
+ });
380
+ try {
381
+ return await fn();
382
+ } finally {
383
+ holder.stdin.end();
384
+ await exited;
385
+ }
386
+ }
387
+ var Repos = class {
388
+ constructor(root = REPOS_ROOT) {
389
+ this.root = root;
390
+ }
391
+ root;
392
+ cloneDir(clone) {
393
+ return join(this.root, clone);
394
+ }
395
+ /** Runs `fn` under the clone's lock. Every write to a clone or its worktrees goes through here. */
396
+ locked(clone, fn) {
397
+ mkdirSync(this.root, { recursive: true });
398
+ return withLock(join(this.root, `${clone}.lock`), fn);
399
+ }
400
+ /**
401
+ * The clone, there and fetched. A first clone goes to a side folder and is
402
+ * renamed in, so the clone's folder never holds half a clone. Call under
403
+ * the clone's lock. Git's failure is the repository's: the box could not
404
+ * reach it, or may not read it.
405
+ */
406
+ async ensureClone(p) {
407
+ const dir = this.cloneDir(p.clone);
408
+ try {
409
+ if (existsSync(join(dir, ".git"))) {
410
+ const fetched = join(dir, ".git", "FETCH_HEAD");
411
+ if (!existsSync(fetched) || Date.now() - statSync(fetched).mtimeMs > FETCH_FRESH_MS)
412
+ await git(dir, ["fetch", "--quiet", "origin"]);
413
+ return;
414
+ }
415
+ const partial = `${dir}.partial`;
416
+ rmSync(partial, { recursive: true, force: true });
417
+ await git(this.root, ["clone", "--quiet", p.url, partial], CLONE_MS);
418
+ renameSync(partial, dir);
419
+ } catch (err) {
420
+ throw Object.assign(new BoxToolError("repo_unreachable"), {
421
+ message: `repo_unreachable: ${err instanceof Error ? err.message : String(err)}`.slice(
422
+ 0,
423
+ 400
424
+ )
425
+ });
426
+ }
427
+ }
428
+ async listed(dir, path) {
429
+ const list = await git(dir, ["worktree", "list", "--porcelain"]);
430
+ return list.split("\n").includes(`worktree ${path}`);
431
+ }
432
+ /**
433
+ * The run's worktree at `path`, on its branch. An empty folder core made is
434
+ * filled; a folder that is already the worktree is left as it is. The run's
435
+ * branch is the local one when there is one, else the one it pushed, else
436
+ * a new one from the remote's default branch. Call under the clone's lock.
437
+ */
438
+ async ensureWorktree(clone, branch, path) {
439
+ const dir = this.cloneDir(clone);
440
+ await git(dir, ["worktree", "prune"]);
441
+ if (await this.listed(dir, path)) return;
442
+ if (await gitOk(dir, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]))
443
+ await git(dir, ["worktree", "add", "--quiet", path, branch]);
444
+ else {
445
+ const pushed = `refs/remotes/origin/${branch}`;
446
+ const base = await gitOk(dir, ["rev-parse", "--verify", "--quiet", pushed]) ? pushed : "origin/HEAD";
447
+ await git(dir, ["worktree", "add", "--quiet", "--no-track", "-b", branch, path, base]);
448
+ }
449
+ }
450
+ /** What is in the worktree at `path`. Call under the clone's lock. */
451
+ async facts(clone, branch, path, busy2) {
452
+ const dir = this.cloneDir(clone);
453
+ const none = { busy: busy2, present: false, uncommitted: false, unpushed: 0, head: branch };
454
+ if (!existsSync(join(dir, ".git"))) return none;
455
+ await git(dir, ["worktree", "prune"]);
456
+ if (!await this.listed(dir, path)) return none;
457
+ const own = await gitOk(dir, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]) ? [`refs/heads/${branch}`] : [];
458
+ const [status, unpushed, head] = await Promise.all([
459
+ git(path, ["status", "--porcelain"]),
460
+ git(path, ["rev-list", "--count", "HEAD", ...own, "--not", "--remotes"]),
461
+ git(path, ["branch", "--show-current"])
462
+ ]);
463
+ return {
464
+ busy: busy2,
465
+ present: true,
466
+ uncommitted: status.length > 0,
467
+ unpushed: Number(unpushed),
468
+ head: head || branch
469
+ };
470
+ }
471
+ /**
472
+ * Removes the worktree and the run's local branch. Call only for the fate
473
+ * `remove`, under the clone's lock. Git refuses to remove a worktree with
474
+ * changes in it, so a change made since the facts were read stays.
475
+ */
476
+ async remove(clone, branch, path) {
477
+ const dir = this.cloneDir(clone);
478
+ await git(dir, ["worktree", "remove", path]);
479
+ if (await gitOk(dir, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]))
480
+ await git(dir, ["branch", "--quiet", "-D", branch]);
481
+ }
482
+ };
483
+
484
+ // src/drivers/cloudroom.ts
485
+ var capital = (s) => `${s.charAt(0).toUpperCase()}${s.slice(1)}`;
486
+ var HARNESSES = {
487
+ "claude-code": {
488
+ name: "Claude Code",
489
+ runner: "Claude",
490
+ aliases: ["claude-code", "claudeAgent", "claude"],
491
+ account: { kind: "claude", label: (plan) => plan && SUBSCRIPTIONS[plan] || "Claude" }
492
+ },
493
+ codex: {
494
+ name: "Codex",
495
+ runner: "Codex",
496
+ aliases: ["codex"],
497
+ account: { kind: "codex", label: (plan) => plan ? `ChatGPT ${capital(plan)}` : "ChatGPT" }
498
+ },
499
+ opencode: { name: "OpenCode", runner: "OpenCode", aliases: ["opencode"] }
500
+ };
501
+ function harnessFacts(harness) {
502
+ return HARNESSES[harness] ?? { name: capital(harness), runner: capital(harness), aliases: [harness] };
503
+ }
504
+ function hostedRunnerName(harness) {
505
+ return `${harnessFacts(harness).runner} \xB7 Cloop Box`;
506
+ }
507
+ var SIGNED_IN = /* @__PURE__ */ new Set(["connected", "limited"]);
508
+ var REQUEST_ID = /^[A-Za-z0-9_-]{1,64}$/;
509
+ function coreRequestId(kind, id) {
510
+ const plain = `${kind}-${id}`;
511
+ return REQUEST_ID.test(plain) ? plain : `${kind}-${createHash("sha256").update(id).digest("hex").slice(0, 40)}`;
512
+ }
513
+ var CLOOP_SESSION_PREFIX = "cr_cloop-";
514
+ function ownerName(repository) {
515
+ const path = repository.trim().replace(/^(https?:\/\/|git@)github\.com[/:]/i, "").replace(/\.git$/i, "").replace(/\/+$/, "");
516
+ return /^[\w-][\w.-]*\/[\w-][\w.-]*$/.test(path) ? path : null;
517
+ }
518
+ var CLONABLE = /^(https?|ssh|git|file):\/\/\S+$|^[\w.-]+@[\w.-]+:\S+$/i;
519
+ var hash8 = (s) => createHash("sha256").update(s).digest("hex").slice(0, 8);
520
+ function placeFor(a) {
521
+ const repository = a.repository?.trim();
522
+ const named = repository ? ownerName(repository) : null;
523
+ if (!repository || !named && !CLONABLE.test(repository))
524
+ return {
525
+ kind: "folder",
526
+ workspace: coreRequestId("work", a.work_id),
527
+ workspace_name: `work-${a.work_id.slice(0, 8)}`,
528
+ ...repository ? { named: repository } : {}
529
+ };
530
+ const key = (named ?? repository).toLowerCase();
531
+ const last = key.replace(/\.git$/, "").split(/[/:]/).at(-1) ?? "";
532
+ const name = last.replace(/[^a-z0-9_.-]+/g, "-").replace(/^\.+/, "") || "repo";
533
+ const clone = `${name.replace(/[^a-z0-9_-]+/g, "-").slice(0, 40)}-${hash8(key)}`;
534
+ const run3 = hash8(a.work_id);
535
+ return {
536
+ kind: "worktree",
537
+ workspace: `wt-${clone}-${run3}`,
538
+ workspace_name: `${name.slice(0, 70)}-${run3}`,
539
+ repository,
540
+ url: named ? `https://github.com/${named}.git` : repository,
541
+ clone,
542
+ branch: `cloop/${run3}`
543
+ };
544
+ }
545
+ function launchText(prompt, place) {
546
+ const where = place.kind === "worktree" ? `
547
+
548
+ This folder is a git worktree of ${place.repository} on its own branch, \`${place.branch}\`, made for this Task. Other Tasks on this repository work in other folders at the same time. Commit here, and push the branch when the work should leave the box.` : place.named ? `
549
+
550
+ The Task names the repository ${place.named}. This folder is empty: clone it here first.` : "";
551
+ return `${prompt}${where}
552
+
553
+ ${RESULT_INSTRUCTION}`;
554
+ }
555
+ var NEW_FOLD = {
556
+ start: null,
557
+ turns: [],
558
+ session: null,
559
+ after: 0,
560
+ spoken: null,
561
+ lastProgressAt: 0,
562
+ ended: false
563
+ };
564
+ var PENDING = /* @__PURE__ */ new Set(["accepted", "delivered", "running"]);
565
+ var DEAD = /* @__PURE__ */ new Set(["closed", "failed", "process_lost"]);
566
+ var END_WORDS = {
567
+ failed: "The run failed.",
568
+ unknown: "The Cloop Box stopped during the run, so its outcome is unknown.",
569
+ unknown_after_restart: "The Cloop Box restarted during the run, so its outcome is unknown.",
570
+ closed: "The run was closed before it finished.",
571
+ process_lost: "The harness was lost during the run and could not resume."
572
+ };
573
+ var LIMIT_WORDS = "The harness hit its usage limit.";
574
+ function openTurn(fold) {
575
+ for (let i = fold.turns.length - 1; i >= 0; i--) {
576
+ const turn = fold.turns[i];
577
+ if (turn && !turn.cancelled && PENDING.has(turn.state)) return turn;
578
+ }
579
+ return void 0;
580
+ }
581
+ function turnOf(fold, request) {
582
+ return request ? fold.turns.find((t) => t.id === request) : openTurn(fold);
583
+ }
584
+ function apply(fold, r) {
585
+ switch (r.kind) {
586
+ case "receipt": {
587
+ const { command, state, error, request_id, target } = r.receipt;
588
+ if (command === "start") fold.start = { state, error };
589
+ else if (command === "prompt") {
590
+ const turn = fold.turns.find((t) => t.id === request_id);
591
+ if (turn) Object.assign(turn, { state, error });
592
+ else
593
+ fold.turns.push({
594
+ id: request_id,
595
+ state,
596
+ error,
597
+ cancelled: false,
598
+ limited: false,
599
+ item: null,
600
+ text: ""
601
+ });
602
+ } else if (command === "cancel" && (state === "accepted" || state === "completed")) {
603
+ const turn = fold.turns.find((t) => t.id === target);
604
+ if (turn) turn.cancelled = true;
605
+ }
606
+ return null;
607
+ }
608
+ case "state":
609
+ fold.session = r.state;
610
+ return null;
611
+ case "text": {
612
+ const turn = turnOf(fold, r.request);
613
+ if (!turn) return null;
614
+ if (turn.item !== r.item) {
615
+ turn.item = r.item;
616
+ turn.text = "";
617
+ }
618
+ turn.text += r.delta;
619
+ return null;
620
+ }
621
+ case "message": {
622
+ const turn = turnOf(fold, r.request);
623
+ if (!turn) return null;
624
+ turn.item = r.item;
625
+ turn.text = r.text;
626
+ return turn;
627
+ }
628
+ case "usage_limited": {
629
+ const turn = openTurn(fold) ?? fold.turns.at(-1);
630
+ if (turn) turn.limited = true;
631
+ return null;
632
+ }
633
+ default:
634
+ return null;
635
+ }
636
+ }
637
+ function failedRun(harness, state, said, limited) {
638
+ const words = said?.trim();
639
+ const limit = limited || HARNESS_LIMIT.test(words ?? "");
640
+ const error = limit ? { error: "harness_limit" } : {};
641
+ if (!words)
642
+ return {
643
+ kind: "failed",
644
+ summary: limit ? LIMIT_WORDS : END_WORDS[state] ?? `The run ended ${state}.`,
645
+ ...error
646
+ };
647
+ const { summary } = failedEnd(harnessFacts(harness).name, {
648
+ result: { ok: false, text: words },
649
+ exit: state
650
+ });
651
+ return { kind: "failed", summary, ...error };
652
+ }
653
+ function runEnd(fold, harness) {
654
+ const turns = fold.turns.filter((t) => !t.cancelled);
655
+ if (turns.some((t) => PENDING.has(t.state)))
656
+ return fold.session && DEAD.has(fold.session) ? failedRun(harness, fold.session, null, false) : null;
657
+ const last = turns.at(-1);
658
+ if (!last) {
659
+ if (fold.turns.length)
660
+ return { kind: "failed", summary: STOPPED_SUMMARY, error: "interrupted" };
661
+ if (fold.start && !PENDING.has(fold.start.state) && fold.start.state !== "completed")
662
+ return failedRun(harness, fold.start.state, fold.start.error, false);
663
+ return null;
664
+ }
665
+ if (last.state === "completed" && !last.limited) {
666
+ const text = last.text.trim();
667
+ const result = readRunResult(text).result;
668
+ const pr = resultPrUrl(text);
669
+ const summary = text.replace(/\s+/g, " ").slice(0, RUN_TEXT_MAX);
670
+ return {
671
+ kind: "settled",
672
+ ...result ? { result } : {},
673
+ ...summary ? { summary } : {},
674
+ ...pr ? { pr_url: pr } : {}
675
+ };
676
+ }
677
+ if (last.state === "interrupted" && !last.limited)
678
+ return { kind: "failed", summary: STOPPED_SUMMARY, error: "interrupted" };
679
+ return failedRun(harness, last.state, last.error || last.text, last.limited);
680
+ }
681
+ function foldRecords(fold, records, opts) {
682
+ const next = structuredClone(fold);
683
+ let said = null;
684
+ for (const r of records) {
685
+ next.after = Math.max(next.after, r.sequence);
686
+ said = apply(next, r) ?? said;
687
+ }
688
+ if (next.ended) return { state: next, events: [] };
689
+ const end = runEnd(next, opts.harness);
690
+ if (end) {
691
+ next.ended = true;
692
+ return { state: next, events: [end] };
693
+ }
694
+ if (!said || said.cancelled || !PENDING.has(said.state) || said.text === next.spoken)
695
+ return { state: next, events: [] };
696
+ next.spoken = said.text;
697
+ const clock = { lastProgressAt: next.lastProgressAt };
698
+ const summary = nextProgress(clock, said.text, opts.now, opts.progressMs);
699
+ next.lastProgressAt = clock.lastProgressAt;
700
+ return { state: next, events: summary ? [{ kind: "progress", summary }] : [] };
701
+ }
702
+ var STARTING = /* @__PURE__ */ new Set(["pending", "starting", "resuming", "starting_turn", "waiting_for_files"]);
703
+ function busy(s) {
704
+ return s.current_request !== null || s.queued > 0 || STARTING.has(s.state);
705
+ }
706
+ function folder(s) {
707
+ if (!s.workspace_path) throw new Error(`core gave session ${s.session_id} no folder`);
708
+ return s.workspace_path;
709
+ }
710
+ var START_REFUSALS = {
711
+ claude_auth_required: "harness_signed_out",
712
+ codex_auth_required: "harness_signed_out",
713
+ cursor_auth_required: "harness_signed_out",
714
+ harness_not_configured: "harness_unavailable"
715
+ };
716
+ var SHARED_SANDBOX_ONLY = "a Cloop Box runs every child in this sandbox. Spawn it again with --shared-sandbox";
717
+ var CHILDREN_POLL_MS = 2e3;
718
+ var GONE_SUMMARY = "This run is not on the runner any more.";
719
+ var UNSENT_SUMMARY = "The runner restarted while it prepared this run, so the Task never reached the harness. Ask again.";
720
+ var CHILDREN_WAIT_MS = 5e3;
721
+ var RETRY_MIN_MS = 1e3;
722
+ var RETRY_MAX_MS = 3e4;
723
+ var STOPPED_IN_PREPARATION = new Error("stopped while being prepared");
724
+ function unpreparedEnd(harness, err) {
725
+ if (err === STOPPED_IN_PREPARATION)
726
+ return { kind: "failed", summary: STOPPED_SUMMARY, error: "interrupted" };
727
+ const code = err instanceof BoxToolError ? err.code : null;
728
+ const name = harnessFacts(harness).name;
729
+ const summary = code === "repo_unreachable" ? "The Cloop Box could not get the repository. Check that GitHub is connected in Cloop and can read it, then ask again." : code === "harness_signed_out" ? `${name} in the Cloop Box is signed out. Connect it again in Agents, then ask again.` : code === "harness_unavailable" ? `The Cloop Box does not have ${name}. Name a coding agent it has, or leave it to its default.` : `The run did not start: ${err instanceof Error ? err.message : String(err)}`.slice(
730
+ 0,
731
+ RUN_TEXT_MAX
732
+ );
733
+ return { kind: "failed", summary };
734
+ }
735
+ var sleep = (ms) => new Promise((resolve) => {
736
+ const timer = setTimeout(resolve, ms);
737
+ timer.unref?.();
738
+ });
739
+ var CloudroomDriver = class {
740
+ constructor(deps) {
741
+ this.deps = deps;
742
+ this.repos = deps.repos ?? new Repos();
743
+ }
744
+ deps;
745
+ name = "cloudroom";
746
+ capabilities = ["view", "start", "steer", "report"];
747
+ repos;
748
+ /** Repository runs still being prepared after launch answered, by thread. A failed one stays, for watch to report. */
749
+ preparing = /* @__PURE__ */ new Map();
750
+ /** Runs stopped while still being prepared. */
751
+ stopped = /* @__PURE__ */ new Set();
752
+ get core() {
753
+ return this.deps.core;
754
+ }
755
+ get harness() {
756
+ return this.deps.harness;
757
+ }
758
+ now() {
759
+ return this.deps.now?.() ?? Date.now();
760
+ }
761
+ log(line) {
762
+ this.deps.log?.(line);
763
+ }
764
+ async status() {
765
+ const [harnesses, sessions] = await Promise.all([this.core.capabilities(), this.sessions()]);
766
+ const running = sessions.filter(busy);
767
+ return {
768
+ box: { label: this.deps.label ?? "Cloop Box", driver: this.name },
769
+ harnesses: await this.reports(harnesses),
770
+ clients: null,
771
+ projects: [],
772
+ threads: {
773
+ unsettled: running.length,
774
+ running: running.length,
775
+ settled: sessions.length - running.length,
776
+ cloop: running.filter((s) => s.session_id.startsWith(CLOOP_SESSION_PREFIX)).length
777
+ }
778
+ };
779
+ }
780
+ async reports(harnesses) {
781
+ const info = harnesses.find((h) => h.id === this.harness);
782
+ if (!info) return [];
783
+ const facts = harnessFacts(this.harness);
784
+ const account = facts.account ? await this.core.account(facts.account.kind) : null;
785
+ const signedIn = account ? SIGNED_IN.has(account.state) : true;
786
+ return [
787
+ {
788
+ id: this.harness,
789
+ name: facts.name,
790
+ version: null,
791
+ ready: account ? account.state === "connected" : true,
792
+ signedIn,
793
+ account: account && signedIn ? facts.account?.label(account.plan) ?? null : null,
794
+ defaultModel: info.model,
795
+ experimental: true
796
+ }
797
+ ];
798
+ }
799
+ async listThreads({
800
+ scope,
801
+ limit
802
+ }) {
803
+ const sessions = await this.sessions();
804
+ const running = sessions.filter(busy);
805
+ const views = (scope === "all" ? sessions : running).map(
806
+ (s) => ({
807
+ id: s.session_id,
808
+ title: s.session_id,
809
+ status: busy(s) ? "running" : DEAD.has(s.state) ? "failed" : "completed",
810
+ branch: null,
811
+ source: s.session_id.startsWith(CLOOP_SESSION_PREFIX) ? "cloop" : "cloudroom",
812
+ cloop: s.session_id.startsWith(CLOOP_SESSION_PREFIX),
813
+ settled: !busy(s),
814
+ updatedAt: new Date(s.last_activity_ms ?? 0).toISOString()
815
+ })
816
+ );
817
+ const shown = orderThreads(views, limit);
818
+ await Promise.all(
819
+ shown.map(async (t) => {
820
+ const first = Object.values((await this.core.session(t.id))?.prompts ?? {})[0];
821
+ const line = first?.trim().split("\n")[0]?.slice(0, 120);
822
+ if (line) t.title = line;
823
+ })
824
+ );
825
+ return {
826
+ scope,
827
+ unsettled: running.length,
828
+ settled: sessions.length - running.length,
829
+ running: running.length,
830
+ threads: shown
831
+ };
832
+ }
833
+ async readThread(id) {
834
+ const session = await this.session(id);
835
+ const fold = await this.history(id);
836
+ const end = runEnd(fold, this.harness);
837
+ const last = fold.turns.filter((t) => !t.cancelled).at(-1);
838
+ return {
839
+ status: end ? end.kind === "settled" ? "completed" : end.error === "interrupted" ? "interrupted" : "failed" : busy(session) ? "running" : session.state,
840
+ settled: Boolean(end),
841
+ pr_url: end?.pr_url ?? null,
842
+ last_assistant_text: end?.summary ?? (last?.text.trim() || null)
843
+ };
844
+ }
845
+ /**
846
+ * Start the session if it is not there, then send the prompt if it was not
847
+ * sent. Both carry request ids made from the work id, so a retry, or two
848
+ * launches at once, start one session and send one prompt. A run on a
849
+ * repository first gets the clone, then its worktree in the folder core
850
+ * made, all under the clone's lock, so the box's two runners never race on
851
+ * one clone. A first clone can take minutes and the mesh waits 20 s for
852
+ * this answer, so a repository run answers at once and is prepared after;
853
+ * watch reports a preparation that failed.
854
+ */
855
+ async launch(a) {
856
+ if (a.harness && !harnessFacts(this.harness).aliases.includes(a.harness))
857
+ throw new BoxToolError("harness_unavailable");
858
+ const start = coreRequestId("cloop", a.work_id);
859
+ const thread = `cr_${start}`;
860
+ const prompt = coreRequestId("run", a.work_id);
861
+ const place = placeFor(a);
862
+ const go = async () => {
863
+ const existing2 = await this.core.session(thread);
864
+ if (existing2?.receipts[prompt]) return existing2;
865
+ if (place.kind === "worktree") await this.repos.ensureClone(place);
866
+ if (this.stopped.has(thread)) throw STOPPED_IN_PREPARATION;
867
+ if (!existing2) {
868
+ try {
869
+ await this.core.start({
870
+ request_id: start,
871
+ harness: this.harness,
872
+ ...a.model ? { model: a.model } : {},
873
+ workspace: place.workspace,
874
+ workspace_name: place.workspace_name
875
+ });
876
+ } catch (err) {
877
+ const refusal = err instanceof CoreError && err.code ? START_REFUSALS[err.code] : void 0;
878
+ if (refusal) throw new BoxToolError(refusal);
879
+ throw err;
880
+ }
881
+ }
882
+ if (place.kind === "worktree")
883
+ await this.repos.ensureWorktree(
884
+ place.clone,
885
+ place.branch,
886
+ folder(existing2 ?? await this.session(thread))
887
+ );
888
+ if (this.stopped.has(thread)) throw STOPPED_IN_PREPARATION;
889
+ await this.core.command(thread, "prompts", {
890
+ request_id: prompt,
891
+ text: launchText(a.prompt, place)
892
+ });
893
+ this.preparing.delete(thread);
894
+ if (this.stopped.has(thread))
895
+ await this.stopRun(thread, `prepared-${a.work_id}`).catch(
896
+ (err) => this.log(
897
+ `interrupt after preparation failed thread=${thread}: ${err instanceof Error ? err.message : String(err)}`
898
+ )
899
+ );
900
+ return existing2;
901
+ };
902
+ const answer = (resumed) => {
903
+ this.log(`launch work=${a.work_id} thread=${thread}${resumed ? " resumed" : ""}`);
904
+ return { thread_id: thread, resumed, permission: "full" };
905
+ };
906
+ if (place.kind === "folder") return answer(Boolean(await go()));
907
+ const existing = await this.core.session(thread);
908
+ if (existing?.receipts[prompt]) return answer(true);
909
+ const again = this.preparing.has(thread);
910
+ if (!again) {
911
+ const prep = this.repos.locked(place.clone, go).then(() => {
912
+ this.preparing.delete(thread);
913
+ });
914
+ prep.catch(
915
+ (err) => this.log(
916
+ `launch failed work=${a.work_id} thread=${thread}: ${err instanceof Error ? err.message : String(err)}`
917
+ )
918
+ );
919
+ this.preparing.set(thread, prep);
920
+ }
921
+ return answer(again || Boolean(existing));
922
+ }
923
+ /**
924
+ * A steer goes into the running turn when the harness takes one, else it
925
+ * waits as the next prompt. A run that ended takes text only to resume.
926
+ * Core keeps every command's receipt, so a retried command id answers what
927
+ * the first delivery did and delivers nothing again. A run's worktree,
928
+ * removed when it ended clean, is made again before the text goes in.
929
+ */
930
+ async send(a) {
931
+ const s = await this.session(a.thread_id);
932
+ if (a.answer) return { delivered: "question_changed", question: null, question_id: null };
933
+ const steer = coreRequestId("steer", a.command_id);
934
+ const queue = coreRequestId("send", a.command_id);
935
+ if (s.receipts[steer]) return { delivered: "steer" };
936
+ if (s.receipts[queue]) return { delivered: "queue" };
937
+ const running = busy(s);
938
+ if (!running && !a.resume) throw new BoxToolError("already_finished");
939
+ const deliver = async () => {
940
+ if (a.mode === "steer" && s.steer && s.current_request) {
941
+ try {
942
+ await this.core.command(a.thread_id, "steer", {
943
+ request_id: steer,
944
+ target_request_id: s.current_request,
945
+ text: a.text
946
+ });
947
+ return { delivered: "steer" };
948
+ } catch (err) {
949
+ if (!(err instanceof CoreError && err.status === 409)) throw err;
950
+ this.log(`steer missed its turn thread=${a.thread_id}; queued instead`);
951
+ }
952
+ }
953
+ await this.core.command(a.thread_id, "prompts", { request_id: queue, text: a.text });
954
+ return { delivered: running ? "queue" : "start" };
955
+ };
956
+ const tree = worktreeOf(s.workspace);
957
+ if (!tree) return deliver();
958
+ return this.repos.locked(tree.clone, async () => {
959
+ await this.repos.ensureWorktree(tree.clone, tree.branch, folder(s));
960
+ return deliver();
961
+ });
962
+ }
963
+ /**
964
+ * When a run ends, its worktree goes if nothing in it would be lost, and
965
+ * the report says where the work is when it stays. Under the clone's lock,
966
+ * core is asked again: a prompt sent since the end, or any other session
967
+ * working in the folder, keeps it. A
968
+ * failure here is logged and the end is reported as it was.
969
+ */
970
+ async tidy(id, end) {
971
+ try {
972
+ const s = await this.core.session(id);
973
+ const tree = worktreeOf(s?.workspace ?? null);
974
+ if (!s || !tree) return end;
975
+ const path = folder(s);
976
+ const line = await this.repos.locked(tree.clone, async () => {
977
+ const inUse = (await this.core.sessions()).some(
978
+ (x) => x.workspace === s.workspace && busy(x)
979
+ );
980
+ const facts = await this.repos.facts(tree.clone, tree.branch, path, inUse);
981
+ const fate = worktreeFate(facts);
982
+ this.log(`worktree ${fate} thread=${id} path=${path}`);
983
+ if (fate !== "remove") return keptLine(fate, path, facts.head);
984
+ try {
985
+ await this.repos.remove(tree.clone, tree.branch, path);
986
+ return null;
987
+ } catch (err) {
988
+ this.log(
989
+ `worktree not removed thread=${id}: ${err instanceof Error ? err.message : String(err)}`
990
+ );
991
+ return `The work is kept in ${path} on branch ${facts.head}.`;
992
+ }
993
+ });
994
+ if (!line) return end;
995
+ const told = (text = "") => text ? `${text.slice(0, RUN_TEXT_MAX - line.length - 2)}
996
+
997
+ ${line}` : line;
998
+ return {
999
+ ...end,
1000
+ summary: told(end.summary),
1001
+ ...end.result ? { result: { ...end.result, summary: told(end.result.summary) } } : {}
1002
+ };
1003
+ } catch (err) {
1004
+ this.log(
1005
+ `worktree tidy failed thread=${id}: ${err instanceof Error ? err.message : String(err)}`
1006
+ );
1007
+ return end;
1008
+ }
1009
+ }
1010
+ /**
1011
+ * Stop the run: drop the prompts waiting behind the current turn, then
1012
+ * interrupt that turn. Core's interrupt alone stops the turn and lets the
1013
+ * queue carry on, and a Stop in Cloop ends the run.
1014
+ */
1015
+ async interrupt(id, commandId) {
1016
+ if (this.preparing.has(id) && !this.stopped.has(id)) {
1017
+ this.stopped.add(id);
1018
+ this.log(`interrupt thread=${id} during preparation`);
1019
+ return { ok: true, was_running: true };
1020
+ }
1021
+ return this.stopRun(id, commandId);
1022
+ }
1023
+ async stopRun(id, commandId) {
1024
+ const s = await this.session(id);
1025
+ const cancelled = await Promise.all(
1026
+ Object.values(s.receipts).filter(
1027
+ (r) => r.command === "prompt" && r.state === "accepted" && r.request_id !== s.current_request
1028
+ ).map(
1029
+ (r) => this.core.command(id, "cancel", {
1030
+ request_id: coreRequestId("cancel", `${commandId}-${r.request_id}`),
1031
+ target_request_id: r.request_id
1032
+ }).then(
1033
+ () => true,
1034
+ () => false
1035
+ )
1036
+ )
1037
+ );
1038
+ let stopped = false;
1039
+ if (s.current_request) {
1040
+ try {
1041
+ await this.core.command(id, "interrupt", {
1042
+ request_id: coreRequestId("stop", commandId),
1043
+ target_request_id: s.current_request
1044
+ });
1045
+ stopped = true;
1046
+ } catch (err) {
1047
+ if (!(err instanceof CoreError && err.status === 409)) throw err;
1048
+ }
1049
+ }
1050
+ const was_running = stopped || cancelled.includes(true);
1051
+ this.log(`interrupt thread=${id} was_running=${was_running}`);
1052
+ return { ok: true, was_running };
1053
+ }
1054
+ /**
1055
+ * Read the run's history after the last record seen, then follow its live
1056
+ * stream. When the stream ends or fails, core stopped or the connection
1057
+ * dropped: read what was missed and follow again, waiting longer each
1058
+ * time up to RETRY_MAX_MS. A run whose session is gone ends at once.
1059
+ *
1060
+ * A run's shared-sandbox children are sessions of their own, and each reply
1061
+ * comes back to the run as a new turn. So an end other than a Stop waits
1062
+ * while a child works or a turn waits, and looks again every
1063
+ * CHILDREN_WAIT_MS in case a child ends without a reply.
1064
+ */
1065
+ watch(id, onEvent) {
1066
+ let fold = NEW_FOLD;
1067
+ let stopped = false;
1068
+ let live = null;
1069
+ let waits = 0;
1070
+ const stop = () => {
1071
+ stopped = true;
1072
+ live?.abort();
1073
+ };
1074
+ const end = async (event) => {
1075
+ if (event.error !== "interrupted" && await this.working(id)) {
1076
+ if (stopped) return;
1077
+ fold = { ...fold, ended: false };
1078
+ const wait = ++waits;
1079
+ await sleep(CHILDREN_WAIT_MS);
1080
+ if (stopped || fold.ended || wait !== waits) return;
1081
+ const again = runEnd(fold, this.harness);
1082
+ if (!again) return;
1083
+ fold = { ...fold, ended: true };
1084
+ return end(again);
1085
+ }
1086
+ if (stopped) return;
1087
+ stop();
1088
+ onEvent(await this.tidy(id, event));
1089
+ };
1090
+ const take = (records) => {
1091
+ if (stopped || !records.length) return;
1092
+ const next = foldRecords(fold, records, {
1093
+ harness: this.harness,
1094
+ now: this.now(),
1095
+ progressMs: this.deps.progressMs
1096
+ });
1097
+ fold = next.state;
1098
+ for (const event of next.events) {
1099
+ if (stopped) return;
1100
+ if (event.kind === "settled" || event.kind === "failed") {
1101
+ void end(event);
1102
+ return;
1103
+ }
1104
+ onEvent(event);
1105
+ }
1106
+ };
1107
+ const follow = async () => {
1108
+ try {
1109
+ await this.preparing.get(id);
1110
+ } catch (err) {
1111
+ stop();
1112
+ onEvent(unpreparedEnd(this.harness, err));
1113
+ return;
1114
+ }
1115
+ let wait = this.deps.retryMs ?? RETRY_MIN_MS;
1116
+ while (!stopped) {
1117
+ try {
1118
+ const missed = [];
1119
+ for (let after = fold.after; ; ) {
1120
+ const page = await this.core.events(id, after);
1121
+ missed.push(...page);
1122
+ if (page.length < EVENTS_PAGE) break;
1123
+ after = page.at(-1)?.sequence ?? after;
1124
+ }
1125
+ take(missed);
1126
+ if (stopped) return;
1127
+ if (fold.start?.state === "completed" && !fold.turns.length && !this.preparing.has(id)) {
1128
+ stop();
1129
+ onEvent({ kind: "failed", summary: UNSENT_SUMMARY });
1130
+ return;
1131
+ }
1132
+ live = new AbortController();
1133
+ await this.core.stream(id, fold.after, (r) => take([r]), live.signal);
1134
+ wait = this.deps.retryMs ?? RETRY_MIN_MS;
1135
+ } catch (err) {
1136
+ if (stopped) return;
1137
+ if (err instanceof CoreError && err.status === 404) {
1138
+ stop();
1139
+ onEvent({ kind: "failed", summary: GONE_SUMMARY });
1140
+ return;
1141
+ }
1142
+ this.log(
1143
+ `follow failed thread=${id}: ${err instanceof Error ? err.message : String(err)}; again in ${wait} ms`
1144
+ );
1145
+ }
1146
+ await sleep(wait);
1147
+ wait = Math.min(wait * 2, RETRY_MAX_MS);
1148
+ }
1149
+ };
1150
+ void follow();
1151
+ return stop;
1152
+ }
1153
+ /**
1154
+ * Refuse at once every child spawned without `--shared-sandbox`. Core
1155
+ * would run it here after 15 s anyway; the refusal makes the agent add
1156
+ * the flag now. Core decides each spawn once, so a refusal is never
1157
+ * tried again.
1158
+ */
1159
+ refuseOwnSandboxChildren(opts = {}) {
1160
+ const cursors = /* @__PURE__ */ new Map();
1161
+ let stopped = false;
1162
+ let first = true;
1163
+ const readOne = async (s) => {
1164
+ const last = s.last_sequence ?? 0;
1165
+ let after = cursors.get(s.session_id) ?? (first ? last : 0);
1166
+ while (after < last && !stopped) {
1167
+ const page = await this.core.events(s.session_id, after);
1168
+ for (const r of page) {
1169
+ after = r.sequence;
1170
+ cursors.set(s.session_id, after);
1171
+ if (r.kind !== "child_request" || !r.child) continue;
1172
+ const outcome = await this.core.answerChild(s.session_id, r.child, { error: SHARED_SANDBOX_ONLY }).then(
1173
+ () => "refused",
1174
+ (err) => `not refused: ${err instanceof Error ? err.message : String(err)}`
1175
+ );
1176
+ this.log(`child ${r.child} of session=${s.session_id} ${outcome}`);
1177
+ }
1178
+ if (page.length < EVENTS_PAGE) break;
1179
+ }
1180
+ cursors.set(s.session_id, after);
1181
+ };
1182
+ const loop = async () => {
1183
+ while (!stopped) {
1184
+ try {
1185
+ for (const s of await this.sessions()) {
1186
+ if (stopped) return;
1187
+ await readOne(s);
1188
+ }
1189
+ first = false;
1190
+ } catch (err) {
1191
+ this.log(`children read failed: ${err instanceof Error ? err.message : String(err)}`);
1192
+ }
1193
+ await sleep(opts.pollMs ?? CHILDREN_POLL_MS);
1194
+ }
1195
+ };
1196
+ void loop();
1197
+ return () => {
1198
+ stopped = true;
1199
+ };
1200
+ }
1201
+ /**
1202
+ * This harness's sessions. A Cloop Box runs a daemon per harness against
1203
+ * one core, and each runner row counts and lists only its own.
1204
+ */
1205
+ async sessions() {
1206
+ return (await this.core.sessions()).filter((s) => s.harness === this.harness);
1207
+ }
1208
+ /** A shared-sandbox child of the run works, or the run has a turn waiting. A failed read counts as neither, so it never holds a run open. */
1209
+ async working(id) {
1210
+ try {
1211
+ return (await this.core.sessions()).some(
1212
+ (s) => (s.session_id === id || s.parent_session === id) && busy(s)
1213
+ );
1214
+ } catch (err) {
1215
+ this.log(
1216
+ `children read failed thread=${id}: ${err instanceof Error ? err.message : String(err)}`
1217
+ );
1218
+ return false;
1219
+ }
1220
+ }
1221
+ async session(id) {
1222
+ const s = await this.core.session(id);
1223
+ if (!s) throw new BoxToolError("bad_args");
1224
+ return s;
1225
+ }
1226
+ /** The whole history, folded. */
1227
+ async history(id) {
1228
+ const records = [];
1229
+ for (let after = 0; ; ) {
1230
+ const page = await this.core.events(id, after);
1231
+ records.push(...page);
1232
+ if (page.length < EVENTS_PAGE) break;
1233
+ after = page.at(-1)?.sequence ?? after;
1234
+ }
1235
+ return foldRecords(NEW_FOLD, records, { harness: this.harness, now: this.now() }).state;
1236
+ }
1237
+ };
1238
+
1239
+ // src/drivers/local-usage.ts
1240
+ import { spawn as spawn2 } from "child_process";
1241
+ import { createReadStream } from "fs";
1242
+ import { readdir, realpath, stat } from "fs/promises";
1243
+ import { homedir, hostname, tmpdir } from "os";
1244
+ import { join as join2 } from "path";
1245
+ import { createInterface } from "readline";
1246
+ var PROBE_TIMEOUT_MS = 1e4;
1247
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1248
+ var count = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0;
1249
+ var parse = (line) => {
1250
+ try {
1251
+ return JSON.parse(line);
1252
+ } catch {
1253
+ return void 0;
1254
+ }
1255
+ };
1256
+ function askHarness(bin, args, requests, answer, timeoutMs = PROBE_TIMEOUT_MS) {
1257
+ const command = commandFor(bin, args);
1258
+ return new Promise((resolve, reject) => {
1259
+ const child = spawn2(command.file, command.args, {
1260
+ cwd: tmpdir(),
1261
+ stdio: ["pipe", "pipe", "ignore"],
1262
+ env: process.env,
1263
+ windowsHide: true,
1264
+ ...command.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
1265
+ });
1266
+ let settled = false;
1267
+ const finish = (err, value) => {
1268
+ if (settled) return;
1269
+ settled = true;
1270
+ clearTimeout(timer);
1271
+ child.stdin?.end();
1272
+ child.kill();
1273
+ setTimeout(() => {
1274
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
1275
+ }, 2e3).unref();
1276
+ if (err) reject(err);
1277
+ else resolve(value);
1278
+ };
1279
+ const timer = setTimeout(
1280
+ () => finish(new Error(`no answer in ${timeoutMs / 1e3} s`)),
1281
+ timeoutMs
1282
+ );
1283
+ child.on("error", (err) => finish(err));
1284
+ child.on("close", () => finish(new Error("it exited before it answered")));
1285
+ child.stdin?.on("error", () => {
1286
+ });
1287
+ createInterface({ input: child.stdout }).on("line", (line) => {
1288
+ const msg = parse(line);
1289
+ const value = isObject(msg) ? answer(msg) : void 0;
1290
+ if (value !== void 0) finish(null, value);
1291
+ });
1292
+ child.stdin?.write(requests.map((r) => `${JSON.stringify(r)}
1293
+ `).join(""));
1294
+ });
1295
+ }
1296
+ var reason = (err) => err?.message ?? "the probe failed";
1297
+ async function probeClaudeQuota(bin = "claude", timeoutMs = PROBE_TIMEOUT_MS) {
1298
+ const args = [
1299
+ "--print",
1300
+ "--verbose",
1301
+ "--output-format",
1302
+ "stream-json",
1303
+ "--input-format",
1304
+ "stream-json",
1305
+ "--settings",
1306
+ JSON.stringify({ disableAllHooks: true }),
1307
+ "--strict-mcp-config",
1308
+ "--no-session-persistence",
1309
+ "--disable-slash-commands"
1310
+ ];
1311
+ const request = (id, request2) => ({
1312
+ type: "control_request",
1313
+ request_id: id,
1314
+ request: request2
1315
+ });
1316
+ try {
1317
+ const response = await askHarness(
1318
+ bin,
1319
+ args,
1320
+ [
1321
+ request("cloop-init", { subtype: "initialize" }),
1322
+ request("cloop-usage", { subtype: "get_usage", skip_behaviors: true })
1323
+ ],
1324
+ (msg) => {
1325
+ const r = msg.type === "control_response" ? msg.response : void 0;
1326
+ return isObject(r) && r.request_id === "cloop-usage" ? r : void 0;
1327
+ },
1328
+ timeoutMs
1329
+ );
1330
+ return quotaFromClaude(response, (/* @__PURE__ */ new Date()).toISOString());
1331
+ } catch (err) {
1332
+ return quotaFromClaude({ subtype: "error", error: reason(err) }, (/* @__PURE__ */ new Date()).toISOString());
1333
+ }
1334
+ }
1335
+ async function probeCodexQuota(bin = "codex", timeoutMs = PROBE_TIMEOUT_MS) {
1336
+ try {
1337
+ const answer = await askHarness(
1338
+ bin,
1339
+ ["app-server"],
1340
+ [
1341
+ {
1342
+ id: 1,
1343
+ method: "initialize",
1344
+ params: { clientInfo: { name: "cloop-runner", version: VERSION } }
1345
+ },
1346
+ { method: "initialized" },
1347
+ { id: 2, method: "account/rateLimits/read" }
1348
+ ],
1349
+ (msg) => msg.id === 2 ? msg : void 0,
1350
+ timeoutMs
1351
+ );
1352
+ return quotaFromCodex(answer, (/* @__PURE__ */ new Date()).toISOString());
1353
+ } catch (err) {
1354
+ return quotaFromCodex({ error: { message: reason(err) } }, (/* @__PURE__ */ new Date()).toISOString());
1355
+ }
1356
+ }
1357
+ async function listLogs(dir, depth, match, found) {
1358
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
1359
+ const path = join2(dir, entry.name);
1360
+ if (entry.isFile() && match(entry.name)) found.files.push(path);
1361
+ else if (entry.isDirectory() && depth > 1)
1362
+ await listLogs(path, depth - 1, match, found).catch(() => {
1363
+ found.skipped++;
1364
+ });
1365
+ }
1366
+ }
1367
+ async function readLines(file, read) {
1368
+ let malformed = 0;
1369
+ let lastBad = false;
1370
+ const lines = createInterface({
1371
+ input: createReadStream(file, "utf-8"),
1372
+ crlfDelay: Number.POSITIVE_INFINITY
1373
+ });
1374
+ for await (const line of lines) {
1375
+ lastBad = !read(line);
1376
+ if (lastBad) malformed++;
1377
+ }
1378
+ return lastBad ? malformed - 1 : malformed;
1379
+ }
1380
+ function dayOf(v) {
1381
+ const ms = typeof v === "string" ? Date.parse(v) : Number.NaN;
1382
+ return Number.isFinite(ms) ? new Date(ms).toISOString().slice(0, 10) : null;
1383
+ }
1384
+ var inWindow = (day, w) => day >= w.sinceDay && day <= w.untilDay;
1385
+ function claudeReader(window, days) {
1386
+ const calls = /* @__PURE__ */ new Map();
1387
+ return {
1388
+ read: (line) => {
1389
+ if (!line.includes('"assistant"')) return true;
1390
+ const d = parse(line);
1391
+ if (d === void 0) return false;
1392
+ if (!isObject(d) || d.type !== "assistant") return true;
1393
+ const m = d.message;
1394
+ const u = isObject(m) ? m.usage : void 0;
1395
+ if (!isObject(m) || !isObject(u) || m.model === "<synthetic>") return true;
1396
+ const day = dayOf(d.timestamp);
1397
+ if (!day) return false;
1398
+ if (!inWindow(day, window)) return true;
1399
+ const details = isObject(u.output_tokens_details) ? u.output_tokens_details : {};
1400
+ const call = {
1401
+ day,
1402
+ uncached: count(u.input_tokens),
1403
+ cached: count(u.cache_read_input_tokens),
1404
+ creation: count(u.cache_creation_input_tokens),
1405
+ output: count(u.output_tokens),
1406
+ reasoning: count(details.thinking_tokens),
1407
+ records: 1
1408
+ };
1409
+ if (typeof m.id !== "string") addTokens(days, day, "claude", call);
1410
+ else {
1411
+ const key = `${m.id} ${String(d.requestId ?? "")}`;
1412
+ const seen2 = calls.get(key);
1413
+ if (!seen2 || call.output >= seen2.output) calls.set(key, call);
1414
+ }
1415
+ return true;
1416
+ },
1417
+ finish: () => {
1418
+ for (const call of calls.values()) addTokens(days, call.day, "claude", call);
1419
+ }
1420
+ };
1421
+ }
1422
+ function codexReader(window, days) {
1423
+ return () => {
1424
+ let prev = { input: 0, cached: 0, write: 0, output: 0, reasoning: 0 };
1425
+ return (line) => {
1426
+ if (!line.includes('"token_count"')) return true;
1427
+ const d = parse(line);
1428
+ if (d === void 0) return false;
1429
+ const p = isObject(d) ? d.payload : void 0;
1430
+ if (!isObject(p) || p.type !== "token_count") return true;
1431
+ if (p.info === null || p.info === void 0) return true;
1432
+ const t = isObject(p.info) ? p.info.total_token_usage : void 0;
1433
+ const day = isObject(d) ? dayOf(d.timestamp) : null;
1434
+ if (!isObject(t) || !day) return false;
1435
+ const cur = {
1436
+ input: count(t.input_tokens),
1437
+ cached: count(t.cached_input_tokens),
1438
+ write: count(t.cache_write_input_tokens),
1439
+ output: count(t.output_tokens),
1440
+ reasoning: count(t.reasoning_output_tokens)
1441
+ };
1442
+ if (cur.input + cur.output <= prev.input + prev.output) return true;
1443
+ const rise = (k) => Math.max(0, cur[k] - prev[k]);
1444
+ if (inWindow(day, window))
1445
+ addTokens(days, day, "codex", {
1446
+ uncached: Math.max(0, rise("input") - rise("cached") - rise("write")),
1447
+ cached: rise("cached"),
1448
+ creation: rise("write"),
1449
+ output: rise("output"),
1450
+ reasoning: rise("reasoning"),
1451
+ records: 1
1452
+ });
1453
+ prev = cur;
1454
+ return true;
1455
+ };
1456
+ };
1457
+ }
1458
+ async function scanSource(source, sinceMs) {
1459
+ const key = sourceKey([
1460
+ hostname(),
1461
+ source.provider,
1462
+ await realpath(source.home).catch(() => source.home)
1463
+ ]);
1464
+ const base = { source_key: key, provider: source.provider };
1465
+ const found = { files: [], skipped: 0 };
1466
+ for (const [i, root] of source.roots.entries()) {
1467
+ try {
1468
+ await listLogs(root.dir, root.depth, source.match, found);
1469
+ } catch (err) {
1470
+ const code = err.code;
1471
+ if (i > 0 && code === "ENOENT") continue;
1472
+ const empty = { scanned_files: 0, skipped_files: 0, malformed_records: 0 };
1473
+ return code === "ENOENT" ? { ...base, status: "missing", ...empty } : {
1474
+ ...base,
1475
+ status: "failed",
1476
+ ...empty,
1477
+ message: `The log folder could not be read (${code ?? "error"}).`
1478
+ };
1479
+ }
1480
+ }
1481
+ let scanned = 0;
1482
+ let skipped = found.skipped;
1483
+ let malformed = 0;
1484
+ for (const file of found.files) {
1485
+ try {
1486
+ if ((await stat(file)).mtimeMs < sinceMs) continue;
1487
+ malformed += await readLines(file, source.reader());
1488
+ scanned++;
1489
+ } catch {
1490
+ skipped++;
1491
+ }
1492
+ }
1493
+ return {
1494
+ ...base,
1495
+ status: skipped || malformed ? "partial" : "ok",
1496
+ scanned_files: scanned,
1497
+ skipped_files: skipped,
1498
+ malformed_records: malformed
1499
+ };
1500
+ }
1501
+ async function scanTokenUsage(opts = {}) {
1502
+ const window = utcWindow(opts.now ?? Date.now(), TOKEN_DAYS);
1503
+ const sinceMs = Date.parse(`${window.sinceDay}T00:00:00Z`);
1504
+ const days = /* @__PURE__ */ new Map();
1505
+ const claudeHome = opts.claudeHome ?? (process.env.CLAUDE_CONFIG_DIR || join2(homedir(), ".claude"));
1506
+ const codexHome = opts.codexHome ?? (process.env.CODEX_HOME || join2(homedir(), ".codex"));
1507
+ const claude = claudeReader(window, days);
1508
+ const sources = [
1509
+ await scanSource(
1510
+ {
1511
+ provider: "claude",
1512
+ home: claudeHome,
1513
+ // projects/<project>/<session>.jsonl and projects/<project>/<session>/subagents/agent-*.jsonl
1514
+ roots: [{ dir: join2(claudeHome, "projects"), depth: 4 }],
1515
+ match: (name) => name.endsWith(".jsonl"),
1516
+ reader: () => claude.read
1517
+ },
1518
+ sinceMs
1519
+ ),
1520
+ await scanSource(
1521
+ {
1522
+ provider: "codex",
1523
+ home: codexHome,
1524
+ roots: [
1525
+ { dir: join2(codexHome, "sessions"), depth: 4 },
1526
+ { dir: join2(codexHome, "archived_sessions"), depth: 1 }
1527
+ ],
1528
+ match: (name) => name.startsWith("rollout-") && name.endsWith(".jsonl"),
1529
+ reader: codexReader(window, days)
1530
+ },
1531
+ sinceMs
1532
+ )
1533
+ ];
1534
+ claude.finish();
1535
+ const partial = sources.some((s) => s.status === "partial" || s.status === "failed");
1536
+ return {
1537
+ status: partial ? "partial" : "ok",
1538
+ scope: TOKEN_SCOPE,
1539
+ window: { since_day: window.sinceDay, until_day: window.untilDay, time_zone: "UTC" },
1540
+ read_at: (/* @__PURE__ */ new Date()).toISOString(),
1541
+ by_day: sortedDays(days),
1542
+ sources
1543
+ };
1544
+ }
1545
+ var LocalUsage = class {
1546
+ constructor(deps) {
1547
+ this.deps = deps;
1548
+ this.tokens = new BackgroundReading({
1549
+ ttlMs: TOKEN_TTL_MS,
1550
+ read: () => this.scan(),
1551
+ now: deps.now
1552
+ });
1553
+ }
1554
+ deps;
1555
+ quotas = /* @__PURE__ */ new Map();
1556
+ tokens;
1557
+ /** The quota of a signed-in harness, probed at most once per harness check period. */
1558
+ quota(harness) {
1559
+ const probe = this.deps.probes[harness];
1560
+ if (!probe) return { status: "not_reported" };
1561
+ let reading = this.quotas.get(harness);
1562
+ if (!reading) {
1563
+ reading = new BackgroundReading({
1564
+ ttlMs: HARNESS_STALE_MS,
1565
+ read: async () => {
1566
+ const q = await probe();
1567
+ if (q.status === "probe_failed")
1568
+ this.deps.log?.(`quota probe failed harness=${harness}: ${q.message ?? ""}`);
1569
+ return q;
1570
+ },
1571
+ now: this.deps.now
1572
+ });
1573
+ this.quotas.set(harness, reading);
1574
+ }
1575
+ return reading.get();
1576
+ }
1577
+ /** Token counts from the last log scan, rescanned at most every TOKEN_TTL_MS. */
1578
+ tokenUsage() {
1579
+ return this.tokens.get();
1580
+ }
1581
+ async scan() {
1582
+ const now = this.deps.now ?? Date.now;
1583
+ const started = now();
1584
+ try {
1585
+ const usage = await (this.deps.scan ?? scanTokenUsage)();
1586
+ this.deps.log?.(`token scan took ${now() - started} ms status=${usage.status}`);
1587
+ return usage;
1588
+ } catch (err) {
1589
+ this.deps.log?.(`token scan failed: ${err?.message}`);
1590
+ return { status: "unavailable", reason: "The agent logs could not be read" };
1591
+ }
1592
+ }
1593
+ };
1594
+
1595
+ // src/outside-sessions.ts
1596
+ import { createReadStream as createReadStream2 } from "fs";
1597
+ import { readdir as readdir2, stat as stat2 } from "fs/promises";
1598
+ import { homedir as homedir2 } from "os";
1599
+ import { join as join3 } from "path";
1600
+ import { createInterface as createInterface2 } from "readline";
1601
+ var seen = /* @__PURE__ */ new Map();
1602
+ var UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
1603
+ async function listOutsideSessions(root = join3(homedir2(), ".claude", "projects"), own = /* @__PURE__ */ new Set(), now = Date.now()) {
1604
+ const files = [];
1605
+ for (const project of await readdir2(root, { withFileTypes: true }).catch(() => [])) {
1606
+ if (!project.isDirectory()) continue;
1607
+ for (const entry of await readdir2(join3(root, project.name), { withFileTypes: true }).catch(
1608
+ () => []
1609
+ )) {
1610
+ if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
1611
+ const id = entry.name.slice(0, -6);
1612
+ if (!UUID.test(id) || own.has(id)) continue;
1613
+ const path = join3(root, project.name, entry.name);
1614
+ const info = await stat2(path).catch(() => null);
1615
+ if (info && info.mtimeMs >= now - 7 * 864e5)
1616
+ files.push({ id, project: project.name.slice(0, 200), file: path, mtime: info.mtimeMs });
1617
+ }
1618
+ }
1619
+ const results = [];
1620
+ const newest = files.sort((a, b) => b.mtime - a.mtime).slice(0, 20);
1621
+ for (const path of seen.keys()) if (!newest.some((file) => file.file === path)) seen.delete(path);
1622
+ for (const file of newest) {
1623
+ const known = seen.get(file.file);
1624
+ let title = known?.mtime === file.mtime ? known.title : void 0;
1625
+ let cwd = known?.mtime === file.mtime ? known.cwd : void 0;
1626
+ if (known?.mtime !== file.mtime) {
1627
+ const stream = createReadStream2(file.file, { encoding: "utf8" });
1628
+ const lines = createInterface2({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });
1629
+ try {
1630
+ for await (const line of lines) {
1631
+ if (!cwd && line.includes('"cwd"')) {
1632
+ try {
1633
+ const record = JSON.parse(line);
1634
+ if (typeof record.cwd === "string" && record.cwd.startsWith("/") && record.cwd.length <= 500)
1635
+ cwd = record.cwd;
1636
+ } catch {
1637
+ }
1638
+ }
1639
+ if (!/^\s*\{\s*"type"\s*:\s*"(?:summary|custom-title|title)"/.test(line)) continue;
1640
+ try {
1641
+ const record = JSON.parse(line);
1642
+ const value = record.type === "summary" ? record.summary : record.type === "custom-title" ? record.customTitle : record.title;
1643
+ if (typeof value === "string" && value.trim()) title = value.trim().slice(0, 120);
1644
+ } catch {
1645
+ }
1646
+ }
1647
+ } finally {
1648
+ lines.close();
1649
+ stream.destroy();
1650
+ }
1651
+ seen.set(file.file, {
1652
+ mtime: file.mtime,
1653
+ ...title ? { title } : {},
1654
+ ...cwd ? { cwd } : {}
1655
+ });
1656
+ }
1657
+ results.push({
1658
+ id: file.id,
1659
+ project: file.project,
1660
+ updatedAt: new Date(file.mtime).toISOString(),
1661
+ status: "idle",
1662
+ ...cwd ? { cwd } : {},
1663
+ ...title ? { title } : {}
1664
+ });
1665
+ }
1666
+ return results;
1667
+ }
1668
+
1669
+ // src/setup-share.ts
1670
+ import { spawn as spawn3 } from "child_process";
1671
+ import {
1672
+ copyFileSync,
1673
+ existsSync as existsSync2,
1674
+ mkdirSync as mkdirSync2,
1675
+ mkdtempSync,
1676
+ readFileSync,
1677
+ readdirSync,
1678
+ realpathSync,
1679
+ rmSync as rmSync2,
1680
+ symlinkSync
1681
+ } from "fs";
1682
+ import { homedir as homedir3, tmpdir as tmpdir2 } from "os";
1683
+ import { join as join4 } from "path";
1684
+ var SKILL_DIRS = [".agents/skills", ".claude/skills", ".codex/skills"];
1685
+ var GUIDE_FILES = [".agents/AGENTS.md", ".claude/CLAUDE.md", ".codex/AGENTS.md"];
1686
+ var SKILLS_CAP_BYTES = 25 * 1024 * 1024;
1687
+ function realpath2(path) {
1688
+ try {
1689
+ return realpathSync(path);
1690
+ } catch {
1691
+ return null;
1692
+ }
1693
+ }
1694
+ function findSetup(home) {
1695
+ const names = /* @__PURE__ */ new Set();
1696
+ const reals = /* @__PURE__ */ new Set();
1697
+ const skills = [];
1698
+ for (const dir of SKILL_DIRS) {
1699
+ let entries;
1700
+ try {
1701
+ entries = readdirSync(join4(home, dir)).sort();
1702
+ } catch {
1703
+ continue;
1704
+ }
1705
+ for (const name of entries) {
1706
+ const path = join4(home, dir, name);
1707
+ if (names.has(name) || !existsSync2(join4(path, "SKILL.md"))) continue;
1708
+ const real = realpath2(path);
1709
+ if (!real || reals.has(real)) continue;
1710
+ names.add(name);
1711
+ reals.add(real);
1712
+ skills.push({ name, path: real });
1713
+ }
1714
+ }
1715
+ const guide = GUIDE_FILES.map((file) => realpath2(join4(home, file))).find((p) => p !== null) ?? null;
1716
+ return { skills, guide };
1717
+ }
1718
+ function stage(setup) {
1719
+ const dir = mkdtempSync(join4(tmpdir2(), "cloop-setup-"));
1720
+ mkdirSync2(join4(dir, ".agents", "skills"), { recursive: true });
1721
+ for (const skill of setup.skills)
1722
+ symlinkSync(skill.path, join4(dir, ".agents", "skills", skill.name), "junction");
1723
+ if (setup.guide) copyFileSync(setup.guide, join4(dir, ".agents", "owner-guide.md"));
1724
+ return dir;
1725
+ }
1726
+ async function packSkills(home = homedir3(), capBytes = SKILLS_CAP_BYTES, tarBin = "tar") {
1727
+ const setup = findSetup(home);
1728
+ if (setup.skills.length === 0 && !setup.guide) return { ok: false, reason: "no_skills" };
1729
+ let dir;
1730
+ try {
1731
+ dir = stage(setup);
1732
+ } catch {
1733
+ return { ok: false, reason: "tar_failed" };
1734
+ }
1735
+ const packed = await new Promise((resolve) => {
1736
+ const child = spawn3(
1737
+ tarBin,
1738
+ [
1739
+ "-c",
1740
+ "-z",
1741
+ "-h",
1742
+ "--exclude",
1743
+ ".git",
1744
+ "--exclude",
1745
+ "node_modules",
1746
+ "-f",
1747
+ "-",
1748
+ "-C",
1749
+ dir,
1750
+ ".agents"
1751
+ ],
1752
+ { stdio: ["ignore", "pipe", "ignore"] }
1753
+ );
1754
+ const chunks = [];
1755
+ let bytes = 0;
1756
+ let over = false;
1757
+ child.stdout.on("data", (chunk) => {
1758
+ if (over) return;
1759
+ bytes += chunk.byteLength;
1760
+ if (bytes > capBytes) {
1761
+ over = true;
1762
+ child.kill("SIGKILL");
1763
+ return;
1764
+ }
1765
+ chunks.push(chunk);
1766
+ });
1767
+ child.on("error", () => resolve({ ok: false, reason: "tar_failed" }));
1768
+ child.on("close", (code) => {
1769
+ if (over) return resolve({ ok: false, reason: "too_large" });
1770
+ if (code !== 0 && code !== 1 || bytes === 0)
1771
+ return resolve({ ok: false, reason: "tar_failed" });
1772
+ resolve({
1773
+ ok: true,
1774
+ tar: Buffer.concat(chunks),
1775
+ skills: setup.skills.length,
1776
+ guide: Boolean(setup.guide)
1777
+ });
1778
+ });
1779
+ });
1780
+ rmSync2(dir, { recursive: true, force: true });
1781
+ return packed;
1782
+ }
1783
+ var RESERVED_MCP = /* @__PURE__ */ new Set(["cloop", "playwright"]);
1784
+ var MAX_REMOTE_MCP = 20;
1785
+ function mcpName(raw) {
1786
+ const name = raw.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/-{2,}/g, "-").replace(/^-+/, "").slice(0, 40).replace(/-+$/, "");
1787
+ return name && !RESERVED_MCP.has(name) ? name : null;
1788
+ }
1789
+ function urlCarriesSecret(url) {
1790
+ if (url.search || url.hash || url.username || url.password) return true;
1791
+ return url.pathname.split("/").some((part) => part.length >= 20 && /\d/.test(part) && /[a-z]/i.test(part));
1792
+ }
1793
+ function httpUrl(raw) {
1794
+ if (typeof raw !== "string") return null;
1795
+ try {
1796
+ const url = new URL(raw);
1797
+ if (url.protocol !== "https:" && url.protocol !== "http:") return null;
1798
+ return urlCarriesSecret(url) ? null : url.toString();
1799
+ } catch {
1800
+ return null;
1801
+ }
1802
+ }
1803
+ function claudeRemoteMcp(raw) {
1804
+ let config;
1805
+ try {
1806
+ config = JSON.parse(raw);
1807
+ } catch {
1808
+ return [];
1809
+ }
1810
+ const found = [];
1811
+ const take = (servers) => {
1812
+ if (!servers || typeof servers !== "object") return;
1813
+ for (const [name, entry] of Object.entries(servers)) {
1814
+ const e = entry ?? {};
1815
+ if (e.type !== "http" && e.type !== "sse") continue;
1816
+ const headers = e.headers && typeof e.headers === "object" ? Object.keys(e.headers) : [];
1817
+ found.push({ name, url: e.url, keyed: headers.length > 0 || Boolean(e.headersHelper) });
1818
+ }
1819
+ };
1820
+ const c = config ?? {};
1821
+ take(c.mcpServers);
1822
+ if (c.projects && typeof c.projects === "object") {
1823
+ for (const project of Object.values(c.projects))
1824
+ take(project?.mcpServers);
1825
+ }
1826
+ return found;
1827
+ }
1828
+ function tomlKey(raw) {
1829
+ const key = raw.trim();
1830
+ return /^".*"$|^'.*'$/.test(key) ? key.slice(1, -1) : key;
1831
+ }
1832
+ function codexRemoteMcp(raw) {
1833
+ const servers = /* @__PURE__ */ new Map();
1834
+ let current = null;
1835
+ for (const line of raw.split(/\r?\n/)) {
1836
+ const text = line.trim();
1837
+ const table = /^\[\s*mcp_servers\s*\.\s*("[^"]+"|'[^']+'|[A-Za-z0-9_-]+)\s*(?:\.\s*([A-Za-z0-9_-]+)\s*)?\]$/.exec(
1838
+ text
1839
+ );
1840
+ if (table) {
1841
+ const name = tomlKey(table[1]);
1842
+ const server = servers.get(name) ?? { name, url: void 0, keyed: false };
1843
+ servers.set(name, server);
1844
+ if (table[2]) {
1845
+ if (/headers/.test(table[2])) server.keyed = true;
1846
+ current = null;
1847
+ } else current = server;
1848
+ continue;
1849
+ }
1850
+ if (text.startsWith("[")) {
1851
+ current = null;
1852
+ continue;
1853
+ }
1854
+ if (!current) continue;
1855
+ const pair = /^([A-Za-z0-9_-]+)\s*=\s*(.+)$/.exec(text);
1856
+ if (!pair) continue;
1857
+ const [, key, value] = pair;
1858
+ if (key === "url")
1859
+ current.url = /^"([^"]*)"|^'([^']*)'/.exec(value)?.slice(1).find((v) => v !== void 0);
1860
+ if (key === "bearer_token_env_var" || /headers/.test(key)) current.keyed = true;
1861
+ }
1862
+ return [...servers.values()];
1863
+ }
1864
+ function remoteMcp(found) {
1865
+ const byUrl = /* @__PURE__ */ new Map();
1866
+ for (const entry of found) {
1867
+ const url = httpUrl(entry.url);
1868
+ const name = mcpName(entry.name);
1869
+ if (!url || !name) continue;
1870
+ const seen2 = byUrl.get(url);
1871
+ if (seen2) seen2.keyed ||= entry.keyed;
1872
+ else byUrl.set(url, { name, url, keyed: entry.keyed });
1873
+ }
1874
+ return [...byUrl.values()].slice(0, MAX_REMOTE_MCP);
1875
+ }
1876
+ function readText(path) {
1877
+ try {
1878
+ return readFileSync(path, "utf8");
1879
+ } catch {
1880
+ return "";
1881
+ }
1882
+ }
1883
+ function readRemoteMcp(home = homedir3(), codexHome = process.env.CODEX_HOME || join4(home, ".codex")) {
1884
+ return remoteMcp([
1885
+ ...claudeRemoteMcp(readText(join4(home, ".claude.json"))),
1886
+ ...codexRemoteMcp(readText(join4(codexHome, "config.toml")))
1887
+ ]);
1888
+ }
1889
+ async function sendSkills(tar, deps) {
1890
+ try {
1891
+ const res = await (deps.fetchFn ?? fetch)(`${deps.origin}/api/agent/mesh/box-skills`, {
1892
+ method: "POST",
1893
+ headers: {
1894
+ "content-type": "application/gzip",
1895
+ authorization: `Bearer ${deps.deviceToken()}`
1896
+ },
1897
+ body: new Uint8Array(tar),
1898
+ // A sleeping box wakes, restores its archive, then unpacks.
1899
+ signal: AbortSignal.timeout(5 * 6e4)
1900
+ });
1901
+ const body = await res.json().catch(() => null);
1902
+ if (!res.ok) {
1903
+ deps.log(`[runner:skills] box refused status=${res.status}`);
1904
+ return null;
1905
+ }
1906
+ return typeof body?.skills === "number" ? body.skills : null;
1907
+ } catch (err) {
1908
+ deps.log(`[runner:skills] unreachable ${err instanceof Error ? err.name : "error"}`);
1909
+ return null;
1910
+ }
1911
+ }
1912
+ var SetupShare = class {
1913
+ constructor(deps, pack = () => packSkills(deps.home), mcp = () => readRemoteMcp(deps.home)) {
1914
+ this.deps = deps;
1915
+ this.pack = pack;
1916
+ this.mcp = mcp;
1917
+ }
1918
+ deps;
1919
+ pack;
1920
+ mcp;
1921
+ running = false;
1922
+ async start() {
1923
+ let mcp;
1924
+ try {
1925
+ mcp = this.mcp();
1926
+ } catch {
1927
+ mcp = [];
1928
+ }
1929
+ const skills = await this.startSkills();
1930
+ this.deps.log(
1931
+ `[runner:setup] mcp=${mcp.length} skills=${skills.started ? "sending" : "running" in skills ? "running" : skills.reason}`
1932
+ );
1933
+ return { skills, mcp };
1934
+ }
1935
+ async startSkills() {
1936
+ if (this.running) return { started: false, running: true };
1937
+ this.running = true;
1938
+ let packed;
1939
+ try {
1940
+ packed = await this.pack();
1941
+ } catch {
1942
+ packed = { ok: false, reason: "tar_failed" };
1943
+ }
1944
+ if (!packed.ok) {
1945
+ this.running = false;
1946
+ this.deps.log(`[runner:skills] not sent reason=${packed.reason}`);
1947
+ return { started: false, reason: packed.reason };
1948
+ }
1949
+ const { tar, skills } = packed;
1950
+ void sendSkills(tar, this.deps).then(
1951
+ (inBox) => this.deps.log(
1952
+ `[runner:skills] sent skills=${skills} bytes=${tar.byteLength} ${inBox === null ? "failed" : `box_has=${inBox}`}`
1953
+ )
1954
+ ).finally(() => {
1955
+ this.running = false;
1956
+ });
1957
+ return { started: true, skills, bytes: tar.byteLength };
1958
+ }
1959
+ };
1960
+
1961
+ // src/update.ts
1962
+ import { execFile as execFile2, spawn as spawn4 } from "child_process";
1963
+ import {
1964
+ closeSync,
1965
+ mkdirSync as mkdirSync3,
1966
+ openSync,
1967
+ readFileSync as readFileSync2,
1968
+ renameSync as renameSync2,
1969
+ rmSync as rmSync3,
1970
+ writeFileSync
1971
+ } from "fs";
1972
+ import { homedir as homedir4 } from "os";
1973
+ import { dirname, join as join5 } from "path";
1974
+ var REGISTRY_LATEST = "https://registry.npmjs.org/@cloop/runner/latest";
1975
+ var FIRST_CHECK_MS = 10 * 6e4;
1976
+ var CHECK_EVERY_MS = 6 * 36e5;
1977
+ var ADOPT_WAIT_MS = 3e4;
1978
+ var FETCH_WAIT_MS = 3 * 6e4;
1979
+ var RELEASE = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
1980
+ var log = (line) => console.error(`[workstation:update] ${line}`);
1981
+ function namesVersion(unitText, version) {
1982
+ const escaped = version.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1983
+ return new RegExp(`(?:^|[\\s"'>])@cloop/runner@${escaped}(?=[\\s"'<]|$)`).test(unitText);
1984
+ }
1985
+ function updateDecision(input) {
1986
+ const stay = (why) => ({ kind: "stay", why });
1987
+ if (!input.latest) return stay("no_latest");
1988
+ if (!olderThan(input.current, input.latest)) return stay("current");
1989
+ if (input.latest === input.failed) return stay("failed_before");
1990
+ if (input.unitText === null || !namesVersion(input.unitText, input.current))
1991
+ return stay("not_our_service");
1992
+ if (!input.canDetach) return stay("no_detach");
1993
+ if (input.running > 0 || input.inFlight > 0) return stay("busy");
1994
+ return { kind: "hand_over", to: input.latest };
1995
+ }
1996
+ async function readLatest(get = fetch) {
1997
+ try {
1998
+ const res = await get(REGISTRY_LATEST, { signal: AbortSignal.timeout(5e3) });
1999
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
2000
+ const version = (await res.json()).version;
2001
+ if (typeof version !== "string" || !RELEASE.test(version))
2002
+ throw new Error("no release version");
2003
+ return version;
2004
+ } catch (err) {
2005
+ log(`could not read latest from npm: ${err instanceof Error ? err.message : String(err)}`);
2006
+ return null;
2007
+ }
2008
+ }
2009
+ function updateDir(env) {
2010
+ return runnerPath(env, process.env.CLOOP_UPDATE_DIR, (dir) => dir);
2011
+ }
2012
+ function updateLogPath() {
2013
+ return join5(updateDir(), "update.log");
2014
+ }
2015
+ function statePath(env) {
2016
+ return join5(updateDir(env), "update.json");
2017
+ }
2018
+ function readFailed() {
2019
+ try {
2020
+ const failed = JSON.parse(readFileSync2(statePath(), "utf-8")).failed;
2021
+ return typeof failed === "string" ? failed : null;
2022
+ } catch {
2023
+ return null;
2024
+ }
2025
+ }
2026
+ function recordFailed(version, env) {
2027
+ try {
2028
+ mkdirSync3(updateDir(env), { recursive: true, mode: 448 });
2029
+ const temp = `${statePath(env)}.${process.pid}.tmp`;
2030
+ writeFileSync(temp, `${JSON.stringify({ failed: version })}
2031
+ `, { mode: 384 });
2032
+ renameSync2(temp, statePath(env));
2033
+ } catch (err) {
2034
+ log(`could not record ${version} as failed: ${err.code ?? err}`);
2035
+ }
2036
+ }
2037
+ function handOverCommand(platform, npx, to, kind, script = adoptScriptPath()) {
2038
+ if (platform === "win32")
2039
+ return [
2040
+ "powershell",
2041
+ "-NoProfile",
2042
+ "-NonInteractive",
2043
+ "-Command",
2044
+ [
2045
+ "$ErrorActionPreference = 'Stop'",
2046
+ `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)`
2047
+ ].join("; ")
2048
+ ];
2049
+ const adopt2 = adoptWords(npx, to, kind);
2050
+ return platform === "linux" ? ["systemd-run", "--user", "--scope", "--quiet", "--collect", "--", ...adopt2] : adopt2;
2051
+ }
2052
+ var adoptWords = (npx, to, kind) => [
2053
+ npx,
2054
+ "-y",
2055
+ `@cloop/runner@${to}`,
2056
+ "box",
2057
+ "adopt",
2058
+ "--from",
2059
+ VERSION,
2060
+ "--kind",
2061
+ kind
2062
+ ];
2063
+ function adoptScriptPath() {
2064
+ return join5(updateDir(), "adopt.cmd");
2065
+ }
2066
+ function adoptScript(npx, to, kind, log3) {
2067
+ return [
2068
+ "@echo off",
2069
+ `call ${adoptWords(npx, to, kind).map(cmdWord).join(" ")} >> ${cmdWord(log3)} 2>&1`,
2070
+ ""
2071
+ ].join("\r\n");
2072
+ }
2073
+ function servicePath(kind, platform) {
2074
+ return installedService({
2075
+ platform,
2076
+ kind,
2077
+ environment: runnerEnvironment(),
2078
+ home: homedir4(),
2079
+ uid: process.getuid?.() ?? 0,
2080
+ ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
2081
+ }).path;
2082
+ }
2083
+ function readText2(path) {
2084
+ try {
2085
+ return readFileSync2(path, "utf-8");
2086
+ } catch {
2087
+ return null;
2088
+ }
2089
+ }
2090
+ function fetchVersion(npx, version) {
2091
+ const { file, args, windowsVerbatimArguments } = commandFor(npx, [
2092
+ "-y",
2093
+ `@cloop/runner@${version}`,
2094
+ "--help"
2095
+ ]);
2096
+ return new Promise((resolve) => {
2097
+ execFile2(
2098
+ file,
2099
+ args,
2100
+ { timeout: FETCH_WAIT_MS, ...windowsVerbatimArguments ? { windowsVerbatimArguments } : {} },
2101
+ (err) => {
2102
+ if (err) log(`could not fetch ${version}: ${err.message.split("\n")[0]}`);
2103
+ resolve(!err);
2104
+ }
2105
+ );
2106
+ });
2107
+ }
2108
+ function selfUpdate(kind, platform = process.platform) {
2109
+ let latest = null;
2110
+ let handing = false;
2111
+ let lastWhy = null;
2112
+ const canDetach = platform === "darwin" || platform === "win32" || platform === "linux" && which("systemd-run") !== null;
2113
+ const check = async () => {
2114
+ const read = await readLatest();
2115
+ if (!read || read === latest || !olderThan(VERSION, read) || read === readFailed()) return;
2116
+ const npx = findNpx();
2117
+ if (npx && await fetchVersion(npx, read)) latest = read;
2118
+ };
2119
+ setTimeout(() => {
2120
+ void check();
2121
+ setInterval(() => void check(), CHECK_EVERY_MS).unref();
2122
+ }, FIRST_CHECK_MS).unref();
2123
+ const handOver = (to) => {
2124
+ const npx = findNpx();
2125
+ if (!npx) {
2126
+ log(`npx is not on PATH, so ${to} cannot start`);
2127
+ recordFailed(to);
2128
+ return;
2129
+ }
2130
+ const [command, ...args] = handOverCommand(platform, npx, to, kind);
2131
+ let fd;
2132
+ try {
2133
+ mkdirSync3(updateDir(), { recursive: true, mode: 448 });
2134
+ if (platform === "win32")
2135
+ writeFileSync(adoptScriptPath(), adoptScript(npx, to, kind, updateLogPath()));
2136
+ fd = openSync(updateLogPath(), "a");
2137
+ } catch (err) {
2138
+ log(`could not open ${updateLogPath()}: ${err.code ?? err}`);
2139
+ return;
2140
+ }
2141
+ handing = true;
2142
+ log(`handing over ${VERSION} -> ${to}; its log is ${updateLogPath()}`);
2143
+ const child = spawn4(
2144
+ command,
2145
+ args,
2146
+ platform === "win32" ? { stdio: "ignore", windowsHide: true, env: windowsPowerShellEnv() } : { detached: true, stdio: ["ignore", fd, fd] }
2147
+ );
2148
+ closeSync(fd);
2149
+ child.unref();
2150
+ const failed = (why) => {
2151
+ handing = false;
2152
+ log(`${to} did not take over (${why}); staying on ${VERSION}`);
2153
+ recordFailed(to);
2154
+ };
2155
+ child.on("error", (err) => failed(err.message));
2156
+ child.on("exit", (code, signal) => {
2157
+ if (code !== 0) failed(signal ? `signal ${signal}` : `exit ${code}`);
2158
+ });
2159
+ };
2160
+ return {
2161
+ beat({ running, inFlight }) {
2162
+ if (handing) return;
2163
+ const decision = updateDecision({
2164
+ current: VERSION,
2165
+ latest,
2166
+ unitText: readText2(servicePath(kind, platform)),
2167
+ running,
2168
+ inFlight,
2169
+ failed: readFailed(),
2170
+ canDetach
2171
+ });
2172
+ if (decision.kind === "hand_over") {
2173
+ lastWhy = null;
2174
+ handOver(decision.to);
2175
+ return;
2176
+ }
2177
+ if (decision.why !== lastWhy && latest) log(`staying on ${VERSION}: ${decision.why}`);
2178
+ lastWhy = decision.why;
2179
+ }
2180
+ };
2181
+ }
2182
+ function newDaemon(oldPid, read = readRunnerState) {
2183
+ const state = read();
2184
+ return state && state.pid !== oldPid ? state : null;
2185
+ }
2186
+ async function adopt(from, kind, { services: given, script = process.argv[1] ?? "cloop", npx = findNpx() } = {}) {
2187
+ const environment = runnerEnvironment();
2188
+ const legacy = legacyStagingRunner();
2189
+ const was = legacy ? "production" : environment;
2190
+ const oldPid = readRunnerState(runnerStatePath(was))?.pid;
2191
+ const services = {
2192
+ ...given ?? systemServices,
2193
+ awaitUp: given?.awaitUp ?? ((since2) => awaitDaemon(since2, () => newDaemon(oldPid), { timeoutMs: ADOPT_WAIT_MS }))
2194
+ };
2195
+ const refuse = (why2) => {
2196
+ log(`adopt ${from} -> ${VERSION} refused: ${why2}`);
2197
+ recordFailed(VERSION, was);
2198
+ return 1;
2199
+ };
2200
+ const program = programFor(script, process.execPath, npx, VERSION);
2201
+ if (typeof program === "string") return refuse(program);
2202
+ const where = {
2203
+ platform: services.platform,
2204
+ kind,
2205
+ home: homedir4(),
2206
+ uid: process.getuid?.() ?? 0,
2207
+ ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
2208
+ };
2209
+ const unit = unitFor({ ...where, environment, program, env: serviceEnv() });
2210
+ const back = legacy ? unitFor({ ...where, environment: was, program, env: {} }) : unit;
2211
+ const old = readText2(back.path);
2212
+ if (old === null) return refuse(`${back.path} is missing`);
2213
+ if (!namesVersion(old, from)) return refuse(`${back.path} does not run ${from}`);
2214
+ const run3 = (command) => void services.run(command);
2215
+ const since = Date.now();
2216
+ let why;
2217
+ try {
2218
+ if (legacy) await moveLegacyStagingRunner(services);
2219
+ mkdirSync3(dirname(unit.path), { recursive: true });
2220
+ writeFileSync(unit.path, unit.contents);
2221
+ await runSteps(unit.start, run3);
2222
+ if (await services.awaitUp(since)) {
2223
+ log(`adopt ${from} -> ${VERSION}: up`);
2224
+ return 0;
2225
+ }
2226
+ why = `the new daemon did not reach Cloop within ${ADOPT_WAIT_MS / 1e3} s`;
2227
+ } catch (err) {
2228
+ why = err instanceof Error ? err.message : String(err);
2229
+ }
2230
+ log(`adopt ${from} -> ${VERSION} failed: ${why}; putting ${from} back`);
2231
+ try {
2232
+ if (legacy) {
2233
+ const added = installedService({ ...where, environment });
2234
+ if (!await stopService(added, run3)) throw new Error(`${added.path} did not stop`);
2235
+ rmSync3(added.path, { force: true });
2236
+ moveRunnerFiles(runnerDir(environment), runnerDir(was));
2237
+ }
2238
+ recordFailed(VERSION, was);
2239
+ writeFileSync(back.path, old);
2240
+ await runSteps(back.start, run3);
2241
+ } catch (err) {
2242
+ log(
2243
+ `ROLLBACK FAILED: could not restart ${from} from ${back.path}: ${err instanceof Error ? err.message : String(err)}. Run cloop connect on this machine.`
2244
+ );
2245
+ return 2;
2246
+ }
2247
+ log(`${from} is back`);
2248
+ return 1;
2249
+ }
2250
+
2251
+ // src/commands/box.ts
2252
+ var BEAT_MS = 6e4;
2253
+ var RESEND_MS = 5 * 6e4;
2254
+ var REPAIR_BEFORE_MS = 2 * 24 * 36e5;
2255
+ var EXPIRING_BEFORE_MS = 3 * 24 * 36e5;
2256
+ var out = (line) => console.log(line);
2257
+ var red = (s) => `\x1B[31m${s}\x1B[0m`;
2258
+ var log2 = (line) => console.error(`[workstation:daemon] ${line}`);
2259
+ var REVOKED_CLOSE = 4001;
2260
+ 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.";
2261
+ async function awaitNewDeviceToken(current, read, { tries = 3, delayMs = 2e3 } = {}) {
2262
+ for (let i = 0; i < tries; i++) {
2263
+ const next = read();
2264
+ if (next && next !== current) return next;
2265
+ if (i < tries - 1) await new Promise((r) => setTimeout(r, delayMs));
2266
+ }
2267
+ return null;
2268
+ }
2269
+ function t3Presence(cfg, renewalFailed, now = Date.now()) {
2270
+ const left = Date.parse(cfg.expiresAt) - now;
2271
+ if (Number.isNaN(left)) return null;
2272
+ const state = left <= 0 ? "expired" : renewalFailed ? "renewal_failed" : left < EXPIRING_BEFORE_MS ? "expiring" : "ok";
2273
+ return { expiresAt: cfg.expiresAt, renewable: Boolean(cfg.t3Bin), state };
2274
+ }
2275
+ function boxPresence(beat) {
2276
+ return {
2277
+ session_key: beat.sessionKey,
2278
+ name: beat.hosted ? hostedRunnerName(beat.hosted) : beat.driver === "t3" ? "Cloop box" : "Cloop runner",
2279
+ kind: "workstation",
2280
+ capabilities: [...beat.capabilities],
2281
+ platform: "workstation",
2282
+ machine: beat.machine,
2283
+ surface: {
2284
+ driver: beat.driver,
2285
+ version: VERSION,
2286
+ outsideThreads: beat.outsideThreads,
2287
+ otherThreads: beat.otherThreads,
2288
+ ...beat.t3 ? { t3: beat.t3 } : {},
2289
+ ...beat.hosted ? { harness: beat.hosted } : {}
2290
+ },
2291
+ status: beat.running > 0 ? "active" : "idle",
2292
+ event: beat.running > 0 ? `${beat.running} running` : ""
2293
+ };
2294
+ }
2295
+ async function machineHarnesses(cfg) {
2296
+ const [claude, codex] = await Promise.all([
2297
+ probeClaude(cfg.driver === "claude-code" ? cfg.bin : void 0),
2298
+ probeCodex(cfg.driver === "codex" ? cfg.bin : void 0)
2299
+ ]);
2300
+ return [claude, codex].filter((h) => h !== null);
2301
+ }
2302
+ async function localDriver(cfg, name) {
2303
+ const bin = cfg.driver === name ? cfg.bin : void 0;
2304
+ const claude = async (at) => claudeDialect(
2305
+ at,
2306
+ cfg.fallbackModels ?? DEFAULT_FALLBACK_MODEL,
2307
+ cfg.askEverything,
2308
+ await probeClaudePermissions(at)
2309
+ );
2310
+ const driver = new LocalDriver({
2311
+ dialect: name === "claude-code" ? await claude(bin) : codexDialect(bin),
2312
+ fallbackHarness: name === "claude-code" ? codexDialect() : await claude(),
2313
+ repos: cfg.repos,
2314
+ label: cfg.label,
2315
+ harnesses: () => machineHarnesses(cfg),
2316
+ usage: new LocalUsage({
2317
+ probes: {
2318
+ "claude-code": () => probeClaudeQuota(cfg.driver === "claude-code" ? cfg.bin : void 0),
2319
+ codex: () => probeCodexQuota(cfg.driver === "codex" ? cfg.bin : void 0)
2320
+ },
2321
+ log: log2
2322
+ }),
2323
+ log: log2
2324
+ });
2325
+ driver.warmHarnesses();
2326
+ return driver;
2327
+ }
2328
+ function recordConnected(logLine, write = writeRunnerState) {
2329
+ try {
2330
+ write({ pid: process.pid, connected_at: (/* @__PURE__ */ new Date()).toISOString() });
2331
+ } catch (err) {
2332
+ logLine(`state write failed: ${err.code ?? "unknown"}`);
2333
+ }
2334
+ }
2335
+ async function run2() {
2336
+ let cfg = readRunnerConfig();
2337
+ if (cfg && isHosted(cfg)) pinRunnerEnvironment(cfg.origin);
2338
+ let token = cfg?.deviceToken ?? getToken();
2339
+ if (!token || !cfg) {
2340
+ out(
2341
+ `${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."}`
2342
+ );
2343
+ process.exit(1);
2344
+ }
2345
+ if (!cfg.deviceToken) {
2346
+ log2("no runner device on this machine; run `cloop connect` so the Agent can reach it");
2347
+ }
2348
+ const name = process.env.CLOOP_DRIVER ?? cfg.driver ?? "t3";
2349
+ const local = isLocal(cfg) ? cfg : null;
2350
+ const hosted = isHosted(cfg) ? cfg : null;
2351
+ if (hosted ? name !== "cloudroom" : name === "cloudroom" || name === "t3" === Boolean(local)) {
2352
+ out(
2353
+ `${red("\u2717")} This machine is not connected for ${name}. Run \`cloop connect --driver ${name}\` first.`
2354
+ );
2355
+ process.exit(1);
2356
+ }
2357
+ const t3 = {
2358
+ client: isT3(cfg) ? new T3Client(cfg.t3Url, cfg.token) : null,
2359
+ renewalFailed: false
2360
+ };
2361
+ const machine = getMachine();
2362
+ const sessionKey = hosted ? `hosted:${hosted.harness}` : `box:${machine}`;
2363
+ const threadsFile = hosted ? hostedThreadsFilePath(hosted.harness) : threadsFilePath();
2364
+ const factory = await defaultSocketFactory();
2365
+ const lock = lockThreadsFile(threadsFile);
2366
+ if (!lock.ok) {
2367
+ out(`${red("\u2717")} Another \`cloop box run\` is running (pid ${lock.heldBy}). Stop it first.`);
2368
+ process.exit(1);
2369
+ }
2370
+ const driver = hosted ? new CloudroomDriver({
2371
+ core: new CoreClient(hosted.coreUrl, hosted.coreToken),
2372
+ harness: hosted.harness,
2373
+ label: hosted.label,
2374
+ log: log2
2375
+ }) : local && (name === "claude-code" || name === "codex") ? await localDriver(local, name) : new T3Driver({
2376
+ client: () => t3.client,
2377
+ t3Bin: isT3(cfg) ? cfg.t3Bin : null,
2378
+ scope: () => cfg && isT3(cfg) ? cfg.scope : void 0,
2379
+ log: log2,
2380
+ watched: ({ work_id, thread_id }) => {
2381
+ const e = watch.list().find((x) => work_id ? x.work_id === work_id : x.thread_id === thread_id);
2382
+ return e && { thread_id: e.thread_id, settled: Boolean(e.settled_at) };
2383
+ }
2384
+ });
2385
+ const watch = new BoxWatch({
2386
+ file: threadsFile,
2387
+ watch: (id, onEvent) => driver.watch(id, onEvent),
2388
+ send: (frame) => socket.send({ ...frame }),
2389
+ log: log2
2390
+ });
2391
+ const setup = hosted ? void 0 : new SetupShare({
2392
+ origin: cfg.origin ?? getOrigin(),
2393
+ deviceToken: () => token,
2394
+ log: (line) => console.error(line)
2395
+ });
2396
+ let inFlight = 0;
2397
+ let callsStarted = 0;
2398
+ const onCall = async (frame) => {
2399
+ const started = Date.now();
2400
+ inFlight++;
2401
+ callsStarted++;
2402
+ try {
2403
+ const result = await runBoxTool(
2404
+ {
2405
+ driver,
2406
+ onLaunch: (workId, threadId) => watch.add(workId, threadId),
2407
+ onResume: (threadId) => watch.resume(threadId),
2408
+ ...setup ? { setup } : {}
2409
+ },
2410
+ frame.tool,
2411
+ frame.args
2412
+ );
2413
+ socket.send({ type: "result", id: frame.id, ...result });
2414
+ log2(
2415
+ `call tool=${frame.tool} ok=${result.ok} ms=${Date.now() - started}${result.ok ? "" : ` error=${result.error} detail=${result.detail.slice(0, 300)}`}`
2416
+ );
2417
+ } finally {
2418
+ inFlight--;
2419
+ }
2420
+ };
2421
+ const socket = new MeshSocket({
2422
+ meshUrl: getMeshUrl(),
2423
+ token,
2424
+ sessionKey,
2425
+ kind: "workstation",
2426
+ factory,
2427
+ onMessage: () => {
2428
+ },
2429
+ onCall: (frame) => void onCall(frame),
2430
+ onAck: (of, ok) => watch.ack(of, ok),
2431
+ onOpen: () => {
2432
+ log2(`connected to ${getMeshUrl()}`);
2433
+ recordConnected(
2434
+ log2,
2435
+ (state) => writeRunnerState(state, runnerStatePath(void 0, threadsFile))
2436
+ );
2437
+ watch.flush();
2438
+ },
2439
+ onClose: (code) => log2(
2440
+ code === REVOKED_CLOSE ? "disconnected by Cloop (revoked), checking" : "disconnected, reconnecting"
2441
+ ),
2442
+ onRefused: () => void (async () => {
2443
+ const fresh = await awaitNewDeviceToken(token ?? "", () => readRunnerConfig()?.deviceToken);
2444
+ const next = fresh ? readRunnerConfig() : null;
2445
+ if (fresh && next) {
2446
+ log2("reconnecting with the device token `cloop connect` just wrote");
2447
+ token = fresh;
2448
+ cfg = next;
2449
+ if (isT3(next)) t3.client = new T3Client(next.t3Url, next.token);
2450
+ t3.renewalFailed = false;
2451
+ socket.restart(fresh);
2452
+ return;
2453
+ }
2454
+ log2(REFUSED_LINE);
2455
+ stop(1);
2456
+ })()
2457
+ });
2458
+ socket.start();
2459
+ log2(
2460
+ `connecting to ${getMeshUrl()} as ${sessionKey} (${readCredentials()?.deviceName ?? machine}) driver=${driver.name}`
2461
+ );
2462
+ watch.start();
2463
+ setInterval(() => watch.flush(), RESEND_MS).unref();
2464
+ const unfollow = driver instanceof CloudroomDriver ? driver.refuseOwnSandboxChildren() : null;
2465
+ if (driver instanceof LocalDriver) serveTakeovers(driver, log2);
2466
+ const renewT3 = async () => {
2467
+ if (!cfg || !isT3(cfg) || Date.parse(cfg.expiresAt) - Date.now() >= REPAIR_BEFORE_MS) return;
2468
+ try {
2469
+ const disk = readRunnerConfig();
2470
+ const renewed = {
2471
+ ...await mintSession(cfg.t3Url, { stored: cfg.t3Bin }),
2472
+ // Read from disk: `cloop connect` may have replaced it since.
2473
+ deviceToken: disk?.deviceToken ?? cfg.deviceToken,
2474
+ hideOtherThreads: disk?.hideOtherThreads === true,
2475
+ ...disk && !isHosted(disk) && disk.chosenDriver ? { chosenDriver: disk.chosenDriver } : {},
2476
+ ...disk?.origin ?? cfg.origin ? { origin: disk?.origin ?? cfg.origin } : {}
2477
+ };
2478
+ cfg = renewed;
2479
+ writeBoxConfig(renewed);
2480
+ t3.client = new T3Client(renewed.t3Url, renewed.token);
2481
+ t3.renewalFailed = false;
2482
+ log2(`T3 session renewed until ${renewed.expiresAt}`);
2483
+ } catch (err) {
2484
+ t3.renewalFailed = true;
2485
+ log2(`T3 session renewal failed: ${err instanceof Error ? err.message : String(err)}`);
2486
+ }
2487
+ };
2488
+ const update = hosted ? null : selfUpdate(driver.name === "t3" ? "workstation" : "local");
2489
+ const beat = async () => {
2490
+ await renewT3();
2491
+ const callsBefore = callsStarted;
2492
+ let running = 0;
2493
+ let outsideThreads = [];
2494
+ const shown = showsOtherThreads(readRunnerConfig());
2495
+ try {
2496
+ const own = shown && driver.name === "claude-code";
2497
+ const listed = await driver.listThreads({
2498
+ scope: own ? "all" : "unsettled",
2499
+ limit: own ? 200 : 1
2500
+ });
2501
+ running = listed.running;
2502
+ if (shown && driver instanceof T3Driver) outsideThreads = await driver.outsideThreads(20);
2503
+ if (own)
2504
+ outsideThreads = await listOutsideSessions(
2505
+ void 0,
2506
+ new Set(listed.threads.map((t) => t.id))
2507
+ );
2508
+ } catch (err) {
2509
+ log2(`${driver.name} unreachable: ${err instanceof Error ? err.message : String(err)}`);
2510
+ }
2511
+ socket.sendPresence(
2512
+ boxPresence({
2513
+ sessionKey,
2514
+ driver: driver.name,
2515
+ capabilities: driver.capabilities,
2516
+ machine,
2517
+ outsideThreads,
2518
+ otherThreads: shown,
2519
+ running,
2520
+ t3: cfg && isT3(cfg) ? t3Presence(cfg, t3.renewalFailed) : null,
2521
+ ...hosted ? { hosted: hosted.harness } : {}
2522
+ })
2523
+ );
2524
+ update?.beat({ running, inFlight: inFlight + callsStarted - callsBefore });
2525
+ };
2526
+ void beat();
2527
+ setInterval(() => void beat(), BEAT_MS);
2528
+ const stop = (code = 0) => {
2529
+ log2("stopping");
2530
+ watch.stop();
2531
+ unfollow?.();
2532
+ if (driver instanceof LocalDriver) driver.stop();
2533
+ lock.release();
2534
+ socket.close();
2535
+ process.exit(code);
2536
+ };
2537
+ process.on("SIGINT", () => stop());
2538
+ process.on("SIGTERM", () => stop());
2539
+ await new Promise(() => {
2540
+ });
2541
+ }
2542
+ function flag(argv, name) {
2543
+ const i = argv.indexOf(name);
2544
+ return i >= 0 ? argv[i + 1] : void 0;
2545
+ }
2546
+ async function boxCommand(argv) {
2547
+ switch (argv[0]) {
2548
+ case "connect":
2549
+ await connectCommand(["--driver", "t3", ...argv.slice(1)]);
2550
+ break;
2551
+ case "run":
2552
+ pinExistingRunner();
2553
+ await run2();
2554
+ break;
2555
+ case "adopt": {
2556
+ const from = flag(argv, "--from");
2557
+ const kind = flag(argv, "--kind");
2558
+ if (!from || kind !== "workstation" && kind !== "local") {
2559
+ console.error("Usage: cloop box adopt --from <version> --kind workstation|local");
2560
+ process.exit(1);
2561
+ }
2562
+ pinExistingRunner();
2563
+ process.exit(await adopt(from, kind));
2564
+ break;
2565
+ }
2566
+ default:
2567
+ console.error(
2568
+ "Usage: cloop box connect [--t3-url <url>] [--t3-bin <path>] [--no-service] | cloop box run"
2569
+ );
2570
+ process.exit(1);
2571
+ }
2572
+ }
2573
+ export {
2574
+ REFUSED_LINE,
2575
+ awaitNewDeviceToken,
2576
+ boxCommand,
2577
+ boxPresence,
2578
+ localDriver,
2579
+ machineHarnesses,
2580
+ recordConnected,
2581
+ run2 as run,
2582
+ t3Presence
2583
+ };