@cloop/runner 0.2.3 → 0.2.5

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-G6JAEE2Y.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-TIXA2YXR.js";
27
+ } from "./chunk-53M5DK6D.js";
13
28
  import {
14
29
  ConnectFailure,
15
30
  connectReport,
16
31
  deviceLogin,
17
32
  newAttempt,
18
33
  sendConnectReport
19
- } from "./chunk-F4WCO6Z4.js";
34
+ } from "./chunk-4XDYJZLF.js";
20
35
  import {
21
36
  VERSION
22
- } from "./chunk-FW7MMQQV.js";
37
+ } from "./chunk-BFVL3E2C.js";
23
38
  import {
24
39
  CONFIG_DIR,
25
40
  STAGING_ORIGIN,
@@ -27,34 +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
-
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
- }
51
+ import { Writable } from "stream";
58
52
 
59
53
  // src/t3.ts
60
54
  var T3_SCOPE = "orchestration:read orchestration:operate";
@@ -75,7 +69,7 @@ async function exchangePairing(t3Url, credential, label, fetchFn = fetch) {
75
69
  client_device_type: "bot"
76
70
  });
77
71
  const res = await fetchFn(`${t3Url}/oauth/token`, { method: "POST", body: form });
78
- if (!res.ok) throw new Error(`T3 token exchange ${res.status}`);
72
+ if (!res.ok) throw new T3HttpError("token exchange", res.status);
79
73
  const token = await res.json();
80
74
  if (!sameScopes(token.scope, T3_SCOPE))
81
75
  throw new Error(`T3 granted scope "${token.scope}", wanted "${T3_SCOPE}"`);
@@ -256,8 +250,8 @@ function parseCommandId(args) {
256
250
  return id;
257
251
  }
