@cloop/runner 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,25 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ getMachine,
4
+ shortMachineName
5
+ } from "./chunk-JX6VG5FE.js";
6
+ import {
7
+ READ_TOOLS,
8
+ readOnlySettings
9
+ } from "./chunk-R3CLO2FB.js";
10
+ import {
11
+ connectWebhook
12
+ } from "./chunk-TIXA2YXR.js";
2
13
  import {
3
14
  ConnectFailure,
4
15
  connectReport,
5
16
  deviceLogin,
6
17
  newAttempt,
7
18
  sendConnectReport
8
- } from "./chunk-AQGBNKUG.js";
9
- import {
10
- getMachine,
11
- shortMachineName
12
- } from "./chunk-JX6VG5FE.js";
19
+ } from "./chunk-F4WCO6Z4.js";
13
20
  import {
14
21
  VERSION
15
- } from "./chunk-OKF4BDBH.js";
22
+ } from "./chunk-FW7MMQQV.js";
16
23
  import {
17
24
  CONFIG_DIR,
18
25
  STAGING_ORIGIN,
@@ -20,12 +27,12 @@ import {
20
27
  } from "./chunk-3DIGCVL4.js";
21
28
 
22
29
  // src/commands/connect.ts
23
- import { execFileSync as execFileSync4 } from "child_process";
30
+ import { execFileSync as execFileSync3 } from "child_process";
24
31
  import { randomUUID as randomUUID2 } from "crypto";
25
- import { existsSync as existsSync2, mkdirSync as mkdirSync4, readdirSync as readdirSync2, rmSync, writeFileSync as writeFileSync4 } from "fs";
26
- import { homedir as homedir4 } from "os";
27
- import { basename as basename4, dirname as dirname4, join as join5, resolve as resolve2 } from "path";
28
- import { createInterface as createInterface2 } from "readline/promises";
32
+ import { existsSync as existsSync2, mkdirSync as mkdirSync3, readdirSync as readdirSync2, rmSync, writeFileSync as writeFileSync3 } from "fs";
33
+ import { homedir as homedir3 } from "os";
34
+ import { basename as basename3, dirname as dirname3, join as join4, resolve as resolve2 } from "path";
35
+ import { createInterface } from "readline/promises";
29
36
 
30
37
  // src/drivers/driver.ts
31
38
  var RUNTIME_MODES = /* @__PURE__ */ new Set([
@@ -249,8 +256,8 @@ function parseCommandId(args) {
249
256
  return id;
250
257
  }
251
258
  function parseSendArgs(args) {
252
- const text = typeof args.text === "string" ? args.text.trim() : "";
253
- if (!text || text.length > 8e3) throw new BoxToolError("bad_args");
259
+ const text2 = typeof args.text === "string" ? args.text.trim() : "";
260
+ if (!text2 || text2.length > 8e3) throw new BoxToolError("bad_args");
254
261
  const mode = args.mode ?? "steer";
255
262
  if (mode !== "steer" && mode !== "queue") throw new BoxToolError("bad_args");
256
263
  if (args.answer !== void 0 && typeof args.answer !== "boolean")
@@ -260,10 +267,11 @@ function parseSendArgs(args) {
260
267
  throw new BoxToolError("bad_args");
261
268
  return {
262
269
  thread_id: parseThreadId(args),
263
- text,
270
+ text: text2,
264
271
  mode,
265
272
  command_id: parseCommandId(args),
266
273
  answer: args.answer === true,
274
+ ...args.resume === true ? { resume: true } : {},
267
275
  ...question !== void 0 ? { question_id: question } : {}
268
276
  };
269
277
  }
@@ -280,7 +288,12 @@ var BOX_TOOLS = {
280
288
  onLaunch?.(a.work_id, launched.thread_id);
281
289
  return launched;
282
290
  },
283
- "thread.send": ({ driver }, args) => driver.send(parseSendArgs(args)),
291
+ async "thread.send"({ driver, onResume }, args) {
292
+ const parsed = parseSendArgs(args);
293
+ const result = await driver.send(parsed);
294
+ if (parsed.resume) onResume?.(parsed.thread_id);
295
+ return result;
296
+ },
284
297
  "thread.interrupt": ({ driver }, args) => driver.interrupt(parseThreadId(args), parseCommandId(args))
285
298
  };
286
299
  function classifyError(err, driver = "t3") {
@@ -406,6 +419,15 @@ var BoxWatch = class {
406
419
  this.deps.log(`launch work=${workId} thread=${threadId}`);
407
420
  this.watch(entry);
408
421
  }
422
+ resume(threadId) {
423
+ const entry = this.entries.find((e) => e.thread_id === threadId);
424
+ if (!entry?.settled_at) return;
425
+ entry.settled_at = void 0;
426
+ entry.event = void 0;
427
+ entry.sent_at = void 0;
428
+ this.save();
429
+ this.watch(entry);
430
+ }
409
431
  /** On every socket open and on a timer: send every event the mesh has not acked. */
410
432
  flush() {
411
433
  for (const e of this.entries) {
@@ -456,6 +478,7 @@ var BoxWatch = class {
456
478
  kind,
457
479
  ...event.kind === "question" ? { question_id: event.question_id } : {},
458
480
  ...summary ? { summary: summary.slice(0, 500) } : {},
481
+ ..."result" in event && event.result ? { result: event.result } : {},
459
482
  ..."pr_url" in event && event.pr_url ? { pr_url: event.pr_url } : {},
460
483
  ..."error" in event && event.error ? { error: event.error } : {},
461
484
  at: new Date(this.now()).toISOString()
@@ -532,751 +555,713 @@ async function revokeOwnDevice(origin, deviceToken, fetchFn = fetch) {
532
555
  }
533
556
 
534
557
  // src/drivers/claude-code.ts
535
- import { execFile as execFile3 } from "child_process";
536
- import { basename as basename2, isAbsolute, relative, resolve } from "path";
537
-
538
- // src/drivers/local.ts
539
- import { execFile as execFile2, execFileSync as execFileSync3, spawn } from "child_process";
540
- import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
541
- import { homedir as homedir2, hostname } from "os";
542
- import { basename, dirname as dirname2, join as join3 } from "path";
543
- import { createInterface } from "readline";
544
-
545
- // src/drivers/t3.ts
546
- import { execFile, execFileSync as execFileSync2 } from "child_process";
547
-
548
- // src/t3-bin.ts
549
- import { execFileSync } from "child_process";
550
- import { existsSync, readdirSync, statSync } from "fs";
551
- import { join as join2 } from "path";
552
- var CLEAN_ENV = () => ({
553
- HOME: process.env.HOME,
554
- USER: process.env.USER,
555
- PATH: process.env.PATH
556
- });
557
- function defaultT3BinSources(home, stored) {
558
- return {
559
- env: process.env,
560
- home,
561
- appDirs: process.platform === "darwin" ? ["/Applications", join2(home, "Applications")] : [],
562
- onPath: () => whichAll("t3"),
563
- ...stored ? { stored } : {}
564
- };
558
+ import { execFile } from "child_process";
559
+ import { basename, isAbsolute, relative, resolve } from "path";
560
+ var SUBSCRIPTIONS = {
561
+ max: "Claude Max",
562
+ pro: "Claude Pro",
563
+ team: "Claude Team",
564
+ enterprise: "Claude Enterprise"
565
+ };
566
+ var YES_WORDS = /* @__PURE__ */ new Set([
567
+ "y",
568
+ "yes",
569
+ "yep",
570
+ "yeah",
571
+ "allow",
572
+ "allow it",
573
+ "ok",
574
+ "okay",
575
+ "approve",
576
+ "approved",
577
+ "go ahead",
578
+ "sure",
579
+ "do it"
580
+ ]);
581
+ function isYes(reply) {
582
+ return YES_WORDS.has(
583
+ reply.trim().toLowerCase().replace(/[.!\s]+$/, "")
584
+ );
565
585
  }
566
- function isExecutable(path) {
567
- try {
568
- const s = statSync(path);
569
- return s.isFile() && (s.mode & 73) !== 0;
570
- } catch {
571
- return false;
572
- }
586
+ function exec(bin, args) {
587
+ return new Promise(
588
+ (resolve3) => execFile(
589
+ bin,
590
+ args,
591
+ { timeout: 1e4, encoding: "utf-8" },
592
+ (err, out2) => resolve3(err ? null : String(out2))
593
+ )
594
+ );
573
595
  }
574
- function bundleBinaries(appDir) {
575
- let bundles;
596
+ function claudeAccount(raw) {
576
597
  try {
577
- bundles = readdirSync(appDir).filter((name) => /^T3 Code.*\.app$/.test(name));
598
+ const auth = JSON.parse(raw ?? "");
599
+ if (auth.loggedIn !== true) return { signedIn: false, account: null };
600
+ const plan = auth.subscriptionType ? SUBSCRIPTIONS[auth.subscriptionType] : void 0;
601
+ return {
602
+ signedIn: true,
603
+ account: plan ?? (auth.authMethod === "claude.ai" ? "Claude" : "API key")
604
+ };
578
605
  } catch {
579
- return [];
606
+ return { signedIn: false, account: null };
580
607
  }
581
- return bundles.flatMap((bundle) => {
582
- const root = join2(appDir, bundle);
583
- try {
584
- return readdirSync(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) => join2(root, rel)).filter(isExecutable);
585
- } catch {
586
- return [];
587
- }
588
- });
589
608
  }
590
- function t3Candidates(serverVersion, sources) {
591
- const ordered = [
592
- sources.env.T3_BIN,
593
- join2(sources.home, ".t3", "runtime", "versions", serverVersion, "t3"),
594
- ...sources.appDirs.flatMap(bundleBinaries),
595
- ...sources.onPath(),
596
- sources.stored
597
- ];
598
- return [...new Set(ordered.filter((p) => Boolean(p) && existsSync(p)))];
609
+ function claudePermissionSupport(help) {
610
+ const choices = help?.match(/--permission-mode[\s\S]*?\(choices:([^)]*)\)/)?.[1] ?? "";
611
+ return { manualMode: /"manual"/.test(choices) ? "manual" : "default" };
599
612
  }
600
- function parseT3Version(output) {
601
- return output.trim().split(/\s+/).at(-1)?.replace(/^v/, "") || null;
613
+ async function probeClaudePermissions(bin = "claude") {
614
+ return claudePermissionSupport(await exec(bin, ["--help"]));
602
615
  }
603
- function t3Version(bin) {
604
- try {
605
- return parseT3Version(runT3(bin, ["--version"], 1e4));
606
- } catch {
607
- return null;
608
- }
616
+ async function probeClaude(bin = "claude") {
617
+ const version = (await exec(bin, ["--version"]))?.trim().split(/\s+/)[0];
618
+ if (!version) return null;
619
+ const { signedIn, account } = claudeAccount(await exec(bin, ["auth", "status", "--json"]));
620
+ return {
621
+ id: "claude-code",
622
+ name: "Claude Code",
623
+ version,
624
+ ready: signedIn,
625
+ signedIn,
626
+ account,
627
+ defaultModel: null
628
+ };
609
629
  }
610
- function pickT3Bin(candidates, serverVersion, versionOf = t3Version) {
611
- return candidates.find((bin) => versionOf(bin) === serverVersion) ?? candidates[0] ?? null;
630
+ function pathOf(input) {
631
+ const fields = input ?? {};
632
+ const path = fields.file_path ?? fields.notebook_path ?? fields.path;
633
+ return typeof path === "string" ? path : void 0;
612
634
  }
613
- function t3BaseDirArgs(env = process.env) {
614
- return env.T3CODE_HOME ? ["--base-dir", env.T3CODE_HOME] : [];
635
+ function shownPath(path, repo) {
636
+ const inside = relative(repo, resolve(repo, path));
637
+ return inside && !inside.startsWith("..") && !isAbsolute(inside) ? inside : path;
615
638
  }
616
- function runT3(bin, args, timeout = 15e3) {
617
- try {
618
- return execFileSync(bin, args, {
619
- encoding: "utf-8",
620
- env: CLEAN_ENV(),
621
- timeout,
622
- stdio: ["ignore", "pipe", "pipe"]
623
- });
624
- } catch (err) {
625
- const stderr = String(err.stderr ?? "").trim().split("\n").filter((line2) => line2 && !/ExperimentalWarning|--trace-warnings/.test(line2)).at(-1);
626
- throw new Error(
627
- `t3 ${args.slice(0, 3).join(" ")} failed${stderr ? `: ${stderr.slice(0, 200)}` : ""}`
639
+ function questionsOf(input) {
640
+ const questions = input?.questions;
641
+ return Array.isArray(questions) ? questions.filter((q) => typeof q?.question === "string") : [];
642
+ }
643
+ function cut(text2, max = 160) {
644
+ const line2 = text2.replace(/\s+/g, " ").trim();
645
+ return line2.length > max ? `${line2.slice(0, max - 1)}\u2026` : line2;
646
+ }
647
+ var TOOL_WORDS = {
648
+ Read: "read the file",
649
+ Write: "write the file",
650
+ Edit: "edit the file",
651
+ Glob: "find files",
652
+ Grep: "search files",
653
+ LS: "list files",
654
+ mcp__cloop__get_task: "read the Task",
655
+ mcp__cloop__get_task_context: "read the Task context",
656
+ mcp__cloop__list_tasks: "list your Tasks",
657
+ mcp__cloop__search: "search Cloop",
658
+ mcp__cloop__add_task: "add a Task",
659
+ mcp__cloop__add_task_note: "add a note to the Task",
660
+ mcp__cloop__complete_task: "complete the Task"
661
+ };
662
+ function askSummary(tool, input, repo) {
663
+ if (tool === "AskUserQuestion") return questionLine(questionsOf(input));
664
+ const fields = input ?? {};
665
+ if (tool === "Bash") {
666
+ const description = typeof fields.description === "string" ? cut(fields.description) : "run this command";
667
+ const words2 = description.replace(/[.?!]+$/, "");
668
+ const command = String(fields.command ?? "").replace(
669
+ /[\r\n\t]/g,
670
+ (c) => c === "\n" ? "\\n" : c === "\r" ? "\\r" : "\\t"
628
671
  );
672
+ const preview = command.length > 158 ? `${command.slice(0, 157)}\u2026` : command;
673
+ return `${words2.charAt(0).toLowerCase()}${words2.slice(1)}. OK?
674
+ (${preview})`;
629
675
  }
676
+ if (tool === "WebFetch" && typeof fields.url === "string") return `read ${cut(fields.url)}. OK?`;
677
+ const words = TOOL_WORDS[tool] ?? tool.replace(/^mcp__[^_]+__/, "").replace(/_/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase();
678
+ const path = pathOf(fields);
679
+ return `${words}${path ? ` ${shownPath(path, repo)}` : ""}. OK?`;
630
680
  }
631
- function whichAll(bin) {
681
+ function line(value) {
682
+ return `${JSON.stringify(value)}
683
+ `;
684
+ }
685
+ function userMessage(run, text2, priority) {
686
+ return {
687
+ type: "user",
688
+ message: { role: "user", content: [{ type: "text", text: text2 }] },
689
+ parent_tool_use_id: null,
690
+ session_id: run.session_id ?? run.work_id,
691
+ ...priority ? { priority } : {}
692
+ };
693
+ }
694
+ function parseClaudeLine(raw, run) {
695
+ let msg;
632
696
  try {
633
- return execFileSync("which", ["-a", bin], {
634
- encoding: "utf-8",
635
- env: CLEAN_ENV(),
636
- stdio: ["ignore", "pipe", "ignore"]
637
- }).split("\n").map((line2) => line2.trim()).filter(Boolean);
697
+ msg = JSON.parse(raw);
638
698
  } catch {
639
699
  return [];
640
700
  }
641
- }
642
-
643
- // src/drivers/t3.ts
644
- function isUnsettled(t) {
645
- return !t.settledAt && !t.archivedAt && !isChild(t);
646
- }
647
- function isChild(t) {
648
- return t.creationSource === "provider" || Boolean(t.lineage?.parentThreadId);
649
- }
650
- var SESSIONS_TTL_MS = 5 * 6e4;
651
- var TERMINAL_RUN = /* @__PURE__ */ new Set(["completed", "interrupted", "failed", "cancelled", "rolled_back"]);
652
- var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master"]);
653
- function pendingQuestions(p) {
654
- const asked = /* @__PURE__ */ new Map();
655
- for (const item of p.turnItems ?? []) {
656
- if (item.type === "user_input_request" && item.requestId && item.questions?.length)
657
- asked.set(item.requestId, item.questions);
701
+ if (msg.type === "system" && msg.subtype === "init" && typeof msg.session_id === "string") {
702
+ return [{ type: "session", id: msg.session_id }];
658
703
  }
659
- 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) ?? [] }));
660
- }
661
- function questionText(q) {
662
- return questionLine(q.questions);
663
- }
664
- function latestRun(runs) {
665
- return runs.reduce(
666
- (latest, r) => !latest || (r.ordinal ?? 0) >= (latest.ordinal ?? 0) ? r : latest,
667
- null
668
- );
669
- }
670
- function isTerminal(runs) {
671
- const run2 = latestRun(runs);
672
- return Boolean(run2 && TERMINAL_RUN.has(run2.status));
673
- }
674
- function activeRun(runs) {
675
- const run2 = latestRun(runs);
676
- return run2 && !TERMINAL_RUN.has(run2.status) ? run2 : null;
677
- }
678
- function steerableRun(p) {
679
- const run2 = activeRun(p.runs ?? []);
680
- if (!run2) return null;
681
- const attempts = new Set((p.attempts ?? []).filter((a) => a.runId === run2.id).map((a) => a.id));
682
- const turning = (p.providerTurns ?? []).some(
683
- (t) => t.status === "running" && t.runAttemptId !== null && attempts.has(t.runAttemptId)
684
- );
685
- return turning ? run2 : null;
686
- }
687
- var STEER_WAIT_MS = 8e3;
688
- var STEER_POLL_MS = 500;
689
- function prUrlOf(thread) {
690
- const branch = thread.branch ?? null;
691
- const linked = thread.pullRequests ?? [];
692
- const own = branch ? linked.filter((pr) => pr.snapshot?.headBranch === branch) : [];
693
- const fromLinked = (own.at(-1) ?? linked.at(-1))?.url ?? thread.linkedPullRequest?.url;
694
- if (fromLinked) return fromLinked;
695
- if (branch && !SHARED_BRANCHES.has(branch)) return thread.branchPullRequest?.url ?? null;
696
- return null;
697
- }
698
- function outcomeOf(p) {
699
- const run2 = latestRun(p.runs ?? []);
700
- const status = run2?.status ?? "pending";
701
- const settled = TERMINAL_RUN.has(status) || Boolean(p.thread.settledAt);
702
- const text = (p.messages ?? []).filter((m) => m.role === "assistant" && m.text).at(-1)?.text?.trim();
703
- return {
704
- status,
705
- settled,
706
- kind: settled ? status === "completed" || !run2 ? "settled" : "failed" : null,
707
- pr_url: prUrlOf(p.thread),
708
- last_assistant_text: text ? text.slice(0, 300) : null
709
- };
710
- }
711
- function pickProject(projects, repository) {
712
- const only = projects.length === 1 ? projects[0] : void 0;
713
- if (!repository) {
714
- if (only) return only;
715
- throw new BoxToolError("no_project");
704
+ if (msg.type === "assistant") {
705
+ const content = msg.message?.content;
706
+ if (!Array.isArray(content)) return [];
707
+ return content.flatMap((block) => {
708
+ if (block?.type === "text" && typeof block.text === "string" && block.text.trim())
709
+ return [{ type: "text", text: block.text }];
710
+ if (block?.type === "tool_use" && typeof block.name === "string" && block.name !== "AskUserQuestion") {
711
+ const path = pathOf(block.input);
712
+ const description = block.input?.description;
713
+ const summary = typeof description === "string" ? cut(description, 200) : TOOL_WORDS[block.name];
714
+ return [
715
+ {
716
+ type: "tool",
717
+ name: block.name,
718
+ ...path ? { target: basename(path) } : {},
719
+ ...summary ? { summary } : {}
720
+ }
721
+ ];
722
+ }
723
+ return [];
724
+ });
716
725
  }
717
- const want = repository.toLowerCase();
718
- const found = projects.find(
719
- (p) => p.title.toLowerCase() === want || p.workspaceRoot.split("/").at(-1)?.toLowerCase() === want || p.repositoryIdentity?.displayName?.toLowerCase() === want
726
+ if (msg.type === "control_request") {
727
+ const request = msg.request;
728
+ if (request?.subtype !== "can_use_tool" || typeof msg.request_id !== "string") return [];
729
+ const tool = request.tool_name ?? "a tool";
730
+ return [
731
+ {
732
+ type: "ask",
733
+ request_id: msg.request_id,
734
+ tool,
735
+ input: request.input ?? {},
736
+ summary: askSummary(tool, request.input, run.repo)
737
+ }
738
+ ];
739
+ }
740
+ if (msg.type === "control_cancel_request" && typeof msg.request_id === "string") {
741
+ return [{ type: "cancel", request_id: msg.request_id }];
742
+ }
743
+ if (msg.type === "result") {
744
+ const denied = Array.isArray(msg.permission_denials) && msg.permission_denials.length > 0;
745
+ return [
746
+ {
747
+ type: "result",
748
+ ok: !denied && msg.subtype === "success" && msg.is_error !== true,
749
+ ...denied ? {
750
+ text: `Claude Code blocked a step. ${typeof msg.result === "string" ? msg.result : "Check the run before retrying."}`
751
+ } : typeof msg.result === "string" ? { text: msg.result } : {}
752
+ }
753
+ ];
754
+ }
755
+ return [];
756
+ }
757
+ var DEFAULT_FALLBACK_MODEL = "opus";
758
+ function claudeDialect(bin = "claude", fallback = DEFAULT_FALLBACK_MODEL, askEverything = false, options = {}) {
759
+ const permission = () => askEverything ? "ask" : "full";
760
+ return {
761
+ permission,
762
+ name: "claude-code",
763
+ fallback,
764
+ aliases: ["claude-code", "claudeAgent", "claude"],
765
+ bin,
766
+ capabilities: ["view", "start", "steer", "report"],
767
+ keepsStdin: true,
768
+ args(run, resume) {
769
+ return [
770
+ "--print",
771
+ "--verbose",
772
+ "--output-format",
773
+ "stream-json",
774
+ "--input-format",
775
+ "stream-json",
776
+ "--permission-prompt-tool",
777
+ "stdio",
778
+ ...permission() === "full" ? ["--dangerously-skip-permissions"] : [
779
+ "--permission-mode",
780
+ options.manualMode ?? "manual",
781
+ "--allowedTools",
782
+ ...READ_TOOLS,
783
+ "--settings",
784
+ JSON.stringify(readOnlySettings(askEverything))
785
+ ],
786
+ "--add-dir",
787
+ run.repo,
788
+ ...resume ? ["--resume", run.session_id ?? run.work_id] : ["--session-id", run.session_id ?? run.work_id],
789
+ ...run.model ? ["--model", run.model] : fallback ? ["--fallback-model", fallback] : []
790
+ ];
791
+ },
792
+ opening(run, prompt) {
793
+ return line({
794
+ type: "control_request",
795
+ request_id: "cloop-init",
796
+ request: { subtype: "initialize" }
797
+ }) + line(userMessage(run, prompt));
798
+ },
799
+ userLine(run, text2, mode) {
800
+ return line(userMessage(run, text2, mode === "steer" ? "now" : "next"));
801
+ },
802
+ answerLine(ask, text2) {
803
+ const input = ask.input ?? {};
804
+ const response = ask.tool === "AskUserQuestion" ? {
805
+ behavior: "allow",
806
+ updatedInput: {
807
+ ...input,
808
+ answers: Object.fromEntries(questionsOf(input).map((q) => [q.question, text2]))
809
+ }
810
+ } : isYes(text2) ? { behavior: "allow", updatedInput: input } : { behavior: "deny", message: text2 };
811
+ return line({
812
+ type: "control_response",
813
+ response: { subtype: "success", request_id: ask.request_id, response }
814
+ });
815
+ },
816
+ parse: parseClaudeLine,
817
+ owns: (run, command) => command.includes(basename(bin)) && [run.work_id, run.session_id].some((id) => id !== null && command.includes(id)),
818
+ probe: () => probeClaude(bin)
819
+ };
820
+ }
821
+
822
+ // src/drivers/codex.ts
823
+ import { execFile as execFile2 } from "child_process";
824
+ import { basename as basename2 } from "path";
825
+ function exec2(bin, args) {
826
+ return new Promise(
827
+ (resolve3) => execFile2(
828
+ bin,
829
+ args,
830
+ { timeout: 1e4, encoding: "utf-8" },
831
+ (err, out2, errOut) => resolve3({ ok: !err, out: `${out2}${errOut}` })
832
+ )
720
833
  );
721
- if (!found) throw new BoxToolError("no_project");
722
- return found;
723
834
  }
724
- var SHELL_HEADERS = { "x-t3-orchestration-protocol": "2" };
725
- function boxCapabilities(scope) {
726
- const scopes = (scope ?? "").split(/\s+/).filter(Boolean);
727
- return scopes.includes("orchestration:operate") ? ["view", "start", "steer"] : ["view"];
835
+ function codexAccount(ok, out2) {
836
+ if (!ok || !/logged in/i.test(out2) || /not logged in/i.test(out2))
837
+ return { signedIn: false, account: null };
838
+ return { signedIn: true, account: /chatgpt/i.test(out2) ? "ChatGPT" : "API key" };
728
839
  }
729
- function threadView(t) {
840
+ async function probeCodex(bin = "codex") {
841
+ const version = await exec2(bin, ["--version"]);
842
+ if (!version.ok) return null;
843
+ const status = await exec2(bin, ["login", "status"]);
844
+ const { signedIn, account } = codexAccount(status.ok, status.out);
730
845
  return {
731
- id: t.id,
732
- title: t.title,
733
- status: t.status,
734
- branch: t.branch ?? null,
735
- source: t.creationSource ?? null,
736
- cloop: (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX),
737
- settled: Boolean(t.settledAt),
738
- updatedAt: t.updatedAt
846
+ id: "codex",
847
+ name: "Codex",
848
+ version: version.out.trim().split(/\s+/).at(-1) ?? null,
849
+ ready: signedIn,
850
+ signedIn,
851
+ account,
852
+ defaultModel: null,
853
+ experimental: true
739
854
  };
740
855
  }
741
- function orderThreads(threads, limit) {
742
- const byRecency = (a, b) => b.updatedAt.localeCompare(a.updatedAt);
743
- const running = threads.filter((t) => t.status === "running").sort(byRecency);
744
- const rest = threads.filter((t) => t.status !== "running").sort(byRecency);
745
- return [...running, ...rest].slice(0, limit);
746
- }
747
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
748
- var T3Driver = class {
749
- constructor(deps) {
750
- this.deps = deps;
856
+ function parseCodexLine(raw) {
857
+ let msg;
858
+ try {
859
+ msg = JSON.parse(raw);
860
+ } catch {
861
+ return [];
751
862
  }
752
- deps;
753
- name = "t3";
754
- get capabilities() {
755
- return boxCapabilities(this.deps.scope?.());
863
+ if (msg.type === "thread.started" && typeof msg.thread_id === "string")
864
+ return [{ type: "session", id: msg.thread_id }];
865
+ const item = msg.item;
866
+ if (msg.type === "item.completed" && item?.type === "agent_message" && typeof item.text === "string")
867
+ return [{ type: "text", text: item.text }];
868
+ if (msg.type === "item.started" && item?.type === "command_execution")
869
+ return [{ type: "tool", name: "Bash" }];
870
+ if (msg.type === "item.completed" && item?.type === "file_change") {
871
+ const changes = Array.isArray(item.changes) ? item.changes : [];
872
+ const path = changes[0]?.path;
873
+ return [
874
+ {
875
+ type: "tool",
876
+ name: "Edit",
877
+ ...typeof path === "string" ? { target: basename2(path) } : {}
878
+ }
879
+ ];
756
880
  }
757
- get t3() {
758
- return this.deps.client();
881
+ if (msg.type === "turn.completed") return [{ type: "result", ok: true }];
882
+ if (msg.type === "turn.failed") {
883
+ const message = msg.error?.message;
884
+ return [
885
+ { type: "result", ok: false, ...typeof message === "string" ? { text: message } : {} }
886
+ ];
759
887
  }
760
- log(line2) {
761
- this.deps.log?.(line2);
888
+ return [];
889
+ }
890
+ function codexDialect(bin = "codex") {
891
+ const permission = () => "full";
892
+ return {
893
+ permission,
894
+ name: "codex",
895
+ aliases: ["codex"],
896
+ bin,
897
+ capabilities: ["view", "start", "report"],
898
+ keepsStdin: false,
899
+ args(run, resume) {
900
+ const model = run.model ? ["--model", run.model] : [];
901
+ const policy = ["--dangerously-bypass-approvals-and-sandbox"];
902
+ return resume && run.session_id ? ["exec", ...policy, "resume", run.session_id, "--json", ...model, "-"] : ["exec", "--cd", run.repo, "--json", ...policy, ...model, "-"];
903
+ },
904
+ opening: (_run, prompt) => prompt,
905
+ parse: parseCodexLine,
906
+ // 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.
907
+ owns: (run, command) => command.includes(basename2(bin)) && command.includes("exec") && command.includes("--json") && (run.session_id !== null && command.includes(run.session_id) || command.includes(`--cd ${run.repo} `)),
908
+ probe: () => probeCodex(bin)
909
+ };
910
+ }
911
+
912
+ // src/drivers/t3.ts
913
+ import { execFile as execFile3, execFileSync as execFileSync2 } from "child_process";
914
+
915
+ // src/run-result.ts
916
+ var RESULT_INSTRUCTION = "When you finish, end your final message with a fenced block tagged cloop-result containing JSON: summary, outputs, checks.";
917
+ var text = (v, max) => typeof v === "string" && v.length <= max;
918
+ var optionalText = (v, max) => v === void 0 || text(v, max);
919
+ var https = (v) => {
920
+ try {
921
+ return typeof v === "string" && new URL(v).protocol === "https:";
922
+ } catch {
923
+ return false;
762
924
  }
763
- async status() {
764
- const [cfg, shell] = await Promise.all([
765
- this.t3.rpc("server.getConfig", {}),
766
- this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
767
- ]);
768
- const sessions = this.listSessions();
769
- const threads = (shell.threads ?? []).filter((t) => !isChild(t));
770
- const unsettled = threads.filter(isUnsettled);
771
- return {
772
- box: {
773
- label: cfg.environment.label,
774
- driver: "t3",
775
- t3Version: cfg.environment.serverVersion,
776
- protocol: cfg.environment.orchestrationProtocolVersion,
777
- hosts: (cfg.remoteOpenTargets ?? []).map((t) => t.host)
778
- },
779
- harnesses: cfg.providers.filter((p) => p.enabled).map((p) => ({
780
- id: p.instanceId,
781
- name: p.displayName ?? p.instanceId,
782
- version: p.version,
783
- ready: p.status === "ready",
784
- signedIn: p.auth?.status === "authenticated",
785
- account: p.auth?.label ?? null,
786
- defaultModel: p.models?.find((m) => m.isDefault)?.slug ?? null
787
- })),
788
- clients: sessions?.filter((s) => s.client?.deviceType !== "bot").map((s) => ({
789
- label: s.client?.label ?? "unknown",
790
- connected: s.connected === true,
791
- lastConnectedAt: s.lastConnectedAt ?? null
792
- })) ?? null,
793
- projects: (shell.projects ?? []).map((p) => p.title),
794
- threads: {
795
- unsettled: unsettled.length,
796
- running: unsettled.filter((t) => t.status === "running").length,
797
- settled: threads.length - unsettled.length,
798
- cloop: unsettled.filter((t) => (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX)).length
925
+ };
926
+ function parseRunResult(message) {
927
+ const block = [...(message ?? "").matchAll(/```cloop-result\s*\n([\s\S]*?)```/g)].at(-1)?.[1];
928
+ if (!block) return void 0;
929
+ try {
930
+ const value = JSON.parse(block);
931
+ if (!value || !text(value.summary, 500)) return void 0;
932
+ const outputs = value.outputs ?? [];
933
+ const checks = value.checks ?? [];
934
+ if (!Array.isArray(outputs) || outputs.length > 10 || !Array.isArray(checks) || checks.length > 10)
935
+ return void 0;
936
+ const clean = [];
937
+ for (const o of outputs) {
938
+ if (!o || !text(o.title, 120)) return void 0;
939
+ switch (o.kind) {
940
+ case "pr":
941
+ case "link":
942
+ if (!https(o.url)) return void 0;
943
+ clean.push({ kind: o.kind, title: o.title, url: o.url });
944
+ break;
945
+ case "draft":
946
+ if (!text(o.body, 4e3) || !optionalText(o.to, 200)) return void 0;
947
+ clean.push({
948
+ kind: "draft",
949
+ title: o.title,
950
+ body: o.body,
951
+ ...o.to !== void 0 ? { to: o.to } : {}
952
+ });
953
+ break;
954
+ case "doc":
955
+ if (!optionalText(o.body, 8e3) || o.url !== void 0 && !https(o.url))
956
+ return void 0;
957
+ clean.push({
958
+ kind: "doc",
959
+ title: o.title,
960
+ ...o.url !== void 0 ? { url: o.url } : {},
961
+ ...o.body !== void 0 ? { body: o.body } : {}
962
+ });
963
+ break;
964
+ case "file":
965
+ if (!text(o.path, 400)) return void 0;
966
+ clean.push({ kind: "file", title: o.title, path: o.path });
967
+ break;
968
+ default:
969
+ return void 0;
799
970
  }
800
- };
801
- }
802
- async listThreads({
803
- scope,
804
- limit
805
- }) {
806
- const shell = await this.t3.http("/api/orchestration/shell", SHELL_HEADERS);
807
- const all = (shell.threads ?? []).filter((t) => !isChild(t));
808
- const threads = scope === "all" ? all : all.filter(isUnsettled);
971
+ }
972
+ if (checks.some(
973
+ (c) => !c || !text(c.name, 80) || !["passed", "failed", "skipped"].includes(c.outcome) || !optionalText(c.detail, 200)
974
+ ))
975
+ return void 0;
809
976
  return {
810
- scope,
811
- unsettled: all.filter(isUnsettled).length,
812
- settled: all.length - all.filter(isUnsettled).length,
813
- running: threads.filter((t) => t.status === "running").length,
814
- threads: orderThreads(threads, limit).map(threadView)
977
+ summary: value.summary,
978
+ outputs: clean,
979
+ checks: checks.map((c) => ({
980
+ name: c.name,
981
+ outcome: c.outcome,
982
+ ...c.detail !== void 0 ? { detail: c.detail } : {}
983
+ }))
815
984
  };
985
+ } catch {
986
+ return void 0;
816
987
  }
817
- /**
818
- * `work_id` is T3's `commandId`, so a second launch of the same work returns
819
- * the same thread with `resumed: true` and runs nothing twice. The worktree
820
- * starts from origin's copy of the branch the project's checkout is on.
821
- */
822
- async launch(a) {
823
- const known = this.deps.watched?.({ work_id: a.work_id });
824
- if (known) return { thread_id: known.thread_id, resumed: true };
825
- const [cfg, shell] = await Promise.all([
826
- this.t3.rpc("server.getConfig", {}),
827
- this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
828
- ]);
829
- const project = pickProject(shell.projects ?? [], a.repository);
830
- const fallback = cfg.settings?.defaultModelSelection;
831
- const harness = a.harness ?? fallback?.instanceId ?? "claudeAgent";
832
- const provider = cfg.providers.find((p) => p.instanceId === harness && p.enabled);
833
- if (!provider) throw new BoxToolError("harness_unavailable");
834
- if (provider.auth && provider.auth.status !== "authenticated")
835
- throw new BoxToolError("harness_signed_out");
836
- const model = a.model ?? (fallback?.instanceId === harness ? fallback.model : void 0) ?? provider.models?.find((m) => m.isDefault)?.slug;
837
- if (!model) throw new BoxToolError("harness_unavailable");
838
- const modelSelection = !a.model && fallback?.instanceId === harness ? fallback : { instanceId: harness, model };
839
- const runtimeMode = a.runtime_mode ?? cfg.settings?.defaultRuntimeMode;
840
- if (!runtimeMode || !RUNTIME_MODES.has(runtimeMode))
841
- throw new BoxToolError("runtime_mode_unknown");
842
- const launched = await this.t3.rpc(
843
- "orchestration.launchThread",
844
- {
845
- commandId: a.work_id,
846
- creationSource: "mcp",
847
- projectId: project.id,
848
- title: a.title,
849
- modelSelection,
850
- runtimeMode,
851
- interactionMode: "default",
852
- workspaceStrategy: {
853
- type: "worktree",
854
- baseRef: this.baseRefFor(project.workspaceRoot)
855
- },
856
- initialMessage: { text: a.prompt, attachments: [] }
857
- }
858
- );
859
- return { thread_id: launched.threadId, resumed: launched.resumed };
988
+ }
989
+
990
+ // src/t3-bin.ts
991
+ import { execFileSync } from "child_process";
992
+ import { existsSync, readdirSync, statSync } from "fs";
993
+ import { join as join2 } from "path";
994
+ var CLEAN_ENV = () => ({
995
+ HOME: process.env.HOME,
996
+ USER: process.env.USER,
997
+ PATH: process.env.PATH
998
+ });
999
+ function defaultT3BinSources(home, stored) {
1000
+ return {
1001
+ env: process.env,
1002
+ home,
1003
+ appDirs: process.platform === "darwin" ? ["/Applications", join2(home, "Applications")] : [],
1004
+ onPath: () => whichAll("t3"),
1005
+ ...stored ? { stored } : {}
1006
+ };
1007
+ }
1008
+ function isExecutable(path) {
1009
+ try {
1010
+ const s = statSync(path);
1011
+ return s.isFile() && (s.mode & 73) !== 0;
1012
+ } catch {
1013
+ return false;
860
1014
  }
861
- /**
862
- * Say something to a thread. While the thread waits on a question, only
863
- * `answer: true` sends anything: the text answers every question in the
864
- * newest request, because a steer does not resolve a pending question and
865
- * the run would wait on. Without it the call sends nothing and returns the
866
- * question, so the owner says which they meant. Otherwise `steer`
867
- * joins the running turn, waiting up to 8 s for a starting run's provider
868
- * turn. A run that still cannot take a steer, or `queue`, gets the text
869
- * after it ends; a thread with nothing running starts a new turn.
870
- * `command_id` is T3's commandId, so a retried call sends once.
871
- */
872
- async send(a) {
873
- let p = await this.readProjection(a.thread_id);
874
- const pending = pendingQuestions(p);
875
- const question = pending.at(-1);
876
- if (a.answer && a.question_id !== void 0 && question?.request_id !== a.question_id) {
877
- return {
878
- delivered: "question_changed",
879
- question: question ? questionText(question) : null,
880
- question_id: question?.request_id ?? null
881
- };
882
- }
883
- if (question && !a.answer) {
884
- return {
885
- delivered: "question_pending",
886
- question: questionText(question),
887
- questions: pending.length
888
- };
889
- }
890
- if (question) {
891
- const receipt2 = await this.dispatch({
892
- type: "runtime-request.respond",
893
- commandId: a.command_id,
894
- threadId: a.thread_id,
895
- requestId: question.request_id,
896
- answers: Object.fromEntries(question.questions.map((q) => [q.id, a.text]))
897
- });
898
- return { sequence: receipt2.sequence, delivered: "answer", question_id: question.request_id };
899
- }
900
- if (a.mode === "steer") {
901
- for (let waited = 0; waited < STEER_WAIT_MS; waited += STEER_POLL_MS) {
902
- if (!activeRun(p.runs ?? []) || steerableRun(p)) break;
903
- await sleep(STEER_POLL_MS);
904
- p = await this.readProjection(a.thread_id);
905
- }
906
- }
907
- const steer = a.mode === "steer" ? steerableRun(p) : null;
908
- const active = activeRun(p.runs ?? []);
909
- if (!active && this.deps.watched?.({ thread_id: a.thread_id })?.settled)
910
- throw new BoxToolError("already_finished");
911
- const receipt = await this.dispatch({
912
- type: "message.dispatch",
913
- commandId: a.command_id,
914
- threadId: a.thread_id,
915
- messageId: a.command_id,
916
- text: a.text,
917
- attachments: [],
918
- dispatchMode: steer ? { type: "steer_active", targetRunId: steer.id } : active ? { type: "queue_after_active" } : { type: "start_immediately" },
919
- createdBy: "user",
920
- creationSource: "mcp"
921
- });
922
- return { sequence: receipt.sequence, delivered: steer ? "steer" : active ? "queue" : "start" };
1015
+ }
1016
+ function bundleBinaries(appDir) {
1017
+ let bundles;
1018
+ try {
1019
+ bundles = readdirSync(appDir).filter((name) => /^T3 Code.*\.app$/.test(name));
1020
+ } catch {
1021
+ return [];
923
1022
  }
924
- /**
925
- * Stop the running turn. A thread with nothing running answers
926
- * `was_running: false`, and so does a run that ended while the interrupt
927
- * was on its way: T3 refuses that interrupt, and the owner's ask is met.
928
- */
929
- async interrupt(threadId, commandId) {
930
- const run2 = activeRun((await this.readProjection(threadId)).runs ?? []);
931
- if (!run2) return { ok: true, was_running: false };
1023
+ return bundles.flatMap((bundle) => {
1024
+ const root = join2(appDir, bundle);
932
1025
  try {
933
- await this.dispatch({
934
- type: "run.interrupt",
935
- commandId,
936
- threadId,
937
- runId: run2.id,
938
- reason: "Stopped from Cloop"
939
- });
940
- } catch (err) {
941
- if (activeRun((await this.readProjection(threadId)).runs ?? [])) throw err;
942
- return { ok: true, was_running: false };
1026
+ return readdirSync(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) => join2(root, rel)).filter(isExecutable);
1027
+ } catch {
1028
+ return [];
943
1029
  }
944
- return { ok: true, was_running: true };
1030
+ });
1031
+ }
1032
+ function t3Candidates(serverVersion, sources) {
1033
+ const ordered = [
1034
+ sources.env.T3_BIN,
1035
+ join2(sources.home, ".t3", "runtime", "versions", serverVersion, "t3"),
1036
+ ...sources.appDirs.flatMap(bundleBinaries),
1037
+ ...sources.onPath(),
1038
+ sources.stored
1039
+ ];
1040
+ return [...new Set(ordered.filter((p) => Boolean(p) && existsSync(p)))];
1041
+ }
1042
+ function parseT3Version(output) {
1043
+ return output.trim().split(/\s+/).at(-1)?.replace(/^v/, "") || null;
1044
+ }
1045
+ function t3Version(bin) {
1046
+ try {
1047
+ return parseT3Version(runT3(bin, ["--version"], 1e4));
1048
+ } catch {
1049
+ return null;
945
1050
  }
946
- async readThread(id) {
947
- const { status, settled, pr_url, last_assistant_text } = outcomeOf(
948
- await this.readProjection(id)
1051
+ }
1052
+ function pickT3Bin(candidates, serverVersion, versionOf = t3Version) {
1053
+ return candidates.find((bin) => versionOf(bin) === serverVersion) ?? candidates[0] ?? null;
1054
+ }
1055
+ function t3BaseDirArgs(env = process.env) {
1056
+ return env.T3CODE_HOME ? ["--base-dir", env.T3CODE_HOME] : [];
1057
+ }
1058
+ function runT3(bin, args, timeout = 15e3) {
1059
+ try {
1060
+ return execFileSync(bin, args, {
1061
+ encoding: "utf-8",
1062
+ env: CLEAN_ENV(),
1063
+ timeout,
1064
+ stdio: ["ignore", "pipe", "pipe"]
1065
+ });
1066
+ } catch (err) {
1067
+ const stderr = String(err.stderr ?? "").trim().split("\n").filter((line2) => line2 && !/ExperimentalWarning|--trace-warnings/.test(line2)).at(-1);
1068
+ throw new Error(
1069
+ `t3 ${args.slice(0, 3).join(" ")} failed${stderr ? `: ${stderr.slice(0, 200)}` : ""}`
949
1070
  );
950
- return { status, settled, pr_url, last_assistant_text };
951
1071
  }
952
- /**
953
- * Subscribe to the thread and resubscribe whenever the stream ends. A thread
954
- * that settled while nobody watched shows a terminal run in its first
955
- * snapshot. A question is reported on every update it is still pending.
956
- */
957
- watch(threadId, onEvent) {
958
- let stopped = false;
959
- let finishing = false;
960
- let live = null;
961
- const retry = () => {
962
- if (stopped) return;
963
- const timer = setTimeout(() => void follow(), this.deps.retryMs ?? 1e4);
964
- timer.unref?.();
965
- };
966
- const finish = async () => {
967
- if (stopped || finishing) return;
968
- finishing = true;
969
- let outcome;
970
- try {
971
- outcome = outcomeOf(await this.readProjection(threadId));
972
- const grace = this.deps.prGraceMs ?? 6e4;
973
- if (outcome.settled && outcome.kind === "settled" && !outcome.pr_url && grace > 0) {
974
- await sleep(grace);
975
- outcome = outcomeOf(await this.readProjection(threadId));
976
- }
977
- } catch (err) {
978
- this.log(
979
- `read failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
980
- );
981
- finishing = false;
982
- retry();
983
- return;
984
- }
985
- if (stopped) return;
986
- if (!outcome.settled) {
987
- finishing = false;
988
- this.log(`run continues thread=${threadId} run=${outcome.status}; watching on`);
989
- if (!live) void follow();
990
- return;
991
- }
992
- stopped = true;
993
- live?.close();
994
- const pr = outcome.pr_url ? { pr_url: outcome.pr_url } : {};
995
- if (outcome.kind === "failed") {
996
- onEvent({ kind: "failed", summary: `The run ended ${outcome.status}.`, ...pr });
997
- } else {
998
- onEvent({
999
- kind: "settled",
1000
- ...outcome.last_assistant_text ? { summary: outcome.last_assistant_text } : {},
1001
- ...pr
1002
- });
1003
- }
1004
- };
1005
- const follow = async () => {
1006
- if (stopped || live) return;
1007
- const runs = /* @__PURE__ */ new Map();
1008
- const requests = /* @__PURE__ */ new Map();
1009
- const asks = /* @__PURE__ */ new Map();
1010
- const keepAsk = (item) => {
1011
- if (item.type === "user_input_request" && item.requestId) asks.set(item.requestId, item);
1012
- };
1013
- let settledByHand = false;
1014
- let stream;
1015
- try {
1016
- stream = await this.t3.stream("orchestration.subscribeThread", { threadId }, (raw) => {
1017
- const item = raw;
1018
- if (item.kind === "snapshot" && "projection" in item) {
1019
- for (const r of item.projection.runs ?? []) runs.set(r.id, r);
1020
- for (const r of item.projection.runtimeRequests ?? []) requests.set(r.id, r);
1021
- for (const t of item.projection.turnItems ?? []) keepAsk(t);
1022
- settledByHand ||= Boolean(item.projection.thread?.settledAt);
1023
- } else if (item.kind === "event" && "event" in item) {
1024
- const { type, payload } = item.event;
1025
- if (type.startsWith("run.") && typeof payload?.id === "string") {
1026
- runs.set(payload.id, payload);
1027
- } else if (type === "runtime-request.updated" && typeof payload?.id === "string") {
1028
- requests.set(payload.id, payload);
1029
- } else if (type === "turn-item.updated" && payload) {
1030
- keepAsk(payload);
1031
- } else if (type.startsWith("thread.") && payload?.settledAt) {
1032
- settledByHand = true;
1033
- } else return;
1034
- } else return;
1035
- if (settledByHand || isTerminal([...runs.values()])) {
1036
- void finish();
1037
- return;
1038
- }
1039
- const pending = pendingQuestions({
1040
- runtimeRequests: [...requests.values()],
1041
- turnItems: [...asks.values()]
1042
- });
1043
- for (const q of pending) {
1044
- onEvent({ kind: "question", question_id: q.request_id, summary: questionText(q) });
1045
- }
1046
- });
1047
- } catch (err) {
1048
- this.log(
1049
- `watch failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
1050
- );
1051
- retry();
1052
- return;
1053
- }
1054
- if (stopped) {
1055
- stream.close();
1056
- return;
1057
- }
1058
- live = stream;
1059
- const reason = await stream.done;
1060
- live = null;
1061
- if (stopped || finishing) return;
1062
- this.log(`watch ended thread=${threadId} reason=${reason}; resubscribing`);
1063
- retry();
1064
- };
1065
- void follow();
1066
- return () => {
1067
- stopped = true;
1068
- live?.close();
1069
- };
1070
- }
1071
- readProjection(threadId) {
1072
- return this.t3.rpc("orchestration.getThreadProjection", { threadId });
1073
- }
1074
- dispatch(command) {
1075
- return this.t3.rpc("orchestration.dispatchCommand", command);
1076
- }
1077
- sessions = {
1078
- list: null,
1079
- at: 0,
1080
- refreshing: false
1081
- };
1082
- /**
1083
- * T3's client sessions, from the cache. `t3 auth session list` starts a whole
1084
- * CLI and took 5 to 14 s on a loaded box, so status never waits on it: it
1085
- * answers with the last list and refreshes it in the background at most
1086
- * once per SESSIONS_TTL_MS.
1087
- */
1088
- listSessions() {
1089
- const bin = this.deps.t3Bin;
1090
- if (!bin) return null;
1091
- const stale = Date.now() - this.sessions.at > SESSIONS_TTL_MS;
1092
- if (stale && !this.sessions.refreshing) {
1093
- this.sessions.refreshing = true;
1094
- const done = (raw) => {
1095
- try {
1096
- if (raw !== null) this.sessions.list = JSON.parse(raw);
1097
- } catch {
1098
- }
1099
- this.sessions.at = Date.now();
1100
- this.sessions.refreshing = false;
1101
- };
1102
- (this.deps.execAsync ?? execFile)(
1103
- bin,
1104
- ["auth", "session", "list", ...t3BaseDirArgs(), "--json"],
1105
- {
1106
- encoding: "utf-8",
1107
- env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
1108
- timeout: 3e4
1109
- },
1110
- (err, stdout) => done(err ? null : String(stdout))
1111
- );
1112
- }
1113
- return this.sessions.list;
1072
+ }
1073
+ function whichAll(bin) {
1074
+ try {
1075
+ return execFileSync("which", ["-a", bin], {
1076
+ encoding: "utf-8",
1077
+ env: CLEAN_ENV(),
1078
+ stdio: ["ignore", "pipe", "ignore"]
1079
+ }).split("\n").map((line2) => line2.trim()).filter(Boolean);
1080
+ } catch {
1081
+ return [];
1114
1082
  }
1115
- /**
1116
- * The branch the project's checkout is on, from origin when origin has it. A
1117
- * local branch can lag origin by hundreds of commits on a box nobody pulls on,
1118
- * and T3 starts the worktree from the ref exactly as given.
1119
- */
1120
- baseRefFor(root) {
1121
- const git = (args) => String(
1122
- (this.deps.exec ?? execFileSync2)("git", ["-C", root, ...args], {
1123
- encoding: "utf-8",
1124
- env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
1125
- timeout: 5e3
1126
- })
1127
- ).trim();
1128
- let branch;
1129
- try {
1130
- branch = git(["rev-parse", "--abbrev-ref", "HEAD"]);
1131
- } catch {
1132
- return "HEAD";
1133
- }
1134
- if (!branch || branch === "HEAD") return "HEAD";
1135
- try {
1136
- git(["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}`]);
1137
- return `origin/${branch}`;
1138
- } catch {
1139
- return branch;
1140
- }
1083
+ }
1084
+
1085
+ // src/drivers/t3.ts
1086
+ function isUnsettled(t) {
1087
+ return !t.settledAt && !t.archivedAt && !isChild(t);
1088
+ }
1089
+ function isChild(t) {
1090
+ return t.creationSource === "provider" || Boolean(t.lineage?.parentThreadId);
1091
+ }
1092
+ var SESSIONS_TTL_MS = 5 * 6e4;
1093
+ var STATUS_TTL_MS = 3e4;
1094
+ var TERMINAL_RUN = /* @__PURE__ */ new Set(["completed", "interrupted", "failed", "cancelled", "rolled_back"]);
1095
+ var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master"]);
1096
+ function pendingQuestions(p) {
1097
+ const asked = /* @__PURE__ */ new Map();
1098
+ for (const item of p.turnItems ?? []) {
1099
+ if (item.type === "user_input_request" && item.requestId && item.questions?.length)
1100
+ asked.set(item.requestId, item.questions);
1141
1101
  }
1142
- };
1143
-
1144
- // src/drivers/local.ts
1145
- var CONTINUE_PROMPT = "Continue the work from where you stopped. If it is already done, say so in one sentence.";
1146
- var PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
1147
- var SHARED_BRANCHES2 = /* @__PURE__ */ new Set(["staging", "main", "master", "HEAD"]);
1148
- var COMMANDS_KEPT = 50;
1149
- var SUMMARY_MAX = 200;
1150
- var HARNESS_NAMES = { "claude-code": "Claude Code", codex: "Codex" };
1151
- var HARNESS_LIMIT = /usage limit|reached your [\w .-]{0,40}limit|hit your [\w .-]{0,40}limit|out of (usage )?credits/i;
1152
- function failedEnd(harness, run2) {
1153
- const said = run2.result?.text?.trim() || run2.lastText;
1154
- const limited = HARNESS_LIMIT.test(run2.result?.text ?? "");
1155
- const words = said?.replace(/\s+/g, " ").trim();
1156
- const error = limited ? { error: "harness_limit" } : {};
1157
- const opening = run2.switched ? `${run2.switched} ` : "";
1158
- if (!words)
1159
- return {
1160
- summary: `${opening}${run2.result ? "The run ended with an error." : `The run exited with ${run2.exit}.`}`,
1161
- ...error
1162
- };
1163
- const lead = `${opening}${HARNESS_NAMES[harness] ?? harness} said: "`;
1164
- const room = SUMMARY_MAX - lead.length - 1;
1165
- const quoted = words.length > room ? `${words.slice(0, room - 1)}\u2026` : words;
1166
- return { summary: `${lead}${quoted}"`, ...error };
1167
- }
1168
- var PERMISSION_MODES = {
1169
- "approval-required": "default",
1170
- "auto-accept-edits": "acceptEdits",
1171
- auto: "auto",
1172
- "full-access": "bypassPermissions"
1173
- };
1174
- function permissionMode(mode) {
1175
- return PERMISSION_MODES[mode ?? "auto-accept-edits"];
1102
+ 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) ?? [] }));
1103
+ }
1104
+ function questionText(q) {
1105
+ return questionLine(q.questions);
1106
+ }
1107
+ function latestRun(runs) {
1108
+ return runs.reduce(
1109
+ (latest, r) => !latest || (r.ordinal ?? 0) >= (latest.ordinal ?? 0) ? r : latest,
1110
+ null
1111
+ );
1112
+ }
1113
+ function isTerminal(runs) {
1114
+ const run = latestRun(runs);
1115
+ return Boolean(run && TERMINAL_RUN.has(run.status));
1116
+ }
1117
+ function activeRun(runs) {
1118
+ const run = latestRun(runs);
1119
+ return run && !TERMINAL_RUN.has(run.status) ? run : null;
1120
+ }
1121
+ function steerableRun(p) {
1122
+ const run = activeRun(p.runs ?? []);
1123
+ if (!run) return null;
1124
+ const attempts = new Set((p.attempts ?? []).filter((a) => a.runId === run.id).map((a) => a.id));
1125
+ const turning = (p.providerTurns ?? []).some(
1126
+ (t) => t.status === "running" && t.runAttemptId !== null && attempts.has(t.runAttemptId)
1127
+ );
1128
+ return turning ? run : null;
1129
+ }
1130
+ var STEER_WAIT_MS = 8e3;
1131
+ var STEER_POLL_MS = 500;
1132
+ function prUrlOf(thread) {
1133
+ const branch = thread.branch ?? null;
1134
+ const linked = thread.pullRequests ?? [];
1135
+ const own = branch ? linked.filter((pr) => pr.snapshot?.headBranch === branch) : [];
1136
+ const fromLinked = (own.at(-1) ?? linked.at(-1))?.url ?? thread.linkedPullRequest?.url;
1137
+ if (fromLinked) return fromLinked;
1138
+ if (branch && !SHARED_BRANCHES.has(branch)) return thread.branchPullRequest?.url ?? null;
1139
+ return null;
1176
1140
  }
1177
- function localRunsFilePath() {
1178
- return process.env.CLOOP_LOCAL_RUNS_FILE ?? join3(homedir2(), CONFIG_DIR, "local-runs.json");
1141
+ function outcomeOf(p) {
1142
+ const run = latestRun(p.runs ?? []);
1143
+ const status = run?.status ?? "pending";
1144
+ const settled = TERMINAL_RUN.has(status) || Boolean(p.thread.settledAt);
1145
+ const text2 = (p.messages ?? []).filter((m) => m.role === "assistant" && m.text).at(-1)?.text?.trim();
1146
+ return {
1147
+ status,
1148
+ settled,
1149
+ kind: settled ? status === "completed" || !run ? "settled" : "failed" : null,
1150
+ pr_url: prUrlOf(p.thread),
1151
+ last_assistant_text: text2 ? text2.slice(0, 300) : null,
1152
+ ...parseRunResult(text2) ? { result: parseRunResult(text2) } : {}
1153
+ };
1179
1154
  }
1180
- function pickRepo(repos, repository) {
1155
+ function pickProject(projects, repository) {
1156
+ const only = projects.length === 1 ? projects[0] : void 0;
1181
1157
  if (!repository) {
1182
- if (repos.length === 1 && repos[0]) return repos[0];
1158
+ if (only) return only;
1183
1159
  throw new BoxToolError("no_project");
1184
1160
  }
1185
- const want = repository.toLowerCase().split("/").at(-1) ?? "";
1186
- const found = repos.find(
1187
- (r) => r.label.toLowerCase() === want || basename(r.path).toLowerCase() === want
1161
+ const want = repository.toLowerCase();
1162
+ const found = projects.find(
1163
+ (p) => p.title.toLowerCase() === want || p.workspaceRoot.split("/").at(-1)?.toLowerCase() === want || p.repositoryIdentity?.displayName?.toLowerCase() === want
1188
1164
  );
1189
1165
  if (!found) throw new BoxToolError("no_project");
1190
1166
  return found;
1191
1167
  }
1192
- function prUrlIn(text) {
1193
- return text?.match(PR_URL)?.at(-1) ?? null;
1168
+ var SHELL_HEADERS = { "x-t3-orchestration-protocol": "2" };
1169
+ function boxCapabilities(scope) {
1170
+ const scopes = (scope ?? "").split(/\s+/).filter(Boolean);
1171
+ return scopes.includes("orchestration:operate") ? ["view", "start", "steer"] : ["view"];
1194
1172
  }
1195
- function run(cmd, args, cwd) {
1196
- return new Promise(
1197
- (resolve3, reject) => execFile2(
1198
- cmd,
1199
- args,
1200
- { cwd, timeout: 1e4, encoding: "utf-8" },
1201
- (err, out2) => err ? reject(err) : resolve3(String(out2).trim())
1202
- )
1203
- );
1173
+ function threadView(t) {
1174
+ return {
1175
+ id: t.id,
1176
+ title: t.title,
1177
+ status: t.status,
1178
+ branch: t.branch ?? null,
1179
+ source: t.creationSource ?? null,
1180
+ cloop: (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX),
1181
+ settled: Boolean(t.settledAt),
1182
+ updatedAt: t.updatedAt
1183
+ };
1204
1184
  }
1205
- var gitProbe = {
1206
- head: (repo) => run("git", ["rev-parse", "HEAD"], repo).catch(() => null),
1207
- pushed: (repo) => run("git", ["branch", "-r", "--contains", "HEAD"], repo).then(
1208
- (out2) => out2.length > 0,
1209
- () => false
1210
- ),
1211
- async branchPr(repo) {
1212
- try {
1213
- const branch = await run("git", ["rev-parse", "--abbrev-ref", "HEAD"], repo);
1214
- if (SHARED_BRANCHES2.has(branch)) return null;
1215
- return prUrlIn(await run("gh", ["pr", "view", "--json", "url", "-q", ".url"], repo));
1216
- } catch {
1217
- return null;
1218
- }
1219
- }
1220
- };
1221
- function harnessAlive(pid, r, dialect) {
1222
- try {
1223
- process.kill(pid, 0);
1224
- } catch (err) {
1225
- if (err.code !== "EPERM") return false;
1226
- }
1227
- try {
1228
- const command = execFileSync3("ps", ["-ww", "-o", "command=", "-p", String(pid)], {
1229
- encoding: "utf-8",
1230
- timeout: 2e3
1231
- });
1232
- return dialect.owns(r, command);
1233
- } catch {
1234
- return false;
1235
- }
1185
+ function orderThreads(threads, limit) {
1186
+ const byRecency = (a, b) => b.updatedAt.localeCompare(a.updatedAt);
1187
+ const running = threads.filter((t) => t.status === "running").sort(byRecency);
1188
+ const rest = threads.filter((t) => t.status !== "running").sort(byRecency);
1189
+ return [...running, ...rest].slice(0, limit);
1236
1190
  }
1237
- var KEEP_MS2 = 7 * 24 * 36e5;
1238
- var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
1239
- var LocalDriver = class {
1191
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1192
+ var T3Driver = class {
1240
1193
  constructor(deps) {
1241
1194
  this.deps = deps;
1242
- this.name = deps.dialect.name;
1243
- this.capabilities = deps.dialect.capabilities;
1244
- this.runs = new Map(this.load().map((r) => [r.work_id, r]));
1245
1195
  }
1246
1196
  deps;
1247
- name;
1248
- capabilities;
1249
- runs;
1250
- lives = /* @__PURE__ */ new Map();
1251
- listeners = /* @__PURE__ */ new Map();
1252
- recovering = /* @__PURE__ */ new Set();
1253
- stopping = false;
1254
- get repo() {
1255
- return this.deps.repo ?? gitProbe;
1256
- }
1257
- get file() {
1258
- return this.deps.file ?? localRunsFilePath();
1197
+ name = "t3";
1198
+ get capabilities() {
1199
+ return boxCapabilities(this.deps.scope?.());
1200
+ }
1201
+ get t3() {
1202
+ return this.deps.client();
1259
1203
  }
1260
1204
  log(line2) {
1261
1205
  this.deps.log?.(line2);
1262
1206
  }
1263
- now() {
1264
- return this.deps.now?.() ?? Date.now();
1207
+ /**
1208
+ * T3's config and shell calls take 2-20 s on a loaded box, past the app's
1209
+ * wait. So status reads them from the last answer at once and refreshes
1210
+ * them in the background, at most once per STATUS_TTL_MS. Only the first
1211
+ * call waits.
1212
+ */
1213
+ t3State = { value: null, at: 0, refreshing: null };
1214
+ readT3State() {
1215
+ const cache = this.t3State;
1216
+ if (!cache.refreshing && Date.now() - cache.at > STATUS_TTL_MS) {
1217
+ cache.refreshing = Promise.all([
1218
+ this.t3.rpc("server.getConfig", {}),
1219
+ this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
1220
+ ]).then((value) => {
1221
+ cache.value = value;
1222
+ cache.at = Date.now();
1223
+ return value;
1224
+ }).finally(() => {
1225
+ cache.refreshing = null;
1226
+ });
1227
+ cache.refreshing.catch(() => {
1228
+ });
1229
+ }
1230
+ return cache.value ? Promise.resolve(cache.value) : cache.refreshing;
1265
1231
  }
1266
1232
  async status() {
1267
- const harnesses = this.deps.harnesses ? await this.deps.harnesses() : [await this.deps.dialect.probe()].filter((h) => h !== null);
1268
- const all = [...this.runs.values()];
1269
- const unsettled = all.filter((r) => !r.end);
1233
+ const [cfg, shell] = await this.readT3State();
1234
+ const sessions = this.listSessions();
1235
+ const threads = (shell.threads ?? []).filter((t) => !isChild(t));
1236
+ const unsettled = threads.filter(isUnsettled);
1270
1237
  return {
1271
- box: { label: this.deps.label ?? hostname(), driver: this.name },
1272
- harnesses,
1273
- clients: null,
1274
- projects: this.deps.repos.map((r) => r.label),
1238
+ box: {
1239
+ label: cfg.environment.label,
1240
+ driver: "t3",
1241
+ t3Version: cfg.environment.serverVersion,
1242
+ protocol: cfg.environment.orchestrationProtocolVersion,
1243
+ hosts: (cfg.remoteOpenTargets ?? []).map((t) => t.host)
1244
+ },
1245
+ harnesses: cfg.providers.filter((p) => p.enabled).map((p) => ({
1246
+ id: p.instanceId,
1247
+ name: p.displayName ?? p.instanceId,
1248
+ version: p.version,
1249
+ ready: p.status === "ready",
1250
+ signedIn: p.auth?.status === "authenticated",
1251
+ account: p.auth?.label ?? null,
1252
+ defaultModel: p.models?.find((m) => m.isDefault)?.slug ?? null
1253
+ })),
1254
+ clients: sessions?.filter((s) => s.client?.deviceType !== "bot").map((s) => ({
1255
+ label: s.client?.label ?? "unknown",
1256
+ connected: s.connected === true,
1257
+ lastConnectedAt: s.lastConnectedAt ?? null
1258
+ })) ?? null,
1259
+ projects: (shell.projects ?? []).map((p) => p.title),
1275
1260
  threads: {
1276
1261
  unsettled: unsettled.length,
1277
- running: unsettled.filter((r) => this.lives.has(r.work_id)).length,
1278
- settled: all.length - unsettled.length,
1279
- cloop: unsettled.length
1262
+ running: unsettled.filter((t) => t.status === "running").length,
1263
+ settled: threads.length - unsettled.length,
1264
+ cloop: unsettled.filter((t) => (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX)).length
1280
1265
  }
1281
1266
  };
1282
1267
  }
@@ -1284,738 +1269,354 @@ var LocalDriver = class {
1284
1269
  scope,
1285
1270
  limit
1286
1271
  }) {
1287
- const all = [...this.runs.values()];
1288
- const unsettled = all.filter((r) => !r.end);
1289
- const shown = (scope === "all" ? all : unsettled).map((r) => ({
1290
- id: r.work_id,
1291
- title: r.title,
1292
- status: this.statusOf(r),
1293
- branch: null,
1294
- source: "cloop",
1295
- cloop: true,
1296
- settled: Boolean(r.end),
1297
- updatedAt: r.end?.at ?? r.started_at
1298
- }));
1272
+ const shell = await this.t3.http("/api/orchestration/shell", SHELL_HEADERS);
1273
+ const all = (shell.threads ?? []).filter((t) => !isChild(t));
1274
+ const threads = scope === "all" ? all : all.filter(isUnsettled);
1299
1275
  return {
1300
1276
  scope,
1301
- unsettled: unsettled.length,
1302
- settled: all.length - unsettled.length,
1303
- running: shown.filter((t) => t.status === "running").length,
1304
- threads: orderThreads(shown, limit)
1305
- };
1306
- }
1307
- async readThread(id) {
1308
- const r = this.record(id);
1309
- return {
1310
- status: this.statusOf(r),
1311
- settled: Boolean(r.end),
1312
- pr_url: r.end?.pr_url ?? null,
1313
- last_assistant_text: r.end?.summary ?? r.last_text ?? null
1277
+ unsettled: all.filter(isUnsettled).length,
1278
+ settled: all.length - all.filter(isUnsettled).length,
1279
+ running: threads.filter((t) => t.status === "running").length,
1280
+ threads: orderThreads(threads, limit).map(threadView)
1314
1281
  };
1315
1282
  }
1283
+ /**
1284
+ * `work_id` is T3's `commandId`, so a second launch of the same work returns
1285
+ * the same thread with `resumed: true` and runs nothing twice. The worktree
1286
+ * starts from origin's copy of the branch the project's checkout is on.
1287
+ */
1316
1288
  async launch(a) {
1317
- if (this.runs.has(a.work_id)) return { thread_id: a.work_id, resumed: true };
1318
- const { dialect } = this.deps;
1319
- if (a.harness && !dialect.aliases.includes(a.harness))
1320
- throw new BoxToolError("harness_unavailable");
1321
- const repo = pickRepo(this.deps.repos, a.repository);
1322
- this.refuseBusy(repo.path);
1323
- const harness = await dialect.probe();
1324
- if (!harness) throw new BoxToolError("harness_unavailable");
1325
- if (!harness.signedIn) throw new BoxToolError("harness_signed_out");
1326
- const head = await this.repo.head(repo.path);
1327
- if (this.runs.has(a.work_id)) return { thread_id: a.work_id, resumed: true };
1328
- this.refuseBusy(repo.path);
1329
- const record = {
1330
- work_id: a.work_id,
1331
- session_id: dialect.name === "claude-code" ? a.work_id : null,
1332
- repo: repo.path,
1333
- title: a.title,
1334
- ...a.model ? { model: a.model } : {},
1335
- ...a.runtime_mode ? { runtime_mode: a.runtime_mode } : {},
1336
- pid: null,
1337
- started_at: new Date(this.now()).toISOString(),
1338
- head_at_launch: head
1339
- };
1340
- this.runs.set(a.work_id, record);
1341
- this.spawnRun(record, a.prompt, false);
1342
- return { thread_id: a.work_id, resumed: false };
1289
+ const known = this.deps.watched?.({ work_id: a.work_id });
1290
+ if (known) return { thread_id: known.thread_id, resumed: true };
1291
+ const [cfg, shell] = await Promise.all([
1292
+ this.t3.rpc("server.getConfig", {}),
1293
+ this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
1294
+ ]);
1295
+ const project = pickProject(shell.projects ?? [], a.repository);
1296
+ const fallback = cfg.settings?.defaultModelSelection;
1297
+ const harness = a.harness ?? fallback?.instanceId ?? "claudeAgent";
1298
+ const provider = cfg.providers.find((p) => p.instanceId === harness && p.enabled);
1299
+ if (!provider) throw new BoxToolError("harness_unavailable");
1300
+ if (provider.auth && provider.auth.status !== "authenticated")
1301
+ throw new BoxToolError("harness_signed_out");
1302
+ const model = a.model ?? (fallback?.instanceId === harness ? fallback.model : void 0) ?? provider.models?.find((m) => m.isDefault)?.slug;
1303
+ if (!model) throw new BoxToolError("harness_unavailable");
1304
+ const modelSelection = !a.model && fallback?.instanceId === harness ? fallback : { instanceId: harness, model };
1305
+ const runtimeMode = a.runtime_mode ?? cfg.settings?.defaultRuntimeMode;
1306
+ if (!runtimeMode || !RUNTIME_MODES.has(runtimeMode))
1307
+ throw new BoxToolError("runtime_mode_unknown");
1308
+ const launched = await this.t3.rpc(
1309
+ "orchestration.launchThread",
1310
+ {
1311
+ commandId: a.work_id,
1312
+ creationSource: "mcp",
1313
+ projectId: project.id,
1314
+ title: a.title,
1315
+ modelSelection,
1316
+ runtimeMode,
1317
+ interactionMode: "default",
1318
+ workspaceStrategy: {
1319
+ type: "worktree",
1320
+ baseRef: this.baseRefFor(project.workspaceRoot)
1321
+ },
1322
+ initialMessage: { text: `${a.prompt}
1323
+
1324
+ ${RESULT_INSTRUCTION}`, attachments: [] }
1325
+ }
1326
+ );
1327
+ return { thread_id: launched.threadId, resumed: launched.resumed };
1343
1328
  }
1329
+ /**
1330
+ * Say something to a thread. While the thread waits on a question, only
1331
+ * `answer: true` sends anything: the text answers every question in the
1332
+ * newest request, because a steer does not resolve a pending question and
1333
+ * the run would wait on. Without it the call sends nothing and returns the
1334
+ * question, so the owner says which they meant. Otherwise `steer`
1335
+ * joins the running turn, waiting up to 8 s for a starting run's provider
1336
+ * turn. A run that still cannot take a steer, or `queue`, gets the text
1337
+ * after it ends; a thread with nothing running starts a new turn.
1338
+ * `command_id` is T3's commandId, so a retried call sends once.
1339
+ */
1344
1340
  async send(a) {
1345
- const r = this.record(a.thread_id);
1346
- const seen = r.commands?.find(([id]) => id === a.command_id);
1347
- if (seen) return { delivered: seen[1] };
1348
- const live = this.lives.get(r.work_id);
1349
- const ask = live?.asks[0];
1350
- if (a.answer && (!ask || ask.request_id !== a.question_id)) {
1351
- this.log(`question_changed work=${r.work_id}`);
1341
+ let p = await this.readProjection(a.thread_id);
1342
+ const pending = pendingQuestions(p);
1343
+ const question = pending.at(-1);
1344
+ if (a.answer && a.question_id !== void 0 && question?.request_id !== a.question_id) {
1352
1345
  return {
1353
1346
  delivered: "question_changed",
1354
- question: ask?.summary ?? null,
1355
- question_id: ask?.request_id ?? null
1347
+ question: question ? questionText(question) : null,
1348
+ question_id: question?.request_id ?? null
1356
1349
  };
1357
1350
  }
1358
- if (live && ask) {
1359
- if (!a.answer) {
1360
- return {
1361
- delivered: "question_pending",
1362
- question: ask.summary,
1363
- questions: live.asks.length
1364
- };
1365
- }
1366
- const line3 = this.deps.dialect.answerLine?.(ask, a.text);
1367
- if (!line3) throw new BoxToolError("cannot_steer");
1368
- live.asks = live.asks.slice(1);
1369
- this.write(live, line3);
1370
- this.remember(r, a.command_id, "answer");
1371
- this.log(`answer work=${r.work_id}`);
1372
- this.askNext(r, live);
1373
- return { delivered: "answer", question_id: ask.request_id };
1374
- }
1375
- if (!live) {
1376
- if (r.end) throw new BoxToolError("already_finished");
1377
- this.spawnRun(r, a.text, true);
1378
- this.remember(r, a.command_id, "start");
1379
- return { delivered: "start" };
1380
- }
1381
- if (live.child.stdin?.writableEnded) {
1382
- live.next = live.next ? `${live.next}
1383
-
1384
- ${a.text}` : a.text;
1385
- this.remember(r, a.command_id, "queue");
1386
- return { delivered: "queue" };
1387
- }
1388
- const line2 = this.deps.dialect.userLine?.(r, a.text, a.mode);
1389
- if (!line2) throw new BoxToolError("cannot_steer");
1390
- live.outstanding++;
1391
- this.write(live, line2);
1392
- const delivered = a.mode === "queue" ? "queue" : "steer";
1393
- this.remember(r, a.command_id, delivered);
1394
- this.log(`${delivered} work=${r.work_id}`);
1395
- return { delivered };
1396
- }
1397
- async interrupt(id) {
1398
- const r = this.record(id);
1399
- const live = this.lives.get(r.work_id);
1400
- if (!live) {
1401
- if (r.end) return { ok: true, was_running: false };
1402
- const orphan = r.pid !== null && this.alive(r.pid, r);
1403
- if (orphan && r.pid !== null) {
1404
- try {
1405
- process.kill(r.pid, "SIGINT");
1406
- } catch {
1407
- }
1408
- }
1409
- await this.end(r, { kind: "failed", summary: "The run was stopped." });
1410
- return { ok: true, was_running: orphan };
1411
- }
1412
- live.interrupted = true;
1413
- live.child.kill("SIGINT");
1414
- const timer = setTimeout(() => {
1415
- if (live.child.exitCode === null && live.child.signalCode === null)
1416
- live.child.kill("SIGTERM");
1417
- }, this.deps.interruptGraceMs ?? 1e4);
1418
- timer.unref();
1419
- this.log(`interrupt work=${r.work_id}`);
1420
- return { ok: true, was_running: true };
1421
- }
1422
- watch(id, onEvent) {
1423
- const set = this.listeners.get(id) ?? /* @__PURE__ */ new Set();
1424
- set.add(onEvent);
1425
- this.listeners.set(id, set);
1426
- const r = this.runs.get(id);
1427
- const unwatch = () => set.delete(onEvent);
1428
- if (!r) {
1429
- onEvent({ kind: "failed", summary: "This run is not on the runner any more." });
1430
- return unwatch;
1431
- }
1432
- if (r.end) {
1433
- const { at: _at, ...end } = r.end;
1434
- onEvent(end);
1435
- return unwatch;
1436
- }
1437
- const live = this.lives.get(id);
1438
- const ask = live?.asks[0];
1439
- if (ask) onEvent({ kind: "question", question_id: ask.request_id, summary: ask.summary });
1440
- if (!live) void this.recover(r);
1441
- return unwatch;
1442
- }
1443
- /** On a daemon stop: end every process, and leave its run open so the next start resumes it. */
1444
- stop() {
1445
- this.stopping = true;
1446
- for (const live of this.lives.values()) live.child.kill("SIGTERM");
1447
- }
1448
- alive(pid, r) {
1449
- return this.deps.alive ? this.deps.alive(pid, r) : harnessAlive(pid, r, this.deps.dialect);
1450
- }
1451
- /** One checkout, one run: two harnesses editing the same files at once would undo each other. */
1452
- refuseBusy(repo) {
1453
- if ([...this.runs.values()].some((r) => r.repo === repo && !r.end))
1454
- throw new BoxToolError("repo_busy");
1455
- }
1456
- /** One question at a time, oldest first, so a yes answers the prompt the owner read. */
1457
- askNext(r, live) {
1458
- const next = live.asks[0];
1459
- if (!next) return;
1460
- this.log(`question work=${r.work_id} tool=${next.tool}`);
1461
- this.emit(r.work_id, { kind: "question", question_id: next.request_id, summary: next.summary });
1462
- }
1463
- /** A run left open by a daemon that died: wait for its old process to go, then resume it once. */
1464
- async recover(r) {
1465
- if (this.recovering.has(r.work_id)) return;
1466
- this.recovering.add(r.work_id);
1467
- try {
1468
- while (r.pid !== null && this.alive(r.pid, r) && !r.end && !this.stopping) {
1469
- await sleep2(this.deps.orphanPollMs ?? 2e3);
1470
- }
1471
- if (r.end || this.stopping || this.lives.has(r.work_id)) return;
1472
- this.log(`resume work=${r.work_id} after a restart`);
1473
- this.spawnRun(r, CONTINUE_PROMPT, true);
1474
- } finally {
1475
- this.recovering.delete(r.work_id);
1476
- }
1477
- }
1478
- spawnRun(r, prompt, resume) {
1479
- const { dialect } = this.deps;
1480
- const child = spawn(dialect.bin, dialect.args(r, resume), {
1481
- cwd: r.repo,
1482
- stdio: ["pipe", "pipe", "pipe"],
1483
- env: process.env
1484
- });
1485
- const live = {
1486
- child,
1487
- outstanding: 1,
1488
- asks: [],
1489
- lastProgressAt: 0,
1490
- interrupted: false,
1491
- stderr: ""
1492
- };
1493
- this.lives.set(r.work_id, live);
1494
- r.pid = child.pid ?? null;
1495
- this.save();
1496
- this.log(`spawn work=${r.work_id} pid=${r.pid ?? "none"} ${resume ? "resume" : "new"}`);
1497
- child.stdin?.on("error", () => {
1498
- });
1499
- child.stdin?.write(dialect.opening(r, prompt));
1500
- if (!dialect.keepsStdin) child.stdin?.end();
1501
- child.stderr?.on("data", (chunk) => {
1502
- live.stderr = (live.stderr + chunk.toString("utf-8")).slice(-2e3);
1503
- });
1504
- const lines = createInterface({ input: child.stdout });
1505
- lines.on("line", (line2) => {
1506
- for (const item of dialect.parse(line2, r)) this.onItem(r, live, item);
1507
- });
1508
- child.on("error", (err) => {
1509
- this.log(`spawn failed work=${r.work_id}: ${err.message.slice(0, 200)}`);
1510
- });
1511
- child.on("close", (code, signal) => void this.onExit(r, live, code, signal));
1512
- }
1513
- onItem(r, live, item) {
1514
- switch (item.type) {
1515
- case "session":
1516
- if (r.session_id !== item.id) {
1517
- r.session_id = item.id;
1518
- this.save();
1519
- }
1520
- return;
1521
- case "text":
1522
- r.last_text = item.text.slice(0, 300);
1523
- this.progress(r, live, item.text, false);
1524
- return;
1525
- case "tool": {
1526
- const changed = item.name !== live.lastTool;
1527
- live.lastTool = item.name;
1528
- this.progress(r, live, item.target ? `${item.name} ${item.target}` : item.name, changed);
1529
- return;
1530
- }
1531
- case "ask":
1532
- live.asks.push(item);
1533
- if (live.asks.length === 1) this.askNext(r, live);
1534
- return;
1535
- case "cancel": {
1536
- const wasAsked = live.asks[0]?.request_id === item.request_id;
1537
- live.asks = live.asks.filter((x) => x.request_id !== item.request_id);
1538
- if (wasAsked) this.askNext(r, live);
1539
- return;
1540
- }
1541
- case "result":
1542
- live.outstanding--;
1543
- live.result = { ok: item.ok, ...item.text ? { text: item.text } : {} };
1544
- if (item.text) r.last_text = item.text.slice(0, 300);
1545
- if (live.outstanding <= 0 && live.asks.length === 0) live.child.stdin?.end();
1546
- return;
1547
- }
1548
- }
1549
- progress(r, live, line2, force) {
1550
- const now = this.now();
1551
- if (!force && now - live.lastProgressAt < (this.deps.progressMs ?? 3e4)) return;
1552
- live.lastProgressAt = now;
1553
- this.emit(r.work_id, {
1554
- kind: "progress",
1555
- summary: line2.replace(/\s+/g, " ").trim().slice(0, 200)
1556
- });
1557
- }
1558
- async onExit(r, live, code, signal) {
1559
- if (this.lives.get(r.work_id) === live) this.lives.delete(r.work_id);
1560
- if (this.stopping || r.end) return;
1561
- const exit = signal ? `signal ${signal}` : `code ${code}`;
1562
- this.log(
1563
- `exit work=${r.work_id} ${exit} result=${live.result ? live.result.ok ? "ok" : "error" : "none"}`
1564
- );
1565
- if (live.interrupted) {
1566
- await this.end(r, { kind: "failed", summary: "The run was stopped." });
1567
- return;
1568
- }
1569
- if (live.next) {
1570
- this.spawnRun(r, live.next, true);
1571
- return;
1351
+ if (question && !a.answer) {
1352
+ return {
1353
+ delivered: "question_pending",
1354
+ question: questionText(question),
1355
+ questions: pending.length
1356
+ };
1572
1357
  }
1573
- if (code === 0 && live.result?.ok) {
1574
- const text = live.result.text?.trim() || r.last_text;
1575
- const { pr, note } = await this.outcome(r, text);
1576
- const summary = [r.switched, note, text].filter(Boolean).join(" ").replace(/\s+/g, " ");
1577
- await this.end(r, {
1578
- kind: "settled",
1579
- ...summary ? { summary: summary.slice(0, SUMMARY_MAX) } : {},
1580
- ...pr ? { pr_url: pr } : {}
1358
+ if (question) {
1359
+ const receipt2 = await this.dispatch({
1360
+ type: "runtime-request.respond",
1361
+ commandId: a.command_id,
1362
+ threadId: a.thread_id,
1363
+ requestId: question.request_id,
1364
+ answers: Object.fromEntries(question.questions.map((q) => [q.id, a.text]))
1581
1365
  });
1582
- return;
1366
+ return { sequence: receipt2.sequence, delivered: "answer", question_id: question.request_id };
1583
1367
  }
1584
- if (live.stderr)
1585
- this.log(`stderr work=${r.work_id}: ${live.stderr.trim().split("\n").at(-1)?.slice(0, 200)}`);
1586
- const end = failedEnd(this.name, {
1587
- result: live.result,
1588
- lastText: r.last_text,
1589
- exit,
1590
- ...r.switched ? { switched: r.switched } : {}
1591
- });
1592
- if (end.error) this.log(`limit work=${r.work_id} error=${end.error}`);
1593
- if (end.error === "harness_limit" && this.fallBack(r, live.result?.text)) return;
1594
- await this.end(r, { kind: "failed", ...end });
1595
- }
1596
- /**
1597
- * Once per run: a run stopped by its model's usage limit resumes its own
1598
- * session on the first fallback model, with the continue prompt, so its
1599
- * steers, answers and edits carry over. It does not when the Task named its
1600
- * model, when the limit is the fallback model's own, or after one switch.
1601
- * `--fallback-model` may already cover this; it is not documented whether a
1602
- * plan's limit counts. The switch opens the end summary, because a progress
1603
- * line is dropped while the socket is down.
1604
- */
1605
- fallBack(r, said) {
1606
- const model = this.deps.dialect.fallback?.split(",")[0]?.trim();
1607
- if (!model || !r.session_id || r.switched || r.model) return false;
1608
- const named = new RegExp(`\\b${model.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i");
1609
- if (named.test(said ?? "")) return false;
1610
- const from = /reached your ([\w .-]{1,40}?) limit/i.exec(said ?? "")?.[1] ?? "The default model";
1611
- const to = `${model.charAt(0).toUpperCase()}${model.slice(1)}`;
1612
- r.switched = `${from} was at its usage limit, so this ran on ${to}.`;
1613
- r.model = model;
1614
- this.save();
1615
- this.log(`fallback work=${r.work_id} model=${model}`);
1616
- this.emit(r.work_id, {
1617
- kind: "progress",
1618
- summary: `${from} is at its usage limit, so I switched to ${to}`
1368
+ if (a.mode === "steer") {
1369
+ for (let waited = 0; waited < STEER_WAIT_MS; waited += STEER_POLL_MS) {
1370
+ if (!activeRun(p.runs ?? []) || steerableRun(p)) break;
1371
+ await sleep(STEER_POLL_MS);
1372
+ p = await this.readProjection(a.thread_id);
1373
+ }
1374
+ }
1375
+ const steer = a.mode === "steer" ? steerableRun(p) : null;
1376
+ const active = activeRun(p.runs ?? []);
1377
+ if (!active && !a.resume && this.deps.watched?.({ thread_id: a.thread_id })?.settled)
1378
+ throw new BoxToolError("already_finished");
1379
+ const receipt = await this.dispatch({
1380
+ type: "message.dispatch",
1381
+ commandId: a.command_id,
1382
+ threadId: a.thread_id,
1383
+ messageId: a.command_id,
1384
+ text: a.text,
1385
+ attachments: [],
1386
+ dispatchMode: steer ? { type: "steer_active", targetRunId: steer.id } : active ? { type: "queue_after_active" } : { type: "start_immediately" },
1387
+ createdBy: "user",
1388
+ creationSource: "mcp"
1619
1389
  });
1620
- this.spawnRun(r, CONTINUE_PROMPT, true);
1621
- return true;
1390
+ return { sequence: receipt.sequence, delivered: steer ? "steer" : active ? "queue" : "start" };
1622
1391
  }
1623
1392
  /**
1624
- * The PR a run produced: one its last text names, else the PR of the
1625
- * branch, but only when the run moved HEAD. A run that left HEAD where it
1626
- * started produced nothing, and the branch's PR belongs to someone else's
1627
- * work. A run that committed without pushing says so.
1393
+ * Stop the running turn. A thread with nothing running answers
1394
+ * `was_running: false`, and so does a run that ended while the interrupt
1395
+ * was on its way: T3 refuses that interrupt, and the owner's ask is met.
1628
1396
  */
1629
- async outcome(r, text) {
1630
- const named = prUrlIn(text);
1631
- if (named) return { pr: named };
1632
- if (!r.head_at_launch) return { pr: null };
1633
- const head = await this.repo.head(r.repo);
1634
- if (!head || head === r.head_at_launch) return { pr: null };
1635
- const pr = await this.repo.branchPr(r.repo);
1636
- if (pr) return { pr };
1637
- return await this.repo.pushed(r.repo) ? { pr: null } : { pr: null, note: `Committed ${head.slice(0, 7)}, not pushed.` };
1638
- }
1639
- async end(r, end) {
1640
- if (r.end) return;
1641
- r.end = { ...end, at: new Date(this.now()).toISOString() };
1642
- r.pid = null;
1643
- this.save();
1644
- this.emit(r.work_id, end);
1645
- }
1646
- emit(id, event) {
1647
- for (const listener of [...this.listeners.get(id) ?? []]) listener(event);
1648
- }
1649
- write(live, line2) {
1650
- live.child.stdin?.write(line2);
1651
- }
1652
- remember(r, commandId, delivered) {
1653
- r.commands = [
1654
- ...r.commands ?? [],
1655
- [commandId, delivered]
1656
- ].slice(-COMMANDS_KEPT);
1657
- this.save();
1658
- }
1659
- record(id) {
1660
- const r = this.runs.get(id);
1661
- if (!r) throw new BoxToolError("bad_args");
1662
- return r;
1663
- }
1664
- statusOf(r) {
1665
- if (this.lives.has(r.work_id)) return "running";
1666
- if (!r.end) return "pending";
1667
- return r.end.kind === "settled" ? "completed" : "failed";
1668
- }
1669
- load() {
1397
+ async interrupt(threadId, commandId) {
1398
+ const run = activeRun((await this.readProjection(threadId)).runs ?? []);
1399
+ if (!run) return { ok: true, was_running: false };
1670
1400
  try {
1671
- const raw = JSON.parse(readFileSync2(this.file, "utf-8"));
1672
- const cutoff = this.now() - KEEP_MS2;
1673
- return Array.isArray(raw) ? raw.filter(
1674
- (r) => typeof r?.work_id === "string" && typeof r?.repo === "string" && !(r.end && Date.parse(r.end.at) < cutoff)
1675
- ) : [];
1676
- } catch {
1677
- return [];
1401
+ await this.dispatch({
1402
+ type: "run.interrupt",
1403
+ commandId,
1404
+ threadId,
1405
+ runId: run.id,
1406
+ reason: "Stopped from Cloop"
1407
+ });
1408
+ } catch (err) {
1409
+ if (activeRun((await this.readProjection(threadId)).runs ?? [])) throw err;
1410
+ return { ok: true, was_running: false };
1678
1411
  }
1412
+ return { ok: true, was_running: true };
1679
1413
  }
1680
- save() {
1681
- mkdirSync2(dirname2(this.file), { recursive: true, mode: 448 });
1682
- const tmp = `${this.file}.tmp`;
1683
- writeFileSync2(tmp, `${JSON.stringify([...this.runs.values()], null, 2)}
1684
- `, { mode: 384 });
1685
- chmodSync2(tmp, 384);
1686
- renameSync2(tmp, this.file);
1414
+ async readThread(id) {
1415
+ const { status, settled, pr_url, last_assistant_text } = outcomeOf(
1416
+ await this.readProjection(id)
1417
+ );
1418
+ return { status, settled, pr_url, last_assistant_text };
1687
1419
  }
1688
- };
1689
-
1690
- // src/drivers/claude-code.ts
1691
- var SUBSCRIPTIONS = {
1692
- max: "Claude Max",
1693
- pro: "Claude Pro",
1694
- team: "Claude Team",
1695
- enterprise: "Claude Enterprise"
1696
- };
1697
- var YES_WORDS = /* @__PURE__ */ new Set([
1698
- "y",
1699
- "yes",
1700
- "yep",
1701
- "yeah",
1702
- "allow",
1703
- "allow it",
1704
- "ok",
1705
- "okay",
1706
- "approve",
1707
- "approved",
1708
- "go ahead",
1709
- "sure",
1710
- "do it"
1711
- ]);
1712
- function isYes(reply) {
1713
- return YES_WORDS.has(
1714
- reply.trim().toLowerCase().replace(/[.!\s]+$/, "")
1715
- );
1716
- }
1717
- function exec(bin, args) {
1718
- return new Promise(
1719
- (resolve3) => execFile3(
1720
- bin,
1721
- args,
1722
- { timeout: 1e4, encoding: "utf-8" },
1723
- (err, out2) => resolve3(err ? null : String(out2))
1724
- )
1725
- );
1726
- }
1727
- function claudeAccount(raw) {
1728
- try {
1729
- const auth = JSON.parse(raw ?? "");
1730
- if (auth.loggedIn !== true) return { signedIn: false, account: null };
1731
- const plan = auth.subscriptionType ? SUBSCRIPTIONS[auth.subscriptionType] : void 0;
1732
- return {
1733
- signedIn: true,
1734
- account: plan ?? (auth.authMethod === "claude.ai" ? "Claude" : "API key")
1420
+ /**
1421
+ * Subscribe to the thread and resubscribe whenever the stream ends. A thread
1422
+ * that settled while nobody watched shows a terminal run in its first
1423
+ * snapshot. A question is reported on every update it is still pending.
1424
+ */
1425
+ watch(threadId, onEvent) {
1426
+ let stopped = false;
1427
+ let finishing = false;
1428
+ let live = null;
1429
+ const retry = () => {
1430
+ if (stopped) return;
1431
+ const timer = setTimeout(() => void follow(), this.deps.retryMs ?? 1e4);
1432
+ timer.unref?.();
1735
1433
  };
1736
- } catch {
1737
- return { signedIn: false, account: null };
1738
- }
1739
- }
1740
- async function probeClaude(bin = "claude") {
1741
- const version = (await exec(bin, ["--version"]))?.trim().split(/\s+/)[0];
1742
- if (!version) return null;
1743
- const { signedIn, account } = claudeAccount(await exec(bin, ["auth", "status", "--json"]));
1744
- return {
1745
- id: "claude-code",
1746
- name: "Claude Code",
1747
- version,
1748
- ready: signedIn,
1749
- signedIn,
1750
- account,
1751
- defaultModel: null
1752
- };
1753
- }
1754
- function pathOf(input) {
1755
- const fields = input ?? {};
1756
- const path = fields.file_path ?? fields.notebook_path ?? fields.path;
1757
- return typeof path === "string" ? path : void 0;
1758
- }
1759
- function shownPath(path, repo) {
1760
- const inside = relative(repo, resolve(repo, path));
1761
- return inside && !inside.startsWith("..") && !isAbsolute(inside) ? inside : path;
1762
- }
1763
- function questionsOf(input) {
1764
- const questions = input?.questions;
1765
- return Array.isArray(questions) ? questions.filter((q) => typeof q?.question === "string") : [];
1766
- }
1767
- var REPLY = "Reply yes to allow it, or say what to do instead.";
1768
- function cut(text) {
1769
- const line2 = text.replace(/\s+/g, " ").trim();
1770
- return line2.length > 200 ? `${line2.slice(0, 200)}\u2026` : line2;
1771
- }
1772
- function askSummary(tool, input, repo) {
1773
- if (tool === "AskUserQuestion") return questionLine(questionsOf(input));
1774
- const fields = input ?? {};
1775
- if (tool === "Bash") {
1776
- const shown = cut(String(fields.command ?? ""));
1777
- const why = typeof fields.description === "string" ? ` (${fields.description.slice(0, 100)})` : "";
1778
- return `Claude Code asks to run: ${shown}${why}. ${REPLY}`;
1779
- }
1780
- if (tool === "WebFetch" && typeof fields.url === "string")
1781
- return `Claude Code asks to fetch ${cut(fields.url)}. ${REPLY}`;
1782
- if (tool.startsWith("mcp__"))
1783
- return `Claude Code asks to use ${tool} with ${cut(JSON.stringify(fields))}. ${REPLY}`;
1784
- const path = pathOf(fields);
1785
- const where = path ? ` on ${shownPath(path, repo)}` : "";
1786
- return `Claude Code asks to use ${tool}${where}. ${REPLY}`;
1787
- }
1788
- function line(value) {
1789
- return `${JSON.stringify(value)}
1790
- `;
1791
- }
1792
- function userMessage(run2, text, priority) {
1793
- return {
1794
- type: "user",
1795
- message: { role: "user", content: [{ type: "text", text }] },
1796
- parent_tool_use_id: null,
1797
- session_id: run2.session_id ?? run2.work_id,
1798
- ...priority ? { priority } : {}
1799
- };
1800
- }
1801
- function parseClaudeLine(raw, run2) {
1802
- let msg;
1803
- try {
1804
- msg = JSON.parse(raw);
1805
- } catch {
1806
- return [];
1807
- }
1808
- if (msg.type === "system" && msg.subtype === "init" && typeof msg.session_id === "string") {
1809
- return [{ type: "session", id: msg.session_id }];
1810
- }
1811
- if (msg.type === "assistant") {
1812
- const content = msg.message?.content;
1813
- if (!Array.isArray(content)) return [];
1814
- return content.flatMap((block) => {
1815
- if (block?.type === "text" && typeof block.text === "string" && block.text.trim())
1816
- return [{ type: "text", text: block.text }];
1817
- if (block?.type === "tool_use" && typeof block.name === "string" && block.name !== "AskUserQuestion") {
1818
- const path = pathOf(block.input);
1819
- return [{ type: "tool", name: block.name, ...path ? { target: basename2(path) } : {} }];
1434
+ const finish = async () => {
1435
+ if (stopped || finishing) return;
1436
+ finishing = true;
1437
+ let outcome;
1438
+ try {
1439
+ outcome = outcomeOf(await this.readProjection(threadId));
1440
+ const grace = this.deps.prGraceMs ?? 6e4;
1441
+ if (outcome.settled && outcome.kind === "settled" && !outcome.pr_url && grace > 0) {
1442
+ await sleep(grace);
1443
+ outcome = outcomeOf(await this.readProjection(threadId));
1444
+ }
1445
+ } catch (err) {
1446
+ this.log(
1447
+ `read failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
1448
+ );
1449
+ finishing = false;
1450
+ retry();
1451
+ return;
1452
+ }
1453
+ if (stopped) return;
1454
+ if (!outcome.settled) {
1455
+ finishing = false;
1456
+ this.log(`run continues thread=${threadId} run=${outcome.status}; watching on`);
1457
+ if (!live) void follow();
1458
+ return;
1459
+ }
1460
+ stopped = true;
1461
+ live?.close();
1462
+ const pr = outcome.pr_url ? { pr_url: outcome.pr_url } : {};
1463
+ if (outcome.kind === "failed") {
1464
+ onEvent({ kind: "failed", summary: `The run ended ${outcome.status}.`, ...pr });
1465
+ } else {
1466
+ onEvent({
1467
+ kind: "settled",
1468
+ ...outcome.result ? { result: outcome.result } : {},
1469
+ ...outcome.last_assistant_text ? { summary: outcome.last_assistant_text } : {},
1470
+ ...pr
1471
+ });
1472
+ }
1473
+ };
1474
+ const follow = async () => {
1475
+ if (stopped || live) return;
1476
+ const runs = /* @__PURE__ */ new Map();
1477
+ const requests = /* @__PURE__ */ new Map();
1478
+ const asks = /* @__PURE__ */ new Map();
1479
+ const keepAsk = (item) => {
1480
+ if (item.type === "user_input_request" && item.requestId) asks.set(item.requestId, item);
1481
+ };
1482
+ let settledByHand = false;
1483
+ let stream;
1484
+ try {
1485
+ stream = await this.t3.stream("orchestration.subscribeThread", { threadId }, (raw) => {
1486
+ const item = raw;
1487
+ if (item.kind === "snapshot" && "projection" in item) {
1488
+ for (const r of item.projection.runs ?? []) runs.set(r.id, r);
1489
+ for (const r of item.projection.runtimeRequests ?? []) requests.set(r.id, r);
1490
+ for (const t of item.projection.turnItems ?? []) keepAsk(t);
1491
+ settledByHand ||= Boolean(item.projection.thread?.settledAt);
1492
+ } else if (item.kind === "event" && "event" in item) {
1493
+ const { type, payload } = item.event;
1494
+ if (type.startsWith("run.") && typeof payload?.id === "string") {
1495
+ runs.set(payload.id, payload);
1496
+ } else if (type === "runtime-request.updated" && typeof payload?.id === "string") {
1497
+ requests.set(payload.id, payload);
1498
+ } else if (type === "turn-item.updated" && payload) {
1499
+ keepAsk(payload);
1500
+ } else if (type.startsWith("thread.") && payload?.settledAt) {
1501
+ settledByHand = true;
1502
+ } else return;
1503
+ } else return;
1504
+ if (settledByHand || isTerminal([...runs.values()])) {
1505
+ void finish();
1506
+ return;
1507
+ }
1508
+ const pending = pendingQuestions({
1509
+ runtimeRequests: [...requests.values()],
1510
+ turnItems: [...asks.values()]
1511
+ });
1512
+ for (const q of pending) {
1513
+ onEvent({ kind: "question", question_id: q.request_id, summary: questionText(q) });
1514
+ }
1515
+ });
1516
+ } catch (err) {
1517
+ this.log(
1518
+ `watch failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
1519
+ );
1520
+ retry();
1521
+ return;
1820
1522
  }
1821
- return [];
1822
- });
1823
- }
1824
- if (msg.type === "control_request") {
1825
- const request = msg.request;
1826
- if (request?.subtype !== "can_use_tool" || typeof msg.request_id !== "string") return [];
1827
- const tool = request.tool_name ?? "a tool";
1828
- return [
1829
- {
1830
- type: "ask",
1831
- request_id: msg.request_id,
1832
- tool,
1833
- input: request.input ?? {},
1834
- summary: askSummary(tool, request.input, run2.repo)
1523
+ if (stopped) {
1524
+ stream.close();
1525
+ return;
1835
1526
  }
1836
- ];
1527
+ live = stream;
1528
+ const reason = await stream.done;
1529
+ live = null;
1530
+ if (stopped || finishing) return;
1531
+ this.log(`watch ended thread=${threadId} reason=${reason}; resubscribing`);
1532
+ retry();
1533
+ };
1534
+ void follow();
1535
+ return () => {
1536
+ stopped = true;
1537
+ live?.close();
1538
+ };
1837
1539
  }
1838
- if (msg.type === "control_cancel_request" && typeof msg.request_id === "string") {
1839
- return [{ type: "cancel", request_id: msg.request_id }];
1540
+ readProjection(threadId) {
1541
+ return this.t3.rpc("orchestration.getThreadProjection", { threadId });
1840
1542
  }
1841
- if (msg.type === "result") {
1842
- return [
1843
- {
1844
- type: "result",
1845
- ok: msg.subtype === "success" && msg.is_error !== true,
1846
- ...typeof msg.result === "string" ? { text: msg.result } : {}
1847
- }
1848
- ];
1543
+ dispatch(command) {
1544
+ return this.t3.rpc("orchestration.dispatchCommand", command);
1849
1545
  }
1850
- return [];
1851
- }
1852
- var DEFAULT_FALLBACK_MODEL = "opus";
1853
- function claudeDialect(bin = "claude", fallback = DEFAULT_FALLBACK_MODEL) {
1854
- return {
1855
- name: "claude-code",
1856
- fallback,
1857
- aliases: ["claude-code", "claudeAgent", "claude"],
1858
- bin,
1859
- capabilities: ["view", "start", "steer", "report"],
1860
- keepsStdin: true,
1861
- args(run2, resume) {
1862
- return [
1863
- "--print",
1864
- "--verbose",
1865
- "--output-format",
1866
- "stream-json",
1867
- "--input-format",
1868
- "stream-json",
1869
- "--permission-prompt-tool",
1870
- "stdio",
1871
- "--permission-mode",
1872
- permissionMode(run2.runtime_mode),
1873
- "--add-dir",
1874
- run2.repo,
1875
- ...resume ? ["--resume", run2.session_id ?? run2.work_id] : ["--session-id", run2.session_id ?? run2.work_id],
1876
- ...run2.model ? ["--model", run2.model] : fallback ? ["--fallback-model", fallback] : []
1877
- ];
1878
- },
1879
- opening(run2, prompt) {
1880
- return line({
1881
- type: "control_request",
1882
- request_id: "cloop-init",
1883
- request: { subtype: "initialize" }
1884
- }) + line(userMessage(run2, prompt));
1885
- },
1886
- userLine(run2, text, mode) {
1887
- return line(userMessage(run2, text, mode === "steer" ? "now" : "next"));
1888
- },
1889
- answerLine(ask, text) {
1890
- const input = ask.input ?? {};
1891
- const response = ask.tool === "AskUserQuestion" ? {
1892
- behavior: "allow",
1893
- updatedInput: {
1894
- ...input,
1895
- answers: Object.fromEntries(questionsOf(input).map((q) => [q.question, text]))
1896
- }
1897
- } : isYes(text) ? { behavior: "allow", updatedInput: input } : { behavior: "deny", message: text };
1898
- return line({
1899
- type: "control_response",
1900
- response: { subtype: "success", request_id: ask.request_id, response }
1901
- });
1902
- },
1903
- parse: parseClaudeLine,
1904
- owns: (run2, command) => command.includes(basename2(bin)) && [run2.work_id, run2.session_id].some((id) => id !== null && command.includes(id)),
1905
- probe: () => probeClaude(bin)
1906
- };
1907
- }
1908
-
1909
- // src/drivers/codex.ts
1910
- import { execFile as execFile4 } from "child_process";
1911
- import { basename as basename3 } from "path";
1912
- var SANDBOX = {
1913
- "approval-required": "read-only",
1914
- "auto-accept-edits": "workspace-write",
1915
- auto: "workspace-write",
1916
- "full-access": "danger-full-access"
1917
- };
1918
- function exec2(bin, args) {
1919
- return new Promise(
1920
- (resolve3) => execFile4(
1921
- bin,
1922
- args,
1923
- { timeout: 1e4, encoding: "utf-8" },
1924
- (err, out2, errOut) => resolve3({ ok: !err, out: `${out2}${errOut}` })
1925
- )
1926
- );
1927
- }
1928
- function codexAccount(ok, out2) {
1929
- if (!ok || !/logged in/i.test(out2) || /not logged in/i.test(out2))
1930
- return { signedIn: false, account: null };
1931
- return { signedIn: true, account: /chatgpt/i.test(out2) ? "ChatGPT" : "API key" };
1932
- }
1933
- async function probeCodex(bin = "codex") {
1934
- const version = await exec2(bin, ["--version"]);
1935
- if (!version.ok) return null;
1936
- const status = await exec2(bin, ["login", "status"]);
1937
- const { signedIn, account } = codexAccount(status.ok, status.out);
1938
- return {
1939
- id: "codex",
1940
- name: "Codex",
1941
- version: version.out.trim().split(/\s+/).at(-1) ?? null,
1942
- ready: signedIn,
1943
- signedIn,
1944
- account,
1945
- defaultModel: null,
1946
- experimental: true
1546
+ sessions = {
1547
+ list: null,
1548
+ at: 0,
1549
+ refreshing: false
1947
1550
  };
1948
- }
1949
- function parseCodexLine(raw) {
1950
- let msg;
1951
- try {
1952
- msg = JSON.parse(raw);
1953
- } catch {
1954
- return [];
1955
- }
1956
- if (msg.type === "thread.started" && typeof msg.thread_id === "string")
1957
- return [{ type: "session", id: msg.thread_id }];
1958
- const item = msg.item;
1959
- if (msg.type === "item.completed" && item?.type === "agent_message" && typeof item.text === "string")
1960
- return [{ type: "text", text: item.text }];
1961
- if (msg.type === "item.started" && item?.type === "command_execution")
1962
- return [{ type: "tool", name: "Bash" }];
1963
- if (msg.type === "item.completed" && item?.type === "file_change") {
1964
- const changes = Array.isArray(item.changes) ? item.changes : [];
1965
- const path = changes[0]?.path;
1966
- return [
1967
- {
1968
- type: "tool",
1969
- name: "Edit",
1970
- ...typeof path === "string" ? { target: basename3(path) } : {}
1971
- }
1972
- ];
1551
+ /**
1552
+ * T3's client sessions, from the cache. `t3 auth session list` starts a whole
1553
+ * CLI and took 5 to 14 s on a loaded box, so status never waits on it: it
1554
+ * answers with the last list and refreshes it in the background at most
1555
+ * once per SESSIONS_TTL_MS.
1556
+ */
1557
+ listSessions() {
1558
+ const bin = this.deps.t3Bin;
1559
+ if (!bin) return null;
1560
+ const stale = Date.now() - this.sessions.at > SESSIONS_TTL_MS;
1561
+ if (stale && !this.sessions.refreshing) {
1562
+ this.sessions.refreshing = true;
1563
+ const done = (raw) => {
1564
+ try {
1565
+ if (raw !== null) this.sessions.list = JSON.parse(raw);
1566
+ } catch {
1567
+ }
1568
+ this.sessions.at = Date.now();
1569
+ this.sessions.refreshing = false;
1570
+ };
1571
+ (this.deps.execAsync ?? execFile3)(
1572
+ bin,
1573
+ ["auth", "session", "list", ...t3BaseDirArgs(), "--json"],
1574
+ {
1575
+ encoding: "utf-8",
1576
+ env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
1577
+ timeout: 3e4
1578
+ },
1579
+ (err, stdout) => done(err ? null : String(stdout))
1580
+ );
1581
+ }
1582
+ return this.sessions.list;
1973
1583
  }
1974
- if (msg.type === "turn.completed") return [{ type: "result", ok: true }];
1975
- if (msg.type === "turn.failed") {
1976
- const message = msg.error?.message;
1977
- return [
1978
- { type: "result", ok: false, ...typeof message === "string" ? { text: message } : {} }
1979
- ];
1584
+ /**
1585
+ * The branch the project's checkout is on, from origin when origin has it. A
1586
+ * local branch can lag origin by hundreds of commits on a box nobody pulls on,
1587
+ * and T3 starts the worktree from the ref exactly as given.
1588
+ */
1589
+ baseRefFor(root) {
1590
+ const git = (args) => String(
1591
+ (this.deps.exec ?? execFileSync2)("git", ["-C", root, ...args], {
1592
+ encoding: "utf-8",
1593
+ env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
1594
+ timeout: 5e3
1595
+ })
1596
+ ).trim();
1597
+ let branch;
1598
+ try {
1599
+ branch = git(["rev-parse", "--abbrev-ref", "HEAD"]);
1600
+ } catch {
1601
+ return "HEAD";
1602
+ }
1603
+ if (!branch || branch === "HEAD") return "HEAD";
1604
+ try {
1605
+ git(["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}`]);
1606
+ return `origin/${branch}`;
1607
+ } catch {
1608
+ return branch;
1609
+ }
1980
1610
  }
1981
- return [];
1982
- }
1983
- function codexDialect(bin = "codex") {
1984
- return {
1985
- name: "codex",
1986
- aliases: ["codex"],
1987
- bin,
1988
- capabilities: ["view", "start", "report"],
1989
- keepsStdin: false,
1990
- args(run2, resume) {
1991
- const model = run2.model ? ["--model", run2.model] : [];
1992
- const sandbox = SANDBOX[run2.runtime_mode ?? "auto-accept-edits"];
1993
- return resume && run2.session_id ? [
1994
- "exec",
1995
- "resume",
1996
- run2.session_id,
1997
- "--json",
1998
- "-c",
1999
- `sandbox_mode="${sandbox}"`,
2000
- ...model,
2001
- "-"
2002
- ] : ["exec", "--cd", run2.repo, "--json", "--sandbox", sandbox, ...model, "-"];
2003
- },
2004
- opening: (_run, prompt) => prompt,
2005
- parse: parseCodexLine,
2006
- // 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.
2007
- 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} `)),
2008
- probe: () => probeCodex(bin)
2009
- };
2010
- }
1611
+ };
2011
1612
 
2012
1613
  // src/runner-config.ts
2013
- import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "fs";
2014
- import { homedir as homedir3 } from "os";
2015
- import { dirname as dirname3, join as join4 } from "path";
1614
+ import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
1615
+ import { homedir as homedir2 } from "os";
1616
+ import { dirname as dirname2, join as join3 } from "path";
2016
1617
  var BOX_FILE = "box.json";
2017
1618
  function boxPath() {
2018
- return process.env.CLOOP_BOX_FILE ?? join4(homedir3(), CONFIG_DIR, BOX_FILE);
1619
+ return process.env.CLOOP_BOX_FILE ?? join3(homedir2(), CONFIG_DIR, BOX_FILE);
2019
1620
  }
2020
1621
  function isLocal(cfg) {
2021
1622
  return cfg.driver === "claude-code" || cfg.driver === "codex";
@@ -2023,7 +1624,7 @@ function isLocal(cfg) {
2023
1624
  function readRunnerConfig() {
2024
1625
  let parsed;
2025
1626
  try {
2026
- parsed = JSON.parse(readFileSync3(boxPath(), "utf-8"));
1627
+ parsed = JSON.parse(readFileSync2(boxPath(), "utf-8"));
2027
1628
  } catch {
2028
1629
  return null;
2029
1630
  }
@@ -2036,12 +1637,12 @@ function readRunnerConfig() {
2036
1637
  }
2037
1638
  function writeBoxConfig(cfg) {
2038
1639
  const path = boxPath();
2039
- mkdirSync3(dirname3(path), { recursive: true, mode: 448 });
1640
+ mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
2040
1641
  const temp = `${path}.${process.pid}.tmp`;
2041
- writeFileSync3(temp, `${JSON.stringify(cfg, null, 2)}
1642
+ writeFileSync2(temp, `${JSON.stringify(cfg, null, 2)}
2042
1643
  `, { mode: 384 });
2043
- chmodSync3(temp, 384);
2044
- renameSync3(temp, path);
1644
+ chmodSync2(temp, 384);
1645
+ renameSync2(temp, path);
2045
1646
  }
2046
1647
 
2047
1648
  // src/commands/connect.ts
@@ -2060,7 +1661,7 @@ function flags(argv, name) {
2060
1661
  }
2061
1662
  function which(bin) {
2062
1663
  try {
2063
- return execFileSync4("which", [bin], { encoding: "utf-8", env: CLEAN_ENV2 }).trim() || null;
1664
+ return execFileSync3("which", [bin], { encoding: "utf-8", env: CLEAN_ENV2 }).trim() || null;
2064
1665
  } catch {
2065
1666
  return null;
2066
1667
  }
@@ -2073,7 +1674,7 @@ async function mintSession(t3Url, opts = {}) {
2073
1674
  `T3 ${env.serverVersion} speaks orchestration protocol ${protocol}; a workstation needs ${MIN_PROTOCOL} (the V2 nightly or later).`
2074
1675
  );
2075
1676
  }
2076
- const sources = opts.sources ?? defaultT3BinSources(homedir4(), opts.stored);
1677
+ const sources = opts.sources ?? defaultT3BinSources(homedir3(), opts.stored);
2077
1678
  const t3Bin = opts.bin ?? pickT3Bin(t3Candidates(env.serverVersion, sources), env.serverVersion);
2078
1679
  if (!t3Bin) throw new Error("no t3 binary found; pass --t3-bin or set T3_BIN");
2079
1680
  const pairing = JSON.parse(
@@ -2151,7 +1752,7 @@ function boxServiceInstalled() {
2151
1752
  installedService({
2152
1753
  platform: process.platform,
2153
1754
  kind: "workstation",
2154
- home: homedir4(),
1755
+ home: homedir3(),
2155
1756
  uid: process.getuid?.() ?? 0,
2156
1757
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
2157
1758
  }).path
@@ -2171,19 +1772,19 @@ async function revokeReplaced(previous, kind, revoke, say) {
2171
1772
  function fallbackLine(reason, driver) {
2172
1773
  return `T3 Code is running but would not pair (${reason}). Connecting ${HARNESS_NAME[driver]} instead. To use T3: cloop connect --driver t3 --t3-bin <path>`;
2173
1774
  }
2174
- async function connectChosen(driver, attempt, run2) {
1775
+ async function connectChosen(driver, attempt, run) {
2175
1776
  attempt.driver = driver;
2176
- if (driver !== "t3") return run2.local(driver);
1777
+ if (driver !== "t3") return run.local(driver);
2177
1778
  try {
2178
- await run2.t3();
1779
+ await run.t3();
2179
1780
  } catch (err) {
2180
1781
  if (!(err instanceof ConnectFailure) || err.code !== "t3_pair_failed") throw err;
2181
- const local = run2.fallback();
1782
+ const local = run.fallback();
2182
1783
  if (!local) throw err;
2183
- run2.say(fallbackLine(err.message, local));
1784
+ run.say(fallbackLine(err.message, local));
2184
1785
  attempt.fellBack = true;
2185
1786
  attempt.driver = local;
2186
- await run2.local(local);
1787
+ await run.local(local);
2187
1788
  }
2188
1789
  }
2189
1790
  function systemdAssignment(assignment) {
@@ -2229,14 +1830,14 @@ function installedService(opts) {
2229
1830
  if (opts.platform === "darwin") {
2230
1831
  const label = `com.cloop.${name}`;
2231
1832
  return {
2232
- path: join5(opts.dir ?? join5(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
1833
+ path: join4(opts.dir ?? join4(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
2233
1834
  steps: [{ command: ["launchctl", "bootout", `gui/${opts.uid}/${label}`], mayFail: true }],
2234
1835
  running: ["launchctl", "print", `gui/${opts.uid}/${label}`]
2235
1836
  };
2236
1837
  }
2237
1838
  const unit = `cloop-${name}.service`;
2238
1839
  return {
2239
- path: join5(opts.dir ?? join5(opts.home, ".config", "systemd", "user"), unit),
1840
+ path: join4(opts.dir ?? join4(opts.home, ".config", "systemd", "user"), unit),
2240
1841
  steps: [{ command: ["systemctl", "--user", "disable", "--now", unit], mayFail: true }],
2241
1842
  running: ["systemctl", "--user", "is-active", "--quiet", unit]
2242
1843
  };
@@ -2250,9 +1851,9 @@ function unitFor(opts) {
2250
1851
  });
2251
1852
  if (opts.platform === "darwin") {
2252
1853
  const label = `com.cloop.${name}`;
2253
- const agents = opts.dir ?? join5(opts.home, "Library", "LaunchAgents");
2254
- const path2 = join5(agents, `${label}.plist`);
2255
- const log = join5(opts.home, "Library", "Logs", `cloop-${name}.log`);
1854
+ const agents = opts.dir ?? join4(opts.home, "Library", "LaunchAgents");
1855
+ const path2 = join4(agents, `${label}.plist`);
1856
+ const log = join4(opts.home, "Library", "Logs", `cloop-${name}.log`);
2256
1857
  const xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
2257
1858
  const contents2 = [
2258
1859
  '<?xml version="1.0" encoding="UTF-8"?>',
@@ -2289,8 +1890,8 @@ function unitFor(opts) {
2289
1890
  };
2290
1891
  }
2291
1892
  const unit = `cloop-${name}.service`;
2292
- const units = opts.dir ?? join5(opts.home, ".config", "systemd", "user");
2293
- const path = join5(units, unit);
1893
+ const units = opts.dir ?? join4(opts.home, ".config", "systemd", "user");
1894
+ const path = join4(units, unit);
2294
1895
  const contents = [
2295
1896
  "[Unit]",
2296
1897
  `Description=Cloop ${name}: answers the Cloop Agent over the mesh`,
@@ -2330,7 +1931,7 @@ function resolveRepos(paths, toplevel) {
2330
1931
  const top = toplevel(resolve2(p));
2331
1932
  if (!top)
2332
1933
  return `${p} is not a git checkout. Pass --repo <path> for each repository Cloop may work in.`;
2333
- if (!repos.some((r) => r.path === top)) repos.push({ label: basename4(top), path: top });
1934
+ if (!repos.some((r) => r.path === top)) repos.push({ label: basename3(top), path: top });
2334
1935
  }
2335
1936
  return repos;
2336
1937
  }
@@ -2338,7 +1939,7 @@ var CHECKOUT_ROOTS = ["projects", "code", "repos", "src", "Developer", "dev", "w
2338
1939
  function lastCommitAt(path) {
2339
1940
  try {
2340
1941
  return Number(
2341
- execFileSync4("git", ["-C", path, "log", "-1", "--format=%ct"], {
1942
+ execFileSync3("git", ["-C", path, "log", "-1", "--format=%ct"], {
2342
1943
  encoding: "utf-8",
2343
1944
  stdio: ["ignore", "pipe", "ignore"],
2344
1945
  timeout: 5e3
@@ -2353,13 +1954,13 @@ function findCheckouts(home, limit = 8) {
2353
1954
  for (const root of CHECKOUT_ROOTS) {
2354
1955
  let entries;
2355
1956
  try {
2356
- entries = readdirSync2(join5(home, root), { withFileTypes: true });
1957
+ entries = readdirSync2(join4(home, root), { withFileTypes: true });
2357
1958
  } catch {
2358
1959
  continue;
2359
1960
  }
2360
1961
  for (const entry of entries) {
2361
- const path = join5(home, root, entry.name);
2362
- if (!entry.isDirectory() || !existsSync2(join5(path, ".git"))) continue;
1962
+ const path = join4(home, root, entry.name);
1963
+ if (!entry.isDirectory() || !existsSync2(join4(path, ".git"))) continue;
2363
1964
  found.push({ repo: { label: entry.name, path }, at: lastCommitAt(path) });
2364
1965
  }
2365
1966
  }
@@ -2408,13 +2009,13 @@ async function reposFor(argv) {
2408
2009
  return repos;
2409
2010
  }
2410
2011
  const here = gitTop(process.cwd());
2411
- if (here) return [{ label: basename4(here), path: here }];
2412
- const home = homedir4();
2012
+ if (here) return [{ label: basename3(here), path: here }];
2013
+ const home = homedir3();
2413
2014
  const found = findCheckouts(home);
2414
2015
  const rerun = rerunCommand(argv);
2415
2016
  if (!found.length || !process.stdin.isTTY || !process.stdout.isTTY)
2416
2017
  throw new ConnectFailure("no_repo", notACheckoutLine(process.cwd(), found, home, rerun));
2417
- const prompt = createInterface2({ input: process.stdin, output: process.stdout });
2018
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
2418
2019
  const closed = () => new ConnectFailure("no_repo", `No folder chosen. Run ${rerun} --repo <path> to name one.`);
2419
2020
  try {
2420
2021
  return await askRepos(found, home, rerun, askOrClosed(prompt, closed), out);
@@ -2440,7 +2041,7 @@ function askOrClosed(prompt, closed) {
2440
2041
  }
2441
2042
  function gitTop(path) {
2442
2043
  try {
2443
- return execFileSync4("git", ["-C", path, "rev-parse", "--show-toplevel"], {
2044
+ return execFileSync3("git", ["-C", path, "rev-parse", "--show-toplevel"], {
2444
2045
  encoding: "utf-8",
2445
2046
  stdio: ["ignore", "pipe", "ignore"]
2446
2047
  }).trim();
@@ -2461,12 +2062,12 @@ function harnessLine(h) {
2461
2062
  const account = h.signedIn ? h.account ?? "signed in" : "signed out";
2462
2063
  return `${h.name}${version}, ${account}${h.experimental ? " (experimental)" : ""}`;
2463
2064
  }
2464
- async function runSteps(steps, run2 = (command) => void execFileSync4(command[0], command.slice(1), { stdio: "ignore", timeout: 15e3 }), wait = (ms) => new Promise((r) => setTimeout(r, ms))) {
2065
+ async function runSteps(steps, run = (command) => void execFileSync3(command[0], command.slice(1), { stdio: "ignore", timeout: 15e3 }), wait = (ms) => new Promise((r) => setTimeout(r, ms))) {
2465
2066
  for (const step of steps) {
2466
2067
  const tries = step.tries ?? 1;
2467
2068
  for (let attempt = 1; ; attempt++) {
2468
2069
  try {
2469
- run2(step.command);
2070
+ run(step.command);
2470
2071
  break;
2471
2072
  } catch (err) {
2472
2073
  if (step.mayFail) break;
@@ -2482,7 +2083,7 @@ async function installService(kind, argv, attempt) {
2482
2083
  return;
2483
2084
  }
2484
2085
  attempt.step = "service_write";
2485
- const npxBeside = join5(dirname4(process.execPath), "npx");
2086
+ const npxBeside = join4(dirname3(process.execPath), "npx");
2486
2087
  const program = programFor(
2487
2088
  process.argv[1] ?? "cloop",
2488
2089
  process.execPath,
@@ -2493,14 +2094,14 @@ async function installService(kind, argv, attempt) {
2493
2094
  const unit = unitFor({
2494
2095
  platform: process.platform,
2495
2096
  kind,
2496
- home: homedir4(),
2097
+ home: homedir3(),
2497
2098
  program,
2498
2099
  env: unitEnv(process.env),
2499
2100
  uid: process.getuid?.() ?? 0,
2500
2101
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
2501
2102
  });
2502
- mkdirSync4(join5(unit.path, ".."), { recursive: true });
2503
- writeFileSync4(unit.path, unit.contents);
2103
+ mkdirSync3(join4(unit.path, ".."), { recursive: true });
2104
+ writeFileSync3(unit.path, unit.contents);
2504
2105
  if (argv.includes("--no-start")) {
2505
2106
  out(
2506
2107
  ` Service: wrote ${unit.path}. Start it with: ${dim(unit.start.map((step) => step.command.join(" ")).join(" && "))}`
@@ -2529,7 +2130,7 @@ async function installService(kind, argv, attempt) {
2529
2130
  );
2530
2131
  try {
2531
2132
  out(
2532
- execFileSync4(unit.tail[0], unit.tail.slice(1), {
2133
+ execFileSync3(unit.tail[0], unit.tail.slice(1), {
2533
2134
  encoding: "utf-8",
2534
2135
  timeout: 5e3
2535
2136
  })
@@ -2578,7 +2179,11 @@ async function connectT3(argv, attempt) {
2578
2179
  });
2579
2180
  return attempt.deviceToken;
2580
2181
  },
2581
- writeBoxConfig: (cfg2) => writeBoxConfig({ ...cfg2, origin: getOrigin() })
2182
+ writeBoxConfig: (cfg2) => writeBoxConfig({
2183
+ ...cfg2,
2184
+ origin: getOrigin(),
2185
+ showOtherThreads: argv.includes("--show-other-threads")
2186
+ })
2582
2187
  });
2583
2188
  await revokeReplaced(previous, "workstation", (t) => revokeOwnDevice(getOrigin(), t), out);
2584
2189
  out(
@@ -2621,6 +2226,7 @@ async function connectLocal(driver, found, argv, attempt) {
2621
2226
  const deviceToken = await deviceLogin({ origin: getOrigin(), deviceName, device });
2622
2227
  attempt.deviceToken = deviceToken;
2623
2228
  const cfg = {
2229
+ showOtherThreads: argv.includes("--show-other-threads"),
2624
2230
  driver,
2625
2231
  environmentId: device.environmentId,
2626
2232
  label: deviceName,
@@ -2628,7 +2234,8 @@ async function connectLocal(driver, found, argv, attempt) {
2628
2234
  repos,
2629
2235
  bin,
2630
2236
  origin: getOrigin(),
2631
- ...fallbackModels ? { fallbackModels } : {}
2237
+ ...fallbackModels ? { fallbackModels } : {},
2238
+ ...driver === "claude-code" ? { askEverything: argv.includes("--ask-everything") } : {}
2632
2239
  };
2633
2240
  writeBoxConfig(cfg);
2634
2241
  await revokeReplaced(previous, "local", (t) => revokeOwnDevice(getOrigin(), t), out);
@@ -2639,6 +2246,9 @@ async function connectLocal(driver, found, argv, attempt) {
2639
2246
  `${bold("Cloop runner")} ${deviceName} is a Local runner: ${[harness, ...others].map(harnessLine).join("; ")}.`
2640
2247
  );
2641
2248
  out(` Repos: ${repos.map((r) => `${r.label} (${r.path})`).join(", ")}`);
2249
+ out(
2250
+ ` ${driver === "codex" ? "Full access: Codex always runs every Task without permission checks. --ask-everything applies to Claude Code only." : cfg.askEverything ? "Asks before actions except allowlisted reads." : "Full access: every Task runs without permission checks. Add --ask-everything to approve each step."}`
2251
+ );
2642
2252
  if (fallbackModels)
2643
2253
  out(
2644
2254
  ` Fallback model: ${fallbackModels}, when Claude Code's default model is at its limit. Change it with --fallback-model.`
@@ -2658,6 +2268,10 @@ function harnessesFound(found) {
2658
2268
  }
2659
2269
  var MODEL_LIST = /^[A-Za-z0-9][\w.:[\]-]*(,[A-Za-z0-9][\w.:[\]-]*)*$/;
2660
2270
  async function connect(argv, attempt) {
2271
+ if (argv.some((arg) => arg === "--webhook" || arg.startsWith("--webhook="))) {
2272
+ await connectWebhook(argv, attempt);
2273
+ return;
2274
+ }
2661
2275
  const forced = flag(argv, "--driver") ?? process.env.CLOOP_DRIVER;
2662
2276
  if (forced && !["t3", "claude-code", "codex"].includes(forced))
2663
2277
  throw new ConnectFailure("bad_flag", "--driver is t3, claude-code, or codex.");
@@ -2703,6 +2317,7 @@ async function connectCommand(argv) {
2703
2317
  }
2704
2318
 
2705
2319
  export {
2320
+ BoxToolError,
2706
2321
  T3Client,
2707
2322
  runBoxTool,
2708
2323
  threadsFilePath,
@@ -2712,14 +2327,16 @@ export {
2712
2327
  BoxWatch,
2713
2328
  tokenGone,
2714
2329
  revokeOwnDevice,
2715
- T3Driver,
2716
- localRunsFilePath,
2717
- LocalDriver,
2330
+ probeClaudePermissions,
2718
2331
  probeClaude,
2719
2332
  DEFAULT_FALLBACK_MODEL,
2720
2333
  claudeDialect,
2721
2334
  probeCodex,
2722
2335
  codexDialect,
2336
+ RESULT_INSTRUCTION,
2337
+ parseRunResult,
2338
+ orderThreads,
2339
+ T3Driver,
2723
2340
  boxPath,
2724
2341
  isLocal,
2725
2342
  readRunnerConfig,