@rivus/gateway 0.19.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.
@@ -1,21 +1,23 @@
1
- import { C as validateRivusDeploymentManifest, S as InvalidRivusProjectSpace, T as deepFreeze, _ as gatewayTemplateDirectory, a as invokeRuntimeControl, b as loadMergedLocalEnvFile, d as renderRivusModelCliArgumentError, f as renderRivusModelCliHelp, h as gatewayPackageManifestPath, i as disposeRuntimeCacheEntries, l as createRivusModelManagementWireRequest, n as withoutRivusHomeDeployment, o as RIVUS_RELEASE_DESCRIPTOR, p as gatewayAudioTranscriberAssetDirectory, r as createRuntimeCache, t as RIVUS_HOME_DEPLOYMENT_ENV, u as parseRivusModelCliArguments, v as loadRivusDeploymentManifest, w as validateRivusProjectSpaceDeployment, x as resolveFeishuEndpointCredentials, y as loadRivusDaemonConfig } from "./rivus-home-deployment-env.js";
2
- import { n as narrowBackgroundSessionDefinition, t as createBackgroundSessionToolContracts } from "./background-session-authority.js";
3
- 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";
4
3
  import { createSha256Digest, createStableId } from "@rivus/platform/identity";
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
7
  import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
8
8
  import { fileURLToPath, pathToFileURL } from "node:url";
9
- import { Cause, Deferred, Effect, Exit, Option, Result, Schema, Semaphore } from "effect";
10
- import { cp, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, rmdir, stat, unlink, writeFile } from "node:fs/promises";
11
- import { createHash, randomUUID } from "node:crypto";
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
+ import { randomUUID } from "node:crypto";
11
+ import { writeAtomicTextFile } from "@rivus/platform/persistence";
12
12
  import { assertPathWithin, isPathWithin } from "@rivus/platform/filesystem";
13
+ import { constants as constants$1 } from "node:fs";
13
14
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
14
- import { readPersistenceFile, writeAtomicTextFile } from "@rivus/platform/persistence";
15
15
  import { spawn } from "node:child_process";
16
16
  import { createConnection } from "node:net";
17
- import { constants as constants$1 } from "node:fs";
18
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";
19
21
  //#region src/core/application/agent-catalog/contracts/rivus-plugin.ts
20
22
  const RIVUS_PLUGIN_API_VERSION = "1";
