@rivus/gateway 0.22.2 → 0.23.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,33 +1,256 @@
1
- import { A as loadMergedLocalEnvFile, C as loadRivusDeploymentManifest, D as gatewayPackageManifestPath, E as gatewayPackageDirectory, F as validateRivusDeploymentManifest, I as validateRivusProjectSpaceDeployment, L as createBackgroundSessionToolContracts, M as resolveFeishuEndpointCredentials, N as InvalidRivusProjectSpace, P as parseRivusDeploymentManifest, R as narrowBackgroundSessionDefinition, S as renderRivusModelCliHelp, T as gatewayAudioTranscriberAssetDirectory, b as parseRivusModelCliArguments, c as readRivusAudioStatus, d as invokeRuntimeControl, g as createRivusModelManagementWireRequest, i as runRivusAudioProcess, j as resolveAcpRuntimeEnvironment, k as gatewayTemplateDirectory, l as createRuntimeCache, n as withoutRivusHomeDeployment, o as installRivusAudioTranscriber, p as parseRivusModelManagementEnabled, r as runRivusAudioPassthroughProcess, s as readRivusAudioInstalledRelease, t as RIVUS_HOME_DEPLOYMENT_ENV, u as disposeRuntimeCacheEntries, w as RIVUS_RELEASE_DESCRIPTOR, x as renderRivusModelCliArgumentError, z as deepFreeze } from "./rivus-home-deployment-env.js";
2
- import { t as decodeFeishuReceiveMessage } from "./feishu-receive-message.js";
3
- import { createRequire, findPackageJSON, registerHooks } from "node:module";
1
+ import { $ as validateTrustedModulePath, A as parseSuperagentArguments, B as createRivusModelManagementWireRequest, D as superagentControlSocketPath, G as renderRivusModelCliArgumentError, K as renderRivusModelCliHelp, L as isRivusModelManagementEnabled, M as superagentUsage, P as parseRivusModelManagementEnabled, Q as resolveNodeRivusPluginModulePath, R as resolveRivusModelSocketPath, T as deploymentStateDirectoryFromEnv, W as parseRivusModelCliArguments, Z as createNodeRivusPluginModuleLoader, _t as createRuntimeCache, a as readRivusAudioInstalledRelease, at as gatewayPackageManifestPath, bt as deepFreeze, c as withoutRivusHomeDeployment, ct as loadMergedLocalEnvFile, dt as toError, et as findTrustedPackageRoot, gt as errorMessage, ht as narrowBackgroundSessionDefinition, i as installRivusAudioTranscriber, it as gatewayPackageDirectory, j as superagentRejectionExitCode, lt as resolveAcpRuntimeEnvironment, mt as createBackgroundSessionToolContracts, n as runRivusAudioProcess, nt as RIVUS_RELEASE_DESCRIPTOR, o as readRivusAudioStatus, q as checkSuperagentConfigurations, rt as gatewayAudioTranscriberAssetDirectory, s as RIVUS_HOME_DEPLOYMENT_ENV, st as gatewayTemplateDirectory, t as runRivusAudioPassthroughProcess, tt as loadRivusDeploymentManifest, u as runRivusRecoveryCliCommand, ut as resolveFeishuEndpointCredentials, vt as disposeRuntimeCacheEntries, yt as invokeRuntimeControl } from "./rivus-audio-process.js";
2
+ import { o as requestLocalJson, r as requestSuperagentWorker, t as SuperagentWorkerRejected } from "./superagent-worker-wire.js";
3
+ import { findPackageJSON, registerHooks } from "node:module";
4
4
  import { createSha256Digest, createStableId } from "@rivus/platform/identity";
5
- import { Cause, Context, Deferred, Effect, Exit, Layer, Option, Result, Schema, SchemaIssue, Semaphore } from "effect";
6
- import { RIVUS_MEMORY_TOOL_PLUGIN_ID, RIVUS_RUNTIME_TOOL_IDS, createRivusMemoryToolContract, isRivusRuntimeToolId } from "@rivus/runtime";
5
+ import { Cause, Context, Deferred, Effect, Exit, Layer, Option, Result, Schema, SchemaGetter, Semaphore } from "effect";
7
6
  import { unwrapExit } from "@rivus/platform/effect";
7
+ import { createConnection } from "node:net";
8
+ import { access, chmod, constants, copyFile, link, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, rmdir, stat, symlink, unlink, writeFile } from "node:fs/promises";
9
+ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
10
+ import { isNodeErrorWithCode, isPathWithin } from "@rivus/platform/filesystem";
11
+ import { RIVUS_MEMORY_TOOL_PLUGIN_ID, RIVUS_RUNTIME_TOOL_IDS, createRivusMemoryToolContract, isRivusRuntimeToolId } from "@rivus/runtime";
8
12
  import { readPersistenceFile, writeAtomicTextFile } from "@rivus/platform/persistence";
9
13
  import { homedir } from "node:os";
10
- import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
14
+ import { text } from "node:stream/consumers";
11
15
  import { fileURLToPath, pathToFileURL } from "node:url";
12
- import { createNodePlatform } from "@rivus/agent-kit/node";
13
- import { access, chmod, constants, copyFile, link, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, rmdir, stat, symlink, unlink, writeFile } from "node:fs/promises";
16
+ import { spawn } from "node:child_process";
17
+ import { isDeepStrictEqual } from "node:util";
14
18
  import { compare, minVersion, parse, satisfies, valid } from "semver";
15
- import { assertPathWithin, isNodeErrorWithCode, isPathWithin } from "@rivus/platform/filesystem";
16
- import { createConnection } from "node:net";
19
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
17
20
  import { randomUUID } from "node:crypto";
21
+ import { createNodePlatform } from "@rivus/agent-kit/node";
18
22
  import { acquireProcessLock } from "@rivus/agent-kit-collab/process-lock";
19
23
  import { constants as constants$1, realpathSync } from "node:fs";
20
- import { spawn } from "node:child_process";
21
- import { isDeepStrictEqual } from "node:util";
22
- import { setTimeout as setTimeout$1 } from "node:timers/promises";
23
24
  import { parse as parse$1, stringify } from "yaml";
24
- //#region src/agent-catalog/domain/plugin/value-objects/rivus-plugin.ts
25
+ import { readHookEvent } from "@rivus/agent-kit/harness/events";
26
+ //#region src/agent-host/application/ports.ts
27
+ var AgentInstanceIdentity = class extends Context.Service()("@rivus/gateway/agent-host/AgentInstanceIdentity") {};
28
+ var AgentHostRuntimes = class extends Context.Service()("@rivus/gateway/agent-host/AgentHostRuntimes") {};
29
+ //#endregion
30
+ //#region src/agent-host/application/services/agent-instance-registry.ts
31
+ var AgentInstanceConflict = class extends Error {
32
+ name = "AgentInstanceConflict";
33
+ };
34
+ function bindingKey(binding, agentId) {
35
+ const bindingId = binding.kind === "endpoint" ? binding.endpointId : binding.kind === "automation" ? binding.automationId : binding.agentId;
36
+ return `${binding.kind}:${bindingId}:${agentId}`;
37
+ }
38
+ function freezeRecord(record) {
39
+ return Object.freeze({
40
+ ...record,
41
+ binding: Object.freeze({ ...record.binding })
42
+ });
43
+ }
44
+ function buildRegistry(identity, options) {
45
+ const records = /* @__PURE__ */ new Map();
46
+ for (const record of options.initialRecords ?? []) {
47
+ if (bindingKey(record.binding, record.agentId) !== record.bindingKey) throw new AgentInstanceConflict(`invalid binding key: ${record.bindingKey}`);
48
+ if (records.has(record.bindingKey)) throw new AgentInstanceConflict(`duplicate binding: ${record.bindingKey}`);
49
+ records.set(record.bindingKey, freezeRecord(record));
50
+ }
51
+ const resolveBinding = (instanceBinding, definition) => Effect.try({
52
+ try: () => {
53
+ const runtimeGenerationId = identity.createRuntimeGenerationId({
54
+ agentId: definition.agentId,
55
+ profileRevision: definition.profileRevision,
56
+ projectSpaceId: definition.projectSpaceId ?? null,
57
+ projectSpaceRevision: definition.projectSpaceRevision ?? null,
58
+ runtimeToolGrantRevision: definition.runtimeToolGrantSet.revision,
59
+ skillGrantRevision: definition.skillGrantSet.revision,
60
+ toolGrantRevision: definition.toolGrantSet.revision
61
+ });
62
+ const key = bindingKey(instanceBinding, definition.agentId);
63
+ const existing = records.get(key);
64
+ if (existing) {
65
+ if (existing.runtimeGenerationId !== runtimeGenerationId) throw new AgentInstanceConflict(`binding ${key} belongs to a different runtime generation`);
66
+ return existing;
67
+ }
68
+ const record = freezeRecord({
69
+ agentId: definition.agentId,
70
+ binding: instanceBinding,
71
+ bindingKey: key,
72
+ instanceId: identity.createInstanceId({
73
+ bindingKey: key,
74
+ runtimeGenerationId
75
+ }),
76
+ runtimeGenerationId
77
+ });
78
+ records.set(key, record);
79
+ return record;
80
+ },
81
+ catch: (error) => error instanceof AgentInstanceConflict ? error : new AgentInstanceConflict(String(error))
82
+ });
83
+ return {
84
+ resolveAutomation: (automationId, definition) => resolveBinding({
85
+ automationId,
86
+ kind: "automation"
87
+ }, definition),
88
+ resolveBackgroundSession: (agentId, definition) => resolveBinding({
89
+ agentId,
90
+ kind: "background-session"
91
+ }, definition),
92
+ resolveEndpoint: (endpointId, definition) => resolveBinding({
93
+ endpointId,
94
+ kind: "endpoint"
95
+ }, definition),
96
+ snapshot: () => Effect.sync(() => Object.freeze([...records.values()]))
97
+ };
98
+ }
99
+ /** An initial record whose key does not match its binding, or that repeats a binding, dies with `AgentInstanceConflict`. */
100
+ function makeAgentInstanceRegistry(options = {}) {
101
+ return AgentInstanceIdentity.pipe(Effect.flatMap((identity) => Effect.sync(() => buildRegistry(identity, options))));
102
+ }
103
+ //#endregion
104
+ //#region src/agent-host/application/use-cases/agent-host.ts
105
+ var InvalidAgentHostBinding = class extends Error {
106
+ name = "InvalidAgentHostBinding";
107
+ };
108
+ function makeAgentHost(options) {
109
+ return Effect.gen(function* () {
110
+ const runtime = yield* AgentHostRuntimes;
111
+ const registry = yield* makeAgentInstanceRegistry({ initialRecords: options.initialInstanceRecords });
112
+ const definitions = new Map(options.definitions.map((definition) => [definition.agentId, definition]));
113
+ const endpoints = /* @__PURE__ */ new Map();
114
+ const automations = /* @__PURE__ */ new Map();
115
+ const backgroundSessions = /* @__PURE__ */ new Map();
116
+ for (const endpoint of options.endpoints) {
117
+ if (endpoints.has(endpoint.id)) return yield* Effect.fail(new InvalidAgentHostBinding(`duplicate endpoint: ${endpoint.id}`));
118
+ const definition = definitions.get(endpoint.agentId);
119
+ if (!definition) return yield* Effect.fail(new InvalidAgentHostBinding(`unknown endpoint agent: ${endpoint.agentId}`));
120
+ if (!definition.endpointIds.includes(endpoint.id)) return yield* Effect.fail(new InvalidAgentHostBinding(`endpoint ${endpoint.id} is not declared by ${endpoint.agentId}`));
121
+ endpoints.set(endpoint.id, yield* registry.resolveEndpoint(endpoint.id, definition));
122
+ }
123
+ for (const automation of options.automations ?? []) {
124
+ if (automations.has(automation.id)) return yield* Effect.fail(new InvalidAgentHostBinding(`duplicate automation: ${automation.id}`));
125
+ if (!definitions.has(automation.definition.agentId)) return yield* Effect.fail(new InvalidAgentHostBinding(`unknown automation agent: ${automation.definition.agentId}`));
126
+ automations.set(automation.id, yield* registry.resolveAutomation(automation.id, automation.definition));
127
+ }
128
+ for (const backgroundSession of options.backgroundSessions ?? []) {
129
+ if (backgroundSession.definition.agentId !== backgroundSession.agentId) return yield* Effect.fail(new InvalidAgentHostBinding(`background session ${backgroundSession.agentId} cannot bind definition ${backgroundSession.definition.agentId}`));
130
+ if (backgroundSessions.has(backgroundSession.agentId)) return yield* Effect.fail(new InvalidAgentHostBinding(`duplicate background session agent: ${backgroundSession.agentId}`));
131
+ if (!definitions.has(backgroundSession.agentId)) return yield* Effect.fail(new InvalidAgentHostBinding(`unknown background session agent: ${backgroundSession.agentId}`));
132
+ backgroundSessions.set(backgroundSession.agentId, yield* registry.resolveBackgroundSession(backgroundSession.agentId, backgroundSession.definition));
133
+ }
134
+ const resolve = (records, id, message) => {
135
+ const instance = records.get(id);
136
+ return instance ? Effect.succeed(instance) : Effect.fail(new InvalidAgentHostBinding(message));
137
+ };
138
+ const resolveEndpoint = (endpointId) => resolve(endpoints, endpointId, `unknown endpoint: ${endpointId}`);
139
+ const resolveAutomation = (automationId) => resolve(automations, automationId, `unknown automation: ${automationId}`);
140
+ const resolveBackgroundSession = (agentId) => resolve(backgroundSessions, agentId, `unknown background session agent: ${agentId}`);
141
+ return {
142
+ cancelBackgroundSession: (agentId, input) => resolveBackgroundSession(agentId).pipe(Effect.flatMap((instance) => runtime.cancel(instance, input))),
143
+ cancelEndpoint: (endpointId, input) => resolveEndpoint(endpointId).pipe(Effect.flatMap((instance) => runtime.cancel(instance, input))),
144
+ dispose: () => runtime.disposeAll(),
145
+ handleAutomation: (automationId, input) => resolveAutomation(automationId).pipe(Effect.flatMap((instance) => runtime.run(instance, input))),
146
+ handleBackgroundSession: (agentId, input) => resolveBackgroundSession(agentId).pipe(Effect.flatMap((instance) => runtime.run(instance, input))),
147
+ handleEndpoint: (endpointId, input) => resolveEndpoint(endpointId).pipe(Effect.flatMap((instance) => runtime.run(instance, input))),
148
+ resolveAutomation,
149
+ resolveBackgroundSession,
150
+ resolveEndpoint,
151
+ steerEndpoint: (endpointId, input) => resolveEndpoint(endpointId).pipe(Effect.flatMap((instance) => runtime.steer(instance, input)))
152
+ };
153
+ });
154
+ }
155
+ //#endregion
156
+ //#region src/agent-host/infra/adapters/runtime-pool.ts
157
+ var RuntimeResourceBusy = class extends Error {
158
+ name = "RuntimeResourceBusy";
159
+ };
160
+ var RuntimeResourceDisposed = class extends Error {
161
+ name = "RuntimeResourceDisposed";
162
+ };
163
+ var RuntimePoolDisposalTimedOut = class extends Error {
164
+ name = "RuntimePoolDisposalTimedOut";
165
+ };
166
+ const DEFAULT_RUNTIME_DISPOSE_TIMEOUT_MS = 1e4;
167
+ function createEffectRuntimePool(options) {
168
+ const runtimes = createRuntimeCache();
169
+ const active = /* @__PURE__ */ new Map();
170
+ const lifecycle = Semaphore.makeUnsafe(1);
171
+ const existingRuntime = (instance) => Effect.gen(function* () {
172
+ const selected = yield* runtimes.getExisting(instance.instanceId);
173
+ if (!selected || !(yield* runtimes.isCurrent(instance.instanceId, selected.entry))) return;
174
+ return selected.runtime;
175
+ });
176
+ return {
177
+ cancel: (instance, input) => invokeRuntimeControl(existingRuntime(instance), (runtime) => runtime.cancel?.(input)),
178
+ disposeAll: () => Effect.gen(function* () {
179
+ const entries = yield* runtimes.drain();
180
+ yield* lifecycle.withPermits(1)(Effect.sync(() => active.clear()));
181
+ yield* disposeRuntimeCacheEntries({
182
+ dispose: (runtime) => runtime.dispose?.() ?? Effect.void,
183
+ entries,
184
+ failureMessage: "runtime pool disposal failed",
185
+ timeout: {
186
+ milliseconds: options.disposeTimeoutMs ?? DEFAULT_RUNTIME_DISPOSE_TIMEOUT_MS,
187
+ onTimeout: () => new RuntimePoolDisposalTimedOut(`runtime pool disposal timed out after ${options.disposeTimeoutMs ?? DEFAULT_RUNTIME_DISPOSE_TIMEOUT_MS}ms`)
188
+ }
189
+ });
190
+ }),
191
+ run: (instance, input) => Effect.gen(function* () {
192
+ const selected = yield* runtimes.getOrCreate(instance.instanceId, () => options.createRuntime(instance));
193
+ if (!(yield* runtimes.isCurrent(instance.instanceId, selected.entry))) return yield* Effect.fail(new RuntimeResourceDisposed(`runtime was disposed before run start: ${instance.instanceId}`));
194
+ if (selected.runtime.concurrency === "managed") return yield* selected.runtime.run(input);
195
+ const token = yield* lifecycle.withPermits(1)(Effect.gen(function* () {
196
+ if (!(yield* runtimes.isCurrent(instance.instanceId, selected.entry))) return yield* Effect.fail(new RuntimeResourceDisposed(`runtime was disposed before run start: ${instance.instanceId}`));
197
+ if (active.has(instance.instanceId)) return yield* Effect.fail(new RuntimeResourceBusy(`runtime already has an active run: ${instance.instanceId}`));
198
+ const activeToken = Symbol(instance.instanceId);
199
+ active.set(instance.instanceId, activeToken);
200
+ return activeToken;
201
+ }));
202
+ return yield* selected.runtime.run(input).pipe(Effect.ensuring(lifecycle.withPermits(1)(Effect.sync(() => {
203
+ if (active.get(instance.instanceId) === token) active.delete(instance.instanceId);
204
+ }))));
205
+ }),
206
+ steer: (instance, input) => invokeRuntimeControl(existingRuntime(instance), (runtime) => runtime.steer?.(input))
207
+ };
208
+ }
209
+ //#endregion
210
+ //#region src/agent-host/infra/adapters/effect-agent-runtime-pool.ts
211
+ var AgentInstanceBusy = class extends Error {
212
+ name = "AgentInstanceBusy";
213
+ };
214
+ var AgentRuntimeDisposed = class extends Error {
215
+ name = "AgentRuntimeDisposed";
216
+ };
217
+ function mapRuntimePoolError(error) {
218
+ if (error instanceof RuntimeResourceBusy) return new AgentInstanceBusy(error.message.replace(/^runtime /, "agent instance "));
219
+ if (error instanceof RuntimeResourceDisposed) return new AgentRuntimeDisposed(error.message.replace(/^runtime /, "agent runtime "));
220
+ if (error instanceof RuntimePoolDisposalTimedOut) return new AgentRuntimeDisposed(error.message.replace(/^runtime pool /, "agent runtime "));
221
+ return error;
222
+ }
223
+ function createAgentHostRuntimePool(factory, disposeTimeoutMs) {
224
+ const pool = createEffectRuntimePool({
225
+ createRuntime: (instance) => factory.create(instance),
226
+ ...disposeTimeoutMs === void 0 ? {} : { disposeTimeoutMs }
227
+ });
228
+ return {
229
+ cancel: (instance, input) => pool.cancel(instance, input),
230
+ disposeAll: () => pool.disposeAll().pipe(Effect.mapError((error) => error instanceof AggregateError && error.errors.length === 1 ? error.errors[0] : mapRuntimePoolError(error))),
231
+ run: (instance, input) => pool.run(instance, input).pipe(Effect.mapError(mapRuntimePoolError)),
232
+ steer: (instance, steering) => pool.steer(instance, steering)
233
+ };
234
+ }
235
+ //#endregion
236
+ //#region src/agent-host/infra/factories/agent-host-live.ts
237
+ /** Instance and generation ids derived from their inputs, so a restart reproduces them. */
238
+ const StableAgentInstanceIdentityLive = Layer.succeed(AgentInstanceIdentity, {
239
+ createInstanceId: (identity) => createStableId("instance", identity),
240
+ createRuntimeGenerationId: (identity) => createStableId("generation", identity)
241
+ });
242
+ /** One runtime per Agent Instance, created on first use by `factory`; each build of the Layer starts an empty pool. */
243
+ function pooledAgentHostRuntimes(factory) {
244
+ return Layer.sync(AgentHostRuntimes, () => createAgentHostRuntimePool(factory));
245
+ }
246
+ //#endregion
247
+ //#region src/agent-host/domain/plugin/rivus-plugin.ts
25
248
  const RIVUS_PLUGIN_API_VERSION = "1";
26
249
  var InvalidRivusPlugin = class extends Error {
27
250
  name = "InvalidRivusPlugin";
28
251
  };
29
252
  //#endregion
