@cloop/runner 0.2.1 → 0.2.2

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-M6MHMCV6.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-F36GGCXC.js";
13
20
  import {
14
21
  VERSION
15
- } from "./chunk-OKF4BDBH.js";
22
+ } from "./chunk-7BREDPJD.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([
@@ -532,751 +539,617 @@ async function revokeOwnDevice(origin, deviceToken, fetchFn = fetch) {
532
539
  }
533
540
 
534
541
  // 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
- };
542
+ import { execFile } from "child_process";
543
+ import { basename, isAbsolute, relative, resolve } from "path";
544
+ var SUBSCRIPTIONS = {
545
+ max: "Claude Max",
546
+ pro: "Claude Pro",
547
+ team: "Claude Team",
548
+ enterprise: "Claude Enterprise"
549
+ };
550
+ var YES_WORDS = /* @__PURE__ */ new Set([
551
+ "y",
552
+ "yes",
553
+ "yep",
554
+ "yeah",
555
+ "allow",
556
+ "allow it",
557
+ "ok",
558
+ "okay",
559
+ "approve",
560
+ "approved",
561
+ "go ahead",
562
+ "sure",
563
+ "do it"
564
+ ]);
565
+ function isYes(reply) {
566
+ return YES_WORDS.has(
567
+ reply.trim().toLowerCase().replace(/[.!\s]+$/, "")
568
+ );
565
569
  }
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
- }
570
+ function exec(bin, args) {
571
+ return new Promise(
572
+ (resolve3) => execFile(
573
+ bin,
574
+ args,
575
+ { timeout: 1e4, encoding: "utf-8" },
576
+ (err, out2) => resolve3(err ? null : String(out2))
577
+ )
578
+ );
573
579
  }
574
- function bundleBinaries(appDir) {
575
- let bundles;
580
+ function claudeAccount(raw) {
576
581
  try {
577
- bundles = readdirSync(appDir).filter((name) => /^T3 Code.*\.app$/.test(name));
582
+ const auth = JSON.parse(raw ?? "");
583
+ if (auth.loggedIn !== true) return { signedIn: false, account: null };
584
+ const plan = auth.subscriptionType ? SUBSCRIPTIONS[auth.subscriptionType] : void 0;
585
+ return {
586
+ signedIn: true,
587
+ account: plan ?? (auth.authMethod === "claude.ai" ? "Claude" : "API key")
588
+ };
578
589
  } catch {
579
- return [];
590
+ return { signedIn: false, account: null };
580
591
  }
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
592
  }
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)))];
593
+ function claudePermissionSupport(help) {
594
+ const choices = help?.match(/--permission-mode[\s\S]*?\(choices:([^)]*)\)/)?.[1] ?? "";
595
+ return {
596
+ autoMode: /"auto"/.test(choices),
597
+ manualMode: /"manual"/.test(choices) ? "manual" : "default"
598
+ };
599
599
  }
