@cloop/runner 0.2.2 → 0.2.4

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,782 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ CONFIG_DIR
4
+ } from "./chunk-3DIGCVL4.js";
5
+
6
+ // src/t3-bin.ts
7
+ import { execFileSync } from "child_process";
8
+ import { existsSync, readdirSync, statSync } from "fs";
9
+ import { join } from "path";
10
+ var CLEAN_ENV = () => ({
11
+ HOME: process.env.HOME,
12
+ USER: process.env.USER,
13
+ PATH: process.env.PATH
14
+ });
15
+ function defaultT3BinSources(home, stored) {
16
+ return {
17
+ env: process.env,
18
+ home,
19
+ appDirs: process.platform === "darwin" ? ["/Applications", join(home, "Applications")] : [],
20
+ onPath: () => whichAll("t3"),
21
+ ...stored ? { stored } : {}
22
+ };
23
+ }
24
+ function isExecutable(path) {
25
+ try {
26
+ const s = statSync(path);
27
+ return s.isFile() && (s.mode & 73) !== 0;
28
+ } catch {
29
+ return false;
30
+ }
31
+ }
32
+ function bundleBinaries(appDir) {
33
+ let bundles;
34
+ try {
35
+ bundles = readdirSync(appDir).filter((name) => /^T3 Code.*\.app$/.test(name));
36
+ } catch {
37
+ return [];
38
+ }
39
+ return bundles.flatMap((bundle) => {
40
+ const root = join(appDir, bundle);
41
+ try {
42
+ return readdirSync(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) => join(root, rel)).filter(isExecutable);
43
+ } catch {
44
+ return [];
45
+ }
46
+ });
47
+ }
48
+ function t3Candidates(serverVersion, sources) {
49
+ const ordered = [
50
+ sources.env.T3_BIN,
51
+ join(sources.home, ".t3", "runtime", "versions", serverVersion, "t3"),
52
+ ...sources.appDirs.flatMap(bundleBinaries),
53
+ ...sources.onPath(),
54
+ sources.stored
55
+ ];
56
+ return [...new Set(ordered.filter((p) => Boolean(p) && existsSync(p)))];
57
+ }
58
+ function parseT3Version(output) {
59
+ return output.trim().split(/\s+/).at(-1)?.replace(/^v/, "") || null;
60
+ }
61
+ function t3Version(bin) {
62
+ try {
63
+ return parseT3Version(runT3(bin, ["--version"], 1e4));
64
+ } catch {
65
+ return null;
66
+ }
67
+ }
68
+ function pickT3Bin(candidates, serverVersion, versionOf = t3Version) {
69
+ return candidates.find((bin) => versionOf(bin) === serverVersion) ?? candidates[0] ?? null;
70
+ }
71
+ function t3BaseDirArgs(env = process.env) {
72
+ return env.T3CODE_HOME ? ["--base-dir", env.T3CODE_HOME] : [];
73
+ }
74
+ function runT3(bin, args, timeout = 15e3) {
75
+ try {
76
+ return execFileSync(bin, args, {
77
+ encoding: "utf-8",
78
+ env: CLEAN_ENV(),
79
+ timeout,
80
+ stdio: ["ignore", "pipe", "pipe"]
81
+ });
82
+ } catch (err) {
83
+ const stderr = String(err.stderr ?? "").trim().split("\n").filter((line) => line && !/ExperimentalWarning|--trace-warnings/.test(line)).at(-1);
84
+ throw new Error(
85
+ `t3 ${args.slice(0, 3).join(" ")} failed${stderr ? `: ${stderr.slice(0, 200)}` : ""}`
86
+ );
87
+ }
88
+ }
89
+ function whichAll(bin) {
90
+ try {
91
+ return execFileSync("which", ["-a", bin], {
92
+ encoding: "utf-8",
93
+ env: CLEAN_ENV(),
94
+ stdio: ["ignore", "pipe", "ignore"]
95
+ }).split("\n").map((line) => line.trim()).filter(Boolean);
96
+ } catch {
97
+ return [];
98
+ }
99
+ }
100
+
101
+ // src/drivers/t3.ts
102
+ import { execFile, execFileSync as execFileSync2 } from "child_process";
103
+
104
+ // src/run-result.ts
105
+ var RESULT_INSTRUCTION = "When you finish, end your final message with a fenced block tagged cloop-result containing JSON: summary, outputs, checks.";
106
+ var text = (v, max) => typeof v === "string" && v.length <= max;
107
+ var optionalText = (v, max) => v === void 0 || text(v, max);
108
+ var https = (v) => {
109
+ try {
110
+ return typeof v === "string" && new URL(v).protocol === "https:";
111
+ } catch {
112
+ return false;
113
+ }
114
+ };
115
+ function parseRunResult(message) {
116
+ const block = [...(message ?? "").matchAll(/```cloop-result\s*\n([\s\S]*?)```/g)].at(-1)?.[1];
117
+ if (!block) return void 0;
118
+ try {
119
+ const value = JSON.parse(block);
120
+ if (!value || !text(value.summary, 500)) return void 0;
121
+ const outputs = value.outputs ?? [];
122
+ const checks = value.checks ?? [];
123
+ if (!Array.isArray(outputs) || outputs.length > 10 || !Array.isArray(checks) || checks.length > 10)
124
+ return void 0;
125
+ const clean = [];
126
+ for (const o of outputs) {
127
+ if (!o || !text(o.title, 120)) return void 0;
128
+ switch (o.kind) {
129
+ case "pr":
130
+ case "link":
131
+ if (!https(o.url)) return void 0;
132
+ clean.push({ kind: o.kind, title: o.title, url: o.url });
133
+ break;
134
+ case "draft":
135
+ if (!text(o.body, 4e3) || !optionalText(o.to, 200)) return void 0;
136
+ clean.push({
137
+ kind: "draft",
138
+ title: o.title,
139
+ body: o.body,
140
+ ...o.to !== void 0 ? { to: o.to } : {}
141
+ });
142
+ break;
143
+ case "doc":
144
+ if (!optionalText(o.body, 8e3) || o.url !== void 0 && !https(o.url))
145
+ return void 0;
146
+ clean.push({
147
+ kind: "doc",
148
+ title: o.title,
149
+ ...o.url !== void 0 ? { url: o.url } : {},
150
+ ...o.body !== void 0 ? { body: o.body } : {}
151
+ });
152
+ break;
153
+ case "file":
154
+ if (!text(o.path, 400)) return void 0;
155
+ clean.push({ kind: "file", title: o.title, path: o.path });
156
+ break;
157
+ default:
158
+ return void 0;
159
+ }
160
+ }
161
+ if (checks.some(
162
+ (c) => !c || !text(c.name, 80) || !["passed", "failed", "skipped"].includes(c.outcome) || !optionalText(c.detail, 200)
163
+ ))
164
+ return void 0;
165
+ return {
166
+ summary: value.summary,
167
+ outputs: clean,
168
+ checks: checks.map((c) => ({
169
+ name: c.name,
170
+ outcome: c.outcome,
171
+ ...c.detail !== void 0 ? { detail: c.detail } : {}
172
+ }))
173
+ };
174
+ } catch {
175
+ return void 0;
176
+ }
177
+ }
178
+
179
+ // src/drivers/driver.ts
180
+ var RUNTIME_MODES = /* @__PURE__ */ new Set([
181
+ "approval-required",
182
+ "auto-accept-edits",
183
+ "auto",
184
+ "full-access"
185
+ ]);
186
+ var BoxToolError = class extends Error {
187
+ constructor(code) {
188
+ super(code);
189
+ this.code = code;
190
+ this.name = "BoxToolError";
191
+ }
192
+ code;
193
+ };
194
+ var CLOOP_THREAD_PREFIX = "cloop:";
195
+ function questionLine(questions) {
196
+ return questions.map(
197
+ (x) => x.options?.length ? `${x.question} (${x.options.map((o) => o.label).join(", ")})` : x.question
198
+ ).join(" ").slice(0, 500);
199
+ }
200
+
201
+ // src/drivers/t3.ts
202
+ function isUnsettled(t) {
203
+ return !t.settledAt && !t.archivedAt && !isChild(t);
204
+ }
205
+ function isChild(t) {
206
+ return t.creationSource === "provider" || Boolean(t.lineage?.parentThreadId);
207
+ }
208
+ var SESSIONS_TTL_MS = 5 * 6e4;
209
+ var STATUS_TTL_MS = 3e4;
210
+ var TERMINAL_RUN = /* @__PURE__ */ new Set(["completed", "interrupted", "failed", "cancelled", "rolled_back"]);
211
+ var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master"]);
212
+ function pendingQuestions(p) {
213
+ const asked = /* @__PURE__ */ new Map();
214
+ for (const item of p.turnItems ?? []) {
215
+ if (item.type === "user_input_request" && item.requestId && item.questions?.length)
216
+ asked.set(item.requestId, item.questions);
217
+ }
218
+ 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) ?? [] }));
219
+ }
220
+ function questionText(q) {
221
+ return questionLine(q.questions);
222
+ }
223
+ function latestRun(runs) {
224
+ return runs.reduce(
225
+ (latest, r) => !latest || (r.ordinal ?? 0) >= (latest.ordinal ?? 0) ? r : latest,
226
+ null
227
+ );
228
+ }
229
+ function isTerminal(runs) {
230
+ const run = latestRun(runs);
231
+ return Boolean(run && TERMINAL_RUN.has(run.status));
232
+ }
233
+ function activeRun(runs) {
234
+ const run = latestRun(runs);
235
+ return run && !TERMINAL_RUN.has(run.status) ? run : null;
236
+ }
237
+ function steerableRun(p) {
238
+ const run = activeRun(p.runs ?? []);
239
+ if (!run) return null;
240
+ const attempts = new Set((p.attempts ?? []).filter((a) => a.runId === run.id).map((a) => a.id));
241
+ const turning = (p.providerTurns ?? []).some(
242
+ (t) => t.status === "running" && t.runAttemptId !== null && attempts.has(t.runAttemptId)
243
+ );
244
+ return turning ? run : null;
245
+ }
246
+ var STEER_WAIT_MS = 8e3;
247
+ var STEER_POLL_MS = 500;
248
+ function prUrlOf(thread) {
249
+ const branch = thread.branch ?? null;
250
+ const linked = thread.pullRequests ?? [];
251
+ const own = branch ? linked.filter((pr) => pr.snapshot?.headBranch === branch) : [];
252
+ const fromLinked = (own.at(-1) ?? linked.at(-1))?.url ?? thread.linkedPullRequest?.url;
253
+ if (fromLinked) return fromLinked;
254
+ if (branch && !SHARED_BRANCHES.has(branch)) return thread.branchPullRequest?.url ?? null;
255
+ return null;
256
+ }
257
+ function outcomeOf(p) {
258
+ const run = latestRun(p.runs ?? []);
259
+ const status = run?.status ?? "pending";
260
+ const settled = TERMINAL_RUN.has(status) || Boolean(p.thread.settledAt);
261
+ const text2 = (p.messages ?? []).filter((m) => m.role === "assistant" && m.text).at(-1)?.text?.trim();
262
+ return {
263
+ status,
264
+ settled,
265
+ kind: settled ? status === "completed" || !run ? "settled" : "failed" : null,
266
+ pr_url: prUrlOf(p.thread),
267
+ last_assistant_text: text2 ? text2.slice(0, 300) : null,
268
+ ...parseRunResult(text2) ? { result: parseRunResult(text2) } : {}
269
+ };
270
+ }
271
+ function pickProject(projects, repository) {
272
+ const only = projects.length === 1 ? projects[0] : void 0;
273
+ if (!repository) {
274
+ if (only) return only;
275
+ throw new BoxToolError("no_project");
276
+ }
277
+ const want = repository.toLowerCase();
278
+ const found = projects.find(
279
+ (p) => p.title.toLowerCase() === want || p.workspaceRoot.split("/").at(-1)?.toLowerCase() === want || p.repositoryIdentity?.displayName?.toLowerCase() === want
280
+ );
281
+ if (!found) throw new BoxToolError("no_project");
282
+ return found;
283
+ }
284
+ var SHELL_HEADERS = { "x-t3-orchestration-protocol": "2" };
285
+ function boxCapabilities(scope) {
286
+ const scopes = (scope ?? "").split(/\s+/).filter(Boolean);
287
+ return scopes.includes("orchestration:operate") ? ["view", "start", "steer"] : ["view"];
288
+ }
289
+ function threadView(t) {
290
+ return {
291
+ id: t.id,
292
+ title: t.title,
293
+ status: t.status,
294
+ branch: t.branch ?? null,
295
+ source: t.creationSource ?? null,
296
+ cloop: (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX),
297
+ settled: Boolean(t.settledAt),
298
+ updatedAt: t.updatedAt
299
+ };
300
+ }
301
+ function orderThreads(threads, limit) {
302
+ const byRecency = (a, b) => b.updatedAt.localeCompare(a.updatedAt);
303
+ const running = threads.filter((t) => t.status === "running").sort(byRecency);
304
+ const rest = threads.filter((t) => t.status !== "running").sort(byRecency);
305
+ return [...running, ...rest].slice(0, limit);
306
+ }
307
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
308
+ var T3Driver = class {
309
+ constructor(deps) {
310
+ this.deps = deps;
311
+ }
312
+ deps;
313
+ name = "t3";
314
+ get capabilities() {
315
+ return boxCapabilities(this.deps.scope?.());
316
+ }
317
+ get t3() {
318
+ return this.deps.client();
319
+ }
320
+ log(line) {
321
+ this.deps.log?.(line);
322
+ }
323
+ /**
324
+ * T3's config and shell calls take 2-20 s on a loaded box, past the app's
325
+ * wait. So status reads them from the last answer at once and refreshes
326
+ * them in the background, at most once per STATUS_TTL_MS. Only the first
327
+ * call waits.
328
+ */
329
+ t3State = { value: null, at: 0, refreshing: null };
330
+ readT3State() {
331
+ const cache = this.t3State;
332
+ if (!cache.refreshing && Date.now() - cache.at > STATUS_TTL_MS) {
333
+ cache.refreshing = Promise.all([
334
+ this.t3.rpc("server.getConfig", {}),
335
+ this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
336
+ ]).then((value) => {
337
+ cache.value = value;
338
+ cache.at = Date.now();
339
+ return value;
340
+ }).finally(() => {
341
+ cache.refreshing = null;
342
+ });
343
+ cache.refreshing.catch(() => {
344
+ });
345
+ }
346
+ return cache.value ? Promise.resolve(cache.value) : cache.refreshing;
347
+ }
348
+ async status() {
349
+ const [cfg, shell] = await this.readT3State();
350
+ const sessions = this.listSessions();
351
+ const threads = (shell.threads ?? []).filter((t) => !isChild(t));
352
+ const unsettled = threads.filter(isUnsettled);
353
+ return {
354
+ box: {
355
+ label: cfg.environment.label,
356
+ driver: "t3",
357
+ t3Version: cfg.environment.serverVersion,
358
+ protocol: cfg.environment.orchestrationProtocolVersion,
359
+ hosts: (cfg.remoteOpenTargets ?? []).map((t) => t.host)
360
+ },
361
+ harnesses: cfg.providers.filter((p) => p.enabled).map((p) => ({
362
+ id: p.instanceId,
363
+ name: p.displayName ?? p.instanceId,
364
+ version: p.version,
365
+ ready: p.status === "ready",
366
+ signedIn: p.auth?.status === "authenticated",
367
+ account: p.auth?.label ?? null,
368
+ defaultModel: p.models?.find((m) => m.isDefault)?.slug ?? null
369
+ })),
370
+ clients: sessions?.filter((s) => s.client?.deviceType !== "bot").map((s) => ({
371
+ label: s.client?.label ?? "unknown",
372
+ connected: s.connected === true,
373
+ lastConnectedAt: s.lastConnectedAt ?? null
374
+ })) ?? null,
375
+ projects: (shell.projects ?? []).map((p) => p.title),
376
+ threads: {
377
+ unsettled: unsettled.length,
378
+ running: unsettled.filter((t) => t.status === "running").length,
379
+ settled: threads.length - unsettled.length,
380
+ cloop: unsettled.filter((t) => (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX)).length
381
+ }
382
+ };
383
+ }
384
+ async listThreads({
385
+ scope,
386
+ limit
387
+ }) {
388
+ const shell = await this.t3.http("/api/orchestration/shell", SHELL_HEADERS);
389
+ const all = (shell.threads ?? []).filter((t) => !isChild(t));
390
+ const threads = scope === "all" ? all : all.filter(isUnsettled);
391
+ return {
392
+ scope,
393
+ unsettled: all.filter(isUnsettled).length,
394
+ settled: all.length - all.filter(isUnsettled).length,
395
+ running: threads.filter((t) => t.status === "running").length,
396
+ threads: orderThreads(threads, limit).map(threadView)
397
+ };
398
+ }
399
+ /**
400
+ * `work_id` is T3's `commandId`, so a second launch of the same work returns
401
+ * the same thread with `resumed: true` and runs nothing twice. The worktree
402
+ * starts from origin's copy of the branch the project's checkout is on.
403
+ */
404
+ async launch(a) {
405
+ const known = this.deps.watched?.({ work_id: a.work_id });
406
+ if (known) return { thread_id: known.thread_id, resumed: true };
407
+ const [cfg, shell] = await Promise.all([
408
+ this.t3.rpc("server.getConfig", {}),
409
+ this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
410
+ ]);
411
+ const project = pickProject(shell.projects ?? [], a.repository);
412
+ const fallback = cfg.settings?.defaultModelSelection;
413
+ const harness = a.harness ?? fallback?.instanceId ?? "claudeAgent";
414
+ const provider = cfg.providers.find((p) => p.instanceId === harness && p.enabled);
415
+ if (!provider) throw new BoxToolError("harness_unavailable");
416
+ if (provider.auth && provider.auth.status !== "authenticated")
417
+ throw new BoxToolError("harness_signed_out");
418
+ const model = a.model ?? (fallback?.instanceId === harness ? fallback.model : void 0) ?? provider.models?.find((m) => m.isDefault)?.slug;
419
+ if (!model) throw new BoxToolError("harness_unavailable");
420
+ const modelSelection = !a.model && fallback?.instanceId === harness ? fallback : { instanceId: harness, model };
421
+ const runtimeMode = a.runtime_mode ?? cfg.settings?.defaultRuntimeMode;
422
+ if (!runtimeMode || !RUNTIME_MODES.has(runtimeMode))
423
+ throw new BoxToolError("runtime_mode_unknown");
424
+ const launched = await this.t3.rpc(
425
+ "orchestration.launchThread",
426
+ {
427
+ commandId: a.work_id,
428
+ creationSource: "mcp",
429
+ projectId: project.id,
430
+ title: a.title,
431
+ modelSelection,
432
+ runtimeMode,
433
+ interactionMode: "default",
434
+ workspaceStrategy: {
435
+ type: "worktree",
436
+ baseRef: this.baseRefFor(project.workspaceRoot)
437
+ },
438
+ initialMessage: { text: `${a.prompt}
439
+
440
+ ${RESULT_INSTRUCTION}`, attachments: [] }
441
+ }
442
+ );
443
+ return { thread_id: launched.threadId, resumed: launched.resumed };
444
+ }
445
+ /**
446
+ * Say something to a thread. While the thread waits on a question, only
447
+ * `answer: true` sends anything: the text answers every question in the
448
+ * newest request, because a steer does not resolve a pending question and
449
+ * the run would wait on. Without it the call sends nothing and returns the
450
+ * question, so the owner says which they meant. Otherwise `steer`
451
+ * joins the running turn, waiting up to 8 s for a starting run's provider
452
+ * turn. A run that still cannot take a steer, or `queue`, gets the text
453
+ * after it ends; a thread with nothing running starts a new turn.
454
+ * `command_id` is T3's commandId, so a retried call sends once.
455
+ */
456
+ async send(a) {
457
+ let p = await this.readProjection(a.thread_id);
458
+ const pending = pendingQuestions(p);
459
+ const question = pending.at(-1);
460
+ if (a.answer && a.question_id !== void 0 && question?.request_id !== a.question_id) {
461
+ return {
462
+ delivered: "question_changed",
463
+ question: question ? questionText(question) : null,
464
+ question_id: question?.request_id ?? null
465
+ };
466
+ }
467
+ if (question && !a.answer) {
468
+ return {
469
+ delivered: "question_pending",
470
+ question: questionText(question),
471
+ questions: pending.length
472
+ };
473
+ }
474
+ if (question) {
475
+ const receipt2 = await this.dispatch({
476
+ type: "runtime-request.respond",
477
+ commandId: a.command_id,
478
+ threadId: a.thread_id,
479
+ requestId: question.request_id,
480
+ answers: Object.fromEntries(question.questions.map((q) => [q.id, a.text]))
481
+ });
482
+ return { sequence: receipt2.sequence, delivered: "answer", question_id: question.request_id };
483
+ }
484
+ if (a.mode === "steer") {
485
+ for (let waited = 0; waited < STEER_WAIT_MS; waited += STEER_POLL_MS) {
486
+ if (!activeRun(p.runs ?? []) || steerableRun(p)) break;
487
+ await sleep(STEER_POLL_MS);
488
+ p = await this.readProjection(a.thread_id);
489
+ }
490
+ }
491
+ const steer = a.mode === "steer" ? steerableRun(p) : null;
492
+ const active = activeRun(p.runs ?? []);
493
+ if (!active && !a.resume && this.deps.watched?.({ thread_id: a.thread_id })?.settled)
494
+ throw new BoxToolError("already_finished");
495
+ const receipt = await this.dispatch({
496
+ type: "message.dispatch",
497
+ commandId: a.command_id,
498
+ threadId: a.thread_id,
499
+ messageId: a.command_id,
500
+ text: a.text,
501
+ attachments: [],
502
+ dispatchMode: steer ? { type: "steer_active", targetRunId: steer.id } : active ? { type: "queue_after_active" } : { type: "start_immediately" },
503
+ createdBy: "user",
504
+ creationSource: "mcp"
505
+ });
506
+ return { sequence: receipt.sequence, delivered: steer ? "steer" : active ? "queue" : "start" };
507
+ }
508
+ /**
509
+ * Stop the running turn. A thread with nothing running answers
510
+ * `was_running: false`, and so does a run that ended while the interrupt
511
+ * was on its way: T3 refuses that interrupt, and the owner's ask is met.
512
+ */
513
+ async interrupt(threadId, commandId) {
514
+ const run = activeRun((await this.readProjection(threadId)).runs ?? []);
515
+ if (!run) return { ok: true, was_running: false };
516
+ try {
517
+ await this.dispatch({
518
+ type: "run.interrupt",
519
+ commandId,
520
+ threadId,
521
+ runId: run.id,
522
+ reason: "Stopped from Cloop"
523
+ });
524
+ } catch (err) {
525
+ if (activeRun((await this.readProjection(threadId)).runs ?? [])) throw err;
526
+ return { ok: true, was_running: false };
527
+ }
528
+ return { ok: true, was_running: true };
529
+ }
530
+ async readThread(id) {
531
+ const { status, settled, pr_url, last_assistant_text } = outcomeOf(
532
+ await this.readProjection(id)
533
+ );
534
+ return { status, settled, pr_url, last_assistant_text };
535
+ }
536
+ /**
537
+ * Subscribe to the thread and resubscribe whenever the stream ends. A thread
538
+ * that settled while nobody watched shows a terminal run in its first
539
+ * snapshot. A question is reported on every update it is still pending.
540
+ */
541
+ watch(threadId, onEvent) {
542
+ let stopped = false;
543
+ let finishing = false;
544
+ let live = null;
545
+ const retry = () => {
546
+ if (stopped) return;
547
+ const timer = setTimeout(() => void follow(), this.deps.retryMs ?? 1e4);
548
+ timer.unref?.();
549
+ };
550
+ const finish = async () => {
551
+ if (stopped || finishing) return;
552
+ finishing = true;
553
+ let outcome;
554
+ try {
555
+ outcome = outcomeOf(await this.readProjection(threadId));
556
+ const grace = this.deps.prGraceMs ?? 6e4;
557
+ if (outcome.settled && outcome.kind === "settled" && !outcome.pr_url && grace > 0) {
558
+ await sleep(grace);
559
+ outcome = outcomeOf(await this.readProjection(threadId));
560
+ }
561
+ } catch (err) {
562
+ this.log(
563
+ `read failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
564
+ );
565
+ finishing = false;
566
+ retry();
567
+ return;
568
+ }
569
+ if (stopped) return;
570
+ if (!outcome.settled) {
571
+ finishing = false;
572
+ this.log(`run continues thread=${threadId} run=${outcome.status}; watching on`);
573
+ if (!live) void follow();
574
+ return;
575
+ }
576
+ stopped = true;
577
+ live?.close();
578
+ const pr = outcome.pr_url ? { pr_url: outcome.pr_url } : {};
579
+ if (outcome.kind === "failed") {
580
+ onEvent({ kind: "failed", summary: `The run ended ${outcome.status}.`, ...pr });
581
+ } else {
582
+ onEvent({
583
+ kind: "settled",
584
+ ...outcome.result ? { result: outcome.result } : {},
585
+ ...outcome.last_assistant_text ? { summary: outcome.last_assistant_text } : {},
586
+ ...pr
587
+ });
588
+ }
589
+ };
590
+ const follow = async () => {
591
+ if (stopped || live) return;
592
+ const runs = /* @__PURE__ */ new Map();
593
+ const requests = /* @__PURE__ */ new Map();
594
+ const asks = /* @__PURE__ */ new Map();
595
+ const keepAsk = (item) => {
596
+ if (item.type === "user_input_request" && item.requestId) asks.set(item.requestId, item);
597
+ };
598
+ let settledByHand = false;
599
+ let stream;
600
+ try {
601
+ stream = await this.t3.stream("orchestration.subscribeThread", { threadId }, (raw) => {
602
+ const item = raw;
603
+ if (item.kind === "snapshot" && "projection" in item) {
604
+ for (const r of item.projection.runs ?? []) runs.set(r.id, r);
605
+ for (const r of item.projection.runtimeRequests ?? []) requests.set(r.id, r);
606
+ for (const t of item.projection.turnItems ?? []) keepAsk(t);
607
+ settledByHand ||= Boolean(item.projection.thread?.settledAt);
608
+ } else if (item.kind === "event" && "event" in item) {
609
+ const { type, payload } = item.event;
610
+ if (type.startsWith("run.") && typeof payload?.id === "string") {
611
+ runs.set(payload.id, payload);
612
+ } else if (type === "runtime-request.updated" && typeof payload?.id === "string") {
613
+ requests.set(payload.id, payload);
614
+ } else if (type === "turn-item.updated" && payload) {
615
+ keepAsk(payload);
616
+ } else if (type.startsWith("thread.") && payload?.settledAt) {
617
+ settledByHand = true;
618
+ } else return;
619
+ } else return;
620
+ if (settledByHand || isTerminal([...runs.values()])) {
621
+ void finish();
622
+ return;
623
+ }
624
+ const pending = pendingQuestions({
625
+ runtimeRequests: [...requests.values()],
626
+ turnItems: [...asks.values()]
627
+ });
628
+ for (const q of pending) {
629
+ onEvent({ kind: "question", question_id: q.request_id, summary: questionText(q) });
630
+ }
631
+ });
632
+ } catch (err) {
633
+ this.log(
634
+ `watch failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
635
+ );
636
+ retry();
637
+ return;
638
+ }
639
+ if (stopped) {
640
+ stream.close();
641
+ return;
642
+ }
643
+ live = stream;
644
+ const reason = await stream.done;
645
+ live = null;
646
+ if (stopped || finishing) return;
647
+ this.log(`watch ended thread=${threadId} reason=${reason}; resubscribing`);
648
+ retry();
649
+ };
650
+ void follow();
651
+ return () => {
652
+ stopped = true;
653
+ live?.close();
654
+ };
655
+ }
656
+ readProjection(threadId) {
657
+ return this.t3.rpc("orchestration.getThreadProjection", { threadId });
658
+ }
659
+ dispatch(command) {
660
+ return this.t3.rpc("orchestration.dispatchCommand", command);
661
+ }
662
+ sessions = {
663
+ list: null,
664
+ at: 0,
665
+ refreshing: false
666
+ };
667
+ /**
668
+ * T3's client sessions, from the cache. `t3 auth session list` starts a whole
669
+ * CLI and took 5 to 14 s on a loaded box, so status never waits on it: it
670
+ * answers with the last list and refreshes it in the background at most
671
+ * once per SESSIONS_TTL_MS.
672
+ */
673
+ listSessions() {
674
+ const bin = this.deps.t3Bin;
675
+ if (!bin) return null;
676
+ const stale = Date.now() - this.sessions.at > SESSIONS_TTL_MS;
677
+ if (stale && !this.sessions.refreshing) {
678
+ this.sessions.refreshing = true;
679
+ const done = (raw) => {
680
+ try {
681
+ if (raw !== null) this.sessions.list = JSON.parse(raw);
682
+ } catch {
683
+ }
684
+ this.sessions.at = Date.now();
685
+ this.sessions.refreshing = false;
686
+ };
687
+ (this.deps.execAsync ?? execFile)(
688
+ bin,
689
+ ["auth", "session", "list", ...t3BaseDirArgs(), "--json"],
690
+ {
691
+ encoding: "utf-8",
692
+ env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
693
+ timeout: 3e4
694
+ },
695
+ (err, stdout) => done(err ? null : String(stdout))
696
+ );
697
+ }
698
+ return this.sessions.list;
699
+ }
700
+ /**
701
+ * The branch the project's checkout is on, from origin when origin has it. A
702
+ * local branch can lag origin by hundreds of commits on a box nobody pulls on,
703
+ * and T3 starts the worktree from the ref exactly as given.
704
+ */
705
+ baseRefFor(root) {
706
+ const git = (args) => String(
707
+ (this.deps.exec ?? execFileSync2)("git", ["-C", root, ...args], {
708
+ encoding: "utf-8",
709
+ env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
710
+ timeout: 5e3
711
+ })
712
+ ).trim();
713
+ let branch;
714
+ try {
715
+ branch = git(["rev-parse", "--abbrev-ref", "HEAD"]);
716
+ } catch {
717
+ return "HEAD";
718
+ }
719
+ if (!branch || branch === "HEAD") return "HEAD";
720
+ try {
721
+ git(["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}`]);
722
+ return `origin/${branch}`;
723
+ } catch {
724
+ return branch;
725
+ }
726
+ }
727
+ };
728
+
729
+ // src/runner-config.ts
730
+ import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
731
+ import { homedir } from "os";
732
+ import { dirname, join as join2 } from "path";
733
+ var BOX_FILE = "box.json";
734
+ function boxPath() {
735
+ return process.env.CLOOP_BOX_FILE ?? join2(homedir(), CONFIG_DIR, BOX_FILE);
736
+ }
737
+ function isLocal(cfg) {
738
+ return cfg.driver === "claude-code" || cfg.driver === "codex";
739
+ }
740
+ function readRunnerConfig() {
741
+ let parsed;
742
+ try {
743
+ parsed = JSON.parse(readFileSync(boxPath(), "utf-8"));
744
+ } catch {
745
+ return null;
746
+ }
747
+ if (parsed.driver === "claude-code" || parsed.driver === "codex") {
748
+ const ok = typeof parsed.deviceToken === "string" && typeof parsed.environmentId === "string" && typeof parsed.bin === "string" && Array.isArray(parsed.repos);
749
+ return ok ? parsed : null;
750
+ }
751
+ if (typeof parsed.t3Url !== "string" || typeof parsed.token !== "string") return null;
752
+ return parsed;
753
+ }
754
+ function writeBoxConfig(cfg) {
755
+ const path = boxPath();
756
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
757
+ const temp = `${path}.${process.pid}.tmp`;
758
+ writeFileSync(temp, `${JSON.stringify(cfg, null, 2)}
759
+ `, { mode: 384 });
760
+ chmodSync(temp, 384);
761
+ renameSync(temp, path);
762
+ }
763
+
764
+ export {
765
+ RUNTIME_MODES,
766
+ BoxToolError,
767
+ CLOOP_THREAD_PREFIX,
768
+ questionLine,
769
+ RESULT_INSTRUCTION,
770
+ parseRunResult,
771
+ defaultT3BinSources,
772
+ t3Candidates,
773
+ pickT3Bin,
774
+ t3BaseDirArgs,
775
+ runT3,
776
+ orderThreads,
777
+ T3Driver,
778
+ boxPath,
779
+ isLocal,
780
+ readRunnerConfig,
781
+ writeBoxConfig
782
+ };