@ours.network/install 1.2.1-nightly.6 → 1.2.1-nightly.61

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 (65) hide show
  1. package/GATEWAY_SETUP.md +178 -0
  2. package/README.md +573 -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 +1221 -4516
  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/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 +54 -28
  34. package/install.mjs +7 -2
  35. package/lib/boot-readiness.mjs +96 -0
  36. package/lib/build-transition.mjs +16 -0
  37. package/lib/client-cli.mjs +127 -0
  38. package/lib/container-engine.mjs +127 -0
  39. package/lib/diagnostics.mjs +1 -0
  40. package/lib/docker-conversion-runtime.mjs +7 -4
  41. package/lib/docker-layout-installation.mjs +2 -1
  42. package/lib/docker-recovery.mjs +60 -0
  43. package/lib/docker-runtime-repair.mjs +49 -14
  44. package/lib/effects.mjs +482 -140
  45. package/lib/gateway-transition.mjs +87 -0
  46. package/lib/gateway.mjs +227 -0
  47. package/lib/legacy-migration.mjs +13 -2
  48. package/lib/orchestrate-uninstall.mjs +23 -6
  49. package/lib/orchestrate.mjs +335 -44
  50. package/lib/ownership.mjs +63 -0
  51. package/lib/plan.mjs +37 -11
  52. package/lib/podman-preflight.mjs +40 -0
  53. package/lib/product.mjs +69 -0
  54. package/lib/removal-plan.mjs +437 -0
  55. package/lib/removal.mjs +749 -0
  56. package/lib/server-onboarding.mjs +182 -16
  57. package/lib/server-ports.mjs +17 -0
  58. package/lib/setup-options.mjs +119 -29
  59. package/lib/setup.mjs +93 -22
  60. package/lib/target.mjs +24 -8
  61. package/lib/uninstall.mjs +2 -2
  62. package/lib/usage.mjs +35 -9
  63. package/lib/welcome.mjs +219 -0
  64. package/lib/workspace-setup.mjs +154 -0
  65. 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, gatewayReadinessScript, describeGatewayReadiness } 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,39 @@ 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 = 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
+ },
710
879
  async prepareInstallation(record, { runtimeOnly = false } = {}) {
880
+ if (!runtimeOnly) await reportBootReadiness(effects, record);
711
881
  let copied = false;
712
882
  if (!existsSync(record.workDir)) {
713
883
  cpSync(INSTALLER_ASSETS, record.workDir, { recursive: true, errorOnExist: true, force: false });
@@ -720,15 +890,35 @@ export function networkEffects(effects) {
720
890
  if (!existsSync(materialized)) writePrivateNew(materialized, retained);
721
891
  else if (!readFileSync(materialized).equals(retained)) throw new Error('Materialized sources differ from retained selection');
722
892
  if (record.mode === 'docker') {
723
- 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
+ }
724
905
  // The installer owns these dependencies in both installation modes.
725
906
  const { dependencies } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
726
907
  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' } });
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' } });
729
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
+ }
730
917
  if (runtimeOnly) return;
731
- 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));
732
922
  } else {
733
923
  if (!existsSync(join(record.workDir, '.packages-ready'))) {
734
924
  const sourceRoot = join(record.root, `build-${randomUUID()}`);
@@ -749,12 +939,15 @@ export function networkEffects(effects) {
749
939
  const profilePath = join(installationPaths(record).mcp, 'profile.json');
750
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') }));
751
941
  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
942
  effects.writeJson(record.configPath, JSON.stringify(config, null, 2) + '\n');
754
943
  const cowork = join(installationPaths(record).cowork, 'config.json');
755
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 } }));
756
945
  }
757
946
  },
