@rivus/gateway 0.20.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,23 @@
1
- import { A as resolveFeishuEndpointCredentials, C as gatewayTemplateDirectory, D as parseRivusModelManagementEnabled, F as narrowBackgroundSessionDefinition, I as deepFreeze, M as validateRivusDeploymentManifest, N as validateRivusProjectSpaceDeployment, P as createBackgroundSessionToolContracts, T as resolveAcpRuntimeEnvironment, _ as readRivusAudioInstalledRelease, a as invokeRuntimeControl, d as renderRivusModelCliArgumentError, f as renderRivusModelCliHelp, g as installRivusAudioTranscriber, i as disposeRuntimeCacheEntries, j as InvalidRivusProjectSpace, 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 } from "./rivus-home-deployment-env.js";
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* loadRivusDeploymentManifest(parsed.manifestPath);
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, daemon),
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,1529 @@ 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
+ "xpcproxy",
4103
+ "spawn scheduled",
4104
+ "spawning",
4105
+ "throttled"
4106
+ ];
4107
+ if (!state || ![...stoppedStates, ...pendingStates].includes(state)) throw new Error("launchctl print returned an unrecognized service state.");
4108
+ const pid = pidText ? Number(pidText) : void 0;
4109
+ const running = Boolean(pid && pid > 0) || pendingStates.includes(state);
4110
+ const block = /^\s*arguments = \{\r?\n([\s\S]*?)^\s*\}\s*$/mu.exec(result.stdout)?.[1];
4111
+ let command = service.command;
4112
+ if (pid || state === "running") {
4113
+ if (!pid || !block) throw new Error("Cannot confirm the running LaunchAgent PID and command.");
4114
+ command = await serviceCommand(block.split(/\r?\n/u).map((line) => line.trim()).filter(Boolean), service.env, true);
4115
+ }
4116
+ return {
4117
+ loaded: true,
4118
+ running,
4119
+ ...pid ? { pid } : {},
4120
+ command
4121
+ };
4122
+ }
4123
+ return {
4124
+ async discover() {
4125
+ let names;
4126
+ try {
4127
+ names = await readdir(directory);
4128
+ } catch (error) {
4129
+ if (!hasServiceFileErrorCode(error, "ENOENT")) throw error;
4130
+ names = [];
4131
+ }
4132
+ const matches = [];
4133
+ for (const name of names.filter((entry) => entry.endsWith(".plist")).sort()) {
4134
+ const path = join(directory, name);
4135
+ const definition = await readDefinition(path);
4136
+ const environment = definition.EnvironmentVariables;
4137
+ if (environment && await matchesHome(environment.RIVUS_HOME, context.home)) matches.push(await fromDefinition(path, definition));
4138
+ }
4139
+ if (matches.length !== 1) throw new Error(`Expected exactly one LaunchAgent for this Home; found ${matches.length}.`);
4140
+ return matches[0];
4141
+ },
4142
+ load,
4143
+ async inspect(identity) {
4144
+ const { loaded: _loaded, ...status } = await query(identity);
4145
+ return status;
4146
+ },
4147
+ async stop(identity) {
4148
+ if ((await query(identity)).loaded) await requireServiceTool(context, "/bin/launchctl", ["bootout", `${domain}/${identity.id}`]);
4149
+ await waitForServiceStop(context, () => query(identity));
4150
+ },
4151
+ async switch(identity, command, backupDirectory) {
4152
+ const service = await load(identity);
4153
+ const candidate = await serviceCommand(command, service.env);
4154
+ const definition = await readDefinition(identity.definitionPath);
4155
+ if (definition.Program !== void 0 && definition.Program !== candidate[0]) throw new Error("LaunchAgent Program would override the candidate executable; use ProgramArguments without Program.");
4156
+ await snapshotFile(identity.definitionPath, join(backupDirectory, "service.plist"));
4157
+ if (sameCommand$1(service.command, candidate)) return;
4158
+ if ((await query(identity)).loaded) throw new Error("LaunchAgent is still loaded; stop it before switching its definition.");
4159
+ const temporary = `${identity.definitionPath}.${randomUUID()}.tmp`;
4160
+ try {
4161
+ await copyFile(identity.definitionPath, temporary);
4162
+ await requireServiceTool(context, "/usr/bin/plutil", [
4163
+ "-replace",
4164
+ "ProgramArguments",
4165
+ "-json",
4166
+ JSON.stringify(candidate),
4167
+ temporary
4168
+ ]);
4169
+ await rename(temporary, identity.definitionPath);
4170
+ } finally {
4171
+ await rm(temporary, { force: true });
4172
+ }
4173
+ },
4174
+ async start(identity) {
4175
+ const status = await query(identity);
4176
+ if (status.running) return;
4177
+ if (status.loaded) await requireServiceTool(context, "/bin/launchctl", ["bootout", `${domain}/${identity.id}`]);
4178
+ await requireServiceTool(context, "/bin/launchctl", [
4179
+ "bootstrap",
4180
+ domain,
4181
+ identity.definitionPath
4182
+ ]);
4183
+ }
4184
+ };
4185
+ }
4186
+ function failUid() {
4187
+ throw new Error("Cannot determine the current user's launchd domain.");
4188
+ }
4189
+ //#endregion
4190
+ //#region src/adapters/deployment/upgrade/service-systemd.ts
4191
+ const bus = "org.freedesktop.systemd1";
4192
+ const managerPath = "/org/freedesktop/systemd1";
4193
+ const stringsSchema = Schema.Array(Schema.String);
4194
+ const environmentFilesSchema = Schema.Array(Schema.Tuple([Schema.String, Schema.Boolean]));
4195
+ const execStartSchema = Schema.Array(Schema.Tuple([
4196
+ Schema.String,
4197
+ stringsSchema,
4198
+ stringsSchema,
4199
+ Schema.Number,
4200
+ Schema.Number,
4201
+ Schema.Number,
4202
+ Schema.Number,
4203
+ Schema.Number,
4204
+ Schema.Number,
4205
+ Schema.Number
4206
+ ]));
4207
+ const stringsPropertySchema = Schema.Struct({
4208
+ type: Schema.Literal("as"),
4209
+ data: stringsSchema
4210
+ });
4211
+ const environmentFilesPropertySchema = Schema.Struct({
4212
+ type: Schema.Literal("a(sb)"),
4213
+ data: environmentFilesSchema
4214
+ });
4215
+ const execStartPropertySchema = Schema.Struct({
4216
+ type: Schema.Literal("a(sasasttttuii)"),
4217
+ data: execStartSchema
4218
+ });
4219
+ const unitPathSchema = Schema.Struct({
4220
+ type: Schema.Literal("o"),
4221
+ data: Schema.Tuple([Schema.String])
4222
+ });
4223
+ const nonEmpty = Schema.String.check(Schema.isNonEmpty());
4224
+ const unitPropertiesSchema = Schema.Struct({
4225
+ Id: nonEmpty,
4226
+ LoadState: nonEmpty,
4227
+ ActiveState: nonEmpty,
4228
+ SubState: nonEmpty,
4229
+ MainPID: Schema.String.check(Schema.isPattern(/^\d+$/u)),
4230
+ WorkingDirectory: Schema.optional(Schema.String),
4231
+ FragmentPath: Schema.optional(Schema.String)
4232
+ });
4233
+ function createSystemdServiceManager(context) {
4234
+ async function busRequest(args, schema) {
4235
+ const output = await requireServiceTool(context, "busctl", [
4236
+ "--user",
4237
+ "--json=short",
4238
+ ...args
4239
+ ]);
4240
+ try {
4241
+ return Schema.decodeUnknownSync(schema)(JSON.parse(output));
4242
+ } catch {
4243
+ throw new Error("busctl returned invalid structured service data.");
4244
+ }
4245
+ }
4246
+ async function property(path, owner, name, schema) {
4247
+ return busRequest([
4248
+ "get-property",
4249
+ bus,
4250
+ path,
4251
+ `${bus}.${owner}`,
4252
+ name
4253
+ ], schema);
4254
+ }
4255
+ async function unitPath(id) {
4256
+ const { data } = await busRequest([
4257
+ "call",
4258
+ bus,
4259
+ managerPath,
4260
+ `${bus}.Manager`,
4261
+ "LoadUnit",
4262
+ "s",
4263
+ id
4264
+ ], unitPathSchema);
4265
+ if (!data[0].startsWith(`${managerPath}/unit/`)) throw new Error("Cannot identify the systemd user service object.");
4266
+ return data[0];
4267
+ }
4268
+ async function show(id) {
4269
+ if (!/^[a-zA-Z0-9_@.\\:-]+\.service$/u.test(id) || id.startsWith("-")) throw new Error("Unsupported systemd service identity.");
4270
+ const output = await requireServiceTool(context, "systemctl", [
4271
+ "--user",
4272
+ "show",
4273
+ id,
4274
+ "--no-pager",
4275
+ "--property=Id,LoadState,ActiveState,SubState,MainPID,WorkingDirectory,FragmentPath,Environment,ExecStart"
4276
+ ]);
4277
+ const values = {};
4278
+ for (const line of output.split(/\r?\n/u)) {
4279
+ const separator = line.indexOf("=");
4280
+ if (separator > 0) values[line.slice(0, separator)] = line.slice(separator + 1);
4281
+ }
4282
+ try {
4283
+ return Schema.decodeUnknownSync(unitPropertiesSchema)(values);
4284
+ } catch {
4285
+ throw new Error("systemctl show could not confirm the loaded service state.");
4286
+ }
4287
+ }
4288
+ async function readService(id) {
4289
+ if (context.env.XDG_CONFIG_HOME !== void 0 && !isAbsolute(context.env.XDG_CONFIG_HOME)) throw new Error("systemd XDG_CONFIG_HOME must be absolute.");
4290
+ const values = await show(id);
4291
+ if (values.LoadState !== "loaded") throw new Error("systemctl show could not confirm the loaded service state.");
4292
+ const path = await unitPath(id);
4293
+ const configured = environment((await property(path, "Service", "Environment", stringsPropertySchema)).data);
4294
+ const inherited = environment((await property(managerPath, "Manager", "Environment", stringsPropertySchema)).data);
4295
+ 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.");
4296
+ const { data: files } = await property(path, "Service", "EnvironmentFiles", environmentFilesPropertySchema);
4297
+ const { data: unset } = await property(path, "Service", "UnsetEnvironment", stringsPropertySchema);
4298
+ 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.");
4299
+ const { data: commands } = await property(path, "Service", "ExecStartEx", execStartPropertySchema);
4300
+ if (commands.length !== 1) throw new Error("Managed systemd service needs exactly one ExecStart command.");
4301
+ const entry = commands[0];
4302
+ if (entry[2].some((flag) => flag !== "no-env-expand") || entry[0] !== entry[1][0]) throw new Error("Unsupported systemd ExecStart flags or executable wrapper.");
4303
+ 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.");
4304
+ if (!values.FragmentPath || !isAbsolute(values.FragmentPath) || !values.WorkingDirectory || !isAbsolute(values.WorkingDirectory)) throw new Error("Managed systemd service needs an absolute FragmentPath and WorkingDirectory.");
4305
+ const env = {
4306
+ ...inherited,
4307
+ ...configured
4308
+ };
4309
+ const service = {
4310
+ kind: "systemd",
4311
+ id: values.Id,
4312
+ definitionPath: values.FragmentPath,
4313
+ command: await serviceCommand(entry[1], env),
4314
+ cwd: values.WorkingDirectory,
4315
+ env
4316
+ };
4317
+ const pid = Number(values.MainPID);
4318
+ return {
4319
+ service,
4320
+ path,
4321
+ running: pid > 0 || !["inactive", "failed"].includes(values.ActiveState),
4322
+ ...pid > 0 ? { pid } : {}
4323
+ };
4324
+ }
4325
+ async function loadAndQuery(identity) {
4326
+ if (identity.kind !== "systemd") throw new Error("Invalid systemd service identity.");
4327
+ const status = await readService(identity.id);
4328
+ if (status.service.id !== identity.id || status.service.definitionPath !== identity.definitionPath) throw new Error("systemd service identity changed; refusing to operate on another definition.");
4329
+ return status;
4330
+ }
4331
+ async function inspect(identity) {
4332
+ const status = await loadAndQuery(identity);
4333
+ let command = status.service.command;
4334
+ if (status.pid) try {
4335
+ command = await serviceCommand(await context.readProcessCommand(status.pid), status.service.env, true);
4336
+ } catch {
4337
+ const observed = await loadAndQuery(identity);
4338
+ if (!observed.running) return {
4339
+ running: false,
4340
+ command: observed.service.command
4341
+ };
4342
+ throw new Error("Cannot confirm the running systemd service command; its process state is unknown.");
4343
+ }
4344
+ return {
4345
+ running: status.running,
4346
+ ...status.pid ? { pid: status.pid } : {},
4347
+ command
4348
+ };
4349
+ }
4350
+ return {
4351
+ async discover() {
4352
+ const output = await requireServiceTool(context, "systemctl", [
4353
+ "--user",
4354
+ "list-unit-files",
4355
+ "--type=service",
4356
+ "--no-legend",
4357
+ "--no-pager"
4358
+ ]);
4359
+ const matches = /* @__PURE__ */ new Map();
4360
+ for (const line of output.split(/\r?\n/u).filter((value) => value.trim())) {
4361
+ const id = line.trim().split(/\s+/u)[0];
4362
+ if (id.endsWith("@.service")) continue;
4363
+ const values = await show(id);
4364
+ if (values.LoadState !== "loaded") {
4365
+ if ([
4366
+ "masked",
4367
+ "not-found",
4368
+ "stub"
4369
+ ].includes(values.LoadState) && ["inactive", "failed"].includes(values.ActiveState) && values.MainPID === "0") continue;
4370
+ throw new Error("systemctl show could not confirm the loaded service state.");
4371
+ }
4372
+ if (await matchesHome(environment((await property(await unitPath(id), "Service", "Environment", stringsPropertySchema)).data).RIVUS_HOME, context.home)) {
4373
+ const { service } = await readService(values.Id);
4374
+ matches.set(service.id, service);
4375
+ }
4376
+ }
4377
+ if (matches.size !== 1) throw new Error(`Expected exactly one user service with direct RIVUS_HOME Environment for this Home; found ${matches.size}.`);
4378
+ return matches.values().next().value;
4379
+ },
4380
+ async load(identity) {
4381
+ return (await loadAndQuery(identity)).service;
4382
+ },
4383
+ inspect,
4384
+ async stop(identity) {
4385
+ if ((await inspect(identity)).running) await requireServiceTool(context, "systemctl", [
4386
+ "--user",
4387
+ "stop",
4388
+ identity.id
4389
+ ]);
4390
+ await waitForServiceStop(context, () => inspect(identity));
4391
+ },
4392
+ async switch(identity, command, backupDirectory) {
4393
+ const status = await loadAndQuery(identity);
4394
+ const candidate = await serviceCommand(command, status.service.env);
4395
+ await snapshotFile(identity.definitionPath, join(backupDirectory, "service.unit"));
4396
+ const manifestPath = join(backupDirectory, "service.drop-ins.json");
4397
+ if (await readFile(manifestPath, "utf8").catch((error) => {
4398
+ if (!hasServiceFileErrorCode(error, "ENOENT")) throw error;
4399
+ }) === void 0) {
4400
+ const { data: dropIns } = await property(status.path, "Unit", "DropInPaths", stringsPropertySchema);
4401
+ if (!dropIns.every((value) => isAbsolute(value))) throw new Error("Cannot confirm existing systemd drop-in definitions.");
4402
+ const manifest = [];
4403
+ for (const [index, path] of dropIns.entries()) {
4404
+ const backup = join("service.drop-ins", `${index}.conf`);
4405
+ await snapshotFile(path, join(backupDirectory, backup));
4406
+ manifest.push({
4407
+ path,
4408
+ backup
4409
+ });
4410
+ }
4411
+ await writeAtomicTextFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, {
4412
+ mode: 384,
4413
+ durable: true
4414
+ });
4415
+ }
4416
+ if (sameCommand$1(status.service.command, candidate)) return;
4417
+ if (status.running) throw new Error("User service is still running; stop it before switching its definition.");
4418
+ const config = context.env.XDG_CONFIG_HOME ?? join(context.userHome, ".config");
4419
+ if (!isAbsolute(config)) throw new Error("systemd XDG_CONFIG_HOME must be absolute.");
4420
+ const dropInPath = join(config, "systemd", "user", `${identity.id}.d`, "zz-rivus-upgrade.conf");
4421
+ const absentMarker = join(backupDirectory, "service.upgrade-drop-in.absent");
4422
+ if (await readFile(absentMarker, "utf8").catch((error) => {
4423
+ if (!hasServiceFileErrorCode(error, "ENOENT")) throw error;
4424
+ }) === void 0) try {
4425
+ await snapshotFile(dropInPath, join(backupDirectory, "service.upgrade-drop-in.conf"));
4426
+ } catch (error) {
4427
+ if (!hasServiceFileErrorCode(error, "ENOENT")) throw error;
4428
+ await writeAtomicTextFile(absentMarker, "", {
4429
+ mode: 384,
4430
+ durable: true
4431
+ });
4432
+ }
4433
+ const content = `[Service]\nExecStart=\nExecStart=:${candidate.map(quoteSystemdArgument).join(" ")}\n`;
4434
+ if (await readFile(dropInPath, "utf8").catch((error) => {
4435
+ if (!hasServiceFileErrorCode(error, "ENOENT")) throw error;
4436
+ }) !== content) await writeAtomicTextFile(dropInPath, content, {
4437
+ mode: 384,
4438
+ durable: true
4439
+ });
4440
+ await requireServiceTool(context, "systemctl", ["--user", "daemon-reload"]);
4441
+ 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.");
4442
+ },
4443
+ async start(identity) {
4444
+ if (!(await inspect(identity)).running) await requireServiceTool(context, "systemctl", [
4445
+ "--user",
4446
+ "start",
4447
+ identity.id
4448
+ ]);
4449
+ }
4450
+ };
4451
+ }
4452
+ function environment(value) {
4453
+ const result = {};
4454
+ for (const entry of value) {
4455
+ const separator = entry.indexOf("=");
4456
+ if (separator < 1) throw new Error("Invalid systemd Environment assignment.");
4457
+ result[entry.slice(0, separator)] = entry.slice(separator + 1);
4458
+ }
4459
+ return result;
4460
+ }
4461
+ function quoteSystemdArgument(argument) {
4462
+ return `"${argument.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"").replaceAll("%", "%%")}"`;
4463
+ }
4464
+ //#endregion
4465
+ //#region src/adapters/deployment/upgrade/service.ts
4466
+ const agentPackageSchema = Schema.Struct({
4467
+ name: Schema.Literal("@rivus/agent"),
4468
+ bin: Schema.Union([Schema.String, Schema.Struct({ rivus: Schema.String })])
4469
+ });
4470
+ const isFileError = Schema.is(Schema.Struct({ code: Schema.String }));
4471
+ function createServiceManager(options) {
4472
+ const context = {
4473
+ ...options,
4474
+ run: options.run ?? runCommand,
4475
+ timeoutMs: options.timeoutMs ?? 3e4,
4476
+ pollIntervalMs: options.pollIntervalMs ?? 100,
4477
+ readProcessCommand: options.readProcessCommand ?? (async (pid) => {
4478
+ return (await readFile(`/proc/${pid}/cmdline`, "utf8")).split("\0").filter(Boolean);
4479
+ })
4480
+ };
4481
+ if (options.platform === "darwin") return createLaunchdServiceManager(context);
4482
+ if (options.platform === "linux") return createSystemdServiceManager(context);
4483
+ throw new Error("Managed upgrade supports only macOS LaunchAgents and Linux user services.");
4484
+ }
4485
+ async function serviceCommand(command, env, runningProcess = false) {
4486
+ if (command.some((argument) => !argument || /[\r\n\0]/u.test(argument))) throw new Error("Unsupported service command arguments.");
4487
+ let normalized = [...command];
4488
+ if (runningProcess && (normalized[0] === "node" || normalized[0] === "nodejs")) normalized[0] = await configuredNode(env, normalized[0]);
4489
+ 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.");
4490
+ if (!isNodeExecutable(normalized[0])) {
4491
+ if (normalized.length !== 2) throw new Error("Unsupported service wrapper; invoke Node and the Rivus CLI directly.");
4492
+ const script = await realpath(normalized[0]);
4493
+ const shebang = (await readFile(script, "utf8")).split("\n", 1)[0];
4494
+ let node;
4495
+ if (shebang === "#!/usr/bin/env node") node = await configuredNode(env, "node");
4496
+ else if (shebang?.startsWith("#!/") && isNodeExecutable(shebang.slice(2))) node = shebang.slice(2);
4497
+ if (!node) throw new Error("Cannot determine the service's Node executable from its shebang and configured PATH.");
4498
+ normalized = [
4499
+ node,
4500
+ script,
4501
+ "start"
4502
+ ];
4503
+ }
4504
+ const script = normalized.at(-2);
4505
+ if (!script || !isAbsolute(script)) throw new Error("Managed service needs an absolute Rivus CLI script path.");
4506
+ validateNodeFlags(normalized.slice(1, -2));
4507
+ await access(normalized[0], constants$1.X_OK);
4508
+ const actualScript = await realpath(script);
4509
+ const packageDirectory = dirname(dirname(actualScript));
4510
+ let manifest;
4511
+ try {
4512
+ manifest = Schema.decodeUnknownSync(agentPackageSchema)(JSON.parse(await readFile(join(packageDirectory, "package.json"), "utf8")));
4513
+ } catch {
4514
+ throw new Error("Cannot identify the managed Rivus CLI package; invoke the installed @rivus/agent bin directly.");
4515
+ }
4516
+ const bin = typeof manifest.bin === "string" ? manifest.bin : manifest.bin.rivus;
4517
+ if (await realpath(resolve(packageDirectory, bin)) !== actualScript) throw new Error("Managed service executable does not match the @rivus/agent rivus bin.");
4518
+ normalized[normalized.length - 2] = actualScript;
4519
+ return normalized;
4520
+ }
4521
+ async function configuredNode(env, name) {
4522
+ for (const directory of env.PATH?.split(":") ?? []) {
4523
+ if (!isAbsolute(directory)) continue;
4524
+ const candidate = join(directory, name);
4525
+ try {
4526
+ await access(candidate, constants$1.X_OK);
4527
+ return candidate;
4528
+ } catch (error) {
4529
+ if (!hasServiceFileErrorCode(error, "ENOENT") && !hasServiceFileErrorCode(error, "EACCES")) throw error;
4530
+ }
4531
+ }
4532
+ throw new Error("Cannot determine the service's Node executable from its configured PATH.");
4533
+ }
4534
+ function isNodeExecutable(path) {
4535
+ return isAbsolute(path) && /^(?:node|nodejs)(?:\.exe)?$/u.test(basename(path));
4536
+ }
4537
+ function validateNodeFlags(flags) {
4538
+ const withValue = /* @__PURE__ */ new Set([
4539
+ "--env-file",
4540
+ "--env-file-if-exists",
4541
+ "--require",
4542
+ "-r",
4543
+ "--import",
4544
+ "--loader",
4545
+ "--experimental-loader",
4546
+ "--conditions",
4547
+ "-C"
4548
+ ]);
4549
+ for (let index = 0; index < flags.length; index += 1) {
4550
+ const flag = flags[index];
4551
+ if (withValue.has(flag)) {
4552
+ if (!flags[index + 1]) throw new Error("A service Node flag is missing its value.");
4553
+ index += 1;
4554
+ } else if (flag.includes("=") && withValue.has(flag.slice(0, flag.indexOf("=")))) {
4555
+ if (!flag.slice(flag.indexOf("=") + 1)) throw new Error("A service Node flag is missing its value.");
4556
+ } 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.");
4557
+ }
4558
+ }
4559
+ async function matchesHome(value, home) {
4560
+ if (!value || !isAbsolute(value)) return false;
4561
+ try {
4562
+ return await realpath(value) === await realpath(home);
4563
+ } catch (error) {
4564
+ if (hasServiceFileErrorCode(error, "ENOENT")) return false;
4565
+ throw error;
4566
+ }
4567
+ }
4568
+ function sameCommand$1(left, right) {
4569
+ return left.length === right.length && left.every((value, index) => value === right[index]);
4570
+ }
4571
+ async function executeServiceTool(context, command, args) {
4572
+ try {
4573
+ return await context.run({
4574
+ command,
4575
+ args,
4576
+ cwd: context.userHome,
4577
+ env: context.env,
4578
+ timeoutMs: context.timeoutMs
4579
+ });
4580
+ } catch {
4581
+ throw new Error(`Cannot execute ${basename(command)} for managed service; check its installation and user permissions.`);
4582
+ }
4583
+ }
4584
+ async function requireServiceTool(context, command, args) {
4585
+ const result = await executeServiceTool(context, command, args);
4586
+ if (result.exitCode !== 0) throw new Error(`${basename(command)} ${args.find((argument) => !argument.startsWith("-")) ?? "query"} failed for managed service.`);
4587
+ return result.stdout;
4588
+ }
4589
+ async function waitForServiceStop(context, inspect) {
4590
+ const deadline = Date.now() + context.timeoutMs;
4591
+ while ((await inspect()).running) {
4592
+ if (Date.now() >= deadline) throw new Error("Managed service did not stop before the timeout; no definition was changed.");
4593
+ await setTimeout$1(context.pollIntervalMs);
4594
+ }
4595
+ }
4596
+ async function snapshotFile(source, destination) {
4597
+ await mkdir(dirname(destination), {
4598
+ recursive: true,
4599
+ mode: 448
4600
+ });
4601
+ const temporary = `${destination}.${randomUUID()}.tmp`;
4602
+ try {
4603
+ await writeFile(temporary, await readFile(source), {
4604
+ flag: "wx",
4605
+ mode: 384,
4606
+ flush: true
4607
+ });
4608
+ await link(temporary, destination);
4609
+ const directory = await open(dirname(destination), "r");
4610
+ try {
4611
+ await directory.sync();
4612
+ } finally {
4613
+ await directory.close();
4614
+ }
4615
+ } catch (error) {
4616
+ if (!hasServiceFileErrorCode(error, "EEXIST")) throw error;
4617
+ } finally {
4618
+ await rm(temporary, { force: true });
4619
+ }
4620
+ }
4621
+ function hasServiceFileErrorCode(error, code) {
4622
+ return isFileError(error) && error.code === code;
4623
+ }
4624
+ //#endregion
4625
+ //#region src/adapters/deployment/upgrade/package-command.ts
4626
+ async function resolveServiceNode(command, cwd, env) {
4627
+ const candidates = isAbsolute(command) || command.includes("/") ? [resolve(cwd, command)] : (env.PATH ?? "").split(delimiter).filter(Boolean).map((directory) => resolve(cwd, directory, command));
4628
+ for (const candidate of candidates) try {
4629
+ await access(candidate, constants.X_OK);
4630
+ return await realpath(candidate);
4631
+ } catch {}
4632
+ throw new Error("The managed service Node executable is unavailable");
4633
+ }
4634
+ async function npmInvocation(nodePath) {
4635
+ for (const candidate of [join(dirname(nodePath), "npm"), resolve(dirname(nodePath), "../lib/node_modules/npm/bin/npm-cli.js")]) try {
4636
+ await access(candidate, constants.R_OK);
4637
+ return [await realpath(candidate)];
4638
+ } catch {}
4639
+ throw new Error("npm is unavailable beside the managed service Node; install npm for that Node distribution");
4640
+ }
4641
+ async function checkedPackageCommand(run, request, phase, diagnosticsPath) {
4642
+ let result;
4643
+ try {
4644
+ result = await run(request);
4645
+ } catch {
4646
+ throw new Error(`${phase} could not complete; the service has not been stopped`);
4647
+ }
4648
+ if (result.exitCode !== 0) {
4649
+ if (diagnosticsPath) {
4650
+ await writeFile(diagnosticsPath, `${result.stdout}\n${result.stderr}`, { mode: 384 });
4651
+ await chmod(diagnosticsPath, 384);
4652
+ }
4653
+ throw new Error(`${phase} failed (exit ${result.exitCode ?? "signal"}); the service has not been stopped${diagnosticsPath ? `; private diagnostics: ${diagnosticsPath}` : ""}`);
4654
+ }
4655
+ return result;
4656
+ }
4657
+ function installerEnvironment(nodePath, env) {
4658
+ return {
4659
+ ...env,
4660
+ PATH: [dirname(nodePath), env.PATH].filter(Boolean).join(delimiter)
4661
+ };
4662
+ }
4663
+ function packedArtifactPath(stdout, directory) {
4664
+ try {
4665
+ const packed = Schema.decodeUnknownSync(Schema.Array(Schema.Struct({ filename: Schema.String })))(JSON.parse(stdout));
4666
+ if (packed.length !== 1 || !packed[0] || basename(packed[0].filename) !== packed[0].filename) throw new Error("invalid artifact");
4667
+ return join(directory, packed[0].filename);
4668
+ } catch {
4669
+ throw new Error("Package preparation returned an invalid artifact");
4670
+ }
4671
+ }
4672
+ //#endregion
4673
+ //#region src/adapters/deployment/upgrade/package-policy.ts
4674
+ const stringMap = Schema.Record(Schema.String, Schema.String);
4675
+ const policySchema = Schema.Struct({
4676
+ schemaVersion: Schema.Literal(1),
4677
+ stateCompatibility: Schema.Literal("rivus-home-0.20"),
4678
+ minimumSourceVersion: Schema.String,
4679
+ pnpmVersion: Schema.String,
4680
+ overrides: stringMap,
4681
+ allowBuilds: Schema.Record(Schema.String, Schema.Boolean)
4682
+ });
4683
+ async function readInstallationPolicy(directory = gatewayPackageDirectory) {
4684
+ return parseInstallationPolicy(await readFile(join(directory, "assets/installation-policy.json"), "utf8").catch(() => ""));
4685
+ }
4686
+ async function fetchInstallationPolicy(input) {
4687
+ const directory = join(input.directory, "policy");
4688
+ await mkdir(directory, {
4689
+ mode: 448,
4690
+ recursive: true
4691
+ });
4692
+ const artifact = packedArtifactPath((await checkedPackageCommand(input.run, {
4693
+ ...input.npm,
4694
+ args: [
4695
+ ...input.npm.args,
4696
+ "pack",
4697
+ `@rivus/gateway@${input.version}`,
4698
+ "--ignore-scripts",
4699
+ "--pack-destination",
4700
+ directory,
4701
+ "--json"
4702
+ ]
4703
+ }, "Target installation policy download", join(input.directory, "policy-download.log"))).stdout, directory);
4704
+ return parseInstallationPolicy((await checkedPackageCommand(input.run, {
4705
+ ...input.npm,
4706
+ command: "/usr/bin/tar",
4707
+ args: [
4708
+ "-xOf",
4709
+ artifact,
4710
+ "package/assets/installation-policy.json"
4711
+ ],
4712
+ timeoutMs: 3e4
4713
+ }, "Target installation policy extraction", join(input.directory, "policy-extraction.log"))).stdout);
4714
+ }
4715
+ function parseInstallationPolicy(text) {
4716
+ try {
4717
+ const policy = Schema.decodeUnknownSync(policySchema)(JSON.parse(text));
4718
+ if (valid(policy.minimumSourceVersion) !== policy.minimumSourceVersion || valid(policy.pnpmVersion) !== policy.pnpmVersion) throw new Error("invalid version");
4719
+ for (const floor of Object.values(policy.overrides)) if (!valid(floor)) throw new Error("invalid security floor");
4720
+ return policy;
4721
+ } catch {
4722
+ throw new Error("Release installation policy is missing, invalid or requires an unsupported Home migration");
4723
+ }
4724
+ }
4725
+ function assertSourceCompatibility(policy, sourceVersion) {
4726
+ 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`);
4727
+ }
4728
+ /** Raise older reviewed pins while keeping consumer overrides that already require a newer dependency. */
4729
+ function mergeInstallationOverrides(source, policy) {
4730
+ const merged = { ...source };
4731
+ for (const [selector, floor] of Object.entries(policy.overrides)) {
4732
+ let selected = floor;
4733
+ const name = dependencyName(selector);
4734
+ for (const [existing, requirement] of Object.entries(merged)) {
4735
+ if (existing !== name && !existing.startsWith(`${name}@`) && !existing.endsWith(`>${name}`) && !existing.includes(`>${name}@`)) continue;
4736
+ const minimum = minVersion(requirement);
4737
+ if (!minimum) throw new Error(`Consumer override for ${name} must use a registry version before managed upgrade`);
4738
+ const affectedRange = selector.slice(name.length + 1);
4739
+ if (affectedRange && !satisfies(minimum, affectedRange) && minimum.major !== minVersion(floor).major) continue;
4740
+ if (compare(minimum, floor) < 0) merged[existing] = floor;
4741
+ else if (compare(minimum, selected) > 0) selected = minimum.version;
4742
+ }
4743
+ merged[selector] = selected;
4744
+ }
4745
+ return merged;
4746
+ }
4747
+ function dependencyName(selector) {
4748
+ const version = selector.indexOf("@", 1);
4749
+ return version === -1 ? selector : selector.slice(0, version);
4750
+ }
4751
+ //#endregion
4752
+ //#region src/adapters/deployment/upgrade/package-consumer.ts
4753
+ const corePackageNames = [
4754
+ "@rivus/agent",
4755
+ "@rivus/gateway",
4756
+ "@rivus/runtime",
4757
+ "@rivus/platform"
4758
+ ];
4759
+ const recordSchema = Schema.Record(Schema.String, Schema.Unknown);
4760
+ const stringMapSchema = Schema.Record(Schema.String, Schema.String);
4761
+ const buildMapSchema = Schema.Record(Schema.String, Schema.Boolean);
4762
+ const installedManifestSchema = Schema.Struct({
4763
+ name: Schema.String,
4764
+ version: Schema.String
4765
+ });
4766
+ async function readInstalledManifest(root, name, resolutionBase) {
4767
+ try {
4768
+ return Schema.decodeUnknownSync(installedManifestSchema)(JSON.parse(await readFile(installedPackageManifestPath(root, name, resolutionBase), "utf8")));
4769
+ } catch {
4770
+ throw new Error(`Installed dependency ${name} is missing or has an invalid package manifest`);
4771
+ }
4772
+ }
4773
+ function installedPackageManifestPath(root, name, resolutionBase = join(root, "package.json")) {
4774
+ try {
4775
+ const manifest = findPackageJSON(name, resolutionBase);
4776
+ if (manifest) return manifest;
4777
+ } catch {}
4778
+ throw new Error(`Installed dependency ${name} cannot be resolved from the managed release`);
4779
+ }
4780
+ async function writeReleaseConsumer(input) {
4781
+ const rootManifest = join(input.sourceRoot, "package.json");
4782
+ const sourceBase = await exists(rootManifest) ? rootManifest : join(input.sourceRoot, "node_modules/@rivus/agent/package.json");
4783
+ const manifest = await optionalRecord(sourceBase);
4784
+ const workspace = await optionalRecord(join(input.sourceRoot, "pnpm-workspace.yaml"), true);
4785
+ const sourcePnpm = record(manifest.pnpm ?? {});
4786
+ const dependencies = {};
4787
+ const optionalDependencies = {};
4788
+ const installedVersions = {};
4789
+ for (const [field, target] of [["dependencies", dependencies], ["optionalDependencies", optionalDependencies]]) {
4790
+ const declared = Schema.decodeUnknownSync(stringMapSchema)(manifest[field] ?? {});
4791
+ for (const [name, requirement] of Object.entries(declared)) {
4792
+ if (corePackageNames.some((core) => core === name)) continue;
4793
+ const installed = await readInstalledManifest(input.sourceRoot, name, sourceBase).catch((error) => {
4794
+ if (field === "optionalDependencies") return;
4795
+ throw error;
4796
+ });
4797
+ if (!installed) continue;
4798
+ installedVersions[name] = installed.version;
4799
+ target[name] = requirement.startsWith("file:") || requirement.startsWith("link:") ? await retainLocalArtifact(input, name, requirement, sourceBase) : requirement.startsWith("npm:") ? `npm:${installed.name}@${installed.version}` : installed.version;
4800
+ }
4801
+ }
4802
+ for (const name of corePackageNames) dependencies[name] = input.version;
4803
+ if (!dependencies.effect) dependencies.effect = (await readInstalledManifest(input.sourceRoot, "effect", sourceBase)).version;
4804
+ const gatewayBase = installedPackageManifestPath(input.sourceRoot, "@rivus/gateway", join(input.sourceRoot, "node_modules/@rivus/agent/package.json"));
4805
+ const homeMetadata = await stat(input.homeManifestPath);
4806
+ if (!homeMetadata.isFile() || homeMetadata.size > 1048576) throw new Error("The Home deployment manifest must be a regular file of at most one MiB");
4807
+ const homeManifest = parseRivusDeploymentManifest(JSON.parse(await readFile(input.homeManifestPath, "utf8")));
4808
+ for (const plugin of homeManifest.plugins) {
4809
+ if (plugin.module.startsWith(".") || plugin.module.startsWith("/")) continue;
4810
+ const name = plugin.module.split("/").slice(0, plugin.module.startsWith("@") ? 2 : 1).join("/");
4811
+ if (corePackageNames.some((core) => core === name) || dependencies[name] || optionalDependencies[name]) continue;
4812
+ installedVersions[name] = (await readInstalledManifest(input.sourceRoot, name, gatewayBase)).version;
4813
+ dependencies[name] = await retainLocalArtifact(input, name, void 0, gatewayBase);
4814
+ }
4815
+ for (const name of corePackageNames) installedVersions[name] = input.version;
4816
+ installedVersions.effect = dependencies.effect;
4817
+ const sourceOverrides = {
4818
+ ...flattenNpmOverrides(record(manifest.overrides ?? {}), dependencies),
4819
+ ...Schema.decodeUnknownSync(stringMapSchema)(sourcePnpm.overrides ?? {}),
4820
+ ...Schema.decodeUnknownSync(stringMapSchema)(workspace.overrides ?? {})
4821
+ };
4822
+ const allowBuilds = {
4823
+ ...input.policy.allowBuilds,
4824
+ ...Schema.decodeUnknownSync(buildMapSchema)(sourcePnpm.allowBuilds ?? {}),
4825
+ ...Schema.decodeUnknownSync(buildMapSchema)(workspace.allowBuilds ?? {})
4826
+ };
4827
+ await privateFile(join(input.directory, "package.json"), `${JSON.stringify({
4828
+ name: "rivus-managed-release",
4829
+ private: true,
4830
+ type: "module",
4831
+ packageManager: `pnpm@${input.policy.pnpmVersion}`,
4832
+ dependencies,
4833
+ ...Object.keys(optionalDependencies).length ? { optionalDependencies } : {},
4834
+ ...manifest.overrides ? { overrides: manifest.overrides } : {}
4835
+ }, null, 2)}\n`);
4836
+ await privateFile(join(input.directory, "pnpm-workspace.yaml"), stringify({
4837
+ packages: ["."],
4838
+ nodeLinker: "hoisted",
4839
+ strictPeerDependencies: true,
4840
+ virtualStoreDir: "node_modules/.pnpm",
4841
+ packageImportMethod: "copy",
4842
+ allowBuilds,
4843
+ overrides: mergeInstallationOverrides(sourceOverrides, input.policy)
4844
+ }));
4845
+ return installedVersions;
4846
+ }
4847
+ async function retainLocalArtifact(input, name, requirement, resolutionBase) {
4848
+ const artifacts = join(input.directory, "artifacts");
4849
+ await mkdir(artifacts, {
4850
+ recursive: true,
4851
+ mode: 448
4852
+ });
4853
+ const target = requirement ? resolve(dirname(resolutionBase), requirement.slice(requirement.indexOf(":") + 1)) : void 0;
4854
+ const artifactName = `${name}.tgz`;
4855
+ const destination = resolve(artifacts, artifactName);
4856
+ if (!destination.startsWith(`${artifacts}${sep}`)) throw new Error("Local dependency artifact escapes the release directory");
4857
+ await mkdir(dirname(destination), {
4858
+ recursive: true,
4859
+ mode: 448
4860
+ });
4861
+ if (target && await exists(target) && (await stat(target)).isFile()) {
4862
+ await copyFile(target, destination);
4863
+ await chmod(destination, 384);
4864
+ return `file:artifacts/${artifactName}`;
4865
+ }
4866
+ const packedPath = packedArtifactPath((await checkedPackageCommand(input.run, {
4867
+ ...input.npm,
4868
+ args: [
4869
+ ...input.npm.args,
4870
+ "pack",
4871
+ dirname(installedPackageManifestPath(input.sourceRoot, name, resolutionBase)),
4872
+ "--ignore-scripts",
4873
+ "--pack-destination",
4874
+ artifacts,
4875
+ "--json"
4876
+ ]
4877
+ }, `Retaining local dependency ${name}`)).stdout, artifacts);
4878
+ if (packedPath !== destination) await copyFile(packedPath, destination);
4879
+ await chmod(destination, 384);
4880
+ return `file:artifacts/${artifactName}`;
4881
+ }
4882
+ function flattenNpmOverrides(source, dependencies, parent = "") {
4883
+ const result = {};
4884
+ for (const [name, value] of Object.entries(source)) {
4885
+ const selector = name === "." ? parent : parent ? `${parent}>${name}` : name;
4886
+ if (typeof value === "string") {
4887
+ const requirement = value.startsWith("$") ? dependencies[value.slice(1)] : value;
4888
+ if (!selector || !requirement) throw new Error("Consumer npm override cannot be resolved for managed installation");
4889
+ result[selector] = requirement;
4890
+ } else Object.assign(result, flattenNpmOverrides(record(value), dependencies, selector));
4891
+ }
4892
+ return result;
4893
+ }
4894
+ async function optionalRecord(path, yaml = false) {
4895
+ let text;
4896
+ try {
4897
+ text = await readFile(path, "utf8");
4898
+ } catch (error) {
4899
+ if (Schema.is(Schema.Struct({ code: Schema.Literal("ENOENT") }))(error)) return {};
4900
+ throw new Error("The installed consumer configuration cannot be read");
4901
+ }
4902
+ try {
4903
+ return record(yaml ? parse$1(text) : JSON.parse(text));
4904
+ } catch {
4905
+ throw new Error("The installed consumer configuration is invalid");
4906
+ }
4907
+ }
4908
+ function record(value) {
4909
+ return Schema.decodeUnknownSync(recordSchema)(value);
4910
+ }
4911
+ async function exists(path) {
4912
+ try {
4913
+ await stat(path);
4914
+ return true;
4915
+ } catch (error) {
4916
+ if (Schema.is(Schema.Struct({ code: Schema.Literal("ENOENT") }))(error)) return false;
4917
+ throw error;
4918
+ }
4919
+ }
4920
+ async function privateFile(path, contents) {
4921
+ await writeFile(path, contents, { mode: 384 });
4922
+ await chmod(path, 384);
4923
+ }
4924
+ //#endregion
4925
+ //#region src/adapters/deployment/upgrade/package-release.ts
4926
+ async function inspectInstalledRelease(command, cwd, env) {
4927
+ const executable = command.at(-1) === "start" ? command.at(-2) : command.length === 2 ? command[1] : void 0;
4928
+ if (!command[0] || !executable) throw new Error("Managed service must invoke Node and the Rivus product CLI");
4929
+ const nodePath = await resolveServiceNode(command[0], cwd, env);
4930
+ let cliPath;
4931
+ try {
4932
+ cliPath = await realpath(resolve(cwd, executable));
4933
+ } catch {
4934
+ throw new Error("The managed Rivus CLI is unavailable");
4935
+ }
4936
+ const root = resolve(dirname(cliPath), "../../../..");
4937
+ if (cliPath !== join(root, "node_modules/@rivus/agent/dist/cli.js")) throw new Error("Managed upgrade requires a direct @rivus/agent product installation");
4938
+ const agentManifest = join(root, "node_modules/@rivus/agent/package.json");
4939
+ let version;
4940
+ for (const name of corePackageNames) {
4941
+ const manifest = await readInstalledManifest(root, name, name === "@rivus/platform" ? installedPackageManifestPath(root, "@rivus/runtime", agentManifest) : agentManifest);
4942
+ 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");
4943
+ version = manifest.version;
4944
+ }
4945
+ return {
4946
+ cliPath,
4947
+ nodePath,
4948
+ root,
4949
+ version
4950
+ };
4951
+ }
4952
+ async function resolveLatestVersion(input) {
4953
+ const nodePath = input.nodePath ?? process.execPath;
4954
+ const result = await checkedPackageCommand(input.run, {
4955
+ command: nodePath,
4956
+ args: [
4957
+ ...await npmInvocation(nodePath),
4958
+ "view",
4959
+ "@rivus/agent",
4960
+ "dist-tags.latest",
4961
+ "--json"
4962
+ ],
4963
+ cwd: input.cwd,
4964
+ env: input.env,
4965
+ timeoutMs: 6e4,
4966
+ ...input.signal ? { signal: input.signal } : {}
4967
+ }, "Latest release lookup");
4968
+ try {
4969
+ const version = JSON.parse(result.stdout);
4970
+ if (typeof version === "string" && stableVersion(version)) return version;
4971
+ } catch {}
4972
+ throw new Error("The configured registry latest tag must identify a stable three-component Rivus version");
4973
+ }
4974
+ async function prepareRelease(input) {
4975
+ if (!stableVersion(input.version)) throw new Error("Managed upgrade requires a stable three-component release version");
4976
+ if (resolve(input.directory) === input.source.root) throw new Error("A candidate release must use a separate installation directory");
4977
+ assertSourceCompatibility(await readInstallationPolicy(), input.source.version);
4978
+ await mkdir(input.directory, {
4979
+ recursive: true,
4980
+ mode: 448
4981
+ });
4982
+ await chmod(input.directory, 448);
4983
+ const npmrc = await retainRegistryConfiguration(input.source.root, input.directory);
4984
+ const npm = {
4985
+ command: input.source.nodePath,
4986
+ args: await npmInvocation(input.source.nodePath),
4987
+ cwd: input.directory,
4988
+ env: installerEnvironment(input.source.nodePath, {
4989
+ ...input.service.env,
4990
+ ...npmrc ? { npm_config_userconfig: npmrc } : {}
4991
+ }),
4992
+ timeoutMs: 9e5,
4993
+ ...input.signal ? { signal: input.signal } : {}
4994
+ };
4995
+ const policy = await fetchInstallationPolicy({
4996
+ version: input.version,
4997
+ directory: input.directory,
4998
+ npm,
4999
+ run: input.run
5000
+ });
5001
+ assertSourceCompatibility(policy, input.source.version);
5002
+ let versions;
5003
+ try {
5004
+ versions = await writeReleaseConsumer({
5005
+ sourceRoot: input.source.root,
5006
+ directory: input.directory,
5007
+ version: input.version,
5008
+ policy,
5009
+ run: input.run,
5010
+ npm,
5011
+ homeManifestPath: input.home.manifestPath
5012
+ });
5013
+ } catch {
5014
+ throw new Error("The source consumer or Home plugins could not be retained; check source dependencies, overrides and the Home manifest before upgrading");
5015
+ }
5016
+ const pnpmArgs = [
5017
+ ...npm.args,
5018
+ "exec",
5019
+ "--yes",
5020
+ "--package",
5021
+ `pnpm@${policy.pnpmVersion}`,
5022
+ "--",
5023
+ "pnpm"
5024
+ ];
5025
+ await checkedPackageCommand(input.run, {
5026
+ ...npm,
5027
+ args: [
5028
+ ...pnpmArgs,
5029
+ "install",
5030
+ "--prod",
5031
+ "--no-frozen-lockfile",
5032
+ "--reporter=silent",
5033
+ "--config.node-linker=hoisted",
5034
+ "--config.strict-peer-dependencies=true",
5035
+ "--config.virtual-store-dir=node_modules/.pnpm",
5036
+ "--config.package-import-method=copy",
5037
+ "--ignore-scripts=false"
5038
+ ],
5039
+ discardStdout: true
5040
+ }, "Candidate package installation", join(input.directory, "installation.log"));
5041
+ const cliPath = join(resolve(input.directory), "node_modules/@rivus/agent/dist/cli.js");
5042
+ const candidate = await inspectInstalledRelease([input.source.nodePath, cliPath], input.service.cwd, input.service.env);
5043
+ if (candidate.version !== input.version) throw new Error("Candidate packages do not match the selected release");
5044
+ 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`);
5045
+ const installedPolicy = await readInstallationPolicy(join(candidate.root, "node_modules/@rivus/gateway"));
5046
+ if (!isDeepStrictEqual(installedPolicy, policy)) throw new Error("Installed candidate policy differs from the selected release artifact");
5047
+ await checkedPackageCommand(input.run, {
5048
+ ...npm,
5049
+ args: [
5050
+ ...pnpmArgs,
5051
+ "audit",
5052
+ "--prod",
5053
+ "--audit-level=high",
5054
+ "--json"
5055
+ ],
5056
+ timeoutMs: 12e4
5057
+ }, "Candidate dependency audit", join(input.directory, "audit.log"));
5058
+ const check = {
5059
+ command: input.source.nodePath,
5060
+ cwd: input.service.cwd,
5061
+ env: {
5062
+ ...input.service.env,
5063
+ RIVUS_HOME: input.home.directory
5064
+ },
5065
+ timeoutMs: 6e4,
5066
+ ...input.signal ? { signal: input.signal } : {}
5067
+ };
5068
+ const nodeArgs = input.service.command.at(-1) === "start" ? input.service.command.slice(1, -2) : [];
5069
+ await checkedPackageCommand(input.run, {
5070
+ ...check,
5071
+ args: [
5072
+ ...nodeArgs,
5073
+ cliPath,
5074
+ "doctor",
5075
+ "--env-file",
5076
+ input.home.envFilePath
5077
+ ]
5078
+ }, "Candidate Home doctor", join(input.directory, "doctor.log"));
5079
+ await checkedPackageCommand(input.run, {
5080
+ ...check,
5081
+ args: [
5082
+ ...nodeArgs,
5083
+ cliPath,
5084
+ "check-config",
5085
+ "--load-plugins"
5086
+ ]
5087
+ }, "Candidate plugin validation", join(input.directory, "plugins.log"));
5088
+ await checkedPackageCommand(input.run, {
5089
+ ...check,
5090
+ args: [
5091
+ ...nodeArgs,
5092
+ "--input-type=commonjs",
5093
+ "--eval",
5094
+ nativeCheck,
5095
+ cliPath,
5096
+ candidate.root
5097
+ ]
5098
+ }, "Candidate native module validation", join(input.directory, "native.log"));
5099
+ return {
5100
+ cliPath,
5101
+ version: candidate.version
5102
+ };
5103
+ }
5104
+ function stableVersion(value) {
5105
+ const parsed = parse(value);
5106
+ return parsed !== null && parsed.version === value && parsed.prerelease.length === 0 && parsed.build.length === 0;
5107
+ }
5108
+ async function hasFile(path) {
5109
+ try {
5110
+ return (await stat(path)).isFile();
5111
+ } catch {
5112
+ return false;
5113
+ }
5114
+ }
5115
+ async function retainRegistryConfiguration(sourceRoot, directory) {
5116
+ const source = join(sourceRoot, ".npmrc");
5117
+ if (!await hasFile(source)) return;
5118
+ const target = await realpath(source);
5119
+ const destination = join(directory, ".npmrc");
5120
+ try {
5121
+ await symlink(target, destination);
5122
+ } catch {
5123
+ if (await realpath(destination).catch(() => void 0) !== target) throw new Error("Candidate registry configuration cannot retain the installed configuration");
5124
+ }
5125
+ return target;
5126
+ }
5127
+ const nativeCheck = `
5128
+ const { createRequire } = require("node:module");
5129
+ const { realpathSync } = require("node:fs");
5130
+ const { join } = require("node:path");
5131
+ const consumer = createRequire(process.argv[1]);
5132
+ const gateway = createRequire(consumer.resolve("@rivus/gateway/package.json"));
5133
+ const { Resvg } = gateway("@resvg/resvg-js");
5134
+ 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();
5135
+ if (!png.length) throw new Error("Resvg produced no image");
5136
+ const pi = createRequire(realpathSync(join(process.argv[2], "node_modules/@earendil-works/pi-coding-agent/package.json")));
5137
+ const { PhotonImage } = pi("@silvia-odwyer/photon-node");
5138
+ const image = new PhotonImage(new Uint8Array([0, 0, 0, 0]), 1, 1);
5139
+ try { if (image.get_width() !== 1 || image.get_height() !== 1 || !image.get_bytes().length) throw new Error("Photon produced no image"); }
5140
+ finally { image.free(); }
5141
+ `;
5142
+ //#endregion
5143
+ //#region src/adapters/deployment/upgrade/home-backup.ts
5144
+ const isMissingFile = Schema.is(Schema.Struct({ code: Schema.Literal("ENOENT") }));
5145
+ async function backUpUpgradeHome(input) {
5146
+ await mkdir(input.directory, {
5147
+ recursive: true,
5148
+ mode: 448
5149
+ });
5150
+ const archive = {
5151
+ path: join(input.directory, "home.tar.gz"),
5152
+ format: "gzip"
5153
+ };
5154
+ const temporary = {
5155
+ ...archive,
5156
+ path: `${archive.path}.partial`
5157
+ };
5158
+ try {
5159
+ await rm(join(input.directory, "home.tar.partial"), { force: true });
5160
+ const existing = await retainedArchive(input.directory);
5161
+ if (existing) {
5162
+ await verifyArchive(existing, input);
5163
+ return existing.path;
5164
+ }
5165
+ const created = await input.run({
5166
+ command: "/usr/bin/tar",
5167
+ args: [
5168
+ "--use-compress-program=/usr/bin/gzip -1",
5169
+ "-cpf",
5170
+ temporary.path,
5171
+ "--exclude=./.rivus-upgrade",
5172
+ "-C",
5173
+ input.home,
5174
+ "."
5175
+ ],
5176
+ cwd: input.home,
5177
+ env: input.env,
5178
+ timeoutMs: 18e5,
5179
+ ...input.signal ? { signal: input.signal } : {},
5180
+ discardStdout: true
5181
+ });
5182
+ if (created.exitCode !== 0) {
5183
+ await rm(temporary.path, { force: true });
5184
+ await throwArchiveFailure("create", archive.path, created);
5185
+ }
5186
+ await chmod(temporary.path, 384);
5187
+ await verifyArchive(temporary, input, true);
5188
+ await rename(temporary.path, archive.path);
5189
+ return archive.path;
5190
+ } finally {
5191
+ await rm(temporary.path, { force: true });
5192
+ }
5193
+ }
5194
+ async function verifyUpgradeBackup(input) {
5195
+ const archive = await retainedArchive(input.directory);
5196
+ if (!archive) throw new Error("Home backup is missing");
5197
+ await verifyArchive(archive, input);
5198
+ }
5199
+ async function retainedArchive(directory) {
5200
+ const archives = [];
5201
+ for (const [name, format] of [["home.tar.gz", "gzip"], ["home.tar", "tar"]]) {
5202
+ const path = join(directory, name);
5203
+ if (await lstat(path).catch((error) => {
5204
+ if (!isMissingFile(error)) throw error;
5205
+ })) archives.push({
5206
+ path,
5207
+ format
5208
+ });
5209
+ }
5210
+ if (archives.length > 1) throw new Error("Both home.tar and home.tar.gz exist; preserve both backups and resolve the ambiguity before resuming");
5211
+ return archives[0];
5212
+ }
5213
+ async function verifyArchive(archive, input, removeFailedPartial = false) {
5214
+ const metadata = await lstat(archive.path);
5215
+ if (!metadata.isFile() || metadata.size === 0) throw new Error("Home backup is missing, empty or not a regular file");
5216
+ const listed = await input.run({
5217
+ command: "/usr/bin/tar",
5218
+ args: [
5219
+ ...archive.format === "gzip" ? ["--use-compress-program=/usr/bin/gzip -d"] : [],
5220
+ "-tf",
5221
+ archive.path
5222
+ ],
5223
+ cwd: input.home,
5224
+ env: input.env,
5225
+ timeoutMs: 18e5,
5226
+ discardStdout: true
5227
+ });
5228
+ if (listed.exitCode !== 0) {
5229
+ if (removeFailedPartial) await rm(archive.path, { force: true });
5230
+ await throwArchiveFailure("verify", archive.path, listed);
5231
+ }
5232
+ }
5233
+ async function throwArchiveFailure(phase, archive, result) {
5234
+ const diagnostics = join(dirname(archive), `tar-${phase}-failure-${randomUUID()}.json`);
5235
+ const summary = phase === "create" ? "Home backup failed; the service remains stopped and the previous release is retained" : "Home backup could not be read; refusing to switch the service";
5236
+ try {
5237
+ await writeAtomicTextFile(diagnostics, `${JSON.stringify({
5238
+ archive,
5239
+ exitCode: result.exitCode,
5240
+ stderr: result.stderr
5241
+ }, null, 2)}\n`, {
5242
+ mode: 384,
5243
+ durable: true
5244
+ });
5245
+ } catch {
5246
+ throw new Error(`${summary} (tar exit ${result.exitCode}); private diagnostics could not be saved to ${diagnostics}`);
5247
+ }
5248
+ throw new Error(`${summary} (tar exit ${result.exitCode}); private diagnostics: ${diagnostics}`);
5249
+ }
5250
+ //#endregion
5251
+ //#region src/bootstrap/upgrade/upgrade-home.ts
5252
+ /** Owns one managed process cutover. Application data is retained in its original Home throughout the operation. */
5253
+ async function upgradeHome(options) {
5254
+ const home = {
5255
+ ...options.home,
5256
+ directory: await realpath(options.home.directory)
5257
+ };
5258
+ const releaseLock = await acquireUpgradeLock(home.directory, options);
5259
+ try {
5260
+ return await upgradeLocked({
5261
+ ...options,
5262
+ home
5263
+ });
5264
+ } finally {
5265
+ await releaseLock();
5266
+ }
5267
+ }
5268
+ async function upgradeLocked(options) {
5269
+ const { home } = options;
5270
+ const runner = options.run ?? runCommand;
5271
+ const run = (request) => runner({
5272
+ ...request,
5273
+ ...options.signal ? { signal: options.signal } : {}
5274
+ });
5275
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
5276
+ const packages = options.packages ?? {
5277
+ inspect: inspectInstalledRelease,
5278
+ latest: resolveLatestVersion,
5279
+ prepare: prepareRelease
5280
+ };
5281
+ const services = options.services ?? createServiceManager({
5282
+ home: home.directory,
5283
+ userHome: options.userHome,
5284
+ platform: options.platform,
5285
+ env: { ...options.env },
5286
+ run
5287
+ });
5288
+ let record = await readUpgradeRecord(home.directory);
5289
+ let service = record && record.phase !== "complete" ? await services.load(record.service) : await services.discover();
5290
+ if (!record || record.phase === "complete") {
5291
+ const source = await packages.inspect(service.command, service.cwd, service.env);
5292
+ options.progress("resolving", `Checking latest release (current ${source.version})`);
5293
+ const target = await packages.latest({
5294
+ run,
5295
+ env: service.env,
5296
+ cwd: source.root,
5297
+ nodePath: source.nodePath
5298
+ });
5299
+ requireStableVersion(target);
5300
+ 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");
5301
+ if (compare(target, source.version) < 0) throw new Error("registry latest is older than the running release; refusing a downgrade");
5302
+ const observed = await services.inspect(service);
5303
+ 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");
5304
+ if (target === source.version) return {
5305
+ status: "current",
5306
+ version: target,
5307
+ previousVersion: source.version,
5308
+ home: home.directory,
5309
+ service: service.id,
5310
+ pid: observed.pid,
5311
+ executable: source.cliPath
5312
+ };
5313
+ record = {
5314
+ schemaVersion: 1,
5315
+ id: randomUUID(),
5316
+ home: home.directory,
5317
+ sourceVersion: source.version,
5318
+ targetVersion: target,
5319
+ sourceCommand: [...service.command],
5320
+ service: {
5321
+ kind: service.kind,
5322
+ id: service.id,
5323
+ definitionPath: service.definitionPath
5324
+ },
5325
+ phase: "preparing",
5326
+ createdAt: now().toISOString()
5327
+ };
5328
+ await writeUpgradeRecord(record);
5329
+ }
5330
+ const paths = upgradePaths(home.directory, record.id);
5331
+ const source = await packages.inspect(record.sourceCommand, service.cwd, service.env);
5332
+ if (source.version !== record.sourceVersion) throw new Error("the retained source release changed; preserve the journal and resolve it before continuing");
5333
+ requireStableVersion(record.targetVersion);
5334
+ const candidateCommand = [...record.sourceCommand];
5335
+ const candidateCli = `${paths.release}/node_modules/@rivus/agent/dist/cli.js`;
5336
+ candidateCommand[candidateCommand.length - 2] = candidateCli;
5337
+ const setPhase = async (phase) => {
5338
+ record = {
5339
+ ...record,
5340
+ phase,
5341
+ ...phase === "stopping" ? { startedAfter: now().toISOString() } : {}
5342
+ };
5343
+ await writeUpgradeRecord(record);
5344
+ options.progress(phase, `${record.sourceVersion} -> ${record.targetVersion}`);
5345
+ };
5346
+ const inspectExpected = async () => {
5347
+ const observed = await services.inspect(record.service);
5348
+ 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");
5349
+ return observed;
5350
+ };
5351
+ if (record.phase === "preparing") {
5352
+ const observed = await inspectExpected();
5353
+ if (!observed.running || !sameCommand(observed.command, record.sourceCommand)) throw new Error("the source service changed during preparation");
5354
+ options.progress("preparing", `Installing ${record.targetVersion} while the current service remains running`);
5355
+ await packages.prepare({
5356
+ source,
5357
+ version: record.targetVersion,
5358
+ directory: paths.release,
5359
+ home,
5360
+ service,
5361
+ run,
5362
+ ...options.signal ? { signal: options.signal } : {}
5363
+ });
5364
+ await setPhase("prepared");
5365
+ }
5366
+ if ((await packages.inspect(candidateCommand, service.cwd, service.env)).version !== record.targetVersion) throw new Error("prepared release does not match the recorded target version");
5367
+ if (record.phase === "prepared") {
5368
+ const observed = await inspectExpected();
5369
+ if (!observed.running || !sameCommand(observed.command, record.sourceCommand)) throw new Error("the source service changed before cutover");
5370
+ await setPhase("stopping");
5371
+ }
5372
+ if (record.phase === "stopping") {
5373
+ const observed = await inspectExpected();
5374
+ if (observed.running) {
5375
+ if (!sameCommand(observed.command, record.sourceCommand)) throw new Error("candidate started before the stopped backup; preserve this operation for recovery");
5376
+ await services.stop(record.service);
5377
+ }
5378
+ if ((await inspectExpected()).running) throw new Error("the managed service has not stopped");
5379
+ await setPhase("stopped");
5380
+ }
5381
+ if (record.phase === "stopped") {
5382
+ if ((await inspectExpected()).running) throw new Error("the service restarted before backup; stop it before resuming this operation");
5383
+ await (options.backup ?? backUpUpgradeHome)({
5384
+ home: home.directory,
5385
+ directory: paths.backup,
5386
+ env: service.env,
5387
+ run,
5388
+ ...options.signal ? { signal: options.signal } : {}
5389
+ });
5390
+ await setPhase("backed-up");
5391
+ }
5392
+ if (record.phase === "backed-up") {
5393
+ await (options.verifyBackup ?? verifyUpgradeBackup)({
5394
+ home: home.directory,
5395
+ directory: paths.backup,
5396
+ env: service.env,
5397
+ run
5398
+ });
5399
+ if ((await inspectExpected()).running) throw new Error("the service restarted before switching; no service definition was changed");
5400
+ await setPhase("switching");
5401
+ }
5402
+ if (record.phase === "switching") {
5403
+ const observed = await inspectExpected();
5404
+ if (observed.running && !sameCommand(observed.command, candidateCommand)) throw new Error("the old service restarted during switching");
5405
+ service = await services.load(record.service);
5406
+ if (!sameCommand(service.command, candidateCommand)) {
5407
+ if (!sameCommand(service.command, record.sourceCommand)) throw new Error("the service definition changed outside this upgrade");
5408
+ await services.switch(record.service, candidateCommand, paths.backup);
5409
+ }
5410
+ await setPhase("starting");
5411
+ }
5412
+ if (record.phase !== "starting") throw new Error(`unsupported recovery phase: ${record.phase}`);
5413
+ const observed = await inspectExpected();
5414
+ if (!observed.running) await services.start(record.service);
5415
+ else if (!sameCommand(observed.command, candidateCommand)) throw new Error("the source process is still running after the switch");
5416
+ const pid = await waitForCandidate(options, services, record, candidateCommand);
5417
+ await setPhase("complete");
5418
+ return {
5419
+ status: "upgraded",
5420
+ version: record.targetVersion,
5421
+ previousVersion: record.sourceVersion,
5422
+ home: home.directory,
5423
+ service: record.service.id,
5424
+ pid,
5425
+ executable: candidateCli,
5426
+ backup: paths.backup,
5427
+ operationId: record.id
5428
+ };
5429
+ }
5430
+ async function waitForCandidate(options, services, record, command) {
5431
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
5432
+ const deadline = now().getTime() + (options.startupTimeoutMs ?? 6e4);
5433
+ const wait = options.wait ?? ((ms) => setTimeout$1(ms, void 0, { signal: options.signal }));
5434
+ do {
5435
+ if (options.signal?.aborted) throw new Error("upgrade interrupted; rerun rivus upgrade to resume");
5436
+ const process = await services.inspect(record.service);
5437
+ const receipt = await (options.receipts ?? readRuntimeReceipt)(record.home);
5438
+ 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)) {
5439
+ const confirmed = await services.inspect(record.service);
5440
+ if (confirmed.running && confirmed.pid === process.pid && sameCommand(confirmed.command, command)) return process.pid;
5441
+ }
5442
+ if (process.running && !sameCommand(process.command, command)) throw new Error("a different command is running after upgrade; preserve the backup and journal");
5443
+ await wait(500);
5444
+ } while (now().getTime() < deadline);
5445
+ throw new Error("new release did not become ready within the startup deadline; rerun rivus upgrade after resolving the service error");
5446
+ }
5447
+ function sameCommand(left, right) {
5448
+ return left.length === right.length && left.every((value, index) => value === right[index]);
5449
+ }
5450
+ function requireStableVersion(version) {
5451
+ if (!/^\d+\.\d+\.\d+$/.test(version) || !valid(version)) throw new Error("registry latest must be a stable release version");
5452
+ }
5453
+ //#endregion
5454
+ //#region src/adapters/cli/upgrade/upgrade-cli-protocol.ts
5455
+ const UPGRADE_USAGE = `Usage: rivus upgrade [--json]
5456
+
5457
+ Upgrade the selected Home's managed service to the latest stable npm release.
5458
+ Prepare and validate before stopping, retain the Home and backup, then verify startup.
5459
+ Rerun the same command to resume an interrupted upgrade at its recorded version.
5460
+ `;
5461
+ function parseUpgradeArguments(argv) {
5462
+ if (argv.includes("--help") || argv.includes("-h")) return { help: true };
5463
+ if (argv.length === 0) return { json: false };
5464
+ if (argv.length === 1 && argv[0] === "--json") return { json: true };
5465
+ return { error: "upgrade accepts only --json; it selects the latest stable release automatically" };
5466
+ }
5467
+ function renderUpgradeResult(result, json) {
5468
+ if (json) return `${JSON.stringify(result)}\n`;
5469
+ 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` : ""}`;
5470
+ }
5471
+ //#endregion
3911
5472
  //#region src/bootstrap/cli/rivus-cli.ts
