droidsembly 0.4.0-beta.4 → 0.4.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.it.md +6 -4
  2. package/README.md +6 -4
  3. package/bin/cubefarm.js +2 -296
  4. package/bin/droidsembly.js +304 -0
  5. package/bin/environment.d.ts +3 -0
  6. package/bin/environment.js +48 -0
  7. package/dist/assets/AccessibilitySettings-vd4x_sEq.js +30 -0
  8. package/dist/assets/{AppViewer-CqGa1r0z.js → AppViewer-BB9lvg-4.js} +1 -1
  9. package/dist/assets/{Balloon-dO9J4khp.js → Balloon-CWEK5uK2.js} +1 -1
  10. package/dist/assets/{Batched-CmXZtCvQ.js → Batched-yAiB-c-b.js} +1 -1
  11. package/dist/assets/{Birds-D51xGT0l.js → Birds-ClBZkA83.js} +1 -1
  12. package/dist/assets/{Blimp-C2c_AKRR.js → Blimp-VHMnVBQt.js} +1 -1
  13. package/dist/assets/{BufferGeometryUtils-Dcu0heeS.js → BufferGeometryUtils-B4Tnxtjb.js} +1 -1
  14. package/dist/assets/{Duck-CzFiUF6U.js → Duck-CCThHMtF.js} +1 -1
  15. package/dist/assets/{Effects-DwOi-gSQ.js → Effects-BZfFy3yq.js} +1 -1
  16. package/dist/assets/{Fireworks-Cc2mGzPJ.js → Fireworks-CxvvEwV_.js} +1 -1
  17. package/dist/assets/{Helicopter-ltB-x8hG.js → Helicopter-DXHDrTnQ.js} +1 -1
  18. package/dist/assets/{Hurricane-C2qHsRw4.js → Hurricane-WXNUxoUz.js} +1 -1
  19. package/dist/assets/{Kaiju-DPHVjFjg.js → Kaiju-D-wVgKo-.js} +1 -1
  20. package/dist/assets/{Meteors-CxcguXTJ.js → Meteors-DSr-7bEl.js} +1 -1
  21. package/dist/assets/{MissionConsole-BUE2mijT.js → MissionConsole-4G02S89d.js} +1 -1
  22. package/dist/assets/{Office-NV5zlSnK.js → Office-B_EroD2U.js} +44 -44
  23. package/dist/assets/{PhotoPanel-CDqgU99Z.js → PhotoPanel-ByzwApow.js} +1 -1
  24. package/dist/assets/{PhotoScene-RRXC4_Jv.js → PhotoScene-CW3yZkqH.js} +3 -3
  25. package/dist/assets/{Plane-BQB72TWZ.js → Plane-CT7-QFbA.js} +1 -1
  26. package/dist/assets/Pocket-B0o4siMl.js +2 -0
  27. package/dist/assets/{Rainbow-DIpZi5-z.js → Rainbow-DNvXfTl9.js} +1 -1
  28. package/dist/assets/{Roof-Cd9I0jtG.js → Roof-yLX0ZK0x.js} +1 -1
  29. package/dist/assets/{Shell-DCqHgrm_.js → Shell-lZOZ3aG8.js} +2 -2
  30. package/dist/assets/{Skywriting-BH6FCdEl.js → Skywriting-N1GDZKYR.js} +1 -1
  31. package/dist/assets/{TerminalView-CoH1yh6r.js → TerminalView-cUAMhOxM.js} +11 -11
  32. package/dist/assets/{ToyWorld--k4uqi9k.js → ToyWorld-BYE8776A.js} +1 -1
  33. package/dist/assets/{Ufo-C5cYunS9.js → Ufo-D_Wt75n1.js} +1 -1
  34. package/dist/assets/{Whale-BAXeezd8.js → Whale-Kkz3B36R.js} +1 -1
  35. package/dist/assets/all-BMItClgN.js +11 -0
  36. package/dist/assets/{bloomMarks-JYeAmd4d.js → bloomMarks-C22qSi5d.js} +1 -1
  37. package/dist/assets/{cheerRules-DvM2z9Qg.js → cheerRules-G9WFRB4C.js} +1 -1
  38. package/dist/assets/{cityLayout-VU-ug-r6.js → cityLayout-C8f5-bpM.js} +1 -1
  39. package/dist/assets/{dogState-Bm3YZHwy.js → dogState-9uong8D8.js} +1 -1
  40. package/dist/assets/{doors-D7Z3s-7W.js → doors-DsKuGpOi.js} +1 -1
  41. package/dist/assets/{gallery-CSWmy4Tf.js → gallery-DSKvNkBq.js} +1 -1
  42. package/dist/assets/gate-D6_NXB1w.js +2 -0
  43. package/dist/assets/index-rznd4Djx.js +10 -0
  44. package/dist/assets/{instantReplay-FXf2kJ7B.js → instantReplay-CiWMru53.js} +1 -1
  45. package/dist/assets/{interact-BatJVhca.js → interact-Bt-XX-z4.js} +1 -1
  46. package/dist/assets/{jsx-runtime-CXW0f58S.js → jsx-runtime-CZP6s5wa.js} +1 -1
  47. package/dist/assets/{kit-D3twk12W.js → kit-CZEafHnz.js} +1 -1
  48. package/dist/assets/mic-DeYDrNoY.js +1 -0
  49. package/dist/assets/{photoMode-B8pRCF0O.js → photoMode-BTxq9-gL.js} +1 -1
  50. package/dist/assets/{pipeline-BgOS9JnJ.js → pipeline-DNe3sjnP.js} +1 -1
  51. package/dist/assets/{rapier-BvQbKz0M.js → rapier-C-KFR0AR.js} +1 -1
  52. package/dist/assets/{rig-BgSxc8mA.js → rig-B88WinIa.js} +1 -1
  53. package/dist/assets/{speechLanguage-Cak8tdL0.js → speechLanguage-Bq3BAswq.js} +1 -1
  54. package/dist/assets/store-9CvxLGNQ.js +5 -0
  55. package/dist/assets/useDayTime-Nrdy7kH1.js +1 -0
  56. package/dist/assets/useGraphics-Bhnj8CAm.js +1 -0
  57. package/dist/assets/voiceMessages-BF3P4sjw.js +1 -0
  58. package/dist/assets/{weatherState-BQ3UU4vU.js → weatherState-CufaxiyU.js} +1 -1
  59. package/dist/index.html +3 -3
  60. package/dist-server/index.js +597 -413
  61. package/dist-server/index.js.map +4 -4
  62. package/dist-server/ptyHost.js +6 -2
  63. package/dist-server/ptyHost.js.map +2 -2
  64. package/package.json +2 -2
  65. package/dist/assets/AccessibilitySettings-6ZCswq5I.js +0 -30
  66. package/dist/assets/Pocket-CjK6fv97.js +0 -2
  67. package/dist/assets/all-BsJ98bWd.js +0 -11
  68. package/dist/assets/gate-DwsbbSNS.js +0 -2
  69. package/dist/assets/index-D_Et7Vx8.js +0 -10
  70. package/dist/assets/mic-BJ0eYLIj.js +0 -1
  71. package/dist/assets/store-Buxt6UcJ.js +0 -5
  72. package/dist/assets/useDayTime-0ms3va3h.js +0 -1
  73. package/dist/assets/useGraphics-p7LAuvYj.js +0 -1
  74. package/dist/assets/voiceMessages-hO1SDnOS.js +0 -1
@@ -1,7 +1,7 @@
1
1
  // server/index.ts
2
2
  import http3 from "node:http";
3
- import path22 from "node:path";
4
- import fs22 from "node:fs";
3
+ import path23 from "node:path";
4
+ import fs23 from "node:fs";
5
5
  import express from "express";
6
6
  import { WebSocketServer } from "ws";
7
7
  import { z as z3 } from "zod";
@@ -78,9 +78,9 @@ function standupLine(count, part) {
78
78
  }
79
79
 
80
80
  // server/config.ts
81
- import fs from "node:fs";
82
- import os from "node:os";
83
- import path from "node:path";
81
+ import fs2 from "node:fs";
82
+ import os2 from "node:os";
83
+ import path2 from "node:path";
84
84
 
85
85
  // shared/types.ts
86
86
  var FLOOR_SEATS = 15;
@@ -89,18 +89,52 @@ var CEO_ID = "ceo";
89
89
  var DEFAULT_DOG_NAME = "Biscuit";
90
90
  var INSTALL_STEP = "Installing dependencies";
91
91
 
92
+ // bin/environment.js
93
+ import fs from "node:fs";
94
+ import os from "node:os";
95
+ import path from "node:path";
96
+ function officeEnv(env, legacyName) {
97
+ const canonical = legacyName.replace(/^(SWARM|CUBEFARM)_/, "DROIDSEMBLY_");
98
+ return env[canonical] ?? env[legacyName];
99
+ }
100
+ function directoryExists(file) {
101
+ try {
102
+ fs.lstatSync(file);
103
+ } catch (error) {
104
+ if (error.code === "ENOENT") return false;
105
+ throw error;
106
+ }
107
+ if (!fs.statSync(file).isDirectory()) throw new Error("Office home path is not a directory. Set DROIDSEMBLY_HOME explicitly.");
108
+ return true;
109
+ }
110
+ function officeHome(env = process.env, home = os.homedir(), exists2 = directoryExists) {
111
+ const explicit = officeEnv(env, "SWARM_HOME");
112
+ if (explicit !== void 0) {
113
+ if (!explicit.trim()) throw new Error("DROIDSEMBLY_HOME / SWARM_HOME must not be empty. Select an office folder explicitly.");
114
+ const selected = path.resolve(explicit);
115
+ exists2(selected);
116
+ return selected;
117
+ }
118
+ const current = path.resolve(home, ".droidsembly");
119
+ const legacy = path.resolve(home, ".cubefarm");
120
+ const hasCurrent = exists2(current);
121
+ const hasLegacy = exists2(legacy);
122
+ if (hasCurrent && hasLegacy) throw new Error("Both .droidsembly and .cubefarm exist. Set DROIDSEMBLY_HOME (or SWARM_HOME) explicitly; no data was merged or moved.");
123
+ return hasLegacy ? legacy : current;
124
+ }
125
+
92
126
  // server/config.ts
93
- var PORT = Number(process.env.SWARM_PORT ?? 4317);
94
- var HOST = process.env.SWARM_HOST?.trim().replace(/^\[|\]$/g, "") || "127.0.0.1";
95
- var VERSION = JSON.parse(fs.readFileSync(path.resolve(import.meta.dirname, "..", "package.json"), "utf8")).version;
96
- var HOME_DIR = process.env.SWARM_HOME ?? path.join(os.homedir(), ".cubefarm");
97
- var WORKSPACE_ROOT = path.join(HOME_DIR, "workspaces");
98
- var DEMO = process.argv.includes("--demo") || process.env.SWARM_DEMO === "1" || process.env.SWARM_DEMO === "true";
127
+ var PORT = Number(officeEnv(process.env, "SWARM_PORT") ?? 4317);
128
+ var HOST = officeEnv(process.env, "SWARM_HOST")?.trim().replace(/^\[|\]$/g, "") || "127.0.0.1";
129
+ var VERSION = JSON.parse(fs2.readFileSync(path2.resolve(import.meta.dirname, "..", "package.json"), "utf8")).version;
130
+ var HOME_DIR = officeHome();
131
+ var WORKSPACE_ROOT = path2.join(HOME_DIR, "workspaces");
132
+ var DEMO = process.argv.includes("--demo") || ["1", "true"].includes(officeEnv(process.env, "SWARM_DEMO") ?? "");
99
133
  var DEMO_MAX = { floors: 20, agents: FLOOR_SEATS };
