deus-machine 0.3.6 → 0.3.11

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.6",
22
+ version: "0.3.11",
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.153.4",
65
+ "@openai/codex-sdk": "0.153.4",
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,899 @@ 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
+ constants,
155
+ cpSync,
156
+ existsSync,
157
+ linkSync,
158
+ mkdirSync,
159
+ mkdtempSync,
160
+ readFileSync,
161
+ rmSync,
162
+ statSync,
163
+ symlinkSync,
164
+ writeFileSync
165
+ } from "node:fs";
142
166
  import path2 from "node:path";
143
167
  import { fileURLToPath } from "node:url";
144
168
  var runtimeDir = path2.dirname(fileURLToPath(import.meta.url));
145
169
  var defaultProjectRoot = path2.resolve(runtimeDir, "../..");
146
- var BUILD_RUNTIME_COMMAND = "bun run build:runtime";
170
+ var VERIFY_TIMEOUT_MS = 2e4;
171
+ var MIN_CODEX_APP_SERVER_VERSION = "0.128.0";
172
+ var VERSION_CHECK_ENV_DENYLIST = [
173
+ "AGENT_SERVER_CWD",
174
+ "AGENT_SERVER_ENTRY",
175
+ "AUTH_TOKEN",
176
+ "BUN_OPTIONS",
177
+ "DATABASE_PATH",
178
+ "DEUS_AUTH_TOKEN",
179
+ "DEUS_BACKEND_PORT",
180
+ "DEUS_BUNDLED_BIN_DIR",
181
+ "DEUS_DATA_DIR",
182
+ "DEUS_PACKAGED",
183
+ "DEUS_RESOURCES_PATH",
184
+ "DEUS_RUNTIME",
185
+ "DEUS_RUNTIME_COMMAND",
186
+ "DEUS_RUNTIME_EXECUTABLE",
187
+ "ELECTRON_RUN_AS_NODE",
188
+ "NODE_PATH",
189
+ "PORT"
190
+ ];
191
+ var CODEX_HELPERS = [
192
+ "codex-runtime/bin/codex-code-mode-host",
193
+ "codex-runtime/codex-resources/zsh/bin/zsh"
194
+ ];
195
+ var CODEX_LINUX_HELPER = "codex-runtime/codex-resources/bwrap";
196
+ function bundledTools(runtimeKey) {
197
+ return [
198
+ "codex",
199
+ "claude",
200
+ "rg",
201
+ "agent-browser",
202
+ ...CODEX_HELPERS,
203
+ ...runtimeKey.startsWith("linux-") ? [CODEX_LINUX_HELPER] : []
204
+ ];
205
+ }
206
+ var AGENT_CLI_TARGETS = [
207
+ {
208
+ runtimeKey: "darwin-arm64",
209
+ fileFormat: "Mach-O 64-bit executable",
210
+ fileArch: "arm64",
211
+ agentBrowserEntry: "bin/agent-browser-darwin-arm64",
212
+ codexAliasPackage: "@openai/codex-darwin-arm64",
213
+ codexTriple: "aarch64-apple-darwin",
214
+ claudePackageName: "@anthropic-ai/claude-agent-sdk-darwin-arm64"
215
+ },
216
+ {
217
+ runtimeKey: "darwin-x64",
218
+ fileFormat: "Mach-O 64-bit executable",
219
+ fileArch: "x86_64",
220
+ agentBrowserEntry: "bin/agent-browser-darwin-x64",
221
+ codexAliasPackage: "@openai/codex-darwin-x64",
222
+ codexTriple: "x86_64-apple-darwin",
223
+ claudePackageName: "@anthropic-ai/claude-agent-sdk-darwin-x64"
224
+ },
225
+ {
226
+ runtimeKey: "linux-x64",
227
+ fileFormat: "ELF 64-bit",
228
+ fileArch: "x86-64",
229
+ agentBrowserEntry: "bin/agent-browser-linux-x64",
230
+ codexAliasPackage: "@openai/codex-linux-x64",
231
+ codexTriple: "x86_64-unknown-linux-musl",
232
+ claudePackageName: "@anthropic-ai/claude-agent-sdk-linux-x64"
233
+ }
234
+ ];
147
235
  function relativeFromProjectRoot(projectRoot, targetPath) {
148
236
  return path2.relative(projectRoot, targetPath).split(path2.sep).join("/");
149
237
  }