947
+ async prepareServerVolumes(record) {
948
+ if (record.mode !== 'docker') return;
949
+ await compose(record, ['run', '--rm', '--no-deps', '-T', 'prepare', 'prepare']);
950
+ },
758
951
  async prepareServerBuild(record, args) {
759
952
  validateInstallation(record, record.root);
760
953
  if (record.schema !== 2 || record.layoutConversion || !['update', 'rebuild'].includes(args.operation)) {
@@ -765,7 +958,7 @@ export function networkEffects(effects) {
765
958
  ? Buffer.from(`${JSON.stringify(args.resolvedSources, null, 2)}\n`)
766
959
  : readFileSync(args.sources))
767
960
  : readFileSync(record.sourcesPath);
768
- selectSourcePackages(JSON.parse(sources), 'server');
961
+ selectSourcePackages(JSON.parse(sources), serverRole(record));
769
962
  privateDirectory(record.root);
770
963
  const root = mkdtempSync(join(record.root, '.build-'));
771
964
  const candidate = { ...record, root, workDir: join(root, 'runtime'), sourcesPath: join(root, 'sources.json'),
@@ -777,6 +970,9 @@ export function networkEffects(effects) {
777
970
  await effects.prepareInstallation(candidate, { runtimeOnly: true });
778
971
  if (candidate.mode === 'docker') {
779
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));
780
976
  await effects.copyDockerBuildRecords(candidate, candidate.workDir);
781
977
  }
782
978
  // npm emits readable build records; maintenance consumes private copies.
@@ -797,17 +993,26 @@ export function networkEffects(effects) {
797
993
  },
798
994
  async copyDockerBuildRecords(record, directory) {
799
995
  // 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();
996
+ const label = (await container(record, ['image', 'inspect', '--format', '{{ index .Config.Labels "network.ours.build-context" }}', `${record.project}:runtime`])).stdout.trim();
801
997
  if (!['', '<no value>', '1'].includes(label)) throw new Error('Unsupported image build-context schema');
802
998
  const names = [...BASE_RECORDS, ...(label === '1' ? [CONTEXT] : [])];
803
999
  const stage = mkdtempSync(join(directory, '.records-'));
804
1000
  const name = `${record.project}-records`;
805
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
+ }
806
1011
  try {
807
- 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`]);
808
1013
  created = true;
809
1014
  for (const file of names) {
810
- await effects.run('docker', ['cp', `${name}:/opt/ours/${file}`, join(stage, file)]);
1015
+ await container(record, ['cp', `${name}:/opt/ours/${file}`, join(stage, file)]);
811
1016
  const st = lstatSync(join(stage, file));
812
1017
  if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o7002)) throw new Error('Unsafe copied build record');
813
1018
  chmodSync(join(stage, file), 0o600);
@@ -817,7 +1022,7 @@ export function networkEffects(effects) {
817
1022
  for (const file of names) renameSync(join(stage, file), join(directory, file));
818
1023
  if (label !== '1' && existsSync(join(directory, CONTEXT))) throw new Error('Legacy image conflicts with retained build context');
819
1024
  } finally {
820
- try { if (created) await effects.run('docker', ['rm', name]); }
1025
+ try { if (created) await container(record, ['rm', name]); }
821
1026
  finally { rmSync(stage, { recursive: true, force: true }); }
822
1027
  }
823
1028
  },
@@ -865,17 +1070,59 @@ export function networkEffects(effects) {
865
1070
  });
866
1071
  }
867
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
+ },
868
1105
  async publishServerBuild(record, candidate) {
869
1106
  const previous = join(candidate.root, 'previous-runtime');
1107
+ const built = {};
870
1108
  if (record.mode === 'docker') {
871
- 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'] : [])]) {
872
1112
  const retained = `${candidate.project}:previous-${target}`;
873
- const found = await effects.run('docker', ['image', 'inspect', retained], { allowCodes: [1] });
1113
+ const found = await container(record, ['image', 'inspect', retained], { allowCodes: [1] });
874
1114
  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]);
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]);
877
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];
878
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])));
879
1126
  }
880
1127
  if (!existsSync(previous)) {
881
1128
  privateDirectory(record.workDir);
@@ -889,11 +1136,32 @@ export function networkEffects(effects) {
889
1136
  renameSync(candidate.workDir, record.workDir);
890
1137
  } else privateDirectory(record.workDir);
891
1138
  if (record.mode === 'docker') {
892
- for (const target of ['runtime', 'maintenance']) {
893
- 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}`]);
894
1141
  }
