droidsembly 0.4.0-beta.3 → 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-HB1JfQbh.js → AccessibilitySettings-6ZCswq5I.js} +3 -3
  4. package/dist/assets/{AppViewer-0Bly3EdB.js → AppViewer-CqGa1r0z.js} +1 -1
  5. package/dist/assets/{Balloon-B6odnAlm.js → Balloon-dO9J4khp.js} +1 -1
  6. package/dist/assets/{Batched-CTJWq46z.js → Batched-CmXZtCvQ.js} +1 -1
  7. package/dist/assets/{Birds-DSS0OIz9.js → Birds-D51xGT0l.js} +1 -1
  8. package/dist/assets/{Blimp-CZt6dddK.js → Blimp-C2c_AKRR.js} +1 -1
  9. package/dist/assets/{BufferGeometryUtils-CmpUrBC5.js → BufferGeometryUtils-Dcu0heeS.js} +1 -1
  10. package/dist/assets/{Duck-BnRLkodp.js → Duck-CzFiUF6U.js} +1 -1
  11. package/dist/assets/{Effects-Bkewth1L.js → Effects-DwOi-gSQ.js} +1 -1
  12. package/dist/assets/{Fireworks-Cvn8YKWd.js → Fireworks-Cc2mGzPJ.js} +1 -1
  13. package/dist/assets/{Helicopter-BDrFQMNX.js → Helicopter-ltB-x8hG.js} +1 -1
  14. package/dist/assets/{Hurricane-C8hyFXjx.js → Hurricane-C2qHsRw4.js} +1 -1
  15. package/dist/assets/{Kaiju-Bxxe9DG0.js → Kaiju-DPHVjFjg.js} +1 -1
  16. package/dist/assets/{Meteors-UdYL0Tbv.js → Meteors-CxcguXTJ.js} +1 -1
  17. package/dist/assets/{MissionConsole-DJRtojZP.js → MissionConsole-BUE2mijT.js} +1 -1
  18. package/dist/assets/{Office-9Mank16i.js → Office-NV5zlSnK.js} +8 -8
  19. package/dist/assets/{PhotoPanel-C_njIXp0.js → PhotoPanel-CDqgU99Z.js} +1 -1
  20. package/dist/assets/{PhotoScene-DwpeJjGe.js → PhotoScene-RRXC4_Jv.js} +3 -3
  21. package/dist/assets/{Plane-DzvUAUYE.js → Plane-BQB72TWZ.js} +1 -1
  22. package/dist/assets/{Pocket-A1iI6Ivy.js → Pocket-CjK6fv97.js} +2 -2
  23. package/dist/assets/{Rainbow-CV1rD6rW.js → Rainbow-DIpZi5-z.js} +1 -1
  24. package/dist/assets/{Roof-DSpKcGXK.js → Roof-Cd9I0jtG.js} +1 -1
  25. package/dist/assets/{Shell-GaQY3zre.js → Shell-DCqHgrm_.js} +1 -1
  26. package/dist/assets/{Skywriting-D4B2ZvH7.js → Skywriting-BH6FCdEl.js} +1 -1
  27. package/dist/assets/TerminalView-CoH1yh6r.js +17 -0
  28. package/dist/assets/{ToyWorld-DeQUxcuy.js → ToyWorld--k4uqi9k.js} +1 -1
  29. package/dist/assets/{Ufo-CitoxReu.js → Ufo-C5cYunS9.js} +1 -1
  30. package/dist/assets/{Whale-Btx5ph-T.js → Whale-BAXeezd8.js} +1 -1
  31. package/dist/assets/{all-gw-szDg1.js → all-BsJ98bWd.js} +1 -1
  32. package/dist/assets/{bloomMarks-DRhDp19k.js → bloomMarks-JYeAmd4d.js} +1 -1
  33. package/dist/assets/{cheerRules-DWb8Qwzg.js → cheerRules-DvM2z9Qg.js} +1 -1
  34. package/dist/assets/{cityLayout-aA2Ktgpu.js → cityLayout-VU-ug-r6.js} +1 -1
  35. package/dist/assets/{dogState-DY7tJEVD.js → dogState-Bm3YZHwy.js} +1 -1
  36. package/dist/assets/{doors-BlKvxXVp.js → doors-D7Z3s-7W.js} +1 -1
  37. package/dist/assets/{gallery-COKuWb9E.js → gallery-CSWmy4Tf.js} +1 -1
  38. package/dist/assets/{gate-D0uU0wv5.js → gate-DwsbbSNS.js} +2 -2
  39. package/dist/assets/{index-CDJgPTOC.js → index-D_Et7Vx8.js} +3 -3
  40. package/dist/assets/{instantReplay-BjoV6jrY.js → instantReplay-FXf2kJ7B.js} +1 -1
  41. package/dist/assets/{interact-0jqx03Xr.js → interact-BatJVhca.js} +1 -1
  42. package/dist/assets/{kit-n-eqZ1AT.js → kit-D3twk12W.js} +1 -1
  43. package/dist/assets/{mic-BnAa4E99.js → mic-BJ0eYLIj.js} +1 -1
  44. package/dist/assets/{photoMode-BybFMLKC.js → photoMode-B8pRCF0O.js} +1 -1
  45. package/dist/assets/{pipeline-BGPWXegt.js → pipeline-BgOS9JnJ.js} +1 -1
  46. package/dist/assets/{rapier-CrXmTSyE.js → rapier-BvQbKz0M.js} +1 -1
  47. package/dist/assets/{rig-DfdntE8m.js → rig-BgSxc8mA.js} +1 -1
  48. package/dist/assets/{speechLanguage-DfsQvU9M.js → speechLanguage-Cak8tdL0.js} +1 -1
  49. package/dist/assets/store-Buxt6UcJ.js +5 -0
  50. package/dist/assets/{useDayTime-BjBDzh_t.js → useDayTime-0ms3va3h.js} +1 -1
  51. package/dist/assets/{useGraphics-Bg6L4EdS.js → useGraphics-p7LAuvYj.js} +1 -1
  52. package/dist/assets/{voiceMessages-CFLyZLZ4.js → voiceMessages-hO1SDnOS.js} +1 -1
  53. package/dist/assets/{weatherState-BJVm5hU-.js → weatherState-BQ3UU4vU.js} +1 -1
  54. package/dist/index.html +2 -2
  55. package/dist-server/index.js +661 -88
  56. package/dist-server/index.js.map +4 -4
  57. package/package.json +1 -1
  58. package/dist/assets/TerminalView-DhmLqjYn.js +0 -17
  59. package/dist/assets/store-CXLtXw8e.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,15 +1493,15 @@ 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
1499
  default_agent: "droidsembly",