30
- //#region src/agent-catalog/domain/plugin/adapters/rivus-catalog-validation.ts
253
+ //#region src/agent-host/domain/plugin/adapters/rivus-catalog-validation.ts
31
254
  const automationRetryPolicySchema = Schema.Struct({
32
255
  maxAttempts: Schema.Number,
33
256
  terminalFailureCodes: Schema.optional(Schema.Array(Schema.String))
@@ -106,14 +329,14 @@ function uniqueRivusRuntimeToolIds(ids, owner) {
106
329
  return [...result];
107
330
  }
108
331
  //#endregion
109
- //#region src/agent-catalog/lib/stable-json.ts
332
+ //#region src/agent-host/lib/stable-json.ts
110
333
  function stableJson(value) {
111
334
  if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
112
335
  if (value !== null && typeof value === "object") return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, child]) => `${JSON.stringify(key)}:${stableJson(child)}`).join(",")}}`;
113
336
  return JSON.stringify(value);
114
337
  }
115
338
  //#endregion
116
- //#region src/agent-catalog/application/services/rivus-plugin-catalog.ts
339
+ //#region src/agent-host/application/services/catalog/rivus-plugin-catalog.ts
117
340
  function createRivusPluginCatalog$1(runtime) {
118
341
  const plugins = /* @__PURE__ */ new Map();
119
342
  const profiles = /* @__PURE__ */ new Map();
@@ -180,7 +403,7 @@ function createRivusPluginCatalog$1(runtime) {
180
403
  };
181
404
  }
182
405
  //#endregion
183
- //#region src/agent-catalog/application/services/rivus-tool-grant-set.ts
406
+ //#region src/agent-host/application/services/catalog/rivus-tool-grant-set.ts
184
407
  function intersectToolIds(sets) {
185
408
  const [first = [], ...rest] = sets;
186
409
  return [...new Set(first)].filter((id) => rest.every((set) => set.includes(id))).sort();
@@ -196,7 +419,7 @@ function narrowRivusToolGrantSet(runtime, parent, restrictions) {
196
419
  });
197
420
  }
198
421
  //#endregion
199
- //#region src/agent-catalog/application/services/rivus-agent-grant-restriction.ts
422
+ //#region src/agent-host/application/services/catalog/rivus-agent-grant-restriction.ts
200
423
  function uniqueRuntimeToolIds(ids) {
201
424
  const requested = /* @__PURE__ */ new Set();
202
425
  for (const id of ids) {
@@ -259,7 +482,7 @@ function restrictRivusAgentDefinitionGrants(runtime, definition, restriction) {
259
482
  });
260
483
  }
261
484
  //#endregion
262
- //#region src/agent-catalog/application/services/rivus-agent-definition-resolver.ts
485
+ //#region src/agent-host/application/services/catalog/rivus-agent-definition-resolver.ts
263
486
  function resolveRuntimeTools(profile, deployment) {
264
487
  const profileToolIds = uniqueRivusRuntimeToolIds(profile.runtimeTools?.allow ?? [], `profile ${profile.id}`);
265
488
  const requestedToolIds = uniqueRivusRuntimeToolIds(deployment.runtimeTools?.allow ?? [], `deployment ${deployment.agentId}`);
@@ -484,12 +707,113 @@ var RivusAgentHostFactory = class extends Context.Service()("@rivus/gateway/depl
484
707
  /** Optional: a deployment without Project Spaces runs without it, and one that declares them fails to prepare. */
485
708
  var RivusProjectSpaceResolver = class extends Context.Service()("@rivus/gateway/deployment/RivusProjectSpaceResolver") {};
486
709
  //#endregion
487
- //#region src/deployment/domain/failure/value-objects/deployment-failure.ts
488
- function formatDeploymentFailure(failure) {
489
- return failure instanceof Error ? failure.message : String(failure);
710
+ //#region src/deployment/domain/manifest/adapters/deployment-manifest.ts
711
+ var InvalidRivusProjectSpace = class extends Error {
712
+ name = "InvalidRivusProjectSpace";
713
+ };
714
+ function isAbsoluteProjectPath(value) {
715
+ return value.startsWith("/") || value.startsWith("\\") || /^[a-z]:[\\/]/i.test(value);
716
+ }
717
+ function validateRelativeProjectPath(value, owner) {
718
+ if (value.trim() === "" || isAbsoluteProjectPath(value) || value.includes("\0")) throw new InvalidRivusProjectSpace(`${owner} must be a non-empty relative path`);
719
+ }
720
+ function validateRivusProjectSpaceDeployment(declaration) {
721
+ validateRelativeProjectPath(declaration.root, `project space ${declaration.id} root`);
722
+ validateRelativeProjectPath(declaration.workingDirectory, `project space ${declaration.id} working directory`);
723
+ const sources = /* @__PURE__ */ new Set();
724
+ for (const source of declaration.skills.sources) {
725
+ validateRelativeProjectPath(source, `project space ${declaration.id} Skill source`);
726
+ if (sources.has(source)) throw new InvalidRivusProjectSpace(`project space ${declaration.id} contains duplicate Skill source: ${source}`);
727
+ sources.add(source);
728
+ }
490
729
  }
491
- function toDeploymentFailure(failure) {
492
- return failure instanceof Error ? failure : new Error(String(failure));
730
+ function validateRivusProjectSpaceDeployments(declarations) {
731
+ const projectSpaceIds = /* @__PURE__ */ new Set();
732
+ for (const declaration of declarations) {
733
+ if (projectSpaceIds.has(declaration.id)) throw new InvalidRivusProjectSpace(`duplicate project space: ${declaration.id}`);
734
+ projectSpaceIds.add(declaration.id);
735
+ validateRivusProjectSpaceDeployment(declaration);
736
+ }
737
+ return projectSpaceIds;
738
+ }
739
+ function validateBackgroundSessions(config) {
740
+ if (config.required && !config.enabled) throw new Error("backgroundSessions.required requires backgroundSessions.enabled");
741
+ if (config.leaseRenewalIntervalMs >= config.leaseMs) throw new Error("backgroundSessions.leaseRenewalIntervalMs must be shorter than leaseMs");
742
+ }
743
+ function validateModuleSpecifier(moduleSpecifier) {
744
+ const absolutePath = moduleSpecifier.startsWith("/") || moduleSpecifier.startsWith("\\\\") || /^[a-zA-Z]:[\\/]/.test(moduleSpecifier);
745
+ if (moduleSpecifier.trim() === "" || absolutePath || /^[a-z][a-z+.-]*:/i.test(moduleSpecifier) || moduleSpecifier.includes("\0")) throw new Error(`invalid plugin module specifier: ${moduleSpecifier}`);
746
+ if ((moduleSpecifier.startsWith("./") || moduleSpecifier.startsWith("../")) && moduleSpecifier.split(/[\\/]/).includes("..")) throw new Error(`plugin module escapes deployment root: ${moduleSpecifier}`);
747
+ }
748
+ function validateRivusDeploymentManifest(manifest) {
749
+ const projectSpaceIds = validateRivusProjectSpaceDeployments(manifest.projectSpaces ?? []);
750
+ const pluginIds = /* @__PURE__ */ new Set();
751
+ for (const plugin of manifest.plugins) {
752
+ if (pluginIds.has(plugin.id)) throw new Error(`duplicate plugin declaration: ${plugin.id}`);
753
+ validateModuleSpecifier(plugin.module);
754
+ pluginIds.add(plugin.id);
755
+ }
756
+ const agentIds = /* @__PURE__ */ new Set();
757
+ const agentById = /* @__PURE__ */ new Map();
758
+ for (const agent of manifest.agents) {
759
+ if (agentIds.has(agent.agentId)) throw new Error(`duplicate agent deployment: ${agent.agentId}`);
760
+ agentIds.add(agent.agentId);
761
+ if (!pluginIds.has(agent.pluginId)) throw new Error(`agent ${agent.agentId} references undeclared plugin: ${agent.pluginId}`);
762
+ if (agent.projectSpaceId && !projectSpaceIds.has(agent.projectSpaceId)) throw new Error(`agent ${agent.agentId} references unknown project space: ${agent.projectSpaceId}`);
763
+ const runtime = agent.runtime;
764
+ if (runtime) {
765
+ if (agent.runtimeTools !== void 0) throw new Error(`ACP agent ${agent.agentId} must not declare runtimeTools`);
766
+ if (agent.skills.allow.length > 0) throw new Error(`ACP agent ${agent.agentId} skills.allow must be empty`);
767
+ if (runtime.args?.includes("--yolo") && !runtime.unattended) throw new Error(`ACP agent ${agent.agentId} runtime.args --yolo requires unattended: true`);
768
+ }
769
+ agentById.set(agent.agentId, agent);
770
+ }
771
+ const endpointIds = /* @__PURE__ */ new Set();
772
+ const sessionNamespaces = /* @__PURE__ */ new Set();
773
+ for (const endpoint of manifest.endpoints) {
774
+ if (endpointIds.has(endpoint.id)) throw new Error(`duplicate endpoint binding: ${endpoint.id}`);
775
+ endpointIds.add(endpoint.id);
776
+ if (sessionNamespaces.has(endpoint.sessionNamespace)) throw new Error(`duplicate endpoint session namespace: ${endpoint.sessionNamespace}`);
777
+ sessionNamespaces.add(endpoint.sessionNamespace);
778
+ const agent = agentById.get(endpoint.agentId);
779
+ if (!agent) throw new Error(`endpoint ${endpoint.id} references unknown agent: ${endpoint.agentId}`);
780
+ if (agent.runtime?.unattended && !endpoint.allowedActors?.length) throw new Error(`unattended ACP agent ${agent.agentId} requires non-empty allowedActors on endpoint ${endpoint.id}`);
781
+ if (!agent.endpointIds.includes(endpoint.id)) throw new Error(`endpoint ${endpoint.id} is not declared by agent ${endpoint.agentId}`);
782
+ }
783
+ for (const agent of manifest.agents) for (const endpointId of agent.endpointIds) {
784
+ const endpoint = manifest.endpoints.find(({ id }) => id === endpointId);
785
+ if (!endpoint) throw new Error(`agent ${agent.agentId} references unknown endpoint: ${endpointId}`);
786
+ if (endpoint.agentId !== agent.agentId) throw new Error(`endpoint ${endpointId} is bound to a different agent`);
787
+ }
788
+ const superagentEndpoints = /* @__PURE__ */ new Set();
789
+ for (const endpoint of manifest.superagentEndpoints ?? []) {
790
+ if (endpointIds.has(endpoint.id) || superagentEndpoints.has(endpoint.id)) throw new Error(`duplicate endpoint binding: ${endpoint.id}`);
791
+ superagentEndpoints.add(endpoint.id);
792
+ }
793
+ const boundEndpoints = /* @__PURE__ */ new Set();
794
+ for (const id of manifest.superagent?.endpointIds ?? []) {
795
+ if (!superagentEndpoints.has(id) || boundEndpoints.has(id)) throw new Error(`Superagent endpoint must reference one mode=superagent endpoint: ${id}`);
796
+ boundEndpoints.add(id);
797
+ }
798
+ for (const id of superagentEndpoints) if (!boundEndpoints.has(id)) throw new Error(`Superagent endpoint has no source: ${id}`);
799
+ const automationIds = /* @__PURE__ */ new Set();
800
+ for (const automation of manifest.automations ?? []) {
801
+ if (automationIds.has(automation.id)) throw new Error(`duplicate automation binding: ${automation.id}`);
802
+ automationIds.add(automation.id);
803
+ if (!agentById.has(automation.agentId)) throw new Error(`automation ${automation.id} references unknown agent: ${automation.agentId}`);
804
+ if (automation.workerId !== void 0 && automation.superagent !== true) throw new Error(`automation ${automation.id} workerId requires superagent`);
805
+ if (automation.superagent === true && (manifest.superagent?.endpointIds.length ?? 0) === 0) throw new Error(`automation ${automation.id} requires a Superagent with a Feishu source`);
806
+ const endpoint = manifest.endpoints.find(({ id }) => id === automation.delivery.endpointId);
807
+ if (!endpoint) throw new Error(`automation ${automation.id} references unknown delivery endpoint: ${automation.delivery.endpointId}`);
808
+ if (automation.enabled && !endpoint.enabled) throw new Error(`automation ${automation.id} delivery endpoint must be enabled`);
809
+ }
810
+ const defaultAgent = agentById.get(manifest.defaultAgentId);
811
+ if (!defaultAgent) throw new Error(`default agent does not exist: ${manifest.defaultAgentId}`);
812
+ const defaultEndpoint = manifest.endpoints.find(({ id }) => id === manifest.defaultEndpointId);
813
+ if (!defaultEndpoint) throw new Error(`default endpoint does not exist: ${manifest.defaultEndpointId}`);
814
+ if (defaultEndpoint.agentId !== defaultAgent.agentId) throw new Error("default endpoint is not bound to the default agent");
815
+ if (!defaultEndpoint.enabled) throw new Error("default endpoint must be enabled");
816
+ if (manifest.backgroundSessions) validateBackgroundSessions(manifest.backgroundSessions);
493
817
  }
494
818
  //#endregion
495
819
  //#region src/deployment/application/services/deployment-resolution.ts
@@ -508,7 +832,7 @@ function resolveRivusDeployment(input) {
508
832
  const pluginLoader = yield* RivusPluginLoader;
509
833
  yield* Effect.try({
510
834
  try: () => validateRivusDeploymentManifest(input.manifest),
511
- catch: toDeploymentFailure
835
+ catch: toError
512
836
  });
513
837
  const catalog = input.agentCatalog.createPluginCatalog();
514
838
  const pluginStatuses = [];
@@ -524,10 +848,10 @@ function resolveRivusDeployment(input) {
524
848
  catalog.registerPlugin(plugin);
525
849
  return plugin;
526
850
  },
527
- catch: toDeploymentFailure
851
+ catch: toError
528
852
  })), Effect.result);
529
853
  if (Result.isFailure(loaded)) {
530
- const message = formatDeploymentFailure(loaded.failure);
854
+ const message = errorMessage(loaded.failure);
531
855
  if (declaration.required) return yield* Effect.fail(new RivusPluginLoadError(declaration.id, declaration.module, `required plugin ${declaration.id} failed to load: ${message}`, { cause: loaded.failure }));
532
856
  const status = Object.freeze({
533
857
  error: message,
@@ -578,7 +902,7 @@ function resolveRivusDeployment(input) {
578
902
  })
579
903
  }) : baseDefinition;
580
904
  },
581
- catch: toDeploymentFailure
905
+ catch: toError
582
906
  }).pipe(Effect.result);
583
907
  if (Result.isFailure(resolved)) {
584
908
  const declaration = input.manifest.plugins.find(({ id }) => id === agent.pluginId);
@@ -627,7 +951,7 @@ function resolveRivusDeployment(input) {
627
951
  }),
628
952
  template
629
953
  }),
630
- catch: toDeploymentFailure
954
+ catch: toError
631
955
  });
632
956
  automationDefinitions.push(definition);
633
957
  }
@@ -725,7 +1049,7 @@ function prepareDeployment(input) {
725
1049
  const resolved = yield* projectSpaceResolver.resolve({
726
1050
  declaration,
727
1051
  deploymentRoot: input.deploymentRoot
728
- }).pipe(Effect.mapError(toDeploymentFailure));
1052
+ }).pipe(Effect.mapError(toError));
729
1053
  projectSpaces.set(resolved.id, resolved);
730
1054
  }
731
1055
  const definitions = yield* Effect.try({
@@ -733,14 +1057,14 @@ function prepareDeployment(input) {
733
1057
  const resolved = bindResolvedProjectSpaceRevision(definition, projectSpaces);
734
1058
  return [resolved.agentId, resolved];
735
1059
  })),
736
- catch: toDeploymentFailure
1060
+ catch: toError
737
1061
  });
738
1062
  const automationDefinitions = yield* Effect.try({
739
1063
  try: () => new Map(deployment.automationDefinitions.map((definition) => [definition.id, Object.freeze({
740
1064
  ...definition,
741
1065
  runtimeDefinition: bindResolvedProjectSpaceRevision(definition.runtimeDefinition, projectSpaces)
742
1066
  })])),
743
- catch: toDeploymentFailure
1067
+ catch: toError
744
1068
  });
745
1069
  const effectiveDeployment = Object.freeze({
746
1070
  ...deployment,
@@ -761,7 +1085,7 @@ function prepareDeployment(input) {
761
1085
  if (agent.status !== "enabled" || !agent.definition) continue;
762
1086
  const narrowed = yield* Effect.try({
763
1087
  try: () => narrowBackgroundSessionDefinition(definitions.get(agent.agentId), input.digest),
764
- catch: toDeploymentFailure
1088
+ catch: toError
765
1089
  });
766
1090
  backgroundDefinitions.set(agent.agentId, narrowed);
767
1091
  }
@@ -805,7 +1129,7 @@ function prepareDeployment(input) {
805
1129
  ...projectSpace ? { projectSpace } : {}
806
1130
  });
807
1131
  } }
808
- }).pipe(Effect.mapError(toDeploymentFailure));
1132
+ }).pipe(Effect.mapError(toError));
809
1133
  return {
810
1134
  automationSlots,
811
1135
  ...backgroundSessionSlot ? { backgroundSessionSlot } : {},
@@ -860,11 +1184,12 @@ function startSlot(slot, available, label, create) {
860
1184
  yield* slot.adapter.start();
861
1185
  if (!(yield* Effect.try({
862
1186
  try: () => slot.adapter.running(),
863
- catch: toDeploymentFailure
1187
+ catch: toError
864
1188
  }))) return yield* Effect.fail(/* @__PURE__ */ new Error(`${label} start completed but the adapter is not running`));
865
1189
  }).pipe(Effect.exit);
866
1190
  if (Exit.isFailure(started)) {
867
- slot.error = formatDeploymentFailure(Cause.squash(started.cause));
1191
+ const error = Cause.squash(started.cause);
1192
+ slot.error = errorMessage(error);
868
1193
  slot.lifecycle = transitionDeploymentComponentLifecycle(slot.lifecycle, "degraded");
869
1194
  return true;
870
1195
  }
@@ -886,13 +1211,13 @@ function stopSlots(slots, errors) {
886
1211
  yield* slot.adapter.stop();
887
1212
  if (yield* Effect.try({
888
1213
  try: () => slot.adapter.running(),
889
- catch: toDeploymentFailure
1214
+ catch: toError
890
1215
  })) return yield* Effect.fail(/* @__PURE__ */ new Error("component stop completed but the adapter is still running"));
891
1216
  }).pipe(Effect.exit);
892
1217
  if (Exit.isFailure(stopped)) {
893
1218
  const error = Cause.squash(stopped.cause);
894
1219
  errors.push(error);
895
- slot.error = formatDeploymentFailure(error);
1220
+ slot.error = errorMessage(error);
896
1221
  slot.lifecycle = transitionDeploymentComponentLifecycle(slot.lifecycle, "cleanup-required");
897
1222
  continue;
898
1223
  }
@@ -907,7 +1232,7 @@ function observeRunning(slot) {
907
1232
  return { running: slot.adapter.running() };
908
1233
  } catch (error) {
909
1234
  return {
910
- error: formatDeploymentFailure(error),
1235
+ error: errorMessage(error),
911
1236
  running: false
912
1237
  };
913
1238
  }
@@ -927,7 +1252,7 @@ function backgroundStatus(slot) {
927
1252
  try {
928
1253
  supervisor = slot.adapter?.status?.();
929
1254
  } catch (error) {
930
- slot.error = formatDeploymentFailure(error);
1255
+ slot.error = errorMessage(error);
931
1256
  }
932
1257
  return Object.freeze({
933
1258
  ...componentStatus(slot),
@@ -1039,6 +1364,12 @@ function makeDeploymentControl(input) {
1039
1364
  steer: (request) => input.host.steerEndpoint(slot.definition.id, request)
1040
1365
  });
1041
1366
  }))) || degraded;
1367
+ let superagentFailure;
1368
+ if (input.superagent !== void 0) {
1369
+ const started = yield* Effect.exit(input.superagent.start());
1370
+ if (Exit.isFailure(started)) superagentFailure = Cause.squash(started.cause);
1371
+ degraded = Exit.isFailure(started) || started.value || degraded;
1372
+ }
1042
1373
  for (const slot of input.automationSlots) {
1043
1374
  const resolvedDefinition = slot.resolvedDefinition;
1044
1375
  const deliverySlot = endpointById.get(slot.definition.delivery.endpointId);
@@ -1086,7 +1417,7 @@ function makeDeploymentControl(input) {
1086
1417
  }))) || degraded;
1087
1418
  }
1088
1419
  lifecycle = transitionDeploymentControlLifecycle(lifecycle, degraded ? "degraded" : "running");
1089
- const failure = readinessFailure();
1420
+ const failure = superagentFailure ?? readinessFailure();
1090
1421
  if (failure) return yield* Effect.fail(failure);
1091
1422
  });
1092
1423
  }),
@@ -1096,8 +1427,12 @@ function makeDeploymentControl(input) {
1096
1427
  lifecycle = transitionDeploymentControlLifecycle(lifecycle, "stopping");
1097
1428
  return Effect.gen(function* () {
1098
1429
  const errors = [];
1099
- yield* stopSlots(input.automationSlots, errors);
1100
1430
  if (input.backgroundSessionSlot) yield* stopSlots([input.backgroundSessionSlot], errors);
1431
+ yield* stopSlots(input.automationSlots, errors);
1432
+ if (input.superagent !== void 0) {
1433
+ const result = yield* Effect.exit(input.superagent.stop());
1434
+ if (Exit.isFailure(result)) errors.push(Cause.squash(result.cause));
1435
+ }
1101
1436
  yield* stopSlots(input.endpointSlots, errors);
1102
1437
  const hostExit = yield* Effect.exit(input.host.dispose());
1103
1438
  if (Exit.isFailure(hostExit)) errors.push(Cause.squash(hostExit.cause));
@@ -1112,6 +1447,7 @@ function createRivusDeploymentControl(input) {
1112
1447
  return Effect.gen(function* () {
1113
1448
  return makeDeploymentControl({
1114
1449
  ...yield* prepareDeployment(input),
1450
+ ...input.superagent === void 0 ? {} : { superagent: input.superagent },
1115
1451
  ...input.automationFactory ? { automationFactory: input.automationFactory } : {},
1116
1452
  ...input.backgroundSessionFactory ? { backgroundSessionFactory: input.backgroundSessionFactory } : {},
1117
1453
  endpointFactory: input.endpointFactory
@@ -1125,17 +1461,17 @@ function createRivusDeploymentControl(input) {
1125
1461
  * treated as absent, so the owner-specific error texts below keep firing in their
1126
1462
  * original order.
1127
1463
  */
1128
- function tolerant$1(schema) {
1464
+ function tolerant(schema) {
1129
1465
  return Schema.optionalKey(schema.pipe(Schema.catchDecoding(() => Effect.succeed(Option.none()))));
1130
1466
  }
1131
1467
  const rivusHomeConfigSchema = Schema.Struct({
1132
- bootstrap: tolerant$1(Schema.String),
1133
- envFile: tolerant$1(Schema.String),
1134
- logs: tolerant$1(Schema.String),
1135
- manifest: tolerant$1(Schema.String),
1136
- state: tolerant$1(Schema.String),
1137
- version: tolerant$1(Schema.Literal(1)),
1138
- workspace: tolerant$1(Schema.String)
1468
+ bootstrap: tolerant(Schema.String),
1469
+ envFile: tolerant(Schema.String),
1470
+ logs: tolerant(Schema.String),
1471
+ manifest: tolerant(Schema.String),
1472
+ state: tolerant(Schema.String),
1473
+ version: tolerant(Schema.Literal(1)),
1474
+ workspace: tolerant(Schema.String)
1139
1475
  });
1140
1476
  const decodeRivusHomeConfig = Schema.decodeUnknownOption(rivusHomeConfigSchema);
1141
1477
  function resolveHomePath(directory, value, owner) {
@@ -1173,9 +1509,6 @@ function parseRivusHomeConfig(value) {
1173
1509
  workspace: relativePath(config.workspace, "workspace")
1174
1510
  };
1175
1511
  }
1176
- function asError$1(error) {
1177
- return error instanceof Error ? error : new Error(String(error));
1178
- }
1179
1512
  /** Loads and validates the operator-owned Home config file. */
1180
1513
  function loadRivusHome(directoryPath) {
1181
1514
  const directory = resolve(directoryPath);
@@ -1195,7 +1528,7 @@ function loadRivusHome(directoryPath) {
1195
1528
  workspaceDirectory: resolveHomePath(directory, config.workspace, "workspace")
1196
1529
  };
1197
1530
  },
1198
- catch: asError$1
1531
+ catch: toError
1199
1532
  });
1200
1533
  }
1201
1534
  //#endregion
@@ -1411,7 +1744,7 @@ function initializeRivusHome(directoryPath) {
1411
1744
  files: paths
1412
1745
  };
1413
1746
  },
1414
- catch: (error) => error instanceof Error ? error : new Error(String(error))
1747
+ catch: toError
1415
1748
  });
1416
1749
  }
1417
1750
  //#endregion
@@ -1436,7 +1769,7 @@ function findMissingRivusHomeWorkspacePaths(home) {
1436
1769
  }
1437
1770
  return missing;
1438
1771
  },
1439
- catch: (error) => error instanceof Error ? error : new Error(String(error))
1772
+ catch: toError
1440
1773
  });
1441
1774
  }
1442
1775
  //#endregion
@@ -1453,116 +1786,6 @@ function createNodeRivusHome(options) {
1453
1786
  };
1454
1787
  }
1455
1788
  //#endregion
1456
- //#region src/home/infra/repository/runtime-receipt.ts
1457
- const absolutePath = Schema.String.check(Schema.makeFilter(isAbsolute));
1458
- const runtimeReceiptSchema = Schema.Struct({
1459
- schemaVersion: Schema.Literal(1),
1460
- home: absolutePath,
1461
- pid: Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0)),
1462
- version: Schema.Trimmed.check(Schema.isNonEmpty()),
1463
- executable: absolutePath,
1464
- startedAt: Schema.String.check(Schema.makeFilter((value) => Number.isFinite(Date.parse(value))))
1465
- });
1466
- async function writeRuntimeReceipt(input) {
1467
- const receipt = Schema.decodeUnknownSync(runtimeReceiptSchema)({
1468
- ...input,
1469
- home: await realpath(input.home),
1470
- executable: await realpath(input.executable),
1471
- schemaVersion: 1
1472
- });
1473
- const directory = join(receipt.home, ".rivus-upgrade");
1474
- await mkdir(directory, {
1475
- mode: 448,
1476
- recursive: true
1477
- });
1478
- await chmod(directory, 448);
1479
- const path = join(directory, "runtime.json");
1480
- await chmod(path, 384).catch((error) => {
1481
- if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
1482
- });
1483
- await writeAtomicTextFile(path, `${JSON.stringify(receipt)}\n`, {
1484
- durable: true,
1485
- mode: 384
1486
- });
1487
- }
1488
- async function readRuntimeReceipt(home) {
1489
- let canonicalHome;
1490
- let raw;
1491
- try {
1492
- canonicalHome = await realpath(home);
1493
- raw = await readFile(join(canonicalHome, ".rivus-upgrade", "runtime.json"), "utf8");
1494
- } catch (error) {
1495
- if (isNodeErrorWithCode(error, "ENOENT")) return;
1496
- throw error;
1497
- }
1498
- try {
1499
- const receipt = Schema.decodeUnknownSync(runtimeReceiptSchema)(JSON.parse(raw));
1500
- return receipt.home === canonicalHome ? receipt : void 0;
1501
- } catch {
1502
- return;
1503
- }
1504
- }
1505
- async function clearRuntimeReceipt(home, pid) {
1506
- const receipt = await readRuntimeReceipt(home);
1507
- if (receipt?.pid === pid) await unlink(join(receipt.home, ".rivus-upgrade", "runtime.json")).catch((error) => {
1508
- if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
1509
- });
1510
- }
1511
- //#endregion
1512
- //#region src/home/infra/repository/upgrade-journal.ts
1513
- const recordSchema$1 = Schema.fromJsonString(Schema.Struct({
1514
- schemaVersion: Schema.Literal(1),
1515
- id: Schema.NonEmptyString,
1516
- home: Schema.NonEmptyString,
1517
- sourceVersion: Schema.NonEmptyString,
1518
- targetVersion: Schema.NonEmptyString,
1519
- sourceCommand: Schema.Array(Schema.NonEmptyString),
1520
- service: Schema.Struct({
1521
- kind: Schema.Literals(["launchd", "systemd"]),
1522
- id: Schema.NonEmptyString,
1523
- definitionPath: Schema.NonEmptyString
1524
- }),
1525
- phase: Schema.Literals([
1526
- "preparing",
1527
- "prepared",
1528
- "stopping",
1529
- "stopped",
1530
- "backed-up",
1531
- "switching",
1532
- "starting",
1533
- "complete"
1534
- ]),
1535
- createdAt: Schema.NonEmptyString,
1536
- startedAfter: Schema.optional(Schema.NonEmptyString)
1537
- }));
1538
- function upgradePaths(home, id) {
1539
- const directory = join(home, ".rivus-upgrade");
1540
- return {
1541
- directory,
1542
- journal: join(directory, "operation.json"),
1543
- release: join(directory, "releases", id ?? ""),
1544
- backup: join(directory, "backups", id ?? "")
1545
- };
1546
- }
1547
- async function readUpgradeRecord(home) {
1548
- const text = await readPersistenceFile(upgradePaths(home).journal);
1549
- if (text === void 0) return;
1550
- const record = Schema.decodeUnknownSync(recordSchema$1)(text);
1551
- if (record.home !== home || !/^[a-f\d-]{36}$/.test(record.id)) throw new Error("upgrade journal belongs to another Home or has an invalid operation id");
1552
- return record;
1553
- }
1554
- async function writeUpgradeRecord(record) {
1555
- const paths = upgradePaths(record.home);
1556
- await mkdir(paths.directory, {
1557
- recursive: true,
1558
- mode: 448
1559
- });
1560
- await writeAtomicTextFile(paths.journal, `${JSON.stringify(record)}\n`, {
1561
- durable: true,
1562
- mode: 384
1563
- });
1564
- }
1565
- //#endregion
1566
1789
  //#region src/home/infra/adapters/project/rivus-project-initializer.ts
1567
1790
  const TEMPLATE_FILES = Object.freeze({
1568
1791
  "current-weather.mjs": "current-weather.mjs",
@@ -1621,20 +1844,17 @@ async function assertSafeProjectAncestors(directory, paths) {
1621
1844
  }
1622
1845
  }
1623
1846
  }
1624
- function asError(error) {
1625
- return error instanceof Error ? error : new Error(String(error));
1626
- }
1627
1847
  async function rollbackCreatedPaths(files, directories) {
1628
1848
  const errors = [];
1629
1849
  for (const path of files.reverse()) try {
1630
1850
  await unlink(path);
1631
1851
  } catch (error) {
1632
- if (!isNodeErrorWithCode(error, "ENOENT")) errors.push(asError(error));
1852
+ if (!isNodeErrorWithCode(error, "ENOENT")) errors.push(toError(error));
1633
1853
  }
1634
1854
  for (const path of directories.reverse()) try {
1635
1855
  await rmdir(path);
1636
1856
  } catch (error) {
1637
- if (!isNodeErrorWithCode(error, "ENOENT") && !isNodeErrorWithCode(error, "ENOTEMPTY")) errors.push(asError(error));
1857
+ if (!isNodeErrorWithCode(error, "ENOENT") && !isNodeErrorWithCode(error, "ENOTEMPTY")) errors.push(toError(error));
1638
1858
  }
1639
1859
  return errors;
1640
1860
  }
@@ -1783,96 +2003,8 @@ async function initializeRivusProject(options) {
1783
2003
  };
1784
2004
  }
1785
2005
  //#endregion
1786
- //#region src/deployment/infra/adapters/plugin/rivus-plugin-module.ts
1787
- /**
1788
- * A plugin export is not JSON data: `register` must be a function, while `manifest` only
1789
- * has to be present — the plugin catalog validates its shape afterwards. `Schema.is`
1790
- * returns the module itself, so the exported object keeps its identity.
1791
- */
1792
- const rivusPluginSchema = Schema.Struct({
1793
- manifest: Schema.Any,
1794
- register: Schema.Any.check(Schema.makeFilter((value) => typeof value === "function"))
1795
- });
1796
- const isRivusPlugin = Schema.is(rivusPluginSchema);
1797
- function toError$3(error) {
1798
- return error instanceof Error ? error : new Error(String(error));
1799
- }
1800
- function resolveRivusPluginModule(module) {
1801
- const candidate = "default" in module ? module.default : module;
1802
- return (typeof candidate === "function" ? Effect.tryPromise({
1803
- try: () => Promise.resolve(candidate()),
1804
- catch: toError$3
1805
- }) : Effect.succeed(candidate)).pipe(Effect.flatMap((plugin) => isRivusPlugin(plugin) ? Effect.succeed(plugin) : Effect.fail(/* @__PURE__ */ new Error("plugin module default export is not a RivusPlugin or factory"))));
1806
- }
1807
- //#endregion
1808
- //#region src/deployment/infra/adapters/plugin/trusted-package-root.ts
1809
- function findTrustedPackageRoot(packageManifestPath) {
1810
- return Effect.tryPromise({
1811
- try: async () => {
1812
- const manifestRealpath = await realpath(packageManifestPath);
1813
- const packageRoot = dirname(manifestRealpath);
1814
- let current = packageRoot;
1815
- for (;;) {
1816
- if (basename(current) === "node_modules") return current;
1817
- const parent = dirname(current);
1818
- if (parent === current) return packageRoot;
1819
- current = parent;
1820
- }
1821
- },
1822
- catch: (error) => error instanceof Error ? error : new Error(String(error))
1823
- });
1824
- }
1825
- //#endregion
1826
- //#region src/deployment/infra/adapters/plugin/trusted-module-path.ts
1827
- function validateTrustedModulePath(trustedRoot, resolvedPath, subject) {
1828
- return Effect.try({
1829
- try: () => {
1830
- assertPathWithin(trustedRoot, resolvedPath, `${subject} resolves outside trusted module root: ${resolvedPath}`);
1831
- return resolvedPath;
1832
- },
1833
- catch: (failure) => failure instanceof Error ? failure : new Error(String(failure))
1834
- });
1835
- }
1836
- //#endregion
1837
- //#region src/deployment/infra/adapters/plugin/node-rivus-plugin-module-loader.ts
1838
- function toError$2(error) {
1839
- return error instanceof Error ? error : new Error(String(error));
1840
- }
1841
- function resolveNodeRivusPluginModulePath(request, options = {}) {
1842
- return Effect.gen(function* () {
1843
- const deploymentRoot = yield* Effect.tryPromise({
1844
- try: () => realpath(request.deploymentRoot),
1845
- catch: toError$2
1846
- });
1847
- const moduleSpecifier = request.module;
1848
- const relativeModule = moduleSpecifier.startsWith("./") || moduleSpecifier.startsWith("../");
1849
- const resolutionManifest = relativeModule ? join(deploymentRoot, "package.json") : options.packageManifestPath ?? join(deploymentRoot, "package.json");
1850
- const resolved = yield* Effect.try({
1851
- try: () => createRequire(resolutionManifest).resolve(moduleSpecifier),
1852
- catch: toError$2
1853
- });
1854
- const resolvedRealpath = yield* Effect.tryPromise({
1855
- try: () => realpath(resolved),
1856
- catch: toError$2
1857
- });
1858
- return yield* validateTrustedModulePath(relativeModule ? deploymentRoot : options.packageManifestPath ? yield* findTrustedPackageRoot(options.packageManifestPath) : deploymentRoot, resolvedRealpath, `plugin module ${request.module}`);
1859
- });
1860
- }
1861
- function loadNodeRivusPluginModule(request, options = {}) {
1862
- return resolveNodeRivusPluginModulePath(request, options).pipe(Effect.flatMap((resolvedRealpath) => Effect.tryPromise({
1863
- try: () => import(pathToFileURL(resolvedRealpath).href),
1864
- catch: toError$2
1865
- })));
1866
- }
1867
- function createNodeRivusPluginModuleLoader(options = {}) {
1868
- return { load: (request) => loadNodeRivusPluginModule(request, options).pipe(Effect.flatMap(resolveRivusPluginModule)) };
1869
- }
1870
- //#endregion
1871
2006
  //#region src/deployment/infra/adapters/inspection/rivus-home-deployment-inspector.ts
1872
2007
  const FEISHU_BOOTSTRAP = "@rivus/gateway/bootstrap/feishu";
1873
- function toError$1(error) {
1874
- return error instanceof Error ? error : new Error(String(error));
1875
- }
1876
2008
  function toEffect(read) {
1877
2009
  return Effect.suspend(() => {
1878
2010
  try {
@@ -1880,10 +2012,10 @@ function toEffect(read) {
1880
2012
  if (Effect.isEffect(value)) return value;
1881
2013
  return Effect.tryPromise({
1882
2014
  try: () => Promise.resolve(value),
1883
- catch: toError$1
2015
+ catch: toError
1884
2016
  });
1885
2017
  } catch (error) {
1886
- return Effect.fail(toError$1(error));
2018
+ return Effect.fail(toError(error));
1887
2019
  }
1888
2020
  });
1889
2021
  }
@@ -1893,17 +2025,15 @@ function defaultResolveModule(specifier, packageManifestPath, homeDirectory) {
1893
2025
  return Effect.gen(function* () {
1894
2026
  const resolvedRealpath = yield* Effect.tryPromise({
1895
2027
  try: () => realpath(fileURLToPath(import.meta.resolve(specifier))),
1896
- catch: toError$1
2028
+ catch: toError
1897
2029
  });
1898
- return yield* validateTrustedModulePath(homeLocal ? yield* Effect.tryPromise({
2030
+ const trustedRoot = homeLocal ? yield* Effect.tryPromise({
1899
2031
  try: () => realpath(homeDirectory),
1900
- catch: toError$1
1901
- }) : yield* findTrustedPackageRoot(packageManifestPath), resolvedRealpath, `module ${specifier}`);
2032
+ catch: toError
2033
+ }) : yield* findTrustedPackageRoot(packageManifestPath);
2034
+ return yield* validateTrustedModulePath(trustedRoot, resolvedRealpath, `module ${specifier}`);
1902
2035
  });
1903
2036
  }
1904
- function formatError(error) {
1905
- return error instanceof Error ? error.message : String(error);
1906
- }
1907
2037
  function checkManifest$1(home) {
1908
2038
  return loadRivusDeploymentManifest(home.manifestPath).pipe(Effect.map((manifest) => {
1909
2039
  validateRivusDeploymentManifest(manifest);
@@ -1916,7 +2046,7 @@ function checkManifest$1(home) {
1916
2046
  manifest
1917
2047
  };
1918
2048
  }), Effect.catch((error) => Effect.succeed({ check: {
1919
- message: `deployment manifest is invalid: ${formatError(error)}`,
2049
+ message: `deployment manifest is invalid: ${errorMessage(error)}`,
1920
2050
  name: "manifest",
1921
2051
  status: "fail"
1922
2052
  } })));
@@ -1932,7 +2062,7 @@ function checkModules(home, manifest, resolveModule, resolvePluginModule) {
1932
2062
  const missing = [];
1933
2063
  for (const specifier of specifiers) {
1934
2064
  const result = yield* toEffect(() => resolveModule(specifier)).pipe(Effect.result);
1935
- if (result._tag === "Failure") missing.push(`${specifier} (${formatError(result.failure)})`);
2065
+ if (result._tag === "Failure") missing.push(`${specifier} (${errorMessage(result.failure)})`);
1936
2066
  }
1937
2067
  for (const plugin of manifest.plugins) {
1938
2068
  const result = yield* toEffect(() => resolvePluginModule({
@@ -1940,7 +2070,7 @@ function checkModules(home, manifest, resolveModule, resolvePluginModule) {
1940
2070
  module: plugin.module,
1941
2071
  pluginId: plugin.id
1942
2072
  })).pipe(Effect.result);
1943
- if (result._tag === "Failure") missing.push(`${plugin.module} (${formatError(result.failure)})`);
2073
+ if (result._tag === "Failure") missing.push(`${plugin.module} (${errorMessage(result.failure)})`);
1944
2074
  }
1945
2075
  return missing.length === 0 ? {
1946
2076
  message: "Bootstrap, Plugin, runtime, and Feishu modules resolve; run check-config --load-plugins to import them",
@@ -1953,7 +2083,7 @@ function checkModules(home, manifest, resolveModule, resolvePluginModule) {
1953
2083
  };
1954
2084
  });
1955
2085
  }
1956
- function checkCredentials$1(home, manifest, env, envFilePath, isModelManagementEnabled) {
2086
+ function checkCredentials$1(home, manifest, env, envFilePath, isModelManagementEnabled, checkSuperagents, nodeVersion, packageManifestPath) {
1957
2087
  if (!manifest) return Effect.succeed({
1958
2088
  message: "credentials cannot be checked until manifest is valid",
1959
2089
  name: "credentials",
@@ -1962,7 +2092,11 @@ function checkCredentials$1(home, manifest, env, envFilePath, isModelManagementE
1962
2092
  return Effect.tryPromise({
1963
2093
  try: async () => {
1964
2094
  const merged = await loadMergedLocalEnvFile(envFilePath ? resolve(home.directory, envFilePath) : home.envFilePath, env);
1965
- for (const endpoint of manifest.endpoints.filter(({ enabled }) => enabled)) resolveFeishuEndpointCredentials(endpoint.credentialRef, merged);
2095
+ await checkSuperagents?.(manifest, merged, nodeVersion, {
2096
+ deploymentRoot: home.directory,
2097
+ packageManifestPath
2098
+ });
2099
+ for (const endpoint of [...manifest.endpoints, ...manifest.superagentEndpoints ?? []].filter(({ enabled }) => enabled)) resolveFeishuEndpointCredentials(endpoint.credentialRef, merged);
1966
2100
  for (const agent of manifest.agents) if (agent.runtime) await resolveAcpRuntimeEnvironment(agent.runtime, merged);
1967
2101
  if (isModelManagementEnabled(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");
1968
2102
  return {
@@ -1971,9 +2105,9 @@ function checkCredentials$1(home, manifest, env, envFilePath, isModelManagementE
1971
2105
  status: "pass"
1972
2106
  };
1973
2107
  },
1974
- catch: toError$1
2108
+ catch: toError
1975
2109
  }).pipe(Effect.catch((error) => Effect.succeed({
1976
- message: `deployment environment is incomplete: ${formatError(error)}`,
2110
+ message: `deployment environment is incomplete: ${errorMessage(error)}`,
1977
2111
  name: "credentials",
1978
2112
  status: "fail"
1979
2113
  })));
@@ -1982,7 +2116,7 @@ function createRivusHomeDeploymentInspector(options) {
1982
2116
  const resolvePluginModule = options.resolvePluginModule ?? ((request) => resolveNodeRivusPluginModulePath(request, options.packageManifestPath ? { packageManifestPath: options.packageManifestPath } : {}));
1983
2117
  return { inspect: (input) => Effect.gen(function* () {
1984
2118
  const manifestResult = yield* checkManifest$1(input.home);
1985
- const credentials = yield* checkCredentials$1(input.home, manifestResult.manifest, input.env, input.envFilePath, options.isModelManagementEnabled);
2119
+ const credentials = yield* checkCredentials$1(input.home, manifestResult.manifest, input.env, input.envFilePath, options.isModelManagementEnabled, options.checkSuperagents, process.versions.node, options.packageManifestPath);
1986
2120
  const modules = yield* checkModules(input.home, manifestResult.manifest, options.resolveModule ?? ((specifier) => defaultResolveModule(specifier, options.packageManifestPath, input.home.directory)), resolvePluginModule);
1987
2121
  return {
1988
2122
  credentials,
@@ -2011,8 +2145,7 @@ function checkManifest(directory) {
2011
2145
  for (const plugin of manifest.plugins) {
2012
2146
  const result = yield* resolveNodeRivusPluginModulePath({
2013
2147
  deploymentRoot: directory,
2014
- module: plugin.module,
2015
- pluginId: plugin.id
2148
+ module: plugin.module
2016
2149
  }).pipe(Effect.result);
2017
2150
  if (Result.isFailure(result)) missingModules.push(plugin.module);
2018
2151
  }
@@ -2035,7 +2168,7 @@ function checkManifest(directory) {
2035
2168
  status: "fail"
2036
2169
  } })));
2037
2170
  }
2038
- async function checkCredentials(manifest, envFilePath, env) {
2171
+ async function checkCredentials(directory, manifest, envFilePath, env, checkSuperagents, nodeVersion) {
2039
2172
  let mergedEnv;
2040
2173
  try {
2041
2174
  mergedEnv = await loadMergedLocalEnvFile(envFilePath, env);
@@ -2052,7 +2185,11 @@ async function checkCredentials(manifest, envFilePath, env) {
2052
2185
  status: "fail"
2053
2186
  };
2054
2187
  try {
2055
- for (const endpoint of manifest.endpoints.filter(({ enabled }) => enabled)) resolveFeishuEndpointCredentials(endpoint.credentialRef, mergedEnv);
2188
+ await checkSuperagents?.(manifest, mergedEnv, nodeVersion, {
2189
+ deploymentRoot: directory,
2190
+ packageManifestPath: void 0
2191
+ });
2192
+ for (const endpoint of [...manifest.endpoints, ...manifest.superagentEndpoints ?? []].filter(({ enabled }) => enabled)) resolveFeishuEndpointCredentials(endpoint.credentialRef, mergedEnv);
2056
2193
  return {
2057
2194
  message: "enabled Endpoint credential references resolve",
2058
2195
  name: "credentials",
@@ -2102,9 +2239,6 @@ async function checkDependencies(directory) {
2102
2239
  status: "fail"
2103
2240
  };
2104
2241
  }
2105
- function toError(error) {
2106
- return error instanceof Error ? error : new Error(String(error));
2107
- }
2108
2242
  function diagnoseRivusProject(options) {
2109
2243
  return Effect.gen(function* () {
2110
2244
  const directory = resolve(options.directory);
@@ -2121,7 +2255,7 @@ function diagnoseRivusProject(options) {
2121
2255
  checks.push(manifestResult.check);
2122
2256
  const envFilePath = resolve(directory, options.envFilePath ?? ".env.local");
2123
2257
  checks.push(yield* Effect.tryPromise({
2124
- try: () => checkCredentials(manifestResult.manifest, envFilePath, options.env),
2258
+ try: () => checkCredentials(directory, manifestResult.manifest, envFilePath, options.env, options.checkSuperagents, options.nodeVersion),
2125
2259
  catch: toError
2126
2260
  }));
2127
2261
  return Object.freeze({
@@ -2209,7 +2343,7 @@ function nodeRivusPluginLoader(options = {}) {
2209
2343
  /** Resolves Project Space directories on the local filesystem. */
2210
2344
  const NodeRivusProjectSpaceResolverLive = Layer.succeed(RivusProjectSpaceResolver, { resolve: (input) => Effect.tryPromise({
2211
2345
  try: () => resolveRivusProjectSpace(input),
2212
- catch: toDeploymentFailure
2346
+ catch: toError
2213
2347
  }) });
2214
2348
  //#endregion
2215
2349
  //#region src/model-management/infra/adapters/cli/rivus-model-management-socket-client.ts
@@ -2280,32 +2414,6 @@ function createRivusModelManagementSocketClient(options) {
2280
2414
  return { execute: (command) => request(options.socketPath, options.env, command, timeoutMs) };
2281
2415
  }
2282
2416
  //#endregion
2283
- //#region src/model-management/infra/adapters/cli/rivus-model-socket.ts
2284
- const RIVUS_MODEL_SOCKET_ENV = "RIVUS_MODEL_SOCKET";
2285
- const RIVUS_MODEL_MANAGEMENT_ENABLED_ENV = "RIVUS_MODEL_MANAGEMENT_ENABLED";
2286
- const RIVUS_MODEL_SOCKET_RELATIVE_PATH = "state/model-management/control.sock";
2287
- function resolveAbsoluteHome(value) {
2288
- if (!isAbsolute(value)) throw new Error("RIVUS_HOME must be an absolute path");
2289
- return resolve(value);
2290
- }
2291
- function optional(value) {
2292
- return value?.trim() || void 0;
2293
- }
2294
- function resolveRivusModelSocketPath(options) {
2295
- const configured = optional(options.env[RIVUS_MODEL_SOCKET_ENV]);
2296
- if (configured) {
2297
- if (!isAbsolute(configured)) throw new Error(`${RIVUS_MODEL_SOCKET_ENV} must be an absolute path`);
2298
- return resolve(configured);
2299
- }
2300
- const configuredHome = optional(options.env.RIVUS_HOME);
2301
- const home = configuredHome ? resolveAbsoluteHome(configuredHome) : resolve(options.homeDirectory, ".rivus-agent");
2302
- return join(home, RIVUS_MODEL_SOCKET_RELATIVE_PATH);
2303
- }
2304
- function isRivusModelManagementEnabled(env) {
2305
- const value = optional(env[RIVUS_MODEL_MANAGEMENT_ENABLED_ENV]);
2306
- return value === "1" || value === "true";
2307
- }
2308
- //#endregion
2309
2417
  //#region src/bootstrap/cli/release-package-resolution.ts
2310
2418
  /**
2311
2419
  * Packages the running release provides to every module in the process. Rivus classes, services and Effect values
@@ -2395,7 +2503,7 @@ function installReleasePackageResolution() {
2395
2503
  registerHooks({ resolve });
2396
2504
  }
2397
2505
  //#endregion
2398
- //#region src/cli/domain/cli/value-objects/rivus-cli-protocol.ts
2506
+ //#region src/cli/lib/home/rivus-cli-protocol.ts
2399
2507
  const RIVUS_CLI_USAGE = `Usage:
