@cloop/runner 0.0.0-stage → 0.2.0

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,2316 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ deviceLogin
4
+ } from "./chunk-CMOMRXTA.js";
5
+ import {
6
+ VERSION
7
+ } from "./chunk-7K5W6ELQ.js";
8
+ import {
9
+ CONFIG_DIR,
10
+ getOrigin
11
+ } from "./chunk-SQJ7ZO4G.js";
12
+
13
+ // src/commands/connect.ts
14
+ import { execFileSync as execFileSync3 } from "child_process";
15
+ import { randomUUID as randomUUID2 } from "crypto";
16
+ import { existsSync, mkdirSync as mkdirSync4, readdirSync, writeFileSync as writeFileSync4 } from "fs";
17
+ import { homedir as homedir4, hostname as hostname2 } from "os";
18
+ import { basename as basename4, dirname as dirname4, join as join4, resolve as resolve2 } from "path";
19
+
20
+ // src/drivers/driver.ts
21
+ var RUNTIME_MODES = /* @__PURE__ */ new Set([
22
+ "approval-required",
23
+ "auto-accept-edits",
24
+ "auto",
25
+ "full-access"
26
+ ]);
27
+ var BoxToolError = class extends Error {
28
+ constructor(code) {
29
+ super(code);
30
+ this.code = code;
31
+ this.name = "BoxToolError";
32
+ }
33
+ code;
34
+ };
35
+ var CLOOP_THREAD_PREFIX = "cloop:";
36
+ function questionLine(questions) {
37
+ return questions.map(
38
+ (x) => x.options?.length ? `${x.question} (${x.options.map((o) => o.label).join(", ")})` : x.question
39
+ ).join(" ").slice(0, 500);
40
+ }
41
+
42
+ // src/t3.ts
43
+ var T3_SCOPE = "orchestration:read orchestration:operate";
44
+ var MIN_PROTOCOL = 2;
45
+ async function readEnvironment(t3Url, fetchFn = fetch) {
46
+ const res = await fetchFn(`${t3Url}/.well-known/t3/environment`);
47
+ if (!res.ok) throw new Error(`T3 environment ${res.status} at ${t3Url}`);
48
+ return await res.json();
49
+ }
50
+ async function exchangePairing(t3Url, credential, label, fetchFn = fetch) {
51
+ const form = new URLSearchParams({
52
+ grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
53
+ subject_token: credential,
54
+ subject_token_type: "urn:t3:params:oauth:token-type:environment-bootstrap",
55
+ requested_token_type: "urn:ietf:params:oauth:token-type:access_token",
56
+ scope: T3_SCOPE,
57
+ client_label: label,
58
+ client_device_type: "bot"
59
+ });
60
+ const res = await fetchFn(`${t3Url}/oauth/token`, { method: "POST", body: form });
61
+ if (!res.ok) throw new Error(`T3 token exchange ${res.status}`);
62
+ const token = await res.json();
63
+ if (!sameScopes(token.scope, T3_SCOPE))
64
+ throw new Error(`T3 granted scope "${token.scope}", wanted "${T3_SCOPE}"`);
65
+ return token;
66
+ }
67
+ function sameScopes(a, b) {
68
+ const set = (s) => [...new Set(s.split(/\s+/).filter(Boolean))].sort().join(" ");
69
+ return set(a) === set(b);
70
+ }
71
+ var T3HttpError = class extends Error {
72
+ constructor(path, status) {
73
+ super(`T3 ${path} ${status}`);
74
+ this.status = status;
75
+ this.name = "T3HttpError";
76
+ }
77
+ status;
78
+ };
79
+ var T3Client = class {
80
+ constructor(t3Url, token, fetchFn = fetch) {
81
+ this.t3Url = t3Url;
82
+ this.token = token;
83
+ this.fetchFn = fetchFn;
84
+ }
85
+ t3Url;
86
+ token;
87
+ fetchFn;
88
+ async http(path, headers = {}) {
89
+ const res = await this.fetchFn(`${this.t3Url}${path}`, {
90
+ headers: { authorization: `Bearer ${this.token}`, ...headers }
91
+ });
92
+ if (!res.ok) throw new T3HttpError(path, res.status);
93
+ return await res.json();
94
+ }
95
+ async openSocket() {
96
+ const ticket = await this.fetchFn(`${this.t3Url}/api/auth/websocket-ticket`, {
97
+ method: "POST",
98
+ headers: { authorization: `Bearer ${this.token}` }
99
+ });
100
+ if (!ticket.ok) throw new T3HttpError("/api/auth/websocket-ticket", ticket.status);
101
+ const { ticket: wsTicket } = await ticket.json();
102
+ const { WebSocket } = await import("ws");
103
+ const url = `${this.t3Url.replace(/^http/, "ws")}/ws?wsTicket=${encodeURIComponent(wsTicket)}&orchestrationProtocol=2&clientSurface=web&clientAppVersion=cloop-box`;
104
+ return new WebSocket(url);
105
+ }
106
+ /** One request over a fresh /ws socket. The daemon makes a few calls a minute, so a socket per call is simpler than keeping one alive. */
107
+ async rpc(tag, payload) {
108
+ const ws = await this.openSocket();
109
+ return new Promise((resolve3, reject) => {
110
+ let settled = false;
111
+ const finish = (fn) => {
112
+ if (settled) return;
113
+ settled = true;
114
+ clearTimeout(timer);
115
+ fn();
116
+ try {
117
+ ws.close();
118
+ } catch {
119
+ }
120
+ };
121
+ const timer = setTimeout(
122
+ () => finish(() => reject(new Error(`T3 rpc ${tag} timed out`))),
123
+ 15e3
124
+ );
125
+ ws.on(
126
+ "error",
127
+ (err) => finish(() => reject(err instanceof Error ? err : new Error(String(err))))
128
+ );
129
+ ws.on(
130
+ "close",
131
+ () => finish(() => reject(new Error(`T3 rpc ${tag}: socket closed before a reply`)))
132
+ );
133
+ ws.on("open", () => {
134
+ ws.send(JSON.stringify({ _tag: "Request", id: 1, tag, payload, headers: [] }));
135
+ });
136
+ ws.on("message", (data) => {
137
+ for (const msg of parseFrames(data)) {
138
+ if (msg._tag !== "Exit" || String(msg.requestId) !== "1") continue;
139
+ const exit = msg.exit;
140
+ if (exit._tag === "Success") finish(() => resolve3(exit.value));
141
+ else {
142
+ finish(
143
+ () => reject(
144
+ new Error(`T3 rpc ${tag} failed: ${JSON.stringify(exit.cause).slice(0, 300)}`)
145
+ )
146
+ );
147
+ }
148
+ }
149
+ });
150
+ });
151
+ }
152
+ /**
153
+ * A streaming request, such as `orchestration.subscribeThread`, on its own
154
+ * socket. Every item is acked, as Effect RPC requires. `done` resolves with
155
+ * the reason the stream ended and never rejects; `close` interrupts it.
156
+ */
157
+ async stream(tag, payload, onItem) {
158
+ const ws = await this.openSocket();
159
+ let resolveDone = () => {
160
+ };
161
+ const done = new Promise((r) => {
162
+ resolveDone = r;
163
+ });
164
+ const end = (reason) => {
165
+ resolveDone(reason);
166
+ try {
167
+ ws.close();
168
+ } catch {
169
+ }
170
+ };
171
+ ws.on("error", (err) => end(`error: ${err instanceof Error ? err.message : String(err)}`));
172
+ ws.on("close", () => end("closed"));
173
+ ws.on("open", () => {
174
+ ws.send(JSON.stringify({ _tag: "Request", id: 1, tag, payload, headers: [] }));
175
+ });
176
+ ws.on("message", (data) => {
177
+ for (const msg of parseFrames(data)) {
178
+ if (String(msg.requestId) !== "1") continue;
179
+ if (msg._tag === "Chunk") {
180
+ ws.send(JSON.stringify({ _tag: "Ack", requestId: msg.requestId }));
181
+ for (const value of msg.values) onItem(value);
182
+ } else if (msg._tag === "Exit") {
183
+ const exit = msg.exit;
184
+ end(
185
+ exit._tag === "Success" ? "exit" : `failed: ${JSON.stringify(exit.cause).slice(0, 300)}`
186
+ );
187
+ }
188
+ }
189
+ });
190
+ return {
191
+ done,
192
+ close: () => {
193
+ try {
194
+ ws.send(JSON.stringify({ _tag: "Interrupt", requestId: "1" }));
195
+ } catch {
196
+ }
197
+ end("closed by client");
198
+ }
199
+ };
200
+ }
201
+ };
202
+ function parseFrames(data) {
203
+ try {
204
+ const raw = JSON.parse(String(data));
205
+ return Array.isArray(raw) ? raw : [raw];
206
+ } catch {
207
+ return [];
208
+ }
209
+ }
210
+
211
+ // src/box-tools.ts
212
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
213
+ function parseLaunchArgs(args) {
214
+ const str = (v, max) => typeof v === "string" && v.trim() && v.length <= max ? v.trim() : void 0;
215
+ const work_id = str(args.work_id, 36);
216
+ const title = str(args.title, 200);
217
+ const prompt = str(args.prompt, 1e5);
218
+ if (!work_id || !UUID.test(work_id) || !title || !prompt) throw new BoxToolError("bad_args");
219
+ const runtime_mode = str(args.runtime_mode, 40);
220
+ if (runtime_mode && !RUNTIME_MODES.has(runtime_mode)) throw new BoxToolError("bad_args");
221
+ return {
222
+ work_id,
223
+ title: title.startsWith(CLOOP_THREAD_PREFIX) ? title : `${CLOOP_THREAD_PREFIX} ${title}`,
224
+ prompt,
225
+ repository: str(args.repository, 200),
226
+ harness: str(args.harness, 80),
227
+ model: str(args.model, 120),
228
+ runtime_mode
229
+ };
230
+ }
231
+ function parseThreadId(args) {
232
+ const id = args.thread_id;
233
+ if (typeof id !== "string" || !id || id.length > 120) throw new BoxToolError("bad_args");
234
+ return id;
235
+ }
236
+ function parseCommandId(args) {
237
+ const id = args.command_id;
238
+ if (typeof id !== "string" || !UUID.test(id)) throw new BoxToolError("bad_args");
239
+ return id;
240
+ }
241
+ function parseSendArgs(args) {
242
+ const text = typeof args.text === "string" ? args.text.trim() : "";
243
+ if (!text || text.length > 8e3) throw new BoxToolError("bad_args");
244
+ const mode = args.mode ?? "steer";
245
+ if (mode !== "steer" && mode !== "queue") throw new BoxToolError("bad_args");
246
+ if (args.answer !== void 0 && typeof args.answer !== "boolean")
247
+ throw new BoxToolError("bad_args");
248
+ const question = args.question_id;
249
+ if (question !== void 0 && question !== null && (typeof question !== "string" || !question || question.length > 1e3))
250
+ throw new BoxToolError("bad_args");
251
+ return {
252
+ thread_id: parseThreadId(args),
253
+ text,
254
+ mode,
255
+ command_id: parseCommandId(args),
256
+ answer: args.answer === true,
257
+ ...question !== void 0 ? { question_id: question } : {}
258
+ };
259
+ }
260
+ var BOX_TOOLS = {
261
+ status: ({ driver }) => driver.status(),
262
+ "threads.list": ({ driver }, args) => driver.listThreads({
263
+ scope: args.scope === "all" ? "all" : "unsettled",
264
+ limit: typeof args.limit === "number" ? Math.min(Math.max(1, args.limit), 50) : 10
265
+ }),
266
+ "thread.read": ({ driver }, args) => driver.readThread(parseThreadId(args)),
267
+ async "thread.launch"({ driver, onLaunch }, args) {
268
+ const a = parseLaunchArgs(args);
269
+ const launched = await driver.launch(a);
270
+ onLaunch?.(a.work_id, launched.thread_id);
271
+ return launched;
272
+ },
273
+ "thread.send": ({ driver }, args) => driver.send(parseSendArgs(args)),
274
+ "thread.interrupt": ({ driver }, args) => driver.interrupt(parseThreadId(args), parseCommandId(args))
275
+ };
276
+ function classifyError(err, driver = "t3") {
277
+ if (err instanceof BoxToolError) return err.code;
278
+ if (driver !== "t3") return "harness_error";
279
+ if (err instanceof T3HttpError)
280
+ return err.status === 401 || err.status === 403 ? "t3_unauthorized" : "t3_error";
281
+ const message = err instanceof Error ? err.message : String(err);
282
+ if (/missing required scope|insufficient_scope/i.test(message)) return "t3_unauthorized";
283
+ if (/ECONNREFUSED|ENOTFOUND|timed out|socket closed|fetch failed/i.test(message))
284
+ return "t3_unreachable";
285
+ return "t3_error";
286
+ }
287
+ async function runBoxTool(ctx, tool, args) {
288
+ const fn = BOX_TOOLS[tool];
289
+ if (!fn) return { ok: false, error: `unknown_tool:${tool}`, detail: "" };
290
+ try {
291
+ return { ok: true, value: await fn(ctx, args) };
292
+ } catch (err) {
293
+ return {
294
+ ok: false,
295
+ error: classifyError(err, ctx.driver.name),
296
+ detail: (err instanceof Error ? err.message : String(err)).slice(0, 400)
297
+ };
298
+ }
299
+ }
300
+
301
+ // src/box-watch.ts
302
+ import { randomUUID } from "crypto";
303
+ import { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "fs";
304
+ import { homedir } from "os";
305
+ import { dirname, join } from "path";
306
+ var KEEP_MS = 7 * 24 * 36e5;
307
+ function threadsFilePath() {
308
+ return process.env.CLOOP_BOX_THREADS_FILE ?? join(homedir(), CONFIG_DIR, "box-threads.json");
309
+ }
310
+ function runnerStatePath() {
311
+ return join(dirname(threadsFilePath()), "runner-state.json");
312
+ }
313
+ function writeRunnerState(state, path = runnerStatePath()) {
314
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
315
+ const tmp = `${path}.tmp`;
316
+ writeFileSync(tmp, `${JSON.stringify(state)}
317
+ `, { mode: 384 });
318
+ renameSync(tmp, path);
319
+ }
320
+ function readRunnerState(path = runnerStatePath()) {
321
+ try {
322
+ const raw = JSON.parse(readFileSync(path, "utf-8"));
323
+ return typeof raw.pid === "number" && typeof raw.connected_at === "string" ? { pid: raw.pid, connected_at: raw.connected_at } : null;
324
+ } catch {
325
+ return null;
326
+ }
327
+ }
328
+ function isAlive(pid) {
329
+ try {
330
+ process.kill(pid, 0);
331
+ return true;
332
+ } catch (err) {
333
+ return err.code === "EPERM";
334
+ }
335
+ }
336
+ function lockThreadsFile(file, pid = process.pid, alive = isAlive) {
337
+ const lock = `${file}.lock`;
338
+ mkdirSync(dirname(lock), { recursive: true, mode: 448 });
339
+ for (let attempt = 0; attempt < 2; attempt++) {
340
+ try {
341
+ writeFileSync(lock, String(pid), { flag: "wx", mode: 384 });
342
+ return {
343
+ ok: true,
344
+ release: () => {
345
+ try {
346
+ if (readFileSync(lock, "utf-8") === String(pid)) unlinkSync(lock);
347
+ } catch {
348
+ }
349
+ }
350
+ };
351
+ } catch (err) {
352
+ if (err.code !== "EEXIST") throw err;
353
+ let held = 0;
354
+ try {
355
+ held = Number(readFileSync(lock, "utf-8").trim());
356
+ } catch (readErr) {
357
+ if (readErr.code !== "ENOENT") throw readErr;
358
+ continue;
359
+ }
360
+ if (Number.isInteger(held) && held > 0 && held !== pid && alive(held)) {
361
+ return { ok: false, heldBy: held };
362
+ }
363
+ try {
364
+ unlinkSync(lock);
365
+ } catch (unlinkErr) {
366
+ if (unlinkErr.code !== "ENOENT") throw unlinkErr;
367
+ }
368
+ }
369
+ }
370
+ return { ok: false, heldBy: -1 };
371
+ }
372
+ var BoxWatch = class {
373
+ constructor(deps) {
374
+ this.deps = deps;
375
+ this.entries = this.load();
376
+ }
377
+ deps;
378
+ entries;
379
+ live = /* @__PURE__ */ new Map();
380
+ stopped = false;
381
+ list() {
382
+ return this.entries;
383
+ }
384
+ start() {
385
+ for (const e of this.entries) if (!e.settled_at) this.watch(e);
386
+ }
387
+ add(workId, threadId) {
388
+ if (this.entries.some((e) => e.work_id === workId)) return;
389
+ const entry = {
390
+ work_id: workId,
391
+ thread_id: threadId,
392
+ launched_at: new Date(this.now()).toISOString()
393
+ };
394
+ this.entries.push(entry);
395
+ this.save();
396
+ this.deps.log(`launch work=${workId} thread=${threadId}`);
397
+ this.watch(entry);
398
+ }
399
+ /** On every socket open and on a timer: send every event the mesh has not acked. */
400
+ flush() {
401
+ for (const e of this.entries) {
402
+ for (const q of e.questions ?? []) if (!q.sent_at) this.trySend(e, q.event);
403
+ if (e.event && !e.sent_at) this.trySend(e, e.event);
404
+ }
405
+ }
406
+ /** `ok` false: the app refused the event for good (unknown work_id, bad frame), so it is not sent again either. */
407
+ ack(eventId, ok = true) {
408
+ for (const e of this.entries) {
409
+ const held = [...e.questions ?? [], e].find((x) => x.event?.id === eventId && !x.sent_at);
410
+ if (!held) continue;
411
+ held.sent_at = new Date(this.now()).toISOString();
412
+ this.save();
413
+ this.deps.log(
414
+ `event ${ok ? "acked" : "refused by the app"} work=${e.work_id} kind=${held.event?.kind}`
415
+ );
416
+ return;
417
+ }
418
+ }
419
+ stop() {
420
+ this.stopped = true;
421
+ for (const unwatch of this.live.values()) unwatch();
422
+ this.live.clear();
423
+ }
424
+ now() {
425
+ return this.deps.now?.() ?? Date.now();
426
+ }
427
+ watch(e) {
428
+ if (this.stopped || e.settled_at || this.live.has(e.work_id)) return;
429
+ const unwatch = this.deps.watch(e.thread_id, (event) => this.onEvent(e, event));
430
+ if (e.settled_at) unwatch();
431
+ else this.live.set(e.work_id, unwatch);
432
+ }
433
+ onEvent(e, event) {
434
+ if (e.settled_at) return;
435
+ if (event.kind === "question") this.ask(e, event.question_id, event.summary);
436
+ else if (event.kind === "progress") this.trySend(e, this.frame(e, event));
437
+ else this.finish(e, event);
438
+ }
439
+ frame(e, event) {
440
+ const { kind, summary } = event;
441
+ return {
442
+ type: "event",
443
+ id: randomUUID(),
444
+ work_id: e.work_id,
445
+ thread_id: e.thread_id,
446
+ kind,
447
+ ...event.kind === "question" ? { question_id: event.question_id } : {},
448
+ ...summary ? { summary: summary.slice(0, 500) } : {},
449
+ ..."pr_url" in event && event.pr_url ? { pr_url: event.pr_url } : {},
450
+ at: new Date(this.now()).toISOString()
451
+ };
452
+ }
453
+ ask(e, questionId, summary) {
454
+ if (e.questions?.some((x) => x.event.question_id === questionId)) return;
455
+ const event = this.frame(e, { kind: "question", question_id: questionId, summary });
456
+ e.questions = [...e.questions ?? [], { event }];
457
+ this.save();
458
+ this.deps.log(`question work=${e.work_id} thread=${e.thread_id}`);
459
+ this.trySend(e, event);
460
+ }
461
+ finish(e, end) {
462
+ this.live.get(e.work_id)?.();
463
+ this.live.delete(e.work_id);
464
+ e.event = this.frame(e, end);
465
+ e.settled_at = e.event.at;
466
+ this.save();
467
+ this.deps.log(
468
+ `settle work=${e.work_id} thread=${e.thread_id} kind=${end.kind} pr=${end.pr_url ? "yes" : "no"}`
469
+ );
470
+ this.trySend(e, e.event);
471
+ }
472
+ trySend(e, event) {
473
+ const sent = this.deps.send(event);
474
+ this.deps.log(
475
+ `event ${sent ? "sent" : "held"} work=${e.work_id} kind=${event.kind}${sent ? "" : "; socket down"}`
476
+ );
477
+ }
478
+ load() {
479
+ let raw;
480
+ try {
481
+ raw = JSON.parse(readFileSync(this.deps.file, "utf-8"));
482
+ } catch {
483
+ return [];
484
+ }
485
+ if (!Array.isArray(raw)) return [];
486
+ const cutoff = this.now() - KEEP_MS;
487
+ return raw.filter(
488
+ (e) => typeof e?.work_id === "string" && typeof e?.thread_id === "string" && !(e.settled_at && Date.parse(e.settled_at) < cutoff)
489
+ );
490
+ }
491
+ save() {
492
+ mkdirSync(dirname(this.deps.file), { recursive: true, mode: 448 });
493
+ const tmp = `${this.deps.file}.tmp`;
494
+ writeFileSync(tmp, `${JSON.stringify(this.entries, null, 2)}
495
+ `, { mode: 384 });
496
+ chmodSync(tmp, 384);
497
+ renameSync(tmp, this.deps.file);
498
+ }
499
+ };
500
+
501
+ // src/drivers/claude-code.ts
502
+ import { execFile as execFile3 } from "child_process";
503
+ import { basename as basename2, isAbsolute, relative, resolve } from "path";
504
+
505
+ // src/drivers/local.ts
506
+ import { execFile as execFile2, execFileSync as execFileSync2, spawn } from "child_process";
507
+ import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
508
+ import { homedir as homedir2, hostname } from "os";
509
+ import { basename, dirname as dirname2, join as join2 } from "path";
510
+ import { createInterface } from "readline";
511
+
512
+ // src/drivers/t3.ts
513
+ import { execFile, execFileSync } from "child_process";
514
+ function isUnsettled(t) {
515
+ return !t.settledAt && !t.archivedAt && !isChild(t);
516
+ }
517
+ function isChild(t) {
518
+ return t.creationSource === "provider" || Boolean(t.lineage?.parentThreadId);
519
+ }
520
+ var SESSIONS_TTL_MS = 5 * 6e4;
521
+ var TERMINAL_RUN = /* @__PURE__ */ new Set(["completed", "interrupted", "failed", "cancelled", "rolled_back"]);
522
+ var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master"]);
523
+ function pendingQuestions(p) {
524
+ const asked = /* @__PURE__ */ new Map();
525
+ for (const item of p.turnItems ?? []) {
526
+ if (item.type === "user_input_request" && item.requestId && item.questions?.length)
527
+ asked.set(item.requestId, item.questions);
528
+ }
529
+ return (p.runtimeRequests ?? []).filter((r) => r.kind === "user_input" && r.status === "pending" && asked.has(r.id)).sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? "")).map((r) => ({ request_id: r.id, questions: asked.get(r.id) ?? [] }));
530
+ }
531
+ function questionText(q) {
532
+ return questionLine(q.questions);
533
+ }
534
+ function latestRun(runs) {
535
+ return runs.reduce(
536
+ (latest, r) => !latest || (r.ordinal ?? 0) >= (latest.ordinal ?? 0) ? r : latest,
537
+ null
538
+ );
539
+ }
540
+ function isTerminal(runs) {
541
+ const run2 = latestRun(runs);
542
+ return Boolean(run2 && TERMINAL_RUN.has(run2.status));
543
+ }
544
+ function activeRun(runs) {
545
+ const run2 = latestRun(runs);
546
+ return run2 && !TERMINAL_RUN.has(run2.status) ? run2 : null;
547
+ }
548
+ function steerableRun(p) {
549
+ const run2 = activeRun(p.runs ?? []);
550
+ if (!run2) return null;
551
+ const attempts = new Set((p.attempts ?? []).filter((a) => a.runId === run2.id).map((a) => a.id));
552
+ const turning = (p.providerTurns ?? []).some(
553
+ (t) => t.status === "running" && t.runAttemptId !== null && attempts.has(t.runAttemptId)
554
+ );
555
+ return turning ? run2 : null;
556
+ }
557
+ var STEER_WAIT_MS = 8e3;
558
+ var STEER_POLL_MS = 500;
559
+ function prUrlOf(thread) {
560
+ const branch = thread.branch ?? null;
561
+ const linked = thread.pullRequests ?? [];
562
+ const own = branch ? linked.filter((pr) => pr.snapshot?.headBranch === branch) : [];
563
+ const fromLinked = (own.at(-1) ?? linked.at(-1))?.url ?? thread.linkedPullRequest?.url;
564
+ if (fromLinked) return fromLinked;
565
+ if (branch && !SHARED_BRANCHES.has(branch)) return thread.branchPullRequest?.url ?? null;
566
+ return null;
567
+ }
568
+ function outcomeOf(p) {
569
+ const run2 = latestRun(p.runs ?? []);
570
+ const status = run2?.status ?? "pending";
571
+ const settled = TERMINAL_RUN.has(status) || Boolean(p.thread.settledAt);
572
+ const text = (p.messages ?? []).filter((m) => m.role === "assistant" && m.text).at(-1)?.text?.trim();
573
+ return {
574
+ status,
575
+ settled,
576
+ kind: settled ? status === "completed" || !run2 ? "settled" : "failed" : null,
577
+ pr_url: prUrlOf(p.thread),
578
+ last_assistant_text: text ? text.slice(0, 300) : null
579
+ };
580
+ }
581
+ function pickProject(projects, repository) {
582
+ const only = projects.length === 1 ? projects[0] : void 0;
583
+ if (!repository) {
584
+ if (only) return only;
585
+ throw new BoxToolError("no_project");
586
+ }
587
+ const want = repository.toLowerCase();
588
+ const found = projects.find(
589
+ (p) => p.title.toLowerCase() === want || p.workspaceRoot.split("/").at(-1)?.toLowerCase() === want || p.repositoryIdentity?.displayName?.toLowerCase() === want
590
+ );
591
+ if (!found) throw new BoxToolError("no_project");
592
+ return found;
593
+ }
594
+ var SHELL_HEADERS = { "x-t3-orchestration-protocol": "2" };
595
+ function boxCapabilities(scope) {
596
+ const scopes = (scope ?? "").split(/\s+/).filter(Boolean);
597
+ return scopes.includes("orchestration:operate") ? ["view", "start", "steer"] : ["view"];
598
+ }
599
+ function threadView(t) {
600
+ return {
601
+ id: t.id,
602
+ title: t.title,
603
+ status: t.status,
604
+ branch: t.branch ?? null,
605
+ source: t.creationSource ?? null,
606
+ cloop: (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX),
607
+ settled: Boolean(t.settledAt),
608
+ updatedAt: t.updatedAt
609
+ };
610
+ }
611
+ function orderThreads(threads, limit) {
612
+ const byRecency = (a, b) => b.updatedAt.localeCompare(a.updatedAt);
613
+ const running = threads.filter((t) => t.status === "running").sort(byRecency);
614
+ const rest = threads.filter((t) => t.status !== "running").sort(byRecency);
615
+ return [...running, ...rest].slice(0, limit);
616
+ }
617
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
618
+ var T3Driver = class {
619
+ constructor(deps) {
620
+ this.deps = deps;
621
+ }
622
+ deps;
623
+ name = "t3";
624
+ get capabilities() {
625
+ return boxCapabilities(this.deps.scope?.());
626
+ }
627
+ get t3() {
628
+ return this.deps.client();
629
+ }
630
+ log(line2) {
631
+ this.deps.log?.(line2);
632
+ }
633
+ async status() {
634
+ const [cfg, shell] = await Promise.all([
635
+ this.t3.rpc("server.getConfig", {}),
636
+ this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
637
+ ]);
638
+ const sessions = this.listSessions();
639
+ const threads = (shell.threads ?? []).filter((t) => !isChild(t));
640
+ const unsettled = threads.filter(isUnsettled);
641
+ return {
642
+ box: {
643
+ label: cfg.environment.label,
644
+ driver: "t3",
645
+ t3Version: cfg.environment.serverVersion,
646
+ protocol: cfg.environment.orchestrationProtocolVersion,
647
+ hosts: (cfg.remoteOpenTargets ?? []).map((t) => t.host)
648
+ },
649
+ harnesses: cfg.providers.filter((p) => p.enabled).map((p) => ({
650
+ id: p.instanceId,
651
+ name: p.displayName ?? p.instanceId,
652
+ version: p.version,
653
+ ready: p.status === "ready",
654
+ signedIn: p.auth?.status === "authenticated",
655
+ account: p.auth?.label ?? null,
656
+ defaultModel: p.models?.find((m) => m.isDefault)?.slug ?? null
657
+ })),
658
+ clients: sessions?.filter((s) => s.client?.deviceType !== "bot").map((s) => ({
659
+ label: s.client?.label ?? "unknown",
660
+ connected: s.connected === true,
661
+ lastConnectedAt: s.lastConnectedAt ?? null
662
+ })) ?? null,
663
+ projects: (shell.projects ?? []).map((p) => p.title),
664
+ threads: {
665
+ unsettled: unsettled.length,
666
+ running: unsettled.filter((t) => t.status === "running").length,
667
+ settled: threads.length - unsettled.length,
668
+ cloop: unsettled.filter((t) => (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX)).length
669
+ }
670
+ };
671
+ }
672
+ async listThreads({
673
+ scope,
674
+ limit
675
+ }) {
676
+ const shell = await this.t3.http("/api/orchestration/shell", SHELL_HEADERS);
677
+ const all = (shell.threads ?? []).filter((t) => !isChild(t));
678
+ const threads = scope === "all" ? all : all.filter(isUnsettled);
679
+ return {
680
+ scope,
681
+ unsettled: all.filter(isUnsettled).length,
682
+ settled: all.length - all.filter(isUnsettled).length,
683
+ running: threads.filter((t) => t.status === "running").length,
684
+ threads: orderThreads(threads, limit).map(threadView)
685
+ };
686
+ }
687
+ /**
688
+ * `work_id` is T3's `commandId`, so a second launch of the same work returns
689
+ * the same thread with `resumed: true` and runs nothing twice. The worktree
690
+ * starts from origin's copy of the branch the project's checkout is on.
691
+ */
692
+ async launch(a) {
693
+ const known = this.deps.watched?.({ work_id: a.work_id });
694
+ if (known) return { thread_id: known.thread_id, resumed: true };
695
+ const [cfg, shell] = await Promise.all([
696
+ this.t3.rpc("server.getConfig", {}),
697
+ this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
698
+ ]);
699
+ const project = pickProject(shell.projects ?? [], a.repository);
700
+ const fallback = cfg.settings?.defaultModelSelection;
701
+ const harness = a.harness ?? fallback?.instanceId ?? "claudeAgent";
702
+ const provider = cfg.providers.find((p) => p.instanceId === harness && p.enabled);
703
+ if (!provider) throw new BoxToolError("harness_unavailable");
704
+ if (provider.auth && provider.auth.status !== "authenticated")
705
+ throw new BoxToolError("harness_signed_out");
706
+ const model = a.model ?? (fallback?.instanceId === harness ? fallback.model : void 0) ?? provider.models?.find((m) => m.isDefault)?.slug;
707
+ if (!model) throw new BoxToolError("harness_unavailable");
708
+ const modelSelection = !a.model && fallback?.instanceId === harness ? fallback : { instanceId: harness, model };
709
+ const runtimeMode = a.runtime_mode ?? cfg.settings?.defaultRuntimeMode;
710
+ if (!runtimeMode || !RUNTIME_MODES.has(runtimeMode))
711
+ throw new BoxToolError("runtime_mode_unknown");
712
+ const launched = await this.t3.rpc(
713
+ "orchestration.launchThread",
714
+ {
715
+ commandId: a.work_id,
716
+ creationSource: "mcp",
717
+ projectId: project.id,
718
+ title: a.title,
719
+ modelSelection,
720
+ runtimeMode,
721
+ interactionMode: "default",
722
+ workspaceStrategy: {
723
+ type: "worktree",
724
+ baseRef: this.baseRefFor(project.workspaceRoot)
725
+ },
726
+ initialMessage: { text: a.prompt, attachments: [] }
727
+ }
728
+ );
729
+ return { thread_id: launched.threadId, resumed: launched.resumed };
730
+ }
731
+ /**
732
+ * Say something to a thread. While the thread waits on a question, only
733
+ * `answer: true` sends anything: the text answers every question in the
734
+ * newest request, because a steer does not resolve a pending question and
735
+ * the run would wait on. Without it the call sends nothing and returns the
736
+ * question, so the owner says which they meant. Otherwise `steer`
737
+ * joins the running turn, waiting up to 8 s for a starting run's provider
738
+ * turn. A run that still cannot take a steer, or `queue`, gets the text
739
+ * after it ends; a thread with nothing running starts a new turn.
740
+ * `command_id` is T3's commandId, so a retried call sends once.
741
+ */
742
+ async send(a) {
743
+ let p = await this.readProjection(a.thread_id);
744
+ const pending = pendingQuestions(p);
745
+ const question = pending.at(-1);
746
+ if (a.answer && a.question_id !== void 0 && question?.request_id !== a.question_id) {
747
+ return {
748
+ delivered: "question_changed",
749
+ question: question ? questionText(question) : null,
750
+ question_id: question?.request_id ?? null
751
+ };
752
+ }
753
+ if (question && !a.answer) {
754
+ return {
755
+ delivered: "question_pending",
756
+ question: questionText(question),
757
+ questions: pending.length
758
+ };
759
+ }
760
+ if (question) {
761
+ const receipt2 = await this.dispatch({
762
+ type: "runtime-request.respond",
763
+ commandId: a.command_id,
764
+ threadId: a.thread_id,
765
+ requestId: question.request_id,
766
+ answers: Object.fromEntries(question.questions.map((q) => [q.id, a.text]))
767
+ });
768
+ return { sequence: receipt2.sequence, delivered: "answer", question_id: question.request_id };
769
+ }
770
+ if (a.mode === "steer") {
771
+ for (let waited = 0; waited < STEER_WAIT_MS; waited += STEER_POLL_MS) {
772
+ if (!activeRun(p.runs ?? []) || steerableRun(p)) break;
773
+ await sleep(STEER_POLL_MS);
774
+ p = await this.readProjection(a.thread_id);
775
+ }
776
+ }
777
+ const steer = a.mode === "steer" ? steerableRun(p) : null;
778
+ const active = activeRun(p.runs ?? []);
779
+ if (!active && this.deps.watched?.({ thread_id: a.thread_id })?.settled)
780
+ throw new BoxToolError("already_finished");
781
+ const receipt = await this.dispatch({
782
+ type: "message.dispatch",
783
+ commandId: a.command_id,
784
+ threadId: a.thread_id,
785
+ messageId: a.command_id,
786
+ text: a.text,
787
+ attachments: [],
788
+ dispatchMode: steer ? { type: "steer_active", targetRunId: steer.id } : active ? { type: "queue_after_active" } : { type: "start_immediately" },
789
+ createdBy: "user",
790
+ creationSource: "mcp"
791
+ });
792
+ return { sequence: receipt.sequence, delivered: steer ? "steer" : active ? "queue" : "start" };
793
+ }
794
+ /**
795
+ * Stop the running turn. A thread with nothing running answers
796
+ * `was_running: false`, and so does a run that ended while the interrupt
797
+ * was on its way: T3 refuses that interrupt, and the owner's ask is met.
798
+ */
799
+ async interrupt(threadId, commandId) {
800
+ const run2 = activeRun((await this.readProjection(threadId)).runs ?? []);
801
+ if (!run2) return { ok: true, was_running: false };
802
+ try {
803
+ await this.dispatch({
804
+ type: "run.interrupt",
805
+ commandId,
806
+ threadId,
807
+ runId: run2.id,
808
+ reason: "Stopped from Cloop"
809
+ });
810
+ } catch (err) {
811
+ if (activeRun((await this.readProjection(threadId)).runs ?? [])) throw err;
812
+ return { ok: true, was_running: false };
813
+ }
814
+ return { ok: true, was_running: true };
815
+ }
816
+ async readThread(id) {
817
+ const { status, settled, pr_url, last_assistant_text } = outcomeOf(
818
+ await this.readProjection(id)
819
+ );
820
+ return { status, settled, pr_url, last_assistant_text };
821
+ }
822
+ /**
823
+ * Subscribe to the thread and resubscribe whenever the stream ends. A thread
824
+ * that settled while nobody watched shows a terminal run in its first
825
+ * snapshot. A question is reported on every update it is still pending.
826
+ */
827
+ watch(threadId, onEvent) {
828
+ let stopped = false;
829
+ let finishing = false;
830
+ let live = null;
831
+ const retry = () => {
832
+ if (stopped) return;
833
+ const timer = setTimeout(() => void follow(), this.deps.retryMs ?? 1e4);
834
+ timer.unref?.();
835
+ };
836
+ const finish = async () => {
837
+ if (stopped || finishing) return;
838
+ finishing = true;
839
+ let outcome;
840
+ try {
841
+ outcome = outcomeOf(await this.readProjection(threadId));
842
+ const grace = this.deps.prGraceMs ?? 6e4;
843
+ if (outcome.settled && outcome.kind === "settled" && !outcome.pr_url && grace > 0) {
844
+ await sleep(grace);
845
+ outcome = outcomeOf(await this.readProjection(threadId));
846
+ }
847
+ } catch (err) {
848
+ this.log(
849
+ `read failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
850
+ );
851
+ finishing = false;
852
+ retry();
853
+ return;
854
+ }
855
+ if (stopped) return;
856
+ if (!outcome.settled) {
857
+ finishing = false;
858
+ this.log(`run continues thread=${threadId} run=${outcome.status}; watching on`);
859
+ if (!live) void follow();
860
+ return;
861
+ }
862
+ stopped = true;
863
+ live?.close();
864
+ const pr = outcome.pr_url ? { pr_url: outcome.pr_url } : {};
865
+ if (outcome.kind === "failed") {
866
+ onEvent({ kind: "failed", summary: `The run ended ${outcome.status}.`, ...pr });
867
+ } else {
868
+ onEvent({
869
+ kind: "settled",
870
+ ...outcome.last_assistant_text ? { summary: outcome.last_assistant_text } : {},
871
+ ...pr
872
+ });
873
+ }
874
+ };
875
+ const follow = async () => {
876
+ if (stopped || live) return;
877
+ const runs = /* @__PURE__ */ new Map();
878
+ const requests = /* @__PURE__ */ new Map();
879
+ const asks = /* @__PURE__ */ new Map();
880
+ const keepAsk = (item) => {
881
+ if (item.type === "user_input_request" && item.requestId) asks.set(item.requestId, item);
882
+ };
883
+ let settledByHand = false;
884
+ let stream;
885
+ try {
886
+ stream = await this.t3.stream("orchestration.subscribeThread", { threadId }, (raw) => {
887
+ const item = raw;
888
+ if (item.kind === "snapshot" && "projection" in item) {
889
+ for (const r of item.projection.runs ?? []) runs.set(r.id, r);
890
+ for (const r of item.projection.runtimeRequests ?? []) requests.set(r.id, r);
891
+ for (const t of item.projection.turnItems ?? []) keepAsk(t);
892
+ settledByHand ||= Boolean(item.projection.thread?.settledAt);
893
+ } else if (item.kind === "event" && "event" in item) {
894
+ const { type, payload } = item.event;
895
+ if (type.startsWith("run.") && typeof payload?.id === "string") {
896
+ runs.set(payload.id, payload);
897
+ } else if (type === "runtime-request.updated" && typeof payload?.id === "string") {
898
+ requests.set(payload.id, payload);
899
+ } else if (type === "turn-item.updated" && payload) {
900
+ keepAsk(payload);
901
+ } else if (type.startsWith("thread.") && payload?.settledAt) {
902
+ settledByHand = true;
903
+ } else return;
904
+ } else return;
905
+ if (settledByHand || isTerminal([...runs.values()])) {
906
+ void finish();
907
+ return;
908
+ }
909
+ const pending = pendingQuestions({
910
+ runtimeRequests: [...requests.values()],
911
+ turnItems: [...asks.values()]
912
+ });
913
+ for (const q of pending) {
914
+ onEvent({ kind: "question", question_id: q.request_id, summary: questionText(q) });
915
+ }
916
+ });
917
+ } catch (err) {
918
+ this.log(
919
+ `watch failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
920
+ );
921
+ retry();
922
+ return;
923
+ }
924
+ if (stopped) {
925
+ stream.close();
926
+ return;
927
+ }
928
+ live = stream;
929
+ const reason = await stream.done;
930
+ live = null;
931
+ if (stopped || finishing) return;
932
+ this.log(`watch ended thread=${threadId} reason=${reason}; resubscribing`);
933
+ retry();
934
+ };
935
+ void follow();
936
+ return () => {
937
+ stopped = true;
938
+ live?.close();
939
+ };
940
+ }
941
+ readProjection(threadId) {
942
+ return this.t3.rpc("orchestration.getThreadProjection", { threadId });
943
+ }
944
+ dispatch(command) {
945
+ return this.t3.rpc("orchestration.dispatchCommand", command);
946
+ }
947
+ sessions = {
948
+ list: null,
949
+ at: 0,
950
+ refreshing: false
951
+ };
952
+ /**
953
+ * T3's client sessions, from the cache. `t3 auth session list` starts a whole
954
+ * CLI and took 5 to 14 s on a loaded box, so status never waits on it: it
955
+ * answers with the last list and refreshes it in the background at most
956
+ * once per SESSIONS_TTL_MS.
957
+ */
958
+ listSessions() {
959
+ const bin = this.deps.t3Bin;
960
+ if (!bin) return null;
961
+ const stale = Date.now() - this.sessions.at > SESSIONS_TTL_MS;
962
+ if (stale && !this.sessions.refreshing) {
963
+ this.sessions.refreshing = true;
964
+ const done = (raw) => {
965
+ try {
966
+ if (raw !== null) this.sessions.list = JSON.parse(raw);
967
+ } catch {
968
+ }
969
+ this.sessions.at = Date.now();
970
+ this.sessions.refreshing = false;
971
+ };
972
+ (this.deps.execAsync ?? execFile)(
973
+ bin,
974
+ ["auth", "session", "list", "--json"],
975
+ {
976
+ encoding: "utf-8",
977
+ env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
978
+ timeout: 3e4
979
+ },
980
+ (err, stdout) => done(err ? null : String(stdout))
981
+ );
982
+ }
983
+ return this.sessions.list;
984
+ }
985
+ /**
986
+ * The branch the project's checkout is on, from origin when origin has it. A
987
+ * local branch can lag origin by hundreds of commits on a box nobody pulls on,
988
+ * and T3 starts the worktree from the ref exactly as given.
989
+ */
990
+ baseRefFor(root) {
991
+ const git = (args) => String(
992
+ (this.deps.exec ?? execFileSync)("git", ["-C", root, ...args], {
993
+ encoding: "utf-8",
994
+ env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
995
+ timeout: 5e3
996
+ })
997
+ ).trim();
998
+ let branch;
999
+ try {
1000
+ branch = git(["rev-parse", "--abbrev-ref", "HEAD"]);
1001
+ } catch {
1002
+ return "HEAD";
1003
+ }
1004
+ if (!branch || branch === "HEAD") return "HEAD";
1005
+ try {
1006
+ git(["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}`]);
1007
+ return `origin/${branch}`;
1008
+ } catch {
1009
+ return branch;
1010
+ }
1011
+ }
1012
+ };
1013
+
1014
+ // src/drivers/local.ts
1015
+ var CONTINUE_PROMPT = "Continue the work from where you stopped. If it is already done, say so in one sentence.";
1016
+ var PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
1017
+ var SHARED_BRANCHES2 = /* @__PURE__ */ new Set(["staging", "main", "master", "HEAD"]);
1018
+ var COMMANDS_KEPT = 50;
1019
+ var SUMMARY_MAX = 200;
1020
+ var PERMISSION_MODES = {
1021
+ "approval-required": "default",
1022
+ "auto-accept-edits": "acceptEdits",
1023
+ auto: "auto",
1024
+ "full-access": "bypassPermissions"
1025
+ };
1026
+ function permissionMode(mode) {
1027
+ return PERMISSION_MODES[mode ?? "auto-accept-edits"];
1028
+ }
1029
+ function localRunsFilePath() {
1030
+ return process.env.CLOOP_LOCAL_RUNS_FILE ?? join2(homedir2(), CONFIG_DIR, "local-runs.json");
1031
+ }
1032
+ function pickRepo(repos, repository) {
1033
+ if (!repository) {
1034
+ if (repos.length === 1 && repos[0]) return repos[0];
1035
+ throw new BoxToolError("no_project");
1036
+ }
1037
+ const want = repository.toLowerCase().split("/").at(-1) ?? "";
1038
+ const found = repos.find(
1039
+ (r) => r.label.toLowerCase() === want || basename(r.path).toLowerCase() === want
1040
+ );
1041
+ if (!found) throw new BoxToolError("no_project");
1042
+ return found;
1043
+ }
1044
+ function prUrlIn(text) {
1045
+ return text?.match(PR_URL)?.at(-1) ?? null;
1046
+ }
1047
+ function run(cmd, args, cwd) {
1048
+ return new Promise(
1049
+ (resolve3, reject) => execFile2(
1050
+ cmd,
1051
+ args,
1052
+ { cwd, timeout: 1e4, encoding: "utf-8" },
1053
+ (err, out2) => err ? reject(err) : resolve3(String(out2).trim())
1054
+ )
1055
+ );
1056
+ }
1057
+ var gitProbe = {
1058
+ head: (repo) => run("git", ["rev-parse", "HEAD"], repo).catch(() => null),
1059
+ pushed: (repo) => run("git", ["branch", "-r", "--contains", "HEAD"], repo).then(
1060
+ (out2) => out2.length > 0,
1061
+ () => false
1062
+ ),
1063
+ async branchPr(repo) {
1064
+ try {
1065
+ const branch = await run("git", ["rev-parse", "--abbrev-ref", "HEAD"], repo);
1066
+ if (SHARED_BRANCHES2.has(branch)) return null;
1067
+ return prUrlIn(await run("gh", ["pr", "view", "--json", "url", "-q", ".url"], repo));
1068
+ } catch {
1069
+ return null;
1070
+ }
1071
+ }
1072
+ };
1073
+ function harnessAlive(pid, r, dialect) {
1074
+ try {
1075
+ process.kill(pid, 0);
1076
+ } catch (err) {
1077
+ if (err.code !== "EPERM") return false;
1078
+ }
1079
+ try {
1080
+ const command = execFileSync2("ps", ["-ww", "-o", "command=", "-p", String(pid)], {
1081
+ encoding: "utf-8",
1082
+ timeout: 2e3
1083
+ });
1084
+ return dialect.owns(r, command);
1085
+ } catch {
1086
+ return false;
1087
+ }
1088
+ }
1089
+ var KEEP_MS2 = 7 * 24 * 36e5;
1090
+ var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
1091
+ var LocalDriver = class {
1092
+ constructor(deps) {
1093
+ this.deps = deps;
1094
+ this.name = deps.dialect.name;
1095
+ this.capabilities = deps.dialect.capabilities;
1096
+ this.runs = new Map(this.load().map((r) => [r.work_id, r]));
1097
+ }
1098
+ deps;
1099
+ name;
1100
+ capabilities;
1101
+ runs;
1102
+ lives = /* @__PURE__ */ new Map();
1103
+ listeners = /* @__PURE__ */ new Map();
1104
+ recovering = /* @__PURE__ */ new Set();
1105
+ stopping = false;
1106
+ get repo() {
1107
+ return this.deps.repo ?? gitProbe;
1108
+ }
1109
+ get file() {
1110
+ return this.deps.file ?? localRunsFilePath();
1111
+ }
1112
+ log(line2) {
1113
+ this.deps.log?.(line2);
1114
+ }
1115
+ now() {
1116
+ return this.deps.now?.() ?? Date.now();
1117
+ }
1118
+ async status() {
1119
+ const harnesses = this.deps.harnesses ? await this.deps.harnesses() : [await this.deps.dialect.probe()].filter((h) => h !== null);
1120
+ const all = [...this.runs.values()];
1121
+ const unsettled = all.filter((r) => !r.end);
1122
+ return {
1123
+ box: { label: this.deps.label ?? hostname(), driver: this.name },
1124
+ harnesses,
1125
+ clients: null,
1126
+ projects: this.deps.repos.map((r) => r.label),
1127
+ threads: {
1128
+ unsettled: unsettled.length,
1129
+ running: unsettled.filter((r) => this.lives.has(r.work_id)).length,
1130
+ settled: all.length - unsettled.length,
1131
+ cloop: unsettled.length
1132
+ }
1133
+ };
1134
+ }
1135
+ async listThreads({
1136
+ scope,
1137
+ limit
1138
+ }) {
1139
+ const all = [...this.runs.values()];
1140
+ const unsettled = all.filter((r) => !r.end);
1141
+ const shown = (scope === "all" ? all : unsettled).map((r) => ({
1142
+ id: r.work_id,
1143
+ title: r.title,
1144
+ status: this.statusOf(r),
1145
+ branch: null,
1146
+ source: "cloop",
1147
+ cloop: true,
1148
+ settled: Boolean(r.end),
1149
+ updatedAt: r.end?.at ?? r.started_at
1150
+ }));
1151
+ return {
1152
+ scope,
1153
+ unsettled: unsettled.length,
1154
+ settled: all.length - unsettled.length,
1155
+ running: shown.filter((t) => t.status === "running").length,
1156
+ threads: orderThreads(shown, limit)
1157
+ };
1158
+ }
1159
+ async readThread(id) {
1160
+ const r = this.record(id);
1161
+ return {
1162
+ status: this.statusOf(r),
1163
+ settled: Boolean(r.end),
1164
+ pr_url: r.end?.pr_url ?? null,
1165
+ last_assistant_text: r.end?.summary ?? r.last_text ?? null
1166
+ };
1167
+ }
1168
+ async launch(a) {
1169
+ if (this.runs.has(a.work_id)) return { thread_id: a.work_id, resumed: true };
1170
+ const { dialect } = this.deps;
1171
+ if (a.harness && !dialect.aliases.includes(a.harness))
1172
+ throw new BoxToolError("harness_unavailable");
1173
+ const repo = pickRepo(this.deps.repos, a.repository);
1174
+ this.refuseBusy(repo.path);
1175
+ const harness = await dialect.probe();
1176
+ if (!harness) throw new BoxToolError("harness_unavailable");
1177
+ if (!harness.signedIn) throw new BoxToolError("harness_signed_out");
1178
+ const head = await this.repo.head(repo.path);
1179
+ if (this.runs.has(a.work_id)) return { thread_id: a.work_id, resumed: true };
1180
+ this.refuseBusy(repo.path);
1181
+ const record = {
1182
+ work_id: a.work_id,
1183
+ session_id: dialect.name === "claude-code" ? a.work_id : null,
1184
+ repo: repo.path,
1185
+ title: a.title,
1186
+ ...a.model ? { model: a.model } : {},
1187
+ ...a.runtime_mode ? { runtime_mode: a.runtime_mode } : {},
1188
+ pid: null,
1189
+ started_at: new Date(this.now()).toISOString(),
1190
+ head_at_launch: head
1191
+ };
1192
+ this.runs.set(a.work_id, record);
1193
+ this.spawnRun(record, a.prompt, false);
1194
+ return { thread_id: a.work_id, resumed: false };
1195
+ }
1196
+ async send(a) {
1197
+ const r = this.record(a.thread_id);
1198
+ const seen = r.commands?.find(([id]) => id === a.command_id);
1199
+ if (seen) return { delivered: seen[1] };
1200
+ const live = this.lives.get(r.work_id);
1201
+ const ask = live?.asks[0];
1202
+ if (a.answer && (!ask || ask.request_id !== a.question_id)) {
1203
+ this.log(`question_changed work=${r.work_id}`);
1204
+ return {
1205
+ delivered: "question_changed",
1206
+ question: ask?.summary ?? null,
1207
+ question_id: ask?.request_id ?? null
1208
+ };
1209
+ }
1210
+ if (live && ask) {
1211
+ if (!a.answer) {
1212
+ return {
1213
+ delivered: "question_pending",
1214
+ question: ask.summary,
1215
+ questions: live.asks.length
1216
+ };
1217
+ }
1218
+ const line3 = this.deps.dialect.answerLine?.(ask, a.text);
1219
+ if (!line3) throw new BoxToolError("cannot_steer");
1220
+ live.asks = live.asks.slice(1);
1221
+ this.write(live, line3);
1222
+ this.remember(r, a.command_id, "answer");
1223
+ this.log(`answer work=${r.work_id}`);
1224
+ this.askNext(r, live);
1225
+ return { delivered: "answer", question_id: ask.request_id };
1226
+ }
1227
+ if (!live) {
1228
+ if (r.end) throw new BoxToolError("already_finished");
1229
+ this.spawnRun(r, a.text, true);
1230
+ this.remember(r, a.command_id, "start");
1231
+ return { delivered: "start" };
1232
+ }
1233
+ if (live.child.stdin?.writableEnded) {
1234
+ live.next = live.next ? `${live.next}
1235
+
1236
+ ${a.text}` : a.text;
1237
+ this.remember(r, a.command_id, "queue");
1238
+ return { delivered: "queue" };
1239
+ }
1240
+ const line2 = this.deps.dialect.userLine?.(r, a.text, a.mode);
1241
+ if (!line2) throw new BoxToolError("cannot_steer");
1242
+ live.outstanding++;
1243
+ this.write(live, line2);
1244
+ const delivered = a.mode === "queue" ? "queue" : "steer";
1245
+ this.remember(r, a.command_id, delivered);
1246
+ this.log(`${delivered} work=${r.work_id}`);
1247
+ return { delivered };
1248
+ }
1249
+ async interrupt(id) {
1250
+ const r = this.record(id);
1251
+ const live = this.lives.get(r.work_id);
1252
+ if (!live) {
1253
+ if (r.end) return { ok: true, was_running: false };
1254
+ const orphan = r.pid !== null && this.alive(r.pid, r);
1255
+ if (orphan && r.pid !== null) {
1256
+ try {
1257
+ process.kill(r.pid, "SIGINT");
1258
+ } catch {
1259
+ }
1260
+ }
1261
+ await this.end(r, { kind: "failed", summary: "The run was stopped." });
1262
+ return { ok: true, was_running: orphan };
1263
+ }
1264
+ live.interrupted = true;
1265
+ live.child.kill("SIGINT");
1266
+ const timer = setTimeout(() => {
1267
+ if (live.child.exitCode === null && live.child.signalCode === null)
1268
+ live.child.kill("SIGTERM");
1269
+ }, this.deps.interruptGraceMs ?? 1e4);
1270
+ timer.unref();
1271
+ this.log(`interrupt work=${r.work_id}`);
1272
+ return { ok: true, was_running: true };
1273
+ }
1274
+ watch(id, onEvent) {
1275
+ const set = this.listeners.get(id) ?? /* @__PURE__ */ new Set();
1276
+ set.add(onEvent);
1277
+ this.listeners.set(id, set);
1278
+ const r = this.runs.get(id);
1279
+ const unwatch = () => set.delete(onEvent);
1280
+ if (!r) {
1281
+ onEvent({ kind: "failed", summary: "This run is not on the runner any more." });
1282
+ return unwatch;
1283
+ }
1284
+ if (r.end) {
1285
+ const { at: _at, ...end } = r.end;
1286
+ onEvent(end);
1287
+ return unwatch;
1288
+ }
1289
+ const live = this.lives.get(id);
1290
+ const ask = live?.asks[0];
1291
+ if (ask) onEvent({ kind: "question", question_id: ask.request_id, summary: ask.summary });
1292
+ if (!live) void this.recover(r);
1293
+ return unwatch;
1294
+ }
1295
+ /** On a daemon stop: end every process, and leave its run open so the next start resumes it. */
1296
+ stop() {
1297
+ this.stopping = true;
1298
+ for (const live of this.lives.values()) live.child.kill("SIGTERM");
1299
+ }
1300
+ alive(pid, r) {
1301
+ return this.deps.alive ? this.deps.alive(pid, r) : harnessAlive(pid, r, this.deps.dialect);
1302
+ }
1303
+ /** One checkout, one run: two harnesses editing the same files at once would undo each other. */
1304
+ refuseBusy(repo) {
1305
+ if ([...this.runs.values()].some((r) => r.repo === repo && !r.end))
1306
+ throw new BoxToolError("repo_busy");
1307
+ }
1308
+ /** One question at a time, oldest first, so a yes answers the prompt the owner read. */
1309
+ askNext(r, live) {
1310
+ const next = live.asks[0];
1311
+ if (!next) return;
1312
+ this.log(`question work=${r.work_id} tool=${next.tool}`);
1313
+ this.emit(r.work_id, { kind: "question", question_id: next.request_id, summary: next.summary });
1314
+ }
1315
+ /** A run left open by a daemon that died: wait for its old process to go, then resume it once. */
1316
+ async recover(r) {
1317
+ if (this.recovering.has(r.work_id)) return;
1318
+ this.recovering.add(r.work_id);
1319
+ try {
1320
+ while (r.pid !== null && this.alive(r.pid, r) && !r.end && !this.stopping) {
1321
+ await sleep2(this.deps.orphanPollMs ?? 2e3);
1322
+ }
1323
+ if (r.end || this.stopping || this.lives.has(r.work_id)) return;
1324
+ this.log(`resume work=${r.work_id} after a restart`);
1325
+ this.spawnRun(r, CONTINUE_PROMPT, true);
1326
+ } finally {
1327
+ this.recovering.delete(r.work_id);
1328
+ }
1329
+ }
1330
+ spawnRun(r, prompt, resume) {
1331
+ const { dialect } = this.deps;
1332
+ const child = spawn(dialect.bin, dialect.args(r, resume), {
1333
+ cwd: r.repo,
1334
+ stdio: ["pipe", "pipe", "pipe"],
1335
+ env: process.env
1336
+ });
1337
+ const live = {
1338
+ child,
1339
+ outstanding: 1,
1340
+ asks: [],
1341
+ lastProgressAt: 0,
1342
+ interrupted: false,
1343
+ stderr: ""
1344
+ };
1345
+ this.lives.set(r.work_id, live);
1346
+ r.pid = child.pid ?? null;
1347
+ this.save();
1348
+ this.log(`spawn work=${r.work_id} pid=${r.pid ?? "none"} ${resume ? "resume" : "new"}`);
1349
+ child.stdin?.on("error", () => {
1350
+ });
1351
+ child.stdin?.write(dialect.opening(r, prompt));
1352
+ if (!dialect.keepsStdin) child.stdin?.end();
1353
+ child.stderr?.on("data", (chunk) => {
1354
+ live.stderr = (live.stderr + chunk.toString("utf-8")).slice(-2e3);
1355
+ });
1356
+ const lines = createInterface({ input: child.stdout });
1357
+ lines.on("line", (line2) => {
1358
+ for (const item of dialect.parse(line2, r)) this.onItem(r, live, item);
1359
+ });
1360
+ child.on("error", (err) => {
1361
+ this.log(`spawn failed work=${r.work_id}: ${err.message.slice(0, 200)}`);
1362
+ });
1363
+ child.on("close", (code, signal) => void this.onExit(r, live, code, signal));
1364
+ }
1365
+ onItem(r, live, item) {
1366
+ switch (item.type) {
1367
+ case "session":
1368
+ if (r.session_id !== item.id) {
1369
+ r.session_id = item.id;
1370
+ this.save();
1371
+ }
1372
+ return;
1373
+ case "text":
1374
+ r.last_text = item.text.slice(0, 300);
1375
+ this.progress(r, live, item.text, false);
1376
+ return;
1377
+ case "tool": {
1378
+ const changed = item.name !== live.lastTool;
1379
+ live.lastTool = item.name;
1380
+ this.progress(r, live, item.target ? `${item.name} ${item.target}` : item.name, changed);
1381
+ return;
1382
+ }
1383
+ case "ask":
1384
+ live.asks.push(item);
1385
+ if (live.asks.length === 1) this.askNext(r, live);
1386
+ return;
1387
+ case "cancel": {
1388
+ const wasAsked = live.asks[0]?.request_id === item.request_id;
1389
+ live.asks = live.asks.filter((x) => x.request_id !== item.request_id);
1390
+ if (wasAsked) this.askNext(r, live);
1391
+ return;
1392
+ }
1393
+ case "result":
1394
+ live.outstanding--;
1395
+ live.result = { ok: item.ok, ...item.text ? { text: item.text } : {} };
1396
+ if (item.text) r.last_text = item.text.slice(0, 300);
1397
+ if (live.outstanding <= 0 && live.asks.length === 0) live.child.stdin?.end();
1398
+ return;
1399
+ }
1400
+ }
1401
+ progress(r, live, line2, force) {
1402
+ const now = this.now();
1403
+ if (!force && now - live.lastProgressAt < (this.deps.progressMs ?? 3e4)) return;
1404
+ live.lastProgressAt = now;
1405
+ this.emit(r.work_id, {
1406
+ kind: "progress",
1407
+ summary: line2.replace(/\s+/g, " ").trim().slice(0, 200)
1408
+ });
1409
+ }
1410
+ async onExit(r, live, code, signal) {
1411
+ if (this.lives.get(r.work_id) === live) this.lives.delete(r.work_id);
1412
+ if (this.stopping || r.end) return;
1413
+ const exit = signal ? `signal ${signal}` : `code ${code}`;
1414
+ this.log(
1415
+ `exit work=${r.work_id} ${exit} result=${live.result ? live.result.ok ? "ok" : "error" : "none"}`
1416
+ );
1417
+ if (live.interrupted) {
1418
+ await this.end(r, { kind: "failed", summary: "The run was stopped." });
1419
+ return;
1420
+ }
1421
+ if (live.next) {
1422
+ this.spawnRun(r, live.next, true);
1423
+ return;
1424
+ }
1425
+ if (code === 0 && live.result?.ok) {
1426
+ const text = live.result.text?.trim() || r.last_text;
1427
+ const { pr, note } = await this.outcome(r, text);
1428
+ const summary = [note, text].filter(Boolean).join(" ").replace(/\s+/g, " ");
1429
+ await this.end(r, {
1430
+ kind: "settled",
1431
+ ...summary ? { summary: summary.slice(0, SUMMARY_MAX) } : {},
1432
+ ...pr ? { pr_url: pr } : {}
1433
+ });
1434
+ return;
1435
+ }
1436
+ if (live.stderr)
1437
+ this.log(`stderr work=${r.work_id}: ${live.stderr.trim().split("\n").at(-1)?.slice(0, 200)}`);
1438
+ await this.end(r, {
1439
+ kind: "failed",
1440
+ summary: live.result ? "The run ended with an error." : `The run exited with ${exit}.`
1441
+ });
1442
+ }
1443
+ /**
1444
+ * The PR a run produced: one its last text names, else the PR of the
1445
+ * branch, but only when the run moved HEAD. A run that left HEAD where it
1446
+ * started produced nothing, and the branch's PR belongs to someone else's
1447
+ * work. A run that committed without pushing says so.
1448
+ */
1449
+ async outcome(r, text) {
1450
+ const named = prUrlIn(text);
1451
+ if (named) return { pr: named };
1452
+ if (!r.head_at_launch) return { pr: null };
1453
+ const head = await this.repo.head(r.repo);
1454
+ if (!head || head === r.head_at_launch) return { pr: null };
1455
+ const pr = await this.repo.branchPr(r.repo);
1456
+ if (pr) return { pr };
1457
+ return await this.repo.pushed(r.repo) ? { pr: null } : { pr: null, note: `Committed ${head.slice(0, 7)}, not pushed.` };
1458
+ }
1459
+ async end(r, end) {
1460
+ if (r.end) return;
1461
+ r.end = { ...end, at: new Date(this.now()).toISOString() };
1462
+ r.pid = null;
1463
+ this.save();
1464
+ this.emit(r.work_id, end);
1465
+ }
1466
+ emit(id, event) {
1467
+ for (const listener of [...this.listeners.get(id) ?? []]) listener(event);
1468
+ }
1469
+ write(live, line2) {
1470
+ live.child.stdin?.write(line2);
1471
+ }
1472
+ remember(r, commandId, delivered) {
1473
+ r.commands = [
1474
+ ...r.commands ?? [],
1475
+ [commandId, delivered]
1476
+ ].slice(-COMMANDS_KEPT);
1477
+ this.save();
1478
+ }
1479
+ record(id) {
1480
+ const r = this.runs.get(id);
1481
+ if (!r) throw new BoxToolError("bad_args");
1482
+ return r;
1483
+ }
1484
+ statusOf(r) {
1485
+ if (this.lives.has(r.work_id)) return "running";
1486
+ if (!r.end) return "pending";
1487
+ return r.end.kind === "settled" ? "completed" : "failed";
1488
+ }
1489
+ load() {
1490
+ try {
1491
+ const raw = JSON.parse(readFileSync2(this.file, "utf-8"));
1492
+ const cutoff = this.now() - KEEP_MS2;
1493
+ return Array.isArray(raw) ? raw.filter(
1494
+ (r) => typeof r?.work_id === "string" && typeof r?.repo === "string" && !(r.end && Date.parse(r.end.at) < cutoff)
1495
+ ) : [];
1496
+ } catch {
1497
+ return [];
1498
+ }
1499
+ }
1500
+ save() {
1501
+ mkdirSync2(dirname2(this.file), { recursive: true, mode: 448 });
1502
+ const tmp = `${this.file}.tmp`;
1503
+ writeFileSync2(tmp, `${JSON.stringify([...this.runs.values()], null, 2)}
1504
+ `, { mode: 384 });
1505
+ chmodSync2(tmp, 384);
1506
+ renameSync2(tmp, this.file);
1507
+ }
1508
+ };
1509
+
1510
+ // src/drivers/claude-code.ts
1511
+ var SUBSCRIPTIONS = {
1512
+ max: "Claude Max",
1513
+ pro: "Claude Pro",
1514
+ team: "Claude Team",
1515
+ enterprise: "Claude Enterprise"
1516
+ };
1517
+ var YES_WORDS = /* @__PURE__ */ new Set([
1518
+ "y",
1519
+ "yes",
1520
+ "yep",
1521
+ "yeah",
1522
+ "allow",
1523
+ "allow it",
1524
+ "ok",
1525
+ "okay",
1526
+ "approve",
1527
+ "approved",
1528
+ "go ahead",
1529
+ "sure",
1530
+ "do it"
1531
+ ]);
1532
+ function isYes(reply) {
1533
+ return YES_WORDS.has(
1534
+ reply.trim().toLowerCase().replace(/[.!\s]+$/, "")
1535
+ );
1536
+ }
1537
+ function exec(bin, args) {
1538
+ return new Promise(
1539
+ (resolve3) => execFile3(
1540
+ bin,
1541
+ args,
1542
+ { timeout: 1e4, encoding: "utf-8" },
1543
+ (err, out2) => resolve3(err ? null : String(out2))
1544
+ )
1545
+ );
1546
+ }
1547
+ function claudeAccount(raw) {
1548
+ try {
1549
+ const auth = JSON.parse(raw ?? "");
1550
+ if (auth.loggedIn !== true) return { signedIn: false, account: null };
1551
+ const plan = auth.subscriptionType ? SUBSCRIPTIONS[auth.subscriptionType] : void 0;
1552
+ return {
1553
+ signedIn: true,
1554
+ account: plan ?? (auth.authMethod === "claude.ai" ? "Claude" : "API key")
1555
+ };
1556
+ } catch {
1557
+ return { signedIn: false, account: null };
1558
+ }
1559
+ }
1560
+ async function probeClaude(bin = "claude") {
1561
+ const version = (await exec(bin, ["--version"]))?.trim().split(/\s+/)[0];
1562
+ if (!version) return null;
1563
+ const { signedIn, account } = claudeAccount(await exec(bin, ["auth", "status", "--json"]));
1564
+ return {
1565
+ id: "claude-code",
1566
+ name: "Claude Code",
1567
+ version,
1568
+ ready: signedIn,
1569
+ signedIn,
1570
+ account,
1571
+ defaultModel: null
1572
+ };
1573
+ }
1574
+ function pathOf(input) {
1575
+ const fields = input ?? {};
1576
+ const path = fields.file_path ?? fields.notebook_path ?? fields.path;
1577
+ return typeof path === "string" ? path : void 0;
1578
+ }
1579
+ function shownPath(path, repo) {
1580
+ const inside = relative(repo, resolve(repo, path));
1581
+ return inside && !inside.startsWith("..") && !isAbsolute(inside) ? inside : path;
1582
+ }
1583
+ function questionsOf(input) {
1584
+ const questions = input?.questions;
1585
+ return Array.isArray(questions) ? questions.filter((q) => typeof q?.question === "string") : [];
1586
+ }
1587
+ var REPLY = "Reply yes to allow it, or say what to do instead.";
1588
+ function cut(text) {
1589
+ const line2 = text.replace(/\s+/g, " ").trim();
1590
+ return line2.length > 200 ? `${line2.slice(0, 200)}\u2026` : line2;
1591
+ }
1592
+ function askSummary(tool, input, repo) {
1593
+ if (tool === "AskUserQuestion") return questionLine(questionsOf(input));
1594
+ const fields = input ?? {};
1595
+ if (tool === "Bash") {
1596
+ const shown = cut(String(fields.command ?? ""));
1597
+ const why = typeof fields.description === "string" ? ` (${fields.description.slice(0, 100)})` : "";
1598
+ return `Claude Code asks to run: ${shown}${why}. ${REPLY}`;
1599
+ }
1600
+ if (tool === "WebFetch" && typeof fields.url === "string")
1601
+ return `Claude Code asks to fetch ${cut(fields.url)}. ${REPLY}`;
1602
+ if (tool.startsWith("mcp__"))
1603
+ return `Claude Code asks to use ${tool} with ${cut(JSON.stringify(fields))}. ${REPLY}`;
1604
+ const path = pathOf(fields);
1605
+ const where = path ? ` on ${shownPath(path, repo)}` : "";
1606
+ return `Claude Code asks to use ${tool}${where}. ${REPLY}`;
1607
+ }
1608
+ function line(value) {
1609
+ return `${JSON.stringify(value)}
1610
+ `;
1611
+ }
1612
+ function userMessage(run2, text, priority) {
1613
+ return {
1614
+ type: "user",
1615
+ message: { role: "user", content: [{ type: "text", text }] },
1616
+ parent_tool_use_id: null,
1617
+ session_id: run2.session_id ?? run2.work_id,
1618
+ ...priority ? { priority } : {}
1619
+ };
1620
+ }
1621
+ function parseClaudeLine(raw, run2) {
1622
+ let msg;
1623
+ try {
1624
+ msg = JSON.parse(raw);
1625
+ } catch {
1626
+ return [];
1627
+ }
1628
+ if (msg.type === "system" && msg.subtype === "init" && typeof msg.session_id === "string") {
1629
+ return [{ type: "session", id: msg.session_id }];
1630
+ }
1631
+ if (msg.type === "assistant") {
1632
+ const content = msg.message?.content;
1633
+ if (!Array.isArray(content)) return [];
1634
+ return content.flatMap((block) => {
1635
+ if (block?.type === "text" && typeof block.text === "string" && block.text.trim())
1636
+ return [{ type: "text", text: block.text }];
1637
+ if (block?.type === "tool_use" && typeof block.name === "string" && block.name !== "AskUserQuestion") {
1638
+ const path = pathOf(block.input);
1639
+ return [{ type: "tool", name: block.name, ...path ? { target: basename2(path) } : {} }];
1640
+ }
1641
+ return [];
1642
+ });
1643
+ }
1644
+ if (msg.type === "control_request") {
1645
+ const request = msg.request;
1646
+ if (request?.subtype !== "can_use_tool" || typeof msg.request_id !== "string") return [];
1647
+ const tool = request.tool_name ?? "a tool";
1648
+ return [
1649
+ {
1650
+ type: "ask",
1651
+ request_id: msg.request_id,
1652
+ tool,
1653
+ input: request.input ?? {},
1654
+ summary: askSummary(tool, request.input, run2.repo)
1655
+ }
1656
+ ];
1657
+ }
1658
+ if (msg.type === "control_cancel_request" && typeof msg.request_id === "string") {
1659
+ return [{ type: "cancel", request_id: msg.request_id }];
1660
+ }
1661
+ if (msg.type === "result") {
1662
+ return [
1663
+ {
1664
+ type: "result",
1665
+ ok: msg.subtype === "success" && msg.is_error !== true,
1666
+ ...typeof msg.result === "string" ? { text: msg.result } : {}
1667
+ }
1668
+ ];
1669
+ }
1670
+ return [];
1671
+ }
1672
+ function claudeDialect(bin = "claude") {
1673
+ return {
1674
+ name: "claude-code",
1675
+ aliases: ["claude-code", "claudeAgent", "claude"],
1676
+ bin,
1677
+ capabilities: ["view", "start", "steer", "report"],
1678
+ keepsStdin: true,
1679
+ args(run2, resume) {
1680
+ return [
1681
+ "--print",
1682
+ "--verbose",
1683
+ "--output-format",
1684
+ "stream-json",
1685
+ "--input-format",
1686
+ "stream-json",
1687
+ "--permission-prompt-tool",
1688
+ "stdio",
1689
+ "--permission-mode",
1690
+ permissionMode(run2.runtime_mode),
1691
+ "--add-dir",
1692
+ run2.repo,
1693
+ ...resume ? ["--resume", run2.session_id ?? run2.work_id] : ["--session-id", run2.work_id],
1694
+ ...run2.model ? ["--model", run2.model] : []
1695
+ ];
1696
+ },
1697
+ opening(run2, prompt) {
1698
+ return line({
1699
+ type: "control_request",
1700
+ request_id: "cloop-init",
1701
+ request: { subtype: "initialize" }
1702
+ }) + line(userMessage(run2, prompt));
1703
+ },
1704
+ userLine(run2, text, mode) {
1705
+ return line(userMessage(run2, text, mode === "steer" ? "now" : "next"));
1706
+ },
1707
+ answerLine(ask, text) {
1708
+ const input = ask.input ?? {};
1709
+ const response = ask.tool === "AskUserQuestion" ? {
1710
+ behavior: "allow",
1711
+ updatedInput: {
1712
+ ...input,
1713
+ answers: Object.fromEntries(questionsOf(input).map((q) => [q.question, text]))
1714
+ }
1715
+ } : isYes(text) ? { behavior: "allow", updatedInput: input } : { behavior: "deny", message: text };
1716
+ return line({
1717
+ type: "control_response",
1718
+ response: { subtype: "success", request_id: ask.request_id, response }
1719
+ });
1720
+ },
1721
+ parse: parseClaudeLine,
1722
+ owns: (run2, command) => command.includes(basename2(bin)) && [run2.work_id, run2.session_id].some((id) => id !== null && command.includes(id)),
1723
+ probe: () => probeClaude(bin)
1724
+ };
1725
+ }
1726
+
1727
+ // src/drivers/codex.ts
1728
+ import { execFile as execFile4 } from "child_process";
1729
+ import { basename as basename3 } from "path";
1730
+ var SANDBOX = {
1731
+ "approval-required": "read-only",
1732
+ "auto-accept-edits": "workspace-write",
1733
+ auto: "workspace-write",
1734
+ "full-access": "danger-full-access"
1735
+ };
1736
+ function exec2(bin, args) {
1737
+ return new Promise(
1738
+ (resolve3) => execFile4(
1739
+ bin,
1740
+ args,
1741
+ { timeout: 1e4, encoding: "utf-8" },
1742
+ (err, out2, errOut) => resolve3({ ok: !err, out: `${out2}${errOut}` })
1743
+ )
1744
+ );
1745
+ }
1746
+ function codexAccount(ok, out2) {
1747
+ if (!ok || !/logged in/i.test(out2) || /not logged in/i.test(out2))
1748
+ return { signedIn: false, account: null };
1749
+ return { signedIn: true, account: /chatgpt/i.test(out2) ? "ChatGPT" : "API key" };
1750
+ }
1751
+ async function probeCodex(bin = "codex") {
1752
+ const version = await exec2(bin, ["--version"]);
1753
+ if (!version.ok) return null;
1754
+ const status = await exec2(bin, ["login", "status"]);
1755
+ const { signedIn, account } = codexAccount(status.ok, status.out);
1756
+ return {
1757
+ id: "codex",
1758
+ name: "Codex",
1759
+ version: version.out.trim().split(/\s+/).at(-1) ?? null,
1760
+ ready: signedIn,
1761
+ signedIn,
1762
+ account,
1763
+ defaultModel: null,
1764
+ experimental: true
1765
+ };
1766
+ }
1767
+ function parseCodexLine(raw) {
1768
+ let msg;
1769
+ try {
1770
+ msg = JSON.parse(raw);
1771
+ } catch {
1772
+ return [];
1773
+ }
1774
+ if (msg.type === "thread.started" && typeof msg.thread_id === "string")
1775
+ return [{ type: "session", id: msg.thread_id }];
1776
+ const item = msg.item;
1777
+ if (msg.type === "item.completed" && item?.type === "agent_message" && typeof item.text === "string")
1778
+ return [{ type: "text", text: item.text }];
1779
+ if (msg.type === "item.started" && item?.type === "command_execution")
1780
+ return [{ type: "tool", name: "Bash" }];
1781
+ if (msg.type === "item.completed" && item?.type === "file_change") {
1782
+ const changes = Array.isArray(item.changes) ? item.changes : [];
1783
+ const path = changes[0]?.path;
1784
+ return [
1785
+ {
1786
+ type: "tool",
1787
+ name: "Edit",
1788
+ ...typeof path === "string" ? { target: basename3(path) } : {}
1789
+ }
1790
+ ];
1791
+ }
1792
+ if (msg.type === "turn.completed") return [{ type: "result", ok: true }];
1793
+ if (msg.type === "turn.failed") return [{ type: "result", ok: false }];
1794
+ return [];
1795
+ }
1796
+ function codexDialect(bin = "codex") {
1797
+ return {
1798
+ name: "codex",
1799
+ aliases: ["codex"],
1800
+ bin,
1801
+ capabilities: ["view", "start", "report"],
1802
+ keepsStdin: false,
1803
+ args(run2, resume) {
1804
+ const model = run2.model ? ["--model", run2.model] : [];
1805
+ const sandbox = SANDBOX[run2.runtime_mode ?? "auto-accept-edits"];
1806
+ return resume && run2.session_id ? [
1807
+ "exec",
1808
+ "resume",
1809
+ run2.session_id,
1810
+ "--json",
1811
+ "-c",
1812
+ `sandbox_mode="${sandbox}"`,
1813
+ ...model,
1814
+ "-"
1815
+ ] : ["exec", "--cd", run2.repo, "--json", "--sandbox", sandbox, ...model, "-"];
1816
+ },
1817
+ opening: (_run, prompt) => prompt,
1818
+ parse: parseCodexLine,
1819
+ // A fresh run's command line names no id: Codex makes its session id after the start. So a run is also matched by its exact repository, which one open run per repository makes unique.
1820
+ owns: (run2, command) => command.includes(basename3(bin)) && command.includes("exec") && command.includes("--json") && (run2.session_id !== null && command.includes(run2.session_id) || command.includes(`--cd ${run2.repo} `)),
1821
+ probe: () => probeCodex(bin)
1822
+ };
1823
+ }
1824
+
1825
+ // src/runner-config.ts
1826
+ import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "fs";
1827
+ import { homedir as homedir3 } from "os";
1828
+ import { dirname as dirname3, join as join3 } from "path";
1829
+ var BOX_FILE = "box.json";
1830
+ function boxPath() {
1831
+ return process.env.CLOOP_BOX_FILE ?? join3(homedir3(), CONFIG_DIR, BOX_FILE);
1832
+ }
1833
+ function isLocal(cfg) {
1834
+ return cfg.driver === "claude-code" || cfg.driver === "codex";
1835
+ }
1836
+ function readRunnerConfig() {
1837
+ let parsed;
1838
+ try {
1839
+ parsed = JSON.parse(readFileSync3(boxPath(), "utf-8"));
1840
+ } catch {
1841
+ return null;
1842
+ }
1843
+ if (parsed.driver === "claude-code" || parsed.driver === "codex") {
1844
+ const ok = typeof parsed.deviceToken === "string" && typeof parsed.environmentId === "string" && typeof parsed.bin === "string" && Array.isArray(parsed.repos);
1845
+ return ok ? parsed : null;
1846
+ }
1847
+ if (typeof parsed.t3Url !== "string" || typeof parsed.token !== "string") return null;
1848
+ return parsed;
1849
+ }
1850
+ function writeBoxConfig(cfg) {
1851
+ const path = boxPath();
1852
+ mkdirSync3(dirname3(path), { recursive: true, mode: 448 });
1853
+ const temp = `${path}.${process.pid}.tmp`;
1854
+ writeFileSync3(temp, `${JSON.stringify(cfg, null, 2)}
1855
+ `, { mode: 384 });
1856
+ chmodSync3(temp, 384);
1857
+ renameSync3(temp, path);
1858
+ }
1859
+
1860
+ // src/commands/connect.ts
1861
+ var DEFAULT_T3_URL = "http://127.0.0.1:3773";
1862
+ var CLEAN_ENV = { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH };
1863
+ var out = (line2) => console.log(line2);
1864
+ var bold = (s) => `\x1B[1m${s}\x1B[0m`;
1865
+ var dim = (s) => `\x1B[2m${s}\x1B[0m`;
1866
+ var red = (s) => `\x1B[31m${s}\x1B[0m`;
1867
+ function flag(argv, name) {
1868
+ const i = argv.indexOf(name);
1869
+ return i >= 0 ? argv[i + 1] : void 0;
1870
+ }
1871
+ function flags(argv, name) {
1872
+ return argv.flatMap((a, i) => a === name && argv[i + 1] ? [argv[i + 1]] : []);
1873
+ }
1874
+ function compareVersions(a, b) {
1875
+ return a.localeCompare(b, void 0, { numeric: true });
1876
+ }
1877
+ function resolveT3Bin(explicit) {
1878
+ if (explicit) return explicit;
1879
+ if (process.env.T3_BIN) return process.env.T3_BIN;
1880
+ const versions = join4(homedir4(), ".t3", "runtime", "versions");
1881
+ try {
1882
+ const newest = readdirSync(versions).sort(compareVersions).at(-1);
1883
+ if (newest && existsSync(join4(versions, newest, "t3"))) return join4(versions, newest, "t3");
1884
+ } catch {
1885
+ }
1886
+ return which("t3");
1887
+ }
1888
+ function which(bin) {
1889
+ try {
1890
+ return execFileSync3("which", [bin], { encoding: "utf-8", env: CLEAN_ENV }).trim() || null;
1891
+ } catch {
1892
+ return null;
1893
+ }
1894
+ }
1895
+ async function mintSession(t3Url, t3Bin) {
1896
+ const env = await readEnvironment(t3Url);
1897
+ const protocol = env.orchestrationProtocolVersion ?? 1;
1898
+ if (protocol < MIN_PROTOCOL) {
1899
+ throw new Error(
1900
+ `T3 ${env.serverVersion} speaks orchestration protocol ${protocol}; a workstation needs ${MIN_PROTOCOL} (the V2 nightly or later).`
1901
+ );
1902
+ }
1903
+ const pairing = JSON.parse(
1904
+ execFileSync3(t3Bin, ["auth", "pairing", "create", "--ttl", "5m", "--json"], {
1905
+ encoding: "utf-8",
1906
+ env: CLEAN_ENV,
1907
+ timeout: 15e3
1908
+ })
1909
+ );
1910
+ const token = await exchangePairing(t3Url, pairing.credential, "cloop box");
1911
+ return {
1912
+ t3Url,
1913
+ t3Bin,
1914
+ token: token.access_token,
1915
+ scope: token.scope,
1916
+ expiresAt: new Date(Date.now() + token.expires_in * 1e3).toISOString(),
1917
+ environmentId: env.environmentId,
1918
+ label: env.label
1919
+ };
1920
+ }
1921
+ async function connectBox(steps) {
1922
+ const environment = await steps.readEnvironment();
1923
+ const session = await steps.mintSession();
1924
+ const deviceToken = await steps.deviceLogin(environment);
1925
+ const cfg = { ...session, deviceToken };
1926
+ steps.writeBoxConfig(cfg);
1927
+ return cfg;
1928
+ }
1929
+ var NONE = "No coding agent found on this machine. Install Claude Code or Codex, sign in, then run `cloop connect` again.";
1930
+ var SIGNED_OUT = {
1931
+ "claude-code": "Claude Code is installed but not signed in. Run `claude` once and sign in, then run `cloop connect` again.",
1932
+ codex: "Codex is installed but not signed in. Run `codex login`, then run `cloop connect` again."
1933
+ };
1934
+ function chooseDriver(found, forced) {
1935
+ const local = (driver) => {
1936
+ const harness = driver === "claude-code" ? found.claude : found.codex;
1937
+ if (!harness)
1938
+ return {
1939
+ ok: false,
1940
+ line: `${driver === "codex" ? "Codex" : "Claude Code"} is not installed here.`
1941
+ };
1942
+ return harness.signedIn ? { ok: true, driver, kind: "local" } : { ok: false, line: SIGNED_OUT[driver] };
1943
+ };
1944
+ if (forced === "t3")
1945
+ return found.t3 ? { ok: true, driver: "t3", kind: "workstation" } : { ok: false, line: `No T3 Code server answers at ${DEFAULT_T3_URL}.` };
1946
+ if (forced) return local(forced);
1947
+ if (found.t3) return { ok: true, driver: "t3", kind: "workstation" };
1948
+ if (found.claude?.signedIn) return local("claude-code");
1949
+ if (found.codex?.signedIn) return local("codex");
1950
+ if (found.claude) return local("claude-code");
1951
+ if (found.codex) return local("codex");
1952
+ return { ok: false, line: NONE };
1953
+ }
1954
+ function systemdAssignment(assignment) {
1955
+ return `"${assignment.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
1956
+ }
1957
+ function systemdWord(arg) {
1958
+ const escaped = arg.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%").replace(/\$/g, "$$$$");
1959
+ return `"${escaped}"`;
1960
+ }
1961
+ function programFor(script, node, npx, version) {
1962
+ if (!script.includes("/_npx/")) return [node, script, "box", "run"];
1963
+ if (!npx)
1964
+ return "npx is not on PATH, so the service cannot run Cloop. Install it with `npm install -g @cloop/runner` and run `cloop connect` again.";
1965
+ return [npx, "-y", `@cloop/runner@${version}`, "box", "run"];
1966
+ }
1967
+ async function awaitDaemon(since, read = readRunnerState, { timeoutMs = 15e3, pollMs = 500 } = {}) {
1968
+ for (let waited = 0; ; waited += pollMs) {
1969
+ const state = read();
1970
+ if (state && Date.parse(state.connected_at) >= since) return true;
1971
+ if (waited >= timeoutMs) return false;
1972
+ await new Promise((r) => setTimeout(r, pollMs));
1973
+ }
1974
+ }
1975
+ var UNIT_ENV = [
1976
+ "PATH",
1977
+ "CLOOP_BOX_FILE",
1978
+ "CLOOP_BOX_THREADS_FILE",
1979
+ "CLOOP_LOCAL_RUNS_FILE",
1980
+ "CLOOP_MESH_URL",
1981
+ "CLOOP_ORIGIN"
1982
+ ];
1983
+ function unitEnv(env) {
1984
+ const picked = { PATH: "/usr/bin:/bin" };
1985
+ for (const key of UNIT_ENV) {
1986
+ const value = env[key];
1987
+ if (value) picked[key] = value;
1988
+ }
1989
+ return picked;
1990
+ }
1991
+ function unitFor(opts) {
1992
+ const env = Object.entries(opts.env);
1993
+ const name = opts.kind === "workstation" ? "box" : "runner";
1994
+ if (opts.platform === "darwin") {
1995
+ const label = `com.cloop.${name}`;
1996
+ const path2 = join4(opts.dir ?? join4(opts.home, "Library", "LaunchAgents"), `${label}.plist`);
1997
+ const log = join4(opts.home, "Library", "Logs", `cloop-${name}.log`);
1998
+ const xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1999
+ const contents2 = [
2000
+ '<?xml version="1.0" encoding="UTF-8"?>',
2001
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
2002
+ '<plist version="1.0">',
2003
+ "<dict>",
2004
+ ` <key>Label</key><string>${label}</string>`,
2005
+ " <key>ProgramArguments</key>",
2006
+ " <array>",
2007
+ ...opts.program.map((arg) => ` <string>${xml(arg)}</string>`),
2008
+ " </array>",
2009
+ " <key>EnvironmentVariables</key>",
2010
+ ` <dict>${env.map(([key, value]) => `<key>${key}</key><string>${xml(value)}</string>`).join("")}</dict>`,
2011
+ " <key>RunAtLoad</key><true/>",
2012
+ " <key>KeepAlive</key><true/>",
2013
+ " <key>ThrottleInterval</key><integer>10</integer>",
2014
+ ` <key>StandardOutPath</key><string>${xml(log)}</string>`,
2015
+ ` <key>StandardErrorPath</key><string>${xml(log)}</string>`,
2016
+ "</dict>",
2017
+ "</plist>",
2018
+ ""
2019
+ ].join("\n");
2020
+ const domain = `gui/${opts.uid}`;
2021
+ return {
2022
+ path: path2,
2023
+ contents: contents2,
2024
+ start: [
2025
+ { command: ["launchctl", "bootout", `${domain}/${label}`], mayFail: true },
2026
+ { command: ["launchctl", "bootstrap", domain, path2], tries: 5 }
2027
+ ],
2028
+ logs: `tail -f ${log}`,
2029
+ tail: ["tail", "-n", "20", log]
2030
+ };
2031
+ }
2032
+ const unit = `cloop-${name}.service`;
2033
+ const path = join4(opts.dir ?? join4(opts.home, ".config", "systemd", "user"), unit);
2034
+ const contents = [
2035
+ "[Unit]",
2036
+ `Description=Cloop ${name}: answers the Cloop Agent over the mesh`,
2037
+ "After=network-online.target",
2038
+ // A disconnected runner exits 1 on every start. Three in ten minutes and
2039
+ // systemd marks the unit failed instead of restarting it forever.
2040
+ "StartLimitIntervalSec=600",
2041
+ "StartLimitBurst=3",
2042
+ "",
2043
+ "[Service]",
2044
+ ...env.map(([key, value]) => `Environment=${systemdAssignment(`${key}=${value}`)}`),
2045
+ `ExecStart=${opts.program.map(systemdWord).join(" ")}`,
2046
+ "Restart=always",
2047
+ "RestartSec=5",
2048
+ "",
2049
+ "[Install]",
2050
+ "WantedBy=default.target",
2051
+ ""
2052
+ ].join("\n");
2053
+ return {
2054
+ path,
2055
+ contents,
2056
+ start: [
2057
+ { command: ["systemctl", "--user", "reset-failed", unit], mayFail: true },
2058
+ { command: ["systemctl", "--user", "daemon-reload"] },
2059
+ { command: ["systemctl", "--user", "enable", unit] },
2060
+ { command: ["systemctl", "--user", "restart", unit] }
2061
+ ],
2062
+ logs: `journalctl --user -u ${unit} -f`,
2063
+ tail: ["journalctl", "--user", "-u", unit, "-n", "20", "--no-pager"]
2064
+ };
2065
+ }
2066
+ function resolveRepos(paths, toplevel) {
2067
+ const repos = [];
2068
+ for (const p of paths) {
2069
+ const top = toplevel(resolve2(p));
2070
+ if (!top)
2071
+ return `${p} is not a git checkout. Pass --repo <path> for each repository Cloop may work in.`;
2072
+ if (!repos.some((r) => r.path === top)) repos.push({ label: basename4(top), path: top });
2073
+ }
2074
+ return repos;
2075
+ }
2076
+ function gitTop(path) {
2077
+ try {
2078
+ return execFileSync3("git", ["-C", path, "rev-parse", "--show-toplevel"], {
2079
+ encoding: "utf-8",
2080
+ stdio: ["ignore", "pipe", "ignore"]
2081
+ }).trim();
2082
+ } catch {
2083
+ return null;
2084
+ }
2085
+ }
2086
+ async function t3Answers(t3Url) {
2087
+ try {
2088
+ await readEnvironment(t3Url);
2089
+ return true;
2090
+ } catch {
2091
+ return false;
2092
+ }
2093
+ }
2094
+ function harnessLine(h) {
2095
+ const version = h.version ? ` ${h.version}` : "";
2096
+ const account = h.signedIn ? h.account ?? "signed in" : "signed out";
2097
+ return `${h.name}${version}, ${account}${h.experimental ? " (experimental)" : ""}`;
2098
+ }
2099
+ async function startService(unit, run2 = (command) => void execFileSync3(command[0], command.slice(1), { stdio: "ignore", timeout: 15e3 }), wait = (ms) => new Promise((r) => setTimeout(r, ms))) {
2100
+ for (const step of unit.start) {
2101
+ const tries = step.tries ?? 1;
2102
+ for (let attempt = 1; ; attempt++) {
2103
+ try {
2104
+ run2(step.command);
2105
+ break;
2106
+ } catch (err) {
2107
+ if (step.mayFail) break;
2108
+ if (attempt >= tries) throw err;
2109
+ await wait(1e3);
2110
+ }
2111
+ }
2112
+ }
2113
+ }
2114
+ async function installService(kind, argv) {
2115
+ if (argv.includes("--no-service")) {
2116
+ out(` Run ${dim("cloop box run")} to go live.`);
2117
+ return;
2118
+ }
2119
+ const npxBeside = join4(dirname4(process.execPath), "npx");
2120
+ const program = programFor(
2121
+ process.argv[1] ?? "cloop",
2122
+ process.execPath,
2123
+ existsSync(npxBeside) ? npxBeside : which("npx"),
2124
+ VERSION
2125
+ );
2126
+ if (typeof program === "string") {
2127
+ out(`${red("\u2717")} ${program}`);
2128
+ process.exit(1);
2129
+ }
2130
+ const unit = unitFor({
2131
+ platform: process.platform,
2132
+ kind,
2133
+ home: homedir4(),
2134
+ program,
2135
+ env: unitEnv(process.env),
2136
+ uid: process.getuid?.() ?? 0,
2137
+ ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
2138
+ });
2139
+ mkdirSync4(join4(unit.path, ".."), { recursive: true });
2140
+ writeFileSync4(unit.path, unit.contents);
2141
+ if (argv.includes("--no-start")) {
2142
+ out(
2143
+ ` Service: wrote ${unit.path}. Start it with: ${dim(unit.start.map((step) => step.command.join(" ")).join(" && "))}`
2144
+ );
2145
+ return;
2146
+ }
2147
+ const since = Date.now();
2148
+ try {
2149
+ await startService(unit);
2150
+ } catch (err) {
2151
+ out(
2152
+ `${red("\u2717")} Wrote ${unit.path} but could not start it: ${err instanceof Error ? err.message : String(err)}`
2153
+ );
2154
+ process.exit(1);
2155
+ }
2156
+ if (!await awaitDaemon(since)) {
2157
+ out(
2158
+ `${red("\u2717")} ${unit.path} started, but the runner did not reach Cloop within 15 s. Its last log lines:`
2159
+ );
2160
+ try {
2161
+ out(
2162
+ execFileSync3(unit.tail[0], unit.tail.slice(1), {
2163
+ encoding: "utf-8",
2164
+ timeout: 5e3
2165
+ })
2166
+ );
2167
+ } catch {
2168
+ out(` (no log yet; run ${unit.logs})`);
2169
+ }
2170
+ process.exit(1);
2171
+ }
2172
+ out(` Service: ${unit.path}, started and connected. Logs: ${dim(unit.logs)}`);
2173
+ }
2174
+ async function connectT3(argv) {
2175
+ const t3Url = (flag(argv, "--t3-url") ?? DEFAULT_T3_URL).replace(/\/+$/, "");
2176
+ const t3Bin = resolveT3Bin(flag(argv, "--t3-bin"));
2177
+ if (!t3Bin) {
2178
+ out(`${red("\u2717")} No t3 binary found. Pass --t3-bin or set T3_BIN.`);
2179
+ process.exit(1);
2180
+ }
2181
+ const cfg = await connectBox({
2182
+ readEnvironment: async () => {
2183
+ const environment = await readEnvironment(t3Url);
2184
+ out(
2185
+ `${bold("Cloop box")} Connecting ${environment.label} (T3 ${environment.serverVersion}) to Cloop.`
2186
+ );
2187
+ return environment;
2188
+ },
2189
+ mintSession: () => mintSession(t3Url, t3Bin),
2190
+ deviceLogin: (environment) => deviceLogin({
2191
+ origin: getOrigin(),
2192
+ deviceName: flag(argv, "--name") ?? hostname2(),
2193
+ device: {
2194
+ kind: "workstation",
2195
+ environmentId: environment.environmentId,
2196
+ label: environment.label,
2197
+ version: environment.serverVersion
2198
+ }
2199
+ }),
2200
+ writeBoxConfig
2201
+ });
2202
+ out(
2203
+ `${bold("Cloop box")} T3 ${cfg.label} paired with scope ${cfg.scope}, until ${cfg.expiresAt.slice(0, 10)}.`
2204
+ );
2205
+ const driver = new T3Driver({ client: () => new T3Client(cfg.t3Url, cfg.token), t3Bin });
2206
+ const report = await runBoxTool({ driver }, "status", {});
2207
+ if (report.ok) {
2208
+ const value = report.value;
2209
+ for (const h of value.harnesses) {
2210
+ out(` ${h.signedIn ? "\u25CF" : "\u25CB"} ${h.name}${h.account ? dim(` ${h.account}`) : ""}`);
2211
+ }
2212
+ out(` ${value.threads.unsettled} open threads, ${value.threads.running} running.`);
2213
+ } else {
2214
+ out(`${red("\u2717")} Status failed: ${report.error}`);
2215
+ }
2216
+ await installService("workstation", argv);
2217
+ }
2218
+ async function connectLocal(driver, found, argv) {
2219
+ const repos = resolveRepos(
2220
+ flags(argv, "--repo").length ? flags(argv, "--repo") : [process.cwd()],
2221
+ gitTop
2222
+ );
2223
+ if (typeof repos === "string") {
2224
+ out(`${red("\u2717")} ${repos}`);
2225
+ process.exit(1);
2226
+ }
2227
+ const harness = driver === "claude-code" ? found.claude : found.codex;
2228
+ const bin = which(driver === "claude-code" ? "claude" : "codex") ?? (driver === "claude-code" ? "claude" : "codex");
2229
+ const previous = readRunnerConfig();
2230
+ const deviceName = flag(argv, "--name") ?? hostname2();
2231
+ const device = {
2232
+ kind: "local",
2233
+ environmentId: previous && isLocal(previous) ? previous.environmentId : `local:${randomUUID2()}`,
2234
+ label: deviceName,
2235
+ version: `${harness.name} ${harness.version ?? ""}`.trim()
2236
+ };
2237
+ out(
2238
+ `${bold("Cloop runner")} Connecting ${deviceName} as a Local runner with ${harnessLine(harness)}.`
2239
+ );
2240
+ const deviceToken = await deviceLogin({ origin: getOrigin(), deviceName, device });
2241
+ const cfg = {
2242
+ driver,
2243
+ environmentId: device.environmentId,
2244
+ label: deviceName,
2245
+ deviceToken,
2246
+ repos,
2247
+ bin
2248
+ };
2249
+ writeBoxConfig(cfg);
2250
+ const others = [found.claude, found.codex].filter(
2251
+ (h) => Boolean(h) && h !== harness
2252
+ );
2253
+ out(
2254
+ `${bold("Cloop runner")} ${deviceName} is a Local runner: ${[harness, ...others].map(harnessLine).join("; ")}.`
2255
+ );
2256
+ out(` Repos: ${repos.map((r) => `${r.label} (${r.path})`).join(", ")}`);
2257
+ await installService("local", argv);
2258
+ }
2259
+ async function detect(probes) {
2260
+ const [t3, claude, codex] = await Promise.all([probes.t3(), probes.claude(), probes.codex()]);
2261
+ return { t3, claude, codex };
2262
+ }
2263
+ async function connectCommand(argv) {
2264
+ const forced = flag(argv, "--driver") ?? process.env.CLOOP_DRIVER;
2265
+ if (forced && !["t3", "claude-code", "codex"].includes(forced)) {
2266
+ out(`${red("\u2717")} --driver is t3, claude-code, or codex.`);
2267
+ process.exit(1);
2268
+ }
2269
+ const t3Url = (flag(argv, "--t3-url") ?? DEFAULT_T3_URL).replace(/\/+$/, "");
2270
+ const found = await detect({
2271
+ t3: () => forced && forced !== "t3" ? Promise.resolve(false) : t3Answers(t3Url),
2272
+ claude: () => probeClaude(),
2273
+ codex: () => probeCodex()
2274
+ });
2275
+ const choice = chooseDriver(found, forced);
2276
+ if (!choice.ok) {
2277
+ out(`${red("\u2717")} ${choice.line}`);
2278
+ process.exit(1);
2279
+ }
2280
+ if (choice.driver === "t3") await connectT3(argv);
2281
+ else await connectLocal(choice.driver, found, argv);
2282
+ }
2283
+
2284
+ export {
2285
+ T3Client,
2286
+ runBoxTool,
2287
+ threadsFilePath,
2288
+ writeRunnerState,
2289
+ lockThreadsFile,
2290
+ BoxWatch,
2291
+ T3Driver,
2292
+ LocalDriver,
2293
+ probeClaude,
2294
+ claudeDialect,
2295
+ probeCodex,
2296
+ codexDialect,
2297
+ isLocal,
2298
+ readRunnerConfig,
2299
+ writeBoxConfig,
2300
+ DEFAULT_T3_URL,
2301
+ compareVersions,
2302
+ resolveT3Bin,
2303
+ mintSession,
2304
+ connectBox,
2305
+ chooseDriver,
2306
+ systemdAssignment,
2307
+ systemdWord,
2308
+ programFor,
2309
+ awaitDaemon,
2310
+ unitEnv,
2311
+ unitFor,
2312
+ resolveRepos,
2313
+ startService,
2314
+ detect,
2315
+ connectCommand
2316
+ };