@ours.network/install 1.2.1-nightly.9 → 2.0.1

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 (67) hide show
  1. package/GATEWAY_SETUP.md +178 -0
  2. package/README.md +564 -11
  3. package/ROOTLESS_PODMAN_VALIDATION.md +210 -0
  4. package/assets/Dockerfile +18 -15
  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 +1263 -4538
  10. package/assets/release.json +32 -24
  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 +1 -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/healthcheck.mjs +49 -15
  27. package/assets/scripts/runtime/notifications-gateway.mjs +90 -0
  28. package/assets/scripts/runtime/recover.mjs +202 -0
  29. package/assets/scripts/runtime/start-cowork.sh +5 -0
  30. package/assets/scripts/runtime/start-messenger.sh +29 -4
  31. package/assets/scripts/runtime/start-telegram.sh +5 -0
  32. package/assets/scripts/runtime/supervise.mjs +35 -0
  33. package/assets/sources.json +49 -33
  34. package/install.mjs +12 -2
  35. package/install.sh +5 -2
  36. package/lib/boot-readiness.mjs +96 -0
  37. package/lib/build-transition.mjs +16 -0
  38. package/lib/client-cli.mjs +12 -2
  39. package/lib/container-engine.mjs +127 -0
  40. package/lib/diagnostics.mjs +1 -0
  41. package/lib/docker-conversion-runtime.mjs +7 -4
  42. package/lib/docker-layout-installation.mjs +2 -1
  43. package/lib/docker-recovery.mjs +60 -0
  44. package/lib/docker-runtime-repair.mjs +49 -14
  45. package/lib/effects.mjs +462 -136
  46. package/lib/gateway-transition.mjs +87 -0
  47. package/lib/gateway.mjs +227 -0
  48. package/lib/legacy-migration.mjs +13 -2
  49. package/lib/orchestrate-uninstall.mjs +23 -6
  50. package/lib/orchestrate.mjs +282 -38
  51. package/lib/ownership.mjs +63 -0
  52. package/lib/plan.mjs +37 -11
  53. package/lib/podman-preflight.mjs +40 -0
  54. package/lib/product.mjs +69 -0
  55. package/lib/removal-plan.mjs +437 -0
  56. package/lib/removal.mjs +749 -0
  57. package/lib/security-versions.mjs +38 -0
  58. package/lib/server-onboarding.mjs +182 -16
  59. package/lib/server-ports.mjs +17 -0
  60. package/lib/setup-options.mjs +119 -29
  61. package/lib/setup.mjs +86 -15
  62. package/lib/target.mjs +24 -8
  63. package/lib/uninstall.mjs +2 -2
  64. package/lib/usage.mjs +35 -9
  65. package/lib/welcome.mjs +219 -0
  66. package/lib/workspace-setup.mjs +164 -0
  67. package/package.json +5 -3
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
@@ -12,24 +15,43 @@
12
15
  // unit file or the service manager directly.
13
16
 
14
17
  import { publishClientCli } from './client-cli.mjs';
18
+ import { commandFailure } from './diagnostics.mjs';
15
19
  import { spawnSync, execFileSync } from 'node:child_process';
16
- 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';
17
21
  import { homedir, userInfo, platform as osPlatform, release as osRelease, arch as osArch } from 'node:os';
18
22
  import { fileURLToPath } from 'node:url';
19
23
  import { randomUUID, createHash } from 'node:crypto';
20
24
  import { dirname, join, resolve } from 'node:path';
21
- import { maintenanceServices, installationPaths, validateInstallation, consumerServiceState, unitNameForStateDir, launchdLabelForStateDir, messengerServicePlan, selectSourcePackages, resolveSourcePolicy, SERVER_SERVICES } from './plan.mjs';
22
- import { validateHostProfile } from './target.mjs';
23
- 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, gatewayReadinessScript, describeGatewayReadiness } from './gateway.mjs';
29
+ import { createServerOnboarding, retainedCredentialRefused } from './server-onboarding.mjs';
24
30
  import { atomicWriteConfig, snapshotConfig, restoreConfig } from './config.mjs';
25
31
  import { select as selectOnTty, multiselect as multiselectOnTty, askLine as askLineOnTty } from './prompt.mjs';
26
32
  import { classifyHarnessProbe } from './logic.mjs';
27
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';
28
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';
29
40
  import { BASE_RECORDS, CONTEXT, readBuildRecords, equalBuildRecords, initializeBuildMarker } from '../assets/scripts/maintenance/build-context.mjs';
30
41
  import { hostCliPolicy, releaseBinding, verifyReleaseGraph, verifyRuntimeRelease } from '../assets/scripts/maintenance/release-graph.mjs';
31
42
 
