@cloop/runner 0.2.3 → 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.
- package/dist/{box-G6HEXSWY.js → box-ZUDKJY2F.js} +22 -9
- package/dist/{chunk-CDG4IEQY.js → chunk-5J4I7DAE.js} +186 -30
- package/dist/{chunk-OJ5AREUC.js → chunk-AEWIRLRS.js} +1 -1
- package/dist/{chunk-TIXA2YXR.js → chunk-KHYA7GEH.js} +1 -1
- package/dist/chunk-M6U2YVEB.js +782 -0
- package/dist/{chunk-FW7MMQQV.js → chunk-PBOQMFNN.js} +1 -1
- package/dist/{chunk-KKFRQ4HQ.js → chunk-VEVDJ3H3.js} +98 -814
- package/dist/{chunk-4LFQXBWP.js → chunk-VK6GV757.js} +1 -0
- package/dist/{chunk-F4WCO6Z4.js → chunk-ZDUKQWKA.js} +1 -1
- package/dist/{connect-B5RZDVIW.js → connect-WXL6JWJN.js} +5 -4
- package/dist/{disconnect-MFHVNESG.js → disconnect-ZAVMFITZ.js} +10 -7
- package/dist/{hook-activity-O2NNKTOE.js → hook-activity-R7OPEYBX.js} +2 -2
- package/dist/{hook-session-start-MT67MMDM.js → hook-session-start-GEBGA63R.js} +1 -1
- package/dist/index.js +29 -10
- package/dist/{login-L6J5HPTR.js → login-MXIM6VMA.js} +2 -2
- package/dist/{mcp-server-Z6MG3AAS.js → mcp-server-ADCSP4SY.js} +3 -3
- package/dist/{runner-D6Z5S3VC.js → runner-OVRZFJIY.js} +3 -3
- package/dist/runs-ZTLNHRRJ.js +265 -0
- package/dist/{statusline-5HLPYTYU.js → statusline-ESZZVOBJ.js} +2 -2
- package/package.json +1 -1
|
@@ -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-
|
|
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-
|
|
34
|
+
} from "./chunk-ZDUKQWKA.js";
|
|
20
35
|
import {
|
|
21
36
|
VERSION
|
|
22
|
-
} from "./chunk-
|
|
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
|
|
45
|
+
import { execFileSync } from "child_process";
|
|
31
46
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
32
|
-
import { existsSync
|
|
33
|
-
import { homedir as
|
|
34
|
-
import { basename as basename3, dirname as
|
|
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;
|
|
@@ -256,8 +249,8 @@ function parseCommandId(args) {
|
|
|
256
249
|
return id;
|
|
257
250
|
}
|
|
258
251
|
function parseSendArgs(args) {
|
|
259
|
-
const
|
|
260
|
-
if (!
|
|
252
|
+
const text = typeof args.text === "string" ? args.text.trim() : "";
|
|
253
|
+
if (!text || text.length > 8e3) throw new BoxToolError("bad_args");
|
|
261
254
|
const mode = args.mode ?? "steer";
|
|
262
255
|
if (mode !== "steer" && mode !== "queue") throw new BoxToolError("bad_args");
|
|
263
256
|
if (args.answer !== void 0 && typeof args.answer !== "boolean")
|
|
@@ -267,7 +260,7 @@ function parseSendArgs(args) {
|
|
|
267
260
|
throw new BoxToolError("bad_args");
|
|
268
261
|
return {
|
|
269
262
|
thread_id: parseThreadId(args),
|
|
270
|
-
text
|
|
263
|
+
text,
|
|
271
264
|
mode,
|
|
272
265
|
command_id: parseCommandId(args),
|
|
273
266
|
answer: args.answer === true,
|
|
@@ -640,8 +633,8 @@ function questionsOf(input) {
|
|
|
640
633
|
const questions = input?.questions;
|
|
641
634
|
return Array.isArray(questions) ? questions.filter((q) => typeof q?.question === "string") : [];
|
|
642
635
|
}
|
|
643
|
-
function cut(
|
|
644
|
-
const line2 =
|
|
636
|
+
function cut(text, max = 160) {
|
|
637
|
+
const line2 = text.replace(/\s+/g, " ").trim();
|
|
645
638
|
return line2.length > max ? `${line2.slice(0, max - 1)}\u2026` : line2;
|
|
646
639
|
}
|
|
647
640
|
var TOOL_WORDS = {
|
|
@@ -659,6 +652,34 @@ var TOOL_WORDS = {
|
|
|
659
652
|
mcp__cloop__add_task_note: "add a note to the Task",
|
|
660
653
|
mcp__cloop__complete_task: "complete the Task"
|
|
661
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
|
+
}
|
|
662
683
|
function askSummary(tool, input, repo) {
|
|
663
684
|
if (tool === "AskUserQuestion") return questionLine(questionsOf(input));
|
|
664
685
|
const fields = input ?? {};
|
|
@@ -682,10 +703,10 @@ function line(value) {
|
|
|
682
703
|
return `${JSON.stringify(value)}
|
|
683
704
|
`;
|
|
684
705
|
}
|
|
685
|
-
function userMessage(run,
|
|
706
|
+
function userMessage(run, text, priority) {
|
|
686
707
|
return {
|
|
687
708
|
type: "user",
|
|
688
|
-
message: { role: "user", content: [{ type: "text", text
|
|
709
|
+
message: { role: "user", content: [{ type: "text", text }] },
|
|
689
710
|
parent_tool_use_id: null,
|
|
690
711
|
session_id: run.session_id ?? run.work_id,
|
|
691
712
|
...priority ? { priority } : {}
|
|
@@ -711,12 +732,14 @@ function parseClaudeLine(raw, run) {
|
|
|
711
732
|
const path = pathOf(block.input);
|
|
712
733
|
const description = block.input?.description;
|
|
713
734
|
const summary = typeof description === "string" ? cut(description, 200) : TOOL_WORDS[block.name];
|
|
735
|
+
const detail = toolDetail(block.name, block.input, run.repo);
|
|
714
736
|
return [
|
|
715
737
|
{
|
|
716
738
|
type: "tool",
|
|
717
739
|
name: block.name,
|
|
718
740
|
...path ? { target: basename(path) } : {},
|
|
719
|
-
...summary ? { summary } : {}
|
|
741
|
+
...summary ? { summary } : {},
|
|
742
|
+
...detail ? { detail } : {}
|
|
720
743
|
}
|
|
721
744
|
];
|
|
722
745
|
}
|
|
@@ -796,18 +819,18 @@ function claudeDialect(bin = "claude", fallback = DEFAULT_FALLBACK_MODEL, askEve
|
|
|
796
819
|
request: { subtype: "initialize" }
|
|
797
820
|
}) + line(userMessage(run, prompt));
|
|
798
821
|
},
|
|
799
|
-
userLine(run,
|
|
800
|
-
return line(userMessage(run,
|
|
822
|
+
userLine(run, text, mode) {
|
|
823
|
+
return line(userMessage(run, text, mode === "steer" ? "now" : "next"));
|
|
801
824
|
},
|
|
802
|
-
answerLine(ask,
|
|
825
|
+
answerLine(ask, text) {
|
|
803
826
|
const input = ask.input ?? {};
|
|
804
827
|
const response = ask.tool === "AskUserQuestion" ? {
|
|
805
828
|
behavior: "allow",
|
|
806
829
|
updatedInput: {
|
|
807
830
|
...input,
|
|
808
|
-
answers: Object.fromEntries(questionsOf(input).map((q) => [q.question,
|
|
831
|
+
answers: Object.fromEntries(questionsOf(input).map((q) => [q.question, text]))
|
|
809
832
|
}
|
|
810
|
-
} : isYes(
|
|
833
|
+
} : isYes(text) ? { behavior: "allow", updatedInput: input } : { behavior: "deny", message: text };
|
|
811
834
|
return line({
|
|
812
835
|
type: "control_response",
|
|
813
836
|
response: { subtype: "success", request_id: ask.request_id, response }
|
|
@@ -866,7 +889,13 @@ function parseCodexLine(raw) {
|
|
|
866
889
|
if (msg.type === "item.completed" && item?.type === "agent_message" && typeof item.text === "string")
|
|
867
890
|
return [{ type: "text", text: item.text }];
|
|
868
891
|
if (msg.type === "item.started" && item?.type === "command_execution")
|
|
869
|
-
return [
|
|
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
|
+
];
|
|
870
899
|
if (msg.type === "item.completed" && item?.type === "file_change") {
|
|
871
900
|
const changes = Array.isArray(item.changes) ? item.changes : [];
|
|
872
901
|
const path = changes[0]?.path;
|
|
@@ -909,745 +938,9 @@ function codexDialect(bin = "codex") {
|
|
|
909
938
|
};
|
|
910
939
|
}
|
|
911
940
|
|
|
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);
|
|
1025
|
-
try {
|
|
1026
|
-
return readdirSync(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) => join2(root, rel)).filter(isExecutable);
|
|
1027
|
-
} catch {
|
|
1028
|
-
return [];
|
|
1029
|
-
}
|
|
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 [];
|
|
1082
|
-
}
|
|
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);
|
|
1646
|
-
}
|
|
1647
|
-
|
|
1648
941
|
// src/commands/connect.ts
|
|
1649
942
|
var DEFAULT_T3_URL = "http://127.0.0.1:3773";
|
|
1650
|
-
var
|
|
943
|
+
var CLEAN_ENV = { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH };
|
|
1651
944
|
var out = (line2) => console.log(line2);
|
|
1652
945
|
var bold = (s) => `\x1B[1m${s}\x1B[0m`;
|
|
1653
946
|
var dim = (s) => `\x1B[2m${s}\x1B[0m`;
|
|
@@ -1661,7 +954,7 @@ function flags(argv, name) {
|
|
|
1661
954
|
}
|
|
1662
955
|
function which(bin) {
|
|
1663
956
|
try {
|
|
1664
|
-
return
|
|
957
|
+
return execFileSync("which", [bin], { encoding: "utf-8", env: CLEAN_ENV }).trim() || null;
|
|
1665
958
|
} catch {
|
|
1666
959
|
return null;
|
|
1667
960
|
}
|
|
@@ -1674,7 +967,7 @@ async function mintSession(t3Url, opts = {}) {
|
|
|
1674
967
|
`T3 ${env.serverVersion} speaks orchestration protocol ${protocol}; a workstation needs ${MIN_PROTOCOL} (the V2 nightly or later).`
|
|
1675
968
|
);
|
|
1676
969
|
}
|
|
1677
|
-
const sources = opts.sources ?? defaultT3BinSources(
|
|
970
|
+
const sources = opts.sources ?? defaultT3BinSources(homedir2(), opts.stored);
|
|
1678
971
|
const t3Bin = opts.bin ?? pickT3Bin(t3Candidates(env.serverVersion, sources), env.serverVersion);
|
|
1679
972
|
if (!t3Bin) throw new Error("no t3 binary found; pass --t3-bin or set T3_BIN");
|
|
1680
973
|
const pairing = JSON.parse(
|
|
@@ -1748,11 +1041,11 @@ function isWorkstation(previous, boxServiceInstalled2) {
|
|
|
1748
1041
|
return boxServiceInstalled2 || Boolean(previous && !isLocal(previous));
|
|
1749
1042
|
}
|
|
1750
1043
|
function boxServiceInstalled() {
|
|
1751
|
-
return
|
|
1044
|
+
return existsSync(
|
|
1752
1045
|
installedService({
|
|
1753
1046
|
platform: process.platform,
|
|
1754
1047
|
kind: "workstation",
|
|
1755
|
-
home:
|
|
1048
|
+
home: homedir2(),
|
|
1756
1049
|
uid: process.getuid?.() ?? 0,
|
|
1757
1050
|
...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
|
|
1758
1051
|
}).path
|
|
@@ -1830,14 +1123,14 @@ function installedService(opts) {
|
|
|
1830
1123
|
if (opts.platform === "darwin") {
|
|
1831
1124
|
const label = `com.cloop.${name}`;
|
|
1832
1125
|
return {
|
|
1833
|
-
path:
|
|
1126
|
+
path: join2(opts.dir ?? join2(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
|
|
1834
1127
|
steps: [{ command: ["launchctl", "bootout", `gui/${opts.uid}/${label}`], mayFail: true }],
|
|
1835
1128
|
running: ["launchctl", "print", `gui/${opts.uid}/${label}`]
|
|
1836
1129
|
};
|
|
1837
1130
|
}
|
|
1838
1131
|
const unit = `cloop-${name}.service`;
|
|
1839
1132
|
return {
|
|
1840
|
-
path:
|
|
1133
|
+
path: join2(opts.dir ?? join2(opts.home, ".config", "systemd", "user"), unit),
|
|
1841
1134
|
steps: [{ command: ["systemctl", "--user", "disable", "--now", unit], mayFail: true }],
|
|
1842
1135
|
running: ["systemctl", "--user", "is-active", "--quiet", unit]
|
|
1843
1136
|
};
|
|
@@ -1851,9 +1144,9 @@ function unitFor(opts) {
|
|
|
1851
1144
|
});
|
|
1852
1145
|
if (opts.platform === "darwin") {
|
|
1853
1146
|
const label = `com.cloop.${name}`;
|
|
1854
|
-
const agents = opts.dir ??
|
|
1855
|
-
const path2 =
|
|
1856
|
-
const 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`);
|
|
1857
1150
|
const xml = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
1858
1151
|
const contents2 = [
|
|
1859
1152
|
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
@@ -1890,8 +1183,8 @@ function unitFor(opts) {
|
|
|
1890
1183
|
};
|
|
1891
1184
|
}
|
|
1892
1185
|
const unit = `cloop-${name}.service`;
|
|
1893
|
-
const units = opts.dir ??
|
|
1894
|
-
const path =
|
|
1186
|
+
const units = opts.dir ?? join2(opts.home, ".config", "systemd", "user");
|
|
1187
|
+
const path = join2(units, unit);
|
|
1895
1188
|
const contents = [
|
|
1896
1189
|
"[Unit]",
|
|
1897
1190
|
`Description=Cloop ${name}: answers the Cloop Agent over the mesh`,
|
|
@@ -1939,7 +1232,7 @@ var CHECKOUT_ROOTS = ["projects", "code", "repos", "src", "Developer", "dev", "w
|
|
|
1939
1232
|
function lastCommitAt(path) {
|
|
1940
1233
|
try {
|
|
1941
1234
|
return Number(
|
|
1942
|
-
|
|
1235
|
+
execFileSync("git", ["-C", path, "log", "-1", "--format=%ct"], {
|
|
1943
1236
|
encoding: "utf-8",
|
|
1944
1237
|
stdio: ["ignore", "pipe", "ignore"],
|
|
1945
1238
|
timeout: 5e3
|
|
@@ -1954,13 +1247,13 @@ function findCheckouts(home, limit = 8) {
|
|
|
1954
1247
|
for (const root of CHECKOUT_ROOTS) {
|
|
1955
1248
|
let entries;
|
|
1956
1249
|
try {
|
|
1957
|
-
entries =
|
|
1250
|
+
entries = readdirSync(join2(home, root), { withFileTypes: true });
|
|
1958
1251
|
} catch {
|
|
1959
1252
|
continue;
|
|
1960
1253
|
}
|
|
1961
1254
|
for (const entry of entries) {
|
|
1962
|
-
const path =
|
|
1963
|
-
if (!entry.isDirectory() || !
|
|
1255
|
+
const path = join2(home, root, entry.name);
|
|
1256
|
+
if (!entry.isDirectory() || !existsSync(join2(path, ".git"))) continue;
|
|
1964
1257
|
found.push({ repo: { label: entry.name, path }, at: lastCommitAt(path) });
|
|
1965
1258
|
}
|
|
1966
1259
|
}
|
|
@@ -2010,7 +1303,7 @@ async function reposFor(argv) {
|
|
|
2010
1303
|
}
|
|
2011
1304
|
const here = gitTop(process.cwd());
|
|
2012
1305
|
if (here) return [{ label: basename3(here), path: here }];
|
|
2013
|
-
const home =
|
|
1306
|
+
const home = homedir2();
|
|
2014
1307
|
const found = findCheckouts(home);
|
|
2015
1308
|
const rerun = rerunCommand(argv);
|
|
2016
1309
|
if (!found.length || !process.stdin.isTTY || !process.stdout.isTTY)
|
|
@@ -2041,7 +1334,7 @@ function askOrClosed(prompt, closed) {
|
|
|
2041
1334
|
}
|
|
2042
1335
|
function gitTop(path) {
|
|
2043
1336
|
try {
|
|
2044
|
-
return
|
|
1337
|
+
return execFileSync("git", ["-C", path, "rev-parse", "--show-toplevel"], {
|
|
2045
1338
|
encoding: "utf-8",
|
|
2046
1339
|
stdio: ["ignore", "pipe", "ignore"]
|
|
2047
1340
|
}).trim();
|
|
@@ -2062,7 +1355,7 @@ function harnessLine(h) {
|
|
|
2062
1355
|
const account = h.signedIn ? h.account ?? "signed in" : "signed out";
|
|
2063
1356
|
return `${h.name}${version}, ${account}${h.experimental ? " (experimental)" : ""}`;
|
|
2064
1357
|
}
|
|
2065
|
-
async function runSteps(steps, run = (command) => void
|
|
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))) {
|
|
2066
1359
|
for (const step of steps) {
|
|
2067
1360
|
const tries = step.tries ?? 1;
|
|
2068
1361
|
for (let attempt = 1; ; attempt++) {
|
|
@@ -2083,25 +1376,25 @@ async function installService(kind, argv, attempt) {
|
|
|
2083
1376
|
return;
|
|
2084
1377
|
}
|
|
2085
1378
|
attempt.step = "service_write";
|
|
2086
|
-
const npxBeside =
|
|
1379
|
+
const npxBeside = join2(dirname2(process.execPath), "npx");
|
|
2087
1380
|
const program = programFor(
|
|
2088
1381
|
process.argv[1] ?? "cloop",
|
|
2089
1382
|
process.execPath,
|
|
2090
|
-
|
|
1383
|
+
existsSync(npxBeside) ? npxBeside : which("npx"),
|
|
2091
1384
|
VERSION
|
|
2092
1385
|
);
|
|
2093
1386
|
if (typeof program === "string") throw new ConnectFailure("npx_missing", program);
|
|
2094
1387
|
const unit = unitFor({
|
|
2095
1388
|
platform: process.platform,
|
|
2096
1389
|
kind,
|
|
2097
|
-
home:
|
|
1390
|
+
home: homedir2(),
|
|
2098
1391
|
program,
|
|
2099
1392
|
env: unitEnv(process.env),
|
|
2100
1393
|
uid: process.getuid?.() ?? 0,
|
|
2101
1394
|
...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
|
|
2102
1395
|
});
|
|
2103
|
-
|
|
2104
|
-
|
|
1396
|
+
mkdirSync2(join2(unit.path, ".."), { recursive: true });
|
|
1397
|
+
writeFileSync2(unit.path, unit.contents);
|
|
2105
1398
|
if (argv.includes("--no-start")) {
|
|
2106
1399
|
out(
|
|
2107
1400
|
` Service: wrote ${unit.path}. Start it with: ${dim(unit.start.map((step) => step.command.join(" ")).join(" && "))}`
|
|
@@ -2111,7 +1404,7 @@ async function installService(kind, argv, attempt) {
|
|
|
2111
1404
|
attempt.step = "service_start";
|
|
2112
1405
|
const since = Date.now();
|
|
2113
1406
|
try {
|
|
2114
|
-
if (
|
|
1407
|
+
if (existsSync(unit.retire.path)) {
|
|
2115
1408
|
out(` This computer is one runner, so connect stops and removes ${unit.retire.path}.`);
|
|
2116
1409
|
await runSteps(unit.retire.steps);
|
|
2117
1410
|
rmSync(unit.retire.path, { force: true });
|
|
@@ -2130,7 +1423,7 @@ async function installService(kind, argv, attempt) {
|
|
|
2130
1423
|
);
|
|
2131
1424
|
try {
|
|
2132
1425
|
out(
|
|
2133
|
-
|
|
1426
|
+
execFileSync(unit.tail[0], unit.tail.slice(1), {
|
|
2134
1427
|
encoding: "utf-8",
|
|
2135
1428
|
timeout: 5e3
|
|
2136
1429
|
})
|
|
@@ -2317,7 +1610,6 @@ async function connectCommand(argv) {
|
|
|
2317
1610
|
}
|
|
2318
1611
|
|
|
2319
1612
|
export {
|
|
2320
|
-
BoxToolError,
|
|
2321
1613
|
T3Client,
|
|
2322
1614
|
runBoxTool,
|
|
2323
1615
|
threadsFilePath,
|
|
@@ -2333,14 +1625,6 @@ export {
|
|
|
2333
1625
|
claudeDialect,
|
|
2334
1626
|
probeCodex,
|
|
2335
1627
|
codexDialect,
|
|
2336
|
-
RESULT_INSTRUCTION,
|
|
2337
|
-
parseRunResult,
|
|
2338
|
-
orderThreads,
|
|
2339
|
-
T3Driver,
|
|
2340
|
-
boxPath,
|
|
2341
|
-
isLocal,
|
|
2342
|
-
readRunnerConfig,
|
|
2343
|
-
writeBoxConfig,
|
|
2344
1628
|
DEFAULT_T3_URL,
|
|
2345
1629
|
mintSession,
|
|
2346
1630
|
connectBox,
|