895
1142
  }
896
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);
897
1165
  },
898
1166
  async validateServerBuildState(record) {
899
1167
  if (record.mode === 'docker') {
@@ -904,10 +1172,10 @@ export function networkEffects(effects) {
904
1172
  },
905
1173
  async discardServerBuild(candidate) {
906
1174
  if (candidate.mode === 'docker') {
907
- 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'] : [])]) {
908
1176
  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]);
1177
+ const found = await container(candidate, ['image', 'inspect', image], { allowCodes: [1] });
1178
+ if (found.code === 0) await container(candidate, ['image', 'rm', image]);
911
1179
  }
912
1180
  }
913
1181
  privateDirectory(candidate.root);
@@ -915,7 +1183,15 @@ export function networkEffects(effects) {
915
1183
  },
916
1184
  async serverAccess(record, operation, { output, migrate = false } = {}) {
917
1185
  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' } });
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' } });
919
1195
  privateDirectory(dirname(output));
920
1196
  if (existsSync(output)) throw new Error('Credential output already exists');
921
1197
  const name = `${record.project}-issue-${randomUUID()}`;
@@ -923,23 +1199,23 @@ export function networkEffects(effects) {
923
1199
  const staging = join(dirname(output), `.ours-issued-${randomUUID()}`);
924
1200
  ensurePrivateDirectory(staging);
925
1201
  try {
926
- 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 });
927
1203
  const file = join(staging, 'credential');
928
- await effects.run('docker', ['cp', `${name}:${issuedPath}`, file], { sensitive: true });
1204
+ await container(record, ['cp', `${name}:${issuedPath}`, file], { sensitive: true });
929
1205
  assertPrivateRegularFile(file, 'issued credential');
930
1206
  // Exclusive publication never overwrites an unrelated credential.
931
1207
  writePrivateNew(output, readFileSync(file));
932
1208
  } finally {
933
1209
  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 });
1210
+ await container(record, ['rm', '-f', name], { sensitive: true });
935
1211
  rmSync(staging, { recursive: true, force: true });
936
1212
  }
937
1213
  return;
938
1214
  }
939
1215
  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);
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);
941
1217
  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);
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);
943
1219
  },