600
- function parseT3Version(output) {
601
- return output.trim().split(/\s+/).at(-1)?.replace(/^v/, "") || null;
600
+ async function probeClaudePermissions(bin = "claude") {
601
+ return claudePermissionSupport(await exec(bin, ["--help"]));
602
602
  }
603
- function t3Version(bin) {
604
- try {
605
- return parseT3Version(runT3(bin, ["--version"], 1e4));
606
- } catch {
607
- return null;
608
- }
603
+ async function probeClaude(bin = "claude") {
604
+ const version = (await exec(bin, ["--version"]))?.trim().split(/\s+/)[0];
605
+ if (!version) return null;
606
+ const { signedIn, account } = claudeAccount(await exec(bin, ["auth", "status", "--json"]));
607
+ return {
608
+ id: "claude-code",
609
+ name: "Claude Code",
610
+ version,
611
+ ready: signedIn,
612
+ signedIn,
613
+ account,
614
+ defaultModel: null
615
+ };
609
616
  }
610
- function pickT3Bin(candidates, serverVersion, versionOf = t3Version) {
611
- return candidates.find((bin) => versionOf(bin) === serverVersion) ?? candidates[0] ?? null;
617
+ function pathOf(input) {
618
+ const fields = input ?? {};
619
+ const path = fields.file_path ?? fields.notebook_path ?? fields.path;
620
+ return typeof path === "string" ? path : void 0;
612
621
  }
613
- function t3BaseDirArgs(env = process.env) {
614
- return env.T3CODE_HOME ? ["--base-dir", env.T3CODE_HOME] : [];
622
+ function shownPath(path, repo) {
623
+ const inside = relative(repo, resolve(repo, path));
624
+ return inside && !inside.startsWith("..") && !isAbsolute(inside) ? inside : path;
615
625
  }
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)}` : ""}`
626
+ function questionsOf(input) {
627
+ const questions = input?.questions;
628
+ return Array.isArray(questions) ? questions.filter((q) => typeof q?.question === "string") : [];
629
+ }
630
+ function cut(text, max = 160) {
631
+ const line2 = text.replace(/\s+/g, " ").trim();
632
+ return line2.length > max ? `${line2.slice(0, max - 1)}\u2026` : line2;
633
+ }
634
+ var TOOL_WORDS = {
635
+ Read: "read the file",
636
+ Write: "write the file",
637
+ Edit: "edit the file",
638
+ Glob: "find files",
639
+ Grep: "search files",
640
+ LS: "list files",
641
+ mcp__cloop__get_task: "read the Task",
642
+ mcp__cloop__get_task_context: "read the Task context",
643
+ mcp__cloop__list_tasks: "list your Tasks",
644
+ mcp__cloop__search: "search Cloop",
645
+ mcp__cloop__add_task: "add a Task",
646
+ mcp__cloop__add_task_note: "add a note to the Task",
647
+ mcp__cloop__complete_task: "complete the Task"
648
+ };
649
+ function askSummary(tool, input, repo) {
650
+ if (tool === "AskUserQuestion") return questionLine(questionsOf(input));
651
+ const fields = input ?? {};
652
+ if (tool === "Bash") {
653
+ const description = typeof fields.description === "string" ? cut(fields.description) : "run this command";
654
+ const words2 = description.replace(/[.?!]+$/, "");
655
+ const command = String(fields.command ?? "").replace(
656
+ /[\r\n\t]/g,
657
+ (c) => c === "\n" ? "\\n" : c === "\r" ? "\\r" : "\\t"
628
658
  );
659
+ const preview = command.length > 158 ? `${command.slice(0, 157)}\u2026` : command;
660
+ return `${words2.charAt(0).toLowerCase()}${words2.slice(1)}. OK?
661
+ (${preview})`;
629
662
  }
663
+ if (tool === "WebFetch" && typeof fields.url === "string") return `read ${cut(fields.url)}. OK?`;
664
+ const words = TOOL_WORDS[tool] ?? tool.replace(/^mcp__[^_]+__/, "").replace(/_/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase();
665
+ const path = pathOf(fields);
666
+ return `${words}${path ? ` ${shownPath(path, repo)}` : ""}. OK?`;
630
667
  }
631
- function whichAll(bin) {
668
+ function line(value) {
669
+ return `${JSON.stringify(value)}
670
+ `;
671
+ }
672
+ function userMessage(run, text, priority) {
673
+ return {
674
+ type: "user",
675
+ message: { role: "user", content: [{ type: "text", text }] },
676
+ parent_tool_use_id: null,
677
+ session_id: run.session_id ?? run.work_id,
678
+ ...priority ? { priority } : {}
679
+ };
680
+ }
681
+ function parseClaudeLine(raw, run) {
682
+ let msg;
632
683
  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);
684
+ msg = JSON.parse(raw);
638
685
  } catch {
639
686
  return [];
640
687
  }
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);
688
+ if (msg.type === "system" && msg.subtype === "init" && typeof msg.session_id === "string") {
689
+ return [{ type: "session", id: msg.session_id }];
658
690
  }
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");
691
+ if (msg.type === "assistant") {
692
+ const content = msg.message?.content;
693
+ if (!Array.isArray(content)) return [];
694
+ return content.flatMap((block) => {
695
+ if (block?.type === "text" && typeof block.text === "string" && block.text.trim())
696
+ return [{ type: "text", text: block.text }];
697
+ if (block?.type === "tool_use" && typeof block.name === "string" && block.name !== "AskUserQuestion") {
698
+ const path = pathOf(block.input);
699
+ const description = block.input?.description;
700
+ const summary = typeof description === "string" ? cut(description, 200) : TOOL_WORDS[block.name];
701
+ return [
702
+ {
703
+ type: "tool",
704
+ name: block.name,
705
+ ...path ? { target: basename(path) } : {},
706
+ ...summary ? { summary } : {}
707
+ }
708
+ ];
709
+ }
710
+ return [];
711
+ });
716
712
  }
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
713
+ if (msg.type === "control_request") {
714
+ const request = msg.request;
715
+ if (request?.subtype !== "can_use_tool" || typeof msg.request_id !== "string") return [];
716
+ const tool = request.tool_name ?? "a tool";
717
+ return [
718
+ {
719
+ type: "ask",
720
+ request_id: msg.request_id,
721
+ tool,
722
+ input: request.input ?? {},
723
+ summary: askSummary(tool, request.input, run.repo)
724
+ }
725
+ ];
726
+ }
727
+ if (msg.type === "control_cancel_request" && typeof msg.request_id === "string") {
728
+ return [{ type: "cancel", request_id: msg.request_id }];
729
+ }
730
+ if (msg.type === "result") {
731
+ const denied = Array.isArray(msg.permission_denials) && msg.permission_denials.length > 0;
732
+ return [
733
+ {
734
+ type: "result",
735
+ ok: !denied && msg.subtype === "success" && msg.is_error !== true,
736
+ ...denied ? {
737
+ text: `Claude Code blocked a step. ${typeof msg.result === "string" ? msg.result : "Check the run before retrying."}`
738
+ } : typeof msg.result === "string" ? { text: msg.result } : {}
739
+ }
740
+ ];
741
+ }
742
+ return [];
743
+ }
744
+ var DEFAULT_FALLBACK_MODEL = "opus";
745
+ function claudeDialect(bin = "claude", fallback = DEFAULT_FALLBACK_MODEL, askEverything = false, options = {}) {
746
+ const permission = () => askEverything ? "ask" : options.fullAccess === true ? "full" : options.autoMode === false ? "acceptEdits" : "auto";
747
+ return {
748
+ permission,
749
+ name: "claude-code",
750
+ fallback,
751
+ aliases: ["claude-code", "claudeAgent", "claude"],
752
+ bin,
753
+ capabilities: ["view", "start", "steer", "report"],
754
+ keepsStdin: true,
755
+ args(run, resume) {
756
+ return [
757
+ "--print",
758
+ "--verbose",
759
+ "--output-format",
760
+ "stream-json",
761
+ "--input-format",
762
+ "stream-json",
763
+ "--permission-prompt-tool",
764
+ "stdio",
765
+ ...permission() === "full" ? ["--dangerously-skip-permissions"] : [
766
+ "--permission-mode",
767
+ permission() === "ask" ? options.manualMode ?? "manual" : permission(),
768
+ "--allowedTools",
769
+ ...READ_TOOLS,
770
+ "--settings",
771
+ JSON.stringify(readOnlySettings(askEverything))
772
+ ],
773
+ "--add-dir",
774
+ run.repo,
775
+ ...resume ? ["--resume", run.session_id ?? run.work_id] : ["--session-id", run.session_id ?? run.work_id],
776
+ ...run.model ? ["--model", run.model] : fallback ? ["--fallback-model", fallback] : []
777
+ ];
778
+ },
779
+ opening(run, prompt) {
780
+ return line({
781
+ type: "control_request",
782
+ request_id: "cloop-init",
783
+ request: { subtype: "initialize" }
784
+ }) + line(userMessage(run, prompt));
785
+ },
786
+ userLine(run, text, mode) {
787
+ return line(userMessage(run, text, mode === "steer" ? "now" : "next"));
788
+ },
789
+ answerLine(ask, text) {
790
+ const input = ask.input ?? {};
791
+ const response = ask.tool === "AskUserQuestion" ? {
792
+ behavior: "allow",
793
+ updatedInput: {
794
+ ...input,
795
+ answers: Object.fromEntries(questionsOf(input).map((q) => [q.question, text]))
796
+ }
797
+ } : isYes(text) ? { behavior: "allow", updatedInput: input } : { behavior: "deny", message: text };
798
+ return line({
799
+ type: "control_response",
800
+ response: { subtype: "success", request_id: ask.request_id, response }
801
+ });
802
+ },
803
+ parse: parseClaudeLine,
804
+ owns: (run, command) => command.includes(basename(bin)) && [run.work_id, run.session_id].some((id) => id !== null && command.includes(id)),
805
+ probe: () => probeClaude(bin)
806
+ };
807
+ }
808
+
809
+ // src/drivers/codex.ts
810
+ import { execFile as execFile2 } from "child_process";
811
+ import { basename as basename2 } from "path";
812
+ function exec2(bin, args) {
813
+ return new Promise(
814
+ (resolve3) => execFile2(
815
+ bin,
816
+ args,
817
+ { timeout: 1e4, encoding: "utf-8" },
818
+ (err, out2, errOut) => resolve3({ ok: !err, out: `${out2}${errOut}` })
819
+ )
720
820
  );
721
- if (!found) throw new BoxToolError("no_project");
722
- return found;
723
821
  }
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"];
822
+ function codexAccount(ok, out2) {
823
+ if (!ok || !/logged in/i.test(out2) || /not logged in/i.test(out2))
824
+ return { signedIn: false, account: null };
825
+ return { signedIn: true, account: /chatgpt/i.test(out2) ? "ChatGPT" : "API key" };
728
826
  }
729
- function threadView(t) {
827
+ async function probeCodex(bin = "codex") {
828
+ const version = await exec2(bin, ["--version"]);
829
+ if (!version.ok) return null;
830
+ const status = await exec2(bin, ["login", "status"]);
831
+ const { signedIn, account } = codexAccount(status.ok, status.out);
730
832
  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
833
+ id: "codex",
834
+ name: "Codex",
835
+ version: version.out.trim().split(/\s+/).at(-1) ?? null,
836
+ ready: signedIn,
837
+ signedIn,
838
+ account,
839
+ defaultModel: null,
840
+ experimental: true
739
841
  };
740
842
  }
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;
843
+ function parseCodexLine(raw) {
844
+ let msg;
845
+ try {
846
+ msg = JSON.parse(raw);
847
+ } catch {
848
+ return [];
751
849
  }
752
- deps;
753
- name = "t3";
754
- get capabilities() {
755
- return boxCapabilities(this.deps.scope?.());
850
+ if (msg.type === "thread.started" && typeof msg.thread_id === "string")
851
+ return [{ type: "session", id: msg.thread_id }];
852
+ const item = msg.item;
853
+ if (msg.type === "item.completed" && item?.type === "agent_message" && typeof item.text === "string")
854
+ return [{ type: "text", text: item.text }];
855
+ if (msg.type === "item.started" && item?.type === "command_execution")
856
+ return [{ type: "tool", name: "Bash" }];
857
+ if (msg.type === "item.completed" && item?.type === "file_change") {
858
+ const changes = Array.isArray(item.changes) ? item.changes : [];
859
+ const path = changes[0]?.path;
860
+ return [
861
+ {
862
+ type: "tool",
863
+ name: "Edit",
864
+ ...typeof path === "string" ? { target: basename2(path) } : {}
865
+ }
866
+ ];
756
867
  }
757
- get t3() {
758
- return this.deps.client();
868
+ if (msg.type === "turn.completed") return [{ type: "result", ok: true }];
869
+ if (msg.type === "turn.failed") {
870
+ const message = msg.error?.message;
871
+ return [
872
+ { type: "result", ok: false, ...typeof message === "string" ? { text: message } : {} }
873
+ ];
759
874
  }
760
- log(line2) {
761
- this.deps.log?.(line2);
875
+ return [];
876
+ }
877
+ function codexDialect(bin = "codex", fullAccess = false) {
878
+ const permission = () => fullAccess === true ? "full" : "auto";
879
+ return {
880
+ permission,
881
+ name: "codex",
882
+ aliases: ["codex"],
883
+ bin,
884
+ capabilities: ["view", "start", "report"],
885
+ keepsStdin: false,
886
+ args(run, resume) {
887
+ const model = run.model ? ["--model", run.model] : [];
888
+ const policy = permission() === "full" ? ["--dangerously-bypass-approvals-and-sandbox"] : ["--approve-for-me", "-c", 'sandbox_mode="workspace-write"'];
889
+ return resume && run.session_id ? ["exec", ...policy, "resume", run.session_id, "--json", ...model, "-"] : ["exec", "--cd", run.repo, "--json", ...policy, ...model, "-"];
890
+ },
891
+ opening: (_run, prompt) => prompt,
892
+ parse: parseCodexLine,
893
+ // 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.
894
+ 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} `)),
895
+ probe: () => probeCodex(bin)
896
+ };
897
+ }
898
+
899
+ // src/drivers/t3.ts
900
+ import { execFile as execFile3, execFileSync as execFileSync2 } from "child_process";
901
+
902
+ // src/t3-bin.ts
903
+ import { execFileSync } from "child_process";
904
+ import { existsSync, readdirSync, statSync } from "fs";
905
+ import { join as join2 } from "path";
906
+ var CLEAN_ENV = () => ({
907
+ HOME: process.env.HOME,
908
+ USER: process.env.USER,
909
+ PATH: process.env.PATH
910
+ });
911
+ function defaultT3BinSources(home, stored) {
912
+ return {
913
+ env: process.env,
914
+ home,
915
+ appDirs: process.platform === "darwin" ? ["/Applications", join2(home, "Applications")] : [],
916
+ onPath: () => whichAll("t3"),
917
+ ...stored ? { stored } : {}
918
+ };
919
+ }
920
+ function isExecutable(path) {
921
+ try {
922
+ const s = statSync(path);
923
+ return s.isFile() && (s.mode & 73) !== 0;
924
+ } catch {
925
+ return false;
762
926
  }
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
799
- }
800
- };
927
+ }
928
+ function bundleBinaries(appDir) {
929
+ let bundles;
930
+ try {
931
+ bundles = readdirSync(appDir).filter((name) => /^T3 Code.*\.app$/.test(name));
932
+ } catch {
933
+ return [];
801
934
  }
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);
809
- 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)
815
- };
816
- }
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 };
860
- }
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" };
923
- }
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 };
935
+ return bundles.flatMap((bundle) => {
936
+ const root = join2(appDir, bundle);
932
937
  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 };
938
+ return readdirSync(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) => join2(root, rel)).filter(isExecutable);
939
+ } catch {
940
+ return [];
943
941
  }
944
- return { ok: true, was_running: true };
942
+ });
943
+ }
944
+ function t3Candidates(serverVersion, sources) {
945
+ const ordered = [
946
+ sources.env.T3_BIN,
947
+ join2(sources.home, ".t3", "runtime", "versions", serverVersion, "t3"),
948
+ ...sources.appDirs.flatMap(bundleBinaries),
949
+ ...sources.onPath(),
950
+ sources.stored
951
+ ];
952
+ return [...new Set(ordered.filter((p) => Boolean(p) && existsSync(p)))];
953
+ }
954
+ function parseT3Version(output) {
955
+ return output.trim().split(/\s+/).at(-1)?.replace(/^v/, "") || null;
956
+ }
957
+ function t3Version(bin) {
958
+ try {
959
+ return parseT3Version(runT3(bin, ["--version"], 1e4));
960
+ } catch {
961
+ return null;
945
962
  }
946
- async readThread(id) {
947
- const { status, settled, pr_url, last_assistant_text } = outcomeOf(
948
- await this.readProjection(id)
963
+ }
964
+ function pickT3Bin(candidates, serverVersion, versionOf = t3Version) {
965
+ return candidates.find((bin) => versionOf(bin) === serverVersion) ?? candidates[0] ?? null;
966
+ }
967
+ function t3BaseDirArgs(env = process.env) {
968
+ return env.T3CODE_HOME ? ["--base-dir", env.T3CODE_HOME] : [];
969
+ }
970
+ function runT3(bin, args, timeout = 15e3) {
971
+ try {
972
+ return execFileSync(bin, args, {
973
+ encoding: "utf-8",
974
+ env: CLEAN_ENV(),
975
+ timeout,
976
+ stdio: ["ignore", "pipe", "pipe"]
977
+ });
978
+ } catch (err) {
979
+ const stderr = String(err.stderr ?? "").trim().split("\n").filter((line2) => line2 && !/ExperimentalWarning|--trace-warnings/.test(line2)).at(-1);
980
+ throw new Error(
981
+ `t3 ${args.slice(0, 3).join(" ")} failed${stderr ? `: ${stderr.slice(0, 200)}` : ""}`
949
982
  );
950
- return { status, settled, pr_url, last_assistant_text };
951
- }
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
983
  }
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;
984
+ }
985
+ function whichAll(bin) {
986
+ try {
987
+ return execFileSync("which", ["-a", bin], {
988
+ encoding: "utf-8",
989
+ env: CLEAN_ENV(),
990
+ stdio: ["ignore", "pipe", "ignore"]
991
+ }).split("\n").map((line2) => line2.trim()).filter(Boolean);
992
+ } catch {
993
+ return [];
1114
994
  }
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
- }
995
+ }
996
+
997
+ // src/drivers/t3.ts
998
+ function isUnsettled(t) {
999
+ return !t.settledAt && !t.archivedAt && !isChild(t);
1000
+ }
1001
+ function isChild(t) {
1002
+ return t.creationSource === "provider" || Boolean(t.lineage?.parentThreadId);
1003
+ }
1004
+ var SESSIONS_TTL_MS = 5 * 6e4;
1005
+ var TERMINAL_RUN = /* @__PURE__ */ new Set(["completed", "interrupted", "failed", "cancelled", "rolled_back"]);
1006
+ var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master"]);
1007
+ function pendingQuestions(p) {
1008
+ const asked = /* @__PURE__ */ new Map();
1009
+ for (const item of p.turnItems ?? []) {
1010
+ if (item.type === "user_input_request" && item.requestId && item.questions?.length)
1011
+ asked.set(item.requestId, item.questions);
1141
1012
  }
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"];
1013
+ 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) ?? [] }));
1014
+ }
1015
+ function questionText(q) {
1016
+ return questionLine(q.questions);
1017
+ }
1018
+ function latestRun(runs) {
1019
+ return runs.reduce(
1020
+ (latest, r) => !latest || (r.ordinal ?? 0) >= (latest.ordinal ?? 0) ? r : latest,
1021
+ null
1022
+ );
1023
+ }
1024
+ function isTerminal(runs) {
1025
+ const run = latestRun(runs);
1026
+ return Boolean(run && TERMINAL_RUN.has(run.status));
1027
+ }
1028
+ function activeRun(runs) {
1029
+ const run = latestRun(runs);
1030
+ return run && !TERMINAL_RUN.has(run.status) ? run : null;
1031
+ }
1032
+ function steerableRun(p) {
1033
+ const run = activeRun(p.runs ?? []);
1034
+ if (!run) return null;
1035
+ const attempts = new Set((p.attempts ?? []).filter((a) => a.runId === run.id).map((a) => a.id));
1036
+ const turning = (p.providerTurns ?? []).some(
1037
+ (t) => t.status === "running" && t.runAttemptId !== null && attempts.has(t.runAttemptId)
1038
+ );
1039
+ return turning ? run : null;
1040
+ }
1041
+ var STEER_WAIT_MS = 8e3;
1042
+ var STEER_POLL_MS = 500;
1043
+ function prUrlOf(thread) {
1044
+ const branch = thread.branch ?? null;
1045
+ const linked = thread.pullRequests ?? [];
1046
+ const own = branch ? linked.filter((pr) => pr.snapshot?.headBranch === branch) : [];
1047
+ const fromLinked = (own.at(-1) ?? linked.at(-1))?.url ?? thread.linkedPullRequest?.url;
1048
+ if (fromLinked) return fromLinked;
1049
+ if (branch && !SHARED_BRANCHES.has(branch)) return thread.branchPullRequest?.url ?? null;
1050
+ return null;
1176
1051
  }
1177
- function localRunsFilePath() {
1178
- return process.env.CLOOP_LOCAL_RUNS_FILE ?? join3(homedir2(), CONFIG_DIR, "local-runs.json");
1052
+ function outcomeOf(p) {
1053
+ const run = latestRun(p.runs ?? []);
1054
+ const status = run?.status ?? "pending";
1055
+ const settled = TERMINAL_RUN.has(status) || Boolean(p.thread.settledAt);
1056
+ const text = (p.messages ?? []).filter((m) => m.role === "assistant" && m.text).at(-1)?.text?.trim();
1057
+ return {
1058
+ status,
1059
+ settled,
1060
+ kind: settled ? status === "completed" || !run ? "settled" : "failed" : null,
1061
+ pr_url: prUrlOf(p.thread),
1062
+ last_assistant_text: text ? text.slice(0, 300) : null
1063
+ };
1179
1064
  }
1180
- function pickRepo(repos, repository) {
1065
+ function pickProject(projects, repository) {
1066
+ const only = projects.length === 1 ? projects[0] : void 0;
1181
1067
  if (!repository) {
1182
- if (repos.length === 1 && repos[0]) return repos[0];
1068
+ if (only) return only;
1183
1069
  throw new BoxToolError("no_project");
1184
1070
  }
1185
- const want = repository.toLowerCase().split("/").at(-1) ?? "";
1186
- const found = repos.find(
1187
- (r) => r.label.toLowerCase() === want || basename(r.path).toLowerCase() === want
1071
+ const want = repository.toLowerCase();
1072
+ const found = projects.find(
1073
+ (p) => p.title.toLowerCase() === want || p.workspaceRoot.split("/").at(-1)?.toLowerCase() === want || p.repositoryIdentity?.displayName?.toLowerCase() === want
1188
1074
  );
1189
1075
  if (!found) throw new BoxToolError("no_project");
1190
1076
  return found;
1191
1077
  }
1192
- function prUrlIn(text) {
1193
- return text?.match(PR_URL)?.at(-1) ?? null;
1078
+ var SHELL_HEADERS = { "x-t3-orchestration-protocol": "2" };
1079
+ function boxCapabilities(scope) {
1080
+ const scopes = (scope ?? "").split(/\s+/).filter(Boolean);
1081
+ return scopes.includes("orchestration:operate") ? ["view", "start", "steer"] : ["view"];
1194
1082
  }
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
- );
1083
+ function threadView(t) {
1084
+ return {
1085
+ id: t.id,
1086
+ title: t.title,
1087
+ status: t.status,
1088
+ branch: t.branch ?? null,
1089
+ source: t.creationSource ?? null,
1090
+ cloop: (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX),
1091
+ settled: Boolean(t.settledAt),
1092
+ updatedAt: t.updatedAt
1093
+ };
1204
1094
  }
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
- }
1095
+ function orderThreads(threads, limit) {
1096
+ const byRecency = (a, b) => b.updatedAt.localeCompare(a.updatedAt);
1097
+ const running = threads.filter((t) => t.status === "running").sort(byRecency);
1098
+ const rest = threads.filter((t) => t.status !== "running").sort(byRecency);
1099
+ return [...running, ...rest].slice(0, limit);
1236
1100
  }
1237
- var KEEP_MS2 = 7 * 24 * 36e5;
1238
- var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
1239
- var LocalDriver = class {
1101
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1102
+ var T3Driver = class {
1240
1103
  constructor(deps) {
1241
1104
  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
1105
  }
1246
1106
  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();
1107
+ name = "t3";
1108
+ get capabilities() {
1109
+ return boxCapabilities(this.deps.scope?.());
1110
+ }
1111
+ get t3() {
1112
+ return this.deps.client();
1259
1113
  }
1260
1114
  log(line2) {
1261
1115
  this.deps.log?.(line2);
1262
1116
  }
1263
- now() {
1264
- return this.deps.now?.() ?? Date.now();
1265
- }
1266
1117
  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);
1118
+ const [cfg, shell] = await Promise.all([
1119
+ this.t3.rpc("server.getConfig", {}),
1120
+ this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
1121
+ ]);
1122
+ const sessions = this.listSessions();
1123
+ const threads = (shell.threads ?? []).filter((t) => !isChild(t));
1124
+ const unsettled = threads.filter(isUnsettled);
1270
1125
  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),
1126
+ box: {
1127
+ label: cfg.environment.label,
1128
+ driver: "t3",
1129
+ t3Version: cfg.environment.serverVersion,
1130
+ protocol: cfg.environment.orchestrationProtocolVersion,
1131
+ hosts: (cfg.remoteOpenTargets ?? []).map((t) => t.host)
1132
+ },
1133
+ harnesses: cfg.providers.filter((p) => p.enabled).map((p) => ({
1134
+ id: p.instanceId,
1135
+ name: p.displayName ?? p.instanceId,
1136
+ version: p.version,
1137
+ ready: p.status === "ready",
1138
+ signedIn: p.auth?.status === "authenticated",
1139
+ account: p.auth?.label ?? null,
1140
+ defaultModel: p.models?.find((m) => m.isDefault)?.slug ?? null
1141
+ })),
1142
+ clients: sessions?.filter((s) => s.client?.deviceType !== "bot").map((s) => ({
1143
+ label: s.client?.label ?? "unknown",
1144
+ connected: s.connected === true,
1145
+ lastConnectedAt: s.lastConnectedAt ?? null
1146
+ })) ?? null,
1147
+ projects: (shell.projects ?? []).map((p) => p.title),
1275
1148
  threads: {
1276
1149
  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
1150
+ running: unsettled.filter((t) => t.status === "running").length,
1151
+ settled: threads.length - unsettled.length,
1152
+ cloop: unsettled.filter((t) => (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX)).length
1280
1153
  }
1281
1154
  };
1282
1155
  }
@@ -1284,738 +1157,351 @@ var LocalDriver = class {
1284
1157
  scope,
1285
1158
  limit
1286
1159
  }) {
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
- }));
1160
+ const shell = await this.t3.http("/api/orchestration/shell", SHELL_HEADERS);
1161
+ const all = (shell.threads ?? []).filter((t) => !isChild(t));
1162
+ const threads = scope === "all" ? all : all.filter(isUnsettled);
1299
1163
  return {
1300
1164
  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
1165
+ unsettled: all.filter(isUnsettled).length,
1166
+ settled: all.length - all.filter(isUnsettled).length,
1167
+ running: threads.filter((t) => t.status === "running").length,
1168
+ threads: orderThreads(threads, limit).map(threadView)
1314
1169
  };
1315
1170
  }
1171
+ /**
1172
+ * `work_id` is T3's `commandId`, so a second launch of the same work returns
1173
+ * the same thread with `resumed: true` and runs nothing twice. The worktree
1174
+ * starts from origin's copy of the branch the project's checkout is on.
1175
+ */
1316
1176
  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 };
1177
+ const known = this.deps.watched?.({ work_id: a.work_id });
1178
+ if (known) return { thread_id: known.thread_id, resumed: true };
1179
+ const [cfg, shell] = await Promise.all([
1180
+ this.t3.rpc("server.getConfig", {}),
1181
+ this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
1182
+ ]);
1183
+ const project = pickProject(shell.projects ?? [], a.repository);
1184
+ const fallback = cfg.settings?.defaultModelSelection;
1185
+ const harness = a.harness ?? fallback?.instanceId ?? "claudeAgent";
1186
+ const provider = cfg.providers.find((p) => p.instanceId === harness && p.enabled);
1187
+ if (!provider) throw new BoxToolError("harness_unavailable");
1188
+ if (provider.auth && provider.auth.status !== "authenticated")
1189
+ throw new BoxToolError("harness_signed_out");
1190
+ const model = a.model ?? (fallback?.instanceId === harness ? fallback.model : void 0) ?? provider.models?.find((m) => m.isDefault)?.slug;
1191
+ if (!model) throw new BoxToolError("harness_unavailable");
1192
+ const modelSelection = !a.model && fallback?.instanceId === harness ? fallback : { instanceId: harness, model };
1193
+ const runtimeMode = a.runtime_mode ?? cfg.settings?.defaultRuntimeMode;
1194
+ if (!runtimeMode || !RUNTIME_MODES.has(runtimeMode))
1195
+ throw new BoxToolError("runtime_mode_unknown");
1196
+ const launched = await this.t3.rpc(
1197
+ "orchestration.launchThread",
1198
+ {
1199
+ commandId: a.work_id,
1200
+ creationSource: "mcp",
1201
+ projectId: project.id,
1202
+ title: a.title,
1203
+ modelSelection,
1204
+ runtimeMode,
1205
+ interactionMode: "default",
1206
+ workspaceStrategy: {
1207
+ type: "worktree",
1208
+ baseRef: this.baseRefFor(project.workspaceRoot)
1209
+ },
1210
+ initialMessage: { text: a.prompt, attachments: [] }
1211
+ }
1212
+ );
1213
+ return { thread_id: launched.threadId, resumed: launched.resumed };
1343
1214
  }
1215
+ /**
1216
+ * Say something to a thread. While the thread waits on a question, only
1217
+ * `answer: true` sends anything: the text answers every question in the
1218
+ * newest request, because a steer does not resolve a pending question and
1219
+ * the run would wait on. Without it the call sends nothing and returns the
1220
+ * question, so the owner says which they meant. Otherwise `steer`
1221
+ * joins the running turn, waiting up to 8 s for a starting run's provider
1222
+ * turn. A run that still cannot take a steer, or `queue`, gets the text
1223
+ * after it ends; a thread with nothing running starts a new turn.
1224
+ * `command_id` is T3's commandId, so a retried call sends once.
1225
+ */
1344
1226
  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}`);
1227
+ let p = await this.readProjection(a.thread_id);
1228
+ const pending = pendingQuestions(p);
1229
+ const question = pending.at(-1);
1230
+ if (a.answer && a.question_id !== void 0 && question?.request_id !== a.question_id) {
1352
1231
  return {
1353
1232
  delivered: "question_changed",
1354
- question: ask?.summary ?? null,
1355
- question_id: ask?.request_id ?? null
1233
+ question: question ? questionText(question) : null,
1234
+ question_id: question?.request_id ?? null
1356
1235
  };
1357
1236
  }
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;
1237
+ if (question && !a.answer) {
1238
+ return {
1239
+ delivered: "question_pending",
1240
+ question: questionText(question),
1241
+ questions: pending.length
1242
+ };
1572
1243
  }
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 } : {}
1244
+ if (question) {
1245
+ const receipt2 = await this.dispatch({
1246
+ type: "runtime-request.respond",
1247
+ commandId: a.command_id,
1248
+ threadId: a.thread_id,
1249
+ requestId: question.request_id,
1250
+ answers: Object.fromEntries(question.questions.map((q) => [q.id, a.text]))
1581
1251
  });
1582
- return;
1252
+ return { sequence: receipt2.sequence, delivered: "answer", question_id: question.request_id };
1583
1253
  }
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}`
1254
+ if (a.mode === "steer") {
1255
+ for (let waited = 0; waited < STEER_WAIT_MS; waited += STEER_POLL_MS) {
1256
+ if (!activeRun(p.runs ?? []) || steerableRun(p)) break;
1257
+ await sleep(STEER_POLL_MS);
1258
+ p = await this.readProjection(a.thread_id);
1259
+ }
1260
+ }
1261
+ const steer = a.mode === "steer" ? steerableRun(p) : null;
1262
+ const active = activeRun(p.runs ?? []);
1263
+ if (!active && this.deps.watched?.({ thread_id: a.thread_id })?.settled)
1264
+ throw new BoxToolError("already_finished");
1265
+ const receipt = await this.dispatch({
1266
+ type: "message.dispatch",
1267
+ commandId: a.command_id,
1268
+ threadId: a.thread_id,
1269
+ messageId: a.command_id,
1270
+ text: a.text,
1271
+ attachments: [],
1272
+ dispatchMode: steer ? { type: "steer_active", targetRunId: steer.id } : active ? { type: "queue_after_active" } : { type: "start_immediately" },
1273
+ createdBy: "user",
1274
+ creationSource: "mcp"
1619
1275
  });
1620
- this.spawnRun(r, CONTINUE_PROMPT, true);
1621
- return true;
1276
+ return { sequence: receipt.sequence, delivered: steer ? "steer" : active ? "queue" : "start" };
1622
1277
  }
1623
1278
  /**
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.
1279
+ * Stop the running turn. A thread with nothing running answers
1280
+ * `was_running: false`, and so does a run that ended while the interrupt
1281
+ * was on its way: T3 refuses that interrupt, and the owner's ask is met.
1628
1282
  */
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() {
1283
+ async interrupt(threadId, commandId) {
1284
+ const run = activeRun((await this.readProjection(threadId)).runs ?? []);
1285
+ if (!run) return { ok: true, was_running: false };
1670
1286
  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 [];
1287
+ await this.dispatch({
1288
+ type: "run.interrupt",
1289
+ commandId,
1290
+ threadId,
1291
+ runId: run.id,
1292
+ reason: "Stopped from Cloop"
1293
+ });
1294
+ } catch (err) {
1295
+ if (activeRun((await this.readProjection(threadId)).runs ?? [])) throw err;
1296
+ return { ok: true, was_running: false };
1678
1297
  }
1298
+ return { ok: true, was_running: true };
1679
1299
  }
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);
1300
+ async readThread(id) {
1301
+ const { status, settled, pr_url, last_assistant_text } = outcomeOf(
1302
+ await this.readProjection(id)
1303
+ );
1304
+ return { status, settled, pr_url, last_assistant_text };
1687
1305
  }
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")
1306
+ /**
1307
+ * Subscribe to the thread and resubscribe whenever the stream ends. A thread
1308
+ * that settled while nobody watched shows a terminal run in its first
1309
+ * snapshot. A question is reported on every update it is still pending.
1310
+ */
1311
+ watch(threadId, onEvent) {
1312
+ let stopped = false;
1313
+ let finishing = false;
1314
+ let live = null;
1315
+ const retry = () => {
1316
+ if (stopped) return;
1317
+ const timer = setTimeout(() => void follow(), this.deps.retryMs ?? 1e4);
1318
+ timer.unref?.();
1735
1319
  };
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) } : {} }];
1320
+ const finish = async () => {
1321
+ if (stopped || finishing) return;
1322
+ finishing = true;
1323
+ let outcome;
1324
+ try {
1325
+ outcome = outcomeOf(await this.readProjection(threadId));
1326
+ const grace = this.deps.prGraceMs ?? 6e4;
1327
+ if (outcome.settled && outcome.kind === "settled" && !outcome.pr_url && grace > 0) {
1328
+ await sleep(grace);
1329
+ outcome = outcomeOf(await this.readProjection(threadId));
1330
+ }
1331
+ } catch (err) {
1332
+ this.log(
1333
+ `read failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
1334
+ );
1335
+ finishing = false;
1336
+ retry();
1337
+ return;
1338
+ }
1339
+ if (stopped) return;
1340
+ if (!outcome.settled) {
1341
+ finishing = false;
1342
+ this.log(`run continues thread=${threadId} run=${outcome.status}; watching on`);
1343
+ if (!live) void follow();
1344
+ return;
1345
+ }
1346
+ stopped = true;
1347
+ live?.close();
1348
+ const pr = outcome.pr_url ? { pr_url: outcome.pr_url } : {};
1349
+ if (outcome.kind === "failed") {
1350
+ onEvent({ kind: "failed", summary: `The run ended ${outcome.status}.`, ...pr });
1351
+ } else {
1352
+ onEvent({
1353
+ kind: "settled",
1354
+ ...outcome.last_assistant_text ? { summary: outcome.last_assistant_text } : {},
1355
+ ...pr
1356
+ });
1357
+ }
1358
+ };
1359
+ const follow = async () => {
1360
+ if (stopped || live) return;
1361
+ const runs = /* @__PURE__ */ new Map();
1362
+ const requests = /* @__PURE__ */ new Map();
1363
+ const asks = /* @__PURE__ */ new Map();
1364
+ const keepAsk = (item) => {
1365
+ if (item.type === "user_input_request" && item.requestId) asks.set(item.requestId, item);
1366
+ };
1367
+ let settledByHand = false;
1368
+ let stream;
1369
+ try {
1370
+ stream = await this.t3.stream("orchestration.subscribeThread", { threadId }, (raw) => {
1371
+ const item = raw;
1372
+ if (item.kind === "snapshot" && "projection" in item) {
1373
+ for (const r of item.projection.runs ?? []) runs.set(r.id, r);
1374
+ for (const r of item.projection.runtimeRequests ?? []) requests.set(r.id, r);
1375
+ for (const t of item.projection.turnItems ?? []) keepAsk(t);
1376
+ settledByHand ||= Boolean(item.projection.thread?.settledAt);
1377
+ } else if (item.kind === "event" && "event" in item) {
1378
+ const { type, payload } = item.event;
1379
+ if (type.startsWith("run.") && typeof payload?.id === "string") {
1380
+ runs.set(payload.id, payload);
1381
+ } else if (type === "runtime-request.updated" && typeof payload?.id === "string") {
1382
+ requests.set(payload.id, payload);
1383
+ } else if (type === "turn-item.updated" && payload) {
1384
+ keepAsk(payload);
1385
+ } else if (type.startsWith("thread.") && payload?.settledAt) {
1386
+ settledByHand = true;
1387
+ } else return;
1388
+ } else return;
1389
+ if (settledByHand || isTerminal([...runs.values()])) {
1390
+ void finish();
1391
+ return;
1392
+ }
1393
+ const pending = pendingQuestions({
1394
+ runtimeRequests: [...requests.values()],
1395
+ turnItems: [...asks.values()]
1396
+ });
1397
+ for (const q of pending) {
1398
+ onEvent({ kind: "question", question_id: q.request_id, summary: questionText(q) });
1399
+ }
1400
+ });
1401
+ } catch (err) {
1402
+ this.log(
1403
+ `watch failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
1404
+ );
1405
+ retry();
1406
+ return;
1820
1407
  }
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)
1408
+ if (stopped) {
1409
+ stream.close();
1410
+ return;
1835
1411
  }
1836
- ];
1412
+ live = stream;
1413
+ const reason = await stream.done;
1414
+ live = null;
1415
+ if (stopped || finishing) return;
1416
+ this.log(`watch ended thread=${threadId} reason=${reason}; resubscribing`);
1417
+ retry();
1418
+ };
1419
+ void follow();
1420
+ return () => {
1421
+ stopped = true;
1422
+ live?.close();
1423
+ };
1837
1424
  }
1838
- if (msg.type === "control_cancel_request" && typeof msg.request_id === "string") {
1839
- return [{ type: "cancel", request_id: msg.request_id }];
1425
+ readProjection(threadId) {
1426
+ return this.t3.rpc("orchestration.getThreadProjection", { threadId });
1840
1427
  }
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
- ];
1428
+ dispatch(command) {
1429
+ return this.t3.rpc("orchestration.dispatchCommand", command);
1849
1430
  }
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
1431
+ sessions = {
1432
+ list: null,
1433
+ at: 0,
1434
+ refreshing: false
1947
1435
  };
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
- ];
1436
+ /**
1437
+ * T3's client sessions, from the cache. `t3 auth session list` starts a whole
1438
+ * CLI and took 5 to 14 s on a loaded box, so status never waits on it: it
1439
+ * answers with the last list and refreshes it in the background at most
1440
+ * once per SESSIONS_TTL_MS.
1441
+ */
1442
+ listSessions() {
1443
+ const bin = this.deps.t3Bin;
1444
+ if (!bin) return null;
1445
+ const stale = Date.now() - this.sessions.at > SESSIONS_TTL_MS;
1446
+ if (stale && !this.sessions.refreshing) {
1447
+ this.sessions.refreshing = true;
1448
+ const done = (raw) => {
1449
+ try {
1450
+ if (raw !== null) this.sessions.list = JSON.parse(raw);
1451
+ } catch {
1452
+ }
1453
+ this.sessions.at = Date.now();
1454
+ this.sessions.refreshing = false;
1455
+ };
1456
+ (this.deps.execAsync ?? execFile3)(
1457
+ bin,
1458
+ ["auth", "session", "list", ...t3BaseDirArgs(), "--json"],
1459
+ {
1460
+ encoding: "utf-8",
1461
+ env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
1462
+ timeout: 3e4
1463
+ },
1464
+ (err, stdout) => done(err ? null : String(stdout))
1465
+ );
1466
+ }
1467
+ return this.sessions.list;
1973
1468
  }
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
- ];
1469
+ /**
1470
+ * The branch the project's checkout is on, from origin when origin has it. A
1471
+ * local branch can lag origin by hundreds of commits on a box nobody pulls on,
1472
+ * and T3 starts the worktree from the ref exactly as given.
1473
+ */
1474
+ baseRefFor(root) {
1475
+ const git = (args) => String(
1476
+ (this.deps.exec ?? execFileSync2)("git", ["-C", root, ...args], {
1477
+ encoding: "utf-8",
1478
+ env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
1479
+ timeout: 5e3
1480
+ })
1481
+ ).trim();
1482
+ let branch;
1483
+ try {
1484
+ branch = git(["rev-parse", "--abbrev-ref", "HEAD"]);
1485
+ } catch {
1486
+ return "HEAD";
1487
+ }
1488
+ if (!branch || branch === "HEAD") return "HEAD";
1489
+ try {
1490
+ git(["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}`]);
1491
+ return `origin/${branch}`;
1492
+ } catch {
1493
+ return branch;
1494
+ }
1980
1495
  }
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
- }
1496
+ };
2011
1497
 