3912
5473
  function runRivusCli(options) {
3913
5474
  const command = options.argv[0];
3914
5475
  if (command === "setup") return runSetupCommand(options);
5476
+ if (command === "upgrade") return runUpgradeCommand(options);
3915
5477
  if (command === "start") return runHomeDaemonCommand(options, "start", []);
3916
5478
  if (command === "status") return runHomeDaemonCommand(options, "status", ["--status"]);
3917
5479
  if (command === "check-config") return runHomeDaemonCommand(options, "check-config", ["--check-config"]);
@@ -3946,6 +5508,45 @@ function runRivusCli(options) {
3946
5508
  env: withoutRivusHomeDeployment(options.env)
3947
5509
  });
3948
5510
  }
5511
+ function runUpgradeCommand(options) {
5512
+ const parsed = parseUpgradeArguments(options.argv.slice(1));
5513
+ if ("help" in parsed) return Effect.sync(() => {
5514
+ options.stdout.write(UPGRADE_USAGE);
5515
+ return 0;
5516
+ });
5517
+ if ("error" in parsed) return Effect.sync(() => {
5518
+ options.stderr.write(`${parsed.error}\n${UPGRADE_USAGE}`);
5519
+ return 1;
5520
+ });
5521
+ return Effect.gen(function* () {
5522
+ const directory = yield* resolveHomeDirectoryEffect(options);
5523
+ const home = yield* options.homeApi.load(directory);
5524
+ if (!options.upgradeHost) return yield* Effect.fail(/* @__PURE__ */ new Error("upgrade requires the Node process host"));
5525
+ const upgradeHost = options.upgradeHost;
5526
+ const result = yield* Effect.tryPromise({
5527
+ try: () => (options.upgradeRunner ?? upgradeHome)({
5528
+ ...upgradeHost,
5529
+ home,
5530
+ userHome: options.homeDirectory,
5531
+ env: options.env,
5532
+ signal: abortOnInterruption(options.signalSource),
5533
+ progress: (phase, detail) => options.stderr.write(`[${phase}] ${detail}\n`)
5534
+ }),
5535
+ catch: (error) => error
5536
+ });
5537
+ options.stdout.write(renderUpgradeResult(result, parsed.json));
5538
+ return 0;
5539
+ }).pipe(Effect.catch((error) => Effect.sync(() => {
5540
+ const message = error instanceof Error ? error.message : String(error);
5541
+ if (parsed.json) options.stdout.write(`${JSON.stringify({
5542
+ status: "failed",
5543
+ message,
5544
+ recovery: "Rerun rivus upgrade to resume the recorded operation after resolving this error."
5545
+ })}\n`);
5546
+ else options.stderr.write(`Upgrade failed: ${message}\nRerun rivus upgrade to resume after resolving this error.\n`);
5547
+ return 1;
5548
+ })));
5549
+ }
3949
5550
  function resolveHomeRecoveryFileArguments(argv, command, cwd) {
3950
5551
  if (command.type === "inspect") return argv;
3951
5552
  const files = /* @__PURE__ */ new Map([["--recovery-note-file", resolve(cwd, command.noteFilePath)]]);
@@ -4056,7 +5657,9 @@ function runSetupCommand(options) {
4056
5657
  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
5658
  }
4058
5659
  function runHomeDaemonCommand(options, command, daemonArgs) {
4059
- if (command !== "recovery" && hasRivusHomeCommandArguments(options.argv.slice(1))) return Effect.sync(() => {
5660
+ const commandArgs = options.argv.slice(1);
5661
+ const checkPlugins = command === "check-config" && commandArgs.length === 1 && commandArgs[0] === "--load-plugins";
5662
+ if (command !== "recovery" && !checkPlugins && hasRivusHomeCommandArguments(commandArgs)) return Effect.sync(() => {
4060
5663
  options.stderr.write(renderRivusHomeCommandUsage(command));
4061
5664
  return 1;
4062
5665
  });
@@ -4077,7 +5680,22 @@ function runHomeDaemonCommand(options, command, daemonArgs) {
4077
5680
  RIVUS_HOME: home.directory,
4078
5681
  [RIVUS_HOME_DEPLOYMENT_ENV]: home.directory
4079
5682
  },
4080
- pluginPackageManifestPath: options.pluginPackageManifestPath ?? gatewayPackageManifestPath
5683
+ pluginPackageManifestPath: options.pluginPackageManifestPath ?? gatewayPackageManifestPath,
5684
+ ...checkPlugins ? { checkPlugins: true } : {},
5685
+ ...command === "start" ? { lifecycle: {
5686
+ started: async () => {
5687
+ if (!options.runtimeProcess) throw new Error("Home start requires the runtime process identity");
5688
+ await writeRuntimeReceipt({
5689
+ ...options.runtimeProcess,
5690
+ home: home.directory,
5691
+ version: RIVUS_RELEASE_DESCRIPTOR.version,
5692
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
5693
+ });
5694
+ },
5695
+ stopped: async () => {
5696
+ if (options.runtimeProcess) await clearRuntimeReceipt(home.directory, options.runtimeProcess.pid);
5697
+ }
5698
+ } } : {}
4081
5699
  })), Effect.catch((error) => writeError(options, error)));
4082
5700
  }
4083
5701
  function runInitCommand(options) {
@@ -4168,6 +5786,23 @@ function runRivusNodeEntrypoint(options) {
4168
5786
  loadBootstrap: (specifier) => import(toImportSpecifier(specifier)),
4169
5787
  nodeExecutable: process.execPath,
4170
5788
  nodeVersion: process.versions.node,
5789
+ upgradeHost: {
5790
+ pid: process.pid,
5791
+ platform: process.platform,
5792
+ isProcessAlive: (pid) => {
5793
+ try {
5794
+ process.kill(pid, 0);
5795
+ return true;
5796
+ } catch (error) {
5797
+ if (Schema.is(Schema.Struct({ code: Schema.Literal("ESRCH") }))(error)) return false;
5798
+ throw new Error("could not determine whether the existing upgrader is still running", { cause: error });
5799
+ }
5800
+ }
5801
+ },
5802
+ runtimeProcess: {
5803
+ pid: process.pid,
5804
+ executable: resolve(options.cwd, process.argv[1] ?? "")
5805
+ },
4171
5806
  signalSource: options.signalSource,
4172
5807
  stderr: options.stderr,
4173
5808
  stdout: options.stdout