1497
1500
  agents: {
1498
- droidsembly: { description: "The Droidsembly office session", mode: "primary", ...model2 ? { model: model2 } : {} },
1501
+ droidsembly: { description: "The Droidsembly office session", mode: "primary", ...model2 ? { model: model2 } : {}, ...ctx.openCodePermissions ? { permissions: ctx.openCodePermissions } : {} },
1499
1502
  // OpenCode keeps the agent ID on an existing session. Keep the old profile available on resume,
1500
1503
  // but out of the picker: do not migrate session IDs or rewrite the user's OpenCode history.
1501
- ...ctx.resumeId ? { cubefarm: { description: "The Droidsembly office session (legacy)", mode: "primary", hidden: true, ...model2 ? { model: model2 } : {} } } : {}
1504
+ ...ctx.resumeId ? { cubefarm: { description: "The Droidsembly office session (legacy)", mode: "primary", hidden: true, ...model2 ? { model: model2 } : {}, ...ctx.openCodePermissions ? { permissions: ctx.openCodePermissions } : {} } } : {}
1502
1505
  },
1503
1506
  ...opencodeLocal(local),
1504
1507
  ...Object.keys(servers).length ? { mcp: { servers } } : {}
@@ -1617,12 +1620,19 @@ var OPENCODE_PLUGIN_SOURCE = String.raw`// cubefarm: forward only this office se
1617
1620
  export default {
1618
1621
  id: 'cubefarm.office',
1619
1622
  async setup(ctx) {
1620
- const { sessionID, notifyUrl } = ctx.options;
1621
- 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;
1622
1626
  const controller = new AbortController();
1623
1627
  let lastIdle;
1628
+ let authFailed = false;
1624
1629
  const reportedUsage = new Map();
1625
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
+ }
1626
1636
  const response = await fetch(notifyUrl, {
1627
1637
  method: 'POST', headers: { 'content-type': 'application/json' },
1628
1638
  body: JSON.stringify({ ...body, session_id: sessionID }),
@@ -1667,7 +1677,10 @@ export default {
1667
1677
  };
1668
1678
  await observe('model.request', (event) => reportResource(event));
1669
1679
  await observe('http.response', async (event) => {
1670
- 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;
1671
1684
  const retry = event.response.headers.get('retry-after');
1672
1685
  const seconds = retry && /^\d+(?:\.\d+)?$/.test(retry) ? Number(retry) : NaN;
1673
1686
  const at = Number.isFinite(seconds) ? Date.now() + seconds * 1000 : retry ? Date.parse(retry) : NaN;
@@ -1680,6 +1693,13 @@ export default {
1680
1693
  for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
1681
1694
  const props = event.data ?? event.properties ?? event;
1682
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
+ }
1683
1703
  if (!['session.execution.succeeded', 'session.execution.failed', 'session.execution.interrupted', 'session.idle'].includes(event.type)) continue;
1684
1704
  const [messages, session] = await Promise.all([
1685
1705
  ctx.session.context({ sessionID }), ctx.session.get({ sessionID }),
@@ -1711,7 +1731,7 @@ export default {
1711
1731
  if (outcome === 'interrupted') {
1712
1732
  await post({ hook_event_name: 'Interrupt' });
1713
1733
  } else if (outcome === 'failed') {
1714
- 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 } : {}) });
1715
1735
  } else {
1716
1736
  const user = messages.findLastIndex((m) => m.type === 'user');
1717
1737
  const reply = messages.slice(user + 1).findLast((m) => m.type === 'assistant');
@@ -2233,7 +2253,7 @@ function decoder(onText) {
2233
2253
  if (text3) onText(text3);
2234
2254
  };
2235
2255
  }
2236
- function upstashBoxes(apiKey) {
2256
+ function upstashBoxes(apiKey, options = {}) {
2237
2257
  const conn2 = { apiKey, enableTelemetry: false };
2238
2258
  const boxes = /* @__PURE__ */ new Map();
2239
2259
  const box = async (id) => {
@@ -2273,7 +2293,7 @@ function upstashBoxes(apiKey) {
2273
2293
  return {
2274
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) }))),
2275
2295
  create: (o) => guard("create a Box", async () => {
2276
- const b = await Box.create({ ...conn2, name: o.name, labels: o.labels, size: o.size, runtime: "node", browser: true, timeout: 3e5 });
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 });
2277
2297
  boxes.set(b.id, b);
2278
2298
  return { id: b.id, name: o.name, labels: o.labels, status: "running" };
2279
2299
  }),
@@ -2300,9 +2320,16 @@ function upstashBoxes(apiKey) {
2300
2320
  run: (id, script, o = {}) => guard("run a command in a Box", async () => {
2301
2321
  let output = "";
2302
2322
  const s2 = await openSession(id, { cmd: script, env: o.env, onData: (t) => output += t });
2303
- 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);
2304
2328
  try {
2305
- 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 };
2306
2333
  } finally {
2307
2334
  clearTimeout(timer);
2308
2335
  }
@@ -2371,7 +2398,7 @@ function resolveCredentials(cli, i) {
2371
2398
  } else if (cli === "codex") {
2372
2399
  if (i.secrets.openaiApiKey) Object.assign(env, { OPENAI_API_KEY: i.secrets.openaiApiKey, CODEX_API_KEY: i.secrets.openaiApiKey });
2373
2400
  else ownLogin = true;
2374
- }
2401
+ } else if (cli === "opencode") ownLogin = true;
2375
2402
  return { env, apiKeyHelper, ownLogin, missing };
2376
2403
  }
2377
2404
  function githubEnv(i) {
@@ -2404,10 +2431,10 @@ var Cloud = class {
2404
2431
  ghAt = 0;
2405
2432
  boxes = null;
2406
2433
  async init() {
2407
- const s2 = await readSecrets(this.deps.secretsFile);
2434
+ const s2 = this.deps.credentials ?? await readSecrets(this.deps.secretsFile);
2408
2435
  for (const k of ["upstashBoxKey", "cloudGithubToken", "anthropicApiKey", "openaiApiKey"]) if (typeof s2[k] === "string" && s2[k]) this.secrets[k] = s2[k];
2409
2436
  if (this.secrets.upstashBoxKey) this.api = this.deps.boxes(this.secrets.upstashBoxKey);
2410
- await this.refreshGh(true);
2437
+ if (!this.secrets.cloudGithubToken) await this.refreshGh(true);
2411
2438
  }
2412
2439
  /** The Box API, or null while no key is saved. */
2413
2440
  boxApi() {
@@ -2416,6 +2443,7 @@ var Cloud = class {
2416
2443
  claudeToken = () => (this.deps.env[CLAUDE_TOKEN_ENV] ?? "").trim();
2417
2444
  /** The gh login token, re-read at most once a minute (the manager may sign in or out meanwhile). */
2418
2445
  async refreshGh(force = false) {
2446
+ if (this.deps.credentials) return "";
2419
2447
  if (!force && Date.now() - this.ghAt < 6e4) return this.gh;
2420
2448
  this.ghAt = Date.now();
2421
2449
  this.gh = await this.deps.ghToken().catch(() => "");
@@ -2447,6 +2475,7 @@ var Cloud = class {
2447
2475
  }
2448
2476
  /** PUT /api/cloud/key: '' disconnects; anything else must list the account's Boxes first. */
2449
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.");
2450
2479
  const key = raw.trim();
2451
2480
  if (key) {
2452
2481
  if (key.length > 400 || /\s/.test(key)) throw new HttpError(400, "That doesn't look like an Upstash Box API key.");
@@ -2467,6 +2496,7 @@ var Cloud = class {
2467
2496
  }
2468
2497
  /** PUT /api/cloud/token: a GitHub token, an Anthropic or an OpenAI API key for cloud agents ('' removes it). */
2469
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.");
2470
2500
  const value = raw.trim();
2471
2501
  if (value.length > 400 || /\s/.test(value)) throw new HttpError(400, "That doesn't look like a token or an API key.");
2472
2502
  if (kind === "anthropic" && value.startsWith("sk-ant-oat")) {
@@ -2554,7 +2584,7 @@ var BRANCH = /^[\w./-]+$/;
2554
2584
  function checkRepo(fullName) {
2555
2585
  if (!OWNER_REPO.test(fullName)) throw new Error(`Not a GitHub repository name: ${fullName}`);
2556
2586
  }
2557
- 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, "_");
2558
2588
  var TMUX_CONF = [
2559
2589
  "set -g status off",
2560
2590
  "set -g prefix None",
@@ -2569,31 +2599,45 @@ var TMUX_CONF = [
2569
2599
  ""
2570
2600
  ].join("\n");
2571
2601
  function setupScript(o) {
2572
- const marker = setupMarker(o.versions, o.rev);
2573
- 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
+ ];
2574
2612
  const helper = `!f() { test "$1" = get || exit 0; echo username=x-access-token; echo "password=$GH_TOKEN"; }; f`;
2575
2613
  return [
2576
2614
  "set -e",
2577
- `mkdir -p ${sq(BOX_BIN)} ${sq(BOX_SESSIONS)}`,
2578
- `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; }',
2579
2620
  'missing=""',