944
1220
  async recordRuntimeBuild(record) {
945
1221
  if (record.mode === 'docker') return; // Image preparation records its build.
@@ -983,7 +1259,7 @@ export function networkEffects(effects) {
983
1259
  await effects.run(process.execPath, [join(INSTALLER_ASSETS, 'scripts/maintenance/state-operation.mjs'), ...command], {
984
1260
  env: { ...localEnv(record), OURS_STATE_DOMAIN: args.domain,
985
1261
  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'),
1262
+ OURS_BUILD_ROOT: record.workDir, OURS_CLI_PATH: bin(record, existsSync(bin(record, 'ours-daemon')) ? 'ours-daemon' : 'ours'),
987
1263
  OURS_DAEMON_CONFIG: record.configPath, OURS_COWORK_CLI_PATH: bin(record, 'ours-cowork'),
988
1264
  OURS_COWORK_CONFIG: join(paths.cowork, 'config.json'), OURS_COWORK_STATE_DIR: paths.cowork },
989
1265
  });
@@ -1001,12 +1277,12 @@ export function networkEffects(effects) {
1001
1277
  if (typeof name !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(name)) {
1002
1278
  throw new Error('Invalid conversion volume name');
1003
1279
  }
1004
- const result = await effects.run('docker', ['volume', 'inspect', '--format', '{{json .}}', name], {
1280
+ const result = await container(record, ['volume', 'inspect', '--format', '{{json .}}', name], {
1005
1281
  ...(optional ? { allowCodes: [1] } : {}),
1006
1282
  });
1007
1283
  if (result.code !== 0) {
1008
1284
  if (optional) {
1009
- const inventory = await effects.run('docker', ['volume', 'ls', '--format', '{{.Name}}']);
1285
+ const inventory = await container(record, ['volume', 'ls', '--format', '{{.Name}}']);
1010
1286
  if (inventory.code === 0 && !inventory.stdout.split(/\s+/).includes(name)) return false;
1011
1287
  }
1012
1288
  throw new Error(`Source volume is missing or unavailable: ${name}`);
@@ -1068,7 +1344,7 @@ export function networkEffects(effects) {
1068
1344
  await ownerCommand(record, 'cowork', 'prepare-backup');
1069
1345
  },
1070
1346
  async retainConvertedPackageAuthority(record, daemon) {
1071
- await effects.run(bin(record, 'ours'), [
1347
+ await effects.run(bin(record, existsSync(bin(record, 'ours-daemon')) ? 'ours-daemon' : 'ours'), [
1072
1348
  'config', 'access-retain', '--config', record.configPath,
1073
1349
  '--target-state-dir', daemon, '--json',
1074
1350
  ], { env: localEnv(record), sensitive: true });
@@ -1112,6 +1388,28 @@ export function networkEffects(effects) {
1112
1388
  }
1113
1389
  await nativeLifecycle(record, 'retire', record.services, { effects, localEnv, ownerCommand, bin });
1114
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
+ },
1115
1413
  async serverLifecycle(record, operation, selected = record.services) {
1116
1414
  record = buildRuntime(record);
1117
1415
  if (record.mode === 'docker') {
@@ -1123,14 +1421,22 @@ export function networkEffects(effects) {
1123
1421
  }
1124
1422
  if (operation === 'stop') {
1125
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']);
1126
1428
  if (consumers.length) await compose(record, ['stop', ...consumers]);
1127
1429
  if (selected.includes('daemon')) await compose(record, ['stop', 'daemon']);
1128
1430
  if ((await effects.serverLifecycle(record, 'status', selected)).length) throw new Error('Writers did not stop');
1129
1431
  return;
1130
1432
  }
1433
+ if (existsSync(record.workDir)) atomicWriteConfig(join(record.workDir, 'compose.recovery.json'), JSON.stringify(recoveryCompose(record)));
1434
+ await reconcileDockerRecovery(record, effects);
1131
1435
  const start = async service => {
1132
1436
  effects.out(`Starting ${service}; waiting for readiness...`);
1133
- 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]); }
1134
1440
  catch (cause) { throw await dockerStartupError(record, service, cause); }
1135
1441
  effects.out(`${service} is ready.`);
1136
1442
  };
@@ -1140,6 +1446,7 @@ export function networkEffects(effects) {
1140
1446
  try { await start(service); }
1141
1447
  catch (error) { failures.push({ service, error }); }
1142
1448
  }
1449
+ if (!failures.length && record.gateway && ['daemon', 'cowork', 'gateway'].every(service => selected.includes(service))) await effects.verifyGateway(record);
1143
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')}`);
1144
1451
  return;
1145
1452
  }
@@ -1154,21 +1461,19 @@ export function networkEffects(effects) {
1154
1461
  return JSON.parse(readFileSync(path, 'utf8'));
1155
1462
  },
1156
1463
  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) });
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.`);
1165
1469
  },
1166
- 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);
1167
1472
  const root = join(home, '.ours-client');
1168
1473
  const configPath = join(root, 'profile.json');
1169
1474
  const credentialPath = join(root, 'credential');
1170
1475
  const current = effects.readManagedClientProfile();
1171
- if (current && (current.endpoint !== profile.endpoint || current.expectedInstanceId !== profile.expectedInstanceId))
1476
+ if (current && current.expectedInstanceId !== profile.expectedInstanceId)
1172
1477
  throw new Error('Managed client already selects another server; existing default was not changed');
1173
1478
  assertPrivateRegularFile(profile.credentialPath, 'credential');
1174
1479
  const credential = readFileSync(profile.credentialPath, 'utf8');
@@ -1179,13 +1484,30 @@ export function networkEffects(effects) {
1179
1484
  : readFileSync(sourcesPath);
1180
1485
  const fleetSettings = (!current || refresh) && fleetSettingsPath ? readFileSync(fleetSettingsPath) : null;
1181
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
+ }
1182
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
+ }
1183
1502
  if (current && !refresh) {
1184
1503
  assertPrivateRegularFile(credentialPath, 'managed credential');
1185
1504
  if (readFileSync(credentialPath, 'utf8') !== credential) atomicWriteConfig(credentialPath, credential);
1186
- 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 };
1187
1509
  }
1188
- const settings = { sourcesPath: join(root, 'sources.json'), integrations };
1510
+ const settings = { sourcesPath: join(root, 'sources.json'), integrations, ...(disableFleetAgentsSetup ? { disableFleetAgentsSetup: true } : {}) };
1189
1511
  if (fleetSettings) settings.fleetSettingsPath = join(root, 'fleet-settings.json');
1190
1512
  // Publish the profile last: clients cannot select incomplete imported inputs.
1191
1513
  atomicWriteConfig(settings.sourcesPath, sources);
@@ -1193,21 +1515,50 @@ export function networkEffects(effects) {
1193
1515
  atomicWriteConfig(credentialPath, credential);
1194
1516
  const saved = { ...profile, credentialPath, installer: settings };
1195
1517
  atomicWriteConfig(configPath, JSON.stringify(saved, null, 2) + '\n');
1196
- 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');
1526
+ },
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 }); }
1197
1538
  },
1198
- async acquireClientPackages(configPath, sourcesPath, integrations, { refresh = false } = {}) {
1539
+ async acquireClientPackages(configPath, sourcesPath, integrations, { refresh = false, hostCliOnly = false, gatewayServerUrl, qualifyOnly = false } = {}) {
1199
1540
  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])];
1541
+ // Every client installation includes the native CLI and its SDK dependency.
1542
+ const selected = clientPackageNames(integrations);
1202
1543
  const packages = selectSourcePackages(manifest, 'client', selected);
1203
- const selectionKey = refresh ? JSON.stringify([configPath, manifest, integrations]) : configPath;
1544
+ const selectionKey = JSON.stringify([hostCliOnly ? 'host-cli-private-v1' : 'host-cli-v1', configPath, ...(hostCliOnly ? [manifest] : []), ...(refresh ? [manifest, integrations] : [])]);
1204
1545
  const root = join(home, '.ours-client-install', createHash('sha256').update(selectionKey).digest('hex').slice(0, 16));
1205
1546
  const hasGit = Object.values(packages).some(selection => selection.source);
1206
1547
  await effects.run('npm', ['--version']);
1207
1548
  if (hasGit) {
1208
1549
  for (const command of ['python3', 'git', 'make', 'cc']) await effects.run(command, ['--version']);
1209
1550
  }
1551
+ // This directory retains active executables, not disposable download cache.
1552
+ ensurePrivateDirectory(join(home, '.ours-client-install'));
1210
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.`); }
1211
1562
  const retained = join(root, 'sources.json');
1212
1563
  const bytes = readFileSync(sourcesPath);
1213
1564
  if (!existsSync(retained)) writePrivateNew(retained, bytes);
@@ -1231,13 +1582,40 @@ export function networkEffects(effects) {
1231
1582
  writePrivateNew(join(root, '.packages-ready'), 'ready\n');
1232
1583
  }
1233
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;
1592
+ const cliPolicy = hostCliOnly ? null : hostCliPolicy(manifest);
1234
1593
  // Local acquisition alone does not publish native commands. Use the user's
1235
1594
  // configured npm prefix and retained dependency closure, including on retry.
1236
1595
  for (const name of integrations.filter(name => name === 'fleet' || name === 'codex')) {
1237
1596
  await effects.run('npm', ['install', '--global', '--install-links=false', '--offline', '--ignore-scripts', '--no-audit', '--no-fund', join(root, 'node_modules', '@ours.network', name)]);
1238
1597
  }
1598
+ let cliBin = join(root, 'node_modules/.bin/ours');
1599
+ if (cliPolicy) {
1600
+ const cliSources = join(root, 'host-cli-sources.json');
1601
+ const cliBytes = JSON.stringify(cliPolicy, null, 2) + '\n';
1602
+ if (!existsSync(cliSources)) writePrivateNew(cliSources, cliBytes);
1603
+ else if (readFileSync(cliSources, 'utf8') !== cliBytes) throw new Error('Retained host CLI source selection differs');
1604
+ const acquired = await effects.acquireClientPackages(configPath, cliSources, [], { refresh, hostCliOnly: true });
1605
+ cliBin = acquired.cliBin;
1606
+ } else {
1607
+ // Publish last so optional integration installation cannot downgrade ours.
1608
+ await publishClientCli(effects, join(root, 'node_modules', '@ours.network/cli'), { policy: manifest, isolated: hostCliOnly });
1609
+ }
1239
1610
  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 };