100
134
  function demoScale(argv, env) {
101
135
  const read = (flag, name) => {
102
136
  const i = argv.findIndex((a) => a === flag || a.startsWith(`${flag}=`));
103
- const raw = i < 0 ? env[name] : argv[i].includes("=") ? argv[i].slice(flag.length + 1) : argv[i + 1];
137
+ const raw = i < 0 ? officeEnv(env, name) : argv[i].includes("=") ? argv[i].slice(flag.length + 1) : argv[i + 1];
104
138
  const n = Number(raw);
105
139
  return raw === void 0 || raw === "" || !Number.isFinite(n) ? null : Math.round(n);
106
140
  };
@@ -111,7 +145,7 @@ function demoScale(argv, env) {
111
145
  return { floors: clamp3(floors ?? 2, DEMO_MAX.floors), agents: clamp3(agents ?? 6, DEMO_MAX.agents) };
112
146
  }
113
147
  var DEMO_SCALE = DEMO ? demoScale(process.argv, process.env) : null;
114
- var STATE_FILE = path.join(HOME_DIR, DEMO ? DEMO_SCALE ? `demo-${DEMO_SCALE.floors}x${DEMO_SCALE.agents}-state.json` : "demo-state.json" : "state.json");
148
+ var STATE_FILE = path2.join(HOME_DIR, DEMO ? DEMO_SCALE ? `demo-${DEMO_SCALE.floors}x${DEMO_SCALE.agents}-state.json` : "demo-state.json" : "state.json");
115
149
  function envPort(value, fallback) {
116
150
  const n = Number(value);
117
151
  return value && Number.isInteger(n) && n >= 1024 && n <= 65e3 ? n : fallback;
@@ -125,7 +159,7 @@ function localAddress(host) {
125
159
  if (h === "0.0.0.0" || h === "::" || h === "") return "127.0.0.1";
126
160
  return h.includes(":") ? `[${h}]` : h;
127
161
  }
128
- function networkUrls(host, port, ifaces = os.networkInterfaces()) {
162
+ function networkUrls(host, port, ifaces = os2.networkInterfaces()) {
129
163
  if (localAddress(host) !== "127.0.0.1" || isLoopback(host)) return [];
130
164
  return Object.values(ifaces).flat().filter((i) => i && i.family === "IPv4" && !i.internal).map((i) => `http://${i.address}:${port}`);
131
165
  }
@@ -133,21 +167,21 @@ function envMinutes(value, fallback) {
133
167
  const n = Number(value);
134
168
  return value && Number.isFinite(n) && n > 0 ? n : fallback;
135
169
  }
136
- var PREVIEW_PORT = envPort(process.env.SWARM_PREVIEW_PORT, 6300);
137
- var PR_PREVIEW_IDLE_MS = envMinutes(process.env.SWARM_PR_PREVIEW_IDLE_MIN, 20) * 6e4;
170
+ var PREVIEW_PORT = envPort(officeEnv(process.env, "SWARM_PREVIEW_PORT"), 6300);
171
+ var PR_PREVIEW_IDLE_MS = envMinutes(officeEnv(process.env, "SWARM_PR_PREVIEW_IDLE_MIN"), 20) * 6e4;
138
172
  var SYNC_INTERVAL_MS = 45e3;
139
173
  var SCHEDULER_INTERVAL_MS = 8e3;
140
174
  var DESK_SWEEP_INTERVAL_MS = 30 * 6e4;
141
175
  var LOG_BUFFER = 600;
142
- function defaultProjectsDir(appDir, home = os.homedir()) {
143
- if (!appDir.split(/[\\/]/).includes("node_modules")) return path.resolve(appDir, "..");
176
+ function defaultProjectsDir(appDir, home = os2.homedir()) {
177
+ if (!appDir.split(/[\\/]/).includes("node_modules")) return path2.resolve(appDir, "..");
144
178
  const names = ["Projects", "projects", "code", "Code", "dev", "Developer", "src", "repos", "git", "GitHub"];
145
- return names.map((n) => path.join(home, n)).find((d) => fs.existsSync(d)) ?? path.join(home, "Projects");
179
+ return names.map((n) => path2.join(home, n)).find((d) => fs2.existsSync(d)) ?? path2.join(home, "Projects");
146
180
  }
147
181
 
148
182
  // server/workspace.ts
149
- import fs2 from "node:fs/promises";
150
- import path2 from "node:path";
183
+ import fs3 from "node:fs/promises";
184
+ import path3 from "node:path";
151
185
 
152
186
  // server/exec.ts
153
187
  import { execFile } from "node:child_process";
@@ -212,24 +246,24 @@ function withRepoLock(fullName, fn) {
212
246
  locks.set(fullName, next);
213
247
  return next;
214
248
  }
215
- var repoDir = (fullName) => path2.join(WORKSPACE_ROOT, fullName.replace("/", "__"));
216
- var mainDir = (fullName) => localRoots.get(fullName.toLowerCase()) ?? path2.join(repoDir(fullName), "main");
217
- var deskDir = (fullName, agentSlug) => path2.join(repoDir(fullName), "desks", agentSlug);
249
+ var repoDir = (fullName) => path3.join(WORKSPACE_ROOT, fullName.replace("/", "__"));
250
+ var mainDir = (fullName) => localRoots.get(fullName.toLowerCase()) ?? path3.join(repoDir(fullName), "main");
251
+ var deskDir = (fullName, agentSlug) => path3.join(repoDir(fullName), "desks", agentSlug);
218
252
  function setLocalPath(fullName, dir) {
219
- if (dir) localRoots.set(fullName.toLowerCase(), path2.resolve(dir));
253
+ if (dir) localRoots.set(fullName.toLowerCase(), path3.resolve(dir));
220
254
  else localRoots.delete(fullName.toLowerCase());
221
255
  }
222
256
  async function exists(p) {
223
- return fs2.access(p).then(() => true).catch(() => false);
257
+ return fs3.access(p).then(() => true).catch(() => false);
224
258
  }
225
259
  var LOCAL_EXCLUDES = [".playwright-mcp/", ".preview-tmp/"];
226
260
  async function addLocalExcludes(main) {
227
- const file = path2.join(main, ".git", "info", "exclude");
228
- const current = await fs2.readFile(file, "utf8").catch(() => "");
261
+ const file = path3.join(main, ".git", "info", "exclude");
262
+ const current = await fs3.readFile(file, "utf8").catch(() => "");
229
263
  const missing = LOCAL_EXCLUDES.filter((l) => !current.split(/\r?\n/).includes(l));
230
264
  if (missing.length === 0) return;
231
- await fs2.mkdir(path2.dirname(file), { recursive: true });
232
- await fs2.appendFile(file, `${current && !current.endsWith("\n") ? "\n" : ""}# added by cubefarm
265
+ await fs3.mkdir(path3.dirname(file), { recursive: true });
266
+ await fs3.appendFile(file, `${current && !current.endsWith("\n") ? "\n" : ""}# added by cubefarm
233
267
  ${missing.join("\n")}
234
268
  `);
235
269
  }
@@ -237,10 +271,10 @@ var ensureLocalExcludes = (fullName) => addLocalExcludes(mainDir(fullName));
237
271
  function ensureClone(fullName) {
238
272
  return withRepoLock(fullName, async () => {
239
273
  const dir = mainDir(fullName);
240
- if (await exists(path2.join(dir, ".git"))) {
274
+ if (await exists(path3.join(dir, ".git"))) {
241
275
  await git(["fetch", "origin", "--prune"], { cwd: dir, timeoutMs: 18e4 });
242
276
  } else {
243
- await fs2.mkdir(path2.dirname(dir), { recursive: true });
277
+ await fs3.mkdir(path3.dirname(dir), { recursive: true });
244
278
  await gh(["repo", "clone", fullName, dir], { timeoutMs: 6e5 });
245
279
  }
246
280
  await addLocalExcludes(dir);
@@ -284,7 +318,7 @@ function fileList(files, max = 3, maxChars = 120) {
284
318
  async function syncMain(fullName, defaultBranch, opts) {
285
319
  const dir = mainDir(fullName);
286
320
  const result = await withRepoLock(fullName, async () => {
287
- if (!await exists(path2.join(dir, ".git"))) return null;
321
+ if (!await exists(path3.join(dir, ".git"))) return null;
288
322
  const g = (args, timeoutMs) => git(args, { cwd: dir, timeoutMs });
289
323
  let behind = 0;
290
324
  try {
@@ -311,7 +345,7 @@ async function syncMain(fullName, defaultBranch, opts) {
311
345
  return { status: `${behind} behind: local files are in the way${files.length ? `: ${fileList(files)}` : ""}`, behind, updatable: true };
312
346
  }
313
347
  const changed = (await g(["diff", "--name-only", before, "HEAD"])).split(/\r?\n/);
314
- const install = changed.some((f) => f === "package.json" || f === "package-lock.json") && await exists(path2.join(dir, "package.json"));
348
+ const install = changed.some((f) => f === "package.json" || f === "package-lock.json") && await exists(path3.join(dir, "package.json"));
315
349
  return { status: `updated to ${await g(["rev-parse", "--short", "HEAD"])}`, behind: 0, updatable: false, install };
316
350
  } catch (err) {
317
351
  return { status: `sync failed: ${err.message.split(/\r?\n/)[0].slice(0, 160)}`, behind, updatable: false };
@@ -333,33 +367,33 @@ function githubFromConfig(config) {
333
367
  return m ? `${m[1]}/${m[2]}` : null;
334
368
  }
335
369
  async function inspectFolder(dir) {
336
- const full = path2.resolve(dir);
337
- const stat = await fs2.stat(full).catch(() => null);
370
+ const full = path3.resolve(dir);
371
+ const stat = await fs3.stat(full).catch(() => null);
338
372
  if (!stat?.isDirectory()) throw new Error(`${full} is not a folder`);
339
- const dotGit = path2.join(full, ".git");
340
- const gitStat = await fs2.stat(dotGit).catch(() => null);
373
+ const dotGit = path3.join(full, ".git");
374
+ const gitStat = await fs3.stat(dotGit).catch(() => null);
341
375
  let config = "";
342
- if (gitStat?.isDirectory()) config = await fs2.readFile(path2.join(dotGit, "config"), "utf8").catch(() => "");
376
+ if (gitStat?.isDirectory()) config = await fs3.readFile(path3.join(dotGit, "config"), "utf8").catch(() => "");
343
377
  else if (gitStat) {
344
- const ref = (await fs2.readFile(dotGit, "utf8").catch(() => "")).match(/gitdir:\s*(.+)/)?.[1]?.trim();
378
+ const ref = (await fs3.readFile(dotGit, "utf8").catch(() => "")).match(/gitdir:\s*(.+)/)?.[1]?.trim();
345
379
  if (ref) {
346
- const gitDir = path2.resolve(full, ref);
347
- config = await fs2.readFile(path2.join(gitDir, "config"), "utf8").catch(() => fs2.readFile(path2.join(gitDir, "..", "..", "config"), "utf8").catch(() => ""));
380
+ const gitDir = path3.resolve(full, ref);
381
+ config = await fs3.readFile(path3.join(gitDir, "config"), "utf8").catch(() => fs3.readFile(path3.join(gitDir, "..", "..", "config"), "utf8").catch(() => ""));
348
382
  }
349
383
  }
350
- return { name: path2.basename(full), path: full, git: !!gitStat, github: githubFromConfig(config), modified: stat.mtimeMs };
384
+ return { name: path3.basename(full), path: full, git: !!gitStat, github: githubFromConfig(config), modified: stat.mtimeMs };
351
385
  }
352
386
  async function scanProjects(root) {
353
- const entries = await fs2.readdir(root, { withFileTypes: true }).catch(() => {
387
+ const entries = await fs3.readdir(root, { withFileTypes: true }).catch(() => {
354
388
  throw new Error(`Can't read the projects folder ${root}`);
355
389
  });
356
390
  const dirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith(".") && e.name !== "node_modules");
357
- const folders = await Promise.all(dirs.map((e) => inspectFolder(path2.join(root, e.name)).catch(() => null)));
391
+ const folders = await Promise.all(dirs.map((e) => inspectFolder(path3.join(root, e.name)).catch(() => null)));
358
392
  return folders.filter((f) => !!f).sort((a, b) => b.modified - a.modified);
359
393
  }
360
394
  async function commitReadme(dir, title, description) {
361
- const readme = path2.join(dir, "README.md");
362
- if (!await exists(readme)) await fs2.writeFile(readme, `# ${title}
395
+ const readme = path3.join(dir, "README.md");
396
+ if (!await exists(readme)) await fs3.writeFile(readme, `# ${title}
363
397
 
364
398
  ${description.trim()}
365
399
  `);
@@ -373,7 +407,7 @@ ${description.trim()}
373
407
  }
374
408
  }
375
409
  async function publishFolder(dir, opts) {
376
- const full = path2.resolve(dir);
410
+ const full = path3.resolve(dir);
377
411
  const info = await inspectFolder(full);
378
412
  if (info.github) return info.github;
379
413
  if (!info.git) await git(["init", "-b", "main"], { cwd: full });
@@ -382,7 +416,7 @@ async function publishFolder(dir, opts) {
382
416
  () => false
383
417
  );
384
418
  if (!hasCommit) {
385
- const files = (await fs2.readdir(full)).filter((f) => f !== ".git" && f !== "README.md");
419
+ const files = (await fs3.readdir(full)).filter((f) => f !== ".git" && f !== "README.md");
386
420
  if (files.length) {
387
421
  throw new Error(`${info.name} has files but no commits yet. Commit what you want on GitHub first (git add, git commit), then publish it.`);
388
422
  }
@@ -397,26 +431,26 @@ async function publishFolder(dir, opts) {
397
431
  return out.match(/github\.com\/([^/\s]+\/[^/\s]+?)(?:\.git)?(?:\s|$)/)?.[1] ?? (await inspectFolder(full)).github ?? target;
398
432
  }
399
433
  async function createProject(root, name, opts) {
400
- const dir = path2.join(root, name);
434
+ const dir = path3.join(root, name);
401
435
  if (await exists(dir)) {
402
- const inside = await fs2.readdir(dir).catch(() => ["?"]);
436
+ const inside = await fs3.readdir(dir).catch(() => ["?"]);
403
437
  if (inside.length) throw new Error(`${dir} already exists. Pick another name, or connect that folder instead.`);
404
438
  }
405
- await fs2.mkdir(dir, { recursive: true });
439
+ await fs3.mkdir(dir, { recursive: true });
406
440
  await git(["init", "-b", "main"], { cwd: dir });
407
441
  await commitReadme(dir, name, opts.description ?? "");
408
442
  const fullName = await publishFolder(dir, { name, ...opts });
409
443
  return { fullName, path: dir };
410
444
  }
411
445
  async function removeDir(dir) {
412
- await fs2.rm(dir, { recursive: true, force: true, maxRetries: 8, retryDelay: 250 });
446
+ await fs3.rm(dir, { recursive: true, force: true, maxRetries: 8, retryDelay: 250 });
413
447
  }
414
448
  var STALE_LOCK_MS = 10 * 6e4;
415
449
  async function staleIndexLock(wt) {
416
- const ref = (await fs2.readFile(path2.join(wt, ".git"), "utf8").catch(() => "")).match(/gitdir:\s*(.+)/)?.[1]?.trim();
450
+ const ref = (await fs3.readFile(path3.join(wt, ".git"), "utf8").catch(() => "")).match(/gitdir:\s*(.+)/)?.[1]?.trim();
417
451
  if (!ref) return null;
418
- const lock = path2.join(path2.resolve(wt, ref), "index.lock");
419
- const stat = await fs2.stat(lock).catch(() => null);
452
+ const lock = path3.join(path3.resolve(wt, ref), "index.lock");
453
+ const stat = await fs3.stat(lock).catch(() => null);
420
454
  return stat && Date.now() - stat.mtimeMs > STALE_LOCK_MS ? lock : null;
421
455
  }
422
456
  async function reuseDesk(wt, branch, ref) {
@@ -428,7 +462,7 @@ async function clearDeskFolder(wt) {
428
462
  try {
429
463
  await removeDir(wt);
430
464
  } catch (err) {
431
- const left = await fs2.readdir(wt).catch(() => null);
465
+ const left = await fs3.readdir(wt).catch(() => null);
432
466
  if (left?.length !== 0) {
433
467
  throw new Error(
434
468
  `Could not clear the desk folder ${wt}: ${err.message}. A program started by the previous task is probably still running there. Close it and try again.`
@@ -454,19 +488,19 @@ async function setUpWorktree(main, wt, fullName, base, branch, note2) {
454
488
  );
455
489
  }
456
490
  await git(["worktree", "prune"], { cwd: main });
457
- const real = (p) => fs2.realpath(p).catch(() => p);
491
+ const real = (p) => fs3.realpath(p).catch(() => p);
458
492
  const worktrees = await Promise.all(parseWorktrees(await git(["worktree", "list", "--porcelain"], { cwd: main })).map(async (w) => ({ ...w, path: await real(w.path) })));
459
493
  const holder = branchHolder(worktrees, branch, await real(wt));
460
494
  const local = holder ? null : branch;
461
495
  if (holder) note2?.(`${branch} is checked out at ${holder}, so this desk works on it as a detached HEAD at ${ref}; push with git push origin HEAD:${branch}.`);
462
- if (await exists(path2.join(wt, ".git"))) {
496
+ if (await exists(path3.join(wt, ".git"))) {
463
497
  try {
464
498
  try {
465
499
  await reuseDesk(wt, local, ref);
466
500
  } catch (err) {
467
501
  const lock = /index\.lock/.test(err.message) ? await staleIndexLock(wt) : null;
468
502
  if (!lock) throw err;
469
- await fs2.rm(lock, { force: true, maxRetries: 3 });
503
+ await fs3.rm(lock, { force: true, maxRetries: 3 });
470
504
  note2?.(`Removed a stale git lock (${lock}) left in the desk.`);
471
505
  await reuseDesk(wt, local, ref);
472
506
  }
@@ -482,12 +516,12 @@ async function setUpWorktree(main, wt, fullName, base, branch, note2) {
482
516
  await clearDeskFolder(wt);
483
517
  }
484
518
  await git(["worktree", "prune"], { cwd: main });
485
- await fs2.mkdir(path2.dirname(wt), { recursive: true });
519
+ await fs3.mkdir(path3.dirname(wt), { recursive: true });
486
520
  await git(["worktree", "add", ...local ? ["-B", local] : ["--detach"], wt, ref], { cwd: main });
487
521
  return wt;
488
522
  }
489
523
  function branchHolder(worktrees, branch, desk) {
490
- return worktrees.find((w) => w.branch === branch && !samePath(w.path, path2.resolve(desk)))?.path ?? null;
524
+ return worktrees.find((w) => w.branch === branch && !samePath(w.path, path3.resolve(desk)))?.path ?? null;
491
525
  }
492
526
  function removeDesk(fullName, agentSlug, main = mainDir(fullName)) {
493
527
  return withRepoLock(fullName, async () => {
@@ -503,7 +537,7 @@ var OFFICE_BRANCH = /^(swarm\/issue-|qa\/pr-)/;
503
537
  function parseWorktrees(porcelain) {
504
538
  const out = [];
505
539
  for (const line of porcelain.split(/\r?\n/)) {
506
- if (line.startsWith("worktree ")) out.push({ path: path2.resolve(line.slice(9)), branch: null, locked: false });
540
+ if (line.startsWith("worktree ")) out.push({ path: path3.resolve(line.slice(9)), branch: null, locked: false });
507
541
  else if (!out.length) continue;
508
542
  else if (line.startsWith("branch ")) out[out.length - 1].branch = line.slice(7).replace(/^refs\/heads\//, "");
509
543
  else if (line === "locked" || line.startsWith("locked ")) out[out.length - 1].locked = true;
@@ -512,20 +546,20 @@ function parseWorktrees(porcelain) {
512
546
  }
513
547
  var samePath = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
514
548
  function isOfficeDesk(p, fullName, root) {
515
- const desks = path2.dirname(p);
516
- const repo = path2.dirname(desks);
517
- const workspaces = path2.dirname(repo);
518
- if (!samePath(path2.basename(desks), "desks") || !samePath(path2.basename(repo), fullName.replace("/", "__"))) return false;
519
- if (samePath(workspaces, path2.resolve(root))) return true;
520
- return path2.basename(workspaces) === "workspaces" && OLD_HOMES.some((h) => samePath(path2.basename(path2.dirname(workspaces)), h));
549
+ const desks = path3.dirname(p);
550
+ const repo = path3.dirname(desks);
551
+ const workspaces = path3.dirname(repo);
552
+ if (!samePath(path3.basename(desks), "desks") || !samePath(path3.basename(repo), fullName.replace("/", "__"))) return false;
553
+ if (samePath(workspaces, path3.resolve(root))) return true;
554
+ return path3.basename(workspaces) === "workspaces" && OLD_HOMES.some((h) => samePath(path3.basename(path3.dirname(workspaces)), h));
521
555
  }
522
556
  function planSweep(input, keep) {
523
- const deskRoot = path2.join(path2.resolve(input.root), input.fullName.replace("/", "__"), "desks");
524
- const kept = (p) => keep.desks.some((slug2) => samePath(p, path2.join(deskRoot, slug2)));
557
+ const deskRoot = path3.join(path3.resolve(input.root), input.fullName.replace("/", "__"), "desks");
558
+ const kept = (p) => keep.desks.some((slug2) => samePath(p, path3.join(deskRoot, slug2)));
525
559
  const worktrees = input.worktrees.slice(1).filter((w) => !w.locked && isOfficeDesk(w.path, input.fullName, input.root) && !kept(w.path));
526
560
  const stays = input.worktrees.filter((w) => !worktrees.includes(w));
527
561
  const folders = input.folders.filter((name) => {
528
- const p = path2.join(deskRoot, name);
562
+ const p = path3.join(deskRoot, name);
529
563
  return !kept(p) && !input.worktrees.some((w) => samePath(w.path, p));
530
564
  });
531
565
  const branches = input.branches.filter((b) => OFFICE_BRANCH.test(b) && !keep.branches.includes(b) && !stays.some((w) => w.branch === b));
@@ -534,31 +568,31 @@ function planSweep(input, keep) {
534
568
  async function inUse(dir) {
535
569
  const probe = `${dir}.sweep`;
536
570
  try {
537
- await fs2.rename(dir, probe);
571
+ await fs3.rename(dir, probe);
538
572
  } catch (err) {
539
573
  return err.code !== "ENOENT";
540
574
  }
541
- await fs2.rename(probe, dir);
575
+ await fs3.rename(probe, dir);
542
576
  return false;
543
577
  }
544
578
  var stamp = (d) => `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, "0")}${String(d.getDate()).padStart(2, "0")}`;
545
- async function saveLeftovers(fullName, desk, label = path2.basename(desk)) {
579
+ async function saveLeftovers(fullName, desk, label = path3.basename(desk)) {
546
580
  const g = (args) => git(args, { cwd: desk, timeoutMs: 6e4 });
547
581
  if (!await g(["rev-parse", "--verify", "-q", "HEAD"]).catch(() => "")) return null;
548
582
  const dirty = await g(["status", "--porcelain", "--untracked-files=no"]);
549
583
  const commits = Number(await g(["rev-list", "--count", "HEAD", "--not", "--remotes"]));
550
584
  if (!dirty && !commits) return null;
551
- const dir = path2.join(HOME_DIR, "leftovers", fullName.replace("/", "__"));
552
- await fs2.mkdir(dir, { recursive: true });
553
- const tmp = await fs2.mkdtemp(path2.join(dir, ".tmp-"));
585
+ const dir = path3.join(HOME_DIR, "leftovers", fullName.replace("/", "__"));
586
+ await fs3.mkdir(dir, { recursive: true });
587
+ const tmp = await fs3.mkdtemp(path3.join(dir, ".tmp-"));
554
588
  try {
555
589
  if (commits) await g(["format-patch", "-q", "-o", tmp, "HEAD", "--not", "--remotes"]);
556
- if (dirty) await g(["diff", "HEAD", "--binary", `--output=${path2.join(tmp, "zz-uncommitted.patch")}`]);
557
- const parts = (await fs2.readdir(tmp)).sort();
590
+ if (dirty) await g(["diff", "HEAD", "--binary", `--output=${path3.join(tmp, "zz-uncommitted.patch")}`]);
591
+ const parts = (await fs3.readdir(tmp)).sort();
558
592
  const base = `${label}-${stamp(/* @__PURE__ */ new Date())}`;
559
- let file = path2.join(dir, `${base}.patch`);
560
- for (let n = 2; await exists(file); n++) file = path2.join(dir, `${base}-${n}.patch`);
561
- await fs2.writeFile(file, Buffer.concat(await Promise.all(parts.map((p) => fs2.readFile(path2.join(tmp, p))))));
593
+ let file = path3.join(dir, `${base}.patch`);
594
+ for (let n = 2; await exists(file); n++) file = path3.join(dir, `${base}-${n}.patch`);
595
+ await fs3.writeFile(file, Buffer.concat(await Promise.all(parts.map((p) => fs3.readFile(path3.join(tmp, p))))));
562
596
  return file;
563
597
  } finally {
564
598
  await removeDir(tmp).catch(() => void 0);
@@ -568,16 +602,16 @@ function sweepDesks(fullName, keep) {
568
602
  return withRepoLock(fullName, async () => {
569
603
  const result = { desks: 0, folders: 0, branches: 0, patches: [], skipped: [] };
570
604
  const main = mainDir(fullName);
571
- if (!await exists(path2.join(main, ".git"))) return result;
605
+ if (!await exists(path3.join(main, ".git"))) return result;
572
606
  const g = (args) => git(args, { cwd: main, timeoutMs: 6e4 });
573
607
  await g(["worktree", "prune"]);
574
- const real = (p) => fs2.realpath(p).catch(() => p);
608
+ const real = (p) => fs3.realpath(p).catch(() => p);
575
609
  const worktrees = await Promise.all(parseWorktrees(await g(["worktree", "list", "--porcelain"])).map(async (w) => ({ ...w, path: await real(w.path) })));
576
610
  const refs = await g(["for-each-ref", "--format=%(refname)", "refs/heads/swarm", "refs/heads/qa"]);
577
611
  const branches = refs.split(/\r?\n/).filter(Boolean).map((r) => r.replace(/^refs\/heads\//, ""));
578
612
  const root = await real(WORKSPACE_ROOT);
579
- const deskRoot = path2.join(root, fullName.replace("/", "__"), "desks");
580
- const folders = (await fs2.readdir(deskRoot, { withFileTypes: true }).catch(() => [])).filter((e) => e.isDirectory()).map((e) => e.name);
613
+ const deskRoot = path3.join(root, fullName.replace("/", "__"), "desks");
614
+ const folders = (await fs3.readdir(deskRoot, { withFileTypes: true }).catch(() => [])).filter((e) => e.isDirectory()).map((e) => e.name);
581
615
  const plan = planSweep({ fullName, root, worktrees, branches, folders }, keep);
582
616
  const held = /* @__PURE__ */ new Set();
583
617
  for (const wt of plan.worktrees) {
@@ -595,7 +629,7 @@ function sweepDesks(fullName, keep) {
595
629
  }
596
630
  await g(["worktree", "prune"]).catch(() => void 0);
597
631
  for (const name of plan.folders) {
598
- const dir = path2.join(deskRoot, name);
632
+ const dir = path3.join(deskRoot, name);
599
633
  try {
600
634
  if (await inUse(dir)) throw new Error("in use");
601
635
  await removeDir(dir);
@@ -619,12 +653,12 @@ async function dirSize(dir, concurrency = 8) {
619
653
  const queue = [dir];
620
654
  let active = 0;
621
655
  const visit = async (d) => {
622
- const entries = await fs2.readdir(d, { withFileTypes: true }).catch(() => []);
656
+ const entries = await fs3.readdir(d, { withFileTypes: true }).catch(() => []);
623
657
  const sizes = await Promise.all(
624
658
  entries.map((e) => {
625
- const p = path2.join(d, e.name);
659
+ const p = path3.join(d, e.name);
626
660
  if (e.isDirectory()) queue.push(p);
627
- return e.isFile() ? fs2.lstat(p).then((s2) => s2.size, () => 0) : 0;
661
+ return e.isFile() ? fs3.lstat(p).then((s2) => s2.size, () => 0) : 0;
628
662
  })
629
663
  );
630
664
  for (const s2 of sizes) total += s2;
@@ -647,29 +681,29 @@ async function dirSize(dir, concurrency = 8) {
647
681
  async function trimTargets(wt) {
648
682
  const ignored = (await git(["ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--directory"], { cwd: wt })).split("\0").filter((p) => p.endsWith("/")).map((p) => p.slice(0, -1)).filter((p) => p.includes("/") ? p.endsWith("/node_modules") : TRIM_DIRS.includes(p));
649
683
  const present = [];
650
- for (const name of TRIM_DIRS) if ((await fs2.lstat(path2.join(wt, name)).catch(() => null))?.isDirectory()) present.push(name);
684
+ for (const name of TRIM_DIRS) if ((await fs3.lstat(path3.join(wt, name)).catch(() => null))?.isDirectory()) present.push(name);
651
685
  const candidates = [.../* @__PURE__ */ new Set([...ignored, ...present])];
652
686
  if (candidates.length === 0) return [];
653
687
  const tracked = (await git(["ls-files", "-z", "--", ...candidates], { cwd: wt })).split("\0").filter(Boolean);
654
688
  return candidates.filter((c) => !tracked.some((f) => f.startsWith(`${c}/`)));
655
689
  }
656
690
  function trimDesk(fullName, agentSlug, stillIdle = () => true) {
657
- return trimWorktree(deskDir(fullName, agentSlug), path2.join(repoDir(fullName), "trash"), agentSlug, fullName, stillIdle);
691
+ return trimWorktree(deskDir(fullName, agentSlug), path3.join(repoDir(fullName), "trash"), agentSlug, fullName, stillIdle);
658
692
  }
659
693
  async function trimWorktree(wt, trash, name, lock, stillIdle) {
660
- for (const old of await fs2.readdir(trash).catch(() => [])) {
661
- if (old.startsWith(`${name}-`)) await removeDir(path2.join(trash, old)).catch(() => void 0);
694
+ for (const old of await fs3.readdir(trash).catch(() => [])) {
695
+ if (old.startsWith(`${name}-`)) await removeDir(path3.join(trash, old)).catch(() => void 0);
662
696
  }
663
- const bin = path2.join(trash, `${name}-${Date.now()}`);
697
+ const bin = path3.join(trash, `${name}-${Date.now()}`);
664
698
  const moved = await withRepoLock(lock, async () => {
665
- if (!stillIdle() || !await exists(path2.join(wt, ".git"))) return null;
699
+ if (!stillIdle() || !await exists(path3.join(wt, ".git"))) return null;
666
700
  const out = { removed: [], skipped: [] };
667
701
  const targets = await trimTargets(wt);
668
702
  for (const [i, rel2] of targets.entries()) {
669
703
  if (!stillIdle()) break;
670
704
  try {
671
- await fs2.mkdir(bin, { recursive: true });
672
- await fs2.rename(path2.join(wt, rel2), path2.join(bin, `${i}-${path2.basename(rel2)}`));
705
+ await fs3.mkdir(bin, { recursive: true });
706
+ await fs3.rename(path3.join(wt, rel2), path3.join(bin, `${i}-${path3.basename(rel2)}`));
673
707
  out.removed.push(rel2);
674
708
  } catch {
675
709
  out.skipped.push(rel2);
@@ -752,20 +786,20 @@ Write-Output $kill.Count`;
752
786
  }
753
787
  }
754
788
  }
755
- var MACHINES_DIR = path2.join(HOME_DIR, "machines");
789
+ var MACHINES_DIR = path3.join(HOME_DIR, "machines");
756
790
  var repoFolder = (fullName) => fullName.replace("/", "__");
757
- var machineDir = (machine) => path2.join(MACHINES_DIR, machine);
758
- var machineClone = (machine, fullName) => path2.join(machineDir(machine), "repos", repoFolder(fullName));
759
- var machineDesk = (machine, fullName) => path2.join(machineDir(machine), "work", repoFolder(fullName));
760
- var machineTmp = (machine) => path2.join(machineDir(machine), "tmp");
791
+ var machineDir = (machine) => path3.join(MACHINES_DIR, machine);
792
+ var machineClone = (machine, fullName) => path3.join(machineDir(machine), "repos", repoFolder(fullName));
793
+ var machineDesk = (machine, fullName) => path3.join(machineDir(machine), "work", repoFolder(fullName));
794
+ var machineTmp = (machine) => path3.join(machineDir(machine), "tmp");
761
795
  var machineLock = (machine, fullName) => `machine:${machine}:${fullName}`;