238
+ function resolveAgentCliManifestPath(projectRoot) {
239
+ return path2.join(resolveRuntimeStagePaths(projectRoot).electron.root, "bin", "agent-clis.json");
240
+ }
241
+ function resolveStagedAgentCliPath(projectRoot, runtimeKey, tool) {
242
+ return path2.join(resolveRuntimeStagePaths(projectRoot).electron.root, "bin", runtimeKey, tool);
243
+ }
244
+ function readSemver(version) {
245
+ return version.match(/\d+\.\d+\.\d+/)?.[0] ?? null;
246
+ }
247
+ function isVersionAtLeast(version, minimum) {
248
+ if (!version) return false;
249
+ const currentParts = version.split(".").map(Number);
250
+ const minimumParts = minimum.split(".").map(Number);
251
+ for (let i = 0; i < minimumParts.length; i++) {
252
+ const current = currentParts[i] ?? 0;
253
+ const required = minimumParts[i] ?? 0;
254
+ if (current > required) return true;
255
+ if (current < required) return false;
256
+ }
257
+ return true;
258
+ }
259
+ function assertCodexAppServerCompatible(version, label) {
260
+ const semver = readSemver(version);
261
+ if (isVersionAtLeast(semver, MIN_CODEX_APP_SERVER_VERSION)) return;
262
+ throw new Error(
263
+ `${label} requires @openai/codex >= ${MIN_CODEX_APP_SERVER_VERSION} for the codex app-server harness; found ${version}`
264
+ );
265
+ }
266
+ function hashFile(filePath) {
267
+ return createHash("sha256").update(readFileSync(filePath)).digest("hex");
268
+ }
269
+ function shouldVerifyRuntimeKey(runtimeKey) {
270
+ if (process.platform === "darwin") return runtimeKey === `darwin-${process.arch}`;
271
+ if (process.platform === "linux" && process.arch === "x64") return runtimeKey === "linux-x64";
272
+ return false;
273
+ }
274
+ function spawnErrorCode(error2) {
275
+ return error2?.code ?? error2?.message ?? "none";
276
+ }
277
+ function verifyVersion(executablePath, args, env = process.env) {
278
+ const result = spawnSync(executablePath, args, {
279
+ encoding: "utf8",
280
+ timeout: VERIFY_TIMEOUT_MS,
281
+ env,
282
+ stdio: ["ignore", "pipe", "pipe"]
283
+ });
284
+ const output = (result.stdout || "").trim();
285
+ if (result.status !== 0) {
286
+ const stderr = (result.stderr || "").trim();
287
+ const diagnostics = stagedExecutableDiagnostics(executablePath);
288
+ const hint2 = macExecutionPolicyHint(diagnostics);
289
+ throw new Error(
290
+ `${path2.basename(executablePath)} ${args.join(" ")} failed: status=${result.status} signal=${result.signal} error=${spawnErrorCode(result.error)} stdout=${output} stderr=${stderr}${diagnostics ? `
291
+ ${diagnostics}` : ""}${hint2}`
292
+ );
293
+ }
294
+ return output;
295
+ }
296
+ function diagnosticOutput(command, args, cwd) {
297
+ const result = spawnSync(command, args, {
298
+ cwd,
299
+ encoding: "utf8",
300
+ timeout: VERIFY_TIMEOUT_MS,
301
+ stdio: ["ignore", "pipe", "pipe"]
302
+ });
303
+ const output = `${result.stdout || ""}${result.stderr || ""}`.trim();
304
+ if (result.error) {
305
+ return [spawnErrorCode(result.error), output].filter(Boolean).join("\n");
306
+ }
307
+ if (result.status !== 0) return output || `${command} exited with status ${result.status}`;
308
+ return output;
309
+ }
310
+ function stagedExecutableDiagnostics(executablePath) {
311
+ if (process.platform !== "darwin") return "";
312
+ const cwd = path2.dirname(executablePath);
313
+ return [
314
+ `file: ${diagnosticOutput("file", [executablePath], cwd)}`,
315
+ `codesign: ${diagnosticOutput("codesign", ["-dv", "--verbose=4", executablePath], cwd)}`,
316
+ `spctl: ${diagnosticOutput("spctl", ["--assess", "--type", "execute", "--verbose=4", executablePath], cwd)}`,
317
+ `xattr: ${diagnosticOutput("xattr", ["-l", executablePath], cwd) || "none"}`
318
+ ].join("\n");
319
+ }
320
+ function macExecutionPolicyHint(diagnostics) {
321
+ if (process.platform !== "darwin") return "";
322
+ if (!/spctl:[\s\S]*rejected/.test(diagnostics)) return "";
323
+ if (!/com\.apple\.(provenance|quarantine)/.test(diagnostics)) return "";
324
+ return [
325
+ "",
326
+ "macOS rejected this executable before --version produced output.",
327
+ "Verify runnable staged agent CLIs on a notarized artifact or a macOS host that allows generated/copied Mach-O binaries to launch."
328
+ ].join("\n");
329
+ }
330
+ function assertVersionOutput(tool, output, executablePath) {
331
+ if (!output) {
332
+ throw new Error(`${tool} --version produced no output for ${executablePath}`);
333
+ }
334
+ if (tool === "codex" && !/\b\d+\.\d+\.\d+\b/.test(output)) {
335
+ throw new Error(`Unexpected codex --version output for ${executablePath}: ${output}`);
336
+ }
337
+ if (tool === "claude" && !/Claude Code|\b\d+\.\d+\.\d+\b/.test(output)) {
338
+ throw new Error(`Unexpected claude --version output for ${executablePath}: ${output}`);
339
+ }
340
+ }
341
+ function verifyStagedAgentCliVersion(tool, executablePath) {
342
+ const binDir = path2.dirname(executablePath);
343
+ const env = versionCheckEnv(binDir);
344
+ const output = verifyVersion(
345
+ executablePath,
346
+ [tool === "claude" ? "--version" : "--version"],
347
+ env
348
+ );
349
+ assertVersionOutput(tool, output, executablePath);
350
+ return output;
351
+ }
352
+ function versionCheckEnv(binDir) {
353
+ const env = { ...process.env };
354
+ for (const key of VERSION_CHECK_ENV_DENYLIST) {
355
+ delete env[key];
356
+ }
357
+ env.PATH = [binDir, process.env.PATH].filter(Boolean).join(path2.delimiter);
358
+ return env;
359
+ }
360
+ function inspectStaticExecutable(projectRoot, filePath, label, fileFormat, fileArch) {
361
+ assertExecutable(filePath, label);
362
+ return {
363
+ sha256: hashFile(filePath),
364
+ size: statSync(filePath).size,
365
+ fileOutput: getExecutableFileOutput(projectRoot, filePath, label, fileFormat, fileArch)
366
+ };
367
+ }
368
+ function assertManifestEntry(projectRoot, manifestEntries, runtimeKey, tool, executablePath, inspection) {
369
+ const entry = manifestEntries.find((candidate) => candidate.tool === tool);
370
+ if (!entry) {
371
+ throw new Error(`Agent CLI manifest is missing ${runtimeKey}/${tool}`);
372
+ }
373
+ const expectedPath = relativeFromProjectRoot(projectRoot, executablePath);
374
+ if (entry.path !== expectedPath) {
375
+ throw new Error(
376
+ `Agent CLI manifest path mismatch for ${runtimeKey}/${tool}: expected ${expectedPath}, found ${entry.path}`
377
+ );
378
+ }
379
+ if (entry.sha256 !== inspection.sha256) {
380
+ throw new Error(`Agent CLI manifest hash mismatch for ${runtimeKey}/${tool}`);
381
+ }
382
+ if (entry.size !== inspection.size) {
383
+ throw new Error(`Agent CLI manifest size mismatch for ${runtimeKey}/${tool}`);
384
+ }
385
+ if (entry.fileOutput !== inspection.fileOutput) {
386
+ throw new Error(`Agent CLI manifest file output mismatch for ${runtimeKey}/${tool}`);
387
+ }
388
+ }
389
+ function assertExecutable(filePath, label) {
390
+ if (!existsSync(filePath)) {
391
+ throw new Error(`Missing ${label}: ${filePath}`);
392
+ }
393
+ const stat = statSync(filePath);
394
+ if (!stat.isFile()) {
395
+ throw new Error(`Expected ${label} to be a regular file: ${filePath}`);
396
+ }
397
+ if ((stat.mode & 73) === 0) {
398
+ throw new Error(`Expected ${label} to be executable: ${filePath}`);
399
+ }
400
+ }
401
+ function getExecutableFileOutput(projectRoot, filePath, label, fileFormat, fileArch) {
402
+ const fileOutput = execFileSync("file", ["-L", relativeFromProjectRoot(projectRoot, filePath)], {
403
+ cwd: projectRoot,
404
+ encoding: "utf8",
405
+ timeout: VERIFY_TIMEOUT_MS,
406
+ stdio: ["ignore", "pipe", "pipe"]
407
+ }).trim();
408
+ const hasExpectedFormat = fileFormat === "Mach-O 64-bit executable" ? fileOutput.includes("Mach-O 64-bit") && fileOutput.includes("executable") : fileOutput.includes(fileFormat);
409
+ if (!hasExpectedFormat || !fileOutput.includes(fileArch)) {
410
+ throw new Error(`Unexpected ${label} architecture: ${fileOutput}`);
411
+ }
412
+ return fileOutput;
413
+ }
414
+ function validateStagedAgentClis(options = {}) {
415
+ const log = options.log ?? console.log;
416
+ const projectRoot = options.projectRoot ?? defaultProjectRoot;
417
+ const manifestPath = resolveAgentCliManifestPath(projectRoot);
418
+ if (!existsSync(manifestPath)) {
419
+ throw new Error(`Missing staged agent CLI manifest: ${manifestPath}`);
420
+ }
421
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
422
+ const runtimeKeys = options.runtimeKey ? [options.runtimeKey] : AGENT_CLI_TARGETS.map((target) => target.runtimeKey);
423
+ for (const runtimeKey of runtimeKeys) {
424
+ const target = AGENT_CLI_TARGETS.find((item) => item.runtimeKey === runtimeKey);
425
+ if (!target) throw new Error(`Unsupported agent CLI runtime key: ${runtimeKey}`);
426
+ const manifestEntries = manifest.targets.filter((entry) => entry.runtimeKey === runtimeKey);
427
+ const codexEntry = manifestEntries.find((entry) => entry.tool === "codex");
428
+ if (!codexEntry) {
429
+ throw new Error(`Agent CLI manifest is missing ${runtimeKey}/codex`);
430
+ }
431
+ assertCodexAppServerCompatible(codexEntry.source.version, `${runtimeKey}/codex`);
432
+ const tools = bundledTools(runtimeKey);
433
+ for (const tool of tools) {
434
+ const executablePath = resolveStagedAgentCliPath(projectRoot, runtimeKey, tool);
435
+ const inspection = inspectStaticExecutable(
436
+ projectRoot,
437
+ executablePath,
438
+ `${runtimeKey}/${tool}`,
439
+ target.fileFormat,
440
+ target.fileArch
441
+ );
442
+ assertManifestEntry(
443
+ projectRoot,
444
+ manifestEntries,
445
+ runtimeKey,
446
+ tool,
447
+ executablePath,
448
+ inspection
449
+ );
450
+ }
451
+ if (manifestEntries.length !== tools.length) {
452
+ throw new Error(
453
+ `Agent CLI manifest expected ${tools.length} entries for ${runtimeKey}, found ${manifestEntries.length}`
454
+ );
455
+ }
456
+ if (!existsSync(
457
+ path2.join(
458
+ path2.dirname(resolveStagedAgentCliPath(projectRoot, runtimeKey, "codex")),
459
+ "codex-runtime",
460
+ "codex-package.json"
461
+ )
462
+ )) {
463
+ throw new Error(`Missing Codex package metadata for ${runtimeKey}`);
464
+ }
465
+ if (options.verifyRunnable === true && shouldVerifyRuntimeKey(runtimeKey)) {
466
+ for (const tool of ["codex", "claude"]) {
467
+ const executablePath = resolveStagedAgentCliPath(projectRoot, runtimeKey, tool);
468
+ const version = verifyStagedAgentCliVersion(tool, executablePath);
469
+ log(`\u2713 ${runtimeKey}/${tool} ${version}`);
470
+ }
471
+ }
472
+ }
473
+ log(`\u2713 Staged agent CLIs ready (${runtimeKeys.join(", ")})`);
474
+ return manifest;
475
+ }
476
+
477
+ // ../../scripts/runtime/native-runtime.ts
478
+ import { execFileSync as execFileSync2, spawnSync as spawnSync2 } from "node:child_process";
479
+ import { createHash as createHash2 } from "node:crypto";
480
+ import {
481
+ chmodSync as chmodSync2,
482
+ existsSync as existsSync2,
483
+ mkdirSync as mkdirSync2,
484
+ readdirSync,
485
+ readFileSync as readFileSync2,
486
+ rmSync as rmSync2,
487
+ statSync as statSync2,
488
+ writeFileSync as writeFileSync2
489
+ } from "node:fs";
490
+ import path3 from "node:path";
491
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
492
+ var runtimeDir2 = path3.dirname(fileURLToPath2(import.meta.url));
493
+ var defaultProjectRoot2 = path3.resolve(runtimeDir2, "../..");
494
+ var VERIFY_TIMEOUT_MS2 = 2e4;
495
+ var VERIFY_STOP_TIMEOUT_MS = 5e3;
496
+ var MAC_CODESIGN_PAGE_SIZE = "4096";
497
+ var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([".cjs", ".js", ".json", ".mjs", ".ts", ".tsx"]);
498
+ var IGNORED_SOURCE_DIRS = /* @__PURE__ */ new Set([
499
+ ".git",
500
+ ".turbo",
501
+ "coverage",
502
+ "dist",
503
+ "node_modules",
504
+ "out",
505
+ "test",
506
+ "tests",
507
+ "__tests__"
508
+ ]);
509
+ var REQUIRED_RUNTIME_ENTITLEMENTS = [
510
+ "com.apple.security.cs.allow-jit",
511
+ "com.apple.security.cs.allow-unsigned-executable-memory",
512
+ "com.apple.security.cs.disable-library-validation"
513
+ ];
514
+ var VERSION_CHECK_ENV_DENYLIST2 = [
515
+ "AGENT_SERVER_CWD",
516
+ "AGENT_SERVER_ENTRY",
517
+ "AUTH_TOKEN",
518
+ "BUN_OPTIONS",
519
+ "DATABASE_PATH",
520
+ "DEUS_AUTH_TOKEN",
521
+ "DEUS_BACKEND_PORT",
522
+ "DEUS_BUNDLED_BIN_DIR",
523
+ "DEUS_DATA_DIR",
524
+ "DEUS_PACKAGED",
525
+ "DEUS_RESOURCES_PATH",
526
+ "DEUS_RUNTIME",
527
+ "DEUS_RUNTIME_COMMAND",
528
+ "DEUS_RUNTIME_EXECUTABLE",
529
+ "ELECTRON_RUN_AS_NODE",
530
+ "NODE_PATH",
531
+ "PORT"
532
+ ];
533
+ var DEUS_RUNTIME_TARGETS = [
534
+ {
535
+ runtimeKey: "darwin-arm64",
536
+ platform: "darwin",
537
+ bunTarget: "bun-darwin-arm64",
538
+ fileArch: "arm64"
539
+ },
540
+ {
541
+ runtimeKey: "darwin-x64",
542
+ platform: "darwin",
543
+ bunTarget: "bun-darwin-x64",
544
+ fileArch: "x86_64"
545
+ },
546
+ {
547
+ runtimeKey: "linux-x64",
548
+ platform: "linux",
549
+ bunTarget: "bun-linux-x64",
550
+ fileArch: "x86-64"
551
+ }
552
+ ];
553
+ function relativeFromProjectRoot2(projectRoot, targetPath) {
554
+ return path3.relative(projectRoot, targetPath).split(path3.sep).join("/");
555
+ }
556
+ function resolveDeusRuntimeManifestPath(projectRoot) {
557
+ return path3.join(resolveRuntimeStagePaths(projectRoot).electron.root, "bin", "deus-runtime.json");
558
+ }
559
+ function resolveStagedDeusRuntimePath(projectRoot, runtimeKey) {
560
+ return path3.join(
561
+ resolveRuntimeStagePaths(projectRoot).electron.root,
562
+ "bin",
563
+ runtimeKey,
564
+ "deus-runtime"
565
+ );
566
+ }
567
+ function hashFile2(filePath) {
568
+ return createHash2("sha256").update(readFileSync2(filePath)).digest("hex");
569
+ }
570
+ function getHostRuntimeKey() {
571
+ if (process.platform === "darwin" && (process.arch === "arm64" || process.arch === "x64")) {
572
+ return `darwin-${process.arch}`;
573
+ }
574
+ if (process.platform === "linux" && process.arch === "x64") {
575
+ return "linux-x64";
576
+ }
577
+ return null;
578
+ }
579
+ function shouldVerifyRuntimeKey2(runtimeKey) {
580
+ return getHostRuntimeKey() === runtimeKey;
581
+ }
582
+ function canInspectMacBinary(target) {
583
+ return target.platform === "darwin" && process.platform === "darwin";
584
+ }
585
+ function execOutput(command, args, cwd) {
586
+ return execFileSync2(command, args, {
587
+ cwd,
588
+ encoding: "utf8",
589
+ timeout: VERIFY_TIMEOUT_MS2,
590
+ stdio: ["ignore", "pipe", "pipe"]
591
+ }).trim();
592
+ }
593
+ function spawnErrorCode2(error2) {
594
+ return error2?.code ?? error2?.message ?? "none";
595
+ }
596
+ function diagnosticOutput2(command, args, cwd) {
597
+ const result = spawnSync2(command, args, {
598
+ cwd,
599
+ encoding: "utf8",
600
+ timeout: VERIFY_TIMEOUT_MS2,
601
+ stdio: ["ignore", "pipe", "pipe"]
602
+ });
603
+ const output = `${result.stdout || ""}${result.stderr || ""}`.trim();
604
+ if (result.error) {
605
+ return [spawnErrorCode2(result.error), output].filter(Boolean).join("\n");
606
+ }
607
+ if (result.status !== 0) return output || `${command} exited with status ${result.status}`;
608
+ return output;
609
+ }
610
+ function runtimeExecutableDiagnostics(executablePath) {
611
+ if (process.platform !== "darwin") return "";
612
+ const cwd = path3.dirname(executablePath);
613
+ return [
614
+ `file: ${diagnosticOutput2("file", [executablePath], cwd)}`,
615
+ `codesign: ${diagnosticOutput2("codesign", ["-dv", "--verbose=4", executablePath], cwd)}`,
616
+ `spctl: ${diagnosticOutput2("spctl", ["--assess", "--type", "execute", "--verbose=4", executablePath], cwd)}`,
617
+ `xattr: ${diagnosticOutput2("xattr", ["-l", executablePath], cwd) || "none"}`
618
+ ].join("\n");
619
+ }
620
+ function macExecutionPolicyHint2(diagnostics) {
621
+ if (process.platform !== "darwin") return "";
622
+ if (!/spctl:[\s\S]*rejected/.test(diagnostics)) return "";
623
+ if (!/com\.apple\.(provenance|quarantine)/.test(diagnostics)) return "";
624
+ return [
625
+ "",
626
+ "macOS rejected this executable before --version produced output.",
627
+ "Verify runnable staged runtime binaries on a notarized artifact or a macOS host that allows generated Mach-O binaries to launch."
628
+ ].join("\n");
629
+ }
630
+ function readPackageVersion(projectRoot) {
631
+ const packageJsonPath = path3.join(projectRoot, "package.json");
632
+ const packageJson = JSON.parse(readFileSync2(packageJsonPath, "utf8"));
633
+ if (typeof packageJson.version !== "string" || packageJson.version.length === 0) {
634
+ throw new Error(`package.json is missing a string version: ${packageJsonPath}`);
635
+ }
636
+ return packageJson.version;
637
+ }
638
+ function latestSourceMtime(projectRoot, sourceRelatives) {
639
+ let latest = { mtimeMs: 0, path: null };
640
+ function visit(sourcePath) {
641
+ if (!existsSync2(sourcePath)) return;
642
+ const stat = statSync2(sourcePath);
643
+ if (stat.isDirectory()) {
644
+ for (const entry of readdirSync(sourcePath, { withFileTypes: true })) {
645
+ if (IGNORED_SOURCE_DIRS.has(entry.name)) continue;
646
+ visit(path3.join(sourcePath, entry.name));
647
+ }
648
+ return;
649
+ }
650
+ if (!SOURCE_EXTENSIONS.has(path3.extname(sourcePath))) return;
651
+ if (stat.mtimeMs > latest.mtimeMs) {
652
+ latest = { mtimeMs: stat.mtimeMs, path: sourcePath };
653
+ }
654
+ }
655
+ for (const sourceRelative of sourceRelatives) {
656
+ visit(path3.join(projectRoot, sourceRelative));
657
+ }
658
+ return latest;
659
+ }
660
+ function assertRuntimeFresh(projectRoot, executablePath, runtimeKey) {
661
+ const latestSource = latestSourceMtime(projectRoot, [
662
+ "apps/runtime",
663
+ "apps/backend/src",
664
+ "apps/agent-server",
665
+ "shared",
666
+ "resources/entitlements.runtime.plist"
667
+ ]);
668
+ if (!latestSource.path) return;
669
+ if (statSync2(executablePath).mtimeMs >= latestSource.mtimeMs) return;
670
+ throw new Error(
671
+ `${runtimeKey}/deus-runtime is stale: ${relativeFromProjectRoot2(
672
+ projectRoot,
673
+ executablePath
674
+ )} is older than ${relativeFromProjectRoot2(projectRoot, latestSource.path)}. Run \`bun run build:runtime\` before packaging.`
675
+ );
676
+ }
677
+ function assertExecutable2(filePath, label) {
678
+ if (!existsSync2(filePath)) {
679
+ throw new Error(`Missing ${label}: ${filePath}`);
680
+ }
681
+ const stat = statSync2(filePath);
682
+ if (!stat.isFile()) {
683
+ throw new Error(`Expected ${label} to be a regular file: ${filePath}`);
684
+ }
685
+ if ((stat.mode & 73) === 0) {
686
+ throw new Error(`Expected ${label} to be executable: ${filePath}`);
687
+ }
688
+ }
689
+ function assertFileArch(fileOutput, target, filePath) {
690
+ const hasExpectedFormat = target.platform === "darwin" ? fileOutput.includes("Mach-O 64-bit") && fileOutput.includes("executable") : fileOutput.includes("ELF 64-bit");
691
+ if (!hasExpectedFormat || !fileOutput.includes(target.fileArch)) {
692
+ throw new Error(`Unexpected file(1) output for ${filePath}: ${fileOutput}`);
693
+ }
694
+ }
695
+ function verifyMacCodeSignature(filePath) {
696
+ if (process.platform !== "darwin") return;
697
+ const result = spawnSync2("codesign", ["--verify", "--verbose=2", filePath], {
698
+ encoding: "utf8",
699
+ stdio: ["ignore", "pipe", "pipe"]
700
+ });
701
+ if (result.status !== 0) {
702
+ throw new Error(`Invalid code signature for ${filePath}: ${result.stderr || result.stdout}`);
703
+ }
704
+ }
705
+ function verifyMacCodeSignaturePageSize(filePath) {
706
+ if (process.platform !== "darwin") return;
707
+ const result = spawnSync2("codesign", ["-dv", "--verbose=4", filePath], {
708
+ encoding: "utf8",
709
+ stdio: ["ignore", "pipe", "pipe"]
710
+ });
711
+ if (result.status !== 0) {
712
+ throw new Error(
713
+ `Unable to inspect code signature for ${filePath}: ${result.stderr || result.stdout}`
714
+ );
715
+ }
716
+ const output = `${result.stdout}
717
+ ${result.stderr}`;
718
+ if (!output.includes(`Page size=${MAC_CODESIGN_PAGE_SIZE}`)) {
719
+ throw new Error(
720
+ `Unexpected code signature page size for ${filePath}; expected ${MAC_CODESIGN_PAGE_SIZE}`
721
+ );
722
+ }
723
+ }
724
+ function readMacEntitlements(filePath) {
725
+ const result = spawnSync2("codesign", ["-d", "--entitlements", ":-", filePath], {
726
+ encoding: "utf8",
727
+ stdio: ["ignore", "pipe", "pipe"]
728
+ });
729
+ if (result.status !== 0) {
730
+ throw new Error(
731
+ `Unable to read entitlements for ${filePath}: ${result.stderr || result.stdout}`
732
+ );
733
+ }
734
+ return `${result.stdout}
735
+ ${result.stderr}`;
736
+ }
737
+ function verifyMacSystemDylibs(otoolOutput, filePath) {
738
+ if (process.platform !== "darwin") return;
739
+ const unexpected = otoolOutput.split(/\r?\n/).slice(1).map((line) => line.trim().split(/\s+/)[0]).filter(Boolean).filter(
740
+ (dependency) => !dependency.startsWith("/usr/lib/") && !dependency.startsWith("/System/Library/")
741
+ );
742
+ if (unexpected.length > 0) {
743
+ throw new Error(
744
+ `Unexpected non-system dylib dependency for ${filePath}: ${unexpected.join(", ")}`
745
+ );
746
+ }
747
+ }
748
+ function verifyMacRuntimeEntitlements(filePath) {
749
+ if (process.platform !== "darwin") return;
750
+ const entitlements = readMacEntitlements(filePath);
751
+ for (const entitlement of REQUIRED_RUNTIME_ENTITLEMENTS) {
752
+ if (!entitlements.includes(entitlement)) {
753
+ throw new Error(`Missing ${entitlement} entitlement for ${filePath}`);
754
+ }
755
+ }
756
+ }
757
+ function verifyStagedDeusRuntimeVersion(executablePath) {
758
+ const helperPath = path3.join(runtimeDir2, "smoke", "run-version-check.cjs");
759
+ const env = { ...process.env };
760
+ for (const key of VERSION_CHECK_ENV_DENYLIST2) {
761
+ delete env[key];
762
+ }
763
+ env.DEUS_VERSION_CHECK_TIMEOUT_MS = String(VERIFY_TIMEOUT_MS2);
764
+ env.DEUS_VERSION_CHECK_STOP_TIMEOUT_MS = String(VERIFY_STOP_TIMEOUT_MS);
765
+ const result = spawnSync2(process.execPath, [helperPath, executablePath, "--version"], {
766
+ encoding: "utf8",
767
+ timeout: VERIFY_TIMEOUT_MS2 + VERIFY_STOP_TIMEOUT_MS + 5e3,
768
+ env,
769
+ stdio: ["ignore", "pipe", "pipe"]
770
+ });
771
+ const rawOutput = (result.stdout || "").trim();
772
+ let checkResult;
773
+ try {
774
+ checkResult = JSON.parse(rawOutput);
775
+ } catch {
776
+ checkResult = {
777
+ ok: false,
778
+ status: result.status,
779
+ signal: result.signal,
780
+ error: spawnErrorCode2(result.error),
781
+ stdout: rawOutput,
782
+ stderr: (result.stderr || "").trim()
783
+ };
784
+ }
785
+ const output = (checkResult.stdout || "").trim();
786
+ if (result.status !== 0) {
787
+ const stderr = [checkResult.stderr, result.stderr].filter(Boolean).join("\n").trim();
788
+ const diagnostics = runtimeExecutableDiagnostics(executablePath);
789
+ const hint2 = macExecutionPolicyHint2(diagnostics);
790
+ throw new Error(
791
+ `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 ? `
792
+ ${diagnostics}` : ""}${hint2}`
793
+ );
794
+ }
795
+ if (!/^deus-runtime \d+\.\d+\.\d+ /.test(output)) {
796
+ throw new Error(`Unexpected deus-runtime --version output for ${executablePath}: ${output}`);
797
+ }
798
+ return output;
799
+ }
800
+ function validateDeusRuntime(options = {}) {
801
+ const log = options.log ?? console.log;
802
+ const projectRoot = options.projectRoot ?? defaultProjectRoot2;
803
+ const manifestPath = resolveDeusRuntimeManifestPath(projectRoot);
804
+ if (!existsSync2(manifestPath)) {
805
+ throw new Error(`Missing native runtime manifest: ${manifestPath}`);
806
+ }
807
+ const manifest = JSON.parse(readFileSync2(manifestPath, "utf8"));
808
+ const packageVersion = readPackageVersion(projectRoot);
809
+ if (manifest.packageVersion !== packageVersion) {
810
+ throw new Error(
811
+ `Native runtime manifest package version mismatch: expected ${packageVersion}, found ${manifest.packageVersion ?? "missing"}. Run \`bun run build:runtime\` before packaging.`
812
+ );
813
+ }
814
+ const runtimeKeys = options.runtimeKey ? [options.runtimeKey] : DEUS_RUNTIME_TARGETS.map((target) => target.runtimeKey);
815
+ for (const runtimeKey of runtimeKeys) {
816
+ const target = DEUS_RUNTIME_TARGETS.find((item) => item.runtimeKey === runtimeKey);
817
+ if (!target) throw new Error(`Unsupported native runtime key: ${runtimeKey}`);
818
+ const executablePath = resolveStagedDeusRuntimePath(projectRoot, runtimeKey);
819
+ assertExecutable2(executablePath, `${runtimeKey}/deus-runtime`);
820
+ assertRuntimeFresh(projectRoot, executablePath, runtimeKey);
821
+ const manifestEntry = manifest.entries.find((entry) => entry.runtimeKey === runtimeKey);
822
+ if (!manifestEntry) throw new Error(`Native runtime manifest is missing ${runtimeKey}`);
823
+ const expectedPath = relativeFromProjectRoot2(projectRoot, executablePath);
824
+ if (manifestEntry.path !== expectedPath) {
825
+ throw new Error(
826
+ `Native runtime manifest path mismatch for ${runtimeKey}: expected ${expectedPath}, found ${manifestEntry.path}`
827
+ );
828
+ }
829
+ if (manifestEntry.sha256 !== hashFile2(executablePath)) {
830
+ throw new Error(`Native runtime manifest hash mismatch for ${runtimeKey}`);
831
+ }
832
+ const manifestCommandPath = relativeFromProjectRoot2(projectRoot, executablePath);
833
+ const fileOutput = execOutput("file", [manifestCommandPath], projectRoot);
834
+ assertFileArch(fileOutput, target, executablePath);
835
+ const otoolOutput = canInspectMacBinary(target) ? execOutput("otool", ["-L", manifestCommandPath], projectRoot) : void 0;
836
+ if (otoolOutput) verifyMacSystemDylibs(otoolOutput, executablePath);
837
+ if (manifestEntry.size !== statSync2(executablePath).size) {
838
+ throw new Error(`Native runtime manifest size mismatch for ${runtimeKey}`);
839
+ }
840
+ if (manifestEntry.fileOutput !== fileOutput) {
841
+ throw new Error(`Native runtime manifest file output mismatch for ${runtimeKey}`);
842
+ }
843
+ if (manifestEntry.otoolOutput !== otoolOutput) {
844
+ throw new Error(`Native runtime manifest otool output mismatch for ${runtimeKey}`);
845
+ }
846
+ if (canInspectMacBinary(target)) {
847
+ verifyMacCodeSignature(executablePath);
848
+ verifyMacCodeSignaturePageSize(executablePath);
849
+ verifyMacRuntimeEntitlements(executablePath);
850
+ }
851
+ if (options.verifyRunnable === true && shouldVerifyRuntimeKey2(runtimeKey)) {
852
+ const version = verifyStagedDeusRuntimeVersion(executablePath);
853
+ log(`\u2713 ${runtimeKey}/deus-runtime ${version}`);
854
+ }
855
+ }
856
+ log(`\u2713 Native runtime ready (${runtimeKeys.join(", ")})`);
857
+ return manifest;
858
+ }
859
+
860
+ // ../../scripts/runtime/validate.ts
861
+ var runtimeDir3 = path4.dirname(fileURLToPath3(import.meta.url));
862
+ var defaultProjectRoot3 = path4.resolve(runtimeDir3, "../..");
863
+ var BUILD_RUNTIME_COMMAND = "bun run build:runtime";
864
+ function relativeFromProjectRoot3(projectRoot, targetPath) {
865
+ return path4.relative(projectRoot, targetPath).split(path4.sep).join("/");
866
+ }
150
867
  function createBuildRuntimeError(message) {
151
868
  return new Error(`${message}
152
869
  Run \`${BUILD_RUNTIME_COMMAND}\` before packaging.`);
153
870
  }
