deus-machine 0.3.12 → 0.3.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -19,7 +19,7 @@ var init_package = __esm({
19
19
  "package.json"() {
20
20
  package_default = {
21
21
  name: "deus-machine",
22
- version: "0.3.12",
22
+ version: "0.3.13",
23
23
  description: "Run Deus IDE from the command line \u2014 headless server or desktop installer",
24
24
  license: "MIT",
25
25
  author: {
@@ -75,29 +75,18 @@ var init_package = __esm({
75
75
  import { parseArgs } from "node:util";
76
76
 
77
77
  // src/start.ts
78
- import { execSync as execSync2, spawn as spawn2 } from "node:child_process";
79
- import { existsSync as existsSync6 } from "node:fs";
78
+ import { spawn } from "node:child_process";
79
+ import { existsSync as existsSync3 } from "node:fs";
80
+ import { createRequire } from "node:module";
80
81
  import { join as join3, resolve, dirname } from "node:path";
81
- import { fileURLToPath as fileURLToPath4 } from "node:url";
82
+ import { fileURLToPath } from "node:url";
82
83
  import { homedir as homedir3 } from "node:os";
83
- import { mkdirSync as mkdirSync4 } from "node:fs";
84
+ import { mkdirSync as mkdirSync2 } from "node:fs";
84
85
 
85
86
  // ../../shared/runtime.ts
86
87
  import path from "node:path";
87
88
  var DEUS_APP_ID = "com.deus.app";
88
89
  var DEUS_DB_FILENAME = "deus.db";
89
- var DEUS_PREFERENCES_FILENAME = "preferences.json";
90
- var RUNTIME_MANIFEST_VERSION = 1;
91
- var CLI_RUNTIME_DEPENDENCIES = [
92
- "@anthropic-ai/claude-agent-sdk",
93
- "@hono/node-server",
94
- "@napi-rs/canvas",
95
- "@sentry/node",
96
- "agent-browser",
97
- "better-sqlite3",
98
- "node-pty",
99
- "ws"
100
- ];
101
90
  function getPathModule(platform4) {
102
91
  return platform4 === "win32" ? path.win32 : path.posix;
103
92
  }
@@ -134,934 +123,6 @@ function resolveRuntimeStagePaths(projectRoot) {
134
123
  };
135
124
  }
136
125
 
137
- // ../../scripts/runtime/validate.ts
138
- import { execFileSync as execFileSync3 } from "node:child_process";
139
- import { createHash as createHash3 } from "node:crypto";
140
- import { existsSync as existsSync3, readFileSync as readFileSync3, statSync as statSync3 } from "node:fs";
141
- import path4 from "node:path";
142
- import { fileURLToPath as fileURLToPath3 } from "node:url";
143
-
144
- // ../../scripts/runtime/agent-clis.ts
145
- import { execFileSync, spawn, spawnSync } from "node:child_process";
146
- import { createHash } from "node:crypto";
147
- import {
148
- chmodSync,
149
- constants,
150
- cpSync,
151
- existsSync,
152
- linkSync,
153
- mkdirSync,
154
- mkdtempSync,
155
- readFileSync,
156
- rmSync,
157
- statSync,
158
- symlinkSync,
159
- writeFileSync
160
- } from "node:fs";
161
- import path2 from "node:path";
162
- import { fileURLToPath } from "node:url";
163
- import { DEFAULT_PINS } from "@zvada/agent-server/core";
164
- import { runInstall } from "@zvada/agent-server/server";
165
- var runtimeDir = path2.dirname(fileURLToPath(import.meta.url));
166
- var defaultProjectRoot = path2.resolve(runtimeDir, "../..");
167
- var VERIFY_TIMEOUT_MS = 2e4;
168
- var VERSION_CHECK_ENV_DENYLIST = [
169
- "AUTH_TOKEN",
170
- "BUN_OPTIONS",
171
- "DATABASE_PATH",
172
- "DEUS_AUTH_TOKEN",
173
- "DEUS_BACKEND_PORT",
174
- "DEUS_BUNDLED_BIN_DIR",
175
- "DEUS_DATA_DIR",
176
- "DEUS_PACKAGED",
177
- "DEUS_RESOURCES_PATH",
178
- "DEUS_RUNTIME",
179
- "DEUS_RUNTIME_COMMAND",
180
- "DEUS_RUNTIME_EXECUTABLE",
181
- "ELECTRON_RUN_AS_NODE",
182
- "NODE_PATH",
183
- "PORT"
184
- ];
185
- var CODEX_HELPERS = [
186
- "codex-runtime/bin/codex-code-mode-host",
187
- "codex-runtime/codex-resources/zsh/bin/zsh"
188
- ];
189
- var CODEX_LINUX_HELPER = "codex-runtime/codex-resources/bwrap";
190
- function bundledTools(runtimeKey) {
191
- return [
192
- "codex",
193
- "claude",
194
- "rg",
195
- "agent-browser",
196
- ...CODEX_HELPERS,
197
- ...runtimeKey.startsWith("linux-") ? [CODEX_LINUX_HELPER] : []
198
- ];
199
- }
200
- var AGENT_CLI_TARGETS = [
201
- {
202
- runtimeKey: "darwin-arm64",
203
- fileFormat: "Mach-O 64-bit executable",
204
- fileArch: "arm64",
205
- agentBrowserEntry: "bin/agent-browser-darwin-arm64"
206
- },
207
- {
208
- runtimeKey: "darwin-x64",
209
- fileFormat: "Mach-O 64-bit executable",
210
- fileArch: "x86_64",
211
- agentBrowserEntry: "bin/agent-browser-darwin-x64"
212
- },
213
- {
214
- runtimeKey: "linux-x64",
215
- fileFormat: "ELF 64-bit",
216
- fileArch: "x86-64",
217
- agentBrowserEntry: "bin/agent-browser-linux-x64"
218
- }
219
- ];
220
- function relativeFromProjectRoot(projectRoot, targetPath) {
221
- return path2.relative(projectRoot, targetPath).split(path2.sep).join("/");
222
- }
223
- function resolveAgentCliManifestPath(projectRoot) {
224
- return path2.join(resolveRuntimeStagePaths(projectRoot).electron.root, "bin", "agent-clis.json");
225
- }
226
- function resolveStagedAgentCliPath(projectRoot, runtimeKey, tool) {
227
- return path2.join(resolveRuntimeStagePaths(projectRoot).electron.root, "bin", runtimeKey, tool);
228
- }
229
- function hashFile(filePath) {
230
- return createHash("sha256").update(readFileSync(filePath)).digest("hex");
231
- }
232
- function shouldVerifyRuntimeKey(runtimeKey) {
233
- if (process.platform === "darwin") return runtimeKey === `darwin-${process.arch}`;
234
- if (process.platform === "linux" && process.arch === "x64") return runtimeKey === "linux-x64";
235
- return false;
236
- }
237
- function spawnErrorCode(error2) {
238
- return error2?.code ?? error2?.message ?? "none";
239
- }
240
- function verifyVersion(executablePath, args, env = process.env) {
241
- const result = spawnSync(executablePath, args, {
242
- encoding: "utf8",
243
- timeout: VERIFY_TIMEOUT_MS,
244
- env,
245
- stdio: ["ignore", "pipe", "pipe"]
246
- });
247
- const output = (result.stdout || "").trim();
248
- if (result.status !== 0) {
249
- const stderr = (result.stderr || "").trim();
250
- const diagnostics = stagedExecutableDiagnostics(executablePath);
251
- const hint2 = macExecutionPolicyHint(diagnostics);
252
- throw new Error(
253
- `${path2.basename(executablePath)} ${args.join(" ")} failed: status=${result.status} signal=${result.signal} error=${spawnErrorCode(result.error)} stdout=${output} stderr=${stderr}${diagnostics ? `
254
- ${diagnostics}` : ""}${hint2}`
255
- );
256
- }
257
- return output;
258
- }
259
- function diagnosticOutput(command, args, cwd) {
260
- const result = spawnSync(command, args, {
261
- cwd,
262
- encoding: "utf8",
263
- timeout: VERIFY_TIMEOUT_MS,
264
- stdio: ["ignore", "pipe", "pipe"]
265
- });
266
- const output = `${result.stdout || ""}${result.stderr || ""}`.trim();
267
- if (result.error) {
268
- return [spawnErrorCode(result.error), output].filter(Boolean).join("\n");
269
- }
270
- if (result.status !== 0) return output || `${command} exited with status ${result.status}`;
271
- return output;
272
- }
273
- function stagedExecutableDiagnostics(executablePath) {
274
- if (process.platform !== "darwin") return "";
275
- const cwd = path2.dirname(executablePath);
276
- return [
277
- `file: ${diagnosticOutput("file", [executablePath], cwd)}`,
278
- `codesign: ${diagnosticOutput("codesign", ["-dv", "--verbose=4", executablePath], cwd)}`,
279
- `spctl: ${diagnosticOutput("spctl", ["--assess", "--type", "execute", "--verbose=4", executablePath], cwd)}`,
280
- `xattr: ${diagnosticOutput("xattr", ["-l", executablePath], cwd) || "none"}`
281
- ].join("\n");
282
- }
283
- function macExecutionPolicyHint(diagnostics) {
284
- if (process.platform !== "darwin") return "";
285
- if (!/spctl:[\s\S]*rejected/.test(diagnostics)) return "";
286
- if (!/com\.apple\.(provenance|quarantine)/.test(diagnostics)) return "";
287
- return [
288
- "",
289
- "macOS rejected this executable before --version produced output.",
290
- "Verify runnable staged agent CLIs on a notarized artifact or a macOS host that allows generated/copied Mach-O binaries to launch."
291
- ].join("\n");
292
- }
293
- function assertVersionOutput(tool, output, executablePath) {
294
- if (!output) {
295
- throw new Error(`${tool} --version produced no output for ${executablePath}`);
296
- }
297
- if (tool === "codex" && !/\b\d+\.\d+\.\d+\b/.test(output)) {
298
- throw new Error(`Unexpected codex --version output for ${executablePath}: ${output}`);
299
- }
300
- if (tool === "claude" && !/Claude Code|\b\d+\.\d+\.\d+\b/.test(output)) {
301
- throw new Error(`Unexpected claude --version output for ${executablePath}: ${output}`);
302
- }
303
- }
304
- function verifyStagedAgentCliVersion(tool, executablePath) {
305
- const binDir = path2.dirname(executablePath);
306
- const env = versionCheckEnv(binDir);
307
- const output = verifyVersion(
308
- executablePath,
309
- [tool === "claude" ? "--version" : "--version"],
310
- env
311
- );
312
- assertVersionOutput(tool, output, executablePath);
313
- return output;
314
- }
315
- function versionCheckEnv(binDir) {
316
- const env = { ...process.env };
317
- for (const key of VERSION_CHECK_ENV_DENYLIST) {
318
- delete env[key];
319
- }
320
- env.PATH = [binDir, process.env.PATH].filter(Boolean).join(path2.delimiter);
321
- return env;
322
- }
323
- function inspectStaticExecutable(projectRoot, filePath, label, fileFormat, fileArch) {
324
- assertExecutable(filePath, label);
325
- return {
326
- sha256: hashFile(filePath),
327
- size: statSync(filePath).size,
328
- fileOutput: getExecutableFileOutput(projectRoot, filePath, label, fileFormat, fileArch)
329
- };
330
- }
331
- function assertManifestEntry(projectRoot, manifestEntries, runtimeKey, tool, executablePath, inspection) {
332
- const entry = manifestEntries.find((candidate) => candidate.tool === tool);
333
- if (!entry) {
334
- throw new Error(`Agent CLI manifest is missing ${runtimeKey}/${tool}`);
335
- }
336
- const expectedPath = relativeFromProjectRoot(projectRoot, executablePath);
337
- if (entry.path !== expectedPath) {
338
- throw new Error(
339
- `Agent CLI manifest path mismatch for ${runtimeKey}/${tool}: expected ${expectedPath}, found ${entry.path}`
340
- );
341
- }
342
- if (entry.sha256 !== inspection.sha256) {
343
- throw new Error(`Agent CLI manifest hash mismatch for ${runtimeKey}/${tool}`);
344
- }
345
- if (entry.size !== inspection.size) {
346
- throw new Error(`Agent CLI manifest size mismatch for ${runtimeKey}/${tool}`);
347
- }
348
- if (entry.fileOutput !== inspection.fileOutput) {
349
- throw new Error(`Agent CLI manifest file output mismatch for ${runtimeKey}/${tool}`);
350
- }
351
- }
352
- function assertExecutable(filePath, label) {
353
- if (!existsSync(filePath)) {
354
- throw new Error(`Missing ${label}: ${filePath}`);
355
- }
356
- const stat = statSync(filePath);
357
- if (!stat.isFile()) {
358
- throw new Error(`Expected ${label} to be a regular file: ${filePath}`);
359
- }
360
- if ((stat.mode & 73) === 0) {
361
- throw new Error(`Expected ${label} to be executable: ${filePath}`);
362
- }
363
- }
364
- function getExecutableFileOutput(projectRoot, filePath, label, fileFormat, fileArch) {
365
- const fileOutput = execFileSync("file", ["-L", relativeFromProjectRoot(projectRoot, filePath)], {
366
- cwd: projectRoot,
367
- encoding: "utf8",
368
- timeout: VERIFY_TIMEOUT_MS,
369
- stdio: ["ignore", "pipe", "pipe"]
370
- }).trim();
371
- const hasExpectedFormat = fileFormat === "Mach-O 64-bit executable" ? fileOutput.includes("Mach-O 64-bit") && fileOutput.includes("executable") : fileOutput.includes(fileFormat);
372
- if (!hasExpectedFormat || !fileOutput.includes(fileArch)) {
373
- throw new Error(`Unexpected ${label} architecture: ${fileOutput}`);
374
- }
375
- return fileOutput;
376
- }
377
- function validateStagedAgentClis(options = {}) {
378
- const log = options.log ?? console.log;
379
- const projectRoot = options.projectRoot ?? defaultProjectRoot;
380
- const manifestPath = resolveAgentCliManifestPath(projectRoot);
381
- if (!existsSync(manifestPath)) {
382
- throw new Error(`Missing staged agent CLI manifest: ${manifestPath}`);
383
- }
384
- const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
385
- const runtimeKeys = options.runtimeKey ? [options.runtimeKey] : AGENT_CLI_TARGETS.map((target) => target.runtimeKey);
386
- for (const runtimeKey of runtimeKeys) {
387
- const target = AGENT_CLI_TARGETS.find((item) => item.runtimeKey === runtimeKey);
388
- if (!target) throw new Error(`Unsupported agent CLI runtime key: ${runtimeKey}`);
389
- const manifestEntries = manifest.targets.filter((entry) => entry.runtimeKey === runtimeKey);
390
- const codexEntry = manifestEntries.find((entry) => entry.tool === "codex");
391
- if (!codexEntry) {
392
- throw new Error(`Agent CLI manifest is missing ${runtimeKey}/codex`);
393
- }
394
- if (codexEntry.source.version !== DEFAULT_PINS.codex) {
395
- throw new Error(
396
- `${runtimeKey}/codex is ${codexEntry.source.version}, but agent-server runs ${DEFAULT_PINS.codex}: stage the CLIs again`
397
- );
398
- }
399
- const tools = bundledTools(runtimeKey);
400
- for (const tool of tools) {
401
- const executablePath = resolveStagedAgentCliPath(projectRoot, runtimeKey, tool);
402
- const inspection = inspectStaticExecutable(
403
- projectRoot,
404
- executablePath,
405
- `${runtimeKey}/${tool}`,
406
- target.fileFormat,
407
- target.fileArch
408
- );
409
- assertManifestEntry(
410
- projectRoot,
411
- manifestEntries,
412
- runtimeKey,
413
- tool,
414
- executablePath,
415
- inspection
416
- );
417
- }
418
- if (manifestEntries.length !== tools.length) {
419
- throw new Error(
420
- `Agent CLI manifest expected ${tools.length} entries for ${runtimeKey}, found ${manifestEntries.length}`
421
- );
422
- }
423
- if (!existsSync(
424
- path2.join(
425
- path2.dirname(resolveStagedAgentCliPath(projectRoot, runtimeKey, "codex")),
426
- "codex-runtime",
427
- "codex-package.json"
428
- )
429
- )) {
430
- throw new Error(`Missing Codex package metadata for ${runtimeKey}`);
431
- }
432
- if (options.verifyRunnable === true && shouldVerifyRuntimeKey(runtimeKey)) {
433
- for (const tool of ["codex", "claude"]) {
434
- const executablePath = resolveStagedAgentCliPath(projectRoot, runtimeKey, tool);
435
- const version = verifyStagedAgentCliVersion(tool, executablePath);
436
- log(`\u2713 ${runtimeKey}/${tool} ${version}`);
437
- }
438
- }
439
- }
440
- log(`\u2713 Staged agent CLIs ready (${runtimeKeys.join(", ")})`);
441
- return manifest;
442
- }
443
-
444
- // ../../scripts/runtime/native-runtime.ts
445
- import { execFileSync as execFileSync2, spawnSync as spawnSync2 } from "node:child_process";
446
- import { createHash as createHash2 } from "node:crypto";
447
- import {
448
- chmodSync as chmodSync2,
449
- existsSync as existsSync2,
450
- mkdirSync as mkdirSync2,
451
- readdirSync,
452
- readFileSync as readFileSync2,
453
- rmSync as rmSync2,
454
- statSync as statSync2,
455
- writeFileSync as writeFileSync2
456
- } from "node:fs";
457
- import path3 from "node:path";
458
- import { fileURLToPath as fileURLToPath2 } from "node:url";
459
- var runtimeDir2 = path3.dirname(fileURLToPath2(import.meta.url));
460
- var defaultProjectRoot2 = path3.resolve(runtimeDir2, "../..");
461
- var VERIFY_TIMEOUT_MS2 = 2e4;
462
- var VERIFY_STOP_TIMEOUT_MS = 5e3;
463
- var MAC_CODESIGN_PAGE_SIZE = "4096";
464
- var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([".cjs", ".js", ".json", ".mjs", ".ts", ".tsx"]);
465
- var IGNORED_SOURCE_DIRS = /* @__PURE__ */ new Set([
466
- ".git",
467
- ".turbo",
468
- "coverage",
469
- "dist",
470
- "node_modules",
471
- "out",
472
- "test",
473
- "tests",
474
- "__tests__"
475
- ]);
476
- var REQUIRED_RUNTIME_ENTITLEMENTS = [
477
- "com.apple.security.cs.allow-jit",
478
- "com.apple.security.cs.allow-unsigned-executable-memory",
479
- "com.apple.security.cs.disable-library-validation"
480
- ];
481
- var VERSION_CHECK_ENV_DENYLIST2 = [
482
- "AUTH_TOKEN",
483
- "BUN_OPTIONS",
484
- "DATABASE_PATH",
485
- "DEUS_AUTH_TOKEN",
486
- "DEUS_BACKEND_PORT",
487
- "DEUS_BUNDLED_BIN_DIR",
488
- "DEUS_DATA_DIR",
489
- "DEUS_PACKAGED",
490
- "DEUS_RESOURCES_PATH",
491
- "DEUS_RUNTIME",
492
- "DEUS_RUNTIME_COMMAND",
493
- "DEUS_RUNTIME_EXECUTABLE",
494
- "ELECTRON_RUN_AS_NODE",
495
- "NODE_PATH",
496
- "PORT"
497
- ];
498
- var DEUS_RUNTIME_TARGETS = [
499
- {
500
- runtimeKey: "darwin-arm64",
501
- platform: "darwin",
502
- bunTarget: "bun-darwin-arm64",
503
- fileArch: "arm64"
504
- },
505
- {
506
- runtimeKey: "darwin-x64",
507
- platform: "darwin",
508
- bunTarget: "bun-darwin-x64",
509
- fileArch: "x86_64"
510
- },
511
- {
512
- runtimeKey: "linux-x64",
513
- platform: "linux",
514
- bunTarget: "bun-linux-x64",
515
- fileArch: "x86-64"
516
- }
517
- ];
518
- function relativeFromProjectRoot2(projectRoot, targetPath) {
519
- return path3.relative(projectRoot, targetPath).split(path3.sep).join("/");
520
- }
521
- function resolveDeusRuntimeManifestPath(projectRoot) {
522
- return path3.join(resolveRuntimeStagePaths(projectRoot).electron.root, "bin", "deus-runtime.json");
523
- }
524
- function resolveStagedDeusRuntimePath(projectRoot, runtimeKey) {
525
- return path3.join(
526
- resolveRuntimeStagePaths(projectRoot).electron.root,
527
- "bin",
528
- runtimeKey,
529
- "deus-runtime"
530
- );
531
- }
532
- function hashFile2(filePath) {
533
- return createHash2("sha256").update(readFileSync2(filePath)).digest("hex");
534
- }
535
- function getHostRuntimeKey() {
536
- if (process.platform === "darwin" && (process.arch === "arm64" || process.arch === "x64")) {
537
- return `darwin-${process.arch}`;
538
- }
539
- if (process.platform === "linux" && process.arch === "x64") {
540
- return "linux-x64";
541
- }
542
- return null;
543
- }
544
- function shouldVerifyRuntimeKey2(runtimeKey) {
545
- return getHostRuntimeKey() === runtimeKey;
546
- }
547
- function canInspectMacBinary(target) {
548
- return target.platform === "darwin" && process.platform === "darwin";
549
- }
550
- function execOutput(command, args, cwd) {
551
- return execFileSync2(command, args, {
552
- cwd,
553
- encoding: "utf8",
554
- timeout: VERIFY_TIMEOUT_MS2,
555
- stdio: ["ignore", "pipe", "pipe"]
556
- }).trim();
557
- }
558
- function spawnErrorCode2(error2) {
559
- return error2?.code ?? error2?.message ?? "none";
560
- }
561
- function diagnosticOutput2(command, args, cwd) {
562
- const result = spawnSync2(command, args, {
563
- cwd,
564
- encoding: "utf8",
565
- timeout: VERIFY_TIMEOUT_MS2,
566
- stdio: ["ignore", "pipe", "pipe"]
567
- });
568
- const output = `${result.stdout || ""}${result.stderr || ""}`.trim();
569
- if (result.error) {
570
- return [spawnErrorCode2(result.error), output].filter(Boolean).join("\n");
571
- }
572
- if (result.status !== 0) return output || `${command} exited with status ${result.status}`;
573
- return output;
574
- }
575
- function runtimeExecutableDiagnostics(executablePath) {
576
- if (process.platform !== "darwin") return "";
577
- const cwd = path3.dirname(executablePath);
578
- return [
579
- `file: ${diagnosticOutput2("file", [executablePath], cwd)}`,
580
- `codesign: ${diagnosticOutput2("codesign", ["-dv", "--verbose=4", executablePath], cwd)}`,
581
- `spctl: ${diagnosticOutput2("spctl", ["--assess", "--type", "execute", "--verbose=4", executablePath], cwd)}`,
582
- `xattr: ${diagnosticOutput2("xattr", ["-l", executablePath], cwd) || "none"}`
583
- ].join("\n");
584
- }
585
- function macExecutionPolicyHint2(diagnostics) {
586
- if (process.platform !== "darwin") return "";
587
- if (!/spctl:[\s\S]*rejected/.test(diagnostics)) return "";
588
- if (!/com\.apple\.(provenance|quarantine)/.test(diagnostics)) return "";
589
- return [
590
- "",
591
- "macOS rejected this executable before --version produced output.",
592
- "Verify runnable staged runtime binaries on a notarized artifact or a macOS host that allows generated Mach-O binaries to launch."
593
- ].join("\n");
594
- }
595
- function readPackageVersion(projectRoot) {
596
- const packageJsonPath = path3.join(projectRoot, "package.json");
597
- const packageJson = JSON.parse(readFileSync2(packageJsonPath, "utf8"));
598
- if (typeof packageJson.version !== "string" || packageJson.version.length === 0) {
599
- throw new Error(`package.json is missing a string version: ${packageJsonPath}`);
600
- }
601
- return packageJson.version;
602
- }
603
- function latestSourceMtime(projectRoot, sourceRelatives) {
604
- let latest = { mtimeMs: 0, path: null };
605
- function visit(sourcePath) {
606
- if (!existsSync2(sourcePath)) return;
607
- const stat = statSync2(sourcePath);
608
- if (stat.isDirectory()) {
609
- for (const entry of readdirSync(sourcePath, { withFileTypes: true })) {
610
- if (IGNORED_SOURCE_DIRS.has(entry.name)) continue;
611
- visit(path3.join(sourcePath, entry.name));
612
- }
613
- return;
614
- }
615
- if (!SOURCE_EXTENSIONS.has(path3.extname(sourcePath))) return;
616
- if (stat.mtimeMs > latest.mtimeMs) {
617
- latest = { mtimeMs: stat.mtimeMs, path: sourcePath };
618
- }
619
- }
620
- for (const sourceRelative of sourceRelatives) {
621
- visit(path3.join(projectRoot, sourceRelative));
622
- }
623
- return latest;
624
- }
625
- function assertRuntimeFresh(projectRoot, executablePath, runtimeKey) {
626
- const latestSource = latestSourceMtime(projectRoot, [
627
- "apps/runtime",
628
- "apps/backend/src",
629
- "apps/agent-server",
630
- "shared",
631
- "resources/entitlements.runtime.plist"
632
- ]);
633
- if (!latestSource.path) return;
634
- if (statSync2(executablePath).mtimeMs >= latestSource.mtimeMs) return;
635
- throw new Error(
636
- `${runtimeKey}/deus-runtime is stale: ${relativeFromProjectRoot2(
637
- projectRoot,
638
- executablePath
639
- )} is older than ${relativeFromProjectRoot2(projectRoot, latestSource.path)}. Run \`bun run build:runtime\` before packaging.`
640
- );
641
- }
642
- function assertExecutable2(filePath, label) {
643
- if (!existsSync2(filePath)) {
644
- throw new Error(`Missing ${label}: ${filePath}`);
645
- }
646
- const stat = statSync2(filePath);
647
- if (!stat.isFile()) {
648
- throw new Error(`Expected ${label} to be a regular file: ${filePath}`);
649
- }
650
- if ((stat.mode & 73) === 0) {
651
- throw new Error(`Expected ${label} to be executable: ${filePath}`);
652
- }
653
- }
654
- function assertFileArch(fileOutput, target, filePath) {
655
- const hasExpectedFormat = target.platform === "darwin" ? fileOutput.includes("Mach-O 64-bit") && fileOutput.includes("executable") : fileOutput.includes("ELF 64-bit");
656
- if (!hasExpectedFormat || !fileOutput.includes(target.fileArch)) {
657
- throw new Error(`Unexpected file(1) output for ${filePath}: ${fileOutput}`);
658
- }
659
- }
660
- function verifyMacCodeSignature(filePath) {
661
- if (process.platform !== "darwin") return;
662
- const result = spawnSync2("codesign", ["--verify", "--verbose=2", filePath], {
663
- encoding: "utf8",
664
- stdio: ["ignore", "pipe", "pipe"]
665
- });
666
- if (result.status !== 0) {
667
- throw new Error(`Invalid code signature for ${filePath}: ${result.stderr || result.stdout}`);
668
- }
669
- }
670
- function verifyMacCodeSignaturePageSize(filePath) {
671
- if (process.platform !== "darwin") return;
672
- const result = spawnSync2("codesign", ["-dv", "--verbose=4", filePath], {
673
- encoding: "utf8",
674
- stdio: ["ignore", "pipe", "pipe"]
675
- });
676
- if (result.status !== 0) {
677
- throw new Error(
678
- `Unable to inspect code signature for ${filePath}: ${result.stderr || result.stdout}`
679
- );
680
- }
681
- const output = `${result.stdout}
682
- ${result.stderr}`;
683
- if (!output.includes(`Page size=${MAC_CODESIGN_PAGE_SIZE}`)) {
684
- throw new Error(
685
- `Unexpected code signature page size for ${filePath}; expected ${MAC_CODESIGN_PAGE_SIZE}`
686
- );
687
- }
688
- }
689
- function readMacEntitlements(filePath) {
690
- const result = spawnSync2("codesign", ["-d", "--entitlements", ":-", filePath], {
691
- encoding: "utf8",
692
- stdio: ["ignore", "pipe", "pipe"]
693
- });
694
- if (result.status !== 0) {
695
- throw new Error(
696
- `Unable to read entitlements for ${filePath}: ${result.stderr || result.stdout}`
697
- );
698
- }
699
- return `${result.stdout}
700
- ${result.stderr}`;
701
- }
702
- function verifyMacSystemDylibs(otoolOutput, filePath) {
703
- if (process.platform !== "darwin") return;
704
- const unexpected = otoolOutput.split(/\r?\n/).slice(1).map((line) => line.trim().split(/\s+/)[0]).filter(Boolean).filter(
705
- (dependency) => !dependency.startsWith("/usr/lib/") && !dependency.startsWith("/System/Library/")
706
- );
707
- if (unexpected.length > 0) {
708
- throw new Error(
709
- `Unexpected non-system dylib dependency for ${filePath}: ${unexpected.join(", ")}`
710
- );
711
- }
712
- }
713
- function verifyMacRuntimeEntitlements(filePath) {
714
- if (process.platform !== "darwin") return;
715
- const entitlements = readMacEntitlements(filePath);
716
- for (const entitlement of REQUIRED_RUNTIME_ENTITLEMENTS) {
717
- if (!entitlements.includes(entitlement)) {
718
- throw new Error(`Missing ${entitlement} entitlement for ${filePath}`);
719
- }
720
- }
721
- }
722
- function verifyStagedDeusRuntimeVersion(executablePath) {
723
- const helperPath = path3.join(runtimeDir2, "smoke", "run-version-check.cjs");
724
- const env = { ...process.env };
725
- for (const key of VERSION_CHECK_ENV_DENYLIST2) {
726
- delete env[key];
727
- }
728
- env.DEUS_VERSION_CHECK_TIMEOUT_MS = String(VERIFY_TIMEOUT_MS2);
729
- env.DEUS_VERSION_CHECK_STOP_TIMEOUT_MS = String(VERIFY_STOP_TIMEOUT_MS);
730
- const result = spawnSync2(process.execPath, [helperPath, executablePath, "--version"], {
731
- encoding: "utf8",
732
- timeout: VERIFY_TIMEOUT_MS2 + VERIFY_STOP_TIMEOUT_MS + 5e3,
733
- env,
734
- stdio: ["ignore", "pipe", "pipe"]
735
- });
736
- const rawOutput = (result.stdout || "").trim();
737
- let checkResult;
738
- try {
739
- checkResult = JSON.parse(rawOutput);
740
- } catch {
741
- checkResult = {
742
- ok: false,
743
- status: result.status,
744
- signal: result.signal,
745
- error: spawnErrorCode2(result.error),
746
- stdout: rawOutput,
747
- stderr: (result.stderr || "").trim()
748
- };
749
- }
750
- const output = (checkResult.stdout || "").trim();
751
- if (result.status !== 0) {
752
- const stderr = [checkResult.stderr, result.stderr].filter(Boolean).join("\n").trim();
753
- const diagnostics = runtimeExecutableDiagnostics(executablePath);
754
- const hint2 = macExecutionPolicyHint2(diagnostics);
755
- throw new Error(
756
- `deus-runtime --version failed for ${executablePath}: status=${result.status} signal=${result.signal} error=${checkResult.error ?? spawnErrorCode2(result.error)} timedOut=${checkResult.timedOut === true} stdout=${output} stderr=${stderr}${diagnostics ? `
757
- ${diagnostics}` : ""}${hint2}`
758
- );
759
- }
760
- if (!/^deus-runtime \d+\.\d+\.\d+ /.test(output)) {
761
- throw new Error(`Unexpected deus-runtime --version output for ${executablePath}: ${output}`);
762
- }
763
- return output;
764
- }
765
- function validateDeusRuntime(options = {}) {
766
- const log = options.log ?? console.log;
767
- const projectRoot = options.projectRoot ?? defaultProjectRoot2;
768
- const manifestPath = resolveDeusRuntimeManifestPath(projectRoot);
769
- if (!existsSync2(manifestPath)) {
770
- throw new Error(`Missing native runtime manifest: ${manifestPath}`);
771
- }
772
- const manifest = JSON.parse(readFileSync2(manifestPath, "utf8"));
773
- const packageVersion = readPackageVersion(projectRoot);
774
- if (manifest.packageVersion !== packageVersion) {
775
- throw new Error(
776
- `Native runtime manifest package version mismatch: expected ${packageVersion}, found ${manifest.packageVersion ?? "missing"}. Run \`bun run build:runtime\` before packaging.`
777
- );
778
- }
779
- const runtimeKeys = options.runtimeKey ? [options.runtimeKey] : DEUS_RUNTIME_TARGETS.map((target) => target.runtimeKey);
780
- for (const runtimeKey of runtimeKeys) {
781
- const target = DEUS_RUNTIME_TARGETS.find((item) => item.runtimeKey === runtimeKey);
782
- if (!target) throw new Error(`Unsupported native runtime key: ${runtimeKey}`);
783
- const executablePath = resolveStagedDeusRuntimePath(projectRoot, runtimeKey);
784
- assertExecutable2(executablePath, `${runtimeKey}/deus-runtime`);
785
- assertRuntimeFresh(projectRoot, executablePath, runtimeKey);
786
- const manifestEntry = manifest.entries.find((entry) => entry.runtimeKey === runtimeKey);
787
- if (!manifestEntry) throw new Error(`Native runtime manifest is missing ${runtimeKey}`);
788
- const expectedPath = relativeFromProjectRoot2(projectRoot, executablePath);
789
- if (manifestEntry.path !== expectedPath) {
790
- throw new Error(
791
- `Native runtime manifest path mismatch for ${runtimeKey}: expected ${expectedPath}, found ${manifestEntry.path}`
792
- );
793
- }
794
- if (manifestEntry.sha256 !== hashFile2(executablePath)) {
795
- throw new Error(`Native runtime manifest hash mismatch for ${runtimeKey}`);
796
- }
797
- const manifestCommandPath = relativeFromProjectRoot2(projectRoot, executablePath);
798
- const fileOutput = execOutput("file", [manifestCommandPath], projectRoot);
799
- assertFileArch(fileOutput, target, executablePath);
800
- const otoolOutput = canInspectMacBinary(target) ? execOutput("otool", ["-L", manifestCommandPath], projectRoot) : void 0;
801
- if (otoolOutput) verifyMacSystemDylibs(otoolOutput, executablePath);
802
- if (manifestEntry.size !== statSync2(executablePath).size) {
803
- throw new Error(`Native runtime manifest size mismatch for ${runtimeKey}`);
804
- }
805
- if (manifestEntry.fileOutput !== fileOutput) {
806
- throw new Error(`Native runtime manifest file output mismatch for ${runtimeKey}`);
807
- }
808
- if (manifestEntry.otoolOutput !== otoolOutput) {
809
- throw new Error(`Native runtime manifest otool output mismatch for ${runtimeKey}`);
810
- }
811
- if (canInspectMacBinary(target)) {
812
- verifyMacCodeSignature(executablePath);
813
- verifyMacCodeSignaturePageSize(executablePath);
814
- verifyMacRuntimeEntitlements(executablePath);
815
- }
816
- if (options.verifyRunnable === true && shouldVerifyRuntimeKey2(runtimeKey)) {
817
- const version = verifyStagedDeusRuntimeVersion(executablePath);
818
- log(`\u2713 ${runtimeKey}/deus-runtime ${version}`);
819
- }
820
- }
821
- log(`\u2713 Native runtime ready (${runtimeKeys.join(", ")})`);
822
- return manifest;
823
- }
824
-
825
- // ../../scripts/runtime/validate.ts
826
- var runtimeDir3 = path4.dirname(fileURLToPath3(import.meta.url));
827
- var defaultProjectRoot3 = path4.resolve(runtimeDir3, "../..");
828
- var BUILD_RUNTIME_COMMAND = "bun run build:runtime";
829
- function relativeFromProjectRoot3(projectRoot, targetPath) {
830
- return path4.relative(projectRoot, targetPath).split(path4.sep).join("/");
831
- }
832
- function createBuildRuntimeError(message) {
833
- return new Error(`${message}
834
- Run \`${BUILD_RUNTIME_COMMAND}\` before packaging.`);
835
- }
836
- function readManifest(manifestPath) {
837
- try {
838
- return JSON.parse(readFileSync3(manifestPath, "utf8"));
839
- } catch (error2) {
840
- throw createBuildRuntimeError(
841
- `Unable to read staged runtime manifest at ${manifestPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
842
- );
843
- }
844
- }
845
- function hashFile3(filePath) {
846
- return createHash3("sha256").update(readFileSync3(filePath)).digest("hex");
847
- }
848
- function ghArchiveName(version, archivePlatform, extension = "zip") {
849
- return `gh_${version}_${archivePlatform}.${extension}`;
850
- }
851
- function readGhCliContract(projectRoot) {
852
- const contractPath = path4.join(projectRoot, "scripts", "runtime", "gh-cli-contract.json");
853
- try {
854
- const contract = JSON.parse(readFileSync3(contractPath, "utf8"));
855
- if (typeof contract.ghVersion !== "string" || !Array.isArray(contract.targets)) {
856
- throw new Error("unexpected contract shape");
857
- }
858
- return contract;
859
- } catch (error2) {
860
- throw createBuildRuntimeError(
861
- `Unable to read GitHub CLI contract at ${contractPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
862
- );
863
- }
864
- }
865
- function assertExists(filePath, label) {
866
- if (!existsSync3(filePath)) {
867
- throw createBuildRuntimeError(`Missing ${label}: ${filePath}`);
868
- }
869
- }
870
- function assertExecutable3(filePath, label) {
871
- assertExists(filePath, label);
872
- const stat = statSync3(filePath);
873
- if (!stat.isFile()) {
874
- throw createBuildRuntimeError(`Expected ${label} to be a regular file: ${filePath}`);
875
- }
876
- if ((stat.mode & 73) === 0) {
877
- throw createBuildRuntimeError(`Expected ${label} to be executable: ${filePath}`);
878
- }
879
- }
880
- function getExecutableFileOutput2(projectRoot, filePath, label, fileFormat, fileArch) {
881
- const fileOutput = execFileSync3("file", [relativeFromProjectRoot3(projectRoot, filePath)], {
882
- cwd: projectRoot,
883
- encoding: "utf8",
884
- timeout: 2e4,
885
- stdio: ["ignore", "pipe", "pipe"]
886
- }).trim();
887
- const hasExpectedFormat = fileFormat === "Mach-O 64-bit executable" ? fileOutput.includes("Mach-O 64-bit") && fileOutput.includes("executable") : fileOutput.includes(fileFormat);
888
- if (!hasExpectedFormat || !fileOutput.includes(fileArch)) {
889
- throw createBuildRuntimeError(`Unexpected ${label} architecture: ${fileOutput}`);
890
- }
891
- return fileOutput;
892
- }
893
- function verifyMacCodeSignature2(filePath, label) {
894
- if (process.platform !== "darwin" || !label.startsWith("darwin-")) return;
895
- try {
896
- execFileSync3("codesign", ["--verify", "--verbose=2", filePath], {
897
- encoding: "utf8",
898
- timeout: 2e4,
899
- stdio: ["ignore", "ignore", "pipe"]
900
- });
901
- } catch (error2) {
902
- throw createBuildRuntimeError(
903
- `Invalid ${label} code signature: ${error2 instanceof Error ? error2.message : String(error2)}`
904
- );
905
- }
906
- }
907
- function assertStagedGhCli(projectRoot) {
908
- const binRoot = path4.join(resolveRuntimeStagePaths(projectRoot).electron.root, "bin");
909
- const manifestPath = path4.join(binRoot, "gh-cli.json");
910
- assertExists(manifestPath, "staged GitHub CLI manifest");
911
- const manifest = JSON.parse(readFileSync3(manifestPath, "utf8"));
912
- if (manifest.version !== 1 || !Array.isArray(manifest.targets)) {
913
- throw createBuildRuntimeError(`Unexpected staged GitHub CLI manifest shape: ${manifestPath}`);
914
- }
915
- const contract = readGhCliContract(projectRoot);
916
- if (manifest.ghVersion !== contract.ghVersion) {
917
- throw createBuildRuntimeError(
918
- `GitHub CLI manifest version mismatch: expected ${contract.ghVersion}, found ${manifest.ghVersion}`
919
- );
920
- }
921
- for (const target of contract.targets) {
922
- const ghPath = path4.join(binRoot, target.runtimeKey, "gh");
923
- const label = `${target.runtimeKey}/gh`;
924
- assertExecutable3(ghPath, label);
925
- const fileOutput = getExecutableFileOutput2(
926
- projectRoot,
927
- ghPath,
928
- label,
929
- target.fileFormat ?? "Mach-O 64-bit executable",
930
- target.fileArch
931
- );
932
- verifyMacCodeSignature2(ghPath, label);
933
- const manifestEntry = manifest.targets.find(
934
- (entry) => entry.runtimeKey === target.runtimeKey && entry.tool === "gh"
935
- );
936
- if (!manifestEntry) {
937
- throw createBuildRuntimeError(`GitHub CLI manifest is missing ${target.runtimeKey}/gh`);
938
- }
939
- const expectedPath = relativeFromProjectRoot3(projectRoot, ghPath);
940
- if (manifestEntry.path !== expectedPath) {
941
- throw createBuildRuntimeError(
942
- `GitHub CLI manifest path mismatch for ${target.runtimeKey}/gh: expected ${expectedPath}, found ${manifestEntry.path}`
943
- );
944
- }
945
- if (manifestEntry.sha256 !== hashFile3(ghPath)) {
946
- throw createBuildRuntimeError(
947
- `GitHub CLI manifest hash mismatch for ${target.runtimeKey}/gh`
948
- );
949
- }
950
- if (manifestEntry.size !== statSync3(ghPath).size) {
951
- throw createBuildRuntimeError(
952
- `GitHub CLI manifest size mismatch for ${target.runtimeKey}/gh`
953
- );
954
- }
955
- if (manifestEntry.fileOutput !== fileOutput) {
956
- throw createBuildRuntimeError(
957
- `GitHub CLI manifest file output mismatch for ${target.runtimeKey}/gh`
958
- );
959
- }
960
- const archiveName = ghArchiveName(
961
- contract.ghVersion,
962
- target.archivePlatform,
963
- target.archiveExtension
964
- );
965
- const expectedUrl = `https://github.com/cli/cli/releases/download/v${contract.ghVersion}/${archiveName}`;
966
- const source = manifestEntry.source;
967
- if (!source || source.version !== contract.ghVersion || source.archiveName !== archiveName || source.archiveSha256 !== target.archiveSha256 || source.url !== expectedUrl) {
968
- throw createBuildRuntimeError(
969
- `GitHub CLI manifest source mismatch for ${target.runtimeKey}/gh`
970
- );
971
- }
972
- }
973
- }
974
- function assertPackagedProviderBinaries(projectRoot) {
975
- try {
976
- validateDeusRuntime({
977
- projectRoot,
978
- log: () => void 0,
979
- verifyRunnable: process.env.DEUS_VERIFY_RUNTIME_RUNNABLE === "1"
980
- });
981
- } catch (error2) {
982
- throw createBuildRuntimeError(
983
- `Native runtime validation failed: ${error2 instanceof Error ? error2.message : String(error2)}`
984
- );
985
- }
986
- try {
987
- validateStagedAgentClis({ projectRoot, log: () => void 0, verifyRunnable: false });
988
- } catch (error2) {
989
- throw createBuildRuntimeError(
990
- `Staged agent CLI validation failed: ${error2 instanceof Error ? error2.message : String(error2)}`
991
- );
992
- }
993
- assertStagedGhCli(projectRoot);
994
- }
995
- function assertNotStale(projectRoot, filePath, label, sourcePath, sourceLabel) {
996
- if (statSync3(filePath).mtimeMs < statSync3(sourcePath).mtimeMs) {
997
- throw createBuildRuntimeError(
998
- `${label} is stale: ${relativeFromProjectRoot3(projectRoot, filePath)} is older than ${relativeFromProjectRoot3(projectRoot, sourcePath)} (${sourceLabel})`
999
- );
1000
- }
1001
- }
1002
- function buildExpectedManifest(projectRoot) {
1003
- const stagePaths = resolveRuntimeStagePaths(projectRoot);
1004
- return {
1005
- version: RUNTIME_MANIFEST_VERSION,
1006
- appId: DEUS_APP_ID,
1007
- data: {
1008
- databaseFile: DEUS_DB_FILENAME,
1009
- preferencesFile: DEUS_PREFERENCES_FILENAME
1010
- },
1011
- bundles: {
1012
- common: {
1013
- backend: relativeFromProjectRoot3(projectRoot, stagePaths.common.backendBundle)
1014
- }
1015
- },
1016
- nodeRuntimeDependencies: CLI_RUNTIME_DEPENDENCIES
1017
- };
1018
- }
1019
- function validateRuntimeStage(options = {}) {
1020
- const log = options.log ?? console.log;
1021
- const projectRoot = options.projectRoot ?? defaultProjectRoot3;
1022
- const stagePaths = resolveRuntimeStagePaths(projectRoot);
1023
- const sources = {
1024
- backendBundle: path4.join(projectRoot, "apps", "backend", "dist", "server.bundled.cjs")
1025
- };
1026
- assertExists(sources.backendBundle, "runtime source bundle (backend)");
1027
- assertExists(stagePaths.manifest, "staged runtime manifest");
1028
- assertExists(stagePaths.common.backendBundle, "staged common backend bundle");
1029
- const manifest = readManifest(stagePaths.manifest);
1030
- const expectedManifest = buildExpectedManifest(projectRoot);
1031
- if (JSON.stringify(manifest) !== JSON.stringify(expectedManifest)) {
1032
- throw createBuildRuntimeError(
1033
- `Staged runtime manifest at ${stagePaths.manifest} does not match the current runtime contract`
1034
- );
1035
- }
1036
- assertNotStale(
1037
- projectRoot,
1038
- stagePaths.common.backendBundle,
1039
- "staged common backend bundle",
1040
- sources.backendBundle,
1041
- "backend source bundle"
1042
- );
1043
- const latestSourceMtime2 = statSync3(sources.backendBundle).mtimeMs;
1044
- if (statSync3(stagePaths.manifest).mtimeMs < latestSourceMtime2) {
1045
- throw createBuildRuntimeError(
1046
- `Staged runtime manifest is stale: ${relativeFromProjectRoot3(projectRoot, stagePaths.manifest)} is older than the source bundles`
1047
- );
1048
- }
1049
- assertPackagedProviderBinaries(projectRoot);
1050
- log(
1051
- `\u2713 Staged runtime ready for packaging (${relativeFromProjectRoot3(projectRoot, stagePaths.root)})`
1052
- );
1053
- return manifest;
1054
- }
1055
- var entryPath = process.argv[1] ? path4.resolve(process.argv[1]) : null;
1056
- if (entryPath === fileURLToPath3(import.meta.url)) {
1057
- try {
1058
- validateRuntimeStage();
1059
- } catch (error2) {
1060
- console.error("Runtime validation failed:", error2);
1061
- process.exit(1);
1062
- }
1063
- }
1064
-
1065
126
  // src/ui.ts
1066
127
  var ESC = "\x1B[";
1067
128
  var RESET = `${ESC}0m`;
@@ -1416,13 +477,13 @@ function sleep(ms) {
1416
477
 
1417
478
  // src/config.ts
1418
479
  import {
1419
- readFileSync as readFileSync4,
1420
- writeFileSync as writeFileSync3,
1421
- existsSync as existsSync4,
480
+ readFileSync,
481
+ writeFileSync,
482
+ existsSync,
1422
483
  unlinkSync,
1423
484
  renameSync,
1424
- mkdirSync as mkdirSync3,
1425
- chmodSync as chmodSync3
485
+ mkdirSync,
486
+ chmodSync
1426
487
  } from "node:fs";
1427
488
  import { join } from "node:path";
1428
489
  import { homedir, platform } from "node:os";
@@ -1449,10 +510,10 @@ function getServerInfoPath() {
1449
510
  return join(getConfigDir(), "server.json");
1450
511
  }
1451
512
  function loadConfig() {
1452
- const path5 = getConfigPath();
1453
- if (!existsSync4(path5)) return { ...DEFAULT_CONFIG };
513
+ const path2 = getConfigPath();
514
+ if (!existsSync(path2)) return { ...DEFAULT_CONFIG };
1454
515
  try {
1455
- const raw = readFileSync4(path5, "utf-8");
516
+ const raw = readFileSync(path2, "utf-8");
1456
517
  const parsed = JSON.parse(raw);
1457
518
  return { ...DEFAULT_CONFIG, ...parsed };
1458
519
  } catch {
@@ -1461,19 +522,19 @@ function loadConfig() {
1461
522
  }
1462
523
  function saveConfig(config) {
1463
524
  const dir = getConfigDir();
1464
- mkdirSync3(dir, { recursive: true });
1465
- const path5 = getConfigPath();
1466
- const tmp = path5 + ".tmp." + randomBytes(4).toString("hex");
525
+ mkdirSync(dir, { recursive: true });
526
+ const path2 = getConfigPath();
527
+ const tmp = path2 + ".tmp." + randomBytes(4).toString("hex");
1467
528
  try {
1468
- writeFileSync3(tmp, JSON.stringify(config, null, 2) + "\n", "utf-8");
1469
- chmodSync3(tmp, 384);
1470
- renameSync(tmp, path5);
529
+ writeFileSync(tmp, JSON.stringify(config, null, 2) + "\n", "utf-8");
530
+ chmodSync(tmp, 384);
531
+ renameSync(tmp, path2);
1471
532
  } catch {
1472
533
  try {
1473
534
  unlinkSync(tmp);
1474
535
  } catch {
1475
536
  }
1476
- throw new Error(`Failed to save config to ${path5}`);
537
+ throw new Error(`Failed to save config to ${path2}`);
1477
538
  }
1478
539
  }
1479
540
  function hasCompletedOnboarding() {
@@ -1481,16 +542,16 @@ function hasCompletedOnboarding() {
1481
542
  }
1482
543
  function writeServerInfo(info2) {
1483
544
  const dir = getConfigDir();
1484
- mkdirSync3(dir, { recursive: true });
1485
- const path5 = getServerInfoPath();
1486
- writeFileSync3(path5, JSON.stringify(info2, null, 2) + "\n", "utf-8");
1487
- chmodSync3(path5, 384);
545
+ mkdirSync(dir, { recursive: true });
546
+ const path2 = getServerInfoPath();
547
+ writeFileSync(path2, JSON.stringify(info2, null, 2) + "\n", "utf-8");
548
+ chmodSync(path2, 384);
1488
549
  }
1489
550
  function readServerInfo() {
1490
- const path5 = getServerInfoPath();
1491
- if (!existsSync4(path5)) return null;
551
+ const path2 = getServerInfoPath();
552
+ if (!existsSync(path2)) return null;
1492
553
  try {
1493
- const raw = readFileSync4(path5, "utf-8");
554
+ const raw = readFileSync(path2, "utf-8");
1494
555
  const info2 = JSON.parse(raw);
1495
556
  try {
1496
557
  process.kill(info2.pid, 0);
@@ -1504,16 +565,16 @@ function readServerInfo() {
1504
565
  }
1505
566
  }
1506
567
  function clearServerInfo() {
1507
- const path5 = getServerInfoPath();
568
+ const path2 = getServerInfoPath();
1508
569
  try {
1509
- unlinkSync(path5);
570
+ unlinkSync(path2);
1510
571
  } catch {
1511
572
  }
1512
573
  }
1513
574
 
1514
575
  // src/login.ts
1515
- import { execSync, spawnSync as spawnSync3 } from "node:child_process";
1516
- import { existsSync as existsSync5 } from "node:fs";
576
+ import { execSync, spawnSync } from "node:child_process";
577
+ import { existsSync as existsSync2 } from "node:fs";
1517
578
  import { join as join2 } from "node:path";
1518
579
  import { homedir as homedir2, platform as platform2 } from "node:os";
1519
580
 
@@ -1728,7 +789,7 @@ function getClaudeCliCandidates() {
1728
789
  }
1729
790
  function detectClaudeCli() {
1730
791
  for (const candidate of getClaudeCliCandidates()) {
1731
- if (existsSync5(candidate)) {
792
+ if (existsSync2(candidate)) {
1732
793
  try {
1733
794
  const version = execSync(`node "${candidate}" --version`, {
1734
795
  encoding: "utf-8",
@@ -1772,7 +833,7 @@ function isClaudeAuthenticated() {
1772
833
  join2(homedir2(), ".claude", "credentials.json")
1773
834
  ];
1774
835
  for (const p of credPaths) {
1775
- if (existsSync5(p)) return true;
836
+ if (existsSync2(p)) return true;
1776
837
  }
1777
838
  return false;
1778
839
  }
@@ -1856,7 +917,7 @@ async function runClaudeLogin(cliPath) {
1856
917
  blank();
1857
918
  hint("Opening browser for authentication...");
1858
919
  blank();
1859
- const result = spawnSync3(cliPath, ["login"], {
920
+ const result = spawnSync(cliPath, ["login"], {
1860
921
  stdio: "inherit",
1861
922
  timeout: 12e4
1862
923
  });
@@ -1876,7 +937,7 @@ async function runClaudeLogin(cliPath) {
1876
937
  async function installAndLogin() {
1877
938
  blank();
1878
939
  const s = spinner("Installing Claude Code CLI...");
1879
- const result = spawnSync3("npm", ["install", "-g", "@anthropic-ai/claude-code"], {
940
+ const result = spawnSync("npm", ["install", "-g", "@anthropic-ai/claude-code"], {
1880
941
  stdio: ["pipe", "pipe", "pipe"],
1881
942
  timeout: 12e4
1882
943
  });
@@ -2346,10 +1407,10 @@ function printQR(data, indent = 4) {
2346
1407
 
2347
1408
  // src/lib/http.ts
2348
1409
  import { request } from "node:http";
2349
- function httpGet(port, path5, timeoutMs = 3e3) {
1410
+ function httpGet(port, path2, timeoutMs = 3e3) {
2350
1411
  return new Promise((resolve2) => {
2351
1412
  const req = request(
2352
- { hostname: "localhost", port, path: path5, method: "GET", timeout: timeoutMs },
1413
+ { hostname: "localhost", port, path: path2, method: "GET", timeout: timeoutMs },
2353
1414
  (res) => {
2354
1415
  let body = "";
2355
1416
  res.on("data", (chunk) => body += chunk.toString());
@@ -2370,14 +1431,14 @@ function httpGet(port, path5, timeoutMs = 3e3) {
2370
1431
  req.end();
2371
1432
  });
2372
1433
  }
2373
- function httpPost(port, path5, body) {
1434
+ function httpPost(port, path2, body) {
2374
1435
  return new Promise((resolve2, reject) => {
2375
1436
  const payload = body ? JSON.stringify(body) : "";
2376
1437
  const req = request(
2377
1438
  {
2378
1439
  hostname: "localhost",
2379
1440
  port,
2380
- path: path5,
1441
+ path: path2,
2381
1442
  method: "POST",
2382
1443
  headers: {
2383
1444
  "Content-Type": "application/json",
@@ -2390,13 +1451,13 @@ function httpPost(port, path5, body) {
2390
1451
  res.on("data", (chunk) => data += chunk.toString());
2391
1452
  res.on("end", () => {
2392
1453
  if (res.statusCode !== 200) {
2393
- reject(new Error(`${path5} returned ${res.statusCode}: ${data}`));
1454
+ reject(new Error(`${path2} returned ${res.statusCode}: ${data}`));
2394
1455
  return;
2395
1456
  }
2396
1457
  try {
2397
1458
  resolve2(JSON.parse(data));
2398
1459
  } catch {
2399
- reject(new Error(`Invalid JSON from ${path5}`));
1460
+ reject(new Error(`Invalid JSON from ${path2}`));
2400
1461
  }
2401
1462
  });
2402
1463
  }
@@ -2404,7 +1465,7 @@ function httpPost(port, path5, body) {
2404
1465
  req.on("error", reject);
2405
1466
  req.on("timeout", () => {
2406
1467
  req.destroy();
2407
- reject(new Error(`Timeout: ${path5}`));
1468
+ reject(new Error(`Timeout: ${path2}`));
2408
1469
  });
2409
1470
  req.end(payload);
2410
1471
  });
@@ -2501,7 +1562,7 @@ async function pair() {
2501
1562
  }
2502
1563
 
2503
1564
  // src/start.ts
2504
- var __filename = fileURLToPath4(import.meta.url);
1565
+ var __filename = fileURLToPath(import.meta.url);
2505
1566
  var __dirname = dirname(__filename);
2506
1567
  async function start(options) {
2507
1568
  const { dataDir } = options;
@@ -2518,7 +1579,16 @@ async function start(options) {
2518
1579
  blank();
2519
1580
  process.exit(1);
2520
1581
  }
2521
- const nodeCmd = resolveNodeBinary();
1582
+ const sqliteFailure = sqliteLoadFailure();
1583
+ if (sqliteFailure) {
1584
+ error(`SQLite (better-sqlite3) does not load under Node ${process.version}: ${sqliteFailure}`);
1585
+ blank();
1586
+ hint(
1587
+ paths.monorepo ? `Run ${c.cyan("bun run native:node")} from the monorepo root, then start again.` : `Reinstall Deus with ${c.cyan("npm install -g deus-machine")}, then start again.`
1588
+ );
1589
+ blank();
1590
+ process.exit(1);
1591
+ }
2522
1592
  const dbPath = resolveDataDir(dataDir);
2523
1593
  kv("Database", c.dim(dbPath));
2524
1594
  blank();
@@ -2552,10 +1622,8 @@ async function start(options) {
2552
1622
  }
2553
1623
  const s1 = spinner("Starting backend...");
2554
1624
  const started = await startBackendProcess({
2555
- command: nodeCmd,
2556
1625
  backendEntry: paths.backend,
2557
1626
  backendCwd: dirname(paths.backend),
2558
- forceElectronRunAsNode: nodeCmd !== process.execPath,
2559
1627
  env: {
2560
1628
  DATABASE_PATH: dbPath,
2561
1629
  PORT: "0",
@@ -2618,21 +1686,24 @@ async function start(options) {
2618
1686
  function resolveBundlePaths() {
2619
1687
  const cliRoot = resolve(__dirname, "..");
2620
1688
  const bundledDir = join3(cliRoot, "bundles");
2621
- if (existsSync6(join3(bundledDir, "server.bundled.cjs"))) {
2622
- return { backend: join3(bundledDir, "server.bundled.cjs") };
1689
+ if (existsSync3(join3(bundledDir, "server.bundled.cjs"))) {
1690
+ return { backend: join3(bundledDir, "server.bundled.cjs"), monorepo: false };
2623
1691
  }
2624
1692
  const monorepoRoot = resolve(cliRoot, "../..");
2625
- const runtimePaths = resolveRuntimeStagePaths(monorepoRoot);
1693
+ const backend = resolveRuntimeStagePaths(monorepoRoot).common.backendBundle;
1694
+ if (existsSync3(backend)) return { backend, monorepo: true };
1695
+ warn(`The staged runtime is missing in the monorepo: ${backend} does not exist.`);
1696
+ return null;
1697
+ }
1698
+ function sqliteLoadFailure() {
2626
1699
  try {
2627
- validateRuntimeStage({ projectRoot: monorepoRoot, log: () => {
2628
- } });
2629
- return { backend: runtimePaths.common.backendBundle };
2630
- } catch (error2) {
2631
- warn(
2632
- `Staged runtime is missing or stale in monorepo mode: ${error2 instanceof Error ? error2.message : String(error2)}`
2633
- );
1700
+ const Database = createRequire(import.meta.url)("better-sqlite3");
1701
+ new Database(":memory:").close();
1702
+ return null;
1703
+ } catch (cause) {
1704
+ const message = cause instanceof Error ? cause.message : String(cause);
1705
+ return message.split("\n")[0];
2634
1706
  }
2635
- return null;
2636
1707
  }
2637
1708
  function resolveDataDir(customDir) {
2638
1709
  const dir = customDir ?? resolveDefaultDataDir({
@@ -2641,42 +1712,16 @@ function resolveDataDir(customDir) {
2641
1712
  appData: process.env.APPDATA,
2642
1713
  xdgDataHome: process.env.XDG_DATA_HOME
2643
1714
  });
2644
- mkdirSync4(dir, { recursive: true });
1715
+ mkdirSync2(dir, { recursive: true });
2645
1716
  return join3(dir, DEUS_DB_FILENAME);
2646
1717
  }
2647
- function resolveNodeBinary() {
2648
- if (process.env.ELECTRON_RUN_AS_NODE === "1") return process.execPath;
2649
- try {
2650
- const electronPath = execSync2(
2651
- `node -e "try { console.log(require('electron')) } catch { process.exit(1) }"`,
2652
- { encoding: "utf-8", timeout: 5e3, stdio: ["pipe", "pipe", "pipe"] }
2653
- ).trim();
2654
- if (electronPath && existsSync6(electronPath)) {
2655
- try {
2656
- execSync2(
2657
- `node -e "const D = require('better-sqlite3'); const d = new D(':memory:'); d.close()"`,
2658
- { timeout: 5e3, stdio: ["pipe", "pipe", "pipe"] }
2659
- );
2660
- return process.execPath;
2661
- } catch {
2662
- return electronPath;
2663
- }
2664
- }
2665
- } catch {
2666
- }
2667
- return process.execPath;
2668
- }
2669
1718
  async function startBackendProcess(opts) {
2670
- const { command, backendEntry, backendCwd, env, forceElectronRunAsNode, onUnexpectedExit } = opts;
1719
+ const { backendEntry, backendCwd, env, onUnexpectedExit } = opts;
2671
1720
  return new Promise((resolve2) => {
2672
- const child = spawn2(command, [backendEntry], {
1721
+ const child = spawn(process.execPath, [backendEntry], {
2673
1722
  cwd: backendCwd,
2674
1723
  stdio: ["ignore", "pipe", "pipe"],
2675
- env: {
2676
- ...process.env,
2677
- ...forceElectronRunAsNode ? { ELECTRON_RUN_AS_NODE: "1" } : {},
2678
- ...env
2679
- }
1724
+ env: { ...process.env, ...env }
2680
1725
  });
2681
1726
  let buffer = "";
2682
1727
  let resolved = false;
@@ -2728,13 +1773,13 @@ function stopBackendProcess(child) {
2728
1773
  }
2729
1774
 
2730
1775
  // src/desktop.ts
2731
- import { execFileSync as execFileSync4, execSync as execSync3, spawn as spawn3 } from "node:child_process";
1776
+ import { execFileSync, execSync as execSync2, spawn as spawn2 } from "node:child_process";
2732
1777
  import {
2733
- chmodSync as chmodSync4,
1778
+ chmodSync as chmodSync2,
2734
1779
  copyFileSync,
2735
1780
  createWriteStream,
2736
- existsSync as existsSync7,
2737
- mkdirSync as mkdirSync5,
1781
+ existsSync as existsSync4,
1782
+ mkdirSync as mkdirSync3,
2738
1783
  unlinkSync as unlinkSync2
2739
1784
  } from "node:fs";
2740
1785
  import { join as join4 } from "node:path";
@@ -2747,7 +1792,7 @@ var INSTALL_PATHS = {
2747
1792
  };
2748
1793
  function hasDisplay() {
2749
1794
  const os = platform3();
2750
- if (process.env.CI || process.env.DOCKER || existsSync7("/.dockerenv")) return false;
1795
+ if (process.env.CI || process.env.DOCKER || existsSync4("/.dockerenv")) return false;
2751
1796
  if (process.env.SSH_CONNECTION || process.env.SSH_TTY) return false;
2752
1797
  if (os === "darwin") return true;
2753
1798
  if (os === "linux") return !!(process.env.DISPLAY || process.env.WAYLAND_DISPLAY);
@@ -2757,7 +1802,7 @@ function findInstalledApp() {
2757
1802
  const os = platform3();
2758
1803
  const paths = INSTALL_PATHS[os] || [];
2759
1804
  for (const p of paths) {
2760
- if (p && existsSync7(p)) return p;
1805
+ if (p && existsSync4(p)) return p;
2761
1806
  }
2762
1807
  return null;
2763
1808
  }
@@ -2765,10 +1810,10 @@ function launchDesktop(appPath) {
2765
1810
  const os = platform3();
2766
1811
  switch (os) {
2767
1812
  case "darwin":
2768
- spawn3("open", [appPath], { detached: true, stdio: "ignore" }).unref();
1813
+ spawn2("open", [appPath], { detached: true, stdio: "ignore" }).unref();
2769
1814
  break;
2770
1815
  case "linux":
2771
- spawn3(appPath, [], {
1816
+ spawn2(appPath, [], {
2772
1817
  detached: true,
2773
1818
  stdio: "ignore",
2774
1819
  env: {
@@ -2788,9 +1833,9 @@ function hasFuse2() {
2788
1833
  "/usr/lib64/libfuse.so.2",
2789
1834
  "/usr/lib/libfuse.so.2"
2790
1835
  ];
2791
- if (commonLibPaths.some((libPath) => existsSync7(libPath))) return true;
1836
+ if (commonLibPaths.some((libPath) => existsSync4(libPath))) return true;
2792
1837
  try {
2793
- return execSync3("ldconfig -p", { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }).split("\n").some((line) => line.includes("libfuse.so.2"));
1838
+ return execSync2("ldconfig -p", { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }).split("\n").some((line) => line.includes("libfuse.so.2"));
2794
1839
  } catch {
2795
1840
  return false;
2796
1841
  }
@@ -2801,21 +1846,21 @@ function isOnPath(dir) {
2801
1846
  function replaceInstalledMacApp(appPath, destPath) {
2802
1847
  const stagedPath = `${destPath}.staged`;
2803
1848
  const backupPath = `${destPath}.backup`;
2804
- const hadExistingInstall = existsSync7(destPath);
2805
- execSync3(`rm -rf "${stagedPath}" "${backupPath}"`, { stdio: "pipe" });
2806
- execSync3(`ditto "${appPath}" "${stagedPath}"`, { stdio: "pipe" });
1849
+ const hadExistingInstall = existsSync4(destPath);
1850
+ execSync2(`rm -rf "${stagedPath}" "${backupPath}"`, { stdio: "pipe" });
1851
+ execSync2(`ditto "${appPath}" "${stagedPath}"`, { stdio: "pipe" });
2807
1852
  if (hadExistingInstall) {
2808
- execSync3(`mv "${destPath}" "${backupPath}"`, { stdio: "pipe" });
1853
+ execSync2(`mv "${destPath}" "${backupPath}"`, { stdio: "pipe" });
2809
1854
  }
2810
1855
  try {
2811
- execSync3(`mv "${stagedPath}" "${destPath}"`, { stdio: "pipe" });
1856
+ execSync2(`mv "${stagedPath}" "${destPath}"`, { stdio: "pipe" });
2812
1857
  if (hadExistingInstall) {
2813
- execSync3(`rm -rf "${backupPath}"`, { stdio: "pipe" });
1858
+ execSync2(`rm -rf "${backupPath}"`, { stdio: "pipe" });
2814
1859
  }
2815
1860
  } catch (error2) {
2816
- execSync3(`rm -rf "${stagedPath}"`, { stdio: "pipe" });
2817
- if (hadExistingInstall && existsSync7(backupPath) && !existsSync7(destPath)) {
2818
- execSync3(`mv "${backupPath}" "${destPath}"`, { stdio: "pipe" });
1861
+ execSync2(`rm -rf "${stagedPath}"`, { stdio: "pipe" });
1862
+ if (hadExistingInstall && existsSync4(backupPath) && !existsSync4(destPath)) {
1863
+ execSync2(`mv "${backupPath}" "${destPath}"`, { stdio: "pipe" });
2819
1864
  }
2820
1865
  throw error2;
2821
1866
  }
@@ -2860,7 +1905,7 @@ async function installDesktop(options) {
2860
1905
  process.exit(1);
2861
1906
  }
2862
1907
  const downloadDir = join4(tmpdir(), "deus-installer");
2863
- mkdirSync5(downloadDir, { recursive: true });
1908
+ mkdirSync3(downloadDir, { recursive: true });
2864
1909
  const downloadPath = join4(downloadDir, asset.name);
2865
1910
  await downloadFile(asset.browser_download_url, downloadPath);
2866
1911
  const s3 = spinner("Installing...");
@@ -3005,7 +2050,7 @@ async function installForPlatform(os, filePath, s) {
3005
2050
  case "darwin": {
3006
2051
  let mountPoint;
3007
2052
  try {
3008
- const mountOutput = execSync3(`hdiutil attach "${filePath}" -nobrowse`, {
2053
+ const mountOutput = execSync2(`hdiutil attach "${filePath}" -nobrowse`, {
3009
2054
  encoding: "utf-8"
3010
2055
  });
3011
2056
  mountPoint = mountOutput.split("\n").filter((line) => line.includes("/Volumes/")).map((line) => line.trim().split(" ").pop()?.trim()).find(Boolean);
@@ -3016,7 +2061,7 @@ async function installForPlatform(os, filePath, s) {
3016
2061
  const appName = "Deus.app";
3017
2062
  const appPath = `${mountPoint}/${appName}`;
3018
2063
  const destPath = `/Applications/${appName}`;
3019
- if (existsSync7(appPath)) {
2064
+ if (existsSync4(appPath)) {
3020
2065
  replaceInstalledMacApp(appPath, destPath);
3021
2066
  s.succeed(`Installed to ${c.dim("/Applications/Deus.app")}`);
3022
2067
  launchDesktop(destPath);
@@ -3027,13 +2072,13 @@ async function installForPlatform(os, filePath, s) {
3027
2072
  return null;
3028
2073
  } catch {
3029
2074
  s.fail("Auto-install failed \u2014 opening DMG manually");
3030
- execFileSync4("open", [filePath], { stdio: "ignore" });
2075
+ execFileSync("open", [filePath], { stdio: "ignore" });
3031
2076
  hint("Drag Deus.app to Applications, then launch it from Applications.");
3032
2077
  return null;
3033
2078
  } finally {
3034
2079
  if (mountPoint) {
3035
2080
  try {
3036
- execSync3(`hdiutil detach "${mountPoint}" -quiet`, { stdio: "pipe" });
2081
+ execSync2(`hdiutil detach "${mountPoint}" -quiet`, { stdio: "pipe" });
3037
2082
  } catch {
3038
2083
  }
3039
2084
  }
@@ -3042,10 +2087,10 @@ async function installForPlatform(os, filePath, s) {
3042
2087
  case "linux": {
3043
2088
  try {
3044
2089
  const installDir = join4(homedir4(), ".local", "bin");
3045
- mkdirSync5(installDir, { recursive: true });
2090
+ mkdirSync3(installDir, { recursive: true });
3046
2091
  const destPath = join4(installDir, "Deus.AppImage");
3047
2092
  copyFileSync(filePath, destPath);
3048
- chmodSync4(destPath, 493);
2093
+ chmodSync2(destPath, 493);
3049
2094
  s.succeed(`Installed to ${c.dim(destPath)}`);
3050
2095
  if (!hasFuse2()) {
3051
2096
  info("libfuse2 not found; launching AppImage with APPIMAGE_EXTRACT_AND_RUN=1.");