@cloop/runner 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,19 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ BoxToolError,
4
+ CLOOP_THREAD_PREFIX,
5
+ RUNTIME_MODES,
6
+ T3Driver,
7
+ defaultT3BinSources,
8
+ isLocal,
9
+ pickT3Bin,
10
+ questionLine,
11
+ readRunnerConfig,
12
+ runT3,
13
+ t3BaseDirArgs,
14
+ t3Candidates,
15
+ writeBoxConfig
16
+ } from "./chunk-M6U2YVEB.js";
2
17
  import {
3
18
  getMachine,
4
19
  shortMachineName
@@ -9,17 +24,17 @@ import {
9
24
  } from "./chunk-R3CLO2FB.js";
10
25
  import {
11
26
  connectWebhook
12
- } from "./chunk-M6MHMCV6.js";
27
+ } from "./chunk-KHYA7GEH.js";
13
28
  import {
14
29
  ConnectFailure,
15
30
  connectReport,
16
31
  deviceLogin,
17
32
  newAttempt,
18
33
  sendConnectReport
19
- } from "./chunk-F36GGCXC.js";
34
+ } from "./chunk-ZDUKQWKA.js";
20
35
  import {
21
36
  VERSION
22
- } from "./chunk-7BREDPJD.js";
37
+ } from "./chunk-PBOQMFNN.js";
23
38
  import {
24
39
  CONFIG_DIR,
25
40
  STAGING_ORIGIN,
@@ -27,35 +42,13 @@ import {
27
42
  } from "./chunk-3DIGCVL4.js";
28
43
 
29
44
  // src/commands/connect.ts
30
- import { execFileSync as execFileSync3 } from "child_process";
45
+ import { execFileSync } from "child_process";
31
46
  import { randomUUID as randomUUID2 } from "crypto";
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";
47
+ import { existsSync, mkdirSync as mkdirSync2, readdirSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
48
+ import { homedir as homedir2 } from "os";
49
+ import { basename as basename3, dirname as dirname2, join as join2, resolve as resolve2 } from "path";
35
50
  import { createInterface } from "readline/promises";
36
51
 
37
- // src/drivers/driver.ts
38
- var RUNTIME_MODES = /* @__PURE__ */ new Set([
39
- "approval-required",
40
- "auto-accept-edits",
41
- "auto",
42
- "full-access"
43
- ]);
44
- var BoxToolError = class extends Error {
45
- constructor(code) {
46
- super(code);
47
- this.code = code;
48
- this.name = "BoxToolError";
49
- }
50
- code;
51
- };
52
- var CLOOP_THREAD_PREFIX = "cloop:";
53
- function questionLine(questions) {
54
- return questions.map(
55
- (x) => x.options?.length ? `${x.question} (${x.options.map((o) => o.label).join(", ")})` : x.question
56
- ).join(" ").slice(0, 500);
57
- }
58
-
59
52
  // src/t3.ts
60
53
  var T3_SCOPE = "orchestration:read orchestration:operate";
61
54
  var MIN_PROTOCOL = 2;
@@ -271,6 +264,7 @@ function parseSendArgs(args) {
271
264
  mode,
272
265
  command_id: parseCommandId(args),
273
266
  answer: args.answer === true,
267
+ ...args.resume === true ? { resume: true } : {},
274
268
  ...question !== void 0 ? { question_id: question } : {}
275
269
  };
276
270
  }
@@ -287,7 +281,12 @@ var BOX_TOOLS = {
287
281
  onLaunch?.(a.work_id, launched.thread_id);
288
282
  return launched;
289
283
  },
290
- "thread.send": ({ driver }, args) => driver.send(parseSendArgs(args)),
284
+ async "thread.send"({ driver, onResume }, args) {
285
+ const parsed = parseSendArgs(args);
286
+ const result = await driver.send(parsed);
287
+ if (parsed.resume) onResume?.(parsed.thread_id);
288
+ return result;
289
+ },
291
290
  "thread.interrupt": ({ driver }, args) => driver.interrupt(parseThreadId(args), parseCommandId(args))
292
291
  };
