@cloop/runner 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{box-SQVB3OUM.js → box-BS6BSQUO.js} +24 -15
- package/dist/{chunk-SQJ7ZO4G.js → chunk-3DIGCVL4.js} +1 -0
- package/dist/{chunk-7K5W6ELQ.js → chunk-7BREDPJD.js} +1 -1
- package/dist/{chunk-IIUHGZKX.js → chunk-7PUGLQL2.js} +1277 -1337
- package/dist/{chunk-4UE33DYW.js → chunk-AG6SI6I2.js} +1 -1
- package/dist/{chunk-CMOMRXTA.js → chunk-F36GGCXC.js} +92 -14
- package/dist/{chunk-UYTSOW2C.js → chunk-J6AEO3GT.js} +1 -1
- package/dist/{chunk-HS5CIDQF.js → chunk-JX6VG5FE.js} +5 -1
- package/dist/chunk-M6MHMCV6.js +336 -0
- package/dist/{chunk-IR3P526R.js → chunk-OJ5AREUC.js} +1 -1
- package/dist/chunk-R3CLO2FB.js +301 -0
- package/dist/chunk-TFZSCXSS.js +569 -0
- package/dist/connect-WRQN37SU.js +68 -0
- package/dist/disconnect-KTII7TXC.js +147 -0
- package/dist/{hook-activity-JHLSVNFG.js → hook-activity-O2NNKTOE.js} +4 -4
- package/dist/{hook-session-start-BIO5QJKT.js → hook-session-start-MT67MMDM.js} +3 -3
- package/dist/index.js +28 -14
- package/dist/{install-2AYAXFYF.js → install-HTDTCELB.js} +1 -1
- package/dist/{login-TLO4ZXLI.js → login-CUQR2MBW.js} +4 -3
- package/dist/{mcp-server-VGCZ6AGJ.js → mcp-server-YDRR6DYJ.js} +12 -12
- package/dist/read-permissions-SPOKGVLO.js +17 -0
- package/dist/runner-WW5OU2YU.js +13 -0
- package/dist/{statusline-YIRFJQWY.js → statusline-SLP4CAFB.js} +3 -3
- package/package.json +1 -1
- package/dist/connect-SFXN3UHJ.js +0 -41
- package/dist/runner-TOCZ4RXC.js +0 -147
|
@@ -1,21 +1,38 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
getMachine,
|
|
4
|
+
shortMachineName
|
|
5
|
+
} from "./chunk-JX6VG5FE.js";
|
|
6
|
+
import {
|
|
7
|
+
READ_TOOLS,
|
|
8
|
+
readOnlySettings
|
|
9
|
+
} from "./chunk-R3CLO2FB.js";
|
|
10
|
+
import {
|
|
11
|
+
connectWebhook
|
|
12
|
+
} from "./chunk-M6MHMCV6.js";
|
|
13
|
+
import {
|
|
14
|
+
ConnectFailure,
|
|
15
|
+
connectReport,
|
|
16
|
+
deviceLogin,
|
|
17
|
+
newAttempt,
|
|
18
|
+
sendConnectReport
|
|
19
|
+
} from "./chunk-F36GGCXC.js";
|
|
5
20
|
import {
|
|
6
21
|
VERSION
|
|
7
|
-
} from "./chunk-
|
|
22
|
+
} from "./chunk-7BREDPJD.js";
|
|
8
23
|
import {
|
|
9
24
|
CONFIG_DIR,
|
|
25
|
+
STAGING_ORIGIN,
|
|
10
26
|
getOrigin
|
|
11
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-3DIGCVL4.js";
|
|
12
28
|
|
|
13
29
|
// src/commands/connect.ts
|
|
14
30
|
import { execFileSync as execFileSync3 } from "child_process";
|
|
15
31
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
16
|
-
import { existsSync, mkdirSync as
|
|
17
|
-
import { homedir as
|
|
18
|
-
import { basename as
|
|
32
|
+
import { existsSync as existsSync2, mkdirSync as mkdirSync3, readdirSync as readdirSync2, rmSync, writeFileSync as writeFileSync3 } from "fs";
|
|
33
|
+
import { homedir as homedir3 } from "os";
|
|
34
|
+
import { basename as basename3, dirname as dirname3, join as join4, resolve as resolve2 } from "path";
|
|
35
|
+
import { createInterface } from "readline/promises";
|
|
19
36
|
|
|
20
37
|
// src/drivers/driver.ts
|
|
21
38
|
var RUNTIME_MODES = /* @__PURE__ */ new Set([
|
|
@@ -447,6 +464,7 @@ var BoxWatch = class {
|
|
|
447
464
|
...event.kind === "question" ? { question_id: event.question_id } : {},
|
|
448
465
|
...summary ? { summary: summary.slice(0, 500) } : {},
|
|
449
466
|
..."pr_url" in event && event.pr_url ? { pr_url: event.pr_url } : {},
|
|
467
|
+
..."error" in event && event.error ? { error: event.error } : {},
|
|
450
468
|
at: new Date(this.now()).toISOString()
|
|
451
469
|
};
|
|
452
470
|
}
|
|
@@ -498,637 +516,640 @@ var BoxWatch = class {
|
|
|
498
516
|
}
|
|
499
517
|
};
|
|
500
518
|
|
|
501
|
-
// src/
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
// src/drivers/local.ts
|
|
506
|
-
import { execFile as execFile2, execFileSync as execFileSync2, spawn } from "child_process";
|
|
507
|
-
import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
508
|
-
import { homedir as homedir2, hostname } from "os";
|
|
509
|
-
import { basename, dirname as dirname2, join as join2 } from "path";
|
|
510
|
-
import { createInterface } from "readline";
|
|
511
|
-
|
|
512
|
-
// src/drivers/t3.ts
|
|
513
|
-
import { execFile, execFileSync } from "child_process";
|
|
514
|
-
function isUnsettled(t) {
|
|
515
|
-
return !t.settledAt && !t.archivedAt && !isChild(t);
|
|
516
|
-
}
|
|
517
|
-
function isChild(t) {
|
|
518
|
-
return t.creationSource === "provider" || Boolean(t.lineage?.parentThreadId);
|
|
519
|
+
// src/device-revoke.ts
|
|
520
|
+
function tokenGone(revoke) {
|
|
521
|
+
return revoke === "revoked" || revoke === "already_revoked" || revoke === "no_device";
|
|
519
522
|
}
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
523
|
+
async function revokeOwnDevice(origin, deviceToken, fetchFn = fetch) {
|
|
524
|
+
if (!deviceToken) return "no_device";
|
|
525
|
+
try {
|
|
526
|
+
const res = await fetchFn(`${origin}/api/agent/mesh/device-revoke`, {
|
|
527
|
+
method: "POST",
|
|
528
|
+
headers: { authorization: `Bearer ${deviceToken}` },
|
|
529
|
+
signal: AbortSignal.timeout(1e4)
|
|
530
|
+
});
|
|
531
|
+
const body = await res.json().catch(() => null);
|
|
532
|
+
if (res.ok && body?.outcome === "revoked") return "revoked";
|
|
533
|
+
if (res.ok && body?.outcome === "already_revoked") return "already_revoked";
|
|
534
|
+
if (res.status === 401 && body?.error === "unknown_device") return "unknown_device";
|
|
535
|
+
return "failed";
|
|
536
|
+
} catch {
|
|
537
|
+
return "failed";
|
|
528
538
|
}
|
|
529
|
-
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) ?? [] }));
|
|
530
|
-
}
|
|
531
|
-
function questionText(q) {
|
|
532
|
-
return questionLine(q.questions);
|
|
533
539
|
}
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
540
|
+
|
|
541
|
+
// src/drivers/claude-code.ts
|
|
542
|
+
import { execFile } from "child_process";
|
|
543
|
+
import { basename, isAbsolute, relative, resolve } from "path";
|
|
544
|
+
var SUBSCRIPTIONS = {
|
|
545
|
+
max: "Claude Max",
|
|
546
|
+
pro: "Claude Pro",
|
|
547
|
+
team: "Claude Team",
|
|
548
|
+
enterprise: "Claude Enterprise"
|
|
549
|
+
};
|
|
550
|
+
var YES_WORDS = /* @__PURE__ */ new Set([
|
|
551
|
+
"y",
|
|
552
|
+
"yes",
|
|
553
|
+
"yep",
|
|
554
|
+
"yeah",
|
|
555
|
+
"allow",
|
|
556
|
+
"allow it",
|
|
557
|
+
"ok",
|
|
558
|
+
"okay",
|
|
559
|
+
"approve",
|
|
560
|
+
"approved",
|
|
561
|
+
"go ahead",
|
|
562
|
+
"sure",
|
|
563
|
+
"do it"
|
|
564
|
+
]);
|
|
565
|
+
function isYes(reply) {
|
|
566
|
+
return YES_WORDS.has(
|
|
567
|
+
reply.trim().toLowerCase().replace(/[.!\s]+$/, "")
|
|
538
568
|
);
|
|
539
569
|
}
|
|
540
|
-
function
|
|
541
|
-
|
|
542
|
-
|
|
570
|
+
function exec(bin, args) {
|
|
571
|
+
return new Promise(
|
|
572
|
+
(resolve3) => execFile(
|
|
573
|
+
bin,
|
|
574
|
+
args,
|
|
575
|
+
{ timeout: 1e4, encoding: "utf-8" },
|
|
576
|
+
(err, out2) => resolve3(err ? null : String(out2))
|
|
577
|
+
)
|
|
578
|
+
);
|
|
543
579
|
}
|
|
544
|
-
function
|
|
545
|
-
|
|
546
|
-
|
|
580
|
+
function claudeAccount(raw) {
|
|
581
|
+
try {
|
|
582
|
+
const auth = JSON.parse(raw ?? "");
|
|
583
|
+
if (auth.loggedIn !== true) return { signedIn: false, account: null };
|
|
584
|
+
const plan = auth.subscriptionType ? SUBSCRIPTIONS[auth.subscriptionType] : void 0;
|
|
585
|
+
return {
|
|
586
|
+
signedIn: true,
|
|
587
|
+
account: plan ?? (auth.authMethod === "claude.ai" ? "Claude" : "API key")
|
|
588
|
+
};
|
|
589
|
+
} catch {
|
|
590
|
+
return { signedIn: false, account: null };
|
|
591
|
+
}
|
|
547
592
|
}
|
|
548
|
-
function
|
|
549
|
-
const
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
);
|
|
555
|
-
return turning ? run2 : null;
|
|
593
|
+
function claudePermissionSupport(help) {
|
|
594
|
+
const choices = help?.match(/--permission-mode[\s\S]*?\(choices:([^)]*)\)/)?.[1] ?? "";
|
|
595
|
+
return {
|
|
596
|
+
autoMode: /"auto"/.test(choices),
|
|
597
|
+
manualMode: /"manual"/.test(choices) ? "manual" : "default"
|
|
598
|
+
};
|
|
556
599
|
}
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
function prUrlOf(thread) {
|
|
560
|
-
const branch = thread.branch ?? null;
|
|
561
|
-
const linked = thread.pullRequests ?? [];
|
|
562
|
-
const own = branch ? linked.filter((pr) => pr.snapshot?.headBranch === branch) : [];
|
|
563
|
-
const fromLinked = (own.at(-1) ?? linked.at(-1))?.url ?? thread.linkedPullRequest?.url;
|
|
564
|
-
if (fromLinked) return fromLinked;
|
|
565
|
-
if (branch && !SHARED_BRANCHES.has(branch)) return thread.branchPullRequest?.url ?? null;
|
|
566
|
-
return null;
|
|
600
|
+
async function probeClaudePermissions(bin = "claude") {
|
|
601
|
+
return claudePermissionSupport(await exec(bin, ["--help"]));
|
|
567
602
|
}
|
|
568
|
-
function
|
|
569
|
-
const
|
|
570
|
-
|
|
571
|
-
const
|
|
572
|
-
const text = (p.messages ?? []).filter((m) => m.role === "assistant" && m.text).at(-1)?.text?.trim();
|
|
603
|
+
async function probeClaude(bin = "claude") {
|
|
604
|
+
const version = (await exec(bin, ["--version"]))?.trim().split(/\s+/)[0];
|
|
605
|
+
if (!version) return null;
|
|
606
|
+
const { signedIn, account } = claudeAccount(await exec(bin, ["auth", "status", "--json"]));
|
|
573
607
|
return {
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
608
|
+
id: "claude-code",
|
|
609
|
+
name: "Claude Code",
|
|
610
|
+
version,
|
|
611
|
+
ready: signedIn,
|
|
612
|
+
signedIn,
|
|
613
|
+
account,
|
|
614
|
+
defaultModel: null
|
|
579
615
|
};
|
|
580
616
|
}
|
|
581
|
-
function
|
|
582
|
-
const
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
617
|
+
function pathOf(input) {
|
|
618
|
+
const fields = input ?? {};
|
|
619
|
+
const path = fields.file_path ?? fields.notebook_path ?? fields.path;
|
|
620
|
+
return typeof path === "string" ? path : void 0;
|
|
621
|
+
}
|
|
622
|
+
function shownPath(path, repo) {
|
|
623
|
+
const inside = relative(repo, resolve(repo, path));
|
|
624
|
+
return inside && !inside.startsWith("..") && !isAbsolute(inside) ? inside : path;
|
|
625
|
+
}
|
|
626
|
+
function questionsOf(input) {
|
|
627
|
+
const questions = input?.questions;
|
|
628
|
+
return Array.isArray(questions) ? questions.filter((q) => typeof q?.question === "string") : [];
|
|
629
|
+
}
|
|
630
|
+
function cut(text, max = 160) {
|
|
631
|
+
const line2 = text.replace(/\s+/g, " ").trim();
|
|
632
|
+
return line2.length > max ? `${line2.slice(0, max - 1)}\u2026` : line2;
|
|
633
|
+
}
|
|
634
|
+
var TOOL_WORDS = {
|
|
635
|
+
Read: "read the file",
|
|
636
|
+
Write: "write the file",
|
|
637
|
+
Edit: "edit the file",
|
|
638
|
+
Glob: "find files",
|
|
639
|
+
Grep: "search files",
|
|
640
|
+
LS: "list files",
|
|
641
|
+
mcp__cloop__get_task: "read the Task",
|
|
642
|
+
mcp__cloop__get_task_context: "read the Task context",
|
|
643
|
+
mcp__cloop__list_tasks: "list your Tasks",
|
|
644
|
+
mcp__cloop__search: "search Cloop",
|
|
645
|
+
mcp__cloop__add_task: "add a Task",
|
|
646
|
+
mcp__cloop__add_task_note: "add a note to the Task",
|
|
647
|
+
mcp__cloop__complete_task: "complete the Task"
|
|
648
|
+
};
|
|
649
|
+
function askSummary(tool, input, repo) {
|
|
650
|
+
if (tool === "AskUserQuestion") return questionLine(questionsOf(input));
|
|
651
|
+
const fields = input ?? {};
|
|
652
|
+
if (tool === "Bash") {
|
|
653
|
+
const description = typeof fields.description === "string" ? cut(fields.description) : "run this command";
|
|
654
|
+
const words2 = description.replace(/[.?!]+$/, "");
|
|
655
|
+
const command = String(fields.command ?? "").replace(
|
|
656
|
+
/[\r\n\t]/g,
|
|
657
|
+
(c) => c === "\n" ? "\\n" : c === "\r" ? "\\r" : "\\t"
|
|
658
|
+
);
|
|
659
|
+
const preview = command.length > 158 ? `${command.slice(0, 157)}\u2026` : command;
|
|
660
|
+
return `${words2.charAt(0).toLowerCase()}${words2.slice(1)}. OK?
|
|
661
|
+
(${preview})`;
|
|
586
662
|
}
|
|
587
|
-
|
|
588
|
-
const
|
|
589
|
-
|
|
590
|
-
)
|
|
591
|
-
if (!found) throw new BoxToolError("no_project");
|
|
592
|
-
return found;
|
|
663
|
+
if (tool === "WebFetch" && typeof fields.url === "string") return `read ${cut(fields.url)}. OK?`;
|
|
664
|
+
const words = TOOL_WORDS[tool] ?? tool.replace(/^mcp__[^_]+__/, "").replace(/_/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase();
|
|
665
|
+
const path = pathOf(fields);
|
|
666
|
+
return `${words}${path ? ` ${shownPath(path, repo)}` : ""}. OK?`;
|
|
593
667
|
}
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
return scopes.includes("orchestration:operate") ? ["view", "start", "steer"] : ["view"];
|
|
668
|
+
function line(value) {
|
|
669
|
+
return `${JSON.stringify(value)}
|
|
670
|
+
`;
|
|
598
671
|
}
|
|
599
|
-
function
|
|
672
|
+
function userMessage(run, text, priority) {
|
|
600
673
|
return {
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
cloop: (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX),
|
|
607
|
-
settled: Boolean(t.settledAt),
|
|
608
|
-
updatedAt: t.updatedAt
|
|
674
|
+
type: "user",
|
|
675
|
+
message: { role: "user", content: [{ type: "text", text }] },
|
|
676
|
+
parent_tool_use_id: null,
|
|
677
|
+
session_id: run.session_id ?? run.work_id,
|
|
678
|
+
...priority ? { priority } : {}
|
|
609
679
|
};
|
|
610
680
|
}
|
|
611
|
-
function
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
618
|
-
var T3Driver = class {
|
|
619
|
-
constructor(deps) {
|
|
620
|
-
this.deps = deps;
|
|
621
|
-
}
|
|
622
|
-
deps;
|
|
623
|
-
name = "t3";
|
|
624
|
-
get capabilities() {
|
|
625
|
-
return boxCapabilities(this.deps.scope?.());
|
|
681
|
+
function parseClaudeLine(raw, run) {
|
|
682
|
+
let msg;
|
|
683
|
+
try {
|
|
684
|
+
msg = JSON.parse(raw);
|
|
685
|
+
} catch {
|
|
686
|
+
return [];
|
|
626
687
|
}
|
|
627
|
-
|
|
628
|
-
return
|
|
688
|
+
if (msg.type === "system" && msg.subtype === "init" && typeof msg.session_id === "string") {
|
|
689
|
+
return [{ type: "session", id: msg.session_id }];
|
|
629
690
|
}
|
|
630
|
-
|
|
631
|
-
|
|
691
|
+
if (msg.type === "assistant") {
|
|
692
|
+
const content = msg.message?.content;
|
|
693
|
+
if (!Array.isArray(content)) return [];
|
|
694
|
+
return content.flatMap((block) => {
|
|
695
|
+
if (block?.type === "text" && typeof block.text === "string" && block.text.trim())
|
|
696
|
+
return [{ type: "text", text: block.text }];
|
|
697
|
+
if (block?.type === "tool_use" && typeof block.name === "string" && block.name !== "AskUserQuestion") {
|
|
698
|
+
const path = pathOf(block.input);
|
|
699
|
+
const description = block.input?.description;
|
|
700
|
+
const summary = typeof description === "string" ? cut(description, 200) : TOOL_WORDS[block.name];
|
|
701
|
+
return [
|
|
702
|
+
{
|
|
703
|
+
type: "tool",
|
|
704
|
+
name: block.name,
|
|
705
|
+
...path ? { target: basename(path) } : {},
|
|
706
|
+
...summary ? { summary } : {}
|
|
707
|
+
}
|
|
708
|
+
];
|
|
709
|
+
}
|
|
710
|
+
return [];
|
|
711
|
+
});
|
|
632
712
|
}
|
|
633
|
-
|
|
634
|
-
const
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
driver: "t3",
|
|
645
|
-
t3Version: cfg.environment.serverVersion,
|
|
646
|
-
protocol: cfg.environment.orchestrationProtocolVersion,
|
|
647
|
-
hosts: (cfg.remoteOpenTargets ?? []).map((t) => t.host)
|
|
648
|
-
},
|
|
649
|
-
harnesses: cfg.providers.filter((p) => p.enabled).map((p) => ({
|
|
650
|
-
id: p.instanceId,
|
|
651
|
-
name: p.displayName ?? p.instanceId,
|
|
652
|
-
version: p.version,
|
|
653
|
-
ready: p.status === "ready",
|
|
654
|
-
signedIn: p.auth?.status === "authenticated",
|
|
655
|
-
account: p.auth?.label ?? null,
|
|
656
|
-
defaultModel: p.models?.find((m) => m.isDefault)?.slug ?? null
|
|
657
|
-
})),
|
|
658
|
-
clients: sessions?.filter((s) => s.client?.deviceType !== "bot").map((s) => ({
|
|
659
|
-
label: s.client?.label ?? "unknown",
|
|
660
|
-
connected: s.connected === true,
|
|
661
|
-
lastConnectedAt: s.lastConnectedAt ?? null
|
|
662
|
-
})) ?? null,
|
|
663
|
-
projects: (shell.projects ?? []).map((p) => p.title),
|
|
664
|
-
threads: {
|
|
665
|
-
unsettled: unsettled.length,
|
|
666
|
-
running: unsettled.filter((t) => t.status === "running").length,
|
|
667
|
-
settled: threads.length - unsettled.length,
|
|
668
|
-
cloop: unsettled.filter((t) => (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX)).length
|
|
713
|
+
if (msg.type === "control_request") {
|
|
714
|
+
const request = msg.request;
|
|
715
|
+
if (request?.subtype !== "can_use_tool" || typeof msg.request_id !== "string") return [];
|
|
716
|
+
const tool = request.tool_name ?? "a tool";
|
|
717
|
+
return [
|
|
718
|
+
{
|
|
719
|
+
type: "ask",
|
|
720
|
+
request_id: msg.request_id,
|
|
721
|
+
tool,
|
|
722
|
+
input: request.input ?? {},
|
|
723
|
+
summary: askSummary(tool, request.input, run.repo)
|
|
669
724
|
}
|
|
670
|
-
|
|
725
|
+
];
|
|
671
726
|
}
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
limit
|
|
675
|
-
}) {
|
|
676
|
-
const shell = await this.t3.http("/api/orchestration/shell", SHELL_HEADERS);
|
|
677
|
-
const all = (shell.threads ?? []).filter((t) => !isChild(t));
|
|
678
|
-
const threads = scope === "all" ? all : all.filter(isUnsettled);
|
|
679
|
-
return {
|
|
680
|
-
scope,
|
|
681
|
-
unsettled: all.filter(isUnsettled).length,
|
|
682
|
-
settled: all.length - all.filter(isUnsettled).length,
|
|
683
|
-
running: threads.filter((t) => t.status === "running").length,
|
|
684
|
-
threads: orderThreads(threads, limit).map(threadView)
|
|
685
|
-
};
|
|
727
|
+
if (msg.type === "control_cancel_request" && typeof msg.request_id === "string") {
|
|
728
|
+
return [{ type: "cancel", request_id: msg.request_id }];
|
|
686
729
|
}
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
* starts from origin's copy of the branch the project's checkout is on.
|
|
691
|
-
*/
|
|
692
|
-
async launch(a) {
|
|
693
|
-
const known = this.deps.watched?.({ work_id: a.work_id });
|
|
694
|
-
if (known) return { thread_id: known.thread_id, resumed: true };
|
|
695
|
-
const [cfg, shell] = await Promise.all([
|
|
696
|
-
this.t3.rpc("server.getConfig", {}),
|
|
697
|
-
this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
|
|
698
|
-
]);
|
|
699
|
-
const project = pickProject(shell.projects ?? [], a.repository);
|
|
700
|
-
const fallback = cfg.settings?.defaultModelSelection;
|
|
701
|
-
const harness = a.harness ?? fallback?.instanceId ?? "claudeAgent";
|
|
702
|
-
const provider = cfg.providers.find((p) => p.instanceId === harness && p.enabled);
|
|
703
|
-
if (!provider) throw new BoxToolError("harness_unavailable");
|
|
704
|
-
if (provider.auth && provider.auth.status !== "authenticated")
|
|
705
|
-
throw new BoxToolError("harness_signed_out");
|
|
706
|
-
const model = a.model ?? (fallback?.instanceId === harness ? fallback.model : void 0) ?? provider.models?.find((m) => m.isDefault)?.slug;
|
|
707
|
-
if (!model) throw new BoxToolError("harness_unavailable");
|
|
708
|
-
const modelSelection = !a.model && fallback?.instanceId === harness ? fallback : { instanceId: harness, model };
|
|
709
|
-
const runtimeMode = a.runtime_mode ?? cfg.settings?.defaultRuntimeMode;
|
|
710
|
-
if (!runtimeMode || !RUNTIME_MODES.has(runtimeMode))
|
|
711
|
-
throw new BoxToolError("runtime_mode_unknown");
|
|
712
|
-
const launched = await this.t3.rpc(
|
|
713
|
-
"orchestration.launchThread",
|
|
730
|
+
if (msg.type === "result") {
|
|
731
|
+
const denied = Array.isArray(msg.permission_denials) && msg.permission_denials.length > 0;
|
|
732
|
+
return [
|
|
714
733
|
{
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
runtimeMode,
|
|
721
|
-
interactionMode: "default",
|
|
722
|
-
workspaceStrategy: {
|
|
723
|
-
type: "worktree",
|
|
724
|
-
baseRef: this.baseRefFor(project.workspaceRoot)
|
|
725
|
-
},
|
|
726
|
-
initialMessage: { text: a.prompt, attachments: [] }
|
|
727
|
-
}
|
|
728
|
-
);
|
|
729
|
-
return { thread_id: launched.threadId, resumed: launched.resumed };
|
|
730
|
-
}
|
|
731
|
-
/**
|
|
732
|
-
* Say something to a thread. While the thread waits on a question, only
|
|
733
|
-
* `answer: true` sends anything: the text answers every question in the
|
|
734
|
-
* newest request, because a steer does not resolve a pending question and
|
|
735
|
-
* the run would wait on. Without it the call sends nothing and returns the
|
|
736
|
-
* question, so the owner says which they meant. Otherwise `steer`
|
|
737
|
-
* joins the running turn, waiting up to 8 s for a starting run's provider
|
|
738
|
-
* turn. A run that still cannot take a steer, or `queue`, gets the text
|
|
739
|
-
* after it ends; a thread with nothing running starts a new turn.
|
|
740
|
-
* `command_id` is T3's commandId, so a retried call sends once.
|
|
741
|
-
*/
|
|
742
|
-
async send(a) {
|
|
743
|
-
let p = await this.readProjection(a.thread_id);
|
|
744
|
-
const pending = pendingQuestions(p);
|
|
745
|
-
const question = pending.at(-1);
|
|
746
|
-
if (a.answer && a.question_id !== void 0 && question?.request_id !== a.question_id) {
|
|
747
|
-
return {
|
|
748
|
-
delivered: "question_changed",
|
|
749
|
-
question: question ? questionText(question) : null,
|
|
750
|
-
question_id: question?.request_id ?? null
|
|
751
|
-
};
|
|
752
|
-
}
|
|
753
|
-
if (question && !a.answer) {
|
|
754
|
-
return {
|
|
755
|
-
delivered: "question_pending",
|
|
756
|
-
question: questionText(question),
|
|
757
|
-
questions: pending.length
|
|
758
|
-
};
|
|
759
|
-
}
|
|
760
|
-
if (question) {
|
|
761
|
-
const receipt2 = await this.dispatch({
|
|
762
|
-
type: "runtime-request.respond",
|
|
763
|
-
commandId: a.command_id,
|
|
764
|
-
threadId: a.thread_id,
|
|
765
|
-
requestId: question.request_id,
|
|
766
|
-
answers: Object.fromEntries(question.questions.map((q) => [q.id, a.text]))
|
|
767
|
-
});
|
|
768
|
-
return { sequence: receipt2.sequence, delivered: "answer", question_id: question.request_id };
|
|
769
|
-
}
|
|
770
|
-
if (a.mode === "steer") {
|
|
771
|
-
for (let waited = 0; waited < STEER_WAIT_MS; waited += STEER_POLL_MS) {
|
|
772
|
-
if (!activeRun(p.runs ?? []) || steerableRun(p)) break;
|
|
773
|
-
await sleep(STEER_POLL_MS);
|
|
774
|
-
p = await this.readProjection(a.thread_id);
|
|
734
|
+
type: "result",
|
|
735
|
+
ok: !denied && msg.subtype === "success" && msg.is_error !== true,
|
|
736
|
+
...denied ? {
|
|
737
|
+
text: `Claude Code blocked a step. ${typeof msg.result === "string" ? msg.result : "Check the run before retrying."}`
|
|
738
|
+
} : typeof msg.result === "string" ? { text: msg.result } : {}
|
|
775
739
|
}
|
|
776
|
-
|
|
777
|
-
const steer = a.mode === "steer" ? steerableRun(p) : null;
|
|
778
|
-
const active = activeRun(p.runs ?? []);
|
|
779
|
-
if (!active && this.deps.watched?.({ thread_id: a.thread_id })?.settled)
|
|
780
|
-
throw new BoxToolError("already_finished");
|
|
781
|
-
const receipt = await this.dispatch({
|
|
782
|
-
type: "message.dispatch",
|
|
783
|
-
commandId: a.command_id,
|
|
784
|
-
threadId: a.thread_id,
|
|
785
|
-
messageId: a.command_id,
|
|
786
|
-
text: a.text,
|
|
787
|
-
attachments: [],
|
|
788
|
-
dispatchMode: steer ? { type: "steer_active", targetRunId: steer.id } : active ? { type: "queue_after_active" } : { type: "start_immediately" },
|
|
789
|
-
createdBy: "user",
|
|
790
|
-
creationSource: "mcp"
|
|
791
|
-
});
|
|
792
|
-
return { sequence: receipt.sequence, delivered: steer ? "steer" : active ? "queue" : "start" };
|
|
793
|
-
}
|
|
794
|
-
/**
|
|
795
|
-
* Stop the running turn. A thread with nothing running answers
|
|
796
|
-
* `was_running: false`, and so does a run that ended while the interrupt
|
|
797
|
-
* was on its way: T3 refuses that interrupt, and the owner's ask is met.
|
|
798
|
-
*/
|
|
799
|
-
async interrupt(threadId, commandId) {
|
|
800
|
-
const run2 = activeRun((await this.readProjection(threadId)).runs ?? []);
|
|
801
|
-
if (!run2) return { ok: true, was_running: false };
|
|
802
|
-
try {
|
|
803
|
-
await this.dispatch({
|
|
804
|
-
type: "run.interrupt",
|
|
805
|
-
commandId,
|
|
806
|
-
threadId,
|
|
807
|
-
runId: run2.id,
|
|
808
|
-
reason: "Stopped from Cloop"
|
|
809
|
-
});
|
|
810
|
-
} catch (err) {
|
|
811
|
-
if (activeRun((await this.readProjection(threadId)).runs ?? [])) throw err;
|
|
812
|
-
return { ok: true, was_running: false };
|
|
813
|
-
}
|
|
814
|
-
return { ok: true, was_running: true };
|
|
815
|
-
}
|
|
816
|
-
async readThread(id) {
|
|
817
|
-
const { status, settled, pr_url, last_assistant_text } = outcomeOf(
|
|
818
|
-
await this.readProjection(id)
|
|
819
|
-
);
|
|
820
|
-
return { status, settled, pr_url, last_assistant_text };
|
|
740
|
+
];
|
|
821
741
|
}
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
const reason = await stream.done;
|
|
930
|
-
live = null;
|
|
931
|
-
if (stopped || finishing) return;
|
|
932
|
-
this.log(`watch ended thread=${threadId} reason=${reason}; resubscribing`);
|
|
933
|
-
retry();
|
|
934
|
-
};
|
|
935
|
-
void follow();
|
|
936
|
-
return () => {
|
|
937
|
-
stopped = true;
|
|
938
|
-
live?.close();
|
|
939
|
-
};
|
|
742
|
+
return [];
|
|
743
|
+
}
|
|
744
|
+
var DEFAULT_FALLBACK_MODEL = "opus";
|
|
745
|
+
function claudeDialect(bin = "claude", fallback = DEFAULT_FALLBACK_MODEL, askEverything = false, options = {}) {
|
|
746
|
+
const permission = () => askEverything ? "ask" : options.fullAccess === true ? "full" : options.autoMode === false ? "acceptEdits" : "auto";
|
|
747
|
+
return {
|
|
748
|
+
permission,
|
|
749
|
+
name: "claude-code",
|
|
750
|
+
fallback,
|
|
751
|
+
aliases: ["claude-code", "claudeAgent", "claude"],
|
|
752
|
+
bin,
|
|
753
|
+
capabilities: ["view", "start", "steer", "report"],
|
|
754
|
+
keepsStdin: true,
|
|
755
|
+
args(run, resume) {
|
|
756
|
+
return [
|
|
757
|
+
"--print",
|
|
758
|
+
"--verbose",
|
|
759
|
+
"--output-format",
|
|
760
|
+
"stream-json",
|
|
761
|
+
"--input-format",
|
|
762
|
+
"stream-json",
|
|
763
|
+
"--permission-prompt-tool",
|
|
764
|
+
"stdio",
|
|
765
|
+
...permission() === "full" ? ["--dangerously-skip-permissions"] : [
|
|
766
|
+
"--permission-mode",
|
|
767
|
+
permission() === "ask" ? options.manualMode ?? "manual" : permission(),
|
|
768
|
+
"--allowedTools",
|
|
769
|
+
...READ_TOOLS,
|
|
770
|
+
"--settings",
|
|
771
|
+
JSON.stringify(readOnlySettings(askEverything))
|
|
772
|
+
],
|
|
773
|
+
"--add-dir",
|
|
774
|
+
run.repo,
|
|
775
|
+
...resume ? ["--resume", run.session_id ?? run.work_id] : ["--session-id", run.session_id ?? run.work_id],
|
|
776
|
+
...run.model ? ["--model", run.model] : fallback ? ["--fallback-model", fallback] : []
|
|
777
|
+
];
|
|
778
|
+
},
|
|
779
|
+
opening(run, prompt) {
|
|
780
|
+
return line({
|
|
781
|
+
type: "control_request",
|
|
782
|
+
request_id: "cloop-init",
|
|
783
|
+
request: { subtype: "initialize" }
|
|
784
|
+
}) + line(userMessage(run, prompt));
|
|
785
|
+
},
|
|
786
|
+
userLine(run, text, mode) {
|
|
787
|
+
return line(userMessage(run, text, mode === "steer" ? "now" : "next"));
|
|
788
|
+
},
|
|
789
|
+
answerLine(ask, text) {
|
|
790
|
+
const input = ask.input ?? {};
|
|
791
|
+
const response = ask.tool === "AskUserQuestion" ? {
|
|
792
|
+
behavior: "allow",
|
|
793
|
+
updatedInput: {
|
|
794
|
+
...input,
|
|
795
|
+
answers: Object.fromEntries(questionsOf(input).map((q) => [q.question, text]))
|
|
796
|
+
}
|
|
797
|
+
} : isYes(text) ? { behavior: "allow", updatedInput: input } : { behavior: "deny", message: text };
|
|
798
|
+
return line({
|
|
799
|
+
type: "control_response",
|
|
800
|
+
response: { subtype: "success", request_id: ask.request_id, response }
|
|
801
|
+
});
|
|
802
|
+
},
|
|
803
|
+
parse: parseClaudeLine,
|
|
804
|
+
owns: (run, command) => command.includes(basename(bin)) && [run.work_id, run.session_id].some((id) => id !== null && command.includes(id)),
|
|
805
|
+
probe: () => probeClaude(bin)
|
|
806
|
+
};
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
// src/drivers/codex.ts
|
|
810
|
+
import { execFile as execFile2 } from "child_process";
|
|
811
|
+
import { basename as basename2 } from "path";
|
|
812
|
+
function exec2(bin, args) {
|
|
813
|
+
return new Promise(
|
|
814
|
+
(resolve3) => execFile2(
|
|
815
|
+
bin,
|
|
816
|
+
args,
|
|
817
|
+
{ timeout: 1e4, encoding: "utf-8" },
|
|
818
|
+
(err, out2, errOut) => resolve3({ ok: !err, out: `${out2}${errOut}` })
|
|
819
|
+
)
|
|
820
|
+
);
|
|
821
|
+
}
|
|
822
|
+
function codexAccount(ok, out2) {
|
|
823
|
+
if (!ok || !/logged in/i.test(out2) || /not logged in/i.test(out2))
|
|
824
|
+
return { signedIn: false, account: null };
|
|
825
|
+
return { signedIn: true, account: /chatgpt/i.test(out2) ? "ChatGPT" : "API key" };
|
|
826
|
+
}
|
|
827
|
+
async function probeCodex(bin = "codex") {
|
|
828
|
+
const version = await exec2(bin, ["--version"]);
|
|
829
|
+
if (!version.ok) return null;
|
|
830
|
+
const status = await exec2(bin, ["login", "status"]);
|
|
831
|
+
const { signedIn, account } = codexAccount(status.ok, status.out);
|
|
832
|
+
return {
|
|
833
|
+
id: "codex",
|
|
834
|
+
name: "Codex",
|
|
835
|
+
version: version.out.trim().split(/\s+/).at(-1) ?? null,
|
|
836
|
+
ready: signedIn,
|
|
837
|
+
signedIn,
|
|
838
|
+
account,
|
|
839
|
+
defaultModel: null,
|
|
840
|
+
experimental: true
|
|
841
|
+
};
|
|
842
|
+
}
|
|
843
|
+
function parseCodexLine(raw) {
|
|
844
|
+
let msg;
|
|
845
|
+
try {
|
|
846
|
+
msg = JSON.parse(raw);
|
|
847
|
+
} catch {
|
|
848
|
+
return [];
|
|
940
849
|
}
|
|
941
|
-
|
|
942
|
-
return
|
|
850
|
+
if (msg.type === "thread.started" && typeof msg.thread_id === "string")
|
|
851
|
+
return [{ type: "session", id: msg.thread_id }];
|
|
852
|
+
const item = msg.item;
|
|
853
|
+
if (msg.type === "item.completed" && item?.type === "agent_message" && typeof item.text === "string")
|
|
854
|
+
return [{ type: "text", text: item.text }];
|
|
855
|
+
if (msg.type === "item.started" && item?.type === "command_execution")
|
|
856
|
+
return [{ type: "tool", name: "Bash" }];
|
|
857
|
+
if (msg.type === "item.completed" && item?.type === "file_change") {
|
|
858
|
+
const changes = Array.isArray(item.changes) ? item.changes : [];
|
|
859
|
+
const path = changes[0]?.path;
|
|
860
|
+
return [
|
|
861
|
+
{
|
|
862
|
+
type: "tool",
|
|
863
|
+
name: "Edit",
|
|
864
|
+
...typeof path === "string" ? { target: basename2(path) } : {}
|
|
865
|
+
}
|
|
866
|
+
];
|
|
943
867
|
}
|
|
944
|
-
|
|
945
|
-
|
|
868
|
+
if (msg.type === "turn.completed") return [{ type: "result", ok: true }];
|
|
869
|
+
if (msg.type === "turn.failed") {
|
|
870
|
+
const message = msg.error?.message;
|
|
871
|
+
return [
|
|
872
|
+
{ type: "result", ok: false, ...typeof message === "string" ? { text: message } : {} }
|
|
873
|
+
];
|
|
946
874
|
}
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
875
|
+
return [];
|
|
876
|
+
}
|
|
877
|
+
function codexDialect(bin = "codex", fullAccess = false) {
|
|
878
|
+
const permission = () => fullAccess === true ? "full" : "auto";
|
|
879
|
+
return {
|
|
880
|
+
permission,
|
|
881
|
+
name: "codex",
|
|
882
|
+
aliases: ["codex"],
|
|
883
|
+
bin,
|
|
884
|
+
capabilities: ["view", "start", "report"],
|
|
885
|
+
keepsStdin: false,
|
|
886
|
+
args(run, resume) {
|
|
887
|
+
const model = run.model ? ["--model", run.model] : [];
|
|
888
|
+
const policy = permission() === "full" ? ["--dangerously-bypass-approvals-and-sandbox"] : ["--approve-for-me", "-c", 'sandbox_mode="workspace-write"'];
|
|
889
|
+
return resume && run.session_id ? ["exec", ...policy, "resume", run.session_id, "--json", ...model, "-"] : ["exec", "--cd", run.repo, "--json", ...policy, ...model, "-"];
|
|
890
|
+
},
|
|
891
|
+
opening: (_run, prompt) => prompt,
|
|
892
|
+
parse: parseCodexLine,
|
|
893
|
+
// A fresh run's command line names no id: Codex makes its session id after the start. So a run is also matched by its exact repository, which one open run per repository makes unique.
|
|
894
|
+
owns: (run, command) => command.includes(basename2(bin)) && command.includes("exec") && command.includes("--json") && (run.session_id !== null && command.includes(run.session_id) || command.includes(`--cd ${run.repo} `)),
|
|
895
|
+
probe: () => probeCodex(bin)
|
|
951
896
|
};
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
);
|
|
982
|
-
}
|
|
983
|
-
return this.sessions.list;
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
// src/drivers/t3.ts
|
|
900
|
+
import { execFile as execFile3, execFileSync as execFileSync2 } from "child_process";
|
|
901
|
+
|
|
902
|
+
// src/t3-bin.ts
|
|
903
|
+
import { execFileSync } from "child_process";
|
|
904
|
+
import { existsSync, readdirSync, statSync } from "fs";
|
|
905
|
+
import { join as join2 } from "path";
|
|
906
|
+
var CLEAN_ENV = () => ({
|
|
907
|
+
HOME: process.env.HOME,
|
|
908
|
+
USER: process.env.USER,
|
|
909
|
+
PATH: process.env.PATH
|
|
910
|
+
});
|
|
911
|
+
function defaultT3BinSources(home, stored) {
|
|
912
|
+
return {
|
|
913
|
+
env: process.env,
|
|
914
|
+
home,
|
|
915
|
+
appDirs: process.platform === "darwin" ? ["/Applications", join2(home, "Applications")] : [],
|
|
916
|
+
onPath: () => whichAll("t3"),
|
|
917
|
+
...stored ? { stored } : {}
|
|
918
|
+
};
|
|
919
|
+
}
|
|
920
|
+
function isExecutable(path) {
|
|
921
|
+
try {
|
|
922
|
+
const s = statSync(path);
|
|
923
|
+
return s.isFile() && (s.mode & 73) !== 0;
|
|
924
|
+
} catch {
|
|
925
|
+
return false;
|
|
984
926
|
}
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
timeout: 5e3
|
|
996
|
-
})
|
|
997
|
-
).trim();
|
|
998
|
-
let branch;
|
|
999
|
-
try {
|
|
1000
|
-
branch = git(["rev-parse", "--abbrev-ref", "HEAD"]);
|
|
1001
|
-
} catch {
|
|
1002
|
-
return "HEAD";
|
|
1003
|
-
}
|
|
1004
|
-
if (!branch || branch === "HEAD") return "HEAD";
|
|
927
|
+
}
|
|
928
|
+
function bundleBinaries(appDir) {
|
|
929
|
+
let bundles;
|
|
930
|
+
try {
|
|
931
|
+
bundles = readdirSync(appDir).filter((name) => /^T3 Code.*\.app$/.test(name));
|
|
932
|
+
} catch {
|
|
933
|
+
return [];
|
|
934
|
+
}
|
|
935
|
+
return bundles.flatMap((bundle) => {
|
|
936
|
+
const root = join2(appDir, bundle);
|
|
1005
937
|
try {
|
|
1006
|
-
|
|
1007
|
-
return `origin/${branch}`;
|
|
938
|
+
return readdirSync(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) => join2(root, rel)).filter(isExecutable);
|
|
1008
939
|
} catch {
|
|
1009
|
-
return
|
|
940
|
+
return [];
|
|
1010
941
|
}
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
function t3Candidates(serverVersion, sources) {
|
|
945
|
+
const ordered = [
|
|
946
|
+
sources.env.T3_BIN,
|
|
947
|
+
join2(sources.home, ".t3", "runtime", "versions", serverVersion, "t3"),
|
|
948
|
+
...sources.appDirs.flatMap(bundleBinaries),
|
|
949
|
+
...sources.onPath(),
|
|
950
|
+
sources.stored
|
|
951
|
+
];
|
|
952
|
+
return [...new Set(ordered.filter((p) => Boolean(p) && existsSync(p)))];
|
|
953
|
+
}
|
|
954
|
+
function parseT3Version(output) {
|
|
955
|
+
return output.trim().split(/\s+/).at(-1)?.replace(/^v/, "") || null;
|
|
956
|
+
}
|
|
957
|
+
function t3Version(bin) {
|
|
958
|
+
try {
|
|
959
|
+
return parseT3Version(runT3(bin, ["--version"], 1e4));
|
|
960
|
+
} catch {
|
|
961
|
+
return null;
|
|
1011
962
|
}
|
|
1012
|
-
}
|
|
963
|
+
}
|
|
964
|
+
function pickT3Bin(candidates, serverVersion, versionOf = t3Version) {
|
|
965
|
+
return candidates.find((bin) => versionOf(bin) === serverVersion) ?? candidates[0] ?? null;
|
|
966
|
+
}
|
|
967
|
+
function t3BaseDirArgs(env = process.env) {
|
|
968
|
+
return env.T3CODE_HOME ? ["--base-dir", env.T3CODE_HOME] : [];
|
|
969
|
+
}
|
|
970
|
+
function runT3(bin, args, timeout = 15e3) {
|
|
971
|
+
try {
|
|
972
|
+
return execFileSync(bin, args, {
|
|
973
|
+
encoding: "utf-8",
|
|
974
|
+
env: CLEAN_ENV(),
|
|
975
|
+
timeout,
|
|
976
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
977
|
+
});
|
|
978
|
+
} catch (err) {
|
|
979
|
+
const stderr = String(err.stderr ?? "").trim().split("\n").filter((line2) => line2 && !/ExperimentalWarning|--trace-warnings/.test(line2)).at(-1);
|
|
980
|
+
throw new Error(
|
|
981
|
+
`t3 ${args.slice(0, 3).join(" ")} failed${stderr ? `: ${stderr.slice(0, 200)}` : ""}`
|
|
982
|
+
);
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
function whichAll(bin) {
|
|
986
|
+
try {
|
|
987
|
+
return execFileSync("which", ["-a", bin], {
|
|
988
|
+
encoding: "utf-8",
|
|
989
|
+
env: CLEAN_ENV(),
|
|
990
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
991
|
+
}).split("\n").map((line2) => line2.trim()).filter(Boolean);
|
|
992
|
+
} catch {
|
|
993
|
+
return [];
|
|
994
|
+
}
|
|
995
|
+
}
|
|
1013
996
|
|
|
1014
|
-
// src/drivers/
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
997
|
+
// src/drivers/t3.ts
|
|
998
|
+
function isUnsettled(t) {
|
|
999
|
+
return !t.settledAt && !t.archivedAt && !isChild(t);
|
|
1000
|
+
}
|
|
1001
|
+
function isChild(t) {
|
|
1002
|
+
return t.creationSource === "provider" || Boolean(t.lineage?.parentThreadId);
|
|
1003
|
+
}
|
|
1004
|
+
var SESSIONS_TTL_MS = 5 * 6e4;
|
|
1005
|
+
var TERMINAL_RUN = /* @__PURE__ */ new Set(["completed", "interrupted", "failed", "cancelled", "rolled_back"]);
|
|
1006
|
+
var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master"]);
|
|
1007
|
+
function pendingQuestions(p) {
|
|
1008
|
+
const asked = /* @__PURE__ */ new Map();
|
|
1009
|
+
for (const item of p.turnItems ?? []) {
|
|
1010
|
+
if (item.type === "user_input_request" && item.requestId && item.questions?.length)
|
|
1011
|
+
asked.set(item.requestId, item.questions);
|
|
1012
|
+
}
|
|
1013
|
+
return (p.runtimeRequests ?? []).filter((r) => r.kind === "user_input" && r.status === "pending" && asked.has(r.id)).sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? "")).map((r) => ({ request_id: r.id, questions: asked.get(r.id) ?? [] }));
|
|
1014
|
+
}
|
|
1015
|
+
function questionText(q) {
|
|
1016
|
+
return questionLine(q.questions);
|
|
1017
|
+
}
|
|
1018
|
+
function latestRun(runs) {
|
|
1019
|
+
return runs.reduce(
|
|
1020
|
+
(latest, r) => !latest || (r.ordinal ?? 0) >= (latest.ordinal ?? 0) ? r : latest,
|
|
1021
|
+
null
|
|
1022
|
+
);
|
|
1023
|
+
}
|
|
1024
|
+
function isTerminal(runs) {
|
|
1025
|
+
const run = latestRun(runs);
|
|
1026
|
+
return Boolean(run && TERMINAL_RUN.has(run.status));
|
|
1027
|
+
}
|
|
1028
|
+
function activeRun(runs) {
|
|
1029
|
+
const run = latestRun(runs);
|
|
1030
|
+
return run && !TERMINAL_RUN.has(run.status) ? run : null;
|
|
1031
|
+
}
|
|
1032
|
+
function steerableRun(p) {
|
|
1033
|
+
const run = activeRun(p.runs ?? []);
|
|
1034
|
+
if (!run) return null;
|
|
1035
|
+
const attempts = new Set((p.attempts ?? []).filter((a) => a.runId === run.id).map((a) => a.id));
|
|
1036
|
+
const turning = (p.providerTurns ?? []).some(
|
|
1037
|
+
(t) => t.status === "running" && t.runAttemptId !== null && attempts.has(t.runAttemptId)
|
|
1038
|
+
);
|
|
1039
|
+
return turning ? run : null;
|
|
1040
|
+
}
|
|
1041
|
+
var STEER_WAIT_MS = 8e3;
|
|
1042
|
+
var STEER_POLL_MS = 500;
|
|
1043
|
+
function prUrlOf(thread) {
|
|
1044
|
+
const branch = thread.branch ?? null;
|
|
1045
|
+
const linked = thread.pullRequests ?? [];
|
|
1046
|
+
const own = branch ? linked.filter((pr) => pr.snapshot?.headBranch === branch) : [];
|
|
1047
|
+
const fromLinked = (own.at(-1) ?? linked.at(-1))?.url ?? thread.linkedPullRequest?.url;
|
|
1048
|
+
if (fromLinked) return fromLinked;
|
|
1049
|
+
if (branch && !SHARED_BRANCHES.has(branch)) return thread.branchPullRequest?.url ?? null;
|
|
1050
|
+
return null;
|
|
1028
1051
|
}
|
|
1029
|
-
function
|
|
1030
|
-
|
|
1052
|
+
function outcomeOf(p) {
|
|
1053
|
+
const run = latestRun(p.runs ?? []);
|
|
1054
|
+
const status = run?.status ?? "pending";
|
|
1055
|
+
const settled = TERMINAL_RUN.has(status) || Boolean(p.thread.settledAt);
|
|
1056
|
+
const text = (p.messages ?? []).filter((m) => m.role === "assistant" && m.text).at(-1)?.text?.trim();
|
|
1057
|
+
return {
|
|
1058
|
+
status,
|
|
1059
|
+
settled,
|
|
1060
|
+
kind: settled ? status === "completed" || !run ? "settled" : "failed" : null,
|
|
1061
|
+
pr_url: prUrlOf(p.thread),
|
|
1062
|
+
last_assistant_text: text ? text.slice(0, 300) : null
|
|
1063
|
+
};
|
|
1031
1064
|
}
|
|
1032
|
-
function
|
|
1065
|
+
function pickProject(projects, repository) {
|
|
1066
|
+
const only = projects.length === 1 ? projects[0] : void 0;
|
|
1033
1067
|
if (!repository) {
|
|
1034
|
-
if (
|
|
1068
|
+
if (only) return only;
|
|
1035
1069
|
throw new BoxToolError("no_project");
|
|
1036
1070
|
}
|
|
1037
|
-
const want = repository.toLowerCase()
|
|
1038
|
-
const found =
|
|
1039
|
-
(
|
|
1071
|
+
const want = repository.toLowerCase();
|
|
1072
|
+
const found = projects.find(
|
|
1073
|
+
(p) => p.title.toLowerCase() === want || p.workspaceRoot.split("/").at(-1)?.toLowerCase() === want || p.repositoryIdentity?.displayName?.toLowerCase() === want
|
|
1040
1074
|
);
|
|
1041
1075
|
if (!found) throw new BoxToolError("no_project");
|
|
1042
1076
|
return found;
|
|
1043
1077
|
}
|
|
1044
|
-
|
|
1045
|
-
|
|
1078
|
+
var SHELL_HEADERS = { "x-t3-orchestration-protocol": "2" };
|
|
1079
|
+
function boxCapabilities(scope) {
|
|
1080
|
+
const scopes = (scope ?? "").split(/\s+/).filter(Boolean);
|
|
1081
|
+
return scopes.includes("orchestration:operate") ? ["view", "start", "steer"] : ["view"];
|
|
1046
1082
|
}
|
|
1047
|
-
function
|
|
1048
|
-
return
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
)
|
|
1055
|
-
|
|
1083
|
+
function threadView(t) {
|
|
1084
|
+
return {
|
|
1085
|
+
id: t.id,
|
|
1086
|
+
title: t.title,
|
|
1087
|
+
status: t.status,
|
|
1088
|
+
branch: t.branch ?? null,
|
|
1089
|
+
source: t.creationSource ?? null,
|
|
1090
|
+
cloop: (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX),
|
|
1091
|
+
settled: Boolean(t.settledAt),
|
|
1092
|
+
updatedAt: t.updatedAt
|
|
1093
|
+
};
|
|
1056
1094
|
}
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
),
|
|
1063
|
-
async branchPr(repo) {
|
|
1064
|
-
try {
|
|
1065
|
-
const branch = await run("git", ["rev-parse", "--abbrev-ref", "HEAD"], repo);
|
|
1066
|
-
if (SHARED_BRANCHES2.has(branch)) return null;
|
|
1067
|
-
return prUrlIn(await run("gh", ["pr", "view", "--json", "url", "-q", ".url"], repo));
|
|
1068
|
-
} catch {
|
|
1069
|
-
return null;
|
|
1070
|
-
}
|
|
1071
|
-
}
|
|
1072
|
-
};
|
|
1073
|
-
function harnessAlive(pid, r, dialect) {
|
|
1074
|
-
try {
|
|
1075
|
-
process.kill(pid, 0);
|
|
1076
|
-
} catch (err) {
|
|
1077
|
-
if (err.code !== "EPERM") return false;
|
|
1078
|
-
}
|
|
1079
|
-
try {
|
|
1080
|
-
const command = execFileSync2("ps", ["-ww", "-o", "command=", "-p", String(pid)], {
|
|
1081
|
-
encoding: "utf-8",
|
|
1082
|
-
timeout: 2e3
|
|
1083
|
-
});
|
|
1084
|
-
return dialect.owns(r, command);
|
|
1085
|
-
} catch {
|
|
1086
|
-
return false;
|
|
1087
|
-
}
|
|
1095
|
+
function orderThreads(threads, limit) {
|
|
1096
|
+
const byRecency = (a, b) => b.updatedAt.localeCompare(a.updatedAt);
|
|
1097
|
+
const running = threads.filter((t) => t.status === "running").sort(byRecency);
|
|
1098
|
+
const rest = threads.filter((t) => t.status !== "running").sort(byRecency);
|
|
1099
|
+
return [...running, ...rest].slice(0, limit);
|
|
1088
1100
|
}
|
|
1089
|
-
var
|
|
1090
|
-
var
|
|
1091
|
-
var LocalDriver = class {
|
|
1101
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
1102
|
+
var T3Driver = class {
|
|
1092
1103
|
constructor(deps) {
|
|
1093
1104
|
this.deps = deps;
|
|
1094
|
-
this.name = deps.dialect.name;
|
|
1095
|
-
this.capabilities = deps.dialect.capabilities;
|
|
1096
|
-
this.runs = new Map(this.load().map((r) => [r.work_id, r]));
|
|
1097
1105
|
}
|
|
1098
1106
|
deps;
|
|
1099
|
-
name;
|
|
1100
|
-
capabilities
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
stopping = false;
|
|
1106
|
-
get repo() {
|
|
1107
|
-
return this.deps.repo ?? gitProbe;
|
|
1108
|
-
}
|
|
1109
|
-
get file() {
|
|
1110
|
-
return this.deps.file ?? localRunsFilePath();
|
|
1107
|
+
name = "t3";
|
|
1108
|
+
get capabilities() {
|
|
1109
|
+
return boxCapabilities(this.deps.scope?.());
|
|
1110
|
+
}
|
|
1111
|
+
get t3() {
|
|
1112
|
+
return this.deps.client();
|
|
1111
1113
|
}
|
|
1112
1114
|
log(line2) {
|
|
1113
1115
|
this.deps.log?.(line2);
|
|
1114
1116
|
}
|
|
1115
|
-
now() {
|
|
1116
|
-
return this.deps.now?.() ?? Date.now();
|
|
1117
|
-
}
|
|
1118
1117
|
async status() {
|
|
1119
|
-
const
|
|
1120
|
-
|
|
1121
|
-
|
|
1118
|
+
const [cfg, shell] = await Promise.all([
|
|
1119
|
+
this.t3.rpc("server.getConfig", {}),
|
|
1120
|
+
this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
|
|
1121
|
+
]);
|
|
1122
|
+
const sessions = this.listSessions();
|
|
1123
|
+
const threads = (shell.threads ?? []).filter((t) => !isChild(t));
|
|
1124
|
+
const unsettled = threads.filter(isUnsettled);
|
|
1122
1125
|
return {
|
|
1123
|
-
box: {
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1126
|
+
box: {
|
|
1127
|
+
label: cfg.environment.label,
|
|
1128
|
+
driver: "t3",
|
|
1129
|
+
t3Version: cfg.environment.serverVersion,
|
|
1130
|
+
protocol: cfg.environment.orchestrationProtocolVersion,
|
|
1131
|
+
hosts: (cfg.remoteOpenTargets ?? []).map((t) => t.host)
|
|
1132
|
+
},
|
|
1133
|
+
harnesses: cfg.providers.filter((p) => p.enabled).map((p) => ({
|
|
1134
|
+
id: p.instanceId,
|
|
1135
|
+
name: p.displayName ?? p.instanceId,
|
|
1136
|
+
version: p.version,
|
|
1137
|
+
ready: p.status === "ready",
|
|
1138
|
+
signedIn: p.auth?.status === "authenticated",
|
|
1139
|
+
account: p.auth?.label ?? null,
|
|
1140
|
+
defaultModel: p.models?.find((m) => m.isDefault)?.slug ?? null
|
|
1141
|
+
})),
|
|
1142
|
+
clients: sessions?.filter((s) => s.client?.deviceType !== "bot").map((s) => ({
|
|
1143
|
+
label: s.client?.label ?? "unknown",
|
|
1144
|
+
connected: s.connected === true,
|
|
1145
|
+
lastConnectedAt: s.lastConnectedAt ?? null
|
|
1146
|
+
})) ?? null,
|
|
1147
|
+
projects: (shell.projects ?? []).map((p) => p.title),
|
|
1127
1148
|
threads: {
|
|
1128
1149
|
unsettled: unsettled.length,
|
|
1129
|
-
running: unsettled.filter((
|
|
1130
|
-
settled:
|
|
1131
|
-
cloop: unsettled.length
|
|
1150
|
+
running: unsettled.filter((t) => t.status === "running").length,
|
|
1151
|
+
settled: threads.length - unsettled.length,
|
|
1152
|
+
cloop: unsettled.filter((t) => (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX)).length
|
|
1132
1153
|
}
|
|
1133
1154
|
};
|
|
1134
1155
|
}
|
|
@@ -1136,699 +1157,351 @@ var LocalDriver = class {
|
|
|
1136
1157
|
scope,
|
|
1137
1158
|
limit
|
|
1138
1159
|
}) {
|
|
1139
|
-
const
|
|
1140
|
-
const
|
|
1141
|
-
const
|
|
1142
|
-
id: r.work_id,
|
|
1143
|
-
title: r.title,
|
|
1144
|
-
status: this.statusOf(r),
|
|
1145
|
-
branch: null,
|
|
1146
|
-
source: "cloop",
|
|
1147
|
-
cloop: true,
|
|
1148
|
-
settled: Boolean(r.end),
|
|
1149
|
-
updatedAt: r.end?.at ?? r.started_at
|
|
1150
|
-
}));
|
|
1160
|
+
const shell = await this.t3.http("/api/orchestration/shell", SHELL_HEADERS);
|
|
1161
|
+
const all = (shell.threads ?? []).filter((t) => !isChild(t));
|
|
1162
|
+
const threads = scope === "all" ? all : all.filter(isUnsettled);
|
|
1151
1163
|
return {
|
|
1152
1164
|
scope,
|
|
1153
|
-
unsettled:
|
|
1154
|
-
settled: all.length -
|
|
1155
|
-
running:
|
|
1156
|
-
threads: orderThreads(
|
|
1157
|
-
};
|
|
1158
|
-
}
|
|
1159
|
-
async readThread(id) {
|
|
1160
|
-
const r = this.record(id);
|
|
1161
|
-
return {
|
|
1162
|
-
status: this.statusOf(r),
|
|
1163
|
-
settled: Boolean(r.end),
|
|
1164
|
-
pr_url: r.end?.pr_url ?? null,
|
|
1165
|
-
last_assistant_text: r.end?.summary ?? r.last_text ?? null
|
|
1165
|
+
unsettled: all.filter(isUnsettled).length,
|
|
1166
|
+
settled: all.length - all.filter(isUnsettled).length,
|
|
1167
|
+
running: threads.filter((t) => t.status === "running").length,
|
|
1168
|
+
threads: orderThreads(threads, limit).map(threadView)
|
|
1166
1169
|
};
|
|
1167
1170
|
}
|
|
1171
|
+
/**
|
|
1172
|
+
* `work_id` is T3's `commandId`, so a second launch of the same work returns
|
|
1173
|
+
* the same thread with `resumed: true` and runs nothing twice. The worktree
|
|
1174
|
+
* starts from origin's copy of the branch the project's checkout is on.
|
|
1175
|
+
*/
|
|
1168
1176
|
async launch(a) {
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
const
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
const
|
|
1179
|
-
if (
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1177
|
+
const known = this.deps.watched?.({ work_id: a.work_id });
|
|
1178
|
+
if (known) return { thread_id: known.thread_id, resumed: true };
|
|
1179
|
+
const [cfg, shell] = await Promise.all([
|
|
1180
|
+
this.t3.rpc("server.getConfig", {}),
|
|
1181
|
+
this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
|
|
1182
|
+
]);
|
|
1183
|
+
const project = pickProject(shell.projects ?? [], a.repository);
|
|
1184
|
+
const fallback = cfg.settings?.defaultModelSelection;
|
|
1185
|
+
const harness = a.harness ?? fallback?.instanceId ?? "claudeAgent";
|
|
1186
|
+
const provider = cfg.providers.find((p) => p.instanceId === harness && p.enabled);
|
|
1187
|
+
if (!provider) throw new BoxToolError("harness_unavailable");
|
|
1188
|
+
if (provider.auth && provider.auth.status !== "authenticated")
|
|
1189
|
+
throw new BoxToolError("harness_signed_out");
|
|
1190
|
+
const model = a.model ?? (fallback?.instanceId === harness ? fallback.model : void 0) ?? provider.models?.find((m) => m.isDefault)?.slug;
|
|
1191
|
+
if (!model) throw new BoxToolError("harness_unavailable");
|
|
1192
|
+
const modelSelection = !a.model && fallback?.instanceId === harness ? fallback : { instanceId: harness, model };
|
|
1193
|
+
const runtimeMode = a.runtime_mode ?? cfg.settings?.defaultRuntimeMode;
|
|
1194
|
+
if (!runtimeMode || !RUNTIME_MODES.has(runtimeMode))
|
|
1195
|
+
throw new BoxToolError("runtime_mode_unknown");
|
|
1196
|
+
const launched = await this.t3.rpc(
|
|
1197
|
+
"orchestration.launchThread",
|
|
1198
|
+
{
|
|
1199
|
+
commandId: a.work_id,
|
|
1200
|
+
creationSource: "mcp",
|
|
1201
|
+
projectId: project.id,
|
|
1202
|
+
title: a.title,
|
|
1203
|
+
modelSelection,
|
|
1204
|
+
runtimeMode,
|
|
1205
|
+
interactionMode: "default",
|
|
1206
|
+
workspaceStrategy: {
|
|
1207
|
+
type: "worktree",
|
|
1208
|
+
baseRef: this.baseRefFor(project.workspaceRoot)
|
|
1209
|
+
},
|
|
1210
|
+
initialMessage: { text: a.prompt, attachments: [] }
|
|
1211
|
+
}
|
|
1212
|
+
);
|
|
1213
|
+
return { thread_id: launched.threadId, resumed: launched.resumed };
|
|
1195
1214
|
}
|
|
1215
|
+
/**
|
|
1216
|
+
* Say something to a thread. While the thread waits on a question, only
|
|
1217
|
+
* `answer: true` sends anything: the text answers every question in the
|
|
1218
|
+
* newest request, because a steer does not resolve a pending question and
|
|
1219
|
+
* the run would wait on. Without it the call sends nothing and returns the
|
|
1220
|
+
* question, so the owner says which they meant. Otherwise `steer`
|
|
1221
|
+
* joins the running turn, waiting up to 8 s for a starting run's provider
|
|
1222
|
+
* turn. A run that still cannot take a steer, or `queue`, gets the text
|
|
1223
|
+
* after it ends; a thread with nothing running starts a new turn.
|
|
1224
|
+
* `command_id` is T3's commandId, so a retried call sends once.
|
|
1225
|
+
*/
|
|
1196
1226
|
async send(a) {
|
|
1197
|
-
|
|
1198
|
-
const
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
const ask = live?.asks[0];
|
|
1202
|
-
if (a.answer && (!ask || ask.request_id !== a.question_id)) {
|
|
1203
|
-
this.log(`question_changed work=${r.work_id}`);
|
|
1227
|
+
let p = await this.readProjection(a.thread_id);
|
|
1228
|
+
const pending = pendingQuestions(p);
|
|
1229
|
+
const question = pending.at(-1);
|
|
1230
|
+
if (a.answer && a.question_id !== void 0 && question?.request_id !== a.question_id) {
|
|
1204
1231
|
return {
|
|
1205
1232
|
delivered: "question_changed",
|
|
1206
|
-
question:
|
|
1207
|
-
question_id:
|
|
1233
|
+
question: question ? questionText(question) : null,
|
|
1234
|
+
question_id: question?.request_id ?? null
|
|
1208
1235
|
};
|
|
1209
1236
|
}
|
|
1210
|
-
if (
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
};
|
|
1217
|
-
}
|
|
1218
|
-
const line3 = this.deps.dialect.answerLine?.(ask, a.text);
|
|
1219
|
-
if (!line3) throw new BoxToolError("cannot_steer");
|
|
1220
|
-
live.asks = live.asks.slice(1);
|
|
1221
|
-
this.write(live, line3);
|
|
1222
|
-
this.remember(r, a.command_id, "answer");
|
|
1223
|
-
this.log(`answer work=${r.work_id}`);
|
|
1224
|
-
this.askNext(r, live);
|
|
1225
|
-
return { delivered: "answer", question_id: ask.request_id };
|
|
1226
|
-
}
|
|
1227
|
-
if (!live) {
|
|
1228
|
-
if (r.end) throw new BoxToolError("already_finished");
|
|
1229
|
-
this.spawnRun(r, a.text, true);
|
|
1230
|
-
this.remember(r, a.command_id, "start");
|
|
1231
|
-
return { delivered: "start" };
|
|
1237
|
+
if (question && !a.answer) {
|
|
1238
|
+
return {
|
|
1239
|
+
delivered: "question_pending",
|
|
1240
|
+
question: questionText(question),
|
|
1241
|
+
questions: pending.length
|
|
1242
|
+
};
|
|
1232
1243
|
}
|
|
1233
|
-
if (
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1244
|
+
if (question) {
|
|
1245
|
+
const receipt2 = await this.dispatch({
|
|
1246
|
+
type: "runtime-request.respond",
|
|
1247
|
+
commandId: a.command_id,
|
|
1248
|
+
threadId: a.thread_id,
|
|
1249
|
+
requestId: question.request_id,
|
|
1250
|
+
answers: Object.fromEntries(question.questions.map((q) => [q.id, a.text]))
|
|
1251
|
+
});
|
|
1252
|
+
return { sequence: receipt2.sequence, delivered: "answer", question_id: question.request_id };
|
|
1239
1253
|
}
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
this.remember(r, a.command_id, delivered);
|
|
1246
|
-
this.log(`${delivered} work=${r.work_id}`);
|
|
1247
|
-
return { delivered };
|
|
1248
|
-
}
|
|
1249
|
-
async interrupt(id) {
|
|
1250
|
-
const r = this.record(id);
|
|
1251
|
-
const live = this.lives.get(r.work_id);
|
|
1252
|
-
if (!live) {
|
|
1253
|
-
if (r.end) return { ok: true, was_running: false };
|
|
1254
|
-
const orphan = r.pid !== null && this.alive(r.pid, r);
|
|
1255
|
-
if (orphan && r.pid !== null) {
|
|
1256
|
-
try {
|
|
1257
|
-
process.kill(r.pid, "SIGINT");
|
|
1258
|
-
} catch {
|
|
1259
|
-
}
|
|
1254
|
+
if (a.mode === "steer") {
|
|
1255
|
+
for (let waited = 0; waited < STEER_WAIT_MS; waited += STEER_POLL_MS) {
|
|
1256
|
+
if (!activeRun(p.runs ?? []) || steerableRun(p)) break;
|
|
1257
|
+
await sleep(STEER_POLL_MS);
|
|
1258
|
+
p = await this.readProjection(a.thread_id);
|
|
1260
1259
|
}
|
|
1261
|
-
await this.end(r, { kind: "failed", summary: "The run was stopped." });
|
|
1262
|
-
return { ok: true, was_running: orphan };
|
|
1263
|
-
}
|
|
1264
|
-
live.interrupted = true;
|
|
1265
|
-
live.child.kill("SIGINT");
|
|
1266
|
-
const timer = setTimeout(() => {
|
|
1267
|
-
if (live.child.exitCode === null && live.child.signalCode === null)
|
|
1268
|
-
live.child.kill("SIGTERM");
|
|
1269
|
-
}, this.deps.interruptGraceMs ?? 1e4);
|
|
1270
|
-
timer.unref();
|
|
1271
|
-
this.log(`interrupt work=${r.work_id}`);
|
|
1272
|
-
return { ok: true, was_running: true };
|
|
1273
|
-
}
|
|
1274
|
-
watch(id, onEvent) {
|
|
1275
|
-
const set = this.listeners.get(id) ?? /* @__PURE__ */ new Set();
|
|
1276
|
-
set.add(onEvent);
|
|
1277
|
-
this.listeners.set(id, set);
|
|
1278
|
-
const r = this.runs.get(id);
|
|
1279
|
-
const unwatch = () => set.delete(onEvent);
|
|
1280
|
-
if (!r) {
|
|
1281
|
-
onEvent({ kind: "failed", summary: "This run is not on the runner any more." });
|
|
1282
|
-
return unwatch;
|
|
1283
1260
|
}
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1261
|
+
const steer = a.mode === "steer" ? steerableRun(p) : null;
|
|
1262
|
+
const active = activeRun(p.runs ?? []);
|
|
1263
|
+
if (!active && this.deps.watched?.({ thread_id: a.thread_id })?.settled)
|
|
1264
|
+
throw new BoxToolError("already_finished");
|
|
1265
|
+
const receipt = await this.dispatch({
|
|
1266
|
+
type: "message.dispatch",
|
|
1267
|
+
commandId: a.command_id,
|
|
1268
|
+
threadId: a.thread_id,
|
|
1269
|
+
messageId: a.command_id,
|
|
1270
|
+
text: a.text,
|
|
1271
|
+
attachments: [],
|
|
1272
|
+
dispatchMode: steer ? { type: "steer_active", targetRunId: steer.id } : active ? { type: "queue_after_active" } : { type: "start_immediately" },
|
|
1273
|
+
createdBy: "user",
|
|
1274
|
+
creationSource: "mcp"
|
|
1275
|
+
});
|
|
1276
|
+
return { sequence: receipt.sequence, delivered: steer ? "steer" : active ? "queue" : "start" };
|
|
1294
1277
|
}
|
|
1295
|
-
/**
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
/** One checkout, one run: two harnesses editing the same files at once would undo each other. */
|
|
1304
|
-
refuseBusy(repo) {
|
|
1305
|
-
if ([...this.runs.values()].some((r) => r.repo === repo && !r.end))
|
|
1306
|
-
throw new BoxToolError("repo_busy");
|
|
1307
|
-
}
|
|
1308
|
-
/** One question at a time, oldest first, so a yes answers the prompt the owner read. */
|
|
1309
|
-
askNext(r, live) {
|
|
1310
|
-
const next = live.asks[0];
|
|
1311
|
-
if (!next) return;
|
|
1312
|
-
this.log(`question work=${r.work_id} tool=${next.tool}`);
|
|
1313
|
-
this.emit(r.work_id, { kind: "question", question_id: next.request_id, summary: next.summary });
|
|
1314
|
-
}
|
|
1315
|
-
/** A run left open by a daemon that died: wait for its old process to go, then resume it once. */
|
|
1316
|
-
async recover(r) {
|
|
1317
|
-
if (this.recovering.has(r.work_id)) return;
|
|
1318
|
-
this.recovering.add(r.work_id);
|
|
1278
|
+
/**
|
|
1279
|
+
* Stop the running turn. A thread with nothing running answers
|
|
1280
|
+
* `was_running: false`, and so does a run that ended while the interrupt
|
|
1281
|
+
* was on its way: T3 refuses that interrupt, and the owner's ask is met.
|
|
1282
|
+
*/
|
|
1283
|
+
async interrupt(threadId, commandId) {
|
|
1284
|
+
const run = activeRun((await this.readProjection(threadId)).runs ?? []);
|
|
1285
|
+
if (!run) return { ok: true, was_running: false };
|
|
1319
1286
|
try {
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1287
|
+
await this.dispatch({
|
|
1288
|
+
type: "run.interrupt",
|
|
1289
|
+
commandId,
|
|
1290
|
+
threadId,
|
|
1291
|
+
runId: run.id,
|
|
1292
|
+
reason: "Stopped from Cloop"
|
|
1293
|
+
});
|
|
1294
|
+
} catch (err) {
|
|
1295
|
+
if (activeRun((await this.readProjection(threadId)).runs ?? [])) throw err;
|
|
1296
|
+
return { ok: true, was_running: false };
|
|
1328
1297
|
}
|
|
1298
|
+
return { ok: true, was_running: true };
|
|
1329
1299
|
}
|
|
1330
|
-
|
|
1331
|
-
const {
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1300
|
+
async readThread(id) {
|
|
1301
|
+
const { status, settled, pr_url, last_assistant_text } = outcomeOf(
|
|
1302
|
+
await this.readProjection(id)
|
|
1303
|
+
);
|
|
1304
|
+
return { status, settled, pr_url, last_assistant_text };
|
|
1305
|
+
}
|
|
1306
|
+
/**
|
|
1307
|
+
* Subscribe to the thread and resubscribe whenever the stream ends. A thread
|
|
1308
|
+
* that settled while nobody watched shows a terminal run in its first
|
|
1309
|
+
* snapshot. A question is reported on every update it is still pending.
|
|
1310
|
+
*/
|
|
1311
|
+
watch(threadId, onEvent) {
|
|
1312
|
+
let stopped = false;
|
|
1313
|
+
let finishing = false;
|
|
1314
|
+
let live = null;
|
|
1315
|
+
const retry = () => {
|
|
1316
|
+
if (stopped) return;
|
|
1317
|
+
const timer = setTimeout(() => void follow(), this.deps.retryMs ?? 1e4);
|
|
1318
|
+
timer.unref?.();
|
|
1344
1319
|
};
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
});
|
|
1356
|
-
const lines = createInterface({ input: child.stdout });
|
|
1357
|
-
lines.on("line", (line2) => {
|
|
1358
|
-
for (const item of dialect.parse(line2, r)) this.onItem(r, live, item);
|
|
1359
|
-
});
|
|
1360
|
-
child.on("error", (err) => {
|
|
1361
|
-
this.log(`spawn failed work=${r.work_id}: ${err.message.slice(0, 200)}`);
|
|
1362
|
-
});
|
|
1363
|
-
child.on("close", (code, signal) => void this.onExit(r, live, code, signal));
|
|
1364
|
-
}
|
|
1365
|
-
onItem(r, live, item) {
|
|
1366
|
-
switch (item.type) {
|
|
1367
|
-
case "session":
|
|
1368
|
-
if (r.session_id !== item.id) {
|
|
1369
|
-
r.session_id = item.id;
|
|
1370
|
-
this.save();
|
|
1320
|
+
const finish = async () => {
|
|
1321
|
+
if (stopped || finishing) return;
|
|
1322
|
+
finishing = true;
|
|
1323
|
+
let outcome;
|
|
1324
|
+
try {
|
|
1325
|
+
outcome = outcomeOf(await this.readProjection(threadId));
|
|
1326
|
+
const grace = this.deps.prGraceMs ?? 6e4;
|
|
1327
|
+
if (outcome.settled && outcome.kind === "settled" && !outcome.pr_url && grace > 0) {
|
|
1328
|
+
await sleep(grace);
|
|
1329
|
+
outcome = outcomeOf(await this.readProjection(threadId));
|
|
1371
1330
|
}
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
const changed = item.name !== live.lastTool;
|
|
1379
|
-
live.lastTool = item.name;
|
|
1380
|
-
this.progress(r, live, item.target ? `${item.name} ${item.target}` : item.name, changed);
|
|
1331
|
+
} catch (err) {
|
|
1332
|
+
this.log(
|
|
1333
|
+
`read failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
|
|
1334
|
+
);
|
|
1335
|
+
finishing = false;
|
|
1336
|
+
retry();
|
|
1381
1337
|
return;
|
|
1382
1338
|
}
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
const wasAsked = live.asks[0]?.request_id === item.request_id;
|
|
1389
|
-
live.asks = live.asks.filter((x) => x.request_id !== item.request_id);
|
|
1390
|
-
if (wasAsked) this.askNext(r, live);
|
|
1339
|
+
if (stopped) return;
|
|
1340
|
+
if (!outcome.settled) {
|
|
1341
|
+
finishing = false;
|
|
1342
|
+
this.log(`run continues thread=${threadId} run=${outcome.status}; watching on`);
|
|
1343
|
+
if (!live) void follow();
|
|
1391
1344
|
return;
|
|
1392
1345
|
}
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
this.emit(r.work_id, {
|
|
1406
|
-
kind: "progress",
|
|
1407
|
-
summary: line2.replace(/\s+/g, " ").trim().slice(0, 200)
|
|
1408
|
-
});
|
|
1409
|
-
}
|
|
1410
|
-
async onExit(r, live, code, signal) {
|
|
1411
|
-
if (this.lives.get(r.work_id) === live) this.lives.delete(r.work_id);
|
|
1412
|
-
if (this.stopping || r.end) return;
|
|
1413
|
-
const exit = signal ? `signal ${signal}` : `code ${code}`;
|
|
1414
|
-
this.log(
|
|
1415
|
-
`exit work=${r.work_id} ${exit} result=${live.result ? live.result.ok ? "ok" : "error" : "none"}`
|
|
1416
|
-
);
|
|
1417
|
-
if (live.interrupted) {
|
|
1418
|
-
await this.end(r, { kind: "failed", summary: "The run was stopped." });
|
|
1419
|
-
return;
|
|
1420
|
-
}
|
|
1421
|
-
if (live.next) {
|
|
1422
|
-
this.spawnRun(r, live.next, true);
|
|
1423
|
-
return;
|
|
1424
|
-
}
|
|
1425
|
-
if (code === 0 && live.result?.ok) {
|
|
1426
|
-
const text = live.result.text?.trim() || r.last_text;
|
|
1427
|
-
const { pr, note } = await this.outcome(r, text);
|
|
1428
|
-
const summary = [note, text].filter(Boolean).join(" ").replace(/\s+/g, " ");
|
|
1429
|
-
await this.end(r, {
|
|
1430
|
-
kind: "settled",
|
|
1431
|
-
...summary ? { summary: summary.slice(0, SUMMARY_MAX) } : {},
|
|
1432
|
-
...pr ? { pr_url: pr } : {}
|
|
1433
|
-
});
|
|
1434
|
-
return;
|
|
1435
|
-
}
|
|
1436
|
-
if (live.stderr)
|
|
1437
|
-
this.log(`stderr work=${r.work_id}: ${live.stderr.trim().split("\n").at(-1)?.slice(0, 200)}`);
|
|
1438
|
-
await this.end(r, {
|
|
1439
|
-
kind: "failed",
|
|
1440
|
-
summary: live.result ? "The run ended with an error." : `The run exited with ${exit}.`
|
|
1441
|
-
});
|
|
1442
|
-
}
|
|
1443
|
-
/**
|
|
1444
|
-
* The PR a run produced: one its last text names, else the PR of the
|
|
1445
|
-
* branch, but only when the run moved HEAD. A run that left HEAD where it
|
|
1446
|
-
* started produced nothing, and the branch's PR belongs to someone else's
|
|
1447
|
-
* work. A run that committed without pushing says so.
|
|
1448
|
-
*/
|
|
1449
|
-
async outcome(r, text) {
|
|
1450
|
-
const named = prUrlIn(text);
|
|
1451
|
-
if (named) return { pr: named };
|
|
1452
|
-
if (!r.head_at_launch) return { pr: null };
|
|
1453
|
-
const head = await this.repo.head(r.repo);
|
|
1454
|
-
if (!head || head === r.head_at_launch) return { pr: null };
|
|
1455
|
-
const pr = await this.repo.branchPr(r.repo);
|
|
1456
|
-
if (pr) return { pr };
|
|
1457
|
-
return await this.repo.pushed(r.repo) ? { pr: null } : { pr: null, note: `Committed ${head.slice(0, 7)}, not pushed.` };
|
|
1458
|
-
}
|
|
1459
|
-
async end(r, end) {
|
|
1460
|
-
if (r.end) return;
|
|
1461
|
-
r.end = { ...end, at: new Date(this.now()).toISOString() };
|
|
1462
|
-
r.pid = null;
|
|
1463
|
-
this.save();
|
|
1464
|
-
this.emit(r.work_id, end);
|
|
1465
|
-
}
|
|
1466
|
-
emit(id, event) {
|
|
1467
|
-
for (const listener of [...this.listeners.get(id) ?? []]) listener(event);
|
|
1468
|
-
}
|
|
1469
|
-
write(live, line2) {
|
|
1470
|
-
live.child.stdin?.write(line2);
|
|
1471
|
-
}
|
|
1472
|
-
remember(r, commandId, delivered) {
|
|
1473
|
-
r.commands = [
|
|
1474
|
-
...r.commands ?? [],
|
|
1475
|
-
[commandId, delivered]
|
|
1476
|
-
].slice(-COMMANDS_KEPT);
|
|
1477
|
-
this.save();
|
|
1478
|
-
}
|
|
1479
|
-
record(id) {
|
|
1480
|
-
const r = this.runs.get(id);
|
|
1481
|
-
if (!r) throw new BoxToolError("bad_args");
|
|
1482
|
-
return r;
|
|
1483
|
-
}
|
|
1484
|
-
statusOf(r) {
|
|
1485
|
-
if (this.lives.has(r.work_id)) return "running";
|
|
1486
|
-
if (!r.end) return "pending";
|
|
1487
|
-
return r.end.kind === "settled" ? "completed" : "failed";
|
|
1488
|
-
}
|
|
1489
|
-
load() {
|
|
1490
|
-
try {
|
|
1491
|
-
const raw = JSON.parse(readFileSync2(this.file, "utf-8"));
|
|
1492
|
-
const cutoff = this.now() - KEEP_MS2;
|
|
1493
|
-
return Array.isArray(raw) ? raw.filter(
|
|
1494
|
-
(r) => typeof r?.work_id === "string" && typeof r?.repo === "string" && !(r.end && Date.parse(r.end.at) < cutoff)
|
|
1495
|
-
) : [];
|
|
1496
|
-
} catch {
|
|
1497
|
-
return [];
|
|
1498
|
-
}
|
|
1499
|
-
}
|
|
1500
|
-
save() {
|
|
1501
|
-
mkdirSync2(dirname2(this.file), { recursive: true, mode: 448 });
|
|
1502
|
-
const tmp = `${this.file}.tmp`;
|
|
1503
|
-
writeFileSync2(tmp, `${JSON.stringify([...this.runs.values()], null, 2)}
|
|
1504
|
-
`, { mode: 384 });
|
|
1505
|
-
chmodSync2(tmp, 384);
|
|
1506
|
-
renameSync2(tmp, this.file);
|
|
1507
|
-
}
|
|
1508
|
-
};
|
|
1509
|
-
|
|
1510
|
-
// src/drivers/claude-code.ts
|
|
1511
|
-
var SUBSCRIPTIONS = {
|
|
1512
|
-
max: "Claude Max",
|
|
1513
|
-
pro: "Claude Pro",
|
|
1514
|
-
team: "Claude Team",
|
|
1515
|
-
enterprise: "Claude Enterprise"
|
|
1516
|
-
};
|
|
1517
|
-
var YES_WORDS = /* @__PURE__ */ new Set([
|
|
1518
|
-
"y",
|
|
1519
|
-
"yes",
|
|
1520
|
-
"yep",
|
|
1521
|
-
"yeah",
|
|
1522
|
-
"allow",
|
|
1523
|
-
"allow it",
|
|
1524
|
-
"ok",
|
|
1525
|
-
"okay",
|
|
1526
|
-
"approve",
|
|
1527
|
-
"approved",
|
|
1528
|
-
"go ahead",
|
|
1529
|
-
"sure",
|
|
1530
|
-
"do it"
|
|
1531
|
-
]);
|
|
1532
|
-
function isYes(reply) {
|
|
1533
|
-
return YES_WORDS.has(
|
|
1534
|
-
reply.trim().toLowerCase().replace(/[.!\s]+$/, "")
|
|
1535
|
-
);
|
|
1536
|
-
}
|
|
1537
|
-
function exec(bin, args) {
|
|
1538
|
-
return new Promise(
|
|
1539
|
-
(resolve3) => execFile3(
|
|
1540
|
-
bin,
|
|
1541
|
-
args,
|
|
1542
|
-
{ timeout: 1e4, encoding: "utf-8" },
|
|
1543
|
-
(err, out2) => resolve3(err ? null : String(out2))
|
|
1544
|
-
)
|
|
1545
|
-
);
|
|
1546
|
-
}
|
|
1547
|
-
function claudeAccount(raw) {
|
|
1548
|
-
try {
|
|
1549
|
-
const auth = JSON.parse(raw ?? "");
|
|
1550
|
-
if (auth.loggedIn !== true) return { signedIn: false, account: null };
|
|
1551
|
-
const plan = auth.subscriptionType ? SUBSCRIPTIONS[auth.subscriptionType] : void 0;
|
|
1552
|
-
return {
|
|
1553
|
-
signedIn: true,
|
|
1554
|
-
account: plan ?? (auth.authMethod === "claude.ai" ? "Claude" : "API key")
|
|
1346
|
+
stopped = true;
|
|
1347
|
+
live?.close();
|
|
1348
|
+
const pr = outcome.pr_url ? { pr_url: outcome.pr_url } : {};
|
|
1349
|
+
if (outcome.kind === "failed") {
|
|
1350
|
+
onEvent({ kind: "failed", summary: `The run ended ${outcome.status}.`, ...pr });
|
|
1351
|
+
} else {
|
|
1352
|
+
onEvent({
|
|
1353
|
+
kind: "settled",
|
|
1354
|
+
...outcome.last_assistant_text ? { summary: outcome.last_assistant_text } : {},
|
|
1355
|
+
...pr
|
|
1356
|
+
});
|
|
1357
|
+
}
|
|
1555
1358
|
};
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
}
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
}
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
const path = pathOf(fields);
|
|
1605
|
-
const where = path ? ` on ${shownPath(path, repo)}` : "";
|
|
1606
|
-
return `Claude Code asks to use ${tool}${where}. ${REPLY}`;
|
|
1607
|
-
}
|
|
1608
|
-
function line(value) {
|
|
1609
|
-
return `${JSON.stringify(value)}
|
|
1610
|
-
`;
|
|
1611
|
-
}
|
|
1612
|
-
function userMessage(run2, text, priority) {
|
|
1613
|
-
return {
|
|
1614
|
-
type: "user",
|
|
1615
|
-
message: { role: "user", content: [{ type: "text", text }] },
|
|
1616
|
-
parent_tool_use_id: null,
|
|
1617
|
-
session_id: run2.session_id ?? run2.work_id,
|
|
1618
|
-
...priority ? { priority } : {}
|
|
1619
|
-
};
|
|
1620
|
-
}
|
|
1621
|
-
function parseClaudeLine(raw, run2) {
|
|
1622
|
-
let msg;
|
|
1623
|
-
try {
|
|
1624
|
-
msg = JSON.parse(raw);
|
|
1625
|
-
} catch {
|
|
1626
|
-
return [];
|
|
1627
|
-
}
|
|
1628
|
-
if (msg.type === "system" && msg.subtype === "init" && typeof msg.session_id === "string") {
|
|
1629
|
-
return [{ type: "session", id: msg.session_id }];
|
|
1630
|
-
}
|
|
1631
|
-
if (msg.type === "assistant") {
|
|
1632
|
-
const content = msg.message?.content;
|
|
1633
|
-
if (!Array.isArray(content)) return [];
|
|
1634
|
-
return content.flatMap((block) => {
|
|
1635
|
-
if (block?.type === "text" && typeof block.text === "string" && block.text.trim())
|
|
1636
|
-
return [{ type: "text", text: block.text }];
|
|
1637
|
-
if (block?.type === "tool_use" && typeof block.name === "string" && block.name !== "AskUserQuestion") {
|
|
1638
|
-
const path = pathOf(block.input);
|
|
1639
|
-
return [{ type: "tool", name: block.name, ...path ? { target: basename2(path) } : {} }];
|
|
1359
|
+
const follow = async () => {
|
|
1360
|
+
if (stopped || live) return;
|
|
1361
|
+
const runs = /* @__PURE__ */ new Map();
|
|
1362
|
+
const requests = /* @__PURE__ */ new Map();
|
|
1363
|
+
const asks = /* @__PURE__ */ new Map();
|
|
1364
|
+
const keepAsk = (item) => {
|
|
1365
|
+
if (item.type === "user_input_request" && item.requestId) asks.set(item.requestId, item);
|
|
1366
|
+
};
|
|
1367
|
+
let settledByHand = false;
|
|
1368
|
+
let stream;
|
|
1369
|
+
try {
|
|
1370
|
+
stream = await this.t3.stream("orchestration.subscribeThread", { threadId }, (raw) => {
|
|
1371
|
+
const item = raw;
|
|
1372
|
+
if (item.kind === "snapshot" && "projection" in item) {
|
|
1373
|
+
for (const r of item.projection.runs ?? []) runs.set(r.id, r);
|
|
1374
|
+
for (const r of item.projection.runtimeRequests ?? []) requests.set(r.id, r);
|
|
1375
|
+
for (const t of item.projection.turnItems ?? []) keepAsk(t);
|
|
1376
|
+
settledByHand ||= Boolean(item.projection.thread?.settledAt);
|
|
1377
|
+
} else if (item.kind === "event" && "event" in item) {
|
|
1378
|
+
const { type, payload } = item.event;
|
|
1379
|
+
if (type.startsWith("run.") && typeof payload?.id === "string") {
|
|
1380
|
+
runs.set(payload.id, payload);
|
|
1381
|
+
} else if (type === "runtime-request.updated" && typeof payload?.id === "string") {
|
|
1382
|
+
requests.set(payload.id, payload);
|
|
1383
|
+
} else if (type === "turn-item.updated" && payload) {
|
|
1384
|
+
keepAsk(payload);
|
|
1385
|
+
} else if (type.startsWith("thread.") && payload?.settledAt) {
|
|
1386
|
+
settledByHand = true;
|
|
1387
|
+
} else return;
|
|
1388
|
+
} else return;
|
|
1389
|
+
if (settledByHand || isTerminal([...runs.values()])) {
|
|
1390
|
+
void finish();
|
|
1391
|
+
return;
|
|
1392
|
+
}
|
|
1393
|
+
const pending = pendingQuestions({
|
|
1394
|
+
runtimeRequests: [...requests.values()],
|
|
1395
|
+
turnItems: [...asks.values()]
|
|
1396
|
+
});
|
|
1397
|
+
for (const q of pending) {
|
|
1398
|
+
onEvent({ kind: "question", question_id: q.request_id, summary: questionText(q) });
|
|
1399
|
+
}
|
|
1400
|
+
});
|
|
1401
|
+
} catch (err) {
|
|
1402
|
+
this.log(
|
|
1403
|
+
`watch failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
|
|
1404
|
+
);
|
|
1405
|
+
retry();
|
|
1406
|
+
return;
|
|
1640
1407
|
}
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
if (msg.type === "control_request") {
|
|
1645
|
-
const request = msg.request;
|
|
1646
|
-
if (request?.subtype !== "can_use_tool" || typeof msg.request_id !== "string") return [];
|
|
1647
|
-
const tool = request.tool_name ?? "a tool";
|
|
1648
|
-
return [
|
|
1649
|
-
{
|
|
1650
|
-
type: "ask",
|
|
1651
|
-
request_id: msg.request_id,
|
|
1652
|
-
tool,
|
|
1653
|
-
input: request.input ?? {},
|
|
1654
|
-
summary: askSummary(tool, request.input, run2.repo)
|
|
1408
|
+
if (stopped) {
|
|
1409
|
+
stream.close();
|
|
1410
|
+
return;
|
|
1655
1411
|
}
|
|
1656
|
-
|
|
1412
|
+
live = stream;
|
|
1413
|
+
const reason = await stream.done;
|
|
1414
|
+
live = null;
|
|
1415
|
+
if (stopped || finishing) return;
|
|
1416
|
+
this.log(`watch ended thread=${threadId} reason=${reason}; resubscribing`);
|
|
1417
|
+
retry();
|
|
1418
|
+
};
|
|
1419
|
+
void follow();
|
|
1420
|
+
return () => {
|
|
1421
|
+
stopped = true;
|
|
1422
|
+
live?.close();
|
|
1423
|
+
};
|
|
1657
1424
|
}
|
|
1658
|
-
|
|
1659
|
-
return
|
|
1425
|
+
readProjection(threadId) {
|
|
1426
|
+
return this.t3.rpc("orchestration.getThreadProjection", { threadId });
|
|
1660
1427
|
}
|
|
1661
|
-
|
|
1662
|
-
return
|
|
1663
|
-
{
|
|
1664
|
-
type: "result",
|
|
1665
|
-
ok: msg.subtype === "success" && msg.is_error !== true,
|
|
1666
|
-
...typeof msg.result === "string" ? { text: msg.result } : {}
|
|
1667
|
-
}
|
|
1668
|
-
];
|
|
1428
|
+
dispatch(command) {
|
|
1429
|
+
return this.t3.rpc("orchestration.dispatchCommand", command);
|
|
1669
1430
|
}
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
name: "claude-code",
|
|
1675
|
-
aliases: ["claude-code", "claudeAgent", "claude"],
|
|
1676
|
-
bin,
|
|
1677
|
-
capabilities: ["view", "start", "steer", "report"],
|
|
1678
|
-
keepsStdin: true,
|
|
1679
|
-
args(run2, resume) {
|
|
1680
|
-
return [
|
|
1681
|
-
"--print",
|
|
1682
|
-
"--verbose",
|
|
1683
|
-
"--output-format",
|
|
1684
|
-
"stream-json",
|
|
1685
|
-
"--input-format",
|
|
1686
|
-
"stream-json",
|
|
1687
|
-
"--permission-prompt-tool",
|
|
1688
|
-
"stdio",
|
|
1689
|
-
"--permission-mode",
|
|
1690
|
-
permissionMode(run2.runtime_mode),
|
|
1691
|
-
"--add-dir",
|
|
1692
|
-
run2.repo,
|
|
1693
|
-
...resume ? ["--resume", run2.session_id ?? run2.work_id] : ["--session-id", run2.work_id],
|
|
1694
|
-
...run2.model ? ["--model", run2.model] : []
|
|
1695
|
-
];
|
|
1696
|
-
},
|
|
1697
|
-
opening(run2, prompt) {
|
|
1698
|
-
return line({
|
|
1699
|
-
type: "control_request",
|
|
1700
|
-
request_id: "cloop-init",
|
|
1701
|
-
request: { subtype: "initialize" }
|
|
1702
|
-
}) + line(userMessage(run2, prompt));
|
|
1703
|
-
},
|
|
1704
|
-
userLine(run2, text, mode) {
|
|
1705
|
-
return line(userMessage(run2, text, mode === "steer" ? "now" : "next"));
|
|
1706
|
-
},
|
|
1707
|
-
answerLine(ask, text) {
|
|
1708
|
-
const input = ask.input ?? {};
|
|
1709
|
-
const response = ask.tool === "AskUserQuestion" ? {
|
|
1710
|
-
behavior: "allow",
|
|
1711
|
-
updatedInput: {
|
|
1712
|
-
...input,
|
|
1713
|
-
answers: Object.fromEntries(questionsOf(input).map((q) => [q.question, text]))
|
|
1714
|
-
}
|
|
1715
|
-
} : isYes(text) ? { behavior: "allow", updatedInput: input } : { behavior: "deny", message: text };
|
|
1716
|
-
return line({
|
|
1717
|
-
type: "control_response",
|
|
1718
|
-
response: { subtype: "success", request_id: ask.request_id, response }
|
|
1719
|
-
});
|
|
1720
|
-
},
|
|
1721
|
-
parse: parseClaudeLine,
|
|
1722
|
-
owns: (run2, command) => command.includes(basename2(bin)) && [run2.work_id, run2.session_id].some((id) => id !== null && command.includes(id)),
|
|
1723
|
-
probe: () => probeClaude(bin)
|
|
1724
|
-
};
|
|
1725
|
-
}
|
|
1726
|
-
|
|
1727
|
-
// src/drivers/codex.ts
|
|
1728
|
-
import { execFile as execFile4 } from "child_process";
|
|
1729
|
-
import { basename as basename3 } from "path";
|
|
1730
|
-
var SANDBOX = {
|
|
1731
|
-
"approval-required": "read-only",
|
|
1732
|
-
"auto-accept-edits": "workspace-write",
|
|
1733
|
-
auto: "workspace-write",
|
|
1734
|
-
"full-access": "danger-full-access"
|
|
1735
|
-
};
|
|
1736
|
-
function exec2(bin, args) {
|
|
1737
|
-
return new Promise(
|
|
1738
|
-
(resolve3) => execFile4(
|
|
1739
|
-
bin,
|
|
1740
|
-
args,
|
|
1741
|
-
{ timeout: 1e4, encoding: "utf-8" },
|
|
1742
|
-
(err, out2, errOut) => resolve3({ ok: !err, out: `${out2}${errOut}` })
|
|
1743
|
-
)
|
|
1744
|
-
);
|
|
1745
|
-
}
|
|
1746
|
-
function codexAccount(ok, out2) {
|
|
1747
|
-
if (!ok || !/logged in/i.test(out2) || /not logged in/i.test(out2))
|
|
1748
|
-
return { signedIn: false, account: null };
|
|
1749
|
-
return { signedIn: true, account: /chatgpt/i.test(out2) ? "ChatGPT" : "API key" };
|
|
1750
|
-
}
|
|
1751
|
-
async function probeCodex(bin = "codex") {
|
|
1752
|
-
const version = await exec2(bin, ["--version"]);
|
|
1753
|
-
if (!version.ok) return null;
|
|
1754
|
-
const status = await exec2(bin, ["login", "status"]);
|
|
1755
|
-
const { signedIn, account } = codexAccount(status.ok, status.out);
|
|
1756
|
-
return {
|
|
1757
|
-
id: "codex",
|
|
1758
|
-
name: "Codex",
|
|
1759
|
-
version: version.out.trim().split(/\s+/).at(-1) ?? null,
|
|
1760
|
-
ready: signedIn,
|
|
1761
|
-
signedIn,
|
|
1762
|
-
account,
|
|
1763
|
-
defaultModel: null,
|
|
1764
|
-
experimental: true
|
|
1431
|
+
sessions = {
|
|
1432
|
+
list: null,
|
|
1433
|
+
at: 0,
|
|
1434
|
+
refreshing: false
|
|
1765
1435
|
};
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1436
|
+
/**
|
|
1437
|
+
* T3's client sessions, from the cache. `t3 auth session list` starts a whole
|
|
1438
|
+
* CLI and took 5 to 14 s on a loaded box, so status never waits on it: it
|
|
1439
|
+
* answers with the last list and refreshes it in the background at most
|
|
1440
|
+
* once per SESSIONS_TTL_MS.
|
|
1441
|
+
*/
|
|
1442
|
+
listSessions() {
|
|
1443
|
+
const bin = this.deps.t3Bin;
|
|
1444
|
+
if (!bin) return null;
|
|
1445
|
+
const stale = Date.now() - this.sessions.at > SESSIONS_TTL_MS;
|
|
1446
|
+
if (stale && !this.sessions.refreshing) {
|
|
1447
|
+
this.sessions.refreshing = true;
|
|
1448
|
+
const done = (raw) => {
|
|
1449
|
+
try {
|
|
1450
|
+
if (raw !== null) this.sessions.list = JSON.parse(raw);
|
|
1451
|
+
} catch {
|
|
1452
|
+
}
|
|
1453
|
+
this.sessions.at = Date.now();
|
|
1454
|
+
this.sessions.refreshing = false;
|
|
1455
|
+
};
|
|
1456
|
+
(this.deps.execAsync ?? execFile3)(
|
|
1457
|
+
bin,
|
|
1458
|
+
["auth", "session", "list", ...t3BaseDirArgs(), "--json"],
|
|
1459
|
+
{
|
|
1460
|
+
encoding: "utf-8",
|
|
1461
|
+
env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
|
|
1462
|
+
timeout: 3e4
|
|
1463
|
+
},
|
|
1464
|
+
(err, stdout) => done(err ? null : String(stdout))
|
|
1465
|
+
);
|
|
1466
|
+
}
|
|
1467
|
+
return this.sessions.list;
|
|
1773
1468
|
}
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1469
|
+
/**
|
|
1470
|
+
* The branch the project's checkout is on, from origin when origin has it. A
|
|
1471
|
+
* local branch can lag origin by hundreds of commits on a box nobody pulls on,
|
|
1472
|
+
* and T3 starts the worktree from the ref exactly as given.
|
|
1473
|
+
*/
|
|
1474
|
+
baseRefFor(root) {
|
|
1475
|
+
const git = (args) => String(
|
|
1476
|
+
(this.deps.exec ?? execFileSync2)("git", ["-C", root, ...args], {
|
|
1477
|
+
encoding: "utf-8",
|
|
1478
|
+
env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
|
|
1479
|
+
timeout: 5e3
|
|
1480
|
+
})
|
|
1481
|
+
).trim();
|
|
1482
|
+
let branch;
|
|
1483
|
+
try {
|
|
1484
|
+
branch = git(["rev-parse", "--abbrev-ref", "HEAD"]);
|
|
1485
|
+
} catch {
|
|
1486
|
+
return "HEAD";
|
|
1487
|
+
}
|
|
1488
|
+
if (!branch || branch === "HEAD") return "HEAD";
|
|
1489
|
+
try {
|
|
1490
|
+
git(["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}`]);
|
|
1491
|
+
return `origin/${branch}`;
|
|
1492
|
+
} catch {
|
|
1493
|
+
return branch;
|
|
1494
|
+
}
|
|
1791
1495
|
}
|
|
1792
|
-
|
|
1793
|
-
if (msg.type === "turn.failed") return [{ type: "result", ok: false }];
|
|
1794
|
-
return [];
|
|
1795
|
-
}
|
|
1796
|
-
function codexDialect(bin = "codex") {
|
|
1797
|
-
return {
|
|
1798
|
-
name: "codex",
|
|
1799
|
-
aliases: ["codex"],
|
|
1800
|
-
bin,
|
|
1801
|
-
capabilities: ["view", "start", "report"],
|
|
1802
|
-
keepsStdin: false,
|
|
1803
|
-
args(run2, resume) {
|
|
1804
|
-
const model = run2.model ? ["--model", run2.model] : [];
|
|
1805
|
-
const sandbox = SANDBOX[run2.runtime_mode ?? "auto-accept-edits"];
|
|
1806
|
-
return resume && run2.session_id ? [
|
|
1807
|
-
"exec",
|
|
1808
|
-
"resume",
|
|
1809
|
-
run2.session_id,
|
|
1810
|
-
"--json",
|
|
1811
|
-
"-c",
|
|
1812
|
-
`sandbox_mode="${sandbox}"`,
|
|
1813
|
-
...model,
|
|
1814
|
-
"-"
|
|
1815
|
-
] : ["exec", "--cd", run2.repo, "--json", "--sandbox", sandbox, ...model, "-"];
|
|
1816
|
-
},
|
|
1817
|
-
opening: (_run, prompt) => prompt,
|
|
1818
|
-
parse: parseCodexLine,
|
|
1819
|
-
// A fresh run's command line names no id: Codex makes its session id after the start. So a run is also matched by its exact repository, which one open run per repository makes unique.
|
|
1820
|
-
owns: (run2, command) => command.includes(basename3(bin)) && command.includes("exec") && command.includes("--json") && (run2.session_id !== null && command.includes(run2.session_id) || command.includes(`--cd ${run2.repo} `)),
|
|
1821
|
-
probe: () => probeCodex(bin)
|
|
1822
|
-
};
|
|
1823
|
-
}
|
|
1496
|
+
};
|
|
1824
1497
|
|
|
1825
1498
|
// src/runner-config.ts
|
|
1826
|
-
import { chmodSync as
|
|
1827
|
-
import { homedir as
|
|
1828
|
-
import { dirname as
|
|
1499
|
+
import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
1500
|
+
import { homedir as homedir2 } from "os";
|
|
1501
|
+
import { dirname as dirname2, join as join3 } from "path";
|
|
1829
1502
|
var BOX_FILE = "box.json";
|
|
1830
1503
|
function boxPath() {
|
|
1831
|
-
return process.env.CLOOP_BOX_FILE ?? join3(
|
|
1504
|
+
return process.env.CLOOP_BOX_FILE ?? join3(homedir2(), CONFIG_DIR, BOX_FILE);
|
|
1832
1505
|
}
|
|
1833
1506
|
function isLocal(cfg) {
|
|
1834
1507
|
return cfg.driver === "claude-code" || cfg.driver === "codex";
|
|
@@ -1836,7 +1509,7 @@ function isLocal(cfg) {
|
|
|
1836
1509
|
function readRunnerConfig() {
|
|
1837
1510
|
let parsed;
|
|
1838
1511
|
try {
|
|
1839
|
-
parsed = JSON.parse(
|
|
1512
|
+
parsed = JSON.parse(readFileSync2(boxPath(), "utf-8"));
|
|
1840
1513
|
} catch {
|
|
1841
1514
|
return null;
|
|
1842
1515
|
}
|
|
@@ -1849,17 +1522,17 @@ function readRunnerConfig() {
|
|
|
1849
1522
|
}
|
|
1850
1523
|
function writeBoxConfig(cfg) {
|
|
1851
1524
|
const path = boxPath();
|
|
1852
|
-
|
|
1525
|
+
mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
|
|
1853
1526
|
const temp = `${path}.${process.pid}.tmp`;
|
|
1854
|
-
|
|
1527
|
+
writeFileSync2(temp, `${JSON.stringify(cfg, null, 2)}
|
|
1855
1528
|
`, { mode: 384 });
|
|
1856
|
-
|
|
1857
|
-
|
|
1529
|
+
chmodSync2(temp, 384);
|
|
1530
|
+
renameSync2(temp, path);
|
|
1858
1531
|
}
|
|
1859
1532
|
|
|
1860
1533
|
// src/commands/connect.ts
|
|
1861
1534
|
var DEFAULT_T3_URL = "http://127.0.0.1:3773";
|
|
1862
|
-
var
|
|
1535
|
+
var CLEAN_ENV2 = { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH };
|
|
1863
1536
|
var out = (line2) => console.log(line2);
|
|
1864
1537
|
var bold = (s) => `\x1B[1m${s}\x1B[0m`;
|
|
1865
1538
|
var dim = (s) => `\x1B[2m${s}\x1B[0m`;
|
|
@@ -1871,43 +1544,36 @@ function flag(argv, name) {
|
|
|
1871
1544
|
function flags(argv, name) {
|
|
1872
1545
|
return argv.flatMap((a, i) => a === name && argv[i + 1] ? [argv[i + 1]] : []);
|
|
1873
1546
|
}
|
|
1874
|
-
function compareVersions(a, b) {
|
|
1875
|
-
return a.localeCompare(b, void 0, { numeric: true });
|
|
1876
|
-
}
|
|
1877
|
-
function resolveT3Bin(explicit) {
|
|
1878
|
-
if (explicit) return explicit;
|
|
1879
|
-
if (process.env.T3_BIN) return process.env.T3_BIN;
|
|
1880
|
-
const versions = join4(homedir4(), ".t3", "runtime", "versions");
|
|
1881
|
-
try {
|
|
1882
|
-
const newest = readdirSync(versions).sort(compareVersions).at(-1);
|
|
1883
|
-
if (newest && existsSync(join4(versions, newest, "t3"))) return join4(versions, newest, "t3");
|
|
1884
|
-
} catch {
|
|
1885
|
-
}
|
|
1886
|
-
return which("t3");
|
|
1887
|
-
}
|
|
1888
1547
|
function which(bin) {
|
|
1889
1548
|
try {
|
|
1890
|
-
return execFileSync3("which", [bin], { encoding: "utf-8", env:
|
|
1549
|
+
return execFileSync3("which", [bin], { encoding: "utf-8", env: CLEAN_ENV2 }).trim() || null;
|
|
1891
1550
|
} catch {
|
|
1892
1551
|
return null;
|
|
1893
1552
|
}
|
|
1894
1553
|
}
|
|
1895
|
-
async function mintSession(t3Url,
|
|
1896
|
-
const env = await readEnvironment(t3Url);
|
|
1554
|
+
async function mintSession(t3Url, opts = {}) {
|
|
1555
|
+
const env = await readEnvironment(t3Url, opts.fetchFn);
|
|
1897
1556
|
const protocol = env.orchestrationProtocolVersion ?? 1;
|
|
1898
1557
|
if (protocol < MIN_PROTOCOL) {
|
|
1899
1558
|
throw new Error(
|
|
1900
1559
|
`T3 ${env.serverVersion} speaks orchestration protocol ${protocol}; a workstation needs ${MIN_PROTOCOL} (the V2 nightly or later).`
|
|
1901
1560
|
);
|
|
1902
1561
|
}
|
|
1562
|
+
const sources = opts.sources ?? defaultT3BinSources(homedir3(), opts.stored);
|
|
1563
|
+
const t3Bin = opts.bin ?? pickT3Bin(t3Candidates(env.serverVersion, sources), env.serverVersion);
|
|
1564
|
+
if (!t3Bin) throw new Error("no t3 binary found; pass --t3-bin or set T3_BIN");
|
|
1903
1565
|
const pairing = JSON.parse(
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1566
|
+
runT3(t3Bin, [
|
|
1567
|
+
"auth",
|
|
1568
|
+
"pairing",
|
|
1569
|
+
"create",
|
|
1570
|
+
...t3BaseDirArgs(sources.env),
|
|
1571
|
+
"--ttl",
|
|
1572
|
+
"5m",
|
|
1573
|
+
"--json"
|
|
1574
|
+
])
|
|
1909
1575
|
);
|
|
1910
|
-
const token = await exchangePairing(t3Url, pairing.credential, "cloop box");
|
|
1576
|
+
const token = await exchangePairing(t3Url, pairing.credential, "cloop box", opts.fetchFn);
|
|
1911
1577
|
return {
|
|
1912
1578
|
t3Url,
|
|
1913
1579
|
t3Bin,
|
|
@@ -1931,25 +1597,80 @@ var SIGNED_OUT = {
|
|
|
1931
1597
|
"claude-code": "Claude Code is installed but not signed in. Run `claude` once and sign in, then run `cloop connect` again.",
|
|
1932
1598
|
codex: "Codex is installed but not signed in. Run `codex login`, then run `cloop connect` again."
|
|
1933
1599
|
};
|
|
1934
|
-
|
|
1600
|
+
var T3_DOWN = "T3 Code is not answering; start it, or pass --driver claude-code.";
|
|
1601
|
+
function chooseDriver(found, forced, workstation = false) {
|
|
1935
1602
|
const local = (driver) => {
|
|
1936
1603
|
const harness = driver === "claude-code" ? found.claude : found.codex;
|
|
1937
1604
|
if (!harness)
|
|
1938
1605
|
return {
|
|
1939
1606
|
ok: false,
|
|
1607
|
+
code: "no_harness",
|
|
1940
1608
|
line: `${driver === "codex" ? "Codex" : "Claude Code"} is not installed here.`
|
|
1941
1609
|
};
|
|
1942
|
-
return harness.signedIn ? { ok: true, driver, kind: "local" } : { ok: false, line: SIGNED_OUT[driver] };
|
|
1610
|
+
return harness.signedIn ? { ok: true, driver, kind: "local" } : { ok: false, code: "signed_out", line: SIGNED_OUT[driver] };
|
|
1943
1611
|
};
|
|
1944
1612
|
if (forced === "t3")
|
|
1945
|
-
return found.t3 ? { ok: true, driver: "t3", kind: "workstation" } : { ok: false, line: `No T3 Code server answers at ${DEFAULT_T3_URL}.` };
|
|
1613
|
+
return found.t3 ? { ok: true, driver: "t3", kind: "workstation" } : { ok: false, code: "no_harness", line: `No T3 Code server answers at ${DEFAULT_T3_URL}.` };
|
|
1946
1614
|
if (forced) return local(forced);
|
|
1947
1615
|
if (found.t3) return { ok: true, driver: "t3", kind: "workstation" };
|
|
1616
|
+
if (workstation) return { ok: false, code: "t3_unreachable", line: T3_DOWN };
|
|
1948
1617
|
if (found.claude?.signedIn) return local("claude-code");
|
|
1949
1618
|
if (found.codex?.signedIn) return local("codex");
|
|
1950
1619
|
if (found.claude) return local("claude-code");
|
|
1951
1620
|
if (found.codex) return local("codex");
|
|
1952
|
-
return { ok: false, line: NONE };
|
|
1621
|
+
return { ok: false, code: "no_harness", line: NONE };
|
|
1622
|
+
}
|
|
1623
|
+
var HARNESS_NAME = {
|
|
1624
|
+
"claude-code": "Claude Code",
|
|
1625
|
+
codex: "Codex"
|
|
1626
|
+
};
|
|
1627
|
+
function fallbackDriver(found, forced, workstation) {
|
|
1628
|
+
if (forced === "t3" || workstation) return null;
|
|
1629
|
+
const choice = chooseDriver({ ...found, t3: false });
|
|
1630
|
+
return choice.ok && choice.driver !== "t3" ? choice.driver : null;
|
|
1631
|
+
}
|
|
1632
|
+
function isWorkstation(previous, boxServiceInstalled2) {
|
|
1633
|
+
return boxServiceInstalled2 || Boolean(previous && !isLocal(previous));
|
|
1634
|
+
}
|
|
1635
|
+
function boxServiceInstalled() {
|
|
1636
|
+
return existsSync2(
|
|
1637
|
+
installedService({
|
|
1638
|
+
platform: process.platform,
|
|
1639
|
+
kind: "workstation",
|
|
1640
|
+
home: homedir3(),
|
|
1641
|
+
uid: process.getuid?.() ?? 0,
|
|
1642
|
+
...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
|
|
1643
|
+
}).path
|
|
1644
|
+
);
|
|
1645
|
+
}
|
|
1646
|
+
var KIND_NAME = { workstation: "a Cloop box with T3 Code", local: "a Local runner" };
|
|
1647
|
+
async function revokeReplaced(previous, kind, revoke, say) {
|
|
1648
|
+
if (!previous?.deviceToken || isLocal(previous) === (kind === "local")) return;
|
|
1649
|
+
const was = isLocal(previous) ? "local" : "workstation";
|
|
1650
|
+
say(
|
|
1651
|
+
`${bold("Cloop runner")} This computer was ${KIND_NAME[was]}. It becomes ${KIND_NAME[kind]}, so its old device goes.`
|
|
1652
|
+
);
|
|
1653
|
+
say(
|
|
1654
|
+
tokenGone(await revoke(previous.deviceToken)) ? " Revoked the old device on Cloop." : " Could not revoke the old device. Press Disconnect on its card on the Threads page."
|
|
1655
|
+
);
|
|
1656
|
+
}
|
|
1657
|
+
function fallbackLine(reason, driver) {
|
|
1658
|
+
return `T3 Code is running but would not pair (${reason}). Connecting ${HARNESS_NAME[driver]} instead. To use T3: cloop connect --driver t3 --t3-bin <path>`;
|
|
1659
|
+
}
|
|
1660
|
+
async function connectChosen(driver, attempt, run) {
|
|
1661
|
+
attempt.driver = driver;
|
|
1662
|
+
if (driver !== "t3") return run.local(driver);
|
|
1663
|
+
try {
|
|
1664
|
+
await run.t3();
|
|
1665
|
+
} catch (err) {
|
|
1666
|
+
if (!(err instanceof ConnectFailure) || err.code !== "t3_pair_failed") throw err;
|
|
1667
|
+
const local = run.fallback();
|
|
1668
|
+
if (!local) throw err;
|
|
1669
|
+
run.say(fallbackLine(err.message, local));
|
|
1670
|
+
attempt.fellBack = true;
|
|
1671
|
+
attempt.driver = local;
|
|
1672
|
+
await run.local(local);
|
|
1673
|
+
}
|
|
1953
1674
|
}
|
|
1954
1675
|
function systemdAssignment(assignment) {
|
|
1955
1676
|
return `"${assignment.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
|
|
@@ -1978,7 +1699,8 @@ var UNIT_ENV = [
|
|
|
1978
1699
|
"CLOOP_BOX_THREADS_FILE",
|
|
1979
1700
|
"CLOOP_LOCAL_RUNS_FILE",
|
|
1980
1701
|
"CLOOP_MESH_URL",
|
|
1981
|
-
"CLOOP_ORIGIN"
|
|
1702
|
+
"CLOOP_ORIGIN",
|
|
1703
|
+
"T3CODE_HOME"
|
|
1982
1704
|
];
|
|
1983
1705
|
function unitEnv(env) {
|
|
1984
1706
|
const picked = { PATH: "/usr/bin:/bin" };
|
|
@@ -1988,12 +1710,34 @@ function unitEnv(env) {
|
|
|
1988
1710
|
}
|
|
1989
1711
|
return picked;
|
|
1990
1712
|
}
|
|
1713
|
+
function installedService(opts) {
|
|
1714
|
+
const name = opts.kind === "workstation" ? "box" : "runner";
|
|
1715
|
+
if (opts.platform === "darwin") {
|
|
1716
|
+
const label = `com.cloop.${name}`;
|
|
1717
|
+
return {
|
|
1718
|
+
path: join4(opts.dir ?? join4(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
|
|
1719
|
+
steps: [{ command: ["launchctl", "bootout", `gui/${opts.uid}/${label}`], mayFail: true }],
|
|
1720
|
+
running: ["launchctl", "print", `gui/${opts.uid}/${label}`]
|
|
1721
|
+
};
|
|
1722
|
+
}
|
|
1723
|
+
const unit = `cloop-${name}.service`;
|
|
1724
|
+
return {
|
|
1725
|
+
path: join4(opts.dir ?? join4(opts.home, ".config", "systemd", "user"), unit),
|
|
1726
|
+
steps: [{ command: ["systemctl", "--user", "disable", "--now", unit], mayFail: true }],
|
|
1727
|
+
running: ["systemctl", "--user", "is-active", "--quiet", unit]
|
|
1728
|
+
};
|
|
1729
|
+
}
|
|
1991
1730
|
function unitFor(opts) {
|
|
1992
1731
|
const env = Object.entries(opts.env);
|
|
1993
1732
|
const name = opts.kind === "workstation" ? "box" : "runner";
|
|
1733
|
+
const retire = installedService({
|
|
1734
|
+
...opts,
|
|
1735
|
+
kind: opts.kind === "workstation" ? "local" : "workstation"
|
|
1736
|
+
});
|
|
1994
1737
|
if (opts.platform === "darwin") {
|
|
1995
1738
|
const label = `com.cloop.${name}`;
|
|
1996
|
-
const
|
|
1739
|
+
const agents = opts.dir ?? join4(opts.home, "Library", "LaunchAgents");
|
|
1740
|
+
const path2 = join4(agents, `${label}.plist`);
|
|
1997
1741
|
const log = join4(opts.home, "Library", "Logs", `cloop-${name}.log`);
|
|
1998
1742
|
const xml = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
1999
1743
|
const contents2 = [
|
|
@@ -2025,12 +1769,14 @@ function unitFor(opts) {
|
|
|
2025
1769
|
{ command: ["launchctl", "bootout", `${domain}/${label}`], mayFail: true },
|
|
2026
1770
|
{ command: ["launchctl", "bootstrap", domain, path2], tries: 5 }
|
|
2027
1771
|
],
|
|
1772
|
+
retire,
|
|
2028
1773
|
logs: `tail -f ${log}`,
|
|
2029
1774
|
tail: ["tail", "-n", "20", log]
|
|
2030
1775
|
};
|
|
2031
1776
|
}
|
|
2032
1777
|
const unit = `cloop-${name}.service`;
|
|
2033
|
-
const
|
|
1778
|
+
const units = opts.dir ?? join4(opts.home, ".config", "systemd", "user");
|
|
1779
|
+
const path = join4(units, unit);
|
|
2034
1780
|
const contents = [
|
|
2035
1781
|
"[Unit]",
|
|
2036
1782
|
`Description=Cloop ${name}: answers the Cloop Agent over the mesh`,
|
|
@@ -2059,6 +1805,7 @@ function unitFor(opts) {
|
|
|
2059
1805
|
{ command: ["systemctl", "--user", "enable", unit] },
|
|
2060
1806
|
{ command: ["systemctl", "--user", "restart", unit] }
|
|
2061
1807
|
],
|
|
1808
|
+
retire,
|
|
2062
1809
|
logs: `journalctl --user -u ${unit} -f`,
|
|
2063
1810
|
tail: ["journalctl", "--user", "-u", unit, "-n", "20", "--no-pager"]
|
|
2064
1811
|
};
|
|
@@ -2069,10 +1816,114 @@ function resolveRepos(paths, toplevel) {
|
|
|
2069
1816
|
const top = toplevel(resolve2(p));
|
|
2070
1817
|
if (!top)
|
|
2071
1818
|
return `${p} is not a git checkout. Pass --repo <path> for each repository Cloop may work in.`;
|
|
2072
|
-
if (!repos.some((r) => r.path === top)) repos.push({ label:
|
|
1819
|
+
if (!repos.some((r) => r.path === top)) repos.push({ label: basename3(top), path: top });
|
|
2073
1820
|
}
|
|
2074
1821
|
return repos;
|
|
2075
1822
|
}
|
|
1823
|
+
var CHECKOUT_ROOTS = ["projects", "code", "repos", "src", "Developer", "dev", "work"];
|
|
1824
|
+
function lastCommitAt(path) {
|
|
1825
|
+
try {
|
|
1826
|
+
return Number(
|
|
1827
|
+
execFileSync3("git", ["-C", path, "log", "-1", "--format=%ct"], {
|
|
1828
|
+
encoding: "utf-8",
|
|
1829
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1830
|
+
timeout: 5e3
|
|
1831
|
+
}).trim()
|
|
1832
|
+
) || 0;
|
|
1833
|
+
} catch {
|
|
1834
|
+
return 0;
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
function findCheckouts(home, limit = 8) {
|
|
1838
|
+
const found = [];
|
|
1839
|
+
for (const root of CHECKOUT_ROOTS) {
|
|
1840
|
+
let entries;
|
|
1841
|
+
try {
|
|
1842
|
+
entries = readdirSync2(join4(home, root), { withFileTypes: true });
|
|
1843
|
+
} catch {
|
|
1844
|
+
continue;
|
|
1845
|
+
}
|
|
1846
|
+
for (const entry of entries) {
|
|
1847
|
+
const path = join4(home, root, entry.name);
|
|
1848
|
+
if (!entry.isDirectory() || !existsSync2(join4(path, ".git"))) continue;
|
|
1849
|
+
found.push({ repo: { label: entry.name, path }, at: lastCommitAt(path) });
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
return found.sort((a, b) => b.at - a.at).slice(0, limit).map((f) => f.repo);
|
|
1853
|
+
}
|
|
1854
|
+
function tilde(path, home) {
|
|
1855
|
+
return path === home || path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
|
|
1856
|
+
}
|
|
1857
|
+
function parsePicks(answer, max) {
|
|
1858
|
+
const picks = answer.split(/[\s,]+/).filter(Boolean).map(Number);
|
|
1859
|
+
if (!picks.length || picks.some((n) => !Number.isInteger(n) || n < 1 || n > max)) return null;
|
|
1860
|
+
return [...new Set(picks)];
|
|
1861
|
+
}
|
|
1862
|
+
function rerunCommand(argv, script = process.argv[1] ?? "") {
|
|
1863
|
+
const base = script.includes("/_npx/") ? "npx -y @cloop/runner" : "cloop";
|
|
1864
|
+
const staging = process.env.CLOOP_ORIGIN === STAGING_ORIGIN ? ["--staging"] : [];
|
|
1865
|
+
return [base, "connect", ...staging, ...argv].join(" ");
|
|
1866
|
+
}
|
|
1867
|
+
function notACheckoutLine(cwd, found, home, rerun) {
|
|
1868
|
+
const here = `${tilde(cwd, home)} is not a git checkout.`;
|
|
1869
|
+
if (!found.length)
|
|
1870
|
+
return `${here} Run it again with --repo <path> for each repository Cloop may work in: ${rerun} --repo <path>`;
|
|
1871
|
+
const list = found.map((r) => `${r.label} (${tilde(r.path, home)})`).join(", ");
|
|
1872
|
+
return `${here} Recent checkouts: ${list}. Run it again with a --repo for each one Cloop may work in, for example: ${rerun} --repo ${tilde(found[0]?.path ?? "", home)}`;
|
|
1873
|
+
}
|
|
1874
|
+
async function askRepos(found, home, rerun, ask, say) {
|
|
1875
|
+
say(`${bold("Cloop runner")} This folder is not a git checkout. Recent ones:`);
|
|
1876
|
+
found.forEach((r, i) => say(` ${i + 1} ${r.label} ${dim(tilde(r.path, home))}`));
|
|
1877
|
+
for (; ; ) {
|
|
1878
|
+
const answer = (await ask("Which folders may Cloop work in? (numbers, comma-separated) ")).trim();
|
|
1879
|
+
if (!answer)
|
|
1880
|
+
throw new ConnectFailure(
|
|
1881
|
+
"no_repo",
|
|
1882
|
+
`No folder chosen. Run ${rerun} --repo <path> to name one.`
|
|
1883
|
+
);
|
|
1884
|
+
const picks = parsePicks(answer, found.length);
|
|
1885
|
+
if (picks) return picks.map((n) => found[n - 1]);
|
|
1886
|
+
say(` Type numbers from 1 to ${found.length}, like 1,3.`);
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
async function reposFor(argv) {
|
|
1890
|
+
const given = flags(argv, "--repo");
|
|
1891
|
+
if (given.length) {
|
|
1892
|
+
const repos = resolveRepos(given, gitTop);
|
|
1893
|
+
if (typeof repos === "string") throw new ConnectFailure("no_repo", repos);
|
|
1894
|
+
return repos;
|
|
1895
|
+
}
|
|
1896
|
+
const here = gitTop(process.cwd());
|
|
1897
|
+
if (here) return [{ label: basename3(here), path: here }];
|
|
1898
|
+
const home = homedir3();
|
|
1899
|
+
const found = findCheckouts(home);
|
|
1900
|
+
const rerun = rerunCommand(argv);
|
|
1901
|
+
if (!found.length || !process.stdin.isTTY || !process.stdout.isTTY)
|
|
1902
|
+
throw new ConnectFailure("no_repo", notACheckoutLine(process.cwd(), found, home, rerun));
|
|
1903
|
+
const prompt = createInterface({ input: process.stdin, output: process.stdout });
|
|
1904
|
+
const closed = () => new ConnectFailure("no_repo", `No folder chosen. Run ${rerun} --repo <path> to name one.`);
|
|
1905
|
+
try {
|
|
1906
|
+
return await askRepos(found, home, rerun, askOrClosed(prompt, closed), out);
|
|
1907
|
+
} finally {
|
|
1908
|
+
prompt.close();
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
function askOrClosed(prompt, closed) {
|
|
1912
|
+
return (question) => new Promise((resolve3, reject) => {
|
|
1913
|
+
const onClose = () => reject(closed());
|
|
1914
|
+
prompt.once("close", onClose);
|
|
1915
|
+
prompt.question(question).then(
|
|
1916
|
+
(answer) => {
|
|
1917
|
+
prompt.off("close", onClose);
|
|
1918
|
+
resolve3(answer);
|
|
1919
|
+
},
|
|
1920
|
+
(err) => {
|
|
1921
|
+
prompt.off("close", onClose);
|
|
1922
|
+
reject(err);
|
|
1923
|
+
}
|
|
1924
|
+
);
|
|
1925
|
+
});
|
|
1926
|
+
}
|
|
2076
1927
|
function gitTop(path) {
|
|
2077
1928
|
try {
|
|
2078
1929
|
return execFileSync3("git", ["-C", path, "rev-parse", "--show-toplevel"], {
|
|
@@ -2096,12 +1947,12 @@ function harnessLine(h) {
|
|
|
2096
1947
|
const account = h.signedIn ? h.account ?? "signed in" : "signed out";
|
|
2097
1948
|
return `${h.name}${version}, ${account}${h.experimental ? " (experimental)" : ""}`;
|
|
2098
1949
|
}
|
|
2099
|
-
async function
|
|
2100
|
-
for (const step of
|
|
1950
|
+
async function runSteps(steps, run = (command) => void execFileSync3(command[0], command.slice(1), { stdio: "ignore", timeout: 15e3 }), wait = (ms) => new Promise((r) => setTimeout(r, ms))) {
|
|
1951
|
+
for (const step of steps) {
|
|
2101
1952
|
const tries = step.tries ?? 1;
|
|
2102
1953
|
for (let attempt = 1; ; attempt++) {
|
|
2103
1954
|
try {
|
|
2104
|
-
|
|
1955
|
+
run(step.command);
|
|
2105
1956
|
break;
|
|
2106
1957
|
} catch (err) {
|
|
2107
1958
|
if (step.mayFail) break;
|
|
@@ -2111,48 +1962,53 @@ async function startService(unit, run2 = (command) => void execFileSync3(command
|
|
|
2111
1962
|
}
|
|
2112
1963
|
}
|
|
2113
1964
|
}
|
|
2114
|
-
async function installService(kind, argv) {
|
|
1965
|
+
async function installService(kind, argv, attempt) {
|
|
2115
1966
|
if (argv.includes("--no-service")) {
|
|
2116
1967
|
out(` Run ${dim("cloop box run")} to go live.`);
|
|
2117
1968
|
return;
|
|
2118
1969
|
}
|
|
2119
|
-
|
|
1970
|
+
attempt.step = "service_write";
|
|
1971
|
+
const npxBeside = join4(dirname3(process.execPath), "npx");
|
|
2120
1972
|
const program = programFor(
|
|
2121
1973
|
process.argv[1] ?? "cloop",
|
|
2122
1974
|
process.execPath,
|
|
2123
|
-
|
|
1975
|
+
existsSync2(npxBeside) ? npxBeside : which("npx"),
|
|
2124
1976
|
VERSION
|
|
2125
1977
|
);
|
|
2126
|
-
if (typeof program === "string")
|
|
2127
|
-
out(`${red("\u2717")} ${program}`);
|
|
2128
|
-
process.exit(1);
|
|
2129
|
-
}
|
|
1978
|
+
if (typeof program === "string") throw new ConnectFailure("npx_missing", program);
|
|
2130
1979
|
const unit = unitFor({
|
|
2131
1980
|
platform: process.platform,
|
|
2132
1981
|
kind,
|
|
2133
|
-
home:
|
|
1982
|
+
home: homedir3(),
|
|
2134
1983
|
program,
|
|
2135
1984
|
env: unitEnv(process.env),
|
|
2136
1985
|
uid: process.getuid?.() ?? 0,
|
|
2137
1986
|
...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
|
|
2138
1987
|
});
|
|
2139
|
-
|
|
2140
|
-
|
|
1988
|
+
mkdirSync3(join4(unit.path, ".."), { recursive: true });
|
|
1989
|
+
writeFileSync3(unit.path, unit.contents);
|
|
2141
1990
|
if (argv.includes("--no-start")) {
|
|
2142
1991
|
out(
|
|
2143
1992
|
` Service: wrote ${unit.path}. Start it with: ${dim(unit.start.map((step) => step.command.join(" ")).join(" && "))}`
|
|
2144
1993
|
);
|
|
2145
1994
|
return;
|
|
2146
1995
|
}
|
|
1996
|
+
attempt.step = "service_start";
|
|
2147
1997
|
const since = Date.now();
|
|
2148
1998
|
try {
|
|
2149
|
-
|
|
1999
|
+
if (existsSync2(unit.retire.path)) {
|
|
2000
|
+
out(` This computer is one runner, so connect stops and removes ${unit.retire.path}.`);
|
|
2001
|
+
await runSteps(unit.retire.steps);
|
|
2002
|
+
rmSync(unit.retire.path, { force: true });
|
|
2003
|
+
}
|
|
2004
|
+
await runSteps(unit.start);
|
|
2150
2005
|
} catch (err) {
|
|
2151
|
-
|
|
2152
|
-
|
|
2006
|
+
throw new ConnectFailure(
|
|
2007
|
+
"service_start_failed",
|
|
2008
|
+
`Wrote ${unit.path} but could not start it: ${err instanceof Error ? err.message : String(err)}`
|
|
2153
2009
|
);
|
|
2154
|
-
process.exit(1);
|
|
2155
2010
|
}
|
|
2011
|
+
attempt.step = "first_connect";
|
|
2156
2012
|
if (!await awaitDaemon(since)) {
|
|
2157
2013
|
out(
|
|
2158
2014
|
`${red("\u2717")} ${unit.path} started, but the runner did not reach Cloop within 15 s. Its last log lines:`
|
|
@@ -2167,42 +2023,57 @@ async function installService(kind, argv) {
|
|
|
2167
2023
|
} catch {
|
|
2168
2024
|
out(` (no log yet; run ${unit.logs})`);
|
|
2169
2025
|
}
|
|
2170
|
-
|
|
2026
|
+
throw new ConnectFailure("first_connect_timeout", "the runner did not reach Cloop", true);
|
|
2171
2027
|
}
|
|
2172
2028
|
out(` Service: ${unit.path}, started and connected. Logs: ${dim(unit.logs)}`);
|
|
2173
2029
|
}
|
|
2174
|
-
async function connectT3(argv) {
|
|
2030
|
+
async function connectT3(argv, attempt) {
|
|
2031
|
+
const previous = readRunnerConfig();
|
|
2175
2032
|
const t3Url = (flag(argv, "--t3-url") ?? DEFAULT_T3_URL).replace(/\/+$/, "");
|
|
2176
|
-
const t3Bin =
|
|
2177
|
-
if (!t3Bin) {
|
|
2178
|
-
out(`${red("\u2717")} No t3 binary found. Pass --t3-bin or set T3_BIN.`);
|
|
2179
|
-
process.exit(1);
|
|
2180
|
-
}
|
|
2033
|
+
const t3Bin = flag(argv, "--t3-bin");
|
|
2181
2034
|
const cfg = await connectBox({
|
|
2182
2035
|
readEnvironment: async () => {
|
|
2183
2036
|
const environment = await readEnvironment(t3Url);
|
|
2184
2037
|
out(
|
|
2185
|
-
`${bold("Cloop
|
|
2038
|
+
`${bold("Cloop runner")} Connecting ${environment.label} (T3 ${environment.serverVersion}) to Cloop.`
|
|
2186
2039
|
);
|
|
2187
2040
|
return environment;
|
|
2188
2041
|
},
|
|
2189
|
-
mintSession: () =>
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2042
|
+
mintSession: async () => {
|
|
2043
|
+
attempt.step = "t3_pair";
|
|
2044
|
+
try {
|
|
2045
|
+
return await mintSession(t3Url, t3Bin ? { bin: t3Bin } : {});
|
|
2046
|
+
} catch (err) {
|
|
2047
|
+
throw new ConnectFailure(
|
|
2048
|
+
"t3_pair_failed",
|
|
2049
|
+
err instanceof Error ? err.message : String(err)
|
|
2050
|
+
);
|
|
2198
2051
|
}
|
|
2199
|
-
}
|
|
2200
|
-
|
|
2052
|
+
},
|
|
2053
|
+
deviceLogin: async (environment) => {
|
|
2054
|
+
attempt.step = "login";
|
|
2055
|
+
attempt.deviceToken = await deviceLogin({
|
|
2056
|
+
origin: getOrigin(),
|
|
2057
|
+
deviceName: flag(argv, "--name") ?? shortMachineName(),
|
|
2058
|
+
device: {
|
|
2059
|
+
kind: "workstation",
|
|
2060
|
+
environmentId: environment.environmentId,
|
|
2061
|
+
label: environment.label,
|
|
2062
|
+
version: environment.serverVersion
|
|
2063
|
+
}
|
|
2064
|
+
});
|
|
2065
|
+
return attempt.deviceToken;
|
|
2066
|
+
},
|
|
2067
|
+
writeBoxConfig: (cfg2) => writeBoxConfig({ ...cfg2, origin: getOrigin() })
|
|
2201
2068
|
});
|
|
2069
|
+
await revokeReplaced(previous, "workstation", (t) => revokeOwnDevice(getOrigin(), t), out);
|
|
2202
2070
|
out(
|
|
2203
|
-
`${bold("Cloop
|
|
2071
|
+
`${bold("Cloop runner")} T3 ${cfg.label} paired with scope ${cfg.scope}, until ${cfg.expiresAt.slice(0, 10)}.`
|
|
2204
2072
|
);
|
|
2205
|
-
const driver = new T3Driver({
|
|
2073
|
+
const driver = new T3Driver({
|
|
2074
|
+
client: () => new T3Client(cfg.t3Url, cfg.token),
|
|
2075
|
+
t3Bin: cfg.t3Bin
|
|
2076
|
+
});
|
|
2206
2077
|
const report = await runBoxTool({ driver }, "status", {});
|
|
2207
2078
|
if (report.ok) {
|
|
2208
2079
|
const value = report.value;
|
|
@@ -2213,21 +2084,16 @@ async function connectT3(argv) {
|
|
|
2213
2084
|
} else {
|
|
2214
2085
|
out(`${red("\u2717")} Status failed: ${report.error}`);
|
|
2215
2086
|
}
|
|
2216
|
-
await installService("workstation", argv);
|
|
2087
|
+
await installService("workstation", argv, attempt);
|
|
2217
2088
|
}
|
|
2218
|
-
async function connectLocal(driver, found, argv) {
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
gitTop
|
|
2222
|
-
);
|
|
2223
|
-
if (typeof repos === "string") {
|
|
2224
|
-
out(`${red("\u2717")} ${repos}`);
|
|
2225
|
-
process.exit(1);
|
|
2226
|
-
}
|
|
2089
|
+
async function connectLocal(driver, found, argv, attempt) {
|
|
2090
|
+
attempt.step = "repos";
|
|
2091
|
+
const repos = await reposFor(argv);
|
|
2227
2092
|
const harness = driver === "claude-code" ? found.claude : found.codex;
|
|
2228
2093
|
const bin = which(driver === "claude-code" ? "claude" : "codex") ?? (driver === "claude-code" ? "claude" : "codex");
|
|
2229
2094
|
const previous = readRunnerConfig();
|
|
2230
|
-
const deviceName = flag(argv, "--name") ??
|
|
2095
|
+
const deviceName = flag(argv, "--name") ?? shortMachineName();
|
|
2096
|
+
const fallbackModels = driver === "claude-code" ? flag(argv, "--fallback-model") ?? (previous && isLocal(previous) ? previous.fallbackModels : void 0) ?? DEFAULT_FALLBACK_MODEL : void 0;
|
|
2231
2097
|
const device = {
|
|
2232
2098
|
kind: "local",
|
|
2233
2099
|
environmentId: previous && isLocal(previous) ? previous.environmentId : `local:${randomUUID2()}`,
|
|
@@ -2237,16 +2103,23 @@ async function connectLocal(driver, found, argv) {
|
|
|
2237
2103
|
out(
|
|
2238
2104
|
`${bold("Cloop runner")} Connecting ${deviceName} as a Local runner with ${harnessLine(harness)}.`
|
|
2239
2105
|
);
|
|
2106
|
+
attempt.step = "login";
|
|
2240
2107
|
const deviceToken = await deviceLogin({ origin: getOrigin(), deviceName, device });
|
|
2108
|
+
attempt.deviceToken = deviceToken;
|
|
2241
2109
|
const cfg = {
|
|
2242
2110
|
driver,
|
|
2243
2111
|
environmentId: device.environmentId,
|
|
2244
2112
|
label: deviceName,
|
|
2245
2113
|
deviceToken,
|
|
2246
2114
|
repos,
|
|
2247
|
-
bin
|
|
2115
|
+
bin,
|
|
2116
|
+
fullAccess: argv.includes("--full-access"),
|
|
2117
|
+
origin: getOrigin(),
|
|
2118
|
+
...fallbackModels ? { fallbackModels } : {},
|
|
2119
|
+
...driver === "claude-code" ? { askEverything: argv.includes("--ask-everything") } : {}
|
|
2248
2120
|
};
|
|
2249
2121
|
writeBoxConfig(cfg);
|
|
2122
|
+
await revokeReplaced(previous, "local", (t) => revokeOwnDevice(getOrigin(), t), out);
|
|
2250
2123
|
const others = [found.claude, found.codex].filter(
|
|
2251
2124
|
(h) => Boolean(h) && h !== harness
|
|
2252
2125
|
);
|
|
@@ -2254,63 +2127,130 @@ async function connectLocal(driver, found, argv) {
|
|
|
2254
2127
|
`${bold("Cloop runner")} ${deviceName} is a Local runner: ${[harness, ...others].map(harnessLine).join("; ")}.`
|
|
2255
2128
|
);
|
|
2256
2129
|
out(` Repos: ${repos.map((r) => `${r.label} (${r.path})`).join(", ")}`);
|
|
2257
|
-
|
|
2130
|
+
const support = driver === "claude-code" ? await probeClaudePermissions(bin) : null;
|
|
2131
|
+
out(
|
|
2132
|
+
` ${cfg.askEverything ? "Asks before actions except allowlisted reads." : cfg.fullAccess ? "Full access: every Task runs without permission checks, including Tasks made from email or other people." : "Runs in auto mode: it asks before risky steps."}`
|
|
2133
|
+
);
|
|
2134
|
+
if (support && !support.autoMode)
|
|
2135
|
+
out(" Auto mode is unavailable. Uses acceptEdits with the read allowlist.");
|
|
2136
|
+
if (driver === "codex")
|
|
2137
|
+
out(" Codex uses sandboxed automatic review; it cannot send owner approval questions.");
|
|
2138
|
+
if (fallbackModels)
|
|
2139
|
+
out(
|
|
2140
|
+
` Fallback model: ${fallbackModels}, when Claude Code's default model is at its limit. Change it with --fallback-model.`
|
|
2141
|
+
);
|
|
2142
|
+
await installService("local", argv, attempt);
|
|
2258
2143
|
}
|
|
2259
2144
|
async function detect(probes) {
|
|
2260
2145
|
const [t3, claude, codex] = await Promise.all([probes.t3(), probes.claude(), probes.codex()]);
|
|
2261
2146
|
return { t3, claude, codex };
|
|
2262
2147
|
}
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2148
|
+
function harnessesFound(found) {
|
|
2149
|
+
return [
|
|
2150
|
+
...found.t3 ? ["t3"] : [],
|
|
2151
|
+
...found.claude ? ["claude-code"] : [],
|
|
2152
|
+
...found.codex ? ["codex"] : []
|
|
2153
|
+
];
|
|
2154
|
+
}
|
|
2155
|
+
var MODEL_LIST = /^[A-Za-z0-9][\w.:[\]-]*(,[A-Za-z0-9][\w.:[\]-]*)*$/;
|
|
2156
|
+
async function connect(argv, attempt) {
|
|
2157
|
+
if (argv.some((arg) => arg === "--webhook" || arg.startsWith("--webhook="))) {
|
|
2158
|
+
await connectWebhook(argv, attempt);
|
|
2159
|
+
return;
|
|
2268
2160
|
}
|
|
2161
|
+
const forced = flag(argv, "--driver") ?? process.env.CLOOP_DRIVER;
|
|
2162
|
+
if (forced && !["t3", "claude-code", "codex"].includes(forced))
|
|
2163
|
+
throw new ConnectFailure("bad_flag", "--driver is t3, claude-code, or codex.");
|
|
2164
|
+
const fallback = flag(argv, "--fallback-model");
|
|
2165
|
+
if (fallback !== void 0 && !MODEL_LIST.test(fallback))
|
|
2166
|
+
throw new ConnectFailure(
|
|
2167
|
+
"bad_flag",
|
|
2168
|
+
"--fallback-model takes model names, comma-separated, like opus or opus,sonnet."
|
|
2169
|
+
);
|
|
2269
2170
|
const t3Url = (flag(argv, "--t3-url") ?? DEFAULT_T3_URL).replace(/\/+$/, "");
|
|
2270
2171
|
const found = await detect({
|
|
2271
2172
|
t3: () => forced && forced !== "t3" ? Promise.resolve(false) : t3Answers(t3Url),
|
|
2272
2173
|
claude: () => probeClaude(),
|
|
2273
2174
|
codex: () => probeCodex()
|
|
2274
2175
|
});
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2176
|
+
attempt.harnesses = harnessesFound(found);
|
|
2177
|
+
const workstation = isWorkstation(readRunnerConfig(), boxServiceInstalled());
|
|
2178
|
+
const choice = chooseDriver(found, forced, workstation);
|
|
2179
|
+
if (!choice.ok) throw new ConnectFailure(choice.code, choice.line);
|
|
2180
|
+
await connectChosen(choice.driver, attempt, {
|
|
2181
|
+
t3: () => connectT3(argv, attempt),
|
|
2182
|
+
local: (driver) => connectLocal(driver, found, argv, attempt),
|
|
2183
|
+
fallback: () => fallbackDriver(found, forced, workstation),
|
|
2184
|
+
say: (line2) => out(`${bold("Cloop runner")} ${line2}`)
|
|
2185
|
+
});
|
|
2186
|
+
}
|
|
2187
|
+
async function connectCommand(argv) {
|
|
2188
|
+
const attempt = newAttempt();
|
|
2189
|
+
let error = null;
|
|
2190
|
+
try {
|
|
2191
|
+
await connect(argv, attempt);
|
|
2192
|
+
} catch (err) {
|
|
2193
|
+
error = err instanceof ConnectFailure ? err.code : "unexpected";
|
|
2194
|
+
if (!(err instanceof ConnectFailure && err.shown))
|
|
2195
|
+
out(`${red("\u2717")} ${err instanceof Error ? err.message : String(err)}`);
|
|
2196
|
+
}
|
|
2197
|
+
await sendConnectReport(
|
|
2198
|
+
getOrigin(),
|
|
2199
|
+
connectReport(attempt, error, getMachine()),
|
|
2200
|
+
attempt.deviceToken
|
|
2201
|
+
);
|
|
2202
|
+
if (error) process.exit(1);
|
|
2282
2203
|
}
|
|
2283
2204
|
|
|
2284
2205
|
export {
|
|
2206
|
+
BoxToolError,
|
|
2285
2207
|
T3Client,
|
|
2286
2208
|
runBoxTool,
|
|
2287
2209
|
threadsFilePath,
|
|
2210
|
+
runnerStatePath,
|
|
2288
2211
|
writeRunnerState,
|
|
2289
2212
|
lockThreadsFile,
|
|
2290
2213
|
BoxWatch,
|
|
2291
|
-
|
|
2292
|
-
|
|
2214
|
+
tokenGone,
|
|
2215
|
+
revokeOwnDevice,
|
|
2216
|
+
probeClaudePermissions,
|
|
2293
2217
|
probeClaude,
|
|
2218
|
+
DEFAULT_FALLBACK_MODEL,
|
|
2294
2219
|
claudeDialect,
|
|
2295
2220
|
probeCodex,
|
|
2296
2221
|
codexDialect,
|
|
2222
|
+
orderThreads,
|
|
2223
|
+
T3Driver,
|
|
2224
|
+
boxPath,
|
|
2297
2225
|
isLocal,
|
|
2298
2226
|
readRunnerConfig,
|
|
2299
2227
|
writeBoxConfig,
|
|
2300
2228
|
DEFAULT_T3_URL,
|
|
2301
|
-
compareVersions,
|
|
2302
|
-
resolveT3Bin,
|
|
2303
2229
|
mintSession,
|
|
2304
2230
|
connectBox,
|
|
2305
2231
|
chooseDriver,
|
|
2232
|
+
fallbackDriver,
|
|
2233
|
+
isWorkstation,
|
|
2234
|
+
revokeReplaced,
|
|
2235
|
+
fallbackLine,
|
|
2236
|
+
connectChosen,
|
|
2306
2237
|
systemdAssignment,
|
|
2307
2238
|
systemdWord,
|
|
2308
2239
|
programFor,
|
|
2309
2240
|
awaitDaemon,
|
|
2310
2241
|
unitEnv,
|
|
2242
|
+
installedService,
|
|
2311
2243
|
unitFor,
|
|
2312
2244
|
resolveRepos,
|
|
2313
|
-
|
|
2245
|
+
findCheckouts,
|
|
2246
|
+
tilde,
|
|
2247
|
+
parsePicks,
|
|
2248
|
+
rerunCommand,
|
|
2249
|
+
notACheckoutLine,
|
|
2250
|
+
askRepos,
|
|
2251
|
+
askOrClosed,
|
|
2252
|
+
runSteps,
|
|
2314
2253
|
detect,
|
|
2254
|
+
harnessesFound,
|
|
2315
2255
|
connectCommand
|
|
2316
2256
|
};
|