32
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
+
33
55
  async function probePort(port, { timeoutMs = 1500 } = {}) {
34
56
  const controller = new AbortController();
35
57
  const timer = setTimeout(() => controller.abort(), timeoutMs);
@@ -331,6 +353,40 @@ export function realEffects({ write, ttyFd, env = process.env, home = homedir(),
331
353
  closeSync(fd);
332
354
  }
333
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,
334
390
  home,
335
391
  env,
336
392
  version,
@@ -345,6 +401,9 @@ export function realEffects({ write, ttyFd, env = process.env, home = homedir(),
345
401
  // pure planner already gated four ways, and this deletes exactly that.
346
402
  removeDir: (path) => { rmSync(resolve(path), { recursive: true, force: true }); },
347
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)),
348
407
  copyDir: (source, destination) => {
349
408
  mkdirSync(dirname(resolve(destination)), { recursive: true, mode: 0o700 });
350
409
  cpSync(resolve(source), resolve(destination), {
@@ -379,6 +438,7 @@ export function realEffects({ write, ttyFd, env = process.env, home = homedir(),
379
438
  brokerUrl: env.OURS_BROKER_URL ?? 'wss://broker1.ours.network',
380
439
  now: () => Date.now(),
381
440
  probe: (port) => probePort(port),
441
+ portState: (port) => portState(port),
382
442
  isTaken: (port) => portTakenSync(port),
383
443
  readJson: readJsonFile,
384
444
  readProfile: readHostProfileFile,
@@ -401,7 +461,7 @@ export function realEffects({ write, ttyFd, env = process.env, home = homedir(),
401
461
  // invocation only and never to the installer's own process: a state
402
462
  // directory selected by one run must not leak into anything the operator
403
463
  // starts afterwards.
404
- 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 } = {}) => {
405
465
  // Always built from this layer's OWN env rather than left to spawnSync's
406
466
  // implicit inheritance, so what a child receives is a property of the
407
467
  // effects object a caller constructed and not of whatever ambient shell
@@ -414,17 +474,17 @@ export function realEffects({ write, ttyFd, env = process.env, home = homedir(),
414
474
  cwd,
415
475
  timeout,
416
476
  encoding: 'utf8',
417
- 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])],
418
479
  env: childEnv,
419
480
  });
420
481
  if (r.error) {
421
- 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 });
422
483
  error.code = r.error.code;
423
484
  throw error;
424
485
  }
425
486
  if (r.status !== 0 && !allowCodes.includes(r.status)) {
426
- const detail = sensitive ? '' : (r.stderr || r.stdout || '').trim().split('\n').slice(-3).join('; ');
427
- throw new Error(`${executable} ${args.join(' ')} exited ${r.status}${detail ? `: ${detail}` : ''}`);
487
+ throw commandFailure(executable, args, r, { sensitive, cwd, env: childEnv });
428
488
  }
429
489
  return { ok: true, code: r.status, stdout: r.stdout ?? '' };
430
490
  },
@@ -438,7 +498,8 @@ export function realEffects({ write, ttyFd, env = process.env, home = homedir(),
438
498
  delete childEnv.OURS_INSTALLER_LOCK_FD;
439
499
  if (installationLockFd !== null) childEnv.OURS_INSTALLER_LOCK_FD = '3';
440
500
  const r = spawnSync(cmd, args, { stdio: ['inherit', 'inherit', 'inherit', ...(installationLockFd === null ? [] : [installationLockFd])], env: childEnv });
441
- 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 };
442
503
  },
443
504
  installedVersion: (pkg) => installedVersionOf(pkg, npmBin),
444
505
  packageDependencies: (spec) => packageDependenciesOf(spec, npmBin),
@@ -455,7 +516,7 @@ export function realEffects({ write, ttyFd, env = process.env, home = homedir(),
455
516
  return Object.assign(effects, networkEffects(effects));
456
517
  }
457
518
 
458
- 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 };
459
520
 
460
521
  // -----------------------------------------------------------------------------
461
522
  // THE PAIR
@@ -537,6 +598,7 @@ export function networkEffects(effects) {
537
598
  const baseEnv = (record) => ({
538
599
  OURS_DAEMON_ID: record.instanceId,
539
600
  OURS_IMAGE: `${record.project}:runtime`,
601
+ OURS_GATEWAY_IMAGE: `${record.project}:gateway`,
540
602
  OURS_MAINTENANCE_IMAGE: `${record.project}:maintenance`,
541
603
  OURS_UID: String(record.uid ?? 1000), OURS_GID: String(record.gid ?? 1000),
542
604
  OURS_HOST_PORT: String(record.port ?? 3050),
@@ -548,14 +610,57 @@ export function networkEffects(effects) {
548
610
  'compose', '--project-directory', record.workDir, '--file', join(record.workDir,
549
611
  record.schema === 1 && existsSync(join(record.workDir, 'docker-compose.legacy.yaml'))
550
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)] : []),
551
617
  '--project-name', record.project, ...args,
552
618
  ];
553
- const compose = (record, args, options = {}) => effects.run('docker', composeArgs(record, args),
554
- { ...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
+ };
555
658
  const dockerStartupError = async (record, service, cause) => {
556
659
  const args = ['logs', '--no-color', '--tail', '50', '--timestamps', service];
557
660
  const quote = value => `'${String(value).replaceAll("'", "'\\''")}'`;
558
- 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(' ')}`;
559
664
  let detail;
560
665
  try {
561
666
  const logs = await compose(record, args);
@@ -566,7 +671,7 @@ export function networkEffects(effects) {
566
671
  } catch {
567
672
  detail = 'Container logs could not be read.';
568
673
  }
569
- 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 });
570
675
  };
571
676
  const bin = (record, name) => join(record.workDir, 'node_modules', '.bin', name);
572
677
  const localEnv = (record, service = 'daemon') => {
@@ -580,21 +685,31 @@ export function networkEffects(effects) {
580
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}` };
581
686
  };
582
687
  const ownerCommand = (record, service, op, options = {}) => {
583
- const name = { daemon: 'ours', telegram: 'ours-tg-connector', cowork: 'ours-cowork' }[service];
584
- 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];
585
691
  return effects.run(bin(record, name), args, { ...options, env: localEnv(record, service) });
586
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
+ };
587
698
  const requireCleanContainerExit = async (record, selected) => {
588
699
  const containers = await compose(record, ['ps', '-aq', ...selected]);
589
700
  for (const id of containers.stdout.split(/\s+/).filter(Boolean)) {
590
- const result = await effects.run('docker', ['inspect', '--format', '{{json .State}}', id]);
701
+ const result = await container(record, ['inspect', '--format', '{{json .State}}', id]);
591
702
  const state = JSON.parse(result.stdout);
592
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;
593
707
  throw new Error('Selected source container did not stop cleanly; state operation refused');
594
708
  }
595
709
  }
596
710
  };
597
711
  return {
712
+ credentialRefused: profile => retainedCredentialRefused(profile),
598
713
  ...createServerOnboarding(effects, { compose, localEnv, bin }),
599
714
  sourcePolicyHash(path) {
600
715
  return createHash('sha256').update(readFileSync(path)).digest('hex');
@@ -621,7 +736,7 @@ export function networkEffects(effects) {
621
736
  return version;
622
737
  });
623
738
  },
624
- newInstallation(root, mode) {
739
+ newInstallation(root, mode, { containerEngine, product } = {}) {
625
740
  if (existsSync(root)) {
626
741
  privateDirectory(root);
627
742
  if (readdirSync(root).some(name => name !== '.operation.lock')) throw new Error('Installation root is not empty and has no selection record');
@@ -629,9 +744,13 @@ export function networkEffects(effects) {
629
744
  const instanceId = env.OURS_DAEMON_ID || randomUUID();
630
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');
631
746
  const project = `ours-${createHash('sha256').update(root).digest('hex').slice(0, 16)}`;
632
- 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 };
633
751
  },
634
- 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);
635
754
  if (existing) {
636
755
  privateDirectory(record.root);
637
756
  assertPrivateRegularFile(join(record.root, 'installation.json'), 'selection');
@@ -639,37 +758,55 @@ export function networkEffects(effects) {
639
758
  if (env.OURS_DAEMON_ID && env.OURS_DAEMON_ID !== record.instanceId) throw new Error('Conflicting instance ID');
640
759
  }
641
760
  if (record.mode === 'docker') {
642
- const nativeRoot = existing ? '/path/to/new-empty-directory' : record.root;
643
- const quotedRoot = `'${String(nativeRoot).replaceAll("'", "'\\''")}'`;
644
- const quotedName = `'${String(identityName ?? record.messengerIdentity ?? 'Your Name').replaceAll("'", "'\\''")}'`;
645
- const recovery = [
646
- 'Please install Docker Desktop on macOS/Windows, or Docker Engine with the Compose plugin on Linux, and start Docker before retrying.',
647
- 'Docker is recommended for macOS and Windows.',
648
- `Alternatively, use native installation: ours-install server install --mode packages --state-dir ${quotedRoot} --identity-name ${quotedName}`,
649
- 'Native mode requires systemd user services on Linux/WSL or a launchd GUI session on macOS.',
650
- ...(existing ? ['Keep this existing Docker installation in Docker mode; use a separate empty directory for a new native installation.'] : []),
651
- ].join('\n');
652
- try {
653
- await effects.run('docker', ['info', '--format', '{{.ServerVersion}}']);
654
- } catch (cause) {
655
- const problem = cause.code === 'ENOENT'
656
- ? 'Docker command was not found in PATH.'
657
- : `Docker Engine is not reachable. Start Docker and check that your user can access it.\nDetails: ${cause.message}`;
658
- throw new Error(`${problem}\n${recovery}`, { cause });
659
- }
660
- let version;
661
- try {
662
- version = await effects.run('docker', ['compose', 'version', '--short']);
663
- } catch (cause) {
664
- 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 });
665
- }
666
- const match = /^v?(\d+)\.(\d+)/.exec(version.stdout.trim());
667
- if (!match || Number(match[1]) < 2 || (Number(match[1]) === 2 && Number(match[2]) < 35)) {
668
- 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
+ }
669
806
  }
670
807
  if (operation !== 'status') {
671
808
  // Compose clients can disappear while their Engine-owned command continues.
672
- 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}}']);
673
810
  if (active.stdout.trim()) throw new Error('Another server installation operation is still running in Docker');
674
811
  }
