droidsembly 0.4.0-beta.3 → 0.4.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.it.md +7 -6
  2. package/README.md +7 -6
  3. package/bin/cubefarm.js +2 -296
  4. package/bin/droidsembly.js +304 -0
  5. package/bin/environment.d.ts +3 -0
  6. package/bin/environment.js +48 -0
  7. package/dist/assets/AccessibilitySettings-vd4x_sEq.js +30 -0
  8. package/dist/assets/{AppViewer-0Bly3EdB.js → AppViewer-BB9lvg-4.js} +1 -1
  9. package/dist/assets/{Balloon-B6odnAlm.js → Balloon-CWEK5uK2.js} +1 -1
  10. package/dist/assets/{Batched-CTJWq46z.js → Batched-yAiB-c-b.js} +1 -1
  11. package/dist/assets/{Birds-DSS0OIz9.js → Birds-ClBZkA83.js} +1 -1
  12. package/dist/assets/{Blimp-CZt6dddK.js → Blimp-VHMnVBQt.js} +1 -1
  13. package/dist/assets/{BufferGeometryUtils-CmpUrBC5.js → BufferGeometryUtils-B4Tnxtjb.js} +1 -1
  14. package/dist/assets/{Duck-BnRLkodp.js → Duck-CCThHMtF.js} +1 -1
  15. package/dist/assets/{Effects-Bkewth1L.js → Effects-BZfFy3yq.js} +1 -1
  16. package/dist/assets/{Fireworks-Cvn8YKWd.js → Fireworks-CxvvEwV_.js} +1 -1
  17. package/dist/assets/{Helicopter-BDrFQMNX.js → Helicopter-DXHDrTnQ.js} +1 -1
  18. package/dist/assets/{Hurricane-C8hyFXjx.js → Hurricane-WXNUxoUz.js} +1 -1
  19. package/dist/assets/{Kaiju-Bxxe9DG0.js → Kaiju-D-wVgKo-.js} +1 -1
  20. package/dist/assets/{Meteors-UdYL0Tbv.js → Meteors-DSr-7bEl.js} +1 -1
  21. package/dist/assets/{MissionConsole-DJRtojZP.js → MissionConsole-4G02S89d.js} +1 -1
  22. package/dist/assets/{Office-9Mank16i.js → Office-B_EroD2U.js} +44 -44
  23. package/dist/assets/{PhotoPanel-C_njIXp0.js → PhotoPanel-ByzwApow.js} +1 -1
  24. package/dist/assets/{PhotoScene-DwpeJjGe.js → PhotoScene-CW3yZkqH.js} +3 -3
  25. package/dist/assets/{Plane-DzvUAUYE.js → Plane-CT7-QFbA.js} +1 -1
  26. package/dist/assets/Pocket-B0o4siMl.js +2 -0
  27. package/dist/assets/{Rainbow-CV1rD6rW.js → Rainbow-DNvXfTl9.js} +1 -1
  28. package/dist/assets/{Roof-DSpKcGXK.js → Roof-yLX0ZK0x.js} +1 -1
  29. package/dist/assets/{Shell-GaQY3zre.js → Shell-lZOZ3aG8.js} +2 -2
  30. package/dist/assets/{Skywriting-D4B2ZvH7.js → Skywriting-N1GDZKYR.js} +1 -1
  31. package/dist/assets/TerminalView-cUAMhOxM.js +17 -0
  32. package/dist/assets/{ToyWorld-DeQUxcuy.js → ToyWorld-BYE8776A.js} +1 -1
  33. package/dist/assets/{Ufo-CitoxReu.js → Ufo-D_Wt75n1.js} +1 -1
  34. package/dist/assets/{Whale-Btx5ph-T.js → Whale-Kkz3B36R.js} +1 -1
  35. package/dist/assets/all-BMItClgN.js +11 -0
  36. package/dist/assets/{bloomMarks-DRhDp19k.js → bloomMarks-C22qSi5d.js} +1 -1
  37. package/dist/assets/{cheerRules-DWb8Qwzg.js → cheerRules-G9WFRB4C.js} +1 -1
  38. package/dist/assets/{cityLayout-aA2Ktgpu.js → cityLayout-C8f5-bpM.js} +1 -1
  39. package/dist/assets/{dogState-DY7tJEVD.js → dogState-9uong8D8.js} +1 -1
  40. package/dist/assets/{doors-BlKvxXVp.js → doors-DsKuGpOi.js} +1 -1
  41. package/dist/assets/{gallery-COKuWb9E.js → gallery-DSKvNkBq.js} +1 -1
  42. package/dist/assets/gate-D6_NXB1w.js +2 -0
  43. package/dist/assets/index-rznd4Djx.js +10 -0
  44. package/dist/assets/{instantReplay-BjoV6jrY.js → instantReplay-CiWMru53.js} +1 -1
  45. package/dist/assets/{interact-0jqx03Xr.js → interact-Bt-XX-z4.js} +1 -1
  46. package/dist/assets/{jsx-runtime-CXW0f58S.js → jsx-runtime-CZP6s5wa.js} +1 -1
  47. package/dist/assets/{kit-n-eqZ1AT.js → kit-CZEafHnz.js} +1 -1
  48. package/dist/assets/mic-DeYDrNoY.js +1 -0
  49. package/dist/assets/{photoMode-BybFMLKC.js → photoMode-BTxq9-gL.js} +1 -1
  50. package/dist/assets/{pipeline-BGPWXegt.js → pipeline-DNe3sjnP.js} +1 -1
  51. package/dist/assets/{rapier-CrXmTSyE.js → rapier-C-KFR0AR.js} +1 -1
  52. package/dist/assets/{rig-DfdntE8m.js → rig-B88WinIa.js} +1 -1
  53. package/dist/assets/{speechLanguage-DfsQvU9M.js → speechLanguage-Bq3BAswq.js} +1 -1
  54. package/dist/assets/store-9CvxLGNQ.js +5 -0
  55. package/dist/assets/useDayTime-Nrdy7kH1.js +1 -0
  56. package/dist/assets/useGraphics-Bhnj8CAm.js +1 -0
  57. package/dist/assets/voiceMessages-BF3P4sjw.js +1 -0
  58. package/dist/assets/{weatherState-BJVm5hU-.js → weatherState-CufaxiyU.js} +1 -1
  59. package/dist/index.html +3 -3
  60. package/dist-server/index.js +1251 -494
  61. package/dist-server/index.js.map +4 -4
  62. package/dist-server/ptyHost.js +6 -2
  63. package/dist-server/ptyHost.js.map +2 -2
  64. package/package.json +2 -2
  65. package/dist/assets/AccessibilitySettings-HB1JfQbh.js +0 -30
  66. package/dist/assets/Pocket-A1iI6Ivy.js +0 -2
  67. package/dist/assets/TerminalView-DhmLqjYn.js +0 -17
  68. package/dist/assets/all-gw-szDg1.js +0 -11
  69. package/dist/assets/gate-D0uU0wv5.js +0 -2
  70. package/dist/assets/index-CDJgPTOC.js +0 -10
  71. package/dist/assets/mic-BnAa4E99.js +0 -1
  72. package/dist/assets/store-CXLtXw8e.js +0 -5
  73. package/dist/assets/useDayTime-BjBDzh_t.js +0 -1
  74. package/dist/assets/useGraphics-Bg6L4EdS.js +0 -1
  75. package/dist/assets/voiceMessages-CFLyZLZ4.js +0 -1
