droidsembly 0.4.0-beta.2 → 0.4.0-beta.4

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 (59) hide show
  1. package/README.it.md +1 -2
  2. package/README.md +1 -2
  3. package/dist/assets/{AccessibilitySettings-BE7rmk0y.js → AccessibilitySettings-6ZCswq5I.js} +3 -3
  4. package/dist/assets/{AppViewer-BINNxHVf.js → AppViewer-CqGa1r0z.js} +1 -1
  5. package/dist/assets/{Balloon-jPkIBPvT.js → Balloon-dO9J4khp.js} +1 -1
  6. package/dist/assets/{Batched-DL3cFl-z.js → Batched-CmXZtCvQ.js} +1 -1
  7. package/dist/assets/{Birds-9cXj_YEG.js → Birds-D51xGT0l.js} +1 -1
  8. package/dist/assets/{Blimp-Ci1lo_c7.js → Blimp-C2c_AKRR.js} +1 -1
  9. package/dist/assets/{BufferGeometryUtils-Dk96On2P.js → BufferGeometryUtils-Dcu0heeS.js} +1 -1
  10. package/dist/assets/{Duck-BMxCVlmW.js → Duck-CzFiUF6U.js} +1 -1
  11. package/dist/assets/{Effects-Crrr3ggK.js → Effects-DwOi-gSQ.js} +1 -1
  12. package/dist/assets/{Fireworks-ddjyPNX6.js → Fireworks-Cc2mGzPJ.js} +1 -1
  13. package/dist/assets/{Helicopter-CX-86eGa.js → Helicopter-ltB-x8hG.js} +1 -1
  14. package/dist/assets/{Hurricane-CLANwn_b.js → Hurricane-C2qHsRw4.js} +1 -1
  15. package/dist/assets/{Kaiju-BCMy-uRo.js → Kaiju-DPHVjFjg.js} +1 -1
  16. package/dist/assets/{Meteors-CiJzDtSj.js → Meteors-CxcguXTJ.js} +1 -1
  17. package/dist/assets/{MissionConsole-CJb-BlEJ.js → MissionConsole-BUE2mijT.js} +1 -1
  18. package/dist/assets/{Office-bAhOa_1d.js → Office-NV5zlSnK.js} +8 -8
  19. package/dist/assets/{PhotoPanel-Bj8-zSMr.js → PhotoPanel-CDqgU99Z.js} +1 -1
  20. package/dist/assets/{PhotoScene-Da13U_uP.js → PhotoScene-RRXC4_Jv.js} +3 -3
  21. package/dist/assets/{Plane-DcyLXU5f.js → Plane-BQB72TWZ.js} +1 -1
  22. package/dist/assets/{Pocket-C3fEmnP6.js → Pocket-CjK6fv97.js} +2 -2
  23. package/dist/assets/{Rainbow-CiwNa4iX.js → Rainbow-DIpZi5-z.js} +1 -1
  24. package/dist/assets/{Roof-DDYcam5j.js → Roof-Cd9I0jtG.js} +1 -1
  25. package/dist/assets/{Shell-CjHm9J8I.js → Shell-DCqHgrm_.js} +1 -1
  26. package/dist/assets/{Skywriting-BD1rTdRn.js → Skywriting-BH6FCdEl.js} +1 -1
  27. package/dist/assets/TerminalView-CoH1yh6r.js +17 -0
  28. package/dist/assets/{ToyWorld-NbwEfz8w.js → ToyWorld--k4uqi9k.js} +1 -1
  29. package/dist/assets/{Ufo-DlOMBNSX.js → Ufo-C5cYunS9.js} +1 -1
  30. package/dist/assets/{Whale-BpAZmX5F.js → Whale-BAXeezd8.js} +1 -1
  31. package/dist/assets/{all-D96CQm6h.js → all-BsJ98bWd.js} +1 -1
  32. package/dist/assets/{bloomMarks-DO_1Aa_j.js → bloomMarks-JYeAmd4d.js} +1 -1
  33. package/dist/assets/{cheerRules-DNkiE7MG.js → cheerRules-DvM2z9Qg.js} +1 -1
  34. package/dist/assets/{cityLayout-BwjgCIoW.js → cityLayout-VU-ug-r6.js} +1 -1
  35. package/dist/assets/{dogState-_4V3U3Ki.js → dogState-Bm3YZHwy.js} +1 -1
  36. package/dist/assets/{doors-BLqiDSGY.js → doors-D7Z3s-7W.js} +1 -1
  37. package/dist/assets/{gallery-CVQaqgJI.js → gallery-CSWmy4Tf.js} +1 -1
  38. package/dist/assets/{gate-B1SWzR3V.js → gate-DwsbbSNS.js} +2 -2
  39. package/dist/assets/{index-BSf1g_FE.js → index-D_Et7Vx8.js} +3 -3
  40. package/dist/assets/{instantReplay-Cuo_dJ0Q.js → instantReplay-FXf2kJ7B.js} +1 -1
  41. package/dist/assets/{interact-2xHzPlZG.js → interact-BatJVhca.js} +1 -1
  42. package/dist/assets/{kit-Cx-l6IRN.js → kit-D3twk12W.js} +1 -1
  43. package/dist/assets/{mic-ChYpSk7U.js → mic-BJ0eYLIj.js} +1 -1
  44. package/dist/assets/{photoMode-7LqNRqz9.js → photoMode-B8pRCF0O.js} +1 -1
  45. package/dist/assets/{pipeline-DWfp7bcu.js → pipeline-BgOS9JnJ.js} +1 -1
  46. package/dist/assets/{rapier-D3erQ37Q.js → rapier-BvQbKz0M.js} +1 -1
  47. package/dist/assets/{rig-CXpaDXip.js → rig-BgSxc8mA.js} +1 -1
  48. package/dist/assets/{speechLanguage-CsSMLLpg.js → speechLanguage-Cak8tdL0.js} +1 -1
  49. package/dist/assets/store-Buxt6UcJ.js +5 -0
  50. package/dist/assets/{useDayTime-DQo6X8vh.js → useDayTime-0ms3va3h.js} +1 -1
  51. package/dist/assets/{useGraphics-B19_wbNT.js → useGraphics-p7LAuvYj.js} +1 -1
  52. package/dist/assets/{voiceMessages-BNuAZiGC.js → voiceMessages-hO1SDnOS.js} +1 -1
  53. package/dist/assets/{weatherState-BmCM8XlW.js → weatherState-BQ3UU4vU.js} +1 -1
  54. package/dist/index.html +2 -2
  55. package/dist-server/index.js +686 -94
  56. package/dist-server/index.js.map +4 -4
  57. package/package.json +1 -1
  58. package/dist/assets/TerminalView-nREejrGe.js +0 -17
  59. package/dist/assets/store-CWHb7890.js +0 -5
@@ -846,17 +846,18 @@ async function repoMeta(fullName) {
846
846
  "view",
847
847
  fullName,
848
848
  "--json",
849
- "nameWithOwner,description,url,defaultBranchRef"
849
+ "nameWithOwner,description,url,defaultBranchRef,isPrivate"
850
850
  ]);
851
851
  return {
852
+ isPrivate: raw.isPrivate,
852
853
  nameWithOwner: raw.nameWithOwner,
853
854
  description: raw.description ?? "",
854
855
  url: raw.url,
855
856
  defaultBranch: raw.defaultBranchRef?.name || "main"
856
857
  };
857
858
  }
