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