293
292
  function classifyError(err, driver = "t3") {
@@ -413,6 +412,15 @@ var BoxWatch = class {
413
412
  this.deps.log(`launch work=${workId} thread=${threadId}`);
414
413
  this.watch(entry);
415
414
  }
415
+ resume(threadId) {
416
+ const entry = this.entries.find((e) => e.thread_id === threadId);
417
+ if (!entry?.settled_at) return;
418
+ entry.settled_at = void 0;
419
+ entry.event = void 0;
420
+ entry.sent_at = void 0;
421
+ this.save();
422
+ this.watch(entry);
423
+ }
416
424
  /** On every socket open and on a timer: send every event the mesh has not acked. */
417
425
  flush() {
418
426
  for (const e of this.entries) {
@@ -463,6 +471,7 @@ var BoxWatch = class {
463
471
  kind,
464
472
  ...event.kind === "question" ? { question_id: event.question_id } : {},
465
473
  ...summary ? { summary: summary.slice(0, 500) } : {},
474
+ ..."result" in event && event.result ? { result: event.result } : {},
466
475
  ..."pr_url" in event && event.pr_url ? { pr_url: event.pr_url } : {},
467
476
  ..."error" in event && event.error ? { error: event.error } : {},
468
477
  at: new Date(this.now()).toISOString()
@@ -592,10 +601,7 @@ function claudeAccount(raw) {
592
601
  }
593
602
  function claudePermissionSupport(help) {
594
603
  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
- };
604
+ return { manualMode: /"manual"/.test(choices) ? "manual" : "default" };
599
605
  }
600
606
  async function probeClaudePermissions(bin = "claude") {
601
607
  return claudePermissionSupport(await exec(bin, ["--help"]));
@@ -646,6 +652,34 @@ var TOOL_WORDS = {
646
652
  mcp__cloop__add_task_note: "add a note to the Task",
647
653
  mcp__cloop__complete_task: "complete the Task"
648
654
  };
655
+ function toolDetail(tool, input, repo) {
656
+ const fields = input ?? {};
657
+ const text = (key) => typeof fields[key] === "string" ? fields[key] : void 0;
658
+ const path = pathOf(fields);
659
+ switch (tool) {
660
+ case "Bash": {
661
+ const command = text("command");
662
+ if (!command) return text("description");
663
+ const lines = command.trim().split(/\r?\n/);
664
+ return cut(`${lines[0]}${lines.length > 1 ? " \u2026" : ""}`, 300);
665
+ }
666
+ case "Grep":
667
+ return [text("pattern"), path ? `in ${shownPath(path, repo)}` : null].filter(Boolean).join(" ");
668
+ case "Glob":
669
+ return text("pattern");
670
+ case "WebFetch":
671
+ return text("url");
672
+ case "WebSearch":
673
+ case "ToolSearch":
674
+ return text("query");
675
+ case "Skill":
676
+ return text("skill");
677
+ default:
678
+ if (path) return shownPath(path, repo);
679
+ if (tool.startsWith("mcp__")) return void 0;
680
+ return text("description");
681
+ }
682
+ }
649
683
  function askSummary(tool, input, repo) {
650
684
  if (tool === "AskUserQuestion") return questionLine(questionsOf(input));
651
685
  const fields = input ?? {};
@@ -698,12 +732,14 @@ function parseClaudeLine(raw, run) {
698
732
  const path = pathOf(block.input);
699
733
  const description = block.input?.description;
700
734
  const summary = typeof description === "string" ? cut(description, 200) : TOOL_WORDS[block.name];
735
+ const detail = toolDetail(block.name, block.input, run.repo);
701
736
  return [
702
737
  {
703
738
  type: "tool",
704
739
  name: block.name,
705
740
  ...path ? { target: basename(path) } : {},
706
- ...summary ? { summary } : {}
741
+ ...summary ? { summary } : {},
742
+ ...detail ? { detail } : {}
707
743
  }
708
744
  ];
709
745
  }
@@ -743,7 +779,7 @@ function parseClaudeLine(raw, run) {
743
779
  }
744
780
  var DEFAULT_FALLBACK_MODEL = "opus";
745
781
  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";
782
+ const permission = () => askEverything ? "ask" : "full";
747
783
  return {
748
784
  permission,
749
785
  name: "claude-code",
@@ -764,7 +800,7 @@ function claudeDialect(bin = "claude", fallback = DEFAULT_FALLBACK_MODEL, askEve
764
800
  "stdio",
765
801
  ...permission() === "full" ? ["--dangerously-skip-permissions"] : [
766
802
  "--permission-mode",
767
- permission() === "ask" ? options.manualMode ?? "manual" : permission(),
803
+ options.manualMode ?? "manual",
768
804
  "--allowedTools",
769
805
  ...READ_TOOLS,
770
806
  "--settings",
@@ -853,7 +889,13 @@ function parseCodexLine(raw) {
853
889
  if (msg.type === "item.completed" && item?.type === "agent_message" && typeof item.text === "string")
854
890
  return [{ type: "text", text: item.text }];
855
891
  if (msg.type === "item.started" && item?.type === "command_execution")
856
- return [{ type: "tool", name: "Bash" }];
892
+ return [
893
+ {
894
+ type: "tool",
895
+ name: "Bash",
896
+ ...typeof item.command === "string" ? { detail: item.command.trim().split(/\r?\n/)[0]?.slice(0, 300) } : {}
897
+ }
898
+ ];
857
899
  if (msg.type === "item.completed" && item?.type === "file_change") {
858
900
  const changes = Array.isArray(item.changes) ? item.changes : [];
859
901
  const path = changes[0]?.path;
@@ -874,8 +916,8 @@ function parseCodexLine(raw) {
874
916
  }
875
917
  return [];
876
918
  }
877
- function codexDialect(bin = "codex", fullAccess = false) {
878
- const permission = () => fullAccess === true ? "full" : "auto";
919
+ function codexDialect(bin = "codex") {
920
+ const permission = () => "full";
879
921
  return {
880
922
  permission,
881
923
  name: "codex",
@@ -885,7 +927,7 @@ function codexDialect(bin = "codex", fullAccess = false) {
885
927
  keepsStdin: false,
886
928
  args(run, resume) {
887
929
  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"'];
930
+ const policy = ["--dangerously-bypass-approvals-and-sandbox"];
889
931
  return resume && run.session_id ? ["exec", ...policy, "resume", run.session_id, "--json", ...model, "-"] : ["exec", "--cd", run.repo, "--json", ...policy, ...model, "-"];
890
932
  },
891
933
  opening: (_run, prompt) => prompt,
@@ -896,643 +938,9 @@ function codexDialect(bin = "codex", fullAccess = false) {
896
938
  };
897
939
  }
898
940
 
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;
926
- }
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 [];
934
- }
935
- return bundles.flatMap((bundle) => {
936
- const root = join2(appDir, bundle);
937
- try {
938
- return readdirSync(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) => join2(root, rel)).filter(isExecutable);
939
- } catch {
940
- return [];
941
- }
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;
962
- }
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)}` : ""}`
982
- );
983
- }
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 [];
994
- }
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);
1012
- }
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;
1051
- }
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
- };
1064
- }
1065
- function pickProject(projects, repository) {
1066
- const only = projects.length === 1 ? projects[0] : void 0;
1067
- if (!repository) {
1068
- if (only) return only;
1069
- throw new BoxToolError("no_project");
1070
- }
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
1074
- );
1075
- if (!found) throw new BoxToolError("no_project");
1076
- return found;
1077
- }
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"];
1082
- }
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
- };
1094
- }
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);
1100
- }
1101
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1102
- var T3Driver = class {
1103
- constructor(deps) {
1104
- this.deps = deps;
1105
- }
1106
- deps;
1107
- name = "t3";
1108
- get capabilities() {
1109
- return boxCapabilities(this.deps.scope?.());
1110
- }
1111
- get t3() {
1112
- return this.deps.client();
1113
- }
1114
- log(line2) {
1115
- this.deps.log?.(line2);
1116
- }
1117
- async status() {
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);
1125
- return {
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),
1148
- threads: {
1149
- unsettled: 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
1153
- }
1154
- };
1155
- }
1156
- async listThreads({
1157
- scope,
1158
- limit
1159
- }) {
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);
1163
- return {
1164
- scope,
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)
1169
- };
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
- */
1176
- async launch(a) {
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 };
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
- */
1226
- async send(a) {
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) {
1231
- return {
1232
- delivered: "question_changed",
1233
- question: question ? questionText(question) : null,
1234
- question_id: question?.request_id ?? null
1235
- };
1236
- }
1237
- if (question && !a.answer) {
1238
- return {
1239
- delivered: "question_pending",
1240
- question: questionText(question),
1241
- questions: pending.length
1242
- };
1243
- }
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]))
1251
- });
1252
- return { sequence: receipt2.sequence, delivered: "answer", question_id: question.request_id };
1253
- }
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"
1275
- });
1276
- return { sequence: receipt.sequence, delivered: steer ? "steer" : active ? "queue" : "start" };
1277
- }
1278
- /**
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.
1282
- */
1283
- async interrupt(threadId, commandId) {
1284
- const run = activeRun((await this.readProjection(threadId)).runs ?? []);
1285
- if (!run) return { ok: true, was_running: false };
1286
- try {
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 };
1297
- }
1298
- return { ok: true, was_running: true };
1299
- }
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 };
1305
- }
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?.();
1319
- };
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;
1407
- }
1408
- if (stopped) {
1409
- stream.close();
1410
- return;
1411
- }
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
- };
1424
- }
1425
- readProjection(threadId) {
1426
- return this.t3.rpc("orchestration.getThreadProjection", { threadId });
1427
- }
1428
- dispatch(command) {
1429
- return this.t3.rpc("orchestration.dispatchCommand", command);
1430
- }
1431
- sessions = {
1432
- list: null,
1433
- at: 0,
1434
- refreshing: false
1435
- };
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;
1468
- }
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
- }
1495
- }
1496
- };
1497
-
1498
- // src/runner-config.ts
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";
1502
- var BOX_FILE = "box.json";
1503
- function boxPath() {
1504
- return process.env.CLOOP_BOX_FILE ?? join3(homedir2(), CONFIG_DIR, BOX_FILE);
1505
- }
1506
- function isLocal(cfg) {
1507
- return cfg.driver === "claude-code" || cfg.driver === "codex";
1508
- }
1509
- function readRunnerConfig() {
1510
- let parsed;
1511
- try {
1512
- parsed = JSON.parse(readFileSync2(boxPath(), "utf-8"));
1513
- } catch {
1514
- return null;
1515
- }
1516
- if (parsed.driver === "claude-code" || parsed.driver === "codex") {
1517
- const ok = typeof parsed.deviceToken === "string" && typeof parsed.environmentId === "string" && typeof parsed.bin === "string" && Array.isArray(parsed.repos);
1518
- return ok ? parsed : null;
1519
- }
1520
- if (typeof parsed.t3Url !== "string" || typeof parsed.token !== "string") return null;
1521
- return parsed;
1522
- }
1523
- function writeBoxConfig(cfg) {
1524
- const path = boxPath();
1525
- mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
1526
- const temp = `${path}.${process.pid}.tmp`;
1527
- writeFileSync2(temp, `${JSON.stringify(cfg, null, 2)}
1528
- `, { mode: 384 });
1529
- chmodSync2(temp, 384);
1530
- renameSync2(temp, path);
1531
- }
1532
-
1533
941
  // src/commands/connect.ts
