droidsembly 0.4.0-beta.3 → 0.4.0-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.it.md +7 -6
- package/README.md +7 -6
- package/bin/cubefarm.js +2 -296
- package/bin/droidsembly.js +304 -0
- package/bin/environment.d.ts +3 -0
- package/bin/environment.js +48 -0
- package/dist/assets/AccessibilitySettings-vd4x_sEq.js +30 -0
- package/dist/assets/{AppViewer-0Bly3EdB.js → AppViewer-BB9lvg-4.js} +1 -1
- package/dist/assets/{Balloon-B6odnAlm.js → Balloon-CWEK5uK2.js} +1 -1
- package/dist/assets/{Batched-CTJWq46z.js → Batched-yAiB-c-b.js} +1 -1
- package/dist/assets/{Birds-DSS0OIz9.js → Birds-ClBZkA83.js} +1 -1
- package/dist/assets/{Blimp-CZt6dddK.js → Blimp-VHMnVBQt.js} +1 -1
- package/dist/assets/{BufferGeometryUtils-CmpUrBC5.js → BufferGeometryUtils-B4Tnxtjb.js} +1 -1
- package/dist/assets/{Duck-BnRLkodp.js → Duck-CCThHMtF.js} +1 -1
- package/dist/assets/{Effects-Bkewth1L.js → Effects-BZfFy3yq.js} +1 -1
- package/dist/assets/{Fireworks-Cvn8YKWd.js → Fireworks-CxvvEwV_.js} +1 -1
- package/dist/assets/{Helicopter-BDrFQMNX.js → Helicopter-DXHDrTnQ.js} +1 -1
- package/dist/assets/{Hurricane-C8hyFXjx.js → Hurricane-WXNUxoUz.js} +1 -1
- package/dist/assets/{Kaiju-Bxxe9DG0.js → Kaiju-D-wVgKo-.js} +1 -1
- package/dist/assets/{Meteors-UdYL0Tbv.js → Meteors-DSr-7bEl.js} +1 -1
- package/dist/assets/{MissionConsole-DJRtojZP.js → MissionConsole-4G02S89d.js} +1 -1
- package/dist/assets/{Office-9Mank16i.js → Office-B_EroD2U.js} +44 -44
- package/dist/assets/{PhotoPanel-C_njIXp0.js → PhotoPanel-ByzwApow.js} +1 -1
- package/dist/assets/{PhotoScene-DwpeJjGe.js → PhotoScene-CW3yZkqH.js} +3 -3
- package/dist/assets/{Plane-DzvUAUYE.js → Plane-CT7-QFbA.js} +1 -1
- package/dist/assets/Pocket-B0o4siMl.js +2 -0
- package/dist/assets/{Rainbow-CV1rD6rW.js → Rainbow-DNvXfTl9.js} +1 -1
- package/dist/assets/{Roof-DSpKcGXK.js → Roof-yLX0ZK0x.js} +1 -1
- package/dist/assets/{Shell-GaQY3zre.js → Shell-lZOZ3aG8.js} +2 -2
- package/dist/assets/{Skywriting-D4B2ZvH7.js → Skywriting-N1GDZKYR.js} +1 -1
- package/dist/assets/TerminalView-cUAMhOxM.js +17 -0
- package/dist/assets/{ToyWorld-DeQUxcuy.js → ToyWorld-BYE8776A.js} +1 -1
- package/dist/assets/{Ufo-CitoxReu.js → Ufo-D_Wt75n1.js} +1 -1
- package/dist/assets/{Whale-Btx5ph-T.js → Whale-Kkz3B36R.js} +1 -1
- package/dist/assets/all-BMItClgN.js +11 -0
- package/dist/assets/{bloomMarks-DRhDp19k.js → bloomMarks-C22qSi5d.js} +1 -1
- package/dist/assets/{cheerRules-DWb8Qwzg.js → cheerRules-G9WFRB4C.js} +1 -1
- package/dist/assets/{cityLayout-aA2Ktgpu.js → cityLayout-C8f5-bpM.js} +1 -1
- package/dist/assets/{dogState-DY7tJEVD.js → dogState-9uong8D8.js} +1 -1
- package/dist/assets/{doors-BlKvxXVp.js → doors-DsKuGpOi.js} +1 -1
- package/dist/assets/{gallery-COKuWb9E.js → gallery-DSKvNkBq.js} +1 -1
- package/dist/assets/gate-D6_NXB1w.js +2 -0
- package/dist/assets/index-rznd4Djx.js +10 -0
- package/dist/assets/{instantReplay-BjoV6jrY.js → instantReplay-CiWMru53.js} +1 -1
- package/dist/assets/{interact-0jqx03Xr.js → interact-Bt-XX-z4.js} +1 -1
- package/dist/assets/{jsx-runtime-CXW0f58S.js → jsx-runtime-CZP6s5wa.js} +1 -1
- package/dist/assets/{kit-n-eqZ1AT.js → kit-CZEafHnz.js} +1 -1
- package/dist/assets/mic-DeYDrNoY.js +1 -0
- package/dist/assets/{photoMode-BybFMLKC.js → photoMode-BTxq9-gL.js} +1 -1
- package/dist/assets/{pipeline-BGPWXegt.js → pipeline-DNe3sjnP.js} +1 -1
- package/dist/assets/{rapier-CrXmTSyE.js → rapier-C-KFR0AR.js} +1 -1
- package/dist/assets/{rig-DfdntE8m.js → rig-B88WinIa.js} +1 -1
- package/dist/assets/{speechLanguage-DfsQvU9M.js → speechLanguage-Bq3BAswq.js} +1 -1
- package/dist/assets/store-9CvxLGNQ.js +5 -0
- package/dist/assets/useDayTime-Nrdy7kH1.js +1 -0
- package/dist/assets/useGraphics-Bhnj8CAm.js +1 -0
- package/dist/assets/voiceMessages-BF3P4sjw.js +1 -0
- package/dist/assets/{weatherState-BJVm5hU-.js → weatherState-CufaxiyU.js} +1 -1
- package/dist/index.html +3 -3
- package/dist-server/index.js +1251 -494
- package/dist-server/index.js.map +4 -4
- package/dist-server/ptyHost.js +6 -2
- package/dist-server/ptyHost.js.map +2 -2
- package/package.json +2 -2
- package/dist/assets/AccessibilitySettings-HB1JfQbh.js +0 -30
- package/dist/assets/Pocket-A1iI6Ivy.js +0 -2
- package/dist/assets/TerminalView-DhmLqjYn.js +0 -17
- package/dist/assets/all-gw-szDg1.js +0 -11
- package/dist/assets/gate-D0uU0wv5.js +0 -2
- package/dist/assets/index-CDJgPTOC.js +0 -10
- package/dist/assets/mic-BnAa4E99.js +0 -1
- package/dist/assets/store-CXLtXw8e.js +0 -5
- package/dist/assets/useDayTime-BjBDzh_t.js +0 -1
- package/dist/assets/useGraphics-Bg6L4EdS.js +0 -1
- package/dist/assets/voiceMessages-CFLyZLZ4.js +0 -1
package/dist-server/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// server/index.ts
|
|
2
2
|
import http3 from "node:http";
|
|
3
|
-
import
|
|
4
|
-
import
|
|
3
|
+
import path23 from "node:path";
|
|
4
|
+
import fs23 from "node:fs";
|
|
5
5
|
import express from "express";
|
|
6
6
|
import { WebSocketServer } from "ws";
|
|
7
7
|
import { z as z3 } from "zod";
|
|
@@ -78,9 +78,9 @@ function standupLine(count, part) {
|
|
|
78
78
|
}
|
|
79
79
|
|
|
80
80
|
// server/config.ts
|
|
81
|
-
import
|
|
82
|
-
import
|
|
83
|
-
import
|
|
81
|
+
import fs2 from "node:fs";
|
|
82
|
+
import os2 from "node:os";
|
|
83
|
+
import path2 from "node:path";
|
|
84
84
|
|
|
85
85
|
// shared/types.ts
|
|
86
86
|
var FLOOR_SEATS = 15;
|
|
@@ -89,18 +89,52 @@ var CEO_ID = "ceo";
|
|
|
89
89
|
var DEFAULT_DOG_NAME = "Biscuit";
|
|
90
90
|
var INSTALL_STEP = "Installing dependencies";
|
|
91
91
|
|
|
92
|
+
// bin/environment.js
|
|
93
|
+
import fs from "node:fs";
|
|
94
|
+
import os from "node:os";
|
|
95
|
+
import path from "node:path";
|
|
96
|
+
function officeEnv(env, legacyName) {
|
|
97
|
+
const canonical = legacyName.replace(/^(SWARM|CUBEFARM)_/, "DROIDSEMBLY_");
|
|
98
|
+
return env[canonical] ?? env[legacyName];
|
|
99
|
+
}
|
|
100
|
+
function directoryExists(file) {
|
|
101
|
+
try {
|
|
102
|
+
fs.lstatSync(file);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
if (error.code === "ENOENT") return false;
|
|
105
|
+
throw error;
|
|
106
|
+
}
|
|
107
|
+
if (!fs.statSync(file).isDirectory()) throw new Error("Office home path is not a directory. Set DROIDSEMBLY_HOME explicitly.");
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
function officeHome(env = process.env, home = os.homedir(), exists2 = directoryExists) {
|
|
111
|
+
const explicit = officeEnv(env, "SWARM_HOME");
|
|
112
|
+
if (explicit !== void 0) {
|
|
113
|
+
if (!explicit.trim()) throw new Error("DROIDSEMBLY_HOME / SWARM_HOME must not be empty. Select an office folder explicitly.");
|
|
114
|
+
const selected = path.resolve(explicit);
|
|
115
|
+
exists2(selected);
|
|
116
|
+
return selected;
|
|
117
|
+
}
|
|
118
|
+
const current = path.resolve(home, ".droidsembly");
|
|
119
|
+
const legacy = path.resolve(home, ".cubefarm");
|
|
120
|
+
const hasCurrent = exists2(current);
|
|
121
|
+
const hasLegacy = exists2(legacy);
|
|
122
|
+
if (hasCurrent && hasLegacy) throw new Error("Both .droidsembly and .cubefarm exist. Set DROIDSEMBLY_HOME (or SWARM_HOME) explicitly; no data was merged or moved.");
|
|
123
|
+
return hasLegacy ? legacy : current;
|
|
124
|
+
}
|
|
125
|
+
|
|
92
126
|
// server/config.ts
|
|
93
|
-
var PORT = Number(process.env
|
|
94
|
-
var HOST = process.env
|
|
95
|
-
var VERSION = JSON.parse(
|
|
96
|
-
var HOME_DIR =
|
|
97
|
-
var WORKSPACE_ROOT =
|
|
98
|
-
var DEMO = process.argv.includes("--demo") ||
|
|
127
|
+
var PORT = Number(officeEnv(process.env, "SWARM_PORT") ?? 4317);
|
|
128
|
+
var HOST = officeEnv(process.env, "SWARM_HOST")?.trim().replace(/^\[|\]$/g, "") || "127.0.0.1";
|
|
129
|
+
var VERSION = JSON.parse(fs2.readFileSync(path2.resolve(import.meta.dirname, "..", "package.json"), "utf8")).version;
|
|
130
|
+
var HOME_DIR = officeHome();
|
|
131
|
+
var WORKSPACE_ROOT = path2.join(HOME_DIR, "workspaces");
|
|
132
|
+
var DEMO = process.argv.includes("--demo") || ["1", "true"].includes(officeEnv(process.env, "SWARM_DEMO") ?? "");
|
|
99
133
|
var DEMO_MAX = { floors: 20, agents: FLOOR_SEATS };
|
|
100
134
|
function demoScale(argv, env) {
|
|
101
135
|
const read = (flag, name) => {
|
|
102
136
|
const i = argv.findIndex((a) => a === flag || a.startsWith(`${flag}=`));
|
|
103
|
-
const raw = i < 0 ? env
|
|
137
|
+
const raw = i < 0 ? officeEnv(env, name) : argv[i].includes("=") ? argv[i].slice(flag.length + 1) : argv[i + 1];
|
|
104
138
|
const n = Number(raw);
|
|
105
139
|
return raw === void 0 || raw === "" || !Number.isFinite(n) ? null : Math.round(n);
|
|
106
140
|
};
|
|
@@ -111,7 +145,7 @@ function demoScale(argv, env) {
|
|
|
111
145
|
return { floors: clamp3(floors ?? 2, DEMO_MAX.floors), agents: clamp3(agents ?? 6, DEMO_MAX.agents) };
|
|
112
146
|
}
|
|
113
147
|
var DEMO_SCALE = DEMO ? demoScale(process.argv, process.env) : null;
|
|
114
|
-
var STATE_FILE =
|
|
148
|
+
var STATE_FILE = path2.join(HOME_DIR, DEMO ? DEMO_SCALE ? `demo-${DEMO_SCALE.floors}x${DEMO_SCALE.agents}-state.json` : "demo-state.json" : "state.json");
|
|
115
149
|
function envPort(value, fallback) {
|
|
116
150
|
const n = Number(value);
|
|
117
151
|
return value && Number.isInteger(n) && n >= 1024 && n <= 65e3 ? n : fallback;
|
|
@@ -125,7 +159,7 @@ function localAddress(host) {
|
|
|
125
159
|
if (h === "0.0.0.0" || h === "::" || h === "") return "127.0.0.1";
|
|
126
160
|
return h.includes(":") ? `[${h}]` : h;
|
|
127
161
|
}
|
|
128
|
-
function networkUrls(host, port, ifaces =
|
|
162
|
+
function networkUrls(host, port, ifaces = os2.networkInterfaces()) {
|
|
129
163
|
if (localAddress(host) !== "127.0.0.1" || isLoopback(host)) return [];
|
|
130
164
|
return Object.values(ifaces).flat().filter((i) => i && i.family === "IPv4" && !i.internal).map((i) => `http://${i.address}:${port}`);
|
|
131
165
|
}
|
|
@@ -133,21 +167,21 @@ function envMinutes(value, fallback) {
|
|
|
133
167
|
const n = Number(value);
|
|
134
168
|
return value && Number.isFinite(n) && n > 0 ? n : fallback;
|
|
135
169
|
}
|
|
136
|
-
var PREVIEW_PORT = envPort(process.env
|
|
137
|
-
var PR_PREVIEW_IDLE_MS = envMinutes(process.env
|
|
170
|
+
var PREVIEW_PORT = envPort(officeEnv(process.env, "SWARM_PREVIEW_PORT"), 6300);
|
|
171
|
+
var PR_PREVIEW_IDLE_MS = envMinutes(officeEnv(process.env, "SWARM_PR_PREVIEW_IDLE_MIN"), 20) * 6e4;
|
|
138
172
|
var SYNC_INTERVAL_MS = 45e3;
|
|
139
173
|
var SCHEDULER_INTERVAL_MS = 8e3;
|
|
140
174
|
var DESK_SWEEP_INTERVAL_MS = 30 * 6e4;
|
|
141
175
|
var LOG_BUFFER = 600;
|
|
142
|
-
function defaultProjectsDir(appDir, home =
|
|
143
|
-
if (!appDir.split(/[\\/]/).includes("node_modules")) return
|
|
176
|
+
function defaultProjectsDir(appDir, home = os2.homedir()) {
|
|
177
|
+
if (!appDir.split(/[\\/]/).includes("node_modules")) return path2.resolve(appDir, "..");
|
|
144
178
|
const names = ["Projects", "projects", "code", "Code", "dev", "Developer", "src", "repos", "git", "GitHub"];
|
|
145
|
-
return names.map((n) =>
|
|
179
|
+
return names.map((n) => path2.join(home, n)).find((d) => fs2.existsSync(d)) ?? path2.join(home, "Projects");
|
|
146
180
|
}
|
|
147
181
|
|
|
148
182
|
// server/workspace.ts
|
|
149
|
-
import
|
|
150
|
-
import
|
|
183
|
+
import fs3 from "node:fs/promises";
|
|
184
|
+
import path3 from "node:path";
|
|
151
185
|
|
|
152
186
|
// server/exec.ts
|
|
153
187
|
import { execFile } from "node:child_process";
|
|
@@ -212,24 +246,24 @@ function withRepoLock(fullName, fn) {
|
|
|
212
246
|
locks.set(fullName, next);
|
|
213
247
|
return next;
|
|
214
248
|
}
|
|
215
|
-
var repoDir = (fullName) =>
|
|
216
|
-
var mainDir = (fullName) => localRoots.get(fullName.toLowerCase()) ??
|
|
217
|
-
var deskDir = (fullName, agentSlug) =>
|
|
249
|
+
var repoDir = (fullName) => path3.join(WORKSPACE_ROOT, fullName.replace("/", "__"));
|
|
250
|
+
var mainDir = (fullName) => localRoots.get(fullName.toLowerCase()) ?? path3.join(repoDir(fullName), "main");
|
|
251
|
+
var deskDir = (fullName, agentSlug) => path3.join(repoDir(fullName), "desks", agentSlug);
|
|
218
252
|
function setLocalPath(fullName, dir) {
|
|
219
|
-
if (dir) localRoots.set(fullName.toLowerCase(),
|
|
253
|
+
if (dir) localRoots.set(fullName.toLowerCase(), path3.resolve(dir));
|
|
220
254
|
else localRoots.delete(fullName.toLowerCase());
|
|
221
255
|
}
|
|
222
256
|
async function exists(p) {
|
|
223
|
-
return
|
|
257
|
+
return fs3.access(p).then(() => true).catch(() => false);
|
|
224
258
|
}
|
|
225
259
|
var LOCAL_EXCLUDES = [".playwright-mcp/", ".preview-tmp/"];
|
|
226
260
|
async function addLocalExcludes(main) {
|
|
227
|
-
const file =
|
|
228
|
-
const current = await
|
|
261
|
+
const file = path3.join(main, ".git", "info", "exclude");
|
|
262
|
+
const current = await fs3.readFile(file, "utf8").catch(() => "");
|
|
229
263
|
const missing = LOCAL_EXCLUDES.filter((l) => !current.split(/\r?\n/).includes(l));
|
|
230
264
|
if (missing.length === 0) return;
|
|
231
|
-
await
|
|
232
|
-
await
|
|
265
|
+
await fs3.mkdir(path3.dirname(file), { recursive: true });
|
|
266
|
+
await fs3.appendFile(file, `${current && !current.endsWith("\n") ? "\n" : ""}# added by cubefarm
|
|
233
267
|
${missing.join("\n")}
|
|
234
268
|
`);
|
|
235
269
|
}
|
|
@@ -237,10 +271,10 @@ var ensureLocalExcludes = (fullName) => addLocalExcludes(mainDir(fullName));
|
|
|
237
271
|
function ensureClone(fullName) {
|
|
238
272
|
return withRepoLock(fullName, async () => {
|
|
239
273
|
const dir = mainDir(fullName);
|
|
240
|
-
if (await exists(
|
|
274
|
+
if (await exists(path3.join(dir, ".git"))) {
|
|
241
275
|
await git(["fetch", "origin", "--prune"], { cwd: dir, timeoutMs: 18e4 });
|
|
242
276
|
} else {
|
|
243
|
-
await
|
|
277
|
+
await fs3.mkdir(path3.dirname(dir), { recursive: true });
|
|
244
278
|
await gh(["repo", "clone", fullName, dir], { timeoutMs: 6e5 });
|
|
245
279
|
}
|
|
246
280
|
await addLocalExcludes(dir);
|
|
@@ -284,7 +318,7 @@ function fileList(files, max = 3, maxChars = 120) {
|
|
|
284
318
|
async function syncMain(fullName, defaultBranch, opts) {
|
|
285
319
|
const dir = mainDir(fullName);
|
|
286
320
|
const result = await withRepoLock(fullName, async () => {
|
|
287
|
-
if (!await exists(
|
|
321
|
+
if (!await exists(path3.join(dir, ".git"))) return null;
|
|
288
322
|
const g = (args, timeoutMs) => git(args, { cwd: dir, timeoutMs });
|
|
289
323
|
let behind = 0;
|
|
290
324
|
try {
|
|
@@ -311,7 +345,7 @@ async function syncMain(fullName, defaultBranch, opts) {
|
|
|
311
345
|
return { status: `${behind} behind: local files are in the way${files.length ? `: ${fileList(files)}` : ""}`, behind, updatable: true };
|
|
312
346
|
}
|
|
313
347
|
const changed = (await g(["diff", "--name-only", before, "HEAD"])).split(/\r?\n/);
|
|
314
|
-
const install = changed.some((f) => f === "package.json" || f === "package-lock.json") && await exists(
|
|
348
|
+
const install = changed.some((f) => f === "package.json" || f === "package-lock.json") && await exists(path3.join(dir, "package.json"));
|
|
315
349
|
return { status: `updated to ${await g(["rev-parse", "--short", "HEAD"])}`, behind: 0, updatable: false, install };
|
|
316
350
|
} catch (err) {
|
|
317
351
|
return { status: `sync failed: ${err.message.split(/\r?\n/)[0].slice(0, 160)}`, behind, updatable: false };
|
|
@@ -333,33 +367,33 @@ function githubFromConfig(config) {
|
|
|
333
367
|
return m ? `${m[1]}/${m[2]}` : null;
|
|
334
368
|
}
|
|
335
369
|
async function inspectFolder(dir) {
|
|
336
|
-
const full =
|
|
337
|
-
const stat = await
|
|
370
|
+
const full = path3.resolve(dir);
|
|
371
|
+
const stat = await fs3.stat(full).catch(() => null);
|
|
338
372
|
if (!stat?.isDirectory()) throw new Error(`${full} is not a folder`);
|
|
339
|
-
const dotGit =
|
|
340
|
-
const gitStat = await
|
|
373
|
+
const dotGit = path3.join(full, ".git");
|
|
374
|
+
const gitStat = await fs3.stat(dotGit).catch(() => null);
|
|
341
375
|
let config = "";
|
|
342
|
-
if (gitStat?.isDirectory()) config = await
|
|
376
|
+
if (gitStat?.isDirectory()) config = await fs3.readFile(path3.join(dotGit, "config"), "utf8").catch(() => "");
|
|
343
377
|
else if (gitStat) {
|
|
344
|
-
const ref = (await
|
|
378
|
+
const ref = (await fs3.readFile(dotGit, "utf8").catch(() => "")).match(/gitdir:\s*(.+)/)?.[1]?.trim();
|
|
345
379
|
if (ref) {
|
|
346
|
-
const gitDir =
|
|
347
|
-
config = await
|
|
380
|
+
const gitDir = path3.resolve(full, ref);
|
|
381
|
+
config = await fs3.readFile(path3.join(gitDir, "config"), "utf8").catch(() => fs3.readFile(path3.join(gitDir, "..", "..", "config"), "utf8").catch(() => ""));
|
|
348
382
|
}
|
|
349
383
|
}
|
|
350
|
-
return { name:
|
|
384
|
+
return { name: path3.basename(full), path: full, git: !!gitStat, github: githubFromConfig(config), modified: stat.mtimeMs };
|
|
351
385
|
}
|
|
352
386
|
async function scanProjects(root) {
|
|
353
|
-
const entries = await
|
|
387
|
+
const entries = await fs3.readdir(root, { withFileTypes: true }).catch(() => {
|
|
354
388
|
throw new Error(`Can't read the projects folder ${root}`);
|
|
355
389
|
});
|
|
356
390
|
const dirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith(".") && e.name !== "node_modules");
|
|
357
|
-
const folders = await Promise.all(dirs.map((e) => inspectFolder(
|
|
391
|
+
const folders = await Promise.all(dirs.map((e) => inspectFolder(path3.join(root, e.name)).catch(() => null)));
|
|
358
392
|
return folders.filter((f) => !!f).sort((a, b) => b.modified - a.modified);
|
|
359
393
|
}
|
|
360
394
|
async function commitReadme(dir, title, description) {
|
|
361
|
-
const readme =
|
|
362
|
-
if (!await exists(readme)) await
|
|
395
|
+
const readme = path3.join(dir, "README.md");
|
|
396
|
+
if (!await exists(readme)) await fs3.writeFile(readme, `# ${title}
|
|
363
397
|
|
|
364
398
|
${description.trim()}
|
|
365
399
|
`);
|
|
@@ -373,7 +407,7 @@ ${description.trim()}
|
|
|
373
407
|
}
|
|
374
408
|
}
|
|
375
409
|
async function publishFolder(dir, opts) {
|
|
376
|
-
const full =
|
|
410
|
+
const full = path3.resolve(dir);
|
|
377
411
|
const info = await inspectFolder(full);
|
|
378
412
|
if (info.github) return info.github;
|
|
379
413
|
if (!info.git) await git(["init", "-b", "main"], { cwd: full });
|
|
@@ -382,7 +416,7 @@ async function publishFolder(dir, opts) {
|
|
|
382
416
|
() => false
|
|
383
417
|
);
|
|
384
418
|
if (!hasCommit) {
|
|
385
|
-
const files = (await
|
|
419
|
+
const files = (await fs3.readdir(full)).filter((f) => f !== ".git" && f !== "README.md");
|
|
386
420
|
if (files.length) {
|
|
387
421
|
throw new Error(`${info.name} has files but no commits yet. Commit what you want on GitHub first (git add, git commit), then publish it.`);
|
|
388
422
|
}
|
|
@@ -397,26 +431,26 @@ async function publishFolder(dir, opts) {
|
|
|
397
431
|
return out.match(/github\.com\/([^/\s]+\/[^/\s]+?)(?:\.git)?(?:\s|$)/)?.[1] ?? (await inspectFolder(full)).github ?? target;
|
|
398
432
|
}
|
|
399
433
|
async function createProject(root, name, opts) {
|
|
400
|
-
const dir =
|
|
434
|
+
const dir = path3.join(root, name);
|
|
401
435
|
if (await exists(dir)) {
|
|
402
|
-
const inside = await
|
|
436
|
+
const inside = await fs3.readdir(dir).catch(() => ["?"]);
|
|
403
437
|
if (inside.length) throw new Error(`${dir} already exists. Pick another name, or connect that folder instead.`);
|
|
404
438
|
}
|
|
405
|
-
await
|
|
439
|
+
await fs3.mkdir(dir, { recursive: true });
|
|
406
440
|
await git(["init", "-b", "main"], { cwd: dir });
|
|
407
441
|
await commitReadme(dir, name, opts.description ?? "");
|
|
408
442
|
const fullName = await publishFolder(dir, { name, ...opts });
|
|
409
443
|
return { fullName, path: dir };
|
|
410
444
|
}
|
|
411
445
|
async function removeDir(dir) {
|
|
412
|
-
await
|
|
446
|
+
await fs3.rm(dir, { recursive: true, force: true, maxRetries: 8, retryDelay: 250 });
|
|
413
447
|
}
|
|
414
448
|
var STALE_LOCK_MS = 10 * 6e4;
|
|
415
449
|
async function staleIndexLock(wt) {
|
|
416
|
-
const ref = (await
|
|
450
|
+
const ref = (await fs3.readFile(path3.join(wt, ".git"), "utf8").catch(() => "")).match(/gitdir:\s*(.+)/)?.[1]?.trim();
|
|
417
451
|
if (!ref) return null;
|
|
418
|
-
const lock =
|
|
419
|
-
const stat = await
|
|
452
|
+
const lock = path3.join(path3.resolve(wt, ref), "index.lock");
|
|
453
|
+
const stat = await fs3.stat(lock).catch(() => null);
|
|
420
454
|
return stat && Date.now() - stat.mtimeMs > STALE_LOCK_MS ? lock : null;
|
|
421
455
|
}
|
|
422
456
|
async function reuseDesk(wt, branch, ref) {
|
|
@@ -428,7 +462,7 @@ async function clearDeskFolder(wt) {
|
|
|
428
462
|
try {
|
|
429
463
|
await removeDir(wt);
|
|
430
464
|
} catch (err) {
|
|
431
|
-
const left = await
|
|
465
|
+
const left = await fs3.readdir(wt).catch(() => null);
|
|
432
466
|
if (left?.length !== 0) {
|
|
433
467
|
throw new Error(
|
|
434
468
|
`Could not clear the desk folder ${wt}: ${err.message}. A program started by the previous task is probably still running there. Close it and try again.`
|
|
@@ -454,19 +488,19 @@ async function setUpWorktree(main, wt, fullName, base, branch, note2) {
|
|
|
454
488
|
);
|
|
455
489
|
}
|
|
456
490
|
await git(["worktree", "prune"], { cwd: main });
|
|
457
|
-
const real = (p) =>
|
|
491
|
+
const real = (p) => fs3.realpath(p).catch(() => p);
|
|
458
492
|
const worktrees = await Promise.all(parseWorktrees(await git(["worktree", "list", "--porcelain"], { cwd: main })).map(async (w) => ({ ...w, path: await real(w.path) })));
|
|
459
493
|
const holder = branchHolder(worktrees, branch, await real(wt));
|
|
460
494
|
const local = holder ? null : branch;
|
|
461
495
|
if (holder) note2?.(`${branch} is checked out at ${holder}, so this desk works on it as a detached HEAD at ${ref}; push with git push origin HEAD:${branch}.`);
|
|
462
|
-
if (await exists(
|
|
496
|
+
if (await exists(path3.join(wt, ".git"))) {
|
|
463
497
|
try {
|
|
464
498
|
try {
|
|
465
499
|
await reuseDesk(wt, local, ref);
|
|
466
500
|
} catch (err) {
|
|
467
501
|
const lock = /index\.lock/.test(err.message) ? await staleIndexLock(wt) : null;
|
|
468
502
|
if (!lock) throw err;
|
|
469
|
-
await
|
|
503
|
+
await fs3.rm(lock, { force: true, maxRetries: 3 });
|
|
470
504
|
note2?.(`Removed a stale git lock (${lock}) left in the desk.`);
|
|
471
505
|
await reuseDesk(wt, local, ref);
|
|
472
506
|
}
|
|
@@ -482,12 +516,12 @@ async function setUpWorktree(main, wt, fullName, base, branch, note2) {
|
|
|
482
516
|
await clearDeskFolder(wt);
|
|
483
517
|
}
|
|
484
518
|
await git(["worktree", "prune"], { cwd: main });
|
|
485
|
-
await
|
|
519
|
+
await fs3.mkdir(path3.dirname(wt), { recursive: true });
|
|
486
520
|
await git(["worktree", "add", ...local ? ["-B", local] : ["--detach"], wt, ref], { cwd: main });
|
|
487
521
|
return wt;
|
|
488
522
|
}
|
|
489
523
|
function branchHolder(worktrees, branch, desk) {
|
|
490
|
-
return worktrees.find((w) => w.branch === branch && !samePath(w.path,
|
|
524
|
+
return worktrees.find((w) => w.branch === branch && !samePath(w.path, path3.resolve(desk)))?.path ?? null;
|
|
491
525
|
}
|
|
492
526
|
function removeDesk(fullName, agentSlug, main = mainDir(fullName)) {
|
|
493
527
|
return withRepoLock(fullName, async () => {
|
|
@@ -503,7 +537,7 @@ var OFFICE_BRANCH = /^(swarm\/issue-|qa\/pr-)/;
|
|
|
503
537
|
function parseWorktrees(porcelain) {
|
|
504
538
|
const out = [];
|
|
505
539
|
for (const line of porcelain.split(/\r?\n/)) {
|
|
506
|
-
if (line.startsWith("worktree ")) out.push({ path:
|
|
540
|
+
if (line.startsWith("worktree ")) out.push({ path: path3.resolve(line.slice(9)), branch: null, locked: false });
|
|
507
541
|
else if (!out.length) continue;
|
|
508
542
|
else if (line.startsWith("branch ")) out[out.length - 1].branch = line.slice(7).replace(/^refs\/heads\//, "");
|
|
509
543
|
else if (line === "locked" || line.startsWith("locked ")) out[out.length - 1].locked = true;
|
|
@@ -512,20 +546,20 @@ function parseWorktrees(porcelain) {
|
|
|
512
546
|
}
|
|
513
547
|
var samePath = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
514
548
|
function isOfficeDesk(p, fullName, root) {
|
|
515
|
-
const desks =
|
|
516
|
-
const repo =
|
|
517
|
-
const workspaces =
|
|
518
|
-
if (!samePath(
|
|
519
|
-
if (samePath(workspaces,
|
|
520
|
-
return
|
|
549
|
+
const desks = path3.dirname(p);
|
|
550
|
+
const repo = path3.dirname(desks);
|
|
551
|
+
const workspaces = path3.dirname(repo);
|
|
552
|
+
if (!samePath(path3.basename(desks), "desks") || !samePath(path3.basename(repo), fullName.replace("/", "__"))) return false;
|
|
553
|
+
if (samePath(workspaces, path3.resolve(root))) return true;
|
|
554
|
+
return path3.basename(workspaces) === "workspaces" && OLD_HOMES.some((h) => samePath(path3.basename(path3.dirname(workspaces)), h));
|
|
521
555
|
}
|
|
522
556
|
function planSweep(input, keep) {
|
|
523
|
-
const deskRoot =
|
|
524
|
-
const kept = (p) => keep.desks.some((slug2) => samePath(p,
|
|
557
|
+
const deskRoot = path3.join(path3.resolve(input.root), input.fullName.replace("/", "__"), "desks");
|
|
558
|
+
const kept = (p) => keep.desks.some((slug2) => samePath(p, path3.join(deskRoot, slug2)));
|
|
525
559
|
const worktrees = input.worktrees.slice(1).filter((w) => !w.locked && isOfficeDesk(w.path, input.fullName, input.root) && !kept(w.path));
|
|
526
560
|
const stays = input.worktrees.filter((w) => !worktrees.includes(w));
|
|
527
561
|
const folders = input.folders.filter((name) => {
|
|
528
|
-
const p =
|
|
562
|
+
const p = path3.join(deskRoot, name);
|
|
529
563
|
return !kept(p) && !input.worktrees.some((w) => samePath(w.path, p));
|
|
530
564
|
});
|
|
531
565
|
const branches = input.branches.filter((b) => OFFICE_BRANCH.test(b) && !keep.branches.includes(b) && !stays.some((w) => w.branch === b));
|
|
@@ -534,31 +568,31 @@ function planSweep(input, keep) {
|
|
|
534
568
|
async function inUse(dir) {
|
|
535
569
|
const probe = `${dir}.sweep`;
|
|
536
570
|
try {
|
|
537
|
-
await
|
|
571
|
+
await fs3.rename(dir, probe);
|
|
538
572
|
} catch (err) {
|
|
539
573
|
return err.code !== "ENOENT";
|
|
540
574
|
}
|
|
541
|
-
await
|
|
575
|
+
await fs3.rename(probe, dir);
|
|
542
576
|
return false;
|
|
543
577
|
}
|
|
544
578
|
var stamp = (d) => `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, "0")}${String(d.getDate()).padStart(2, "0")}`;
|
|
545
|
-
async function saveLeftovers(fullName, desk, label =
|
|
579
|
+
async function saveLeftovers(fullName, desk, label = path3.basename(desk)) {
|
|
546
580
|
const g = (args) => git(args, { cwd: desk, timeoutMs: 6e4 });
|
|
547
581
|
if (!await g(["rev-parse", "--verify", "-q", "HEAD"]).catch(() => "")) return null;
|
|
548
582
|
const dirty = await g(["status", "--porcelain", "--untracked-files=no"]);
|
|
549
583
|
const commits = Number(await g(["rev-list", "--count", "HEAD", "--not", "--remotes"]));
|
|
550
584
|
if (!dirty && !commits) return null;
|
|
551
|
-
const dir =
|
|
552
|
-
await
|
|
553
|
-
const tmp = await
|
|
585
|
+
const dir = path3.join(HOME_DIR, "leftovers", fullName.replace("/", "__"));
|
|
586
|
+
await fs3.mkdir(dir, { recursive: true });
|
|
587
|
+
const tmp = await fs3.mkdtemp(path3.join(dir, ".tmp-"));
|
|
554
588
|
try {
|
|
555
589
|
if (commits) await g(["format-patch", "-q", "-o", tmp, "HEAD", "--not", "--remotes"]);
|
|
556
|
-
if (dirty) await g(["diff", "HEAD", "--binary", `--output=${
|
|
557
|
-
const parts = (await
|
|
590
|
+
if (dirty) await g(["diff", "HEAD", "--binary", `--output=${path3.join(tmp, "zz-uncommitted.patch")}`]);
|
|
591
|
+
const parts = (await fs3.readdir(tmp)).sort();
|
|
558
592
|
const base = `${label}-${stamp(/* @__PURE__ */ new Date())}`;
|
|
559
|
-
let file =
|
|
560
|
-
for (let n = 2; await exists(file); n++) file =
|
|
561
|
-
await
|
|
593
|
+
let file = path3.join(dir, `${base}.patch`);
|
|
594
|
+
for (let n = 2; await exists(file); n++) file = path3.join(dir, `${base}-${n}.patch`);
|
|
595
|
+
await fs3.writeFile(file, Buffer.concat(await Promise.all(parts.map((p) => fs3.readFile(path3.join(tmp, p))))));
|
|
562
596
|
return file;
|
|
563
597
|
} finally {
|
|
564
598
|
await removeDir(tmp).catch(() => void 0);
|
|
@@ -568,16 +602,16 @@ function sweepDesks(fullName, keep) {
|
|
|
568
602
|
return withRepoLock(fullName, async () => {
|
|
569
603
|
const result = { desks: 0, folders: 0, branches: 0, patches: [], skipped: [] };
|
|
570
604
|
const main = mainDir(fullName);
|
|
571
|
-
if (!await exists(
|
|
605
|
+
if (!await exists(path3.join(main, ".git"))) return result;
|
|
572
606
|
const g = (args) => git(args, { cwd: main, timeoutMs: 6e4 });
|
|
573
607
|
await g(["worktree", "prune"]);
|
|
574
|
-
const real = (p) =>
|
|
608
|
+
const real = (p) => fs3.realpath(p).catch(() => p);
|
|
575
609
|
const worktrees = await Promise.all(parseWorktrees(await g(["worktree", "list", "--porcelain"])).map(async (w) => ({ ...w, path: await real(w.path) })));
|
|
576
610
|
const refs = await g(["for-each-ref", "--format=%(refname)", "refs/heads/swarm", "refs/heads/qa"]);
|
|
577
611
|
const branches = refs.split(/\r?\n/).filter(Boolean).map((r) => r.replace(/^refs\/heads\//, ""));
|
|
578
612
|
const root = await real(WORKSPACE_ROOT);
|
|
579
|
-
const deskRoot =
|
|
580
|
-
const folders = (await
|
|
613
|
+
const deskRoot = path3.join(root, fullName.replace("/", "__"), "desks");
|
|
614
|
+
const folders = (await fs3.readdir(deskRoot, { withFileTypes: true }).catch(() => [])).filter((e) => e.isDirectory()).map((e) => e.name);
|
|
581
615
|
const plan = planSweep({ fullName, root, worktrees, branches, folders }, keep);
|
|
582
616
|
const held = /* @__PURE__ */ new Set();
|
|
583
617
|
for (const wt of plan.worktrees) {
|
|
@@ -595,7 +629,7 @@ function sweepDesks(fullName, keep) {
|
|
|
595
629
|
}
|
|
596
630
|
await g(["worktree", "prune"]).catch(() => void 0);
|
|
597
631
|
for (const name of plan.folders) {
|
|
598
|
-
const dir =
|
|
632
|
+
const dir = path3.join(deskRoot, name);
|
|
599
633
|
try {
|
|
600
634
|
if (await inUse(dir)) throw new Error("in use");
|
|
601
635
|
await removeDir(dir);
|
|
@@ -619,12 +653,12 @@ async function dirSize(dir, concurrency = 8) {
|
|
|
619
653
|
const queue = [dir];
|
|
620
654
|
let active = 0;
|
|
621
655
|
const visit = async (d) => {
|
|
622
|
-
const entries = await
|
|
656
|
+
const entries = await fs3.readdir(d, { withFileTypes: true }).catch(() => []);
|
|
623
657
|
const sizes = await Promise.all(
|
|
624
658
|
entries.map((e) => {
|
|
625
|
-
const p =
|
|
659
|
+
const p = path3.join(d, e.name);
|
|
626
660
|
if (e.isDirectory()) queue.push(p);
|
|
627
|
-
return e.isFile() ?
|
|
661
|
+
return e.isFile() ? fs3.lstat(p).then((s2) => s2.size, () => 0) : 0;
|
|
628
662
|
})
|
|
629
663
|
);
|
|
630
664
|
for (const s2 of sizes) total += s2;
|
|
@@ -647,29 +681,29 @@ async function dirSize(dir, concurrency = 8) {
|
|
|
647
681
|
async function trimTargets(wt) {
|
|
648
682
|
const ignored = (await git(["ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--directory"], { cwd: wt })).split("\0").filter((p) => p.endsWith("/")).map((p) => p.slice(0, -1)).filter((p) => p.includes("/") ? p.endsWith("/node_modules") : TRIM_DIRS.includes(p));
|
|
649
683
|
const present = [];
|
|
650
|
-
for (const name of TRIM_DIRS) if ((await
|
|
684
|
+
for (const name of TRIM_DIRS) if ((await fs3.lstat(path3.join(wt, name)).catch(() => null))?.isDirectory()) present.push(name);
|
|
651
685
|
const candidates = [.../* @__PURE__ */ new Set([...ignored, ...present])];
|
|
652
686
|
if (candidates.length === 0) return [];
|
|
653
687
|
const tracked = (await git(["ls-files", "-z", "--", ...candidates], { cwd: wt })).split("\0").filter(Boolean);
|
|
654
688
|
return candidates.filter((c) => !tracked.some((f) => f.startsWith(`${c}/`)));
|
|
655
689
|
}
|
|
656
690
|
function trimDesk(fullName, agentSlug, stillIdle = () => true) {
|
|
657
|
-
return trimWorktree(deskDir(fullName, agentSlug),
|
|
691
|
+
return trimWorktree(deskDir(fullName, agentSlug), path3.join(repoDir(fullName), "trash"), agentSlug, fullName, stillIdle);
|
|
658
692
|
}
|
|
659
693
|
async function trimWorktree(wt, trash, name, lock, stillIdle) {
|
|
660
|
-
for (const old of await
|
|
661
|
-
if (old.startsWith(`${name}-`)) await removeDir(
|
|
694
|
+
for (const old of await fs3.readdir(trash).catch(() => [])) {
|
|
695
|
+
if (old.startsWith(`${name}-`)) await removeDir(path3.join(trash, old)).catch(() => void 0);
|
|
662
696
|
}
|
|
663
|
-
const bin =
|
|
697
|
+
const bin = path3.join(trash, `${name}-${Date.now()}`);
|
|
664
698
|
const moved = await withRepoLock(lock, async () => {
|
|
665
|
-
if (!stillIdle() || !await exists(
|
|
699
|
+
if (!stillIdle() || !await exists(path3.join(wt, ".git"))) return null;
|
|
666
700
|
const out = { removed: [], skipped: [] };
|
|
667
701
|
const targets = await trimTargets(wt);
|
|
668
702
|
for (const [i, rel2] of targets.entries()) {
|
|
669
703
|
if (!stillIdle()) break;
|
|
670
704
|
try {
|
|
671
|
-
await
|
|
672
|
-
await
|
|
705
|
+
await fs3.mkdir(bin, { recursive: true });
|
|
706
|
+
await fs3.rename(path3.join(wt, rel2), path3.join(bin, `${i}-${path3.basename(rel2)}`));
|
|
673
707
|
out.removed.push(rel2);
|
|
674
708
|
} catch {
|
|
675
709
|
out.skipped.push(rel2);
|
|
@@ -752,20 +786,20 @@ Write-Output $kill.Count`;
|
|
|
752
786
|
}
|
|
753
787
|
}
|
|
754
788
|
}
|
|
755
|
-
var MACHINES_DIR =
|
|
789
|
+
var MACHINES_DIR = path3.join(HOME_DIR, "machines");
|
|
756
790
|
var repoFolder = (fullName) => fullName.replace("/", "__");
|
|
757
|
-
var machineDir = (machine) =>
|
|
758
|
-
var machineClone = (machine, fullName) =>
|
|
759
|
-
var machineDesk = (machine, fullName) =>
|
|
760
|
-
var machineTmp = (machine) =>
|
|
791
|
+
var machineDir = (machine) => path3.join(MACHINES_DIR, machine);
|
|
792
|
+
var machineClone = (machine, fullName) => path3.join(machineDir(machine), "repos", repoFolder(fullName));
|
|
793
|
+
var machineDesk = (machine, fullName) => path3.join(machineDir(machine), "work", repoFolder(fullName));
|
|
794
|
+
var machineTmp = (machine) => path3.join(machineDir(machine), "tmp");
|
|
761
795
|
var machineLock = (machine, fullName) => `machine:${machine}:${fullName}`;
|
|
762
796
|
async function ensureMachineClone(machine, fullName) {
|
|
763
797
|
const clone = machineClone(machine, fullName);
|
|
764
|
-
if (await exists(
|
|
798
|
+
if (await exists(path3.join(clone, ".git"))) return clone;
|
|
765
799
|
await removeDir(clone).catch(() => void 0);
|
|
766
|
-
await
|
|
800
|
+
await fs3.mkdir(path3.dirname(clone), { recursive: true });
|
|
767
801
|
const main = mainDir(fullName);
|
|
768
|
-
const origin = await exists(
|
|
802
|
+
const origin = await exists(path3.join(main, ".git")) ? await git(["remote", "get-url", "origin"], { cwd: main }).catch(() => "") : "";
|
|
769
803
|
if (origin) await git(["clone", "-q", "--no-checkout", "--reference-if-able", main, "--dissociate", origin, clone], { timeoutMs: 6e5 });
|
|
770
804
|
else await gh(["repo", "clone", fullName, clone, "--", "--no-checkout"], { timeoutMs: 6e5 });
|
|
771
805
|
await addLocalExcludes(clone);
|
|
@@ -775,7 +809,7 @@ function prepareMachineDesk(machine, fullName, base, branch, note2) {
|
|
|
775
809
|
return withRepoLock(machineLock(machine, fullName), async () => setUpWorktree(await ensureMachineClone(machine, fullName), machineDesk(machine, fullName), fullName, base, branch, note2));
|
|
776
810
|
}
|
|
777
811
|
function trimMachineDesk(machine, fullName, stillIdle = () => true) {
|
|
778
|
-
return trimWorktree(machineDesk(machine, fullName),
|
|
812
|
+
return trimWorktree(machineDesk(machine, fullName), path3.join(machineDir(machine), "trash"), repoFolder(fullName), machineLock(machine, fullName), stillIdle);
|
|
779
813
|
}
|
|
780
814
|
function releaseMachine(machine, fullName, port, keep = { pids: [], markers: [] }) {
|
|
781
815
|
return releaseDirs([machineDesk(machine, fullName)], port, keep);
|
|
@@ -783,7 +817,7 @@ function releaseMachine(machine, fullName, port, keep = { pids: [], markers: []
|
|
|
783
817
|
function sweepMachine(machine, fullName, keep) {
|
|
784
818
|
return withRepoLock(machineLock(machine, fullName), async () => {
|
|
785
819
|
const clone = machineClone(machine, fullName);
|
|
786
|
-
if (!await exists(
|
|
820
|
+
if (!await exists(path3.join(clone, ".git"))) return 0;
|
|
787
821
|
const g = (args) => git(args, { cwd: clone, timeoutMs: 6e4 });
|
|
788
822
|
await g(["worktree", "prune"]);
|
|
789
823
|
const out = parseWorktrees(await g(["worktree", "list", "--porcelain"])).map((w) => w.branch);
|
|
@@ -801,8 +835,8 @@ async function removeMachine(machine) {
|
|
|
801
835
|
if (!await exists(dir)) return { removed: true, patches: [] };
|
|
802
836
|
if (await inUse(dir)) return { removed: false, patches: [] };
|
|
803
837
|
const patches = [];
|
|
804
|
-
for (const name of await
|
|
805
|
-
const patch = await saveLeftovers(name.replace("__", "/"),
|
|
838
|
+
for (const name of await fs3.readdir(path3.join(dir, "work")).catch(() => [])) {
|
|
839
|
+
const patch = await saveLeftovers(name.replace("__", "/"), path3.join(dir, "work", name), `machine-${machine}`).catch(() => null);
|
|
806
840
|
if (patch) patches.push(patch);
|
|
807
841
|
}
|
|
808
842
|
try {
|
|
@@ -813,7 +847,7 @@ async function removeMachine(machine) {
|
|
|
813
847
|
}
|
|
814
848
|
}
|
|
815
849
|
async function listMachines() {
|
|
816
|
-
return (await
|
|
850
|
+
return (await fs3.readdir(MACHINES_DIR, { withFileTypes: true }).catch(() => [])).filter((e) => e.isDirectory()).map((e) => e.name);
|
|
817
851
|
}
|
|
818
852
|
|
|
819
853
|
// server/backend.ts
|
|
@@ -846,17 +880,18 @@ async function repoMeta(fullName) {
|
|
|
846
880
|
"view",
|
|
847
881
|
fullName,
|
|
848
882
|
"--json",
|
|
849
|
-
"nameWithOwner,description,url,defaultBranchRef"
|
|
883
|
+
"nameWithOwner,description,url,defaultBranchRef,isPrivate"
|
|
850
884
|
]);
|
|
851
885
|
return {
|
|
886
|
+
isPrivate: raw.isPrivate,
|
|
852
887
|
nameWithOwner: raw.nameWithOwner,
|
|
853
888
|
description: raw.description ?? "",
|
|
854
889
|
url: raw.url,
|
|
855
890
|
defaultBranch: raw.defaultBranchRef?.name || "main"
|
|
856
891
|
};
|
|
857
892
|
}
|
|
858
|
-
async function listIssues(fullName) {
|
|
859
|
-
const raw = await
|
|
893
|
+
async function listIssues(fullName, read = readTwice) {
|
|
894
|
+
const raw = await read(
|
|
860
895
|
() => ghJson(
|
|
861
896
|
["issue", "list", "-R", fullName, "--state", "open", "--limit", "100", "--json", "number,title,body,url,labels,createdAt"],
|
|
862
897
|
SYNC_READ
|
|
@@ -906,10 +941,10 @@ function toPull(p) {
|
|
|
906
941
|
checkRun: checkRunOf(p.statusCheckRollup)
|
|
907
942
|
};
|
|
908
943
|
}
|
|
909
|
-
async function listPulls(fullName) {
|
|
944
|
+
async function listPulls(fullName, read = readTwice) {
|
|
910
945
|
const [open, merged2] = await Promise.all([
|
|
911
|
-
|
|
912
|
-
|
|
946
|
+
read(() => ghJson(["pr", "list", "-R", fullName, "--state", "open", "--limit", "50", "--json", PR_FIELDS], SYNC_READ)),
|
|
947
|
+
read(() => ghJson(["pr", "list", "-R", fullName, "--state", "merged", "--limit", "8", "--json", PR_FIELDS], SYNC_READ))
|
|
913
948
|
]);
|
|
914
949
|
return [...open, ...merged2].map(toPull);
|
|
915
950
|
}
|
|
@@ -1038,8 +1073,8 @@ async function uploadEvidence(fullName, filePath, data) {
|
|
|
1038
1073
|
}
|
|
1039
1074
|
|
|
1040
1075
|
// server/agentRunner.ts
|
|
1041
|
-
import
|
|
1042
|
-
import
|
|
1076
|
+
import fs6 from "node:fs";
|
|
1077
|
+
import path6 from "node:path";
|
|
1043
1078
|
import { query } from "@anthropic-ai/claude-agent-sdk";
|
|
1044
1079
|
|
|
1045
1080
|
// shared/aiUsage.ts
|
|
@@ -1173,15 +1208,15 @@ function codexUsage(sessionId, records, now2) {
|
|
|
1173
1208
|
}
|
|
1174
1209
|
|
|
1175
1210
|
// server/browser.ts
|
|
1176
|
-
import
|
|
1211
|
+
import fs4 from "node:fs";
|
|
1177
1212
|
import { createRequire } from "node:module";
|
|
1178
|
-
import
|
|
1179
|
-
import
|
|
1213
|
+
import os3 from "node:os";
|
|
1214
|
+
import path4 from "node:path";
|
|
1180
1215
|
function playwrightMcpCli() {
|
|
1181
1216
|
try {
|
|
1182
1217
|
const pkgFile = createRequire(import.meta.url).resolve("@playwright/mcp/package.json");
|
|
1183
|
-
const bin = JSON.parse(
|
|
1184
|
-
return
|
|
1218
|
+
const bin = JSON.parse(fs4.readFileSync(pkgFile, "utf8")).bin?.["playwright-mcp"] ?? "cli.js";
|
|
1219
|
+
return path4.join(path4.dirname(pkgFile), bin);
|
|
1185
1220
|
} catch {
|
|
1186
1221
|
return null;
|
|
1187
1222
|
}
|
|
@@ -1191,16 +1226,16 @@ function playwrightMcpCommand(cli, initScript, outputDir, node = process.execPat
|
|
|
1191
1226
|
}
|
|
1192
1227
|
function playwrightMcp(outputDir) {
|
|
1193
1228
|
const cli = playwrightMcpCli();
|
|
1194
|
-
return cli ? playwrightMcpCommand(cli,
|
|
1229
|
+
return cli ? playwrightMcpCommand(cli, path4.join(import.meta.dirname, "browser-init.js"), outputDir) : null;
|
|
1195
1230
|
}
|
|
1196
|
-
function chromePaths(platform = process.platform, env = process.env, home =
|
|
1231
|
+
function chromePaths(platform = process.platform, env = process.env, home = os3.homedir()) {
|
|
1197
1232
|
if (platform === "win32") {
|
|
1198
|
-
return [env.LOCALAPPDATA, env.PROGRAMFILES, env["PROGRAMFILES(X86)"]].filter((d) => !!d).map((d) =>
|
|
1233
|
+
return [env.LOCALAPPDATA, env.PROGRAMFILES, env["PROGRAMFILES(X86)"]].filter((d) => !!d).map((d) => path4.win32.join(d, "Google", "Chrome", "Application", "chrome.exe"));
|
|
1199
1234
|
}
|
|
1200
|
-
if (platform === "darwin") return ["/Applications/Google Chrome.app",
|
|
1235
|
+
if (platform === "darwin") return ["/Applications/Google Chrome.app", path4.posix.join(home, "Applications", "Google Chrome.app")];
|
|
1201
1236
|
return ["/opt/google/chrome/chrome", "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable"];
|
|
1202
1237
|
}
|
|
1203
|
-
var hasChrome = () => chromePaths().some((p) =>
|
|
1238
|
+
var hasChrome = () => chromePaths().some((p) => fs4.existsSync(p));
|
|
1204
1239
|
function browserProblem(mcp, chrome = hasChrome()) {
|
|
1205
1240
|
if (!mcp) return "\u26A0 The browser tool (@playwright/mcp) is not installed with Droidsembly: reinstall it, or run npx cubefarm doctor";
|
|
1206
1241
|
if (!chrome) return "\u26A0 Google Chrome not found, so this session cannot test in a browser: install it, or run npx cubefarm doctor";
|
|
@@ -1208,7 +1243,7 @@ function browserProblem(mcp, chrome = hasChrome()) {
|
|
|
1208
1243
|
}
|
|
1209
1244
|
|
|
1210
1245
|
// server/clis.ts
|
|
1211
|
-
import
|
|
1246
|
+
import fs5 from "node:fs";
|
|
1212
1247
|
|
|
1213
1248
|
// server/codexUsage.ts
|
|
1214
1249
|
var CODEX_USAGE_READER_SOURCE = String.raw`
|
|
@@ -1247,7 +1282,7 @@ function usageRecords(event) {
|
|
|
1247
1282
|
|
|
1248
1283
|
// server/clis.ts
|
|
1249
1284
|
import { createRequire as createRequire2 } from "node:module";
|
|
1250
|
-
import
|
|
1285
|
+
import path5 from "node:path";
|
|
1251
1286
|
|
|
1252
1287
|
// shared/models.ts
|
|
1253
1288
|
var isClaudeModel = (model2) => /^(claude|opus|sonnet|haiku|fable|default|best|opusplan)\b/i.test(model2.trim());
|
|
@@ -1289,13 +1324,13 @@ var cliLabel = (id) => CLIS.find((c) => c.id === id)?.label ?? id;
|
|
|
1289
1324
|
var WIN = process.platform === "win32";
|
|
1290
1325
|
function resolveCommand(name, env = process.env) {
|
|
1291
1326
|
const key = Object.keys(env).find((k) => k.toUpperCase() === "PATH") ?? "PATH";
|
|
1292
|
-
const dirs = (env[key] ?? "").split(
|
|
1327
|
+
const dirs = (env[key] ?? "").split(path5.delimiter).filter(Boolean);
|
|
1293
1328
|
const exts = WIN ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter((e) => /^\.(exe|cmd|bat|com)$/i.test(e)) : [""];
|
|
1294
1329
|
for (const dir of dirs) {
|
|
1295
1330
|
for (const ext of exts) {
|
|
1296
|
-
const file =
|
|
1331
|
+
const file = path5.join(dir, name + ext.toLowerCase());
|
|
1297
1332
|
try {
|
|
1298
|
-
const st =
|
|
1333
|
+
const st = fs5.statSync(file);
|
|
1299
1334
|
if (st.isFile() && (WIN || (st.mode & 73) !== 0)) return file;
|
|
1300
1335
|
} catch {
|
|
1301
1336
|
}
|
|
@@ -1316,16 +1351,16 @@ function unwrapCmdShim(shimPath, text3, env = process.env) {
|
|
|
1316
1351
|
});
|
|
1317
1352
|
return missing ? null : { file, args: [] };
|
|
1318
1353
|
}
|
|
1319
|
-
const dir =
|
|
1320
|
-
const targets = [...line.matchAll(/"%dp0%\\([^"]+)"/g)].map((m) =>
|
|
1354
|
+
const dir = path5.dirname(shimPath);
|
|
1355
|
+
const targets = [...line.matchAll(/"%dp0%\\([^"]+)"/g)].map((m) => path5.join(dir, m[1]));
|
|
1321
1356
|
const target = targets[targets.length - 1];
|
|
1322
1357
|
if (!target) return null;
|
|
1323
1358
|
if (/\.exe$/i.test(target)) return { file: target, args: [] };
|
|
1324
1359
|
if (!/\.[cm]?js$/i.test(target)) return null;
|
|
1325
1360
|
const between = line.slice(line.indexOf('"%_prog%"') + '"%_prog%"'.length, line.lastIndexOf(`"%dp0%\\`));
|
|
1326
1361
|
const nodeFlags = line.includes('"%_prog%"') ? between.trim().split(/\s+/).filter((f) => f.startsWith("--")) : [];
|
|
1327
|
-
const localNode =
|
|
1328
|
-
return { file:
|
|
1362
|
+
const localNode = path5.join(dir, "node.exe");
|
|
1363
|
+
return { file: fs5.existsSync(localNode) ? localNode : process.execPath, args: [...nodeFlags, target] };
|
|
1329
1364
|
}
|
|
1330
1365
|
var bundled;
|
|
1331
1366
|
function bundledClaude() {
|
|
@@ -1358,7 +1393,7 @@ function commandFor(id) {
|
|
|
1358
1393
|
if (!found2) return null;
|
|
1359
1394
|
if (WIN && /\.(cmd|bat)$/i.test(found2)) {
|
|
1360
1395
|
try {
|
|
1361
|
-
return unwrapCmdShim(found2,
|
|
1396
|
+
return unwrapCmdShim(found2, fs5.readFileSync(found2, "utf8")) ?? { file: found2, args: [] };
|
|
1362
1397
|
} catch {
|
|
1363
1398
|
return { file: found2, args: [] };
|
|
1364
1399
|
}
|
|
@@ -1375,9 +1410,9 @@ async function checkOpenCodeVersion(cmd) {
|
|
|
1375
1410
|
const version = await run(cmd.file, [...cmd.args, "--version"], { timeoutMs: 2e4 }).catch(() => null);
|
|
1376
1411
|
return openCodeVersionProblem(version);
|
|
1377
1412
|
}
|
|
1378
|
-
async function detectClis() {
|
|
1413
|
+
async function detectClis(ids) {
|
|
1379
1414
|
return Promise.all(
|
|
1380
|
-
CLIS.map(async (c) => {
|
|
1415
|
+
CLIS.filter((c) => !ids || ids.includes(c.id)).map(async (c) => {
|
|
1381
1416
|
const cmd = commandFor(c.id);
|
|
1382
1417
|
const version = cmd ? await run(cmd.file, [...cmd.args, "--version"], { timeoutMs: 2e4 }).catch(() => null) : null;
|
|
1383
1418
|
const problem = c.id === "opencode" && cmd ? openCodeVersionProblem(version) : null;
|
|
@@ -1386,16 +1421,17 @@ async function detectClis() {
|
|
|
1386
1421
|
);
|
|
1387
1422
|
}
|
|
1388
1423
|
var BOX_CODEX_VERSION = "0.163.0";
|
|
1424
|
+
var BOX_OPENCODE_VERSION = "2.2.6";
|
|
1389
1425
|
function packageField(pkg, field) {
|
|
1390
1426
|
try {
|
|
1391
|
-
let dir =
|
|
1427
|
+
let dir = path5.dirname(createRequire2(import.meta.url).resolve(pkg));
|
|
1392
1428
|
for (let i = 0; i < 6; i++) {
|
|
1393
|
-
const file =
|
|
1394
|
-
if (
|
|
1395
|
-
const json = JSON.parse(
|
|
1429
|
+
const file = path5.join(dir, "package.json");
|
|
1430
|
+
if (fs5.existsSync(file)) {
|
|
1431
|
+
const json = JSON.parse(fs5.readFileSync(file, "utf8"));
|
|
1396
1432
|
if (json.name === pkg) return typeof json[field] === "string" ? json[field] : null;
|
|
1397
1433
|
}
|
|
1398
|
-
dir =
|
|
1434
|
+
dir = path5.dirname(dir);
|
|
1399
1435
|
}
|
|
1400
1436
|
} catch {
|
|
1401
1437
|
}
|
|
@@ -1405,11 +1441,12 @@ function boxVersions() {
|
|
|
1405
1441
|
return {
|
|
1406
1442
|
claude: packageField("@anthropic-ai/claude-agent-sdk", "claudeCodeVersion") ?? "latest",
|
|
1407
1443
|
playwrightMcp: packageField("@playwright/mcp", "version") ?? "latest",
|
|
1408
|
-
codex: BOX_CODEX_VERSION
|
|
1444
|
+
codex: BOX_CODEX_VERSION,
|
|
1445
|
+
opencode: BOX_OPENCODE_VERSION
|
|
1409
1446
|
};
|
|
1410
1447
|
}
|
|
1411
1448
|
function localUrl(p, env = process.env) {
|
|
1412
|
-
return env
|
|
1449
|
+
return officeEnv(env, `CUBEFARM_${p.id.toUpperCase()}_URL`)?.trim() || p.url;
|
|
1413
1450
|
}
|
|
1414
1451
|
function codexLocal(model2, toml) {
|
|
1415
1452
|
const local = localModel(model2);
|
|
@@ -1482,7 +1519,7 @@ function launchArgs(id, ctx) {
|
|
|
1482
1519
|
}
|
|
1483
1520
|
case "opencode": {
|
|
1484
1521
|
const local = localModel(ctx.model);
|
|
1485
|
-
const sessionID = ctx.resumeId || `
|
|
1522
|
+
const sessionID = ctx.resumeId || `ses_droidsembly${ctx.sessionId.replaceAll("-", "")}`;
|
|
1486
1523
|
const model2 = local ? `${local.provider.id}/${local.model}` : ctx.model;
|
|
1487
1524
|
const servers = {
|
|
1488
1525
|
...ctx.browser ? { playwright: { type: "local", command: [ctx.browser.command, ...ctx.browser.args] } } : {},
|
|
@@ -1490,15 +1527,15 @@ function launchArgs(id, ctx) {
|
|
|
1490
1527
|
};
|
|
1491
1528
|
const config = {
|
|
1492
1529
|
$schema: "https://opencode.ai/config.json",
|
|
1493
|
-
plugins: [{ package: ctx.plugin, options: { sessionID, notifyUrl: ctx.notify.url, model: openCodeModelRef(model2) } }],
|
|
1530
|
+
plugins: [{ package: ctx.plugin, options: { sessionID, ...ctx.posix ? { eventsFile: ctx.notify.url } : { notifyUrl: ctx.notify.url }, model: openCodeModelRef(model2) } }],
|
|
1494
1531
|
instructions: [ctx.files.system],
|
|
1495
1532
|
// A dedicated primary agent also retains a model's explicit #variant (the root model setting doesn't).
|
|
1496
1533
|
default_agent: "droidsembly",
|
|
1497
1534
|
agents: {
|
|
1498
|
-
droidsembly: { description: "The Droidsembly office session", mode: "primary", ...model2 ? { model: model2 } : {} },
|
|
1535
|
+
droidsembly: { description: "The Droidsembly office session", mode: "primary", ...model2 ? { model: model2 } : {}, ...ctx.openCodePermissions ? { permissions: ctx.openCodePermissions } : {} },
|
|
1499
1536
|
// OpenCode keeps the agent ID on an existing session. Keep the old profile available on resume,
|
|
1500
1537
|
// but out of the picker: do not migrate session IDs or rewrite the user's OpenCode history.
|
|
1501
|
-
...ctx.resumeId ? { cubefarm: { description: "The Droidsembly office session (legacy)", mode: "primary", hidden: true, ...model2 ? { model: model2 } : {} } } : {}
|
|
1538
|
+
...ctx.resumeId ? { cubefarm: { description: "The Droidsembly office session (legacy)", mode: "primary", hidden: true, ...model2 ? { model: model2 } : {}, ...ctx.openCodePermissions ? { permissions: ctx.openCodePermissions } : {} } } : {}
|
|
1502
1539
|
},
|
|
1503
1540
|
...opencodeLocal(local),
|
|
1504
1541
|
...Object.keys(servers).length ? { mcp: { servers } } : {}
|
|
@@ -1617,12 +1654,19 @@ var OPENCODE_PLUGIN_SOURCE = String.raw`// cubefarm: forward only this office se
|
|
|
1617
1654
|
export default {
|
|
1618
1655
|
id: 'cubefarm.office',
|
|
1619
1656
|
async setup(ctx) {
|
|
1620
|
-
const { sessionID, notifyUrl } = ctx.options;
|
|
1621
|
-
if (!sessionID || !notifyUrl) throw new Error('Missing Droidsembly callback configuration');
|
|
1657
|
+
const { sessionID, notifyUrl, eventsFile } = ctx.options;
|
|
1658
|
+
if (!sessionID || (!notifyUrl && !eventsFile)) throw new Error('Missing Droidsembly callback configuration');
|
|
1659
|
+
const fs = eventsFile ? await import('node:fs') : null;
|
|
1622
1660
|
const controller = new AbortController();
|
|
1623
1661
|
let lastIdle;
|
|
1662
|
+
let authFailed = false;
|
|
1624
1663
|
const reportedUsage = new Map();
|
|
1625
1664
|
const post = async (body) => {
|
|
1665
|
+
if (fs) {
|
|
1666
|
+
const line = JSON.stringify({ ...body, session_id: sessionID }).replace(/[\u007f-]/g, (c) => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0'));
|
|
1667
|
+
fs.appendFileSync(eventsFile, line + '\n');
|
|
1668
|
+
return;
|
|
1669
|
+
}
|
|
1626
1670
|
const response = await fetch(notifyUrl, {
|
|
1627
1671
|
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
1628
1672
|
body: JSON.stringify({ ...body, session_id: sessionID }),
|
|
@@ -1667,7 +1711,10 @@ export default {
|
|
|
1667
1711
|
};
|
|
1668
1712
|
await observe('model.request', (event) => reportResource(event));
|
|
1669
1713
|
await observe('http.response', async (event) => {
|
|
1670
|
-
if (event.sessionID !== sessionID
|
|
1714
|
+
if (event.sessionID !== sessionID) return;
|
|
1715
|
+
if (event.response.status === 401) authFailed = true;
|
|
1716
|
+
else if (event.response.status < 400) authFailed = false;
|
|
1717
|
+
if (event.response.status !== 429) return;
|
|
1671
1718
|
const retry = event.response.headers.get('retry-after');
|
|
1672
1719
|
const seconds = retry && /^\d+(?:\.\d+)?$/.test(retry) ? Number(retry) : NaN;
|
|
1673
1720
|
const at = Number.isFinite(seconds) ? Date.now() + seconds * 1000 : retry ? Date.parse(retry) : NaN;
|
|
@@ -1680,6 +1727,13 @@ export default {
|
|
|
1680
1727
|
for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
|
|
1681
1728
|
const props = event.data ?? event.properties ?? event;
|
|
1682
1729
|
if ((props.sessionID ?? props.info?.id ?? props.session?.id) !== sessionID) continue;
|
|
1730
|
+
if (eventsFile && ['session.tool.called', 'session.tool.success', 'session.tool.failed'].includes(event.type)) {
|
|
1731
|
+
// Tool names only: do not copy tool arguments, output, credentials or private reasoning into telemetry.
|
|
1732
|
+
const messages = await ctx.session.context({ sessionID });
|
|
1733
|
+
const tool = messages.flatMap(m => m.type === 'assistant' ? m.content ?? [] : []).find(p => p.type === 'tool' && p.id === props.id);
|
|
1734
|
+
if (tool) await post({ hook_event_name: event.type === 'session.tool.called' ? 'PreToolUse' : event.type === 'session.tool.failed' ? 'PostToolUseFailure' : 'PostToolUse', tool_name: tool.name, tool_use_id: props.id, ...(event.type === 'session.tool.failed' ? { error: 'Tool failed (see the remote terminal)' } : {}) });
|
|
1735
|
+
continue;
|
|
1736
|
+
}
|
|
1683
1737
|
if (!['session.execution.succeeded', 'session.execution.failed', 'session.execution.interrupted', 'session.idle'].includes(event.type)) continue;
|
|
1684
1738
|
const [messages, session] = await Promise.all([
|
|
1685
1739
|
ctx.session.context({ sessionID }), ctx.session.get({ sessionID }),
|
|
@@ -1711,7 +1765,7 @@ export default {
|
|
|
1711
1765
|
if (outcome === 'interrupted') {
|
|
1712
1766
|
await post({ hook_event_name: 'Interrupt' });
|
|
1713
1767
|
} else if (outcome === 'failed') {
|
|
1714
|
-
await post({ hook_event_name: 'TurnError', error: JSON.stringify(props.error ?? idle?.error ?? 'OpenCode session failed') });
|
|
1768
|
+
await post({ hook_event_name: 'TurnError', error: JSON.stringify(props.error ?? idle?.error ?? 'OpenCode session failed'), ...(eventsFile && authFailed ? { signed_out: true } : {}) });
|
|
1715
1769
|
} else {
|
|
1716
1770
|
const user = messages.findLastIndex((m) => m.type === 'user');
|
|
1717
1771
|
const reply = messages.slice(user + 1).findLast((m) => m.type === 'assistant');
|
|
@@ -1765,7 +1819,7 @@ function screenshotFile(cwd, text3) {
|
|
|
1765
1819
|
const file = text3.match(/\]\(([^)\s]+\.(png|jpe?g))\)/i);
|
|
1766
1820
|
if (!file) return null;
|
|
1767
1821
|
try {
|
|
1768
|
-
return { data:
|
|
1822
|
+
return { data: fs6.readFileSync(path6.resolve(cwd, file[1])), mime: /png$/i.test(file[2]) ? "image/png" : "image/jpeg" };
|
|
1769
1823
|
} catch {
|
|
1770
1824
|
return null;
|
|
1771
1825
|
}
|
|
@@ -1774,17 +1828,17 @@ var IMAGE_MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jp
|
|
|
1774
1828
|
function newScreenshots(dir, seen, now2 = Date.now()) {
|
|
1775
1829
|
let names;
|
|
1776
1830
|
try {
|
|
1777
|
-
names =
|
|
1831
|
+
names = fs6.readdirSync(dir);
|
|
1778
1832
|
} catch {
|
|
1779
1833
|
return [];
|
|
1780
1834
|
}
|
|
1781
1835
|
const found2 = [];
|
|
1782
1836
|
for (const name of names.sort()) {
|
|
1783
|
-
const mime = IMAGE_MIME[
|
|
1784
|
-
const file =
|
|
1837
|
+
const mime = IMAGE_MIME[path6.extname(name).toLowerCase()];
|
|
1838
|
+
const file = path6.join(dir, name);
|
|
1785
1839
|
if (!mime || seen.has(name)) continue;
|
|
1786
1840
|
try {
|
|
1787
|
-
if (now2 -
|
|
1841
|
+
if (now2 - fs6.statSync(file).mtimeMs < 1e3) continue;
|
|
1788
1842
|
} catch {
|
|
1789
1843
|
continue;
|
|
1790
1844
|
}
|
|
@@ -1796,7 +1850,7 @@ var clip = (s2, n) => s2.length > n ? `${s2.slice(0, n - 1)}\u2026` : s2;
|
|
|
1796
1850
|
function rel(cwd, p) {
|
|
1797
1851
|
const s2 = String(p ?? "");
|
|
1798
1852
|
if (!s2) return "";
|
|
1799
|
-
const r =
|
|
1853
|
+
const r = path6.relative(cwd, path6.resolve(cwd, s2));
|
|
1800
1854
|
return r && !r.startsWith("..") ? r.replaceAll("\\", "/") : s2;
|
|
1801
1855
|
}
|
|
1802
1856
|
var escapeRe = (s2) => s2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
@@ -1933,7 +1987,7 @@ function startSession(opts, callbacks) {
|
|
|
1933
1987
|
env[k] = v;
|
|
1934
1988
|
}
|
|
1935
1989
|
Object.assign(env, opts.env);
|
|
1936
|
-
env.CLAUDE_AGENT_SDK_CLIENT_APP = `
|
|
1990
|
+
env.CLAUDE_AGENT_SDK_CLIENT_APP = `droidsembly/${VERSION}`;
|
|
1937
1991
|
const mcpServers = {};
|
|
1938
1992
|
if (opts.browserTesting) {
|
|
1939
1993
|
const browser = playwrightMcp();
|
|
@@ -2116,8 +2170,8 @@ function startSession(opts, callbacks) {
|
|
|
2116
2170
|
|
|
2117
2171
|
// server/cliRunner.ts
|
|
2118
2172
|
import crypto3 from "node:crypto";
|
|
2119
|
-
import
|
|
2120
|
-
import
|
|
2173
|
+
import fs9 from "node:fs";
|
|
2174
|
+
import path10 from "node:path";
|
|
2121
2175
|
import { pathToFileURL } from "node:url";
|
|
2122
2176
|
|
|
2123
2177
|
// server/mcpHttp.ts
|
|
@@ -2174,12 +2228,12 @@ var HttpError = class extends Error {
|
|
|
2174
2228
|
};
|
|
2175
2229
|
|
|
2176
2230
|
// server/secrets.ts
|
|
2177
|
-
import
|
|
2178
|
-
import
|
|
2231
|
+
import fs7 from "node:fs/promises";
|
|
2232
|
+
import path7 from "node:path";
|
|
2179
2233
|
var queues = /* @__PURE__ */ new Map();
|
|
2180
2234
|
async function readSecrets(file) {
|
|
2181
2235
|
try {
|
|
2182
|
-
const s2 = JSON.parse(await
|
|
2236
|
+
const s2 = JSON.parse(await fs7.readFile(file, "utf8"));
|
|
2183
2237
|
return s2 && typeof s2 === "object" ? s2 : {};
|
|
2184
2238
|
} catch {
|
|
2185
2239
|
return {};
|
|
@@ -2189,11 +2243,11 @@ function mergeSecrets(file, patch) {
|
|
|
2189
2243
|
const write = (queues.get(file) ?? Promise.resolve()).then(async () => {
|
|
2190
2244
|
const next = { ...await readSecrets(file), ...patch };
|
|
2191
2245
|
for (const k of Object.keys(next)) if (next[k] === void 0) delete next[k];
|
|
2192
|
-
await
|
|
2246
|
+
await fs7.mkdir(path7.dirname(file), { recursive: true });
|
|
2193
2247
|
const tmp = `${file}.tmp`;
|
|
2194
|
-
await
|
|
2195
|
-
await
|
|
2196
|
-
await
|
|
2248
|
+
await fs7.writeFile(tmp, JSON.stringify(next, null, 2), { mode: 384 });
|
|
2249
|
+
await fs7.rename(tmp, file);
|
|
2250
|
+
await fs7.chmod(file, 384).catch(() => void 0);
|
|
2197
2251
|
});
|
|
2198
2252
|
queues.set(
|
|
2199
2253
|
file,
|
|
@@ -2233,7 +2287,7 @@ function decoder(onText) {
|
|
|
2233
2287
|
if (text3) onText(text3);
|
|
2234
2288
|
};
|
|
2235
2289
|
}
|
|
2236
|
-
function upstashBoxes(apiKey) {
|
|
2290
|
+
function upstashBoxes(apiKey, options = {}) {
|
|
2237
2291
|
const conn2 = { apiKey, enableTelemetry: false };
|
|
2238
2292
|
const boxes = /* @__PURE__ */ new Map();
|
|
2239
2293
|
const box = async (id) => {
|
|
@@ -2273,7 +2327,7 @@ function upstashBoxes(apiKey) {
|
|
|
2273
2327
|
return {
|
|
2274
2328
|
list: () => guard("list your Boxes", async () => (await Box.list(conn2)).map((d) => ({ id: d.id, name: d.name ?? "", labels: d.labels ?? [], status: state(d.status) }))),
|
|
2275
2329
|
create: (o) => guard("create a Box", async () => {
|
|
2276
|
-
const b = await Box.create({ ...conn2, name: o.name, labels: o.labels, size: o.size, runtime: "node", browser: true, timeout: 3e5 });
|
|
2330
|
+
const b = await Box.create({ ...conn2, name: o.name, labels: o.labels, size: o.size, runtime: "node", browser: o.browser ?? options.browser ?? true, keepAlive: false, timeout: 3e5 });
|
|
2277
2331
|
boxes.set(b.id, b);
|
|
2278
2332
|
return { id: b.id, name: o.name, labels: o.labels, status: "running" };
|
|
2279
2333
|
}),
|
|
@@ -2300,9 +2354,16 @@ function upstashBoxes(apiKey) {
|
|
|
2300
2354
|
run: (id, script, o = {}) => guard("run a command in a Box", async () => {
|
|
2301
2355
|
let output = "";
|
|
2302
2356
|
const s2 = await openSession(id, { cmd: script, env: o.env, onData: (t) => output += t });
|
|
2303
|
-
|
|
2357
|
+
let timedOut = false;
|
|
2358
|
+
const timer = setTimeout(() => {
|
|
2359
|
+
timedOut = true;
|
|
2360
|
+
s2.close();
|
|
2361
|
+
}, o.timeoutMs ?? 6e5);
|
|
2304
2362
|
try {
|
|
2305
|
-
|
|
2363
|
+
const code = await s2.done;
|
|
2364
|
+
if (timedOut) throw new CloudError("The Box command timed out before a verified exit status was received.", "other");
|
|
2365
|
+
if (!Number.isInteger(code) || code < 0 || code > 255) throw new CloudError("The Box command ended without a verified exit status. Its outcome is unknown.", "other");
|
|
2366
|
+
return { code, output };
|
|
2306
2367
|
} finally {
|
|
2307
2368
|
clearTimeout(timer);
|
|
2308
2369
|
}
|
|
@@ -2340,16 +2401,32 @@ function upstashBoxes(apiKey) {
|
|
|
2340
2401
|
};
|
|
2341
2402
|
}
|
|
2342
2403
|
|
|
2404
|
+
// server/boxRemoval.ts
|
|
2405
|
+
async function removeBoxVerified(api, id) {
|
|
2406
|
+
await api.remove(id);
|
|
2407
|
+
const absent = await api.get(id) === null;
|
|
2408
|
+
const remaining = await api.list();
|
|
2409
|
+
return absent && !remaining.some((box) => box.id === id);
|
|
2410
|
+
}
|
|
2411
|
+
|
|
2343
2412
|
// server/cloud.ts
|
|
2344
|
-
var CLAUDE_TOKEN_ENV = "
|
|
2413
|
+
var CLAUDE_TOKEN_ENV = "DROIDSEMBLY_CLAUDE_TOKEN";
|
|
2345
2414
|
var ANTHROPIC_KEY_ENV = "CUBEFARM_ANTHROPIC_KEY";
|
|
2346
2415
|
var TOKEN_FIELD = { github: "cloudGithubToken", anthropic: "anthropicApiKey", openai: "openaiApiKey" };
|
|
2347
2416
|
var officeId = () => Math.random().toString(36).slice(2, 8).padEnd(6, "0");
|
|
2348
|
-
var boxName = (office, machine) => `
|
|
2349
|
-
var boxLabels = (office, machine) => ["cubefarm", `cf:${office}`, `m:${machine}`];
|
|
2417
|
+
var boxName = (office, machine) => `droidsembly-${office}-${machine}`;
|
|
2418
|
+
var boxLabels = (office, machine) => ["droidsembly", `ds:${office}`, "cubefarm", `cf:${office}`, `m:${machine}`];
|
|
2350
2419
|
function machineOfBox(box, office) {
|
|
2351
|
-
|
|
2352
|
-
|
|
2420
|
+
const labels = box.labels;
|
|
2421
|
+
const legacy = labels.includes("cubefarm");
|
|
2422
|
+
const current = labels.includes("droidsembly");
|
|
2423
|
+
const cf = labels.filter((l) => l.startsWith("cf:"));
|
|
2424
|
+
const ds = labels.filter((l) => l.startsWith("ds:"));
|
|
2425
|
+
const machines = labels.filter((l) => l.startsWith("m:"));
|
|
2426
|
+
if (!legacy && !current || legacy !== (cf.length === 1) || current !== (ds.length === 1)) return null;
|
|
2427
|
+
if (cf.length > 1 || ds.length > 1 || legacy && cf[0] !== `cf:${office}` || current && ds[0] !== `ds:${office}`) return null;
|
|
2428
|
+
if (machines.length !== 1 || !/^m:[A-Za-z0-9._-]{1,18}$/.test(machines[0])) return null;
|
|
2429
|
+
return machines[0].slice(2);
|
|
2353
2430
|
}
|
|
2354
2431
|
var CLAUDE_VARS = ["CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", ANTHROPIC_KEY_ENV];
|
|
2355
2432
|
var github = (i) => i.secrets.cloudGithubToken || i.ghToken;
|
|
@@ -2371,7 +2448,7 @@ function resolveCredentials(cli, i) {
|
|
|
2371
2448
|
} else if (cli === "codex") {
|
|
2372
2449
|
if (i.secrets.openaiApiKey) Object.assign(env, { OPENAI_API_KEY: i.secrets.openaiApiKey, CODEX_API_KEY: i.secrets.openaiApiKey });
|
|
2373
2450
|
else ownLogin = true;
|
|
2374
|
-
}
|
|
2451
|
+
} else if (cli === "opencode") ownLogin = true;
|
|
2375
2452
|
return { env, apiKeyHelper, ownLogin, missing };
|
|
2376
2453
|
}
|
|
2377
2454
|
function githubEnv(i) {
|
|
@@ -2404,18 +2481,19 @@ var Cloud = class {
|
|
|
2404
2481
|
ghAt = 0;
|
|
2405
2482
|
boxes = null;
|
|
2406
2483
|
async init() {
|
|
2407
|
-
const s2 = await readSecrets(this.deps.secretsFile);
|
|
2484
|
+
const s2 = this.deps.credentials ?? await readSecrets(this.deps.secretsFile);
|
|
2408
2485
|
for (const k of ["upstashBoxKey", "cloudGithubToken", "anthropicApiKey", "openaiApiKey"]) if (typeof s2[k] === "string" && s2[k]) this.secrets[k] = s2[k];
|
|
2409
2486
|
if (this.secrets.upstashBoxKey) this.api = this.deps.boxes(this.secrets.upstashBoxKey);
|
|
2410
|
-
await this.refreshGh(true);
|
|
2487
|
+
if (!this.secrets.cloudGithubToken) await this.refreshGh(true);
|
|
2411
2488
|
}
|
|
2412
2489
|
/** The Box API, or null while no key is saved. */
|
|
2413
2490
|
boxApi() {
|
|
2414
2491
|
return this.api;
|
|
2415
2492
|
}
|
|
2416
|
-
claudeToken = () => (this.deps.env
|
|
2493
|
+
claudeToken = () => (officeEnv(this.deps.env, "CUBEFARM_CLAUDE_TOKEN") ?? "").trim();
|
|
2417
2494
|
/** The gh login token, re-read at most once a minute (the manager may sign in or out meanwhile). */
|
|
2418
2495
|
async refreshGh(force = false) {
|
|
2496
|
+
if (this.deps.credentials) return "";
|
|
2419
2497
|
if (!force && Date.now() - this.ghAt < 6e4) return this.gh;
|
|
2420
2498
|
this.ghAt = Date.now();
|
|
2421
2499
|
this.gh = await this.deps.ghToken().catch(() => "");
|
|
@@ -2435,7 +2513,7 @@ var Cloud = class {
|
|
|
2435
2513
|
}
|
|
2436
2514
|
/** Every saved key and token, so they're scrubbed from anything the office writes or shows. */
|
|
2437
2515
|
secretValues() {
|
|
2438
|
-
return [...Object.values(this.secrets), this.claudeToken(), this.gh].filter((s2) => !!s2);
|
|
2516
|
+
return [...Object.values(this.secrets), this.claudeToken(), this.deps.env.CUBEFARM_CLAUDE_TOKEN, this.deps.env.DROIDSEMBLY_CLAUDE_TOKEN, this.gh].filter((s2) => !!s2);
|
|
2439
2517
|
}
|
|
2440
2518
|
/** What a CLI runs with in a Box. */
|
|
2441
2519
|
async credentials(cli) {
|
|
@@ -2447,6 +2525,7 @@ var Cloud = class {
|
|
|
2447
2525
|
}
|
|
2448
2526
|
/** PUT /api/cloud/key: '' disconnects; anything else must list the account's Boxes first. */
|
|
2449
2527
|
async setKey(raw) {
|
|
2528
|
+
if (this.deps.credentials) throw new HttpError(409, "This isolated run uses in-memory credentials; changing or saving them is disabled.");
|
|
2450
2529
|
const key = raw.trim();
|
|
2451
2530
|
if (key) {
|
|
2452
2531
|
if (key.length > 400 || /\s/.test(key)) throw new HttpError(400, "That doesn't look like an Upstash Box API key.");
|
|
@@ -2467,6 +2546,7 @@ var Cloud = class {
|
|
|
2467
2546
|
}
|
|
2468
2547
|
/** PUT /api/cloud/token: a GitHub token, an Anthropic or an OpenAI API key for cloud agents ('' removes it). */
|
|
2469
2548
|
async setToken(kind, raw) {
|
|
2549
|
+
if (this.deps.credentials) throw new HttpError(409, "This isolated run uses in-memory credentials; changing or saving them is disabled.");
|
|
2470
2550
|
const value = raw.trim();
|
|
2471
2551
|
if (value.length > 400 || /\s/.test(value)) throw new HttpError(400, "That doesn't look like a token or an API key.");
|
|
2472
2552
|
if (kind === "anthropic" && value.startsWith("sk-ant-oat")) {
|
|
@@ -2497,7 +2577,7 @@ var Cloud = class {
|
|
|
2497
2577
|
const all = await this.api.list();
|
|
2498
2578
|
const office = this.deps.office();
|
|
2499
2579
|
const machines = this.deps.machines();
|
|
2500
|
-
const ours = all.filter((b) => b.
|
|
2580
|
+
const ours = all.filter((b) => b.status !== "deleted" && machineOfBox(b, office) !== null);
|
|
2501
2581
|
this.boxes = {
|
|
2502
2582
|
total: all.filter((b) => b.status !== "deleted").length,
|
|
2503
2583
|
running: ours.filter((b) => b.status === "running" || b.status === "idle" || b.status === "creating").length,
|
|
@@ -2519,13 +2599,24 @@ var Cloud = class {
|
|
|
2519
2599
|
if (!this.api) throw new HttpError(400, "Save your Upstash Box API key first.");
|
|
2520
2600
|
const office = this.deps.office();
|
|
2521
2601
|
const machines = this.deps.machines();
|
|
2522
|
-
const doomed = (await this.count()).filter((b) =>
|
|
2523
|
-
|
|
2602
|
+
const doomed = (await this.count()).filter((b) => {
|
|
2603
|
+
const machine = machineOfBox(b, office);
|
|
2604
|
+
return b.status !== "deleted" && machine !== null && !machines.has(machine);
|
|
2605
|
+
});
|
|
2606
|
+
let deleted = 0, unconfirmed = 0;
|
|
2524
2607
|
for (const b of doomed) {
|
|
2525
|
-
|
|
2608
|
+
const machine = machineOfBox(b, this.deps.office());
|
|
2609
|
+
if (machine === null || this.deps.office() !== office || this.deps.machines().has(machine)) continue;
|
|
2610
|
+
try {
|
|
2611
|
+
if (await removeBoxVerified(this.api, b.id)) deleted++;
|
|
2612
|
+
else unconfirmed++;
|
|
2613
|
+
} catch {
|
|
2614
|
+
unconfirmed++;
|
|
2615
|
+
}
|
|
2526
2616
|
}
|
|
2617
|
+
if (unconfirmed) this.deps.log(`${unconfirmed} orphan Box removal(s) could not be confirmed; check the Upstash console. No automatic retry.`);
|
|
2527
2618
|
await this.count().catch(() => void 0);
|
|
2528
|
-
return { deleted };
|
|
2619
|
+
return { deleted, unconfirmed };
|
|
2529
2620
|
}
|
|
2530
2621
|
emit() {
|
|
2531
2622
|
const view = this.view();
|
|
@@ -2554,7 +2645,7 @@ var BRANCH = /^[\w./-]+$/;
|
|
|
2554
2645
|
function checkRepo(fullName) {
|
|
2555
2646
|
if (!OWNER_REPO.test(fullName)) throw new Error(`Not a GitHub repository name: ${fullName}`);
|
|
2556
2647
|
}
|
|
2557
|
-
var setupMarker = (v, rev) => `${BOX_CF}/setup-${rev}-${v.claude}-${v.playwrightMcp}-${v.codex}
|
|
2648
|
+
var setupMarker = (v, rev, cli, browser = false) => (cli ? `${BOX_CF}/setup-${rev}-${cli}-${v[cli]}${browser ? `-browser-${v.playwrightMcp}` : ""}` : `${BOX_CF}/setup-${rev}-${v.claude}-${v.playwrightMcp}-${v.codex}-${v.opencode}`).replace(/[^\w./-]/g, "_");
|
|
2558
2649
|
var TMUX_CONF = [
|
|
2559
2650
|
"set -g status off",
|
|
2560
2651
|
"set -g prefix None",
|
|
@@ -2569,31 +2660,45 @@ var TMUX_CONF = [
|
|
|
2569
2660
|
""
|
|
2570
2661
|
].join("\n");
|
|
2571
2662
|
function setupScript(o) {
|
|
2572
|
-
const
|
|
2573
|
-
const
|
|
2663
|
+
const marker2 = setupMarker(o.versions, o.rev, o.cli, o.browser);
|
|
2664
|
+
const selected = o.cli ? [o.cli] : ["claude", "codex", "opencode"];
|
|
2665
|
+
const packages = { claude: `@anthropic-ai/claude-code@${o.versions.claude}`, codex: `@openai/codex@${o.versions.codex}`, opencode: `@opencode/cli@${o.versions.opencode}` };
|
|
2666
|
+
const browser = !o.cli || o.browser === true;
|
|
2667
|
+
const pkgs = o.cli ? [...selected.map((cli) => packages[cli]), ...browser ? [`@playwright/mcp@${o.versions.playwrightMcp}`] : []] : [packages.claude, `@playwright/mcp@${o.versions.playwrightMcp}`, packages.codex, packages.opencode];
|
|
2668
|
+
const bins = [...selected, ...browser ? ["playwright-mcp"] : []];
|
|
2669
|
+
const verify = [
|
|
2670
|
+
`for c in ${bins.join(" ")}; do test -x ${sq(BOX_CLI_BIN)}/$c || { echo "$c was not installed" >&2; exit 4; }; done`,
|
|
2671
|
+
...selected.includes("opencode") ? [`V="$("${BOX_CLI_BIN}/opencode" --version)"; case "$V" in ${[o.versions.opencode, `v${o.versions.opencode}`, `opencode ${o.versions.opencode}`, `opencode v${o.versions.opencode}`].map(sq).join("|")}) ;; *) echo "OpenCode version mismatch" >&2; exit 4;; esac`] : []
|
|
2672
|
+
];
|
|
2574
2673
|
const helper = `!f() { test "$1" = get || exit 0; echo username=x-access-token; echo "password=$GH_TOKEN"; }; f`;
|
|
2575
2674
|
return [
|
|
2576
2675
|
"set -e",
|
|
2577
|
-
`mkdir -p ${sq(BOX_BIN)} ${sq(BOX_SESSIONS)}`,
|
|
2578
|
-
`if [ -f ${sq(
|
|
2676
|
+
`mkdir -p ${sq(`${BOX_BIN}/opencode-plugin`)} ${sq(BOX_SESSIONS)}`,
|
|
2677
|
+
`if [ -f ${sq(marker2)} ]; then`,
|
|
2678
|
+
...verify,
|
|
2679
|
+
"echo CUBEFARM_SETUP_OK; exit 0; fi",
|
|
2680
|
+
'command -v node >/dev/null && command -v npm >/dev/null || { echo "Node/npm are required" >&2; exit 3; }',
|
|
2579
2681
|
'missing=""',
|
|
2580
|
-
'for t in tmux lsof gh; do command -v "$t" >/dev/null 2>&1 || missing="$missing $t"; done',
|
|
2682
|
+
'for t in tmux lsof gh git; do command -v "$t" >/dev/null 2>&1 || missing="$missing $t"; done',
|
|
2581
2683
|
'if [ -n "$missing" ]; then',
|
|
2582
|
-
" sudo DEBIAN_FRONTEND=noninteractive apt-get
|
|
2583
|
-
" sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -
|
|
2684
|
+
" sudo -n env DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=0 -o APT::Update::Error-Mode=any update -qq",
|
|
2685
|
+
" sudo -n env DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=0 -o DPkg::Lock::Timeout=0 install -y --no-install-recommends $missing",
|
|
2584
2686
|
"fi",
|
|
2585
2687
|
'command -v tmux >/dev/null 2>&1 || { echo "tmux could not be installed in the Box" >&2; exit 3; }',
|
|
2586
2688
|
// Into the office's own folder, not the image's global one: the Box image ships its own CLIs first on the PATH.
|
|
2587
|
-
`npm install -g --prefix ${sq(`${BOX_CF}/cli`)} --no-fund --no-audit --loglevel=error ${pkgs.map(sq).join(" ")} > /tmp/cubefarm-cli.log 2>&1 || { tail -n 5 /tmp/cubefarm-cli.log >&2; exit 4; }`,
|
|
2588
|
-
|
|
2689
|
+
`npm install -g --prefix ${sq(`${BOX_CF}/cli`)} --fetch-retries=0 --no-fund --no-audit --loglevel=error ${pkgs.map(sq).join(" ")} > /tmp/cubefarm-cli.log 2>&1 || { tail -n 5 /tmp/cubefarm-cli.log >&2; exit 4; }`,
|
|
2690
|
+
...verify,
|
|
2691
|
+
...selected.includes("opencode") ? [
|
|
2692
|
+
`mkdir -p ${sq(`${BOX_CF}/opencode/config/opencode`)}`,
|
|
2693
|
+
`test -f ${sq(`${BOX_CF}/opencode/config/opencode/opencode.json`)} || printf '%s' '{"update":"disable"}' > ${sq(`${BOX_CF}/opencode/config/opencode/opencode.json`)}`
|
|
2694
|
+
] : [],
|
|
2589
2695
|
"git config --global --unset-all credential.helper >/dev/null 2>&1 || true",
|
|
2590
2696
|
`git config --global credential.https://github.com.helper ${sq(helper)}`,
|
|
2591
2697
|
`git config --global user.name ${sq(o.gitName || "cubefarm")}`,
|
|
2592
2698
|
`git config --global user.email ${sq(o.gitEmail || "cubefarm@users.noreply.github.com")}`,
|
|
2593
2699
|
"git config --global init.defaultBranch main",
|
|
2594
2700
|
"git config --global advice.detachedHead false",
|
|
2595
|
-
`
|
|
2596
|
-
`touch ${sq(marker)}`,
|
|
2701
|
+
`touch ${sq(marker2)}`,
|
|
2597
2702
|
"echo CUBEFARM_SETUP_OK"
|
|
2598
2703
|
].join("\n");
|
|
2599
2704
|
}
|
|
@@ -2604,6 +2709,7 @@ function prepareDeskScript(fullName, base, branch) {
|
|
|
2604
2709
|
const desk = boxDeskDir(fullName);
|
|
2605
2710
|
const ref = base.pr ? `origin/pr/${base.pr}` : `origin/${base.defaultBranch}`;
|
|
2606
2711
|
return [
|
|
2712
|
+
"(",
|
|
2607
2713
|
"set -e",
|
|
2608
2714
|
`R=${sq(repo)}`,
|
|
2609
2715
|
`W=${sq(desk)}`,
|
|
@@ -2631,7 +2737,8 @@ function prepareDeskScript(fullName, base, branch) {
|
|
|
2631
2737
|
"fi",
|
|
2632
2738
|
'rm -rf "$W"; mkdir -p "$(dirname "$W")"',
|
|
2633
2739
|
'git worktree add -q -B "$B" "$W" "$REF"',
|
|
2634
|
-
'echo "$W"'
|
|
2740
|
+
'echo "$W"',
|
|
2741
|
+
")"
|
|
2635
2742
|
].join("\n");
|
|
2636
2743
|
}
|
|
2637
2744
|
function linkedReposScript(fullNames) {
|
|
@@ -2710,12 +2817,12 @@ function signInOutcome(output) {
|
|
|
2710
2817
|
const last = output.split("\n").map((l) => l.trim()).filter((l) => /^CUBEFARM_SIGNED_(IN|OUT)$/.test(l)).pop();
|
|
2711
2818
|
return last ? last === "CUBEFARM_SIGNED_IN" : null;
|
|
2712
2819
|
}
|
|
2713
|
-
var signOutScript = (cli) => `${sq(`${BOX_CLI_BIN}/${cli}`)} ${cli === "claude" ? "auth logout" : "logout"} >/dev/null 2>&1; true`;
|
|
2714
|
-
var signInCommand = (cli) => ({ file: `${BOX_CLI_BIN}/${cli}`, args: cli === "
|
|
2820
|
+
var signOutScript = (cli) => cli === "opencode" ? "true" : `${sq(`${BOX_CLI_BIN}/${cli}`)} ${cli === "claude" ? "auth logout" : "logout"} >/dev/null 2>&1; true`;
|
|
2821
|
+
var signInCommand = (cli) => ({ file: `${BOX_CLI_BIN}/${cli}`, args: cli === "codex" ? ["login", "--device-auth"] : ["auth", "login"] });
|
|
2715
2822
|
|
|
2716
2823
|
// server/boxCli.ts
|
|
2717
2824
|
var BOX_CDP = "http://127.0.0.1:9222";
|
|
2718
|
-
var TURN_ENDS = ["Stop", "StopFailure", "TurnComplete"];
|
|
2825
|
+
var TURN_ENDS = ["Stop", "StopFailure", "TurnComplete", "TurnError", "Interrupt"];
|
|
2719
2826
|
var EventLines = class {
|
|
2720
2827
|
/** turnAt: where the last turn end seen starts (see BoxCliRecord.turnAt). */
|
|
2721
2828
|
constructor(offset = 0, turnAt = offset) {
|
|
@@ -2796,7 +2903,11 @@ var BoxPty = class {
|
|
|
2796
2903
|
replay(events, at) {
|
|
2797
2904
|
void hooksOpen.then(() => {
|
|
2798
2905
|
if (this.stopped) return;
|
|
2799
|
-
for (const e of events)
|
|
2906
|
+
for (const e of events) {
|
|
2907
|
+
if (this.stopped || this.exited) return;
|
|
2908
|
+
if (e.hook_event_name !== "CubefarmExit") this.o.event(e);
|
|
2909
|
+
}
|
|
2910
|
+
if (this.stopped || this.exited) return;
|
|
2800
2911
|
this.lines = new EventLines(at.offset, at.turnAt);
|
|
2801
2912
|
this.o.save(at.offset, at.turnAt, this.meta);
|
|
2802
2913
|
setTimeout(() => this.fireExit(exitCode(events) ?? (finishedTurn(events) ? 0 : -1)), 6e3);
|
|
@@ -2865,9 +2976,11 @@ var BoxPty = class {
|
|
|
2865
2976
|
if (this.stopped || this.exited) return;
|
|
2866
2977
|
let exit = null;
|
|
2867
2978
|
for (const e of this.lines.push(text3)) {
|
|
2979
|
+
if (this.stopped || this.exited) return;
|
|
2868
2980
|
if (e.hook_event_name === "CubefarmExit") exit = Number(e.code) || 0;
|
|
2869
2981
|
else this.o.event(e);
|
|
2870
2982
|
}
|
|
2983
|
+
if (this.stopped || this.exited) return;
|
|
2871
2984
|
this.o.save(this.lines.offset, this.lines.turnAt, this.meta);
|
|
2872
2985
|
if (exit !== null) this.fireExit(exit);
|
|
2873
2986
|
}
|
|
@@ -2898,8 +3011,7 @@ var BoxPty = class {
|
|
|
2898
3011
|
const wasRunning = !this.exited;
|
|
2899
3012
|
this.stopped = true;
|
|
2900
3013
|
this.close();
|
|
2901
|
-
void this.o.api.run(this.o.boxId, tmuxKill(this.o.token), { timeoutMs: 6e4 }).catch(() => void 0);
|
|
2902
|
-
this.o.gone();
|
|
3014
|
+
void this.o.api.run(this.o.boxId, tmuxKill(this.o.token), { timeoutMs: 6e4 }).catch(() => void 0).then(() => this.o.gone());
|
|
2903
3015
|
if (wasRunning) for (const cb of this.exitCbs) cb(-1);
|
|
2904
3016
|
}
|
|
2905
3017
|
/** The office is closing: let go of the CLI, which carries on in the Box. */
|
|
@@ -2948,24 +3060,189 @@ async function sweepStrayClis(api, boxId, keepTokens) {
|
|
|
2948
3060
|
return n;
|
|
2949
3061
|
}
|
|
2950
3062
|
|
|
3063
|
+
// server/boxSessionFiles.ts
|
|
3064
|
+
var marker = "/* DS_BOX_SESSION_FILES */\n";
|
|
3065
|
+
var allowed = /* @__PURE__ */ new Set(["settings.json", "mcp.json", "instructions.md", "task.md", "launch.json"]);
|
|
3066
|
+
function boxSessionFilesScripts(directory, files) {
|
|
3067
|
+
if (!new RegExp(`^${BOX_CF.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/sessions/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$`).test(directory)) throw new Error("Invalid remote session directory");
|
|
3068
|
+
const seen = /* @__PURE__ */ new Set(), scripts = [];
|
|
3069
|
+
for (const [file, text3] of files) {
|
|
3070
|
+
const name = file.slice(directory.length + 1);
|
|
3071
|
+
if (file !== directory + "/" + name || !allowed.has(name) || seen.has(name) || typeof text3 !== "string") throw new Error("Invalid remote session file");
|
|
3072
|
+
seen.add(name);
|
|
3073
|
+
const bytes = Buffer.from(text3, "utf8");
|
|
3074
|
+
for (let offset = 0; offset === 0 || offset < bytes.length; offset += 16384) {
|
|
3075
|
+
const request = { directory, name, offset, base64: bytes.subarray(offset, offset + 16384).toString("base64") };
|
|
3076
|
+
const code = marker + `const request=${JSON.stringify(request)};
|
|
3077
|
+
const fs=require('node:fs'),path=require('node:path');
|
|
3078
|
+
try{
|
|
3079
|
+
if(process.geteuid()===0)throw new Error();
|
|
3080
|
+
const base=${JSON.stringify(BOX_CF)};
|
|
3081
|
+
if(fs.realpathSync(base)!==base)throw new Error();
|
|
3082
|
+
for(const dir of [base+'/sessions',request.directory]){try{fs.mkdirSync(dir,{mode:0o700});}catch(e){if(e.code!=='EEXIST')throw e;}if(fs.realpathSync(dir)!==dir)throw new Error();}
|
|
3083
|
+
const file=path.join(request.directory,request.name),data=Buffer.from(request.base64,'base64');
|
|
3084
|
+
const flags=fs.constants.O_WRONLY|fs.constants.O_NOFOLLOW|(request.offset===0?fs.constants.O_CREAT|fs.constants.O_EXCL:0);
|
|
3085
|
+
const fd=fs.openSync(file,flags,0o600);
|
|
3086
|
+
try{const st=fs.fstatSync(fd);if(!st.isFile()||st.uid!==process.geteuid()||st.size!==request.offset)throw new Error();if(fs.writeSync(fd,data,0,data.length,request.offset)!==data.length)throw new Error();}finally{fs.closeSync(fd);}
|
|
3087
|
+
process.stdout.write('DS_SESSION_FILES=written');
|
|
3088
|
+
}catch{process.stdout.write('DS_SESSION_FILES=failed');process.exitCode=1;}`;
|
|
3089
|
+
scripts.push("node -e " + sq(code));
|
|
3090
|
+
}
|
|
3091
|
+
}
|
|
3092
|
+
return scripts;
|
|
3093
|
+
}
|
|
3094
|
+
async function writeBoxSessionFiles(api, id, directory, files) {
|
|
3095
|
+
const scripts = boxSessionFilesScripts(directory, files);
|
|
3096
|
+
try {
|
|
3097
|
+
for (const script of scripts) {
|
|
3098
|
+
const result = await api.run(id, script, { env: { GH_TOKEN: "", GITHUB_TOKEN: "", OPENAI_API_KEY: "", ANTHROPIC_API_KEY: "" }, timeoutMs: 6e4 });
|
|
3099
|
+
if (result.code !== 0 || result.output !== "DS_SESSION_FILES=written") throw new Error();
|
|
3100
|
+
}
|
|
3101
|
+
} catch {
|
|
3102
|
+
throw new Error("Remote session files could not be prepared; worker not started");
|
|
3103
|
+
}
|
|
3104
|
+
}
|
|
3105
|
+
|
|
3106
|
+
// shared/opencodeReadiness.ts
|
|
3107
|
+
var READINESS_STATES = ["ready", "model-not-listed", "model-disabled", "model-non-chat", "model-no-tools", "variant-unavailable", "provider-not-listed", "provider-disabled", "provider-no-integration", "integration-not-listed", "no-connection", "connection-needs-auth", "connection-status-unknown", "oauth-unavailable"];
|
|
3108
|
+
var READINESS_CHECKS = ["box", "transport", "output", "version", "models", "default-model", "provider", "integration"];
|
|
3109
|
+
|
|
3110
|
+
// server/openCodeBox.ts
|
|
3111
|
+
var OPENCODE_BOX_ENV = {
|
|
3112
|
+
XDG_CONFIG_HOME: `${BOX_CF}/opencode/config`,
|
|
3113
|
+
XDG_DATA_HOME: `${BOX_CF}/opencode/data`,
|
|
3114
|
+
XDG_CACHE_HOME: `${BOX_CF}/opencode/cache`,
|
|
3115
|
+
XDG_STATE_HOME: `${BOX_CF}/opencode/state`
|
|
3116
|
+
};
|
|
3117
|
+
var OPENCODE_BOX_QUERY_SOURCE = String.raw`
|
|
3118
|
+
const { spawnSync } = require('child_process');
|
|
3119
|
+
const fs = require('fs');
|
|
3120
|
+
const [cli, mode, directory, requested = ''] = process.argv.slice(2);
|
|
3121
|
+
const cwd = fs.existsSync(directory) ? directory : '/workspace/home';
|
|
3122
|
+
let check = 'version';
|
|
3123
|
+
function query(endpoint, stage) {
|
|
3124
|
+
if (stage) check = stage;
|
|
3125
|
+
const r = spawnSync(cli, ['api', '--standalone', 'get', endpoint + '?location[directory]=' + encodeURIComponent(cwd)], { cwd, encoding: 'utf8', timeout: 10000, maxBuffer: 8 * 1024 * 1024 });
|
|
3126
|
+
if (r.status !== 0) throw new Error('OpenCode metadata unavailable');
|
|
3127
|
+
return JSON.parse(r.stdout).data;
|
|
3128
|
+
}
|
|
3129
|
+
function lookup(endpoint, stage, id) {
|
|
3130
|
+
// v2.2.6 list handlers await plugin activation; single-object get handlers deliberately do not.
|
|
3131
|
+
// Every CLI invocation owns a fresh --standalone server, so warming a previous process cannot fix this race.
|
|
3132
|
+
const list = query(endpoint, stage);
|
|
3133
|
+
if (!Array.isArray(list) || list.some(item => !item || typeof item !== 'object' || typeof item.id !== 'string')) throw new Error('Invalid metadata list');
|
|
3134
|
+
const matches = list.filter(item => item.id === id);
|
|
3135
|
+
if (matches.length > 1) throw new Error('Ambiguous metadata ID');
|
|
3136
|
+
return matches[0];
|
|
3137
|
+
}
|
|
3138
|
+
try {
|
|
3139
|
+
const version = spawnSync(cli, ['--version'], { encoding: 'utf8', timeout: 15000 });
|
|
3140
|
+
if (version.status !== 0 || !/^(?:opencode\s+)?v?2\.\d+\.\d+(?:[-+][\w.-]+)?\s*$/i.test(version.stdout)) throw new Error('Unsupported OpenCode version');
|
|
3141
|
+
if (mode === 'connections') {
|
|
3142
|
+
const list = query('/api/integration');
|
|
3143
|
+
if (!Array.isArray(list)) throw new Error('Invalid integrations');
|
|
3144
|
+
// Allowlist before data crosses the Box boundary; never return forms, commands or status URLs.
|
|
3145
|
+
process.stdout.write(JSON.stringify({ data: list.map(i => ({ id: i.id, name: i.name,
|
|
3146
|
+
methods: (i.methods || []).map(m => ({ id: m.id, type: m.type, label: m.label })),
|
|
3147
|
+
connections: (i.connections || []).map(c => ({ id: c.id, label: c.label, method: c.method, type: c.type, name: c.name, ...(c.status ? { status: true } : {}) })),
|
|
3148
|
+
})) }));
|
|
3149
|
+
} else {
|
|
3150
|
+
const models = query('/api/model', 'models');
|
|
3151
|
+
if (!Array.isArray(models)) throw new Error('Invalid model inventory');
|
|
3152
|
+
const selected = requested || !models.length ? null : query('/api/model/default', 'default-model');
|
|
3153
|
+
if (mode === 'models') {
|
|
3154
|
+
const clean = models.filter(m => m && m.enabled !== false && (!m.type || m.type === 'chat')).map(m => ({
|
|
3155
|
+
id: m.id, providerID: m.providerID, name: m.name,
|
|
3156
|
+
capabilities: { tools: m.capabilities?.tools === true },
|
|
3157
|
+
variants: Array.isArray(m.variants) ? m.variants.map(v => ({ id: v.id })) : [],
|
|
3158
|
+
}));
|
|
3159
|
+
process.stdout.write(JSON.stringify({ list: { data: clean }, selected: { data: selected && { id: selected.id, providerID: selected.providerID } } }));
|
|
3160
|
+
} else if (mode === 'readiness') {
|
|
3161
|
+
const evaluate = () => {
|
|
3162
|
+
check = 'models';
|
|
3163
|
+
const [ref, variant] = requested.split('#');
|
|
3164
|
+
const model = ref ? models.find(m => m && m.providerID + '/' + m.id === ref) : selected;
|
|
3165
|
+
if (!model) return 'model-not-listed';
|
|
3166
|
+
if (model.enabled === false) return 'model-disabled';
|
|
3167
|
+
if (model.type && model.type !== 'chat') return 'model-non-chat';
|
|
3168
|
+
if (model.capabilities?.tools !== true) return 'model-no-tools';
|
|
3169
|
+
if (variant && (!Array.isArray(model.variants) || !model.variants.some(v => v && v.id === variant))) return 'variant-unavailable';
|
|
3170
|
+
const provider = lookup('/api/provider', 'provider', model.providerID);
|
|
3171
|
+
if (!provider) return 'provider-not-listed';
|
|
3172
|
+
if (provider.activation === 'disabled') return 'provider-disabled';
|
|
3173
|
+
if (!provider.integrationID) return 'provider-no-integration';
|
|
3174
|
+
if (typeof provider.integrationID !== 'string') throw new Error('Invalid integration reference');
|
|
3175
|
+
const integration = lookup('/api/integration', 'integration', provider.integrationID);
|
|
3176
|
+
if (!integration) return 'integration-not-listed';
|
|
3177
|
+
if (!Array.isArray(integration.connections) || integration.connections.some(c => !c || typeof c !== 'object')) throw new Error('Invalid connection metadata');
|
|
3178
|
+
const connections = integration.connections;
|
|
3179
|
+
if (!connections.length) return 'no-connection';
|
|
3180
|
+
// This detailed mode is for the OAuth-only smoke gate, not the legacy any-provider status check.
|
|
3181
|
+
const oauth = connections.filter(c => c.type === 'credential' && c.method === 'oauth');
|
|
3182
|
+
if (!oauth.length) return 'oauth-unavailable';
|
|
3183
|
+
if (oauth.some(c => !c.status)) return 'ready';
|
|
3184
|
+
if (oauth.every(c => c.status && c.status.status === 'needs_auth')) return 'connection-needs-auth';
|
|
3185
|
+
return 'connection-status-unknown';
|
|
3186
|
+
};
|
|
3187
|
+
process.stdout.write(JSON.stringify({ state: evaluate() }));
|
|
3188
|
+
} else {
|
|
3189
|
+
const ref = requested.replace(/#[^#]*$/, '');
|
|
3190
|
+
const model = ref ? models.find(m => m.providerID + '/' + m.id === ref) : selected;
|
|
3191
|
+
let ready = false;
|
|
3192
|
+
if (model && model.enabled !== false && model.capabilities?.tools === true) {
|
|
3193
|
+
const provider = lookup('/api/provider', 'provider', model.providerID);
|
|
3194
|
+
if (!provider) throw new Error('Provider not listed');
|
|
3195
|
+
if (!provider.integrationID) ready = true;
|
|
3196
|
+
else {
|
|
3197
|
+
const integration = lookup('/api/integration', 'integration', provider.integrationID);
|
|
3198
|
+
if (!integration) throw new Error('Integration not listed');
|
|
3199
|
+
ready = Array.isArray(integration.connections) && integration.connections.some(c => !c.status);
|
|
3200
|
+
}
|
|
3201
|
+
}
|
|
3202
|
+
process.stdout.write(ready ? 'CUBEFARM_SIGNED_IN' : 'CUBEFARM_SIGNED_OUT');
|
|
3203
|
+
}
|
|
3204
|
+
}
|
|
3205
|
+
} catch {
|
|
3206
|
+
// An infrastructure/configuration error is NOT an expired login. No raw API output can leak.
|
|
3207
|
+
process.stdout.write(mode === 'readiness' ? JSON.stringify({ state: 'query-failed', check }) : 'CUBEFARM_OPENCODE_QUERY_FAILED');
|
|
3208
|
+
process.exitCode = 2;
|
|
3209
|
+
}
|
|
3210
|
+
`;
|
|
3211
|
+
var openCodeBoxQuery = (mode, directory = BOX_HOME, model2 = "") => `node ${sq(`${BOX_BIN}/opencode-query.cjs`)} ${sq(`${BOX_CLI_BIN}/opencode`)} ${sq(mode)} ${sq(directory)} ${sq(model2)}`;
|
|
3212
|
+
function parseOpenCodeReadiness(code, output) {
|
|
3213
|
+
const invalid = { state: "query-failed", check: "output" };
|
|
3214
|
+
try {
|
|
3215
|
+
if (output.length > 512) return invalid;
|
|
3216
|
+
const value = JSON.parse(output);
|
|
3217
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return invalid;
|
|
3218
|
+
if (value.state === "query-failed" && code !== 0 && Object.keys(value).length === 2 && READINESS_CHECKS.includes(value.check)) return { state: "query-failed", check: value.check };
|
|
3219
|
+
if (code === 0 && Object.keys(value).length === 1 && READINESS_STATES.includes(value.state)) return { state: value.state };
|
|
3220
|
+
} catch {
|
|
3221
|
+
}
|
|
3222
|
+
return invalid;
|
|
3223
|
+
}
|
|
3224
|
+
|
|
2951
3225
|
// server/ptyClient.ts
|
|
2952
3226
|
import crypto2 from "node:crypto";
|
|
2953
|
-
import
|
|
3227
|
+
import fs8 from "node:fs";
|
|
2954
3228
|
import net from "node:net";
|
|
2955
|
-
import
|
|
3229
|
+
import path9 from "node:path";
|
|
2956
3230
|
import { spawn } from "node:child_process";
|
|
2957
3231
|
|
|
2958
3232
|
// server/ptyProtocol.ts
|
|
2959
3233
|
import crypto from "node:crypto";
|
|
2960
|
-
import
|
|
3234
|
+
import path8 from "node:path";
|
|
2961
3235
|
var PTY_PROTOCOL = 1;
|
|
2962
3236
|
function hostSocket(home, platform = process.platform) {
|
|
2963
|
-
if (platform !== "win32") return
|
|
2964
|
-
const tag = crypto.createHash("sha1").update(
|
|
3237
|
+
if (platform !== "win32") return path8.join(home, "pty.sock");
|
|
3238
|
+
const tag = crypto.createHash("sha1").update(path8.resolve(home).toLowerCase()).digest("hex").slice(0, 12);
|
|
2965
3239
|
return `\\\\.\\pipe\\cubefarm-pty-${tag}`;
|
|
2966
3240
|
}
|
|
2967
3241
|
var encode = (m) => `${JSON.stringify(m)}
|
|
2968
3242
|
`;
|
|
3243
|
+
function ptyExitCode(value) {
|
|
3244
|
+
return typeof value === "number" && Number.isSafeInteger(value) ? value : -1;
|
|
3245
|
+
}
|
|
2969
3246
|
function readMessages(sock, onMessage2) {
|
|
2970
3247
|
let buf = "";
|
|
2971
3248
|
sock.setEncoding("utf8");
|
|
@@ -3054,7 +3331,7 @@ function onMessage(m) {
|
|
|
3054
3331
|
case "data":
|
|
3055
3332
|
return remote.get(m.id)?.data(m.data);
|
|
3056
3333
|
case "exit":
|
|
3057
|
-
return remote.get(m.id)?.exit(m.code);
|
|
3334
|
+
return remote.get(m.id)?.exit(ptyExitCode(m.code));
|
|
3058
3335
|
case "hook":
|
|
3059
3336
|
void Promise.resolve().then(() => hookHandler(m.token, m.body)).catch(() => ({})).then((answer) => send({ op: "hookReply", rid: m.rid, answer }));
|
|
3060
3337
|
return;
|
|
@@ -3092,7 +3369,7 @@ function connect(socket, secret) {
|
|
|
3092
3369
|
}
|
|
3093
3370
|
var runtimeFlags = () => process.execArgv.filter((a, i, all) => !/^--(inspect|watch|debug)/.test(a) && !/^--(inspect|watch|debug)/.test(all[i - 1] ?? ""));
|
|
3094
3371
|
function launch(socket, secretFile) {
|
|
3095
|
-
const entry =
|
|
3372
|
+
const entry = path9.join(import.meta.dirname, `ptyHost${path9.extname(import.meta.filename)}`);
|
|
3096
3373
|
spawn(process.execPath, [...runtimeFlags(), entry, "launch", socket, secretFile], { detached: true, stdio: "ignore", windowsHide: true }).once("error", () => void 0).unref();
|
|
3097
3374
|
}
|
|
3098
3375
|
var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
@@ -3100,17 +3377,17 @@ async function startKeeper(home, onHook) {
|
|
|
3100
3377
|
hookHandler = onHook;
|
|
3101
3378
|
if (!nodePty) return [];
|
|
3102
3379
|
const socket = hostSocket(home);
|
|
3103
|
-
const secretFile =
|
|
3380
|
+
const secretFile = path9.join(home, "pty.secret");
|
|
3104
3381
|
try {
|
|
3105
|
-
if (!
|
|
3106
|
-
|
|
3107
|
-
|
|
3382
|
+
if (!fs8.existsSync(secretFile)) {
|
|
3383
|
+
fs8.mkdirSync(home, { recursive: true });
|
|
3384
|
+
fs8.writeFileSync(secretFile, crypto2.randomBytes(24).toString("hex"), { mode: 384 });
|
|
3108
3385
|
}
|
|
3109
3386
|
} catch (err) {
|
|
3110
3387
|
console.warn(` terminal keeper unavailable: ${err.message}`);
|
|
3111
3388
|
return [];
|
|
3112
3389
|
}
|
|
3113
|
-
const secret =
|
|
3390
|
+
const secret = fs8.readFileSync(secretFile, "utf8").trim();
|
|
3114
3391
|
let hello = await connect(socket, secret);
|
|
3115
3392
|
if (hello && hello.ready.version !== PTY_PROTOCOL) {
|
|
3116
3393
|
console.log(` replacing the terminal keeper (v${hello.ready.version}); the ${hello.ready.ptys.length} terminal(s) it held are stopped`);
|
|
@@ -3157,7 +3434,7 @@ function spawnPty(file, args, o, meta) {
|
|
|
3157
3434
|
kill: () => killTree(p),
|
|
3158
3435
|
setMeta: () => void 0,
|
|
3159
3436
|
onData: (cb) => void p.onData(cb),
|
|
3160
|
-
onExit: (cb) => void p.onExit(({ exitCode: exitCode2 }) => cb(exitCode2))
|
|
3437
|
+
onExit: (cb) => void p.onExit(({ exitCode: exitCode2 }) => cb(ptyExitCode(exitCode2)))
|
|
3161
3438
|
};
|
|
3162
3439
|
}
|
|
3163
3440
|
function adoptPty(held) {
|
|
@@ -3190,8 +3467,8 @@ function killTree(proc) {
|
|
|
3190
3467
|
}
|
|
3191
3468
|
|
|
3192
3469
|
// server/cliRunner.ts
|
|
3193
|
-
var SESSIONS_DIR =
|
|
3194
|
-
var BIN_DIR =
|
|
3470
|
+
var SESSIONS_DIR = path10.join(HOME_DIR, "sessions");
|
|
3471
|
+
var BIN_DIR = path10.join(HOME_DIR, "bin");
|
|
3195
3472
|
var FINISH_GRACE_MS = 3e3;
|
|
3196
3473
|
var BOOT_MS = 6e4;
|
|
3197
3474
|
var USAGE_WARN_PCT = 90;
|
|
@@ -3217,14 +3494,14 @@ async function handleMcp(token, req, res) {
|
|
|
3217
3494
|
var helpersWritten = false;
|
|
3218
3495
|
function writeHelpers() {
|
|
3219
3496
|
if (helpersWritten) return;
|
|
3220
|
-
|
|
3221
|
-
|
|
3222
|
-
|
|
3223
|
-
|
|
3224
|
-
const pluginDir =
|
|
3225
|
-
|
|
3226
|
-
|
|
3227
|
-
|
|
3497
|
+
fs9.mkdirSync(BIN_DIR, { recursive: true });
|
|
3498
|
+
fs9.writeFileSync(path10.join(BIN_DIR, "statusline.cjs"), STATUSLINE_SOURCE);
|
|
3499
|
+
fs9.writeFileSync(path10.join(BIN_DIR, "notify.cjs"), NOTIFY_SOURCE);
|
|
3500
|
+
fs9.writeFileSync(path10.join(BIN_DIR, "codex-hook.cjs"), CODEX_HOOK_SOURCE);
|
|
3501
|
+
const pluginDir = path10.join(BIN_DIR, "opencode-plugin");
|
|
3502
|
+
fs9.mkdirSync(pluginDir, { recursive: true });
|
|
3503
|
+
fs9.writeFileSync(path10.join(pluginDir, "index.js"), OPENCODE_PLUGIN_SOURCE);
|
|
3504
|
+
fs9.writeFileSync(path10.join(pluginDir, "package.json"), JSON.stringify({ name: "droidsembly-office-plugin", type: "module", exports: "./index.js" }));
|
|
3228
3505
|
helpersWritten = true;
|
|
3229
3506
|
}
|
|
3230
3507
|
var shellArg = (p) => `"${p.replaceAll("\\", "/")}"`;
|
|
@@ -3277,7 +3554,7 @@ function endLive(live) {
|
|
|
3277
3554
|
live.proc = null;
|
|
3278
3555
|
live.term.note(`\u2500\u2500 ${cliLabel(live.cli)} session ended \u2500\u2500`);
|
|
3279
3556
|
if (live.box) return gone;
|
|
3280
|
-
|
|
3557
|
+
fs9.rm(live.dir, { recursive: true, force: true, maxRetries: 5 }, () => void 0);
|
|
3281
3558
|
if (live.cli === "codex" && live.resumeId) void codexThread("archive", live.resumeId, gone);
|
|
3282
3559
|
return gone;
|
|
3283
3560
|
}
|
|
@@ -3377,9 +3654,9 @@ function startBoxSignIn(o, exited) {
|
|
|
3377
3654
|
o.term.note(`\u2500\u2500 Signing ${cliLabel(o.cli)} in \xB7 \u2601 cloud machine \u2500\u2500`);
|
|
3378
3655
|
void (async () => {
|
|
3379
3656
|
try {
|
|
3380
|
-
await o.api.write(o.boxId, `${dir}/launch.json`, JSON.stringify({ ...signInCommand(o.cli), cwd: BOX_HOME, events: `${dir}/events.jsonl` }));
|
|
3657
|
+
await o.api.write(o.boxId, `${dir}/launch.json`, JSON.stringify({ ...signInCommand(o.cli), ...o.cli === "opencode" && o.authArgs ? { args: o.authArgs } : {}, cwd: BOX_HOME, events: `${dir}/events.jsonl` }));
|
|
3381
3658
|
if (over) return;
|
|
3382
|
-
const pty = boxPty(l, { api: o.api, boxId: o.boxId, record: () => void 0 }, o.term.cols, o.term.rows, 0, {});
|
|
3659
|
+
const pty = boxPty(l, { api: o.api, boxId: o.boxId, record: () => void 0 }, o.term.cols, o.term.rows, 0, o.cli === "opencode" ? OPENCODE_BOX_ENV : {});
|
|
3383
3660
|
l.proc = pty;
|
|
3384
3661
|
wire(l);
|
|
3385
3662
|
await pty.open("new");
|
|
@@ -3395,6 +3672,42 @@ function startBoxSignIn(o, exited) {
|
|
|
3395
3672
|
}
|
|
3396
3673
|
};
|
|
3397
3674
|
}
|
|
3675
|
+
function startOpenCodeAuth(o, exited) {
|
|
3676
|
+
const cmd = commandFor("opencode");
|
|
3677
|
+
if (!cmd) throw new Error("OpenCode is not installed on this computer.");
|
|
3678
|
+
const token = crypto3.randomUUID();
|
|
3679
|
+
const dir = path10.join(SESSIONS_DIR, token);
|
|
3680
|
+
fs9.mkdirSync(dir, { recursive: true });
|
|
3681
|
+
const l = { agentId: o.agentId, cli: "opencode", term: o.term, proc: null, token, dir, resumeId: null, statusLine: "", shots: /* @__PURE__ */ new Set(), session: null };
|
|
3682
|
+
let over = false;
|
|
3683
|
+
const end = (code) => {
|
|
3684
|
+
if (over) return;
|
|
3685
|
+
over = true;
|
|
3686
|
+
void endLive(l);
|
|
3687
|
+
exited(code);
|
|
3688
|
+
};
|
|
3689
|
+
l.session = { hook: () => ({}), exited: end };
|
|
3690
|
+
void checkOpenCodeVersion(cmd).then((problem) => {
|
|
3691
|
+
if (over) return;
|
|
3692
|
+
if (problem) {
|
|
3693
|
+
o.term.note(problem);
|
|
3694
|
+
end(-1);
|
|
3695
|
+
return;
|
|
3696
|
+
}
|
|
3697
|
+
try {
|
|
3698
|
+
const env = Object.fromEntries(Object.entries(process.env).filter((entry) => entry[1] !== void 0));
|
|
3699
|
+
l.proc = spawnPty(cmd.file, [...cmd.args, ...o.args], { cwd: o.cwd, cols: o.term.cols, rows: o.term.rows, env }, { kind: "opencode-auth" });
|
|
3700
|
+
wire(l);
|
|
3701
|
+
} catch {
|
|
3702
|
+
o.term.note("Could not start official OpenCode authentication.");
|
|
3703
|
+
end(-1);
|
|
3704
|
+
}
|
|
3705
|
+
}).catch(() => end(-1));
|
|
3706
|
+
return { stop() {
|
|
3707
|
+
over = true;
|
|
3708
|
+
void endLive(l);
|
|
3709
|
+
} };
|
|
3710
|
+
}
|
|
3398
3711
|
function hooksReady2() {
|
|
3399
3712
|
hooksReady();
|
|
3400
3713
|
boxHooksReady();
|
|
@@ -3451,7 +3764,7 @@ function startCliSession(opts, callbacks) {
|
|
|
3451
3764
|
const inBox = !!(box ?? live?.box);
|
|
3452
3765
|
const token = crypto3.randomUUID();
|
|
3453
3766
|
const sessionId = opts.resumeSessionId ?? crypto3.randomUUID();
|
|
3454
|
-
const dir = box ? boxSessionDir(token) :
|
|
3767
|
+
const dir = box ? boxSessionDir(token) : path10.join(SESSIONS_DIR, token);
|
|
3455
3768
|
const started = Date.now();
|
|
3456
3769
|
const statusLine = `\u{1F3E2} Droidsembly${opts.label ? ` \xB7 ${opts.label}` : ""}`;
|
|
3457
3770
|
const toolNames = /* @__PURE__ */ new Map();
|
|
@@ -3478,10 +3791,10 @@ function startCliSession(opts, callbacks) {
|
|
|
3478
3791
|
const collectShots = (all = false) => {
|
|
3479
3792
|
const l2 = live;
|
|
3480
3793
|
if (!l2 || l2.box || cli === "claude" || !opts.browserTesting) return;
|
|
3481
|
-
for (const shot of newScreenshots(
|
|
3794
|
+
for (const shot of newScreenshots(path10.join(l2.dir, "browser"), l2.shots, all ? Infinity : Date.now())) {
|
|
3482
3795
|
l2.shots.add(shot.name);
|
|
3483
3796
|
try {
|
|
3484
|
-
cb.screenshot(
|
|
3797
|
+
cb.screenshot(fs9.readFileSync(shot.file), shot.mime);
|
|
3485
3798
|
} catch {
|
|
3486
3799
|
}
|
|
3487
3800
|
}
|
|
@@ -3556,7 +3869,7 @@ function startCliSession(opts, callbacks) {
|
|
|
3556
3869
|
const m = text3.match(/\]\(([^)\s]+\.(png|jpe?g))\)/i);
|
|
3557
3870
|
const b = live?.box;
|
|
3558
3871
|
if (!m || !b) return;
|
|
3559
|
-
const file = m[1].startsWith("/") ? m[1] :
|
|
3872
|
+
const file = m[1].startsWith("/") ? m[1] : path10.posix.join(opts.cwd, m[1]);
|
|
3560
3873
|
const data = await b.api.read(b.boxId, file, { base64: true }).catch(() => null);
|
|
3561
3874
|
if (data) cb.screenshot(Buffer.from(data, "base64"), /png$/i.test(m[2]) ? "image/png" : "image/jpeg");
|
|
3562
3875
|
};
|
|
@@ -3592,7 +3905,7 @@ function startCliSession(opts, callbacks) {
|
|
|
3592
3905
|
const event = String(b.hook_event_name ?? "");
|
|
3593
3906
|
const sub = typeof b.agent_id === "string" && b.agent_id !== "";
|
|
3594
3907
|
if (cli === "claude" && !sub && b.session_id !== kept) {
|
|
3595
|
-
const id = resumableSession(b, inBox ? () => b.transcript_exists === true :
|
|
3908
|
+
const id = resumableSession(b, inBox ? () => b.transcript_exists === true : fs9.existsSync);
|
|
3596
3909
|
if (id) {
|
|
3597
3910
|
kept = id;
|
|
3598
3911
|
cb.sessionId(id);
|
|
@@ -3658,6 +3971,11 @@ function startCliSession(opts, callbacks) {
|
|
|
3658
3971
|
}
|
|
3659
3972
|
case "UserPromptSubmit": {
|
|
3660
3973
|
if (sub) return {};
|
|
3974
|
+
if (cli === "opencode" && inBox && live && typeof b.session_id === "string" && live.resumeId !== b.session_id) {
|
|
3975
|
+
live.resumeId = b.session_id;
|
|
3976
|
+
cb.sessionId(b.session_id);
|
|
3977
|
+
remember(live);
|
|
3978
|
+
}
|
|
3661
3979
|
busy2();
|
|
3662
3980
|
const prompt2 = String(b.prompt ?? "").trim();
|
|
3663
3981
|
const i = officePrompts.findIndex((p2) => p2.slice(0, 60) === prompt2.slice(0, 60));
|
|
@@ -3718,12 +4036,20 @@ function startCliSession(opts, callbacks) {
|
|
|
3718
4036
|
case "TurnError":
|
|
3719
4037
|
turnError = `${label}: ${clip(String(b.error ?? "error"), 200)}`;
|
|
3720
4038
|
log([{ kind: "error", text: `\u2717 ${turnError}` }]);
|
|
4039
|
+
if (inBox && b.signed_out === true) {
|
|
4040
|
+
finish({ ok: false, text: lastText, errors: [`${label}'s provider connection needs sign-in.`], signedOut: true });
|
|
4041
|
+
return {};
|
|
4042
|
+
}
|
|
3721
4043
|
turnEnded(lastText);
|
|
3722
4044
|
return {};
|
|
3723
4045
|
}
|
|
3724
4046
|
return {};
|
|
3725
4047
|
};
|
|
3726
4048
|
const exited = (exitCode2) => {
|
|
4049
|
+
if (cli === "opencode" && turnError) {
|
|
4050
|
+
finish({ ok: false, text: lastText, errors: [turnError] });
|
|
4051
|
+
return;
|
|
4052
|
+
}
|
|
3727
4053
|
if (cli === "claude" && opts.resumeSessionId && !begun && lostConversation(term.screen())) {
|
|
3728
4054
|
cb.sessionId(null);
|
|
3729
4055
|
finish({ ok: false, text: "", errors: [`${label} couldn't find the conversation it was resuming, so the next session starts a new one.`] });
|
|
@@ -3765,10 +4091,6 @@ function startCliSession(opts, callbacks) {
|
|
|
3765
4091
|
return handle;
|
|
3766
4092
|
}
|
|
3767
4093
|
const cmd = box ? { file: `${BOX_CLI_BIN}/${CLIS.find((c) => c.id === cli).command}`, args: [] } : commandFor(cli);
|
|
3768
|
-
if (box && cli === "opencode") {
|
|
3769
|
-
setTimeout(() => finish({ ok: false, text: "", errors: [`${label} can't run in a cloud machine yet: give this agent Claude Code or Codex.`] }), 0);
|
|
3770
|
-
return handle;
|
|
3771
|
-
}
|
|
3772
4094
|
if (!box && (!terminalsAvailable || !cmd)) {
|
|
3773
4095
|
const why2 = !terminalsAvailable ? "the terminal module could not be loaded on this machine" : `${label} isn't installed (no "${cli}" on PATH)`;
|
|
3774
4096
|
setTimeout(() => finish({ ok: false, text: "", errors: [`Could not start ${label}: ${why2}.`] }), 0);
|
|
@@ -3777,8 +4099,8 @@ function startCliSession(opts, callbacks) {
|
|
|
3777
4099
|
const keeper = box ? null : keeperHookUrl();
|
|
3778
4100
|
const events = `${dir}/events.jsonl`;
|
|
3779
4101
|
const hookUrl = box ? events : `${keeper ?? officeUrl}/api/hooks/${token}`;
|
|
3780
|
-
const p = box ?
|
|
3781
|
-
const browser = !opts.browserTesting ? null : box ? box.browser ? { command: `${BOX_CLI_BIN}/playwright-mcp`, args: ["--cdp-endpoint", BOX_CDP, "--output-dir", `${dir}/browser`] } : null : playwrightMcp(
|
|
4102
|
+
const p = box ? path10.posix : path10;
|
|
4103
|
+
const browser = !opts.browserTesting ? null : box ? box.browser ? { command: `${BOX_CLI_BIN}/playwright-mcp`, args: ["--cdp-endpoint", BOX_CDP, "--output-dir", `${dir}/browser`] } : null : playwrightMcp(path10.join(dir, "browser"));
|
|
3782
4104
|
const browserIssue = !opts.browserTesting ? null : box ? box.browser ? null : "\u26A0 This cloud machine has no browser, so this session can't test in one." : browserProblem(browser);
|
|
3783
4105
|
if (browserIssue) log([{ kind: "error", text: browserIssue }]);
|
|
3784
4106
|
let prompt = opts.prompt;
|
|
@@ -3790,16 +4112,16 @@ ${JSON.stringify(opts.outputSchema)}`;
|
|
|
3790
4112
|
}
|
|
3791
4113
|
let files;
|
|
3792
4114
|
const boxFiles = [];
|
|
3793
|
-
const put = (file, text3) => box ? boxFiles.push([file, text3]) :
|
|
4115
|
+
const put = (file, text3) => box ? boxFiles.push([file, text3]) : fs9.writeFileSync(file, text3);
|
|
3794
4116
|
try {
|
|
3795
4117
|
if (!box) {
|
|
3796
4118
|
writeHelpers();
|
|
3797
|
-
|
|
4119
|
+
fs9.mkdirSync(dir, { recursive: true });
|
|
3798
4120
|
}
|
|
3799
4121
|
const boxHook = `node ${BOX_BIN}/hook.cjs ${events}`;
|
|
3800
4122
|
const settings = {
|
|
3801
4123
|
hooks: Object.fromEntries(HOOK_EVENTS.map((e) => [e, [{ hooks: [box ? { type: "command", command: boxHook, timeout: 30 } : { type: "http", url: hookUrl, timeout: keeper ? 120 : 30 }] }]])),
|
|
3802
|
-
statusLine: box ? { type: "command", command: `node ${BOX_BIN}/statusline.cjs ${events}`, padding: 0 } : { type: "command", command: `${shellArg(process.execPath)} ${shellArg(
|
|
4124
|
+
statusLine: box ? { type: "command", command: `node ${BOX_BIN}/statusline.cjs ${events}`, padding: 0 } : { type: "command", command: `${shellArg(process.execPath)} ${shellArg(path10.join(BIN_DIR, "statusline.cjs"))} ${shellArg(hookUrl)}`, padding: 0 },
|
|
3803
4125
|
...box?.apiKeyHelper ? { apiKeyHelper: box.apiKeyHelper } : {}
|
|
3804
4126
|
};
|
|
3805
4127
|
const servers = {};
|
|
@@ -3829,17 +4151,18 @@ ${JSON.stringify(opts.outputSchema)}`;
|
|
|
3829
4151
|
sessionId,
|
|
3830
4152
|
name: opts.label ?? "Droidsembly",
|
|
3831
4153
|
role: opts.role,
|
|
4154
|
+
openCodePermissions: opts.openCodePermissions,
|
|
3832
4155
|
additionalDirectories: opts.additionalDirectories,
|
|
3833
4156
|
files,
|
|
3834
|
-
notify: box ? { script: `${BOX_BIN}/notify.cjs`, url: events } : { script:
|
|
3835
|
-
codexHook: box ? `${BOX_BIN}/codex-hook.cjs` :
|
|
3836
|
-
plugin: box ?
|
|
4157
|
+
notify: box ? { script: `${BOX_BIN}/notify.cjs`, url: events } : { script: path10.join(BIN_DIR, "notify.cjs"), url: hookUrl },
|
|
4158
|
+
codexHook: box ? `${BOX_BIN}/codex-hook.cjs` : path10.join(BIN_DIR, "codex-hook.cjs"),
|
|
4159
|
+
plugin: box ? `file://${BOX_BIN}/opencode-plugin` : pathToFileURL(path10.join(BIN_DIR, "opencode-plugin")).href,
|
|
3837
4160
|
...opts.office && !box ? { officeUrl: `${officeUrl}/api/mcp/${token}` } : {},
|
|
3838
4161
|
browser,
|
|
3839
4162
|
...box ? { node: "node", posix: true } : {}
|
|
3840
4163
|
});
|
|
3841
4164
|
const env = {};
|
|
3842
|
-
if (box) Object.assign(env, BOX_ENV, box.env, launch2.env, { CUBEFARM_STATUS: statusLine });
|
|
4165
|
+
if (box) Object.assign(env, BOX_ENV, box.env, cli === "opencode" ? OPENCODE_BOX_ENV : {}, launch2.env, { CUBEFARM_STATUS: statusLine });
|
|
3843
4166
|
else {
|
|
3844
4167
|
for (const [k, v] of Object.entries(process.env)) {
|
|
3845
4168
|
if (v === void 0) continue;
|
|
@@ -3903,7 +4226,8 @@ ${JSON.stringify(opts.outputSchema)}`;
|
|
|
3903
4226
|
const beginInBox = async (b) => {
|
|
3904
4227
|
try {
|
|
3905
4228
|
boxFiles.push([`${dir}/launch.json`, JSON.stringify({ file: cmd.file, args: [...cmd.args, ...launch2.args], cwd: opts.cwd, events })]);
|
|
3906
|
-
|
|
4229
|
+
if (cli === "opencode") await writeBoxSessionFiles(b.api, b.boxId, dir, boxFiles);
|
|
4230
|
+
else for (const [file, text3] of boxFiles) await b.api.write(b.boxId, file, text3);
|
|
3907
4231
|
if (done) return;
|
|
3908
4232
|
const pty = boxPty(l, b, term.cols, term.rows, 0, env);
|
|
3909
4233
|
l.proc = pty;
|
|
@@ -3928,30 +4252,30 @@ ${JSON.stringify(opts.outputSchema)}`;
|
|
|
3928
4252
|
}
|
|
3929
4253
|
|
|
3930
4254
|
// server/machines.ts
|
|
3931
|
-
import
|
|
4255
|
+
import fs11 from "node:fs";
|
|
3932
4256
|
|
|
3933
4257
|
// server/deps.ts
|
|
3934
4258
|
import { spawn as spawn2 } from "node:child_process";
|
|
3935
4259
|
import crypto4 from "node:crypto";
|
|
3936
|
-
import
|
|
3937
|
-
import
|
|
4260
|
+
import fs10 from "node:fs/promises";
|
|
4261
|
+
import path11 from "node:path";
|
|
3938
4262
|
var INSTALL_MARKER = ".cubefarm-preview-install";
|
|
3939
4263
|
var INSTALL_TIMEOUT_MS = 15 * 6e4;
|
|
3940
4264
|
var INSTALL_PROGRESS_MS = 6e4;
|
|
3941
4265
|
var MAX_DESK_INSTALLS = 2;
|
|
3942
4266
|
var depsHash = (pkg, lock) => crypto4.createHash("sha256").update(pkg).update("\0").update(lock ?? "").digest("hex");
|
|
3943
4267
|
async function readDeps(dir) {
|
|
3944
|
-
const read = (file) =>
|
|
3945
|
-
const [pkg, lock,
|
|
4268
|
+
const read = (file) => fs10.readFile(path11.join(dir, file), "utf8").catch(() => null);
|
|
4269
|
+
const [pkg, lock, marker2, nodeModules] = await Promise.all([
|
|
3946
4270
|
read("package.json"),
|
|
3947
4271
|
read("package-lock.json"),
|
|
3948
|
-
read(
|
|
3949
|
-
|
|
4272
|
+
read(path11.join("node_modules", INSTALL_MARKER)),
|
|
4273
|
+
fs10.stat(path11.join(dir, "node_modules")).then((s2) => s2.isDirectory()).catch(() => false)
|
|
3950
4274
|
]);
|
|
3951
|
-
return { pkg, lock, hash: depsHash(pkg ?? "", lock), marker:
|
|
4275
|
+
return { pkg, lock, hash: depsHash(pkg ?? "", lock), marker: marker2 ?? "", nodeModules };
|
|
3952
4276
|
}
|
|
3953
4277
|
var depsCurrent = (s2) => s2.nodeModules && s2.marker === s2.hash;
|
|
3954
|
-
var writeMarker = (dir, hash) =>
|
|
4278
|
+
var writeMarker = (dir, hash) => fs10.writeFile(path11.join(dir, "node_modules", INSTALL_MARKER), hash).catch(() => void 0);
|
|
3955
4279
|
function deskDepsPlan(s2) {
|
|
3956
4280
|
if (s2.pkg === null) return "none";
|
|
3957
4281
|
if (s2.lock === null) return "agent";
|
|
@@ -4066,7 +4390,7 @@ function localMachines(keep) {
|
|
|
4066
4390
|
prepareDesk: (machine, fullName, base, branch, note2) => prepareMachineDesk(machine, fullName, base, branch, note2),
|
|
4067
4391
|
env: (machine) => {
|
|
4068
4392
|
const tmp = machineTmp(machine);
|
|
4069
|
-
|
|
4393
|
+
fs11.mkdirSync(tmp, { recursive: true });
|
|
4070
4394
|
return { TMP: tmp, TEMP: tmp, TMPDIR: tmp };
|
|
4071
4395
|
},
|
|
4072
4396
|
release: (machine, fullName, port) => releaseMachine(machine, fullName, port, keep()),
|
|
@@ -4074,7 +4398,7 @@ function localMachines(keep) {
|
|
|
4074
4398
|
sweep: (machine, fullName, keepBranches) => sweepMachine(machine, fullName, keepBranches),
|
|
4075
4399
|
remove: (machine) => removeMachine(machine),
|
|
4076
4400
|
list: () => listMachines(),
|
|
4077
|
-
exists: async (machine, fullName) =>
|
|
4401
|
+
exists: async (machine, fullName) => fs11.existsSync(machineDesk(machine, fullName)),
|
|
4078
4402
|
installDeps: (machine, fullName, cb) => installDesk(machineDesk(machine, fullName), cb)
|
|
4079
4403
|
};
|
|
4080
4404
|
}
|
|
@@ -4133,11 +4457,70 @@ var openCodeModels = createModelCatalogReader(async (directory) => {
|
|
|
4133
4457
|
}
|
|
4134
4458
|
});
|
|
4135
4459
|
|
|
4460
|
+
// shared/opencodeConnections.ts
|
|
4461
|
+
function sanitizeConnections(value) {
|
|
4462
|
+
const data = value?.data;
|
|
4463
|
+
if (!Array.isArray(data)) throw new Error("Invalid OpenCode connections");
|
|
4464
|
+
const text3 = (v) => typeof v === "string" && !!v && v.length <= 512 && !/[\x00-\x1f\x7f]/.test(v);
|
|
4465
|
+
return data.flatMap((i) => {
|
|
4466
|
+
if (!i || !text3(i.id) || !text3(i.name) || !Array.isArray(i.methods) || !Array.isArray(i.connections)) return [];
|
|
4467
|
+
return [{
|
|
4468
|
+
id: i.id,
|
|
4469
|
+
name: i.name,
|
|
4470
|
+
methods: i.methods.flatMap((m) => {
|
|
4471
|
+
if (!m || !["key", "oauth", "command", "external", "env"].includes(String(m.type))) return [];
|
|
4472
|
+
const id = m.type === "key" || m.type === "env" ? m.type : m.id;
|
|
4473
|
+
if (!text3(id)) return [];
|
|
4474
|
+
return [{ id, type: m.type, label: text3(m.label) ? m.label : String(m.type) }];
|
|
4475
|
+
}),
|
|
4476
|
+
connections: i.connections.flatMap((c) => {
|
|
4477
|
+
if (!c || !["credential", "env"].includes(String(c.type))) return [];
|
|
4478
|
+
const environment = c.type === "env";
|
|
4479
|
+
const id = environment ? c.name : c.id;
|
|
4480
|
+
if (!text3(id) || !environment && (!text3(c.label) || !["key", "oauth", "external"].includes(String(c.method)))) return [];
|
|
4481
|
+
return [{ id, label: environment ? id : c.label, method: environment ? "env" : String(c.method), environment, needsAuth: !!c.status }];
|
|
4482
|
+
})
|
|
4483
|
+
}];
|
|
4484
|
+
});
|
|
4485
|
+
}
|
|
4486
|
+
function connectionArgs(integrations, input) {
|
|
4487
|
+
const a = input;
|
|
4488
|
+
if (!a || typeof a !== "object") throw new Error("Invalid connection action");
|
|
4489
|
+
if (Object.keys(a).some((k) => !["action", "integration", a.action === "login" ? "method" : "account"].includes(k))) throw new Error("Only provider, method and account IDs are accepted; enter credentials in the official terminal.");
|
|
4490
|
+
const i = integrations.find((i2) => i2.id === a.integration);
|
|
4491
|
+
if (!i || i.id.startsWith("-")) throw new Error("Unknown OpenCode provider");
|
|
4492
|
+
if (a.action === "login" && "method" in a) {
|
|
4493
|
+
const m = i.methods.find((m2) => m2.id === a.method);
|
|
4494
|
+
if (!m || m.type === "env" || m.id.startsWith("-")) throw new Error("Choose a supported interactive authentication method");
|
|
4495
|
+
return ["auth", "login", i.id, "--method", m.id];
|
|
4496
|
+
}
|
|
4497
|
+
if (a.action === "switch" && "account" in a) {
|
|
4498
|
+
const c = i.connections.find((c2) => c2.id === a.account && !c2.environment);
|
|
4499
|
+
if (!c || c.id.startsWith("-")) throw new Error("Unknown saved OpenCode account");
|
|
4500
|
+
return ["auth", "switch", i.id, c.id];
|
|
4501
|
+
}
|
|
4502
|
+
throw new Error("Invalid connection action");
|
|
4503
|
+
}
|
|
4504
|
+
|
|
4505
|
+
// server/opencodeConnections.ts
|
|
4506
|
+
async function openCodeConnections(directory) {
|
|
4507
|
+
const cmd = commandFor("opencode");
|
|
4508
|
+
if (!cmd) throw new Error("OpenCode is not installed on this computer.");
|
|
4509
|
+
const problem = await checkOpenCodeVersion(cmd);
|
|
4510
|
+
if (problem) throw new Error(problem);
|
|
4511
|
+
try {
|
|
4512
|
+
const text3 = await run(cmd.file, [...cmd.args, "api", "get", `/api/integration?location[directory]=${encodeURIComponent(directory)}`], { timeoutMs: 3e4 });
|
|
4513
|
+
return sanitizeConnections(JSON.parse(text3));
|
|
4514
|
+
} catch {
|
|
4515
|
+
throw new Error("Could not read OpenCode connections. No credentials were changed.");
|
|
4516
|
+
}
|
|
4517
|
+
}
|
|
4518
|
+
|
|
4136
4519
|
// server/previewRunner.ts
|
|
4137
4520
|
import { spawn as spawn3 } from "node:child_process";
|
|
4138
|
-
import
|
|
4521
|
+
import fs12 from "node:fs/promises";
|
|
4139
4522
|
import net2 from "node:net";
|
|
4140
|
-
import
|
|
4523
|
+
import path12 from "node:path";
|
|
4141
4524
|
var PREVIEW_SLUG = "preview";
|
|
4142
4525
|
var PREVIEW_BRANCH = "swarm-preview";
|
|
4143
4526
|
var PREVIEW_TMP = ".preview-tmp";
|
|
@@ -4171,7 +4554,7 @@ async function portOpen(port) {
|
|
|
4171
4554
|
var sleep3 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
4172
4555
|
async function readJson(file) {
|
|
4173
4556
|
try {
|
|
4174
|
-
return JSON.parse(await
|
|
4557
|
+
return JSON.parse(await fs12.readFile(file, "utf8"));
|
|
4175
4558
|
} catch {
|
|
4176
4559
|
return null;
|
|
4177
4560
|
}
|
|
@@ -4216,9 +4599,9 @@ var RealPreview = class {
|
|
|
4216
4599
|
this.check();
|
|
4217
4600
|
await ensureLocalExcludes(job.fullName).catch(() => void 0);
|
|
4218
4601
|
cb.commit(await git(["rev-parse", "--short", "HEAD"], { cwd: wt }).catch(() => ""));
|
|
4219
|
-
const tmp =
|
|
4220
|
-
await
|
|
4221
|
-
const pkg = await readJson(
|
|
4602
|
+
const tmp = path12.join(wt, PREVIEW_TMP);
|
|
4603
|
+
await fs12.mkdir(tmp, { recursive: true });
|
|
4604
|
+
const pkg = await readJson(path12.join(wt, "package.json"));
|
|
4222
4605
|
const command = job.command ?? defaultCommand(pkg);
|
|
4223
4606
|
if (!command) {
|
|
4224
4607
|
this.stopped = true;
|
|
@@ -4303,16 +4686,16 @@ var RealPreview = class {
|
|
|
4303
4686
|
};
|
|
4304
4687
|
var realPreviews = {
|
|
4305
4688
|
start: (job, cb) => new RealPreview(job, cb),
|
|
4306
|
-
hasDefault: async (fullName) =>
|
|
4689
|
+
hasDefault: async (fullName) => fs12.access(path12.join(mainDir(fullName), "package.json")).then(() => true).catch(() => false)
|
|
4307
4690
|
};
|
|
4308
4691
|
|
|
4309
4692
|
// server/officeUpdate.ts
|
|
4310
|
-
import
|
|
4311
|
-
import
|
|
4693
|
+
import fs13 from "node:fs/promises";
|
|
4694
|
+
import path13 from "node:path";
|
|
4312
4695
|
var DRAIN_TIMEOUT_MS = 20 * 6e4;
|
|
4313
4696
|
var POSTPONE_MS = 2 * 60 * 6e4;
|
|
4314
4697
|
function underLauncher(proc = process) {
|
|
4315
|
-
return typeof proc.send === "function" && proc.env
|
|
4698
|
+
return typeof proc.send === "function" && officeEnv(proc.env, "SWARM_LAUNCHER") === "1";
|
|
4316
4699
|
}
|
|
4317
4700
|
function drainDecision(s2) {
|
|
4318
4701
|
const idle2 = (state2) => ({ state: state2, drainingSince: null, send: false, timedOut: false });
|
|
@@ -4345,10 +4728,10 @@ function parseLastUpdate(raw) {
|
|
|
4345
4728
|
}
|
|
4346
4729
|
}
|
|
4347
4730
|
async function takeLastUpdate(home) {
|
|
4348
|
-
const file =
|
|
4349
|
-
const raw = await
|
|
4731
|
+
const file = path13.join(home, "last-update.json");
|
|
4732
|
+
const raw = await fs13.readFile(file, "utf8").catch(() => null);
|
|
4350
4733
|
if (raw === null) return null;
|
|
4351
|
-
await
|
|
4734
|
+
await fs13.rm(file, { force: true, maxRetries: 3 }).catch(() => void 0);
|
|
4352
4735
|
return parseLastUpdate(raw);
|
|
4353
4736
|
}
|
|
4354
4737
|
function lastUpdateMessage(u, commits) {
|
|
@@ -4356,8 +4739,8 @@ function lastUpdateMessage(u, commits) {
|
|
|
4356
4739
|
const n = commits === null ? "" : ` (${commits} commit${commits === 1 ? "" : "s"})`;
|
|
4357
4740
|
return `\u2B06\uFE0F Updated the office from ${u.from.slice(0, 7)} to ${u.to.slice(0, 7)}${n}`;
|
|
4358
4741
|
}
|
|
4359
|
-
var OFFICE_DIR =
|
|
4360
|
-
var isSamePath = (a, b) => process.platform === "win32" ?
|
|
4742
|
+
var OFFICE_DIR = path13.resolve(import.meta.dirname, "..");
|
|
4743
|
+
var isSamePath = (a, b) => process.platform === "win32" ? path13.resolve(a).toLowerCase() === path13.resolve(b).toLowerCase() : path13.resolve(a) === path13.resolve(b);
|
|
4361
4744
|
var realOffice = {
|
|
4362
4745
|
launcher: underLauncher(),
|
|
4363
4746
|
head: () => git(["rev-parse", "HEAD"], { cwd: OFFICE_DIR }).catch(() => null),
|
|
@@ -4373,11 +4756,38 @@ var realOffice = {
|
|
|
4373
4756
|
|
|
4374
4757
|
// server/voice.ts
|
|
4375
4758
|
import crypto5 from "node:crypto";
|
|
4376
|
-
import
|
|
4377
|
-
import
|
|
4759
|
+
import fs14 from "node:fs/promises";
|
|
4760
|
+
import path14 from "node:path";
|
|
4378
4761
|
|
|
4379
4762
|
// shared/italianUi.ts
|
|
4380
4763
|
var italianUi = {
|
|
4764
|
+
"OpenCode connections": "Connessioni OpenCode",
|
|
4765
|
+
"Continue": "Continua",
|
|
4766
|
+
"Open terminal": "Apri terminale",
|
|
4767
|
+
"Could not load connections.": "Impossibile caricare le connessioni.",
|
|
4768
|
+
"Change OpenCode connection?": "Cambiare connessione OpenCode?",
|
|
4769
|
+
"This changes the shared OpenCode account on this computer, not just this agent. Stop all work and close coding-agent terminals first. Continue?": "La modifica riguarda l\u2019account OpenCode condiviso su questo computer, non solo questo agente. Prima ferma le attivit\xE0 e chiudi le sessioni degli strumenti di sviluppo. Continuare?",
|
|
4770
|
+
"This changes OpenCode accounts in this Box only. Stop all work and close coding-agent terminals first. Continue?": "La modifica riguarda gli account OpenCode solo in questa Box. Prima ferma le attivit\xE0 e chiudi le sessioni degli strumenti di sviluppo. Continuare?",
|
|
4771
|
+
"Authentication started in the terminal. Finish there, then refresh connections. Selection alone does not activate an account.": "Autenticazione avviata nel terminale. Completala l\xEC, poi aggiorna le connessioni. La sola selezione non attiva un account.",
|
|
4772
|
+
"Choose a provider and authentication method, or activate a saved account. Credentials are entered only in OpenCode\u2019s official terminal flow, never in these fields.": "Scegli provider e metodo di autenticazione, oppure attiva un account salvato. Le credenziali si inseriscono solo nel flusso ufficiale OpenCode nel terminale, mai in questi campi.",
|
|
4773
|
+
"Scope: this Box. Other Boxes and this computer are separate. Using the same subscription still shares its usage limits.": "Ambito: questa Box. Le altre Box e questo computer sono separati. Usare lo stesso abbonamento comporta comunque limiti di utilizzo condivisi.",
|
|
4774
|
+
"Scope: shared OpenCode environment on this computer, including other local agents. No per-agent account isolation.": "Ambito: ambiente OpenCode condiviso su questo computer, inclusi gli altri agenti locali. Gli account non sono isolati per agente.",
|
|
4775
|
+
"API keys use provider API billing. OAuth may use a subscription only when the provider supports it; check the method and provider terms.": "Le API key usano la fatturazione API del provider. OAuth pu\xF2 usare un abbonamento solo se il provider lo supporta: verifica metodo e condizioni del provider.",
|
|
4776
|
+
"Refresh connections": "Aggiorna connessioni",
|
|
4777
|
+
"Loading connections\u2026": "Caricamento connessioni\u2026",
|
|
4778
|
+
"OpenCode authentication is running. Finish in its terminal or stop the connection operation.": "Autenticazione OpenCode in corso. Completala nel suo terminale oppure interrompi l\u2019operazione di connessione.",
|
|
4779
|
+
"Stop connection operation": "Interrompi operazione di connessione",
|
|
4780
|
+
"Select a provider": "Seleziona un provider",
|
|
4781
|
+
"Authentication method": "Metodo di autenticazione",
|
|
4782
|
+
"Select an authentication method": "Seleziona un metodo di autenticazione",
|
|
4783
|
+
"Environment credentials are managed on this host, not saved or copied by the app. Use the provider\u2019s official setup instructions.": "Le credenziali d\u2019ambiente si gestiscono su questa macchina: l\u2019app non le salva n\xE9 le copia. Segui le istruzioni ufficiali del provider.",
|
|
4784
|
+
"Add account in terminal": "Aggiungi account nel terminale",
|
|
4785
|
+
"Saved account / profile": "Account / profilo salvato",
|
|
4786
|
+
"Select an account": "Seleziona un account",
|
|
4787
|
+
"needs sign-in": "accesso necessario",
|
|
4788
|
+
"Activate account in terminal": "Attiva account nel terminale",
|
|
4789
|
+
"The public API lists saved accounts but does not identify the active one. Verify the active account with OpenCode auth list. Accounts persist in OpenCode on this host, not as an app preference.": "L\u2019API pubblica elenca gli account salvati, ma non identifica quello attivo. Verificalo con OpenCode auth list. Gli account restano salvati in OpenCode su questa macchina, non come preferenza dell\u2019app.",
|
|
4790
|
+
"In the agent\u2019s Setup, open OpenCode connections to choose a provider, authentication method and saved account. Account changes apply to that Box, not to this computer or other Boxes.": "Nella Configurazione dell\u2019agente, apri Connessioni OpenCode per scegliere provider, metodo di autenticazione e account salvato. Le modifiche agli account riguardano quella Box, non questo computer o le altre Box.",
|
|
4381
4791
|
"Look around": "Guardati intorno",
|
|
4382
4792
|
"Pull out your phone": "Apri il telefono",
|
|
4383
4793
|
"Visit the CEO": "Visita il CEO",
|
|
@@ -4759,7 +5169,7 @@ var italianUi = {
|
|
|
4759
5169
|
"Where they work": "Dove lavora",
|
|
4760
5170
|
"Works on": "Lavora su",
|
|
4761
5171
|
" (connect Upstash in Settings first)": " (collega prima Upstash nelle Impostazioni)",
|
|
4762
|
-
"
|
|
5172
|
+
"OpenCode signs in to its selected provider in each Box. Use Sign in in the agent terminal, then browse models in that agent\u2019s Setup. Local OpenCode accounts and the Claude/Codex keys below are not copied or reused.": "OpenCode accede al provider scelto in ogni Box. Usa Accedi nel terminale dell\u2019agente, poi consulta i modelli nella sua Configurazione. Gli account OpenCode locali e le chiavi Claude/Codex qui sotto non vengono copiati n\xE9 riutilizzati.",
|
|
4763
5173
|
"no Box yet": "nessun Box",
|
|
4764
5174
|
"creating their Box\u2026": "creazione del Box\u2026",
|
|
4765
5175
|
"setting up their Box\u2026": "configurazione del Box\u2026",
|
|
@@ -4826,6 +5236,23 @@ var italianUi = {
|
|
|
4826
5236
|
"It\u2019s deleted from the office. Cloud agents that need it can\u2019t sign in until you add it again.": "Viene eliminato dall\u2019ufficio. Gli agenti cloud che ne hanno bisogno non potranno accedere finch\xE9 non lo aggiungerai di nuovo.",
|
|
4827
5237
|
"Not set up yet": "Non ancora configurato",
|
|
4828
5238
|
"\u2713 Connected": "\u2713 Connesso",
|
|
5239
|
+
"First cloud task: four checks": "Primo incarico cloud: quattro controlli",
|
|
5240
|
+
"Save and test the Upstash key, then confirm GitHub access to the intended repositories.": "Salva e verifica la chiave Upstash, poi conferma l\u2019accesso GitHub ai repository previsti.",
|
|
5241
|
+
"Choose a cloud agent, coding agent and model in Setup before signing in.": "Scegli agente cloud, strumento di sviluppo e modello in Configurazione prima dell\u2019accesso.",
|
|
5242
|
+
"Use Sign in on the agent card and finish the official provider login in that Box terminal. Never copy a PC login file.": "Usa Accedi sulla scheda dell\u2019agente e completa il login ufficiale nel terminale della Box. Non copiare file di accesso dal PC.",
|
|
5243
|
+
"Check model access and provider quota, then assign one task. A ready Box or saved account is not proof of available AI quota.": "Verifica accesso al modello e quota del provider, poi assegna un incarico. Una Box pronta o un account salvato non dimostrano disponibilit\xE0 di quota AI.",
|
|
5244
|
+
"Cloud work and spending awareness": "Lavoro cloud e consapevolezza dei consumi",
|
|
5245
|
+
"Pause new cloud work": "Sospendi nuovi lavori cloud",
|
|
5246
|
+
"Resume": "Riprendi",
|
|
5247
|
+
"New cloud work is paused. Local work and the CEO are unaffected.": "I nuovi lavori cloud sono sospesi. Lavoro locale e CEO restano attivi.",
|
|
5248
|
+
"Resume new cloud work?": "Riprendere i nuovi lavori cloud?",
|
|
5249
|
+
"Queued cloud issues, QA and fixes may start and consume provider quota and Box resources.": "Issue, QA e correzioni cloud in coda potranno partire, consumando quota del provider e risorse Box.",
|
|
5250
|
+
"This blocks new cloud assignments and new AI launches, not sessions already running, manual sign-in or Box storage charges. Stop or remove resources explicitly when you are finished.": "Blocca nuove assegnazioni cloud e nuovi avvii AI, non sessioni gi\xE0 attive, login manuali o costi di archiviazione Box. Al termine arresta o elimina esplicitamente le risorse.",
|
|
5251
|
+
"Reference CPU rates are not an invoice or a spending cap. Actual Box CPU time, storage and AI charges are not reported here; check provider dashboards. Unknown usage is not zero.": "Le tariffe CPU indicative non sono una fattura n\xE9 un tetto di spesa. Tempo CPU, archiviazione Box e costi AI effettivi non sono riportati qui: consulta le dashboard dei provider. Un consumo ignoto non equivale a zero.",
|
|
5252
|
+
"A ready Box describes its machine, not provider authentication or quota. Finish Sign in in this agent\u2019s terminal and check its model before assigning work.": "Una Box pronta descrive la macchina, non l\u2019autenticazione o la quota del provider. Completa Accedi nel terminale dell\u2019agente e verifica il modello prima di assegnare lavoro.",
|
|
5253
|
+
"{deleted} removals confirmed; {unconfirmed} not confirmed. Check the Upstash console; resources may still be billed.": "{deleted} eliminazioni confermate; {unconfirmed} non confermate. Controlla la console Upstash: le risorse potrebbero essere ancora fatturate.",
|
|
5254
|
+
"\u2713 {count} Box removals confirmed": "\u2713 {count} eliminazioni Box confermate",
|
|
5255
|
+
"Paused Boxes can still incur storage charges. Check current plan limits and prices in Upstash; the office\u2019s Box limit is not a billing cap. Setup and what keeps going while the office is closed:": "Le Box in pausa possono ancora generare costi di archiviazione. Verifica limiti e prezzi attuali su Upstash: il limite Box dell\u2019ufficio non \xE8 un tetto di spesa. Configurazione e attivit\xE0 a ufficio chiuso:",
|
|
4829
5256
|
"{total} Boxes on your account \xB7 this office: {running} running, {paused} paused": "{total} Box nel tuo account \xB7 questo ufficio: {running} attivi, {paused} in pausa",
|
|
4830
5257
|
"Boxes not counted yet.": "Box non ancora conteggiati.",
|
|
4831
5258
|
"Delete {count} orphaned Boxes?": "Eliminare {count} Box senza agente?",
|
|
@@ -5187,6 +5614,11 @@ var italianUi = {
|
|
|
5187
5614
|
"Study the repo again and rethink the plan and the team\u2019s size": "Studia di nuovo il repository e rivedi il piano e le dimensioni del team",
|
|
5188
5615
|
"Brief: what should this floor build next? The CEO turns it into issues and a team size.": "Obiettivo: che cosa deve sviluppare questo piano? Il CEO lo traduce in issue e dimensioni del team.",
|
|
5189
5616
|
" (none yet)": " (non ancora disponibile)",
|
|
5617
|
+
"QA brief \u2014 not filled in yet": "Indicazioni QA \u2014 non ancora compilate",
|
|
5618
|
+
"Your Claude subscription (DROIDSEMBLY_CLAUDE_TOKEN)": "Il tuo abbonamento Claude (DROIDSEMBLY_CLAUDE_TOKEN)",
|
|
5619
|
+
"CUBEFARM_CLAUDE_TOKEN is still supported. DROIDSEMBLY_CLAUDE_TOKEN takes precedence when both are set.": "CUBEFARM_CLAUDE_TOKEN \xE8 ancora supportata. DROIDSEMBLY_CLAUDE_TOKEN ha la precedenza quando sono impostate entrambe.",
|
|
5620
|
+
"OpenCode is the coding agent validated in manual testing for this version. Claude Code and Codex are available but have not yet been tested to the same extent.": "OpenCode \xE8 lo strumento collaudato nei test manuali di questa versione. Claude Code e Codex sono disponibili, ma non ancora verificati allo stesso livello.",
|
|
5621
|
+
"Follow the instructions in their terminal for the selected provider and sign-in method. If a link is shown, open it and use the account for that provider; enter or paste a code only where instructed.": "Segui le istruzioni nel terminale per il provider e il metodo di accesso selezionati. Se compare un link, aprilo e usa l\u2019account di quel provider; inserisci o incolla un codice solo dove indicato.",
|
|
5190
5622
|
"What every QA pass must check on this project.": "Che cosa deve verificare ogni controllo QA di questo progetto.",
|
|
5191
5623
|
"Model: provider/model, or provider/model#variant for reasoning. Empty uses the OpenCode default.": "Modello: provider/model, oppure provider/model#variant per il ragionamento. Lascia vuoto per il valore predefinito di OpenCode.",
|
|
5192
5624
|
"Up next:": "In coda:",
|
|
@@ -6608,7 +7040,7 @@ var Voice = class {
|
|
|
6608
7040
|
const s2 = await this.readSecrets();
|
|
6609
7041
|
this.key = typeof s2.elevenlabsKey === "string" ? s2.elevenlabsKey : "";
|
|
6610
7042
|
this.rejected = !!this.key && s2.elevenlabsKeyRejected === true;
|
|
6611
|
-
const raw = await
|
|
7043
|
+
const raw = await fs14.readFile(this.manifestFile(), "utf8").catch(() => "");
|
|
6612
7044
|
try {
|
|
6613
7045
|
this.clips = parseManifest(raw ? JSON.parse(raw) : {});
|
|
6614
7046
|
} catch {
|
|
@@ -6673,7 +7105,7 @@ var Voice = class {
|
|
|
6673
7105
|
const m = this.message(id);
|
|
6674
7106
|
if (!m || !speaks(m, s2)) throw new HttpError(404, `No spoken message ${id}`);
|
|
6675
7107
|
const saved = clipsFor(this.clips, m);
|
|
6676
|
-
const first = saved && await
|
|
7108
|
+
const first = saved && await fs14.readFile(path14.join(this.deps.cacheDir, saved[0])).catch(() => null);
|
|
6677
7109
|
if (first) return first;
|
|
6678
7110
|
const text3 = speechText(m.text);
|
|
6679
7111
|
if (!text3) throw new HttpError(404, `Message ${id} has nothing to say aloud`);
|
|
@@ -6687,15 +7119,15 @@ var Voice = class {
|
|
|
6687
7119
|
const m = this.message(id);
|
|
6688
7120
|
const files = m && clipsFor(this.clips, m);
|
|
6689
7121
|
const file = files?.[part];
|
|
6690
|
-
const audio = file && await
|
|
7122
|
+
const audio = file && await fs14.readFile(path14.join(this.deps.cacheDir, file)).catch(() => null);
|
|
6691
7123
|
if (!files || !audio) throw new HttpError(404, `Audio for message ${id} is no longer saved.`);
|
|
6692
7124
|
return { audio, parts: files.length };
|
|
6693
7125
|
}
|
|
6694
7126
|
/** DELETE /api/voice/cache: Settings → Voice's "Clear saved clips". */
|
|
6695
7127
|
clearCache() {
|
|
6696
7128
|
return this.cacheOp(async () => {
|
|
6697
|
-
const names = await
|
|
6698
|
-
for (const name of names.filter((n) => n.endsWith(".mp3"))) await
|
|
7129
|
+
const names = await fs14.readdir(this.deps.cacheDir).catch(() => []);
|
|
7130
|
+
for (const name of names.filter((n) => n.endsWith(".mp3"))) await fs14.rm(path14.join(this.deps.cacheDir, name), { force: true, maxRetries: 3 });
|
|
6699
7131
|
this.clips = {};
|
|
6700
7132
|
await this.saveManifest();
|
|
6701
7133
|
return this.measure([]);
|
|
@@ -6708,12 +7140,12 @@ var Voice = class {
|
|
|
6708
7140
|
prune() {
|
|
6709
7141
|
return this.cacheOp(async () => {
|
|
6710
7142
|
const dir = this.deps.cacheDir;
|
|
6711
|
-
const names = (await
|
|
6712
|
-
const stats = await Promise.all(names.map(async (name) => ({ name, st: await
|
|
7143
|
+
const names = (await fs14.readdir(dir).catch(() => [])).filter((n) => n.endsWith(".mp3"));
|
|
7144
|
+
const stats = await Promise.all(names.map(async (name) => ({ name, st: await fs14.stat(path14.join(dir, name)).catch(() => null) })));
|
|
6713
7145
|
const files = stats.flatMap(({ name, st }) => st ? [{ name, mtimeMs: st.mtimeMs, size: st.size }] : []);
|
|
6714
7146
|
const keep = newestClips(this.clips, this.deps.messages());
|
|
6715
7147
|
const gone = new Set(cacheToPrune(files, this.now(), CACHE_MAX_FILES, this.deps.settings().keepDays * DAY_MS, keep));
|
|
6716
|
-
for (const name of [...gone]) await
|
|
7148
|
+
for (const name of [...gone]) await fs14.rm(path14.join(dir, name), { force: true, maxRetries: 3 }).catch(() => gone.delete(name));
|
|
6717
7149
|
const left = files.filter((f) => !gone.has(f.name));
|
|
6718
7150
|
const clips = withoutMissing(this.clips, new Set(left.map((f) => f.name)));
|
|
6719
7151
|
if (Object.keys(clips).length !== Object.keys(this.clips).length) {
|
|
@@ -6759,10 +7191,10 @@ var Voice = class {
|
|
|
6759
7191
|
const hash = crypto5.createHash("sha256").update(`${voiceId}
|
|
6760
7192
|
${model2}
|
|
6761
7193
|
${text3}${language === "it" ? "\nit" : ""}`).digest("hex").slice(0, 12);
|
|
6762
|
-
const file =
|
|
6763
|
-
const cached = await
|
|
7194
|
+
const file = path14.join(this.deps.cacheDir, `${name}-${hash}.mp3`);
|
|
7195
|
+
const cached = await fs14.readFile(file).catch(() => null);
|
|
6764
7196
|
if (cached) {
|
|
6765
|
-
if (m) await this.record(m, [
|
|
7197
|
+
if (m) await this.record(m, [path14.basename(file)]);
|
|
6766
7198
|
return cached;
|
|
6767
7199
|
}
|
|
6768
7200
|
this.requireKey();
|
|
@@ -6781,12 +7213,12 @@ ${text3}${language === "it" ? "\nit" : ""}`).digest("hex").slice(0, 12);
|
|
|
6781
7213
|
this.requireKey();
|
|
6782
7214
|
const key = this.key;
|
|
6783
7215
|
const audio = await this.deps.api.synthesize(key, req, AbortSignal.timeout(SYNTH_TIMEOUT_MS)).catch((err) => this.failed(err, key, "speak the message"));
|
|
6784
|
-
await
|
|
7216
|
+
await fs14.mkdir(this.deps.cacheDir, { recursive: true });
|
|
6785
7217
|
const tmp = `${file}.${process.pid}.tmp`;
|
|
6786
|
-
await
|
|
6787
|
-
await
|
|
6788
|
-
this.deps.log?.(`voice: made a new clip ${
|
|
6789
|
-
if (m) await this.record(m, [
|
|
7218
|
+
await fs14.writeFile(tmp, audio);
|
|
7219
|
+
await fs14.rename(tmp, file);
|
|
7220
|
+
this.deps.log?.(`voice: made a new clip ${path14.basename(file)} (${req.text.length} characters)`);
|
|
7221
|
+
if (m) await this.record(m, [path14.basename(file)]);
|
|
6790
7222
|
else await this.prune();
|
|
6791
7223
|
return audio;
|
|
6792
7224
|
}
|
|
@@ -6822,13 +7254,13 @@ ${text3}${language === "it" ? "\nit" : ""}`).digest("hex").slice(0, 12);
|
|
|
6822
7254
|
await this.prune();
|
|
6823
7255
|
}
|
|
6824
7256
|
manifestFile() {
|
|
6825
|
-
return
|
|
7257
|
+
return path14.join(this.deps.cacheDir, MANIFEST);
|
|
6826
7258
|
}
|
|
6827
7259
|
async saveManifest() {
|
|
6828
|
-
await
|
|
7260
|
+
await fs14.mkdir(this.deps.cacheDir, { recursive: true });
|
|
6829
7261
|
const tmp = `${this.manifestFile()}.${process.pid}.tmp`;
|
|
6830
|
-
await
|
|
6831
|
-
await
|
|
7262
|
+
await fs14.writeFile(tmp, JSON.stringify(this.clips));
|
|
7263
|
+
await fs14.rename(tmp, this.manifestFile());
|
|
6832
7264
|
}
|
|
6833
7265
|
/** The cache view for `files` (what's on disk), told to the clients when it changed. */
|
|
6834
7266
|
measure(files) {
|
|
@@ -6932,8 +7364,11 @@ var elevenLabs = {
|
|
|
6932
7364
|
};
|
|
6933
7365
|
|
|
6934
7366
|
// server/notifier.ts
|
|
6935
|
-
import
|
|
6936
|
-
import
|
|
7367
|
+
import fs15 from "node:fs/promises";
|
|
7368
|
+
import path15 from "node:path";
|
|
7369
|
+
|
|
7370
|
+
// shared/browserProtocol.ts
|
|
7371
|
+
var notificationTag = (id) => `cubefarm-${id}`;
|
|
6937
7372
|
|
|
6938
7373
|
// shared/notify.ts
|
|
6939
7374
|
var NOTIFY_EVENTS = [
|
|
@@ -7225,7 +7660,7 @@ var Notifier = class {
|
|
|
7225
7660
|
}
|
|
7226
7661
|
}
|
|
7227
7662
|
try {
|
|
7228
|
-
const raw = JSON.parse(await
|
|
7663
|
+
const raw = JSON.parse(await fs15.readFile(this.deps.pushFile, "utf8"));
|
|
7229
7664
|
const devices = Array.isArray(raw.devices) ? raw.devices : [];
|
|
7230
7665
|
this.push = {
|
|
7231
7666
|
vapid: checkVapidKeys(raw.vapid),
|
|
@@ -7332,7 +7767,7 @@ var Notifier = class {
|
|
|
7332
7767
|
const sends = [];
|
|
7333
7768
|
for (const c of NOTIFY_WEBHOOKS) if (on(c) && this.webhooks[c]) sends.push(this.send(this.webhookRequest(c, n, s2.officeUrl)));
|
|
7334
7769
|
if (on("push") && this.push.vapid) {
|
|
7335
|
-
const payload = JSON.stringify({ title: view.title, body: view.body, tag:
|
|
7770
|
+
const payload = JSON.stringify({ title: view.title, body: view.body, tag: notificationTag(view.id), url: view.url });
|
|
7336
7771
|
for (const d of [...this.push.devices]) sends.push(this.sendPush(d, payload, noteText(n)));
|
|
7337
7772
|
}
|
|
7338
7773
|
return Promise.all(sends);
|
|
@@ -7370,10 +7805,10 @@ var Notifier = class {
|
|
|
7370
7805
|
const file = this.deps.pushFile;
|
|
7371
7806
|
const data = JSON.stringify({ vapid: this.push.vapid, devices: this.push.devices }, null, 2);
|
|
7372
7807
|
const write = this.pushWrites.then(async () => {
|
|
7373
|
-
await
|
|
7374
|
-
await
|
|
7375
|
-
await
|
|
7376
|
-
await
|
|
7808
|
+
await fs15.mkdir(path15.dirname(file), { recursive: true });
|
|
7809
|
+
await fs15.writeFile(`${file}.tmp`, data, { mode: 384 });
|
|
7810
|
+
await fs15.rename(`${file}.tmp`, file);
|
|
7811
|
+
await fs15.chmod(file, 384).catch(() => void 0);
|
|
7377
7812
|
});
|
|
7378
7813
|
this.pushWrites = write.catch(() => void 0);
|
|
7379
7814
|
return write;
|
|
@@ -7398,8 +7833,8 @@ function loadWebhooks(raw) {
|
|
|
7398
7833
|
}
|
|
7399
7834
|
|
|
7400
7835
|
// server/weather.ts
|
|
7401
|
-
import
|
|
7402
|
-
import
|
|
7836
|
+
import fs16 from "node:fs/promises";
|
|
7837
|
+
import path16 from "node:path";
|
|
7403
7838
|
|
|
7404
7839
|
// shared/outside.ts
|
|
7405
7840
|
var WEATHER_KINDS = ["clear", "cloudy", "light-rain", "heavy-rain", "storm", "fog", "snow"];
|
|
@@ -7545,7 +7980,7 @@ var WeatherService = class {
|
|
|
7545
7980
|
now = () => this.o.now?.() ?? Date.now();
|
|
7546
7981
|
async init() {
|
|
7547
7982
|
try {
|
|
7548
|
-
const cached = parseCache(JSON.parse(await
|
|
7983
|
+
const cached = parseCache(JSON.parse(await fs16.readFile(this.o.file, "utf8")));
|
|
7549
7984
|
this.city = cached.city;
|
|
7550
7985
|
this.view = { place: cached.place, reading: cached.reading, error: null };
|
|
7551
7986
|
} catch {
|
|
@@ -7624,9 +8059,9 @@ var WeatherService = class {
|
|
|
7624
8059
|
async save() {
|
|
7625
8060
|
const tmp = `${this.o.file}.tmp`;
|
|
7626
8061
|
try {
|
|
7627
|
-
await
|
|
7628
|
-
await
|
|
7629
|
-
await
|
|
8062
|
+
await fs16.mkdir(path16.dirname(this.o.file), { recursive: true });
|
|
8063
|
+
await fs16.writeFile(tmp, JSON.stringify({ city: this.city, place: this.view.place, reading: this.view.reading }, null, 2));
|
|
8064
|
+
await fs16.rename(tmp, this.o.file);
|
|
7630
8065
|
} catch (err) {
|
|
7631
8066
|
this.o.log(`weather: couldn't save the cache: ${err.message}`);
|
|
7632
8067
|
}
|
|
@@ -7692,6 +8127,8 @@ var realBackend = {
|
|
|
7692
8127
|
releaseClis,
|
|
7693
8128
|
detectClis,
|
|
7694
8129
|
openCodeModels,
|
|
8130
|
+
openCodeConnections,
|
|
8131
|
+
openCodeAuth: startOpenCodeAuth,
|
|
7695
8132
|
previews: realPreviews,
|
|
7696
8133
|
office: realOffice,
|
|
7697
8134
|
voice: elevenLabs,
|
|
@@ -7702,9 +8139,9 @@ var realBackend = {
|
|
|
7702
8139
|
|
|
7703
8140
|
// server/demo.ts
|
|
7704
8141
|
import crypto7 from "node:crypto";
|
|
7705
|
-
import
|
|
8142
|
+
import fs17 from "node:fs";
|
|
7706
8143
|
import http from "node:http";
|
|
7707
|
-
import
|
|
8144
|
+
import path17 from "node:path";
|
|
7708
8145
|
|
|
7709
8146
|
// shared/ops.ts
|
|
7710
8147
|
var needsManager = (q) => q?.status === "needs-human" && !q.ceoLooking;
|
|
@@ -7896,10 +8333,10 @@ var closedIssues = /* @__PURE__ */ new Set();
|
|
|
7896
8333
|
var stalls = /* @__PURE__ */ new Map();
|
|
7897
8334
|
var signOuts = /* @__PURE__ */ new Map();
|
|
7898
8335
|
var fakeSha = () => crypto7.randomBytes(20).toString("hex");
|
|
7899
|
-
var NUMBERS_FILE =
|
|
8336
|
+
var NUMBERS_FILE = path17.join(HOME_DIR, "demo-github.json");
|
|
7900
8337
|
function restoreNumbers() {
|
|
7901
8338
|
try {
|
|
7902
|
-
const saved = JSON.parse(
|
|
8339
|
+
const saved = JSON.parse(fs17.readFileSync(NUMBERS_FILE, "utf8"));
|
|
7903
8340
|
for (const r of repos.values()) if (Number.isInteger(saved[r.fullName])) r.nextNumber = Math.max(r.nextNumber, saved[r.fullName]);
|
|
7904
8341
|
} catch {
|
|
7905
8342
|
}
|
|
@@ -7907,9 +8344,9 @@ function restoreNumbers() {
|
|
|
7907
8344
|
function takeNumber(r) {
|
|
7908
8345
|
const n = r.nextNumber++;
|
|
7909
8346
|
try {
|
|
7910
|
-
|
|
7911
|
-
|
|
7912
|
-
|
|
8347
|
+
fs17.mkdirSync(HOME_DIR, { recursive: true });
|
|
8348
|
+
fs17.writeFileSync(`${NUMBERS_FILE}.tmp`, JSON.stringify(Object.fromEntries([...repos.values()].map((x) => [x.fullName, x.nextNumber]))));
|
|
8349
|
+
fs17.renameSync(`${NUMBERS_FILE}.tmp`, NUMBERS_FILE);
|
|
7913
8350
|
} catch (err) {
|
|
7914
8351
|
console.warn("could not save the demo PR numbers", err);
|
|
7915
8352
|
}
|
|
@@ -8032,7 +8469,7 @@ function screenshotSvg(title, url, hue) {
|
|
|
8032
8469
|
</svg>`;
|
|
8033
8470
|
}
|
|
8034
8471
|
function issueScript(opts, cb, issueNumber, issueTitle) {
|
|
8035
|
-
const branch =
|
|
8472
|
+
const branch = path17.basename(opts.cwd);
|
|
8036
8473
|
const hue = issueNumber * 67 % 360;
|
|
8037
8474
|
const file = ["src/App.tsx", "src/components/TodoList.tsx", "src/api/routes.ts", "src/styles.css"][issueNumber % 4];
|
|
8038
8475
|
const port = 5200 + issueNumber % 50;
|
|
@@ -8232,7 +8669,7 @@ function fakeSession(opts, cb, fullName) {
|
|
|
8232
8669
|
number: n,
|
|
8233
8670
|
title,
|
|
8234
8671
|
url,
|
|
8235
|
-
headRefName: `swarm/issue-${number}-${
|
|
8672
|
+
headRefName: `swarm/issue-${number}-${path17.basename(opts.cwd).replace(/-[0-9a-f]{4}$/, "")}`,
|
|
8236
8673
|
state: "OPEN",
|
|
8237
8674
|
isDraft: false,
|
|
8238
8675
|
mergeable: "MERGEABLE",
|
|
@@ -8697,7 +9134,7 @@ var OFFICE_REPO = "demo-co/pixel-todo";
|
|
|
8697
9134
|
var DEMO_HEAD = `0ff1ce5${"0".repeat(33)}`;
|
|
8698
9135
|
var lastFakeUpdate = { to: "", commits: 0 };
|
|
8699
9136
|
var demoOffice = {
|
|
8700
|
-
launcher: underLauncher() || process.env
|
|
9137
|
+
launcher: underLauncher() || officeEnv(process.env, "SWARM_DEMO_LAUNCHER") === "1",
|
|
8701
9138
|
head: async () => DEMO_HEAD,
|
|
8702
9139
|
isOwnFolder: (dir) => dir === `/demo/${OFFICE_REPO}/main`,
|
|
8703
9140
|
// Only its own fake updates have a count; one the real launcher did (u) gets no count rather than a wrong one.
|
|
@@ -9200,8 +9637,9 @@ function demoBoxes(logins) {
|
|
|
9200
9637
|
},
|
|
9201
9638
|
run: async (id, script) => {
|
|
9202
9639
|
box(id).status = "running";
|
|
9203
|
-
const cli = /claude'? auth /.test(script) ? "claude" : "codex";
|
|
9204
|
-
if (script.includes("CUBEFARM_SIGNED_IN")) return { code: 0, output: logins.get(id)?.has(cli) ? "CUBEFARM_SIGNED_IN" : "CUBEFARM_SIGNED_OUT" };
|
|
9640
|
+
const cli = script.includes("opencode-query.cjs") ? "opencode" : /claude'? auth /.test(script) ? "claude" : "codex";
|
|
9641
|
+
if (script.includes("CUBEFARM_SIGNED_IN") || cli === "opencode" && script.includes("'status'")) return { code: 0, output: logins.get(id)?.has(cli) ? "CUBEFARM_SIGNED_IN" : "CUBEFARM_SIGNED_OUT" };
|
|
9642
|
+
if (cli === "opencode" && script.includes("'models'")) return { code: 0, output: JSON.stringify({ list: { data: [{ providerID: "demo", id: "cloud-model", name: "Demo cloud model", capabilities: { tools: true } }] }, selected: { data: null } }) };
|
|
9205
9643
|
if (/auth logout|' logout/.test(script)) {
|
|
9206
9644
|
logins.get(id)?.delete(cli);
|
|
9207
9645
|
return { code: 0, output: "" };
|
|
@@ -9251,13 +9689,13 @@ function demoCloud() {
|
|
|
9251
9689
|
}
|
|
9252
9690
|
};
|
|
9253
9691
|
}
|
|
9254
|
-
var DEMO_SIGN_IN = { claude: "https://example.com/cubefarm-demo/claude-sign-in", codex: "https://example.com/cubefarm-demo/codex-device" };
|
|
9692
|
+
var DEMO_SIGN_IN = { claude: "https://example.com/cubefarm-demo/claude-sign-in", codex: "https://example.com/cubefarm-demo/codex-device", opencode: "https://example.com/droidsembly-demo/opencode" };
|
|
9255
9693
|
function demoSignIn(o, logins, exited) {
|
|
9256
9694
|
const { term } = o;
|
|
9257
9695
|
const claude = o.cli === "claude";
|
|
9258
|
-
term.note(`\u2500\u2500 Signing ${
|
|
9696
|
+
term.note(`\u2500\u2500 Signing ${cliLabel(o.cli)} in \xB7 \u2601 cloud machine (demo) \u2500\u2500`);
|
|
9259
9697
|
term.write(
|
|
9260
|
-
(claude ? ["Opening browser to sign in\u2026", `If the browser didn't open, visit: ${DEMO_SIGN_IN.claude}`, "", "\x1B[2m(demo) Paste anything and press Enter.\x1B[0m", "Paste code here if prompted > "] : [
|
|
9698
|
+
(o.cli === "opencode" ? ["OpenCode provider login (demo)", DEMO_SIGN_IN.opencode, "(demo) Press Enter to finish."] : claude ? ["Opening browser to sign in\u2026", `If the browser didn't open, visit: ${DEMO_SIGN_IN.claude}`, "", "\x1B[2m(demo) Paste anything and press Enter.\x1B[0m", "Paste code here if prompted > "] : [
|
|
9261
9699
|
"Welcome to Codex (demo)",
|
|
9262
9700
|
"",
|
|
9263
9701
|
"Follow these steps to sign in with ChatGPT using device code authorization:",
|
|
@@ -9307,8 +9745,8 @@ function demoSignIn(o, logins, exited) {
|
|
|
9307
9745
|
}
|
|
9308
9746
|
|
|
9309
9747
|
// server/journal.ts
|
|
9310
|
-
import
|
|
9311
|
-
import
|
|
9748
|
+
import fs18 from "node:fs/promises";
|
|
9749
|
+
import path18 from "node:path";
|
|
9312
9750
|
|
|
9313
9751
|
// shared/journal.ts
|
|
9314
9752
|
var KEYFRAME_MS = 10 * 6e4;
|
|
@@ -9805,12 +10243,12 @@ function parseRange(q, now2) {
|
|
|
9805
10243
|
return { from, to, seek: q.seek === "1" || q.seek === "true" };
|
|
9806
10244
|
}
|
|
9807
10245
|
async function writeAtomic(file, data) {
|
|
9808
|
-
await
|
|
10246
|
+
await fs18.mkdir(path18.dirname(file), { recursive: true });
|
|
9809
10247
|
const tmp = `${file}.tmp`;
|
|
9810
|
-
await
|
|
10248
|
+
await fs18.writeFile(tmp, data);
|
|
9811
10249
|
for (let i = 0; ; i++) {
|
|
9812
10250
|
try {
|
|
9813
|
-
await
|
|
10251
|
+
await fs18.rename(tmp, file);
|
|
9814
10252
|
return;
|
|
9815
10253
|
} catch (err) {
|
|
9816
10254
|
const code = err.code;
|
|
@@ -9912,7 +10350,7 @@ var Journal = class {
|
|
|
9912
10350
|
const start = prev && at <= prev.start ? prev.start + 1 : at;
|
|
9913
10351
|
const day = dayKey(start);
|
|
9914
10352
|
const frame = this.opts.frame();
|
|
9915
|
-
const seg = { day, start, file:
|
|
10353
|
+
const seg = { day, start, file: path18.join(this.opts.dir, day, `${start}.ndjson`), lines: [], bytes: 0, events: 0, dirty: false };
|
|
9916
10354
|
this.push(seg, boot ? { t: start, k: frame, boot: true } : { t: start, k: frame });
|
|
9917
10355
|
this.last = frameKeys(frame);
|
|
9918
10356
|
this.cur = seg;
|
|
@@ -9931,24 +10369,24 @@ var Journal = class {
|
|
|
9931
10369
|
const tmp = [];
|
|
9932
10370
|
let days = [];
|
|
9933
10371
|
try {
|
|
9934
|
-
days = (await
|
|
10372
|
+
days = (await fs18.readdir(this.opts.dir)).filter((d) => DAY_DIR.test(d));
|
|
9935
10373
|
} catch {
|
|
9936
10374
|
return { segments, tmp, days };
|
|
9937
10375
|
}
|
|
9938
10376
|
for (const day of days) {
|
|
9939
|
-
const dir =
|
|
10377
|
+
const dir = path18.join(this.opts.dir, day);
|
|
9940
10378
|
let names = [];
|
|
9941
10379
|
try {
|
|
9942
|
-
names = await
|
|
10380
|
+
names = await fs18.readdir(dir);
|
|
9943
10381
|
} catch {
|
|
9944
10382
|
continue;
|
|
9945
10383
|
}
|
|
9946
10384
|
for (const name of names) {
|
|
9947
|
-
const file =
|
|
10385
|
+
const file = path18.join(dir, name);
|
|
9948
10386
|
if (withTmp && name.endsWith(".tmp")) tmp.push(file);
|
|
9949
10387
|
const m = SEGMENT_FILE.exec(name);
|
|
9950
10388
|
if (!m || file === this.cur?.file) continue;
|
|
9951
|
-
const st = await
|
|
10389
|
+
const st = await fs18.stat(file).catch(() => null);
|
|
9952
10390
|
if (st?.isFile()) segments.push({ day, start: Number(m[1]), bytes: st.size, file });
|
|
9953
10391
|
}
|
|
9954
10392
|
}
|
|
@@ -9960,17 +10398,17 @@ var Journal = class {
|
|
|
9960
10398
|
const { segments, tmp, days } = await this.files(boot);
|
|
9961
10399
|
const current = this.cur ? [{ day: this.cur.day, start: this.cur.start, bytes: this.cur.bytes, file: this.cur.file }] : [];
|
|
9962
10400
|
const gone = toPrune([...segments, ...current], this.now(), { keepDays: this.opts.keepDays ?? KEEP_DAYS, maxBytes: this.opts.maxBytes ?? MAX_BYTES, keep: this.cur?.start });
|
|
9963
|
-
for (const f of [...gone.map((g) => g.file), ...tmp]) await
|
|
10401
|
+
for (const f of [...gone.map((g) => g.file), ...tmp]) await fs18.rm(f, { force: true, maxRetries: 3 }).catch(() => void 0);
|
|
9964
10402
|
for (const g of gone) for (const k of this.summaries.keys()) if (k.startsWith(`${g.file}|`)) this.summaries.delete(k);
|
|
9965
10403
|
for (const day of days) {
|
|
9966
|
-
const dir =
|
|
9967
|
-
const left = await
|
|
9968
|
-
if (left && left.length === 0) await
|
|
10404
|
+
const dir = path18.join(this.opts.dir, day);
|
|
10405
|
+
const left = await fs18.readdir(dir).catch(() => null);
|
|
10406
|
+
if (left && left.length === 0) await fs18.rm(dir, { recursive: true, force: true, maxRetries: 3 }).catch(() => void 0);
|
|
9969
10407
|
}
|
|
9970
10408
|
return gone.length;
|
|
9971
10409
|
}
|
|
9972
10410
|
readRaw(f) {
|
|
9973
|
-
return
|
|
10411
|
+
return fs18.readFile(f.file, "utf8").catch(() => "");
|
|
9974
10412
|
}
|
|
9975
10413
|
currentRaw() {
|
|
9976
10414
|
return this.cur ? this.cur.lines.join("\n") : "";
|
|
@@ -10023,12 +10461,12 @@ var Journal = class {
|
|
|
10023
10461
|
if (!lines.length || !isFrame(lines[0])) throw new Error("a day starts with a keyframe");
|
|
10024
10462
|
const day = dayKey(lines[0].t);
|
|
10025
10463
|
if (day === this.cur?.day) throw new HttpError(409, "Today is being recorded: a sample day must be another day");
|
|
10026
|
-
const dir =
|
|
10027
|
-
await
|
|
10028
|
-
for (const k of this.summaries.keys()) if (k.startsWith(`${dir}${
|
|
10464
|
+
const dir = path18.join(this.opts.dir, day);
|
|
10465
|
+
await fs18.rm(dir, { recursive: true, force: true, maxRetries: 3 });
|
|
10466
|
+
for (const k of this.summaries.keys()) if (k.startsWith(`${dir}${path18.sep}`)) this.summaries.delete(k);
|
|
10029
10467
|
let chunk = [];
|
|
10030
10468
|
const write = async () => {
|
|
10031
|
-
if (chunk.length) await writeAtomic(
|
|
10469
|
+
if (chunk.length) await writeAtomic(path18.join(dir, `${chunk[0].t}.ndjson`), `${chunk.map((l) => JSON.stringify(l)).join("\n")}
|
|
10032
10470
|
`);
|
|
10033
10471
|
};
|
|
10034
10472
|
for (const l of lines) {
|
|
@@ -10057,9 +10495,9 @@ ${commit ?? ""}
|
|
|
10057
10495
|
${indexHtml}`).digest("hex").slice(0, 12);
|
|
10058
10496
|
}
|
|
10059
10497
|
function serviceWorkerSource(version) {
|
|
10060
|
-
return `//
|
|
10498
|
+
return `// Droidsembly's service worker (server/pwa.ts). Version ${version}.
|
|
10061
10499
|
const VERSION = ${JSON.stringify(version)};
|
|
10062
|
-
const CACHE = '
|
|
10500
|
+
const CACHE = 'droidsembly-shell-' + VERSION;
|
|
10063
10501
|
const PRECACHE = ['/', '/manifest.webmanifest', ...['icon-192.png', 'icon-512.png', 'icon-maskable-512.png', 'apple-touch-icon.png', 'icon.svg', 'favicon.svg', 'favicon-32.png', 'badge-96.png', 'sora-400.ttf', 'sora-700.ttf', 'droid-wire.svg', 'droid-shell.svg', 'droid-eyes.svg', 'droid-antenna.svg', 'droid-spark.svg'].map(name => '/icons/' + name)];
|
|
10064
10502
|
|
|
10065
10503
|
self.addEventListener('install', (event) => {
|
|
@@ -10069,7 +10507,7 @@ self.addEventListener('install', (event) => {
|
|
|
10069
10507
|
self.addEventListener('activate', (event) => {
|
|
10070
10508
|
event.waitUntil(
|
|
10071
10509
|
caches.keys()
|
|
10072
|
-
.then((keys) => Promise.all(keys.filter((k) => k.startsWith('cubefarm-shell-') && k !== CACHE).map((k) => caches.delete(k))))
|
|
10510
|
+
.then((keys) => Promise.all(keys.filter((k) => (k.startsWith('droidsembly-shell-') || k.startsWith('cubefarm-shell-')) && k !== CACHE).map((k) => caches.delete(k))))
|
|
10073
10511
|
.then(() => self.clients.claim()),
|
|
10074
10512
|
);
|
|
10075
10513
|
});
|
|
@@ -10097,7 +10535,7 @@ self.addEventListener('fetch', (event) => {
|
|
|
10097
10535
|
if (!isShell(url)) return;
|
|
10098
10536
|
// Bundles are content-hashed, so a cached one never goes stale.
|
|
10099
10537
|
event.respondWith(
|
|
10100
|
-
caches.match(req).then(
|
|
10538
|
+
caches.has(CACHE).then((exists) => exists ? caches.open(CACHE).then((cache) => cache.match(req)) : undefined).then(
|
|
10101
10539
|
(hit) =>
|
|
10102
10540
|
hit ||
|
|
10103
10541
|
fetch(req).then((res) => {
|
|
@@ -10123,7 +10561,9 @@ self.addEventListener('notificationclick', (event) => {
|
|
|
10123
10561
|
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((list) => {
|
|
10124
10562
|
const open = list.find((c) => new URL(c.url).origin === self.location.origin);
|
|
10125
10563
|
if (!open) return self.clients.openWindow(url);
|
|
10126
|
-
|
|
10564
|
+
// Keep the legacy type for already-open old pages, with canonical metadata.
|
|
10565
|
+
// One message only: new pages normalize it to droidsembly:open.
|
|
10566
|
+
open.postMessage({ type: 'cubefarm:open', canonicalType: 'droidsembly:open', url });
|
|
10127
10567
|
return open.focus();
|
|
10128
10568
|
}),
|
|
10129
10569
|
);
|
|
@@ -10281,18 +10721,18 @@ function passHeaders(headers) {
|
|
|
10281
10721
|
for (const [k, v] of Object.entries(headers)) if (v !== void 0 && !HOP.test(k)) out[k] = v;
|
|
10282
10722
|
return out;
|
|
10283
10723
|
}
|
|
10284
|
-
function upstream(target, req, body2, onResponse, onError,
|
|
10724
|
+
function upstream(target, req, body2, onResponse, onError, path24 = req.url) {
|
|
10285
10725
|
const headers = { ...req.headers, host: `localhost:${target}`, "accept-encoding": "identity" };
|
|
10286
10726
|
for (const k of Object.keys(headers)) if (HOP.test(k)) delete headers[k];
|
|
10287
10727
|
const send2 = (host, retry) => {
|
|
10288
|
-
const up = http2.request({ host, port: target, method: req.method, path:
|
|
10728
|
+
const up = http2.request({ host, port: target, method: req.method, path: path24, headers }, onResponse);
|
|
10289
10729
|
up.once("error", (err) => retry && err.code === "ECONNREFUSED" ? send2("::1", false) : onError(err));
|
|
10290
10730
|
up.end(body2);
|
|
10291
10731
|
};
|
|
10292
10732
|
send2("127.0.0.1", true);
|
|
10293
10733
|
}
|
|
10294
|
-
function tunnel(target, req, socket, head,
|
|
10295
|
-
const lines = [`${req.method} ${
|
|
10734
|
+
function tunnel(target, req, socket, head, path24 = req.url) {
|
|
10735
|
+
const lines = [`${req.method} ${path24} HTTP/${req.httpVersion}`];
|
|
10296
10736
|
for (let i = 0; i < req.rawHeaders.length; i += 2) {
|
|
10297
10737
|
const name = req.rawHeaders[i];
|
|
10298
10738
|
lines.push(`${name}: ${/^host$/i.test(name) ? `localhost:${target}` : req.rawHeaders[i + 1]}`);
|
|
@@ -11024,10 +11464,14 @@ var PresenceHub = class {
|
|
|
11024
11464
|
};
|
|
11025
11465
|
|
|
11026
11466
|
// server/swarm.ts
|
|
11027
|
-
import
|
|
11028
|
-
import
|
|
11467
|
+
import fs22 from "node:fs/promises";
|
|
11468
|
+
import path22 from "node:path";
|
|
11029
11469
|
import crypto10 from "node:crypto";
|
|
11030
11470
|
|
|
11471
|
+
// shared/agentDefaults.ts
|
|
11472
|
+
var DEFAULT_CLI = "opencode";
|
|
11473
|
+
var DEFAULT_CEO_CLI = DEFAULT_CLI;
|
|
11474
|
+
|
|
11031
11475
|
// shared/usage.ts
|
|
11032
11476
|
function clock(at, now2, locale = "en-US") {
|
|
11033
11477
|
const d = new Date(at);
|
|
@@ -11157,8 +11601,8 @@ function analysisPrompt(name, fullName) {
|
|
|
11157
11601
|
}
|
|
11158
11602
|
|
|
11159
11603
|
// server/boxMachines.ts
|
|
11160
|
-
import
|
|
11161
|
-
import
|
|
11604
|
+
import fs19 from "node:fs/promises";
|
|
11605
|
+
import path19 from "node:path";
|
|
11162
11606
|
|
|
11163
11607
|
// server/boxHelpers.ts
|
|
11164
11608
|
var PUT = String.raw`
|
|
@@ -11321,6 +11765,9 @@ for (const dir of process.argv.slice(2)) c.projects[dir] = Object.assign({}, c.p
|
|
|
11321
11765
|
fs.writeFileSync(file, JSON.stringify(c, null, 2));
|
|
11322
11766
|
`;
|
|
11323
11767
|
var BOX_HELPERS = {
|
|
11768
|
+
"opencode-query.cjs": OPENCODE_BOX_QUERY_SOURCE,
|
|
11769
|
+
"opencode-plugin/index.js": OPENCODE_PLUGIN_SOURCE,
|
|
11770
|
+
"opencode-plugin/package.json": JSON.stringify({ name: "droidsembly-box-plugin", type: "module", exports: "./index.js" }),
|
|
11324
11771
|
"launch.cjs": BOX_LAUNCH_SOURCE,
|
|
11325
11772
|
"hook.cjs": BOX_HOOK_SOURCE,
|
|
11326
11773
|
"statusline.cjs": BOX_STATUSLINE_SOURCE,
|
|
@@ -11330,8 +11777,17 @@ var BOX_HELPERS = {
|
|
|
11330
11777
|
"seed-claude.cjs": BOX_SEED_CLAUDE_SOURCE
|
|
11331
11778
|
};
|
|
11332
11779
|
|
|
11780
|
+
// shared/opencodeGateDiagnostics.ts
|
|
11781
|
+
var GateDiagnosticError = class extends Error {
|
|
11782
|
+
constructor(category) {
|
|
11783
|
+
super(category);
|
|
11784
|
+
this.category = category;
|
|
11785
|
+
}
|
|
11786
|
+
category;
|
|
11787
|
+
};
|
|
11788
|
+
|
|
11333
11789
|
// server/boxMachines.ts
|
|
11334
|
-
var SETUP_REV =
|
|
11790
|
+
var SETUP_REV = 4;
|
|
11335
11791
|
var SETUP_TIMEOUT_MS = 20 * 6e4;
|
|
11336
11792
|
var LIVE = ["running", "idle", "creating"];
|
|
11337
11793
|
function failure(what, output, secrets) {
|
|
@@ -11347,8 +11803,8 @@ var BoxMachines = class {
|
|
|
11347
11803
|
ids = /* @__PURE__ */ new Map();
|
|
11348
11804
|
// machine -> Box id
|
|
11349
11805
|
ready = /* @__PURE__ */ new Map();
|
|
11350
|
-
// machine -> its Box, set up (once per office run)
|
|
11351
11806
|
states = /* @__PURE__ */ new Map();
|
|
11807
|
+
pausing = /* @__PURE__ */ new Map();
|
|
11352
11808
|
api() {
|
|
11353
11809
|
const api = this.deps.api();
|
|
11354
11810
|
if (!api) throw new Error("Cloud agents need your Upstash Box API key: Settings \u2192 Cloud agents.");
|
|
@@ -11392,17 +11848,22 @@ var BoxMachines = class {
|
|
|
11392
11848
|
}
|
|
11393
11849
|
/** The machine's Box, created, running and set up: the first time takes a few minutes. */
|
|
11394
11850
|
ensure(machine, note2) {
|
|
11395
|
-
|
|
11396
|
-
if (
|
|
11397
|
-
|
|
11398
|
-
|
|
11851
|
+
const pausing = this.pausing.get(machine);
|
|
11852
|
+
if (pausing) return pausing.catch(() => void 0).then(() => this.ensure(machine, note2));
|
|
11853
|
+
const cli = this.deps.cli?.(machine);
|
|
11854
|
+
const browser = this.deps.browser?.(machine) ?? !cli;
|
|
11855
|
+
const profile = `${cli ?? "all"}:${browser}`;
|
|
11856
|
+
const previous = this.ready.get(machine);
|
|
11857
|
+
if (!previous || previous.profile !== profile) {
|
|
11858
|
+
const p = (previous ? previous.promise : Promise.resolve()).then(() => this.bringUp(machine, note2, cli, browser)).catch((err) => {
|
|
11859
|
+
if (this.ready.get(machine)?.promise === p) this.ready.delete(machine);
|
|
11399
11860
|
this.setState(machine, "error");
|
|
11400
11861
|
throw err;
|
|
11401
11862
|
});
|
|
11402
|
-
this.ready.set(machine, p);
|
|
11863
|
+
this.ready.set(machine, { profile, promise: p });
|
|
11403
11864
|
return p;
|
|
11404
11865
|
}
|
|
11405
|
-
return
|
|
11866
|
+
return previous.promise.then(async (id) => {
|
|
11406
11867
|
const info = await this.api().get(id);
|
|
11407
11868
|
if (!info) {
|
|
11408
11869
|
this.ready.delete(machine);
|
|
@@ -11417,7 +11878,7 @@ var BoxMachines = class {
|
|
|
11417
11878
|
return id;
|
|
11418
11879
|
});
|
|
11419
11880
|
}
|
|
11420
|
-
async bringUp(machine, note2) {
|
|
11881
|
+
async bringUp(machine, note2, cli, browser = false) {
|
|
11421
11882
|
const api = this.api();
|
|
11422
11883
|
let id = await this.boxId(machine);
|
|
11423
11884
|
if (id) {
|
|
@@ -11440,8 +11901,12 @@ var BoxMachines = class {
|
|
|
11440
11901
|
}
|
|
11441
11902
|
this.setState(machine, "setting-up");
|
|
11442
11903
|
const git2 = await this.deps.git();
|
|
11443
|
-
const setup = await api.run(id, setupScript({ versions: this.deps.versions, rev: SETUP_REV, gitName: git2.name, gitEmail: git2.email })
|
|
11444
|
-
|
|
11904
|
+
const setup = await api.run(id, `sh -c ${sq(setupScript({ versions: this.deps.versions, rev: SETUP_REV, gitName: git2.name, gitEmail: git2.email, cli, browser }))}`, { timeoutMs: SETUP_TIMEOUT_MS });
|
|
11905
|
+
const setupMarkerPresent = setup.output.includes("CUBEFARM_SETUP_OK");
|
|
11906
|
+
if (setup.code !== 0 || !setupMarkerPresent) {
|
|
11907
|
+
const exit = Number.isInteger(setup.code) ? String(setup.code) : "unverified";
|
|
11908
|
+
throw failure(`Couldn't set up the cloud machine (exit ${exit}; setup marker ${setupMarkerPresent ? "present" : "missing"})`, setup.output, this.deps.secrets());
|
|
11909
|
+
}
|
|
11445
11910
|
for (const [name, source] of Object.entries(BOX_HELPERS)) await api.write(id, `${BOX_BIN}/${name}`, source);
|
|
11446
11911
|
await api.write(id, BOX_TMUX_CONF, TMUX_CONF);
|
|
11447
11912
|
this.setState(machine, "ready");
|
|
@@ -11456,7 +11921,7 @@ var BoxMachines = class {
|
|
|
11456
11921
|
const id = await this.ensure(machine, note2);
|
|
11457
11922
|
const r = await api.run(id, prepareDeskScript(fullName, base, branch), { env: await this.deps.githubEnv(), timeoutMs: 15 * 6e4 });
|
|
11458
11923
|
const lines = r.output.trim().split("\n");
|
|
11459
|
-
if (r.code !== 0) throw failure(`Couldn't set up the desk in ${fullName}'s cloud machine`, r.output, this.deps.secrets());
|
|
11924
|
+
if (r.code !== 0) throw failure(`Couldn't set up the desk in ${fullName}'s cloud machine (exit ${r.code})`, r.output, this.deps.secrets());
|
|
11460
11925
|
for (const l of lines.slice(0, -1)) if (/stale git lock|rebuilt/.test(l)) note2?.(l.trim());
|
|
11461
11926
|
await api.run(id, `node ${sq(`${BOX_BIN}/seed-claude.cjs`)} ${sq(boxDeskDir(fullName))}`);
|
|
11462
11927
|
return boxDeskDir(fullName);
|
|
@@ -11487,7 +11952,7 @@ var BoxMachines = class {
|
|
|
11487
11952
|
}
|
|
11488
11953
|
async remove(machine) {
|
|
11489
11954
|
const api = this.deps.api();
|
|
11490
|
-
const id = api ? await this.boxId(machine)
|
|
11955
|
+
const id = api ? await this.boxId(machine) : null;
|
|
11491
11956
|
if (!api || !id) return { removed: !!api, patches: [] };
|
|
11492
11957
|
const patches = [];
|
|
11493
11958
|
try {
|
|
@@ -11506,7 +11971,10 @@ var BoxMachines = class {
|
|
|
11506
11971
|
this.deps.log(`could not save the leftovers of cloud machine ${machine}: ${err.message}`);
|
|
11507
11972
|
return { removed: false, patches };
|
|
11508
11973
|
}
|
|
11509
|
-
await api
|
|
11974
|
+
if (!await removeBoxVerified(api, id)) {
|
|
11975
|
+
this.deps.log(`Removal of cloud machine ${machine} is not confirmed; its Box may still exist.`);
|
|
11976
|
+
return { removed: false, patches };
|
|
11977
|
+
}
|
|
11510
11978
|
this.ids.delete(machine);
|
|
11511
11979
|
this.ready.delete(machine);
|
|
11512
11980
|
this.states.delete(machine);
|
|
@@ -11567,32 +12035,83 @@ var BoxMachines = class {
|
|
|
11567
12035
|
* Is the Box's own CLI signed in (its login in the Box user's home)? Run with no credentials of any kind, so only that
|
|
11568
12036
|
* login counts. Wakes the Box. Throws when Upstash can't say.
|
|
11569
12037
|
*/
|
|
11570
|
-
async signedIn(machine, cli) {
|
|
12038
|
+
async signedIn(machine, cli, directory, model2 = "") {
|
|
11571
12039
|
const id = await this.ensure(machine);
|
|
11572
|
-
const r = await this.api().run(id, signInCheckScript(cli), { timeoutMs: 6e4 });
|
|
12040
|
+
const r = await this.api().run(id, cli === "opencode" ? openCodeBoxQuery("status", directory, model2) : signInCheckScript(cli), { timeoutMs: 6e4, ...cli === "opencode" ? { env: OPENCODE_BOX_ENV } : {} });
|
|
11573
12041
|
const out = signInOutcome(r.output);
|
|
11574
|
-
if (out === null) throw new Error(`Couldn't
|
|
12042
|
+
if (r.code !== 0 || out === null) throw new Error(`Couldn't check the coding agent's connection in the cloud machine. Check its provider and model setup.`);
|
|
11575
12043
|
return out;
|
|
11576
12044
|
}
|
|
12045
|
+
async openCodeConnections(machine, directory) {
|
|
12046
|
+
const id = await this.boxId(machine);
|
|
12047
|
+
if (!id) throw new Error("The cloud machine is not ready. Connection settings never create a Box.");
|
|
12048
|
+
const r = await this.api().run(id, openCodeBoxQuery("connections", directory), { env: OPENCODE_BOX_ENV, timeoutMs: 6e4 });
|
|
12049
|
+
if (r.code !== 0) throw new Error("Could not read OpenCode connections in the cloud machine.");
|
|
12050
|
+
try {
|
|
12051
|
+
return sanitizeConnections(JSON.parse(r.output));
|
|
12052
|
+
} catch {
|
|
12053
|
+
throw new Error("Invalid OpenCode connections from the cloud machine.");
|
|
12054
|
+
}
|
|
12055
|
+
}
|
|
12056
|
+
/** Post-login metadata check. Unlike task setup, this must never provision a missing Box. */
|
|
12057
|
+
async openCodeConnectionReady(machine, directory, model2) {
|
|
12058
|
+
const id = await this.boxId(machine);
|
|
12059
|
+
if (!id) return false;
|
|
12060
|
+
const r = await this.api().run(id, openCodeBoxQuery("status", directory, model2), { env: OPENCODE_BOX_ENV, timeoutMs: 6e4 });
|
|
12061
|
+
const outcome = signInOutcome(r.output);
|
|
12062
|
+
if (r.code !== 0 || outcome === null) throw new GateDiagnosticError("remote-query-output-failed");
|
|
12063
|
+
return outcome;
|
|
12064
|
+
}
|
|
12065
|
+
/** OAuth-only gate probe: existing Box only, no resume/setup, no raw remote output in the result. */
|
|
12066
|
+
async openCodeReadiness(machine, directory, model2) {
|
|
12067
|
+
try {
|
|
12068
|
+
const id = await this.boxId(machine);
|
|
12069
|
+
if (!id) return { state: "query-failed", check: "box" };
|
|
12070
|
+
const r = await this.api().run(id, openCodeBoxQuery("readiness", directory, model2), { env: OPENCODE_BOX_ENV, timeoutMs: 6e4 });
|
|
12071
|
+
return parseOpenCodeReadiness(r.code, r.output);
|
|
12072
|
+
} catch {
|
|
12073
|
+
return { state: "query-failed", check: "transport" };
|
|
12074
|
+
}
|
|
12075
|
+
}
|
|
12076
|
+
async openCodeModels(machine, directory) {
|
|
12077
|
+
const id = await this.boxId(machine);
|
|
12078
|
+
if (!id) throw new Error("The cloud machine is not ready yet. Wait for setup before browsing its models.");
|
|
12079
|
+
const r = await this.api().run(id, openCodeBoxQuery("models", directory), { env: OPENCODE_BOX_ENV, timeoutMs: 6e4 });
|
|
12080
|
+
if (r.code !== 0) throw new Error("Could not read OpenCode models in the cloud machine.");
|
|
12081
|
+
try {
|
|
12082
|
+
const data = JSON.parse(r.output);
|
|
12083
|
+
return sanitizeCatalog(data.list, data.selected, directory);
|
|
12084
|
+
} catch {
|
|
12085
|
+
throw new Error("Invalid OpenCode model inventory from the cloud machine.");
|
|
12086
|
+
}
|
|
12087
|
+
}
|
|
11577
12088
|
/** Forget a login its CLI's servers turned away (an expired one), so it reads as signed out until it's signed in again. */
|
|
11578
12089
|
async signOut(machine, cli) {
|
|
11579
12090
|
const id = await this.ensure(machine);
|
|
11580
12091
|
await this.api().run(id, signOutScript(cli), { timeoutMs: 6e4 });
|
|
11581
12092
|
}
|
|
11582
12093
|
/** Pause a machine's Box (an idle cloud agent); it wakes for their next task. */
|
|
11583
|
-
|
|
11584
|
-
const
|
|
11585
|
-
if (
|
|
11586
|
-
|
|
11587
|
-
|
|
12094
|
+
pause(machine, stillIdle = () => true) {
|
|
12095
|
+
const previous = this.pausing.get(machine);
|
|
12096
|
+
if (previous) return previous;
|
|
12097
|
+
const pending2 = (async () => {
|
|
12098
|
+
const id = await this.running(machine);
|
|
12099
|
+
if (!id || !stillIdle()) return;
|
|
12100
|
+
await this.api().pause(id);
|
|
12101
|
+
this.setState(machine, "paused");
|
|
12102
|
+
})().finally(() => {
|
|
12103
|
+
this.pausing.delete(machine);
|
|
12104
|
+
});
|
|
12105
|
+
this.pausing.set(machine, pending2);
|
|
12106
|
+
return pending2;
|
|
11588
12107
|
}
|
|
11589
12108
|
async saveLeftovers(fullName, machine, data) {
|
|
11590
|
-
const dir =
|
|
11591
|
-
await
|
|
12109
|
+
const dir = path19.join(HOME_DIR, "leftovers", fullName.replace("/", "__"));
|
|
12110
|
+
await fs19.mkdir(dir, { recursive: true });
|
|
11592
12111
|
const base = `machine-${machine}-${stamp2(/* @__PURE__ */ new Date())}`;
|
|
11593
|
-
let file =
|
|
11594
|
-
for (let n = 2; await
|
|
11595
|
-
await
|
|
12112
|
+
let file = path19.join(dir, `${base}.patch`);
|
|
12113
|
+
for (let n = 2; await fs19.stat(file).then(() => true, () => false); n++) file = path19.join(dir, `${base}-${n}.patch`);
|
|
12114
|
+
await fs19.writeFile(file, data);
|
|
11596
12115
|
return file;
|
|
11597
12116
|
}
|
|
11598
12117
|
};
|
|
@@ -13027,39 +13546,39 @@ var Previews = class {
|
|
|
13027
13546
|
};
|
|
13028
13547
|
|
|
13029
13548
|
// server/qaShots.ts
|
|
13030
|
-
import
|
|
13031
|
-
import
|
|
13549
|
+
import fs20 from "node:fs/promises";
|
|
13550
|
+
import path20 from "node:path";
|
|
13032
13551
|
var QA_SHOTS_KEPT = 8;
|
|
13033
13552
|
var EXT = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/svg+xml": "svg" };
|
|
13034
|
-
var qaShotsDir = (root, repoId2, pr) =>
|
|
13035
|
-
var qaShotFile = (dir, index, mime) =>
|
|
13553
|
+
var qaShotsDir = (root, repoId2, pr) => path20.join(root, repoId2.replace("/", "__"), `pr-${pr}`);
|
|
13554
|
+
var qaShotFile = (dir, index, mime) => path20.join(dir, `${String(index + 1).padStart(2, "0")}.${EXT[mime] ?? "img"}`);
|
|
13036
13555
|
async function saveQaShots(dir, shots) {
|
|
13037
13556
|
await removeQaShots(dir);
|
|
13038
13557
|
const kept = shots.slice(-QA_SHOTS_KEPT);
|
|
13039
13558
|
if (!kept.length) return [];
|
|
13040
|
-
await
|
|
13559
|
+
await fs20.mkdir(dir, { recursive: true });
|
|
13041
13560
|
const out = [];
|
|
13042
13561
|
for (const [i, s2] of kept.entries()) {
|
|
13043
|
-
await
|
|
13562
|
+
await fs20.writeFile(qaShotFile(dir, i, s2.mime), s2.data);
|
|
13044
13563
|
out.push({ caption: s2.caption, page: s2.page, mime: s2.mime });
|
|
13045
13564
|
}
|
|
13046
13565
|
return out;
|
|
13047
13566
|
}
|
|
13048
13567
|
async function readQaShot(dir, index, mime) {
|
|
13049
|
-
return
|
|
13568
|
+
return fs20.readFile(qaShotFile(dir, index, mime)).catch(() => null);
|
|
13050
13569
|
}
|
|
13051
13570
|
async function removeQaShots(dir) {
|
|
13052
|
-
await
|
|
13571
|
+
await fs20.rm(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
|
|
13053
13572
|
}
|
|
13054
13573
|
async function pruneQaShots(root, keep) {
|
|
13055
|
-
const repos2 = await
|
|
13574
|
+
const repos2 = await fs20.readdir(root, { withFileTypes: true }).catch(() => []);
|
|
13056
13575
|
for (const repo of repos2.filter((e) => e.isDirectory())) {
|
|
13057
13576
|
const repoId2 = repo.name.replace("__", "/");
|
|
13058
|
-
const prs = await
|
|
13577
|
+
const prs = await fs20.readdir(path20.join(root, repo.name), { withFileTypes: true }).catch(() => []);
|
|
13059
13578
|
for (const pr of prs) {
|
|
13060
13579
|
const n = /^pr-(\d+)$/.exec(pr.name)?.[1];
|
|
13061
13580
|
if (!n || keep.has(`${repoId2}#${n}`)) continue;
|
|
13062
|
-
await removeQaShots(
|
|
13581
|
+
await removeQaShots(path20.join(root, repo.name, pr.name)).catch(() => void 0);
|
|
13063
13582
|
}
|
|
13064
13583
|
}
|
|
13065
13584
|
}
|
|
@@ -13823,8 +14342,8 @@ function loadLedger(raw) {
|
|
|
13823
14342
|
}
|
|
13824
14343
|
|
|
13825
14344
|
// server/terminal.ts
|
|
13826
|
-
import
|
|
13827
|
-
import
|
|
14345
|
+
import fs21 from "node:fs/promises";
|
|
14346
|
+
import path21 from "node:path";
|
|
13828
14347
|
import { stripVTControlCharacters } from "node:util";
|
|
13829
14348
|
import xtermHeadless from "@xterm/headless";
|
|
13830
14349
|
import xtermSerialize from "@xterm/addon-serialize";
|
|
@@ -13938,15 +14457,15 @@ var AgentTerminal = class {
|
|
|
13938
14457
|
const next = this.saving.then(async () => {
|
|
13939
14458
|
this.dirty = false;
|
|
13940
14459
|
await this.flush();
|
|
13941
|
-
await
|
|
13942
|
-
await
|
|
13943
|
-
await
|
|
14460
|
+
await fs21.mkdir(path21.dirname(file), { recursive: true });
|
|
14461
|
+
await fs21.writeFile(`${file}.tmp`, this.snapshot());
|
|
14462
|
+
await fs21.rename(`${file}.tmp`, file);
|
|
13944
14463
|
});
|
|
13945
14464
|
this.saving = next.catch(() => void 0);
|
|
13946
14465
|
return next;
|
|
13947
14466
|
}
|
|
13948
14467
|
async load(file) {
|
|
13949
|
-
const data = await
|
|
14468
|
+
const data = await fs21.readFile(file, "utf8").catch(() => "");
|
|
13950
14469
|
if (!data) return;
|
|
13951
14470
|
this.term.write(data);
|
|
13952
14471
|
this.note("(the office restarted)");
|
|
@@ -14632,14 +15151,15 @@ var Outbox = class {
|
|
|
14632
15151
|
var BOX_SIZES = ["small", "medium", "large"];
|
|
14633
15152
|
var FREE_BOX_LIMIT = 10;
|
|
14634
15153
|
var MAX_BOX_LIMIT = 1e3;
|
|
14635
|
-
var DEFAULT_CLOUD = { machineKind: "local", boxSize: "small", boxLimit: FREE_BOX_LIMIT };
|
|
15154
|
+
var DEFAULT_CLOUD = { machineKind: "local", boxSize: "small", boxLimit: FREE_BOX_LIMIT, pauseNewWork: false };
|
|
14636
15155
|
function cloudSettings(base, raw) {
|
|
14637
15156
|
const r = raw && typeof raw === "object" ? raw : {};
|
|
14638
15157
|
const limit = Math.round(Number(r.boxLimit));
|
|
14639
15158
|
return {
|
|
14640
15159
|
machineKind: r.machineKind === "box" || r.machineKind === "local" ? r.machineKind : base.machineKind,
|
|
14641
15160
|
boxSize: BOX_SIZES.includes(r.boxSize) ? r.boxSize : base.boxSize,
|
|
14642
|
-
boxLimit: Number.isFinite(limit) && limit >= 1 ? Math.min(MAX_BOX_LIMIT, limit) : base.boxLimit
|
|
15161
|
+
boxLimit: Number.isFinite(limit) && limit >= 1 ? Math.min(MAX_BOX_LIMIT, limit) : base.boxLimit,
|
|
15162
|
+
pauseNewWork: typeof r.pauseNewWork === "boolean" ? r.pauseNewWork : base.pauseNewWork ?? false
|
|
14643
15163
|
};
|
|
14644
15164
|
}
|
|
14645
15165
|
|
|
@@ -14875,8 +15395,8 @@ var EFFORTS = ["low", "medium", "high", "xhigh", "max"];
|
|
|
14875
15395
|
var CEO_MODEL = "claude-opus-5-5";
|
|
14876
15396
|
var CEO_EFFORT = "xhigh";
|
|
14877
15397
|
var CEO_NAME = "Morgan";
|
|
14878
|
-
var CEO_DIR =
|
|
14879
|
-
var DEFAULT_PROJECTS_DIR = defaultProjectsDir(
|
|
15398
|
+
var CEO_DIR = path22.join(HOME_DIR, "ceo");
|
|
15399
|
+
var DEFAULT_PROJECTS_DIR = defaultProjectsDir(path22.resolve(import.meta.dirname, ".."));
|
|
14880
15400
|
var MAX_ISSUES_PER_JOB = 12;
|
|
14881
15401
|
var KEEP_MESSAGES = 200;
|
|
14882
15402
|
var KEEP_DECIDED_REQUESTS = 40;
|
|
@@ -14902,26 +15422,26 @@ var SignInNeeded = class extends Error {
|
|
|
14902
15422
|
}
|
|
14903
15423
|
cli;
|
|
14904
15424
|
};
|
|
14905
|
-
var SCREENS_DIR =
|
|
15425
|
+
var SCREENS_DIR = path22.join(HOME_DIR, "screens");
|
|
14906
15426
|
var MIME_EXT = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/svg+xml": "svg" };
|
|
14907
|
-
var screenFile = (agentId, mime) =>
|
|
15427
|
+
var screenFile = (agentId, mime) => path22.join(SCREENS_DIR, `${agentId}.${MIME_EXT[mime] ?? "img"}`);
|
|
14908
15428
|
async function loadScreen(agentId) {
|
|
14909
15429
|
for (const [mime, ext] of Object.entries(MIME_EXT)) {
|
|
14910
|
-
const file =
|
|
15430
|
+
const file = path22.join(SCREENS_DIR, `${agentId}.${ext}`);
|
|
14911
15431
|
try {
|
|
14912
|
-
const [data, stat] = await Promise.all([
|
|
15432
|
+
const [data, stat] = await Promise.all([fs22.readFile(file), fs22.stat(file)]);
|
|
14913
15433
|
return { data, mime, at: stat.mtimeMs };
|
|
14914
15434
|
} catch {
|
|
14915
15435
|
}
|
|
14916
15436
|
}
|
|
14917
15437
|
return null;
|
|
14918
15438
|
}
|
|
14919
|
-
var QA_SHOTS_DIR =
|
|
15439
|
+
var QA_SHOTS_DIR = path22.join(HOME_DIR, "qa-shots");
|
|
14920
15440
|
async function removeScreens(agentId) {
|
|
14921
|
-
await Promise.all(Object.values(MIME_EXT).map((ext) =>
|
|
15441
|
+
await Promise.all(Object.values(MIME_EXT).map((ext) => fs22.rm(path22.join(SCREENS_DIR, `${agentId}.${ext}`), { force: true })));
|
|
14922
15442
|
}
|
|
14923
|
-
var TERMINALS_DIR =
|
|
14924
|
-
var terminalFile = (agentId) =>
|
|
15443
|
+
var TERMINALS_DIR = path22.join(HOME_DIR, "terminals");
|
|
15444
|
+
var terminalFile = (agentId) => path22.join(TERMINALS_DIR, `${agentId}.ansi`);
|
|
14925
15445
|
var TERMINAL_SAVE_MS = 2e4;
|
|
14926
15446
|
var QA_SCHEMA = {
|
|
14927
15447
|
type: "object",
|
|
@@ -15003,15 +15523,15 @@ var Swarm = class {
|
|
|
15003
15523
|
this.backend = backend;
|
|
15004
15524
|
this.weather = new WeatherService({
|
|
15005
15525
|
api: backend.weather,
|
|
15006
|
-
file:
|
|
15526
|
+
file: path22.join(HOME_DIR, backend.demo ? "demo-weather.json" : "weather.json"),
|
|
15007
15527
|
settings: () => this.state.settings.weather,
|
|
15008
15528
|
changed: (weather) => this.broadcast({ type: "weather", weather }),
|
|
15009
15529
|
log: (line) => console.log(line)
|
|
15010
15530
|
});
|
|
15011
15531
|
this.voice = new Voice({
|
|
15012
15532
|
api: backend.voice,
|
|
15013
|
-
secretsFile:
|
|
15014
|
-
cacheDir:
|
|
15533
|
+
secretsFile: path22.join(HOME_DIR, backend.demo ? "demo-secrets.json" : "secrets.json"),
|
|
15534
|
+
cacheDir: path22.join(HOME_DIR, backend.demo ? "demo-voice" : "voice"),
|
|
15015
15535
|
settings: () => this.state.settings.voice,
|
|
15016
15536
|
listen: () => this.state.settings.listen,
|
|
15017
15537
|
language: () => languageOf(this.state.settings.language),
|
|
@@ -15022,14 +15542,14 @@ var Swarm = class {
|
|
|
15022
15542
|
log: (line) => console.log(line)
|
|
15023
15543
|
});
|
|
15024
15544
|
this.journal = new Journal({
|
|
15025
|
-
dir:
|
|
15545
|
+
dir: path22.join(HOME_DIR, backend.demo ? "demo-journal" : "journal"),
|
|
15026
15546
|
frame: () => journalFrame(this.snapshot(), this.secrets()),
|
|
15027
15547
|
secrets: () => this.secrets()
|
|
15028
15548
|
});
|
|
15029
15549
|
this.notifier = new Notifier({
|
|
15030
15550
|
transport: backend.notify,
|
|
15031
|
-
secretsFile:
|
|
15032
|
-
pushFile:
|
|
15551
|
+
secretsFile: path22.join(HOME_DIR, backend.demo ? "demo-secrets.json" : "secrets.json"),
|
|
15552
|
+
pushFile: path22.join(HOME_DIR, backend.demo ? "demo-push.json" : "push.json"),
|
|
15033
15553
|
settings: () => this.state.settings.notify,
|
|
15034
15554
|
broadcast: (note2) => this.broadcast({ type: "notify", note: note2 }),
|
|
15035
15555
|
channelsChanged: (notifyChannels) => this.broadcast({ type: "notifyChannels", notifyChannels }),
|
|
@@ -15037,7 +15557,8 @@ var Swarm = class {
|
|
|
15037
15557
|
});
|
|
15038
15558
|
this.cloud = new Cloud({
|
|
15039
15559
|
// The demo's fake cloud keeps a file of its own: its tests run beside the notifier's, which share demo-secrets.json.
|
|
15040
|
-
secretsFile:
|
|
15560
|
+
secretsFile: path22.join(HOME_DIR, backend.demo ? "demo-cloud-secrets.json" : "secrets.json"),
|
|
15561
|
+
credentials: backend.cloud.credentials,
|
|
15041
15562
|
env: backend.cloud.env(),
|
|
15042
15563
|
boxes: (key) => backend.cloud.boxes(key),
|
|
15043
15564
|
ghToken: () => backend.cloud.ghToken(),
|
|
@@ -15051,6 +15572,14 @@ var Swarm = class {
|
|
|
15051
15572
|
office: () => this.state.officeId,
|
|
15052
15573
|
size: () => this.state.settings.cloud.boxSize,
|
|
15053
15574
|
versions: boxVersions(),
|
|
15575
|
+
cli: (machine) => {
|
|
15576
|
+
const a = this.state.agents.find((a2) => a2.machine === machine);
|
|
15577
|
+
return a?.cli || this.state.settings.defaultCli;
|
|
15578
|
+
},
|
|
15579
|
+
browser: (machine) => {
|
|
15580
|
+
const a = this.state.agents.find((a2) => a2.machine === machine);
|
|
15581
|
+
return this.state.repos.find((r) => r.id === a?.repoId)?.browserTesting ?? false;
|
|
15582
|
+
},
|
|
15054
15583
|
git: () => backend.cloud.gitIdentity(this.user),
|
|
15055
15584
|
githubEnv: () => this.cloud.githubEnv(),
|
|
15056
15585
|
state: (machine) => this.boxState(machine),
|
|
@@ -15069,14 +15598,22 @@ var Swarm = class {
|
|
|
15069
15598
|
});
|
|
15070
15599
|
}
|
|
15071
15600
|
backend;
|
|
15601
|
+
eventListeners = /* @__PURE__ */ new Set();
|
|
15602
|
+
/** In-process observers use the same public events as UI clients; no polling or private-state patching. */
|
|
15603
|
+
onEvent(listener) {
|
|
15604
|
+
this.eventListeners.add(listener);
|
|
15605
|
+
return () => {
|
|
15606
|
+
this.eventListeners.delete(listener);
|
|
15607
|
+
};
|
|
15608
|
+
}
|
|
15072
15609
|
state = {
|
|
15073
15610
|
settings: {
|
|
15074
15611
|
sessionLimit: 0,
|
|
15075
15612
|
language: "en",
|
|
15076
|
-
defaultModel:
|
|
15613
|
+
defaultModel: "",
|
|
15077
15614
|
defaultEffort: "medium",
|
|
15078
15615
|
runtime: "terminal",
|
|
15079
|
-
defaultCli:
|
|
15616
|
+
defaultCli: DEFAULT_CLI,
|
|
15080
15617
|
scaling: "approve",
|
|
15081
15618
|
maxAgents: DEFAULT_MAX_AGENTS,
|
|
15082
15619
|
ceoHeartbeatMin: 60,
|
|
@@ -15109,7 +15646,8 @@ var Swarm = class {
|
|
|
15109
15646
|
held: [],
|
|
15110
15647
|
progress: emptyLedger(),
|
|
15111
15648
|
pong: {},
|
|
15112
|
-
officeId: officeId()
|
|
15649
|
+
officeId: officeId(),
|
|
15650
|
+
agentDefaultsVersion: 1
|
|
15113
15651
|
};
|
|
15114
15652
|
/**
|
|
15115
15653
|
* The CEO's office tools. Every session gets its own server: one can only be connected to one session at a time, so
|
|
@@ -15201,16 +15739,22 @@ var Swarm = class {
|
|
|
15201
15739
|
cloud;
|
|
15202
15740
|
/** Cloud agents' machines: an Upstash Box each. */
|
|
15203
15741
|
boxMachines;
|
|
15742
|
+
finishingAgents = /* @__PURE__ */ new Map();
|
|
15743
|
+
pausingAgents = /* @__PURE__ */ new Set();
|
|
15204
15744
|
/** Cloud agents waiting for a sign-in in their terminal (holdForSignIn), by agent id. */
|
|
15205
15745
|
signIns = /* @__PURE__ */ new Map();
|
|
15206
15746
|
toldStuck = /* @__PURE__ */ new Set();
|
|
15207
15747
|
// ---------- lifecycle ----------
|
|
15208
15748
|
async init() {
|
|
15749
|
+
let legacyDefaults = false;
|
|
15209
15750
|
try {
|
|
15210
|
-
const raw = await
|
|
15751
|
+
const raw = await fs22.readFile(STATE_FILE, "utf8");
|
|
15211
15752
|
const loaded = JSON.parse(raw);
|
|
15753
|
+
legacyDefaults = loaded.agentDefaultsVersion !== 1;
|
|
15212
15754
|
this.state = {
|
|
15213
|
-
|
|
15755
|
+
agentDefaultsVersion: 1,
|
|
15756
|
+
// Missing legacy defaults meant Claude; do not inherit the new-office proposal.
|
|
15757
|
+
settings: { ...this.state.settings, defaultCli: "claude", defaultModel: DEFAULT_MODEL, ...loaded.settings },
|
|
15214
15758
|
repos: (loaded.repos ?? []).map((r) => ({
|
|
15215
15759
|
...r,
|
|
15216
15760
|
autoMerge: r.autoMerge ?? true,
|
|
@@ -15230,7 +15774,7 @@ var Swarm = class {
|
|
|
15230
15774
|
look: a.look ?? lookFor(a.name),
|
|
15231
15775
|
style: cleanStyle(a.style),
|
|
15232
15776
|
task: a.task ?? (a.issueNumber ? "issue" : null),
|
|
15233
|
-
cli: isCli(a.cli) ? a.cli : "",
|
|
15777
|
+
cli: isCli(a.cli) ? a.cli : legacyDefaults && a.role === "ceo" ? "claude" : "",
|
|
15234
15778
|
sessionCli: a.sessionCli ?? (a.sessionId ? "claude" : null)
|
|
15235
15779
|
})),
|
|
15236
15780
|
qa: (loaded.qa ?? []).map((q) => ({
|
|
@@ -15328,13 +15872,16 @@ var Swarm = class {
|
|
|
15328
15872
|
const boxKept = this.state.agents.filter((a) => a.host === "box" && a.boxCli);
|
|
15329
15873
|
if (!boxApi) for (const a of boxKept) a.boxCli = null;
|
|
15330
15874
|
else {
|
|
15331
|
-
const kept = boxKept.map((a) =>
|
|
15332
|
-
|
|
15333
|
-
|
|
15334
|
-
|
|
15335
|
-
|
|
15336
|
-
|
|
15337
|
-
|
|
15875
|
+
const kept = boxKept.map((a) => {
|
|
15876
|
+
const token = a.boxCli.token;
|
|
15877
|
+
return {
|
|
15878
|
+
agentId: a.id,
|
|
15879
|
+
rec: a.boxCli,
|
|
15880
|
+
api: boxApi,
|
|
15881
|
+
record: (rec) => this.boxCliRecord(a.id, rec, rec ? void 0 : token),
|
|
15882
|
+
connection: (up) => this.boxMachines.connection(a.machine ?? machineName(a.id), up)
|
|
15883
|
+
};
|
|
15884
|
+
});
|
|
15338
15885
|
back.push(
|
|
15339
15886
|
...await this.backend.cloud.reconnect(kept, terminalOf).catch((err) => {
|
|
15340
15887
|
console.warn("could not pick up cloud agents' CLIs", err);
|
|
@@ -15368,7 +15915,7 @@ var Swarm = class {
|
|
|
15368
15915
|
this.state.ops = this.backend.seedOps?.(this.state.repos.map((r) => r.id), Date.now()) ?? this.state.ops;
|
|
15369
15916
|
}
|
|
15370
15917
|
for (const r of this.state.repos) this.ensureAgent(r);
|
|
15371
|
-
this.ensureCeo(interrupted);
|
|
15918
|
+
this.ensureCeo(interrupted, legacyDefaults ? "claude" : DEFAULT_CEO_CLI);
|
|
15372
15919
|
for (const a of this.state.agents) if (a.role !== "ceo") apply(this.state.progress, { kind: "hired", agentId: a.id, at: Date.now() });
|
|
15373
15920
|
for (const r of this.state.repos) void this.cloneRepo(r.id);
|
|
15374
15921
|
await Promise.all(this.state.repos.map((r) => this.syncRepo(r.id)));
|
|
@@ -15687,6 +16234,7 @@ var Swarm = class {
|
|
|
15687
16234
|
broadcast(ev) {
|
|
15688
16235
|
this.outbox.broadcast(ev);
|
|
15689
16236
|
this.observe(ev);
|
|
16237
|
+
for (const listener of this.eventListeners) listener(ev);
|
|
15690
16238
|
}
|
|
15691
16239
|
/** What follows from an event besides the tabs hearing it: ticker lines and mission control's numbers. */
|
|
15692
16240
|
observe(ev) {
|
|
@@ -15770,10 +16318,10 @@ var Swarm = class {
|
|
|
15770
16318
|
}
|
|
15771
16319
|
async writeStateFile() {
|
|
15772
16320
|
for (const a of this.state.agents) a.logTail = (this.agentRt.get(a.id)?.log ?? []).slice(-200);
|
|
15773
|
-
await
|
|
16321
|
+
await fs22.mkdir(path22.dirname(STATE_FILE), { recursive: true });
|
|
15774
16322
|
const tmp = `${STATE_FILE}.tmp`;
|
|
15775
|
-
await
|
|
15776
|
-
await
|
|
16323
|
+
await fs22.writeFile(tmp, JSON.stringify(this.state, null, 2));
|
|
16324
|
+
await fs22.rename(tmp, STATE_FILE);
|
|
15777
16325
|
}
|
|
15778
16326
|
// ---------- lookups ----------
|
|
15779
16327
|
repo(id) {
|
|
@@ -15841,7 +16389,7 @@ var Swarm = class {
|
|
|
15841
16389
|
/** Remove a machine, saying where its unpushed work went; one still in use is tried again by sweepMachines. */
|
|
15842
16390
|
async removeMachine(machine, name, host = "local") {
|
|
15843
16391
|
const r = await this.machinesFor({ host }).remove(machine).catch(() => ({ removed: false, patches: [] }));
|
|
15844
|
-
if (r.patches.length) this.postMessage("office", `\u{1F9F3} ${name ?? "A former agent"} left work that was on no GitHub branch: saved in ${
|
|
16392
|
+
if (r.patches.length) this.postMessage("office", `\u{1F9F3} ${name ?? "A former agent"} left work that was on no GitHub branch: saved in ${path22.dirname(r.patches[0])}.`);
|
|
15845
16393
|
if (host === "box" && r.removed) void this.cloud.count().catch(() => void 0);
|
|
15846
16394
|
}
|
|
15847
16395
|
/** Machines whose agents are gone (on this computer, or Boxes of this office): removed while still in use, or left by an office that stopped half-way. */
|
|
@@ -15855,17 +16403,117 @@ var Swarm = class {
|
|
|
15855
16403
|
this.quotaWaiting.delete(a.id);
|
|
15856
16404
|
Object.assign(a, { status: "idle", task: null, issueNumber: null, issueTitle: null, branch: null, prNumber: null, prUrl: null, lastError: null });
|
|
15857
16405
|
this.emitAgent(a);
|
|
16406
|
+
this.pauseIdleBox(a);
|
|
16407
|
+
}
|
|
16408
|
+
/** Either the task or the CLI can finish first; check both transitions. */
|
|
16409
|
+
pauseIdleBox(a) {
|
|
16410
|
+
const machine = a.machine;
|
|
16411
|
+
const idle2 = () => this.state.agents.includes(a) && a.host === "box" && a.machine === machine && (a.status === "idle" && !a.task || a.status === "done") && !this.finishingAgents.has(a.id) && !a.boxCli && !a.needsSignIn && this.openCodeAuthRun?.agentId !== a.id;
|
|
16412
|
+
if (!machine || !idle2() || this.pausingAgents.has(a.id)) return;
|
|
16413
|
+
this.pausingAgents.add(a.id);
|
|
16414
|
+
void this.boxMachines.pause(machine, idle2).catch(() => {
|
|
16415
|
+
this.appendLog(a, [{ kind: "system", text: "\u2601 Automatic Box pause failed. The cloud machine may still be active." }]);
|
|
16416
|
+
}).finally(() => {
|
|
16417
|
+
this.pausingAgents.delete(a.id);
|
|
16418
|
+
});
|
|
15858
16419
|
}
|
|
15859
16420
|
// ---------- GitHub / repos ----------
|
|
15860
16421
|
listGithubRepos(owner) {
|
|
15861
16422
|
return this.backend.listMyRepos(owner);
|
|
15862
16423
|
}
|
|
16424
|
+
configuringOpenCode = false;
|
|
16425
|
+
openCodeAuthRun = null;
|
|
16426
|
+
async openCodeConnections(id) {
|
|
16427
|
+
const a = this.agent(id);
|
|
16428
|
+
if ((a.cli || (a.role === "ceo" ? DEFAULT_CEO_CLI : this.state.settings.defaultCli)) !== "opencode") throw new HttpError(409, "Choose OpenCode first.");
|
|
16429
|
+
if (a.host === "box" && a.role !== "ceo") {
|
|
16430
|
+
const machine = this.machineOf(a);
|
|
16431
|
+
return { scope: "box", scopeKey: `box:${machine}`, integrations: await this.boxMachines.openCodeConnections(machine, this.boxMachines.deskDir(machine, this.repo(a.repoId).fullName)), configuringAgent: this.openCodeAuthRun?.agentId ?? null };
|
|
16432
|
+
}
|
|
16433
|
+
if (!this.backend.openCodeConnections) throw new HttpError(409, "OpenCode connections are unavailable in this backend.");
|
|
16434
|
+
if (a.role === "ceo") await fs22.mkdir(CEO_DIR, { recursive: true });
|
|
16435
|
+
const directory = a.role === "ceo" ? CEO_DIR : this.backend.mainDir(this.repo(a.repoId).fullName);
|
|
16436
|
+
return { scope: "local", scopeKey: "local", integrations: await this.backend.openCodeConnections(directory), configuringAgent: this.openCodeAuthRun?.agentId ?? null };
|
|
16437
|
+
}
|
|
16438
|
+
async configureOpenCode(id, input, expectedScope) {
|
|
16439
|
+
const a = this.agent(id);
|
|
16440
|
+
const replaceable = () => {
|
|
16441
|
+
const s2 = this.signIns.get(id);
|
|
16442
|
+
return !!s2?.run && !s2.held && !s2.starting;
|
|
16443
|
+
};
|
|
16444
|
+
const busy2 = () => this.state.agents.some((a2) => BUSY3.includes(a2.status)) || [...this.agentRt].some(([agentId, rt]) => rt.session || rt.terminal?.live && !(agentId === id && replaceable())) || [...this.signIns].some(([agentId, s2]) => s2.starting || s2.run && !(agentId === id && replaceable()));
|
|
16445
|
+
const available = () => !this.configuringOpenCode && !busy2();
|
|
16446
|
+
if (!available()) throw new HttpError(409, "Stop all work and close coding-agent terminals before changing OpenCode accounts.");
|
|
16447
|
+
const host = a.host;
|
|
16448
|
+
const machine = a.host === "box" ? this.machineOf(a) : null;
|
|
16449
|
+
const operation = { agentId: id, run: null };
|
|
16450
|
+
this.configuringOpenCode = true;
|
|
16451
|
+
this.openCodeAuthRun = operation;
|
|
16452
|
+
try {
|
|
16453
|
+
const catalog = await this.openCodeConnections(id);
|
|
16454
|
+
if (catalog.scopeKey !== expectedScope) throw new HttpError(409, "Connection host changed; reload connections before making changes.");
|
|
16455
|
+
let args;
|
|
16456
|
+
try {
|
|
16457
|
+
args = connectionArgs(catalog.integrations, input);
|
|
16458
|
+
} catch (err) {
|
|
16459
|
+
throw new HttpError(400, err.message);
|
|
16460
|
+
}
|
|
16461
|
+
const unchanged = () => this.openCodeAuthRun === operation && this.state.agents.includes(a) && a.host === host && (a.cli || (a.role === "ceo" ? DEFAULT_CEO_CLI : this.state.settings.defaultCli)) === "opencode" && (host !== "box" || this.machineOf(a) === machine);
|
|
16462
|
+
if (!unchanged() || busy2()) throw new HttpError(409, "Agent setup or work changed; reload connections.");
|
|
16463
|
+
if (replaceable()) this.dropSignIn(id);
|
|
16464
|
+
const term = this.terminalFor(a);
|
|
16465
|
+
const end = async (code) => {
|
|
16466
|
+
if (this.openCodeAuthRun !== operation) return;
|
|
16467
|
+
if (code === 0 && catalog.scope === "box" && unchanged()) {
|
|
16468
|
+
const ready2 = await this.boxMachines.openCodeConnectionReady(machine, this.boxMachines.deskDir(machine, this.repo(a.repoId).fullName), this.modelFor(a, "opencode")).catch(() => false);
|
|
16469
|
+
if (this.openCodeAuthRun !== operation) return;
|
|
16470
|
+
if (ready2 && unchanged()) {
|
|
16471
|
+
a.needsSignIn = false;
|
|
16472
|
+
delete a.openCodeAuthRejected;
|
|
16473
|
+
this.emitAgent(a);
|
|
16474
|
+
this.save();
|
|
16475
|
+
}
|
|
16476
|
+
}
|
|
16477
|
+
this.openCodeAuthRun = null;
|
|
16478
|
+
this.configuringOpenCode = false;
|
|
16479
|
+
term.note(code === 0 ? "OpenCode authentication command completed. Refresh connections; use auth list in OpenCode to verify the active account." : "OpenCode authentication did not complete. Refresh connections before retrying.");
|
|
16480
|
+
};
|
|
16481
|
+
if (catalog.scope === "box") {
|
|
16482
|
+
const api = this.cloud.boxApi();
|
|
16483
|
+
const boxId = await this.boxMachines.boxId(this.machineOf(a));
|
|
16484
|
+
if (!unchanged()) throw new HttpError(409, "Agent setup changed; reload connections.");
|
|
16485
|
+
if (!api || !boxId) throw new HttpError(409, "Cloud machine is not ready. No Box was created.");
|
|
16486
|
+
operation.run = this.backend.cloud.signIn({ api, boxId, cli: "opencode", term, agentId: id, authArgs: args }, end);
|
|
16487
|
+
} else {
|
|
16488
|
+
if (!this.backend.openCodeAuth) throw new HttpError(409, "OpenCode authentication is unavailable in this backend.");
|
|
16489
|
+
operation.run = this.backend.openCodeAuth({ args, term, agentId: id, cwd: a.role === "ceo" ? CEO_DIR : this.backend.mainDir(this.repo(a.repoId).fullName) }, end);
|
|
16490
|
+
}
|
|
16491
|
+
return { started: true };
|
|
16492
|
+
} catch (err) {
|
|
16493
|
+
if (this.openCodeAuthRun === operation) {
|
|
16494
|
+
this.openCodeAuthRun = null;
|
|
16495
|
+
this.configuringOpenCode = false;
|
|
16496
|
+
}
|
|
16497
|
+
throw err;
|
|
16498
|
+
}
|
|
16499
|
+
}
|
|
16500
|
+
cancelOpenCodeConfiguration(id) {
|
|
16501
|
+
if (this.openCodeAuthRun?.agentId !== id) throw new HttpError(409, "No OpenCode authentication is running for this agent.");
|
|
16502
|
+
this.openCodeAuthRun.run?.stop();
|
|
16503
|
+
this.openCodeAuthRun = null;
|
|
16504
|
+
this.configuringOpenCode = false;
|
|
16505
|
+
return { stopped: true };
|
|
16506
|
+
}
|
|
15863
16507
|
openCodeModels(agentId, repoId2, refresh = false) {
|
|
15864
16508
|
let directory = process.cwd();
|
|
15865
16509
|
if (agentId) {
|
|
15866
16510
|
const a = this.agent(agentId);
|
|
16511
|
+
if (a.host === "box" && a.role !== "ceo") {
|
|
16512
|
+
const machine = this.machineOf(a);
|
|
16513
|
+
return this.boxMachines.openCodeModels(machine, this.boxMachines.deskDir(machine, this.repo(a.repoId).fullName));
|
|
16514
|
+
}
|
|
15867
16515
|
if (a.role === "ceo") {
|
|
15868
|
-
return
|
|
16516
|
+
return fs22.mkdir(CEO_DIR, { recursive: true }).then(() => this.backend.openCodeModels(CEO_DIR, refresh));
|
|
15869
16517
|
}
|
|
15870
16518
|
directory = this.backend.mainDir(this.repo(a.repoId).fullName);
|
|
15871
16519
|
} else if (repoId2) directory = this.backend.mainDir(this.repo(repoId2).fullName);
|
|
@@ -15891,7 +16539,7 @@ var Swarm = class {
|
|
|
15891
16539
|
color: FLOOR_COLORS[(floor - 1) % FLOOR_COLORS.length],
|
|
15892
16540
|
autoAssign: !!opts.autoAssign,
|
|
15893
16541
|
autoMerge: opts.autoMerge !== false,
|
|
15894
|
-
browserTesting:
|
|
16542
|
+
browserTesting: opts.browserTesting !== false,
|
|
15895
16543
|
links: [],
|
|
15896
16544
|
localPath: folder2,
|
|
15897
16545
|
mission: (opts.mission ?? "").trim().slice(0, 4e3),
|
|
@@ -15924,7 +16572,7 @@ var Swarm = class {
|
|
|
15924
16572
|
const name = fullName.split("/")[1];
|
|
15925
16573
|
const taken = folders.find((f) => f.name.toLowerCase() === name.toLowerCase());
|
|
15926
16574
|
if (taken) throw new HttpError(409, `${taken.path} already exists and isn't a clone of ${fullName}. Connect that folder instead, or rename it first.`);
|
|
15927
|
-
return
|
|
16575
|
+
return path22.join(root, name);
|
|
15928
16576
|
}
|
|
15929
16577
|
/** A brand-new project: a folder in your projects folder, pushed to a new GitHub repo. */
|
|
15930
16578
|
async createRepo(name, opts) {
|
|
@@ -15936,11 +16584,11 @@ var Swarm = class {
|
|
|
15936
16584
|
}
|
|
15937
16585
|
/** The folders in your projects folder (or another folder you point at), and which are floors already. */
|
|
15938
16586
|
async listProjectFolders(dir) {
|
|
15939
|
-
const root = dir?.trim() ?
|
|
16587
|
+
const root = dir?.trim() ? path22.resolve(dir.trim()) : this.state.settings.projectsDir;
|
|
15940
16588
|
const folders = await this.backend.scanProjects(root).catch((err) => {
|
|
15941
16589
|
throw new HttpError(400, err.message);
|
|
15942
16590
|
});
|
|
15943
|
-
const same3 = (a, b) =>
|
|
16591
|
+
const same3 = (a, b) => path22.resolve(a).toLowerCase() === path22.resolve(b).toLowerCase();
|
|
15944
16592
|
const floorOf2 = (f) => this.state.repos.find((r) => r.localPath && same3(r.localPath, f.path) || f.github && r.id.toLowerCase() === f.github.toLowerCase())?.floor ?? null;
|
|
15945
16593
|
return { root, folders: folders.map((f) => ({ name: f.name, path: f.path, git: f.git, github: f.github, floor: floorOf2(f) })) };
|
|
15946
16594
|
}
|
|
@@ -16160,7 +16808,7 @@ var Swarm = class {
|
|
|
16160
16808
|
rt.folderSync = status;
|
|
16161
16809
|
this.emitRepo(repo);
|
|
16162
16810
|
if (status && status !== before) {
|
|
16163
|
-
const name = repo.localPath ?
|
|
16811
|
+
const name = repo.localPath ? path22.basename(repo.localPath) : repo.fullName;
|
|
16164
16812
|
if (status.startsWith("updated")) this.toast("success", `\u{1F4C1} ${name}: ${status}`);
|
|
16165
16813
|
else if (/behind|diverged|failed/.test(status)) this.toast("info", `\u{1F4C1} ${name} wasn't updated: ${status}`);
|
|
16166
16814
|
}
|
|
@@ -16186,7 +16834,7 @@ var Swarm = class {
|
|
|
16186
16834
|
const r = await this.backend.sweepDesks(repo.fullName, keep);
|
|
16187
16835
|
for (const a of agents) if (a.machine) r.branches += await this.machinesFor(a).sweep(a.machine, repo.fullName, keep.branches).catch(() => 0);
|
|
16188
16836
|
const desks = r.desks + r.folders;
|
|
16189
|
-
const saved = r.patches.length ? ` (${r.patches.length} patch${r.patches.length === 1 ? "" : "es"} saved to ${
|
|
16837
|
+
const saved = r.patches.length ? ` (${r.patches.length} patch${r.patches.length === 1 ? "" : "es"} saved to ${path22.dirname(r.patches[0])})` : "";
|
|
16190
16838
|
console.log(`desk sweep ${repo.fullName}: ${desks} desks, ${r.branches} branches removed${saved}${r.skipped.length ? `, ${r.skipped.length} still in use` : ""}`);
|
|
16191
16839
|
if (!desks && !r.branches) return;
|
|
16192
16840
|
const removed = [desks && `${desks} old desk${desks === 1 ? "" : "s"}`, r.branches && `${r.branches} finished branch${r.branches === 1 ? "" : "es"}`].filter(Boolean).join(" and ");
|
|
@@ -16245,6 +16893,7 @@ var Swarm = class {
|
|
|
16245
16893
|
return this.shutdownTask;
|
|
16246
16894
|
}
|
|
16247
16895
|
async finishShutdown(restart) {
|
|
16896
|
+
if (this.openCodeAuthRun) this.cancelOpenCodeConfiguration(this.openCodeAuthRun.agentId);
|
|
16248
16897
|
this.backend.cloud.detach();
|
|
16249
16898
|
await this.writeState().catch((err) => console.warn("could not save the state", err));
|
|
16250
16899
|
try {
|
|
@@ -16596,13 +17245,13 @@ var Swarm = class {
|
|
|
16596
17245
|
// ---------- cloud agents (docs/cloud.md) ----------
|
|
16597
17246
|
/**
|
|
16598
17247
|
* Where a new (or moving) agent works: what was asked, else the office default. A cloud agent needs the Upstash key,
|
|
16599
|
-
* room under the plan's Box limit and a CLI
|
|
17248
|
+
* room under the plan's Box limit and a supported CLI (Claude Code, Codex or OpenCode). `strict`: the manager asked for the
|
|
16600
17249
|
* cloud, so say why not; otherwise (a floor's first agent, the demo) they work on this computer instead.
|
|
16601
17250
|
*/
|
|
16602
|
-
hostFor(asked,
|
|
17251
|
+
hostFor(asked, _cli, strict, moving) {
|
|
16603
17252
|
const want = asked === "box" || asked === "local" ? asked : this.state.settings.cloud.machineKind;
|
|
16604
17253
|
if (want === "local") return "local";
|
|
16605
|
-
const why2 = !this.cloud.boxApi() ? "Cloud agents need your Upstash Box API key first: Settings \u2192 Cloud agents." :
|
|
17254
|
+
const why2 = !this.cloud.boxApi() ? "Cloud agents need your Upstash Box API key first: Settings \u2192 Cloud agents." : !this.boxRoom(moving) ? `Your Upstash plan's Box limit (${this.state.settings.cloud.boxLimit}) is reached. Raise it in Settings \u2192 Cloud agents if your plan allows more, or delete Boxes you don't need.` : null;
|
|
16606
17255
|
if (!why2) return "box";
|
|
16607
17256
|
if (strict || asked === "box") throw new HttpError(409, why2);
|
|
16608
17257
|
return "local";
|
|
@@ -16642,6 +17291,7 @@ var Swarm = class {
|
|
|
16642
17291
|
a.boxCli = null;
|
|
16643
17292
|
this.dropSignIn(a.id);
|
|
16644
17293
|
delete a.needsSignIn;
|
|
17294
|
+
delete a.openCodeAuthRejected;
|
|
16645
17295
|
a.sessionId = null;
|
|
16646
17296
|
a.sessionCli = null;
|
|
16647
17297
|
for (const q of this.state.qa) if (q.devAgentId === a.id) q.devSessionId = null;
|
|
@@ -16660,19 +17310,32 @@ var Swarm = class {
|
|
|
16660
17310
|
const boxId = await this.boxMachines.ensure(machine, (text3) => this.appendLog(a, [{ kind: "system", text: `\u2601 ${text3}` }]));
|
|
16661
17311
|
const creds = await this.cloud.credentials(cli);
|
|
16662
17312
|
if (creds.missing.length) throw new Error(`Cloud agents can't sign in yet. Missing: ${creds.missing.join("; ")}.`);
|
|
16663
|
-
if (check && creds.ownLogin &&
|
|
17313
|
+
if (check && creds.ownLogin && !await this.boxSignedIn(a, cli)) throw new SignInNeeded(cli);
|
|
16664
17314
|
const browser = browserTesting ? await api.browser(boxId).catch(() => false) : false;
|
|
16665
|
-
|
|
17315
|
+
let token;
|
|
17316
|
+
return {
|
|
17317
|
+
api,
|
|
17318
|
+
boxId,
|
|
17319
|
+
env: creds.env,
|
|
17320
|
+
apiKeyHelper: creds.apiKeyHelper,
|
|
17321
|
+
browser,
|
|
17322
|
+
record: (rec) => {
|
|
17323
|
+
if (rec) token = rec.token;
|
|
17324
|
+
if (rec || token) this.boxCliRecord(a.id, rec, rec ? void 0 : token);
|
|
17325
|
+
},
|
|
17326
|
+
connection: (up) => this.boxMachines.connection(machine, up)
|
|
17327
|
+
};
|
|
16666
17328
|
}
|
|
16667
17329
|
/** A cloud agent's live CLI record changed: kept with them, so a restart picks the CLI up. Gone with no task: the Box can pause. */
|
|
16668
|
-
boxCliRecord(agentId, rec) {
|
|
17330
|
+
boxCliRecord(agentId, rec, expectedToken) {
|
|
16669
17331
|
const a = this.state.agents.find((x) => x.id === agentId);
|
|
16670
17332
|
if (!a) return;
|
|
17333
|
+
if (!rec && expectedToken && a.boxCli?.token !== expectedToken) return;
|
|
16671
17334
|
const was = a.boxCli;
|
|
16672
17335
|
a.boxCli = rec;
|
|
16673
17336
|
if (rec && was && was.token === rec.token && was.offset === rec.offset && was.busy === rec.busy && was.resumeId === rec.resumeId) return;
|
|
16674
17337
|
this.save();
|
|
16675
|
-
if (!rec && was
|
|
17338
|
+
if (!rec && was) this.pauseIdleBox(a);
|
|
16676
17339
|
}
|
|
16677
17340
|
/** A machine's Box changed state: its agent's card shows it. */
|
|
16678
17341
|
boxState(machine) {
|
|
@@ -16698,6 +17361,42 @@ var Swarm = class {
|
|
|
16698
17361
|
});
|
|
16699
17362
|
}
|
|
16700
17363
|
// ---------- signing cloud agents in (docs/cloud.md) ----------
|
|
17364
|
+
boxSignedIn(a, cli) {
|
|
17365
|
+
const machine = this.machineOf(a);
|
|
17366
|
+
return this.boxMachines.signedIn(machine, cli, this.boxMachines.deskDir(machine, this.repo(a.repoId).fullName), this.modelFor(a, cli));
|
|
17367
|
+
}
|
|
17368
|
+
/** Explicit post-auth check for a held-free OpenCode Box: metadata only, never provisions or releases a task. */
|
|
17369
|
+
async refreshOpenCodeSignIn(id) {
|
|
17370
|
+
const a = this.agent(id);
|
|
17371
|
+
if (a.host !== "box" || (a.cli || this.state.settings.defaultCli) !== "opencode" || BUSY3.includes(a.status) || this.signIns.get(id)?.held) throw new HttpError(409, "Stop held work before verifying this OpenCode connection.");
|
|
17372
|
+
const machine = this.machineOf(a);
|
|
17373
|
+
const ready2 = await this.boxMachines.openCodeConnectionReady(machine, this.boxMachines.deskDir(machine, this.repo(a.repoId).fullName), this.modelFor(a, "opencode"));
|
|
17374
|
+
if (!this.state.agents.includes(a) || a.host !== "box" || this.machineOf(a) !== machine) throw new HttpError(409, "Agent host changed during connection check.");
|
|
17375
|
+
if (ready2) {
|
|
17376
|
+
this.dropSignIn(id);
|
|
17377
|
+
a.needsSignIn = false;
|
|
17378
|
+
delete a.openCodeAuthRejected;
|
|
17379
|
+
this.emitAgent(a);
|
|
17380
|
+
this.save();
|
|
17381
|
+
}
|
|
17382
|
+
return ready2;
|
|
17383
|
+
}
|
|
17384
|
+
/** Detailed OAuth-only smoke-gate probe; never provisions a Box or releases held work. */
|
|
17385
|
+
async inspectOpenCodeSignIn(id) {
|
|
17386
|
+
const a = this.agent(id);
|
|
17387
|
+
if (a.host !== "box" || (a.cli || this.state.settings.defaultCli) !== "opencode" || BUSY3.includes(a.status) || this.signIns.get(id)?.held) throw new HttpError(409, "Stop held work before verifying this OpenCode connection.");
|
|
17388
|
+
const machine = this.machineOf(a);
|
|
17389
|
+
const result = await this.boxMachines.openCodeReadiness(machine, this.boxMachines.deskDir(machine, this.repo(a.repoId).fullName), this.modelFor(a, "opencode"));
|
|
17390
|
+
if (!this.state.agents.includes(a) || a.host !== "box" || this.machineOf(a) !== machine) throw new HttpError(409, "Agent host changed during connection check.");
|
|
17391
|
+
if (result.state === "ready") {
|
|
17392
|
+
this.dropSignIn(id);
|
|
17393
|
+
a.needsSignIn = false;
|
|
17394
|
+
delete a.openCodeAuthRejected;
|
|
17395
|
+
this.emitAgent(a);
|
|
17396
|
+
this.save();
|
|
17397
|
+
}
|
|
17398
|
+
return result;
|
|
17399
|
+
}
|
|
16701
17400
|
/**
|
|
16702
17401
|
* A cloud agent's CLI has no login in their Box (a new Box, or one that expired): they're marked as needing a sign-in
|
|
16703
17402
|
* and take no work, the task they were starting (if any) waits, and the CLI's own sign-in starts in their terminal.
|
|
@@ -16705,6 +17404,7 @@ var Swarm = class {
|
|
|
16705
17404
|
holdForSignIn(a, cli, task, expired2 = false) {
|
|
16706
17405
|
if (!this.state.agents.includes(a) || a.host !== "box") return;
|
|
16707
17406
|
const s2 = this.signInOf(a, cli);
|
|
17407
|
+
if (cli === "opencode" && expired2) a.openCodeAuthRejected = true;
|
|
16708
17408
|
const label = cliLabel(cli);
|
|
16709
17409
|
if (task) {
|
|
16710
17410
|
a.status = "preparing";
|
|
@@ -16743,6 +17443,7 @@ var Swarm = class {
|
|
|
16743
17443
|
}
|
|
16744
17444
|
/** Their sign-in goes (they left, moved to this computer): its CLI closes and a held task is dropped with it. */
|
|
16745
17445
|
dropSignIn(agentId) {
|
|
17446
|
+
if (this.openCodeAuthRun?.agentId === agentId && this.openCodeAuthRun.run) this.cancelOpenCodeConfiguration(agentId);
|
|
16746
17447
|
const s2 = this.signIns.get(agentId);
|
|
16747
17448
|
if (!s2) return;
|
|
16748
17449
|
this.signIns.delete(agentId);
|
|
@@ -16751,9 +17452,11 @@ var Swarm = class {
|
|
|
16751
17452
|
}
|
|
16752
17453
|
/** Start the CLI's own sign-in in their terminal, unless it's running already. */
|
|
16753
17454
|
async startSignIn(a) {
|
|
17455
|
+
if (this.backend.cloud.automaticSignIn === false) return;
|
|
17456
|
+
if (this.configuringOpenCode) return;
|
|
16754
17457
|
const cli = a.cli || this.state.settings.defaultCli;
|
|
16755
17458
|
const api = this.cloud.boxApi();
|
|
16756
|
-
if (!a.needsSignIn || a.host !== "box" ||
|
|
17459
|
+
if (!a.needsSignIn || a.host !== "box" || !api) return;
|
|
16757
17460
|
const s2 = this.signInOf(a, cli);
|
|
16758
17461
|
if (s2.run || s2.starting) return;
|
|
16759
17462
|
s2.starting = true;
|
|
@@ -16776,7 +17479,8 @@ var Swarm = class {
|
|
|
16776
17479
|
s2.poll = setTimeout(() => {
|
|
16777
17480
|
s2.poll = null;
|
|
16778
17481
|
if (this.signIns.get(a.id) !== s2 || !s2.run) return;
|
|
16779
|
-
|
|
17482
|
+
if (s2.cli === "opencode" && a.openCodeAuthRejected) return;
|
|
17483
|
+
void this.boxSignedIn(a, s2.cli).catch(() => null).then((ok) => {
|
|
16780
17484
|
if (this.signIns.get(a.id) !== s2) return;
|
|
16781
17485
|
if (ok) this.signedIn(a);
|
|
16782
17486
|
else if (s2.run) this.pollSignIn(a, s2);
|
|
@@ -16788,9 +17492,9 @@ var Swarm = class {
|
|
|
16788
17492
|
if (this.signIns.get(a.id) !== s2) return;
|
|
16789
17493
|
s2.run = null;
|
|
16790
17494
|
if (s2.poll) clearTimeout(s2.poll);
|
|
16791
|
-
const ok = await this.
|
|
17495
|
+
const ok = await this.boxSignedIn(a, s2.cli).catch(() => null);
|
|
16792
17496
|
if (this.signIns.get(a.id) !== s2 || s2.run) return;
|
|
16793
|
-
if (ok) return this.signedIn(a);
|
|
17497
|
+
if (ok && !(s2.cli === "opencode" && a.openCodeAuthRejected && code !== 0)) return this.signedIn(a);
|
|
16794
17498
|
this.agentRt.get(a.id)?.terminal?.note(`Not signed in yet. \u{1F511} Sign in starts it again.`);
|
|
16795
17499
|
this.appendLog(a, [{ kind: "error", text: `\u{1F511} ${cliLabel(s2.cli)} didn't finish signing in${code > 0 ? ` (it exited with code ${code})` : ""}. \u{1F511} Sign in in their terminal starts it again.` }]);
|
|
16796
17500
|
}
|
|
@@ -16803,6 +17507,7 @@ var Swarm = class {
|
|
|
16803
17507
|
if (run2) setTimeout(() => run2.stop(), 3e3);
|
|
16804
17508
|
if (!a.needsSignIn) return;
|
|
16805
17509
|
a.needsSignIn = false;
|
|
17510
|
+
delete a.openCodeAuthRejected;
|
|
16806
17511
|
this.appendLog(a, [{ kind: "done", text: `\u2714 ${cliLabel(s2?.cli ?? "claude")} is signed in in their cloud machine.${s2?.held ? " Back to the task." : ""}` }]);
|
|
16807
17512
|
this.emitAgent(a);
|
|
16808
17513
|
this.save();
|
|
@@ -16822,15 +17527,19 @@ var Swarm = class {
|
|
|
16822
17527
|
s2?.run?.stop();
|
|
16823
17528
|
if (s2) s2.run = null;
|
|
16824
17529
|
}
|
|
16825
|
-
if (cli === "opencode"
|
|
17530
|
+
if (cli === "opencode" && a.openCodeAuthRejected) {
|
|
17531
|
+
this.holdForSignIn(a, cli, null, true);
|
|
17532
|
+
return;
|
|
17533
|
+
}
|
|
16826
17534
|
const creds = await this.cloud.credentials(cli).catch(() => null);
|
|
16827
|
-
const ok = !creds ? null : creds.ownLogin ? await this.
|
|
17535
|
+
const ok = !creds ? null : creds.ownLogin ? await this.boxSignedIn(a, cli).catch(() => null) : true;
|
|
16828
17536
|
if (!this.state.agents.includes(a) || a.host !== "box") return;
|
|
16829
17537
|
if (ok === true) this.signedIn(a);
|
|
16830
17538
|
else if (ok === false) this.holdForSignIn(a, cli, null);
|
|
16831
17539
|
}
|
|
16832
17540
|
/** POST /api/agents/:id/sign-in: start a cloud agent's sign-in (over) in their terminal: it ended, went stale or never started. */
|
|
16833
17541
|
signIn(id) {
|
|
17542
|
+
if (this.configuringOpenCode) throw new HttpError(409, "Finish OpenCode authentication in the terminal first.");
|
|
16834
17543
|
const a = this.agent(id);
|
|
16835
17544
|
if (a.host !== "box") throw new HttpError(409, `${a.name} works on this computer: their coding agent signs in there.`);
|
|
16836
17545
|
if (!a.needsSignIn) throw new HttpError(409, `${a.name}'s coding agent is signed in already.`);
|
|
@@ -16874,13 +17583,13 @@ var Swarm = class {
|
|
|
16874
17583
|
return !this.clis.length || this.clis.some((c) => c.id === cli && c.installed);
|
|
16875
17584
|
}
|
|
16876
17585
|
updateAgent(id, patch) {
|
|
17586
|
+
if (this.openCodeAuthRun?.agentId === id && (patch.host !== void 0 || patch.cli !== void 0)) throw new HttpError(409, "Finish or stop OpenCode authentication before changing the host or coding agent.");
|
|
16877
17587
|
const a = this.agent(id);
|
|
16878
17588
|
if (patch.host !== void 0 && a.role !== "ceo" && (patch.host === "box" || patch.host === "local")) this.moveAgent(a, patch.host);
|
|
16879
17589
|
if (patch.cli !== void 0) {
|
|
16880
17590
|
const cli = isCli(patch.cli) ? patch.cli : "";
|
|
16881
17591
|
if (a.role === "ceo" && cli && cli !== "claude" && cli !== "opencode") throw new HttpError(400, "The CEO can run Claude Code or OpenCode.");
|
|
16882
|
-
|
|
16883
|
-
const localCli = cli || (a.role === "ceo" ? "claude" : this.state.settings.defaultCli);
|
|
17592
|
+
const localCli = cli || (a.role === "ceo" ? DEFAULT_CEO_CLI : this.state.settings.defaultCli);
|
|
16884
17593
|
if (a.host !== "box" && (cli || localCli === "opencode") && !this.cliReady(localCli)) throw new HttpError(400, `${cliLabel(localCli)} isn't installed on this computer.`);
|
|
16885
17594
|
const changed = cli !== a.cli;
|
|
16886
17595
|
a.cli = cli;
|
|
@@ -16919,7 +17628,7 @@ var Swarm = class {
|
|
|
16919
17628
|
this.agentRt.get(id)?.terminal?.releaseIdle?.();
|
|
16920
17629
|
this.agentRt.get(id)?.terminal?.dispose();
|
|
16921
17630
|
void removeScreens(id);
|
|
16922
|
-
void
|
|
17631
|
+
void fs22.rm(terminalFile(id), { force: true }).catch(() => void 0);
|
|
16923
17632
|
for (const q of this.state.qa) {
|
|
16924
17633
|
if (q.qaAgentId === id && q.status === "testing") this.setQa(q, { status: "queued", qaAgentId: null });
|
|
16925
17634
|
if (q.devAgentId === id) q.devAgentId = null;
|
|
@@ -16988,11 +17697,13 @@ var Swarm = class {
|
|
|
16988
17697
|
);
|
|
16989
17698
|
}
|
|
16990
17699
|
ensureSlot() {
|
|
17700
|
+
if (this.configuringOpenCode) throw new HttpError(409, "Finish OpenCode authentication in the terminal first.");
|
|
16991
17701
|
if (this.slotsFull()) {
|
|
16992
17702
|
throw new HttpError(429, `All ${this.state.settings.sessionLimit} session slots are busy. Raise or clear the session limit in the manager's console, or wait.`);
|
|
16993
17703
|
}
|
|
16994
17704
|
}
|
|
16995
17705
|
ensureUsage(a, kind) {
|
|
17706
|
+
if (this.cloudWorkPaused(a)) throw new HttpError(409, "New cloud work is paused in Settings \u2192 Cloud agents. Running sessions and Box costs are not stopped.");
|
|
16996
17707
|
if (this.quotaWaiting.has(a.id)) throw new HttpError(409, "This agent has work waiting for a quota reset. Clear the desk to replace it.");
|
|
16997
17708
|
if (!this.mayStart(kind, a)) throw new HttpError(429, "This AI quota is paused or pacing. See AI usage for the affected resource and reset time.");
|
|
16998
17709
|
}
|
|
@@ -17065,7 +17776,7 @@ var Swarm = class {
|
|
|
17065
17776
|
*/
|
|
17066
17777
|
sessionRuntime(a, resume) {
|
|
17067
17778
|
const inTerminal2 = a.host === "box" || this.state.settings.runtime === "terminal" && this.backend.terminals;
|
|
17068
|
-
let cli = !inTerminal2 ? "claude" : a.cli || (a.role === "ceo" ?
|
|
17779
|
+
let cli = !inTerminal2 ? "claude" : a.cli || (a.role === "ceo" ? DEFAULT_CEO_CLI : this.state.settings.defaultCli);
|
|
17069
17780
|
if (resume && a.sessionCli && a.sessionCli !== cli) {
|
|
17070
17781
|
if (a.role === "ceo") resume = void 0;
|
|
17071
17782
|
else if (inTerminal2) cli = a.sessionCli;
|
|
@@ -17082,7 +17793,7 @@ var Swarm = class {
|
|
|
17082
17793
|
}
|
|
17083
17794
|
// ---------- terminals ----------
|
|
17084
17795
|
async loadTerminal(agentId) {
|
|
17085
|
-
if (!await
|
|
17796
|
+
if (!await fs22.stat(terminalFile(agentId)).catch(() => null)) return null;
|
|
17086
17797
|
const t = this.newTerminal(agentId);
|
|
17087
17798
|
await t.load(terminalFile(agentId));
|
|
17088
17799
|
return t;
|
|
@@ -17269,6 +17980,7 @@ var Swarm = class {
|
|
|
17269
17980
|
}
|
|
17270
17981
|
}
|
|
17271
17982
|
async runTask(a, repo, issue2, note2) {
|
|
17983
|
+
if (this.cloudWorkPaused(a)) return;
|
|
17272
17984
|
const branch = devBranch(issue2.number, slugify(a.name));
|
|
17273
17985
|
this.beginTask(
|
|
17274
17986
|
a,
|
|
@@ -17302,6 +18014,10 @@ Note from the manager: ${note2}` : ""
|
|
|
17302
18014
|
startAgentSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode = null) {
|
|
17303
18015
|
const rt = this.agentRt.get(a.id);
|
|
17304
18016
|
if (!rt || !this.state.agents.includes(a)) return;
|
|
18017
|
+
if (!mode && this.cloudWorkPaused(a)) {
|
|
18018
|
+
this.waitForCloudResume(a, () => this.startAgentSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode));
|
|
18019
|
+
return;
|
|
18020
|
+
}
|
|
17305
18021
|
if (a.host === "box" && mode !== "reattach") {
|
|
17306
18022
|
const cli = this.sessionRuntime(a, resumeSessionId).cli ?? "claude";
|
|
17307
18023
|
const note2 = (text3) => this.appendLog(a, [{ kind: "system", text: text3 }]);
|
|
@@ -17321,6 +18037,10 @@ Note from the manager: ${note2}` : ""
|
|
|
17321
18037
|
launchSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode, box, linked) {
|
|
17322
18038
|
const rt = this.agentRt.get(a.id);
|
|
17323
18039
|
if (!rt || !this.state.agents.includes(a)) return;
|
|
18040
|
+
if (!mode && this.cloudWorkPaused(a)) {
|
|
18041
|
+
this.waitForCloudResume(a, () => this.launchSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode, box, linked));
|
|
18042
|
+
return;
|
|
18043
|
+
}
|
|
17324
18044
|
if (a.host !== "box" && sessionStart(this.backend.deskExists(cwd), mode) === "prepare") {
|
|
17325
18045
|
if (a.task === "analysis") {
|
|
17326
18046
|
this.fail(a, { ok: false, text: "", costUsd: 0, turns: 0, errors: ["The analysis checkout is missing. No worktree or dependencies were created."] }, "analysis");
|
|
@@ -17394,7 +18114,7 @@ Note from the manager: ${note2}` : ""
|
|
|
17394
18114
|
rt.shots.push({ data, mime, url: rt.browserUrl, at });
|
|
17395
18115
|
if (rt.shots.length > 12) rt.shots.shift();
|
|
17396
18116
|
this.broadcast({ type: "screen", agentId: a.id, url: rt.browserUrl, at });
|
|
17397
|
-
void removeScreens(a.id).then(() =>
|
|
18117
|
+
void removeScreens(a.id).then(() => fs22.mkdir(SCREENS_DIR, { recursive: true })).then(() => fs22.writeFile(screenFile(a.id, mime), data)).catch((err) => console.warn("could not save screenshot", err));
|
|
17398
18118
|
},
|
|
17399
18119
|
usage: (observation) => this.recordAiUsage(a, observation),
|
|
17400
18120
|
usageBatch: (observations) => this.recordAiUsageBatch(a, observations),
|
|
@@ -17414,8 +18134,8 @@ Note from the manager: ${note2}` : ""
|
|
|
17414
18134
|
async signedOutMidTask(a, repo, result, cli, again) {
|
|
17415
18135
|
const rt = this.agentRt.get(a.id);
|
|
17416
18136
|
if (!rt || !this.state.agents.includes(a)) return;
|
|
17417
|
-
const creds =
|
|
17418
|
-
if (
|
|
18137
|
+
const creds = await this.cloud.credentials(cli).catch(() => null);
|
|
18138
|
+
if (!creds?.ownLogin || a.status === "stopped" || this.dropping.has(a.id) || a.host !== "box") {
|
|
17419
18139
|
const errors = creds && !creds.ownLogin ? [`${cliLabel(cli)} turned the key it was given away: check it in Settings \u2192 Cloud agents.`] : result.errors;
|
|
17420
18140
|
return this.onFinished(a, repo, { ...result, errors });
|
|
17421
18141
|
}
|
|
@@ -17429,6 +18149,17 @@ Note from the manager: ${note2}` : ""
|
|
|
17429
18149
|
this.holdForSignIn(a, cli, again, true);
|
|
17430
18150
|
}
|
|
17431
18151
|
async onFinished(a, repo, result) {
|
|
18152
|
+
this.finishingAgents.set(a.id, (this.finishingAgents.get(a.id) ?? 0) + 1);
|
|
18153
|
+
try {
|
|
18154
|
+
await this.finishAgentSession(a, repo, result);
|
|
18155
|
+
} finally {
|
|
18156
|
+
const remaining = this.finishingAgents.get(a.id) - 1;
|
|
18157
|
+
if (remaining) this.finishingAgents.set(a.id, remaining);
|
|
18158
|
+
else this.finishingAgents.delete(a.id);
|
|
18159
|
+
this.pauseIdleBox(a);
|
|
18160
|
+
}
|
|
18161
|
+
}
|
|
18162
|
+
async finishAgentSession(a, repo, result) {
|
|
17432
18163
|
const rt = this.agentRt.get(a.id);
|
|
17433
18164
|
if (!rt || !this.state.agents.includes(a)) return;
|
|
17434
18165
|
if (this.officeUpdate.handedOver && a.host !== "box") return;
|
|
@@ -17440,7 +18171,8 @@ Note from the manager: ${note2}` : ""
|
|
|
17440
18171
|
a.turns += result.turns;
|
|
17441
18172
|
recordCost(this.state.ops, repo.id, result.costUsd, a.endedAt);
|
|
17442
18173
|
this.ledger({ kind: "session", agentId: a.id, key: `${a.id}:${a.startedAt}:${a.endedAt}`, costUsd: result.costUsd, turns: result.turns }, false);
|
|
17443
|
-
|
|
18174
|
+
const released = this.releaseDesk(a, repo).catch(() => void 0);
|
|
18175
|
+
if (a.host === "box") await released;
|
|
17444
18176
|
if (result.interrupted) this.interrupted(a);
|
|
17445
18177
|
if (this.dropping.has(a.id)) this.dropTask(a, "\u21BA Cleared desk. Ready for new work.");
|
|
17446
18178
|
else if (a.task === "analysis") {
|
|
@@ -17618,6 +18350,8 @@ Note from the manager: ${note2}` : ""
|
|
|
17618
18350
|
return qaSystemPrompt({ agent: a, repo, port: this.port(a), cwd, branch, pr, testStep: testStep2, depsLine: depsPromptLine(deps) });
|
|
17619
18351
|
}
|
|
17620
18352
|
async runQa(a, repo, rec) {
|
|
18353
|
+
if (this.cloudWorkPaused(a)) return;
|
|
18354
|
+
if (this.backend.allowWork && !this.backend.allowWork("qa", a)) return;
|
|
17621
18355
|
const branch = qaBranch(rec.prNumber, slugify(a.name));
|
|
17622
18356
|
this.qaWaits.set(`${repo.id}#${rec.prNumber}`, Date.now() - rec.updatedAt);
|
|
17623
18357
|
this.setQa(rec, { status: "testing", qaAgentId: a.id });
|
|
@@ -17838,6 +18572,8 @@ ${issue2.body.trim() || "(no description)"}` : ""
|
|
|
17838
18572
|
}
|
|
17839
18573
|
/** Send a failed PR back to the agent who wrote it (or any free agent on the floor). */
|
|
17840
18574
|
async runFix(dev, repo, rec) {
|
|
18575
|
+
if (this.cloudWorkPaused(dev)) return;
|
|
18576
|
+
if (this.backend.allowWork && !this.backend.allowWork("fix", dev)) return;
|
|
17841
18577
|
const original = rec.devAgentId === dev.id;
|
|
17842
18578
|
const pull = this.repoRt.get(repo.id)?.pulls.find((p) => p.number === rec.prNumber);
|
|
17843
18579
|
const headRef = pull?.headRefName ?? dev.branch ?? `pr-${rec.prNumber}`;
|
|
@@ -18041,7 +18777,7 @@ ${text3}` : text3);
|
|
|
18041
18777
|
if (typeof patch.managerName === "string") s2.managerName = patch.managerName.trim().slice(0, 40);
|
|
18042
18778
|
if (typeof patch.companyName === "string") s2.companyName = patch.companyName.trim().slice(0, 60);
|
|
18043
18779
|
if (typeof patch.dogName === "string") s2.dogName = patch.dogName.trim().slice(0, 24) || DEFAULT_DOG_NAME;
|
|
18044
|
-
if (typeof patch.projectsDir === "string" && patch.projectsDir.trim()) s2.projectsDir =
|
|
18780
|
+
if (typeof patch.projectsDir === "string" && patch.projectsDir.trim()) s2.projectsDir = path22.resolve(patch.projectsDir.trim());
|
|
18045
18781
|
if (typeof patch.setupDone === "boolean") s2.setupDone = patch.setupDone;
|
|
18046
18782
|
if (patch.tutorialStep !== void 0) s2.tutorialStep = Math.max(-1, Math.round(Number(patch.tutorialStep)) || 0);
|
|
18047
18783
|
if (typeof patch.autoUpdate === "boolean") s2.autoUpdate = patch.autoUpdate;
|
|
@@ -18143,20 +18879,24 @@ ${text3}` : text3);
|
|
|
18143
18879
|
).sort((x, y) => x.updatedAt - y.updatedAt);
|
|
18144
18880
|
const fixes = waiting("failed", "fix");
|
|
18145
18881
|
const owed = new Set(fixes.map((q) => q.devAgentId).filter((id) => !!id));
|
|
18882
|
+
const qaFree = free.filter((a) => this.mayStart("qa", a));
|
|
18146
18883
|
for (const rec of waiting("queued", "qa")) {
|
|
18147
18884
|
const othersCan = this.state.agents.some((a) => a.repoId === repo.id && a.role !== "ceo" && a.id !== rec.devAgentId && a.status !== "stopped");
|
|
18148
|
-
const tester = pickTester(
|
|
18885
|
+
const tester = pickTester(qaFree, rec.devAgentId, owed, othersCan, now2 - rec.updatedAt);
|
|
18149
18886
|
if (!tester) continue;
|
|
18150
18887
|
void this.runQa(tester, repo, rec);
|
|
18151
18888
|
return true;
|
|
18152
18889
|
}
|
|
18890
|
+
const fixFree = free.filter((a) => this.mayStart("fix", a));
|
|
18153
18891
|
for (const rec of fixes) {
|
|
18892
|
+
if (!fixFree.length) continue;
|
|
18154
18893
|
const author = this.state.agents.find((a) => a.id === rec.devAgentId && a.repoId === repo.id && a.role !== "ceo") ?? null;
|
|
18155
18894
|
if (author && this.limited(author)) continue;
|
|
18895
|
+
if (author && !this.mayStart("fix", author)) continue;
|
|
18156
18896
|
const headRef = this.repoRt.get(repo.id).pulls.find((p) => p.number === rec.prNumber)?.headRefName ?? null;
|
|
18157
|
-
const to = fixGoesTo(author, !!author &&
|
|
18897
|
+
const to = fixGoesTo(author, !!author && fixFree.includes(author), rec.prNumber, headRef);
|
|
18158
18898
|
if (to === "wait") continue;
|
|
18159
|
-
void this.runFix(to === "author" ? author :
|
|
18899
|
+
void this.runFix(to === "author" ? author : fixFree.find((a) => !owed.has(a.id)) ?? fixFree[0], repo, rec);
|
|
18160
18900
|
return true;
|
|
18161
18901
|
}
|
|
18162
18902
|
return false;
|
|
@@ -18177,7 +18917,7 @@ ${text3}` : text3);
|
|
|
18177
18917
|
return new QuotaGate(this.state.aiQuotas ??= {});
|
|
18178
18918
|
}
|
|
18179
18919
|
usageTool(a) {
|
|
18180
|
-
return a.host === "box" || this.state.settings.runtime === "terminal" && this.backend.terminals ? a.cli || (a.role === "ceo" ?
|
|
18920
|
+
return a.host === "box" || this.state.settings.runtime === "terminal" && this.backend.terminals ? a.cli || (a.role === "ceo" ? DEFAULT_CEO_CLI : this.state.settings.defaultCli) : "claude";
|
|
18181
18921
|
}
|
|
18182
18922
|
resourceFor(a, tool2 = this.usageTool(a)) {
|
|
18183
18923
|
const model2 = this.modelFor(a, tool2);
|
|
@@ -18268,8 +19008,21 @@ ${text3}` : text3);
|
|
|
18268
19008
|
}
|
|
18269
19009
|
return this.usageNow();
|
|
18270
19010
|
}
|
|
18271
|
-
|
|
19011
|
+
cloudWorkPaused(a) {
|
|
19012
|
+
return a.role !== "ceo" && a.host === "box" && this.state.settings.cloud?.pauseNewWork === true;
|
|
19013
|
+
}
|
|
19014
|
+
waitForCloudResume(a, start) {
|
|
19015
|
+
this.quotaWaiting.set(a.id, start);
|
|
19016
|
+
a.status = "stopped";
|
|
19017
|
+
a.lastError = "New cloud work is paused in Settings \u2192 Cloud agents";
|
|
19018
|
+
this.emitAgent(a);
|
|
19019
|
+
this.save();
|
|
19020
|
+
}
|
|
19021
|
+
/** May work of this kind start now, as far as resource controls and AI usage go? */
|
|
18272
19022
|
mayStart(kind, a) {
|
|
19023
|
+
if (this.cloudWorkPaused(a)) return false;
|
|
19024
|
+
if (this.backend.allowWork && !this.backend.allowWork(kind, a)) return false;
|
|
19025
|
+
if (this.configuringOpenCode) return false;
|
|
18273
19026
|
const key = this.gateKey(a);
|
|
18274
19027
|
const running = this.state.agents.filter((other) => BUSY3.includes(other.status) && this.gateKey(other) === key).length;
|
|
18275
19028
|
return this.quotaGate().allows(key, kind, Date.now(), running, this.state.settings.pacingSessions);
|
|
@@ -18396,7 +19149,7 @@ ${text3}` : text3);
|
|
|
18396
19149
|
this.quotaWaiting.delete(id);
|
|
18397
19150
|
continue;
|
|
18398
19151
|
}
|
|
18399
|
-
if (!this.slotsFull() && !this.limited(a)) {
|
|
19152
|
+
if (!this.cloudWorkPaused(a) && !this.slotsFull() && !this.limited(a)) {
|
|
18400
19153
|
this.quotaWaiting.delete(id);
|
|
18401
19154
|
start();
|
|
18402
19155
|
}
|
|
@@ -18548,7 +19301,7 @@ ${text3}` : text3);
|
|
|
18548
19301
|
return this.state.agents.find((a) => a.id === CEO_ID);
|
|
18549
19302
|
}
|
|
18550
19303
|
/** The company always has a CEO. One cut off by a server restart picks its job back up. */
|
|
18551
|
-
ensureCeo(interrupted) {
|
|
19304
|
+
ensureCeo(interrupted, cli = DEFAULT_CEO_CLI) {
|
|
18552
19305
|
let a = this.state.agents.find((x) => x.id === CEO_ID);
|
|
18553
19306
|
if (!a) {
|
|
18554
19307
|
a = {
|
|
@@ -18563,9 +19316,9 @@ ${text3}` : text3);
|
|
|
18563
19316
|
hair: "#2b2118",
|
|
18564
19317
|
skin: pick(SKIN),
|
|
18565
19318
|
style: null,
|
|
18566
|
-
model: CEO_MODEL,
|
|
19319
|
+
model: cli === "claude" ? CEO_MODEL : "",
|
|
18567
19320
|
effort: CEO_EFFORT,
|
|
18568
|
-
cli
|
|
19321
|
+
cli,
|
|
18569
19322
|
machine: null,
|
|
18570
19323
|
status: "idle",
|
|
18571
19324
|
issueNumber: null,
|
|
@@ -18662,7 +19415,7 @@ ${job.text}` } : job;
|
|
|
18662
19415
|
}
|
|
18663
19416
|
ceoPromptInput(a) {
|
|
18664
19417
|
const s2 = this.state.settings;
|
|
18665
|
-
return { name: a.name, company: s2.companyName, manager: s2.managerName, notesFile:
|
|
19418
|
+
return { name: a.name, company: s2.companyName, manager: s2.managerName, notesFile: path22.join(CEO_DIR, "NOTES.md"), sessionLimit: s2.sessionLimit, maxAgents: s2.maxAgents, scaling: s2.scaling, cli: s2.runtime === "terminal" && this.backend.terminals ? a.cli || DEFAULT_CEO_CLI : "claude", language: languageOf(s2.language) };
|
|
18666
19419
|
}
|
|
18667
19420
|
async runCeoJob(a, job) {
|
|
18668
19421
|
const rt = this.agentRt.get(a.id);
|
|
@@ -18684,7 +19437,7 @@ ${job.text}` } : job;
|
|
|
18684
19437
|
this.emitAgent(a);
|
|
18685
19438
|
this.emitCeo();
|
|
18686
19439
|
this.save();
|
|
18687
|
-
await
|
|
19440
|
+
await fs22.mkdir(CEO_DIR, { recursive: true }).catch(() => void 0);
|
|
18688
19441
|
const triage2 = job.kind === "triage" ? await this.triagePr(job) : null;
|
|
18689
19442
|
if (a.status !== "working") {
|
|
18690
19443
|
this.state.ceo.job = null;
|
|
@@ -18713,6 +19466,7 @@ ${job.text}` } : job;
|
|
|
18713
19466
|
browserTesting: false,
|
|
18714
19467
|
additionalDirectories: this.state.repos.filter((r) => this.repoRt.get(r.id)?.cloneStatus === "ready").map((r) => this.backend.mainDir(r.fullName)),
|
|
18715
19468
|
role: "ceo",
|
|
19469
|
+
agentId: a.id,
|
|
18716
19470
|
office: this.officeTools(),
|
|
18717
19471
|
...how
|
|
18718
19472
|
},
|
|
@@ -19628,7 +20382,7 @@ ${t}`);
|
|
|
19628
20382
|
agentSetup(a) {
|
|
19629
20383
|
const ceo = a.role === "ceo";
|
|
19630
20384
|
const terminal = a.host === "box" || this.state.settings.runtime === "terminal" && this.backend.terminals;
|
|
19631
|
-
const cli = terminal ? a.cli || (ceo ?
|
|
20385
|
+
const cli = terminal ? a.cli || (ceo ? DEFAULT_CEO_CLI : this.state.settings.defaultCli) : "claude";
|
|
19632
20386
|
return {
|
|
19633
20387
|
codingAgent: cli,
|
|
19634
20388
|
model: this.modelFor(a, cli) || "the coding agent default",
|
|
@@ -19951,6 +20705,9 @@ app.post("/api/agents/:id/analyze", route((req) => swarm.analyze(String(req.para
|
|
|
19951
20705
|
app.post("/api/agents/:id/reset", route((req) => swarm.resetAgent(String(req.params.id))));
|
|
19952
20706
|
app.post("/api/agents/:id/message", route((req) => swarm.message(String(req.params.id), str(req.body.text))));
|
|
19953
20707
|
app.post("/api/agents/:id/sign-in", route((req) => swarm.signIn(String(req.params.id))));
|
|
20708
|
+
app.get("/api/agents/:id/opencode/connections", route((req) => swarm.openCodeConnections(String(req.params.id))));
|
|
20709
|
+
app.post("/api/agents/:id/opencode/connections", route((req) => swarm.configureOpenCode(String(req.params.id), req.body?.selection, req.body?.scope)));
|
|
20710
|
+
app.delete("/api/agents/:id/opencode/connections", route((req) => swarm.cancelOpenCodeConfiguration(String(req.params.id))));
|
|
19954
20711
|
app.get("/api/agents/:id/prompt", route((req) => swarm.agentPrompt(String(req.params.id))));
|
|
19955
20712
|
app.get("/api/agents/:id/screen", (req, res) => {
|
|
19956
20713
|
const shot = swarm.screenshot(String(req.params.id));
|
|
@@ -20058,16 +20815,16 @@ app.post("/api/repos/:repo/decor/buy", route((req) => swarm.buyDecoration(repoId
|
|
|
20058
20815
|
app.post("/api/repos/:repo/decor/place", route((req) => swarm.placeDecoration(repoId(req), req.body ?? {})));
|
|
20059
20816
|
app.post("/api/progress/coffee", route((req) => swarm.drankCoffee(req.body?.id)));
|
|
20060
20817
|
app.post("/api/progress/demo", route((req) => swarm.demoProgress(req.body ?? {})));
|
|
20061
|
-
var dist =
|
|
20062
|
-
if (
|
|
20818
|
+
var dist = path23.resolve(import.meta.dirname, "../dist");
|
|
20819
|
+
if (fs23.existsSync(dist)) {
|
|
20063
20820
|
app.get("/sw.js", (_req, res) => {
|
|
20064
|
-
const html =
|
|
20821
|
+
const html = fs23.readFileSync(path23.join(dist, "index.html"), "utf8");
|
|
20065
20822
|
res.setHeader("Content-Type", "text/javascript; charset=utf-8");
|
|
20066
20823
|
res.setHeader("Cache-Control", "no-cache");
|
|
20067
20824
|
res.end(serviceWorkerSource(swVersion(html, VERSION, swarm.officeCommit())));
|
|
20068
20825
|
});
|
|
20069
20826
|
app.use(express.static(dist));
|
|
20070
|
-
app.get(/^(?!\/api).*/, (_req, res) => res.sendFile(
|
|
20827
|
+
app.get(/^(?!\/api).*/, (_req, res) => res.sendFile(path23.join(dist, "index.html")));
|
|
20071
20828
|
}
|
|
20072
20829
|
app.use((err, _req, res, _next) => {
|
|
20073
20830
|
const parserStatus = err?.status;
|