2400
2508
  rivus setup [directory]
2401
2509
  rivus upgrade [--json]
@@ -2406,6 +2514,8 @@ const RIVUS_CLI_USAGE = `Usage:
2406
2514
  rivus init [directory]
2407
2515
  rivus doctor [directory] [--env-file <path>]
2408
2516
  rivus model <status|set|rollback> ...
2517
+ rivus superagent <command> ...
2518
+ rivus task <show|report|call> ...
2409
2519
  rivus audio <install|status|transcribe> ...
2410
2520
  rivus --bootstrap <module> [--manifest <rivus.config.json>] [options]
2411
2521
 
@@ -2420,12 +2530,14 @@ Commands:
2420
2530
  init Create a standalone local Rivus project without overwriting files
2421
2531
  doctor Check Rivus Home by default, or an explicit standalone project directory
2422
2532
  model Query or change the managed default model through the current Home
2533
+ superagent Inspect or control the Superagent and its tasks
2534
+ task Call tools for the current worker execution
2423
2535
  audio Install, inspect, or run the managed audio transcriber of the current Home
2424
2536
 
2425
2537
  Run rivus --help for the complete daemon option list.
2426
2538
  `;
2427
2539
  function renderRivusCliError(error) {
2428
- return `${error instanceof Error ? error.message : String(error)}\n`;
2540
+ return `${errorMessage(error)}\n`;
2429
2541
  }
