@ours.network/install 1.2.1-nightly.5 → 1.2.1-nightly.51

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 (64) hide show
  1. package/GATEWAY_SETUP.md +178 -0
  2. package/README.md +548 -9
  3. package/ROOTLESS_PODMAN_VALIDATION.md +210 -0
  4. package/assets/Dockerfile +15 -12
  5. package/assets/Dockerfile.gateway +5 -0
  6. package/assets/docker-compose.yaml +8 -1
  7. package/assets/fleet-settings.example.json +48 -0
  8. package/assets/gateway-entrypoint.sh +37 -0
  9. package/assets/release-lock.json +1227 -4522
  10. package/assets/release.json +37 -19
  11. package/assets/scripts/build/build-common.mjs +10 -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 +22 -7
  16. package/assets/scripts/maintenance/recover-notifications.mjs +36 -0
  17. package/assets/scripts/maintenance/release-graph.mjs +18 -1
  18. package/assets/scripts/maintenance/state-operation.mjs +76 -8
  19. package/assets/scripts/runtime/README.md +7 -0
  20. package/assets/scripts/runtime/client-setup.mjs +105 -20
  21. package/assets/scripts/runtime/daemon-client-prefix.mjs +115 -0
  22. package/assets/scripts/runtime/dependency-ready.mjs +13 -0
  23. package/assets/scripts/runtime/diagnostics.mjs +72 -0
  24. package/assets/scripts/runtime/entrypoint.sh +5 -1
  25. package/assets/scripts/runtime/health-messenger.mjs +7 -6
  26. package/assets/scripts/runtime/notifications-gateway.mjs +90 -0
  27. package/assets/scripts/runtime/recover.mjs +165 -0
  28. package/assets/scripts/runtime/start-cowork.sh +5 -0
  29. package/assets/scripts/runtime/start-messenger.sh +29 -4
  30. package/assets/scripts/runtime/start-telegram.sh +5 -0
  31. package/assets/scripts/runtime/supervise.mjs +35 -0
  32. package/assets/sources.json +54 -28
  33. package/install.mjs +7 -2
  34. package/lib/boot-readiness.mjs +96 -0
  35. package/lib/build-transition.mjs +16 -0
  36. package/lib/client-cli.mjs +127 -0
  37. package/lib/container-engine.mjs +127 -0
  38. package/lib/diagnostics.mjs +1 -0
  39. package/lib/docker-conversion-runtime.mjs +7 -4
  40. package/lib/docker-layout-installation.mjs +2 -1
  41. package/lib/docker-recovery.mjs +60 -0
  42. package/lib/docker-runtime-repair.mjs +74 -19
  43. package/lib/effects.mjs +499 -140
  44. package/lib/gateway-transition.mjs +87 -0
  45. package/lib/gateway.mjs +159 -0
  46. package/lib/legacy-migration.mjs +13 -2
  47. package/lib/orchestrate-uninstall.mjs +23 -6
  48. package/lib/orchestrate.mjs +219 -44
  49. package/lib/ownership.mjs +63 -0
  50. package/lib/plan.mjs +37 -11
  51. package/lib/podman-preflight.mjs +40 -0
  52. package/lib/product.mjs +69 -0
  53. package/lib/removal-plan.mjs +437 -0
  54. package/lib/removal.mjs +749 -0
  55. package/lib/server-onboarding.mjs +182 -16
  56. package/lib/server-ports.mjs +17 -0
  57. package/lib/setup-options.mjs +119 -29
  58. package/lib/setup.mjs +83 -22
  59. package/lib/target.mjs +24 -8
  60. package/lib/uninstall.mjs +2 -2
  61. package/lib/usage.mjs +35 -9
  62. package/lib/welcome.mjs +219 -0
  63. package/lib/workspace-setup.mjs +83 -0
  64. package/package.json +4 -2
package/lib/effects.mjs CHANGED
@@ -1,3 +1,6 @@
1
+ import { selectServerPorts } from './server-ports.mjs';
2
+ import { qualifyPodman } from './podman-preflight.mjs';
3
+ import { engineName, bindPodman, runContainer, nativeBuildCommands } from './container-engine.mjs';
1
4
  // ours-install v3 — the real side effects.
2
5
  //
3
6
  // Every mutation the installer can perform lives here and nowhere else, behind
@@ -11,24 +14,44 @@
11
14
  // state-directory guard and the enable/reload. The installer never touches a
12
15
  // unit file or the service manager directly.
13
16
 
17
+ import { publishClientCli } from './client-cli.mjs';
18
+ import { commandFailure } from './diagnostics.mjs';
14
19
  import { spawnSync, execFileSync } from 'node:child_process';