2012
1498
  // 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";
1499
+ import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
1500
+ import { homedir as homedir2 } from "os";
1501
+ import { dirname as dirname2, join as join3 } from "path";
2016
1502
  var BOX_FILE = "box.json";
2017
1503
  function boxPath() {
2018
- return process.env.CLOOP_BOX_FILE ?? join4(homedir3(), CONFIG_DIR, BOX_FILE);
1504
+ return process.env.CLOOP_BOX_FILE ?? join3(homedir2(), CONFIG_DIR, BOX_FILE);
2019
1505
  }
2020
1506
  function isLocal(cfg) {
2021
1507
  return cfg.driver === "claude-code" || cfg.driver === "codex";
@@ -2023,7 +1509,7 @@ function isLocal(cfg) {
2023
1509
  function readRunnerConfig() {
2024
1510
  let parsed;
2025
1511
  try {
2026
- parsed = JSON.parse(readFileSync3(boxPath(), "utf-8"));
1512
+ parsed = JSON.parse(readFileSync2(boxPath(), "utf-8"));
2027
1513
  } catch {
2028
1514
  return null;
2029
1515
  }
@@ -2036,12 +1522,12 @@ function readRunnerConfig() {
2036
1522
  }
2037
1523
  function writeBoxConfig(cfg) {
2038
1524
  const path = boxPath();
2039
- mkdirSync3(dirname3(path), { recursive: true, mode: 448 });
1525
+ mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
2040
1526
  const temp = `${path}.${process.pid}.tmp`;
2041
- writeFileSync3(temp, `${JSON.stringify(cfg, null, 2)}
1527
+ writeFileSync2(temp, `${JSON.stringify(cfg, null, 2)}
2042
1528
  `, { mode: 384 });
2043
- chmodSync3(temp, 384);
2044
- renameSync3(temp, path);
1529
+ chmodSync2(temp, 384);
1530
+ renameSync2(temp, path);
2045
1531
  }
2046
1532
 
2047
1533
  // src/commands/connect.ts
@@ -2060,7 +1546,7 @@ function flags(argv, name) {
2060
1546
  }
2061
1547
  function which(bin) {
2062
1548
  try {
2063
- return execFileSync4("which", [bin], { encoding: "utf-8", env: CLEAN_ENV2 }).trim() || null;
1549
+ return execFileSync3("which", [bin], { encoding: "utf-8", env: CLEAN_ENV2 }).trim() || null;
2064
1550
  } catch {
2065
1551
  return null;
2066
1552
  }
@@ -2073,7 +1559,7 @@ async function mintSession(t3Url, opts = {}) {
2073
1559
  `T3 ${env.serverVersion} speaks orchestration protocol ${protocol}; a workstation needs ${MIN_PROTOCOL} (the V2 nightly or later).`
2074
1560
  );
2075
1561
  }
2076
- const sources = opts.sources ?? defaultT3BinSources(homedir4(), opts.stored);
1562
+ const sources = opts.sources ?? defaultT3BinSources(homedir3(), opts.stored);
2077
1563
  const t3Bin = opts.bin ?? pickT3Bin(t3Candidates(env.serverVersion, sources), env.serverVersion);
2078
1564
  if (!t3Bin) throw new Error("no t3 binary found; pass --t3-bin or set T3_BIN");
2079
1565
  const pairing = JSON.parse(
@@ -2151,7 +1637,7 @@ function boxServiceInstalled() {
2151
1637
  installedService({
2152
1638
  platform: process.platform,
2153
1639
  kind: "workstation",
2154
- home: homedir4(),
1640
+ home: homedir3(),
2155
1641
  uid: process.getuid?.() ?? 0,
2156
1642
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
2157
1643
  }).path
@@ -2171,19 +1657,19 @@ async function revokeReplaced(previous, kind, revoke, say) {
2171
1657
  function fallbackLine(reason, driver) {
2172
1658
  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
1659
  }
2174
- async function connectChosen(driver, attempt, run2) {
1660
+ async function connectChosen(driver, attempt, run) {
2175
1661
  attempt.driver = driver;
2176
- if (driver !== "t3") return run2.local(driver);
1662
+ if (driver !== "t3") return run.local(driver);
2177
1663
  try {
2178
- await run2.t3();
1664
+ await run.t3();
2179
1665
  } catch (err) {
2180
1666
  if (!(err instanceof ConnectFailure) || err.code !== "t3_pair_failed") throw err;
2181
- const local = run2.fallback();
1667
+ const local = run.fallback();
2182
1668
  if (!local) throw err;
2183
- run2.say(fallbackLine(err.message, local));
1669
+ run.say(fallbackLine(err.message, local));
2184
1670
  attempt.fellBack = true;
2185
1671
  attempt.driver = local;
2186
- await run2.local(local);
1672
+ await run.local(local);
2187
1673
  }
2188
1674
  }
2189
1675
  function systemdAssignment(assignment) {
@@ -2229,14 +1715,14 @@ function installedService(opts) {
2229
1715
  if (opts.platform === "darwin") {
2230
1716
  const label = `com.cloop.${name}`;
2231
1717
  return {
2232
- path: join5(opts.dir ?? join5(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
1718
+ path: join4(opts.dir ?? join4(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
2233
1719
  steps: [{ command: ["launchctl", "bootout", `gui/${opts.uid}/${label}`], mayFail: true }],
2234
1720
  running: ["launchctl", "print", `gui/${opts.uid}/${label}`]
2235
1721
  };
2236
1722
  }
2237
1723
  const unit = `cloop-${name}.service`;
2238
1724
  return {
2239
- path: join5(opts.dir ?? join5(opts.home, ".config", "systemd", "user"), unit),
1725
+ path: join4(opts.dir ?? join4(opts.home, ".config", "systemd", "user"), unit),
2240
1726
  steps: [{ command: ["systemctl", "--user", "disable", "--now", unit], mayFail: true }],
2241
1727
  running: ["systemctl", "--user", "is-active", "--quiet", unit]
2242
1728
  };
@@ -2250,9 +1736,9 @@ function unitFor(opts) {
2250
1736
  });
2251
1737
  if (opts.platform === "darwin") {
2252
1738
  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`);
1739
+ const agents = opts.dir ?? join4(opts.home, "Library", "LaunchAgents");
1740
+ const path2 = join4(agents, `${label}.plist`);
1741
+ const log = join4(opts.home, "Library", "Logs", `cloop-${name}.log`);
2256
1742
  const xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
2257
1743
  const contents2 = [
2258
1744
  '<?xml version="1.0" encoding="UTF-8"?>',
@@ -2289,8 +1775,8 @@ function unitFor(opts) {
2289
1775
  };
2290
1776
  }
2291
1777
  const unit = `cloop-${name}.service`;
2292
- const units = opts.dir ?? join5(opts.home, ".config", "systemd", "user");
2293
- const path = join5(units, unit);
1778
+ const units = opts.dir ?? join4(opts.home, ".config", "systemd", "user");
1779
+ const path = join4(units, unit);
2294
1780
  const contents = [
2295
1781
  "[Unit]",
2296
1782
  `Description=Cloop ${name}: answers the Cloop Agent over the mesh`,
@@ -2330,7 +1816,7 @@ function resolveRepos(paths, toplevel) {
2330
1816
  const top = toplevel(resolve2(p));
2331
1817
  if (!top)
2332
1818
  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 });
1819
+ if (!repos.some((r) => r.path === top)) repos.push({ label: basename3(top), path: top });
2334
1820
  }
2335
1821
  return repos;
2336
1822
  }
@@ -2338,7 +1824,7 @@ var CHECKOUT_ROOTS = ["projects", "code", "repos", "src", "Developer", "dev", "w
2338
1824
  function lastCommitAt(path) {
2339
1825
  try {
2340
1826
  return Number(
2341
- execFileSync4("git", ["-C", path, "log", "-1", "--format=%ct"], {
1827
+ execFileSync3("git", ["-C", path, "log", "-1", "--format=%ct"], {
2342
1828
  encoding: "utf-8",
2343
1829
  stdio: ["ignore", "pipe", "ignore"],
2344
1830
  timeout: 5e3
@@ -2353,13 +1839,13 @@ function findCheckouts(home, limit = 8) {
2353
1839
  for (const root of CHECKOUT_ROOTS) {
2354
1840
  let entries;
2355
1841
  try {
2356
- entries = readdirSync2(join5(home, root), { withFileTypes: true });
1842
+ entries = readdirSync2(join4(home, root), { withFileTypes: true });
2357
1843
  } catch {
2358
1844
  continue;
2359
1845
  }
2360
1846
  for (const entry of entries) {
2361
- const path = join5(home, root, entry.name);
2362
- if (!entry.isDirectory() || !existsSync2(join5(path, ".git"))) continue;
1847
+ const path = join4(home, root, entry.name);
1848
+ if (!entry.isDirectory() || !existsSync2(join4(path, ".git"))) continue;
2363
1849
  found.push({ repo: { label: entry.name, path }, at: lastCommitAt(path) });
2364
1850
  }
2365
1851
  }
@@ -2408,13 +1894,13 @@ async function reposFor(argv) {
2408
1894
  return repos;
2409
1895
  }
2410
1896
  const here = gitTop(process.cwd());
2411
- if (here) return [{ label: basename4(here), path: here }];
2412
- const home = homedir4();
1897
+ if (here) return [{ label: basename3(here), path: here }];
1898
+ const home = homedir3();
2413
1899
  const found = findCheckouts(home);
2414
1900
  const rerun = rerunCommand(argv);
2415
1901
  if (!found.length || !process.stdin.isTTY || !process.stdout.isTTY)
2416
1902
  throw new ConnectFailure("no_repo", notACheckoutLine(process.cwd(), found, home, rerun));
2417
- const prompt = createInterface2({ input: process.stdin, output: process.stdout });
1903
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
2418
1904
  const closed = () => new ConnectFailure("no_repo", `No folder chosen. Run ${rerun} --repo <path> to name one.`);
2419
1905
  try {
2420
1906
  return await askRepos(found, home, rerun, askOrClosed(prompt, closed), out);
@@ -2440,7 +1926,7 @@ function askOrClosed(prompt, closed) {
2440
1926
  }
2441
1927
  function gitTop(path) {
2442
1928
  try {
2443
- return execFileSync4("git", ["-C", path, "rev-parse", "--show-toplevel"], {
1929
+ return execFileSync3("git", ["-C", path, "rev-parse", "--show-toplevel"], {
2444
1930
  encoding: "utf-8",
2445
1931
  stdio: ["ignore", "pipe", "ignore"]
2446
1932
  }).trim();
@@ -2461,12 +1947,12 @@ function harnessLine(h) {
2461
1947
  const account = h.signedIn ? h.account ?? "signed in" : "signed out";
2462
1948
  return `${h.name}${version}, ${account}${h.experimental ? " (experimental)" : ""}`;
2463
1949
  }
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))) {
1950
+ 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
1951
  for (const step of steps) {
2466
1952
  const tries = step.tries ?? 1;
2467
1953
  for (let attempt = 1; ; attempt++) {
2468
1954
  try {
2469
- run2(step.command);
1955
+ run(step.command);
2470
1956
  break;
2471
1957
  } catch (err) {
2472
1958
  if (step.mayFail) break;
@@ -2482,7 +1968,7 @@ async function installService(kind, argv, attempt) {
2482
1968
  return;
2483
1969
  }
2484
1970
  attempt.step = "service_write";
2485
- const npxBeside = join5(dirname4(process.execPath), "npx");
1971
+ const npxBeside = join4(dirname3(process.execPath), "npx");
2486
1972
  const program = programFor(
2487
1973
  process.argv[1] ?? "cloop",
2488
1974
  process.execPath,
@@ -2493,14 +1979,14 @@ async function installService(kind, argv, attempt) {
2493
1979
  const unit = unitFor({
2494
1980
  platform: process.platform,
2495
1981
  kind,
2496
- home: homedir4(),
1982
+ home: homedir3(),
2497
1983
  program,
2498
1984
  env: unitEnv(process.env),
2499
1985
  uid: process.getuid?.() ?? 0,
2500
1986
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
2501
1987
  });
2502
- mkdirSync4(join5(unit.path, ".."), { recursive: true });
2503
- writeFileSync4(unit.path, unit.contents);
1988
+ mkdirSync3(join4(unit.path, ".."), { recursive: true });
1989
+ writeFileSync3(unit.path, unit.contents);
2504
1990
  if (argv.includes("--no-start")) {
2505
1991
  out(
2506
1992
  ` Service: wrote ${unit.path}. Start it with: ${dim(unit.start.map((step) => step.command.join(" ")).join(" && "))}`
@@ -2529,7 +2015,7 @@ async function installService(kind, argv, attempt) {
2529
2015
  );
2530
2016
  try {
2531
2017
  out(
2532
- execFileSync4(unit.tail[0], unit.tail.slice(1), {
2018
+ execFileSync3(unit.tail[0], unit.tail.slice(1), {
2533
2019
  encoding: "utf-8",
2534
2020
  timeout: 5e3
2535
2021
  })
@@ -2627,8 +2113,10 @@ async function connectLocal(driver, found, argv, attempt) {
2627
2113
  deviceToken,
2628
2114
  repos,
2629
2115
  bin,
2116
+ fullAccess: argv.includes("--full-access"),
2630
2117
  origin: getOrigin(),
2631
- ...fallbackModels ? { fallbackModels } : {}
2118
+ ...fallbackModels ? { fallbackModels } : {},
2119
+ ...driver === "claude-code" ? { askEverything: argv.includes("--ask-everything") } : {}
2632
2120
  };
2633
2121
  writeBoxConfig(cfg);
2634
2122
  await revokeReplaced(previous, "local", (t) => revokeOwnDevice(getOrigin(), t), out);
@@ -2639,6 +2127,14 @@ async function connectLocal(driver, found, argv, attempt) {
2639
2127
  `${bold("Cloop runner")} ${deviceName} is a Local runner: ${[harness, ...others].map(harnessLine).join("; ")}.`
2640
2128
  );
2641
2129
  out(` Repos: ${repos.map((r) => `${r.label} (${r.path})`).join(", ")}`);
2130
+ const support = driver === "claude-code" ? await probeClaudePermissions(bin) : null;
2131
+ out(
2132
+ ` ${cfg.askEverything ? "Asks before actions except allowlisted reads." : cfg.fullAccess ? "Full access: every Task runs without permission checks, including Tasks made from email or other people." : "Runs in auto mode: it asks before risky steps."}`
2133
+ );
2134
+ if (support && !support.autoMode)
2135
+ out(" Auto mode is unavailable. Uses acceptEdits with the read allowlist.");
2136
+ if (driver === "codex")
2137
+ out(" Codex uses sandboxed automatic review; it cannot send owner approval questions.");
2642
2138
  if (fallbackModels)
2643
2139
  out(
2644
2140
  ` Fallback model: ${fallbackModels}, when Claude Code's default model is at its limit. Change it with --fallback-model.`
@@ -2658,6 +2154,10 @@ function harnessesFound(found) {
2658
2154
  }
2659
2155
  var MODEL_LIST = /^[A-Za-z0-9][\w.:[\]-]*(,[A-Za-z0-9][\w.:[\]-]*)*$/;
2660
2156
  async function connect(argv, attempt) {
2157
+ if (argv.some((arg) => arg === "--webhook" || arg.startsWith("--webhook="))) {
2158
+ await connectWebhook(argv, attempt);
2159
+ return;
2160
+ }
2661
2161
  const forced = flag(argv, "--driver") ?? process.env.CLOOP_DRIVER;
2662
2162
  if (forced && !["t3", "claude-code", "codex"].includes(forced))
2663
2163
  throw new ConnectFailure("bad_flag", "--driver is t3, claude-code, or codex.");
@@ -2703,6 +2203,7 @@ async function connectCommand(argv) {
2703
2203
  }
2704
2204
 
2705
2205
  export {
2206
+ BoxToolError,
2706
2207
  T3Client,
2707
2208
  runBoxTool,
2708
2209
  threadsFilePath,
@@ -2712,14 +2213,14 @@ export {
2712
2213
  BoxWatch,
2713
2214
  tokenGone,
2714
2215
  revokeOwnDevice,
2715
- T3Driver,
2716
- localRunsFilePath,
2717
- LocalDriver,
2216
+ probeClaudePermissions,
2718
2217
  probeClaude,
2719
2218
  DEFAULT_FALLBACK_MODEL,
2720
2219
  claudeDialect,
2721
2220
  probeCodex,
2722
2221
  codexDialect,
2222
+ orderThreads,
2223
+ T3Driver,
2723
2224
  boxPath,
2724
2225
  isLocal,
2725
2226
  readRunnerConfig,