@rivus/gateway 0.19.0 → 0.20.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,20 +1,16 @@
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";
1
+ import { A as resolveFeishuEndpointCredentials, C as gatewayTemplateDirectory, D as parseRivusModelManagementEnabled, F as narrowBackgroundSessionDefinition, I as deepFreeze, M as validateRivusDeploymentManifest, N as validateRivusProjectSpaceDeployment, P as createBackgroundSessionToolContracts, T as resolveAcpRuntimeEnvironment, _ as readRivusAudioInstalledRelease, a as invokeRuntimeControl, d as renderRivusModelCliArgumentError, f as renderRivusModelCliHelp, g as installRivusAudioTranscriber, i as disposeRuntimeCacheEntries, j as InvalidRivusProjectSpace, k as loadMergedLocalEnvFile, l as createRivusModelManagementWireRequest, m as runRivusAudioProcess, n as withoutRivusHomeDeployment, o as RIVUS_RELEASE_DESCRIPTOR, p as runRivusAudioPassthroughProcess, r as createRuntimeCache, t as RIVUS_HOME_DEPLOYMENT_ENV, u as parseRivusModelCliArguments, v as readRivusAudioStatus, w as loadRivusDeploymentManifest, x as gatewayPackageManifestPath, y as gatewayAudioTranscriberAssetDirectory } from "./rivus-home-deployment-env.js";
3
2
  import { createRequire } 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
