deus-machine 0.3.3 → 0.3.8

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.3",
22
+ version: "0.3.8",
23
23
  description: "Run Deus IDE from the command line \u2014 headless server or desktop installer",
24
24
  license: "MIT",
25
25
  author: {
@@ -58,9 +58,11 @@ var init_package = __esm({
58
58
  build: "bunx tsx build.ts"
59
59
  },
60
60
  dependencies: {
61
+ "@anthropic-ai/claude-agent-sdk": "0.2.131",
62
+ "@hono/node-server": "^1.19.9",
61
63
  "@napi-rs/canvas": "^0.1.97",
62
- "@openai/codex": "^0.101.0",
63
- "@openai/codex-sdk": "^0.101.0",
64
+ "@openai/codex": "0.130.0",
65
+ "@openai/codex-sdk": "0.130.0",
64
66
  "@sentry/node": "^10.40.0",
65
67
  "agent-browser": "^0.21.4",
66
68
  "better-sqlite3": "^12.4.1",
@@ -75,12 +77,12 @@ var init_package = __esm({
75
77
  import { parseArgs } from "node:util";
76
78
 
77
79
  // src/start.ts
78
- import { spawn, execSync as execSync2 } from "node:child_process";
79
- import { existsSync as existsSync4 } from "node:fs";
80
+ import { execSync as execSync2, spawn as spawn2 } from "node:child_process";
81
+ import { existsSync as existsSync6 } from "node:fs";
80
82
  import { join as join3, resolve, dirname } from "node:path";
81
- import { fileURLToPath as fileURLToPath2 } from "node:url";
83
+ import { fileURLToPath as fileURLToPath4 } from "node:url";
82
84
  import { homedir as homedir3 } from "node:os";
83
- import { mkdirSync as mkdirSync2 } from "node:fs";
85
+ import { mkdirSync as mkdirSync4 } from "node:fs";
84
86
 
85
87
  // ../../shared/runtime.ts
86
88
  import path from "node:path";
@@ -89,6 +91,8 @@ var DEUS_DB_FILENAME = "deus.db";
89
91
  var DEUS_PREFERENCES_FILENAME = "preferences.json";
90
92
  var RUNTIME_MANIFEST_VERSION = 1;
91
93
  var CLI_RUNTIME_DEPENDENCIES = [
94
+ "@anthropic-ai/claude-agent-sdk",
95
+ "@hono/node-server",
92
96
  "@napi-rs/canvas",
93
97
  "@openai/codex",
94
98
  "@openai/codex-sdk",
@@ -130,45 +134,872 @@ function resolveRuntimeStagePaths(projectRoot) {
130
134
  agentServerBundle: path.join(commonRoot, "agent-server.bundled.cjs")
131
135
  },
132
136
  electron: {
133
- root: electronRoot,
134
- backendBundle: path.join(electronRoot, "backend", "server.bundled.cjs"),
135
- agentServerBundle: path.join(electronRoot, "bin", "index.bundled.cjs")
137
+ root: electronRoot
136
138
  }
137
139
  };
138
140
  }
139
141
 
140
- // ../runtime/validate.ts
141
- import { existsSync, readFileSync, statSync } from "node:fs";
142
+ // ../../scripts/runtime/validate.ts
143
+ import { execFileSync as execFileSync3 } from "node:child_process";
144
+ import { createHash as createHash3 } from "node:crypto";
145
+ import { existsSync as existsSync3, readFileSync as readFileSync3, statSync as statSync3 } from "node:fs";
146
+ import path4 from "node:path";
147
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
148
+
149
+ // ../../scripts/runtime/agent-clis.ts
150
+ import { execFileSync, spawn, spawnSync } from "node:child_process";
151
+ import { createHash } from "node:crypto";
152
+ import {
153
+ chmodSync,
154
+ cpSync,
155
+ existsSync,
156
+ linkSync,
157
+ mkdirSync,
158
+ mkdtempSync,
159
+ readFileSync,
160
+ rmSync,
161
+ statSync,
162
+ writeFileSync
163
+ } from "node:fs";
142
164
  import path2 from "node:path";
143
165
  import { fileURLToPath } from "node:url";
144
166
  var runtimeDir = path2.dirname(fileURLToPath(import.meta.url));
145
167
  var defaultProjectRoot = path2.resolve(runtimeDir, "../..");
146
- var BUILD_RUNTIME_COMMAND = "bun run build:runtime";
168
+ var VERIFY_TIMEOUT_MS = 2e4;
169
+ var MIN_CODEX_APP_SERVER_VERSION = "0.128.0";
170
+ var VERSION_CHECK_ENV_DENYLIST = [
171
+ "AGENT_SERVER_CWD",
172
+ "AGENT_SERVER_ENTRY",
173
+ "AUTH_TOKEN",
174
+ "BUN_OPTIONS",
175
+ "DATABASE_PATH",
176
+ "DEUS_AUTH_TOKEN",
177
+ "DEUS_BACKEND_PORT",
178
+ "DEUS_BUNDLED_BIN_DIR",
179
+ "DEUS_DATA_DIR",
180
+ "DEUS_PACKAGED",
181
+ "DEUS_RESOURCES_PATH",
182
+ "DEUS_RUNTIME",
183
+ "DEUS_RUNTIME_COMMAND",
184
+ "DEUS_RUNTIME_EXECUTABLE",
185
+ "ELECTRON_RUN_AS_NODE",
186
+ "NODE_PATH",
187
+ "PORT"
188
+ ];
189
+ var AGENT_CLI_TARGETS = [
190
+ {
191
+ runtimeKey: "darwin-arm64",
192
+ fileFormat: "Mach-O 64-bit executable",
193
+ fileArch: "arm64",
194
+ agentBrowserEntry: "bin/agent-browser-darwin-arm64",
195
+ codexAliasPackage: "@openai/codex-darwin-arm64",
196
+ codexTriple: "aarch64-apple-darwin",
197
+ claudePackageName: "@anthropic-ai/claude-agent-sdk-darwin-arm64"
198
+ },
199
+ {
200
+ runtimeKey: "darwin-x64",
201
+ fileFormat: "Mach-O 64-bit executable",
202
+ fileArch: "x86_64",
203
+ agentBrowserEntry: "bin/agent-browser-darwin-x64",
204
+ codexAliasPackage: "@openai/codex-darwin-x64",
205
+ codexTriple: "x86_64-apple-darwin",
206
+ claudePackageName: "@anthropic-ai/claude-agent-sdk-darwin-x64"
207
+ },
208
+ {
209
+ runtimeKey: "linux-x64",
210
+ fileFormat: "ELF 64-bit",
211
+ fileArch: "x86-64",
212
+ agentBrowserEntry: "bin/agent-browser-linux-x64",
213
+ codexAliasPackage: "@openai/codex-linux-x64",
214
+ codexTriple: "x86_64-unknown-linux-musl",
215
+ claudePackageName: "@anthropic-ai/claude-agent-sdk-linux-x64"
216
+ }
217
+ ];
147
218
  function relativeFromProjectRoot(projectRoot, targetPath) {
148
219
  return path2.relative(projectRoot, targetPath).split(path2.sep).join("/");
149
220
  }
221
+ function resolveAgentCliManifestPath(projectRoot) {
222
+ return path2.join(resolveRuntimeStagePaths(projectRoot).electron.root, "bin", "agent-clis.json");
223
+ }
224
+ function resolveStagedAgentCliPath(projectRoot, runtimeKey, tool) {
225
+ return path2.join(resolveRuntimeStagePaths(projectRoot).electron.root, "bin", runtimeKey, tool);
226
+ }
227
+ function readSemver(version) {
228
+ return version.match(/\d+\.\d+\.\d+/)?.[0] ?? null;
229
+ }
230
+ function isVersionAtLeast(version, minimum) {
231
+ if (!version) return false;
232
+ const currentParts = version.split(".").map(Number);
233
+ const minimumParts = minimum.split(".").map(Number);
234
+ for (let i = 0; i < minimumParts.length; i++) {
235
+ const current = currentParts[i] ?? 0;
236
+ const required = minimumParts[i] ?? 0;
237
+ if (current > required) return true;
238
+ if (current < required) return false;
239
+ }
240
+ return true;
241
+ }
242
+ function assertCodexAppServerCompatible(version, label) {
243
+ const semver = readSemver(version);
244
+ if (isVersionAtLeast(semver, MIN_CODEX_APP_SERVER_VERSION)) return;
245
+ throw new Error(
246
+ `${label} requires @openai/codex >= ${MIN_CODEX_APP_SERVER_VERSION} for the codex app-server harness; found ${version}`
247
+ );
248
+ }
249
+ function hashFile(filePath) {
250
+ return createHash("sha256").update(readFileSync(filePath)).digest("hex");
251
+ }
252
+ function shouldVerifyRuntimeKey(runtimeKey) {
253
+ if (process.platform === "darwin") return runtimeKey === `darwin-${process.arch}`;
254
+ if (process.platform === "linux" && process.arch === "x64") return runtimeKey === "linux-x64";
255
+ return false;
256
+ }
257
+ function spawnErrorCode(error2) {
258
+ return error2?.code ?? error2?.message ?? "none";
259
+ }
260
+ function verifyVersion(executablePath, args, env = process.env) {
261
+ const result = spawnSync(executablePath, args, {
262
+ encoding: "utf8",
263
+ timeout: VERIFY_TIMEOUT_MS,
264
+ env,
265
+ stdio: ["ignore", "pipe", "pipe"]
266
+ });
267
+ const output = (result.stdout || "").trim();
268
+ if (result.status !== 0) {
269
+ const stderr = (result.stderr || "").trim();
270
+ const diagnostics = stagedExecutableDiagnostics(executablePath);
271
+ const hint2 = macExecutionPolicyHint(diagnostics);
272
+ throw new Error(
273
+ `${path2.basename(executablePath)} ${args.join(" ")} failed: status=${result.status} signal=${result.signal} error=${spawnErrorCode(result.error)} stdout=${output} stderr=${stderr}${diagnostics ? `
274
+ ${diagnostics}` : ""}${hint2}`
275
+ );
276
+ }
277
+ return output;
278
+ }
279
+ function diagnosticOutput(command, args, cwd) {
280
+ const result = spawnSync(command, args, {
281
+ cwd,
282
+ encoding: "utf8",
283
+ timeout: VERIFY_TIMEOUT_MS,
284
+ stdio: ["ignore", "pipe", "pipe"]
285
+ });
286
+ const output = `${result.stdout || ""}${result.stderr || ""}`.trim();
287
+ if (result.error) {
288
+ return [spawnErrorCode(result.error), output].filter(Boolean).join("\n");
289
+ }
290
+ if (result.status !== 0) return output || `${command} exited with status ${result.status}`;
291
+ return output;
292
+ }
293
+ function stagedExecutableDiagnostics(executablePath) {
294
+ if (process.platform !== "darwin") return "";
295
+ const cwd = path2.dirname(executablePath);
296
+ return [
297
+ `file: ${diagnosticOutput("file", [executablePath], cwd)}`,
298
+ `codesign: ${diagnosticOutput("codesign", ["-dv", "--verbose=4", executablePath], cwd)}`,
299
+ `spctl: ${diagnosticOutput("spctl", ["--assess", "--type", "execute", "--verbose=4", executablePath], cwd)}`,
300
+ `xattr: ${diagnosticOutput("xattr", ["-l", executablePath], cwd) || "none"}`
301
+ ].join("\n");
302
+ }
303
+ function macExecutionPolicyHint(diagnostics) {
304
+ if (process.platform !== "darwin") return "";
305
+ if (!/spctl:[\s\S]*rejected/.test(diagnostics)) return "";
306
+ if (!/com\.apple\.(provenance|quarantine)/.test(diagnostics)) return "";
307
+ return [
308
+ "",
309
+ "macOS rejected this executable before --version produced output.",
310
+ "Verify runnable staged agent CLIs on a notarized artifact or a macOS host that allows generated/copied Mach-O binaries to launch."
311
+ ].join("\n");
312
+ }
313
+ function assertVersionOutput(tool, output, executablePath) {
314
+ if (!output) {
315
+ throw new Error(`${tool} --version produced no output for ${executablePath}`);
316
+ }
317
+ if (tool === "codex" && !/\b\d+\.\d+\.\d+\b/.test(output)) {
318
+ throw new Error(`Unexpected codex --version output for ${executablePath}: ${output}`);
319
+ }
320
+ if (tool === "claude" && !/Claude Code|\b\d+\.\d+\.\d+\b/.test(output)) {
321
+ throw new Error(`Unexpected claude --version output for ${executablePath}: ${output}`);
322
+ }
323
+ }
324
+ function verifyStagedAgentCliVersion(tool, executablePath) {
325
+ const binDir = path2.dirname(executablePath);
326
+ const env = versionCheckEnv(binDir);
327
+ const output = verifyVersion(
328
+ executablePath,
329
+ [tool === "claude" ? "--version" : "--version"],
330
+ env
331
+ );
332
+ assertVersionOutput(tool, output, executablePath);
333
+ return output;
334
+ }
335
+ function versionCheckEnv(binDir) {
336
+ const env = { ...process.env };
337
+ for (const key of VERSION_CHECK_ENV_DENYLIST) {
338
+ delete env[key];
339
+ }
340
+ env.PATH = [binDir, process.env.PATH].filter(Boolean).join(path2.delimiter);
341
+ return env;
342
+ }
343
+ function inspectStaticExecutable(projectRoot, filePath, label, fileFormat, fileArch) {
344
+ assertExecutable(filePath, label);
345
+ return {
346
+ sha256: hashFile(filePath),
347
+ size: statSync(filePath).size,
348
+ fileOutput: getExecutableFileOutput(projectRoot, filePath, label, fileFormat, fileArch)
349
+ };
350
+ }
351
+ function assertManifestEntry(projectRoot, manifestEntries, runtimeKey, tool, executablePath, inspection) {
352
+ const entry = manifestEntries.find((candidate) => candidate.tool === tool);
353
+ if (!entry) {
354
+ throw new Error(`Agent CLI manifest is missing ${runtimeKey}/${tool}`);
355
+ }
356
+ const expectedPath = relativeFromProjectRoot(projectRoot, executablePath);
357
+ if (entry.path !== expectedPath) {
358
+ throw new Error(
359
+ `Agent CLI manifest path mismatch for ${runtimeKey}/${tool}: expected ${expectedPath}, found ${entry.path}`
360
+ );
361
+ }
362
+ if (entry.sha256 !== inspection.sha256) {
363
+ throw new Error(`Agent CLI manifest hash mismatch for ${runtimeKey}/${tool}`);
364
+ }
365
+ if (entry.size !== inspection.size) {
366
+ throw new Error(`Agent CLI manifest size mismatch for ${runtimeKey}/${tool}`);
367
+ }
368
+ if (entry.fileOutput !== inspection.fileOutput) {
369
+ throw new Error(`Agent CLI manifest file output mismatch for ${runtimeKey}/${tool}`);
370
+ }
371
+ }
372
+ function assertExecutable(filePath, label) {
373
+ if (!existsSync(filePath)) {
374
+ throw new Error(`Missing ${label}: ${filePath}`);
375
+ }
376
+ const stat = statSync(filePath);
377
+ if (!stat.isFile()) {
378
+ throw new Error(`Expected ${label} to be a regular file: ${filePath}`);
379
+ }
380
+ if ((stat.mode & 73) === 0) {
381
+ throw new Error(`Expected ${label} to be executable: ${filePath}`);
382
+ }
383
+ }
384
+ function getExecutableFileOutput(projectRoot, filePath, label, fileFormat, fileArch) {
385
+ const fileOutput = execFileSync("file", [relativeFromProjectRoot(projectRoot, filePath)], {
386
+ cwd: projectRoot,
387
+ encoding: "utf8",
388
+ timeout: VERIFY_TIMEOUT_MS,
389
+ stdio: ["ignore", "pipe", "pipe"]
390
+ }).trim();
391
+ const hasExpectedFormat = fileFormat === "Mach-O 64-bit executable" ? fileOutput.includes("Mach-O 64-bit") && fileOutput.includes("executable") : fileOutput.includes(fileFormat);
392
+ if (!hasExpectedFormat || !fileOutput.includes(fileArch)) {
393
+ throw new Error(`Unexpected ${label} architecture: ${fileOutput}`);
394
+ }
395
+ return fileOutput;
396
+ }
397
+ function validateStagedAgentClis(options = {}) {
398
+ const log = options.log ?? console.log;
399
+ const projectRoot = options.projectRoot ?? defaultProjectRoot;
400
+ const manifestPath = resolveAgentCliManifestPath(projectRoot);
401
+ if (!existsSync(manifestPath)) {
402
+ throw new Error(`Missing staged agent CLI manifest: ${manifestPath}`);
403
+ }
404
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
405
+ const runtimeKeys = options.runtimeKey ? [options.runtimeKey] : AGENT_CLI_TARGETS.map((target) => target.runtimeKey);
406
+ for (const runtimeKey of runtimeKeys) {
407
+ const target = AGENT_CLI_TARGETS.find((item) => item.runtimeKey === runtimeKey);
408
+ if (!target) throw new Error(`Unsupported agent CLI runtime key: ${runtimeKey}`);
409
+ const manifestEntries = manifest.targets.filter((entry) => entry.runtimeKey === runtimeKey);
410
+ const codexEntry = manifestEntries.find((entry) => entry.tool === "codex");
411
+ if (!codexEntry) {
412
+ throw new Error(`Agent CLI manifest is missing ${runtimeKey}/codex`);
413
+ }
414
+ assertCodexAppServerCompatible(codexEntry.source.version, `${runtimeKey}/codex`);
415
+ for (const tool of ["codex", "claude", "rg", "agent-browser"]) {
416
+ const executablePath = resolveStagedAgentCliPath(projectRoot, runtimeKey, tool);
417
+ const inspection = inspectStaticExecutable(
418
+ projectRoot,
419
+ executablePath,
420
+ `${runtimeKey}/${tool}`,
421
+ target.fileFormat,
422
+ target.fileArch
423
+ );
424
+ assertManifestEntry(
425
+ projectRoot,
426
+ manifestEntries,
427
+ runtimeKey,
428
+ tool,
429
+ executablePath,
430
+ inspection
431
+ );
432
+ }
433
+ if (manifestEntries.length !== 4) {
434
+ throw new Error(
435
+ `Agent CLI manifest expected 4 entries for ${runtimeKey}, found ${manifestEntries.length}`
436
+ );
437
+ }
438
+ if (options.verifyRunnable === true && shouldVerifyRuntimeKey(runtimeKey)) {
439
+ for (const tool of ["codex", "claude"]) {
440
+ const executablePath = resolveStagedAgentCliPath(projectRoot, runtimeKey, tool);
441
+ const version = verifyStagedAgentCliVersion(tool, executablePath);
442
+ log(`\u2713 ${runtimeKey}/${tool} ${version}`);
443
+ }
444
+ }
445
+ }
446
+ log(`\u2713 Staged agent CLIs ready (${runtimeKeys.join(", ")})`);
447
+ return manifest;
448
+ }
449
+
450
+ // ../../scripts/runtime/native-runtime.ts
451
+ import { execFileSync as execFileSync2, spawnSync as spawnSync2 } from "node:child_process";
452
+ import { createHash as createHash2 } from "node:crypto";
453
+ import {
454
+ chmodSync as chmodSync2,
455
+ existsSync as existsSync2,
456
+ mkdirSync as mkdirSync2,
457
+ readdirSync,
458
+ readFileSync as readFileSync2,
459
+ rmSync as rmSync2,
460
+ statSync as statSync2,
461
+ writeFileSync as writeFileSync2
462
+ } from "node:fs";
463
+ import path3 from "node:path";
464
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
465
+ var runtimeDir2 = path3.dirname(fileURLToPath2(import.meta.url));
466
+ var defaultProjectRoot2 = path3.resolve(runtimeDir2, "../..");
467
+ var VERIFY_TIMEOUT_MS2 = 2e4;
468
+ var VERIFY_STOP_TIMEOUT_MS = 5e3;
469
+ var MAC_CODESIGN_PAGE_SIZE = "4096";
470
+ var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([".cjs", ".js", ".json", ".mjs", ".ts", ".tsx"]);
471
+ var IGNORED_SOURCE_DIRS = /* @__PURE__ */ new Set([
472
+ ".git",
473
+ ".turbo",
474
+ "coverage",
475
+ "dist",
476
+ "node_modules",
477
+ "out",
478
+ "test",
479
+ "tests",
480
+ "__tests__"
481
+ ]);
482
+ var REQUIRED_RUNTIME_ENTITLEMENTS = [
483
+ "com.apple.security.cs.allow-jit",
484
+ "com.apple.security.cs.allow-unsigned-executable-memory",
485
+ "com.apple.security.cs.disable-library-validation"
486
+ ];
487
+ var VERSION_CHECK_ENV_DENYLIST2 = [
488
+ "AGENT_SERVER_CWD",
489
+ "AGENT_SERVER_ENTRY",
490
+ "AUTH_TOKEN",
491
+ "BUN_OPTIONS",
492
+ "DATABASE_PATH",
493
+ "DEUS_AUTH_TOKEN",
494
+ "DEUS_BACKEND_PORT",
495
+ "DEUS_BUNDLED_BIN_DIR",
496
+ "DEUS_DATA_DIR",
497
+ "DEUS_PACKAGED",
498
+ "DEUS_RESOURCES_PATH",
499
+ "DEUS_RUNTIME",
500
+ "DEUS_RUNTIME_COMMAND",
501
+ "DEUS_RUNTIME_EXECUTABLE",
502
+ "ELECTRON_RUN_AS_NODE",
503
+ "NODE_PATH",
504
+ "PORT"
505
+ ];
506
+ var DEUS_RUNTIME_TARGETS = [
507
+ {
508
+ runtimeKey: "darwin-arm64",
509
+ platform: "darwin",
510
+ bunTarget: "bun-darwin-arm64",
511
+ fileArch: "arm64"
512
+ },
513
+ {
514
+ runtimeKey: "darwin-x64",
515
+ platform: "darwin",
516
+ bunTarget: "bun-darwin-x64",
517
+ fileArch: "x86_64"
518
+ },
519
+ {
520
+ runtimeKey: "linux-x64",
521
+ platform: "linux",
522
+ bunTarget: "bun-linux-x64",
523
+ fileArch: "x86-64"
524
+ }
525
+ ];
526
+ function relativeFromProjectRoot2(projectRoot, targetPath) {
527
+ return path3.relative(projectRoot, targetPath).split(path3.sep).join("/");
528
+ }
529
+ function resolveDeusRuntimeManifestPath(projectRoot) {
530
+ return path3.join(resolveRuntimeStagePaths(projectRoot).electron.root, "bin", "deus-runtime.json");
531
+ }
532
+ function resolveStagedDeusRuntimePath(projectRoot, runtimeKey) {
533
+ return path3.join(
534
+ resolveRuntimeStagePaths(projectRoot).electron.root,
535
+ "bin",
536
+ runtimeKey,
537
+ "deus-runtime"
538
+ );
539
+ }
540
+ function hashFile2(filePath) {
541
+ return createHash2("sha256").update(readFileSync2(filePath)).digest("hex");
542
+ }
543
+ function getHostRuntimeKey() {
544
+ if (process.platform === "darwin" && (process.arch === "arm64" || process.arch === "x64")) {
545
+ return `darwin-${process.arch}`;
546
+ }
547
+ if (process.platform === "linux" && process.arch === "x64") {
548
+ return "linux-x64";
549
+ }
550
+ return null;
551
+ }
552
+ function shouldVerifyRuntimeKey2(runtimeKey) {
553
+ return getHostRuntimeKey() === runtimeKey;
554
+ }
555
+ function canInspectMacBinary(target) {
556
+ return target.platform === "darwin" && process.platform === "darwin";
557
+ }
558
+ function execOutput(command, args, cwd) {
559
+ return execFileSync2(command, args, {
560
+ cwd,
561
+ encoding: "utf8",
562
+ timeout: VERIFY_TIMEOUT_MS2,
563
+ stdio: ["ignore", "pipe", "pipe"]
564
+ }).trim();
565
+ }
566
+ function spawnErrorCode2(error2) {
567
+ return error2?.code ?? error2?.message ?? "none";
568
+ }
569
+ function diagnosticOutput2(command, args, cwd) {
570
+ const result = spawnSync2(command, args, {
571
+ cwd,
572
+ encoding: "utf8",
573
+ timeout: VERIFY_TIMEOUT_MS2,
574
+ stdio: ["ignore", "pipe", "pipe"]
575
+ });
576
+ const output = `${result.stdout || ""}${result.stderr || ""}`.trim();
577
+ if (result.error) {
578
+ return [spawnErrorCode2(result.error), output].filter(Boolean).join("\n");
579
+ }
580
+ if (result.status !== 0) return output || `${command} exited with status ${result.status}`;
581
+ return output;
582
+ }
583
+ function runtimeExecutableDiagnostics(executablePath) {
584
+ if (process.platform !== "darwin") return "";
585
+ const cwd = path3.dirname(executablePath);
586
+ return [
587
+ `file: ${diagnosticOutput2("file", [executablePath], cwd)}`,
588
+ `codesign: ${diagnosticOutput2("codesign", ["-dv", "--verbose=4", executablePath], cwd)}`,
589
+ `spctl: ${diagnosticOutput2("spctl", ["--assess", "--type", "execute", "--verbose=4", executablePath], cwd)}`,
590
+ `xattr: ${diagnosticOutput2("xattr", ["-l", executablePath], cwd) || "none"}`
591
+ ].join("\n");
592
+ }
593
+ function macExecutionPolicyHint2(diagnostics) {
594
+ if (process.platform !== "darwin") return "";
595
+ if (!/spctl:[\s\S]*rejected/.test(diagnostics)) return "";
596
+ if (!/com\.apple\.(provenance|quarantine)/.test(diagnostics)) return "";
597
+ return [
598
+ "",
599
+ "macOS rejected this executable before --version produced output.",
600
+ "Verify runnable staged runtime binaries on a notarized artifact or a macOS host that allows generated Mach-O binaries to launch."
601
+ ].join("\n");
602
+ }
603
+ function readPackageVersion(projectRoot) {
604
+ const packageJsonPath = path3.join(projectRoot, "package.json");
605
+ const packageJson = JSON.parse(readFileSync2(packageJsonPath, "utf8"));
606
+ if (typeof packageJson.version !== "string" || packageJson.version.length === 0) {
607
+ throw new Error(`package.json is missing a string version: ${packageJsonPath}`);
608
+ }
609
+ return packageJson.version;
610
+ }
611
+ function latestSourceMtime(projectRoot, sourceRelatives) {
612
+ let latest = { mtimeMs: 0, path: null };
613
+ function visit(sourcePath) {
614
+ if (!existsSync2(sourcePath)) return;
615
+ const stat = statSync2(sourcePath);
616
+ if (stat.isDirectory()) {
617
+ for (const entry of readdirSync(sourcePath, { withFileTypes: true })) {
618
+ if (IGNORED_SOURCE_DIRS.has(entry.name)) continue;
619
+ visit(path3.join(sourcePath, entry.name));
620
+ }
621
+ return;
622
+ }
623
+ if (!SOURCE_EXTENSIONS.has(path3.extname(sourcePath))) return;
624
+ if (stat.mtimeMs > latest.mtimeMs) {
625
+ latest = { mtimeMs: stat.mtimeMs, path: sourcePath };
626
+ }
627
+ }
628
+ for (const sourceRelative of sourceRelatives) {
629
+ visit(path3.join(projectRoot, sourceRelative));
630
+ }
631
+ return latest;
632
+ }
633
+ function assertRuntimeFresh(projectRoot, executablePath, runtimeKey) {
634
+ const latestSource = latestSourceMtime(projectRoot, [
635
+ "apps/runtime",
636
+ "apps/backend/src",
637
+ "apps/agent-server",
638
+ "shared",
639
+ "resources/entitlements.runtime.plist"
640
+ ]);
641
+ if (!latestSource.path) return;
642
+ if (statSync2(executablePath).mtimeMs >= latestSource.mtimeMs) return;
643
+ throw new Error(
644
+ `${runtimeKey}/deus-runtime is stale: ${relativeFromProjectRoot2(
645
+ projectRoot,
646
+ executablePath
647
+ )} is older than ${relativeFromProjectRoot2(projectRoot, latestSource.path)}. Run \`bun run build:runtime\` before packaging.`
648
+ );
649
+ }
650
+ function assertExecutable2(filePath, label) {
651
+ if (!existsSync2(filePath)) {
652
+ throw new Error(`Missing ${label}: ${filePath}`);
653
+ }
654
+ const stat = statSync2(filePath);
655
+ if (!stat.isFile()) {
656
+ throw new Error(`Expected ${label} to be a regular file: ${filePath}`);
657
+ }
658
+ if ((stat.mode & 73) === 0) {
659
+ throw new Error(`Expected ${label} to be executable: ${filePath}`);
660
+ }
661
+ }
662
+ function assertFileArch(fileOutput, target, filePath) {
663
+ const hasExpectedFormat = target.platform === "darwin" ? fileOutput.includes("Mach-O 64-bit") && fileOutput.includes("executable") : fileOutput.includes("ELF 64-bit");
664
+ if (!hasExpectedFormat || !fileOutput.includes(target.fileArch)) {
665
+ throw new Error(`Unexpected file(1) output for ${filePath}: ${fileOutput}`);
666
+ }
667
+ }
668
+ function verifyMacCodeSignature(filePath) {
669
+ if (process.platform !== "darwin") return;
670
+ const result = spawnSync2("codesign", ["--verify", "--verbose=2", filePath], {
671
+ encoding: "utf8",
672
+ stdio: ["ignore", "pipe", "pipe"]
673
+ });
674
+ if (result.status !== 0) {
675
+ throw new Error(`Invalid code signature for ${filePath}: ${result.stderr || result.stdout}`);
676
+ }
677
+ }
678
+ function verifyMacCodeSignaturePageSize(filePath) {
679
+ if (process.platform !== "darwin") return;
680
+ const result = spawnSync2("codesign", ["-dv", "--verbose=4", filePath], {
681
+ encoding: "utf8",
682
+ stdio: ["ignore", "pipe", "pipe"]
683
+ });
684
+ if (result.status !== 0) {
685
+ throw new Error(
686
+ `Unable to inspect code signature for ${filePath}: ${result.stderr || result.stdout}`
687
+ );
688
+ }
689
+ const output = `${result.stdout}
690
+ ${result.stderr}`;
691
+ if (!output.includes(`Page size=${MAC_CODESIGN_PAGE_SIZE}`)) {
692
+ throw new Error(
693
+ `Unexpected code signature page size for ${filePath}; expected ${MAC_CODESIGN_PAGE_SIZE}`
694
+ );
695
+ }
696
+ }
697
+ function readMacEntitlements(filePath) {
698
+ const result = spawnSync2("codesign", ["-d", "--entitlements", ":-", filePath], {
699
+ encoding: "utf8",
700
+ stdio: ["ignore", "pipe", "pipe"]
701
+ });
702
+ if (result.status !== 0) {
703
+ throw new Error(
704
+ `Unable to read entitlements for ${filePath}: ${result.stderr || result.stdout}`
705
+ );
706
+ }
707
+ return `${result.stdout}
708
+ ${result.stderr}`;
709
+ }
710
+ function verifyMacSystemDylibs(otoolOutput, filePath) {
711
+ if (process.platform !== "darwin") return;
712
+ const unexpected = otoolOutput.split(/\r?\n/).slice(1).map((line) => line.trim().split(/\s+/)[0]).filter(Boolean).filter(
713
+ (dependency) => !dependency.startsWith("/usr/lib/") && !dependency.startsWith("/System/Library/")
714
+ );
715
+ if (unexpected.length > 0) {
716
+ throw new Error(
717
+ `Unexpected non-system dylib dependency for ${filePath}: ${unexpected.join(", ")}`
718
+ );
719
+ }
720
+ }
721
+ function verifyMacRuntimeEntitlements(filePath) {
722
+ if (process.platform !== "darwin") return;
723
+ const entitlements = readMacEntitlements(filePath);
724
+ for (const entitlement of REQUIRED_RUNTIME_ENTITLEMENTS) {
725
+ if (!entitlements.includes(entitlement)) {
726
+ throw new Error(`Missing ${entitlement} entitlement for ${filePath}`);
727
+ }
728
+ }
729
+ }
730
+ function verifyStagedDeusRuntimeVersion(executablePath) {
731
+ const helperPath = path3.join(runtimeDir2, "run-version-check.cjs");
732
+ const env = { ...process.env };
733
+ for (const key of VERSION_CHECK_ENV_DENYLIST2) {
734
+ delete env[key];
735
+ }
736
+ env.DEUS_VERSION_CHECK_TIMEOUT_MS = String(VERIFY_TIMEOUT_MS2);
737
+ env.DEUS_VERSION_CHECK_STOP_TIMEOUT_MS = String(VERIFY_STOP_TIMEOUT_MS);
738
+ const result = spawnSync2(process.execPath, [helperPath, executablePath, "--version"], {
739
+ encoding: "utf8",
740
+ timeout: VERIFY_TIMEOUT_MS2 + VERIFY_STOP_TIMEOUT_MS + 5e3,
741
+ env,
742
+ stdio: ["ignore", "pipe", "pipe"]
743
+ });
744
+ const rawOutput = (result.stdout || "").trim();
745
+ let checkResult;
746
+ try {
747
+ checkResult = JSON.parse(rawOutput);
748
+ } catch {
749
+ checkResult = {
750
+ ok: false,
751
+ status: result.status,
752
+ signal: result.signal,
753
+ error: spawnErrorCode2(result.error),
754
+ stdout: rawOutput,
755
+ stderr: (result.stderr || "").trim()
756
+ };
757
+ }
758
+ const output = (checkResult.stdout || "").trim();
759
+ if (result.status !== 0) {
760
+ const stderr = [checkResult.stderr, result.stderr].filter(Boolean).join("\n").trim();
761
+ const diagnostics = runtimeExecutableDiagnostics(executablePath);
762
+ const hint2 = macExecutionPolicyHint2(diagnostics);
763
+ throw new Error(
764
+ `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 ? `
765
+ ${diagnostics}` : ""}${hint2}`
766
+ );
767
+ }
768
+ if (!/^deus-runtime \d+\.\d+\.\d+ /.test(output)) {
769
+ throw new Error(`Unexpected deus-runtime --version output for ${executablePath}: ${output}`);
770
+ }
771
+ return output;
772
+ }
773
+ function validateDeusRuntime(options = {}) {
774
+ const log = options.log ?? console.log;
775
+ const projectRoot = options.projectRoot ?? defaultProjectRoot2;
776
+ const manifestPath = resolveDeusRuntimeManifestPath(projectRoot);
777
+ if (!existsSync2(manifestPath)) {
778
+ throw new Error(`Missing native runtime manifest: ${manifestPath}`);
779
+ }
780
+ const manifest = JSON.parse(readFileSync2(manifestPath, "utf8"));
781
+ const packageVersion = readPackageVersion(projectRoot);
782
+ if (manifest.packageVersion !== packageVersion) {
783
+ throw new Error(
784
+ `Native runtime manifest package version mismatch: expected ${packageVersion}, found ${manifest.packageVersion ?? "missing"}. Run \`bun run build:runtime\` before packaging.`
785
+ );
786
+ }
787
+ const runtimeKeys = options.runtimeKey ? [options.runtimeKey] : DEUS_RUNTIME_TARGETS.map((target) => target.runtimeKey);
788
+ for (const runtimeKey of runtimeKeys) {
789
+ const target = DEUS_RUNTIME_TARGETS.find((item) => item.runtimeKey === runtimeKey);
790
+ if (!target) throw new Error(`Unsupported native runtime key: ${runtimeKey}`);
791
+ const executablePath = resolveStagedDeusRuntimePath(projectRoot, runtimeKey);
792
+ assertExecutable2(executablePath, `${runtimeKey}/deus-runtime`);
793
+ assertRuntimeFresh(projectRoot, executablePath, runtimeKey);
794
+ const manifestEntry = manifest.entries.find((entry) => entry.runtimeKey === runtimeKey);
795
+ if (!manifestEntry) throw new Error(`Native runtime manifest is missing ${runtimeKey}`);
796
+ const expectedPath = relativeFromProjectRoot2(projectRoot, executablePath);
797
+ if (manifestEntry.path !== expectedPath) {
798
+ throw new Error(
799
+ `Native runtime manifest path mismatch for ${runtimeKey}: expected ${expectedPath}, found ${manifestEntry.path}`
800
+ );
801
+ }
802
+ if (manifestEntry.sha256 !== hashFile2(executablePath)) {
803
+ throw new Error(`Native runtime manifest hash mismatch for ${runtimeKey}`);
804
+ }
805
+ const manifestCommandPath = relativeFromProjectRoot2(projectRoot, executablePath);
806
+ const fileOutput = execOutput("file", [manifestCommandPath], projectRoot);
807
+ assertFileArch(fileOutput, target, executablePath);
808
+ const otoolOutput = canInspectMacBinary(target) ? execOutput("otool", ["-L", manifestCommandPath], projectRoot) : void 0;
809
+ if (otoolOutput) verifyMacSystemDylibs(otoolOutput, executablePath);
810
+ if (manifestEntry.size !== statSync2(executablePath).size) {
811
+ throw new Error(`Native runtime manifest size mismatch for ${runtimeKey}`);
812
+ }
813
+ if (manifestEntry.fileOutput !== fileOutput) {
814
+ throw new Error(`Native runtime manifest file output mismatch for ${runtimeKey}`);
815
+ }
816
+ if (manifestEntry.otoolOutput !== otoolOutput) {
817
+ throw new Error(`Native runtime manifest otool output mismatch for ${runtimeKey}`);
818
+ }
819
+ if (canInspectMacBinary(target)) {
820
+ verifyMacCodeSignature(executablePath);
821
+ verifyMacCodeSignaturePageSize(executablePath);
822
+ verifyMacRuntimeEntitlements(executablePath);
823
+ }
824
+ if (options.verifyRunnable === true && shouldVerifyRuntimeKey2(runtimeKey)) {
825
+ const version = verifyStagedDeusRuntimeVersion(executablePath);
826
+ log(`\u2713 ${runtimeKey}/deus-runtime ${version}`);
827
+ }
828
+ }
829
+ log(`\u2713 Native runtime ready (${runtimeKeys.join(", ")})`);
830
+ return manifest;
831
+ }
832
+
833
+ // ../../scripts/runtime/validate.ts
834
+ var runtimeDir3 = path4.dirname(fileURLToPath3(import.meta.url));
835
+ var defaultProjectRoot3 = path4.resolve(runtimeDir3, "../..");
836
+ var BUILD_RUNTIME_COMMAND = "bun run build:runtime";
837
+ function relativeFromProjectRoot3(projectRoot, targetPath) {
838
+ return path4.relative(projectRoot, targetPath).split(path4.sep).join("/");
839
+ }
150
840
  function createBuildRuntimeError(message) {
151
841
  return new Error(`${message}
152
842
  Run \`${BUILD_RUNTIME_COMMAND}\` before packaging.`);
153
843
  }
154
844
  function readManifest(manifestPath) {
155
845
  try {
156
- return JSON.parse(readFileSync(manifestPath, "utf8"));
846
+ return JSON.parse(readFileSync3(manifestPath, "utf8"));
157
847
  } catch (error2) {
158
848
  throw createBuildRuntimeError(
159
849
  `Unable to read staged runtime manifest at ${manifestPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
160
850
  );
161
851
  }
162
852
  }
853
+ function hashFile3(filePath) {
854
+ return createHash3("sha256").update(readFileSync3(filePath)).digest("hex");
855
+ }
856
+ function ghArchiveName(version, archivePlatform, extension = "zip") {
857
+ return `gh_${version}_${archivePlatform}.${extension}`;
858
+ }
859
+ function readGhCliContract(projectRoot) {
860
+ const contractPath = path4.join(projectRoot, "scripts", "runtime", "gh-cli-contract.json");
861
+ try {
862
+ const contract = JSON.parse(readFileSync3(contractPath, "utf8"));
863
+ if (typeof contract.ghVersion !== "string" || !Array.isArray(contract.targets)) {
864
+ throw new Error("unexpected contract shape");
865
+ }
866
+ return contract;
867
+ } catch (error2) {
868
+ throw createBuildRuntimeError(
869
+ `Unable to read GitHub CLI contract at ${contractPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
870
+ );
871
+ }
872
+ }
163
873
  function assertExists(filePath, label) {
164
- if (!existsSync(filePath)) {
874
+ if (!existsSync3(filePath)) {
165
875
  throw createBuildRuntimeError(`Missing ${label}: ${filePath}`);
166
876
  }
167
877
  }
878
+ function assertExecutable3(filePath, label) {
879
+ assertExists(filePath, label);
880
+ const stat = statSync3(filePath);
881
+ if (!stat.isFile()) {
882
+ throw createBuildRuntimeError(`Expected ${label} to be a regular file: ${filePath}`);
883
+ }
884
+ if ((stat.mode & 73) === 0) {
885
+ throw createBuildRuntimeError(`Expected ${label} to be executable: ${filePath}`);
886
+ }
887
+ }
888
+ function getExecutableFileOutput2(projectRoot, filePath, label, fileFormat, fileArch) {
889
+ const fileOutput = execFileSync3("file", [relativeFromProjectRoot3(projectRoot, filePath)], {
890
+ cwd: projectRoot,
891
+ encoding: "utf8",
892
+ timeout: 2e4,
893
+ stdio: ["ignore", "pipe", "pipe"]
894
+ }).trim();
895
+ const hasExpectedFormat = fileFormat === "Mach-O 64-bit executable" ? fileOutput.includes("Mach-O 64-bit") && fileOutput.includes("executable") : fileOutput.includes(fileFormat);
896
+ if (!hasExpectedFormat || !fileOutput.includes(fileArch)) {
897
+ throw createBuildRuntimeError(`Unexpected ${label} architecture: ${fileOutput}`);
898
+ }
899
+ return fileOutput;
900
+ }
901
+ function verifyMacCodeSignature2(filePath, label) {
902
+ if (process.platform !== "darwin" || !label.startsWith("darwin-")) return;
903
+ try {
904
+ execFileSync3("codesign", ["--verify", "--verbose=2", filePath], {
905
+ encoding: "utf8",
906
+ timeout: 2e4,
907
+ stdio: ["ignore", "ignore", "pipe"]
908
+ });
909
+ } catch (error2) {
910
+ throw createBuildRuntimeError(
911
+ `Invalid ${label} code signature: ${error2 instanceof Error ? error2.message : String(error2)}`
912
+ );
913
+ }
914
+ }
915
+ function assertStagedGhCli(projectRoot) {
916
+ const binRoot = path4.join(resolveRuntimeStagePaths(projectRoot).electron.root, "bin");
917
+ const manifestPath = path4.join(binRoot, "gh-cli.json");
918
+ assertExists(manifestPath, "staged GitHub CLI manifest");
919
+ const manifest = JSON.parse(readFileSync3(manifestPath, "utf8"));
920
+ if (manifest.version !== 1 || !Array.isArray(manifest.targets)) {
921
+ throw createBuildRuntimeError(`Unexpected staged GitHub CLI manifest shape: ${manifestPath}`);
922
+ }
923
+ const contract = readGhCliContract(projectRoot);
924
+ if (manifest.ghVersion !== contract.ghVersion) {
925
+ throw createBuildRuntimeError(
926
+ `GitHub CLI manifest version mismatch: expected ${contract.ghVersion}, found ${manifest.ghVersion}`
927
+ );
928
+ }
929
+ for (const target of contract.targets) {
930
+ const ghPath = path4.join(binRoot, target.runtimeKey, "gh");
931
+ const label = `${target.runtimeKey}/gh`;
932
+ assertExecutable3(ghPath, label);
933
+ const fileOutput = getExecutableFileOutput2(
934
+ projectRoot,
935
+ ghPath,
936
+ label,
937
+ target.fileFormat ?? "Mach-O 64-bit executable",
938
+ target.fileArch
939
+ );
940
+ verifyMacCodeSignature2(ghPath, label);
941
+ const manifestEntry = manifest.targets.find(
942
+ (entry) => entry.runtimeKey === target.runtimeKey && entry.tool === "gh"
943
+ );
944
+ if (!manifestEntry) {
945
+ throw createBuildRuntimeError(`GitHub CLI manifest is missing ${target.runtimeKey}/gh`);
946
+ }
947
+ const expectedPath = relativeFromProjectRoot3(projectRoot, ghPath);
948
+ if (manifestEntry.path !== expectedPath) {
949
+ throw createBuildRuntimeError(
950
+ `GitHub CLI manifest path mismatch for ${target.runtimeKey}/gh: expected ${expectedPath}, found ${manifestEntry.path}`
951
+ );
952
+ }
953
+ if (manifestEntry.sha256 !== hashFile3(ghPath)) {
954
+ throw createBuildRuntimeError(`GitHub CLI manifest hash mismatch for ${target.runtimeKey}/gh`);
955
+ }
956
+ if (manifestEntry.size !== statSync3(ghPath).size) {
957
+ throw createBuildRuntimeError(`GitHub CLI manifest size mismatch for ${target.runtimeKey}/gh`);
958
+ }
959
+ if (manifestEntry.fileOutput !== fileOutput) {
960
+ throw createBuildRuntimeError(
961
+ `GitHub CLI manifest file output mismatch for ${target.runtimeKey}/gh`
962
+ );
963
+ }
964
+ const archiveName = ghArchiveName(
965
+ contract.ghVersion,
966
+ target.archivePlatform,
967
+ target.archiveExtension
968
+ );
969
+ const expectedUrl = `https://github.com/cli/cli/releases/download/v${contract.ghVersion}/${archiveName}`;
970
+ const source = manifestEntry.source;
971
+ if (!source || source.version !== contract.ghVersion || source.archiveName !== archiveName || source.archiveSha256 !== target.archiveSha256 || source.url !== expectedUrl) {
972
+ throw createBuildRuntimeError(
973
+ `GitHub CLI manifest source mismatch for ${target.runtimeKey}/gh`
974
+ );
975
+ }
976
+ }
977
+ }
978
+ function assertPackagedProviderBinaries(projectRoot) {
979
+ try {
980
+ validateDeusRuntime({
981
+ projectRoot,
982
+ log: () => void 0,
983
+ verifyRunnable: process.env.DEUS_VERIFY_RUNTIME_RUNNABLE === "1"
984
+ });
985
+ } catch (error2) {
986
+ throw createBuildRuntimeError(
987
+ `Native runtime validation failed: ${error2 instanceof Error ? error2.message : String(error2)}`
988
+ );
989
+ }
990
+ try {
991
+ validateStagedAgentClis({ projectRoot, log: () => void 0, verifyRunnable: false });
992
+ } catch (error2) {
993
+ throw createBuildRuntimeError(
994
+ `Staged agent CLI validation failed: ${error2 instanceof Error ? error2.message : String(error2)}`
995
+ );
996
+ }
997
+ assertStagedGhCli(projectRoot);
998
+ }
168
999
  function assertNotStale(projectRoot, filePath, label, sourcePath, sourceLabel) {
169
- if (statSync(filePath).mtimeMs < statSync(sourcePath).mtimeMs) {
1000
+ if (statSync3(filePath).mtimeMs < statSync3(sourcePath).mtimeMs) {
170
1001
  throw createBuildRuntimeError(
171
- `${label} is stale: ${relativeFromProjectRoot(projectRoot, filePath)} is older than ${relativeFromProjectRoot(projectRoot, sourcePath)} (${sourceLabel})`
1002
+ `${label} is stale: ${relativeFromProjectRoot3(projectRoot, filePath)} is older than ${relativeFromProjectRoot3(projectRoot, sourcePath)} (${sourceLabel})`
172
1003
  );
173
1004
  }
174
1005
  }
@@ -183,12 +1014,8 @@ function buildExpectedManifest(projectRoot) {
183
1014
  },
184
1015
  bundles: {
185
1016
  common: {
186
- backend: relativeFromProjectRoot(projectRoot, stagePaths.common.backendBundle),
187
- agentServer: relativeFromProjectRoot(projectRoot, stagePaths.common.agentServerBundle)
188
- },
189
- electron: {
190
- backend: relativeFromProjectRoot(projectRoot, stagePaths.electron.backendBundle),
191
- agentServer: relativeFromProjectRoot(projectRoot, stagePaths.electron.agentServerBundle)
1017
+ backend: relativeFromProjectRoot3(projectRoot, stagePaths.common.backendBundle),
1018
+ agentServer: relativeFromProjectRoot3(projectRoot, stagePaths.common.agentServerBundle)
192
1019
  }
193
1020
  },
194
1021
  nodeRuntimeDependencies: CLI_RUNTIME_DEPENDENCIES
@@ -196,19 +1023,17 @@ function buildExpectedManifest(projectRoot) {
196
1023
  }
197
1024
  function validateRuntimeStage(options = {}) {
198
1025
  const log = options.log ?? console.log;
199
- const projectRoot = options.projectRoot ?? defaultProjectRoot;
1026
+ const projectRoot = options.projectRoot ?? defaultProjectRoot3;
200
1027
  const stagePaths = resolveRuntimeStagePaths(projectRoot);
201
1028
  const sources = {
202
- backendBundle: path2.join(projectRoot, "apps", "backend", "dist", "server.bundled.cjs"),
203
- agentServerBundle: path2.join(projectRoot, "apps", "agent-server", "dist", "index.bundled.cjs")
1029
+ backendBundle: path4.join(projectRoot, "apps", "backend", "dist", "server.bundled.cjs"),
1030
+ agentServerBundle: path4.join(projectRoot, "apps", "agent-server", "dist", "index.bundled.cjs")
204
1031
  };
205
1032
  assertExists(sources.backendBundle, "runtime source bundle (backend)");
206
1033
  assertExists(sources.agentServerBundle, "runtime source bundle (agent-server)");
207
1034
  assertExists(stagePaths.manifest, "staged runtime manifest");
208
1035
  assertExists(stagePaths.common.backendBundle, "staged common backend bundle");
209
1036
  assertExists(stagePaths.common.agentServerBundle, "staged common agent-server bundle");
210
- assertExists(stagePaths.electron.backendBundle, "staged electron backend bundle");
211
- assertExists(stagePaths.electron.agentServerBundle, "staged electron agent-server bundle");
212
1037
  const manifest = readManifest(stagePaths.manifest);
213
1038
  const expectedManifest = buildExpectedManifest(projectRoot);
214
1039
  if (JSON.stringify(manifest) !== JSON.stringify(expectedManifest)) {
@@ -223,13 +1048,6 @@ function validateRuntimeStage(options = {}) {
223
1048
  sources.backendBundle,
224
1049
  "backend source bundle"
225
1050
  );
226
- assertNotStale(
227
- projectRoot,
228
- stagePaths.electron.backendBundle,
229
- "staged electron backend bundle",
230
- sources.backendBundle,
231
- "backend source bundle"
232
- );
233
1051
  assertNotStale(
234
1052
  projectRoot,
235
1053
  stagePaths.common.agentServerBundle,
@@ -237,29 +1055,23 @@ function validateRuntimeStage(options = {}) {
237
1055
  sources.agentServerBundle,
238
1056
  "agent-server source bundle"
239
1057
  );
240
- assertNotStale(
241
- projectRoot,
242
- stagePaths.electron.agentServerBundle,
243
- "staged electron agent-server bundle",
244
- sources.agentServerBundle,
245
- "agent-server source bundle"
1058
+ const latestSourceMtime2 = Math.max(
1059
+ statSync3(sources.backendBundle).mtimeMs,
1060
+ statSync3(sources.agentServerBundle).mtimeMs
246
1061
  );
247
- const latestSourceMtime = Math.max(
248
- statSync(sources.backendBundle).mtimeMs,
249
- statSync(sources.agentServerBundle).mtimeMs
250
- );
251
- if (statSync(stagePaths.manifest).mtimeMs < latestSourceMtime) {
1062
+ if (statSync3(stagePaths.manifest).mtimeMs < latestSourceMtime2) {
252
1063
  throw createBuildRuntimeError(
253
- `Staged runtime manifest is stale: ${relativeFromProjectRoot(projectRoot, stagePaths.manifest)} is older than the source bundles`
1064
+ `Staged runtime manifest is stale: ${relativeFromProjectRoot3(projectRoot, stagePaths.manifest)} is older than the source bundles`
254
1065
  );
255
1066
  }
1067
+ assertPackagedProviderBinaries(projectRoot);
256
1068
  log(
257
- `\u2713 Staged runtime ready for packaging (${relativeFromProjectRoot(projectRoot, stagePaths.root)})`
1069
+ `\u2713 Staged runtime ready for packaging (${relativeFromProjectRoot3(projectRoot, stagePaths.root)})`
258
1070
  );
259
1071
  return manifest;
260
1072
  }
261
- var entryPath = process.argv[1] ? path2.resolve(process.argv[1]) : null;
262
- if (entryPath === fileURLToPath(import.meta.url)) {
1073
+ var entryPath = process.argv[1] ? path4.resolve(process.argv[1]) : null;
1074
+ if (entryPath === fileURLToPath3(import.meta.url)) {
263
1075
  try {
264
1076
  validateRuntimeStage();
265
1077
  } catch (error2) {
@@ -314,7 +1126,7 @@ var sym = {
314
1126
  arrow: isUnicode ? "\u2192" : "->",
315
1127
  diamond: isUnicode ? "\u25C6" : "*",
316
1128
  pointer: isUnicode ? "\u276F" : ">",
317
- info: isUnicode ? "\u2139" : "i",
1129
+ info: "i",
318
1130
  warning: isUnicode ? "\u26A0" : "!",
319
1131
  bullet: isUnicode ? "\u2022" : "-",
320
1132
  // Box drawing
@@ -622,13 +1434,13 @@ function sleep(ms) {
622
1434
 
623
1435
  // src/config.ts
624
1436
  import {
625
- readFileSync as readFileSync2,
626
- writeFileSync,
627
- existsSync as existsSync2,
1437
+ readFileSync as readFileSync4,
1438
+ writeFileSync as writeFileSync3,
1439
+ existsSync as existsSync4,
628
1440
  unlinkSync,
629
1441
  renameSync,
630
- mkdirSync,
631
- chmodSync
1442
+ mkdirSync as mkdirSync3,
1443
+ chmodSync as chmodSync3
632
1444
  } from "node:fs";
633
1445
  import { join } from "node:path";
634
1446
  import { homedir, platform } from "node:os";
@@ -655,10 +1467,10 @@ function getServerInfoPath() {
655
1467
  return join(getConfigDir(), "server.json");
656
1468
  }
657
1469
  function loadConfig() {
658
- const path3 = getConfigPath();
659
- if (!existsSync2(path3)) return { ...DEFAULT_CONFIG };
1470
+ const path5 = getConfigPath();
1471
+ if (!existsSync4(path5)) return { ...DEFAULT_CONFIG };
660
1472
  try {
661
- const raw = readFileSync2(path3, "utf-8");
1473
+ const raw = readFileSync4(path5, "utf-8");
662
1474
  const parsed = JSON.parse(raw);
663
1475
  return { ...DEFAULT_CONFIG, ...parsed };
664
1476
  } catch {
@@ -667,19 +1479,19 @@ function loadConfig() {
667
1479
  }
668
1480
  function saveConfig(config) {
669
1481
  const dir = getConfigDir();
670
- mkdirSync(dir, { recursive: true });
671
- const path3 = getConfigPath();
672
- const tmp = path3 + ".tmp." + randomBytes(4).toString("hex");
1482
+ mkdirSync3(dir, { recursive: true });
1483
+ const path5 = getConfigPath();
1484
+ const tmp = path5 + ".tmp." + randomBytes(4).toString("hex");
673
1485
  try {
674
- writeFileSync(tmp, JSON.stringify(config, null, 2) + "\n", "utf-8");
675
- chmodSync(tmp, 384);
676
- renameSync(tmp, path3);
1486
+ writeFileSync3(tmp, JSON.stringify(config, null, 2) + "\n", "utf-8");
1487
+ chmodSync3(tmp, 384);
1488
+ renameSync(tmp, path5);
677
1489
  } catch {
678
1490
  try {
679
1491
  unlinkSync(tmp);
680
1492
  } catch {
681
1493
  }
682
- throw new Error(`Failed to save config to ${path3}`);
1494
+ throw new Error(`Failed to save config to ${path5}`);
683
1495
  }
684
1496
  }
685
1497
  function hasCompletedOnboarding() {
@@ -687,16 +1499,16 @@ function hasCompletedOnboarding() {
687
1499
  }
688
1500
  function writeServerInfo(info2) {
689
1501
  const dir = getConfigDir();
690
- mkdirSync(dir, { recursive: true });
691
- const path3 = getServerInfoPath();
692
- writeFileSync(path3, JSON.stringify(info2, null, 2) + "\n", "utf-8");
693
- chmodSync(path3, 384);
1502
+ mkdirSync3(dir, { recursive: true });
1503
+ const path5 = getServerInfoPath();
1504
+ writeFileSync3(path5, JSON.stringify(info2, null, 2) + "\n", "utf-8");
1505
+ chmodSync3(path5, 384);
694
1506
  }
695
1507
  function readServerInfo() {
696
- const path3 = getServerInfoPath();
697
- if (!existsSync2(path3)) return null;
1508
+ const path5 = getServerInfoPath();
1509
+ if (!existsSync4(path5)) return null;
698
1510
  try {
699
- const raw = readFileSync2(path3, "utf-8");
1511
+ const raw = readFileSync4(path5, "utf-8");
700
1512
  const info2 = JSON.parse(raw);
701
1513
  try {
702
1514
  process.kill(info2.pid, 0);
@@ -710,16 +1522,16 @@ function readServerInfo() {
710
1522
  }
711
1523
  }
712
1524
  function clearServerInfo() {
713
- const path3 = getServerInfoPath();
1525
+ const path5 = getServerInfoPath();
714
1526
  try {
715
- unlinkSync(path3);
1527
+ unlinkSync(path5);
716
1528
  } catch {
717
1529
  }
718
1530
  }
719
1531
 
720
1532
  // src/login.ts
721
- import { execSync, spawnSync } from "node:child_process";
722
- import { existsSync as existsSync3 } from "node:fs";
1533
+ import { execSync, spawnSync as spawnSync3 } from "node:child_process";
1534
+ import { existsSync as existsSync5 } from "node:fs";
723
1535
  import { join as join2 } from "node:path";
724
1536
  import { homedir as homedir2, platform as platform2 } from "node:os";
725
1537
 
@@ -934,7 +1746,7 @@ function getClaudeCliCandidates() {
934
1746
  }
935
1747
  function detectClaudeCli() {
936
1748
  for (const candidate of getClaudeCliCandidates()) {
937
- if (existsSync3(candidate)) {
1749
+ if (existsSync5(candidate)) {
938
1750
  try {
939
1751
  const version = execSync(`node "${candidate}" --version`, {
940
1752
  encoding: "utf-8",
@@ -978,7 +1790,7 @@ function isClaudeAuthenticated() {
978
1790
  join2(homedir2(), ".claude", "credentials.json")
979
1791
  ];
980
1792
  for (const p of credPaths) {
981
- if (existsSync3(p)) return true;
1793
+ if (existsSync5(p)) return true;
982
1794
  }
983
1795
  return false;
984
1796
  }
@@ -1062,7 +1874,7 @@ async function runClaudeLogin(cliPath) {
1062
1874
  blank();
1063
1875
  hint("Opening browser for authentication...");
1064
1876
  blank();
1065
- const result = spawnSync(cliPath, ["login"], {
1877
+ const result = spawnSync3(cliPath, ["login"], {
1066
1878
  stdio: "inherit",
1067
1879
  timeout: 12e4
1068
1880
  });
@@ -1082,7 +1894,7 @@ async function runClaudeLogin(cliPath) {
1082
1894
  async function installAndLogin() {
1083
1895
  blank();
1084
1896
  const s = spinner("Installing Claude Code CLI...");
1085
- const result = spawnSync("npm", ["install", "-g", "@anthropic-ai/claude-code"], {
1897
+ const result = spawnSync3("npm", ["install", "-g", "@anthropic-ai/claude-code"], {
1086
1898
  stdio: ["pipe", "pipe", "pipe"],
1087
1899
  timeout: 12e4
1088
1900
  });
@@ -1552,10 +2364,10 @@ function printQR(data, indent = 4) {
1552
2364
 
1553
2365
  // src/lib/http.ts
1554
2366
  import { request } from "node:http";
1555
- function httpGet(port, path3, timeoutMs = 3e3) {
2367
+ function httpGet(port, path5, timeoutMs = 3e3) {
1556
2368
  return new Promise((resolve2) => {
1557
2369
  const req = request(
1558
- { hostname: "localhost", port, path: path3, method: "GET", timeout: timeoutMs },
2370
+ { hostname: "localhost", port, path: path5, method: "GET", timeout: timeoutMs },
1559
2371
  (res) => {
1560
2372
  let body = "";
1561
2373
  res.on("data", (chunk) => body += chunk.toString());
@@ -1576,14 +2388,14 @@ function httpGet(port, path3, timeoutMs = 3e3) {
1576
2388
  req.end();
1577
2389
  });
1578
2390
  }
1579
- function httpPost(port, path3, body) {
2391
+ function httpPost(port, path5, body) {
1580
2392
  return new Promise((resolve2, reject) => {
1581
2393
  const payload = body ? JSON.stringify(body) : "";
1582
2394
  const req = request(
1583
2395
  {
1584
2396
  hostname: "localhost",
1585
2397
  port,
1586
- path: path3,
2398
+ path: path5,
1587
2399
  method: "POST",
1588
2400
  headers: {
1589
2401
  "Content-Type": "application/json",
@@ -1596,13 +2408,13 @@ function httpPost(port, path3, body) {
1596
2408
  res.on("data", (chunk) => data += chunk.toString());
1597
2409
  res.on("end", () => {
1598
2410
  if (res.statusCode !== 200) {
1599
- reject(new Error(`${path3} returned ${res.statusCode}: ${data}`));
2411
+ reject(new Error(`${path5} returned ${res.statusCode}: ${data}`));
1600
2412
  return;
1601
2413
  }
1602
2414
  try {
1603
2415
  resolve2(JSON.parse(data));
1604
2416
  } catch {
1605
- reject(new Error(`Invalid JSON from ${path3}`));
2417
+ reject(new Error(`Invalid JSON from ${path5}`));
1606
2418
  }
1607
2419
  });
1608
2420
  }
@@ -1610,7 +2422,7 @@ function httpPost(port, path3, body) {
1610
2422
  req.on("error", reject);
1611
2423
  req.on("timeout", () => {
1612
2424
  req.destroy();
1613
- reject(new Error(`Timeout: ${path3}`));
2425
+ reject(new Error(`Timeout: ${path5}`));
1614
2426
  });
1615
2427
  req.end(payload);
1616
2428
  });
@@ -1707,7 +2519,7 @@ async function pair() {
1707
2519
  }
1708
2520
 
1709
2521
  // src/start.ts
1710
- var __filename = fileURLToPath2(import.meta.url);
2522
+ var __filename = fileURLToPath4(import.meta.url);
1711
2523
  var __dirname = dirname(__filename);
1712
2524
  async function start(options) {
1713
2525
  const { dataDir } = options;
@@ -1728,7 +2540,7 @@ async function start(options) {
1728
2540
  const dbPath = resolveDataDir(dataDir);
1729
2541
  kv("Database", c.dim(dbPath));
1730
2542
  blank();
1731
- const children = [];
2543
+ let backendProcess = null;
1732
2544
  let status = null;
1733
2545
  let shuttingDown = false;
1734
2546
  let exitCode = 0;
@@ -1740,26 +2552,8 @@ async function start(options) {
1740
2552
  blank();
1741
2553
  const msg = gradientText("Shutting down...", [167, 139, 250], [34, 211, 238]);
1742
2554
  console.log(` ${msg}`);
1743
- const exitPromises = [];
1744
- for (const child of children) {
1745
- if (child.process.exitCode === null && child.process.signalCode === null) {
1746
- exitPromises.push(
1747
- new Promise((resolve2) => {
1748
- child.process.once("exit", resolve2);
1749
- child.process.kill("SIGTERM");
1750
- })
1751
- );
1752
- }
1753
- }
1754
- const drainTimeout = setTimeout(() => {
1755
- for (const child of children) {
1756
- if (child.process.exitCode === null && child.process.signalCode === null) {
1757
- child.process.kill("SIGKILL");
1758
- }
1759
- }
1760
- }, 5e3);
1761
- Promise.all(exitPromises).finally(() => {
1762
- clearTimeout(drainTimeout);
2555
+ stopBackendProcess(backendProcess).finally(() => {
2556
+ backendProcess = null;
1763
2557
  clearServerInfo();
1764
2558
  blank();
1765
2559
  const bye = gradientText("Thanks for using Deus!", [167, 139, 250], [34, 211, 238]);
@@ -1774,46 +2568,38 @@ async function start(options) {
1774
2568
  if (config.auth_method === "api_key" && config.anthropic_api_key) {
1775
2569
  extraEnv.ANTHROPIC_API_KEY = config.anthropic_api_key;
1776
2570
  }
1777
- const s1 = spinner("Starting agent server...");
1778
- const agentServerUrl = await startProcess({
1779
- name: "agent-server",
1780
- command: nodeCmd,
1781
- args: [paths.agentServer],
1782
- env: { DATABASE_PATH: dbPath, ...extraEnv },
1783
- waitFor: /LISTEN_URL=(.+)/,
1784
- children
1785
- });
1786
- if (!agentServerUrl) {
1787
- s1.fail("Agent server failed to start");
1788
- shutdown(1);
1789
- return;
1790
- }
1791
- s1.succeed(`Agent server ${c.dim("ready")}`);
1792
- const s2 = spinner("Starting backend...");
1793
- const backendPort = await startProcess({
1794
- name: "backend",
2571
+ const s1 = spinner("Starting backend...");
2572
+ const started = await startBackendProcess({
1795
2573
  command: nodeCmd,
1796
- args: [paths.backend],
2574
+ backendEntry: paths.backend,
2575
+ backendCwd: dirname(paths.backend),
2576
+ forceElectronRunAsNode: nodeCmd !== process.execPath,
1797
2577
  env: {
1798
- AGENT_SERVER_URL: agentServerUrl,
1799
2578
  DATABASE_PATH: dbPath,
2579
+ AGENT_SERVER_ENTRY: paths.agentServer,
2580
+ AGENT_SERVER_CWD: dirname(paths.agentServer),
1800
2581
  PORT: "0",
1801
2582
  ...extraEnv
1802
2583
  },
1803
- waitFor: /\[BACKEND_PORT\](\d+)/,
1804
- children
2584
+ onUnexpectedExit: (code, signal) => {
2585
+ if (shuttingDown) return;
2586
+ blank();
2587
+ warn(`backend exited unexpectedly${signal ? ` (${signal})` : code ? ` (code ${code})` : ""}`);
2588
+ shutdown(1);
2589
+ }
1805
2590
  });
1806
- if (!backendPort) {
1807
- s2.fail("Backend failed to start");
2591
+ if (!started) {
2592
+ s1.fail("Runtime failed to start");
1808
2593
  shutdown(1);
1809
2594
  return;
1810
2595
  }
1811
- s2.succeed(`Backend ${c.dim("ready")}`);
1812
- const port = parseInt(backendPort, 10);
2596
+ backendProcess = started.process;
2597
+ s1.succeed(`Runtime ${c.dim("ready")}`);
2598
+ const port = started.backendPort;
1813
2599
  writeServerInfo({
1814
2600
  pid: process.pid,
1815
2601
  backendPort: port,
1816
- agentServerUrl,
2602
+ agentServerUrl: "managed-by-backend",
1817
2603
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
1818
2604
  });
1819
2605
  blank();
@@ -1847,24 +2633,13 @@ async function start(options) {
1847
2633
  const elapsed = formatUptime(Date.now() - startedAt.getTime());
1848
2634
  return `${c.dim(`Running for ${elapsed}`)} ${c.dim(`${sym.bullet} Ctrl+C to stop`)}`;
1849
2635
  }, 2e3);
1850
- for (const child of children) {
1851
- child.process.on("exit", (code, signal) => {
1852
- if (!shuttingDown) {
1853
- blank();
1854
- warn(
1855
- `${child.name} exited unexpectedly${signal ? ` (${signal})` : code ? ` (code ${code})` : ""}`
1856
- );
1857
- shutdown(1);
1858
- }
1859
- });
1860
- }
1861
2636
  await new Promise(() => {
1862
2637
  });
1863
2638
  }
1864
2639
  function resolveBundlePaths() {
1865
2640
  const cliRoot = resolve(__dirname, "..");
1866
2641
  const bundledDir = join3(cliRoot, "bundles");
1867
- if (existsSync4(join3(bundledDir, "agent-server.bundled.cjs"))) {
2642
+ if (existsSync6(join3(bundledDir, "agent-server.bundled.cjs"))) {
1868
2643
  return {
1869
2644
  agentServer: join3(bundledDir, "agent-server.bundled.cjs"),
1870
2645
  backend: join3(bundledDir, "server.bundled.cjs")
@@ -1893,7 +2668,7 @@ function resolveDataDir(customDir) {
1893
2668
  appData: process.env.APPDATA,
1894
2669
  xdgDataHome: process.env.XDG_DATA_HOME
1895
2670
  });
1896
- mkdirSync2(dir, { recursive: true });
2671
+ mkdirSync4(dir, { recursive: true });
1897
2672
  return join3(dir, DEUS_DB_FILENAME);
1898
2673
  }
1899
2674
  function resolveNodeBinary() {
@@ -1903,7 +2678,7 @@ function resolveNodeBinary() {
1903
2678
  `node -e "try { console.log(require('electron')) } catch { process.exit(1) }"`,
1904
2679
  { encoding: "utf-8", timeout: 5e3, stdio: ["pipe", "pipe", "pipe"] }
1905
2680
  ).trim();
1906
- if (electronPath && existsSync4(electronPath)) {
2681
+ if (electronPath && existsSync6(electronPath)) {
1907
2682
  try {
1908
2683
  execSync2(
1909
2684
  `node -e "const D = require('better-sqlite3'); const d = new D(':memory:'); d.close()"`,
@@ -1918,18 +2693,18 @@ function resolveNodeBinary() {
1918
2693
  }
1919
2694
  return process.execPath;
1920
2695
  }
1921
- async function startProcess(opts) {
1922
- const { name, command, args, env, waitFor, children, timeoutMs = 15e3 } = opts;
2696
+ async function startBackendProcess(opts) {
2697
+ const { command, backendEntry, backendCwd, env, forceElectronRunAsNode, onUnexpectedExit } = opts;
1923
2698
  return new Promise((resolve2) => {
1924
- const processEnv = {};
1925
- if (command !== process.execPath && command.includes("Electron")) {
1926
- processEnv.ELECTRON_RUN_AS_NODE = "1";
1927
- }
1928
- const child = spawn(command, args, {
2699
+ const child = spawn2(command, [backendEntry], {
2700
+ cwd: backendCwd,
1929
2701
  stdio: ["ignore", "pipe", "pipe"],
1930
- env: { ...process.env, ...processEnv, ...env }
2702
+ env: {
2703
+ ...process.env,
2704
+ ...forceElectronRunAsNode ? { ELECTRON_RUN_AS_NODE: "1" } : {},
2705
+ ...env
2706
+ }
1931
2707
  });
1932
- children.push({ process: child, name });
1933
2708
  let buffer = "";
1934
2709
  let resolved = false;
1935
2710
  const timeout = setTimeout(() => {
@@ -1938,50 +2713,70 @@ async function startProcess(opts) {
1938
2713
  child.kill("SIGTERM");
1939
2714
  resolve2(null);
1940
2715
  }
1941
- }, timeoutMs);
1942
- function onStdout(data) {
2716
+ }, 3e4);
2717
+ child.stdout?.on("data", (data) => {
2718
+ process.stdout.write(data);
1943
2719
  buffer += data.toString();
1944
- const match = buffer.match(waitFor);
2720
+ const match = buffer.match(/^\[BACKEND_PORT\](\d+)$/m);
1945
2721
  if (match && !resolved) {
1946
2722
  resolved = true;
1947
2723
  clearTimeout(timeout);
1948
- child.stdout?.removeListener("data", onStdout);
1949
- buffer = "";
1950
- resolve2(match[1]);
2724
+ resolve2({ process: child, backendPort: parseInt(match[1], 10) });
1951
2725
  }
1952
- }
1953
- child.stdout?.on("data", onStdout);
1954
- child.on("exit", () => {
2726
+ });
2727
+ child.stderr?.on("data", (data) => process.stderr.write(data));
2728
+ child.on("exit", (code, signal) => {
1955
2729
  if (!resolved) {
1956
2730
  resolved = true;
1957
2731
  clearTimeout(timeout);
1958
2732
  resolve2(null);
2733
+ return;
1959
2734
  }
2735
+ onUnexpectedExit(code, signal);
1960
2736
  });
1961
2737
  });
1962
2738
  }
2739
+ function stopBackendProcess(child) {
2740
+ if (!child || child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
2741
+ return new Promise((resolve2) => {
2742
+ let finished = false;
2743
+ const finish = () => {
2744
+ if (finished) return;
2745
+ finished = true;
2746
+ clearTimeout(forceTimer);
2747
+ resolve2();
2748
+ };
2749
+ child.once("exit", finish);
2750
+ child.kill("SIGTERM");
2751
+ const forceTimer = setTimeout(() => {
2752
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
2753
+ }, 5e3);
2754
+ });
2755
+ }
1963
2756
 
1964
2757
  // src/desktop.ts
1965
- import { execSync as execSync3, spawn as spawn2 } from "node:child_process";
1966
- import { createWriteStream, existsSync as existsSync5, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2 } from "node:fs";
2758
+ import { execFileSync as execFileSync4, execSync as execSync3, spawn as spawn3 } from "node:child_process";
2759
+ import {
2760
+ chmodSync as chmodSync4,
2761
+ copyFileSync,
2762
+ createWriteStream,
2763
+ existsSync as existsSync7,
2764
+ mkdirSync as mkdirSync5,
2765
+ unlinkSync as unlinkSync2
2766
+ } from "node:fs";
1967
2767
  import { join as join4 } from "node:path";
1968
2768
  import { tmpdir, platform as platform3, arch, homedir as homedir4 } from "node:os";
1969
2769
  import { get } from "node:https";
1970
2770
  var GITHUB_REPO = "zvadaadam/deus-machine";
1971
2771
  var INSTALL_PATHS = {
1972
2772
  darwin: ["/Applications/Deus.app", `${homedir4()}/Applications/Deus.app`],
1973
- win32: [
1974
- `${process.env.LOCALAPPDATA || ""}\\Programs\\Deus\\Deus.exe`,
1975
- `${process.env.PROGRAMFILES || ""}\\Deus\\Deus.exe`
1976
- ],
1977
2773
  linux: [`${homedir4()}/.local/bin/Deus.AppImage`, "/usr/local/bin/Deus.AppImage"]
1978
2774
  };
1979
2775
  function hasDisplay() {
1980
2776
  const os = platform3();
1981
- if (process.env.CI || process.env.DOCKER || existsSync5("/.dockerenv")) return false;
2777
+ if (process.env.CI || process.env.DOCKER || existsSync7("/.dockerenv")) return false;
1982
2778
  if (process.env.SSH_CONNECTION || process.env.SSH_TTY) return false;
1983
2779
  if (os === "darwin") return true;
1984
- if (os === "win32") return true;
1985
2780
  if (os === "linux") return !!(process.env.DISPLAY || process.env.WAYLAND_DISPLAY);
1986
2781
  return false;
1987
2782
  }
@@ -1989,7 +2784,7 @@ function findInstalledApp() {
1989
2784
  const os = platform3();
1990
2785
  const paths = INSTALL_PATHS[os] || [];
1991
2786
  for (const p of paths) {
1992
- if (p && existsSync5(p)) return p;
2787
+ if (p && existsSync7(p)) return p;
1993
2788
  }
1994
2789
  return null;
1995
2790
  }
@@ -1997,18 +2792,43 @@ function launchDesktop(appPath) {
1997
2792
  const os = platform3();
1998
2793
  switch (os) {
1999
2794
  case "darwin":
2000
- spawn2("open", [appPath], { detached: true, stdio: "ignore" }).unref();
2795
+ spawn3("open", [appPath], { detached: true, stdio: "ignore" }).unref();
2001
2796
  break;
2002
- case "win32":
2003
2797
  case "linux":
2004
- spawn2(appPath, [], { detached: true, stdio: "ignore" }).unref();
2798
+ spawn3(appPath, [], {
2799
+ detached: true,
2800
+ stdio: "ignore",
2801
+ env: {
2802
+ ...process.env,
2803
+ ...hasFuse2() ? {} : { APPIMAGE_EXTRACT_AND_RUN: "1" }
2804
+ }
2805
+ }).unref();
2005
2806
  break;
2006
2807
  }
2007
2808
  }
2809
+ function hasFuse2() {
2810
+ const commonLibPaths = [
2811
+ "/lib/x86_64-linux-gnu/libfuse.so.2",
2812
+ "/usr/lib/x86_64-linux-gnu/libfuse.so.2",
2813
+ "/lib/aarch64-linux-gnu/libfuse.so.2",
2814
+ "/usr/lib/aarch64-linux-gnu/libfuse.so.2",
2815
+ "/usr/lib64/libfuse.so.2",
2816
+ "/usr/lib/libfuse.so.2"
2817
+ ];
2818
+ if (commonLibPaths.some((libPath) => existsSync7(libPath))) return true;
2819
+ try {
2820
+ return execSync3("ldconfig -p", { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }).split("\n").some((line) => line.includes("libfuse.so.2"));
2821
+ } catch {
2822
+ return false;
2823
+ }
2824
+ }
2825
+ function isOnPath(dir) {
2826
+ return (process.env.PATH ?? "").split(":").filter(Boolean).includes(dir);
2827
+ }
2008
2828
  function replaceInstalledMacApp(appPath, destPath) {
2009
2829
  const stagedPath = `${destPath}.staged`;
2010
2830
  const backupPath = `${destPath}.backup`;
2011
- const hadExistingInstall = existsSync5(destPath);
2831
+ const hadExistingInstall = existsSync7(destPath);
2012
2832
  execSync3(`rm -rf "${stagedPath}" "${backupPath}"`, { stdio: "pipe" });
2013
2833
  execSync3(`ditto "${appPath}" "${stagedPath}"`, { stdio: "pipe" });
2014
2834
  if (hadExistingInstall) {
@@ -2021,7 +2841,7 @@ function replaceInstalledMacApp(appPath, destPath) {
2021
2841
  }
2022
2842
  } catch (error2) {
2023
2843
  execSync3(`rm -rf "${stagedPath}"`, { stdio: "pipe" });
2024
- if (hadExistingInstall && existsSync5(backupPath) && !existsSync5(destPath)) {
2844
+ if (hadExistingInstall && existsSync7(backupPath) && !existsSync7(destPath)) {
2025
2845
  execSync3(`mv "${backupPath}" "${destPath}"`, { stdio: "pipe" });
2026
2846
  }
2027
2847
  throw error2;
@@ -2035,7 +2855,7 @@ async function installDesktop(options) {
2035
2855
  if (!assetPattern) {
2036
2856
  error(`Unsupported platform: ${os} ${cpuArch}`);
2037
2857
  blank();
2038
- hint("Supported: macOS (arm64/x64), Windows (x64), Linux (x64)");
2858
+ hint("Supported: macOS (arm64/x64), Linux (x64)");
2039
2859
  hint(`Or run ${c.cyan("deus start")} to run as a headless server.`);
2040
2860
  blank();
2041
2861
  process.exit(1);
@@ -2067,17 +2887,26 @@ async function installDesktop(options) {
2067
2887
  process.exit(1);
2068
2888
  }
2069
2889
  const downloadDir = join4(tmpdir(), "deus-installer");
2070
- mkdirSync3(downloadDir, { recursive: true });
2890
+ mkdirSync5(downloadDir, { recursive: true });
2071
2891
  const downloadPath = join4(downloadDir, asset.name);
2072
2892
  await downloadFile(asset.browser_download_url, downloadPath);
2073
2893
  const s3 = spinner("Installing...");
2074
- const installed = await installForPlatform(os, downloadPath, s3);
2894
+ const installedPath = await installForPlatform(os, downloadPath, s3);
2075
2895
  try {
2076
2896
  unlinkSync2(downloadPath);
2077
2897
  } catch {
2078
2898
  }
2079
- if (installed) {
2899
+ if (installedPath) {
2080
2900
  blank();
2901
+ success("Launching Deus...");
2902
+ if (os === "linux") {
2903
+ const installDir = join4(homedir4(), ".local", "bin");
2904
+ if (!isOnPath(installDir)) {
2905
+ info(
2906
+ hasFuse2() ? `Add ${c.dim(installDir)} to PATH to launch the AppImage directly.` : `Add ${c.dim(installDir)} to PATH. Until libfuse2 is installed, launch it with ${c.dim("APPIMAGE_EXTRACT_AND_RUN=1 Deus.AppImage")} or create a wrapper script.`
2907
+ );
2908
+ }
2909
+ }
2081
2910
  success("Deus is ready!");
2082
2911
  blank();
2083
2912
  }
@@ -2091,11 +2920,6 @@ function getAssetPattern(os, cpuArch) {
2091
2920
  description: `macOS DMG (${archSuffix})`
2092
2921
  };
2093
2922
  }
2094
- case "win32":
2095
- return {
2096
- matcher: (name) => name.endsWith(".exe") && !name.includes("blockmap"),
2097
- description: "Windows installer (exe)"
2098
- };
2099
2923
  case "linux":
2100
2924
  return {
2101
2925
  matcher: (name) => name.endsWith(".AppImage"),
@@ -2213,24 +3037,25 @@ async function installForPlatform(os, filePath, s) {
2213
3037
  mountPoint = mountOutput.split("\n").filter((line) => line.includes("/Volumes/")).map((line) => line.trim().split(" ").pop()?.trim()).find(Boolean);
2214
3038
  if (!mountPoint) {
2215
3039
  s.fail("Could not mount disk image");
2216
- return false;
3040
+ return null;
2217
3041
  }
2218
3042
  const appName = "Deus.app";
2219
3043
  const appPath = `${mountPoint}/${appName}`;
2220
3044
  const destPath = `/Applications/${appName}`;
2221
- if (existsSync5(appPath)) {
3045
+ if (existsSync7(appPath)) {
2222
3046
  replaceInstalledMacApp(appPath, destPath);
2223
3047
  s.succeed(`Installed to ${c.dim("/Applications/Deus.app")}`);
2224
3048
  launchDesktop(destPath);
3049
+ return destPath;
2225
3050
  } else {
2226
3051
  s.warn("DMG mounted \u2014 drag Deus to Applications to finish");
2227
3052
  }
2228
- return true;
3053
+ return null;
2229
3054
  } catch {
2230
3055
  s.fail("Auto-install failed \u2014 opening DMG manually");
2231
- execSync3(`open "${filePath}"`);
3056
+ execFileSync4("open", [filePath], { stdio: "ignore" });
2232
3057
  hint("Drag Deus.app to Applications, then launch it from Applications.");
2233
- return false;
3058
+ return null;
2234
3059
  } finally {
2235
3060
  if (mountPoint) {
2236
3061
  try {
@@ -2240,30 +3065,27 @@ async function installForPlatform(os, filePath, s) {
2240
3065
  }
2241
3066
  }
2242
3067
  }
2243
- case "win32": {
2244
- s.succeed("Launching installer...");
2245
- spawn2(filePath, [], { detached: true, stdio: "ignore" }).unref();
2246
- hint("Follow the on-screen instructions to complete installation.");
2247
- return true;
2248
- }
2249
3068
  case "linux": {
2250
3069
  try {
2251
- execSync3(`chmod +x "${filePath}"`);
2252
3070
  const installDir = join4(homedir4(), ".local", "bin");
2253
- mkdirSync3(installDir, { recursive: true });
3071
+ mkdirSync5(installDir, { recursive: true });
2254
3072
  const destPath = join4(installDir, "Deus.AppImage");
2255
- execSync3(`cp "${filePath}" "${destPath}"`);
3073
+ copyFileSync(filePath, destPath);
3074
+ chmodSync4(destPath, 493);
2256
3075
  s.succeed(`Installed to ${c.dim(destPath)}`);
3076
+ if (!hasFuse2()) {
3077
+ info("libfuse2 not found; launching AppImage with APPIMAGE_EXTRACT_AND_RUN=1.");
3078
+ }
2257
3079
  launchDesktop(destPath);
2258
- return true;
3080
+ return destPath;
2259
3081
  } catch {
2260
3082
  s.fail("Installation failed \u2014 check permissions");
2261
- return false;
3083
+ return null;
2262
3084
  }
2263
3085
  }
2264
3086
  default:
2265
3087
  s.fail("Unsupported platform");
2266
- return false;
3088
+ return null;
2267
3089
  }
2268
3090
  }
2269
3091
 
@@ -2336,6 +3158,19 @@ async function showStatus() {
2336
3158
  blank();
2337
3159
  }
2338
3160
 
3161
+ // src/args.ts
3162
+ function getCliCommandIndex(args) {
3163
+ return args.findIndex((arg) => !arg.startsWith("-"));
3164
+ }
3165
+ function getCliCommand(args) {
3166
+ const commandIndex = getCliCommandIndex(args);
3167
+ return commandIndex === -1 ? null : args[commandIndex];
3168
+ }
3169
+ function isGlobalVersionRequest(args) {
3170
+ if (getCliCommandIndex(args) !== -1) return false;
3171
+ return args.includes("--version") || args.includes("-v");
3172
+ }
3173
+
2339
3174
  // src/cli.ts
2340
3175
  function printHelp(version) {
2341
3176
  banner(version);
@@ -2375,11 +3210,12 @@ function printHelp(version) {
2375
3210
  }
2376
3211
  async function main() {
2377
3212
  const args = process.argv.slice(2);
2378
- const command = args[0] && !args[0].startsWith("-") ? args[0] : null;
2379
- const commandArgs = command ? args.slice(1) : args;
3213
+ const commandIndex = getCliCommandIndex(args);
3214
+ const command = getCliCommand(args);
3215
+ const commandArgs = commandIndex === -1 ? args : args.slice(commandIndex + 1);
2380
3216
  const pkg = await Promise.resolve().then(() => (init_package(), package_exports));
2381
3217
  const version = pkg.default.version;
2382
- if (args.includes("--version") || args.includes("-v")) {
3218
+ if (isGlobalVersionRequest(args)) {
2383
3219
  console.log(version);
2384
3220
  process.exit(0);
2385
3221
  }