15
- import { chmodSync, closeSync, constants, cpSync, existsSync, fstatSync, lstatSync, openSync, readFileSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
20
+ import { chmodSync, closeSync, constants, cpSync, existsSync, fstatSync, lstatSync, openSync, readFileSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, writeFileSync } from 'node:fs';
16
21
  import { homedir, userInfo, platform as osPlatform, release as osRelease, arch as osArch } from 'node:os';
17
22
  import { fileURLToPath } from 'node:url';
18
23
  import { randomUUID, createHash } from 'node:crypto';
19
24
  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';
22
- import { createServerOnboarding } from './server-onboarding.mjs';
25
+ import { connect as netConnect } from 'node:net';
26
+ import { clientPackageNames, maintenanceServices, installationPaths, validateInstallation, consumerServiceState, unitNameForStateDir, launchdLabelForStateDir, messengerServicePlan, selectSourcePackages, resolveSourcePolicy, SERVER_SERVICES } from './plan.mjs';
27
+ import { validateHostProfile, validateGatewayClientProfile } from './target.mjs';
28
+ import { serverBase, validateGatewayDiscovery, gatewayCompose, gatewayNginx, gatewayAddress } from './gateway.mjs';
29
+ import { createServerOnboarding, retainedCredentialRefused } from './server-onboarding.mjs';
23
30
  import { atomicWriteConfig, snapshotConfig, restoreConfig } from './config.mjs';
24
31
  import { select as selectOnTty, multiselect as multiselectOnTty, askLine as askLineOnTty } from './prompt.mjs';
25
32
  import { classifyHarnessProbe } from './logic.mjs';
26
33
  import { qualifyDockerRuntime, refreshDockerPolicyCopy } from './docker-runtime-repair.mjs';
34
+ import { refreshDockerRecovery, recoveryCompose, reconcileDockerRecovery } from './docker-recovery.mjs';
35
+ import { reportBootReadiness } from './boot-readiness.mjs';
27
36
  import { classifyStateDir } from './detect.mjs';
37
+ import { isPluginOnly, serverRole, pluginOnlyCompose, PLUGIN_ONLY_COMPOSE } from './product.mjs';
38
+ import { OWNERS_FILE, OWNED_IMAGES_FILE, addOwner, ownedImagesRecord, changedImages } from './ownership.mjs';
39
+ import { IMAGE_TARGETS } from './removal-plan.mjs';
28
40
  import { BASE_RECORDS, CONTEXT, readBuildRecords, equalBuildRecords, initializeBuildMarker } from '../assets/scripts/maintenance/build-context.mjs';
29
- import { releaseBinding, verifyReleaseGraph, verifyRuntimeRelease } from '../assets/scripts/maintenance/release-graph.mjs';
41
+ import { hostCliPolicy, releaseBinding, verifyReleaseGraph, verifyRuntimeRelease } from '../assets/scripts/maintenance/release-graph.mjs';
30
42
 
31
43
  /** GET http://127.0.0.1:<port>/state-dir — the unauthenticated identity probe. */
44
+ /** Whether anything accepts TCP connections on a loopback port: 'refused', 'open', or 'unknown' (timeout or other error). */
45
+ function portState(port, { timeoutMs = 1500 } = {}) {
46
+ return new Promise(done => {
47
+ const socket = netConnect({ host: '127.0.0.1', port });
48
+ const finish = state => { socket.destroy(); done(state); };
49
+ socket.setTimeout(timeoutMs, () => finish('unknown'));
50
+ socket.once('connect', () => finish('open'));
51
+ socket.once('error', error => finish(error?.code === 'ECONNREFUSED' ? 'refused' : 'unknown'));
52
+ });
53
+ }
54
+
32
55
  async function probePort(port, { timeoutMs = 1500 } = {}) {
33
56
  const controller = new AbortController();
34
57
  const timer = setTimeout(() => controller.abort(), timeoutMs);
@@ -330,6 +353,40 @@ export function realEffects({ write, ttyFd, env = process.env, home = homedir(),
330
353
  closeSync(fd);
331
354
  }
332
355
  },
356
+ /**
357
+ * Removal holds the installation lock of every root it removes for the
358
+ * whole run, so no installer operation can start inside a root being deleted.
359
+ */
360
+ async holdInstallationLocks(roots) {
361
+ const { tryLock } = await import('../assets/scripts/maintenance/state-native.mjs');
362
+ const held = [];
363
+ try {
364
+ for (const root of roots) {
365
+ if (!existsSync(root)) continue;
366
+ privateDirectory(root);
367
+ const path = join(root, '.operation.lock');
368
+ const fd = openSync(path, constants.O_CREAT | constants.O_RDWR | constants.O_NOFOLLOW, 0o600);
369
+ held.push(fd);
370
+ const stat = fstatSync(fd);
371
+ if (!stat.isFile() || stat.uid !== process.getuid() || (stat.mode & 0o077) || stat.nlink !== 1) throw new Error(`Unsafe installation lock in ${root}`);
372
+ if (!tryLock(fd)) throw new Error(`Another installer operation is active in ${root}; try again when it has finished`);
373
+ }
374
+ } catch (error) {
375
+ for (const fd of held) closeSync(fd);
376
+ throw error;
377
+ }
378
+ return () => { for (const fd of held) { try { closeSync(fd); } catch { /* released */ } } };
379
+ },
380
+ /** lstat as a plain record; null when absent. Never follows a link. */
381
+ stat: (path) => {
382
+ try {
383
+ const st = lstatSync(path, { bigint: true });
384
+ return { type: st.isSymbolicLink() ? 'symlink' : st.isDirectory() ? 'dir' : st.isFile() ? 'file' : 'other', uid: Number(st.uid), mode: Number(st.mode & 0o7777n), nlink: Number(st.nlink), size: Number(st.size), id: `${st.dev}:${st.ino}` };
385
+ } catch (error) { if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return null; throw error; }
386
+ },
387
+ realpath: (path) => { try { return realpathSync(path); } catch { return null; } },
388
+ list: (path) => { try { return readdirSync(path); } catch { return null; } },
389
+ uid: process.getuid?.() ?? -1,
333
390
  home,
334
391
  env,
335
392
  version,
@@ -344,6 +401,9 @@ export function realEffects({ write, ttyFd, env = process.env, home = homedir(),
344
401
  // pure planner already gated four ways, and this deletes exactly that.
345
402
  removeDir: (path) => { rmSync(resolve(path), { recursive: true, force: true }); },
346
403
  removeFile: (path) => { rmSync(resolve(path), { force: true }); },
404
+ removeEmptyDir: (path) => { rmdirSync(resolve(path)); },
405
+ renamePath: (from, to) => { renameSync(resolve(from), resolve(to)); },
406
+ sleep: (ms) => new Promise(done => setTimeout(done, ms)),
347
407
  copyDir: (source, destination) => {
348
408
  mkdirSync(dirname(resolve(destination)), { recursive: true, mode: 0o700 });
349
409
  cpSync(resolve(source), resolve(destination), {
@@ -378,6 +438,7 @@ export function realEffects({ write, ttyFd, env = process.env, home = homedir(),
378
438
  brokerUrl: env.OURS_BROKER_URL ?? 'wss://broker1.ours.network',
379
439
  now: () => Date.now(),
380
440
  probe: (port) => probePort(port),
441
+ portState: (port) => portState(port),
381
442
  isTaken: (port) => portTakenSync(port),
382
443
  readJson: readJsonFile,
383
444
  readProfile: readHostProfileFile,
@@ -400,7 +461,7 @@ export function realEffects({ write, ttyFd, env = process.env, home = homedir(),
400
461
  // invocation only and never to the installer's own process: a state
401
462
  // directory selected by one run must not leak into anything the operator
402
463
  // starts afterwards.
403
- run: async (cmd, args, { env: extraEnv = null, stream = false, cwd, sensitive = false, allowCodes = [], timeout } = {}) => {
464
+ run: async (cmd, args, { env: extraEnv = null, stream = false, cwd, sensitive = false, allowCodes = [], timeout, input } = {}) => {
404
465
  // Always built from this layer's OWN env rather than left to spawnSync's
405
466
  // implicit inheritance, so what a child receives is a property of the
406
467
  // effects object a caller constructed and not of whatever ambient shell
@@ -413,17 +474,17 @@ export function realEffects({ write, ttyFd, env = process.env, home = homedir(),
413
474
  cwd,
414
475
  timeout,
415
476
  encoding: 'utf8',
416
- stdio: [...(stream ? ['ignore', 'inherit', 'inherit'] : ['ignore', 'pipe', 'pipe']), ...(installationLockFd === null ? [] : [installationLockFd])],
477
+ input,
478
+ stdio: [...(stream ? [input === undefined ? 'ignore' : 'pipe', 'inherit', 'inherit'] : [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe']), ...(installationLockFd === null ? [] : [installationLockFd])],
417
479
  env: childEnv,
418
480
  });
419
481
  if (r.error) {
420
- const error = new Error(`${executable} could not start (${r.error.code ?? 'launch error'})`, { cause: r.error });
482
+ const error = commandFailure(executable, args, r, { sensitive, cwd, env: childEnv });
421
483
  error.code = r.error.code;
422
484
  throw error;
423
485
  }
424
486
  if (r.status !== 0 && !allowCodes.includes(r.status)) {
425
- const detail = sensitive ? '' : (r.stderr || r.stdout || '').trim().split('\n').slice(-3).join('; ');
426
- throw new Error(`${executable} ${args.join(' ')} exited ${r.status}${detail ? `: ${detail}` : ''}`);
487
+ throw commandFailure(executable, args, r, { sensitive, cwd, env: childEnv });
427
488
  }
428
489
  return { ok: true, code: r.status, stdout: r.stdout ?? '' };
429
490
  },
@@ -437,7 +498,8 @@ export function realEffects({ write, ttyFd, env = process.env, home = homedir(),
437
498
  delete childEnv.OURS_INSTALLER_LOCK_FD;
438
499
  if (installationLockFd !== null) childEnv.OURS_INSTALLER_LOCK_FD = '3';
439
500
  const r = spawnSync(cmd, args, { stdio: ['inherit', 'inherit', 'inherit', ...(installationLockFd === null ? [] : [installationLockFd])], env: childEnv });
440
- return { ok: !r.error && r.status === 0, code: r.status ?? -1 };
501
+ if (r.error || r.status !== 0) throw commandFailure(cmd, args, r, { env: childEnv });
502
+ return { ok: true, code: r.status };
441
503
  },
442
504
  installedVersion: (pkg) => installedVersionOf(pkg, npmBin),
443
505
  packageDependencies: (spec) => packageDependenciesOf(spec, npmBin),
@@ -454,7 +516,7 @@ export function realEffects({ write, ttyFd, env = process.env, home = homedir(),
454
516
  return Object.assign(effects, networkEffects(effects));
455
517
  }
456
518
 
457
- export const __testables = { probePort, portTakenSync, readJsonFile, readTextFile, readHostProfileFile, verifyHostProfile, installedVersionOf, packageDependenciesOf, resolvePackageVersion, codexMarketplace, hasClaudePlugin, knownStateDirsIn };
519
+ export const __testables = { probePort, portState, portTakenSync, readJsonFile, readTextFile, readHostProfileFile, verifyHostProfile, installedVersionOf, packageDependenciesOf, resolvePackageVersion, codexMarketplace, hasClaudePlugin, knownStateDirsIn };
458
520
 
459
521
  // -----------------------------------------------------------------------------
460
522
  // THE PAIR
@@ -536,6 +598,7 @@ export function networkEffects(effects) {
536
598
  const baseEnv = (record) => ({
537
599
  OURS_DAEMON_ID: record.instanceId,
538
600
  OURS_IMAGE: `${record.project}:runtime`,
601
+ OURS_GATEWAY_IMAGE: `${record.project}:gateway`,
539
602
  OURS_MAINTENANCE_IMAGE: `${record.project}:maintenance`,
540
603
  OURS_UID: String(record.uid ?? 1000), OURS_GID: String(record.gid ?? 1000),
541
604
  OURS_HOST_PORT: String(record.port ?? 3050),
@@ -547,14 +610,57 @@ export function networkEffects(effects) {
547
610
  'compose', '--project-directory', record.workDir, '--file', join(record.workDir,
548
611
  record.schema === 1 && existsSync(join(record.workDir, 'docker-compose.legacy.yaml'))
549
612
  ? 'docker-compose.legacy.yaml' : 'docker-compose.yaml'),
613
+ ...(record.gateway ? ['--file', join(record.workDir, 'docker-compose.gateway.yaml')] : []),
614
+ ...(existsSync(join(record.workDir, 'compose.recovery.json')) ? ['--file', join(record.workDir, 'compose.recovery.json')] : []),
615
+ ...(engineName(record) === 'podman' ? ['--file', join(record.workDir, 'compose.podman.json')] : []),
616
+ ...(isPluginOnly(record) ? ['--file', join(record.workDir, PLUGIN_ONLY_COMPOSE)] : []),
550
617
  '--project-name', record.project, ...args,
551
618
  ];
552
- const compose = (record, args, options = {}) => effects.run('docker', composeArgs(record, args),
553
- { ...options, env: { ...baseEnv(record), ...options.env } });
619
+ const container = (record, args, options = {}) => runContainer(effects, record, args, options);
620
+ const compose = async (record, args, options = {}) => {
621
+ const selected = { ...options, env: { ...baseEnv(record), ...options.env } };
622
+ if (engineName(record) === 'podman' && args[0] === 'build') {
623
+ const result = await container(record, composeArgs(record, ['--profile', '*', 'config', '--format', 'json']), { env: selected.env });
624
+ for (const command of nativeBuildCommands(JSON.parse(result.stdout), args.slice(1), { ...env, ...selected.env })) await container(record, command, selected);
625
+ return { code: 0, stdout: '' };
626
+ }
627
+ if (engineName(record) === 'podman' && ['run', 'up'].includes(args[0])) {
628
+ const resolved = JSON.parse((await container(record, composeArgs(record, ['--profile', '*', 'config', '--format', 'json']), { env: selected.env })).stdout);
629
+ for (const [key, volume] of Object.entries(resolved.volumes ?? {})) {
630
+ if (volume.external) throw new Error('Unexpected external installation volume');
631
+ const name = volume.name ?? `${record.project}_${key}`;
632
+ const found = await container(record, ['volume', 'inspect', '--format', '{{json .}}', name], { allowCodes: [1] });
633
+ if (found.code === 1) continue;
634
+ const value = JSON.parse(found.stdout);
635
+ 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}`);
636
+ }
637
+ }
638
+ // Compose run can implicitly build an absent administration image. Build
639
+ // its resolved target natively first, just like explicit build operations.
640
+ if (engineName(record) === 'podman' && args[0] === 'run') {
641
+ const resolved = JSON.parse((await container(record, composeArgs(record, ['--profile', '*', 'config', '--format', 'json']), { env: selected.env })).stdout);
642
+ const takesValue = new Set(['--name', '--entrypoint', '--env', '-e', '--user', '-u', '--workdir', '-w', '--volume', '-v', '--publish', '-p', '--label', '-l', '--pull']);
643
+ let name;
644
+ for (let i = 1; i < args.length; i++) {
645
+ if (takesValue.has(args[i])) { i++; continue; }
646
+ if (args[i].startsWith('-')) continue;
647
+ name = args[i]; break;
648
+ }
649
+ const service = resolved.services?.[name];
650
+ if (!service) throw new Error(`Unresolved Podman administration service: ${name}`);
651
+ if (service.build) {
652
+ const image = await container(record, ['image', 'inspect', service.image], { allowCodes: [1] });
653
+ if (image.code === 1) for (const command of nativeBuildCommands(resolved, [name], { ...env, ...selected.env })) await container(record, command, selected);
654
+ }
655
+ }
656
+ return container(record, composeArgs(record, args), selected);
657
+ };
554
658
  const dockerStartupError = async (record, service, cause) => {
555
659
  const args = ['logs', '--no-color', '--tail', '50', '--timestamps', service];
556
660
  const quote = value => `'${String(value).replaceAll("'", "'\\''")}'`;
557
- const command = `OURS_DAEMON_ID=${quote(record.instanceId)} docker ${composeArgs(record, args).map(quote).join(' ')}`;
661
+ const engine = engineName(record);
662
+ const prefix = engine === 'podman' ? ['--remote', '--url', `unix://${record.containerBinding.socket}`] : [];
663
+ const command = `OURS_DAEMON_ID=${quote(record.instanceId)} ${engine} ${[...prefix, ...composeArgs(record, args)].map(quote).join(' ')}`;
558
664
  let detail;
559
665
  try {
560
666
  const logs = await compose(record, args);
@@ -565,7 +671,7 @@ export function networkEffects(effects) {
565
671
  } catch {
566
672
  detail = 'Container logs could not be read.';
567
673
  }
568
- return new Error(`Docker service "${service}" failed to start or become healthy.\n${detail}\nStartup error: ${cause.message}\nInspect logs: ${command}`, { cause });
674
+ 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 });
569
675
  };
570
676
  const bin = (record, name) => join(record.workDir, 'node_modules', '.bin', name);
571
677
  const localEnv = (record, service = 'daemon') => {
@@ -579,21 +685,31 @@ export function networkEffects(effects) {
579
685
  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}` };
580
686
  };
581
687
  const ownerCommand = (record, service, op, options = {}) => {
582
- const name = { daemon: 'ours', telegram: 'ours-tg-connector', cowork: 'ours-cowork' }[service];
583
- const args = service === 'daemon' ? ['daemon', op, ...(['install-service', 'uninstall-service'].includes(op) ? ['--yes'] : []), '--config', record.configPath, '--state-dir', installationPaths(record).daemon, '--json'] : [op];
688
+ const daemonBinary = existsSync(bin(record, 'ours-daemon')) ? 'ours-daemon' : 'ours';
689
+ const name = { daemon: daemonBinary, telegram: 'ours-tg-connector', cowork: 'ours-cowork' }[service];
690
+ 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];
584
691
  return effects.run(bin(record, name), args, { ...options, env: localEnv(record, service) });
585
692
  };
693
+ const statelessGateway = (record, detail) => {
694
+ const labels = detail?.Config?.Labels ?? {};
695
+ return labels['com.docker.compose.project'] === record.project && labels['com.docker.compose.service'] === 'gateway'
696
+ && detail.HostConfig?.ReadonlyRootfs === true && Array.isArray(detail.Mounts) && detail.Mounts.every(mount => mount.Type === 'tmpfs');
697
+ };
586
698
  const requireCleanContainerExit = async (record, selected) => {
587
699
  const containers = await compose(record, ['ps', '-aq', ...selected]);
588
700
  for (const id of containers.stdout.split(/\s+/).filter(Boolean)) {
589
- const result = await effects.run('docker', ['inspect', '--format', '{{json .State}}', id]);
701
+ const result = await container(record, ['inspect', '--format', '{{json .State}}', id]);
590
702
  const state = JSON.parse(result.stdout);
591
703
  if (state.Status !== 'exited' || state.ExitCode !== 0 || state.OOMKilled !== false || state.Dead !== false) {
704
+ // A forced gateway stop cannot damage stored state: accept it only when
705
+ // the container itself proves it has a read-only root and tmpfs mounts.
706
+ if (state.Status === 'exited' && statelessGateway(record, JSON.parse((await container(record, ['inspect', '--format', '{{json .}}', id])).stdout))) continue;
592
707
  throw new Error('Selected source container did not stop cleanly; state operation refused');
593
708
  }
594
709
  }
595
710
  };
596
711
  return {
712
+ credentialRefused: profile => retainedCredentialRefused(profile),
597
713
  ...createServerOnboarding(effects, { compose, localEnv, bin }),
598
714
  sourcePolicyHash(path) {
599
715
  return createHash('sha256').update(readFileSync(path)).digest('hex');
@@ -620,7 +736,7 @@ export function networkEffects(effects) {
620
736
  return version;
621
737
  });
622
738
  },
623
- newInstallation(root, mode) {
739
+ newInstallation(root, mode, { containerEngine, product } = {}) {
624
740
  if (existsSync(root)) {
625
741
  privateDirectory(root);
626
742
  if (readdirSync(root).some(name => name !== '.operation.lock')) throw new Error('Installation root is not empty and has no selection record');
@@ -628,9 +744,13 @@ export function networkEffects(effects) {
628
744
  const instanceId = env.OURS_DAEMON_ID || randomUUID();
629
745
  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');
630
746
  const project = `ours-${createHash('sha256').update(root).digest('hex').slice(0, 16)}`;
631
- 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 };
747
+ if (isPluginOnly(product ?? 'workspace') && mode !== 'docker') throw new Error('Collaboration tools for existing agent apps run in Docker or Podman');
748
+ const services = isPluginOnly(product ?? 'workspace') ? ['daemon'] : [...SERVER_SERVICES, ...(mode === 'docker' ? ['gateway'] : [])];
749
+ const gateway = mode === 'docker' && !isPluginOnly(product ?? 'workspace');
750
+ return { schema: 2, root, mode, ...(isPluginOnly(product ?? 'workspace') ? { product } : {}), ...(containerEngine ? { containerEngine } : {}), instanceId, project, workDir: join(root, 'runtime'), configPath: installationPaths({ schema: 2, root }).config, sourcesPath: join(root, 'sources.json'), services, ...(gateway ? { gateway: { version: 1 } } : {}), port: 3050, coworkPort: 3052, messengerPort: 8420, messengerIdentity: env.OURS_MESSENGER_IDENTITY || null, uid: 1000, gid: 1000 };
632
751
  },
633
- async serverPreflight(record, operation, { existing, sourcePath = record.sourcesPath, sourceManifest, identityName } = {}) {
752
+ async serverPreflight(record, operation, { existing, sourcePath = record.sourcesPath, sourceManifest, identityName, explicitPorts } = {}) {
753
+ if (!existing && operation === 'install' && Number.isInteger(record.port)) selectServerPorts(record, portTakenSync, explicitPorts, effects.out);
634
754
  if (existing) {
635
755
  privateDirectory(record.root);
636
756
  assertPrivateRegularFile(join(record.root, 'installation.json'), 'selection');
@@ -638,37 +758,55 @@ export function networkEffects(effects) {
638
758
  if (env.OURS_DAEMON_ID && env.OURS_DAEMON_ID !== record.instanceId) throw new Error('Conflicting instance ID');
639
759
  }
640
760
  if (record.mode === 'docker') {
641
- const nativeRoot = existing ? '/path/to/new-empty-directory' : record.root;
642
- const quotedRoot = `'${String(nativeRoot).replaceAll("'", "'\\''")}'`;
643
- const quotedName = `'${String(identityName ?? record.messengerIdentity ?? 'Your Name').replaceAll("'", "'\\''")}'`;
644
- const recovery = [
645
- 'Please install Docker Desktop on macOS/Windows, or Docker Engine with the Compose plugin on Linux, and start Docker before retrying.',
646
- 'Docker is recommended for macOS and Windows.',
647
- `Alternatively, use native installation: ours-install server install --mode packages --state-dir ${quotedRoot} --identity-name ${quotedName}`,
648
- 'Native mode requires systemd user services on Linux/WSL or a launchd GUI session on macOS.',
649
- ...(existing ? ['Keep this existing Docker installation in Docker mode; use a separate empty directory for a new native installation.'] : []),
650
- ].join('\n');
651
- try {
652
- await effects.run('docker', ['info', '--format', '{{.ServerVersion}}']);
653
- } catch (cause) {
654
- const problem = cause.code === 'ENOENT'
655
- ? 'Docker command was not found in PATH.'
656
- : `Docker Engine is not reachable. Start Docker and check that your user can access it.\nDetails: ${cause.message}`;
657
- throw new Error(`${problem}\n${recovery}`, { cause });
658
- }
659
- let version;
660
- try {
661
- version = await effects.run('docker', ['compose', 'version', '--short']);
662
- } catch (cause) {
663
- 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 });
664
- }
665
- const match = /^v?(\d+)\.(\d+)/.exec(version.stdout.trim());
666
- if (!match || Number(match[1]) < 2 || (Number(match[1]) === 2 && Number(match[2]) < 35)) {
667
- throw new Error(`Docker Compose 2.35 or newer is required. Update Docker Desktop or the Docker Compose plugin.\n${recovery}`);
761
+ if (engineName(record) === 'podman') {
762
+ await bindPodman(effects, record);
763
+ if (['install', 'start', 'restart', 'update', 'rebuild', 'gateway-enable'].includes(operation)) {
764
+ const userHome = userInfo().homedir;
765
+ 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()}` })) {
766
+ if (env[key] && env[key] !== expected) throw new Error(`${key} selects a custom Podman environment that the standard boot service does not retain`);
767
+ }
768
+ 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');
769
+ await effects.run('systemctl', ['--user', 'is-enabled', 'podman.socket']);
770
+ await effects.run('systemctl', ['--user', 'is-enabled', 'podman-restart.service']);
771
+ const restart = await effects.run('systemctl', ['--user', 'show', 'podman-restart.service', '--property=ExecStart', '--value']);
772
+ 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');
773
+ const linger = await effects.run('loginctl', ['show-user', String(process.getuid()), '--property=Linger', '--value']);
774
+ if (linger.stdout.trim() !== 'yes') throw new Error('Rootless server requires user linger for logout/reboot recovery; ask your administrator to enable it');
775
+ await qualifyPodman(effects, record);
776
+ }
777
+ } else {
778
+ const nativeRoot = existing ? '/path/to/new-empty-directory' : record.root;
779
+ const quotedRoot = `'${String(nativeRoot).replaceAll("'", "'\\''")}'`;
780
+ const quotedName = `'${String(identityName ?? record.messengerIdentity ?? 'Your Name').replaceAll("'", "'\\''")}'`;
781
+ const recovery = [
782
+ 'Please install Docker Desktop on macOS/Windows, or Docker Engine with the Compose plugin on Linux, and start Docker before retrying.',
783
+ 'Docker is recommended for macOS and Windows.',
784
+ `Alternatively, use native installation: ours-install server install --mode packages --state-dir ${quotedRoot} --identity-name ${quotedName}`,
785
+ 'Native mode requires systemd user services on Linux/WSL or a launchd GUI session on macOS.',
786
+ ...(existing ? ['Keep this existing Docker installation in Docker mode; use a separate empty directory for a new native installation.'] : []),
787
+ ].join('\n');
788
+ try {
789
+ await container(record, ['info', '--format', '{{.ServerVersion}}']);
790
+ } catch (cause) {
791
+ const problem = cause.code === 'ENOENT'
792
+ ? 'Docker command was not found in PATH.'
793
+ : `Docker Engine is not reachable. Start Docker and check that your user can access it.\nDetails: ${cause.message}`;
794
+ throw new Error(`${problem}\n${recovery}`, { cause });
795
+ }
796
+ let version;
797
+ try {
798
+ version = await container(record, ['compose', 'version', '--short']);
799
+ } catch (cause) {
800
+ 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 });
801
+ }
802
+ const match = /^v?(\d+)\.(\d+)/.exec(version.stdout.trim());
803
+ if (!match || Number(match[1]) < 2 || (Number(match[1]) === 2 && Number(match[2]) < 35)) {
804
+ throw new Error(`Docker Compose 2.35 or newer is required. Update Docker Desktop or the Docker Compose plugin.\n${recovery}`);
805
+ }
668
806
  }
669
807
  if (operation !== 'status') {
670
808
  // Compose clients can disappear while their Engine-owned command continues.
671
- const active = await effects.run('docker', ['ps', '--filter', `label=com.docker.compose.project=${record.project}`, '--filter', 'label=com.docker.compose.oneoff=True', '--format', '{{.ID}}']);
809
+ const active = await container(record, ['ps', '--filter', `label=com.docker.compose.project=${record.project}`, '--filter', 'label=com.docker.compose.oneoff=True', '--format', '{{.ID}}']);
672
810
  if (active.stdout.trim()) throw new Error('Another server installation operation is still running in Docker');
673
811
  }
674
812
  } else {
@@ -676,7 +814,7 @@ export function networkEffects(effects) {
676
814
  await effects.run(effects.platform.platform === 'linux' ? 'systemctl' : 'launchctl', effects.platform.platform === 'linux' ? ['--user', 'show-environment'] : ['print', `gui/${process.getuid()}`]);
677
815
  if (operation === 'install') {
678
816
  for (const command of ['node', 'npm']) await effects.run(command, ['--version']);
679
- const packages = selectSourcePackages(sourceManifest ?? effects.readJson(existing ? record.sourcesPath : sourcePath), 'server');
817
+ const packages = selectSourcePackages(sourceManifest ?? effects.readJson(existing ? record.sourcesPath : sourcePath), serverRole(record));
680
818
  if (Object.values(packages).some(selection => selection.source)) {
681
819
  // Native dependencies in source builds still use their own toolchains.
682
820
  for (const command of ['python3', 'git', 'make', 'cc']) await effects.run(command, ['--version']);
@@ -696,7 +834,7 @@ export function networkEffects(effects) {
696
834
  },
697
835
  async initializeSelection(record, manifest, { retainConfig = false } = {}) {
698
836
  if (typeof manifest === 'string') manifest = JSON.parse(readFileSync(manifest, 'utf8'));
699
- selectSourcePackages(manifest, 'server');
837
+ selectSourcePackages(manifest, serverRole(record));
700
838
  const bytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);
701
839
  ensurePrivateDirectory(record.root);
702
840
  if (record.schema === 2) {
@@ -707,7 +845,56 @@ export function networkEffects(effects) {
707
845
  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');
708
846
  },
709
847
  async qualifyDockerRuntime(record) { return qualifyDockerRuntime(record, effects); },
848
+ async prepareGateway(record) {
849
+ atomicWriteConfig(join(record.workDir, 'docker-compose.gateway.yaml'), gatewayCompose(record));
850
+ atomicWriteConfig(join(record.workDir, 'nginx.conf'), gatewayNginx(record));
851
+ atomicWriteConfig(join(record.workDir, 'gateway-entrypoint.sh'), readFileSync(join(INSTALLER_ASSETS, 'gateway-entrypoint.sh'), 'utf8'));
852
+ atomicWriteConfig(join(record.workDir, 'Dockerfile.gateway'), readFileSync(join(INSTALLER_ASSETS, 'Dockerfile.gateway'), 'utf8'));
853
+ await compose(record, ['build', 'gateway'], { stream: true, env: { BUILDKIT_PROGRESS: 'plain' } });
854
+ },
855
+ async removeGatewayContainer(record) { await compose(record, ['rm', '-f', 'gateway']); },
856
+ async verifyGateway(record) {
857
+ const { prefix } = gatewayAddress(record);
858
+ const script = `const fs=require('node:fs');let stage='selection';(async()=>{
859
+ const base=${JSON.stringify('http://gateway:8080' + prefix)};
860
+ 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();};
861
+ const selection=await get('/daemon/selection');
862
+ if(selection.instanceId!==${JSON.stringify(record.instanceId)})throw Error('Gateway daemon instance mismatch');
863
+ stage='unauthenticated-management';
864
+ const denied=await fetch(base+'/cowork/management/rpc',{method:'POST',redirect:'error',signal:AbortSignal.timeout(5000),headers:{'content-type':'application/json'},body:'{}'});
865
+ await denied.body?.cancel();if(denied.status!==401)throw Error('Gateway management does not reject unauthenticated requests');
866
+ stage='credential';
867
+ const token=fs.readFileSync('/var/lib/ours/daemon-token','utf8').trim();
868
+ const headers={'x-ours-api-token':token,'content-type':'application/json'};
869
+ stage='authenticated-daemon';
870
+ const identities=await get('/daemon/identities',{headers});
871
+ if(!Array.isArray(identities.identities))throw Error('Gateway daemon API invalid');
872
+ stage='authenticated-management';
873
+ const result=await get('/cowork/management/rpc',{method:'POST',headers,body:JSON.stringify({version:1,id:'installer-readiness',method:'room.list',params:{}})});
874
+ if(result.version!==1||result.id!=='installer-readiness'||!Array.isArray(result.result)||result.error)throw Error('Gateway Cowork management unavailable');
875
+ })().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;});`;
876
+ const result = await compose(record, ['exec', '-T', 'daemon', 'node', '-e', script], { sensitive: true, allowCodes: [1] });
877
+ if (result.code === 1) {
878
+ const match = /^gateway-readiness:(selection|unauthenticated-management|credential|authenticated-daemon|authenticated-management):(EAI_AGAIN|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|CHECK_FAILED)$/.exec(result.stdout.trim());
879
+ const detail = match ? ` (${match[1]}, ${match[2]})` : '';
880
+ throw new Error(`Gateway readiness failed${detail}. Keep installation state intact; check the managed gateway startup and network connection, then retry setup.`);
881
+ }
882
+ },
883
+ async qualifyGatewayRuntime(record) {
884
+ for (const [name, args, capability] of [
885
+ ['cowork', ['--json', 'capabilities'], 'cowork.http-management-v1'],
886
+ ['messenger-server', ['capabilities'], 'messenger.gateway-prefix-v1'],
887
+ ['tg-connector', ['capabilities'], 'telegram.gateway-listener-v1'],
888
+ ]) {
889
+ 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]);
890
+ let value; try { value = JSON.parse(probe.stdout); } catch {}
891
+ const capabilities = value?.result?.capabilities ?? value?.capabilities;
892
+ if (!Array.isArray(capabilities) || !capabilities.includes(capability))
893
+ throw new Error(`Selected ${name} artifact lacks ${capability}; select a compatible release before enabling the gateway`);
894
+ }
895
+ },
710
896
  async prepareInstallation(record, { runtimeOnly = false } = {}) {
897
+ if (!runtimeOnly) await reportBootReadiness(effects, record);
711
898
  let copied = false;
712
899
  if (!existsSync(record.workDir)) {
713
900
  cpSync(INSTALLER_ASSETS, record.workDir, { recursive: true, errorOnExist: true, force: false });
@@ -720,15 +907,35 @@ export function networkEffects(effects) {
720
907
  if (!existsSync(materialized)) writePrivateNew(materialized, retained);
721
908
  else if (!readFileSync(materialized).equals(retained)) throw new Error('Materialized sources differ from retained selection');
722
909
  if (record.mode === 'docker') {
723
- refreshDockerPolicyCopy(record);
910
+ // Image IDs before this run builds anything: only what it creates or changes becomes proof.
911
+ const imagesBefore = runtimeOnly ? null : await effects.imageIds(record);
912
+ if (isPluginOnly(record)) atomicWriteConfig(join(record.workDir, PLUGIN_ONLY_COMPOSE), pluginOnlyCompose());
913
+ if (engineName(record) === 'podman') atomicWriteConfig(join(record.workDir, 'compose.podman.json'), JSON.stringify({ services: Object.fromEntries(record.services.map(name => [name, { restart: 'unless-stopped' }])) }));
914
+ const rebuildPrivateScripts = refreshDockerPolicyCopy(record);
915
+ const rebuildRecovery = refreshDockerRecovery(record);
916
+ atomicWriteConfig(join(record.workDir, 'compose.recovery.json'), JSON.stringify(recoveryCompose(record)));
917
+ if (record.gateway) {
918
+ atomicWriteConfig(join(record.workDir, 'docker-compose.gateway.yaml'), gatewayCompose(record));
919
+ atomicWriteConfig(join(record.workDir, 'nginx.conf'), gatewayNginx(record));
920
+ for (const file of ['Dockerfile.gateway', 'gateway-entrypoint.sh']) atomicWriteConfig(join(record.workDir, file), readFileSync(join(INSTALLER_ASSETS, file), 'utf8'));
921
+ }
724
922
  // The installer owns these dependencies in both installation modes.
725
923
  const { dependencies } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
726
924
  writeFileSync(join(record.workDir, 'scripts/maintenance/package.json'), JSON.stringify({ private: true, type: 'module', dependencies }, null, 2) + '\n', { mode: 0o600 });
727
- const image = await effects.run('docker', ['image', 'inspect', `${record.project}:runtime`], { allowCodes: [1] });
728
- if (image.code !== 0) await compose(record, ['build', 'daemon'], { stream: true, env: { BUILDKIT_PROGRESS: 'plain' } });
925
+ const image = await container(record, ['image', 'inspect', `${record.project}:runtime`], { allowCodes: [1] });
926
+ if (image.code !== 0 || rebuildPrivateScripts || rebuildRecovery) await compose(record, ['build', 'daemon'], { stream: true, env: { BUILDKIT_PROGRESS: 'plain' } });
729
927
  await effects.qualifyDockerRuntime(record);
928
+ if (rebuildPrivateScripts) rmSync(join(record.workDir, '.script-permissions-rebuild'));
929
+ if (rebuildRecovery) rmSync(join(record.workDir, '.recovery-rebuild'));
930
+ if (record.gateway) {
931
+ await effects.qualifyGatewayRuntime(record);
932
+ await compose(record, ['build', 'gateway'], { stream: true, env: { BUILDKIT_PROGRESS: 'plain' } });
933
+ }
730
934
  if (runtimeOnly) return;
731
- await compose(record, ['run', '--rm', '--no-deps', '-T', 'prepare', 'prepare']);
935
+ await effects.prepareServerVolumes(record);
936
+ // Volume preparation may build the maintenance image; record after it.
937
+ const imagesAfter = await effects.imageIds(record);
938
+ await effects.recordOwnedImages(record, changedImages(imagesBefore, imagesAfter));
732
939
  } else {
733
940
  if (!existsSync(join(record.workDir, '.packages-ready'))) {
734
941
  const sourceRoot = join(record.root, `build-${randomUUID()}`);
@@ -749,12 +956,15 @@ export function networkEffects(effects) {
749
956
  const profilePath = join(installationPaths(record).mcp, 'profile.json');
750
957
  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') }));
751
958
  const config = JSON.parse(readFileSync(record.configPath, 'utf8'));
752
- 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') };
753
959
  effects.writeJson(record.configPath, JSON.stringify(config, null, 2) + '\n');
754
960
  const cowork = join(installationPaths(record).cowork, 'config.json');
755
961
  if (!existsSync(cowork)) writePrivateNew(cowork, JSON.stringify({ version: 1, stateDir: installationPaths(record).cowork, rest: { enabled: true, host: '127.0.0.1', port: record.coworkPort } }));
756
962
  }
757
963
  },
964
+ async prepareServerVolumes(record) {
965
+ if (record.mode !== 'docker') return;
966
+ await compose(record, ['run', '--rm', '--no-deps', '-T', 'prepare', 'prepare']);
967
+ },
758
968
  async prepareServerBuild(record, args) {
759
969
  validateInstallation(record, record.root);
760
970
  if (record.schema !== 2 || record.layoutConversion || !['update', 'rebuild'].includes(args.operation)) {
@@ -765,7 +975,7 @@ export function networkEffects(effects) {
765
975
  ? Buffer.from(`${JSON.stringify(args.resolvedSources, null, 2)}\n`)
766
976
  : readFileSync(args.sources))
767
977
  : readFileSync(record.sourcesPath);
768
- selectSourcePackages(JSON.parse(sources), 'server');
978
+ selectSourcePackages(JSON.parse(sources), serverRole(record));
769
979
  privateDirectory(record.root);
770
980
  const root = mkdtempSync(join(record.root, '.build-'));
771
981
  const candidate = { ...record, root, workDir: join(root, 'runtime'), sourcesPath: join(root, 'sources.json'),
@@ -777,6 +987,9 @@ export function networkEffects(effects) {
777
987
  await effects.prepareInstallation(candidate, { runtimeOnly: true });
778
988
  if (candidate.mode === 'docker') {
779
989
  await compose(candidate, ['build', 'state-operation']);
990
+ // The candidate's project name is new for this build: every image under it was
991
+ // built now. Record them with the installation so removal can prove them.
992
+ await effects.recordOwnedImages(record, await effects.imageIds(candidate));
780
993
  await effects.copyDockerBuildRecords(candidate, candidate.workDir);
781
994
  }
782
995
  // npm emits readable build records; maintenance consumes private copies.
@@ -797,17 +1010,26 @@ export function networkEffects(effects) {
797
1010
  },
798
1011
  async copyDockerBuildRecords(record, directory) {
799
1012
  // Inspect immutable image metadata; never reinterpret a failed context copy as legacy.
800
- const label = (await effects.run('docker', ['image', 'inspect', '--format', '{{ index .Config.Labels "network.ours.build-context" }}', `${record.project}:runtime`])).stdout.trim();
1013
+ const label = (await container(record, ['image', 'inspect', '--format', '{{ index .Config.Labels "network.ours.build-context" }}', `${record.project}:runtime`])).stdout.trim();
801
1014
  if (!['', '<no value>', '1'].includes(label)) throw new Error('Unsupported image build-context schema');
802
1015
  const names = [...BASE_RECORDS, ...(label === '1' ? [CONTEXT] : [])];
803
1016
  const stage = mkdtempSync(join(directory, '.records-'));
804
1017
  const name = `${record.project}-records`;
805
1018
  let created = false;
1019
+ // An interrupted earlier run can leave its stopped helper behind; clear only that.
1020
+ const stale = await container(record, ['container', 'inspect', name], { allowCodes: [1] });
1021
+ const [value] = stale.code === 0 ? (() => { try { return JSON.parse(stale.stdout); } catch { return []; } })() : [];
1022
+ if (value) {
1023
+ const helper = value?.State?.Running === false && JSON.stringify(value?.Config?.Entrypoint) === JSON.stringify(['/bin/true'])
1024
+ && value?.Config?.Image === `${record.project}:runtime`;
1025
+ if (!helper) throw new Error(`A container named ${name} exists and is not this installer's stopped build-record helper; remove or rename it, then run the installer again`);
1026
+ await container(record, ['rm', name]);
1027
+ }
806
1028
  try {
807
- await effects.run('docker', ['create', '--name', name, '--entrypoint', '/bin/true', `${record.project}:runtime`]);
1029
+ await container(record, ['create', '--name', name, '--entrypoint', '/bin/true', `${record.project}:runtime`]);
808
1030
  created = true;
809
1031
  for (const file of names) {
810
- await effects.run('docker', ['cp', `${name}:/opt/ours/${file}`, join(stage, file)]);
1032
+ await container(record, ['cp', `${name}:/opt/ours/${file}`, join(stage, file)]);
811
1033
  const st = lstatSync(join(stage, file));
812
1034
  if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o7002)) throw new Error('Unsafe copied build record');
813
1035
  chmodSync(join(stage, file), 0o600);
@@ -817,7 +1039,7 @@ export function networkEffects(effects) {
817
1039
  for (const file of names) renameSync(join(stage, file), join(directory, file));
818
1040
  if (label !== '1' && existsSync(join(directory, CONTEXT))) throw new Error('Legacy image conflicts with retained build context');
819
1041
  } finally {
820
- try { if (created) await effects.run('docker', ['rm', name]); }
1042
+ try { if (created) await container(record, ['rm', name]); }
821
1043
  finally { rmSync(stage, { recursive: true, force: true }); }
822
1044
  }
823
1045
  },
@@ -865,17 +1087,59 @@ export function networkEffects(effects) {
865
1087
  });
866
1088
  }
867
1089
  },
1090
+ async recoverServerBuildNotifications(record, candidate, phase) {
1091
+ const transition = record.buildTransition;
1092
+ if (record.mode !== 'docker' || transition?.operation !== 'update' || !transition.compatible
1093
+ || !['prepared', 'state-updated', 'runtime-activated'].includes(phase)
1094
+ || transition.phase !== phase
1095
+ || transition.candidate.root !== candidate.root) throw new Error('Notifications recovery requires the retained compatible Docker update');
1096
+ const previous = join(candidate.root, 'previous-build');
1097
+ privateDirectory(previous);
1098
+ let active = phase === 'runtime-activated' ? record.workDir : candidate.workDir;
1099
+ // Publication can move both directories before its journal save. Resume
1100
+ // from the protected active copy only when the previous runtime was kept.
1101
+ if (phase === 'state-updated' && !existsSync(candidate.workDir)) {
1102
+ privateDirectory(join(candidate.root, 'previous-runtime'));
1103
+ active = record.workDir;
1104
+ }
1105
+ privateDirectory(active);
1106
+ const encode = directory => Object.fromEntries(Object.entries(readBuildRecords(directory, { privateFiles: true })).map(([name, bytes]) => [name, bytes.toString('base64')]));
1107
+ const input = JSON.stringify({ phase, previous: encode(previous), target: encode(active) });
1108
+ // Execute shipped maintenance against the retained image and its selected
1109
+ // volume/user contract. No image retag, build replacement or host bind mount.
1110
+ const source = readFileSync(join(INSTALLER_ASSETS, 'scripts/maintenance/state-operation.mjs'), 'utf8')
1111
+ .replaceAll("from './", "from 'file:///opt/ours/docker/");
1112
+ const module = `data:text/javascript;base64,${Buffer.from(source).toString('base64')}`;
1113
+ const helper = readFileSync(join(INSTALLER_ASSETS, 'scripts/maintenance/recover-notifications.mjs'), 'utf8')
1114
+ .replace("'./state-operation.mjs'", JSON.stringify(module));
1115
+ const result = await compose({ ...record, workDir: active }, ['run', '--rm', '--no-deps', '-T', '--entrypoint', 'node', 'state-operation', '--input-type=module', '-e', helper], {
1116
+ input, env: { OURS_MAINTENANCE_IMAGE: `${candidate.project}:maintenance`, OURS_STATE_DOMAIN: 'server', OURS_LIVE_ROOT: '/storage/state' },
1117
+ });
1118
+ const recovered = JSON.parse(result.stdout);
1119
+ if (!recovered || Object.keys(recovered).join(',') !== 'stateUpdated' || typeof recovered.stateUpdated !== 'boolean') throw new Error('Invalid Notifications recovery result');
1120
+ return recovered.stateUpdated;
1121
+ },
868
1122
  async publishServerBuild(record, candidate) {
869
1123
  const previous = join(candidate.root, 'previous-runtime');
1124
+ const built = {};
870
1125
  if (record.mode === 'docker') {
871
- for (const target of ['runtime', 'maintenance']) {
1126
+ const proven = effects.ownedImages(record);
1127
+ const before = await effects.imageIds(record);
1128
+ for (const target of ['runtime', 'maintenance', ...(record.gateway ? ['gateway'] : [])]) {
872
1129
  const retained = `${candidate.project}:previous-${target}`;
873
- const found = await effects.run('docker', ['image', 'inspect', retained], { allowCodes: [1] });
1130
+ const found = await container(record, ['image', 'inspect', retained], { allowCodes: [1] });
874
1131
  if (found.code !== 0) {
875
- const current = await effects.run('docker', ['image', 'inspect', `${record.project}:${target}`], { allowCodes: [1] });
876
- if (current.code === 0) await effects.run('docker', ['tag', `${record.project}:${target}`, retained]);
1132
+ const current = await container(record, ['image', 'inspect', `${record.project}:${target}`], { allowCodes: [1] });
1133
+ if (current.code === 0) await container(record, ['tag', `${record.project}:${target}`, retained]);
877
1134
  }
1135
+ // A retained copy is proven only when the image it copies already was.
1136
+ const tag = `${record.project}:${target}`;
1137
+ if (before[tag] && proven[tag] === before[tag]) built[retained] = before[tag];
878
1138
  }
1139
+ // The candidate project name is a random per-build name kept in the private
1140
+ // record; its images were built by this update.
1141
+ Object.assign(built, Object.fromEntries(Object.entries(await effects.imageIds(candidate, ['runtime', 'maintenance', ...(record.gateway ? ['gateway'] : [])]))
1142
+ .map(([tag, id]) => [`${record.project}:${tag.slice(candidate.project.length + 1)}`, id])));
879
1143
  }
880
1144
  if (!existsSync(previous)) {
881
1145
  privateDirectory(record.workDir);
@@ -889,11 +1153,32 @@ export function networkEffects(effects) {
889
1153
  renameSync(candidate.workDir, record.workDir);
890
1154
  } else privateDirectory(record.workDir);
891
1155
  if (record.mode === 'docker') {
892
- for (const target of ['runtime', 'maintenance']) {
893
- await effects.run('docker', ['tag', `${candidate.project}:${target}`, `${record.project}:${target}`]);
1156
+ for (const target of ['runtime', 'maintenance', ...(record.gateway ? ['gateway'] : [])]) {
1157
+ await container(candidate, ['tag', `${candidate.project}:${target}`, `${record.project}:${target}`]);
894
1158
  }
895
1159
  }
896
1160
  atomicWriteConfig(record.sourcesPath, readFileSync(candidate.sourcesPath));
1161
+ if (record.mode === 'docker') await effects.recordOwnedImages(record, built);
1162
+ },
1163
+ /** Current image IDs of this project's tags (only those that exist). */
1164
+ async imageIds(record, targets = IMAGE_TARGETS) {
1165
+ const images = {};
1166
+ for (const target of targets) {
1167
+ const tag = `${record.project}:${target}`;
1168
+ const found = await container(record, ['image', 'inspect', '--format', '{{.Id}}', tag], { allowCodes: [1] });
1169
+ if (found.code === 0 && /^sha256:[0-9a-f]{64}$/.test(found.stdout.trim())) images[tag] = found.stdout.trim();
1170
+ }
1171
+ return images;
1172
+ },
1173
+ ownedImages(record) {
1174
+ const path = join(record.root, OWNED_IMAGES_FILE);
1175
+ try { const value = JSON.parse(readFileSync(path, 'utf8')); return value?.schema === 1 && value.images && typeof value.images === 'object' ? value.images : {}; } catch { return {}; }
1176
+ },
1177
+ /** Add the IDs of images this run built; never adopts a tag it did not produce. */
1178
+ async recordOwnedImages(record, built) {
1179
+ const path = join(record.root, OWNED_IMAGES_FILE);
1180
+ const next = ownedImagesRecord(existsSync(path) ? readFileSync(path, 'utf8') : null, built);
1181
+ if (next) atomicWriteConfig(path, next);
897
1182
  },
898
1183
  async validateServerBuildState(record) {
899
1184
  if (record.mode === 'docker') {
@@ -904,10 +1189,10 @@ export function networkEffects(effects) {
904
1189
  },
905
1190
  async discardServerBuild(candidate) {
906
1191
  if (candidate.mode === 'docker') {
907
- for (const target of ['runtime', 'maintenance', 'previous-runtime', 'previous-maintenance']) {
1192
+ for (const target of ['runtime', 'maintenance', 'previous-runtime', 'previous-maintenance', ...(candidate.gateway ? ['gateway', 'previous-gateway'] : [])]) {
908
1193
  const image = `${candidate.project}:${target}`;
909
- const found = await effects.run('docker', ['image', 'inspect', image], { allowCodes: [1] });
910
- if (found.code === 0) await effects.run('docker', ['image', 'rm', image]);
1194
+ const found = await container(candidate, ['image', 'inspect', image], { allowCodes: [1] });
1195
+ if (found.code === 0) await container(candidate, ['image', 'rm', image]);
911
1196
  }
912
1197
  }
913
1198
  privateDirectory(candidate.root);
@@ -915,7 +1200,15 @@ export function networkEffects(effects) {
915
1200
  },
916
1201
  async serverAccess(record, operation, { output, migrate = false } = {}) {
917
1202
  if (record.mode === 'docker') {
918
- if (!output) return compose(record, ['run', '--rm', '--no-deps', '-T', 'access', operation], { sensitive: true, env: { OURS_ACCESS_MIGRATE: migrate ? '1' : '0' } });
1203
+ // Retained images contain the old helper that discarded CLI errors.
1204
+ // Execute the shipped installer helper against the SAME selected image
1205
+ // and Compose volume/user/environment contract, without retag/rebuild.
1206
+ const diagnosticsUrl = `data:text/javascript;base64,${readFileSync(join(INSTALLER_ASSETS, 'scripts/runtime/diagnostics.mjs')).toString('base64')}`;
1207
+ const helper = `process.argv.splice(1, 0, '/opt/ours/docker/client-setup.mjs');\n` + readFileSync(join(INSTALLER_ASSETS, 'scripts/runtime/client-setup.mjs'), 'utf8')
1208
+ .replace("'../maintenance/build-context.mjs'", "'/opt/ours/maintenance/build-context.mjs'")
1209
+ .replace("'./diagnostics.mjs'", JSON.stringify(diagnosticsUrl));
1210
+ const accessArgs = (...args) => ['--entrypoint', 'node', 'access', '--input-type=module', '-e', helper, '--', ...args];
1211
+ if (!output) return compose(record, ['run', '--rm', '--no-deps', '-T', ...accessArgs(operation)], { sensitive: true, env: { OURS_ACCESS_MIGRATE: migrate ? '1' : '0' } });
919
1212
  privateDirectory(dirname(output));
920
1213
  if (existsSync(output)) throw new Error('Credential output already exists');
921
1214
  const name = `${record.project}-issue-${randomUUID()}`;
@@ -923,23 +1216,23 @@ export function networkEffects(effects) {
923
1216
  const staging = join(dirname(output), `.ours-issued-${randomUUID()}`);
924
1217
  ensurePrivateDirectory(staging);
925
1218
  try {
926
- await compose(record, ['run', '--name', name, '--no-deps', '-T', 'access', 'access-issue', issuedPath], { sensitive: true });
1219
+ await compose(record, ['run', '--name', name, '--no-deps', '-T', ...accessArgs('access-issue', issuedPath)], { sensitive: true });
927
1220
  const file = join(staging, 'credential');
928
- await effects.run('docker', ['cp', `${name}:${issuedPath}`, file], { sensitive: true });
1221
+ await container(record, ['cp', `${name}:${issuedPath}`, file], { sensitive: true });
929
1222
  assertPrivateRegularFile(file, 'issued credential');
930
1223
  // Exclusive publication never overwrites an unrelated credential.
931
1224
  writePrivateNew(output, readFileSync(file));
932
1225
  } finally {
933
1226
  await compose(record, ['run', '--rm', '--no-deps', '-T', '--entrypoint', 'rm', 'access', '-f', issuedPath], { sensitive: true });
934
- await effects.run('docker', ['rm', '-f', name], { sensitive: true });
1227
+ await container(record, ['rm', '-f', name], { sensitive: true });
935
1228
  rmSync(staging, { recursive: true, force: true });
936
1229
  }
937
1230
  return;
938
1231
  }
939
1232
  const options = { env: localEnv(record), sensitive: true };
940
- if (operation !== 'access-issue') return effects.run(bin(record, 'ours'), ['config', operation, '--config', record.configPath, ...(operation === 'access-replace' ? ['--confirm'] : migrate ? ['--migrate'] : []), '--json'], options);
1233
+ 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);
941
1234
  const outputs = output ? [output] : [join(installationPaths(record).daemon, 'daemon-token'), ...['telegram', 'cowork', 'messenger'].map(s => installationPaths(record).credentials[s])];
942
- for (const path of outputs) await effects.run(bin(record, 'ours'), ['config', operation, '--config', record.configPath, '--output', path, ...(output ? [] : ['--replace']), '--json'], options);
1235
+ 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);
943
1236
  },
944
1237
  async recordRuntimeBuild(record) {
945
1238
  if (record.mode === 'docker') return; // Image preparation records its build.
@@ -983,7 +1276,7 @@ export function networkEffects(effects) {
983
1276
  await effects.run(process.execPath, [join(INSTALLER_ASSETS, 'scripts/maintenance/state-operation.mjs'), ...command], {
984
1277
  env: { ...localEnv(record), OURS_STATE_DOMAIN: args.domain,
985
1278
  OURS_STATE_ROOT: join(record.root, 'storage'), OURS_LIVE_ROOT: ['server', 'daemon'].includes(args.domain) ? paths.state : paths[args.domain],
986
- OURS_BUILD_ROOT: record.workDir, OURS_CLI_PATH: bin(record, 'ours'),
1279
+ OURS_BUILD_ROOT: record.workDir, OURS_CLI_PATH: bin(record, existsSync(bin(record, 'ours-daemon')) ? 'ours-daemon' : 'ours'),
987
1280
  OURS_DAEMON_CONFIG: record.configPath, OURS_COWORK_CLI_PATH: bin(record, 'ours-cowork'),
988
1281
  OURS_COWORK_CONFIG: join(paths.cowork, 'config.json'), OURS_COWORK_STATE_DIR: paths.cowork },
989
1282
  });
@@ -1001,12 +1294,12 @@ export function networkEffects(effects) {
1001
1294
  if (typeof name !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(name)) {
1002
1295
  throw new Error('Invalid conversion volume name');
1003
1296
  }
1004
- const result = await effects.run('docker', ['volume', 'inspect', '--format', '{{json .}}', name], {
1297
+ const result = await container(record, ['volume', 'inspect', '--format', '{{json .}}', name], {
1005
1298
  ...(optional ? { allowCodes: [1] } : {}),
1006
1299
  });
1007
1300
  if (result.code !== 0) {
1008
1301
  if (optional) {
1009
- const inventory = await effects.run('docker', ['volume', 'ls', '--format', '{{.Name}}']);
1302
+ const inventory = await container(record, ['volume', 'ls', '--format', '{{.Name}}']);
1010
1303
  if (inventory.code === 0 && !inventory.stdout.split(/\s+/).includes(name)) return false;
1011
1304
  }
1012
1305
  throw new Error(`Source volume is missing or unavailable: ${name}`);
@@ -1068,7 +1361,7 @@ export function networkEffects(effects) {
1068
1361
  await ownerCommand(record, 'cowork', 'prepare-backup');
1069
1362
  },
1070
1363
  async retainConvertedPackageAuthority(record, daemon) {
1071
- await effects.run(bin(record, 'ours'), [
1364
+ await effects.run(bin(record, existsSync(bin(record, 'ours-daemon')) ? 'ours-daemon' : 'ours'), [
1072
1365
  'config', 'access-retain', '--config', record.configPath,
1073
1366
  '--target-state-dir', daemon, '--json',
1074
1367
  ], { env: localEnv(record), sensitive: true });
@@ -1112,6 +1405,28 @@ export function networkEffects(effects) {
1112
1405
  }
1113
1406
  await nativeLifecycle(record, 'retire', record.services, { effects, localEnv, ownerCommand, bin });
1114
1407
  },
1408
+ async serverUninstall(record) {
1409
+ if (record.schema !== 2 || record.layoutConversion || record.buildTransition) throw new Error('Complete retained installation transitions before uninstall');
1410
+ if (record.mode === 'docker') {
1411
+ await effects.serverLifecycle(record, 'stop');
1412
+ await requireCleanContainerExit(record, record.services);
1413
+ await compose(record, ['rm', '-f', ...record.services]);
1414
+ } else await nativeLifecycle(record, 'retire', record.services, { effects, localEnv, ownerCommand, bin });
1415
+ effects.out('Managed services removed; installation selection, stored identities, credentials and volumes retained.');
1416
+ },
1417
+ /**
1418
+ * Stop a managed installation's services before its complete removal.
1419
+ * Docker writers stop through Compose; containers are removed by project
1420
+ * label afterwards. Native services are retired through their owners, which
1421
+ * also removes their boot registrations.
1422
+ */
1423
+ async serverStopForRemoval(record) {
1424
+ if (record.mode === 'docker') {
1425
+ if (existsSync(record.workDir)) await effects.serverLifecycle(record, 'stop');
1426
+ return;
1427
+ }
1428
+ await nativeLifecycle(record, 'retire', record.services, { effects, localEnv, ownerCommand, bin });
1429
+ },
1115
1430
  async serverLifecycle(record, operation, selected = record.services) {
1116
1431
  record = buildRuntime(record);
1117
1432
  if (record.mode === 'docker') {
@@ -1123,14 +1438,22 @@ export function networkEffects(effects) {
1123
1438
  }
1124
1439
  if (operation === 'stop') {
1125
1440
  const consumers = selected.filter(s => s !== 'daemon').reverse();
1441
+ // Gateways created before stop_signal was set still stop with nginx's
1442
+ // SIGQUIT, which waits for open streams beyond the grace period and
1443
+ // ends in SIGKILL. SIGTERM is nginx's fast shutdown; it exits cleanly.
1444
+ if (consumers.includes('gateway')) await compose(record, ['kill', '-s', 'SIGTERM', 'gateway']);
1126
1445
  if (consumers.length) await compose(record, ['stop', ...consumers]);
1127
1446
  if (selected.includes('daemon')) await compose(record, ['stop', 'daemon']);
1128
1447
  if ((await effects.serverLifecycle(record, 'status', selected)).length) throw new Error('Writers did not stop');
1129
1448
  return;
1130
1449
  }
1450
+ if (existsSync(record.workDir)) atomicWriteConfig(join(record.workDir, 'compose.recovery.json'), JSON.stringify(recoveryCompose(record)));
1451
+ await reconcileDockerRecovery(record, effects);
1131
1452
  const start = async service => {
1132
1453
  effects.out(`Starting ${service}; waiting for readiness...`);
1133
- try { await compose(record, ['up', '-d', '--no-build', '--no-deps', '--wait', service]); }
1454
+ // Gateway has no persistent state. Recreate its network endpoint on each
1455
+ // managed start, including retries after an interrupted/failed bind.
1456
+ try { await compose(record, ['up', '-d', '--no-build', '--no-deps', ...(service === 'gateway' ? ['--force-recreate'] : []), '--wait', service]); }
1134
1457
  catch (cause) { throw await dockerStartupError(record, service, cause); }
1135
1458
  effects.out(`${service} is ready.`);
1136
1459
  };
@@ -1140,6 +1463,7 @@ export function networkEffects(effects) {
1140
1463
  try { await start(service); }
1141
1464
  catch (error) { failures.push({ service, error }); }
1142
1465
  }
1466
+ if (!failures.length && record.gateway && ['daemon', 'cowork', 'gateway'].every(service => selected.includes(service))) await effects.verifyGateway(record);
1143
1467
  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')}`);
1144
1468
  return;
1145
1469
  }
@@ -1154,21 +1478,19 @@ export function networkEffects(effects) {
1154
1478
  return JSON.parse(readFileSync(path, 'utf8'));
1155
1479
  },
1156
1480
  async discoverClientProfile(endpoint, credentialPath) {
1157
- const url = new URL(endpoint);
1158
- if (url.protocol !== 'http:' || url.username || url.password || url.pathname !== '/' || url.search || url.hash)
1159
- throw new Error('Client endpoint must be an HTTP origin');
1160
- const response = await fetch(`${url.origin}/selection`, { redirect: 'error', signal: AbortSignal.timeout(5000) });
1161
- if (!response.ok) throw new Error(`Daemon selection answered HTTP ${response.status}`);
1162
- const selection = await response.json();
1163
- // Full metadata and authenticated capability validation follows before publication.
1164
- return validateHostProfile({ endpoint: url.origin, expectedInstanceId: selection.instanceId, credentialPath: resolve(credentialPath) });
1481
+ const base = serverBase(endpoint);
1482
+ const request = path => fetch(`${base}${path}`, { redirect: 'error', signal: AbortSignal.timeout(5000) });
1483
+ const discovery = await request('/.well-known/ours');
1484
+ if (discovery.ok) return validateGatewayDiscovery(base, await discovery.json(), resolve(credentialPath));
1485
+ throw new Error(`Gateway discovery answered HTTP ${discovery.status}; enable the gateway. Direct daemon fallback is not supported.`);
1165
1486
  },
1166
- importClientProfile({ profile, sourcesPath, sources: resolvedSources, integrations, fleetSettingsPath, refresh = false }) {
1487
+ importClientProfile({ profile, sourcesPath, sources: resolvedSources, integrations, fleetSettingsPath, disableFleetAgentsSetup = false, refresh = false, notificationsProducerPath }) {
1488
+ profile = validateGatewayClientProfile(profile);
1167
1489
  const root = join(home, '.ours-client');
1168
1490
  const configPath = join(root, 'profile.json');
1169
1491
  const credentialPath = join(root, 'credential');
1170
1492
  const current = effects.readManagedClientProfile();
1171
- if (current && (current.endpoint !== profile.endpoint || current.expectedInstanceId !== profile.expectedInstanceId))
1493
+ if (current && current.expectedInstanceId !== profile.expectedInstanceId)
1172
1494
  throw new Error('Managed client already selects another server; existing default was not changed');
1173
1495
  assertPrivateRegularFile(profile.credentialPath, 'credential');
1174
1496
  const credential = readFileSync(profile.credentialPath, 'utf8');
@@ -1179,13 +1501,30 @@ export function networkEffects(effects) {
1179
1501
  : readFileSync(sourcesPath);
1180
1502
  const fleetSettings = (!current || refresh) && fleetSettingsPath ? readFileSync(fleetSettingsPath) : null;
1181
1503
  if (fleetSettings) JSON.parse(fleetSettings.toString());
1504
+ let producer = null;
1505
+ if (notificationsProducerPath) {
1506
+ assertPrivateRegularFile(notificationsProducerPath, 'notification producer credential');
1507
+ producer = readFileSync(notificationsProducerPath, 'utf8');
1508
+ let bound; try { bound = JSON.parse(producer); } catch { bound = null; }
1509
+ if (bound?.schema !== 1 || bound.serverUrl !== profile.serverUrl || bound.expectedInstanceId !== profile.expectedInstanceId || !/^[A-Za-z0-9_-]{32,256}$/.test(bound.token ?? ''))
1510
+ throw new Error('Notification producer credential does not match the selected server');
1511
+ }
1182
1512
  ensurePrivateDirectory(root);
1513
+ // Written before the profile it belongs to is published or changed.
1514
+ let notificationsProducerChanged = false;
1515
+ if (producer !== null) {
1516
+ const producerPath = join(root, 'notifications-producer.json');
1517
+ if (!existsSync(producerPath) || readFileSync(producerPath, 'utf8') !== producer) { atomicWriteConfig(producerPath, producer); notificationsProducerChanged = true; }
1518
+ }
1183
1519
  if (current && !refresh) {
1184
1520
  assertPrivateRegularFile(credentialPath, 'managed credential');
1185
1521
  if (readFileSync(credentialPath, 'utf8') !== credential) atomicWriteConfig(credentialPath, credential);
1186
- return { configPath, profile: validateHostProfile(current), settings: current.installer };
1522
+ const saved = { ...current, ...profile, credentialPath };
1523
+ if (current.endpoint !== saved.endpoint || current.serverUrl !== saved.serverUrl)
1524
+ atomicWriteConfig(configPath, JSON.stringify(saved, null, 2) + '\n');
1525
+ return { configPath, profile: validateGatewayClientProfile(saved), settings: current.installer, notificationsProducerChanged };
1187
1526
  }
1188
- const settings = { sourcesPath: join(root, 'sources.json'), integrations };
1527
+ const settings = { sourcesPath: join(root, 'sources.json'), integrations, ...(disableFleetAgentsSetup ? { disableFleetAgentsSetup: true } : {}) };
1189
1528
  if (fleetSettings) settings.fleetSettingsPath = join(root, 'fleet-settings.json');
1190
1529
  // Publish the profile last: clients cannot select incomplete imported inputs.
1191
1530
  atomicWriteConfig(settings.sourcesPath, sources);
@@ -1193,21 +1532,50 @@ export function networkEffects(effects) {
1193
1532
  atomicWriteConfig(credentialPath, credential);
1194
1533
  const saved = { ...profile, credentialPath, installer: settings };
1195
1534
  atomicWriteConfig(configPath, JSON.stringify(saved, null, 2) + '\n');
1196
- return { configPath, profile: validateHostProfile(saved), settings };
1535
+ return { configPath, profile: validateHostProfile(saved), settings, notificationsProducerChanged };
1536
+ },
1537
+ async qualifyInstalledGatewayClient(profile) {
1538
+ if (!profile.installer?.integrations?.includes('fleet')) return;
1539
+ let info;
1540
+ try { info = JSON.parse((await effects.run('ours-fleet', ['version', '--json'])).stdout); } catch {}
1541
+ if (!Array.isArray(info?.capabilities) || !info.capabilities.includes('cowork.http-management-v1'))
1542
+ throw new Error('Installed Fleet does not support gateway HTTP management; upgrade Fleet before gateway-enable');
1543
+ },
1544
+ async qualifyGatewayClient({ profile, sourcesPath, sources, integrations, refresh = false }) {
1545
+ if (!profile.serverUrl || !integrations.includes('fleet')) return;
1546
+ // Acquire into the retained package cache without publishing a profile,
1547
+ // credential, native command, or integration. Normal acquisition rechecks it.
1548
+ const staging = mkdtempSync(join(home, '.ours-gateway-client-'));
1549
+ try {
1550
+ const stagedSources = join(staging, 'sources.json');
1551
+ writeFileSync(stagedSources, sources ? JSON.stringify(sources, null, 2) + '\n' : readFileSync(sourcesPath), { mode: 0o600 });
1552
+ await effects.acquireClientPackages(join(home, '.ours-client/profile.json'), stagedSources, integrations,
1553
+ { refresh, gatewayServerUrl: profile.serverUrl, qualifyOnly: true });
1554
+ } finally { rmSync(staging, { recursive: true, force: true }); }
1197
1555
  },
1198
- async acquireClientPackages(configPath, sourcesPath, integrations, { refresh = false } = {}) {
1556
+ async acquireClientPackages(configPath, sourcesPath, integrations, { refresh = false, hostCliOnly = false, gatewayServerUrl, qualifyOnly = false } = {}) {
1199
1557
  const manifest = JSON.parse(readFileSync(sourcesPath, 'utf8'));
1200
- // Public SDK client APIs are actual integration dependencies; Fleet also owns CLI usage.
1201
- const selected = [...new Set(['sdk', ...(integrations.includes('fleet') ? ['cli'] : []), ...integrations])];
1558
+ // Every client installation includes the native CLI and its SDK dependency.
1559
+ const selected = clientPackageNames(integrations);
1202
1560
  const packages = selectSourcePackages(manifest, 'client', selected);
1203
- const selectionKey = refresh ? JSON.stringify([configPath, manifest, integrations]) : configPath;
1561
+ const selectionKey = JSON.stringify([hostCliOnly ? 'host-cli-private-v1' : 'host-cli-v1', configPath, ...(hostCliOnly ? [manifest] : []), ...(refresh ? [manifest, integrations] : [])]);
1204
1562
  const root = join(home, '.ours-client-install', createHash('sha256').update(selectionKey).digest('hex').slice(0, 16));
1205
1563
  const hasGit = Object.values(packages).some(selection => selection.source);
1206
1564
  await effects.run('npm', ['--version']);
1207
1565
  if (hasGit) {
1208
1566
  for (const command of ['python3', 'git', 'make', 'cc']) await effects.run(command, ['--version']);
1209
1567
  }
1568
+ // This directory retains active executables, not disposable download cache.
1569
+ ensurePrivateDirectory(join(home, '.ours-client-install'));
1210
1570
  ensurePrivateDirectory(root);
1571
+ // Record which installation this acquisition serves, for complete removal.
1572
+ let owner = null;
1573
+ try { owner = readHostProfileFile(configPath)?.expectedInstanceId ?? null; } catch { /* not yet imported */ }
1574
+ const ownersPath = join(root, OWNERS_FILE);
1575
+ try {
1576
+ const ownerRecord = owner ? addOwner(existsSync(ownersPath) ? readFileSync(ownersPath, 'utf8') : null, owner) : null;
1577
+ if (ownerRecord) atomicWriteConfig(ownersPath, ownerRecord);
1578
+ } catch (error) { effects.out?.(`! ${error.message}; complete removal will leave ${root} in place and say so.`); }
1211
1579
  const retained = join(root, 'sources.json');
1212
1580
  const bytes = readFileSync(sourcesPath);
1213
1581
  if (!existsSync(retained)) writePrivateNew(retained, bytes);
@@ -1231,13 +1599,40 @@ export function networkEffects(effects) {
1231
1599
  writePrivateNew(join(root, '.packages-ready'), 'ready\n');
1232
1600
  }
1233
1601
  verifyReleaseGraph(root, manifest, { requiredPackages: Object.keys(packages) });
1602
+ if (integrations.includes('fleet') && (gatewayServerUrl || readHostProfileFile(configPath)?.serverUrl)) {
1603
+ let info;
1604
+ try { info = JSON.parse(readFileSync(join(root, 'node_modules/@ours.network/fleet/dist/build-info.json'), 'utf8')); } catch {}
1605
+ if (!Array.isArray(info?.capabilities) || !info.capabilities.includes('cowork.http-management-v1'))
1606
+ throw new Error('Selected Fleet artifact does not support gateway HTTP management; select a compatible client release');
1607
+ }
1608
+ if (qualifyOnly) return;
1609
+ const cliPolicy = hostCliOnly ? null : hostCliPolicy(manifest);
1234
1610
  // Local acquisition alone does not publish native commands. Use the user's
1235
1611
  // configured npm prefix and retained dependency closure, including on retry.
1236
1612
  for (const name of integrations.filter(name => name === 'fleet' || name === 'codex')) {
1237
1613
  await effects.run('npm', ['install', '--global', '--install-links=false', '--offline', '--ignore-scripts', '--no-audit', '--no-fund', join(root, 'node_modules', '@ours.network', name)]);
1238
1614
  }
1615
+ let cliBin = join(root, 'node_modules/.bin/ours');
1616
+ if (cliPolicy) {
1617
+ const cliSources = join(root, 'host-cli-sources.json');
1618
+ const cliBytes = JSON.stringify(cliPolicy, null, 2) + '\n';
1619
+ if (!existsSync(cliSources)) writePrivateNew(cliSources, cliBytes);
1620
+ else if (readFileSync(cliSources, 'utf8') !== cliBytes) throw new Error('Retained host CLI source selection differs');
1621
+ const acquired = await effects.acquireClientPackages(configPath, cliSources, [], { refresh, hostCliOnly: true });
1622
+ cliBin = acquired.cliBin;
1623
+ } else {
1624
+ // Publish last so optional integration installation cannot downgrade ours.
1625
+ await publishClientCli(effects, join(root, 'node_modules', '@ours.network/cli'), { policy: manifest, isolated: hostCliOnly });
1626
+ }
1239
1627
  const localPackages = Object.fromEntries(integrations.filter(n => n !== 'fleet').map(name => [name, join(root, 'node_modules', '@ours.network', name)]));
1240
- return { localPackages, packages: {}, fleetBin: integrations.includes('fleet') ? join(root, 'node_modules/.bin/ours-fleet') : null };
1628
+ return { localPackages, packages: {}, cliBin, fleetBin: integrations.includes('fleet') ? join(root, 'node_modules/.bin/ours-fleet') : null };
1629
+ },
1630
+ /** Capability tokens the given Fleet executable reports for itself; [] when it reports none. */
1631
+ async fleetCapabilities(fleetBin, env = null) {
1632
+ try {
1633
+ const capabilities = JSON.parse((await effects.run(fleetBin, ['version', '--json'], { env })).stdout).capabilities;
1634
+ return Array.isArray(capabilities) ? capabilities.filter(item => typeof item === 'string') : [];
1635
+ } catch { return []; }
1241
1636
  },
1242
1637
  async prepareClientMarketplace(name, packagePath) {
1243
1638
  const acquisitionRoot = dirname(dirname(dirname(packagePath)));
@@ -1246,7 +1641,7 @@ export function networkEffects(effects) {
1246
1641
  const release = releaseBinding(policy);
1247
1642
  const integrationsPath = join(acquisitionRoot, 'integrations.json');
1248
1643
  const integrations = existsSync(integrationsPath) ? JSON.parse(readFileSync(integrationsPath, 'utf8')) : null;
1249
- const requiredPackages = integrations ? [...new Set(['sdk', ...(integrations.includes('fleet') ? ['cli'] : []), ...integrations])].map(name => '@ours.network/' + name) : Object.keys(policy.packages ?? {});
1644
+ const requiredPackages = integrations ? clientPackageNames(integrations).map(name => '@ours.network/' + name) : Object.keys(policy.packages ?? {});
1250
1645
  verifyReleaseGraph(acquisitionRoot, policy, { requiredPackages });
1251
1646
  const root = join(acquisitionRoot, 'marketplaces', name);
1252
1647
  const plugin = join(root, 'plugins', 'ours');
@@ -1255,7 +1650,7 @@ export function networkEffects(effects) {
1255
1650
  cpSync(packagePath, plugin, { recursive: true });
1256
1651
  const manifestPath = join(plugin, 'package.json');
1257
1652
  const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
1258
- for (const dependency of release ? [] : ['sdk', 'cli']) {
1653
+ for (const dependency of release ? [] : ['sdk', 'cli', 'mcp']) {
1259
1654
  const name = `@ours.network/${dependency}`;
1260
1655
  if (manifest.dependencies?.[name]) manifest.dependencies[name] = `file:${join(dirname(packagePath), dependency)}`;
1261
1656
  }
@@ -1275,42 +1670,7 @@ export function networkEffects(effects) {
1275
1670
  effects.writeJson(manifestPath, JSON.stringify(value, null, 2) + '\n');
1276
1671
  return root;
1277
1672
  },
1278
- async verifyPackagedMcp(configPath) {
1279
- const profile = typeof configPath === 'string' ? readHostProfileFile(configPath) : validateHostProfile(configPath);
1280
- assertPrivateRegularFile(profile.credentialPath, 'credential');
1281
- const token = readFileSync(profile.credentialPath, 'utf8').trim();
1282
- 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() };
1283
- const request = async (method, params, id) => {
1284
- 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 }) });
1285
- const session = response.headers.get('mcp-session-id');
1286
- if (session) headers['mcp-session-id'] = session;
1287
- if (!response.ok) throw new Error(`Packaged MCP verification failed: HTTP ${response.status}`);
1288
- if (id === undefined) { await response.body?.cancel(); return; }
1289
- const text = await response.text();
1290
- const messages = response.headers.get('content-type')?.includes('text/event-stream')
1291
- ? text.split('\n').filter(line => line.startsWith('data:')).map(line => JSON.parse(line.slice(5)))
1292
- : [JSON.parse(text)];
1293
- const message = messages.find(value => value.id === id);
1294
- if (!message || message.error || !message.result) throw new Error('Packaged MCP returned no successful protocol result');
1295
- return message.result;
1296
- };
1297
- try {
1298
- const initialized = await request('initialize', { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'ours-install', version: '1' } }, 1);
1299
- if (initialized.serverInfo?.name !== 'ours' || !initialized.protocolVersion) throw new Error('Selected MCP is not the packaged OURS server');
1300
- headers['mcp-protocol-version'] = initialized.protocolVersion;
1301
- await request('notifications/initialized', {}, undefined);
1302
- const resources = await request('resources/list', {}, 2);
1303
- if (!resources.resources?.some(resource => resource.uri === 'ours://application-identities')) throw new Error('Packaged network MCP identity resource is absent');
1304
- const toolList = await request('tools/list', {}, 3);
1305
- if (!toolList.tools?.some(tool => tool.name === 'list_identities')) throw new Error('Packaged OURS identity tools are absent');
1306
- } finally {
1307
- if (headers['mcp-session-id']) {
1308
- const response = await fetch(`${profile.endpoint}/mcp`, { method: 'DELETE', redirect: 'error', signal: AbortSignal.timeout(5000), headers });
1309
- await response.body?.cancel();
1310
- if (!response.ok) throw new Error('MCP verification session could not be closed');
1311
- }
1312
- }
1313
- },
1673
+
1314
1674
  };
1315
1675
  }
1316
1676
 
@@ -1357,7 +1717,6 @@ async function nativeLifecycle(record, operation, selected, { effects, localEnv,
1357
1717
  if (service === 'daemon') {
1358
1718
  const profilePath = join(installationPaths(record).mcp, 'profile.json');
1359
1719
  await effects.verifyHostProfile(profilePath);
1360
- await effects.verifyPackagedMcp(profilePath);
1361
1720
  return;
1362
1721
  }
1363
1722
  if (service === 'cowork') { await ownerCommand(record, service, 'status'); return; }
@@ -1435,7 +1794,7 @@ async function nativeLifecycle(record, operation, selected, { effects, localEnv,
1435
1794
  }
1436
1795
  if (!ready) throw new Error('Application is not ready');
1437
1796
  } catch {
1438
- if (service === 'daemon') throw new Error('Daemon and packaged MCP are not ready; consumers were not started');
1797
+ if (service === 'daemon') throw new Error('Daemon API is not ready; consumers were not started');
1439
1798
  failures.push(service);
1440
1799
  }
1441
1800
  }