- import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
+ import { basename, 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 { lstat, mkdir, open, readFile, readdir, realpath, rmdir, stat, unlink, writeFile } from "node:fs/promises";
10
+ import { randomUUID } from "node:crypto";
12
11
  import { assertPathWithin, isPathWithin } from "@rivus/platform/filesystem";
13
- import { setTimeout as setTimeout$1 } from "node:timers/promises";
14
- import { readPersistenceFile, writeAtomicTextFile } from "@rivus/platform/persistence";
15
- import { spawn } from "node:child_process";
16
- import { createConnection } from "node:net";
17
12
  import { constants as constants$1 } from "node:fs";
13
+ import { createConnection } from "node:net";
18
14
  import { unwrapExit } from "@rivus/platform/effect";
19
15
  //#region src/core/application/agent-catalog/contracts/rivus-plugin.ts
20
16
  const RIVUS_PLUGIN_API_VERSION = "1";
@@ -23,6 +19,28 @@ var InvalidRivusPlugin = class extends Error {
23
19
  };
24
20
  //#endregion
25
21
  //#region src/core/application/agent-catalog/catalog/rivus-catalog-validation.ts
22
+ const automationRetryPolicySchema = Schema.Struct({
23
+ maxAttempts: Schema.Number,
24
+ terminalFailureCodes: Schema.optional(Schema.Array(Schema.String))
25
+ });
26
+ function validateRivusAutomationRetryPolicy(value, automationId) {
27
+ if (value === void 0) return;
28
+ const reject = (field, requirement) => {
29
+ throw new InvalidRivusPlugin(`automation ${automationId} retry ${field} ${requirement}`);
30
+ };
31
+ const decoded = Schema.decodeUnknownResult(automationRetryPolicySchema, { onExcessProperty: "error" })(value);
32
+ if (Result.isFailure(decoded)) return reject("policy", decoded.failure.message);
33
+ const policy = decoded.success;
34
+ if (!Number.isInteger(policy.maxAttempts) || policy.maxAttempts < 1 || policy.maxAttempts > 10) reject("maxAttempts", "must be an integer from 1 to 10");
35
+ const codes = policy.terminalFailureCodes ?? [];
36
+ if (codes.length > 16) reject("terminalFailureCodes", "must contain at most 16 codes");
37
+ const seen = /* @__PURE__ */ new Set();
38
+ for (const [index, code] of codes.entries()) {
39
+ if (!/^[A-Z][A-Z0-9_]{0,63}$/.test(code)) reject(`terminalFailureCodes[${index}]`, "must match ^[A-Z][A-Z0-9_]{0,63}$");
40
+ if (seen.has(code)) reject(`terminalFailureCodes[${index}]`, "must not duplicate another code");
41
+ seen.add(code);
42
+ }
43
+ }
26
44
  const MEMORY_SCOPES = [
27
45
  "conversation",
28
46
  "agent-private",
@@ -125,6 +143,7 @@ function createRivusPluginCatalog$1(runtime) {
125
143
  validateRivusCatalogReferences(profile.skills.allow, availableSkillIds, `profile ${profile.id}`, "skill");
126
144
  }
127
145
  for (const automation of pendingAutomations) {
146
+ validateRivusAutomationRetryPolicy(automation.retry, automation.id);
128
147
  validateRivusCatalogReference(automation.profileId, availableProfileIds, `automation ${automation.id}`, "profile");
129
148
  validateRivusCatalogReferences(automation.requestedToolIds, availableToolIds, `automation ${automation.id}`, "tool");
130
149
  validateRivusCatalogReferences(automation.requestedSkillIds, availableSkillIds, `automation ${automation.id}`, "skill");
@@ -314,6 +333,16 @@ function resolveRivusAgentDefinition$1(catalog, deployment, providers, runtime)
314
333
  profileId: deployment.profileId,
315
334
  ...deployment.projectSpaceId ? { projectSpaceId: deployment.projectSpaceId } : {},
316
335
  profileRevision,
336
+ ...deployment.runtime ? { runtime: {
337
+ args: [...deployment.runtime.args ?? []],
338
+ command: deployment.runtime.command,
339
+ env: { ...deployment.runtime.env },
340
+ initializationTimeoutMs: deployment.runtime.initializationTimeoutMs ?? 1e4,
341
+ permissions: deployment.runtime.permissions ?? "ask",
342
+ steering: deployment.runtime.steering ?? "disabled",
343
+ type: deployment.runtime.type,
344
+ unattended: deployment.runtime.unattended ?? false
345
+ } } : {},
317
346
  runtimeToolGrantSet,
318
347
  skillGrantSet,
319
348
  skills,
@@ -517,14 +546,13 @@ function toError$3(error) {
517
546
  }
518
547
  //#endregion
519
548
  //#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"]);
549
+ const FEISHU_BOOTSTRAP = "@rivus/gateway/bootstrap/feishu";
521
550
  function createRivusHomeDeploymentInspector(options = {}) {
522
- const resolveModule = options.resolveModule ?? ((specifier) => defaultResolveModule(specifier, options.packageManifestPath));
523
551
  const resolvePluginModule = options.resolvePluginModule ?? ((request) => resolveNodeRivusPluginModulePath(request, options.packageManifestPath ? { packageManifestPath: options.packageManifestPath } : {}));
524
552
  return { inspect: (input) => Effect.gen(function* () {
525
553
  const manifestResult = yield* checkManifest$1(input.home);
526
554
  const credentials = yield* checkCredentials$1(input.home, manifestResult.manifest, input.env, input.envFilePath);
527
- const modules = yield* checkModules(input.home, manifestResult.manifest, resolveModule, resolvePluginModule);
555
+ const modules = yield* checkModules(input.home, manifestResult.manifest, options.resolveModule ?? ((specifier) => defaultResolveModule(specifier, options.packageManifestPath, input.home.directory)), resolvePluginModule);
528
556
  return {
529
557
  credentials,
530
558
  manifest: manifestResult.check,
@@ -555,7 +583,7 @@ function checkModules(home, manifest, resolveModule, resolvePluginModule) {
555
583
  name: "modules",
556
584
  status: "fail"
557
585
  });
558
- const specifiers = [home.bootstrap, ...home.bootstrap === "@rivus/gateway/bootstrap/pi-feishu" ? DEFAULT_BOOTSTRAP_PEERS : []];
586
+ const specifiers = [home.bootstrap, ...home.bootstrap === FEISHU_BOOTSTRAP ? ["@larksuiteoapi/node-sdk", ...manifest.agents.some(({ runtime }) => !runtime) ? ["@earendil-works/pi-coding-agent"] : []] : []];
559
587
  return Effect.gen(function* () {
560
588
  const missing = [];
561
589
  for (const specifier of specifiers) {
@@ -571,7 +599,7 @@ function checkModules(home, manifest, resolveModule, resolvePluginModule) {
571
599
  if (result._tag === "Failure") missing.push(`${plugin.module} (${formatError(result.failure)})`);
572
600
  }
573
601
  return missing.length === 0 ? {
574
- message: "Bootstrap, Plugin, Pi, and Feishu modules resolve from the global installation",
602
+ message: "Bootstrap, Plugin, runtime, and Feishu modules resolve from the global installation",
575
603
  name: "modules",
576
604
  status: "pass"
577
605
  } : {
@@ -605,27 +633,33 @@ function checkCredentials$1(home, manifest, env, envFilePath) {
605
633
  try: async () => {
606
634
  const merged = await loadMergedLocalEnvFile(envFilePath ? resolve(home.directory, envFilePath) : home.envFilePath, env);
607
635
  for (const endpoint of manifest.endpoints.filter(({ enabled }) => enabled)) resolveFeishuEndpointCredentials(endpoint.credentialRef, merged);
636
+ for (const agent of manifest.agents) if (agent.runtime) await resolveAcpRuntimeEnvironment(agent.runtime, merged);
637
+ 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
638
  return {
609
- message: "enabled Endpoint credential references resolve",
639
+ message: "Endpoint credentials and Agent runtime environment references resolve",
610
640
  name: "credentials",
611
641
  status: "pass"
612
642
  };
613
643
  },
614
644
  catch: toError$2
615
645
  }).pipe(Effect.catch((error) => Effect.succeed({
616
- message: `enabled Endpoint credentials are incomplete: ${formatError(error)}`,
646
+ message: `deployment environment is incomplete: ${formatError(error)}`,
617
647
  name: "credentials",
618
648
  status: "fail"
619
649
  })));
620
650
  }
621
- function defaultResolveModule(specifier, packageManifestPath) {
622
- if (!packageManifestPath) return Effect.fail(/* @__PURE__ */ new Error("Rivus package manifest path is required for trusted module resolution"));
651
+ function defaultResolveModule(specifier, packageManifestPath, homeDirectory) {
652
+ const homeLocal = isAbsolute(specifier);
653
+ if (!homeLocal && !packageManifestPath) return Effect.fail(/* @__PURE__ */ new Error("Rivus package manifest path is required for trusted module resolution"));
623
654
  return Effect.gen(function* () {
624
655
  const resolvedRealpath = yield* Effect.tryPromise({
625
656
  try: () => realpath(fileURLToPath(import.meta.resolve(specifier))),
626
657
  catch: toError$2
627
658
  });
628
- return yield* validateTrustedModulePath(yield* findTrustedPackageRoot(packageManifestPath), resolvedRealpath, `module ${specifier}`);
659
+ return yield* validateTrustedModulePath(homeLocal ? yield* Effect.tryPromise({
660
+ try: () => realpath(homeDirectory),
661
+ catch: toError$2
662
+ }) : yield* findTrustedPackageRoot(packageManifestPath), resolvedRealpath, `module ${specifier}`);
629
663
  });
630
664
  }
631
665
  function toError$2(error) {
@@ -802,7 +836,7 @@ function createRivusHomeLayout() {
802
836
  }
803
837
  function homeConfig() {
804
838
  return `${JSON.stringify({
805
- bootstrap: "@rivus/gateway/bootstrap/pi-feishu",
839
+ bootstrap: "@rivus/gateway/bootstrap/feishu",
806
840
  envFile: ".env",
807
841
  logs: "logs",
808
842
  manifest: "rivus.config.json",
@@ -955,6 +989,195 @@ function createNodeRivusHome(options) {
955
989
  setup: initializeRivusHome
956
990
  };
957
991
  }
992
+ //#endregion
993
+ //#region src/adapters/cli/recovery/rivus-recovery-cli.ts
994
+ function createRivusRecoveryCliParser() {
995
+ const input = { recoveryList: false };
996
+ return {
997
+ build: () => buildCommand(input),
998
+ consume: (argument, next) => consumeArgument(input, argument, next)
999
+ };
1000
+ }
1001
+ async function runRivusRecoveryCliCommand(control, command) {
1002
+ switch (command.type) {
1003
+ case "inspect": return Effect.runPromise(control.inspect());
1004
+ case "grant-automation-attempt": return Effect.runPromise(control.grantAutomationAttempt({
1005
+ actorId: "local-cli",
1006
+ automationId: command.automationId,
1007
+ expectedRevision: command.expectedRevision,
1008
+ note: await readPrivateTextFile(command.noteFilePath, "Recovery note", 16384),
1009
+ occurrence: command.occurrence
1010
+ }));
1011
+ case "requeue-dead-letter": return Effect.runPromise(control.requeueDeadLetter({
1012
+ actorId: "local-cli",
1013
+ deliveryId: command.deliveryId,
1014
+ endpointId: command.endpointId,
1015
+ expectedRevision: command.expectedRevision,
1016
+ note: await readPrivateTextFile(command.noteFilePath, "Recovery note", 16384)
1017
+ }));
1018
+ case "resolve-tool-operation": {
1019
+ const note = await readPrivateTextFile(command.noteFilePath, "Recovery note", 16384);
1020
+ const outcome = command.outcome.status === "applied" ? {
1021
+ result: parseToolResult(await readPrivateTextFile(command.outcome.resultFilePath, "Tool result", 1048576)),
1022
+ status: "applied"
1023
+ } : command.outcome;
1024
+ return Effect.runPromise(control.resolveToolOperation({
1025
+ actorId: "local-cli",
1026
+ expectedRevision: command.expectedRevision,
1027
+ instanceId: command.instanceId,
1028
+ note,
1029
+ operationId: command.operationId,
1030
+ outcome
1031
+ }));
1032
+ }
1033
+ }
1034
+ }
1035
+ function consumeArgument(input, argument, next) {
1036
+ if (argument === "--recovery-list") {
1037
+ input.recoveryList = true;
1038
+ return {
1039
+ consumed: 0,
1040
+ handled: true
1041
+ };
1042
+ }
1043
+ for (const [flag, key] of [
1044
+ ["--grant-automation-attempt", "grantAutomationAttemptId"],
1045
+ ["--occurrence", "occurrence"],
1046
+ ["--requeue-dead-letter", "requeueDeadLetterId"],
1047
+ ["--resolve-tool-operation", "resolveToolOperationId"],
1048
+ ["--endpoint-id", "endpointId"],
1049
+ ["--instance-id", "instanceId"],
1050
+ ["--expected-revision", "expectedRevision"],
1051
+ ["--recovery-note-file", "recoveryNoteFile"],
1052
+ ["--tool-outcome", "toolOutcome"],
1053
+ ["--tool-result-file", "toolResultFile"]
1054
+ ]) {
1055
+ if (argument === flag) {
1056
+ if (!next || next.startsWith("--")) return {
1057
+ consumed: 0,
1058
+ error: `${flag} requires a value`,
1059
+ handled: true
1060
+ };
1061
+ input[key] = next;
1062
+ return {
1063
+ consumed: 1,
1064
+ handled: true
1065
+ };
1066
+ }
1067
+ if (argument?.startsWith(`${flag}=`)) {
1068
+ const value = argument.slice(flag.length + 1);
1069
+ if (!value) return {
1070
+ consumed: 0,
1071
+ error: `${flag} requires a value`,
1072
+ handled: true
1073
+ };
1074
+ input[key] = value;
1075
+ return {
1076
+ consumed: 0,
1077
+ handled: true
1078
+ };
1079
+ }
1080
+ }
1081
+ return {
1082
+ consumed: 0,
1083
+ handled: false
1084
+ };
1085
+ }
1086
+ function buildCommand(input) {
1087
+ const actionCount = Number(input.recoveryList) + Number(input.grantAutomationAttemptId !== void 0) + Number(input.requeueDeadLetterId !== void 0) + Number(input.resolveToolOperationId !== void 0);
1088
+ 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;
1089
+ if (actionCount === 0) return hasOptions ? { error: "Recovery options require --recovery-list, --grant-automation-attempt, --requeue-dead-letter, or --resolve-tool-operation" } : {};
1090
+ if (actionCount > 1) return { error: "Choose only one recovery command" };
1091
+ if (input.recoveryList) return hasOptions ? { error: "--recovery-list does not accept mutation options" } : { command: { type: "inspect" } };
1092
+ const expectedRevision = parsePositiveInteger(input.expectedRevision);
1093
+ if (expectedRevision === void 0) return { error: "Recovery mutations require --expected-revision with a positive integer" };
1094
+ const noteFilePath = input.recoveryNoteFile?.trim();
1095
+ if (!noteFilePath) return { error: "Recovery mutations require --recovery-note-file" };
1096
+ if (input.grantAutomationAttemptId !== void 0) return buildAutomationAttemptCommand(input, expectedRevision, noteFilePath);
1097
+ if (input.occurrence !== void 0) return { error: "--occurrence is only valid with --grant-automation-attempt" };
1098
+ if (input.requeueDeadLetterId !== void 0) return buildDeadLetterCommand(input, expectedRevision, noteFilePath);
1099
+ return buildToolOperationCommand(input, expectedRevision, noteFilePath);
1100
+ }
1101
+ function buildAutomationAttemptCommand(input, expectedRevision, noteFilePath) {
1102
+ const automationId = input.grantAutomationAttemptId?.trim();
1103
+ const occurrence = input.occurrence?.trim();
1104
+ if (!automationId || !occurrence) return { error: "--grant-automation-attempt requires an automation id and --occurrence" };
1105
+ 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" };
1106
+ return { command: {
1107
+ automationId,
1108
+ expectedRevision,
1109
+ noteFilePath,
1110
+ occurrence,
1111
+ type: "grant-automation-attempt"
1112
+ } };
1113
+ }
1114
+ function buildDeadLetterCommand(input, expectedRevision, noteFilePath) {
1115
+ const endpointId = input.endpointId?.trim();
1116
+ if (!endpointId) return { error: "--requeue-dead-letter requires --endpoint-id" };
1117
+ if (input.instanceId !== void 0 || input.toolOutcome !== void 0 || input.toolResultFile !== void 0) return { error: "--requeue-dead-letter cannot use Tool reconciliation options" };
1118
+ return { command: {
1119
+ deliveryId: input.requeueDeadLetterId,
1120
+ endpointId,
1121
+ expectedRevision,
1122
+ noteFilePath,
1123
+ type: "requeue-dead-letter"
1124
+ } };
1125
+ }
1126
+ function buildToolOperationCommand(input, expectedRevision, noteFilePath) {
1127
+ const instanceId = input.instanceId?.trim();
1128
+ if (!instanceId) return { error: "--resolve-tool-operation requires --instance-id" };
1129
+ if (input.endpointId !== void 0) return { error: "--resolve-tool-operation cannot use --endpoint-id" };
1130
+ if (input.toolOutcome !== "applied" && input.toolOutcome !== "not-applied") return { error: "--resolve-tool-operation requires --tool-outcome applied or not-applied" };
1131
+ if (input.toolOutcome === "not-applied") {
1132
+ if (input.toolResultFile !== void 0) return { error: "--tool-result-file is only valid when --tool-outcome is applied" };
1133
+ return { command: {
1134
+ expectedRevision,
1135
+ instanceId,
1136
+ noteFilePath,
1137
+ operationId: input.resolveToolOperationId,
1138
+ outcome: { status: "not-applied" },
1139
+ type: "resolve-tool-operation"
1140
+ } };
1141
+ }
1142
+ const resultFilePath = input.toolResultFile?.trim();
1143
+ if (!resultFilePath) return { error: "--tool-outcome applied requires --tool-result-file" };
1144
+ return { command: {
1145
+ expectedRevision,
1146
+ instanceId,
1147
+ noteFilePath,
1148
+ operationId: input.resolveToolOperationId,
1149
+ outcome: {
1150
+ resultFilePath,
1151
+ status: "applied"
1152
+ },
1153
+ type: "resolve-tool-operation"
1154
+ } };
1155
+ }
1156
+ function parsePositiveInteger(value) {
1157
+ const number = value && /^[1-9]\d*$/.test(value) ? Number(value) : void 0;
1158
+ return Number.isSafeInteger(number) ? number : void 0;
1159
+ }
1160
+ async function readPrivateTextFile(filePath, label, maxBytes) {
1161
+ const handle = await open(filePath, constants$1.O_RDONLY | constants$1.O_NOFOLLOW);
1162
+ try {
1163
+ const metadata = await handle.stat();
1164
+ if (!metadata.isFile()) throw new Error(`${label} must be a regular file`);
1165
+ if ((metadata.mode & 127) !== 0) throw new Error(`${label} file permissions must be 0600 or stricter`);
1166
+ if (metadata.size > maxBytes) throw new Error(`${label} file exceeds ${maxBytes} bytes`);
1167
+ const value = (await handle.readFile("utf8")).trim();
1168
+ if (!value) throw new Error(`${label} file must not be empty`);
1169
+ return value;
1170
+ } finally {
1171
+ await handle.close();
1172
+ }
1173
+ }
1174
+ function parseToolResult(value) {
1175
+ try {
1176
+ return JSON.parse(value);
1177
+ } catch {
1178
+ throw new Error("Tool result file must contain valid JSON");
1179
+ }
1180
+ }
958
1181
  const RIVUS_AUDIO_CLI_USAGE = `Usage:
959
1182
  rivus audio install [--force] [--json]
960
1183
  rivus audio status
@@ -1005,475 +1228,6 @@ function renderRivusAudioCliNotInstalled() {
1005
1228
  return "audio transcriber is not installed; run: rivus audio install\n";
1006
1229
  }
1007
1230
  //#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
1041
- });
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);
1053
- }
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;
1063
- }
1064
- }
1065
- async function readLockRecords(path) {
1066
- const names = await readdir(path).catch((error) => {
1067
- if (hasErrorCode(error, "ENOENT")) return [];
1068
- throw error;
1069
- });
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
- }));
1077
- }
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
- };
1090
- }
1091
- function isLiveProcess(pid) {
1092
- try {
1093
- process.kill(pid, 0);
1094
- return true;
1095
- } catch (error) {
1096
- return hasErrorCode(error, "EPERM");
1097
- }
1098
- }
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
1231
  //#region src/adapters/cli/audio/rivus-audio-cli.ts
1478
1232
  /** Runs one parsed `rivus audio` command and returns its exit code; installation failures are thrown. */
1479
1233
  async function runRivusAudioCliCommand(command, context) {
@@ -1517,6 +1271,7 @@ const RIVUS_CLI_USAGE = `Usage:
1517
1271
  rivus start
1518
1272
  rivus status
1519
1273
  rivus check-config
1274
+ rivus recovery <recovery options>
1520
1275
  rivus init [directory]
1521
1276
  rivus doctor [directory] [--env-file <path>]
1522
1277
  rivus model <status|set|rollback> ...
@@ -1529,6 +1284,7 @@ Commands:
1529
1284
  status Print Rivus Home deployment status without activating Endpoints
1530
1285
  check-config
1531
1286
  Validate and print the redacted Rivus Home manifest
1287
+ recovery Inspect or recover local state after stopping the Home daemon
1532
1288
  init Create a standalone local Rivus project without overwriting files
1533
1289
  doctor Check Rivus Home by default, or an explicit standalone project directory
1534
1290
  model Query or change the managed default model through the current Home
@@ -1546,7 +1302,7 @@ function renderRivusDirectoryCommandUsage(command) {
1546
1302
  return `Usage: rivus ${command} [directory]\n`;
1547
1303
  }
1548
1304
  function renderRivusHomeCommandUsage(command) {
1549
- return `Usage: rivus ${command}\n`;
1305
+ return `Usage: rivus ${command}${command === "recovery" ? " <recovery options>" : ""}\n`;
1550
1306
  }
1551
1307
  function renderRivusDoctorUsage() {
1552
1308
  return "Usage: rivus doctor [directory] [--env-file <path>]\n";
@@ -1854,7 +1610,7 @@ const TEMPLATE_FILES = Object.freeze({
1854
1610
  "current-weather.mjs": "current-weather.mjs",
1855
1611
  "https-response-reader.mjs": "https-response-reader.mjs",
1856
1612
  "rivus-agents.plugin.mjs": "rivus-starter.plugin.mjs",
1857
- "rivus.bootstrap.ts": "pi-feishu-deployment.bootstrap.ts"
1613
+ "rivus.bootstrap.ts": "feishu-deployment.bootstrap.ts"
1858
1614
  });
1859
1615
  async function initializeRivusProject(options) {
1860
1616
  const directory = resolve(options.directory);
@@ -2246,254 +2002,76 @@ function optionalRecord(value) {
2246
2002
  function readPath(record, path) {
2247
2003
  let value = record;
2248
2004
  for (const segment of path) {
2249
- const current = optionalRecord(value);
2250
- if (!current) return;
2251
- value = current[segment];
2252
- }
2253
- return value;
2254
- }
2255
- //#endregion
2256
- //#region src/adapters/cli/config/rivus-daemon-config.ts
2257
- async function loadRivusEnvFromOpenClawConfig(filePath, piApiKeyFile) {
2258
- return createRivusEnvFromOpenClawConfig(JSON.parse(await readFile(filePath, "utf8")), piApiKeyFile ? { piApiKeyFile } : {});
2259
- }
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
- function toRedactedDeploymentManifest(manifest) {
2279
- return {
2280
- agents: manifest.agents.map(({ agentId, endpointIds, pluginId, profileId }) => ({
2281
- agentId,
2282
- endpointIds,
2283
- pluginId,
2284
- profileId
2285
- })),
2286
- automations: (manifest.automations ?? []).map(({ agentId, delivery, enabled, id, required, schedule, templateId, timeZone }) => ({
2287
- agentId,
2288
- delivery: {
2289
- endpointId: delivery.endpointId,
2290
- targetRef: delivery.targetRef,
2291
- targetType: delivery.targetType
2292
- },
2293
- enabled,
2294
- id,
2295
- required,
2296
- schedule,
2297
- templateId,
2298
- timeZone
2299
- })),
2300
- ...manifest.backgroundSessions ? { backgroundSessions: {
2301
- enabled: manifest.backgroundSessions.enabled,
2302
- leaseMs: manifest.backgroundSessions.leaseMs,
2303
- leaseRenewalIntervalMs: manifest.backgroundSessions.leaseRenewalIntervalMs,
2304
- maxConsecutiveFailures: manifest.backgroundSessions.maxConsecutiveFailures,
2305
- maxConcurrentSessions: manifest.backgroundSessions.maxConcurrentSessions,
2306
- required: manifest.backgroundSessions.required,
2307
- retryBackoffMs: manifest.backgroundSessions.retryBackoffMs,
2308
- sessionLifetimeMs: manifest.backgroundSessions.sessionLifetimeMs,
2309
- stepTimeoutMs: manifest.backgroundSessions.stepTimeoutMs
2310
- } } : {},
2311
- defaultAgentId: manifest.defaultAgentId,
2312
- defaultEndpointId: manifest.defaultEndpointId,
2313
- endpoints: manifest.endpoints.map(({ agentId, credentialRef, enabled, id, required, sessionNamespace }) => ({
2314
- agentId,
2315
- credentialRef,
2316
- enabled,
2317
- id,
2318
- required,
2319
- sessionNamespace
2320
- })),
2321
- plugins: manifest.plugins.map(({ id, module, required }) => ({
2322
- id,
2323
- module,
2324
- required
2325
- }))
2326
- };
2327
- }
2328
- async function loadCliEnv(envFilePath, overrideEnv) {
2329
- if (!envFilePath) return overrideEnv;
2330
- return loadMergedLocalEnvFile(envFilePath, overrideEnv);
2331
- }
2332
- //#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");
2005
+ const current = optionalRecord(value);
2006
+ if (!current) return;
2007
+ value = current[segment];
2492
2008
  }
2009
+ return value;
2010
+ }
2011
+ //#endregion
2012
+ //#region src/adapters/cli/config/rivus-daemon-config.ts
2013
+ async function loadRivusEnvFromOpenClawConfig(filePath, piApiKeyFile) {
2014
+ return createRivusEnvFromOpenClawConfig(JSON.parse(await readFile(filePath, "utf8")), piApiKeyFile ? { piApiKeyFile } : {});
2015
+ }
2016
+ function toRedactedDeploymentManifest(manifest) {
2017
+ return {
2018
+ agents: manifest.agents.map(({ agentId, endpointIds, pluginId, profileId, runtime }) => ({
2019
+ agentId,
2020
+ endpointIds,
2021
+ pluginId,
2022
+ profileId,
2023
+ ...runtime ? { runtime } : {}
2024
+ })),
2025
+ automations: (manifest.automations ?? []).map(({ agentId, delivery, enabled, id, required, schedule, templateId, timeZone }) => ({
2026
+ agentId,
2027
+ delivery: {
2028
+ endpointId: delivery.endpointId,
2029
+ targetRef: delivery.targetRef,
2030
+ targetType: delivery.targetType
2031
+ },
2032
+ enabled,
2033
+ id,
2034
+ required,
2035
+ schedule,
2036
+ templateId,
2037
+ timeZone
2038
+ })),
2039
+ ...manifest.backgroundSessions ? { backgroundSessions: {
2040
+ enabled: manifest.backgroundSessions.enabled,
2041
+ leaseMs: manifest.backgroundSessions.leaseMs,
2042
+ leaseRenewalIntervalMs: manifest.backgroundSessions.leaseRenewalIntervalMs,
2043
+ maxConsecutiveFailures: manifest.backgroundSessions.maxConsecutiveFailures,
2044
+ maxConcurrentSessions: manifest.backgroundSessions.maxConcurrentSessions,
2045
+ required: manifest.backgroundSessions.required,
2046
+ retryBackoffMs: manifest.backgroundSessions.retryBackoffMs,
2047
+ sessionLifetimeMs: manifest.backgroundSessions.sessionLifetimeMs,
2048
+ stepTimeoutMs: manifest.backgroundSessions.stepTimeoutMs
2049
+ } } : {},
2050
+ defaultAgentId: manifest.defaultAgentId,
2051
+ defaultEndpointId: manifest.defaultEndpointId,
2052
+ endpoints: manifest.endpoints.map(({ agentId, allowedActors, credentialRef, enabled, id, required, sessionNamespace }) => ({
2053
+ agentId,
2054
+ ...allowedActors ? { allowedActorsCount: allowedActors.length } : {},
2055
+ credentialRef,
2056
+ enabled,
2057
+ id,
2058
+ required,
2059
+ sessionNamespace
2060
+ })),
2061
+ plugins: manifest.plugins.map(({ id, module, required }) => ({
2062
+ id,
2063
+ module,
2064
+ required
2065
+ }))
2066
+ };
2067
+ }
2068
+ async function loadCliEnv(envFilePath, overrideEnv) {
2069
+ if (!envFilePath) return overrideEnv;
2070
+ return loadMergedLocalEnvFile(envFilePath, overrideEnv);
2493
2071
  }
2494
2072
  //#endregion
2495
2073
  //#region src/adapters/cli/command/rivus-daemon-arguments.ts
2496
- const RIVUS_DAEMON_USAGE = `Usage: rivus --bootstrap <module> [--manifest <rivus.config.json>]
2074
+ const RIVUS_DAEMON_USAGE = `Usage: rivus --bootstrap <module> --manifest <rivus.config.json>
2497
2075
 
2498
2076
  Starts a local Rivus Agent daemon from an injected bootstrap module.
2499
2077
 
@@ -2502,14 +2080,15 @@ Project commands:
2502
2080
  rivus start
2503
2081
  rivus status
2504
2082
  rivus check-config
2083
+ rivus recovery <recovery options>
2505
2084
  rivus init [directory]
2506
2085
  rivus doctor [directory] [--env-file <path>]
2507
2086
  rivus model <status|set|rollback> ...
2508
2087
  rivus audio <install|status|transcribe> ...
2509
2088
 
2510
2089
  Options:
2511
- --bootstrap <module> Module exporting createRivusDaemonProcess(context)
2512
- --manifest <path> Start the manifest-driven multi-agent deployment; bootstrap exports createRivusDeploymentAdapters(context)
2090
+ --bootstrap <module> Module exporting createRivusDeploymentAdapters(context)
2091
+ --manifest <path> Deployment manifest to load
2513
2092
  --env-file <path> Load local KEY=value config before reading environment
2514
2093
  --check-config Print redacted local config JSON and exit
2515
2094
  --prompt <text> Run one local prompt through bootstrap promptText() and exit
@@ -2530,7 +2109,12 @@ Options:
2530
2109
  Add PI_API_KEY_FILE when using --print-openclaw-env
2531
2110
  --session-key <key> Session key for --prompt (default local:<agent-id>:cli)
2532
2111
  --status Print bootstrap status JSON without starting the daemon
2533
- --recovery-list List Dead Letters and Tool operations requiring reconciliation
2112
+ --recovery-list List stopped Automation occurrences, Dead Letters, and Tool operations requiring reconciliation
2113
+ --grant-automation-attempt <automation-id>
2114
+ Grant one stopped occurrence another attempt; requires --occurrence,
2115
+ --expected-revision, and --recovery-note-file
2116
+ --occurrence <occurrence>
2117
+ Scheduled occurrence selected by --grant-automation-attempt
2534
2118
  --requeue-dead-letter <message-id>
2535
2119
  Requeue one Dead Letter; requires --endpoint-id, --expected-revision, and --recovery-note-file
2536
2120
  --resolve-tool-operation <operation-id>
@@ -2546,23 +2130,11 @@ Options:
2546
2130
  Confirm whether the external Tool effect occurred
2547
2131
  --tool-result-file <path>
2548
2132
  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
2133
  --help Show this help
2560
2134
 
2561
2135
  Environment:
2562
2136
  RIVUS_HOME selects Rivus Home (default ~/.rivus-agent) for Home commands.
2563
2137
  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
2138
  PI_API_KEY_FILE may point to a local BYOK key file instead of PI_API_KEY.
2567
2139
  `;
2568
2140
  function parseRivusDaemonArguments(argv) {
@@ -2582,19 +2154,11 @@ function parseRivusDaemonArguments(argv) {
2582
2154
  const recoveryCli = createRivusRecoveryCliParser();
2583
2155
  let sessionKey;
2584
2156
  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
2157
  for (let index = 0; index < argv.length; index += 1) {
2593
2158
  const arg = argv[index];
2594
2159
  if (arg === "--help" || arg === "-h") return {
2595
2160
  help: true,
2596
- status,
2597
- ...statusUrl ? { statusUrl } : {}
2161
+ status
2598
2162
  };
2599
2163
  if (arg === "--status") {
2600
2164
  status = true;
@@ -2834,150 +2398,6 @@ function parseRivusDaemonArguments(argv) {
2834
2398
  };
2835
2399
  continue;
2836
2400
  }
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
2401
  if (arg === "--bootstrap") {
2982
2402
  const value = argv[index + 1];
2983
2403
  if (!value) return {
@@ -3059,17 +2479,6 @@ function parseRivusDaemonArguments(argv) {
3059
2479
  status,
3060
2480
  checkConfig
3061
2481
  };
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
2482
  if (printOpenClawEnvPath !== void 0 && prompt !== void 0) return {
3074
2483
  error: "--print-openclaw-env cannot be combined with --prompt",
3075
2484
  help: false,
@@ -3090,11 +2499,6 @@ function parseRivusDaemonArguments(argv) {
3090
2499
  help: false,
3091
2500
  status
3092
2501
  };
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
2502
  if (piApiKeyFile !== void 0 && printOpenClawEnvPath === void 0) return {
3099
2503
  error: "--pi-api-key-file requires --print-openclaw-env",
3100
2504
  help: false,
@@ -3115,11 +2519,6 @@ function parseRivusDaemonArguments(argv) {
3115
2519
  help: false,
3116
2520
  status
3117
2521
  };
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
2522
  if (replayFeishuText !== void 0 && prompt !== void 0) return {
3124
2523
  error: "--replay-feishu-text cannot be combined with --prompt",
3125
2524
  help: false,
@@ -3130,11 +2529,6 @@ function parseRivusDaemonArguments(argv) {
3130
2529
  help: false,
3131
2530
  status
3132
2531
  };
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
2532
  if (feishuReplayMessageId !== void 0 && replayFeishuText === void 0) return {
3139
2533
  error: "--feishu-message-id requires --replay-feishu-text",
3140
2534
  help: false,
@@ -3160,62 +2554,6 @@ function parseRivusDaemonArguments(argv) {
3160
2554
  help: false,
3161
2555
  status
3162
2556
  };
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
2557
  const recovery = recoveryCli.build();
3220
2558
  if (recovery.error) return {
3221
2559
  error: recovery.error,
@@ -3228,7 +2566,7 @@ function parseRivusDaemonArguments(argv) {
3228
2566
  help: false,
3229
2567
  status
3230
2568
  };
3231
- if (checkConfig || prompt !== void 0 || printOpenClawEnvPath !== void 0 || replayFeishuEventPath !== void 0 || replayFeishuText !== void 0 || status || statusUrl !== void 0 || waitReceive !== void 0) return {
2569
+ if (checkConfig || prompt !== void 0 || printOpenClawEnvPath !== void 0 || replayFeishuEventPath !== void 0 || replayFeishuText !== void 0 || status) return {
3232
2570
  error: "Recovery commands cannot be combined with another one-shot command",
3233
2571
  help: false,
3234
2572
  status
@@ -3251,27 +2589,9 @@ function parseRivusDaemonArguments(argv) {
3251
2589
  ...replayFeishuText !== void 0 ? { replayFeishuText } : {},
3252
2590
  ...recovery.command ? { recoveryCommand: recovery.command } : {},
3253
2591
  ...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 } : {}
2592
+ status
3262
2593
  };
3263
2594
  }
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
2595
  //#endregion
3276
2596
  //#region src/adapters/cli/command/rivus-daemon-output.ts
3277
2597
  const RIVUS_DAEMON_STARTED_MESSAGE = "Rivus Agent daemon started\n";
@@ -3315,84 +2635,11 @@ function createSyntheticFeishuTextReplayPayload(text, options) {
3315
2635
  sender: { tenant_key: options.tenantKey ?? "tenant_cli" }
3316
2636
  } };
3317
2637
  }
2638
+ //#endregion
2639
+ //#region src/adapters/cli/status/rivus-daemon-status.ts
3318
2640
  function formatRivusDaemonError(error) {
3319
- if (error instanceof ReceiveWaitTimeoutError) return `${error.message}\nLast status:\n${JSON.stringify(error.lastStatus, null, 2)}`;
3320
2641
  return error instanceof Error ? error.message : String(error);
3321
2642
  }
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
2643
  //#endregion
3397
2644
  //#region src/platform/daemon/process/rivus-daemon-shutdown-controller.ts
3398
2645
  const DEFAULT_SIGNALS = ["SIGINT", "SIGTERM"];
@@ -4488,16 +3735,6 @@ function runRivusDaemonCli(options) {
4488
3735
  options.stderr.write(formatRivusDaemonUsageError(parsed.error));
4489
3736
  return 1;
4490
3737
  }
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
3738
  if (parsed.printOpenClawEnvPath) {
4502
3739
  const openClawConfigPath = parsed.printOpenClawEnvPath;
4503
3740
  const result = yield* Effect.tryPromise({
@@ -4520,29 +3757,18 @@ function runRivusDaemonCli(options) {
4520
3757
  options.stderr.write(formatRivusDaemonUsageError("Missing --bootstrap <module> or RIVUS_BOOTSTRAP_MODULE"));
4521
3758
  return 1;
4522
3759
  }
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
- }
3760
+ if (!parsed.manifestPath) {
3761
+ options.stderr.write(formatRivusDaemonUsageError("Missing --manifest <rivus.config.json>"));
3762
+ return 1;
3763
+ }
3764
+ if (parsed.checkConfig) {
3765
+ const manifest = yield* loadRivusDeploymentManifest(parsed.manifestPath);
3766
+ yield* Effect.try({
3767
+ try: () => validateRivusDeploymentManifest(manifest),
3768
+ catch: (error) => error
3769
+ });
3770
+ options.stdout.write(formatRivusDaemonJson(toRedactedDeploymentManifest(manifest)));
3771
+ return 0;
4546
3772
  }
4547
3773
  if (!bootstrapSpecifier) {
4548
3774
  options.stderr.write(formatRivusDaemonUsageError("Missing --bootstrap <module> or RIVUS_BOOTSTRAP_MODULE"));
@@ -4554,17 +3780,13 @@ function runRivusDaemonCli(options) {
4554
3780
  catch: (error) => error
4555
3781
  });
4556
3782
  const daemon = yield* Effect.tryPromise({
4557
- try: () => parsed.manifestPath ? createCliDeploymentDaemon(module.createRivusDeploymentAdapters, {
3783
+ try: () => createCliDeploymentDaemon(module.createRivusDeploymentAdapters, {
4558
3784
  argv: options.argv,
4559
3785
  env,
4560
3786
  ...parsed.envFilePath ? { envFilePath: parsed.envFilePath } : {},
4561
3787
  environmentOverrides: options.env,
4562
3788
  manifestPath: parsed.manifestPath,
4563
3789
  ...options.pluginPackageManifestPath ? { pluginPackageManifestPath: options.pluginPackageManifestPath } : {}
4564
- }) : createCliLegacyDaemon(module, {
4565
- argv: options.argv,
4566
- config: legacyConfig,
4567
- env
4568
3790
  }),
4569
3791
  catch: (error) => error
4570
3792
  });
@@ -4597,7 +3819,7 @@ function runRivusDaemonCli(options) {
4597
3819
  return 1;
4598
3820
  }
4599
3821
  const text = yield* daemon.promptText({
4600
- sessionKey: parsed.sessionKey ?? daemon.defaultSessionKey ?? `local:${legacyConfig.agentId}:cli`,
3822
+ sessionKey: parsed.sessionKey ?? daemon.defaultSessionKey ?? "local:cli",
4601
3823
  text: prompt
4602
3824
  });
4603
3825
  options.stdout.write(formatRivusDaemonLine(text));
@@ -4620,19 +3842,6 @@ function runRivusDaemonCli(options) {
4620
3842
  catch: (error) => error
4621
3843
  }));
4622
3844
  }
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),
4628
- catch: (error) => error
4629
- });
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
- }
4636
3845
  yield* Effect.try({
4637
3846
  try: () => installCliShutdownController(options, daemon),
4638
3847
  catch: (error) => error
@@ -4645,11 +3854,6 @@ function runRivusDaemonCli(options) {
4645
3854
  return 1;
4646
3855
  })));
4647
3856
  }
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
3857
  async function createCliDeploymentDaemon(factory, context) {
4654
3858
  if (!factory) throw new Error("Manifest bootstrap module must export createRivusDeploymentAdapters(context)");
4655
3859
  return createRivusDeploymentCliProcess(factory, context);
@@ -4678,15 +3882,6 @@ function runReplayOneShot(options, daemon, createPayload, replayOptions) {
4678
3882
  return 0;
4679
3883
  }));
4680
3884
  }
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
3885
  function installCliShutdownController(options, daemon) {
4691
3886
  createRivusDaemonShutdownController({
4692
3887
  daemon,
@@ -4720,6 +3915,24 @@ function runRivusCli(options) {
4720
3915
  if (command === "start") return runHomeDaemonCommand(options, "start", []);
4721
3916
  if (command === "status") return runHomeDaemonCommand(options, "status", ["--status"]);
4722
3917
  if (command === "check-config") return runHomeDaemonCommand(options, "check-config", ["--check-config"]);
3918
+ if (command === "recovery") {
3919
+ const argv = options.argv.slice(1);
3920
+ const parser = createRivusRecoveryCliParser();
3921
+ for (let index = 0; index < argv.length; index += 1) {
3922
+ const argument = parser.consume(argv[index], argv[index + 1]);
3923
+ if (!argument.handled || argument.error) return Effect.sync(() => {
3924
+ options.stderr.write(renderRivusHomeCommandUsage("recovery"));
3925
+ return 1;
3926
+ });
3927
+ index += argument.consumed;
3928
+ }
3929
+ const parsed = parser.build();
3930
+ if (argv.length === 0 || parsed.error || !parsed.command) return Effect.sync(() => {
3931
+ options.stderr.write(renderRivusHomeCommandUsage("recovery"));
3932
+ return 1;
3933
+ });
3934
+ return runHomeDaemonCommand(options, "recovery", resolveHomeRecoveryFileArguments(argv, parsed.command, options.cwd));
3935
+ }
4723
3936
  if (command === "init") return runInitCommand(options);
4724
3937
  if (command === "doctor") return runDoctorCommand(options);
4725
3938
  if (command === "model") return runModelCommand(options);
@@ -4733,6 +3946,22 @@ function runRivusCli(options) {
4733
3946
  env: withoutRivusHomeDeployment(options.env)
4734
3947
  });
4735
3948
  }
3949
+ function resolveHomeRecoveryFileArguments(argv, command, cwd) {
3950
+ if (command.type === "inspect") return argv;
3951
+ const files = /* @__PURE__ */ new Map([["--recovery-note-file", resolve(cwd, command.noteFilePath)]]);
3952
+ if (command.type === "resolve-tool-operation" && command.outcome.status === "applied") files.set("--tool-result-file", resolve(cwd, command.outcome.resultFilePath));
3953
+ const resolved = [];
3954
+ for (let index = 0; index < argv.length; index += 1) {
3955
+ const argument = argv[index];
3956
+ const file = [...files].find(([flag]) => argument === flag || argument.startsWith(`${flag}=`));
3957
+ if (!file) resolved.push(argument);
3958
+ else if (argument === file[0]) {
3959
+ resolved.push(argument, file[1]);
3960
+ index += 1;
3961
+ } else resolved.push(`${file[0]}=${file[1]}`);
3962
+ }
3963
+ return resolved;
3964
+ }
4736
3965
  function runModelCommand(options) {
4737
3966
  const parsed = parseRivusModelCliArguments(options.argv.slice(1));
4738
3967
  if ("help" in parsed) return Effect.sync(() => {
@@ -4827,7 +4056,7 @@ function runSetupCommand(options) {
4827
4056
  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
4057
  }
4829
4058
  function runHomeDaemonCommand(options, command, daemonArgs) {
4830
- if (hasRivusHomeCommandArguments(options.argv.slice(1))) return Effect.sync(() => {
4059
+ if (command !== "recovery" && hasRivusHomeCommandArguments(options.argv.slice(1))) return Effect.sync(() => {
4831
4060
  options.stderr.write(renderRivusHomeCommandUsage(command));
4832
4061
  return 1;
4833
4062
  });