@cloop/runner 0.0.0-stage → 0.2.1
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/README.md +65 -2
- package/dist/box-HBQ4ZM2Y.js +247 -0
- package/dist/chunk-2ZVYM4JU.js +2755 -0
- package/dist/chunk-3DIGCVL4.js +70 -0
- package/dist/chunk-4LFQXBWP.js +26 -0
- package/dist/chunk-AG6SI6I2.js +88 -0
- package/dist/chunk-AQGBNKUG.js +239 -0
- package/dist/chunk-J6AEO3GT.js +97 -0
- package/dist/chunk-JX6VG5FE.js +150 -0
- package/dist/chunk-OJ5AREUC.js +131 -0
- package/dist/chunk-OKF4BDBH.js +8 -0
- package/dist/chunk-ZILLDYL4.js +150 -0
- package/dist/connect-LRQ4C3KK.js +66 -0
- package/dist/disconnect-FQ6ODTTE.js +143 -0
- package/dist/hook-activity-O2NNKTOE.js +91 -0
- package/dist/hook-session-start-MT67MMDM.js +153 -0
- package/dist/index.js +111 -0
- package/dist/install-HTDTCELB.js +100 -0
- package/dist/login-4GUYT5MR.js +14 -0
- package/dist/mcp-server-TV7MHVHZ.js +399 -0
- package/dist/runner-5H7ECAZ6.js +147 -0
- package/dist/statusline-6JMHIL54.js +177 -0
- package/package.json +57 -5
|
@@ -0,0 +1,2755 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
ConnectFailure,
|
|
4
|
+
connectReport,
|
|
5
|
+
deviceLogin,
|
|
6
|
+
newAttempt,
|
|
7
|
+
sendConnectReport
|
|
8
|
+
} from "./chunk-AQGBNKUG.js";
|
|
9
|
+
import {
|
|
10
|
+
getMachine,
|
|
11
|
+
shortMachineName
|
|
12
|
+
} from "./chunk-JX6VG5FE.js";
|
|
13
|
+
import {
|
|
14
|
+
VERSION
|
|
15
|
+
} from "./chunk-OKF4BDBH.js";
|
|
16
|
+
import {
|
|
17
|
+
CONFIG_DIR,
|
|
18
|
+
STAGING_ORIGIN,
|
|
19
|
+
getOrigin
|
|
20
|
+
} from "./chunk-3DIGCVL4.js";
|
|
21
|
+
|
|
22
|
+
// src/commands/connect.ts
|
|
23
|
+
import { execFileSync as execFileSync4 } from "child_process";
|
|
24
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
25
|
+
import { existsSync as existsSync2, mkdirSync as mkdirSync4, readdirSync as readdirSync2, rmSync, writeFileSync as writeFileSync4 } from "fs";
|
|
26
|
+
import { homedir as homedir4 } from "os";
|
|
27
|
+
import { basename as basename4, dirname as dirname4, join as join5, resolve as resolve2 } from "path";
|
|
28
|
+
import { createInterface as createInterface2 } from "readline/promises";
|
|
29
|
+
|
|
30
|
+
// src/drivers/driver.ts
|
|
31
|
+
var RUNTIME_MODES = /* @__PURE__ */ new Set([
|
|
32
|
+
"approval-required",
|
|
33
|
+
"auto-accept-edits",
|
|
34
|
+
"auto",
|
|
35
|
+
"full-access"
|
|
36
|
+
]);
|
|
37
|
+
var BoxToolError = class extends Error {
|
|
38
|
+
constructor(code) {
|
|
39
|
+
super(code);
|
|
40
|
+
this.code = code;
|
|
41
|
+
this.name = "BoxToolError";
|
|
42
|
+
}
|
|
43
|
+
code;
|
|
44
|
+
};
|
|
45
|
+
var CLOOP_THREAD_PREFIX = "cloop:";
|
|
46
|
+
function questionLine(questions) {
|
|
47
|
+
return questions.map(
|
|
48
|
+
(x) => x.options?.length ? `${x.question} (${x.options.map((o) => o.label).join(", ")})` : x.question
|
|
49
|
+
).join(" ").slice(0, 500);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// src/t3.ts
|
|
53
|
+
var T3_SCOPE = "orchestration:read orchestration:operate";
|
|
54
|
+
var MIN_PROTOCOL = 2;
|
|
55
|
+
async function readEnvironment(t3Url, fetchFn = fetch) {
|
|
56
|
+
const res = await fetchFn(`${t3Url}/.well-known/t3/environment`);
|
|
57
|
+
if (!res.ok) throw new Error(`T3 environment ${res.status} at ${t3Url}`);
|
|
58
|
+
return await res.json();
|
|
59
|
+
}
|
|
60
|
+
async function exchangePairing(t3Url, credential, label, fetchFn = fetch) {
|
|
61
|
+
const form = new URLSearchParams({
|
|
62
|
+
grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
|
|
63
|
+
subject_token: credential,
|
|
64
|
+
subject_token_type: "urn:t3:params:oauth:token-type:environment-bootstrap",
|
|
65
|
+
requested_token_type: "urn:ietf:params:oauth:token-type:access_token",
|
|
66
|
+
scope: T3_SCOPE,
|
|
67
|
+
client_label: label,
|
|
68
|
+
client_device_type: "bot"
|
|
69
|
+
});
|
|
70
|
+
const res = await fetchFn(`${t3Url}/oauth/token`, { method: "POST", body: form });
|
|
71
|
+
if (!res.ok) throw new Error(`T3 token exchange ${res.status}`);
|
|
72
|
+
const token = await res.json();
|
|
73
|
+
if (!sameScopes(token.scope, T3_SCOPE))
|
|
74
|
+
throw new Error(`T3 granted scope "${token.scope}", wanted "${T3_SCOPE}"`);
|
|
75
|
+
return token;
|
|
76
|
+
}
|
|
77
|
+
function sameScopes(a, b) {
|
|
78
|
+
const set = (s) => [...new Set(s.split(/\s+/).filter(Boolean))].sort().join(" ");
|
|
79
|
+
return set(a) === set(b);
|
|
80
|
+
}
|
|
81
|
+
var T3HttpError = class extends Error {
|
|
82
|
+
constructor(path, status) {
|
|
83
|
+
super(`T3 ${path} ${status}`);
|
|
84
|
+
this.status = status;
|
|
85
|
+
this.name = "T3HttpError";
|
|
86
|
+
}
|
|
87
|
+
status;
|
|
88
|
+
};
|
|
89
|
+
var T3Client = class {
|
|
90
|
+
constructor(t3Url, token, fetchFn = fetch) {
|
|
91
|
+
this.t3Url = t3Url;
|
|
92
|
+
this.token = token;
|
|
93
|
+
this.fetchFn = fetchFn;
|
|
94
|
+
}
|
|
95
|
+
t3Url;
|
|
96
|
+
token;
|
|
97
|
+
fetchFn;
|
|
98
|
+
async http(path, headers = {}) {
|
|
99
|
+
const res = await this.fetchFn(`${this.t3Url}${path}`, {
|
|
100
|
+
headers: { authorization: `Bearer ${this.token}`, ...headers }
|
|
101
|
+
});
|
|
102
|
+
if (!res.ok) throw new T3HttpError(path, res.status);
|
|
103
|
+
return await res.json();
|
|
104
|
+
}
|
|
105
|
+
async openSocket() {
|
|
106
|
+
const ticket = await this.fetchFn(`${this.t3Url}/api/auth/websocket-ticket`, {
|
|
107
|
+
method: "POST",
|
|
108
|
+
headers: { authorization: `Bearer ${this.token}` }
|
|
109
|
+
});
|
|
110
|
+
if (!ticket.ok) throw new T3HttpError("/api/auth/websocket-ticket", ticket.status);
|
|
111
|
+
const { ticket: wsTicket } = await ticket.json();
|
|
112
|
+
const { WebSocket } = await import("ws");
|
|
113
|
+
const url = `${this.t3Url.replace(/^http/, "ws")}/ws?wsTicket=${encodeURIComponent(wsTicket)}&orchestrationProtocol=2&clientSurface=web&clientAppVersion=cloop-box`;
|
|
114
|
+
return new WebSocket(url);
|
|
115
|
+
}
|
|
116
|
+
/** 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. */
|
|
117
|
+
async rpc(tag, payload) {
|
|
118
|
+
const ws = await this.openSocket();
|
|
119
|
+
return new Promise((resolve3, reject) => {
|
|
120
|
+
let settled = false;
|
|
121
|
+
const finish = (fn) => {
|
|
122
|
+
if (settled) return;
|
|
123
|
+
settled = true;
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
fn();
|
|
126
|
+
try {
|
|
127
|
+
ws.close();
|
|
128
|
+
} catch {
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
const timer = setTimeout(
|
|
132
|
+
() => finish(() => reject(new Error(`T3 rpc ${tag} timed out`))),
|
|
133
|
+
15e3
|
|
134
|
+
);
|
|
135
|
+
ws.on(
|
|
136
|
+
"error",
|
|
137
|
+
(err) => finish(() => reject(err instanceof Error ? err : new Error(String(err))))
|
|
138
|
+
);
|
|
139
|
+
ws.on(
|
|
140
|
+
"close",
|
|
141
|
+
() => finish(() => reject(new Error(`T3 rpc ${tag}: socket closed before a reply`)))
|
|
142
|
+
);
|
|
143
|
+
ws.on("open", () => {
|
|
144
|
+
ws.send(JSON.stringify({ _tag: "Request", id: 1, tag, payload, headers: [] }));
|
|
145
|
+
});
|
|
146
|
+
ws.on("message", (data) => {
|
|
147
|
+
for (const msg of parseFrames(data)) {
|
|
148
|
+
if (msg._tag !== "Exit" || String(msg.requestId) !== "1") continue;
|
|
149
|
+
const exit = msg.exit;
|
|
150
|
+
if (exit._tag === "Success") finish(() => resolve3(exit.value));
|
|
151
|
+
else {
|
|
152
|
+
finish(
|
|
153
|
+
() => reject(
|
|
154
|
+
new Error(`T3 rpc ${tag} failed: ${JSON.stringify(exit.cause).slice(0, 300)}`)
|
|
155
|
+
)
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* A streaming request, such as `orchestration.subscribeThread`, on its own
|
|
164
|
+
* socket. Every item is acked, as Effect RPC requires. `done` resolves with
|
|
165
|
+
* the reason the stream ended and never rejects; `close` interrupts it.
|
|
166
|
+
*/
|
|
167
|
+
async stream(tag, payload, onItem) {
|
|
168
|
+
const ws = await this.openSocket();
|
|
169
|
+
let resolveDone = () => {
|
|
170
|
+
};
|
|
171
|
+
const done = new Promise((r) => {
|
|
172
|
+
resolveDone = r;
|
|
173
|
+
});
|
|
174
|
+
const end = (reason) => {
|
|
175
|
+
resolveDone(reason);
|
|
176
|
+
try {
|
|
177
|
+
ws.close();
|
|
178
|
+
} catch {
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
ws.on("error", (err) => end(`error: ${err instanceof Error ? err.message : String(err)}`));
|
|
182
|
+
ws.on("close", () => end("closed"));
|
|
183
|
+
ws.on("open", () => {
|
|
184
|
+
ws.send(JSON.stringify({ _tag: "Request", id: 1, tag, payload, headers: [] }));
|
|
185
|
+
});
|
|
186
|
+
ws.on("message", (data) => {
|
|
187
|
+
for (const msg of parseFrames(data)) {
|
|
188
|
+
if (String(msg.requestId) !== "1") continue;
|
|
189
|
+
if (msg._tag === "Chunk") {
|
|
190
|
+
ws.send(JSON.stringify({ _tag: "Ack", requestId: msg.requestId }));
|
|
191
|
+
for (const value of msg.values) onItem(value);
|
|
192
|
+
} else if (msg._tag === "Exit") {
|
|
193
|
+
const exit = msg.exit;
|
|
194
|
+
end(
|
|
195
|
+
exit._tag === "Success" ? "exit" : `failed: ${JSON.stringify(exit.cause).slice(0, 300)}`
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
return {
|
|
201
|
+
done,
|
|
202
|
+
close: () => {
|
|
203
|
+
try {
|
|
204
|
+
ws.send(JSON.stringify({ _tag: "Interrupt", requestId: "1" }));
|
|
205
|
+
} catch {
|
|
206
|
+
}
|
|
207
|
+
end("closed by client");
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
function parseFrames(data) {
|
|
213
|
+
try {
|
|
214
|
+
const raw = JSON.parse(String(data));
|
|
215
|
+
return Array.isArray(raw) ? raw : [raw];
|
|
216
|
+
} catch {
|
|
217
|
+
return [];
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// src/box-tools.ts
|
|
222
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
223
|
+
function parseLaunchArgs(args) {
|
|
224
|
+
const str = (v, max) => typeof v === "string" && v.trim() && v.length <= max ? v.trim() : void 0;
|
|
225
|
+
const work_id = str(args.work_id, 36);
|
|
226
|
+
const title = str(args.title, 200);
|
|
227
|
+
const prompt = str(args.prompt, 1e5);
|
|
228
|
+
if (!work_id || !UUID.test(work_id) || !title || !prompt) throw new BoxToolError("bad_args");
|
|
229
|
+
const runtime_mode = str(args.runtime_mode, 40);
|
|
230
|
+
if (runtime_mode && !RUNTIME_MODES.has(runtime_mode)) throw new BoxToolError("bad_args");
|
|
231
|
+
return {
|
|
232
|
+
work_id,
|
|
233
|
+
title: title.startsWith(CLOOP_THREAD_PREFIX) ? title : `${CLOOP_THREAD_PREFIX} ${title}`,
|
|
234
|
+
prompt,
|
|
235
|
+
repository: str(args.repository, 200),
|
|
236
|
+
harness: str(args.harness, 80),
|
|
237
|
+
model: str(args.model, 120),
|
|
238
|
+
runtime_mode
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
function parseThreadId(args) {
|
|
242
|
+
const id = args.thread_id;
|
|
243
|
+
if (typeof id !== "string" || !id || id.length > 120) throw new BoxToolError("bad_args");
|
|
244
|
+
return id;
|
|
245
|
+
}
|
|
246
|
+
function parseCommandId(args) {
|
|
247
|
+
const id = args.command_id;
|
|
248
|
+
if (typeof id !== "string" || !UUID.test(id)) throw new BoxToolError("bad_args");
|
|
249
|
+
return id;
|
|
250
|
+
}
|
|
251
|
+
function parseSendArgs(args) {
|
|
252
|
+
const text = typeof args.text === "string" ? args.text.trim() : "";
|
|
253
|
+
if (!text || text.length > 8e3) throw new BoxToolError("bad_args");
|
|
254
|
+
const mode = args.mode ?? "steer";
|
|
255
|
+
if (mode !== "steer" && mode !== "queue") throw new BoxToolError("bad_args");
|
|
256
|
+
if (args.answer !== void 0 && typeof args.answer !== "boolean")
|
|
257
|
+
throw new BoxToolError("bad_args");
|
|
258
|
+
const question = args.question_id;
|
|
259
|
+
if (question !== void 0 && question !== null && (typeof question !== "string" || !question || question.length > 1e3))
|
|
260
|
+
throw new BoxToolError("bad_args");
|
|
261
|
+
return {
|
|
262
|
+
thread_id: parseThreadId(args),
|
|
263
|
+
text,
|
|
264
|
+
mode,
|
|
265
|
+
command_id: parseCommandId(args),
|
|
266
|
+
answer: args.answer === true,
|
|
267
|
+
...question !== void 0 ? { question_id: question } : {}
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
var BOX_TOOLS = {
|
|
271
|
+
status: ({ driver }) => driver.status(),
|
|
272
|
+
"threads.list": ({ driver }, args) => driver.listThreads({
|
|
273
|
+
scope: args.scope === "all" ? "all" : "unsettled",
|
|
274
|
+
limit: typeof args.limit === "number" ? Math.min(Math.max(1, args.limit), 50) : 10
|
|
275
|
+
}),
|
|
276
|
+
"thread.read": ({ driver }, args) => driver.readThread(parseThreadId(args)),
|
|
277
|
+
async "thread.launch"({ driver, onLaunch }, args) {
|
|
278
|
+
const a = parseLaunchArgs(args);
|
|
279
|
+
const launched = await driver.launch(a);
|
|
280
|
+
onLaunch?.(a.work_id, launched.thread_id);
|
|
281
|
+
return launched;
|
|
282
|
+
},
|
|
283
|
+
"thread.send": ({ driver }, args) => driver.send(parseSendArgs(args)),
|
|
284
|
+
"thread.interrupt": ({ driver }, args) => driver.interrupt(parseThreadId(args), parseCommandId(args))
|
|
285
|
+
};
|
|
286
|
+
function classifyError(err, driver = "t3") {
|
|
287
|
+
if (err instanceof BoxToolError) return err.code;
|
|
288
|
+
if (driver !== "t3") return "harness_error";
|
|
289
|
+
if (err instanceof T3HttpError)
|
|
290
|
+
return err.status === 401 || err.status === 403 ? "t3_unauthorized" : "t3_error";
|
|
291
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
292
|
+
if (/missing required scope|insufficient_scope/i.test(message)) return "t3_unauthorized";
|
|
293
|
+
if (/ECONNREFUSED|ENOTFOUND|timed out|socket closed|fetch failed/i.test(message))
|
|
294
|
+
return "t3_unreachable";
|
|
295
|
+
return "t3_error";
|
|
296
|
+
}
|
|
297
|
+
async function runBoxTool(ctx, tool, args) {
|
|
298
|
+
const fn = BOX_TOOLS[tool];
|
|
299
|
+
if (!fn) return { ok: false, error: `unknown_tool:${tool}`, detail: "" };
|
|
300
|
+
try {
|
|
301
|
+
return { ok: true, value: await fn(ctx, args) };
|
|
302
|
+
} catch (err) {
|
|
303
|
+
return {
|
|
304
|
+
ok: false,
|
|
305
|
+
error: classifyError(err, ctx.driver.name),
|
|
306
|
+
detail: (err instanceof Error ? err.message : String(err)).slice(0, 400)
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// src/box-watch.ts
|
|
312
|
+
import { randomUUID } from "crypto";
|
|
313
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "fs";
|
|
314
|
+
import { homedir } from "os";
|
|
315
|
+
import { dirname, join } from "path";
|
|
316
|
+
var KEEP_MS = 7 * 24 * 36e5;
|
|
317
|
+
function threadsFilePath() {
|
|
318
|
+
return process.env.CLOOP_BOX_THREADS_FILE ?? join(homedir(), CONFIG_DIR, "box-threads.json");
|
|
319
|
+
}
|
|
320
|
+
function runnerStatePath() {
|
|
321
|
+
return join(dirname(threadsFilePath()), "runner-state.json");
|
|
322
|
+
}
|
|
323
|
+
function writeRunnerState(state, path = runnerStatePath()) {
|
|
324
|
+
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
325
|
+
const tmp = `${path}.tmp`;
|
|
326
|
+
writeFileSync(tmp, `${JSON.stringify(state)}
|
|
327
|
+
`, { mode: 384 });
|
|
328
|
+
renameSync(tmp, path);
|
|
329
|
+
}
|
|
330
|
+
function readRunnerState(path = runnerStatePath()) {
|
|
331
|
+
try {
|
|
332
|
+
const raw = JSON.parse(readFileSync(path, "utf-8"));
|
|
333
|
+
return typeof raw.pid === "number" && typeof raw.connected_at === "string" ? { pid: raw.pid, connected_at: raw.connected_at } : null;
|
|
334
|
+
} catch {
|
|
335
|
+
return null;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
function isAlive(pid) {
|
|
339
|
+
try {
|
|
340
|
+
process.kill(pid, 0);
|
|
341
|
+
return true;
|
|
342
|
+
} catch (err) {
|
|
343
|
+
return err.code === "EPERM";
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
function lockThreadsFile(file, pid = process.pid, alive = isAlive) {
|
|
347
|
+
const lock = `${file}.lock`;
|
|
348
|
+
mkdirSync(dirname(lock), { recursive: true, mode: 448 });
|
|
349
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
350
|
+
try {
|
|
351
|
+
writeFileSync(lock, String(pid), { flag: "wx", mode: 384 });
|
|
352
|
+
return {
|
|
353
|
+
ok: true,
|
|
354
|
+
release: () => {
|
|
355
|
+
try {
|
|
356
|
+
if (readFileSync(lock, "utf-8") === String(pid)) unlinkSync(lock);
|
|
357
|
+
} catch {
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
};
|
|
361
|
+
} catch (err) {
|
|
362
|
+
if (err.code !== "EEXIST") throw err;
|
|
363
|
+
let held = 0;
|
|
364
|
+
try {
|
|
365
|
+
held = Number(readFileSync(lock, "utf-8").trim());
|
|
366
|
+
} catch (readErr) {
|
|
367
|
+
if (readErr.code !== "ENOENT") throw readErr;
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
if (Number.isInteger(held) && held > 0 && held !== pid && alive(held)) {
|
|
371
|
+
return { ok: false, heldBy: held };
|
|
372
|
+
}
|
|
373
|
+
try {
|
|
374
|
+
unlinkSync(lock);
|
|
375
|
+
} catch (unlinkErr) {
|
|
376
|
+
if (unlinkErr.code !== "ENOENT") throw unlinkErr;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return { ok: false, heldBy: -1 };
|
|
381
|
+
}
|
|
382
|
+
var BoxWatch = class {
|
|
383
|
+
constructor(deps) {
|
|
384
|
+
this.deps = deps;
|
|
385
|
+
this.entries = this.load();
|
|
386
|
+
}
|
|
387
|
+
deps;
|
|
388
|
+
entries;
|
|
389
|
+
live = /* @__PURE__ */ new Map();
|
|
390
|
+
stopped = false;
|
|
391
|
+
list() {
|
|
392
|
+
return this.entries;
|
|
393
|
+
}
|
|
394
|
+
start() {
|
|
395
|
+
for (const e of this.entries) if (!e.settled_at) this.watch(e);
|
|
396
|
+
}
|
|
397
|
+
add(workId, threadId) {
|
|
398
|
+
if (this.entries.some((e) => e.work_id === workId)) return;
|
|
399
|
+
const entry = {
|
|
400
|
+
work_id: workId,
|
|
401
|
+
thread_id: threadId,
|
|
402
|
+
launched_at: new Date(this.now()).toISOString()
|
|
403
|
+
};
|
|
404
|
+
this.entries.push(entry);
|
|
405
|
+
this.save();
|
|
406
|
+
this.deps.log(`launch work=${workId} thread=${threadId}`);
|
|
407
|
+
this.watch(entry);
|
|
408
|
+
}
|
|
409
|
+
/** On every socket open and on a timer: send every event the mesh has not acked. */
|
|
410
|
+
flush() {
|
|
411
|
+
for (const e of this.entries) {
|
|
412
|
+
for (const q of e.questions ?? []) if (!q.sent_at) this.trySend(e, q.event);
|
|
413
|
+
if (e.event && !e.sent_at) this.trySend(e, e.event);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
/** `ok` false: the app refused the event for good (unknown work_id, bad frame), so it is not sent again either. */
|
|
417
|
+
ack(eventId, ok = true) {
|
|
418
|
+
for (const e of this.entries) {
|
|
419
|
+
const held = [...e.questions ?? [], e].find((x) => x.event?.id === eventId && !x.sent_at);
|
|
420
|
+
if (!held) continue;
|
|
421
|
+
held.sent_at = new Date(this.now()).toISOString();
|
|
422
|
+
this.save();
|
|
423
|
+
this.deps.log(
|
|
424
|
+
`event ${ok ? "acked" : "refused by the app"} work=${e.work_id} kind=${held.event?.kind}`
|
|
425
|
+
);
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
stop() {
|
|
430
|
+
this.stopped = true;
|
|
431
|
+
for (const unwatch of this.live.values()) unwatch();
|
|
432
|
+
this.live.clear();
|
|
433
|
+
}
|
|
434
|
+
now() {
|
|
435
|
+
return this.deps.now?.() ?? Date.now();
|
|
436
|
+
}
|
|
437
|
+
watch(e) {
|
|
438
|
+
if (this.stopped || e.settled_at || this.live.has(e.work_id)) return;
|
|
439
|
+
const unwatch = this.deps.watch(e.thread_id, (event) => this.onEvent(e, event));
|
|
440
|
+
if (e.settled_at) unwatch();
|
|
441
|
+
else this.live.set(e.work_id, unwatch);
|
|
442
|
+
}
|
|
443
|
+
onEvent(e, event) {
|
|
444
|
+
if (e.settled_at) return;
|
|
445
|
+
if (event.kind === "question") this.ask(e, event.question_id, event.summary);
|
|
446
|
+
else if (event.kind === "progress") this.trySend(e, this.frame(e, event));
|
|
447
|
+
else this.finish(e, event);
|
|
448
|
+
}
|
|
449
|
+
frame(e, event) {
|
|
450
|
+
const { kind, summary } = event;
|
|
451
|
+
return {
|
|
452
|
+
type: "event",
|
|
453
|
+
id: randomUUID(),
|
|
454
|
+
work_id: e.work_id,
|
|
455
|
+
thread_id: e.thread_id,
|
|
456
|
+
kind,
|
|
457
|
+
...event.kind === "question" ? { question_id: event.question_id } : {},
|
|
458
|
+
...summary ? { summary: summary.slice(0, 500) } : {},
|
|
459
|
+
..."pr_url" in event && event.pr_url ? { pr_url: event.pr_url } : {},
|
|
460
|
+
..."error" in event && event.error ? { error: event.error } : {},
|
|
461
|
+
at: new Date(this.now()).toISOString()
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
ask(e, questionId, summary) {
|
|
465
|
+
if (e.questions?.some((x) => x.event.question_id === questionId)) return;
|
|
466
|
+
const event = this.frame(e, { kind: "question", question_id: questionId, summary });
|
|
467
|
+
e.questions = [...e.questions ?? [], { event }];
|
|
468
|
+
this.save();
|
|
469
|
+
this.deps.log(`question work=${e.work_id} thread=${e.thread_id}`);
|
|
470
|
+
this.trySend(e, event);
|
|
471
|
+
}
|
|
472
|
+
finish(e, end) {
|
|
473
|
+
this.live.get(e.work_id)?.();
|
|
474
|
+
this.live.delete(e.work_id);
|
|
475
|
+
e.event = this.frame(e, end);
|
|
476
|
+
e.settled_at = e.event.at;
|
|
477
|
+
this.save();
|
|
478
|
+
this.deps.log(
|
|
479
|
+
`settle work=${e.work_id} thread=${e.thread_id} kind=${end.kind} pr=${end.pr_url ? "yes" : "no"}`
|
|
480
|
+
);
|
|
481
|
+
this.trySend(e, e.event);
|
|
482
|
+
}
|
|
483
|
+
trySend(e, event) {
|
|
484
|
+
const sent = this.deps.send(event);
|
|
485
|
+
this.deps.log(
|
|
486
|
+
`event ${sent ? "sent" : "held"} work=${e.work_id} kind=${event.kind}${sent ? "" : "; socket down"}`
|
|
487
|
+
);
|
|
488
|
+
}
|
|
489
|
+
load() {
|
|
490
|
+
let raw;
|
|
491
|
+
try {
|
|
492
|
+
raw = JSON.parse(readFileSync(this.deps.file, "utf-8"));
|
|
493
|
+
} catch {
|
|
494
|
+
return [];
|
|
495
|
+
}
|
|
496
|
+
if (!Array.isArray(raw)) return [];
|
|
497
|
+
const cutoff = this.now() - KEEP_MS;
|
|
498
|
+
return raw.filter(
|
|
499
|
+
(e) => typeof e?.work_id === "string" && typeof e?.thread_id === "string" && !(e.settled_at && Date.parse(e.settled_at) < cutoff)
|
|
500
|
+
);
|
|
501
|
+
}
|
|
502
|
+
save() {
|
|
503
|
+
mkdirSync(dirname(this.deps.file), { recursive: true, mode: 448 });
|
|
504
|
+
const tmp = `${this.deps.file}.tmp`;
|
|
505
|
+
writeFileSync(tmp, `${JSON.stringify(this.entries, null, 2)}
|
|
506
|
+
`, { mode: 384 });
|
|
507
|
+
chmodSync(tmp, 384);
|
|
508
|
+
renameSync(tmp, this.deps.file);
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
|
|
512
|
+
// src/device-revoke.ts
|
|
513
|
+
function tokenGone(revoke) {
|
|
514
|
+
return revoke === "revoked" || revoke === "already_revoked" || revoke === "no_device";
|
|
515
|
+
}
|
|
516
|
+
async function revokeOwnDevice(origin, deviceToken, fetchFn = fetch) {
|
|
517
|
+
if (!deviceToken) return "no_device";
|
|
518
|
+
try {
|
|
519
|
+
const res = await fetchFn(`${origin}/api/agent/mesh/device-revoke`, {
|
|
520
|
+
method: "POST",
|
|
521
|
+
headers: { authorization: `Bearer ${deviceToken}` },
|
|
522
|
+
signal: AbortSignal.timeout(1e4)
|
|
523
|
+
});
|
|
524
|
+
const body = await res.json().catch(() => null);
|
|
525
|
+
if (res.ok && body?.outcome === "revoked") return "revoked";
|
|
526
|
+
if (res.ok && body?.outcome === "already_revoked") return "already_revoked";
|
|
527
|
+
if (res.status === 401 && body?.error === "unknown_device") return "unknown_device";
|
|
528
|
+
return "failed";
|
|
529
|
+
} catch {
|
|
530
|
+
return "failed";
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// src/drivers/claude-code.ts
|
|
535
|
+
import { execFile as execFile3 } from "child_process";
|
|
536
|
+
import { basename as basename2, isAbsolute, relative, resolve } from "path";
|
|
537
|
+
|
|
538
|
+
// src/drivers/local.ts
|
|
539
|
+
import { execFile as execFile2, execFileSync as execFileSync3, spawn } from "child_process";
|
|
540
|
+
import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
541
|
+
import { homedir as homedir2, hostname } from "os";
|
|
542
|
+
import { basename, dirname as dirname2, join as join3 } from "path";
|
|
543
|
+
import { createInterface } from "readline";
|
|
544
|
+
|
|
545
|
+
// src/drivers/t3.ts
|
|
546
|
+
import { execFile, execFileSync as execFileSync2 } from "child_process";
|
|
547
|
+
|
|
548
|
+
// src/t3-bin.ts
|
|
549
|
+
import { execFileSync } from "child_process";
|
|
550
|
+
import { existsSync, readdirSync, statSync } from "fs";
|
|
551
|
+
import { join as join2 } from "path";
|
|
552
|
+
var CLEAN_ENV = () => ({
|
|
553
|
+
HOME: process.env.HOME,
|
|
554
|
+
USER: process.env.USER,
|
|
555
|
+
PATH: process.env.PATH
|
|
556
|
+
});
|
|
557
|
+
function defaultT3BinSources(home, stored) {
|
|
558
|
+
return {
|
|
559
|
+
env: process.env,
|
|
560
|
+
home,
|
|
561
|
+
appDirs: process.platform === "darwin" ? ["/Applications", join2(home, "Applications")] : [],
|
|
562
|
+
onPath: () => whichAll("t3"),
|
|
563
|
+
...stored ? { stored } : {}
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
function isExecutable(path) {
|
|
567
|
+
try {
|
|
568
|
+
const s = statSync(path);
|
|
569
|
+
return s.isFile() && (s.mode & 73) !== 0;
|
|
570
|
+
} catch {
|
|
571
|
+
return false;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
function bundleBinaries(appDir) {
|
|
575
|
+
let bundles;
|
|
576
|
+
try {
|
|
577
|
+
bundles = readdirSync(appDir).filter((name) => /^T3 Code.*\.app$/.test(name));
|
|
578
|
+
} catch {
|
|
579
|
+
return [];
|
|
580
|
+
}
|
|
581
|
+
return bundles.flatMap((bundle) => {
|
|
582
|
+
const root = join2(appDir, bundle);
|
|
583
|
+
try {
|
|
584
|
+
return readdirSync(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) => join2(root, rel)).filter(isExecutable);
|
|
585
|
+
} catch {
|
|
586
|
+
return [];
|
|
587
|
+
}
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
function t3Candidates(serverVersion, sources) {
|
|
591
|
+
const ordered = [
|
|
592
|
+
sources.env.T3_BIN,
|
|
593
|
+
join2(sources.home, ".t3", "runtime", "versions", serverVersion, "t3"),
|
|
594
|
+
...sources.appDirs.flatMap(bundleBinaries),
|
|
595
|
+
...sources.onPath(),
|
|
596
|
+
sources.stored
|
|
597
|
+
];
|
|
598
|
+
return [...new Set(ordered.filter((p) => Boolean(p) && existsSync(p)))];
|
|
599
|
+
}
|
|
600
|
+
function parseT3Version(output) {
|
|
601
|
+
return output.trim().split(/\s+/).at(-1)?.replace(/^v/, "") || null;
|
|
602
|
+
}
|
|
603
|
+
function t3Version(bin) {
|
|
604
|
+
try {
|
|
605
|
+
return parseT3Version(runT3(bin, ["--version"], 1e4));
|
|
606
|
+
} catch {
|
|
607
|
+
return null;
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
function pickT3Bin(candidates, serverVersion, versionOf = t3Version) {
|
|
611
|
+
return candidates.find((bin) => versionOf(bin) === serverVersion) ?? candidates[0] ?? null;
|
|
612
|
+
}
|
|
613
|
+
function t3BaseDirArgs(env = process.env) {
|
|
614
|
+
return env.T3CODE_HOME ? ["--base-dir", env.T3CODE_HOME] : [];
|
|
615
|
+
}
|
|
616
|
+
function runT3(bin, args, timeout = 15e3) {
|
|
617
|
+
try {
|
|
618
|
+
return execFileSync(bin, args, {
|
|
619
|
+
encoding: "utf-8",
|
|
620
|
+
env: CLEAN_ENV(),
|
|
621
|
+
timeout,
|
|
622
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
623
|
+
});
|
|
624
|
+
} catch (err) {
|
|
625
|
+
const stderr = String(err.stderr ?? "").trim().split("\n").filter((line2) => line2 && !/ExperimentalWarning|--trace-warnings/.test(line2)).at(-1);
|
|
626
|
+
throw new Error(
|
|
627
|
+
`t3 ${args.slice(0, 3).join(" ")} failed${stderr ? `: ${stderr.slice(0, 200)}` : ""}`
|
|
628
|
+
);
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
function whichAll(bin) {
|
|
632
|
+
try {
|
|
633
|
+
return execFileSync("which", ["-a", bin], {
|
|
634
|
+
encoding: "utf-8",
|
|
635
|
+
env: CLEAN_ENV(),
|
|
636
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
637
|
+
}).split("\n").map((line2) => line2.trim()).filter(Boolean);
|
|
638
|
+
} catch {
|
|
639
|
+
return [];
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
// src/drivers/t3.ts
|
|
644
|
+
function isUnsettled(t) {
|
|
645
|
+
return !t.settledAt && !t.archivedAt && !isChild(t);
|
|
646
|
+
}
|
|
647
|
+
function isChild(t) {
|
|
648
|
+
return t.creationSource === "provider" || Boolean(t.lineage?.parentThreadId);
|
|
649
|
+
}
|
|
650
|
+
var SESSIONS_TTL_MS = 5 * 6e4;
|
|
651
|
+
var TERMINAL_RUN = /* @__PURE__ */ new Set(["completed", "interrupted", "failed", "cancelled", "rolled_back"]);
|
|
652
|
+
var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master"]);
|
|
653
|
+
function pendingQuestions(p) {
|
|
654
|
+
const asked = /* @__PURE__ */ new Map();
|
|
655
|
+
for (const item of p.turnItems ?? []) {
|
|
656
|
+
if (item.type === "user_input_request" && item.requestId && item.questions?.length)
|
|
657
|
+
asked.set(item.requestId, item.questions);
|
|
658
|
+
}
|
|
659
|
+
return (p.runtimeRequests ?? []).filter((r) => r.kind === "user_input" && r.status === "pending" && asked.has(r.id)).sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? "")).map((r) => ({ request_id: r.id, questions: asked.get(r.id) ?? [] }));
|
|
660
|
+
}
|
|
661
|
+
function questionText(q) {
|
|
662
|
+
return questionLine(q.questions);
|
|
663
|
+
}
|
|
664
|
+
function latestRun(runs) {
|
|
665
|
+
return runs.reduce(
|
|
666
|
+
(latest, r) => !latest || (r.ordinal ?? 0) >= (latest.ordinal ?? 0) ? r : latest,
|
|
667
|
+
null
|
|
668
|
+
);
|
|
669
|
+
}
|
|
670
|
+
function isTerminal(runs) {
|
|
671
|
+
const run2 = latestRun(runs);
|
|
672
|
+
return Boolean(run2 && TERMINAL_RUN.has(run2.status));
|
|
673
|
+
}
|
|
674
|
+
function activeRun(runs) {
|
|
675
|
+
const run2 = latestRun(runs);
|
|
676
|
+
return run2 && !TERMINAL_RUN.has(run2.status) ? run2 : null;
|
|
677
|
+
}
|
|
678
|
+
function steerableRun(p) {
|
|
679
|
+
const run2 = activeRun(p.runs ?? []);
|
|
680
|
+
if (!run2) return null;
|
|
681
|
+
const attempts = new Set((p.attempts ?? []).filter((a) => a.runId === run2.id).map((a) => a.id));
|
|
682
|
+
const turning = (p.providerTurns ?? []).some(
|
|
683
|
+
(t) => t.status === "running" && t.runAttemptId !== null && attempts.has(t.runAttemptId)
|
|
684
|
+
);
|
|
685
|
+
return turning ? run2 : null;
|
|
686
|
+
}
|
|
687
|
+
var STEER_WAIT_MS = 8e3;
|
|
688
|
+
var STEER_POLL_MS = 500;
|
|
689
|
+
function prUrlOf(thread) {
|
|
690
|
+
const branch = thread.branch ?? null;
|
|
691
|
+
const linked = thread.pullRequests ?? [];
|
|
692
|
+
const own = branch ? linked.filter((pr) => pr.snapshot?.headBranch === branch) : [];
|
|
693
|
+
const fromLinked = (own.at(-1) ?? linked.at(-1))?.url ?? thread.linkedPullRequest?.url;
|
|
694
|
+
if (fromLinked) return fromLinked;
|
|
695
|
+
if (branch && !SHARED_BRANCHES.has(branch)) return thread.branchPullRequest?.url ?? null;
|
|
696
|
+
return null;
|
|
697
|
+
}
|
|
698
|
+
function outcomeOf(p) {
|
|
699
|
+
const run2 = latestRun(p.runs ?? []);
|
|
700
|
+
const status = run2?.status ?? "pending";
|
|
701
|
+
const settled = TERMINAL_RUN.has(status) || Boolean(p.thread.settledAt);
|
|
702
|
+
const text = (p.messages ?? []).filter((m) => m.role === "assistant" && m.text).at(-1)?.text?.trim();
|
|
703
|
+
return {
|
|
704
|
+
status,
|
|
705
|
+
settled,
|
|
706
|
+
kind: settled ? status === "completed" || !run2 ? "settled" : "failed" : null,
|
|
707
|
+
pr_url: prUrlOf(p.thread),
|
|
708
|
+
last_assistant_text: text ? text.slice(0, 300) : null
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
function pickProject(projects, repository) {
|
|
712
|
+
const only = projects.length === 1 ? projects[0] : void 0;
|
|
713
|
+
if (!repository) {
|
|
714
|
+
if (only) return only;
|
|
715
|
+
throw new BoxToolError("no_project");
|
|
716
|
+
}
|
|
717
|
+
const want = repository.toLowerCase();
|
|
718
|
+
const found = projects.find(
|
|
719
|
+
(p) => p.title.toLowerCase() === want || p.workspaceRoot.split("/").at(-1)?.toLowerCase() === want || p.repositoryIdentity?.displayName?.toLowerCase() === want
|
|
720
|
+
);
|
|
721
|
+
if (!found) throw new BoxToolError("no_project");
|
|
722
|
+
return found;
|
|
723
|
+
}
|
|
724
|
+
var SHELL_HEADERS = { "x-t3-orchestration-protocol": "2" };
|
|
725
|
+
function boxCapabilities(scope) {
|
|
726
|
+
const scopes = (scope ?? "").split(/\s+/).filter(Boolean);
|
|
727
|
+
return scopes.includes("orchestration:operate") ? ["view", "start", "steer"] : ["view"];
|
|
728
|
+
}
|
|
729
|
+
function threadView(t) {
|
|
730
|
+
return {
|
|
731
|
+
id: t.id,
|
|
732
|
+
title: t.title,
|
|
733
|
+
status: t.status,
|
|
734
|
+
branch: t.branch ?? null,
|
|
735
|
+
source: t.creationSource ?? null,
|
|
736
|
+
cloop: (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX),
|
|
737
|
+
settled: Boolean(t.settledAt),
|
|
738
|
+
updatedAt: t.updatedAt
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
function orderThreads(threads, limit) {
|
|
742
|
+
const byRecency = (a, b) => b.updatedAt.localeCompare(a.updatedAt);
|
|
743
|
+
const running = threads.filter((t) => t.status === "running").sort(byRecency);
|
|
744
|
+
const rest = threads.filter((t) => t.status !== "running").sort(byRecency);
|
|
745
|
+
return [...running, ...rest].slice(0, limit);
|
|
746
|
+
}
|
|
747
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
748
|
+
var T3Driver = class {
|
|
749
|
+
constructor(deps) {
|
|
750
|
+
this.deps = deps;
|
|
751
|
+
}
|
|
752
|
+
deps;
|
|
753
|
+
name = "t3";
|
|
754
|
+
get capabilities() {
|
|
755
|
+
return boxCapabilities(this.deps.scope?.());
|
|
756
|
+
}
|
|
757
|
+
get t3() {
|
|
758
|
+
return this.deps.client();
|
|
759
|
+
}
|
|
760
|
+
log(line2) {
|
|
761
|
+
this.deps.log?.(line2);
|
|
762
|
+
}
|
|
763
|
+
async status() {
|
|
764
|
+
const [cfg, shell] = await Promise.all([
|
|
765
|
+
this.t3.rpc("server.getConfig", {}),
|
|
766
|
+
this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
|
|
767
|
+
]);
|
|
768
|
+
const sessions = this.listSessions();
|
|
769
|
+
const threads = (shell.threads ?? []).filter((t) => !isChild(t));
|
|
770
|
+
const unsettled = threads.filter(isUnsettled);
|
|
771
|
+
return {
|
|
772
|
+
box: {
|
|
773
|
+
label: cfg.environment.label,
|
|
774
|
+
driver: "t3",
|
|
775
|
+
t3Version: cfg.environment.serverVersion,
|
|
776
|
+
protocol: cfg.environment.orchestrationProtocolVersion,
|
|
777
|
+
hosts: (cfg.remoteOpenTargets ?? []).map((t) => t.host)
|
|
778
|
+
},
|
|
779
|
+
harnesses: cfg.providers.filter((p) => p.enabled).map((p) => ({
|
|
780
|
+
id: p.instanceId,
|
|
781
|
+
name: p.displayName ?? p.instanceId,
|
|
782
|
+
version: p.version,
|
|
783
|
+
ready: p.status === "ready",
|
|
784
|
+
signedIn: p.auth?.status === "authenticated",
|
|
785
|
+
account: p.auth?.label ?? null,
|
|
786
|
+
defaultModel: p.models?.find((m) => m.isDefault)?.slug ?? null
|
|
787
|
+
})),
|
|
788
|
+
clients: sessions?.filter((s) => s.client?.deviceType !== "bot").map((s) => ({
|
|
789
|
+
label: s.client?.label ?? "unknown",
|
|
790
|
+
connected: s.connected === true,
|
|
791
|
+
lastConnectedAt: s.lastConnectedAt ?? null
|
|
792
|
+
})) ?? null,
|
|
793
|
+
projects: (shell.projects ?? []).map((p) => p.title),
|
|
794
|
+
threads: {
|
|
795
|
+
unsettled: unsettled.length,
|
|
796
|
+
running: unsettled.filter((t) => t.status === "running").length,
|
|
797
|
+
settled: threads.length - unsettled.length,
|
|
798
|
+
cloop: unsettled.filter((t) => (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX)).length
|
|
799
|
+
}
|
|
800
|
+
};
|
|
801
|
+
}
|
|
802
|
+
async listThreads({
|
|
803
|
+
scope,
|
|
804
|
+
limit
|
|
805
|
+
}) {
|
|
806
|
+
const shell = await this.t3.http("/api/orchestration/shell", SHELL_HEADERS);
|
|
807
|
+
const all = (shell.threads ?? []).filter((t) => !isChild(t));
|
|
808
|
+
const threads = scope === "all" ? all : all.filter(isUnsettled);
|
|
809
|
+
return {
|
|
810
|
+
scope,
|
|
811
|
+
unsettled: all.filter(isUnsettled).length,
|
|
812
|
+
settled: all.length - all.filter(isUnsettled).length,
|
|
813
|
+
running: threads.filter((t) => t.status === "running").length,
|
|
814
|
+
threads: orderThreads(threads, limit).map(threadView)
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
/**
|
|
818
|
+
* `work_id` is T3's `commandId`, so a second launch of the same work returns
|
|
819
|
+
* the same thread with `resumed: true` and runs nothing twice. The worktree
|
|
820
|
+
* starts from origin's copy of the branch the project's checkout is on.
|
|
821
|
+
*/
|
|
822
|
+
async launch(a) {
|
|
823
|
+
const known = this.deps.watched?.({ work_id: a.work_id });
|
|
824
|
+
if (known) return { thread_id: known.thread_id, resumed: true };
|
|
825
|
+
const [cfg, shell] = await Promise.all([
|
|
826
|
+
this.t3.rpc("server.getConfig", {}),
|
|
827
|
+
this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
|
|
828
|
+
]);
|
|
829
|
+
const project = pickProject(shell.projects ?? [], a.repository);
|
|
830
|
+
const fallback = cfg.settings?.defaultModelSelection;
|
|
831
|
+
const harness = a.harness ?? fallback?.instanceId ?? "claudeAgent";
|
|
832
|
+
const provider = cfg.providers.find((p) => p.instanceId === harness && p.enabled);
|
|
833
|
+
if (!provider) throw new BoxToolError("harness_unavailable");
|
|
834
|
+
if (provider.auth && provider.auth.status !== "authenticated")
|
|
835
|
+
throw new BoxToolError("harness_signed_out");
|
|
836
|
+
const model = a.model ?? (fallback?.instanceId === harness ? fallback.model : void 0) ?? provider.models?.find((m) => m.isDefault)?.slug;
|
|
837
|
+
if (!model) throw new BoxToolError("harness_unavailable");
|
|
838
|
+
const modelSelection = !a.model && fallback?.instanceId === harness ? fallback : { instanceId: harness, model };
|
|
839
|
+
const runtimeMode = a.runtime_mode ?? cfg.settings?.defaultRuntimeMode;
|
|
840
|
+
if (!runtimeMode || !RUNTIME_MODES.has(runtimeMode))
|
|
841
|
+
throw new BoxToolError("runtime_mode_unknown");
|
|
842
|
+
const launched = await this.t3.rpc(
|
|
843
|
+
"orchestration.launchThread",
|
|
844
|
+
{
|
|
845
|
+
commandId: a.work_id,
|
|
846
|
+
creationSource: "mcp",
|
|
847
|
+
projectId: project.id,
|
|
848
|
+
title: a.title,
|
|
849
|
+
modelSelection,
|
|
850
|
+
runtimeMode,
|
|
851
|
+
interactionMode: "default",
|
|
852
|
+
workspaceStrategy: {
|
|
853
|
+
type: "worktree",
|
|
854
|
+
baseRef: this.baseRefFor(project.workspaceRoot)
|
|
855
|
+
},
|
|
856
|
+
initialMessage: { text: a.prompt, attachments: [] }
|
|
857
|
+
}
|
|
858
|
+
);
|
|
859
|
+
return { thread_id: launched.threadId, resumed: launched.resumed };
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* Say something to a thread. While the thread waits on a question, only
|
|
863
|
+
* `answer: true` sends anything: the text answers every question in the
|
|
864
|
+
* newest request, because a steer does not resolve a pending question and
|
|
865
|
+
* the run would wait on. Without it the call sends nothing and returns the
|
|
866
|
+
* question, so the owner says which they meant. Otherwise `steer`
|
|
867
|
+
* joins the running turn, waiting up to 8 s for a starting run's provider
|
|
868
|
+
* turn. A run that still cannot take a steer, or `queue`, gets the text
|
|
869
|
+
* after it ends; a thread with nothing running starts a new turn.
|
|
870
|
+
* `command_id` is T3's commandId, so a retried call sends once.
|
|
871
|
+
*/
|
|
872
|
+
async send(a) {
|
|
873
|
+
let p = await this.readProjection(a.thread_id);
|
|
874
|
+
const pending = pendingQuestions(p);
|
|
875
|
+
const question = pending.at(-1);
|
|
876
|
+
if (a.answer && a.question_id !== void 0 && question?.request_id !== a.question_id) {
|
|
877
|
+
return {
|
|
878
|
+
delivered: "question_changed",
|
|
879
|
+
question: question ? questionText(question) : null,
|
|
880
|
+
question_id: question?.request_id ?? null
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
if (question && !a.answer) {
|
|
884
|
+
return {
|
|
885
|
+
delivered: "question_pending",
|
|
886
|
+
question: questionText(question),
|
|
887
|
+
questions: pending.length
|
|
888
|
+
};
|
|
889
|
+
}
|
|
890
|
+
if (question) {
|
|
891
|
+
const receipt2 = await this.dispatch({
|
|
892
|
+
type: "runtime-request.respond",
|
|
893
|
+
commandId: a.command_id,
|
|
894
|
+
threadId: a.thread_id,
|
|
895
|
+
requestId: question.request_id,
|
|
896
|
+
answers: Object.fromEntries(question.questions.map((q) => [q.id, a.text]))
|
|
897
|
+
});
|
|
898
|
+
return { sequence: receipt2.sequence, delivered: "answer", question_id: question.request_id };
|
|
899
|
+
}
|
|
900
|
+
if (a.mode === "steer") {
|
|
901
|
+
for (let waited = 0; waited < STEER_WAIT_MS; waited += STEER_POLL_MS) {
|
|
902
|
+
if (!activeRun(p.runs ?? []) || steerableRun(p)) break;
|
|
903
|
+
await sleep(STEER_POLL_MS);
|
|
904
|
+
p = await this.readProjection(a.thread_id);
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
const steer = a.mode === "steer" ? steerableRun(p) : null;
|
|
908
|
+
const active = activeRun(p.runs ?? []);
|
|
909
|
+
if (!active && this.deps.watched?.({ thread_id: a.thread_id })?.settled)
|
|
910
|
+
throw new BoxToolError("already_finished");
|
|
911
|
+
const receipt = await this.dispatch({
|
|
912
|
+
type: "message.dispatch",
|
|
913
|
+
commandId: a.command_id,
|
|
914
|
+
threadId: a.thread_id,
|
|
915
|
+
messageId: a.command_id,
|
|
916
|
+
text: a.text,
|
|
917
|
+
attachments: [],
|
|
918
|
+
dispatchMode: steer ? { type: "steer_active", targetRunId: steer.id } : active ? { type: "queue_after_active" } : { type: "start_immediately" },
|
|
919
|
+
createdBy: "user",
|
|
920
|
+
creationSource: "mcp"
|
|
921
|
+
});
|
|
922
|
+
return { sequence: receipt.sequence, delivered: steer ? "steer" : active ? "queue" : "start" };
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* Stop the running turn. A thread with nothing running answers
|
|
926
|
+
* `was_running: false`, and so does a run that ended while the interrupt
|
|
927
|
+
* was on its way: T3 refuses that interrupt, and the owner's ask is met.
|
|
928
|
+
*/
|
|
929
|
+
async interrupt(threadId, commandId) {
|
|
930
|
+
const run2 = activeRun((await this.readProjection(threadId)).runs ?? []);
|
|
931
|
+
if (!run2) return { ok: true, was_running: false };
|
|
932
|
+
try {
|
|
933
|
+
await this.dispatch({
|
|
934
|
+
type: "run.interrupt",
|
|
935
|
+
commandId,
|
|
936
|
+
threadId,
|
|
937
|
+
runId: run2.id,
|
|
938
|
+
reason: "Stopped from Cloop"
|
|
939
|
+
});
|
|
940
|
+
} catch (err) {
|
|
941
|
+
if (activeRun((await this.readProjection(threadId)).runs ?? [])) throw err;
|
|
942
|
+
return { ok: true, was_running: false };
|
|
943
|
+
}
|
|
944
|
+
return { ok: true, was_running: true };
|
|
945
|
+
}
|
|
946
|
+
async readThread(id) {
|
|
947
|
+
const { status, settled, pr_url, last_assistant_text } = outcomeOf(
|
|
948
|
+
await this.readProjection(id)
|
|
949
|
+
);
|
|
950
|
+
return { status, settled, pr_url, last_assistant_text };
|
|
951
|
+
}
|
|
952
|
+
/**
|
|
953
|
+
* Subscribe to the thread and resubscribe whenever the stream ends. A thread
|
|
954
|
+
* that settled while nobody watched shows a terminal run in its first
|
|
955
|
+
* snapshot. A question is reported on every update it is still pending.
|
|
956
|
+
*/
|
|
957
|
+
watch(threadId, onEvent) {
|
|
958
|
+
let stopped = false;
|
|
959
|
+
let finishing = false;
|
|
960
|
+
let live = null;
|
|
961
|
+
const retry = () => {
|
|
962
|
+
if (stopped) return;
|
|
963
|
+
const timer = setTimeout(() => void follow(), this.deps.retryMs ?? 1e4);
|
|
964
|
+
timer.unref?.();
|
|
965
|
+
};
|
|
966
|
+
const finish = async () => {
|
|
967
|
+
if (stopped || finishing) return;
|
|
968
|
+
finishing = true;
|
|
969
|
+
let outcome;
|
|
970
|
+
try {
|
|
971
|
+
outcome = outcomeOf(await this.readProjection(threadId));
|
|
972
|
+
const grace = this.deps.prGraceMs ?? 6e4;
|
|
973
|
+
if (outcome.settled && outcome.kind === "settled" && !outcome.pr_url && grace > 0) {
|
|
974
|
+
await sleep(grace);
|
|
975
|
+
outcome = outcomeOf(await this.readProjection(threadId));
|
|
976
|
+
}
|
|
977
|
+
} catch (err) {
|
|
978
|
+
this.log(
|
|
979
|
+
`read failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
|
|
980
|
+
);
|
|
981
|
+
finishing = false;
|
|
982
|
+
retry();
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
if (stopped) return;
|
|
986
|
+
if (!outcome.settled) {
|
|
987
|
+
finishing = false;
|
|
988
|
+
this.log(`run continues thread=${threadId} run=${outcome.status}; watching on`);
|
|
989
|
+
if (!live) void follow();
|
|
990
|
+
return;
|
|
991
|
+
}
|
|
992
|
+
stopped = true;
|
|
993
|
+
live?.close();
|
|
994
|
+
const pr = outcome.pr_url ? { pr_url: outcome.pr_url } : {};
|
|
995
|
+
if (outcome.kind === "failed") {
|
|
996
|
+
onEvent({ kind: "failed", summary: `The run ended ${outcome.status}.`, ...pr });
|
|
997
|
+
} else {
|
|
998
|
+
onEvent({
|
|
999
|
+
kind: "settled",
|
|
1000
|
+
...outcome.last_assistant_text ? { summary: outcome.last_assistant_text } : {},
|
|
1001
|
+
...pr
|
|
1002
|
+
});
|
|
1003
|
+
}
|
|
1004
|
+
};
|
|
1005
|
+
const follow = async () => {
|
|
1006
|
+
if (stopped || live) return;
|
|
1007
|
+
const runs = /* @__PURE__ */ new Map();
|
|
1008
|
+
const requests = /* @__PURE__ */ new Map();
|
|
1009
|
+
const asks = /* @__PURE__ */ new Map();
|
|
1010
|
+
const keepAsk = (item) => {
|
|
1011
|
+
if (item.type === "user_input_request" && item.requestId) asks.set(item.requestId, item);
|
|
1012
|
+
};
|
|
1013
|
+
let settledByHand = false;
|
|
1014
|
+
let stream;
|
|
1015
|
+
try {
|
|
1016
|
+
stream = await this.t3.stream("orchestration.subscribeThread", { threadId }, (raw) => {
|
|
1017
|
+
const item = raw;
|
|
1018
|
+
if (item.kind === "snapshot" && "projection" in item) {
|
|
1019
|
+
for (const r of item.projection.runs ?? []) runs.set(r.id, r);
|
|
1020
|
+
for (const r of item.projection.runtimeRequests ?? []) requests.set(r.id, r);
|
|
1021
|
+
for (const t of item.projection.turnItems ?? []) keepAsk(t);
|
|
1022
|
+
settledByHand ||= Boolean(item.projection.thread?.settledAt);
|
|
1023
|
+
} else if (item.kind === "event" && "event" in item) {
|
|
1024
|
+
const { type, payload } = item.event;
|
|
1025
|
+
if (type.startsWith("run.") && typeof payload?.id === "string") {
|
|
1026
|
+
runs.set(payload.id, payload);
|
|
1027
|
+
} else if (type === "runtime-request.updated" && typeof payload?.id === "string") {
|
|
1028
|
+
requests.set(payload.id, payload);
|
|
1029
|
+
} else if (type === "turn-item.updated" && payload) {
|
|
1030
|
+
keepAsk(payload);
|
|
1031
|
+
} else if (type.startsWith("thread.") && payload?.settledAt) {
|
|
1032
|
+
settledByHand = true;
|
|
1033
|
+
} else return;
|
|
1034
|
+
} else return;
|
|
1035
|
+
if (settledByHand || isTerminal([...runs.values()])) {
|
|
1036
|
+
void finish();
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
const pending = pendingQuestions({
|
|
1040
|
+
runtimeRequests: [...requests.values()],
|
|
1041
|
+
turnItems: [...asks.values()]
|
|
1042
|
+
});
|
|
1043
|
+
for (const q of pending) {
|
|
1044
|
+
onEvent({ kind: "question", question_id: q.request_id, summary: questionText(q) });
|
|
1045
|
+
}
|
|
1046
|
+
});
|
|
1047
|
+
} catch (err) {
|
|
1048
|
+
this.log(
|
|
1049
|
+
`watch failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
|
|
1050
|
+
);
|
|
1051
|
+
retry();
|
|
1052
|
+
return;
|
|
1053
|
+
}
|
|
1054
|
+
if (stopped) {
|
|
1055
|
+
stream.close();
|
|
1056
|
+
return;
|
|
1057
|
+
}
|
|
1058
|
+
live = stream;
|
|
1059
|
+
const reason = await stream.done;
|
|
1060
|
+
live = null;
|
|
1061
|
+
if (stopped || finishing) return;
|
|
1062
|
+
this.log(`watch ended thread=${threadId} reason=${reason}; resubscribing`);
|
|
1063
|
+
retry();
|
|
1064
|
+
};
|
|
1065
|
+
void follow();
|
|
1066
|
+
return () => {
|
|
1067
|
+
stopped = true;
|
|
1068
|
+
live?.close();
|
|
1069
|
+
};
|
|
1070
|
+
}
|
|
1071
|
+
readProjection(threadId) {
|
|
1072
|
+
return this.t3.rpc("orchestration.getThreadProjection", { threadId });
|
|
1073
|
+
}
|
|
1074
|
+
dispatch(command) {
|
|
1075
|
+
return this.t3.rpc("orchestration.dispatchCommand", command);
|
|
1076
|
+
}
|
|
1077
|
+
sessions = {
|
|
1078
|
+
list: null,
|
|
1079
|
+
at: 0,
|
|
1080
|
+
refreshing: false
|
|
1081
|
+
};
|
|
1082
|
+
/**
|
|
1083
|
+
* T3's client sessions, from the cache. `t3 auth session list` starts a whole
|
|
1084
|
+
* CLI and took 5 to 14 s on a loaded box, so status never waits on it: it
|
|
1085
|
+
* answers with the last list and refreshes it in the background at most
|
|
1086
|
+
* once per SESSIONS_TTL_MS.
|
|
1087
|
+
*/
|
|
1088
|
+
listSessions() {
|
|
1089
|
+
const bin = this.deps.t3Bin;
|
|
1090
|
+
if (!bin) return null;
|
|
1091
|
+
const stale = Date.now() - this.sessions.at > SESSIONS_TTL_MS;
|
|
1092
|
+
if (stale && !this.sessions.refreshing) {
|
|
1093
|
+
this.sessions.refreshing = true;
|
|
1094
|
+
const done = (raw) => {
|
|
1095
|
+
try {
|
|
1096
|
+
if (raw !== null) this.sessions.list = JSON.parse(raw);
|
|
1097
|
+
} catch {
|
|
1098
|
+
}
|
|
1099
|
+
this.sessions.at = Date.now();
|
|
1100
|
+
this.sessions.refreshing = false;
|
|
1101
|
+
};
|
|
1102
|
+
(this.deps.execAsync ?? execFile)(
|
|
1103
|
+
bin,
|
|
1104
|
+
["auth", "session", "list", ...t3BaseDirArgs(), "--json"],
|
|
1105
|
+
{
|
|
1106
|
+
encoding: "utf-8",
|
|
1107
|
+
env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
|
|
1108
|
+
timeout: 3e4
|
|
1109
|
+
},
|
|
1110
|
+
(err, stdout) => done(err ? null : String(stdout))
|
|
1111
|
+
);
|
|
1112
|
+
}
|
|
1113
|
+
return this.sessions.list;
|
|
1114
|
+
}
|
|
1115
|
+
/**
|
|
1116
|
+
* The branch the project's checkout is on, from origin when origin has it. A
|
|
1117
|
+
* local branch can lag origin by hundreds of commits on a box nobody pulls on,
|
|
1118
|
+
* and T3 starts the worktree from the ref exactly as given.
|
|
1119
|
+
*/
|
|
1120
|
+
baseRefFor(root) {
|
|
1121
|
+
const git = (args) => String(
|
|
1122
|
+
(this.deps.exec ?? execFileSync2)("git", ["-C", root, ...args], {
|
|
1123
|
+
encoding: "utf-8",
|
|
1124
|
+
env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
|
|
1125
|
+
timeout: 5e3
|
|
1126
|
+
})
|
|
1127
|
+
).trim();
|
|
1128
|
+
let branch;
|
|
1129
|
+
try {
|
|
1130
|
+
branch = git(["rev-parse", "--abbrev-ref", "HEAD"]);
|
|
1131
|
+
} catch {
|
|
1132
|
+
return "HEAD";
|
|
1133
|
+
}
|
|
1134
|
+
if (!branch || branch === "HEAD") return "HEAD";
|
|
1135
|
+
try {
|
|
1136
|
+
git(["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}`]);
|
|
1137
|
+
return `origin/${branch}`;
|
|
1138
|
+
} catch {
|
|
1139
|
+
return branch;
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
};
|
|
1143
|
+
|
|
1144
|
+
// src/drivers/local.ts
|
|
1145
|
+
var CONTINUE_PROMPT = "Continue the work from where you stopped. If it is already done, say so in one sentence.";
|
|
1146
|
+
var PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
|
|
1147
|
+
var SHARED_BRANCHES2 = /* @__PURE__ */ new Set(["staging", "main", "master", "HEAD"]);
|
|
1148
|
+
var COMMANDS_KEPT = 50;
|
|
1149
|
+
var SUMMARY_MAX = 200;
|
|
1150
|
+
var HARNESS_NAMES = { "claude-code": "Claude Code", codex: "Codex" };
|
|
1151
|
+
var HARNESS_LIMIT = /usage limit|reached your [\w .-]{0,40}limit|hit your [\w .-]{0,40}limit|out of (usage )?credits/i;
|
|
1152
|
+
function failedEnd(harness, run2) {
|
|
1153
|
+
const said = run2.result?.text?.trim() || run2.lastText;
|
|
1154
|
+
const limited = HARNESS_LIMIT.test(run2.result?.text ?? "");
|
|
1155
|
+
const words = said?.replace(/\s+/g, " ").trim();
|
|
1156
|
+
const error = limited ? { error: "harness_limit" } : {};
|
|
1157
|
+
const opening = run2.switched ? `${run2.switched} ` : "";
|
|
1158
|
+
if (!words)
|
|
1159
|
+
return {
|
|
1160
|
+
summary: `${opening}${run2.result ? "The run ended with an error." : `The run exited with ${run2.exit}.`}`,
|
|
1161
|
+
...error
|
|
1162
|
+
};
|
|
1163
|
+
const lead = `${opening}${HARNESS_NAMES[harness] ?? harness} said: "`;
|
|
1164
|
+
const room = SUMMARY_MAX - lead.length - 1;
|
|
1165
|
+
const quoted = words.length > room ? `${words.slice(0, room - 1)}\u2026` : words;
|
|
1166
|
+
return { summary: `${lead}${quoted}"`, ...error };
|
|
1167
|
+
}
|
|
1168
|
+
var PERMISSION_MODES = {
|
|
1169
|
+
"approval-required": "default",
|
|
1170
|
+
"auto-accept-edits": "acceptEdits",
|
|
1171
|
+
auto: "auto",
|
|
1172
|
+
"full-access": "bypassPermissions"
|
|
1173
|
+
};
|
|
1174
|
+
function permissionMode(mode) {
|
|
1175
|
+
return PERMISSION_MODES[mode ?? "auto-accept-edits"];
|
|
1176
|
+
}
|
|
1177
|
+
function localRunsFilePath() {
|
|
1178
|
+
return process.env.CLOOP_LOCAL_RUNS_FILE ?? join3(homedir2(), CONFIG_DIR, "local-runs.json");
|
|
1179
|
+
}
|
|
1180
|
+
function pickRepo(repos, repository) {
|
|
1181
|
+
if (!repository) {
|
|
1182
|
+
if (repos.length === 1 && repos[0]) return repos[0];
|
|
1183
|
+
throw new BoxToolError("no_project");
|
|
1184
|
+
}
|
|
1185
|
+
const want = repository.toLowerCase().split("/").at(-1) ?? "";
|
|
1186
|
+
const found = repos.find(
|
|
1187
|
+
(r) => r.label.toLowerCase() === want || basename(r.path).toLowerCase() === want
|
|
1188
|
+
);
|
|
1189
|
+
if (!found) throw new BoxToolError("no_project");
|
|
1190
|
+
return found;
|
|
1191
|
+
}
|
|
1192
|
+
function prUrlIn(text) {
|
|
1193
|
+
return text?.match(PR_URL)?.at(-1) ?? null;
|
|
1194
|
+
}
|
|
1195
|
+
function run(cmd, args, cwd) {
|
|
1196
|
+
return new Promise(
|
|
1197
|
+
(resolve3, reject) => execFile2(
|
|
1198
|
+
cmd,
|
|
1199
|
+
args,
|
|
1200
|
+
{ cwd, timeout: 1e4, encoding: "utf-8" },
|
|
1201
|
+
(err, out2) => err ? reject(err) : resolve3(String(out2).trim())
|
|
1202
|
+
)
|
|
1203
|
+
);
|
|
1204
|
+
}
|
|
1205
|
+
var gitProbe = {
|
|
1206
|
+
head: (repo) => run("git", ["rev-parse", "HEAD"], repo).catch(() => null),
|
|
1207
|
+
pushed: (repo) => run("git", ["branch", "-r", "--contains", "HEAD"], repo).then(
|
|
1208
|
+
(out2) => out2.length > 0,
|
|
1209
|
+
() => false
|
|
1210
|
+
),
|
|
1211
|
+
async branchPr(repo) {
|
|
1212
|
+
try {
|
|
1213
|
+
const branch = await run("git", ["rev-parse", "--abbrev-ref", "HEAD"], repo);
|
|
1214
|
+
if (SHARED_BRANCHES2.has(branch)) return null;
|
|
1215
|
+
return prUrlIn(await run("gh", ["pr", "view", "--json", "url", "-q", ".url"], repo));
|
|
1216
|
+
} catch {
|
|
1217
|
+
return null;
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
};
|
|
1221
|
+
function harnessAlive(pid, r, dialect) {
|
|
1222
|
+
try {
|
|
1223
|
+
process.kill(pid, 0);
|
|
1224
|
+
} catch (err) {
|
|
1225
|
+
if (err.code !== "EPERM") return false;
|
|
1226
|
+
}
|
|
1227
|
+
try {
|
|
1228
|
+
const command = execFileSync3("ps", ["-ww", "-o", "command=", "-p", String(pid)], {
|
|
1229
|
+
encoding: "utf-8",
|
|
1230
|
+
timeout: 2e3
|
|
1231
|
+
});
|
|
1232
|
+
return dialect.owns(r, command);
|
|
1233
|
+
} catch {
|
|
1234
|
+
return false;
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
var KEEP_MS2 = 7 * 24 * 36e5;
|
|
1238
|
+
var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
1239
|
+
var LocalDriver = class {
|
|
1240
|
+
constructor(deps) {
|
|
1241
|
+
this.deps = deps;
|
|
1242
|
+
this.name = deps.dialect.name;
|
|
1243
|
+
this.capabilities = deps.dialect.capabilities;
|
|
1244
|
+
this.runs = new Map(this.load().map((r) => [r.work_id, r]));
|
|
1245
|
+
}
|
|
1246
|
+
deps;
|
|
1247
|
+
name;
|
|
1248
|
+
capabilities;
|
|
1249
|
+
runs;
|
|
1250
|
+
lives = /* @__PURE__ */ new Map();
|
|
1251
|
+
listeners = /* @__PURE__ */ new Map();
|
|
1252
|
+
recovering = /* @__PURE__ */ new Set();
|
|
1253
|
+
stopping = false;
|
|
1254
|
+
get repo() {
|
|
1255
|
+
return this.deps.repo ?? gitProbe;
|
|
1256
|
+
}
|
|
1257
|
+
get file() {
|
|
1258
|
+
return this.deps.file ?? localRunsFilePath();
|
|
1259
|
+
}
|
|
1260
|
+
log(line2) {
|
|
1261
|
+
this.deps.log?.(line2);
|
|
1262
|
+
}
|
|
1263
|
+
now() {
|
|
1264
|
+
return this.deps.now?.() ?? Date.now();
|
|
1265
|
+
}
|
|
1266
|
+
async status() {
|
|
1267
|
+
const harnesses = this.deps.harnesses ? await this.deps.harnesses() : [await this.deps.dialect.probe()].filter((h) => h !== null);
|
|
1268
|
+
const all = [...this.runs.values()];
|
|
1269
|
+
const unsettled = all.filter((r) => !r.end);
|
|
1270
|
+
return {
|
|
1271
|
+
box: { label: this.deps.label ?? hostname(), driver: this.name },
|
|
1272
|
+
harnesses,
|
|
1273
|
+
clients: null,
|
|
1274
|
+
projects: this.deps.repos.map((r) => r.label),
|
|
1275
|
+
threads: {
|
|
1276
|
+
unsettled: unsettled.length,
|
|
1277
|
+
running: unsettled.filter((r) => this.lives.has(r.work_id)).length,
|
|
1278
|
+
settled: all.length - unsettled.length,
|
|
1279
|
+
cloop: unsettled.length
|
|
1280
|
+
}
|
|
1281
|
+
};
|
|
1282
|
+
}
|
|
1283
|
+
async listThreads({
|
|
1284
|
+
scope,
|
|
1285
|
+
limit
|
|
1286
|
+
}) {
|
|
1287
|
+
const all = [...this.runs.values()];
|
|
1288
|
+
const unsettled = all.filter((r) => !r.end);
|
|
1289
|
+
const shown = (scope === "all" ? all : unsettled).map((r) => ({
|
|
1290
|
+
id: r.work_id,
|
|
1291
|
+
title: r.title,
|
|
1292
|
+
status: this.statusOf(r),
|
|
1293
|
+
branch: null,
|
|
1294
|
+
source: "cloop",
|
|
1295
|
+
cloop: true,
|
|
1296
|
+
settled: Boolean(r.end),
|
|
1297
|
+
updatedAt: r.end?.at ?? r.started_at
|
|
1298
|
+
}));
|
|
1299
|
+
return {
|
|
1300
|
+
scope,
|
|
1301
|
+
unsettled: unsettled.length,
|
|
1302
|
+
settled: all.length - unsettled.length,
|
|
1303
|
+
running: shown.filter((t) => t.status === "running").length,
|
|
1304
|
+
threads: orderThreads(shown, limit)
|
|
1305
|
+
};
|
|
1306
|
+
}
|
|
1307
|
+
async readThread(id) {
|
|
1308
|
+
const r = this.record(id);
|
|
1309
|
+
return {
|
|
1310
|
+
status: this.statusOf(r),
|
|
1311
|
+
settled: Boolean(r.end),
|
|
1312
|
+
pr_url: r.end?.pr_url ?? null,
|
|
1313
|
+
last_assistant_text: r.end?.summary ?? r.last_text ?? null
|
|
1314
|
+
};
|
|
1315
|
+
}
|
|
1316
|
+
async launch(a) {
|
|
1317
|
+
if (this.runs.has(a.work_id)) return { thread_id: a.work_id, resumed: true };
|
|
1318
|
+
const { dialect } = this.deps;
|
|
1319
|
+
if (a.harness && !dialect.aliases.includes(a.harness))
|
|
1320
|
+
throw new BoxToolError("harness_unavailable");
|
|
1321
|
+
const repo = pickRepo(this.deps.repos, a.repository);
|
|
1322
|
+
this.refuseBusy(repo.path);
|
|
1323
|
+
const harness = await dialect.probe();
|
|
1324
|
+
if (!harness) throw new BoxToolError("harness_unavailable");
|
|
1325
|
+
if (!harness.signedIn) throw new BoxToolError("harness_signed_out");
|
|
1326
|
+
const head = await this.repo.head(repo.path);
|
|
1327
|
+
if (this.runs.has(a.work_id)) return { thread_id: a.work_id, resumed: true };
|
|
1328
|
+
this.refuseBusy(repo.path);
|
|
1329
|
+
const record = {
|
|
1330
|
+
work_id: a.work_id,
|
|
1331
|
+
session_id: dialect.name === "claude-code" ? a.work_id : null,
|
|
1332
|
+
repo: repo.path,
|
|
1333
|
+
title: a.title,
|
|
1334
|
+
...a.model ? { model: a.model } : {},
|
|
1335
|
+
...a.runtime_mode ? { runtime_mode: a.runtime_mode } : {},
|
|
1336
|
+
pid: null,
|
|
1337
|
+
started_at: new Date(this.now()).toISOString(),
|
|
1338
|
+
head_at_launch: head
|
|
1339
|
+
};
|
|
1340
|
+
this.runs.set(a.work_id, record);
|
|
1341
|
+
this.spawnRun(record, a.prompt, false);
|
|
1342
|
+
return { thread_id: a.work_id, resumed: false };
|
|
1343
|
+
}
|
|
1344
|
+
async send(a) {
|
|
1345
|
+
const r = this.record(a.thread_id);
|
|
1346
|
+
const seen = r.commands?.find(([id]) => id === a.command_id);
|
|
1347
|
+
if (seen) return { delivered: seen[1] };
|
|
1348
|
+
const live = this.lives.get(r.work_id);
|
|
1349
|
+
const ask = live?.asks[0];
|
|
1350
|
+
if (a.answer && (!ask || ask.request_id !== a.question_id)) {
|
|
1351
|
+
this.log(`question_changed work=${r.work_id}`);
|
|
1352
|
+
return {
|
|
1353
|
+
delivered: "question_changed",
|
|
1354
|
+
question: ask?.summary ?? null,
|
|
1355
|
+
question_id: ask?.request_id ?? null
|
|
1356
|
+
};
|
|
1357
|
+
}
|
|
1358
|
+
if (live && ask) {
|
|
1359
|
+
if (!a.answer) {
|
|
1360
|
+
return {
|
|
1361
|
+
delivered: "question_pending",
|
|
1362
|
+
question: ask.summary,
|
|
1363
|
+
questions: live.asks.length
|
|
1364
|
+
};
|
|
1365
|
+
}
|
|
1366
|
+
const line3 = this.deps.dialect.answerLine?.(ask, a.text);
|
|
1367
|
+
if (!line3) throw new BoxToolError("cannot_steer");
|
|
1368
|
+
live.asks = live.asks.slice(1);
|
|
1369
|
+
this.write(live, line3);
|
|
1370
|
+
this.remember(r, a.command_id, "answer");
|
|
1371
|
+
this.log(`answer work=${r.work_id}`);
|
|
1372
|
+
this.askNext(r, live);
|
|
1373
|
+
return { delivered: "answer", question_id: ask.request_id };
|
|
1374
|
+
}
|
|
1375
|
+
if (!live) {
|
|
1376
|
+
if (r.end) throw new BoxToolError("already_finished");
|
|
1377
|
+
this.spawnRun(r, a.text, true);
|
|
1378
|
+
this.remember(r, a.command_id, "start");
|
|
1379
|
+
return { delivered: "start" };
|
|
1380
|
+
}
|
|
1381
|
+
if (live.child.stdin?.writableEnded) {
|
|
1382
|
+
live.next = live.next ? `${live.next}
|
|
1383
|
+
|
|
1384
|
+
${a.text}` : a.text;
|
|
1385
|
+
this.remember(r, a.command_id, "queue");
|
|
1386
|
+
return { delivered: "queue" };
|
|
1387
|
+
}
|
|
1388
|
+
const line2 = this.deps.dialect.userLine?.(r, a.text, a.mode);
|
|
1389
|
+
if (!line2) throw new BoxToolError("cannot_steer");
|
|
1390
|
+
live.outstanding++;
|
|
1391
|
+
this.write(live, line2);
|
|
1392
|
+
const delivered = a.mode === "queue" ? "queue" : "steer";
|
|
1393
|
+
this.remember(r, a.command_id, delivered);
|
|
1394
|
+
this.log(`${delivered} work=${r.work_id}`);
|
|
1395
|
+
return { delivered };
|
|
1396
|
+
}
|
|
1397
|
+
async interrupt(id) {
|
|
1398
|
+
const r = this.record(id);
|
|
1399
|
+
const live = this.lives.get(r.work_id);
|
|
1400
|
+
if (!live) {
|
|
1401
|
+
if (r.end) return { ok: true, was_running: false };
|
|
1402
|
+
const orphan = r.pid !== null && this.alive(r.pid, r);
|
|
1403
|
+
if (orphan && r.pid !== null) {
|
|
1404
|
+
try {
|
|
1405
|
+
process.kill(r.pid, "SIGINT");
|
|
1406
|
+
} catch {
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
await this.end(r, { kind: "failed", summary: "The run was stopped." });
|
|
1410
|
+
return { ok: true, was_running: orphan };
|
|
1411
|
+
}
|
|
1412
|
+
live.interrupted = true;
|
|
1413
|
+
live.child.kill("SIGINT");
|
|
1414
|
+
const timer = setTimeout(() => {
|
|
1415
|
+
if (live.child.exitCode === null && live.child.signalCode === null)
|
|
1416
|
+
live.child.kill("SIGTERM");
|
|
1417
|
+
}, this.deps.interruptGraceMs ?? 1e4);
|
|
1418
|
+
timer.unref();
|
|
1419
|
+
this.log(`interrupt work=${r.work_id}`);
|
|
1420
|
+
return { ok: true, was_running: true };
|
|
1421
|
+
}
|
|
1422
|
+
watch(id, onEvent) {
|
|
1423
|
+
const set = this.listeners.get(id) ?? /* @__PURE__ */ new Set();
|
|
1424
|
+
set.add(onEvent);
|
|
1425
|
+
this.listeners.set(id, set);
|
|
1426
|
+
const r = this.runs.get(id);
|
|
1427
|
+
const unwatch = () => set.delete(onEvent);
|
|
1428
|
+
if (!r) {
|
|
1429
|
+
onEvent({ kind: "failed", summary: "This run is not on the runner any more." });
|
|
1430
|
+
return unwatch;
|
|
1431
|
+
}
|
|
1432
|
+
if (r.end) {
|
|
1433
|
+
const { at: _at, ...end } = r.end;
|
|
1434
|
+
onEvent(end);
|
|
1435
|
+
return unwatch;
|
|
1436
|
+
}
|
|
1437
|
+
const live = this.lives.get(id);
|
|
1438
|
+
const ask = live?.asks[0];
|
|
1439
|
+
if (ask) onEvent({ kind: "question", question_id: ask.request_id, summary: ask.summary });
|
|
1440
|
+
if (!live) void this.recover(r);
|
|
1441
|
+
return unwatch;
|
|
1442
|
+
}
|
|
1443
|
+
/** On a daemon stop: end every process, and leave its run open so the next start resumes it. */
|
|
1444
|
+
stop() {
|
|
1445
|
+
this.stopping = true;
|
|
1446
|
+
for (const live of this.lives.values()) live.child.kill("SIGTERM");
|
|
1447
|
+
}
|
|
1448
|
+
alive(pid, r) {
|
|
1449
|
+
return this.deps.alive ? this.deps.alive(pid, r) : harnessAlive(pid, r, this.deps.dialect);
|
|
1450
|
+
}
|
|
1451
|
+
/** One checkout, one run: two harnesses editing the same files at once would undo each other. */
|
|
1452
|
+
refuseBusy(repo) {
|
|
1453
|
+
if ([...this.runs.values()].some((r) => r.repo === repo && !r.end))
|
|
1454
|
+
throw new BoxToolError("repo_busy");
|
|
1455
|
+
}
|
|
1456
|
+
/** One question at a time, oldest first, so a yes answers the prompt the owner read. */
|
|
1457
|
+
askNext(r, live) {
|
|
1458
|
+
const next = live.asks[0];
|
|
1459
|
+
if (!next) return;
|
|
1460
|
+
this.log(`question work=${r.work_id} tool=${next.tool}`);
|
|
1461
|
+
this.emit(r.work_id, { kind: "question", question_id: next.request_id, summary: next.summary });
|
|
1462
|
+
}
|
|
1463
|
+
/** A run left open by a daemon that died: wait for its old process to go, then resume it once. */
|
|
1464
|
+
async recover(r) {
|
|
1465
|
+
if (this.recovering.has(r.work_id)) return;
|
|
1466
|
+
this.recovering.add(r.work_id);
|
|
1467
|
+
try {
|
|
1468
|
+
while (r.pid !== null && this.alive(r.pid, r) && !r.end && !this.stopping) {
|
|
1469
|
+
await sleep2(this.deps.orphanPollMs ?? 2e3);
|
|
1470
|
+
}
|
|
1471
|
+
if (r.end || this.stopping || this.lives.has(r.work_id)) return;
|
|
1472
|
+
this.log(`resume work=${r.work_id} after a restart`);
|
|
1473
|
+
this.spawnRun(r, CONTINUE_PROMPT, true);
|
|
1474
|
+
} finally {
|
|
1475
|
+
this.recovering.delete(r.work_id);
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
spawnRun(r, prompt, resume) {
|
|
1479
|
+
const { dialect } = this.deps;
|
|
1480
|
+
const child = spawn(dialect.bin, dialect.args(r, resume), {
|
|
1481
|
+
cwd: r.repo,
|
|
1482
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
1483
|
+
env: process.env
|
|
1484
|
+
});
|
|
1485
|
+
const live = {
|
|
1486
|
+
child,
|
|
1487
|
+
outstanding: 1,
|
|
1488
|
+
asks: [],
|
|
1489
|
+
lastProgressAt: 0,
|
|
1490
|
+
interrupted: false,
|
|
1491
|
+
stderr: ""
|
|
1492
|
+
};
|
|
1493
|
+
this.lives.set(r.work_id, live);
|
|
1494
|
+
r.pid = child.pid ?? null;
|
|
1495
|
+
this.save();
|
|
1496
|
+
this.log(`spawn work=${r.work_id} pid=${r.pid ?? "none"} ${resume ? "resume" : "new"}`);
|
|
1497
|
+
child.stdin?.on("error", () => {
|
|
1498
|
+
});
|
|
1499
|
+
child.stdin?.write(dialect.opening(r, prompt));
|
|
1500
|
+
if (!dialect.keepsStdin) child.stdin?.end();
|
|
1501
|
+
child.stderr?.on("data", (chunk) => {
|
|
1502
|
+
live.stderr = (live.stderr + chunk.toString("utf-8")).slice(-2e3);
|
|
1503
|
+
});
|
|
1504
|
+
const lines = createInterface({ input: child.stdout });
|
|
1505
|
+
lines.on("line", (line2) => {
|
|
1506
|
+
for (const item of dialect.parse(line2, r)) this.onItem(r, live, item);
|
|
1507
|
+
});
|
|
1508
|
+
child.on("error", (err) => {
|
|
1509
|
+
this.log(`spawn failed work=${r.work_id}: ${err.message.slice(0, 200)}`);
|
|
1510
|
+
});
|
|
1511
|
+
child.on("close", (code, signal) => void this.onExit(r, live, code, signal));
|
|
1512
|
+
}
|
|
1513
|
+
onItem(r, live, item) {
|
|
1514
|
+
switch (item.type) {
|
|
1515
|
+
case "session":
|
|
1516
|
+
if (r.session_id !== item.id) {
|
|
1517
|
+
r.session_id = item.id;
|
|
1518
|
+
this.save();
|
|
1519
|
+
}
|
|
1520
|
+
return;
|
|
1521
|
+
case "text":
|
|
1522
|
+
r.last_text = item.text.slice(0, 300);
|
|
1523
|
+
this.progress(r, live, item.text, false);
|
|
1524
|
+
return;
|
|
1525
|
+
case "tool": {
|
|
1526
|
+
const changed = item.name !== live.lastTool;
|
|
1527
|
+
live.lastTool = item.name;
|
|
1528
|
+
this.progress(r, live, item.target ? `${item.name} ${item.target}` : item.name, changed);
|
|
1529
|
+
return;
|
|
1530
|
+
}
|
|
1531
|
+
case "ask":
|
|
1532
|
+
live.asks.push(item);
|
|
1533
|
+
if (live.asks.length === 1) this.askNext(r, live);
|
|
1534
|
+
return;
|
|
1535
|
+
case "cancel": {
|
|
1536
|
+
const wasAsked = live.asks[0]?.request_id === item.request_id;
|
|
1537
|
+
live.asks = live.asks.filter((x) => x.request_id !== item.request_id);
|
|
1538
|
+
if (wasAsked) this.askNext(r, live);
|
|
1539
|
+
return;
|
|
1540
|
+
}
|
|
1541
|
+
case "result":
|
|
1542
|
+
live.outstanding--;
|
|
1543
|
+
live.result = { ok: item.ok, ...item.text ? { text: item.text } : {} };
|
|
1544
|
+
if (item.text) r.last_text = item.text.slice(0, 300);
|
|
1545
|
+
if (live.outstanding <= 0 && live.asks.length === 0) live.child.stdin?.end();
|
|
1546
|
+
return;
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
progress(r, live, line2, force) {
|
|
1550
|
+
const now = this.now();
|
|
1551
|
+
if (!force && now - live.lastProgressAt < (this.deps.progressMs ?? 3e4)) return;
|
|
1552
|
+
live.lastProgressAt = now;
|
|
1553
|
+
this.emit(r.work_id, {
|
|
1554
|
+
kind: "progress",
|
|
1555
|
+
summary: line2.replace(/\s+/g, " ").trim().slice(0, 200)
|
|
1556
|
+
});
|
|
1557
|
+
}
|
|
1558
|
+
async onExit(r, live, code, signal) {
|
|
1559
|
+
if (this.lives.get(r.work_id) === live) this.lives.delete(r.work_id);
|
|
1560
|
+
if (this.stopping || r.end) return;
|
|
1561
|
+
const exit = signal ? `signal ${signal}` : `code ${code}`;
|
|
1562
|
+
this.log(
|
|
1563
|
+
`exit work=${r.work_id} ${exit} result=${live.result ? live.result.ok ? "ok" : "error" : "none"}`
|
|
1564
|
+
);
|
|
1565
|
+
if (live.interrupted) {
|
|
1566
|
+
await this.end(r, { kind: "failed", summary: "The run was stopped." });
|
|
1567
|
+
return;
|
|
1568
|
+
}
|
|
1569
|
+
if (live.next) {
|
|
1570
|
+
this.spawnRun(r, live.next, true);
|
|
1571
|
+
return;
|
|
1572
|
+
}
|
|
1573
|
+
if (code === 0 && live.result?.ok) {
|
|
1574
|
+
const text = live.result.text?.trim() || r.last_text;
|
|
1575
|
+
const { pr, note } = await this.outcome(r, text);
|
|
1576
|
+
const summary = [r.switched, note, text].filter(Boolean).join(" ").replace(/\s+/g, " ");
|
|
1577
|
+
await this.end(r, {
|
|
1578
|
+
kind: "settled",
|
|
1579
|
+
...summary ? { summary: summary.slice(0, SUMMARY_MAX) } : {},
|
|
1580
|
+
...pr ? { pr_url: pr } : {}
|
|
1581
|
+
});
|
|
1582
|
+
return;
|
|
1583
|
+
}
|
|
1584
|
+
if (live.stderr)
|
|
1585
|
+
this.log(`stderr work=${r.work_id}: ${live.stderr.trim().split("\n").at(-1)?.slice(0, 200)}`);
|
|
1586
|
+
const end = failedEnd(this.name, {
|
|
1587
|
+
result: live.result,
|
|
1588
|
+
lastText: r.last_text,
|
|
1589
|
+
exit,
|
|
1590
|
+
...r.switched ? { switched: r.switched } : {}
|
|
1591
|
+
});
|
|
1592
|
+
if (end.error) this.log(`limit work=${r.work_id} error=${end.error}`);
|
|
1593
|
+
if (end.error === "harness_limit" && this.fallBack(r, live.result?.text)) return;
|
|
1594
|
+
await this.end(r, { kind: "failed", ...end });
|
|
1595
|
+
}
|
|
1596
|
+
/**
|
|
1597
|
+
* Once per run: a run stopped by its model's usage limit resumes its own
|
|
1598
|
+
* session on the first fallback model, with the continue prompt, so its
|
|
1599
|
+
* steers, answers and edits carry over. It does not when the Task named its
|
|
1600
|
+
* model, when the limit is the fallback model's own, or after one switch.
|
|
1601
|
+
* `--fallback-model` may already cover this; it is not documented whether a
|
|
1602
|
+
* plan's limit counts. The switch opens the end summary, because a progress
|
|
1603
|
+
* line is dropped while the socket is down.
|
|
1604
|
+
*/
|
|
1605
|
+
fallBack(r, said) {
|
|
1606
|
+
const model = this.deps.dialect.fallback?.split(",")[0]?.trim();
|
|
1607
|
+
if (!model || !r.session_id || r.switched || r.model) return false;
|
|
1608
|
+
const named = new RegExp(`\\b${model.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i");
|
|
1609
|
+
if (named.test(said ?? "")) return false;
|
|
1610
|
+
const from = /reached your ([\w .-]{1,40}?) limit/i.exec(said ?? "")?.[1] ?? "The default model";
|
|
1611
|
+
const to = `${model.charAt(0).toUpperCase()}${model.slice(1)}`;
|
|
1612
|
+
r.switched = `${from} was at its usage limit, so this ran on ${to}.`;
|
|
1613
|
+
r.model = model;
|
|
1614
|
+
this.save();
|
|
1615
|
+
this.log(`fallback work=${r.work_id} model=${model}`);
|
|
1616
|
+
this.emit(r.work_id, {
|
|
1617
|
+
kind: "progress",
|
|
1618
|
+
summary: `${from} is at its usage limit, so I switched to ${to}`
|
|
1619
|
+
});
|
|
1620
|
+
this.spawnRun(r, CONTINUE_PROMPT, true);
|
|
1621
|
+
return true;
|
|
1622
|
+
}
|
|
1623
|
+
/**
|
|
1624
|
+
* The PR a run produced: one its last text names, else the PR of the
|
|
1625
|
+
* branch, but only when the run moved HEAD. A run that left HEAD where it
|
|
1626
|
+
* started produced nothing, and the branch's PR belongs to someone else's
|
|
1627
|
+
* work. A run that committed without pushing says so.
|
|
1628
|
+
*/
|
|
1629
|
+
async outcome(r, text) {
|
|
1630
|
+
const named = prUrlIn(text);
|
|
1631
|
+
if (named) return { pr: named };
|
|
1632
|
+
if (!r.head_at_launch) return { pr: null };
|
|
1633
|
+
const head = await this.repo.head(r.repo);
|
|
1634
|
+
if (!head || head === r.head_at_launch) return { pr: null };
|
|
1635
|
+
const pr = await this.repo.branchPr(r.repo);
|
|
1636
|
+
if (pr) return { pr };
|
|
1637
|
+
return await this.repo.pushed(r.repo) ? { pr: null } : { pr: null, note: `Committed ${head.slice(0, 7)}, not pushed.` };
|
|
1638
|
+
}
|
|
1639
|
+
async end(r, end) {
|
|
1640
|
+
if (r.end) return;
|
|
1641
|
+
r.end = { ...end, at: new Date(this.now()).toISOString() };
|
|
1642
|
+
r.pid = null;
|
|
1643
|
+
this.save();
|
|
1644
|
+
this.emit(r.work_id, end);
|
|
1645
|
+
}
|
|
1646
|
+
emit(id, event) {
|
|
1647
|
+
for (const listener of [...this.listeners.get(id) ?? []]) listener(event);
|
|
1648
|
+
}
|
|
1649
|
+
write(live, line2) {
|
|
1650
|
+
live.child.stdin?.write(line2);
|
|
1651
|
+
}
|
|
1652
|
+
remember(r, commandId, delivered) {
|
|
1653
|
+
r.commands = [
|
|
1654
|
+
...r.commands ?? [],
|
|
1655
|
+
[commandId, delivered]
|
|
1656
|
+
].slice(-COMMANDS_KEPT);
|
|
1657
|
+
this.save();
|
|
1658
|
+
}
|
|
1659
|
+
record(id) {
|
|
1660
|
+
const r = this.runs.get(id);
|
|
1661
|
+
if (!r) throw new BoxToolError("bad_args");
|
|
1662
|
+
return r;
|
|
1663
|
+
}
|
|
1664
|
+
statusOf(r) {
|
|
1665
|
+
if (this.lives.has(r.work_id)) return "running";
|
|
1666
|
+
if (!r.end) return "pending";
|
|
1667
|
+
return r.end.kind === "settled" ? "completed" : "failed";
|
|
1668
|
+
}
|
|
1669
|
+
load() {
|
|
1670
|
+
try {
|
|
1671
|
+
const raw = JSON.parse(readFileSync2(this.file, "utf-8"));
|
|
1672
|
+
const cutoff = this.now() - KEEP_MS2;
|
|
1673
|
+
return Array.isArray(raw) ? raw.filter(
|
|
1674
|
+
(r) => typeof r?.work_id === "string" && typeof r?.repo === "string" && !(r.end && Date.parse(r.end.at) < cutoff)
|
|
1675
|
+
) : [];
|
|
1676
|
+
} catch {
|
|
1677
|
+
return [];
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
save() {
|
|
1681
|
+
mkdirSync2(dirname2(this.file), { recursive: true, mode: 448 });
|
|
1682
|
+
const tmp = `${this.file}.tmp`;
|
|
1683
|
+
writeFileSync2(tmp, `${JSON.stringify([...this.runs.values()], null, 2)}
|
|
1684
|
+
`, { mode: 384 });
|
|
1685
|
+
chmodSync2(tmp, 384);
|
|
1686
|
+
renameSync2(tmp, this.file);
|
|
1687
|
+
}
|
|
1688
|
+
};
|
|
1689
|
+
|
|
1690
|
+
// src/drivers/claude-code.ts
|
|
1691
|
+
var SUBSCRIPTIONS = {
|
|
1692
|
+
max: "Claude Max",
|
|
1693
|
+
pro: "Claude Pro",
|
|
1694
|
+
team: "Claude Team",
|
|
1695
|
+
enterprise: "Claude Enterprise"
|
|
1696
|
+
};
|
|
1697
|
+
var YES_WORDS = /* @__PURE__ */ new Set([
|
|
1698
|
+
"y",
|
|
1699
|
+
"yes",
|
|
1700
|
+
"yep",
|
|
1701
|
+
"yeah",
|
|
1702
|
+
"allow",
|
|
1703
|
+
"allow it",
|
|
1704
|
+
"ok",
|
|
1705
|
+
"okay",
|
|
1706
|
+
"approve",
|
|
1707
|
+
"approved",
|
|
1708
|
+
"go ahead",
|
|
1709
|
+
"sure",
|
|
1710
|
+
"do it"
|
|
1711
|
+
]);
|
|
1712
|
+
function isYes(reply) {
|
|
1713
|
+
return YES_WORDS.has(
|
|
1714
|
+
reply.trim().toLowerCase().replace(/[.!\s]+$/, "")
|
|
1715
|
+
);
|
|
1716
|
+
}
|
|
1717
|
+
function exec(bin, args) {
|
|
1718
|
+
return new Promise(
|
|
1719
|
+
(resolve3) => execFile3(
|
|
1720
|
+
bin,
|
|
1721
|
+
args,
|
|
1722
|
+
{ timeout: 1e4, encoding: "utf-8" },
|
|
1723
|
+
(err, out2) => resolve3(err ? null : String(out2))
|
|
1724
|
+
)
|
|
1725
|
+
);
|
|
1726
|
+
}
|
|
1727
|
+
function claudeAccount(raw) {
|
|
1728
|
+
try {
|
|
1729
|
+
const auth = JSON.parse(raw ?? "");
|
|
1730
|
+
if (auth.loggedIn !== true) return { signedIn: false, account: null };
|
|
1731
|
+
const plan = auth.subscriptionType ? SUBSCRIPTIONS[auth.subscriptionType] : void 0;
|
|
1732
|
+
return {
|
|
1733
|
+
signedIn: true,
|
|
1734
|
+
account: plan ?? (auth.authMethod === "claude.ai" ? "Claude" : "API key")
|
|
1735
|
+
};
|
|
1736
|
+
} catch {
|
|
1737
|
+
return { signedIn: false, account: null };
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
async function probeClaude(bin = "claude") {
|
|
1741
|
+
const version = (await exec(bin, ["--version"]))?.trim().split(/\s+/)[0];
|
|
1742
|
+
if (!version) return null;
|
|
1743
|
+
const { signedIn, account } = claudeAccount(await exec(bin, ["auth", "status", "--json"]));
|
|
1744
|
+
return {
|
|
1745
|
+
id: "claude-code",
|
|
1746
|
+
name: "Claude Code",
|
|
1747
|
+
version,
|
|
1748
|
+
ready: signedIn,
|
|
1749
|
+
signedIn,
|
|
1750
|
+
account,
|
|
1751
|
+
defaultModel: null
|
|
1752
|
+
};
|
|
1753
|
+
}
|
|
1754
|
+
function pathOf(input) {
|
|
1755
|
+
const fields = input ?? {};
|
|
1756
|
+
const path = fields.file_path ?? fields.notebook_path ?? fields.path;
|
|
1757
|
+
return typeof path === "string" ? path : void 0;
|
|
1758
|
+
}
|
|
1759
|
+
function shownPath(path, repo) {
|
|
1760
|
+
const inside = relative(repo, resolve(repo, path));
|
|
1761
|
+
return inside && !inside.startsWith("..") && !isAbsolute(inside) ? inside : path;
|
|
1762
|
+
}
|
|
1763
|
+
function questionsOf(input) {
|
|
1764
|
+
const questions = input?.questions;
|
|
1765
|
+
return Array.isArray(questions) ? questions.filter((q) => typeof q?.question === "string") : [];
|
|
1766
|
+
}
|
|
1767
|
+
var REPLY = "Reply yes to allow it, or say what to do instead.";
|
|
1768
|
+
function cut(text) {
|
|
1769
|
+
const line2 = text.replace(/\s+/g, " ").trim();
|
|
1770
|
+
return line2.length > 200 ? `${line2.slice(0, 200)}\u2026` : line2;
|
|
1771
|
+
}
|
|
1772
|
+
function askSummary(tool, input, repo) {
|
|
1773
|
+
if (tool === "AskUserQuestion") return questionLine(questionsOf(input));
|
|
1774
|
+
const fields = input ?? {};
|
|
1775
|
+
if (tool === "Bash") {
|
|
1776
|
+
const shown = cut(String(fields.command ?? ""));
|
|
1777
|
+
const why = typeof fields.description === "string" ? ` (${fields.description.slice(0, 100)})` : "";
|
|
1778
|
+
return `Claude Code asks to run: ${shown}${why}. ${REPLY}`;
|
|
1779
|
+
}
|
|
1780
|
+
if (tool === "WebFetch" && typeof fields.url === "string")
|
|
1781
|
+
return `Claude Code asks to fetch ${cut(fields.url)}. ${REPLY}`;
|
|
1782
|
+
if (tool.startsWith("mcp__"))
|
|
1783
|
+
return `Claude Code asks to use ${tool} with ${cut(JSON.stringify(fields))}. ${REPLY}`;
|
|
1784
|
+
const path = pathOf(fields);
|
|
1785
|
+
const where = path ? ` on ${shownPath(path, repo)}` : "";
|
|
1786
|
+
return `Claude Code asks to use ${tool}${where}. ${REPLY}`;
|
|
1787
|
+
}
|
|
1788
|
+
function line(value) {
|
|
1789
|
+
return `${JSON.stringify(value)}
|
|
1790
|
+
`;
|
|
1791
|
+
}
|
|
1792
|
+
function userMessage(run2, text, priority) {
|
|
1793
|
+
return {
|
|
1794
|
+
type: "user",
|
|
1795
|
+
message: { role: "user", content: [{ type: "text", text }] },
|
|
1796
|
+
parent_tool_use_id: null,
|
|
1797
|
+
session_id: run2.session_id ?? run2.work_id,
|
|
1798
|
+
...priority ? { priority } : {}
|
|
1799
|
+
};
|
|
1800
|
+
}
|
|
1801
|
+
function parseClaudeLine(raw, run2) {
|
|
1802
|
+
let msg;
|
|
1803
|
+
try {
|
|
1804
|
+
msg = JSON.parse(raw);
|
|
1805
|
+
} catch {
|
|
1806
|
+
return [];
|
|
1807
|
+
}
|
|
1808
|
+
if (msg.type === "system" && msg.subtype === "init" && typeof msg.session_id === "string") {
|
|
1809
|
+
return [{ type: "session", id: msg.session_id }];
|
|
1810
|
+
}
|
|
1811
|
+
if (msg.type === "assistant") {
|
|
1812
|
+
const content = msg.message?.content;
|
|
1813
|
+
if (!Array.isArray(content)) return [];
|
|
1814
|
+
return content.flatMap((block) => {
|
|
1815
|
+
if (block?.type === "text" && typeof block.text === "string" && block.text.trim())
|
|
1816
|
+
return [{ type: "text", text: block.text }];
|
|
1817
|
+
if (block?.type === "tool_use" && typeof block.name === "string" && block.name !== "AskUserQuestion") {
|
|
1818
|
+
const path = pathOf(block.input);
|
|
1819
|
+
return [{ type: "tool", name: block.name, ...path ? { target: basename2(path) } : {} }];
|
|
1820
|
+
}
|
|
1821
|
+
return [];
|
|
1822
|
+
});
|
|
1823
|
+
}
|
|
1824
|
+
if (msg.type === "control_request") {
|
|
1825
|
+
const request = msg.request;
|
|
1826
|
+
if (request?.subtype !== "can_use_tool" || typeof msg.request_id !== "string") return [];
|
|
1827
|
+
const tool = request.tool_name ?? "a tool";
|
|
1828
|
+
return [
|
|
1829
|
+
{
|
|
1830
|
+
type: "ask",
|
|
1831
|
+
request_id: msg.request_id,
|
|
1832
|
+
tool,
|
|
1833
|
+
input: request.input ?? {},
|
|
1834
|
+
summary: askSummary(tool, request.input, run2.repo)
|
|
1835
|
+
}
|
|
1836
|
+
];
|
|
1837
|
+
}
|
|
1838
|
+
if (msg.type === "control_cancel_request" && typeof msg.request_id === "string") {
|
|
1839
|
+
return [{ type: "cancel", request_id: msg.request_id }];
|
|
1840
|
+
}
|
|
1841
|
+
if (msg.type === "result") {
|
|
1842
|
+
return [
|
|
1843
|
+
{
|
|
1844
|
+
type: "result",
|
|
1845
|
+
ok: msg.subtype === "success" && msg.is_error !== true,
|
|
1846
|
+
...typeof msg.result === "string" ? { text: msg.result } : {}
|
|
1847
|
+
}
|
|
1848
|
+
];
|
|
1849
|
+
}
|
|
1850
|
+
return [];
|
|
1851
|
+
}
|
|
1852
|
+
var DEFAULT_FALLBACK_MODEL = "opus";
|
|
1853
|
+
function claudeDialect(bin = "claude", fallback = DEFAULT_FALLBACK_MODEL) {
|
|
1854
|
+
return {
|
|
1855
|
+
name: "claude-code",
|
|
1856
|
+
fallback,
|
|
1857
|
+
aliases: ["claude-code", "claudeAgent", "claude"],
|
|
1858
|
+
bin,
|
|
1859
|
+
capabilities: ["view", "start", "steer", "report"],
|
|
1860
|
+
keepsStdin: true,
|
|
1861
|
+
args(run2, resume) {
|
|
1862
|
+
return [
|
|
1863
|
+
"--print",
|
|
1864
|
+
"--verbose",
|
|
1865
|
+
"--output-format",
|
|
1866
|
+
"stream-json",
|
|
1867
|
+
"--input-format",
|
|
1868
|
+
"stream-json",
|
|
1869
|
+
"--permission-prompt-tool",
|
|
1870
|
+
"stdio",
|
|
1871
|
+
"--permission-mode",
|
|
1872
|
+
permissionMode(run2.runtime_mode),
|
|
1873
|
+
"--add-dir",
|
|
1874
|
+
run2.repo,
|
|
1875
|
+
...resume ? ["--resume", run2.session_id ?? run2.work_id] : ["--session-id", run2.session_id ?? run2.work_id],
|
|
1876
|
+
...run2.model ? ["--model", run2.model] : fallback ? ["--fallback-model", fallback] : []
|
|
1877
|
+
];
|
|
1878
|
+
},
|
|
1879
|
+
opening(run2, prompt) {
|
|
1880
|
+
return line({
|
|
1881
|
+
type: "control_request",
|
|
1882
|
+
request_id: "cloop-init",
|
|
1883
|
+
request: { subtype: "initialize" }
|
|
1884
|
+
}) + line(userMessage(run2, prompt));
|
|
1885
|
+
},
|
|
1886
|
+
userLine(run2, text, mode) {
|
|
1887
|
+
return line(userMessage(run2, text, mode === "steer" ? "now" : "next"));
|
|
1888
|
+
},
|
|
1889
|
+
answerLine(ask, text) {
|
|
1890
|
+
const input = ask.input ?? {};
|
|
1891
|
+
const response = ask.tool === "AskUserQuestion" ? {
|
|
1892
|
+
behavior: "allow",
|
|
1893
|
+
updatedInput: {
|
|
1894
|
+
...input,
|
|
1895
|
+
answers: Object.fromEntries(questionsOf(input).map((q) => [q.question, text]))
|
|
1896
|
+
}
|
|
1897
|
+
} : isYes(text) ? { behavior: "allow", updatedInput: input } : { behavior: "deny", message: text };
|
|
1898
|
+
return line({
|
|
1899
|
+
type: "control_response",
|
|
1900
|
+
response: { subtype: "success", request_id: ask.request_id, response }
|
|
1901
|
+
});
|
|
1902
|
+
},
|
|
1903
|
+
parse: parseClaudeLine,
|
|
1904
|
+
owns: (run2, command) => command.includes(basename2(bin)) && [run2.work_id, run2.session_id].some((id) => id !== null && command.includes(id)),
|
|
1905
|
+
probe: () => probeClaude(bin)
|
|
1906
|
+
};
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
// src/drivers/codex.ts
|
|
1910
|
+
import { execFile as execFile4 } from "child_process";
|
|
1911
|
+
import { basename as basename3 } from "path";
|
|
1912
|
+
var SANDBOX = {
|
|
1913
|
+
"approval-required": "read-only",
|
|
1914
|
+
"auto-accept-edits": "workspace-write",
|
|
1915
|
+
auto: "workspace-write",
|
|
1916
|
+
"full-access": "danger-full-access"
|
|
1917
|
+
};
|
|
1918
|
+
function exec2(bin, args) {
|
|
1919
|
+
return new Promise(
|
|
1920
|
+
(resolve3) => execFile4(
|
|
1921
|
+
bin,
|
|
1922
|
+
args,
|
|
1923
|
+
{ timeout: 1e4, encoding: "utf-8" },
|
|
1924
|
+
(err, out2, errOut) => resolve3({ ok: !err, out: `${out2}${errOut}` })
|
|
1925
|
+
)
|
|
1926
|
+
);
|
|
1927
|
+
}
|
|
1928
|
+
function codexAccount(ok, out2) {
|
|
1929
|
+
if (!ok || !/logged in/i.test(out2) || /not logged in/i.test(out2))
|
|
1930
|
+
return { signedIn: false, account: null };
|
|
1931
|
+
return { signedIn: true, account: /chatgpt/i.test(out2) ? "ChatGPT" : "API key" };
|
|
1932
|
+
}
|
|
1933
|
+
async function probeCodex(bin = "codex") {
|
|
1934
|
+
const version = await exec2(bin, ["--version"]);
|
|
1935
|
+
if (!version.ok) return null;
|
|
1936
|
+
const status = await exec2(bin, ["login", "status"]);
|
|
1937
|
+
const { signedIn, account } = codexAccount(status.ok, status.out);
|
|
1938
|
+
return {
|
|
1939
|
+
id: "codex",
|
|
1940
|
+
name: "Codex",
|
|
1941
|
+
version: version.out.trim().split(/\s+/).at(-1) ?? null,
|
|
1942
|
+
ready: signedIn,
|
|
1943
|
+
signedIn,
|
|
1944
|
+
account,
|
|
1945
|
+
defaultModel: null,
|
|
1946
|
+
experimental: true
|
|
1947
|
+
};
|
|
1948
|
+
}
|
|
1949
|
+
function parseCodexLine(raw) {
|
|
1950
|
+
let msg;
|
|
1951
|
+
try {
|
|
1952
|
+
msg = JSON.parse(raw);
|
|
1953
|
+
} catch {
|
|
1954
|
+
return [];
|
|
1955
|
+
}
|
|
1956
|
+
if (msg.type === "thread.started" && typeof msg.thread_id === "string")
|
|
1957
|
+
return [{ type: "session", id: msg.thread_id }];
|
|
1958
|
+
const item = msg.item;
|
|
1959
|
+
if (msg.type === "item.completed" && item?.type === "agent_message" && typeof item.text === "string")
|
|
1960
|
+
return [{ type: "text", text: item.text }];
|
|
1961
|
+
if (msg.type === "item.started" && item?.type === "command_execution")
|
|
1962
|
+
return [{ type: "tool", name: "Bash" }];
|
|
1963
|
+
if (msg.type === "item.completed" && item?.type === "file_change") {
|
|
1964
|
+
const changes = Array.isArray(item.changes) ? item.changes : [];
|
|
1965
|
+
const path = changes[0]?.path;
|
|
1966
|
+
return [
|
|
1967
|
+
{
|
|
1968
|
+
type: "tool",
|
|
1969
|
+
name: "Edit",
|
|
1970
|
+
...typeof path === "string" ? { target: basename3(path) } : {}
|
|
1971
|
+
}
|
|
1972
|
+
];
|
|
1973
|
+
}
|
|
1974
|
+
if (msg.type === "turn.completed") return [{ type: "result", ok: true }];
|
|
1975
|
+
if (msg.type === "turn.failed") {
|
|
1976
|
+
const message = msg.error?.message;
|
|
1977
|
+
return [
|
|
1978
|
+
{ type: "result", ok: false, ...typeof message === "string" ? { text: message } : {} }
|
|
1979
|
+
];
|
|
1980
|
+
}
|
|
1981
|
+
return [];
|
|
1982
|
+
}
|
|
1983
|
+
function codexDialect(bin = "codex") {
|
|
1984
|
+
return {
|
|
1985
|
+
name: "codex",
|
|
1986
|
+
aliases: ["codex"],
|
|
1987
|
+
bin,
|
|
1988
|
+
capabilities: ["view", "start", "report"],
|
|
1989
|
+
keepsStdin: false,
|
|
1990
|
+
args(run2, resume) {
|
|
1991
|
+
const model = run2.model ? ["--model", run2.model] : [];
|
|
1992
|
+
const sandbox = SANDBOX[run2.runtime_mode ?? "auto-accept-edits"];
|
|
1993
|
+
return resume && run2.session_id ? [
|
|
1994
|
+
"exec",
|
|
1995
|
+
"resume",
|
|
1996
|
+
run2.session_id,
|
|
1997
|
+
"--json",
|
|
1998
|
+
"-c",
|
|
1999
|
+
`sandbox_mode="${sandbox}"`,
|
|
2000
|
+
...model,
|
|
2001
|
+
"-"
|
|
2002
|
+
] : ["exec", "--cd", run2.repo, "--json", "--sandbox", sandbox, ...model, "-"];
|
|
2003
|
+
},
|
|
2004
|
+
opening: (_run, prompt) => prompt,
|
|
2005
|
+
parse: parseCodexLine,
|
|
2006
|
+
// A fresh run's command line names no id: Codex makes its session id after the start. So a run is also matched by its exact repository, which one open run per repository makes unique.
|
|
2007
|
+
owns: (run2, command) => command.includes(basename3(bin)) && command.includes("exec") && command.includes("--json") && (run2.session_id !== null && command.includes(run2.session_id) || command.includes(`--cd ${run2.repo} `)),
|
|
2008
|
+
probe: () => probeCodex(bin)
|
|
2009
|
+
};
|
|
2010
|
+
}
|
|
2011
|
+
|
|
2012
|
+
// src/runner-config.ts
|
|
2013
|
+
import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "fs";
|
|
2014
|
+
import { homedir as homedir3 } from "os";
|
|
2015
|
+
import { dirname as dirname3, join as join4 } from "path";
|
|
2016
|
+
var BOX_FILE = "box.json";
|
|
2017
|
+
function boxPath() {
|
|
2018
|
+
return process.env.CLOOP_BOX_FILE ?? join4(homedir3(), CONFIG_DIR, BOX_FILE);
|
|
2019
|
+
}
|
|
2020
|
+
function isLocal(cfg) {
|
|
2021
|
+
return cfg.driver === "claude-code" || cfg.driver === "codex";
|
|
2022
|
+
}
|
|
2023
|
+
function readRunnerConfig() {
|
|
2024
|
+
let parsed;
|
|
2025
|
+
try {
|
|
2026
|
+
parsed = JSON.parse(readFileSync3(boxPath(), "utf-8"));
|
|
2027
|
+
} catch {
|
|
2028
|
+
return null;
|
|
2029
|
+
}
|
|
2030
|
+
if (parsed.driver === "claude-code" || parsed.driver === "codex") {
|
|
2031
|
+
const ok = typeof parsed.deviceToken === "string" && typeof parsed.environmentId === "string" && typeof parsed.bin === "string" && Array.isArray(parsed.repos);
|
|
2032
|
+
return ok ? parsed : null;
|
|
2033
|
+
}
|
|
2034
|
+
if (typeof parsed.t3Url !== "string" || typeof parsed.token !== "string") return null;
|
|
2035
|
+
return parsed;
|
|
2036
|
+
}
|
|
2037
|
+
function writeBoxConfig(cfg) {
|
|
2038
|
+
const path = boxPath();
|
|
2039
|
+
mkdirSync3(dirname3(path), { recursive: true, mode: 448 });
|
|
2040
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
2041
|
+
writeFileSync3(temp, `${JSON.stringify(cfg, null, 2)}
|
|
2042
|
+
`, { mode: 384 });
|
|
2043
|
+
chmodSync3(temp, 384);
|
|
2044
|
+
renameSync3(temp, path);
|
|
2045
|
+
}
|
|
2046
|
+
|
|
2047
|
+
// src/commands/connect.ts
|
|
2048
|
+
var DEFAULT_T3_URL = "http://127.0.0.1:3773";
|
|
2049
|
+
var CLEAN_ENV2 = { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH };
|
|
2050
|
+
var out = (line2) => console.log(line2);
|
|
2051
|
+
var bold = (s) => `\x1B[1m${s}\x1B[0m`;
|
|
2052
|
+
var dim = (s) => `\x1B[2m${s}\x1B[0m`;
|
|
2053
|
+
var red = (s) => `\x1B[31m${s}\x1B[0m`;
|
|
2054
|
+
function flag(argv, name) {
|
|
2055
|
+
const i = argv.indexOf(name);
|
|
2056
|
+
return i >= 0 ? argv[i + 1] : void 0;
|
|
2057
|
+
}
|
|
2058
|
+
function flags(argv, name) {
|
|
2059
|
+
return argv.flatMap((a, i) => a === name && argv[i + 1] ? [argv[i + 1]] : []);
|
|
2060
|
+
}
|
|
2061
|
+
function which(bin) {
|
|
2062
|
+
try {
|
|
2063
|
+
return execFileSync4("which", [bin], { encoding: "utf-8", env: CLEAN_ENV2 }).trim() || null;
|
|
2064
|
+
} catch {
|
|
2065
|
+
return null;
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
async function mintSession(t3Url, opts = {}) {
|
|
2069
|
+
const env = await readEnvironment(t3Url, opts.fetchFn);
|
|
2070
|
+
const protocol = env.orchestrationProtocolVersion ?? 1;
|
|
2071
|
+
if (protocol < MIN_PROTOCOL) {
|
|
2072
|
+
throw new Error(
|
|
2073
|
+
`T3 ${env.serverVersion} speaks orchestration protocol ${protocol}; a workstation needs ${MIN_PROTOCOL} (the V2 nightly or later).`
|
|
2074
|
+
);
|
|
2075
|
+
}
|
|
2076
|
+
const sources = opts.sources ?? defaultT3BinSources(homedir4(), opts.stored);
|
|
2077
|
+
const t3Bin = opts.bin ?? pickT3Bin(t3Candidates(env.serverVersion, sources), env.serverVersion);
|
|
2078
|
+
if (!t3Bin) throw new Error("no t3 binary found; pass --t3-bin or set T3_BIN");
|
|
2079
|
+
const pairing = JSON.parse(
|
|
2080
|
+
runT3(t3Bin, [
|
|
2081
|
+
"auth",
|
|
2082
|
+
"pairing",
|
|
2083
|
+
"create",
|
|
2084
|
+
...t3BaseDirArgs(sources.env),
|
|
2085
|
+
"--ttl",
|
|
2086
|
+
"5m",
|
|
2087
|
+
"--json"
|
|
2088
|
+
])
|
|
2089
|
+
);
|
|
2090
|
+
const token = await exchangePairing(t3Url, pairing.credential, "cloop box", opts.fetchFn);
|
|
2091
|
+
return {
|
|
2092
|
+
t3Url,
|
|
2093
|
+
t3Bin,
|
|
2094
|
+
token: token.access_token,
|
|
2095
|
+
scope: token.scope,
|
|
2096
|
+
expiresAt: new Date(Date.now() + token.expires_in * 1e3).toISOString(),
|
|
2097
|
+
environmentId: env.environmentId,
|
|
2098
|
+
label: env.label
|
|
2099
|
+
};
|
|
2100
|
+
}
|
|
2101
|
+
async function connectBox(steps) {
|
|
2102
|
+
const environment = await steps.readEnvironment();
|
|
2103
|
+
const session = await steps.mintSession();
|
|
2104
|
+
const deviceToken = await steps.deviceLogin(environment);
|
|
2105
|
+
const cfg = { ...session, deviceToken };
|
|
2106
|
+
steps.writeBoxConfig(cfg);
|
|
2107
|
+
return cfg;
|
|
2108
|
+
}
|
|
2109
|
+
var NONE = "No coding agent found on this machine. Install Claude Code or Codex, sign in, then run `cloop connect` again.";
|
|
2110
|
+
var SIGNED_OUT = {
|
|
2111
|
+
"claude-code": "Claude Code is installed but not signed in. Run `claude` once and sign in, then run `cloop connect` again.",
|
|
2112
|
+
codex: "Codex is installed but not signed in. Run `codex login`, then run `cloop connect` again."
|
|
2113
|
+
};
|
|
2114
|
+
var T3_DOWN = "T3 Code is not answering; start it, or pass --driver claude-code.";
|
|
2115
|
+
function chooseDriver(found, forced, workstation = false) {
|
|
2116
|
+
const local = (driver) => {
|
|
2117
|
+
const harness = driver === "claude-code" ? found.claude : found.codex;
|
|
2118
|
+
if (!harness)
|
|
2119
|
+
return {
|
|
2120
|
+
ok: false,
|
|
2121
|
+
code: "no_harness",
|
|
2122
|
+
line: `${driver === "codex" ? "Codex" : "Claude Code"} is not installed here.`
|
|
2123
|
+
};
|
|
2124
|
+
return harness.signedIn ? { ok: true, driver, kind: "local" } : { ok: false, code: "signed_out", line: SIGNED_OUT[driver] };
|
|
2125
|
+
};
|
|
2126
|
+
if (forced === "t3")
|
|
2127
|
+
return found.t3 ? { ok: true, driver: "t3", kind: "workstation" } : { ok: false, code: "no_harness", line: `No T3 Code server answers at ${DEFAULT_T3_URL}.` };
|
|
2128
|
+
if (forced) return local(forced);
|
|
2129
|
+
if (found.t3) return { ok: true, driver: "t3", kind: "workstation" };
|
|
2130
|
+
if (workstation) return { ok: false, code: "t3_unreachable", line: T3_DOWN };
|
|
2131
|
+
if (found.claude?.signedIn) return local("claude-code");
|
|
2132
|
+
if (found.codex?.signedIn) return local("codex");
|
|
2133
|
+
if (found.claude) return local("claude-code");
|
|
2134
|
+
if (found.codex) return local("codex");
|
|
2135
|
+
return { ok: false, code: "no_harness", line: NONE };
|
|
2136
|
+
}
|
|
2137
|
+
var HARNESS_NAME = {
|
|
2138
|
+
"claude-code": "Claude Code",
|
|
2139
|
+
codex: "Codex"
|
|
2140
|
+
};
|
|
2141
|
+
function fallbackDriver(found, forced, workstation) {
|
|
2142
|
+
if (forced === "t3" || workstation) return null;
|
|
2143
|
+
const choice = chooseDriver({ ...found, t3: false });
|
|
2144
|
+
return choice.ok && choice.driver !== "t3" ? choice.driver : null;
|
|
2145
|
+
}
|
|
2146
|
+
function isWorkstation(previous, boxServiceInstalled2) {
|
|
2147
|
+
return boxServiceInstalled2 || Boolean(previous && !isLocal(previous));
|
|
2148
|
+
}
|
|
2149
|
+
function boxServiceInstalled() {
|
|
2150
|
+
return existsSync2(
|
|
2151
|
+
installedService({
|
|
2152
|
+
platform: process.platform,
|
|
2153
|
+
kind: "workstation",
|
|
2154
|
+
home: homedir4(),
|
|
2155
|
+
uid: process.getuid?.() ?? 0,
|
|
2156
|
+
...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
|
|
2157
|
+
}).path
|
|
2158
|
+
);
|
|
2159
|
+
}
|
|
2160
|
+
var KIND_NAME = { workstation: "a Cloop box with T3 Code", local: "a Local runner" };
|
|
2161
|
+
async function revokeReplaced(previous, kind, revoke, say) {
|
|
2162
|
+
if (!previous?.deviceToken || isLocal(previous) === (kind === "local")) return;
|
|
2163
|
+
const was = isLocal(previous) ? "local" : "workstation";
|
|
2164
|
+
say(
|
|
2165
|
+
`${bold("Cloop runner")} This computer was ${KIND_NAME[was]}. It becomes ${KIND_NAME[kind]}, so its old device goes.`
|
|
2166
|
+
);
|
|
2167
|
+
say(
|
|
2168
|
+
tokenGone(await revoke(previous.deviceToken)) ? " Revoked the old device on Cloop." : " Could not revoke the old device. Press Disconnect on its card on the Threads page."
|
|
2169
|
+
);
|
|
2170
|
+
}
|
|
2171
|
+
function fallbackLine(reason, driver) {
|
|
2172
|
+
return `T3 Code is running but would not pair (${reason}). Connecting ${HARNESS_NAME[driver]} instead. To use T3: cloop connect --driver t3 --t3-bin <path>`;
|
|
2173
|
+
}
|
|
2174
|
+
async function connectChosen(driver, attempt, run2) {
|
|
2175
|
+
attempt.driver = driver;
|
|
2176
|
+
if (driver !== "t3") return run2.local(driver);
|
|
2177
|
+
try {
|
|
2178
|
+
await run2.t3();
|
|
2179
|
+
} catch (err) {
|
|
2180
|
+
if (!(err instanceof ConnectFailure) || err.code !== "t3_pair_failed") throw err;
|
|
2181
|
+
const local = run2.fallback();
|
|
2182
|
+
if (!local) throw err;
|
|
2183
|
+
run2.say(fallbackLine(err.message, local));
|
|
2184
|
+
attempt.fellBack = true;
|
|
2185
|
+
attempt.driver = local;
|
|
2186
|
+
await run2.local(local);
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
function systemdAssignment(assignment) {
|
|
2190
|
+
return `"${assignment.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
|
|
2191
|
+
}
|
|
2192
|
+
function systemdWord(arg) {
|
|
2193
|
+
const escaped = arg.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%").replace(/\$/g, "$$$$");
|
|
2194
|
+
return `"${escaped}"`;
|
|
2195
|
+
}
|
|
2196
|
+
function programFor(script, node, npx, version) {
|
|
2197
|
+
if (!script.includes("/_npx/")) return [node, script, "box", "run"];
|
|
2198
|
+
if (!npx)
|
|
2199
|
+
return "npx is not on PATH, so the service cannot run Cloop. Install it with `npm install -g @cloop/runner` and run `cloop connect` again.";
|
|
2200
|
+
return [npx, "-y", `@cloop/runner@${version}`, "box", "run"];
|
|
2201
|
+
}
|
|
2202
|
+
async function awaitDaemon(since, read = readRunnerState, { timeoutMs = 15e3, pollMs = 500 } = {}) {
|
|
2203
|
+
for (let waited = 0; ; waited += pollMs) {
|
|
2204
|
+
const state = read();
|
|
2205
|
+
if (state && Date.parse(state.connected_at) >= since) return true;
|
|
2206
|
+
if (waited >= timeoutMs) return false;
|
|
2207
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
2208
|
+
}
|
|
2209
|
+
}
|
|
2210
|
+
var UNIT_ENV = [
|
|
2211
|
+
"PATH",
|
|
2212
|
+
"CLOOP_BOX_FILE",
|
|
2213
|
+
"CLOOP_BOX_THREADS_FILE",
|
|
2214
|
+
"CLOOP_LOCAL_RUNS_FILE",
|
|
2215
|
+
"CLOOP_MESH_URL",
|
|
2216
|
+
"CLOOP_ORIGIN",
|
|
2217
|
+
"T3CODE_HOME"
|
|
2218
|
+
];
|
|
2219
|
+
function unitEnv(env) {
|
|
2220
|
+
const picked = { PATH: "/usr/bin:/bin" };
|
|
2221
|
+
for (const key of UNIT_ENV) {
|
|
2222
|
+
const value = env[key];
|
|
2223
|
+
if (value) picked[key] = value;
|
|
2224
|
+
}
|
|
2225
|
+
return picked;
|
|
2226
|
+
}
|
|
2227
|
+
function installedService(opts) {
|
|
2228
|
+
const name = opts.kind === "workstation" ? "box" : "runner";
|
|
2229
|
+
if (opts.platform === "darwin") {
|
|
2230
|
+
const label = `com.cloop.${name}`;
|
|
2231
|
+
return {
|
|
2232
|
+
path: join5(opts.dir ?? join5(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
|
|
2233
|
+
steps: [{ command: ["launchctl", "bootout", `gui/${opts.uid}/${label}`], mayFail: true }],
|
|
2234
|
+
running: ["launchctl", "print", `gui/${opts.uid}/${label}`]
|
|
2235
|
+
};
|
|
2236
|
+
}
|
|
2237
|
+
const unit = `cloop-${name}.service`;
|
|
2238
|
+
return {
|
|
2239
|
+
path: join5(opts.dir ?? join5(opts.home, ".config", "systemd", "user"), unit),
|
|
2240
|
+
steps: [{ command: ["systemctl", "--user", "disable", "--now", unit], mayFail: true }],
|
|
2241
|
+
running: ["systemctl", "--user", "is-active", "--quiet", unit]
|
|
2242
|
+
};
|
|
2243
|
+
}
|
|
2244
|
+
function unitFor(opts) {
|
|
2245
|
+
const env = Object.entries(opts.env);
|
|
2246
|
+
const name = opts.kind === "workstation" ? "box" : "runner";
|
|
2247
|
+
const retire = installedService({
|
|
2248
|
+
...opts,
|
|
2249
|
+
kind: opts.kind === "workstation" ? "local" : "workstation"
|
|
2250
|
+
});
|
|
2251
|
+
if (opts.platform === "darwin") {
|
|
2252
|
+
const label = `com.cloop.${name}`;
|
|
2253
|
+
const agents = opts.dir ?? join5(opts.home, "Library", "LaunchAgents");
|
|
2254
|
+
const path2 = join5(agents, `${label}.plist`);
|
|
2255
|
+
const log = join5(opts.home, "Library", "Logs", `cloop-${name}.log`);
|
|
2256
|
+
const xml = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
2257
|
+
const contents2 = [
|
|
2258
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
2259
|
+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
2260
|
+
'<plist version="1.0">',
|
|
2261
|
+
"<dict>",
|
|
2262
|
+
` <key>Label</key><string>${label}</string>`,
|
|
2263
|
+
" <key>ProgramArguments</key>",
|
|
2264
|
+
" <array>",
|
|
2265
|
+
...opts.program.map((arg) => ` <string>${xml(arg)}</string>`),
|
|
2266
|
+
" </array>",
|
|
2267
|
+
" <key>EnvironmentVariables</key>",
|
|
2268
|
+
` <dict>${env.map(([key, value]) => `<key>${key}</key><string>${xml(value)}</string>`).join("")}</dict>`,
|
|
2269
|
+
" <key>RunAtLoad</key><true/>",
|
|
2270
|
+
" <key>KeepAlive</key><true/>",
|
|
2271
|
+
" <key>ThrottleInterval</key><integer>10</integer>",
|
|
2272
|
+
` <key>StandardOutPath</key><string>${xml(log)}</string>`,
|
|
2273
|
+
` <key>StandardErrorPath</key><string>${xml(log)}</string>`,
|
|
2274
|
+
"</dict>",
|
|
2275
|
+
"</plist>",
|
|
2276
|
+
""
|
|
2277
|
+
].join("\n");
|
|
2278
|
+
const domain = `gui/${opts.uid}`;
|
|
2279
|
+
return {
|
|
2280
|
+
path: path2,
|
|
2281
|
+
contents: contents2,
|
|
2282
|
+
start: [
|
|
2283
|
+
{ command: ["launchctl", "bootout", `${domain}/${label}`], mayFail: true },
|
|
2284
|
+
{ command: ["launchctl", "bootstrap", domain, path2], tries: 5 }
|
|
2285
|
+
],
|
|
2286
|
+
retire,
|
|
2287
|
+
logs: `tail -f ${log}`,
|
|
2288
|
+
tail: ["tail", "-n", "20", log]
|
|
2289
|
+
};
|
|
2290
|
+
}
|
|
2291
|
+
const unit = `cloop-${name}.service`;
|
|
2292
|
+
const units = opts.dir ?? join5(opts.home, ".config", "systemd", "user");
|
|
2293
|
+
const path = join5(units, unit);
|
|
2294
|
+
const contents = [
|
|
2295
|
+
"[Unit]",
|
|
2296
|
+
`Description=Cloop ${name}: answers the Cloop Agent over the mesh`,
|
|
2297
|
+
"After=network-online.target",
|
|
2298
|
+
// A disconnected runner exits 1 on every start. Three in ten minutes and
|
|
2299
|
+
// systemd marks the unit failed instead of restarting it forever.
|
|
2300
|
+
"StartLimitIntervalSec=600",
|
|
2301
|
+
"StartLimitBurst=3",
|
|
2302
|
+
"",
|
|
2303
|
+
"[Service]",
|
|
2304
|
+
...env.map(([key, value]) => `Environment=${systemdAssignment(`${key}=${value}`)}`),
|
|
2305
|
+
`ExecStart=${opts.program.map(systemdWord).join(" ")}`,
|
|
2306
|
+
"Restart=always",
|
|
2307
|
+
"RestartSec=5",
|
|
2308
|
+
"",
|
|
2309
|
+
"[Install]",
|
|
2310
|
+
"WantedBy=default.target",
|
|
2311
|
+
""
|
|
2312
|
+
].join("\n");
|
|
2313
|
+
return {
|
|
2314
|
+
path,
|
|
2315
|
+
contents,
|
|
2316
|
+
start: [
|
|
2317
|
+
{ command: ["systemctl", "--user", "reset-failed", unit], mayFail: true },
|
|
2318
|
+
{ command: ["systemctl", "--user", "daemon-reload"] },
|
|
2319
|
+
{ command: ["systemctl", "--user", "enable", unit] },
|
|
2320
|
+
{ command: ["systemctl", "--user", "restart", unit] }
|
|
2321
|
+
],
|
|
2322
|
+
retire,
|
|
2323
|
+
logs: `journalctl --user -u ${unit} -f`,
|
|
2324
|
+
tail: ["journalctl", "--user", "-u", unit, "-n", "20", "--no-pager"]
|
|
2325
|
+
};
|
|
2326
|
+
}
|
|
2327
|
+
function resolveRepos(paths, toplevel) {
|
|
2328
|
+
const repos = [];
|
|
2329
|
+
for (const p of paths) {
|
|
2330
|
+
const top = toplevel(resolve2(p));
|
|
2331
|
+
if (!top)
|
|
2332
|
+
return `${p} is not a git checkout. Pass --repo <path> for each repository Cloop may work in.`;
|
|
2333
|
+
if (!repos.some((r) => r.path === top)) repos.push({ label: basename4(top), path: top });
|
|
2334
|
+
}
|
|
2335
|
+
return repos;
|
|
2336
|
+
}
|
|
2337
|
+
var CHECKOUT_ROOTS = ["projects", "code", "repos", "src", "Developer", "dev", "work"];
|
|
2338
|
+
function lastCommitAt(path) {
|
|
2339
|
+
try {
|
|
2340
|
+
return Number(
|
|
2341
|
+
execFileSync4("git", ["-C", path, "log", "-1", "--format=%ct"], {
|
|
2342
|
+
encoding: "utf-8",
|
|
2343
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
2344
|
+
timeout: 5e3
|
|
2345
|
+
}).trim()
|
|
2346
|
+
) || 0;
|
|
2347
|
+
} catch {
|
|
2348
|
+
return 0;
|
|
2349
|
+
}
|
|
2350
|
+
}
|
|
2351
|
+
function findCheckouts(home, limit = 8) {
|
|
2352
|
+
const found = [];
|
|
2353
|
+
for (const root of CHECKOUT_ROOTS) {
|
|
2354
|
+
let entries;
|
|
2355
|
+
try {
|
|
2356
|
+
entries = readdirSync2(join5(home, root), { withFileTypes: true });
|
|
2357
|
+
} catch {
|
|
2358
|
+
continue;
|
|
2359
|
+
}
|
|
2360
|
+
for (const entry of entries) {
|
|
2361
|
+
const path = join5(home, root, entry.name);
|
|
2362
|
+
if (!entry.isDirectory() || !existsSync2(join5(path, ".git"))) continue;
|
|
2363
|
+
found.push({ repo: { label: entry.name, path }, at: lastCommitAt(path) });
|
|
2364
|
+
}
|
|
2365
|
+
}
|
|
2366
|
+
return found.sort((a, b) => b.at - a.at).slice(0, limit).map((f) => f.repo);
|
|
2367
|
+
}
|
|
2368
|
+
function tilde(path, home) {
|
|
2369
|
+
return path === home || path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
|
|
2370
|
+
}
|
|
2371
|
+
function parsePicks(answer, max) {
|
|
2372
|
+
const picks = answer.split(/[\s,]+/).filter(Boolean).map(Number);
|
|
2373
|
+
if (!picks.length || picks.some((n) => !Number.isInteger(n) || n < 1 || n > max)) return null;
|
|
2374
|
+
return [...new Set(picks)];
|
|
2375
|
+
}
|
|
2376
|
+
function rerunCommand(argv, script = process.argv[1] ?? "") {
|
|
2377
|
+
const base = script.includes("/_npx/") ? "npx -y @cloop/runner" : "cloop";
|
|
2378
|
+
const staging = process.env.CLOOP_ORIGIN === STAGING_ORIGIN ? ["--staging"] : [];
|
|
2379
|
+
return [base, "connect", ...staging, ...argv].join(" ");
|
|
2380
|
+
}
|
|
2381
|
+
function notACheckoutLine(cwd, found, home, rerun) {
|
|
2382
|
+
const here = `${tilde(cwd, home)} is not a git checkout.`;
|
|
2383
|
+
if (!found.length)
|
|
2384
|
+
return `${here} Run it again with --repo <path> for each repository Cloop may work in: ${rerun} --repo <path>`;
|
|
2385
|
+
const list = found.map((r) => `${r.label} (${tilde(r.path, home)})`).join(", ");
|
|
2386
|
+
return `${here} Recent checkouts: ${list}. Run it again with a --repo for each one Cloop may work in, for example: ${rerun} --repo ${tilde(found[0]?.path ?? "", home)}`;
|
|
2387
|
+
}
|
|
2388
|
+
async function askRepos(found, home, rerun, ask, say) {
|
|
2389
|
+
say(`${bold("Cloop runner")} This folder is not a git checkout. Recent ones:`);
|
|
2390
|
+
found.forEach((r, i) => say(` ${i + 1} ${r.label} ${dim(tilde(r.path, home))}`));
|
|
2391
|
+
for (; ; ) {
|
|
2392
|
+
const answer = (await ask("Which folders may Cloop work in? (numbers, comma-separated) ")).trim();
|
|
2393
|
+
if (!answer)
|
|
2394
|
+
throw new ConnectFailure(
|
|
2395
|
+
"no_repo",
|
|
2396
|
+
`No folder chosen. Run ${rerun} --repo <path> to name one.`
|
|
2397
|
+
);
|
|
2398
|
+
const picks = parsePicks(answer, found.length);
|
|
2399
|
+
if (picks) return picks.map((n) => found[n - 1]);
|
|
2400
|
+
say(` Type numbers from 1 to ${found.length}, like 1,3.`);
|
|
2401
|
+
}
|
|
2402
|
+
}
|
|
2403
|
+
async function reposFor(argv) {
|
|
2404
|
+
const given = flags(argv, "--repo");
|
|
2405
|
+
if (given.length) {
|
|
2406
|
+
const repos = resolveRepos(given, gitTop);
|
|
2407
|
+
if (typeof repos === "string") throw new ConnectFailure("no_repo", repos);
|
|
2408
|
+
return repos;
|
|
2409
|
+
}
|
|
2410
|
+
const here = gitTop(process.cwd());
|
|
2411
|
+
if (here) return [{ label: basename4(here), path: here }];
|
|
2412
|
+
const home = homedir4();
|
|
2413
|
+
const found = findCheckouts(home);
|
|
2414
|
+
const rerun = rerunCommand(argv);
|
|
2415
|
+
if (!found.length || !process.stdin.isTTY || !process.stdout.isTTY)
|
|
2416
|
+
throw new ConnectFailure("no_repo", notACheckoutLine(process.cwd(), found, home, rerun));
|
|
2417
|
+
const prompt = createInterface2({ input: process.stdin, output: process.stdout });
|
|
2418
|
+
const closed = () => new ConnectFailure("no_repo", `No folder chosen. Run ${rerun} --repo <path> to name one.`);
|
|
2419
|
+
try {
|
|
2420
|
+
return await askRepos(found, home, rerun, askOrClosed(prompt, closed), out);
|
|
2421
|
+
} finally {
|
|
2422
|
+
prompt.close();
|
|
2423
|
+
}
|
|
2424
|
+
}
|
|
2425
|
+
function askOrClosed(prompt, closed) {
|
|
2426
|
+
return (question) => new Promise((resolve3, reject) => {
|
|
2427
|
+
const onClose = () => reject(closed());
|
|
2428
|
+
prompt.once("close", onClose);
|
|
2429
|
+
prompt.question(question).then(
|
|
2430
|
+
(answer) => {
|
|
2431
|
+
prompt.off("close", onClose);
|
|
2432
|
+
resolve3(answer);
|
|
2433
|
+
},
|
|
2434
|
+
(err) => {
|
|
2435
|
+
prompt.off("close", onClose);
|
|
2436
|
+
reject(err);
|
|
2437
|
+
}
|
|
2438
|
+
);
|
|
2439
|
+
});
|
|
2440
|
+
}
|
|
2441
|
+
function gitTop(path) {
|
|
2442
|
+
try {
|
|
2443
|
+
return execFileSync4("git", ["-C", path, "rev-parse", "--show-toplevel"], {
|
|
2444
|
+
encoding: "utf-8",
|
|
2445
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
2446
|
+
}).trim();
|
|
2447
|
+
} catch {
|
|
2448
|
+
return null;
|
|
2449
|
+
}
|
|
2450
|
+
}
|
|
2451
|
+
async function t3Answers(t3Url) {
|
|
2452
|
+
try {
|
|
2453
|
+
await readEnvironment(t3Url);
|
|
2454
|
+
return true;
|
|
2455
|
+
} catch {
|
|
2456
|
+
return false;
|
|
2457
|
+
}
|
|
2458
|
+
}
|
|
2459
|
+
function harnessLine(h) {
|
|
2460
|
+
const version = h.version ? ` ${h.version}` : "";
|
|
2461
|
+
const account = h.signedIn ? h.account ?? "signed in" : "signed out";
|
|
2462
|
+
return `${h.name}${version}, ${account}${h.experimental ? " (experimental)" : ""}`;
|
|
2463
|
+
}
|
|
2464
|
+
async function runSteps(steps, run2 = (command) => void execFileSync4(command[0], command.slice(1), { stdio: "ignore", timeout: 15e3 }), wait = (ms) => new Promise((r) => setTimeout(r, ms))) {
|
|
2465
|
+
for (const step of steps) {
|
|
2466
|
+
const tries = step.tries ?? 1;
|
|
2467
|
+
for (let attempt = 1; ; attempt++) {
|
|
2468
|
+
try {
|
|
2469
|
+
run2(step.command);
|
|
2470
|
+
break;
|
|
2471
|
+
} catch (err) {
|
|
2472
|
+
if (step.mayFail) break;
|
|
2473
|
+
if (attempt >= tries) throw err;
|
|
2474
|
+
await wait(1e3);
|
|
2475
|
+
}
|
|
2476
|
+
}
|
|
2477
|
+
}
|
|
2478
|
+
}
|
|
2479
|
+
async function installService(kind, argv, attempt) {
|
|
2480
|
+
if (argv.includes("--no-service")) {
|
|
2481
|
+
out(` Run ${dim("cloop box run")} to go live.`);
|
|
2482
|
+
return;
|
|
2483
|
+
}
|
|
2484
|
+
attempt.step = "service_write";
|
|
2485
|
+
const npxBeside = join5(dirname4(process.execPath), "npx");
|
|
2486
|
+
const program = programFor(
|
|
2487
|
+
process.argv[1] ?? "cloop",
|
|
2488
|
+
process.execPath,
|
|
2489
|
+
existsSync2(npxBeside) ? npxBeside : which("npx"),
|
|
2490
|
+
VERSION
|
|
2491
|
+
);
|
|
2492
|
+
if (typeof program === "string") throw new ConnectFailure("npx_missing", program);
|
|
2493
|
+
const unit = unitFor({
|
|
2494
|
+
platform: process.platform,
|
|
2495
|
+
kind,
|
|
2496
|
+
home: homedir4(),
|
|
2497
|
+
program,
|
|
2498
|
+
env: unitEnv(process.env),
|
|
2499
|
+
uid: process.getuid?.() ?? 0,
|
|
2500
|
+
...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
|
|
2501
|
+
});
|
|
2502
|
+
mkdirSync4(join5(unit.path, ".."), { recursive: true });
|
|
2503
|
+
writeFileSync4(unit.path, unit.contents);
|
|
2504
|
+
if (argv.includes("--no-start")) {
|
|
2505
|
+
out(
|
|
2506
|
+
` Service: wrote ${unit.path}. Start it with: ${dim(unit.start.map((step) => step.command.join(" ")).join(" && "))}`
|
|
2507
|
+
);
|
|
2508
|
+
return;
|
|
2509
|
+
}
|
|
2510
|
+
attempt.step = "service_start";
|
|
2511
|
+
const since = Date.now();
|
|
2512
|
+
try {
|
|
2513
|
+
if (existsSync2(unit.retire.path)) {
|
|
2514
|
+
out(` This computer is one runner, so connect stops and removes ${unit.retire.path}.`);
|
|
2515
|
+
await runSteps(unit.retire.steps);
|
|
2516
|
+
rmSync(unit.retire.path, { force: true });
|
|
2517
|
+
}
|
|
2518
|
+
await runSteps(unit.start);
|
|
2519
|
+
} catch (err) {
|
|
2520
|
+
throw new ConnectFailure(
|
|
2521
|
+
"service_start_failed",
|
|
2522
|
+
`Wrote ${unit.path} but could not start it: ${err instanceof Error ? err.message : String(err)}`
|
|
2523
|
+
);
|
|
2524
|
+
}
|
|
2525
|
+
attempt.step = "first_connect";
|
|
2526
|
+
if (!await awaitDaemon(since)) {
|
|
2527
|
+
out(
|
|
2528
|
+
`${red("\u2717")} ${unit.path} started, but the runner did not reach Cloop within 15 s. Its last log lines:`
|
|
2529
|
+
);
|
|
2530
|
+
try {
|
|
2531
|
+
out(
|
|
2532
|
+
execFileSync4(unit.tail[0], unit.tail.slice(1), {
|
|
2533
|
+
encoding: "utf-8",
|
|
2534
|
+
timeout: 5e3
|
|
2535
|
+
})
|
|
2536
|
+
);
|
|
2537
|
+
} catch {
|
|
2538
|
+
out(` (no log yet; run ${unit.logs})`);
|
|
2539
|
+
}
|
|
2540
|
+
throw new ConnectFailure("first_connect_timeout", "the runner did not reach Cloop", true);
|
|
2541
|
+
}
|
|
2542
|
+
out(` Service: ${unit.path}, started and connected. Logs: ${dim(unit.logs)}`);
|
|
2543
|
+
}
|
|
2544
|
+
async function connectT3(argv, attempt) {
|
|
2545
|
+
const previous = readRunnerConfig();
|
|
2546
|
+
const t3Url = (flag(argv, "--t3-url") ?? DEFAULT_T3_URL).replace(/\/+$/, "");
|
|
2547
|
+
const t3Bin = flag(argv, "--t3-bin");
|
|
2548
|
+
const cfg = await connectBox({
|
|
2549
|
+
readEnvironment: async () => {
|
|
2550
|
+
const environment = await readEnvironment(t3Url);
|
|
2551
|
+
out(
|
|
2552
|
+
`${bold("Cloop runner")} Connecting ${environment.label} (T3 ${environment.serverVersion}) to Cloop.`
|
|
2553
|
+
);
|
|
2554
|
+
return environment;
|
|
2555
|
+
},
|
|
2556
|
+
mintSession: async () => {
|
|
2557
|
+
attempt.step = "t3_pair";
|
|
2558
|
+
try {
|
|
2559
|
+
return await mintSession(t3Url, t3Bin ? { bin: t3Bin } : {});
|
|
2560
|
+
} catch (err) {
|
|
2561
|
+
throw new ConnectFailure(
|
|
2562
|
+
"t3_pair_failed",
|
|
2563
|
+
err instanceof Error ? err.message : String(err)
|
|
2564
|
+
);
|
|
2565
|
+
}
|
|
2566
|
+
},
|
|
2567
|
+
deviceLogin: async (environment) => {
|
|
2568
|
+
attempt.step = "login";
|
|
2569
|
+
attempt.deviceToken = await deviceLogin({
|
|
2570
|
+
origin: getOrigin(),
|
|
2571
|
+
deviceName: flag(argv, "--name") ?? shortMachineName(),
|
|
2572
|
+
device: {
|
|
2573
|
+
kind: "workstation",
|
|
2574
|
+
environmentId: environment.environmentId,
|
|
2575
|
+
label: environment.label,
|
|
2576
|
+
version: environment.serverVersion
|
|
2577
|
+
}
|
|
2578
|
+
});
|
|
2579
|
+
return attempt.deviceToken;
|
|
2580
|
+
},
|
|
2581
|
+
writeBoxConfig: (cfg2) => writeBoxConfig({ ...cfg2, origin: getOrigin() })
|
|
2582
|
+
});
|
|
2583
|
+
await revokeReplaced(previous, "workstation", (t) => revokeOwnDevice(getOrigin(), t), out);
|
|
2584
|
+
out(
|
|
2585
|
+
`${bold("Cloop runner")} T3 ${cfg.label} paired with scope ${cfg.scope}, until ${cfg.expiresAt.slice(0, 10)}.`
|
|
2586
|
+
);
|
|
2587
|
+
const driver = new T3Driver({
|
|
2588
|
+
client: () => new T3Client(cfg.t3Url, cfg.token),
|
|
2589
|
+
t3Bin: cfg.t3Bin
|
|
2590
|
+
});
|
|
2591
|
+
const report = await runBoxTool({ driver }, "status", {});
|
|
2592
|
+
if (report.ok) {
|
|
2593
|
+
const value = report.value;
|
|
2594
|
+
for (const h of value.harnesses) {
|
|
2595
|
+
out(` ${h.signedIn ? "\u25CF" : "\u25CB"} ${h.name}${h.account ? dim(` ${h.account}`) : ""}`);
|
|
2596
|
+
}
|
|
2597
|
+
out(` ${value.threads.unsettled} open threads, ${value.threads.running} running.`);
|
|
2598
|
+
} else {
|
|
2599
|
+
out(`${red("\u2717")} Status failed: ${report.error}`);
|
|
2600
|
+
}
|
|
2601
|
+
await installService("workstation", argv, attempt);
|
|
2602
|
+
}
|
|
2603
|
+
async function connectLocal(driver, found, argv, attempt) {
|
|
2604
|
+
attempt.step = "repos";
|
|
2605
|
+
const repos = await reposFor(argv);
|
|
2606
|
+
const harness = driver === "claude-code" ? found.claude : found.codex;
|
|
2607
|
+
const bin = which(driver === "claude-code" ? "claude" : "codex") ?? (driver === "claude-code" ? "claude" : "codex");
|
|
2608
|
+
const previous = readRunnerConfig();
|
|
2609
|
+
const deviceName = flag(argv, "--name") ?? shortMachineName();
|
|
2610
|
+
const fallbackModels = driver === "claude-code" ? flag(argv, "--fallback-model") ?? (previous && isLocal(previous) ? previous.fallbackModels : void 0) ?? DEFAULT_FALLBACK_MODEL : void 0;
|
|
2611
|
+
const device = {
|
|
2612
|
+
kind: "local",
|
|
2613
|
+
environmentId: previous && isLocal(previous) ? previous.environmentId : `local:${randomUUID2()}`,
|
|
2614
|
+
label: deviceName,
|
|
2615
|
+
version: `${harness.name} ${harness.version ?? ""}`.trim()
|
|
2616
|
+
};
|
|
2617
|
+
out(
|
|
2618
|
+
`${bold("Cloop runner")} Connecting ${deviceName} as a Local runner with ${harnessLine(harness)}.`
|
|
2619
|
+
);
|
|
2620
|
+
attempt.step = "login";
|
|
2621
|
+
const deviceToken = await deviceLogin({ origin: getOrigin(), deviceName, device });
|
|
2622
|
+
attempt.deviceToken = deviceToken;
|
|
2623
|
+
const cfg = {
|
|
2624
|
+
driver,
|
|
2625
|
+
environmentId: device.environmentId,
|
|
2626
|
+
label: deviceName,
|
|
2627
|
+
deviceToken,
|
|
2628
|
+
repos,
|
|
2629
|
+
bin,
|
|
2630
|
+
origin: getOrigin(),
|
|
2631
|
+
...fallbackModels ? { fallbackModels } : {}
|
|
2632
|
+
};
|
|
2633
|
+
writeBoxConfig(cfg);
|
|
2634
|
+
await revokeReplaced(previous, "local", (t) => revokeOwnDevice(getOrigin(), t), out);
|
|
2635
|
+
const others = [found.claude, found.codex].filter(
|
|
2636
|
+
(h) => Boolean(h) && h !== harness
|
|
2637
|
+
);
|
|
2638
|
+
out(
|
|
2639
|
+
`${bold("Cloop runner")} ${deviceName} is a Local runner: ${[harness, ...others].map(harnessLine).join("; ")}.`
|
|
2640
|
+
);
|
|
2641
|
+
out(` Repos: ${repos.map((r) => `${r.label} (${r.path})`).join(", ")}`);
|
|
2642
|
+
if (fallbackModels)
|
|
2643
|
+
out(
|
|
2644
|
+
` Fallback model: ${fallbackModels}, when Claude Code's default model is at its limit. Change it with --fallback-model.`
|
|
2645
|
+
);
|
|
2646
|
+
await installService("local", argv, attempt);
|
|
2647
|
+
}
|
|
2648
|
+
async function detect(probes) {
|
|
2649
|
+
const [t3, claude, codex] = await Promise.all([probes.t3(), probes.claude(), probes.codex()]);
|
|
2650
|
+
return { t3, claude, codex };
|
|
2651
|
+
}
|
|
2652
|
+
function harnessesFound(found) {
|
|
2653
|
+
return [
|
|
2654
|
+
...found.t3 ? ["t3"] : [],
|
|
2655
|
+
...found.claude ? ["claude-code"] : [],
|
|
2656
|
+
...found.codex ? ["codex"] : []
|
|
2657
|
+
];
|
|
2658
|
+
}
|
|
2659
|
+
var MODEL_LIST = /^[A-Za-z0-9][\w.:[\]-]*(,[A-Za-z0-9][\w.:[\]-]*)*$/;
|
|
2660
|
+
async function connect(argv, attempt) {
|
|
2661
|
+
const forced = flag(argv, "--driver") ?? process.env.CLOOP_DRIVER;
|
|
2662
|
+
if (forced && !["t3", "claude-code", "codex"].includes(forced))
|
|
2663
|
+
throw new ConnectFailure("bad_flag", "--driver is t3, claude-code, or codex.");
|
|
2664
|
+
const fallback = flag(argv, "--fallback-model");
|
|
2665
|
+
if (fallback !== void 0 && !MODEL_LIST.test(fallback))
|
|
2666
|
+
throw new ConnectFailure(
|
|
2667
|
+
"bad_flag",
|
|
2668
|
+
"--fallback-model takes model names, comma-separated, like opus or opus,sonnet."
|
|
2669
|
+
);
|
|
2670
|
+
const t3Url = (flag(argv, "--t3-url") ?? DEFAULT_T3_URL).replace(/\/+$/, "");
|
|
2671
|
+
const found = await detect({
|
|
2672
|
+
t3: () => forced && forced !== "t3" ? Promise.resolve(false) : t3Answers(t3Url),
|
|
2673
|
+
claude: () => probeClaude(),
|
|
2674
|
+
codex: () => probeCodex()
|
|
2675
|
+
});
|
|
2676
|
+
attempt.harnesses = harnessesFound(found);
|
|
2677
|
+
const workstation = isWorkstation(readRunnerConfig(), boxServiceInstalled());
|
|
2678
|
+
const choice = chooseDriver(found, forced, workstation);
|
|
2679
|
+
if (!choice.ok) throw new ConnectFailure(choice.code, choice.line);
|
|
2680
|
+
await connectChosen(choice.driver, attempt, {
|
|
2681
|
+
t3: () => connectT3(argv, attempt),
|
|
2682
|
+
local: (driver) => connectLocal(driver, found, argv, attempt),
|
|
2683
|
+
fallback: () => fallbackDriver(found, forced, workstation),
|
|
2684
|
+
say: (line2) => out(`${bold("Cloop runner")} ${line2}`)
|
|
2685
|
+
});
|
|
2686
|
+
}
|
|
2687
|
+
async function connectCommand(argv) {
|
|
2688
|
+
const attempt = newAttempt();
|
|
2689
|
+
let error = null;
|
|
2690
|
+
try {
|
|
2691
|
+
await connect(argv, attempt);
|
|
2692
|
+
} catch (err) {
|
|
2693
|
+
error = err instanceof ConnectFailure ? err.code : "unexpected";
|
|
2694
|
+
if (!(err instanceof ConnectFailure && err.shown))
|
|
2695
|
+
out(`${red("\u2717")} ${err instanceof Error ? err.message : String(err)}`);
|
|
2696
|
+
}
|
|
2697
|
+
await sendConnectReport(
|
|
2698
|
+
getOrigin(),
|
|
2699
|
+
connectReport(attempt, error, getMachine()),
|
|
2700
|
+
attempt.deviceToken
|
|
2701
|
+
);
|
|
2702
|
+
if (error) process.exit(1);
|
|
2703
|
+
}
|
|
2704
|
+
|
|
2705
|
+
export {
|
|
2706
|
+
T3Client,
|
|
2707
|
+
runBoxTool,
|
|
2708
|
+
threadsFilePath,
|
|
2709
|
+
runnerStatePath,
|
|
2710
|
+
writeRunnerState,
|
|
2711
|
+
lockThreadsFile,
|
|
2712
|
+
BoxWatch,
|
|
2713
|
+
tokenGone,
|
|
2714
|
+
revokeOwnDevice,
|
|
2715
|
+
T3Driver,
|
|
2716
|
+
localRunsFilePath,
|
|
2717
|
+
LocalDriver,
|
|
2718
|
+
probeClaude,
|
|
2719
|
+
DEFAULT_FALLBACK_MODEL,
|
|
2720
|
+
claudeDialect,
|
|
2721
|
+
probeCodex,
|
|
2722
|
+
codexDialect,
|
|
2723
|
+
boxPath,
|
|
2724
|
+
isLocal,
|
|
2725
|
+
readRunnerConfig,
|
|
2726
|
+
writeBoxConfig,
|
|
2727
|
+
DEFAULT_T3_URL,
|
|
2728
|
+
mintSession,
|
|
2729
|
+
connectBox,
|
|
2730
|
+
chooseDriver,
|
|
2731
|
+
fallbackDriver,
|
|
2732
|
+
isWorkstation,
|
|
2733
|
+
revokeReplaced,
|
|
2734
|
+
fallbackLine,
|
|
2735
|
+
connectChosen,
|
|
2736
|
+
systemdAssignment,
|
|
2737
|
+
systemdWord,
|
|
2738
|
+
programFor,
|
|
2739
|
+
awaitDaemon,
|
|
2740
|
+
unitEnv,
|
|
2741
|
+
installedService,
|
|
2742
|
+
unitFor,
|
|
2743
|
+
resolveRepos,
|
|
2744
|
+
findCheckouts,
|
|
2745
|
+
tilde,
|
|
2746
|
+
parsePicks,
|
|
2747
|
+
rerunCommand,
|
|
2748
|
+
notACheckoutLine,
|
|
2749
|
+
askRepos,
|
|
2750
|
+
askOrClosed,
|
|
2751
|
+
runSteps,
|
|
2752
|
+
detect,
|
|
2753
|
+
harnessesFound,
|
|
2754
|
+
connectCommand
|
|
2755
|
+
};
|