154
871
  function readManifest(manifestPath) {
155
872
  try {
156
- return JSON.parse(readFileSync(manifestPath, "utf8"));
873
+ return JSON.parse(readFileSync3(manifestPath, "utf8"));
157
874
  } catch (error2) {
158
875
  throw createBuildRuntimeError(
159
876
  `Unable to read staged runtime manifest at ${manifestPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
160
877
  );
161
878
  }
162
879
  }
880
+ function hashFile3(filePath) {
881
+ return createHash3("sha256").update(readFileSync3(filePath)).digest("hex");
882
+ }
883
+ function ghArchiveName(version, archivePlatform, extension = "zip") {
884
+ return `gh_${version}_${archivePlatform}.${extension}`;
885
+ }
886
+ function readGhCliContract(projectRoot) {
887
+ const contractPath = path4.join(projectRoot, "scripts", "runtime", "gh-cli-contract.json");
888
+ try {
889
+ const contract = JSON.parse(readFileSync3(contractPath, "utf8"));
890
+ if (typeof contract.ghVersion !== "string" || !Array.isArray(contract.targets)) {
891
+ throw new Error("unexpected contract shape");
892
+ }
893
+ return contract;
894
+ } catch (error2) {
895
+ throw createBuildRuntimeError(
896
+ `Unable to read GitHub CLI contract at ${contractPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
897
+ );
898
+ }
899
+ }
163
900
  function assertExists(filePath, label) {
164
- if (!existsSync(filePath)) {
901
+ if (!existsSync3(filePath)) {
165
902
  throw createBuildRuntimeError(`Missing ${label}: ${filePath}`);
166
903
  }
167
904
  }
905
+ function assertExecutable3(filePath, label) {
906
+ assertExists(filePath, label);
907
+ const stat = statSync3(filePath);
908
+ if (!stat.isFile()) {
909
+ throw createBuildRuntimeError(`Expected ${label} to be a regular file: ${filePath}`);
910
+ }
911
+ if ((stat.mode & 73) === 0) {
912
+ throw createBuildRuntimeError(`Expected ${label} to be executable: ${filePath}`);
913
+ }
914
+ }
915
+ function getExecutableFileOutput2(projectRoot, filePath, label, fileFormat, fileArch) {
916
+ const fileOutput = execFileSync3("file", [relativeFromProjectRoot3(projectRoot, filePath)], {
917
+ cwd: projectRoot,
918
+ encoding: "utf8",
919
+ timeout: 2e4,
920
+ stdio: ["ignore", "pipe", "pipe"]
921
+ }).trim();
922
+ const hasExpectedFormat = fileFormat === "Mach-O 64-bit executable" ? fileOutput.includes("Mach-O 64-bit") && fileOutput.includes("executable") : fileOutput.includes(fileFormat);
923
+ if (!hasExpectedFormat || !fileOutput.includes(fileArch)) {
924
+ throw createBuildRuntimeError(`Unexpected ${label} architecture: ${fileOutput}`);
925
+ }
926
+ return fileOutput;
927
+ }
928
+ function verifyMacCodeSignature2(filePath, label) {
929
+ if (process.platform !== "darwin" || !label.startsWith("darwin-")) return;
930
+ try {
931
+ execFileSync3("codesign", ["--verify", "--verbose=2", filePath], {
932
+ encoding: "utf8",
933
+ timeout: 2e4,
934
+ stdio: ["ignore", "ignore", "pipe"]
935
+ });
936
+ } catch (error2) {
937
+ throw createBuildRuntimeError(
938
+ `Invalid ${label} code signature: ${error2 instanceof Error ? error2.message : String(error2)}`
939
+ );
940
+ }
941
+ }
942
+ function assertStagedGhCli(projectRoot) {
943
+ const binRoot = path4.join(resolveRuntimeStagePaths(projectRoot).electron.root, "bin");
944
+ const manifestPath = path4.join(binRoot, "gh-cli.json");
945
+ assertExists(manifestPath, "staged GitHub CLI manifest");
946
+ const manifest = JSON.parse(readFileSync3(manifestPath, "utf8"));
947
+ if (manifest.version !== 1 || !Array.isArray(manifest.targets)) {
948
+ throw createBuildRuntimeError(`Unexpected staged GitHub CLI manifest shape: ${manifestPath}`);
949
+ }
950
+ const contract = readGhCliContract(projectRoot);
951
+ if (manifest.ghVersion !== contract.ghVersion) {
952
+ throw createBuildRuntimeError(
953
+ `GitHub CLI manifest version mismatch: expected ${contract.ghVersion}, found ${manifest.ghVersion}`
954
+ );
955
+ }
956
+ for (const target of contract.targets) {
957
+ const ghPath = path4.join(binRoot, target.runtimeKey, "gh");
958
+ const label = `${target.runtimeKey}/gh`;
959
+ assertExecutable3(ghPath, label);
960
+ const fileOutput = getExecutableFileOutput2(
961
+ projectRoot,
962
+ ghPath,
963
+ label,
964
+ target.fileFormat ?? "Mach-O 64-bit executable",
965
+ target.fileArch
966
+ );
967
+ verifyMacCodeSignature2(ghPath, label);
968
+ const manifestEntry = manifest.targets.find(
969
+ (entry) => entry.runtimeKey === target.runtimeKey && entry.tool === "gh"
970
+ );
971
+ if (!manifestEntry) {
972
+ throw createBuildRuntimeError(`GitHub CLI manifest is missing ${target.runtimeKey}/gh`);
973
+ }
974
+ const expectedPath = relativeFromProjectRoot3(projectRoot, ghPath);
975
+ if (manifestEntry.path !== expectedPath) {
976
+ throw createBuildRuntimeError(
977
+ `GitHub CLI manifest path mismatch for ${target.runtimeKey}/gh: expected ${expectedPath}, found ${manifestEntry.path}`
978
+ );
979
+ }
980
+ if (manifestEntry.sha256 !== hashFile3(ghPath)) {
981
+ throw createBuildRuntimeError(`GitHub CLI manifest hash mismatch for ${target.runtimeKey}/gh`);
982
+ }
983
+ if (manifestEntry.size !== statSync3(ghPath).size) {
984
+ throw createBuildRuntimeError(`GitHub CLI manifest size mismatch for ${target.runtimeKey}/gh`);
985
+ }
986
+ if (manifestEntry.fileOutput !== fileOutput) {
987
+ throw createBuildRuntimeError(
988
+ `GitHub CLI manifest file output mismatch for ${target.runtimeKey}/gh`
989
+ );
990
+ }
991
+ const archiveName = ghArchiveName(
992
+ contract.ghVersion,
993
+ target.archivePlatform,
994
+ target.archiveExtension
995
+ );
996
+ const expectedUrl = `https://github.com/cli/cli/releases/download/v${contract.ghVersion}/${archiveName}`;
997
+ const source = manifestEntry.source;
998
+ if (!source || source.version !== contract.ghVersion || source.archiveName !== archiveName || source.archiveSha256 !== target.archiveSha256 || source.url !== expectedUrl) {
999
+ throw createBuildRuntimeError(
1000
+ `GitHub CLI manifest source mismatch for ${target.runtimeKey}/gh`
1001
+ );
1002
+ }
1003
+ }
1004
+ }
1005
+ function assertPackagedProviderBinaries(projectRoot) {
1006
+ try {
1007
+ validateDeusRuntime({
1008
+ projectRoot,
1009
+ log: () => void 0,
1010
+ verifyRunnable: process.env.DEUS_VERIFY_RUNTIME_RUNNABLE === "1"
1011
+ });
1012
+ } catch (error2) {
1013
+ throw createBuildRuntimeError(
1014
+ `Native runtime validation failed: ${error2 instanceof Error ? error2.message : String(error2)}`
1015
+ );
1016
+ }
1017
+ try {
1018
+ validateStagedAgentClis({ projectRoot, log: () => void 0, verifyRunnable: false });
1019
+ } catch (error2) {
1020
+ throw createBuildRuntimeError(
1021
+ `Staged agent CLI validation failed: ${error2 instanceof Error ? error2.message : String(error2)}`
1022
+ );
1023
+ }
1024
+ assertStagedGhCli(projectRoot);
1025
+ }
168
1026
  function assertNotStale(projectRoot, filePath, label, sourcePath, sourceLabel) {
169
- if (statSync(filePath).mtimeMs < statSync(sourcePath).mtimeMs) {
1027
+ if (statSync3(filePath).mtimeMs < statSync3(sourcePath).mtimeMs) {
170
1028
  throw createBuildRuntimeError(
171
- `${label} is stale: ${relativeFromProjectRoot(projectRoot, filePath)} is older than ${relativeFromProjectRoot(projectRoot, sourcePath)} (${sourceLabel})`
1029
+ `${label} is stale: ${relativeFromProjectRoot3(projectRoot, filePath)} is older than ${relativeFromProjectRoot3(projectRoot, sourcePath)} (${sourceLabel})`
172
1030
  );
173
1031
  }
174
1032
  }
@@ -183,12 +1041,8 @@ function buildExpectedManifest(projectRoot) {
183
1041
  },
184
1042
  bundles: {
185
1043
  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)
1044
+ backend: relativeFromProjectRoot3(projectRoot, stagePaths.common.backendBundle),
1045
+ agentServer: relativeFromProjectRoot3(projectRoot, stagePaths.common.agentServerBundle)
192
1046
  }
193
1047
  },
194
1048
  nodeRuntimeDependencies: CLI_RUNTIME_DEPENDENCIES
@@ -196,19 +1050,17 @@ function buildExpectedManifest(projectRoot) {
196
1050
  }
197
1051
  function validateRuntimeStage(options = {}) {
198
1052
  const log = options.log ?? console.log;
199
- const projectRoot = options.projectRoot ?? defaultProjectRoot;
1053
+ const projectRoot = options.projectRoot ?? defaultProjectRoot3;
200
1054
  const stagePaths = resolveRuntimeStagePaths(projectRoot);
201
1055
  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")
1056
+ backendBundle: path4.join(projectRoot, "apps", "backend", "dist", "server.bundled.cjs"),
1057
+ agentServerBundle: path4.join(projectRoot, "apps", "agent-server", "dist", "index.bundled.cjs")
204
1058
  };
205
1059
  assertExists(sources.backendBundle, "runtime source bundle (backend)");
206
1060
  assertExists(sources.agentServerBundle, "runtime source bundle (agent-server)");
207
1061
  assertExists(stagePaths.manifest, "staged runtime manifest");
208
1062
  assertExists(stagePaths.common.backendBundle, "staged common backend bundle");
209
1063
  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
1064
  const manifest = readManifest(stagePaths.manifest);
213
1065
  const expectedManifest = buildExpectedManifest(projectRoot);
214
1066
  if (JSON.stringify(manifest) !== JSON.stringify(expectedManifest)) {
@@ -223,13 +1075,6 @@ function validateRuntimeStage(options = {}) {
223
1075
  sources.backendBundle,
224
1076
  "backend source bundle"
225
1077
  );
226
- assertNotStale(
227
- projectRoot,
228
- stagePaths.electron.backendBundle,
229
- "staged electron backend bundle",
230
- sources.backendBundle,
231
- "backend source bundle"
232
- );
233
1078
  assertNotStale(
234
1079
  projectRoot,
235
1080
  stagePaths.common.agentServerBundle,
@@ -237,29 +1082,23 @@ function validateRuntimeStage(options = {}) {
237
1082
  sources.agentServerBundle,
238
1083
  "agent-server source bundle"
239
1084
  );
240
- assertNotStale(
241
- projectRoot,
242
- stagePaths.electron.agentServerBundle,
243
- "staged electron agent-server bundle",
244
- sources.agentServerBundle,
245
- "agent-server source bundle"
1085
+ const latestSourceMtime2 = Math.max(
1086
+ statSync3(sources.backendBundle).mtimeMs,
1087
+ statSync3(sources.agentServerBundle).mtimeMs
246
1088
  );
247
- const latestSourceMtime = Math.max(
248
- statSync(sources.backendBundle).mtimeMs,
249
- statSync(sources.agentServerBundle).mtimeMs
250
- );
251
- if (statSync(stagePaths.manifest).mtimeMs < latestSourceMtime) {
1089
+ if (statSync3(stagePaths.manifest).mtimeMs < latestSourceMtime2) {
252
1090
  throw createBuildRuntimeError(
253
- `Staged runtime manifest is stale: ${relativeFromProjectRoot(projectRoot, stagePaths.manifest)} is older than the source bundles`
1091
+ `Staged runtime manifest is stale: ${relativeFromProjectRoot3(projectRoot, stagePaths.manifest)} is older than the source bundles`
254
1092
  );
255
1093
  }
1094
+ assertPackagedProviderBinaries(projectRoot);
256
1095
  log(
257
- `\u2713 Staged runtime ready for packaging (${relativeFromProjectRoot(projectRoot, stagePaths.root)})`
1096
+ `\u2713 Staged runtime ready for packaging (${relativeFromProjectRoot3(projectRoot, stagePaths.root)})`
258
1097
  );
259
1098
  return manifest;
260
1099
  }
261
- var entryPath = process.argv[1] ? path2.resolve(process.argv[1]) : null;
262
- if (entryPath === fileURLToPath(import.meta.url)) {
1100
+ var entryPath = process.argv[1] ? path4.resolve(process.argv[1]) : null;
1101
+ if (entryPath === fileURLToPath3(import.meta.url)) {
263
1102
  try {
264
1103
  validateRuntimeStage();
265
1104
  } catch (error2) {
@@ -314,7 +1153,7 @@ var sym = {
314
1153
  arrow: isUnicode ? "\u2192" : "->",
315
1154
  diamond: isUnicode ? "\u25C6" : "*",
316
1155
  pointer: isUnicode ? "\u276F" : ">",
317
- info: isUnicode ? "\u2139" : "i",
1156
+ info: "i",
318
1157
  warning: isUnicode ? "\u26A0" : "!",
319
1158
  bullet: isUnicode ? "\u2022" : "-",
320
1159
  // Box drawing
@@ -622,13 +1461,13 @@ function sleep(ms) {
622
1461
 
623
1462
  // src/config.ts
624
1463
  import {
625
- readFileSync as readFileSync2,
626
- writeFileSync,
627
- existsSync as existsSync2,
1464
+ readFileSync as readFileSync4,
1465
+ writeFileSync as writeFileSync3,
1466
+ existsSync as existsSync4,
628
1467
  unlinkSync,
629
1468
  renameSync,
630
- mkdirSync,
631
- chmodSync
1469
+ mkdirSync as mkdirSync3,
1470
+ chmodSync as chmodSync3
632
1471
  } from "node:fs";
633
1472
  import { join } from "node:path";
634
1473
  import { homedir, platform } from "node:os";
@@ -655,10 +1494,10 @@ function getServerInfoPath() {
655
1494
  return join(getConfigDir(), "server.json");
656
1495
  }
657
1496
  function loadConfig() {
658
- const path3 = getConfigPath();
659
- if (!existsSync2(path3)) return { ...DEFAULT_CONFIG };
1497
+ const path5 = getConfigPath();
1498
+ if (!existsSync4(path5)) return { ...DEFAULT_CONFIG };
660
1499
  try {
661
- const raw = readFileSync2(path3, "utf-8");
1500
+ const raw = readFileSync4(path5, "utf-8");
662
1501
  const parsed = JSON.parse(raw);
663
1502
  return { ...DEFAULT_CONFIG, ...parsed };
664
1503
  } catch {
@@ -667,19 +1506,19 @@ function loadConfig() {
667
1506
  }
668
1507
  function saveConfig(config) {
669
1508
  const dir = getConfigDir();
670
- mkdirSync(dir, { recursive: true });
671
- const path3 = getConfigPath();
672
- const tmp = path3 + ".tmp." + randomBytes(4).toString("hex");
1509
+ mkdirSync3(dir, { recursive: true });
1510
+ const path5 = getConfigPath();
1511
+ const tmp = path5 + ".tmp." + randomBytes(4).toString("hex");
673
1512
  try {
674
- writeFileSync(tmp, JSON.stringify(config, null, 2) + "\n", "utf-8");
675
- chmodSync(tmp, 384);
676
- renameSync(tmp, path3);
1513
+ writeFileSync3(tmp, JSON.stringify(config, null, 2) + "\n", "utf-8");
1514
+ chmodSync3(tmp, 384);
1515
+ renameSync(tmp, path5);
677
1516
  } catch {
678
1517
  try {
679
1518
  unlinkSync(tmp);
680
1519
  } catch {
681
1520
  }
682
- throw new Error(`Failed to save config to ${path3}`);
1521
+ throw new Error(`Failed to save config to ${path5}`);
683
1522
  }
684
1523
  }
685
1524
  function hasCompletedOnboarding() {
@@ -687,16 +1526,16 @@ function hasCompletedOnboarding() {
687
1526
  }
688
1527
  function writeServerInfo(info2) {
689
1528
  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);
1529
+ mkdirSync3(dir, { recursive: true });
1530
+ const path5 = getServerInfoPath();
1531
+ writeFileSync3(path5, JSON.stringify(info2, null, 2) + "\n", "utf-8");
1532
+ chmodSync3(path5, 384);
694
1533
  }
695
1534
  function readServerInfo() {
696
- const path3 = getServerInfoPath();
697
- if (!existsSync2(path3)) return null;
1535
+ const path5 = getServerInfoPath();
1536
+ if (!existsSync4(path5)) return null;
698
1537
  try {
699
- const raw = readFileSync2(path3, "utf-8");
1538
+ const raw = readFileSync4(path5, "utf-8");
700
1539
  const info2 = JSON.parse(raw);
701
1540
  try {
702
1541
  process.kill(info2.pid, 0);
@@ -710,16 +1549,16 @@ function readServerInfo() {
710
1549
  }
711
1550
  }
712
1551
  function clearServerInfo() {
713
- const path3 = getServerInfoPath();
1552
+ const path5 = getServerInfoPath();
714
1553
  try {
715
- unlinkSync(path3);
1554
+ unlinkSync(path5);
716
1555
  } catch {
717
1556
  }
718
1557
  }
719
1558
 
720
1559
  // src/login.ts
721
- import { execSync, spawnSync } from "node:child_process";
722
- import { existsSync as existsSync3 } from "node:fs";
1560
+ import { execSync, spawnSync as spawnSync3 } from "node:child_process";
1561
+ import { existsSync as existsSync5 } from "node:fs";
723
1562
  import { join as join2 } from "node:path";
724
1563
  import { homedir as homedir2, platform as platform2 } from "node:os";
725
1564
 
@@ -934,7 +1773,7 @@ function getClaudeCliCandidates() {
934
1773
  }
935
1774
  function detectClaudeCli() {
936
1775
  for (const candidate of getClaudeCliCandidates()) {
937
- if (existsSync3(candidate)) {
1776
+ if (existsSync5(candidate)) {
938
1777
  try {
939
1778
  const version = execSync(`node "${candidate}" --version`, {
940
1779
  encoding: "utf-8",
@@ -978,7 +1817,7 @@ function isClaudeAuthenticated() {
978
1817
  join2(homedir2(), ".claude", "credentials.json")
979
1818
  ];
980
1819
  for (const p of credPaths) {
981
- if (existsSync3(p)) return true;
1820
+ if (existsSync5(p)) return true;
982
1821
  }
983
1822
  return false;
984
1823
  }
@@ -1062,7 +1901,7 @@ async function runClaudeLogin(cliPath) {
1062
1901
  blank();
1063
1902
  hint("Opening browser for authentication...");
1064
1903
  blank();
1065
- const result = spawnSync(cliPath, ["login"], {
1904
+ const result = spawnSync3(cliPath, ["login"], {
1066
1905
  stdio: "inherit",
1067
1906
  timeout: 12e4
1068
1907
  });
@@ -1082,7 +1921,7 @@ async function runClaudeLogin(cliPath) {
1082
1921
  async function installAndLogin() {
1083
1922
  blank();
1084
1923
  const s = spinner("Installing Claude Code CLI...");
1085
- const result = spawnSync("npm", ["install", "-g", "@anthropic-ai/claude-code"], {
1924
+ const result = spawnSync3("npm", ["install", "-g", "@anthropic-ai/claude-code"], {
1086
1925
  stdio: ["pipe", "pipe", "pipe"],
1087
1926
  timeout: 12e4
1088
1927
  });
@@ -1552,10 +2391,10 @@ function printQR(data, indent = 4) {
1552
2391
 
1553
2392
  // src/lib/http.ts
1554
2393
  import { request } from "node:http";
1555
- function httpGet(port, path3, timeoutMs = 3e3) {
2394
+ function httpGet(port, path5, timeoutMs = 3e3) {
1556
2395
  return new Promise((resolve2) => {
1557
2396
  const req = request(
1558
- { hostname: "localhost", port, path: path3, method: "GET", timeout: timeoutMs },
2397
+ { hostname: "localhost", port, path: path5, method: "GET", timeout: timeoutMs },
1559
2398
  (res) => {
1560
2399
  let body = "";
1561
2400
  res.on("data", (chunk) => body += chunk.toString());
@@ -1576,14 +2415,14 @@ function httpGet(port, path3, timeoutMs = 3e3) {
1576
2415
  req.end();
1577
2416
  });
1578
2417
  }
1579
- function httpPost(port, path3, body) {
2418
+ function httpPost(port, path5, body) {
1580
2419
  return new Promise((resolve2, reject) => {
1581
2420
  const payload = body ? JSON.stringify(body) : "";
1582
2421
  const req = request(
1583
2422
  {
1584
2423
  hostname: "localhost",
1585
2424
  port,
1586
- path: path3,
2425
+ path: path5,
1587
2426
  method: "POST",
1588
2427
  headers: {
1589
2428
  "Content-Type": "application/json",
@@ -1596,13 +2435,13 @@ function httpPost(port, path3, body) {
1596
2435
  res.on("data", (chunk) => data += chunk.toString());
1597
2436
  res.on("end", () => {
1598
2437
  if (res.statusCode !== 200) {
1599
- reject(new Error(`${path3} returned ${res.statusCode}: ${data}`));
2438
+ reject(new Error(`${path5} returned ${res.statusCode}: ${data}`));
1600
2439
  return;
1601
2440
  }
1602
2441
  try {
1603
2442
  resolve2(JSON.parse(data));
1604
2443
  } catch {
1605
- reject(new Error(`Invalid JSON from ${path3}`));
2444
+ reject(new Error(`Invalid JSON from ${path5}`));
1606
2445
  }
1607
2446
  });
1608
2447
  }
@@ -1610,7 +2449,7 @@ function httpPost(port, path3, body) {
1610
2449
  req.on("error", reject);
1611
2450
  req.on("timeout", () => {
1612
2451
  req.destroy();
1613
- reject(new Error(`Timeout: ${path3}`));
2452
+ reject(new Error(`Timeout: ${path5}`));
1614
2453
  });
1615
2454
  req.end(payload);
1616
2455
  });
@@ -1707,7 +2546,7 @@ async function pair() {
1707
2546
  }
1708
2547
 
1709
2548
  // src/start.ts
1710
- var __filename = fileURLToPath2(import.meta.url);
2549
+ var __filename = fileURLToPath4(import.meta.url);
1711
2550
  var __dirname = dirname(__filename);
1712
2551
  async function start(options) {
1713
2552
  const { dataDir } = options;
@@ -1728,7 +2567,7 @@ async function start(options) {
1728
2567
  const dbPath = resolveDataDir(dataDir);
1729
2568
  kv("Database", c.dim(dbPath));
1730
2569
  blank();
1731
- const children = [];
2570
+ let backendProcess = null;
1732
2571
  let status = null;
1733
2572
  let shuttingDown = false;
1734
2573
  let exitCode = 0;
@@ -1740,26 +2579,8 @@ async function start(options) {
1740
2579
  blank();
1741
2580
  const msg = gradientText("Shutting down...", [167, 139, 250], [34, 211, 238]);
1742
2581
  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);
2582
+ stopBackendProcess(backendProcess).finally(() => {
2583
+ backendProcess = null;
1763
2584
  clearServerInfo();
1764
2585
  blank();
1765
2586
  const bye = gradientText("Thanks for using Deus!", [167, 139, 250], [34, 211, 238]);
@@ -1774,46 +2595,38 @@ async function start(options) {
1774
2595
  if (config.auth_method === "api_key" && config.anthropic_api_key) {
1775
2596
  extraEnv.ANTHROPIC_API_KEY = config.anthropic_api_key;
1776
2597
  }
1777
- const s1 = spinner("Starting agent server...");
1778
- const agentServerUrl = await startProcess({
1779
- name: "agent-server",
2598
+ const s1 = spinner("Starting backend...");
2599
+ const started = await startBackendProcess({
1780
2600
  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",
1795
- command: nodeCmd,
1796
- args: [paths.backend],
2601
+ backendEntry: paths.backend,
2602
+ backendCwd: dirname(paths.backend),
2603
+ forceElectronRunAsNode: nodeCmd !== process.execPath,
1797
2604
  env: {
1798
- AGENT_SERVER_URL: agentServerUrl,
1799
2605
  DATABASE_PATH: dbPath,
2606
+ AGENT_SERVER_ENTRY: paths.agentServer,
2607
+ AGENT_SERVER_CWD: dirname(paths.agentServer),
1800
2608
  PORT: "0",
1801
2609
  ...extraEnv
1802
2610
  },
1803
- waitFor: /\[BACKEND_PORT\](\d+)/,
1804
- children
2611
+ onUnexpectedExit: (code, signal) => {
2612
+ if (shuttingDown) return;
2613
+ blank();
2614
+ warn(`backend exited unexpectedly${signal ? ` (${signal})` : code ? ` (code ${code})` : ""}`);
2615
+ shutdown(1);
2616
+ }
1805
2617
  });
1806
- if (!backendPort) {
1807
- s2.fail("Backend failed to start");
2618
+ if (!started) {
2619
+ s1.fail("Runtime failed to start");
1808
2620
  shutdown(1);
1809
2621
  return;
1810
2622
  }
1811
- s2.succeed(`Backend ${c.dim("ready")}`);
1812
- const port = parseInt(backendPort, 10);
2623
+ backendProcess = started.process;
2624
+ s1.succeed(`Runtime ${c.dim("ready")}`);
2625
+ const port = started.backendPort;
1813
2626
  writeServerInfo({
1814
2627
  pid: process.pid,
1815
2628
  backendPort: port,
1816
- agentServerUrl,
2629
+ agentServerUrl: "managed-by-backend",
1817
2630
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
1818
2631
  });
1819
2632
  blank();
@@ -1847,24 +2660,13 @@ async function start(options) {
1847
2660
  const elapsed = formatUptime(Date.now() - startedAt.getTime());
1848
2661
  return `${c.dim(`Running for ${elapsed}`)} ${c.dim(`${sym.bullet} Ctrl+C to stop`)}`;
1849
2662
  }, 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
2663
  await new Promise(() => {
1862
2664
  });
1863
2665
  }
1864
2666
  function resolveBundlePaths() {
1865
2667
  const cliRoot = resolve(__dirname, "..");
1866
2668
  const bundledDir = join3(cliRoot, "bundles");
1867
- if (existsSync4(join3(bundledDir, "agent-server.bundled.cjs"))) {
2669
+ if (existsSync6(join3(bundledDir, "agent-server.bundled.cjs"))) {
1868
2670
  return {
1869
2671
  agentServer: join3(bundledDir, "agent-server.bundled.cjs"),
1870
2672
  backend: join3(bundledDir, "server.bundled.cjs")
@@ -1893,7 +2695,7 @@ function resolveDataDir(customDir) {
1893
2695
  appData: process.env.APPDATA,
1894
2696
  xdgDataHome: process.env.XDG_DATA_HOME
1895
2697
  });
1896
- mkdirSync2(dir, { recursive: true });
2698
+ mkdirSync4(dir, { recursive: true });
1897
2699
  return join3(dir, DEUS_DB_FILENAME);
1898
2700
  }
1899
2701
  function resolveNodeBinary() {
@@ -1903,7 +2705,7 @@ function resolveNodeBinary() {
1903
2705
  `node -e "try { console.log(require('electron')) } catch { process.exit(1) }"`,
1904
2706
  { encoding: "utf-8", timeout: 5e3, stdio: ["pipe", "pipe", "pipe"] }
1905
2707
  ).trim();
1906
- if (electronPath && existsSync4(electronPath)) {
2708
+ if (electronPath && existsSync6(electronPath)) {
1907
2709
  try {
1908
2710
  execSync2(
1909
2711
  `node -e "const D = require('better-sqlite3'); const d = new D(':memory:'); d.close()"`,
@@ -1918,18 +2720,18 @@ function resolveNodeBinary() {
1918
2720
  }
1919
2721
  return process.execPath;
1920
2722
  }
1921
- async function startProcess(opts) {
1922
- const { name, command, args, env, waitFor, children, timeoutMs = 15e3 } = opts;
2723
+ async function startBackendProcess(opts) {
2724
+ const { command, backendEntry, backendCwd, env, forceElectronRunAsNode, onUnexpectedExit } = opts;
1923
2725
  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, {
2726
+ const child = spawn2(command, [backendEntry], {
2727
+ cwd: backendCwd,
1929
2728
  stdio: ["ignore", "pipe", "pipe"],
1930
- env: { ...process.env, ...processEnv, ...env }
2729
+ env: {
2730
+ ...process.env,
2731
+ ...forceElectronRunAsNode ? { ELECTRON_RUN_AS_NODE: "1" } : {},
2732
+ ...env
2733
+ }
1931
2734
  });
1932
- children.push({ process: child, name });
1933
2735
  let buffer = "";
1934
2736
  let resolved = false;
1935
2737
  const timeout = setTimeout(() => {
@@ -1938,50 +2740,70 @@ async function startProcess(opts) {
1938
2740
  child.kill("SIGTERM");
1939
2741
  resolve2(null);
1940
2742
  }
1941
- }, timeoutMs);
1942
- function onStdout(data) {
2743
+ }, 3e4);
2744
+ child.stdout?.on("data", (data) => {
2745
+ process.stdout.write(data);
1943
2746
  buffer += data.toString();
1944
- const match = buffer.match(waitFor);
2747
+ const match = buffer.match(/^\[BACKEND_PORT\](\d+)$/m);
1945
2748
  if (match && !resolved) {
1946
2749
  resolved = true;
1947
2750
  clearTimeout(timeout);
1948
- child.stdout?.removeListener("data", onStdout);
1949
- buffer = "";
1950
- resolve2(match[1]);
2751
+ resolve2({ process: child, backendPort: parseInt(match[1], 10) });
1951
2752
  }
1952
- }
1953
- child.stdout?.on("data", onStdout);
1954
- child.on("exit", () => {
2753
+ });
2754
+ child.stderr?.on("data", (data) => process.stderr.write(data));
2755
+ child.on("exit", (code, signal) => {
1955
2756
  if (!resolved) {
1956
2757
  resolved = true;
1957
2758
  clearTimeout(timeout);
1958
2759
  resolve2(null);
2760
+ return;
1959
2761
  }
2762
+ onUnexpectedExit(code, signal);
1960
2763
  });
1961
2764
  });
1962
2765
  }
2766
+ function stopBackendProcess(child) {
2767
+ if (!child || child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
2768
+ return new Promise((resolve2) => {
2769
+ let finished = false;
2770
+ const finish = () => {
2771
+ if (finished) return;
2772
+ finished = true;
2773
+ clearTimeout(forceTimer);
2774
+ resolve2();
2775
+ };
2776
+ child.once("exit", finish);
2777
+ child.kill("SIGTERM");
2778
+ const forceTimer = setTimeout(() => {
2779
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
2780
+ }, 5e3);
2781
+ });
2782
+ }
1963
2783
 
1964
2784
  // 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";
2785
+ import { execFileSync as execFileSync4, execSync as execSync3, spawn as spawn3 } from "node:child_process";
2786
+ import {
2787
+ chmodSync as chmodSync4,
2788
+ copyFileSync,
2789
+ createWriteStream,
2790
+ existsSync as existsSync7,
2791
+ mkdirSync as mkdirSync5,
2792
+ unlinkSync as unlinkSync2
2793
+ } from "node:fs";
1967
2794
  import { join as join4 } from "node:path";
1968
2795
  import { tmpdir, platform as platform3, arch, homedir as homedir4 } from "node:os";
1969
2796
  import { get } from "node:https";
1970
2797
  var GITHUB_REPO = "zvadaadam/deus-machine";
1971
2798
  var INSTALL_PATHS = {
1972
2799
  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
2800
  linux: [`${homedir4()}/.local/bin/Deus.AppImage`, "/usr/local/bin/Deus.AppImage"]
1978
2801
  };
1979
2802
  function hasDisplay() {
1980
2803
  const os = platform3();
1981
- if (process.env.CI || process.env.DOCKER || existsSync5("/.dockerenv")) return false;
2804
+ if (process.env.CI || process.env.DOCKER || existsSync7("/.dockerenv")) return false;
1982
2805
  if (process.env.SSH_CONNECTION || process.env.SSH_TTY) return false;
1983
2806
  if (os === "darwin") return true;
1984
- if (os === "win32") return true;
1985
2807
  if (os === "linux") return !!(process.env.DISPLAY || process.env.WAYLAND_DISPLAY);
1986
2808
  return false;
1987
2809
  }
@@ -1989,7 +2811,7 @@ function findInstalledApp() {
1989
2811
  const os = platform3();
1990
2812
  const paths = INSTALL_PATHS[os] || [];
1991
2813
  for (const p of paths) {
1992
- if (p && existsSync5(p)) return p;
2814
+ if (p && existsSync7(p)) return p;
1993
2815
  }
1994
2816
  return null;
1995
2817
  }
@@ -1997,18 +2819,43 @@ function launchDesktop(appPath) {
1997
2819
  const os = platform3();
1998
2820
  switch (os) {
1999
2821
  case "darwin":
2000
- spawn2("open", [appPath], { detached: true, stdio: "ignore" }).unref();
2822
+ spawn3("open", [appPath], { detached: true, stdio: "ignore" }).unref();
2001
2823
  break;
2002
- case "win32":
2003
2824
  case "linux":
2004
- spawn2(appPath, [], { detached: true, stdio: "ignore" }).unref();
2825
+ spawn3(appPath, [], {
2826
+ detached: true,
2827
+ stdio: "ignore",
2828
+ env: {
2829
+ ...process.env,
2830
+ ...hasFuse2() ? {} : { APPIMAGE_EXTRACT_AND_RUN: "1" }
2831
+ }
2832
+ }).unref();
2005
2833
  break;
2006
2834
  }
2007
2835
  }
2836
+ function hasFuse2() {
2837
+ const commonLibPaths = [
2838
+ "/lib/x86_64-linux-gnu/libfuse.so.2",
2839
+ "/usr/lib/x86_64-linux-gnu/libfuse.so.2",
2840
+ "/lib/aarch64-linux-gnu/libfuse.so.2",
2841
+ "/usr/lib/aarch64-linux-gnu/libfuse.so.2",
2842
+ "/usr/lib64/libfuse.so.2",
2843
+ "/usr/lib/libfuse.so.2"
2844
+ ];
2845
+ if (commonLibPaths.some((libPath) => existsSync7(libPath))) return true;
2846
+ try {
2847
+ return execSync3("ldconfig -p", { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }).split("\n").some((line) => line.includes("libfuse.so.2"));
2848
+ } catch {
2849
+ return false;
2850
+ }
2851
+ }
2852
+ function isOnPath(dir) {
2853
+ return (process.env.PATH ?? "").split(":").filter(Boolean).includes(dir);
2854
+ }
2008
2855
  function replaceInstalledMacApp(appPath, destPath) {
2009
2856
  const stagedPath = `${destPath}.staged`;
2010
2857
  const backupPath = `${destPath}.backup`;
2011
- const hadExistingInstall = existsSync5(destPath);
2858
+ const hadExistingInstall = existsSync7(destPath);
2012
2859
  execSync3(`rm -rf "${stagedPath}" "${backupPath}"`, { stdio: "pipe" });
2013
2860
  execSync3(`ditto "${appPath}" "${stagedPath}"`, { stdio: "pipe" });
2014
2861
  if (hadExistingInstall) {
@@ -2021,7 +2868,7 @@ function replaceInstalledMacApp(appPath, destPath) {
2021
2868
  }
2022
2869
  } catch (error2) {
2023
2870
  execSync3(`rm -rf "${stagedPath}"`, { stdio: "pipe" });
2024
- if (hadExistingInstall && existsSync5(backupPath) && !existsSync5(destPath)) {
2871
+ if (hadExistingInstall && existsSync7(backupPath) && !existsSync7(destPath)) {
2025
2872
  execSync3(`mv "${backupPath}" "${destPath}"`, { stdio: "pipe" });
2026
2873
  }
2027
2874
  throw error2;
@@ -2035,7 +2882,7 @@ async function installDesktop(options) {
2035
2882
  if (!assetPattern) {
2036
2883
  error(`Unsupported platform: ${os} ${cpuArch}`);
2037
2884
  blank();
2038
- hint("Supported: macOS (arm64/x64), Windows (x64), Linux (x64)");
2885
+ hint("Supported: macOS (arm64/x64), Linux (x64)");
2039
2886
  hint(`Or run ${c.cyan("deus start")} to run as a headless server.`);
2040
2887
  blank();
2041
2888
  process.exit(1);
@@ -2067,17 +2914,26 @@ async function installDesktop(options) {
2067
2914
  process.exit(1);
2068
2915
  }
2069
2916
  const downloadDir = join4(tmpdir(), "deus-installer");
2070
- mkdirSync3(downloadDir, { recursive: true });
2917
+ mkdirSync5(downloadDir, { recursive: true });
2071
2918
  const downloadPath = join4(downloadDir, asset.name);
2072
2919
  await downloadFile(asset.browser_download_url, downloadPath);
2073
2920
  const s3 = spinner("Installing...");
2074
- const installed = await installForPlatform(os, downloadPath, s3);
2921
+ const installedPath = await installForPlatform(os, downloadPath, s3);
2075
2922
  try {
2076
2923
  unlinkSync2(downloadPath);
2077
2924
  } catch {
2078
2925
  }
2079
- if (installed) {
2926
+ if (installedPath) {
2080
2927
  blank();
2928
+ success("Launching Deus...");
2929
+ if (os === "linux") {
2930
+ const installDir = join4(homedir4(), ".local", "bin");
2931
+ if (!isOnPath(installDir)) {
2932
+ info(
2933
+ 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.`
2934
+ );
2935
+ }
2936
+ }
2081
2937
  success("Deus is ready!");
2082
2938
  blank();
2083
2939
  }
@@ -2087,15 +2943,11 @@ function getAssetPattern(os, cpuArch) {
2087
2943
  case "darwin": {
2088
2944
  const archSuffix = cpuArch === "arm64" ? "arm64" : "x64";
2089
2945
  return {
2090
- matcher: (name) => name.endsWith(".dmg") && name.includes(archSuffix),
2946
+ // electron-builder names Intel DMGs without an architecture suffix.
2947
+ matcher: (name) => name.endsWith(".dmg") && (cpuArch === "arm64" ? name.includes("arm64") : !name.includes("arm64")),
2091
2948
  description: `macOS DMG (${archSuffix})`
2092
2949
  };
2093
2950
  }
2094
- case "win32":
2095
- return {
2096
- matcher: (name) => name.endsWith(".exe") && !name.includes("blockmap"),
2097
- description: "Windows installer (exe)"
2098
- };
2099
2951
  case "linux":
2100
2952
  return {
2101
2953
  matcher: (name) => name.endsWith(".AppImage"),
@@ -2213,24 +3065,25 @@ async function installForPlatform(os, filePath, s) {
2213
3065
  mountPoint = mountOutput.split("\n").filter((line) => line.includes("/Volumes/")).map((line) => line.trim().split(" ").pop()?.trim()).find(Boolean);
2214
3066
  if (!mountPoint) {
2215
3067
  s.fail("Could not mount disk image");
2216
- return false;
3068
+ return null;
2217
3069
  }
2218
3070
  const appName = "Deus.app";
2219
3071
  const appPath = `${mountPoint}/${appName}`;
2220
3072
  const destPath = `/Applications/${appName}`;
2221
- if (existsSync5(appPath)) {
3073
+ if (existsSync7(appPath)) {
2222
3074
  replaceInstalledMacApp(appPath, destPath);
2223
3075
  s.succeed(`Installed to ${c.dim("/Applications/Deus.app")}`);
2224
3076
  launchDesktop(destPath);
3077
+ return destPath;
2225
3078
  } else {
2226
3079
  s.warn("DMG mounted \u2014 drag Deus to Applications to finish");
2227
3080
  }
2228
- return true;
3081
+ return null;
2229
3082
  } catch {
2230
3083
  s.fail("Auto-install failed \u2014 opening DMG manually");
2231
- execSync3(`open "${filePath}"`);
3084
+ execFileSync4("open", [filePath], { stdio: "ignore" });
2232
3085
  hint("Drag Deus.app to Applications, then launch it from Applications.");
2233
- return false;
3086
+ return null;
2234
3087
  } finally {
2235
3088
  if (mountPoint) {
2236
3089
  try {
@@ -2240,30 +3093,27 @@ async function installForPlatform(os, filePath, s) {
2240
3093
  }
2241
3094
  }
2242
3095
  }
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
3096
  case "linux": {
2250
3097
  try {
2251
- execSync3(`chmod +x "${filePath}"`);
2252
3098
  const installDir = join4(homedir4(), ".local", "bin");
2253
- mkdirSync3(installDir, { recursive: true });
3099
+ mkdirSync5(installDir, { recursive: true });
2254
3100
  const destPath = join4(installDir, "Deus.AppImage");
2255
- execSync3(`cp "${filePath}" "${destPath}"`);
3101
+ copyFileSync(filePath, destPath);
3102
+ chmodSync4(destPath, 493);
2256
3103
  s.succeed(`Installed to ${c.dim(destPath)}`);
3104
+ if (!hasFuse2()) {
3105
+ info("libfuse2 not found; launching AppImage with APPIMAGE_EXTRACT_AND_RUN=1.");
3106
+ }
2257
3107
  launchDesktop(destPath);
2258
- return true;
3108
+ return destPath;
2259
3109
  } catch {
2260
3110
  s.fail("Installation failed \u2014 check permissions");
2261
- return false;
3111
+ return null;
2262
3112
  }
2263
3113
  }
2264
3114
  default:
2265
3115
  s.fail("Unsupported platform");
2266
- return false;
3116
+ return null;
2267
3117
  }
2268
3118
  }
2269
3119
 
@@ -2336,6 +3186,94 @@ async function showStatus() {
2336
3186
  blank();
2337
3187
  }
2338
3188
 
3189
+ // src/feedback.ts
3190
+ import { randomUUID } from "node:crypto";
3191
+ var HIVENET_ENDPOINT = "https://hivenet.app/v1/feedback";
3192
+ function buildFeedbackPayload(message, version, opts = {}) {
3193
+ return {
3194
+ v: 1,
3195
+ to: "deus",
3196
+ category: opts.category ?? "cli",
3197
+ feedback: message,
3198
+ ...opts.subject ? { subject: opts.subject } : {},
3199
+ thread: { id: opts.threadId ?? randomUUID().replaceAll("-", "") },
3200
+ client: { name: "deus-cli", version },
3201
+ consent: { telemetry: false }
3202
+ };
3203
+ }
3204
+ async function sendFeedback(message, version, opts = {}) {
3205
+ const trimmed = message.trim();
3206
+ if (!trimmed) {
3207
+ error("Feedback message is required.");
3208
+ blank();
3209
+ info("Tell the Deus team what you need \u2014 feature requests, confusing UX, broken flows:");
3210
+ hint(
3211
+ ` ${c.cyan('deus feedback "feature request: let me pin a workspace to the top of the sidebar"')}`
3212
+ );
3213
+ hint(
3214
+ ` ${c.cyan('deus feedback --subject "deus pair" "the QR code renders off-screen on small terminals"')}`
3215
+ );
3216
+ process.exitCode = 1;
3217
+ return;
3218
+ }
3219
+ const payload = buildFeedbackPayload(trimmed, version, opts);
3220
+ let response;
3221
+ try {
3222
+ response = await fetch(HIVENET_ENDPOINT, {
3223
+ method: "POST",
3224
+ headers: { "content-type": "application/json" },
3225
+ body: JSON.stringify(payload),
3226
+ signal: AbortSignal.timeout(1e4)
3227
+ });
3228
+ } catch {
3229
+ error("Could not reach hivenet.app \u2014 feedback not sent.");
3230
+ process.exitCode = 1;
3231
+ return;
3232
+ }
3233
+ if (!response.ok) {
3234
+ error(`Feedback submission failed (${response.status}).`);
3235
+ process.exitCode = 1;
3236
+ return;
3237
+ }
3238
+ const body = await response.json().catch(() => null) ?? {};
3239
+ success("Feedback sent to the Deus team.");
3240
+ const threadId = safe(body.thread?.id) || payload.thread.id;
3241
+ hint(
3242
+ `Thread: ${c.cyan(threadId)} \u2014 continue with ${c.cyan(`npx --yes hivenet@latest --to deus --resume ${threadId}`)}`
3243
+ );
3244
+ if (body.known_issue?.title) {
3245
+ blank();
3246
+ info(`Known issue: ${safe(body.known_issue.title)}`);
3247
+ if (body.known_issue.note) info(`Deus team: ${safe(body.known_issue.note)}`);
3248
+ }
3249
+ if (body.guidance) {
3250
+ blank();
3251
+ info(`Deus team: ${safe(body.guidance)}`);
3252
+ }
3253
+ if (body.ask?.prompt) {
3254
+ blank();
3255
+ info(`Deus asks: ${safe(body.ask.prompt)}`);
3256
+ if (body.ask.command) hint(`Answer (only if grounded): ${c.cyan(safe(body.ask.command))}`);
3257
+ }
3258
+ }
3259
+ function safe(value) {
3260
+ if (typeof value !== "string") return "";
3261
+ return value.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").trim();
3262
+ }
3263
+
3264
+ // src/args.ts
3265
+ function getCliCommandIndex(args) {
3266
+ return args.findIndex((arg) => !arg.startsWith("-"));
3267
+ }
3268
+ function getCliCommand(args) {
3269
+ const commandIndex = getCliCommandIndex(args);
3270
+ return commandIndex === -1 ? null : args[commandIndex];
3271
+ }
3272
+ function isGlobalVersionRequest(args) {
3273
+ if (getCliCommandIndex(args) !== -1) return false;
3274
+ return args.includes("--version") || args.includes("-v");
3275
+ }
3276
+
2339
3277
  // src/cli.ts
2340
3278
  function printHelp(version) {
2341
3279
  banner(version);
@@ -2350,6 +3288,7 @@ function printHelp(version) {
2350
3288
  console.log(` ${c.cyan("pair")} Generate a pairing code for remote access`);
2351
3289
  console.log(` ${c.cyan("login")} Configure AI agent authentication`);
2352
3290
  console.log(` ${c.cyan("status")} Show server info and connected devices`);
3291
+ console.log(` ${c.cyan("feedback")} Send feedback or a feature request to the Deus team`);
2353
3292
  blank();
2354
3293
  console.log(` ${c.bold("Options")} ${c.dim("(start):")}`);
2355
3294
  console.log(` ${c.cyan("--data-dir")} Directory for database and data files`);
@@ -2375,11 +3314,12 @@ function printHelp(version) {
2375
3314
  }
2376
3315
  async function main() {
2377
3316
  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;
3317
+ const commandIndex = getCliCommandIndex(args);
3318
+ const command = getCliCommand(args);
3319
+ const commandArgs = commandIndex === -1 ? args : args.slice(commandIndex + 1);
2380
3320
  const pkg = await Promise.resolve().then(() => (init_package(), package_exports));
2381
3321
  const version = pkg.default.version;
2382
- if (args.includes("--version") || args.includes("-v")) {
3322
+ if (isGlobalVersionRequest(args)) {
2383
3323
  console.log(version);
2384
3324
  process.exit(0);
2385
3325
  }
@@ -2387,7 +3327,7 @@ async function main() {
2387
3327
  printHelp(version);
2388
3328
  process.exit(0);
2389
3329
  }
2390
- const quickCommands = ["pair", "status", "login"];
3330
+ const quickCommands = ["pair", "status", "login", "feedback"];
2391
3331
  if (!command || !quickCommands.includes(command)) {
2392
3332
  await animatedBanner(version);
2393
3333
  }
@@ -2447,6 +3387,23 @@ async function main() {
2447
3387
  await showStatus();
2448
3388
  break;
2449
3389
  }
3390
+ // ── Feedback to the Deus team (Hivenet) ────────────────────────
3391
+ case "feedback": {
3392
+ const { values, positionals } = parseArgs({
3393
+ args: commandArgs,
3394
+ options: {
3395
+ subject: { type: "string" },
3396
+ category: { type: "string" }
3397
+ },
3398
+ allowPositionals: true,
3399
+ strict: false
3400
+ });
3401
+ await sendFeedback(positionals.join(" "), version, {
3402
+ subject: values.subject,
3403
+ category: values.category
3404
+ });
3405
+ break;
3406
+ }
2450
3407
  default:
2451
3408
  error(`Unknown command: ${c.bold(resolvedCommand)}`);
2452
3409
  blank();