@ours.network/install 1.2.1-nightly.2 → 1.2.1-nightly.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/GATEWAY_SETUP.md +178 -0
  2. package/README.md +337 -12
  3. package/ROOTLESS_PODMAN_VALIDATION.md +210 -0
  4. package/assets/Dockerfile +16 -12
  5. package/assets/Dockerfile.gateway +5 -0
  6. package/assets/docker-compose.yaml +21 -1
  7. package/assets/fleet-settings.example.json +48 -0
  8. package/assets/gateway-entrypoint.sh +37 -0
  9. package/assets/release-lock.json +1111 -4265
  10. package/assets/release.json +33 -19
  11. package/assets/scripts/build/build-common.mjs +1 -1
  12. package/assets/scripts/build/build-sdk.mjs +6 -1
  13. package/assets/scripts/maintenance/build-context.mjs +1 -1
  14. package/assets/scripts/maintenance/daemon-owner.mjs +15 -0
  15. package/assets/scripts/maintenance/docker-layout-conversion.mjs +7 -3
  16. package/assets/scripts/maintenance/release-graph.mjs +18 -1
  17. package/assets/scripts/maintenance/state-operation.mjs +4 -2
  18. package/assets/scripts/runtime/client-setup.mjs +3 -3
  19. package/assets/scripts/runtime/entrypoint.sh +1 -1
  20. package/assets/scripts/runtime/legacy-import.mjs +103 -0
  21. package/assets/sources.json +46 -28
  22. package/install.mjs +5 -1
  23. package/lib/build-transition.mjs +1 -0
  24. package/lib/client-cli.mjs +127 -0
  25. package/lib/container-engine.mjs +127 -0
  26. package/lib/docker-conversion-runtime.mjs +3 -2
  27. package/lib/docker-layout-installation.mjs +2 -1
  28. package/lib/docker-runtime-repair.mjs +152 -0
  29. package/lib/effects.mjs +276 -126
  30. package/lib/gateway-transition.mjs +87 -0
  31. package/lib/gateway.mjs +142 -0
  32. package/lib/legacy-migration.mjs +213 -0
  33. package/lib/legacy-state.mjs +205 -0
  34. package/lib/managed-cli.mjs +164 -0
  35. package/lib/orchestrate.mjs +114 -38
  36. package/lib/plan.mjs +22 -9
  37. package/lib/podman-preflight.mjs +40 -0
  38. package/lib/prompt.mjs +113 -119
  39. package/lib/server-onboarding.mjs +63 -16
  40. package/lib/setup-options.mjs +137 -35
  41. package/lib/setup.mjs +30 -16
  42. package/lib/target.mjs +24 -8
  43. package/lib/uninstall.mjs +2 -2
  44. package/lib/usage.mjs +9 -4
  45. package/lib/workspace-setup.mjs +83 -0
  46. package/package.json +4 -2
package/lib/effects.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import { qualifyPodman } from './podman-preflight.mjs';
2
+ import { engineName, bindPodman, runContainer, nativeBuildCommands } from './container-engine.mjs';
1
3
  // ours-install v3 — the real side effects.
2
4
  //
3
5
  // Every mutation the installer can perform lives here and nowhere else, behind
@@ -11,21 +13,24 @@
11
13
  // state-directory guard and the enable/reload. The installer never touches a
12
14
  // unit file or the service manager directly.
13
15
 
16
+ import { publishClientCli } from './client-cli.mjs';
14
17
  import { spawnSync, execFileSync } from 'node:child_process';