1611
+ return { localPackages, packages: {}, cliBin, fleetBin: integrations.includes('fleet') ? join(root, 'node_modules/.bin/ours-fleet') : null };
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 []; }
1241
1619
  },
1242
1620
  async prepareClientMarketplace(name, packagePath) {
1243
1621
  const acquisitionRoot = dirname(dirname(dirname(packagePath)));
@@ -1246,7 +1624,7 @@ export function networkEffects(effects) {
1246
1624
  const release = releaseBinding(policy);
1247
1625
  const integrationsPath = join(acquisitionRoot, 'integrations.json');
1248
1626
  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 ?? {});
1627
+ const requiredPackages = integrations ? clientPackageNames(integrations).map(name => '@ours.network/' + name) : Object.keys(policy.packages ?? {});
1250
1628
  verifyReleaseGraph(acquisitionRoot, policy, { requiredPackages });
1251
1629
  const root = join(acquisitionRoot, 'marketplaces', name);
1252
1630
  const plugin = join(root, 'plugins', 'ours');
@@ -1255,7 +1633,7 @@ export function networkEffects(effects) {
1255
1633
  cpSync(packagePath, plugin, { recursive: true });
1256
1634
  const manifestPath = join(plugin, 'package.json');
1257
1635
  const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
1258
- for (const dependency of release ? [] : ['sdk', 'cli']) {
1636
+ for (const dependency of release ? [] : ['sdk', 'cli', 'mcp']) {
1259
1637
  const name = `@ours.network/${dependency}`;
1260
1638
  if (manifest.dependencies?.[name]) manifest.dependencies[name] = `file:${join(dirname(packagePath), dependency)}`;
1261
1639
  }
@@ -1275,42 +1653,7 @@ export function networkEffects(effects) {
1275
1653
  effects.writeJson(manifestPath, JSON.stringify(value, null, 2) + '\n');
1276
1654
  return root;
1277
1655
  },
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
- },
1656
+
1314
1657
  };
1315
1658
  }
1316
1659
 
@@ -1357,7 +1700,6 @@ async function nativeLifecycle(record, operation, selected, { effects, localEnv,
1357
1700
  if (service === 'daemon') {
1358
1701
  const profilePath = join(installationPaths(record).mcp, 'profile.json');
1359
1702
  await effects.verifyHostProfile(profilePath);
1360
- await effects.verifyPackagedMcp(profilePath);
1361
1703
  return;
1362
1704
  }
1363
1705
  if (service === 'cowork') { await ownerCommand(record, service, 'status'); return; }
@@ -1435,7 +1777,7 @@ async function nativeLifecycle(record, operation, selected, { effects, localEnv,
1435
1777
  }
1436
1778
  if (!ready) throw new Error('Application is not ready');
1437
1779
  } catch {
1438
- 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');
1439
1781
  failures.push(service);
1440
1782
  }
1441
1783
  }