675
812
  } else {
@@ -677,7 +814,7 @@ export function networkEffects(effects) {
677
814
  await effects.run(effects.platform.platform === 'linux' ? 'systemctl' : 'launchctl', effects.platform.platform === 'linux' ? ['--user', 'show-environment'] : ['print', `gui/${process.getuid()}`]);
678
815
  if (operation === 'install') {
679
816
  for (const command of ['node', 'npm']) await effects.run(command, ['--version']);
680
- const packages = selectSourcePackages(sourceManifest ?? effects.readJson(existing ? record.sourcesPath : sourcePath), 'server');
817
+ const packages = selectSourcePackages(sourceManifest ?? effects.readJson(existing ? record.sourcesPath : sourcePath), serverRole(record));
681
818
  if (Object.values(packages).some(selection => selection.source)) {
682
819
  // Native dependencies in source builds still use their own toolchains.
683
820
  for (const command of ['python3', 'git', 'make', 'cc']) await effects.run(command, ['--version']);
@@ -697,7 +834,7 @@ export function networkEffects(effects) {
697
834
  },
698
835
  async initializeSelection(record, manifest, { retainConfig = false } = {}) {
699
836
  if (typeof manifest === 'string') manifest = JSON.parse(readFileSync(manifest, 'utf8'));
700
- selectSourcePackages(manifest, 'server');
837
+ selectSourcePackages(manifest, serverRole(record));
701
838
  const bytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);
702
839
  ensurePrivateDirectory(record.root);
703
840
  if (record.schema === 2) {
@@ -708,7 +845,39 @@ export function networkEffects(effects) {
708
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');
709
846
  },
710
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 = gatewayReadinessScript({ base: 'http://gateway:8080' + prefix, instanceId: record.instanceId });
859
+ const result = await compose(record, ['exec', '-T', 'daemon', 'node', '-e', script], { sensitive: true, allowCodes: [1] });
860
+ if (result.code === 1) {
861
+ const described = describeGatewayReadiness(result.stdout);
862
+ const detail = described ? ` (${described})` : '';
863
+ throw new Error(`Gateway readiness failed${detail}. Keep installation state intact; check the managed gateway startup and network connection, then retry setup.`);
864
+ }
865
+ },
866
+ async qualifyGatewayRuntime(record) {
867
+ for (const [name, args, capability] of [
868
+ ['cowork', ['--json', 'capabilities'], 'cowork.http-management-v1'],
869
+ ['messenger-server', ['capabilities'], 'messenger.gateway-prefix-v1'],
870
+ ['tg-connector', ['capabilities'], 'telegram.gateway-listener-v1'],
871
+ ]) {
872
+ 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]);
873
+ let value; try { value = JSON.parse(probe.stdout); } catch {}
874
+ const capabilities = value?.result?.capabilities ?? value?.capabilities;
875
+ if (!Array.isArray(capabilities) || !capabilities.includes(capability))
876
+ throw new Error(`Selected ${name} artifact lacks ${capability}; select a compatible release before enabling the gateway`);
877
+ }
878
+ },
711
879
  async prepareInstallation(record, { runtimeOnly = false } = {}) {
880
+ if (!runtimeOnly) await reportBootReadiness(effects, record);
712
881
  let copied = false;
713
882
  if (!existsSync(record.workDir)) {
714
883
  cpSync(INSTALLER_ASSETS, record.workDir, { recursive: true, errorOnExist: true, force: false });
@@ -721,15 +890,35 @@ export function networkEffects(effects) {
721
890
  if (!existsSync(materialized)) writePrivateNew(materialized, retained);
722
891
  else if (!readFileSync(materialized).equals(retained)) throw new Error('Materialized sources differ from retained selection');
723
892
  if (record.mode === 'docker') {
724
- refreshDockerPolicyCopy(record);
893
+ // Image IDs before this run builds anything: only what it creates or changes becomes proof.
894
+ const imagesBefore = runtimeOnly ? null : await effects.imageIds(record);
895
+ if (isPluginOnly(record)) atomicWriteConfig(join(record.workDir, PLUGIN_ONLY_COMPOSE), pluginOnlyCompose());
896
+ if (engineName(record) === 'podman') atomicWriteConfig(join(record.workDir, 'compose.podman.json'), JSON.stringify({ services: Object.fromEntries(record.services.map(name => [name, { restart: 'unless-stopped' }])) }));
897
+ const rebuildPrivateScripts = refreshDockerPolicyCopy(record);
898
+ const rebuildRecovery = refreshDockerRecovery(record);
899
+ atomicWriteConfig(join(record.workDir, 'compose.recovery.json'), JSON.stringify(recoveryCompose(record)));
900
+ if (record.gateway) {
901
+ atomicWriteConfig(join(record.workDir, 'docker-compose.gateway.yaml'), gatewayCompose(record));
902
+ atomicWriteConfig(join(record.workDir, 'nginx.conf'), gatewayNginx(record));
903
+ for (const file of ['Dockerfile.gateway', 'gateway-entrypoint.sh']) atomicWriteConfig(join(record.workDir, file), readFileSync(join(INSTALLER_ASSETS, file), 'utf8'));
904
+ }
725
905
  // The installer owns these dependencies in both installation modes.
726
906
  const { dependencies } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
727
907
  writeFileSync(join(record.workDir, 'scripts/maintenance/package.json'), JSON.stringify({ private: true, type: 'module', dependencies }, null, 2) + '\n', { mode: 0o600 });
728
- const image = await effects.run('docker', ['image', 'inspect', `${record.project}:runtime`], { allowCodes: [1] });
729
- if (image.code !== 0) await compose(record, ['build', 'daemon'], { stream: true, env: { BUILDKIT_PROGRESS: 'plain' } });
908
+ const image = await container(record, ['image', 'inspect', `${record.project}:runtime`], { allowCodes: [1] });
909
+ if (image.code !== 0 || rebuildPrivateScripts || rebuildRecovery) await compose(record, ['build', 'daemon'], { stream: true, env: { BUILDKIT_PROGRESS: 'plain' } });
730
910
  await effects.qualifyDockerRuntime(record);
911
+ if (rebuildPrivateScripts) rmSync(join(record.workDir, '.script-permissions-rebuild'));
912
+ if (rebuildRecovery) rmSync(join(record.workDir, '.recovery-rebuild'));
913
+ if (record.gateway) {
914
+ await effects.qualifyGatewayRuntime(record);
915
+ await compose(record, ['build', 'gateway'], { stream: true, env: { BUILDKIT_PROGRESS: 'plain' } });
916
+ }
731
917
  if (runtimeOnly) return;
732
- await compose(record, ['run', '--rm', '--no-deps', '-T', 'prepare', 'prepare']);
918
+ await effects.prepareServerVolumes(record);
919
+ // Volume preparation may build the maintenance image; record after it.
920
+ const imagesAfter = await effects.imageIds(record);
921
+ await effects.recordOwnedImages(record, changedImages(imagesBefore, imagesAfter));
733
922
  } else {
734
923
  if (!existsSync(join(record.workDir, '.packages-ready'))) {
735
924
  const sourceRoot = join(record.root, `build-${randomUUID()}`);
@@ -750,12 +939,15 @@ export function networkEffects(effects) {
750
939
  const profilePath = join(installationPaths(record).mcp, 'profile.json');
751
940
  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') }));
752
941
  const config = JSON.parse(readFileSync(record.configPath, 'utf8'));
753
- 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') };
754
942
  effects.writeJson(record.configPath, JSON.stringify(config, null, 2) + '\n');
755
943
  const cowork = join(installationPaths(record).cowork, 'config.json');
756
944
  if (!existsSync(cowork)) writePrivateNew(cowork, JSON.stringify({ version: 1, stateDir: installationPaths(record).cowork, rest: { enabled: true, host: '127.0.0.1', port: record.coworkPort } }));
757
945
  }
758
946
  },
947
+ async prepareServerVolumes(record) {
948
+ if (record.mode !== 'docker') return;
949
+ await compose(record, ['run', '--rm', '--no-deps', '-T', 'prepare', 'prepare']);
950
+ },
759
951
  async prepareServerBuild(record, args) {
760
952
  validateInstallation(record, record.root);
761
953
  if (record.schema !== 2 || record.layoutConversion || !['update', 'rebuild'].includes(args.operation)) {
@@ -766,7 +958,7 @@ export function networkEffects(effects) {
766
958
  ? Buffer.from(`${JSON.stringify(args.resolvedSources, null, 2)}\n`)
767
959
  : readFileSync(args.sources))
768
960
  : readFileSync(record.sourcesPath);
769
- selectSourcePackages(JSON.parse(sources), 'server');
961
+ selectSourcePackages(JSON.parse(sources), serverRole(record));
770
962
  privateDirectory(record.root);
771
963
  const root = mkdtempSync(join(record.root, '.build-'));
772
964
  const candidate = { ...record, root, workDir: join(root, 'runtime'), sourcesPath: join(root, 'sources.json'),
@@ -778,6 +970,9 @@ export function networkEffects(effects) {
778
970
  await effects.prepareInstallation(candidate, { runtimeOnly: true });
779
971
  if (candidate.mode === 'docker') {
780
972
  await compose(candidate, ['build', 'state-operation']);
973
+ // The candidate's project name is new for this build: every image under it was
974
+ // built now. Record them with the installation so removal can prove them.
975
+ await effects.recordOwnedImages(record, await effects.imageIds(candidate));
781
976
  await effects.copyDockerBuildRecords(candidate, candidate.workDir);
782
977
  }
783
978
  // npm emits readable build records; maintenance consumes private copies.
@@ -798,17 +993,26 @@ export function networkEffects(effects) {
798
993
  },
799
994
  async copyDockerBuildRecords(record, directory) {
800
995
  // Inspect immutable image metadata; never reinterpret a failed context copy as legacy.
801
- const label = (await effects.run('docker', ['image', 'inspect', '--format', '{{ index .Config.Labels "network.ours.build-context" }}', `${record.project}:runtime`])).stdout.trim();
996
+ const label = (await container(record, ['image', 'inspect', '--format', '{{ index .Config.Labels "network.ours.build-context" }}', `${record.project}:runtime`])).stdout.trim();
802
997
  if (!['', '<no value>', '1'].includes(label)) throw new Error('Unsupported image build-context schema');
803
998
  const names = [...BASE_RECORDS, ...(label === '1' ? [CONTEXT] : [])];
804
999
  const stage = mkdtempSync(join(directory, '.records-'));
805
1000
  const name = `${record.project}-records`;
806
1001
  let created = false;
1002
+ // An interrupted earlier run can leave its stopped helper behind; clear only that.
1003
+ const stale = await container(record, ['container', 'inspect', name], { allowCodes: [1] });
1004
+ const [value] = stale.code === 0 ? (() => { try { return JSON.parse(stale.stdout); } catch { return []; } })() : [];
1005
+ if (value) {
1006
+ const helper = value?.State?.Running === false && JSON.stringify(value?.Config?.Entrypoint) === JSON.stringify(['/bin/true'])
1007
+ && value?.Config?.Image === `${record.project}:runtime`;
1008
+ 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`);
1009
+ await container(record, ['rm', name]);
1010
+ }
807
1011
  try {
808
- await effects.run('docker', ['create', '--name', name, '--entrypoint', '/bin/true', `${record.project}:runtime`]);
1012
+ await container(record, ['create', '--name', name, '--entrypoint', '/bin/true', `${record.project}:runtime`]);
809
1013
  created = true;
810
1014
  for (const file of names) {
811
- await effects.run('docker', ['cp', `${name}:/opt/ours/${file}`, join(stage, file)]);
1015
+ await container(record, ['cp', `${name}:/opt/ours/${file}`, join(stage, file)]);
812
1016
  const st = lstatSync(join(stage, file));
813
1017
  if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o7002)) throw new Error('Unsafe copied build record');
814
1018
  chmodSync(join(stage, file), 0o600);
@@ -818,7 +1022,7 @@ export function networkEffects(effects) {
818
1022
  for (const file of names) renameSync(join(stage, file), join(directory, file));
819
1023
  if (label !== '1' && existsSync(join(directory, CONTEXT))) throw new Error('Legacy image conflicts with retained build context');
820
1024
  } finally {
821
- try { if (created) await effects.run('docker', ['rm', name]); }
1025
+ try { if (created) await container(record, ['rm', name]); }
822
1026
  finally { rmSync(stage, { recursive: true, force: true }); }
823
1027
  }
824
1028
  },
@@ -866,17 +1070,59 @@ export function networkEffects(effects) {
866
1070
  });
867
1071
  }
868
1072
  },
1073
+ async recoverServerBuildNotifications(record, candidate, phase) {
1074
+ const transition = record.buildTransition;
1075
+ if (record.mode !== 'docker' || transition?.operation !== 'update' || !transition.compatible
1076
+ || !['prepared', 'state-updated', 'runtime-activated'].includes(phase)
1077
+ || transition.phase !== phase
1078
+ || transition.candidate.root !== candidate.root) throw new Error('Notifications recovery requires the retained compatible Docker update');
1079
+ const previous = join(candidate.root, 'previous-build');
1080
+ privateDirectory(previous);
1081
+ let active = phase === 'runtime-activated' ? record.workDir : candidate.workDir;
1082
+ // Publication can move both directories before its journal save. Resume
1083
+ // from the protected active copy only when the previous runtime was kept.
1084
+ if (phase === 'state-updated' && !existsSync(candidate.workDir)) {
1085
+ privateDirectory(join(candidate.root, 'previous-runtime'));
1086
+ active = record.workDir;
1087
+ }
1088
+ privateDirectory(active);
1089
+ const encode = directory => Object.fromEntries(Object.entries(readBuildRecords(directory, { privateFiles: true })).map(([name, bytes]) => [name, bytes.toString('base64')]));
1090
+ const input = JSON.stringify({ phase, previous: encode(previous), target: encode(active) });
1091
+ // Execute shipped maintenance against the retained image and its selected
1092
+ // volume/user contract. No image retag, build replacement or host bind mount.
1093
+ const source = readFileSync(join(INSTALLER_ASSETS, 'scripts/maintenance/state-operation.mjs'), 'utf8')
1094
+ .replaceAll("from './", "from 'file:///opt/ours/docker/");
1095
+ const module = `data:text/javascript;base64,${Buffer.from(source).toString('base64')}`;
1096
+ const helper = readFileSync(join(INSTALLER_ASSETS, 'scripts/maintenance/recover-notifications.mjs'), 'utf8')
1097
+ .replace("'./state-operation.mjs'", JSON.stringify(module));
1098
+ const result = await compose({ ...record, workDir: active }, ['run', '--rm', '--no-deps', '-T', '--entrypoint', 'node', 'state-operation', '--input-type=module', '-e', helper], {
1099
+ input, env: { OURS_MAINTENANCE_IMAGE: `${candidate.project}:maintenance`, OURS_STATE_DOMAIN: 'server', OURS_LIVE_ROOT: '/storage/state' },
1100
+ });
1101
+ const recovered = JSON.parse(result.stdout);
1102
+ if (!recovered || Object.keys(recovered).join(',') !== 'stateUpdated' || typeof recovered.stateUpdated !== 'boolean') throw new Error('Invalid Notifications recovery result');
1103
+ return recovered.stateUpdated;
1104
+ },
869
1105
  async publishServerBuild(record, candidate) {
870
1106
  const previous = join(candidate.root, 'previous-runtime');
1107
+ const built = {};
871
1108
  if (record.mode === 'docker') {
872
- for (const target of ['runtime', 'maintenance']) {
1109
+ const proven = effects.ownedImages(record);
1110
+ const before = await effects.imageIds(record);
1111
+ for (const target of ['runtime', 'maintenance', ...(record.gateway ? ['gateway'] : [])]) {
873
1112
  const retained = `${candidate.project}:previous-${target}`;
874
- const found = await effects.run('docker', ['image', 'inspect', retained], { allowCodes: [1] });
1113
+ const found = await container(record, ['image', 'inspect', retained], { allowCodes: [1] });
875
1114
  if (found.code !== 0) {
876
- const current = await effects.run('docker', ['image', 'inspect', `${record.project}:${target}`], { allowCodes: [1] });
877
- if (current.code === 0) await effects.run('docker', ['tag', `${record.project}:${target}`, retained]);
1115
+ const current = await container(record, ['image', 'inspect', `${record.project}:${target}`], { allowCodes: [1] });
1116
+ if (current.code === 0) await container(record, ['tag', `${record.project}:${target}`, retained]);
878
1117
  }
1118
+ // A retained copy is proven only when the image it copies already was.
1119
+ const tag = `${record.project}:${target}`;
1120
+ if (before[tag] && proven[tag] === before[tag]) built[retained] = before[tag];
879
1121
  }
1122
+ // The candidate project name is a random per-build name kept in the private
1123
+ // record; its images were built by this update.
1124
+ Object.assign(built, Object.fromEntries(Object.entries(await effects.imageIds(candidate, ['runtime', 'maintenance', ...(record.gateway ? ['gateway'] : [])]))
1125
+ .map(([tag, id]) => [`${record.project}:${tag.slice(candidate.project.length + 1)}`, id])));
880
1126
  }
881
1127
  if (!existsSync(previous)) {
882
1128
  privateDirectory(record.workDir);
@@ -890,11 +1136,32 @@ export function networkEffects(effects) {
890
1136
  renameSync(candidate.workDir, record.workDir);
891
1137
  } else privateDirectory(record.workDir);
892
1138
  if (record.mode === 'docker') {
893
- for (const target of ['runtime', 'maintenance']) {
894
- await effects.run('docker', ['tag', `${candidate.project}:${target}`, `${record.project}:${target}`]);
1139
+ for (const target of ['runtime', 'maintenance', ...(record.gateway ? ['gateway'] : [])]) {
1140
+ await container(candidate, ['tag', `${candidate.project}:${target}`, `${record.project}:${target}`]);
895
1141
  }
896
1142
  }
897
1143
  atomicWriteConfig(record.sourcesPath, readFileSync(candidate.sourcesPath));
1144
+ if (record.mode === 'docker') await effects.recordOwnedImages(record, built);
1145
+ },
1146
+ /** Current image IDs of this project's tags (only those that exist). */
1147
+ async imageIds(record, targets = IMAGE_TARGETS) {
1148
+ const images = {};
1149
+ for (const target of targets) {
1150
+ const tag = `${record.project}:${target}`;
1151
+ const found = await container(record, ['image', 'inspect', '--format', '{{.Id}}', tag], { allowCodes: [1] });
1152
+ if (found.code === 0 && /^sha256:[0-9a-f]{64}$/.test(found.stdout.trim())) images[tag] = found.stdout.trim();
1153
+ }
1154
+ return images;
1155
+ },
1156
+ ownedImages(record) {
1157
+ const path = join(record.root, OWNED_IMAGES_FILE);
1158
+ try { const value = JSON.parse(readFileSync(path, 'utf8')); return value?.schema === 1 && value.images && typeof value.images === 'object' ? value.images : {}; } catch { return {}; }
1159
+ },
1160
+ /** Add the IDs of images this run built; never adopts a tag it did not produce. */
1161
+ async recordOwnedImages(record, built) {
1162
+ const path = join(record.root, OWNED_IMAGES_FILE);
1163
+ const next = ownedImagesRecord(existsSync(path) ? readFileSync(path, 'utf8') : null, built);
1164
+ if (next) atomicWriteConfig(path, next);
898
1165
  },
899
1166
  async validateServerBuildState(record) {
900
1167
  if (record.mode === 'docker') {
@@ -905,10 +1172,10 @@ export function networkEffects(effects) {
905
1172
  },
906
1173
  async discardServerBuild(candidate) {
907
1174
  if (candidate.mode === 'docker') {
908
- for (const target of ['runtime', 'maintenance', 'previous-runtime', 'previous-maintenance']) {
1175
+ for (const target of ['runtime', 'maintenance', 'previous-runtime', 'previous-maintenance', ...(candidate.gateway ? ['gateway', 'previous-gateway'] : [])]) {
909
1176
  const image = `${candidate.project}:${target}`;
910
- const found = await effects.run('docker', ['image', 'inspect', image], { allowCodes: [1] });
911
- if (found.code === 0) await effects.run('docker', ['image', 'rm', image]);
1177
+ const found = await container(candidate, ['image', 'inspect', image], { allowCodes: [1] });
1178
+ if (found.code === 0) await container(candidate, ['image', 'rm', image]);
912
1179
  }
913
1180
  }
914
1181
  privateDirectory(candidate.root);
@@ -916,7 +1183,15 @@ export function networkEffects(effects) {
916
1183
  },
917
1184
  async serverAccess(record, operation, { output, migrate = false } = {}) {
918
1185
  if (record.mode === 'docker') {
919
- if (!output) return compose(record, ['run', '--rm', '--no-deps', '-T', 'access', operation], { sensitive: true, env: { OURS_ACCESS_MIGRATE: migrate ? '1' : '0' } });
1186
+ // Retained images contain the old helper that discarded CLI errors.
1187
+ // Execute the shipped installer helper against the SAME selected image
1188
+ // and Compose volume/user/environment contract, without retag/rebuild.
1189
+ const diagnosticsUrl = `data:text/javascript;base64,${readFileSync(join(INSTALLER_ASSETS, 'scripts/runtime/diagnostics.mjs')).toString('base64')}`;
1190
+ const helper = `process.argv.splice(1, 0, '/opt/ours/docker/client-setup.mjs');\n` + readFileSync(join(INSTALLER_ASSETS, 'scripts/runtime/client-setup.mjs'), 'utf8')
1191
+ .replace("'../maintenance/build-context.mjs'", "'/opt/ours/maintenance/build-context.mjs'")
1192
+ .replace("'./diagnostics.mjs'", JSON.stringify(diagnosticsUrl));
1193
+ const accessArgs = (...args) => ['--entrypoint', 'node', 'access', '--input-type=module', '-e', helper, '--', ...args];
1194
+ if (!output) return compose(record, ['run', '--rm', '--no-deps', '-T', ...accessArgs(operation)], { sensitive: true, env: { OURS_ACCESS_MIGRATE: migrate ? '1' : '0' } });
920
1195
  privateDirectory(dirname(output));
921
1196
  if (existsSync(output)) throw new Error('Credential output already exists');
922
1197
  const name = `${record.project}-issue-${randomUUID()}`;
@@ -924,23 +1199,23 @@ export function networkEffects(effects) {
924
1199
  const staging = join(dirname(output), `.ours-issued-${randomUUID()}`);
925
1200
  ensurePrivateDirectory(staging);
926
1201
  try {
927
- await compose(record, ['run', '--name', name, '--no-deps', '-T', 'access', 'access-issue', issuedPath], { sensitive: true });
1202
+ await compose(record, ['run', '--name', name, '--no-deps', '-T', ...accessArgs('access-issue', issuedPath)], { sensitive: true });
928
1203
  const file = join(staging, 'credential');
929
- await effects.run('docker', ['cp', `${name}:${issuedPath}`, file], { sensitive: true });
1204
+ await container(record, ['cp', `${name}:${issuedPath}`, file], { sensitive: true });
930
1205
  assertPrivateRegularFile(file, 'issued credential');
931
1206
  // Exclusive publication never overwrites an unrelated credential.
932
1207
  writePrivateNew(output, readFileSync(file));
933
1208
  } finally {
934
1209
  await compose(record, ['run', '--rm', '--no-deps', '-T', '--entrypoint', 'rm', 'access', '-f', issuedPath], { sensitive: true });
935
- await effects.run('docker', ['rm', '-f', name], { sensitive: true });
1210
+ await container(record, ['rm', '-f', name], { sensitive: true });
936
1211
  rmSync(staging, { recursive: true, force: true });
937
1212
  }
938
1213
  return;
939
1214
  }
940
1215
  const options = { env: localEnv(record), sensitive: true };
941
- if (operation !== 'access-issue') return effects.run(bin(record, 'ours'), ['config', operation, '--config', record.configPath, ...(operation === 'access-replace' ? ['--confirm'] : migrate ? ['--migrate'] : []), '--json'], options);
1216
+ 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);
942
1217
  const outputs = output ? [output] : [join(installationPaths(record).daemon, 'daemon-token'), ...['telegram', 'cowork', 'messenger'].map(s => installationPaths(record).credentials[s])];
943
- for (const path of outputs) await effects.run(bin(record, 'ours'), ['config', operation, '--config', record.configPath, '--output', path, ...(output ? [] : ['--replace']), '--json'], options);
1218
+ 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);
944
1219
  },
945
1220
  async recordRuntimeBuild(record) {
946
1221
  if (record.mode === 'docker') return; // Image preparation records its build.
@@ -984,7 +1259,7 @@ export function networkEffects(effects) {
984
1259
  await effects.run(process.execPath, [join(INSTALLER_ASSETS, 'scripts/maintenance/state-operation.mjs'), ...command], {
985
1260
  env: { ...localEnv(record), OURS_STATE_DOMAIN: args.domain,
986
1261
  OURS_STATE_ROOT: join(record.root, 'storage'), OURS_LIVE_ROOT: ['server', 'daemon'].includes(args.domain) ? paths.state : paths[args.domain],
987
- OURS_BUILD_ROOT: record.workDir, OURS_CLI_PATH: bin(record, 'ours'),
1262
+ OURS_BUILD_ROOT: record.workDir, OURS_CLI_PATH: bin(record, existsSync(bin(record, 'ours-daemon')) ? 'ours-daemon' : 'ours'),
988
1263
  OURS_DAEMON_CONFIG: record.configPath, OURS_COWORK_CLI_PATH: bin(record, 'ours-cowork'),
989
1264
  OURS_COWORK_CONFIG: join(paths.cowork, 'config.json'), OURS_COWORK_STATE_DIR: paths.cowork },
990
1265
  });
@@ -1002,12 +1277,12 @@ export function networkEffects(effects) {
1002
1277
  if (typeof name !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(name)) {
1003
1278
  throw new Error('Invalid conversion volume name');
1004
1279
  }
1005
- const result = await effects.run('docker', ['volume', 'inspect', '--format', '{{json .}}', name], {
1280
+ const result = await container(record, ['volume', 'inspect', '--format', '{{json .}}', name], {
1006
1281
  ...(optional ? { allowCodes: [1] } : {}),
1007
1282
  });
1008
1283
  if (result.code !== 0) {
1009
1284
  if (optional) {
1010
- const inventory = await effects.run('docker', ['volume', 'ls', '--format', '{{.Name}}']);
1285
+ const inventory = await container(record, ['volume', 'ls', '--format', '{{.Name}}']);
1011
1286
  if (inventory.code === 0 && !inventory.stdout.split(/\s+/).includes(name)) return false;
1012
1287
  }
1013
1288
  throw new Error(`Source volume is missing or unavailable: ${name}`);
@@ -1069,7 +1344,7 @@ export function networkEffects(effects) {
1069
1344
  await ownerCommand(record, 'cowork', 'prepare-backup');
1070
1345
  },
1071
1346
  async retainConvertedPackageAuthority(record, daemon) {
1072
- await effects.run(bin(record, 'ours'), [
1347
+ await effects.run(bin(record, existsSync(bin(record, 'ours-daemon')) ? 'ours-daemon' : 'ours'), [
1073
1348
  'config', 'access-retain', '--config', record.configPath,
1074
1349
  '--target-state-dir', daemon, '--json',
1075
1350
  ], { env: localEnv(record), sensitive: true });
@@ -1113,6 +1388,28 @@ export function networkEffects(effects) {
1113
1388
  }
1114
1389
  await nativeLifecycle(record, 'retire', record.services, { effects, localEnv, ownerCommand, bin });
1115
1390
  },
1391
+ async serverUninstall(record) {
1392
+ if (record.schema !== 2 || record.layoutConversion || record.buildTransition) throw new Error('Complete retained installation transitions before uninstall');
1393
+ if (record.mode === 'docker') {
1394
+ await effects.serverLifecycle(record, 'stop');
1395
+ await requireCleanContainerExit(record, record.services);
1396
+ await compose(record, ['rm', '-f', ...record.services]);
1397
+ } else await nativeLifecycle(record, 'retire', record.services, { effects, localEnv, ownerCommand, bin });
1398
+ effects.out('Managed services removed; installation selection, stored identities, credentials and volumes retained.');
1399
+ },
1400
+ /**
1401
+ * Stop a managed installation's services before its complete removal.
1402
+ * Docker writers stop through Compose; containers are removed by project
1403
+ * label afterwards. Native services are retired through their owners, which
1404
+ * also removes their boot registrations.
1405
+ */
1406
+ async serverStopForRemoval(record) {
1407
+ if (record.mode === 'docker') {
1408
+ if (existsSync(record.workDir)) await effects.serverLifecycle(record, 'stop');
1409
+ return;
1410
+ }
1411
+ await nativeLifecycle(record, 'retire', record.services, { effects, localEnv, ownerCommand, bin });
1412
+ },
1116
1413
  async serverLifecycle(record, operation, selected = record.services) {
1117
1414
  record = buildRuntime(record);
1118
1415
  if (record.mode === 'docker') {
@@ -1124,14 +1421,22 @@ export function networkEffects(effects) {
1124
1421
  }
1125
1422
  if (operation === 'stop') {
1126
1423
  const consumers = selected.filter(s => s !== 'daemon').reverse();
1424
+ // Gateways created before stop_signal was set still stop with nginx's
1425
+ // SIGQUIT, which waits for open streams beyond the grace period and
1426
+ // ends in SIGKILL. SIGTERM is nginx's fast shutdown; it exits cleanly.
1427
+ if (consumers.includes('gateway')) await compose(record, ['kill', '-s', 'SIGTERM', 'gateway']);
1127
1428
  if (consumers.length) await compose(record, ['stop', ...consumers]);
1128
1429
  if (selected.includes('daemon')) await compose(record, ['stop', 'daemon']);
1129
1430
  if ((await effects.serverLifecycle(record, 'status', selected)).length) throw new Error('Writers did not stop');
1130
1431
  return;
1131
1432
  }
1433
+ if (existsSync(record.workDir)) atomicWriteConfig(join(record.workDir, 'compose.recovery.json'), JSON.stringify(recoveryCompose(record)));
1434
+ await reconcileDockerRecovery(record, effects);
1132
1435
  const start = async service => {
1133
1436
  effects.out(`Starting ${service}; waiting for readiness...`);
1134
- try { await compose(record, ['up', '-d', '--no-build', '--no-deps', '--wait', service]); }
1437
+ // Gateway has no persistent state. Recreate its network endpoint on each
1438
+ // managed start, including retries after an interrupted/failed bind.
1439
+ try { await compose(record, ['up', '-d', '--no-build', '--no-deps', ...(service === 'gateway' ? ['--force-recreate'] : []), '--wait', service]); }
1135
1440
  catch (cause) { throw await dockerStartupError(record, service, cause); }
1136
1441
  effects.out(`${service} is ready.`);
1137
1442
  };
@@ -1141,6 +1446,7 @@ export function networkEffects(effects) {
1141
1446
  try { await start(service); }
1142
1447
  catch (error) { failures.push({ service, error }); }
1143
1448
  }
1449
+ if (!failures.length && record.gateway && ['daemon', 'cowork', 'gateway'].every(service => selected.includes(service))) await effects.verifyGateway(record);
1144
1450
  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')}`);
1145
1451
  return;
1146
1452
  }
@@ -1155,21 +1461,19 @@ export function networkEffects(effects) {
1155
1461
  return JSON.parse(readFileSync(path, 'utf8'));
1156
1462
  },
1157
1463
  async discoverClientProfile(endpoint, credentialPath) {
1158
- const url = new URL(endpoint);
1159
- if ((url.protocol !== 'http:' && url.protocol !== 'https:') || url.username || url.password || url.pathname !== '/' || url.search || url.hash)
1160
- throw new Error('Client endpoint must be an HTTP or HTTPS origin');
1161
- const response = await fetch(`${url.origin}/selection`, { redirect: 'error', signal: AbortSignal.timeout(5000) });
1162
- if (!response.ok) throw new Error(`Daemon selection answered HTTP ${response.status}`);
1163
- const selection = await response.json();
1164
- // Full metadata and authenticated capability validation follows before publication.
1165
- return validateHostProfile({ endpoint: url.origin, expectedInstanceId: selection.instanceId, credentialPath: resolve(credentialPath) });
1464
+ const base = serverBase(endpoint);
1465
+ const request = path => fetch(`${base}${path}`, { redirect: 'error', signal: AbortSignal.timeout(5000) });
1466
+ const discovery = await request('/.well-known/ours');
1467
+ if (discovery.ok) return validateGatewayDiscovery(base, await discovery.json(), resolve(credentialPath));
1468
+ throw new Error(`Gateway discovery answered HTTP ${discovery.status}; enable the gateway. Direct daemon fallback is not supported.`);
1166
1469
  },
1167
- importClientProfile({ profile, sourcesPath, sources: resolvedSources, integrations, fleetSettingsPath, refresh = false }) {
1470
+ importClientProfile({ profile, sourcesPath, sources: resolvedSources, integrations, fleetSettingsPath, disableFleetAgentsSetup = false, refresh = false, notificationsProducerPath }) {
1471
+ profile = validateGatewayClientProfile(profile);
1168
1472
  const root = join(home, '.ours-client');
1169
1473
  const configPath = join(root, 'profile.json');
1170
1474
  const credentialPath = join(root, 'credential');
1171
1475
  const current = effects.readManagedClientProfile();
1172
- if (current && (current.endpoint !== profile.endpoint || current.expectedInstanceId !== profile.expectedInstanceId))
1476
+ if (current && current.expectedInstanceId !== profile.expectedInstanceId)
1173
1477
  throw new Error('Managed client already selects another server; existing default was not changed');
1174
1478
  assertPrivateRegularFile(profile.credentialPath, 'credential');
1175
1479
  const credential = readFileSync(profile.credentialPath, 'utf8');
@@ -1180,13 +1484,30 @@ export function networkEffects(effects) {
1180
1484
  : readFileSync(sourcesPath);
1181
1485
  const fleetSettings = (!current || refresh) && fleetSettingsPath ? readFileSync(fleetSettingsPath) : null;
1182
1486
  if (fleetSettings) JSON.parse(fleetSettings.toString());
1487
+ let producer = null;
1488
+ if (notificationsProducerPath) {
1489
+ assertPrivateRegularFile(notificationsProducerPath, 'notification producer credential');
1490
+ producer = readFileSync(notificationsProducerPath, 'utf8');
1491
+ let bound; try { bound = JSON.parse(producer); } catch { bound = null; }
1492
+ if (bound?.schema !== 1 || bound.serverUrl !== profile.serverUrl || bound.expectedInstanceId !== profile.expectedInstanceId || !/^[A-Za-z0-9_-]{32,256}$/.test(bound.token ?? ''))
1493
+ throw new Error('Notification producer credential does not match the selected server');
1494
+ }
1183
1495
  ensurePrivateDirectory(root);
1496
+ // Written before the profile it belongs to is published or changed.
1497
+ let notificationsProducerChanged = false;
1498
+ if (producer !== null) {
1499
+ const producerPath = join(root, 'notifications-producer.json');
1500
+ if (!existsSync(producerPath) || readFileSync(producerPath, 'utf8') !== producer) { atomicWriteConfig(producerPath, producer); notificationsProducerChanged = true; }
1501
+ }
1184
1502
  if (current && !refresh) {
1185
1503
  assertPrivateRegularFile(credentialPath, 'managed credential');
1186
1504
  if (readFileSync(credentialPath, 'utf8') !== credential) atomicWriteConfig(credentialPath, credential);
1187
- return { configPath, profile: validateHostProfile(current), settings: current.installer };
1505
+ const saved = { ...current, ...profile, credentialPath };
1506
+ if (current.endpoint !== saved.endpoint || current.serverUrl !== saved.serverUrl)
1507
+ atomicWriteConfig(configPath, JSON.stringify(saved, null, 2) + '\n');
1508
+ return { configPath, profile: validateGatewayClientProfile(saved), settings: current.installer, notificationsProducerChanged };
1188
1509
  }
1189
- const settings = { sourcesPath: join(root, 'sources.json'), integrations };
1510
+ const settings = { sourcesPath: join(root, 'sources.json'), integrations, ...(disableFleetAgentsSetup ? { disableFleetAgentsSetup: true } : {}) };
1190
1511
  if (fleetSettings) settings.fleetSettingsPath = join(root, 'fleet-settings.json');
1191
1512
  // Publish the profile last: clients cannot select incomplete imported inputs.
1192
1513
  atomicWriteConfig(settings.sourcesPath, sources);
@@ -1194,12 +1515,31 @@ export function networkEffects(effects) {
1194
1515
  atomicWriteConfig(credentialPath, credential);
1195
1516
  const saved = { ...profile, credentialPath, installer: settings };
1196
1517
  atomicWriteConfig(configPath, JSON.stringify(saved, null, 2) + '\n');
1197
- return { configPath, profile: validateHostProfile(saved), settings };
1518
+ return { configPath, profile: validateHostProfile(saved), settings, notificationsProducerChanged };
1519
+ },
1520
+ async qualifyInstalledGatewayClient(profile) {
1521
+ if (!profile.installer?.integrations?.includes('fleet')) return;
1522
+ let info;
1523
+ try { info = JSON.parse((await effects.run('ours-fleet', ['version', '--json'])).stdout); } catch {}
1524
+ if (!Array.isArray(info?.capabilities) || !info.capabilities.includes('cowork.http-management-v1'))
1525
+ throw new Error('Installed Fleet does not support gateway HTTP management; upgrade Fleet before gateway-enable');
1198
1526
  },
1199
- async acquireClientPackages(configPath, sourcesPath, integrations, { refresh = false, hostCliOnly = false } = {}) {
1527
+ async qualifyGatewayClient({ profile, sourcesPath, sources, integrations, refresh = false }) {
1528
+ if (!profile.serverUrl || !integrations.includes('fleet')) return;
1529
+ // Acquire into the retained package cache without publishing a profile,
1530
+ // credential, native command, or integration. Normal acquisition rechecks it.
1531
+ const staging = mkdtempSync(join(home, '.ours-gateway-client-'));
1532
+ try {
1533
+ const stagedSources = join(staging, 'sources.json');
1534
+ writeFileSync(stagedSources, sources ? JSON.stringify(sources, null, 2) + '\n' : readFileSync(sourcesPath), { mode: 0o600 });
1535
+ await effects.acquireClientPackages(join(home, '.ours-client/profile.json'), stagedSources, integrations,
1536
+ { refresh, gatewayServerUrl: profile.serverUrl, qualifyOnly: true });
1537
+ } finally { rmSync(staging, { recursive: true, force: true }); }
1538
+ },
1539
+ async acquireClientPackages(configPath, sourcesPath, integrations, { refresh = false, hostCliOnly = false, gatewayServerUrl, qualifyOnly = false } = {}) {
1200
1540
  const manifest = JSON.parse(readFileSync(sourcesPath, 'utf8'));
1201
1541
  // Every client installation includes the native CLI and its SDK dependency.
1202
- const selected = [...new Set(['sdk', 'cli', ...integrations])];
1542
+ const selected = clientPackageNames(integrations);
1203
1543
  const packages = selectSourcePackages(manifest, 'client', selected);
1204
1544
  const selectionKey = JSON.stringify([hostCliOnly ? 'host-cli-private-v1' : 'host-cli-v1', configPath, ...(hostCliOnly ? [manifest] : []), ...(refresh ? [manifest, integrations] : [])]);
1205
1545
  const root = join(home, '.ours-client-install', createHash('sha256').update(selectionKey).digest('hex').slice(0, 16));
@@ -1211,6 +1551,14 @@ export function networkEffects(effects) {
1211
1551
  // This directory retains active executables, not disposable download cache.
1212
1552
  ensurePrivateDirectory(join(home, '.ours-client-install'));
1213
1553
  ensurePrivateDirectory(root);
1554
+ // Record which installation this acquisition serves, for complete removal.
1555
+ let owner = null;
1556
+ try { owner = readHostProfileFile(configPath)?.expectedInstanceId ?? null; } catch { /* not yet imported */ }
1557
+ const ownersPath = join(root, OWNERS_FILE);
1558
+ try {
1559
+ const ownerRecord = owner ? addOwner(existsSync(ownersPath) ? readFileSync(ownersPath, 'utf8') : null, owner) : null;
1560
+ if (ownerRecord) atomicWriteConfig(ownersPath, ownerRecord);
1561
+ } catch (error) { effects.out?.(`! ${error.message}; complete removal will leave ${root} in place and say so.`); }
1214
1562
  const retained = join(root, 'sources.json');
1215
1563
  const bytes = readFileSync(sourcesPath);
1216
1564
  if (!existsSync(retained)) writePrivateNew(retained, bytes);
@@ -1234,6 +1582,13 @@ export function networkEffects(effects) {
1234
1582
  writePrivateNew(join(root, '.packages-ready'), 'ready\n');
1235
1583
  }
1236
1584
  verifyReleaseGraph(root, manifest, { requiredPackages: Object.keys(packages) });
1585
+ if (integrations.includes('fleet') && (gatewayServerUrl || readHostProfileFile(configPath)?.serverUrl)) {
1586
+ let info;
1587
+ try { info = JSON.parse(readFileSync(join(root, 'node_modules/@ours.network/fleet/dist/build-info.json'), 'utf8')); } catch {}
1588
+ if (!Array.isArray(info?.capabilities) || !info.capabilities.includes('cowork.http-management-v1'))
1589
+ throw new Error('Selected Fleet artifact does not support gateway HTTP management; select a compatible client release');
1590
+ }
1591
+ if (qualifyOnly) return;
1237
1592
  const cliPolicy = hostCliOnly ? null : hostCliPolicy(manifest);
1238
1593
  // Local acquisition alone does not publish native commands. Use the user's
1239
1594
  // configured npm prefix and retained dependency closure, including on retry.
@@ -1255,6 +1610,13 @@ export function networkEffects(effects) {
1255
1610
  const localPackages = Object.fromEntries(integrations.filter(n => n !== 'fleet').map(name => [name, join(root, 'node_modules', '@ours.network', name)]));
1256
1611
  return { localPackages, packages: {}, cliBin, fleetBin: integrations.includes('fleet') ? join(root, 'node_modules/.bin/ours-fleet') : null };
1257
1612
  },
1613
+ /** Capability tokens the given Fleet executable reports for itself; [] when it reports none. */
1614
+ async fleetCapabilities(fleetBin, env = null) {
1615
+ try {
1616
+ const capabilities = JSON.parse((await effects.run(fleetBin, ['version', '--json'], { env })).stdout).capabilities;
1617
+ return Array.isArray(capabilities) ? capabilities.filter(item => typeof item === 'string') : [];
1618
+ } catch { return []; }
1619
+ },
1258
1620
  async prepareClientMarketplace(name, packagePath) {
1259
1621
  const acquisitionRoot = dirname(dirname(dirname(packagePath)));
1260
1622
  const sourcePath = join(acquisitionRoot, 'sources.json');
@@ -1262,7 +1624,7 @@ export function networkEffects(effects) {
1262
1624
  const release = releaseBinding(policy);
1263
1625
  const integrationsPath = join(acquisitionRoot, 'integrations.json');
1264
1626
  const integrations = existsSync(integrationsPath) ? JSON.parse(readFileSync(integrationsPath, 'utf8')) : null;
1265
- const requiredPackages = integrations ? [...new Set(['sdk', 'cli', ...integrations])].map(name => '@ours.network/' + name) : Object.keys(policy.packages ?? {});
1627
+ const requiredPackages = integrations ? clientPackageNames(integrations).map(name => '@ours.network/' + name) : Object.keys(policy.packages ?? {});
1266
1628
  verifyReleaseGraph(acquisitionRoot, policy, { requiredPackages });
1267
1629
  const root = join(acquisitionRoot, 'marketplaces', name);
1268
1630
  const plugin = join(root, 'plugins', 'ours');
@@ -1271,7 +1633,7 @@ export function networkEffects(effects) {
1271
1633
  cpSync(packagePath, plugin, { recursive: true });
1272
1634
  const manifestPath = join(plugin, 'package.json');
1273
1635
  const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
1274
- for (const dependency of release ? [] : ['sdk', 'cli']) {
1636
+ for (const dependency of release ? [] : ['sdk', 'cli', 'mcp']) {
1275
1637
  const name = `@ours.network/${dependency}`;
1276
1638
  if (manifest.dependencies?.[name]) manifest.dependencies[name] = `file:${join(dirname(packagePath), dependency)}`;
1277
1639
  }
@@ -1291,42 +1653,7 @@ export function networkEffects(effects) {
1291
1653
  effects.writeJson(manifestPath, JSON.stringify(value, null, 2) + '\n');
1292
1654
  return root;
1293
1655
  },
1294
- async verifyPackagedMcp(configPath) {
1295
- const profile = typeof configPath === 'string' ? readHostProfileFile(configPath) : validateHostProfile(configPath);
1296
- assertPrivateRegularFile(profile.credentialPath, 'credential');
1297
- const token = readFileSync(profile.credentialPath, 'utf8').trim();
1298
- 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() };
1299
- const request = async (method, params, id) => {
1300
- 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 }) });
1301
- const session = response.headers.get('mcp-session-id');
1302
- if (session) headers['mcp-session-id'] = session;
1303
- if (!response.ok) throw new Error(`Packaged MCP verification failed: HTTP ${response.status}`);
1304
- if (id === undefined) { await response.body?.cancel(); return; }
1305
- const text = await response.text();
1306
- const messages = response.headers.get('content-type')?.includes('text/event-stream')
1307
- ? text.split('\n').filter(line => line.startsWith('data:')).map(line => JSON.parse(line.slice(5)))
1308
- : [JSON.parse(text)];
1309
- const message = messages.find(value => value.id === id);
1310
- if (!message || message.error || !message.result) throw new Error('Packaged MCP returned no successful protocol result');
1311
- return message.result;
1312
- };
1313
- try {
1314
- const initialized = await request('initialize', { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'ours-install', version: '1' } }, 1);
1315
- if (initialized.serverInfo?.name !== 'ours' || !initialized.protocolVersion) throw new Error('Selected MCP is not the packaged OURS server');
1316
- headers['mcp-protocol-version'] = initialized.protocolVersion;
1317
- await request('notifications/initialized', {}, undefined);
1318
- const resources = await request('resources/list', {}, 2);
1319
- if (!resources.resources?.some(resource => resource.uri === 'ours://application-identities')) throw new Error('Packaged network MCP identity resource is absent');
1320
- const toolList = await request('tools/list', {}, 3);
1321
- if (!toolList.tools?.some(tool => tool.name === 'list_identities')) throw new Error('Packaged OURS identity tools are absent');
1322
- } finally {
1323
- if (headers['mcp-session-id']) {
1324
- const response = await fetch(`${profile.endpoint}/mcp`, { method: 'DELETE', redirect: 'error', signal: AbortSignal.timeout(5000), headers });
1325
- await response.body?.cancel();
1326
- if (!response.ok) throw new Error('MCP verification session could not be closed');
1327
- }
1328
- }
1329
- },
1656
+
1330
1657
  };
1331
1658
  }
1332
1659
 
@@ -1373,7 +1700,6 @@ async function nativeLifecycle(record, operation, selected, { effects, localEnv,
1373
1700
  if (service === 'daemon') {
1374
1701
  const profilePath = join(installationPaths(record).mcp, 'profile.json');
1375
1702
  await effects.verifyHostProfile(profilePath);
1376
- await effects.verifyPackagedMcp(profilePath);
1377
1703
  return;
1378
1704
  }
1379
1705
  if (service === 'cowork') { await ownerCommand(record, service, 'status'); return; }
@@ -1451,7 +1777,7 @@ async function nativeLifecycle(record, operation, selected, { effects, localEnv,
1451
1777
  }
1452
1778
  if (!ready) throw new Error('Application is not ready');
1453
1779
  } catch {
1454
- if (service === 'daemon') throw new Error('Daemon and packaged MCP are not ready; consumers were not started');
1780
+ if (service === 'daemon') throw new Error('Daemon API is not ready; consumers were not started');
1455
1781
  failures.push(service);
1456
1782
  }
1457
1783
  }