2580
- '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',
2581
2622
  'if [ -n "$missing" ]; then',
2582
- " sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq >/dev/null 2>&1 || true",
2583
- " 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",
2584
2625
  "fi",
2585
2626
  'command -v tmux >/dev/null 2>&1 || { echo "tmux could not be installed in the Box" >&2; exit 3; }',
2586
2627
  // Into the office's own folder, not the image's global one: the Box image ships its own CLIs first on the PATH.
2587
- `npm install -g --prefix ${sq(`${BOX_CF}/cli`)} --no-fund --no-audit --loglevel=error ${pkgs.map(sq).join(" ")} > /tmp/cubefarm-cli.log 2>&1 || { tail -n 5 /tmp/cubefarm-cli.log >&2; exit 4; }`,
2588
- `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
+ ] : [],
2589
2634
  "git config --global --unset-all credential.helper >/dev/null 2>&1 || true",
2590
2635
  `git config --global credential.https://github.com.helper ${sq(helper)}`,
2591
2636
  `git config --global user.name ${sq(o.gitName || "cubefarm")}`,
2592
2637
  `git config --global user.email ${sq(o.gitEmail || "cubefarm@users.noreply.github.com")}`,
2593
2638
  "git config --global init.defaultBranch main",
2594
2639
  "git config --global advice.detachedHead false",
2595
- `rm -f ${sq(BOX_CF)}/setup-*`,
2596
- `touch ${sq(marker)}`,
2640
+ `touch ${sq(marker2)}`,
2597
2641
  "echo CUBEFARM_SETUP_OK"
2598
2642
  ].join("\n");
2599
2643
  }