@@ -0,0 +1,304 @@
1
+ #!/usr/bin/env node
2
+ // Canonical entry for the public droidsembly command. cubefarm.js remains a compatibility wrapper.
3
+ import { spawn, spawnSync } from 'node:child_process';
4
+ import fs from 'node:fs';
5
+ import { createRequire } from 'node:module';
6
+ import net from 'node:net';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import { fileURLToPath, pathToFileURL } from 'node:url';
10
+ import { parseArgs } from 'node:util';
11
+ import { isNewer, updateInfo } from './distribution.js';
12
+ import { officeEnv, officeHome, officeOverrides } from './environment.js';
13
+
14
+ const MIN_NODE = 22;
15
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
16
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
17
+ const update = updateInfo(pkg.name, pkg.version);
18
+
19
+ const HELP = `
20
+ Droidsembly ${pkg.version}: a cartoon 3D office where a team of AI coding agents works through your GitHub issues.
21
+
22
+ Usage
23
+ ${update.command} start the office and open it in your browser
24
+ ${update.command} login sign in to Claude Code, the built-in coding agent
25
+ ${update.command} doctor check that this machine is ready
26
+
27
+ Options
28
+ --port <n> port for the office (default 4317)
29
+ --host <address>
30
+ address to listen on (default 127.0.0.1, this machine only). 0.0.0.0 opens the office to your
31
+ network with no sign-in: anyone who reaches it can run your agents. Only on a network you trust
32
+ --demo fake GitHub and fake agents: look around without spending any usage
33
+ --floors <n> --agents <n>
34
+ with --demo: a bigger company, n floors with n people each (up to 20 and 15)
35
+ --no-open don't open the browser
36
+ -v, --version
37
+ -h, --help
38
+
39
+ New offices use ~/.droidsembly; existing ~/.cubefarm offices keep their data in place.
40
+ Set DROIDSEMBLY_HOME (legacy: SWARM_HOME) to choose a folder explicitly.
41
+ If both default folders exist, an explicit choice is required; no data is moved or merged.
42
+ `;
43
+
44
+ const color = process.stdout.isTTY && !process.env.NO_COLOR;
45
+ const paint = (open, close) => (s) => (color ? `\x1b[${open}m${s}\x1b[${close}m` : s);
46
+ const green = paint(32, 39);
47
+ const red = paint(31, 39);
48
+ const dim = paint(2, 22);
49
+ const fail = (msg) => {
50
+ console.error(`\n ${red('✗')} ${msg}\n`);
51
+ process.exit(1);
52
+ };
53
+
54
+ if (Number(process.versions.node.split('.')[0]) < MIN_NODE) fail(`Droidsembly needs Node.js ${MIN_NODE} or newer (this is ${process.version}). Get it from https://nodejs.org`);
55
+
56
+ let args;
57
+ try {
58
+ args = parseArgs({
59
+ allowPositionals: true,
60
+ options: {
61
+ port: { type: 'string', short: 'p' },
62
+ host: { type: 'string' },
63
+ bind: { type: 'string' },
64
+ demo: { type: 'boolean' },
65
+ floors: { type: 'string' },
66
+ agents: { type: 'string' },
67
+ 'no-open': { type: 'boolean' },
68
+ version: { type: 'boolean', short: 'v' },
69
+ help: { type: 'boolean', short: 'h' },
70
+ },
71
+ });
72
+ } catch (err) {
73
+ fail(`${err.message}\n Run ${update.command} --help for the options.`);
74
+ }
75
+ const { values, positionals } = args;
76
+ const command = positionals[0] ?? 'start';
77
+
78
+ if (values.help) {
79
+ console.log(HELP);
80
+ process.exit(0);
81
+ }
82
+ if (values.version) {
83
+ console.log(pkg.version);
84
+ process.exit(0);
85
+ }
86
+
87
+ // ---------- Claude Code ----------
88
+
89
+ // The Agent SDK ships Claude Code as a per-platform package. The office runs its agents on it, so logging in with it
90
+ // is logging the agents in. Same lookup as the SDK's own.
91
+ function claudeBinary() {
92
+ let sdk;
93
+ try {
94
+ sdk = createRequire(import.meta.url).resolve('@anthropic-ai/claude-agent-sdk');
95
+ } catch {
96
+ return null;
97
+ }
98
+ const { platform, arch } = process;
99
+ const musl = platform === 'linux' && !process.report?.getReport?.()?.header?.glibcVersionRuntime;
100
+ const targets = platform === 'linux' ? (musl ? [`linux-${arch}-musl`, `linux-${arch}`] : [`linux-${arch}`, `linux-${arch}-musl`]) : [`${platform}-${arch}`];
101
+ const fromSdk = createRequire(sdk);
102
+ for (const target of targets) {
103
+ try {
104
+ return fromSdk.resolve(`@anthropic-ai/claude-agent-sdk-${target}/claude${platform === 'win32' ? '.exe' : ''}`);
105
+ } catch {
106
+ // not installed for this target
107
+ }
108
+ }
109
+ return null;
110
+ }
111
+
112
+ // Like the agents: no API keys or settings inherited from a Claude Code session this was started from.
113
+ function claudeEnv() {
114
+ const env = {};
115
+ for (const [k, v] of Object.entries(process.env)) if (!/^(ANTHROPIC_|CLAUDE)/i.test(k) || k === 'CLAUDE_CONFIG_DIR') env[k] = v;
116
+ return env;
117
+ }
118
+
119
+ // ---------- checks ----------
120
+
121
+ const sh = (cmd, cmdArgs, env) => spawnSync(cmd, cmdArgs, { encoding: 'utf8', windowsHide: true, timeout: 30_000, env });
122
+
123
+ /** What the office needs: { name, ok, detail, fix, required }. */
124
+ function checks() {
125
+ const out = [{ name: 'Node.js', ok: true, detail: process.version }];
126
+
127
+ const git = sh('git', ['--version']);
128
+ out.push({ name: 'git', ok: git.status === 0, detail: git.stdout?.trim().replace(/^git version /, ''), fix: 'install git: https://git-scm.com/downloads', required: true });
129
+
130
+ if (sh('gh', ['--version']).status !== 0) {
131
+ out.push({ name: 'GitHub CLI', ok: false, fix: 'install it from https://cli.github.com, then run: gh auth login' });
132
+ } else {
133
+ const ok = sh('gh', ['auth', 'status']).status === 0;
134
+ out.push({ name: 'GitHub CLI', ok, detail: ok ? 'signed in' : 'not signed in', fix: 'run: gh auth login' });
135
+ }
136
+
137
+ const claude = claudeBinary();
138
+ if (!claude) {
139
+ out.push({ name: 'Claude Code', ok: false, fix: `if using Claude, reinstall ${pkg.name}: Claude Code for ${process.platform}-${process.arch} is missing` });
140
+ } else {
141
+ let status = null;
142
+ try {
143
+ status = JSON.parse(sh(claude, ['auth', 'status', '--json'], claudeEnv()).stdout);
144
+ } catch {
145
+ // unreadable: treated as signed out
146
+ }
147
+ const ok = status?.loggedIn === true;
148
+ out.push({ name: 'Claude', ok, detail: ok ? `signed in${status.subscriptionType ? ` (${status.subscriptionType})` : ''}` : 'not signed in (only needed for Claude sessions)', fix: `if using Claude, run: ${update.command} login` });
149
+ }
150
+
151
+ // Agents test in a browser through Playwright, which drives Google Chrome by default.
152
+ const chrome = chromePaths().some((p) => fs.existsSync(p));
153
+ out.push({ name: 'Chrome', ok: chrome, detail: chrome ? 'for browser testing' : 'Google Chrome not found', fix: 'install Google Chrome so agents can test in a browser' });
154
+ // The pinned Playwright MCP server the agents' browser runs on (server/browser.ts), installed with cubefarm.
155
+ let mcp = null;
156
+ try {
157
+ mcp = JSON.parse(fs.readFileSync(createRequire(import.meta.url).resolve('@playwright/mcp/package.json'), 'utf8')).version;
158
+ } catch {
159
+ // not installed
160
+ }
161
+ out.push({ name: 'Browser tool', ok: !!mcp, detail: mcp ? `@playwright/mcp ${mcp}` : 'not installed', fix: `reinstall ${pkg.name}: ${update.command}` });
162
+ return out;
163
+ }
164
+
165
+ function chromePaths() {
166
+ const env = process.env;
167
+ if (process.platform === 'win32') {
168
+ return [env.PROGRAMFILES, env['PROGRAMFILES(X86)'], env.LOCALAPPDATA].filter(Boolean).map((d) => path.join(d, 'Google', 'Chrome', 'Application', 'chrome.exe'));
169
+ }
170
+ if (process.platform === 'darwin') return ['/Applications/Google Chrome.app', path.join(os.homedir(), 'Applications', 'Google Chrome.app')];
171
+ return ['/opt/google/chrome/chrome', '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable'];
172
+ }
173
+
174
+ const printCheck = (c) => console.log(` ${c.ok ? green('✓') : red('✗')} ${c.name.padEnd(12)} ${c.detail ? dim(c.detail) : ''}${c.ok ? '' : ` → ${c.fix}`}`);
175
+
176
+ // ---------- helpers ----------
177
+
178
+ // Where this machine reaches an office listening on `host`: loopback for the any-address, else that address (as
179
+ // server/config.ts's localAddress, which also brackets IPv6 for URLs).
180
+ const localHost = (host) => (['0.0.0.0', '::', ''].includes(host) ? '127.0.0.1' : host);
181
+
182
+ function portOpen(port, host) {
183
+ return new Promise((resolve) => {
184
+ const socket = net.connect({ port, host });
185
+ const done = (open) => {
186
+ socket.destroy();
187
+ resolve(open);
188
+ };
189
+ socket.once('connect', () => done(true));
190
+ socket.once('error', () => done(false));
191
+ socket.setTimeout(1000, () => done(false));
192
+ });
193
+ }
194
+
195
+ async function isOffice(url) {
196
+ try {
197
+ const res = await fetch(`${url}/api/state`, { signal: AbortSignal.timeout(3000) });
198
+ const data = await res.json();
199
+ return Array.isArray(data?.repos) && Array.isArray(data?.agents);
200
+ } catch {
201
+ return false;
202
+ }
203
+ }
204
+
205
+ function openBrowser(url) {
206
+ const [cmd, cmdArgs, opts] =
207
+ process.platform === 'win32'
208
+ ? ['cmd.exe', ['/d', '/s', '/c', `"start "" "${url}""`], { windowsVerbatimArguments: true }]
209
+ : process.platform === 'darwin'
210
+ ? ['open', [url], {}]
211
+ : ['xdg-open', [url], {}];
212
+ try {
213
+ spawn(cmd, cmdArgs, { ...opts, stdio: 'ignore', detached: true, windowsHide: true })
214
+ .on('error', () => undefined)
215
+ .unref();
216
+ } catch {
217
+ // no browser to open: the URL is printed anyway
218
+ }
219
+ }
220
+
221
+ async function checkForUpdate() {
222
+ // A checkout's `npm start` runs this under scripts/office.mjs, which updates the office from its origin instead.
223
+ if (process.env.CI || officeEnv(process.env, 'SWARM_LAUNCHER') === '1') return;
224
+ try {
225
+ const res = await fetch(update.url, { signal: AbortSignal.timeout(4000) });
226
+ if (!res.ok) return;
227
+ const { version } = await res.json();
228
+ if (typeof version === 'string' && isNewer(version, pkg.version)) {
229
+ console.log(`\n Droidsembly ${version} is out (this is ${pkg.version}). Start it with ${green(update.command)} to update.\n`);
230
+ }
231
+ } catch {
232
+ // offline, or the registry is slow: try again next time
233
+ }
234
+ }
235
+
236
+ // ---------- commands ----------
237
+
238
+ if (command === 'doctor') {
239
+ console.log(`\n Droidsembly ${pkg.version}\n`);
240
+ const results = checks();
241
+ results.forEach(printCheck);
242
+ const ok = results.every((c) => c.ok);
243
+ console.log(ok ? `\n All set. Start the office with: ${update.command}\n` : '\n Claude checks apply only to Claude sessions; OpenCode and Codex use their own setup.\n');
244
+ process.exit(ok ? 0 : 1);
245
+ }
246
+
247
+ if (command === 'login') {
248
+ const claude = claudeBinary();
249
+ if (!claude) fail(`Claude Code for ${process.platform}-${process.arch} is missing. Reinstall ${pkg.name}.`);
250
+ console.log('\n Signing in to Claude. Your agents use this login and your subscription.\n');
251
+ const res = spawnSync(claude, ['auth', 'login'], { stdio: 'inherit', env: claudeEnv() });
252
+ process.exit(res.status ?? 1);
253
+ }
254
+
255
+ if (command !== 'start') fail(`Unknown command "${command}". Run ${update.command} --help for the options.`);
256
+
257
+ const port = Number(values.port ?? officeEnv(process.env, 'SWARM_PORT') ?? 4317);
258
+ if (!Number.isInteger(port) || port < 0 || port > 65535) fail(`"${values.port ?? officeEnv(process.env, 'SWARM_PORT')}" isn't a port number.`);
259
+ const host = (values.host ?? values.bind ?? officeEnv(process.env, 'SWARM_HOST') ?? '').trim().replace(/^\[|\]$/g, '') || '127.0.0.1';
260
+ if (/[\s/]/.test(host)) fail(`"${host}" isn't an address to listen on. Try 0.0.0.0 (every network) or one of this machine's IPs.`);
261
+ const local = localHost(host);
262
+ const hostUrl = local.includes(':') ? `[${local}]` : local;
263
+ const url = `http://${local === '127.0.0.1' ? 'localhost' : hostUrl}:${port}`;
264
+ const demo = values.demo || ['1', 'true'].includes(officeEnv(process.env, 'SWARM_DEMO') ?? '');
265
+ let home;
266
+ try { home = officeHome(); }
267
+ catch (error) { fail(error.message); }
268
+
269
+ // A second office on the same state would resume every agent's session a second time.
270
+ if (port !== 0 && (await portOpen(port, local))) {
271
+ if (!(await isOffice(`http://${hostUrl}:${port}`))) fail(`Something else is using port ${port}. Start Droidsembly on another one: ${update.command} --port 4400`);
272
+ console.log(`\n Droidsembly is already running: ${url}\n`);
273
+ if (!values['no-open']) openBrowser(url);
274
+ process.exit(0);
275
+ }
276
+
277
+ if (!demo) {
278
+ const problems = checks().filter((c) => !c.ok);
279
+ if (problems.length) {
280
+ console.log('');
281
+ problems.forEach(printCheck);
282
+ if (problems.some((c) => c.required)) fail('Droidsembly can’t run without these.');
283
+ console.log(dim(`\n Starting anyway. Check your selected provider setup, then run: ${update.command} doctor`));
284
+ }
285
+ }
286
+
287
+ const entry = path.join(root, 'dist-server', 'index.js');
288
+ if (!fs.existsSync(entry)) fail(`${path.relative(process.cwd(), entry) || entry} is missing. In a checkout of the repo, run npm run build first.`);
289
+
290
+ Object.assign(process.env, officeOverrides(process.env, {
291
+ SWARM_HOME: home, SWARM_PORT: String(port), SWARM_HOST: host,
292
+ ...(demo ? { SWARM_DEMO: '1' } : {}),
293
+ ...(values.floors ? { SWARM_DEMO_FLOORS: values.floors } : {}),
294
+ ...(values.agents ? { SWARM_DEMO_AGENTS: values.agents } : {}),
295
+ }));
296
+ process.setSourceMapsEnabled(true);
297
+ // The server loads its state, then listens.
298
+ await import(pathToFileURL(entry).href);
299
+
300
+ if (!values['no-open'] && port !== 0) {
301
+ for (let i = 0; i < 100 && !(await portOpen(port, local)); i++) await new Promise((r) => setTimeout(r, 200));
302
+ openBrowser(url);
303
+ }
304
+ void checkForUpdate();
@@ -0,0 +1,3 @@
1
+ export function officeEnv(env: NodeJS.ProcessEnv, legacyName: string): string | undefined;
2
+ export function officeOverrides(env: NodeJS.ProcessEnv, values: Record<string, string>): NodeJS.ProcessEnv;
3
+ export function officeHome(env?: NodeJS.ProcessEnv, home?: string, exists?: (file: string) => boolean): string;
@@ -0,0 +1,48 @@
1
+ // Shared by the published CLI, checkout launcher and bundled server. No I/O at import time.
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ /** Canonical values win even when empty (an empty token must not revive a legacy token). */
7
+ export function officeEnv(env, legacyName) {
8
+ const canonical = legacyName.replace(/^(SWARM|CUBEFARM)_/, 'DROIDSEMBLY_');
9
+ return env[canonical] ?? env[legacyName];
10
+ }
11
+
12
+ /** Explicit process options must override both generations of inherited variables. */
13
+ export function officeOverrides(env, values) {
14
+ const result = { ...env };
15
+ for (const [name, value] of Object.entries(values)) {
16
+ result[name] = value;
17
+ result[name.replace(/^(SWARM|CUBEFARM)_/, 'DROIDSEMBLY_')] = value;
18
+ }
19
+ return result;
20
+ }
21
+
22
+ function directoryExists(file) {
23
+ try { fs.lstatSync(file); }
24
+ catch (error) {
25
+ if (error.code === 'ENOENT') return false;
26
+ throw error; // Permission/I/O errors are not evidence of a new office.
27
+ }
28
+ // Do not silently bypass a file or dangling symlink at either data path.
29
+ if (!fs.statSync(file).isDirectory()) throw new Error('Office home path is not a directory. Set DROIDSEMBLY_HOME explicitly.');
30
+ return true;
31
+ }
32
+
33
+ /** Selection only: never create, move, merge or read the contents of a data folder. */
34
+ export function officeHome(env = process.env, home = os.homedir(), exists = directoryExists) {
35
+ const explicit = officeEnv(env, 'SWARM_HOME');
36
+ if (explicit !== undefined) {
37
+ if (!explicit.trim()) throw new Error('DROIDSEMBLY_HOME / SWARM_HOME must not be empty. Select an office folder explicitly.');
38
+ const selected = path.resolve(explicit);
39
+ exists(selected); // An absent explicit path is allowed; invalid existing paths are not.
40
+ return selected;
41
+ }
42
+ const current = path.resolve(home, '.droidsembly');
43
+ const legacy = path.resolve(home, '.cubefarm');
44
+ const hasCurrent = exists(current);
45
+ const hasLegacy = exists(legacy);
46
+ if (hasCurrent && hasLegacy) throw new Error('Both .droidsembly and .cubefarm exist. Set DROIDSEMBLY_HOME (or SWARM_HOME) explicitly; no data was merged or moved.');
47
+ return hasLegacy ? legacy : current;
48
+ }