21
23
  var InvalidRivusPlugin = class extends Error {
@@ -23,6 +25,28 @@ var InvalidRivusPlugin = class extends Error {
23
25
  };
24
26
  //#endregion
25
27
  //#region src/core/application/agent-catalog/catalog/rivus-catalog-validation.ts
28
+ const automationRetryPolicySchema = Schema.Struct({
29
+ maxAttempts: Schema.Number,
30
+ terminalFailureCodes: Schema.optional(Schema.Array(Schema.String))
31
+ });
32
+ function validateRivusAutomationRetryPolicy(value, automationId) {
33
+ if (value === void 0) return;
34
+ const reject = (field, requirement) => {
35
+ throw new InvalidRivusPlugin(`automation ${automationId} retry ${field} ${requirement}`);
36
+ };
37
+ const decoded = Schema.decodeUnknownResult(automationRetryPolicySchema, { onExcessProperty: "error" })(value);
38
+ if (Result.isFailure(decoded)) return reject("policy", decoded.failure.message);
39
+ const policy = decoded.success;
40
+ if (!Number.isInteger(policy.maxAttempts) || policy.maxAttempts < 1 || policy.maxAttempts > 10) reject("maxAttempts", "must be an integer from 1 to 10");
41
+ const codes = policy.terminalFailureCodes ?? [];
42
+ if (codes.length > 16) reject("terminalFailureCodes", "must contain at most 16 codes");
43
+ const seen = /* @__PURE__ */ new Set();
44
+ for (const [index, code] of codes.entries()) {
45
+ if (!/^[A-Z][A-Z0-9_]{0,63}$/.test(code)) reject(`terminalFailureCodes[${index}]`, "must match ^[A-Z][A-Z0-9_]{0,63}$");
46
+ if (seen.has(code)) reject(`terminalFailureCodes[${index}]`, "must not duplicate another code");
47
+ seen.add(code);
48
+ }
49
+ }
26
50
  const MEMORY_SCOPES = [
27
51
  "conversation",
28
52
  "agent-private",
@@ -125,6 +149,7 @@ function createRivusPluginCatalog$1(runtime) {
125
149
  validateRivusCatalogReferences(profile.skills.allow, availableSkillIds, `profile ${profile.id}`, "skill");
126
150
  }
127
151
  for (const automation of pendingAutomations) {
152
+ validateRivusAutomationRetryPolicy(automation.retry, automation.id);
128
153
  validateRivusCatalogReference(automation.profileId, availableProfileIds, `automation ${automation.id}`, "profile");
129
154
  validateRivusCatalogReferences(automation.requestedToolIds, availableToolIds, `automation ${automation.id}`, "tool");
130
155
  validateRivusCatalogReferences(automation.requestedSkillIds, availableSkillIds, `automation ${automation.id}`, "skill");
@@ -314,6 +339,16 @@ function resolveRivusAgentDefinition$1(catalog, deployment, providers, runtime)
314
339
  profileId: deployment.profileId,
315
340
  ...deployment.projectSpaceId ? { projectSpaceId: deployment.projectSpaceId } : {},
316
341
  profileRevision,
342
+ ...deployment.runtime ? { runtime: {
343
+ args: [...deployment.runtime.args ?? []],
344
+ command: deployment.runtime.command,
345
+ env: { ...deployment.runtime.env },
346
+ initializationTimeoutMs: deployment.runtime.initializationTimeoutMs ?? 1e4,
347
+ permissions: deployment.runtime.permissions ?? "ask",
348
+ steering: deployment.runtime.steering ?? "disabled",
349
+ type: deployment.runtime.type,
350
+ unattended: deployment.runtime.unattended ?? false
351
+ } } : {},
317
352
  runtimeToolGrantSet,
318
353
  skillGrantSet,
319
354
  skills,
@@ -517,14 +552,13 @@ function toError$3(error) {
517
552
  }
518
553
  //#endregion
519
554
  //#region src/adapters/deployment/inspection/rivus-home-deployment-inspector.ts
520
- const DEFAULT_BOOTSTRAP_PEERS = Object.freeze(["@earendil-works/pi-coding-agent", "@larksuiteoapi/node-sdk"]);
555
+ const FEISHU_BOOTSTRAP = "@rivus/gateway/bootstrap/feishu";
521
556
  function createRivusHomeDeploymentInspector(options = {}) {
522
- const resolveModule = options.resolveModule ?? ((specifier) => defaultResolveModule(specifier, options.packageManifestPath));
523
557
  const resolvePluginModule = options.resolvePluginModule ?? ((request) => resolveNodeRivusPluginModulePath(request, options.packageManifestPath ? { packageManifestPath: options.packageManifestPath } : {}));
524
558
  return { inspect: (input) => Effect.gen(function* () {
525
559
  const manifestResult = yield* checkManifest$1(input.home);
526
560
  const credentials = yield* checkCredentials$1(input.home, manifestResult.manifest, input.env, input.envFilePath);
527
- const modules = yield* checkModules(input.home, manifestResult.manifest, resolveModule, resolvePluginModule);
561
+ const modules = yield* checkModules(input.home, manifestResult.manifest, options.resolveModule ?? ((specifier) => defaultResolveModule(specifier, options.packageManifestPath, input.home.directory)), resolvePluginModule);
528
562
  return {
529
563
  credentials,
530
564
  manifest: manifestResult.check,
@@ -555,7 +589,7 @@ function checkModules(home, manifest, resolveModule, resolvePluginModule) {
555
589
  name: "modules",
556
590
  status: "fail"
557
591
  });
558
- const specifiers = [home.bootstrap, ...home.bootstrap === "@rivus/gateway/bootstrap/pi-feishu" ? DEFAULT_BOOTSTRAP_PEERS : []];
592
+ const specifiers = [home.bootstrap, ...home.bootstrap === FEISHU_BOOTSTRAP ? ["@larksuiteoapi/node-sdk", ...manifest.agents.some(({ runtime }) => !runtime) ? ["@earendil-works/pi-coding-agent"] : []] : []];
559
593
  return Effect.gen(function* () {
560
594
  const missing = [];
561
595
  for (const specifier of specifiers) {
@@ -571,7 +605,7 @@ function checkModules(home, manifest, resolveModule, resolvePluginModule) {
571
605
  if (result._tag === "Failure") missing.push(`${plugin.module} (${formatError(result.failure)})`);
572
606
  }
573
607
  return missing.length === 0 ? {
574
- message: "Bootstrap, Plugin, Pi, and Feishu modules resolve from the global installation",
608
+ message: "Bootstrap, Plugin, runtime, and Feishu modules resolve from the global installation",
575
609
  name: "modules",
576
610
  status: "pass"
577
611
  } : {
@@ -605,27 +639,33 @@ function checkCredentials$1(home, manifest, env, envFilePath) {
605
639
  try: async () => {
606
640
  const merged = await loadMergedLocalEnvFile(envFilePath ? resolve(home.directory, envFilePath) : home.envFilePath, env);
607
641
  for (const endpoint of manifest.endpoints.filter(({ enabled }) => enabled)) resolveFeishuEndpointCredentials(endpoint.credentialRef, merged);
642
+ for (const agent of manifest.agents) if (agent.runtime) await resolveAcpRuntimeEnvironment(agent.runtime, merged);
643
+ if (parseRivusModelManagementEnabled(merged.RIVUS_MODEL_MANAGEMENT_ENABLED) && manifest.agents.find(({ agentId }) => agentId === manifest.defaultAgentId)?.runtime) throw new Error("RIVUS_MODEL_MANAGEMENT_ENABLED requires a Pi default Agent");
608
644
  return {
609
- message: "enabled Endpoint credential references resolve",
645
+ message: "Endpoint credentials and Agent runtime environment references resolve",
610
646
  name: "credentials",
611
647
  status: "pass"
612
648
  };
613
649
  },
614
650
  catch: toError$2
615
651
  }).pipe(Effect.catch((error) => Effect.succeed({
616
- message: `enabled Endpoint credentials are incomplete: ${formatError(error)}`,
652
+ message: `deployment environment is incomplete: ${formatError(error)}`,
617
653
  name: "credentials",
618
654
  status: "fail"
619
655
  })));
620
656
  }
621
- function defaultResolveModule(specifier, packageManifestPath) {
622
- if (!packageManifestPath) return Effect.fail(/* @__PURE__ */ new Error("Rivus package manifest path is required for trusted module resolution"));
657
+ function defaultResolveModule(specifier, packageManifestPath, homeDirectory) {
658
+ const homeLocal = isAbsolute(specifier);
659
+ if (!homeLocal && !packageManifestPath) return Effect.fail(/* @__PURE__ */ new Error("Rivus package manifest path is required for trusted module resolution"));
623
660
  return Effect.gen(function* () {
624
661
  const resolvedRealpath = yield* Effect.tryPromise({
625
662
  try: () => realpath(fileURLToPath(import.meta.resolve(specifier))),
626
663
  catch: toError$2
627
664
  });
628
- return yield* validateTrustedModulePath(yield* findTrustedPackageRoot(packageManifestPath), resolvedRealpath, `module ${specifier}`);
665
+ return yield* validateTrustedModulePath(homeLocal ? yield* Effect.tryPromise({
666
+ try: () => realpath(homeDirectory),
667
+ catch: toError$2
668
+ }) : yield* findTrustedPackageRoot(packageManifestPath), resolvedRealpath, `module ${specifier}`);
629
669
  });
630
670
  }
631
671
  function toError$2(error) {
@@ -659,7 +699,7 @@ function loadRivusHome(directoryPath) {
659
699
  });
660
700
  }
661
701
  function parseRivusHomeConfig(value) {
662
- const config = record(value, "Rivus Home config");
702
+ const config = record$1(value, "Rivus Home config");
663
703
  if (config.version !== 1) throw new Error("Rivus Home config version must be 1");
664
704
  return {
665
705
  bootstrap: nonEmptyString(config.bootstrap, "bootstrap"),
@@ -691,7 +731,7 @@ function nonEmptyString(value, owner) {
691
731
  if (typeof value !== "string" || !value.trim()) throw new Error(`Rivus Home ${owner} must be a non-empty string`);
692
732
  return value;
693
733
  }
694
- function record(value, owner) {
734
+ function record$1(value, owner) {
695
735
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${owner} must be an object`);
696
736
  return value;
697
737
  }
@@ -802,7 +842,7 @@ function createRivusHomeLayout() {
802
842
  }
803
843
  function homeConfig() {
804
844
  return `${JSON.stringify({
805
- bootstrap: "@rivus/gateway/bootstrap/pi-feishu",
845
+ bootstrap: "@rivus/gateway/bootstrap/feishu",
806
846
  envFile: ".env",
807
847
  logs: "logs",
808
848
  manifest: "rivus.config.json",
@@ -955,6 +995,195 @@ function createNodeRivusHome(options) {
955
995
  setup: initializeRivusHome
956
996
  };
957
997
  }
998
+ //#endregion
999
+ //#region src/adapters/cli/recovery/rivus-recovery-cli.ts
1000
+ function createRivusRecoveryCliParser() {
1001
+ const input = { recoveryList: false };
1002
+ return {
1003
+ build: () => buildCommand(input),
1004
+ consume: (argument, next) => consumeArgument(input, argument, next)
1005
+ };
1006
+ }
1007
+ async function runRivusRecoveryCliCommand(control, command) {
1008
+ switch (command.type) {
1009
+ case "inspect": return Effect.runPromise(control.inspect());
1010
+ case "grant-automation-attempt": return Effect.runPromise(control.grantAutomationAttempt({
1011
+ actorId: "local-cli",
1012
+ automationId: command.automationId,
1013
+ expectedRevision: command.expectedRevision,
1014
+ note: await readPrivateTextFile(command.noteFilePath, "Recovery note", 16384),
1015
+ occurrence: command.occurrence
1016
+ }));
1017
+ case "requeue-dead-letter": return Effect.runPromise(control.requeueDeadLetter({
1018
+ actorId: "local-cli",
1019
+ deliveryId: command.deliveryId,
1020
+ endpointId: command.endpointId,
1021
+ expectedRevision: command.expectedRevision,
1022
+ note: await readPrivateTextFile(command.noteFilePath, "Recovery note", 16384)
1023
+ }));
1024
+ case "resolve-tool-operation": {
1025
+ const note = await readPrivateTextFile(command.noteFilePath, "Recovery note", 16384);
1026
+ const outcome = command.outcome.status === "applied" ? {
1027
+ result: parseToolResult(await readPrivateTextFile(command.outcome.resultFilePath, "Tool result", 1048576)),
1028
+ status: "applied"
1029
+ } : command.outcome;
1030
+ return Effect.runPromise(control.resolveToolOperation({
1031
+ actorId: "local-cli",
1032
+ expectedRevision: command.expectedRevision,
1033
+ instanceId: command.instanceId,
1034
+ note,
1035
+ operationId: command.operationId,
1036
+ outcome
1037
+ }));
1038
+ }
1039
+ }
1040
+ }
1041
+ function consumeArgument(input, argument, next) {
1042
+ if (argument === "--recovery-list") {
1043
+ input.recoveryList = true;
1044
+ return {
1045
+ consumed: 0,
1046
+ handled: true
1047
+ };
1048
+ }
1049
+ for (const [flag, key] of [
1050
+ ["--grant-automation-attempt", "grantAutomationAttemptId"],
1051
+ ["--occurrence", "occurrence"],
1052
+ ["--requeue-dead-letter", "requeueDeadLetterId"],
1053
+ ["--resolve-tool-operation", "resolveToolOperationId"],
1054
+ ["--endpoint-id", "endpointId"],
1055
+ ["--instance-id", "instanceId"],
1056
+ ["--expected-revision", "expectedRevision"],
1057
+ ["--recovery-note-file", "recoveryNoteFile"],
1058
+ ["--tool-outcome", "toolOutcome"],
1059
+ ["--tool-result-file", "toolResultFile"]
1060
+ ]) {
1061
+ if (argument === flag) {
1062
+ if (!next || next.startsWith("--")) return {
1063
+ consumed: 0,
1064
+ error: `${flag} requires a value`,
1065
+ handled: true
1066
+ };
1067
+ input[key] = next;
1068
+ return {
1069
+ consumed: 1,
1070
+ handled: true
1071
+ };
1072
+ }
1073
+ if (argument?.startsWith(`${flag}=`)) {
1074
+ const value = argument.slice(flag.length + 1);
1075
+ if (!value) return {
1076
+ consumed: 0,
1077
+ error: `${flag} requires a value`,
1078
+ handled: true
1079
+ };
1080
+ input[key] = value;
1081
+ return {
1082
+ consumed: 0,
1083
+ handled: true
1084
+ };
1085
+ }
1086
+ }
1087
+ return {
1088
+ consumed: 0,
1089
+ handled: false
1090
+ };
1091
+ }
1092
+ function buildCommand(input) {
1093
+ const actionCount = Number(input.recoveryList) + Number(input.grantAutomationAttemptId !== void 0) + Number(input.requeueDeadLetterId !== void 0) + Number(input.resolveToolOperationId !== void 0);
1094
+ const hasOptions = input.occurrence !== void 0 || input.endpointId !== void 0 || input.expectedRevision !== void 0 || input.instanceId !== void 0 || input.recoveryNoteFile !== void 0 || input.toolOutcome !== void 0 || input.toolResultFile !== void 0;
1095
+ if (actionCount === 0) return hasOptions ? { error: "Recovery options require --recovery-list, --grant-automation-attempt, --requeue-dead-letter, or --resolve-tool-operation" } : {};
1096
+ if (actionCount > 1) return { error: "Choose only one recovery command" };
1097
+ if (input.recoveryList) return hasOptions ? { error: "--recovery-list does not accept mutation options" } : { command: { type: "inspect" } };
1098
+ const expectedRevision = parsePositiveInteger(input.expectedRevision);
1099
+ if (expectedRevision === void 0) return { error: "Recovery mutations require --expected-revision with a positive integer" };
1100
+ const noteFilePath = input.recoveryNoteFile?.trim();
1101
+ if (!noteFilePath) return { error: "Recovery mutations require --recovery-note-file" };
1102
+ if (input.grantAutomationAttemptId !== void 0) return buildAutomationAttemptCommand(input, expectedRevision, noteFilePath);
1103
+ if (input.occurrence !== void 0) return { error: "--occurrence is only valid with --grant-automation-attempt" };
1104
+ if (input.requeueDeadLetterId !== void 0) return buildDeadLetterCommand(input, expectedRevision, noteFilePath);
1105
+ return buildToolOperationCommand(input, expectedRevision, noteFilePath);
1106
+ }
1107
+ function buildAutomationAttemptCommand(input, expectedRevision, noteFilePath) {
1108
+ const automationId = input.grantAutomationAttemptId?.trim();
1109
+ const occurrence = input.occurrence?.trim();
1110
+ if (!automationId || !occurrence) return { error: "--grant-automation-attempt requires an automation id and --occurrence" };
1111
+ if (input.endpointId !== void 0 || input.instanceId !== void 0 || input.toolOutcome !== void 0 || input.toolResultFile !== void 0) return { error: "--grant-automation-attempt cannot use Endpoint or Tool reconciliation options" };
1112
+ return { command: {
1113
+ automationId,
1114
+ expectedRevision,
1115
+ noteFilePath,
1116
+ occurrence,
1117
+ type: "grant-automation-attempt"
1118
+ } };
1119
+ }
1120
+ function buildDeadLetterCommand(input, expectedRevision, noteFilePath) {
1121
+ const endpointId = input.endpointId?.trim();
1122
+ if (!endpointId) return { error: "--requeue-dead-letter requires --endpoint-id" };
1123
+ if (input.instanceId !== void 0 || input.toolOutcome !== void 0 || input.toolResultFile !== void 0) return { error: "--requeue-dead-letter cannot use Tool reconciliation options" };
1124
+ return { command: {
1125
+ deliveryId: input.requeueDeadLetterId,
1126
+ endpointId,
1127
+ expectedRevision,
1128
+ noteFilePath,
1129
+ type: "requeue-dead-letter"
1130
+ } };
1131
+ }
1132
+ function buildToolOperationCommand(input, expectedRevision, noteFilePath) {
1133
+ const instanceId = input.instanceId?.trim();
1134
+ if (!instanceId) return { error: "--resolve-tool-operation requires --instance-id" };
1135
+ if (input.endpointId !== void 0) return { error: "--resolve-tool-operation cannot use --endpoint-id" };
1136
+ if (input.toolOutcome !== "applied" && input.toolOutcome !== "not-applied") return { error: "--resolve-tool-operation requires --tool-outcome applied or not-applied" };
1137
+ if (input.toolOutcome === "not-applied") {
1138
+ if (input.toolResultFile !== void 0) return { error: "--tool-result-file is only valid when --tool-outcome is applied" };
1139
+ return { command: {
1140
+ expectedRevision,
1141
+ instanceId,
1142
+ noteFilePath,
1143
+ operationId: input.resolveToolOperationId,
1144
+ outcome: { status: "not-applied" },
1145
+ type: "resolve-tool-operation"
1146
+ } };
1147
+ }
1148
+ const resultFilePath = input.toolResultFile?.trim();
1149
+ if (!resultFilePath) return { error: "--tool-outcome applied requires --tool-result-file" };
1150
+ return { command: {
1151
+ expectedRevision,
1152
+ instanceId,
1153
+ noteFilePath,
1154
+ operationId: input.resolveToolOperationId,
1155
+ outcome: {
1156
+ resultFilePath,
1157
+ status: "applied"
1158
+ },
1159
+ type: "resolve-tool-operation"
1160
+ } };
1161
+ }
1162
+ function parsePositiveInteger(value) {
1163
+ const number = value && /^[1-9]\d*$/.test(value) ? Number(value) : void 0;
1164
+ return Number.isSafeInteger(number) ? number : void 0;
1165
+ }
1166
+ async function readPrivateTextFile(filePath, label, maxBytes) {
1167
+ const handle = await open(filePath, constants$1.O_RDONLY | constants$1.O_NOFOLLOW);
1168
+ try {
1169
+ const metadata = await handle.stat();
1170
+ if (!metadata.isFile()) throw new Error(`${label} must be a regular file`);
1171
+ if ((metadata.mode & 127) !== 0) throw new Error(`${label} file permissions must be 0600 or stricter`);
1172
+ if (metadata.size > maxBytes) throw new Error(`${label} file exceeds ${maxBytes} bytes`);
1173
+ const value = (await handle.readFile("utf8")).trim();
1174
+ if (!value) throw new Error(`${label} file must not be empty`);
1175
+ return value;
1176
+ } finally {
1177
+ await handle.close();
1178
+ }
1179
+ }
1180
+ function parseToolResult(value) {
1181
+ try {
1182
+ return JSON.parse(value);
1183
+ } catch {
1184
+ throw new Error("Tool result file must contain valid JSON");
1185
+ }
1186
+ }
958
1187
  const RIVUS_AUDIO_CLI_USAGE = `Usage:
959
1188
  rivus audio install [--force] [--json]
960
1189
  rivus audio status
@@ -1005,548 +1234,83 @@ function renderRivusAudioCliNotInstalled() {
1005
1234
  return "audio transcriber is not installed; run: rivus audio install\n";
1006
1235
  }
1007
1236
  //#endregion
1008
- //#region src/adapters/cli/audio/rivus-audio-install-lock.ts
1009
- var RivusAudioInstallInProgressError = class extends Error {
1010
- constructor() {
1011
- super("another audio transcriber installation is in progress");
1012
- this.name = "RivusAudioInstallInProgressError";
1013
- }
1014
- };
1015
- const lockOwnerSchema = Schema.fromJsonString(Schema.Struct({
1016
- pid: Schema.Int,
1017
- startedAt: Schema.Number,
1018
- token: Schema.NonEmptyString
1019
- }));
1020
- /**
1021
- * Takes the installation lock at `path`: a directory holding one owner record named by the owner's token. The record
1022
- * is written into a private draft directory that is then renamed onto `path`, which succeeds only while `path` is
1023
- * absent or empty, so a reader never observes a partially written lock. A lock whose pid is dead, whose record is
1024
- * unreadable, or which is older than `maxAgeMs` is reclaimed by removing that record by name and then `path` only
1025
- * while it is empty, so a reclaim based on an outdated reading never removes another installer's live lock.
1026
- */
1027
- async function acquireRivusAudioInstallLock(path, options) {
1028
- const now = options.now ?? Date.now;
1029
- const isProcessAlive = options.isProcessAlive ?? isLiveProcess;
1030
- const owner = {
1031
- pid: process.pid,
1032
- startedAt: now(),
1033
- token: randomUUID()
1034
- };
1035
- const draft = `${path}.${owner.token}.draft`;
1036
- await mkdir(draft, { mode: 448 });
1037
- try {
1038
- await writeFile(join(draft, owner.token), `${JSON.stringify(owner)}\n`, {
1039
- flag: "wx",
1040
- mode: 384
1237
+ //#region src/adapters/cli/audio/rivus-audio-cli.ts
1238
+ /** Runs one parsed `rivus audio` command and returns its exit code; installation failures are thrown. */
1239
+ async function runRivusAudioCliCommand(command, context) {
1240
+ if (command.operation === "install") {
1241
+ const result = await installRivusAudioTranscriber({
1242
+ assetDirectory: context.assetDirectory,
1243
+ env: context.env,
1244
+ force: command.force,
1245
+ installRoot: context.installRoot,
1246
+ nodeExecutable: context.nodeExecutable,
1247
+ runProcess: context.runProcess,
1248
+ ...context.signal ? { signal: context.signal } : {}
1041
1249
  });
1042
- for (let attempt = 0; attempt < 3; attempt += 1) {
1043
- if (await tryPublish(draft, path)) return { release: () => removeRecords(path, [owner.token]) };
1044
- const records = await readLockRecords(path);
1045
- if (records.some(({ owner: held }) => held !== void 0 && held.pid !== process.pid && isProcessAlive(held.pid) && now() - held.startedAt < options.maxAgeMs)) throw new RivusAudioInstallInProgressError();
1046
- await removeRecords(path, records.map(({ name }) => name));
1047
- }
1048
- } finally {
1049
- await rm(draft, {
1050
- force: true,
1051
- recursive: true
1052
- }).catch(() => void 0);
1250
+ context.stdout.write(renderRivusAudioCliInstallResult(result, command.json));
1251
+ return 0;
1053
1252
  }
1054
- throw new RivusAudioInstallInProgressError();
1055
- }
1056
- async function tryPublish(draft, path) {
1057
- try {
1058
- await rename(draft, path);
1059
- return true;
1060
- } catch (error) {
1061
- if (hasErrorCode(error, "EEXIST") || hasErrorCode(error, "ENOTEMPTY")) return false;
1062
- throw error;
1253
+ if (command.operation === "status") {
1254
+ context.stdout.write(renderRivusAudioCliStatus(await readRivusAudioStatus(context.installRoot, context.assetDirectory)));
1255
+ return 0;
1063
1256
  }
1064
- }
1065
- async function readLockRecords(path) {
1066
- const names = await readdir(path).catch((error) => {
1067
- if (hasErrorCode(error, "ENOENT")) return [];
1068
- throw error;
1257
+ const release = await readRivusAudioInstalledRelease(context.installRoot);
1258
+ if (release === void 0) {
1259
+ context.stderr.write(renderRivusAudioCliNotInstalled());
1260
+ return 3;
1261
+ }
1262
+ const exitCode = await runRivusAudioPassthroughProcess({
1263
+ args: [join(release.directory, "transcribe.mjs"), resolve(context.cwd, command.path)],
1264
+ command: context.nodeExecutable,
1265
+ cwd: release.directory,
1266
+ env: context.env,
1267
+ ...context.signal ? { signal: context.signal } : {},
1268
+ stderr: context.stderr,
1269
+ stdout: context.stdout
1069
1270
  });
1070
- return Promise.all(names.map(async (name) => {
1071
- const text = await readPersistenceFile(join(path, name));
1072
- return {
1073
- name,
1074
- owner: text === void 0 ? void 0 : Option.getOrUndefined(Schema.decodeUnknownOption(lockOwnerSchema)(text))
1075
- };
1076
- }));
1271
+ return exitCode === 0 || exitCode === 1 || exitCode === 2 ? exitCode : 1;
1077
1272
  }
1078
- /**
1079
- * Removes the named owner records and then the lock directory only if nothing else is in it, so a record that another
1080
- * installer published meanwhile keeps the lock held.
1081
- */
1082
- async function removeRecords(path, names) {
1083
- await Promise.all(names.map((name) => unlink(join(path, name)).catch(ignoreErrorCodes("ENOENT"))));
1084
- await rmdir(path).catch(ignoreErrorCodes("ENOENT", "ENOTEMPTY", "EEXIST"));
1085
- }
1086
- function ignoreErrorCodes(...codes) {
1087
- return (error) => {
1088
- if (!codes.some((code) => hasErrorCode(error, code))) throw error;
1089
- };
1273
+ //#endregion
1274
+ //#region src/adapters/cli/command/rivus-cli-protocol.ts
1275
+ const RIVUS_CLI_USAGE = `Usage:
1276
+ rivus setup [directory]
1277
+ rivus upgrade [--json]
1278
+ rivus start
1279
+ rivus status
1280
+ rivus check-config [--load-plugins]
1281
+ rivus recovery <recovery options>
1282
+ rivus init [directory]
1283
+ rivus doctor [directory] [--env-file <path>]
1284
+ rivus model <status|set|rollback> ...
1285
+ rivus audio <install|status|transcribe> ...
1286
+ rivus --bootstrap <module> [--manifest <rivus.config.json>] [options]
1287
+
1288
+ Commands:
1289
+ setup Create Rivus Home (default ~/.rivus-agent) without overwriting files
1290
+ upgrade Upgrade the managed Home service to the latest stable release
1291
+ start Start the Rivus Home deployment in the foreground
1292
+ status Print Rivus Home deployment status without activating Endpoints
1293
+ check-config
1294
+ Validate and print the redacted Rivus Home manifest; optionally load and resolve Plugins
1295
+ recovery Inspect or recover local state after stopping the Home daemon
1296
+ init Create a standalone local Rivus project without overwriting files
1297
+ doctor Check Rivus Home by default, or an explicit standalone project directory
1298
+ model Query or change the managed default model through the current Home
1299
+ audio Install, inspect, or run the managed audio transcriber of the current Home
1300
+
1301
+ Run rivus --help for the complete daemon option list.
1302
+ `;
1303
+ function renderRivusCliError(error) {
1304
+ return `${error instanceof Error ? error.message : String(error)}\n`;
1090
1305
  }
1091
- function isLiveProcess(pid) {
1092
- try {
1093
- process.kill(pid, 0);
1094
- return true;
1095
- } catch (error) {
1096
- return hasErrorCode(error, "EPERM");
1097
- }
1306
+ function renderRivusCliUnknownCommand(command) {
1307
+ return `Unknown command: ${command}\n\n${RIVUS_CLI_USAGE}`;
1098
1308
  }
1099
- function hasErrorCode(error, code) {
1100
- return error?.code === code;
1101
- }
1102
- //#endregion
1103
- //#region src/adapters/cli/audio/rivus-audio-release.ts
1104
- const RIVUS_AUDIO_MANIFEST_FILE = "manifest.json";
1105
- const RIVUS_AUDIO_RELEASES_DIRECTORY = "releases";
1106
- const manifestSchema = Schema.fromJsonString(Schema.Struct({
1107
- id: Schema.NonEmptyString,
1108
- smoke: Schema.Struct({
1109
- expect: Schema.NonEmptyString,
1110
- input: Schema.NonEmptyString
1111
- })
1112
- }));
1113
- const currentSchema = Schema.fromJsonString(Schema.Struct({
1114
- digest: Schema.optional(Schema.NonEmptyString),
1115
- id: Schema.NonEmptyString,
1116
- release: Schema.NonEmptyString
1117
- }));
1118
- function rivusAudioCurrentPath(installRoot) {
1119
- return join(installRoot, "current.json");
1120
- }
1121
- async function readRivusAudioReleaseManifest(directory) {
1122
- const path = join(directory, RIVUS_AUDIO_MANIFEST_FILE);
1123
- const manifest = Option.getOrUndefined(Schema.decodeUnknownOption(manifestSchema)(await readFile(path, "utf8")));
1124
- if (manifest === void 0 || !isStrictlyWithin(directory, resolve(directory, manifest.smoke.input))) throw new Error(`audio transcriber manifest is invalid: ${path}`);
1125
- return manifest;
1126
- }
1127
- /**
1128
- * Whether an entry of the asset directory, at any depth, belongs in a release. Dependencies come from the shrinkwrap
1129
- * and colocated tests stay out of the published package, so a release never contains either and a workspace checkout
1130
- * produces the same release and digest as the published package.
1131
- */
1132
- function isRivusAudioReleaseAsset(name) {
1133
- return name !== "node_modules" && !name.endsWith(".test.ts");
1134
- }
1135
- /**
1136
- * Digests the asset files that an installation copies, so an asset change reinstalls the transcriber even when the
1137
- * manifest id stays the same.
1138
- */
1139
- async function readRivusAudioAssetDigest(directory) {
1140
- const hash = createHash("sha256");
1141
- for (const file of (await listAssetFiles(directory, "")).sort()) {
1142
- const content = await readFile(join(directory, file));
1143
- hash.update(`${file}\0${String(content.length)}\0`).update(content);
1144
- }
1145
- return hash.digest("hex");
1146
- }
1147
- /**
1148
- * Reads the release that current.json selects. A missing or malformed record, a release outside `releases/`, or a
1149
- * missing release directory all mean "not installed", which a reinstall repairs.
1150
- */
1151
- async function readRivusAudioInstalledRelease(installRoot) {
1152
- const text = await readPersistenceFile(rivusAudioCurrentPath(installRoot));
1153
- const current = text === void 0 ? void 0 : Option.getOrUndefined(Schema.decodeUnknownOption(currentSchema)(text));
1154
- if (current === void 0) return;
1155
- const directory = resolve(installRoot, current.release);
1156
- if (!isStrictlyWithin(join(installRoot, "releases"), directory)) return;
1157
- return await stat(directory).then((info) => info.isDirectory(), () => false) ? {
1158
- ...current.digest === void 0 ? {} : { digest: current.digest },
1159
- directory,
1160
- id: current.id,
1161
- release: current.release
1162
- } : void 0;
1163
- }
1164
- async function readRivusAudioStatus(installRoot, assetDirectory) {
1165
- const expected = await readRivusAudioReleaseManifest(assetDirectory);
1166
- const expectedDigest = await readRivusAudioAssetDigest(assetDirectory);
1167
- const installed = await readRivusAudioInstalledRelease(installRoot);
1168
- return installed === void 0 ? {
1169
- installed: false,
1170
- expectedId: expected.id,
1171
- expectedDigest,
1172
- upToDate: false
1173
- } : {
1174
- installed: true,
1175
- id: installed.id,
1176
- ...installed.digest === void 0 ? {} : { digest: installed.digest },
1177
- release: installed.directory,
1178
- expectedId: expected.id,
1179
- expectedDigest,
1180
- upToDate: installed.id === expected.id && installed.digest === expectedDigest
1181
- };
1182
- }
1183
- /** Lists the release asset files by relative path with "/" separators. */
1184
- async function listAssetFiles(root, prefix) {
1185
- const entries = await readdir(join(root, prefix), { withFileTypes: true });
1186
- return (await Promise.all(entries.filter((entry) => isRivusAudioReleaseAsset(entry.name)).map(async (entry) => {
1187
- const path = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
1188
- return entry.isDirectory() ? listAssetFiles(root, path) : [path];
1189
- }))).flat();
1190
- }
1191
- function isStrictlyWithin(root, candidate) {
1192
- return candidate !== resolve(root) && isPathWithin(root, candidate);
1193
- }
1194
- //#endregion
1195
- //#region src/adapters/cli/audio/rivus-audio-installer.ts
1196
- const INSTALL_DEADLINE_MS = 15e5;
1197
- const NPM_TIMEOUT_MS = 3e5;
1198
- const FETCH_TIMEOUT_MS = 12e5;
1199
- const SMOKE_TIMEOUT_MS = 3e5;
1200
- const STALE_LOCK_MS = 2 * INSTALL_DEADLINE_MS;
1201
- const LOCK_POLL_MS = 2e3;
1202
- const STAGING_PREFIX = "staging-";
1203
- var RivusAudioInstallStepError = class extends Error {
1204
- step;
1205
- constructor(step, reason, output = "") {
1206
- const detail = output.trim().slice(-4e3);
1207
- super(`audio transcriber installation failed at ${step}: ${reason}${detail ? `\n${detail}` : ""}`);
1208
- this.name = "RivusAudioInstallStepError";
1209
- this.step = step;
1210
- }
1211
- };
1212
- /**
1213
- * Builds a release in a staging directory beside `releases/`, smoke-tests it, then publishes it by renaming the
1214
- * directory and atomically replacing current.json. A failure before current.json changes leaves the previous release
1215
- * selected and removes the staging directory. While another installer holds the lock, this one waits within its
1216
- * deadline and then rechecks current.json, so it does not rebuild a release that installer just published.
1217
- */
1218
- async function installRivusAudioTranscriber(options) {
1219
- const now = options.now ?? Date.now;
1220
- const deadlineMs = options.deadlineMs ?? INSTALL_DEADLINE_MS;
1221
- const deadline = {
1222
- at: now() + deadlineMs,
1223
- ms: deadlineMs,
1224
- now
1225
- };
1226
- const root = resolve(options.installRoot);
1227
- await mkdir(root, { recursive: true });
1228
- const lock = await acquireLockWhenFree(root, options, deadline);
1229
- try {
1230
- await removeInterruptedStaging(root);
1231
- const manifest = await readRivusAudioReleaseManifest(options.assetDirectory);
1232
- const digest = await readRivusAudioAssetDigest(options.assetDirectory);
1233
- const previous = await readRivusAudioInstalledRelease(root);
1234
- if (!options.force && previous?.id === manifest.id && previous.digest === digest) return {
1235
- status: "already-installed",
1236
- id: previous.id,
1237
- release: previous.directory
1238
- };
1239
- const release = await buildRelease(root, manifest, digest, options, deadline);
1240
- await pruneReleases(root, [release, previous?.directory]);
1241
- return {
1242
- status: "installed",
1243
- id: manifest.id,
1244
- release
1245
- };
1246
- } finally {
1247
- await lock.release().catch(() => void 0);
1248
- }
1249
- }
1250
- async function acquireLockWhenFree(root, options, deadline) {
1251
- const sleep = options.sleep ?? ((ms) => sleepUnlessAborted(ms, options.signal));
1252
- for (;;) {
1253
- try {
1254
- return await acquireRivusAudioInstallLock(join(root, "install.lock"), {
1255
- maxAgeMs: STALE_LOCK_MS,
1256
- ...options.isProcessAlive ? { isProcessAlive: options.isProcessAlive } : {}
1257
- });
1258
- } catch (error) {
1259
- if (!(error instanceof RivusAudioInstallInProgressError)) throw error;
1260
- }
1261
- const remainingMs = deadline.at - deadline.now();
1262
- if (remainingMs <= 0) throw new Error("another audio transcriber installation did not finish in time");
1263
- await sleep(Math.min(LOCK_POLL_MS, remainingMs));
1264
- if (options.signal?.aborted) throw new Error("audio transcriber installation was interrupted while waiting for another installation");
1265
- }
1266
- }
1267
- function sleepUnlessAborted(ms, signal) {
1268
- return setTimeout$1(ms, void 0, signal ? { signal } : {}).catch(() => void 0);
1269
- }
1270
- async function buildRelease(root, manifest, digest, options, deadline) {
1271
- const staging = join(root, `${STAGING_PREFIX}${randomUUID()}`);
1272
- const release = join(root, RIVUS_AUDIO_RELEASES_DIRECTORY, `${manifest.id.replaceAll(/[^\w.-]/g, "_")}-${digest.slice(0, 12)}-${randomUUID().slice(0, 8)}`);
1273
- const env = withNodeOnPath(options.env, options.nodeExecutable);
1274
- let renamed = false;
1275
- try {
1276
- await cp(options.assetDirectory, staging, {
1277
- filter: (source) => isRivusAudioReleaseAsset(basename(source)),
1278
- recursive: true
1279
- }).catch((error) => {
1280
- throw new RivusAudioInstallStepError("copy assets", errorMessage(error));
1281
- });
1282
- await runStep(options, deadline, "npm ci", {
1283
- args: [
1284
- "ci",
1285
- "--ignore-scripts",
1286
- "--omit=dev",
1287
- "--no-audit",
1288
- "--no-fund"
1289
- ],
1290
- command: "npm",
1291
- cwd: staging,
1292
- env,
1293
- timeoutMs: NPM_TIMEOUT_MS
1294
- });
1295
- await runStep(options, deadline, "model download", {
1296
- args: [
1297
- "fetch-model.mjs",
1298
- RIVUS_AUDIO_MANIFEST_FILE,
1299
- "model"
1300
- ],
1301
- command: options.nodeExecutable,
1302
- cwd: staging,
1303
- env,
1304
- timeoutMs: FETCH_TIMEOUT_MS
1305
- });
1306
- const { RIVUS_AUDIO_LANGUAGE: _language, ...smokeEnv } = env;
1307
- const smoke = await runStep(options, deadline, "smoke test", {
1308
- args: ["transcribe.mjs", resolve(staging, manifest.smoke.input)],
1309
- command: options.nodeExecutable,
1310
- cwd: staging,
1311
- env: smokeEnv,
1312
- timeoutMs: SMOKE_TIMEOUT_MS
1313
- });
1314
- if (smoke.stderrTail !== "") throw new RivusAudioInstallStepError("smoke test", "the transcriber wrote to stderr", smoke.stderrTail);
1315
- if (!smoke.stdout.includes(manifest.smoke.expect)) throw new RivusAudioInstallStepError("smoke test", `the transcript does not contain ${JSON.stringify(manifest.smoke.expect)}`, smoke.stdout);
1316
- await mkdir(dirname(release), { recursive: true });
1317
- await rename(staging, release);
1318
- renamed = true;
1319
- await writeAtomicTextFile(rivusAudioCurrentPath(root), `${JSON.stringify({
1320
- id: manifest.id,
1321
- digest,
1322
- release: relative(root, release)
1323
- })}\n`, { durable: true });
1324
- return release;
1325
- } catch (error) {
1326
- if ((renamed ? await readRivusAudioInstalledRelease(root).then((installed) => installed?.directory, () => void 0) : void 0) !== release) await rm(renamed ? release : staging, {
1327
- force: true,
1328
- recursive: true
1329
- }).catch(() => void 0);
1330
- throw error instanceof RivusAudioInstallStepError ? error : new RivusAudioInstallStepError("publish", errorMessage(error));
1331
- }
1332
- }
1333
- async function runStep(options, deadline, step, request) {
1334
- if (options.signal?.aborted) throw new RivusAudioInstallStepError(step, "interrupted");
1335
- const deadlineReason = `the installation did not finish within ${seconds(deadline.ms)} s`;
1336
- const remainingMs = deadline.at - deadline.now();
1337
- if (remainingMs <= 0) throw new RivusAudioInstallStepError(step, deadlineReason);
1338
- const timeoutMs = Math.min(request.timeoutMs, remainingMs);
1339
- const result = await options.runProcess({
1340
- ...request,
1341
- timeoutMs,
1342
- ...options.signal ? { signal: options.signal } : {}
1343
- }).catch((error) => {
1344
- throw new RivusAudioInstallStepError(step, `could not start ${request.command}: ${errorMessage(error)}`);
1345
- });
1346
- if (result.outcome === "timed-out") throw new RivusAudioInstallStepError(step, timeoutMs < request.timeoutMs ? deadlineReason : `timed out after ${seconds(request.timeoutMs)} s`, result.stderrTail);
1347
- if (result.outcome === "interrupted") throw new RivusAudioInstallStepError(step, "interrupted", result.stderrTail);
1348
- if (result.exitCode !== 0) throw new RivusAudioInstallStepError(step, `exited with code ${String(result.exitCode)}`, result.stderrTail);
1349
- return result;
1350
- }
1351
- async function removeInterruptedStaging(root) {
1352
- const entries = await readdir(root);
1353
- await Promise.all(entries.filter((name) => name.startsWith(STAGING_PREFIX)).map((name) => join(root, name)).map((path) => rm(path, {
1354
- force: true,
1355
- maxRetries: 5,
1356
- recursive: true
1357
- }).catch((error) => {
1358
- throw new RivusAudioInstallStepError("staging cleanup", `could not remove the staging directory of an interrupted installation, ${path}: ${errorMessage(error)}`);
1359
- })));
1360
- }
1361
- /** Keeps the new and the previous release, so a transcription that started before the switch can still finish. */
1362
- async function pruneReleases(root, keep) {
1363
- const directory = join(root, RIVUS_AUDIO_RELEASES_DIRECTORY);
1364
- const kept = new Set(keep.filter((path) => path !== void 0));
1365
- const entries = await readdir(directory).catch(() => []);
1366
- await Promise.all(entries.map((name) => join(directory, name)).filter((path) => !kept.has(path)).map((path) => rm(path, {
1367
- force: true,
1368
- recursive: true
1369
- }).catch(() => void 0)));
1370
- }
1371
- /** npm may be missing from a service PATH, but it is installed beside the running Node executable. */
1372
- function withNodeOnPath(env, nodeExecutable) {
1373
- const nodeDirectory = dirname(nodeExecutable);
1374
- return {
1375
- ...env,
1376
- PATH: env.PATH ? `${nodeDirectory}${delimiter}${env.PATH}` : nodeDirectory
1377
- };
1378
- }
1379
- function seconds(ms) {
1380
- return String(ms / 1e3);
1381
- }
1382
- function errorMessage(error) {
1383
- return error instanceof Error ? error.message : String(error);
1384
- }
1385
- //#endregion
1386
- //#region src/adapters/cli/audio/rivus-audio-process.ts
1387
- const OUTPUT_LIMIT = 65536;
1388
- const KILL_GRACE_MS = 2e3;
1389
- /**
1390
- * Runs one installation step. This CLI's own timeout or interruption signals only the step process, so a step must not
1391
- * start processes of its own: npm ci runs with --ignore-scripts and the asset scripts are plain Node.
1392
- */
1393
- function runRivusAudioProcess(request) {
1394
- return new Promise((resolve, reject) => {
1395
- let stdout = "";
1396
- let stderrTail = "";
1397
- const child = spawnInCallerGroup(request, (text) => {
1398
- stdout = stdout.length >= OUTPUT_LIMIT ? stdout : (stdout + text).slice(0, OUTPUT_LIMIT);
1399
- }, (text) => {
1400
- stderrTail = (stderrTail + text).slice(-65536);
1401
- });
1402
- let outcome = "exited";
1403
- let exitCode = null;
1404
- let exited = false;
1405
- let escalation;
1406
- const stop = (reason) => {
1407
- if (exited || outcome !== "exited") return;
1408
- outcome = reason;
1409
- child.kill("SIGTERM");
1410
- escalation = setTimeout(() => child.kill("SIGKILL"), KILL_GRACE_MS);
1411
- };
1412
- const onAbort = () => stop("interrupted");
1413
- const timeout = setTimeout(() => stop("timed-out"), request.timeoutMs);
1414
- const finish = () => {
1415
- clearTimeout(timeout);
1416
- clearTimeout(escalation);
1417
- request.signal?.removeEventListener("abort", onAbort);
1418
- };
1419
- request.signal?.addEventListener("abort", onAbort, { once: true });
1420
- if (request.signal?.aborted) onAbort();
1421
- child.once("exit", (code) => {
1422
- exited = true;
1423
- exitCode = code;
1424
- });
1425
- child.once("error", (error) => {
1426
- finish();
1427
- reject(error);
1428
- });
1429
- child.once("close", () => {
1430
- finish();
1431
- resolve({
1432
- exitCode,
1433
- outcome,
1434
- stderrTail,
1435
- stdout
1436
- });
1437
- });
1438
- });
1439
- }
1440
- /** Streams the transcriber's stdout and stderr to the caller and resolves with its exit code. */
1441
- function runRivusAudioPassthroughProcess(request) {
1442
- return new Promise((resolve, reject) => {
1443
- const child = spawnInCallerGroup(request, (text) => request.stdout.write(text), (text) => request.stderr.write(text));
1444
- const onAbort = () => {
1445
- child.kill("SIGTERM");
1446
- };
1447
- request.signal?.addEventListener("abort", onAbort, { once: true });
1448
- child.once("error", (error) => {
1449
- request.signal?.removeEventListener("abort", onAbort);
1450
- reject(error);
1451
- });
1452
- child.once("close", (code) => {
1453
- request.signal?.removeEventListener("abort", onAbort);
1454
- resolve(code);
1455
- });
1456
- });
1457
- }
1458
- /**
1459
- * Starts a child in the caller's process group, because Pi stops a timed-out or aborted bash command by killing that
1460
- * group and the child must stop with it.
1461
- */
1462
- function spawnInCallerGroup(request, onStdout, onStderr) {
1463
- const child = spawn(request.command, [...request.args], {
1464
- cwd: request.cwd,
1465
- env: { ...request.env },
1466
- stdio: [
1467
- "ignore",
1468
- "pipe",
1469
- "pipe"
1470
- ]
1471
- });
1472
- child.stdout.setEncoding("utf8").on("data", onStdout);
1473
- child.stderr.setEncoding("utf8").on("data", onStderr);
1474
- return child;
1475
- }
1476
- //#endregion
1477
- //#region src/adapters/cli/audio/rivus-audio-cli.ts
1478
- /** Runs one parsed `rivus audio` command and returns its exit code; installation failures are thrown. */
1479
- async function runRivusAudioCliCommand(command, context) {
1480
- if (command.operation === "install") {
1481
- const result = await installRivusAudioTranscriber({
1482
- assetDirectory: context.assetDirectory,
1483
- env: context.env,
1484
- force: command.force,
1485
- installRoot: context.installRoot,
1486
- nodeExecutable: context.nodeExecutable,
1487
- runProcess: context.runProcess,
1488
- ...context.signal ? { signal: context.signal } : {}
1489
- });
1490
- context.stdout.write(renderRivusAudioCliInstallResult(result, command.json));
1491
- return 0;
1492
- }
1493
- if (command.operation === "status") {
1494
- context.stdout.write(renderRivusAudioCliStatus(await readRivusAudioStatus(context.installRoot, context.assetDirectory)));
1495
- return 0;
1496
- }
1497
- const release = await readRivusAudioInstalledRelease(context.installRoot);
1498
- if (release === void 0) {
1499
- context.stderr.write(renderRivusAudioCliNotInstalled());
1500
- return 3;
1501
- }
1502
- const exitCode = await runRivusAudioPassthroughProcess({
1503
- args: [join(release.directory, "transcribe.mjs"), resolve(context.cwd, command.path)],
1504
- command: context.nodeExecutable,
1505
- cwd: release.directory,
1506
- env: context.env,
1507
- ...context.signal ? { signal: context.signal } : {},
1508
- stderr: context.stderr,
1509
- stdout: context.stdout
1510
- });
1511
- return exitCode === 0 || exitCode === 1 || exitCode === 2 ? exitCode : 1;
1512
- }
1513
- //#endregion
1514
- //#region src/adapters/cli/command/rivus-cli-protocol.ts
1515
- const RIVUS_CLI_USAGE = `Usage:
1516
- rivus setup [directory]
1517
- rivus start
1518
- rivus status
1519
- rivus check-config
1520
- rivus init [directory]
1521
- rivus doctor [directory] [--env-file <path>]
1522
- rivus model <status|set|rollback> ...
1523
- rivus audio <install|status|transcribe> ...
1524
- rivus --bootstrap <module> [--manifest <rivus.config.json>] [options]
1525
-
1526
- Commands:
1527
- setup Create Rivus Home (default ~/.rivus-agent) without overwriting files
1528
- start Start the Rivus Home deployment in the foreground
1529
- status Print Rivus Home deployment status without activating Endpoints
1530
- check-config
1531
- Validate and print the redacted Rivus Home manifest
1532
- init Create a standalone local Rivus project without overwriting files
1533
- doctor Check Rivus Home by default, or an explicit standalone project directory
1534
- model Query or change the managed default model through the current Home
1535
- audio Install, inspect, or run the managed audio transcriber of the current Home
1536
-
1537
- Run rivus --help for the complete daemon option list.
1538
- `;
1539
- function renderRivusCliError(error) {
1540
- return `${error instanceof Error ? error.message : String(error)}\n`;
1541
- }
1542
- function renderRivusCliUnknownCommand(command) {
1543
- return `Unknown command: ${command}\n\n${RIVUS_CLI_USAGE}`;
1544
- }
1545
- function renderRivusDirectoryCommandUsage(command) {
1546
- return `Usage: rivus ${command} [directory]\n`;
1309
+ function renderRivusDirectoryCommandUsage(command) {
1310
+ return `Usage: rivus ${command} [directory]\n`;
1547
1311
  }
1548
1312
  function renderRivusHomeCommandUsage(command) {
1549
- return `Usage: rivus ${command}\n`;
1313
+ return `Usage: rivus ${command}${command === "recovery" ? " <recovery options>" : command === "check-config" ? " [--load-plugins]" : ""}\n`;
1550
1314
  }
1551
1315
  function renderRivusDoctorUsage() {
1552
1316
  return "Usage: rivus doctor [directory] [--env-file <path>]\n";
@@ -1854,7 +1618,7 @@ const TEMPLATE_FILES = Object.freeze({
1854
1618
  "current-weather.mjs": "current-weather.mjs",
1855
1619
  "https-response-reader.mjs": "https-response-reader.mjs",
1856
1620
  "rivus-agents.plugin.mjs": "rivus-starter.plugin.mjs",
1857
- "rivus.bootstrap.ts": "pi-feishu-deployment.bootstrap.ts"
1621
+ "rivus.bootstrap.ts": "feishu-deployment.bootstrap.ts"
1858
1622
  });
1859
1623
  async function initializeRivusProject(options) {
1860
1624
  const directory = resolve(options.directory);
@@ -2115,7 +1879,7 @@ function createRivusEnvFromOpenClawConfig(openClawConfig, options = {}) {
2115
1879
  const appSecret = requiredString(feishu, "appSecret", "channels.feishu.appSecret");
2116
1880
  const modelReference = findPrimaryModelReference(config);
2117
1881
  const providerId = modelReference ? parseProviderId(modelReference) : void 0;
2118
- const provider = providerId ? optionalRecord(readPath(config, [
1882
+ const provider = providerId ? optionalRecord$1(readPath(config, [
2119
1883
  "models",
2120
1884
  "providers",
2121
1885
  providerId
@@ -2142,8 +1906,8 @@ function formatRivusEnvFile(env) {
2142
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`;
2143
1907
  }
2144
1908
  function findAgentId(config) {
2145
- const agents = optionalRecord(config.agents);
2146
- 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;
2147
1911
  }
2148
1912
  function findPrimaryModelReference(config) {
2149
1913
  const primary = optionalString(readPath(config, [
@@ -2153,15 +1917,15 @@ function findPrimaryModelReference(config) {
2153
1917
  "primary"
2154
1918
  ]));
2155
1919
  if (primary) return primary;
2156
- const providers = optionalRecord(readPath(config, ["models", "providers"]));
1920
+ const providers = optionalRecord$1(readPath(config, ["models", "providers"]));
2157
1921
  if (!providers) return;
2158
1922
  for (const [providerId, provider] of Object.entries(providers)) {
2159
- const model = firstModelId(optionalRecord(provider));
1923
+ const model = firstModelId(optionalRecord$1(provider));
2160
1924
  if (model) return `${providerId}/${model}`;
2161
1925
  }
2162
1926
  }
2163
1927
  function firstModelId(provider) {
2164
- return optionalString(optionalRecord((Array.isArray(provider?.models) ? provider.models : [])[0])?.id);
1928
+ return optionalString(optionalRecord$1((Array.isArray(provider?.models) ? provider.models : [])[0])?.id);
2165
1929
  }
2166
1930
  function parseProviderId(modelReference) {
2167
1931
  const separator = modelReference.indexOf("/");
@@ -2206,7 +1970,7 @@ function readProviderModelThinkingCandidates(config, providerId, modelId) {
2206
1970
  "models"
2207
1971
  ]);
2208
1972
  if (!Array.isArray(providerModels)) return [];
2209
- const model = providerModels.map(optionalRecord).find((candidate) => optionalString(candidate?.id) === modelId);
1973
+ const model = providerModels.map(optionalRecord$1).find((candidate) => optionalString(candidate?.id) === modelId);
2210
1974
  if (!model) return [];
2211
1975
  return [
2212
1976
  model.thinkingLevel,
@@ -2236,17 +2000,17 @@ function optionalString(value) {
2236
2000
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
2237
2001
  }
2238
2002
  function asRecord(value, path) {
2239
- const record = optionalRecord(value);
2003
+ const record = optionalRecord$1(value);
2240
2004
  if (!record) throw new OpenClawEnvImportError(`${path} must be an object`);
2241
2005
  return record;
2242
2006
  }
2243
- function optionalRecord(value) {
2007
+ function optionalRecord$1(value) {
2244
2008
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2245
2009
  }
2246
2010
  function readPath(record, path) {
2247
2011
  let value = record;
2248
2012
  for (const segment of path) {
2249
- const current = optionalRecord(value);
2013
+ const current = optionalRecord$1(value);
2250
2014
  if (!current) return;
2251
2015
  value = current[segment];
2252
2016
  }
@@ -2257,31 +2021,14 @@ function readPath(record, path) {
2257
2021
  async function loadRivusEnvFromOpenClawConfig(filePath, piApiKeyFile) {
2258
2022
  return createRivusEnvFromOpenClawConfig(JSON.parse(await readFile(filePath, "utf8")), piApiKeyFile ? { piApiKeyFile } : {});
2259
2023
  }
2260
- function toRedactedConfig(config) {
2261
- return {
2262
- agentId: config.agentId,
2263
- feishu: {
2264
- appIdPresent: Boolean(config.feishu.appId),
2265
- appSecretPresent: Boolean(config.feishu.appSecret),
2266
- baseUrl: config.feishu.baseUrl,
2267
- cardStreamLeaseMs: config.feishu.cardStreamLeaseMs,
2268
- streamMinIntervalMs: config.feishu.streamMinIntervalMs
2269
- },
2270
- pi: {
2271
- apiKeyPresent: Boolean(config.pi.apiKey),
2272
- ...config.pi.baseUrl ? { baseUrl: config.pi.baseUrl } : {},
2273
- ...config.pi.model ? { model: config.pi.model } : {},
2274
- ...config.pi.thinkingLevel ? { thinkingLevel: config.pi.thinkingLevel } : {}
2275
- }
2276
- };
2277
- }
2278
2024
  function toRedactedDeploymentManifest(manifest) {
2279
2025
  return {
2280
- agents: manifest.agents.map(({ agentId, endpointIds, pluginId, profileId }) => ({
2026
+ agents: manifest.agents.map(({ agentId, endpointIds, pluginId, profileId, runtime }) => ({
2281
2027
  agentId,
2282
2028
  endpointIds,
2283
2029
  pluginId,
2284
- profileId
2030
+ profileId,
2031
+ ...runtime ? { runtime } : {}
2285
2032
  })),
2286
2033
  automations: (manifest.automations ?? []).map(({ agentId, delivery, enabled, id, required, schedule, templateId, timeZone }) => ({
2287
2034
  agentId,
@@ -2310,8 +2057,9 @@ function toRedactedDeploymentManifest(manifest) {
2310
2057
  } } : {},
2311
2058
  defaultAgentId: manifest.defaultAgentId,
2312
2059
  defaultEndpointId: manifest.defaultEndpointId,
2313
- endpoints: manifest.endpoints.map(({ agentId, credentialRef, enabled, id, required, sessionNamespace }) => ({
2060
+ endpoints: manifest.endpoints.map(({ agentId, allowedActors, credentialRef, enabled, id, required, sessionNamespace }) => ({
2314
2061
  agentId,
2062
+ ...allowedActors ? { allowedActorsCount: allowedActors.length } : {},
2315
2063
  credentialRef,
2316
2064
  enabled,
2317
2065
  id,
@@ -2330,170 +2078,8 @@ async function loadCliEnv(envFilePath, overrideEnv) {
2330
2078
  return loadMergedLocalEnvFile(envFilePath, overrideEnv);
2331
2079
  }
2332
2080
  //#endregion
2333
- //#region src/adapters/cli/recovery/rivus-recovery-cli.ts
2334
- function createRivusRecoveryCliParser() {
2335
- const input = { recoveryList: false };
2336
- return {
2337
- build: () => buildCommand(input),
2338
- consume: (argument, next) => consumeArgument(input, argument, next)
2339
- };
2340
- }
2341
- async function runRivusRecoveryCliCommand(control, command) {
2342
- switch (command.type) {
2343
- case "inspect": return Effect.runPromise(control.inspect());
2344
- case "requeue-dead-letter": return Effect.runPromise(control.requeueDeadLetter({
2345
- actorId: "local-cli",
2346
- deliveryId: command.deliveryId,
2347
- endpointId: command.endpointId,
2348
- expectedRevision: command.expectedRevision,
2349
- note: await readPrivateTextFile(command.noteFilePath, "Recovery note", 16384)
2350
- }));
2351
- case "resolve-tool-operation": {
2352
- const note = await readPrivateTextFile(command.noteFilePath, "Recovery note", 16384);
2353
- const outcome = command.outcome.status === "applied" ? {
2354
- result: parseToolResult(await readPrivateTextFile(command.outcome.resultFilePath, "Tool result", 1048576)),
2355
- status: "applied"
2356
- } : command.outcome;
2357
- return Effect.runPromise(control.resolveToolOperation({
2358
- actorId: "local-cli",
2359
- expectedRevision: command.expectedRevision,
2360
- instanceId: command.instanceId,
2361
- note,
2362
- operationId: command.operationId,
2363
- outcome
2364
- }));
2365
- }
2366
- }
2367
- }
2368
- function consumeArgument(input, argument, next) {
2369
- if (argument === "--recovery-list") {
2370
- input.recoveryList = true;
2371
- return {
2372
- consumed: 0,
2373
- handled: true
2374
- };
2375
- }
2376
- for (const [flag, key] of [
2377
- ["--requeue-dead-letter", "requeueDeadLetterId"],
2378
- ["--resolve-tool-operation", "resolveToolOperationId"],
2379
- ["--endpoint-id", "endpointId"],
2380
- ["--instance-id", "instanceId"],
2381
- ["--expected-revision", "expectedRevision"],
2382
- ["--recovery-note-file", "recoveryNoteFile"],
2383
- ["--tool-outcome", "toolOutcome"],
2384
- ["--tool-result-file", "toolResultFile"]
2385
- ]) {
2386
- if (argument === flag) {
2387
- if (!next) return {
2388
- consumed: 0,
2389
- error: `${flag} requires a value`,
2390
- handled: true
2391
- };
2392
- input[key] = next;
2393
- return {
2394
- consumed: 1,
2395
- handled: true
2396
- };
2397
- }
2398
- if (argument?.startsWith(`${flag}=`)) {
2399
- const value = argument.slice(flag.length + 1);
2400
- if (!value) return {
2401
- consumed: 0,
2402
- error: `${flag} requires a value`,
2403
- handled: true
2404
- };
2405
- input[key] = value;
2406
- return {
2407
- consumed: 0,
2408
- handled: true
2409
- };
2410
- }
2411
- }
2412
- return {
2413
- consumed: 0,
2414
- handled: false
2415
- };
2416
- }
2417
- function buildCommand(input) {
2418
- const actionCount = Number(input.recoveryList) + Number(input.requeueDeadLetterId !== void 0) + Number(input.resolveToolOperationId !== void 0);
2419
- const hasOptions = input.endpointId !== void 0 || input.expectedRevision !== void 0 || input.instanceId !== void 0 || input.recoveryNoteFile !== void 0 || input.toolOutcome !== void 0 || input.toolResultFile !== void 0;
2420
- if (actionCount === 0) return hasOptions ? { error: "Recovery options require --recovery-list, --requeue-dead-letter, or --resolve-tool-operation" } : {};
2421
- if (actionCount > 1) return { error: "Choose only one recovery command" };
2422
- if (input.recoveryList) return hasOptions ? { error: "--recovery-list does not accept mutation options" } : { command: { type: "inspect" } };
2423
- const expectedRevision = parsePositiveInteger(input.expectedRevision);
2424
- if (expectedRevision === void 0) return { error: "Recovery mutations require --expected-revision with a positive integer" };
2425
- const noteFilePath = input.recoveryNoteFile?.trim();
2426
- if (!noteFilePath) return { error: "Recovery mutations require --recovery-note-file" };
2427
- if (input.requeueDeadLetterId !== void 0) return buildDeadLetterCommand(input, expectedRevision, noteFilePath);
2428
- return buildToolOperationCommand(input, expectedRevision, noteFilePath);
2429
- }
2430
- function buildDeadLetterCommand(input, expectedRevision, noteFilePath) {
2431
- const endpointId = input.endpointId?.trim();
2432
- if (!endpointId) return { error: "--requeue-dead-letter requires --endpoint-id" };
2433
- if (input.instanceId !== void 0 || input.toolOutcome !== void 0 || input.toolResultFile !== void 0) return { error: "--requeue-dead-letter cannot use Tool reconciliation options" };
2434
- return { command: {
2435
- deliveryId: input.requeueDeadLetterId,
2436
- endpointId,
2437
- expectedRevision,
2438
- noteFilePath,
2439
- type: "requeue-dead-letter"
2440
- } };
2441
- }
2442
- function buildToolOperationCommand(input, expectedRevision, noteFilePath) {
2443
- const instanceId = input.instanceId?.trim();
2444
- if (!instanceId) return { error: "--resolve-tool-operation requires --instance-id" };
2445
- if (input.endpointId !== void 0) return { error: "--resolve-tool-operation cannot use --endpoint-id" };
2446
- if (input.toolOutcome !== "applied" && input.toolOutcome !== "not-applied") return { error: "--resolve-tool-operation requires --tool-outcome applied or not-applied" };
2447
- if (input.toolOutcome === "not-applied") {
2448
- if (input.toolResultFile !== void 0) return { error: "--tool-result-file is only valid when --tool-outcome is applied" };
2449
- return { command: {
2450
- expectedRevision,
2451
- instanceId,
2452
- noteFilePath,
2453
- operationId: input.resolveToolOperationId,
2454
- outcome: { status: "not-applied" },
2455
- type: "resolve-tool-operation"
2456
- } };
2457
- }
2458
- const resultFilePath = input.toolResultFile?.trim();
2459
- if (!resultFilePath) return { error: "--tool-outcome applied requires --tool-result-file" };
2460
- return { command: {
2461
- expectedRevision,
2462
- instanceId,
2463
- noteFilePath,
2464
- operationId: input.resolveToolOperationId,
2465
- outcome: {
2466
- resultFilePath,
2467
- status: "applied"
2468
- },
2469
- type: "resolve-tool-operation"
2470
- } };
2471
- }
2472
- function parsePositiveInteger(value) {
2473
- return value && /^[1-9]\d*$/.test(value) ? Number(value) : void 0;
2474
- }
2475
- async function readPrivateTextFile(filePath, label, maxBytes) {
2476
- const handle = await open(filePath, constants$1.O_RDONLY | constants$1.O_NOFOLLOW);
2477
- try {
2478
- const metadata = await handle.stat();
2479
- if (!metadata.isFile()) throw new Error(`${label} must be a regular file`);
2480
- if ((metadata.mode & 63) !== 0) throw new Error(`${label} file permissions must be 0600 or stricter`);
2481
- if (metadata.size > maxBytes) throw new Error(`${label} file exceeds ${maxBytes} bytes`);
2482
- return (await handle.readFile("utf8")).trim();
2483
- } finally {
2484
- await handle.close();
2485
- }
2486
- }
2487
- function parseToolResult(value) {
2488
- try {
2489
- return JSON.parse(value);
2490
- } catch {
2491
- throw new Error("Tool result file must contain valid JSON");
2492
- }
2493
- }
2494
- //#endregion
2495
2081
  //#region src/adapters/cli/command/rivus-daemon-arguments.ts
2496
- const RIVUS_DAEMON_USAGE = `Usage: rivus --bootstrap <module> [--manifest <rivus.config.json>]
2082
+ const RIVUS_DAEMON_USAGE = `Usage: rivus --bootstrap <module> --manifest <rivus.config.json>
2497
2083
 
2498
2084
  Starts a local Rivus Agent daemon from an injected bootstrap module.
2499
2085
 
@@ -2502,14 +2088,15 @@ Project commands:
2502
2088
  rivus start
2503
2089
  rivus status
2504
2090
  rivus check-config
2091
+ rivus recovery <recovery options>
2505
2092
  rivus init [directory]
2506
2093
  rivus doctor [directory] [--env-file <path>]
2507
2094
  rivus model <status|set|rollback> ...
2508
2095
  rivus audio <install|status|transcribe> ...
2509
2096
 
2510
2097
  Options:
2511
- --bootstrap <module> Module exporting createRivusDaemonProcess(context)
2512
- --manifest <path> Start the manifest-driven multi-agent deployment; bootstrap exports createRivusDeploymentAdapters(context)
2098
+ --bootstrap <module> Module exporting createRivusDeploymentAdapters(context)
2099
+ --manifest <path> Deployment manifest to load
2513
2100
  --env-file <path> Load local KEY=value config before reading environment
2514
2101
  --check-config Print redacted local config JSON and exit
2515
2102
  --prompt <text> Run one local prompt through bootstrap promptText() and exit
@@ -2530,7 +2117,12 @@ Options:
2530
2117
  Add PI_API_KEY_FILE when using --print-openclaw-env
2531
2118
  --session-key <key> Session key for --prompt (default local:<agent-id>:cli)
2532
2119
  --status Print bootstrap status JSON without starting the daemon
2533
- --recovery-list List Dead Letters and Tool operations requiring reconciliation
2120
+ --recovery-list List stopped Automation occurrences, Dead Letters, and Tool operations requiring reconciliation
2121
+ --grant-automation-attempt <automation-id>
2122
+ Grant one stopped occurrence another attempt; requires --occurrence,
2123
+ --expected-revision, and --recovery-note-file
2124
+ --occurrence <occurrence>
2125
+ Scheduled occurrence selected by --grant-automation-attempt
2534
2126
  --requeue-dead-letter <message-id>
2535
2127
  Requeue one Dead Letter; requires --endpoint-id, --expected-revision, and --recovery-note-file
2536
2128
  --resolve-tool-operation <operation-id>
@@ -2546,23 +2138,11 @@ Options:
2546
2138
  Confirm whether the external Tool effect occurred
2547
2139
  --tool-result-file <path>
2548
2140
  Private (0600) JSON file required when --tool-outcome is applied
2549
- --status-url <url> Print live daemon status JSON from a running daemon
2550
- --wait-receive <kind> Wait with --status-url or a started bootstrap daemon until receive.lastAccepted or receive.lastHandled exists
2551
- --wait-receive-text <text>
2552
- With --wait-receive handled, wait until receive.lastHandled.intake.text contains text
2553
- --wait-receive-message-id <id>
2554
- With --wait-receive, wait until the accepted or handled receive observation has this Feishu message id
2555
- --wait-receive-observed-after <iso>
2556
- With --wait-receive, ignore receive observations at or before this ISO timestamp
2557
- --wait-timeout-ms <n> Timeout for --wait-receive (default 30000)
2558
- --wait-poll-ms <n> Poll interval for --wait-receive (default 500)
2559
2141
  --help Show this help
2560
2142
 
2561
2143
  Environment:
2562
2144
  RIVUS_HOME selects Rivus Home (default ~/.rivus-agent) for Home commands.
2563
2145
  RIVUS_BOOTSTRAP_MODULE may be used instead of --bootstrap.
2564
- FEISHU_APP_ID and FEISHU_APP_SECRET are required by the default config loader.
2565
- FEISHU_CARD_STREAM_LEASE_MS shortens or extends the proactive CardKit rollover threshold.
2566
2146
  PI_API_KEY_FILE may point to a local BYOK key file instead of PI_API_KEY.
2567
2147
  `;
2568
2148
  function parseRivusDaemonArguments(argv) {
@@ -2582,19 +2162,11 @@ function parseRivusDaemonArguments(argv) {
2582
2162
  const recoveryCli = createRivusRecoveryCliParser();
2583
2163
  let sessionKey;
2584
2164
  let status = false;
2585
- let statusUrl;
2586
- let waitPollMs;
2587
- let waitReceive;
2588
- let waitReceiveMessageId;
2589
- let waitReceiveObservedAfter;
2590
- let waitReceiveText;
2591
- let waitTimeoutMs;
2592
2165
  for (let index = 0; index < argv.length; index += 1) {
2593
2166
  const arg = argv[index];
2594
2167
  if (arg === "--help" || arg === "-h") return {
2595
2168
  help: true,
2596
- status,
2597
- ...statusUrl ? { statusUrl } : {}
2169
+ status
2598
2170
  };
2599
2171
  if (arg === "--status") {
2600
2172
  status = true;
@@ -2834,150 +2406,6 @@ function parseRivusDaemonArguments(argv) {
2834
2406
  };
2835
2407
  continue;
2836
2408
  }
2837
- if (arg === "--status-url") {
2838
- const value = argv[index + 1];
2839
- if (!value) return {
2840
- error: "--status-url requires a URL",
2841
- help: false,
2842
- status
2843
- };
2844
- statusUrl = value;
2845
- index += 1;
2846
- continue;
2847
- }
2848
- if (arg?.startsWith("--status-url=")) {
2849
- statusUrl = arg.slice(13);
2850
- if (!statusUrl) return {
2851
- error: "--status-url requires a URL",
2852
- help: false,
2853
- status
2854
- };
2855
- continue;
2856
- }
2857
- if (arg === "--wait-receive") {
2858
- const parsedWait = parseWaitReceive(argv[index + 1]);
2859
- if (!parsedWait) return {
2860
- error: "--wait-receive requires accepted or handled",
2861
- help: false,
2862
- status
2863
- };
2864
- waitReceive = parsedWait;
2865
- index += 1;
2866
- continue;
2867
- }
2868
- if (arg?.startsWith("--wait-receive=")) {
2869
- const parsedWait = parseWaitReceive(arg.slice(15));
2870
- if (!parsedWait) return {
2871
- error: "--wait-receive requires accepted or handled",
2872
- help: false,
2873
- status
2874
- };
2875
- waitReceive = parsedWait;
2876
- continue;
2877
- }
2878
- if (arg === "--wait-receive-text") {
2879
- const value = argv[index + 1];
2880
- if (!value) return {
2881
- error: "--wait-receive-text requires text",
2882
- help: false,
2883
- status
2884
- };
2885
- waitReceiveText = value;
2886
- index += 1;
2887
- continue;
2888
- }
2889
- if (arg?.startsWith("--wait-receive-text=")) {
2890
- waitReceiveText = arg.slice(20);
2891
- if (!waitReceiveText) return {
2892
- error: "--wait-receive-text requires text",
2893
- help: false,
2894
- status
2895
- };
2896
- continue;
2897
- }
2898
- if (arg === "--wait-receive-message-id") {
2899
- const value = argv[index + 1];
2900
- if (!value) return {
2901
- error: "--wait-receive-message-id requires a message id",
2902
- help: false,
2903
- status
2904
- };
2905
- waitReceiveMessageId = value;
2906
- index += 1;
2907
- continue;
2908
- }
2909
- if (arg?.startsWith("--wait-receive-message-id=")) {
2910
- waitReceiveMessageId = arg.slice(26);
2911
- if (!waitReceiveMessageId) return {
2912
- error: "--wait-receive-message-id requires a message id",
2913
- help: false,
2914
- status
2915
- };
2916
- continue;
2917
- }
2918
- if (arg === "--wait-receive-observed-after") {
2919
- const value = parseIsoTimestampArgument(argv[index + 1]);
2920
- if (!value) return {
2921
- error: "--wait-receive-observed-after requires an ISO timestamp",
2922
- help: false,
2923
- status
2924
- };
2925
- waitReceiveObservedAfter = value;
2926
- index += 1;
2927
- continue;
2928
- }
2929
- if (arg?.startsWith("--wait-receive-observed-after=")) {
2930
- const value = parseIsoTimestampArgument(arg.slice(30));
2931
- if (!value) return {
2932
- error: "--wait-receive-observed-after requires an ISO timestamp",
2933
- help: false,
2934
- status
2935
- };
2936
- waitReceiveObservedAfter = value;
2937
- continue;
2938
- }
2939
- if (arg === "--wait-timeout-ms") {
2940
- const parsedMs = parsePositiveIntegerArgument(argv[index + 1]);
2941
- if (parsedMs === void 0) return {
2942
- error: "--wait-timeout-ms requires a positive integer",
2943
- help: false,
2944
- status
2945
- };
2946
- waitTimeoutMs = parsedMs;
2947
- index += 1;
2948
- continue;
2949
- }
2950
- if (arg?.startsWith("--wait-timeout-ms=")) {
2951
- const parsedMs = parsePositiveIntegerArgument(arg.slice(18));
2952
- if (parsedMs === void 0) return {
2953
- error: "--wait-timeout-ms requires a positive integer",
2954
- help: false,
2955
- status
2956
- };
2957
- waitTimeoutMs = parsedMs;
2958
- continue;
2959
- }
2960
- if (arg === "--wait-poll-ms") {
2961
- const parsedMs = parsePositiveIntegerArgument(argv[index + 1]);
2962
- if (parsedMs === void 0) return {
2963
- error: "--wait-poll-ms requires a positive integer",
2964
- help: false,
2965
- status
2966
- };
2967
- waitPollMs = parsedMs;
2968
- index += 1;
2969
- continue;
2970
- }
2971
- if (arg?.startsWith("--wait-poll-ms=")) {
2972
- const parsedMs = parsePositiveIntegerArgument(arg.slice(15));
2973
- if (parsedMs === void 0) return {
2974
- error: "--wait-poll-ms requires a positive integer",
2975
- help: false,
2976
- status
2977
- };
2978
- waitPollMs = parsedMs;
2979
- continue;
2980
- }
2981
2409
  if (arg === "--bootstrap") {
2982
2410
  const value = argv[index + 1];
2983
2411
  if (!value) return {
@@ -3059,17 +2487,6 @@ function parseRivusDaemonArguments(argv) {
3059
2487
  status,
3060
2488
  checkConfig
3061
2489
  };
3062
- if (checkConfig && statusUrl) return {
3063
- error: "--check-config cannot be combined with --status-url",
3064
- help: false,
3065
- status,
3066
- checkConfig
3067
- };
3068
- if (prompt !== void 0 && statusUrl) return {
3069
- error: "--prompt cannot be combined with --status-url",
3070
- help: false,
3071
- status
3072
- };
3073
2490
  if (printOpenClawEnvPath !== void 0 && prompt !== void 0) return {
3074
2491
  error: "--print-openclaw-env cannot be combined with --prompt",
3075
2492
  help: false,
@@ -3090,11 +2507,6 @@ function parseRivusDaemonArguments(argv) {
3090
2507
  help: false,
3091
2508
  status
3092
2509
  };
3093
- if (printOpenClawEnvPath !== void 0 && statusUrl) return {
3094
- error: "--print-openclaw-env cannot be combined with --status-url",
3095
- help: false,
3096
- status
3097
- };
3098
2510
  if (piApiKeyFile !== void 0 && printOpenClawEnvPath === void 0) return {
3099
2511
  error: "--pi-api-key-file requires --print-openclaw-env",
3100
2512
  help: false,
@@ -3115,11 +2527,6 @@ function parseRivusDaemonArguments(argv) {
3115
2527
  help: false,
3116
2528
  status
3117
2529
  };
3118
- if (replayFeishuEventPath !== void 0 && statusUrl) return {
3119
- error: "--replay-feishu-event cannot be combined with --status-url",
3120
- help: false,
3121
- status
3122
- };
3123
2530
  if (replayFeishuText !== void 0 && prompt !== void 0) return {
3124
2531
  error: "--replay-feishu-text cannot be combined with --prompt",
3125
2532
  help: false,
@@ -3130,11 +2537,6 @@ function parseRivusDaemonArguments(argv) {
3130
2537
  help: false,
3131
2538
  status
3132
2539
  };
3133
- if (replayFeishuText !== void 0 && statusUrl) return {
3134
- error: "--replay-feishu-text cannot be combined with --status-url",
3135
- help: false,
3136
- status
3137
- };
3138
2540
  if (feishuReplayMessageId !== void 0 && replayFeishuText === void 0) return {
3139
2541
  error: "--feishu-message-id requires --replay-feishu-text",
3140
2542
  help: false,
@@ -3160,62 +2562,6 @@ function parseRivusDaemonArguments(argv) {
3160
2562
  help: false,
3161
2563
  status
3162
2564
  };
3163
- if (waitReceive !== void 0 && status) return {
3164
- error: "--wait-receive cannot be combined with --status",
3165
- help: false,
3166
- status
3167
- };
3168
- if (waitReceive !== void 0 && checkConfig) return {
3169
- error: "--wait-receive cannot be combined with --check-config",
3170
- help: false,
3171
- status,
3172
- checkConfig
3173
- };
3174
- if (waitReceive !== void 0 && prompt !== void 0) return {
3175
- error: "--wait-receive cannot be combined with --prompt",
3176
- help: false,
3177
- status
3178
- };
3179
- if (waitReceive !== void 0 && replayFeishuEventPath !== void 0) return {
3180
- error: "--wait-receive cannot be combined with --replay-feishu-event",
3181
- help: false,
3182
- status
3183
- };
3184
- if (waitReceive !== void 0 && replayFeishuText !== void 0) return {
3185
- error: "--wait-receive cannot be combined with --replay-feishu-text",
3186
- help: false,
3187
- status
3188
- };
3189
- if (waitReceive !== void 0 && printOpenClawEnvPath !== void 0) return {
3190
- error: "--wait-receive cannot be combined with --print-openclaw-env",
3191
- help: false,
3192
- status
3193
- };
3194
- if (waitTimeoutMs !== void 0 && waitReceive === void 0) return {
3195
- error: "--wait-timeout-ms requires --wait-receive",
3196
- help: false,
3197
- status
3198
- };
3199
- if (waitPollMs !== void 0 && waitReceive === void 0) return {
3200
- error: "--wait-poll-ms requires --wait-receive",
3201
- help: false,
3202
- status
3203
- };
3204
- if (waitReceiveText !== void 0 && waitReceive !== "handled") return {
3205
- error: "--wait-receive-text requires --wait-receive handled",
3206
- help: false,
3207
- status
3208
- };
3209
- if (waitReceiveMessageId !== void 0 && waitReceive === void 0) return {
3210
- error: "--wait-receive-message-id requires --wait-receive",
3211
- help: false,
3212
- status
3213
- };
3214
- if (waitReceiveObservedAfter !== void 0 && waitReceive === void 0) return {
3215
- error: "--wait-receive-observed-after requires --wait-receive",
3216
- help: false,
3217
- status
3218
- };
3219
2565
  const recovery = recoveryCli.build();
3220
2566
  if (recovery.error) return {
3221
2567
  error: recovery.error,
@@ -3228,7 +2574,7 @@ function parseRivusDaemonArguments(argv) {
3228
2574
  help: false,
3229
2575
  status
3230
2576
  };
3231
- if (checkConfig || prompt !== void 0 || printOpenClawEnvPath !== void 0 || replayFeishuEventPath !== void 0 || replayFeishuText !== void 0 || status || statusUrl !== void 0 || waitReceive !== void 0) return {
2577
+ if (checkConfig || prompt !== void 0 || printOpenClawEnvPath !== void 0 || replayFeishuEventPath !== void 0 || replayFeishuText !== void 0 || status) return {
3232
2578
  error: "Recovery commands cannot be combined with another one-shot command",
3233
2579
  help: false,
3234
2580
  status
@@ -3251,27 +2597,9 @@ function parseRivusDaemonArguments(argv) {
3251
2597
  ...replayFeishuText !== void 0 ? { replayFeishuText } : {},
3252
2598
  ...recovery.command ? { recoveryCommand: recovery.command } : {},
3253
2599
  ...sessionKey ? { sessionKey } : {},
3254
- status,
3255
- ...statusUrl ? { statusUrl } : {},
3256
- ...waitPollMs !== void 0 ? { waitPollMs } : {},
3257
- ...waitReceive !== void 0 ? { waitReceive } : {},
3258
- ...waitReceiveMessageId !== void 0 ? { waitReceiveMessageId } : {},
3259
- ...waitReceiveObservedAfter !== void 0 ? { waitReceiveObservedAfter } : {},
3260
- ...waitReceiveText !== void 0 ? { waitReceiveText } : {},
3261
- ...waitTimeoutMs !== void 0 ? { waitTimeoutMs } : {}
2600
+ status
3262
2601
  };
3263
2602
  }
3264
- function parseWaitReceive(value) {
3265
- return value === "accepted" || value === "handled" ? value : void 0;
3266
- }
3267
- function parsePositiveIntegerArgument(value) {
3268
- return value && /^[1-9]\d*$/.test(value) ? Number(value) : void 0;
3269
- }
3270
- function parseIsoTimestampArgument(value) {
3271
- if (!value) return;
3272
- const time = Date.parse(value);
3273
- return Number.isNaN(time) ? void 0 : new Date(time).toISOString();
3274
- }
3275
2603
  //#endregion
3276
2604
  //#region src/adapters/cli/command/rivus-daemon-output.ts
3277
2605
  const RIVUS_DAEMON_STARTED_MESSAGE = "Rivus Agent daemon started\n";
@@ -3315,84 +2643,11 @@ function createSyntheticFeishuTextReplayPayload(text, options) {
3315
2643
  sender: { tenant_key: options.tenantKey ?? "tenant_cli" }
3316
2644
  } };
3317
2645
  }
2646
+ //#endregion
2647
+ //#region src/adapters/cli/status/rivus-daemon-status.ts
3318
2648
  function formatRivusDaemonError(error) {
3319
- if (error instanceof ReceiveWaitTimeoutError) return `${error.message}\nLast status:\n${JSON.stringify(error.lastStatus, null, 2)}`;
3320
2649
  return error instanceof Error ? error.message : String(error);
3321
2650
  }
3322
- var ReceiveWaitTimeoutError = class extends Error {
3323
- target;
3324
- lastStatus;
3325
- messageId;
3326
- observedAfter;
3327
- text;
3328
- constructor(target, lastStatus, messageId, observedAfter, text) {
3329
- super(`Timed out waiting for ${target === "accepted" ? "receive.lastAccepted" : "receive.lastHandled"}${messageId ? ` with message id ${JSON.stringify(messageId)}` : ""}${observedAfter ? ` observed after ${JSON.stringify(observedAfter)}` : ""}${text ? ` containing text ${JSON.stringify(text)}` : ""}`);
3330
- this.target = target;
3331
- this.lastStatus = lastStatus;
3332
- this.messageId = messageId;
3333
- this.observedAfter = observedAfter;
3334
- this.text = text;
3335
- this.name = "ReceiveWaitTimeoutError";
3336
- }
3337
- };
3338
- async function fetchLiveStatus(url) {
3339
- const response = await fetch(url, { headers: { accept: "application/json" } });
3340
- if (!response.ok) throw new Error(`Status request failed with HTTP ${response.status}`);
3341
- return response.json();
3342
- }
3343
- function waitForReceiveStatus(readStatus, target, options) {
3344
- return Effect.suspend(() => {
3345
- const startedAt = Date.now();
3346
- let lastStatus;
3347
- const poll = () => readStatus().pipe(Effect.flatMap((status) => {
3348
- lastStatus = status;
3349
- if (hasReceiveObservation(status, target, {
3350
- ...options.messageId ? { messageId: options.messageId } : {},
3351
- ...options.observedAfter ? { observedAfter: options.observedAfter } : {},
3352
- ...options.text ? { text: options.text } : {}
3353
- })) return Effect.succeed(status);
3354
- if (Date.now() - startedAt >= options.timeoutMs) return Effect.fail(new ReceiveWaitTimeoutError(target, lastStatus, options.messageId, options.observedAfter, options.text));
3355
- return Effect.sleep(options.pollMs).pipe(Effect.flatMap(poll));
3356
- }));
3357
- return poll();
3358
- });
3359
- }
3360
- function hasReceiveObservation(status, target, criteria) {
3361
- const receive = isStatusRecord(status) ? status.receive : void 0;
3362
- if (!isStatusRecord(receive)) return false;
3363
- if (target === "accepted") {
3364
- const lastAccepted = receive.lastAccepted;
3365
- if (!isStatusRecord(lastAccepted)) return false;
3366
- if (criteria.messageId === void 0) return observedAfterMatches(lastAccepted, criteria.observedAfter);
3367
- const message = lastAccepted.message;
3368
- return isStatusRecord(message) && message.messageId === criteria.messageId && observedAfterMatches(lastAccepted, criteria.observedAfter);
3369
- }
3370
- const lastHandled = receive.lastHandled;
3371
- if (!isStatusRecord(lastHandled)) return false;
3372
- if (criteria.messageId !== void 0 && lastHandled.messageId !== criteria.messageId) return false;
3373
- if (!observedAfterMatches(lastHandled, criteria.observedAfter)) return false;
3374
- if (criteria.text === void 0) return true;
3375
- const intake = lastHandled.intake;
3376
- return isStatusRecord(intake) && typeof intake.text === "string" && intake.text.includes(criteria.text);
3377
- }
3378
- function isStatusRecord(value) {
3379
- return typeof value === "object" && value !== null && !Array.isArray(value);
3380
- }
3381
- function observedAfterMatches(observation, observedAfter) {
3382
- if (observedAfter === void 0) return true;
3383
- const observedAtMs = readObservedAtMs(observation.observedAt);
3384
- return observedAtMs !== void 0 && observedAtMs > Date.parse(observedAfter);
3385
- }
3386
- function readObservedAtMs(value) {
3387
- if (value instanceof Date) {
3388
- const time = value.getTime();
3389
- return Number.isNaN(time) ? void 0 : time;
3390
- }
3391
- if (typeof value === "string") {
3392
- const time = Date.parse(value);
3393
- return Number.isNaN(time) ? void 0 : time;
3394
- }
3395
- }
3396
2651
  //#endregion
3397
2652
  //#region src/platform/daemon/process/rivus-daemon-shutdown-controller.ts
3398
2653
  const DEFAULT_SIGNALS = ["SIGINT", "SIGTERM"];
@@ -4476,6 +3731,23 @@ function toError(error) {
4476
3731
  return error instanceof Error ? error : new Error(String(error));
4477
3732
  }
4478
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
4479
3751
  //#region src/bootstrap/daemon/rivus-daemon-cli.ts
4480
3752
  function runRivusDaemonCli(options) {
4481
3753
  return Effect.gen(function* () {
@@ -4488,16 +3760,6 @@ function runRivusDaemonCli(options) {
4488
3760
  options.stderr.write(formatRivusDaemonUsageError(parsed.error));
4489
3761
  return 1;
4490
3762
  }
4491
- if (parsed.statusUrl) {
4492
- const statusUrl = parsed.statusUrl;
4493
- const readStatus = () => Effect.tryPromise({
4494
- try: () => fetchLiveStatus(statusUrl),
4495
- catch: (error) => error
4496
- });
4497
- const status = parsed.waitReceive ? yield* waitForReceiveStatus(readStatus, parsed.waitReceive, createWaitReceiveOptions(parsed)) : yield* readStatus();
4498
- options.stdout.write(formatRivusDaemonJson(status));
4499
- return 0;
4500
- }
4501
3763
  if (parsed.printOpenClawEnvPath) {
4502
3764
  const openClawConfigPath = parsed.printOpenClawEnvPath;
4503
3765
  const result = yield* Effect.tryPromise({
@@ -4520,29 +3782,21 @@ function runRivusDaemonCli(options) {
4520
3782
  options.stderr.write(formatRivusDaemonUsageError("Missing --bootstrap <module> or RIVUS_BOOTSTRAP_MODULE"));
4521
3783
  return 1;
4522
3784
  }
4523
- let legacyConfig;
4524
- if (parsed.manifestPath) {
4525
- if (parsed.checkConfig) {
4526
- const manifestPath = parsed.manifestPath;
4527
- const manifest = yield* loadRivusDeploymentManifest(manifestPath);
4528
- yield* Effect.try({
4529
- try: () => validateRivusDeploymentManifest(manifest),
4530
- catch: (error) => error
4531
- });
4532
- options.stdout.write(formatRivusDaemonJson(toRedactedDeploymentManifest(manifest)));
4533
- return 0;
4534
- }
4535
- } else {
4536
- const configExit = yield* Effect.exit(loadRivusDaemonConfig(env));
4537
- if (configExit._tag === "Failure") {
4538
- options.stderr.write(formatRivusDaemonLine(configExit.cause.toString()));
4539
- return 1;
4540
- }
4541
- legacyConfig = configExit.value;
4542
- if (parsed.checkConfig) {
4543
- options.stdout.write(formatRivusDaemonJson(toRedactedConfig(legacyConfig)));
4544
- return 0;
4545
- }
3785
+ if (!parsed.manifestPath) {
3786
+ options.stderr.write(formatRivusDaemonUsageError("Missing --manifest <rivus.config.json>"));
3787
+ return 1;
3788
+ }
3789
+ if (parsed.checkConfig) {
3790
+ const manifest = yield* options.checkPlugins ? checkDeploymentPlugins({
3791
+ manifestPath: parsed.manifestPath,
3792
+ ...options.pluginPackageManifestPath ? { pluginPackageManifestPath: options.pluginPackageManifestPath } : {}
3793
+ }) : loadRivusDeploymentManifest(parsed.manifestPath);
3794
+ yield* Effect.try({
3795
+ try: () => validateRivusDeploymentManifest(manifest),
3796
+ catch: (error) => error
3797
+ });
3798
+ options.stdout.write(formatRivusDaemonJson(toRedactedDeploymentManifest(manifest)));
3799
+ return 0;
4546
3800
  }
4547
3801
  if (!bootstrapSpecifier) {
4548
3802
  options.stderr.write(formatRivusDaemonUsageError("Missing --bootstrap <module> or RIVUS_BOOTSTRAP_MODULE"));
@@ -4554,17 +3808,13 @@ function runRivusDaemonCli(options) {
4554
3808
  catch: (error) => error
4555
3809
  });
4556
3810
  const daemon = yield* Effect.tryPromise({
4557
- try: () => parsed.manifestPath ? createCliDeploymentDaemon(module.createRivusDeploymentAdapters, {
3811
+ try: () => createCliDeploymentDaemon(module.createRivusDeploymentAdapters, {
4558
3812
  argv: options.argv,
4559
3813
  env,
4560
3814
  ...parsed.envFilePath ? { envFilePath: parsed.envFilePath } : {},
4561
3815
  environmentOverrides: options.env,
4562
3816
  manifestPath: parsed.manifestPath,
4563
3817
  ...options.pluginPackageManifestPath ? { pluginPackageManifestPath: options.pluginPackageManifestPath } : {}
4564
- }) : createCliLegacyDaemon(module, {
4565
- argv: options.argv,
4566
- config: legacyConfig,
4567
- env
4568
3818
  }),
4569
3819
  catch: (error) => error
4570
3820
  });
@@ -4597,7 +3847,7 @@ function runRivusDaemonCli(options) {
4597
3847
  return 1;
4598
3848
  }
4599
3849
  const text = yield* daemon.promptText({
4600
- sessionKey: parsed.sessionKey ?? daemon.defaultSessionKey ?? `local:${legacyConfig.agentId}:cli`,
3850
+ sessionKey: parsed.sessionKey ?? daemon.defaultSessionKey ?? "local:cli",
4601
3851
  text: prompt
4602
3852
  });
4603
3853
  options.stdout.write(formatRivusDaemonLine(text));
@@ -4620,24 +3870,26 @@ function runRivusDaemonCli(options) {
4620
3870
  catch: (error) => error
4621
3871
  }));
4622
3872
  }
4623
- if (parsed.waitReceive) {
4624
- const waitReceive = parsed.waitReceive;
4625
- return yield* runStatusOneShot(options, daemon, (statusDaemon) => Effect.gen(function* () {
4626
- yield* Effect.try({
4627
- try: () => installCliShutdownController(options, statusDaemon),
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,
4628
3879
  catch: (error) => error
4629
3880
  });
4630
- yield* statusDaemon.start();
4631
- const status = yield* waitForReceiveStatus(() => statusDaemon.status(), waitReceive, createWaitReceiveOptions(parsed));
4632
- options.stdout.write(formatRivusDaemonJson(status));
4633
- return 0;
4634
- }));
4635
- }
3881
+ if (Exit.isFailure(exit)) return yield* Effect.failCause(exit.cause);
3882
+ })
3883
+ };
4636
3884
  yield* Effect.try({
4637
- try: () => installCliShutdownController(options, daemon),
3885
+ try: () => installCliShutdownController(options, managedDaemon),
4638
3886
  catch: (error) => error
4639
3887
  });
4640
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)))));
4641
3893
  options.stdout.write(RIVUS_DAEMON_STARTED_MESSAGE);
4642
3894
  return 0;
4643
3895
  }).pipe(Effect.catch((error) => Effect.sync(() => {
@@ -4645,11 +3897,6 @@ function runRivusDaemonCli(options) {
4645
3897
  return 1;
4646
3898
  })));
4647
3899
  }
4648
- async function createCliLegacyDaemon(module, context) {
4649
- const factory = module.createRivusDaemonProcess ?? module.default;
4650
- if (!factory) throw new Error("Bootstrap module must export createRivusDaemonProcess(context) or a default factory");
4651
- return factory(context);
4652
- }
4653
3900
  async function createCliDeploymentDaemon(factory, context) {
4654
3901
  if (!factory) throw new Error("Manifest bootstrap module must export createRivusDeploymentAdapters(context)");
4655
3902
  return createRivusDeploymentCliProcess(factory, context);
@@ -4678,15 +3925,6 @@ function runReplayOneShot(options, daemon, createPayload, replayOptions) {
4678
3925
  return 0;
4679
3926
  }));
4680
3927
  }
4681
- function createWaitReceiveOptions(parsed) {
4682
- return {
4683
- ...parsed.waitReceiveMessageId ? { messageId: parsed.waitReceiveMessageId } : {},
4684
- ...parsed.waitReceiveObservedAfter ? { observedAfter: parsed.waitReceiveObservedAfter } : {},
4685
- pollMs: parsed.waitPollMs ?? 500,
4686
- ...parsed.waitReceiveText ? { text: parsed.waitReceiveText } : {},
4687
- timeoutMs: parsed.waitTimeoutMs ?? 3e4
4688
- };
4689
- }
4690
3928
  function installCliShutdownController(options, daemon) {
4691
3929
  createRivusDaemonShutdownController({
4692
3930
  daemon,
@@ -4713,16 +3951,1493 @@ function hasRecoveryRunner(daemon) {
4713
3951
  return typeof daemon.openRecoveryControl === "function";
4714
3952
  }
4715
3953
  //#endregion
4716
- //#region src/bootstrap/cli/rivus-cli.ts
4717
- function runRivusCli(options) {
4718
- const command = options.argv[0];
4719
- if (command === "setup") return runSetupCommand(options);
4720
- if (command === "start") return runHomeDaemonCommand(options, "start", []);
4721
- if (command === "status") return runHomeDaemonCommand(options, "status", ["--status"]);
4722
- if (command === "check-config") return runHomeDaemonCommand(options, "check-config", ["--check-config"]);
4723
- if (command === "init") return runInitCommand(options);
4724
- if (command === "doctor") return runDoctorCommand(options);
4725
- if (command === "model") return runModelCommand(options);
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
5412
+ //#region src/bootstrap/cli/rivus-cli.ts
5413
+ function runRivusCli(options) {
5414
+ const command = options.argv[0];
5415
+ if (command === "setup") return runSetupCommand(options);
5416
+ if (command === "upgrade") return runUpgradeCommand(options);
5417
+ if (command === "start") return runHomeDaemonCommand(options, "start", []);
5418
+ if (command === "status") return runHomeDaemonCommand(options, "status", ["--status"]);
5419
+ if (command === "check-config") return runHomeDaemonCommand(options, "check-config", ["--check-config"]);
5420
+ if (command === "recovery") {
5421
+ const argv = options.argv.slice(1);
5422
+ const parser = createRivusRecoveryCliParser();
5423
+ for (let index = 0; index < argv.length; index += 1) {
5424
+ const argument = parser.consume(argv[index], argv[index + 1]);
5425
+ if (!argument.handled || argument.error) return Effect.sync(() => {
5426
+ options.stderr.write(renderRivusHomeCommandUsage("recovery"));
5427
+ return 1;
5428
+ });
5429
+ index += argument.consumed;
5430
+ }
5431
+ const parsed = parser.build();
5432
+ if (argv.length === 0 || parsed.error || !parsed.command) return Effect.sync(() => {
5433
+ options.stderr.write(renderRivusHomeCommandUsage("recovery"));
5434
+ return 1;
5435
+ });
5436
+ return runHomeDaemonCommand(options, "recovery", resolveHomeRecoveryFileArguments(argv, parsed.command, options.cwd));
5437
+ }
5438
+ if (command === "init") return runInitCommand(options);
5439
+ if (command === "doctor") return runDoctorCommand(options);
5440
+ if (command === "model") return runModelCommand(options);
4726
5441
  if (command === "audio") return runAudioCommand(options);
4727
5442
  if (command && !command.startsWith("-")) return Effect.sync(() => {
4728
5443
  options.stderr.write(renderRivusCliUnknownCommand(command));
@@ -4733,6 +5448,61 @@ function runRivusCli(options) {
4733
5448
  env: withoutRivusHomeDeployment(options.env)
4734
5449
  });
4735
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
+ }
5490
+ function resolveHomeRecoveryFileArguments(argv, command, cwd) {
5491
+ if (command.type === "inspect") return argv;
5492
+ const files = /* @__PURE__ */ new Map([["--recovery-note-file", resolve(cwd, command.noteFilePath)]]);
5493
+ if (command.type === "resolve-tool-operation" && command.outcome.status === "applied") files.set("--tool-result-file", resolve(cwd, command.outcome.resultFilePath));
5494
+ const resolved = [];
5495
+ for (let index = 0; index < argv.length; index += 1) {
5496
+ const argument = argv[index];
5497
+ const file = [...files].find(([flag]) => argument === flag || argument.startsWith(`${flag}=`));
5498
+ if (!file) resolved.push(argument);
5499
+ else if (argument === file[0]) {
5500
+ resolved.push(argument, file[1]);
5501
+ index += 1;
5502
+ } else resolved.push(`${file[0]}=${file[1]}`);
5503
+ }
5504
+ return resolved;
5505
+ }
4736
5506
  function runModelCommand(options) {
4737
5507
  const parsed = parseRivusModelCliArguments(options.argv.slice(1));
4738
5508
  if ("help" in parsed) return Effect.sync(() => {
@@ -4827,7 +5597,9 @@ function runSetupCommand(options) {
4827
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))));
4828
5598
  }
4829
5599
  function runHomeDaemonCommand(options, command, daemonArgs) {
4830
- if (hasRivusHomeCommandArguments(options.argv.slice(1))) return Effect.sync(() => {
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(() => {
4831
5603
  options.stderr.write(renderRivusHomeCommandUsage(command));
4832
5604
  return 1;
4833
5605
  });
@@ -4848,7 +5620,22 @@ function runHomeDaemonCommand(options, command, daemonArgs) {
4848
5620
  RIVUS_HOME: home.directory,
4849
5621
  [RIVUS_HOME_DEPLOYMENT_ENV]: home.directory
4850
5622
  },
4851
- 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
+ } } : {}
4852
5639
  })), Effect.catch((error) => writeError(options, error)));
4853
5640
  }
4854
5641
  function runInitCommand(options) {
@@ -4939,6 +5726,23 @@ function runRivusNodeEntrypoint(options) {
4939
5726
  loadBootstrap: (specifier) => import(toImportSpecifier(specifier)),
4940
5727
  nodeExecutable: process.execPath,
4941
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
+ },
4942
5746
  signalSource: options.signalSource,
4943
5747
  stderr: options.stderr,
4944
5748
  stdout: options.stdout