15
18
  import { chmodSync, closeSync, constants, cpSync, existsSync, fstatSync, lstatSync, openSync, readFileSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
16
19
  import { homedir, userInfo, platform as osPlatform, release as osRelease, arch as osArch } from 'node:os';
17
20
  import { fileURLToPath } from 'node:url';
18
21
  import { randomUUID, createHash } from 'node:crypto';
19
22
  import { dirname, join, resolve } from 'node:path';
20
- import { maintenanceServices, installationPaths, validateInstallation, consumerServiceState, unitNameForStateDir, launchdLabelForStateDir, messengerServicePlan, selectSourcePackages, resolveSourcePolicy, SERVER_SERVICES } from './plan.mjs';
21
- import { validateHostProfile } from './target.mjs';
23
+ import { clientPackageNames, maintenanceServices, installationPaths, validateInstallation, consumerServiceState, unitNameForStateDir, launchdLabelForStateDir, messengerServicePlan, selectSourcePackages, resolveSourcePolicy, SERVER_SERVICES } from './plan.mjs';
24
+ import { validateHostProfile, validateGatewayClientProfile } from './target.mjs';
25
+ import { serverBase, validateGatewayDiscovery, gatewayCompose, gatewayNginx, gatewayAddress } from './gateway.mjs';
22
26
  import { createServerOnboarding } from './server-onboarding.mjs';
23
27
  import { atomicWriteConfig, snapshotConfig, restoreConfig } from './config.mjs';
24
- import { askYesNo, askLine as askLineOnTty } from './prompt.mjs';
28
+ import { select as selectOnTty, multiselect as multiselectOnTty, askLine as askLineOnTty } from './prompt.mjs';
25
29
  import { classifyHarnessProbe } from './logic.mjs';
30
+ import { qualifyDockerRuntime, refreshDockerPolicyCopy } from './docker-runtime-repair.mjs';
26
31
  import { classifyStateDir } from './detect.mjs';
27
32
  import { BASE_RECORDS, CONTEXT, readBuildRecords, equalBuildRecords, initializeBuildMarker } from '../assets/scripts/maintenance/build-context.mjs';
28
- import { releaseBinding, verifyReleaseGraph, verifyRuntimeRelease } from '../assets/scripts/maintenance/release-graph.mjs';
33
+ import { hostCliPolicy, releaseBinding, verifyReleaseGraph, verifyRuntimeRelease } from '../assets/scripts/maintenance/release-graph.mjs';
29
34
 
30
35
  /** GET http://127.0.0.1:<port>/state-dir — the unauthenticated identity probe. */
31
36
  async function probePort(port, { timeoutMs = 1500 } = {}) {
@@ -399,7 +404,7 @@ export function realEffects({ write, ttyFd, env = process.env, home = homedir(),
399
404
  // invocation only and never to the installer's own process: a state
400
405
  // directory selected by one run must not leak into anything the operator
401
406
  // starts afterwards.
402
- run: async (cmd, args, { env: extraEnv = null, stream = false, cwd, sensitive = false, allowCodes = [] } = {}) => {
407
+ run: async (cmd, args, { env: extraEnv = null, stream = false, cwd, sensitive = false, allowCodes = [], timeout } = {}) => {
403
408
  // Always built from this layer's OWN env rather than left to spawnSync's
404
409
  // implicit inheritance, so what a child receives is a property of the
405
410
  // effects object a caller constructed and not of whatever ambient shell
@@ -410,6 +415,7 @@ export function realEffects({ write, ttyFd, env = process.env, home = homedir(),
410
415
  const executable = cmd === 'npm' ? npmBin : cmd;
411
416
  const r = spawnSync(executable, args, {
412
417
  cwd,
418
+ timeout,
413
419
  encoding: 'utf8',
414
420
  stdio: [...(stream ? ['ignore', 'inherit', 'inherit'] : ['ignore', 'pipe', 'pipe']), ...(installationLockFd === null ? [] : [installationLockFd])],
415
421
  env: childEnv,
@@ -444,7 +450,9 @@ export function realEffects({ write, ttyFd, env = process.env, home = homedir(),
444
450
  hasClaudePlugin,
445
451
  out: out ?? ((line) => process.stdout.write(`${line}\n`)),
446
452
  // Never called when assumeYes: the orchestrator takes the default itself.
447
- ask: async (prompt, def = false) => (ttyFd == null ? def : askYesNo(write, ttyFd, ` ${prompt} `, def)),
453
+ select: async (question, choices, def) => selectOnTty(write, ttyFd, question, choices, def),
454
+ multiselect: async (question, choices, defaults = []) => multiselectOnTty(write, ttyFd, question, choices, defaults),
455
+ ask: async (question, def = false) => selectOnTty(write, ttyFd, question, [{ value: true, label: 'Yes' }, { value: false, label: 'No' }], def),
448
456
  askLine: async (prompt, def = '') => (ttyFd == null ? def : askLineOnTty(write, ttyFd, ` ${prompt} `, def)),
449
457
  };
450
458
  return Object.assign(effects, networkEffects(effects));
@@ -532,6 +540,7 @@ export function networkEffects(effects) {
532
540
  const baseEnv = (record) => ({
533
541
  OURS_DAEMON_ID: record.instanceId,
534
542
  OURS_IMAGE: `${record.project}:runtime`,
543
+ OURS_GATEWAY_IMAGE: `${record.project}:gateway`,
535
544
  OURS_MAINTENANCE_IMAGE: `${record.project}:maintenance`,
536
545
  OURS_UID: String(record.uid ?? 1000), OURS_GID: String(record.gid ?? 1000),
537
546
  OURS_HOST_PORT: String(record.port ?? 3050),
@@ -543,14 +552,55 @@ export function networkEffects(effects) {
543
552
  'compose', '--project-directory', record.workDir, '--file', join(record.workDir,
544
553
  record.schema === 1 && existsSync(join(record.workDir, 'docker-compose.legacy.yaml'))
545
554
  ? 'docker-compose.legacy.yaml' : 'docker-compose.yaml'),
555
+ ...(record.gateway ? ['--file', join(record.workDir, 'docker-compose.gateway.yaml')] : []),
556
+ ...(engineName(record) === 'podman' ? ['--file', join(record.workDir, 'compose.podman.json')] : []),
546
557
  '--project-name', record.project, ...args,
547
558
  ];
548
- const compose = (record, args, options = {}) => effects.run('docker', composeArgs(record, args),
549
- { ...options, env: { ...baseEnv(record), ...options.env } });
559
+ const container = (record, args, options = {}) => runContainer(effects, record, args, options);
560
+ const compose = async (record, args, options = {}) => {
561
+ const selected = { ...options, env: { ...baseEnv(record), ...options.env } };
562
+ if (engineName(record) === 'podman' && args[0] === 'build') {
563
+ const result = await container(record, composeArgs(record, ['--profile', '*', 'config', '--format', 'json']), { env: selected.env });
564
+ for (const command of nativeBuildCommands(JSON.parse(result.stdout), args.slice(1), { ...env, ...selected.env })) await container(record, command, selected);
565
+ return { code: 0, stdout: '' };
566
+ }
567
+ if (engineName(record) === 'podman' && ['run', 'up'].includes(args[0])) {
568
+ const resolved = JSON.parse((await container(record, composeArgs(record, ['--profile', '*', 'config', '--format', 'json']), { env: selected.env })).stdout);
569
+ for (const [key, volume] of Object.entries(resolved.volumes ?? {})) {
570
+ if (volume.external) throw new Error('Unexpected external installation volume');
571
+ const name = volume.name ?? `${record.project}_${key}`;
572
+ const found = await container(record, ['volume', 'inspect', '--format', '{{json .}}', name], { allowCodes: [1] });
573
+ if (found.code === 1) continue;
574
+ const value = JSON.parse(found.stdout);
575
+ if (value.Name !== name || value.Labels?.['com.docker.compose.project'] !== record.project || value.Labels?.['com.docker.compose.volume'] !== key) throw new Error(`Refusing foreign volume: ${name}`);
576
+ }
577
+ }
578
+ // Compose run can implicitly build an absent administration image. Build
579
+ // its resolved target natively first, just like explicit build operations.
580
+ if (engineName(record) === 'podman' && args[0] === 'run') {
581
+ const resolved = JSON.parse((await container(record, composeArgs(record, ['--profile', '*', 'config', '--format', 'json']), { env: selected.env })).stdout);
582
+ const takesValue = new Set(['--name', '--entrypoint', '--env', '-e', '--user', '-u', '--workdir', '-w', '--volume', '-v', '--publish', '-p', '--label', '-l', '--pull']);
583
+ let name;
584
+ for (let i = 1; i < args.length; i++) {
585
+ if (takesValue.has(args[i])) { i++; continue; }
586
+ if (args[i].startsWith('-')) continue;
587
+ name = args[i]; break;
588
+ }
589
+ const service = resolved.services?.[name];
590
+ if (!service) throw new Error(`Unresolved Podman administration service: ${name}`);
591
+ if (service.build) {
592
+ const image = await container(record, ['image', 'inspect', service.image], { allowCodes: [1] });
593
+ if (image.code === 1) for (const command of nativeBuildCommands(resolved, [name], { ...env, ...selected.env })) await container(record, command, selected);
594
+ }
595
+ }
596
+ return container(record, composeArgs(record, args), selected);
597
+ };
550
598
  const dockerStartupError = async (record, service, cause) => {
551
599
  const args = ['logs', '--no-color', '--tail', '50', '--timestamps', service];
552
600
  const quote = value => `'${String(value).replaceAll("'", "'\\''")}'`;
553
- const command = `OURS_DAEMON_ID=${quote(record.instanceId)} docker ${composeArgs(record, args).map(quote).join(' ')}`;
601
+ const engine = engineName(record);
602
+ const prefix = engine === 'podman' ? ['--remote', '--url', `unix://${record.containerBinding.socket}`] : [];
603
+ const command = `OURS_DAEMON_ID=${quote(record.instanceId)} ${engine} ${[...prefix, ...composeArgs(record, args)].map(quote).join(' ')}`;
554
604
  let detail;
555
605
  try {
556
606
  const logs = await compose(record, args);
@@ -561,7 +611,7 @@ export function networkEffects(effects) {
561
611
  } catch {
562
612
  detail = 'Container logs could not be read.';
563
613
  }
564
- return new Error(`Docker service "${service}" failed to start or become healthy.\n${detail}\nStartup error: ${cause.message}\nInspect logs: ${command}`, { cause });
614
+ return new Error(`${engine === 'podman' ? 'Podman' : 'Docker'} service "${service}" failed to start or become healthy.\n${detail}\nStartup error: ${cause.message}\nInspect logs: ${command}`, { cause });
565
615
  };
566
616
  const bin = (record, name) => join(record.workDir, 'node_modules', '.bin', name);
567
617
  const localEnv = (record, service = 'daemon') => {
@@ -575,14 +625,15 @@ export function networkEffects(effects) {
575
625
  return { ...common, OURS_MESSENGER_STATE_DIR: state, ...(record.messengerIdentity ? { OURS_MESSENGER_IDENTITY: record.messengerIdentity } : {}), OURS_MESSENGER_PORT: String(record.messengerPort), OURS_MESSENGER_HOST: '127.0.0.1', OURS_MESSENGER_PUBLIC_ORIGIN: `http://127.0.0.1:${record.messengerPort}` };
576
626
  };
577
627
  const ownerCommand = (record, service, op, options = {}) => {
578
- const name = { daemon: 'ours', telegram: 'ours-tg-connector', cowork: 'ours-cowork' }[service];
579
- const args = service === 'daemon' ? ['daemon', op, ...(['install-service', 'uninstall-service'].includes(op) ? ['--yes'] : []), '--config', record.configPath, '--state-dir', installationPaths(record).daemon, '--json'] : [op];
628
+ const daemonBinary = existsSync(bin(record, 'ours-daemon')) ? 'ours-daemon' : 'ours';
629
+ const name = { daemon: daemonBinary, telegram: 'ours-tg-connector', cowork: 'ours-cowork' }[service];
630
+ const args = service === 'daemon' ? [...(daemonBinary === 'ours' ? ['daemon'] : []), op, ...(['install-service', 'uninstall-service'].includes(op) ? ['--yes'] : []), '--config', record.configPath, '--state-dir', installationPaths(record).daemon, '--json'] : [op];
580
631
  return effects.run(bin(record, name), args, { ...options, env: localEnv(record, service) });
581
632
  };
582
633
  const requireCleanContainerExit = async (record, selected) => {
583
634
  const containers = await compose(record, ['ps', '-aq', ...selected]);
584
635
  for (const id of containers.stdout.split(/\s+/).filter(Boolean)) {
585
- const result = await effects.run('docker', ['inspect', '--format', '{{json .State}}', id]);
636
+ const result = await container(record, ['inspect', '--format', '{{json .State}}', id]);
586
637
  const state = JSON.parse(result.stdout);
587
638
  if (state.Status !== 'exited' || state.ExitCode !== 0 || state.OOMKilled !== false || state.Dead !== false) {
588
639
  throw new Error('Selected source container did not stop cleanly; state operation refused');
@@ -616,7 +667,7 @@ export function networkEffects(effects) {
616
667
  return version;
617
668
  });
618
669
  },
619
- newInstallation(root, mode) {
670
+ newInstallation(root, mode, { containerEngine } = {}) {
620
671
  if (existsSync(root)) {
621
672
  privateDirectory(root);
622
673
  if (readdirSync(root).some(name => name !== '.operation.lock')) throw new Error('Installation root is not empty and has no selection record');
@@ -624,7 +675,7 @@ export function networkEffects(effects) {
624
675
  const instanceId = env.OURS_DAEMON_ID || randomUUID();
625
676
  if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(instanceId)) throw new Error('OURS_DAEMON_ID must be a lowercase UUID');
626
677
  const project = `ours-${createHash('sha256').update(root).digest('hex').slice(0, 16)}`;
627
- return { schema: 2, root, mode, instanceId, project, workDir: join(root, 'runtime'), configPath: installationPaths({ schema: 2, root }).config, sourcesPath: join(root, 'sources.json'), services: [...SERVER_SERVICES], port: 3050, coworkPort: 3052, messengerPort: 8420, messengerIdentity: env.OURS_MESSENGER_IDENTITY || null, uid: 1000, gid: 1000 };
678
+ return { schema: 2, root, mode, ...(containerEngine ? { containerEngine } : {}), instanceId, project, workDir: join(root, 'runtime'), configPath: installationPaths({ schema: 2, root }).config, sourcesPath: join(root, 'sources.json'), services: [...SERVER_SERVICES, ...(mode === 'docker' ? ['gateway'] : [])], ...(mode === 'docker' ? { gateway: { version: 1 } } : {}), port: 3050, coworkPort: 3052, messengerPort: 8420, messengerIdentity: env.OURS_MESSENGER_IDENTITY || null, uid: 1000, gid: 1000 };
628
679
  },
629
680
  async serverPreflight(record, operation, { existing, sourcePath = record.sourcesPath, sourceManifest, identityName } = {}) {
630
681
  if (existing) {
@@ -634,37 +685,55 @@ export function networkEffects(effects) {
634
685
  if (env.OURS_DAEMON_ID && env.OURS_DAEMON_ID !== record.instanceId) throw new Error('Conflicting instance ID');
635
686
  }
636
687
  if (record.mode === 'docker') {
637
- const nativeRoot = existing ? '/path/to/new-empty-directory' : record.root;
638
- const quotedRoot = `'${String(nativeRoot).replaceAll("'", "'\\''")}'`;
639
- const quotedName = `'${String(identityName ?? record.messengerIdentity ?? 'Your Name').replaceAll("'", "'\\''")}'`;
640
- const recovery = [
641
- 'Please install Docker Desktop on macOS/Windows, or Docker Engine with the Compose plugin on Linux, and start Docker before retrying.',
642
- 'Docker is recommended for macOS and Windows.',
643
- `Alternatively, use native installation: ours-install server install --mode packages --state-dir ${quotedRoot} --identity-name ${quotedName}`,
644
- 'Native mode requires systemd user services on Linux/WSL or a launchd GUI session on macOS.',
645
- ...(existing ? ['Keep this existing Docker installation in Docker mode; use a separate empty directory for a new native installation.'] : []),
646
- ].join('\n');
647
- try {
648
- await effects.run('docker', ['info', '--format', '{{.ServerVersion}}']);
649
- } catch (cause) {
650
- const problem = cause.code === 'ENOENT'
651
- ? 'Docker command was not found in PATH.'
652
- : `Docker Engine is not reachable. Start Docker and check that your user can access it.\nDetails: ${cause.message}`;
653
- throw new Error(`${problem}\n${recovery}`, { cause });
654
- }
655
- let version;
656
- try {
657
- version = await effects.run('docker', ['compose', 'version', '--short']);
658
- } catch (cause) {
659
- throw new Error(`Docker Compose 2.35 or newer is required, but the Compose plugin could not run. Update Docker Desktop or install the Docker Compose plugin.\n${recovery}`, { cause });
660
- }
661
- const match = /^v?(\d+)\.(\d+)/.exec(version.stdout.trim());
662
- if (!match || Number(match[1]) < 2 || (Number(match[1]) === 2 && Number(match[2]) < 35)) {
663
- throw new Error(`Docker Compose 2.35 or newer is required. Update Docker Desktop or the Docker Compose plugin.\n${recovery}`);
688
+ if (engineName(record) === 'podman') {
689
+ await bindPodman(effects, record);
690
+ if (['install', 'start', 'restart', 'update', 'rebuild', 'gateway-enable'].includes(operation)) {
691
+ const userHome = userInfo().homedir;
692
+ for (const [key, expected] of Object.entries({ HOME: userHome, XDG_CONFIG_HOME: join(userHome, '.config'), XDG_DATA_HOME: join(userHome, '.local/share'), XDG_RUNTIME_DIR: `/run/user/${process.getuid()}` })) {
693
+ if (env[key] && env[key] !== expected) throw new Error(`${key} selects a custom Podman environment that the standard boot service does not retain`);
694
+ }
695
+ if (record.containerBinding.socket !== `/run/user/${process.getuid()}/podman/podman.sock`) throw new Error('The standard user boot service requires the default local Podman socket');
696
+ await effects.run('systemctl', ['--user', 'is-enabled', 'podman.socket']);
697
+ await effects.run('systemctl', ['--user', 'is-enabled', 'podman-restart.service']);
698
+ const restart = await effects.run('systemctl', ['--user', 'show', 'podman-restart.service', '--property=ExecStart', '--value']);
699
+ if (!/--filter[ =]+should-start-on-boot=true(?:[ ;}]|$)/.test(restart.stdout)) throw new Error('Installed podman-restart.service cannot recover unless-stopped workloads; use a Podman release with should-start-on-boot support');
700
+ const linger = await effects.run('loginctl', ['show-user', String(process.getuid()), '--property=Linger', '--value']);
701
+ if (linger.stdout.trim() !== 'yes') throw new Error('Rootless server requires user linger for logout/reboot recovery; ask your administrator to enable it');
702
+ await qualifyPodman(effects, record);
703
+ }
704
+ } else {
705
+ const nativeRoot = existing ? '/path/to/new-empty-directory' : record.root;
706
+ const quotedRoot = `'${String(nativeRoot).replaceAll("'", "'\\''")}'`;
707
+ const quotedName = `'${String(identityName ?? record.messengerIdentity ?? 'Your Name').replaceAll("'", "'\\''")}'`;
708
+ const recovery = [
709
+ 'Please install Docker Desktop on macOS/Windows, or Docker Engine with the Compose plugin on Linux, and start Docker before retrying.',
710
+ 'Docker is recommended for macOS and Windows.',
711
+ `Alternatively, use native installation: ours-install server install --mode packages --state-dir ${quotedRoot} --identity-name ${quotedName}`,
712
+ 'Native mode requires systemd user services on Linux/WSL or a launchd GUI session on macOS.',
713
+ ...(existing ? ['Keep this existing Docker installation in Docker mode; use a separate empty directory for a new native installation.'] : []),
714
+ ].join('\n');
715
+ try {
716
+ await container(record, ['info', '--format', '{{.ServerVersion}}']);
717
+ } catch (cause) {
718
+ const problem = cause.code === 'ENOENT'
719
+ ? 'Docker command was not found in PATH.'
720
+ : `Docker Engine is not reachable. Start Docker and check that your user can access it.\nDetails: ${cause.message}`;
721
+ throw new Error(`${problem}\n${recovery}`, { cause });
722
+ }
723
+ let version;
724
+ try {
725
+ version = await container(record, ['compose', 'version', '--short']);
726
+ } catch (cause) {
727
+ throw new Error(`Docker Compose 2.35 or newer is required, but the Compose plugin could not run. Update Docker Desktop or install the Docker Compose plugin.\n${recovery}`, { cause });
728
+ }
729
+ const match = /^v?(\d+)\.(\d+)/.exec(version.stdout.trim());
730
+ if (!match || Number(match[1]) < 2 || (Number(match[1]) === 2 && Number(match[2]) < 35)) {
731
+ throw new Error(`Docker Compose 2.35 or newer is required. Update Docker Desktop or the Docker Compose plugin.\n${recovery}`);
732
+ }
664
733
  }
665
734
  if (operation !== 'status') {
666
735
  // Compose clients can disappear while their Engine-owned command continues.
667
- const active = await effects.run('docker', ['ps', '--filter', `label=com.docker.compose.project=${record.project}`, '--filter', 'label=com.docker.compose.oneoff=True', '--format', '{{.ID}}']);
736
+ const active = await container(record, ['ps', '--filter', `label=com.docker.compose.project=${record.project}`, '--filter', 'label=com.docker.compose.oneoff=True', '--format', '{{.ID}}']);
668
737
  if (active.stdout.trim()) throw new Error('Another server installation operation is still running in Docker');
669
738
  }
670
739
  } else {
@@ -680,7 +749,17 @@ export function networkEffects(effects) {
680
749
  }
681
750
  }
682
751
  },
683
- async initializeSelection(record, manifest) {
752
+ async prepareLegacyDockerImport(record) {
753
+ if (record.mode === 'docker') await compose(record, ['build', 'legacy-import'], { stream: true, env: { BUILDKIT_PROGRESS: 'plain' } });
754
+ },
755
+ async importLegacyDockerState(record) {
756
+ if (record.mode !== 'docker') return;
757
+ const source = join(record.root, 'storage', 'state');
758
+ if (source.includes(':')) throw new Error('Docker migration requires an installation path without colon characters');
759
+ await compose(record, ['run', '--rm', '--no-deps', '-T', '--volume', `${source}:/legacy-import:ro`,
760
+ '--env', `OURS_LEGACY_TARGET_ROOT=${record.root}`, 'legacy-import']);
761
+ },
762
+ async initializeSelection(record, manifest, { retainConfig = false } = {}) {
684
763
  if (typeof manifest === 'string') manifest = JSON.parse(readFileSync(manifest, 'utf8'));
685
764
  selectSourcePackages(manifest, 'server');
686
765
  const bytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);
@@ -688,8 +767,58 @@ export function networkEffects(effects) {
688
767
  if (record.schema === 2) {
689
768
  for (const path of [join(record.root, 'storage'), installationPaths(record).state, installationPaths(record).daemon]) ensurePrivateDirectory(path);
690
769
  }
691
- writePrivateNew(record.sourcesPath, bytes);
692
- writePrivateNew(record.configPath, JSON.stringify({ stateDir: record.mode === 'docker' ? '/var/lib/ours' : installationPaths(record).daemon, port: record.port, apiVisibility: 'owner' }, null, 2) + '\n');
770
+ if (!retainConfig || !existsSync(record.sourcesPath)) writePrivateNew(record.sourcesPath, bytes);
771
+ else if (!readFileSync(record.sourcesPath).equals(bytes)) throw new Error('Migration source selection changed');
772
+ if (!retainConfig) writePrivateNew(record.configPath, JSON.stringify({ stateDir: record.mode === 'docker' ? '/var/lib/ours' : installationPaths(record).daemon, port: record.port, apiVisibility: 'owner' }, null, 2) + '\n');
773
+ },
774
+ async qualifyDockerRuntime(record) { return qualifyDockerRuntime(record, effects); },
775
+ async prepareGateway(record) {
776
+ atomicWriteConfig(join(record.workDir, 'docker-compose.gateway.yaml'), gatewayCompose(record));
777
+ atomicWriteConfig(join(record.workDir, 'nginx.conf'), gatewayNginx(record));
778
+ atomicWriteConfig(join(record.workDir, 'gateway-entrypoint.sh'), readFileSync(join(INSTALLER_ASSETS, 'gateway-entrypoint.sh'), 'utf8'));
779
+ atomicWriteConfig(join(record.workDir, 'Dockerfile.gateway'), readFileSync(join(INSTALLER_ASSETS, 'Dockerfile.gateway'), 'utf8'));
780
+ await compose(record, ['build', 'gateway'], { stream: true, env: { BUILDKIT_PROGRESS: 'plain' } });
781
+ },
782
+ async removeGatewayContainer(record) { await compose(record, ['rm', '-f', 'gateway']); },
783
+ async verifyGateway(record) {
784
+ const { prefix } = gatewayAddress(record);
785
+ const script = `const fs=require('node:fs');let stage='selection';(async()=>{
786
+ const base=${JSON.stringify('http://gateway:8080' + prefix)};
787
+ const get=async(path,options={})=>{const r=await fetch(base+path,{...options,redirect:'error',signal:AbortSignal.timeout(5000)});if(!r.ok)throw Error('Gateway readiness HTTP '+r.status);return r.json();};
788
+ const selection=await get('/daemon/selection');
789
+ if(selection.instanceId!==${JSON.stringify(record.instanceId)})throw Error('Gateway daemon instance mismatch');
790
+ stage='unauthenticated-management';
791
+ const denied=await fetch(base+'/cowork/management/rpc',{method:'POST',redirect:'error',signal:AbortSignal.timeout(5000),headers:{'content-type':'application/json'},body:'{}'});
792
+ await denied.body?.cancel();if(denied.status!==401)throw Error('Gateway management does not reject unauthenticated requests');
793
+ stage='credential';
794
+ const token=fs.readFileSync('/var/lib/ours/daemon-token','utf8').trim();
795
+ const headers={'x-ours-api-token':token,'content-type':'application/json'};
796
+ stage='authenticated-daemon';
797
+ const identities=await get('/daemon/identities',{headers});
798
+ if(!Array.isArray(identities.identities))throw Error('Gateway daemon API invalid');
799
+ stage='authenticated-management';
800
+ const result=await get('/cowork/management/rpc',{method:'POST',headers,body:JSON.stringify({version:1,id:'installer-readiness',method:'room.list',params:{}})});
801
+ if(result.version!==1||result.id!=='installer-readiness'||!Array.isArray(result.result)||result.error)throw Error('Gateway Cowork management unavailable');
802
+ })().catch(error=>{const code=error.cause?.code;process.stdout.write('gateway-readiness:'+stage+':'+(['EAI_AGAIN','ENOTFOUND','ECONNREFUSED','ETIMEDOUT'].includes(code)?code:'CHECK_FAILED'));process.exitCode=1;});`;
803
+ const result = await compose(record, ['exec', '-T', 'daemon', 'node', '-e', script], { sensitive: true, allowCodes: [1] });
804
+ if (result.code === 1) {
805
+ const match = /^gateway-readiness:(selection|unauthenticated-management|credential|authenticated-daemon|authenticated-management):(EAI_AGAIN|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|CHECK_FAILED)$/.exec(result.stdout.trim());
806
+ const detail = match ? ` (${match[1]}, ${match[2]})` : '';
807
+ throw new Error(`Gateway readiness failed${detail}. Keep installation state intact; check the managed gateway startup and network connection, then retry setup.`);
808
+ }
809
+ },
810
+ async qualifyGatewayRuntime(record) {
811
+ for (const [name, args, capability] of [
812
+ ['cowork', ['--json', 'capabilities'], 'cowork.http-management-v1'],
813
+ ['messenger-server', ['capabilities'], 'messenger.gateway-prefix-v1'],
814
+ ['tg-connector', ['capabilities'], 'telegram.gateway-listener-v1'],
815
+ ]) {
816
+ const probe = await container(record, ['run', '--rm', '--network', 'none', '--read-only', '--entrypoint', 'node', `${record.project}:runtime`, `/opt/ours/node_modules/@ours.network/${name}/dist/cli.js`, ...args]);
817
+ let value; try { value = JSON.parse(probe.stdout); } catch {}
818
+ const capabilities = value?.result?.capabilities ?? value?.capabilities;
819
+ if (!Array.isArray(capabilities) || !capabilities.includes(capability))
820
+ throw new Error(`Selected ${name} artifact lacks ${capability}; select a compatible release before enabling the gateway`);
821
+ }
693
822
  },
694
823
  async prepareInstallation(record, { runtimeOnly = false } = {}) {
695
824
  let copied = false;
@@ -704,11 +833,24 @@ export function networkEffects(effects) {
704
833
  if (!existsSync(materialized)) writePrivateNew(materialized, retained);
705
834
  else if (!readFileSync(materialized).equals(retained)) throw new Error('Materialized sources differ from retained selection');
706
835
  if (record.mode === 'docker') {
836
+ if (engineName(record) === 'podman') atomicWriteConfig(join(record.workDir, 'compose.podman.json'), JSON.stringify({ services: Object.fromEntries(record.services.map(name => [name, { restart: 'unless-stopped' }])) }));
837
+ const rebuildPrivateScripts = refreshDockerPolicyCopy(record);
838
+ if (record.gateway) {
839
+ atomicWriteConfig(join(record.workDir, 'docker-compose.gateway.yaml'), gatewayCompose(record));
840
+ atomicWriteConfig(join(record.workDir, 'nginx.conf'), gatewayNginx(record));
841
+ for (const file of ['Dockerfile.gateway', 'gateway-entrypoint.sh']) atomicWriteConfig(join(record.workDir, file), readFileSync(join(INSTALLER_ASSETS, file), 'utf8'));
842
+ }
707
843
  // The installer owns these dependencies in both installation modes.
708
844
  const { dependencies } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
709
845
  writeFileSync(join(record.workDir, 'scripts/maintenance/package.json'), JSON.stringify({ private: true, type: 'module', dependencies }, null, 2) + '\n', { mode: 0o600 });
710
- const image = await effects.run('docker', ['image', 'inspect', `${record.project}:runtime`], { allowCodes: [1] });
711
- if (image.code !== 0) await compose(record, ['build', 'daemon'], { stream: true, env: { BUILDKIT_PROGRESS: 'plain' } });
846
+ const image = await container(record, ['image', 'inspect', `${record.project}:runtime`], { allowCodes: [1] });
847
+ if (image.code !== 0 || rebuildPrivateScripts) await compose(record, ['build', 'daemon'], { stream: true, env: { BUILDKIT_PROGRESS: 'plain' } });
848
+ await effects.qualifyDockerRuntime(record);
849
+ if (rebuildPrivateScripts) rmSync(join(record.workDir, '.script-permissions-rebuild'));
850
+ if (record.gateway) {
851
+ await effects.qualifyGatewayRuntime(record);
852
+ await compose(record, ['build', 'gateway'], { stream: true, env: { BUILDKIT_PROGRESS: 'plain' } });
853
+ }
712
854
  if (runtimeOnly) return;
713
855
  await compose(record, ['run', '--rm', '--no-deps', '-T', 'prepare', 'prepare']);
714
856
  } else {
@@ -731,7 +873,6 @@ export function networkEffects(effects) {
731
873
  const profilePath = join(installationPaths(record).mcp, 'profile.json');
732
874
  if (!existsSync(profilePath)) writePrivateNew(profilePath, JSON.stringify({ endpoint: `http://127.0.0.1:${record.port}`, expectedInstanceId: record.instanceId, credentialPath: join(installationPaths(record).daemon, 'daemon-token') }));
733
875
  const config = JSON.parse(readFileSync(record.configPath, 'utf8'));
734
- config.networkMcp ??= { profile: { endpoint: `http://127.0.0.1:${record.port}`, expectedInstanceId: record.instanceId, credentialPath: join(installationPaths(record).daemon, 'daemon-token') }, applicationConfigPath: join(installationPaths(record).mcp, 'config.json') };
735
876
  effects.writeJson(record.configPath, JSON.stringify(config, null, 2) + '\n');
736
877
  const cowork = join(installationPaths(record).cowork, 'config.json');
737
878
  if (!existsSync(cowork)) writePrivateNew(cowork, JSON.stringify({ version: 1, stateDir: installationPaths(record).cowork, rest: { enabled: true, host: '127.0.0.1', port: record.coworkPort } }));
@@ -779,17 +920,17 @@ export function networkEffects(effects) {
779
920
  },
780
921
  async copyDockerBuildRecords(record, directory) {
781
922
  // Inspect immutable image metadata; never reinterpret a failed context copy as legacy.
782
- const label = (await effects.run('docker', ['image', 'inspect', '--format', '{{ index .Config.Labels "network.ours.build-context" }}', `${record.project}:runtime`])).stdout.trim();
923
+ const label = (await container(record, ['image', 'inspect', '--format', '{{ index .Config.Labels "network.ours.build-context" }}', `${record.project}:runtime`])).stdout.trim();
783
924
  if (!['', '<no value>', '1'].includes(label)) throw new Error('Unsupported image build-context schema');
784
925
  const names = [...BASE_RECORDS, ...(label === '1' ? [CONTEXT] : [])];
785
926
  const stage = mkdtempSync(join(directory, '.records-'));
786
927
  const name = `${record.project}-records`;
787
928
  let created = false;
788
929
  try {
789
- await effects.run('docker', ['create', '--name', name, '--entrypoint', '/bin/true', `${record.project}:runtime`]);
930
+ await container(record, ['create', '--name', name, '--entrypoint', '/bin/true', `${record.project}:runtime`]);
790
931
  created = true;
791
932
  for (const file of names) {
792
- await effects.run('docker', ['cp', `${name}:/opt/ours/${file}`, join(stage, file)]);
933
+ await container(record, ['cp', `${name}:/opt/ours/${file}`, join(stage, file)]);
793
934
  const st = lstatSync(join(stage, file));
794
935
  if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o7002)) throw new Error('Unsafe copied build record');
795
936
  chmodSync(join(stage, file), 0o600);
@@ -799,7 +940,7 @@ export function networkEffects(effects) {
799
940
  for (const file of names) renameSync(join(stage, file), join(directory, file));
800
941
  if (label !== '1' && existsSync(join(directory, CONTEXT))) throw new Error('Legacy image conflicts with retained build context');
801
942
  } finally {
802
- try { if (created) await effects.run('docker', ['rm', name]); }
943
+ try { if (created) await container(record, ['rm', name]); }
803
944
  finally { rmSync(stage, { recursive: true, force: true }); }
804
945
  }
805
946
  },
@@ -850,12 +991,12 @@ export function networkEffects(effects) {
850
991
  async publishServerBuild(record, candidate) {
851
992
  const previous = join(candidate.root, 'previous-runtime');
852
993
  if (record.mode === 'docker') {
853
- for (const target of ['runtime', 'maintenance']) {
994
+ for (const target of ['runtime', 'maintenance', ...(record.gateway ? ['gateway'] : [])]) {
854
995
  const retained = `${candidate.project}:previous-${target}`;
855
- const found = await effects.run('docker', ['image', 'inspect', retained], { allowCodes: [1] });
996
+ const found = await container(record, ['image', 'inspect', retained], { allowCodes: [1] });
856
997
  if (found.code !== 0) {
857
- const current = await effects.run('docker', ['image', 'inspect', `${record.project}:${target}`], { allowCodes: [1] });
858
- if (current.code === 0) await effects.run('docker', ['tag', `${record.project}:${target}`, retained]);
998
+ const current = await container(record, ['image', 'inspect', `${record.project}:${target}`], { allowCodes: [1] });
999
+ if (current.code === 0) await container(record, ['tag', `${record.project}:${target}`, retained]);
859
1000
  }
860
1001
  }
861
1002
  }
@@ -871,8 +1012,8 @@ export function networkEffects(effects) {
871
1012
  renameSync(candidate.workDir, record.workDir);
872
1013
  } else privateDirectory(record.workDir);
873
1014
  if (record.mode === 'docker') {
874
- for (const target of ['runtime', 'maintenance']) {
875
- await effects.run('docker', ['tag', `${candidate.project}:${target}`, `${record.project}:${target}`]);
1015
+ for (const target of ['runtime', 'maintenance', ...(record.gateway ? ['gateway'] : [])]) {
1016
+ await container(candidate, ['tag', `${candidate.project}:${target}`, `${record.project}:${target}`]);
876
1017
  }
877
1018
  }
878
1019
  atomicWriteConfig(record.sourcesPath, readFileSync(candidate.sourcesPath));
@@ -886,10 +1027,10 @@ export function networkEffects(effects) {
886
1027
  },
887
1028
  async discardServerBuild(candidate) {
888
1029
  if (candidate.mode === 'docker') {
889
- for (const target of ['runtime', 'maintenance', 'previous-runtime', 'previous-maintenance']) {
1030
+ for (const target of ['runtime', 'maintenance', 'previous-runtime', 'previous-maintenance', ...(candidate.gateway ? ['gateway', 'previous-gateway'] : [])]) {
890
1031
  const image = `${candidate.project}:${target}`;
891
- const found = await effects.run('docker', ['image', 'inspect', image], { allowCodes: [1] });
892
- if (found.code === 0) await effects.run('docker', ['image', 'rm', image]);
1032
+ const found = await container(candidate, ['image', 'inspect', image], { allowCodes: [1] });
1033
+ if (found.code === 0) await container(candidate, ['image', 'rm', image]);
893
1034
  }
894
1035
  }
895
1036
  privateDirectory(candidate.root);
@@ -907,21 +1048,21 @@ export function networkEffects(effects) {
907
1048
  try {
908
1049
  await compose(record, ['run', '--name', name, '--no-deps', '-T', 'access', 'access-issue', issuedPath], { sensitive: true });
909
1050
  const file = join(staging, 'credential');
910
- await effects.run('docker', ['cp', `${name}:${issuedPath}`, file], { sensitive: true });
1051
+ await container(record, ['cp', `${name}:${issuedPath}`, file], { sensitive: true });
911
1052
  assertPrivateRegularFile(file, 'issued credential');
912
1053
  // Exclusive publication never overwrites an unrelated credential.
913
1054
  writePrivateNew(output, readFileSync(file));
914
1055
  } finally {
915
1056
  await compose(record, ['run', '--rm', '--no-deps', '-T', '--entrypoint', 'rm', 'access', '-f', issuedPath], { sensitive: true });
916
- await effects.run('docker', ['rm', '-f', name], { sensitive: true });
1057
+ await container(record, ['rm', '-f', name], { sensitive: true });
917
1058
  rmSync(staging, { recursive: true, force: true });
918
1059
  }
919
1060
  return;
920
1061
  }
921
1062
  const options = { env: localEnv(record), sensitive: true };
922
- if (operation !== 'access-issue') return effects.run(bin(record, 'ours'), ['config', operation, '--config', record.configPath, ...(operation === 'access-replace' ? ['--confirm'] : migrate ? ['--migrate'] : []), '--json'], options);
1063
+ if (operation !== 'access-issue') return effects.run(bin(record, existsSync(bin(record, 'ours-daemon')) ? 'ours-daemon' : 'ours'), ['config', operation, '--config', record.configPath, ...(operation === 'access-replace' ? ['--confirm'] : migrate ? ['--migrate'] : []), '--json'], options);
923
1064
  const outputs = output ? [output] : [join(installationPaths(record).daemon, 'daemon-token'), ...['telegram', 'cowork', 'messenger'].map(s => installationPaths(record).credentials[s])];
924
- for (const path of outputs) await effects.run(bin(record, 'ours'), ['config', operation, '--config', record.configPath, '--output', path, ...(output ? [] : ['--replace']), '--json'], options);
1065
+ for (const path of outputs) await effects.run(bin(record, existsSync(bin(record, 'ours-daemon')) ? 'ours-daemon' : 'ours'), ['config', operation, '--config', record.configPath, '--output', path, ...(output ? [] : ['--replace']), '--json'], options);
925
1066
  },
926
1067
  async recordRuntimeBuild(record) {
927
1068
  if (record.mode === 'docker') return; // Image preparation records its build.
@@ -965,7 +1106,7 @@ export function networkEffects(effects) {
965
1106
  await effects.run(process.execPath, [join(INSTALLER_ASSETS, 'scripts/maintenance/state-operation.mjs'), ...command], {
966
1107
  env: { ...localEnv(record), OURS_STATE_DOMAIN: args.domain,
967
1108
  OURS_STATE_ROOT: join(record.root, 'storage'), OURS_LIVE_ROOT: ['server', 'daemon'].includes(args.domain) ? paths.state : paths[args.domain],
968
- OURS_BUILD_ROOT: record.workDir, OURS_CLI_PATH: bin(record, 'ours'),
1109
+ OURS_BUILD_ROOT: record.workDir, OURS_CLI_PATH: bin(record, existsSync(bin(record, 'ours-daemon')) ? 'ours-daemon' : 'ours'),
969
1110
  OURS_DAEMON_CONFIG: record.configPath, OURS_COWORK_CLI_PATH: bin(record, 'ours-cowork'),
970
1111
  OURS_COWORK_CONFIG: join(paths.cowork, 'config.json'), OURS_COWORK_STATE_DIR: paths.cowork },
971
1112
  });
@@ -983,12 +1124,12 @@ export function networkEffects(effects) {
983
1124
  if (typeof name !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(name)) {
984
1125
  throw new Error('Invalid conversion volume name');
985
1126
  }
986
- const result = await effects.run('docker', ['volume', 'inspect', '--format', '{{json .}}', name], {
1127
+ const result = await container(record, ['volume', 'inspect', '--format', '{{json .}}', name], {
987
1128
  ...(optional ? { allowCodes: [1] } : {}),
988
1129
  });
989
1130
  if (result.code !== 0) {
990
1131
  if (optional) {
991
- const inventory = await effects.run('docker', ['volume', 'ls', '--format', '{{.Name}}']);
1132
+ const inventory = await container(record, ['volume', 'ls', '--format', '{{.Name}}']);
992
1133
  if (inventory.code === 0 && !inventory.stdout.split(/\s+/).includes(name)) return false;
993
1134
  }
994
1135
  throw new Error(`Source volume is missing or unavailable: ${name}`);
@@ -1050,7 +1191,7 @@ export function networkEffects(effects) {
1050
1191
  await ownerCommand(record, 'cowork', 'prepare-backup');
1051
1192
  },
1052
1193
  async retainConvertedPackageAuthority(record, daemon) {
1053
- await effects.run(bin(record, 'ours'), [
1194
+ await effects.run(bin(record, existsSync(bin(record, 'ours-daemon')) ? 'ours-daemon' : 'ours'), [
1054
1195
  'config', 'access-retain', '--config', record.configPath,
1055
1196
  '--target-state-dir', daemon, '--json',
1056
1197
  ], { env: localEnv(record), sensitive: true });
@@ -1112,7 +1253,9 @@ export function networkEffects(effects) {
1112
1253
  }
1113
1254
  const start = async service => {
1114
1255
  effects.out(`Starting ${service}; waiting for readiness...`);
1115
- try { await compose(record, ['up', '-d', '--no-build', '--no-deps', '--wait', service]); }
1256
+ // Gateway has no persistent state. Recreate its network endpoint on each
1257
+ // managed start, including retries after an interrupted/failed bind.
1258
+ try { await compose(record, ['up', '-d', '--no-build', '--no-deps', ...(service === 'gateway' ? ['--force-recreate'] : []), '--wait', service]); }
1116
1259
  catch (cause) { throw await dockerStartupError(record, service, cause); }
1117
1260
  effects.out(`${service} is ready.`);
1118
1261
  };
@@ -1122,6 +1265,7 @@ export function networkEffects(effects) {
1122
1265
  try { await start(service); }
1123
1266
  catch (error) { failures.push({ service, error }); }
1124
1267
  }
1268
+ if (!failures.length && record.gateway && ['daemon', 'cowork', 'gateway'].every(service => selected.includes(service))) await effects.verifyGateway(record);
1125
1269
  if (failures.length) throw new Error(`Application readiness failed: ${failures.map(f => f.service).join(', ')}. Check the selected application prerequisites.\n${failures.map(f => f.error.message).join('\n\n')}`);
1126
1270
  return;
1127
1271
  }
@@ -1136,21 +1280,19 @@ export function networkEffects(effects) {
1136
1280
  return JSON.parse(readFileSync(path, 'utf8'));
1137
1281
  },
1138
1282
  async discoverClientProfile(endpoint, credentialPath) {
1139
- const url = new URL(endpoint);
1140
- if (url.protocol !== 'http:' || url.username || url.password || url.pathname !== '/' || url.search || url.hash)
1141
- throw new Error('Client endpoint must be an HTTP origin');
1142
- const response = await fetch(`${url.origin}/selection`, { redirect: 'error', signal: AbortSignal.timeout(5000) });
1143
- if (!response.ok) throw new Error(`Daemon selection answered HTTP ${response.status}`);
1144
- const selection = await response.json();
1145
- // Full metadata and authenticated capability validation follows before publication.
1146
- return validateHostProfile({ endpoint: url.origin, expectedInstanceId: selection.instanceId, credentialPath: resolve(credentialPath) });
1283
+ const base = serverBase(endpoint);
1284
+ const request = path => fetch(`${base}${path}`, { redirect: 'error', signal: AbortSignal.timeout(5000) });
1285
+ const discovery = await request('/.well-known/ours');
1286
+ if (discovery.ok) return validateGatewayDiscovery(base, await discovery.json(), resolve(credentialPath));
1287
+ throw new Error(`Gateway discovery answered HTTP ${discovery.status}; enable the gateway. Direct daemon fallback is not supported.`);
1147
1288
  },
1148
1289
  importClientProfile({ profile, sourcesPath, sources: resolvedSources, integrations, fleetSettingsPath, refresh = false }) {
1290
+ profile = validateGatewayClientProfile(profile);
1149
1291
  const root = join(home, '.ours-client');
1150
1292
  const configPath = join(root, 'profile.json');
1151
1293
  const credentialPath = join(root, 'credential');
1152
1294
  const current = effects.readManagedClientProfile();
1153
- if (current && (current.endpoint !== profile.endpoint || current.expectedInstanceId !== profile.expectedInstanceId))
1295
+ if (current && current.expectedInstanceId !== profile.expectedInstanceId)
1154
1296
  throw new Error('Managed client already selects another server; existing default was not changed');
1155
1297
  assertPrivateRegularFile(profile.credentialPath, 'credential');
1156
1298
  const credential = readFileSync(profile.credentialPath, 'utf8');
@@ -1165,7 +1307,10 @@ export function networkEffects(effects) {
1165
1307
  if (current && !refresh) {
1166
1308
  assertPrivateRegularFile(credentialPath, 'managed credential');
1167
1309
  if (readFileSync(credentialPath, 'utf8') !== credential) atomicWriteConfig(credentialPath, credential);
1168
- return { configPath, profile: validateHostProfile(current), settings: current.installer };
1310
+ const saved = { ...current, ...profile, credentialPath };
1311
+ if (current.endpoint !== saved.endpoint || current.serverUrl !== saved.serverUrl)
1312
+ atomicWriteConfig(configPath, JSON.stringify(saved, null, 2) + '\n');
1313
+ return { configPath, profile: validateGatewayClientProfile(saved), settings: current.installer };
1169
1314
  }
1170
1315
  const settings = { sourcesPath: join(root, 'sources.json'), integrations };
1171
1316
  if (fleetSettings) settings.fleetSettingsPath = join(root, 'fleet-settings.json');
@@ -1177,18 +1322,39 @@ export function networkEffects(effects) {
1177
1322
  atomicWriteConfig(configPath, JSON.stringify(saved, null, 2) + '\n');
1178
1323
  return { configPath, profile: validateHostProfile(saved), settings };
1179
1324
  },
1180
- async acquireClientPackages(configPath, sourcesPath, integrations, { refresh = false } = {}) {
1325
+ async qualifyInstalledGatewayClient(profile) {
1326
+ if (!profile.installer?.integrations?.includes('fleet')) return;
1327
+ let info;
1328
+ try { info = JSON.parse((await effects.run('ours-fleet', ['version', '--json'])).stdout); } catch {}
1329
+ if (!Array.isArray(info?.capabilities) || !info.capabilities.includes('cowork.http-management-v1'))
1330
+ throw new Error('Installed Fleet does not support gateway HTTP management; upgrade Fleet before gateway-enable');
1331
+ },
1332
+ async qualifyGatewayClient({ profile, sourcesPath, sources, integrations, refresh = false }) {
1333
+ if (!profile.serverUrl || !integrations.includes('fleet')) return;
1334
+ // Acquire into the retained package cache without publishing a profile,
1335
+ // credential, native command, or integration. Normal acquisition rechecks it.
1336
+ const staging = mkdtempSync(join(home, '.ours-gateway-client-'));
1337
+ try {
1338
+ const stagedSources = join(staging, 'sources.json');
1339
+ writeFileSync(stagedSources, sources ? JSON.stringify(sources, null, 2) + '\n' : readFileSync(sourcesPath), { mode: 0o600 });
1340
+ await effects.acquireClientPackages(join(home, '.ours-client/profile.json'), stagedSources, integrations,
1341
+ { refresh, gatewayServerUrl: profile.serverUrl, qualifyOnly: true });
1342
+ } finally { rmSync(staging, { recursive: true, force: true }); }
1343
+ },
1344
+ async acquireClientPackages(configPath, sourcesPath, integrations, { refresh = false, hostCliOnly = false, gatewayServerUrl, qualifyOnly = false } = {}) {
1181
1345
  const manifest = JSON.parse(readFileSync(sourcesPath, 'utf8'));
1182
- // Public SDK client APIs are actual integration dependencies; Fleet also owns CLI usage.
1183
- const selected = [...new Set(['sdk', ...(integrations.includes('fleet') ? ['cli'] : []), ...integrations])];
1346
+ // Every client installation includes the native CLI and its SDK dependency.
1347
+ const selected = clientPackageNames(integrations);
1184
1348
  const packages = selectSourcePackages(manifest, 'client', selected);
1185
- const selectionKey = refresh ? JSON.stringify([configPath, manifest, integrations]) : configPath;
1349
+ const selectionKey = JSON.stringify([hostCliOnly ? 'host-cli-private-v1' : 'host-cli-v1', configPath, ...(hostCliOnly ? [manifest] : []), ...(refresh ? [manifest, integrations] : [])]);
1186
1350
  const root = join(home, '.ours-client-install', createHash('sha256').update(selectionKey).digest('hex').slice(0, 16));
1187
1351
  const hasGit = Object.values(packages).some(selection => selection.source);
1188
1352
  await effects.run('npm', ['--version']);
1189
1353
  if (hasGit) {
1190
1354
  for (const command of ['python3', 'git', 'make', 'cc']) await effects.run(command, ['--version']);
1191
1355
  }
1356
+ // This directory retains active executables, not disposable download cache.
1357
+ ensurePrivateDirectory(join(home, '.ours-client-install'));
1192
1358
  ensurePrivateDirectory(root);
1193
1359
  const retained = join(root, 'sources.json');
1194
1360
  const bytes = readFileSync(sourcesPath);
@@ -1213,13 +1379,33 @@ export function networkEffects(effects) {
1213
1379
  writePrivateNew(join(root, '.packages-ready'), 'ready\n');
1214
1380
  }
1215
1381
  verifyReleaseGraph(root, manifest, { requiredPackages: Object.keys(packages) });
1382
+ if (integrations.includes('fleet') && (gatewayServerUrl || readHostProfileFile(configPath)?.serverUrl)) {
1383
+ let info;
1384
+ try { info = JSON.parse(readFileSync(join(root, 'node_modules/@ours.network/fleet/dist/build-info.json'), 'utf8')); } catch {}
1385
+ if (!Array.isArray(info?.capabilities) || !info.capabilities.includes('cowork.http-management-v1'))
1386
+ throw new Error('Selected Fleet artifact does not support gateway HTTP management; select a compatible client release');
1387
+ }
1388
+ if (qualifyOnly) return;
1389
+ const cliPolicy = hostCliOnly ? null : hostCliPolicy(manifest);
1216
1390
  // Local acquisition alone does not publish native commands. Use the user's
1217
1391
  // configured npm prefix and retained dependency closure, including on retry.
1218
1392
  for (const name of integrations.filter(name => name === 'fleet' || name === 'codex')) {
1219
1393
  await effects.run('npm', ['install', '--global', '--install-links=false', '--offline', '--ignore-scripts', '--no-audit', '--no-fund', join(root, 'node_modules', '@ours.network', name)]);
1220
1394
  }
1395
+ let cliBin = join(root, 'node_modules/.bin/ours');
1396
+ if (cliPolicy) {
1397
+ const cliSources = join(root, 'host-cli-sources.json');
1398
+ const cliBytes = JSON.stringify(cliPolicy, null, 2) + '\n';
1399
+ if (!existsSync(cliSources)) writePrivateNew(cliSources, cliBytes);
1400
+ else if (readFileSync(cliSources, 'utf8') !== cliBytes) throw new Error('Retained host CLI source selection differs');
1401
+ const acquired = await effects.acquireClientPackages(configPath, cliSources, [], { refresh, hostCliOnly: true });
1402
+ cliBin = acquired.cliBin;
1403
+ } else {
1404
+ // Publish last so optional integration installation cannot downgrade ours.
1405
+ await publishClientCli(effects, join(root, 'node_modules', '@ours.network/cli'), { policy: manifest, isolated: hostCliOnly });
1406
+ }
1221
1407
  const localPackages = Object.fromEntries(integrations.filter(n => n !== 'fleet').map(name => [name, join(root, 'node_modules', '@ours.network', name)]));
1222
- return { localPackages, packages: {}, fleetBin: integrations.includes('fleet') ? join(root, 'node_modules/.bin/ours-fleet') : null };
1408
+ return { localPackages, packages: {}, cliBin, fleetBin: integrations.includes('fleet') ? join(root, 'node_modules/.bin/ours-fleet') : null };
1223
1409
  },
1224
1410
  async prepareClientMarketplace(name, packagePath) {
1225
1411
  const acquisitionRoot = dirname(dirname(dirname(packagePath)));
@@ -1228,7 +1414,7 @@ export function networkEffects(effects) {
1228
1414
  const release = releaseBinding(policy);
1229
1415
  const integrationsPath = join(acquisitionRoot, 'integrations.json');
1230
1416
  const integrations = existsSync(integrationsPath) ? JSON.parse(readFileSync(integrationsPath, 'utf8')) : null;
1231
- const requiredPackages = integrations ? [...new Set(['sdk', ...(integrations.includes('fleet') ? ['cli'] : []), ...integrations])].map(name => '@ours.network/' + name) : Object.keys(policy.packages ?? {});
1417
+ const requiredPackages = integrations ? clientPackageNames(integrations).map(name => '@ours.network/' + name) : Object.keys(policy.packages ?? {});
1232
1418
  verifyReleaseGraph(acquisitionRoot, policy, { requiredPackages });
1233
1419
  const root = join(acquisitionRoot, 'marketplaces', name);
1234
1420
  const plugin = join(root, 'plugins', 'ours');
@@ -1237,7 +1423,7 @@ export function networkEffects(effects) {
1237
1423
  cpSync(packagePath, plugin, { recursive: true });
1238
1424
  const manifestPath = join(plugin, 'package.json');
1239
1425
  const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
1240
- for (const dependency of release ? [] : ['sdk', 'cli']) {
1426
+ for (const dependency of release ? [] : ['sdk', 'cli', 'mcp']) {
1241
1427
  const name = `@ours.network/${dependency}`;
1242
1428
  if (manifest.dependencies?.[name]) manifest.dependencies[name] = `file:${join(dirname(packagePath), dependency)}`;
1243
1429
  }
@@ -1257,42 +1443,7 @@ export function networkEffects(effects) {
1257
1443
  effects.writeJson(manifestPath, JSON.stringify(value, null, 2) + '\n');
1258
1444
  return root;
1259
1445
  },
1260
- async verifyPackagedMcp(configPath) {
1261
- const profile = typeof configPath === 'string' ? readHostProfileFile(configPath) : validateHostProfile(configPath);
1262
- assertPrivateRegularFile(profile.credentialPath, 'credential');
1263
- const token = readFileSync(profile.credentialPath, 'utf8').trim();
1264
- const headers = { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'x-ours-api-token': token, 'x-ours-session-mode': 'external', 'x-ours-lease-token': randomUUID() };
1265
- const request = async (method, params, id) => {
1266
- const response = await fetch(`${profile.endpoint}/mcp`, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(5000), headers, body: JSON.stringify({ jsonrpc: '2.0', ...(id === undefined ? {} : { id }), method, params }) });
1267
- const session = response.headers.get('mcp-session-id');
1268
- if (session) headers['mcp-session-id'] = session;
1269
- if (!response.ok) throw new Error(`Packaged MCP verification failed: HTTP ${response.status}`);
1270
- if (id === undefined) { await response.body?.cancel(); return; }
1271
- const text = await response.text();
1272
- const messages = response.headers.get('content-type')?.includes('text/event-stream')
1273
- ? text.split('\n').filter(line => line.startsWith('data:')).map(line => JSON.parse(line.slice(5)))
1274
- : [JSON.parse(text)];
1275
- const message = messages.find(value => value.id === id);
1276
- if (!message || message.error || !message.result) throw new Error('Packaged MCP returned no successful protocol result');
1277
- return message.result;
1278
- };
1279
- try {
1280
- const initialized = await request('initialize', { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'ours-install', version: '1' } }, 1);
1281
- if (initialized.serverInfo?.name !== 'ours' || !initialized.protocolVersion) throw new Error('Selected MCP is not the packaged OURS server');
1282
- headers['mcp-protocol-version'] = initialized.protocolVersion;
1283
- await request('notifications/initialized', {}, undefined);
1284
- const resources = await request('resources/list', {}, 2);
1285
- if (!resources.resources?.some(resource => resource.uri === 'ours://application-identities')) throw new Error('Packaged network MCP identity resource is absent');
1286
- const toolList = await request('tools/list', {}, 3);
1287
- if (!toolList.tools?.some(tool => tool.name === 'list_identities')) throw new Error('Packaged OURS identity tools are absent');
1288
- } finally {
1289
- if (headers['mcp-session-id']) {
1290
- const response = await fetch(`${profile.endpoint}/mcp`, { method: 'DELETE', redirect: 'error', signal: AbortSignal.timeout(5000), headers });
1291
- await response.body?.cancel();
1292
- if (!response.ok) throw new Error('MCP verification session could not be closed');
1293
- }
1294
- }
1295
- },
1446
+
1296
1447
  };
1297
1448
  }
1298
1449
 
@@ -1339,7 +1490,6 @@ async function nativeLifecycle(record, operation, selected, { effects, localEnv,
1339
1490
  if (service === 'daemon') {
1340
1491
  const profilePath = join(installationPaths(record).mcp, 'profile.json');
1341
1492
  await effects.verifyHostProfile(profilePath);
1342
- await effects.verifyPackagedMcp(profilePath);
1343
1493
  return;
1344
1494
  }
1345
1495
  if (service === 'cowork') { await ownerCommand(record, service, 'status'); return; }
@@ -1417,7 +1567,7 @@ async function nativeLifecycle(record, operation, selected, { effects, localEnv,
1417
1567
  }
1418
1568
  if (!ready) throw new Error('Application is not ready');
1419
1569
  } catch {
1420
- if (service === 'daemon') throw new Error('Daemon and packaged MCP are not ready; consumers were not started');
1570
+ if (service === 'daemon') throw new Error('Daemon API is not ready; consumers were not started');
1421
1571
  failures.push(service);
1422
1572
  }
1423
1573
  }