droidsembly 0.4.0-beta.5 → 0.4.0-beta.6
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 +12 -3
- package/README.md +11 -3
- package/dist/assets/{AccessibilitySettings-vd4x_sEq.js → AccessibilitySettings-BLUQhCir.js} +5 -3
- package/dist/assets/{AccessibilitySettings-HrzBDUTN.css → AccessibilitySettings-DGcxiTfe.css} +1 -1
- package/dist/assets/{AppViewer-BB9lvg-4.js → AppViewer-CkRhHzAg.js} +2 -2
- package/dist/assets/{Balloon-CWEK5uK2.js → Balloon-CyA9jx7L.js} +1 -1
- package/dist/assets/{Batched-yAiB-c-b.js → Batched-BnwN-jIb.js} +1 -1
- package/dist/assets/{Birds-ClBZkA83.js → Birds-T-cAlNXa.js} +1 -1
- package/dist/assets/{Blimp-VHMnVBQt.js → Blimp-D5lM1i8g.js} +1 -1
- package/dist/assets/{BufferGeometryUtils-B4Tnxtjb.js → BufferGeometryUtils-BQuR3FyE.js} +1 -1
- package/dist/assets/{Duck-CCThHMtF.js → Duck-Df57hNLp.js} +1 -1
- package/dist/assets/{Effects-BZfFy3yq.js → Effects-BkJu9eYu.js} +1 -1
- package/dist/assets/{Fireworks-CxvvEwV_.js → Fireworks-BB1Mfdb3.js} +1 -1
- package/dist/assets/{Helicopter-DXHDrTnQ.js → Helicopter-B5NObfW4.js} +1 -1
- package/dist/assets/{Hurricane-WXNUxoUz.js → Hurricane-CGsnFbNg.js} +1 -1
- package/dist/assets/{Kaiju-D-wVgKo-.js → Kaiju-5SPvHn_6.js} +1 -1
- package/dist/assets/{Meteors-DSr-7bEl.js → Meteors-rA1sR1A3.js} +1 -1
- package/dist/assets/{MissionConsole-4G02S89d.js → MissionConsole-zJYkK_M1.js} +1 -1
- package/dist/assets/{Office-B_EroD2U.js → Office-fRdJ34l-.js} +44 -44
- package/dist/assets/{PhotoPanel-ByzwApow.js → PhotoPanel-DiplEiL_.js} +1 -1
- package/dist/assets/{PhotoScene-CW3yZkqH.js → PhotoScene-DG1ui0Av.js} +3 -3
- package/dist/assets/{Plane-CT7-QFbA.js → Plane-CtJDMF4A.js} +1 -1
- package/dist/assets/{Pocket-B0o4siMl.js → Pocket-x37KplGU.js} +2 -2
- package/dist/assets/{Rainbow-DNvXfTl9.js → Rainbow-Bbqcvhxa.js} +1 -1
- package/dist/assets/{Roof-yLX0ZK0x.js → Roof-DP8gTSp6.js} +1 -1
- package/dist/assets/{Shell-lZOZ3aG8.js → Shell-BzhH2Tnv.js} +2 -2
- package/dist/assets/{Skywriting-N1GDZKYR.js → Skywriting-CDweiNEJ.js} +1 -1
- package/dist/assets/{TerminalView-cUAMhOxM.js → TerminalView-CZkLeOi6.js} +11 -11
- package/dist/assets/{ToyWorld-BYE8776A.js → ToyWorld-ZLc2l8lQ.js} +1 -1
- package/dist/assets/{Ufo-D_Wt75n1.js → Ufo-CQvPbWUN.js} +1 -1
- package/dist/assets/{Whale-Kkz3B36R.js → Whale-Mz6Mfxvb.js} +1 -1
- package/dist/assets/{all-BMItClgN.js → all-AJNOOWx8.js} +2 -2
- package/dist/assets/{bloomMarks-C22qSi5d.js → bloomMarks-CWsszTY1.js} +1 -1
- package/dist/assets/{cheerRules-G9WFRB4C.js → cheerRules-Bs7u6fhI.js} +1 -1
- package/dist/assets/{cityLayout-C8f5-bpM.js → cityLayout-1I0cF38a.js} +1 -1
- package/dist/assets/{dogState-9uong8D8.js → dogState-DSYyIK7C.js} +1 -1
- package/dist/assets/{doors-DsKuGpOi.js → doors-BUM4Izj_.js} +1 -1
- package/dist/assets/{gallery-DSKvNkBq.js → gallery-BntMgHVx.js} +1 -1
- package/dist/assets/{gate-D6_NXB1w.js → gate-B4Yyimy5.js} +2 -2
- package/dist/assets/{index-COpmc42S.css → index-0ut5ekje.css} +1 -1
- package/dist/assets/{index-rznd4Djx.js → index-BoDJkaEF.js} +3 -3
- package/dist/assets/{instantReplay-CiWMru53.js → instantReplay-D8hjR3t4.js} +1 -1
- package/dist/assets/{interact-Bt-XX-z4.js → interact-Bj1zja21.js} +1 -1
- package/dist/assets/{kit-CZEafHnz.js → kit-iArIGJf-.js} +1 -1
- package/dist/assets/{mic-DeYDrNoY.js → mic-B-UxYaQY.js} +1 -1
- package/dist/assets/{photoMode-BTxq9-gL.js → photoMode-CRSRNKrX.js} +1 -1
- package/dist/assets/{pipeline-DNe3sjnP.js → pipeline-DvDJ46O5.js} +1 -1
- package/dist/assets/{rapier-C-KFR0AR.js → rapier-Dtx9m4Xq.js} +1 -1
- package/dist/assets/{rig-B88WinIa.js → rig-Bs_tw8rH.js} +1 -1
- package/dist/assets/{speechLanguage-Bq3BAswq.js → speechLanguage-CSuv5EYa.js} +1 -1
- package/dist/assets/store-D1ymxjG0.js +5 -0
- package/dist/assets/{useDayTime-Nrdy7kH1.js → useDayTime-Cn8OOG-d.js} +1 -1
- package/dist/assets/{useGraphics-Bhnj8CAm.js → useGraphics-CnMUzm0p.js} +1 -1
- package/dist/assets/{voiceMessages-BF3P4sjw.js → voiceMessages-CvKdLaYv.js} +1 -1
- package/dist/assets/{weatherState-CufaxiyU.js → weatherState-BGsd5Mzz.js} +1 -1
- package/dist/index.html +3 -3
- package/dist-server/index.js +1404 -650
- package/dist-server/index.js.map +4 -4
- package/dist-server/skills/ceo-app-starter.md +53 -0
- package/docs/app-starter-provenance.md +25 -0
- package/docs/app-starter.md +107 -0
- package/package.json +4 -2
- package/dist/assets/store-9CvxLGNQ.js +0 -5
package/dist-server/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// server/index.ts
|
|
2
2
|
import http3 from "node:http";
|
|
3
|
-
import
|
|
4
|
-
import
|
|
3
|
+
import path24 from "node:path";
|
|
4
|
+
import fs24 from "node:fs";
|
|
5
5
|
import express from "express";
|
|
6
6
|
import { WebSocketServer } from "ws";
|
|
7
|
-
import { z as
|
|
7
|
+
import { z as z4 } from "zod";
|
|
8
8
|
|
|
9
9
|
// shared/clipLimits.ts
|
|
10
10
|
var CLIP_MAX_MS = 6e4;
|
|
@@ -36,8 +36,8 @@ var SPEECH_MAX_CHARS = 1500;
|
|
|
36
36
|
var SAMPLE_LINE = "Hi! This is how I'll sound when I message you from the office.";
|
|
37
37
|
var EMOJI = /[\p{Extended_Pictographic}\p{Regional_Indicator}\u{1F3FB}-\u{1F3FF}︎️⃣]/gu;
|
|
38
38
|
var URL2 = /\b(?:https?:\/\/|www\.)[^\s<>()]+[^\s<>().,;:!?'"]/gi;
|
|
39
|
-
function speechText(
|
|
40
|
-
let s2 =
|
|
39
|
+
function speechText(text4, max = SPEECH_MAX_CHARS) {
|
|
40
|
+
let s2 = text4.replace(/\r\n?/g, "\n");
|
|
41
41
|
s2 = s2.replace(/```[\s\S]*?(```|$)/g, "\n");
|
|
42
42
|
s2 = s2.replace(/`([^`\n]*)`/g, "$1");
|
|
43
43
|
s2 = s2.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1");
|
|
@@ -180,8 +180,8 @@ function defaultProjectsDir(appDir, home = os2.homedir()) {
|
|
|
180
180
|
}
|
|
181
181
|
|
|
182
182
|
// server/workspace.ts
|
|
183
|
-
import
|
|
184
|
-
import
|
|
183
|
+
import fs4 from "node:fs/promises";
|
|
184
|
+
import path4 from "node:path";
|
|
185
185
|
|
|
186
186
|
// server/exec.ts
|
|
187
187
|
import { execFile } from "node:child_process";
|
|
@@ -195,8 +195,8 @@ var CommandError = class extends Error {
|
|
|
195
195
|
code;
|
|
196
196
|
};
|
|
197
197
|
function failureDetail(err, stderr, timeoutMs) {
|
|
198
|
-
const
|
|
199
|
-
if (
|
|
198
|
+
const text4 = stderr.trim();
|
|
199
|
+
if (text4) return text4;
|
|
200
200
|
if (typeof err.code === "string") return err.message.trim();
|
|
201
201
|
if (err.killed) return `timed out after ${Math.round(timeoutMs / 1e3)} s`;
|
|
202
202
|
if (err.signal) return `stopped by ${err.signal}`;
|
|
@@ -237,6 +237,38 @@ async function ghJson(args, opts) {
|
|
|
237
237
|
return out ? JSON.parse(out) : null;
|
|
238
238
|
}
|
|
239
239
|
|
|
240
|
+
// server/resumeDesk.ts
|
|
241
|
+
import fs3 from "node:fs/promises";
|
|
242
|
+
import path3 from "node:path";
|
|
243
|
+
async function resumeDesk(main, desk, branch, defaultRef) {
|
|
244
|
+
const g = (cwd, args) => git(args, { cwd });
|
|
245
|
+
await g(main, ["check-ref-format", "--branch", branch]);
|
|
246
|
+
const entries = await fs3.readdir(desk).catch((error) => {
|
|
247
|
+
if (error.code === "ENOENT") return [];
|
|
248
|
+
throw error;
|
|
249
|
+
});
|
|
250
|
+
if (entries.includes(".git")) {
|
|
251
|
+
const real = async (p) => fs3.realpath(p);
|
|
252
|
+
const root = await g(desk, ["rev-parse", "--show-toplevel"]);
|
|
253
|
+
const common = await g(desk, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
|
|
254
|
+
const expected = await g(main, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
|
|
255
|
+
if (await real(root) !== await real(desk) || await real(common) !== await real(expected)) throw new Error("The existing desk belongs to another checkout; its files were left untouched.");
|
|
256
|
+
const current = await g(desk, ["symbolic-ref", "--short", "-q", "HEAD"]).catch(() => "");
|
|
257
|
+
if (current !== branch) throw new Error("The existing desk is not on the interrupted branch; its files were left untouched.");
|
|
258
|
+
return desk;
|
|
259
|
+
}
|
|
260
|
+
if (entries.length) throw new Error("The desk folder contains files but is not a worktree; its files were left untouched.");
|
|
261
|
+
await g(main, ["fetch", "origin", "--prune"]);
|
|
262
|
+
const exists2 = (ref) => g(main, ["show-ref", "--verify", "--quiet", ref]).then(() => true, () => false);
|
|
263
|
+
await fs3.mkdir(path3.dirname(desk), { recursive: true });
|
|
264
|
+
if (await exists2(`refs/heads/${branch}`)) await g(main, ["worktree", "add", desk, branch]);
|
|
265
|
+
else {
|
|
266
|
+
const ref = await exists2(`refs/remotes/origin/${branch}`) ? `origin/${branch}` : defaultRef;
|
|
267
|
+
await g(main, ["worktree", "add", "-b", branch, desk, ref]);
|
|
268
|
+
}
|
|
269
|
+
return desk;
|
|
270
|
+
}
|
|
271
|
+
|
|
240
272
|
// server/workspace.ts
|
|
241
273
|
var locks = /* @__PURE__ */ new Map();
|
|
242
274
|
var localRoots = /* @__PURE__ */ new Map();
|
|
@@ -246,24 +278,24 @@ function withRepoLock(fullName, fn) {
|
|
|
246
278
|
locks.set(fullName, next);
|
|
247
279
|
return next;
|
|
248
280
|
}
|
|
249
|
-
var repoDir = (fullName) =>
|
|
250
|
-
var mainDir = (fullName) => localRoots.get(fullName.toLowerCase()) ??
|
|
251
|
-
var deskDir = (fullName, agentSlug) =>
|
|
281
|
+
var repoDir = (fullName) => path4.join(WORKSPACE_ROOT, fullName.replace("/", "__"));
|
|
282
|
+
var mainDir = (fullName) => localRoots.get(fullName.toLowerCase()) ?? path4.join(repoDir(fullName), "main");
|
|
283
|
+
var deskDir = (fullName, agentSlug) => path4.join(repoDir(fullName), "desks", agentSlug);
|
|
252
284
|
function setLocalPath(fullName, dir) {
|
|
253
|
-
if (dir) localRoots.set(fullName.toLowerCase(),
|
|
285
|
+
if (dir) localRoots.set(fullName.toLowerCase(), path4.resolve(dir));
|
|
254
286
|
else localRoots.delete(fullName.toLowerCase());
|
|
255
287
|
}
|
|
256
288
|
async function exists(p) {
|
|
257
|
-
return
|
|
289
|
+
return fs4.access(p).then(() => true).catch(() => false);
|
|
258
290
|
}
|
|
259
291
|
var LOCAL_EXCLUDES = [".playwright-mcp/", ".preview-tmp/"];
|
|
260
292
|
async function addLocalExcludes(main) {
|
|
261
|
-
const file =
|
|
262
|
-
const current = await
|
|
293
|
+
const file = path4.join(main, ".git", "info", "exclude");
|
|
294
|
+
const current = await fs4.readFile(file, "utf8").catch(() => "");
|
|
263
295
|
const missing = LOCAL_EXCLUDES.filter((l) => !current.split(/\r?\n/).includes(l));
|
|
264
296
|
if (missing.length === 0) return;
|
|
265
|
-
await
|
|
266
|
-
await
|
|
297
|
+
await fs4.mkdir(path4.dirname(file), { recursive: true });
|
|
298
|
+
await fs4.appendFile(file, `${current && !current.endsWith("\n") ? "\n" : ""}# added by cubefarm
|
|
267
299
|
${missing.join("\n")}
|
|
268
300
|
`);
|
|
269
301
|
}
|
|
@@ -271,10 +303,10 @@ var ensureLocalExcludes = (fullName) => addLocalExcludes(mainDir(fullName));
|
|
|
271
303
|
function ensureClone(fullName) {
|
|
272
304
|
return withRepoLock(fullName, async () => {
|
|
273
305
|
const dir = mainDir(fullName);
|
|
274
|
-
if (await exists(
|
|
306
|
+
if (await exists(path4.join(dir, ".git"))) {
|
|
275
307
|
await git(["fetch", "origin", "--prune"], { cwd: dir, timeoutMs: 18e4 });
|
|
276
308
|
} else {
|
|
277
|
-
await
|
|
309
|
+
await fs4.mkdir(path4.dirname(dir), { recursive: true });
|
|
278
310
|
await gh(["repo", "clone", fullName, dir], { timeoutMs: 6e5 });
|
|
279
311
|
}
|
|
280
312
|
await addLocalExcludes(dir);
|
|
@@ -318,7 +350,7 @@ function fileList(files, max = 3, maxChars = 120) {
|
|
|
318
350
|
async function syncMain(fullName, defaultBranch, opts) {
|
|
319
351
|
const dir = mainDir(fullName);
|
|
320
352
|
const result = await withRepoLock(fullName, async () => {
|
|
321
|
-
if (!await exists(
|
|
353
|
+
if (!await exists(path4.join(dir, ".git"))) return null;
|
|
322
354
|
const g = (args, timeoutMs) => git(args, { cwd: dir, timeoutMs });
|
|
323
355
|
let behind = 0;
|
|
324
356
|
try {
|
|
@@ -345,7 +377,7 @@ async function syncMain(fullName, defaultBranch, opts) {
|
|
|
345
377
|
return { status: `${behind} behind: local files are in the way${files.length ? `: ${fileList(files)}` : ""}`, behind, updatable: true };
|
|
346
378
|
}
|
|
347
379
|
const changed = (await g(["diff", "--name-only", before, "HEAD"])).split(/\r?\n/);
|
|
348
|
-
const install = changed.some((f) => f === "package.json" || f === "package-lock.json") && await exists(
|
|
380
|
+
const install = changed.some((f) => f === "package.json" || f === "package-lock.json") && await exists(path4.join(dir, "package.json"));
|
|
349
381
|
return { status: `updated to ${await g(["rev-parse", "--short", "HEAD"])}`, behind: 0, updatable: false, install };
|
|
350
382
|
} catch (err) {
|
|
351
383
|
return { status: `sync failed: ${err.message.split(/\r?\n/)[0].slice(0, 160)}`, behind, updatable: false };
|
|
@@ -367,33 +399,33 @@ function githubFromConfig(config) {
|
|
|
367
399
|
return m ? `${m[1]}/${m[2]}` : null;
|
|
368
400
|
}
|
|
369
401
|
async function inspectFolder(dir) {
|
|
370
|
-
const full =
|
|
371
|
-
const stat = await
|
|
402
|
+
const full = path4.resolve(dir);
|
|
403
|
+
const stat = await fs4.stat(full).catch(() => null);
|
|
372
404
|
if (!stat?.isDirectory()) throw new Error(`${full} is not a folder`);
|
|
373
|
-
const dotGit =
|
|
374
|
-
const gitStat = await
|
|
405
|
+
const dotGit = path4.join(full, ".git");
|
|
406
|
+
const gitStat = await fs4.stat(dotGit).catch(() => null);
|
|
375
407
|
let config = "";
|
|
376
|
-
if (gitStat?.isDirectory()) config = await
|
|
408
|
+
if (gitStat?.isDirectory()) config = await fs4.readFile(path4.join(dotGit, "config"), "utf8").catch(() => "");
|
|
377
409
|
else if (gitStat) {
|
|
378
|
-
const ref = (await
|
|
410
|
+
const ref = (await fs4.readFile(dotGit, "utf8").catch(() => "")).match(/gitdir:\s*(.+)/)?.[1]?.trim();
|
|
379
411
|
if (ref) {
|
|
380
|
-
const gitDir =
|
|
381
|
-
config = await
|
|
412
|
+
const gitDir = path4.resolve(full, ref);
|
|
413
|
+
config = await fs4.readFile(path4.join(gitDir, "config"), "utf8").catch(() => fs4.readFile(path4.join(gitDir, "..", "..", "config"), "utf8").catch(() => ""));
|
|
382
414
|
}
|
|
383
415
|
}
|
|
384
|
-
return { name:
|
|
416
|
+
return { name: path4.basename(full), path: full, git: !!gitStat, github: githubFromConfig(config), modified: stat.mtimeMs };
|
|
385
417
|
}
|
|
386
418
|
async function scanProjects(root) {
|
|
387
|
-
const entries = await
|
|
419
|
+
const entries = await fs4.readdir(root, { withFileTypes: true }).catch(() => {
|
|
388
420
|
throw new Error(`Can't read the projects folder ${root}`);
|
|
389
421
|
});
|
|
390
422
|
const dirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith(".") && e.name !== "node_modules");
|
|
391
|
-
const folders = await Promise.all(dirs.map((e) => inspectFolder(
|
|
423
|
+
const folders = await Promise.all(dirs.map((e) => inspectFolder(path4.join(root, e.name)).catch(() => null)));
|
|
392
424
|
return folders.filter((f) => !!f).sort((a, b) => b.modified - a.modified);
|
|
393
425
|
}
|
|
394
426
|
async function commitReadme(dir, title, description) {
|
|
395
|
-
const readme =
|
|
396
|
-
if (!await exists(readme)) await
|
|
427
|
+
const readme = path4.join(dir, "README.md");
|
|
428
|
+
if (!await exists(readme)) await fs4.writeFile(readme, `# ${title}
|
|
397
429
|
|
|
398
430
|
${description.trim()}
|
|
399
431
|
`);
|
|
@@ -407,7 +439,7 @@ ${description.trim()}
|
|
|
407
439
|
}
|
|
408
440
|
}
|
|
409
441
|
async function publishFolder(dir, opts) {
|
|
410
|
-
const full =
|
|
442
|
+
const full = path4.resolve(dir);
|
|
411
443
|
const info = await inspectFolder(full);
|
|
412
444
|
if (info.github) return info.github;
|
|
413
445
|
if (!info.git) await git(["init", "-b", "main"], { cwd: full });
|
|
@@ -416,7 +448,7 @@ async function publishFolder(dir, opts) {
|
|
|
416
448
|
() => false
|
|
417
449
|
);
|
|
418
450
|
if (!hasCommit) {
|
|
419
|
-
const files = (await
|
|
451
|
+
const files = (await fs4.readdir(full)).filter((f) => f !== ".git" && f !== "README.md");
|
|
420
452
|
if (files.length) {
|
|
421
453
|
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.`);
|
|
422
454
|
}
|
|
@@ -431,26 +463,26 @@ async function publishFolder(dir, opts) {
|
|
|
431
463
|
return out.match(/github\.com\/([^/\s]+\/[^/\s]+?)(?:\.git)?(?:\s|$)/)?.[1] ?? (await inspectFolder(full)).github ?? target;
|
|
432
464
|
}
|
|
433
465
|
async function createProject(root, name, opts) {
|
|
434
|
-
const dir =
|
|
466
|
+
const dir = path4.join(root, name);
|
|
435
467
|
if (await exists(dir)) {
|
|
436
|
-
const inside = await
|
|
468
|
+
const inside = await fs4.readdir(dir).catch(() => ["?"]);
|
|
437
469
|
if (inside.length) throw new Error(`${dir} already exists. Pick another name, or connect that folder instead.`);
|
|
438
470
|
}
|
|
439
|
-
await
|
|
471
|
+
await fs4.mkdir(dir, { recursive: true });
|
|
440
472
|
await git(["init", "-b", "main"], { cwd: dir });
|
|
441
473
|
await commitReadme(dir, name, opts.description ?? "");
|
|
442
474
|
const fullName = await publishFolder(dir, { name, ...opts });
|
|
443
475
|
return { fullName, path: dir };
|
|
444
476
|
}
|
|
445
477
|
async function removeDir(dir) {
|
|
446
|
-
await
|
|
478
|
+
await fs4.rm(dir, { recursive: true, force: true, maxRetries: 8, retryDelay: 250 });
|
|
447
479
|
}
|
|
448
480
|
var STALE_LOCK_MS = 10 * 6e4;
|
|
449
481
|
async function staleIndexLock(wt) {
|
|
450
|
-
const ref = (await
|
|
482
|
+
const ref = (await fs4.readFile(path4.join(wt, ".git"), "utf8").catch(() => "")).match(/gitdir:\s*(.+)/)?.[1]?.trim();
|
|
451
483
|
if (!ref) return null;
|
|
452
|
-
const lock =
|
|
453
|
-
const stat = await
|
|
484
|
+
const lock = path4.join(path4.resolve(wt, ref), "index.lock");
|
|
485
|
+
const stat = await fs4.stat(lock).catch(() => null);
|
|
454
486
|
return stat && Date.now() - stat.mtimeMs > STALE_LOCK_MS ? lock : null;
|
|
455
487
|
}
|
|
456
488
|
async function reuseDesk(wt, branch, ref) {
|
|
@@ -462,7 +494,7 @@ async function clearDeskFolder(wt) {
|
|
|
462
494
|
try {
|
|
463
495
|
await removeDir(wt);
|
|
464
496
|
} catch (err) {
|
|
465
|
-
const left = await
|
|
497
|
+
const left = await fs4.readdir(wt).catch(() => null);
|
|
466
498
|
if (left?.length !== 0) {
|
|
467
499
|
throw new Error(
|
|
468
500
|
`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.`
|
|
@@ -471,9 +503,35 @@ async function clearDeskFolder(wt) {
|
|
|
471
503
|
}
|
|
472
504
|
}
|
|
473
505
|
function prepareDesk(fullName, base, agentSlug, branch, note2) {
|
|
474
|
-
return withRepoLock(fullName, () =>
|
|
506
|
+
return withRepoLock(fullName, async () => {
|
|
507
|
+
const main = mainDir(fullName);
|
|
508
|
+
let desk = deskDir(fullName, agentSlug);
|
|
509
|
+
if (base.preserve && !base.pr) {
|
|
510
|
+
const entries = await fs4.readdir(desk).catch((err) => {
|
|
511
|
+
if (err.code === "ENOENT") return [];
|
|
512
|
+
throw err;
|
|
513
|
+
});
|
|
514
|
+
const suffix = agentSlug.match(/-([a-z0-9]{4})$/)?.[0];
|
|
515
|
+
if (!entries.length && suffix) {
|
|
516
|
+
const root = await fs4.realpath(path4.dirname(desk)).catch(() => null);
|
|
517
|
+
const worktrees = parseWorktrees(await git(["-c", "core.quotePath=false", "worktree", "list", "--porcelain"], { cwd: main }));
|
|
518
|
+
const candidates = [];
|
|
519
|
+
for (const wt of worktrees) {
|
|
520
|
+
if (wt.branch !== branch || !path4.basename(wt.path).endsWith(suffix)) continue;
|
|
521
|
+
if (root && await fs4.realpath(path4.dirname(wt.path)).catch(() => null) === root) candidates.push(wt.path);
|
|
522
|
+
}
|
|
523
|
+
if (candidates.length > 1) throw new Error("Multiple legacy desks match the interrupted branch; files were left untouched.");
|
|
524
|
+
if (candidates.length === 1) desk = candidates[0];
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
return setUpWorktree(main, desk, fullName, base, branch, note2);
|
|
528
|
+
});
|
|
475
529
|
}
|
|
476
530
|
async function setUpWorktree(main, wt, fullName, base, branch, note2) {
|
|
531
|
+
if (base.preserve) {
|
|
532
|
+
if (base.pr) throw new Error("Preserving an interrupted desk is only supported for issues.");
|
|
533
|
+
return resumeDesk(main, wt, branch, `origin/${base.defaultBranch}`);
|
|
534
|
+
}
|
|
477
535
|
await git(["fetch", "origin", "--prune"], { cwd: main, timeoutMs: 18e4 });
|
|
478
536
|
let ref = `origin/${base.defaultBranch}`;
|
|
479
537
|
if (base.pr) {
|
|
@@ -488,19 +546,19 @@ async function setUpWorktree(main, wt, fullName, base, branch, note2) {
|
|
|
488
546
|
);
|
|
489
547
|
}
|
|
490
548
|
await git(["worktree", "prune"], { cwd: main });
|
|
491
|
-
const real = (p) =>
|
|
549
|
+
const real = (p) => fs4.realpath(p).catch(() => p);
|
|
492
550
|
const worktrees = await Promise.all(parseWorktrees(await git(["worktree", "list", "--porcelain"], { cwd: main })).map(async (w) => ({ ...w, path: await real(w.path) })));
|
|
493
551
|
const holder = branchHolder(worktrees, branch, await real(wt));
|
|
494
552
|
const local = holder ? null : branch;
|
|
495
553
|
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}.`);
|
|
496
|
-
if (await exists(
|
|
554
|
+
if (await exists(path4.join(wt, ".git"))) {
|
|
497
555
|
try {
|
|
498
556
|
try {
|
|
499
557
|
await reuseDesk(wt, local, ref);
|
|
500
558
|
} catch (err) {
|
|
501
559
|
const lock = /index\.lock/.test(err.message) ? await staleIndexLock(wt) : null;
|
|
502
560
|
if (!lock) throw err;
|
|
503
|
-
await
|
|
561
|
+
await fs4.rm(lock, { force: true, maxRetries: 3 });
|
|
504
562
|
note2?.(`Removed a stale git lock (${lock}) left in the desk.`);
|
|
505
563
|
await reuseDesk(wt, local, ref);
|
|
506
564
|
}
|
|
@@ -516,12 +574,12 @@ async function setUpWorktree(main, wt, fullName, base, branch, note2) {
|
|
|
516
574
|
await clearDeskFolder(wt);
|
|
517
575
|
}
|
|
518
576
|
await git(["worktree", "prune"], { cwd: main });
|
|
519
|
-
await
|
|
577
|
+
await fs4.mkdir(path4.dirname(wt), { recursive: true });
|
|
520
578
|
await git(["worktree", "add", ...local ? ["-B", local] : ["--detach"], wt, ref], { cwd: main });
|
|
521
579
|
return wt;
|
|
522
580
|
}
|
|
523
581
|
function branchHolder(worktrees, branch, desk) {
|
|
524
|
-
return worktrees.find((w) => w.branch === branch && !samePath(w.path,
|
|
582
|
+
return worktrees.find((w) => w.branch === branch && !samePath(w.path, path4.resolve(desk)))?.path ?? null;
|
|
525
583
|
}
|
|
526
584
|
function removeDesk(fullName, agentSlug, main = mainDir(fullName)) {
|
|
527
585
|
return withRepoLock(fullName, async () => {
|
|
@@ -537,7 +595,7 @@ var OFFICE_BRANCH = /^(swarm\/issue-|qa\/pr-)/;
|
|
|
537
595
|
function parseWorktrees(porcelain) {
|
|
538
596
|
const out = [];
|
|
539
597
|
for (const line of porcelain.split(/\r?\n/)) {
|
|
540
|
-
if (line.startsWith("worktree ")) out.push({ path:
|
|
598
|
+
if (line.startsWith("worktree ")) out.push({ path: path4.resolve(line.slice(9)), branch: null, locked: false });
|
|
541
599
|
else if (!out.length) continue;
|
|
542
600
|
else if (line.startsWith("branch ")) out[out.length - 1].branch = line.slice(7).replace(/^refs\/heads\//, "");
|
|
543
601
|
else if (line === "locked" || line.startsWith("locked ")) out[out.length - 1].locked = true;
|
|
@@ -546,20 +604,20 @@ function parseWorktrees(porcelain) {
|
|
|
546
604
|
}
|
|
547
605
|
var samePath = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
548
606
|
function isOfficeDesk(p, fullName, root) {
|
|
549
|
-
const desks =
|
|
550
|
-
const repo =
|
|
551
|
-
const workspaces =
|
|
552
|
-
if (!samePath(
|
|
553
|
-
if (samePath(workspaces,
|
|
554
|
-
return
|
|
607
|
+
const desks = path4.dirname(p);
|
|
608
|
+
const repo = path4.dirname(desks);
|
|
609
|
+
const workspaces = path4.dirname(repo);
|
|
610
|
+
if (!samePath(path4.basename(desks), "desks") || !samePath(path4.basename(repo), fullName.replace("/", "__"))) return false;
|
|
611
|
+
if (samePath(workspaces, path4.resolve(root))) return true;
|
|
612
|
+
return path4.basename(workspaces) === "workspaces" && OLD_HOMES.some((h) => samePath(path4.basename(path4.dirname(workspaces)), h));
|
|
555
613
|
}
|
|
556
614
|
function planSweep(input, keep) {
|
|
557
|
-
const deskRoot =
|
|
558
|
-
const kept = (p) => keep.desks.some((slug2) => samePath(p,
|
|
615
|
+
const deskRoot = path4.join(path4.resolve(input.root), input.fullName.replace("/", "__"), "desks");
|
|
616
|
+
const kept = (p) => keep.desks.some((slug2) => samePath(p, path4.join(deskRoot, slug2)));
|
|
559
617
|
const worktrees = input.worktrees.slice(1).filter((w) => !w.locked && isOfficeDesk(w.path, input.fullName, input.root) && !kept(w.path));
|
|
560
618
|
const stays = input.worktrees.filter((w) => !worktrees.includes(w));
|
|
561
619
|
const folders = input.folders.filter((name) => {
|
|
562
|
-
const p =
|
|
620
|
+
const p = path4.join(deskRoot, name);
|
|
563
621
|
return !kept(p) && !input.worktrees.some((w) => samePath(w.path, p));
|
|
564
622
|
});
|
|
565
623
|
const branches = input.branches.filter((b) => OFFICE_BRANCH.test(b) && !keep.branches.includes(b) && !stays.some((w) => w.branch === b));
|
|
@@ -568,31 +626,31 @@ function planSweep(input, keep) {
|
|
|
568
626
|
async function inUse(dir) {
|
|
569
627
|
const probe = `${dir}.sweep`;
|
|
570
628
|
try {
|
|
571
|
-
await
|
|
629
|
+
await fs4.rename(dir, probe);
|
|
572
630
|
} catch (err) {
|
|
573
631
|
return err.code !== "ENOENT";
|
|
574
632
|
}
|
|
575
|
-
await
|
|
633
|
+
await fs4.rename(probe, dir);
|
|
576
634
|
return false;
|
|
577
635
|
}
|
|
578
636
|
var stamp = (d) => `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, "0")}${String(d.getDate()).padStart(2, "0")}`;
|
|
579
|
-
async function saveLeftovers(fullName, desk, label =
|
|
637
|
+
async function saveLeftovers(fullName, desk, label = path4.basename(desk)) {
|
|
580
638
|
const g = (args) => git(args, { cwd: desk, timeoutMs: 6e4 });
|
|
581
639
|
if (!await g(["rev-parse", "--verify", "-q", "HEAD"]).catch(() => "")) return null;
|
|
582
640
|
const dirty = await g(["status", "--porcelain", "--untracked-files=no"]);
|
|
583
641
|
const commits = Number(await g(["rev-list", "--count", "HEAD", "--not", "--remotes"]));
|
|
584
642
|
if (!dirty && !commits) return null;
|
|
585
|
-
const dir =
|
|
586
|
-
await
|
|
587
|
-
const tmp = await
|
|
643
|
+
const dir = path4.join(HOME_DIR, "leftovers", fullName.replace("/", "__"));
|
|
644
|
+
await fs4.mkdir(dir, { recursive: true });
|
|
645
|
+
const tmp = await fs4.mkdtemp(path4.join(dir, ".tmp-"));
|
|
588
646
|
try {
|
|
589
647
|
if (commits) await g(["format-patch", "-q", "-o", tmp, "HEAD", "--not", "--remotes"]);
|
|
590
|
-
if (dirty) await g(["diff", "HEAD", "--binary", `--output=${
|
|
591
|
-
const parts = (await
|
|
648
|
+
if (dirty) await g(["diff", "HEAD", "--binary", `--output=${path4.join(tmp, "zz-uncommitted.patch")}`]);
|
|
649
|
+
const parts = (await fs4.readdir(tmp)).sort();
|
|
592
650
|
const base = `${label}-${stamp(/* @__PURE__ */ new Date())}`;
|
|
593
|
-
let file =
|
|
594
|
-
for (let n = 2; await exists(file); n++) file =
|
|
595
|
-
await
|
|
651
|
+
let file = path4.join(dir, `${base}.patch`);
|
|
652
|
+
for (let n = 2; await exists(file); n++) file = path4.join(dir, `${base}-${n}.patch`);
|
|
653
|
+
await fs4.writeFile(file, Buffer.concat(await Promise.all(parts.map((p) => fs4.readFile(path4.join(tmp, p))))));
|
|
596
654
|
return file;
|
|
597
655
|
} finally {
|
|
598
656
|
await removeDir(tmp).catch(() => void 0);
|
|
@@ -602,16 +660,16 @@ function sweepDesks(fullName, keep) {
|
|
|
602
660
|
return withRepoLock(fullName, async () => {
|
|
603
661
|
const result = { desks: 0, folders: 0, branches: 0, patches: [], skipped: [] };
|
|
604
662
|
const main = mainDir(fullName);
|
|
605
|
-
if (!await exists(
|
|
663
|
+
if (!await exists(path4.join(main, ".git"))) return result;
|
|
606
664
|
const g = (args) => git(args, { cwd: main, timeoutMs: 6e4 });
|
|
607
665
|
await g(["worktree", "prune"]);
|
|
608
|
-
const real = (p) =>
|
|
666
|
+
const real = (p) => fs4.realpath(p).catch(() => p);
|
|
609
667
|
const worktrees = await Promise.all(parseWorktrees(await g(["worktree", "list", "--porcelain"])).map(async (w) => ({ ...w, path: await real(w.path) })));
|
|
610
668
|
const refs = await g(["for-each-ref", "--format=%(refname)", "refs/heads/swarm", "refs/heads/qa"]);
|
|
611
669
|
const branches = refs.split(/\r?\n/).filter(Boolean).map((r) => r.replace(/^refs\/heads\//, ""));
|
|
612
670
|
const root = await real(WORKSPACE_ROOT);
|
|
613
|
-
const deskRoot =
|
|
614
|
-
const folders = (await
|
|
671
|
+
const deskRoot = path4.join(root, fullName.replace("/", "__"), "desks");
|
|
672
|
+
const folders = (await fs4.readdir(deskRoot, { withFileTypes: true }).catch(() => [])).filter((e) => e.isDirectory()).map((e) => e.name);
|
|
615
673
|
const plan = planSweep({ fullName, root, worktrees, branches, folders }, keep);
|
|
616
674
|
const held = /* @__PURE__ */ new Set();
|
|
617
675
|
for (const wt of plan.worktrees) {
|
|
@@ -629,7 +687,7 @@ function sweepDesks(fullName, keep) {
|
|
|
629
687
|
}
|
|
630
688
|
await g(["worktree", "prune"]).catch(() => void 0);
|
|
631
689
|
for (const name of plan.folders) {
|
|
632
|
-
const dir =
|
|
690
|
+
const dir = path4.join(deskRoot, name);
|
|
633
691
|
try {
|
|
634
692
|
if (await inUse(dir)) throw new Error("in use");
|
|
635
693
|
await removeDir(dir);
|
|
@@ -653,12 +711,12 @@ async function dirSize(dir, concurrency = 8) {
|
|
|
653
711
|
const queue = [dir];
|
|
654
712
|
let active = 0;
|
|
655
713
|
const visit = async (d) => {
|
|
656
|
-
const entries = await
|
|
714
|
+
const entries = await fs4.readdir(d, { withFileTypes: true }).catch(() => []);
|
|
657
715
|
const sizes = await Promise.all(
|
|
658
716
|
entries.map((e) => {
|
|
659
|
-
const p =
|
|
717
|
+
const p = path4.join(d, e.name);
|
|
660
718
|
if (e.isDirectory()) queue.push(p);
|
|
661
|
-
return e.isFile() ?
|
|
719
|
+
return e.isFile() ? fs4.lstat(p).then((s2) => s2.size, () => 0) : 0;
|
|
662
720
|
})
|
|
663
721
|
);
|
|
664
722
|
for (const s2 of sizes) total += s2;
|
|
@@ -681,29 +739,29 @@ async function dirSize(dir, concurrency = 8) {
|
|
|
681
739
|
async function trimTargets(wt) {
|
|
682
740
|
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));
|
|
683
741
|
const present = [];
|
|
684
|
-
for (const name of TRIM_DIRS) if ((await
|
|
742
|
+
for (const name of TRIM_DIRS) if ((await fs4.lstat(path4.join(wt, name)).catch(() => null))?.isDirectory()) present.push(name);
|
|
685
743
|
const candidates = [.../* @__PURE__ */ new Set([...ignored, ...present])];
|
|
686
744
|
if (candidates.length === 0) return [];
|
|
687
745
|
const tracked = (await git(["ls-files", "-z", "--", ...candidates], { cwd: wt })).split("\0").filter(Boolean);
|
|
688
746
|
return candidates.filter((c) => !tracked.some((f) => f.startsWith(`${c}/`)));
|
|
689
747
|
}
|
|
690
748
|
function trimDesk(fullName, agentSlug, stillIdle = () => true) {
|
|
691
|
-
return trimWorktree(deskDir(fullName, agentSlug),
|
|
749
|
+
return trimWorktree(deskDir(fullName, agentSlug), path4.join(repoDir(fullName), "trash"), agentSlug, fullName, stillIdle);
|
|
692
750
|
}
|
|
693
751
|
async function trimWorktree(wt, trash, name, lock, stillIdle) {
|
|
694
|
-
for (const old of await
|
|
695
|
-
if (old.startsWith(`${name}-`)) await removeDir(
|
|
752
|
+
for (const old of await fs4.readdir(trash).catch(() => [])) {
|
|
753
|
+
if (old.startsWith(`${name}-`)) await removeDir(path4.join(trash, old)).catch(() => void 0);
|
|
696
754
|
}
|
|
697
|
-
const bin =
|
|
755
|
+
const bin = path4.join(trash, `${name}-${Date.now()}`);
|
|
698
756
|
const moved = await withRepoLock(lock, async () => {
|
|
699
|
-
if (!stillIdle() || !await exists(
|
|
757
|
+
if (!stillIdle() || !await exists(path4.join(wt, ".git"))) return null;
|
|
700
758
|
const out = { removed: [], skipped: [] };
|
|
701
759
|
const targets = await trimTargets(wt);
|
|
702
760
|
for (const [i, rel2] of targets.entries()) {
|
|
703
761
|
if (!stillIdle()) break;
|
|
704
762
|
try {
|
|
705
|
-
await
|
|
706
|
-
await
|
|
763
|
+
await fs4.mkdir(bin, { recursive: true });
|
|
764
|
+
await fs4.rename(path4.join(wt, rel2), path4.join(bin, `${i}-${path4.basename(rel2)}`));
|
|
707
765
|
out.removed.push(rel2);
|
|
708
766
|
} catch {
|
|
709
767
|
out.skipped.push(rel2);
|
|
@@ -786,20 +844,20 @@ Write-Output $kill.Count`;
|
|
|
786
844
|
}
|
|
787
845
|
}
|
|
788
846
|
}
|
|
789
|
-
var MACHINES_DIR =
|
|
847
|
+
var MACHINES_DIR = path4.join(HOME_DIR, "machines");
|
|
790
848
|
var repoFolder = (fullName) => fullName.replace("/", "__");
|
|
791
|
-
var machineDir = (machine) =>
|
|
792
|
-
var machineClone = (machine, fullName) =>
|
|
793
|
-
var machineDesk = (machine, fullName) =>
|
|
794
|
-
var machineTmp = (machine) =>
|
|
849
|
+
var machineDir = (machine) => path4.join(MACHINES_DIR, machine);
|
|
850
|
+
var machineClone = (machine, fullName) => path4.join(machineDir(machine), "repos", repoFolder(fullName));
|
|
851
|
+
var machineDesk = (machine, fullName) => path4.join(machineDir(machine), "work", repoFolder(fullName));
|
|
852
|
+
var machineTmp = (machine) => path4.join(machineDir(machine), "tmp");
|
|
795
853
|
var machineLock = (machine, fullName) => `machine:${machine}:${fullName}`;
|
|
796
854
|
async function ensureMachineClone(machine, fullName) {
|
|
797
855
|
const clone = machineClone(machine, fullName);
|
|
798
|
-
if (await exists(
|
|
856
|
+
if (await exists(path4.join(clone, ".git"))) return clone;
|
|
799
857
|
await removeDir(clone).catch(() => void 0);
|
|
800
|
-
await
|
|
858
|
+
await fs4.mkdir(path4.dirname(clone), { recursive: true });
|
|
801
859
|
const main = mainDir(fullName);
|
|
802
|
-
const origin = await exists(
|
|
860
|
+
const origin = await exists(path4.join(main, ".git")) ? await git(["remote", "get-url", "origin"], { cwd: main }).catch(() => "") : "";
|
|
803
861
|
if (origin) await git(["clone", "-q", "--no-checkout", "--reference-if-able", main, "--dissociate", origin, clone], { timeoutMs: 6e5 });
|
|
804
862
|
else await gh(["repo", "clone", fullName, clone, "--", "--no-checkout"], { timeoutMs: 6e5 });
|
|
805
863
|
await addLocalExcludes(clone);
|
|
@@ -809,7 +867,7 @@ function prepareMachineDesk(machine, fullName, base, branch, note2) {
|
|
|
809
867
|
return withRepoLock(machineLock(machine, fullName), async () => setUpWorktree(await ensureMachineClone(machine, fullName), machineDesk(machine, fullName), fullName, base, branch, note2));
|
|
810
868
|
}
|
|
811
869
|
function trimMachineDesk(machine, fullName, stillIdle = () => true) {
|
|
812
|
-
return trimWorktree(machineDesk(machine, fullName),
|
|
870
|
+
return trimWorktree(machineDesk(machine, fullName), path4.join(machineDir(machine), "trash"), repoFolder(fullName), machineLock(machine, fullName), stillIdle);
|
|
813
871
|
}
|
|
814
872
|
function releaseMachine(machine, fullName, port, keep = { pids: [], markers: [] }) {
|
|
815
873
|
return releaseDirs([machineDesk(machine, fullName)], port, keep);
|
|
@@ -817,7 +875,7 @@ function releaseMachine(machine, fullName, port, keep = { pids: [], markers: []
|
|
|
817
875
|
function sweepMachine(machine, fullName, keep) {
|
|
818
876
|
return withRepoLock(machineLock(machine, fullName), async () => {
|
|
819
877
|
const clone = machineClone(machine, fullName);
|
|
820
|
-
if (!await exists(
|
|
878
|
+
if (!await exists(path4.join(clone, ".git"))) return 0;
|
|
821
879
|
const g = (args) => git(args, { cwd: clone, timeoutMs: 6e4 });
|
|
822
880
|
await g(["worktree", "prune"]);
|
|
823
881
|
const out = parseWorktrees(await g(["worktree", "list", "--porcelain"])).map((w) => w.branch);
|
|
@@ -835,8 +893,8 @@ async function removeMachine(machine) {
|
|
|
835
893
|
if (!await exists(dir)) return { removed: true, patches: [] };
|
|
836
894
|
if (await inUse(dir)) return { removed: false, patches: [] };
|
|
837
895
|
const patches = [];
|
|
838
|
-
for (const name of await
|
|
839
|
-
const patch = await saveLeftovers(name.replace("__", "/"),
|
|
896
|
+
for (const name of await fs4.readdir(path4.join(dir, "work")).catch(() => [])) {
|
|
897
|
+
const patch = await saveLeftovers(name.replace("__", "/"), path4.join(dir, "work", name), `machine-${machine}`).catch(() => null);
|
|
840
898
|
if (patch) patches.push(patch);
|
|
841
899
|
}
|
|
842
900
|
try {
|
|
@@ -847,7 +905,7 @@ async function removeMachine(machine) {
|
|
|
847
905
|
}
|
|
848
906
|
}
|
|
849
907
|
async function listMachines() {
|
|
850
|
-
return (await
|
|
908
|
+
return (await fs4.readdir(MACHINES_DIR, { withFileTypes: true }).catch(() => [])).filter((e) => e.isDirectory()).map((e) => e.name);
|
|
851
909
|
}
|
|
852
910
|
|
|
853
911
|
// server/backend.ts
|
|
@@ -890,6 +948,13 @@ async function repoMeta(fullName) {
|
|
|
890
948
|
defaultBranch: raw.defaultBranchRef?.name || "main"
|
|
891
949
|
};
|
|
892
950
|
}
|
|
951
|
+
async function findPlanIssues(fullName, marker2) {
|
|
952
|
+
const pages = await ghJson(
|
|
953
|
+
["api", "--paginate", "--slurp", `repos/${fullName}/issues?state=all&per_page=100`],
|
|
954
|
+
SYNC_READ
|
|
955
|
+
);
|
|
956
|
+
return pages.flat().filter((i) => !i.pull_request && i.body?.includes(marker2)).map((i) => ({ number: i.number, title: i.title, body: i.body ?? "" }));
|
|
957
|
+
}
|
|
893
958
|
async function listIssues(fullName, read = readTwice) {
|
|
894
959
|
const raw = await read(
|
|
895
960
|
() => ghJson(
|
|
@@ -1073,8 +1138,8 @@ async function uploadEvidence(fullName, filePath, data) {
|
|
|
1073
1138
|
}
|
|
1074
1139
|
|
|
1075
1140
|
// server/agentRunner.ts
|
|
1076
|
-
import
|
|
1077
|
-
import
|
|
1141
|
+
import fs7 from "node:fs";
|
|
1142
|
+
import path7 from "node:path";
|
|
1078
1143
|
import { query } from "@anthropic-ai/claude-agent-sdk";
|
|
1079
1144
|
|
|
1080
1145
|
// shared/aiUsage.ts
|
|
@@ -1208,15 +1273,15 @@ function codexUsage(sessionId, records, now2) {
|
|
|
1208
1273
|
}
|
|
1209
1274
|
|
|
1210
1275
|
// server/browser.ts
|
|
1211
|
-
import
|
|
1276
|
+
import fs5 from "node:fs";
|
|
1212
1277
|
import { createRequire } from "node:module";
|
|
1213
1278
|
import os3 from "node:os";
|
|
1214
|
-
import
|
|
1279
|
+
import path5 from "node:path";
|
|
1215
1280
|
function playwrightMcpCli() {
|
|
1216
1281
|
try {
|
|
1217
1282
|
const pkgFile = createRequire(import.meta.url).resolve("@playwright/mcp/package.json");
|
|
1218
|
-
const bin = JSON.parse(
|
|
1219
|
-
return
|
|
1283
|
+
const bin = JSON.parse(fs5.readFileSync(pkgFile, "utf8")).bin?.["playwright-mcp"] ?? "cli.js";
|
|
1284
|
+
return path5.join(path5.dirname(pkgFile), bin);
|
|
1220
1285
|
} catch {
|
|
1221
1286
|
return null;
|
|
1222
1287
|
}
|
|
@@ -1226,16 +1291,16 @@ function playwrightMcpCommand(cli, initScript, outputDir, node = process.execPat
|
|
|
1226
1291
|
}
|
|
1227
1292
|
function playwrightMcp(outputDir) {
|
|
1228
1293
|
const cli = playwrightMcpCli();
|
|
1229
|
-
return cli ? playwrightMcpCommand(cli,
|
|
1294
|
+
return cli ? playwrightMcpCommand(cli, path5.join(import.meta.dirname, "browser-init.js"), outputDir) : null;
|
|
1230
1295
|
}
|
|
1231
1296
|
function chromePaths(platform = process.platform, env = process.env, home = os3.homedir()) {
|
|
1232
1297
|
if (platform === "win32") {
|
|
1233
|
-
return [env.LOCALAPPDATA, env.PROGRAMFILES, env["PROGRAMFILES(X86)"]].filter((d) => !!d).map((d) =>
|
|
1298
|
+
return [env.LOCALAPPDATA, env.PROGRAMFILES, env["PROGRAMFILES(X86)"]].filter((d) => !!d).map((d) => path5.win32.join(d, "Google", "Chrome", "Application", "chrome.exe"));
|
|
1234
1299
|
}
|
|
1235
|
-
if (platform === "darwin") return ["/Applications/Google Chrome.app",
|
|
1300
|
+
if (platform === "darwin") return ["/Applications/Google Chrome.app", path5.posix.join(home, "Applications", "Google Chrome.app")];
|
|
1236
1301
|
return ["/opt/google/chrome/chrome", "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable"];
|
|
1237
1302
|
}
|
|
1238
|
-
var hasChrome = () => chromePaths().some((p) =>
|
|
1303
|
+
var hasChrome = () => chromePaths().some((p) => fs5.existsSync(p));
|
|
1239
1304
|
function browserProblem(mcp, chrome = hasChrome()) {
|
|
1240
1305
|
if (!mcp) return "\u26A0 The browser tool (@playwright/mcp) is not installed with Droidsembly: reinstall it, or run npx cubefarm doctor";
|
|
1241
1306
|
if (!chrome) return "\u26A0 Google Chrome not found, so this session cannot test in a browser: install it, or run npx cubefarm doctor";
|
|
@@ -1243,7 +1308,7 @@ function browserProblem(mcp, chrome = hasChrome()) {
|
|
|
1243
1308
|
}
|
|
1244
1309
|
|
|
1245
1310
|
// server/clis.ts
|
|
1246
|
-
import
|
|
1311
|
+
import fs6 from "node:fs";
|
|
1247
1312
|
|
|
1248
1313
|
// server/codexUsage.ts
|
|
1249
1314
|
var CODEX_USAGE_READER_SOURCE = String.raw`
|
|
@@ -1282,7 +1347,7 @@ function usageRecords(event) {
|
|
|
1282
1347
|
|
|
1283
1348
|
// server/clis.ts
|
|
1284
1349
|
import { createRequire as createRequire2 } from "node:module";
|
|
1285
|
-
import
|
|
1350
|
+
import path6 from "node:path";
|
|
1286
1351
|
|
|
1287
1352
|
// shared/models.ts
|
|
1288
1353
|
var isClaudeModel = (model2) => /^(claude|opus|sonnet|haiku|fable|default|best|opusplan)\b/i.test(model2.trim());
|
|
@@ -1324,13 +1389,13 @@ var cliLabel = (id) => CLIS.find((c) => c.id === id)?.label ?? id;
|
|
|
1324
1389
|
var WIN = process.platform === "win32";
|
|
1325
1390
|
function resolveCommand(name, env = process.env) {
|
|
1326
1391
|
const key = Object.keys(env).find((k) => k.toUpperCase() === "PATH") ?? "PATH";
|
|
1327
|
-
const dirs = (env[key] ?? "").split(
|
|
1392
|
+
const dirs = (env[key] ?? "").split(path6.delimiter).filter(Boolean);
|
|
1328
1393
|
const exts = WIN ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter((e) => /^\.(exe|cmd|bat|com)$/i.test(e)) : [""];
|
|
1329
1394
|
for (const dir of dirs) {
|
|
1330
1395
|
for (const ext of exts) {
|
|
1331
|
-
const file =
|
|
1396
|
+
const file = path6.join(dir, name + ext.toLowerCase());
|
|
1332
1397
|
try {
|
|
1333
|
-
const st =
|
|
1398
|
+
const st = fs6.statSync(file);
|
|
1334
1399
|
if (st.isFile() && (WIN || (st.mode & 73) !== 0)) return file;
|
|
1335
1400
|
} catch {
|
|
1336
1401
|
}
|
|
@@ -1338,8 +1403,8 @@ function resolveCommand(name, env = process.env) {
|
|
|
1338
1403
|
}
|
|
1339
1404
|
return null;
|
|
1340
1405
|
}
|
|
1341
|
-
function unwrapCmdShim(shimPath,
|
|
1342
|
-
const line =
|
|
1406
|
+
function unwrapCmdShim(shimPath, text4, env = process.env) {
|
|
1407
|
+
const line = text4.split(/\r?\n/).find((l) => /%\*\s*$/.test(l));
|
|
1343
1408
|
if (!line) return null;
|
|
1344
1409
|
const executable = line.match(/^\s*"([^"]+\.exe)"\s+%\*\s*$/i)?.[1];
|
|
1345
1410
|
if (executable && !/%dp0%/i.test(executable)) {
|
|
@@ -1351,16 +1416,16 @@ function unwrapCmdShim(shimPath, text3, env = process.env) {
|
|
|
1351
1416
|
});
|
|
1352
1417
|
return missing ? null : { file, args: [] };
|
|
1353
1418
|
}
|
|
1354
|
-
const dir =
|
|
1355
|
-
const targets = [...line.matchAll(/"%dp0%\\([^"]+)"/g)].map((m) =>
|
|
1419
|
+
const dir = path6.dirname(shimPath);
|
|
1420
|
+
const targets = [...line.matchAll(/"%dp0%\\([^"]+)"/g)].map((m) => path6.join(dir, m[1]));
|
|
1356
1421
|
const target = targets[targets.length - 1];
|
|
1357
1422
|
if (!target) return null;
|
|
1358
1423
|
if (/\.exe$/i.test(target)) return { file: target, args: [] };
|
|
1359
1424
|
if (!/\.[cm]?js$/i.test(target)) return null;
|
|
1360
1425
|
const between = line.slice(line.indexOf('"%_prog%"') + '"%_prog%"'.length, line.lastIndexOf(`"%dp0%\\`));
|
|
1361
1426
|
const nodeFlags = line.includes('"%_prog%"') ? between.trim().split(/\s+/).filter((f) => f.startsWith("--")) : [];
|
|
1362
|
-
const localNode =
|
|
1363
|
-
return { file:
|
|
1427
|
+
const localNode = path6.join(dir, "node.exe");
|
|
1428
|
+
return { file: fs6.existsSync(localNode) ? localNode : process.execPath, args: [...nodeFlags, target] };
|
|
1364
1429
|
}
|
|
1365
1430
|
var bundled;
|
|
1366
1431
|
function bundledClaude() {
|
|
@@ -1393,7 +1458,7 @@ function commandFor(id) {
|
|
|
1393
1458
|
if (!found2) return null;
|
|
1394
1459
|
if (WIN && /\.(cmd|bat)$/i.test(found2)) {
|
|
1395
1460
|
try {
|
|
1396
|
-
return unwrapCmdShim(found2,
|
|
1461
|
+
return unwrapCmdShim(found2, fs6.readFileSync(found2, "utf8")) ?? { file: found2, args: [] };
|
|
1397
1462
|
} catch {
|
|
1398
1463
|
return { file: found2, args: [] };
|
|
1399
1464
|
}
|
|
@@ -1401,10 +1466,10 @@ function commandFor(id) {
|
|
|
1401
1466
|
return { file: found2, args: [] };
|
|
1402
1467
|
}
|
|
1403
1468
|
function openCodeVersionProblem(version) {
|
|
1404
|
-
const
|
|
1405
|
-
const match =
|
|
1469
|
+
const text4 = version?.split(/\r?\n/)[0].trim() ?? "";
|
|
1470
|
+
const match = text4.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:[-+][\w.-]+)?$/i);
|
|
1406
1471
|
if (!match) return "Could not verify the OpenCode version. Droidsembly requires OpenCode 2.x. Check opencode --version before trying again.";
|
|
1407
|
-
return Number(match[1]) === 2 ? null : `OpenCode ${
|
|
1472
|
+
return Number(match[1]) === 2 ? null : `OpenCode ${text4} is not supported. Droidsembly requires OpenCode 2.x; install V2 before starting this agent.`;
|
|
1408
1473
|
}
|
|
1409
1474
|
async function checkOpenCodeVersion(cmd) {
|
|
1410
1475
|
const version = await run(cmd.file, [...cmd.args, "--version"], { timeoutMs: 2e4 }).catch(() => null);
|
|
@@ -1424,14 +1489,14 @@ var BOX_CODEX_VERSION = "0.163.0";
|
|
|
1424
1489
|
var BOX_OPENCODE_VERSION = "2.2.6";
|
|
1425
1490
|
function packageField(pkg, field) {
|
|
1426
1491
|
try {
|
|
1427
|
-
let dir =
|
|
1492
|
+
let dir = path6.dirname(createRequire2(import.meta.url).resolve(pkg));
|
|
1428
1493
|
for (let i = 0; i < 6; i++) {
|
|
1429
|
-
const file =
|
|
1430
|
-
if (
|
|
1431
|
-
const json = JSON.parse(
|
|
1494
|
+
const file = path6.join(dir, "package.json");
|
|
1495
|
+
if (fs6.existsSync(file)) {
|
|
1496
|
+
const json = JSON.parse(fs6.readFileSync(file, "utf8"));
|
|
1432
1497
|
if (json.name === pkg) return typeof json[field] === "string" ? json[field] : null;
|
|
1433
1498
|
}
|
|
1434
|
-
dir =
|
|
1499
|
+
dir = path6.dirname(dir);
|
|
1435
1500
|
}
|
|
1436
1501
|
} catch {
|
|
1437
1502
|
}
|
|
@@ -1679,7 +1744,9 @@ export default {
|
|
|
1679
1744
|
// A resumed session keeps its previous model over agent configuration. Apply the office's next-task choice.
|
|
1680
1745
|
let model = ctx.options.model;
|
|
1681
1746
|
if (!model) {
|
|
1682
|
-
const
|
|
1747
|
+
const response = await ctx.model.default();
|
|
1748
|
+
// Location-scoped V2 reads wrap their result; older V2 plugins returned the model directly.
|
|
1749
|
+
const selected = response && 'data' in response ? response.data : response;
|
|
1683
1750
|
if (selected) model = { providerID: selected.providerID, id: selected.id };
|
|
1684
1751
|
}
|
|
1685
1752
|
if (model) await ctx.session.switchModel({ sessionID, model });
|
|
@@ -1792,9 +1859,9 @@ var InputQueue = class {
|
|
|
1792
1859
|
items = [];
|
|
1793
1860
|
waiters = [];
|
|
1794
1861
|
closed = false;
|
|
1795
|
-
push(
|
|
1862
|
+
push(text4) {
|
|
1796
1863
|
if (this.closed) return;
|
|
1797
|
-
const msg = { type: "user", message: { role: "user", content:
|
|
1864
|
+
const msg = { type: "user", message: { role: "user", content: text4 }, parent_tool_use_id: null };
|
|
1798
1865
|
const waiter = this.waiters.shift();
|
|
1799
1866
|
if (waiter) waiter({ value: msg, done: false });
|
|
1800
1867
|
else this.items.push(msg);
|
|
@@ -1815,11 +1882,11 @@ var InputQueue = class {
|
|
|
1815
1882
|
}
|
|
1816
1883
|
};
|
|
1817
1884
|
var allowAll = async (_toolName, input) => ({ behavior: "allow", updatedInput: input });
|
|
1818
|
-
function screenshotFile(cwd,
|
|
1819
|
-
const file =
|
|
1885
|
+
function screenshotFile(cwd, text4) {
|
|
1886
|
+
const file = text4.match(/\]\(([^)\s]+\.(png|jpe?g))\)/i);
|
|
1820
1887
|
if (!file) return null;
|
|
1821
1888
|
try {
|
|
1822
|
-
return { data:
|
|
1889
|
+
return { data: fs7.readFileSync(path7.resolve(cwd, file[1])), mime: /png$/i.test(file[2]) ? "image/png" : "image/jpeg" };
|
|
1823
1890
|
} catch {
|
|
1824
1891
|
return null;
|
|
1825
1892
|
}
|
|
@@ -1828,17 +1895,17 @@ var IMAGE_MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jp
|
|
|
1828
1895
|
function newScreenshots(dir, seen, now2 = Date.now()) {
|
|
1829
1896
|
let names;
|
|
1830
1897
|
try {
|
|
1831
|
-
names =
|
|
1898
|
+
names = fs7.readdirSync(dir);
|
|
1832
1899
|
} catch {
|
|
1833
1900
|
return [];
|
|
1834
1901
|
}
|
|
1835
1902
|
const found2 = [];
|
|
1836
1903
|
for (const name of names.sort()) {
|
|
1837
|
-
const mime = IMAGE_MIME[
|
|
1838
|
-
const file =
|
|
1904
|
+
const mime = IMAGE_MIME[path7.extname(name).toLowerCase()];
|
|
1905
|
+
const file = path7.join(dir, name);
|
|
1839
1906
|
if (!mime || seen.has(name)) continue;
|
|
1840
1907
|
try {
|
|
1841
|
-
if (now2 -
|
|
1908
|
+
if (now2 - fs7.statSync(file).mtimeMs < 1e3) continue;
|
|
1842
1909
|
} catch {
|
|
1843
1910
|
continue;
|
|
1844
1911
|
}
|
|
@@ -1850,12 +1917,12 @@ var clip = (s2, n) => s2.length > n ? `${s2.slice(0, n - 1)}\u2026` : s2;
|
|
|
1850
1917
|
function rel(cwd, p) {
|
|
1851
1918
|
const s2 = String(p ?? "");
|
|
1852
1919
|
if (!s2) return "";
|
|
1853
|
-
const r =
|
|
1920
|
+
const r = path7.relative(cwd, path7.resolve(cwd, s2));
|
|
1854
1921
|
return r && !r.startsWith("..") ? r.replaceAll("\\", "/") : s2;
|
|
1855
1922
|
}
|
|
1856
1923
|
var escapeRe = (s2) => s2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1857
|
-
function tidyPaths(cwd,
|
|
1858
|
-
let out =
|
|
1924
|
+
function tidyPaths(cwd, text4) {
|
|
1925
|
+
let out = text4;
|
|
1859
1926
|
for (const v of /* @__PURE__ */ new Set([cwd, cwd.replaceAll("\\", "/")])) {
|
|
1860
1927
|
out = out.replace(new RegExp(`^cd\\s+"?${escapeRe(v)}"?\\s*(&&|;)\\s*`, "i"), "");
|
|
1861
1928
|
out = out.replace(new RegExp(`${escapeRe(v)}[\\\\/]?`, "gi"), "./");
|
|
@@ -1950,14 +2017,14 @@ function resultText(content) {
|
|
|
1950
2017
|
}
|
|
1951
2018
|
return "";
|
|
1952
2019
|
}
|
|
1953
|
-
var lineCount = (
|
|
1954
|
-
function summariseResult(cwd, tool2,
|
|
2020
|
+
var lineCount = (text4) => text4.replace(/\r/g, "").split("\n").filter((l) => l.trim() !== "").length;
|
|
2021
|
+
function summariseResult(cwd, tool2, text4) {
|
|
1955
2022
|
if (tool2 === "Edit" || tool2 === "MultiEdit" || tool2 === "NotebookEdit") return [{ kind: "result", text: " \u23BF Updated" }];
|
|
1956
|
-
if (tool2 === "apply_patch" && /Success\. Updated the following files/.test(
|
|
2023
|
+
if (tool2 === "apply_patch" && /Success\. Updated the following files/.test(text4)) return [{ kind: "result", text: " \u23BF Updated" }];
|
|
1957
2024
|
if (tool2 === "Write") return [{ kind: "result", text: " \u23BF Saved" }];
|
|
1958
|
-
if (tool2 === "Read") return [{ kind: "result", text: ` \u23BF Read ${lineCount(
|
|
1959
|
-
if (tool2 === "Glob") return [{ kind: "result", text: ` \u23BF Found ${lineCount(
|
|
1960
|
-
const lines = tidyPaths(cwd,
|
|
2025
|
+
if (tool2 === "Read") return [{ kind: "result", text: ` \u23BF Read ${lineCount(text4)} lines` }];
|
|
2026
|
+
if (tool2 === "Glob") return [{ kind: "result", text: ` \u23BF Found ${lineCount(text4)} files` }];
|
|
2027
|
+
const lines = tidyPaths(cwd, text4).replace(/\r/g, "").split("\n").filter((l) => l.trim() !== "");
|
|
1961
2028
|
if (lines.length === 0) return [{ kind: "result", text: " \u23BF (no output)" }];
|
|
1962
2029
|
const shown = lines.slice(0, 3).map((l, i) => ({ kind: "result", text: `${i === 0 ? " \u23BF " : " "}${clip(l, 170)}` }));
|
|
1963
2030
|
if (lines.length > 3) shown.push({ kind: "result", text: ` \u2026 +${lines.length - 3} lines` });
|
|
@@ -2104,7 +2171,7 @@ function startSession(opts, callbacks) {
|
|
|
2104
2171
|
for (const block of content) {
|
|
2105
2172
|
if (block.type !== "tool_result") continue;
|
|
2106
2173
|
const name = toolNames.get(block.tool_use_id) ?? "";
|
|
2107
|
-
const
|
|
2174
|
+
const text4 = resultText(block.content);
|
|
2108
2175
|
let images = 0;
|
|
2109
2176
|
if (Array.isArray(block.content)) {
|
|
2110
2177
|
for (const part of block.content) {
|
|
@@ -2114,15 +2181,15 @@ function startSession(opts, callbacks) {
|
|
|
2114
2181
|
}
|
|
2115
2182
|
}
|
|
2116
2183
|
}
|
|
2117
|
-
const saved = name === "mcp__playwright__browser_take_screenshot" && !images ? screenshotFile(opts.cwd,
|
|
2184
|
+
const saved = name === "mcp__playwright__browser_take_screenshot" && !images ? screenshotFile(opts.cwd, text4) : null;
|
|
2118
2185
|
if (saved) cb.screenshot(saved.data, saved.mime);
|
|
2119
2186
|
if (name.startsWith("mcp__playwright__")) {
|
|
2120
|
-
const url =
|
|
2187
|
+
const url = text4.match(/Page URL:\s*(\S+)/);
|
|
2121
2188
|
if (url) cb.browserUrl(url[1]);
|
|
2122
2189
|
}
|
|
2123
2190
|
if (name === "TodoWrite") continue;
|
|
2124
|
-
if (block.is_error) out.push({ kind: "error", text: ` \u23BF ${clip(tidyPaths(opts.cwd,
|
|
2125
|
-
else out.push(...summariseResult(opts.cwd, name,
|
|
2191
|
+
if (block.is_error) out.push({ kind: "error", text: ` \u23BF ${clip(tidyPaths(opts.cwd, text4).split("\n")[0] || "Error", 200)}` });
|
|
2192
|
+
else out.push(...summariseResult(opts.cwd, name, text4));
|
|
2126
2193
|
}
|
|
2127
2194
|
cb.tool(null);
|
|
2128
2195
|
if (out.length) cb.log(out);
|
|
@@ -2155,9 +2222,9 @@ function startSession(opts, callbacks) {
|
|
|
2155
2222
|
}
|
|
2156
2223
|
})();
|
|
2157
2224
|
return {
|
|
2158
|
-
send(
|
|
2225
|
+
send(text4) {
|
|
2159
2226
|
pendingTurns += 1;
|
|
2160
|
-
input.push(
|
|
2227
|
+
input.push(text4);
|
|
2161
2228
|
},
|
|
2162
2229
|
stop() {
|
|
2163
2230
|
stopped = true;
|
|
@@ -2170,8 +2237,8 @@ function startSession(opts, callbacks) {
|
|
|
2170
2237
|
|
|
2171
2238
|
// server/cliRunner.ts
|
|
2172
2239
|
import crypto3 from "node:crypto";
|
|
2173
|
-
import
|
|
2174
|
-
import
|
|
2240
|
+
import fs10 from "node:fs";
|
|
2241
|
+
import path11 from "node:path";
|
|
2175
2242
|
import { pathToFileURL } from "node:url";
|
|
2176
2243
|
|
|
2177
2244
|
// server/mcpHttp.ts
|
|
@@ -2228,12 +2295,12 @@ var HttpError = class extends Error {
|
|
|
2228
2295
|
};
|
|
2229
2296
|
|
|
2230
2297
|
// server/secrets.ts
|
|
2231
|
-
import
|
|
2232
|
-
import
|
|
2298
|
+
import fs8 from "node:fs/promises";
|
|
2299
|
+
import path8 from "node:path";
|
|
2233
2300
|
var queues = /* @__PURE__ */ new Map();
|
|
2234
2301
|
async function readSecrets(file) {
|
|
2235
2302
|
try {
|
|
2236
|
-
const s2 = JSON.parse(await
|
|
2303
|
+
const s2 = JSON.parse(await fs8.readFile(file, "utf8"));
|
|
2237
2304
|
return s2 && typeof s2 === "object" ? s2 : {};
|
|
2238
2305
|
} catch {
|
|
2239
2306
|
return {};
|
|
@@ -2243,11 +2310,11 @@ function mergeSecrets(file, patch) {
|
|
|
2243
2310
|
const write = (queues.get(file) ?? Promise.resolve()).then(async () => {
|
|
2244
2311
|
const next = { ...await readSecrets(file), ...patch };
|
|
2245
2312
|
for (const k of Object.keys(next)) if (next[k] === void 0) delete next[k];
|
|
2246
|
-
await
|
|
2313
|
+
await fs8.mkdir(path8.dirname(file), { recursive: true });
|
|
2247
2314
|
const tmp = `${file}.tmp`;
|
|
2248
|
-
await
|
|
2249
|
-
await
|
|
2250
|
-
await
|
|
2315
|
+
await fs8.writeFile(tmp, JSON.stringify(next, null, 2), { mode: 384 });
|
|
2316
|
+
await fs8.rename(tmp, file);
|
|
2317
|
+
await fs8.chmod(file, 384).catch(() => void 0);
|
|
2251
2318
|
});
|
|
2252
2319
|
queues.set(
|
|
2253
2320
|
file,
|
|
@@ -2268,23 +2335,23 @@ var CloudError = class extends Error {
|
|
|
2268
2335
|
function cloudError(err, what) {
|
|
2269
2336
|
if (err instanceof CloudError) return err;
|
|
2270
2337
|
const status = err instanceof BoxError ? err.statusCode : void 0;
|
|
2271
|
-
const
|
|
2272
|
-
if (status === 401 || status === 403 || /unauthori[sz]ed|invalid api key|forbidden/i.test(
|
|
2338
|
+
const text4 = err?.message ?? String(err);
|
|
2339
|
+
if (status === 401 || status === 403 || /unauthori[sz]ed|invalid api key|forbidden/i.test(text4)) {
|
|
2273
2340
|
return new CloudError("Upstash turned the Box API key away. Copy it again from console.upstash.com \u2192 Box \u2192 API Keys.", "auth");
|
|
2274
2341
|
}
|
|
2275
|
-
if (status === 402 || status === 429 || /limit|quota|concurrent|exceed/i.test(
|
|
2276
|
-
return new CloudError(`Upstash refused to ${what}: your plan's Box limit or usage is used up (${
|
|
2342
|
+
if (status === 402 || status === 429 || /limit|quota|concurrent|exceed/i.test(text4)) {
|
|
2343
|
+
return new CloudError(`Upstash refused to ${what}: your plan's Box limit or usage is used up (${text4.slice(0, 160)}).`, "limit");
|
|
2277
2344
|
}
|
|
2278
|
-
if (status === 404 || /not found/i.test(
|
|
2279
|
-
return new CloudError(`Couldn't ${what} on Upstash: ${
|
|
2345
|
+
if (status === 404 || /not found/i.test(text4)) return new CloudError(`That Box is gone (${text4.slice(0, 120)}).`, "gone");
|
|
2346
|
+
return new CloudError(`Couldn't ${what} on Upstash: ${text4.slice(0, 200)}`, "other");
|
|
2280
2347
|
}
|
|
2281
2348
|
var STATES = ["creating", "idle", "running", "paused", "error", "deleted"];
|
|
2282
2349
|
var state = (s2) => STATES.includes(s2) ? s2 : "error";
|
|
2283
2350
|
function decoder(onText) {
|
|
2284
2351
|
const d = new TextDecoder("utf-8");
|
|
2285
2352
|
return (bytes) => {
|
|
2286
|
-
const
|
|
2287
|
-
if (
|
|
2353
|
+
const text4 = d.decode(bytes, { stream: true });
|
|
2354
|
+
if (text4) onText(text4);
|
|
2288
2355
|
};
|
|
2289
2356
|
}
|
|
2290
2357
|
function upstashBoxes(apiKey, options = {}) {
|
|
@@ -2464,8 +2531,8 @@ function credentialViews(i) {
|
|
|
2464
2531
|
const codex = i.secrets.openaiApiKey ? { ready: true, source: "apiKey", hint: hint(i.secrets.openaiApiKey) } : login;
|
|
2465
2532
|
return { github: gh2, claude, codex };
|
|
2466
2533
|
}
|
|
2467
|
-
function redact(
|
|
2468
|
-
let out =
|
|
2534
|
+
function redact(text4, secrets) {
|
|
2535
|
+
let out = text4;
|
|
2469
2536
|
for (const s2 of secrets) if (s2 && s2.length >= 8) out = out.split(s2).join("\u2022\u2022\u2022");
|
|
2470
2537
|
return out;
|
|
2471
2538
|
}
|
|
@@ -2708,6 +2775,43 @@ function prepareDeskScript(fullName, base, branch) {
|
|
|
2708
2775
|
const repo = boxRepoDir(fullName);
|
|
2709
2776
|
const desk = boxDeskDir(fullName);
|
|
2710
2777
|
const ref = base.pr ? `origin/pr/${base.pr}` : `origin/${base.defaultBranch}`;
|
|
2778
|
+
if (base.preserve) {
|
|
2779
|
+
if (base.pr) throw new Error("Preserving an interrupted desk is only supported for issues.");
|
|
2780
|
+
return [
|
|
2781
|
+
"(",
|
|
2782
|
+
"set -e",
|
|
2783
|
+
`R=${sq(repo)}`,
|
|
2784
|
+
`W=${sq(desk)}`,
|
|
2785
|
+
`B=${sq(branch)}`,
|
|
2786
|
+
`REF=${sq(ref)}`,
|
|
2787
|
+
'git check-ref-format --branch "$B" >/dev/null',
|
|
2788
|
+
'if [ -e "$W/.git" ]; then',
|
|
2789
|
+
' test -d "$R/.git" || { echo "The desk clone is missing; files left untouched." >&2; exit 2; }',
|
|
2790
|
+
' ROOT="$(git -C "$W" rev-parse --show-toplevel)"',
|
|
2791
|
+
' test "$(cd "$ROOT" && pwd -P)" = "$(cd "$W" && pwd -P)" || exit 2',
|
|
2792
|
+
' C="$(git -C "$W" rev-parse --path-format=absolute --git-common-dir)"',
|
|
2793
|
+
' E="$(git -C "$R" rev-parse --path-format=absolute --git-common-dir)"',
|
|
2794
|
+
' test "$(cd "$C" && pwd -P)" = "$(cd "$E" && pwd -P)" || { echo "The desk belongs to another checkout; files left untouched." >&2; exit 2; }',
|
|
2795
|
+
' test "$(git -C "$W" symbolic-ref --short -q HEAD)" = "$B" || { echo "The desk is not on the interrupted branch; files left untouched." >&2; exit 2; }',
|
|
2796
|
+
' echo "$W"; exit 0',
|
|
2797
|
+
"fi",
|
|
2798
|
+
'if [ -e "$W" ]; then test -d "$W" && test -z "$(ls -A "$W")" || { echo "The desk folder is not empty; files left untouched." >&2; exit 2; }; fi',
|
|
2799
|
+
'if [ ! -d "$R/.git" ]; then',
|
|
2800
|
+
' mkdir -p "$(dirname "$R")"',
|
|
2801
|
+
` git clone -q --no-checkout ${sq(`https://github.com/${fullName}.git`)} "$R"`,
|
|
2802
|
+
"fi",
|
|
2803
|
+
'git -C "$R" fetch -q origin --prune',
|
|
2804
|
+
'mkdir -p "$(dirname "$W")"',
|
|
2805
|
+
'if git -C "$R" show-ref --verify --quiet "refs/heads/$B"; then',
|
|
2806
|
+
' git -C "$R" worktree add -q "$W" "$B"',
|
|
2807
|
+
"else",
|
|
2808
|
+
' if git -C "$R" show-ref --verify --quiet "refs/remotes/origin/$B"; then REF="origin/$B"; fi',
|
|
2809
|
+
' git -C "$R" worktree add -q -b "$B" "$W" "$REF"',
|
|
2810
|
+
"fi",
|
|
2811
|
+
'echo "$W"',
|
|
2812
|
+
")"
|
|
2813
|
+
].join("\n");
|
|
2814
|
+
}
|
|
2711
2815
|
return [
|
|
2712
2816
|
"(",
|
|
2713
2817
|
"set -e",
|
|
@@ -2820,6 +2924,41 @@ function signInOutcome(output) {
|
|
|
2820
2924
|
var signOutScript = (cli) => cli === "opencode" ? "true" : `${sq(`${BOX_CLI_BIN}/${cli}`)} ${cli === "claude" ? "auth logout" : "logout"} >/dev/null 2>&1; true`;
|
|
2821
2925
|
var signInCommand = (cli) => ({ file: `${BOX_CLI_BIN}/${cli}`, args: cli === "codex" ? ["login", "--device-auth"] : ["auth", "login"] });
|
|
2822
2926
|
|
|
2927
|
+
// server/ptyProtocol.ts
|
|
2928
|
+
import crypto from "node:crypto";
|
|
2929
|
+
import path9 from "node:path";
|
|
2930
|
+
var PTY_PROTOCOL = 1;
|
|
2931
|
+
function hostSocket(home, platform = process.platform) {
|
|
2932
|
+
if (platform !== "win32") return path9.join(home, "pty.sock");
|
|
2933
|
+
const tag = crypto.createHash("sha1").update(path9.resolve(home).toLowerCase()).digest("hex").slice(0, 12);
|
|
2934
|
+
return `\\\\.\\pipe\\cubefarm-pty-${tag}`;
|
|
2935
|
+
}
|
|
2936
|
+
var encode = (m) => `${JSON.stringify(m)}
|
|
2937
|
+
`;
|
|
2938
|
+
function ptyExitCode(value) {
|
|
2939
|
+
return typeof value === "number" && Number.isSafeInteger(value) ? value : -1;
|
|
2940
|
+
}
|
|
2941
|
+
function readMessages(sock, onMessage2) {
|
|
2942
|
+
let buf = "";
|
|
2943
|
+
sock.setEncoding("utf8");
|
|
2944
|
+
sock.on("data", (chunk) => {
|
|
2945
|
+
buf += chunk;
|
|
2946
|
+
let nl;
|
|
2947
|
+
while ((nl = buf.indexOf("\n")) >= 0) {
|
|
2948
|
+
const line = buf.slice(0, nl);
|
|
2949
|
+
buf = buf.slice(nl + 1);
|
|
2950
|
+
if (!line) continue;
|
|
2951
|
+
let m;
|
|
2952
|
+
try {
|
|
2953
|
+
m = JSON.parse(line);
|
|
2954
|
+
} catch {
|
|
2955
|
+
continue;
|
|
2956
|
+
}
|
|
2957
|
+
onMessage2(m);
|
|
2958
|
+
}
|
|
2959
|
+
});
|
|
2960
|
+
}
|
|
2961
|
+
|
|
2823
2962
|
// server/boxCli.ts
|
|
2824
2963
|
var BOX_CDP = "http://127.0.0.1:9222";
|
|
2825
2964
|
var TURN_ENDS = ["Stop", "StopFailure", "TurnComplete", "TurnError", "Interrupt"];
|
|
@@ -2832,8 +2971,8 @@ var EventLines = class {
|
|
|
2832
2971
|
offset;
|
|
2833
2972
|
turnAt;
|
|
2834
2973
|
rest = "";
|
|
2835
|
-
push(
|
|
2836
|
-
const parts = (this.rest +
|
|
2974
|
+
push(text4) {
|
|
2975
|
+
const parts = (this.rest + text4).split("\n");
|
|
2837
2976
|
this.rest = parts.pop() ?? "";
|
|
2838
2977
|
const out = [];
|
|
2839
2978
|
for (const line of parts) {
|
|
@@ -2860,7 +2999,7 @@ function finishedTurn(events) {
|
|
|
2860
2999
|
}
|
|
2861
3000
|
function exitCode(events) {
|
|
2862
3001
|
const exit = events.filter((e) => e.hook_event_name === "CubefarmExit").pop();
|
|
2863
|
-
return exit ?
|
|
3002
|
+
return exit ? ptyExitCode(exit.code) : null;
|
|
2864
3003
|
}
|
|
2865
3004
|
var backoff = (tries) => Math.min(3e4, 1e3 * 2 ** Math.min(tries, 5));
|
|
2866
3005
|
var ready;
|
|
@@ -2960,7 +3099,7 @@ var BoxPty = class {
|
|
|
2960
3099
|
const s2 = await this.o.api.session(this.o.boxId, {
|
|
2961
3100
|
cmd: `exec tail -c +${from + 1} -F ${sq(eventsFile(this.dir))} 2>/dev/null`,
|
|
2962
3101
|
env: BOX_ENV,
|
|
2963
|
-
onData: (
|
|
3102
|
+
onData: (text4) => this.handle(text4)
|
|
2964
3103
|
});
|
|
2965
3104
|
this.tail = s2;
|
|
2966
3105
|
this.tailTries = 0;
|
|
@@ -2972,12 +3111,12 @@ var BoxPty = class {
|
|
|
2972
3111
|
await new Promise((r) => setTimeout(r, backoff(this.tailTries++)));
|
|
2973
3112
|
}
|
|
2974
3113
|
}
|
|
2975
|
-
handle(
|
|
3114
|
+
handle(text4) {
|
|
2976
3115
|
if (this.stopped || this.exited) return;
|
|
2977
3116
|
let exit = null;
|
|
2978
|
-
for (const e of this.lines.push(
|
|
3117
|
+
for (const e of this.lines.push(text4)) {
|
|
2979
3118
|
if (this.stopped || this.exited) return;
|
|
2980
|
-
if (e.hook_event_name === "CubefarmExit") exit =
|
|
3119
|
+
if (e.hook_event_name === "CubefarmExit") exit = ptyExitCode(e.code);
|
|
2981
3120
|
else this.o.event(e);
|
|
2982
3121
|
}
|
|
2983
3122
|
if (this.stopped || this.exited) return;
|
|
@@ -3066,11 +3205,11 @@ var allowed = /* @__PURE__ */ new Set(["settings.json", "mcp.json", "instruction
|
|
|
3066
3205
|
function boxSessionFilesScripts(directory, files) {
|
|
3067
3206
|
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
3207
|
const seen = /* @__PURE__ */ new Set(), scripts = [];
|
|
3069
|
-
for (const [file,
|
|
3208
|
+
for (const [file, text4] of files) {
|
|
3070
3209
|
const name = file.slice(directory.length + 1);
|
|
3071
|
-
if (file !== directory + "/" + name || !allowed.has(name) || seen.has(name) || typeof
|
|
3210
|
+
if (file !== directory + "/" + name || !allowed.has(name) || seen.has(name) || typeof text4 !== "string") throw new Error("Invalid remote session file");
|
|
3072
3211
|
seen.add(name);
|
|
3073
|
-
const bytes = Buffer.from(
|
|
3212
|
+
const bytes = Buffer.from(text4, "utf8");
|
|
3074
3213
|
for (let offset = 0; offset === 0 || offset < bytes.length; offset += 16384) {
|
|
3075
3214
|
const request = { directory, name, offset, base64: bytes.subarray(offset, offset + 16384).toString("base64") };
|
|
3076
3215
|
const code = marker + `const request=${JSON.stringify(request)};
|
|
@@ -3224,47 +3363,10 @@ function parseOpenCodeReadiness(code, output) {
|
|
|
3224
3363
|
|
|
3225
3364
|
// server/ptyClient.ts
|
|
3226
3365
|
import crypto2 from "node:crypto";
|
|
3227
|
-
import
|
|
3366
|
+
import fs9 from "node:fs";
|
|
3228
3367
|
import net from "node:net";
|
|
3229
|
-
import
|
|
3368
|
+
import path10 from "node:path";
|
|
3230
3369
|
import { spawn } from "node:child_process";
|
|
3231
|
-
|
|
3232
|
-
// server/ptyProtocol.ts
|
|
3233
|
-
import crypto from "node:crypto";
|
|
3234
|
-
import path8 from "node:path";
|
|
3235
|
-
var PTY_PROTOCOL = 1;
|
|
3236
|
-
function hostSocket(home, platform = process.platform) {
|
|
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);
|
|
3239
|
-
return `\\\\.\\pipe\\cubefarm-pty-${tag}`;
|
|
3240
|
-
}
|
|
3241
|
-
var encode = (m) => `${JSON.stringify(m)}
|
|
3242
|
-
`;
|
|
3243
|
-
function ptyExitCode(value) {
|
|
3244
|
-
return typeof value === "number" && Number.isSafeInteger(value) ? value : -1;
|
|
3245
|
-
}
|
|
3246
|
-
function readMessages(sock, onMessage2) {
|
|
3247
|
-
let buf = "";
|
|
3248
|
-
sock.setEncoding("utf8");
|
|
3249
|
-
sock.on("data", (chunk) => {
|
|
3250
|
-
buf += chunk;
|
|
3251
|
-
let nl;
|
|
3252
|
-
while ((nl = buf.indexOf("\n")) >= 0) {
|
|
3253
|
-
const line = buf.slice(0, nl);
|
|
3254
|
-
buf = buf.slice(nl + 1);
|
|
3255
|
-
if (!line) continue;
|
|
3256
|
-
let m;
|
|
3257
|
-
try {
|
|
3258
|
-
m = JSON.parse(line);
|
|
3259
|
-
} catch {
|
|
3260
|
-
continue;
|
|
3261
|
-
}
|
|
3262
|
-
onMessage2(m);
|
|
3263
|
-
}
|
|
3264
|
-
});
|
|
3265
|
-
}
|
|
3266
|
-
|
|
3267
|
-
// server/ptyClient.ts
|
|
3268
3370
|
var nodePty = await import("@lydell/node-pty").catch((err) => {
|
|
3269
3371
|
console.warn(` terminals unavailable: ${err.message}`);
|
|
3270
3372
|
return null;
|
|
@@ -3369,7 +3471,7 @@ function connect(socket, secret) {
|
|
|
3369
3471
|
}
|
|
3370
3472
|
var runtimeFlags = () => process.execArgv.filter((a, i, all) => !/^--(inspect|watch|debug)/.test(a) && !/^--(inspect|watch|debug)/.test(all[i - 1] ?? ""));
|
|
3371
3473
|
function launch(socket, secretFile) {
|
|
3372
|
-
const entry =
|
|
3474
|
+
const entry = path10.join(import.meta.dirname, `ptyHost${path10.extname(import.meta.filename)}`);
|
|
3373
3475
|
spawn(process.execPath, [...runtimeFlags(), entry, "launch", socket, secretFile], { detached: true, stdio: "ignore", windowsHide: true }).once("error", () => void 0).unref();
|
|
3374
3476
|
}
|
|
3375
3477
|
var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
@@ -3377,17 +3479,17 @@ async function startKeeper(home, onHook) {
|
|
|
3377
3479
|
hookHandler = onHook;
|
|
3378
3480
|
if (!nodePty) return [];
|
|
3379
3481
|
const socket = hostSocket(home);
|
|
3380
|
-
const secretFile =
|
|
3482
|
+
const secretFile = path10.join(home, "pty.secret");
|
|
3381
3483
|
try {
|
|
3382
|
-
if (!
|
|
3383
|
-
|
|
3384
|
-
|
|
3484
|
+
if (!fs9.existsSync(secretFile)) {
|
|
3485
|
+
fs9.mkdirSync(home, { recursive: true });
|
|
3486
|
+
fs9.writeFileSync(secretFile, crypto2.randomBytes(24).toString("hex"), { mode: 384 });
|
|
3385
3487
|
}
|
|
3386
3488
|
} catch (err) {
|
|
3387
3489
|
console.warn(` terminal keeper unavailable: ${err.message}`);
|
|
3388
3490
|
return [];
|
|
3389
3491
|
}
|
|
3390
|
-
const secret =
|
|
3492
|
+
const secret = fs9.readFileSync(secretFile, "utf8").trim();
|
|
3391
3493
|
let hello = await connect(socket, secret);
|
|
3392
3494
|
if (hello && hello.ready.version !== PTY_PROTOCOL) {
|
|
3393
3495
|
console.log(` replacing the terminal keeper (v${hello.ready.version}); the ${hello.ready.ptys.length} terminal(s) it held are stopped`);
|
|
@@ -3467,8 +3569,8 @@ function killTree(proc) {
|
|
|
3467
3569
|
}
|
|
3468
3570
|
|
|
3469
3571
|
// server/cliRunner.ts
|
|
3470
|
-
var SESSIONS_DIR =
|
|
3471
|
-
var BIN_DIR =
|
|
3572
|
+
var SESSIONS_DIR = path11.join(HOME_DIR, "sessions");
|
|
3573
|
+
var BIN_DIR = path11.join(HOME_DIR, "bin");
|
|
3472
3574
|
var FINISH_GRACE_MS = 3e3;
|
|
3473
3575
|
var BOOT_MS = 6e4;
|
|
3474
3576
|
var USAGE_WARN_PCT = 90;
|
|
@@ -3494,14 +3596,14 @@ async function handleMcp(token, req, res) {
|
|
|
3494
3596
|
var helpersWritten = false;
|
|
3495
3597
|
function writeHelpers() {
|
|
3496
3598
|
if (helpersWritten) return;
|
|
3497
|
-
|
|
3498
|
-
|
|
3499
|
-
|
|
3500
|
-
|
|
3501
|
-
const pluginDir =
|
|
3502
|
-
|
|
3503
|
-
|
|
3504
|
-
|
|
3599
|
+
fs10.mkdirSync(BIN_DIR, { recursive: true });
|
|
3600
|
+
fs10.writeFileSync(path11.join(BIN_DIR, "statusline.cjs"), STATUSLINE_SOURCE);
|
|
3601
|
+
fs10.writeFileSync(path11.join(BIN_DIR, "notify.cjs"), NOTIFY_SOURCE);
|
|
3602
|
+
fs10.writeFileSync(path11.join(BIN_DIR, "codex-hook.cjs"), CODEX_HOOK_SOURCE);
|
|
3603
|
+
const pluginDir = path11.join(BIN_DIR, "opencode-plugin");
|
|
3604
|
+
fs10.mkdirSync(pluginDir, { recursive: true });
|
|
3605
|
+
fs10.writeFileSync(path11.join(pluginDir, "index.js"), OPENCODE_PLUGIN_SOURCE);
|
|
3606
|
+
fs10.writeFileSync(path11.join(pluginDir, "package.json"), JSON.stringify({ name: "droidsembly-office-plugin", type: "module", exports: "./index.js" }));
|
|
3505
3607
|
helpersWritten = true;
|
|
3506
3608
|
}
|
|
3507
3609
|
var shellArg = (p) => `"${p.replaceAll("\\", "/")}"`;
|
|
@@ -3554,7 +3656,7 @@ function endLive(live) {
|
|
|
3554
3656
|
live.proc = null;
|
|
3555
3657
|
live.term.note(`\u2500\u2500 ${cliLabel(live.cli)} session ended \u2500\u2500`);
|
|
3556
3658
|
if (live.box) return gone;
|
|
3557
|
-
|
|
3659
|
+
fs10.rm(live.dir, { recursive: true, force: true, maxRetries: 5 }, () => void 0);
|
|
3558
3660
|
if (live.cli === "codex" && live.resumeId) void codexThread("archive", live.resumeId, gone);
|
|
3559
3661
|
return gone;
|
|
3560
3662
|
}
|
|
@@ -3676,8 +3778,8 @@ function startOpenCodeAuth(o, exited) {
|
|
|
3676
3778
|
const cmd = commandFor("opencode");
|
|
3677
3779
|
if (!cmd) throw new Error("OpenCode is not installed on this computer.");
|
|
3678
3780
|
const token = crypto3.randomUUID();
|
|
3679
|
-
const dir =
|
|
3680
|
-
|
|
3781
|
+
const dir = path11.join(SESSIONS_DIR, token);
|
|
3782
|
+
fs10.mkdirSync(dir, { recursive: true });
|
|
3681
3783
|
const l = { agentId: o.agentId, cli: "opencode", term: o.term, proc: null, token, dir, resumeId: null, statusLine: "", shots: /* @__PURE__ */ new Set(), session: null };
|
|
3682
3784
|
let over = false;
|
|
3683
3785
|
const end = (code) => {
|
|
@@ -3734,8 +3836,8 @@ function idleHook(live, b) {
|
|
|
3734
3836
|
case "PreToolUse":
|
|
3735
3837
|
return ALLOW;
|
|
3736
3838
|
case "UserPromptSubmit": {
|
|
3737
|
-
const
|
|
3738
|
-
if (!
|
|
3839
|
+
const text4 = String(b.prompt ?? "").trim();
|
|
3840
|
+
if (!text4 || live.term.onIdlePrompt?.(text4)) return {};
|
|
3739
3841
|
return { decision: "block", reason: "The office couldn't take that on as a follow-up right now (see the agent's panel). Nothing was sent." };
|
|
3740
3842
|
}
|
|
3741
3843
|
case "StatusLine":
|
|
@@ -3764,7 +3866,7 @@ function startCliSession(opts, callbacks) {
|
|
|
3764
3866
|
const inBox = !!(box ?? live?.box);
|
|
3765
3867
|
const token = crypto3.randomUUID();
|
|
3766
3868
|
const sessionId = opts.resumeSessionId ?? crypto3.randomUUID();
|
|
3767
|
-
const dir = box ? boxSessionDir(token) :
|
|
3869
|
+
const dir = box ? boxSessionDir(token) : path11.join(SESSIONS_DIR, token);
|
|
3768
3870
|
const started = Date.now();
|
|
3769
3871
|
const statusLine = `\u{1F3E2} Droidsembly${opts.label ? ` \xB7 ${opts.label}` : ""}`;
|
|
3770
3872
|
const toolNames = /* @__PURE__ */ new Map();
|
|
@@ -3791,10 +3893,10 @@ function startCliSession(opts, callbacks) {
|
|
|
3791
3893
|
const collectShots = (all = false) => {
|
|
3792
3894
|
const l2 = live;
|
|
3793
3895
|
if (!l2 || l2.box || cli === "claude" || !opts.browserTesting) return;
|
|
3794
|
-
for (const shot of newScreenshots(
|
|
3896
|
+
for (const shot of newScreenshots(path11.join(l2.dir, "browser"), l2.shots, all ? Infinity : Date.now())) {
|
|
3795
3897
|
l2.shots.add(shot.name);
|
|
3796
3898
|
try {
|
|
3797
|
-
cb.screenshot(
|
|
3899
|
+
cb.screenshot(fs10.readFileSync(shot.file), shot.mime);
|
|
3798
3900
|
} catch {
|
|
3799
3901
|
}
|
|
3800
3902
|
}
|
|
@@ -3842,8 +3944,8 @@ function startCliSession(opts, callbacks) {
|
|
|
3842
3944
|
if (l2?.box && cli !== "claude" && opts.browserTesting) void collectBoxShots().catch(() => void 0).finally(close);
|
|
3843
3945
|
else close();
|
|
3844
3946
|
};
|
|
3845
|
-
const turnEnded = (
|
|
3846
|
-
lastText =
|
|
3947
|
+
const turnEnded = (text4) => {
|
|
3948
|
+
lastText = text4;
|
|
3847
3949
|
cb.tool(null);
|
|
3848
3950
|
clearTimeout(finishTimer);
|
|
3849
3951
|
finishTimer = setTimeout(() => finish({ ok: !turnError, text: lastText, errors: turnError ? [turnError] : [] }, true), FINISH_GRACE_MS);
|
|
@@ -3865,16 +3967,16 @@ function startCliSession(opts, callbacks) {
|
|
|
3865
3967
|
setTimeout(look, 800);
|
|
3866
3968
|
};
|
|
3867
3969
|
term.onInput = watchKeys;
|
|
3868
|
-
const boxScreenshotFile = async (
|
|
3869
|
-
const m =
|
|
3970
|
+
const boxScreenshotFile = async (text4) => {
|
|
3971
|
+
const m = text4.match(/\]\(([^)\s]+\.(png|jpe?g))\)/i);
|
|
3870
3972
|
const b = live?.box;
|
|
3871
3973
|
if (!m || !b) return;
|
|
3872
|
-
const file = m[1].startsWith("/") ? m[1] :
|
|
3974
|
+
const file = m[1].startsWith("/") ? m[1] : path11.posix.join(opts.cwd, m[1]);
|
|
3873
3975
|
const data = await b.api.read(b.boxId, file, { base64: true }).catch(() => null);
|
|
3874
3976
|
if (data) cb.screenshot(Buffer.from(data, "base64"), /png$/i.test(m[2]) ? "image/png" : "image/jpeg");
|
|
3875
3977
|
};
|
|
3876
|
-
const assistantLines = (
|
|
3877
|
-
const lines =
|
|
3978
|
+
const assistantLines = (text4) => {
|
|
3979
|
+
const lines = text4.split("\n");
|
|
3878
3980
|
const out = lines.slice(0, 30).map((l2, i) => ({ kind: "text", text: `${i === 0 ? "\u25CF " : " "}${l2}` }));
|
|
3879
3981
|
if (lines.length > 30) out.push({ kind: "text", text: ` \u2026 (${lines.length - 30} more lines)` });
|
|
3880
3982
|
return out;
|
|
@@ -3905,7 +4007,7 @@ function startCliSession(opts, callbacks) {
|
|
|
3905
4007
|
const event = String(b.hook_event_name ?? "");
|
|
3906
4008
|
const sub = typeof b.agent_id === "string" && b.agent_id !== "";
|
|
3907
4009
|
if (cli === "claude" && !sub && b.session_id !== kept) {
|
|
3908
|
-
const id = resumableSession(b, inBox ? () => b.transcript_exists === true :
|
|
4010
|
+
const id = resumableSession(b, inBox ? () => b.transcript_exists === true : fs10.existsSync);
|
|
3909
4011
|
if (id) {
|
|
3910
4012
|
kept = id;
|
|
3911
4013
|
cb.sessionId(id);
|
|
@@ -3984,13 +4086,13 @@ function startCliSession(opts, callbacks) {
|
|
|
3984
4086
|
return {};
|
|
3985
4087
|
}
|
|
3986
4088
|
case "Stop": {
|
|
3987
|
-
const
|
|
4089
|
+
const text4 = String(b.last_assistant_message ?? "").trim();
|
|
3988
4090
|
turns += 1;
|
|
3989
|
-
if (
|
|
3990
|
-
log(assistantLines(
|
|
3991
|
-
cb.turn?.(
|
|
4091
|
+
if (text4) {
|
|
4092
|
+
log(assistantLines(text4));
|
|
4093
|
+
cb.turn?.(text4);
|
|
3992
4094
|
}
|
|
3993
|
-
turnEnded(
|
|
4095
|
+
turnEnded(text4);
|
|
3994
4096
|
return {};
|
|
3995
4097
|
}
|
|
3996
4098
|
case "StopFailure": {
|
|
@@ -4024,13 +4126,13 @@ function startCliSession(opts, callbacks) {
|
|
|
4024
4126
|
remember(live);
|
|
4025
4127
|
}
|
|
4026
4128
|
}
|
|
4027
|
-
const
|
|
4129
|
+
const text4 = String(b.last_assistant_message ?? "").trim();
|
|
4028
4130
|
turns += 1;
|
|
4029
|
-
if (
|
|
4030
|
-
log(assistantLines(
|
|
4031
|
-
cb.turn?.(
|
|
4131
|
+
if (text4) {
|
|
4132
|
+
log(assistantLines(text4));
|
|
4133
|
+
cb.turn?.(text4);
|
|
4032
4134
|
}
|
|
4033
|
-
turnEnded(
|
|
4135
|
+
turnEnded(text4);
|
|
4034
4136
|
return {};
|
|
4035
4137
|
}
|
|
4036
4138
|
case "TurnError":
|
|
@@ -4059,13 +4161,13 @@ function startCliSession(opts, callbacks) {
|
|
|
4059
4161
|
finish({ ok, text: lastText, errors: ok ? [] : [`${label} exited${exitCode2 ? ` with code ${exitCode2}` : ""} before finishing.`] });
|
|
4060
4162
|
};
|
|
4061
4163
|
const handle = {
|
|
4062
|
-
send(
|
|
4164
|
+
send(text4) {
|
|
4063
4165
|
const proc = live?.proc;
|
|
4064
4166
|
if (done || !proc) return;
|
|
4065
4167
|
busy2();
|
|
4066
4168
|
turnError = null;
|
|
4067
|
-
officePrompts.push(
|
|
4068
|
-
const clean =
|
|
4169
|
+
officePrompts.push(text4.trim());
|
|
4170
|
+
const clean = text4.replace(/\x1b\[20[01]~/g, "").replace(/\r\n?/g, "\n");
|
|
4069
4171
|
launched.push(clean.trim());
|
|
4070
4172
|
quietly(() => proc.write(`\x1B[200~${clean}\x1B[201~`));
|
|
4071
4173
|
setTimeout(() => quietly(() => live?.proc?.write("\r")), 150);
|
|
@@ -4099,8 +4201,8 @@ function startCliSession(opts, callbacks) {
|
|
|
4099
4201
|
const keeper = box ? null : keeperHookUrl();
|
|
4100
4202
|
const events = `${dir}/events.jsonl`;
|
|
4101
4203
|
const hookUrl = box ? events : `${keeper ?? officeUrl}/api/hooks/${token}`;
|
|
4102
|
-
const p = box ?
|
|
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(
|
|
4204
|
+
const p = box ? path11.posix : path11;
|
|
4205
|
+
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(path11.join(dir, "browser"));
|
|
4104
4206
|
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);
|
|
4105
4207
|
if (browserIssue) log([{ kind: "error", text: browserIssue }]);
|
|
4106
4208
|
let prompt = opts.prompt;
|
|
@@ -4112,16 +4214,16 @@ ${JSON.stringify(opts.outputSchema)}`;
|
|
|
4112
4214
|
}
|
|
4113
4215
|
let files;
|
|
4114
4216
|
const boxFiles = [];
|
|
4115
|
-
const put = (file,
|
|
4217
|
+
const put = (file, text4) => box ? boxFiles.push([file, text4]) : fs10.writeFileSync(file, text4);
|
|
4116
4218
|
try {
|
|
4117
4219
|
if (!box) {
|
|
4118
4220
|
writeHelpers();
|
|
4119
|
-
|
|
4221
|
+
fs10.mkdirSync(dir, { recursive: true });
|
|
4120
4222
|
}
|
|
4121
4223
|
const boxHook = `node ${BOX_BIN}/hook.cjs ${events}`;
|
|
4122
4224
|
const settings = {
|
|
4123
4225
|
hooks: Object.fromEntries(HOOK_EVENTS.map((e) => [e, [{ hooks: [box ? { type: "command", command: boxHook, timeout: 30 } : { type: "http", url: hookUrl, timeout: keeper ? 120 : 30 }] }]])),
|
|
4124
|
-
statusLine: box ? { type: "command", command: `node ${BOX_BIN}/statusline.cjs ${events}`, padding: 0 } : { type: "command", command: `${shellArg(process.execPath)} ${shellArg(
|
|
4226
|
+
statusLine: box ? { type: "command", command: `node ${BOX_BIN}/statusline.cjs ${events}`, padding: 0 } : { type: "command", command: `${shellArg(process.execPath)} ${shellArg(path11.join(BIN_DIR, "statusline.cjs"))} ${shellArg(hookUrl)}`, padding: 0 },
|
|
4125
4227
|
...box?.apiKeyHelper ? { apiKeyHelper: box.apiKeyHelper } : {}
|
|
4126
4228
|
};
|
|
4127
4229
|
const servers = {};
|
|
@@ -4154,9 +4256,9 @@ ${JSON.stringify(opts.outputSchema)}`;
|
|
|
4154
4256
|
openCodePermissions: opts.openCodePermissions,
|
|
4155
4257
|
additionalDirectories: opts.additionalDirectories,
|
|
4156
4258
|
files,
|
|
4157
|
-
notify: box ? { script: `${BOX_BIN}/notify.cjs`, url: events } : { script:
|
|
4158
|
-
codexHook: box ? `${BOX_BIN}/codex-hook.cjs` :
|
|
4159
|
-
plugin: box ? `file://${BOX_BIN}/opencode-plugin` : pathToFileURL(
|
|
4259
|
+
notify: box ? { script: `${BOX_BIN}/notify.cjs`, url: events } : { script: path11.join(BIN_DIR, "notify.cjs"), url: hookUrl },
|
|
4260
|
+
codexHook: box ? `${BOX_BIN}/codex-hook.cjs` : path11.join(BIN_DIR, "codex-hook.cjs"),
|
|
4261
|
+
plugin: box ? `file://${BOX_BIN}/opencode-plugin` : pathToFileURL(path11.join(BIN_DIR, "opencode-plugin")).href,
|
|
4160
4262
|
...opts.office && !box ? { officeUrl: `${officeUrl}/api/mcp/${token}` } : {},
|
|
4161
4263
|
browser,
|
|
4162
4264
|
...box ? { node: "node", posix: true } : {}
|
|
@@ -4227,7 +4329,7 @@ ${JSON.stringify(opts.outputSchema)}`;
|
|
|
4227
4329
|
try {
|
|
4228
4330
|
boxFiles.push([`${dir}/launch.json`, JSON.stringify({ file: cmd.file, args: [...cmd.args, ...launch2.args], cwd: opts.cwd, events })]);
|
|
4229
4331
|
if (cli === "opencode") await writeBoxSessionFiles(b.api, b.boxId, dir, boxFiles);
|
|
4230
|
-
else for (const [file,
|
|
4332
|
+
else for (const [file, text4] of boxFiles) await b.api.write(b.boxId, file, text4);
|
|
4231
4333
|
if (done) return;
|
|
4232
4334
|
const pty = boxPty(l, b, term.cols, term.rows, 0, env);
|
|
4233
4335
|
l.proc = pty;
|
|
@@ -4252,30 +4354,30 @@ ${JSON.stringify(opts.outputSchema)}`;
|
|
|
4252
4354
|
}
|
|
4253
4355
|
|
|
4254
4356
|
// server/machines.ts
|
|
4255
|
-
import
|
|
4357
|
+
import fs12 from "node:fs";
|
|
4256
4358
|
|
|
4257
4359
|
// server/deps.ts
|
|
4258
4360
|
import { spawn as spawn2 } from "node:child_process";
|
|
4259
4361
|
import crypto4 from "node:crypto";
|
|
4260
|
-
import
|
|
4261
|
-
import
|
|
4362
|
+
import fs11 from "node:fs/promises";
|
|
4363
|
+
import path12 from "node:path";
|
|
4262
4364
|
var INSTALL_MARKER = ".cubefarm-preview-install";
|
|
4263
4365
|
var INSTALL_TIMEOUT_MS = 15 * 6e4;
|
|
4264
4366
|
var INSTALL_PROGRESS_MS = 6e4;
|
|
4265
4367
|
var MAX_DESK_INSTALLS = 2;
|
|
4266
4368
|
var depsHash = (pkg, lock) => crypto4.createHash("sha256").update(pkg).update("\0").update(lock ?? "").digest("hex");
|
|
4267
4369
|
async function readDeps(dir) {
|
|
4268
|
-
const read = (file) =>
|
|
4370
|
+
const read = (file) => fs11.readFile(path12.join(dir, file), "utf8").catch(() => null);
|
|
4269
4371
|
const [pkg, lock, marker2, nodeModules] = await Promise.all([
|
|
4270
4372
|
read("package.json"),
|
|
4271
4373
|
read("package-lock.json"),
|
|
4272
|
-
read(
|
|
4273
|
-
|
|
4374
|
+
read(path12.join("node_modules", INSTALL_MARKER)),
|
|
4375
|
+
fs11.stat(path12.join(dir, "node_modules")).then((s2) => s2.isDirectory()).catch(() => false)
|
|
4274
4376
|
]);
|
|
4275
4377
|
return { pkg, lock, hash: depsHash(pkg ?? "", lock), marker: marker2 ?? "", nodeModules };
|
|
4276
4378
|
}
|
|
4277
4379
|
var depsCurrent = (s2) => s2.nodeModules && s2.marker === s2.hash;
|
|
4278
|
-
var writeMarker = (dir, hash) =>
|
|
4380
|
+
var writeMarker = (dir, hash) => fs11.writeFile(path12.join(dir, "node_modules", INSTALL_MARKER), hash).catch(() => void 0);
|
|
4279
4381
|
function deskDepsPlan(s2) {
|
|
4280
4382
|
if (s2.pkg === null) return "none";
|
|
4281
4383
|
if (s2.lock === null) return "agent";
|
|
@@ -4390,7 +4492,7 @@ function localMachines(keep) {
|
|
|
4390
4492
|
prepareDesk: (machine, fullName, base, branch, note2) => prepareMachineDesk(machine, fullName, base, branch, note2),
|
|
4391
4493
|
env: (machine) => {
|
|
4392
4494
|
const tmp = machineTmp(machine);
|
|
4393
|
-
|
|
4495
|
+
fs12.mkdirSync(tmp, { recursive: true });
|
|
4394
4496
|
return { TMP: tmp, TEMP: tmp, TMPDIR: tmp };
|
|
4395
4497
|
},
|
|
4396
4498
|
release: (machine, fullName, port) => releaseMachine(machine, fullName, port, keep()),
|
|
@@ -4398,7 +4500,7 @@ function localMachines(keep) {
|
|
|
4398
4500
|
sweep: (machine, fullName, keepBranches) => sweepMachine(machine, fullName, keepBranches),
|
|
4399
4501
|
remove: (machine) => removeMachine(machine),
|
|
4400
4502
|
list: () => listMachines(),
|
|
4401
|
-
exists: async (machine, fullName) =>
|
|
4503
|
+
exists: async (machine, fullName) => fs12.existsSync(machineDesk(machine, fullName)),
|
|
4402
4504
|
installDeps: (machine, fullName, cb) => installDesk(machineDesk(machine, fullName), cb)
|
|
4403
4505
|
};
|
|
4404
4506
|
}
|
|
@@ -4450,7 +4552,7 @@ var openCodeModels = createModelCatalogReader(async (directory) => {
|
|
|
4450
4552
|
if (problem) throw new Error(problem);
|
|
4451
4553
|
try {
|
|
4452
4554
|
const query2 = `?location[directory]=${encodeURIComponent(directory)}`;
|
|
4453
|
-
const [list, selected] = await Promise.all(["/api/model", "/api/model/default"].map((endpoint) => run(cmd.file, [...cmd.args, "api", "get", endpoint + query2], { timeoutMs: 3e4 }).then((
|
|
4555
|
+
const [list, selected] = await Promise.all(["/api/model", "/api/model/default"].map((endpoint) => run(cmd.file, [...cmd.args, "api", "get", endpoint + query2], { timeoutMs: 3e4 }).then((text4) => JSON.parse(text4))));
|
|
4454
4556
|
return sanitizeCatalog(list, selected, directory);
|
|
4455
4557
|
} catch {
|
|
4456
4558
|
throw new Error("Could not read OpenCode models. Check OpenCode connections and retry; manual model entry is still available.");
|
|
@@ -4461,23 +4563,23 @@ var openCodeModels = createModelCatalogReader(async (directory) => {
|
|
|
4461
4563
|
function sanitizeConnections(value) {
|
|
4462
4564
|
const data = value?.data;
|
|
4463
4565
|
if (!Array.isArray(data)) throw new Error("Invalid OpenCode connections");
|
|
4464
|
-
const
|
|
4566
|
+
const text4 = (v) => typeof v === "string" && !!v && v.length <= 512 && !/[\x00-\x1f\x7f]/.test(v);
|
|
4465
4567
|
return data.flatMap((i) => {
|
|
4466
|
-
if (!i || !
|
|
4568
|
+
if (!i || !text4(i.id) || !text4(i.name) || !Array.isArray(i.methods) || !Array.isArray(i.connections)) return [];
|
|
4467
4569
|
return [{
|
|
4468
4570
|
id: i.id,
|
|
4469
4571
|
name: i.name,
|
|
4470
4572
|
methods: i.methods.flatMap((m) => {
|
|
4471
4573
|
if (!m || !["key", "oauth", "command", "external", "env"].includes(String(m.type))) return [];
|
|
4472
4574
|
const id = m.type === "key" || m.type === "env" ? m.type : m.id;
|
|
4473
|
-
if (!
|
|
4474
|
-
return [{ id, type: m.type, label:
|
|
4575
|
+
if (!text4(id)) return [];
|
|
4576
|
+
return [{ id, type: m.type, label: text4(m.label) ? m.label : String(m.type) }];
|
|
4475
4577
|
}),
|
|
4476
4578
|
connections: i.connections.flatMap((c) => {
|
|
4477
4579
|
if (!c || !["credential", "env"].includes(String(c.type))) return [];
|
|
4478
4580
|
const environment = c.type === "env";
|
|
4479
4581
|
const id = environment ? c.name : c.id;
|
|
4480
|
-
if (!
|
|
4582
|
+
if (!text4(id) || !environment && (!text4(c.label) || !["key", "oauth", "external"].includes(String(c.method)))) return [];
|
|
4481
4583
|
return [{ id, label: environment ? id : c.label, method: environment ? "env" : String(c.method), environment, needsAuth: !!c.status }];
|
|
4482
4584
|
})
|
|
4483
4585
|
}];
|
|
@@ -4509,8 +4611,8 @@ async function openCodeConnections(directory) {
|
|
|
4509
4611
|
const problem = await checkOpenCodeVersion(cmd);
|
|
4510
4612
|
if (problem) throw new Error(problem);
|
|
4511
4613
|
try {
|
|
4512
|
-
const
|
|
4513
|
-
return sanitizeConnections(JSON.parse(
|
|
4614
|
+
const text4 = await run(cmd.file, [...cmd.args, "api", "get", `/api/integration?location[directory]=${encodeURIComponent(directory)}`], { timeoutMs: 3e4 });
|
|
4615
|
+
return sanitizeConnections(JSON.parse(text4));
|
|
4514
4616
|
} catch {
|
|
4515
4617
|
throw new Error("Could not read OpenCode connections. No credentials were changed.");
|
|
4516
4618
|
}
|
|
@@ -4518,9 +4620,9 @@ async function openCodeConnections(directory) {
|
|
|
4518
4620
|
|
|
4519
4621
|
// server/previewRunner.ts
|
|
4520
4622
|
import { spawn as spawn3 } from "node:child_process";
|
|
4521
|
-
import
|
|
4623
|
+
import fs13 from "node:fs/promises";
|
|
4522
4624
|
import net2 from "node:net";
|
|
4523
|
-
import
|
|
4625
|
+
import path13 from "node:path";
|
|
4524
4626
|
var PREVIEW_SLUG = "preview";
|
|
4525
4627
|
var PREVIEW_BRANCH = "swarm-preview";
|
|
4526
4628
|
var PREVIEW_TMP = ".preview-tmp";
|
|
@@ -4554,7 +4656,7 @@ async function portOpen(port) {
|
|
|
4554
4656
|
var sleep3 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
4555
4657
|
async function readJson(file) {
|
|
4556
4658
|
try {
|
|
4557
|
-
return JSON.parse(await
|
|
4659
|
+
return JSON.parse(await fs13.readFile(file, "utf8"));
|
|
4558
4660
|
} catch {
|
|
4559
4661
|
return null;
|
|
4560
4662
|
}
|
|
@@ -4599,9 +4701,9 @@ var RealPreview = class {
|
|
|
4599
4701
|
this.check();
|
|
4600
4702
|
await ensureLocalExcludes(job.fullName).catch(() => void 0);
|
|
4601
4703
|
cb.commit(await git(["rev-parse", "--short", "HEAD"], { cwd: wt }).catch(() => ""));
|
|
4602
|
-
const tmp =
|
|
4603
|
-
await
|
|
4604
|
-
const pkg = await readJson(
|
|
4704
|
+
const tmp = path13.join(wt, PREVIEW_TMP);
|
|
4705
|
+
await fs13.mkdir(tmp, { recursive: true });
|
|
4706
|
+
const pkg = await readJson(path13.join(wt, "package.json"));
|
|
4605
4707
|
const command = job.command ?? defaultCommand(pkg);
|
|
4606
4708
|
if (!command) {
|
|
4607
4709
|
this.stopped = true;
|
|
@@ -4663,8 +4765,8 @@ var RealPreview = class {
|
|
|
4663
4765
|
const child = spawn3(cmd, { cwd, env, shell: true, windowsHide: true, detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"] });
|
|
4664
4766
|
this.child = child;
|
|
4665
4767
|
const onData = (buf) => {
|
|
4666
|
-
const
|
|
4667
|
-
const lines =
|
|
4768
|
+
const text4 = this.partial + buf.toString().replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "");
|
|
4769
|
+
const lines = text4.split(/\r?\n|\r/);
|
|
4668
4770
|
this.partial = lines.pop() ?? "";
|
|
4669
4771
|
const out = lines.filter((l) => l.trim());
|
|
4670
4772
|
if (out.length) this.cb.log(out);
|
|
@@ -4686,12 +4788,12 @@ var RealPreview = class {
|
|
|
4686
4788
|
};
|
|
4687
4789
|
var realPreviews = {
|
|
4688
4790
|
start: (job, cb) => new RealPreview(job, cb),
|
|
4689
|
-
hasDefault: async (fullName) =>
|
|
4791
|
+
hasDefault: async (fullName) => fs13.access(path13.join(mainDir(fullName), "package.json")).then(() => true).catch(() => false)
|
|
4690
4792
|
};
|
|
4691
4793
|
|
|
4692
4794
|
// server/officeUpdate.ts
|
|
4693
|
-
import
|
|
4694
|
-
import
|
|
4795
|
+
import fs14 from "node:fs/promises";
|
|
4796
|
+
import path14 from "node:path";
|
|
4695
4797
|
var DRAIN_TIMEOUT_MS = 20 * 6e4;
|
|
4696
4798
|
var POSTPONE_MS = 2 * 60 * 6e4;
|
|
4697
4799
|
function underLauncher(proc = process) {
|
|
@@ -4728,10 +4830,10 @@ function parseLastUpdate(raw) {
|
|
|
4728
4830
|
}
|
|
4729
4831
|
}
|
|
4730
4832
|
async function takeLastUpdate(home) {
|
|
4731
|
-
const file =
|
|
4732
|
-
const raw = await
|
|
4833
|
+
const file = path14.join(home, "last-update.json");
|
|
4834
|
+
const raw = await fs14.readFile(file, "utf8").catch(() => null);
|
|
4733
4835
|
if (raw === null) return null;
|
|
4734
|
-
await
|
|
4836
|
+
await fs14.rm(file, { force: true, maxRetries: 3 }).catch(() => void 0);
|
|
4735
4837
|
return parseLastUpdate(raw);
|
|
4736
4838
|
}
|
|
4737
4839
|
function lastUpdateMessage(u, commits) {
|
|
@@ -4739,8 +4841,8 @@ function lastUpdateMessage(u, commits) {
|
|
|
4739
4841
|
const n = commits === null ? "" : ` (${commits} commit${commits === 1 ? "" : "s"})`;
|
|
4740
4842
|
return `\u2B06\uFE0F Updated the office from ${u.from.slice(0, 7)} to ${u.to.slice(0, 7)}${n}`;
|
|
4741
4843
|
}
|
|
4742
|
-
var OFFICE_DIR =
|
|
4743
|
-
var isSamePath = (a, b) => process.platform === "win32" ?
|
|
4844
|
+
var OFFICE_DIR = path14.resolve(import.meta.dirname, "..");
|
|
4845
|
+
var isSamePath = (a, b) => process.platform === "win32" ? path14.resolve(a).toLowerCase() === path14.resolve(b).toLowerCase() : path14.resolve(a) === path14.resolve(b);
|
|
4744
4846
|
var realOffice = {
|
|
4745
4847
|
launcher: underLauncher(),
|
|
4746
4848
|
head: () => git(["rev-parse", "HEAD"], { cwd: OFFICE_DIR }).catch(() => null),
|
|
@@ -4756,8 +4858,8 @@ var realOffice = {
|
|
|
4756
4858
|
|
|
4757
4859
|
// server/voice.ts
|
|
4758
4860
|
import crypto5 from "node:crypto";
|
|
4759
|
-
import
|
|
4760
|
-
import
|
|
4861
|
+
import fs15 from "node:fs/promises";
|
|
4862
|
+
import path15 from "node:path";
|
|
4761
4863
|
|
|
4762
4864
|
// shared/italianUi.ts
|
|
4763
4865
|
var italianUi = {
|
|
@@ -6602,6 +6704,63 @@ var italianPhoneAccess = {
|
|
|
6602
6704
|
"The preview is hidden until this browser can route its assets securely. Your running app has not been stopped.": "L\u2019anteprima \xE8 nascosta finch\xE9 questo browser non pu\xF2 instradare le risorse in modo sicuro. L\u2019app in esecuzione non \xE8 stata fermata."
|
|
6603
6705
|
};
|
|
6604
6706
|
|
|
6707
|
+
// shared/italianAppStarter.ts
|
|
6708
|
+
var italianAppStarter = {
|
|
6709
|
+
"Conversation history ({count})": "Storico della conversazione ({count})",
|
|
6710
|
+
"Current CEO question": "Domanda attuale del CEO",
|
|
6711
|
+
"Request a plan change": "Richiedi una modifica al piano",
|
|
6712
|
+
"Describe your changes below. Review the new revision before approving.": "Descrivi qui sotto le modifiche. Leggi la nuova revisione prima di approvarla.",
|
|
6713
|
+
"Your answer is saved. Waiting for the next CEO question\u2026": "La risposta \xE8 salvata. In attesa della prossima domanda del CEO\u2026",
|
|
6714
|
+
"Waiting for the CEO interview to start\u2026": "In attesa dell\u2019inizio dell\u2019intervista del CEO\u2026",
|
|
6715
|
+
"Creating project {name}\u2026": "Creazione del progetto {name}\u2026",
|
|
6716
|
+
"Please wait. Do not submit the request again.": "Attendi. Non inviare nuovamente la richiesta.",
|
|
6717
|
+
"Project creation was not confirmed.": "La creazione del progetto non \xE8 stata confermata.",
|
|
6718
|
+
"Check the project list before retrying; the request may already have completed.": "Controlla l\u2019elenco dei progetti prima di riprovare: la richiesta potrebbe essere gi\xE0 stata completata.",
|
|
6719
|
+
"Project created: {name}": "Progetto creato: {name}",
|
|
6720
|
+
"Next: answer the CEO interview. No plan issues or workers start before you approve the plan.": "Ora rispondi all\u2019intervista del CEO. Nessuna issue del piano o attivit\xE0 worker parte prima della tua approvazione del piano.",
|
|
6721
|
+
"The project is now in the office.": "Il progetto \xE8 ora presente nell\u2019ufficio.",
|
|
6722
|
+
"Open project interview": "Apri intervista del progetto",
|
|
6723
|
+
"View project": "Visualizza progetto",
|
|
6724
|
+
"Create another project": "Crea un altro progetto",
|
|
6725
|
+
"CEO conversation": "Conversazione CEO",
|
|
6726
|
+
"Company chat (not a plan approval)": "Chat aziendale (non approva piani)",
|
|
6727
|
+
"New app plan": "Piano nuova app",
|
|
6728
|
+
"Project interview and complete plan": "Intervista progetto e piano completo",
|
|
6729
|
+
"Revision": "Revisione",
|
|
6730
|
+
"interview": "intervista",
|
|
6731
|
+
"awaiting-approval": "in attesa di approvazione",
|
|
6732
|
+
"publishing": "pubblicazione in corso",
|
|
6733
|
+
"ready": "pronto",
|
|
6734
|
+
"paused": "in pausa",
|
|
6735
|
+
"cancelled": "annullato",
|
|
6736
|
+
"pending": "da pubblicare",
|
|
6737
|
+
"in-flight": "richiesta in corso",
|
|
6738
|
+
"confirmed": "confermato",
|
|
6739
|
+
"unknown": "esito da riconciliare",
|
|
6740
|
+
"No plan issues or workers start before explicit approval and confirmed publication.": "Nessuna issue del piano o attivit\xE0 worker parte prima dell\u2019approvazione esplicita e della pubblicazione confermata.",
|
|
6741
|
+
"Do not paste passwords, connection strings or real data. Describe requirements using examples.": "Non incollare password, stringhe di connessione o dati reali. Descrivi i requisiti usando esempi.",
|
|
6742
|
+
"You": "Tu",
|
|
6743
|
+
"Decisions so far": "Decisioni raccolte",
|
|
6744
|
+
"Complete proposed plan": "Piano proposto completo",
|
|
6745
|
+
"Plan fingerprint": "Impronta del piano",
|
|
6746
|
+
"Publication ledger": "Registro di pubblicazione",
|
|
6747
|
+
"Approval applies only to this project, revision and exact tasks. A chat \u201Cyes\u201D does not publish.": "L\u2019approvazione vale solo per questo progetto, revisione e task esatti. Un \u201Cs\xEC\u201D in chat non pubblica.",
|
|
6748
|
+
"I have read the complete plan and its tasks above.": "Ho letto il piano completo e tutti i task sopra.",
|
|
6749
|
+
"I confirm the worker, test/preview and deployment environments; tests and migrations are isolated from production.": "Confermo gli ambienti worker, test/preview e deploy; test e migrazioni sono isolati dalla produzione.",
|
|
6750
|
+
"I confirm local workers for non-transferable data and will keep this computer on.": "Confermo worker locali per i dati non trasferibili e terr\xF2 acceso questo computer.",
|
|
6751
|
+
"Auto-assign is on: confirmed publication may start AI work and use the team\u2019s approved Box resources. No paid account, database or deploy is authorized.": "Auto-assegnazione attiva: la pubblicazione confermata pu\xF2 avviare lavoro AI e usare le risorse Box approvate per il team. Non autorizza account a pagamento, database o deploy.",
|
|
6752
|
+
"Auto-assign is off: publication does not turn it on. No paid account, database or deploy is authorized.": "Auto-assegnazione disattiva: la pubblicazione non la riattiva. Non autorizza account a pagamento, database o deploy.",
|
|
6753
|
+
"Modify plan": "Modifica piano",
|
|
6754
|
+
"Approve plan and create issues": "Approva piano e crea issue",
|
|
6755
|
+
"Resume / reconcile": "Riprendi / riconcilia",
|
|
6756
|
+
"Pause planning": "Metti in pausa",
|
|
6757
|
+
"Cancel planning": "Annulla pianificazione",
|
|
6758
|
+
"Answer or request a plan change\u2026": "Rispondi o richiedi una modifica al piano\u2026",
|
|
6759
|
+
"Project interview answer": "Risposta all\u2019intervista del progetto",
|
|
6760
|
+
"with a README and pushes it to a new {visibility} GitHub repo.": "con un README e lo invia a un nuovo repository GitHub {visibility}.",
|
|
6761
|
+
"The CEO starts a project interview in Chat, even without a brief. Read and approve the complete plan before any plan issues or workers start.": "Il CEO avvia un\u2019intervista per progetto nella Chat, anche senza brief. Leggi e approva il piano completo prima che partano issue del piano o worker."
|
|
6762
|
+
};
|
|
6763
|
+
|
|
6605
6764
|
// shared/i18n.ts
|
|
6606
6765
|
var languageOf = (value) => value === "it" ? "it" : "en";
|
|
6607
6766
|
var italian = {
|
|
@@ -6610,6 +6769,13 @@ var italian = {
|
|
|
6610
6769
|
...italianNavigation,
|
|
6611
6770
|
...italianSpecialized,
|
|
6612
6771
|
...italianPhoneAccess,
|
|
6772
|
+
...italianAppStarter,
|
|
6773
|
+
"Resume task": "Riprendi attivit\xE0",
|
|
6774
|
+
"Resuming\u2026": "Ripresa in corso\u2026",
|
|
6775
|
+
"Resume issue #{number}?": "Riprendere l\u2019issue #{number}?",
|
|
6776
|
+
"Resume issue #{number} with {name}": "Riprendi l\u2019issue #{number} con {name}",
|
|
6777
|
+
"The task has changed. Check the agent before resuming.": "L\u2019attivit\xE0 \xE8 cambiata. Controlla l\u2019agente prima di riprendere.",
|
|
6778
|
+
"Restart preparation for {name} on the same issue and branch, preserving the existing worktree. No reset or duplicate issue. This starts agent work and may consume AI quota.": "Riavvia la preparazione per {name} sulla stessa issue e sullo stesso branch, preservando il worktree esistente. Nessun reset o duplicazione dell\u2019issue. Questa azione avvia il lavoro dell\u2019agente e pu\xF2 consumare quota AI.",
|
|
6613
6779
|
"Shell module": "Modulo della scocca",
|
|
6614
6780
|
"Agent identity": "Identit\xE0 dell\u2019agente",
|
|
6615
6781
|
"She": "Lei",
|
|
@@ -7040,7 +7206,7 @@ var Voice = class {
|
|
|
7040
7206
|
const s2 = await this.readSecrets();
|
|
7041
7207
|
this.key = typeof s2.elevenlabsKey === "string" ? s2.elevenlabsKey : "";
|
|
7042
7208
|
this.rejected = !!this.key && s2.elevenlabsKeyRejected === true;
|
|
7043
|
-
const raw = await
|
|
7209
|
+
const raw = await fs15.readFile(this.manifestFile(), "utf8").catch(() => "");
|
|
7044
7210
|
try {
|
|
7045
7211
|
this.clips = parseManifest(raw ? JSON.parse(raw) : {});
|
|
7046
7212
|
} catch {
|
|
@@ -7105,11 +7271,11 @@ var Voice = class {
|
|
|
7105
7271
|
const m = this.message(id);
|
|
7106
7272
|
if (!m || !speaks(m, s2)) throw new HttpError(404, `No spoken message ${id}`);
|
|
7107
7273
|
const saved = clipsFor(this.clips, m);
|
|
7108
|
-
const first = saved && await
|
|
7274
|
+
const first = saved && await fs15.readFile(path15.join(this.deps.cacheDir, saved[0])).catch(() => null);
|
|
7109
7275
|
if (first) return first;
|
|
7110
|
-
const
|
|
7111
|
-
if (!
|
|
7112
|
-
return this.audio(String(m.id), s2.voiceId, s2.model,
|
|
7276
|
+
const text4 = speechText(m.text);
|
|
7277
|
+
if (!text4) throw new HttpError(404, `Message ${id} has nothing to say aloud`);
|
|
7278
|
+
return this.audio(String(m.id), s2.voiceId, s2.model, text4, m);
|
|
7113
7279
|
}
|
|
7114
7280
|
/**
|
|
7115
7281
|
* GET /api/voice/messages/:id?cached=1&part=N: the phone's ▶. Only clips already on disk, never ElevenLabs: a 404
|
|
@@ -7119,15 +7285,15 @@ var Voice = class {
|
|
|
7119
7285
|
const m = this.message(id);
|
|
7120
7286
|
const files = m && clipsFor(this.clips, m);
|
|
7121
7287
|
const file = files?.[part];
|
|
7122
|
-
const audio = file && await
|
|
7288
|
+
const audio = file && await fs15.readFile(path15.join(this.deps.cacheDir, file)).catch(() => null);
|
|
7123
7289
|
if (!files || !audio) throw new HttpError(404, `Audio for message ${id} is no longer saved.`);
|
|
7124
7290
|
return { audio, parts: files.length };
|
|
7125
7291
|
}
|
|
7126
7292
|
/** DELETE /api/voice/cache: Settings → Voice's "Clear saved clips". */
|
|
7127
7293
|
clearCache() {
|
|
7128
7294
|
return this.cacheOp(async () => {
|
|
7129
|
-
const names = await
|
|
7130
|
-
for (const name of names.filter((n) => n.endsWith(".mp3"))) await
|
|
7295
|
+
const names = await fs15.readdir(this.deps.cacheDir).catch(() => []);
|
|
7296
|
+
for (const name of names.filter((n) => n.endsWith(".mp3"))) await fs15.rm(path15.join(this.deps.cacheDir, name), { force: true, maxRetries: 3 });
|
|
7131
7297
|
this.clips = {};
|
|
7132
7298
|
await this.saveManifest();
|
|
7133
7299
|
return this.measure([]);
|
|
@@ -7140,12 +7306,12 @@ var Voice = class {
|
|
|
7140
7306
|
prune() {
|
|
7141
7307
|
return this.cacheOp(async () => {
|
|
7142
7308
|
const dir = this.deps.cacheDir;
|
|
7143
|
-
const names = (await
|
|
7144
|
-
const stats = await Promise.all(names.map(async (name) => ({ name, st: await
|
|
7309
|
+
const names = (await fs15.readdir(dir).catch(() => [])).filter((n) => n.endsWith(".mp3"));
|
|
7310
|
+
const stats = await Promise.all(names.map(async (name) => ({ name, st: await fs15.stat(path15.join(dir, name)).catch(() => null) })));
|
|
7145
7311
|
const files = stats.flatMap(({ name, st }) => st ? [{ name, mtimeMs: st.mtimeMs, size: st.size }] : []);
|
|
7146
7312
|
const keep = newestClips(this.clips, this.deps.messages());
|
|
7147
7313
|
const gone = new Set(cacheToPrune(files, this.now(), CACHE_MAX_FILES, this.deps.settings().keepDays * DAY_MS, keep));
|
|
7148
|
-
for (const name of [...gone]) await
|
|
7314
|
+
for (const name of [...gone]) await fs15.rm(path15.join(dir, name), { force: true, maxRetries: 3 }).catch(() => gone.delete(name));
|
|
7149
7315
|
const left = files.filter((f) => !gone.has(f.name));
|
|
7150
7316
|
const clips = withoutMissing(this.clips, new Set(left.map((f) => f.name)));
|
|
7151
7317
|
if (Object.keys(clips).length !== Object.keys(this.clips).length) {
|
|
@@ -7166,13 +7332,13 @@ var Voice = class {
|
|
|
7166
7332
|
if (!this.key) throw new HttpError(409, "Add your ElevenLabs API key in Settings \u2192 Voice to talk instead of type, or pick the browser there.");
|
|
7167
7333
|
this.requireKey();
|
|
7168
7334
|
const key = this.key;
|
|
7169
|
-
const
|
|
7335
|
+
const text4 = await this.deps.api.transcribe(key, { audio, type: clipType(contentType), ...this.deps.language?.() === "it" ? { language: "it" } : {} }, AbortSignal.timeout(TRANSCRIBE_TIMEOUT_MS)).catch((err) => {
|
|
7170
7336
|
if (err instanceof VoiceApiError && err.status === 403) throw new HttpError(502, "Your ElevenLabs key may not use Speech to Text: allow it for the key on elevenlabs.io (Developers \u2192 API Keys).");
|
|
7171
7337
|
return this.failed(err, key, "turn your speech into text");
|
|
7172
7338
|
});
|
|
7173
7339
|
const secs = Number.isFinite(ms) ? ` ${(ms / 1e3).toFixed(1)} s` : "";
|
|
7174
7340
|
this.deps.log?.(`voice: transcribed a${secs} clip (${Math.ceil(audio.length / 1024)} KB)`);
|
|
7175
|
-
return
|
|
7341
|
+
return text4.trim();
|
|
7176
7342
|
}
|
|
7177
7343
|
/** GET /api/voice/sample: the settings' Test button, in `voiceId` (default: the chosen voice). */
|
|
7178
7344
|
async sampleAudio(voiceId) {
|
|
@@ -7185,22 +7351,22 @@ var Voice = class {
|
|
|
7185
7351
|
if (s2.provider !== "elevenlabs") throw new HttpError(404, "The CEO isn't voiced by ElevenLabs right now.");
|
|
7186
7352
|
return this.audio("standup", s2.voiceId, s2.model, standupLine(count, part));
|
|
7187
7353
|
}
|
|
7188
|
-
async audio(name, voiceId, model2,
|
|
7354
|
+
async audio(name, voiceId, model2, text4, m) {
|
|
7189
7355
|
if (!VOICE_ID.test(voiceId)) throw new HttpError(400, "Pick an ElevenLabs voice first.");
|
|
7190
7356
|
const language = languageOf(this.deps.language?.());
|
|
7191
7357
|
const hash = crypto5.createHash("sha256").update(`${voiceId}
|
|
7192
7358
|
${model2}
|
|
7193
|
-
${
|
|
7194
|
-
const file =
|
|
7195
|
-
const cached = await
|
|
7359
|
+
${text4}${language === "it" ? "\nit" : ""}`).digest("hex").slice(0, 12);
|
|
7360
|
+
const file = path15.join(this.deps.cacheDir, `${name}-${hash}.mp3`);
|
|
7361
|
+
const cached = await fs15.readFile(file).catch(() => null);
|
|
7196
7362
|
if (cached) {
|
|
7197
|
-
if (m) await this.record(m, [
|
|
7363
|
+
if (m) await this.record(m, [path15.basename(file)]);
|
|
7198
7364
|
return cached;
|
|
7199
7365
|
}
|
|
7200
7366
|
this.requireKey();
|
|
7201
7367
|
const busy2 = this.making.get(file);
|
|
7202
7368
|
if (busy2) return busy2;
|
|
7203
|
-
const made = this.oneAtATime(() => this.synthesize(file, { voiceId, model: model2, text:
|
|
7369
|
+
const made = this.oneAtATime(() => this.synthesize(file, { voiceId, model: model2, text: text4, ...language === "it" ? { language } : {} }, m)).finally(() => this.making.delete(file));
|
|
7204
7370
|
this.making.set(file, made);
|
|
7205
7371
|
return made;
|
|
7206
7372
|
}
|
|
@@ -7213,12 +7379,12 @@ ${text3}${language === "it" ? "\nit" : ""}`).digest("hex").slice(0, 12);
|
|
|
7213
7379
|
this.requireKey();
|
|
7214
7380
|
const key = this.key;
|
|
7215
7381
|
const audio = await this.deps.api.synthesize(key, req, AbortSignal.timeout(SYNTH_TIMEOUT_MS)).catch((err) => this.failed(err, key, "speak the message"));
|
|
7216
|
-
await
|
|
7382
|
+
await fs15.mkdir(this.deps.cacheDir, { recursive: true });
|
|
7217
7383
|
const tmp = `${file}.${process.pid}.tmp`;
|
|
7218
|
-
await
|
|
7219
|
-
await
|
|
7220
|
-
this.deps.log?.(`voice: made a new clip ${
|
|
7221
|
-
if (m) await this.record(m, [
|
|
7384
|
+
await fs15.writeFile(tmp, audio);
|
|
7385
|
+
await fs15.rename(tmp, file);
|
|
7386
|
+
this.deps.log?.(`voice: made a new clip ${path15.basename(file)} (${req.text.length} characters)`);
|
|
7387
|
+
if (m) await this.record(m, [path15.basename(file)]);
|
|
7222
7388
|
else await this.prune();
|
|
7223
7389
|
return audio;
|
|
7224
7390
|
}
|
|
@@ -7254,13 +7420,13 @@ ${text3}${language === "it" ? "\nit" : ""}`).digest("hex").slice(0, 12);
|
|
|
7254
7420
|
await this.prune();
|
|
7255
7421
|
}
|
|
7256
7422
|
manifestFile() {
|
|
7257
|
-
return
|
|
7423
|
+
return path15.join(this.deps.cacheDir, MANIFEST);
|
|
7258
7424
|
}
|
|
7259
7425
|
async saveManifest() {
|
|
7260
|
-
await
|
|
7426
|
+
await fs15.mkdir(this.deps.cacheDir, { recursive: true });
|
|
7261
7427
|
const tmp = `${this.manifestFile()}.${process.pid}.tmp`;
|
|
7262
|
-
await
|
|
7263
|
-
await
|
|
7428
|
+
await fs15.writeFile(tmp, JSON.stringify(this.clips));
|
|
7429
|
+
await fs15.rename(tmp, this.manifestFile());
|
|
7264
7430
|
}
|
|
7265
7431
|
/** The cache view for `files` (what's on disk), told to the clients when it changed. */
|
|
7266
7432
|
measure(files) {
|
|
@@ -7302,15 +7468,15 @@ async function call(key, pathname, init, signal) {
|
|
|
7302
7468
|
}
|
|
7303
7469
|
async function reason(res) {
|
|
7304
7470
|
const body2 = await res.text().catch(() => "");
|
|
7305
|
-
let
|
|
7471
|
+
let text4 = "";
|
|
7306
7472
|
try {
|
|
7307
7473
|
const d = JSON.parse(body2).detail;
|
|
7308
|
-
if (typeof d === "string")
|
|
7309
|
-
else if (Array.isArray(d))
|
|
7310
|
-
else if (d && typeof d === "object")
|
|
7474
|
+
if (typeof d === "string") text4 = d;
|
|
7475
|
+
else if (Array.isArray(d)) text4 = d.map((x) => x?.msg).filter(Boolean).join("; ");
|
|
7476
|
+
else if (d && typeof d === "object") text4 = String(d.message ?? d.status ?? "");
|
|
7311
7477
|
} catch {
|
|
7312
7478
|
}
|
|
7313
|
-
return `${res.status}${
|
|
7479
|
+
return `${res.status}${text4 ? `: ${text4}` : ""}`.slice(0, 200);
|
|
7314
7480
|
}
|
|
7315
7481
|
var s = (v) => typeof v === "string" ? v : "";
|
|
7316
7482
|
function voiceOption(v) {
|
|
@@ -7341,11 +7507,11 @@ var elevenLabs = {
|
|
|
7341
7507
|
}
|
|
7342
7508
|
return out;
|
|
7343
7509
|
},
|
|
7344
|
-
async synthesize(key, { voiceId, model: model2, text:
|
|
7510
|
+
async synthesize(key, { voiceId, model: model2, text: text4, language }, signal) {
|
|
7345
7511
|
const res = await call(
|
|
7346
7512
|
key,
|
|
7347
7513
|
`/v1/text-to-speech/${encodeURIComponent(voiceId)}?output_format=mp3_44100_128`,
|
|
7348
|
-
{ method: "POST", headers: { "Content-Type": "application/json", Accept: "audio/mpeg" }, body: JSON.stringify({ text:
|
|
7514
|
+
{ method: "POST", headers: { "Content-Type": "application/json", Accept: "audio/mpeg" }, body: JSON.stringify({ text: text4, model_id: model2, ...language ? { language_code: language } : {} }) },
|
|
7349
7515
|
signal
|
|
7350
7516
|
);
|
|
7351
7517
|
return Buffer.from(await res.arrayBuffer());
|
|
@@ -7364,8 +7530,8 @@ var elevenLabs = {
|
|
|
7364
7530
|
};
|
|
7365
7531
|
|
|
7366
7532
|
// server/notifier.ts
|
|
7367
|
-
import
|
|
7368
|
-
import
|
|
7533
|
+
import fs16 from "node:fs/promises";
|
|
7534
|
+
import path16 from "node:path";
|
|
7369
7535
|
|
|
7370
7536
|
// shared/browserProtocol.ts
|
|
7371
7537
|
var notificationTag = (id) => `cubefarm-${id}`;
|
|
@@ -7522,8 +7688,8 @@ function webhookHint(channel, w) {
|
|
|
7522
7688
|
function secretValues(w) {
|
|
7523
7689
|
return Object.values(w).flatMap((v) => Object.values(v ?? {}).filter((x) => typeof x === "string" && x.length >= 6));
|
|
7524
7690
|
}
|
|
7525
|
-
function redact2(
|
|
7526
|
-
let out =
|
|
7691
|
+
function redact2(text4, secrets) {
|
|
7692
|
+
let out = text4;
|
|
7527
7693
|
for (const s2 of secrets) if (s2) out = out.split(s2).join("\u2022\u2022\u2022\u2022");
|
|
7528
7694
|
return out.replace(/(https?:\/\/[^/\s]+)\/[^\s]*/g, "$1/\u2022\u2022\u2022\u2022");
|
|
7529
7695
|
}
|
|
@@ -7660,7 +7826,7 @@ var Notifier = class {
|
|
|
7660
7826
|
}
|
|
7661
7827
|
}
|
|
7662
7828
|
try {
|
|
7663
|
-
const raw = JSON.parse(await
|
|
7829
|
+
const raw = JSON.parse(await fs16.readFile(this.deps.pushFile, "utf8"));
|
|
7664
7830
|
const devices = Array.isArray(raw.devices) ? raw.devices : [];
|
|
7665
7831
|
this.push = {
|
|
7666
7832
|
vapid: checkVapidKeys(raw.vapid),
|
|
@@ -7774,10 +7940,10 @@ var Notifier = class {
|
|
|
7774
7940
|
}
|
|
7775
7941
|
webhookRequest(c, n, officeUrl3) {
|
|
7776
7942
|
const json = { "Content-Type": "application/json" };
|
|
7777
|
-
const
|
|
7943
|
+
const text4 = noteText(n, officeUrl3);
|
|
7778
7944
|
const w = this.webhooks;
|
|
7779
7945
|
const { root, topic } = ntfyTarget(w.ntfy.url);
|
|
7780
|
-
return { channel: c, url: root, headers: { ...json, ...w.ntfy.token ? { Authorization: `Bearer ${w.ntfy.token}` } : {} }, body: JSON.stringify(ntfyPayload(n, topic, officeUrl3)), text:
|
|
7946
|
+
return { channel: c, url: root, headers: { ...json, ...w.ntfy.token ? { Authorization: `Bearer ${w.ntfy.token}` } : {} }, body: JSON.stringify(ntfyPayload(n, topic, officeUrl3)), text: text4 };
|
|
7781
7947
|
}
|
|
7782
7948
|
async send(req) {
|
|
7783
7949
|
const status = await this.deps.transport.post(req).catch(() => 0);
|
|
@@ -7786,9 +7952,9 @@ var Notifier = class {
|
|
|
7786
7952
|
this.deps.log(redact2(`notify: ${LABEL[req.channel]} failed: ${why2}`, this.secrets()));
|
|
7787
7953
|
return why2;
|
|
7788
7954
|
}
|
|
7789
|
-
async sendPush(d, payload,
|
|
7955
|
+
async sendPush(d, payload, text4) {
|
|
7790
7956
|
const req = pushRequest(d, payload, this.push.vapid, SUBJECT, this.now());
|
|
7791
|
-
const why2 = await this.send({ channel: "push", ...req, text:
|
|
7957
|
+
const why2 = await this.send({ channel: "push", ...req, text: text4 });
|
|
7792
7958
|
if (why2 && /HTTP (404|410)/.test(why2)) await this.unsubscribe(d.endpoint).catch(() => void 0);
|
|
7793
7959
|
return why2;
|
|
7794
7960
|
}
|
|
@@ -7805,10 +7971,10 @@ var Notifier = class {
|
|
|
7805
7971
|
const file = this.deps.pushFile;
|
|
7806
7972
|
const data = JSON.stringify({ vapid: this.push.vapid, devices: this.push.devices }, null, 2);
|
|
7807
7973
|
const write = this.pushWrites.then(async () => {
|
|
7808
|
-
await
|
|
7809
|
-
await
|
|
7810
|
-
await
|
|
7811
|
-
await
|
|
7974
|
+
await fs16.mkdir(path16.dirname(file), { recursive: true });
|
|
7975
|
+
await fs16.writeFile(`${file}.tmp`, data, { mode: 384 });
|
|
7976
|
+
await fs16.rename(`${file}.tmp`, file);
|
|
7977
|
+
await fs16.chmod(file, 384).catch(() => void 0);
|
|
7812
7978
|
});
|
|
7813
7979
|
this.pushWrites = write.catch(() => void 0);
|
|
7814
7980
|
return write;
|
|
@@ -7833,8 +7999,8 @@ function loadWebhooks(raw) {
|
|
|
7833
7999
|
}
|
|
7834
8000
|
|
|
7835
8001
|
// server/weather.ts
|
|
7836
|
-
import
|
|
7837
|
-
import
|
|
8002
|
+
import fs17 from "node:fs/promises";
|
|
8003
|
+
import path17 from "node:path";
|
|
7838
8004
|
|
|
7839
8005
|
// shared/outside.ts
|
|
7840
8006
|
var WEATHER_KINDS = ["clear", "cloudy", "light-rain", "heavy-rain", "storm", "fog", "snow"];
|
|
@@ -7860,8 +8026,8 @@ function worldEventSettings(base, patch) {
|
|
|
7860
8026
|
return out;
|
|
7861
8027
|
}
|
|
7862
8028
|
var roundCoord = (v) => Math.round(v * 100) / 100;
|
|
7863
|
-
function parseCoordinates(
|
|
7864
|
-
const m = /^\s*(-?\d{1,2}(?:\.\d+)?)\s*[,;\s]\s*(-?\d{1,3}(?:\.\d+)?)\s*$/.exec(
|
|
8029
|
+
function parseCoordinates(text4) {
|
|
8030
|
+
const m = /^\s*(-?\d{1,2}(?:\.\d+)?)\s*[,;\s]\s*(-?\d{1,3}(?:\.\d+)?)\s*$/.exec(text4);
|
|
7865
8031
|
if (!m) return null;
|
|
7866
8032
|
const lat = Number(m[1]);
|
|
7867
8033
|
const lon = Number(m[2]);
|
|
@@ -7980,7 +8146,7 @@ var WeatherService = class {
|
|
|
7980
8146
|
now = () => this.o.now?.() ?? Date.now();
|
|
7981
8147
|
async init() {
|
|
7982
8148
|
try {
|
|
7983
|
-
const cached = parseCache(JSON.parse(await
|
|
8149
|
+
const cached = parseCache(JSON.parse(await fs17.readFile(this.o.file, "utf8")));
|
|
7984
8150
|
this.city = cached.city;
|
|
7985
8151
|
this.view = { place: cached.place, reading: cached.reading, error: null };
|
|
7986
8152
|
} catch {
|
|
@@ -8041,9 +8207,9 @@ var WeatherService = class {
|
|
|
8041
8207
|
this.set({ place: place3, reading: readingFrom(code, wind, this.now()), error: null });
|
|
8042
8208
|
} catch (err) {
|
|
8043
8209
|
if (this.city === city) {
|
|
8044
|
-
const
|
|
8045
|
-
this.o.log(`weather: ${
|
|
8046
|
-
this.set({ ...this.view, error: `${
|
|
8210
|
+
const text4 = why(err);
|
|
8211
|
+
this.o.log(`weather: ${text4}`);
|
|
8212
|
+
this.set({ ...this.view, error: `${text4[0].toUpperCase()}${text4.slice(1)}: showing the calm cycle meanwhile.` });
|
|
8047
8213
|
}
|
|
8048
8214
|
} finally {
|
|
8049
8215
|
this.running = false;
|
|
@@ -8059,9 +8225,9 @@ var WeatherService = class {
|
|
|
8059
8225
|
async save() {
|
|
8060
8226
|
const tmp = `${this.o.file}.tmp`;
|
|
8061
8227
|
try {
|
|
8062
|
-
await
|
|
8063
|
-
await
|
|
8064
|
-
await
|
|
8228
|
+
await fs17.mkdir(path17.dirname(this.o.file), { recursive: true });
|
|
8229
|
+
await fs17.writeFile(tmp, JSON.stringify({ city: this.city, place: this.view.place, reading: this.view.reading }, null, 2));
|
|
8230
|
+
await fs17.rename(tmp, this.o.file);
|
|
8065
8231
|
} catch (err) {
|
|
8066
8232
|
this.o.log(`weather: couldn't save the cache: ${err.message}`);
|
|
8067
8233
|
}
|
|
@@ -8090,6 +8256,7 @@ var realBackend = {
|
|
|
8090
8256
|
listIssues,
|
|
8091
8257
|
listPulls,
|
|
8092
8258
|
createIssue,
|
|
8259
|
+
findPlanIssues,
|
|
8093
8260
|
issueState,
|
|
8094
8261
|
editIssue,
|
|
8095
8262
|
closeIssue,
|
|
@@ -8139,9 +8306,9 @@ var realBackend = {
|
|
|
8139
8306
|
|
|
8140
8307
|
// server/demo.ts
|
|
8141
8308
|
import crypto7 from "node:crypto";
|
|
8142
|
-
import
|
|
8309
|
+
import fs18 from "node:fs";
|
|
8143
8310
|
import http from "node:http";
|
|
8144
|
-
import
|
|
8311
|
+
import path18 from "node:path";
|
|
8145
8312
|
|
|
8146
8313
|
// shared/ops.ts
|
|
8147
8314
|
var needsManager = (q) => q?.status === "needs-human" && !q.ceoLooking;
|
|
@@ -8321,6 +8488,75 @@ function opsView(floors, h, now2) {
|
|
|
8321
8488
|
};
|
|
8322
8489
|
}
|
|
8323
8490
|
|
|
8491
|
+
// server/demoAppStarter.ts
|
|
8492
|
+
var questions = [
|
|
8493
|
+
["Who will use the app, and what is their main action?", "Chi user\xE0 l\u2019app e qual \xE8 la sua azione principale?"],
|
|
8494
|
+
["What data should it remember, and who may see or change it?", "Quali dati deve ricordare e chi pu\xF2 vederli o modificarli?"],
|
|
8495
|
+
["Where should workers develop: this computer or Upstash Boxes?", "Dove lavoreranno i worker: questo computer oppure Upstash Box?"],
|
|
8496
|
+
["Where will isolated tests and previews run?", "Dove saranno eseguiti test e preview isolati?"],
|
|
8497
|
+
["Where will the finished app be published?", "Dove verr\xE0 pubblicata l\u2019app finale?"],
|
|
8498
|
+
["Are synthetic sample data enough, or do you need existing data?", "Bastano dati sintetici di esempio oppure servono dati esistenti?"],
|
|
8499
|
+
["Must any existing data stay local, or can anonymized copies / safe services be used?", "Gli eventuali dati esistenti devono restare locali oppure si possono usare copie anonimizzate o servizi sicuri?"],
|
|
8500
|
+
["What belongs in the MVP, and what must remain outside it?", "Cosa comprende l\u2019MVP e cosa deve restarne escluso?"],
|
|
8501
|
+
["What visual style and device layouts do you want?", "Quale stile visivo e quali dispositivi vuoi supportare?"]
|
|
8502
|
+
];
|
|
8503
|
+
function affirms(text4, choice) {
|
|
8504
|
+
return text4.split(/[.!?;,\n]|\b(?:ma|but)\b/i).some((clause) => {
|
|
8505
|
+
const match = choice.exec(clause);
|
|
8506
|
+
if (!match) return false;
|
|
8507
|
+
const before = clause.slice(0, match.index);
|
|
8508
|
+
const after = clause.slice(match.index + match[0].length);
|
|
8509
|
+
return !/\b(?:non|no|not|without|senza|nessun[oaie]?|né|neither)\b/i.test(before) && !/^\s+(?:non\s+(?:servono|occorrono|sono\s+necessari)|(?:are|is)\s+not\s+(?:needed|required))/i.test(after);
|
|
8510
|
+
});
|
|
8511
|
+
}
|
|
8512
|
+
function demoAppTurn(d, italian2) {
|
|
8513
|
+
const asked = d.messages.filter((m) => m.from === "ceo").length;
|
|
8514
|
+
const answers = d.messages.filter((m) => m.from === "manager");
|
|
8515
|
+
const decisions = answers.map((m) => m.text).join("\n").slice(0, 8e3);
|
|
8516
|
+
if (asked < questions.length) return { decisions, question: questions[asked][italian2 ? 1 : 0] };
|
|
8517
|
+
const a = questions.map((q) => {
|
|
8518
|
+
const at = d.messages.findIndex((m) => m.from === "ceo" && q.includes(m.text));
|
|
8519
|
+
return d.messages.slice(at + 1).find((m) => m.from === "manager")?.text ?? "";
|
|
8520
|
+
});
|
|
8521
|
+
const designQuestion = d.messages.findIndex((m) => m.from === "ceo" && questions[8].includes(m.text));
|
|
8522
|
+
const designAnswer = d.messages.findIndex((m, i) => i > designQuestion && m.from === "manager");
|
|
8523
|
+
const changes = d.messages.slice(designAnswer + 1).filter((m) => m.from === "manager").map((m) => m.text).join("\n");
|
|
8524
|
+
const amendment = changes ? `
|
|
8525
|
+
|
|
8526
|
+
Manager revision requests:
|
|
8527
|
+
${changes}` : "";
|
|
8528
|
+
const existing = affirms(a[5], /\b(?:esistent\w*|existing)\b/i);
|
|
8529
|
+
const workerHost = affirms(a[2], /\b(?:boxes|box|cloud)\b/i) ? "box" : "local";
|
|
8530
|
+
const anonymized = affirms(a[6], /\banon\w*/i);
|
|
8531
|
+
const secure = affirms(a[6], /\b(?:sicur\w*|secure|safe)\b/i);
|
|
8532
|
+
if (existing && workerHost === "box" && !anonymized && !secure)
|
|
8533
|
+
return { decisions, question: italian2 ? "Per i Box scegli una copia anonimizzata o un servizio raggiungibile in sicurezza; nessun dato locale non trasferibile." : "For Boxes choose anonymized copies or a safely reachable service; non-transferable local data needs local workers." };
|
|
8534
|
+
return { decisions, plan: {
|
|
8535
|
+
requirements: (answers[0]?.text ?? "Synthetic demo app") + amendment,
|
|
8536
|
+
users: a[0],
|
|
8537
|
+
dataModel: a[1],
|
|
8538
|
+
mvp: a[7] + amendment,
|
|
8539
|
+
exclusions: "Everything not explicitly in the agreed MVP.",
|
|
8540
|
+
stack: "Suggested React + TypeScript; SQLite with synthetic per-environment seeds. Alternatives remain open; no provider is mandatory.",
|
|
8541
|
+
design: a[8],
|
|
8542
|
+
environments: {
|
|
8543
|
+
workerHost,
|
|
8544
|
+
testPreview: a[3],
|
|
8545
|
+
deployment: a[4],
|
|
8546
|
+
data: existing ? "existing" : "sample",
|
|
8547
|
+
dataAccess: !existing ? "sample" : workerHost === "local" ? "local-only" : anonymized ? "anonymized-copy" : "secure-service",
|
|
8548
|
+
database: "SQLite for this synthetic demo; confirm suitability for the chosen deployment.",
|
|
8549
|
+
isolation: "Disposable test and preview databases, separate from production. Migrations tested only on synthetic seeds or approved anonymized copies.",
|
|
8550
|
+
prerequisites: "Verify runtime and database tooling in each environment. No provisioning or deploy is authorized. Local workers require this computer on."
|
|
8551
|
+
},
|
|
8552
|
+
risks: "Synthetic demo proposal, not a certification of real infrastructure. SQLite to Postgres can require code and migration changes.",
|
|
8553
|
+
tasks: [
|
|
8554
|
+
{ id: "foundation", title: "Create the agreed application foundation", body: "Implement the approved stack and design tokens. Configure separate development, preview and disposable test databases; supply synthetic seed and migration commands. Acceptance: tests and build pass without production access or committed secrets.", dependsOn: [] },
|
|
8555
|
+
{ id: "mvp", title: "Implement the approved MVP", body: `Implement: ${a[7]}${amendment}. Acceptance: ownership rules and core actions work end to end; regression tests and accessible desktop/mobile UI pass. Document prerequisites and deployment steps without deploying.`, dependsOn: ["foundation"] }
|
|
8556
|
+
]
|
|
8557
|
+
} };
|
|
8558
|
+
}
|
|
8559
|
+
|
|
8324
8560
|
// server/demo.ts
|
|
8325
8561
|
var now = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
8326
8562
|
function issue(n, title, body2, fullName, labels = []) {
|
|
@@ -8333,10 +8569,10 @@ var closedIssues = /* @__PURE__ */ new Set();
|
|
|
8333
8569
|
var stalls = /* @__PURE__ */ new Map();
|
|
8334
8570
|
var signOuts = /* @__PURE__ */ new Map();
|
|
8335
8571
|
var fakeSha = () => crypto7.randomBytes(20).toString("hex");
|
|
8336
|
-
var NUMBERS_FILE =
|
|
8572
|
+
var NUMBERS_FILE = path18.join(HOME_DIR, "demo-github.json");
|
|
8337
8573
|
function restoreNumbers() {
|
|
8338
8574
|
try {
|
|
8339
|
-
const saved = JSON.parse(
|
|
8575
|
+
const saved = JSON.parse(fs18.readFileSync(NUMBERS_FILE, "utf8"));
|
|
8340
8576
|
for (const r of repos.values()) if (Number.isInteger(saved[r.fullName])) r.nextNumber = Math.max(r.nextNumber, saved[r.fullName]);
|
|
8341
8577
|
} catch {
|
|
8342
8578
|
}
|
|
@@ -8344,9 +8580,9 @@ function restoreNumbers() {
|
|
|
8344
8580
|
function takeNumber(r) {
|
|
8345
8581
|
const n = r.nextNumber++;
|
|
8346
8582
|
try {
|
|
8347
|
-
|
|
8348
|
-
|
|
8349
|
-
|
|
8583
|
+
fs18.mkdirSync(HOME_DIR, { recursive: true });
|
|
8584
|
+
fs18.writeFileSync(`${NUMBERS_FILE}.tmp`, JSON.stringify(Object.fromEntries([...repos.values()].map((x) => [x.fullName, x.nextNumber]))));
|
|
8585
|
+
fs18.renameSync(`${NUMBERS_FILE}.tmp`, NUMBERS_FILE);
|
|
8350
8586
|
} catch (err) {
|
|
8351
8587
|
console.warn("could not save the demo PR numbers", err);
|
|
8352
8588
|
}
|
|
@@ -8469,7 +8705,7 @@ function screenshotSvg(title, url, hue) {
|
|
|
8469
8705
|
</svg>`;
|
|
8470
8706
|
}
|
|
8471
8707
|
function issueScript(opts, cb, issueNumber, issueTitle) {
|
|
8472
|
-
const branch =
|
|
8708
|
+
const branch = path18.basename(opts.cwd);
|
|
8473
8709
|
const hue = issueNumber * 67 % 360;
|
|
8474
8710
|
const file = ["src/App.tsx", "src/components/TodoList.tsx", "src/api/routes.ts", "src/styles.css"][issueNumber % 4];
|
|
8475
8711
|
const port = 5200 + issueNumber % 50;
|
|
@@ -8562,9 +8798,9 @@ function fakeSession(opts, cb, fullName) {
|
|
|
8562
8798
|
if (opts.task === "analysis") {
|
|
8563
8799
|
cb.sessionId(opts.resumeSessionId ?? `demo-analysis-${crypto7.randomUUID()}`);
|
|
8564
8800
|
const timer = setTimeout(() => {
|
|
8565
|
-
const
|
|
8566
|
-
cb.log([{ kind: "text", text:
|
|
8567
|
-
cb.finished({ ok: true, text:
|
|
8801
|
+
const text4 = opts.systemAppend?.includes("Office language: Italian") ? `Analisi demo di ${fullName}: nessun file modificato, nessuna issue o PR creata. Un agente reale leggerebbe il checkout e risponderebbe alla tua richiesta.` : `Demo analysis of ${fullName}: no files changed, no issue or PR created. A real agent would read the checkout and answer your request.`;
|
|
8802
|
+
cb.log([{ kind: "text", text: text4 }]);
|
|
8803
|
+
cb.finished({ ok: true, text: text4, costUsd: 0, turns: 1, errors: [] });
|
|
8568
8804
|
}, 500);
|
|
8569
8805
|
return { send: () => void 0, stop: () => {
|
|
8570
8806
|
clearTimeout(timer);
|
|
@@ -8655,9 +8891,9 @@ function fakeSession(opts, cb, fullName) {
|
|
|
8655
8891
|
pr.mergeable = "MERGEABLE";
|
|
8656
8892
|
runChecks(pr, false);
|
|
8657
8893
|
}
|
|
8658
|
-
const
|
|
8659
|
-
cb.log([{ kind: "text", text:
|
|
8660
|
-
cb.finished({ ok: true, text:
|
|
8894
|
+
const text4 = pushes ? `\u25CF Fixed PR #${number} and pushed. Ready for another QA round.` : nudged ? "NO CHANGE NEEDED: main already makes the toolbar wrap, so the PR is right as it is." : "\u25CF The toolbar wraps on narrow screens now. Ready for another QA round.";
|
|
8895
|
+
cb.log([{ kind: "text", text: text4 }]);
|
|
8896
|
+
cb.finished({ ok: true, text: text4, costUsd, turns, errors: [] });
|
|
8661
8897
|
return;
|
|
8662
8898
|
}
|
|
8663
8899
|
const repo = repos.get(fullName);
|
|
@@ -8669,7 +8905,7 @@ function fakeSession(opts, cb, fullName) {
|
|
|
8669
8905
|
number: n,
|
|
8670
8906
|
title,
|
|
8671
8907
|
url,
|
|
8672
|
-
headRefName: `swarm/issue-${number}-${
|
|
8908
|
+
headRefName: `swarm/issue-${number}-${path18.basename(opts.cwd).replace(/-[0-9a-f]{4}$/, "")}`,
|
|
8673
8909
|
state: "OPEN",
|
|
8674
8910
|
isDraft: false,
|
|
8675
8911
|
mergeable: "MERGEABLE",
|
|
@@ -8709,11 +8945,11 @@ function fakeSession(opts, cb, fullName) {
|
|
|
8709
8945
|
};
|
|
8710
8946
|
timers.push(setTimeout(step, 600));
|
|
8711
8947
|
return {
|
|
8712
|
-
send(
|
|
8948
|
+
send(text4) {
|
|
8713
8949
|
timers.push(
|
|
8714
8950
|
setTimeout(() => {
|
|
8715
8951
|
if (stopped || stalled) return;
|
|
8716
|
-
cb.log([{ kind: "text", text: `\u25CF Got it \u2014 "${
|
|
8952
|
+
cb.log([{ kind: "text", text: `\u25CF Got it \u2014 "${text4.slice(0, 60)}". Adjusting my approach.` }]);
|
|
8717
8953
|
}, 1500)
|
|
8718
8954
|
);
|
|
8719
8955
|
},
|
|
@@ -8759,12 +8995,12 @@ function inTerminal(opts, cb, start) {
|
|
|
8759
8995
|
write: (data) => {
|
|
8760
8996
|
for (const ch of data.replace(/\x1b\[[0-9;?]*[A-Za-z~]|\x1b./g, "")) {
|
|
8761
8997
|
if (ch === "\r") {
|
|
8762
|
-
const
|
|
8998
|
+
const text4 = line.trim();
|
|
8763
8999
|
line = "";
|
|
8764
9000
|
term.write("\r\n");
|
|
8765
|
-
if (
|
|
8766
|
-
cb.log([{ kind: "manager", text: `\u25B6 Typed in the terminal: ${
|
|
8767
|
-
handle.send(
|
|
9001
|
+
if (text4 && handle) {
|
|
9002
|
+
cb.log([{ kind: "manager", text: `\u25B6 Typed in the terminal: ${text4}` }]);
|
|
9003
|
+
handle.send(text4);
|
|
8768
9004
|
}
|
|
8769
9005
|
} else if (ch === "\x7F" || ch === "\b") {
|
|
8770
9006
|
if (line) term.write("\b \b");
|
|
@@ -8843,6 +9079,23 @@ async function fakeTrim(stillIdle) {
|
|
|
8843
9079
|
return { freed: Math.round((300 + Math.random() * 600) * 2 ** 20), removed: ["node_modules", "dist"], skipped: [] };
|
|
8844
9080
|
}
|
|
8845
9081
|
function createDemoBackend(scale = null) {
|
|
9082
|
+
const planIssues = /* @__PURE__ */ new Map();
|
|
9083
|
+
const planningDir = path18.join(HOME_DIR, "demo-planning-github");
|
|
9084
|
+
const planningRepos = /* @__PURE__ */ new Set();
|
|
9085
|
+
for (const file of fs18.existsSync(planningDir) ? fs18.readdirSync(planningDir).filter((f) => f.endsWith(".json")) : []) {
|
|
9086
|
+
const saved = JSON.parse(fs18.readFileSync(path18.join(planningDir, file), "utf8"));
|
|
9087
|
+
const name = saved.repo.fullName;
|
|
9088
|
+
repos.set(name, saved.repo);
|
|
9089
|
+
bareRepos.add(name);
|
|
9090
|
+
planningRepos.add(name);
|
|
9091
|
+
planIssues.set(name, saved.issues);
|
|
9092
|
+
}
|
|
9093
|
+
const savePlanning = (name) => {
|
|
9094
|
+
const planningFile = path18.join(planningDir, `${encodeURIComponent(name)}.json`);
|
|
9095
|
+
fs18.mkdirSync(planningDir, { recursive: true });
|
|
9096
|
+
fs18.writeFileSync(`${planningFile}.tmp`, JSON.stringify({ repo: repos.get(name), issues: planIssues.get(name) ?? [] }));
|
|
9097
|
+
fs18.renameSync(`${planningFile}.tmp`, planningFile);
|
|
9098
|
+
};
|
|
8846
9099
|
if (scale) seedBigCompany(scale.floors);
|
|
8847
9100
|
restoreNumbers();
|
|
8848
9101
|
const deskRepo = /* @__PURE__ */ new Map();
|
|
@@ -8888,6 +9141,11 @@ function createDemoBackend(scale = null) {
|
|
|
8888
9141
|
return { fullName: newRepo(name, opts.description), path: `/demo/projects/${name}` };
|
|
8889
9142
|
},
|
|
8890
9143
|
listIssues: async (fullName) => {
|
|
9144
|
+
if (!repos.has(fullName)) {
|
|
9145
|
+
repos.set(fullName, { fullName, description: "", issues: [], pulls: [], nextNumber: 1 });
|
|
9146
|
+
bareRepos.add(fullName);
|
|
9147
|
+
restoreNumbers();
|
|
9148
|
+
}
|
|
8891
9149
|
const r = repos.get(fullName);
|
|
8892
9150
|
if (r && scale) topUp(r, scale.agents * 2);
|
|
8893
9151
|
return [...r?.issues ?? []];
|
|
@@ -8902,8 +9160,14 @@ function createDemoBackend(scale = null) {
|
|
|
8902
9160
|
if (!r) throw new Error("Unknown repo");
|
|
8903
9161
|
const n = takeNumber(r);
|
|
8904
9162
|
r.issues.push(issue(n, title, body2, fullName, labels));
|
|
9163
|
+
if (body2.includes("<!-- droidsembly-plan:")) {
|
|
9164
|
+
planningRepos.add(fullName);
|
|
9165
|
+
planIssues.set(fullName, [...planIssues.get(fullName) ?? [], { number: n, title, body: body2 }]);
|
|
9166
|
+
savePlanning(fullName);
|
|
9167
|
+
}
|
|
8905
9168
|
return n;
|
|
8906
9169
|
},
|
|
9170
|
+
findPlanIssues: async (fullName, marker2) => (planIssues.get(fullName) ?? []).filter((i) => i.body.includes(marker2)),
|
|
8907
9171
|
issueState: async (fullName, number) => {
|
|
8908
9172
|
const r = repos.get(fullName);
|
|
8909
9173
|
return r?.issues.some((i) => i.number === number) ? "OPEN" : closedIssues.has(`${fullName}#${number}`) || forgotten(fullName, number) ? "CLOSED" : null;
|
|
@@ -8913,6 +9177,11 @@ function createDemoBackend(scale = null) {
|
|
|
8913
9177
|
if (!i) throw new Error(`Unknown issue #${number}`);
|
|
8914
9178
|
if (edit.body !== void 0) i.body = edit.body;
|
|
8915
9179
|
i.labels = [...i.labels.filter((l) => !edit.removeLabels?.includes(l)), ...(edit.addLabels ?? []).filter((l) => !i.labels.includes(l))];
|
|
9180
|
+
const planned = planIssues.get(fullName)?.find((p) => p.number === number);
|
|
9181
|
+
if (planned) {
|
|
9182
|
+
planned.body = i.body;
|
|
9183
|
+
savePlanning(fullName);
|
|
9184
|
+
}
|
|
8916
9185
|
},
|
|
8917
9186
|
mergePull: async (fullName, number, _method, headSha) => {
|
|
8918
9187
|
const r = repos.get(fullName);
|
|
@@ -8926,6 +9195,7 @@ function createDemoBackend(scale = null) {
|
|
|
8926
9195
|
setTimeout(() => {
|
|
8927
9196
|
for (const n of pr.closesIssues) closedIssues.add(`${fullName}#${n}`);
|
|
8928
9197
|
r.issues = r.issues.filter((i) => !pr.closesIssues.includes(i.number));
|
|
9198
|
+
if (planningRepos.has(fullName)) savePlanning(fullName);
|
|
8929
9199
|
}, 2e4).unref();
|
|
8930
9200
|
},
|
|
8931
9201
|
closeIssue: async (fullName, number) => {
|
|
@@ -8933,6 +9203,7 @@ function createDemoBackend(scale = null) {
|
|
|
8933
9203
|
if (!r?.issues.some((i) => i.number === number)) throw new Error(`Issue #${number} is not open`);
|
|
8934
9204
|
closedIssues.add(`${fullName}#${number}`);
|
|
8935
9205
|
r.issues = r.issues.filter((i) => i.number !== number);
|
|
9206
|
+
if (planningRepos.has(fullName)) savePlanning(fullName);
|
|
8936
9207
|
},
|
|
8937
9208
|
updateBranch: async (fullName, number) => {
|
|
8938
9209
|
const pr = repos.get(fullName)?.pulls.find((p) => p.number === number);
|
|
@@ -9001,7 +9272,8 @@ Closes #${pr.closesIssues[0] ?? "?"}`,
|
|
|
9001
9272
|
},
|
|
9002
9273
|
issueDetails: async (fullName, number) => {
|
|
9003
9274
|
const i = repos.get(fullName)?.issues.find((x) => x.number === number);
|
|
9004
|
-
|
|
9275
|
+
const planned = planIssues.get(fullName)?.find((x) => x.number === number);
|
|
9276
|
+
return { title: i?.title ?? planned?.title ?? `Issue #${number}`, body: i?.body ?? planned?.body ?? "", createdAt: i?.createdAt };
|
|
9005
9277
|
},
|
|
9006
9278
|
commentPull: async (fullName, number) => `https://github.com/${fullName}/pull/${number}#issuecomment-${Date.now()}`,
|
|
9007
9279
|
uploadEvidence: async (fullName, filePath) => `https://github.com/${fullName}/raw/swarm-qa-evidence/${filePath}`,
|
|
@@ -9318,7 +9590,7 @@ function ceoSession(opts, cb) {
|
|
|
9318
9590
|
return out;
|
|
9319
9591
|
};
|
|
9320
9592
|
const read = (file, lines) => step([{ kind: "tool", tool: "Read", text: `\u23FA Read ${file}` }, { kind: "result", text: ` \u23BF Read ${lines} lines` }]);
|
|
9321
|
-
const think = (
|
|
9593
|
+
const think = (text4) => step([{ kind: "thinking", text: "\u273B Thinking\u2026" }, { kind: "text", text: `\u25CF ${text4}` }], 1800);
|
|
9322
9594
|
const short = (s2, n = 48) => s2.length > n ? `${s2.slice(0, n - 1).trim()}\u2026` : s2;
|
|
9323
9595
|
const refused = (out) => out.replace(/^Refused: /, "");
|
|
9324
9596
|
const after = (s2, added) => {
|
|
@@ -9416,17 +9688,17 @@ Acceptance criteria:
|
|
|
9416
9688
|
await use("escalate", { floor, pr, reason: `I tried ${tool2}, but the office refused: ${refused(out)}` });
|
|
9417
9689
|
return `PR #${pr} on floor ${floor} is stuck and I couldn't move it, so it's with you now.`;
|
|
9418
9690
|
},
|
|
9419
|
-
async chat(
|
|
9691
|
+
async chat(text4) {
|
|
9420
9692
|
const s2 = await status();
|
|
9421
9693
|
await think("Reading your message.");
|
|
9422
|
-
const close =
|
|
9694
|
+
const close = text4.match(/\bclose #(\d+)[\s,:;.-]*(.*)/i);
|
|
9423
9695
|
const closeFloor = close && (s2.floors.find((f) => f.backlog.some((i) => i.number === Number(close[1]))) ?? s2.floors[0]);
|
|
9424
9696
|
if (close && closeFloor) {
|
|
9425
9697
|
const reason2 = close[2].trim() || "No longer wanted.";
|
|
9426
9698
|
const out = await use("close_issue", { floor: closeFloor.floor, number: Number(close[1]), reason: reason2 });
|
|
9427
9699
|
return out.startsWith("Refused") ? `I couldn't close #${close[1]}: ${refused(out)}` : `Done: ${out} I left "${short(reason2, 80)}" on it as a comment.`;
|
|
9428
9700
|
}
|
|
9429
|
-
if (/\b(hire|hiring|grow|team|bigger)\b/i.test(
|
|
9701
|
+
if (/\b(hire|hiring|grow|team|bigger)\b/i.test(text4)) {
|
|
9430
9702
|
if (!s2.floors.length) return "There are no floors yet: add a project first, and I will size its team.";
|
|
9431
9703
|
const room = s2.floors.filter((f2) => plannedSize(f2.team) < f2.team.max);
|
|
9432
9704
|
if (!room.length) return `Every floor is at its most agents (${s2.floors[0].team.max}). Raise it in Settings \u2192 Most agents per floor, and I'll grow the busiest one.`;
|
|
@@ -9471,19 +9743,25 @@ Acceptance criteria:
|
|
|
9471
9743
|
"SWARM_HOME=/tmp/cubefarm-demo SWARM_PORT=5260 node --import tsx server/index.ts --demo",
|
|
9472
9744
|
"```",
|
|
9473
9745
|
"",
|
|
9474
|
-
`> I'm the demo CEO, so I can't act on "${short(
|
|
9746
|
+
`> I'm the demo CEO, so I can't act on "${short(text4)}", but the real one would. See the [coding agent docs](${opts.cli === "opencode" ? "https://opencode.ai/v2/docs/" : "https://docs.claude.com/en/docs/claude-code/overview"}).`
|
|
9475
9747
|
].join("\n");
|
|
9476
9748
|
}
|
|
9477
9749
|
};
|
|
9478
9750
|
const prompt = opts.prompt;
|
|
9751
|
+
const interview = opts.systemAppend.includes("# CEO app-starter \u2014 planning only");
|
|
9479
9752
|
const where = prompt.match(/[Ff]loor (\d+) \(([^,)]+)/);
|
|
9480
9753
|
const triage2 = prompt.match(/^Triage: pull request #(\d+) on floor (\d+)/);
|
|
9481
|
-
const run2 =
|
|
9482
|
-
|
|
9754
|
+
const run2 = interview ? async () => {
|
|
9755
|
+
const d = JSON.parse(opts.systemAppend.split("Persistent context:\n")[1]);
|
|
9756
|
+
const out = await office.call("update_app_plan", demoAppTurn(d, opts.systemAppend.includes("Office language: Italian")));
|
|
9757
|
+
if (out.startsWith("Refused:")) throw new Error(out);
|
|
9758
|
+
return out;
|
|
9759
|
+
} : triage2 ? () => scripts.triage(Number(triage2[2]), Number(triage2[1]), prompt) : /no longer needs triage/.test(prompt) ? async () => "Nothing to do." : /just joined the company/.test(prompt) ? () => scripts.onboard(Number(where?.[1]), where?.[2] ?? "") : /has a brief for floor/.test(prompt) ? () => scripts.plan(Number(where?.[1]), prompt.match(/"""([\s\S]*?)"""/)?.[1]?.trim() ?? "") : /Periodic review/.test(prompt) ? () => scripts.review() : () => scripts.chat(prompt.split("\n").slice(1).join(" ").trim() || prompt);
|
|
9760
|
+
const finish = (ok, text4, error) => {
|
|
9483
9761
|
if (done) return;
|
|
9484
9762
|
done = true;
|
|
9485
9763
|
cb.tool(null);
|
|
9486
|
-
cb.finished({ ok, text:
|
|
9764
|
+
cb.finished({ ok, text: text4, costUsd: ok ? 0.4 + Math.random() : 0.05, turns: 6 + Math.floor(Math.random() * 10), errors: error ? [error] : [] });
|
|
9487
9765
|
};
|
|
9488
9766
|
timers.push(
|
|
9489
9767
|
setTimeout(async () => {
|
|
@@ -9499,13 +9777,13 @@ Acceptance criteria:
|
|
|
9499
9777
|
}, 500)
|
|
9500
9778
|
);
|
|
9501
9779
|
return {
|
|
9502
|
-
send(
|
|
9780
|
+
send(text4) {
|
|
9503
9781
|
timers.push(
|
|
9504
9782
|
setTimeout(() => {
|
|
9505
9783
|
if (stopped || done) return;
|
|
9506
|
-
const said =
|
|
9784
|
+
const said = text4.split("keep it short):\n").pop()?.trim() || text4;
|
|
9507
9785
|
cb.log([{ kind: "text", text: `\u25CF Noted: "${short(said, 70)}"` }]);
|
|
9508
|
-
cb.turn?.(
|
|
9786
|
+
cb.turn?.(text4.includes("Office language: Italian") ? `Ricevuto, ne terr\xF2 conto: "${short(said, 90)}"` : `Noted, I'll factor that in: "${short(said, 90)}"`);
|
|
9509
9787
|
}, 1500)
|
|
9510
9788
|
);
|
|
9511
9789
|
},
|
|
@@ -9553,9 +9831,9 @@ var demoVoice = {
|
|
|
9553
9831
|
if (/bad/i.test(key)) throw new VoiceApiError(401, "401: invalid_api_key (demo)");
|
|
9554
9832
|
},
|
|
9555
9833
|
listVoices: async () => demoVoices,
|
|
9556
|
-
synthesize: async (_key, { text:
|
|
9834
|
+
synthesize: async (_key, { text: text4, voiceId }) => {
|
|
9557
9835
|
await new Promise((r) => setTimeout(r, 300));
|
|
9558
|
-
return demoChime(
|
|
9836
|
+
return demoChime(text4.length, voiceId);
|
|
9559
9837
|
},
|
|
9560
9838
|
transcribe: async () => {
|
|
9561
9839
|
await new Promise((r) => setTimeout(r, 400));
|
|
@@ -9566,9 +9844,9 @@ var demoNotify = {
|
|
|
9566
9844
|
demoWebhooks: {
|
|
9567
9845
|
ntfy: { url: "https://ntfy.sh/cubefarm-demo-office" }
|
|
9568
9846
|
},
|
|
9569
|
-
post: async ({ channel, url, text:
|
|
9847
|
+
post: async ({ channel, url, text: text4 }) => {
|
|
9570
9848
|
const ok = !/bad/i.test(url);
|
|
9571
|
-
console.log(`\u{1F514} demo ${channel}${ok ? "" : ' (fails: "bad" address)'} would get: ${
|
|
9849
|
+
console.log(`\u{1F514} demo ${channel}${ok ? "" : ' (fails: "bad" address)'} would get: ${text4.replace(/\n/g, " \u23CE ")}`);
|
|
9572
9850
|
return ok ? 200 : 404;
|
|
9573
9851
|
}
|
|
9574
9852
|
};
|
|
@@ -9745,8 +10023,8 @@ function demoSignIn(o, logins, exited) {
|
|
|
9745
10023
|
}
|
|
9746
10024
|
|
|
9747
10025
|
// server/journal.ts
|
|
9748
|
-
import
|
|
9749
|
-
import
|
|
10026
|
+
import fs19 from "node:fs/promises";
|
|
10027
|
+
import path19 from "node:path";
|
|
9750
10028
|
|
|
9751
10029
|
// shared/journal.ts
|
|
9752
10030
|
var KEYFRAME_MS = 10 * 6e4;
|
|
@@ -9770,8 +10048,8 @@ var SECRET_PATTERNS = [
|
|
|
9770
10048
|
[/\b(api[_-]?key|access[_-]?token|auth[_-]?token|secret|password|passwd|token)(["']?\s*[=:]\s*)("[^"]*"|'[^']*'|[^\s,;}]+)/gi, `$1$2${REDACTED}`],
|
|
9771
10049
|
[/\b(?=[\w-]*\d)(?=[\w-]*[a-z])(?=[\w-]*[A-Z])[\w-]{32,}/g, REDACTED]
|
|
9772
10050
|
];
|
|
9773
|
-
function redact3(
|
|
9774
|
-
let out =
|
|
10051
|
+
function redact3(text4, secrets = []) {
|
|
10052
|
+
let out = text4;
|
|
9775
10053
|
for (const s2 of secrets) if (s2 && s2.length >= 6 && out.includes(s2)) out = out.split(s2).join(REDACTED);
|
|
9776
10054
|
for (const [re, to] of SECRET_PATTERNS) out = out.replace(re, to);
|
|
9777
10055
|
return out;
|
|
@@ -10243,12 +10521,12 @@ function parseRange(q, now2) {
|
|
|
10243
10521
|
return { from, to, seek: q.seek === "1" || q.seek === "true" };
|
|
10244
10522
|
}
|
|
10245
10523
|
async function writeAtomic(file, data) {
|
|
10246
|
-
await
|
|
10524
|
+
await fs19.mkdir(path19.dirname(file), { recursive: true });
|
|
10247
10525
|
const tmp = `${file}.tmp`;
|
|
10248
|
-
await
|
|
10526
|
+
await fs19.writeFile(tmp, data);
|
|
10249
10527
|
for (let i = 0; ; i++) {
|
|
10250
10528
|
try {
|
|
10251
|
-
await
|
|
10529
|
+
await fs19.rename(tmp, file);
|
|
10252
10530
|
return;
|
|
10253
10531
|
} catch (err) {
|
|
10254
10532
|
const code = err.code;
|
|
@@ -10350,7 +10628,7 @@ var Journal = class {
|
|
|
10350
10628
|
const start = prev && at <= prev.start ? prev.start + 1 : at;
|
|
10351
10629
|
const day = dayKey(start);
|
|
10352
10630
|
const frame = this.opts.frame();
|
|
10353
|
-
const seg = { day, start, file:
|
|
10631
|
+
const seg = { day, start, file: path19.join(this.opts.dir, day, `${start}.ndjson`), lines: [], bytes: 0, events: 0, dirty: false };
|
|
10354
10632
|
this.push(seg, boot ? { t: start, k: frame, boot: true } : { t: start, k: frame });
|
|
10355
10633
|
this.last = frameKeys(frame);
|
|
10356
10634
|
this.cur = seg;
|
|
@@ -10369,24 +10647,24 @@ var Journal = class {
|
|
|
10369
10647
|
const tmp = [];
|
|
10370
10648
|
let days = [];
|
|
10371
10649
|
try {
|
|
10372
|
-
days = (await
|
|
10650
|
+
days = (await fs19.readdir(this.opts.dir)).filter((d) => DAY_DIR.test(d));
|
|
10373
10651
|
} catch {
|
|
10374
10652
|
return { segments, tmp, days };
|
|
10375
10653
|
}
|
|
10376
10654
|
for (const day of days) {
|
|
10377
|
-
const dir =
|
|
10655
|
+
const dir = path19.join(this.opts.dir, day);
|
|
10378
10656
|
let names = [];
|
|
10379
10657
|
try {
|
|
10380
|
-
names = await
|
|
10658
|
+
names = await fs19.readdir(dir);
|
|
10381
10659
|
} catch {
|
|
10382
10660
|
continue;
|
|
10383
10661
|
}
|
|
10384
10662
|
for (const name of names) {
|
|
10385
|
-
const file =
|
|
10663
|
+
const file = path19.join(dir, name);
|
|
10386
10664
|
if (withTmp && name.endsWith(".tmp")) tmp.push(file);
|
|
10387
10665
|
const m = SEGMENT_FILE.exec(name);
|
|
10388
10666
|
if (!m || file === this.cur?.file) continue;
|
|
10389
|
-
const st = await
|
|
10667
|
+
const st = await fs19.stat(file).catch(() => null);
|
|
10390
10668
|
if (st?.isFile()) segments.push({ day, start: Number(m[1]), bytes: st.size, file });
|
|
10391
10669
|
}
|
|
10392
10670
|
}
|
|
@@ -10398,17 +10676,17 @@ var Journal = class {
|
|
|
10398
10676
|
const { segments, tmp, days } = await this.files(boot);
|
|
10399
10677
|
const current = this.cur ? [{ day: this.cur.day, start: this.cur.start, bytes: this.cur.bytes, file: this.cur.file }] : [];
|
|
10400
10678
|
const gone = toPrune([...segments, ...current], this.now(), { keepDays: this.opts.keepDays ?? KEEP_DAYS, maxBytes: this.opts.maxBytes ?? MAX_BYTES, keep: this.cur?.start });
|
|
10401
|
-
for (const f of [...gone.map((g) => g.file), ...tmp]) await
|
|
10679
|
+
for (const f of [...gone.map((g) => g.file), ...tmp]) await fs19.rm(f, { force: true, maxRetries: 3 }).catch(() => void 0);
|
|
10402
10680
|
for (const g of gone) for (const k of this.summaries.keys()) if (k.startsWith(`${g.file}|`)) this.summaries.delete(k);
|
|
10403
10681
|
for (const day of days) {
|
|
10404
|
-
const dir =
|
|
10405
|
-
const left = await
|
|
10406
|
-
if (left && left.length === 0) await
|
|
10682
|
+
const dir = path19.join(this.opts.dir, day);
|
|
10683
|
+
const left = await fs19.readdir(dir).catch(() => null);
|
|
10684
|
+
if (left && left.length === 0) await fs19.rm(dir, { recursive: true, force: true, maxRetries: 3 }).catch(() => void 0);
|
|
10407
10685
|
}
|
|
10408
10686
|
return gone.length;
|
|
10409
10687
|
}
|
|
10410
10688
|
readRaw(f) {
|
|
10411
|
-
return
|
|
10689
|
+
return fs19.readFile(f.file, "utf8").catch(() => "");
|
|
10412
10690
|
}
|
|
10413
10691
|
currentRaw() {
|
|
10414
10692
|
return this.cur ? this.cur.lines.join("\n") : "";
|
|
@@ -10461,12 +10739,12 @@ var Journal = class {
|
|
|
10461
10739
|
if (!lines.length || !isFrame(lines[0])) throw new Error("a day starts with a keyframe");
|
|
10462
10740
|
const day = dayKey(lines[0].t);
|
|
10463
10741
|
if (day === this.cur?.day) throw new HttpError(409, "Today is being recorded: a sample day must be another day");
|
|
10464
|
-
const dir =
|
|
10465
|
-
await
|
|
10466
|
-
for (const k of this.summaries.keys()) if (k.startsWith(`${dir}${
|
|
10742
|
+
const dir = path19.join(this.opts.dir, day);
|
|
10743
|
+
await fs19.rm(dir, { recursive: true, force: true, maxRetries: 3 });
|
|
10744
|
+
for (const k of this.summaries.keys()) if (k.startsWith(`${dir}${path19.sep}`)) this.summaries.delete(k);
|
|
10467
10745
|
let chunk = [];
|
|
10468
10746
|
const write = async () => {
|
|
10469
|
-
if (chunk.length) await writeAtomic(
|
|
10747
|
+
if (chunk.length) await writeAtomic(path19.join(dir, `${chunk[0].t}.ndjson`), `${chunk.map((l) => JSON.stringify(l)).join("\n")}
|
|
10470
10748
|
`);
|
|
10471
10749
|
};
|
|
10472
10750
|
for (const l of lines) {
|
|
@@ -10721,18 +10999,18 @@ function passHeaders(headers) {
|
|
|
10721
10999
|
for (const [k, v] of Object.entries(headers)) if (v !== void 0 && !HOP.test(k)) out[k] = v;
|
|
10722
11000
|
return out;
|
|
10723
11001
|
}
|
|
10724
|
-
function upstream(target, req, body2, onResponse, onError,
|
|
11002
|
+
function upstream(target, req, body2, onResponse, onError, path25 = req.url) {
|
|
10725
11003
|
const headers = { ...req.headers, host: `localhost:${target}`, "accept-encoding": "identity" };
|
|
10726
11004
|
for (const k of Object.keys(headers)) if (HOP.test(k)) delete headers[k];
|
|
10727
11005
|
const send2 = (host, retry) => {
|
|
10728
|
-
const up = http2.request({ host, port: target, method: req.method, path:
|
|
11006
|
+
const up = http2.request({ host, port: target, method: req.method, path: path25, headers }, onResponse);
|
|
10729
11007
|
up.once("error", (err) => retry && err.code === "ECONNREFUSED" ? send2("::1", false) : onError(err));
|
|
10730
11008
|
up.end(body2);
|
|
10731
11009
|
};
|
|
10732
11010
|
send2("127.0.0.1", true);
|
|
10733
11011
|
}
|
|
10734
|
-
function tunnel(target, req, socket, head,
|
|
10735
|
-
const lines = [`${req.method} ${
|
|
11012
|
+
function tunnel(target, req, socket, head, path25 = req.url) {
|
|
11013
|
+
const lines = [`${req.method} ${path25} HTTP/${req.httpVersion}`];
|
|
10736
11014
|
for (let i = 0; i < req.rawHeaders.length; i += 2) {
|
|
10737
11015
|
const name = req.rawHeaders[i];
|
|
10738
11016
|
lines.push(`${name}: ${/^host$/i.test(name) ? `localhost:${target}` : req.rawHeaders[i + 1]}`);
|
|
@@ -11046,8 +11324,8 @@ var BOUNDS = { x: 24, zMin: -16, zMax: 18, yMin: -1, yMax: 5, floorMin: -1, floo
|
|
|
11046
11324
|
var HELD_KINDS = ["ball", "mug", "blaster"];
|
|
11047
11325
|
function cleanText(raw, max) {
|
|
11048
11326
|
if (typeof raw !== "string") return "";
|
|
11049
|
-
const
|
|
11050
|
-
return Array.from(
|
|
11327
|
+
const text4 = raw.slice(0, max * 8).normalize("NFC").replace(/[\p{Cc}\p{Cf}\p{Co}\p{Cs}\p{Zl}\p{Zp}]/gu, " ").replace(new RegExp("(\\p{M}{2})\\p{M}+", "gu"), "$1").replace(/\s+/g, " ").trim();
|
|
11328
|
+
return Array.from(text4).slice(0, max).join("").trim();
|
|
11051
11329
|
}
|
|
11052
11330
|
var cleanName = (raw, fallback = DEFAULT_NAME) => cleanText(raw, NAME_MAX) || fallback;
|
|
11053
11331
|
var cleanLabel = (raw) => cleanText(raw, LABEL_MAX);
|
|
@@ -11464,9 +11742,9 @@ var PresenceHub = class {
|
|
|
11464
11742
|
};
|
|
11465
11743
|
|
|
11466
11744
|
// server/swarm.ts
|
|
11467
|
-
import
|
|
11468
|
-
import
|
|
11469
|
-
import
|
|
11745
|
+
import fs23 from "node:fs/promises";
|
|
11746
|
+
import path23 from "node:path";
|
|
11747
|
+
import crypto11 from "node:crypto";
|
|
11470
11748
|
|
|
11471
11749
|
// shared/agentDefaults.ts
|
|
11472
11750
|
var DEFAULT_CLI = "opencode";
|
|
@@ -11601,8 +11879,8 @@ function analysisPrompt(name, fullName) {
|
|
|
11601
11879
|
}
|
|
11602
11880
|
|
|
11603
11881
|
// server/boxMachines.ts
|
|
11604
|
-
import
|
|
11605
|
-
import
|
|
11882
|
+
import fs20 from "node:fs/promises";
|
|
11883
|
+
import path20 from "node:path";
|
|
11606
11884
|
|
|
11607
11885
|
// server/boxHelpers.ts
|
|
11608
11886
|
var PUT = String.raw`
|
|
@@ -12106,19 +12384,19 @@ var BoxMachines = class {
|
|
|
12106
12384
|
return pending2;
|
|
12107
12385
|
}
|
|
12108
12386
|
async saveLeftovers(fullName, machine, data) {
|
|
12109
|
-
const dir =
|
|
12110
|
-
await
|
|
12387
|
+
const dir = path20.join(HOME_DIR, "leftovers", fullName.replace("/", "__"));
|
|
12388
|
+
await fs20.mkdir(dir, { recursive: true });
|
|
12111
12389
|
const base = `machine-${machine}-${stamp2(/* @__PURE__ */ new Date())}`;
|
|
12112
|
-
let file =
|
|
12113
|
-
for (let n = 2; await
|
|
12114
|
-
await
|
|
12390
|
+
let file = path20.join(dir, `${base}.patch`);
|
|
12391
|
+
for (let n = 2; await fs20.stat(file).then(() => true, () => false); n++) file = path20.join(dir, `${base}-${n}.patch`);
|
|
12392
|
+
await fs20.writeFile(file, data);
|
|
12115
12393
|
return file;
|
|
12116
12394
|
}
|
|
12117
12395
|
};
|
|
12118
12396
|
|
|
12119
12397
|
// server/ceo.ts
|
|
12120
12398
|
import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
|
|
12121
|
-
import { z as
|
|
12399
|
+
import { z as z3 } from "zod";
|
|
12122
12400
|
|
|
12123
12401
|
// shared/issues.ts
|
|
12124
12402
|
function blockers(body2, open) {
|
|
@@ -12278,7 +12556,7 @@ function agentPromptPreview({ slug: slug2, linked, ...i }) {
|
|
|
12278
12556
|
]
|
|
12279
12557
|
};
|
|
12280
12558
|
}
|
|
12281
|
-
var ceoPromptPreview = (
|
|
12559
|
+
var ceoPromptPreview = (text4) => ({ kind: "ceo", parts: [{ label: "Office instructions", text: text4 }] });
|
|
12282
12560
|
|
|
12283
12561
|
// server/triage.ts
|
|
12284
12562
|
var MAX_TRIAGES = 2;
|
|
@@ -12300,11 +12578,232 @@ function checkTriageTarget(r) {
|
|
|
12300
12578
|
if (r.status !== "needs-human") throw new HttpError(409, `PR #${r.pr} isn't stuck: it is ${r.status ?? "not in QA"}.`);
|
|
12301
12579
|
}
|
|
12302
12580
|
|
|
12581
|
+
// server/appStarter.ts
|
|
12582
|
+
import crypto10 from "node:crypto";
|
|
12583
|
+
import { readFileSync } from "node:fs";
|
|
12584
|
+
import { z as z2 } from "zod";
|
|
12585
|
+
|
|
12586
|
+
// shared/appStarter.ts
|
|
12587
|
+
var planningHeld = (draft) => !!draft && draft.status !== "ready";
|
|
12588
|
+
var compatibleHost = (draft, host) => !draft || draft.status === "ready" && draft.plan?.environments.workerHost === host;
|
|
12589
|
+
function appPlanText(p) {
|
|
12590
|
+
const e = p.environments;
|
|
12591
|
+
return [
|
|
12592
|
+
`## Requirements
|
|
12593
|
+
${p.requirements}`,
|
|
12594
|
+
`## Users
|
|
12595
|
+
${p.users}`,
|
|
12596
|
+
`## Data model
|
|
12597
|
+
${p.dataModel}`,
|
|
12598
|
+
`## MVP
|
|
12599
|
+
${p.mvp}`,
|
|
12600
|
+
`## Exclusions
|
|
12601
|
+
${p.exclusions}`,
|
|
12602
|
+
`## Stack / alternatives
|
|
12603
|
+
${p.stack}`,
|
|
12604
|
+
`## Design
|
|
12605
|
+
${p.design}`,
|
|
12606
|
+
`## Environments / data
|
|
12607
|
+
Worker: ${e.workerHost}
|
|
12608
|
+
|
|
12609
|
+
Test / preview: ${e.testPreview}
|
|
12610
|
+
|
|
12611
|
+
Deployment: ${e.deployment}
|
|
12612
|
+
|
|
12613
|
+
Data: ${e.data} / ${e.dataAccess}
|
|
12614
|
+
|
|
12615
|
+
Database: ${e.database}
|
|
12616
|
+
|
|
12617
|
+
Isolation: ${e.isolation}
|
|
12618
|
+
|
|
12619
|
+
Prerequisites: ${e.prerequisites}`,
|
|
12620
|
+
`## Risks
|
|
12621
|
+
${p.risks}`,
|
|
12622
|
+
"## Tasks",
|
|
12623
|
+
...p.tasks.map((t) => `### ${t.id}: ${t.title}
|
|
12624
|
+
${t.body}
|
|
12625
|
+
|
|
12626
|
+
Depends on tasks: ${t.dependsOn.join(", ") || "\u2014"}`)
|
|
12627
|
+
].join("\n\n");
|
|
12628
|
+
}
|
|
12629
|
+
|
|
12630
|
+
// server/appStarter.ts
|
|
12631
|
+
var text3 = z2.string().trim().min(1).max(4e3);
|
|
12632
|
+
var appPlanSchema = z2.object({
|
|
12633
|
+
requirements: text3,
|
|
12634
|
+
users: text3,
|
|
12635
|
+
dataModel: text3,
|
|
12636
|
+
mvp: text3,
|
|
12637
|
+
exclusions: text3,
|
|
12638
|
+
stack: text3,
|
|
12639
|
+
design: text3,
|
|
12640
|
+
risks: text3,
|
|
12641
|
+
environments: z2.object({
|
|
12642
|
+
workerHost: z2.enum(["local", "box"]),
|
|
12643
|
+
testPreview: text3,
|
|
12644
|
+
deployment: text3,
|
|
12645
|
+
data: z2.enum(["sample", "existing"]),
|
|
12646
|
+
dataAccess: z2.enum(["sample", "local-only", "anonymized-copy", "secure-service"]),
|
|
12647
|
+
database: text3,
|
|
12648
|
+
isolation: text3,
|
|
12649
|
+
prerequisites: text3
|
|
12650
|
+
}).strict(),
|
|
12651
|
+
tasks: z2.array(z2.object({
|
|
12652
|
+
id: z2.string().regex(/^[a-z][a-z0-9-]{0,39}$/),
|
|
12653
|
+
title: z2.string().trim().min(1).max(120),
|
|
12654
|
+
body: text3,
|
|
12655
|
+
dependsOn: z2.array(z2.string()).max(10)
|
|
12656
|
+
}).strict()).min(1).max(12)
|
|
12657
|
+
}).strict();
|
|
12658
|
+
function planningText(value) {
|
|
12659
|
+
if (/(?:[a-z][a-z0-9+.-]*:\/\/)[^\s/]+:[^\s/@]+@|-----BEGIN .*PRIVATE KEY-----|\b(?:sk-[a-zA-Z0-9_-]{16,}|gh[pousr]_[a-zA-Z0-9]{16,})|\b(?:password|passwd|token|secret|api[_-]?key)\s*[:=]\s*["']?[^\s"']{4,}/i.test(value))
|
|
12660
|
+
throw new HttpError(400, "Do not put credentials, connection strings or data dumps in planning. Use synthetic descriptions.");
|
|
12661
|
+
return value;
|
|
12662
|
+
}
|
|
12663
|
+
function newAppStarter(brief) {
|
|
12664
|
+
planningText(brief);
|
|
12665
|
+
return {
|
|
12666
|
+
id: crypto10.randomUUID(),
|
|
12667
|
+
revision: 1,
|
|
12668
|
+
status: "interview",
|
|
12669
|
+
messages: brief ? [{ id: crypto10.randomUUID(), from: "manager", text: brief }] : [],
|
|
12670
|
+
decisions: "",
|
|
12671
|
+
ledger: []
|
|
12672
|
+
};
|
|
12673
|
+
}
|
|
12674
|
+
function checkDraft(d, ref) {
|
|
12675
|
+
if (!d || d.id !== ref.draftId || d.revision !== ref.revision)
|
|
12676
|
+
throw new HttpError(409, "This planning revision is stale. Read the current project plan.");
|
|
12677
|
+
}
|
|
12678
|
+
function validatePlan(input) {
|
|
12679
|
+
const result = appPlanSchema.safeParse(input);
|
|
12680
|
+
if (!result.success) throw new HttpError(400, result.error.message);
|
|
12681
|
+
const p = result.data;
|
|
12682
|
+
planningText(JSON.stringify(p));
|
|
12683
|
+
if (appPlanText(p).length > 3e4) throw new HttpError(400, "Plan exceeds 30000 characters.");
|
|
12684
|
+
const e = p.environments;
|
|
12685
|
+
if (e.data === "sample" !== (e.dataAccess === "sample"))
|
|
12686
|
+
throw new HttpError(400, "Describe how existing data can safely be used.");
|
|
12687
|
+
if (e.dataAccess === "local-only" && e.workerHost !== "local")
|
|
12688
|
+
throw new HttpError(400, "Non-transferable local data needs confirmed local workers; SQLite or Docker alone does not.");
|
|
12689
|
+
const ids = new Set(p.tasks.map((t) => t.id));
|
|
12690
|
+
if (ids.size !== p.tasks.length) throw new HttpError(400, "Task IDs must be unique.");
|
|
12691
|
+
const visit = (id, seen = []) => {
|
|
12692
|
+
if (seen.includes(id)) throw new HttpError(400, "Task dependencies form a cycle.");
|
|
12693
|
+
const t = p.tasks.find((t2) => t2.id === id);
|
|
12694
|
+
if (!t) throw new HttpError(400, `Unknown dependency ${id}.`);
|
|
12695
|
+
if (/Depends on #\d+/i.test(t.body)) throw new HttpError(400, "Use stable task IDs for dependencies, not issue numbers.");
|
|
12696
|
+
return Math.max(0, ...t.dependsOn.map((dep) => 1 + visit(dep, [...seen, id])));
|
|
12697
|
+
};
|
|
12698
|
+
for (const t of p.tasks) if (visit(t.id) > 2) throw new HttpError(400, "Keep dependency chains to two steps.");
|
|
12699
|
+
return p;
|
|
12700
|
+
}
|
|
12701
|
+
var planHash = (p) => crypto10.createHash("sha256").update(JSON.stringify(p)).digest("hex");
|
|
12702
|
+
var planningSkill = () => readFileSync(new URL("./skills/ceo-app-starter.md", import.meta.url), "utf8");
|
|
12703
|
+
function presentPlan(d, input, decisions) {
|
|
12704
|
+
if (!["interview", "awaiting-approval"].includes(d.status) || d.ledger.length)
|
|
12705
|
+
throw new HttpError(409, "This draft is not editable.");
|
|
12706
|
+
const plan = validatePlan(input);
|
|
12707
|
+
planningText(decisions);
|
|
12708
|
+
d.plan = plan;
|
|
12709
|
+
d.decisions = decisions;
|
|
12710
|
+
d.revision++;
|
|
12711
|
+
d.hash = planHash(plan);
|
|
12712
|
+
delete d.approved;
|
|
12713
|
+
d.status = "awaiting-approval";
|
|
12714
|
+
}
|
|
12715
|
+
function approvePlan(d, hash, confirmedEnvironments, confirmedLocal) {
|
|
12716
|
+
if (d.status !== "awaiting-approval" || !d.plan || d.hash !== hash || hash !== planHash(d.plan))
|
|
12717
|
+
throw new HttpError(409, "Only the exact displayed revision can be approved, once.");
|
|
12718
|
+
if (!confirmedEnvironments || d.plan.environments.dataAccess === "local-only" && !confirmedLocal)
|
|
12719
|
+
throw new HttpError(400, "Confirm isolated test/preview environments and, if needed, local workers with the computer kept on.");
|
|
12720
|
+
d.approved = { revision: d.revision, hash, at: Date.now(), environments: true, localWorkers: confirmedLocal };
|
|
12721
|
+
d.ledger = d.plan.tasks.map((t) => ({ taskId: t.id, state: "pending" }));
|
|
12722
|
+
d.status = "publishing";
|
|
12723
|
+
}
|
|
12724
|
+
var taskMarker = (d, taskId) => `<!-- droidsembly-plan:${d.id}:${d.approved.revision}:${d.approved.hash}:${taskId} -->`;
|
|
12725
|
+
function taskBody(d, taskId) {
|
|
12726
|
+
const t = d.plan.tasks.find((t2) => t2.id === taskId);
|
|
12727
|
+
const deps = t.dependsOn.map((id) => {
|
|
12728
|
+
const entry = d.ledger.find((l) => l.taskId === id);
|
|
12729
|
+
if (entry?.state !== "confirmed" || !entry.number) throw new Error("Dependencies are not confirmed.");
|
|
12730
|
+
return `#${entry.number}`;
|
|
12731
|
+
});
|
|
12732
|
+
return `${deps.length ? `Depends on ${deps.join(", ")}
|
|
12733
|
+
|
|
12734
|
+
` : ""}${t.body}
|
|
12735
|
+
|
|
12736
|
+
${taskMarker(d, t.id)}
|
|
12737
|
+
|
|
12738
|
+
---
|
|
12739
|
+
Approved project plan (revision ${d.approved.revision})
|
|
12740
|
+
|
|
12741
|
+
${appPlanText(d.plan)}`;
|
|
12742
|
+
}
|
|
12743
|
+
async function publishPlan(d, remote2, persist, active) {
|
|
12744
|
+
if (!d.plan || !d.approved || !d.approved.environments || d.plan.environments.dataAccess === "local-only" && !d.approved.localWorkers || d.approved.hash !== planHash(d.plan) || d.approved.revision !== d.revision)
|
|
12745
|
+
throw new HttpError(409, "No exact approved plan.");
|
|
12746
|
+
const live = () => active() && d.status === "publishing";
|
|
12747
|
+
try {
|
|
12748
|
+
for (const entry of d.ledger.filter((l) => l.state === "confirmed")) {
|
|
12749
|
+
if (!live()) return;
|
|
12750
|
+
const task = d.plan.tasks.find((t) => t.id === entry.taskId);
|
|
12751
|
+
const actual = await remote2.details(entry.number);
|
|
12752
|
+
if (actual.title !== task.title || actual.body !== taskBody(d, task.id))
|
|
12753
|
+
throw new Error("A previously confirmed issue was changed.");
|
|
12754
|
+
}
|
|
12755
|
+
while (live()) {
|
|
12756
|
+
const entry = d.ledger.find((l) => l.state !== "confirmed" && d.plan.tasks.find((t) => t.id === l.taskId).dependsOn.every((id) => d.ledger.find((l2) => l2.taskId === id)?.state === "confirmed"));
|
|
12757
|
+
if (!entry) break;
|
|
12758
|
+
const task = d.plan.tasks.find((t) => t.id === entry.taskId);
|
|
12759
|
+
const body2 = taskBody(d, task.id);
|
|
12760
|
+
if (entry.state === "in-flight" || entry.state === "unknown") {
|
|
12761
|
+
const matches = await remote2.find(taskMarker(d, task.id));
|
|
12762
|
+
if (!live()) return;
|
|
12763
|
+
if (matches.length !== 1 || matches[0].title !== task.title || matches[0].body !== body2)
|
|
12764
|
+
throw new Error("Ambiguous GitHub outcome. Reconcile the marked issue; no automatic recreation or deletion.");
|
|
12765
|
+
entry.number = matches[0].number;
|
|
12766
|
+
} else {
|
|
12767
|
+
entry.state = "in-flight";
|
|
12768
|
+
await persist();
|
|
12769
|
+
if (!live()) return;
|
|
12770
|
+
try {
|
|
12771
|
+
entry.number = await remote2.create(task.title, body2);
|
|
12772
|
+
} catch (err) {
|
|
12773
|
+
entry.state = "unknown";
|
|
12774
|
+
throw err;
|
|
12775
|
+
}
|
|
12776
|
+
}
|
|
12777
|
+
const actual = await remote2.details(entry.number);
|
|
12778
|
+
if (actual.title !== task.title || actual.body !== body2) throw new Error("Published issue differs from the approved task/dependencies.");
|
|
12779
|
+
entry.state = "confirmed";
|
|
12780
|
+
await persist();
|
|
12781
|
+
}
|
|
12782
|
+
if (live() && d.ledger.every((l) => l.state === "confirmed")) {
|
|
12783
|
+
for (const entry of d.ledger) {
|
|
12784
|
+
if (!live()) return;
|
|
12785
|
+
const task = d.plan.tasks.find((t) => t.id === entry.taskId);
|
|
12786
|
+
const actual = await remote2.details(entry.number);
|
|
12787
|
+
if (actual.title !== task.title || actual.body !== taskBody(d, task.id))
|
|
12788
|
+
throw new Error("A published issue was changed.");
|
|
12789
|
+
}
|
|
12790
|
+
if (!live()) return;
|
|
12791
|
+
d.status = "ready";
|
|
12792
|
+
delete d.problem;
|
|
12793
|
+
await persist();
|
|
12794
|
+
}
|
|
12795
|
+
} catch {
|
|
12796
|
+
if (d.status === "publishing") d.status = "paused";
|
|
12797
|
+
d.problem = "Publication paused: GitHub outcome may be ambiguous. Reconcile marked issues before resuming; no automatic recreation or deletion.";
|
|
12798
|
+
await persist();
|
|
12799
|
+
}
|
|
12800
|
+
}
|
|
12801
|
+
|
|
12303
12802
|
// server/ceo.ts
|
|
12304
12803
|
var NOT_ASKED = "Only the manager decides on new work, and they haven't asked for any in this job. Suggest it in your final message instead; they can ask you to file it.";
|
|
12305
12804
|
var askedFor = (job) => job.kind === "plan" || job.kind === "chat";
|
|
12306
|
-
var EFFORT =
|
|
12307
|
-
var CLI =
|
|
12805
|
+
var EFFORT = z3.enum(["low", "medium", "high", "xhigh", "max"]);
|
|
12806
|
+
var CLI = z3.enum(["claude", "codex", "opencode"]);
|
|
12308
12807
|
function createOfficeTools(h) {
|
|
12309
12808
|
const run2 = async (fn) => {
|
|
12310
12809
|
try {
|
|
@@ -12314,6 +12813,12 @@ function createOfficeTools(h) {
|
|
|
12314
12813
|
}
|
|
12315
12814
|
};
|
|
12316
12815
|
const defs = [
|
|
12816
|
+
...h.updateAppPlan ? [tool(
|
|
12817
|
+
"update_app_plan",
|
|
12818
|
+
"Save the current new-app interview decisions and one next question, OR present a complete plan for explicit manager approval. Never publishes issues or approves.",
|
|
12819
|
+
{ decisions: z3.string().max(8e3), question: z3.string().min(1).max(2e3).optional(), plan: appPlanSchema.optional() },
|
|
12820
|
+
(a) => run2(() => h.updateAppPlan(a))
|
|
12821
|
+
)] : [],
|
|
12317
12822
|
tool(
|
|
12318
12823
|
"company_status",
|
|
12319
12824
|
"Everything about the company right now: settings, every floor (repo, clone path, brief, profile, QA brief), its team and throughput, backlog, pull requests and QA, team changes waiting for the manager and their recent decisions. Call this first.",
|
|
@@ -12323,21 +12828,21 @@ function createOfficeTools(h) {
|
|
|
12323
12828
|
tool(
|
|
12324
12829
|
"agent_detail",
|
|
12325
12830
|
"One agent in full: status, current task, and the coding agent, model and effort they run.",
|
|
12326
|
-
{ agent_id:
|
|
12831
|
+
{ agent_id: z3.string().describe("An id (or name) from company_status") },
|
|
12327
12832
|
(a) => run2(() => h.agentDetail(a))
|
|
12328
12833
|
),
|
|
12329
12834
|
tool(
|
|
12330
12835
|
"set_floor_profile",
|
|
12331
12836
|
"Record your read of a floor's project: a one-line summary (kind of project and stack), the QA brief that tells agents what to check when they test a pull request for this kind of project, and how to run the app for the floor's preview monitor.",
|
|
12332
12837
|
{
|
|
12333
|
-
floor:
|
|
12334
|
-
summary:
|
|
12335
|
-
qa_brief:
|
|
12336
|
-
preview_command:
|
|
12838
|
+
floor: z3.number().int().describe("Floor number"),
|
|
12839
|
+
summary: z3.string().max(140).optional().describe('e.g. "3D browser game \xB7 Three.js + Vite + TypeScript"'),
|
|
12840
|
+
qa_brief: z3.string().max(2500).optional().describe("What QA must check on every PR for this project, as short bullet points"),
|
|
12841
|
+
preview_command: z3.string().max(2e3).optional().describe(
|
|
12337
12842
|
'Shell command that serves the app on port {port} from a fresh checkout after npm install, e.g. "npm run dev -- --port {port} --strictPort". PORT={port} is always set. {tmp} is a scratch folder. Empty string: back to the default (npm run dev, else start, else preview). Only set it when the default would not serve the app on PORT.'
|
|
12338
12843
|
),
|
|
12339
12844
|
// Not z.record(): the SDK can't turn it into JSON Schema, and one bad tool empties the whole tools/list.
|
|
12340
|
-
preview_env:
|
|
12845
|
+
preview_env: z3.object({}).catchall(z3.string()).optional().describe(
|
|
12341
12846
|
`Extra environment variables for the preview; {port} and {tmp} are replaced in the values. Replaces the whole set. At most ${PREVIEW_ENV_MAX_CHARS} characters in all, each variable counted as KEY=value plus 2: only what the app needs to run.`
|
|
12342
12847
|
)
|
|
12343
12848
|
},
|
|
@@ -12347,11 +12852,11 @@ function createOfficeTools(h) {
|
|
|
12347
12852
|
"scale_team",
|
|
12348
12853
|
"Set how many agents a floor has. Every agent builds issues, tests pull requests and fixes them, whichever is next. Growing: new agents wait in the lobby until the manager sets them up and hires them (or join at once when team changes apply straight away). Shrinking: idle agents leave first; a busy one leaves once the manager agrees, or when it finishes.",
|
|
12349
12854
|
{
|
|
12350
|
-
floor:
|
|
12351
|
-
size:
|
|
12352
|
-
reason:
|
|
12855
|
+
floor: z3.number().int(),
|
|
12856
|
+
size: z3.number().int().min(1).max(FLOOR_SEATS).describe("The team size you want, counting everyone already there; at most the floor's max in company_status"),
|
|
12857
|
+
reason: z3.string().min(1).max(600).describe("Why, from the floor's throughput. The manager reads this."),
|
|
12353
12858
|
cli: CLI.optional().describe("New agents' coding agent; leave out for the office default"),
|
|
12354
|
-
model:
|
|
12859
|
+
model: z3.string().optional().describe("New agents' model; leave out for the default"),
|
|
12355
12860
|
effort: EFFORT.optional().describe("New agents' reasoning effort; leave out for the default")
|
|
12356
12861
|
},
|
|
12357
12862
|
(a) => run2(() => h.scaleTeam(a))
|
|
@@ -12360,10 +12865,10 @@ function createOfficeTools(h) {
|
|
|
12360
12865
|
"configure_agent",
|
|
12361
12866
|
"Change an agent's coding agent, model or reasoning effort. Takes effect from their next task.",
|
|
12362
12867
|
{
|
|
12363
|
-
agent_id:
|
|
12364
|
-
cli:
|
|
12365
|
-
model:
|
|
12366
|
-
effort:
|
|
12868
|
+
agent_id: z3.string(),
|
|
12869
|
+
cli: z3.union([CLI, z3.literal("")]).optional().describe('"" for the office default'),
|
|
12870
|
+
model: z3.string().optional().describe('"" for the default'),
|
|
12871
|
+
effort: z3.union([EFFORT, z3.literal("")]).optional().describe('"" for the office default')
|
|
12367
12872
|
},
|
|
12368
12873
|
(a) => run2(() => h.configureAgent(a))
|
|
12369
12874
|
),
|
|
@@ -12371,9 +12876,9 @@ function createOfficeTools(h) {
|
|
|
12371
12876
|
"file_issue",
|
|
12372
12877
|
'File a GitHub issue on a floor, only for work the manager asked for in this job (a plan, or their message); anything else is refused. The next free agent takes the next issue that can start. Write "Depends on #N" in the body only when it cannot start until #N is merged: the office will not start it until #N is closed.',
|
|
12373
12878
|
{
|
|
12374
|
-
floor:
|
|
12375
|
-
title:
|
|
12376
|
-
body:
|
|
12879
|
+
floor: z3.number().int(),
|
|
12880
|
+
title: z3.string().max(120),
|
|
12881
|
+
body: z3.string().max(6e3).describe("Context, what to build, acceptance criteria")
|
|
12377
12882
|
},
|
|
12378
12883
|
(a) => run2(() => h.fileIssue(a))
|
|
12379
12884
|
),
|
|
@@ -12381,9 +12886,9 @@ function createOfficeTools(h) {
|
|
|
12381
12886
|
"set_dependencies",
|
|
12382
12887
|
'Rewrite the "Depends on #N" line of an open issue instead of filing a duplicate. The rest of the body stays as it is. Not for an issue in progress.',
|
|
12383
12888
|
{
|
|
12384
|
-
floor:
|
|
12385
|
-
number:
|
|
12386
|
-
depends_on:
|
|
12889
|
+
floor: z3.number().int(),
|
|
12890
|
+
number: z3.number().int().positive().describe("The issue number"),
|
|
12891
|
+
depends_on: z3.array(z3.number().int().positive()).max(10).describe("Issues it waits for; [] for none")
|
|
12387
12892
|
},
|
|
12388
12893
|
(a) => run2(() => h.setDependencies(a))
|
|
12389
12894
|
),
|
|
@@ -12391,40 +12896,40 @@ function createOfficeTools(h) {
|
|
|
12391
12896
|
"close_issue",
|
|
12392
12897
|
'Close an open issue that is superseded or no longer wanted, as "not planned", with your reason as a comment. Not while an open pull request closes it. Nothing is deleted.',
|
|
12393
12898
|
{
|
|
12394
|
-
floor:
|
|
12395
|
-
number:
|
|
12396
|
-
reason:
|
|
12899
|
+
floor: z3.number().int(),
|
|
12900
|
+
number: z3.number().int().positive().describe("The issue number"),
|
|
12901
|
+
reason: z3.string().min(1).max(1e3).describe('Posted as a comment, e.g. "Superseded by #152."')
|
|
12397
12902
|
},
|
|
12398
12903
|
(a) => run2(() => h.closeIssue(a))
|
|
12399
12904
|
),
|
|
12400
12905
|
tool(
|
|
12401
12906
|
"retry_qa",
|
|
12402
12907
|
"Triage only: give a stuck pull request another QA round (a flaky session, or the problem has since been fixed).",
|
|
12403
|
-
{ floor:
|
|
12908
|
+
{ floor: z3.number().int(), pr: z3.number().int().positive().describe("The pull request number") },
|
|
12404
12909
|
(a) => run2(() => h.retryQa(a))
|
|
12405
12910
|
),
|
|
12406
12911
|
tool(
|
|
12407
12912
|
"send_back",
|
|
12408
12913
|
"Triage only: send a stuck pull request back to a developer with QA's findings plus your note, without another QA round first.",
|
|
12409
|
-
{ floor:
|
|
12914
|
+
{ floor: z3.number().int(), pr: z3.number().int().positive(), note: z3.string().min(1).max(1e3).describe('What the developer should do, e.g. "Merge main and keep both toolbar changes."') },
|
|
12410
12915
|
(a) => run2(() => h.sendBack(a))
|
|
12411
12916
|
),
|
|
12412
12917
|
tool(
|
|
12413
12918
|
"rerun_checks",
|
|
12414
12919
|
"Triage only: re-run the failed GitHub Actions runs on a stuck pull request's head commit (a flaky check or an outage), then hand it back to the office.",
|
|
12415
|
-
{ floor:
|
|
12920
|
+
{ floor: z3.number().int(), pr: z3.number().int().positive() },
|
|
12416
12921
|
(a) => run2(() => h.rerunChecks(a))
|
|
12417
12922
|
),
|
|
12418
12923
|
tool(
|
|
12419
12924
|
"close_pull",
|
|
12420
12925
|
"Triage only: close a stuck pull request that is the wrong approach, with your comment on it. Its issue stays open so it is built again. No branch is deleted.",
|
|
12421
|
-
{ floor:
|
|
12926
|
+
{ floor: z3.number().int(), pr: z3.number().int().positive(), comment: z3.string().min(1).max(1e3).describe("Posted on the PR: why it is closed") },
|
|
12422
12927
|
(a) => run2(() => h.closePull(a))
|
|
12423
12928
|
),
|
|
12424
12929
|
tool(
|
|
12425
12930
|
"escalate",
|
|
12426
12931
|
"Triage only: hand a stuck pull request to the manager with your one-line diagnosis, when it needs a decision only they can make.",
|
|
12427
|
-
{ floor:
|
|
12932
|
+
{ floor: z3.number().int(), pr: z3.number().int().positive(), reason: z3.string().min(1).max(300).describe("One line: what is wrong and what the manager has to decide") },
|
|
12428
12933
|
(a) => run2(() => h.escalate(a))
|
|
12429
12934
|
)
|
|
12430
12935
|
];
|
|
@@ -12492,6 +12997,9 @@ function ceoSystemPrompt(o) {
|
|
|
12492
12997
|
}
|
|
12493
12998
|
function ceoJobPrompt(job, floor, pr) {
|
|
12494
12999
|
switch (job.kind) {
|
|
13000
|
+
case "app-starter":
|
|
13001
|
+
return `New-app interview for project ${job.repoId}, draft ${job.draftId}, revision ${job.revision}.
|
|
13002
|
+
Use only the attached persistent project context. Save progress with update_app_plan and end the turn. Do not file issues.`;
|
|
12495
13003
|
case "triage":
|
|
12496
13004
|
if (!floor || !pr) return `Pull request #${job.prNumber ?? "?"} no longer needs triage. Reply "Nothing to do."`;
|
|
12497
13005
|
return [
|
|
@@ -12549,6 +13057,8 @@ ${job.text ?? ""}`;
|
|
|
12549
13057
|
function jobLabel(job, floor) {
|
|
12550
13058
|
const where = floor ? `floor ${floor.floor} \xB7 ${floor.fullName.split("/")[1] ?? floor.fullName}` : "a removed floor";
|
|
12551
13059
|
switch (job.kind) {
|
|
13060
|
+
case "app-starter":
|
|
13061
|
+
return `App-starter \xB7 ${where}`;
|
|
12552
13062
|
case "onboard":
|
|
12553
13063
|
return `Onboarding ${where}`;
|
|
12554
13064
|
case "plan":
|
|
@@ -12873,8 +13383,8 @@ function orphanedQa(qa, agents, busy2) {
|
|
|
12873
13383
|
// server/prOwnership.ts
|
|
12874
13384
|
var QA_STOPPED = "QA was stopped by the manager.";
|
|
12875
13385
|
var PR_LIMITS_VERSION = 2;
|
|
12876
|
-
function noChangeReason(
|
|
12877
|
-
const m =
|
|
13386
|
+
function noChangeReason(text4) {
|
|
13387
|
+
const m = text4.match(/^[ \t*_>`#-]*NO CHANGE NEEDED[*_`]*[ \t]*:[*_`]*[ \t]*(.*)$/im);
|
|
12878
13388
|
return m ? m[1].replace(/[*_`]+$/, "").trim() || "no reason given" : null;
|
|
12879
13389
|
}
|
|
12880
13390
|
function unpushedFix(rec, head, i) {
|
|
@@ -13082,8 +13592,8 @@ var ago = (ms) => {
|
|
|
13082
13592
|
function finding(p, name, work, now2) {
|
|
13083
13593
|
const who = name(p.agentId) ?? "Someone";
|
|
13084
13594
|
const what = p.prNumber != null ? `PR #${p.prNumber}` : `#${p.issueNumber}`;
|
|
13085
|
-
const [
|
|
13086
|
-
return { id: p.key, kind: p.kind, repoId: p.repoId, agentId: p.agentId, prNumber: p.prNumber, issueNumber: p.issueNumber, text:
|
|
13595
|
+
const [text4, fixes] = p.kind === "quiet" ? [`${who} has been quiet for ${ago(now2 - p.since)} on ${what}, even after a nudge. Stop them, or put the work back in line?`, ["stop", "requeue"]] : p.kind === "preparing" ? [`${who} has been setting up a desk for ${what} for ${ago(now2 - p.since)}. Put the work back in line?`, ["requeue", "stop"]] : p.kind === "stale" ? [`${who}'s last task ${what} is already ${work === "merged" ? "merged" : "closed"}. Clear the desk?`, ["clear"]] : p.kind === "qa-orphan" ? [`PR #${p.prNumber} is marked as in QA, but nobody is testing it. Test it again?`, ["retry-qa", "send-back"]] : p.kind === "fix-orphan" ? [`PR #${p.prNumber} is waiting for a fix, but ${p.agentId ? `${who} is on something else` : "nobody is on it"}. Hand it to a free agent?`, ["send-back", "retry-qa"]] : [`Issue #${p.issueNumber} is still open, but PR #${p.prNumber}, which closes it, was merged ${ago(now2 - p.since)} ago. Close it?`, ["close-issue"]];
|
|
13596
|
+
return { id: p.key, kind: p.kind, repoId: p.repoId, agentId: p.agentId, prNumber: p.prNumber, issueNumber: p.issueNumber, text: text4, fixes, since: p.since };
|
|
13087
13597
|
}
|
|
13088
13598
|
function nudgeText(quietMs) {
|
|
13089
13599
|
return `The office hasn't seen any output from you for ${ago(quietMs)}. If you're stuck, say what's blocking you; otherwise carry on and finish your task.`;
|
|
@@ -13546,39 +14056,39 @@ var Previews = class {
|
|
|
13546
14056
|
};
|
|
13547
14057
|
|
|
13548
14058
|
// server/qaShots.ts
|
|
13549
|
-
import
|
|
13550
|
-
import
|
|
14059
|
+
import fs21 from "node:fs/promises";
|
|
14060
|
+
import path21 from "node:path";
|
|
13551
14061
|
var QA_SHOTS_KEPT = 8;
|
|
13552
14062
|
var EXT = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/svg+xml": "svg" };
|
|
13553
|
-
var qaShotsDir = (root, repoId2, pr) =>
|
|
13554
|
-
var qaShotFile = (dir, index, mime) =>
|
|
14063
|
+
var qaShotsDir = (root, repoId2, pr) => path21.join(root, repoId2.replace("/", "__"), `pr-${pr}`);
|
|
14064
|
+
var qaShotFile = (dir, index, mime) => path21.join(dir, `${String(index + 1).padStart(2, "0")}.${EXT[mime] ?? "img"}`);
|
|
13555
14065
|
async function saveQaShots(dir, shots) {
|
|
13556
14066
|
await removeQaShots(dir);
|
|
13557
14067
|
const kept = shots.slice(-QA_SHOTS_KEPT);
|
|
13558
14068
|
if (!kept.length) return [];
|
|
13559
|
-
await
|
|
14069
|
+
await fs21.mkdir(dir, { recursive: true });
|
|
13560
14070
|
const out = [];
|
|
13561
14071
|
for (const [i, s2] of kept.entries()) {
|
|
13562
|
-
await
|
|
14072
|
+
await fs21.writeFile(qaShotFile(dir, i, s2.mime), s2.data);
|
|
13563
14073
|
out.push({ caption: s2.caption, page: s2.page, mime: s2.mime });
|
|
13564
14074
|
}
|
|
13565
14075
|
return out;
|
|
13566
14076
|
}
|
|
13567
14077
|
async function readQaShot(dir, index, mime) {
|
|
13568
|
-
return
|
|
14078
|
+
return fs21.readFile(qaShotFile(dir, index, mime)).catch(() => null);
|
|
13569
14079
|
}
|
|
13570
14080
|
async function removeQaShots(dir) {
|
|
13571
|
-
await
|
|
14081
|
+
await fs21.rm(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
|
|
13572
14082
|
}
|
|
13573
14083
|
async function pruneQaShots(root, keep) {
|
|
13574
|
-
const repos2 = await
|
|
14084
|
+
const repos2 = await fs21.readdir(root, { withFileTypes: true }).catch(() => []);
|
|
13575
14085
|
for (const repo of repos2.filter((e) => e.isDirectory())) {
|
|
13576
14086
|
const repoId2 = repo.name.replace("__", "/");
|
|
13577
|
-
const prs = await
|
|
14087
|
+
const prs = await fs21.readdir(path21.join(root, repo.name), { withFileTypes: true }).catch(() => []);
|
|
13578
14088
|
for (const pr of prs) {
|
|
13579
14089
|
const n = /^pr-(\d+)$/.exec(pr.name)?.[1];
|
|
13580
14090
|
if (!n || keep.has(`${repoId2}#${n}`)) continue;
|
|
13581
|
-
await removeQaShots(
|
|
14091
|
+
await removeQaShots(path21.join(root, repo.name, pr.name)).catch(() => void 0);
|
|
13582
14092
|
}
|
|
13583
14093
|
}
|
|
13584
14094
|
}
|
|
@@ -13697,8 +14207,8 @@ function sampleDay(base, midnight, rand = seeded(7)) {
|
|
|
13697
14207
|
ev({ type: "agent", agent: a });
|
|
13698
14208
|
};
|
|
13699
14209
|
const ticker = [];
|
|
13700
|
-
const tick = (repoId2,
|
|
13701
|
-
const item = { id: ticker.length + 1, repoId: repoId2, at: t, text:
|
|
14210
|
+
const tick = (repoId2, text4, tone = "info") => {
|
|
14211
|
+
const item = { id: ticker.length + 1, repoId: repoId2, at: t, text: text4, tone };
|
|
13702
14212
|
ticker.push(item);
|
|
13703
14213
|
ev({ type: "ticker", item });
|
|
13704
14214
|
};
|
|
@@ -13706,8 +14216,8 @@ function sampleDay(base, midnight, rand = seeded(7)) {
|
|
|
13706
14216
|
q.updatedAt = t;
|
|
13707
14217
|
ev({ type: "qa", qa: q });
|
|
13708
14218
|
};
|
|
13709
|
-
const say = (from,
|
|
13710
|
-
const m = { id: msgId++, from, text:
|
|
14219
|
+
const say = (from, text4) => {
|
|
14220
|
+
const m = { id: msgId++, from, text: text4, at: t };
|
|
13711
14221
|
messages.push(m);
|
|
13712
14222
|
ev({ type: "message", message: m });
|
|
13713
14223
|
};
|
|
@@ -14342,8 +14852,8 @@ function loadLedger(raw) {
|
|
|
14342
14852
|
}
|
|
14343
14853
|
|
|
14344
14854
|
// server/terminal.ts
|
|
14345
|
-
import
|
|
14346
|
-
import
|
|
14855
|
+
import fs22 from "node:fs/promises";
|
|
14856
|
+
import path22 from "node:path";
|
|
14347
14857
|
import { stripVTControlCharacters } from "node:util";
|
|
14348
14858
|
import xtermHeadless from "@xterm/headless";
|
|
14349
14859
|
import xtermSerialize from "@xterm/addon-serialize";
|
|
@@ -14400,15 +14910,15 @@ var AgentTerminal = class {
|
|
|
14400
14910
|
this.send({ t: "data", data });
|
|
14401
14911
|
}
|
|
14402
14912
|
/** A dim line from the office itself, e.g. between sessions. */
|
|
14403
|
-
note(
|
|
14913
|
+
note(text4) {
|
|
14404
14914
|
this.write(`\r
|
|
14405
|
-
\x1B[2m${
|
|
14915
|
+
\x1B[2m${text4}\x1B[0m\r
|
|
14406
14916
|
`);
|
|
14407
14917
|
}
|
|
14408
14918
|
/** A closed full-screen CLI cannot redraw after resize. Keep its final reply in reflowable scrollback. */
|
|
14409
|
-
retainReply(
|
|
14919
|
+
retainReply(text4) {
|
|
14410
14920
|
this.write("\x1B[?1049l\x1B[0m\r\n");
|
|
14411
|
-
this.write(`${stripVTControlCharacters(
|
|
14921
|
+
this.write(`${stripVTControlCharacters(text4).replace(/\r?\n/g, "\r\n")}\r
|
|
14412
14922
|
`);
|
|
14413
14923
|
}
|
|
14414
14924
|
get live() {
|
|
@@ -14457,15 +14967,15 @@ var AgentTerminal = class {
|
|
|
14457
14967
|
const next = this.saving.then(async () => {
|
|
14458
14968
|
this.dirty = false;
|
|
14459
14969
|
await this.flush();
|
|
14460
|
-
await
|
|
14461
|
-
await
|
|
14462
|
-
await
|
|
14970
|
+
await fs22.mkdir(path22.dirname(file), { recursive: true });
|
|
14971
|
+
await fs22.writeFile(`${file}.tmp`, this.snapshot());
|
|
14972
|
+
await fs22.rename(`${file}.tmp`, file);
|
|
14463
14973
|
});
|
|
14464
14974
|
this.saving = next.catch(() => void 0);
|
|
14465
14975
|
return next;
|
|
14466
14976
|
}
|
|
14467
14977
|
async load(file) {
|
|
14468
|
-
const data = await
|
|
14978
|
+
const data = await fs22.readFile(file, "utf8").catch(() => "");
|
|
14469
14979
|
if (!data) return;
|
|
14470
14980
|
this.term.write(data);
|
|
14471
14981
|
this.note("(the office restarted)");
|
|
@@ -14570,8 +15080,8 @@ var TOKENS = [
|
|
|
14570
15080
|
// JWTs
|
|
14571
15081
|
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g
|
|
14572
15082
|
];
|
|
14573
|
-
function redact4(
|
|
14574
|
-
let s2 =
|
|
15083
|
+
function redact4(text4) {
|
|
15084
|
+
let s2 = text4;
|
|
14575
15085
|
for (const re of TOKENS) s2 = s2.replace(re, MASK);
|
|
14576
15086
|
s2 = s2.replace(/(\b[a-z][a-z0-9+.-]*:\/\/)[^\s/@]+@/gi, `$1${MASK}@`);
|
|
14577
15087
|
s2 = s2.replace(/([?&;](?:[\w-]*(?:token|key|secret|password|passwd|pwd|auth|sig|signature|credential)[\w-]*)=)[^&\s#'"]+/gi, `$1${MASK}`);
|
|
@@ -14583,8 +15093,8 @@ function redact4(text3) {
|
|
|
14583
15093
|
s2 = s2.replace(/[A-Za-z0-9+/_-]{32,}={0,2}/g, (m) => /[a-z]/.test(m) && /[A-Z]/.test(m) && /\d/.test(m) ? MASK : m);
|
|
14584
15094
|
return s2;
|
|
14585
15095
|
}
|
|
14586
|
-
function clipText(
|
|
14587
|
-
const s2 =
|
|
15096
|
+
function clipText(text4, max) {
|
|
15097
|
+
const s2 = text4.replace(/\s+/g, " ").trim();
|
|
14588
15098
|
return s2.length > max ? `${s2.slice(0, Math.max(1, max - 1)).trimEnd()}\u2026` : s2;
|
|
14589
15099
|
}
|
|
14590
15100
|
var outsideDesk = (p) => /^(?:[A-Za-z]:[\\/]|[\\/]|~|\.\.(?:[\\/]|$)|\$|%)/.test(p.trim());
|
|
@@ -14712,8 +15222,8 @@ var OFFICE_KINDS = {
|
|
|
14712
15222
|
close_pull: "git",
|
|
14713
15223
|
escalate: "talk"
|
|
14714
15224
|
};
|
|
14715
|
-
function toolActivity(tool2,
|
|
14716
|
-
const body2 =
|
|
15225
|
+
function toolActivity(tool2, text4, max = DETAIL_MAX) {
|
|
15226
|
+
const body2 = text4.replace(/^\s*⏺\s*/u, "").trim();
|
|
14717
15227
|
const rest = body2.replace(/^\S+\s*/, "");
|
|
14718
15228
|
const clip4 = (s2) => clipText(redact4(s2), max);
|
|
14719
15229
|
if (body2.startsWith("$ ")) return shellActivity(body2.slice(2), max);
|
|
@@ -14789,7 +15299,7 @@ var opened = (repoId2, pr) => `opened:${repoId2}#${pr}`;
|
|
|
14789
15299
|
function agentTicks(prev, next) {
|
|
14790
15300
|
if (next.role === "ceo" || !next.repoId) return [];
|
|
14791
15301
|
const out = [];
|
|
14792
|
-
const say = (
|
|
15302
|
+
const say = (text4, tone = "info", key) => out.push({ repoId: next.repoId, text: text4, tone, key });
|
|
14793
15303
|
const was = prev && busy(prev.status) ? prev : null;
|
|
14794
15304
|
if (busy(next.status) && next.task === "issue" && next.issueNumber != null && (was?.task !== "issue" || was.issueNumber !== next.issueNumber)) {
|
|
14795
15305
|
say(`${next.name} picked up #${next.issueNumber}`);
|
|
@@ -14809,7 +15319,7 @@ function qaTicks(prev, next, nameOf) {
|
|
|
14809
15319
|
if (prev === next.status) return [];
|
|
14810
15320
|
const pr = `PR #${next.prNumber}`;
|
|
14811
15321
|
const who = nameOf(next.qaAgentId) ?? "QA";
|
|
14812
|
-
const tick = (
|
|
15322
|
+
const tick = (text4, tone = "info") => [{ repoId: next.repoId, text: text4, tone }];
|
|
14813
15323
|
switch (next.status) {
|
|
14814
15324
|
case "queued":
|
|
14815
15325
|
return tick(`${pr} is queued for QA${next.round > 1 ? ` (round ${next.round})` : ""}`);
|
|
@@ -14831,7 +15341,7 @@ function repoFacts(repo) {
|
|
|
14831
15341
|
}
|
|
14832
15342
|
function repoTicks(prev, next, authorOf, now2 = Date.now()) {
|
|
14833
15343
|
const out = [];
|
|
14834
|
-
const say = (
|
|
15344
|
+
const say = (text4, tone = "info", key) => out.push({ repoId: next.id, text: text4, tone, key });
|
|
14835
15345
|
for (const p of next.pulls) {
|
|
14836
15346
|
const before = prev.pulls.get(p.number);
|
|
14837
15347
|
if (!before) {
|
|
@@ -15395,8 +15905,8 @@ var EFFORTS = ["low", "medium", "high", "xhigh", "max"];
|
|
|
15395
15905
|
var CEO_MODEL = "claude-opus-5-5";
|
|
15396
15906
|
var CEO_EFFORT = "xhigh";
|
|
15397
15907
|
var CEO_NAME = "Morgan";
|
|
15398
|
-
var CEO_DIR =
|
|
15399
|
-
var DEFAULT_PROJECTS_DIR = defaultProjectsDir(
|
|
15908
|
+
var CEO_DIR = path23.join(HOME_DIR, "ceo");
|
|
15909
|
+
var DEFAULT_PROJECTS_DIR = defaultProjectsDir(path23.resolve(import.meta.dirname, ".."));
|
|
15400
15910
|
var MAX_ISSUES_PER_JOB = 12;
|
|
15401
15911
|
var KEEP_MESSAGES = 200;
|
|
15402
15912
|
var KEEP_DECIDED_REQUESTS = 40;
|
|
@@ -15422,26 +15932,26 @@ var SignInNeeded = class extends Error {
|
|
|
15422
15932
|
}
|
|
15423
15933
|
cli;
|
|
15424
15934
|
};
|
|
15425
|
-
var SCREENS_DIR =
|
|
15935
|
+
var SCREENS_DIR = path23.join(HOME_DIR, "screens");
|
|
15426
15936
|
var MIME_EXT = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/svg+xml": "svg" };
|
|
15427
|
-
var screenFile = (agentId, mime) =>
|
|
15937
|
+
var screenFile = (agentId, mime) => path23.join(SCREENS_DIR, `${agentId}.${MIME_EXT[mime] ?? "img"}`);
|
|
15428
15938
|
async function loadScreen(agentId) {
|
|
15429
15939
|
for (const [mime, ext] of Object.entries(MIME_EXT)) {
|
|
15430
|
-
const file =
|
|
15940
|
+
const file = path23.join(SCREENS_DIR, `${agentId}.${ext}`);
|
|
15431
15941
|
try {
|
|
15432
|
-
const [data, stat] = await Promise.all([
|
|
15942
|
+
const [data, stat] = await Promise.all([fs23.readFile(file), fs23.stat(file)]);
|
|
15433
15943
|
return { data, mime, at: stat.mtimeMs };
|
|
15434
15944
|
} catch {
|
|
15435
15945
|
}
|
|
15436
15946
|
}
|
|
15437
15947
|
return null;
|
|
15438
15948
|
}
|
|
15439
|
-
var QA_SHOTS_DIR =
|
|
15949
|
+
var QA_SHOTS_DIR = path23.join(HOME_DIR, "qa-shots");
|
|
15440
15950
|
async function removeScreens(agentId) {
|
|
15441
|
-
await Promise.all(Object.values(MIME_EXT).map((ext) =>
|
|
15951
|
+
await Promise.all(Object.values(MIME_EXT).map((ext) => fs23.rm(path23.join(SCREENS_DIR, `${agentId}.${ext}`), { force: true })));
|
|
15442
15952
|
}
|
|
15443
|
-
var TERMINALS_DIR =
|
|
15444
|
-
var terminalFile = (agentId) =>
|
|
15953
|
+
var TERMINALS_DIR = path23.join(HOME_DIR, "terminals");
|
|
15954
|
+
var terminalFile = (agentId) => path23.join(TERMINALS_DIR, `${agentId}.ansi`);
|
|
15445
15955
|
var TERMINAL_SAVE_MS = 2e4;
|
|
15446
15956
|
var QA_SCHEMA = {
|
|
15447
15957
|
type: "object",
|
|
@@ -15523,33 +16033,33 @@ var Swarm = class {
|
|
|
15523
16033
|
this.backend = backend;
|
|
15524
16034
|
this.weather = new WeatherService({
|
|
15525
16035
|
api: backend.weather,
|
|
15526
|
-
file:
|
|
16036
|
+
file: path23.join(HOME_DIR, backend.demo ? "demo-weather.json" : "weather.json"),
|
|
15527
16037
|
settings: () => this.state.settings.weather,
|
|
15528
16038
|
changed: (weather) => this.broadcast({ type: "weather", weather }),
|
|
15529
16039
|
log: (line) => console.log(line)
|
|
15530
16040
|
});
|
|
15531
16041
|
this.voice = new Voice({
|
|
15532
16042
|
api: backend.voice,
|
|
15533
|
-
secretsFile:
|
|
15534
|
-
cacheDir:
|
|
16043
|
+
secretsFile: path23.join(HOME_DIR, backend.demo ? "demo-secrets.json" : "secrets.json"),
|
|
16044
|
+
cacheDir: path23.join(HOME_DIR, backend.demo ? "demo-voice" : "voice"),
|
|
15535
16045
|
settings: () => this.state.settings.voice,
|
|
15536
16046
|
listen: () => this.state.settings.listen,
|
|
15537
16047
|
language: () => languageOf(this.state.settings.language),
|
|
15538
16048
|
messages: () => this.state.messages,
|
|
15539
|
-
officeNote: (
|
|
16049
|
+
officeNote: (text4) => this.postMessage("office", text4),
|
|
15540
16050
|
keyChanged: (view) => this.broadcast({ type: "voiceKey", ...view }),
|
|
15541
16051
|
cacheChanged: (voiceCache) => this.broadcast({ type: "voiceCache", voiceCache }),
|
|
15542
16052
|
log: (line) => console.log(line)
|
|
15543
16053
|
});
|
|
15544
16054
|
this.journal = new Journal({
|
|
15545
|
-
dir:
|
|
16055
|
+
dir: path23.join(HOME_DIR, backend.demo ? "demo-journal" : "journal"),
|
|
15546
16056
|
frame: () => journalFrame(this.snapshot(), this.secrets()),
|
|
15547
16057
|
secrets: () => this.secrets()
|
|
15548
16058
|
});
|
|
15549
16059
|
this.notifier = new Notifier({
|
|
15550
16060
|
transport: backend.notify,
|
|
15551
|
-
secretsFile:
|
|
15552
|
-
pushFile:
|
|
16061
|
+
secretsFile: path23.join(HOME_DIR, backend.demo ? "demo-secrets.json" : "secrets.json"),
|
|
16062
|
+
pushFile: path23.join(HOME_DIR, backend.demo ? "demo-push.json" : "push.json"),
|
|
15553
16063
|
settings: () => this.state.settings.notify,
|
|
15554
16064
|
broadcast: (note2) => this.broadcast({ type: "notify", note: note2 }),
|
|
15555
16065
|
channelsChanged: (notifyChannels) => this.broadcast({ type: "notifyChannels", notifyChannels }),
|
|
@@ -15557,7 +16067,7 @@ var Swarm = class {
|
|
|
15557
16067
|
});
|
|
15558
16068
|
this.cloud = new Cloud({
|
|
15559
16069
|
// The demo's fake cloud keeps a file of its own: its tests run beside the notifier's, which share demo-secrets.json.
|
|
15560
|
-
secretsFile:
|
|
16070
|
+
secretsFile: path23.join(HOME_DIR, backend.demo ? "demo-cloud-secrets.json" : "secrets.json"),
|
|
15561
16071
|
credentials: backend.cloud.credentials,
|
|
15562
16072
|
env: backend.cloud.env(),
|
|
15563
16073
|
boxes: (key) => backend.cloud.boxes(key),
|
|
@@ -15594,7 +16104,7 @@ var Swarm = class {
|
|
|
15594
16104
|
pulls: (id) => this.repoRt.get(id)?.pulls ?? [],
|
|
15595
16105
|
emitPr: (preview) => this.broadcast({ type: "prPreview", preview }),
|
|
15596
16106
|
prRemoved: (repoId2, pr) => this.broadcast({ type: "prPreviewRemoved", repoId: repoId2, pr }),
|
|
15597
|
-
note: (
|
|
16107
|
+
note: (text4) => this.toast("info", text4)
|
|
15598
16108
|
});
|
|
15599
16109
|
}
|
|
15600
16110
|
backend;
|
|
@@ -15653,8 +16163,9 @@ var Swarm = class {
|
|
|
15653
16163
|
* The CEO's office tools. Every session gets its own server: one can only be connected to one session at a time, so
|
|
15654
16164
|
* a shared one left the next session connected but without any tools while an earlier session still held it.
|
|
15655
16165
|
*/
|
|
15656
|
-
officeTools() {
|
|
16166
|
+
officeTools(job) {
|
|
15657
16167
|
return createOfficeTools({
|
|
16168
|
+
...job?.kind === "app-starter" ? { updateAppPlan: (a) => this.updateAppPlan(job, a) } : {},
|
|
15658
16169
|
companyStatus: () => this.companyStatus(),
|
|
15659
16170
|
agentDetail: (a) => this.agentDetail(a),
|
|
15660
16171
|
setFloorProfile: (a) => this.setFloorProfile(a),
|
|
@@ -15693,6 +16204,8 @@ var Swarm = class {
|
|
|
15693
16204
|
// `${repoId}#${pr}:${task}` -> its desks that couldn't be set up
|
|
15694
16205
|
dropping = /* @__PURE__ */ new Map();
|
|
15695
16206
|
// agent id -> why their task's issue or PR closed: the desk clears once the session ends
|
|
16207
|
+
issuePreparations = /* @__PURE__ */ new Set();
|
|
16208
|
+
// a stopped setup must settle before a manual resume can start another
|
|
15696
16209
|
// Everything sent to the tabs on /ws: agent and floor changes batched as patches, terminal lines only where shown.
|
|
15697
16210
|
outbox = new Outbox({
|
|
15698
16211
|
agents: () => this.state.agents.map((a) => ({ id: a.id, floor: this.floorOf(a) })),
|
|
@@ -15748,7 +16261,7 @@ var Swarm = class {
|
|
|
15748
16261
|
async init() {
|
|
15749
16262
|
let legacyDefaults = false;
|
|
15750
16263
|
try {
|
|
15751
|
-
const raw = await
|
|
16264
|
+
const raw = await fs23.readFile(STATE_FILE, "utf8");
|
|
15752
16265
|
const loaded = JSON.parse(raw);
|
|
15753
16266
|
legacyDefaults = loaded.agentDefaultsVersion !== 1;
|
|
15754
16267
|
this.state = {
|
|
@@ -15757,6 +16270,7 @@ var Swarm = class {
|
|
|
15757
16270
|
settings: { ...this.state.settings, defaultCli: "claude", defaultModel: DEFAULT_MODEL, ...loaded.settings },
|
|
15758
16271
|
repos: (loaded.repos ?? []).map((r) => ({
|
|
15759
16272
|
...r,
|
|
16273
|
+
...r.appStarter?.status === "publishing" ? { appStarter: { ...r.appStarter, status: "paused", problem: "Publication interrupted. Reconcile and resume explicitly." } } : {},
|
|
15760
16274
|
autoMerge: r.autoMerge ?? true,
|
|
15761
16275
|
links: r.links ?? [],
|
|
15762
16276
|
mission: r.mission ?? "",
|
|
@@ -15769,6 +16283,7 @@ var Swarm = class {
|
|
|
15769
16283
|
agents: (loaded.agents ?? []).map((raw2) => legacyAgent(raw2)).map((a) => ({
|
|
15770
16284
|
...a,
|
|
15771
16285
|
machine: a.machine ?? null,
|
|
16286
|
+
legacyDeskSlug: typeof a.legacyDeskSlug === "string" && /^[a-z0-9-]+$/.test(a.legacyDeskSlug) && a.legacyDeskSlug.endsWith(`-${a.id.slice(0, 4)}`) ? a.legacyDeskSlug : void 0,
|
|
15772
16287
|
boxCli: a.host === "box" ? a.boxCli ?? null : null,
|
|
15773
16288
|
effort: a.effort ?? "",
|
|
15774
16289
|
look: a.look ?? lookFor(a.name),
|
|
@@ -16029,8 +16544,8 @@ var Swarm = class {
|
|
|
16029
16544
|
/** After the startup sync: the restart's interrupted work resumes or goes back in line, and the phone hears what happened. */
|
|
16030
16545
|
finishRestart(r) {
|
|
16031
16546
|
this.recover([...r.interrupted, ...[...r.requeue].filter((a) => !r.interrupted.includes(a))], r.preparing, r.requeue, r.counts);
|
|
16032
|
-
const
|
|
16033
|
-
if (
|
|
16547
|
+
const text4 = restartMessage(r.counts);
|
|
16548
|
+
if (text4) this.postMessage("office", text4);
|
|
16034
16549
|
}
|
|
16035
16550
|
/**
|
|
16036
16551
|
* Agents cut off by a server restart pick their session back up, told what they were doing. QA, demo agents, tasks
|
|
@@ -16075,6 +16590,7 @@ var Swarm = class {
|
|
|
16075
16590
|
repoView(r) {
|
|
16076
16591
|
const rt = this.repoRt.get(r.id);
|
|
16077
16592
|
return {
|
|
16593
|
+
...r.appStarter ? { appStarter: structuredClone(r.appStarter) } : {},
|
|
16078
16594
|
id: r.id,
|
|
16079
16595
|
fullName: r.fullName,
|
|
16080
16596
|
description: r.description,
|
|
@@ -16130,6 +16646,7 @@ var Swarm = class {
|
|
|
16130
16646
|
prNumber: a.prNumber,
|
|
16131
16647
|
prUrl: a.prUrl,
|
|
16132
16648
|
currentTool: rt.currentTool,
|
|
16649
|
+
canResumeIssue: this.canResumeIssue(a),
|
|
16133
16650
|
startedAt: a.startedAt,
|
|
16134
16651
|
endedAt: a.endedAt,
|
|
16135
16652
|
costUsd: a.costUsd,
|
|
@@ -16255,8 +16772,8 @@ var Swarm = class {
|
|
|
16255
16772
|
const day = await this.journal.writeDay(sampleDay(journalFrame(this.snapshot(), this.secrets()), midnight, seeded(Number(dayKey(midnight).replace(/-/g, "")))));
|
|
16256
16773
|
return { day };
|
|
16257
16774
|
}
|
|
16258
|
-
toast(level,
|
|
16259
|
-
this.broadcast({ type: "toast", level, text:
|
|
16775
|
+
toast(level, text4) {
|
|
16776
|
+
this.broadcast({ type: "toast", level, text: text4 });
|
|
16260
16777
|
}
|
|
16261
16778
|
emitRepo(r) {
|
|
16262
16779
|
const repo = this.repoView(r);
|
|
@@ -16318,10 +16835,10 @@ var Swarm = class {
|
|
|
16318
16835
|
}
|
|
16319
16836
|
async writeStateFile() {
|
|
16320
16837
|
for (const a of this.state.agents) a.logTail = (this.agentRt.get(a.id)?.log ?? []).slice(-200);
|
|
16321
|
-
await
|
|
16838
|
+
await fs23.mkdir(path23.dirname(STATE_FILE), { recursive: true });
|
|
16322
16839
|
const tmp = `${STATE_FILE}.tmp`;
|
|
16323
|
-
await
|
|
16324
|
-
await
|
|
16840
|
+
await fs23.writeFile(tmp, JSON.stringify(this.state, null, 2));
|
|
16841
|
+
await fs23.rename(tmp, STATE_FILE);
|
|
16325
16842
|
}
|
|
16326
16843
|
// ---------- lookups ----------
|
|
16327
16844
|
repo(id) {
|
|
@@ -16347,7 +16864,7 @@ var Swarm = class {
|
|
|
16347
16864
|
return limit > 0 && this.running() >= limit;
|
|
16348
16865
|
}
|
|
16349
16866
|
agentSlug(a) {
|
|
16350
|
-
return `${slugify(a.name)}-${a.id.slice(0, 4)}`;
|
|
16867
|
+
return a.legacyDeskSlug ?? `${slugify(a.name)}-${a.id.slice(0, 4)}`;
|
|
16351
16868
|
}
|
|
16352
16869
|
/** The machines an agent's machine is one of: folders on this computer, or Upstash Boxes (docs/cloud.md). */
|
|
16353
16870
|
machinesFor(a) {
|
|
@@ -16389,7 +16906,7 @@ var Swarm = class {
|
|
|
16389
16906
|
/** Remove a machine, saying where its unpushed work went; one still in use is tried again by sweepMachines. */
|
|
16390
16907
|
async removeMachine(machine, name, host = "local") {
|
|
16391
16908
|
const r = await this.machinesFor({ host }).remove(machine).catch(() => ({ removed: false, patches: [] }));
|
|
16392
|
-
if (r.patches.length) this.postMessage("office", `\u{1F9F3} ${name ?? "A former agent"} left work that was on no GitHub branch: saved in ${
|
|
16909
|
+
if (r.patches.length) this.postMessage("office", `\u{1F9F3} ${name ?? "A former agent"} left work that was on no GitHub branch: saved in ${path23.dirname(r.patches[0])}.`);
|
|
16393
16910
|
if (host === "box" && r.removed) void this.cloud.count().catch(() => void 0);
|
|
16394
16911
|
}
|
|
16395
16912
|
/** 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. */
|
|
@@ -16400,6 +16917,7 @@ var Swarm = class {
|
|
|
16400
16917
|
}
|
|
16401
16918
|
}
|
|
16402
16919
|
clearTask(a) {
|
|
16920
|
+
this.cancelSessionStart(a);
|
|
16403
16921
|
this.quotaWaiting.delete(a.id);
|
|
16404
16922
|
Object.assign(a, { status: "idle", task: null, issueNumber: null, issueTitle: null, branch: null, prNumber: null, prUrl: null, lastError: null });
|
|
16405
16923
|
this.emitAgent(a);
|
|
@@ -16431,7 +16949,7 @@ var Swarm = class {
|
|
|
16431
16949
|
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
16950
|
}
|
|
16433
16951
|
if (!this.backend.openCodeConnections) throw new HttpError(409, "OpenCode connections are unavailable in this backend.");
|
|
16434
|
-
if (a.role === "ceo") await
|
|
16952
|
+
if (a.role === "ceo") await fs23.mkdir(CEO_DIR, { recursive: true });
|
|
16435
16953
|
const directory = a.role === "ceo" ? CEO_DIR : this.backend.mainDir(this.repo(a.repoId).fullName);
|
|
16436
16954
|
return { scope: "local", scopeKey: "local", integrations: await this.backend.openCodeConnections(directory), configuringAgent: this.openCodeAuthRun?.agentId ?? null };
|
|
16437
16955
|
}
|
|
@@ -16513,7 +17031,7 @@ var Swarm = class {
|
|
|
16513
17031
|
return this.boxMachines.openCodeModels(machine, this.boxMachines.deskDir(machine, this.repo(a.repoId).fullName));
|
|
16514
17032
|
}
|
|
16515
17033
|
if (a.role === "ceo") {
|
|
16516
|
-
return
|
|
17034
|
+
return fs23.mkdir(CEO_DIR, { recursive: true }).then(() => this.backend.openCodeModels(CEO_DIR, refresh));
|
|
16517
17035
|
}
|
|
16518
17036
|
directory = this.backend.mainDir(this.repo(a.repoId).fullName);
|
|
16519
17037
|
} else if (repoId2) directory = this.backend.mainDir(this.repo(repoId2).fullName);
|
|
@@ -16546,7 +17064,8 @@ var Swarm = class {
|
|
|
16546
17064
|
summary: "",
|
|
16547
17065
|
qaBrief: "",
|
|
16548
17066
|
preview: { ...DEFAULT_PREVIEW, env: {} },
|
|
16549
|
-
addedAt: Date.now()
|
|
17067
|
+
addedAt: Date.now(),
|
|
17068
|
+
...opts.guidedApp ? { appStarter: newAppStarter((opts.mission ?? "").trim().slice(0, 4e3)) } : {}
|
|
16550
17069
|
};
|
|
16551
17070
|
this.backend.setLocalPath(repo.fullName, folder2);
|
|
16552
17071
|
this.state.repos.push(repo);
|
|
@@ -16557,7 +17076,9 @@ var Swarm = class {
|
|
|
16557
17076
|
this.ensureAgent(repo);
|
|
16558
17077
|
void this.cloneRepo(repo.id);
|
|
16559
17078
|
void this.syncRepo(repo.id);
|
|
16560
|
-
if (
|
|
17079
|
+
if (repo.appStarter) {
|
|
17080
|
+
this.queueAppInterview(repo);
|
|
17081
|
+
} else if (opts.onboardCeo !== false) {
|
|
16561
17082
|
this.enqueueCeo({ kind: "onboard", repoId: repo.id, at: Date.now() });
|
|
16562
17083
|
if (repo.mission) this.enqueueCeo({ kind: "plan", repoId: repo.id, at: Date.now() });
|
|
16563
17084
|
}
|
|
@@ -16572,23 +17093,149 @@ var Swarm = class {
|
|
|
16572
17093
|
const name = fullName.split("/")[1];
|
|
16573
17094
|
const taken = folders.find((f) => f.name.toLowerCase() === name.toLowerCase());
|
|
16574
17095
|
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.`);
|
|
16575
|
-
return
|
|
17096
|
+
return path23.join(root, name);
|
|
17097
|
+
}
|
|
17098
|
+
// ---------- new-app planning ----------
|
|
17099
|
+
planPublications = /* @__PURE__ */ new Map();
|
|
17100
|
+
requirePlanReady(repo, agent) {
|
|
17101
|
+
if (planningHeld(repo.appStarter)) throw new HttpError(409, "This new app is held: complete the project interview, approve its exact plan and confirm publication first.");
|
|
17102
|
+
if (agent && !compatibleHost(repo.appStarter, agent.host ?? "local"))
|
|
17103
|
+
throw new HttpError(409, "This agent is incompatible with the approved environments. Work is held, not migrated.");
|
|
17104
|
+
}
|
|
17105
|
+
queueAppInterview(repo) {
|
|
17106
|
+
const d = repo.appStarter;
|
|
17107
|
+
this.enqueueCeo({ kind: "app-starter", repoId: repo.id, draftId: d.id, revision: d.revision, at: Date.now() });
|
|
17108
|
+
}
|
|
17109
|
+
currentAppJob(job) {
|
|
17110
|
+
const d = this.state.repos.find((r) => r.id === job.repoId)?.appStarter;
|
|
17111
|
+
return !!d && d.id === job.draftId && d.revision === job.revision && d.status === "interview";
|
|
17112
|
+
}
|
|
17113
|
+
/** Answers have explicit project/revision and idempotency identity, never "last CEO chat". */
|
|
17114
|
+
async answerAppInterview(repoId2, ref, messageId, text4) {
|
|
17115
|
+
const repo = this.repo(repoId2), d = repo.appStarter;
|
|
17116
|
+
if (!/^[a-zA-Z0-9-]{8,80}$/.test(messageId) || !text4.trim() || text4.length > 4e3) throw new HttpError(400, "Invalid planning message.");
|
|
17117
|
+
if (d?.id === ref.draftId && d.messages.some((m) => m.id === messageId && m.from === "manager" && m.text === text4.trim())) return this.repoView(repo);
|
|
17118
|
+
checkDraft(d, ref);
|
|
17119
|
+
if (!["interview", "awaiting-approval"].includes(d.status) || d.ledger.length) throw new HttpError(409, "This draft cannot be edited.");
|
|
17120
|
+
if (d.messages.length >= 100) throw new HttpError(409, "Interview transcript is full. Pause and review the requirements.");
|
|
17121
|
+
if (d.messages.some((m) => m.id === messageId)) throw new HttpError(409, "Message ID already used.");
|
|
17122
|
+
d.messages.push({ id: messageId, from: "manager", text: planningText(text4.trim()) });
|
|
17123
|
+
d.revision++;
|
|
17124
|
+
d.status = "interview";
|
|
17125
|
+
delete d.approved;
|
|
17126
|
+
delete d.hash;
|
|
17127
|
+
await this.writeState();
|
|
17128
|
+
this.emitRepo(repo);
|
|
17129
|
+
this.queueAppInterview(repo);
|
|
17130
|
+
return this.repoView(repo);
|
|
17131
|
+
}
|
|
17132
|
+
async updateAppPlan(job, x) {
|
|
17133
|
+
if (this.state.ceo.job !== job || !this.currentAppJob(job)) throw new HttpError(409, "Stale or foreign project interview turn.");
|
|
17134
|
+
const repo = this.repo(job.repoId), d = repo.appStarter;
|
|
17135
|
+
if (typeof x.decisions !== "string" || x.decisions.length > 8e3 || x.plan === void 0 === !x.question)
|
|
17136
|
+
throw new HttpError(400, "Save decisions with either one question or a complete plan.");
|
|
17137
|
+
if (d.messages.length >= 100) throw new HttpError(409, "Interview transcript is full.");
|
|
17138
|
+
if (x.plan !== void 0) presentPlan(d, x.plan, x.decisions);
|
|
17139
|
+
else {
|
|
17140
|
+
if (typeof x.question !== "string" || x.question.length > 2e3) throw new HttpError(400, "Question is too long.");
|
|
17141
|
+
const question = planningText(x.question.trim());
|
|
17142
|
+
if (!question) throw new HttpError(400, "Empty question.");
|
|
17143
|
+
const decisions = planningText(x.decisions);
|
|
17144
|
+
d.messages.push({ id: crypto11.randomUUID(), from: "ceo", text: question });
|
|
17145
|
+
d.decisions = decisions;
|
|
17146
|
+
d.revision++;
|
|
17147
|
+
}
|
|
17148
|
+
await this.writeState();
|
|
17149
|
+
this.emitRepo(repo);
|
|
17150
|
+
return `Saved ${repo.id}, draft ${d.id}, revision ${d.revision}. ${d.status}. End this turn; wait for the manager.`;
|
|
17151
|
+
}
|
|
17152
|
+
async approveAppPlan(repoId2, ref, hash, environments, local) {
|
|
17153
|
+
const repo = this.repo(repoId2), d = repo.appStarter;
|
|
17154
|
+
checkDraft(d, ref);
|
|
17155
|
+
if (this.planPublications.has(repoId2)) throw new HttpError(409, "Publication is already in progress.");
|
|
17156
|
+
approvePlan(d, hash, environments, local);
|
|
17157
|
+
try {
|
|
17158
|
+
await this.writeState();
|
|
17159
|
+
} catch (err) {
|
|
17160
|
+
d.status = "paused";
|
|
17161
|
+
d.problem = "Approval could not be saved. No publication started.";
|
|
17162
|
+
this.emitRepo(repo);
|
|
17163
|
+
throw err;
|
|
17164
|
+
}
|
|
17165
|
+
this.emitRepo(repo);
|
|
17166
|
+
await this.publishAppPlan(repo);
|
|
17167
|
+
return this.repoView(repo);
|
|
17168
|
+
}
|
|
17169
|
+
async appPlanAction(repoId2, ref, action) {
|
|
17170
|
+
const repo = this.repo(repoId2), d = repo.appStarter;
|
|
17171
|
+
checkDraft(d, ref);
|
|
17172
|
+
if (["ready", "cancelled"].includes(d.status)) throw new HttpError(409, "This planning workflow is closed.");
|
|
17173
|
+
if (action === "edit" && d.status === "awaiting-approval" && !d.ledger.length) {
|
|
17174
|
+
d.status = "interview";
|
|
17175
|
+
d.revision++;
|
|
17176
|
+
delete d.hash;
|
|
17177
|
+
delete d.approved;
|
|
17178
|
+
} else if (action === "pause" || action === "cancel") {
|
|
17179
|
+
d.status = action === "pause" ? "paused" : "cancelled";
|
|
17180
|
+
this.state.ceo.queue = this.state.ceo.queue.filter((j) => j.draftId !== d.id);
|
|
17181
|
+
} else if (action === "resume" && d.status === "paused") {
|
|
17182
|
+
if (this.planPublications.has(repoId2)) throw new HttpError(409, "Wait for the in-flight publication to settle.");
|
|
17183
|
+
d.status = d.approved ? "publishing" : d.hash ? "awaiting-approval" : "interview";
|
|
17184
|
+
} else throw new HttpError(400, "Choose pause, cancel or resume a paused plan.");
|
|
17185
|
+
await this.writeState();
|
|
17186
|
+
this.emitRepo(repo);
|
|
17187
|
+
if (d.status === "publishing") await this.publishAppPlan(repo);
|
|
17188
|
+
else if (d.status === "interview" && action !== "edit") this.queueAppInterview(repo);
|
|
17189
|
+
return this.repoView(repo);
|
|
17190
|
+
}
|
|
17191
|
+
publishAppPlan(repo) {
|
|
17192
|
+
if (this.planPublications.has(repo.id)) throw new HttpError(409, "Publication is already in progress.");
|
|
17193
|
+
const d = repo.appStarter;
|
|
17194
|
+
const operation = (async () => {
|
|
17195
|
+
await publishPlan(
|
|
17196
|
+
d,
|
|
17197
|
+
{
|
|
17198
|
+
create: (title, body2) => this.backend.createIssue(repo.fullName, title, body2),
|
|
17199
|
+
find: (marker2) => this.backend.findPlanIssues(repo.fullName, marker2),
|
|
17200
|
+
details: (n) => this.backend.issueDetails(repo.fullName, n)
|
|
17201
|
+
},
|
|
17202
|
+
async () => {
|
|
17203
|
+
await this.writeState();
|
|
17204
|
+
this.emitRepo(repo);
|
|
17205
|
+
},
|
|
17206
|
+
() => !this.stopping && this.state.repos.includes(repo) && repo.appStarter === d
|
|
17207
|
+
);
|
|
17208
|
+
if (d.status !== "ready" || this.stopping || !this.state.repos.includes(repo)) return;
|
|
17209
|
+
try {
|
|
17210
|
+
this.ensureAgent(repo);
|
|
17211
|
+
} catch (err) {
|
|
17212
|
+
d.problem = `Worker setup awaits compatible resources: ${oneLine(err)}`;
|
|
17213
|
+
this.emitRepo(repo);
|
|
17214
|
+
await this.writeState();
|
|
17215
|
+
}
|
|
17216
|
+
await this.syncRepo(repo.id);
|
|
17217
|
+
this.schedule();
|
|
17218
|
+
})();
|
|
17219
|
+
this.planPublications.set(repo.id, operation);
|
|
17220
|
+
void operation.finally(() => this.planPublications.delete(repo.id)).catch(() => void 0);
|
|
17221
|
+
return operation;
|
|
16576
17222
|
}
|
|
16577
17223
|
/** A brand-new project: a folder in your projects folder, pushed to a new GitHub repo. */
|
|
16578
17224
|
async createRepo(name, opts) {
|
|
16579
17225
|
if (!/^[A-Za-z0-9._-]+$/.test(name)) throw new HttpError(400, 'Project names may only contain letters, numbers, ".", "-" and "_"');
|
|
17226
|
+
if (opts.onboardCeo !== false) planningText(opts.mission ?? "");
|
|
16580
17227
|
const created = await this.backend.createProject(this.state.settings.projectsDir, name, opts).catch((err) => {
|
|
16581
17228
|
throw new HttpError(400, err.message);
|
|
16582
17229
|
});
|
|
16583
|
-
return this.connectRepo(created.fullName, { ...opts, localPath: created.path });
|
|
17230
|
+
return this.connectRepo(created.fullName, { ...opts, guidedApp: opts.onboardCeo !== false, localPath: created.path });
|
|
16584
17231
|
}
|
|
16585
17232
|
/** The folders in your projects folder (or another folder you point at), and which are floors already. */
|
|
16586
17233
|
async listProjectFolders(dir) {
|
|
16587
|
-
const root = dir?.trim() ?
|
|
17234
|
+
const root = dir?.trim() ? path23.resolve(dir.trim()) : this.state.settings.projectsDir;
|
|
16588
17235
|
const folders = await this.backend.scanProjects(root).catch((err) => {
|
|
16589
17236
|
throw new HttpError(400, err.message);
|
|
16590
17237
|
});
|
|
16591
|
-
const same3 = (a, b) =>
|
|
17238
|
+
const same3 = (a, b) => path23.resolve(a).toLowerCase() === path23.resolve(b).toLowerCase();
|
|
16592
17239
|
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;
|
|
16593
17240
|
return { root, folders: folders.map((f) => ({ name: f.name, path: f.path, git: f.git, github: f.github, floor: floorOf2(f) })) };
|
|
16594
17241
|
}
|
|
@@ -16613,6 +17260,7 @@ var Swarm = class {
|
|
|
16613
17260
|
}
|
|
16614
17261
|
disconnectRepo(id) {
|
|
16615
17262
|
const repo = this.repo(id);
|
|
17263
|
+
if (this.planPublications.has(id)) throw new HttpError(409, "Pause publication and wait for the in-flight action before disconnecting.");
|
|
16616
17264
|
this.state.ceo.queue = this.state.ceo.queue.filter((j) => j.repoId !== id);
|
|
16617
17265
|
for (const r of this.state.requests.filter((x) => x.repoId === id && x.status === "pending")) {
|
|
16618
17266
|
this.decide(r, { status: "rejected", note: "The floor was disconnected.", decidedBy: null });
|
|
@@ -16638,6 +17286,8 @@ var Swarm = class {
|
|
|
16638
17286
|
}
|
|
16639
17287
|
updateRepo(id, patch) {
|
|
16640
17288
|
const repo = this.repo(id);
|
|
17289
|
+
if (planningHeld(repo.appStarter) && (patch.mission !== void 0 || patch.previewCommand !== void 0 || patch.previewEnv !== void 0))
|
|
17290
|
+
throw new HttpError(409, "Use the project interview to revise the plan and environments before approval.");
|
|
16641
17291
|
const preview = parsePreviewPatch(patch.previewCommand, patch.previewEnv);
|
|
16642
17292
|
repo.preview = { ...repo.preview, ...preview };
|
|
16643
17293
|
if (preview.command === null) void this.previews.refreshDefault(repo);
|
|
@@ -16778,9 +17428,9 @@ var Swarm = class {
|
|
|
16778
17428
|
}
|
|
16779
17429
|
}
|
|
16780
17430
|
/** Show where auto-merge stands on a PR's card. Doesn't count as a change to the record. */
|
|
16781
|
-
mergeNote(rec,
|
|
16782
|
-
if (rec.mergeNote !==
|
|
16783
|
-
rec.mergeNote =
|
|
17431
|
+
mergeNote(rec, text4) {
|
|
17432
|
+
if (rec.mergeNote !== text4) {
|
|
17433
|
+
rec.mergeNote = text4;
|
|
16784
17434
|
this.broadcast({ type: "qa", qa: this.qaView(rec) });
|
|
16785
17435
|
}
|
|
16786
17436
|
return false;
|
|
@@ -16808,7 +17458,7 @@ var Swarm = class {
|
|
|
16808
17458
|
rt.folderSync = status;
|
|
16809
17459
|
this.emitRepo(repo);
|
|
16810
17460
|
if (status && status !== before) {
|
|
16811
|
-
const name = repo.localPath ?
|
|
17461
|
+
const name = repo.localPath ? path23.basename(repo.localPath) : repo.fullName;
|
|
16812
17462
|
if (status.startsWith("updated")) this.toast("success", `\u{1F4C1} ${name}: ${status}`);
|
|
16813
17463
|
else if (/behind|diverged|failed/.test(status)) this.toast("info", `\u{1F4C1} ${name} wasn't updated: ${status}`);
|
|
16814
17464
|
}
|
|
@@ -16834,13 +17484,13 @@ var Swarm = class {
|
|
|
16834
17484
|
const r = await this.backend.sweepDesks(repo.fullName, keep);
|
|
16835
17485
|
for (const a of agents) if (a.machine) r.branches += await this.machinesFor(a).sweep(a.machine, repo.fullName, keep.branches).catch(() => 0);
|
|
16836
17486
|
const desks = r.desks + r.folders;
|
|
16837
|
-
const saved = r.patches.length ? ` (${r.patches.length} patch${r.patches.length === 1 ? "" : "es"} saved to ${
|
|
17487
|
+
const saved = r.patches.length ? ` (${r.patches.length} patch${r.patches.length === 1 ? "" : "es"} saved to ${path23.dirname(r.patches[0])})` : "";
|
|
16838
17488
|
console.log(`desk sweep ${repo.fullName}: ${desks} desks, ${r.branches} branches removed${saved}${r.skipped.length ? `, ${r.skipped.length} still in use` : ""}`);
|
|
16839
17489
|
if (!desks && !r.branches) return;
|
|
16840
17490
|
const removed = [desks && `${desks} old desk${desks === 1 ? "" : "s"}`, r.branches && `${r.branches} finished branch${r.branches === 1 ? "" : "es"}`].filter(Boolean).join(" and ");
|
|
16841
|
-
const
|
|
16842
|
-
this.toast("info",
|
|
16843
|
-
this.postMessage("office",
|
|
17491
|
+
const text4 = `\u{1F9F9} ${repo.fullName.split("/")[1]}: removed ${removed}${saved}`;
|
|
17492
|
+
this.toast("info", text4);
|
|
17493
|
+
this.postMessage("office", text4);
|
|
16844
17494
|
} catch (err) {
|
|
16845
17495
|
console.warn(`desk sweep ${repo.fullName} failed: ${oneLine(err)}`);
|
|
16846
17496
|
}
|
|
@@ -16848,6 +17498,7 @@ var Swarm = class {
|
|
|
16848
17498
|
// ---------- the floor's app (preview monitor) ----------
|
|
16849
17499
|
/** Run the floor's app from its preview worktree: the default branch, or an open PR. Replaces what it is running now. */
|
|
16850
17500
|
async startPreview(id, pr) {
|
|
17501
|
+
this.requirePlanReady(this.repo(id));
|
|
16851
17502
|
const repo = this.repo(id);
|
|
16852
17503
|
return this.previews.start(repo, `${repo.fullName.split("/")[1]} app`, pr);
|
|
16853
17504
|
}
|
|
@@ -16856,6 +17507,7 @@ var Swarm = class {
|
|
|
16856
17507
|
}
|
|
16857
17508
|
/** The PR theatre: run an open PR beside the floor's main preview (kept when it's already up, unless restart). */
|
|
16858
17509
|
startPrPreview(id, pr, restart = false) {
|
|
17510
|
+
this.requirePlanReady(this.repo(id));
|
|
16859
17511
|
const repo = this.repo(id);
|
|
16860
17512
|
return this.previews.startPr(repo, pr, `${repo.fullName.split("/")[1]} app`, restart);
|
|
16861
17513
|
}
|
|
@@ -16893,6 +17545,7 @@ var Swarm = class {
|
|
|
16893
17545
|
return this.shutdownTask;
|
|
16894
17546
|
}
|
|
16895
17547
|
async finishShutdown(restart) {
|
|
17548
|
+
await Promise.allSettled([...this.planPublications.values()]);
|
|
16896
17549
|
if (this.openCodeAuthRun) this.cancelOpenCodeConfiguration(this.openCodeAuthRun.agentId);
|
|
16897
17550
|
this.backend.cloud.detach();
|
|
16898
17551
|
await this.writeState().catch((err) => console.warn("could not save the state", err));
|
|
@@ -16997,6 +17650,7 @@ var Swarm = class {
|
|
|
16997
17650
|
}
|
|
16998
17651
|
async createIssue(repoId2, title, body2, assignTo) {
|
|
16999
17652
|
const repo = this.repo(repoId2);
|
|
17653
|
+
this.requirePlanReady(repo);
|
|
17000
17654
|
if (!title.trim()) throw new HttpError(400, "An issue needs a title");
|
|
17001
17655
|
const number = await this.backend.createIssue(repo.fullName, title.trim(), body2);
|
|
17002
17656
|
await this.syncRepo(repo.id);
|
|
@@ -17110,6 +17764,7 @@ var Swarm = class {
|
|
|
17110
17764
|
}
|
|
17111
17765
|
/** End a session whose issue or PR closed, as ■ Stop does. Its desk is cleared once the session has ended. */
|
|
17112
17766
|
stopForClosure(a, why2) {
|
|
17767
|
+
this.cancelSessionStart(a);
|
|
17113
17768
|
a.status = "stopped";
|
|
17114
17769
|
a.lastError = `Stopped: ${why2}`;
|
|
17115
17770
|
this.dropping.set(a.id, why2);
|
|
@@ -17123,11 +17778,11 @@ var Swarm = class {
|
|
|
17123
17778
|
}
|
|
17124
17779
|
}
|
|
17125
17780
|
/** Clear the desk of an agent whose work closed, as ↺ Clear desk does. */
|
|
17126
|
-
dropTask(a,
|
|
17781
|
+
dropTask(a, text4, kind = "system") {
|
|
17127
17782
|
this.dropping.delete(a.id);
|
|
17128
17783
|
this.agentRt.get(a.id)?.terminal?.releaseIdle?.();
|
|
17129
17784
|
this.clearTask(a);
|
|
17130
|
-
if (
|
|
17785
|
+
if (text4) this.appendLog(a, [{ kind, text: text4 }]);
|
|
17131
17786
|
}
|
|
17132
17787
|
/** A task given up before its session started: one stopped because its issue or PR closed clears the desk now. */
|
|
17133
17788
|
abandoned(a) {
|
|
@@ -17188,6 +17843,7 @@ var Swarm = class {
|
|
|
17188
17843
|
hireAgent(repoId2, opts) {
|
|
17189
17844
|
const repo = this.repo(repoId2);
|
|
17190
17845
|
const team = this.state.agents.filter((a) => a.repoId === repo.id);
|
|
17846
|
+
this.requirePlanReady(repo);
|
|
17191
17847
|
const max = this.state.settings.maxAgents;
|
|
17192
17848
|
if (team.length >= max) throw new HttpError(409, `Floor ${repo.floor} already has ${team.length} agents, its most (${max}). Raise "Most agents per floor" in Settings to add more.`);
|
|
17193
17849
|
const used = new Set(team.map((a) => a.desk));
|
|
@@ -17196,10 +17852,12 @@ var Swarm = class {
|
|
|
17196
17852
|
if (desk >= FLOOR_SEATS) throw new HttpError(409, `Floor ${repo.floor} has no free desk (${FLOOR_SEATS} desks)`);
|
|
17197
17853
|
const name = opts.name?.trim().slice(0, 24) || this.freeName();
|
|
17198
17854
|
const cli = isCli(opts.cli) ? opts.cli : "";
|
|
17199
|
-
const
|
|
17855
|
+
const plannedHost = repo.appStarter?.plan?.environments.workerHost;
|
|
17856
|
+
if (plannedHost && opts.host && opts.host !== plannedHost) throw new HttpError(409, "Host incompatible with the approved project environments.");
|
|
17857
|
+
const host = this.hostFor(plannedHost ?? opts.host, cli || this.state.settings.defaultCli, !!plannedHost || !!opts.strict);
|
|
17200
17858
|
const localCli = cli || this.state.settings.defaultCli;
|
|
17201
17859
|
if (host === "local" && (cli || localCli === "opencode") && !this.cliReady(localCli)) throw new HttpError(400, `${cliLabel(localCli)} isn't installed on this computer.`);
|
|
17202
|
-
const id = opts.id && !this.state.agents.some((a) => a.id === opts.id) ? opts.id :
|
|
17860
|
+
const id = opts.id && !this.state.agents.some((a) => a.id === opts.id) ? opts.id : crypto11.randomUUID();
|
|
17203
17861
|
const agent = {
|
|
17204
17862
|
id,
|
|
17205
17863
|
name,
|
|
@@ -17233,6 +17891,10 @@ var Swarm = class {
|
|
|
17233
17891
|
logTail: []
|
|
17234
17892
|
};
|
|
17235
17893
|
this.state.agents.push(agent);
|
|
17894
|
+
if (repo.appStarter?.problem?.startsWith("Worker setup awaits compatible resources:")) {
|
|
17895
|
+
delete repo.appStarter.problem;
|
|
17896
|
+
this.emitRepo(repo);
|
|
17897
|
+
}
|
|
17236
17898
|
apply(this.state.progress, { kind: "hired", agentId: agent.id, at: Date.now() });
|
|
17237
17899
|
this.agentRt.set(agent.id, { log: [], session: null, currentTool: null, browserUrl: null, screenshot: null, shots: [], terminal: null });
|
|
17238
17900
|
this.appendLog(agent, [{ kind: "system", text: `\u{1F44B} ${name} joined floor ${repo.floor} (${repo.fullName})${host === "box" ? ", working in the cloud" : ""}.` }]);
|
|
@@ -17264,7 +17926,7 @@ var Swarm = class {
|
|
|
17264
17926
|
/** Create and set up a new cloud agent's Box in the background, so their first task doesn't wait for it. */
|
|
17265
17927
|
bringUpBox(a) {
|
|
17266
17928
|
const machine = this.machineOf(a);
|
|
17267
|
-
const note2 = (
|
|
17929
|
+
const note2 = (text4) => this.appendLog(a, [{ kind: "system", text: `\u2601 ${text4}` }]);
|
|
17268
17930
|
void this.boxMachines.ensure(machine, note2).then(() => {
|
|
17269
17931
|
note2("Their cloud machine is ready.");
|
|
17270
17932
|
void this.cloud.count().catch(() => void 0);
|
|
@@ -17280,6 +17942,7 @@ var Swarm = class {
|
|
|
17280
17942
|
* saved to leftovers); sessions can't move between machines, so their next one starts fresh.
|
|
17281
17943
|
*/
|
|
17282
17944
|
moveAgent(a, to) {
|
|
17945
|
+
if (!compatibleHost(this.repo(a.repoId).appStarter, to)) throw new HttpError(409, "Host incompatible with the approved project environments.");
|
|
17283
17946
|
if ((a.host ?? "local") === to) return;
|
|
17284
17947
|
if (a.task || BUSY3.includes(a.status)) throw new HttpError(409, `${a.name} is on a task: move them once it's done.`);
|
|
17285
17948
|
const host = this.hostFor(to, a.cli || this.state.settings.defaultCli, true, a);
|
|
@@ -17307,7 +17970,7 @@ var Swarm = class {
|
|
|
17307
17970
|
const api = this.cloud.boxApi();
|
|
17308
17971
|
if (!api) throw new Error("Cloud agents need your Upstash Box API key: Settings \u2192 Cloud agents.");
|
|
17309
17972
|
const machine = this.machineOf(a);
|
|
17310
|
-
const boxId = await this.boxMachines.ensure(machine, (
|
|
17973
|
+
const boxId = await this.boxMachines.ensure(machine, (text4) => this.appendLog(a, [{ kind: "system", text: `\u2601 ${text4}` }]));
|
|
17311
17974
|
const creds = await this.cloud.credentials(cli);
|
|
17312
17975
|
if (creds.missing.length) throw new Error(`Cloud agents can't sign in yet. Missing: ${creds.missing.join("; ")}.`);
|
|
17313
17976
|
if (check && creds.ownLogin && !await this.boxSignedIn(a, cli)) throw new SignInNeeded(cli);
|
|
@@ -17461,7 +18124,7 @@ var Swarm = class {
|
|
|
17461
18124
|
if (s2.run || s2.starting) return;
|
|
17462
18125
|
s2.starting = true;
|
|
17463
18126
|
try {
|
|
17464
|
-
const boxId = await this.boxMachines.ensure(this.machineOf(a), (
|
|
18127
|
+
const boxId = await this.boxMachines.ensure(this.machineOf(a), (text4) => this.appendLog(a, [{ kind: "system", text: `\u2601 ${text4}` }]));
|
|
17465
18128
|
if (!a.needsSignIn || this.signIns.get(a.id) !== s2 || s2.cli !== cli || !this.state.agents.includes(a)) return;
|
|
17466
18129
|
s2.run = this.backend.cloud.signIn({ api, boxId, cli, term: this.terminalFor(a), agentId: a.id }, (code) => void this.signInEnded(a, s2, code));
|
|
17467
18130
|
this.emitAgent(a);
|
|
@@ -17568,8 +18231,16 @@ var Swarm = class {
|
|
|
17568
18231
|
}
|
|
17569
18232
|
/** Every floor has at least one agent. */
|
|
17570
18233
|
ensureAgent(repo) {
|
|
18234
|
+
if (planningHeld(repo.appStarter)) return;
|
|
17571
18235
|
if (this.state.agents.some((a) => a.repoId === repo.id)) return;
|
|
17572
|
-
|
|
18236
|
+
try {
|
|
18237
|
+
this.hireAgent(repo.id, {});
|
|
18238
|
+
} catch (err) {
|
|
18239
|
+
if (!repo.appStarter) throw err;
|
|
18240
|
+
repo.appStarter.problem = `Worker setup awaits compatible resources: ${oneLine(err)}`;
|
|
18241
|
+
this.emitRepo(repo);
|
|
18242
|
+
this.save();
|
|
18243
|
+
}
|
|
17573
18244
|
}
|
|
17574
18245
|
/** A name from the pool that no agent or waiting candidate has. */
|
|
17575
18246
|
freeName() {
|
|
@@ -17628,7 +18299,7 @@ var Swarm = class {
|
|
|
17628
18299
|
this.agentRt.get(id)?.terminal?.releaseIdle?.();
|
|
17629
18300
|
this.agentRt.get(id)?.terminal?.dispose();
|
|
17630
18301
|
void removeScreens(id);
|
|
17631
|
-
void
|
|
18302
|
+
void fs23.rm(terminalFile(id), { force: true }).catch(() => void 0);
|
|
17632
18303
|
for (const q of this.state.qa) {
|
|
17633
18304
|
if (q.qaAgentId === id && q.status === "testing") this.setQa(q, { status: "queued", qaAgentId: null });
|
|
17634
18305
|
if (q.devAgentId === id) q.devAgentId = null;
|
|
@@ -17651,6 +18322,7 @@ var Swarm = class {
|
|
|
17651
18322
|
stopAgent(id) {
|
|
17652
18323
|
this.quotaWaiting.delete(id);
|
|
17653
18324
|
const a = this.agent(id);
|
|
18325
|
+
this.cancelSessionStart(a);
|
|
17654
18326
|
if (!BUSY3.includes(a.status)) return;
|
|
17655
18327
|
a.status = "stopped";
|
|
17656
18328
|
a.lastError = "Stopped by manager";
|
|
@@ -17670,6 +18342,7 @@ var Swarm = class {
|
|
|
17670
18342
|
}
|
|
17671
18343
|
/** The manager pressed Esc in the agent's terminal and the CLI stopped its turn: a Stop that leaves the CLI to them. */
|
|
17672
18344
|
interrupted(a) {
|
|
18345
|
+
this.cancelSessionStart(a);
|
|
17673
18346
|
if (!BUSY3.includes(a.status)) return;
|
|
17674
18347
|
a.status = "stopped";
|
|
17675
18348
|
a.lastError = "Interrupted in the terminal";
|
|
@@ -17708,14 +18381,15 @@ var Swarm = class {
|
|
|
17708
18381
|
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.");
|
|
17709
18382
|
}
|
|
17710
18383
|
/** A manual, local, read-only workflow: no issue, worktree, dependency install or PR pipeline. */
|
|
17711
|
-
analyze(agentId,
|
|
18384
|
+
analyze(agentId, text4, resume = false) {
|
|
17712
18385
|
const a = this.agent(agentId);
|
|
17713
18386
|
if (a.role === "ceo") throw new HttpError(400, "Give analysis tasks to a team member, not the CEO.");
|
|
17714
18387
|
if (a.host === "box") throw new HttpError(400, "Analysis is currently available on this computer only.");
|
|
17715
|
-
if (typeof
|
|
18388
|
+
if (typeof text4 !== "string" || !text4.trim() || text4.length > 4e3) throw new HttpError(400, "An analysis request must contain 1\u20134000 characters.");
|
|
17716
18389
|
if (BUSY3.includes(a.status)) throw new HttpError(409, `${a.name} is busy; stop the current task first.`);
|
|
17717
18390
|
const repo = this.repo(a.repoId);
|
|
17718
18391
|
if (this.repoRt.get(repo.id)?.cloneStatus !== "ready") throw new HttpError(409, "Wait until the repository checkout is ready.");
|
|
18392
|
+
this.requirePlanReady(repo, a);
|
|
17719
18393
|
if (!this.backend.deskExists(this.backend.mainDir(repo.fullName))) throw new HttpError(409, "The repository checkout is missing; reconnect it before starting analysis.");
|
|
17720
18394
|
this.ensureUsage(a, "issue");
|
|
17721
18395
|
this.ensureSlot();
|
|
@@ -17737,17 +18411,33 @@ var Swarm = class {
|
|
|
17737
18411
|
turns: 0,
|
|
17738
18412
|
lastError: null
|
|
17739
18413
|
});
|
|
17740
|
-
this.appendLog(a, [{ kind: "system", text: "\u2501\u2501\u2501 Read-only analysis \xB7 no issue or PR workflow \u2501\u2501\u2501" }, { kind: "manager", text: `\u25B6 ${
|
|
17741
|
-
this.startAgentSession(a, repo, this.backend.mainDir(repo.fullName),
|
|
18414
|
+
this.appendLog(a, [{ kind: "system", text: "\u2501\u2501\u2501 Read-only analysis \xB7 no issue or PR workflow \u2501\u2501\u2501" }, { kind: "manager", text: `\u25B6 ${text4.trim()}` }]);
|
|
18415
|
+
this.startAgentSession(a, repo, this.backend.mainDir(repo.fullName), text4.trim(), analysisPrompt(a.name, repo.fullName) + "\n" + communicationInstructions(this.state.settings.language), session);
|
|
17742
18416
|
this.save();
|
|
17743
18417
|
return this.agentView(a, false);
|
|
17744
18418
|
}
|
|
17745
18419
|
/** `waitForDeps`: refuse an issue that still waits for open ones (a sticky carried to a desk; the console may override). */
|
|
17746
18420
|
async assign(agentId, issueNumber, note2, waitForDeps = false) {
|
|
18421
|
+
return this.assignIssue(agentId, issueNumber, note2, waitForDeps);
|
|
18422
|
+
}
|
|
18423
|
+
canResumeIssue(a) {
|
|
18424
|
+
const rt = this.agentRt.get(a.id);
|
|
18425
|
+
return a.role !== "ceo" && a.task === "issue" && (a.status === "stopped" || a.status === "error") && a.issueNumber !== null && !!a.branch && !a.prNumber && !a.prUrl && !a.sessionId && !!rt && !rt.session && !rt.pendingBoxStart && !rt.terminal?.live && !a.needsSignIn && !this.issuePreparations.has(a.id) && !this.dropping.has(a.id);
|
|
18426
|
+
}
|
|
18427
|
+
/** Manager-confirmed recovery only; stale UI state cannot restart another task. */
|
|
18428
|
+
async resumeIssue(agentId, repoId2, issueNumber) {
|
|
18429
|
+
const a = this.agent(agentId);
|
|
18430
|
+
if (a.repoId !== repoId2 || a.issueNumber !== issueNumber || !this.canResumeIssue(a)) throw new HttpError(409, "This interrupted issue can no longer be resumed. Refresh the office and check the agent.");
|
|
18431
|
+
return this.assignIssue(agentId, issueNumber, void 0, false, a.branch);
|
|
18432
|
+
}
|
|
18433
|
+
async assignIssue(agentId, issueNumber, note2, waitForDeps = false, resumeBranch) {
|
|
17747
18434
|
const a = this.agent(agentId);
|
|
17748
18435
|
const repo = this.repo(a.repoId);
|
|
18436
|
+
this.requirePlanReady(repo, a);
|
|
17749
18437
|
if (a.role === "ceo") throw new HttpError(400, `${a.name} runs the company; give issues to the agents on the floors.`);
|
|
17750
18438
|
if (BUSY3.includes(a.status)) throw new HttpError(409, `${a.name} is busy: ${this.agentDoing(a)}`);
|
|
18439
|
+
if (this.issuePreparations.has(a.id)) throw new HttpError(409, `${a.name}'s previous setup is still finishing. Try again in a moment.`);
|
|
18440
|
+
if (this.agentRt.get(a.id)?.pendingBoxStart) throw new HttpError(409, `${a.name}'s previous session startup is still finishing. Try again in a moment.`);
|
|
17751
18441
|
this.ensureUsage(a, "issue");
|
|
17752
18442
|
this.ensureSlot();
|
|
17753
18443
|
const issues = this.repoRt.get(repo.id)?.issues ?? [];
|
|
@@ -17761,7 +18451,7 @@ var Swarm = class {
|
|
|
17761
18451
|
this.state.held = this.state.held.filter((h) => !(h.repoId === repo.id && h.issue === issueNumber));
|
|
17762
18452
|
this.emitRepo(repo);
|
|
17763
18453
|
}
|
|
17764
|
-
void this.runTask(a, repo, issue2, note2);
|
|
18454
|
+
void this.runTask(a, repo, issue2, note2, resumeBranch);
|
|
17765
18455
|
return this.agentView(a, false);
|
|
17766
18456
|
}
|
|
17767
18457
|
port(a) {
|
|
@@ -17793,7 +18483,7 @@ var Swarm = class {
|
|
|
17793
18483
|
}
|
|
17794
18484
|
// ---------- terminals ----------
|
|
17795
18485
|
async loadTerminal(agentId) {
|
|
17796
|
-
if (!await
|
|
18486
|
+
if (!await fs23.stat(terminalFile(agentId)).catch(() => null)) return null;
|
|
17797
18487
|
const t = this.newTerminal(agentId);
|
|
17798
18488
|
await t.load(terminalFile(agentId));
|
|
17799
18489
|
return t;
|
|
@@ -17806,8 +18496,8 @@ var Swarm = class {
|
|
|
17806
18496
|
}
|
|
17807
18497
|
newTerminal(agentId) {
|
|
17808
18498
|
const t = new AgentTerminal();
|
|
17809
|
-
t.onIdlePrompt = (
|
|
17810
|
-
void this.message(agentId,
|
|
18499
|
+
t.onIdlePrompt = (text4) => {
|
|
18500
|
+
void this.message(agentId, text4, true).catch(() => void 0);
|
|
17811
18501
|
return !!this.agentRt.get(agentId)?.session;
|
|
17812
18502
|
};
|
|
17813
18503
|
return t;
|
|
@@ -17861,6 +18551,7 @@ var Swarm = class {
|
|
|
17861
18551
|
return agentPromptPreview({ agent: a, repo, port: this.port(a), slug: slugify(a.name), linked: this.linkedDirs(repo, a) });
|
|
17862
18552
|
}
|
|
17863
18553
|
beginTask(a, patch, banner, preparing) {
|
|
18554
|
+
this.cancelSessionStart(a);
|
|
17864
18555
|
const rt = this.agentRt.get(a.id);
|
|
17865
18556
|
this.dropping.delete(a.id);
|
|
17866
18557
|
Object.assign(a, {
|
|
@@ -17887,12 +18578,14 @@ var Swarm = class {
|
|
|
17887
18578
|
/** job: the PR fix or QA run this desk is for; if the desk can't be set up, the PR pays for it, not the agent. */
|
|
17888
18579
|
async prepare(a, repo, base, branch, job) {
|
|
17889
18580
|
try {
|
|
18581
|
+
this.requirePlanReady(repo, a);
|
|
17890
18582
|
if (this.repoRt.get(repo.id)?.cloneStatus !== "ready") await this.cloneRepo(repo.id);
|
|
17891
|
-
const note2 = (
|
|
18583
|
+
const note2 = (text4) => this.appendLog(a, [{ kind: "system", text: text4 }]);
|
|
17892
18584
|
const cwd = await setUpDesk(this.agentRt.get(a.id)?.terminal, {
|
|
17893
18585
|
release: () => this.releaseDesk(a, repo),
|
|
17894
|
-
prepare: () => this.machinesFor(a).prepareDesk(this.machineOf(a), repo.fullName, { defaultBranch: repo.defaultBranch, pr: base.pr }, branch, note2)
|
|
18586
|
+
prepare: () => base.preserve && !a.machine && a.host !== "box" ? this.backend.prepareDesk(repo.fullName, { defaultBranch: repo.defaultBranch, preserve: true }, this.agentSlug(a), branch, note2) : this.machinesFor(a).prepareDesk(this.machineOf(a), repo.fullName, { defaultBranch: repo.defaultBranch, pr: base.pr, ...base.preserve ? { preserve: true } : {} }, branch, note2)
|
|
17895
18587
|
});
|
|
18588
|
+
if (base.preserve && !a.machine && a.host !== "box") a.legacyDeskSlug = path23.basename(cwd);
|
|
17896
18589
|
this.deskAlerts.delete(a.id);
|
|
17897
18590
|
if (job) this.prepStrikes.delete(prepKey(repo.id, job.rec.prNumber, job.task));
|
|
17898
18591
|
if (a.status !== "preparing") return this.abandoned(a);
|
|
@@ -17961,8 +18654,8 @@ var Swarm = class {
|
|
|
17961
18654
|
const rt = this.agentRt.get(a.id);
|
|
17962
18655
|
const cb = {
|
|
17963
18656
|
log: (lines) => {
|
|
17964
|
-
this.appendLog(a, lines.map((
|
|
17965
|
-
if (a.status === "preparing") for (const
|
|
18657
|
+
this.appendLog(a, lines.map((text4) => ({ kind: text4.startsWith("\u26A0") ? "error" : "system", text: text4 })));
|
|
18658
|
+
if (a.status === "preparing") for (const text4 of lines) rt?.terminal?.note(text4);
|
|
17966
18659
|
},
|
|
17967
18660
|
installing: () => {
|
|
17968
18661
|
if (!rt) return;
|
|
@@ -17979,9 +18672,16 @@ var Swarm = class {
|
|
|
17979
18672
|
}
|
|
17980
18673
|
}
|
|
17981
18674
|
}
|
|
17982
|
-
|
|
18675
|
+
runTask(a, repo, issue2, note2, resumeBranch) {
|
|
18676
|
+
this.issuePreparations.add(a.id);
|
|
18677
|
+
return this.runIssueTask(a, repo, issue2, note2, resumeBranch).finally(() => {
|
|
18678
|
+
this.issuePreparations.delete(a.id);
|
|
18679
|
+
if (this.state.agents.includes(a)) this.emitAgent(a);
|
|
18680
|
+
});
|
|
18681
|
+
}
|
|
18682
|
+
async runIssueTask(a, repo, issue2, note2, resumeBranch) {
|
|
17983
18683
|
if (this.cloudWorkPaused(a)) return;
|
|
17984
|
-
const branch = devBranch(issue2.number, slugify(a.name));
|
|
18684
|
+
const branch = resumeBranch ?? devBranch(issue2.number, slugify(a.name));
|
|
17985
18685
|
this.beginTask(
|
|
17986
18686
|
a,
|
|
17987
18687
|
{ task: "issue", issueNumber: issue2.number, issueTitle: issue2.title, branch, prNumber: null, prUrl: null, sessionId: null },
|
|
@@ -17997,7 +18697,7 @@ var Swarm = class {
|
|
|
17997
18697
|
this.learnIssueClosed(repo, issue2.number);
|
|
17998
18698
|
return;
|
|
17999
18699
|
}
|
|
18000
|
-
const desk = await this.prepare(a, repo, {}, branch);
|
|
18700
|
+
const desk = await this.prepare(a, repo, resumeBranch ? { preserve: true } : {}, branch);
|
|
18001
18701
|
if (!desk) return;
|
|
18002
18702
|
const { cwd } = desk;
|
|
18003
18703
|
const prompt = [
|
|
@@ -18009,36 +18709,57 @@ var Swarm = class {
|
|
|
18009
18709
|
note2 ? `
|
|
18010
18710
|
Note from the manager: ${note2}` : ""
|
|
18011
18711
|
].filter(Boolean).join("\n");
|
|
18012
|
-
this.startAgentSession(a, repo, cwd, prompt, this.buildSystemAppend(a, repo, cwd, branch, void 0, desk.deps));
|
|
18712
|
+
await this.startAgentSession(a, repo, cwd, prompt, this.buildSystemAppend(a, repo, cwd, branch, void 0, desk.deps));
|
|
18713
|
+
}
|
|
18714
|
+
cancelSessionStart(a) {
|
|
18715
|
+
const rt = this.agentRt.get(a.id);
|
|
18716
|
+
if (rt) rt.sessionStart = void 0;
|
|
18717
|
+
}
|
|
18718
|
+
currentSessionStart(a, attempt) {
|
|
18719
|
+
return !this.stopping && this.state.agents.includes(a) && this.agentRt.get(a.id)?.sessionStart === attempt;
|
|
18013
18720
|
}
|
|
18014
18721
|
startAgentSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode = null) {
|
|
18015
18722
|
const rt = this.agentRt.get(a.id);
|
|
18016
18723
|
if (!rt || !this.state.agents.includes(a)) return;
|
|
18724
|
+
if (!compatibleHost(repo.appStarter, a.host ?? "local")) return;
|
|
18725
|
+
const attempt = /* @__PURE__ */ Symbol("session startup");
|
|
18726
|
+
rt.sessionStart = attempt;
|
|
18017
18727
|
if (!mode && this.cloudWorkPaused(a)) {
|
|
18018
|
-
this.waitForCloudResume(a, () => this.startAgentSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode));
|
|
18728
|
+
this.waitForCloudResume(a, () => this.currentSessionStart(a, attempt) && this.startAgentSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode));
|
|
18019
18729
|
return;
|
|
18020
18730
|
}
|
|
18021
18731
|
if (a.host === "box" && mode !== "reattach") {
|
|
18022
18732
|
const cli = this.sessionRuntime(a, resumeSessionId).cli ?? "claude";
|
|
18023
|
-
const note2 = (
|
|
18024
|
-
|
|
18733
|
+
const note2 = (text4) => this.appendLog(a, [{ kind: "system", text: text4 }]);
|
|
18734
|
+
rt.pendingBoxStart = attempt;
|
|
18735
|
+
return this.boxTarget(a, cli, repo.browserTesting, mode !== "typed").then(async (box) => {
|
|
18736
|
+
if (!this.currentSessionStart(a, attempt)) return;
|
|
18025
18737
|
const linked = await this.boxMachines.linkRepos(this.machineOf(a), this.linkedRepos(repo).map((r) => r.fullName), note2).catch(() => []);
|
|
18026
|
-
this.
|
|
18738
|
+
if (!this.currentSessionStart(a, attempt)) return;
|
|
18739
|
+
this.launchSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode, box, linked, attempt);
|
|
18027
18740
|
}).catch((err) => {
|
|
18028
|
-
if (
|
|
18741
|
+
if (!this.currentSessionStart(a, attempt)) return;
|
|
18742
|
+
if (err instanceof SignInNeeded) return this.holdForSignIn(a, err.cli, () => this.currentSessionStart(a, attempt) && this.startAgentSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode));
|
|
18029
18743
|
const why2 = redact(oneLine(err), this.secrets());
|
|
18030
18744
|
this.appendLog(a, [{ kind: "error", text: `\u2717 ${why2}` }]);
|
|
18031
18745
|
void this.onFinished(a, repo, { ok: false, text: "", costUsd: 0, turns: 0, errors: [why2] });
|
|
18746
|
+
}).finally(() => {
|
|
18747
|
+
if (rt.pendingBoxStart === attempt) rt.pendingBoxStart = void 0;
|
|
18748
|
+
if (this.state.agents.includes(a)) {
|
|
18749
|
+
if (this.dropping.has(a.id) && !rt.session) this.abandoned(a);
|
|
18750
|
+
this.emitAgent(a);
|
|
18751
|
+
}
|
|
18032
18752
|
});
|
|
18033
18753
|
return;
|
|
18034
18754
|
}
|
|
18035
|
-
this.launchSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode);
|
|
18755
|
+
this.launchSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode, void 0, void 0, attempt);
|
|
18036
18756
|
}
|
|
18037
|
-
launchSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode, box, linked) {
|
|
18757
|
+
launchSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode, box, linked, attempt) {
|
|
18038
18758
|
const rt = this.agentRt.get(a.id);
|
|
18039
18759
|
if (!rt || !this.state.agents.includes(a)) return;
|
|
18760
|
+
if (!this.currentSessionStart(a, attempt)) return;
|
|
18040
18761
|
if (!mode && this.cloudWorkPaused(a)) {
|
|
18041
|
-
this.waitForCloudResume(a, () => this.launchSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode, box, linked));
|
|
18762
|
+
this.waitForCloudResume(a, () => this.launchSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode, box, linked, attempt));
|
|
18042
18763
|
return;
|
|
18043
18764
|
}
|
|
18044
18765
|
if (a.host !== "box" && sessionStart(this.backend.deskExists(cwd), mode) === "prepare") {
|
|
@@ -18049,12 +18770,14 @@ Note from the manager: ${note2}` : ""
|
|
|
18049
18770
|
return;
|
|
18050
18771
|
}
|
|
18051
18772
|
const machine = a.machine;
|
|
18052
|
-
void this.restoreDesk(a, repo).then((dir) =>
|
|
18773
|
+
void this.restoreDesk(a, repo).then((dir) => {
|
|
18774
|
+
if (dir && this.currentSessionStart(a, attempt)) return this.startAgentSession(a, repo, dir, prompt, systemAppend, a.machine === machine ? resumeSessionId : void 0, outputSchema, mode);
|
|
18775
|
+
});
|
|
18053
18776
|
return;
|
|
18054
18777
|
}
|
|
18055
18778
|
const how = this.sessionRuntime(a, resumeSessionId);
|
|
18056
18779
|
if (!mode && !this.quotaGate().allows(this.gateKey(a, this.resourceFor(a, how.cli ?? "claude")), "ceo", Date.now(), 0, 1)) {
|
|
18057
|
-
this.quotaWaiting.set(a.id, () => this.launchSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode, box, linked));
|
|
18780
|
+
this.quotaWaiting.set(a.id, () => this.launchSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode, box, linked, attempt));
|
|
18058
18781
|
a.status = "stopped";
|
|
18059
18782
|
a.lastError = "Waiting for AI quota reset";
|
|
18060
18783
|
this.emitAgent(a);
|
|
@@ -18114,7 +18837,7 @@ Note from the manager: ${note2}` : ""
|
|
|
18114
18837
|
rt.shots.push({ data, mime, url: rt.browserUrl, at });
|
|
18115
18838
|
if (rt.shots.length > 12) rt.shots.shift();
|
|
18116
18839
|
this.broadcast({ type: "screen", agentId: a.id, url: rt.browserUrl, at });
|
|
18117
|
-
void removeScreens(a.id).then(() =>
|
|
18840
|
+
void removeScreens(a.id).then(() => fs23.mkdir(SCREENS_DIR, { recursive: true })).then(() => fs23.writeFile(screenFile(a.id, mime), data)).catch((err) => console.warn("could not save screenshot", err));
|
|
18118
18841
|
},
|
|
18119
18842
|
usage: (observation) => this.recordAiUsage(a, observation),
|
|
18120
18843
|
usageBatch: (observations) => this.recordAiUsageBatch(a, observations),
|
|
@@ -18306,6 +19029,7 @@ Note from the manager: ${note2}` : ""
|
|
|
18306
19029
|
/** Manager's "send to QA" for any open PR (including ones opened by people); with `agentId`, that free agent tests it now. */
|
|
18307
19030
|
async sendToQa(repoId2, prNumber, agentId) {
|
|
18308
19031
|
const repo = this.repo(repoId2);
|
|
19032
|
+
this.requirePlanReady(repo, agentId ? this.agent(agentId) : void 0);
|
|
18309
19033
|
const pr = this.repoRt.get(repo.id)?.pulls.find((p) => p.number === prNumber && p.state === "OPEN");
|
|
18310
19034
|
if (!pr) throw new HttpError(404, `PR #${prNumber} is not open on ${repo.fullName}`);
|
|
18311
19035
|
const rec = this.state.qa.find((q) => q.repoId === repo.id && q.prNumber === prNumber);
|
|
@@ -18333,6 +19057,7 @@ Note from the manager: ${note2}` : ""
|
|
|
18333
19057
|
/** Manager's "send back to dev" for a PR that needs a human or failed QA: a developer fixes it, with the note. */
|
|
18334
19058
|
async sendBackToDev(repoId2, prNumber, note2, from) {
|
|
18335
19059
|
const repo = this.repo(repoId2);
|
|
19060
|
+
this.requirePlanReady(repo);
|
|
18336
19061
|
const find = () => this.state.qa.find((q) => q.repoId === repo.id && q.prNumber === prNumber);
|
|
18337
19062
|
const listed = this.repoRt.get(repo.id)?.pulls.find((p) => p.number === prNumber);
|
|
18338
19063
|
const allowPassed = from === void 0;
|
|
@@ -18350,6 +19075,7 @@ Note from the manager: ${note2}` : ""
|
|
|
18350
19075
|
return qaSystemPrompt({ agent: a, repo, port: this.port(a), cwd, branch, pr, testStep: testStep2, depsLine: depsPromptLine(deps) });
|
|
18351
19076
|
}
|
|
18352
19077
|
async runQa(a, repo, rec) {
|
|
19078
|
+
if (!compatibleHost(repo.appStarter, a.host ?? "local")) return;
|
|
18353
19079
|
if (this.cloudWorkPaused(a)) return;
|
|
18354
19080
|
if (this.backend.allowWork && !this.backend.allowWork("qa", a)) return;
|
|
18355
19081
|
const branch = qaBranch(rec.prNumber, slugify(a.name));
|
|
@@ -18474,7 +19200,6 @@ ${issue2.body.trim() || "(no description)"}` : ""
|
|
|
18474
19200
|
}
|
|
18475
19201
|
return;
|
|
18476
19202
|
}
|
|
18477
|
-
a.status = "done";
|
|
18478
19203
|
const pass = report.verdict === "pass";
|
|
18479
19204
|
if (rec) this.ledger({ kind: "qa", repoId: repo.id, pr: rec.prNumber, round: rec.round, pass, tester: a.id, author: rec.devAgentId, at: Date.now() });
|
|
18480
19205
|
this.appendLog(a, [{ kind: pass ? "done" : "error", text: `${pass ? "\u2705 QA passed" : "\u274C QA failed"} PR #${a.prNumber} \xB7 ${report.checks.length} checks \xB7 ${rt.shots.length} screenshots` }]);
|
|
@@ -18528,6 +19253,7 @@ ${issue2.body.trim() || "(no description)"}` : ""
|
|
|
18528
19253
|
pass ? `\u2705 ${a.name} passed PR #${rec.prNumber}${repo.autoMerge ? "; it merges once GitHub's checks are green" : ": ready to merge"}` : nextStatus === "needs-human" ? `\u274C PR #${rec.prNumber} failed QA ${qaRounds} times${triaged ? `; ${this.ceo().name} takes a look before it comes to you` : " and needs a human"}` : next2 === "conflict" ? `\u274C ${a.name} failed PR #${rec.prNumber}, and it conflicts with ${repo.defaultBranch}; sending it back to merge and fix` : `\u274C ${a.name} failed PR #${rec.prNumber}; sending it back to the developer`
|
|
18529
19254
|
);
|
|
18530
19255
|
}
|
|
19256
|
+
if (a.status !== "stopped") a.status = "done";
|
|
18531
19257
|
}
|
|
18532
19258
|
async renderQaComment(a, repo, rec, report, shots, next) {
|
|
18533
19259
|
const pass = report.verdict === "pass";
|
|
@@ -18572,6 +19298,7 @@ ${issue2.body.trim() || "(no description)"}` : ""
|
|
|
18572
19298
|
}
|
|
18573
19299
|
/** Send a failed PR back to the agent who wrote it (or any free agent on the floor). */
|
|
18574
19300
|
async runFix(dev, repo, rec) {
|
|
19301
|
+
if (!compatibleHost(repo.appStarter, dev.host ?? "local")) return;
|
|
18575
19302
|
if (this.cloudWorkPaused(dev)) return;
|
|
18576
19303
|
if (this.backend.allowWork && !this.backend.allowWork("fix", dev)) return;
|
|
18577
19304
|
const original = rec.devAgentId === dev.id;
|
|
@@ -18735,30 +19462,30 @@ Full report with screenshots: ${rec.commentUrl}` : "",
|
|
|
18735
19462
|
}
|
|
18736
19463
|
}
|
|
18737
19464
|
/** A message for an agent: sent into their running session, or a follow-up that resumes it. typed: the manager typed it at their CLI's prompt, where it's already running. */
|
|
18738
|
-
async message(id,
|
|
19465
|
+
async message(id, text4, typed = false) {
|
|
18739
19466
|
const a = this.agent(id);
|
|
18740
|
-
if (a.role === "ceo") return this.messageCeo(
|
|
19467
|
+
if (a.role === "ceo") return this.messageCeo(text4);
|
|
18741
19468
|
const repo = this.repo(a.repoId);
|
|
18742
|
-
if (!
|
|
19469
|
+
if (!text4.trim()) throw new HttpError(400, "Empty message");
|
|
18743
19470
|
const rt = this.agentRt.get(id);
|
|
18744
19471
|
if (rt.session) {
|
|
18745
|
-
this.appendLog(a, [{ kind: "manager", text: `\u25B6 Manager: ${
|
|
19472
|
+
this.appendLog(a, [{ kind: "manager", text: `\u25B6 Manager: ${text4}` }]);
|
|
18746
19473
|
if (!typed) rt.session.send(a.task === "analysis" ? `${communicationInstructions(this.state.settings.language)}
|
|
18747
|
-
${
|
|
19474
|
+
${text4}` : text4);
|
|
18748
19475
|
return;
|
|
18749
19476
|
}
|
|
18750
19477
|
if (a.status === "preparing") throw new HttpError(409, `${a.name} is still setting up; try again in a moment`);
|
|
18751
|
-
if (a.task === "analysis") return this.analyze(id,
|
|
19478
|
+
if (a.task === "analysis") return this.analyze(id, text4, true);
|
|
18752
19479
|
if (!a.sessionId || !a.branch || a.task === "qa") throw new HttpError(409, `${a.name} has no session to continue. Give them an issue or a PR to test instead.`);
|
|
18753
19480
|
if (!typed) this.ensureUsage(a, a.task === "fix" ? "fix" : "issue");
|
|
18754
19481
|
this.ensureSlot();
|
|
18755
|
-
this.appendLog(a, [{ kind: "manager", text: `\u25B6 Manager: ${
|
|
19482
|
+
this.appendLog(a, [{ kind: "manager", text: `\u25B6 Manager: ${text4}` }]);
|
|
18756
19483
|
const cwd = this.deskOf(a, repo);
|
|
18757
19484
|
a.lastError = null;
|
|
18758
19485
|
a.startedAt = Date.now();
|
|
18759
19486
|
if (a.task === null) a.task = "issue";
|
|
18760
19487
|
const fixing = a.task === "fix" && a.prNumber ? { pr: a.prNumber, headRef: a.branch } : void 0;
|
|
18761
|
-
this.startAgentSession(a, repo, cwd,
|
|
19488
|
+
this.startAgentSession(a, repo, cwd, text4, this.buildSystemAppend(a, repo, cwd, a.branch, fixing), a.sessionId, void 0, typed ? "typed" : null);
|
|
18762
19489
|
}
|
|
18763
19490
|
updateSettings(patch) {
|
|
18764
19491
|
const s2 = this.state.settings;
|
|
@@ -18777,7 +19504,7 @@ ${text3}` : text3);
|
|
|
18777
19504
|
if (typeof patch.managerName === "string") s2.managerName = patch.managerName.trim().slice(0, 40);
|
|
18778
19505
|
if (typeof patch.companyName === "string") s2.companyName = patch.companyName.trim().slice(0, 60);
|
|
18779
19506
|
if (typeof patch.dogName === "string") s2.dogName = patch.dogName.trim().slice(0, 24) || DEFAULT_DOG_NAME;
|
|
18780
|
-
if (typeof patch.projectsDir === "string" && patch.projectsDir.trim()) s2.projectsDir =
|
|
19507
|
+
if (typeof patch.projectsDir === "string" && patch.projectsDir.trim()) s2.projectsDir = path23.resolve(patch.projectsDir.trim());
|
|
18781
19508
|
if (typeof patch.setupDone === "boolean") s2.setupDone = patch.setupDone;
|
|
18782
19509
|
if (patch.tutorialStep !== void 0) s2.tutorialStep = Math.max(-1, Math.round(Number(patch.tutorialStep)) || 0);
|
|
18783
19510
|
if (typeof patch.autoUpdate === "boolean") s2.autoUpdate = patch.autoUpdate;
|
|
@@ -18842,7 +19569,7 @@ ${text3}` : text3);
|
|
|
18842
19569
|
}
|
|
18843
19570
|
/** A floor's agents who can take work now, by desk. */
|
|
18844
19571
|
available(repo) {
|
|
18845
|
-
return this.state.agents.filter((a) => a.repoId === repo.id && a.role !== "ceo" && this.isFree(a) && !this.limited(a)).sort((x, y) => x.desk - y.desk);
|
|
19572
|
+
return this.state.agents.filter((a) => a.repoId === repo.id && a.role !== "ceo" && compatibleHost(repo.appStarter, a.host ?? "local") && this.isFree(a) && !this.limited(a)).sort((x, y) => x.desk - y.desk);
|
|
18846
19573
|
}
|
|
18847
19574
|
scheduleOffset = 0;
|
|
18848
19575
|
issueFailures = /* @__PURE__ */ new Map();
|
|
@@ -18870,6 +19597,7 @@ ${text3}` : text3);
|
|
|
18870
19597
|
* failing to set up sits out.
|
|
18871
19598
|
*/
|
|
18872
19599
|
startPipelineWork(repo) {
|
|
19600
|
+
if (planningHeld(repo.appStarter)) return false;
|
|
18873
19601
|
const free = this.available(repo);
|
|
18874
19602
|
if (!free.length) return false;
|
|
18875
19603
|
const now2 = Date.now();
|
|
@@ -18906,7 +19634,7 @@ ${text3}` : text3);
|
|
|
18906
19634
|
* "Depends on #N" wait until #N is closed; the rest go in readyIssues() order.
|
|
18907
19635
|
*/
|
|
18908
19636
|
startIssueWork(repo) {
|
|
18909
|
-
if (!repo.autoAssign) return false;
|
|
19637
|
+
if (!repo.autoAssign || planningHeld(repo.appStarter)) return false;
|
|
18910
19638
|
const agent = this.available(repo).find((a) => this.mayStart("issue", a));
|
|
18911
19639
|
const next = agent ? this.readyIssues(repo)[0] : void 0;
|
|
18912
19640
|
if (!agent || !next) return false;
|
|
@@ -18931,7 +19659,7 @@ ${text3}` : text3);
|
|
|
18931
19659
|
}
|
|
18932
19660
|
resourceKey(a, resource = this.resourceFor(a)) {
|
|
18933
19661
|
const identity = quotaKey({ ...resource, fallback: `${a.id}:${this.usageHost(a)}` });
|
|
18934
|
-
return
|
|
19662
|
+
return crypto11.createHash("sha256").update(identity).digest("hex").slice(0, 32);
|
|
18935
19663
|
}
|
|
18936
19664
|
gateKey(a, resource = this.resourceFor(a)) {
|
|
18937
19665
|
const key = this.resourceKey(a, resource);
|
|
@@ -18941,7 +19669,7 @@ ${text3}` : text3);
|
|
|
18941
19669
|
return a.host === "box" ? `box:${a.machine ?? a.id}` : "local";
|
|
18942
19670
|
}
|
|
18943
19671
|
recordResource(a, resource) {
|
|
18944
|
-
if (resource.account) resource = { ...resource, account:
|
|
19672
|
+
if (resource.account) resource = { ...resource, account: crypto11.createHash("sha256").update(`${this.usageHost(a)}:${resource.tool}:${resource.account}`).digest("hex").slice(0, 24) };
|
|
18945
19673
|
(this.state.aiResources ??= {})[a.id] = { resource, configuredModel: this.modelFor(a, resource.tool), host: this.usageHost(a), at: Date.now() };
|
|
18946
19674
|
this.save();
|
|
18947
19675
|
this.emitUsage();
|
|
@@ -19020,6 +19748,7 @@ ${text3}` : text3);
|
|
|
19020
19748
|
}
|
|
19021
19749
|
/** May work of this kind start now, as far as resource controls and AI usage go? */
|
|
19022
19750
|
mayStart(kind, a) {
|
|
19751
|
+
if (a.role !== "ceo" && !compatibleHost(this.state.repos.find((r) => r.id === a.repoId)?.appStarter, a.host ?? "local")) return false;
|
|
19023
19752
|
if (this.cloudWorkPaused(a)) return false;
|
|
19024
19753
|
if (this.backend.allowWork && !this.backend.allowWork(kind, a)) return false;
|
|
19025
19754
|
if (this.configuringOpenCode) return false;
|
|
@@ -19139,6 +19868,7 @@ ${text3}` : text3);
|
|
|
19139
19868
|
* so no repo can hog the slots.
|
|
19140
19869
|
*/
|
|
19141
19870
|
schedule() {
|
|
19871
|
+
if (this.stopping) return;
|
|
19142
19872
|
this.tickUsage();
|
|
19143
19873
|
this.progressTick();
|
|
19144
19874
|
if (this.officeUpdateTick()) return;
|
|
@@ -19395,7 +20125,8 @@ ${job.text}` } : job;
|
|
|
19395
20125
|
if (!a || BUSY3.includes(a.status) || c.job || c.queue.length === 0) return;
|
|
19396
20126
|
if (!this.mayStart("ceo", a)) return;
|
|
19397
20127
|
if (this.slotsFull()) return;
|
|
19398
|
-
|
|
20128
|
+
c.queue = c.queue.filter((j) => j.kind !== "app-starter" || this.currentAppJob(j));
|
|
20129
|
+
const rank = { chat: 0, "app-starter": 0, triage: 0, onboard: 1, plan: 1, review: 2 };
|
|
19399
20130
|
const ready2 = (j) => {
|
|
19400
20131
|
const rt2 = j.repoId ? this.repoRt.get(j.repoId) : void 0;
|
|
19401
20132
|
return !rt2 || rt2.cloneStatus === "error" || rt2.cloneStatus === "ready" && rt2.lastSync != null;
|
|
@@ -19415,9 +20146,10 @@ ${job.text}` } : job;
|
|
|
19415
20146
|
}
|
|
19416
20147
|
ceoPromptInput(a) {
|
|
19417
20148
|
const s2 = this.state.settings;
|
|
19418
|
-
return { name: a.name, company: s2.companyName, manager: s2.managerName, notesFile:
|
|
20149
|
+
return { name: a.name, company: s2.companyName, manager: s2.managerName, notesFile: path23.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) };
|
|
19419
20150
|
}
|
|
19420
20151
|
async runCeoJob(a, job) {
|
|
20152
|
+
if (job.kind === "app-starter" && !this.currentAppJob(job)) return;
|
|
19421
20153
|
const rt = this.agentRt.get(a.id);
|
|
19422
20154
|
const floor = this.ceoFloor(job.repoId);
|
|
19423
20155
|
const label = jobLabel(job, floor);
|
|
@@ -19437,7 +20169,7 @@ ${job.text}` } : job;
|
|
|
19437
20169
|
this.emitAgent(a);
|
|
19438
20170
|
this.emitCeo();
|
|
19439
20171
|
this.save();
|
|
19440
|
-
await
|
|
20172
|
+
await fs23.mkdir(CEO_DIR, { recursive: true }).catch(() => void 0);
|
|
19441
20173
|
const triage2 = job.kind === "triage" ? await this.triagePr(job) : null;
|
|
19442
20174
|
if (a.status !== "working") {
|
|
19443
20175
|
this.state.ceo.job = null;
|
|
@@ -19456,18 +20188,23 @@ ${job.text}` } : job;
|
|
|
19456
20188
|
return;
|
|
19457
20189
|
}
|
|
19458
20190
|
const how = this.sessionRuntime(a, job.kind === "chat" ? a.sessionId ?? void 0 : void 0);
|
|
20191
|
+
const draft = job.kind === "app-starter" ? this.repo(job.repoId).appStarter : void 0;
|
|
20192
|
+
const scopedSystem = draft ? `${communicationInstructions(this.state.settings.language)}
|
|
20193
|
+
${planningSkill()}
|
|
20194
|
+
Project ${job.repoId}. Persistent context:
|
|
20195
|
+
${JSON.stringify(draft)}` : ceoSystemPrompt(this.ceoPromptInput(a));
|
|
19459
20196
|
rt.session = this.backend.startSession(
|
|
19460
20197
|
{
|
|
19461
20198
|
cwd: CEO_DIR,
|
|
19462
20199
|
prompt: ceoJobPrompt(job, floor, triage2),
|
|
19463
|
-
systemAppend:
|
|
20200
|
+
systemAppend: scopedSystem,
|
|
19464
20201
|
model: this.modelFor(a, how.cli),
|
|
19465
20202
|
effort: a.effort || CEO_EFFORT,
|
|
19466
20203
|
browserTesting: false,
|
|
19467
|
-
additionalDirectories: this.state.repos.filter((r) => this.repoRt.get(r.id)?.cloneStatus === "ready").map((r) => this.backend.mainDir(r.fullName)),
|
|
20204
|
+
additionalDirectories: this.state.repos.filter((r) => (!draft || r.id === job.repoId) && this.repoRt.get(r.id)?.cloneStatus === "ready").map((r) => this.backend.mainDir(r.fullName)),
|
|
19468
20205
|
role: "ceo",
|
|
19469
20206
|
agentId: a.id,
|
|
19470
|
-
office: this.officeTools(),
|
|
20207
|
+
office: this.officeTools(job),
|
|
19471
20208
|
...how
|
|
19472
20209
|
},
|
|
19473
20210
|
{
|
|
@@ -19478,12 +20215,15 @@ ${job.text}` } : job;
|
|
|
19478
20215
|
this.emitAgent(a);
|
|
19479
20216
|
},
|
|
19480
20217
|
sessionId: (id) => {
|
|
20218
|
+
if (draft) return;
|
|
19481
20219
|
a.sessionId = id;
|
|
19482
20220
|
a.sessionCli = id ? how.cli ?? "claude" : null;
|
|
19483
20221
|
},
|
|
19484
20222
|
browserUrl: () => void 0,
|
|
19485
20223
|
screenshot: () => void 0,
|
|
19486
|
-
turn: (
|
|
20224
|
+
turn: (text4) => {
|
|
20225
|
+
if (!draft) this.postMessage("ceo", text4);
|
|
20226
|
+
},
|
|
19487
20227
|
usage: (observation) => this.recordAiUsage(a, observation),
|
|
19488
20228
|
usageBatch: (observations) => this.recordAiUsageBatch(a, observations),
|
|
19489
20229
|
resource: (resource) => this.recordResource(a, resource),
|
|
@@ -19526,13 +20266,13 @@ ${job.text}` } : job;
|
|
|
19526
20266
|
setTimeout(() => this.schedule(), 300);
|
|
19527
20267
|
}
|
|
19528
20268
|
/** The manager's phone → the CEO. Injected into a running session, otherwise the CEO picks it up next. */
|
|
19529
|
-
async messageCeo(
|
|
19530
|
-
const t =
|
|
20269
|
+
async messageCeo(text4) {
|
|
20270
|
+
const t = text4.trim().slice(0, 4e3);
|
|
19531
20271
|
if (!t) throw new HttpError(400, "Empty message");
|
|
19532
20272
|
const a = this.ceo();
|
|
19533
20273
|
this.postMessage("manager", t);
|
|
19534
20274
|
const rt = this.agentRt.get(a.id);
|
|
19535
|
-
if (rt.session) {
|
|
20275
|
+
if (rt.session && this.state.ceo.job?.kind !== "app-starter") {
|
|
19536
20276
|
this.appendLog(a, [{ kind: "manager", text: `\u25B6 Manager: ${t}` }]);
|
|
19537
20277
|
this.ceoIssues.managerMessage();
|
|
19538
20278
|
this.ceoAsked = true;
|
|
@@ -19549,11 +20289,13 @@ ${t}`);
|
|
|
19549
20289
|
}
|
|
19550
20290
|
onboardFloor(repoId2) {
|
|
19551
20291
|
const repo = this.repo(repoId2);
|
|
20292
|
+
this.requirePlanReady(repo);
|
|
19552
20293
|
this.enqueueCeo({ kind: "onboard", repoId: repo.id, at: Date.now() });
|
|
19553
20294
|
}
|
|
19554
20295
|
/** The manager hands the CEO a brief for a floor; the CEO turns it into issues and a team. */
|
|
19555
20296
|
planFloor(repoId2, mission) {
|
|
19556
20297
|
const repo = this.repo(repoId2);
|
|
20298
|
+
this.requirePlanReady(repo);
|
|
19557
20299
|
if (typeof mission === "string") {
|
|
19558
20300
|
repo.mission = mission.trim().slice(0, 4e3);
|
|
19559
20301
|
this.emitRepo(repo);
|
|
@@ -19572,7 +20314,7 @@ ${t}`);
|
|
|
19572
20314
|
qa: this.state.qa.map((q) => [q.repoId, q.prNumber, q.status]),
|
|
19573
20315
|
requests: this.state.requests.filter((r) => r.status === "pending").map((r) => r.id)
|
|
19574
20316
|
};
|
|
19575
|
-
return
|
|
20317
|
+
return crypto11.createHash("sha1").update(JSON.stringify(data)).digest("hex");
|
|
19576
20318
|
}
|
|
19577
20319
|
maybeHeartbeat() {
|
|
19578
20320
|
const min = this.state.settings.ceoHeartbeatMin;
|
|
@@ -19946,15 +20688,15 @@ ${t}`);
|
|
|
19946
20688
|
async demoDoctor(action) {
|
|
19947
20689
|
const dd = this.backend.demoDoctor;
|
|
19948
20690
|
if (!dd) throw new HttpError(404, "The office doctor can only be tried out in the demo office.");
|
|
19949
|
-
let
|
|
19950
|
-
if (action === "restart")
|
|
20691
|
+
let text4 = "The watchdog looked.";
|
|
20692
|
+
if (action === "restart") text4 = await this.demoRestart(dd);
|
|
19951
20693
|
else if (action === "stuck") {
|
|
19952
20694
|
const a = this.state.agents.find((x) => x.role !== "ceo" && x.status === "working" && !this.stalled.has(x.id) && this.agentRt.get(x.id)?.session && dd.stall(x.id));
|
|
19953
20695
|
if (!a) throw new HttpError(409, "Nobody is working right now. Wait for someone to start an issue, then try again.");
|
|
19954
20696
|
this.stalled.add(a.id);
|
|
19955
20697
|
this.activity.set(a.id, Date.now() - QUIET_MS - 6e4);
|
|
19956
20698
|
this.watchdogTick();
|
|
19957
|
-
|
|
20699
|
+
text4 = `${a.name} went quiet 21 minutes ago (pretend), and the watchdog nudged them.`;
|
|
19958
20700
|
} else if (action === "later") {
|
|
19959
20701
|
const skip = NUDGE_WAIT_MS + 6e4;
|
|
19960
20702
|
for (const id of this.stalled) {
|
|
@@ -19963,17 +20705,17 @@ ${t}`);
|
|
|
19963
20705
|
}
|
|
19964
20706
|
for (const [key, at] of this.watch.nudged) if ([...this.stalled].some((id) => key.includes(`:${id}:`))) this.watch.nudged.set(key, at - skip);
|
|
19965
20707
|
this.watchdogTick();
|
|
19966
|
-
|
|
20708
|
+
text4 = "Eleven more minutes passed for the stuck sessions.";
|
|
19967
20709
|
} else if (action === "unclosed") {
|
|
19968
20710
|
const repo = this.state.repos[0];
|
|
19969
20711
|
const made = repo && dd.unclosedMerge(repo.fullName, 15 * 6e4);
|
|
19970
20712
|
if (!made) throw new HttpError(409, "The first floor has no open issue to leave open.");
|
|
19971
20713
|
await this.syncRepo(repo.id);
|
|
19972
20714
|
this.watchdogTick();
|
|
19973
|
-
|
|
20715
|
+
text4 = `PR #${made.pr} merged 15 minutes ago (pretend), but issue #${made.issue} is still open.`;
|
|
19974
20716
|
} else if (action === "check") this.watchdogTick();
|
|
19975
20717
|
else throw new HttpError(400, 'action must be "restart", "stuck", "later", "unclosed" or "check"');
|
|
19976
|
-
return { text:
|
|
20718
|
+
return { text: text4, doctor: this.doctorView() };
|
|
19977
20719
|
}
|
|
19978
20720
|
/**
|
|
19979
20721
|
* The demo's restart, in place: of the people working, one's CLI keeps going (followed again), the others' sessions
|
|
@@ -20085,8 +20827,8 @@ ${t}`);
|
|
|
20085
20827
|
throw new HttpError(400, 'action is "coins" or "tenure"');
|
|
20086
20828
|
}
|
|
20087
20829
|
// ---------- the phone ----------
|
|
20088
|
-
postMessage(from,
|
|
20089
|
-
const m = { id: this.messageSeq++, from, text:
|
|
20830
|
+
postMessage(from, text4, requestId) {
|
|
20831
|
+
const m = { id: this.messageSeq++, from, text: text4.trim().slice(0, 6e3), at: Date.now(), ...requestId ? { requestId } : {} };
|
|
20090
20832
|
const v = this.state.settings.voice;
|
|
20091
20833
|
if (v.provider !== "off" && speaks(m, v)) m.voice = v.provider;
|
|
20092
20834
|
this.state.messages.push(m);
|
|
@@ -20098,8 +20840,8 @@ ${t}`);
|
|
|
20098
20840
|
}
|
|
20099
20841
|
/** The team's holiday greeting (shared/themes.ts) from the CEO, once a day while a theme is on. */
|
|
20100
20842
|
greet() {
|
|
20101
|
-
const
|
|
20102
|
-
if (
|
|
20843
|
+
const text4 = dueGreeting(/* @__PURE__ */ new Date(), this.state.settings.themes, this.state.settings.managerName || this.user || "", this.state.messages);
|
|
20844
|
+
if (text4) this.postMessage("ceo", text4);
|
|
20103
20845
|
}
|
|
20104
20846
|
// ---------- notifications ----------
|
|
20105
20847
|
notifyNeedsHuman(rec) {
|
|
@@ -20253,7 +20995,7 @@ ${t}`);
|
|
|
20253
20995
|
newHire(repo, reason2, setup) {
|
|
20254
20996
|
const name = this.freeName();
|
|
20255
20997
|
const req = {
|
|
20256
|
-
id:
|
|
20998
|
+
id: crypto11.randomUUID(),
|
|
20257
20999
|
kind: "hire",
|
|
20258
21000
|
repoId: repo.id,
|
|
20259
21001
|
agentId: null,
|
|
@@ -20275,7 +21017,7 @@ ${t}`);
|
|
|
20275
21017
|
}
|
|
20276
21018
|
newLetGo(a, reason2) {
|
|
20277
21019
|
const req = {
|
|
20278
|
-
id:
|
|
21020
|
+
id: crypto11.randomUUID(),
|
|
20279
21021
|
kind: "let-go",
|
|
20280
21022
|
repoId: a.repoId,
|
|
20281
21023
|
agentId: a.id,
|
|
@@ -20304,6 +21046,7 @@ ${t}`);
|
|
|
20304
21046
|
*/
|
|
20305
21047
|
scaleTeam(x) {
|
|
20306
21048
|
const repo = this.floorRepo(x.floor);
|
|
21049
|
+
this.requirePlanReady(repo);
|
|
20307
21050
|
const reason2 = String(x.reason ?? "").trim().slice(0, 600);
|
|
20308
21051
|
if (!reason2) throw new Error("Say why: the manager reads the reason.");
|
|
20309
21052
|
const cli = isCli(x.cli) ? x.cli : "";
|
|
@@ -20335,8 +21078,8 @@ ${t}`);
|
|
|
20335
21078
|
const leaves = made.filter((r) => r.kind === "let-go");
|
|
20336
21079
|
const asks = [hires.length ? `add ${names(hires)}` : "", leaves.length ? `let ${names(leaves)} go` : ""].filter(Boolean).join(" and ");
|
|
20337
21080
|
if (made.length) {
|
|
20338
|
-
const
|
|
20339
|
-
this.postMessage("ceo", hires.length ? `${
|
|
21081
|
+
const text4 = `\u{1F4C8} Floor ${repo.floor}: from ${before} to ${plan.size} agents? I'd ${asks}. ${reason2}`;
|
|
21082
|
+
this.postMessage("ceo", hires.length ? `${text4} ${hires.length === 1 ? `${hires[0].name} waits` : "They wait"} in the lobby, where you can set them up before hiring.` : text4, made.length === 1 ? made[0].id : void 0);
|
|
20340
21083
|
this.notifier.notify("hire", `Floor ${repo.floor}: ${before} \u2192 ${plan.size} agents?`, `${this.ceo().name} would ${asks}. ${plainText(reason2)}`, `floor ${repo.floor} team change`);
|
|
20341
21084
|
}
|
|
20342
21085
|
return `Floor ${repo.floor} goes from ${before} to ${plan.size} agents${capped} once the manager agrees: ${asks || "withdrew the waiting changes"}.`;
|
|
@@ -20510,6 +21253,7 @@ ${t}`);
|
|
|
20510
21253
|
}
|
|
20511
21254
|
async fileIssue(x) {
|
|
20512
21255
|
const repo = this.floorRepo(x.floor);
|
|
21256
|
+
this.requirePlanReady(repo);
|
|
20513
21257
|
if (!this.ceoAsked) throw new Error(NOT_ASKED);
|
|
20514
21258
|
this.ceoIssues.check();
|
|
20515
21259
|
const title = String(x.title ?? "").trim().slice(0, 120);
|
|
@@ -20525,6 +21269,7 @@ _Filed by ${this.ceo().name}, the Droidsembly CEO._`;
|
|
|
20525
21269
|
/** Rewrite an open issue's "Depends on #N" line (see planDependencies for what is refused). */
|
|
20526
21270
|
async setDependencies(x) {
|
|
20527
21271
|
const repo = this.floorRepo(x.floor);
|
|
21272
|
+
this.requirePlanReady(repo);
|
|
20528
21273
|
const issues = this.repoRt.get(repo.id)?.issues ?? [];
|
|
20529
21274
|
const deps = (x.depends_on ?? []).map(Number);
|
|
20530
21275
|
const asked = [Number(x.number), ...deps].filter((n) => !issues.some((i) => i.number === n));
|
|
@@ -20700,6 +21445,7 @@ app.post(
|
|
|
20700
21445
|
app.patch("/api/agents/:id", route((req) => swarm.updateAgent(String(req.params.id), req.body ?? {})));
|
|
20701
21446
|
app.delete("/api/agents/:id", route((req) => swarm.fireAgent(String(req.params.id))));
|
|
20702
21447
|
app.post("/api/agents/:id/assign", route((req) => swarm.assign(String(req.params.id), num2(req.body.issueNumber), str(req.body.note) || void 0, req.body?.waitForDeps === true)));
|
|
21448
|
+
app.post("/api/agents/:id/resume-issue", route((req) => swarm.resumeIssue(String(req.params.id), str(req.body.repoId), num2(req.body.issueNumber))));
|
|
20703
21449
|
app.post("/api/agents/:id/stop", route((req) => swarm.stopAgent(String(req.params.id))));
|
|
20704
21450
|
app.post("/api/agents/:id/analyze", route((req) => swarm.analyze(String(req.params.id), str(req.body.text))));
|
|
20705
21451
|
app.post("/api/agents/:id/reset", route((req) => swarm.resetAgent(String(req.params.id))));
|
|
@@ -20727,12 +21473,12 @@ var sendAudio = (res, audio, cache = "private, max-age=3600") => {
|
|
|
20727
21473
|
res.setHeader("Cache-Control", cache);
|
|
20728
21474
|
res.end(audio);
|
|
20729
21475
|
};
|
|
20730
|
-
app.put("/api/voice/key", route((req) => swarm.voice.setKey(parse2(
|
|
20731
|
-
app.put("/api/cloud/key", route((req) => swarm.setCloudKey(parse2(
|
|
21476
|
+
app.put("/api/voice/key", route((req) => swarm.voice.setKey(parse2(z4.object({ key: z4.string().max(400) }), req.body).key)));
|
|
21477
|
+
app.put("/api/cloud/key", route((req) => swarm.setCloudKey(parse2(z4.object({ key: z4.string().max(400) }), req.body).key)));
|
|
20732
21478
|
app.put(
|
|
20733
21479
|
"/api/cloud/token",
|
|
20734
21480
|
route((req) => {
|
|
20735
|
-
const body2 = parse2(
|
|
21481
|
+
const body2 = parse2(z4.object({ kind: z4.enum(["github", "anthropic", "openai"]), value: z4.string().max(400) }), req.body);
|
|
20736
21482
|
return swarm.setCloudToken(body2.kind, body2.value);
|
|
20737
21483
|
})
|
|
20738
21484
|
);
|
|
@@ -20743,8 +21489,8 @@ app.get("/api/voice/voices", route(() => swarm.voice.voices()));
|
|
|
20743
21489
|
app.get(
|
|
20744
21490
|
"/api/voice/messages/:id",
|
|
20745
21491
|
route(async (req, res) => {
|
|
20746
|
-
const { id } = parse2(
|
|
20747
|
-
const q = parse2(
|
|
21492
|
+
const { id } = parse2(z4.object({ id: z4.coerce.number().int().positive() }), req.params);
|
|
21493
|
+
const q = parse2(z4.object({ cached: z4.literal("1").optional(), part: z4.coerce.number().int().min(0).max(99).default(0) }), req.query);
|
|
20748
21494
|
if (!q.cached) return sendAudio(res, await swarm.voice.messageAudio(id));
|
|
20749
21495
|
const { audio, parts } = await swarm.voice.cachedAudio(id, q.part);
|
|
20750
21496
|
res.setHeader("X-Voice-Parts", String(parts));
|
|
@@ -20763,12 +21509,12 @@ app.post(
|
|
|
20763
21509
|
);
|
|
20764
21510
|
app.get(
|
|
20765
21511
|
"/api/voice/sample",
|
|
20766
|
-
route(async (req, res) => sendAudio(res, await swarm.voice.sampleAudio(parse2(
|
|
21512
|
+
route(async (req, res) => sendAudio(res, await swarm.voice.sampleAudio(parse2(z4.object({ voiceId: z4.string().regex(/^[A-Za-z0-9_-]{1,64}$/, "not a voice id").optional() }), req.query).voiceId)))
|
|
20767
21513
|
);
|
|
20768
21514
|
app.get(
|
|
20769
21515
|
"/api/voice/standup",
|
|
20770
21516
|
route(async (req, res) => {
|
|
20771
|
-
const q = parse2(
|
|
21517
|
+
const q = parse2(z4.object({ n: z4.coerce.number().int().min(1).max(99), part: z4.enum(DAY_PARTS) }), req.query);
|
|
20772
21518
|
sendAudio(res, await swarm.voice.standupAudio(q.n, q.part));
|
|
20773
21519
|
})
|
|
20774
21520
|
);
|
|
@@ -20794,6 +21540,14 @@ app.get(
|
|
|
20794
21540
|
);
|
|
20795
21541
|
app.post("/api/journal/sample", route(() => swarm.journalSample()));
|
|
20796
21542
|
app.post("/api/ceo/message", route((req) => swarm.messageCeo(str(req.body.text))));
|
|
21543
|
+
var draftRef = (req) => {
|
|
21544
|
+
if (typeof req.body.draftId !== "string" || !Number.isSafeInteger(req.body.revision) || req.body.revision < 1)
|
|
21545
|
+
throw new HttpError(400, "Project draft ID and exact revision required.");
|
|
21546
|
+
return { draftId: req.body.draftId, revision: req.body.revision };
|
|
21547
|
+
};
|
|
21548
|
+
app.post("/api/repos/:repo/app-starter/answer", route((req) => swarm.answerAppInterview(repoId(req), draftRef(req), str(req.body.messageId), str(req.body.text))));
|
|
21549
|
+
app.post("/api/repos/:repo/app-starter/approve", route((req) => swarm.approveAppPlan(repoId(req), draftRef(req), str(req.body.hash), req.body.confirmEnvironments === true, req.body.confirmLocal === true)));
|
|
21550
|
+
app.post("/api/repos/:repo/app-starter/action", route((req) => swarm.appPlanAction(repoId(req), draftRef(req), str(req.body.action))));
|
|
20797
21551
|
app.post("/api/ceo/review", route(() => swarm.requestReview()));
|
|
20798
21552
|
app.post("/api/phone/read", route((req) => swarm.markPhoneRead(Number(req.body?.at) || Date.now())));
|
|
20799
21553
|
app.post(
|
|
@@ -20815,16 +21569,16 @@ app.post("/api/repos/:repo/decor/buy", route((req) => swarm.buyDecoration(repoId
|
|
|
20815
21569
|
app.post("/api/repos/:repo/decor/place", route((req) => swarm.placeDecoration(repoId(req), req.body ?? {})));
|
|
20816
21570
|
app.post("/api/progress/coffee", route((req) => swarm.drankCoffee(req.body?.id)));
|
|
20817
21571
|
app.post("/api/progress/demo", route((req) => swarm.demoProgress(req.body ?? {})));
|
|
20818
|
-
var dist =
|
|
20819
|
-
if (
|
|
21572
|
+
var dist = path24.resolve(import.meta.dirname, "../dist");
|
|
21573
|
+
if (fs24.existsSync(dist)) {
|
|
20820
21574
|
app.get("/sw.js", (_req, res) => {
|
|
20821
|
-
const html =
|
|
21575
|
+
const html = fs24.readFileSync(path24.join(dist, "index.html"), "utf8");
|
|
20822
21576
|
res.setHeader("Content-Type", "text/javascript; charset=utf-8");
|
|
20823
21577
|
res.setHeader("Cache-Control", "no-cache");
|
|
20824
21578
|
res.end(serviceWorkerSource(swVersion(html, VERSION, swarm.officeCommit())));
|
|
20825
21579
|
});
|
|
20826
21580
|
app.use(express.static(dist));
|
|
20827
|
-
app.get(/^(?!\/api).*/, (_req, res) => res.sendFile(
|
|
21581
|
+
app.get(/^(?!\/api).*/, (_req, res) => res.sendFile(path24.join(dist, "index.html")));
|
|
20828
21582
|
}
|
|
20829
21583
|
app.use((err, _req, res, _next) => {
|
|
20830
21584
|
const parserStatus = err?.status;
|