@cloop/runner 0.3.68 → 0.3.69
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-YFGM56QY.js → box-UOJ6ET2B.js} +156 -511
- package/dist/{chunk-7LPSTDZE.js → chunk-4JTIWZHB.js} +1 -1
- package/dist/{chunk-BVPS6DCH.js → chunk-57E5WOOP.js} +574 -1673
- package/dist/{chunk-TCNIRZLU.js → chunk-CLOYOD2X.js} +10 -6
- package/dist/{chunk-6LYMSWSB.js → chunk-DN6TQALA.js} +265 -1961
- package/dist/{chunk-HWNRORIZ.js → chunk-DTUNRKBC.js} +1 -1
- package/dist/chunk-EEG5JOZ7.js +939 -0
- package/dist/chunk-GAEZIKCK.js +626 -0
- package/dist/chunk-HIBAH65V.js +1178 -0
- package/dist/{chunk-7ZL3Z3IO.js → chunk-JI5FWLDU.js} +6 -6
- package/dist/chunk-JJWSPBM4.js +40 -0
- package/dist/{chunk-L7D3ANPW.js → chunk-KIYCULVE.js} +4 -2
- package/dist/{chunk-34VZ5LZI.js → chunk-SJAGZNFF.js} +3 -83
- package/dist/chunk-TPKYD3JF.js +43 -0
- package/dist/chunk-WCKW2Z2G.js +459 -0
- package/dist/chunk-ZHQSGJCE.js +85 -0
- package/dist/{connect-D2SXLADA.js → connect-HVOAYXWM.js} +11 -47
- package/dist/disconnect-DQ6WSDR7.js +163 -0
- package/dist/existing-runner-BSSRQFFP.js +15 -0
- package/dist/index.js +14 -14
- package/dist/{login-VNDFCJD4.js → login-4HWP4PF4.js} +3 -2
- package/dist/{mcp-server-XPHCDBFR.js → mcp-server-DTJVCFRG.js} +10 -10
- package/dist/{runner-A3HFZ727.js → runner-4XWS2RJL.js} +4 -3
- package/dist/{runs-DOFU45TW.js → runs-TWUGWGNU.js} +4 -2
- package/dist/{statusline-VA2DSWVT.js → statusline-C2FH3YQ4.js} +1 -1
- package/dist/{takeover-U2EHJ5GW.js → takeover-5QSP6YAG.js} +6 -4
- package/dist/{use-7D5GQFGB.js → use-U3E55XBK.js} +20 -13
- package/package.json +1 -1
- package/dist/disconnect-7SJKPYIN.js +0 -30
- package/dist/existing-runner-XT3HLIPM.js +0 -20
|
@@ -1,768 +1,222 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
BoxToolError,
|
|
4
|
+
CLOOP_THREAD_PREFIX,
|
|
5
|
+
HARNESS_LIMIT,
|
|
6
|
+
HARNESS_SIGNED_OUT,
|
|
7
|
+
IDLE_SETTLE_MS,
|
|
8
|
+
LIMIT_HOLD_MS,
|
|
9
|
+
MACHINE_RESULT_INSTRUCTION,
|
|
10
|
+
RUNTIME_MODES,
|
|
11
|
+
RUN_TEXT_MAX,
|
|
12
|
+
cloneLine,
|
|
13
|
+
droppedLine,
|
|
14
|
+
handoverPrompt,
|
|
15
|
+
hasResultBlock,
|
|
16
|
+
holdsForNextTurn,
|
|
17
|
+
isYes,
|
|
18
|
+
limitedModel,
|
|
19
|
+
movedLine,
|
|
20
|
+
movingLine,
|
|
21
|
+
nextProgress,
|
|
22
|
+
questionLine,
|
|
23
|
+
readRunResult,
|
|
24
|
+
resultPrUrl,
|
|
25
|
+
resultText
|
|
26
|
+
} from "./chunk-GAEZIKCK.js";
|
|
2
27
|
import {
|
|
3
28
|
sanitizeLabel,
|
|
4
29
|
stripControl
|
|
5
30
|
} from "./chunk-VK6GV757.js";
|
|
6
|
-
import {
|
|
7
|
-
CONFIG_DIR,
|
|
8
|
-
PRODUCTION_ORIGIN,
|
|
9
|
-
STAGING_ORIGIN,
|
|
10
|
-
getOrigin
|
|
11
|
-
} from "./chunk-D5UZW42X.js";
|
|
12
|
-
|
|
13
|
-
// ../clo0p-app/contracts/run-result.ts
|
|
14
|
-
var WIZARD_STEPS_MAX = 6;
|
|
15
|
-
var WIZARD_FOR = "steps only the user can do by hand: a sign-in, an app permission, a key from a dashboard, or a change in a dashboard or console you cannot make yourself";
|
|
16
|
-
var CHECK_BACK_MIN_MINUTES = 5;
|
|
17
|
-
var CHECK_BACK_MAX_MINUTES = 3 * 24 * 60;
|
|
18
|
-
var CHECK_BACK_WHY_MAX = 300;
|
|
19
|
-
var UNDERWAY_MAX = 3;
|
|
20
|
-
var GITHUB_WORK = /^https:\/\/(?:www\.)?github\.com\/[\w.-]+\/[\w.-]+\/(?:pull|issues)\/[1-9]\d*(?:[/?#]|$)/i;
|
|
21
|
-
var RUN_IMAGES_MAX = 6;
|
|
22
|
-
var RUN_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
|
|
23
|
-
var RUN_FILES_MAX = 6;
|
|
24
|
-
var RUN_FILE_MAX_BYTES = 20 * 1024 * 1024;
|
|
25
|
-
var RUN_MEDIA_CLASSES = {
|
|
26
|
-
image: { max: RUN_IMAGES_MAX, maxBytes: RUN_IMAGE_MAX_BYTES },
|
|
27
|
-
file: { max: RUN_FILES_MAX, maxBytes: RUN_FILE_MAX_BYTES }
|
|
28
|
-
};
|
|
29
|
-
var startsWith = (bytes, at, want) => want.every((b, j) => bytes[at + j] === b);
|
|
30
|
-
var ascii = (word) => [...word].map((c) => c.charCodeAt(0));
|
|
31
|
-
var PROOFS = {
|
|
32
|
-
png: (bytes) => startsWith(bytes, 0, [137, 80, 78, 71, 13, 10, 26, 10]),
|
|
33
|
-
jpg: (bytes) => startsWith(bytes, 0, [255, 216, 255]),
|
|
34
|
-
webp: (bytes) => startsWith(bytes, 0, ascii("RIFF")) && startsWith(bytes, 8, ascii("WEBP")),
|
|
35
|
-
pdf: (bytes) => startsWith(bytes, 0, ascii("%PDF-")),
|
|
36
|
-
// A docx, an xlsx and a pptx are each a zip: the bytes say zip, the name says which.
|
|
37
|
-
zip: (bytes) => startsWith(bytes, 0, [80, 75, 3, 4]),
|
|
38
|
-
text: (bytes) => {
|
|
39
|
-
if (bytes.includes(0)) return false;
|
|
40
|
-
try {
|
|
41
|
-
new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
42
|
-
return true;
|
|
43
|
-
} catch {
|
|
44
|
-
return false;
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
};
|
|
48
|
-
var RUN_MEDIA_TYPES = {
|
|
49
|
-
png: { mime: "image/png", class: "image", proof: "png" },
|
|
50
|
-
jpg: { mime: "image/jpeg", class: "image", proof: "jpg" },
|
|
51
|
-
webp: { mime: "image/webp", class: "image", proof: "webp" },
|
|
52
|
-
pdf: { mime: "application/pdf", class: "file", proof: "pdf" },
|
|
53
|
-
docx: { mime: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", class: "file", proof: "zip" },
|
|
54
|
-
xlsx: { mime: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", class: "file", proof: "zip" },
|
|
55
|
-
pptx: { mime: "application/vnd.openxmlformats-officedocument.presentationml.presentation", class: "file", proof: "zip" },
|
|
56
|
-
csv: { mime: "text/csv", class: "file", proof: "text" },
|
|
57
|
-
txt: { mime: "text/plain", class: "file", proof: "text" },
|
|
58
|
-
md: { mime: "text/markdown", class: "file", proof: "text" }
|
|
59
|
-
};
|
|
60
|
-
var EXTS = Object.keys(RUN_MEDIA_TYPES);
|
|
61
|
-
function imageExt(bytes) {
|
|
62
|
-
return EXTS.find((ext) => RUN_MEDIA_TYPES[ext].class === "image" && PROOFS[RUN_MEDIA_TYPES[ext].proof](bytes)) ?? null;
|
|
63
|
-
}
|
|
64
|
-
function mediaExt(bytes, name) {
|
|
65
|
-
const image = imageExt(bytes);
|
|
66
|
-
if (image) return image;
|
|
67
|
-
const dot = name?.lastIndexOf(".") ?? -1;
|
|
68
|
-
const ext = dot > 0 ? name.slice(dot + 1).toLowerCase() : "";
|
|
69
|
-
if (!Object.hasOwn(RUN_MEDIA_TYPES, ext)) return null;
|
|
70
|
-
const type = RUN_MEDIA_TYPES[ext];
|
|
71
|
-
return type.class === "file" && PROOFS[type.proof](bytes) ? ext : null;
|
|
72
|
-
}
|
|
73
|
-
var RUN_MEDIA_KEY = runMediaPattern("[0-9a-f-]{36}\\/[0-9a-f-]{36}\\/");
|
|
74
|
-
var RUN_MEDIA_FILE = runMediaPattern("");
|
|
75
|
-
var RUN_PREVIEWS_MAX = 3;
|
|
76
|
-
var PREVIEW_HOURS = 24;
|
|
77
|
-
var BOX_PREVIEW_HOURS = 6;
|
|
78
|
-
var PREVIEW_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
79
|
-
function isPort(v) {
|
|
80
|
-
return typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 65535;
|
|
81
|
-
}
|
|
82
|
-
function isPreviewPath(v) {
|
|
83
|
-
return typeof v === "string" && v.length <= 400 && v.startsWith("/") && !v.startsWith("//") && !/[\s\\]/.test(v);
|
|
84
|
-
}
|
|
85
|
-
function fileTypes() {
|
|
86
|
-
const files = EXTS.filter((ext) => RUN_MEDIA_TYPES[ext].class === "file");
|
|
87
|
-
return `${files.slice(0, -1).join(", ")} or ${files.at(-1)}`;
|
|
88
|
-
}
|
|
89
|
-
function runMediaPattern(folder) {
|
|
90
|
-
return new RegExp(`^${folder}[0-9a-f-]{36}\\.(${Object.keys(RUN_MEDIA_TYPES).join("|")})$`);
|
|
91
|
-
}
|
|
92
|
-
var RESULT_INSTRUCTION = [
|
|
93
|
-
"When you finish, end your final message with a fenced block tagged cloop-result containing JSON, for example:",
|
|
94
|
-
"```cloop-result",
|
|
95
|
-
'{"summary": "Your conclusion or what you did, in one or two sentences.", "outputs": [{"kind": "pr", "title": "fix: the thing", "url": "https://github.com/org/repo/pull/1"}], "checks": [{"name": "Tests", "outcome": "passed"}]}',
|
|
96
|
-
"```",
|
|
97
|
-
"An output kind is one of: pr or link (title, url), draft (title, body, optional to, optional url), doc (title, optional url or body), wizard (title, steps). A check outcome is passed, failed or skipped.",
|
|
98
|
-
"A draft's body is the message itself, as the recipient will read it; if you saved it somewhere (a Gmail draft), put that link in url, never in body. A doc's body is the whole page in GitHub Markdown: headings, lists, bold and tables all show; a table suits one row per item. Give every product, page or source you mention as a full https link.",
|
|
99
|
-
`A wizard is for ${WIZARD_FOR}. When the work needs such a step, return a wizard for it, not only words. A wizard has 1 to ${WIZARD_STEPS_MAX} steps in order, each {"title", "body" in Markdown, optional https "url"}. Never ask the user to paste a password, key or other secret anywhere. The user sees a wizard as a walkthrough: in your own words, call it a walkthrough, never a wizard.`,
|
|
100
|
-
"List as outputs only what this run made. A PR or page you only read, checked or cited goes in the summary, never in outputs.",
|
|
101
|
-
"When you push a branch and open no PR, list the branch as a link output with its GitHub address, https://github.com/org/repo/tree/<branch>: Cloop asks the owner whether to open one.",
|
|
102
|
-
`When an open GitHub PR or issue already does this Task and you found it, not made it, add "underway": [{"title": "feat: the thing", "url": "https://github.com/org/repo/pull/1"}] to the block, at most ${UNDERWAY_MAX}: Cloop links each one to the Task. Never list it in outputs.`,
|
|
103
|
-
'Your answer shows in the chat as GitHub Markdown, so most answers need no page: write the whole answer above the cloop-result block, and keep the summary to your conclusion or what you did. Make a doc output only when the answer is a document the owner will keep or share, such as a report, a plan or research longer than about 400 words, with its own headings. Then the summary is your conclusion in one or two sentences, such as "I recommend X, because Y.", the doc holds the method and caveats, and it does not repeat the summary. Title a doc for what it says, never "Full answer" or "Summary".'
|
|
104
|
-
].join("\n");
|
|
105
|
-
var MACHINE_RESULT_INSTRUCTION = [
|
|
106
|
-
RESULT_INSTRUCTION,
|
|
107
|
-
`To show the owner a picture, such as a screenshot of a UI change or a result a picture explains better than words, save it as a PNG, JPEG or WebP file outside the repository (for example in /tmp) and list it as an output: {"kind": "image", "title": "The new sign-in page", "path": "/tmp/sign-in.png"}, with the file's absolute path. Cloop uploads the file and shows it on the run. At most ${RUN_IMAGES_MAX} images, each under ${RUN_IMAGE_MAX_BYTES / (1024 * 1024)} MB. On a Cloop Box, take a picture of a website with the cloop \`browser\` tool: action screenshot shows you the page, and with a title Cloop also attaches the picture to this run and shows it to the owner. You need not list it in your outputs. Use the Playwright browser tool only for a page on localhost, and list its file by path.`,
|
|
108
|
-
`To hand the owner a file Cloop cannot show, such as a spreadsheet, a deck, a Word document, a PDF or a CSV, list it as an output: {"kind": "file", "title": "Converge model", "path": "/abs/path/Converge_Model.xlsx"}, with the file's absolute path. Cloop uploads it and the owner downloads it from the Task. Never give the owner a path on this machine as the deliverable: they cannot open it. A file is one of ${fileTypes()}, named with its type's extension. At most ${RUN_FILES_MAX} files, each under ${RUN_FILE_MAX_BYTES / (1024 * 1024)} MB. A page you write (a report, notes, research) is a doc output with the whole text in its body, never a Markdown file: Cloop shows the page and the owner can download it there.`,
|
|
109
|
-
`To let the owner open a web app or page you are running on this machine, such as a dev server, leave the server running after your turn ends: start it in the background, detached from your shell (for example \`nohup npm run dev -- --port 5173 > /tmp/dev.log 2>&1 &\`), and check it answers on its port. Then list it as an output: {"kind": "preview", "title": "The new sign-in page", "port": 5173, "path": "/sign-in"}, with the port it listens on and an optional path to open first. Cloop gives the owner a private link to it for ${PREVIEW_HOURS} hours while this machine is on, or ${BOX_PREVIEW_HOURS} hours on a Cloop Box, where a live preview keeps the box awake: say how long when you give the link. At most ${RUN_PREVIEWS_MAX} previews a run.`,
|
|
110
|
-
`When you started something that keeps running after this turn (a build, a deploy, a long job) or you wait on something outside, do not wait in the turn: add "check_back": {"in_minutes": 120, "why": "Read the training log and report the score."} to the block. Cloop sends you a message in this conversation then, with your why, and you carry on from there. Give ${CHECK_BACK_MIN_MINUTES} to ${CHECK_BACK_MAX_MINUTES} minutes. Leave it out when the work is done.`
|
|
111
|
-
].join("\n");
|
|
112
|
-
var SUMMARY_MAX = 4e3;
|
|
113
|
-
var ASKS_MAX = 1e3;
|
|
114
|
-
var DOC_BODY_MAX = 8e3;
|
|
115
|
-
var ITEMS_MAX = 10;
|
|
116
|
-
var BLOCK = /```cloop-result\s*\n([\s\S]*?)```/g;
|
|
117
|
-
var text = (v, max) => typeof v === "string" && v.length <= max;
|
|
118
|
-
var optionalText = (v, max) => v === void 0 || text(v, max);
|
|
119
|
-
function isHttps(v) {
|
|
120
|
-
try {
|
|
121
|
-
return typeof v === "string" && new URL(v).protocol === "https:";
|
|
122
|
-
} catch {
|
|
123
|
-
return false;
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
var GITHUB_PR = /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/(\d+)$/;
|
|
127
|
-
function addressOutput(value) {
|
|
128
|
-
const url = value.trim();
|
|
129
|
-
if (!isHttps(url)) return null;
|
|
130
|
-
const pr = url.match(GITHUB_PR);
|
|
131
|
-
if (pr) return { kind: "pr", title: `Pull request #${pr[1]}`, url };
|
|
132
|
-
const { host, pathname } = new URL(url);
|
|
133
|
-
return { kind: "link", title: `${host}${pathname === "/" ? "" : pathname}`.slice(0, 120), url };
|
|
134
|
-
}
|
|
135
|
-
function readOutput(o) {
|
|
136
|
-
if (typeof o === "string") return addressOutput(o);
|
|
137
|
-
if (!o || typeof o !== "object") return null;
|
|
138
|
-
const out = o;
|
|
139
|
-
if (!text(out.title, 120)) return null;
|
|
140
|
-
const title = out.title;
|
|
141
|
-
switch (out.kind) {
|
|
142
|
-
case "pr":
|
|
143
|
-
case "link":
|
|
144
|
-
return isHttps(out.url) ? out.kind === "pr" ? { kind: "pr", title, url: out.url } : { kind: "link", title, url: out.url } : null;
|
|
145
|
-
case "draft":
|
|
146
|
-
return text(out.body, 4e3) && optionalText(out.to, 200) && (out.url === void 0 || isHttps(out.url)) ? {
|
|
147
|
-
kind: "draft",
|
|
148
|
-
title,
|
|
149
|
-
body: out.body,
|
|
150
|
-
...out.to !== void 0 ? { to: out.to } : {},
|
|
151
|
-
...out.url !== void 0 ? { url: out.url } : {}
|
|
152
|
-
} : null;
|
|
153
|
-
case "doc": {
|
|
154
|
-
const body = typeof out.body === "string" && out.body.length > DOC_BODY_MAX ? `${out.body.slice(0, DOC_BODY_MAX - 1)}\u2026` : out.body;
|
|
155
|
-
if (!optionalText(body, DOC_BODY_MAX) || out.url !== void 0 && !isHttps(out.url)) return null;
|
|
156
|
-
if (out.url === void 0 && !body?.trim()) return null;
|
|
157
|
-
return {
|
|
158
|
-
kind: "doc",
|
|
159
|
-
title,
|
|
160
|
-
...out.url !== void 0 ? { url: out.url } : {},
|
|
161
|
-
...body !== void 0 ? { body } : {}
|
|
162
|
-
};
|
|
163
|
-
}
|
|
164
|
-
case "image": {
|
|
165
|
-
const media = typeof out.media === "string" && RUN_MEDIA_KEY.test(out.media) ? out.media : void 0;
|
|
166
|
-
if (out.path === void 0) return media ? { kind: "image", title, media } : null;
|
|
167
|
-
if (!text(out.path, 400)) return null;
|
|
168
|
-
return { kind: "image", title, path: out.path, ...media ? { media } : {} };
|
|
169
|
-
}
|
|
170
|
-
// Only the runner writes a file's `media` or `unsent`, after this read: a run that wrote its own claims nothing.
|
|
171
|
-
case "file":
|
|
172
|
-
return text(out.path, 400) ? { kind: "file", title, path: out.path } : null;
|
|
173
|
-
case "preview":
|
|
174
|
-
if (!isPort(out.port) || out.path !== void 0 && !isPreviewPath(out.path)) return null;
|
|
175
|
-
return {
|
|
176
|
-
kind: "preview",
|
|
177
|
-
title,
|
|
178
|
-
port: out.port,
|
|
179
|
-
...out.path !== void 0 ? { path: out.path } : {},
|
|
180
|
-
...typeof out.preview === "string" && PREVIEW_ID.test(out.preview) ? { preview: out.preview } : {}
|
|
181
|
-
};
|
|
182
|
-
case "wizard":
|
|
183
|
-
return Array.isArray(out.steps) && out.steps.length ? { kind: "wizard", title, steps: out.steps } : null;
|
|
184
|
-
default:
|
|
185
|
-
return null;
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
function readCheckBack(v) {
|
|
189
|
-
if (!v || typeof v !== "object") return null;
|
|
190
|
-
const { in_minutes: minutes, why } = v;
|
|
191
|
-
if (typeof minutes !== "number" || !Number.isFinite(minutes) || typeof why !== "string" || !why.trim()) return null;
|
|
192
|
-
return {
|
|
193
|
-
in_minutes: Math.min(CHECK_BACK_MAX_MINUTES, Math.max(CHECK_BACK_MIN_MINUTES, Math.round(minutes))),
|
|
194
|
-
why: why.trim().slice(0, CHECK_BACK_WHY_MAX)
|
|
195
|
-
};
|
|
196
|
-
}
|
|
197
|
-
function readUnderway(v) {
|
|
198
|
-
return (Array.isArray(v) ? v : []).flatMap((u) => {
|
|
199
|
-
const { title, url } = u && typeof u === "object" ? u : {};
|
|
200
|
-
return text(title, 120) && typeof url === "string" && GITHUB_WORK.test(url) ? [{ title, url }] : [];
|
|
201
|
-
}).slice(0, UNDERWAY_MAX);
|
|
202
|
-
}
|
|
203
|
-
function readCheck(c) {
|
|
204
|
-
if (!c || typeof c !== "object") return null;
|
|
205
|
-
const check = c;
|
|
206
|
-
if (!text(check.name, 80) || !["passed", "failed", "skipped"].includes(check.outcome)) return null;
|
|
207
|
-
if (!optionalText(check.detail, 200)) return null;
|
|
208
|
-
return {
|
|
209
|
-
name: check.name,
|
|
210
|
-
outcome: check.outcome,
|
|
211
|
-
...check.detail !== void 0 ? { detail: check.detail } : {}
|
|
212
|
-
};
|
|
213
|
-
}
|
|
214
|
-
function readRunResult(message) {
|
|
215
|
-
const none = { dropped: { outputs: 0, checks: 0 } };
|
|
216
|
-
const block = [...(message ?? "").matchAll(BLOCK)].at(-1)?.[1];
|
|
217
|
-
if (!block) return none;
|
|
218
|
-
let value;
|
|
219
|
-
try {
|
|
220
|
-
value = JSON.parse(block);
|
|
221
|
-
} catch {
|
|
222
|
-
return none;
|
|
223
|
-
}
|
|
224
|
-
const summary = typeof value?.summary === "string" ? value.summary.trim() : "";
|
|
225
|
-
if (!summary) return none;
|
|
226
|
-
const list = (v) => Array.isArray(v) ? v : [];
|
|
227
|
-
const asks = typeof value?.asks === "string" ? value.asks.trim() : "";
|
|
228
|
-
const outputs = list(value?.outputs).flatMap((o) => readOutput(o) ?? []);
|
|
229
|
-
const checks = list(value?.checks).flatMap((c) => readCheck(c) ?? []);
|
|
230
|
-
const checkBack = readCheckBack(value?.check_back);
|
|
231
|
-
const underway = readUnderway(value?.underway);
|
|
232
|
-
return {
|
|
233
|
-
result: {
|
|
234
|
-
summary: summary.length > SUMMARY_MAX ? `${summary.slice(0, SUMMARY_MAX - 1)}\u2026` : summary,
|
|
235
|
-
outputs: outputs.slice(0, ITEMS_MAX),
|
|
236
|
-
checks: checks.slice(0, ITEMS_MAX),
|
|
237
|
-
...value?.nothing_new === true ? { nothing_new: true } : {},
|
|
238
|
-
...asks ? { asks: asks.length > ASKS_MAX ? `${asks.slice(0, ASKS_MAX - 1)}\u2026` : asks } : {},
|
|
239
|
-
...checkBack ? { check_back: checkBack } : {},
|
|
240
|
-
...underway.length ? { underway } : {}
|
|
241
|
-
},
|
|
242
|
-
dropped: { outputs: list(value?.outputs).length - outputs.length, checks: list(value?.checks).length - checks.length }
|
|
243
|
-
};
|
|
244
|
-
}
|
|
245
|
-
function hasResultBlock(message) {
|
|
246
|
-
return /```cloop-result\s*\n/.test(message ?? "");
|
|
247
|
-
}
|
|
248
|
-
function resultText(final, earlier) {
|
|
249
|
-
return (hasResultBlock(final) ? final : hasResultBlock(earlier) ? earlier : final) ?? void 0;
|
|
250
|
-
}
|
|
251
31
|
|
|
252
|
-
// src/
|
|
253
|
-
var
|
|
254
|
-
var
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
);
|
|
261
|
-
}
|
|
262
|
-
function resultPrUrl(finalMessage) {
|
|
263
|
-
const result = parseRunResult(finalMessage);
|
|
264
|
-
if (!result) return prUrlIn(finalMessage);
|
|
265
|
-
const prs = result.outputs.flatMap((o) => o.kind === "pr" ? [o.url] : []);
|
|
266
|
-
return prs.at(-1) ?? null;
|
|
267
|
-
}
|
|
268
|
-
function parseRunResult(message) {
|
|
269
|
-
return readRunResult(message).result;
|
|
270
|
-
}
|
|
271
|
-
function droppedLine(dropped, run2) {
|
|
272
|
-
return dropped.outputs || dropped.checks ? `result_items_dropped run=${run2} outputs=${dropped.outputs} checks=${dropped.checks}` : null;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
// src/drivers/driver.ts
|
|
276
|
-
function ownHarnessFirst(reports, driver) {
|
|
277
|
-
return reports.filter((h) => h !== null && (h.id === driver || h.signedIn)).sort((a, b) => Number(b.id === driver) - Number(a.id === driver));
|
|
278
|
-
}
|
|
279
|
-
var RUNTIME_MODES = /* @__PURE__ */ new Set([
|
|
280
|
-
"approval-required",
|
|
281
|
-
"auto-accept-edits",
|
|
282
|
-
"auto",
|
|
283
|
-
"full-access"
|
|
284
|
-
]);
|
|
285
|
-
function cloneLine(repository) {
|
|
286
|
-
return `This Task names the repository ${repository}, and this machine has no project for it. Clone it outside this folder, or find it on this machine, and work in it.`;
|
|
287
|
-
}
|
|
288
|
-
var BoxToolError = class extends Error {
|
|
289
|
-
constructor(code) {
|
|
290
|
-
super(code);
|
|
291
|
-
this.code = code;
|
|
292
|
-
this.name = "BoxToolError";
|
|
293
|
-
}
|
|
294
|
-
code;
|
|
295
|
-
};
|
|
296
|
-
var CLOOP_THREAD_PREFIX = "cloop:";
|
|
297
|
-
function questionLine(questions) {
|
|
298
|
-
return questions.map(
|
|
299
|
-
(x) => x.options?.length ? `${x.question} (${x.options.map((o) => o.label).join(", ")})` : x.question
|
|
300
|
-
).join(" ").slice(0, 500);
|
|
301
|
-
}
|
|
302
|
-
function isProgressSentence(value) {
|
|
303
|
-
return typeof value === "string" && /\S[ \t]+\S/.test(value.trim().split(/\r?\n/)[0] ?? "");
|
|
304
|
-
}
|
|
305
|
-
var PROGRESS_MS = 3e4;
|
|
306
|
-
var IDLE_SETTLE_MS = 20 * 6e4;
|
|
307
|
-
function holdsForNextTurn(turn) {
|
|
308
|
-
return turn.completed && !turn.limited && !turn.result;
|
|
309
|
-
}
|
|
310
|
-
var RUN_TEXT_MAX = 4e3;
|
|
311
|
-
function finalWords(text3) {
|
|
312
|
-
return text3.replace(/\r\n?/g, "\n").replace(/[ \t]+$/gm, "").replace(/\n{3,}/g, "\n\n").trim();
|
|
313
|
-
}
|
|
314
|
-
function nextProgress(clock, text3, now, ms = PROGRESS_MS, force = false) {
|
|
315
|
-
const summary = (parseRunResult(text3)?.summary ?? text3.split("```cloop-result")[0] ?? "").replace(/\s+/g, " ").trim().slice(0, RUN_TEXT_MAX);
|
|
316
|
-
if (!isProgressSentence(summary)) return null;
|
|
317
|
-
if (!force && now - clock.lastProgressAt < ms) return null;
|
|
318
|
-
clock.lastProgressAt = now;
|
|
319
|
-
return summary;
|
|
320
|
-
}
|
|
321
|
-
var YES_WORDS = /* @__PURE__ */ new Set([
|
|
322
|
-
"y",
|
|
323
|
-
"yes",
|
|
324
|
-
"yep",
|
|
325
|
-
"yeah",
|
|
326
|
-
"allow",
|
|
327
|
-
"allow it",
|
|
328
|
-
"ok",
|
|
329
|
-
"okay",
|
|
330
|
-
"approve",
|
|
331
|
-
"approved",
|
|
332
|
-
"go ahead",
|
|
333
|
-
"sure",
|
|
334
|
-
"do it"
|
|
335
|
-
]);
|
|
336
|
-
function isYes(reply) {
|
|
337
|
-
return YES_WORDS.has(
|
|
338
|
-
reply.trim().toLowerCase().replace(/[.!\s]+$/, "")
|
|
339
|
-
);
|
|
340
|
-
}
|
|
341
|
-
var HARNESS_LIMIT = /usage limit|reached your [\w .-]{0,40}limit|hit your [\w .-]{0,40}limit|out of (usage )?credits/i;
|
|
342
|
-
function limitedModel(said) {
|
|
343
|
-
const name = /reached your ([\w .-]{1,40}?) limit/i.exec(said ?? "")?.[1];
|
|
344
|
-
return name && !/usage|weekly|daily|session|hour|month/i.test(name) ? name : null;
|
|
345
|
-
}
|
|
346
|
-
function refusedModel(said) {
|
|
347
|
-
return /The '([^']+)' model is not supported/i.exec(said ?? "")?.[1] ?? null;
|
|
348
|
-
}
|
|
349
|
-
function nextModel(listed, tried) {
|
|
350
|
-
return listed.find((m) => !tried.includes(m)) ?? null;
|
|
351
|
-
}
|
|
352
|
-
var MODEL_REFUSAL_MS = 24 * 36e5;
|
|
353
|
-
function refusedRecently(refusals, now) {
|
|
354
|
-
return refusals.filter((r) => now - Date.parse(r.at) < MODEL_REFUSAL_MS).map((r) => r.model);
|
|
355
|
-
}
|
|
356
|
-
function refusedModelLine(harness, refused, next) {
|
|
357
|
-
return `${harness} cannot use ${refused} on this account, so this ran on ${next}.`;
|
|
358
|
-
}
|
|
359
|
-
function apiErrorWords(said) {
|
|
360
|
-
try {
|
|
361
|
-
const inner = JSON.parse(said)?.error?.message;
|
|
362
|
-
return typeof inner === "string" && inner.trim() ? inner.trim() : said;
|
|
363
|
-
} catch {
|
|
364
|
-
return said;
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
var HARNESS_SIGNED_OUT = /^\s*(Failed to authenticate:\s*OAuth session expired and could not be refreshed\b|Your access token could not be refreshed\b|Your authentication session could not be refreshed\b|Not signed in\. Please run 'codex login'|unexpected status 401\b)/i;
|
|
368
|
-
var CLAUDE_AUTH_LOCKED = /another Claude Code process is refreshing/i;
|
|
369
|
-
var LIMIT_HOLD_MS = 60 * 6e4;
|
|
370
|
-
var HARNESS_STATE = {
|
|
371
|
-
limit: "at its usage limit",
|
|
372
|
-
signed_out: "signed out here",
|
|
373
|
-
missing: "not installed here"
|
|
374
|
-
};
|
|
375
|
-
function movedLine(reason, from, to, tense) {
|
|
376
|
-
return `${from} ${tense} ${HARNESS_STATE[reason]}, so ${to} did this run.`;
|
|
377
|
-
}
|
|
378
|
-
function movingLine(reason, from, to) {
|
|
379
|
-
return `${from} is ${HARNESS_STATE[reason]}, so I moved this to ${to}`;
|
|
32
|
+
// src/t3.ts
|
|
33
|
+
var T3_SCOPE = "orchestration:read orchestration:operate diagnostics:read";
|
|
34
|
+
var REQUIRED_SCOPES = ["orchestration:read", "orchestration:operate"];
|
|
35
|
+
var MIN_PROTOCOL = 2;
|
|
36
|
+
async function readEnvironment(t3Url, fetchFn = fetch) {
|
|
37
|
+
const res = await fetchFn(`${t3Url}/.well-known/t3/environment`);
|
|
38
|
+
if (!res.ok) throw new Error(`T3 environment ${res.status} at ${t3Url}`);
|
|
39
|
+
return await res.json();
|
|
380
40
|
}
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
41
|
+
async function exchangePairing(t3Url, credential, label, fetchFn = fetch) {
|
|
42
|
+
const form = new URLSearchParams({
|
|
43
|
+
grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
|
|
44
|
+
subject_token: credential,
|
|
45
|
+
subject_token_type: "urn:t3:params:oauth:token-type:environment-bootstrap",
|
|
46
|
+
requested_token_type: "urn:ietf:params:oauth:token-type:access_token",
|
|
47
|
+
scope: T3_SCOPE,
|
|
48
|
+
client_label: label,
|
|
49
|
+
client_device_type: "bot"
|
|
50
|
+
});
|
|
51
|
+
const res = await fetchFn(`${t3Url}/oauth/token`, { method: "POST", body: form });
|
|
52
|
+
if (!res.ok) throw new T3HttpError("token exchange", res.status);
|
|
53
|
+
const token = await res.json();
|
|
54
|
+
if (!REQUIRED_SCOPES.every((s) => hasScope(token.scope, s)) || scopes(token.scope).some((s) => !hasScope(T3_SCOPE, s)))
|
|
55
|
+
throw new Error(`T3 granted scope "${token.scope}", wanted "${T3_SCOPE}"`);
|
|
56
|
+
return token;
|
|
389
57
|
}
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
dir: (home) => join(home, CONFIG_DIR),
|
|
398
|
-
suffix: "",
|
|
399
|
-
flag: "",
|
|
400
|
-
mcpUrl: "https://app.mycloop.com/api/mcp/mcp",
|
|
401
|
-
mcpName: "cloop"
|
|
402
|
-
},
|
|
403
|
-
staging: {
|
|
404
|
-
origin: STAGING_ORIGIN,
|
|
405
|
-
dir: (home) => join(home, CONFIG_DIR, "staging"),
|
|
406
|
-
suffix: "staging",
|
|
407
|
-
flag: "--staging",
|
|
408
|
-
mcpUrl: "https://mcp-staging.mycloop.com/mcp",
|
|
409
|
-
mcpName: "cloop-staging"
|
|
58
|
+
var scopes = (s) => s.split(/\s+/).filter(Boolean);
|
|
59
|
+
var hasScope = (scope, name) => scopes(scope ?? "").includes(name);
|
|
60
|
+
var T3HttpError = class extends Error {
|
|
61
|
+
constructor(path, status) {
|
|
62
|
+
super(`T3 ${path} ${status}`);
|
|
63
|
+
this.status = status;
|
|
64
|
+
this.name = "T3HttpError";
|
|
410
65
|
}
|
|
66
|
+
status;
|
|
411
67
|
};
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
}
|
|
418
|
-
function runnerDir(env = runnerEnvironment(), home = homedir()) {
|
|
419
|
-
return ENVIRONMENTS[env].dir(home);
|
|
420
|
-
}
|
|
421
|
-
function runnerPath(env, override, inDir) {
|
|
422
|
-
const own = runnerEnvironment();
|
|
423
|
-
return override && (env ?? own) === own ? override : inDir(runnerDir(env ?? own));
|
|
424
|
-
}
|
|
425
|
-
function cloopCommand(env, args) {
|
|
426
|
-
return ["cloop", args, ENVIRONMENTS[env].flag].filter(Boolean).join(" ");
|
|
427
|
-
}
|
|
428
|
-
var KIND = {
|
|
429
|
-
workstation: { name: "box", task: "Cloop Box" },
|
|
430
|
-
local: { name: "runner", task: "Cloop Runner" }
|
|
431
|
-
};
|
|
432
|
-
function serviceIdentity(kind, env) {
|
|
433
|
-
const { suffix } = ENVIRONMENTS[env];
|
|
434
|
-
const { name, task } = KIND[kind];
|
|
435
|
-
const file = ["cloop", name, suffix].filter(Boolean).join("-");
|
|
436
|
-
return {
|
|
437
|
-
label: ["com.cloop", name, suffix].filter(Boolean).join("."),
|
|
438
|
-
unit: `${file}.service`,
|
|
439
|
-
task: suffix ? `${task} ${suffix[0]?.toUpperCase()}${suffix.slice(1)}` : task,
|
|
440
|
-
file
|
|
441
|
-
};
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
// src/spawn-command.ts
|
|
445
|
-
import { execFileSync } from "child_process";
|
|
446
|
-
function commandFor(bin, args, platform = process.platform, comspec = process.env.ComSpec) {
|
|
447
|
-
if (platform !== "win32") return { file: bin, args };
|
|
448
|
-
const executable = windowsExecutable(bin) ?? bin;
|
|
449
|
-
if (!/\.(cmd|bat)$/i.test(executable)) return { file: executable, args };
|
|
450
|
-
return {
|
|
451
|
-
file: comspec ?? "cmd.exe",
|
|
452
|
-
args: ["/d", "/s", "/c", `"${[executable, ...args].map(quoteWindowsArg).join(" ")}"`],
|
|
453
|
-
windowsVerbatimArguments: true
|
|
454
|
-
};
|
|
455
|
-
}
|
|
456
|
-
function quoteWindowsArg(arg) {
|
|
457
|
-
if (arg && !/[ \t"]/.test(arg)) return arg;
|
|
458
|
-
let quoted = '"';
|
|
459
|
-
let backslashes = 0;
|
|
460
|
-
for (const ch of arg) {
|
|
461
|
-
if (ch === "\\") {
|
|
462
|
-
backslashes++;
|
|
463
|
-
continue;
|
|
464
|
-
}
|
|
465
|
-
quoted += "\\".repeat(ch === '"' ? backslashes * 2 + 1 : backslashes) + ch;
|
|
466
|
-
backslashes = 0;
|
|
467
|
-
}
|
|
468
|
-
return `${quoted}${"\\".repeat(backslashes * 2)}"`;
|
|
469
|
-
}
|
|
470
|
-
function preferExecutable(lines) {
|
|
471
|
-
return lines.find((line) => /\.exe$/i.test(line)) ?? lines.find((line) => /\.(cmd|bat)$/i.test(line)) ?? null;
|
|
472
|
-
}
|
|
473
|
-
var windowsExecutables = /* @__PURE__ */ new Map();
|
|
474
|
-
function windowsExecutable(bin) {
|
|
475
|
-
if (/[\\/]/.test(bin)) return bin;
|
|
476
|
-
if (process.platform !== "win32") return null;
|
|
477
|
-
const key = JSON.stringify([bin, process.env.PATH, process.env.PATHEXT]);
|
|
478
|
-
if (windowsExecutables.has(key)) return windowsExecutables.get(key) ?? null;
|
|
479
|
-
let resolved = null;
|
|
480
|
-
try {
|
|
481
|
-
resolved = preferExecutable(
|
|
482
|
-
execFileSync("where.exe", [bin], { encoding: "utf-8", timeout: 5e3 }).split(/\r?\n/).map((line) => line.trim()).filter(Boolean)
|
|
483
|
-
);
|
|
484
|
-
} catch {
|
|
485
|
-
}
|
|
486
|
-
windowsExecutables.set(key, resolved);
|
|
487
|
-
if (!resolved)
|
|
488
|
-
console.error(
|
|
489
|
-
`[runner:spawn] Could not resolve ${bin} to an executable on PATH. Install the agent and reconnect the runner.`
|
|
490
|
-
);
|
|
491
|
-
return resolved;
|
|
492
|
-
}
|
|
493
|
-
function windowsPowerShellEnv(env = process.env) {
|
|
494
|
-
return Object.fromEntries(
|
|
495
|
-
Object.entries(env).filter(([key]) => key.toLowerCase() !== "psmodulepath")
|
|
496
|
-
);
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
// src/runner-config.ts
|
|
500
|
-
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
|
|
501
|
-
import { dirname, join as join2 } from "path";
|
|
502
|
-
var BOX_FILE = "box.json";
|
|
503
|
-
function boxPath(env = runnerEnvironment()) {
|
|
504
|
-
return runnerPath(env, process.env.CLOOP_BOX_FILE, (dir) => join2(dir, BOX_FILE));
|
|
505
|
-
}
|
|
506
|
-
function isLocal(cfg) {
|
|
507
|
-
return cfg.driver === "claude-code" || cfg.driver === "codex";
|
|
508
|
-
}
|
|
509
|
-
function isHosted(cfg) {
|
|
510
|
-
return cfg.driver === "cloudroom";
|
|
511
|
-
}
|
|
512
|
-
function isT3(cfg) {
|
|
513
|
-
return cfg.driver === void 0 || cfg.driver === "t3";
|
|
514
|
-
}
|
|
515
|
-
function showsOtherThreads(cfg) {
|
|
516
|
-
return cfg?.hideOtherThreads !== true;
|
|
517
|
-
}
|
|
518
|
-
function otherThreadsChoice(argv, previous) {
|
|
519
|
-
if (argv.includes("--hide-other-threads")) return true;
|
|
520
|
-
if (argv.includes("--show-other-threads")) return false;
|
|
521
|
-
return previous?.hideOtherThreads === true;
|
|
522
|
-
}
|
|
523
|
-
function readRunnerConfig(env) {
|
|
524
|
-
let parsed;
|
|
525
|
-
try {
|
|
526
|
-
parsed = JSON.parse(readFileSync(boxPath(env), "utf-8"));
|
|
527
|
-
} catch {
|
|
528
|
-
return null;
|
|
529
|
-
}
|
|
530
|
-
if (parsed.driver === "claude-code" || parsed.driver === "codex") {
|
|
531
|
-
const ok = typeof parsed.deviceToken === "string" && typeof parsed.environmentId === "string" && typeof parsed.bin === "string" && Array.isArray(parsed.repos);
|
|
532
|
-
return ok ? parsed : null;
|
|
533
|
-
}
|
|
534
|
-
if (parsed.driver === "cloudroom") {
|
|
535
|
-
const ok = ["harness", "coreUrl", "coreToken", "deviceToken", "origin", "environmentId"].every(
|
|
536
|
-
(key) => typeof parsed[key] === "string" && parsed[key]
|
|
537
|
-
);
|
|
538
|
-
return ok && /^[a-z0-9-]{1,40}$/.test(parsed.harness) ? parsed : null;
|
|
68
|
+
var T3Client = class {
|
|
69
|
+
constructor(t3Url, token, fetchFn = fetch) {
|
|
70
|
+
this.t3Url = t3Url;
|
|
71
|
+
this.token = token;
|
|
72
|
+
this.fetchFn = fetchFn;
|
|
539
73
|
}
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
chmodSync(temp, 384);
|
|
550
|
-
renameSync(temp, path);
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
// src/outside-sessions.ts
|
|
554
|
-
import { createReadStream } from "fs";
|
|
555
|
-
import { readFile, readdir, stat } from "fs/promises";
|
|
556
|
-
import { homedir as homedir2 } from "os";
|
|
557
|
-
import { dirname as dirname2, join as join3 } from "path";
|
|
558
|
-
import { createInterface } from "readline";
|
|
559
|
-
var seen = /* @__PURE__ */ new Map();
|
|
560
|
-
var UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
|
|
561
|
-
async function listOutsideSessions(root = join3(homedir2(), ".claude", "projects"), own = /* @__PURE__ */ new Set(), now = Date.now()) {
|
|
562
|
-
const files = [];
|
|
563
|
-
for (const project of await readdir(root, { withFileTypes: true }).catch(() => [])) {
|
|
564
|
-
if (!project.isDirectory()) continue;
|
|
565
|
-
for (const entry of await readdir(join3(root, project.name), { withFileTypes: true }).catch(
|
|
566
|
-
() => []
|
|
567
|
-
)) {
|
|
568
|
-
if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
|
|
569
|
-
const id = entry.name.slice(0, -6);
|
|
570
|
-
if (!UUID.test(id) || own.has(id)) continue;
|
|
571
|
-
const path = join3(root, project.name, entry.name);
|
|
572
|
-
const info = await stat(path).catch(() => null);
|
|
573
|
-
if (info && info.mtimeMs >= now - 7 * 864e5)
|
|
574
|
-
files.push({ id, project: project.name.slice(0, 200), file: path, mtime: info.mtimeMs });
|
|
575
|
-
}
|
|
74
|
+
t3Url;
|
|
75
|
+
token;
|
|
76
|
+
fetchFn;
|
|
77
|
+
async http(path, headers = {}) {
|
|
78
|
+
const res = await this.fetchFn(`${this.t3Url}${path}`, {
|
|
79
|
+
headers: { authorization: `Bearer ${this.token}`, ...headers }
|
|
80
|
+
});
|
|
81
|
+
if (!res.ok) throw new T3HttpError(path, res.status);
|
|
82
|
+
return await res.json();
|
|
576
83
|
}
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
const { title, cwd } = await claudeMeta(file.file, file.mtime);
|
|
582
|
-
results.push({
|
|
583
|
-
id: file.id,
|
|
584
|
-
project: file.project,
|
|
585
|
-
updatedAt: new Date(file.mtime).toISOString(),
|
|
586
|
-
status: "idle",
|
|
587
|
-
...cwd ? { cwd } : {},
|
|
588
|
-
...title ? { title } : {}
|
|
84
|
+
async openSocket() {
|
|
85
|
+
const ticket = await this.fetchFn(`${this.t3Url}/api/auth/websocket-ticket`, {
|
|
86
|
+
method: "POST",
|
|
87
|
+
headers: { authorization: `Bearer ${this.token}` }
|
|
589
88
|
});
|
|
89
|
+
if (!ticket.ok) throw new T3HttpError("/api/auth/websocket-ticket", ticket.status);
|
|
90
|
+
const { ticket: wsTicket } = await ticket.json();
|
|
91
|
+
const { WebSocket } = await import("ws");
|
|
92
|
+
const url = `${this.t3Url.replace(/^http/, "ws")}/ws?wsTicket=${encodeURIComponent(wsTicket)}&orchestrationProtocol=2&clientSurface=web&clientAppVersion=cloop-box`;
|
|
93
|
+
return new WebSocket(url);
|
|
590
94
|
}
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
for await (const line of lines) {
|
|
602
|
-
if (!cwd && line.includes('"cwd"')) {
|
|
95
|
+
/** One request over a fresh /ws socket. The daemon makes a few calls a minute, so a socket per call is simpler than keeping one alive. */
|
|
96
|
+
async rpc(tag, payload) {
|
|
97
|
+
const ws = await this.openSocket();
|
|
98
|
+
return new Promise((resolve, reject) => {
|
|
99
|
+
let settled = false;
|
|
100
|
+
const finish = (fn) => {
|
|
101
|
+
if (settled) return;
|
|
102
|
+
settled = true;
|
|
103
|
+
clearTimeout(timer);
|
|
104
|
+
fn();
|
|
603
105
|
try {
|
|
604
|
-
|
|
605
|
-
if (typeof record.cwd === "string" && record.cwd.startsWith("/") && record.cwd.length <= 500)
|
|
606
|
-
cwd = record.cwd;
|
|
106
|
+
ws.close();
|
|
607
107
|
} catch {
|
|
608
108
|
}
|
|
609
|
-
}
|
|
610
|
-
if (!/^\s*\{\s*"type"\s*:\s*"(?:summary|custom-title|title)"/.test(line)) continue;
|
|
611
|
-
try {
|
|
612
|
-
const record = JSON.parse(line);
|
|
613
|
-
const value = record.type === "summary" ? record.summary : record.type === "custom-title" ? record.customTitle : record.title;
|
|
614
|
-
if (typeof value === "string" && value.trim()) title = value.trim().slice(0, 120);
|
|
615
|
-
} catch {
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
} finally {
|
|
619
|
-
lines.close();
|
|
620
|
-
stream.destroy();
|
|
621
|
-
}
|
|
622
|
-
const meta = { mtime, ...title ? { title } : {}, ...cwd ? { cwd } : {} };
|
|
623
|
-
seen.set(file, meta);
|
|
624
|
-
return meta;
|
|
625
|
-
}
|
|
626
|
-
function sessionRoots(home = homedir2()) {
|
|
627
|
-
return { claude: join3(home, ".claude", "projects"), codex: join3(home, ".codex", "sessions") };
|
|
628
|
-
}
|
|
629
|
-
async function findSession(id, roots, harnesses) {
|
|
630
|
-
if (!UUID.test(id)) return null;
|
|
631
|
-
if (harnesses.includes("claude-code")) {
|
|
632
|
-
for (const project of await readdir(roots.claude, { withFileTypes: true }).catch(() => [])) {
|
|
633
|
-
if (!project.isDirectory()) continue;
|
|
634
|
-
const file = join3(roots.claude, project.name, `${id}.jsonl`);
|
|
635
|
-
const info = await stat(file).catch(() => null);
|
|
636
|
-
if (!info?.isFile()) continue;
|
|
637
|
-
const meta = await claudeMeta(file, info.mtimeMs);
|
|
638
|
-
return {
|
|
639
|
-
harness: "claude-code",
|
|
640
|
-
id,
|
|
641
|
-
cwd: meta.cwd ?? null,
|
|
642
|
-
...meta.title ? { title: meta.title } : {},
|
|
643
|
-
mtime: info.mtimeMs
|
|
644
109
|
};
|
|
645
|
-
|
|
110
|
+
const timer = setTimeout(
|
|
111
|
+
() => finish(() => reject(new Error(`T3 rpc ${tag} timed out`))),
|
|
112
|
+
15e3
|
|
113
|
+
);
|
|
114
|
+
ws.on(
|
|
115
|
+
"error",
|
|
116
|
+
(err) => finish(() => reject(err instanceof Error ? err : new Error(String(err))))
|
|
117
|
+
);
|
|
118
|
+
ws.on(
|
|
119
|
+
"close",
|
|
120
|
+
() => finish(() => reject(new Error(`T3 rpc ${tag}: socket closed before a reply`)))
|
|
121
|
+
);
|
|
122
|
+
ws.on("open", () => {
|
|
123
|
+
ws.send(JSON.stringify({ _tag: "Request", id: 1, tag, payload, headers: [] }));
|
|
124
|
+
});
|
|
125
|
+
ws.on("message", (data) => {
|
|
126
|
+
for (const msg of parseFrames(data)) {
|
|
127
|
+
if (msg._tag !== "Exit" || String(msg.requestId) !== "1") continue;
|
|
128
|
+
const exit = msg.exit;
|
|
129
|
+
if (exit._tag === "Success") finish(() => resolve(exit.value));
|
|
130
|
+
else {
|
|
131
|
+
finish(
|
|
132
|
+
() => reject(
|
|
133
|
+
new Error(`T3 rpc ${tag} failed: ${JSON.stringify(exit.cause).slice(0, 300)}`)
|
|
134
|
+
)
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
});
|
|
646
140
|
}
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
141
|
+
/**
|
|
142
|
+
* A streaming request, such as `orchestration.subscribeThread`, on its own
|
|
143
|
+
* socket. Every item is acked, as Effect RPC requires. `done` resolves with
|
|
144
|
+
* the reason the stream ended and never rejects; `close` interrupts it.
|
|
145
|
+
*/
|
|
146
|
+
async stream(tag, payload, onItem) {
|
|
147
|
+
const ws = await this.openSocket();
|
|
148
|
+
let resolveDone = () => {
|
|
149
|
+
};
|
|
150
|
+
const done = new Promise((r) => {
|
|
151
|
+
resolveDone = r;
|
|
152
|
+
});
|
|
153
|
+
const end = (reason) => {
|
|
154
|
+
resolveDone(reason);
|
|
155
|
+
try {
|
|
156
|
+
ws.close();
|
|
157
|
+
} catch {
|
|
660
158
|
}
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
const files = (await codexFiles(root, now - 7 * 864e5)).filter((f) => !own.has(f.id)).slice(0, 20);
|
|
667
|
-
const titles = files.length ? await codexTitles(root) : /* @__PURE__ */ new Map();
|
|
668
|
-
const results = [];
|
|
669
|
-
for (const file of files) {
|
|
670
|
-
const meta = await codexMeta(file.file, file.mtime);
|
|
671
|
-
if (meta?.id !== file.id) continue;
|
|
672
|
-
const title = titles.get(file.id);
|
|
673
|
-
results.push({
|
|
674
|
-
id: file.id,
|
|
675
|
-
updatedAt: new Date(file.mtime).toISOString(),
|
|
676
|
-
status: "idle",
|
|
677
|
-
...meta.cwd ? { cwd: meta.cwd } : {},
|
|
678
|
-
...title ? { title } : {}
|
|
159
|
+
};
|
|
160
|
+
ws.on("error", (err) => end(`error: ${err instanceof Error ? err.message : String(err)}`));
|
|
161
|
+
ws.on("close", () => end("closed"));
|
|
162
|
+
ws.on("open", () => {
|
|
163
|
+
ws.send(JSON.stringify({ _tag: "Request", id: 1, tag, payload, headers: [] }));
|
|
679
164
|
});
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
|
692
|
-
const id = entry.isFile() ? ROLLOUT.exec(entry.name)?.[1] : void 0;
|
|
693
|
-
if (!id) continue;
|
|
694
|
-
const file = join3(dir, entry.name);
|
|
695
|
-
const info = await stat(file).catch(() => null);
|
|
696
|
-
if (info && info.mtimeMs >= since) out.push({ id, file, mtime: info.mtimeMs });
|
|
165
|
+
ws.on("message", (data) => {
|
|
166
|
+
for (const msg of parseFrames(data)) {
|
|
167
|
+
if (String(msg.requestId) !== "1") continue;
|
|
168
|
+
if (msg._tag === "Chunk") {
|
|
169
|
+
ws.send(JSON.stringify({ _tag: "Ack", requestId: msg.requestId }));
|
|
170
|
+
for (const value of msg.values) onItem(value);
|
|
171
|
+
} else if (msg._tag === "Exit") {
|
|
172
|
+
const exit = msg.exit;
|
|
173
|
+
end(
|
|
174
|
+
exit._tag === "Success" ? "exit" : `failed: ${JSON.stringify(exit.cause).slice(0, 300)}`
|
|
175
|
+
);
|
|
697
176
|
}
|
|
698
177
|
}
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
const lines = createInterface({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });
|
|
707
|
-
let meta = null;
|
|
708
|
-
try {
|
|
709
|
-
for await (const line of lines) {
|
|
710
|
-
try {
|
|
711
|
-
const record = JSON.parse(line);
|
|
712
|
-
const payload = record?.type === "session_meta" ? record.payload : null;
|
|
713
|
-
if (typeof payload?.id === "string") {
|
|
714
|
-
const cwd = payload.cwd;
|
|
715
|
-
meta = {
|
|
716
|
-
id: payload.id,
|
|
717
|
-
cwd: typeof cwd === "string" && cwd.startsWith("/") && cwd.length <= 500 ? cwd : null
|
|
718
|
-
};
|
|
178
|
+
});
|
|
179
|
+
return {
|
|
180
|
+
done,
|
|
181
|
+
close: () => {
|
|
182
|
+
try {
|
|
183
|
+
ws.send(JSON.stringify({ _tag: "Interrupt", requestId: "1" }));
|
|
184
|
+
} catch {
|
|
719
185
|
}
|
|
720
|
-
|
|
186
|
+
end("closed by client");
|
|
721
187
|
}
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
}
|
|
732
|
-
async function codexTitles(root) {
|
|
733
|
-
const titles = /* @__PURE__ */ new Map();
|
|
734
|
-
const text3 = await readFile(join3(dirname2(root), "session_index.jsonl"), "utf8").catch(() => "");
|
|
735
|
-
for (const line of text3.split("\n")) {
|
|
736
|
-
try {
|
|
737
|
-
const record = JSON.parse(line);
|
|
738
|
-
if (typeof record?.id === "string" && typeof record.thread_name === "string" && record.thread_name.trim())
|
|
739
|
-
titles.set(record.id, record.thread_name.trim().slice(0, 120));
|
|
740
|
-
} catch {
|
|
741
|
-
}
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
function parseFrames(data) {
|
|
192
|
+
try {
|
|
193
|
+
const raw = JSON.parse(String(data));
|
|
194
|
+
return Array.isArray(raw) ? raw : [raw];
|
|
195
|
+
} catch {
|
|
196
|
+
return [];
|
|
742
197
|
}
|
|
743
|
-
return titles;
|
|
744
198
|
}
|
|
745
199
|
|
|
746
200
|
// src/run-log.ts
|
|
747
201
|
import {
|
|
748
202
|
appendFileSync,
|
|
749
|
-
chmodSync
|
|
750
|
-
mkdirSync
|
|
203
|
+
chmodSync,
|
|
204
|
+
mkdirSync,
|
|
751
205
|
readdirSync,
|
|
752
|
-
renameSync
|
|
206
|
+
renameSync,
|
|
753
207
|
statSync,
|
|
754
208
|
unlinkSync
|
|
755
209
|
} from "fs";
|
|
756
|
-
import { dirname
|
|
210
|
+
import { dirname, join } from "path";
|
|
757
211
|
var RUN_LOG_LINE_MAX = 500;
|
|
758
212
|
var RUN_LOG_MAX_BYTES = 5 * 1024 * 1024;
|
|
759
213
|
var RUN_LOG_KEEP_MS = 14 * 24 * 36e5;
|
|
760
214
|
var SAFE_ID = /^[\w-]{1,100}$/;
|
|
761
215
|
function runLogDir(runsFile) {
|
|
762
|
-
return
|
|
216
|
+
return join(dirname(runsFile), "runs");
|
|
763
217
|
}
|
|
764
218
|
function runLogPath(dir, workId) {
|
|
765
|
-
return SAFE_ID.test(workId) ?
|
|
219
|
+
return SAFE_ID.test(workId) ? join(dir, `${workId}.log`) : null;
|
|
766
220
|
}
|
|
767
221
|
var SECRETS = [
|
|
768
222
|
// The whole block, to its END line or the end of the text: a cut-off paste still hides its body.
|
|
@@ -789,16 +243,16 @@ var SECRETS = [
|
|
|
789
243
|
[/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}/g, "[redacted]"]
|
|
790
244
|
];
|
|
791
245
|
var OPAQUE = /[A-Za-z0-9_+=-]{32,}/g;
|
|
792
|
-
function redactSecrets(
|
|
793
|
-
let out =
|
|
246
|
+
function redactSecrets(text2) {
|
|
247
|
+
let out = text2;
|
|
794
248
|
for (const [pattern, replacement] of SECRETS) out = out.replace(pattern, replacement);
|
|
795
249
|
return out.replace(
|
|
796
250
|
OPAQUE,
|
|
797
|
-
(
|
|
251
|
+
(run) => /^[0-9a-f-]+$/i.test(run) || !/\d/.test(run) || !/[A-Za-z]/.test(run) ? run : "[redacted]"
|
|
798
252
|
);
|
|
799
253
|
}
|
|
800
|
-
function logText(
|
|
801
|
-
const flat = redactSecrets(stripControl(
|
|
254
|
+
function logText(text2) {
|
|
255
|
+
const flat = redactSecrets(stripControl(text2).replace(/\s+/g, " ").trim());
|
|
802
256
|
return flat.length > RUN_LOG_LINE_MAX ? `${flat.slice(0, RUN_LOG_LINE_MAX - 1)}\u2026` : flat;
|
|
803
257
|
}
|
|
804
258
|
function logLineFor(item) {
|
|
@@ -819,23 +273,23 @@ function logLineFor(item) {
|
|
|
819
273
|
return null;
|
|
820
274
|
}
|
|
821
275
|
}
|
|
822
|
-
function appendRunLog(dir, workId,
|
|
276
|
+
function appendRunLog(dir, workId, text2, { now = Date.now(), maxBytes = RUN_LOG_MAX_BYTES } = {}) {
|
|
823
277
|
const path = runLogPath(dir, workId);
|
|
824
278
|
if (!path) return;
|
|
825
|
-
const line = `${stamp(now)} ${logText(
|
|
279
|
+
const line = `${stamp(now)} ${logText(text2)}
|
|
826
280
|
`;
|
|
827
|
-
|
|
281
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
828
282
|
const size = sizeOf(path);
|
|
829
|
-
if (size > 0 && size + Buffer.byteLength(line) > maxBytes)
|
|
283
|
+
if (size > 0 && size + Buffer.byteLength(line) > maxBytes) renameSync(path, `${path}.1`);
|
|
830
284
|
appendFileSync(path, line, { mode: 384 });
|
|
831
285
|
}
|
|
832
286
|
function pruneRunLogs(dir, now = Date.now(), keepMs = RUN_LOG_KEEP_MS) {
|
|
833
|
-
|
|
834
|
-
|
|
287
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
288
|
+
chmodSync(dir, 448);
|
|
835
289
|
let removed = 0;
|
|
836
290
|
for (const name of readdirSync(dir)) {
|
|
837
291
|
if (!/\.log(\.1)?$/.test(name)) continue;
|
|
838
|
-
const path =
|
|
292
|
+
const path = join(dir, name);
|
|
839
293
|
try {
|
|
840
294
|
if (statSync(path).mtimeMs < now - keepMs) {
|
|
841
295
|
unlinkSync(path);
|
|
@@ -866,9 +320,9 @@ function stamp(now) {
|
|
|
866
320
|
}
|
|
867
321
|
|
|
868
322
|
// src/t3-bin.ts
|
|
869
|
-
import { execFile, execFileSync
|
|
323
|
+
import { execFile, execFileSync } from "child_process";
|
|
870
324
|
import { existsSync, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
|
|
871
|
-
import { join as
|
|
325
|
+
import { join as join2 } from "path";
|
|
872
326
|
var CLEAN_ENV = () => ({
|
|
873
327
|
HOME: process.env.HOME,
|
|
874
328
|
USER: process.env.USER,
|
|
@@ -878,7 +332,7 @@ function defaultT3BinSources(home, stored) {
|
|
|
878
332
|
return {
|
|
879
333
|
env: process.env,
|
|
880
334
|
home,
|
|
881
|
-
appDirs: process.platform === "darwin" ? ["/Applications",
|
|
335
|
+
appDirs: process.platform === "darwin" ? ["/Applications", join2(home, "Applications")] : [],
|
|
882
336
|
onPath: () => whichAll("t3"),
|
|
883
337
|
...stored ? { stored } : {}
|
|
884
338
|
};
|
|
@@ -899,9 +353,9 @@ function bundleBinaries(appDir) {
|
|
|
899
353
|
return [];
|
|
900
354
|
}
|
|
901
355
|
return bundles.flatMap((bundle) => {
|
|
902
|
-
const root =
|
|
356
|
+
const root = join2(appDir, bundle);
|
|
903
357
|
try {
|
|
904
|
-
return readdirSync2(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) =>
|
|
358
|
+
return readdirSync2(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) => join2(root, rel)).filter(isExecutable);
|
|
905
359
|
} catch {
|
|
906
360
|
return [];
|
|
907
361
|
}
|
|
@@ -910,8 +364,8 @@ function bundleBinaries(appDir) {
|
|
|
910
364
|
function t3Candidates(serverVersion, sources) {
|
|
911
365
|
const ordered = [
|
|
912
366
|
sources.env.T3_BIN,
|
|
913
|
-
|
|
914
|
-
|
|
367
|
+
join2(sources.home, ".t3", "runtime", "versions", serverVersion, "t3"),
|
|
368
|
+
join2(sources.env.T3CODE_HOME || join2(sources.home, ".t3"), "bin", "t3"),
|
|
915
369
|
...sources.appDirs.flatMap(bundleBinaries),
|
|
916
370
|
...sources.onPath(),
|
|
917
371
|
sources.stored
|
|
@@ -936,7 +390,7 @@ function t3BaseDirArgs(env = process.env) {
|
|
|
936
390
|
}
|
|
937
391
|
function runT3(bin, args, timeout = 15e3) {
|
|
938
392
|
try {
|
|
939
|
-
return
|
|
393
|
+
return execFileSync(bin, args, {
|
|
940
394
|
encoding: "utf-8",
|
|
941
395
|
env: CLEAN_ENV(),
|
|
942
396
|
timeout,
|
|
@@ -962,189 +416,21 @@ function t3Failed(args, err) {
|
|
|
962
416
|
}
|
|
963
417
|
function whichAll(bin) {
|
|
964
418
|
try {
|
|
965
|
-
return
|
|
419
|
+
return execFileSync("which", ["-a", bin], {
|
|
966
420
|
encoding: "utf-8",
|
|
967
421
|
env: CLEAN_ENV(),
|
|
968
|
-
stdio: ["ignore", "pipe", "ignore"]
|
|
969
|
-
}).split("\n").map((line) => line.trim()).filter(Boolean);
|
|
970
|
-
} catch {
|
|
971
|
-
return [];
|
|
972
|
-
}
|
|
973
|
-
}
|
|
974
|
-
|
|
975
|
-
// src/t3.ts
|
|
976
|
-
var T3_SCOPE = "orchestration:read orchestration:operate diagnostics:read";
|
|
977
|
-
var REQUIRED_SCOPES = ["orchestration:read", "orchestration:operate"];
|
|
978
|
-
var MIN_PROTOCOL = 2;
|
|
979
|
-
async function readEnvironment(t3Url, fetchFn = fetch) {
|
|
980
|
-
const res = await fetchFn(`${t3Url}/.well-known/t3/environment`);
|
|
981
|
-
if (!res.ok) throw new Error(`T3 environment ${res.status} at ${t3Url}`);
|
|
982
|
-
return await res.json();
|
|
983
|
-
}
|
|
984
|
-
async function exchangePairing(t3Url, credential, label, fetchFn = fetch) {
|
|
985
|
-
const form = new URLSearchParams({
|
|
986
|
-
grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
|
|
987
|
-
subject_token: credential,
|
|
988
|
-
subject_token_type: "urn:t3:params:oauth:token-type:environment-bootstrap",
|
|
989
|
-
requested_token_type: "urn:ietf:params:oauth:token-type:access_token",
|
|
990
|
-
scope: T3_SCOPE,
|
|
991
|
-
client_label: label,
|
|
992
|
-
client_device_type: "bot"
|
|
993
|
-
});
|
|
994
|
-
const res = await fetchFn(`${t3Url}/oauth/token`, { method: "POST", body: form });
|
|
995
|
-
if (!res.ok) throw new T3HttpError("token exchange", res.status);
|
|
996
|
-
const token = await res.json();
|
|
997
|
-
if (!REQUIRED_SCOPES.every((s) => hasScope(token.scope, s)) || scopes(token.scope).some((s) => !hasScope(T3_SCOPE, s)))
|
|
998
|
-
throw new Error(`T3 granted scope "${token.scope}", wanted "${T3_SCOPE}"`);
|
|
999
|
-
return token;
|
|
1000
|
-
}
|
|
1001
|
-
var scopes = (s) => s.split(/\s+/).filter(Boolean);
|
|
1002
|
-
var hasScope = (scope, name) => scopes(scope ?? "").includes(name);
|
|
1003
|
-
var T3HttpError = class extends Error {
|
|
1004
|
-
constructor(path, status) {
|
|
1005
|
-
super(`T3 ${path} ${status}`);
|
|
1006
|
-
this.status = status;
|
|
1007
|
-
this.name = "T3HttpError";
|
|
1008
|
-
}
|
|
1009
|
-
status;
|
|
1010
|
-
};
|
|
1011
|
-
var T3Client = class {
|
|
1012
|
-
constructor(t3Url, token, fetchFn = fetch) {
|
|
1013
|
-
this.t3Url = t3Url;
|
|
1014
|
-
this.token = token;
|
|
1015
|
-
this.fetchFn = fetchFn;
|
|
1016
|
-
}
|
|
1017
|
-
t3Url;
|
|
1018
|
-
token;
|
|
1019
|
-
fetchFn;
|
|
1020
|
-
async http(path, headers = {}) {
|
|
1021
|
-
const res = await this.fetchFn(`${this.t3Url}${path}`, {
|
|
1022
|
-
headers: { authorization: `Bearer ${this.token}`, ...headers }
|
|
1023
|
-
});
|
|
1024
|
-
if (!res.ok) throw new T3HttpError(path, res.status);
|
|
1025
|
-
return await res.json();
|
|
1026
|
-
}
|
|
1027
|
-
async openSocket() {
|
|
1028
|
-
const ticket = await this.fetchFn(`${this.t3Url}/api/auth/websocket-ticket`, {
|
|
1029
|
-
method: "POST",
|
|
1030
|
-
headers: { authorization: `Bearer ${this.token}` }
|
|
1031
|
-
});
|
|
1032
|
-
if (!ticket.ok) throw new T3HttpError("/api/auth/websocket-ticket", ticket.status);
|
|
1033
|
-
const { ticket: wsTicket } = await ticket.json();
|
|
1034
|
-
const { WebSocket } = await import("ws");
|
|
1035
|
-
const url = `${this.t3Url.replace(/^http/, "ws")}/ws?wsTicket=${encodeURIComponent(wsTicket)}&orchestrationProtocol=2&clientSurface=web&clientAppVersion=cloop-box`;
|
|
1036
|
-
return new WebSocket(url);
|
|
1037
|
-
}
|
|
1038
|
-
/** One request over a fresh /ws socket. The daemon makes a few calls a minute, so a socket per call is simpler than keeping one alive. */
|
|
1039
|
-
async rpc(tag, payload) {
|
|
1040
|
-
const ws = await this.openSocket();
|
|
1041
|
-
return new Promise((resolve, reject) => {
|
|
1042
|
-
let settled = false;
|
|
1043
|
-
const finish = (fn) => {
|
|
1044
|
-
if (settled) return;
|
|
1045
|
-
settled = true;
|
|
1046
|
-
clearTimeout(timer);
|
|
1047
|
-
fn();
|
|
1048
|
-
try {
|
|
1049
|
-
ws.close();
|
|
1050
|
-
} catch {
|
|
1051
|
-
}
|
|
1052
|
-
};
|
|
1053
|
-
const timer = setTimeout(
|
|
1054
|
-
() => finish(() => reject(new Error(`T3 rpc ${tag} timed out`))),
|
|
1055
|
-
15e3
|
|
1056
|
-
);
|
|
1057
|
-
ws.on(
|
|
1058
|
-
"error",
|
|
1059
|
-
(err) => finish(() => reject(err instanceof Error ? err : new Error(String(err))))
|
|
1060
|
-
);
|
|
1061
|
-
ws.on(
|
|
1062
|
-
"close",
|
|
1063
|
-
() => finish(() => reject(new Error(`T3 rpc ${tag}: socket closed before a reply`)))
|
|
1064
|
-
);
|
|
1065
|
-
ws.on("open", () => {
|
|
1066
|
-
ws.send(JSON.stringify({ _tag: "Request", id: 1, tag, payload, headers: [] }));
|
|
1067
|
-
});
|
|
1068
|
-
ws.on("message", (data) => {
|
|
1069
|
-
for (const msg of parseFrames(data)) {
|
|
1070
|
-
if (msg._tag !== "Exit" || String(msg.requestId) !== "1") continue;
|
|
1071
|
-
const exit = msg.exit;
|
|
1072
|
-
if (exit._tag === "Success") finish(() => resolve(exit.value));
|
|
1073
|
-
else {
|
|
1074
|
-
finish(
|
|
1075
|
-
() => reject(
|
|
1076
|
-
new Error(`T3 rpc ${tag} failed: ${JSON.stringify(exit.cause).slice(0, 300)}`)
|
|
1077
|
-
)
|
|
1078
|
-
);
|
|
1079
|
-
}
|
|
1080
|
-
}
|
|
1081
|
-
});
|
|
1082
|
-
});
|
|
1083
|
-
}
|
|
1084
|
-
/**
|
|
1085
|
-
* A streaming request, such as `orchestration.subscribeThread`, on its own
|
|
1086
|
-
* socket. Every item is acked, as Effect RPC requires. `done` resolves with
|
|
1087
|
-
* the reason the stream ended and never rejects; `close` interrupts it.
|
|
1088
|
-
*/
|
|
1089
|
-
async stream(tag, payload, onItem) {
|
|
1090
|
-
const ws = await this.openSocket();
|
|
1091
|
-
let resolveDone = () => {
|
|
1092
|
-
};
|
|
1093
|
-
const done = new Promise((r) => {
|
|
1094
|
-
resolveDone = r;
|
|
1095
|
-
});
|
|
1096
|
-
const end = (reason) => {
|
|
1097
|
-
resolveDone(reason);
|
|
1098
|
-
try {
|
|
1099
|
-
ws.close();
|
|
1100
|
-
} catch {
|
|
1101
|
-
}
|
|
1102
|
-
};
|
|
1103
|
-
ws.on("error", (err) => end(`error: ${err instanceof Error ? err.message : String(err)}`));
|
|
1104
|
-
ws.on("close", () => end("closed"));
|
|
1105
|
-
ws.on("open", () => {
|
|
1106
|
-
ws.send(JSON.stringify({ _tag: "Request", id: 1, tag, payload, headers: [] }));
|
|
1107
|
-
});
|
|
1108
|
-
ws.on("message", (data) => {
|
|
1109
|
-
for (const msg of parseFrames(data)) {
|
|
1110
|
-
if (String(msg.requestId) !== "1") continue;
|
|
1111
|
-
if (msg._tag === "Chunk") {
|
|
1112
|
-
ws.send(JSON.stringify({ _tag: "Ack", requestId: msg.requestId }));
|
|
1113
|
-
for (const value of msg.values) onItem(value);
|
|
1114
|
-
} else if (msg._tag === "Exit") {
|
|
1115
|
-
const exit = msg.exit;
|
|
1116
|
-
end(
|
|
1117
|
-
exit._tag === "Success" ? "exit" : `failed: ${JSON.stringify(exit.cause).slice(0, 300)}`
|
|
1118
|
-
);
|
|
1119
|
-
}
|
|
1120
|
-
}
|
|
1121
|
-
});
|
|
1122
|
-
return {
|
|
1123
|
-
done,
|
|
1124
|
-
close: () => {
|
|
1125
|
-
try {
|
|
1126
|
-
ws.send(JSON.stringify({ _tag: "Interrupt", requestId: "1" }));
|
|
1127
|
-
} catch {
|
|
1128
|
-
}
|
|
1129
|
-
end("closed by client");
|
|
1130
|
-
}
|
|
1131
|
-
};
|
|
1132
|
-
}
|
|
1133
|
-
};
|
|
1134
|
-
function parseFrames(data) {
|
|
1135
|
-
try {
|
|
1136
|
-
const raw = JSON.parse(String(data));
|
|
1137
|
-
return Array.isArray(raw) ? raw : [raw];
|
|
422
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
423
|
+
}).split("\n").map((line) => line.trim()).filter(Boolean);
|
|
1138
424
|
} catch {
|
|
1139
425
|
return [];
|
|
1140
426
|
}
|
|
1141
427
|
}
|
|
1142
428
|
|
|
1143
429
|
// src/drivers/t3.ts
|
|
1144
|
-
import { execFile as execFile2, execFileSync as
|
|
430
|
+
import { execFile as execFile2, execFileSync as execFileSync2 } from "child_process";
|
|
1145
431
|
import { randomUUID } from "crypto";
|
|
1146
432
|
import { existsSync as existsSync2 } from "fs";
|
|
1147
|
-
import { join as
|
|
433
|
+
import { join as join4 } from "path";
|
|
1148
434
|
|
|
1149
435
|
// ../clo0p-app/contracts/work-spec.ts
|
|
1150
436
|
var IMAGE_TYPES = {
|
|
@@ -1165,7 +451,7 @@ function repoName(repository) {
|
|
|
1165
451
|
|
|
1166
452
|
// src/drivers/attachments.ts
|
|
1167
453
|
import { mkdir, writeFile } from "fs/promises";
|
|
1168
|
-
import { join as
|
|
454
|
+
import { join as join3 } from "path";
|
|
1169
455
|
var FETCH_BUDGET_MS = 1e4;
|
|
1170
456
|
function parseAttachments(value) {
|
|
1171
457
|
if (!Array.isArray(value)) return void 0;
|
|
@@ -1224,7 +510,7 @@ async function saveImages(images, dir) {
|
|
|
1224
510
|
await mkdir(dir, { recursive: true, mode: 448 });
|
|
1225
511
|
return Promise.all(
|
|
1226
512
|
images.map(async (image) => {
|
|
1227
|
-
const path =
|
|
513
|
+
const path = join3(dir, image.name);
|
|
1228
514
|
await writeFile(path, image.data, { mode: 384 });
|
|
1229
515
|
return path;
|
|
1230
516
|
})
|
|
@@ -1255,10 +541,10 @@ var MISSING_DIAGNOSTICS = {
|
|
|
1255
541
|
};
|
|
1256
542
|
var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
1257
543
|
var count = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
|
|
1258
|
-
var
|
|
544
|
+
var text = (v) => typeof v === "string" && v.length > 0;
|
|
1259
545
|
var DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
1260
546
|
function safeMessage(v) {
|
|
1261
|
-
if (!
|
|
547
|
+
if (!text(v)) return void 0;
|
|
1262
548
|
return sanitizeLabel(v.replace(/(?:[A-Za-z]:)?[\\/][^\s'"]+/g, "<path>"), 200);
|
|
1263
549
|
}
|
|
1264
550
|
var KINDS = /* @__PURE__ */ new Set(["session", "weekly", "monthly", "other"]);
|
|
@@ -1274,7 +560,7 @@ function quotaWindow(id, kind, label, usedPercent, resetsAt, windowMinutes) {
|
|
|
1274
560
|
};
|
|
1275
561
|
}
|
|
1276
562
|
function isoTime(v) {
|
|
1277
|
-
const ms = typeof v === "number" && Number.isFinite(v) && v > 0 ? v < 1e12 ? v * 1e3 : v :
|
|
563
|
+
const ms = typeof v === "number" && Number.isFinite(v) && v > 0 ? v < 1e12 ? v * 1e3 : v : text(v) ? Date.parse(v) : Number.NaN;
|
|
1278
564
|
return Number.isFinite(ms) ? new Date(ms).toISOString() : null;
|
|
1279
565
|
}
|
|
1280
566
|
var KIND_LABEL = { session: "Session", weekly: "Weekly", monthly: "Monthly", other: "Limit" };
|
|
@@ -1289,7 +575,7 @@ var capped = (v) => typeof v === "number" ? Math.min(v, 100) : v;
|
|
|
1289
575
|
function quotaFromT3(raw) {
|
|
1290
576
|
if (raw === void 0 || raw === null) return { status: "not_reported" };
|
|
1291
577
|
if (!isObject(raw)) return { status: "malformed" };
|
|
1292
|
-
const checkedAt =
|
|
578
|
+
const checkedAt = text(raw.checkedAt) ? raw.checkedAt : null;
|
|
1293
579
|
if (raw.unavailable !== void 0) {
|
|
1294
580
|
const u = raw.unavailable;
|
|
1295
581
|
if (!isObject(u) || u.reason !== "unsupported" && u.reason !== "probeFailed")
|
|
@@ -1305,12 +591,12 @@ function quotaFromT3(raw) {
|
|
|
1305
591
|
return { status: "malformed" };
|
|
1306
592
|
const windows = [];
|
|
1307
593
|
for (const w of raw.windows) {
|
|
1308
|
-
const window = isObject(w) &&
|
|
594
|
+
const window = isObject(w) && text(w.id) && KINDS.has(w.kind) && text(w.label) ? quotaWindow(
|
|
1309
595
|
w.id,
|
|
1310
596
|
w.kind,
|
|
1311
597
|
w.label,
|
|
1312
598
|
w.usedPercent,
|
|
1313
|
-
|
|
599
|
+
text(w.resetsAt) ? w.resetsAt : null,
|
|
1314
600
|
w.windowDurationMins
|
|
1315
601
|
) : null;
|
|
1316
602
|
if (!window) return { status: "malformed" };
|
|
@@ -1324,7 +610,7 @@ function quotaFromT3(raw) {
|
|
|
1324
610
|
...isObject(credits) && count(credits.availableCount) ? {
|
|
1325
611
|
resetCredits: {
|
|
1326
612
|
available: credits.availableCount,
|
|
1327
|
-
nextExpiresAt:
|
|
613
|
+
nextExpiresAt: text(credits.nextExpiresAt) ? credits.nextExpiresAt : null
|
|
1328
614
|
}
|
|
1329
615
|
} : {}
|
|
1330
616
|
};
|
|
@@ -1346,8 +632,8 @@ function quotaFromCodex(answer, checkedAt) {
|
|
|
1346
632
|
const windows = [];
|
|
1347
633
|
for (const limit of limits) {
|
|
1348
634
|
if (!isObject(limit)) return { status: "malformed" };
|
|
1349
|
-
const id =
|
|
1350
|
-
const name =
|
|
635
|
+
const id = text(limit.limitId) ? limit.limitId : "codex";
|
|
636
|
+
const name = text(limit.limitName) ? limit.limitName : id;
|
|
1351
637
|
for (const slot of ["primary", "secondary"]) {
|
|
1352
638
|
const w = limit[slot];
|
|
1353
639
|
if (w === null || w === void 0) continue;
|
|
@@ -1410,7 +696,7 @@ function quotaFromClaude(response, checkedAt) {
|
|
|
1410
696
|
for (const l of Array.isArray(limits.limits) ? limits.limits : []) {
|
|
1411
697
|
const scope = isObject(l) && isObject(l.scope) ? l.scope : null;
|
|
1412
698
|
const model = isObject(scope?.model) ? scope.model.display_name : void 0;
|
|
1413
|
-
if (!isObject(l) || !
|
|
699
|
+
if (!isObject(l) || !text(model)) continue;
|
|
1414
700
|
const kind = l.group === "session" || l.group === "weekly" ? l.group : "other";
|
|
1415
701
|
const window = quotaWindow(
|
|
1416
702
|
`${kind}_${model.toLowerCase().replace(/[^a-z0-9]+/g, "_")}`,
|
|
@@ -1500,7 +786,7 @@ function tokenUsageFromSummary(raw, window) {
|
|
|
1500
786
|
let malformed = 0;
|
|
1501
787
|
for (const b of raw.buckets) {
|
|
1502
788
|
const t = isObject(b) ? b.totals : void 0;
|
|
1503
|
-
if (!isObject(b) || !isObject(t) || !
|
|
789
|
+
if (!isObject(b) || !isObject(t) || !text(b.day) || !DAY.test(b.day) || !text(b.provider) || !count(b.records) || !count(t.uncachedInputTokens) || !count(t.cachedInputTokens) || !count(t.cacheCreationTokens) || !count(t.outputTokens) || !count(t.reasoningTokens)) {
|
|
1504
790
|
malformed++;
|
|
1505
791
|
continue;
|
|
1506
792
|
}
|
|
@@ -1516,7 +802,7 @@ function tokenUsageFromSummary(raw, window) {
|
|
|
1516
802
|
const sources = [];
|
|
1517
803
|
for (const s of raw.sources) {
|
|
1518
804
|
const f = isObject(s) ? s.fingerprint : void 0;
|
|
1519
|
-
if (!isObject(s) || !isObject(f) || !
|
|
805
|
+
if (!isObject(s) || !isObject(f) || !text(f.provider) || !SOURCE_STATUS.has(s.status)) {
|
|
1520
806
|
malformed++;
|
|
1521
807
|
continue;
|
|
1522
808
|
}
|
|
@@ -1536,7 +822,7 @@ function tokenUsageFromSummary(raw, window) {
|
|
|
1536
822
|
status: partial ? "partial" : "ok",
|
|
1537
823
|
scope: TOKEN_SCOPE,
|
|
1538
824
|
window: { since_day: window.sinceDay, until_day: window.untilDay, time_zone: "UTC" },
|
|
1539
|
-
read_at:
|
|
825
|
+
read_at: text(raw.readAt) ? raw.readAt : null,
|
|
1540
826
|
by_day: sortedDays(days),
|
|
1541
827
|
sources,
|
|
1542
828
|
...malformed ? { malformed_rows: malformed } : {}
|
|
@@ -1595,8 +881,8 @@ function pendingQuestions(p) {
|
|
|
1595
881
|
return [];
|
|
1596
882
|
});
|
|
1597
883
|
}
|
|
1598
|
-
var oneLine = (
|
|
1599
|
-
const flat =
|
|
884
|
+
var oneLine = (text2, max) => {
|
|
885
|
+
const flat = text2.replace(/[\r\n\t]+/g, " ");
|
|
1600
886
|
return flat.length > max ? `${flat.slice(0, max - 1)}\u2026` : flat;
|
|
1601
887
|
};
|
|
1602
888
|
function questionText(q) {
|
|
@@ -1615,40 +901,40 @@ function latestRun(runs) {
|
|
|
1615
901
|
);
|
|
1616
902
|
}
|
|
1617
903
|
function isTerminal(runs) {
|
|
1618
|
-
const
|
|
1619
|
-
return Boolean(
|
|
904
|
+
const run = latestRun(runs);
|
|
905
|
+
return Boolean(run && TERMINAL_RUN.has(run.status));
|
|
1620
906
|
}
|
|
1621
907
|
function activeRun(runs) {
|
|
1622
|
-
const
|
|
1623
|
-
return
|
|
908
|
+
const run = latestRun(runs);
|
|
909
|
+
return run && !TERMINAL_RUN.has(run.status) ? run : null;
|
|
1624
910
|
}
|
|
1625
911
|
function steerableRun(p) {
|
|
1626
|
-
const
|
|
1627
|
-
if (!
|
|
1628
|
-
const attempts = new Set((p.attempts ?? []).filter((a) => a.runId ===
|
|
912
|
+
const run = activeRun(p.runs ?? []);
|
|
913
|
+
if (!run) return null;
|
|
914
|
+
const attempts = new Set((p.attempts ?? []).filter((a) => a.runId === run.id).map((a) => a.id));
|
|
1629
915
|
const turning = (p.providerTurns ?? []).some(
|
|
1630
916
|
(t) => t.status === "running" && t.runAttemptId !== null && attempts.has(t.runAttemptId)
|
|
1631
917
|
);
|
|
1632
|
-
return turning ?
|
|
918
|
+
return turning ? run : null;
|
|
1633
919
|
}
|
|
1634
920
|
var STEER_WAIT_MS = 8e3;
|
|
1635
921
|
var STEER_POLL_MS = 500;
|
|
1636
922
|
var ASKS_READ_MAX = 8;
|
|
1637
923
|
var START_WAIT_MS = 5e3;
|
|
1638
924
|
function outcomeOf(p) {
|
|
1639
|
-
const
|
|
1640
|
-
const status =
|
|
925
|
+
const run = latestRun(p.runs ?? []);
|
|
926
|
+
const status = run?.status ?? "pending";
|
|
1641
927
|
const settled = TERMINAL_RUN.has(status) || Boolean(p.thread.settledAt);
|
|
1642
928
|
const said = (p.messages ?? []).filter((m) => m.role === "assistant" && m.text);
|
|
1643
|
-
const
|
|
1644
|
-
const block = said.filter((m) => (!
|
|
1645
|
-
const { result, dropped } = readRunResult(resultText(
|
|
929
|
+
const text2 = said.at(-1)?.text?.trim();
|
|
930
|
+
const block = said.filter((m) => (!run || m.runId === run.id) && hasResultBlock(m.text)).at(-1)?.text?.trim();
|
|
931
|
+
const { result, dropped } = readRunResult(resultText(text2, block));
|
|
1646
932
|
return {
|
|
1647
933
|
status,
|
|
1648
934
|
settled,
|
|
1649
|
-
kind: settled ? status === "completed" || !
|
|
1650
|
-
pr_url: resultPrUrl(
|
|
1651
|
-
last_assistant_text:
|
|
935
|
+
kind: settled ? status === "completed" || !run ? "settled" : "failed" : null,
|
|
936
|
+
pr_url: resultPrUrl(text2),
|
|
937
|
+
last_assistant_text: text2 ? text2.slice(0, RUN_TEXT_MAX) : null,
|
|
1652
938
|
...result ? { result } : {},
|
|
1653
939
|
...dropped.outputs || dropped.checks ? { dropped } : {}
|
|
1654
940
|
};
|
|
@@ -1685,11 +971,11 @@ function otherDriver(cfg, instanceId) {
|
|
|
1685
971
|
const driver = p?.driver ?? p?.instanceId ?? instanceId;
|
|
1686
972
|
return driver === CODEX_PROVIDER ? CLAUDE_PROVIDER : driver === CLAUDE_PROVIDER ? CODEX_PROVIDER : null;
|
|
1687
973
|
}
|
|
1688
|
-
function signedOutWords(p,
|
|
1689
|
-
if (
|
|
1690
|
-
const said = (p.messages ?? []).filter((m) => m.role === "assistant" && m.runId ===
|
|
974
|
+
function signedOutWords(p, run) {
|
|
975
|
+
if (run.status !== "failed") return null;
|
|
976
|
+
const said = (p.messages ?? []).filter((m) => m.role === "assistant" && m.runId === run.id && m.text?.trim()).at(-1)?.text?.trim();
|
|
1691
977
|
const words = said && HARNESS_SIGNED_OUT.test(said) ? said : null;
|
|
1692
|
-
const failure = (p.turnItems ?? []).filter((i) => i.type === "error" && i.runId ===
|
|
978
|
+
const failure = (p.turnItems ?? []).filter((i) => i.type === "error" && i.runId === run.id).at(-1)?.failure;
|
|
1693
979
|
if (!failure) return words;
|
|
1694
980
|
if (failure.class && failure.class !== "provider_error") return null;
|
|
1695
981
|
const message = failure.message?.trim() ?? "";
|
|
@@ -1756,7 +1042,7 @@ function projectNames(p) {
|
|
|
1756
1042
|
return [...new Set(names.filter((name) => Boolean(name)))];
|
|
1757
1043
|
}
|
|
1758
1044
|
function isRepository(p) {
|
|
1759
|
-
return Boolean(p.repositoryIdentity) || existsSync2(
|
|
1045
|
+
return Boolean(p.repositoryIdentity) || existsSync2(join4(p.workspaceRoot, ".git"));
|
|
1760
1046
|
}
|
|
1761
1047
|
function holdsRepository(p, repository) {
|
|
1762
1048
|
return projectNames(p).some((name) => repoName(name) === repoName(repository));
|
|
@@ -2213,8 +1499,8 @@ var T3Driver = class {
|
|
|
2213
1499
|
* was on its way: T3 refuses that interrupt, and the owner's ask is met.
|
|
2214
1500
|
*/
|
|
2215
1501
|
async interrupt(threadId, commandId) {
|
|
2216
|
-
const
|
|
2217
|
-
if (!
|
|
1502
|
+
const run = activeRun((await this.readProjection(threadId)).runs ?? []);
|
|
1503
|
+
if (!run) {
|
|
2218
1504
|
const end = this.held.get(threadId);
|
|
2219
1505
|
end?.();
|
|
2220
1506
|
return { ok: true, was_running: Boolean(end) };
|
|
@@ -2224,7 +1510,7 @@ var T3Driver = class {
|
|
|
2224
1510
|
type: "run.interrupt",
|
|
2225
1511
|
commandId,
|
|
2226
1512
|
threadId,
|
|
2227
|
-
runId:
|
|
1513
|
+
runId: run.id,
|
|
2228
1514
|
reason: "Stopped from Cloop"
|
|
2229
1515
|
});
|
|
2230
1516
|
} catch (err) {
|
|
@@ -2307,7 +1593,7 @@ var T3Driver = class {
|
|
|
2307
1593
|
try {
|
|
2308
1594
|
value = tailscaleServed(
|
|
2309
1595
|
String(
|
|
2310
|
-
(this.deps.exec ??
|
|
1596
|
+
(this.deps.exec ?? execFileSync2)("tailscale", ["serve", "status", "--json"], {
|
|
2311
1597
|
encoding: "utf-8",
|
|
2312
1598
|
stdio: ["ignore", "pipe", "ignore"],
|
|
2313
1599
|
timeout: 3e3
|
|
@@ -2346,8 +1632,8 @@ var T3Driver = class {
|
|
|
2346
1632
|
const speak = (runs, messages) => {
|
|
2347
1633
|
const latest = [...messages.values()].filter((m) => m.role === "assistant" && m.text?.trim()).at(-1);
|
|
2348
1634
|
if (!latest?.text || latest.streaming || latest.text === spoken) return;
|
|
2349
|
-
const
|
|
2350
|
-
if (
|
|
1635
|
+
const run = latest.runId ? runs.get(latest.runId) : void 0;
|
|
1636
|
+
if (run && TERMINAL_RUN.has(run.status)) return;
|
|
2351
1637
|
spoken = latest.text;
|
|
2352
1638
|
const now = this.deps.now?.() ?? Date.now();
|
|
2353
1639
|
const summary = nextProgress(clock, latest.text, now, this.deps.progressMs);
|
|
@@ -2687,7 +1973,7 @@ ${MACHINE_RESULT_INSTRUCTION}`
|
|
|
2687
1973
|
*/
|
|
2688
1974
|
baseRefFor(root) {
|
|
2689
1975
|
const git = (args) => String(
|
|
2690
|
-
(this.deps.exec ??
|
|
1976
|
+
(this.deps.exec ?? execFileSync2)("git", ["-C", root, ...args], {
|
|
2691
1977
|
encoding: "utf-8",
|
|
2692
1978
|
env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
|
|
2693
1979
|
timeout: 5e3
|
|
@@ -2709,13 +1995,6 @@ ${MACHINE_RESULT_INSTRUCTION}`
|
|
|
2709
1995
|
}
|
|
2710
1996
|
};
|
|
2711
1997
|
|
|
2712
|
-
// src/drivers/local.ts
|
|
2713
|
-
import { execFile as execFile3, execFileSync as execFileSync4, spawn } from "child_process";
|
|
2714
|
-
import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync2, readdirSync as readdirSync3, renameSync as renameSync3, rmSync, writeFileSync as writeFileSync2 } from "fs";
|
|
2715
|
-
import { hostname } from "os";
|
|
2716
|
-
import { basename, dirname as dirname4, join as join8 } from "path";
|
|
2717
|
-
import { createInterface as createInterface2 } from "readline";
|
|
2718
|
-
|
|
2719
1998
|
// src/drivers/harness-check.ts
|
|
2720
1999
|
var HARNESS_STALE_MS = 5 * 6e4;
|
|
2721
2000
|
var FIRST_CHECK_WAIT_MS = 3e3;
|
|
@@ -2758,1004 +2037,21 @@ var HarnessCheck = class {
|
|
|
2758
2037
|
}
|
|
2759
2038
|
};
|
|
2760
2039
|
|
|
2761
|
-
// src/drivers/local.ts
|
|
2762
|
-
var STOPPED = { kind: "failed", summary: STOPPED_SUMMARY };
|
|
2763
|
-
function takeoverSummary(machine) {
|
|
2764
|
-
return `You took this over on ${machine}.`;
|
|
2765
|
-
}
|
|
2766
|
-
var ADOPT_QUIET_MS = 2 * 6e4;
|
|
2767
|
-
var CONTINUE_PROMPT = "Continue the work from where you stopped. If it is already done, say so in one sentence.";
|
|
2768
|
-
var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master", "HEAD"]);
|
|
2769
|
-
var COMMANDS_KEPT = 50;
|
|
2770
|
-
var SUMMARY_MAX2 = 200;
|
|
2771
|
-
var HARNESS_NAMES = { "claude-code": "Claude Code", codex: "Codex" };
|
|
2772
|
-
var harnessName = (name) => HARNESS_NAMES[name] ?? name;
|
|
2773
|
-
function runHarness(run2, own) {
|
|
2774
|
-
const driver = own?.driver === "codex" ? "codex" : "claude-code";
|
|
2775
|
-
const harness = run2.harness ?? driver;
|
|
2776
|
-
const bin = harness === driver && own?.bin ? own.bin : harness === "codex" ? "codex" : "claude";
|
|
2777
|
-
return { harness, bin };
|
|
2778
|
-
}
|
|
2779
|
-
var switchedLine = (move, from, to) => movedLine(move.reason, harnessName(from), harnessName(to), move.at === "run" ? "was" : "is");
|
|
2780
|
-
function failedEnd(harness, run2) {
|
|
2781
|
-
const said = run2.result?.text?.trim() || run2.lastText;
|
|
2782
|
-
const limited = HARNESS_LIMIT.test(run2.result?.text ?? "");
|
|
2783
|
-
const words = said && apiErrorWords(said.trim()).replace(/\s+/g, " ").trim();
|
|
2784
|
-
const error = limited ? { error: "harness_limit" } : {};
|
|
2785
|
-
const opening = run2.switched ? `${run2.switched} ` : "";
|
|
2786
|
-
if (!words)
|
|
2787
|
-
return {
|
|
2788
|
-
summary: `${opening}${run2.result ? "The run ended with an error." : `The run exited with ${run2.exit}.`}`,
|
|
2789
|
-
...error
|
|
2790
|
-
};
|
|
2791
|
-
const lead = `${opening}${harnessName(harness)} said: "`;
|
|
2792
|
-
const room = SUMMARY_MAX2 - lead.length - 1;
|
|
2793
|
-
const quoted = words.length > room ? `${words.slice(0, room - 1)}\u2026` : words;
|
|
2794
|
-
return { summary: `${lead}${quoted}"`, ...error };
|
|
2795
|
-
}
|
|
2796
|
-
function localRunsFilePath(env) {
|
|
2797
|
-
return runnerPath(env, process.env.CLOOP_LOCAL_RUNS_FILE, (dir) => join8(dir, "local-runs.json"));
|
|
2798
|
-
}
|
|
2799
|
-
function holdsRepository2(r, repository) {
|
|
2800
|
-
const want = repoName(repository);
|
|
2801
|
-
return repoName(r.label) === want || repoName(basename(r.path)) === want;
|
|
2802
|
-
}
|
|
2803
|
-
function apartLine(busy) {
|
|
2804
|
-
return `Another run is working in ${busy.label} (${busy.path}), so this run has a folder of its own. If this work needs that project's code, do not edit ${busy.path}: make a git worktree of it in this folder and work there. If you open a pull request, put its URL in your result.`;
|
|
2805
|
-
}
|
|
2806
|
-
function pruneApartFolders(dir, kept, repos) {
|
|
2807
|
-
let names;
|
|
2808
|
-
try {
|
|
2809
|
-
names = readdirSync3(dir);
|
|
2810
|
-
} catch {
|
|
2811
|
-
return 0;
|
|
2812
|
-
}
|
|
2813
|
-
const gone = names.filter((name) => !kept.has(name));
|
|
2814
|
-
for (const name of gone) rmSync(join8(dir, name), { recursive: true, force: true });
|
|
2815
|
-
if (gone.length)
|
|
2816
|
-
for (const repo of repos) {
|
|
2817
|
-
try {
|
|
2818
|
-
execFileSync4("git", ["worktree", "prune"], { cwd: repo.path, stdio: "ignore", timeout: 1e4 });
|
|
2819
|
-
} catch {
|
|
2820
|
-
}
|
|
2821
|
-
}
|
|
2822
|
-
return gone.length;
|
|
2823
|
-
}
|
|
2824
|
-
function pickRepo(repos, repository) {
|
|
2825
|
-
const picked = repository && repos.find((r) => holdsRepository2(r, repository)) || repos[0];
|
|
2826
|
-
if (!picked) throw new BoxToolError("no_project");
|
|
2827
|
-
return picked;
|
|
2828
|
-
}
|
|
2829
|
-
function withFolder(r, end) {
|
|
2830
|
-
return end.kind === "settled" ? { ...end, cwd: r.repo } : end;
|
|
2831
|
-
}
|
|
2832
|
-
function run(cmd, args, cwd) {
|
|
2833
|
-
return new Promise(
|
|
2834
|
-
(resolve, reject) => execFile3(
|
|
2835
|
-
cmd,
|
|
2836
|
-
args,
|
|
2837
|
-
{ cwd, timeout: 1e4, encoding: "utf-8" },
|
|
2838
|
-
(err, out) => err ? reject(err) : resolve(String(out).trim())
|
|
2839
|
-
)
|
|
2840
|
-
);
|
|
2841
|
-
}
|
|
2842
|
-
var gitProbe = {
|
|
2843
|
-
head: (repo) => run("git", ["rev-parse", "HEAD"], repo).catch(() => null),
|
|
2844
|
-
pushed: (repo) => run("git", ["branch", "-r", "--contains", "HEAD"], repo).then(
|
|
2845
|
-
(out) => out.length > 0,
|
|
2846
|
-
() => false
|
|
2847
|
-
),
|
|
2848
|
-
async branchPr(repo) {
|
|
2849
|
-
try {
|
|
2850
|
-
const branch = await run("git", ["rev-parse", "--abbrev-ref", "HEAD"], repo);
|
|
2851
|
-
if (SHARED_BRANCHES.has(branch)) return null;
|
|
2852
|
-
return prUrlIn(await run("gh", ["pr", "view", "--json", "url", "-q", ".url"], repo));
|
|
2853
|
-
} catch {
|
|
2854
|
-
return null;
|
|
2855
|
-
}
|
|
2856
|
-
}
|
|
2857
|
-
};
|
|
2858
|
-
function processCommandLine(pid, platform = process.platform) {
|
|
2859
|
-
if (platform === "win32")
|
|
2860
|
-
return [
|
|
2861
|
-
"powershell",
|
|
2862
|
-
"-NoProfile",
|
|
2863
|
-
"-NonInteractive",
|
|
2864
|
-
"-Command",
|
|
2865
|
-
`(Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}').CommandLine`
|
|
2866
|
-
];
|
|
2867
|
-
return ["ps", "-ww", "-o", "command=", "-p", String(pid)];
|
|
2868
|
-
}
|
|
2869
|
-
function harnessAlive(pid, r, dialect) {
|
|
2870
|
-
try {
|
|
2871
|
-
process.kill(pid, 0);
|
|
2872
|
-
} catch (err) {
|
|
2873
|
-
if (err.code !== "EPERM") return false;
|
|
2874
|
-
}
|
|
2875
|
-
try {
|
|
2876
|
-
const [file, ...args] = processCommandLine(pid);
|
|
2877
|
-
const command = execFileSync4(file, args, {
|
|
2878
|
-
encoding: "utf-8",
|
|
2879
|
-
timeout: 2e3,
|
|
2880
|
-
...file === "powershell" ? { env: windowsPowerShellEnv() } : {}
|
|
2881
|
-
});
|
|
2882
|
-
return dialect.owns(r, command);
|
|
2883
|
-
} catch {
|
|
2884
|
-
return false;
|
|
2885
|
-
}
|
|
2886
|
-
}
|
|
2887
|
-
var KEEP_MS = 7 * 24 * 36e5;
|
|
2888
|
-
var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2889
|
-
var LocalDriver = class {
|
|
2890
|
-
constructor(deps) {
|
|
2891
|
-
this.deps = deps;
|
|
2892
|
-
this.name = deps.dialect.name;
|
|
2893
|
-
this.harnessCheck = new HarnessCheck(
|
|
2894
|
-
deps.harnesses ?? (async () => [await deps.dialect.probe()].filter((h) => h !== null)),
|
|
2895
|
-
{ now: () => this.now(), log: (line) => this.log(line) }
|
|
2896
|
-
);
|
|
2897
|
-
this.capabilities = deps.dialect.capabilities;
|
|
2898
|
-
this.runs = new Map(this.load().map((r) => [r.work_id, r]));
|
|
2899
|
-
this.logDir = deps.logDir ?? runLogDir(this.file);
|
|
2900
|
-
try {
|
|
2901
|
-
const removed = pruneRunLogs(this.logDir, this.now());
|
|
2902
|
-
if (removed) this.log(`run logs removed=${removed} older than 14 days`);
|
|
2903
|
-
} catch (err) {
|
|
2904
|
-
this.log(`run log prune failed: ${err.code ?? "unknown"}`);
|
|
2905
|
-
}
|
|
2906
|
-
try {
|
|
2907
|
-
const removed = pruneApartFolders(join8(dirname4(this.file), "work"), new Set(this.runs.keys()), deps.repos);
|
|
2908
|
-
if (removed) this.log(`run folders removed=${removed} of runs no longer kept`);
|
|
2909
|
-
} catch (err) {
|
|
2910
|
-
this.log(`run folder prune failed: ${err.code ?? "unknown"}`);
|
|
2911
|
-
}
|
|
2912
|
-
}
|
|
2913
|
-
deps;
|
|
2914
|
-
name;
|
|
2915
|
-
capabilities;
|
|
2916
|
-
runs;
|
|
2917
|
-
lives = /* @__PURE__ */ new Map();
|
|
2918
|
-
listeners = /* @__PURE__ */ new Map();
|
|
2919
|
-
recovering = /* @__PURE__ */ new Set();
|
|
2920
|
-
stopping = false;
|
|
2921
|
-
logDir;
|
|
2922
|
-
logFailed = false;
|
|
2923
|
-
harnessCheck;
|
|
2924
|
-
/** Until then, the runner's own harness is at an account-wide limit and new runs start on the fallback. */
|
|
2925
|
-
limitedUntil = 0;
|
|
2926
|
-
get repo() {
|
|
2927
|
-
return this.deps.repo ?? gitProbe;
|
|
2928
|
-
}
|
|
2929
|
-
get file() {
|
|
2930
|
-
return this.deps.file ?? localRunsFilePath();
|
|
2931
|
-
}
|
|
2932
|
-
log(line) {
|
|
2933
|
-
this.deps.log?.(line);
|
|
2934
|
-
}
|
|
2935
|
-
/** One line in the run's own log, for `cloop watch`. A full disk must not stop the run. */
|
|
2936
|
-
note(r, text3) {
|
|
2937
|
-
try {
|
|
2938
|
-
appendRunLog(this.logDir, r.work_id, text3, { now: this.now() });
|
|
2939
|
-
} catch (err) {
|
|
2940
|
-
if (this.logFailed) return;
|
|
2941
|
-
this.logFailed = true;
|
|
2942
|
-
this.log(`run log write failed: ${err.code ?? "unknown"}`);
|
|
2943
|
-
}
|
|
2944
|
-
}
|
|
2945
|
-
now() {
|
|
2946
|
-
return this.deps.now?.() ?? Date.now();
|
|
2947
|
-
}
|
|
2948
|
-
/** Probes the harnesses now, so the first status after the daemon starts answers at once. */
|
|
2949
|
-
warmHarnesses() {
|
|
2950
|
-
void this.harnessCheck.refresh().then(() => this.status()).catch((err) => this.log(`usage warm failed: ${err?.message}`));
|
|
2951
|
-
}
|
|
2952
|
-
/** Its repository folders, by label and folder name, the names `pickRepo` matches. */
|
|
2953
|
-
async checkouts() {
|
|
2954
|
-
return [...new Set(this.deps.repos.flatMap((r) => [r.label, basename(r.path)]))];
|
|
2955
|
-
}
|
|
2956
|
-
async status() {
|
|
2957
|
-
const { harnesses, checkedAt, probing } = await this.harnessCheck.read();
|
|
2958
|
-
const all = [...this.runs.values()];
|
|
2959
|
-
const unsettled = all.filter((r) => !r.end);
|
|
2960
|
-
const usage = this.deps.usage;
|
|
2961
|
-
return {
|
|
2962
|
-
box: { label: this.deps.label ?? hostname(), driver: this.name },
|
|
2963
|
-
harnesses: usage ? usage.withQuota(harnesses) : harnesses,
|
|
2964
|
-
harnesses_checked_at: checkedAt,
|
|
2965
|
-
...probing ? { probing: true } : {},
|
|
2966
|
-
clients: null,
|
|
2967
|
-
projects: this.deps.repos.map((r) => r.label),
|
|
2968
|
-
threads: {
|
|
2969
|
-
unsettled: unsettled.length,
|
|
2970
|
-
running: unsettled.filter((r) => this.lives.has(r.work_id)).length,
|
|
2971
|
-
settled: all.length - unsettled.length,
|
|
2972
|
-
cloop: unsettled.length
|
|
2973
|
-
},
|
|
2974
|
-
...usage ? { token_usage: usage.tokenUsage() } : {}
|
|
2975
|
-
};
|
|
2976
|
-
}
|
|
2977
|
-
async listThreads({
|
|
2978
|
-
scope,
|
|
2979
|
-
limit
|
|
2980
|
-
}) {
|
|
2981
|
-
const all = [...this.runs.values()];
|
|
2982
|
-
const unsettled = all.filter((r) => !r.end);
|
|
2983
|
-
const shown = (scope === "all" ? all : unsettled).map((r) => {
|
|
2984
|
-
const asks = this.lives.get(r.work_id)?.asks ?? [];
|
|
2985
|
-
return {
|
|
2986
|
-
id: r.work_id,
|
|
2987
|
-
title: r.title,
|
|
2988
|
-
status: this.statusOf(r),
|
|
2989
|
-
branch: null,
|
|
2990
|
-
source: r.adopted ? this.dialectOf(r).name : "cloop",
|
|
2991
|
-
cloop: !r.adopted,
|
|
2992
|
-
settled: Boolean(r.end),
|
|
2993
|
-
updatedAt: r.end?.at ?? r.started_at,
|
|
2994
|
-
...asks.length ? { asks: asks.map((a) => ({ question_id: a.request_id, question: a.summary })) } : {}
|
|
2995
|
-
};
|
|
2996
|
-
});
|
|
2997
|
-
const running = shown.filter((t) => t.status === "running").length;
|
|
2998
|
-
return {
|
|
2999
|
-
scope,
|
|
3000
|
-
unsettled: unsettled.length,
|
|
3001
|
-
settled: all.length - unsettled.length,
|
|
3002
|
-
running,
|
|
3003
|
-
// The daemon owns every run's harness process here, the owner's adopted sessions too.
|
|
3004
|
-
cloopRunning: running,
|
|
3005
|
-
threads: orderThreads([...shown, ...await this.ownSessions()], limit)
|
|
3006
|
-
};
|
|
3007
|
-
}
|
|
3008
|
-
/**
|
|
3009
|
-
* The owner's own Claude Code and Codex sessions on this machine, the ones
|
|
3010
|
-
* Cloop did not start, so a thread id from this list can be steered. Each
|
|
3011
|
-
* is idle: a send resumes it.
|
|
3012
|
-
*/
|
|
3013
|
-
async ownSessions() {
|
|
3014
|
-
const known = new Set(
|
|
3015
|
-
[...this.runs.values()].flatMap((r) => [r.work_id, ...r.session_id ? [r.session_id] : []])
|
|
3016
|
-
);
|
|
3017
|
-
const roots = this.deps.sessions ?? sessionRoots();
|
|
3018
|
-
const harnesses = this.sessionHarnesses();
|
|
3019
|
-
const [claude, codex] = await Promise.all([
|
|
3020
|
-
harnesses.includes("claude-code") ? listOutsideSessions(roots.claude, known) : [],
|
|
3021
|
-
harnesses.includes("codex") ? listCodexSessions(roots.codex, known) : []
|
|
3022
|
-
]);
|
|
3023
|
-
const view = (source) => (t) => ({
|
|
3024
|
-
id: t.id,
|
|
3025
|
-
title: t.title ?? t.project ?? "Untitled session",
|
|
3026
|
-
status: t.status,
|
|
3027
|
-
branch: null,
|
|
3028
|
-
source,
|
|
3029
|
-
cloop: false,
|
|
3030
|
-
settled: false,
|
|
3031
|
-
updatedAt: t.updatedAt
|
|
3032
|
-
});
|
|
3033
|
-
return [...claude.map(view("claude-code")), ...codex.map(view("codex"))];
|
|
3034
|
-
}
|
|
3035
|
-
sessionHarnesses() {
|
|
3036
|
-
return [this.deps.dialect, this.deps.fallbackHarness].flatMap(
|
|
3037
|
-
(d) => d && (d.name === "claude-code" || d.name === "codex") ? [d.name] : []
|
|
3038
|
-
);
|
|
3039
|
-
}
|
|
3040
|
-
/**
|
|
3041
|
-
* A session the owner started outside Cloop, as a run, the first time Cloop
|
|
3042
|
-
* sends it something. It keeps its own harness and folder, and a send
|
|
3043
|
-
* resumes it there. Not registered here: the send that takes it does that.
|
|
3044
|
-
*/
|
|
3045
|
-
async adopt(id) {
|
|
3046
|
-
const found = await findSession(
|
|
3047
|
-
id,
|
|
3048
|
-
this.deps.sessions ?? sessionRoots(),
|
|
3049
|
-
this.sessionHarnesses()
|
|
3050
|
-
);
|
|
3051
|
-
if (!found) throw new BoxToolError("bad_args");
|
|
3052
|
-
if (!found.cwd) throw new BoxToolError("no_project");
|
|
3053
|
-
const age = this.now() - found.mtime;
|
|
3054
|
-
if (age < ADOPT_QUIET_MS) {
|
|
3055
|
-
this.log(`adopt refused work=${id} reason=thread_busy age_ms=${Math.round(age)}`);
|
|
3056
|
-
throw new BoxToolError("thread_busy");
|
|
3057
|
-
}
|
|
3058
|
-
this.refuseBusy(found.cwd);
|
|
3059
|
-
const head = await this.repo.head(found.cwd).catch(() => null);
|
|
3060
|
-
const raced = this.runs.get(id);
|
|
3061
|
-
if (raced) return raced;
|
|
3062
|
-
this.log(`adopt work=${id} harness=${found.harness}`);
|
|
3063
|
-
return {
|
|
3064
|
-
work_id: id,
|
|
3065
|
-
session_id: id,
|
|
3066
|
-
repo: found.cwd,
|
|
3067
|
-
title: found.title ?? "Your session",
|
|
3068
|
-
// A move to the other harness would leave the owner's session behind.
|
|
3069
|
-
harness_named: true,
|
|
3070
|
-
...found.harness !== this.deps.dialect.name ? { harness: found.harness } : {},
|
|
3071
|
-
adopted: true,
|
|
3072
|
-
pid: null,
|
|
3073
|
-
started_at: new Date(this.now()).toISOString(),
|
|
3074
|
-
head_at_launch: head
|
|
3075
|
-
};
|
|
3076
|
-
}
|
|
3077
|
-
async readThread(id) {
|
|
3078
|
-
const r = this.record(id);
|
|
3079
|
-
return {
|
|
3080
|
-
status: this.statusOf(r),
|
|
3081
|
-
settled: Boolean(r.end),
|
|
3082
|
-
pr_url: r.end?.pr_url ?? null,
|
|
3083
|
-
last_assistant_text: r.end?.summary ?? r.last_text ?? null,
|
|
3084
|
-
resume: this.dialectOf(r).name === "claude-code" && r.session_id ? { cwd: r.repo, session_id: r.session_id } : null
|
|
3085
|
-
};
|
|
3086
|
-
}
|
|
3087
|
-
async launch(a) {
|
|
3088
|
-
const existing = this.runs.get(a.work_id);
|
|
3089
|
-
if (existing)
|
|
3090
|
-
return {
|
|
3091
|
-
thread_id: a.work_id,
|
|
3092
|
-
resumed: true,
|
|
3093
|
-
permission: existing.used_permission,
|
|
3094
|
-
takeover: true,
|
|
3095
|
-
harness: this.dialectOf(existing).name
|
|
3096
|
-
};
|
|
3097
|
-
const own = this.deps.dialect;
|
|
3098
|
-
if (a.harness && !own.aliases.includes(a.harness))
|
|
3099
|
-
throw new BoxToolError("harness_unavailable");
|
|
3100
|
-
const repo = pickRepo(this.deps.repos, a.repository);
|
|
3101
|
-
const missing = a.repository && !holdsRepository2(repo, a.repository) ? a.repository : null;
|
|
3102
|
-
if (missing)
|
|
3103
|
-
this.log(
|
|
3104
|
-
`launch work=${a.work_id} has no ${missing}; starts in ${basename(repo.path)} to clone it`
|
|
3105
|
-
);
|
|
3106
|
-
else if (a.repository) this.refuseBusy(repo.path);
|
|
3107
|
-
const { dialect, moved } = await this.route(a);
|
|
3108
|
-
const head = await this.repo.head(repo.path);
|
|
3109
|
-
const photos2 = await this.photos(a);
|
|
3110
|
-
const concurrent = this.runs.get(a.work_id);
|
|
3111
|
-
if (concurrent)
|
|
3112
|
-
return {
|
|
3113
|
-
thread_id: a.work_id,
|
|
3114
|
-
resumed: true,
|
|
3115
|
-
permission: concurrent.used_permission,
|
|
3116
|
-
takeover: true,
|
|
3117
|
-
harness: this.dialectOf(concurrent).name
|
|
3118
|
-
};
|
|
3119
|
-
if (!missing && a.repository) this.refuseBusy(repo.path);
|
|
3120
|
-
const apart = !missing && !a.repository && this.busy(repo.path) ? join8(dirname4(this.file), "work", a.work_id) : null;
|
|
3121
|
-
if (apart) {
|
|
3122
|
-
mkdirSync3(apart, { recursive: true, mode: 448 });
|
|
3123
|
-
this.log(`launch work=${a.work_id} ${basename(repo.path)} is busy; starts in its own folder`);
|
|
3124
|
-
}
|
|
3125
|
-
const record = {
|
|
3126
|
-
work_id: a.work_id,
|
|
3127
|
-
session_id: dialect.name === "claude-code" ? a.work_id : null,
|
|
3128
|
-
repo: apart ?? repo.path,
|
|
3129
|
-
title: a.title,
|
|
3130
|
-
prompt: [a.prompt, missing && cloneLine(missing), apart && apartLine(repo), photos2.line].filter(Boolean).join("\n\n"),
|
|
3131
|
-
...photos2.paths.length ? { images: photos2.paths } : {},
|
|
3132
|
-
...a.model && !moved ? { model: a.model } : {},
|
|
3133
|
-
...a.runtime_mode ? { runtime_mode: a.runtime_mode } : {},
|
|
3134
|
-
...a.harness ? { harness_named: true } : {},
|
|
3135
|
-
...a.model ? { model_named: true } : {},
|
|
3136
|
-
...moved ? { harness: dialect.name, moved, switched: switchedLine(moved, own.name, dialect.name) } : {},
|
|
3137
|
-
pid: null,
|
|
3138
|
-
started_at: new Date(this.now()).toISOString(),
|
|
3139
|
-
head_at_launch: apart ? null : head
|
|
3140
|
-
};
|
|
3141
|
-
this.runs.set(a.work_id, record);
|
|
3142
|
-
if (moved)
|
|
3143
|
-
this.log(`fallback work=${a.work_id} harness=${dialect.name} reason=${moved.reason}`);
|
|
3144
|
-
this.spawnRun(record, record.prompt ?? a.prompt, false);
|
|
3145
|
-
return {
|
|
3146
|
-
thread_id: a.work_id,
|
|
3147
|
-
resumed: false,
|
|
3148
|
-
permission: record.used_permission,
|
|
3149
|
-
takeover: true,
|
|
3150
|
-
harness: dialect.name,
|
|
3151
|
-
repository: basename(repo.path),
|
|
3152
|
-
...delivery(a.attachments, photos2.paths.length)
|
|
3153
|
-
};
|
|
3154
|
-
}
|
|
3155
|
-
async send(a) {
|
|
3156
|
-
const r = this.runs.get(a.thread_id) ?? await this.adopt(a.thread_id);
|
|
3157
|
-
const seen2 = r.commands?.find(([id]) => id === a.command_id);
|
|
3158
|
-
if (seen2) return { delivered: seen2[1] };
|
|
3159
|
-
const live = this.lives.get(r.work_id);
|
|
3160
|
-
const ask = live?.asks[0];
|
|
3161
|
-
if (a.answer && (!ask || ask.request_id !== a.question_id)) {
|
|
3162
|
-
this.log(`question_changed work=${r.work_id}`);
|
|
3163
|
-
return {
|
|
3164
|
-
delivered: "question_changed",
|
|
3165
|
-
question: ask?.summary ?? null,
|
|
3166
|
-
question_id: ask?.request_id ?? null
|
|
3167
|
-
};
|
|
3168
|
-
}
|
|
3169
|
-
if (live && ask) {
|
|
3170
|
-
if (!a.answer) {
|
|
3171
|
-
return {
|
|
3172
|
-
delivered: "question_pending",
|
|
3173
|
-
question: ask.summary,
|
|
3174
|
-
questions: live.asks.length
|
|
3175
|
-
};
|
|
3176
|
-
}
|
|
3177
|
-
const line2 = this.dialectOf(r).answerLine?.(ask, a.text);
|
|
3178
|
-
if (!line2) throw new BoxToolError("cannot_steer");
|
|
3179
|
-
live.asks = live.asks.slice(1);
|
|
3180
|
-
this.write(live, line2);
|
|
3181
|
-
this.note(r, `< You answered: ${a.text}`);
|
|
3182
|
-
this.remember(r, a.command_id, "answer");
|
|
3183
|
-
this.log(`answer work=${r.work_id}`);
|
|
3184
|
-
this.askNext(r, live);
|
|
3185
|
-
return { delivered: "answer", question_id: ask.request_id };
|
|
3186
|
-
}
|
|
3187
|
-
if (!live) {
|
|
3188
|
-
if (r.end && !a.resume) throw new BoxToolError("already_finished");
|
|
3189
|
-
if (r.end) {
|
|
3190
|
-
this.refuseBusy(r.repo);
|
|
3191
|
-
r.end = void 0;
|
|
3192
|
-
r.last_text = void 0;
|
|
3193
|
-
}
|
|
3194
|
-
this.runs.set(r.work_id, r);
|
|
3195
|
-
this.spawnRun(r, a.text, true);
|
|
3196
|
-
this.remember(r, a.command_id, "start");
|
|
3197
|
-
return { delivered: "start" };
|
|
3198
|
-
}
|
|
3199
|
-
if (live.child.stdin?.writableEnded) {
|
|
3200
|
-
live.next = live.next ? `${live.next}
|
|
3201
|
-
|
|
3202
|
-
${a.text}` : a.text;
|
|
3203
|
-
this.remember(r, a.command_id, "queue");
|
|
3204
|
-
return { delivered: "queue" };
|
|
3205
|
-
}
|
|
3206
|
-
const line = this.dialectOf(r).userLine?.(r, a.text, a.mode);
|
|
3207
|
-
if (!line) throw new BoxToolError("cannot_steer");
|
|
3208
|
-
live.outstanding++;
|
|
3209
|
-
this.write(live, line);
|
|
3210
|
-
this.note(r, `< You: ${a.text}`);
|
|
3211
|
-
const delivered = a.mode === "queue" ? "queue" : "steer";
|
|
3212
|
-
this.remember(r, a.command_id, delivered);
|
|
3213
|
-
this.log(`${delivered} work=${r.work_id}`);
|
|
3214
|
-
return { delivered };
|
|
3215
|
-
}
|
|
3216
|
-
async interrupt(id, _commandId, stop = STOPPED) {
|
|
3217
|
-
const r = this.record(id);
|
|
3218
|
-
const live = this.lives.get(r.work_id);
|
|
3219
|
-
if (!live) {
|
|
3220
|
-
if (r.end) return { ok: true, was_running: false };
|
|
3221
|
-
const orphan = r.pid !== null && this.alive(r.pid, r);
|
|
3222
|
-
if (orphan && r.pid !== null) {
|
|
3223
|
-
try {
|
|
3224
|
-
process.kill(r.pid, "SIGINT");
|
|
3225
|
-
} catch {
|
|
3226
|
-
}
|
|
3227
|
-
}
|
|
3228
|
-
await this.end(r, stop);
|
|
3229
|
-
return { ok: true, was_running: orphan };
|
|
3230
|
-
}
|
|
3231
|
-
live.interrupted = stop;
|
|
3232
|
-
live.child.kill("SIGINT");
|
|
3233
|
-
this.note(r, stop === STOPPED ? "= Stop requested." : `= ${stop.summary}`);
|
|
3234
|
-
const timer = setTimeout(() => {
|
|
3235
|
-
if (live.child.exitCode === null && live.child.signalCode === null)
|
|
3236
|
-
live.child.kill("SIGTERM");
|
|
3237
|
-
}, this.deps.interruptGraceMs ?? 1e4);
|
|
3238
|
-
timer.unref();
|
|
3239
|
-
this.log(`interrupt work=${r.work_id}${stop.error ? ` reason=${stop.error}` : ""}`);
|
|
3240
|
-
return { ok: true, was_running: true };
|
|
3241
|
-
}
|
|
3242
|
-
/**
|
|
3243
|
-
* `cloop takeover`: stop the run so the owner can open its session in
|
|
3244
|
-
* their own terminal. It ends as a stop, with the machine in its words, and
|
|
3245
|
-
* never resumes by itself: two processes on one session would fight.
|
|
3246
|
-
*/
|
|
3247
|
-
takeOver(id, machine) {
|
|
3248
|
-
return this.interrupt(id, void 0, {
|
|
3249
|
-
kind: "failed",
|
|
3250
|
-
summary: takeoverSummary(machine),
|
|
3251
|
-
error: "taken_over"
|
|
3252
|
-
});
|
|
3253
|
-
}
|
|
3254
|
-
watch(id, onEvent) {
|
|
3255
|
-
const set = this.listeners.get(id) ?? /* @__PURE__ */ new Set();
|
|
3256
|
-
set.add(onEvent);
|
|
3257
|
-
this.listeners.set(id, set);
|
|
3258
|
-
const r = this.runs.get(id);
|
|
3259
|
-
const unwatch = () => set.delete(onEvent);
|
|
3260
|
-
if (!r) {
|
|
3261
|
-
onEvent({ kind: "failed", summary: "This run is not on the machine any more." });
|
|
3262
|
-
return unwatch;
|
|
3263
|
-
}
|
|
3264
|
-
if (r.end) {
|
|
3265
|
-
const { at: _at, ...end } = r.end;
|
|
3266
|
-
onEvent(withFolder(r, end));
|
|
3267
|
-
return unwatch;
|
|
3268
|
-
}
|
|
3269
|
-
const live = this.lives.get(id);
|
|
3270
|
-
const ask = live?.asks[0];
|
|
3271
|
-
if (ask) onEvent({ kind: "question", question_id: ask.request_id, summary: ask.summary });
|
|
3272
|
-
if (!live) void this.recover(r);
|
|
3273
|
-
return unwatch;
|
|
3274
|
-
}
|
|
3275
|
-
/** On a daemon stop: end every process, and leave its run open so the next start resumes it. */
|
|
3276
|
-
stop() {
|
|
3277
|
-
this.stopping = true;
|
|
3278
|
-
for (const live of this.lives.values()) live.child.kill("SIGTERM");
|
|
3279
|
-
}
|
|
3280
|
-
alive(pid, r) {
|
|
3281
|
-
return this.deps.alive ? this.deps.alive(pid, r) : harnessAlive(pid, r, this.dialectOf(r));
|
|
3282
|
-
}
|
|
3283
|
-
/** The harness a run is on: the fallback once it took the run over. */
|
|
3284
|
-
dialectOf(r) {
|
|
3285
|
-
const fallback = this.deps.fallbackHarness;
|
|
3286
|
-
return fallback && r.harness === fallback.name ? fallback : this.deps.dialect;
|
|
3287
|
-
}
|
|
3288
|
-
/**
|
|
3289
|
-
* The fallback harness, when it may carry this run. A move never gives a
|
|
3290
|
-
* run more access than its own harness would: a run that asks the owner
|
|
3291
|
-
* does not go to a harness that asks nothing.
|
|
3292
|
-
*/
|
|
3293
|
-
carrier(run2, own) {
|
|
3294
|
-
const to = this.deps.fallbackHarness;
|
|
3295
|
-
return to && (to.permission?.(run2) !== "full" || own === "full") ? to : null;
|
|
3296
|
-
}
|
|
3297
|
-
/**
|
|
3298
|
-
* A Task that names its harness stays on it. Otherwise a run starts on the
|
|
3299
|
-
* fallback while the runner's own harness is held at its limit, or when the
|
|
3300
|
-
* own harness is signed out or not installed and the fallback is signed in,
|
|
3301
|
-
* unless the Task named its model.
|
|
3302
|
-
*/
|
|
3303
|
-
async route(a) {
|
|
3304
|
-
const own = this.deps.dialect;
|
|
3305
|
-
const mode = a.runtime_mode ? { runtime_mode: a.runtime_mode } : {};
|
|
3306
|
-
const to = a.harness ? null : this.carrier(mode, own.permission?.(mode));
|
|
3307
|
-
const ready = async () => Boolean(to && (await to.probe().catch(() => null))?.signedIn);
|
|
3308
|
-
if (to && this.now() < this.limitedUntil && await ready())
|
|
3309
|
-
return { dialect: to, moved: { reason: "limit", at: "launch" } };
|
|
3310
|
-
const harness = await own.probe();
|
|
3311
|
-
if (harness?.signedIn) return { dialect: own };
|
|
3312
|
-
if (to && !a.model && await ready())
|
|
3313
|
-
return {
|
|
3314
|
-
dialect: to,
|
|
3315
|
-
moved: { reason: harness ? "signed_out" : "missing", at: "launch" }
|
|
3316
|
-
};
|
|
3317
|
-
throw new BoxToolError(harness ? "harness_signed_out" : "harness_unavailable");
|
|
3318
|
-
}
|
|
3319
|
-
/**
|
|
3320
|
-
* The Task's photos for this run, saved beside the runs file so a harness
|
|
3321
|
-
* that takes the run over later attaches them too. `line` tells the agent
|
|
3322
|
-
* they are attached, and how many could not be loaded.
|
|
3323
|
-
*/
|
|
3324
|
-
async photos(a) {
|
|
3325
|
-
if (!a.attachments?.length) return { paths: [], line: "" };
|
|
3326
|
-
const log = (line) => this.log(`${line} work=${a.work_id}`);
|
|
3327
|
-
const { images, missed } = await fetchImages(a.attachments, { log });
|
|
3328
|
-
const paths = await saveImages(
|
|
3329
|
-
images,
|
|
3330
|
-
join8(dirname4(this.file), "attachments", a.work_id)
|
|
3331
|
-
).catch((err) => {
|
|
3332
|
-
log(`attachments_unsaved reason=${err.message.slice(0, 120)}`);
|
|
3333
|
-
return [];
|
|
3334
|
-
});
|
|
3335
|
-
this.log(
|
|
3336
|
-
`attachments work=${a.work_id} attached=${paths.length} missed=${missed + images.length - paths.length}`
|
|
3337
|
-
);
|
|
3338
|
-
return { paths, line: attachedLine(paths.length, a.attachments.length - paths.length) };
|
|
3339
|
-
}
|
|
3340
|
-
/** One checkout, one run: two harnesses editing the same files at once would undo each other. */
|
|
3341
|
-
refuseBusy(repo) {
|
|
3342
|
-
if (this.busy(repo)) throw new BoxToolError("repo_busy");
|
|
3343
|
-
}
|
|
3344
|
-
busy(repo) {
|
|
3345
|
-
return [...this.runs.values()].some((r) => r.repo === repo && !r.end);
|
|
3346
|
-
}
|
|
3347
|
-
/** One question at a time, oldest first, so a yes answers the prompt the owner read. */
|
|
3348
|
-
askNext(r, live) {
|
|
3349
|
-
const next = live.asks[0];
|
|
3350
|
-
if (!next) return;
|
|
3351
|
-
this.log(`question work=${r.work_id} tool=${next.tool}`);
|
|
3352
|
-
this.emit(r.work_id, { kind: "question", question_id: next.request_id, summary: next.summary });
|
|
3353
|
-
}
|
|
3354
|
-
/** A run left open by a daemon that died: wait for its old process to go, then resume it once. */
|
|
3355
|
-
async recover(r) {
|
|
3356
|
-
if (this.recovering.has(r.work_id)) return;
|
|
3357
|
-
this.recovering.add(r.work_id);
|
|
3358
|
-
try {
|
|
3359
|
-
while (r.pid !== null && this.alive(r.pid, r) && !r.end && !this.stopping) {
|
|
3360
|
-
await sleep2(this.deps.orphanPollMs ?? 2e3);
|
|
3361
|
-
}
|
|
3362
|
-
if (r.end || this.stopping || this.lives.has(r.work_id)) return;
|
|
3363
|
-
this.log(`resume work=${r.work_id} after a restart`);
|
|
3364
|
-
this.spawnRun(r, CONTINUE_PROMPT, true);
|
|
3365
|
-
} finally {
|
|
3366
|
-
this.recovering.delete(r.work_id);
|
|
3367
|
-
}
|
|
3368
|
-
}
|
|
3369
|
-
spawnRun(r, prompt, resume) {
|
|
3370
|
-
r.block_text = void 0;
|
|
3371
|
-
const dialect = this.dialectOf(r);
|
|
3372
|
-
r.used_permission = dialect.permission?.(r);
|
|
3373
|
-
const images = resume ? [] : r.images ?? [];
|
|
3374
|
-
const command = commandFor(dialect.bin, dialect.args(r, resume, images));
|
|
3375
|
-
const child = spawn(command.file, command.args, {
|
|
3376
|
-
cwd: r.repo,
|
|
3377
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
3378
|
-
env: { ...dialect.env, ...process.env },
|
|
3379
|
-
...command.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
|
|
3380
|
-
});
|
|
3381
|
-
const live = {
|
|
3382
|
-
child,
|
|
3383
|
-
outstanding: 1,
|
|
3384
|
-
asks: [],
|
|
3385
|
-
lastProgressAt: 0,
|
|
3386
|
-
interrupted: null,
|
|
3387
|
-
stderr: ""
|
|
3388
|
-
};
|
|
3389
|
-
this.lives.set(r.work_id, live);
|
|
3390
|
-
r.pid = child.pid ?? null;
|
|
3391
|
-
this.save();
|
|
3392
|
-
this.log(`spawn work=${r.work_id} pid=${r.pid ?? "none"} ${resume ? "resume" : "new"}`);
|
|
3393
|
-
this.note(r, resume ? "= Resumed." : `= Started "${r.title}" in ${r.repo}`);
|
|
3394
|
-
child.stdin?.on("error", () => {
|
|
3395
|
-
});
|
|
3396
|
-
child.stdin?.write(dialect.opening(r, `${prompt}
|
|
3397
|
-
|
|
3398
|
-
${MACHINE_RESULT_INSTRUCTION}`, images));
|
|
3399
|
-
if (!dialect.keepsStdin) child.stdin?.end();
|
|
3400
|
-
child.stderr?.on("data", (chunk) => {
|
|
3401
|
-
live.stderr = (live.stderr + chunk.toString("utf-8")).slice(-2e3);
|
|
3402
|
-
});
|
|
3403
|
-
const lines = createInterface2({ input: child.stdout });
|
|
3404
|
-
lines.on("line", (line) => {
|
|
3405
|
-
for (const item of dialect.parse(line, r)) this.onItem(r, live, item);
|
|
3406
|
-
});
|
|
3407
|
-
child.on("error", (err) => {
|
|
3408
|
-
this.log(`spawn failed work=${r.work_id}: ${err.message.slice(0, 200)}`);
|
|
3409
|
-
});
|
|
3410
|
-
child.on("close", (code, signal) => void this.onExit(r, live, code, signal));
|
|
3411
|
-
}
|
|
3412
|
-
onItem(r, live, item) {
|
|
3413
|
-
const logged = logLineFor(item);
|
|
3414
|
-
if (logged) this.note(r, logged);
|
|
3415
|
-
switch (item.type) {
|
|
3416
|
-
case "session":
|
|
3417
|
-
if (r.session_id !== item.id) {
|
|
3418
|
-
r.session_id = item.id;
|
|
3419
|
-
this.save();
|
|
3420
|
-
}
|
|
3421
|
-
return;
|
|
3422
|
-
case "text":
|
|
3423
|
-
r.last_text = item.text.slice(0, 1e5);
|
|
3424
|
-
if (hasResultBlock(item.text)) r.block_text = r.last_text;
|
|
3425
|
-
this.progress(r, live, item.text, false);
|
|
3426
|
-
return;
|
|
3427
|
-
case "tool": {
|
|
3428
|
-
const line = item.summary ?? (item.target ? `${item.name} ${item.target}` : item.name);
|
|
3429
|
-
if (!isProgressSentence(line)) return;
|
|
3430
|
-
const changed = item.name !== live.lastTool;
|
|
3431
|
-
live.lastTool = item.name;
|
|
3432
|
-
this.progress(r, live, line, changed);
|
|
3433
|
-
return;
|
|
3434
|
-
}
|
|
3435
|
-
case "ask":
|
|
3436
|
-
live.asks.push(item);
|
|
3437
|
-
if (live.asks.length === 1) this.askNext(r, live);
|
|
3438
|
-
return;
|
|
3439
|
-
case "cancel": {
|
|
3440
|
-
const wasAsked = live.asks[0]?.request_id === item.request_id;
|
|
3441
|
-
live.asks = live.asks.filter((x) => x.request_id !== item.request_id);
|
|
3442
|
-
if (wasAsked) this.askNext(r, live);
|
|
3443
|
-
return;
|
|
3444
|
-
}
|
|
3445
|
-
case "signed_out":
|
|
3446
|
-
live.signedOut = true;
|
|
3447
|
-
return;
|
|
3448
|
-
case "result":
|
|
3449
|
-
live.outstanding--;
|
|
3450
|
-
live.result = { ok: item.ok, ...item.text ? { text: item.text } : {} };
|
|
3451
|
-
if (item.text) r.last_text = item.text.slice(0, 1e5);
|
|
3452
|
-
if (live.outstanding <= 0 && live.asks.length === 0) live.child.stdin?.end();
|
|
3453
|
-
return;
|
|
3454
|
-
}
|
|
3455
|
-
}
|
|
3456
|
-
progress(r, live, line, force) {
|
|
3457
|
-
const summary = nextProgress(live, line, this.now(), this.deps.progressMs, force);
|
|
3458
|
-
if (summary) this.emit(r.work_id, { kind: "progress", summary });
|
|
3459
|
-
}
|
|
3460
|
-
async onExit(r, live, code, signal) {
|
|
3461
|
-
if (this.lives.get(r.work_id) === live) this.lives.delete(r.work_id);
|
|
3462
|
-
if (this.stopping || r.end) return;
|
|
3463
|
-
const exit = signal ? `signal ${signal}` : `code ${code}`;
|
|
3464
|
-
this.log(
|
|
3465
|
-
`exit work=${r.work_id} ${exit} result=${live.result ? live.result.ok ? "ok" : "error" : "none"}`
|
|
3466
|
-
);
|
|
3467
|
-
if (live.interrupted) {
|
|
3468
|
-
await this.end(r, live.interrupted);
|
|
3469
|
-
return;
|
|
3470
|
-
}
|
|
3471
|
-
if (live.next) {
|
|
3472
|
-
this.spawnRun(r, live.next, true);
|
|
3473
|
-
return;
|
|
3474
|
-
}
|
|
3475
|
-
if (code === 0 && live.result?.ok) {
|
|
3476
|
-
const text3 = live.result.text?.trim() || r.last_text;
|
|
3477
|
-
const { result, dropped } = readRunResult(resultText(text3, r.block_text));
|
|
3478
|
-
const lost = droppedLine(dropped, r.work_id);
|
|
3479
|
-
if (lost) this.log(lost);
|
|
3480
|
-
const { pr, note } = await this.outcome(r, text3);
|
|
3481
|
-
const summary = finalWords([r.switched, note, text3].filter(Boolean).join("\n\n"));
|
|
3482
|
-
await this.end(r, {
|
|
3483
|
-
kind: "settled",
|
|
3484
|
-
...result ? { result } : {},
|
|
3485
|
-
...summary ? { summary: summary.slice(0, RUN_TEXT_MAX) } : {},
|
|
3486
|
-
...pr ? { pr_url: pr } : {}
|
|
3487
|
-
});
|
|
3488
|
-
return;
|
|
3489
|
-
}
|
|
3490
|
-
if (live.stderr)
|
|
3491
|
-
this.log(`stderr work=${r.work_id}: ${live.stderr.trim().split("\n").at(-1)?.slice(0, 200)}`);
|
|
3492
|
-
const end = failedEnd(this.dialectOf(r).name, {
|
|
3493
|
-
result: live.result,
|
|
3494
|
-
lastText: r.last_text,
|
|
3495
|
-
exit,
|
|
3496
|
-
...r.switched ? { switched: r.switched } : {}
|
|
3497
|
-
});
|
|
3498
|
-
if (await this.otherModel(r, live.result?.text)) return;
|
|
3499
|
-
if (end.error) this.log(`limit work=${r.work_id} error=${end.error}`);
|
|
3500
|
-
if (end.error === "harness_limit") {
|
|
3501
|
-
if (this.fallBack(r, live.result?.text)) return;
|
|
3502
|
-
if (await this.moveHarness(r, live.result?.text, "limit")) return;
|
|
3503
|
-
}
|
|
3504
|
-
if (live.signedOut) {
|
|
3505
|
-
this.log(`signed_out work=${r.work_id} harness=${this.dialectOf(r).name}`);
|
|
3506
|
-
if (await this.moveHarness(r, live.result?.text, "signed_out")) return;
|
|
3507
|
-
}
|
|
3508
|
-
const signedOut = !end.error && live.signedOut ? { error: "harness_signed_out" } : {};
|
|
3509
|
-
await this.end(r, { kind: "failed", ...end, ...signedOut });
|
|
3510
|
-
}
|
|
3511
|
-
/**
|
|
3512
|
-
* Once per run: a run stopped by its model's usage limit resumes its own
|
|
3513
|
-
* session on the first fallback model, with the continue prompt, so its
|
|
3514
|
-
* steers, answers and edits carry over. It does not when the Task named its
|
|
3515
|
-
* model, when the limit is the fallback model's own or names no model, or
|
|
3516
|
-
* after one switch. `--fallback-model` may already cover this; it is not
|
|
3517
|
-
* documented whether a plan's limit counts. The switch opens the end
|
|
3518
|
-
* summary, because a progress line is dropped while the socket is down.
|
|
3519
|
-
*/
|
|
3520
|
-
fallBack(r, said) {
|
|
3521
|
-
const model = this.dialectOf(r).fallback?.split(",")[0]?.trim();
|
|
3522
|
-
if (!model || !r.session_id || r.switched || r.model) return false;
|
|
3523
|
-
const named = new RegExp(`\\b${model.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i");
|
|
3524
|
-
if (named.test(said ?? "")) return false;
|
|
3525
|
-
const from = limitedModel(said);
|
|
3526
|
-
if (!from) return false;
|
|
3527
|
-
const to = `${model.charAt(0).toUpperCase()}${model.slice(1)}`;
|
|
3528
|
-
r.switched = `${from} was at its usage limit, so this ran on ${to}.`;
|
|
3529
|
-
r.model = model;
|
|
3530
|
-
this.save();
|
|
3531
|
-
this.log(`fallback work=${r.work_id} model=${model}`);
|
|
3532
|
-
this.emit(r.work_id, {
|
|
3533
|
-
kind: "progress",
|
|
3534
|
-
summary: `${from} is at its usage limit, so I switched to ${to}`
|
|
3535
|
-
});
|
|
3536
|
-
this.spawnRun(r, CONTINUE_PROMPT, true);
|
|
3537
|
-
return true;
|
|
3538
|
-
}
|
|
3539
|
-
/**
|
|
3540
|
-
* A model the account cannot use refuses the run before it does any work,
|
|
3541
|
-
* as ChatGPT Free does for a model `config.toml` pins. The run starts again
|
|
3542
|
-
* on the next model the account lists, best first, until one takes it or
|
|
3543
|
-
* the list runs out. It does not when the Task named its model.
|
|
3544
|
-
*/
|
|
3545
|
-
async otherModel(r, said) {
|
|
3546
|
-
const refused = refusedModel(said);
|
|
3547
|
-
const dialect = this.dialectOf(r);
|
|
3548
|
-
if (!refused || !dialect.models || !r.prompt || r.model && !r.refused) return false;
|
|
3549
|
-
const tried = [...r.refused ?? [], refused];
|
|
3550
|
-
this.recovering.add(r.work_id);
|
|
3551
|
-
let listed;
|
|
3552
|
-
try {
|
|
3553
|
-
listed = await dialect.models().catch(() => []);
|
|
3554
|
-
} finally {
|
|
3555
|
-
this.recovering.delete(r.work_id);
|
|
3556
|
-
}
|
|
3557
|
-
const next = nextModel(listed, tried);
|
|
3558
|
-
if (!next)
|
|
3559
|
-
this.log(`model work=${r.work_id} refused=${refused} next=none catalog=${listed.length}`);
|
|
3560
|
-
if (!next || this.stopping || r.end) return false;
|
|
3561
|
-
const moved = r.harness && r.moved ? switchedLine(r.moved, this.deps.dialect.name, r.harness) : null;
|
|
3562
|
-
r.refused = tried;
|
|
3563
|
-
r.model = next;
|
|
3564
|
-
r.session_id = null;
|
|
3565
|
-
r.switched = [moved, refusedModelLine(harnessName(dialect.name), tried[0] ?? refused, next)].filter(Boolean).join(" ");
|
|
3566
|
-
this.save();
|
|
3567
|
-
this.log(`model work=${r.work_id} refused=${refused} next=${next}`);
|
|
3568
|
-
this.spawnRun(
|
|
3569
|
-
r,
|
|
3570
|
-
r.moved?.at === "run" ? handoverPrompt(r.prompt, harnessName(this.deps.dialect.name), r.moved.reason) : r.prompt,
|
|
3571
|
-
false
|
|
3572
|
-
);
|
|
3573
|
-
return true;
|
|
3574
|
-
}
|
|
3575
|
-
/**
|
|
3576
|
-
* Once per run: a run its own harness cannot carry on, at its usage limit
|
|
3577
|
-
* or signed out, starts again on the fallback harness, in the same
|
|
3578
|
-
* checkout, so the edits so far carry over. The session does not: the
|
|
3579
|
-
* prompt goes again, with a note to read the checkout first. A limit that
|
|
3580
|
-
* names no model holds the account, so new runs start on the fallback for
|
|
3581
|
-
* LIMIT_HOLD_MS; a sign-in failure holds nothing, because the next run's
|
|
3582
|
-
* check may find the harness signed in again. It does not move a run whose
|
|
3583
|
-
* Task named its harness, a signed-out run whose Task named its model, nor
|
|
3584
|
-
* one the fallback may not carry.
|
|
3585
|
-
*/
|
|
3586
|
-
async moveHarness(r, said, reason) {
|
|
3587
|
-
const to = this.deps.fallbackHarness;
|
|
3588
|
-
if (!to || r.harness) return false;
|
|
3589
|
-
if (reason === "limit" && !limitedModel(said)) this.limitedUntil = this.now() + LIMIT_HOLD_MS;
|
|
3590
|
-
if (r.harness_named || reason === "signed_out" && r.model_named) return false;
|
|
3591
|
-
if (!this.carrier(r, r.used_permission) || !r.prompt) return false;
|
|
3592
|
-
this.recovering.add(r.work_id);
|
|
3593
|
-
try {
|
|
3594
|
-
const probe = await to.probe().catch(() => null);
|
|
3595
|
-
if (!probe?.signedIn || this.stopping || r.end) return false;
|
|
3596
|
-
} finally {
|
|
3597
|
-
this.recovering.delete(r.work_id);
|
|
3598
|
-
}
|
|
3599
|
-
const from = this.deps.dialect.name;
|
|
3600
|
-
const move = { reason, at: "run" };
|
|
3601
|
-
r.harness = to.name;
|
|
3602
|
-
r.moved = move;
|
|
3603
|
-
r.session_id = null;
|
|
3604
|
-
r.model = void 0;
|
|
3605
|
-
r.switched = switchedLine(move, from, to.name);
|
|
3606
|
-
this.save();
|
|
3607
|
-
this.log(`fallback work=${r.work_id} harness=${to.name} reason=${reason}`);
|
|
3608
|
-
this.emit(r.work_id, {
|
|
3609
|
-
kind: "progress",
|
|
3610
|
-
summary: movingLine(reason, harnessName(from), harnessName(to.name))
|
|
3611
|
-
});
|
|
3612
|
-
this.spawnRun(r, handoverPrompt(r.prompt, harnessName(from), reason), false);
|
|
3613
|
-
return true;
|
|
3614
|
-
}
|
|
3615
|
-
/**
|
|
3616
|
-
* The PR a run produced: one its last text names, else the PR of the
|
|
3617
|
-
* branch, but only when the run moved HEAD. A run that left HEAD where it
|
|
3618
|
-
* started produced nothing, and the branch's PR belongs to someone else's
|
|
3619
|
-
* work. A run that committed without pushing says so.
|
|
3620
|
-
*/
|
|
3621
|
-
async outcome(r, text3) {
|
|
3622
|
-
const named = resultPrUrl(text3);
|
|
3623
|
-
if (named) return { pr: named };
|
|
3624
|
-
if (!r.head_at_launch) return { pr: null };
|
|
3625
|
-
const head = await this.repo.head(r.repo);
|
|
3626
|
-
if (!head || head === r.head_at_launch) return { pr: null };
|
|
3627
|
-
const pr = await this.repo.branchPr(r.repo);
|
|
3628
|
-
if (pr) return { pr };
|
|
3629
|
-
return await this.repo.pushed(r.repo) ? { pr: null } : { pr: null, note: `Committed ${head.slice(0, 7)}, not pushed.` };
|
|
3630
|
-
}
|
|
3631
|
-
async end(r, ended) {
|
|
3632
|
-
if (r.end) return;
|
|
3633
|
-
const end = { ...ended, harness: this.dialectOf(r).name };
|
|
3634
|
-
r.end = { ...end, at: new Date(this.now()).toISOString() };
|
|
3635
|
-
r.pid = null;
|
|
3636
|
-
this.save();
|
|
3637
|
-
this.note(r, endNote(end));
|
|
3638
|
-
this.emit(r.work_id, withFolder(r, end));
|
|
3639
|
-
}
|
|
3640
|
-
emit(id, event) {
|
|
3641
|
-
for (const listener of [...this.listeners.get(id) ?? []]) listener(event);
|
|
3642
|
-
}
|
|
3643
|
-
write(live, line) {
|
|
3644
|
-
live.child.stdin?.write(line);
|
|
3645
|
-
}
|
|
3646
|
-
remember(r, commandId, delivered) {
|
|
3647
|
-
r.commands = [
|
|
3648
|
-
...r.commands ?? [],
|
|
3649
|
-
[commandId, delivered]
|
|
3650
|
-
].slice(-COMMANDS_KEPT);
|
|
3651
|
-
this.save();
|
|
3652
|
-
}
|
|
3653
|
-
record(id) {
|
|
3654
|
-
const r = this.runs.get(id);
|
|
3655
|
-
if (!r) throw new BoxToolError("bad_args");
|
|
3656
|
-
return r;
|
|
3657
|
-
}
|
|
3658
|
-
statusOf(r) {
|
|
3659
|
-
if (this.lives.has(r.work_id)) return "running";
|
|
3660
|
-
if (!r.end) return "pending";
|
|
3661
|
-
return r.end.kind === "settled" ? "completed" : "failed";
|
|
3662
|
-
}
|
|
3663
|
-
load() {
|
|
3664
|
-
const cutoff = this.now() - KEEP_MS;
|
|
3665
|
-
return readRunRecords(this.file).filter((r) => !(r.end && Date.parse(r.end.at) < cutoff));
|
|
3666
|
-
}
|
|
3667
|
-
save() {
|
|
3668
|
-
mkdirSync3(dirname4(this.file), { recursive: true, mode: 448 });
|
|
3669
|
-
const tmp = `${this.file}.tmp`;
|
|
3670
|
-
writeFileSync2(tmp, `${JSON.stringify([...this.runs.values()], null, 2)}
|
|
3671
|
-
`, { mode: 384 });
|
|
3672
|
-
chmodSync3(tmp, 384);
|
|
3673
|
-
renameSync3(tmp, this.file);
|
|
3674
|
-
}
|
|
3675
|
-
};
|
|
3676
|
-
function readRunRecords(file = localRunsFilePath()) {
|
|
3677
|
-
try {
|
|
3678
|
-
const raw = JSON.parse(readFileSync2(file, "utf-8"));
|
|
3679
|
-
return Array.isArray(raw) ? raw.filter(
|
|
3680
|
-
(r) => typeof r?.work_id === "string" && typeof r?.repo === "string"
|
|
3681
|
-
) : [];
|
|
3682
|
-
} catch {
|
|
3683
|
-
return [];
|
|
3684
|
-
}
|
|
3685
|
-
}
|
|
3686
|
-
|
|
3687
2040
|
export {
|
|
3688
|
-
RUN_MEDIA_CLASSES,
|
|
3689
|
-
RUN_MEDIA_TYPES,
|
|
3690
|
-
imageExt,
|
|
3691
|
-
mediaExt,
|
|
3692
|
-
RUN_PREVIEWS_MAX,
|
|
3693
|
-
MACHINE_RESULT_INSTRUCTION,
|
|
3694
|
-
readRunResult,
|
|
3695
|
-
hasResultBlock,
|
|
3696
|
-
resultText,
|
|
3697
|
-
resultPrUrl,
|
|
3698
|
-
ownHarnessFirst,
|
|
3699
|
-
RUNTIME_MODES,
|
|
3700
|
-
BoxToolError,
|
|
3701
|
-
CLOOP_THREAD_PREFIX,
|
|
3702
|
-
questionLine,
|
|
3703
|
-
IDLE_SETTLE_MS,
|
|
3704
|
-
holdsForNextTurn,
|
|
3705
|
-
RUN_TEXT_MAX,
|
|
3706
|
-
finalWords,
|
|
3707
|
-
nextProgress,
|
|
3708
|
-
isYes,
|
|
3709
|
-
HARNESS_LIMIT,
|
|
3710
|
-
refusedModel,
|
|
3711
|
-
nextModel,
|
|
3712
|
-
refusedRecently,
|
|
3713
|
-
refusedModelLine,
|
|
3714
|
-
apiErrorWords,
|
|
3715
|
-
HARNESS_SIGNED_OUT,
|
|
3716
|
-
CLAUDE_AUTH_LOCKED,
|
|
3717
|
-
ENVIRONMENTS,
|
|
3718
|
-
environmentOf,
|
|
3719
|
-
runnerEnvironment,
|
|
3720
|
-
runnerDir,
|
|
3721
|
-
runnerPath,
|
|
3722
|
-
cloopCommand,
|
|
3723
|
-
serviceIdentity,
|
|
3724
|
-
commandFor,
|
|
3725
|
-
quoteWindowsArg,
|
|
3726
|
-
windowsExecutable,
|
|
3727
|
-
windowsPowerShellEnv,
|
|
3728
|
-
boxPath,
|
|
3729
|
-
isLocal,
|
|
3730
|
-
isHosted,
|
|
3731
|
-
isT3,
|
|
3732
|
-
showsOtherThreads,
|
|
3733
|
-
otherThreadsChoice,
|
|
3734
|
-
readRunnerConfig,
|
|
3735
|
-
writeBoxConfig,
|
|
3736
2041
|
IMAGE_TYPES,
|
|
3737
|
-
|
|
3738
|
-
runLogDir,
|
|
3739
|
-
runLogPath,
|
|
3740
|
-
redactSecrets,
|
|
3741
|
-
STOPPED_SUMMARY,
|
|
3742
|
-
isEndLogLine,
|
|
2042
|
+
repoName,
|
|
3743
2043
|
parseAttachments,
|
|
3744
2044
|
fetchImages,
|
|
3745
2045
|
delivery,
|
|
3746
2046
|
saveImages,
|
|
3747
2047
|
attachedLine,
|
|
3748
|
-
HARNESS_STALE_MS,
|
|
3749
|
-
defaultT3BinSources,
|
|
3750
|
-
t3Candidates,
|
|
3751
|
-
pickT3Bin,
|
|
3752
|
-
t3BaseDirArgs,
|
|
3753
|
-
runT3Async,
|
|
3754
2048
|
MIN_PROTOCOL,
|
|
3755
2049
|
readEnvironment,
|
|
3756
2050
|
exchangePairing,
|
|
3757
2051
|
T3HttpError,
|
|
3758
2052
|
T3Client,
|
|
2053
|
+
HARNESS_STALE_MS,
|
|
2054
|
+
HarnessCheck,
|
|
3759
2055
|
TOKEN_SCOPE,
|
|
3760
2056
|
quotaFromCodex,
|
|
3761
2057
|
quotaFromClaude,
|
|
@@ -3766,12 +2062,20 @@ export {
|
|
|
3766
2062
|
addTokens,
|
|
3767
2063
|
sortedDays,
|
|
3768
2064
|
sourceKey,
|
|
2065
|
+
runLogDir,
|
|
2066
|
+
runLogPath,
|
|
2067
|
+
redactSecrets,
|
|
2068
|
+
logLineFor,
|
|
2069
|
+
appendRunLog,
|
|
2070
|
+
pruneRunLogs,
|
|
2071
|
+
STOPPED_SUMMARY,
|
|
2072
|
+
endNote,
|
|
2073
|
+
isEndLogLine,
|
|
2074
|
+
defaultT3BinSources,
|
|
2075
|
+
t3Candidates,
|
|
2076
|
+
pickT3Bin,
|
|
2077
|
+
t3BaseDirArgs,
|
|
2078
|
+
runT3Async,
|
|
3769
2079
|
orderThreads,
|
|
3770
|
-
T3Driver
|
|
3771
|
-
takeoverSummary,
|
|
3772
|
-
runHarness,
|
|
3773
|
-
failedEnd,
|
|
3774
|
-
localRunsFilePath,
|
|
3775
|
-
LocalDriver,
|
|
3776
|
-
readRunRecords
|
|
2080
|
+
T3Driver
|
|
3777
2081
|
};
|