258
252
  function parseSendArgs(args) {
259
- const text2 = typeof args.text === "string" ? args.text.trim() : "";
260
- if (!text2 || text2.length > 8e3) throw new BoxToolError("bad_args");
253
+ const text = typeof args.text === "string" ? args.text.trim() : "";
254
+ if (!text || text.length > 8e3) throw new BoxToolError("bad_args");
261
255
  const mode = args.mode ?? "steer";
262
256
  if (mode !== "steer" && mode !== "queue") throw new BoxToolError("bad_args");
263
257
  if (args.answer !== void 0 && typeof args.answer !== "boolean")
@@ -267,7 +261,7 @@ function parseSendArgs(args) {
267
261
  throw new BoxToolError("bad_args");
268
262
  return {
269
263
  thread_id: parseThreadId(args),
270
- text: text2,
264
+ text,
271
265
  mode,
272
266
  command_id: parseCommandId(args),
273
267
  answer: args.answer === true,
@@ -640,8 +634,8 @@ function questionsOf(input) {
640
634
  const questions = input?.questions;
641
635
  return Array.isArray(questions) ? questions.filter((q) => typeof q?.question === "string") : [];
642
636
  }
643
- function cut(text2, max = 160) {
644
- const line2 = text2.replace(/\s+/g, " ").trim();
637
+ function cut(text, max = 160) {
638
+ const line2 = text.replace(/\s+/g, " ").trim();
645
639
  return line2.length > max ? `${line2.slice(0, max - 1)}\u2026` : line2;
646
640
  }
647
641
  var TOOL_WORDS = {
@@ -659,6 +653,34 @@ var TOOL_WORDS = {
659
653
  mcp__cloop__add_task_note: "add a note to the Task",
660
654
  mcp__cloop__complete_task: "complete the Task"
661
655
  };
656
+ function toolDetail(tool, input, repo) {
657
+ const fields = input ?? {};
658
+ const text = (key) => typeof fields[key] === "string" ? fields[key] : void 0;
659
+ const path = pathOf(fields);
660
+ switch (tool) {
661
+ case "Bash": {
662
+ const command = text("command");
663
+ if (!command) return text("description");
664
+ const lines = command.trim().split(/\r?\n/);
665
+ return cut(`${lines[0]}${lines.length > 1 ? " \u2026" : ""}`, 300);
666
+ }
667
+ case "Grep":
668
+ return [text("pattern"), path ? `in ${shownPath(path, repo)}` : null].filter(Boolean).join(" ");
669
+ case "Glob":
670
+ return text("pattern");
671
+ case "WebFetch":
672
+ return text("url");
673
+ case "WebSearch":
674
+ case "ToolSearch":
675
+ return text("query");
676
+ case "Skill":
677
+ return text("skill");
678
+ default:
679
+ if (path) return shownPath(path, repo);
680
+ if (tool.startsWith("mcp__")) return void 0;
681
+ return text("description");
682
+ }
683
+ }
662
684
  function askSummary(tool, input, repo) {
663
685
  if (tool === "AskUserQuestion") return questionLine(questionsOf(input));
664
686
  const fields = input ?? {};
@@ -682,10 +704,10 @@ function line(value) {
682
704
  return `${JSON.stringify(value)}
683
705
  `;
684
706
  }
685
- function userMessage(run, text2, priority) {
707
+ function userMessage(run, text, priority) {
686
708
  return {
687
709
  type: "user",
688
- message: { role: "user", content: [{ type: "text", text: text2 }] },
710
+ message: { role: "user", content: [{ type: "text", text }] },
689
711
  parent_tool_use_id: null,
690
712
  session_id: run.session_id ?? run.work_id,
691
713
  ...priority ? { priority } : {}
@@ -711,12 +733,14 @@ function parseClaudeLine(raw, run) {
711
733
  const path = pathOf(block.input);
712
734
  const description = block.input?.description;
713
735
  const summary = typeof description === "string" ? cut(description, 200) : TOOL_WORDS[block.name];
736
+ const detail = toolDetail(block.name, block.input, run.repo);
714
737
  return [
715
738
  {
716
739
  type: "tool",
717
740
  name: block.name,
718
741
  ...path ? { target: basename(path) } : {},
719
- ...summary ? { summary } : {}
742
+ ...summary ? { summary } : {},
743
+ ...detail ? { detail } : {}
720
744
  }
721
745
  ];
722
746
  }
@@ -796,18 +820,18 @@ function claudeDialect(bin = "claude", fallback = DEFAULT_FALLBACK_MODEL, askEve
796
820
  request: { subtype: "initialize" }
797
821
  }) + line(userMessage(run, prompt));
798
822
  },
799
- userLine(run, text2, mode) {
800
- return line(userMessage(run, text2, mode === "steer" ? "now" : "next"));
823
+ userLine(run, text, mode) {
824
+ return line(userMessage(run, text, mode === "steer" ? "now" : "next"));
801
825
  },
802
- answerLine(ask, text2) {
826
+ answerLine(ask, text) {
803
827
  const input = ask.input ?? {};
804
828
  const response = ask.tool === "AskUserQuestion" ? {
805
829
  behavior: "allow",
806
830
  updatedInput: {
807
831
  ...input,
808
- answers: Object.fromEntries(questionsOf(input).map((q) => [q.question, text2]))
832
+ answers: Object.fromEntries(questionsOf(input).map((q) => [q.question, text]))
809
833
  }
810
- } : isYes(text2) ? { behavior: "allow", updatedInput: input } : { behavior: "deny", message: text2 };
834
+ } : isYes(text) ? { behavior: "allow", updatedInput: input } : { behavior: "deny", message: text };
811
835
  return line({
812
836
  type: "control_response",
813
837
  response: { subtype: "success", request_id: ask.request_id, response }
@@ -866,7 +890,13 @@ function parseCodexLine(raw) {
866
890
  if (msg.type === "item.completed" && item?.type === "agent_message" && typeof item.text === "string")
867
891
  return [{ type: "text", text: item.text }];
868
892
  if (msg.type === "item.started" && item?.type === "command_execution")
869
- return [{ type: "tool", name: "Bash" }];
893
+ return [
894
+ {
895
+ type: "tool",
896
+ name: "Bash",
897
+ ...typeof item.command === "string" ? { detail: item.command.trim().split(/\r?\n/)[0]?.slice(0, 300) } : {}
898
+ }
899
+ ];
870
900
  if (msg.type === "item.completed" && item?.type === "file_change") {
871
901
  const changes = Array.isArray(item.changes) ? item.changes : [];
872
902
  const path = changes[0]?.path;
@@ -909,745 +939,33 @@ function codexDialect(bin = "codex") {
909
939
  };
910
940
  }
911
941
 
912
- // src/drivers/t3.ts
913
- import { execFile as execFile3, execFileSync as execFileSync2 } from "child_process";
914
-
915
- // src/run-result.ts
916
- var RESULT_INSTRUCTION = "When you finish, end your final message with a fenced block tagged cloop-result containing JSON: summary, outputs, checks.";
917
- var text = (v, max) => typeof v === "string" && v.length <= max;
918
- var optionalText = (v, max) => v === void 0 || text(v, max);
919
- var https = (v) => {
920
- try {
921
- return typeof v === "string" && new URL(v).protocol === "https:";
922
- } catch {
923
- return false;
924
- }
925
- };
926
- function parseRunResult(message) {
927
- const block = [...(message ?? "").matchAll(/```cloop-result\s*\n([\s\S]*?)```/g)].at(-1)?.[1];
928
- if (!block) return void 0;
929
- try {
930
- const value = JSON.parse(block);
931
- if (!value || !text(value.summary, 500)) return void 0;
932
- const outputs = value.outputs ?? [];
933
- const checks = value.checks ?? [];
934
- if (!Array.isArray(outputs) || outputs.length > 10 || !Array.isArray(checks) || checks.length > 10)
935
- return void 0;
936
- const clean = [];
937
- for (const o of outputs) {
938
- if (!o || !text(o.title, 120)) return void 0;
939
- switch (o.kind) {
940
- case "pr":
941
- case "link":
942
- if (!https(o.url)) return void 0;
943
- clean.push({ kind: o.kind, title: o.title, url: o.url });
944
- break;
945
- case "draft":
946
- if (!text(o.body, 4e3) || !optionalText(o.to, 200)) return void 0;
947
- clean.push({
948
- kind: "draft",
949
- title: o.title,
950
- body: o.body,
951
- ...o.to !== void 0 ? { to: o.to } : {}
952
- });
953
- break;
954
- case "doc":
955
- if (!optionalText(o.body, 8e3) || o.url !== void 0 && !https(o.url))
956
- return void 0;
957
- clean.push({
958
- kind: "doc",
959
- title: o.title,
960
- ...o.url !== void 0 ? { url: o.url } : {},
961
- ...o.body !== void 0 ? { body: o.body } : {}
962
- });
963
- break;
964
- case "file":
965
- if (!text(o.path, 400)) return void 0;
966
- clean.push({ kind: "file", title: o.title, path: o.path });
967
- break;
968
- default:
969
- return void 0;
970
- }
971
- }
972
- if (checks.some(
973
- (c) => !c || !text(c.name, 80) || !["passed", "failed", "skipped"].includes(c.outcome) || !optionalText(c.detail, 200)
974
- ))
975
- return void 0;
976
- return {
977
- summary: value.summary,
978
- outputs: clean,
979
- checks: checks.map((c) => ({
980
- name: c.name,
981
- outcome: c.outcome,
982
- ...c.detail !== void 0 ? { detail: c.detail } : {}
983
- }))
984
- };
985
- } catch {
986
- return void 0;
987
- }
988
- }
989
-
990
- // src/t3-bin.ts
991
- import { execFileSync } from "child_process";
992
- import { existsSync, readdirSync, statSync } from "fs";
993
- import { join as join2 } from "path";
994
- var CLEAN_ENV = () => ({
995
- HOME: process.env.HOME,
996
- USER: process.env.USER,
997
- PATH: process.env.PATH
998
- });
999
- function defaultT3BinSources(home, stored) {
1000
- return {
1001
- env: process.env,
1002
- home,
1003
- appDirs: process.platform === "darwin" ? ["/Applications", join2(home, "Applications")] : [],
1004
- onPath: () => whichAll("t3"),
1005
- ...stored ? { stored } : {}
1006
- };
1007
- }
1008
- function isExecutable(path) {
1009
- try {
1010
- const s = statSync(path);
1011
- return s.isFile() && (s.mode & 73) !== 0;
1012
- } catch {
1013
- return false;
1014
- }
1015
- }
1016
- function bundleBinaries(appDir) {
1017
- let bundles;
1018
- try {
1019
- bundles = readdirSync(appDir).filter((name) => /^T3 Code.*\.app$/.test(name));
1020
- } catch {
1021
- return [];
1022
- }
1023
- return bundles.flatMap((bundle) => {
1024
- const root = join2(appDir, bundle);
942
+ // src/t3-pair-link.ts
943
+ var CODE = /^[A-Za-z0-9_-]{8,256}$/;
944
+ function tokenOf(url) {
945
+ const hash = new URLSearchParams(url.hash.replace(/^#/, "")).get("token")?.trim();
946
+ if (hash) return hash;
947
+ return url.searchParams.get("token")?.trim() || null;
948
+ }
949
+ function pairingCredential(input) {
950
+ const text = input.trim().replace(/^["'<]+|["'>]+$/g, "");
951
+ if (!text) return null;
952
+ if (/^[a-z][a-z\d+.-]*:\/\//i.test(text)) {
953
+ let url;
1025
954
  try {
1026
- return readdirSync(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) => join2(root, rel)).filter(isExecutable);
955
+ url = new URL(text);
1027
956
  } catch {
1028
- return [];
957
+ return null;
1029
958
  }
1030
- });
1031
- }
1032
- function t3Candidates(serverVersion, sources) {
1033
- const ordered = [
1034
- sources.env.T3_BIN,
1035
- join2(sources.home, ".t3", "runtime", "versions", serverVersion, "t3"),
1036
- ...sources.appDirs.flatMap(bundleBinaries),
1037
- ...sources.onPath(),
1038
- sources.stored
1039
- ];
1040
- return [...new Set(ordered.filter((p) => Boolean(p) && existsSync(p)))];
1041
- }
1042
- function parseT3Version(output) {
1043
- return output.trim().split(/\s+/).at(-1)?.replace(/^v/, "") || null;
1044
- }
1045
- function t3Version(bin) {
1046
- try {
1047
- return parseT3Version(runT3(bin, ["--version"], 1e4));
1048
- } catch {
1049
- return null;
1050
- }
1051
- }
1052
- function pickT3Bin(candidates, serverVersion, versionOf = t3Version) {
1053
- return candidates.find((bin) => versionOf(bin) === serverVersion) ?? candidates[0] ?? null;
1054
- }
1055
- function t3BaseDirArgs(env = process.env) {
1056
- return env.T3CODE_HOME ? ["--base-dir", env.T3CODE_HOME] : [];
1057
- }
1058
- function runT3(bin, args, timeout = 15e3) {
1059
- try {
1060
- return execFileSync(bin, args, {
1061
- encoding: "utf-8",
1062
- env: CLEAN_ENV(),
1063
- timeout,
1064
- stdio: ["ignore", "pipe", "pipe"]
1065
- });
1066
- } catch (err) {
1067
- const stderr = String(err.stderr ?? "").trim().split("\n").filter((line2) => line2 && !/ExperimentalWarning|--trace-warnings/.test(line2)).at(-1);
1068
- throw new Error(
1069
- `t3 ${args.slice(0, 3).join(" ")} failed${stderr ? `: ${stderr.slice(0, 200)}` : ""}`
1070
- );
1071
- }
1072
- }
1073
- function whichAll(bin) {
1074
- try {
1075
- return execFileSync("which", ["-a", bin], {
1076
- encoding: "utf-8",
1077
- env: CLEAN_ENV(),
1078
- stdio: ["ignore", "pipe", "ignore"]
1079
- }).split("\n").map((line2) => line2.trim()).filter(Boolean);
1080
- } catch {
1081
- return [];
959
+ if (!["http:", "https:", "ws:", "wss:"].includes(url.protocol)) return null;
960
+ const token = tokenOf(url);
961
+ return token && CODE.test(token) ? token : null;
1082
962
  }
1083
- }
1084
-
1085
- // src/drivers/t3.ts
1086
- function isUnsettled(t) {
1087
- return !t.settledAt && !t.archivedAt && !isChild(t);
1088
- }
1089
- function isChild(t) {
1090
- return t.creationSource === "provider" || Boolean(t.lineage?.parentThreadId);
1091
- }
1092
- var SESSIONS_TTL_MS = 5 * 6e4;
1093
- var STATUS_TTL_MS = 3e4;
1094
- var TERMINAL_RUN = /* @__PURE__ */ new Set(["completed", "interrupted", "failed", "cancelled", "rolled_back"]);
1095
- var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master"]);
1096
- function pendingQuestions(p) {
1097
- const asked = /* @__PURE__ */ new Map();
1098
- for (const item of p.turnItems ?? []) {
1099
- if (item.type === "user_input_request" && item.requestId && item.questions?.length)
1100
- asked.set(item.requestId, item.questions);
1101
- }
1102
- return (p.runtimeRequests ?? []).filter((r) => r.kind === "user_input" && r.status === "pending" && asked.has(r.id)).sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? "")).map((r) => ({ request_id: r.id, questions: asked.get(r.id) ?? [] }));
1103
- }
1104
- function questionText(q) {
1105
- return questionLine(q.questions);
1106
- }
1107
- function latestRun(runs) {
1108
- return runs.reduce(
1109
- (latest, r) => !latest || (r.ordinal ?? 0) >= (latest.ordinal ?? 0) ? r : latest,
1110
- null
1111
- );
1112
- }
1113
- function isTerminal(runs) {
1114
- const run = latestRun(runs);
1115
- return Boolean(run && TERMINAL_RUN.has(run.status));
1116
- }
1117
- function activeRun(runs) {
1118
- const run = latestRun(runs);
1119
- return run && !TERMINAL_RUN.has(run.status) ? run : null;
1120
- }
1121
- function steerableRun(p) {
1122
- const run = activeRun(p.runs ?? []);
1123
- if (!run) return null;
1124
- const attempts = new Set((p.attempts ?? []).filter((a) => a.runId === run.id).map((a) => a.id));
1125
- const turning = (p.providerTurns ?? []).some(
1126
- (t) => t.status === "running" && t.runAttemptId !== null && attempts.has(t.runAttemptId)
1127
- );
1128
- return turning ? run : null;
1129
- }
1130
- var STEER_WAIT_MS = 8e3;
1131
- var STEER_POLL_MS = 500;
1132
- function prUrlOf(thread) {
1133
- const branch = thread.branch ?? null;
1134
- const linked = thread.pullRequests ?? [];
1135
- const own = branch ? linked.filter((pr) => pr.snapshot?.headBranch === branch) : [];
1136
- const fromLinked = (own.at(-1) ?? linked.at(-1))?.url ?? thread.linkedPullRequest?.url;
1137
- if (fromLinked) return fromLinked;
1138
- if (branch && !SHARED_BRANCHES.has(branch)) return thread.branchPullRequest?.url ?? null;
1139
- return null;
1140
- }
1141
- function outcomeOf(p) {
1142
- const run = latestRun(p.runs ?? []);
1143
- const status = run?.status ?? "pending";
1144
- const settled = TERMINAL_RUN.has(status) || Boolean(p.thread.settledAt);
1145
- const text2 = (p.messages ?? []).filter((m) => m.role === "assistant" && m.text).at(-1)?.text?.trim();
1146
- return {
1147
- status,
1148
- settled,
1149
- kind: settled ? status === "completed" || !run ? "settled" : "failed" : null,
1150
- pr_url: prUrlOf(p.thread),
1151
- last_assistant_text: text2 ? text2.slice(0, 300) : null,
1152
- ...parseRunResult(text2) ? { result: parseRunResult(text2) } : {}
1153
- };
1154
- }
1155
- function pickProject(projects, repository) {
1156
- const only = projects.length === 1 ? projects[0] : void 0;
1157
- if (!repository) {
1158
- if (only) return only;
1159
- throw new BoxToolError("no_project");
1160
- }
1161
- const want = repository.toLowerCase();
1162
- const found = projects.find(
1163
- (p) => p.title.toLowerCase() === want || p.workspaceRoot.split("/").at(-1)?.toLowerCase() === want || p.repositoryIdentity?.displayName?.toLowerCase() === want
1164
- );
1165
- if (!found) throw new BoxToolError("no_project");
1166
- return found;
1167
- }
1168
- var SHELL_HEADERS = { "x-t3-orchestration-protocol": "2" };
1169
- function boxCapabilities(scope) {
1170
- const scopes = (scope ?? "").split(/\s+/).filter(Boolean);
1171
- return scopes.includes("orchestration:operate") ? ["view", "start", "steer"] : ["view"];
1172
- }
1173
- function threadView(t) {
1174
- return {
1175
- id: t.id,
1176
- title: t.title,
1177
- status: t.status,
1178
- branch: t.branch ?? null,
1179
- source: t.creationSource ?? null,
1180
- cloop: (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX),
1181
- settled: Boolean(t.settledAt),
1182
- updatedAt: t.updatedAt
1183
- };
1184
- }
1185
- function orderThreads(threads, limit) {
1186
- const byRecency = (a, b) => b.updatedAt.localeCompare(a.updatedAt);
1187
- const running = threads.filter((t) => t.status === "running").sort(byRecency);
1188
- const rest = threads.filter((t) => t.status !== "running").sort(byRecency);
1189
- return [...running, ...rest].slice(0, limit);
1190
- }
1191
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1192
- var T3Driver = class {
1193
- constructor(deps) {
1194
- this.deps = deps;
1195
- }
1196
- deps;
1197
- name = "t3";
1198
- get capabilities() {
1199
- return boxCapabilities(this.deps.scope?.());
1200
- }
1201
- get t3() {
1202
- return this.deps.client();
1203
- }
1204
- log(line2) {
1205
- this.deps.log?.(line2);
1206
- }
1207
- /**
1208
- * T3's config and shell calls take 2-20 s on a loaded box, past the app's
1209
- * wait. So status reads them from the last answer at once and refreshes
1210
- * them in the background, at most once per STATUS_TTL_MS. Only the first
1211
- * call waits.
1212
- */
1213
- t3State = { value: null, at: 0, refreshing: null };
1214
- readT3State() {
1215
- const cache = this.t3State;
1216
- if (!cache.refreshing && Date.now() - cache.at > STATUS_TTL_MS) {
1217
- cache.refreshing = Promise.all([
1218
- this.t3.rpc("server.getConfig", {}),
1219
- this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
1220
- ]).then((value) => {
1221
- cache.value = value;
1222
- cache.at = Date.now();
1223
- return value;
1224
- }).finally(() => {
1225
- cache.refreshing = null;
1226
- });
1227
- cache.refreshing.catch(() => {
1228
- });
1229
- }
1230
- return cache.value ? Promise.resolve(cache.value) : cache.refreshing;
1231
- }
1232
- async status() {
1233
- const [cfg, shell] = await this.readT3State();
1234
- const sessions = this.listSessions();
1235
- const threads = (shell.threads ?? []).filter((t) => !isChild(t));
1236
- const unsettled = threads.filter(isUnsettled);
1237
- return {
1238
- box: {
1239
- label: cfg.environment.label,
1240
- driver: "t3",
1241
- t3Version: cfg.environment.serverVersion,
1242
- protocol: cfg.environment.orchestrationProtocolVersion,
1243
- hosts: (cfg.remoteOpenTargets ?? []).map((t) => t.host)
1244
- },
1245
- harnesses: cfg.providers.filter((p) => p.enabled).map((p) => ({
1246
- id: p.instanceId,
1247
- name: p.displayName ?? p.instanceId,
1248
- version: p.version,
1249
- ready: p.status === "ready",
1250
- signedIn: p.auth?.status === "authenticated",
1251
- account: p.auth?.label ?? null,
1252
- defaultModel: p.models?.find((m) => m.isDefault)?.slug ?? null
1253
- })),
1254
- clients: sessions?.filter((s) => s.client?.deviceType !== "bot").map((s) => ({
1255
- label: s.client?.label ?? "unknown",
1256
- connected: s.connected === true,
1257
- lastConnectedAt: s.lastConnectedAt ?? null
1258
- })) ?? null,
1259
- projects: (shell.projects ?? []).map((p) => p.title),
1260
- threads: {
1261
- unsettled: unsettled.length,
1262
- running: unsettled.filter((t) => t.status === "running").length,
1263
- settled: threads.length - unsettled.length,
1264
- cloop: unsettled.filter((t) => (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX)).length
1265
- }
1266
- };
1267
- }
1268
- async listThreads({
1269
- scope,
1270
- limit
1271
- }) {
1272
- const shell = await this.t3.http("/api/orchestration/shell", SHELL_HEADERS);
1273
- const all = (shell.threads ?? []).filter((t) => !isChild(t));
1274
- const threads = scope === "all" ? all : all.filter(isUnsettled);
1275
- return {
1276
- scope,
1277
- unsettled: all.filter(isUnsettled).length,
1278
- settled: all.length - all.filter(isUnsettled).length,
1279
- running: threads.filter((t) => t.status === "running").length,
1280
- threads: orderThreads(threads, limit).map(threadView)
1281
- };
1282
- }
1283
- /**
1284
- * `work_id` is T3's `commandId`, so a second launch of the same work returns
1285
- * the same thread with `resumed: true` and runs nothing twice. The worktree
1286
- * starts from origin's copy of the branch the project's checkout is on.
1287
- */
1288
- async launch(a) {
1289
- const known = this.deps.watched?.({ work_id: a.work_id });
1290
- if (known) return { thread_id: known.thread_id, resumed: true };
1291
- const [cfg, shell] = await Promise.all([
1292
- this.t3.rpc("server.getConfig", {}),
1293
- this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
1294
- ]);
1295
- const project = pickProject(shell.projects ?? [], a.repository);
1296
- const fallback = cfg.settings?.defaultModelSelection;
1297
- const harness = a.harness ?? fallback?.instanceId ?? "claudeAgent";
1298
- const provider = cfg.providers.find((p) => p.instanceId === harness && p.enabled);
1299
- if (!provider) throw new BoxToolError("harness_unavailable");
1300
- if (provider.auth && provider.auth.status !== "authenticated")
1301
- throw new BoxToolError("harness_signed_out");
1302
- const model = a.model ?? (fallback?.instanceId === harness ? fallback.model : void 0) ?? provider.models?.find((m) => m.isDefault)?.slug;
1303
- if (!model) throw new BoxToolError("harness_unavailable");
1304
- const modelSelection = !a.model && fallback?.instanceId === harness ? fallback : { instanceId: harness, model };
1305
- const runtimeMode = a.runtime_mode ?? cfg.settings?.defaultRuntimeMode;
1306
- if (!runtimeMode || !RUNTIME_MODES.has(runtimeMode))
1307
- throw new BoxToolError("runtime_mode_unknown");
1308
- const launched = await this.t3.rpc(
1309
- "orchestration.launchThread",
1310
- {
1311
- commandId: a.work_id,
1312
- creationSource: "mcp",
1313
- projectId: project.id,
1314
- title: a.title,
1315
- modelSelection,
1316
- runtimeMode,
1317
- interactionMode: "default",
1318
- workspaceStrategy: {
1319
- type: "worktree",
1320
- baseRef: this.baseRefFor(project.workspaceRoot)
1321
- },
1322
- initialMessage: { text: `${a.prompt}
1323
-
1324
- ${RESULT_INSTRUCTION}`, attachments: [] }
1325
- }
1326
- );
1327
- return { thread_id: launched.threadId, resumed: launched.resumed };
1328
- }
1329
- /**
1330
- * Say something to a thread. While the thread waits on a question, only
1331
- * `answer: true` sends anything: the text answers every question in the
1332
- * newest request, because a steer does not resolve a pending question and
1333
- * the run would wait on. Without it the call sends nothing and returns the
1334
- * question, so the owner says which they meant. Otherwise `steer`
1335
- * joins the running turn, waiting up to 8 s for a starting run's provider
1336
- * turn. A run that still cannot take a steer, or `queue`, gets the text
1337
- * after it ends; a thread with nothing running starts a new turn.
1338
- * `command_id` is T3's commandId, so a retried call sends once.
1339
- */
1340
- async send(a) {
1341
- let p = await this.readProjection(a.thread_id);
1342
- const pending = pendingQuestions(p);
1343
- const question = pending.at(-1);
1344
- if (a.answer && a.question_id !== void 0 && question?.request_id !== a.question_id) {
1345
- return {
1346
- delivered: "question_changed",
1347
- question: question ? questionText(question) : null,
1348
- question_id: question?.request_id ?? null
1349
- };
1350
- }
1351
- if (question && !a.answer) {
1352
- return {
1353
- delivered: "question_pending",
1354
- question: questionText(question),
1355
- questions: pending.length
1356
- };
1357
- }
1358
- if (question) {
1359
- const receipt2 = await this.dispatch({
1360
- type: "runtime-request.respond",
1361
- commandId: a.command_id,
1362
- threadId: a.thread_id,
1363
- requestId: question.request_id,
1364
- answers: Object.fromEntries(question.questions.map((q) => [q.id, a.text]))
1365
- });
1366
- return { sequence: receipt2.sequence, delivered: "answer", question_id: question.request_id };
1367
- }
1368
- if (a.mode === "steer") {
1369
- for (let waited = 0; waited < STEER_WAIT_MS; waited += STEER_POLL_MS) {
1370
- if (!activeRun(p.runs ?? []) || steerableRun(p)) break;
1371
- await sleep(STEER_POLL_MS);
1372
- p = await this.readProjection(a.thread_id);
1373
- }
1374
- }
1375
- const steer = a.mode === "steer" ? steerableRun(p) : null;
1376
- const active = activeRun(p.runs ?? []);
1377
- if (!active && !a.resume && this.deps.watched?.({ thread_id: a.thread_id })?.settled)
1378
- throw new BoxToolError("already_finished");
1379
- const receipt = await this.dispatch({
1380
- type: "message.dispatch",
1381
- commandId: a.command_id,
1382
- threadId: a.thread_id,
1383
- messageId: a.command_id,
1384
- text: a.text,
1385
- attachments: [],
1386
- dispatchMode: steer ? { type: "steer_active", targetRunId: steer.id } : active ? { type: "queue_after_active" } : { type: "start_immediately" },
1387
- createdBy: "user",
1388
- creationSource: "mcp"
1389
- });
1390
- return { sequence: receipt.sequence, delivered: steer ? "steer" : active ? "queue" : "start" };
1391
- }
1392
- /**
1393
- * Stop the running turn. A thread with nothing running answers
1394
- * `was_running: false`, and so does a run that ended while the interrupt
1395
- * was on its way: T3 refuses that interrupt, and the owner's ask is met.
1396
- */
1397
- async interrupt(threadId, commandId) {
1398
- const run = activeRun((await this.readProjection(threadId)).runs ?? []);
1399
- if (!run) return { ok: true, was_running: false };
1400
- try {
1401
- await this.dispatch({
1402
- type: "run.interrupt",
1403
- commandId,
1404
- threadId,
1405
- runId: run.id,
1406
- reason: "Stopped from Cloop"
1407
- });
1408
- } catch (err) {
1409
- if (activeRun((await this.readProjection(threadId)).runs ?? [])) throw err;
1410
- return { ok: true, was_running: false };
1411
- }
1412
- return { ok: true, was_running: true };
1413
- }
1414
- async readThread(id) {
1415
- const { status, settled, pr_url, last_assistant_text } = outcomeOf(
1416
- await this.readProjection(id)
1417
- );
1418
- return { status, settled, pr_url, last_assistant_text };
1419
- }
1420
- /**
1421
- * Subscribe to the thread and resubscribe whenever the stream ends. A thread
1422
- * that settled while nobody watched shows a terminal run in its first
1423
- * snapshot. A question is reported on every update it is still pending.
1424
- */
1425
- watch(threadId, onEvent) {
1426
- let stopped = false;
1427
- let finishing = false;
1428
- let live = null;
1429
- const retry = () => {
1430
- if (stopped) return;
1431
- const timer = setTimeout(() => void follow(), this.deps.retryMs ?? 1e4);
1432
- timer.unref?.();
1433
- };
1434
- const finish = async () => {
1435
- if (stopped || finishing) return;
1436
- finishing = true;
1437
- let outcome;
1438
- try {
1439
- outcome = outcomeOf(await this.readProjection(threadId));
1440
- const grace = this.deps.prGraceMs ?? 6e4;
1441
- if (outcome.settled && outcome.kind === "settled" && !outcome.pr_url && grace > 0) {
1442
- await sleep(grace);
1443
- outcome = outcomeOf(await this.readProjection(threadId));
1444
- }
1445
- } catch (err) {
1446
- this.log(
1447
- `read failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
1448
- );
1449
- finishing = false;
1450
- retry();
1451
- return;
1452
- }
1453
- if (stopped) return;
1454
- if (!outcome.settled) {
1455
- finishing = false;
1456
- this.log(`run continues thread=${threadId} run=${outcome.status}; watching on`);
1457
- if (!live) void follow();
1458
- return;
1459
- }
1460
- stopped = true;
1461
- live?.close();
1462
- const pr = outcome.pr_url ? { pr_url: outcome.pr_url } : {};
1463
- if (outcome.kind === "failed") {
1464
- onEvent({ kind: "failed", summary: `The run ended ${outcome.status}.`, ...pr });
1465
- } else {
1466
- onEvent({
1467
- kind: "settled",
1468
- ...outcome.result ? { result: outcome.result } : {},
1469
- ...outcome.last_assistant_text ? { summary: outcome.last_assistant_text } : {},
1470
- ...pr
1471
- });
1472
- }
1473
- };
1474
- const follow = async () => {
1475
- if (stopped || live) return;
1476
- const runs = /* @__PURE__ */ new Map();
1477
- const requests = /* @__PURE__ */ new Map();
1478
- const asks = /* @__PURE__ */ new Map();
1479
- const keepAsk = (item) => {
1480
- if (item.type === "user_input_request" && item.requestId) asks.set(item.requestId, item);
1481
- };
1482
- let settledByHand = false;
1483
- let stream;
1484
- try {
1485
- stream = await this.t3.stream("orchestration.subscribeThread", { threadId }, (raw) => {
1486
- const item = raw;
1487
- if (item.kind === "snapshot" && "projection" in item) {
1488
- for (const r of item.projection.runs ?? []) runs.set(r.id, r);
1489
- for (const r of item.projection.runtimeRequests ?? []) requests.set(r.id, r);
1490
- for (const t of item.projection.turnItems ?? []) keepAsk(t);
1491
- settledByHand ||= Boolean(item.projection.thread?.settledAt);
1492
- } else if (item.kind === "event" && "event" in item) {
1493
- const { type, payload } = item.event;
1494
- if (type.startsWith("run.") && typeof payload?.id === "string") {
1495
- runs.set(payload.id, payload);
1496
- } else if (type === "runtime-request.updated" && typeof payload?.id === "string") {
1497
- requests.set(payload.id, payload);
1498
- } else if (type === "turn-item.updated" && payload) {
1499
- keepAsk(payload);
1500
- } else if (type.startsWith("thread.") && payload?.settledAt) {
1501
- settledByHand = true;
1502
- } else return;
1503
- } else return;
1504
- if (settledByHand || isTerminal([...runs.values()])) {
1505
- void finish();
1506
- return;
1507
- }
1508
- const pending = pendingQuestions({
1509
- runtimeRequests: [...requests.values()],
1510
- turnItems: [...asks.values()]
1511
- });
1512
- for (const q of pending) {
1513
- onEvent({ kind: "question", question_id: q.request_id, summary: questionText(q) });
1514
- }
1515
- });
1516
- } catch (err) {
1517
- this.log(
1518
- `watch failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
1519
- );
1520
- retry();
1521
- return;
1522
- }
1523
- if (stopped) {
1524
- stream.close();
1525
- return;
1526
- }
1527
- live = stream;
1528
- const reason = await stream.done;
1529
- live = null;
1530
- if (stopped || finishing) return;
1531
- this.log(`watch ended thread=${threadId} reason=${reason}; resubscribing`);
1532
- retry();
1533
- };
1534
- void follow();
1535
- return () => {
1536
- stopped = true;
1537
- live?.close();
1538
- };
1539
- }
1540
- readProjection(threadId) {
1541
- return this.t3.rpc("orchestration.getThreadProjection", { threadId });
1542
- }
1543
- dispatch(command) {
1544
- return this.t3.rpc("orchestration.dispatchCommand", command);
1545
- }
1546
- sessions = {
1547
- list: null,
1548
- at: 0,
1549
- refreshing: false
1550
- };
1551
- /**
1552
- * T3's client sessions, from the cache. `t3 auth session list` starts a whole
1553
- * CLI and took 5 to 14 s on a loaded box, so status never waits on it: it
1554
- * answers with the last list and refreshes it in the background at most
1555
- * once per SESSIONS_TTL_MS.
1556
- */
1557
- listSessions() {
1558
- const bin = this.deps.t3Bin;
1559
- if (!bin) return null;
1560
- const stale = Date.now() - this.sessions.at > SESSIONS_TTL_MS;
1561
- if (stale && !this.sessions.refreshing) {
1562
- this.sessions.refreshing = true;
1563
- const done = (raw) => {
1564
- try {
1565
- if (raw !== null) this.sessions.list = JSON.parse(raw);
1566
- } catch {
1567
- }
1568
- this.sessions.at = Date.now();
1569
- this.sessions.refreshing = false;
1570
- };
1571
- (this.deps.execAsync ?? execFile3)(
1572
- bin,
1573
- ["auth", "session", "list", ...t3BaseDirArgs(), "--json"],
1574
- {
1575
- encoding: "utf-8",
1576
- env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
1577
- timeout: 3e4
1578
- },
1579
- (err, stdout) => done(err ? null : String(stdout))
1580
- );
1581
- }
1582
- return this.sessions.list;
1583
- }
1584
- /**
1585
- * The branch the project's checkout is on, from origin when origin has it. A
1586
- * local branch can lag origin by hundreds of commits on a box nobody pulls on,
1587
- * and T3 starts the worktree from the ref exactly as given.
1588
- */
1589
- baseRefFor(root) {
1590
- const git = (args) => String(
1591
- (this.deps.exec ?? execFileSync2)("git", ["-C", root, ...args], {
1592
- encoding: "utf-8",
1593
- env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
1594
- timeout: 5e3
1595
- })
1596
- ).trim();
1597
- let branch;
1598
- try {
1599
- branch = git(["rev-parse", "--abbrev-ref", "HEAD"]);
1600
- } catch {
1601
- return "HEAD";
1602
- }
1603
- if (!branch || branch === "HEAD") return "HEAD";
1604
- try {
1605
- git(["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}`]);
1606
- return `origin/${branch}`;
1607
- } catch {
1608
- return branch;
1609
- }
1610
- }
1611
- };
1612
-
1613
- // src/runner-config.ts
1614
- import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
1615
- import { homedir as homedir2 } from "os";
1616
- import { dirname as dirname2, join as join3 } from "path";
1617
- var BOX_FILE = "box.json";
1618
- function boxPath() {
1619
- return process.env.CLOOP_BOX_FILE ?? join3(homedir2(), CONFIG_DIR, BOX_FILE);
1620
- }
1621
- function isLocal(cfg) {
1622
- return cfg.driver === "claude-code" || cfg.driver === "codex";
1623
- }
1624
- function readRunnerConfig() {
1625
- let parsed;
1626
- try {
1627
- parsed = JSON.parse(readFileSync2(boxPath(), "utf-8"));
1628
- } catch {
1629
- return null;
1630
- }
1631
- if (parsed.driver === "claude-code" || parsed.driver === "codex") {
1632
- const ok = typeof parsed.deviceToken === "string" && typeof parsed.environmentId === "string" && typeof parsed.bin === "string" && Array.isArray(parsed.repos);
1633
- return ok ? parsed : null;
1634
- }
1635
- if (typeof parsed.t3Url !== "string" || typeof parsed.token !== "string") return null;
1636
- return parsed;
1637
- }
1638
- function writeBoxConfig(cfg) {
1639
- const path = boxPath();
1640
- mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
1641
- const temp = `${path}.${process.pid}.tmp`;
1642
- writeFileSync2(temp, `${JSON.stringify(cfg, null, 2)}
1643
- `, { mode: 384 });
1644
- chmodSync2(temp, 384);
1645
- renameSync2(temp, path);
963
+ return CODE.test(text) ? text : null;
1646
964
  }
1647
965
 
1648
966
  // src/commands/connect.ts
1649
967
  var DEFAULT_T3_URL = "http://127.0.0.1:3773";
1650
- var CLEAN_ENV2 = { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH };
968
+ var CLEAN_ENV = { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH };
1651
969
  var out = (line2) => console.log(line2);
1652
970
  var bold = (s) => `\x1B[1m${s}\x1B[0m`;
1653
971
  var dim = (s) => `\x1B[2m${s}\x1B[0m`;
@@ -1661,34 +979,25 @@ function flags(argv, name) {
1661
979
  }
1662
980
  function which(bin) {
1663
981
  try {
1664
- return execFileSync3("which", [bin], { encoding: "utf-8", env: CLEAN_ENV2 }).trim() || null;
982
+ return execFileSync("which", [bin], { encoding: "utf-8", env: CLEAN_ENV }).trim() || null;
1665
983
  } catch {
1666
984
  return null;
1667
985
  }
1668
986
  }
1669
- async function mintSession(t3Url, opts = {}) {
1670
- const env = await readEnvironment(t3Url, opts.fetchFn);
987
+ var T3PairError = class extends Error {
988
+ name = "T3PairError";
989
+ };
990
+ async function workstationEnvironment(t3Url, fetchFn) {
991
+ const env = await readEnvironment(t3Url, fetchFn);
1671
992
  const protocol = env.orchestrationProtocolVersion ?? 1;
1672
993
  if (protocol < MIN_PROTOCOL) {
1673
994
  throw new Error(
1674
995
  `T3 ${env.serverVersion} speaks orchestration protocol ${protocol}; a workstation needs ${MIN_PROTOCOL} (the V2 nightly or later).`
1675
996
  );
1676
997
  }
1677
- const sources = opts.sources ?? defaultT3BinSources(homedir3(), opts.stored);
1678
- const t3Bin = opts.bin ?? pickT3Bin(t3Candidates(env.serverVersion, sources), env.serverVersion);
1679
- if (!t3Bin) throw new Error("no t3 binary found; pass --t3-bin or set T3_BIN");
1680
- const pairing = JSON.parse(
1681
- runT3(t3Bin, [
1682
- "auth",
1683
- "pairing",
1684
- "create",
1685
- ...t3BaseDirArgs(sources.env),
1686
- "--ttl",
1687
- "5m",
1688
- "--json"
1689
- ])
1690
- );
1691
- const token = await exchangePairing(t3Url, pairing.credential, "cloop box", opts.fetchFn);
998
+ return env;
999
+ }
1000
+ function boxSession(t3Url, t3Bin, env, token) {
1692
1001
  return {
1693
1002
  t3Url,
1694
1003
  t3Bin,
@@ -1699,6 +1008,75 @@ async function mintSession(t3Url, opts = {}) {
1699
1008
  label: env.label
1700
1009
  };
1701
1010
  }
1011
+ async function mintSession(t3Url, opts = {}) {
1012
+ const env = await workstationEnvironment(t3Url, opts.fetchFn);
1013
+ const sources = opts.sources ?? defaultT3BinSources(homedir2(), opts.stored);
1014
+ try {
1015
+ const t3Bin = opts.bin ?? pickT3Bin(t3Candidates(env.serverVersion, sources), env.serverVersion);
1016
+ if (!t3Bin) throw new Error("no t3 binary found; pass --t3-bin or set T3_BIN");
1017
+ const pairing = JSON.parse(
1018
+ runT3(t3Bin, [
1019
+ "auth",
1020
+ "pairing",
1021
+ "create",
1022
+ ...t3BaseDirArgs(sources.env),
1023
+ "--ttl",
1024
+ "5m",
1025
+ "--json"
1026
+ ])
1027
+ );
1028
+ const token = await exchangePairing(t3Url, pairing.credential, "cloop box", opts.fetchFn);
1029
+ return boxSession(t3Url, t3Bin, env, token);
1030
+ } catch (err) {
1031
+ throw new T3PairError(err instanceof Error ? err.message : String(err));
1032
+ }
1033
+ }
1034
+ async function sessionFromLink(t3Url, link, fetchFn) {
1035
+ const credential = pairingCredential(link);
1036
+ if (!credential) throw new Error("that is not a T3 pairing link or code");
1037
+ const env = await workstationEnvironment(t3Url, fetchFn);
1038
+ let token;
1039
+ try {
1040
+ token = await exchangePairing(t3Url, credential, "cloop box", fetchFn);
1041
+ } catch (err) {
1042
+ const status = err instanceof T3HttpError ? err.status : null;
1043
+ if (status === 401)
1044
+ throw new Error(
1045
+ "T3 refused the pairing link; a link works once and lasts 5 minutes, so create a new one"
1046
+ );
1047
+ if (status === 400)
1048
+ throw new Error("T3 refused the pairing link; create one with the Standard permission");
1049
+ throw err;
1050
+ }
1051
+ return boxSession(t3Url, "", env, token);
1052
+ }
1053
+ function pairPrompt(fallback) {
1054
+ return `T3 Code is running, but this computer cannot pair with it automatically. In T3 Code, open Settings, then Connections, then Create pairing link. Copy the link and paste it here (or press Enter to ${fallback ? `use ${fallback} instead` : "stop"}): `;
1055
+ }
1056
+ async function pairT3(steps) {
1057
+ if (steps.link !== void 0) return { session: await steps.fromLink(steps.link), byLink: true };
1058
+ try {
1059
+ return { session: await steps.mint(), byLink: false };
1060
+ } catch (err) {
1061
+ if (!(err instanceof T3PairError) || !steps.ask) throw err;
1062
+ const answer = (await steps.ask(pairPrompt(steps.fallback)).catch(() => "")).trim();
1063
+ if (!answer) throw new Error(`${err.message}; no pairing link given`);
1064
+ return { session: await steps.fromLink(answer), byLink: true };
1065
+ }
1066
+ }
1067
+ function askHidden(question, input = process.stdin, output = process.stdout) {
1068
+ const muted = new Writable({ write: (_chunk, _encoding, done) => done() });
1069
+ const prompt = createInterface({ input, output: muted, terminal: true });
1070
+ output.write(`${question}
1071
+ ${dim("(The link stays hidden while you paste it.)")} `);
1072
+ return askOrClosed(
1073
+ prompt,
1074
+ () => new Error("closed")
1075
+ )("").finally(() => {
1076
+ prompt.close();
1077
+ output.write("\n");
1078
+ });
1079
+ }
1702
1080
  async function connectBox(steps) {
1703
1081
  const environment = await steps.readEnvironment();
1704
1082
  const session = await steps.mintSession();
@@ -1748,11 +1126,11 @@ function isWorkstation(previous, boxServiceInstalled2) {
1748
1126
  return boxServiceInstalled2 || Boolean(previous && !isLocal(previous));
1749
1127
  }
1750
1128
  function boxServiceInstalled() {
1751
- return existsSync2(
1129
+ return existsSync(
1752
1130
  installedService({
1753
1131
  platform: process.platform,
1754
1132
  kind: "workstation",
1755
- home: homedir3(),
1133
+ home: homedir2(),
1756
1134
  uid: process.getuid?.() ?? 0,
1757
1135
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
1758
1136
  }).path
@@ -1770,7 +1148,7 @@ async function revokeReplaced(previous, kind, revoke, say) {
1770
1148
  );
1771
1149
  }
1772
1150
  function fallbackLine(reason, driver) {
1773
- return `T3 Code is running but would not pair (${reason}). Connecting ${HARNESS_NAME[driver]} instead. To use T3: cloop connect --driver t3 --t3-bin <path>`;
1151
+ return `T3 Code is running but would not pair (${reason}). Connecting ${HARNESS_NAME[driver]} instead. To use T3, create a pairing link in T3 Code (Settings, Connections) and run: cloop connect --t3-pair <link>`;
1774
1152
  }
1775
1153
  async function connectChosen(driver, attempt, run) {
1776
1154
  attempt.driver = driver;
@@ -1830,14 +1208,14 @@ function installedService(opts) {
1830
1208
  if (opts.platform === "darwin") {
1831
1209
  const label = `com.cloop.${name}`;
1832
1210
  return {
1833
- path: join4(opts.dir ?? join4(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
1211
+ path: join2(opts.dir ?? join2(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
1834
1212
  steps: [{ command: ["launchctl", "bootout", `gui/${opts.uid}/${label}`], mayFail: true }],
1835
1213
  running: ["launchctl", "print", `gui/${opts.uid}/${label}`]
1836
1214
  };
1837
1215
  }
1838
1216
  const unit = `cloop-${name}.service`;
1839
1217
  return {
1840
- path: join4(opts.dir ?? join4(opts.home, ".config", "systemd", "user"), unit),
1218
+ path: join2(opts.dir ?? join2(opts.home, ".config", "systemd", "user"), unit),
1841
1219
  steps: [{ command: ["systemctl", "--user", "disable", "--now", unit], mayFail: true }],
1842
1220
  running: ["systemctl", "--user", "is-active", "--quiet", unit]
1843
1221
  };
@@ -1851,9 +1229,9 @@ function unitFor(opts) {
1851
1229
  });
1852
1230
  if (opts.platform === "darwin") {
1853
1231
  const label = `com.cloop.${name}`;
1854
- const agents = opts.dir ?? join4(opts.home, "Library", "LaunchAgents");
1855
- const path2 = join4(agents, `${label}.plist`);
1856
- const log = join4(opts.home, "Library", "Logs", `cloop-${name}.log`);
1232
+ const agents = opts.dir ?? join2(opts.home, "Library", "LaunchAgents");
1233
+ const path2 = join2(agents, `${label}.plist`);
1234
+ const log = join2(opts.home, "Library", "Logs", `cloop-${name}.log`);
1857
1235
  const xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1858
1236
  const contents2 = [
1859
1237
  '<?xml version="1.0" encoding="UTF-8"?>',
@@ -1890,8 +1268,8 @@ function unitFor(opts) {
1890
1268
  };
1891
1269
  }
1892
1270
  const unit = `cloop-${name}.service`;
1893
- const units = opts.dir ?? join4(opts.home, ".config", "systemd", "user");
1894
- const path = join4(units, unit);
1271
+ const units = opts.dir ?? join2(opts.home, ".config", "systemd", "user");
1272
+ const path = join2(units, unit);
1895
1273
  const contents = [
1896
1274
  "[Unit]",
1897
1275
  `Description=Cloop ${name}: answers the Cloop Agent over the mesh`,
@@ -1939,7 +1317,7 @@ var CHECKOUT_ROOTS = ["projects", "code", "repos", "src", "Developer", "dev", "w
1939
1317
  function lastCommitAt(path) {
1940
1318
  try {
1941
1319
  return Number(
1942
- execFileSync3("git", ["-C", path, "log", "-1", "--format=%ct"], {
1320
+ execFileSync("git", ["-C", path, "log", "-1", "--format=%ct"], {
1943
1321
  encoding: "utf-8",
1944
1322
  stdio: ["ignore", "pipe", "ignore"],
1945
1323
  timeout: 5e3
@@ -1954,13 +1332,13 @@ function findCheckouts(home, limit = 8) {
1954
1332
  for (const root of CHECKOUT_ROOTS) {
1955
1333
  let entries;
1956
1334
  try {
1957
- entries = readdirSync2(join4(home, root), { withFileTypes: true });
1335
+ entries = readdirSync(join2(home, root), { withFileTypes: true });
1958
1336
  } catch {
1959
1337
  continue;
1960
1338
  }
1961
1339
  for (const entry of entries) {
1962
- const path = join4(home, root, entry.name);
1963
- if (!entry.isDirectory() || !existsSync2(join4(path, ".git"))) continue;
1340
+ const path = join2(home, root, entry.name);
1341
+ if (!entry.isDirectory() || !existsSync(join2(path, ".git"))) continue;
1964
1342
  found.push({ repo: { label: entry.name, path }, at: lastCommitAt(path) });
1965
1343
  }
1966
1344
  }
@@ -2010,7 +1388,7 @@ async function reposFor(argv) {
2010
1388
  }
2011
1389
  const here = gitTop(process.cwd());
2012
1390
  if (here) return [{ label: basename3(here), path: here }];
2013
- const home = homedir3();
1391
+ const home = homedir2();
2014
1392
  const found = findCheckouts(home);
2015
1393
  const rerun = rerunCommand(argv);
2016
1394
  if (!found.length || !process.stdin.isTTY || !process.stdout.isTTY)
@@ -2041,7 +1419,7 @@ function askOrClosed(prompt, closed) {
2041
1419
  }
2042
1420
  function gitTop(path) {
2043
1421
  try {
2044
- return execFileSync3("git", ["-C", path, "rev-parse", "--show-toplevel"], {
1422
+ return execFileSync("git", ["-C", path, "rev-parse", "--show-toplevel"], {
2045
1423
  encoding: "utf-8",
2046
1424
  stdio: ["ignore", "pipe", "ignore"]
2047
1425
  }).trim();
@@ -2062,7 +1440,7 @@ function harnessLine(h) {
2062
1440
  const account = h.signedIn ? h.account ?? "signed in" : "signed out";
2063
1441
  return `${h.name}${version}, ${account}${h.experimental ? " (experimental)" : ""}`;
2064
1442
  }
2065
- async function runSteps(steps, run = (command) => void execFileSync3(command[0], command.slice(1), { stdio: "ignore", timeout: 15e3 }), wait = (ms) => new Promise((r) => setTimeout(r, ms))) {
1443
+ 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))) {
2066
1444
  for (const step of steps) {
2067
1445
  const tries = step.tries ?? 1;
2068
1446
  for (let attempt = 1; ; attempt++) {
@@ -2083,25 +1461,25 @@ async function installService(kind, argv, attempt) {
2083
1461
  return;
2084
1462
  }
2085
1463
  attempt.step = "service_write";
2086
- const npxBeside = join4(dirname3(process.execPath), "npx");
1464
+ const npxBeside = join2(dirname2(process.execPath), "npx");
2087
1465
  const program = programFor(
2088
1466
  process.argv[1] ?? "cloop",
2089
1467
  process.execPath,
2090
- existsSync2(npxBeside) ? npxBeside : which("npx"),
1468
+ existsSync(npxBeside) ? npxBeside : which("npx"),
2091
1469
  VERSION
2092
1470
  );
2093
1471
  if (typeof program === "string") throw new ConnectFailure("npx_missing", program);
2094
1472
  const unit = unitFor({
2095
1473
  platform: process.platform,
2096
1474
  kind,
2097
- home: homedir3(),
1475
+ home: homedir2(),
2098
1476
  program,
2099
1477
  env: unitEnv(process.env),
2100
1478
  uid: process.getuid?.() ?? 0,
2101
1479
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
2102
1480
  });
2103
- mkdirSync3(join4(unit.path, ".."), { recursive: true });
2104
- writeFileSync3(unit.path, unit.contents);
1481
+ mkdirSync2(join2(unit.path, ".."), { recursive: true });
1482
+ writeFileSync2(unit.path, unit.contents);
2105
1483
  if (argv.includes("--no-start")) {
2106
1484
  out(
2107
1485
  ` Service: wrote ${unit.path}. Start it with: ${dim(unit.start.map((step) => step.command.join(" ")).join(" && "))}`
@@ -2111,7 +1489,7 @@ async function installService(kind, argv, attempt) {
2111
1489
  attempt.step = "service_start";
2112
1490
  const since = Date.now();
2113
1491
  try {
2114
- if (existsSync2(unit.retire.path)) {
1492
+ if (existsSync(unit.retire.path)) {
2115
1493
  out(` This computer is one runner, so connect stops and removes ${unit.retire.path}.`);
2116
1494
  await runSteps(unit.retire.steps);
2117
1495
  rmSync(unit.retire.path, { force: true });
@@ -2130,7 +1508,7 @@ async function installService(kind, argv, attempt) {
2130
1508
  );
2131
1509
  try {
2132
1510
  out(
2133
- execFileSync3(unit.tail[0], unit.tail.slice(1), {
1511
+ execFileSync(unit.tail[0], unit.tail.slice(1), {
2134
1512
  encoding: "utf-8",
2135
1513
  timeout: 5e3
2136
1514
  })
@@ -2142,10 +1520,17 @@ async function installService(kind, argv, attempt) {
2142
1520
  }
2143
1521
  out(` Service: ${unit.path}, started and connected. Logs: ${dim(unit.logs)}`);
2144
1522
  }
2145
- async function connectT3(argv, attempt) {
1523
+ async function connectT3(argv, attempt, fallback) {
2146
1524
  const previous = readRunnerConfig();
2147
1525
  const t3Url = (flag(argv, "--t3-url") ?? DEFAULT_T3_URL).replace(/\/+$/, "");
2148
1526
  const t3Bin = flag(argv, "--t3-bin");
1527
+ const link = flag(argv, "--t3-pair");
1528
+ if (argv.includes("--t3-pair") && !link)
1529
+ throw new ConnectFailure(
1530
+ "bad_flag",
1531
+ "--t3-pair takes the pairing link from T3 Code (Settings, Connections)."
1532
+ );
1533
+ let byLink = false;
2149
1534
  const cfg = await connectBox({
2150
1535
  readEnvironment: async () => {
2151
1536
  const environment = await readEnvironment(t3Url);
@@ -2157,7 +1542,15 @@ async function connectT3(argv, attempt) {
2157
1542
  mintSession: async () => {
2158
1543
  attempt.step = "t3_pair";
2159
1544
  try {
2160
- return await mintSession(t3Url, t3Bin ? { bin: t3Bin } : {});
1545
+ const paired = await pairT3({
1546
+ ...link ? { link } : {},
1547
+ mint: () => mintSession(t3Url, t3Bin ? { bin: t3Bin } : {}),
1548
+ fromLink: (pasted) => sessionFromLink(t3Url, pasted),
1549
+ ask: process.stdin.isTTY && process.stdout.isTTY ? (q) => askHidden(q) : null,
1550
+ fallback
1551
+ });
1552
+ byLink = paired.byLink;
1553
+ return paired.session;
2161
1554
  } catch (err) {
2162
1555
  throw new ConnectFailure(
2163
1556
  "t3_pair_failed",
@@ -2189,6 +1582,10 @@ async function connectT3(argv, attempt) {
2189
1582
  out(
2190
1583
  `${bold("Cloop runner")} T3 ${cfg.label} paired with scope ${cfg.scope}, until ${cfg.expiresAt.slice(0, 10)}.`
2191
1584
  );
1585
+ if (byLink)
1586
+ out(
1587
+ ` Paired with a link from T3 Code. This session cannot renew itself: before ${cfg.expiresAt.slice(0, 10)}, run cloop connect again with a new link.`
1588
+ );
2192
1589
  const driver = new T3Driver({
2193
1590
  client: () => new T3Client(cfg.t3Url, cfg.token),
2194
1591
  t3Bin: cfg.t3Bin
@@ -2291,8 +1688,9 @@ async function connect(argv, attempt) {
2291
1688
  const workstation = isWorkstation(readRunnerConfig(), boxServiceInstalled());
2292
1689
  const choice = chooseDriver(found, forced, workstation);
2293
1690
  if (!choice.ok) throw new ConnectFailure(choice.code, choice.line);
1691
+ const local = fallbackDriver(found, forced, workstation);
2294
1692
  await connectChosen(choice.driver, attempt, {
2295
- t3: () => connectT3(argv, attempt),
1693
+ t3: () => connectT3(argv, attempt, local ? HARNESS_NAME[local] : null),
2296
1694
  local: (driver) => connectLocal(driver, found, argv, attempt),
2297
1695
  fallback: () => fallbackDriver(found, forced, workstation),
2298
1696
  say: (line2) => out(`${bold("Cloop runner")} ${line2}`)
@@ -2317,7 +1715,6 @@ async function connectCommand(argv) {
2317
1715
  }
2318
1716
 
2319
1717
  export {
2320
- BoxToolError,
2321
1718
  T3Client,
2322
1719
  runBoxTool,
2323
1720
  threadsFilePath,
@@ -2333,16 +1730,13 @@ export {
2333
1730
  claudeDialect,
2334
1731
  probeCodex,
2335
1732
  codexDialect,
2336
- RESULT_INSTRUCTION,
2337
- parseRunResult,
2338
- orderThreads,
2339
- T3Driver,
2340
- boxPath,
2341
- isLocal,
2342
- readRunnerConfig,
2343
- writeBoxConfig,
2344
1733
  DEFAULT_T3_URL,
1734
+ T3PairError,
2345
1735
  mintSession,
1736
+ sessionFromLink,
1737
+ pairPrompt,
1738
+ pairT3,
1739
+ askHidden,
2346
1740
  connectBox,
2347
1741
  chooseDriver,
2348
1742
  fallbackDriver,