1534
942
  var DEFAULT_T3_URL = "http://127.0.0.1:3773";
1535
- var CLEAN_ENV2 = { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH };
943
+ var CLEAN_ENV = { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH };
1536
944
  var out = (line2) => console.log(line2);
1537
945
  var bold = (s) => `\x1B[1m${s}\x1B[0m`;
1538
946
  var dim = (s) => `\x1B[2m${s}\x1B[0m`;
@@ -1546,7 +954,7 @@ function flags(argv, name) {
1546
954
  }
1547
955
  function which(bin) {
1548
956
  try {
1549
- return execFileSync3("which", [bin], { encoding: "utf-8", env: CLEAN_ENV2 }).trim() || null;
957
+ return execFileSync("which", [bin], { encoding: "utf-8", env: CLEAN_ENV }).trim() || null;
1550
958
  } catch {
1551
959
  return null;
1552
960
  }
@@ -1559,7 +967,7 @@ async function mintSession(t3Url, opts = {}) {
1559
967
  `T3 ${env.serverVersion} speaks orchestration protocol ${protocol}; a workstation needs ${MIN_PROTOCOL} (the V2 nightly or later).`
1560
968
  );
1561
969
  }
1562
- const sources = opts.sources ?? defaultT3BinSources(homedir3(), opts.stored);
970
+ const sources = opts.sources ?? defaultT3BinSources(homedir2(), opts.stored);
1563
971
  const t3Bin = opts.bin ?? pickT3Bin(t3Candidates(env.serverVersion, sources), env.serverVersion);