858
- async function listIssues(fullName) {
859
- const raw = await readTwice(
859
+ async function listIssues(fullName, read = readTwice) {
860
+ const raw = await read(
860
861
  () => ghJson(
861
862
  ["issue", "list", "-R", fullName, "--state", "open", "--limit", "100", "--json", "number,title,body,url,labels,createdAt"],
862
863
  SYNC_READ
@@ -906,10 +907,10 @@ function toPull(p) {
906
907
  checkRun: checkRunOf(p.statusCheckRollup)
907
908
  };
908
909
  }
909
- async function listPulls(fullName) {
910
+ async function listPulls(fullName, read = readTwice) {
910
911
  const [open, merged2] = await Promise.all([
911
- readTwice(() => ghJson(["pr", "list", "-R", fullName, "--state", "open", "--limit", "50", "--json", PR_FIELDS], SYNC_READ)),
912
- readTwice(() => ghJson(["pr", "list", "-R", fullName, "--state", "merged", "--limit", "8", "--json", PR_FIELDS], SYNC_READ))
912
+ read(() => ghJson(["pr", "list", "-R", fullName, "--state", "open", "--limit", "50", "--json", PR_FIELDS], SYNC_READ)),
913
+ read(() => ghJson(["pr", "list", "-R", fullName, "--state", "merged", "--limit", "8", "--json", PR_FIELDS], SYNC_READ))
913
914
  ]);
914
915
  return [...open, ...merged2].map(toPull);
915
916
  }
@@ -1375,9 +1376,9 @@ async function checkOpenCodeVersion(cmd) {
1375
1376
  const version = await run(cmd.file, [...cmd.args, "--version"], { timeoutMs: 2e4 }).catch(() => null);
1376
1377
  return openCodeVersionProblem(version);
1377
1378
  }
1378
- async function detectClis() {
1379
+ async function detectClis(ids) {
1379
1380
  return Promise.all(
1380
- CLIS.map(async (c) => {
1381
+ CLIS.filter((c) => !ids || ids.includes(c.id)).map(async (c) => {
1381
1382
  const cmd = commandFor(c.id);
1382
1383
  const version = cmd ? await run(cmd.file, [...cmd.args, "--version"], { timeoutMs: 2e4 }).catch(() => null) : null;
1383
1384
  const problem = c.id === "opencode" && cmd ? openCodeVersionProblem(version) : null;
@@ -1386,6 +1387,7 @@ async function detectClis() {
1386
1387
  );
1387
1388
  }
1388
1389
  var BOX_CODEX_VERSION = "0.163.0";
1390
+ var BOX_OPENCODE_VERSION = "2.2.6";
1389
1391
  function packageField(pkg, field) {
1390
1392
  try {
1391
1393
  let dir = path4.dirname(createRequire2(import.meta.url).resolve(pkg));
@@ -1405,7 +1407,8 @@ function boxVersions() {
1405
1407
  return {
1406
1408
  claude: packageField("@anthropic-ai/claude-agent-sdk", "claudeCodeVersion") ?? "latest",
1407
1409
  playwrightMcp: packageField("@playwright/mcp", "version") ?? "latest",
1408
- codex: BOX_CODEX_VERSION
1410
+ codex: BOX_CODEX_VERSION,
1411
+ opencode: BOX_OPENCODE_VERSION
1409
1412
  };
1410
1413
  }
1411
1414
  function localUrl(p, env = process.env) {
@@ -1490,11 +1493,16 @@ function launchArgs(id, ctx) {
1490
1493
  };
1491
1494
  const config = {
1492
1495
  $schema: "https://opencode.ai/config.json",
1493
- plugins: [{ package: ctx.plugin, options: { sessionID, notifyUrl: ctx.notify.url, model: openCodeModelRef(model2) } }],
1496
+ plugins: [{ package: ctx.plugin, options: { sessionID, ...ctx.posix ? { eventsFile: ctx.notify.url } : { notifyUrl: ctx.notify.url }, model: openCodeModelRef(model2) } }],
1494
1497
  instructions: [ctx.files.system],
1495
1498
  // A dedicated primary agent also retains a model's explicit #variant (the root model setting doesn't).
1496
- default_agent: "cubefarm",
1497
- agents: { cubefarm: { description: "The Droidsembly office session", mode: "primary", ...model2 ? { model: model2 } : {} } },
1499
+ default_agent: "droidsembly",
1500
+ agents: {
1501
+ droidsembly: { description: "The Droidsembly office session", mode: "primary", ...model2 ? { model: model2 } : {}, ...ctx.openCodePermissions ? { permissions: ctx.openCodePermissions } : {} },
1502
+ // OpenCode keeps the agent ID on an existing session. Keep the old profile available on resume,
1503
+ // but out of the picker: do not migrate session IDs or rewrite the user's OpenCode history.
1504
+ ...ctx.resumeId ? { cubefarm: { description: "The Droidsembly office session (legacy)", mode: "primary", hidden: true, ...model2 ? { model: model2 } : {}, ...ctx.openCodePermissions ? { permissions: ctx.openCodePermissions } : {} } } : {}
1505
+ },
1498
1506
  ...opencodeLocal(local),
1499
1507
  ...Object.keys(servers).length ? { mcp: { servers } } : {}
1500
1508
  };
@@ -1612,12 +1620,19 @@ var OPENCODE_PLUGIN_SOURCE = String.raw`// cubefarm: forward only this office se
1612
1620
  export default {
1613
1621
  id: 'cubefarm.office',
1614
1622
  async setup(ctx) {
1615
- const { sessionID, notifyUrl } = ctx.options;
1616
- if (!sessionID || !notifyUrl) throw new Error('Missing Droidsembly callback configuration');
1623
+ const { sessionID, notifyUrl, eventsFile } = ctx.options;
1624
+ if (!sessionID || (!notifyUrl && !eventsFile)) throw new Error('Missing Droidsembly callback configuration');
1625
+ const fs = eventsFile ? await import('node:fs') : null;
1617
1626
  const controller = new AbortController();
1618
1627
  let lastIdle;
1628
+ let authFailed = false;
1619
1629
  const reportedUsage = new Map();
1620
1630
  const post = async (body) => {
1631
+ if (fs) {
1632
+ const line = JSON.stringify({ ...body, session_id: sessionID }).replace(/[\u007f-￿]/g, (c) => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0'));
1633
+ fs.appendFileSync(eventsFile, line + '\n');
1634
+ return;
1635
+ }
1621
1636
  const response = await fetch(notifyUrl, {
1622
1637
  method: 'POST', headers: { 'content-type': 'application/json' },
1623
1638
  body: JSON.stringify({ ...body, session_id: sessionID }),
@@ -1662,7 +1677,10 @@ export default {
1662
1677
  };
1663
1678
  await observe('model.request', (event) => reportResource(event));
1664
1679
  await observe('http.response', async (event) => {
1665
- if (event.sessionID !== sessionID || event.response.status !== 429) return;
1680
+ if (event.sessionID !== sessionID) return;
1681
+ if (event.response.status === 401) authFailed = true;
1682
+ else if (event.response.status < 400) authFailed = false;
1683
+ if (event.response.status !== 429) return;
1666
1684
  const retry = event.response.headers.get('retry-after');
1667
1685
  const seconds = retry && /^\d+(?:\.\d+)?$/.test(retry) ? Number(retry) : NaN;
1668
1686
  const at = Number.isFinite(seconds) ? Date.now() + seconds * 1000 : retry ? Date.parse(retry) : NaN;
@@ -1675,6 +1693,13 @@ export default {
1675
1693
  for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
1676
1694
  const props = event.data ?? event.properties ?? event;
1677
1695
  if ((props.sessionID ?? props.info?.id ?? props.session?.id) !== sessionID) continue;
1696
+ if (eventsFile && ['session.tool.called', 'session.tool.success', 'session.tool.failed'].includes(event.type)) {
1697
+ // Tool names only: do not copy tool arguments, output, credentials or private reasoning into telemetry.
1698
+ const messages = await ctx.session.context({ sessionID });
1699
+ const tool = messages.flatMap(m => m.type === 'assistant' ? m.content ?? [] : []).find(p => p.type === 'tool' && p.id === props.id);
1700
+ if (tool) await post({ hook_event_name: event.type === 'session.tool.called' ? 'PreToolUse' : event.type === 'session.tool.failed' ? 'PostToolUseFailure' : 'PostToolUse', tool_name: tool.name, tool_use_id: props.id, ...(event.type === 'session.tool.failed' ? { error: 'Tool failed (see the remote terminal)' } : {}) });
1701
+ continue;
1702
+ }
1678
1703
  if (!['session.execution.succeeded', 'session.execution.failed', 'session.execution.interrupted', 'session.idle'].includes(event.type)) continue;
1679
1704
  const [messages, session] = await Promise.all([
1680
1705
  ctx.session.context({ sessionID }), ctx.session.get({ sessionID }),
@@ -1706,7 +1731,7 @@ export default {
1706
1731
  if (outcome === 'interrupted') {
1707
1732
  await post({ hook_event_name: 'Interrupt' });
1708
1733
  } else if (outcome === 'failed') {
1709
- await post({ hook_event_name: 'TurnError', error: JSON.stringify(props.error ?? idle?.error ?? 'OpenCode session failed') });
1734
+ await post({ hook_event_name: 'TurnError', error: JSON.stringify(props.error ?? idle?.error ?? 'OpenCode session failed'), ...(eventsFile && authFailed ? { signed_out: true } : {}) });
1710
1735
  } else {
1711
1736
  const user = messages.findLastIndex((m) => m.type === 'user');
1712
1737
  const reply = messages.slice(user + 1).findLast((m) => m.type === 'assistant');
@@ -2228,7 +2253,7 @@ function decoder(onText) {
2228
2253
  if (text3) onText(text3);
2229
2254
  };
2230
2255
  }
2231
- function upstashBoxes(apiKey) {
2256
+ function upstashBoxes(apiKey, options = {}) {
2232
2257
  const conn2 = { apiKey, enableTelemetry: false };
2233
2258
  const boxes = /* @__PURE__ */ new Map();
2234
2259
  const box = async (id) => {
@@ -2268,7 +2293,7 @@ function upstashBoxes(apiKey) {
2268
2293
  return {
2269
2294
  list: () => guard("list your Boxes", async () => (await Box.list(conn2)).map((d) => ({ id: d.id, name: d.name ?? "", labels: d.labels ?? [], status: state(d.status) }))),
2270
2295
  create: (o) => guard("create a Box", async () => {
2271
- const b = await Box.create({ ...conn2, name: o.name, labels: o.labels, size: o.size, runtime: "node", browser: true, timeout: 3e5 });
2296
+ const b = await Box.create({ ...conn2, name: o.name, labels: o.labels, size: o.size, runtime: "node", browser: o.browser ?? options.browser ?? true, keepAlive: false, timeout: 3e5 });
2272
2297
  boxes.set(b.id, b);
2273
2298
  return { id: b.id, name: o.name, labels: o.labels, status: "running" };
2274
2299
  }),
@@ -2295,9 +2320,16 @@ function upstashBoxes(apiKey) {
2295
2320
  run: (id, script, o = {}) => guard("run a command in a Box", async () => {
2296
2321
  let output = "";
2297
2322
  const s2 = await openSession(id, { cmd: script, env: o.env, onData: (t) => output += t });
2298
- const timer = setTimeout(() => s2.close(), o.timeoutMs ?? 6e5);
2323
+ let timedOut = false;
2324
+ const timer = setTimeout(() => {
2325
+ timedOut = true;
2326
+ s2.close();
2327
+ }, o.timeoutMs ?? 6e5);
2299
2328
  try {
2300
- return { code: await s2.done, output };
2329
+ const code = await s2.done;
2330
+ if (timedOut) throw new CloudError("The Box command timed out before a verified exit status was received.", "other");
2331
+ if (!Number.isInteger(code) || code < 0 || code > 255) throw new CloudError("The Box command ended without a verified exit status. Its outcome is unknown.", "other");
2332
+ return { code, output };
2301
2333
  } finally {
2302
2334
  clearTimeout(timer);
2303
2335
  }
@@ -2366,7 +2398,7 @@ function resolveCredentials(cli, i) {
2366
2398
  } else if (cli === "codex") {
2367
2399
  if (i.secrets.openaiApiKey) Object.assign(env, { OPENAI_API_KEY: i.secrets.openaiApiKey, CODEX_API_KEY: i.secrets.openaiApiKey });
2368
2400
  else ownLogin = true;
2369
- }
2401
+ } else if (cli === "opencode") ownLogin = true;
2370
2402
  return { env, apiKeyHelper, ownLogin, missing };
2371
2403
  }
2372
2404
  function githubEnv(i) {
@@ -2399,10 +2431,10 @@ var Cloud = class {
2399
2431
  ghAt = 0;
2400
2432
  boxes = null;
2401
2433
  async init() {
2402
- const s2 = await readSecrets(this.deps.secretsFile);
2434
+ const s2 = this.deps.credentials ?? await readSecrets(this.deps.secretsFile);
2403
2435
  for (const k of ["upstashBoxKey", "cloudGithubToken", "anthropicApiKey", "openaiApiKey"]) if (typeof s2[k] === "string" && s2[k]) this.secrets[k] = s2[k];
2404
2436
  if (this.secrets.upstashBoxKey) this.api = this.deps.boxes(this.secrets.upstashBoxKey);
2405
- await this.refreshGh(true);
2437
+ if (!this.secrets.cloudGithubToken) await this.refreshGh(true);
2406
2438
  }
2407
2439
  /** The Box API, or null while no key is saved. */
2408
2440
  boxApi() {
@@ -2411,6 +2443,7 @@ var Cloud = class {
2411
2443
  claudeToken = () => (this.deps.env[CLAUDE_TOKEN_ENV] ?? "").trim();
2412
2444
  /** The gh login token, re-read at most once a minute (the manager may sign in or out meanwhile). */
2413
2445
  async refreshGh(force = false) {
2446
+ if (this.deps.credentials) return "";
2414
2447
  if (!force && Date.now() - this.ghAt < 6e4) return this.gh;
2415
2448
  this.ghAt = Date.now();
2416
2449
  this.gh = await this.deps.ghToken().catch(() => "");
@@ -2442,6 +2475,7 @@ var Cloud = class {
2442
2475
  }
2443
2476
  /** PUT /api/cloud/key: '' disconnects; anything else must list the account's Boxes first. */
2444
2477
  async setKey(raw) {
2478
+ if (this.deps.credentials) throw new HttpError(409, "This isolated run uses in-memory credentials; changing or saving them is disabled.");
2445
2479
  const key = raw.trim();
2446
2480
  if (key) {
2447
2481
  if (key.length > 400 || /\s/.test(key)) throw new HttpError(400, "That doesn't look like an Upstash Box API key.");
@@ -2462,6 +2496,7 @@ var Cloud = class {
2462
2496
  }
2463
2497
  /** PUT /api/cloud/token: a GitHub token, an Anthropic or an OpenAI API key for cloud agents ('' removes it). */
2464
2498
  async setToken(kind, raw) {
2499
+ if (this.deps.credentials) throw new HttpError(409, "This isolated run uses in-memory credentials; changing or saving them is disabled.");
2465
2500
  const value = raw.trim();
2466
2501
  if (value.length > 400 || /\s/.test(value)) throw new HttpError(400, "That doesn't look like a token or an API key.");
2467
2502
  if (kind === "anthropic" && value.startsWith("sk-ant-oat")) {
@@ -2549,7 +2584,7 @@ var BRANCH = /^[\w./-]+$/;
2549
2584
  function checkRepo(fullName) {
2550
2585
  if (!OWNER_REPO.test(fullName)) throw new Error(`Not a GitHub repository name: ${fullName}`);
2551
2586
  }
2552
- var setupMarker = (v, rev) => `${BOX_CF}/setup-${rev}-${v.claude}-${v.playwrightMcp}-${v.codex}`.replace(/[^\w./-]/g, "_");
2587
+ var setupMarker = (v, rev, cli, browser = false) => (cli ? `${BOX_CF}/setup-${rev}-${cli}-${v[cli]}${browser ? `-browser-${v.playwrightMcp}` : ""}` : `${BOX_CF}/setup-${rev}-${v.claude}-${v.playwrightMcp}-${v.codex}-${v.opencode}`).replace(/[^\w./-]/g, "_");
2553
2588
  var TMUX_CONF = [
2554
2589
  "set -g status off",
2555
2590
  "set -g prefix None",
@@ -2564,31 +2599,45 @@ var TMUX_CONF = [
2564
2599
  ""
2565
2600
  ].join("\n");
2566
2601
  function setupScript(o) {
2567
- const marker = setupMarker(o.versions, o.rev);
2568
- const pkgs = [`@anthropic-ai/claude-code@${o.versions.claude}`, `@playwright/mcp@${o.versions.playwrightMcp}`, `@openai/codex@${o.versions.codex}`];
2602
+ const marker2 = setupMarker(o.versions, o.rev, o.cli, o.browser);
2603
+ const selected = o.cli ? [o.cli] : ["claude", "codex", "opencode"];
2604
+ const packages = { claude: `@anthropic-ai/claude-code@${o.versions.claude}`, codex: `@openai/codex@${o.versions.codex}`, opencode: `@opencode/cli@${o.versions.opencode}` };
2605
+ const browser = !o.cli || o.browser === true;
2606
+ const pkgs = o.cli ? [...selected.map((cli) => packages[cli]), ...browser ? [`@playwright/mcp@${o.versions.playwrightMcp}`] : []] : [packages.claude, `@playwright/mcp@${o.versions.playwrightMcp}`, packages.codex, packages.opencode];
2607
+ const bins = [...selected, ...browser ? ["playwright-mcp"] : []];
2608
+ const verify = [
2609
+ `for c in ${bins.join(" ")}; do test -x ${sq(BOX_CLI_BIN)}/$c || { echo "$c was not installed" >&2; exit 4; }; done`,
2610
+ ...selected.includes("opencode") ? [`V="$("${BOX_CLI_BIN}/opencode" --version)"; case "$V" in ${[o.versions.opencode, `v${o.versions.opencode}`, `opencode ${o.versions.opencode}`, `opencode v${o.versions.opencode}`].map(sq).join("|")}) ;; *) echo "OpenCode version mismatch" >&2; exit 4;; esac`] : []
2611
+ ];
2569
2612
  const helper = `!f() { test "$1" = get || exit 0; echo username=x-access-token; echo "password=$GH_TOKEN"; }; f`;
2570
2613
  return [
2571
2614
  "set -e",
2572
- `mkdir -p ${sq(BOX_BIN)} ${sq(BOX_SESSIONS)}`,
2573
- `if [ -f ${sq(marker)} ]; then echo CUBEFARM_SETUP_OK; exit 0; fi`,
2615
+ `mkdir -p ${sq(`${BOX_BIN}/opencode-plugin`)} ${sq(BOX_SESSIONS)}`,
2616
+ `if [ -f ${sq(marker2)} ]; then`,
2617
+ ...verify,
2618
+ "echo CUBEFARM_SETUP_OK; exit 0; fi",
2619
+ 'command -v node >/dev/null && command -v npm >/dev/null || { echo "Node/npm are required" >&2; exit 3; }',
2574
2620
  'missing=""',
2575
- 'for t in tmux lsof gh; do command -v "$t" >/dev/null 2>&1 || missing="$missing $t"; done',
2621
+ 'for t in tmux lsof gh git; do command -v "$t" >/dev/null 2>&1 || missing="$missing $t"; done',
2576
2622
  'if [ -n "$missing" ]; then',
2577
- " sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq >/dev/null 2>&1 || true",
2578
- " sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq $missing >/dev/null 2>&1 || true",
2623
+ " sudo -n env DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=0 -o APT::Update::Error-Mode=any update -qq",
2624
+ " sudo -n env DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=0 -o DPkg::Lock::Timeout=0 install -y --no-install-recommends $missing",
2579
2625
  "fi",
2580
2626
  'command -v tmux >/dev/null 2>&1 || { echo "tmux could not be installed in the Box" >&2; exit 3; }',
2581
2627
  // Into the office's own folder, not the image's global one: the Box image ships its own CLIs first on the PATH.
2582
- `npm install -g --prefix ${sq(`${BOX_CF}/cli`)} --no-fund --no-audit --loglevel=error ${pkgs.map(sq).join(" ")} > /tmp/cubefarm-cli.log 2>&1 || { tail -n 5 /tmp/cubefarm-cli.log >&2; exit 4; }`,
2583
- `for c in claude codex playwright-mcp; do test -x ${sq(BOX_CLI_BIN)}/$c || { echo "$c was not installed" >&2; exit 4; }; done`,
2628
+ `npm install -g --prefix ${sq(`${BOX_CF}/cli`)} --fetch-retries=0 --no-fund --no-audit --loglevel=error ${pkgs.map(sq).join(" ")} > /tmp/cubefarm-cli.log 2>&1 || { tail -n 5 /tmp/cubefarm-cli.log >&2; exit 4; }`,
2629
+ ...verify,
2630
+ ...selected.includes("opencode") ? [
2631
+ `mkdir -p ${sq(`${BOX_CF}/opencode/config/opencode`)}`,
2632
+ `test -f ${sq(`${BOX_CF}/opencode/config/opencode/opencode.json`)} || printf '%s' '{"update":"disable"}' > ${sq(`${BOX_CF}/opencode/config/opencode/opencode.json`)}`
2633
+ ] : [],
2584
2634
  "git config --global --unset-all credential.helper >/dev/null 2>&1 || true",
2585
2635
  `git config --global credential.https://github.com.helper ${sq(helper)}`,
2586
2636
  `git config --global user.name ${sq(o.gitName || "cubefarm")}`,
2587
2637
  `git config --global user.email ${sq(o.gitEmail || "cubefarm@users.noreply.github.com")}`,
2588
2638
  "git config --global init.defaultBranch main",
2589
2639
  "git config --global advice.detachedHead false",
2590
- `rm -f ${sq(BOX_CF)}/setup-*`,
2591
- `touch ${sq(marker)}`,
2640
+ `touch ${sq(marker2)}`,
2592
2641
  "echo CUBEFARM_SETUP_OK"
2593
2642
  ].join("\n");
2594
2643
  }
@@ -2599,6 +2648,7 @@ function prepareDeskScript(fullName, base, branch) {
2599
2648
  const desk = boxDeskDir(fullName);
2600
2649
  const ref = base.pr ? `origin/pr/${base.pr}` : `origin/${base.defaultBranch}`;
2601
2650
  return [
2651
+ "(",
2602
2652
  "set -e",
2603
2653
  `R=${sq(repo)}`,
2604
2654
  `W=${sq(desk)}`,
@@ -2626,7 +2676,8 @@ function prepareDeskScript(fullName, base, branch) {
2626
2676
  "fi",
2627
2677
  'rm -rf "$W"; mkdir -p "$(dirname "$W")"',
2628
2678
  'git worktree add -q -B "$B" "$W" "$REF"',
2629
- 'echo "$W"'
2679
+ 'echo "$W"',
2680
+ ")"
2630
2681
  ].join("\n");
2631
2682
  }
2632
2683
  function linkedReposScript(fullNames) {
@@ -2705,12 +2756,12 @@ function signInOutcome(output) {
2705
2756
  const last = output.split("\n").map((l) => l.trim()).filter((l) => /^CUBEFARM_SIGNED_(IN|OUT)$/.test(l)).pop();
2706
2757
  return last ? last === "CUBEFARM_SIGNED_IN" : null;
2707
2758
  }
2708
- var signOutScript = (cli) => `${sq(`${BOX_CLI_BIN}/${cli}`)} ${cli === "claude" ? "auth logout" : "logout"} >/dev/null 2>&1; true`;
2709
- var signInCommand = (cli) => ({ file: `${BOX_CLI_BIN}/${cli}`, args: cli === "claude" ? ["auth", "login"] : ["login", "--device-auth"] });
2759
+ var signOutScript = (cli) => cli === "opencode" ? "true" : `${sq(`${BOX_CLI_BIN}/${cli}`)} ${cli === "claude" ? "auth logout" : "logout"} >/dev/null 2>&1; true`;
2760
+ var signInCommand = (cli) => ({ file: `${BOX_CLI_BIN}/${cli}`, args: cli === "codex" ? ["login", "--device-auth"] : ["auth", "login"] });
2710
2761
 
2711
2762
  // server/boxCli.ts
2712
2763
  var BOX_CDP = "http://127.0.0.1:9222";
2713
- var TURN_ENDS = ["Stop", "StopFailure", "TurnComplete"];
2764
+ var TURN_ENDS = ["Stop", "StopFailure", "TurnComplete", "TurnError", "Interrupt"];
2714
2765
  var EventLines = class {
2715
2766
  /** turnAt: where the last turn end seen starts (see BoxCliRecord.turnAt). */
2716
2767
  constructor(offset = 0, turnAt = offset) {
@@ -2791,7 +2842,11 @@ var BoxPty = class {
2791
2842
  replay(events, at) {
2792
2843
  void hooksOpen.then(() => {
2793
2844
  if (this.stopped) return;
2794
- for (const e of events) if (e.hook_event_name !== "CubefarmExit") this.o.event(e);
2845
+ for (const e of events) {
2846
+ if (this.stopped || this.exited) return;
2847
+ if (e.hook_event_name !== "CubefarmExit") this.o.event(e);
2848
+ }
2849
+ if (this.stopped || this.exited) return;
2795
2850
  this.lines = new EventLines(at.offset, at.turnAt);
2796
2851
  this.o.save(at.offset, at.turnAt, this.meta);
2797
2852
  setTimeout(() => this.fireExit(exitCode(events) ?? (finishedTurn(events) ? 0 : -1)), 6e3);
@@ -2860,9 +2915,11 @@ var BoxPty = class {
2860
2915
  if (this.stopped || this.exited) return;
2861
2916
  let exit = null;
2862
2917
  for (const e of this.lines.push(text3)) {
2918
+ if (this.stopped || this.exited) return;
2863
2919
  if (e.hook_event_name === "CubefarmExit") exit = Number(e.code) || 0;
2864
2920
  else this.o.event(e);
2865
2921
  }
2922
+ if (this.stopped || this.exited) return;
2866
2923
  this.o.save(this.lines.offset, this.lines.turnAt, this.meta);
2867
2924
  if (exit !== null) this.fireExit(exit);
2868
2925
  }
@@ -2943,6 +3000,168 @@ async function sweepStrayClis(api, boxId, keepTokens) {
2943
3000
  return n;
2944
3001
  }
2945
3002
 
3003
+ // server/boxSessionFiles.ts
3004
+ var marker = "/* DS_BOX_SESSION_FILES */\n";
3005
+ var allowed = /* @__PURE__ */ new Set(["settings.json", "mcp.json", "instructions.md", "task.md", "launch.json"]);
3006
+ function boxSessionFilesScripts(directory, files) {
3007
+ if (!new RegExp(`^${BOX_CF.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/sessions/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$`).test(directory)) throw new Error("Invalid remote session directory");
3008
+ const seen = /* @__PURE__ */ new Set(), scripts = [];
3009
+ for (const [file, text3] of files) {
3010
+ const name = file.slice(directory.length + 1);
3011
+ if (file !== directory + "/" + name || !allowed.has(name) || seen.has(name) || typeof text3 !== "string") throw new Error("Invalid remote session file");
3012
+ seen.add(name);
3013
+ const bytes = Buffer.from(text3, "utf8");
3014
+ for (let offset = 0; offset === 0 || offset < bytes.length; offset += 16384) {
3015
+ const request = { directory, name, offset, base64: bytes.subarray(offset, offset + 16384).toString("base64") };
3016
+ const code = marker + `const request=${JSON.stringify(request)};
3017
+ const fs=require('node:fs'),path=require('node:path');
3018
+ try{
3019
+ if(process.geteuid()===0)throw new Error();
3020
+ const base=${JSON.stringify(BOX_CF)};
3021
+ if(fs.realpathSync(base)!==base)throw new Error();
3022
+ for(const dir of [base+'/sessions',request.directory]){try{fs.mkdirSync(dir,{mode:0o700});}catch(e){if(e.code!=='EEXIST')throw e;}if(fs.realpathSync(dir)!==dir)throw new Error();}
3023
+ const file=path.join(request.directory,request.name),data=Buffer.from(request.base64,'base64');
3024
+ const flags=fs.constants.O_WRONLY|fs.constants.O_NOFOLLOW|(request.offset===0?fs.constants.O_CREAT|fs.constants.O_EXCL:0);
3025
+ const fd=fs.openSync(file,flags,0o600);
3026
+ try{const st=fs.fstatSync(fd);if(!st.isFile()||st.uid!==process.geteuid()||st.size!==request.offset)throw new Error();if(fs.writeSync(fd,data,0,data.length,request.offset)!==data.length)throw new Error();}finally{fs.closeSync(fd);}
3027
+ process.stdout.write('DS_SESSION_FILES=written');
3028
+ }catch{process.stdout.write('DS_SESSION_FILES=failed');process.exitCode=1;}`;
3029
+ scripts.push("node -e " + sq(code));
3030
+ }
3031
+ }
3032
+ return scripts;
3033
+ }
3034
+ async function writeBoxSessionFiles(api, id, directory, files) {
3035
+ const scripts = boxSessionFilesScripts(directory, files);
3036
+ try {
3037
+ for (const script of scripts) {
3038
+ const result = await api.run(id, script, { env: { GH_TOKEN: "", GITHUB_TOKEN: "", OPENAI_API_KEY: "", ANTHROPIC_API_KEY: "" }, timeoutMs: 6e4 });
3039
+ if (result.code !== 0 || result.output !== "DS_SESSION_FILES=written") throw new Error();
3040
+ }
3041
+ } catch {
3042
+ throw new Error("Remote session files could not be prepared; worker not started");
3043
+ }
3044
+ }
3045
+
3046
+ // shared/opencodeReadiness.ts
3047
+ var READINESS_STATES = ["ready", "model-not-listed", "model-disabled", "model-non-chat", "model-no-tools", "variant-unavailable", "provider-not-listed", "provider-disabled", "provider-no-integration", "integration-not-listed", "no-connection", "connection-needs-auth", "connection-status-unknown", "oauth-unavailable"];
3048
+ var READINESS_CHECKS = ["box", "transport", "output", "version", "models", "default-model", "provider", "integration"];
3049
+
3050
+ // server/openCodeBox.ts
3051
+ var OPENCODE_BOX_ENV = {
3052
+ XDG_CONFIG_HOME: `${BOX_CF}/opencode/config`,
3053
+ XDG_DATA_HOME: `${BOX_CF}/opencode/data`,
3054
+ XDG_CACHE_HOME: `${BOX_CF}/opencode/cache`,
3055
+ XDG_STATE_HOME: `${BOX_CF}/opencode/state`
3056
+ };
3057
+ var OPENCODE_BOX_QUERY_SOURCE = String.raw`
3058
+ const { spawnSync } = require('child_process');
3059
+ const fs = require('fs');
3060
+ const [cli, mode, directory, requested = ''] = process.argv.slice(2);
3061
+ const cwd = fs.existsSync(directory) ? directory : '/workspace/home';
3062
+ let check = 'version';
3063
+ function query(endpoint, stage) {
3064
+ if (stage) check = stage;
3065
+ const r = spawnSync(cli, ['api', '--standalone', 'get', endpoint + '?location[directory]=' + encodeURIComponent(cwd)], { cwd, encoding: 'utf8', timeout: 10000, maxBuffer: 8 * 1024 * 1024 });
3066
+ if (r.status !== 0) throw new Error('OpenCode metadata unavailable');
3067
+ return JSON.parse(r.stdout).data;
3068
+ }
3069
+ function lookup(endpoint, stage, id) {
3070
+ // v2.2.6 list handlers await plugin activation; single-object get handlers deliberately do not.
3071
+ // Every CLI invocation owns a fresh --standalone server, so warming a previous process cannot fix this race.
3072
+ const list = query(endpoint, stage);
3073
+ if (!Array.isArray(list) || list.some(item => !item || typeof item !== 'object' || typeof item.id !== 'string')) throw new Error('Invalid metadata list');
3074
+ const matches = list.filter(item => item.id === id);
3075
+ if (matches.length > 1) throw new Error('Ambiguous metadata ID');
3076
+ return matches[0];
3077
+ }
3078
+ try {
3079
+ const version = spawnSync(cli, ['--version'], { encoding: 'utf8', timeout: 15000 });
3080
+ if (version.status !== 0 || !/^(?:opencode\s+)?v?2\.\d+\.\d+(?:[-+][\w.-]+)?\s*$/i.test(version.stdout)) throw new Error('Unsupported OpenCode version');
3081
+ if (mode === 'connections') {
3082
+ const list = query('/api/integration');
3083
+ if (!Array.isArray(list)) throw new Error('Invalid integrations');
3084
+ // Allowlist before data crosses the Box boundary; never return forms, commands or status URLs.
3085
+ process.stdout.write(JSON.stringify({ data: list.map(i => ({ id: i.id, name: i.name,
3086
+ methods: (i.methods || []).map(m => ({ id: m.id, type: m.type, label: m.label })),
3087
+ connections: (i.connections || []).map(c => ({ id: c.id, label: c.label, method: c.method, type: c.type, name: c.name, ...(c.status ? { status: true } : {}) })),
3088
+ })) }));
3089
+ } else {
3090
+ const models = query('/api/model', 'models');
3091
+ if (!Array.isArray(models)) throw new Error('Invalid model inventory');
3092
+ const selected = requested || !models.length ? null : query('/api/model/default', 'default-model');
3093
+ if (mode === 'models') {
3094
+ const clean = models.filter(m => m && m.enabled !== false && (!m.type || m.type === 'chat')).map(m => ({
3095
+ id: m.id, providerID: m.providerID, name: m.name,
3096
+ capabilities: { tools: m.capabilities?.tools === true },
3097
+ variants: Array.isArray(m.variants) ? m.variants.map(v => ({ id: v.id })) : [],
3098
+ }));
3099
+ process.stdout.write(JSON.stringify({ list: { data: clean }, selected: { data: selected && { id: selected.id, providerID: selected.providerID } } }));
3100
+ } else if (mode === 'readiness') {
3101
+ const evaluate = () => {
3102
+ check = 'models';
3103
+ const [ref, variant] = requested.split('#');
3104
+ const model = ref ? models.find(m => m && m.providerID + '/' + m.id === ref) : selected;
3105
+ if (!model) return 'model-not-listed';
3106
+ if (model.enabled === false) return 'model-disabled';
3107
+ if (model.type && model.type !== 'chat') return 'model-non-chat';
3108
+ if (model.capabilities?.tools !== true) return 'model-no-tools';
3109
+ if (variant && (!Array.isArray(model.variants) || !model.variants.some(v => v && v.id === variant))) return 'variant-unavailable';
3110
+ const provider = lookup('/api/provider', 'provider', model.providerID);
3111
+ if (!provider) return 'provider-not-listed';
3112
+ if (provider.activation === 'disabled') return 'provider-disabled';
3113
+ if (!provider.integrationID) return 'provider-no-integration';
3114
+ if (typeof provider.integrationID !== 'string') throw new Error('Invalid integration reference');
3115
+ const integration = lookup('/api/integration', 'integration', provider.integrationID);
3116
+ if (!integration) return 'integration-not-listed';
3117
+ if (!Array.isArray(integration.connections) || integration.connections.some(c => !c || typeof c !== 'object')) throw new Error('Invalid connection metadata');
3118
+ const connections = integration.connections;
3119
+ if (!connections.length) return 'no-connection';
3120
+ // This detailed mode is for the OAuth-only smoke gate, not the legacy any-provider status check.
3121
+ const oauth = connections.filter(c => c.type === 'credential' && c.method === 'oauth');
3122
+ if (!oauth.length) return 'oauth-unavailable';
3123
+ if (oauth.some(c => !c.status)) return 'ready';
3124
+ if (oauth.every(c => c.status && c.status.status === 'needs_auth')) return 'connection-needs-auth';
3125
+ return 'connection-status-unknown';
3126
+ };
3127
+ process.stdout.write(JSON.stringify({ state: evaluate() }));
3128
+ } else {
3129
+ const ref = requested.replace(/#[^#]*$/, '');
3130
+ const model = ref ? models.find(m => m.providerID + '/' + m.id === ref) : selected;
3131
+ let ready = false;
3132
+ if (model && model.enabled !== false && model.capabilities?.tools === true) {
3133
+ const provider = lookup('/api/provider', 'provider', model.providerID);
3134
+ if (!provider) throw new Error('Provider not listed');
3135
+ if (!provider.integrationID) ready = true;
3136
+ else {
3137
+ const integration = lookup('/api/integration', 'integration', provider.integrationID);
3138
+ if (!integration) throw new Error('Integration not listed');
3139
+ ready = Array.isArray(integration.connections) && integration.connections.some(c => !c.status);
3140
+ }
3141
+ }
3142
+ process.stdout.write(ready ? 'CUBEFARM_SIGNED_IN' : 'CUBEFARM_SIGNED_OUT');
3143
+ }
3144
+ }
3145
+ } catch {
3146
+ // An infrastructure/configuration error is NOT an expired login. No raw API output can leak.
3147
+ process.stdout.write(mode === 'readiness' ? JSON.stringify({ state: 'query-failed', check }) : 'CUBEFARM_OPENCODE_QUERY_FAILED');
3148
+ process.exitCode = 2;
3149
+ }
3150
+ `;
3151
+ var openCodeBoxQuery = (mode, directory = BOX_HOME, model2 = "") => `node ${sq(`${BOX_BIN}/opencode-query.cjs`)} ${sq(`${BOX_CLI_BIN}/opencode`)} ${sq(mode)} ${sq(directory)} ${sq(model2)}`;
3152
+ function parseOpenCodeReadiness(code, output) {
3153
+ const invalid = { state: "query-failed", check: "output" };
3154
+ try {
3155
+ if (output.length > 512) return invalid;
3156
+ const value = JSON.parse(output);
3157
+ if (!value || typeof value !== "object" || Array.isArray(value)) return invalid;
3158
+ if (value.state === "query-failed" && code !== 0 && Object.keys(value).length === 2 && READINESS_CHECKS.includes(value.check)) return { state: "query-failed", check: value.check };
3159
+ if (code === 0 && Object.keys(value).length === 1 && READINESS_STATES.includes(value.state)) return { state: value.state };
3160
+ } catch {
3161
+ }
3162
+ return invalid;
3163
+ }
3164
+
2946
3165
  // server/ptyClient.ts
2947
3166
  import crypto2 from "node:crypto";
2948
3167
  import fs7 from "node:fs";
@@ -3372,9 +3591,9 @@ function startBoxSignIn(o, exited) {
3372
3591
  o.term.note(`\u2500\u2500 Signing ${cliLabel(o.cli)} in \xB7 \u2601 cloud machine \u2500\u2500`);
3373
3592
  void (async () => {
3374
3593
  try {
3375
- await o.api.write(o.boxId, `${dir}/launch.json`, JSON.stringify({ ...signInCommand(o.cli), cwd: BOX_HOME, events: `${dir}/events.jsonl` }));
3594
+ await o.api.write(o.boxId, `${dir}/launch.json`, JSON.stringify({ ...signInCommand(o.cli), ...o.cli === "opencode" && o.authArgs ? { args: o.authArgs } : {}, cwd: BOX_HOME, events: `${dir}/events.jsonl` }));
3376
3595
  if (over) return;
3377
- const pty = boxPty(l, { api: o.api, boxId: o.boxId, record: () => void 0 }, o.term.cols, o.term.rows, 0, {});
3596
+ const pty = boxPty(l, { api: o.api, boxId: o.boxId, record: () => void 0 }, o.term.cols, o.term.rows, 0, o.cli === "opencode" ? OPENCODE_BOX_ENV : {});
3378
3597
  l.proc = pty;
3379
3598
  wire(l);
3380
3599
  await pty.open("new");
@@ -3390,6 +3609,42 @@ function startBoxSignIn(o, exited) {
3390
3609
  }
3391
3610
  };
3392
3611
  }
3612
+ function startOpenCodeAuth(o, exited) {
3613
+ const cmd = commandFor("opencode");
3614
+ if (!cmd) throw new Error("OpenCode is not installed on this computer.");
3615
+ const token = crypto3.randomUUID();
3616
+ const dir = path9.join(SESSIONS_DIR, token);
3617
+ fs8.mkdirSync(dir, { recursive: true });
3618
+ const l = { agentId: o.agentId, cli: "opencode", term: o.term, proc: null, token, dir, resumeId: null, statusLine: "", shots: /* @__PURE__ */ new Set(), session: null };
3619
+ let over = false;
3620
+ const end = (code) => {
3621
+ if (over) return;
3622
+ over = true;
3623
+ void endLive(l);
3624
+ exited(code);
3625
+ };
3626
+ l.session = { hook: () => ({}), exited: end };
3627
+ void checkOpenCodeVersion(cmd).then((problem) => {
3628
+ if (over) return;
3629
+ if (problem) {
3630
+ o.term.note(problem);
3631
+ end(-1);
3632
+ return;
3633
+ }
3634
+ try {
3635
+ const env = Object.fromEntries(Object.entries(process.env).filter((entry) => entry[1] !== void 0));
3636
+ l.proc = spawnPty(cmd.file, [...cmd.args, ...o.args], { cwd: o.cwd, cols: o.term.cols, rows: o.term.rows, env }, { kind: "opencode-auth" });
3637
+ wire(l);
3638
+ } catch {
3639
+ o.term.note("Could not start official OpenCode authentication.");
3640
+ end(-1);
3641
+ }
3642
+ }).catch(() => end(-1));
3643
+ return { stop() {
3644
+ over = true;
3645
+ void endLive(l);
3646
+ } };
3647
+ }
3393
3648
  function hooksReady2() {
3394
3649
  hooksReady();
3395
3650
  boxHooksReady();
@@ -3653,6 +3908,11 @@ function startCliSession(opts, callbacks) {
3653
3908
  }
3654
3909
  case "UserPromptSubmit": {
3655
3910
  if (sub) return {};
3911
+ if (cli === "opencode" && inBox && live && typeof b.session_id === "string" && live.resumeId !== b.session_id) {
3912
+ live.resumeId = b.session_id;
3913
+ cb.sessionId(b.session_id);
3914
+ remember(live);
3915
+ }
3656
3916
  busy2();
3657
3917
  const prompt2 = String(b.prompt ?? "").trim();
3658
3918
  const i = officePrompts.findIndex((p2) => p2.slice(0, 60) === prompt2.slice(0, 60));
@@ -3713,12 +3973,20 @@ function startCliSession(opts, callbacks) {
3713
3973
  case "TurnError":
3714
3974
  turnError = `${label}: ${clip(String(b.error ?? "error"), 200)}`;
3715
3975
  log([{ kind: "error", text: `\u2717 ${turnError}` }]);
3976
+ if (inBox && b.signed_out === true) {
3977
+ finish({ ok: false, text: lastText, errors: [`${label}'s provider connection needs sign-in.`], signedOut: true });
3978
+ return {};
3979
+ }
3716
3980
  turnEnded(lastText);
3717
3981
  return {};
3718
3982
  }
3719
3983
  return {};
3720
3984
  };
3721
3985
  const exited = (exitCode2) => {
3986
+ if (cli === "opencode" && turnError) {
3987
+ finish({ ok: false, text: lastText, errors: [turnError] });
3988
+ return;
3989
+ }
3722
3990
  if (cli === "claude" && opts.resumeSessionId && !begun && lostConversation(term.screen())) {
3723
3991
  cb.sessionId(null);
3724
3992
  finish({ ok: false, text: "", errors: [`${label} couldn't find the conversation it was resuming, so the next session starts a new one.`] });
@@ -3760,10 +4028,6 @@ function startCliSession(opts, callbacks) {
3760
4028
  return handle;
3761
4029
  }
3762
4030
  const cmd = box ? { file: `${BOX_CLI_BIN}/${CLIS.find((c) => c.id === cli).command}`, args: [] } : commandFor(cli);
3763
- if (box && cli === "opencode") {
3764
- setTimeout(() => finish({ ok: false, text: "", errors: [`${label} can't run in a cloud machine yet: give this agent Claude Code or Codex.`] }), 0);
3765
- return handle;
3766
- }
3767
4031
  if (!box && (!terminalsAvailable || !cmd)) {
3768
4032
  const why2 = !terminalsAvailable ? "the terminal module could not be loaded on this machine" : `${label} isn't installed (no "${cli}" on PATH)`;
3769
4033
  setTimeout(() => finish({ ok: false, text: "", errors: [`Could not start ${label}: ${why2}.`] }), 0);
@@ -3824,17 +4088,18 @@ ${JSON.stringify(opts.outputSchema)}`;
3824
4088
  sessionId,
3825
4089
  name: opts.label ?? "Droidsembly",
3826
4090
  role: opts.role,
4091
+ openCodePermissions: opts.openCodePermissions,
3827
4092
  additionalDirectories: opts.additionalDirectories,
3828
4093
  files,
3829
4094
  notify: box ? { script: `${BOX_BIN}/notify.cjs`, url: events } : { script: path9.join(BIN_DIR, "notify.cjs"), url: hookUrl },
3830
4095
  codexHook: box ? `${BOX_BIN}/codex-hook.cjs` : path9.join(BIN_DIR, "codex-hook.cjs"),
3831
- plugin: box ? "" : pathToFileURL(path9.join(BIN_DIR, "opencode-plugin")).href,
4096
+ plugin: box ? `file://${BOX_BIN}/opencode-plugin` : pathToFileURL(path9.join(BIN_DIR, "opencode-plugin")).href,
3832
4097
  ...opts.office && !box ? { officeUrl: `${officeUrl}/api/mcp/${token}` } : {},
3833
4098
  browser,
3834
4099
  ...box ? { node: "node", posix: true } : {}
3835
4100
  });
3836
4101
  const env = {};
3837
- if (box) Object.assign(env, BOX_ENV, box.env, launch2.env, { CUBEFARM_STATUS: statusLine });
4102
+ if (box) Object.assign(env, BOX_ENV, box.env, cli === "opencode" ? OPENCODE_BOX_ENV : {}, launch2.env, { CUBEFARM_STATUS: statusLine });
3838
4103
  else {
3839
4104
  for (const [k, v] of Object.entries(process.env)) {
3840
4105
  if (v === void 0) continue;
@@ -3898,7 +4163,8 @@ ${JSON.stringify(opts.outputSchema)}`;
3898
4163
  const beginInBox = async (b) => {
3899
4164
  try {
3900
4165
  boxFiles.push([`${dir}/launch.json`, JSON.stringify({ file: cmd.file, args: [...cmd.args, ...launch2.args], cwd: opts.cwd, events })]);
3901
- for (const [file, text3] of boxFiles) await b.api.write(b.boxId, file, text3);
4166
+ if (cli === "opencode") await writeBoxSessionFiles(b.api, b.boxId, dir, boxFiles);
4167
+ else for (const [file, text3] of boxFiles) await b.api.write(b.boxId, file, text3);
3902
4168
  if (done) return;
3903
4169
  const pty = boxPty(l, b, term.cols, term.rows, 0, env);
3904
4170
  l.proc = pty;
@@ -3937,13 +4203,13 @@ var MAX_DESK_INSTALLS = 2;
3937
4203
  var depsHash = (pkg, lock) => crypto4.createHash("sha256").update(pkg).update("\0").update(lock ?? "").digest("hex");
3938
4204
  async function readDeps(dir) {
3939
4205
  const read = (file) => fs9.readFile(path10.join(dir, file), "utf8").catch(() => null);
3940
- const [pkg, lock, marker, nodeModules] = await Promise.all([
4206
+ const [pkg, lock, marker2, nodeModules] = await Promise.all([
3941
4207
  read("package.json"),
3942
4208
  read("package-lock.json"),
3943
4209
  read(path10.join("node_modules", INSTALL_MARKER)),
3944
4210
  fs9.stat(path10.join(dir, "node_modules")).then((s2) => s2.isDirectory()).catch(() => false)
3945
4211
  ]);
3946
- return { pkg, lock, hash: depsHash(pkg ?? "", lock), marker: marker ?? "", nodeModules };
4212
+ return { pkg, lock, hash: depsHash(pkg ?? "", lock), marker: marker2 ?? "", nodeModules };
3947
4213
  }
3948
4214
  var depsCurrent = (s2) => s2.nodeModules && s2.marker === s2.hash;
3949
4215
  var writeMarker = (dir, hash) => fs9.writeFile(path10.join(dir, "node_modules", INSTALL_MARKER), hash).catch(() => void 0);
@@ -4128,6 +4394,65 @@ var openCodeModels = createModelCatalogReader(async (directory) => {
4128
4394
  }
4129
4395
  });
4130
4396
 
4397
+ // shared/opencodeConnections.ts
4398
+ function sanitizeConnections(value) {
4399
+ const data = value?.data;
4400
+ if (!Array.isArray(data)) throw new Error("Invalid OpenCode connections");
4401
+ const text3 = (v) => typeof v === "string" && !!v && v.length <= 512 && !/[\x00-\x1f\x7f]/.test(v);
4402
+ return data.flatMap((i) => {
4403
+ if (!i || !text3(i.id) || !text3(i.name) || !Array.isArray(i.methods) || !Array.isArray(i.connections)) return [];
4404
+ return [{
4405
+ id: i.id,
4406
+ name: i.name,
4407
+ methods: i.methods.flatMap((m) => {
4408
+ if (!m || !["key", "oauth", "command", "external", "env"].includes(String(m.type))) return [];
4409
+ const id = m.type === "key" || m.type === "env" ? m.type : m.id;
4410
+ if (!text3(id)) return [];
4411
+ return [{ id, type: m.type, label: text3(m.label) ? m.label : String(m.type) }];
4412
+ }),
4413
+ connections: i.connections.flatMap((c) => {
4414
+ if (!c || !["credential", "env"].includes(String(c.type))) return [];
4415
+ const environment = c.type === "env";
4416
+ const id = environment ? c.name : c.id;
4417
+ if (!text3(id) || !environment && (!text3(c.label) || !["key", "oauth", "external"].includes(String(c.method)))) return [];
4418
+ return [{ id, label: environment ? id : c.label, method: environment ? "env" : String(c.method), environment, needsAuth: !!c.status }];
4419
+ })
4420
+ }];
4421
+ });
4422
+ }
4423
+ function connectionArgs(integrations, input) {
4424
+ const a = input;
4425
+ if (!a || typeof a !== "object") throw new Error("Invalid connection action");
4426
+ if (Object.keys(a).some((k) => !["action", "integration", a.action === "login" ? "method" : "account"].includes(k))) throw new Error("Only provider, method and account IDs are accepted; enter credentials in the official terminal.");
4427
+ const i = integrations.find((i2) => i2.id === a.integration);
4428
+ if (!i || i.id.startsWith("-")) throw new Error("Unknown OpenCode provider");
4429
+ if (a.action === "login" && "method" in a) {
4430
+ const m = i.methods.find((m2) => m2.id === a.method);
4431
+ if (!m || m.type === "env" || m.id.startsWith("-")) throw new Error("Choose a supported interactive authentication method");
4432
+ return ["auth", "login", i.id, "--method", m.id];
4433
+ }
4434
+ if (a.action === "switch" && "account" in a) {
4435
+ const c = i.connections.find((c2) => c2.id === a.account && !c2.environment);
4436
+ if (!c || c.id.startsWith("-")) throw new Error("Unknown saved OpenCode account");
4437
+ return ["auth", "switch", i.id, c.id];
4438
+ }
4439
+ throw new Error("Invalid connection action");
4440
+ }
4441
+
4442
+ // server/opencodeConnections.ts
4443
+ async function openCodeConnections(directory) {
4444
+ const cmd = commandFor("opencode");
4445
+ if (!cmd) throw new Error("OpenCode is not installed on this computer.");
4446
+ const problem = await checkOpenCodeVersion(cmd);
4447
+ if (problem) throw new Error(problem);
4448
+ try {
4449
+ const text3 = await run(cmd.file, [...cmd.args, "api", "get", `/api/integration?location[directory]=${encodeURIComponent(directory)}`], { timeoutMs: 3e4 });
4450
+ return sanitizeConnections(JSON.parse(text3));
4451
+ } catch {
4452
+ throw new Error("Could not read OpenCode connections. No credentials were changed.");
4453
+ }
4454
+ }
4455
+
4131
4456
  // server/previewRunner.ts
4132
4457
  import { spawn as spawn3 } from "node:child_process";
4133
4458
  import fs11 from "node:fs/promises";
@@ -4373,6 +4698,33 @@ import path13 from "node:path";
4373
4698
 
4374
4699
  // shared/italianUi.ts
4375
4700
  var italianUi = {
4701
+ "OpenCode connections": "Connessioni OpenCode",
4702
+ "Continue": "Continua",
4703
+ "Open terminal": "Apri terminale",
4704
+ "Could not load connections.": "Impossibile caricare le connessioni.",
4705
+ "Change OpenCode connection?": "Cambiare connessione OpenCode?",
4706
+ "This changes the shared OpenCode account on this computer, not just this agent. Stop all work and close coding-agent terminals first. Continue?": "La modifica riguarda l\u2019account OpenCode condiviso su questo computer, non solo questo agente. Prima ferma le attivit\xE0 e chiudi le sessioni degli strumenti di sviluppo. Continuare?",
4707
+ "This changes OpenCode accounts in this Box only. Stop all work and close coding-agent terminals first. Continue?": "La modifica riguarda gli account OpenCode solo in questa Box. Prima ferma le attivit\xE0 e chiudi le sessioni degli strumenti di sviluppo. Continuare?",
4708
+ "Authentication started in the terminal. Finish there, then refresh connections. Selection alone does not activate an account.": "Autenticazione avviata nel terminale. Completala l\xEC, poi aggiorna le connessioni. La sola selezione non attiva un account.",
4709
+ "Choose a provider and authentication method, or activate a saved account. Credentials are entered only in OpenCode\u2019s official terminal flow, never in these fields.": "Scegli provider e metodo di autenticazione, oppure attiva un account salvato. Le credenziali si inseriscono solo nel flusso ufficiale OpenCode nel terminale, mai in questi campi.",
4710
+ "Scope: this Box. Other Boxes and this computer are separate. Using the same subscription still shares its usage limits.": "Ambito: questa Box. Le altre Box e questo computer sono separati. Usare lo stesso abbonamento comporta comunque limiti di utilizzo condivisi.",
4711
+ "Scope: shared OpenCode environment on this computer, including other local agents. No per-agent account isolation.": "Ambito: ambiente OpenCode condiviso su questo computer, inclusi gli altri agenti locali. Gli account non sono isolati per agente.",
4712
+ "API keys use provider API billing. OAuth may use a subscription only when the provider supports it; check the method and provider terms.": "Le API key usano la fatturazione API del provider. OAuth pu\xF2 usare un abbonamento solo se il provider lo supporta: verifica metodo e condizioni del provider.",
4713
+ "Refresh connections": "Aggiorna connessioni",
4714
+ "Loading connections\u2026": "Caricamento connessioni\u2026",
4715
+ "OpenCode authentication is running. Finish in its terminal or stop the connection operation.": "Autenticazione OpenCode in corso. Completala nel suo terminale oppure interrompi l\u2019operazione di connessione.",
4716
+ "Stop connection operation": "Interrompi operazione di connessione",
4717
+ "Select a provider": "Seleziona un provider",
4718
+ "Authentication method": "Metodo di autenticazione",
4719
+ "Select an authentication method": "Seleziona un metodo di autenticazione",
4720
+ "Environment credentials are managed on this host, not saved or copied by the app. Use the provider\u2019s official setup instructions.": "Le credenziali d\u2019ambiente si gestiscono su questa macchina: l\u2019app non le salva n\xE9 le copia. Segui le istruzioni ufficiali del provider.",
4721
+ "Add account in terminal": "Aggiungi account nel terminale",
4722
+ "Saved account / profile": "Account / profilo salvato",
4723
+ "Select an account": "Seleziona un account",
4724
+ "needs sign-in": "accesso necessario",
4725
+ "Activate account in terminal": "Attiva account nel terminale",
4726
+ "The public API lists saved accounts but does not identify the active one. Verify the active account with OpenCode auth list. Accounts persist in OpenCode on this host, not as an app preference.": "L\u2019API pubblica elenca gli account salvati, ma non identifica quello attivo. Verificalo con OpenCode auth list. Gli account restano salvati in OpenCode su questa macchina, non come preferenza dell\u2019app.",
4727
+ "In the agent\u2019s Setup, open OpenCode connections to choose a provider, authentication method and saved account. Account changes apply to that Box, not to this computer or other Boxes.": "Nella Configurazione dell\u2019agente, apri Connessioni OpenCode per scegliere provider, metodo di autenticazione e account salvato. Le modifiche agli account riguardano quella Box, non questo computer o le altre Box.",
4376
4728
  "Look around": "Guardati intorno",
4377
4729
  "Pull out your phone": "Apri il telefono",
4378
4730
  "Visit the CEO": "Visita il CEO",
@@ -4754,7 +5106,7 @@ var italianUi = {
4754
5106
  "Where they work": "Dove lavora",
4755
5107
  "Works on": "Lavora su",
4756
5108
  " (connect Upstash in Settings first)": " (collega prima Upstash nelle Impostazioni)",
4757
- " (OpenCode can\u2019t run there)": " (OpenCode non pu\xF2 essere eseguito qui)",
5109
+ "OpenCode signs in to its selected provider in each Box. Use Sign in in the agent terminal, then browse models in that agent\u2019s Setup. Local OpenCode accounts and the Claude/Codex keys below are not copied or reused.": "OpenCode accede al provider scelto in ogni Box. Usa Accedi nel terminale dell\u2019agente, poi consulta i modelli nella sua Configurazione. Gli account OpenCode locali e le chiavi Claude/Codex qui sotto non vengono copiati n\xE9 riutilizzati.",
4758
5110
  "no Box yet": "nessun Box",
4759
5111
  "creating their Box\u2026": "creazione del Box\u2026",
4760
5112
  "setting up their Box\u2026": "configurazione del Box\u2026",
@@ -5072,9 +5424,9 @@ var italianUi = {
5072
5424
  "File issue on GitHub": "Crea issue su GitHub",
5073
5425
  "QA report \u2197": "Rapporto QA \u2197",
5074
5426
  "This floor no longer exists.": "Questo piano non esiste pi\xF9.",
5075
- "Merge PR #{number}?": "Eseguire il merge della PR #{number}?",
5076
- "\u201C{title}\u201D passed QA. It will be squash-merged into {branch}.": "\u201C{title}\u201D ha superato il QA. Verr\xE0 integrata in {branch} con squash merge.",
5077
- "Squash & merge": "Squash e merge",
5427
+ "Merge PR #{number}?": "Integrare la PR #{number}?",
5428
+ "\u201C{title}\u201D passed QA. It will be squash-merged into {branch}.": "\u201C{title}\u201D ha superato la verifica QA. I suoi commit verranno unificati in un unico commit e integrati nel ramo {branch}.",
5429
+ "Squash & merge": "Integra unificando i commit",
5078
5430
  "Merge PR #{number} without QA?": "Eseguire il merge della PR #{number} senza QA?",
5079
5431
  "\u201C{title}\u201D has not passed QA yet. Merge it into {branch} anyway?": "\u201C{title}\u201D non ha ancora superato il QA. Integrarla comunque in {branch}?",
5080
5432
  "Merge anyway": "Esegui comunque il merge",
@@ -7687,6 +8039,8 @@ var realBackend = {
7687
8039
  releaseClis,
7688
8040
  detectClis,
7689
8041
  openCodeModels,
8042
+ openCodeConnections,
8043
+ openCodeAuth: startOpenCodeAuth,
7690
8044
  previews: realPreviews,
7691
8045
  office: realOffice,
7692
8046
  voice: elevenLabs,
@@ -9195,8 +9549,9 @@ function demoBoxes(logins) {
9195
9549
  },
9196
9550
  run: async (id, script) => {
9197
9551
  box(id).status = "running";
9198
- const cli = /claude'? auth /.test(script) ? "claude" : "codex";
9199
- if (script.includes("CUBEFARM_SIGNED_IN")) return { code: 0, output: logins.get(id)?.has(cli) ? "CUBEFARM_SIGNED_IN" : "CUBEFARM_SIGNED_OUT" };
9552
+ const cli = script.includes("opencode-query.cjs") ? "opencode" : /claude'? auth /.test(script) ? "claude" : "codex";
9553
+ if (script.includes("CUBEFARM_SIGNED_IN") || cli === "opencode" && script.includes("'status'")) return { code: 0, output: logins.get(id)?.has(cli) ? "CUBEFARM_SIGNED_IN" : "CUBEFARM_SIGNED_OUT" };
9554
+ if (cli === "opencode" && script.includes("'models'")) return { code: 0, output: JSON.stringify({ list: { data: [{ providerID: "demo", id: "cloud-model", name: "Demo cloud model", capabilities: { tools: true } }] }, selected: { data: null } }) };
9200
9555
  if (/auth logout|' logout/.test(script)) {
9201
9556
  logins.get(id)?.delete(cli);
9202
9557
  return { code: 0, output: "" };
@@ -9246,13 +9601,13 @@ function demoCloud() {
9246
9601
  }
9247
9602
  };
9248
9603
  }
9249
- var DEMO_SIGN_IN = { claude: "https://example.com/cubefarm-demo/claude-sign-in", codex: "https://example.com/cubefarm-demo/codex-device" };
9604
+ var DEMO_SIGN_IN = { claude: "https://example.com/cubefarm-demo/claude-sign-in", codex: "https://example.com/cubefarm-demo/codex-device", opencode: "https://example.com/droidsembly-demo/opencode" };
9250
9605
  function demoSignIn(o, logins, exited) {
9251
9606
  const { term } = o;
9252
9607
  const claude = o.cli === "claude";
9253
- term.note(`\u2500\u2500 Signing ${claude ? "Claude Code" : "Codex"} in \xB7 \u2601 cloud machine (demo) \u2500\u2500`);
9608
+ term.note(`\u2500\u2500 Signing ${cliLabel(o.cli)} in \xB7 \u2601 cloud machine (demo) \u2500\u2500`);
9254
9609
  term.write(
9255
- (claude ? ["Opening browser to sign in\u2026", `If the browser didn't open, visit: ${DEMO_SIGN_IN.claude}`, "", "\x1B[2m(demo) Paste anything and press Enter.\x1B[0m", "Paste code here if prompted > "] : [
9610
+ (o.cli === "opencode" ? ["OpenCode provider login (demo)", DEMO_SIGN_IN.opencode, "(demo) Press Enter to finish."] : claude ? ["Opening browser to sign in\u2026", `If the browser didn't open, visit: ${DEMO_SIGN_IN.claude}`, "", "\x1B[2m(demo) Paste anything and press Enter.\x1B[0m", "Paste code here if prompted > "] : [
9256
9611
  "Welcome to Codex (demo)",
9257
9612
  "",
9258
9613
  "Follow these steps to sign in with ChatGPT using device code authorization:",
@@ -11316,6 +11671,9 @@ for (const dir of process.argv.slice(2)) c.projects[dir] = Object.assign({}, c.p
11316
11671
  fs.writeFileSync(file, JSON.stringify(c, null, 2));
11317
11672
  `;
11318
11673
  var BOX_HELPERS = {
11674
+ "opencode-query.cjs": OPENCODE_BOX_QUERY_SOURCE,
11675
+ "opencode-plugin/index.js": OPENCODE_PLUGIN_SOURCE,
11676
+ "opencode-plugin/package.json": JSON.stringify({ name: "droidsembly-box-plugin", type: "module", exports: "./index.js" }),
11319
11677
  "launch.cjs": BOX_LAUNCH_SOURCE,
11320
11678
  "hook.cjs": BOX_HOOK_SOURCE,
11321
11679
  "statusline.cjs": BOX_STATUSLINE_SOURCE,
@@ -11325,8 +11683,17 @@ var BOX_HELPERS = {
11325
11683
  "seed-claude.cjs": BOX_SEED_CLAUDE_SOURCE
11326
11684
  };
11327
11685
 
11686
+ // shared/opencodeGateDiagnostics.ts
11687
+ var GateDiagnosticError = class extends Error {
11688
+ constructor(category) {
11689
+ super(category);
11690
+ this.category = category;
11691
+ }
11692
+ category;
11693
+ };
11694
+
11328
11695
  // server/boxMachines.ts
11329
- var SETUP_REV = 2;
11696
+ var SETUP_REV = 4;
11330
11697
  var SETUP_TIMEOUT_MS = 20 * 6e4;
11331
11698
  var LIVE = ["running", "idle", "creating"];
11332
11699
  function failure(what, output, secrets) {
@@ -11342,7 +11709,6 @@ var BoxMachines = class {
11342
11709
  ids = /* @__PURE__ */ new Map();
11343
11710
  // machine -> Box id
11344
11711
  ready = /* @__PURE__ */ new Map();
11345
- // machine -> its Box, set up (once per office run)
11346
11712
  states = /* @__PURE__ */ new Map();
11347
11713
  api() {
11348
11714
  const api = this.deps.api();
@@ -11387,17 +11753,20 @@ var BoxMachines = class {
11387
11753
  }
11388
11754
  /** The machine's Box, created, running and set up: the first time takes a few minutes. */
11389
11755
  ensure(machine, note2) {
11390
- let p = this.ready.get(machine);
11391
- if (!p) {
11392
- p = this.bringUp(machine, note2).catch((err) => {
11393
- this.ready.delete(machine);
11756
+ const cli = this.deps.cli?.(machine);
11757
+ const browser = this.deps.browser?.(machine) ?? !cli;
11758
+ const profile = `${cli ?? "all"}:${browser}`;
11759
+ const previous = this.ready.get(machine);
11760
+ if (!previous || previous.profile !== profile) {
11761
+ const p = (previous ? previous.promise : Promise.resolve()).then(() => this.bringUp(machine, note2, cli, browser)).catch((err) => {
11762
+ if (this.ready.get(machine)?.promise === p) this.ready.delete(machine);
11394
11763
  this.setState(machine, "error");
11395
11764
  throw err;
11396
11765
  });
11397
- this.ready.set(machine, p);
11766
+ this.ready.set(machine, { profile, promise: p });
11398
11767
  return p;
11399
11768
  }
11400
- return p.then(async (id) => {
11769
+ return previous.promise.then(async (id) => {
11401
11770
  const info = await this.api().get(id);
11402
11771
  if (!info) {
11403
11772
  this.ready.delete(machine);
@@ -11412,7 +11781,7 @@ var BoxMachines = class {
11412
11781
  return id;
11413
11782
  });
11414
11783
  }
11415
- async bringUp(machine, note2) {
11784
+ async bringUp(machine, note2, cli, browser = false) {
11416
11785
  const api = this.api();
11417
11786
  let id = await this.boxId(machine);
11418
11787
  if (id) {
@@ -11435,7 +11804,7 @@ var BoxMachines = class {
11435
11804
  }
11436
11805
  this.setState(machine, "setting-up");
11437
11806
  const git2 = await this.deps.git();
11438
- const setup = await api.run(id, setupScript({ versions: this.deps.versions, rev: SETUP_REV, gitName: git2.name, gitEmail: git2.email }), { timeoutMs: SETUP_TIMEOUT_MS });
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 });
11439
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());
11440
11809
  for (const [name, source] of Object.entries(BOX_HELPERS)) await api.write(id, `${BOX_BIN}/${name}`, source);
11441
11810
  await api.write(id, BOX_TMUX_CONF, TMUX_CONF);
@@ -11451,7 +11820,7 @@ var BoxMachines = class {
11451
11820
  const id = await this.ensure(machine, note2);
11452
11821
  const r = await api.run(id, prepareDeskScript(fullName, base, branch), { env: await this.deps.githubEnv(), timeoutMs: 15 * 6e4 });
11453
11822
  const lines = r.output.trim().split("\n");
11454
- if (r.code !== 0) throw failure(`Couldn't set up the desk in ${fullName}'s cloud machine`, r.output, this.deps.secrets());
11823
+ if (r.code !== 0) throw failure(`Couldn't set up the desk in ${fullName}'s cloud machine (exit ${r.code})`, r.output, this.deps.secrets());
11455
11824
  for (const l of lines.slice(0, -1)) if (/stale git lock|rebuilt/.test(l)) note2?.(l.trim());
11456
11825
  await api.run(id, `node ${sq(`${BOX_BIN}/seed-claude.cjs`)} ${sq(boxDeskDir(fullName))}`);
11457
11826
  return boxDeskDir(fullName);
@@ -11562,13 +11931,56 @@ var BoxMachines = class {
11562
11931
  * Is the Box's own CLI signed in (its login in the Box user's home)? Run with no credentials of any kind, so only that
11563
11932
  * login counts. Wakes the Box. Throws when Upstash can't say.
11564
11933
  */
11565
- async signedIn(machine, cli) {
11934
+ async signedIn(machine, cli, directory, model2 = "") {
11566
11935
  const id = await this.ensure(machine);
11567
- const r = await this.api().run(id, signInCheckScript(cli), { timeoutMs: 6e4 });
11936
+ const r = await this.api().run(id, cli === "opencode" ? openCodeBoxQuery("status", directory, model2) : signInCheckScript(cli), { timeoutMs: 6e4, ...cli === "opencode" ? { env: OPENCODE_BOX_ENV } : {} });
11568
11937
  const out = signInOutcome(r.output);
11569
- if (out === null) throw new Error(`Couldn't ask ${cli === "claude" ? "Claude Code" : "Codex"} in the cloud machine whether it's signed in.`);
11938
+ if (r.code !== 0 || out === null) throw new Error(`Couldn't check the coding agent's connection in the cloud machine. Check its provider and model setup.`);
11570
11939
  return out;
11571
11940
  }
11941
+ async openCodeConnections(machine, directory) {
11942
+ const id = await this.boxId(machine);
11943
+ if (!id) throw new Error("The cloud machine is not ready. Connection settings never create a Box.");
11944
+ const r = await this.api().run(id, openCodeBoxQuery("connections", directory), { env: OPENCODE_BOX_ENV, timeoutMs: 6e4 });
11945
+ if (r.code !== 0) throw new Error("Could not read OpenCode connections in the cloud machine.");
11946
+ try {
11947
+ return sanitizeConnections(JSON.parse(r.output));
11948
+ } catch {
11949
+ throw new Error("Invalid OpenCode connections from the cloud machine.");
11950
+ }
11951
+ }
11952
+ /** Post-login metadata check. Unlike task setup, this must never provision a missing Box. */
11953
+ async openCodeConnectionReady(machine, directory, model2) {
11954
+ const id = await this.boxId(machine);
11955
+ if (!id) return false;
11956
+ const r = await this.api().run(id, openCodeBoxQuery("status", directory, model2), { env: OPENCODE_BOX_ENV, timeoutMs: 6e4 });
11957
+ const outcome = signInOutcome(r.output);
11958
+ if (r.code !== 0 || outcome === null) throw new GateDiagnosticError("remote-query-output-failed");
11959
+ return outcome;
11960
+ }
11961
+ /** OAuth-only gate probe: existing Box only, no resume/setup, no raw remote output in the result. */
11962
+ async openCodeReadiness(machine, directory, model2) {
11963
+ try {
11964
+ const id = await this.boxId(machine);
11965
+ if (!id) return { state: "query-failed", check: "box" };
11966
+ const r = await this.api().run(id, openCodeBoxQuery("readiness", directory, model2), { env: OPENCODE_BOX_ENV, timeoutMs: 6e4 });
11967
+ return parseOpenCodeReadiness(r.code, r.output);
11968
+ } catch {
11969
+ return { state: "query-failed", check: "transport" };
11970
+ }
11971
+ }
11972
+ async openCodeModels(machine, directory) {
11973
+ const id = await this.boxId(machine);
11974
+ if (!id) throw new Error("The cloud machine is not ready yet. Wait for setup before browsing its models.");
11975
+ const r = await this.api().run(id, openCodeBoxQuery("models", directory), { env: OPENCODE_BOX_ENV, timeoutMs: 6e4 });
11976
+ if (r.code !== 0) throw new Error("Could not read OpenCode models in the cloud machine.");
11977
+ try {
11978
+ const data = JSON.parse(r.output);
11979
+ return sanitizeCatalog(data.list, data.selected, directory);
11980
+ } catch {
11981
+ throw new Error("Invalid OpenCode model inventory from the cloud machine.");
11982
+ }
11983
+ }
11572
11984
  /** Forget a login its CLI's servers turned away (an expired one), so it reads as signed out until it's signed in again. */
11573
11985
  async signOut(machine, cli) {
11574
11986
  const id = await this.ensure(machine);
@@ -12848,15 +13260,17 @@ var Previews = class {
12848
13260
  if (watched) watched.viewedAt = now2;
12849
13261
  this.tellScreen(watched);
12850
13262
  }
12851
- /** Every few seconds: forget viewers that went quiet, and stop PR previews nobody has watched for the idle time. */
13263
+ /** Forget quiet viewers and stop idle previews. Resolves after their app/worktree cleanup, not just removal from the view. */
12852
13264
  sweepPrs(now2 = Date.now()) {
13265
+ const stopping = [];
12853
13266
  for (const [viewer, w] of this.watches) if (now2 - w.at > WATCH_MS) this.watches.delete(viewer);
12854
13267
  for (const key of expired(this.prInfos(), this.screen(now2), now2, PR_PREVIEW_IDLE_MS)) {
12855
13268
  const r = this.prRuns.get(key);
12856
13269
  console.log(`PR theatre: PR #${r.pr} of ${r.fullName} stopped after ${+(PR_PREVIEW_IDLE_MS / 6e4).toFixed(2)} minutes off screen`);
12857
- void this.endPr(r);
13270
+ stopping.push(this.endPr(r));
12858
13271
  }
12859
13272
  this.tellScreen();
13273
+ return Promise.all(stopping).then(() => void 0);
12860
13274
  }
12861
13275
  /** The floor's PRs as the office knows them now: previews of PRs that merged or closed stop. */
12862
13276
  pullsChanged(f, pulls) {
@@ -15031,6 +15445,7 @@ var Swarm = class {
15031
15445
  this.cloud = new Cloud({
15032
15446
  // The demo's fake cloud keeps a file of its own: its tests run beside the notifier's, which share demo-secrets.json.
15033
15447
  secretsFile: path21.join(HOME_DIR, backend.demo ? "demo-cloud-secrets.json" : "secrets.json"),
15448
+ credentials: backend.cloud.credentials,
15034
15449
  env: backend.cloud.env(),
15035
15450
  boxes: (key) => backend.cloud.boxes(key),
15036
15451
  ghToken: () => backend.cloud.ghToken(),
@@ -15044,6 +15459,14 @@ var Swarm = class {
15044
15459
  office: () => this.state.officeId,
15045
15460
  size: () => this.state.settings.cloud.boxSize,
15046
15461
  versions: boxVersions(),
15462
+ cli: (machine) => {
15463
+ const a = this.state.agents.find((a2) => a2.machine === machine);
15464
+ return a?.cli || this.state.settings.defaultCli;
15465
+ },
15466
+ browser: (machine) => {
15467
+ const a = this.state.agents.find((a2) => a2.machine === machine);
15468
+ return this.state.repos.find((r) => r.id === a?.repoId)?.browserTesting ?? false;
15469
+ },
15047
15470
  git: () => backend.cloud.gitIdentity(this.user),
15048
15471
  githubEnv: () => this.cloud.githubEnv(),
15049
15472
  state: (machine) => this.boxState(machine),
@@ -15062,6 +15485,14 @@ var Swarm = class {
15062
15485
  });
15063
15486
  }
15064
15487
  backend;
15488
+ eventListeners = /* @__PURE__ */ new Set();
15489
+ /** In-process observers use the same public events as UI clients; no polling or private-state patching. */
15490
+ onEvent(listener) {
15491
+ this.eventListeners.add(listener);
15492
+ return () => {
15493
+ this.eventListeners.delete(listener);
15494
+ };
15495
+ }
15065
15496
  state = {
15066
15497
  settings: {
15067
15498
  sessionLimit: 0,
@@ -15161,6 +15592,7 @@ var Swarm = class {
15161
15592
  stopping = false;
15162
15593
  writing = Promise.resolve();
15163
15594
  // state file writes, one at a time: they share its temp file
15595
+ terminalSaving = null;
15164
15596
  logSeq = 1;
15165
15597
  previews;
15166
15598
  officeHead = null;
@@ -15679,6 +16111,7 @@ var Swarm = class {
15679
16111
  broadcast(ev) {
15680
16112
  this.outbox.broadcast(ev);
15681
16113
  this.observe(ev);
16114
+ for (const listener of this.eventListeners) listener(ev);
15682
16115
  }
15683
16116
  /** What follows from an event besides the tabs hearing it: ticker lines and mission control's numbers. */
15684
16117
  observe(ev) {
@@ -15852,10 +16285,97 @@ var Swarm = class {
15852
16285
  listGithubRepos(owner) {
15853
16286
  return this.backend.listMyRepos(owner);
15854
16287
  }
16288
+ configuringOpenCode = false;
16289
+ openCodeAuthRun = null;
16290
+ async openCodeConnections(id) {
16291
+ 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.");
16293
+ if (a.host === "box" && a.role !== "ceo") {
16294
+ const machine = this.machineOf(a);
16295
+ 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
+ }
16297
+ 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 });
16299
+ const directory = a.role === "ceo" ? CEO_DIR : this.backend.mainDir(this.repo(a.repoId).fullName);
16300
+ return { scope: "local", scopeKey: "local", integrations: await this.backend.openCodeConnections(directory), configuringAgent: this.openCodeAuthRun?.agentId ?? null };
16301
+ }
16302
+ async configureOpenCode(id, input, expectedScope) {
16303
+ const a = this.agent(id);
16304
+ const replaceable = () => {
16305
+ const s2 = this.signIns.get(id);
16306
+ return !!s2?.run && !s2.held && !s2.starting;
16307
+ };
16308
+ const busy2 = () => this.state.agents.some((a2) => BUSY3.includes(a2.status)) || [...this.agentRt].some(([agentId, rt]) => rt.session || rt.terminal?.live && !(agentId === id && replaceable())) || [...this.signIns].some(([agentId, s2]) => s2.starting || s2.run && !(agentId === id && replaceable()));
16309
+ const available = () => !this.configuringOpenCode && !busy2();
16310
+ if (!available()) throw new HttpError(409, "Stop all work and close coding-agent terminals before changing OpenCode accounts.");
16311
+ const host = a.host;
16312
+ const machine = a.host === "box" ? this.machineOf(a) : null;
16313
+ const operation = { agentId: id, run: null };
16314
+ this.configuringOpenCode = true;
16315
+ this.openCodeAuthRun = operation;
16316
+ try {
16317
+ const catalog = await this.openCodeConnections(id);
16318
+ if (catalog.scopeKey !== expectedScope) throw new HttpError(409, "Connection host changed; reload connections before making changes.");
16319
+ let args;
16320
+ try {
16321
+ args = connectionArgs(catalog.integrations, input);
16322
+ } catch (err) {
16323
+ throw new HttpError(400, err.message);
16324
+ }
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);
16326
+ if (!unchanged() || busy2()) throw new HttpError(409, "Agent setup or work changed; reload connections.");
16327
+ if (replaceable()) this.dropSignIn(id);
16328
+ const term = this.terminalFor(a);
16329
+ const end = async (code) => {
16330
+ if (this.openCodeAuthRun !== operation) return;
16331
+ if (code === 0 && catalog.scope === "box" && unchanged()) {
16332
+ const ready2 = await this.boxMachines.openCodeConnectionReady(machine, this.boxMachines.deskDir(machine, this.repo(a.repoId).fullName), this.modelFor(a, "opencode")).catch(() => false);
16333
+ if (this.openCodeAuthRun !== operation) return;
16334
+ if (ready2 && unchanged()) {
16335
+ a.needsSignIn = false;
16336
+ delete a.openCodeAuthRejected;
16337
+ this.emitAgent(a);
16338
+ this.save();
16339
+ }
16340
+ }
16341
+ this.openCodeAuthRun = null;
16342
+ this.configuringOpenCode = false;
16343
+ term.note(code === 0 ? "OpenCode authentication command completed. Refresh connections; use auth list in OpenCode to verify the active account." : "OpenCode authentication did not complete. Refresh connections before retrying.");
16344
+ };
16345
+ if (catalog.scope === "box") {
16346
+ const api = this.cloud.boxApi();
16347
+ const boxId = await this.boxMachines.boxId(this.machineOf(a));
16348
+ if (!unchanged()) throw new HttpError(409, "Agent setup changed; reload connections.");
16349
+ if (!api || !boxId) throw new HttpError(409, "Cloud machine is not ready. No Box was created.");
16350
+ operation.run = this.backend.cloud.signIn({ api, boxId, cli: "opencode", term, agentId: id, authArgs: args }, end);
16351
+ } else {
16352
+ if (!this.backend.openCodeAuth) throw new HttpError(409, "OpenCode authentication is unavailable in this backend.");
16353
+ operation.run = this.backend.openCodeAuth({ args, term, agentId: id, cwd: a.role === "ceo" ? CEO_DIR : this.backend.mainDir(this.repo(a.repoId).fullName) }, end);
16354
+ }
16355
+ return { started: true };
16356
+ } catch (err) {
16357
+ if (this.openCodeAuthRun === operation) {
16358
+ this.openCodeAuthRun = null;
16359
+ this.configuringOpenCode = false;
16360
+ }
16361
+ throw err;
16362
+ }
16363
+ }
16364
+ cancelOpenCodeConfiguration(id) {
16365
+ if (this.openCodeAuthRun?.agentId !== id) throw new HttpError(409, "No OpenCode authentication is running for this agent.");
16366
+ this.openCodeAuthRun.run?.stop();
16367
+ this.openCodeAuthRun = null;
16368
+ this.configuringOpenCode = false;
16369
+ return { stopped: true };
16370
+ }
15855
16371
  openCodeModels(agentId, repoId2, refresh = false) {
15856
16372
  let directory = process.cwd();
15857
16373
  if (agentId) {
15858
16374
  const a = this.agent(agentId);
16375
+ if (a.host === "box" && a.role !== "ceo") {
16376
+ const machine = this.machineOf(a);
16377
+ return this.boxMachines.openCodeModels(machine, this.boxMachines.deskDir(machine, this.repo(a.repoId).fullName));
16378
+ }
15859
16379
  if (a.role === "ceo") {
15860
16380
  return fs21.mkdir(CEO_DIR, { recursive: true }).then(() => this.backend.openCodeModels(CEO_DIR, refresh));
15861
16381
  }
@@ -15883,7 +16403,7 @@ var Swarm = class {
15883
16403
  color: FLOOR_COLORS[(floor - 1) % FLOOR_COLORS.length],
15884
16404
  autoAssign: !!opts.autoAssign,
15885
16405
  autoMerge: opts.autoMerge !== false,
15886
- browserTesting: true,
16406
+ browserTesting: opts.browserTesting !== false,
15887
16407
  links: [],
15888
16408
  localPath: folder2,
15889
16409
  mission: (opts.mission ?? "").trim().slice(0, 4e3),
@@ -16237,6 +16757,7 @@ var Swarm = class {
16237
16757
  return this.shutdownTask;
16238
16758
  }
16239
16759
  async finishShutdown(restart) {
16760
+ if (this.openCodeAuthRun) this.cancelOpenCodeConfiguration(this.openCodeAuthRun.agentId);
16240
16761
  this.backend.cloud.detach();
16241
16762
  await this.writeState().catch((err) => console.warn("could not save the state", err));
16242
16763
  try {
@@ -16588,13 +17109,13 @@ var Swarm = class {
16588
17109
  // ---------- cloud agents (docs/cloud.md) ----------
16589
17110
  /**
16590
17111
  * Where a new (or moving) agent works: what was asked, else the office default. A cloud agent needs the Upstash key,
16591
- * room under the plan's Box limit and a CLI a Box can run (Claude Code or Codex). `strict`: the manager asked for the
17112
+ * room under the plan's Box limit and a supported CLI (Claude Code, Codex or OpenCode). `strict`: the manager asked for the
16592
17113
  * cloud, so say why not; otherwise (a floor's first agent, the demo) they work on this computer instead.
16593
17114
  */
16594
- hostFor(asked, cli, strict, moving) {
17115
+ hostFor(asked, _cli, strict, moving) {
16595
17116
  const want = asked === "box" || asked === "local" ? asked : this.state.settings.cloud.machineKind;
16596
17117
  if (want === "local") return "local";
16597
- const why2 = !this.cloud.boxApi() ? "Cloud agents need your Upstash Box API key first: Settings \u2192 Cloud agents." : cli === "opencode" ? "OpenCode can't run in a cloud machine yet: give this agent Claude Code or Codex." : !this.boxRoom(moving) ? `Your Upstash plan's Box limit (${this.state.settings.cloud.boxLimit}) is reached. Raise it in Settings \u2192 Cloud agents if your plan allows more, or delete Boxes you don't need.` : null;
17118
+ const why2 = !this.cloud.boxApi() ? "Cloud agents need your Upstash Box API key first: Settings \u2192 Cloud agents." : !this.boxRoom(moving) ? `Your Upstash plan's Box limit (${this.state.settings.cloud.boxLimit}) is reached. Raise it in Settings \u2192 Cloud agents if your plan allows more, or delete Boxes you don't need.` : null;
16598
17119
  if (!why2) return "box";
16599
17120
  if (strict || asked === "box") throw new HttpError(409, why2);
16600
17121
  return "local";
@@ -16634,6 +17155,7 @@ var Swarm = class {
16634
17155
  a.boxCli = null;
16635
17156
  this.dropSignIn(a.id);
16636
17157
  delete a.needsSignIn;
17158
+ delete a.openCodeAuthRejected;
16637
17159
  a.sessionId = null;
16638
17160
  a.sessionCli = null;
16639
17161
  for (const q of this.state.qa) if (q.devAgentId === a.id) q.devSessionId = null;
@@ -16652,7 +17174,7 @@ var Swarm = class {
16652
17174
  const boxId = await this.boxMachines.ensure(machine, (text3) => this.appendLog(a, [{ kind: "system", text: `\u2601 ${text3}` }]));
16653
17175
  const creds = await this.cloud.credentials(cli);
16654
17176
  if (creds.missing.length) throw new Error(`Cloud agents can't sign in yet. Missing: ${creds.missing.join("; ")}.`);
16655
- if (check && creds.ownLogin && cli !== "opencode" && await this.boxMachines.signedIn(machine, cli).catch(() => null) === false) throw new SignInNeeded(cli);
17177
+ if (check && creds.ownLogin && !await this.boxSignedIn(a, cli)) throw new SignInNeeded(cli);
16656
17178
  const browser = browserTesting ? await api.browser(boxId).catch(() => false) : false;
16657
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) };
16658
17180
  }
@@ -16690,6 +17212,42 @@ var Swarm = class {
16690
17212
  });
16691
17213
  }
16692
17214
  // ---------- signing cloud agents in (docs/cloud.md) ----------
17215
+ boxSignedIn(a, cli) {
17216
+ const machine = this.machineOf(a);
17217
+ return this.boxMachines.signedIn(machine, cli, this.boxMachines.deskDir(machine, this.repo(a.repoId).fullName), this.modelFor(a, cli));
17218
+ }
17219
+ /** Explicit post-auth check for a held-free OpenCode Box: metadata only, never provisions or releases a task. */
17220
+ async refreshOpenCodeSignIn(id) {
17221
+ const a = this.agent(id);
17222
+ if (a.host !== "box" || (a.cli || this.state.settings.defaultCli) !== "opencode" || BUSY3.includes(a.status) || this.signIns.get(id)?.held) throw new HttpError(409, "Stop held work before verifying this OpenCode connection.");
17223
+ const machine = this.machineOf(a);
17224
+ const ready2 = await this.boxMachines.openCodeConnectionReady(machine, this.boxMachines.deskDir(machine, this.repo(a.repoId).fullName), this.modelFor(a, "opencode"));
17225
+ if (!this.state.agents.includes(a) || a.host !== "box" || this.machineOf(a) !== machine) throw new HttpError(409, "Agent host changed during connection check.");
17226
+ if (ready2) {
17227
+ this.dropSignIn(id);
17228
+ a.needsSignIn = false;
17229
+ delete a.openCodeAuthRejected;
17230
+ this.emitAgent(a);
17231
+ this.save();
17232
+ }
17233
+ return ready2;
17234
+ }
17235
+ /** Detailed OAuth-only smoke-gate probe; never provisions a Box or releases held work. */
17236
+ async inspectOpenCodeSignIn(id) {
17237
+ const a = this.agent(id);
17238
+ if (a.host !== "box" || (a.cli || this.state.settings.defaultCli) !== "opencode" || BUSY3.includes(a.status) || this.signIns.get(id)?.held) throw new HttpError(409, "Stop held work before verifying this OpenCode connection.");
17239
+ const machine = this.machineOf(a);
17240
+ const result = await this.boxMachines.openCodeReadiness(machine, this.boxMachines.deskDir(machine, this.repo(a.repoId).fullName), this.modelFor(a, "opencode"));
17241
+ if (!this.state.agents.includes(a) || a.host !== "box" || this.machineOf(a) !== machine) throw new HttpError(409, "Agent host changed during connection check.");
17242
+ if (result.state === "ready") {
17243
+ this.dropSignIn(id);
17244
+ a.needsSignIn = false;
17245
+ delete a.openCodeAuthRejected;
17246
+ this.emitAgent(a);
17247
+ this.save();
17248
+ }
17249
+ return result;
17250
+ }
16693
17251
  /**
16694
17252
  * A cloud agent's CLI has no login in their Box (a new Box, or one that expired): they're marked as needing a sign-in
16695
17253
  * and take no work, the task they were starting (if any) waits, and the CLI's own sign-in starts in their terminal.
@@ -16697,6 +17255,7 @@ var Swarm = class {
16697
17255
  holdForSignIn(a, cli, task, expired2 = false) {
16698
17256
  if (!this.state.agents.includes(a) || a.host !== "box") return;
16699
17257
  const s2 = this.signInOf(a, cli);
17258
+ if (cli === "opencode" && expired2) a.openCodeAuthRejected = true;
16700
17259
  const label = cliLabel(cli);
16701
17260
  if (task) {
16702
17261
  a.status = "preparing";
@@ -16735,6 +17294,7 @@ var Swarm = class {
16735
17294
  }
16736
17295
  /** Their sign-in goes (they left, moved to this computer): its CLI closes and a held task is dropped with it. */
16737
17296
  dropSignIn(agentId) {
17297
+ if (this.openCodeAuthRun?.agentId === agentId && this.openCodeAuthRun.run) this.cancelOpenCodeConfiguration(agentId);
16738
17298
  const s2 = this.signIns.get(agentId);
16739
17299
  if (!s2) return;
16740
17300
  this.signIns.delete(agentId);
@@ -16743,9 +17303,11 @@ var Swarm = class {
16743
17303
  }
16744
17304
  /** Start the CLI's own sign-in in their terminal, unless it's running already. */
16745
17305
  async startSignIn(a) {
17306
+ if (this.backend.cloud.automaticSignIn === false) return;
17307
+ if (this.configuringOpenCode) return;
16746
17308
  const cli = a.cli || this.state.settings.defaultCli;
16747
17309
  const api = this.cloud.boxApi();
16748
- if (!a.needsSignIn || a.host !== "box" || cli === "opencode" || !api) return;
17310
+ if (!a.needsSignIn || a.host !== "box" || !api) return;
16749
17311
  const s2 = this.signInOf(a, cli);
16750
17312
  if (s2.run || s2.starting) return;
16751
17313
  s2.starting = true;
@@ -16768,7 +17330,8 @@ var Swarm = class {
16768
17330
  s2.poll = setTimeout(() => {
16769
17331
  s2.poll = null;
16770
17332
  if (this.signIns.get(a.id) !== s2 || !s2.run) return;
16771
- void this.boxMachines.signedIn(this.machineOf(a), s2.cli).catch(() => null).then((ok) => {
17333
+ if (s2.cli === "opencode" && a.openCodeAuthRejected) return;
17334
+ void this.boxSignedIn(a, s2.cli).catch(() => null).then((ok) => {
16772
17335
  if (this.signIns.get(a.id) !== s2) return;
16773
17336
  if (ok) this.signedIn(a);
16774
17337
  else if (s2.run) this.pollSignIn(a, s2);
@@ -16780,9 +17343,9 @@ var Swarm = class {
16780
17343
  if (this.signIns.get(a.id) !== s2) return;
16781
17344
  s2.run = null;
16782
17345
  if (s2.poll) clearTimeout(s2.poll);
16783
- const ok = await this.boxMachines.signedIn(this.machineOf(a), s2.cli).catch(() => null);
17346
+ const ok = await this.boxSignedIn(a, s2.cli).catch(() => null);
16784
17347
  if (this.signIns.get(a.id) !== s2 || s2.run) return;
16785
- if (ok) return this.signedIn(a);
17348
+ if (ok && !(s2.cli === "opencode" && a.openCodeAuthRejected && code !== 0)) return this.signedIn(a);
16786
17349
  this.agentRt.get(a.id)?.terminal?.note(`Not signed in yet. \u{1F511} Sign in starts it again.`);
16787
17350
  this.appendLog(a, [{ kind: "error", text: `\u{1F511} ${cliLabel(s2.cli)} didn't finish signing in${code > 0 ? ` (it exited with code ${code})` : ""}. \u{1F511} Sign in in their terminal starts it again.` }]);
16788
17351
  }
@@ -16795,6 +17358,7 @@ var Swarm = class {
16795
17358
  if (run2) setTimeout(() => run2.stop(), 3e3);
16796
17359
  if (!a.needsSignIn) return;
16797
17360
  a.needsSignIn = false;
17361
+ delete a.openCodeAuthRejected;
16798
17362
  this.appendLog(a, [{ kind: "done", text: `\u2714 ${cliLabel(s2?.cli ?? "claude")} is signed in in their cloud machine.${s2?.held ? " Back to the task." : ""}` }]);
16799
17363
  this.emitAgent(a);
16800
17364
  this.save();
@@ -16814,15 +17378,19 @@ var Swarm = class {
16814
17378
  s2?.run?.stop();
16815
17379
  if (s2) s2.run = null;
16816
17380
  }
16817
- if (cli === "opencode") return this.signedIn(a);
17381
+ if (cli === "opencode" && a.openCodeAuthRejected) {
17382
+ this.holdForSignIn(a, cli, null, true);
17383
+ return;
17384
+ }
16818
17385
  const creds = await this.cloud.credentials(cli).catch(() => null);
16819
- const ok = !creds ? null : creds.ownLogin ? await this.boxMachines.signedIn(this.machineOf(a), cli).catch(() => null) : true;
17386
+ const ok = !creds ? null : creds.ownLogin ? await this.boxSignedIn(a, cli).catch(() => null) : true;
16820
17387
  if (!this.state.agents.includes(a) || a.host !== "box") return;
16821
17388
  if (ok === true) this.signedIn(a);
16822
17389
  else if (ok === false) this.holdForSignIn(a, cli, null);
16823
17390
  }
16824
17391
  /** POST /api/agents/:id/sign-in: start a cloud agent's sign-in (over) in their terminal: it ended, went stale or never started. */
16825
17392
  signIn(id) {
17393
+ if (this.configuringOpenCode) throw new HttpError(409, "Finish OpenCode authentication in the terminal first.");
16826
17394
  const a = this.agent(id);
16827
17395
  if (a.host !== "box") throw new HttpError(409, `${a.name} works on this computer: their coding agent signs in there.`);
16828
17396
  if (!a.needsSignIn) throw new HttpError(409, `${a.name}'s coding agent is signed in already.`);
@@ -16866,12 +17434,12 @@ var Swarm = class {
16866
17434
  return !this.clis.length || this.clis.some((c) => c.id === cli && c.installed);
16867
17435
  }
16868
17436
  updateAgent(id, patch) {
17437
+ if (this.openCodeAuthRun?.agentId === id && (patch.host !== void 0 || patch.cli !== void 0)) throw new HttpError(409, "Finish or stop OpenCode authentication before changing the host or coding agent.");
16869
17438
  const a = this.agent(id);
16870
17439
  if (patch.host !== void 0 && a.role !== "ceo" && (patch.host === "box" || patch.host === "local")) this.moveAgent(a, patch.host);
16871
17440
  if (patch.cli !== void 0) {
16872
17441
  const cli = isCli(patch.cli) ? patch.cli : "";
16873
17442
  if (a.role === "ceo" && cli && cli !== "claude" && cli !== "opencode") throw new HttpError(400, "The CEO can run Claude Code or OpenCode.");
16874
- if (a.host === "box" && (cli || this.state.settings.defaultCli) === "opencode") throw new HttpError(400, `${a.name} works in the cloud, where OpenCode can't run yet: move them to this computer first.`);
16875
17443
  const localCli = cli || (a.role === "ceo" ? "claude" : this.state.settings.defaultCli);
16876
17444
  if (a.host !== "box" && (cli || localCli === "opencode") && !this.cliReady(localCli)) throw new HttpError(400, `${cliLabel(localCli)} isn't installed on this computer.`);
16877
17445
  const changed = cli !== a.cli;
@@ -16980,6 +17548,7 @@ var Swarm = class {
16980
17548
  );
16981
17549
  }
16982
17550
  ensureSlot() {
17551
+ if (this.configuringOpenCode) throw new HttpError(409, "Finish OpenCode authentication in the terminal first.");
16983
17552
  if (this.slotsFull()) {
16984
17553
  throw new HttpError(429, `All ${this.state.settings.sessionLimit} session slots are busy. Raise or clear the session limit in the manager's console, or wait.`);
16985
17554
  }
@@ -17093,7 +17662,18 @@ var Swarm = class {
17093
17662
  };
17094
17663
  return t;
17095
17664
  }
17096
- async saveTerminals(all = false) {
17665
+ saveTerminals(all = false) {
17666
+ if (!all && (this.stopping || this.terminalSaving)) return this.terminalSaving ?? Promise.resolve();
17667
+ const write = () => this.writeTerminals(all);
17668
+ const next = this.terminalSaving ? this.terminalSaving.then(write, write) : write();
17669
+ this.terminalSaving = next;
17670
+ const clear = () => {
17671
+ if (this.terminalSaving === next) this.terminalSaving = null;
17672
+ };
17673
+ void next.then(clear, clear);
17674
+ return next;
17675
+ }
17676
+ async writeTerminals(all) {
17097
17677
  const pending2 = [...this.agentRt].flatMap(
17098
17678
  ([id, rt]) => rt.terminal && (all || rt.terminal.dirty) ? [{ id, terminal: rt.terminal }] : []
17099
17679
  );
@@ -17395,8 +17975,8 @@ Note from the manager: ${note2}` : ""
17395
17975
  async signedOutMidTask(a, repo, result, cli, again) {
17396
17976
  const rt = this.agentRt.get(a.id);
17397
17977
  if (!rt || !this.state.agents.includes(a)) return;
17398
- const creds = cli === "opencode" ? null : await this.cloud.credentials(cli).catch(() => null);
17399
- if (cli === "opencode" || !creds?.ownLogin || a.status === "stopped" || this.dropping.has(a.id) || a.host !== "box") {
17978
+ const creds = await this.cloud.credentials(cli).catch(() => null);
17979
+ if (!creds?.ownLogin || a.status === "stopped" || this.dropping.has(a.id) || a.host !== "box") {
17400
17980
  const errors = creds && !creds.ownLogin ? [`${cliLabel(cli)} turned the key it was given away: check it in Settings \u2192 Cloud agents.`] : result.errors;
17401
17981
  return this.onFinished(a, repo, { ...result, errors });
17402
17982
  }
@@ -17599,6 +18179,7 @@ Note from the manager: ${note2}` : ""
17599
18179
  return qaSystemPrompt({ agent: a, repo, port: this.port(a), cwd, branch, pr, testStep: testStep2, depsLine: depsPromptLine(deps) });
17600
18180
  }
17601
18181
  async runQa(a, repo, rec) {
18182
+ if (this.backend.allowWork && !this.backend.allowWork("qa", a)) return;
17602
18183
  const branch = qaBranch(rec.prNumber, slugify(a.name));
17603
18184
  this.qaWaits.set(`${repo.id}#${rec.prNumber}`, Date.now() - rec.updatedAt);
17604
18185
  this.setQa(rec, { status: "testing", qaAgentId: a.id });
@@ -17819,6 +18400,7 @@ ${issue2.body.trim() || "(no description)"}` : ""
17819
18400
  }
17820
18401
  /** Send a failed PR back to the agent who wrote it (or any free agent on the floor). */
17821
18402
  async runFix(dev, repo, rec) {
18403
+ if (this.backend.allowWork && !this.backend.allowWork("fix", dev)) return;
17822
18404
  const original = rec.devAgentId === dev.id;
17823
18405
  const pull = this.repoRt.get(repo.id)?.pulls.find((p) => p.number === rec.prNumber);
17824
18406
  const headRef = pull?.headRefName ?? dev.branch ?? `pr-${rec.prNumber}`;
@@ -18124,20 +18706,24 @@ ${text3}` : text3);
18124
18706
  ).sort((x, y) => x.updatedAt - y.updatedAt);
18125
18707
  const fixes = waiting("failed", "fix");
18126
18708
  const owed = new Set(fixes.map((q) => q.devAgentId).filter((id) => !!id));
18709
+ const qaFree = free.filter((a) => this.mayStart("qa", a));
18127
18710
  for (const rec of waiting("queued", "qa")) {
18128
18711
  const othersCan = this.state.agents.some((a) => a.repoId === repo.id && a.role !== "ceo" && a.id !== rec.devAgentId && a.status !== "stopped");
18129
- const tester = pickTester(free, rec.devAgentId, owed, othersCan, now2 - rec.updatedAt);
18712
+ const tester = pickTester(qaFree, rec.devAgentId, owed, othersCan, now2 - rec.updatedAt);
18130
18713
  if (!tester) continue;
18131
18714
  void this.runQa(tester, repo, rec);
18132
18715
  return true;
18133
18716
  }
18717
+ const fixFree = free.filter((a) => this.mayStart("fix", a));
18134
18718
  for (const rec of fixes) {
18719
+ if (!fixFree.length) continue;
18135
18720
  const author = this.state.agents.find((a) => a.id === rec.devAgentId && a.repoId === repo.id && a.role !== "ceo") ?? null;
18136
18721
  if (author && this.limited(author)) continue;
18722
+ if (author && !this.mayStart("fix", author)) continue;
18137
18723
  const headRef = this.repoRt.get(repo.id).pulls.find((p) => p.number === rec.prNumber)?.headRefName ?? null;
18138
- const to = fixGoesTo(author, !!author && free.includes(author), rec.prNumber, headRef);
18724
+ const to = fixGoesTo(author, !!author && fixFree.includes(author), rec.prNumber, headRef);
18139
18725
  if (to === "wait") continue;
18140
- void this.runFix(to === "author" ? author : free.find((a) => !owed.has(a.id)) ?? free[0], repo, rec);
18726
+ void this.runFix(to === "author" ? author : fixFree.find((a) => !owed.has(a.id)) ?? fixFree[0], repo, rec);
18141
18727
  return true;
18142
18728
  }
18143
18729
  return false;
@@ -18251,6 +18837,8 @@ ${text3}` : text3);
18251
18837
  }
18252
18838
  /** May work of this kind start now, as far as Claude's usage goes? */
18253
18839
  mayStart(kind, a) {
18840
+ if (this.backend.allowWork && !this.backend.allowWork(kind, a)) return false;
18841
+ if (this.configuringOpenCode) return false;
18254
18842
  const key = this.gateKey(a);
18255
18843
  const running = this.state.agents.filter((other) => BUSY3.includes(other.status) && this.gateKey(other) === key).length;
18256
18844
  return this.quotaGate().allows(key, kind, Date.now(), running, this.state.settings.pacingSessions);
@@ -18694,6 +19282,7 @@ ${job.text}` } : job;
18694
19282
  browserTesting: false,
18695
19283
  additionalDirectories: this.state.repos.filter((r) => this.repoRt.get(r.id)?.cloneStatus === "ready").map((r) => this.backend.mainDir(r.fullName)),
18696
19284
  role: "ceo",
19285
+ agentId: a.id,
18697
19286
  office: this.officeTools(),
18698
19287
  ...how
18699
19288
  },
@@ -19932,6 +20521,9 @@ app.post("/api/agents/:id/analyze", route((req) => swarm.analyze(String(req.para
19932
20521
  app.post("/api/agents/:id/reset", route((req) => swarm.resetAgent(String(req.params.id))));
19933
20522
  app.post("/api/agents/:id/message", route((req) => swarm.message(String(req.params.id), str(req.body.text))));
19934
20523
  app.post("/api/agents/:id/sign-in", route((req) => swarm.signIn(String(req.params.id))));
20524
+ app.get("/api/agents/:id/opencode/connections", route((req) => swarm.openCodeConnections(String(req.params.id))));
20525
+ app.post("/api/agents/:id/opencode/connections", route((req) => swarm.configureOpenCode(String(req.params.id), req.body?.selection, req.body?.scope)));
20526
+ app.delete("/api/agents/:id/opencode/connections", route((req) => swarm.cancelOpenCodeConfiguration(String(req.params.id))));
19935
20527
  app.get("/api/agents/:id/prompt", route((req) => swarm.agentPrompt(String(req.params.id))));
19936
20528
  app.get("/api/agents/:id/screen", (req, res) => {
19937
20529
  const shot = swarm.screenshot(String(req.params.id));