762
796
  async function ensureMachineClone(machine, fullName) {
763
797
  const clone = machineClone(machine, fullName);
764
- if (await exists(path2.join(clone, ".git"))) return clone;
798
+ if (await exists(path3.join(clone, ".git"))) return clone;
765
799
  await removeDir(clone).catch(() => void 0);
766
- await fs2.mkdir(path2.dirname(clone), { recursive: true });
800
+ await fs3.mkdir(path3.dirname(clone), { recursive: true });
767
801
  const main = mainDir(fullName);
768
- const origin = await exists(path2.join(main, ".git")) ? await git(["remote", "get-url", "origin"], { cwd: main }).catch(() => "") : "";
802
+ const origin = await exists(path3.join(main, ".git")) ? await git(["remote", "get-url", "origin"], { cwd: main }).catch(() => "") : "";
769
803
  if (origin) await git(["clone", "-q", "--no-checkout", "--reference-if-able", main, "--dissociate", origin, clone], { timeoutMs: 6e5 });
770
804
  else await gh(["repo", "clone", fullName, clone, "--", "--no-checkout"], { timeoutMs: 6e5 });
771
805
  await addLocalExcludes(clone);
@@ -775,7 +809,7 @@ function prepareMachineDesk(machine, fullName, base, branch, note2) {
775
809
  return withRepoLock(machineLock(machine, fullName), async () => setUpWorktree(await ensureMachineClone(machine, fullName), machineDesk(machine, fullName), fullName, base, branch, note2));
776
810
  }
777
811
  function trimMachineDesk(machine, fullName, stillIdle = () => true) {
778
- return trimWorktree(machineDesk(machine, fullName), path2.join(machineDir(machine), "trash"), repoFolder(fullName), machineLock(machine, fullName), stillIdle);
812
+ return trimWorktree(machineDesk(machine, fullName), path3.join(machineDir(machine), "trash"), repoFolder(fullName), machineLock(machine, fullName), stillIdle);
779
813
  }
780
814
  function releaseMachine(machine, fullName, port, keep = { pids: [], markers: [] }) {
781
815
  return releaseDirs([machineDesk(machine, fullName)], port, keep);
@@ -783,7 +817,7 @@ function releaseMachine(machine, fullName, port, keep = { pids: [], markers: []
783
817
  function sweepMachine(machine, fullName, keep) {
784
818
  return withRepoLock(machineLock(machine, fullName), async () => {
785
819
  const clone = machineClone(machine, fullName);
786
- if (!await exists(path2.join(clone, ".git"))) return 0;
820
+ if (!await exists(path3.join(clone, ".git"))) return 0;
787
821
  const g = (args) => git(args, { cwd: clone, timeoutMs: 6e4 });
788
822
  await g(["worktree", "prune"]);
789
823
  const out = parseWorktrees(await g(["worktree", "list", "--porcelain"])).map((w) => w.branch);
@@ -801,8 +835,8 @@ async function removeMachine(machine) {
801
835
  if (!await exists(dir)) return { removed: true, patches: [] };
802
836
  if (await inUse(dir)) return { removed: false, patches: [] };
803
837
  const patches = [];
804
- for (const name of await fs2.readdir(path2.join(dir, "work")).catch(() => [])) {
805
- const patch = await saveLeftovers(name.replace("__", "/"), path2.join(dir, "work", name), `machine-${machine}`).catch(() => null);
838
+ for (const name of await fs3.readdir(path3.join(dir, "work")).catch(() => [])) {
839
+ const patch = await saveLeftovers(name.replace("__", "/"), path3.join(dir, "work", name), `machine-${machine}`).catch(() => null);
806
840
  if (patch) patches.push(patch);
807
841
  }
808
842
  try {
@@ -813,7 +847,7 @@ async function removeMachine(machine) {
813
847
  }
814
848
  }
815
849
  async function listMachines() {
816
- return (await fs2.readdir(MACHINES_DIR, { withFileTypes: true }).catch(() => [])).filter((e) => e.isDirectory()).map((e) => e.name);
850
+ return (await fs3.readdir(MACHINES_DIR, { withFileTypes: true }).catch(() => [])).filter((e) => e.isDirectory()).map((e) => e.name);
817
851
  }
818
852
 
819
853
  // server/backend.ts
@@ -1039,8 +1073,8 @@ async function uploadEvidence(fullName, filePath, data) {
1039
1073
  }
1040
1074
 
1041
1075
  // server/agentRunner.ts
1042
- import fs5 from "node:fs";
1043
- import path5 from "node:path";
1076
+ import fs6 from "node:fs";
1077
+ import path6 from "node:path";
1044
1078
  import { query } from "@anthropic-ai/claude-agent-sdk";
1045
1079
 
1046
1080
  // shared/aiUsage.ts
@@ -1174,15 +1208,15 @@ function codexUsage(sessionId, records, now2) {
1174
1208
  }
1175
1209
 
1176
1210
  // server/browser.ts
1177
- import fs3 from "node:fs";
1211
+ import fs4 from "node:fs";
1178
1212
  import { createRequire } from "node:module";
1179
- import os2 from "node:os";
1180
- import path3 from "node:path";
1213
+ import os3 from "node:os";
1214
+ import path4 from "node:path";
1181
1215
  function playwrightMcpCli() {
1182
1216
  try {
1183
1217
  const pkgFile = createRequire(import.meta.url).resolve("@playwright/mcp/package.json");
1184
- const bin = JSON.parse(fs3.readFileSync(pkgFile, "utf8")).bin?.["playwright-mcp"] ?? "cli.js";
1185
- return path3.join(path3.dirname(pkgFile), bin);
1218
+ const bin = JSON.parse(fs4.readFileSync(pkgFile, "utf8")).bin?.["playwright-mcp"] ?? "cli.js";
1219
+ return path4.join(path4.dirname(pkgFile), bin);
1186
1220
  } catch {
1187
1221
  return null;
1188
1222
  }
@@ -1192,16 +1226,16 @@ function playwrightMcpCommand(cli, initScript, outputDir, node = process.execPat
1192
1226
  }
1193
1227
  function playwrightMcp(outputDir) {
1194
1228
  const cli = playwrightMcpCli();
1195
- return cli ? playwrightMcpCommand(cli, path3.join(import.meta.dirname, "browser-init.js"), outputDir) : null;
1229
+ return cli ? playwrightMcpCommand(cli, path4.join(import.meta.dirname, "browser-init.js"), outputDir) : null;
1196
1230
  }
1197
- function chromePaths(platform = process.platform, env = process.env, home = os2.homedir()) {
1231
+ function chromePaths(platform = process.platform, env = process.env, home = os3.homedir()) {
1198
1232
  if (platform === "win32") {
1199
- return [env.LOCALAPPDATA, env.PROGRAMFILES, env["PROGRAMFILES(X86)"]].filter((d) => !!d).map((d) => path3.win32.join(d, "Google", "Chrome", "Application", "chrome.exe"));
1233
+ return [env.LOCALAPPDATA, env.PROGRAMFILES, env["PROGRAMFILES(X86)"]].filter((d) => !!d).map((d) => path4.win32.join(d, "Google", "Chrome", "Application", "chrome.exe"));
1200
1234
  }
1201
- if (platform === "darwin") return ["/Applications/Google Chrome.app", path3.posix.join(home, "Applications", "Google Chrome.app")];
1235
+ if (platform === "darwin") return ["/Applications/Google Chrome.app", path4.posix.join(home, "Applications", "Google Chrome.app")];
1202
1236
  return ["/opt/google/chrome/chrome", "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable"];
1203
1237
  }
1204
- var hasChrome = () => chromePaths().some((p) => fs3.existsSync(p));
1238
+ var hasChrome = () => chromePaths().some((p) => fs4.existsSync(p));
1205
1239
  function browserProblem(mcp, chrome = hasChrome()) {
1206
1240
  if (!mcp) return "\u26A0 The browser tool (@playwright/mcp) is not installed with Droidsembly: reinstall it, or run npx cubefarm doctor";
1207
1241
  if (!chrome) return "\u26A0 Google Chrome not found, so this session cannot test in a browser: install it, or run npx cubefarm doctor";
@@ -1209,7 +1243,7 @@ function browserProblem(mcp, chrome = hasChrome()) {
1209
1243
  }
1210
1244
 
1211
1245
  // server/clis.ts
1212
- import fs4 from "node:fs";
1246
+ import fs5 from "node:fs";
1213
1247
 
1214
1248
  // server/codexUsage.ts
1215
1249
  var CODEX_USAGE_READER_SOURCE = String.raw`
@@ -1248,7 +1282,7 @@ function usageRecords(event) {
1248
1282
 
1249
1283
  // server/clis.ts
1250
1284
  import { createRequire as createRequire2 } from "node:module";
1251
- import path4 from "node:path";
1285
+ import path5 from "node:path";
1252
1286
 
1253
1287
  // shared/models.ts
1254
1288
  var isClaudeModel = (model2) => /^(claude|opus|sonnet|haiku|fable|default|best|opusplan)\b/i.test(model2.trim());
@@ -1290,13 +1324,13 @@ var cliLabel = (id) => CLIS.find((c) => c.id === id)?.label ?? id;
1290
1324
  var WIN = process.platform === "win32";
1291
1325
  function resolveCommand(name, env = process.env) {
1292
1326
  const key = Object.keys(env).find((k) => k.toUpperCase() === "PATH") ?? "PATH";
1293
- const dirs = (env[key] ?? "").split(path4.delimiter).filter(Boolean);
1327
+ const dirs = (env[key] ?? "").split(path5.delimiter).filter(Boolean);
1294
1328
  const exts = WIN ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter((e) => /^\.(exe|cmd|bat|com)$/i.test(e)) : [""];
1295
1329
  for (const dir of dirs) {
1296
1330
  for (const ext of exts) {
1297
- const file = path4.join(dir, name + ext.toLowerCase());
1331
+ const file = path5.join(dir, name + ext.toLowerCase());
1298
1332
  try {
1299
- const st = fs4.statSync(file);
1333
+ const st = fs5.statSync(file);
1300
1334
  if (st.isFile() && (WIN || (st.mode & 73) !== 0)) return file;
1301
1335
  } catch {
1302
1336
  }
@@ -1317,16 +1351,16 @@ function unwrapCmdShim(shimPath, text3, env = process.env) {
1317
1351
  });
1318
1352
  return missing ? null : { file, args: [] };
1319
1353
  }
1320
- const dir = path4.dirname(shimPath);
1321
- const targets = [...line.matchAll(/"%dp0%\\([^"]+)"/g)].map((m) => path4.join(dir, m[1]));
1354
+ const dir = path5.dirname(shimPath);
1355
+ const targets = [...line.matchAll(/"%dp0%\\([^"]+)"/g)].map((m) => path5.join(dir, m[1]));
1322
1356
  const target = targets[targets.length - 1];
1323
1357
  if (!target) return null;
1324
1358
  if (/\.exe$/i.test(target)) return { file: target, args: [] };
1325
1359
  if (!/\.[cm]?js$/i.test(target)) return null;
1326
1360
  const between = line.slice(line.indexOf('"%_prog%"') + '"%_prog%"'.length, line.lastIndexOf(`"%dp0%\\`));
1327
1361
  const nodeFlags = line.includes('"%_prog%"') ? between.trim().split(/\s+/).filter((f) => f.startsWith("--")) : [];
1328
- const localNode = path4.join(dir, "node.exe");
1329
- return { file: fs4.existsSync(localNode) ? localNode : process.execPath, args: [...nodeFlags, target] };
1362
+ const localNode = path5.join(dir, "node.exe");
1363
+ return { file: fs5.existsSync(localNode) ? localNode : process.execPath, args: [...nodeFlags, target] };
1330
1364
  }
1331
1365
  var bundled;
1332
1366
  function bundledClaude() {
@@ -1359,7 +1393,7 @@ function commandFor(id) {
1359
1393
  if (!found2) return null;
1360
1394
  if (WIN && /\.(cmd|bat)$/i.test(found2)) {
1361
1395
  try {
1362
- return unwrapCmdShim(found2, fs4.readFileSync(found2, "utf8")) ?? { file: found2, args: [] };
1396
+ return unwrapCmdShim(found2, fs5.readFileSync(found2, "utf8")) ?? { file: found2, args: [] };
1363
1397
  } catch {
1364
1398
  return { file: found2, args: [] };
1365
1399
  }
@@ -1390,14 +1424,14 @@ var BOX_CODEX_VERSION = "0.163.0";
1390
1424
  var BOX_OPENCODE_VERSION = "2.2.6";
1391
1425
  function packageField(pkg, field) {
1392
1426
  try {
1393
- let dir = path4.dirname(createRequire2(import.meta.url).resolve(pkg));
1427
+ let dir = path5.dirname(createRequire2(import.meta.url).resolve(pkg));
1394
1428
  for (let i = 0; i < 6; i++) {
1395
- const file = path4.join(dir, "package.json");
1396
- if (fs4.existsSync(file)) {
1397
- const json = JSON.parse(fs4.readFileSync(file, "utf8"));
1429
+ const file = path5.join(dir, "package.json");
1430
+ if (fs5.existsSync(file)) {
1431
+ const json = JSON.parse(fs5.readFileSync(file, "utf8"));
1398
1432
  if (json.name === pkg) return typeof json[field] === "string" ? json[field] : null;
1399
1433
  }
1400
- dir = path4.dirname(dir);
1434
+ dir = path5.dirname(dir);
1401
1435
  }
1402
1436
  } catch {
1403
1437
  }
@@ -1412,7 +1446,7 @@ function boxVersions() {
1412
1446
  };
1413
1447
  }
1414
1448
  function localUrl(p, env = process.env) {
1415
- return env[`CUBEFARM_${p.id.toUpperCase()}_URL`]?.trim() || p.url;
1449
+ return officeEnv(env, `CUBEFARM_${p.id.toUpperCase()}_URL`)?.trim() || p.url;
1416
1450
  }
1417
1451
  function codexLocal(model2, toml) {
1418
1452
  const local = localModel(model2);
@@ -1485,7 +1519,7 @@ function launchArgs(id, ctx) {
1485
1519
  }
1486
1520
  case "opencode": {
1487
1521
  const local = localModel(ctx.model);
1488
- const sessionID = ctx.resumeId || `ses_cubefarm${ctx.sessionId.replaceAll("-", "")}`;
1522
+ const sessionID = ctx.resumeId || `ses_droidsembly${ctx.sessionId.replaceAll("-", "")}`;
1489
1523
  const model2 = local ? `${local.provider.id}/${local.model}` : ctx.model;
1490
1524
  const servers = {
1491
1525
  ...ctx.browser ? { playwright: { type: "local", command: [ctx.browser.command, ...ctx.browser.args] } } : {},
@@ -1785,7 +1819,7 @@ function screenshotFile(cwd, text3) {
1785
1819
  const file = text3.match(/\]\(([^)\s]+\.(png|jpe?g))\)/i);
1786
1820
  if (!file) return null;
1787
1821
  try {
1788
- return { data: fs5.readFileSync(path5.resolve(cwd, file[1])), mime: /png$/i.test(file[2]) ? "image/png" : "image/jpeg" };
1822
+ return { data: fs6.readFileSync(path6.resolve(cwd, file[1])), mime: /png$/i.test(file[2]) ? "image/png" : "image/jpeg" };
1789
1823
  } catch {
1790
1824
  return null;
1791
1825
  }
@@ -1794,17 +1828,17 @@ var IMAGE_MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jp
1794
1828
  function newScreenshots(dir, seen, now2 = Date.now()) {
1795
1829
  let names;
1796
1830
  try {
1797
- names = fs5.readdirSync(dir);
1831
+ names = fs6.readdirSync(dir);
1798
1832
  } catch {
1799
1833
  return [];
1800
1834
  }
1801
1835
  const found2 = [];
1802
1836
  for (const name of names.sort()) {
1803
- const mime = IMAGE_MIME[path5.extname(name).toLowerCase()];
1804
- const file = path5.join(dir, name);
1837
+ const mime = IMAGE_MIME[path6.extname(name).toLowerCase()];
1838
+ const file = path6.join(dir, name);
1805
1839
  if (!mime || seen.has(name)) continue;
1806
1840
  try {
1807
- if (now2 - fs5.statSync(file).mtimeMs < 1e3) continue;
1841
+ if (now2 - fs6.statSync(file).mtimeMs < 1e3) continue;
1808
1842
  } catch {
1809
1843
  continue;
1810
1844
  }
@@ -1816,7 +1850,7 @@ var clip = (s2, n) => s2.length > n ? `${s2.slice(0, n - 1)}\u2026` : s2;
1816
1850
  function rel(cwd, p) {
1817
1851
  const s2 = String(p ?? "");
1818
1852
  if (!s2) return "";
1819
- const r = path5.relative(cwd, path5.resolve(cwd, s2));
1853
+ const r = path6.relative(cwd, path6.resolve(cwd, s2));
1820
1854
  return r && !r.startsWith("..") ? r.replaceAll("\\", "/") : s2;
1821
1855
  }
1822
1856
  var escapeRe = (s2) => s2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -1953,7 +1987,7 @@ function startSession(opts, callbacks) {
1953
1987
  env[k] = v;
1954
1988
  }
1955
1989
  Object.assign(env, opts.env);
1956
- env.CLAUDE_AGENT_SDK_CLIENT_APP = `cubefarm/${VERSION}`;
1990
+ env.CLAUDE_AGENT_SDK_CLIENT_APP = `droidsembly/${VERSION}`;
1957
1991
  const mcpServers = {};
1958
1992
  if (opts.browserTesting) {
1959
1993
  const browser = playwrightMcp();
@@ -2136,8 +2170,8 @@ function startSession(opts, callbacks) {
2136
2170
 
2137
2171
  // server/cliRunner.ts
2138
2172
  import crypto3 from "node:crypto";
2139
- import fs8 from "node:fs";
2140
- import path9 from "node:path";
2173
+ import fs9 from "node:fs";
2174
+ import path10 from "node:path";
2141
2175
  import { pathToFileURL } from "node:url";
2142
2176
 
2143
2177
  // server/mcpHttp.ts
@@ -2194,12 +2228,12 @@ var HttpError = class extends Error {
2194
2228
  };
2195
2229
 
2196
2230
  // server/secrets.ts
2197
- import fs6 from "node:fs/promises";
2198
- import path6 from "node:path";
2231
+ import fs7 from "node:fs/promises";
2232
+ import path7 from "node:path";
2199
2233
  var queues = /* @__PURE__ */ new Map();
2200
2234
  async function readSecrets(file) {
2201
2235
  try {
2202
- const s2 = JSON.parse(await fs6.readFile(file, "utf8"));
2236
+ const s2 = JSON.parse(await fs7.readFile(file, "utf8"));
2203
2237
  return s2 && typeof s2 === "object" ? s2 : {};
2204
2238
  } catch {
2205
2239
  return {};
@@ -2209,11 +2243,11 @@ function mergeSecrets(file, patch) {
2209
2243
  const write = (queues.get(file) ?? Promise.resolve()).then(async () => {
2210
2244
  const next = { ...await readSecrets(file), ...patch };
2211
2245
  for (const k of Object.keys(next)) if (next[k] === void 0) delete next[k];
2212
- await fs6.mkdir(path6.dirname(file), { recursive: true });
2246
+ await fs7.mkdir(path7.dirname(file), { recursive: true });
2213
2247
  const tmp = `${file}.tmp`;
2214
- await fs6.writeFile(tmp, JSON.stringify(next, null, 2), { mode: 384 });
2215
- await fs6.rename(tmp, file);
2216
- await fs6.chmod(file, 384).catch(() => void 0);
2248
+ await fs7.writeFile(tmp, JSON.stringify(next, null, 2), { mode: 384 });
2249
+ await fs7.rename(tmp, file);
2250
+ await fs7.chmod(file, 384).catch(() => void 0);
2217
2251
  });
2218
2252
  queues.set(
2219
2253
  file,
@@ -2367,16 +2401,32 @@ function upstashBoxes(apiKey, options = {}) {
2367
2401
  };
2368
2402
  }
2369
2403
 
2404
+ // server/boxRemoval.ts
2405
+ async function removeBoxVerified(api, id) {
2406
+ await api.remove(id);
2407
+ const absent = await api.get(id) === null;
2408
+ const remaining = await api.list();
2409
+ return absent && !remaining.some((box) => box.id === id);
2410
+ }
2411
+
2370
2412
  // server/cloud.ts
2371
- var CLAUDE_TOKEN_ENV = "CUBEFARM_CLAUDE_TOKEN";
2413
+ var CLAUDE_TOKEN_ENV = "DROIDSEMBLY_CLAUDE_TOKEN";
2372
2414
  var ANTHROPIC_KEY_ENV = "CUBEFARM_ANTHROPIC_KEY";
2373
2415
  var TOKEN_FIELD = { github: "cloudGithubToken", anthropic: "anthropicApiKey", openai: "openaiApiKey" };
2374
2416
  var officeId = () => Math.random().toString(36).slice(2, 8).padEnd(6, "0");
2375
- var boxName = (office, machine) => `cubefarm-${office}-${machine}`;
2376
- var boxLabels = (office, machine) => ["cubefarm", `cf:${office}`, `m:${machine}`];
2417
+ var boxName = (office, machine) => `droidsembly-${office}-${machine}`;
2418
+ var boxLabels = (office, machine) => ["droidsembly", `ds:${office}`, "cubefarm", `cf:${office}`, `m:${machine}`];
2377
2419
  function machineOfBox(box, office) {
2378
- if (!box.labels.includes(`cf:${office}`)) return null;
2379
- return box.labels.find((l) => l.startsWith("m:"))?.slice(2) || null;
2420
+ const labels = box.labels;
2421
+ const legacy = labels.includes("cubefarm");
2422
+ const current = labels.includes("droidsembly");
2423
+ const cf = labels.filter((l) => l.startsWith("cf:"));
2424
+ const ds = labels.filter((l) => l.startsWith("ds:"));
2425
+ const machines = labels.filter((l) => l.startsWith("m:"));
2426
+ if (!legacy && !current || legacy !== (cf.length === 1) || current !== (ds.length === 1)) return null;
2427
+ if (cf.length > 1 || ds.length > 1 || legacy && cf[0] !== `cf:${office}` || current && ds[0] !== `ds:${office}`) return null;
2428
+ if (machines.length !== 1 || !/^m:[A-Za-z0-9._-]{1,18}$/.test(machines[0])) return null;
2429
+ return machines[0].slice(2);
2380
2430
  }
2381
2431
  var CLAUDE_VARS = ["CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", ANTHROPIC_KEY_ENV];
2382
2432
  var github = (i) => i.secrets.cloudGithubToken || i.ghToken;
@@ -2440,7 +2490,7 @@ var Cloud = class {
2440
2490
  boxApi() {
2441
2491
  return this.api;
2442
2492
  }
2443
- claudeToken = () => (this.deps.env[CLAUDE_TOKEN_ENV] ?? "").trim();
2493
+ claudeToken = () => (officeEnv(this.deps.env, "CUBEFARM_CLAUDE_TOKEN") ?? "").trim();
2444
2494
  /** The gh login token, re-read at most once a minute (the manager may sign in or out meanwhile). */
2445
2495
  async refreshGh(force = false) {
2446
2496
  if (this.deps.credentials) return "";
@@ -2463,7 +2513,7 @@ var Cloud = class {
2463
2513
  }
2464
2514
  /** Every saved key and token, so they're scrubbed from anything the office writes or shows. */
2465
2515
  secretValues() {
2466
- return [...Object.values(this.secrets), this.claudeToken(), this.gh].filter((s2) => !!s2);
2516
+ return [...Object.values(this.secrets), this.claudeToken(), this.deps.env.CUBEFARM_CLAUDE_TOKEN, this.deps.env.DROIDSEMBLY_CLAUDE_TOKEN, this.gh].filter((s2) => !!s2);
2467
2517
  }
2468
2518
  /** What a CLI runs with in a Box. */
2469
2519
  async credentials(cli) {
@@ -2527,7 +2577,7 @@ var Cloud = class {
2527
2577
  const all = await this.api.list();
2528
2578
  const office = this.deps.office();
2529
2579
  const machines = this.deps.machines();
2530
- const ours = all.filter((b) => b.labels.includes(`cf:${office}`));
2580
+ const ours = all.filter((b) => b.status !== "deleted" && machineOfBox(b, office) !== null);
2531
2581
  this.boxes = {
2532
2582
  total: all.filter((b) => b.status !== "deleted").length,
2533
2583
  running: ours.filter((b) => b.status === "running" || b.status === "idle" || b.status === "creating").length,
@@ -2549,13 +2599,24 @@ var Cloud = class {
2549
2599
  if (!this.api) throw new HttpError(400, "Save your Upstash Box API key first.");
2550
2600
  const office = this.deps.office();
2551
2601
  const machines = this.deps.machines();
2552
- const doomed = (await this.count()).filter((b) => b.labels.includes(`cf:${office}`) && !machines.has(machineOfBox(b, office) ?? ""));
2553
- let deleted = 0;
2602
+ const doomed = (await this.count()).filter((b) => {
2603
+ const machine = machineOfBox(b, office);
2604
+ return b.status !== "deleted" && machine !== null && !machines.has(machine);
2605
+ });
2606
+ let deleted = 0, unconfirmed = 0;
2554
2607
  for (const b of doomed) {
2555
- await this.api.remove(b.id).then(() => deleted++).catch((err) => this.deps.log(`could not delete the orphan Box ${b.name}: ${err.message}`));
2608
+ const machine = machineOfBox(b, this.deps.office());
2609
+ if (machine === null || this.deps.office() !== office || this.deps.machines().has(machine)) continue;
2610
+ try {
2611
+ if (await removeBoxVerified(this.api, b.id)) deleted++;
2612
+ else unconfirmed++;
2613
+ } catch {
2614
+ unconfirmed++;
2615
+ }
2556
2616
  }
2617
+ if (unconfirmed) this.deps.log(`${unconfirmed} orphan Box removal(s) could not be confirmed; check the Upstash console. No automatic retry.`);
2557
2618
  await this.count().catch(() => void 0);
2558
- return { deleted };
2619
+ return { deleted, unconfirmed };
2559
2620
  }
2560
2621
  emit() {
2561
2622
  const view = this.view();
@@ -2950,8 +3011,7 @@ var BoxPty = class {
2950
3011
  const wasRunning = !this.exited;
2951
3012
  this.stopped = true;
2952
3013
  this.close();
2953
- void this.o.api.run(this.o.boxId, tmuxKill(this.o.token), { timeoutMs: 6e4 }).catch(() => void 0);
2954
- this.o.gone();
3014
+ void this.o.api.run(this.o.boxId, tmuxKill(this.o.token), { timeoutMs: 6e4 }).catch(() => void 0).then(() => this.o.gone());
2955
3015
  if (wasRunning) for (const cb of this.exitCbs) cb(-1);
2956
3016
  }
2957
3017
  /** The office is closing: let go of the CLI, which carries on in the Box. */
@@ -3164,22 +3224,25 @@ function parseOpenCodeReadiness(code, output) {
3164
3224
 
3165
3225
  // server/ptyClient.ts
3166
3226
  import crypto2 from "node:crypto";
3167
- import fs7 from "node:fs";
3227
+ import fs8 from "node:fs";
3168
3228
  import net from "node:net";
3169
- import path8 from "node:path";
3229
+ import path9 from "node:path";
3170
3230
  import { spawn } from "node:child_process";
3171
3231
 
3172
3232
  // server/ptyProtocol.ts
3173
3233
  import crypto from "node:crypto";
3174
- import path7 from "node:path";
3234
+ import path8 from "node:path";
3175
3235
  var PTY_PROTOCOL = 1;
3176
3236
  function hostSocket(home, platform = process.platform) {
3177
- if (platform !== "win32") return path7.join(home, "pty.sock");
3178
- const tag = crypto.createHash("sha1").update(path7.resolve(home).toLowerCase()).digest("hex").slice(0, 12);
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);
3179
3239
  return `\\\\.\\pipe\\cubefarm-pty-${tag}`;
3180
3240
  }
3181
3241
  var encode = (m) => `${JSON.stringify(m)}
3182
3242
  `;
3243
+ function ptyExitCode(value) {
3244
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : -1;
3245
+ }
3183
3246
  function readMessages(sock, onMessage2) {
3184
3247
  let buf = "";
3185
3248
  sock.setEncoding("utf8");
@@ -3268,7 +3331,7 @@ function onMessage(m) {
3268
3331
  case "data":
3269
3332
  return remote.get(m.id)?.data(m.data);
3270
3333
  case "exit":
3271
- return remote.get(m.id)?.exit(m.code);
3334
+ return remote.get(m.id)?.exit(ptyExitCode(m.code));
3272
3335
  case "hook":
3273
3336
  void Promise.resolve().then(() => hookHandler(m.token, m.body)).catch(() => ({})).then((answer) => send({ op: "hookReply", rid: m.rid, answer }));
3274
3337
  return;
@@ -3306,7 +3369,7 @@ function connect(socket, secret) {
3306
3369
  }
3307
3370
  var runtimeFlags = () => process.execArgv.filter((a, i, all) => !/^--(inspect|watch|debug)/.test(a) && !/^--(inspect|watch|debug)/.test(all[i - 1] ?? ""));
3308
3371
  function launch(socket, secretFile) {
3309
- const entry = path8.join(import.meta.dirname, `ptyHost${path8.extname(import.meta.filename)}`);
3372
+ const entry = path9.join(import.meta.dirname, `ptyHost${path9.extname(import.meta.filename)}`);
3310
3373
  spawn(process.execPath, [...runtimeFlags(), entry, "launch", socket, secretFile], { detached: true, stdio: "ignore", windowsHide: true }).once("error", () => void 0).unref();
3311
3374
  }
3312
3375
  var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -3314,17 +3377,17 @@ async function startKeeper(home, onHook) {
3314
3377
  hookHandler = onHook;
3315
3378
  if (!nodePty) return [];
3316
3379
  const socket = hostSocket(home);
3317
- const secretFile = path8.join(home, "pty.secret");
3380
+ const secretFile = path9.join(home, "pty.secret");
3318
3381
  try {
3319
- if (!fs7.existsSync(secretFile)) {
3320
- fs7.mkdirSync(home, { recursive: true });
3321
- fs7.writeFileSync(secretFile, crypto2.randomBytes(24).toString("hex"), { mode: 384 });
3382
+ if (!fs8.existsSync(secretFile)) {
3383
+ fs8.mkdirSync(home, { recursive: true });
3384
+ fs8.writeFileSync(secretFile, crypto2.randomBytes(24).toString("hex"), { mode: 384 });
3322
3385
  }
3323
3386
  } catch (err) {
3324
3387
  console.warn(` terminal keeper unavailable: ${err.message}`);
3325
3388
  return [];
3326
3389
  }
3327
- const secret = fs7.readFileSync(secretFile, "utf8").trim();
3390
+ const secret = fs8.readFileSync(secretFile, "utf8").trim();
3328
3391
  let hello = await connect(socket, secret);
3329
3392
  if (hello && hello.ready.version !== PTY_PROTOCOL) {
3330
3393
  console.log(` replacing the terminal keeper (v${hello.ready.version}); the ${hello.ready.ptys.length} terminal(s) it held are stopped`);
@@ -3371,7 +3434,7 @@ function spawnPty(file, args, o, meta) {
3371
3434
  kill: () => killTree(p),
3372
3435
  setMeta: () => void 0,
3373
3436
  onData: (cb) => void p.onData(cb),
3374
- onExit: (cb) => void p.onExit(({ exitCode: exitCode2 }) => cb(exitCode2))
3437
+ onExit: (cb) => void p.onExit(({ exitCode: exitCode2 }) => cb(ptyExitCode(exitCode2)))
3375
3438
  };
3376
3439
  }
3377
3440
  function adoptPty(held) {
@@ -3404,8 +3467,8 @@ function killTree(proc) {
3404
3467
  }
3405
3468
 
3406
3469
  // server/cliRunner.ts
3407
- var SESSIONS_DIR = path9.join(HOME_DIR, "sessions");
3408
- var BIN_DIR = path9.join(HOME_DIR, "bin");
3470
+ var SESSIONS_DIR = path10.join(HOME_DIR, "sessions");
3471
+ var BIN_DIR = path10.join(HOME_DIR, "bin");
3409
3472
  var FINISH_GRACE_MS = 3e3;
3410
3473
  var BOOT_MS = 6e4;
3411
3474
  var USAGE_WARN_PCT = 90;
@@ -3431,14 +3494,14 @@ async function handleMcp(token, req, res) {
3431
3494
  var helpersWritten = false;
3432
3495
  function writeHelpers() {
3433
3496
  if (helpersWritten) return;
3434
- fs8.mkdirSync(BIN_DIR, { recursive: true });
3435
- fs8.writeFileSync(path9.join(BIN_DIR, "statusline.cjs"), STATUSLINE_SOURCE);
3436
- fs8.writeFileSync(path9.join(BIN_DIR, "notify.cjs"), NOTIFY_SOURCE);
3437
- fs8.writeFileSync(path9.join(BIN_DIR, "codex-hook.cjs"), CODEX_HOOK_SOURCE);
3438
- const pluginDir = path9.join(BIN_DIR, "opencode-plugin");
3439
- fs8.mkdirSync(pluginDir, { recursive: true });
3440
- fs8.writeFileSync(path9.join(pluginDir, "index.js"), OPENCODE_PLUGIN_SOURCE);
3441
- fs8.writeFileSync(path9.join(pluginDir, "package.json"), JSON.stringify({ name: "cubefarm-office-plugin", type: "module", exports: "./index.js" }));
3497
+ fs9.mkdirSync(BIN_DIR, { recursive: true });
3498
+ fs9.writeFileSync(path10.join(BIN_DIR, "statusline.cjs"), STATUSLINE_SOURCE);
3499
+ fs9.writeFileSync(path10.join(BIN_DIR, "notify.cjs"), NOTIFY_SOURCE);
3500
+ fs9.writeFileSync(path10.join(BIN_DIR, "codex-hook.cjs"), CODEX_HOOK_SOURCE);
3501
+ const pluginDir = path10.join(BIN_DIR, "opencode-plugin");
3502
+ fs9.mkdirSync(pluginDir, { recursive: true });
3503
+ fs9.writeFileSync(path10.join(pluginDir, "index.js"), OPENCODE_PLUGIN_SOURCE);
3504
+ fs9.writeFileSync(path10.join(pluginDir, "package.json"), JSON.stringify({ name: "droidsembly-office-plugin", type: "module", exports: "./index.js" }));
3442
3505
  helpersWritten = true;
3443
3506
  }
3444
3507
  var shellArg = (p) => `"${p.replaceAll("\\", "/")}"`;
@@ -3491,7 +3554,7 @@ function endLive(live) {
3491
3554
  live.proc = null;
3492
3555
  live.term.note(`\u2500\u2500 ${cliLabel(live.cli)} session ended \u2500\u2500`);
3493
3556
  if (live.box) return gone;
3494
- fs8.rm(live.dir, { recursive: true, force: true, maxRetries: 5 }, () => void 0);
3557
+ fs9.rm(live.dir, { recursive: true, force: true, maxRetries: 5 }, () => void 0);
3495
3558
  if (live.cli === "codex" && live.resumeId) void codexThread("archive", live.resumeId, gone);
3496
3559
  return gone;
3497
3560
  }
@@ -3613,8 +3676,8 @@ function startOpenCodeAuth(o, exited) {
3613
3676
  const cmd = commandFor("opencode");
3614
3677
  if (!cmd) throw new Error("OpenCode is not installed on this computer.");
3615
3678
  const token = crypto3.randomUUID();
3616
- const dir = path9.join(SESSIONS_DIR, token);
3617
- fs8.mkdirSync(dir, { recursive: true });
3679
+ const dir = path10.join(SESSIONS_DIR, token);
3680
+ fs9.mkdirSync(dir, { recursive: true });
3618
3681
  const l = { agentId: o.agentId, cli: "opencode", term: o.term, proc: null, token, dir, resumeId: null, statusLine: "", shots: /* @__PURE__ */ new Set(), session: null };
3619
3682
  let over = false;
3620
3683
  const end = (code) => {
@@ -3701,7 +3764,7 @@ function startCliSession(opts, callbacks) {
3701
3764
  const inBox = !!(box ?? live?.box);
3702
3765
  const token = crypto3.randomUUID();
3703
3766
  const sessionId = opts.resumeSessionId ?? crypto3.randomUUID();
3704
- const dir = box ? boxSessionDir(token) : path9.join(SESSIONS_DIR, token);
3767
+ const dir = box ? boxSessionDir(token) : path10.join(SESSIONS_DIR, token);
3705
3768
  const started = Date.now();
3706
3769
  const statusLine = `\u{1F3E2} Droidsembly${opts.label ? ` \xB7 ${opts.label}` : ""}`;
3707
3770
  const toolNames = /* @__PURE__ */ new Map();
@@ -3728,10 +3791,10 @@ function startCliSession(opts, callbacks) {
3728
3791
  const collectShots = (all = false) => {
3729
3792
  const l2 = live;
3730
3793
  if (!l2 || l2.box || cli === "claude" || !opts.browserTesting) return;
3731
- for (const shot of newScreenshots(path9.join(l2.dir, "browser"), l2.shots, all ? Infinity : Date.now())) {
3794
+ for (const shot of newScreenshots(path10.join(l2.dir, "browser"), l2.shots, all ? Infinity : Date.now())) {
3732
3795
  l2.shots.add(shot.name);
3733
3796
  try {
3734
- cb.screenshot(fs8.readFileSync(shot.file), shot.mime);
3797
+ cb.screenshot(fs9.readFileSync(shot.file), shot.mime);
3735
3798
  } catch {
3736
3799
  }
3737
3800
  }
@@ -3806,7 +3869,7 @@ function startCliSession(opts, callbacks) {
3806
3869
  const m = text3.match(/\]\(([^)\s]+\.(png|jpe?g))\)/i);
3807
3870
  const b = live?.box;
3808
3871
  if (!m || !b) return;
3809
- const file = m[1].startsWith("/") ? m[1] : path9.posix.join(opts.cwd, m[1]);
3872
+ const file = m[1].startsWith("/") ? m[1] : path10.posix.join(opts.cwd, m[1]);
3810
3873
  const data = await b.api.read(b.boxId, file, { base64: true }).catch(() => null);
3811
3874
  if (data) cb.screenshot(Buffer.from(data, "base64"), /png$/i.test(m[2]) ? "image/png" : "image/jpeg");
3812
3875
  };
@@ -3842,7 +3905,7 @@ function startCliSession(opts, callbacks) {
3842
3905
  const event = String(b.hook_event_name ?? "");
3843
3906
  const sub = typeof b.agent_id === "string" && b.agent_id !== "";
3844
3907
  if (cli === "claude" && !sub && b.session_id !== kept) {
3845
- const id = resumableSession(b, inBox ? () => b.transcript_exists === true : fs8.existsSync);
3908
+ const id = resumableSession(b, inBox ? () => b.transcript_exists === true : fs9.existsSync);
3846
3909
  if (id) {
3847
3910
  kept = id;
3848
3911
  cb.sessionId(id);
@@ -4036,8 +4099,8 @@ function startCliSession(opts, callbacks) {
4036
4099
  const keeper = box ? null : keeperHookUrl();
4037
4100
  const events = `${dir}/events.jsonl`;
4038
4101
  const hookUrl = box ? events : `${keeper ?? officeUrl}/api/hooks/${token}`;
4039
- const p = box ? path9.posix : path9;
4040
- 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(path9.join(dir, "browser"));
4102
+ const p = box ? path10.posix : path10;
4103
+ const browser = !opts.browserTesting ? null : box ? box.browser ? { command: `${BOX_CLI_BIN}/playwright-mcp`, args: ["--cdp-endpoint", BOX_CDP, "--output-dir", `${dir}/browser`] } : null : playwrightMcp(path10.join(dir, "browser"));
4041
4104
  const browserIssue = !opts.browserTesting ? null : box ? box.browser ? null : "\u26A0 This cloud machine has no browser, so this session can't test in one." : browserProblem(browser);
4042
4105
  if (browserIssue) log([{ kind: "error", text: browserIssue }]);
4043
4106
  let prompt = opts.prompt;
@@ -4049,16 +4112,16 @@ ${JSON.stringify(opts.outputSchema)}`;
4049
4112
  }
4050
4113
  let files;
4051
4114
  const boxFiles = [];
4052
- const put = (file, text3) => box ? boxFiles.push([file, text3]) : fs8.writeFileSync(file, text3);
4115
+ const put = (file, text3) => box ? boxFiles.push([file, text3]) : fs9.writeFileSync(file, text3);
4053
4116
  try {
4054
4117
  if (!box) {
4055
4118
  writeHelpers();
4056
- fs8.mkdirSync(dir, { recursive: true });
4119
+ fs9.mkdirSync(dir, { recursive: true });
4057
4120
  }
4058
4121
  const boxHook = `node ${BOX_BIN}/hook.cjs ${events}`;
4059
4122
  const settings = {
4060
4123
  hooks: Object.fromEntries(HOOK_EVENTS.map((e) => [e, [{ hooks: [box ? { type: "command", command: boxHook, timeout: 30 } : { type: "http", url: hookUrl, timeout: keeper ? 120 : 30 }] }]])),
4061
- statusLine: box ? { type: "command", command: `node ${BOX_BIN}/statusline.cjs ${events}`, padding: 0 } : { type: "command", command: `${shellArg(process.execPath)} ${shellArg(path9.join(BIN_DIR, "statusline.cjs"))} ${shellArg(hookUrl)}`, padding: 0 },
4124
+ statusLine: box ? { type: "command", command: `node ${BOX_BIN}/statusline.cjs ${events}`, padding: 0 } : { type: "command", command: `${shellArg(process.execPath)} ${shellArg(path10.join(BIN_DIR, "statusline.cjs"))} ${shellArg(hookUrl)}`, padding: 0 },
4062
4125
  ...box?.apiKeyHelper ? { apiKeyHelper: box.apiKeyHelper } : {}
4063
4126
  };
4064
4127
  const servers = {};
@@ -4091,9 +4154,9 @@ ${JSON.stringify(opts.outputSchema)}`;
4091
4154
  openCodePermissions: opts.openCodePermissions,
4092
4155
  additionalDirectories: opts.additionalDirectories,
4093
4156
  files,
4094
- notify: box ? { script: `${BOX_BIN}/notify.cjs`, url: events } : { script: path9.join(BIN_DIR, "notify.cjs"), url: hookUrl },
4095
- codexHook: box ? `${BOX_BIN}/codex-hook.cjs` : path9.join(BIN_DIR, "codex-hook.cjs"),
4096
- plugin: box ? `file://${BOX_BIN}/opencode-plugin` : pathToFileURL(path9.join(BIN_DIR, "opencode-plugin")).href,
4157
+ notify: box ? { script: `${BOX_BIN}/notify.cjs`, url: events } : { script: path10.join(BIN_DIR, "notify.cjs"), url: hookUrl },
4158
+ codexHook: box ? `${BOX_BIN}/codex-hook.cjs` : path10.join(BIN_DIR, "codex-hook.cjs"),
4159
+ plugin: box ? `file://${BOX_BIN}/opencode-plugin` : pathToFileURL(path10.join(BIN_DIR, "opencode-plugin")).href,
4097
4160
  ...opts.office && !box ? { officeUrl: `${officeUrl}/api/mcp/${token}` } : {},
4098
4161
  browser,
4099
4162
  ...box ? { node: "node", posix: true } : {}
@@ -4189,30 +4252,30 @@ ${JSON.stringify(opts.outputSchema)}`;
4189
4252
  }
4190
4253
 
4191
4254
  // server/machines.ts
4192
- import fs10 from "node:fs";
4255
+ import fs11 from "node:fs";
4193
4256
 
4194
4257
  // server/deps.ts
4195
4258
  import { spawn as spawn2 } from "node:child_process";
4196
4259
  import crypto4 from "node:crypto";
4197
- import fs9 from "node:fs/promises";
4198
- import path10 from "node:path";
4260
+ import fs10 from "node:fs/promises";
4261
+ import path11 from "node:path";
4199
4262
  var INSTALL_MARKER = ".cubefarm-preview-install";
4200
4263
  var INSTALL_TIMEOUT_MS = 15 * 6e4;
4201
4264
  var INSTALL_PROGRESS_MS = 6e4;
4202
4265
  var MAX_DESK_INSTALLS = 2;
4203
4266
  var depsHash = (pkg, lock) => crypto4.createHash("sha256").update(pkg).update("\0").update(lock ?? "").digest("hex");
4204
4267
  async function readDeps(dir) {
4205
- const read = (file) => fs9.readFile(path10.join(dir, file), "utf8").catch(() => null);
4268
+ const read = (file) => fs10.readFile(path11.join(dir, file), "utf8").catch(() => null);
4206
4269
  const [pkg, lock, marker2, nodeModules] = await Promise.all([
4207
4270
  read("package.json"),
4208
4271
  read("package-lock.json"),
4209
- read(path10.join("node_modules", INSTALL_MARKER)),
4210
- fs9.stat(path10.join(dir, "node_modules")).then((s2) => s2.isDirectory()).catch(() => false)
4272
+ read(path11.join("node_modules", INSTALL_MARKER)),
4273
+ fs10.stat(path11.join(dir, "node_modules")).then((s2) => s2.isDirectory()).catch(() => false)
4211
4274
  ]);
4212
4275
  return { pkg, lock, hash: depsHash(pkg ?? "", lock), marker: marker2 ?? "", nodeModules };
4213
4276
  }
4214
4277
  var depsCurrent = (s2) => s2.nodeModules && s2.marker === s2.hash;
4215
- var writeMarker = (dir, hash) => fs9.writeFile(path10.join(dir, "node_modules", INSTALL_MARKER), hash).catch(() => void 0);
4278
+ var writeMarker = (dir, hash) => fs10.writeFile(path11.join(dir, "node_modules", INSTALL_MARKER), hash).catch(() => void 0);
4216
4279
  function deskDepsPlan(s2) {
4217
4280
  if (s2.pkg === null) return "none";
4218
4281
  if (s2.lock === null) return "agent";
@@ -4327,7 +4390,7 @@ function localMachines(keep) {
4327
4390
  prepareDesk: (machine, fullName, base, branch, note2) => prepareMachineDesk(machine, fullName, base, branch, note2),
4328
4391
  env: (machine) => {
4329
4392
  const tmp = machineTmp(machine);
4330
- fs10.mkdirSync(tmp, { recursive: true });
4393
+ fs11.mkdirSync(tmp, { recursive: true });
4331
4394
  return { TMP: tmp, TEMP: tmp, TMPDIR: tmp };
4332
4395
  },
4333
4396
  release: (machine, fullName, port) => releaseMachine(machine, fullName, port, keep()),
@@ -4335,7 +4398,7 @@ function localMachines(keep) {
4335
4398
  sweep: (machine, fullName, keepBranches) => sweepMachine(machine, fullName, keepBranches),
4336
4399
  remove: (machine) => removeMachine(machine),
4337
4400
  list: () => listMachines(),
4338
- exists: async (machine, fullName) => fs10.existsSync(machineDesk(machine, fullName)),
4401
+ exists: async (machine, fullName) => fs11.existsSync(machineDesk(machine, fullName)),
4339
4402
  installDeps: (machine, fullName, cb) => installDesk(machineDesk(machine, fullName), cb)
4340
4403
  };
4341
4404
  }
@@ -4455,9 +4518,9 @@ async function openCodeConnections(directory) {
4455
4518
 
4456
4519
  // server/previewRunner.ts
4457
4520
  import { spawn as spawn3 } from "node:child_process";
4458
- import fs11 from "node:fs/promises";
4521
+ import fs12 from "node:fs/promises";
4459
4522
  import net2 from "node:net";
4460
- import path11 from "node:path";
4523
+ import path12 from "node:path";
4461
4524
  var PREVIEW_SLUG = "preview";
4462
4525
  var PREVIEW_BRANCH = "swarm-preview";
4463
4526
  var PREVIEW_TMP = ".preview-tmp";
@@ -4491,7 +4554,7 @@ async function portOpen(port) {
4491
4554
  var sleep3 = (ms) => new Promise((r) => setTimeout(r, ms));
4492
4555
  async function readJson(file) {
4493
4556
  try {
4494
- return JSON.parse(await fs11.readFile(file, "utf8"));
4557
+ return JSON.parse(await fs12.readFile(file, "utf8"));
4495
4558
  } catch {
4496
4559
  return null;
4497
4560
  }
@@ -4536,9 +4599,9 @@ var RealPreview = class {
4536
4599
  this.check();
4537
4600
  await ensureLocalExcludes(job.fullName).catch(() => void 0);
4538
4601
  cb.commit(await git(["rev-parse", "--short", "HEAD"], { cwd: wt }).catch(() => ""));
4539
- const tmp = path11.join(wt, PREVIEW_TMP);
4540
- await fs11.mkdir(tmp, { recursive: true });
4541
- const pkg = await readJson(path11.join(wt, "package.json"));
4602
+ const tmp = path12.join(wt, PREVIEW_TMP);
4603
+ await fs12.mkdir(tmp, { recursive: true });
4604
+ const pkg = await readJson(path12.join(wt, "package.json"));
4542
4605
  const command = job.command ?? defaultCommand(pkg);
4543
4606
  if (!command) {
4544
4607
  this.stopped = true;
@@ -4623,16 +4686,16 @@ var RealPreview = class {
4623
4686
  };
4624
4687
  var realPreviews = {
4625
4688
  start: (job, cb) => new RealPreview(job, cb),
4626
- hasDefault: async (fullName) => fs11.access(path11.join(mainDir(fullName), "package.json")).then(() => true).catch(() => false)
4689
+ hasDefault: async (fullName) => fs12.access(path12.join(mainDir(fullName), "package.json")).then(() => true).catch(() => false)
4627
4690
  };
4628
4691
 
4629
4692
  // server/officeUpdate.ts
4630
- import fs12 from "node:fs/promises";
4631
- import path12 from "node:path";
4693
+ import fs13 from "node:fs/promises";
4694
+ import path13 from "node:path";
4632
4695
  var DRAIN_TIMEOUT_MS = 20 * 6e4;
4633
4696
  var POSTPONE_MS = 2 * 60 * 6e4;
4634
4697
  function underLauncher(proc = process) {
4635
- return typeof proc.send === "function" && proc.env.SWARM_LAUNCHER === "1";
4698
+ return typeof proc.send === "function" && officeEnv(proc.env, "SWARM_LAUNCHER") === "1";
4636
4699
  }
4637
4700
  function drainDecision(s2) {
4638
4701
  const idle2 = (state2) => ({ state: state2, drainingSince: null, send: false, timedOut: false });
@@ -4665,10 +4728,10 @@ function parseLastUpdate(raw) {
4665
4728
  }
4666
4729
  }
4667
4730
  async function takeLastUpdate(home) {
4668
- const file = path12.join(home, "last-update.json");
4669
- const raw = await fs12.readFile(file, "utf8").catch(() => null);
4731
+ const file = path13.join(home, "last-update.json");
4732
+ const raw = await fs13.readFile(file, "utf8").catch(() => null);
4670
4733
  if (raw === null) return null;
4671
- await fs12.rm(file, { force: true, maxRetries: 3 }).catch(() => void 0);
4734
+ await fs13.rm(file, { force: true, maxRetries: 3 }).catch(() => void 0);
4672
4735
  return parseLastUpdate(raw);
4673
4736
  }
4674
4737
  function lastUpdateMessage(u, commits) {
@@ -4676,8 +4739,8 @@ function lastUpdateMessage(u, commits) {
4676
4739
  const n = commits === null ? "" : ` (${commits} commit${commits === 1 ? "" : "s"})`;
4677
4740
  return `\u2B06\uFE0F Updated the office from ${u.from.slice(0, 7)} to ${u.to.slice(0, 7)}${n}`;
4678
4741
  }
4679
- var OFFICE_DIR = path12.resolve(import.meta.dirname, "..");
4680
- var isSamePath = (a, b) => process.platform === "win32" ? path12.resolve(a).toLowerCase() === path12.resolve(b).toLowerCase() : path12.resolve(a) === path12.resolve(b);
4742
+ var OFFICE_DIR = path13.resolve(import.meta.dirname, "..");
4743
+ var isSamePath = (a, b) => process.platform === "win32" ? path13.resolve(a).toLowerCase() === path13.resolve(b).toLowerCase() : path13.resolve(a) === path13.resolve(b);
4681
4744
  var realOffice = {
4682
4745
  launcher: underLauncher(),
4683
4746
  head: () => git(["rev-parse", "HEAD"], { cwd: OFFICE_DIR }).catch(() => null),
@@ -4693,8 +4756,8 @@ var realOffice = {
4693
4756
 
4694
4757
  // server/voice.ts
4695
4758
  import crypto5 from "node:crypto";
4696
- import fs13 from "node:fs/promises";
4697
- import path13 from "node:path";
4759
+ import fs14 from "node:fs/promises";
4760
+ import path14 from "node:path";
4698
4761
 
4699
4762
  // shared/italianUi.ts
4700
4763
  var italianUi = {
@@ -5173,6 +5236,23 @@ var italianUi = {
5173
5236
  "It\u2019s deleted from the office. Cloud agents that need it can\u2019t sign in until you add it again.": "Viene eliminato dall\u2019ufficio. Gli agenti cloud che ne hanno bisogno non potranno accedere finch\xE9 non lo aggiungerai di nuovo.",
5174
5237
  "Not set up yet": "Non ancora configurato",
5175
5238
  "\u2713 Connected": "\u2713 Connesso",
5239
+ "First cloud task: four checks": "Primo incarico cloud: quattro controlli",
5240
+ "Save and test the Upstash key, then confirm GitHub access to the intended repositories.": "Salva e verifica la chiave Upstash, poi conferma l\u2019accesso GitHub ai repository previsti.",
5241
+ "Choose a cloud agent, coding agent and model in Setup before signing in.": "Scegli agente cloud, strumento di sviluppo e modello in Configurazione prima dell\u2019accesso.",
5242
+ "Use Sign in on the agent card and finish the official provider login in that Box terminal. Never copy a PC login file.": "Usa Accedi sulla scheda dell\u2019agente e completa il login ufficiale nel terminale della Box. Non copiare file di accesso dal PC.",
5243
+ "Check model access and provider quota, then assign one task. A ready Box or saved account is not proof of available AI quota.": "Verifica accesso al modello e quota del provider, poi assegna un incarico. Una Box pronta o un account salvato non dimostrano disponibilit\xE0 di quota AI.",
5244
+ "Cloud work and spending awareness": "Lavoro cloud e consapevolezza dei consumi",
5245
+ "Pause new cloud work": "Sospendi nuovi lavori cloud",
5246
+ "Resume": "Riprendi",
5247
+ "New cloud work is paused. Local work and the CEO are unaffected.": "I nuovi lavori cloud sono sospesi. Lavoro locale e CEO restano attivi.",
5248
+ "Resume new cloud work?": "Riprendere i nuovi lavori cloud?",
5249
+ "Queued cloud issues, QA and fixes may start and consume provider quota and Box resources.": "Issue, QA e correzioni cloud in coda potranno partire, consumando quota del provider e risorse Box.",
5250
+ "This blocks new cloud assignments and new AI launches, not sessions already running, manual sign-in or Box storage charges. Stop or remove resources explicitly when you are finished.": "Blocca nuove assegnazioni cloud e nuovi avvii AI, non sessioni gi\xE0 attive, login manuali o costi di archiviazione Box. Al termine arresta o elimina esplicitamente le risorse.",
5251
+ "Reference CPU rates are not an invoice or a spending cap. Actual Box CPU time, storage and AI charges are not reported here; check provider dashboards. Unknown usage is not zero.": "Le tariffe CPU indicative non sono una fattura n\xE9 un tetto di spesa. Tempo CPU, archiviazione Box e costi AI effettivi non sono riportati qui: consulta le dashboard dei provider. Un consumo ignoto non equivale a zero.",
5252
+ "A ready Box describes its machine, not provider authentication or quota. Finish Sign in in this agent\u2019s terminal and check its model before assigning work.": "Una Box pronta descrive la macchina, non l\u2019autenticazione o la quota del provider. Completa Accedi nel terminale dell\u2019agente e verifica il modello prima di assegnare lavoro.",
5253
+ "{deleted} removals confirmed; {unconfirmed} not confirmed. Check the Upstash console; resources may still be billed.": "{deleted} eliminazioni confermate; {unconfirmed} non confermate. Controlla la console Upstash: le risorse potrebbero essere ancora fatturate.",
5254
+ "\u2713 {count} Box removals confirmed": "\u2713 {count} eliminazioni Box confermate",
5255
+ "Paused Boxes can still incur storage charges. Check current plan limits and prices in Upstash; the office\u2019s Box limit is not a billing cap. Setup and what keeps going while the office is closed:": "Le Box in pausa possono ancora generare costi di archiviazione. Verifica limiti e prezzi attuali su Upstash: il limite Box dell\u2019ufficio non \xE8 un tetto di spesa. Configurazione e attivit\xE0 a ufficio chiuso:",
5176
5256
  "{total} Boxes on your account \xB7 this office: {running} running, {paused} paused": "{total} Box nel tuo account \xB7 questo ufficio: {running} attivi, {paused} in pausa",
5177
5257
  "Boxes not counted yet.": "Box non ancora conteggiati.",
5178
5258
  "Delete {count} orphaned Boxes?": "Eliminare {count} Box senza agente?",
@@ -5534,6 +5614,11 @@ var italianUi = {
5534
5614
  "Study the repo again and rethink the plan and the team\u2019s size": "Studia di nuovo il repository e rivedi il piano e le dimensioni del team",
5535
5615
  "Brief: what should this floor build next? The CEO turns it into issues and a team size.": "Obiettivo: che cosa deve sviluppare questo piano? Il CEO lo traduce in issue e dimensioni del team.",
5536
5616
  " (none yet)": " (non ancora disponibile)",
5617
+ "QA brief \u2014 not filled in yet": "Indicazioni QA \u2014 non ancora compilate",
5618
+ "Your Claude subscription (DROIDSEMBLY_CLAUDE_TOKEN)": "Il tuo abbonamento Claude (DROIDSEMBLY_CLAUDE_TOKEN)",
5619
+ "CUBEFARM_CLAUDE_TOKEN is still supported. DROIDSEMBLY_CLAUDE_TOKEN takes precedence when both are set.": "CUBEFARM_CLAUDE_TOKEN \xE8 ancora supportata. DROIDSEMBLY_CLAUDE_TOKEN ha la precedenza quando sono impostate entrambe.",
5620
+ "OpenCode is the coding agent validated in manual testing for this version. Claude Code and Codex are available but have not yet been tested to the same extent.": "OpenCode \xE8 lo strumento collaudato nei test manuali di questa versione. Claude Code e Codex sono disponibili, ma non ancora verificati allo stesso livello.",
5621
+ "Follow the instructions in their terminal for the selected provider and sign-in method. If a link is shown, open it and use the account for that provider; enter or paste a code only where instructed.": "Segui le istruzioni nel terminale per il provider e il metodo di accesso selezionati. Se compare un link, aprilo e usa l\u2019account di quel provider; inserisci o incolla un codice solo dove indicato.",
5537
5622
  "What every QA pass must check on this project.": "Che cosa deve verificare ogni controllo QA di questo progetto.",
5538
5623
  "Model: provider/model, or provider/model#variant for reasoning. Empty uses the OpenCode default.": "Modello: provider/model, oppure provider/model#variant per il ragionamento. Lascia vuoto per il valore predefinito di OpenCode.",
5539
5624
  "Up next:": "In coda:",
@@ -6955,7 +7040,7 @@ var Voice = class {
6955
7040
  const s2 = await this.readSecrets();
6956
7041
  this.key = typeof s2.elevenlabsKey === "string" ? s2.elevenlabsKey : "";
6957
7042
  this.rejected = !!this.key && s2.elevenlabsKeyRejected === true;
6958
- const raw = await fs13.readFile(this.manifestFile(), "utf8").catch(() => "");
7043
+ const raw = await fs14.readFile(this.manifestFile(), "utf8").catch(() => "");
6959
7044
  try {
6960
7045
  this.clips = parseManifest(raw ? JSON.parse(raw) : {});
6961
7046
  } catch {
@@ -7020,7 +7105,7 @@ var Voice = class {
7020
7105
  const m = this.message(id);
7021
7106
  if (!m || !speaks(m, s2)) throw new HttpError(404, `No spoken message ${id}`);
7022
7107
  const saved = clipsFor(this.clips, m);
7023
- const first = saved && await fs13.readFile(path13.join(this.deps.cacheDir, saved[0])).catch(() => null);
7108
+ const first = saved && await fs14.readFile(path14.join(this.deps.cacheDir, saved[0])).catch(() => null);
7024
7109
  if (first) return first;
7025
7110
  const text3 = speechText(m.text);
7026
7111
  if (!text3) throw new HttpError(404, `Message ${id} has nothing to say aloud`);
@@ -7034,15 +7119,15 @@ var Voice = class {
7034
7119
  const m = this.message(id);
7035
7120
  const files = m && clipsFor(this.clips, m);
7036
7121
  const file = files?.[part];
7037
- const audio = file && await fs13.readFile(path13.join(this.deps.cacheDir, file)).catch(() => null);
7122
+ const audio = file && await fs14.readFile(path14.join(this.deps.cacheDir, file)).catch(() => null);
7038
7123
  if (!files || !audio) throw new HttpError(404, `Audio for message ${id} is no longer saved.`);
7039
7124
  return { audio, parts: files.length };
7040
7125
  }
7041
7126
  /** DELETE /api/voice/cache: Settings → Voice's "Clear saved clips". */
7042
7127
  clearCache() {
7043
7128
  return this.cacheOp(async () => {
7044
- const names = await fs13.readdir(this.deps.cacheDir).catch(() => []);
7045
- for (const name of names.filter((n) => n.endsWith(".mp3"))) await fs13.rm(path13.join(this.deps.cacheDir, name), { force: true, maxRetries: 3 });
7129
+ const names = await fs14.readdir(this.deps.cacheDir).catch(() => []);
7130
+ for (const name of names.filter((n) => n.endsWith(".mp3"))) await fs14.rm(path14.join(this.deps.cacheDir, name), { force: true, maxRetries: 3 });
7046
7131
  this.clips = {};
7047
7132
  await this.saveManifest();
7048
7133
  return this.measure([]);
@@ -7055,12 +7140,12 @@ var Voice = class {
7055
7140
  prune() {
7056
7141
  return this.cacheOp(async () => {
7057
7142
  const dir = this.deps.cacheDir;
7058
- const names = (await fs13.readdir(dir).catch(() => [])).filter((n) => n.endsWith(".mp3"));
7059
- const stats = await Promise.all(names.map(async (name) => ({ name, st: await fs13.stat(path13.join(dir, name)).catch(() => null) })));
7143
+ const names = (await fs14.readdir(dir).catch(() => [])).filter((n) => n.endsWith(".mp3"));
7144
+ const stats = await Promise.all(names.map(async (name) => ({ name, st: await fs14.stat(path14.join(dir, name)).catch(() => null) })));
7060
7145
  const files = stats.flatMap(({ name, st }) => st ? [{ name, mtimeMs: st.mtimeMs, size: st.size }] : []);
7061
7146
  const keep = newestClips(this.clips, this.deps.messages());
7062
7147
  const gone = new Set(cacheToPrune(files, this.now(), CACHE_MAX_FILES, this.deps.settings().keepDays * DAY_MS, keep));
7063
- for (const name of [...gone]) await fs13.rm(path13.join(dir, name), { force: true, maxRetries: 3 }).catch(() => gone.delete(name));
7148
+ for (const name of [...gone]) await fs14.rm(path14.join(dir, name), { force: true, maxRetries: 3 }).catch(() => gone.delete(name));
7064
7149
  const left = files.filter((f) => !gone.has(f.name));
7065
7150
  const clips = withoutMissing(this.clips, new Set(left.map((f) => f.name)));
7066
7151
  if (Object.keys(clips).length !== Object.keys(this.clips).length) {
@@ -7106,10 +7191,10 @@ var Voice = class {
7106
7191
  const hash = crypto5.createHash("sha256").update(`${voiceId}
7107
7192
  ${model2}
7108
7193
  ${text3}${language === "it" ? "\nit" : ""}`).digest("hex").slice(0, 12);
7109
- const file = path13.join(this.deps.cacheDir, `${name}-${hash}.mp3`);
7110
- const cached = await fs13.readFile(file).catch(() => null);
7194
+ const file = path14.join(this.deps.cacheDir, `${name}-${hash}.mp3`);
7195
+ const cached = await fs14.readFile(file).catch(() => null);
7111
7196
  if (cached) {
7112
- if (m) await this.record(m, [path13.basename(file)]);
7197
+ if (m) await this.record(m, [path14.basename(file)]);
7113
7198
  return cached;
7114
7199
  }
7115
7200
  this.requireKey();
@@ -7128,12 +7213,12 @@ ${text3}${language === "it" ? "\nit" : ""}`).digest("hex").slice(0, 12);
7128
7213
  this.requireKey();
7129
7214
  const key = this.key;
7130
7215
  const audio = await this.deps.api.synthesize(key, req, AbortSignal.timeout(SYNTH_TIMEOUT_MS)).catch((err) => this.failed(err, key, "speak the message"));
7131
- await fs13.mkdir(this.deps.cacheDir, { recursive: true });
7216
+ await fs14.mkdir(this.deps.cacheDir, { recursive: true });
7132
7217
  const tmp = `${file}.${process.pid}.tmp`;
7133
- await fs13.writeFile(tmp, audio);
7134
- await fs13.rename(tmp, file);
7135
- this.deps.log?.(`voice: made a new clip ${path13.basename(file)} (${req.text.length} characters)`);
7136
- if (m) await this.record(m, [path13.basename(file)]);
7218
+ await fs14.writeFile(tmp, audio);
7219
+ await fs14.rename(tmp, file);
7220
+ this.deps.log?.(`voice: made a new clip ${path14.basename(file)} (${req.text.length} characters)`);
7221
+ if (m) await this.record(m, [path14.basename(file)]);
7137
7222
  else await this.prune();
7138
7223
  return audio;
7139
7224
  }
@@ -7169,13 +7254,13 @@ ${text3}${language === "it" ? "\nit" : ""}`).digest("hex").slice(0, 12);
7169
7254
  await this.prune();
7170
7255
  }
7171
7256
  manifestFile() {
7172
- return path13.join(this.deps.cacheDir, MANIFEST);
7257
+ return path14.join(this.deps.cacheDir, MANIFEST);
7173
7258
  }
7174
7259
  async saveManifest() {
7175
- await fs13.mkdir(this.deps.cacheDir, { recursive: true });
7260
+ await fs14.mkdir(this.deps.cacheDir, { recursive: true });
7176
7261
  const tmp = `${this.manifestFile()}.${process.pid}.tmp`;
7177
- await fs13.writeFile(tmp, JSON.stringify(this.clips));
7178
- await fs13.rename(tmp, this.manifestFile());
7262
+ await fs14.writeFile(tmp, JSON.stringify(this.clips));
7263
+ await fs14.rename(tmp, this.manifestFile());
7179
7264
  }
7180
7265
  /** The cache view for `files` (what's on disk), told to the clients when it changed. */
7181
7266
  measure(files) {
@@ -7279,8 +7364,11 @@ var elevenLabs = {
7279
7364
  };
7280
7365
 
7281
7366
  // server/notifier.ts
7282
- import fs14 from "node:fs/promises";
7283
- import path14 from "node:path";
7367
+ import fs15 from "node:fs/promises";
7368
+ import path15 from "node:path";
7369
+
7370
+ // shared/browserProtocol.ts
7371
+ var notificationTag = (id) => `cubefarm-${id}`;
7284
7372
 
7285
7373
  // shared/notify.ts
7286
7374
  var NOTIFY_EVENTS = [
@@ -7572,7 +7660,7 @@ var Notifier = class {
7572
7660
  }
7573
7661
  }
7574
7662
  try {
7575
- const raw = JSON.parse(await fs14.readFile(this.deps.pushFile, "utf8"));
7663
+ const raw = JSON.parse(await fs15.readFile(this.deps.pushFile, "utf8"));
7576
7664
  const devices = Array.isArray(raw.devices) ? raw.devices : [];
7577
7665
  this.push = {
7578
7666
  vapid: checkVapidKeys(raw.vapid),
@@ -7679,7 +7767,7 @@ var Notifier = class {
7679
7767
  const sends = [];
7680
7768
  for (const c of NOTIFY_WEBHOOKS) if (on(c) && this.webhooks[c]) sends.push(this.send(this.webhookRequest(c, n, s2.officeUrl)));
7681
7769
  if (on("push") && this.push.vapid) {
7682
- const payload = JSON.stringify({ title: view.title, body: view.body, tag: `cubefarm-${view.id}`, url: view.url });
7770
+ const payload = JSON.stringify({ title: view.title, body: view.body, tag: notificationTag(view.id), url: view.url });
7683
7771
  for (const d of [...this.push.devices]) sends.push(this.sendPush(d, payload, noteText(n)));
7684
7772
  }
7685
7773
  return Promise.all(sends);
@@ -7717,10 +7805,10 @@ var Notifier = class {
7717
7805
  const file = this.deps.pushFile;
7718
7806
  const data = JSON.stringify({ vapid: this.push.vapid, devices: this.push.devices }, null, 2);
7719
7807
  const write = this.pushWrites.then(async () => {
7720
- await fs14.mkdir(path14.dirname(file), { recursive: true });
7721
- await fs14.writeFile(`${file}.tmp`, data, { mode: 384 });
7722
- await fs14.rename(`${file}.tmp`, file);
7723
- await fs14.chmod(file, 384).catch(() => void 0);
7808
+ await fs15.mkdir(path15.dirname(file), { recursive: true });
7809
+ await fs15.writeFile(`${file}.tmp`, data, { mode: 384 });
7810
+ await fs15.rename(`${file}.tmp`, file);
7811
+ await fs15.chmod(file, 384).catch(() => void 0);
7724
7812
  });
7725
7813
  this.pushWrites = write.catch(() => void 0);
7726
7814
  return write;
@@ -7745,8 +7833,8 @@ function loadWebhooks(raw) {
7745
7833
  }
7746
7834
 
7747
7835
  // server/weather.ts
7748
- import fs15 from "node:fs/promises";
7749
- import path15 from "node:path";
7836
+ import fs16 from "node:fs/promises";
7837
+ import path16 from "node:path";
7750
7838
 
7751
7839
  // shared/outside.ts
7752
7840
  var WEATHER_KINDS = ["clear", "cloudy", "light-rain", "heavy-rain", "storm", "fog", "snow"];
@@ -7892,7 +7980,7 @@ var WeatherService = class {
7892
7980
  now = () => this.o.now?.() ?? Date.now();
7893
7981
  async init() {
7894
7982
  try {
7895
- const cached = parseCache(JSON.parse(await fs15.readFile(this.o.file, "utf8")));
7983
+ const cached = parseCache(JSON.parse(await fs16.readFile(this.o.file, "utf8")));
7896
7984
  this.city = cached.city;
7897
7985
  this.view = { place: cached.place, reading: cached.reading, error: null };
7898
7986
  } catch {
@@ -7971,9 +8059,9 @@ var WeatherService = class {
7971
8059
  async save() {
7972
8060
  const tmp = `${this.o.file}.tmp`;
7973
8061
  try {
7974
- await fs15.mkdir(path15.dirname(this.o.file), { recursive: true });
7975
- await fs15.writeFile(tmp, JSON.stringify({ city: this.city, place: this.view.place, reading: this.view.reading }, null, 2));
7976
- await fs15.rename(tmp, this.o.file);
8062
+ await fs16.mkdir(path16.dirname(this.o.file), { recursive: true });
8063
+ await fs16.writeFile(tmp, JSON.stringify({ city: this.city, place: this.view.place, reading: this.view.reading }, null, 2));
8064
+ await fs16.rename(tmp, this.o.file);
7977
8065
  } catch (err) {
7978
8066
  this.o.log(`weather: couldn't save the cache: ${err.message}`);
7979
8067
  }
@@ -8051,9 +8139,9 @@ var realBackend = {
8051
8139
 
8052
8140
  // server/demo.ts
8053
8141
  import crypto7 from "node:crypto";
8054
- import fs16 from "node:fs";
8142
+ import fs17 from "node:fs";
8055
8143
  import http from "node:http";
8056
- import path16 from "node:path";
8144
+ import path17 from "node:path";
8057
8145
 
8058
8146
  // shared/ops.ts
8059
8147
  var needsManager = (q) => q?.status === "needs-human" && !q.ceoLooking;
@@ -8245,10 +8333,10 @@ var closedIssues = /* @__PURE__ */ new Set();
8245
8333
  var stalls = /* @__PURE__ */ new Map();
8246
8334
  var signOuts = /* @__PURE__ */ new Map();
8247
8335
  var fakeSha = () => crypto7.randomBytes(20).toString("hex");
8248
- var NUMBERS_FILE = path16.join(HOME_DIR, "demo-github.json");
8336
+ var NUMBERS_FILE = path17.join(HOME_DIR, "demo-github.json");
8249
8337
  function restoreNumbers() {
8250
8338
  try {
8251
- const saved = JSON.parse(fs16.readFileSync(NUMBERS_FILE, "utf8"));
8339
+ const saved = JSON.parse(fs17.readFileSync(NUMBERS_FILE, "utf8"));
8252
8340
  for (const r of repos.values()) if (Number.isInteger(saved[r.fullName])) r.nextNumber = Math.max(r.nextNumber, saved[r.fullName]);
8253
8341
  } catch {
8254
8342
  }
@@ -8256,9 +8344,9 @@ function restoreNumbers() {
8256
8344
  function takeNumber(r) {
8257
8345
  const n = r.nextNumber++;
8258
8346
  try {
8259
- fs16.mkdirSync(HOME_DIR, { recursive: true });
8260
- fs16.writeFileSync(`${NUMBERS_FILE}.tmp`, JSON.stringify(Object.fromEntries([...repos.values()].map((x) => [x.fullName, x.nextNumber]))));
8261
- fs16.renameSync(`${NUMBERS_FILE}.tmp`, NUMBERS_FILE);
8347
+ fs17.mkdirSync(HOME_DIR, { recursive: true });
8348
+ fs17.writeFileSync(`${NUMBERS_FILE}.tmp`, JSON.stringify(Object.fromEntries([...repos.values()].map((x) => [x.fullName, x.nextNumber]))));
8349
+ fs17.renameSync(`${NUMBERS_FILE}.tmp`, NUMBERS_FILE);
8262
8350
  } catch (err) {
8263
8351
  console.warn("could not save the demo PR numbers", err);
8264
8352
  }
@@ -8381,7 +8469,7 @@ function screenshotSvg(title, url, hue) {
8381
8469
  </svg>`;
8382
8470
  }
8383
8471
  function issueScript(opts, cb, issueNumber, issueTitle) {
8384
- const branch = path16.basename(opts.cwd);
8472
+ const branch = path17.basename(opts.cwd);
8385
8473
  const hue = issueNumber * 67 % 360;
8386
8474
  const file = ["src/App.tsx", "src/components/TodoList.tsx", "src/api/routes.ts", "src/styles.css"][issueNumber % 4];
8387
8475
  const port = 5200 + issueNumber % 50;
@@ -8581,7 +8669,7 @@ function fakeSession(opts, cb, fullName) {
8581
8669
  number: n,
8582
8670
  title,
8583
8671
  url,
8584
- headRefName: `swarm/issue-${number}-${path16.basename(opts.cwd).replace(/-[0-9a-f]{4}$/, "")}`,
8672
+ headRefName: `swarm/issue-${number}-${path17.basename(opts.cwd).replace(/-[0-9a-f]{4}$/, "")}`,
8585
8673
  state: "OPEN",
8586
8674
  isDraft: false,
8587
8675
  mergeable: "MERGEABLE",
@@ -9046,7 +9134,7 @@ var OFFICE_REPO = "demo-co/pixel-todo";
9046
9134
  var DEMO_HEAD = `0ff1ce5${"0".repeat(33)}`;
9047
9135
  var lastFakeUpdate = { to: "", commits: 0 };
9048
9136
  var demoOffice = {
9049
- launcher: underLauncher() || process.env.SWARM_DEMO_LAUNCHER === "1",
9137
+ launcher: underLauncher() || officeEnv(process.env, "SWARM_DEMO_LAUNCHER") === "1",
9050
9138
  head: async () => DEMO_HEAD,
9051
9139
  isOwnFolder: (dir) => dir === `/demo/${OFFICE_REPO}/main`,
9052
9140
  // Only its own fake updates have a count; one the real launcher did (u) gets no count rather than a wrong one.
@@ -9657,8 +9745,8 @@ function demoSignIn(o, logins, exited) {
9657
9745
  }
9658
9746
 
9659
9747
  // server/journal.ts
9660
- import fs17 from "node:fs/promises";
9661
- import path17 from "node:path";
9748
+ import fs18 from "node:fs/promises";
9749
+ import path18 from "node:path";
9662
9750
 
9663
9751
  // shared/journal.ts
9664
9752
  var KEYFRAME_MS = 10 * 6e4;
@@ -10155,12 +10243,12 @@ function parseRange(q, now2) {
10155
10243
  return { from, to, seek: q.seek === "1" || q.seek === "true" };
10156
10244
  }
10157
10245
  async function writeAtomic(file, data) {
10158
- await fs17.mkdir(path17.dirname(file), { recursive: true });
10246
+ await fs18.mkdir(path18.dirname(file), { recursive: true });
10159
10247
  const tmp = `${file}.tmp`;
10160
- await fs17.writeFile(tmp, data);
10248
+ await fs18.writeFile(tmp, data);
10161
10249
  for (let i = 0; ; i++) {
10162
10250
  try {
10163
- await fs17.rename(tmp, file);
10251
+ await fs18.rename(tmp, file);
10164
10252
  return;
10165
10253
  } catch (err) {
10166
10254
  const code = err.code;
@@ -10262,7 +10350,7 @@ var Journal = class {
10262
10350
  const start = prev && at <= prev.start ? prev.start + 1 : at;
10263
10351
  const day = dayKey(start);
10264
10352
  const frame = this.opts.frame();
10265
- const seg = { day, start, file: path17.join(this.opts.dir, day, `${start}.ndjson`), lines: [], bytes: 0, events: 0, dirty: false };
10353
+ const seg = { day, start, file: path18.join(this.opts.dir, day, `${start}.ndjson`), lines: [], bytes: 0, events: 0, dirty: false };
10266
10354
  this.push(seg, boot ? { t: start, k: frame, boot: true } : { t: start, k: frame });
10267
10355
  this.last = frameKeys(frame);
10268
10356
  this.cur = seg;
@@ -10281,24 +10369,24 @@ var Journal = class {
10281
10369
  const tmp = [];
10282
10370
  let days = [];
10283
10371
  try {
10284
- days = (await fs17.readdir(this.opts.dir)).filter((d) => DAY_DIR.test(d));
10372
+ days = (await fs18.readdir(this.opts.dir)).filter((d) => DAY_DIR.test(d));
10285
10373
  } catch {
10286
10374
  return { segments, tmp, days };
10287
10375
  }
10288
10376
  for (const day of days) {
10289
- const dir = path17.join(this.opts.dir, day);
10377
+ const dir = path18.join(this.opts.dir, day);
10290
10378
  let names = [];
10291
10379
  try {
10292
- names = await fs17.readdir(dir);
10380
+ names = await fs18.readdir(dir);
10293
10381
  } catch {
10294
10382
  continue;
10295
10383
  }
10296
10384
  for (const name of names) {
10297
- const file = path17.join(dir, name);
10385
+ const file = path18.join(dir, name);
10298
10386
  if (withTmp && name.endsWith(".tmp")) tmp.push(file);
10299
10387
  const m = SEGMENT_FILE.exec(name);
10300
10388
  if (!m || file === this.cur?.file) continue;
10301
- const st = await fs17.stat(file).catch(() => null);
10389
+ const st = await fs18.stat(file).catch(() => null);
10302
10390
  if (st?.isFile()) segments.push({ day, start: Number(m[1]), bytes: st.size, file });
10303
10391
  }
10304
10392
  }
@@ -10310,17 +10398,17 @@ var Journal = class {
10310
10398
  const { segments, tmp, days } = await this.files(boot);
10311
10399
  const current = this.cur ? [{ day: this.cur.day, start: this.cur.start, bytes: this.cur.bytes, file: this.cur.file }] : [];
10312
10400
  const gone = toPrune([...segments, ...current], this.now(), { keepDays: this.opts.keepDays ?? KEEP_DAYS, maxBytes: this.opts.maxBytes ?? MAX_BYTES, keep: this.cur?.start });
10313
- for (const f of [...gone.map((g) => g.file), ...tmp]) await fs17.rm(f, { force: true, maxRetries: 3 }).catch(() => void 0);
10401
+ for (const f of [...gone.map((g) => g.file), ...tmp]) await fs18.rm(f, { force: true, maxRetries: 3 }).catch(() => void 0);
10314
10402
  for (const g of gone) for (const k of this.summaries.keys()) if (k.startsWith(`${g.file}|`)) this.summaries.delete(k);
10315
10403
  for (const day of days) {
10316
- const dir = path17.join(this.opts.dir, day);
10317
- const left = await fs17.readdir(dir).catch(() => null);
10318
- if (left && left.length === 0) await fs17.rm(dir, { recursive: true, force: true, maxRetries: 3 }).catch(() => void 0);
10404
+ const dir = path18.join(this.opts.dir, day);
10405
+ const left = await fs18.readdir(dir).catch(() => null);
10406
+ if (left && left.length === 0) await fs18.rm(dir, { recursive: true, force: true, maxRetries: 3 }).catch(() => void 0);
10319
10407
  }
10320
10408
  return gone.length;
10321
10409
  }
10322
10410
  readRaw(f) {
10323
- return fs17.readFile(f.file, "utf8").catch(() => "");
10411
+ return fs18.readFile(f.file, "utf8").catch(() => "");
10324
10412
  }
10325
10413
  currentRaw() {
10326
10414
  return this.cur ? this.cur.lines.join("\n") : "";
@@ -10373,12 +10461,12 @@ var Journal = class {
10373
10461
  if (!lines.length || !isFrame(lines[0])) throw new Error("a day starts with a keyframe");
10374
10462
  const day = dayKey(lines[0].t);
10375
10463
  if (day === this.cur?.day) throw new HttpError(409, "Today is being recorded: a sample day must be another day");
10376
- const dir = path17.join(this.opts.dir, day);
10377
- await fs17.rm(dir, { recursive: true, force: true, maxRetries: 3 });
10378
- for (const k of this.summaries.keys()) if (k.startsWith(`${dir}${path17.sep}`)) this.summaries.delete(k);
10464
+ const dir = path18.join(this.opts.dir, day);
10465
+ await fs18.rm(dir, { recursive: true, force: true, maxRetries: 3 });
10466
+ for (const k of this.summaries.keys()) if (k.startsWith(`${dir}${path18.sep}`)) this.summaries.delete(k);
10379
10467
  let chunk = [];
10380
10468
  const write = async () => {
10381
- if (chunk.length) await writeAtomic(path17.join(dir, `${chunk[0].t}.ndjson`), `${chunk.map((l) => JSON.stringify(l)).join("\n")}
10469
+ if (chunk.length) await writeAtomic(path18.join(dir, `${chunk[0].t}.ndjson`), `${chunk.map((l) => JSON.stringify(l)).join("\n")}
10382
10470
  `);
10383
10471
  };
10384
10472
  for (const l of lines) {
@@ -10407,9 +10495,9 @@ ${commit ?? ""}
10407
10495
  ${indexHtml}`).digest("hex").slice(0, 12);
10408
10496
  }
10409
10497
  function serviceWorkerSource(version) {
10410
- return `// cubefarm's service worker (server/pwa.ts). Version ${version}.
10498
+ return `// Droidsembly's service worker (server/pwa.ts). Version ${version}.
10411
10499
  const VERSION = ${JSON.stringify(version)};
10412
- const CACHE = 'cubefarm-shell-' + VERSION;
10500
+ const CACHE = 'droidsembly-shell-' + VERSION;
10413
10501
  const PRECACHE = ['/', '/manifest.webmanifest', ...['icon-192.png', 'icon-512.png', 'icon-maskable-512.png', 'apple-touch-icon.png', 'icon.svg', 'favicon.svg', 'favicon-32.png', 'badge-96.png', 'sora-400.ttf', 'sora-700.ttf', 'droid-wire.svg', 'droid-shell.svg', 'droid-eyes.svg', 'droid-antenna.svg', 'droid-spark.svg'].map(name => '/icons/' + name)];
10414
10502
 
10415
10503
  self.addEventListener('install', (event) => {
@@ -10419,7 +10507,7 @@ self.addEventListener('install', (event) => {
10419
10507
  self.addEventListener('activate', (event) => {
10420
10508
  event.waitUntil(
10421
10509
  caches.keys()
10422
- .then((keys) => Promise.all(keys.filter((k) => k.startsWith('cubefarm-shell-') && k !== CACHE).map((k) => caches.delete(k))))
10510
+ .then((keys) => Promise.all(keys.filter((k) => (k.startsWith('droidsembly-shell-') || k.startsWith('cubefarm-shell-')) && k !== CACHE).map((k) => caches.delete(k))))
10423
10511
  .then(() => self.clients.claim()),
10424
10512
  );
10425
10513
  });
@@ -10447,7 +10535,7 @@ self.addEventListener('fetch', (event) => {
10447
10535
  if (!isShell(url)) return;
10448
10536
  // Bundles are content-hashed, so a cached one never goes stale.
10449
10537
  event.respondWith(
10450
- caches.match(req).then(
10538
+ caches.has(CACHE).then((exists) => exists ? caches.open(CACHE).then((cache) => cache.match(req)) : undefined).then(
10451
10539
  (hit) =>
10452
10540
  hit ||
10453
10541
  fetch(req).then((res) => {
@@ -10473,7 +10561,9 @@ self.addEventListener('notificationclick', (event) => {
10473
10561
  self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((list) => {
10474
10562
  const open = list.find((c) => new URL(c.url).origin === self.location.origin);
10475
10563
  if (!open) return self.clients.openWindow(url);
10476
- open.postMessage({ type: 'cubefarm:open', url });
10564
+ // Keep the legacy type for already-open old pages, with canonical metadata.
10565
+ // One message only: new pages normalize it to droidsembly:open.
10566
+ open.postMessage({ type: 'cubefarm:open', canonicalType: 'droidsembly:open', url });
10477
10567
  return open.focus();
10478
10568
  }),
10479
10569
  );
@@ -10631,18 +10721,18 @@ function passHeaders(headers) {
10631
10721
  for (const [k, v] of Object.entries(headers)) if (v !== void 0 && !HOP.test(k)) out[k] = v;
10632
10722
  return out;
10633
10723
  }
10634
- function upstream(target, req, body2, onResponse, onError, path23 = req.url) {
10724
+ function upstream(target, req, body2, onResponse, onError, path24 = req.url) {
10635
10725
  const headers = { ...req.headers, host: `localhost:${target}`, "accept-encoding": "identity" };
10636
10726
  for (const k of Object.keys(headers)) if (HOP.test(k)) delete headers[k];
10637
10727
  const send2 = (host, retry) => {
10638
- const up = http2.request({ host, port: target, method: req.method, path: path23, headers }, onResponse);
10728
+ const up = http2.request({ host, port: target, method: req.method, path: path24, headers }, onResponse);
10639
10729
  up.once("error", (err) => retry && err.code === "ECONNREFUSED" ? send2("::1", false) : onError(err));
10640
10730
  up.end(body2);
10641
10731
  };
10642
10732
  send2("127.0.0.1", true);
10643
10733
  }
10644
- function tunnel(target, req, socket, head, path23 = req.url) {
10645
- const lines = [`${req.method} ${path23} HTTP/${req.httpVersion}`];
10734
+ function tunnel(target, req, socket, head, path24 = req.url) {
10735
+ const lines = [`${req.method} ${path24} HTTP/${req.httpVersion}`];
10646
10736
  for (let i = 0; i < req.rawHeaders.length; i += 2) {
10647
10737
  const name = req.rawHeaders[i];
10648
10738
  lines.push(`${name}: ${/^host$/i.test(name) ? `localhost:${target}` : req.rawHeaders[i + 1]}`);
@@ -11374,10 +11464,14 @@ var PresenceHub = class {
11374
11464
  };
11375
11465
 
11376
11466
  // server/swarm.ts
11377
- import fs21 from "node:fs/promises";
11378
- import path21 from "node:path";
11467
+ import fs22 from "node:fs/promises";
11468
+ import path22 from "node:path";
11379
11469
  import crypto10 from "node:crypto";
11380
11470
 
11471
+ // shared/agentDefaults.ts
11472
+ var DEFAULT_CLI = "opencode";
11473
+ var DEFAULT_CEO_CLI = DEFAULT_CLI;
11474
+
11381
11475
  // shared/usage.ts
11382
11476
  function clock(at, now2, locale = "en-US") {
11383
11477
  const d = new Date(at);
@@ -11507,8 +11601,8 @@ function analysisPrompt(name, fullName) {
11507
11601
  }
11508
11602
 
11509
11603
  // server/boxMachines.ts
11510
- import fs18 from "node:fs/promises";
11511
- import path18 from "node:path";
11604
+ import fs19 from "node:fs/promises";
11605
+ import path19 from "node:path";
11512
11606
 
11513
11607
  // server/boxHelpers.ts
11514
11608
  var PUT = String.raw`
@@ -11710,6 +11804,7 @@ var BoxMachines = class {
11710
11804
  // machine -> Box id
11711
11805
  ready = /* @__PURE__ */ new Map();
11712
11806
  states = /* @__PURE__ */ new Map();
11807
+ pausing = /* @__PURE__ */ new Map();
11713
11808
  api() {
11714
11809
  const api = this.deps.api();
11715
11810
  if (!api) throw new Error("Cloud agents need your Upstash Box API key: Settings \u2192 Cloud agents.");
@@ -11753,6 +11848,8 @@ var BoxMachines = class {
11753
11848
  }
11754
11849
  /** The machine's Box, created, running and set up: the first time takes a few minutes. */
11755
11850
  ensure(machine, note2) {
11851
+ const pausing = this.pausing.get(machine);
11852
+ if (pausing) return pausing.catch(() => void 0).then(() => this.ensure(machine, note2));
11756
11853
  const cli = this.deps.cli?.(machine);
11757
11854
  const browser = this.deps.browser?.(machine) ?? !cli;
11758
11855
  const profile = `${cli ?? "all"}:${browser}`;
@@ -11804,8 +11901,12 @@ var BoxMachines = class {
11804
11901
  }
11805
11902
  this.setState(machine, "setting-up");
11806
11903
  const git2 = await this.deps.git();
11807
- const setup = await api.run(id, setupScript({ versions: this.deps.versions, rev: SETUP_REV, gitName: git2.name, gitEmail: git2.email, cli, browser }), { timeoutMs: SETUP_TIMEOUT_MS });
11808
- if (setup.code !== 0 || !setup.output.includes("CUBEFARM_SETUP_OK")) throw failure("Couldn't set up the cloud machine", setup.output, this.deps.secrets());
11904
+ const setup = await api.run(id, `sh -c ${sq(setupScript({ versions: this.deps.versions, rev: SETUP_REV, gitName: git2.name, gitEmail: git2.email, cli, browser }))}`, { timeoutMs: SETUP_TIMEOUT_MS });
11905
+ const setupMarkerPresent = setup.output.includes("CUBEFARM_SETUP_OK");
11906
+ if (setup.code !== 0 || !setupMarkerPresent) {
11907
+ const exit = Number.isInteger(setup.code) ? String(setup.code) : "unverified";
11908
+ throw failure(`Couldn't set up the cloud machine (exit ${exit}; setup marker ${setupMarkerPresent ? "present" : "missing"})`, setup.output, this.deps.secrets());
11909
+ }
11809
11910
  for (const [name, source] of Object.entries(BOX_HELPERS)) await api.write(id, `${BOX_BIN}/${name}`, source);
11810
11911
  await api.write(id, BOX_TMUX_CONF, TMUX_CONF);
11811
11912
  this.setState(machine, "ready");
@@ -11851,7 +11952,7 @@ var BoxMachines = class {
11851
11952
  }
11852
11953
  async remove(machine) {
11853
11954
  const api = this.deps.api();
11854
- const id = api ? await this.boxId(machine).catch(() => null) : null;
11955
+ const id = api ? await this.boxId(machine) : null;
11855
11956
  if (!api || !id) return { removed: !!api, patches: [] };
11856
11957
  const patches = [];
11857
11958
  try {
@@ -11870,7 +11971,10 @@ var BoxMachines = class {
11870
11971
  this.deps.log(`could not save the leftovers of cloud machine ${machine}: ${err.message}`);
11871
11972
  return { removed: false, patches };
11872
11973
  }
11873
- await api.remove(id);
11974
+ if (!await removeBoxVerified(api, id)) {
11975
+ this.deps.log(`Removal of cloud machine ${machine} is not confirmed; its Box may still exist.`);
11976
+ return { removed: false, patches };
11977
+ }
11874
11978
  this.ids.delete(machine);
11875
11979
  this.ready.delete(machine);
11876
11980
  this.states.delete(machine);
@@ -11987,19 +12091,27 @@ var BoxMachines = class {
11987
12091
  await this.api().run(id, signOutScript(cli), { timeoutMs: 6e4 });
11988
12092
  }
11989
12093
  /** Pause a machine's Box (an idle cloud agent); it wakes for their next task. */
11990
- async pause(machine) {
11991
- const id = await this.running(machine);
11992
- if (!id) return;
11993
- await this.api().pause(id);
11994
- this.setState(machine, "paused");
12094
+ pause(machine, stillIdle = () => true) {
12095
+ const previous = this.pausing.get(machine);
12096
+ if (previous) return previous;
12097
+ const pending2 = (async () => {
12098
+ const id = await this.running(machine);
12099
+ if (!id || !stillIdle()) return;
12100
+ await this.api().pause(id);
12101
+ this.setState(machine, "paused");
12102
+ })().finally(() => {
12103
+ this.pausing.delete(machine);
12104
+ });
12105
+ this.pausing.set(machine, pending2);
12106
+ return pending2;
11995
12107
  }
11996
12108
  async saveLeftovers(fullName, machine, data) {
11997
- const dir = path18.join(HOME_DIR, "leftovers", fullName.replace("/", "__"));
11998
- await fs18.mkdir(dir, { recursive: true });
12109
+ const dir = path19.join(HOME_DIR, "leftovers", fullName.replace("/", "__"));
12110
+ await fs19.mkdir(dir, { recursive: true });
11999
12111
  const base = `machine-${machine}-${stamp2(/* @__PURE__ */ new Date())}`;
12000
- let file = path18.join(dir, `${base}.patch`);
12001
- for (let n = 2; await fs18.stat(file).then(() => true, () => false); n++) file = path18.join(dir, `${base}-${n}.patch`);
12002
- await fs18.writeFile(file, data);
12112
+ let file = path19.join(dir, `${base}.patch`);
12113
+ for (let n = 2; await fs19.stat(file).then(() => true, () => false); n++) file = path19.join(dir, `${base}-${n}.patch`);
12114
+ await fs19.writeFile(file, data);
12003
12115
  return file;
12004
12116
  }
12005
12117
  };
@@ -13434,39 +13546,39 @@ var Previews = class {
13434
13546
  };
13435
13547
 
13436
13548
  // server/qaShots.ts
13437
- import fs19 from "node:fs/promises";
13438
- import path19 from "node:path";
13549
+ import fs20 from "node:fs/promises";
13550
+ import path20 from "node:path";
13439
13551
  var QA_SHOTS_KEPT = 8;
13440
13552
  var EXT = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/svg+xml": "svg" };
13441
- var qaShotsDir = (root, repoId2, pr) => path19.join(root, repoId2.replace("/", "__"), `pr-${pr}`);
13442
- var qaShotFile = (dir, index, mime) => path19.join(dir, `${String(index + 1).padStart(2, "0")}.${EXT[mime] ?? "img"}`);
13553
+ var qaShotsDir = (root, repoId2, pr) => path20.join(root, repoId2.replace("/", "__"), `pr-${pr}`);
13554
+ var qaShotFile = (dir, index, mime) => path20.join(dir, `${String(index + 1).padStart(2, "0")}.${EXT[mime] ?? "img"}`);
13443
13555
  async function saveQaShots(dir, shots) {
13444
13556
  await removeQaShots(dir);
13445
13557
  const kept = shots.slice(-QA_SHOTS_KEPT);
13446
13558
  if (!kept.length) return [];
13447
- await fs19.mkdir(dir, { recursive: true });
13559
+ await fs20.mkdir(dir, { recursive: true });
13448
13560
  const out = [];
13449
13561
  for (const [i, s2] of kept.entries()) {
13450
- await fs19.writeFile(qaShotFile(dir, i, s2.mime), s2.data);
13562
+ await fs20.writeFile(qaShotFile(dir, i, s2.mime), s2.data);
13451
13563
  out.push({ caption: s2.caption, page: s2.page, mime: s2.mime });
13452
13564
  }
13453
13565
  return out;
13454
13566
  }
13455
13567
  async function readQaShot(dir, index, mime) {
13456
- return fs19.readFile(qaShotFile(dir, index, mime)).catch(() => null);
13568
+ return fs20.readFile(qaShotFile(dir, index, mime)).catch(() => null);
13457
13569
  }
13458
13570
  async function removeQaShots(dir) {
13459
- await fs19.rm(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
13571
+ await fs20.rm(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
13460
13572
  }
13461
13573
  async function pruneQaShots(root, keep) {
13462
- const repos2 = await fs19.readdir(root, { withFileTypes: true }).catch(() => []);
13574
+ const repos2 = await fs20.readdir(root, { withFileTypes: true }).catch(() => []);
13463
13575
  for (const repo of repos2.filter((e) => e.isDirectory())) {
13464
13576
  const repoId2 = repo.name.replace("__", "/");
13465
- const prs = await fs19.readdir(path19.join(root, repo.name), { withFileTypes: true }).catch(() => []);
13577
+ const prs = await fs20.readdir(path20.join(root, repo.name), { withFileTypes: true }).catch(() => []);
13466
13578
  for (const pr of prs) {
13467
13579
  const n = /^pr-(\d+)$/.exec(pr.name)?.[1];
13468
13580
  if (!n || keep.has(`${repoId2}#${n}`)) continue;
13469
- await removeQaShots(path19.join(root, repo.name, pr.name)).catch(() => void 0);
13581
+ await removeQaShots(path20.join(root, repo.name, pr.name)).catch(() => void 0);
13470
13582
  }
13471
13583
  }
13472
13584
  }
@@ -14230,8 +14342,8 @@ function loadLedger(raw) {
14230
14342
  }
14231
14343
 
14232
14344
  // server/terminal.ts
14233
- import fs20 from "node:fs/promises";
14234
- import path20 from "node:path";
14345
+ import fs21 from "node:fs/promises";
14346
+ import path21 from "node:path";
14235
14347
  import { stripVTControlCharacters } from "node:util";
14236
14348
  import xtermHeadless from "@xterm/headless";
14237
14349
  import xtermSerialize from "@xterm/addon-serialize";
@@ -14345,15 +14457,15 @@ var AgentTerminal = class {
14345
14457
  const next = this.saving.then(async () => {
14346
14458
  this.dirty = false;
14347
14459
  await this.flush();
14348
- await fs20.mkdir(path20.dirname(file), { recursive: true });
14349
- await fs20.writeFile(`${file}.tmp`, this.snapshot());
14350
- await fs20.rename(`${file}.tmp`, file);
14460
+ await fs21.mkdir(path21.dirname(file), { recursive: true });
14461
+ await fs21.writeFile(`${file}.tmp`, this.snapshot());
14462
+ await fs21.rename(`${file}.tmp`, file);
14351
14463
  });
14352
14464
  this.saving = next.catch(() => void 0);
14353
14465
  return next;
14354
14466
  }
14355
14467
  async load(file) {
14356
- const data = await fs20.readFile(file, "utf8").catch(() => "");
14468
+ const data = await fs21.readFile(file, "utf8").catch(() => "");
14357
14469
  if (!data) return;
14358
14470
  this.term.write(data);
14359
14471
  this.note("(the office restarted)");
@@ -15039,14 +15151,15 @@ var Outbox = class {
15039
15151
  var BOX_SIZES = ["small", "medium", "large"];
15040
15152
  var FREE_BOX_LIMIT = 10;
15041
15153
  var MAX_BOX_LIMIT = 1e3;
15042
- var DEFAULT_CLOUD = { machineKind: "local", boxSize: "small", boxLimit: FREE_BOX_LIMIT };
15154
+ var DEFAULT_CLOUD = { machineKind: "local", boxSize: "small", boxLimit: FREE_BOX_LIMIT, pauseNewWork: false };
15043
15155
  function cloudSettings(base, raw) {
15044
15156
  const r = raw && typeof raw === "object" ? raw : {};
15045
15157
  const limit = Math.round(Number(r.boxLimit));
15046
15158
  return {
15047
15159
  machineKind: r.machineKind === "box" || r.machineKind === "local" ? r.machineKind : base.machineKind,
15048
15160
  boxSize: BOX_SIZES.includes(r.boxSize) ? r.boxSize : base.boxSize,
15049
- boxLimit: Number.isFinite(limit) && limit >= 1 ? Math.min(MAX_BOX_LIMIT, limit) : base.boxLimit
15161
+ boxLimit: Number.isFinite(limit) && limit >= 1 ? Math.min(MAX_BOX_LIMIT, limit) : base.boxLimit,
15162
+ pauseNewWork: typeof r.pauseNewWork === "boolean" ? r.pauseNewWork : base.pauseNewWork ?? false
15050
15163
  };
15051
15164
  }
15052
15165
 
@@ -15282,8 +15395,8 @@ var EFFORTS = ["low", "medium", "high", "xhigh", "max"];
15282
15395
  var CEO_MODEL = "claude-opus-5-5";
15283
15396
  var CEO_EFFORT = "xhigh";
15284
15397
  var CEO_NAME = "Morgan";
15285
- var CEO_DIR = path21.join(HOME_DIR, "ceo");
15286
- var DEFAULT_PROJECTS_DIR = defaultProjectsDir(path21.resolve(import.meta.dirname, ".."));
15398
+ var CEO_DIR = path22.join(HOME_DIR, "ceo");
15399
+ var DEFAULT_PROJECTS_DIR = defaultProjectsDir(path22.resolve(import.meta.dirname, ".."));
15287
15400
  var MAX_ISSUES_PER_JOB = 12;
15288
15401
  var KEEP_MESSAGES = 200;
15289
15402
  var KEEP_DECIDED_REQUESTS = 40;
@@ -15309,26 +15422,26 @@ var SignInNeeded = class extends Error {
15309
15422
  }
15310
15423
  cli;
15311
15424
  };
15312
- var SCREENS_DIR = path21.join(HOME_DIR, "screens");
15425
+ var SCREENS_DIR = path22.join(HOME_DIR, "screens");
15313
15426
  var MIME_EXT = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/svg+xml": "svg" };
15314
- var screenFile = (agentId, mime) => path21.join(SCREENS_DIR, `${agentId}.${MIME_EXT[mime] ?? "img"}`);
15427
+ var screenFile = (agentId, mime) => path22.join(SCREENS_DIR, `${agentId}.${MIME_EXT[mime] ?? "img"}`);
15315
15428
  async function loadScreen(agentId) {
15316
15429
  for (const [mime, ext] of Object.entries(MIME_EXT)) {
15317
- const file = path21.join(SCREENS_DIR, `${agentId}.${ext}`);
15430
+ const file = path22.join(SCREENS_DIR, `${agentId}.${ext}`);
15318
15431
  try {
15319
- const [data, stat] = await Promise.all([fs21.readFile(file), fs21.stat(file)]);
15432
+ const [data, stat] = await Promise.all([fs22.readFile(file), fs22.stat(file)]);
15320
15433
  return { data, mime, at: stat.mtimeMs };
15321
15434
  } catch {
15322
15435
  }
15323
15436
  }
15324
15437
  return null;
15325
15438
  }
15326
- var QA_SHOTS_DIR = path21.join(HOME_DIR, "qa-shots");
15439
+ var QA_SHOTS_DIR = path22.join(HOME_DIR, "qa-shots");
15327
15440
  async function removeScreens(agentId) {
15328
- await Promise.all(Object.values(MIME_EXT).map((ext) => fs21.rm(path21.join(SCREENS_DIR, `${agentId}.${ext}`), { force: true })));
15441
+ await Promise.all(Object.values(MIME_EXT).map((ext) => fs22.rm(path22.join(SCREENS_DIR, `${agentId}.${ext}`), { force: true })));
15329
15442
  }
15330
- var TERMINALS_DIR = path21.join(HOME_DIR, "terminals");
15331
- var terminalFile = (agentId) => path21.join(TERMINALS_DIR, `${agentId}.ansi`);
15443
+ var TERMINALS_DIR = path22.join(HOME_DIR, "terminals");
15444
+ var terminalFile = (agentId) => path22.join(TERMINALS_DIR, `${agentId}.ansi`);
15332
15445
  var TERMINAL_SAVE_MS = 2e4;
15333
15446
  var QA_SCHEMA = {
15334
15447
  type: "object",
@@ -15410,15 +15523,15 @@ var Swarm = class {
15410
15523
  this.backend = backend;
15411
15524
  this.weather = new WeatherService({
15412
15525
  api: backend.weather,
15413
- file: path21.join(HOME_DIR, backend.demo ? "demo-weather.json" : "weather.json"),
15526
+ file: path22.join(HOME_DIR, backend.demo ? "demo-weather.json" : "weather.json"),
15414
15527
  settings: () => this.state.settings.weather,
15415
15528
  changed: (weather) => this.broadcast({ type: "weather", weather }),
15416
15529
  log: (line) => console.log(line)
15417
15530
  });
15418
15531
  this.voice = new Voice({
15419
15532
  api: backend.voice,
15420
- secretsFile: path21.join(HOME_DIR, backend.demo ? "demo-secrets.json" : "secrets.json"),
15421
- cacheDir: path21.join(HOME_DIR, backend.demo ? "demo-voice" : "voice"),
15533
+ secretsFile: path22.join(HOME_DIR, backend.demo ? "demo-secrets.json" : "secrets.json"),
15534
+ cacheDir: path22.join(HOME_DIR, backend.demo ? "demo-voice" : "voice"),
15422
15535
  settings: () => this.state.settings.voice,
15423
15536
  listen: () => this.state.settings.listen,
15424
15537
  language: () => languageOf(this.state.settings.language),
@@ -15429,14 +15542,14 @@ var Swarm = class {
15429
15542
  log: (line) => console.log(line)
15430
15543
  });
15431
15544
  this.journal = new Journal({
15432
- dir: path21.join(HOME_DIR, backend.demo ? "demo-journal" : "journal"),
15545
+ dir: path22.join(HOME_DIR, backend.demo ? "demo-journal" : "journal"),
15433
15546
  frame: () => journalFrame(this.snapshot(), this.secrets()),
15434
15547
  secrets: () => this.secrets()
15435
15548
  });
15436
15549
  this.notifier = new Notifier({
15437
15550
  transport: backend.notify,
15438
- secretsFile: path21.join(HOME_DIR, backend.demo ? "demo-secrets.json" : "secrets.json"),
15439
- pushFile: path21.join(HOME_DIR, backend.demo ? "demo-push.json" : "push.json"),
15551
+ secretsFile: path22.join(HOME_DIR, backend.demo ? "demo-secrets.json" : "secrets.json"),
15552
+ pushFile: path22.join(HOME_DIR, backend.demo ? "demo-push.json" : "push.json"),
15440
15553
  settings: () => this.state.settings.notify,
15441
15554
  broadcast: (note2) => this.broadcast({ type: "notify", note: note2 }),
15442
15555
  channelsChanged: (notifyChannels) => this.broadcast({ type: "notifyChannels", notifyChannels }),
@@ -15444,7 +15557,7 @@ var Swarm = class {
15444
15557
  });
15445
15558
  this.cloud = new Cloud({
15446
15559
  // The demo's fake cloud keeps a file of its own: its tests run beside the notifier's, which share demo-secrets.json.
15447
- secretsFile: path21.join(HOME_DIR, backend.demo ? "demo-cloud-secrets.json" : "secrets.json"),
15560
+ secretsFile: path22.join(HOME_DIR, backend.demo ? "demo-cloud-secrets.json" : "secrets.json"),
15448
15561
  credentials: backend.cloud.credentials,
15449
15562
  env: backend.cloud.env(),
15450
15563
  boxes: (key) => backend.cloud.boxes(key),
@@ -15497,10 +15610,10 @@ var Swarm = class {
15497
15610
  settings: {
15498
15611
  sessionLimit: 0,
15499
15612
  language: "en",
15500
- defaultModel: DEFAULT_MODEL,
15613
+ defaultModel: "",
15501
15614
  defaultEffort: "medium",
15502
15615
  runtime: "terminal",
15503
- defaultCli: "claude",
15616
+ defaultCli: DEFAULT_CLI,
15504
15617
  scaling: "approve",
15505
15618
  maxAgents: DEFAULT_MAX_AGENTS,
15506
15619
  ceoHeartbeatMin: 60,
@@ -15533,7 +15646,8 @@ var Swarm = class {
15533
15646
  held: [],
15534
15647
  progress: emptyLedger(),
15535
15648
  pong: {},
15536
- officeId: officeId()
15649
+ officeId: officeId(),
15650
+ agentDefaultsVersion: 1
15537
15651
  };
15538
15652
  /**
15539
15653
  * The CEO's office tools. Every session gets its own server: one can only be connected to one session at a time, so
@@ -15625,16 +15739,22 @@ var Swarm = class {
15625
15739
  cloud;
15626
15740
  /** Cloud agents' machines: an Upstash Box each. */
15627
15741
  boxMachines;
15742
+ finishingAgents = /* @__PURE__ */ new Map();
15743
+ pausingAgents = /* @__PURE__ */ new Set();
15628
15744
  /** Cloud agents waiting for a sign-in in their terminal (holdForSignIn), by agent id. */
15629
15745
  signIns = /* @__PURE__ */ new Map();
15630
15746
  toldStuck = /* @__PURE__ */ new Set();
15631
15747
  // ---------- lifecycle ----------
15632
15748
  async init() {
15749
+ let legacyDefaults = false;
15633
15750
  try {
15634
- const raw = await fs21.readFile(STATE_FILE, "utf8");
15751
+ const raw = await fs22.readFile(STATE_FILE, "utf8");
15635
15752
  const loaded = JSON.parse(raw);
15753
+ legacyDefaults = loaded.agentDefaultsVersion !== 1;
15636
15754
  this.state = {
15637
- settings: { ...this.state.settings, ...loaded.settings },
15755
+ agentDefaultsVersion: 1,
15756
+ // Missing legacy defaults meant Claude; do not inherit the new-office proposal.
15757
+ settings: { ...this.state.settings, defaultCli: "claude", defaultModel: DEFAULT_MODEL, ...loaded.settings },
15638
15758
  repos: (loaded.repos ?? []).map((r) => ({
15639
15759
  ...r,
15640
15760
  autoMerge: r.autoMerge ?? true,
@@ -15654,7 +15774,7 @@ var Swarm = class {
15654
15774
  look: a.look ?? lookFor(a.name),
15655
15775
  style: cleanStyle(a.style),
15656
15776
  task: a.task ?? (a.issueNumber ? "issue" : null),
15657
- cli: isCli(a.cli) ? a.cli : "",
15777
+ cli: isCli(a.cli) ? a.cli : legacyDefaults && a.role === "ceo" ? "claude" : "",
15658
15778
  sessionCli: a.sessionCli ?? (a.sessionId ? "claude" : null)
15659
15779
  })),
15660
15780
  qa: (loaded.qa ?? []).map((q) => ({
@@ -15752,13 +15872,16 @@ var Swarm = class {
15752
15872
  const boxKept = this.state.agents.filter((a) => a.host === "box" && a.boxCli);
15753
15873
  if (!boxApi) for (const a of boxKept) a.boxCli = null;
15754
15874
  else {
15755
- const kept = boxKept.map((a) => ({
15756
- agentId: a.id,
15757
- rec: a.boxCli,
15758
- api: boxApi,
15759
- record: (rec) => this.boxCliRecord(a.id, rec),
15760
- connection: (up) => this.boxMachines.connection(a.machine ?? machineName(a.id), up)
15761
- }));
15875
+ const kept = boxKept.map((a) => {
15876
+ const token = a.boxCli.token;
15877
+ return {
15878
+ agentId: a.id,
15879
+ rec: a.boxCli,
15880
+ api: boxApi,
15881
+ record: (rec) => this.boxCliRecord(a.id, rec, rec ? void 0 : token),
15882
+ connection: (up) => this.boxMachines.connection(a.machine ?? machineName(a.id), up)
15883
+ };
15884
+ });
15762
15885
  back.push(
15763
15886
  ...await this.backend.cloud.reconnect(kept, terminalOf).catch((err) => {
15764
15887
  console.warn("could not pick up cloud agents' CLIs", err);
@@ -15792,7 +15915,7 @@ var Swarm = class {
15792
15915
  this.state.ops = this.backend.seedOps?.(this.state.repos.map((r) => r.id), Date.now()) ?? this.state.ops;
15793
15916
  }
15794
15917
  for (const r of this.state.repos) this.ensureAgent(r);
15795
- this.ensureCeo(interrupted);
15918
+ this.ensureCeo(interrupted, legacyDefaults ? "claude" : DEFAULT_CEO_CLI);
15796
15919
  for (const a of this.state.agents) if (a.role !== "ceo") apply(this.state.progress, { kind: "hired", agentId: a.id, at: Date.now() });
15797
15920
  for (const r of this.state.repos) void this.cloneRepo(r.id);
15798
15921
  await Promise.all(this.state.repos.map((r) => this.syncRepo(r.id)));
@@ -16195,10 +16318,10 @@ var Swarm = class {
16195
16318
  }
16196
16319
  async writeStateFile() {
16197
16320
  for (const a of this.state.agents) a.logTail = (this.agentRt.get(a.id)?.log ?? []).slice(-200);
16198
- await fs21.mkdir(path21.dirname(STATE_FILE), { recursive: true });
16321
+ await fs22.mkdir(path22.dirname(STATE_FILE), { recursive: true });
16199
16322
  const tmp = `${STATE_FILE}.tmp`;
16200
- await fs21.writeFile(tmp, JSON.stringify(this.state, null, 2));
16201
- await fs21.rename(tmp, STATE_FILE);
16323
+ await fs22.writeFile(tmp, JSON.stringify(this.state, null, 2));
16324
+ await fs22.rename(tmp, STATE_FILE);
16202
16325
  }
16203
16326
  // ---------- lookups ----------
16204
16327
  repo(id) {
@@ -16266,7 +16389,7 @@ var Swarm = class {
16266
16389
  /** Remove a machine, saying where its unpushed work went; one still in use is tried again by sweepMachines. */
16267
16390
  async removeMachine(machine, name, host = "local") {
16268
16391
  const r = await this.machinesFor({ host }).remove(machine).catch(() => ({ removed: false, patches: [] }));
16269
- if (r.patches.length) this.postMessage("office", `\u{1F9F3} ${name ?? "A former agent"} left work that was on no GitHub branch: saved in ${path21.dirname(r.patches[0])}.`);
16392
+ if (r.patches.length) this.postMessage("office", `\u{1F9F3} ${name ?? "A former agent"} left work that was on no GitHub branch: saved in ${path22.dirname(r.patches[0])}.`);
16270
16393
  if (host === "box" && r.removed) void this.cloud.count().catch(() => void 0);
16271
16394
  }
16272
16395
  /** Machines whose agents are gone (on this computer, or Boxes of this office): removed while still in use, or left by an office that stopped half-way. */
@@ -16280,6 +16403,19 @@ var Swarm = class {
16280
16403
  this.quotaWaiting.delete(a.id);
16281
16404
  Object.assign(a, { status: "idle", task: null, issueNumber: null, issueTitle: null, branch: null, prNumber: null, prUrl: null, lastError: null });
16282
16405
  this.emitAgent(a);
16406
+ this.pauseIdleBox(a);
16407
+ }
16408
+ /** Either the task or the CLI can finish first; check both transitions. */
16409
+ pauseIdleBox(a) {
16410
+ const machine = a.machine;
16411
+ const idle2 = () => this.state.agents.includes(a) && a.host === "box" && a.machine === machine && (a.status === "idle" && !a.task || a.status === "done") && !this.finishingAgents.has(a.id) && !a.boxCli && !a.needsSignIn && this.openCodeAuthRun?.agentId !== a.id;
16412
+ if (!machine || !idle2() || this.pausingAgents.has(a.id)) return;
16413
+ this.pausingAgents.add(a.id);
16414
+ void this.boxMachines.pause(machine, idle2).catch(() => {
16415
+ this.appendLog(a, [{ kind: "system", text: "\u2601 Automatic Box pause failed. The cloud machine may still be active." }]);
16416
+ }).finally(() => {
16417
+ this.pausingAgents.delete(a.id);
16418
+ });
16283
16419
  }
16284
16420
  // ---------- GitHub / repos ----------
16285
16421
  listGithubRepos(owner) {
@@ -16289,13 +16425,13 @@ var Swarm = class {
16289
16425
  openCodeAuthRun = null;
16290
16426
  async openCodeConnections(id) {
16291
16427
  const a = this.agent(id);
16292
- if ((a.cli || (a.role === "ceo" ? "claude" : this.state.settings.defaultCli)) !== "opencode") throw new HttpError(409, "Choose OpenCode first.");
16428
+ if ((a.cli || (a.role === "ceo" ? DEFAULT_CEO_CLI : this.state.settings.defaultCli)) !== "opencode") throw new HttpError(409, "Choose OpenCode first.");
16293
16429
  if (a.host === "box" && a.role !== "ceo") {
16294
16430
  const machine = this.machineOf(a);
16295
16431
  return { scope: "box", scopeKey: `box:${machine}`, integrations: await this.boxMachines.openCodeConnections(machine, this.boxMachines.deskDir(machine, this.repo(a.repoId).fullName)), configuringAgent: this.openCodeAuthRun?.agentId ?? null };
16296
16432
  }
16297
16433
  if (!this.backend.openCodeConnections) throw new HttpError(409, "OpenCode connections are unavailable in this backend.");
16298
- if (a.role === "ceo") await fs21.mkdir(CEO_DIR, { recursive: true });
16434
+ if (a.role === "ceo") await fs22.mkdir(CEO_DIR, { recursive: true });
16299
16435
  const directory = a.role === "ceo" ? CEO_DIR : this.backend.mainDir(this.repo(a.repoId).fullName);
16300
16436
  return { scope: "local", scopeKey: "local", integrations: await this.backend.openCodeConnections(directory), configuringAgent: this.openCodeAuthRun?.agentId ?? null };
16301
16437
  }
@@ -16322,7 +16458,7 @@ var Swarm = class {
16322
16458
  } catch (err) {
16323
16459
  throw new HttpError(400, err.message);
16324
16460
  }
16325
- const unchanged = () => this.openCodeAuthRun === operation && this.state.agents.includes(a) && a.host === host && (a.cli || (a.role === "ceo" ? "claude" : this.state.settings.defaultCli)) === "opencode" && (host !== "box" || this.machineOf(a) === machine);
16461
+ const unchanged = () => this.openCodeAuthRun === operation && this.state.agents.includes(a) && a.host === host && (a.cli || (a.role === "ceo" ? DEFAULT_CEO_CLI : this.state.settings.defaultCli)) === "opencode" && (host !== "box" || this.machineOf(a) === machine);
16326
16462
  if (!unchanged() || busy2()) throw new HttpError(409, "Agent setup or work changed; reload connections.");
16327
16463
  if (replaceable()) this.dropSignIn(id);
16328
16464
  const term = this.terminalFor(a);
@@ -16377,7 +16513,7 @@ var Swarm = class {
16377
16513
  return this.boxMachines.openCodeModels(machine, this.boxMachines.deskDir(machine, this.repo(a.repoId).fullName));
16378
16514
  }
16379
16515
  if (a.role === "ceo") {
16380
- return fs21.mkdir(CEO_DIR, { recursive: true }).then(() => this.backend.openCodeModels(CEO_DIR, refresh));
16516
+ return fs22.mkdir(CEO_DIR, { recursive: true }).then(() => this.backend.openCodeModels(CEO_DIR, refresh));
16381
16517
  }
16382
16518
  directory = this.backend.mainDir(this.repo(a.repoId).fullName);
16383
16519
  } else if (repoId2) directory = this.backend.mainDir(this.repo(repoId2).fullName);
@@ -16436,7 +16572,7 @@ var Swarm = class {
16436
16572
  const name = fullName.split("/")[1];
16437
16573
  const taken = folders.find((f) => f.name.toLowerCase() === name.toLowerCase());
16438
16574
  if (taken) throw new HttpError(409, `${taken.path} already exists and isn't a clone of ${fullName}. Connect that folder instead, or rename it first.`);
16439
- return path21.join(root, name);
16575
+ return path22.join(root, name);
16440
16576
  }
16441
16577
  /** A brand-new project: a folder in your projects folder, pushed to a new GitHub repo. */
16442
16578
  async createRepo(name, opts) {
@@ -16448,11 +16584,11 @@ var Swarm = class {
16448
16584
  }
16449
16585
  /** The folders in your projects folder (or another folder you point at), and which are floors already. */
16450
16586
  async listProjectFolders(dir) {
16451
- const root = dir?.trim() ? path21.resolve(dir.trim()) : this.state.settings.projectsDir;
16587
+ const root = dir?.trim() ? path22.resolve(dir.trim()) : this.state.settings.projectsDir;
16452
16588
  const folders = await this.backend.scanProjects(root).catch((err) => {
16453
16589
  throw new HttpError(400, err.message);
16454
16590
  });
16455
- const same3 = (a, b) => path21.resolve(a).toLowerCase() === path21.resolve(b).toLowerCase();
16591
+ const same3 = (a, b) => path22.resolve(a).toLowerCase() === path22.resolve(b).toLowerCase();
16456
16592
  const floorOf2 = (f) => this.state.repos.find((r) => r.localPath && same3(r.localPath, f.path) || f.github && r.id.toLowerCase() === f.github.toLowerCase())?.floor ?? null;
16457
16593
  return { root, folders: folders.map((f) => ({ name: f.name, path: f.path, git: f.git, github: f.github, floor: floorOf2(f) })) };
16458
16594
  }
@@ -16672,7 +16808,7 @@ var Swarm = class {
16672
16808
  rt.folderSync = status;
16673
16809
  this.emitRepo(repo);
16674
16810
  if (status && status !== before) {
16675
- const name = repo.localPath ? path21.basename(repo.localPath) : repo.fullName;
16811
+ const name = repo.localPath ? path22.basename(repo.localPath) : repo.fullName;
16676
16812
  if (status.startsWith("updated")) this.toast("success", `\u{1F4C1} ${name}: ${status}`);
16677
16813
  else if (/behind|diverged|failed/.test(status)) this.toast("info", `\u{1F4C1} ${name} wasn't updated: ${status}`);
16678
16814
  }
@@ -16698,7 +16834,7 @@ var Swarm = class {
16698
16834
  const r = await this.backend.sweepDesks(repo.fullName, keep);
16699
16835
  for (const a of agents) if (a.machine) r.branches += await this.machinesFor(a).sweep(a.machine, repo.fullName, keep.branches).catch(() => 0);
16700
16836
  const desks = r.desks + r.folders;
16701
- const saved = r.patches.length ? ` (${r.patches.length} patch${r.patches.length === 1 ? "" : "es"} saved to ${path21.dirname(r.patches[0])})` : "";
16837
+ const saved = r.patches.length ? ` (${r.patches.length} patch${r.patches.length === 1 ? "" : "es"} saved to ${path22.dirname(r.patches[0])})` : "";
16702
16838
  console.log(`desk sweep ${repo.fullName}: ${desks} desks, ${r.branches} branches removed${saved}${r.skipped.length ? `, ${r.skipped.length} still in use` : ""}`);
16703
16839
  if (!desks && !r.branches) return;
16704
16840
  const removed = [desks && `${desks} old desk${desks === 1 ? "" : "s"}`, r.branches && `${r.branches} finished branch${r.branches === 1 ? "" : "es"}`].filter(Boolean).join(" and ");
@@ -17176,17 +17312,30 @@ var Swarm = class {
17176
17312
  if (creds.missing.length) throw new Error(`Cloud agents can't sign in yet. Missing: ${creds.missing.join("; ")}.`);
17177
17313
  if (check && creds.ownLogin && !await this.boxSignedIn(a, cli)) throw new SignInNeeded(cli);
17178
17314
  const browser = browserTesting ? await api.browser(boxId).catch(() => false) : false;
17179
- return { api, boxId, env: creds.env, apiKeyHelper: creds.apiKeyHelper, browser, record: (rec) => this.boxCliRecord(a.id, rec), connection: (up) => this.boxMachines.connection(machine, up) };
17315
+ let token;
17316
+ return {
17317
+ api,
17318
+ boxId,
17319
+ env: creds.env,
17320
+ apiKeyHelper: creds.apiKeyHelper,
17321
+ browser,
17322
+ record: (rec) => {
17323
+ if (rec) token = rec.token;
17324
+ if (rec || token) this.boxCliRecord(a.id, rec, rec ? void 0 : token);
17325
+ },
17326
+ connection: (up) => this.boxMachines.connection(machine, up)
17327
+ };
17180
17328
  }
17181
17329
  /** A cloud agent's live CLI record changed: kept with them, so a restart picks the CLI up. Gone with no task: the Box can pause. */
17182
- boxCliRecord(agentId, rec) {
17330
+ boxCliRecord(agentId, rec, expectedToken) {
17183
17331
  const a = this.state.agents.find((x) => x.id === agentId);
17184
17332
  if (!a) return;
17333
+ if (!rec && expectedToken && a.boxCli?.token !== expectedToken) return;
17185
17334
  const was = a.boxCli;
17186
17335
  a.boxCli = rec;
17187
17336
  if (rec && was && was.token === rec.token && was.offset === rec.offset && was.busy === rec.busy && was.resumeId === rec.resumeId) return;
17188
17337
  this.save();
17189
- if (!rec && was && !a.task && a.machine && a.host === "box") void this.boxMachines.pause(a.machine).catch(() => void 0);
17338
+ if (!rec && was) this.pauseIdleBox(a);
17190
17339
  }
17191
17340
  /** A machine's Box changed state: its agent's card shows it. */
17192
17341
  boxState(machine) {
@@ -17440,7 +17589,7 @@ var Swarm = class {
17440
17589
  if (patch.cli !== void 0) {
17441
17590
  const cli = isCli(patch.cli) ? patch.cli : "";
17442
17591
  if (a.role === "ceo" && cli && cli !== "claude" && cli !== "opencode") throw new HttpError(400, "The CEO can run Claude Code or OpenCode.");
17443
- const localCli = cli || (a.role === "ceo" ? "claude" : this.state.settings.defaultCli);
17592
+ const localCli = cli || (a.role === "ceo" ? DEFAULT_CEO_CLI : this.state.settings.defaultCli);
17444
17593
  if (a.host !== "box" && (cli || localCli === "opencode") && !this.cliReady(localCli)) throw new HttpError(400, `${cliLabel(localCli)} isn't installed on this computer.`);
17445
17594
  const changed = cli !== a.cli;
17446
17595
  a.cli = cli;
@@ -17479,7 +17628,7 @@ var Swarm = class {
17479
17628
  this.agentRt.get(id)?.terminal?.releaseIdle?.();
17480
17629
  this.agentRt.get(id)?.terminal?.dispose();
17481
17630
  void removeScreens(id);
17482
- void fs21.rm(terminalFile(id), { force: true }).catch(() => void 0);
17631
+ void fs22.rm(terminalFile(id), { force: true }).catch(() => void 0);
17483
17632
  for (const q of this.state.qa) {
17484
17633
  if (q.qaAgentId === id && q.status === "testing") this.setQa(q, { status: "queued", qaAgentId: null });
17485
17634
  if (q.devAgentId === id) q.devAgentId = null;
@@ -17554,6 +17703,7 @@ var Swarm = class {
17554
17703
  }
17555
17704
  }
17556
17705
  ensureUsage(a, kind) {
17706
+ if (this.cloudWorkPaused(a)) throw new HttpError(409, "New cloud work is paused in Settings \u2192 Cloud agents. Running sessions and Box costs are not stopped.");
17557
17707
  if (this.quotaWaiting.has(a.id)) throw new HttpError(409, "This agent has work waiting for a quota reset. Clear the desk to replace it.");
17558
17708
  if (!this.mayStart(kind, a)) throw new HttpError(429, "This AI quota is paused or pacing. See AI usage for the affected resource and reset time.");
17559
17709
  }
@@ -17626,7 +17776,7 @@ var Swarm = class {
17626
17776
  */
17627
17777
  sessionRuntime(a, resume) {
17628
17778
  const inTerminal2 = a.host === "box" || this.state.settings.runtime === "terminal" && this.backend.terminals;
17629
- let cli = !inTerminal2 ? "claude" : a.cli || (a.role === "ceo" ? "claude" : this.state.settings.defaultCli);
17779
+ let cli = !inTerminal2 ? "claude" : a.cli || (a.role === "ceo" ? DEFAULT_CEO_CLI : this.state.settings.defaultCli);
17630
17780
  if (resume && a.sessionCli && a.sessionCli !== cli) {
17631
17781
  if (a.role === "ceo") resume = void 0;
17632
17782
  else if (inTerminal2) cli = a.sessionCli;
@@ -17643,7 +17793,7 @@ var Swarm = class {
17643
17793
  }
17644
17794
  // ---------- terminals ----------
17645
17795
  async loadTerminal(agentId) {
17646
- if (!await fs21.stat(terminalFile(agentId)).catch(() => null)) return null;
17796
+ if (!await fs22.stat(terminalFile(agentId)).catch(() => null)) return null;
17647
17797
  const t = this.newTerminal(agentId);
17648
17798
  await t.load(terminalFile(agentId));
17649
17799
  return t;
@@ -17830,6 +17980,7 @@ var Swarm = class {
17830
17980
  }
17831
17981
  }
17832
17982
  async runTask(a, repo, issue2, note2) {
17983
+ if (this.cloudWorkPaused(a)) return;
17833
17984
  const branch = devBranch(issue2.number, slugify(a.name));
17834
17985
  this.beginTask(
17835
17986
  a,
@@ -17863,6 +18014,10 @@ Note from the manager: ${note2}` : ""
17863
18014
  startAgentSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode = null) {
17864
18015
  const rt = this.agentRt.get(a.id);
17865
18016
  if (!rt || !this.state.agents.includes(a)) return;
18017
+ if (!mode && this.cloudWorkPaused(a)) {
18018
+ this.waitForCloudResume(a, () => this.startAgentSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode));
18019
+ return;
18020
+ }
17866
18021
  if (a.host === "box" && mode !== "reattach") {
17867
18022
  const cli = this.sessionRuntime(a, resumeSessionId).cli ?? "claude";
17868
18023
  const note2 = (text3) => this.appendLog(a, [{ kind: "system", text: text3 }]);
@@ -17882,6 +18037,10 @@ Note from the manager: ${note2}` : ""
17882
18037
  launchSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode, box, linked) {
17883
18038
  const rt = this.agentRt.get(a.id);
17884
18039
  if (!rt || !this.state.agents.includes(a)) return;
18040
+ if (!mode && this.cloudWorkPaused(a)) {
18041
+ this.waitForCloudResume(a, () => this.launchSession(a, repo, cwd, prompt, systemAppend, resumeSessionId, outputSchema, mode, box, linked));
18042
+ return;
18043
+ }
17885
18044
  if (a.host !== "box" && sessionStart(this.backend.deskExists(cwd), mode) === "prepare") {
17886
18045
  if (a.task === "analysis") {
17887
18046
  this.fail(a, { ok: false, text: "", costUsd: 0, turns: 0, errors: ["The analysis checkout is missing. No worktree or dependencies were created."] }, "analysis");
@@ -17955,7 +18114,7 @@ Note from the manager: ${note2}` : ""
17955
18114
  rt.shots.push({ data, mime, url: rt.browserUrl, at });
17956
18115
  if (rt.shots.length > 12) rt.shots.shift();
17957
18116
  this.broadcast({ type: "screen", agentId: a.id, url: rt.browserUrl, at });
17958
- void removeScreens(a.id).then(() => fs21.mkdir(SCREENS_DIR, { recursive: true })).then(() => fs21.writeFile(screenFile(a.id, mime), data)).catch((err) => console.warn("could not save screenshot", err));
18117
+ void removeScreens(a.id).then(() => fs22.mkdir(SCREENS_DIR, { recursive: true })).then(() => fs22.writeFile(screenFile(a.id, mime), data)).catch((err) => console.warn("could not save screenshot", err));
17959
18118
  },
17960
18119
  usage: (observation) => this.recordAiUsage(a, observation),
17961
18120
  usageBatch: (observations) => this.recordAiUsageBatch(a, observations),
@@ -17990,6 +18149,17 @@ Note from the manager: ${note2}` : ""
17990
18149
  this.holdForSignIn(a, cli, again, true);
17991
18150
  }
17992
18151
  async onFinished(a, repo, result) {
18152
+ this.finishingAgents.set(a.id, (this.finishingAgents.get(a.id) ?? 0) + 1);
18153
+ try {
18154
+ await this.finishAgentSession(a, repo, result);
18155
+ } finally {
18156
+ const remaining = this.finishingAgents.get(a.id) - 1;
18157
+ if (remaining) this.finishingAgents.set(a.id, remaining);
18158
+ else this.finishingAgents.delete(a.id);
18159
+ this.pauseIdleBox(a);
18160
+ }
18161
+ }
18162
+ async finishAgentSession(a, repo, result) {
17993
18163
  const rt = this.agentRt.get(a.id);
17994
18164
  if (!rt || !this.state.agents.includes(a)) return;
17995
18165
  if (this.officeUpdate.handedOver && a.host !== "box") return;
@@ -18001,7 +18171,8 @@ Note from the manager: ${note2}` : ""
18001
18171
  a.turns += result.turns;
18002
18172
  recordCost(this.state.ops, repo.id, result.costUsd, a.endedAt);
18003
18173
  this.ledger({ kind: "session", agentId: a.id, key: `${a.id}:${a.startedAt}:${a.endedAt}`, costUsd: result.costUsd, turns: result.turns }, false);
18004
- void this.releaseDesk(a, repo).catch(() => void 0);
18174
+ const released = this.releaseDesk(a, repo).catch(() => void 0);
18175
+ if (a.host === "box") await released;
18005
18176
  if (result.interrupted) this.interrupted(a);
18006
18177
  if (this.dropping.has(a.id)) this.dropTask(a, "\u21BA Cleared desk. Ready for new work.");
18007
18178
  else if (a.task === "analysis") {
@@ -18179,6 +18350,7 @@ Note from the manager: ${note2}` : ""
18179
18350
  return qaSystemPrompt({ agent: a, repo, port: this.port(a), cwd, branch, pr, testStep: testStep2, depsLine: depsPromptLine(deps) });
18180
18351
  }
18181
18352
  async runQa(a, repo, rec) {
18353
+ if (this.cloudWorkPaused(a)) return;
18182
18354
  if (this.backend.allowWork && !this.backend.allowWork("qa", a)) return;
18183
18355
  const branch = qaBranch(rec.prNumber, slugify(a.name));
18184
18356
  this.qaWaits.set(`${repo.id}#${rec.prNumber}`, Date.now() - rec.updatedAt);
@@ -18400,6 +18572,7 @@ ${issue2.body.trim() || "(no description)"}` : ""
18400
18572
  }
18401
18573
  /** Send a failed PR back to the agent who wrote it (or any free agent on the floor). */
18402
18574
  async runFix(dev, repo, rec) {
18575
+ if (this.cloudWorkPaused(dev)) return;
18403
18576
  if (this.backend.allowWork && !this.backend.allowWork("fix", dev)) return;
18404
18577
  const original = rec.devAgentId === dev.id;
18405
18578
  const pull = this.repoRt.get(repo.id)?.pulls.find((p) => p.number === rec.prNumber);
@@ -18604,7 +18777,7 @@ ${text3}` : text3);
18604
18777
  if (typeof patch.managerName === "string") s2.managerName = patch.managerName.trim().slice(0, 40);
18605
18778
  if (typeof patch.companyName === "string") s2.companyName = patch.companyName.trim().slice(0, 60);
18606
18779
  if (typeof patch.dogName === "string") s2.dogName = patch.dogName.trim().slice(0, 24) || DEFAULT_DOG_NAME;
18607
- if (typeof patch.projectsDir === "string" && patch.projectsDir.trim()) s2.projectsDir = path21.resolve(patch.projectsDir.trim());
18780
+ if (typeof patch.projectsDir === "string" && patch.projectsDir.trim()) s2.projectsDir = path22.resolve(patch.projectsDir.trim());
18608
18781
  if (typeof patch.setupDone === "boolean") s2.setupDone = patch.setupDone;
18609
18782
  if (patch.tutorialStep !== void 0) s2.tutorialStep = Math.max(-1, Math.round(Number(patch.tutorialStep)) || 0);
18610
18783
  if (typeof patch.autoUpdate === "boolean") s2.autoUpdate = patch.autoUpdate;
@@ -18744,7 +18917,7 @@ ${text3}` : text3);
18744
18917
  return new QuotaGate(this.state.aiQuotas ??= {});
18745
18918
  }
18746
18919
  usageTool(a) {
18747
- return a.host === "box" || this.state.settings.runtime === "terminal" && this.backend.terminals ? a.cli || (a.role === "ceo" ? "claude" : this.state.settings.defaultCli) : "claude";
18920
+ return a.host === "box" || this.state.settings.runtime === "terminal" && this.backend.terminals ? a.cli || (a.role === "ceo" ? DEFAULT_CEO_CLI : this.state.settings.defaultCli) : "claude";
18748
18921
  }
18749
18922
  resourceFor(a, tool2 = this.usageTool(a)) {
18750
18923
  const model2 = this.modelFor(a, tool2);
@@ -18835,8 +19008,19 @@ ${text3}` : text3);
18835
19008
  }
18836
19009
  return this.usageNow();
18837
19010
  }
18838
- /** May work of this kind start now, as far as Claude's usage goes? */
19011
+ cloudWorkPaused(a) {
19012
+ return a.role !== "ceo" && a.host === "box" && this.state.settings.cloud?.pauseNewWork === true;
19013
+ }
19014
+ waitForCloudResume(a, start) {
19015
+ this.quotaWaiting.set(a.id, start);
19016
+ a.status = "stopped";
19017
+ a.lastError = "New cloud work is paused in Settings \u2192 Cloud agents";
19018
+ this.emitAgent(a);
19019
+ this.save();
19020
+ }
19021
+ /** May work of this kind start now, as far as resource controls and AI usage go? */
18839
19022
  mayStart(kind, a) {
19023
+ if (this.cloudWorkPaused(a)) return false;
18840
19024
  if (this.backend.allowWork && !this.backend.allowWork(kind, a)) return false;
18841
19025
  if (this.configuringOpenCode) return false;
18842
19026
  const key = this.gateKey(a);
@@ -18965,7 +19149,7 @@ ${text3}` : text3);
18965
19149
  this.quotaWaiting.delete(id);
18966
19150
  continue;
18967
19151
  }
18968
- if (!this.slotsFull() && !this.limited(a)) {
19152
+ if (!this.cloudWorkPaused(a) && !this.slotsFull() && !this.limited(a)) {
18969
19153
  this.quotaWaiting.delete(id);
18970
19154
  start();
18971
19155
  }
@@ -19117,7 +19301,7 @@ ${text3}` : text3);
19117
19301
  return this.state.agents.find((a) => a.id === CEO_ID);
19118
19302
  }
19119
19303
  /** The company always has a CEO. One cut off by a server restart picks its job back up. */
19120
- ensureCeo(interrupted) {
19304
+ ensureCeo(interrupted, cli = DEFAULT_CEO_CLI) {
19121
19305
  let a = this.state.agents.find((x) => x.id === CEO_ID);
19122
19306
  if (!a) {
19123
19307
  a = {
@@ -19132,9 +19316,9 @@ ${text3}` : text3);
19132
19316
  hair: "#2b2118",
19133
19317
  skin: pick(SKIN),
19134
19318
  style: null,
19135
- model: CEO_MODEL,
19319
+ model: cli === "claude" ? CEO_MODEL : "",
19136
19320
  effort: CEO_EFFORT,
19137
- cli: "claude",
19321
+ cli,
19138
19322
  machine: null,
19139
19323
  status: "idle",
19140
19324
  issueNumber: null,
@@ -19231,7 +19415,7 @@ ${job.text}` } : job;
19231
19415
  }
19232
19416
  ceoPromptInput(a) {
19233
19417
  const s2 = this.state.settings;
19234
- return { name: a.name, company: s2.companyName, manager: s2.managerName, notesFile: path21.join(CEO_DIR, "NOTES.md"), sessionLimit: s2.sessionLimit, maxAgents: s2.maxAgents, scaling: s2.scaling, cli: s2.runtime === "terminal" && this.backend.terminals ? a.cli || "claude" : "claude", language: languageOf(s2.language) };
19418
+ return { name: a.name, company: s2.companyName, manager: s2.managerName, notesFile: path22.join(CEO_DIR, "NOTES.md"), sessionLimit: s2.sessionLimit, maxAgents: s2.maxAgents, scaling: s2.scaling, cli: s2.runtime === "terminal" && this.backend.terminals ? a.cli || DEFAULT_CEO_CLI : "claude", language: languageOf(s2.language) };
19235
19419
  }
19236
19420
  async runCeoJob(a, job) {
19237
19421
  const rt = this.agentRt.get(a.id);
@@ -19253,7 +19437,7 @@ ${job.text}` } : job;
19253
19437
  this.emitAgent(a);
19254
19438
  this.emitCeo();
19255
19439
  this.save();
19256
- await fs21.mkdir(CEO_DIR, { recursive: true }).catch(() => void 0);
19440
+ await fs22.mkdir(CEO_DIR, { recursive: true }).catch(() => void 0);
19257
19441
  const triage2 = job.kind === "triage" ? await this.triagePr(job) : null;
19258
19442
  if (a.status !== "working") {
19259
19443
  this.state.ceo.job = null;
@@ -20198,7 +20382,7 @@ ${t}`);
20198
20382
  agentSetup(a) {
20199
20383
  const ceo = a.role === "ceo";
20200
20384
  const terminal = a.host === "box" || this.state.settings.runtime === "terminal" && this.backend.terminals;
20201
- const cli = terminal ? a.cli || (ceo ? "claude" : this.state.settings.defaultCli) : "claude";
20385
+ const cli = terminal ? a.cli || (ceo ? DEFAULT_CEO_CLI : this.state.settings.defaultCli) : "claude";
20202
20386
  return {
20203
20387
  codingAgent: cli,
20204
20388
  model: this.modelFor(a, cli) || "the coding agent default",
@@ -20631,16 +20815,16 @@ app.post("/api/repos/:repo/decor/buy", route((req) => swarm.buyDecoration(repoId
20631
20815
  app.post("/api/repos/:repo/decor/place", route((req) => swarm.placeDecoration(repoId(req), req.body ?? {})));
20632
20816
  app.post("/api/progress/coffee", route((req) => swarm.drankCoffee(req.body?.id)));
20633
20817
  app.post("/api/progress/demo", route((req) => swarm.demoProgress(req.body ?? {})));
20634
- var dist = path22.resolve(import.meta.dirname, "../dist");
20635
- if (fs22.existsSync(dist)) {
20818
+ var dist = path23.resolve(import.meta.dirname, "../dist");
20819
+ if (fs23.existsSync(dist)) {
20636
20820
  app.get("/sw.js", (_req, res) => {
20637
- const html = fs22.readFileSync(path22.join(dist, "index.html"), "utf8");
20821
+ const html = fs23.readFileSync(path23.join(dist, "index.html"), "utf8");
20638
20822
  res.setHeader("Content-Type", "text/javascript; charset=utf-8");
20639
20823
  res.setHeader("Cache-Control", "no-cache");
20640
20824
  res.end(serviceWorkerSource(swVersion(html, VERSION, swarm.officeCommit())));
20641
20825
  });
20642
20826
  app.use(express.static(dist));
20643
- app.get(/^(?!\/api).*/, (_req, res) => res.sendFile(path22.join(dist, "index.html")));
20827
+ app.get(/^(?!\/api).*/, (_req, res) => res.sendFile(path23.join(dist, "index.html")));
20644
20828
  }
20645
20829
  app.use((err, _req, res, _next) => {
20646
20830
  const parserStatus = err?.status;