1564
972
  if (!t3Bin) throw new Error("no t3 binary found; pass --t3-bin or set T3_BIN");
1565
973
  const pairing = JSON.parse(
@@ -1633,11 +1041,11 @@ function isWorkstation(previous, boxServiceInstalled2) {
1633
1041
  return boxServiceInstalled2 || Boolean(previous && !isLocal(previous));
1634
1042
  }
1635
1043
  function boxServiceInstalled() {
1636
- return existsSync2(
1044
+ return existsSync(
1637
1045
  installedService({
1638
1046
  platform: process.platform,
1639
1047
  kind: "workstation",
1640
- home: homedir3(),
1048
+ home: homedir2(),
1641
1049
  uid: process.getuid?.() ?? 0,
1642
1050
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
1643
1051
  }).path
@@ -1715,14 +1123,14 @@ function installedService(opts) {
1715
1123
  if (opts.platform === "darwin") {
1716
1124
  const label = `com.cloop.${name}`;
1717
1125
  return {
1718
- path: join4(opts.dir ?? join4(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
1126
+ path: join2(opts.dir ?? join2(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
1719
1127
  steps: [{ command: ["launchctl", "bootout", `gui/${opts.uid}/${label}`], mayFail: true }],
1720
1128
  running: ["launchctl", "print", `gui/${opts.uid}/${label}`]
1721
1129
  };
1722
1130
  }
1723
1131
  const unit = `cloop-${name}.service`;
1724
1132
  return {
1725
- path: join4(opts.dir ?? join4(opts.home, ".config", "systemd", "user"), unit),
1133
+ path: join2(opts.dir ?? join2(opts.home, ".config", "systemd", "user"), unit),
1726
1134
  steps: [{ command: ["systemctl", "--user", "disable", "--now", unit], mayFail: true }],
1727
1135
  running: ["systemctl", "--user", "is-active", "--quiet", unit]
1728
1136
  };
@@ -1736,9 +1144,9 @@ function unitFor(opts) {
1736
1144
  });
1737
1145
  if (opts.platform === "darwin") {
1738
1146
  const label = `com.cloop.${name}`;
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`);
1147
+ const agents = opts.dir ?? join2(opts.home, "Library", "LaunchAgents");
1148
+ const path2 = join2(agents, `${label}.plist`);
1149
+ const log = join2(opts.home, "Library", "Logs", `cloop-${name}.log`);
1742
1150
  const xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1743
1151
  const contents2 = [
1744
1152
  '<?xml version="1.0" encoding="UTF-8"?>',
@@ -1775,8 +1183,8 @@ function unitFor(opts) {
1775
1183
  };
1776
1184
  }
1777
1185
  const unit = `cloop-${name}.service`;
1778
- const units = opts.dir ?? join4(opts.home, ".config", "systemd", "user");
1779
- const path = join4(units, unit);
1186
+ const units = opts.dir ?? join2(opts.home, ".config", "systemd", "user");
1187
+ const path = join2(units, unit);
1780
1188
  const contents = [
1781
1189
  "[Unit]",
1782
1190
  `Description=Cloop ${name}: answers the Cloop Agent over the mesh`,
@@ -1824,7 +1232,7 @@ var CHECKOUT_ROOTS = ["projects", "code", "repos", "src", "Developer", "dev", "w
1824
1232
  function lastCommitAt(path) {
1825
1233
  try {
1826
1234
  return Number(
1827
- execFileSync3("git", ["-C", path, "log", "-1", "--format=%ct"], {
1235
+ execFileSync("git", ["-C", path, "log", "-1", "--format=%ct"], {
1828
1236
  encoding: "utf-8",
1829
1237
  stdio: ["ignore", "pipe", "ignore"],
1830
1238
  timeout: 5e3
@@ -1839,13 +1247,13 @@ function findCheckouts(home, limit = 8) {
1839
1247
  for (const root of CHECKOUT_ROOTS) {
1840
1248
  let entries;
1841
1249
  try {
1842
- entries = readdirSync2(join4(home, root), { withFileTypes: true });
1250
+ entries = readdirSync(join2(home, root), { withFileTypes: true });
1843
1251
  } catch {
1844
1252
  continue;
1845
1253
  }
1846
1254
  for (const entry of entries) {
1847
- const path = join4(home, root, entry.name);
1848
- if (!entry.isDirectory() || !existsSync2(join4(path, ".git"))) continue;
1255
+ const path = join2(home, root, entry.name);
1256
+ if (!entry.isDirectory() || !existsSync(join2(path, ".git"))) continue;
1849
1257
  found.push({ repo: { label: entry.name, path }, at: lastCommitAt(path) });
1850
1258
  }
1851
1259
  }
@@ -1895,7 +1303,7 @@ async function reposFor(argv) {
1895
1303
  }
1896
1304
  const here = gitTop(process.cwd());
1897
1305
  if (here) return [{ label: basename3(here), path: here }];
1898
- const home = homedir3();
1306
+ const home = homedir2();
1899
1307
  const found = findCheckouts(home);
1900
1308
  const rerun = rerunCommand(argv);
1901
1309
  if (!found.length || !process.stdin.isTTY || !process.stdout.isTTY)
@@ -1926,7 +1334,7 @@ function askOrClosed(prompt, closed) {
1926
1334
  }
1927
1335
  function gitTop(path) {
1928
1336
  try {
1929
- return execFileSync3("git", ["-C", path, "rev-parse", "--show-toplevel"], {
1337
+ return execFileSync("git", ["-C", path, "rev-parse", "--show-toplevel"], {
1930
1338
  encoding: "utf-8",
1931
1339
  stdio: ["ignore", "pipe", "ignore"]
1932
1340
  }).trim();
@@ -1947,7 +1355,7 @@ function harnessLine(h) {
1947
1355
  const account = h.signedIn ? h.account ?? "signed in" : "signed out";
1948
1356
  return `${h.name}${version}, ${account}${h.experimental ? " (experimental)" : ""}`;
1949
1357
  }
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))) {
1358
+ async function runSteps(steps, run = (command) => void execFileSync(command[0], command.slice(1), { stdio: "ignore", timeout: 15e3 }), wait = (ms) => new Promise((r) => setTimeout(r, ms))) {
1951
1359
  for (const step of steps) {
1952
1360
  const tries = step.tries ?? 1;
1953
1361
  for (let attempt = 1; ; attempt++) {
@@ -1968,25 +1376,25 @@ async function installService(kind, argv, attempt) {
1968
1376
  return;
1969
1377
  }
1970
1378
  attempt.step = "service_write";
1971
- const npxBeside = join4(dirname3(process.execPath), "npx");
1379
+ const npxBeside = join2(dirname2(process.execPath), "npx");
1972
1380
  const program = programFor(
1973
1381
  process.argv[1] ?? "cloop",
1974
1382
  process.execPath,
1975
- existsSync2(npxBeside) ? npxBeside : which("npx"),
1383
+ existsSync(npxBeside) ? npxBeside : which("npx"),
1976
1384
  VERSION
1977
1385
  );
1978
1386
  if (typeof program === "string") throw new ConnectFailure("npx_missing", program);
1979
1387
  const unit = unitFor({
1980
1388
  platform: process.platform,
1981
1389
  kind,
1982
- home: homedir3(),
1390
+ home: homedir2(),
1983
1391
  program,
1984
1392
  env: unitEnv(process.env),
1985
1393
  uid: process.getuid?.() ?? 0,
1986
1394
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
1987
1395
  });
1988
- mkdirSync3(join4(unit.path, ".."), { recursive: true });
1989
- writeFileSync3(unit.path, unit.contents);
1396
+ mkdirSync2(join2(unit.path, ".."), { recursive: true });
1397
+ writeFileSync2(unit.path, unit.contents);
1990
1398
  if (argv.includes("--no-start")) {
1991
1399
  out(
1992
1400
  ` Service: wrote ${unit.path}. Start it with: ${dim(unit.start.map((step) => step.command.join(" ")).join(" && "))}`
@@ -1996,7 +1404,7 @@ async function installService(kind, argv, attempt) {
1996
1404
  attempt.step = "service_start";
1997
1405
  const since = Date.now();
1998
1406
  try {
1999
- if (existsSync2(unit.retire.path)) {
1407
+ if (existsSync(unit.retire.path)) {
2000
1408
  out(` This computer is one runner, so connect stops and removes ${unit.retire.path}.`);
2001
1409
  await runSteps(unit.retire.steps);
2002
1410
  rmSync(unit.retire.path, { force: true });
@@ -2015,7 +1423,7 @@ async function installService(kind, argv, attempt) {
2015
1423
  );
2016
1424
  try {
2017
1425
  out(
2018
- execFileSync3(unit.tail[0], unit.tail.slice(1), {
1426
+ execFileSync(unit.tail[0], unit.tail.slice(1), {
2019
1427
  encoding: "utf-8",
2020
1428
  timeout: 5e3
2021
1429
  })
@@ -2064,7 +1472,11 @@ async function connectT3(argv, attempt) {
2064
1472
  });
2065
1473
  return attempt.deviceToken;
2066
1474
  },
2067
- writeBoxConfig: (cfg2) => writeBoxConfig({ ...cfg2, origin: getOrigin() })
1475
+ writeBoxConfig: (cfg2) => writeBoxConfig({
1476
+ ...cfg2,
1477
+ origin: getOrigin(),
1478
+ showOtherThreads: argv.includes("--show-other-threads")
1479
+ })
2068
1480
  });
2069
1481
  await revokeReplaced(previous, "workstation", (t) => revokeOwnDevice(getOrigin(), t), out);
2070
1482
  out(
@@ -2107,13 +1519,13 @@ async function connectLocal(driver, found, argv, attempt) {
2107
1519
  const deviceToken = await deviceLogin({ origin: getOrigin(), deviceName, device });
2108
1520
  attempt.deviceToken = deviceToken;
2109
1521
  const cfg = {
1522
+ showOtherThreads: argv.includes("--show-other-threads"),
2110
1523
  driver,
2111
1524
  environmentId: device.environmentId,
2112
1525
  label: deviceName,
2113
1526
  deviceToken,
2114
1527
  repos,
2115
1528
  bin,
2116
- fullAccess: argv.includes("--full-access"),
2117
1529
  origin: getOrigin(),
2118
1530
  ...fallbackModels ? { fallbackModels } : {},
2119
1531
  ...driver === "claude-code" ? { askEverything: argv.includes("--ask-everything") } : {}
@@ -2127,14 +1539,9 @@ async function connectLocal(driver, found, argv, attempt) {
2127
1539
  `${bold("Cloop runner")} ${deviceName} is a Local runner: ${[harness, ...others].map(harnessLine).join("; ")}.`
2128
1540
  );
2129
1541
  out(` Repos: ${repos.map((r) => `${r.label} (${r.path})`).join(", ")}`);
2130
- const support = driver === "claude-code" ? await probeClaudePermissions(bin) : null;
2131
1542
  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."}`
1543
+ ` ${driver === "codex" ? "Full access: Codex always runs every Task without permission checks. --ask-everything applies to Claude Code only." : cfg.askEverything ? "Asks before actions except allowlisted reads." : "Full access: every Task runs without permission checks. Add --ask-everything to approve each step."}`
2133
1544
  );
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.");
2138
1545
  if (fallbackModels)
2139
1546
  out(
2140
1547
  ` Fallback model: ${fallbackModels}, when Claude Code's default model is at its limit. Change it with --fallback-model.`
@@ -2203,7 +1610,6 @@ async function connectCommand(argv) {
2203
1610
  }
2204
1611
 
2205
1612
  export {
2206
- BoxToolError,
2207
1613
  T3Client,
2208
1614
  runBoxTool,
2209
1615
  threadsFilePath,
@@ -2219,12 +1625,6 @@ export {
2219
1625
  claudeDialect,
2220
1626
  probeCodex,
2221
1627
  codexDialect,
2222
- orderThreads,
2223
- T3Driver,
2224
- boxPath,
2225
- isLocal,
2226
- readRunnerConfig,
2227
- writeBoxConfig,
2228
1628
  DEFAULT_T3_URL,
2229
1629
  mintSession,
2230
1630
  connectBox,