2430
2542
  function renderRivusCliUnknownCommand(command) {
2431
2543
  return `Unknown command: ${command}\n\n${RIVUS_CLI_USAGE}`;
@@ -2492,7 +2604,7 @@ function renderRivusProjectInitializationSuccess(directory) {
2492
2604
  return `Initialized Rivus project in ${directory}\n\nNext:\n cd ${shellQuote(directory)}\n npm install\n cp .env.example .env.local\n npm run doctor\n npm start\n`;
2493
2605
  }
2494
2606
  //#endregion
2495
- //#region src/cli/domain/cli/value-objects/rivus-recovery-cli-protocol.ts
2607
+ //#region src/cli/lib/recovery/rivus-recovery-cli-protocol.ts
2496
2608
  function consumeArgument(input, argument, next) {
2497
2609
  if (argument === "--recovery-list") {
2498
2610
  input.recoveryList = true;
@@ -2626,7 +2738,7 @@ function createRivusRecoveryCliParser() {
2626
2738
  };
2627
2739
  }
2628
2740
  //#endregion
2629
- //#region src/cli/domain/cli/value-objects/rivus-daemon-arguments.ts
2741
+ //#region src/cli/lib/daemon/rivus-daemon-arguments.ts
2630
2742
  const RIVUS_DAEMON_USAGE = `Usage: rivus --bootstrap <module> --manifest <rivus.config.json>
2631
2743
 
2632
2744
  Starts a local Rivus Agent daemon from an injected bootstrap module.
@@ -2648,21 +2760,6 @@ Options:
2648
2760
  --env-file <path> Load local KEY=value config before reading environment
2649
2761
  --check-config Print redacted local config JSON and exit
2650
2762
  --prompt <text> Run one local prompt through bootstrap promptText() and exit
2651
- --replay-feishu-event <json>
2652
- Replay one Feishu receive-message payload through bootstrap replayReceiveMessage() and exit
2653
- --replay-feishu-text <text>
2654
- Replay one synthetic Feishu receive-message text payload without Feishu side effects and exit
2655
- --feishu-message-id <id>
2656
- Message id for --replay-feishu-text (default om_cli_<timestamp>)
2657
- --feishu-chat-id <id> Chat id for --replay-feishu-text (default oc_cli)
2658
- --feishu-thread-id <id>
2659
- Thread id for --replay-feishu-text (default omt_cli)
2660
- --feishu-tenant-key <key>
2661
- Tenant key for --replay-feishu-text (default tenant_cli)
2662
- --print-openclaw-env <json>
2663
- Print a Rivus env file from an OpenClaw config JSON and exit
2664
- --pi-api-key-file <path>
2665
- Add PI_API_KEY_FILE when using --print-openclaw-env
2666
2763
  --session-key <key> Session key for --prompt (default local:<agent-id>:cli)
2667
2764
  --status Print bootstrap status JSON without starting the daemon
2668
2765
  --recovery-list List stopped Automation occurrences, Dead Letters, and Tool operations requiring reconciliation
@@ -2697,16 +2794,8 @@ function parseRivusDaemonArguments(argv) {
2697
2794
  let bootstrap;
2698
2795
  let checkConfig = false;
2699
2796
  let envFilePath;
2700
- let feishuReplayChatId;
2701
- let feishuReplayMessageId;
2702
- let feishuReplayTenantKey;
2703
- let feishuReplayThreadId;
2704
2797
  let manifestPath;
2705
- let piApiKeyFile;
2706
2798
  let prompt;
2707
- let printOpenClawEnvPath;
2708
- let replayFeishuEventPath;
2709
- let replayFeishuText;
2710
2799
  const recoveryCli = createRivusRecoveryCliParser();
2711
2800
  let sessionKey;
2712
2801
  let status = false;
@@ -2785,166 +2874,6 @@ function parseRivusDaemonArguments(argv) {
2785
2874
  index += 1;
2786
2875
  continue;
2787
2876
  }
2788
- if (arg === "--print-openclaw-env") {
2789
- const value = argv[index + 1];
2790
- if (!value) return {
2791
- error: "--print-openclaw-env requires a JSON file path",
2792
- help: false,
2793
- status
2794
- };
2795
- printOpenClawEnvPath = value;
2796
- index += 1;
2797
- continue;
2798
- }
2799
- if (arg?.startsWith("--print-openclaw-env=")) {
2800
- printOpenClawEnvPath = arg.slice(21);
2801
- if (!printOpenClawEnvPath) return {
2802
- error: "--print-openclaw-env requires a JSON file path",
2803
- help: false,
2804
- status
2805
- };
2806
- continue;
2807
- }
2808
- if (arg === "--pi-api-key-file") {
2809
- const value = argv[index + 1];
2810
- if (!value) return {
2811
- error: "--pi-api-key-file requires a path",
2812
- help: false,
2813
- status
2814
- };
2815
- piApiKeyFile = value;
2816
- index += 1;
2817
- continue;
2818
- }
2819
- if (arg?.startsWith("--pi-api-key-file=")) {
2820
- piApiKeyFile = arg.slice(18);
2821
- if (!piApiKeyFile) return {
2822
- error: "--pi-api-key-file requires a path",
2823
- help: false,
2824
- status
2825
- };
2826
- continue;
2827
- }
2828
- if (arg === "--replay-feishu-event") {
2829
- const value = argv[index + 1];
2830
- if (!value) return {
2831
- error: "--replay-feishu-event requires a JSON file path",
2832
- help: false,
2833
- status
2834
- };
2835
- replayFeishuEventPath = value;
2836
- index += 1;
2837
- continue;
2838
- }
2839
- if (arg?.startsWith("--replay-feishu-event=")) {
2840
- replayFeishuEventPath = arg.slice(22);
2841
- if (!replayFeishuEventPath) return {
2842
- error: "--replay-feishu-event requires a JSON file path",
2843
- help: false,
2844
- status
2845
- };
2846
- continue;
2847
- }
2848
- if (arg === "--replay-feishu-text") {
2849
- const value = argv[index + 1];
2850
- if (!value) return {
2851
- error: "--replay-feishu-text requires text",
2852
- help: false,
2853
- status
2854
- };
2855
- replayFeishuText = value;
2856
- index += 1;
2857
- continue;
2858
- }
2859
- if (arg?.startsWith("--replay-feishu-text=")) {
2860
- replayFeishuText = arg.slice(21);
2861
- if (!replayFeishuText) return {
2862
- error: "--replay-feishu-text requires text",
2863
- help: false,
2864
- status
2865
- };
2866
- continue;
2867
- }
2868
- if (arg === "--feishu-message-id") {
2869
- const value = argv[index + 1];
2870
- if (!value) return {
2871
- error: "--feishu-message-id requires a value",
2872
- help: false,
2873
- status
2874
- };
2875
- feishuReplayMessageId = value;
2876
- index += 1;
2877
- continue;
2878
- }
2879
- if (arg?.startsWith("--feishu-message-id=")) {
2880
- feishuReplayMessageId = arg.slice(20);
2881
- if (!feishuReplayMessageId) return {
2882
- error: "--feishu-message-id requires a value",
2883
- help: false,
2884
- status
2885
- };
2886
- continue;
2887
- }
2888
- if (arg === "--feishu-chat-id") {
2889
- const value = argv[index + 1];
2890
- if (!value) return {
2891
- error: "--feishu-chat-id requires a value",
2892
- help: false,
2893
- status
2894
- };
2895
- feishuReplayChatId = value;
2896
- index += 1;
2897
- continue;
2898
- }
2899
- if (arg?.startsWith("--feishu-chat-id=")) {
2900
- feishuReplayChatId = arg.slice(17);
2901
- if (!feishuReplayChatId) return {
2902
- error: "--feishu-chat-id requires a value",
2903
- help: false,
2904
- status
2905
- };
2906
- continue;
2907
- }
2908
- if (arg === "--feishu-thread-id") {
2909
- const value = argv[index + 1];
2910
- if (!value) return {
2911
- error: "--feishu-thread-id requires a value",
2912
- help: false,
2913
- status
2914
- };
2915
- feishuReplayThreadId = value;
2916
- index += 1;
2917
- continue;
2918
- }
2919
- if (arg?.startsWith("--feishu-thread-id=")) {
2920
- feishuReplayThreadId = arg.slice(19);
2921
- if (!feishuReplayThreadId) return {
2922
- error: "--feishu-thread-id requires a value",
2923
- help: false,
2924
- status
2925
- };
2926
- continue;
2927
- }
2928
- if (arg === "--feishu-tenant-key") {
2929
- const value = argv[index + 1];
2930
- if (!value) return {
2931
- error: "--feishu-tenant-key requires a value",
2932
- help: false,
2933
- status
2934
- };
2935
- feishuReplayTenantKey = value;
2936
- index += 1;
2937
- continue;
2938
- }
2939
- if (arg?.startsWith("--feishu-tenant-key=")) {
2940
- feishuReplayTenantKey = arg.slice(20);
2941
- if (!feishuReplayTenantKey) return {
2942
- error: "--feishu-tenant-key requires a value",
2943
- help: false,
2944
- status
2945
- };
2946
- continue;
2947
- }
2948
2877
  if (arg?.startsWith("--session-key=")) {
2949
2878
  sessionKey = arg.slice(14);
2950
2879
  if (!sessionKey) return {
@@ -3017,96 +2946,8 @@ function parseRivusDaemonArguments(argv) {
3017
2946
  status,
3018
2947
  checkConfig
3019
2948
  };
3020
- if (checkConfig && replayFeishuEventPath !== void 0) return {
3021
- error: "--check-config cannot be combined with --replay-feishu-event",
3022
- help: false,
3023
- status,
3024
- checkConfig
3025
- };
3026
- if (checkConfig && replayFeishuText !== void 0) return {
3027
- error: "--check-config cannot be combined with --replay-feishu-text",
3028
- help: false,
3029
- status,
3030
- checkConfig
3031
- };
3032
- if (checkConfig && printOpenClawEnvPath !== void 0) return {
3033
- error: "--check-config cannot be combined with --print-openclaw-env",
3034
- help: false,
3035
- status,
3036
- checkConfig
3037
- };
3038
- if (printOpenClawEnvPath !== void 0 && prompt !== void 0) return {
3039
- error: "--print-openclaw-env cannot be combined with --prompt",
3040
- help: false,
3041
- status
3042
- };
3043
- if (printOpenClawEnvPath !== void 0 && replayFeishuEventPath !== void 0) return {
3044
- error: "--print-openclaw-env cannot be combined with --replay-feishu-event",
3045
- help: false,
3046
- status
3047
- };
3048
- if (printOpenClawEnvPath !== void 0 && replayFeishuText !== void 0) return {
3049
- error: "--print-openclaw-env cannot be combined with --replay-feishu-text",
3050
- help: false,
3051
- status
3052
- };
3053
- if (printOpenClawEnvPath !== void 0 && status) return {
3054
- error: "--print-openclaw-env cannot be combined with --status",
3055
- help: false,
3056
- status
3057
- };
3058
- if (piApiKeyFile !== void 0 && printOpenClawEnvPath === void 0) return {
3059
- error: "--pi-api-key-file requires --print-openclaw-env",
3060
- help: false,
3061
- status
3062
- };
3063
- if (replayFeishuEventPath !== void 0 && prompt !== void 0) return {
3064
- error: "--replay-feishu-event cannot be combined with --prompt",
3065
- help: false,
3066
- status
3067
- };
3068
- if (replayFeishuEventPath !== void 0 && replayFeishuText !== void 0) return {
3069
- error: "--replay-feishu-event cannot be combined with --replay-feishu-text",
3070
- help: false,
3071
- status
3072
- };
3073
- if (replayFeishuEventPath !== void 0 && status) return {
3074
- error: "--replay-feishu-event cannot be combined with --status",
3075
- help: false,
3076
- status
3077
- };
3078
- if (replayFeishuText !== void 0 && prompt !== void 0) return {
3079
- error: "--replay-feishu-text cannot be combined with --prompt",
3080
- help: false,
3081
- status
3082
- };
3083
- if (replayFeishuText !== void 0 && status) return {
3084
- error: "--replay-feishu-text cannot be combined with --status",
3085
- help: false,
3086
- status
3087
- };
3088
- if (feishuReplayMessageId !== void 0 && replayFeishuText === void 0) return {
3089
- error: "--feishu-message-id requires --replay-feishu-text",
3090
- help: false,
3091
- status
3092
- };
3093
- if (feishuReplayChatId !== void 0 && replayFeishuText === void 0) return {
3094
- error: "--feishu-chat-id requires --replay-feishu-text",
3095
- help: false,
3096
- status
3097
- };
3098
- if (feishuReplayThreadId !== void 0 && replayFeishuText === void 0) return {
3099
- error: "--feishu-thread-id requires --replay-feishu-text",
3100
- help: false,
3101
- status
3102
- };
3103
- if (feishuReplayTenantKey !== void 0 && replayFeishuText === void 0) return {
3104
- error: "--feishu-tenant-key requires --replay-feishu-text",
3105
- help: false,
3106
- status
3107
- };
3108
- if (sessionKey !== void 0 && prompt === void 0) return {
3109
- error: "--session-key requires --prompt",
2949
+ if (sessionKey !== void 0 && prompt === void 0) return {
2950
+ error: "--session-key requires --prompt",
3110
2951
  help: false,
3111
2952
  status
3112
2953
  };
@@ -3122,7 +2963,7 @@ function parseRivusDaemonArguments(argv) {
3122
2963
  help: false,
3123
2964
  status
3124
2965
  };
3125
- if (checkConfig || prompt !== void 0 || printOpenClawEnvPath !== void 0 || replayFeishuEventPath !== void 0 || replayFeishuText !== void 0 || status) return {
2966
+ if (checkConfig || prompt !== void 0 || status) return {
3126
2967
  error: "Recovery commands cannot be combined with another one-shot command",
3127
2968
  help: false,
3128
2969
  status
@@ -3132,24 +2973,16 @@ function parseRivusDaemonArguments(argv) {
3132
2973
  ...bootstrap ? { bootstrap } : {},
3133
2974
  checkConfig,
3134
2975
  ...envFilePath ? { envFilePath } : {},
3135
- ...feishuReplayChatId !== void 0 ? { feishuReplayChatId } : {},
3136
- ...feishuReplayMessageId !== void 0 ? { feishuReplayMessageId } : {},
3137
- ...feishuReplayTenantKey !== void 0 ? { feishuReplayTenantKey } : {},
3138
- ...feishuReplayThreadId !== void 0 ? { feishuReplayThreadId } : {},
3139
2976
  help: false,
3140
2977
  ...manifestPath ? { manifestPath } : {},
3141
- ...piApiKeyFile !== void 0 ? { piApiKeyFile } : {},
3142
2978
  ...prompt !== void 0 ? { prompt } : {},
3143
- ...printOpenClawEnvPath !== void 0 ? { printOpenClawEnvPath } : {},
3144
- ...replayFeishuEventPath !== void 0 ? { replayFeishuEventPath } : {},
3145
- ...replayFeishuText !== void 0 ? { replayFeishuText } : {},
3146
2979
  ...recovery.command ? { recoveryCommand: recovery.command } : {},
3147
2980
  ...sessionKey ? { sessionKey } : {},
3148
2981
  status
3149
2982
  };
3150
2983
  }
3151
2984
  //#endregion
3152
- //#region src/cli/domain/cli/value-objects/rivus-daemon-output.ts
2985
+ //#region src/cli/lib/daemon/rivus-daemon-output.ts
3153
2986
  const RIVUS_DAEMON_STARTED_MESSAGE = "Rivus Agent daemon started\n";
3154
2987
  function formatRivusDaemonUsageError(error) {
3155
2988
  return `${error}\n\n${RIVUS_DAEMON_USAGE}`;
@@ -3160,194 +2993,18 @@ function formatRivusDaemonJson(value) {
3160
2993
  function formatRivusDaemonLine(text) {
3161
2994
  return `${text}\n`;
3162
2995
  }
3163
- function formatRivusDaemonWarning(warning) {
3164
- return `Warning: ${warning}\n`;
3165
- }
3166
2996
  function formatRivusDaemonCapabilityError(capability) {
3167
2997
  return `${{
3168
2998
  recovery: "Bootstrap daemon does not expose openRecoveryControl()",
3169
2999
  status: "Bootstrap daemon does not expose status()",
3170
- prompt: "Bootstrap daemon does not expose promptText(command)",
3171
- replay: "Bootstrap daemon does not expose replayReceiveMessage(payload)"
3000
+ prompt: "Bootstrap daemon does not expose promptText(command)"
3172
3001
  }[capability]}\n`;
3173
3002
  }
3174
3003
  function formatRivusDaemonShutdownFailure(signal, error) {
3175
3004
  return `Failed to stop daemon after ${signal}: ${error}\n`;
3176
3005
  }
3177
3006
  //#endregion
3178
- //#region src/cli/domain/cli/value-objects/rivus-daemon-status.ts
3179
- function formatRivusDaemonError(error) {
3180
- return error instanceof Error ? error.message : String(error);
3181
- }
3182
- //#endregion
3183
- //#region src/cli/infra/adapters/openclaw/openclaw-env-import.ts
3184
- var OpenClawEnvImportError = class extends Error {
3185
- constructor(message) {
3186
- super(message);
3187
- this.name = "OpenClawEnvImportError";
3188
- }
3189
- };
3190
- const DEFAULT_AGENT_ID = "main";
3191
- const DEFAULT_FEISHU_BASE_URL = "https://open.feishu.cn";
3192
- const DEFAULT_LARK_BASE_URL = "https://open.larksuite.com";
3193
- const DEFAULT_STREAM_MIN_INTERVAL_MS = 200;
3194
- const THINKING_LEVELS = /* @__PURE__ */ new Set([
3195
- "off",
3196
- "minimal",
3197
- "low",
3198
- "medium",
3199
- "high",
3200
- "xhigh"
3201
- ]);
3202
- const ENV_FILE_ORDER = [
3203
- "FEISHU_APP_ID",
3204
- "FEISHU_APP_SECRET",
3205
- "FEISHU_BASE_URL",
3206
- "FEISHU_STREAM_MIN_INTERVAL_MS",
3207
- "RIVUS_AGENT_ID",
3208
- "PI_API_KEY_FILE",
3209
- "PI_BASE_URL",
3210
- "PI_MODEL",
3211
- "PI_THINKING_LEVEL"
3212
- ];
3213
- /**
3214
- * OpenClaw config fields are read tolerantly (authoring guide, Validation): a field whose value has the wrong type is treated as
3215
- * absent, so the next fallback path or the default applies.
3216
- */
3217
- function tolerant(schema) {
3218
- return Schema.optionalKey(schema.pipe(Schema.catchDecoding(() => Effect.succeed(Option.none()))));
3219
- }
3220
- const trimmedNonEmpty = Schema.Trim.check(Schema.isNonEmpty());
3221
- const tolerantText = tolerant(Schema.String);
3222
- const tolerantTrimmedText = tolerant(trimmedNonEmpty);
3223
- const providerModelSchema = Schema.Struct({
3224
- id: tolerantTrimmedText,
3225
- reasoning: tolerant(Schema.Struct({
3226
- level: tolerantText,
3227
- thinkLevel: tolerantText,
3228
- thinkingLevel: tolerantText
3229
- })),
3230
- thinkingLevel: tolerantText,
3231
- thinkLevel: tolerantText,
3232
- reasoningLevel: tolerantText
3233
- });
3234
- const openClawConfigSchema = Schema.Struct({
3235
- agents: tolerant(Schema.Struct({
3236
- defaults: tolerant(Schema.Struct({
3237
- model: tolerant(Schema.Struct({ primary: tolerantTrimmedText })),
3238
- models: tolerant(Schema.Record(Schema.String, Schema.Struct({
3239
- thinkingLevel: tolerantText,
3240
- thinkLevel: tolerantText,
3241
- reasoningLevel: tolerantText
3242
- })))
3243
- })),
3244
- list: tolerant(Schema.Array(Schema.Struct({ id: tolerantTrimmedText })))
3245
- })),
3246
- channels: Schema.Struct({ feishu: Schema.Struct({
3247
- appId: trimmedNonEmpty,
3248
- appSecret: trimmedNonEmpty,
3249
- domain: tolerantText
3250
- }) }),
3251
- models: tolerant(Schema.Struct({ providers: tolerant(Schema.Record(Schema.String, Schema.Struct({
3252
- baseUrl: tolerantText,
3253
- models: tolerant(Schema.Array(providerModelSchema))
3254
- }))) }))
3255
- });
3256
- const decodeOpenClawConfig = Schema.decodeUnknownResult(openClawConfigSchema);
3257
- /** Non-empty trimmed text over a decoded string; an empty decoded string is absent. */
3258
- function text(value) {
3259
- return value !== void 0 && value.trim().length > 0 ? value.trim() : void 0;
3260
- }
3261
- function findAgentId(config) {
3262
- const firstAgent = config.agents?.list?.[0];
3263
- return text(firstAgent?.id) ?? DEFAULT_AGENT_ID;
3264
- }
3265
- function firstModelId(provider) {
3266
- const firstModel = (provider.models ?? [])[0];
3267
- return firstModel === void 0 ? void 0 : text(firstModel.id);
3268
- }
3269
- function findPrimaryModelReference(config) {
3270
- const primary = text(config.agents?.defaults?.model?.primary);
3271
- if (primary !== void 0) return primary;
3272
- const providers = config.models?.providers;
3273
- if (providers === void 0) return;
3274
- for (const [providerId, provider] of Object.entries(providers)) {
3275
- const model = firstModelId(provider);
3276
- if (model !== void 0) return `${providerId}/${model}`;
3277
- }
3278
- }
3279
- function parseProviderId(modelReference) {
3280
- const separator = modelReference.indexOf("/");
3281
- return separator > 0 ? modelReference.slice(0, separator) : void 0;
3282
- }
3283
- function readModelId(modelReference) {
3284
- const separator = modelReference.indexOf("/");
3285
- return separator >= 0 && separator < modelReference.length - 1 ? modelReference.slice(separator + 1) : void 0;
3286
- }
3287
- function findThinkingLevel(config, modelReference) {
3288
- const providerId = parseProviderId(modelReference);
3289
- const modelId = readModelId(modelReference);
3290
- const defaultsModel = config.agents?.defaults?.models?.[modelReference];
3291
- const providerModels = providerId === void 0 ? void 0 : config.models?.providers?.[providerId]?.models?.find((model) => text(model.id) === modelId);
3292
- const rawLevel = [
3293
- defaultsModel?.thinkingLevel,
3294
- defaultsModel?.thinkLevel,
3295
- defaultsModel?.reasoningLevel,
3296
- providerModels?.thinkingLevel,
3297
- providerModels?.thinkLevel,
3298
- providerModels?.reasoningLevel,
3299
- providerModels?.reasoning?.level,
3300
- providerModels?.reasoning?.thinkingLevel,
3301
- providerModels?.reasoning?.thinkLevel
3302
- ].map(text).find((candidate) => candidate !== void 0);
3303
- if (rawLevel === void 0) return;
3304
- if (THINKING_LEVELS.has(rawLevel)) return { level: rawLevel };
3305
- return { warning: `Unsupported OpenClaw thinking level '${rawLevel}' was ignored` };
3306
- }
3307
- function inferFeishuBaseUrl(domain) {
3308
- return domain === "lark" ? DEFAULT_LARK_BASE_URL : DEFAULT_FEISHU_BASE_URL;
3309
- }
3310
- function createRivusEnvFromOpenClawConfig(openClawConfig, options = {}) {
3311
- const decoded = decodeOpenClawConfig(openClawConfig);
3312
- if (Result.isFailure(decoded)) {
3313
- const path = (SchemaIssue.makeFormatterStandardSchemaV1()(decoded.failure.issue).issues[0].path ?? []).map(String);
3314
- throw new OpenClawEnvImportError(path.length === 0 ? "OpenClaw config must be an object" : path.length === 3 ? `channels.feishu.${path[2]} is required` : "channels.feishu must be an object");
3315
- }
3316
- const config = decoded.success;
3317
- const appId = text(config.channels.feishu.appId);
3318
- const appSecret = text(config.channels.feishu.appSecret);
3319
- if (!appId || !appSecret) throw new OpenClawEnvImportError(!appId ? "channels.feishu.appId is required" : "channels.feishu.appSecret is required");
3320
- const modelReference = findPrimaryModelReference(config);
3321
- const providerId = modelReference === void 0 ? void 0 : parseProviderId(modelReference);
3322
- const providerBaseUrl = providerId === void 0 ? void 0 : text(config.models?.providers?.[providerId]?.baseUrl);
3323
- const thinkingLevel = modelReference === void 0 ? void 0 : findThinkingLevel(config, modelReference);
3324
- const warnings = thinkingLevel?.warning ? [thinkingLevel.warning] : [];
3325
- return {
3326
- env: {
3327
- FEISHU_APP_ID: appId,
3328
- FEISHU_APP_SECRET: appSecret,
3329
- FEISHU_BASE_URL: options.feishuBaseUrl ?? inferFeishuBaseUrl(text(config.channels.feishu.domain)),
3330
- FEISHU_STREAM_MIN_INTERVAL_MS: String(options.streamMinIntervalMs ?? DEFAULT_STREAM_MIN_INTERVAL_MS),
3331
- RIVUS_AGENT_ID: findAgentId(config),
3332
- ...options.piApiKeyFile ? { PI_API_KEY_FILE: options.piApiKeyFile } : {},
3333
- ...providerBaseUrl ? { PI_BASE_URL: providerBaseUrl } : {},
3334
- ...modelReference ? { PI_MODEL: modelReference } : {},
3335
- ...thinkingLevel?.level ? { PI_THINKING_LEVEL: thinkingLevel.level } : {}
3336
- },
3337
- warnings
3338
- };
3339
- }
3340
- function quoteEnvValue(value) {
3341
- return `'${value.replaceAll("'", "'\\''")}'`;
3342
- }
3343
- function formatRivusEnvFile(env) {
3344
- 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`;
3345
- }
3346
- //#endregion
3347
3007
  //#region src/cli/infra/adapters/config/rivus-daemon-config.ts
3348
- async function loadRivusEnvFromOpenClawConfig(filePath, piApiKeyFile) {
3349
- return createRivusEnvFromOpenClawConfig(JSON.parse(await readFile(filePath, "utf8")), piApiKeyFile ? { piApiKeyFile } : {});
3350
- }
3351
3008
  function toRedactedDeploymentManifest(manifest) {
3352
3009
  return {
3353
3010
  agents: manifest.agents.map(({ agentId, endpointIds, pluginId, profileId, runtime }) => ({
@@ -3393,6 +3050,7 @@ function toRedactedDeploymentManifest(manifest) {
3393
3050
  required,
3394
3051
  sessionNamespace
3395
3052
  })),
3053
+ ...manifest.superagent === void 0 ? {} : { superagent: { endpointIds: manifest.superagent.endpointIds } },
3396
3054
  plugins: manifest.plugins.map(({ id, module, required }) => ({
3397
3055
  id,
3398
3056
  module,
@@ -3426,422 +3084,107 @@ function createLocalCliAgentInvocation(input) {
3426
3084
  tenantKey: "local"
3427
3085
  };
3428
3086
  }
3429
- //#endregion
3430
- //#region src/cli/infra/adapters/recovery/rivus-recovery-cli.ts
3431
- async function readPrivateTextFile(filePath, label, maxBytes) {
3432
- const handle = await open(filePath, constants$1.O_RDONLY | constants$1.O_NOFOLLOW);
3433
- try {
3434
- const metadata = await handle.stat();
3435
- if (!metadata.isFile()) throw new Error(`${label} must be a regular file`);
3436
- if ((metadata.mode & 127) !== 0) throw new Error(`${label} file permissions must be 0600 or stricter`);
3437
- if (metadata.size > maxBytes) throw new Error(`${label} file exceeds ${maxBytes} bytes`);
3438
- const value = (await handle.readFile("utf8")).trim();
3439
- if (!value) throw new Error(`${label} file must not be empty`);
3440
- return value;
3441
- } finally {
3442
- await handle.close();
3087
+ const RIVUS_AUDIO_CLI_USAGE = `Usage:
3088
+ rivus audio install [--force] [--json]
3089
+ rivus audio status
3090
+ rivus audio transcribe <path>
3091
+
3092
+ Commands:
3093
+ install Install or upgrade the managed audio transcriber in the current Home's state directory
3094
+ status Print the installed and shipped transcriber releases as JSON
3095
+ transcribe Print the transcript of one audio file; exits 2 when no speech is detected
3096
+ and ${String(3)} when the transcriber is not installed
3097
+ `;
3098
+ function parseRivusAudioCliArguments(argv) {
3099
+ if (argv.includes("--help") || argv.includes("-h")) return { help: true };
3100
+ const [operation, ...rest] = argv;
3101
+ if (operation === "install") {
3102
+ const flags = new Set(rest);
3103
+ const unknown = rest.find((argument) => argument !== "--force" && argument !== "--json");
3104
+ if (unknown !== void 0) return { error: `Unknown audio install option: ${unknown}` };
3105
+ if (flags.size !== rest.length) return { error: "audio install options may only be provided once" };
3106
+ return {
3107
+ force: flags.has("--force"),
3108
+ json: flags.has("--json"),
3109
+ operation
3110
+ };
3443
3111
  }
3444
- }
3445
- function parseToolResult(value) {
3446
- try {
3447
- return JSON.parse(value);
3448
- } catch {
3449
- throw new Error("Tool result file must contain valid JSON");
3112
+ if (operation === "status") return rest.length === 0 ? { operation } : { error: "audio status accepts no arguments" };
3113
+ if (operation === "transcribe") {
3114
+ const path = rest[0];
3115
+ if (rest.length !== 1 || !path || path.startsWith("-")) return { error: "audio transcribe requires exactly one audio path" };
3116
+ return {
3117
+ operation,
3118
+ path
3119
+ };
3450
3120
  }
3121
+ return { error: "audio requires one of install, status, transcribe" };
3451
3122
  }
3452
- async function runRivusRecoveryCliCommand(control, command) {
3453
- switch (command.type) {
3454
- case "inspect": return Effect.runPromise(control.inspect());
3455
- case "grant-automation-attempt": return Effect.runPromise(control.grantAutomationAttempt({
3456
- actorId: "local-cli",
3457
- automationId: command.automationId,
3458
- expectedRevision: command.expectedRevision,
3459
- note: await readPrivateTextFile(command.noteFilePath, "Recovery note", 16384),
3460
- occurrence: command.occurrence
3461
- }));
3462
- case "requeue-dead-letter": return Effect.runPromise(control.requeueDeadLetter({
3463
- actorId: "local-cli",
3464
- deliveryId: command.deliveryId,
3465
- endpointId: command.endpointId,
3466
- expectedRevision: command.expectedRevision,
3467
- note: await readPrivateTextFile(command.noteFilePath, "Recovery note", 16384)
3468
- }));
3469
- case "resolve-tool-operation": {
3470
- const note = await readPrivateTextFile(command.noteFilePath, "Recovery note", 16384);
3471
- const outcome = command.outcome.status === "applied" ? {
3472
- result: parseToolResult(await readPrivateTextFile(command.outcome.resultFilePath, "Tool result", 1048576)),
3473
- status: "applied"
3474
- } : command.outcome;
3475
- return Effect.runPromise(control.resolveToolOperation({
3476
- actorId: "local-cli",
3477
- expectedRevision: command.expectedRevision,
3478
- instanceId: command.instanceId,
3479
- note,
3480
- operationId: command.operationId,
3481
- outcome
3482
- }));
3483
- }
3484
- }
3123
+ function renderRivusAudioCliArgumentError(error) {
3124
+ return `${error}\n\n${RIVUS_AUDIO_CLI_USAGE}`;
3125
+ }
3126
+ function renderRivusAudioCliStatus(status) {
3127
+ return `${JSON.stringify(status)}\n`;
3128
+ }
3129
+ function renderRivusAudioCliInstallResult(result, json) {
3130
+ if (json) return `${JSON.stringify(result)}\n`;
3131
+ return result.status === "installed" ? `Installed audio transcriber ${result.id} in ${result.release}\n` : `Audio transcriber ${result.id} is already installed in ${result.release}\n`;
3132
+ }
3133
+ function renderRivusAudioCliNotInstalled() {
3134
+ return "audio transcriber is not installed; run: rivus audio install\n";
3485
3135
  }
3486
3136
  //#endregion
3487
- //#region src/agent-host/application/ports.ts
3488
- var AgentInstanceIdentity = class extends Context.Service()("@rivus/gateway/agent-host/AgentInstanceIdentity") {};
3489
- var AgentHostRuntimes = class extends Context.Service()("@rivus/gateway/agent-host/AgentHostRuntimes") {};
3490
- //#endregion
3491
- //#region src/agent-host/application/services/agent-instance-registry.ts
3492
- var AgentInstanceConflict = class extends Error {
3493
- name = "AgentInstanceConflict";
3494
- };
3495
- function bindingKey(binding, agentId) {
3496
- const bindingId = binding.kind === "endpoint" ? binding.endpointId : binding.kind === "automation" ? binding.automationId : binding.agentId;
3497
- return `${binding.kind}:${bindingId}:${agentId}`;
3137
+ //#region src/cli/lib/upgrade/upgrade-cli-protocol.ts
3138
+ const UPGRADE_USAGE = `Usage: rivus upgrade [--json]
3139
+
3140
+ Upgrade the selected Home's managed service to the latest stable npm release.
3141
+ Prepare and validate before stopping, retain the Home and backup, then verify startup.
3142
+ Rerun the same command to resume an interrupted upgrade at its recorded version.
3143
+ `;
3144
+ function parseUpgradeArguments(argv) {
3145
+ if (argv.includes("--help") || argv.includes("-h")) return { help: true };
3146
+ if (argv.length === 0) return { json: false };
3147
+ if (argv.length === 1 && argv[0] === "--json") return { json: true };
3148
+ return { error: "upgrade accepts only --json; it selects the latest stable release automatically" };
3498
3149
  }
3499
- function freezeRecord(record) {
3500
- return Object.freeze({
3501
- ...record,
3502
- binding: Object.freeze({ ...record.binding })
3503
- });
3150
+ function renderUpgradeResult(result, json) {
3151
+ if (json) return `${JSON.stringify(result)}\n`;
3152
+ 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` : ""}`;
3504
3153
  }
3505
- function buildRegistry(identity, options) {
3506
- const records = /* @__PURE__ */ new Map();
3507
- for (const record of options.initialRecords ?? []) {
3508
- if (bindingKey(record.binding, record.agentId) !== record.bindingKey) throw new AgentInstanceConflict(`invalid binding key: ${record.bindingKey}`);
3509
- if (records.has(record.bindingKey)) throw new AgentInstanceConflict(`duplicate binding: ${record.bindingKey}`);
3510
- records.set(record.bindingKey, freezeRecord(record));
3511
- }
3512
- const resolveBinding = (instanceBinding, definition) => Effect.try({
3513
- try: () => {
3514
- const runtimeGenerationId = identity.createRuntimeGenerationId({
3515
- agentId: definition.agentId,
3516
- profileRevision: definition.profileRevision,
3517
- projectSpaceId: definition.projectSpaceId ?? null,
3518
- projectSpaceRevision: definition.projectSpaceRevision ?? null,
3519
- runtimeToolGrantRevision: definition.runtimeToolGrantSet.revision,
3520
- skillGrantRevision: definition.skillGrantSet.revision,
3521
- toolGrantRevision: definition.toolGrantSet.revision
3522
- });
3523
- const key = bindingKey(instanceBinding, definition.agentId);
3524
- const existing = records.get(key);
3525
- if (existing) {
3526
- if (existing.runtimeGenerationId !== runtimeGenerationId) throw new AgentInstanceConflict(`binding ${key} belongs to a different runtime generation`);
3527
- return existing;
3528
- }
3529
- const record = freezeRecord({
3530
- agentId: definition.agentId,
3531
- binding: instanceBinding,
3532
- bindingKey: key,
3533
- instanceId: identity.createInstanceId({
3534
- bindingKey: key,
3535
- runtimeGenerationId
3536
- }),
3537
- runtimeGenerationId
3154
+ //#endregion
3155
+ //#region src/bootstrap/daemon/process/rivus-daemon-shutdown-controller.ts
3156
+ const DEFAULT_SIGNALS = ["SIGINT", "SIGTERM"];
3157
+ function createRivusDaemonShutdownController(options) {
3158
+ let shutdown;
3159
+ const handle = (signal) => {
3160
+ shutdown ??= Effect.runPromise(options.daemon.stop()).then(() => options.onStopped?.(signal)).catch(async (error) => {
3161
+ await options.onError?.(error, signal);
3162
+ throw error;
3163
+ });
3164
+ return shutdown;
3165
+ };
3166
+ return {
3167
+ handle,
3168
+ install: () => {
3169
+ for (const signal of options.signals ?? DEFAULT_SIGNALS) options.signalSource.on(signal, () => {
3170
+ handle(signal);
3538
3171
  });
3539
- records.set(key, record);
3540
- return record;
3541
3172
  },
3542
- catch: (error) => error instanceof AgentInstanceConflict ? error : new AgentInstanceConflict(String(error))
3543
- });
3544
- return {
3545
- resolveAutomation: (automationId, definition) => resolveBinding({
3546
- automationId,
3547
- kind: "automation"
3548
- }, definition),
3549
- resolveBackgroundSession: (agentId, definition) => resolveBinding({
3550
- agentId,
3551
- kind: "background-session"
3552
- }, definition),
3553
- resolveEndpoint: (endpointId, definition) => resolveBinding({
3554
- endpointId,
3555
- kind: "endpoint"
3556
- }, definition),
3557
- snapshot: () => Effect.sync(() => Object.freeze([...records.values()]))
3173
+ stopping: () => shutdown !== void 0
3558
3174
  };
3559
3175
  }
3560
- /** An initial record whose key does not match its binding, or that repeats a binding, dies with `AgentInstanceConflict`. */
3561
- function makeAgentInstanceRegistry(options = {}) {
3562
- return AgentInstanceIdentity.pipe(Effect.flatMap((identity) => Effect.sync(() => buildRegistry(identity, options))));
3563
- }
3564
- //#endregion
3565
- //#region src/agent-host/application/use-cases/agent-host.ts
3566
- var InvalidAgentHostBinding = class extends Error {
3567
- name = "InvalidAgentHostBinding";
3568
- };
3569
- function makeAgentHost(options) {
3570
- return Effect.gen(function* () {
3571
- const runtime = yield* AgentHostRuntimes;
3572
- const registry = yield* makeAgentInstanceRegistry({ initialRecords: options.initialInstanceRecords });
3573
- const definitions = new Map(options.definitions.map((definition) => [definition.agentId, definition]));
3574
- const endpoints = /* @__PURE__ */ new Map();
3575
- const automations = /* @__PURE__ */ new Map();
3576
- const backgroundSessions = /* @__PURE__ */ new Map();
3577
- for (const endpoint of options.endpoints) {
3578
- if (endpoints.has(endpoint.id)) return yield* Effect.fail(new InvalidAgentHostBinding(`duplicate endpoint: ${endpoint.id}`));
3579
- const definition = definitions.get(endpoint.agentId);
3580
- if (!definition) return yield* Effect.fail(new InvalidAgentHostBinding(`unknown endpoint agent: ${endpoint.agentId}`));
3581
- if (!definition.endpointIds.includes(endpoint.id)) return yield* Effect.fail(new InvalidAgentHostBinding(`endpoint ${endpoint.id} is not declared by ${endpoint.agentId}`));
3582
- endpoints.set(endpoint.id, yield* registry.resolveEndpoint(endpoint.id, definition));
3583
- }
3584
- for (const automation of options.automations ?? []) {
3585
- if (automations.has(automation.id)) return yield* Effect.fail(new InvalidAgentHostBinding(`duplicate automation: ${automation.id}`));
3586
- if (!definitions.has(automation.definition.agentId)) return yield* Effect.fail(new InvalidAgentHostBinding(`unknown automation agent: ${automation.definition.agentId}`));
3587
- automations.set(automation.id, yield* registry.resolveAutomation(automation.id, automation.definition));
3588
- }
3589
- for (const backgroundSession of options.backgroundSessions ?? []) {
3590
- if (backgroundSession.definition.agentId !== backgroundSession.agentId) return yield* Effect.fail(new InvalidAgentHostBinding(`background session ${backgroundSession.agentId} cannot bind definition ${backgroundSession.definition.agentId}`));
3591
- if (backgroundSessions.has(backgroundSession.agentId)) return yield* Effect.fail(new InvalidAgentHostBinding(`duplicate background session agent: ${backgroundSession.agentId}`));
3592
- if (!definitions.has(backgroundSession.agentId)) return yield* Effect.fail(new InvalidAgentHostBinding(`unknown background session agent: ${backgroundSession.agentId}`));
3593
- backgroundSessions.set(backgroundSession.agentId, yield* registry.resolveBackgroundSession(backgroundSession.agentId, backgroundSession.definition));
3594
- }
3595
- const resolve = (records, id, message) => {
3596
- const instance = records.get(id);
3597
- return instance ? Effect.succeed(instance) : Effect.fail(new InvalidAgentHostBinding(message));
3598
- };
3599
- const resolveEndpoint = (endpointId) => resolve(endpoints, endpointId, `unknown endpoint: ${endpointId}`);
3600
- const resolveAutomation = (automationId) => resolve(automations, automationId, `unknown automation: ${automationId}`);
3601
- const resolveBackgroundSession = (agentId) => resolve(backgroundSessions, agentId, `unknown background session agent: ${agentId}`);
3602
- return {
3603
- cancelBackgroundSession: (agentId, input) => resolveBackgroundSession(agentId).pipe(Effect.flatMap((instance) => runtime.cancel(instance, input))),
3604
- cancelEndpoint: (endpointId, input) => resolveEndpoint(endpointId).pipe(Effect.flatMap((instance) => runtime.cancel(instance, input))),
3605
- dispose: () => runtime.disposeAll(),
3606
- handleAutomation: (automationId, input) => resolveAutomation(automationId).pipe(Effect.flatMap((instance) => runtime.run(instance, input))),
3607
- handleBackgroundSession: (agentId, input) => resolveBackgroundSession(agentId).pipe(Effect.flatMap((instance) => runtime.run(instance, input))),
3608
- handleEndpoint: (endpointId, input) => resolveEndpoint(endpointId).pipe(Effect.flatMap((instance) => runtime.run(instance, input))),
3609
- resolveAutomation,
3610
- resolveBackgroundSession,
3611
- resolveEndpoint,
3612
- steerEndpoint: (endpointId, input) => resolveEndpoint(endpointId).pipe(Effect.flatMap((instance) => runtime.steer(instance, input)))
3613
- };
3614
- });
3615
- }
3616
- //#endregion
3617
- //#region src/agent-host/infra/adapters/runtime-pool.ts
3618
- var RuntimeResourceBusy = class extends Error {
3619
- name = "RuntimeResourceBusy";
3620
- };
3621
- var RuntimeResourceDisposed = class extends Error {
3622
- name = "RuntimeResourceDisposed";
3623
- };
3624
- var RuntimePoolDisposalTimedOut = class extends Error {
3625
- name = "RuntimePoolDisposalTimedOut";
3626
- };
3627
- const DEFAULT_RUNTIME_DISPOSE_TIMEOUT_MS = 1e4;
3628
- function createEffectRuntimePool(options) {
3629
- const runtimes = createRuntimeCache();
3630
- const active = /* @__PURE__ */ new Map();
3631
- const lifecycle = Semaphore.makeUnsafe(1);
3632
- const existingRuntime = (instance) => Effect.gen(function* () {
3633
- const selected = yield* runtimes.getExisting(instance.instanceId);
3634
- if (!selected || !(yield* runtimes.isCurrent(instance.instanceId, selected.entry))) return;
3635
- return selected.runtime;
3636
- });
3637
- return {
3638
- cancel: (instance, input) => invokeRuntimeControl(existingRuntime(instance), (runtime) => runtime.cancel?.(input)),
3639
- disposeAll: () => Effect.gen(function* () {
3640
- const entries = yield* runtimes.drain();
3641
- yield* lifecycle.withPermits(1)(Effect.sync(() => active.clear()));
3642
- yield* disposeRuntimeCacheEntries({
3643
- dispose: (runtime) => runtime.dispose?.() ?? Effect.void,
3644
- entries,
3645
- failureMessage: "runtime pool disposal failed",
3646
- timeout: {
3647
- milliseconds: options.disposeTimeoutMs ?? DEFAULT_RUNTIME_DISPOSE_TIMEOUT_MS,
3648
- onTimeout: () => new RuntimePoolDisposalTimedOut(`runtime pool disposal timed out after ${options.disposeTimeoutMs ?? DEFAULT_RUNTIME_DISPOSE_TIMEOUT_MS}ms`)
3649
- }
3650
- });
3651
- }),
3652
- run: (instance, input) => Effect.gen(function* () {
3653
- const selected = yield* runtimes.getOrCreate(instance.instanceId, () => options.createRuntime(instance));
3654
- if (!(yield* runtimes.isCurrent(instance.instanceId, selected.entry))) return yield* Effect.fail(new RuntimeResourceDisposed(`runtime was disposed before run start: ${instance.instanceId}`));
3655
- if (selected.runtime.concurrency === "managed") return yield* selected.runtime.run(input);
3656
- const token = yield* lifecycle.withPermits(1)(Effect.gen(function* () {
3657
- if (!(yield* runtimes.isCurrent(instance.instanceId, selected.entry))) return yield* Effect.fail(new RuntimeResourceDisposed(`runtime was disposed before run start: ${instance.instanceId}`));
3658
- if (active.has(instance.instanceId)) return yield* Effect.fail(new RuntimeResourceBusy(`runtime already has an active run: ${instance.instanceId}`));
3659
- const activeToken = Symbol(instance.instanceId);
3660
- active.set(instance.instanceId, activeToken);
3661
- return activeToken;
3662
- }));
3663
- return yield* selected.runtime.run(input).pipe(Effect.ensuring(lifecycle.withPermits(1)(Effect.sync(() => {
3664
- if (active.get(instance.instanceId) === token) active.delete(instance.instanceId);
3665
- }))));
3666
- }),
3667
- steer: (instance, input) => invokeRuntimeControl(existingRuntime(instance), (runtime) => runtime.steer?.(input))
3668
- };
3669
- }
3670
- //#endregion
3671
- //#region src/agent-host/infra/adapters/effect-agent-runtime-pool.ts
3672
- var AgentInstanceBusy = class extends Error {
3673
- name = "AgentInstanceBusy";
3674
- };
3675
- var AgentRuntimeDisposed = class extends Error {
3676
- name = "AgentRuntimeDisposed";
3677
- };
3678
- function mapRuntimePoolError(error) {
3679
- if (error instanceof RuntimeResourceBusy) return new AgentInstanceBusy(error.message.replace(/^runtime /, "agent instance "));
3680
- if (error instanceof RuntimeResourceDisposed) return new AgentRuntimeDisposed(error.message.replace(/^runtime /, "agent runtime "));
3681
- if (error instanceof RuntimePoolDisposalTimedOut) return new AgentRuntimeDisposed(error.message.replace(/^runtime pool /, "agent runtime "));
3682
- return error;
3683
- }
3684
- function createAgentHostRuntimePool(factory, disposeTimeoutMs) {
3685
- const pool = createEffectRuntimePool({
3686
- createRuntime: (instance) => factory.create(instance),
3687
- ...disposeTimeoutMs === void 0 ? {} : { disposeTimeoutMs }
3688
- });
3689
- return {
3690
- cancel: (instance, input) => pool.cancel(instance, input),
3691
- disposeAll: () => pool.disposeAll().pipe(Effect.mapError((error) => error instanceof AggregateError && error.errors.length === 1 ? error.errors[0] : mapRuntimePoolError(error))),
3692
- run: (instance, input) => pool.run(instance, input).pipe(Effect.mapError(mapRuntimePoolError)),
3693
- steer: (instance, steering) => pool.steer(instance, steering)
3694
- };
3695
- }
3696
- //#endregion
3697
- //#region src/agent-host/infra/factories/agent-host-live.ts
3698
- /** Instance and generation ids derived from their inputs, so a restart reproduces them. */
3699
- const StableAgentInstanceIdentityLive = Layer.succeed(AgentInstanceIdentity, {
3700
- createInstanceId: (identity) => createStableId("instance", identity),
3701
- createRuntimeGenerationId: (identity) => createStableId("generation", identity)
3702
- });
3703
- /** One runtime per Agent Instance, created on first use by `factory`; each build of the Layer starts an empty pool. */
3704
- function pooledAgentHostRuntimes(factory) {
3705
- return Layer.sync(AgentHostRuntimes, () => createAgentHostRuntimePool(factory));
3706
- }
3707
- //#endregion
3708
- //#region src/cli/infra/adapters/replay/rivus-daemon-replay.ts
3709
- async function readFeishuReceiveMessagePayload(filePath) {
3710
- return decodeFeishuReceiveMessage(JSON.parse(await readFile(filePath, "utf8")));
3711
- }
3712
- function createSyntheticFeishuTextReplayPayload(text, options) {
3713
- return { event: {
3714
- message: {
3715
- chat_id: options.chatId ?? "oc_cli",
3716
- content: JSON.stringify({ text }),
3717
- message_id: options.messageId ?? `om_cli_${Date.now()}`,
3718
- message_type: "text",
3719
- thread_id: options.threadId ?? "omt_cli"
3720
- },
3721
- sender: { tenant_key: options.tenantKey ?? "tenant_cli" }
3722
- } };
3723
- }
3724
- const RIVUS_AUDIO_CLI_USAGE = `Usage:
3725
- rivus audio install [--force] [--json]
3726
- rivus audio status
3727
- rivus audio transcribe <path>
3728
-
3729
- Commands:
3730
- install Install or upgrade the managed audio transcriber in the current Home's state directory
3731
- status Print the installed and shipped transcriber releases as JSON
3732
- transcribe Print the transcript of one audio file; exits 2 when no speech is detected
3733
- and ${String(3)} when the transcriber is not installed
3734
- `;
3735
- function parseRivusAudioCliArguments(argv) {
3736
- if (argv.includes("--help") || argv.includes("-h")) return { help: true };
3737
- const [operation, ...rest] = argv;
3738
- if (operation === "install") {
3739
- const flags = new Set(rest);
3740
- const unknown = rest.find((argument) => argument !== "--force" && argument !== "--json");
3741
- if (unknown !== void 0) return { error: `Unknown audio install option: ${unknown}` };
3742
- if (flags.size !== rest.length) return { error: "audio install options may only be provided once" };
3743
- return {
3744
- force: flags.has("--force"),
3745
- json: flags.has("--json"),
3746
- operation
3747
- };
3748
- }
3749
- if (operation === "status") return rest.length === 0 ? { operation } : { error: "audio status accepts no arguments" };
3750
- if (operation === "transcribe") {
3751
- const path = rest[0];
3752
- if (rest.length !== 1 || !path || path.startsWith("-")) return { error: "audio transcribe requires exactly one audio path" };
3753
- return {
3754
- operation,
3755
- path
3756
- };
3757
- }
3758
- return { error: "audio requires one of install, status, transcribe" };
3759
- }
3760
- function renderRivusAudioCliArgumentError(error) {
3761
- return `${error}\n\n${RIVUS_AUDIO_CLI_USAGE}`;
3762
- }
3763
- function renderRivusAudioCliStatus(status) {
3764
- return `${JSON.stringify(status)}\n`;
3765
- }
3766
- function renderRivusAudioCliInstallResult(result, json) {
3767
- if (json) return `${JSON.stringify(result)}\n`;
3768
- return result.status === "installed" ? `Installed audio transcriber ${result.id} in ${result.release}\n` : `Audio transcriber ${result.id} is already installed in ${result.release}\n`;
3769
- }
3770
- function renderRivusAudioCliNotInstalled() {
3771
- return "audio transcriber is not installed; run: rivus audio install\n";
3772
- }
3773
- //#endregion
3774
- //#region src/audio-transcription/infra/adapters/cli/rivus-audio-cli.ts
3775
- /** Runs one parsed `rivus audio` command and returns its exit code; installation failures are thrown. */
3776
- async function runRivusAudioCliCommand(command, context) {
3777
- if (command.operation === "install") {
3778
- const result = await installRivusAudioTranscriber({
3779
- assetDirectory: context.assetDirectory,
3780
- env: context.env,
3781
- force: command.force,
3782
- installRoot: context.installRoot,
3783
- nodeExecutable: context.nodeExecutable,
3784
- platform: context.platform,
3785
- runProcess: context.runProcess,
3786
- ...context.signal ? { signal: context.signal } : {}
3787
- });
3788
- context.stdout.write(renderRivusAudioCliInstallResult(result, command.json));
3789
- return 0;
3790
- }
3791
- if (command.operation === "status") {
3792
- context.stdout.write(renderRivusAudioCliStatus(await readRivusAudioStatus(context.installRoot, context.assetDirectory)));
3793
- return 0;
3794
- }
3795
- const release = await readRivusAudioInstalledRelease(context.installRoot);
3796
- if (release === void 0) {
3797
- context.stderr.write(renderRivusAudioCliNotInstalled());
3798
- return 3;
3799
- }
3800
- const exitCode = await runRivusAudioPassthroughProcess({
3801
- args: [join(release.directory, "transcribe.mjs"), resolve(context.cwd, command.path)],
3802
- command: context.nodeExecutable,
3803
- cwd: release.directory,
3804
- env: context.env,
3805
- ...context.signal ? { signal: context.signal } : {},
3806
- stderr: context.stderr,
3807
- stdout: context.stdout
3808
- });
3809
- return exitCode === 0 || exitCode === 1 || exitCode === 2 ? exitCode : 1;
3810
- }
3811
- //#endregion
3812
- //#region src/bootstrap/daemon/process/rivus-daemon-shutdown-controller.ts
3813
- const DEFAULT_SIGNALS = ["SIGINT", "SIGTERM"];
3814
- function createRivusDaemonShutdownController(options) {
3815
- let shutdown;
3816
- const handle = (signal) => {
3817
- shutdown ??= Effect.runPromise(options.daemon.stop()).then(() => options.onStopped?.(signal)).catch(async (error) => {
3818
- await options.onError?.(error, signal);
3819
- throw error;
3820
- });
3821
- return shutdown;
3822
- };
3823
- return {
3824
- handle,
3825
- install: () => {
3826
- for (const signal of options.signals ?? DEFAULT_SIGNALS) options.signalSource.on(signal, () => {
3827
- handle(signal);
3828
- });
3829
- },
3830
- stopping: () => shutdown !== void 0
3831
- };
3832
- }
3833
- //#endregion
3834
- //#region src/bootstrap/deployment/deployment-control-ports.ts
3835
- /** Builds every Agent Host with stable instance ids and a fresh runtime pool over that host's runtime factory. */
3836
- const ProcessRivusAgentHostFactoryLive = Layer.succeed(RivusAgentHostFactory, { create: ({ runtimeFactory, ...options }) => makeAgentHost(options).pipe(Effect.provide(Layer.mergeAll(StableAgentInstanceIdentityLive, pooledAgentHostRuntimes(runtimeFactory)))) });
3837
- function createProcessDeploymentControlPorts(factories, backgroundSessions) {
3838
- return {
3839
- agentCatalog: createBootstrapAgentCatalog(backgroundSessions),
3840
- runtimeFactory: { create: factories.createRuntime },
3841
- endpointFactory: { create: factories.createEndpoint },
3842
- ...factories.createAutomation ? { automationFactory: { create: factories.createAutomation } } : {},
3843
- ...factories.createBackgroundSession ? { backgroundSessionFactory: { create: factories.createBackgroundSession } } : {}
3844
- };
3176
+ //#endregion
3177
+ //#region src/bootstrap/deployment/deployment-control-ports.ts
3178
+ /** Builds every Agent Host with stable instance ids and a fresh runtime pool over that host's runtime factory. */
3179
+ const ProcessRivusAgentHostFactoryLive = Layer.succeed(RivusAgentHostFactory, { create: ({ runtimeFactory, ...options }) => makeAgentHost(options).pipe(Effect.provide(Layer.mergeAll(StableAgentInstanceIdentityLive, pooledAgentHostRuntimes(runtimeFactory)))) });
3180
+ function createProcessDeploymentControlPorts(factories, backgroundSessions) {
3181
+ return {
3182
+ agentCatalog: createBootstrapAgentCatalog(backgroundSessions),
3183
+ runtimeFactory: { create: factories.createRuntime },
3184
+ endpointFactory: { create: factories.createEndpoint },
3185
+ ...factories.createAutomation ? { automationFactory: { create: factories.createAutomation } } : {},
3186
+ ...factories.createBackgroundSession ? { backgroundSessionFactory: { create: factories.createBackgroundSession } } : {}
3187
+ };
3845
3188
  }
3846
3189
  //#endregion
3847
3190
  //#region src/bootstrap/deployment/rivus-deployment-cli-process.ts
@@ -3881,7 +3224,8 @@ async function createRivusDeploymentCliProcess(factory, context) {
3881
3224
  }).pipe(Effect.flatMap((deployment) => createRivusDeploymentControl({
3882
3225
  ...assemblyInput,
3883
3226
  deployment,
3884
- digest: createSha256Digest
3227
+ digest: createSha256Digest,
3228
+ ...adapters.superagent === void 0 ? {} : { superagent: adapters.superagent }
3885
3229
  })), Effect.provide(Layer.mergeAll(nodeRivusPluginLoader(context.pluginPackageManifestPath ? { packageManifestPath: context.pluginPackageManifestPath } : {}), NodeRivusProjectSpaceResolverLive, ProcessRivusAgentHostFactoryLive)));
3886
3230
  })).pipe(Effect.map((control) => {
3887
3231
  let opening;
@@ -3923,12 +3267,22 @@ async function createRivusDeploymentCliProcess(factory, context) {
3923
3267
  if (errors.length > 1) return Effect.fail(new AggregateError(errors, "deployment and adapter cleanup failed"));
3924
3268
  return Effect.void;
3925
3269
  })));
3926
- const process = {
3270
+ return {
3927
3271
  defaultSessionKey: `local:${daemon.deployment.manifest.defaultAgentId}:cli`,
3928
3272
  openRecoveryControl: () => Effect.suspend(() => adaptersDisposed ? Effect.fail(/* @__PURE__ */ new Error("Rivus deployment process cannot open Recovery Control after disposal")) : openRecovery),
3929
3273
  running: () => daemon.running(),
3930
3274
  start: () => startDeployment,
3931
- status: () => Effect.sync(() => daemon.status()),
3275
+ status: () => Effect.gen(function* () {
3276
+ const snapshot = daemon.status();
3277
+ if (daemon.deployment.manifest.superagent === void 0) return snapshot;
3278
+ const path = superagentControlSocketPath(deploymentStateDirectoryFromEnv(context.env));
3279
+ const unavailable = { state: "unavailable" };
3280
+ const superagent = yield* Effect.promise(() => requestLocalJson(path, { operation: "status" }).then((response) => response.ok ? response.value : unavailable, () => unavailable));
3281
+ return {
3282
+ ...snapshot,
3283
+ superagent
3284
+ };
3285
+ }),
3932
3286
  stop: () => stopDeployment,
3933
3287
  promptText: (command) => Effect.suspend(() => {
3934
3288
  if (adaptersDisposed) return Effect.fail(/* @__PURE__ */ new Error("Rivus deployment process cannot restart after its adapters have been disposed"));
@@ -3944,9 +3298,6 @@ async function createRivusDeploymentCliProcess(factory, context) {
3944
3298
  }).pipe(Effect.map(readPromptFinalText));
3945
3299
  }).pipe(Effect.catchCause((cause) => Effect.fail(Cause.squash(cause))))
3946
3300
  };
3947
- const replayReceiveMessage = adapters.replayReceiveMessage;
3948
- if (replayReceiveMessage) process.replayReceiveMessage = (payload, options) => Effect.suspend(() => daemon.running() ? Effect.void : startDeployment).pipe(Effect.flatMap(() => replayReceiveMessage((input) => daemon.handleDefault(input), payload, options)));
3949
- return process;
3950
3301
  }
3951
3302
  //#endregion
3952
3303
  //#region src/bootstrap/deployment/check-deployment-plugins.ts
@@ -3980,7 +3331,7 @@ function installCliShutdownController(options, daemon) {
3980
3331
  createRivusDaemonShutdownController({
3981
3332
  daemon,
3982
3333
  onError: (error, signal) => {
3983
- options.stderr.write(formatRivusDaemonShutdownFailure(signal, formatRivusDaemonError(error)));
3334
+ options.stderr.write(formatRivusDaemonShutdownFailure(signal, errorMessage(error)));
3984
3335
  options.exitAfterSignal?.(1);
3985
3336
  },
3986
3337
  onStopped: () => {
@@ -4001,23 +3352,8 @@ function runStatusOneShot(options, daemon, action) {
4001
3352
  return yield* action(daemon);
4002
3353
  }));
4003
3354
  }
4004
- function hasPromptRunner(daemon) {
4005
- return typeof daemon.promptText === "function";
4006
- }
4007
- function hasFeishuReplayRunner(daemon) {
4008
- return typeof daemon.replayReceiveMessage === "function";
4009
- }
4010
- function runReplayOneShot(options, daemon, createPayload, replayOptions) {
4011
- return runOneShotDaemon(daemon, () => Effect.gen(function* () {
4012
- if (!hasFeishuReplayRunner(daemon)) {
4013
- options.stderr.write(formatRivusDaemonCapabilityError("replay"));
4014
- return 1;
4015
- }
4016
- const payload = yield* createPayload();
4017
- const result = replayOptions === void 0 ? yield* daemon.replayReceiveMessage(payload) : yield* daemon.replayReceiveMessage(payload, replayOptions);
4018
- options.stdout.write(formatRivusDaemonJson(result));
4019
- return 0;
4020
- }));
3355
+ function hasPromptRunner(daemon) {
3356
+ return typeof daemon.promptText === "function";
4021
3357
  }
4022
3358
  function hasRecoveryRunner(daemon) {
4023
3359
  return typeof daemon.openRecoveryControl === "function";
@@ -4033,16 +3369,6 @@ function runRivusDaemonCli(options) {
4033
3369
  options.stderr.write(formatRivusDaemonUsageError(parsed.error));
4034
3370
  return 1;
4035
3371
  }
4036
- if (parsed.printOpenClawEnvPath) {
4037
- const openClawConfigPath = parsed.printOpenClawEnvPath;
4038
- const result = yield* Effect.tryPromise({
4039
- try: () => loadRivusEnvFromOpenClawConfig(openClawConfigPath, parsed.piApiKeyFile),
4040
- catch: (error) => error
4041
- });
4042
- for (const warning of result.warnings) options.stderr.write(formatRivusDaemonWarning(warning));
4043
- options.stdout.write(formatRivusEnvFile(result.env));
4044
- return 0;
4045
- }
4046
3372
  const env = yield* Effect.tryPromise({
4047
3373
  try: async () => {
4048
3374
  const loaded = await loadCliEnv(parsed.envFilePath, options.env);
@@ -4124,22 +3450,6 @@ function runRivusDaemonCli(options) {
4124
3450
  return 0;
4125
3451
  }));
4126
3452
  }
4127
- if (parsed.replayFeishuText !== void 0) {
4128
- const replayFeishuText = parsed.replayFeishuText;
4129
- return yield* runReplayOneShot(options, daemon, () => Effect.sync(() => createSyntheticFeishuTextReplayPayload(replayFeishuText, {
4130
- ...parsed.feishuReplayChatId !== void 0 ? { chatId: parsed.feishuReplayChatId } : {},
4131
- ...parsed.feishuReplayMessageId !== void 0 ? { messageId: parsed.feishuReplayMessageId } : {},
4132
- ...parsed.feishuReplayTenantKey !== void 0 ? { tenantKey: parsed.feishuReplayTenantKey } : {},
4133
- ...parsed.feishuReplayThreadId !== void 0 ? { threadId: parsed.feishuReplayThreadId } : {}
4134
- })), { sideEffects: "disabled" });
4135
- }
4136
- if (parsed.replayFeishuEventPath !== void 0) {
4137
- const replayFeishuEventPath = parsed.replayFeishuEventPath;
4138
- return yield* runReplayOneShot(options, daemon, () => Effect.tryPromise({
4139
- try: () => readFeishuReceiveMessagePayload(replayFeishuEventPath),
4140
- catch: (error) => error
4141
- }));
4142
- }
4143
3453
  const managedDaemon = {
4144
3454
  ...daemon,
4145
3455
  stop: () => Effect.gen(function* () {
@@ -4163,43 +3473,128 @@ function runRivusDaemonCli(options) {
4163
3473
  options.stdout.write(RIVUS_DAEMON_STARTED_MESSAGE);
4164
3474
  return 0;
4165
3475
  }).pipe(Effect.catch((error) => Effect.sync(() => {
4166
- options.stderr.write(formatRivusDaemonLine(formatRivusDaemonError(error)));
3476
+ options.stderr.write(formatRivusDaemonLine(errorMessage(error)));
4167
3477
  return 1;
4168
3478
  })));
4169
3479
  }
4170
3480
  //#endregion
4171
- //#region src/upgrade/domain/cli/value-objects/upgrade-cli-protocol.ts
4172
- const UPGRADE_USAGE = `Usage: rivus upgrade [--json]
4173
-
4174
- Upgrade the selected Home's managed service to the latest stable npm release.
4175
- Prepare and validate before stopping, retain the Home and backup, then verify startup.
4176
- Rerun the same command to resume an interrupted upgrade at its recorded version.
4177
- `;
4178
- function parseUpgradeArguments(argv) {
4179
- if (argv.includes("--help") || argv.includes("-h")) return { help: true };
4180
- if (argv.length === 0) return { json: false };
4181
- if (argv.length === 1 && argv[0] === "--json") return { json: true };
4182
- return { error: "upgrade accepts only --json; it selects the latest stable release automatically" };
3481
+ //#region src/bootstrap/cli/cli-support.ts
3482
+ function writeError(options, error) {
3483
+ return Effect.sync(() => {
3484
+ options.stderr.write(renderRivusCliError(error));
3485
+ return 1;
3486
+ });
4183
3487
  }
4184
- function renderUpgradeResult(result, json) {
4185
- if (json) return `${JSON.stringify(result)}\n`;
4186
- 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` : ""}`;
3488
+ /** Lets an interrupted install stop its child processes and remove its staging directory before the CLI exits. */
3489
+ function abortOnInterruption(signalSource) {
3490
+ const controller = new AbortController();
3491
+ signalSource.on("SIGINT", () => controller.abort());
3492
+ signalSource.on("SIGTERM", () => controller.abort());
3493
+ return controller.signal;
3494
+ }
3495
+ function withOptionalDirectoryArgument(options, command, run) {
3496
+ const parsed = parseRivusDirectoryArguments(options.argv.slice(1));
3497
+ if (parsed.help) return Effect.sync(() => {
3498
+ options.stdout.write(renderRivusDirectoryCommandUsage(command));
3499
+ return 0;
3500
+ });
3501
+ if (parsed.error) return Effect.sync(() => {
3502
+ options.stderr.write(renderRivusDirectoryCommandUsage(command));
3503
+ return 1;
3504
+ });
3505
+ return run(parsed.directory);
3506
+ }
3507
+ function resolveHomeDirectoryEffect(options, argument) {
3508
+ return Effect.try({
3509
+ try: () => {
3510
+ if (argument) return resolve(options.cwd, argument);
3511
+ const configured = options.env.RIVUS_HOME?.trim();
3512
+ if (!configured) return resolve(options.homeDirectory, ".rivus-agent");
3513
+ if (!isAbsolute(configured)) throw new Error("RIVUS_HOME must be an absolute path");
3514
+ return resolve(configured);
3515
+ },
3516
+ catch: toError
3517
+ });
3518
+ }
3519
+ function superagentTransportError(options, error) {
3520
+ if (isNodeErrorWithCode(error, "ENOENT") || isNodeErrorWithCode(error, "ECONNREFUSED")) return Effect.sync(() => {
3521
+ options.stderr.write("Superagent daemon is unavailable\n");
3522
+ return 3;
3523
+ });
3524
+ return writeError(options, error);
4187
3525
  }
4188
3526
  //#endregion
4189
- //#region src/upgrade/infra/adapters/home-backup.ts
4190
- async function retainedArchive(directory) {
4191
- const archives = [];
4192
- for (const [name, format] of [["home.tar.gz", "gzip"], ["home.tar", "tar"]]) {
4193
- const path = join(directory, name);
4194
- if (await lstat(path).catch((error) => {
4195
- if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
4196
- })) archives.push({
4197
- path,
4198
- format
3527
+ //#region src/bootstrap/cli/audio-command.ts
3528
+ /** Runs one parsed `rivus audio` command and returns its exit code; installation failures are thrown. */
3529
+ async function runRivusAudioCliCommand(command, context) {
3530
+ if (command.operation === "install") {
3531
+ const result = await installRivusAudioTranscriber({
3532
+ assetDirectory: context.assetDirectory,
3533
+ env: context.env,
3534
+ force: command.force,
3535
+ installRoot: context.installRoot,
3536
+ nodeExecutable: context.nodeExecutable,
3537
+ platform: context.platform,
3538
+ runProcess: context.runProcess,
3539
+ ...context.signal ? { signal: context.signal } : {}
4199
3540
  });
3541
+ context.stdout.write(renderRivusAudioCliInstallResult(result, command.json));
3542
+ return 0;
3543
+ }
3544
+ if (command.operation === "status") {
3545
+ context.stdout.write(renderRivusAudioCliStatus(await readRivusAudioStatus(context.installRoot, context.assetDirectory)));
3546
+ return 0;
3547
+ }
3548
+ const release = await readRivusAudioInstalledRelease(context.installRoot);
3549
+ if (release === void 0) {
3550
+ context.stderr.write(renderRivusAudioCliNotInstalled());
3551
+ return 3;
4200
3552
  }
4201
- if (archives.length > 1) throw new Error("Both home.tar and home.tar.gz exist; preserve both backups and resolve the ambiguity before resuming");
4202
- return archives[0];
3553
+ const exitCode = await runRivusAudioPassthroughProcess({
3554
+ args: [join(release.directory, "transcribe.mjs"), resolve(context.cwd, command.path)],
3555
+ command: context.nodeExecutable,
3556
+ cwd: release.directory,
3557
+ env: context.env,
3558
+ ...context.signal ? { signal: context.signal } : {},
3559
+ stderr: context.stderr,
3560
+ stdout: context.stdout
3561
+ });
3562
+ return exitCode === 0 || exitCode === 1 || exitCode === 2 ? exitCode : 1;
3563
+ }
3564
+ function runAudioCommand(options) {
3565
+ const parsed = parseRivusAudioCliArguments(options.argv.slice(1));
3566
+ if ("help" in parsed) return Effect.sync(() => {
3567
+ options.stdout.write(RIVUS_AUDIO_CLI_USAGE);
3568
+ return 0;
3569
+ });
3570
+ if ("error" in parsed) return Effect.sync(() => {
3571
+ options.stderr.write(renderRivusAudioCliArgumentError(parsed.error));
3572
+ return 1;
3573
+ });
3574
+ return resolveHomeDirectoryEffect(options).pipe(Effect.flatMap((directory) => options.homeApi.load(directory)), Effect.flatMap((home) => Effect.tryPromise({
3575
+ try: () => runRivusAudioCliCommand(parsed, {
3576
+ assetDirectory: gatewayAudioTranscriberAssetDirectory,
3577
+ cwd: options.cwd,
3578
+ env: options.env,
3579
+ installRoot: join(home.stateDirectory, "audio-transcriber"),
3580
+ nodeExecutable: options.nodeExecutable,
3581
+ platform: createNodePlatform(),
3582
+ runProcess: runRivusAudioProcess,
3583
+ signal: abortOnInterruption(options.signalSource),
3584
+ stderr: options.stderr,
3585
+ stdout: options.stdout
3586
+ }),
3587
+ catch: (error) => error
3588
+ })), Effect.catch((error) => writeError(options, error)));
3589
+ }
3590
+ //#endregion
3591
+ //#region src/upgrade/infra/adapters/home-backup.ts
3592
+ const ARCHIVE_NAME = "home.tar.gz";
3593
+ async function retainedArchive(directory) {
3594
+ const path = join(directory, ARCHIVE_NAME);
3595
+ return await lstat(path).catch((error) => {
3596
+ if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
3597
+ }) ? path : void 0;
4203
3598
  }
4204
3599
  async function throwArchiveFailure(phase, archive, result) {
4205
3600
  const diagnostics = join(dirname(archive), `tar-${phase}-failure-${randomUUID()}.json`);
@@ -4219,14 +3614,14 @@ async function throwArchiveFailure(phase, archive, result) {
4219
3614
  throw new Error(`${summary} (tar exit ${result.exitCode}); private diagnostics: ${diagnostics}`);
4220
3615
  }
4221
3616
  async function verifyArchive(archive, input, removeFailedPartial = false) {
4222
- const metadata = await lstat(archive.path);
3617
+ const metadata = await lstat(archive);
4223
3618
  if (!metadata.isFile() || metadata.size === 0) throw new Error("Home backup is missing, empty or not a regular file");
4224
3619
  const listed = await input.run({
4225
3620
  command: "/usr/bin/tar",
4226
3621
  args: [
4227
- ...archive.format === "gzip" ? ["--use-compress-program=/usr/bin/gzip -d"] : [],
3622
+ "--use-compress-program=/usr/bin/gzip -d",
4228
3623
  "-tf",
4229
- archive.path
3624
+ archive
4230
3625
  ],
4231
3626
  cwd: input.home,
4232
3627
  env: input.env,
@@ -4234,8 +3629,8 @@ async function verifyArchive(archive, input, removeFailedPartial = false) {
4234
3629
  discardStdout: true
4235
3630
  });
4236
3631
  if (listed.exitCode !== 0) {
4237
- if (removeFailedPartial) await rm(archive.path, { force: true });
4238
- await throwArchiveFailure("verify", archive.path, listed);
3632
+ if (removeFailedPartial) await rm(archive, { force: true });
3633
+ await throwArchiveFailure("verify", archive, listed);
4239
3634
  }
4240
3635
  }
4241
3636
  async function backUpUpgradeHome(input) {
@@ -4243,27 +3638,20 @@ async function backUpUpgradeHome(input) {
4243
3638
  recursive: true,
4244
3639
  mode: 448
4245
3640
  });
4246
- const archive = {
4247
- path: join(input.directory, "home.tar.gz"),
4248
- format: "gzip"
4249
- };
4250
- const temporary = {
4251
- ...archive,
4252
- path: `${archive.path}.partial`
4253
- };
3641
+ const archive = join(input.directory, ARCHIVE_NAME);
3642
+ const temporary = `${archive}.partial`;
4254
3643
  try {
4255
- await rm(join(input.directory, "home.tar.partial"), { force: true });
4256
3644
  const existing = await retainedArchive(input.directory);
4257
3645
  if (existing) {
4258
3646
  await verifyArchive(existing, input);
4259
- return existing.path;
3647
+ return existing;
4260
3648
  }
4261
3649
  const created = await input.run({
4262
3650
  command: "/usr/bin/tar",
4263
3651
  args: [
4264
3652
  "--use-compress-program=/usr/bin/gzip -1",
4265
3653
  "-cpf",
4266
- temporary.path,
3654
+ temporary,
4267
3655
  "--exclude=./.rivus-upgrade",
4268
3656
  "-C",
4269
3657
  input.home,
@@ -4276,15 +3664,15 @@ async function backUpUpgradeHome(input) {
4276
3664
  discardStdout: true
4277
3665
  });
4278
3666
  if (created.exitCode !== 0) {
4279
- await rm(temporary.path, { force: true });
4280
- await throwArchiveFailure("create", archive.path, created);
3667
+ await rm(temporary, { force: true });
3668
+ await throwArchiveFailure("create", archive, created);
4281
3669
  }
4282
- await chmod(temporary.path, 384);
3670
+ await chmod(temporary, 384);
4283
3671
  await verifyArchive(temporary, input, true);
4284
- await rename(temporary.path, archive.path);
4285
- return archive.path;
3672
+ await rename(temporary, archive);
3673
+ return archive;
4286
3674
  } finally {
4287
- await rm(temporary.path, { force: true });
3675
+ await rm(temporary, { force: true });
4288
3676
  }
4289
3677
  }
4290
3678
  async function verifyUpgradeBackup(input) {
@@ -4345,8 +3733,6 @@ function packedArtifactPath(stdout, directory) {
4345
3733
  const stringMap = Schema.Record(Schema.String, Schema.String);
4346
3734
  const policySchema = Schema.Struct({
4347
3735
  schemaVersion: Schema.Literal(1),
4348
- stateCompatibility: Schema.Literal("rivus-home-0.20"),
4349
- minimumSourceVersion: Schema.String,
4350
3736
  pnpmVersion: Schema.String,
4351
3737
  overrides: stringMap,
4352
3738
  allowBuilds: Schema.Record(Schema.String, Schema.Boolean)
@@ -4354,11 +3740,11 @@ const policySchema = Schema.Struct({
4354
3740
  function parseInstallationPolicy(text) {
4355
3741
  try {
4356
3742
  const policy = Schema.decodeUnknownSync(policySchema)(JSON.parse(text));
4357
- if (valid(policy.minimumSourceVersion) !== policy.minimumSourceVersion || valid(policy.pnpmVersion) !== policy.pnpmVersion) throw new Error("invalid version");
3743
+ if (valid(policy.pnpmVersion) !== policy.pnpmVersion) throw new Error("invalid version");
4358
3744
  for (const floor of Object.values(policy.overrides)) if (!valid(floor)) throw new Error("invalid security floor");
4359
3745
  return policy;
4360
3746
  } catch {
4361
- throw new Error("Release installation policy is missing, invalid or requires an unsupported Home migration");
3747
+ throw new Error("Release installation policy is missing or invalid");
4362
3748
  }
4363
3749
  }
4364
3750
  async function readInstallationPolicy(directory = gatewayPackageDirectory) {
@@ -4393,9 +3779,6 @@ async function fetchInstallationPolicy(input) {
4393
3779
  timeoutMs: 3e4
4394
3780
  }, "Target installation policy extraction", join(input.directory, "policy-extraction.log"))).stdout);
4395
3781
  }
4396
- function assertSourceCompatibility(policy, sourceVersion) {
4397
- 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`);
4398
- }
4399
3782
  function dependencyName(selector) {
4400
3783
  const version = selector.indexOf("@", 1);
4401
3784
  return version === -1 ? selector : selector.slice(0, version);
@@ -4427,13 +3810,31 @@ const corePackageNames = [
4427
3810
  "@rivus/runtime",
4428
3811
  "@rivus/platform"
4429
3812
  ];
4430
- const recordSchema = Schema.Record(Schema.String, Schema.Unknown);
4431
- const stringMapSchema = Schema.Record(Schema.String, Schema.String);
4432
- const buildMapSchema = Schema.Record(Schema.String, Schema.Boolean);
3813
+ const StringMap = Schema.Record(Schema.String, Schema.String);
3814
+ const BuildMap = Schema.Record(Schema.String, Schema.Boolean);
4433
3815
  const installedManifestSchema = Schema.Struct({
4434
3816
  name: Schema.String,
4435
3817
  version: Schema.String
4436
3818
  });
3819
+ const NpmOverrides = Schema.Record(Schema.String, Schema.Union([Schema.String, Schema.suspend(() => NpmOverrides)]));
3820
+ /** A missing, `undefined` or `null` section reads as `empty`, as the consumer configuration always has. */
3821
+ function nullishAs(section, empty) {
3822
+ return Schema.optional(Schema.NullOr(Schema.toEncoded(section))).pipe(Schema.decodeTo(section, {
3823
+ decode: SchemaGetter.transformOptional((value) => Option.some(Option.getOrNull(value) ?? empty)),
3824
+ encode: SchemaGetter.passthroughSupertype()
3825
+ }));
3826
+ }
3827
+ const PnpmSettings = Schema.Struct({
3828
+ allowBuilds: nullishAs(BuildMap, {}),
3829
+ overrides: nullishAs(StringMap, {})
3830
+ });
3831
+ /** The consumer `package.json`; fields Rivus does not read stay unchecked. */
3832
+ const ConsumerPackageJson = Schema.Struct({
3833
+ dependencies: nullishAs(StringMap, {}),
3834
+ optionalDependencies: nullishAs(StringMap, {}),
3835
+ overrides: Schema.optional(Schema.NullOr(NpmOverrides)),
3836
+ pnpm: nullishAs(PnpmSettings, {})
3837
+ });
4437
3838
  function installedPackageManifestPath(root, name, resolutionBase = join(root, "package.json")) {
4438
3839
  try {
4439
3840
  const manifest = findPackageJSON(name, resolutionBase);
@@ -4492,9 +3893,6 @@ async function retainLocalArtifact(input, name, requirement, resolutionBase) {
4492
3893
  await chmod(destination, 384);
4493
3894
  return `file:artifacts/${artifactName}`;
4494
3895
  }
4495
- function record(value) {
4496
- return Schema.decodeUnknownSync(recordSchema)(value);
4497
- }
4498
3896
  function flattenNpmOverrides(source, dependencies, parent = "") {
4499
3897
  const result = {};
4500
3898
  for (const [name, value] of Object.entries(source)) {
@@ -4503,20 +3901,19 @@ function flattenNpmOverrides(source, dependencies, parent = "") {
4503
3901
  const requirement = value.startsWith("$") ? dependencies[value.slice(1)] : value;
4504
3902
  if (!selector || !requirement) throw new Error("Consumer npm override cannot be resolved for managed installation");
4505
3903
  result[selector] = requirement;
4506
- } else Object.assign(result, flattenNpmOverrides(record(value), dependencies, selector));
3904
+ } else Object.assign(result, flattenNpmOverrides(value, dependencies, selector));
4507
3905
  }
4508
3906
  return result;
4509
3907
  }
4510
- async function optionalRecord(path, yaml = false) {
3908
+ async function readConsumerConfiguration(schema, path, yaml = false) {
4511
3909
  let text;
4512
3910
  try {
4513
3911
  text = await readFile(path, "utf8");
4514
3912
  } catch (error) {
4515
- if (isNodeErrorWithCode(error, "ENOENT")) return {};
4516
- throw new Error("The installed consumer configuration cannot be read");
3913
+ if (!isNodeErrorWithCode(error, "ENOENT")) throw new Error("The installed consumer configuration cannot be read");
4517
3914
  }
4518
3915
  try {
4519
- return record(yaml ? parse$1(text) : JSON.parse(text));
3916
+ return Schema.decodeUnknownSync(schema)(text === void 0 ? {} : yaml ? parse$1(text) : JSON.parse(text));
4520
3917
  } catch {
4521
3918
  throw new Error("The installed consumer configuration is invalid");
4522
3919
  }
@@ -4528,31 +3925,25 @@ async function privateFile(path, contents) {
4528
3925
  async function writeReleaseConsumer(input) {
4529
3926
  const rootManifest = join(input.sourceRoot, "package.json");
4530
3927
  const sourceBase = await exists(rootManifest) ? rootManifest : join(input.sourceRoot, "node_modules/@rivus/agent/package.json");
4531
- const manifest = await optionalRecord(sourceBase);
4532
- const workspace = await optionalRecord(join(input.sourceRoot, "pnpm-workspace.yaml"), true);
4533
- const sourcePnpm = record(manifest.pnpm ?? {});
3928
+ const manifest = await readConsumerConfiguration(ConsumerPackageJson, sourceBase);
3929
+ const workspace = await readConsumerConfiguration(PnpmSettings, join(input.sourceRoot, "pnpm-workspace.yaml"), true);
4534
3930
  const dependencies = {};
4535
3931
  const optionalDependencies = {};
4536
3932
  const installedVersions = {};
4537
- for (const [field, target] of [["dependencies", dependencies], ["optionalDependencies", optionalDependencies]]) {
4538
- const declared = Schema.decodeUnknownSync(stringMapSchema)(manifest[field] ?? {});
4539
- for (const [name, requirement] of Object.entries(declared)) {
4540
- if (corePackageNames.some((core) => core === name)) continue;
4541
- const installed = await readInstalledManifest(input.sourceRoot, name, sourceBase).catch((error) => {
4542
- if (field === "optionalDependencies") return;
4543
- throw error;
4544
- });
4545
- if (!installed) continue;
4546
- installedVersions[name] = installed.version;
4547
- target[name] = requirement.startsWith("file:") || requirement.startsWith("link:") ? await retainLocalArtifact(input, name, requirement, sourceBase) : requirement.startsWith("npm:") ? `npm:${installed.name}@${installed.version}` : installed.version;
4548
- }
3933
+ for (const [field, target] of [["dependencies", dependencies], ["optionalDependencies", optionalDependencies]]) for (const [name, requirement] of Object.entries(manifest[field])) {
3934
+ if (corePackageNames.some((core) => core === name)) continue;
3935
+ const installed = await readInstalledManifest(input.sourceRoot, name, sourceBase).catch((error) => {
3936
+ if (field === "optionalDependencies") return;
3937
+ throw error;
3938
+ });
3939
+ if (!installed) continue;
3940
+ installedVersions[name] = installed.version;
3941
+ target[name] = requirement.startsWith("file:") || requirement.startsWith("link:") ? await retainLocalArtifact(input, name, requirement, sourceBase) : requirement.startsWith("npm:") ? `npm:${installed.name}@${installed.version}` : installed.version;
4549
3942
  }
4550
3943
  for (const name of corePackageNames) dependencies[name] = input.version;
4551
3944
  if (!dependencies.effect) dependencies.effect = (await readInstalledManifest(input.sourceRoot, "effect", sourceBase)).version;
4552
3945
  const gatewayBase = installedPackageManifestPath(input.sourceRoot, "@rivus/gateway", join(input.sourceRoot, "node_modules/@rivus/agent/package.json"));
4553
- const homeMetadata = await stat(input.homeManifestPath);
4554
- if (!homeMetadata.isFile() || homeMetadata.size > 1048576) throw new Error("The Home deployment manifest must be a regular file of at most one MiB");
4555
- const homeManifest = parseRivusDeploymentManifest(JSON.parse(await readFile(input.homeManifestPath, "utf8")));
3946
+ const homeManifest = await Effect.runPromise(loadRivusDeploymentManifest(input.homeManifestPath));
4556
3947
  for (const plugin of homeManifest.plugins) {
4557
3948
  if (plugin.module.startsWith(".") || plugin.module.startsWith("/")) continue;
4558
3949
  const name = plugin.module.split("/").slice(0, plugin.module.startsWith("@") ? 2 : 1).join("/");
@@ -4563,14 +3954,14 @@ async function writeReleaseConsumer(input) {
4563
3954
  for (const name of corePackageNames) installedVersions[name] = input.version;
4564
3955
  installedVersions.effect = dependencies.effect;
4565
3956
  const sourceOverrides = {
4566
- ...flattenNpmOverrides(record(manifest.overrides ?? {}), dependencies),
4567
- ...Schema.decodeUnknownSync(stringMapSchema)(sourcePnpm.overrides ?? {}),
4568
- ...Schema.decodeUnknownSync(stringMapSchema)(workspace.overrides ?? {})
3957
+ ...flattenNpmOverrides(manifest.overrides ?? {}, dependencies),
3958
+ ...manifest.pnpm.overrides,
3959
+ ...workspace.overrides
4569
3960
  };
4570
3961
  const allowBuilds = {
4571
3962
  ...input.policy.allowBuilds,
4572
- ...Schema.decodeUnknownSync(buildMapSchema)(sourcePnpm.allowBuilds ?? {}),
4573
- ...Schema.decodeUnknownSync(buildMapSchema)(workspace.allowBuilds ?? {})
3963
+ ...manifest.pnpm.allowBuilds,
3964
+ ...workspace.allowBuilds
4574
3965
  };
4575
3966
  await privateFile(join(input.directory, "package.json"), `${JSON.stringify({
4576
3967
  name: "rivus-managed-release",
@@ -4683,7 +4074,6 @@ async function retainRegistryConfiguration(sourceRoot, directory) {
4683
4074
  async function prepareRelease(input) {
4684
4075
  if (!stableVersion(input.version)) throw new Error("Managed upgrade requires a stable three-component release version");
4685
4076
  if (resolve(input.directory) === input.source.root) throw new Error("A candidate release must use a separate installation directory");
4686
- assertSourceCompatibility(await readInstallationPolicy(), input.source.version);
4687
4077
  await mkdir(input.directory, {
4688
4078
  recursive: true,
4689
4079
  mode: 448
@@ -4707,7 +4097,6 @@ async function prepareRelease(input) {
4707
4097
  npm,
4708
4098
  run: input.run
4709
4099
  });
4710
- assertSourceCompatibility(policy, input.source.version);
4711
4100
  let versions;
4712
4101
  try {
4713
4102
  versions = await writeReleaseConsumer({
@@ -5461,45 +4850,185 @@ async function snapshotFile(source, destination) {
5461
4850
  recursive: true,
5462
4851
  mode: 448
5463
4852
  });
5464
- const temporary = `${destination}.${randomUUID()}.tmp`;
4853
+ const temporary = `${destination}.${randomUUID()}.tmp`;
4854
+ try {
4855
+ await writeFile(temporary, await readFile(source), {
4856
+ flag: "wx",
4857
+ mode: 384,
4858
+ flush: true
4859
+ });
4860
+ await link(temporary, destination);
4861
+ const directory = await open(dirname(destination), "r");
4862
+ try {
4863
+ await directory.sync();
4864
+ } finally {
4865
+ await directory.close();
4866
+ }
4867
+ } catch (error) {
4868
+ if (!isNodeErrorWithCode(error, "EEXIST")) throw error;
4869
+ } finally {
4870
+ await rm(temporary, { force: true });
4871
+ }
4872
+ }
4873
+ //#endregion
4874
+ //#region src/upgrade/domain/upgrade/phase.ts
4875
+ /** The phases of one managed upgrade, in the order a run passes through them. The journal records the phase reached,
4876
+ * so this order is also the resume order. */
4877
+ const upgradePhases = [
4878
+ "preparing",
4879
+ "prepared",
4880
+ "stopping",
4881
+ "stopped",
4882
+ "backed-up",
4883
+ "switching",
4884
+ "starting",
4885
+ "complete"
4886
+ ];
4887
+ const successors = {
4888
+ preparing: "prepared",
4889
+ prepared: "stopping",
4890
+ stopping: "stopped",
4891
+ stopped: "backed-up",
4892
+ "backed-up": "switching",
4893
+ switching: "starting",
4894
+ starting: "complete"
4895
+ };
4896
+ function nextUpgradePhase(phase) {
4897
+ return successors[phase];
4898
+ }
4899
+ function isPendingUpgradePhase(phase) {
4900
+ return phase !== "complete";
4901
+ }
4902
+ //#endregion
4903
+ //#region src/upgrade/infra/repository/upgrade-journal.ts
4904
+ const recordSchema = Schema.fromJsonString(Schema.Struct({
4905
+ schemaVersion: Schema.Literal(1),
4906
+ id: Schema.NonEmptyString,
4907
+ home: Schema.NonEmptyString,
4908
+ sourceVersion: Schema.NonEmptyString,
4909
+ targetVersion: Schema.NonEmptyString,
4910
+ sourceCommand: Schema.Array(Schema.NonEmptyString),
4911
+ service: Schema.Struct({
4912
+ kind: Schema.Literals(["launchd", "systemd"]),
4913
+ id: Schema.NonEmptyString,
4914
+ definitionPath: Schema.NonEmptyString
4915
+ }),
4916
+ phase: Schema.Literals(upgradePhases),
4917
+ createdAt: Schema.NonEmptyString,
4918
+ startedAfter: Schema.optional(Schema.NonEmptyString)
4919
+ }));
4920
+ /** The Home's upgrade directory: this journal and, per operation, the prepared release and the Home backup. */
4921
+ function upgradePaths(home, id) {
4922
+ const directory = join(home, ".rivus-upgrade");
4923
+ return {
4924
+ directory,
4925
+ journal: join(directory, "operation.json"),
4926
+ release: join(directory, "releases", id ?? ""),
4927
+ backup: join(directory, "backups", id ?? "")
4928
+ };
4929
+ }
4930
+ async function readUpgradeRecord(home) {
4931
+ const text = await readPersistenceFile(upgradePaths(home).journal);
4932
+ if (text === void 0) return;
4933
+ const record = Schema.decodeUnknownSync(recordSchema)(text);
4934
+ if (record.home !== home || !/^[a-f\d-]{36}$/.test(record.id)) throw new Error("upgrade journal belongs to another Home or has an invalid operation id");
4935
+ return record;
4936
+ }
4937
+ async function writeUpgradeRecord(record) {
4938
+ const paths = upgradePaths(record.home);
4939
+ await mkdir(paths.directory, {
4940
+ recursive: true,
4941
+ mode: 448
4942
+ });
4943
+ await writeAtomicTextFile(paths.journal, `${JSON.stringify(record)}\n`, {
4944
+ durable: true,
4945
+ mode: 384
4946
+ });
4947
+ }
4948
+ //#endregion
4949
+ //#region src/upgrade/infra/adapters/upgrade-lock.ts
4950
+ /**
4951
+ * Takes the Home upgrade lock at `.rivus-upgrade/upgrade.process-lock`: an exclusive kernel lock held until release or
4952
+ * until the holding process exits or crashes — the kernel releases a crashed holder's lock at once, so there is no
4953
+ * pid-based reclamation. The lock file stays on disk after release and this code never deletes it; deleting it while a
4954
+ * holder runs would let the next invocation take a second lock beside it.
4955
+ */
4956
+ async function acquireUpgradeLock(home, lockPlatform) {
4957
+ const root = upgradePaths(home).directory;
4958
+ await mkdir(root, {
4959
+ recursive: true,
4960
+ mode: 448
4961
+ });
4962
+ const acquired = await acquireProcessLock(lockPlatform, join(root, "upgrade.process-lock"));
4963
+ if (!acquired.ok) throw new Error("another upgrade owns this Home; wait for that invocation to finish");
4964
+ const lock = acquired.value;
4965
+ return () => lock.release();
4966
+ }
4967
+ //#endregion
4968
+ //#region src/upgrade/infra/repository/runtime-receipt.ts
4969
+ const absolutePath = Schema.String.check(Schema.makeFilter(isAbsolute));
4970
+ const runtimeReceiptSchema = Schema.Struct({
4971
+ schemaVersion: Schema.Literal(1),
4972
+ home: absolutePath,
4973
+ pid: Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0)),
4974
+ version: Schema.Trimmed.check(Schema.isNonEmpty()),
4975
+ executable: absolutePath,
4976
+ startedAt: Schema.String.check(Schema.makeFilter((value) => Number.isFinite(Date.parse(value))))
4977
+ });
4978
+ async function writeRuntimeReceipt(input) {
4979
+ const receipt = Schema.decodeUnknownSync(runtimeReceiptSchema)({
4980
+ ...input,
4981
+ home: await realpath(input.home),
4982
+ executable: await realpath(input.executable),
4983
+ schemaVersion: 1
4984
+ });
4985
+ const directory = join(receipt.home, ".rivus-upgrade");
4986
+ await mkdir(directory, {
4987
+ mode: 448,
4988
+ recursive: true
4989
+ });
4990
+ await chmod(directory, 448);
4991
+ const path = join(directory, "runtime.json");
4992
+ await chmod(path, 384).catch((error) => {
4993
+ if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
4994
+ });
4995
+ await writeAtomicTextFile(path, `${JSON.stringify(receipt)}\n`, {
4996
+ durable: true,
4997
+ mode: 384
4998
+ });
4999
+ }
5000
+ async function readRuntimeReceipt(home) {
5001
+ let canonicalHome;
5002
+ let raw;
5465
5003
  try {
5466
- await writeFile(temporary, await readFile(source), {
5467
- flag: "wx",
5468
- mode: 384,
5469
- flush: true
5470
- });
5471
- await link(temporary, destination);
5472
- const directory = await open(dirname(destination), "r");
5473
- try {
5474
- await directory.sync();
5475
- } finally {
5476
- await directory.close();
5477
- }
5004
+ canonicalHome = await realpath(home);
5005
+ raw = await readFile(join(canonicalHome, ".rivus-upgrade", "runtime.json"), "utf8");
5478
5006
  } catch (error) {
5479
- if (!isNodeErrorWithCode(error, "EEXIST")) throw error;
5480
- } finally {
5481
- await rm(temporary, { force: true });
5007
+ if (isNodeErrorWithCode(error, "ENOENT")) return;
5008
+ throw error;
5009
+ }
5010
+ try {
5011
+ const receipt = Schema.decodeUnknownSync(runtimeReceiptSchema)(JSON.parse(raw));
5012
+ return receipt.home === canonicalHome ? receipt : void 0;
5013
+ } catch {
5014
+ return;
5482
5015
  }
5483
5016
  }
5484
- //#endregion
5485
- //#region src/upgrade/infra/adapters/upgrade-lock.ts
5486
- /**
5487
- * Takes the Home upgrade lock at `.rivus-upgrade/upgrade.process-lock`: an exclusive kernel lock held until release or
5488
- * until the holding process exits or crashes — the kernel releases a crashed holder's lock at once, so there is no
5489
- * pid-based reclamation. The lock file stays on disk after release and this code never deletes it; deleting it while a
5490
- * holder runs would let the next invocation take a second lock beside it. Only the never-read legacy `lock/`
5491
- * owner-record directory can be deleted manually.
5492
- */
5493
- async function acquireUpgradeLock(home, lockPlatform) {
5494
- const root = upgradePaths(home).directory;
5495
- await mkdir(root, {
5496
- recursive: true,
5497
- mode: 448
5017
+ async function clearRuntimeReceipt(home, pid) {
5018
+ const receipt = await readRuntimeReceipt(home);
5019
+ if (receipt?.pid === pid) await unlink(join(receipt.home, ".rivus-upgrade", "runtime.json")).catch((error) => {
5020
+ if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
5498
5021
  });
5499
- const acquired = await acquireProcessLock(lockPlatform, join(root, "upgrade.process-lock"));
5500
- if (!acquired.ok) throw new Error("another upgrade owns this Home; wait for that invocation to finish");
5501
- const lock = acquired.value;
5502
- return () => lock.release();
5022
+ }
5023
+ //#endregion
5024
+ //#region src/upgrade/domain/upgrade/record.ts
5025
+ /** The record after entering `phase`. Entering `stopping` stamps `startedAfter`; `now` is read only then. */
5026
+ function enterUpgradePhase(record, phase, now) {
5027
+ return {
5028
+ ...record,
5029
+ phase,
5030
+ ...phase === "stopping" ? { startedAfter: now() } : {}
5031
+ };
5503
5032
  }
5504
5033
  //#endregion
5505
5034
  //#region src/upgrade/application/ports.ts
@@ -5553,9 +5082,9 @@ function runUpgrade(input) {
5553
5082
  const services = yield* UpgradeServiceManager;
5554
5083
  const versions = yield* UpgradeVersions;
5555
5084
  const record0 = yield* journal.read(home.directory);
5556
- let service = record0 && record0.phase !== "complete" ? yield* services.load(record0.service) : yield* services.discover();
5085
+ let service = record0 && isPendingUpgradePhase(record0.phase) ? yield* services.load(record0.service) : yield* services.discover();
5557
5086
  let record = record0;
5558
- if (!record || record.phase === "complete") {
5087
+ if (!record || !isPendingUpgradePhase(record.phase)) {
5559
5088
  const source = yield* packages.inspect(service.command, service.cwd, service.env);
5560
5089
  input.progress("resolving", `Checking latest release (current ${source.version})`);
5561
5090
  const target = yield* packages.latest({
@@ -5564,7 +5093,7 @@ function runUpgrade(input) {
5564
5093
  nodePath: source.nodePath
5565
5094
  });
5566
5095
  yield* requireStableVersion(versions, target);
5567
- if (!versions.isValid(source.version) || versions.compare(source.version, "0.20.0") < 0) return yield* Effect.fail(/* @__PURE__ */ new Error("this Home requires the documented 0.20 migration before managed upgrades"));
5096
+ if (!versions.isValid(source.version)) return yield* Effect.fail(/* @__PURE__ */ new Error(`the running release version ${source.version} is not a valid version`));
5568
5097
  if (versions.compare(target, source.version) < 0) return yield* Effect.fail(/* @__PURE__ */ new Error("registry latest is older than the running release; refusing a downgrade"));
5569
5098
  const observed = yield* services.inspect(service);
5570
5099
  if (!observed.running || !observed.pid || !sameCommand(observed.command, service.command)) return yield* Effect.fail(/* @__PURE__ */ new Error("the selected service is not running its configured Rivus command; resolve its state before upgrading"));
@@ -5594,19 +5123,16 @@ function runUpgrade(input) {
5594
5123
  };
5595
5124
  yield* journal.write(record);
5596
5125
  }
5597
- const paths = upgradePaths(home.directory, record.id);
5126
+ const paths = journal.directories(home.directory, record.id);
5598
5127
  const source = yield* packages.inspect(record.sourceCommand, service.cwd, service.env);
5599
5128
  if (source.version !== record.sourceVersion) return yield* Effect.fail(/* @__PURE__ */ new Error("the retained source release changed; preserve the journal and resolve it before continuing"));
5600
5129
  yield* requireStableVersion(versions, record.targetVersion);
5601
5130
  const candidateCommand = [...record.sourceCommand];
5602
5131
  const candidateCli = `${paths.release}/node_modules/@rivus/agent/dist/cli.js`;
5603
5132
  candidateCommand[candidateCommand.length - 2] = candidateCli;
5604
- const setPhase = (phase) => Effect.gen(function* () {
5605
- record = {
5606
- ...record,
5607
- phase,
5608
- ...phase === "stopping" ? { startedAfter: clock.now().toISOString() } : {}
5609
- };
5133
+ const advance = (from) => Effect.gen(function* () {
5134
+ const phase = nextUpgradePhase(from);
5135
+ record = enterUpgradePhase(record, phase, () => clock.now().toISOString());
5610
5136
  yield* journal.write(record);
5611
5137
  input.progress(phase, `${record.sourceVersion} -> ${record.targetVersion}`);
5612
5138
  });
@@ -5626,13 +5152,13 @@ function runUpgrade(input) {
5626
5152
  home,
5627
5153
  service
5628
5154
  });
5629
- yield* setPhase("prepared");
5155
+ yield* advance(record.phase);
5630
5156
  }
5631
5157
  if ((yield* packages.inspect(candidateCommand, service.cwd, service.env)).version !== record.targetVersion) return yield* Effect.fail(/* @__PURE__ */ new Error("prepared release does not match the recorded target version"));
5632
5158
  if (record.phase === "prepared") {
5633
5159
  const observed = yield* inspectExpected();
5634
5160
  if (!observed.running || !sameCommand(observed.command, record.sourceCommand)) return yield* Effect.fail(/* @__PURE__ */ new Error("the source service changed before cutover"));
5635
- yield* setPhase("stopping");
5161
+ yield* advance(record.phase);
5636
5162
  }
5637
5163
  if (record.phase === "stopping") {
5638
5164
  const observed = yield* inspectExpected();
@@ -5641,7 +5167,7 @@ function runUpgrade(input) {
5641
5167
  yield* services.stop(record.service);
5642
5168
  }
5643
5169
  if ((yield* inspectExpected()).running) return yield* Effect.fail(/* @__PURE__ */ new Error("the managed service has not stopped"));
5644
- yield* setPhase("stopped");
5170
+ yield* advance(record.phase);
5645
5171
  }
5646
5172
  if (record.phase === "stopped") {
5647
5173
  if ((yield* inspectExpected()).running) return yield* Effect.fail(/* @__PURE__ */ new Error("the service restarted before backup; stop it before resuming this operation"));
@@ -5650,7 +5176,7 @@ function runUpgrade(input) {
5650
5176
  directory: paths.backup,
5651
5177
  env: service.env
5652
5178
  });
5653
- yield* setPhase("backed-up");
5179
+ yield* advance(record.phase);
5654
5180
  }
5655
5181
  if (record.phase === "backed-up") {
5656
5182
  yield* archive.verify({
@@ -5659,7 +5185,7 @@ function runUpgrade(input) {
5659
5185
  env: service.env
5660
5186
  });
5661
5187
  if ((yield* inspectExpected()).running) return yield* Effect.fail(/* @__PURE__ */ new Error("the service restarted before switching; no service definition was changed"));
5662
- yield* setPhase("switching");
5188
+ yield* advance(record.phase);
5663
5189
  }
5664
5190
  if (record.phase === "switching") {
5665
5191
  const observed = yield* inspectExpected();
@@ -5669,7 +5195,7 @@ function runUpgrade(input) {
5669
5195
  if (!sameCommand(service.command, record.sourceCommand)) return yield* Effect.fail(/* @__PURE__ */ new Error("the service definition changed outside this upgrade"));
5670
5196
  yield* services.switch(record.service, candidateCommand, paths.backup);
5671
5197
  }
5672
- yield* setPhase("starting");
5198
+ yield* advance(record.phase);
5673
5199
  }
5674
5200
  if (record.phase !== "starting") return yield* Effect.fail(/* @__PURE__ */ new Error(`unsupported recovery phase: ${record.phase}`));
5675
5201
  const observed = yield* inspectExpected();
@@ -5680,7 +5206,7 @@ function runUpgrade(input) {
5680
5206
  receipts,
5681
5207
  services
5682
5208
  }, record, candidateCommand);
5683
- yield* setPhase("complete");
5209
+ yield* advance(record.phase);
5684
5210
  return {
5685
5211
  status: "upgraded",
5686
5212
  version: record.targetVersion,
@@ -5770,7 +5296,14 @@ function nodeUpgradePorts(options) {
5770
5296
  write: (record) => Effect.tryPromise({
5771
5297
  try: () => writeUpgradeRecord(record),
5772
5298
  catch: (error) => error
5773
- })
5299
+ }),
5300
+ directories: (home, id) => {
5301
+ const { release, backup } = upgradePaths(home, id);
5302
+ return {
5303
+ release,
5304
+ backup
5305
+ };
5306
+ }
5774
5307
  }), Layer.succeed(UpgradeReceipts, { read: (home) => Effect.tryPromise({
5775
5308
  try: () => options.receipts(home),
5776
5309
  catch: (error) => error
@@ -5783,8 +5316,333 @@ function nodeUpgradePorts(options) {
5783
5316
  sleep: (milliseconds) => Effect.tryPromise({
5784
5317
  try: () => wait(milliseconds),
5785
5318
  catch: (error) => error
5786
- })
5787
- }), Layer.succeed(UpgradeIds, { next: () => randomUUID() }));
5319
+ })
5320
+ }), Layer.succeed(UpgradeIds, { next: () => randomUUID() }));
5321
+ }
5322
+ //#endregion
5323
+ //#region src/bootstrap/cli/home-daemon-command.ts
5324
+ function resolveHomeRecoveryFileArguments(argv, command, cwd) {
5325
+ if (command.type === "inspect") return argv;
5326
+ const files = /* @__PURE__ */ new Map([["--recovery-note-file", resolve(cwd, command.noteFilePath)]]);
5327
+ if (command.type === "resolve-tool-operation" && command.outcome.status === "applied") files.set("--tool-result-file", resolve(cwd, command.outcome.resultFilePath));
5328
+ const resolved = [];
5329
+ for (let index = 0; index < argv.length; index += 1) {
5330
+ const argument = argv[index];
5331
+ const file = [...files].find(([flag]) => argument === flag || argument.startsWith(`${flag}=`));
5332
+ if (!file) resolved.push(argument);
5333
+ else if (argument === file[0]) {
5334
+ resolved.push(argument, file[1]);
5335
+ index += 1;
5336
+ } else resolved.push(`${file[0]}=${file[1]}`);
5337
+ }
5338
+ return resolved;
5339
+ }
5340
+ function runHomeDaemonCommand(options, command, daemonArgs) {
5341
+ const commandArgs = options.argv.slice(1);
5342
+ const checkPlugins = command === "check-config" && commandArgs.length === 1 && commandArgs[0] === "--load-plugins";
5343
+ if (command !== "recovery" && !checkPlugins && hasRivusHomeCommandArguments(commandArgs)) return Effect.sync(() => {
5344
+ options.stderr.write(renderRivusHomeCommandUsage(command));
5345
+ return 1;
5346
+ });
5347
+ return resolveHomeDirectoryEffect(options).pipe(Effect.flatMap((directory) => options.homeApi.load(directory)), Effect.tap((home) => Effect.sync(() => options.changeWorkingDirectory(home.workspaceDirectory))), Effect.flatMap((home) => runRivusDaemonCli({
5348
+ ...options,
5349
+ argv: [
5350
+ "--env-file",
5351
+ home.envFilePath,
5352
+ "--bootstrap",
5353
+ home.bootstrap,
5354
+ "--manifest",
5355
+ home.manifestPath,
5356
+ ...daemonArgs
5357
+ ],
5358
+ env: {
5359
+ ...options.env,
5360
+ RIVUS_DEPLOYMENT_STATE_DIR: home.stateDirectory,
5361
+ RIVUS_HOME: home.directory,
5362
+ [RIVUS_HOME_DEPLOYMENT_ENV]: home.directory
5363
+ },
5364
+ pluginPackageManifestPath: options.pluginPackageManifestPath ?? gatewayPackageManifestPath,
5365
+ ...checkPlugins ? { checkPlugins: true } : {},
5366
+ ...command === "start" ? { lifecycle: {
5367
+ started: async () => {
5368
+ if (!options.runtimeProcess) throw new Error("Home start requires the runtime process identity");
5369
+ await writeRuntimeReceipt({
5370
+ ...options.runtimeProcess,
5371
+ home: home.directory,
5372
+ version: RIVUS_RELEASE_DESCRIPTOR.version,
5373
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
5374
+ });
5375
+ },
5376
+ stopped: async () => {
5377
+ if (options.runtimeProcess) await clearRuntimeReceipt(home.directory, options.runtimeProcess.pid);
5378
+ }
5379
+ } } : {}
5380
+ })), Effect.catch((error) => writeError(options, error)));
5381
+ }
5382
+ function runRecoveryCommand(options) {
5383
+ const argv = options.argv.slice(1);
5384
+ const parser = createRivusRecoveryCliParser();
5385
+ for (let index = 0; index < argv.length; index += 1) {
5386
+ const argument = parser.consume(argv[index], argv[index + 1]);
5387
+ if (!argument.handled || argument.error) return Effect.sync(() => {
5388
+ options.stderr.write(renderRivusHomeCommandUsage("recovery"));
5389
+ return 1;
5390
+ });
5391
+ index += argument.consumed;
5392
+ }
5393
+ const parsed = parser.build();
5394
+ if (argv.length === 0 || parsed.error || !parsed.command) return Effect.sync(() => {
5395
+ options.stderr.write(renderRivusHomeCommandUsage("recovery"));
5396
+ return 1;
5397
+ });
5398
+ return runHomeDaemonCommand(options, "recovery", resolveHomeRecoveryFileArguments(argv, parsed.command, options.cwd));
5399
+ }
5400
+ //#endregion
5401
+ //#region src/bootstrap/cli/model-command.ts
5402
+ /** The exit code reads the request receipt from the open model response record by name (authoring guide, Validation). */
5403
+ const requestReceipt = Schema.Struct({ requestId: Schema.String });
5404
+ function modelManagementExitCode(response) {
5405
+ if (response.status !== "failed") return 0;
5406
+ if (typeof response.requestId === "string" && response.requestId.trim()) return 0;
5407
+ const request = response.request;
5408
+ if (!Schema.is(requestReceipt)(request)) return 1;
5409
+ return request.requestId.trim() ? 0 : 1;
5410
+ }
5411
+ function writeModelResponse(stdout, response) {
5412
+ stdout.write(`${JSON.stringify(response)}\n`);
5413
+ }
5414
+ function modelTransportFailure(error) {
5415
+ const code = error instanceof RivusModelManagementTransportError ? error.code : "socket_error";
5416
+ return {
5417
+ error: {
5418
+ code,
5419
+ message: code === "timeout" ? "model management service timed out" : code === "invalid_response" ? "model management returned an invalid response" : "model management service is unavailable"
5420
+ },
5421
+ schemaVersion: 1,
5422
+ status: "failed"
5423
+ };
5424
+ }
5425
+ function runModelCommand(options) {
5426
+ const parsed = parseRivusModelCliArguments(options.argv.slice(1));
5427
+ if ("help" in parsed) return Effect.sync(() => {
5428
+ options.stdout.write(renderRivusModelCliHelp());
5429
+ return 0;
5430
+ });
5431
+ if ("error" in parsed) return Effect.sync(() => {
5432
+ options.stderr.write(renderRivusModelCliArgumentError(parsed.error));
5433
+ return 1;
5434
+ });
5435
+ if (parsed.operation !== "status" && !isRivusModelManagementEnabled(options.env)) return Effect.sync(() => {
5436
+ writeModelResponse(options.stdout, {
5437
+ error: {
5438
+ code: "management_disabled",
5439
+ message: "model management is not enabled for this Home"
5440
+ },
5441
+ schemaVersion: 1,
5442
+ status: "failed"
5443
+ });
5444
+ return 1;
5445
+ });
5446
+ const client = options.modelManagementClient ?? createRivusModelManagementSocketClient({
5447
+ env: options.env,
5448
+ socketPath: resolveRivusModelSocketPath({
5449
+ env: options.env,
5450
+ homeDirectory: options.homeDirectory
5451
+ })
5452
+ });
5453
+ return Effect.tryPromise({
5454
+ try: () => client.execute(parsed),
5455
+ catch: (error) => error
5456
+ }).pipe(Effect.tap((response) => Effect.sync(() => writeModelResponse(options.stdout, response))), Effect.map((response) => modelManagementExitCode(response)), Effect.catch((error) => Effect.sync(() => {
5457
+ writeModelResponse(options.stdout, modelTransportFailure(error));
5458
+ return 1;
5459
+ })));
5460
+ }
5461
+ //#endregion
5462
+ //#region src/bootstrap/cli/setup-command.ts
5463
+ function runSetupCommand(options) {
5464
+ 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))));
5465
+ }
5466
+ function runInitCommand(options) {
5467
+ return withOptionalDirectoryArgument(options, "init", (argument) => {
5468
+ const directory = resolve(options.cwd, argument ?? ".");
5469
+ return Effect.tryPromise({
5470
+ try: () => initializeRivusProject({
5471
+ directory,
5472
+ nodeExecutable: options.nodeExecutable,
5473
+ templateDirectory: gatewayTemplateDirectory
5474
+ }),
5475
+ catch: (error) => error
5476
+ }).pipe(Effect.tap((result) => Effect.sync(() => options.stdout.write(renderRivusProjectInitializationSuccess(result.directory)))), Effect.as(0), Effect.catch((error) => writeError(options, error)));
5477
+ });
5478
+ }
5479
+ function writeDoctorReport(stdout, report, owner) {
5480
+ for (const chunk of renderRivusDoctorReport(report, owner)) stdout.write(chunk);
5481
+ return report.ready ? 0 : 1;
5482
+ }
5483
+ function runDoctorCommand(options) {
5484
+ const parsed = parseRivusDoctorArguments(options.argv.slice(1));
5485
+ if (parsed.help) return Effect.sync(() => {
5486
+ options.stdout.write(renderRivusDoctorUsage());
5487
+ return 0;
5488
+ });
5489
+ if (parsed.error) {
5490
+ const error = parsed.error;
5491
+ return Effect.sync(() => {
5492
+ options.stderr.write(renderRivusDoctorArgumentError(error));
5493
+ return 1;
5494
+ });
5495
+ }
5496
+ if (parsed.directory === void 0) return resolveHomeDirectoryEffect(options).pipe(Effect.flatMap((directory) => options.homeApi.diagnose({
5497
+ directory,
5498
+ env: options.env,
5499
+ ...parsed.envFilePath ? { envFilePath: parsed.envFilePath } : {},
5500
+ nodeVersion: options.nodeVersion
5501
+ })), Effect.map((report) => writeDoctorReport(options.stdout, report, "Home")), Effect.catch((error) => writeError(options, error)));
5502
+ const projectDirectory = parsed.directory;
5503
+ return diagnoseRivusProject({
5504
+ checkSuperagents: checkSuperagentConfigurations,
5505
+ directory: resolve(options.cwd, projectDirectory),
5506
+ env: options.env,
5507
+ ...parsed.envFilePath ? { envFilePath: parsed.envFilePath } : {},
5508
+ nodeVersion: options.nodeVersion
5509
+ }).pipe(Effect.map((report) => writeDoctorReport(options.stdout, report, "project")), Effect.catch((error) => writeError(options, error)));
5510
+ }
5511
+ //#endregion
5512
+ //#region src/bootstrap/cli/superagent-command.ts
5513
+ function runSuperagentCommand(options) {
5514
+ const args = options.argv.slice(1);
5515
+ if (args.length === 1 && (args[0] === "--help" || args[0] === "-h")) return Effect.sync(() => {
5516
+ options.stdout.write(superagentUsage);
5517
+ return 0;
5518
+ });
5519
+ return Effect.gen(function* () {
5520
+ const request = yield* Effect.try({
5521
+ try: () => parseSuperagentArguments(args),
5522
+ catch: (error) => error
5523
+ });
5524
+ const state = options.env.RIVUS_DEPLOYMENT_STATE_DIR?.trim() || (yield* options.homeApi.load(yield* resolveHomeDirectoryEffect(options))).stateDirectory;
5525
+ const response = yield* Effect.tryPromise({
5526
+ try: () => requestLocalJson(superagentControlSocketPath(resolve(options.cwd, state)), request),
5527
+ catch: (error) => error
5528
+ });
5529
+ if (!response.ok) {
5530
+ options.stderr.write(renderRivusCliError(new Error(response.error)));
5531
+ return superagentRejectionExitCode(response.code);
5532
+ }
5533
+ options.stdout.write(JSON.stringify(response.value, null, 2) + "\n");
5534
+ return 0;
5535
+ }).pipe(Effect.catch((error) => superagentTransportError(options, error)));
5536
+ }
5537
+ //#endregion
5538
+ //#region src/bootstrap/cli/worker-hook.ts
5539
+ const decodePayload = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json));
5540
+ const questions = Schema.NonEmptyArray(Schema.Struct({
5541
+ question: Schema.NonEmptyString,
5542
+ multiSelect: Schema.optionalKey(Schema.Boolean),
5543
+ options: Schema.Array(Schema.Struct({
5544
+ label: Schema.NonEmptyString,
5545
+ description: Schema.optionalKey(Schema.String)
5546
+ }))
5547
+ }));
5548
+ const decodeQuestions = Schema.decodeUnknownOption(Schema.Struct({ tool_input: Schema.Struct({ questions }) }));
5549
+ /** What a hook that only observes prints, so that Claude Code proceeds unchanged. */
5550
+ const passThrough = "{}";
5551
+ const denyQuestion = JSON.stringify({ hookSpecificOutput: {
5552
+ hookEventName: "PreToolUse",
5553
+ permissionDecision: "deny",
5554
+ permissionDecisionReason: "The question was sent to the task thread; the answer arrives as the next input. Stop and wait for it."
5555
+ } });
5556
+ function questionText(asked) {
5557
+ return asked.map(({ question, multiSelect, options }) => [multiSelect === true ? `${question} (choose any number)` : question, ...options.map(({ label, description }, index) => description ? `${index + 1}. ${label}: ${description}` : `${index + 1}. ${label}`)].join("\n")).join("\n\n");
5558
+ }
5559
+ /**
5560
+ * Reads one Claude Code hook payload into the event sent to the worker socket. Raw tool input and output stay in the
5561
+ * hook process: only the lifecycle fields and, for AskUserQuestion, the decoded question text leave it.
5562
+ */
5563
+ function readWorkerHook(stdin, env, at) {
5564
+ const payload = decodePayload(stdin);
5565
+ if (Option.isNone(payload)) return;
5566
+ const event = readHookEvent("claude-code", payload.value, env);
5567
+ if (event.phase === "unknown" || event.nativeEvent === "Notification" && event.phase === "blocked") return;
5568
+ const activity = {
5569
+ phase: event.phase === "blocked" ? "blocked" : event.phase === "finish" && event.scope === "turn" ? "finish" : "activity",
5570
+ ...event.phase === "blocked" && event.blocker !== void 0 ? { blocker: event.blocker } : {},
5571
+ ...event.tool === void 0 ? {} : { tool: event.tool.name },
5572
+ at,
5573
+ ...event.turnId === void 0 ? {} : { turnId: event.turnId }
5574
+ };
5575
+ const asked = event.nativeEvent === "PreToolUse" && event.tool?.name === "AskUserQuestion" ? decodeQuestions(payload.value) : Option.none();
5576
+ return Option.isSome(asked) ? {
5577
+ activity,
5578
+ question: questionText(asked.value.tool_input.questions)
5579
+ } : { activity };
5580
+ }
5581
+ /**
5582
+ * Runs `rivus task hook` and returns what it prints. It never fails: a hook that cannot reach Rivus lets Claude Code
5583
+ * proceed, and AskUserQuestion is denied only after the question was recorded, so a rejected question stays in the
5584
+ * terminal.
5585
+ */
5586
+ async function runWorkerHook(stdin, env, at) {
5587
+ const path = env.RIVUS_WORKER_SOCKET;
5588
+ const execution = env.RIVUS_WORKER_KEY;
5589
+ const token = env.RIVUS_WORKER_TOKEN;
5590
+ const event = readWorkerHook(stdin, env, at);
5591
+ if (!path || !execution || !token || event === void 0) return passThrough;
5592
+ try {
5593
+ const outcome = await requestSuperagentWorker(path, {
5594
+ execution,
5595
+ token
5596
+ }, {
5597
+ operation: "event",
5598
+ ...event
5599
+ }, 2e3);
5600
+ return event.question !== void 0 && outcome === "recorded" ? denyQuestion : passThrough;
5601
+ } catch {
5602
+ return passThrough;
5603
+ }
5604
+ }
5605
+ //#endregion
5606
+ //#region src/bootstrap/cli/task-command.ts
5607
+ function runTaskCommand(options) {
5608
+ if (options.argv[1] === "hook" && options.argv.length === 2) return Effect.promise(async () => {
5609
+ const payload = await options.readStdin().catch(() => "");
5610
+ options.stdout.write(await runWorkerHook(payload, options.env, Date.now()) + "\n");
5611
+ return 0;
5612
+ });
5613
+ return Effect.gen(function* () {
5614
+ const [, command, raw, ...rest] = options.argv;
5615
+ const path = options.env.RIVUS_WORKER_SOCKET;
5616
+ const execution = options.env.RIVUS_WORKER_KEY;
5617
+ const token = options.env.RIVUS_WORKER_TOKEN;
5618
+ if (!path || !execution || !token) return yield* writeError(options, /* @__PURE__ */ new Error("This command requires an active Rivus worker execution"));
5619
+ const payload = command === "report" && rest.length === 0 ? raw : command === "call" && rest.length === 1 ? rest[0] : void 0;
5620
+ const request = command === "show" && raw === void 0 ? {
5621
+ operation: "call",
5622
+ name: "task_show",
5623
+ input: {}
5624
+ } : payload !== void 0 && raw !== void 0 ? {
5625
+ operation: "call",
5626
+ name: command === "report" ? "task_report" : raw,
5627
+ input: yield* Effect.try({
5628
+ try: () => Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Json))(payload),
5629
+ catch: (error) => error
5630
+ })
5631
+ } : void 0;
5632
+ if (request === void 0) return yield* writeError(options, /* @__PURE__ */ new Error("Usage: rivus task show | rivus task report '<json>' | rivus task call <name> '<json>'"));
5633
+ const value = yield* Effect.tryPromise({
5634
+ try: () => requestSuperagentWorker(path, {
5635
+ execution,
5636
+ token
5637
+ }, request),
5638
+ catch: (error) => error
5639
+ });
5640
+ options.stdout.write(JSON.stringify(value, null, 2) + "\n");
5641
+ return 0;
5642
+ }).pipe(Effect.catch((error) => error instanceof SuperagentWorkerRejected ? Effect.sync(() => {
5643
+ options.stderr.write(renderRivusCliError(error));
5644
+ return 2;
5645
+ }) : superagentTransportError(options, error)));
5788
5646
  }
5789
5647
  //#endregion
5790
5648
  //#region src/bootstrap/upgrade/upgrade-home.ts
@@ -5836,113 +5694,7 @@ async function upgradeHome(options) {
5836
5694
  }
5837
5695
  }
5838
5696
  //#endregion
5839
- //#region src/bootstrap/cli/rivus-cli.ts
5840
- function resolveHomeRecoveryFileArguments(argv, command, cwd) {
5841
- if (command.type === "inspect") return argv;
5842
- const files = /* @__PURE__ */ new Map([["--recovery-note-file", resolve(cwd, command.noteFilePath)]]);
5843
- if (command.type === "resolve-tool-operation" && command.outcome.status === "applied") files.set("--tool-result-file", resolve(cwd, command.outcome.resultFilePath));
5844
- const resolved = [];
5845
- for (let index = 0; index < argv.length; index += 1) {
5846
- const argument = argv[index];
5847
- const file = [...files].find(([flag]) => argument === flag || argument.startsWith(`${flag}=`));
5848
- if (!file) resolved.push(argument);
5849
- else if (argument === file[0]) {
5850
- resolved.push(argument, file[1]);
5851
- index += 1;
5852
- } else resolved.push(`${file[0]}=${file[1]}`);
5853
- }
5854
- return resolved;
5855
- }
5856
- /** The exit code reads the request receipt from the open model response record by name (authoring guide, Validation). */
5857
- const requestReceipt = Schema.Struct({ requestId: Schema.String });
5858
- function modelManagementExitCode(response) {
5859
- if (response.status !== "failed") return 0;
5860
- if (typeof response.requestId === "string" && response.requestId.trim()) return 0;
5861
- const request = response.request;
5862
- if (!Schema.is(requestReceipt)(request)) return 1;
5863
- return request.requestId.trim() ? 0 : 1;
5864
- }
5865
- function writeModelResponse(stdout, response) {
5866
- stdout.write(`${JSON.stringify(response)}\n`);
5867
- }
5868
- function modelTransportFailure(error) {
5869
- const code = error instanceof RivusModelManagementTransportError ? error.code : "socket_error";
5870
- return {
5871
- error: {
5872
- code,
5873
- message: code === "timeout" ? "model management service timed out" : code === "invalid_response" ? "model management returned an invalid response" : "model management service is unavailable"
5874
- },
5875
- schemaVersion: 1,
5876
- status: "failed"
5877
- };
5878
- }
5879
- function runModelCommand(options) {
5880
- const parsed = parseRivusModelCliArguments(options.argv.slice(1));
5881
- if ("help" in parsed) return Effect.sync(() => {
5882
- options.stdout.write(renderRivusModelCliHelp());
5883
- return 0;
5884
- });
5885
- if ("error" in parsed) return Effect.sync(() => {
5886
- options.stderr.write(renderRivusModelCliArgumentError(parsed.error));
5887
- return 1;
5888
- });
5889
- if (parsed.operation !== "status" && !isRivusModelManagementEnabled(options.env)) return Effect.sync(() => {
5890
- writeModelResponse(options.stdout, {
5891
- error: {
5892
- code: "management_disabled",
5893
- message: "model management is not enabled for this Home"
5894
- },
5895
- schemaVersion: 1,
5896
- status: "failed"
5897
- });
5898
- return 1;
5899
- });
5900
- const client = options.modelManagementClient ?? createRivusModelManagementSocketClient({
5901
- env: options.env,
5902
- socketPath: resolveRivusModelSocketPath({
5903
- env: options.env,
5904
- homeDirectory: options.homeDirectory
5905
- })
5906
- });
5907
- return Effect.tryPromise({
5908
- try: () => client.execute(parsed),
5909
- catch: (error) => error
5910
- }).pipe(Effect.tap((response) => Effect.sync(() => writeModelResponse(options.stdout, response))), Effect.map((response) => modelManagementExitCode(response)), Effect.catch((error) => Effect.sync(() => {
5911
- writeModelResponse(options.stdout, modelTransportFailure(error));
5912
- return 1;
5913
- })));
5914
- }
5915
- /** Lets an interrupted install stop its child processes and remove its staging directory before the CLI exits. */
5916
- function abortOnInterruption(signalSource) {
5917
- const controller = new AbortController();
5918
- signalSource.on("SIGINT", () => controller.abort());
5919
- signalSource.on("SIGTERM", () => controller.abort());
5920
- return controller.signal;
5921
- }
5922
- function withOptionalDirectoryArgument(options, command, run) {
5923
- const parsed = parseRivusDirectoryArguments(options.argv.slice(1));
5924
- if (parsed.help) return Effect.sync(() => {
5925
- options.stdout.write(renderRivusDirectoryCommandUsage(command));
5926
- return 0;
5927
- });
5928
- if (parsed.error) return Effect.sync(() => {
5929
- options.stderr.write(renderRivusDirectoryCommandUsage(command));
5930
- return 1;
5931
- });
5932
- return run(parsed.directory);
5933
- }
5934
- function resolveHomeDirectoryEffect(options, argument) {
5935
- return Effect.try({
5936
- try: () => {
5937
- if (argument) return resolve(options.cwd, argument);
5938
- const configured = options.env.RIVUS_HOME?.trim();
5939
- if (!configured) return resolve(options.homeDirectory, ".rivus-agent");
5940
- if (!isAbsolute(configured)) throw new Error("RIVUS_HOME must be an absolute path");
5941
- return resolve(configured);
5942
- },
5943
- catch: (error) => error instanceof Error ? error : new Error(String(error))
5944
- });
5945
- }
5697
+ //#region src/bootstrap/cli/upgrade-command.ts
5946
5698
  function runUpgradeCommand(options) {
5947
5699
  const parsed = parseUpgradeArguments(options.argv.slice(1));
5948
5700
  if ("help" in parsed) return Effect.sync(() => {
@@ -5982,127 +5734,8 @@ function runUpgradeCommand(options) {
5982
5734
  return 1;
5983
5735
  })));
5984
5736
  }
5985
- function writeDoctorReport(stdout, report, owner) {
5986
- for (const chunk of renderRivusDoctorReport(report, owner)) stdout.write(chunk);
5987
- return report.ready ? 0 : 1;
5988
- }
5989
- function writeError(options, error) {
5990
- return Effect.sync(() => {
5991
- options.stderr.write(renderRivusCliError(error));
5992
- return 1;
5993
- });
5994
- }
5995
- function runAudioCommand(options) {
5996
- const parsed = parseRivusAudioCliArguments(options.argv.slice(1));
5997
- if ("help" in parsed) return Effect.sync(() => {
5998
- options.stdout.write(RIVUS_AUDIO_CLI_USAGE);
5999
- return 0;
6000
- });
6001
- if ("error" in parsed) return Effect.sync(() => {
6002
- options.stderr.write(renderRivusAudioCliArgumentError(parsed.error));
6003
- return 1;
6004
- });
6005
- return resolveHomeDirectoryEffect(options).pipe(Effect.flatMap((directory) => options.homeApi.load(directory)), Effect.flatMap((home) => Effect.tryPromise({
6006
- try: () => runRivusAudioCliCommand(parsed, {
6007
- assetDirectory: gatewayAudioTranscriberAssetDirectory,
6008
- cwd: options.cwd,
6009
- env: options.env,
6010
- installRoot: join(home.stateDirectory, "audio-transcriber"),
6011
- nodeExecutable: options.nodeExecutable,
6012
- platform: createNodePlatform(),
6013
- runProcess: runRivusAudioProcess,
6014
- signal: abortOnInterruption(options.signalSource),
6015
- stderr: options.stderr,
6016
- stdout: options.stdout
6017
- }),
6018
- catch: (error) => error
6019
- })), Effect.catch((error) => writeError(options, error)));
6020
- }
6021
- function runSetupCommand(options) {
6022
- 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))));
6023
- }
6024
- function runHomeDaemonCommand(options, command, daemonArgs) {
6025
- const commandArgs = options.argv.slice(1);
6026
- const checkPlugins = command === "check-config" && commandArgs.length === 1 && commandArgs[0] === "--load-plugins";
6027
- if (command !== "recovery" && !checkPlugins && hasRivusHomeCommandArguments(commandArgs)) return Effect.sync(() => {
6028
- options.stderr.write(renderRivusHomeCommandUsage(command));
6029
- return 1;
6030
- });
6031
- return resolveHomeDirectoryEffect(options).pipe(Effect.flatMap((directory) => options.homeApi.load(directory)), Effect.tap((home) => Effect.sync(() => options.changeWorkingDirectory(home.workspaceDirectory))), Effect.flatMap((home) => runRivusDaemonCli({
6032
- ...options,
6033
- argv: [
6034
- "--env-file",
6035
- home.envFilePath,
6036
- "--bootstrap",
6037
- home.bootstrap,
6038
- "--manifest",
6039
- home.manifestPath,
6040
- ...daemonArgs
6041
- ],
6042
- env: {
6043
- ...options.env,
6044
- RIVUS_DEPLOYMENT_STATE_DIR: home.stateDirectory,
6045
- RIVUS_HOME: home.directory,
6046
- [RIVUS_HOME_DEPLOYMENT_ENV]: home.directory
6047
- },
6048
- pluginPackageManifestPath: options.pluginPackageManifestPath ?? gatewayPackageManifestPath,
6049
- ...checkPlugins ? { checkPlugins: true } : {},
6050
- ...command === "start" ? { lifecycle: {
6051
- started: async () => {
6052
- if (!options.runtimeProcess) throw new Error("Home start requires the runtime process identity");
6053
- await writeRuntimeReceipt({
6054
- ...options.runtimeProcess,
6055
- home: home.directory,
6056
- version: RIVUS_RELEASE_DESCRIPTOR.version,
6057
- startedAt: (/* @__PURE__ */ new Date()).toISOString()
6058
- });
6059
- },
6060
- stopped: async () => {
6061
- if (options.runtimeProcess) await clearRuntimeReceipt(home.directory, options.runtimeProcess.pid);
6062
- }
6063
- } } : {}
6064
- })), Effect.catch((error) => writeError(options, error)));
6065
- }
6066
- function runInitCommand(options) {
6067
- return withOptionalDirectoryArgument(options, "init", (argument) => {
6068
- const directory = resolve(options.cwd, argument ?? ".");
6069
- return Effect.tryPromise({
6070
- try: () => initializeRivusProject({
6071
- directory,
6072
- nodeExecutable: options.nodeExecutable,
6073
- templateDirectory: gatewayTemplateDirectory
6074
- }),
6075
- catch: (error) => error
6076
- }).pipe(Effect.tap((result) => Effect.sync(() => options.stdout.write(renderRivusProjectInitializationSuccess(result.directory)))), Effect.as(0), Effect.catch((error) => writeError(options, error)));
6077
- });
6078
- }
6079
- function runDoctorCommand(options) {
6080
- const parsed = parseRivusDoctorArguments(options.argv.slice(1));
6081
- if (parsed.help) return Effect.sync(() => {
6082
- options.stdout.write(renderRivusDoctorUsage());
6083
- return 0;
6084
- });
6085
- if (parsed.error) {
6086
- const error = parsed.error;
6087
- return Effect.sync(() => {
6088
- options.stderr.write(renderRivusDoctorArgumentError(error));
6089
- return 1;
6090
- });
6091
- }
6092
- if (parsed.directory === void 0) return resolveHomeDirectoryEffect(options).pipe(Effect.flatMap((directory) => options.homeApi.diagnose({
6093
- directory,
6094
- env: options.env,
6095
- ...parsed.envFilePath ? { envFilePath: parsed.envFilePath } : {},
6096
- nodeVersion: options.nodeVersion
6097
- })), Effect.map((report) => writeDoctorReport(options.stdout, report, "Home")), Effect.catch((error) => writeError(options, error)));
6098
- const projectDirectory = parsed.directory;
6099
- return diagnoseRivusProject({
6100
- directory: resolve(options.cwd, projectDirectory),
6101
- env: options.env,
6102
- ...parsed.envFilePath ? { envFilePath: parsed.envFilePath } : {},
6103
- nodeVersion: options.nodeVersion
6104
- }).pipe(Effect.map((report) => writeDoctorReport(options.stdout, report, "project")), Effect.catch((error) => writeError(options, error)));
6105
- }
5737
+ //#endregion
5738
+ //#region src/bootstrap/cli/rivus-cli.ts
6106
5739
  function runRivusCli(options) {
6107
5740
  const command = options.argv[0];
6108
5741
  if (command === "setup") return runSetupCommand(options);
@@ -6110,27 +5743,12 @@ function runRivusCli(options) {
6110
5743
  if (command === "start") return runHomeDaemonCommand(options, "start", []);
6111
5744
  if (command === "status") return runHomeDaemonCommand(options, "status", ["--status"]);
6112
5745
  if (command === "check-config") return runHomeDaemonCommand(options, "check-config", ["--check-config"]);
6113
- if (command === "recovery") {
6114
- const argv = options.argv.slice(1);
6115
- const parser = createRivusRecoveryCliParser();
6116
- for (let index = 0; index < argv.length; index += 1) {
6117
- const argument = parser.consume(argv[index], argv[index + 1]);
6118
- if (!argument.handled || argument.error) return Effect.sync(() => {
6119
- options.stderr.write(renderRivusHomeCommandUsage("recovery"));
6120
- return 1;
6121
- });
6122
- index += argument.consumed;
6123
- }
6124
- const parsed = parser.build();
6125
- if (argv.length === 0 || parsed.error || !parsed.command) return Effect.sync(() => {
6126
- options.stderr.write(renderRivusHomeCommandUsage("recovery"));
6127
- return 1;
6128
- });
6129
- return runHomeDaemonCommand(options, "recovery", resolveHomeRecoveryFileArguments(argv, parsed.command, options.cwd));
6130
- }
5746
+ if (command === "recovery") return runRecoveryCommand(options);
6131
5747
  if (command === "init") return runInitCommand(options);
6132
5748
  if (command === "doctor") return runDoctorCommand(options);
6133
5749
  if (command === "model") return runModelCommand(options);
5750
+ if (command === "superagent") return runSuperagentCommand(options);
5751
+ if (command === "task") return runTaskCommand(options);
6134
5752
  if (command === "audio") return runAudioCommand(options);
6135
5753
  if (command && !command.startsWith("-")) return Effect.sync(() => {
6136
5754
  options.stderr.write(renderRivusCliUnknownCommand(command));
@@ -6155,6 +5773,7 @@ function runRivusNodeEntrypoint(options) {
6155
5773
  env: options.env,
6156
5774
  ...options.exitAfterSignal !== void 0 ? { exitAfterSignal: options.exitAfterSignal } : {},
6157
5775
  homeApi: createNodeRivusHome({ deploymentInspector: createRivusHomeDeploymentInspector({
5776
+ checkSuperagents: checkSuperagentConfigurations,
6158
5777
  isModelManagementEnabled: parseRivusModelManagementEnabled,
6159
5778
  packageManifestPath: gatewayPackageManifestPath
6160
5779
  }) }),
@@ -6162,6 +5781,7 @@ function runRivusNodeEntrypoint(options) {
6162
5781
  loadBootstrap: (specifier) => import(toImportSpecifier(specifier)),
6163
5782
  nodeExecutable: process.execPath,
6164
5783
  nodeVersion: process.versions.node,
5784
+ readStdin: () => text(process.stdin),
6165
5785
  upgradeHost: {
6166
5786
  platform: process.platform,
6167
5787
  lockPlatform: createNodePlatform()