@@ -2604,6 +2648,7 @@ function prepareDeskScript(fullName, base, branch) {
2604
2648
  const desk = boxDeskDir(fullName);
2605
2649
  const ref = base.pr ? `origin/pr/${base.pr}` : `origin/${base.defaultBranch}`;
2606
2650
  return [
2651
+ "(",
2607
2652
  "set -e",
2608
2653
  `R=${sq(repo)}`,
2609
2654
  `W=${sq(desk)}`,
@@ -2631,7 +2676,8 @@ function prepareDeskScript(fullName, base, branch) {
2631
2676
  "fi",
2632
2677
  'rm -rf "$W"; mkdir -p "$(dirname "$W")"',
2633
2678
  'git worktree add -q -B "$B" "$W" "$REF"',
2634
- 'echo "$W"'
2679
+ 'echo "$W"',
2680
+ ")"
2635
2681
  ].join("\n");
2636
2682
  }
2637
2683
  function linkedReposScript(fullNames) {
@@ -2710,12 +2756,12 @@ function signInOutcome(output) {
2710
2756
  const last = output.split("\n").map((l) => l.trim()).filter((l) => /^CUBEFARM_SIGNED_(IN|OUT)$/.test(l)).pop();
2711
2757
  return last ? last === "CUBEFARM_SIGNED_IN" : null;
2712
2758
  }
2713
- var signOutScript = (cli) => `${sq(`${BOX_CLI_BIN}/${cli}`)} ${cli === "claude" ? "auth logout" : "logout"} >/dev/null 2>&1; true`;
2714
- var signInCommand = (cli) => ({ file: `${BOX_CLI_BIN}/${cli}`, args: cli === "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"] });
2715
2761
 
2716
2762
  // server/boxCli.ts
2717
2763
  var BOX_CDP = "http://127.0.0.1:9222";
2718
- var TURN_ENDS = ["Stop", "StopFailure", "TurnComplete"];
2764
+ var TURN_ENDS = ["Stop", "StopFailure", "TurnComplete", "TurnError", "Interrupt"];
2719
2765
  var EventLines = class {
2720
2766
  /** turnAt: where the last turn end seen starts (see BoxCliRecord.turnAt). */
2721
2767
  constructor(offset = 0, turnAt = offset) {
@@ -2796,7 +2842,11 @@ var BoxPty = class {
2796
2842
  replay(events, at) {
2797
2843
  void hooksOpen.then(() => {
2798
2844
  if (this.stopped) return;
2799
- 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;
2800
2850
  this.lines = new EventLines(at.offset, at.turnAt);
2801
2851
  this.o.save(at.offset, at.turnAt, this.meta);
2802
2852
  setTimeout(() => this.fireExit(exitCode(events) ?? (finishedTurn(events) ? 0 : -1)), 6e3);
@@ -2865,9 +2915,11 @@ var BoxPty = class {
2865
2915
  if (this.stopped || this.exited) return;
2866
2916
  let exit = null;
2867
2917
  for (const e of this.lines.push(text3)) {
2918
+ if (this.stopped || this.exited) return;
2868
2919
  if (e.hook_event_name === "CubefarmExit") exit = Number(e.code) || 0;
2869
2920
  else this.o.event(e);
2870
2921
  }
2922
+ if (this.stopped || this.exited) return;
2871
2923
  this.o.save(this.lines.offset, this.lines.turnAt, this.meta);
2872
2924
  if (exit !== null) this.fireExit(exit);
2873
2925
  }
@@ -2948,6 +3000,168 @@ async function sweepStrayClis(api, boxId, keepTokens) {
2948
3000
  return n;
2949
3001
  }
2950
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
+
2951
3165
  // server/ptyClient.ts
2952
3166
  import crypto2 from "node:crypto";
2953
3167
  import fs7 from "node:fs";
@@ -3377,9 +3591,9 @@ function startBoxSignIn(o, exited) {
3377
3591
  o.term.note(`\u2500\u2500 Signing ${cliLabel(o.cli)} in \xB7 \u2601 cloud machine \u2500\u2500`);
3378
3592
  void (async () => {
3379
3593
  try {
3380
- 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` }));
3381
3595
  if (over) return;
3382
- 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 : {});
3383
3597
  l.proc = pty;
3384
3598
  wire(l);
3385
3599
  await pty.open("new");
@@ -3395,6 +3609,42 @@ function startBoxSignIn(o, exited) {
3395
3609
  }
3396
3610
  };
3397
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
+ }
3398
3648
  function hooksReady2() {
3399
3649
  hooksReady();
3400
3650
  boxHooksReady();
@@ -3658,6 +3908,11 @@ function startCliSession(opts, callbacks) {
3658
3908
  }
3659
3909
  case "UserPromptSubmit": {
3660
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
+ }
3661
3916
  busy2();
3662
3917
  const prompt2 = String(b.prompt ?? "").trim();
3663
3918
  const i = officePrompts.findIndex((p2) => p2.slice(0, 60) === prompt2.slice(0, 60));
@@ -3718,12 +3973,20 @@ function startCliSession(opts, callbacks) {
3718
3973
  case "TurnError":
3719
3974
  turnError = `${label}: ${clip(String(b.error ?? "error"), 200)}`;
3720
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
+ }
3721
3980
  turnEnded(lastText);
3722
3981
  return {};
3723
3982
  }
3724
3983
  return {};
3725
3984
  };
3726
3985
  const exited = (exitCode2) => {
3986
+ if (cli === "opencode" && turnError) {
3987
+ finish({ ok: false, text: lastText, errors: [turnError] });
3988
+ return;
3989
+ }
3727
3990
  if (cli === "claude" && opts.resumeSessionId && !begun && lostConversation(term.screen())) {
3728
3991
  cb.sessionId(null);
3729
3992
  finish({ ok: false, text: "", errors: [`${label} couldn't find the conversation it was resuming, so the next session starts a new one.`] });
@@ -3765,10 +4028,6 @@ function startCliSession(opts, callbacks) {
3765
4028
  return handle;
3766
4029
  }
3767
4030
  const cmd = box ? { file: `${BOX_CLI_BIN}/${CLIS.find((c) => c.id === cli).command}`, args: [] } : commandFor(cli);
3768
- if (box && cli === "opencode") {
3769
- setTimeout(() => finish({ ok: false, text: "", errors: [`${label} can't run in a cloud machine yet: give this agent Claude Code or Codex.`] }), 0);
3770
- return handle;
3771
- }
3772
4031
  if (!box && (!terminalsAvailable || !cmd)) {
3773
4032
  const why2 = !terminalsAvailable ? "the terminal module could not be loaded on this machine" : `${label} isn't installed (no "${cli}" on PATH)`;
3774
4033
  setTimeout(() => finish({ ok: false, text: "", errors: [`Could not start ${label}: ${why2}.`] }), 0);
@@ -3829,17 +4088,18 @@ ${JSON.stringify(opts.outputSchema)}`;
3829
4088
  sessionId,
3830
4089
  name: opts.label ?? "Droidsembly",
3831
4090
  role: opts.role,
4091
+ openCodePermissions: opts.openCodePermissions,
3832
4092
  additionalDirectories: opts.additionalDirectories,
3833
4093
  files,
3834
4094
  notify: box ? { script: `${BOX_BIN}/notify.cjs`, url: events } : { script: path9.join(BIN_DIR, "notify.cjs"), url: hookUrl },
3835
4095
  codexHook: box ? `${BOX_BIN}/codex-hook.cjs` : path9.join(BIN_DIR, "codex-hook.cjs"),
3836
- 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,
3837
4097
  ...opts.office && !box ? { officeUrl: `${officeUrl}/api/mcp/${token}` } : {},
3838
4098
  browser,
3839
4099
  ...box ? { node: "node", posix: true } : {}
3840
4100
  });
3841
4101
  const env = {};
3842
- 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 });
3843
4103
  else {
3844
4104
  for (const [k, v] of Object.entries(process.env)) {
3845
4105
  if (v === void 0) continue;
@@ -3903,7 +4163,8 @@ ${JSON.stringify(opts.outputSchema)}`;
3903
4163
  const beginInBox = async (b) => {
3904
4164
  try {
3905
4165
  boxFiles.push([`${dir}/launch.json`, JSON.stringify({ file: cmd.file, args: [...cmd.args, ...launch2.args], cwd: opts.cwd, events })]);
3906
- 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);
3907
4168
  if (done) return;
3908
4169
  const pty = boxPty(l, b, term.cols, term.rows, 0, env);
3909
4170
  l.proc = pty;
@@ -3942,13 +4203,13 @@ var MAX_DESK_INSTALLS = 2;
3942
4203
  var depsHash = (pkg, lock) => crypto4.createHash("sha256").update(pkg).update("\0").update(lock ?? "").digest("hex");
3943
4204
  async function readDeps(dir) {
3944
4205
  const read = (file) => fs9.readFile(path10.join(dir, file), "utf8").catch(() => null);
3945
- const [pkg, lock, marker, nodeModules] = await Promise.all([
4206
+ const [pkg, lock, marker2, nodeModules] = await Promise.all([
3946
4207
  read("package.json"),
3947
4208
  read("package-lock.json"),
3948
4209
  read(path10.join("node_modules", INSTALL_MARKER)),
3949
4210
  fs9.stat(path10.join(dir, "node_modules")).then((s2) => s2.isDirectory()).catch(() => false)
3950
4211
  ]);
3951
- return { pkg, lock, hash: depsHash(pkg ?? "", lock), marker: marker ?? "", nodeModules };
4212
+ return { pkg, lock, hash: depsHash(pkg ?? "", lock), marker: marker2 ?? "", nodeModules };
3952
4213
  }
3953
4214
  var depsCurrent = (s2) => s2.nodeModules && s2.marker === s2.hash;
3954
4215
  var writeMarker = (dir, hash) => fs9.writeFile(path10.join(dir, "node_modules", INSTALL_MARKER), hash).catch(() => void 0);
@@ -4133,6 +4394,65 @@ var openCodeModels = createModelCatalogReader(async (directory) => {
4133
4394
  }
4134
4395
  });
4135
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
+
4136
4456
  // server/previewRunner.ts
4137
4457
  import { spawn as spawn3 } from "node:child_process";
4138
4458
  import fs11 from "node:fs/promises";
@@ -4378,6 +4698,33 @@ import path13 from "node:path";
4378
4698
 
4379
4699
  // shared/italianUi.ts
4380
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.",
4381
4728
  "Look around": "Guardati intorno",
4382
4729
  "Pull out your phone": "Apri il telefono",
4383
4730
  "Visit the CEO": "Visita il CEO",
@@ -4759,7 +5106,7 @@ var italianUi = {
4759
5106
  "Where they work": "Dove lavora",
4760
5107
  "Works on": "Lavora su",
4761
5108
  " (connect Upstash in Settings first)": " (collega prima Upstash nelle Impostazioni)",
4762
- " (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.",
4763
5110
  "no Box yet": "nessun Box",
4764
5111
  "creating their Box\u2026": "creazione del Box\u2026",
4765
5112
  "setting up their Box\u2026": "configurazione del Box\u2026",
@@ -7692,6 +8039,8 @@ var realBackend = {
7692
8039
  releaseClis,
7693
8040
  detectClis,
7694
8041
  openCodeModels,
8042
+ openCodeConnections,
8043
+ openCodeAuth: startOpenCodeAuth,
7695
8044
  previews: realPreviews,
7696
8045
  office: realOffice,
7697
8046
  voice: elevenLabs,
@@ -9200,8 +9549,9 @@ function demoBoxes(logins) {
9200
9549
  },
9201
9550
  run: async (id, script) => {
9202
9551
  box(id).status = "running";
9203
- const cli = /claude'? auth /.test(script) ? "claude" : "codex";
9204
- if (script.includes("CUBEFARM_SIGNED_IN")) return { code: 0, output: logins.get(id)?.has(cli) ? "CUBEFARM_SIGNED_IN" : "CUBEFARM_SIGNED_OUT" };
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 } }) };
9205
9555
  if (/auth logout|' logout/.test(script)) {
9206
9556
  logins.get(id)?.delete(cli);
9207
9557
  return { code: 0, output: "" };
@@ -9251,13 +9601,13 @@ function demoCloud() {
9251
9601
  }
9252
9602
  };
9253
9603
  }
9254
- 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" };
9255
9605
  function demoSignIn(o, logins, exited) {
9256
9606
  const { term } = o;
9257
9607
  const claude = o.cli === "claude";
9258
- 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`);
9259
9609
  term.write(
9260
- (claude ? ["Opening browser to sign in\u2026", `If the browser didn't open, visit: ${DEMO_SIGN_IN.claude}`, "", "\x1B[2m(demo) Paste anything and press Enter.\x1B[0m", "Paste code here if prompted > "] : [
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 > "] : [
9261
9611
  "Welcome to Codex (demo)",
9262
9612
  "",
9263
9613
  "Follow these steps to sign in with ChatGPT using device code authorization:",
@@ -11321,6 +11671,9 @@ for (const dir of process.argv.slice(2)) c.projects[dir] = Object.assign({}, c.p
11321
11671
  fs.writeFileSync(file, JSON.stringify(c, null, 2));
11322
11672
  `;
11323
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" }),
11324
11677
  "launch.cjs": BOX_LAUNCH_SOURCE,
11325
11678
  "hook.cjs": BOX_HOOK_SOURCE,
11326
11679
  "statusline.cjs": BOX_STATUSLINE_SOURCE,
@@ -11330,8 +11683,17 @@ var BOX_HELPERS = {
11330
11683
  "seed-claude.cjs": BOX_SEED_CLAUDE_SOURCE
11331
11684
  };
11332
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
+
11333
11695
  // server/boxMachines.ts
11334
- var SETUP_REV = 2;
11696
+ var SETUP_REV = 4;
11335
11697
  var SETUP_TIMEOUT_MS = 20 * 6e4;
11336
11698
  var LIVE = ["running", "idle", "creating"];
11337
11699
  function failure(what, output, secrets) {
@@ -11347,7 +11709,6 @@ var BoxMachines = class {
11347
11709
  ids = /* @__PURE__ */ new Map();
11348
11710
  // machine -> Box id
11349
11711
  ready = /* @__PURE__ */ new Map();
11350
- // machine -> its Box, set up (once per office run)
11351
11712
  states = /* @__PURE__ */ new Map();
11352
11713
  api() {
11353
11714
  const api = this.deps.api();
@@ -11392,17 +11753,20 @@ var BoxMachines = class {
11392
11753
  }
11393
11754
  /** The machine's Box, created, running and set up: the first time takes a few minutes. */
11394
11755
  ensure(machine, note2) {
11395
- let p = this.ready.get(machine);
11396
- if (!p) {
11397
- p = this.bringUp(machine, note2).catch((err) => {
11398
- 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);
11399
11763
  this.setState(machine, "error");
11400
11764
  throw err;
11401
11765
  });
11402
- this.ready.set(machine, p);
11766
+ this.ready.set(machine, { profile, promise: p });
11403
11767
  return p;
11404
11768
  }
11405
- return p.then(async (id) => {
11769
+ return previous.promise.then(async (id) => {
11406
11770
  const info = await this.api().get(id);
11407
11771
  if (!info) {
11408
11772
  this.ready.delete(machine);
@@ -11417,7 +11781,7 @@ var BoxMachines = class {
11417
11781
  return id;
11418
11782
  });
11419
11783
  }
11420
- async bringUp(machine, note2) {
11784
+ async bringUp(machine, note2, cli, browser = false) {
11421
11785
  const api = this.api();
11422
11786
  let id = await this.boxId(machine);
11423
11787
  if (id) {
@@ -11440,7 +11804,7 @@ var BoxMachines = class {
11440
11804
  }
11441
11805
  this.setState(machine, "setting-up");
11442
11806
  const git2 = await this.deps.git();
11443
- const setup = await api.run(id, setupScript({ versions: this.deps.versions, rev: SETUP_REV, gitName: git2.name, gitEmail: git2.email }), { 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 });
11444
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());
11445
11809
  for (const [name, source] of Object.entries(BOX_HELPERS)) await api.write(id, `${BOX_BIN}/${name}`, source);
11446
11810
  await api.write(id, BOX_TMUX_CONF, TMUX_CONF);
@@ -11456,7 +11820,7 @@ var BoxMachines = class {
11456
11820
  const id = await this.ensure(machine, note2);
11457
11821
  const r = await api.run(id, prepareDeskScript(fullName, base, branch), { env: await this.deps.githubEnv(), timeoutMs: 15 * 6e4 });
11458
11822
  const lines = r.output.trim().split("\n");
11459
- if (r.code !== 0) throw failure(`Couldn't set up the desk in ${fullName}'s cloud machine`, r.output, this.deps.secrets());
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());
11460
11824
  for (const l of lines.slice(0, -1)) if (/stale git lock|rebuilt/.test(l)) note2?.(l.trim());
11461
11825
  await api.run(id, `node ${sq(`${BOX_BIN}/seed-claude.cjs`)} ${sq(boxDeskDir(fullName))}`);
11462
11826
  return boxDeskDir(fullName);
@@ -11567,13 +11931,56 @@ var BoxMachines = class {
11567
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
11568
11932
  * login counts. Wakes the Box. Throws when Upstash can't say.
11569
11933
  */
11570
- async signedIn(machine, cli) {
11934
+ async signedIn(machine, cli, directory, model2 = "") {
11571
11935
  const id = await this.ensure(machine);
11572
- 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 } : {} });
11573
11937
  const out = signInOutcome(r.output);
11574
- 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.`);
11575
11939
  return out;
11576
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
+ }
11577
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. */
11578
11985
  async signOut(machine, cli) {
11579
11986
  const id = await this.ensure(machine);
@@ -15038,6 +15445,7 @@ var Swarm = class {
15038
15445
  this.cloud = new Cloud({
15039
15446
  // The demo's fake cloud keeps a file of its own: its tests run beside the notifier's, which share demo-secrets.json.
15040
15447
  secretsFile: path21.join(HOME_DIR, backend.demo ? "demo-cloud-secrets.json" : "secrets.json"),
15448
+ credentials: backend.cloud.credentials,
15041
15449
  env: backend.cloud.env(),
15042
15450
  boxes: (key) => backend.cloud.boxes(key),
15043
15451
  ghToken: () => backend.cloud.ghToken(),
@@ -15051,6 +15459,14 @@ var Swarm = class {
15051
15459
  office: () => this.state.officeId,
15052
15460
  size: () => this.state.settings.cloud.boxSize,
15053
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
+ },
15054
15470
  git: () => backend.cloud.gitIdentity(this.user),
15055
15471
  githubEnv: () => this.cloud.githubEnv(),
15056
15472
  state: (machine) => this.boxState(machine),
@@ -15069,6 +15485,14 @@ var Swarm = class {
15069
15485
  });
15070
15486
  }
15071
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
+ }
15072
15496
  state = {
15073
15497
  settings: {
15074
15498
  sessionLimit: 0,
@@ -15687,6 +16111,7 @@ var Swarm = class {
15687
16111
  broadcast(ev) {
15688
16112
  this.outbox.broadcast(ev);
15689
16113
  this.observe(ev);
16114
+ for (const listener of this.eventListeners) listener(ev);
15690
16115
  }
15691
16116
  /** What follows from an event besides the tabs hearing it: ticker lines and mission control's numbers. */
15692
16117
  observe(ev) {
@@ -15860,10 +16285,97 @@ var Swarm = class {
15860
16285
  listGithubRepos(owner) {
15861
16286
  return this.backend.listMyRepos(owner);
15862
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
+ }
15863
16371
  openCodeModels(agentId, repoId2, refresh = false) {
15864
16372
  let directory = process.cwd();
15865
16373
  if (agentId) {
15866
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
+ }
15867
16379
  if (a.role === "ceo") {
15868
16380
  return fs21.mkdir(CEO_DIR, { recursive: true }).then(() => this.backend.openCodeModels(CEO_DIR, refresh));
15869
16381
  }
@@ -15891,7 +16403,7 @@ var Swarm = class {
15891
16403
  color: FLOOR_COLORS[(floor - 1) % FLOOR_COLORS.length],
15892
16404
  autoAssign: !!opts.autoAssign,
15893
16405
  autoMerge: opts.autoMerge !== false,
15894
- browserTesting: true,
16406
+ browserTesting: opts.browserTesting !== false,
15895
16407
  links: [],
15896
16408
  localPath: folder2,
15897
16409
  mission: (opts.mission ?? "").trim().slice(0, 4e3),
@@ -16245,6 +16757,7 @@ var Swarm = class {
16245
16757
  return this.shutdownTask;
16246
16758
  }
16247
16759
  async finishShutdown(restart) {
16760
+ if (this.openCodeAuthRun) this.cancelOpenCodeConfiguration(this.openCodeAuthRun.agentId);
16248
16761
  this.backend.cloud.detach();
16249
16762
  await this.writeState().catch((err) => console.warn("could not save the state", err));
16250
16763
  try {
@@ -16596,13 +17109,13 @@ var Swarm = class {
16596
17109
  // ---------- cloud agents (docs/cloud.md) ----------
16597
17110
  /**
16598
17111
  * Where a new (or moving) agent works: what was asked, else the office default. A cloud agent needs the Upstash key,
16599
- * room under the plan's Box limit and a CLI 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
16600
17113
  * cloud, so say why not; otherwise (a floor's first agent, the demo) they work on this computer instead.
16601
17114
  */
16602
- hostFor(asked, cli, strict, moving) {
17115
+ hostFor(asked, _cli, strict, moving) {
16603
17116
  const want = asked === "box" || asked === "local" ? asked : this.state.settings.cloud.machineKind;
16604
17117
  if (want === "local") return "local";
16605
- 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;
16606
17119
  if (!why2) return "box";
16607
17120
  if (strict || asked === "box") throw new HttpError(409, why2);
16608
17121
  return "local";
@@ -16642,6 +17155,7 @@ var Swarm = class {
16642
17155
  a.boxCli = null;
16643
17156
  this.dropSignIn(a.id);
16644
17157
  delete a.needsSignIn;
17158
+ delete a.openCodeAuthRejected;
16645
17159
  a.sessionId = null;
16646
17160
  a.sessionCli = null;
16647
17161
  for (const q of this.state.qa) if (q.devAgentId === a.id) q.devSessionId = null;
@@ -16660,7 +17174,7 @@ var Swarm = class {
16660
17174
  const boxId = await this.boxMachines.ensure(machine, (text3) => this.appendLog(a, [{ kind: "system", text: `\u2601 ${text3}` }]));
16661
17175
  const creds = await this.cloud.credentials(cli);
16662
17176
  if (creds.missing.length) throw new Error(`Cloud agents can't sign in yet. Missing: ${creds.missing.join("; ")}.`);
16663
- 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);
16664
17178
  const browser = browserTesting ? await api.browser(boxId).catch(() => false) : false;
16665
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) };
16666
17180
  }
@@ -16698,6 +17212,42 @@ var Swarm = class {
16698
17212
  });
16699
17213
  }
16700
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
+ }
16701
17251
  /**
16702
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
16703
17253
  * and take no work, the task they were starting (if any) waits, and the CLI's own sign-in starts in their terminal.
@@ -16705,6 +17255,7 @@ var Swarm = class {
16705
17255
  holdForSignIn(a, cli, task, expired2 = false) {
16706
17256
  if (!this.state.agents.includes(a) || a.host !== "box") return;
16707
17257
  const s2 = this.signInOf(a, cli);
17258
+ if (cli === "opencode" && expired2) a.openCodeAuthRejected = true;
16708
17259
  const label = cliLabel(cli);
16709
17260
  if (task) {
16710
17261
  a.status = "preparing";
@@ -16743,6 +17294,7 @@ var Swarm = class {
16743
17294
  }
16744
17295
  /** Their sign-in goes (they left, moved to this computer): its CLI closes and a held task is dropped with it. */
16745
17296
  dropSignIn(agentId) {
17297
+ if (this.openCodeAuthRun?.agentId === agentId && this.openCodeAuthRun.run) this.cancelOpenCodeConfiguration(agentId);
16746
17298
  const s2 = this.signIns.get(agentId);
16747
17299
  if (!s2) return;
16748
17300
  this.signIns.delete(agentId);
@@ -16751,9 +17303,11 @@ var Swarm = class {
16751
17303
  }
16752
17304
  /** Start the CLI's own sign-in in their terminal, unless it's running already. */
16753
17305
  async startSignIn(a) {
17306
+ if (this.backend.cloud.automaticSignIn === false) return;
17307
+ if (this.configuringOpenCode) return;
16754
17308
  const cli = a.cli || this.state.settings.defaultCli;
16755
17309
  const api = this.cloud.boxApi();
16756
- if (!a.needsSignIn || a.host !== "box" || cli === "opencode" || !api) return;
17310
+ if (!a.needsSignIn || a.host !== "box" || !api) return;
16757
17311
  const s2 = this.signInOf(a, cli);
16758
17312
  if (s2.run || s2.starting) return;
16759
17313
  s2.starting = true;
@@ -16776,7 +17330,8 @@ var Swarm = class {
16776
17330
  s2.poll = setTimeout(() => {
16777
17331
  s2.poll = null;
16778
17332
  if (this.signIns.get(a.id) !== s2 || !s2.run) return;
16779
- 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) => {
16780
17335
  if (this.signIns.get(a.id) !== s2) return;
16781
17336
  if (ok) this.signedIn(a);
16782
17337
  else if (s2.run) this.pollSignIn(a, s2);
@@ -16788,9 +17343,9 @@ var Swarm = class {
16788
17343
  if (this.signIns.get(a.id) !== s2) return;
16789
17344
  s2.run = null;
16790
17345
  if (s2.poll) clearTimeout(s2.poll);
16791
- const ok = await this.boxMachines.signedIn(this.machineOf(a), s2.cli).catch(() => null);
17346
+ const ok = await this.boxSignedIn(a, s2.cli).catch(() => null);
16792
17347
  if (this.signIns.get(a.id) !== s2 || s2.run) return;
16793
- if (ok) return this.signedIn(a);
17348
+ if (ok && !(s2.cli === "opencode" && a.openCodeAuthRejected && code !== 0)) return this.signedIn(a);
16794
17349
  this.agentRt.get(a.id)?.terminal?.note(`Not signed in yet. \u{1F511} Sign in starts it again.`);
16795
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.` }]);
16796
17351
  }
@@ -16803,6 +17358,7 @@ var Swarm = class {
16803
17358
  if (run2) setTimeout(() => run2.stop(), 3e3);
16804
17359
  if (!a.needsSignIn) return;
16805
17360
  a.needsSignIn = false;
17361
+ delete a.openCodeAuthRejected;
16806
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." : ""}` }]);
16807
17363
  this.emitAgent(a);
16808
17364
  this.save();
@@ -16822,15 +17378,19 @@ var Swarm = class {
16822
17378
  s2?.run?.stop();
16823
17379
  if (s2) s2.run = null;
16824
17380
  }
16825
- if (cli === "opencode") return this.signedIn(a);
17381
+ if (cli === "opencode" && a.openCodeAuthRejected) {
17382
+ this.holdForSignIn(a, cli, null, true);
17383
+ return;
17384
+ }
16826
17385
  const creds = await this.cloud.credentials(cli).catch(() => null);
16827
- 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;
16828
17387
  if (!this.state.agents.includes(a) || a.host !== "box") return;
16829
17388
  if (ok === true) this.signedIn(a);
16830
17389
  else if (ok === false) this.holdForSignIn(a, cli, null);
16831
17390
  }
16832
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. */
16833
17392
  signIn(id) {
17393
+ if (this.configuringOpenCode) throw new HttpError(409, "Finish OpenCode authentication in the terminal first.");
16834
17394
  const a = this.agent(id);
16835
17395
  if (a.host !== "box") throw new HttpError(409, `${a.name} works on this computer: their coding agent signs in there.`);
16836
17396
  if (!a.needsSignIn) throw new HttpError(409, `${a.name}'s coding agent is signed in already.`);
@@ -16874,12 +17434,12 @@ var Swarm = class {
16874
17434
  return !this.clis.length || this.clis.some((c) => c.id === cli && c.installed);
16875
17435
  }
16876
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.");
16877
17438
  const a = this.agent(id);
16878
17439
  if (patch.host !== void 0 && a.role !== "ceo" && (patch.host === "box" || patch.host === "local")) this.moveAgent(a, patch.host);
16879
17440
  if (patch.cli !== void 0) {
16880
17441
  const cli = isCli(patch.cli) ? patch.cli : "";
16881
17442
  if (a.role === "ceo" && cli && cli !== "claude" && cli !== "opencode") throw new HttpError(400, "The CEO can run Claude Code or OpenCode.");
16882
- 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.`);
16883
17443
  const localCli = cli || (a.role === "ceo" ? "claude" : this.state.settings.defaultCli);
16884
17444
  if (a.host !== "box" && (cli || localCli === "opencode") && !this.cliReady(localCli)) throw new HttpError(400, `${cliLabel(localCli)} isn't installed on this computer.`);
16885
17445
  const changed = cli !== a.cli;
@@ -16988,6 +17548,7 @@ var Swarm = class {
16988
17548
  );
16989
17549
  }
16990
17550
  ensureSlot() {
17551
+ if (this.configuringOpenCode) throw new HttpError(409, "Finish OpenCode authentication in the terminal first.");
16991
17552
  if (this.slotsFull()) {
16992
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.`);
16993
17554
  }
@@ -17414,8 +17975,8 @@ Note from the manager: ${note2}` : ""
17414
17975
  async signedOutMidTask(a, repo, result, cli, again) {
17415
17976
  const rt = this.agentRt.get(a.id);
17416
17977
  if (!rt || !this.state.agents.includes(a)) return;
17417
- const creds = cli === "opencode" ? null : await this.cloud.credentials(cli).catch(() => null);
17418
- 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") {
17419
17980
  const errors = creds && !creds.ownLogin ? [`${cliLabel(cli)} turned the key it was given away: check it in Settings \u2192 Cloud agents.`] : result.errors;
17420
17981
  return this.onFinished(a, repo, { ...result, errors });
17421
17982
  }
@@ -17618,6 +18179,7 @@ Note from the manager: ${note2}` : ""
17618
18179
  return qaSystemPrompt({ agent: a, repo, port: this.port(a), cwd, branch, pr, testStep: testStep2, depsLine: depsPromptLine(deps) });
17619
18180
  }
17620
18181
  async runQa(a, repo, rec) {
18182
+ if (this.backend.allowWork && !this.backend.allowWork("qa", a)) return;
17621
18183
  const branch = qaBranch(rec.prNumber, slugify(a.name));
17622
18184
  this.qaWaits.set(`${repo.id}#${rec.prNumber}`, Date.now() - rec.updatedAt);
17623
18185
  this.setQa(rec, { status: "testing", qaAgentId: a.id });
@@ -17838,6 +18400,7 @@ ${issue2.body.trim() || "(no description)"}` : ""
17838
18400
  }
17839
18401
  /** Send a failed PR back to the agent who wrote it (or any free agent on the floor). */
17840
18402
  async runFix(dev, repo, rec) {
18403
+ if (this.backend.allowWork && !this.backend.allowWork("fix", dev)) return;
17841
18404
  const original = rec.devAgentId === dev.id;
17842
18405
  const pull = this.repoRt.get(repo.id)?.pulls.find((p) => p.number === rec.prNumber);
17843
18406
  const headRef = pull?.headRefName ?? dev.branch ?? `pr-${rec.prNumber}`;
@@ -18143,20 +18706,24 @@ ${text3}` : text3);
18143
18706
  ).sort((x, y) => x.updatedAt - y.updatedAt);
18144
18707
  const fixes = waiting("failed", "fix");
18145
18708
  const owed = new Set(fixes.map((q) => q.devAgentId).filter((id) => !!id));
18709
+ const qaFree = free.filter((a) => this.mayStart("qa", a));
18146
18710
  for (const rec of waiting("queued", "qa")) {
18147
18711
  const othersCan = this.state.agents.some((a) => a.repoId === repo.id && a.role !== "ceo" && a.id !== rec.devAgentId && a.status !== "stopped");
18148
- const tester = pickTester(free, rec.devAgentId, owed, othersCan, now2 - rec.updatedAt);
18712
+ const tester = pickTester(qaFree, rec.devAgentId, owed, othersCan, now2 - rec.updatedAt);
18149
18713
  if (!tester) continue;
18150
18714
  void this.runQa(tester, repo, rec);
18151
18715
  return true;
18152
18716
  }
18717
+ const fixFree = free.filter((a) => this.mayStart("fix", a));
18153
18718
  for (const rec of fixes) {
18719
+ if (!fixFree.length) continue;
18154
18720
  const author = this.state.agents.find((a) => a.id === rec.devAgentId && a.repoId === repo.id && a.role !== "ceo") ?? null;
18155
18721
  if (author && this.limited(author)) continue;
18722
+ if (author && !this.mayStart("fix", author)) continue;
18156
18723
  const headRef = this.repoRt.get(repo.id).pulls.find((p) => p.number === rec.prNumber)?.headRefName ?? null;
18157
- const to = fixGoesTo(author, !!author && free.includes(author), rec.prNumber, headRef);
18724
+ const to = fixGoesTo(author, !!author && fixFree.includes(author), rec.prNumber, headRef);
18158
18725
  if (to === "wait") continue;
18159
- 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);
18160
18727
  return true;
18161
18728
  }
18162
18729
  return false;
@@ -18270,6 +18837,8 @@ ${text3}` : text3);
18270
18837
  }
18271
18838
  /** May work of this kind start now, as far as Claude's usage goes? */
18272
18839
  mayStart(kind, a) {
18840
+ if (this.backend.allowWork && !this.backend.allowWork(kind, a)) return false;
18841
+ if (this.configuringOpenCode) return false;
18273
18842
  const key = this.gateKey(a);
18274
18843
  const running = this.state.agents.filter((other) => BUSY3.includes(other.status) && this.gateKey(other) === key).length;
18275
18844
  return this.quotaGate().allows(key, kind, Date.now(), running, this.state.settings.pacingSessions);
@@ -18713,6 +19282,7 @@ ${job.text}` } : job;
18713
19282
  browserTesting: false,
18714
19283
  additionalDirectories: this.state.repos.filter((r) => this.repoRt.get(r.id)?.cloneStatus === "ready").map((r) => this.backend.mainDir(r.fullName)),
18715
19284
  role: "ceo",
19285
+ agentId: a.id,
18716
19286
  office: this.officeTools(),
18717
19287
  ...how
18718
19288
  },
@@ -19951,6 +20521,9 @@ app.post("/api/agents/:id/analyze", route((req) => swarm.analyze(String(req.para
19951
20521
  app.post("/api/agents/:id/reset", route((req) => swarm.resetAgent(String(req.params.id))));
19952
20522
  app.post("/api/agents/:id/message", route((req) => swarm.message(String(req.params.id), str(req.body.text))));
19953
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))));
19954
20527
  app.get("/api/agents/:id/prompt", route((req) => swarm.agentPrompt(String(req.params.id))));
19955
20528
  app.get("/api/agents/:id/screen", (req, res) => {
19956
20529
  const shot = swarm.screenshot(String(req.params.id));