@rivus/gateway 0.20.0 → 0.21.0
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/README.md +9 -0
- package/assets/installation-policy.json +13 -0
- package/dist/bootstrap/feishu.d.ts +1 -1
- package/dist/bootstrap/feishu.js +2 -2
- package/dist/chunks/rivus-deployment-cli-process.d.ts +1 -1
- package/dist/chunks/rivus-home-deployment-env.js +187 -4
- package/dist/chunks/rivus-node-entrypoint.js +1598 -23
- package/dist/index.d.ts +35 -1
- package/package.json +7 -4
|
@@ -1,17 +1,23 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
import { createRequire } from "node:module";
|
|
1
|
+
import { A as clearRuntimeReceipt, B as validateRivusDeploymentManifest, C as gatewayTemplateDirectory, D as parseRivusModelManagementEnabled, F as upgradePaths, H as createBackgroundSessionToolContracts, I as writeUpgradeRecord, L as resolveFeishuEndpointCredentials, M as writeRuntimeReceipt, N as acquireUpgradeLock, P as readUpgradeRecord, R as InvalidRivusProjectSpace, T as resolveAcpRuntimeEnvironment, U as narrowBackgroundSessionDefinition, V as validateRivusProjectSpaceDeployment, W as deepFreeze, _ as readRivusAudioInstalledRelease, a as invokeRuntimeControl, b as gatewayPackageDirectory, d as renderRivusModelCliArgumentError, f as renderRivusModelCliHelp, g as installRivusAudioTranscriber, i as disposeRuntimeCacheEntries, j as readRuntimeReceipt, k as loadMergedLocalEnvFile, l as createRivusModelManagementWireRequest, m as runRivusAudioProcess, n as withoutRivusHomeDeployment, o as RIVUS_RELEASE_DESCRIPTOR, p as runRivusAudioPassthroughProcess, r as createRuntimeCache, t as RIVUS_HOME_DEPLOYMENT_ENV, u as parseRivusModelCliArguments, v as readRivusAudioStatus, w as loadRivusDeploymentManifest, x as gatewayPackageManifestPath, y as gatewayAudioTranscriberAssetDirectory, z as parseRivusDeploymentManifest } from "./rivus-home-deployment-env.js";
|
|
2
|
+
import { createRequire, findPackageJSON } from "node:module";
|
|
3
3
|
import { createSha256Digest, createStableId } from "@rivus/platform/identity";
|
|
4
4
|
import { Cause, Deferred, Effect, Exit, Result, Schema, Semaphore } from "effect";
|
|
5
5
|
import { RIVUS_MEMORY_TOOL_PLUGIN_ID, RIVUS_RUNTIME_TOOL_IDS, createRivusMemoryToolContract, isRivusRuntimeToolId } from "@rivus/runtime";
|
|
6
6
|
import { homedir } from "node:os";
|
|
7
|
-
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
7
|
+
import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
8
8
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
9
|
-
import { lstat, mkdir, open, readFile, readdir, realpath, rmdir, stat, unlink, writeFile } from "node:fs/promises";
|
|
9
|
+
import { access, chmod, constants, copyFile, link, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, rmdir, stat, symlink, unlink, writeFile } from "node:fs/promises";
|
|
10
10
|
import { randomUUID } from "node:crypto";
|
|
11
|
+
import { writeAtomicTextFile } from "@rivus/platform/persistence";
|
|
11
12
|
import { assertPathWithin, isPathWithin } from "@rivus/platform/filesystem";
|
|
12
13
|
import { constants as constants$1 } from "node:fs";
|
|
14
|
+
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
15
|
+
import { spawn } from "node:child_process";
|
|
13
16
|
import { createConnection } from "node:net";
|
|
14
17
|
import { unwrapExit } from "@rivus/platform/effect";
|
|
18
|
+
import { compare, minVersion, parse, satisfies, valid } from "semver";
|
|
19
|
+
import { isDeepStrictEqual } from "node:util";
|
|
20
|
+
import { parse as parse$1, stringify } from "yaml";
|
|
15
21
|
//#region src/core/application/agent-catalog/contracts/rivus-plugin.ts
|
|
16
22
|
const RIVUS_PLUGIN_API_VERSION = "1";
|
|
17
23
|
var InvalidRivusPlugin = class extends Error {
|
|
@@ -693,7 +699,7 @@ function loadRivusHome(directoryPath) {
|
|
|
693
699
|
});
|
|
694
700
|
}
|
|
695
701
|
function parseRivusHomeConfig(value) {
|
|
696
|
-
const config = record(value, "Rivus Home config");
|
|
702
|
+
const config = record$1(value, "Rivus Home config");
|
|
697
703
|
if (config.version !== 1) throw new Error("Rivus Home config version must be 1");
|
|
698
704
|
return {
|
|
699
705
|
bootstrap: nonEmptyString(config.bootstrap, "bootstrap"),
|
|
@@ -725,7 +731,7 @@ function nonEmptyString(value, owner) {
|
|
|
725
731
|
if (typeof value !== "string" || !value.trim()) throw new Error(`Rivus Home ${owner} must be a non-empty string`);
|
|
726
732
|
return value;
|
|
727
733
|
}
|
|
728
|
-
function record(value, owner) {
|
|
734
|
+
function record$1(value, owner) {
|
|
729
735
|
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${owner} must be an object`);
|
|
730
736
|
return value;
|
|
731
737
|
}
|
|
@@ -1268,9 +1274,10 @@ async function runRivusAudioCliCommand(command, context) {
|
|
|
1268
1274
|
//#region src/adapters/cli/command/rivus-cli-protocol.ts
|
|
1269
1275
|
const RIVUS_CLI_USAGE = `Usage:
|
|
1270
1276
|
rivus setup [directory]
|
|
1277
|
+
rivus upgrade [--json]
|
|
1271
1278
|
rivus start
|
|
1272
1279
|
rivus status
|
|
1273
|
-
rivus check-config
|
|
1280
|
+
rivus check-config [--load-plugins]
|
|
1274
1281
|
rivus recovery <recovery options>
|
|
1275
1282
|
rivus init [directory]
|
|
1276
1283
|
rivus doctor [directory] [--env-file <path>]
|
|
@@ -1280,10 +1287,11 @@ const RIVUS_CLI_USAGE = `Usage:
|
|
|
1280
1287
|
|
|
1281
1288
|
Commands:
|
|
1282
1289
|
setup Create Rivus Home (default ~/.rivus-agent) without overwriting files
|
|
1290
|
+
upgrade Upgrade the managed Home service to the latest stable release
|
|
1283
1291
|
start Start the Rivus Home deployment in the foreground
|
|
1284
1292
|
status Print Rivus Home deployment status without activating Endpoints
|
|
1285
1293
|
check-config
|
|
1286
|
-
Validate and print the redacted Rivus Home manifest
|
|
1294
|
+
Validate and print the redacted Rivus Home manifest; optionally load and resolve Plugins
|
|
1287
1295
|
recovery Inspect or recover local state after stopping the Home daemon
|
|
1288
1296
|
init Create a standalone local Rivus project without overwriting files
|
|
1289
1297
|
doctor Check Rivus Home by default, or an explicit standalone project directory
|
|
@@ -1302,7 +1310,7 @@ function renderRivusDirectoryCommandUsage(command) {
|
|
|
1302
1310
|
return `Usage: rivus ${command} [directory]\n`;
|
|
1303
1311
|
}
|
|
1304
1312
|
function renderRivusHomeCommandUsage(command) {
|
|
1305
|
-
return `Usage: rivus ${command}${command === "recovery" ? " <recovery options>" : ""}\n`;
|
|
1313
|
+
return `Usage: rivus ${command}${command === "recovery" ? " <recovery options>" : command === "check-config" ? " [--load-plugins]" : ""}\n`;
|
|
1306
1314
|
}
|
|
1307
1315
|
function renderRivusDoctorUsage() {
|
|
1308
1316
|
return "Usage: rivus doctor [directory] [--env-file <path>]\n";
|
|
@@ -1871,7 +1879,7 @@ function createRivusEnvFromOpenClawConfig(openClawConfig, options = {}) {
|
|
|
1871
1879
|
const appSecret = requiredString(feishu, "appSecret", "channels.feishu.appSecret");
|
|
1872
1880
|
const modelReference = findPrimaryModelReference(config);
|
|
1873
1881
|
const providerId = modelReference ? parseProviderId(modelReference) : void 0;
|
|
1874
|
-
const provider = providerId ? optionalRecord(readPath(config, [
|
|
1882
|
+
const provider = providerId ? optionalRecord$1(readPath(config, [
|
|
1875
1883
|
"models",
|
|
1876
1884
|
"providers",
|
|
1877
1885
|
providerId
|
|
@@ -1898,8 +1906,8 @@ function formatRivusEnvFile(env) {
|
|
|
1898
1906
|
return `${[...ENV_FILE_ORDER.filter((key) => Object.hasOwn(env, key)), ...Object.keys(env).filter((key) => !ENV_FILE_ORDER.includes(key)).sort()].map((key) => `${key}=${quoteEnvValue(env[key] ?? "")}`).join("\n")}\n`;
|
|
1899
1907
|
}
|
|
1900
1908
|
function findAgentId(config) {
|
|
1901
|
-
const agents = optionalRecord(config.agents);
|
|
1902
|
-
return optionalString(optionalRecord((Array.isArray(agents?.list) ? agents.list : [])[0])?.id) ?? DEFAULT_AGENT_ID;
|
|
1909
|
+
const agents = optionalRecord$1(config.agents);
|
|
1910
|
+
return optionalString(optionalRecord$1((Array.isArray(agents?.list) ? agents.list : [])[0])?.id) ?? DEFAULT_AGENT_ID;
|
|
1903
1911
|
}
|
|
1904
1912
|
function findPrimaryModelReference(config) {
|
|
1905
1913
|
const primary = optionalString(readPath(config, [
|
|
@@ -1909,15 +1917,15 @@ function findPrimaryModelReference(config) {
|
|
|
1909
1917
|
"primary"
|
|
1910
1918
|
]));
|
|
1911
1919
|
if (primary) return primary;
|
|
1912
|
-
const providers = optionalRecord(readPath(config, ["models", "providers"]));
|
|
1920
|
+
const providers = optionalRecord$1(readPath(config, ["models", "providers"]));
|
|
1913
1921
|
if (!providers) return;
|
|
1914
1922
|
for (const [providerId, provider] of Object.entries(providers)) {
|
|
1915
|
-
const model = firstModelId(optionalRecord(provider));
|
|
1923
|
+
const model = firstModelId(optionalRecord$1(provider));
|
|
1916
1924
|
if (model) return `${providerId}/${model}`;
|
|
1917
1925
|
}
|
|
1918
1926
|
}
|
|
1919
1927
|
function firstModelId(provider) {
|
|
1920
|
-
return optionalString(optionalRecord((Array.isArray(provider?.models) ? provider.models : [])[0])?.id);
|
|
1928
|
+
return optionalString(optionalRecord$1((Array.isArray(provider?.models) ? provider.models : [])[0])?.id);
|
|
1921
1929
|
}
|
|
1922
1930
|
function parseProviderId(modelReference) {
|
|
1923
1931
|
const separator = modelReference.indexOf("/");
|
|
@@ -1962,7 +1970,7 @@ function readProviderModelThinkingCandidates(config, providerId, modelId) {
|
|
|
1962
1970
|
"models"
|
|
1963
1971
|
]);
|
|
1964
1972
|
if (!Array.isArray(providerModels)) return [];
|
|
1965
|
-
const model = providerModels.map(optionalRecord).find((candidate) => optionalString(candidate?.id) === modelId);
|
|
1973
|
+
const model = providerModels.map(optionalRecord$1).find((candidate) => optionalString(candidate?.id) === modelId);
|
|
1966
1974
|
if (!model) return [];
|
|
1967
1975
|
return [
|
|
1968
1976
|
model.thinkingLevel,
|
|
@@ -1992,17 +2000,17 @@ function optionalString(value) {
|
|
|
1992
2000
|
return typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
1993
2001
|
}
|
|
1994
2002
|
function asRecord(value, path) {
|
|
1995
|
-
const record = optionalRecord(value);
|
|
2003
|
+
const record = optionalRecord$1(value);
|
|
1996
2004
|
if (!record) throw new OpenClawEnvImportError(`${path} must be an object`);
|
|
1997
2005
|
return record;
|
|
1998
2006
|
}
|
|
1999
|
-
function optionalRecord(value) {
|
|
2007
|
+
function optionalRecord$1(value) {
|
|
2000
2008
|
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
2001
2009
|
}
|
|
2002
2010
|
function readPath(record, path) {
|
|
2003
2011
|
let value = record;
|
|
2004
2012
|
for (const segment of path) {
|
|
2005
|
-
const current = optionalRecord(value);
|
|
2013
|
+
const current = optionalRecord$1(value);
|
|
2006
2014
|
if (!current) return;
|
|
2007
2015
|
value = current[segment];
|
|
2008
2016
|
}
|
|
@@ -3723,6 +3731,23 @@ function toError(error) {
|
|
|
3723
3731
|
return error instanceof Error ? error : new Error(String(error));
|
|
3724
3732
|
}
|
|
3725
3733
|
//#endregion
|
|
3734
|
+
//#region src/bootstrap/deployment/check-deployment-plugins.ts
|
|
3735
|
+
function checkDeploymentPlugins(input) {
|
|
3736
|
+
return loadRivusDeploymentManifest(input.manifestPath).pipe(Effect.flatMap((manifest) => resolveRivusDeployment({
|
|
3737
|
+
agentCatalog: createBootstrapAgentCatalog(manifest.backgroundSessions?.enabled === true),
|
|
3738
|
+
createStableId,
|
|
3739
|
+
deepFreeze,
|
|
3740
|
+
deploymentRoot: dirname(input.manifestPath),
|
|
3741
|
+
manifest,
|
|
3742
|
+
pluginLoader: createNodeRivusPluginModuleLoader(input.pluginPackageManifestPath ? { packageManifestPath: input.pluginPackageManifestPath } : {})
|
|
3743
|
+
})), Effect.flatMap((deployment) => {
|
|
3744
|
+
const failedPlugin = deployment.plugins.find((plugin) => plugin.status === "failed");
|
|
3745
|
+
if (failedPlugin) return Effect.fail(/* @__PURE__ */ new Error(`plugin ${failedPlugin.id} failed to load: ${failedPlugin.error}`));
|
|
3746
|
+
const disabledAgent = deployment.agents.find((agent) => agent.status === "disabled");
|
|
3747
|
+
return disabledAgent ? Effect.fail(/* @__PURE__ */ new Error(`deployment ${disabledAgent.agentId} failed to resolve: ${disabledAgent.reason}`)) : Effect.succeed(deployment.manifest);
|
|
3748
|
+
}));
|
|
3749
|
+
}
|
|
3750
|
+
//#endregion
|
|
3726
3751
|
//#region src/bootstrap/daemon/rivus-daemon-cli.ts
|
|
3727
3752
|
function runRivusDaemonCli(options) {
|
|
3728
3753
|
return Effect.gen(function* () {
|
|
@@ -3762,7 +3787,10 @@ function runRivusDaemonCli(options) {
|
|
|
3762
3787
|
return 1;
|
|
3763
3788
|
}
|
|
3764
3789
|
if (parsed.checkConfig) {
|
|
3765
|
-
const manifest = yield*
|
|
3790
|
+
const manifest = yield* options.checkPlugins ? checkDeploymentPlugins({
|
|
3791
|
+
manifestPath: parsed.manifestPath,
|
|
3792
|
+
...options.pluginPackageManifestPath ? { pluginPackageManifestPath: options.pluginPackageManifestPath } : {}
|
|
3793
|
+
}) : loadRivusDeploymentManifest(parsed.manifestPath);
|
|
3766
3794
|
yield* Effect.try({
|
|
3767
3795
|
try: () => validateRivusDeploymentManifest(manifest),
|
|
3768
3796
|
catch: (error) => error
|
|
@@ -3842,11 +3870,26 @@ function runRivusDaemonCli(options) {
|
|
|
3842
3870
|
catch: (error) => error
|
|
3843
3871
|
}));
|
|
3844
3872
|
}
|
|
3873
|
+
const managedDaemon = {
|
|
3874
|
+
...daemon,
|
|
3875
|
+
stop: () => Effect.gen(function* () {
|
|
3876
|
+
const exit = yield* Effect.exit(daemon.stop());
|
|
3877
|
+
if (options.lifecycle) yield* Effect.tryPromise({
|
|
3878
|
+
try: options.lifecycle.stopped,
|
|
3879
|
+
catch: (error) => error
|
|
3880
|
+
});
|
|
3881
|
+
if (Exit.isFailure(exit)) return yield* Effect.failCause(exit.cause);
|
|
3882
|
+
})
|
|
3883
|
+
};
|
|
3845
3884
|
yield* Effect.try({
|
|
3846
|
-
try: () => installCliShutdownController(options,
|
|
3885
|
+
try: () => installCliShutdownController(options, managedDaemon),
|
|
3847
3886
|
catch: (error) => error
|
|
3848
3887
|
});
|
|
3849
3888
|
yield* daemon.start();
|
|
3889
|
+
if (options.lifecycle) yield* Effect.tryPromise({
|
|
3890
|
+
try: options.lifecycle.started,
|
|
3891
|
+
catch: (error) => error
|
|
3892
|
+
}).pipe(Effect.catchCause((cause) => managedDaemon.stop().pipe(Effect.andThen(Effect.failCause(cause)))));
|
|
3850
3893
|
options.stdout.write(RIVUS_DAEMON_STARTED_MESSAGE);
|
|
3851
3894
|
return 0;
|
|
3852
3895
|
}).pipe(Effect.catch((error) => Effect.sync(() => {
|
|
@@ -3908,10 +3951,1469 @@ function hasRecoveryRunner(daemon) {
|
|
|
3908
3951
|
return typeof daemon.openRecoveryControl === "function";
|
|
3909
3952
|
}
|
|
3910
3953
|
//#endregion
|
|
3954
|
+
//#region src/platform/process/run-command.ts
|
|
3955
|
+
const MAX_BYTES = 1048576;
|
|
3956
|
+
/** Bounded subprocesses own their POSIX group so interrupted package managers do not leave installers running. */
|
|
3957
|
+
const runCommand = (request) => new Promise((resolve, reject) => {
|
|
3958
|
+
if (request.signal?.aborted) {
|
|
3959
|
+
reject(/* @__PURE__ */ new Error("command interrupted"));
|
|
3960
|
+
return;
|
|
3961
|
+
}
|
|
3962
|
+
const child = spawn(request.command, [...request.args], {
|
|
3963
|
+
cwd: request.cwd,
|
|
3964
|
+
env: { ...request.env },
|
|
3965
|
+
detached: process.platform !== "win32",
|
|
3966
|
+
stdio: [
|
|
3967
|
+
"ignore",
|
|
3968
|
+
"pipe",
|
|
3969
|
+
"pipe"
|
|
3970
|
+
]
|
|
3971
|
+
});
|
|
3972
|
+
const output = {
|
|
3973
|
+
stdout: [],
|
|
3974
|
+
stderr: []
|
|
3975
|
+
};
|
|
3976
|
+
const sizes = {
|
|
3977
|
+
stdout: 0,
|
|
3978
|
+
stderr: 0
|
|
3979
|
+
};
|
|
3980
|
+
let failure;
|
|
3981
|
+
let escalation;
|
|
3982
|
+
let termination;
|
|
3983
|
+
let terminated;
|
|
3984
|
+
const signal = (name) => {
|
|
3985
|
+
try {
|
|
3986
|
+
if (process.platform !== "win32" && child.pid !== void 0) process.kill(-child.pid, name);
|
|
3987
|
+
else child.kill(name);
|
|
3988
|
+
} catch {}
|
|
3989
|
+
};
|
|
3990
|
+
const stop = (reason) => {
|
|
3991
|
+
if (failure) return;
|
|
3992
|
+
failure = new Error(reason);
|
|
3993
|
+
termination = new Promise((done) => {
|
|
3994
|
+
terminated = done;
|
|
3995
|
+
});
|
|
3996
|
+
signal("SIGTERM");
|
|
3997
|
+
escalation = setTimeout(() => {
|
|
3998
|
+
signal("SIGKILL");
|
|
3999
|
+
terminated?.();
|
|
4000
|
+
}, 2e3);
|
|
4001
|
+
};
|
|
4002
|
+
const timeout = setTimeout(() => stop("command timed out"), request.timeoutMs);
|
|
4003
|
+
const onAbort = () => stop("command interrupted");
|
|
4004
|
+
request.signal?.addEventListener("abort", onAbort, { once: true });
|
|
4005
|
+
for (const stream of ["stdout", "stderr"]) child[stream].on("data", (data) => {
|
|
4006
|
+
if (stream === "stdout" && request.discardStdout) return;
|
|
4007
|
+
sizes[stream] += data.length;
|
|
4008
|
+
if (sizes[stream] > MAX_BYTES) stop("command output exceeded its limit");
|
|
4009
|
+
else output[stream].push(data);
|
|
4010
|
+
});
|
|
4011
|
+
const cleanup = () => {
|
|
4012
|
+
clearTimeout(timeout);
|
|
4013
|
+
clearTimeout(escalation);
|
|
4014
|
+
request.signal?.removeEventListener("abort", onAbort);
|
|
4015
|
+
};
|
|
4016
|
+
child.once("error", (error) => {
|
|
4017
|
+
cleanup();
|
|
4018
|
+
reject(error);
|
|
4019
|
+
});
|
|
4020
|
+
child.once("close", async (exitCode) => {
|
|
4021
|
+
if (termination) await termination;
|
|
4022
|
+
cleanup();
|
|
4023
|
+
if (failure) reject(failure);
|
|
4024
|
+
else resolve({
|
|
4025
|
+
exitCode,
|
|
4026
|
+
stdout: Buffer.concat(output.stdout).toString("utf8"),
|
|
4027
|
+
stderr: Buffer.concat(output.stderr).toString("utf8")
|
|
4028
|
+
});
|
|
4029
|
+
});
|
|
4030
|
+
});
|
|
4031
|
+
//#endregion
|
|
4032
|
+
//#region src/adapters/deployment/upgrade/service-launchd.ts
|
|
4033
|
+
const launchAgentSchema = Schema.Struct({
|
|
4034
|
+
Label: Schema.optional(Schema.String),
|
|
4035
|
+
EnvironmentVariables: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
4036
|
+
Program: Schema.optional(Schema.String),
|
|
4037
|
+
ProgramArguments: Schema.optional(Schema.Array(Schema.String)),
|
|
4038
|
+
WorkingDirectory: Schema.optional(Schema.String)
|
|
4039
|
+
});
|
|
4040
|
+
function createLaunchdServiceManager(context) {
|
|
4041
|
+
const directory = join(context.userHome, "Library", "LaunchAgents");
|
|
4042
|
+
const domain = `gui/${process.getuid?.() ?? failUid()}`;
|
|
4043
|
+
async function readDefinition(path) {
|
|
4044
|
+
try {
|
|
4045
|
+
return Schema.decodeUnknownSync(launchAgentSchema)(JSON.parse(await requireServiceTool(context, "/usr/bin/plutil", [
|
|
4046
|
+
"-convert",
|
|
4047
|
+
"json",
|
|
4048
|
+
"-o",
|
|
4049
|
+
"-",
|
|
4050
|
+
path
|
|
4051
|
+
])));
|
|
4052
|
+
} catch {
|
|
4053
|
+
throw new Error("Cannot read LaunchAgent definition with plutil.");
|
|
4054
|
+
}
|
|
4055
|
+
}
|
|
4056
|
+
async function fromDefinition(path, definition) {
|
|
4057
|
+
const environment = definition.EnvironmentVariables;
|
|
4058
|
+
if (!environment) throw new Error("Managed LaunchAgent needs explicit string EnvironmentVariables.");
|
|
4059
|
+
const env = { ...environment };
|
|
4060
|
+
if (!await matchesHome(env.RIVUS_HOME, context.home)) throw new Error("LaunchAgent no longer selects this Home.");
|
|
4061
|
+
if (!definition.Label || !/^[a-zA-Z0-9._-]+$/u.test(definition.Label)) throw new Error("Unsupported LaunchAgent label.");
|
|
4062
|
+
if (!definition.ProgramArguments) throw new Error("Managed LaunchAgent needs explicit ProgramArguments.");
|
|
4063
|
+
if (definition.Program !== void 0 && definition.Program !== definition.ProgramArguments[0]) throw new Error("LaunchAgent Program differs from ProgramArguments; use a direct Rivus start invocation.");
|
|
4064
|
+
if (!definition.WorkingDirectory || !isAbsolute(definition.WorkingDirectory)) throw new Error("Managed LaunchAgent needs an absolute WorkingDirectory.");
|
|
4065
|
+
const command = await serviceCommand(definition.ProgramArguments, env);
|
|
4066
|
+
if (definition.Program !== void 0 && definition.Program !== command[0]) throw new Error("LaunchAgent Program prevents switching to a direct Node invocation; use ProgramArguments without Program.");
|
|
4067
|
+
return {
|
|
4068
|
+
kind: "launchd",
|
|
4069
|
+
id: definition.Label,
|
|
4070
|
+
definitionPath: path,
|
|
4071
|
+
command,
|
|
4072
|
+
cwd: definition.WorkingDirectory,
|
|
4073
|
+
env
|
|
4074
|
+
};
|
|
4075
|
+
}
|
|
4076
|
+
async function load(identity) {
|
|
4077
|
+
if (identity.kind !== "launchd" || !isAbsolute(identity.definitionPath)) throw new Error("Invalid LaunchAgent identity.");
|
|
4078
|
+
const service = await fromDefinition(identity.definitionPath, await readDefinition(identity.definitionPath));
|
|
4079
|
+
if (service.id !== identity.id) throw new Error("LaunchAgent identity changed; refusing to operate on another service.");
|
|
4080
|
+
return service;
|
|
4081
|
+
}
|
|
4082
|
+
async function query(identity) {
|
|
4083
|
+
const service = await load(identity);
|
|
4084
|
+
const result = await executeServiceTool(context, "/bin/launchctl", ["print", `${domain}/${identity.id}`]);
|
|
4085
|
+
if (result.exitCode !== 0) {
|
|
4086
|
+
if (/Could not find service ["']?[^\n]+ in domain/u.test(result.stderr)) return {
|
|
4087
|
+
loaded: false,
|
|
4088
|
+
running: false,
|
|
4089
|
+
command: service.command
|
|
4090
|
+
};
|
|
4091
|
+
throw new Error("launchctl print failed; the managed service state is unknown.");
|
|
4092
|
+
}
|
|
4093
|
+
const state = /^\s*state = ([^\r\n]+)$/mu.exec(result.stdout)?.[1]?.trim();
|
|
4094
|
+
const pidText = /^\s*pid = (\d+)\s*$/mu.exec(result.stdout)?.[1];
|
|
4095
|
+
const stoppedStates = [
|
|
4096
|
+
"waiting",
|
|
4097
|
+
"not running",
|
|
4098
|
+
"exited"
|
|
4099
|
+
];
|
|
4100
|
+
const pendingStates = [
|
|
4101
|
+
"running",
|
|
4102
|
+
"spawn scheduled",
|
|
4103
|
+
"spawning",
|
|
4104
|
+
"throttled"
|
|
4105
|
+
];
|
|
4106
|
+
if (!state || ![...stoppedStates, ...pendingStates].includes(state)) throw new Error("launchctl print returned an unrecognized service state.");
|
|
4107
|
+
const pid = pidText ? Number(pidText) : void 0;
|
|
4108
|
+
const running = Boolean(pid && pid > 0) || pendingStates.includes(state);
|
|
4109
|
+
const block = /^\s*arguments = \{\r?\n([\s\S]*?)^\s*\}\s*$/mu.exec(result.stdout)?.[1];
|
|
4110
|
+
let command = service.command;
|
|
4111
|
+
if (pid || state === "running") {
|
|
4112
|
+
if (!pid || !block) throw new Error("Cannot confirm the running LaunchAgent PID and command.");
|
|
4113
|
+
command = await serviceCommand(block.split(/\r?\n/u).map((line) => line.trim()).filter(Boolean), service.env, true);
|
|
4114
|
+
}
|
|
4115
|
+
return {
|
|
4116
|
+
loaded: true,
|
|
4117
|
+
running,
|
|
4118
|
+
...pid ? { pid } : {},
|
|
4119
|
+
command
|
|
4120
|
+
};
|
|
4121
|
+
}
|
|
4122
|
+
return {
|
|
4123
|
+
async discover() {
|
|
4124
|
+
let names;
|
|
4125
|
+
try {
|
|
4126
|
+
names = await readdir(directory);
|
|
4127
|
+
} catch (error) {
|
|
4128
|
+
if (!hasServiceFileErrorCode(error, "ENOENT")) throw error;
|
|
4129
|
+
names = [];
|
|
4130
|
+
}
|
|
4131
|
+
const matches = [];
|
|
4132
|
+
for (const name of names.filter((entry) => entry.endsWith(".plist")).sort()) {
|
|
4133
|
+
const path = join(directory, name);
|
|
4134
|
+
const definition = await readDefinition(path);
|
|
4135
|
+
const environment = definition.EnvironmentVariables;
|
|
4136
|
+
if (environment && await matchesHome(environment.RIVUS_HOME, context.home)) matches.push(await fromDefinition(path, definition));
|
|
4137
|
+
}
|
|
4138
|
+
if (matches.length !== 1) throw new Error(`Expected exactly one LaunchAgent for this Home; found ${matches.length}.`);
|
|
4139
|
+
return matches[0];
|
|
4140
|
+
},
|
|
4141
|
+
load,
|
|
4142
|
+
async inspect(identity) {
|
|
4143
|
+
const { loaded: _loaded, ...status } = await query(identity);
|
|
4144
|
+
return status;
|
|
4145
|
+
},
|
|
4146
|
+
async stop(identity) {
|
|
4147
|
+
if ((await query(identity)).loaded) await requireServiceTool(context, "/bin/launchctl", ["bootout", `${domain}/${identity.id}`]);
|
|
4148
|
+
await waitForServiceStop(context, () => query(identity));
|
|
4149
|
+
},
|
|
4150
|
+
async switch(identity, command, backupDirectory) {
|
|
4151
|
+
const service = await load(identity);
|
|
4152
|
+
const candidate = await serviceCommand(command, service.env);
|
|
4153
|
+
const definition = await readDefinition(identity.definitionPath);
|
|
4154
|
+
if (definition.Program !== void 0 && definition.Program !== candidate[0]) throw new Error("LaunchAgent Program would override the candidate executable; use ProgramArguments without Program.");
|
|
4155
|
+
await snapshotFile(identity.definitionPath, join(backupDirectory, "service.plist"));
|
|
4156
|
+
if (sameCommand$1(service.command, candidate)) return;
|
|
4157
|
+
if ((await query(identity)).loaded) throw new Error("LaunchAgent is still loaded; stop it before switching its definition.");
|
|
4158
|
+
const temporary = `${identity.definitionPath}.${randomUUID()}.tmp`;
|
|
4159
|
+
try {
|
|
4160
|
+
await copyFile(identity.definitionPath, temporary);
|
|
4161
|
+
await requireServiceTool(context, "/usr/bin/plutil", [
|
|
4162
|
+
"-replace",
|
|
4163
|
+
"ProgramArguments",
|
|
4164
|
+
"-json",
|
|
4165
|
+
JSON.stringify(candidate),
|
|
4166
|
+
temporary
|
|
4167
|
+
]);
|
|
4168
|
+
await rename(temporary, identity.definitionPath);
|
|
4169
|
+
} finally {
|
|
4170
|
+
await rm(temporary, { force: true });
|
|
4171
|
+
}
|
|
4172
|
+
},
|
|
4173
|
+
async start(identity) {
|
|
4174
|
+
const status = await query(identity);
|
|
4175
|
+
if (status.running) return;
|
|
4176
|
+
if (status.loaded) await requireServiceTool(context, "/bin/launchctl", ["bootout", `${domain}/${identity.id}`]);
|
|
4177
|
+
await requireServiceTool(context, "/bin/launchctl", [
|
|
4178
|
+
"bootstrap",
|
|
4179
|
+
domain,
|
|
4180
|
+
identity.definitionPath
|
|
4181
|
+
]);
|
|
4182
|
+
}
|
|
4183
|
+
};
|
|
4184
|
+
}
|
|
4185
|
+
function failUid() {
|
|
4186
|
+
throw new Error("Cannot determine the current user's launchd domain.");
|
|
4187
|
+
}
|
|
4188
|
+
//#endregion
|
|
4189
|
+
//#region src/adapters/deployment/upgrade/service-systemd.ts
|
|
4190
|
+
const bus = "org.freedesktop.systemd1";
|
|
4191
|
+
const managerPath = "/org/freedesktop/systemd1";
|
|
4192
|
+
const stringsSchema = Schema.Array(Schema.String);
|
|
4193
|
+
const environmentFilesSchema = Schema.Array(Schema.Tuple([Schema.String, Schema.Boolean]));
|
|
4194
|
+
const execStartSchema = Schema.Array(Schema.Tuple([
|
|
4195
|
+
Schema.String,
|
|
4196
|
+
stringsSchema,
|
|
4197
|
+
stringsSchema,
|
|
4198
|
+
Schema.Number,
|
|
4199
|
+
Schema.Number,
|
|
4200
|
+
Schema.Number,
|
|
4201
|
+
Schema.Number,
|
|
4202
|
+
Schema.Number,
|
|
4203
|
+
Schema.Number,
|
|
4204
|
+
Schema.Number
|
|
4205
|
+
]));
|
|
4206
|
+
const stringsPropertySchema = Schema.Struct({
|
|
4207
|
+
type: Schema.Literal("as"),
|
|
4208
|
+
data: stringsSchema
|
|
4209
|
+
});
|
|
4210
|
+
const environmentFilesPropertySchema = Schema.Struct({
|
|
4211
|
+
type: Schema.Literal("a(sb)"),
|
|
4212
|
+
data: environmentFilesSchema
|
|
4213
|
+
});
|
|
4214
|
+
const execStartPropertySchema = Schema.Struct({
|
|
4215
|
+
type: Schema.Literal("a(sasasttttuii)"),
|
|
4216
|
+
data: execStartSchema
|
|
4217
|
+
});
|
|
4218
|
+
const unitPathSchema = Schema.Struct({
|
|
4219
|
+
type: Schema.Literal("o"),
|
|
4220
|
+
data: Schema.Tuple([Schema.String])
|
|
4221
|
+
});
|
|
4222
|
+
const nonEmpty = Schema.String.check(Schema.isNonEmpty());
|
|
4223
|
+
const unitPropertiesSchema = Schema.Struct({
|
|
4224
|
+
Id: nonEmpty,
|
|
4225
|
+
LoadState: nonEmpty,
|
|
4226
|
+
ActiveState: nonEmpty,
|
|
4227
|
+
SubState: nonEmpty,
|
|
4228
|
+
MainPID: Schema.String.check(Schema.isPattern(/^\d+$/u)),
|
|
4229
|
+
WorkingDirectory: Schema.optional(Schema.String),
|
|
4230
|
+
FragmentPath: Schema.optional(Schema.String)
|
|
4231
|
+
});
|
|
4232
|
+
function createSystemdServiceManager(context) {
|
|
4233
|
+
async function busRequest(args, schema) {
|
|
4234
|
+
const output = await requireServiceTool(context, "busctl", [
|
|
4235
|
+
"--user",
|
|
4236
|
+
"--json=short",
|
|
4237
|
+
...args
|
|
4238
|
+
]);
|
|
4239
|
+
try {
|
|
4240
|
+
return Schema.decodeUnknownSync(schema)(JSON.parse(output));
|
|
4241
|
+
} catch {
|
|
4242
|
+
throw new Error("busctl returned invalid structured service data.");
|
|
4243
|
+
}
|
|
4244
|
+
}
|
|
4245
|
+
async function property(path, owner, name, schema) {
|
|
4246
|
+
return busRequest([
|
|
4247
|
+
"get-property",
|
|
4248
|
+
bus,
|
|
4249
|
+
path,
|
|
4250
|
+
`${bus}.${owner}`,
|
|
4251
|
+
name
|
|
4252
|
+
], schema);
|
|
4253
|
+
}
|
|
4254
|
+
async function unitPath(id) {
|
|
4255
|
+
const { data } = await busRequest([
|
|
4256
|
+
"call",
|
|
4257
|
+
bus,
|
|
4258
|
+
managerPath,
|
|
4259
|
+
`${bus}.Manager`,
|
|
4260
|
+
"GetUnit",
|
|
4261
|
+
"s",
|
|
4262
|
+
id
|
|
4263
|
+
], unitPathSchema);
|
|
4264
|
+
if (!data[0].startsWith(`${managerPath}/unit/`)) throw new Error("Cannot identify the systemd user service object.");
|
|
4265
|
+
return data[0];
|
|
4266
|
+
}
|
|
4267
|
+
async function show(id) {
|
|
4268
|
+
if (!/^[a-zA-Z0-9_@.\\:-]+\.service$/u.test(id) || id.startsWith("-")) throw new Error("Unsupported systemd service identity.");
|
|
4269
|
+
const output = await requireServiceTool(context, "systemctl", [
|
|
4270
|
+
"--user",
|
|
4271
|
+
"show",
|
|
4272
|
+
id,
|
|
4273
|
+
"--no-pager",
|
|
4274
|
+
"--property=Id,LoadState,ActiveState,SubState,MainPID,WorkingDirectory,FragmentPath,Environment,ExecStart"
|
|
4275
|
+
]);
|
|
4276
|
+
const values = {};
|
|
4277
|
+
for (const line of output.split(/\r?\n/u)) {
|
|
4278
|
+
const separator = line.indexOf("=");
|
|
4279
|
+
if (separator > 0) values[line.slice(0, separator)] = line.slice(separator + 1);
|
|
4280
|
+
}
|
|
4281
|
+
try {
|
|
4282
|
+
return Schema.decodeUnknownSync(unitPropertiesSchema)(values);
|
|
4283
|
+
} catch {
|
|
4284
|
+
throw new Error("systemctl show could not confirm the loaded service state.");
|
|
4285
|
+
}
|
|
4286
|
+
}
|
|
4287
|
+
async function readService(id) {
|
|
4288
|
+
if (context.env.XDG_CONFIG_HOME !== void 0 && !isAbsolute(context.env.XDG_CONFIG_HOME)) throw new Error("systemd XDG_CONFIG_HOME must be absolute.");
|
|
4289
|
+
const values = await show(id);
|
|
4290
|
+
if (values.LoadState !== "loaded") throw new Error("systemctl show could not confirm the loaded service state.");
|
|
4291
|
+
const path = await unitPath(id);
|
|
4292
|
+
const configured = environment((await property(path, "Service", "Environment", stringsPropertySchema)).data);
|
|
4293
|
+
const inherited = environment((await property(managerPath, "Manager", "Environment", stringsPropertySchema)).data);
|
|
4294
|
+
if (!await matchesHome(configured.RIVUS_HOME, context.home)) throw new Error("User service must declare this RIVUS_HOME directly in Environment; EnvironmentFile-only binding is unsupported.");
|
|
4295
|
+
const { data: files } = await property(path, "Service", "EnvironmentFiles", environmentFilesPropertySchema);
|
|
4296
|
+
const { data: unset } = await property(path, "Service", "UnsetEnvironment", stringsPropertySchema);
|
|
4297
|
+
if (files.length !== 0 || unset.length !== 0) throw new Error("Managed upgrade cannot determine service environment with EnvironmentFile or UnsetEnvironment; declare it directly before upgrading.");
|
|
4298
|
+
const { data: commands } = await property(path, "Service", "ExecStartEx", execStartPropertySchema);
|
|
4299
|
+
if (commands.length !== 1) throw new Error("Managed systemd service needs exactly one ExecStart command.");
|
|
4300
|
+
const entry = commands[0];
|
|
4301
|
+
if (entry[2].some((flag) => flag !== "no-env-expand") || entry[0] !== entry[1][0]) throw new Error("Unsupported systemd ExecStart flags or executable wrapper.");
|
|
4302
|
+
if (entry[2].length === 0 && entry[1].some((argument) => argument.includes("$"))) throw new Error("Managed upgrade requires literal ExecStart arguments; dynamic systemd environment expansion is unsupported.");
|
|
4303
|
+
if (!values.FragmentPath || !isAbsolute(values.FragmentPath) || !values.WorkingDirectory || !isAbsolute(values.WorkingDirectory)) throw new Error("Managed systemd service needs an absolute FragmentPath and WorkingDirectory.");
|
|
4304
|
+
const env = {
|
|
4305
|
+
...inherited,
|
|
4306
|
+
...configured
|
|
4307
|
+
};
|
|
4308
|
+
const service = {
|
|
4309
|
+
kind: "systemd",
|
|
4310
|
+
id: values.Id,
|
|
4311
|
+
definitionPath: values.FragmentPath,
|
|
4312
|
+
command: await serviceCommand(entry[1], env),
|
|
4313
|
+
cwd: values.WorkingDirectory,
|
|
4314
|
+
env
|
|
4315
|
+
};
|
|
4316
|
+
const pid = Number(values.MainPID);
|
|
4317
|
+
return {
|
|
4318
|
+
service,
|
|
4319
|
+
path,
|
|
4320
|
+
running: pid > 0 || !["inactive", "failed"].includes(values.ActiveState),
|
|
4321
|
+
...pid > 0 ? { pid } : {}
|
|
4322
|
+
};
|
|
4323
|
+
}
|
|
4324
|
+
async function loadAndQuery(identity) {
|
|
4325
|
+
if (identity.kind !== "systemd") throw new Error("Invalid systemd service identity.");
|
|
4326
|
+
const status = await readService(identity.id);
|
|
4327
|
+
if (status.service.id !== identity.id || status.service.definitionPath !== identity.definitionPath) throw new Error("systemd service identity changed; refusing to operate on another definition.");
|
|
4328
|
+
return status;
|
|
4329
|
+
}
|
|
4330
|
+
async function inspect(identity) {
|
|
4331
|
+
const status = await loadAndQuery(identity);
|
|
4332
|
+
let command = status.service.command;
|
|
4333
|
+
if (status.pid) try {
|
|
4334
|
+
command = await serviceCommand(await context.readProcessCommand(status.pid), status.service.env, true);
|
|
4335
|
+
} catch {
|
|
4336
|
+
const observed = await loadAndQuery(identity);
|
|
4337
|
+
if (!observed.running) return {
|
|
4338
|
+
running: false,
|
|
4339
|
+
command: observed.service.command
|
|
4340
|
+
};
|
|
4341
|
+
throw new Error("Cannot confirm the running systemd service command; its process state is unknown.");
|
|
4342
|
+
}
|
|
4343
|
+
return {
|
|
4344
|
+
running: status.running,
|
|
4345
|
+
...status.pid ? { pid: status.pid } : {},
|
|
4346
|
+
command
|
|
4347
|
+
};
|
|
4348
|
+
}
|
|
4349
|
+
return {
|
|
4350
|
+
async discover() {
|
|
4351
|
+
const output = await requireServiceTool(context, "systemctl", [
|
|
4352
|
+
"--user",
|
|
4353
|
+
"list-unit-files",
|
|
4354
|
+
"--type=service",
|
|
4355
|
+
"--no-legend",
|
|
4356
|
+
"--no-pager"
|
|
4357
|
+
]);
|
|
4358
|
+
const matches = /* @__PURE__ */ new Map();
|
|
4359
|
+
for (const line of output.split(/\r?\n/u).filter((value) => value.trim())) {
|
|
4360
|
+
const id = line.trim().split(/\s+/u)[0];
|
|
4361
|
+
if (id.endsWith("@.service")) continue;
|
|
4362
|
+
const values = await show(id);
|
|
4363
|
+
if (values.LoadState !== "loaded") {
|
|
4364
|
+
if ([
|
|
4365
|
+
"masked",
|
|
4366
|
+
"not-found",
|
|
4367
|
+
"stub"
|
|
4368
|
+
].includes(values.LoadState) && ["inactive", "failed"].includes(values.ActiveState) && values.MainPID === "0") continue;
|
|
4369
|
+
throw new Error("systemctl show could not confirm the loaded service state.");
|
|
4370
|
+
}
|
|
4371
|
+
if (await matchesHome(environment((await property(await unitPath(id), "Service", "Environment", stringsPropertySchema)).data).RIVUS_HOME, context.home)) {
|
|
4372
|
+
const { service } = await readService(values.Id);
|
|
4373
|
+
matches.set(service.id, service);
|
|
4374
|
+
}
|
|
4375
|
+
}
|
|
4376
|
+
if (matches.size !== 1) throw new Error(`Expected exactly one user service with direct RIVUS_HOME Environment for this Home; found ${matches.size}.`);
|
|
4377
|
+
return matches.values().next().value;
|
|
4378
|
+
},
|
|
4379
|
+
async load(identity) {
|
|
4380
|
+
return (await loadAndQuery(identity)).service;
|
|
4381
|
+
},
|
|
4382
|
+
inspect,
|
|
4383
|
+
async stop(identity) {
|
|
4384
|
+
if ((await inspect(identity)).running) await requireServiceTool(context, "systemctl", [
|
|
4385
|
+
"--user",
|
|
4386
|
+
"stop",
|
|
4387
|
+
identity.id
|
|
4388
|
+
]);
|
|
4389
|
+
await waitForServiceStop(context, () => inspect(identity));
|
|
4390
|
+
},
|
|
4391
|
+
async switch(identity, command, backupDirectory) {
|
|
4392
|
+
const status = await loadAndQuery(identity);
|
|
4393
|
+
const candidate = await serviceCommand(command, status.service.env);
|
|
4394
|
+
await snapshotFile(identity.definitionPath, join(backupDirectory, "service.unit"));
|
|
4395
|
+
const manifestPath = join(backupDirectory, "service.drop-ins.json");
|
|
4396
|
+
if (await readFile(manifestPath, "utf8").catch((error) => {
|
|
4397
|
+
if (!hasServiceFileErrorCode(error, "ENOENT")) throw error;
|
|
4398
|
+
}) === void 0) {
|
|
4399
|
+
const { data: dropIns } = await property(status.path, "Unit", "DropInPaths", stringsPropertySchema);
|
|
4400
|
+
if (!dropIns.every((value) => isAbsolute(value))) throw new Error("Cannot confirm existing systemd drop-in definitions.");
|
|
4401
|
+
const manifest = [];
|
|
4402
|
+
for (const [index, path] of dropIns.entries()) {
|
|
4403
|
+
const backup = join("service.drop-ins", `${index}.conf`);
|
|
4404
|
+
await snapshotFile(path, join(backupDirectory, backup));
|
|
4405
|
+
manifest.push({
|
|
4406
|
+
path,
|
|
4407
|
+
backup
|
|
4408
|
+
});
|
|
4409
|
+
}
|
|
4410
|
+
await writeAtomicTextFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, {
|
|
4411
|
+
mode: 384,
|
|
4412
|
+
durable: true
|
|
4413
|
+
});
|
|
4414
|
+
}
|
|
4415
|
+
if (sameCommand$1(status.service.command, candidate)) return;
|
|
4416
|
+
if (status.running) throw new Error("User service is still running; stop it before switching its definition.");
|
|
4417
|
+
const config = context.env.XDG_CONFIG_HOME ?? join(context.userHome, ".config");
|
|
4418
|
+
if (!isAbsolute(config)) throw new Error("systemd XDG_CONFIG_HOME must be absolute.");
|
|
4419
|
+
const dropInPath = join(config, "systemd", "user", `${identity.id}.d`, "zz-rivus-upgrade.conf");
|
|
4420
|
+
const absentMarker = join(backupDirectory, "service.upgrade-drop-in.absent");
|
|
4421
|
+
if (await readFile(absentMarker, "utf8").catch((error) => {
|
|
4422
|
+
if (!hasServiceFileErrorCode(error, "ENOENT")) throw error;
|
|
4423
|
+
}) === void 0) try {
|
|
4424
|
+
await snapshotFile(dropInPath, join(backupDirectory, "service.upgrade-drop-in.conf"));
|
|
4425
|
+
} catch (error) {
|
|
4426
|
+
if (!hasServiceFileErrorCode(error, "ENOENT")) throw error;
|
|
4427
|
+
await writeAtomicTextFile(absentMarker, "", {
|
|
4428
|
+
mode: 384,
|
|
4429
|
+
durable: true
|
|
4430
|
+
});
|
|
4431
|
+
}
|
|
4432
|
+
const content = `[Service]\nExecStart=\nExecStart=:${candidate.map(quoteSystemdArgument).join(" ")}\n`;
|
|
4433
|
+
if (await readFile(dropInPath, "utf8").catch((error) => {
|
|
4434
|
+
if (!hasServiceFileErrorCode(error, "ENOENT")) throw error;
|
|
4435
|
+
}) !== content) await writeAtomicTextFile(dropInPath, content, {
|
|
4436
|
+
mode: 384,
|
|
4437
|
+
durable: true
|
|
4438
|
+
});
|
|
4439
|
+
await requireServiceTool(context, "systemctl", ["--user", "daemon-reload"]);
|
|
4440
|
+
if (!sameCommand$1((await loadAndQuery(identity)).service.command, candidate)) throw new Error("systemd did not apply the candidate ExecStart; inspect overriding drop-ins before resuming.");
|
|
4441
|
+
},
|
|
4442
|
+
async start(identity) {
|
|
4443
|
+
if (!(await inspect(identity)).running) await requireServiceTool(context, "systemctl", [
|
|
4444
|
+
"--user",
|
|
4445
|
+
"start",
|
|
4446
|
+
identity.id
|
|
4447
|
+
]);
|
|
4448
|
+
}
|
|
4449
|
+
};
|
|
4450
|
+
}
|
|
4451
|
+
function environment(value) {
|
|
4452
|
+
const result = {};
|
|
4453
|
+
for (const entry of value) {
|
|
4454
|
+
const separator = entry.indexOf("=");
|
|
4455
|
+
if (separator < 1) throw new Error("Invalid systemd Environment assignment.");
|
|
4456
|
+
result[entry.slice(0, separator)] = entry.slice(separator + 1);
|
|
4457
|
+
}
|
|
4458
|
+
return result;
|
|
4459
|
+
}
|
|
4460
|
+
function quoteSystemdArgument(argument) {
|
|
4461
|
+
return `"${argument.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"").replaceAll("%", "%%")}"`;
|
|
4462
|
+
}
|
|
4463
|
+
//#endregion
|
|
4464
|
+
//#region src/adapters/deployment/upgrade/service.ts
|
|
4465
|
+
const agentPackageSchema = Schema.Struct({
|
|
4466
|
+
name: Schema.Literal("@rivus/agent"),
|
|
4467
|
+
bin: Schema.Union([Schema.String, Schema.Struct({ rivus: Schema.String })])
|
|
4468
|
+
});
|
|
4469
|
+
const isFileError = Schema.is(Schema.Struct({ code: Schema.String }));
|
|
4470
|
+
function createServiceManager(options) {
|
|
4471
|
+
const context = {
|
|
4472
|
+
...options,
|
|
4473
|
+
run: options.run ?? runCommand,
|
|
4474
|
+
timeoutMs: options.timeoutMs ?? 3e4,
|
|
4475
|
+
pollIntervalMs: options.pollIntervalMs ?? 100,
|
|
4476
|
+
readProcessCommand: options.readProcessCommand ?? (async (pid) => {
|
|
4477
|
+
return (await readFile(`/proc/${pid}/cmdline`, "utf8")).split("\0").filter(Boolean);
|
|
4478
|
+
})
|
|
4479
|
+
};
|
|
4480
|
+
if (options.platform === "darwin") return createLaunchdServiceManager(context);
|
|
4481
|
+
if (options.platform === "linux") return createSystemdServiceManager(context);
|
|
4482
|
+
throw new Error("Managed upgrade supports only macOS LaunchAgents and Linux user services.");
|
|
4483
|
+
}
|
|
4484
|
+
async function serviceCommand(command, env, runningProcess = false) {
|
|
4485
|
+
if (command.some((argument) => !argument || /[\r\n\0]/u.test(argument))) throw new Error("Unsupported service command arguments.");
|
|
4486
|
+
let normalized = [...command];
|
|
4487
|
+
if (runningProcess && (normalized[0] === "node" || normalized[0] === "nodejs")) normalized[0] = await configuredNode(env, normalized[0]);
|
|
4488
|
+
if (normalized.at(-1) !== "start" || !normalized[0] || !isAbsolute(normalized[0])) throw new Error("Managed service must invoke an absolute Rivus executable with only the start command.");
|
|
4489
|
+
if (!isNodeExecutable(normalized[0])) {
|
|
4490
|
+
if (normalized.length !== 2) throw new Error("Unsupported service wrapper; invoke Node and the Rivus CLI directly.");
|
|
4491
|
+
const script = await realpath(normalized[0]);
|
|
4492
|
+
const shebang = (await readFile(script, "utf8")).split("\n", 1)[0];
|
|
4493
|
+
let node;
|
|
4494
|
+
if (shebang === "#!/usr/bin/env node") node = await configuredNode(env, "node");
|
|
4495
|
+
else if (shebang?.startsWith("#!/") && isNodeExecutable(shebang.slice(2))) node = shebang.slice(2);
|
|
4496
|
+
if (!node) throw new Error("Cannot determine the service's Node executable from its shebang and configured PATH.");
|
|
4497
|
+
normalized = [
|
|
4498
|
+
node,
|
|
4499
|
+
script,
|
|
4500
|
+
"start"
|
|
4501
|
+
];
|
|
4502
|
+
}
|
|
4503
|
+
const script = normalized.at(-2);
|
|
4504
|
+
if (!script || !isAbsolute(script)) throw new Error("Managed service needs an absolute Rivus CLI script path.");
|
|
4505
|
+
validateNodeFlags(normalized.slice(1, -2));
|
|
4506
|
+
await access(normalized[0], constants$1.X_OK);
|
|
4507
|
+
const actualScript = await realpath(script);
|
|
4508
|
+
const packageDirectory = dirname(dirname(actualScript));
|
|
4509
|
+
let manifest;
|
|
4510
|
+
try {
|
|
4511
|
+
manifest = Schema.decodeUnknownSync(agentPackageSchema)(JSON.parse(await readFile(join(packageDirectory, "package.json"), "utf8")));
|
|
4512
|
+
} catch {
|
|
4513
|
+
throw new Error("Cannot identify the managed Rivus CLI package; invoke the installed @rivus/agent bin directly.");
|
|
4514
|
+
}
|
|
4515
|
+
const bin = typeof manifest.bin === "string" ? manifest.bin : manifest.bin.rivus;
|
|
4516
|
+
if (await realpath(resolve(packageDirectory, bin)) !== actualScript) throw new Error("Managed service executable does not match the @rivus/agent rivus bin.");
|
|
4517
|
+
normalized[normalized.length - 2] = actualScript;
|
|
4518
|
+
return normalized;
|
|
4519
|
+
}
|
|
4520
|
+
async function configuredNode(env, name) {
|
|
4521
|
+
for (const directory of env.PATH?.split(":") ?? []) {
|
|
4522
|
+
if (!isAbsolute(directory)) continue;
|
|
4523
|
+
const candidate = join(directory, name);
|
|
4524
|
+
try {
|
|
4525
|
+
await access(candidate, constants$1.X_OK);
|
|
4526
|
+
return candidate;
|
|
4527
|
+
} catch (error) {
|
|
4528
|
+
if (!hasServiceFileErrorCode(error, "ENOENT") && !hasServiceFileErrorCode(error, "EACCES")) throw error;
|
|
4529
|
+
}
|
|
4530
|
+
}
|
|
4531
|
+
throw new Error("Cannot determine the service's Node executable from its configured PATH.");
|
|
4532
|
+
}
|
|
4533
|
+
function isNodeExecutable(path) {
|
|
4534
|
+
return isAbsolute(path) && /^(?:node|nodejs)(?:\.exe)?$/u.test(basename(path));
|
|
4535
|
+
}
|
|
4536
|
+
function validateNodeFlags(flags) {
|
|
4537
|
+
const withValue = /* @__PURE__ */ new Set([
|
|
4538
|
+
"--env-file",
|
|
4539
|
+
"--env-file-if-exists",
|
|
4540
|
+
"--require",
|
|
4541
|
+
"-r",
|
|
4542
|
+
"--import",
|
|
4543
|
+
"--loader",
|
|
4544
|
+
"--experimental-loader",
|
|
4545
|
+
"--conditions",
|
|
4546
|
+
"-C"
|
|
4547
|
+
]);
|
|
4548
|
+
for (let index = 0; index < flags.length; index += 1) {
|
|
4549
|
+
const flag = flags[index];
|
|
4550
|
+
if (withValue.has(flag)) {
|
|
4551
|
+
if (!flags[index + 1]) throw new Error("A service Node flag is missing its value.");
|
|
4552
|
+
index += 1;
|
|
4553
|
+
} else if (flag.includes("=") && withValue.has(flag.slice(0, flag.indexOf("=")))) {
|
|
4554
|
+
if (!flag.slice(flag.indexOf("=") + 1)) throw new Error("A service Node flag is missing its value.");
|
|
4555
|
+
} else if (!flag.startsWith("--") || !process.allowedNodeEnvironmentFlags.has(flag) || flag === "--test") throw new Error("Unsupported service Node flags; use a direct Node invocation of rivus start.");
|
|
4556
|
+
}
|
|
4557
|
+
}
|
|
4558
|
+
async function matchesHome(value, home) {
|
|
4559
|
+
if (!value || !isAbsolute(value)) return false;
|
|
4560
|
+
try {
|
|
4561
|
+
return await realpath(value) === await realpath(home);
|
|
4562
|
+
} catch (error) {
|
|
4563
|
+
if (hasServiceFileErrorCode(error, "ENOENT")) return false;
|
|
4564
|
+
throw error;
|
|
4565
|
+
}
|
|
4566
|
+
}
|
|
4567
|
+
function sameCommand$1(left, right) {
|
|
4568
|
+
return left.length === right.length && left.every((value, index) => value === right[index]);
|
|
4569
|
+
}
|
|
4570
|
+
async function executeServiceTool(context, command, args) {
|
|
4571
|
+
try {
|
|
4572
|
+
return await context.run({
|
|
4573
|
+
command,
|
|
4574
|
+
args,
|
|
4575
|
+
cwd: context.userHome,
|
|
4576
|
+
env: context.env,
|
|
4577
|
+
timeoutMs: context.timeoutMs
|
|
4578
|
+
});
|
|
4579
|
+
} catch {
|
|
4580
|
+
throw new Error(`Cannot execute ${basename(command)} for managed service; check its installation and user permissions.`);
|
|
4581
|
+
}
|
|
4582
|
+
}
|
|
4583
|
+
async function requireServiceTool(context, command, args) {
|
|
4584
|
+
const result = await executeServiceTool(context, command, args);
|
|
4585
|
+
if (result.exitCode !== 0) throw new Error(`${basename(command)} ${args.find((argument) => !argument.startsWith("-")) ?? "query"} failed for managed service.`);
|
|
4586
|
+
return result.stdout;
|
|
4587
|
+
}
|
|
4588
|
+
async function waitForServiceStop(context, inspect) {
|
|
4589
|
+
const deadline = Date.now() + context.timeoutMs;
|
|
4590
|
+
while ((await inspect()).running) {
|
|
4591
|
+
if (Date.now() >= deadline) throw new Error("Managed service did not stop before the timeout; no definition was changed.");
|
|
4592
|
+
await setTimeout$1(context.pollIntervalMs);
|
|
4593
|
+
}
|
|
4594
|
+
}
|
|
4595
|
+
async function snapshotFile(source, destination) {
|
|
4596
|
+
await mkdir(dirname(destination), {
|
|
4597
|
+
recursive: true,
|
|
4598
|
+
mode: 448
|
|
4599
|
+
});
|
|
4600
|
+
const temporary = `${destination}.${randomUUID()}.tmp`;
|
|
4601
|
+
try {
|
|
4602
|
+
await writeFile(temporary, await readFile(source), {
|
|
4603
|
+
flag: "wx",
|
|
4604
|
+
mode: 384,
|
|
4605
|
+
flush: true
|
|
4606
|
+
});
|
|
4607
|
+
await link(temporary, destination);
|
|
4608
|
+
const directory = await open(dirname(destination), "r");
|
|
4609
|
+
try {
|
|
4610
|
+
await directory.sync();
|
|
4611
|
+
} finally {
|
|
4612
|
+
await directory.close();
|
|
4613
|
+
}
|
|
4614
|
+
} catch (error) {
|
|
4615
|
+
if (!hasServiceFileErrorCode(error, "EEXIST")) throw error;
|
|
4616
|
+
} finally {
|
|
4617
|
+
await rm(temporary, { force: true });
|
|
4618
|
+
}
|
|
4619
|
+
}
|
|
4620
|
+
function hasServiceFileErrorCode(error, code) {
|
|
4621
|
+
return isFileError(error) && error.code === code;
|
|
4622
|
+
}
|
|
4623
|
+
//#endregion
|
|
4624
|
+
//#region src/adapters/deployment/upgrade/package-command.ts
|
|
4625
|
+
async function resolveServiceNode(command, cwd, env) {
|
|
4626
|
+
const candidates = isAbsolute(command) || command.includes("/") ? [resolve(cwd, command)] : (env.PATH ?? "").split(delimiter).filter(Boolean).map((directory) => resolve(cwd, directory, command));
|
|
4627
|
+
for (const candidate of candidates) try {
|
|
4628
|
+
await access(candidate, constants.X_OK);
|
|
4629
|
+
return await realpath(candidate);
|
|
4630
|
+
} catch {}
|
|
4631
|
+
throw new Error("The managed service Node executable is unavailable");
|
|
4632
|
+
}
|
|
4633
|
+
async function npmInvocation(nodePath) {
|
|
4634
|
+
for (const candidate of [join(dirname(nodePath), "npm"), resolve(dirname(nodePath), "../lib/node_modules/npm/bin/npm-cli.js")]) try {
|
|
4635
|
+
await access(candidate, constants.R_OK);
|
|
4636
|
+
return [await realpath(candidate)];
|
|
4637
|
+
} catch {}
|
|
4638
|
+
throw new Error("npm is unavailable beside the managed service Node; install npm for that Node distribution");
|
|
4639
|
+
}
|
|
4640
|
+
async function checkedPackageCommand(run, request, phase, diagnosticsPath) {
|
|
4641
|
+
let result;
|
|
4642
|
+
try {
|
|
4643
|
+
result = await run(request);
|
|
4644
|
+
} catch {
|
|
4645
|
+
throw new Error(`${phase} could not complete; the service has not been stopped`);
|
|
4646
|
+
}
|
|
4647
|
+
if (result.exitCode !== 0) {
|
|
4648
|
+
if (diagnosticsPath) {
|
|
4649
|
+
await writeFile(diagnosticsPath, `${result.stdout}\n${result.stderr}`, { mode: 384 });
|
|
4650
|
+
await chmod(diagnosticsPath, 384);
|
|
4651
|
+
}
|
|
4652
|
+
throw new Error(`${phase} failed (exit ${result.exitCode ?? "signal"}); the service has not been stopped${diagnosticsPath ? `; private diagnostics: ${diagnosticsPath}` : ""}`);
|
|
4653
|
+
}
|
|
4654
|
+
return result;
|
|
4655
|
+
}
|
|
4656
|
+
function installerEnvironment(nodePath, env) {
|
|
4657
|
+
return {
|
|
4658
|
+
...env,
|
|
4659
|
+
PATH: [dirname(nodePath), env.PATH].filter(Boolean).join(delimiter)
|
|
4660
|
+
};
|
|
4661
|
+
}
|
|
4662
|
+
function packedArtifactPath(stdout, directory) {
|
|
4663
|
+
try {
|
|
4664
|
+
const packed = Schema.decodeUnknownSync(Schema.Array(Schema.Struct({ filename: Schema.String })))(JSON.parse(stdout));
|
|
4665
|
+
if (packed.length !== 1 || !packed[0] || basename(packed[0].filename) !== packed[0].filename) throw new Error("invalid artifact");
|
|
4666
|
+
return join(directory, packed[0].filename);
|
|
4667
|
+
} catch {
|
|
4668
|
+
throw new Error("Package preparation returned an invalid artifact");
|
|
4669
|
+
}
|
|
4670
|
+
}
|
|
4671
|
+
//#endregion
|
|
4672
|
+
//#region src/adapters/deployment/upgrade/package-policy.ts
|
|
4673
|
+
const stringMap = Schema.Record(Schema.String, Schema.String);
|
|
4674
|
+
const policySchema = Schema.Struct({
|
|
4675
|
+
schemaVersion: Schema.Literal(1),
|
|
4676
|
+
stateCompatibility: Schema.Literal("rivus-home-0.20"),
|
|
4677
|
+
minimumSourceVersion: Schema.String,
|
|
4678
|
+
pnpmVersion: Schema.String,
|
|
4679
|
+
overrides: stringMap,
|
|
4680
|
+
allowBuilds: Schema.Record(Schema.String, Schema.Boolean)
|
|
4681
|
+
});
|
|
4682
|
+
async function readInstallationPolicy(directory = gatewayPackageDirectory) {
|
|
4683
|
+
return parseInstallationPolicy(await readFile(join(directory, "assets/installation-policy.json"), "utf8").catch(() => ""));
|
|
4684
|
+
}
|
|
4685
|
+
async function fetchInstallationPolicy(input) {
|
|
4686
|
+
const directory = join(input.directory, "policy");
|
|
4687
|
+
await mkdir(directory, {
|
|
4688
|
+
mode: 448,
|
|
4689
|
+
recursive: true
|
|
4690
|
+
});
|
|
4691
|
+
const artifact = packedArtifactPath((await checkedPackageCommand(input.run, {
|
|
4692
|
+
...input.npm,
|
|
4693
|
+
args: [
|
|
4694
|
+
...input.npm.args,
|
|
4695
|
+
"pack",
|
|
4696
|
+
`@rivus/gateway@${input.version}`,
|
|
4697
|
+
"--ignore-scripts",
|
|
4698
|
+
"--pack-destination",
|
|
4699
|
+
directory,
|
|
4700
|
+
"--json"
|
|
4701
|
+
]
|
|
4702
|
+
}, "Target installation policy download", join(input.directory, "policy-download.log"))).stdout, directory);
|
|
4703
|
+
return parseInstallationPolicy((await checkedPackageCommand(input.run, {
|
|
4704
|
+
...input.npm,
|
|
4705
|
+
command: "/usr/bin/tar",
|
|
4706
|
+
args: [
|
|
4707
|
+
"-xOf",
|
|
4708
|
+
artifact,
|
|
4709
|
+
"package/assets/installation-policy.json"
|
|
4710
|
+
],
|
|
4711
|
+
timeoutMs: 3e4
|
|
4712
|
+
}, "Target installation policy extraction", join(input.directory, "policy-extraction.log"))).stdout);
|
|
4713
|
+
}
|
|
4714
|
+
function parseInstallationPolicy(text) {
|
|
4715
|
+
try {
|
|
4716
|
+
const policy = Schema.decodeUnknownSync(policySchema)(JSON.parse(text));
|
|
4717
|
+
if (valid(policy.minimumSourceVersion) !== policy.minimumSourceVersion || valid(policy.pnpmVersion) !== policy.pnpmVersion) throw new Error("invalid version");
|
|
4718
|
+
for (const floor of Object.values(policy.overrides)) if (!valid(floor)) throw new Error("invalid security floor");
|
|
4719
|
+
return policy;
|
|
4720
|
+
} catch {
|
|
4721
|
+
throw new Error("Release installation policy is missing, invalid or requires an unsupported Home migration");
|
|
4722
|
+
}
|
|
4723
|
+
}
|
|
4724
|
+
function assertSourceCompatibility(policy, sourceVersion) {
|
|
4725
|
+
if (compare(sourceVersion, policy.minimumSourceVersion) < 0) throw new Error(`This release requires a Home from Rivus ${policy.minimumSourceVersion} or newer; migrate the Home explicitly before upgrading`);
|
|
4726
|
+
}
|
|
4727
|
+
/** Raise older reviewed pins while keeping consumer overrides that already require a newer dependency. */
|
|
4728
|
+
function mergeInstallationOverrides(source, policy) {
|
|
4729
|
+
const merged = { ...source };
|
|
4730
|
+
for (const [selector, floor] of Object.entries(policy.overrides)) {
|
|
4731
|
+
let selected = floor;
|
|
4732
|
+
const name = dependencyName(selector);
|
|
4733
|
+
for (const [existing, requirement] of Object.entries(merged)) {
|
|
4734
|
+
if (existing !== name && !existing.startsWith(`${name}@`) && !existing.endsWith(`>${name}`) && !existing.includes(`>${name}@`)) continue;
|
|
4735
|
+
const minimum = minVersion(requirement);
|
|
4736
|
+
if (!minimum) throw new Error(`Consumer override for ${name} must use a registry version before managed upgrade`);
|
|
4737
|
+
const affectedRange = selector.slice(name.length + 1);
|
|
4738
|
+
if (affectedRange && !satisfies(minimum, affectedRange) && minimum.major !== minVersion(floor).major) continue;
|
|
4739
|
+
if (compare(minimum, floor) < 0) merged[existing] = floor;
|
|
4740
|
+
else if (compare(minimum, selected) > 0) selected = minimum.version;
|
|
4741
|
+
}
|
|
4742
|
+
merged[selector] = selected;
|
|
4743
|
+
}
|
|
4744
|
+
return merged;
|
|
4745
|
+
}
|
|
4746
|
+
function dependencyName(selector) {
|
|
4747
|
+
const version = selector.indexOf("@", 1);
|
|
4748
|
+
return version === -1 ? selector : selector.slice(0, version);
|
|
4749
|
+
}
|
|
4750
|
+
//#endregion
|
|
4751
|
+
//#region src/adapters/deployment/upgrade/package-consumer.ts
|
|
4752
|
+
const corePackageNames = [
|
|
4753
|
+
"@rivus/agent",
|
|
4754
|
+
"@rivus/gateway",
|
|
4755
|
+
"@rivus/runtime",
|
|
4756
|
+
"@rivus/platform"
|
|
4757
|
+
];
|
|
4758
|
+
const recordSchema = Schema.Record(Schema.String, Schema.Unknown);
|
|
4759
|
+
const stringMapSchema = Schema.Record(Schema.String, Schema.String);
|
|
4760
|
+
const buildMapSchema = Schema.Record(Schema.String, Schema.Boolean);
|
|
4761
|
+
const installedManifestSchema = Schema.Struct({
|
|
4762
|
+
name: Schema.String,
|
|
4763
|
+
version: Schema.String
|
|
4764
|
+
});
|
|
4765
|
+
async function readInstalledManifest(root, name, resolutionBase) {
|
|
4766
|
+
try {
|
|
4767
|
+
return Schema.decodeUnknownSync(installedManifestSchema)(JSON.parse(await readFile(installedPackageManifestPath(root, name, resolutionBase), "utf8")));
|
|
4768
|
+
} catch {
|
|
4769
|
+
throw new Error(`Installed dependency ${name} is missing or has an invalid package manifest`);
|
|
4770
|
+
}
|
|
4771
|
+
}
|
|
4772
|
+
function installedPackageManifestPath(root, name, resolutionBase = join(root, "package.json")) {
|
|
4773
|
+
try {
|
|
4774
|
+
const manifest = findPackageJSON(name, resolutionBase);
|
|
4775
|
+
if (manifest) return manifest;
|
|
4776
|
+
} catch {}
|
|
4777
|
+
throw new Error(`Installed dependency ${name} cannot be resolved from the managed release`);
|
|
4778
|
+
}
|
|
4779
|
+
async function writeReleaseConsumer(input) {
|
|
4780
|
+
const rootManifest = join(input.sourceRoot, "package.json");
|
|
4781
|
+
const sourceBase = await exists(rootManifest) ? rootManifest : join(input.sourceRoot, "node_modules/@rivus/agent/package.json");
|
|
4782
|
+
const manifest = await optionalRecord(sourceBase);
|
|
4783
|
+
const workspace = await optionalRecord(join(input.sourceRoot, "pnpm-workspace.yaml"), true);
|
|
4784
|
+
const sourcePnpm = record(manifest.pnpm ?? {});
|
|
4785
|
+
const dependencies = {};
|
|
4786
|
+
const optionalDependencies = {};
|
|
4787
|
+
const installedVersions = {};
|
|
4788
|
+
for (const [field, target] of [["dependencies", dependencies], ["optionalDependencies", optionalDependencies]]) {
|
|
4789
|
+
const declared = Schema.decodeUnknownSync(stringMapSchema)(manifest[field] ?? {});
|
|
4790
|
+
for (const [name, requirement] of Object.entries(declared)) {
|
|
4791
|
+
if (corePackageNames.some((core) => core === name)) continue;
|
|
4792
|
+
const installed = await readInstalledManifest(input.sourceRoot, name, sourceBase).catch((error) => {
|
|
4793
|
+
if (field === "optionalDependencies") return;
|
|
4794
|
+
throw error;
|
|
4795
|
+
});
|
|
4796
|
+
if (!installed) continue;
|
|
4797
|
+
installedVersions[name] = installed.version;
|
|
4798
|
+
target[name] = requirement.startsWith("file:") || requirement.startsWith("link:") ? await retainLocalArtifact(input, name, requirement, sourceBase) : requirement.startsWith("npm:") ? `npm:${installed.name}@${installed.version}` : installed.version;
|
|
4799
|
+
}
|
|
4800
|
+
}
|
|
4801
|
+
for (const name of corePackageNames) dependencies[name] = input.version;
|
|
4802
|
+
if (!dependencies.effect) dependencies.effect = (await readInstalledManifest(input.sourceRoot, "effect", sourceBase)).version;
|
|
4803
|
+
const gatewayBase = installedPackageManifestPath(input.sourceRoot, "@rivus/gateway", join(input.sourceRoot, "node_modules/@rivus/agent/package.json"));
|
|
4804
|
+
const homeMetadata = await stat(input.homeManifestPath);
|
|
4805
|
+
if (!homeMetadata.isFile() || homeMetadata.size > 1048576) throw new Error("The Home deployment manifest must be a regular file of at most one MiB");
|
|
4806
|
+
const homeManifest = parseRivusDeploymentManifest(JSON.parse(await readFile(input.homeManifestPath, "utf8")));
|
|
4807
|
+
for (const plugin of homeManifest.plugins) {
|
|
4808
|
+
if (plugin.module.startsWith(".") || plugin.module.startsWith("/")) continue;
|
|
4809
|
+
const name = plugin.module.split("/").slice(0, plugin.module.startsWith("@") ? 2 : 1).join("/");
|
|
4810
|
+
if (corePackageNames.some((core) => core === name) || dependencies[name] || optionalDependencies[name]) continue;
|
|
4811
|
+
installedVersions[name] = (await readInstalledManifest(input.sourceRoot, name, gatewayBase)).version;
|
|
4812
|
+
dependencies[name] = await retainLocalArtifact(input, name, void 0, gatewayBase);
|
|
4813
|
+
}
|
|
4814
|
+
for (const name of corePackageNames) installedVersions[name] = input.version;
|
|
4815
|
+
installedVersions.effect = dependencies.effect;
|
|
4816
|
+
const sourceOverrides = {
|
|
4817
|
+
...flattenNpmOverrides(record(manifest.overrides ?? {}), dependencies),
|
|
4818
|
+
...Schema.decodeUnknownSync(stringMapSchema)(sourcePnpm.overrides ?? {}),
|
|
4819
|
+
...Schema.decodeUnknownSync(stringMapSchema)(workspace.overrides ?? {})
|
|
4820
|
+
};
|
|
4821
|
+
const allowBuilds = {
|
|
4822
|
+
...input.policy.allowBuilds,
|
|
4823
|
+
...Schema.decodeUnknownSync(buildMapSchema)(sourcePnpm.allowBuilds ?? {}),
|
|
4824
|
+
...Schema.decodeUnknownSync(buildMapSchema)(workspace.allowBuilds ?? {})
|
|
4825
|
+
};
|
|
4826
|
+
await privateFile(join(input.directory, "package.json"), `${JSON.stringify({
|
|
4827
|
+
name: "rivus-managed-release",
|
|
4828
|
+
private: true,
|
|
4829
|
+
type: "module",
|
|
4830
|
+
packageManager: `pnpm@${input.policy.pnpmVersion}`,
|
|
4831
|
+
dependencies,
|
|
4832
|
+
...Object.keys(optionalDependencies).length ? { optionalDependencies } : {},
|
|
4833
|
+
...manifest.overrides ? { overrides: manifest.overrides } : {}
|
|
4834
|
+
}, null, 2)}\n`);
|
|
4835
|
+
await privateFile(join(input.directory, "pnpm-workspace.yaml"), stringify({
|
|
4836
|
+
packages: ["."],
|
|
4837
|
+
nodeLinker: "hoisted",
|
|
4838
|
+
strictPeerDependencies: true,
|
|
4839
|
+
virtualStoreDir: "node_modules/.pnpm",
|
|
4840
|
+
packageImportMethod: "copy",
|
|
4841
|
+
allowBuilds,
|
|
4842
|
+
overrides: mergeInstallationOverrides(sourceOverrides, input.policy)
|
|
4843
|
+
}));
|
|
4844
|
+
return installedVersions;
|
|
4845
|
+
}
|
|
4846
|
+
async function retainLocalArtifact(input, name, requirement, resolutionBase) {
|
|
4847
|
+
const artifacts = join(input.directory, "artifacts");
|
|
4848
|
+
await mkdir(artifacts, {
|
|
4849
|
+
recursive: true,
|
|
4850
|
+
mode: 448
|
|
4851
|
+
});
|
|
4852
|
+
const target = requirement ? resolve(dirname(resolutionBase), requirement.slice(requirement.indexOf(":") + 1)) : void 0;
|
|
4853
|
+
const artifactName = `${name}.tgz`;
|
|
4854
|
+
const destination = resolve(artifacts, artifactName);
|
|
4855
|
+
if (!destination.startsWith(`${artifacts}${sep}`)) throw new Error("Local dependency artifact escapes the release directory");
|
|
4856
|
+
await mkdir(dirname(destination), {
|
|
4857
|
+
recursive: true,
|
|
4858
|
+
mode: 448
|
|
4859
|
+
});
|
|
4860
|
+
if (target && await exists(target) && (await stat(target)).isFile()) {
|
|
4861
|
+
await copyFile(target, destination);
|
|
4862
|
+
await chmod(destination, 384);
|
|
4863
|
+
return `file:artifacts/${artifactName}`;
|
|
4864
|
+
}
|
|
4865
|
+
const packedPath = packedArtifactPath((await checkedPackageCommand(input.run, {
|
|
4866
|
+
...input.npm,
|
|
4867
|
+
args: [
|
|
4868
|
+
...input.npm.args,
|
|
4869
|
+
"pack",
|
|
4870
|
+
dirname(installedPackageManifestPath(input.sourceRoot, name, resolutionBase)),
|
|
4871
|
+
"--ignore-scripts",
|
|
4872
|
+
"--pack-destination",
|
|
4873
|
+
artifacts,
|
|
4874
|
+
"--json"
|
|
4875
|
+
]
|
|
4876
|
+
}, `Retaining local dependency ${name}`)).stdout, artifacts);
|
|
4877
|
+
if (packedPath !== destination) await copyFile(packedPath, destination);
|
|
4878
|
+
await chmod(destination, 384);
|
|
4879
|
+
return `file:artifacts/${artifactName}`;
|
|
4880
|
+
}
|
|
4881
|
+
function flattenNpmOverrides(source, dependencies, parent = "") {
|
|
4882
|
+
const result = {};
|
|
4883
|
+
for (const [name, value] of Object.entries(source)) {
|
|
4884
|
+
const selector = name === "." ? parent : parent ? `${parent}>${name}` : name;
|
|
4885
|
+
if (typeof value === "string") {
|
|
4886
|
+
const requirement = value.startsWith("$") ? dependencies[value.slice(1)] : value;
|
|
4887
|
+
if (!selector || !requirement) throw new Error("Consumer npm override cannot be resolved for managed installation");
|
|
4888
|
+
result[selector] = requirement;
|
|
4889
|
+
} else Object.assign(result, flattenNpmOverrides(record(value), dependencies, selector));
|
|
4890
|
+
}
|
|
4891
|
+
return result;
|
|
4892
|
+
}
|
|
4893
|
+
async function optionalRecord(path, yaml = false) {
|
|
4894
|
+
let text;
|
|
4895
|
+
try {
|
|
4896
|
+
text = await readFile(path, "utf8");
|
|
4897
|
+
} catch (error) {
|
|
4898
|
+
if (Schema.is(Schema.Struct({ code: Schema.Literal("ENOENT") }))(error)) return {};
|
|
4899
|
+
throw new Error("The installed consumer configuration cannot be read");
|
|
4900
|
+
}
|
|
4901
|
+
try {
|
|
4902
|
+
return record(yaml ? parse$1(text) : JSON.parse(text));
|
|
4903
|
+
} catch {
|
|
4904
|
+
throw new Error("The installed consumer configuration is invalid");
|
|
4905
|
+
}
|
|
4906
|
+
}
|
|
4907
|
+
function record(value) {
|
|
4908
|
+
return Schema.decodeUnknownSync(recordSchema)(value);
|
|
4909
|
+
}
|
|
4910
|
+
async function exists(path) {
|
|
4911
|
+
try {
|
|
4912
|
+
await stat(path);
|
|
4913
|
+
return true;
|
|
4914
|
+
} catch (error) {
|
|
4915
|
+
if (Schema.is(Schema.Struct({ code: Schema.Literal("ENOENT") }))(error)) return false;
|
|
4916
|
+
throw error;
|
|
4917
|
+
}
|
|
4918
|
+
}
|
|
4919
|
+
async function privateFile(path, contents) {
|
|
4920
|
+
await writeFile(path, contents, { mode: 384 });
|
|
4921
|
+
await chmod(path, 384);
|
|
4922
|
+
}
|
|
4923
|
+
//#endregion
|
|
4924
|
+
//#region src/adapters/deployment/upgrade/package-release.ts
|
|
4925
|
+
async function inspectInstalledRelease(command, cwd, env) {
|
|
4926
|
+
const executable = command.at(-1) === "start" ? command.at(-2) : command.length === 2 ? command[1] : void 0;
|
|
4927
|
+
if (!command[0] || !executable) throw new Error("Managed service must invoke Node and the Rivus product CLI");
|
|
4928
|
+
const nodePath = await resolveServiceNode(command[0], cwd, env);
|
|
4929
|
+
let cliPath;
|
|
4930
|
+
try {
|
|
4931
|
+
cliPath = await realpath(resolve(cwd, executable));
|
|
4932
|
+
} catch {
|
|
4933
|
+
throw new Error("The managed Rivus CLI is unavailable");
|
|
4934
|
+
}
|
|
4935
|
+
const root = resolve(dirname(cliPath), "../../../..");
|
|
4936
|
+
if (cliPath !== join(root, "node_modules/@rivus/agent/dist/cli.js")) throw new Error("Managed upgrade requires a direct @rivus/agent product installation");
|
|
4937
|
+
const agentManifest = join(root, "node_modules/@rivus/agent/package.json");
|
|
4938
|
+
let version;
|
|
4939
|
+
for (const name of corePackageNames) {
|
|
4940
|
+
const manifest = await readInstalledManifest(root, name, name === "@rivus/platform" ? installedPackageManifestPath(root, "@rivus/runtime", agentManifest) : agentManifest);
|
|
4941
|
+
if (manifest.name !== name || !stableVersion(manifest.version) || version !== void 0 && version !== manifest.version) throw new Error("The managed service does not have one complete, stable four-package Rivus release");
|
|
4942
|
+
version = manifest.version;
|
|
4943
|
+
}
|
|
4944
|
+
return {
|
|
4945
|
+
cliPath,
|
|
4946
|
+
nodePath,
|
|
4947
|
+
root,
|
|
4948
|
+
version
|
|
4949
|
+
};
|
|
4950
|
+
}
|
|
4951
|
+
async function resolveLatestVersion(input) {
|
|
4952
|
+
const nodePath = input.nodePath ?? process.execPath;
|
|
4953
|
+
const result = await checkedPackageCommand(input.run, {
|
|
4954
|
+
command: nodePath,
|
|
4955
|
+
args: [
|
|
4956
|
+
...await npmInvocation(nodePath),
|
|
4957
|
+
"view",
|
|
4958
|
+
"@rivus/agent",
|
|
4959
|
+
"dist-tags.latest",
|
|
4960
|
+
"--json"
|
|
4961
|
+
],
|
|
4962
|
+
cwd: input.cwd,
|
|
4963
|
+
env: input.env,
|
|
4964
|
+
timeoutMs: 6e4,
|
|
4965
|
+
...input.signal ? { signal: input.signal } : {}
|
|
4966
|
+
}, "Latest release lookup");
|
|
4967
|
+
try {
|
|
4968
|
+
const version = JSON.parse(result.stdout);
|
|
4969
|
+
if (typeof version === "string" && stableVersion(version)) return version;
|
|
4970
|
+
} catch {}
|
|
4971
|
+
throw new Error("The configured registry latest tag must identify a stable three-component Rivus version");
|
|
4972
|
+
}
|
|
4973
|
+
async function prepareRelease(input) {
|
|
4974
|
+
if (!stableVersion(input.version)) throw new Error("Managed upgrade requires a stable three-component release version");
|
|
4975
|
+
if (resolve(input.directory) === input.source.root) throw new Error("A candidate release must use a separate installation directory");
|
|
4976
|
+
assertSourceCompatibility(await readInstallationPolicy(), input.source.version);
|
|
4977
|
+
await mkdir(input.directory, {
|
|
4978
|
+
recursive: true,
|
|
4979
|
+
mode: 448
|
|
4980
|
+
});
|
|
4981
|
+
await chmod(input.directory, 448);
|
|
4982
|
+
const npmrc = await retainRegistryConfiguration(input.source.root, input.directory);
|
|
4983
|
+
const npm = {
|
|
4984
|
+
command: input.source.nodePath,
|
|
4985
|
+
args: await npmInvocation(input.source.nodePath),
|
|
4986
|
+
cwd: input.directory,
|
|
4987
|
+
env: installerEnvironment(input.source.nodePath, {
|
|
4988
|
+
...input.service.env,
|
|
4989
|
+
...npmrc ? { npm_config_userconfig: npmrc } : {}
|
|
4990
|
+
}),
|
|
4991
|
+
timeoutMs: 9e5,
|
|
4992
|
+
...input.signal ? { signal: input.signal } : {}
|
|
4993
|
+
};
|
|
4994
|
+
const policy = await fetchInstallationPolicy({
|
|
4995
|
+
version: input.version,
|
|
4996
|
+
directory: input.directory,
|
|
4997
|
+
npm,
|
|
4998
|
+
run: input.run
|
|
4999
|
+
});
|
|
5000
|
+
assertSourceCompatibility(policy, input.source.version);
|
|
5001
|
+
let versions;
|
|
5002
|
+
try {
|
|
5003
|
+
versions = await writeReleaseConsumer({
|
|
5004
|
+
sourceRoot: input.source.root,
|
|
5005
|
+
directory: input.directory,
|
|
5006
|
+
version: input.version,
|
|
5007
|
+
policy,
|
|
5008
|
+
run: input.run,
|
|
5009
|
+
npm,
|
|
5010
|
+
homeManifestPath: input.home.manifestPath
|
|
5011
|
+
});
|
|
5012
|
+
} catch {
|
|
5013
|
+
throw new Error("The source consumer or Home plugins could not be retained; check source dependencies, overrides and the Home manifest before upgrading");
|
|
5014
|
+
}
|
|
5015
|
+
const pnpmArgs = [
|
|
5016
|
+
...npm.args,
|
|
5017
|
+
"exec",
|
|
5018
|
+
"--yes",
|
|
5019
|
+
"--package",
|
|
5020
|
+
`pnpm@${policy.pnpmVersion}`,
|
|
5021
|
+
"--",
|
|
5022
|
+
"pnpm"
|
|
5023
|
+
];
|
|
5024
|
+
await checkedPackageCommand(input.run, {
|
|
5025
|
+
...npm,
|
|
5026
|
+
args: [
|
|
5027
|
+
...pnpmArgs,
|
|
5028
|
+
"install",
|
|
5029
|
+
"--prod",
|
|
5030
|
+
"--no-frozen-lockfile",
|
|
5031
|
+
"--reporter=silent",
|
|
5032
|
+
"--config.node-linker=hoisted",
|
|
5033
|
+
"--config.strict-peer-dependencies=true",
|
|
5034
|
+
"--config.virtual-store-dir=node_modules/.pnpm",
|
|
5035
|
+
"--config.package-import-method=copy",
|
|
5036
|
+
"--ignore-scripts=false"
|
|
5037
|
+
],
|
|
5038
|
+
discardStdout: true
|
|
5039
|
+
}, "Candidate package installation", join(input.directory, "installation.log"));
|
|
5040
|
+
const cliPath = join(resolve(input.directory), "node_modules/@rivus/agent/dist/cli.js");
|
|
5041
|
+
const candidate = await inspectInstalledRelease([input.source.nodePath, cliPath], input.service.cwd, input.service.env);
|
|
5042
|
+
if (candidate.version !== input.version) throw new Error("Candidate packages do not match the selected release");
|
|
5043
|
+
for (const [name, version] of Object.entries(versions)) if ((await readInstalledManifest(candidate.root, name)).version !== version) throw new Error(`Candidate dependency ${name} does not retain the selected installed version`);
|
|
5044
|
+
const installedPolicy = await readInstallationPolicy(join(candidate.root, "node_modules/@rivus/gateway"));
|
|
5045
|
+
if (!isDeepStrictEqual(installedPolicy, policy)) throw new Error("Installed candidate policy differs from the selected release artifact");
|
|
5046
|
+
await checkedPackageCommand(input.run, {
|
|
5047
|
+
...npm,
|
|
5048
|
+
args: [
|
|
5049
|
+
...pnpmArgs,
|
|
5050
|
+
"audit",
|
|
5051
|
+
"--prod",
|
|
5052
|
+
"--audit-level=high",
|
|
5053
|
+
"--json"
|
|
5054
|
+
],
|
|
5055
|
+
timeoutMs: 12e4
|
|
5056
|
+
}, "Candidate dependency audit", join(input.directory, "audit.log"));
|
|
5057
|
+
const check = {
|
|
5058
|
+
command: input.source.nodePath,
|
|
5059
|
+
cwd: input.service.cwd,
|
|
5060
|
+
env: {
|
|
5061
|
+
...input.service.env,
|
|
5062
|
+
RIVUS_HOME: input.home.directory
|
|
5063
|
+
},
|
|
5064
|
+
timeoutMs: 6e4,
|
|
5065
|
+
...input.signal ? { signal: input.signal } : {}
|
|
5066
|
+
};
|
|
5067
|
+
const nodeArgs = input.service.command.at(-1) === "start" ? input.service.command.slice(1, -2) : [];
|
|
5068
|
+
await checkedPackageCommand(input.run, {
|
|
5069
|
+
...check,
|
|
5070
|
+
args: [
|
|
5071
|
+
...nodeArgs,
|
|
5072
|
+
cliPath,
|
|
5073
|
+
"doctor",
|
|
5074
|
+
"--env-file",
|
|
5075
|
+
input.home.envFilePath
|
|
5076
|
+
]
|
|
5077
|
+
}, "Candidate Home doctor", join(input.directory, "doctor.log"));
|
|
5078
|
+
await checkedPackageCommand(input.run, {
|
|
5079
|
+
...check,
|
|
5080
|
+
args: [
|
|
5081
|
+
...nodeArgs,
|
|
5082
|
+
cliPath,
|
|
5083
|
+
"check-config",
|
|
5084
|
+
"--load-plugins"
|
|
5085
|
+
]
|
|
5086
|
+
}, "Candidate plugin validation", join(input.directory, "plugins.log"));
|
|
5087
|
+
await checkedPackageCommand(input.run, {
|
|
5088
|
+
...check,
|
|
5089
|
+
args: [
|
|
5090
|
+
...nodeArgs,
|
|
5091
|
+
"--input-type=commonjs",
|
|
5092
|
+
"--eval",
|
|
5093
|
+
nativeCheck,
|
|
5094
|
+
cliPath,
|
|
5095
|
+
candidate.root
|
|
5096
|
+
]
|
|
5097
|
+
}, "Candidate native module validation", join(input.directory, "native.log"));
|
|
5098
|
+
return {
|
|
5099
|
+
cliPath,
|
|
5100
|
+
version: candidate.version
|
|
5101
|
+
};
|
|
5102
|
+
}
|
|
5103
|
+
function stableVersion(value) {
|
|
5104
|
+
const parsed = parse(value);
|
|
5105
|
+
return parsed !== null && parsed.version === value && parsed.prerelease.length === 0 && parsed.build.length === 0;
|
|
5106
|
+
}
|
|
5107
|
+
async function hasFile(path) {
|
|
5108
|
+
try {
|
|
5109
|
+
return (await stat(path)).isFile();
|
|
5110
|
+
} catch {
|
|
5111
|
+
return false;
|
|
5112
|
+
}
|
|
5113
|
+
}
|
|
5114
|
+
async function retainRegistryConfiguration(sourceRoot, directory) {
|
|
5115
|
+
const source = join(sourceRoot, ".npmrc");
|
|
5116
|
+
if (!await hasFile(source)) return;
|
|
5117
|
+
const target = await realpath(source);
|
|
5118
|
+
const destination = join(directory, ".npmrc");
|
|
5119
|
+
try {
|
|
5120
|
+
await symlink(target, destination);
|
|
5121
|
+
} catch {
|
|
5122
|
+
if (await realpath(destination).catch(() => void 0) !== target) throw new Error("Candidate registry configuration cannot retain the installed configuration");
|
|
5123
|
+
}
|
|
5124
|
+
return target;
|
|
5125
|
+
}
|
|
5126
|
+
const nativeCheck = `
|
|
5127
|
+
const { createRequire } = require("node:module");
|
|
5128
|
+
const { realpathSync } = require("node:fs");
|
|
5129
|
+
const { join } = require("node:path");
|
|
5130
|
+
const consumer = createRequire(process.argv[1]);
|
|
5131
|
+
const gateway = createRequire(consumer.resolve("@rivus/gateway/package.json"));
|
|
5132
|
+
const { Resvg } = gateway("@resvg/resvg-js");
|
|
5133
|
+
const png = new Resvg('<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"><rect width="1" height="1" fill="red"/></svg>').render().asPng();
|
|
5134
|
+
if (!png.length) throw new Error("Resvg produced no image");
|
|
5135
|
+
const pi = createRequire(realpathSync(join(process.argv[2], "node_modules/@earendil-works/pi-coding-agent/package.json")));
|
|
5136
|
+
const { PhotonImage } = pi("@silvia-odwyer/photon-node");
|
|
5137
|
+
const image = new PhotonImage(new Uint8Array([0, 0, 0, 0]), 1, 1);
|
|
5138
|
+
try { if (image.get_width() !== 1 || image.get_height() !== 1 || !image.get_bytes().length) throw new Error("Photon produced no image"); }
|
|
5139
|
+
finally { image.free(); }
|
|
5140
|
+
`;
|
|
5141
|
+
//#endregion
|
|
5142
|
+
//#region src/adapters/deployment/upgrade/home-backup.ts
|
|
5143
|
+
async function backUpUpgradeHome(input) {
|
|
5144
|
+
await mkdir(input.directory, {
|
|
5145
|
+
recursive: true,
|
|
5146
|
+
mode: 448
|
|
5147
|
+
});
|
|
5148
|
+
const archive = join(input.directory, "home.tar");
|
|
5149
|
+
const temporary = `${archive}.partial`;
|
|
5150
|
+
try {
|
|
5151
|
+
if ((await input.run({
|
|
5152
|
+
command: "/usr/bin/tar",
|
|
5153
|
+
args: [
|
|
5154
|
+
"-cpf",
|
|
5155
|
+
temporary,
|
|
5156
|
+
"--exclude=./.rivus-upgrade",
|
|
5157
|
+
"-C",
|
|
5158
|
+
input.home,
|
|
5159
|
+
"."
|
|
5160
|
+
],
|
|
5161
|
+
cwd: input.home,
|
|
5162
|
+
env: input.env,
|
|
5163
|
+
timeoutMs: 18e5,
|
|
5164
|
+
...input.signal ? { signal: input.signal } : {},
|
|
5165
|
+
discardStdout: true
|
|
5166
|
+
})).exitCode !== 0) throw new Error("Home backup failed; the service remains stopped and the previous release is retained");
|
|
5167
|
+
await chmod(temporary, 384);
|
|
5168
|
+
await verifyArchive(temporary, input);
|
|
5169
|
+
await rename(temporary, archive);
|
|
5170
|
+
return archive;
|
|
5171
|
+
} finally {
|
|
5172
|
+
await rm(temporary, { force: true });
|
|
5173
|
+
}
|
|
5174
|
+
}
|
|
5175
|
+
async function verifyUpgradeBackup(input) {
|
|
5176
|
+
await verifyArchive(join(input.directory, "home.tar"), input);
|
|
5177
|
+
}
|
|
5178
|
+
async function verifyArchive(path, input) {
|
|
5179
|
+
const metadata = await stat(path);
|
|
5180
|
+
if (!metadata.isFile() || metadata.size === 0) throw new Error("Home backup is missing or empty");
|
|
5181
|
+
if ((await input.run({
|
|
5182
|
+
command: "/usr/bin/tar",
|
|
5183
|
+
args: ["-tf", path],
|
|
5184
|
+
cwd: input.home,
|
|
5185
|
+
env: input.env,
|
|
5186
|
+
timeoutMs: 18e5,
|
|
5187
|
+
discardStdout: true
|
|
5188
|
+
})).exitCode !== 0) throw new Error("Home backup could not be read; refusing to switch the service");
|
|
5189
|
+
}
|
|
5190
|
+
//#endregion
|
|
5191
|
+
//#region src/bootstrap/upgrade/upgrade-home.ts
|
|
5192
|
+
/** Owns one managed process cutover. Application data is retained in its original Home throughout the operation. */
|
|
5193
|
+
async function upgradeHome(options) {
|
|
5194
|
+
const home = {
|
|
5195
|
+
...options.home,
|
|
5196
|
+
directory: await realpath(options.home.directory)
|
|
5197
|
+
};
|
|
5198
|
+
const releaseLock = await acquireUpgradeLock(home.directory, options);
|
|
5199
|
+
try {
|
|
5200
|
+
return await upgradeLocked({
|
|
5201
|
+
...options,
|
|
5202
|
+
home
|
|
5203
|
+
});
|
|
5204
|
+
} finally {
|
|
5205
|
+
await releaseLock();
|
|
5206
|
+
}
|
|
5207
|
+
}
|
|
5208
|
+
async function upgradeLocked(options) {
|
|
5209
|
+
const { home } = options;
|
|
5210
|
+
const runner = options.run ?? runCommand;
|
|
5211
|
+
const run = (request) => runner({
|
|
5212
|
+
...request,
|
|
5213
|
+
...options.signal ? { signal: options.signal } : {}
|
|
5214
|
+
});
|
|
5215
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
5216
|
+
const packages = options.packages ?? {
|
|
5217
|
+
inspect: inspectInstalledRelease,
|
|
5218
|
+
latest: resolveLatestVersion,
|
|
5219
|
+
prepare: prepareRelease
|
|
5220
|
+
};
|
|
5221
|
+
const services = options.services ?? createServiceManager({
|
|
5222
|
+
home: home.directory,
|
|
5223
|
+
userHome: options.userHome,
|
|
5224
|
+
platform: options.platform,
|
|
5225
|
+
env: { ...options.env },
|
|
5226
|
+
run
|
|
5227
|
+
});
|
|
5228
|
+
let record = await readUpgradeRecord(home.directory);
|
|
5229
|
+
let service = record && record.phase !== "complete" ? await services.load(record.service) : await services.discover();
|
|
5230
|
+
if (!record || record.phase === "complete") {
|
|
5231
|
+
const source = await packages.inspect(service.command, service.cwd, service.env);
|
|
5232
|
+
options.progress("resolving", `Checking latest release (current ${source.version})`);
|
|
5233
|
+
const target = await packages.latest({
|
|
5234
|
+
run,
|
|
5235
|
+
env: service.env,
|
|
5236
|
+
cwd: source.root,
|
|
5237
|
+
nodePath: source.nodePath
|
|
5238
|
+
});
|
|
5239
|
+
requireStableVersion(target);
|
|
5240
|
+
if (!valid(source.version) || compare(source.version, "0.20.0") < 0) throw new Error("this Home requires the documented 0.20 migration before managed upgrades");
|
|
5241
|
+
if (compare(target, source.version) < 0) throw new Error("registry latest is older than the running release; refusing a downgrade");
|
|
5242
|
+
const observed = await services.inspect(service);
|
|
5243
|
+
if (!observed.running || !observed.pid || !sameCommand(observed.command, service.command)) throw new Error("the selected service is not running its configured Rivus command; resolve its state before upgrading");
|
|
5244
|
+
if (target === source.version) return {
|
|
5245
|
+
status: "current",
|
|
5246
|
+
version: target,
|
|
5247
|
+
previousVersion: source.version,
|
|
5248
|
+
home: home.directory,
|
|
5249
|
+
service: service.id,
|
|
5250
|
+
pid: observed.pid,
|
|
5251
|
+
executable: source.cliPath
|
|
5252
|
+
};
|
|
5253
|
+
record = {
|
|
5254
|
+
schemaVersion: 1,
|
|
5255
|
+
id: randomUUID(),
|
|
5256
|
+
home: home.directory,
|
|
5257
|
+
sourceVersion: source.version,
|
|
5258
|
+
targetVersion: target,
|
|
5259
|
+
sourceCommand: [...service.command],
|
|
5260
|
+
service: {
|
|
5261
|
+
kind: service.kind,
|
|
5262
|
+
id: service.id,
|
|
5263
|
+
definitionPath: service.definitionPath
|
|
5264
|
+
},
|
|
5265
|
+
phase: "preparing",
|
|
5266
|
+
createdAt: now().toISOString()
|
|
5267
|
+
};
|
|
5268
|
+
await writeUpgradeRecord(record);
|
|
5269
|
+
}
|
|
5270
|
+
const paths = upgradePaths(home.directory, record.id);
|
|
5271
|
+
const source = await packages.inspect(record.sourceCommand, service.cwd, service.env);
|
|
5272
|
+
if (source.version !== record.sourceVersion) throw new Error("the retained source release changed; preserve the journal and resolve it before continuing");
|
|
5273
|
+
requireStableVersion(record.targetVersion);
|
|
5274
|
+
const candidateCommand = [...record.sourceCommand];
|
|
5275
|
+
const candidateCli = `${paths.release}/node_modules/@rivus/agent/dist/cli.js`;
|
|
5276
|
+
candidateCommand[candidateCommand.length - 2] = candidateCli;
|
|
5277
|
+
const setPhase = async (phase) => {
|
|
5278
|
+
record = {
|
|
5279
|
+
...record,
|
|
5280
|
+
phase,
|
|
5281
|
+
...phase === "stopping" ? { startedAfter: now().toISOString() } : {}
|
|
5282
|
+
};
|
|
5283
|
+
await writeUpgradeRecord(record);
|
|
5284
|
+
options.progress(phase, `${record.sourceVersion} -> ${record.targetVersion}`);
|
|
5285
|
+
};
|
|
5286
|
+
const inspectExpected = async () => {
|
|
5287
|
+
const observed = await services.inspect(record.service);
|
|
5288
|
+
if (observed.running && !sameCommand(observed.command, record.sourceCommand) && !sameCommand(observed.command, candidateCommand)) throw new Error("the service is running an unexpected command; no further upgrade action was taken");
|
|
5289
|
+
return observed;
|
|
5290
|
+
};
|
|
5291
|
+
if (record.phase === "preparing") {
|
|
5292
|
+
const observed = await inspectExpected();
|
|
5293
|
+
if (!observed.running || !sameCommand(observed.command, record.sourceCommand)) throw new Error("the source service changed during preparation");
|
|
5294
|
+
options.progress("preparing", `Installing ${record.targetVersion} while the current service remains running`);
|
|
5295
|
+
await packages.prepare({
|
|
5296
|
+
source,
|
|
5297
|
+
version: record.targetVersion,
|
|
5298
|
+
directory: paths.release,
|
|
5299
|
+
home,
|
|
5300
|
+
service,
|
|
5301
|
+
run,
|
|
5302
|
+
...options.signal ? { signal: options.signal } : {}
|
|
5303
|
+
});
|
|
5304
|
+
await setPhase("prepared");
|
|
5305
|
+
}
|
|
5306
|
+
if ((await packages.inspect(candidateCommand, service.cwd, service.env)).version !== record.targetVersion) throw new Error("prepared release does not match the recorded target version");
|
|
5307
|
+
if (record.phase === "prepared") {
|
|
5308
|
+
const observed = await inspectExpected();
|
|
5309
|
+
if (!observed.running || !sameCommand(observed.command, record.sourceCommand)) throw new Error("the source service changed before cutover");
|
|
5310
|
+
await setPhase("stopping");
|
|
5311
|
+
}
|
|
5312
|
+
if (record.phase === "stopping") {
|
|
5313
|
+
const observed = await inspectExpected();
|
|
5314
|
+
if (observed.running) {
|
|
5315
|
+
if (!sameCommand(observed.command, record.sourceCommand)) throw new Error("candidate started before the stopped backup; preserve this operation for recovery");
|
|
5316
|
+
await services.stop(record.service);
|
|
5317
|
+
}
|
|
5318
|
+
if ((await inspectExpected()).running) throw new Error("the managed service has not stopped");
|
|
5319
|
+
await setPhase("stopped");
|
|
5320
|
+
}
|
|
5321
|
+
if (record.phase === "stopped") {
|
|
5322
|
+
if ((await inspectExpected()).running) throw new Error("the service restarted before backup; stop it before resuming this operation");
|
|
5323
|
+
await (options.backup ?? backUpUpgradeHome)({
|
|
5324
|
+
home: home.directory,
|
|
5325
|
+
directory: paths.backup,
|
|
5326
|
+
env: service.env,
|
|
5327
|
+
run,
|
|
5328
|
+
...options.signal ? { signal: options.signal } : {}
|
|
5329
|
+
});
|
|
5330
|
+
await setPhase("backed-up");
|
|
5331
|
+
}
|
|
5332
|
+
if (record.phase === "backed-up") {
|
|
5333
|
+
await (options.verifyBackup ?? verifyUpgradeBackup)({
|
|
5334
|
+
home: home.directory,
|
|
5335
|
+
directory: paths.backup,
|
|
5336
|
+
env: service.env,
|
|
5337
|
+
run
|
|
5338
|
+
});
|
|
5339
|
+
if ((await inspectExpected()).running) throw new Error("the service restarted before switching; no service definition was changed");
|
|
5340
|
+
await setPhase("switching");
|
|
5341
|
+
}
|
|
5342
|
+
if (record.phase === "switching") {
|
|
5343
|
+
const observed = await inspectExpected();
|
|
5344
|
+
if (observed.running && !sameCommand(observed.command, candidateCommand)) throw new Error("the old service restarted during switching");
|
|
5345
|
+
service = await services.load(record.service);
|
|
5346
|
+
if (!sameCommand(service.command, candidateCommand)) {
|
|
5347
|
+
if (!sameCommand(service.command, record.sourceCommand)) throw new Error("the service definition changed outside this upgrade");
|
|
5348
|
+
await services.switch(record.service, candidateCommand, paths.backup);
|
|
5349
|
+
}
|
|
5350
|
+
await setPhase("starting");
|
|
5351
|
+
}
|
|
5352
|
+
if (record.phase !== "starting") throw new Error(`unsupported recovery phase: ${record.phase}`);
|
|
5353
|
+
const observed = await inspectExpected();
|
|
5354
|
+
if (!observed.running) await services.start(record.service);
|
|
5355
|
+
else if (!sameCommand(observed.command, candidateCommand)) throw new Error("the source process is still running after the switch");
|
|
5356
|
+
const pid = await waitForCandidate(options, services, record, candidateCommand);
|
|
5357
|
+
await setPhase("complete");
|
|
5358
|
+
return {
|
|
5359
|
+
status: "upgraded",
|
|
5360
|
+
version: record.targetVersion,
|
|
5361
|
+
previousVersion: record.sourceVersion,
|
|
5362
|
+
home: home.directory,
|
|
5363
|
+
service: record.service.id,
|
|
5364
|
+
pid,
|
|
5365
|
+
executable: candidateCli,
|
|
5366
|
+
backup: paths.backup,
|
|
5367
|
+
operationId: record.id
|
|
5368
|
+
};
|
|
5369
|
+
}
|
|
5370
|
+
async function waitForCandidate(options, services, record, command) {
|
|
5371
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
5372
|
+
const deadline = now().getTime() + (options.startupTimeoutMs ?? 6e4);
|
|
5373
|
+
const wait = options.wait ?? ((ms) => setTimeout$1(ms, void 0, { signal: options.signal }));
|
|
5374
|
+
do {
|
|
5375
|
+
if (options.signal?.aborted) throw new Error("upgrade interrupted; rerun rivus upgrade to resume");
|
|
5376
|
+
const process = await services.inspect(record.service);
|
|
5377
|
+
const receipt = await (options.receipts ?? readRuntimeReceipt)(record.home);
|
|
5378
|
+
if (process.running && process.pid && sameCommand(process.command, command) && receipt?.pid === process.pid && receipt.version === record.targetVersion && receipt.executable === command[command.length - 2] && Date.parse(receipt.startedAt) >= Date.parse(record.startedAfter ?? record.createdAt)) {
|
|
5379
|
+
const confirmed = await services.inspect(record.service);
|
|
5380
|
+
if (confirmed.running && confirmed.pid === process.pid && sameCommand(confirmed.command, command)) return process.pid;
|
|
5381
|
+
}
|
|
5382
|
+
if (process.running && !sameCommand(process.command, command)) throw new Error("a different command is running after upgrade; preserve the backup and journal");
|
|
5383
|
+
await wait(500);
|
|
5384
|
+
} while (now().getTime() < deadline);
|
|
5385
|
+
throw new Error("new release did not become ready within the startup deadline; rerun rivus upgrade after resolving the service error");
|
|
5386
|
+
}
|
|
5387
|
+
function sameCommand(left, right) {
|
|
5388
|
+
return left.length === right.length && left.every((value, index) => value === right[index]);
|
|
5389
|
+
}
|
|
5390
|
+
function requireStableVersion(version) {
|
|
5391
|
+
if (!/^\d+\.\d+\.\d+$/.test(version) || !valid(version)) throw new Error("registry latest must be a stable release version");
|
|
5392
|
+
}
|
|
5393
|
+
//#endregion
|
|
5394
|
+
//#region src/adapters/cli/upgrade/upgrade-cli-protocol.ts
|
|
5395
|
+
const UPGRADE_USAGE = `Usage: rivus upgrade [--json]
|
|
5396
|
+
|
|
5397
|
+
Upgrade the selected Home's managed service to the latest stable npm release.
|
|
5398
|
+
Prepare and validate before stopping, retain the Home and backup, then verify startup.
|
|
5399
|
+
Rerun the same command to resume an interrupted upgrade at its recorded version.
|
|
5400
|
+
`;
|
|
5401
|
+
function parseUpgradeArguments(argv) {
|
|
5402
|
+
if (argv.includes("--help") || argv.includes("-h")) return { help: true };
|
|
5403
|
+
if (argv.length === 0) return { json: false };
|
|
5404
|
+
if (argv.length === 1 && argv[0] === "--json") return { json: true };
|
|
5405
|
+
return { error: "upgrade accepts only --json; it selects the latest stable release automatically" };
|
|
5406
|
+
}
|
|
5407
|
+
function renderUpgradeResult(result, json) {
|
|
5408
|
+
if (json) return `${JSON.stringify(result)}\n`;
|
|
5409
|
+
return `${result.status === "current" ? `Rivus ${result.version} is already current` : `Upgraded Rivus ${result.previousVersion} -> ${result.version}`}\nService: ${result.service} (PID ${result.pid})\n${result.executable ? `CLI: ${result.executable}\n` : ""}${result.backup ? `Backup: ${result.backup}\n` : ""}`;
|
|
5410
|
+
}
|
|
5411
|
+
//#endregion
|
|
3911
5412
|
//#region src/bootstrap/cli/rivus-cli.ts
|
|
3912
5413
|
function runRivusCli(options) {
|
|
3913
5414
|
const command = options.argv[0];
|
|
3914
5415
|
if (command === "setup") return runSetupCommand(options);
|
|
5416
|
+
if (command === "upgrade") return runUpgradeCommand(options);
|
|
3915
5417
|
if (command === "start") return runHomeDaemonCommand(options, "start", []);
|
|
3916
5418
|
if (command === "status") return runHomeDaemonCommand(options, "status", ["--status"]);
|
|
3917
5419
|
if (command === "check-config") return runHomeDaemonCommand(options, "check-config", ["--check-config"]);
|
|
@@ -3946,6 +5448,45 @@ function runRivusCli(options) {
|
|
|
3946
5448
|
env: withoutRivusHomeDeployment(options.env)
|
|
3947
5449
|
});
|
|
3948
5450
|
}
|
|
5451
|
+
function runUpgradeCommand(options) {
|
|
5452
|
+
const parsed = parseUpgradeArguments(options.argv.slice(1));
|
|
5453
|
+
if ("help" in parsed) return Effect.sync(() => {
|
|
5454
|
+
options.stdout.write(UPGRADE_USAGE);
|
|
5455
|
+
return 0;
|
|
5456
|
+
});
|
|
5457
|
+
if ("error" in parsed) return Effect.sync(() => {
|
|
5458
|
+
options.stderr.write(`${parsed.error}\n${UPGRADE_USAGE}`);
|
|
5459
|
+
return 1;
|
|
5460
|
+
});
|
|
5461
|
+
return Effect.gen(function* () {
|
|
5462
|
+
const directory = yield* resolveHomeDirectoryEffect(options);
|
|
5463
|
+
const home = yield* options.homeApi.load(directory);
|
|
5464
|
+
if (!options.upgradeHost) return yield* Effect.fail(/* @__PURE__ */ new Error("upgrade requires the Node process host"));
|
|
5465
|
+
const upgradeHost = options.upgradeHost;
|
|
5466
|
+
const result = yield* Effect.tryPromise({
|
|
5467
|
+
try: () => (options.upgradeRunner ?? upgradeHome)({
|
|
5468
|
+
...upgradeHost,
|
|
5469
|
+
home,
|
|
5470
|
+
userHome: options.homeDirectory,
|
|
5471
|
+
env: options.env,
|
|
5472
|
+
signal: abortOnInterruption(options.signalSource),
|
|
5473
|
+
progress: (phase, detail) => options.stderr.write(`[${phase}] ${detail}\n`)
|
|
5474
|
+
}),
|
|
5475
|
+
catch: (error) => error
|
|
5476
|
+
});
|
|
5477
|
+
options.stdout.write(renderUpgradeResult(result, parsed.json));
|
|
5478
|
+
return 0;
|
|
5479
|
+
}).pipe(Effect.catch((error) => Effect.sync(() => {
|
|
5480
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
5481
|
+
if (parsed.json) options.stdout.write(`${JSON.stringify({
|
|
5482
|
+
status: "failed",
|
|
5483
|
+
message,
|
|
5484
|
+
recovery: "Rerun rivus upgrade to resume the recorded operation after resolving this error."
|
|
5485
|
+
})}\n`);
|
|
5486
|
+
else options.stderr.write(`Upgrade failed: ${message}\nRerun rivus upgrade to resume after resolving this error.\n`);
|
|
5487
|
+
return 1;
|
|
5488
|
+
})));
|
|
5489
|
+
}
|
|
3949
5490
|
function resolveHomeRecoveryFileArguments(argv, command, cwd) {
|
|
3950
5491
|
if (command.type === "inspect") return argv;
|
|
3951
5492
|
const files = /* @__PURE__ */ new Map([["--recovery-note-file", resolve(cwd, command.noteFilePath)]]);
|
|
@@ -4056,7 +5597,9 @@ function runSetupCommand(options) {
|
|
|
4056
5597
|
return withOptionalDirectoryArgument(options, "setup", (argument) => resolveHomeDirectoryEffect(options, argument).pipe(Effect.flatMap((directory) => options.homeApi.setup(directory).pipe(Effect.tap(() => Effect.sync(() => options.stdout.write(renderRivusSetupSuccess(directory)))), Effect.as(0))), Effect.catch((error) => writeError(options, error))));
|
|
4057
5598
|
}
|
|
4058
5599
|
function runHomeDaemonCommand(options, command, daemonArgs) {
|
|
4059
|
-
|
|
5600
|
+
const commandArgs = options.argv.slice(1);
|
|
5601
|
+
const checkPlugins = command === "check-config" && commandArgs.length === 1 && commandArgs[0] === "--load-plugins";
|
|
5602
|
+
if (command !== "recovery" && !checkPlugins && hasRivusHomeCommandArguments(commandArgs)) return Effect.sync(() => {
|
|
4060
5603
|
options.stderr.write(renderRivusHomeCommandUsage(command));
|
|
4061
5604
|
return 1;
|
|
4062
5605
|
});
|
|
@@ -4077,7 +5620,22 @@ function runHomeDaemonCommand(options, command, daemonArgs) {
|
|
|
4077
5620
|
RIVUS_HOME: home.directory,
|
|
4078
5621
|
[RIVUS_HOME_DEPLOYMENT_ENV]: home.directory
|
|
4079
5622
|
},
|
|
4080
|
-
pluginPackageManifestPath: options.pluginPackageManifestPath ?? gatewayPackageManifestPath
|
|
5623
|
+
pluginPackageManifestPath: options.pluginPackageManifestPath ?? gatewayPackageManifestPath,
|
|
5624
|
+
...checkPlugins ? { checkPlugins: true } : {},
|
|
5625
|
+
...command === "start" ? { lifecycle: {
|
|
5626
|
+
started: async () => {
|
|
5627
|
+
if (!options.runtimeProcess) throw new Error("Home start requires the runtime process identity");
|
|
5628
|
+
await writeRuntimeReceipt({
|
|
5629
|
+
...options.runtimeProcess,
|
|
5630
|
+
home: home.directory,
|
|
5631
|
+
version: RIVUS_RELEASE_DESCRIPTOR.version,
|
|
5632
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
5633
|
+
});
|
|
5634
|
+
},
|
|
5635
|
+
stopped: async () => {
|
|
5636
|
+
if (options.runtimeProcess) await clearRuntimeReceipt(home.directory, options.runtimeProcess.pid);
|
|
5637
|
+
}
|
|
5638
|
+
} } : {}
|
|
4081
5639
|
})), Effect.catch((error) => writeError(options, error)));
|
|
4082
5640
|
}
|
|
4083
5641
|
function runInitCommand(options) {
|
|
@@ -4168,6 +5726,23 @@ function runRivusNodeEntrypoint(options) {
|
|
|
4168
5726
|
loadBootstrap: (specifier) => import(toImportSpecifier(specifier)),
|
|
4169
5727
|
nodeExecutable: process.execPath,
|
|
4170
5728
|
nodeVersion: process.versions.node,
|
|
5729
|
+
upgradeHost: {
|
|
5730
|
+
pid: process.pid,
|
|
5731
|
+
platform: process.platform,
|
|
5732
|
+
isProcessAlive: (pid) => {
|
|
5733
|
+
try {
|
|
5734
|
+
process.kill(pid, 0);
|
|
5735
|
+
return true;
|
|
5736
|
+
} catch (error) {
|
|
5737
|
+
if (Schema.is(Schema.Struct({ code: Schema.Literal("ESRCH") }))(error)) return false;
|
|
5738
|
+
throw new Error("could not determine whether the existing upgrader is still running", { cause: error });
|
|
5739
|
+
}
|
|
5740
|
+
}
|
|
5741
|
+
},
|
|
5742
|
+
runtimeProcess: {
|
|
5743
|
+
pid: process.pid,
|
|
5744
|
+
executable: resolve(options.cwd, process.argv[1] ?? "")
|
|
5745
|
+
},
|
|
4171
5746
|
signalSource: options.signalSource,
|
|
4172
5747
|
stderr: options.stderr,
|
|
4173
5748
|
stdout: options.stdout
|