@rivus/gateway 0.22.3 → 0.24.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,261 @@
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 { $t as invokeRuntimeControl, At as createNodeRivusPluginModuleLoader, B as readRivusAudioStatus, Bt as gatewayTemplateDirectory, Ct as parseRivusModelCliArguments, E as decodeWorkerStartParams, Et as checkSuperagentConfigurations, F as runRivusAudioPassthroughProcess, Ft as RIVUS_RELEASE_DESCRIPTOR, H as withoutRivusHomeDeployment, Ht as resolveAcpRuntimeEnvironment, I as runRivusAudioProcess, It as gatewayAudioTranscriberAssetDirectory, Jt as narrowBackgroundSessionDefinition, Lt as gatewayPackageDirectory, Mt as validateTrustedModulePath, N as createHerdrWorkerExecutor, Nt as findTrustedPackageRoot, Pt as loadRivusDeploymentManifest, Qt as disposeRuntimeCacheEntries, R as installRivusAudioTranscriber, Rt as gatewayPackageManifestPath, T as decodeWorkerRetireParams, Tt as renderRivusModelCliHelp, Ut as resolveFeishuEndpointCredentials, V as RIVUS_HOME_DEPLOYMENT_ENV, Vt as loadMergedLocalEnvFile, W as runRivusRecoveryCliCommand, Wt as toError, Xt as openLocalJsonSocket, Yt as errorMessage, Zt as createRuntimeCache, _t as resolveRivusModelSocketPath, a as FILE_CHUNK_BYTES, dt as superagentUsage, en as deepFreeze, g as decodeWorkerChooseMenuParams, gt as isRivusModelManagementEnabled, h as decodeWorkerBackendParams, i as createStdioRpcChannel, it as deploymentStateDirectoryFromEnv, j as decodeWorkspaceReadFileParams, jt as resolveNodeRivusPluginModulePath, k as decodeWorkspacePrepareParams, lt as parseSuperagentArguments, n as BridgeRpcError, ot as superagentControlSocketPath, p as decodeWorkerAvailableParams, pt as parseRivusModelManagementEnabled, qt as createBackgroundSessionToolContracts, s as decodeHelloParams, t as prepareWorkerPrograms, u as decodeMenuClaimResult, ut as superagentRejectionExitCode, v as decodeWorkerDeliverParams, w as decodeWorkerReadTerminalParams, wt as renderRivusModelCliArgumentError, x as decodeWorkerPressKeyParams, yt as createRivusModelManagementWireRequest, z as readRivusAudioInstalledRelease } from "./superagent-worker-programs.js";
2
+ import { o as requestLocalJson, r as requestSuperagentWorker, t as SuperagentWorkerRejected } from "./superagent-worker-wire.js";
3
+ import { t as createHerdrSocketClient } from "./herdr-socket-client.js";
4
+ import { findPackageJSON, registerHooks } from "node:module";
4
5
  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";
6
+ import { Cause, Context, Deferred, Effect, Exit, Layer, Option, Result, Schema, SchemaGetter, Semaphore } from "effect";
7
7
  import { unwrapExit } from "@rivus/platform/effect";
8
+ import { createConnection } from "node:net";
9
+ import { access, chmod, constants, copyFile, link, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, rmdir, stat, symlink, unlink, writeFile } from "node:fs/promises";
10
+ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
11
+ import { isNodeErrorWithCode, isPathWithin } from "@rivus/platform/filesystem";
12
+ import { RIVUS_MEMORY_TOOL_PLUGIN_ID, RIVUS_RUNTIME_TOOL_IDS, createRivusMemoryToolContract, isRivusRuntimeToolId } from "@rivus/runtime";
8
13
  import { readPersistenceFile, writeAtomicTextFile } from "@rivus/platform/persistence";
9
14
  import { homedir } from "node:os";
10
- import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
15
+ import { text } from "node:stream/consumers";
11
16
  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";
14
17
  import { compare, minVersion, parse, satisfies, valid } from "semver";
15
- import { assertPathWithin, isNodeErrorWithCode, isPathWithin } from "@rivus/platform/filesystem";
16
- import { createConnection } from "node:net";
18
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
17
19
  import { randomUUID } from "node:crypto";
20
+ import { createNodePlatform } from "@rivus/agent-kit/node";
18
21
  import { acquireProcessLock } from "@rivus/agent-kit-collab/process-lock";
19
22
  import { constants as constants$1, realpathSync } from "node:fs";
20
23
  import { spawn } from "node:child_process";
21
24
  import { isDeepStrictEqual } from "node:util";
22
- import { setTimeout as setTimeout$1 } from "node:timers/promises";
23
25
  import { parse as parse$1, stringify } from "yaml";
24
- //#region src/agent-catalog/domain/plugin/value-objects/rivus-plugin.ts
26
+ import { readHookEvent } from "@rivus/agent-kit/harness/events";
27
+ //#region src/agent-host/application/ports.ts
28
+ var AgentInstanceIdentity = class extends Context.Service()("@rivus/gateway/agent-host/AgentInstanceIdentity") {};
29
+ var AgentHostRuntimes = class extends Context.Service()("@rivus/gateway/agent-host/AgentHostRuntimes") {};
30
+ //#endregion
31
+ //#region src/agent-host/application/services/agent-instance-registry.ts
32
+ /** @internal */
33
+ var AgentInstanceConflict = class extends Error {
34
+ name = "AgentInstanceConflict";
35
+ };
36
+ function bindingKey(binding, agentId) {
37
+ const bindingId = binding.kind === "endpoint" ? binding.endpointId : binding.kind === "automation" ? binding.automationId : binding.agentId;
38
+ return `${binding.kind}:${bindingId}:${agentId}`;
39
+ }
40
+ function freezeRecord(record) {
41
+ return Object.freeze({
42
+ ...record,
43
+ binding: Object.freeze({ ...record.binding })
44
+ });
45
+ }
46
+ function buildRegistry(identity, options) {
47
+ const records = /* @__PURE__ */ new Map();
48
+ for (const record of options.initialRecords ?? []) {
49
+ if (bindingKey(record.binding, record.agentId) !== record.bindingKey) throw new AgentInstanceConflict(`invalid binding key: ${record.bindingKey}`);
50
+ if (records.has(record.bindingKey)) throw new AgentInstanceConflict(`duplicate binding: ${record.bindingKey}`);
51
+ records.set(record.bindingKey, freezeRecord(record));
52
+ }
53
+ const resolveBinding = (instanceBinding, definition) => Effect.try({
54
+ try: () => {
55
+ const runtimeGenerationId = identity.createRuntimeGenerationId({
56
+ agentId: definition.agentId,
57
+ profileRevision: definition.profileRevision,
58
+ projectSpaceId: definition.projectSpaceId ?? null,
59
+ projectSpaceRevision: definition.projectSpaceRevision ?? null,
60
+ runtimeToolGrantRevision: definition.runtimeToolGrantSet.revision,
61
+ skillGrantRevision: definition.skillGrantSet.revision,
62
+ toolGrantRevision: definition.toolGrantSet.revision
63
+ });
64
+ const key = bindingKey(instanceBinding, definition.agentId);
65
+ const existing = records.get(key);
66
+ if (existing) {
67
+ if (existing.runtimeGenerationId !== runtimeGenerationId) throw new AgentInstanceConflict(`binding ${key} belongs to a different runtime generation`);
68
+ return existing;
69
+ }
70
+ const record = freezeRecord({
71
+ agentId: definition.agentId,
72
+ binding: instanceBinding,
73
+ bindingKey: key,
74
+ instanceId: identity.createInstanceId({
75
+ bindingKey: key,
76
+ runtimeGenerationId
77
+ }),
78
+ runtimeGenerationId
79
+ });
80
+ records.set(key, record);
81
+ return record;
82
+ },
83
+ catch: (error) => error instanceof AgentInstanceConflict ? error : new AgentInstanceConflict(String(error))
84
+ });
85
+ return {
86
+ resolveAutomation: (automationId, definition) => resolveBinding({
87
+ automationId,
88
+ kind: "automation"
89
+ }, definition),
90
+ resolveBackgroundSession: (agentId, definition) => resolveBinding({
91
+ agentId,
92
+ kind: "background-session"
93
+ }, definition),
94
+ resolveEndpoint: (endpointId, definition) => resolveBinding({
95
+ endpointId,
96
+ kind: "endpoint"
97
+ }, definition),
98
+ snapshot: () => Effect.sync(() => Object.freeze([...records.values()]))
99
+ };
100
+ }
101
+ /** An initial record whose key does not match its binding, or that repeats a binding, dies with `AgentInstanceConflict`. */
102
+ function makeAgentInstanceRegistry(options = {}) {
103
+ return AgentInstanceIdentity.pipe(Effect.flatMap((identity) => Effect.sync(() => buildRegistry(identity, options))));
104
+ }
105
+ //#endregion
106
+ //#region src/agent-host/application/use-cases/agent-host.ts
107
+ /** @internal */
108
+ var InvalidAgentHostBinding = class extends Error {
109
+ name = "InvalidAgentHostBinding";
110
+ };
111
+ function makeAgentHost(options) {
112
+ return Effect.gen(function* () {
113
+ const runtime = yield* AgentHostRuntimes;
114
+ const registry = yield* makeAgentInstanceRegistry({ initialRecords: options.initialInstanceRecords });
115
+ const definitions = new Map(options.definitions.map((definition) => [definition.agentId, definition]));
116
+ const endpoints = /* @__PURE__ */ new Map();
117
+ const automations = /* @__PURE__ */ new Map();
118
+ const backgroundSessions = /* @__PURE__ */ new Map();
119
+ for (const endpoint of options.endpoints) {
120
+ if (endpoints.has(endpoint.id)) return yield* Effect.fail(new InvalidAgentHostBinding(`duplicate endpoint: ${endpoint.id}`));
121
+ const definition = definitions.get(endpoint.agentId);
122
+ if (!definition) return yield* Effect.fail(new InvalidAgentHostBinding(`unknown endpoint agent: ${endpoint.agentId}`));
123
+ if (!definition.endpointIds.includes(endpoint.id)) return yield* Effect.fail(new InvalidAgentHostBinding(`endpoint ${endpoint.id} is not declared by ${endpoint.agentId}`));
124
+ endpoints.set(endpoint.id, yield* registry.resolveEndpoint(endpoint.id, definition));
125
+ }
126
+ for (const automation of options.automations ?? []) {
127
+ if (automations.has(automation.id)) return yield* Effect.fail(new InvalidAgentHostBinding(`duplicate automation: ${automation.id}`));
128
+ if (!definitions.has(automation.definition.agentId)) return yield* Effect.fail(new InvalidAgentHostBinding(`unknown automation agent: ${automation.definition.agentId}`));
129
+ automations.set(automation.id, yield* registry.resolveAutomation(automation.id, automation.definition));
130
+ }
131
+ for (const backgroundSession of options.backgroundSessions ?? []) {
132
+ if (backgroundSession.definition.agentId !== backgroundSession.agentId) return yield* Effect.fail(new InvalidAgentHostBinding(`background session ${backgroundSession.agentId} cannot bind definition ${backgroundSession.definition.agentId}`));
133
+ if (backgroundSessions.has(backgroundSession.agentId)) return yield* Effect.fail(new InvalidAgentHostBinding(`duplicate background session agent: ${backgroundSession.agentId}`));
134
+ if (!definitions.has(backgroundSession.agentId)) return yield* Effect.fail(new InvalidAgentHostBinding(`unknown background session agent: ${backgroundSession.agentId}`));
135
+ backgroundSessions.set(backgroundSession.agentId, yield* registry.resolveBackgroundSession(backgroundSession.agentId, backgroundSession.definition));
136
+ }
137
+ const resolve = (records, id, message) => {
138
+ const instance = records.get(id);
139
+ return instance ? Effect.succeed(instance) : Effect.fail(new InvalidAgentHostBinding(message));
140
+ };
141
+ const resolveEndpoint = (endpointId) => resolve(endpoints, endpointId, `unknown endpoint: ${endpointId}`);
142
+ const resolveAutomation = (automationId) => resolve(automations, automationId, `unknown automation: ${automationId}`);
143
+ const resolveBackgroundSession = (agentId) => resolve(backgroundSessions, agentId, `unknown background session agent: ${agentId}`);
144
+ return {
145
+ cancelBackgroundSession: (agentId, input) => resolveBackgroundSession(agentId).pipe(Effect.flatMap((instance) => runtime.cancel(instance, input))),
146
+ cancelEndpoint: (endpointId, input) => resolveEndpoint(endpointId).pipe(Effect.flatMap((instance) => runtime.cancel(instance, input))),
147
+ dispose: () => runtime.disposeAll(),
148
+ handleAutomation: (automationId, input) => resolveAutomation(automationId).pipe(Effect.flatMap((instance) => runtime.run(instance, input))),
149
+ handleBackgroundSession: (agentId, input) => resolveBackgroundSession(agentId).pipe(Effect.flatMap((instance) => runtime.run(instance, input))),
150
+ handleEndpoint: (endpointId, input) => resolveEndpoint(endpointId).pipe(Effect.flatMap((instance) => runtime.run(instance, input))),
151
+ resolveAutomation,
152
+ resolveBackgroundSession,
153
+ resolveEndpoint,
154
+ steerEndpoint: (endpointId, input) => resolveEndpoint(endpointId).pipe(Effect.flatMap((instance) => runtime.steer(instance, input)))
155
+ };
156
+ });
157
+ }
158
+ //#endregion
159
+ //#region src/agent-host/infra/adapters/runtime-pool.ts
160
+ var RuntimeResourceBusy = class extends Error {
161
+ name = "RuntimeResourceBusy";
162
+ };
163
+ var RuntimeResourceDisposed = class extends Error {
164
+ name = "RuntimeResourceDisposed";
165
+ };
166
+ var RuntimePoolDisposalTimedOut = class extends Error {
167
+ name = "RuntimePoolDisposalTimedOut";
168
+ };
169
+ const DEFAULT_RUNTIME_DISPOSE_TIMEOUT_MS = 1e4;
170
+ function createEffectRuntimePool(options) {
171
+ const runtimes = createRuntimeCache();
172
+ const active = /* @__PURE__ */ new Map();
173
+ const lifecycle = Semaphore.makeUnsafe(1);
174
+ const existingRuntime = (instance) => Effect.gen(function* () {
175
+ const selected = yield* runtimes.getExisting(instance.instanceId);
176
+ if (!selected || !(yield* runtimes.isCurrent(instance.instanceId, selected.entry))) return;
177
+ return selected.runtime;
178
+ });
179
+ return {
180
+ cancel: (instance, input) => invokeRuntimeControl(existingRuntime(instance), (runtime) => runtime.cancel?.(input)),
181
+ disposeAll: () => Effect.gen(function* () {
182
+ const entries = yield* runtimes.drain();
183
+ yield* lifecycle.withPermits(1)(Effect.sync(() => active.clear()));
184
+ yield* disposeRuntimeCacheEntries({
185
+ dispose: (runtime) => runtime.dispose?.() ?? Effect.void,
186
+ entries,
187
+ failureMessage: "runtime pool disposal failed",
188
+ timeout: {
189
+ milliseconds: options.disposeTimeoutMs ?? DEFAULT_RUNTIME_DISPOSE_TIMEOUT_MS,
190
+ onTimeout: () => new RuntimePoolDisposalTimedOut(`runtime pool disposal timed out after ${options.disposeTimeoutMs ?? DEFAULT_RUNTIME_DISPOSE_TIMEOUT_MS}ms`)
191
+ }
192
+ });
193
+ }),
194
+ run: (instance, input) => Effect.gen(function* () {
195
+ const selected = yield* runtimes.getOrCreate(instance.instanceId, () => options.createRuntime(instance));
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 (selected.runtime.concurrency === "managed") return yield* selected.runtime.run(input);
198
+ const token = yield* lifecycle.withPermits(1)(Effect.gen(function* () {
199
+ if (!(yield* runtimes.isCurrent(instance.instanceId, selected.entry))) return yield* Effect.fail(new RuntimeResourceDisposed(`runtime was disposed before run start: ${instance.instanceId}`));
200
+ if (active.has(instance.instanceId)) return yield* Effect.fail(new RuntimeResourceBusy(`runtime already has an active run: ${instance.instanceId}`));
201
+ const activeToken = Symbol(instance.instanceId);
202
+ active.set(instance.instanceId, activeToken);
203
+ return activeToken;
204
+ }));
205
+ return yield* selected.runtime.run(input).pipe(Effect.ensuring(lifecycle.withPermits(1)(Effect.sync(() => {
206
+ if (active.get(instance.instanceId) === token) active.delete(instance.instanceId);
207
+ }))));
208
+ }),
209
+ steer: (instance, input) => invokeRuntimeControl(existingRuntime(instance), (runtime) => runtime.steer?.(input))
210
+ };
211
+ }
212
+ //#endregion
213
+ //#region src/agent-host/infra/adapters/effect-agent-runtime-pool.ts
214
+ /** @internal */
215
+ var AgentInstanceBusy = class extends Error {
216
+ name = "AgentInstanceBusy";
217
+ };
218
+ /** @internal */
219
+ var AgentRuntimeDisposed = class extends Error {
220
+ name = "AgentRuntimeDisposed";
221
+ };
222
+ function mapRuntimePoolError(error) {
223
+ if (error instanceof RuntimeResourceBusy) return new AgentInstanceBusy(error.message.replace(/^runtime /, "agent instance "));
224
+ if (error instanceof RuntimeResourceDisposed) return new AgentRuntimeDisposed(error.message.replace(/^runtime /, "agent runtime "));
225
+ if (error instanceof RuntimePoolDisposalTimedOut) return new AgentRuntimeDisposed(error.message.replace(/^runtime pool /, "agent runtime "));
226
+ return error;
227
+ }
228
+ function createAgentHostRuntimePool(factory, disposeTimeoutMs) {
229
+ const pool = createEffectRuntimePool({
230
+ createRuntime: (instance) => factory.create(instance),
231
+ ...disposeTimeoutMs === void 0 ? {} : { disposeTimeoutMs }
232
+ });
233
+ return {
234
+ cancel: (instance, input) => pool.cancel(instance, input),
235
+ disposeAll: () => pool.disposeAll().pipe(Effect.mapError((error) => error instanceof AggregateError && error.errors.length === 1 ? error.errors[0] : mapRuntimePoolError(error))),
236
+ run: (instance, input) => pool.run(instance, input).pipe(Effect.mapError(mapRuntimePoolError)),
237
+ steer: (instance, steering) => pool.steer(instance, steering)
238
+ };
239
+ }
240
+ //#endregion
241
+ //#region src/agent-host/infra/factories/agent-host-live.ts
242
+ /** Instance and generation ids derived from their inputs, so a restart reproduces them. */
243
+ const StableAgentInstanceIdentityLive = Layer.succeed(AgentInstanceIdentity, {
244
+ createInstanceId: (identity) => createStableId("instance", identity),
245
+ createRuntimeGenerationId: (identity) => createStableId("generation", identity)
246
+ });
247
+ /** One runtime per Agent Instance, created on first use by `factory`; each build of the Layer starts an empty pool. */
248
+ function pooledAgentHostRuntimes(factory) {
249
+ return Layer.sync(AgentHostRuntimes, () => createAgentHostRuntimePool(factory));
250
+ }
251
+ //#endregion
252
+ //#region src/agent-host/domain/plugin/rivus-plugin.ts
25
253
  const RIVUS_PLUGIN_API_VERSION = "1";
26
254
  var InvalidRivusPlugin = class extends Error {
27
255
  name = "InvalidRivusPlugin";
28
256
  };
29
257
  //#endregion
30
- //#region src/agent-catalog/domain/plugin/adapters/rivus-catalog-validation.ts
258
+ //#region src/agent-host/domain/plugin/adapters/rivus-catalog-validation.ts
31
259
  const automationRetryPolicySchema = Schema.Struct({
32
260
  maxAttempts: Schema.Number,
33
261
  terminalFailureCodes: Schema.optional(Schema.Array(Schema.String))
@@ -106,14 +334,14 @@ function uniqueRivusRuntimeToolIds(ids, owner) {
106
334
  return [...result];
107
335
  }
108
336
  //#endregion
109
- //#region src/agent-catalog/lib/stable-json.ts
337
+ //#region src/agent-host/lib/stable-json.ts
110
338
  function stableJson(value) {
111
339
  if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
112
340
  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
341
  return JSON.stringify(value);
114
342
  }
115
343
  //#endregion
116
- //#region src/agent-catalog/application/services/rivus-plugin-catalog.ts
344
+ //#region src/agent-host/application/services/catalog/rivus-plugin-catalog.ts
117
345
  function createRivusPluginCatalog$1(runtime) {
118
346
  const plugins = /* @__PURE__ */ new Map();
119
347
  const profiles = /* @__PURE__ */ new Map();
@@ -180,7 +408,7 @@ function createRivusPluginCatalog$1(runtime) {
180
408
  };
181
409
  }
182
410
  //#endregion
183
- //#region src/agent-catalog/application/services/rivus-tool-grant-set.ts
411
+ //#region src/agent-host/application/services/catalog/rivus-tool-grant-set.ts
184
412
  function intersectToolIds(sets) {
185
413
  const [first = [], ...rest] = sets;
186
414
  return [...new Set(first)].filter((id) => rest.every((set) => set.includes(id))).sort();
@@ -196,7 +424,7 @@ function narrowRivusToolGrantSet(runtime, parent, restrictions) {
196
424
  });
197
425
  }
198
426
  //#endregion
199
- //#region src/agent-catalog/application/services/rivus-agent-grant-restriction.ts
427
+ //#region src/agent-host/application/services/catalog/rivus-agent-grant-restriction.ts
200
428
  function uniqueRuntimeToolIds(ids) {
201
429
  const requested = /* @__PURE__ */ new Set();
202
430
  for (const id of ids) {
@@ -259,7 +487,7 @@ function restrictRivusAgentDefinitionGrants(runtime, definition, restriction) {
259
487
  });
260
488
  }
261
489
  //#endregion
262
- //#region src/agent-catalog/application/services/rivus-agent-definition-resolver.ts
490
+ //#region src/agent-host/application/services/catalog/rivus-agent-definition-resolver.ts
263
491
  function resolveRuntimeTools(profile, deployment) {
264
492
  const profileToolIds = uniqueRivusRuntimeToolIds(profile.runtimeTools?.allow ?? [], `profile ${profile.id}`);
265
493
  const requestedToolIds = uniqueRivusRuntimeToolIds(deployment.runtimeTools?.allow ?? [], `deployment ${deployment.agentId}`);
@@ -429,6 +657,7 @@ function resolveRivusAgentDefinition$1(runtime, catalog, deployment, providers)
429
657
  tools
430
658
  }), runtimeContributions);
431
659
  }
660
+ /** @internal */
432
661
  function createRivusAgentDefinitionResolver(runtime, providers) {
433
662
  return Object.freeze({ resolve: (catalog, deployment) => resolveRivusAgentDefinition$1(runtime, catalog, deployment, providers) });
434
663
  }
@@ -484,12 +713,115 @@ var RivusAgentHostFactory = class extends Context.Service()("@rivus/gateway/depl
484
713
  /** Optional: a deployment without Project Spaces runs without it, and one that declares them fails to prepare. */
485
714
  var RivusProjectSpaceResolver = class extends Context.Service()("@rivus/gateway/deployment/RivusProjectSpaceResolver") {};
486
715
  //#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);
716
+ //#region src/deployment/domain/manifest/adapters/deployment-manifest.ts
717
+ var InvalidRivusProjectSpace = class extends Error {
718
+ name = "InvalidRivusProjectSpace";
719
+ };
720
+ function isAbsoluteProjectPath(value) {
721
+ return value.startsWith("/") || value.startsWith("\\") || /^[a-z]:[\\/]/i.test(value);
722
+ }
723
+ function validateRelativeProjectPath(value, owner) {
724
+ if (value.trim() === "" || isAbsoluteProjectPath(value) || value.includes("\0")) throw new InvalidRivusProjectSpace(`${owner} must be a non-empty relative path`);
725
+ }
726
+ function validateRivusProjectSpaceDeployment(declaration) {
727
+ validateRelativeProjectPath(declaration.root, `project space ${declaration.id} root`);
728
+ validateRelativeProjectPath(declaration.workingDirectory, `project space ${declaration.id} working directory`);
729
+ const sources = /* @__PURE__ */ new Set();
730
+ for (const source of declaration.skills.sources) {
731
+ validateRelativeProjectPath(source, `project space ${declaration.id} Skill source`);
732
+ if (sources.has(source)) throw new InvalidRivusProjectSpace(`project space ${declaration.id} contains duplicate Skill source: ${source}`);
733
+ sources.add(source);
734
+ }
490
735
  }
491
- function toDeploymentFailure(failure) {
492
- return failure instanceof Error ? failure : new Error(String(failure));
736
+ /** @internal */
737
+ function validateRivusProjectSpaceDeployments(declarations) {
738
+ const projectSpaceIds = /* @__PURE__ */ new Set();
739
+ for (const declaration of declarations) {
740
+ if (projectSpaceIds.has(declaration.id)) throw new InvalidRivusProjectSpace(`duplicate project space: ${declaration.id}`);
741
+ projectSpaceIds.add(declaration.id);
742
+ validateRivusProjectSpaceDeployment(declaration);
743
+ }
744
+ return projectSpaceIds;
745
+ }
746
+ function validateBackgroundSessions(config) {
747
+ if (config.required && !config.enabled) throw new Error("backgroundSessions.required requires backgroundSessions.enabled");
748
+ if (config.leaseRenewalIntervalMs >= config.leaseMs) throw new Error("backgroundSessions.leaseRenewalIntervalMs must be shorter than leaseMs");
749
+ }
750
+ function validateModuleSpecifier(moduleSpecifier) {
751
+ const absolutePath = moduleSpecifier.startsWith("/") || moduleSpecifier.startsWith("\\\\") || /^[a-zA-Z]:[\\/]/.test(moduleSpecifier);
752
+ if (moduleSpecifier.trim() === "" || absolutePath || /^[a-z][a-z+.-]*:/i.test(moduleSpecifier) || moduleSpecifier.includes("\0")) throw new Error(`invalid plugin module specifier: ${moduleSpecifier}`);
753
+ if ((moduleSpecifier.startsWith("./") || moduleSpecifier.startsWith("../")) && moduleSpecifier.split(/[\\/]/).includes("..")) throw new Error(`plugin module escapes deployment root: ${moduleSpecifier}`);
754
+ }
755
+ function validateRivusDeploymentManifest(manifest) {
756
+ const projectSpaceIds = validateRivusProjectSpaceDeployments(manifest.projectSpaces ?? []);
757
+ const pluginIds = /* @__PURE__ */ new Set();
758
+ for (const plugin of manifest.plugins) {
759
+ if (pluginIds.has(plugin.id)) throw new Error(`duplicate plugin declaration: ${plugin.id}`);
760
+ validateModuleSpecifier(plugin.module);
761
+ pluginIds.add(plugin.id);
762
+ }
763
+ const agentIds = /* @__PURE__ */ new Set();
764
+ const agentById = /* @__PURE__ */ new Map();
765
+ for (const agent of manifest.agents) {
766
+ if (agentIds.has(agent.agentId)) throw new Error(`duplicate agent deployment: ${agent.agentId}`);
767
+ agentIds.add(agent.agentId);
768
+ if (!pluginIds.has(agent.pluginId)) throw new Error(`agent ${agent.agentId} references undeclared plugin: ${agent.pluginId}`);
769
+ if (agent.projectSpaceId && !projectSpaceIds.has(agent.projectSpaceId)) throw new Error(`agent ${agent.agentId} references unknown project space: ${agent.projectSpaceId}`);
770
+ const runtime = agent.runtime;
771
+ if (runtime) {
772
+ if (agent.runtimeTools !== void 0) throw new Error(`ACP agent ${agent.agentId} must not declare runtimeTools`);
773
+ if (agent.skills.allow.length > 0) throw new Error(`ACP agent ${agent.agentId} skills.allow must be empty`);
774
+ if (runtime.args?.includes("--yolo") && !runtime.unattended) throw new Error(`ACP agent ${agent.agentId} runtime.args --yolo requires unattended: true`);
775
+ }
776
+ agentById.set(agent.agentId, agent);
777
+ }
778
+ const endpointIds = /* @__PURE__ */ new Set();
779
+ const sessionNamespaces = /* @__PURE__ */ new Set();
780
+ for (const endpoint of manifest.endpoints) {
781
+ if (endpointIds.has(endpoint.id)) throw new Error(`duplicate endpoint binding: ${endpoint.id}`);
782
+ endpointIds.add(endpoint.id);
783
+ if (sessionNamespaces.has(endpoint.sessionNamespace)) throw new Error(`duplicate endpoint session namespace: ${endpoint.sessionNamespace}`);
784
+ sessionNamespaces.add(endpoint.sessionNamespace);
785
+ const agent = agentById.get(endpoint.agentId);
786
+ if (!agent) throw new Error(`endpoint ${endpoint.id} references unknown agent: ${endpoint.agentId}`);
787
+ if (agent.runtime?.unattended && !endpoint.allowedActors?.length) throw new Error(`unattended ACP agent ${agent.agentId} requires non-empty allowedActors on endpoint ${endpoint.id}`);
788
+ if (!agent.endpointIds.includes(endpoint.id)) throw new Error(`endpoint ${endpoint.id} is not declared by agent ${endpoint.agentId}`);
789
+ }
790
+ for (const agent of manifest.agents) for (const endpointId of agent.endpointIds) {
791
+ const endpoint = manifest.endpoints.find(({ id }) => id === endpointId);
792
+ if (!endpoint) throw new Error(`agent ${agent.agentId} references unknown endpoint: ${endpointId}`);
793
+ if (endpoint.agentId !== agent.agentId) throw new Error(`endpoint ${endpointId} is bound to a different agent`);
794
+ }
795
+ const superagentEndpoints = /* @__PURE__ */ new Set();
796
+ for (const endpoint of manifest.superagentEndpoints ?? []) {
797
+ if (endpointIds.has(endpoint.id) || superagentEndpoints.has(endpoint.id)) throw new Error(`duplicate endpoint binding: ${endpoint.id}`);
798
+ superagentEndpoints.add(endpoint.id);
799
+ }
800
+ const boundEndpoints = /* @__PURE__ */ new Set();
801
+ for (const id of manifest.superagent?.endpointIds ?? []) {
802
+ if (boundEndpoints.has(id)) throw new Error(`duplicate Superagent source binding: ${id}`);
803
+ if (!endpointIds.has(id) && !superagentEndpoints.has(id)) throw new Error(`Superagent source references unknown endpoint: ${id}`);
804
+ boundEndpoints.add(id);
805
+ }
806
+ for (const id of superagentEndpoints) if (!boundEndpoints.has(id)) throw new Error(`Superagent endpoint has no source: ${id}`);
807
+ const automationIds = /* @__PURE__ */ new Set();
808
+ for (const automation of manifest.automations ?? []) {
809
+ if (automationIds.has(automation.id)) throw new Error(`duplicate automation binding: ${automation.id}`);
810
+ automationIds.add(automation.id);
811
+ if (!agentById.has(automation.agentId)) throw new Error(`automation ${automation.id} references unknown agent: ${automation.agentId}`);
812
+ if (automation.workerId !== void 0 && automation.superagent !== true) throw new Error(`automation ${automation.id} workerId requires superagent`);
813
+ if (automation.superagent === true && (manifest.superagent?.endpointIds.length ?? 0) === 0) throw new Error(`automation ${automation.id} requires a Superagent with a Feishu source`);
814
+ const endpoint = manifest.endpoints.find(({ id }) => id === automation.delivery.endpointId);
815
+ if (!endpoint) throw new Error(`automation ${automation.id} references unknown delivery endpoint: ${automation.delivery.endpointId}`);
816
+ if (automation.enabled && !endpoint.enabled) throw new Error(`automation ${automation.id} delivery endpoint must be enabled`);
817
+ }
818
+ const defaultAgent = agentById.get(manifest.defaultAgentId);
819
+ if (!defaultAgent) throw new Error(`default agent does not exist: ${manifest.defaultAgentId}`);
820
+ const defaultEndpoint = manifest.endpoints.find(({ id }) => id === manifest.defaultEndpointId);
821
+ if (!defaultEndpoint) throw new Error(`default endpoint does not exist: ${manifest.defaultEndpointId}`);
822
+ if (defaultEndpoint.agentId !== defaultAgent.agentId) throw new Error("default endpoint is not bound to the default agent");
823
+ if (!defaultEndpoint.enabled) throw new Error("default endpoint must be enabled");
824
+ if (manifest.backgroundSessions) validateBackgroundSessions(manifest.backgroundSessions);
493
825
  }
494
826
  //#endregion
495
827
  //#region src/deployment/application/services/deployment-resolution.ts
@@ -508,7 +840,7 @@ function resolveRivusDeployment(input) {
508
840
  const pluginLoader = yield* RivusPluginLoader;
509
841
  yield* Effect.try({
510
842
  try: () => validateRivusDeploymentManifest(input.manifest),
511
- catch: toDeploymentFailure
843
+ catch: toError
512
844
  });
513
845
  const catalog = input.agentCatalog.createPluginCatalog();
514
846
  const pluginStatuses = [];
@@ -524,10 +856,10 @@ function resolveRivusDeployment(input) {
524
856
  catalog.registerPlugin(plugin);
525
857
  return plugin;
526
858
  },
527
- catch: toDeploymentFailure
859
+ catch: toError
528
860
  })), Effect.result);
529
861
  if (Result.isFailure(loaded)) {
530
- const message = formatDeploymentFailure(loaded.failure);
862
+ const message = errorMessage(loaded.failure);
531
863
  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
864
  const status = Object.freeze({
533
865
  error: message,
@@ -578,7 +910,7 @@ function resolveRivusDeployment(input) {
578
910
  })
579
911
  }) : baseDefinition;
580
912
  },
581
- catch: toDeploymentFailure
913
+ catch: toError
582
914
  }).pipe(Effect.result);
583
915
  if (Result.isFailure(resolved)) {
584
916
  const declaration = input.manifest.plugins.find(({ id }) => id === agent.pluginId);
@@ -627,7 +959,7 @@ function resolveRivusDeployment(input) {
627
959
  }),
628
960
  template
629
961
  }),
630
- catch: toDeploymentFailure
962
+ catch: toError
631
963
  });
632
964
  automationDefinitions.push(definition);
633
965
  }
@@ -725,7 +1057,7 @@ function prepareDeployment(input) {
725
1057
  const resolved = yield* projectSpaceResolver.resolve({
726
1058
  declaration,
727
1059
  deploymentRoot: input.deploymentRoot
728
- }).pipe(Effect.mapError(toDeploymentFailure));
1060
+ }).pipe(Effect.mapError(toError));
729
1061
  projectSpaces.set(resolved.id, resolved);
730
1062
  }
731
1063
  const definitions = yield* Effect.try({
@@ -733,14 +1065,14 @@ function prepareDeployment(input) {
733
1065
  const resolved = bindResolvedProjectSpaceRevision(definition, projectSpaces);
734
1066
  return [resolved.agentId, resolved];
735
1067
  })),
736
- catch: toDeploymentFailure
1068
+ catch: toError
737
1069
  });
738
1070
  const automationDefinitions = yield* Effect.try({
739
1071
  try: () => new Map(deployment.automationDefinitions.map((definition) => [definition.id, Object.freeze({
740
1072
  ...definition,
741
1073
  runtimeDefinition: bindResolvedProjectSpaceRevision(definition.runtimeDefinition, projectSpaces)
742
1074
  })])),
743
- catch: toDeploymentFailure
1075
+ catch: toError
744
1076
  });
745
1077
  const effectiveDeployment = Object.freeze({
746
1078
  ...deployment,
@@ -761,7 +1093,7 @@ function prepareDeployment(input) {
761
1093
  if (agent.status !== "enabled" || !agent.definition) continue;
762
1094
  const narrowed = yield* Effect.try({
763
1095
  try: () => narrowBackgroundSessionDefinition(definitions.get(agent.agentId), input.digest),
764
- catch: toDeploymentFailure
1096
+ catch: toError
765
1097
  });
766
1098
  backgroundDefinitions.set(agent.agentId, narrowed);
767
1099
  }
@@ -805,7 +1137,7 @@ function prepareDeployment(input) {
805
1137
  ...projectSpace ? { projectSpace } : {}
806
1138
  });
807
1139
  } }
808
- }).pipe(Effect.mapError(toDeploymentFailure));
1140
+ }).pipe(Effect.mapError(toError));
809
1141
  return {
810
1142
  automationSlots,
811
1143
  ...backgroundSessionSlot ? { backgroundSessionSlot } : {},
@@ -819,6 +1151,7 @@ function prepareDeployment(input) {
819
1151
  }
820
1152
  //#endregion
821
1153
  //#region src/deployment/application/use-cases/deployment-control.ts
1154
+ /** @internal */
822
1155
  var RivusDeploymentReadinessError = class extends Error {
823
1156
  endpointIds;
824
1157
  name = "RivusDeploymentReadinessError";
@@ -860,11 +1193,12 @@ function startSlot(slot, available, label, create) {
860
1193
  yield* slot.adapter.start();
861
1194
  if (!(yield* Effect.try({
862
1195
  try: () => slot.adapter.running(),
863
- catch: toDeploymentFailure
1196
+ catch: toError
864
1197
  }))) return yield* Effect.fail(/* @__PURE__ */ new Error(`${label} start completed but the adapter is not running`));
865
1198
  }).pipe(Effect.exit);
866
1199
  if (Exit.isFailure(started)) {
867
- slot.error = formatDeploymentFailure(Cause.squash(started.cause));
1200
+ const error = Cause.squash(started.cause);
1201
+ slot.error = errorMessage(error);
868
1202
  slot.lifecycle = transitionDeploymentComponentLifecycle(slot.lifecycle, "degraded");
869
1203
  return true;
870
1204
  }
@@ -886,13 +1220,13 @@ function stopSlots(slots, errors) {
886
1220
  yield* slot.adapter.stop();
887
1221
  if (yield* Effect.try({
888
1222
  try: () => slot.adapter.running(),
889
- catch: toDeploymentFailure
1223
+ catch: toError
890
1224
  })) return yield* Effect.fail(/* @__PURE__ */ new Error("component stop completed but the adapter is still running"));
891
1225
  }).pipe(Effect.exit);
892
1226
  if (Exit.isFailure(stopped)) {
893
1227
  const error = Cause.squash(stopped.cause);
894
1228
  errors.push(error);
895
- slot.error = formatDeploymentFailure(error);
1229
+ slot.error = errorMessage(error);
896
1230
  slot.lifecycle = transitionDeploymentComponentLifecycle(slot.lifecycle, "cleanup-required");
897
1231
  continue;
898
1232
  }
@@ -907,7 +1241,7 @@ function observeRunning(slot) {
907
1241
  return { running: slot.adapter.running() };
908
1242
  } catch (error) {
909
1243
  return {
910
- error: formatDeploymentFailure(error),
1244
+ error: errorMessage(error),
911
1245
  running: false
912
1246
  };
913
1247
  }
@@ -927,7 +1261,7 @@ function backgroundStatus(slot) {
927
1261
  try {
928
1262
  supervisor = slot.adapter?.status?.();
929
1263
  } catch (error) {
930
- slot.error = formatDeploymentFailure(error);
1264
+ slot.error = errorMessage(error);
931
1265
  }
932
1266
  return Object.freeze({
933
1267
  ...componentStatus(slot),
@@ -944,6 +1278,9 @@ function isSlotReady(slot) {
944
1278
  }
945
1279
  function makeDeploymentControl(input) {
946
1280
  const endpointById = new Map(input.endpointSlots.map((slot) => [slot.definition.id, slot]));
1281
+ const sharedIds = new Set(input.deployment.manifest.superagent?.endpointIds);
1282
+ const sharedEndpoints = input.endpointSlots.filter((slot) => sharedIds.has(slot.definition.id));
1283
+ const otherEndpoints = input.endpointSlots.filter((slot) => !sharedIds.has(slot.definition.id));
947
1284
  const allSlots = [
948
1285
  ...input.endpointSlots,
949
1286
  ...input.automationSlots,
@@ -974,6 +1311,27 @@ function makeDeploymentControl(input) {
974
1311
  if (!canRunIntake() || slot.lifecycle !== "running" || !observed.running) return Effect.fail(new RivusDeploymentDaemonLifecycleError(`endpoint ${endpointId} cannot accept intake while Deployment Control is ${lifecycle} and endpoint is ${slot.lifecycle}`));
975
1312
  return input.host.handleEndpoint(endpointId, request);
976
1313
  });
1314
+ const startEndpoints = (slots) => Effect.gen(function* () {
1315
+ let failed = false;
1316
+ for (const slot of slots) failed = (yield* startSlot(slot, slot.agentEnabled, `endpoint ${slot.definition.id}`, () => Effect.gen(function* () {
1317
+ const instance = yield* input.host.resolveEndpoint(slot.definition.id);
1318
+ const agentDefinition = input.definitions.get(slot.definition.agentId);
1319
+ const projectSpace = agentDefinition?.projectSpaceId ? input.projectSpaces.get(agentDefinition.projectSpaceId) : void 0;
1320
+ return yield* input.endpointFactory.create({
1321
+ agentId: slot.definition.agentId,
1322
+ cancel: (request) => input.host.cancelEndpoint(slot.definition.id, request),
1323
+ definition: slot.definition,
1324
+ endpointId: slot.definition.id,
1325
+ handle: (request) => handleEndpoint(slot.definition.id, request),
1326
+ instanceId: instance.instanceId,
1327
+ ...agentDefinition ? { runtimeDefinition: agentDefinition } : {},
1328
+ ...projectSpace ? { projectSpace } : {},
1329
+ ...agentDefinition?.projectSpaceId ? { projectSpaceId: agentDefinition.projectSpaceId } : {},
1330
+ steer: (request) => input.host.steerEndpoint(slot.definition.id, request)
1331
+ });
1332
+ }))) || failed;
1333
+ return failed;
1334
+ });
977
1335
  const isReady = () => allSlots.every((slot) => isSlotReady(slot));
978
1336
  const readinessFailure = () => {
979
1337
  const endpointIds = input.endpointSlots.filter((slot) => slot.definition.enabled && slot.definition.required && !isSlotReady(slot)).map((slot) => slot.definition.id);
@@ -1022,23 +1380,14 @@ function makeDeploymentControl(input) {
1022
1380
  lifecycle = transitionDeploymentControlLifecycle(lifecycle, "starting");
1023
1381
  return Effect.gen(function* () {
1024
1382
  let degraded = input.deployment.plugins.some(({ status: pluginStatus }) => pluginStatus === "failed");
1025
- for (const slot of input.endpointSlots) degraded = (yield* startSlot(slot, slot.agentEnabled, `endpoint ${slot.definition.id}`, () => Effect.gen(function* () {
1026
- const instance = yield* input.host.resolveEndpoint(slot.definition.id);
1027
- const agentDefinition = input.definitions.get(slot.definition.agentId);
1028
- const projectSpace = agentDefinition?.projectSpaceId ? input.projectSpaces.get(agentDefinition.projectSpaceId) : void 0;
1029
- return yield* input.endpointFactory.create({
1030
- agentId: slot.definition.agentId,
1031
- cancel: (request) => input.host.cancelEndpoint(slot.definition.id, request),
1032
- definition: slot.definition,
1033
- endpointId: slot.definition.id,
1034
- handle: (request) => handleEndpoint(slot.definition.id, request),
1035
- instanceId: instance.instanceId,
1036
- ...agentDefinition ? { runtimeDefinition: agentDefinition } : {},
1037
- ...projectSpace ? { projectSpace } : {},
1038
- ...agentDefinition?.projectSpaceId ? { projectSpaceId: agentDefinition.projectSpaceId } : {},
1039
- steer: (request) => input.host.steerEndpoint(slot.definition.id, request)
1040
- });
1041
- }))) || degraded;
1383
+ degraded = (yield* startEndpoints(otherEndpoints)) || degraded;
1384
+ let superagentFailure;
1385
+ if (input.superagent !== void 0) {
1386
+ const started = yield* Effect.exit(input.superagent.start());
1387
+ if (Exit.isFailure(started)) superagentFailure = Cause.squash(started.cause);
1388
+ degraded = Exit.isFailure(started) || started.value || degraded;
1389
+ }
1390
+ degraded = (yield* startEndpoints(sharedEndpoints)) || degraded;
1042
1391
  for (const slot of input.automationSlots) {
1043
1392
  const resolvedDefinition = slot.resolvedDefinition;
1044
1393
  const deliverySlot = endpointById.get(slot.definition.delivery.endpointId);
@@ -1086,7 +1435,7 @@ function makeDeploymentControl(input) {
1086
1435
  }))) || degraded;
1087
1436
  }
1088
1437
  lifecycle = transitionDeploymentControlLifecycle(lifecycle, degraded ? "degraded" : "running");
1089
- const failure = readinessFailure();
1438
+ const failure = superagentFailure ?? readinessFailure();
1090
1439
  if (failure) return yield* Effect.fail(failure);
1091
1440
  });
1092
1441
  }),
@@ -1096,9 +1445,14 @@ function makeDeploymentControl(input) {
1096
1445
  lifecycle = transitionDeploymentControlLifecycle(lifecycle, "stopping");
1097
1446
  return Effect.gen(function* () {
1098
1447
  const errors = [];
1099
- yield* stopSlots(input.automationSlots, errors);
1100
1448
  if (input.backgroundSessionSlot) yield* stopSlots([input.backgroundSessionSlot], errors);
1101
- yield* stopSlots(input.endpointSlots, errors);
1449
+ yield* stopSlots(input.automationSlots, errors);
1450
+ yield* stopSlots(sharedEndpoints, errors);
1451
+ if (input.superagent !== void 0) {
1452
+ const result = yield* Effect.exit(input.superagent.stop());
1453
+ if (Exit.isFailure(result)) errors.push(Cause.squash(result.cause));
1454
+ }
1455
+ yield* stopSlots(otherEndpoints, errors);
1102
1456
  const hostExit = yield* Effect.exit(input.host.dispose());
1103
1457
  if (Exit.isFailure(hostExit)) errors.push(Cause.squash(hostExit.cause));
1104
1458
  lifecycle = transitionDeploymentControlLifecycle(lifecycle, errors.length === 0 ? "stopped" : "cleanup-required");
@@ -1112,6 +1466,7 @@ function createRivusDeploymentControl(input) {
1112
1466
  return Effect.gen(function* () {
1113
1467
  return makeDeploymentControl({
1114
1468
  ...yield* prepareDeployment(input),
1469
+ ...input.superagent === void 0 ? {} : { superagent: input.superagent },
1115
1470
  ...input.automationFactory ? { automationFactory: input.automationFactory } : {},
1116
1471
  ...input.backgroundSessionFactory ? { backgroundSessionFactory: input.backgroundSessionFactory } : {},
1117
1472
  endpointFactory: input.endpointFactory
@@ -1119,23 +1474,87 @@ function createRivusDeploymentControl(input) {
1119
1474
  });
1120
1475
  }
1121
1476
  //#endregion
1477
+ //#region src/home/infra/adapters/doctor/rivus-home-doctor.ts
1478
+ function checkNodeRuntime(version) {
1479
+ const range = "^24.11.0 || ^26.13.1";
1480
+ const supported = satisfies(version, range);
1481
+ return {
1482
+ name: "node",
1483
+ status: supported ? "pass" : "fail",
1484
+ message: supported ? `Node.js ${version} satisfies ${range}` : `Node.js ${range} is required; current version is ${version}`
1485
+ };
1486
+ }
1487
+ function checkWorkspace(home, findMissingWorkspacePaths) {
1488
+ return findMissingWorkspacePaths(home).pipe(Effect.map((missing) => missing.length === 0 ? {
1489
+ message: "Workspace instructions, Memory, Skills, and work directories are present",
1490
+ name: "workspace",
1491
+ status: "pass"
1492
+ } : {
1493
+ message: `Workspace paths are missing: ${missing.join(", ")}`,
1494
+ name: "workspace",
1495
+ status: "fail"
1496
+ }));
1497
+ }
1498
+ function blockedCheck(name, owner) {
1499
+ return {
1500
+ message: `${owner} cannot be checked until config.json is valid`,
1501
+ name,
1502
+ status: "fail"
1503
+ };
1504
+ }
1505
+ function report(directory, checks) {
1506
+ return {
1507
+ checks,
1508
+ directory,
1509
+ ready: checks.every(({ status }) => status === "pass")
1510
+ };
1511
+ }
1512
+ function diagnoseRivusHome(input, options) {
1513
+ return Effect.gen(function* () {
1514
+ const checks = [checkNodeRuntime(input.nodeVersion)];
1515
+ const loaded = yield* options.load(input.directory).pipe(Effect.result);
1516
+ if (Result.isFailure(loaded)) {
1517
+ checks.push({
1518
+ message: `Rivus Home is invalid: ${loaded.failure.message}`,
1519
+ name: "home",
1520
+ status: "fail"
1521
+ }, blockedCheck("workspace", "Workspace"), blockedCheck("manifest", "manifest"), blockedCheck("modules", "modules"), blockedCheck("credentials", "credentials"));
1522
+ return report(input.directory, checks);
1523
+ }
1524
+ const home = loaded.success;
1525
+ checks.push({
1526
+ message: "config.json is valid and contained in Rivus Home",
1527
+ name: "home",
1528
+ status: "pass"
1529
+ });
1530
+ checks.push(yield* checkWorkspace(home, options.findMissingWorkspacePaths));
1531
+ const deployment = yield* options.deploymentInspector.inspect({
1532
+ env: input.env,
1533
+ ...input.envFilePath ? { envFilePath: input.envFilePath } : {},
1534
+ home
1535
+ });
1536
+ checks.push(deployment.manifest, deployment.modules, deployment.credentials);
1537
+ return report(input.directory, checks);
1538
+ });
1539
+ }
1540
+ //#endregion
1122
1541
  //#region src/home/infra/adapters/config/rivus-home-config.ts
1123
1542
  /**
1124
1543
  * Config fields are read tolerantly (authoring guide, Validation): a field whose value has the wrong type is
1125
1544
  * treated as absent, so the owner-specific error texts below keep firing in their
1126
1545
  * original order.
1127
1546
  */
1128
- function tolerant$1(schema) {
1547
+ function tolerant(schema) {
1129
1548
  return Schema.optionalKey(schema.pipe(Schema.catchDecoding(() => Effect.succeed(Option.none()))));
1130
1549
  }
1131
1550
  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)
1551
+ bootstrap: tolerant(Schema.String),
1552
+ envFile: tolerant(Schema.String),
1553
+ logs: tolerant(Schema.String),
1554
+ manifest: tolerant(Schema.String),
1555
+ state: tolerant(Schema.String),
1556
+ version: tolerant(Schema.Literal(1)),
1557
+ workspace: tolerant(Schema.String)
1139
1558
  });
1140
1559
  const decodeRivusHomeConfig = Schema.decodeUnknownOption(rivusHomeConfigSchema);
1141
1560
  function resolveHomePath(directory, value, owner) {
@@ -1173,9 +1592,6 @@ function parseRivusHomeConfig(value) {
1173
1592
  workspace: relativePath(config.workspace, "workspace")
1174
1593
  };
1175
1594
  }
1176
- function asError$1(error) {
1177
- return error instanceof Error ? error : new Error(String(error));
1178
- }
1179
1595
  /** Loads and validates the operator-owned Home config file. */
1180
1596
  function loadRivusHome(directoryPath) {
1181
1597
  const directory = resolve(directoryPath);
@@ -1195,71 +1611,7 @@ function loadRivusHome(directoryPath) {
1195
1611
  workspaceDirectory: resolveHomePath(directory, config.workspace, "workspace")
1196
1612
  };
1197
1613
  },
1198
- catch: asError$1
1199
- });
1200
- }
1201
- //#endregion
1202
- //#region src/home/infra/adapters/doctor/rivus-home-doctor.ts
1203
- function checkNodeRuntime(version) {
1204
- const range = "^24.11.0 || ^26.13.1";
1205
- const supported = satisfies(version, range);
1206
- return {
1207
- name: "node",
1208
- status: supported ? "pass" : "fail",
1209
- message: supported ? `Node.js ${version} satisfies ${range}` : `Node.js ${range} is required; current version is ${version}`
1210
- };
1211
- }
1212
- function checkWorkspace(home, findMissingWorkspacePaths) {
1213
- return findMissingWorkspacePaths(home).pipe(Effect.map((missing) => missing.length === 0 ? {
1214
- message: "Workspace instructions, Memory, Skills, and work directories are present",
1215
- name: "workspace",
1216
- status: "pass"
1217
- } : {
1218
- message: `Workspace paths are missing: ${missing.join(", ")}`,
1219
- name: "workspace",
1220
- status: "fail"
1221
- }));
1222
- }
1223
- function blockedCheck(name, owner) {
1224
- return {
1225
- message: `${owner} cannot be checked until config.json is valid`,
1226
- name,
1227
- status: "fail"
1228
- };
1229
- }
1230
- function report(directory, checks) {
1231
- return {
1232
- checks,
1233
- directory,
1234
- ready: checks.every(({ status }) => status === "pass")
1235
- };
1236
- }
1237
- function diagnoseRivusHome(input, options) {
1238
- return Effect.gen(function* () {
1239
- const checks = [checkNodeRuntime(input.nodeVersion)];
1240
- const loaded = yield* options.load(input.directory).pipe(Effect.result);
1241
- if (Result.isFailure(loaded)) {
1242
- checks.push({
1243
- message: `Rivus Home is invalid: ${loaded.failure.message}`,
1244
- name: "home",
1245
- status: "fail"
1246
- }, blockedCheck("workspace", "Workspace"), blockedCheck("manifest", "manifest"), blockedCheck("modules", "modules"), blockedCheck("credentials", "credentials"));
1247
- return report(input.directory, checks);
1248
- }
1249
- const home = loaded.success;
1250
- checks.push({
1251
- message: "config.json is valid and contained in Rivus Home",
1252
- name: "home",
1253
- status: "pass"
1254
- });
1255
- checks.push(yield* checkWorkspace(home, options.findMissingWorkspacePaths));
1256
- const deployment = yield* options.deploymentInspector.inspect({
1257
- env: input.env,
1258
- ...input.envFilePath ? { envFilePath: input.envFilePath } : {},
1259
- home
1260
- });
1261
- checks.push(deployment.manifest, deployment.modules, deployment.credentials);
1262
- return report(input.directory, checks);
1614
+ catch: toError
1263
1615
  });
1264
1616
  }
1265
1617
  //#endregion
@@ -1411,7 +1763,7 @@ function initializeRivusHome(directoryPath) {
1411
1763
  files: paths
1412
1764
  };
1413
1765
  },
1414
- catch: (error) => error instanceof Error ? error : new Error(String(error))
1766
+ catch: toError
1415
1767
  });
1416
1768
  }
1417
1769
  //#endregion
@@ -1436,7 +1788,7 @@ function findMissingRivusHomeWorkspacePaths(home) {
1436
1788
  }
1437
1789
  return missing;
1438
1790
  },
1439
- catch: (error) => error instanceof Error ? error : new Error(String(error))
1791
+ catch: toError
1440
1792
  });
1441
1793
  }
1442
1794
  //#endregion
@@ -1453,116 +1805,6 @@ function createNodeRivusHome(options) {
1453
1805
  };
1454
1806
  }
1455
1807
  //#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
1808
  //#region src/home/infra/adapters/project/rivus-project-initializer.ts
1567
1809
  const TEMPLATE_FILES = Object.freeze({
1568
1810
  "current-weather.mjs": "current-weather.mjs",
@@ -1621,20 +1863,17 @@ async function assertSafeProjectAncestors(directory, paths) {
1621
1863
  }
1622
1864
  }
1623
1865
  }
1624
- function asError(error) {
1625
- return error instanceof Error ? error : new Error(String(error));
1626
- }
1627
1866
  async function rollbackCreatedPaths(files, directories) {
1628
1867
  const errors = [];
1629
1868
  for (const path of files.reverse()) try {
1630
1869
  await unlink(path);
1631
1870
  } catch (error) {
1632
- if (!isNodeErrorWithCode(error, "ENOENT")) errors.push(asError(error));
1871
+ if (!isNodeErrorWithCode(error, "ENOENT")) errors.push(toError(error));
1633
1872
  }
1634
1873
  for (const path of directories.reverse()) try {
1635
1874
  await rmdir(path);
1636
1875
  } catch (error) {
1637
- if (!isNodeErrorWithCode(error, "ENOENT") && !isNodeErrorWithCode(error, "ENOTEMPTY")) errors.push(asError(error));
1876
+ if (!isNodeErrorWithCode(error, "ENOENT") && !isNodeErrorWithCode(error, "ENOTEMPTY")) errors.push(toError(error));
1638
1877
  }
1639
1878
  return errors;
1640
1879
  }
@@ -1783,108 +2022,20 @@ async function initializeRivusProject(options) {
1783
2022
  };
1784
2023
  }
1785
2024
  //#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
- //#region src/deployment/infra/adapters/inspection/rivus-home-deployment-inspector.ts
1872
- const FEISHU_BOOTSTRAP = "@rivus/gateway/bootstrap/feishu";
1873
- function toError$1(error) {
1874
- return error instanceof Error ? error : new Error(String(error));
1875
- }
1876
- function toEffect(read) {
1877
- return Effect.suspend(() => {
1878
- try {
1879
- const value = read();
1880
- if (Effect.isEffect(value)) return value;
1881
- return Effect.tryPromise({
1882
- try: () => Promise.resolve(value),
1883
- catch: toError$1
1884
- });
1885
- } catch (error) {
1886
- return Effect.fail(toError$1(error));
1887
- }
2025
+ //#region src/deployment/infra/adapters/inspection/rivus-home-deployment-inspector.ts
2026
+ const FEISHU_BOOTSTRAP = "@rivus/gateway/bootstrap/feishu";
2027
+ function toEffect(read) {
2028
+ return Effect.suspend(() => {
2029
+ try {
2030
+ const value = read();
2031
+ if (Effect.isEffect(value)) return value;
2032
+ return Effect.tryPromise({
2033
+ try: () => Promise.resolve(value),
2034
+ catch: toError
2035
+ });
2036
+ } catch (error) {
2037
+ return Effect.fail(toError(error));
2038
+ }
1888
2039
  });
1889
2040
  }
1890
2041
  function defaultResolveModule(specifier, packageManifestPath, homeDirectory) {
@@ -1893,17 +2044,15 @@ function defaultResolveModule(specifier, packageManifestPath, homeDirectory) {
1893
2044
  return Effect.gen(function* () {
1894
2045
  const resolvedRealpath = yield* Effect.tryPromise({
1895
2046
  try: () => realpath(fileURLToPath(import.meta.resolve(specifier))),
1896
- catch: toError$1
2047
+ catch: toError
1897
2048
  });
1898
- return yield* validateTrustedModulePath(homeLocal ? yield* Effect.tryPromise({
2049
+ const trustedRoot = homeLocal ? yield* Effect.tryPromise({
1899
2050
  try: () => realpath(homeDirectory),
1900
- catch: toError$1
1901
- }) : yield* findTrustedPackageRoot(packageManifestPath), resolvedRealpath, `module ${specifier}`);
2051
+ catch: toError
2052
+ }) : yield* findTrustedPackageRoot(packageManifestPath);
2053
+ return yield* validateTrustedModulePath(trustedRoot, resolvedRealpath, `module ${specifier}`);
1902
2054
  });
1903
2055
  }
1904
- function formatError(error) {
1905
- return error instanceof Error ? error.message : String(error);
1906
- }
1907
2056
  function checkManifest$1(home) {
1908
2057
  return loadRivusDeploymentManifest(home.manifestPath).pipe(Effect.map((manifest) => {
1909
2058
  validateRivusDeploymentManifest(manifest);
@@ -1916,7 +2065,7 @@ function checkManifest$1(home) {
1916
2065
  manifest
1917
2066
  };
1918
2067
  }), Effect.catch((error) => Effect.succeed({ check: {
1919
- message: `deployment manifest is invalid: ${formatError(error)}`,
2068
+ message: `deployment manifest is invalid: ${errorMessage(error)}`,
1920
2069
  name: "manifest",
1921
2070
  status: "fail"
1922
2071
  } })));
@@ -1932,7 +2081,7 @@ function checkModules(home, manifest, resolveModule, resolvePluginModule) {
1932
2081
  const missing = [];
1933
2082
  for (const specifier of specifiers) {
1934
2083
  const result = yield* toEffect(() => resolveModule(specifier)).pipe(Effect.result);
1935
- if (result._tag === "Failure") missing.push(`${specifier} (${formatError(result.failure)})`);
2084
+ if (result._tag === "Failure") missing.push(`${specifier} (${errorMessage(result.failure)})`);
1936
2085
  }
1937
2086
  for (const plugin of manifest.plugins) {
1938
2087
  const result = yield* toEffect(() => resolvePluginModule({
@@ -1940,7 +2089,7 @@ function checkModules(home, manifest, resolveModule, resolvePluginModule) {
1940
2089
  module: plugin.module,
1941
2090
  pluginId: plugin.id
1942
2091
  })).pipe(Effect.result);
1943
- if (result._tag === "Failure") missing.push(`${plugin.module} (${formatError(result.failure)})`);
2092
+ if (result._tag === "Failure") missing.push(`${plugin.module} (${errorMessage(result.failure)})`);
1944
2093
  }
1945
2094
  return missing.length === 0 ? {
1946
2095
  message: "Bootstrap, Plugin, runtime, and Feishu modules resolve; run check-config --load-plugins to import them",
@@ -1953,7 +2102,7 @@ function checkModules(home, manifest, resolveModule, resolvePluginModule) {
1953
2102
  };
1954
2103
  });
1955
2104
  }
1956
- function checkCredentials$1(home, manifest, env, envFilePath, isModelManagementEnabled) {
2105
+ function checkCredentials$1(home, manifest, env, envFilePath, isModelManagementEnabled, checkSuperagents, nodeVersion, packageManifestPath) {
1957
2106
  if (!manifest) return Effect.succeed({
1958
2107
  message: "credentials cannot be checked until manifest is valid",
1959
2108
  name: "credentials",
@@ -1962,7 +2111,11 @@ function checkCredentials$1(home, manifest, env, envFilePath, isModelManagementE
1962
2111
  return Effect.tryPromise({
1963
2112
  try: async () => {
1964
2113
  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);
2114
+ await checkSuperagents?.(manifest, merged, nodeVersion, {
2115
+ deploymentRoot: home.directory,
2116
+ packageManifestPath
2117
+ });
2118
+ for (const endpoint of [...manifest.endpoints, ...manifest.superagentEndpoints ?? []].filter(({ enabled }) => enabled)) resolveFeishuEndpointCredentials(endpoint.credentialRef, merged);
1966
2119
  for (const agent of manifest.agents) if (agent.runtime) await resolveAcpRuntimeEnvironment(agent.runtime, merged);
1967
2120
  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
2121
  return {
@@ -1971,9 +2124,9 @@ function checkCredentials$1(home, manifest, env, envFilePath, isModelManagementE
1971
2124
  status: "pass"
1972
2125
  };
1973
2126
  },
1974
- catch: toError$1
2127
+ catch: toError
1975
2128
  }).pipe(Effect.catch((error) => Effect.succeed({
1976
- message: `deployment environment is incomplete: ${formatError(error)}`,
2129
+ message: `deployment environment is incomplete: ${errorMessage(error)}`,
1977
2130
  name: "credentials",
1978
2131
  status: "fail"
1979
2132
  })));
@@ -1982,7 +2135,7 @@ function createRivusHomeDeploymentInspector(options) {
1982
2135
  const resolvePluginModule = options.resolvePluginModule ?? ((request) => resolveNodeRivusPluginModulePath(request, options.packageManifestPath ? { packageManifestPath: options.packageManifestPath } : {}));
1983
2136
  return { inspect: (input) => Effect.gen(function* () {
1984
2137
  const manifestResult = yield* checkManifest$1(input.home);
1985
- const credentials = yield* checkCredentials$1(input.home, manifestResult.manifest, input.env, input.envFilePath, options.isModelManagementEnabled);
2138
+ const credentials = yield* checkCredentials$1(input.home, manifestResult.manifest, input.env, input.envFilePath, options.isModelManagementEnabled, options.checkSuperagents, process.versions.node, options.packageManifestPath);
1986
2139
  const modules = yield* checkModules(input.home, manifestResult.manifest, options.resolveModule ?? ((specifier) => defaultResolveModule(specifier, options.packageManifestPath, input.home.directory)), resolvePluginModule);
1987
2140
  return {
1988
2141
  credentials,
@@ -2011,8 +2164,7 @@ function checkManifest(directory) {
2011
2164
  for (const plugin of manifest.plugins) {
2012
2165
  const result = yield* resolveNodeRivusPluginModulePath({
2013
2166
  deploymentRoot: directory,
2014
- module: plugin.module,
2015
- pluginId: plugin.id
2167
+ module: plugin.module
2016
2168
  }).pipe(Effect.result);
2017
2169
  if (Result.isFailure(result)) missingModules.push(plugin.module);
2018
2170
  }
@@ -2035,7 +2187,7 @@ function checkManifest(directory) {
2035
2187
  status: "fail"
2036
2188
  } })));
2037
2189
  }
2038
- async function checkCredentials(manifest, envFilePath, env) {
2190
+ async function checkCredentials(directory, manifest, envFilePath, env, checkSuperagents, nodeVersion) {
2039
2191
  let mergedEnv;
2040
2192
  try {
2041
2193
  mergedEnv = await loadMergedLocalEnvFile(envFilePath, env);
@@ -2052,7 +2204,11 @@ async function checkCredentials(manifest, envFilePath, env) {
2052
2204
  status: "fail"
2053
2205
  };
2054
2206
  try {
2055
- for (const endpoint of manifest.endpoints.filter(({ enabled }) => enabled)) resolveFeishuEndpointCredentials(endpoint.credentialRef, mergedEnv);
2207
+ await checkSuperagents?.(manifest, mergedEnv, nodeVersion, {
2208
+ deploymentRoot: directory,
2209
+ packageManifestPath: void 0
2210
+ });
2211
+ for (const endpoint of [...manifest.endpoints, ...manifest.superagentEndpoints ?? []].filter(({ enabled }) => enabled)) resolveFeishuEndpointCredentials(endpoint.credentialRef, mergedEnv);
2056
2212
  return {
2057
2213
  message: "enabled Endpoint credential references resolve",
2058
2214
  name: "credentials",
@@ -2102,9 +2258,6 @@ async function checkDependencies(directory) {
2102
2258
  status: "fail"
2103
2259
  };
2104
2260
  }
2105
- function toError(error) {
2106
- return error instanceof Error ? error : new Error(String(error));
2107
- }
2108
2261
  function diagnoseRivusProject(options) {
2109
2262
  return Effect.gen(function* () {
2110
2263
  const directory = resolve(options.directory);
@@ -2121,7 +2274,7 @@ function diagnoseRivusProject(options) {
2121
2274
  checks.push(manifestResult.check);
2122
2275
  const envFilePath = resolve(directory, options.envFilePath ?? ".env.local");
2123
2276
  checks.push(yield* Effect.tryPromise({
2124
- try: () => checkCredentials(manifestResult.manifest, envFilePath, options.env),
2277
+ try: () => checkCredentials(directory, manifestResult.manifest, envFilePath, options.env, options.checkSuperagents, options.nodeVersion),
2125
2278
  catch: toError
2126
2279
  }));
2127
2280
  return Object.freeze({
@@ -2209,7 +2362,7 @@ function nodeRivusPluginLoader(options = {}) {
2209
2362
  /** Resolves Project Space directories on the local filesystem. */
2210
2363
  const NodeRivusProjectSpaceResolverLive = Layer.succeed(RivusProjectSpaceResolver, { resolve: (input) => Effect.tryPromise({
2211
2364
  try: () => resolveRivusProjectSpace(input),
2212
- catch: toDeploymentFailure
2365
+ catch: toError
2213
2366
  }) });
2214
2367
  //#endregion
2215
2368
  //#region src/model-management/infra/adapters/cli/rivus-model-management-socket-client.ts
@@ -2280,32 +2433,6 @@ function createRivusModelManagementSocketClient(options) {
2280
2433
  return { execute: (command) => request(options.socketPath, options.env, command, timeoutMs) };
2281
2434
  }
2282
2435
  //#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
2436
  //#region src/bootstrap/cli/release-package-resolution.ts
2310
2437
  /**
2311
2438
  * Packages the running release provides to every module in the process. Rivus classes, services and Effect values
@@ -2320,7 +2447,10 @@ const RELEASE_PACKAGES = [
2320
2447
  ];
2321
2448
  let installed = false;
2322
2449
  let resolvingReleasePackage = false;
2323
- /** Returns the release package a bare specifier names, such as `effect` for `effect/Schema`. */
2450
+ /**
2451
+ * Returns the release package a bare specifier names, such as `effect` for `effect/Schema`.
2452
+ * @internal
2453
+ */
2324
2454
  function releasePackageOf(specifier) {
2325
2455
  return RELEASE_PACKAGES.find((name) => specifier === name || specifier.startsWith(`${name}/`));
2326
2456
  }
@@ -2338,6 +2468,7 @@ function copyOutsideRoots(path, releaseRoots) {
2338
2468
  * recognized by its `node_modules/<name>/` directory, which also matches pnpm's `.pnpm/.../node_modules/<name>/`.
2339
2469
  * A match is rechecked by real path, because `--preserve-symlinks` reports files of the running copy by link paths
2340
2470
  * while the running roots are real paths.
2471
+ * @internal
2341
2472
  */
2342
2473
  function foreignReleasePackageOf(path, releaseRoots) {
2343
2474
  if (!copyOutsideRoots(path, releaseRoots)) return;
@@ -2395,7 +2526,7 @@ function installReleasePackageResolution() {
2395
2526
  registerHooks({ resolve });
2396
2527
  }
2397
2528
  //#endregion
2398
- //#region src/cli/domain/cli/value-objects/rivus-cli-protocol.ts
2529
+ //#region src/cli/lib/home/rivus-cli-protocol.ts
2399
2530
  const RIVUS_CLI_USAGE = `Usage:
2400
2531
  rivus setup [directory]
2401
2532
  rivus upgrade [--json]
@@ -2406,6 +2537,9 @@ const RIVUS_CLI_USAGE = `Usage:
2406
2537
  rivus init [directory]
2407
2538
  rivus doctor [directory] [--env-file <path>]
2408
2539
  rivus model <status|set|rollback> ...
2540
+ rivus superagent <command> ...
2541
+ rivus task <show|report|call> ...
2542
+ rivus worker-bridge --stdio --herdr-root <path> --workspace-root <path> --state-root <path>
2409
2543
  rivus audio <install|status|transcribe> ...
2410
2544
  rivus --bootstrap <module> [--manifest <rivus.config.json>] [options]
2411
2545
 
@@ -2420,12 +2554,16 @@ Commands:
2420
2554
  init Create a standalone local Rivus project without overwriting files
2421
2555
  doctor Check Rivus Home by default, or an explicit standalone project directory
2422
2556
  model Query or change the managed default model through the current Home
2557
+ superagent Inspect or control the Superagent and its tasks
2558
+ task Call tools for the current worker execution
2559
+ worker-bridge
2560
+ Serve a remote Superagent worker bridge over standard input and output
2423
2561
  audio Install, inspect, or run the managed audio transcriber of the current Home
2424
2562
 
2425
2563
  Run rivus --help for the complete daemon option list.
2426
2564
  `;
2427
2565
  function renderRivusCliError(error) {
2428
- return `${error instanceof Error ? error.message : String(error)}\n`;
2566
+ return `${errorMessage(error)}\n`;
2429
2567
  }
2430
2568
  function renderRivusCliUnknownCommand(command) {
2431
2569
  return `Unknown command: ${command}\n\n${RIVUS_CLI_USAGE}`;
@@ -2492,7 +2630,7 @@ function renderRivusProjectInitializationSuccess(directory) {
2492
2630
  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
2631
  }
2494
2632
  //#endregion
2495
- //#region src/cli/domain/cli/value-objects/rivus-recovery-cli-protocol.ts
2633
+ //#region src/cli/lib/recovery/rivus-recovery-cli-protocol.ts
2496
2634
  function consumeArgument(input, argument, next) {
2497
2635
  if (argument === "--recovery-list") {
2498
2636
  input.recoveryList = true;
@@ -2626,7 +2764,7 @@ function createRivusRecoveryCliParser() {
2626
2764
  };
2627
2765
  }
2628
2766
  //#endregion
2629
- //#region src/cli/domain/cli/value-objects/rivus-daemon-arguments.ts
2767
+ //#region src/cli/lib/daemon/rivus-daemon-arguments.ts
2630
2768
  const RIVUS_DAEMON_USAGE = `Usage: rivus --bootstrap <module> --manifest <rivus.config.json>
2631
2769
 
2632
2770
  Starts a local Rivus Agent daemon from an injected bootstrap module.
@@ -2648,21 +2786,6 @@ Options:
2648
2786
  --env-file <path> Load local KEY=value config before reading environment
2649
2787
  --check-config Print redacted local config JSON and exit
2650
2788
  --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
2789
  --session-key <key> Session key for --prompt (default local:<agent-id>:cli)
2667
2790
  --status Print bootstrap status JSON without starting the daemon
2668
2791
  --recovery-list List stopped Automation occurrences, Dead Letters, and Tool operations requiring reconciliation
@@ -2697,16 +2820,8 @@ function parseRivusDaemonArguments(argv) {
2697
2820
  let bootstrap;
2698
2821
  let checkConfig = false;
2699
2822
  let envFilePath;
2700
- let feishuReplayChatId;
2701
- let feishuReplayMessageId;
2702
- let feishuReplayTenantKey;
2703
- let feishuReplayThreadId;
2704
2823
  let manifestPath;
2705
- let piApiKeyFile;
2706
2824
  let prompt;
2707
- let printOpenClawEnvPath;
2708
- let replayFeishuEventPath;
2709
- let replayFeishuText;
2710
2825
  const recoveryCli = createRivusRecoveryCliParser();
2711
2826
  let sessionKey;
2712
2827
  let status = false;
@@ -2785,166 +2900,6 @@ function parseRivusDaemonArguments(argv) {
2785
2900
  index += 1;
2786
2901
  continue;
2787
2902
  }
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
2903
  if (arg?.startsWith("--session-key=")) {
2949
2904
  sessionKey = arg.slice(14);
2950
2905
  if (!sessionKey) return {
@@ -3017,94 +2972,6 @@ function parseRivusDaemonArguments(argv) {
3017
2972
  status,
3018
2973
  checkConfig
3019
2974
  };
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
2975
  if (sessionKey !== void 0 && prompt === void 0) return {
3109
2976
  error: "--session-key requires --prompt",
3110
2977
  help: false,
@@ -3122,7 +2989,7 @@ function parseRivusDaemonArguments(argv) {
3122
2989
  help: false,
3123
2990
  status
3124
2991
  };
3125
- if (checkConfig || prompt !== void 0 || printOpenClawEnvPath !== void 0 || replayFeishuEventPath !== void 0 || replayFeishuText !== void 0 || status) return {
2992
+ if (checkConfig || prompt !== void 0 || status) return {
3126
2993
  error: "Recovery commands cannot be combined with another one-shot command",
3127
2994
  help: false,
3128
2995
  status
@@ -3132,24 +2999,16 @@ function parseRivusDaemonArguments(argv) {
3132
2999
  ...bootstrap ? { bootstrap } : {},
3133
3000
  checkConfig,
3134
3001
  ...envFilePath ? { envFilePath } : {},
3135
- ...feishuReplayChatId !== void 0 ? { feishuReplayChatId } : {},
3136
- ...feishuReplayMessageId !== void 0 ? { feishuReplayMessageId } : {},
3137
- ...feishuReplayTenantKey !== void 0 ? { feishuReplayTenantKey } : {},
3138
- ...feishuReplayThreadId !== void 0 ? { feishuReplayThreadId } : {},
3139
3002
  help: false,
3140
3003
  ...manifestPath ? { manifestPath } : {},
3141
- ...piApiKeyFile !== void 0 ? { piApiKeyFile } : {},
3142
3004
  ...prompt !== void 0 ? { prompt } : {},
3143
- ...printOpenClawEnvPath !== void 0 ? { printOpenClawEnvPath } : {},
3144
- ...replayFeishuEventPath !== void 0 ? { replayFeishuEventPath } : {},
3145
- ...replayFeishuText !== void 0 ? { replayFeishuText } : {},
3146
3005
  ...recovery.command ? { recoveryCommand: recovery.command } : {},
3147
3006
  ...sessionKey ? { sessionKey } : {},
3148
3007
  status
3149
3008
  };
3150
3009
  }
3151
3010
  //#endregion
3152
- //#region src/cli/domain/cli/value-objects/rivus-daemon-output.ts
3011
+ //#region src/cli/lib/daemon/rivus-daemon-output.ts
3153
3012
  const RIVUS_DAEMON_STARTED_MESSAGE = "Rivus Agent daemon started\n";
3154
3013
  function formatRivusDaemonUsageError(error) {
3155
3014
  return `${error}\n\n${RIVUS_DAEMON_USAGE}`;
@@ -3160,194 +3019,18 @@ function formatRivusDaemonJson(value) {
3160
3019
  function formatRivusDaemonLine(text) {
3161
3020
  return `${text}\n`;
3162
3021
  }
3163
- function formatRivusDaemonWarning(warning) {
3164
- return `Warning: ${warning}\n`;
3165
- }
3166
3022
  function formatRivusDaemonCapabilityError(capability) {
3167
3023
  return `${{
3168
3024
  recovery: "Bootstrap daemon does not expose openRecoveryControl()",
3169
3025
  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)"
3026
+ prompt: "Bootstrap daemon does not expose promptText(command)"
3172
3027
  }[capability]}\n`;
3173
3028
  }
3174
3029
  function formatRivusDaemonShutdownFailure(signal, error) {
3175
3030
  return `Failed to stop daemon after ${signal}: ${error}\n`;
3176
3031
  }
3177
3032
  //#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
3033
  //#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
3034
  function toRedactedDeploymentManifest(manifest) {
3352
3035
  return {
3353
3036
  agents: manifest.agents.map(({ agentId, endpointIds, pluginId, profileId, runtime }) => ({
@@ -3393,6 +3076,7 @@ function toRedactedDeploymentManifest(manifest) {
3393
3076
  required,
3394
3077
  sessionNamespace
3395
3078
  })),
3079
+ ...manifest.superagent === void 0 ? {} : { superagent: { endpointIds: manifest.superagent.endpointIds } },
3396
3080
  plugins: manifest.plugins.map(({ id, module, required }) => ({
3397
3081
  id,
3398
3082
  module,
@@ -3426,301 +3110,6 @@ function createLocalCliAgentInvocation(input) {
3426
3110
  tenantKey: "local"
3427
3111
  };
3428
3112
  }
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();
3443
- }
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");
3450
- }
3451
- }
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
- }
3485
- }
3486
- //#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}`;
3498
- }
3499
- function freezeRecord(record) {
3500
- return Object.freeze({
3501
- ...record,
3502
- binding: Object.freeze({ ...record.binding })
3503
- });
3504
- }
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
3538
- });
3539
- records.set(key, record);
3540
- return record;
3541
- },
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()]))
3558
- };
3559
- }
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
3113
  const RIVUS_AUDIO_CLI_USAGE = `Usage:
3725
3114
  rivus audio install [--force] [--json]
3726
3115
  rivus audio status
@@ -3771,42 +3160,65 @@ function renderRivusAudioCliNotInstalled() {
3771
3160
  return "audio transcriber is not installed; run: rivus audio install\n";
3772
3161
  }
3773
3162
  //#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;
3163
+ //#region src/cli/lib/worker-bridge/worker-bridge-cli.ts
3164
+ const absolutePath$1 = Schema.NonEmptyString.check(Schema.isPattern(/^\/\P{Cc}+$/u));
3165
+ const workerBridgeSchema = Schema.Struct({
3166
+ transport: Schema.Literal("stdio"),
3167
+ herdrRoot: absolutePath$1,
3168
+ workspaceRoot: absolutePath$1,
3169
+ stateRoot: absolutePath$1
3170
+ });
3171
+ const decodeBridgeArguments = Schema.decodeUnknownSync(workerBridgeSchema, { onExcessProperty: "error" });
3172
+ const workerBridgeUsage = "Usage: rivus worker-bridge --stdio --herdr-root <path> --workspace-root <path> --state-root <path>\n";
3173
+ /** Parses arguments for `rivus worker-bridge`; requires `--stdio` and three absolute remote paths. */
3174
+ function parseWorkerBridgeArguments(args) {
3175
+ const invalid = (detail) => new Error(detail ? `${detail}\n${workerBridgeUsage.trim()}` : workerBridgeUsage.trim());
3176
+ let stdio = false;
3177
+ const flags = /* @__PURE__ */ new Map([
3178
+ ["--herdr-root", "herdrRoot"],
3179
+ ["--workspace-root", "workspaceRoot"],
3180
+ ["--state-root", "stateRoot"]
3181
+ ]);
3182
+ const paths = {};
3183
+ for (let index = 0; index < args.length; index++) {
3184
+ const flag = args[index];
3185
+ if (flag === "--stdio") {
3186
+ stdio = true;
3187
+ continue;
3188
+ }
3189
+ const field = flags.get(flag);
3190
+ if (field === void 0) throw invalid(`Unknown worker-bridge option: ${flag}`);
3191
+ const value = args[++index];
3192
+ if (!value || value.startsWith("-")) throw invalid(`${flag} requires an absolute path`);
3193
+ paths[field] = value;
3794
3194
  }
3795
- const release = await readRivusAudioInstalledRelease(context.installRoot);
3796
- if (release === void 0) {
3797
- context.stderr.write(renderRivusAudioCliNotInstalled());
3798
- return 3;
3195
+ if (!stdio) throw invalid("worker-bridge requires --stdio");
3196
+ try {
3197
+ return decodeBridgeArguments({
3198
+ transport: "stdio",
3199
+ ...paths
3200
+ });
3201
+ } catch {
3202
+ throw invalid("worker-bridge requires absolute --herdr-root, --workspace-root and --state-root paths");
3799
3203
  }
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;
3204
+ }
3205
+ //#endregion
3206
+ //#region src/cli/lib/upgrade/upgrade-cli-protocol.ts
3207
+ const UPGRADE_USAGE = `Usage: rivus upgrade [--json]
3208
+
3209
+ Upgrade the selected Home's managed service to the latest stable npm release.
3210
+ Prepare and validate before stopping, retain the Home and backup, then verify startup.
3211
+ Rerun the same command to resume an interrupted upgrade at its recorded version.
3212
+ `;
3213
+ function parseUpgradeArguments(argv) {
3214
+ if (argv.includes("--help") || argv.includes("-h")) return { help: true };
3215
+ if (argv.length === 0) return { json: false };
3216
+ if (argv.length === 1 && argv[0] === "--json") return { json: true };
3217
+ return { error: "upgrade accepts only --json; it selects the latest stable release automatically" };
3218
+ }
3219
+ function renderUpgradeResult(result, json) {
3220
+ if (json) return `${JSON.stringify(result)}\n`;
3221
+ 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` : ""}`;
3810
3222
  }
3811
3223
  //#endregion
3812
3224
  //#region src/bootstrap/daemon/process/rivus-daemon-shutdown-controller.ts
@@ -3881,7 +3293,8 @@ async function createRivusDeploymentCliProcess(factory, context) {
3881
3293
  }).pipe(Effect.flatMap((deployment) => createRivusDeploymentControl({
3882
3294
  ...assemblyInput,
3883
3295
  deployment,
3884
- digest: createSha256Digest
3296
+ digest: createSha256Digest,
3297
+ ...adapters.superagent === void 0 ? {} : { superagent: adapters.superagent }
3885
3298
  })), Effect.provide(Layer.mergeAll(nodeRivusPluginLoader(context.pluginPackageManifestPath ? { packageManifestPath: context.pluginPackageManifestPath } : {}), NodeRivusProjectSpaceResolverLive, ProcessRivusAgentHostFactoryLive)));
3886
3299
  })).pipe(Effect.map((control) => {
3887
3300
  let opening;
@@ -3923,12 +3336,22 @@ async function createRivusDeploymentCliProcess(factory, context) {
3923
3336
  if (errors.length > 1) return Effect.fail(new AggregateError(errors, "deployment and adapter cleanup failed"));
3924
3337
  return Effect.void;
3925
3338
  })));
3926
- const process = {
3339
+ return {
3927
3340
  defaultSessionKey: `local:${daemon.deployment.manifest.defaultAgentId}:cli`,
3928
3341
  openRecoveryControl: () => Effect.suspend(() => adaptersDisposed ? Effect.fail(/* @__PURE__ */ new Error("Rivus deployment process cannot open Recovery Control after disposal")) : openRecovery),
3929
3342
  running: () => daemon.running(),
3930
3343
  start: () => startDeployment,
3931
- status: () => Effect.sync(() => daemon.status()),
3344
+ status: () => Effect.gen(function* () {
3345
+ const snapshot = daemon.status();
3346
+ if (daemon.deployment.manifest.superagent === void 0) return snapshot;
3347
+ const path = superagentControlSocketPath(deploymentStateDirectoryFromEnv(context.env));
3348
+ const unavailable = { state: "unavailable" };
3349
+ const superagent = yield* Effect.promise(() => requestLocalJson(path, { operation: "status" }).then((response) => response.ok ? response.value : unavailable, () => unavailable));
3350
+ return {
3351
+ ...snapshot,
3352
+ superagent
3353
+ };
3354
+ }),
3932
3355
  stop: () => stopDeployment,
3933
3356
  promptText: (command) => Effect.suspend(() => {
3934
3357
  if (adaptersDisposed) return Effect.fail(/* @__PURE__ */ new Error("Rivus deployment process cannot restart after its adapters have been disposed"));
@@ -3944,9 +3367,6 @@ async function createRivusDeploymentCliProcess(factory, context) {
3944
3367
  }).pipe(Effect.map(readPromptFinalText));
3945
3368
  }).pipe(Effect.catchCause((cause) => Effect.fail(Cause.squash(cause))))
3946
3369
  };
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
3370
  }
3951
3371
  //#endregion
3952
3372
  //#region src/bootstrap/deployment/check-deployment-plugins.ts
@@ -3980,7 +3400,7 @@ function installCliShutdownController(options, daemon) {
3980
3400
  createRivusDaemonShutdownController({
3981
3401
  daemon,
3982
3402
  onError: (error, signal) => {
3983
- options.stderr.write(formatRivusDaemonShutdownFailure(signal, formatRivusDaemonError(error)));
3403
+ options.stderr.write(formatRivusDaemonShutdownFailure(signal, errorMessage(error)));
3984
3404
  options.exitAfterSignal?.(1);
3985
3405
  },
3986
3406
  onStopped: () => {
@@ -4004,21 +3424,6 @@ function runStatusOneShot(options, daemon, action) {
4004
3424
  function hasPromptRunner(daemon) {
4005
3425
  return typeof daemon.promptText === "function";
4006
3426
  }
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
- }));
4021
- }
4022
3427
  function hasRecoveryRunner(daemon) {
4023
3428
  return typeof daemon.openRecoveryControl === "function";
4024
3429
  }
@@ -4033,16 +3438,6 @@ function runRivusDaemonCli(options) {
4033
3438
  options.stderr.write(formatRivusDaemonUsageError(parsed.error));
4034
3439
  return 1;
4035
3440
  }
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
3441
  const env = yield* Effect.tryPromise({
4047
3442
  try: async () => {
4048
3443
  const loaded = await loadCliEnv(parsed.envFilePath, options.env);
@@ -4124,22 +3519,6 @@ function runRivusDaemonCli(options) {
4124
3519
  return 0;
4125
3520
  }));
4126
3521
  }
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
3522
  const managedDaemon = {
4144
3523
  ...daemon,
4145
3524
  stop: () => Effect.gen(function* () {
@@ -4163,43 +3542,131 @@ function runRivusDaemonCli(options) {
4163
3542
  options.stdout.write(RIVUS_DAEMON_STARTED_MESSAGE);
4164
3543
  return 0;
4165
3544
  }).pipe(Effect.catch((error) => Effect.sync(() => {
4166
- options.stderr.write(formatRivusDaemonLine(formatRivusDaemonError(error)));
3545
+ options.stderr.write(formatRivusDaemonLine(errorMessage(error)));
4167
3546
  return 1;
4168
3547
  })));
4169
3548
  }
4170
3549
  //#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" };
3550
+ //#region src/bootstrap/cli/cli-support.ts
3551
+ function writeError(options, error) {
3552
+ return Effect.sync(() => {
3553
+ options.stderr.write(renderRivusCliError(error));
3554
+ return 1;
3555
+ });
4183
3556
  }
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` : ""}`;
3557
+ /** Lets an interrupted install stop its child processes and remove its staging directory before the CLI exits. */
3558
+ function abortOnInterruption(signalSource) {
3559
+ const controller = new AbortController();
3560
+ signalSource.on("SIGINT", () => controller.abort());
3561
+ signalSource.on("SIGTERM", () => controller.abort());
3562
+ return controller.signal;
3563
+ }
3564
+ function withOptionalDirectoryArgument(options, command, run) {
3565
+ const parsed = parseRivusDirectoryArguments(options.argv.slice(1));
3566
+ if (parsed.help) return Effect.sync(() => {
3567
+ options.stdout.write(renderRivusDirectoryCommandUsage(command));
3568
+ return 0;
3569
+ });
3570
+ if (parsed.error) return Effect.sync(() => {
3571
+ options.stderr.write(renderRivusDirectoryCommandUsage(command));
3572
+ return 1;
3573
+ });
3574
+ return run(parsed.directory);
3575
+ }
3576
+ function resolveHomeDirectoryEffect(options, argument) {
3577
+ return Effect.try({
3578
+ try: () => {
3579
+ if (argument) return resolve(options.cwd, argument);
3580
+ const configured = options.env.RIVUS_HOME?.trim();
3581
+ if (!configured) return resolve(options.homeDirectory, ".rivus-agent");
3582
+ if (!isAbsolute(configured)) throw new Error("RIVUS_HOME must be an absolute path");
3583
+ return resolve(configured);
3584
+ },
3585
+ catch: toError
3586
+ });
3587
+ }
3588
+ function superagentTransportError(options, error) {
3589
+ if (isNodeErrorWithCode(error, "ENOENT") || isNodeErrorWithCode(error, "ECONNREFUSED")) return Effect.sync(() => {
3590
+ options.stderr.write("Superagent daemon is unavailable\n");
3591
+ return 3;
3592
+ });
3593
+ return writeError(options, error);
4187
3594
  }
4188
3595
  //#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
3596
+ //#region src/bootstrap/cli/audio-command.ts
3597
+ /**
3598
+ * Runs one parsed `rivus audio` command and returns its exit code; installation failures are thrown.
3599
+ * @internal
3600
+ */
3601
+ async function runRivusAudioCliCommand(command, context) {
3602
+ if (command.operation === "install") {
3603
+ const result = await installRivusAudioTranscriber({
3604
+ assetDirectory: context.assetDirectory,
3605
+ env: context.env,
3606
+ force: command.force,
3607
+ installRoot: context.installRoot,
3608
+ nodeExecutable: context.nodeExecutable,
3609
+ platform: context.platform,
3610
+ runProcess: context.runProcess,
3611
+ ...context.signal ? { signal: context.signal } : {}
4199
3612
  });
3613
+ context.stdout.write(renderRivusAudioCliInstallResult(result, command.json));
3614
+ return 0;
4200
3615
  }
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];
3616
+ if (command.operation === "status") {
3617
+ context.stdout.write(renderRivusAudioCliStatus(await readRivusAudioStatus(context.installRoot, context.assetDirectory)));
3618
+ return 0;
3619
+ }
3620
+ const release = await readRivusAudioInstalledRelease(context.installRoot);
3621
+ if (release === void 0) {
3622
+ context.stderr.write(renderRivusAudioCliNotInstalled());
3623
+ return 3;
3624
+ }
3625
+ const exitCode = await runRivusAudioPassthroughProcess({
3626
+ args: [join(release.directory, "transcribe.mjs"), resolve(context.cwd, command.path)],
3627
+ command: context.nodeExecutable,
3628
+ cwd: release.directory,
3629
+ env: context.env,
3630
+ ...context.signal ? { signal: context.signal } : {},
3631
+ stderr: context.stderr,
3632
+ stdout: context.stdout
3633
+ });
3634
+ return exitCode === 0 || exitCode === 1 || exitCode === 2 ? exitCode : 1;
3635
+ }
3636
+ function runAudioCommand(options) {
3637
+ const parsed = parseRivusAudioCliArguments(options.argv.slice(1));
3638
+ if ("help" in parsed) return Effect.sync(() => {
3639
+ options.stdout.write(RIVUS_AUDIO_CLI_USAGE);
3640
+ return 0;
3641
+ });
3642
+ if ("error" in parsed) return Effect.sync(() => {
3643
+ options.stderr.write(renderRivusAudioCliArgumentError(parsed.error));
3644
+ return 1;
3645
+ });
3646
+ return resolveHomeDirectoryEffect(options).pipe(Effect.flatMap((directory) => options.homeApi.load(directory)), Effect.flatMap((home) => Effect.tryPromise({
3647
+ try: () => runRivusAudioCliCommand(parsed, {
3648
+ assetDirectory: gatewayAudioTranscriberAssetDirectory,
3649
+ cwd: options.cwd,
3650
+ env: options.env,
3651
+ installRoot: join(home.stateDirectory, "audio-transcriber"),
3652
+ nodeExecutable: options.nodeExecutable,
3653
+ platform: createNodePlatform(),
3654
+ runProcess: runRivusAudioProcess,
3655
+ signal: abortOnInterruption(options.signalSource),
3656
+ stderr: options.stderr,
3657
+ stdout: options.stdout
3658
+ }),
3659
+ catch: (error) => error
3660
+ })), Effect.catch((error) => writeError(options, error)));
3661
+ }
3662
+ //#endregion
3663
+ //#region src/upgrade/infra/adapters/home-backup.ts
3664
+ const ARCHIVE_NAME = "home.tar.gz";
3665
+ async function retainedArchive(directory) {
3666
+ const path = join(directory, ARCHIVE_NAME);
3667
+ return await lstat(path).catch((error) => {
3668
+ if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
3669
+ }) ? path : void 0;
4203
3670
  }
4204
3671
  async function throwArchiveFailure(phase, archive, result) {
4205
3672
  const diagnostics = join(dirname(archive), `tar-${phase}-failure-${randomUUID()}.json`);
@@ -4219,14 +3686,14 @@ async function throwArchiveFailure(phase, archive, result) {
4219
3686
  throw new Error(`${summary} (tar exit ${result.exitCode}); private diagnostics: ${diagnostics}`);
4220
3687
  }
4221
3688
  async function verifyArchive(archive, input, removeFailedPartial = false) {
4222
- const metadata = await lstat(archive.path);
3689
+ const metadata = await lstat(archive);
4223
3690
  if (!metadata.isFile() || metadata.size === 0) throw new Error("Home backup is missing, empty or not a regular file");
4224
3691
  const listed = await input.run({
4225
3692
  command: "/usr/bin/tar",
4226
3693
  args: [
4227
- ...archive.format === "gzip" ? ["--use-compress-program=/usr/bin/gzip -d"] : [],
3694
+ "--use-compress-program=/usr/bin/gzip -d",
4228
3695
  "-tf",
4229
- archive.path
3696
+ archive
4230
3697
  ],
4231
3698
  cwd: input.home,
4232
3699
  env: input.env,
@@ -4234,8 +3701,8 @@ async function verifyArchive(archive, input, removeFailedPartial = false) {
4234
3701
  discardStdout: true
4235
3702
  });
4236
3703
  if (listed.exitCode !== 0) {
4237
- if (removeFailedPartial) await rm(archive.path, { force: true });
4238
- await throwArchiveFailure("verify", archive.path, listed);
3704
+ if (removeFailedPartial) await rm(archive, { force: true });
3705
+ await throwArchiveFailure("verify", archive, listed);
4239
3706
  }
4240
3707
  }
4241
3708
  async function backUpUpgradeHome(input) {
@@ -4243,27 +3710,20 @@ async function backUpUpgradeHome(input) {
4243
3710
  recursive: true,
4244
3711
  mode: 448
4245
3712
  });
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
- };
3713
+ const archive = join(input.directory, ARCHIVE_NAME);
3714
+ const temporary = `${archive}.partial`;
4254
3715
  try {
4255
- await rm(join(input.directory, "home.tar.partial"), { force: true });
4256
3716
  const existing = await retainedArchive(input.directory);
4257
3717
  if (existing) {
4258
3718
  await verifyArchive(existing, input);
4259
- return existing.path;
3719
+ return existing;
4260
3720
  }
4261
3721
  const created = await input.run({
4262
3722
  command: "/usr/bin/tar",
4263
3723
  args: [
4264
3724
  "--use-compress-program=/usr/bin/gzip -1",
4265
3725
  "-cpf",
4266
- temporary.path,
3726
+ temporary,
4267
3727
  "--exclude=./.rivus-upgrade",
4268
3728
  "-C",
4269
3729
  input.home,
@@ -4276,15 +3736,15 @@ async function backUpUpgradeHome(input) {
4276
3736
  discardStdout: true
4277
3737
  });
4278
3738
  if (created.exitCode !== 0) {
4279
- await rm(temporary.path, { force: true });
4280
- await throwArchiveFailure("create", archive.path, created);
3739
+ await rm(temporary, { force: true });
3740
+ await throwArchiveFailure("create", archive, created);
4281
3741
  }
4282
- await chmod(temporary.path, 384);
3742
+ await chmod(temporary, 384);
4283
3743
  await verifyArchive(temporary, input, true);
4284
- await rename(temporary.path, archive.path);
4285
- return archive.path;
3744
+ await rename(temporary, archive);
3745
+ return archive;
4286
3746
  } finally {
4287
- await rm(temporary.path, { force: true });
3747
+ await rm(temporary, { force: true });
4288
3748
  }
4289
3749
  }
4290
3750
  async function verifyUpgradeBackup(input) {
@@ -4345,8 +3805,6 @@ function packedArtifactPath(stdout, directory) {
4345
3805
  const stringMap = Schema.Record(Schema.String, Schema.String);
4346
3806
  const policySchema = Schema.Struct({
4347
3807
  schemaVersion: Schema.Literal(1),
4348
- stateCompatibility: Schema.Literal("rivus-home-0.20"),
4349
- minimumSourceVersion: Schema.String,
4350
3808
  pnpmVersion: Schema.String,
4351
3809
  overrides: stringMap,
4352
3810
  allowBuilds: Schema.Record(Schema.String, Schema.Boolean)
@@ -4354,11 +3812,11 @@ const policySchema = Schema.Struct({
4354
3812
  function parseInstallationPolicy(text) {
4355
3813
  try {
4356
3814
  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");
3815
+ if (valid(policy.pnpmVersion) !== policy.pnpmVersion) throw new Error("invalid version");
4358
3816
  for (const floor of Object.values(policy.overrides)) if (!valid(floor)) throw new Error("invalid security floor");
4359
3817
  return policy;
4360
3818
  } catch {
4361
- throw new Error("Release installation policy is missing, invalid or requires an unsupported Home migration");
3819
+ throw new Error("Release installation policy is missing or invalid");
4362
3820
  }
4363
3821
  }
4364
3822
  async function readInstallationPolicy(directory = gatewayPackageDirectory) {
@@ -4393,9 +3851,6 @@ async function fetchInstallationPolicy(input) {
4393
3851
  timeoutMs: 3e4
4394
3852
  }, "Target installation policy extraction", join(input.directory, "policy-extraction.log"))).stdout);
4395
3853
  }
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
3854
  function dependencyName(selector) {
4400
3855
  const version = selector.indexOf("@", 1);
4401
3856
  return version === -1 ? selector : selector.slice(0, version);
@@ -4427,13 +3882,31 @@ const corePackageNames = [
4427
3882
  "@rivus/runtime",
4428
3883
  "@rivus/platform"
4429
3884
  ];
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);
3885
+ const StringMap = Schema.Record(Schema.String, Schema.String);
3886
+ const BuildMap = Schema.Record(Schema.String, Schema.Boolean);
4433
3887
  const installedManifestSchema = Schema.Struct({
4434
3888
  name: Schema.String,
4435
3889
  version: Schema.String
4436
3890
  });
3891
+ const NpmOverrides = Schema.Record(Schema.String, Schema.Union([Schema.String, Schema.suspend(() => NpmOverrides)]));
3892
+ /** A missing, `undefined` or `null` section reads as `empty`, as the consumer configuration always has. */
3893
+ function nullishAs(section, empty) {
3894
+ return Schema.optional(Schema.NullOr(Schema.toEncoded(section))).pipe(Schema.decodeTo(section, {
3895
+ decode: SchemaGetter.transformOptional((value) => Option.some(Option.getOrNull(value) ?? empty)),
3896
+ encode: SchemaGetter.passthroughSupertype()
3897
+ }));
3898
+ }
3899
+ const PnpmSettings = Schema.Struct({
3900
+ allowBuilds: nullishAs(BuildMap, {}),
3901
+ overrides: nullishAs(StringMap, {})
3902
+ });
3903
+ /** The consumer `package.json`; fields Rivus does not read stay unchecked. */
3904
+ const ConsumerPackageJson = Schema.Struct({
3905
+ dependencies: nullishAs(StringMap, {}),
3906
+ optionalDependencies: nullishAs(StringMap, {}),
3907
+ overrides: Schema.optional(Schema.NullOr(NpmOverrides)),
3908
+ pnpm: nullishAs(PnpmSettings, {})
3909
+ });
4437
3910
  function installedPackageManifestPath(root, name, resolutionBase = join(root, "package.json")) {
4438
3911
  try {
4439
3912
  const manifest = findPackageJSON(name, resolutionBase);
@@ -4492,9 +3965,6 @@ async function retainLocalArtifact(input, name, requirement, resolutionBase) {
4492
3965
  await chmod(destination, 384);
4493
3966
  return `file:artifacts/${artifactName}`;
4494
3967
  }
4495
- function record(value) {
4496
- return Schema.decodeUnknownSync(recordSchema)(value);
4497
- }
4498
3968
  function flattenNpmOverrides(source, dependencies, parent = "") {
4499
3969
  const result = {};
4500
3970
  for (const [name, value] of Object.entries(source)) {
@@ -4503,20 +3973,19 @@ function flattenNpmOverrides(source, dependencies, parent = "") {
4503
3973
  const requirement = value.startsWith("$") ? dependencies[value.slice(1)] : value;
4504
3974
  if (!selector || !requirement) throw new Error("Consumer npm override cannot be resolved for managed installation");
4505
3975
  result[selector] = requirement;
4506
- } else Object.assign(result, flattenNpmOverrides(record(value), dependencies, selector));
3976
+ } else Object.assign(result, flattenNpmOverrides(value, dependencies, selector));
4507
3977
  }
4508
3978
  return result;
4509
3979
  }
4510
- async function optionalRecord(path, yaml = false) {
3980
+ async function readConsumerConfiguration(schema, path, yaml = false) {
4511
3981
  let text;
4512
3982
  try {
4513
3983
  text = await readFile(path, "utf8");
4514
3984
  } catch (error) {
4515
- if (isNodeErrorWithCode(error, "ENOENT")) return {};
4516
- throw new Error("The installed consumer configuration cannot be read");
3985
+ if (!isNodeErrorWithCode(error, "ENOENT")) throw new Error("The installed consumer configuration cannot be read");
4517
3986
  }
4518
3987
  try {
4519
- return record(yaml ? parse$1(text) : JSON.parse(text));
3988
+ return Schema.decodeUnknownSync(schema)(text === void 0 ? {} : yaml ? parse$1(text) : JSON.parse(text));
4520
3989
  } catch {
4521
3990
  throw new Error("The installed consumer configuration is invalid");
4522
3991
  }
@@ -4528,31 +3997,25 @@ async function privateFile(path, contents) {
4528
3997
  async function writeReleaseConsumer(input) {
4529
3998
  const rootManifest = join(input.sourceRoot, "package.json");
4530
3999
  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 ?? {});
4000
+ const manifest = await readConsumerConfiguration(ConsumerPackageJson, sourceBase);
4001
+ const workspace = await readConsumerConfiguration(PnpmSettings, join(input.sourceRoot, "pnpm-workspace.yaml"), true);
4534
4002
  const dependencies = {};
4535
4003
  const optionalDependencies = {};
4536
4004
  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
- }
4005
+ for (const [field, target] of [["dependencies", dependencies], ["optionalDependencies", optionalDependencies]]) for (const [name, requirement] of Object.entries(manifest[field])) {
4006
+ if (corePackageNames.some((core) => core === name)) continue;
4007
+ const installed = await readInstalledManifest(input.sourceRoot, name, sourceBase).catch((error) => {
4008
+ if (field === "optionalDependencies") return;
4009
+ throw error;
4010
+ });
4011
+ if (!installed) continue;
4012
+ installedVersions[name] = installed.version;
4013
+ 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
4014
  }
4550
4015
  for (const name of corePackageNames) dependencies[name] = input.version;
4551
4016
  if (!dependencies.effect) dependencies.effect = (await readInstalledManifest(input.sourceRoot, "effect", sourceBase)).version;
4552
4017
  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")));
4018
+ const homeManifest = await Effect.runPromise(loadRivusDeploymentManifest(input.homeManifestPath));
4556
4019
  for (const plugin of homeManifest.plugins) {
4557
4020
  if (plugin.module.startsWith(".") || plugin.module.startsWith("/")) continue;
4558
4021
  const name = plugin.module.split("/").slice(0, plugin.module.startsWith("@") ? 2 : 1).join("/");
@@ -4563,14 +4026,14 @@ async function writeReleaseConsumer(input) {
4563
4026
  for (const name of corePackageNames) installedVersions[name] = input.version;
4564
4027
  installedVersions.effect = dependencies.effect;
4565
4028
  const sourceOverrides = {
4566
- ...flattenNpmOverrides(record(manifest.overrides ?? {}), dependencies),
4567
- ...Schema.decodeUnknownSync(stringMapSchema)(sourcePnpm.overrides ?? {}),
4568
- ...Schema.decodeUnknownSync(stringMapSchema)(workspace.overrides ?? {})
4029
+ ...flattenNpmOverrides(manifest.overrides ?? {}, dependencies),
4030
+ ...manifest.pnpm.overrides,
4031
+ ...workspace.overrides
4569
4032
  };
4570
4033
  const allowBuilds = {
4571
4034
  ...input.policy.allowBuilds,
4572
- ...Schema.decodeUnknownSync(buildMapSchema)(sourcePnpm.allowBuilds ?? {}),
4573
- ...Schema.decodeUnknownSync(buildMapSchema)(workspace.allowBuilds ?? {})
4035
+ ...manifest.pnpm.allowBuilds,
4036
+ ...workspace.allowBuilds
4574
4037
  };
4575
4038
  await privateFile(join(input.directory, "package.json"), `${JSON.stringify({
4576
4039
  name: "rivus-managed-release",
@@ -4683,7 +4146,6 @@ async function retainRegistryConfiguration(sourceRoot, directory) {
4683
4146
  async function prepareRelease(input) {
4684
4147
  if (!stableVersion(input.version)) throw new Error("Managed upgrade requires a stable three-component release version");
4685
4148
  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
4149
  await mkdir(input.directory, {
4688
4150
  recursive: true,
4689
4151
  mode: 448
@@ -4707,7 +4169,6 @@ async function prepareRelease(input) {
4707
4169
  npm,
4708
4170
  run: input.run
4709
4171
  });
4710
- assertSourceCompatibility(policy, input.source.version);
4711
4172
  let versions;
4712
4173
  try {
4713
4174
  versions = await writeReleaseConsumer({
@@ -5461,25 +4922,100 @@ async function snapshotFile(source, destination) {
5461
4922
  recursive: true,
5462
4923
  mode: 448
5463
4924
  });
5464
- const temporary = `${destination}.${randomUUID()}.tmp`;
5465
- 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
- }
5478
- } catch (error) {
5479
- if (!isNodeErrorWithCode(error, "EEXIST")) throw error;
5480
- } finally {
5481
- await rm(temporary, { force: true });
5482
- }
4925
+ const temporary = `${destination}.${randomUUID()}.tmp`;
4926
+ try {
4927
+ await writeFile(temporary, await readFile(source), {
4928
+ flag: "wx",
4929
+ mode: 384,
4930
+ flush: true
4931
+ });
4932
+ await link(temporary, destination);
4933
+ const directory = await open(dirname(destination), "r");
4934
+ try {
4935
+ await directory.sync();
4936
+ } finally {
4937
+ await directory.close();
4938
+ }
4939
+ } catch (error) {
4940
+ if (!isNodeErrorWithCode(error, "EEXIST")) throw error;
4941
+ } finally {
4942
+ await rm(temporary, { force: true });
4943
+ }
4944
+ }
4945
+ //#endregion
4946
+ //#region src/upgrade/domain/upgrade/phase.ts
4947
+ /** The phases of one managed upgrade, in the order a run passes through them. The journal records the phase reached,
4948
+ * so this order is also the resume order. */
4949
+ const upgradePhases = [
4950
+ "preparing",
4951
+ "prepared",
4952
+ "stopping",
4953
+ "stopped",
4954
+ "backed-up",
4955
+ "switching",
4956
+ "starting",
4957
+ "complete"
4958
+ ];
4959
+ const successors = {
4960
+ preparing: "prepared",
4961
+ prepared: "stopping",
4962
+ stopping: "stopped",
4963
+ stopped: "backed-up",
4964
+ "backed-up": "switching",
4965
+ switching: "starting",
4966
+ starting: "complete"
4967
+ };
4968
+ function nextUpgradePhase(phase) {
4969
+ return successors[phase];
4970
+ }
4971
+ function isPendingUpgradePhase(phase) {
4972
+ return phase !== "complete";
4973
+ }
4974
+ //#endregion
4975
+ //#region src/upgrade/infra/repository/upgrade-journal.ts
4976
+ const recordSchema = Schema.fromJsonString(Schema.Struct({
4977
+ schemaVersion: Schema.Literal(1),
4978
+ id: Schema.NonEmptyString,
4979
+ home: Schema.NonEmptyString,
4980
+ sourceVersion: Schema.NonEmptyString,
4981
+ targetVersion: Schema.NonEmptyString,
4982
+ sourceCommand: Schema.Array(Schema.NonEmptyString),
4983
+ service: Schema.Struct({
4984
+ kind: Schema.Literals(["launchd", "systemd"]),
4985
+ id: Schema.NonEmptyString,
4986
+ definitionPath: Schema.NonEmptyString
4987
+ }),
4988
+ phase: Schema.Literals(upgradePhases),
4989
+ createdAt: Schema.NonEmptyString,
4990
+ startedAfter: Schema.optional(Schema.NonEmptyString)
4991
+ }));
4992
+ /** The Home's upgrade directory: this journal and, per operation, the prepared release and the Home backup. */
4993
+ function upgradePaths(home, id) {
4994
+ const directory = join(home, ".rivus-upgrade");
4995
+ return {
4996
+ directory,
4997
+ journal: join(directory, "operation.json"),
4998
+ release: join(directory, "releases", id ?? ""),
4999
+ backup: join(directory, "backups", id ?? "")
5000
+ };
5001
+ }
5002
+ async function readUpgradeRecord(home) {
5003
+ const text = await readPersistenceFile(upgradePaths(home).journal);
5004
+ if (text === void 0) return;
5005
+ const record = Schema.decodeUnknownSync(recordSchema)(text);
5006
+ 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");
5007
+ return record;
5008
+ }
5009
+ async function writeUpgradeRecord(record) {
5010
+ const paths = upgradePaths(record.home);
5011
+ await mkdir(paths.directory, {
5012
+ recursive: true,
5013
+ mode: 448
5014
+ });
5015
+ await writeAtomicTextFile(paths.journal, `${JSON.stringify(record)}\n`, {
5016
+ durable: true,
5017
+ mode: 384
5018
+ });
5483
5019
  }
5484
5020
  //#endregion
5485
5021
  //#region src/upgrade/infra/adapters/upgrade-lock.ts
@@ -5487,8 +5023,7 @@ async function snapshotFile(source, destination) {
5487
5023
  * Takes the Home upgrade lock at `.rivus-upgrade/upgrade.process-lock`: an exclusive kernel lock held until release or
5488
5024
  * until the holding process exits or crashes — the kernel releases a crashed holder's lock at once, so there is no
5489
5025
  * 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.
5026
+ * holder runs would let the next invocation take a second lock beside it.
5492
5027
  */
5493
5028
  async function acquireUpgradeLock(home, lockPlatform) {
5494
5029
  const root = upgradePaths(home).directory;
@@ -5502,6 +5037,72 @@ async function acquireUpgradeLock(home, lockPlatform) {
5502
5037
  return () => lock.release();
5503
5038
  }
5504
5039
  //#endregion
5040
+ //#region src/upgrade/infra/repository/runtime-receipt.ts
5041
+ const absolutePath = Schema.String.check(Schema.makeFilter(isAbsolute));
5042
+ const runtimeReceiptSchema = Schema.Struct({
5043
+ schemaVersion: Schema.Literal(1),
5044
+ home: absolutePath,
5045
+ pid: Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0)),
5046
+ version: Schema.Trimmed.check(Schema.isNonEmpty()),
5047
+ executable: absolutePath,
5048
+ startedAt: Schema.String.check(Schema.makeFilter((value) => Number.isFinite(Date.parse(value))))
5049
+ });
5050
+ async function writeRuntimeReceipt(input) {
5051
+ const receipt = Schema.decodeUnknownSync(runtimeReceiptSchema)({
5052
+ ...input,
5053
+ home: await realpath(input.home),
5054
+ executable: await realpath(input.executable),
5055
+ schemaVersion: 1
5056
+ });
5057
+ const directory = join(receipt.home, ".rivus-upgrade");
5058
+ await mkdir(directory, {
5059
+ mode: 448,
5060
+ recursive: true
5061
+ });
5062
+ await chmod(directory, 448);
5063
+ const path = join(directory, "runtime.json");
5064
+ await chmod(path, 384).catch((error) => {
5065
+ if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
5066
+ });
5067
+ await writeAtomicTextFile(path, `${JSON.stringify(receipt)}\n`, {
5068
+ durable: true,
5069
+ mode: 384
5070
+ });
5071
+ }
5072
+ async function readRuntimeReceipt(home) {
5073
+ let canonicalHome;
5074
+ let raw;
5075
+ try {
5076
+ canonicalHome = await realpath(home);
5077
+ raw = await readFile(join(canonicalHome, ".rivus-upgrade", "runtime.json"), "utf8");
5078
+ } catch (error) {
5079
+ if (isNodeErrorWithCode(error, "ENOENT")) return;
5080
+ throw error;
5081
+ }
5082
+ try {
5083
+ const receipt = Schema.decodeUnknownSync(runtimeReceiptSchema)(JSON.parse(raw));
5084
+ return receipt.home === canonicalHome ? receipt : void 0;
5085
+ } catch {
5086
+ return;
5087
+ }
5088
+ }
5089
+ async function clearRuntimeReceipt(home, pid) {
5090
+ const receipt = await readRuntimeReceipt(home);
5091
+ if (receipt?.pid === pid) await unlink(join(receipt.home, ".rivus-upgrade", "runtime.json")).catch((error) => {
5092
+ if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
5093
+ });
5094
+ }
5095
+ //#endregion
5096
+ //#region src/upgrade/domain/upgrade/record.ts
5097
+ /** The record after entering `phase`. Entering `stopping` stamps `startedAfter`; `now` is read only then. */
5098
+ function enterUpgradePhase(record, phase, now) {
5099
+ return {
5100
+ ...record,
5101
+ phase,
5102
+ ...phase === "stopping" ? { startedAfter: now() } : {}
5103
+ };
5104
+ }
5105
+ //#endregion
5505
5106
  //#region src/upgrade/application/ports.ts
5506
5107
  var UpgradeServiceManager = class extends Context.Service()("@rivus/gateway/upgrade/UpgradeServiceManager") {};
5507
5108
  var UpgradePackages = class extends Context.Service()("@rivus/gateway/upgrade/UpgradePackages") {};
@@ -5553,9 +5154,9 @@ function runUpgrade(input) {
5553
5154
  const services = yield* UpgradeServiceManager;
5554
5155
  const versions = yield* UpgradeVersions;
5555
5156
  const record0 = yield* journal.read(home.directory);
5556
- let service = record0 && record0.phase !== "complete" ? yield* services.load(record0.service) : yield* services.discover();
5157
+ let service = record0 && isPendingUpgradePhase(record0.phase) ? yield* services.load(record0.service) : yield* services.discover();
5557
5158
  let record = record0;
5558
- if (!record || record.phase === "complete") {
5159
+ if (!record || !isPendingUpgradePhase(record.phase)) {
5559
5160
  const source = yield* packages.inspect(service.command, service.cwd, service.env);
5560
5161
  input.progress("resolving", `Checking latest release (current ${source.version})`);
5561
5162
  const target = yield* packages.latest({
@@ -5564,7 +5165,7 @@ function runUpgrade(input) {
5564
5165
  nodePath: source.nodePath
5565
5166
  });
5566
5167
  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"));
5168
+ if (!versions.isValid(source.version)) return yield* Effect.fail(/* @__PURE__ */ new Error(`the running release version ${source.version} is not a valid version`));
5568
5169
  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
5170
  const observed = yield* services.inspect(service);
5570
5171
  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 +5195,16 @@ function runUpgrade(input) {
5594
5195
  };
5595
5196
  yield* journal.write(record);
5596
5197
  }
5597
- const paths = upgradePaths(home.directory, record.id);
5198
+ const paths = journal.directories(home.directory, record.id);
5598
5199
  const source = yield* packages.inspect(record.sourceCommand, service.cwd, service.env);
5599
5200
  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
5201
  yield* requireStableVersion(versions, record.targetVersion);
5601
5202
  const candidateCommand = [...record.sourceCommand];
5602
5203
  const candidateCli = `${paths.release}/node_modules/@rivus/agent/dist/cli.js`;
5603
5204
  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
- };
5205
+ const advance = (from) => Effect.gen(function* () {
5206
+ const phase = nextUpgradePhase(from);
5207
+ record = enterUpgradePhase(record, phase, () => clock.now().toISOString());
5610
5208
  yield* journal.write(record);
5611
5209
  input.progress(phase, `${record.sourceVersion} -> ${record.targetVersion}`);
5612
5210
  });
@@ -5626,13 +5224,13 @@ function runUpgrade(input) {
5626
5224
  home,
5627
5225
  service
5628
5226
  });
5629
- yield* setPhase("prepared");
5227
+ yield* advance(record.phase);
5630
5228
  }
5631
5229
  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
5230
  if (record.phase === "prepared") {
5633
5231
  const observed = yield* inspectExpected();
5634
5232
  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");
5233
+ yield* advance(record.phase);
5636
5234
  }
5637
5235
  if (record.phase === "stopping") {
5638
5236
  const observed = yield* inspectExpected();
@@ -5641,7 +5239,7 @@ function runUpgrade(input) {
5641
5239
  yield* services.stop(record.service);
5642
5240
  }
5643
5241
  if ((yield* inspectExpected()).running) return yield* Effect.fail(/* @__PURE__ */ new Error("the managed service has not stopped"));
5644
- yield* setPhase("stopped");
5242
+ yield* advance(record.phase);
5645
5243
  }
5646
5244
  if (record.phase === "stopped") {
5647
5245
  if ((yield* inspectExpected()).running) return yield* Effect.fail(/* @__PURE__ */ new Error("the service restarted before backup; stop it before resuming this operation"));
@@ -5650,7 +5248,7 @@ function runUpgrade(input) {
5650
5248
  directory: paths.backup,
5651
5249
  env: service.env
5652
5250
  });
5653
- yield* setPhase("backed-up");
5251
+ yield* advance(record.phase);
5654
5252
  }
5655
5253
  if (record.phase === "backed-up") {
5656
5254
  yield* archive.verify({
@@ -5659,7 +5257,7 @@ function runUpgrade(input) {
5659
5257
  env: service.env
5660
5258
  });
5661
5259
  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");
5260
+ yield* advance(record.phase);
5663
5261
  }
5664
5262
  if (record.phase === "switching") {
5665
5263
  const observed = yield* inspectExpected();
@@ -5669,7 +5267,7 @@ function runUpgrade(input) {
5669
5267
  if (!sameCommand(service.command, record.sourceCommand)) return yield* Effect.fail(/* @__PURE__ */ new Error("the service definition changed outside this upgrade"));
5670
5268
  yield* services.switch(record.service, candidateCommand, paths.backup);
5671
5269
  }
5672
- yield* setPhase("starting");
5270
+ yield* advance(record.phase);
5673
5271
  }
5674
5272
  if (record.phase !== "starting") return yield* Effect.fail(/* @__PURE__ */ new Error(`unsupported recovery phase: ${record.phase}`));
5675
5273
  const observed = yield* inspectExpected();
@@ -5680,7 +5278,7 @@ function runUpgrade(input) {
5680
5278
  receipts,
5681
5279
  services
5682
5280
  }, record, candidateCommand);
5683
- yield* setPhase("complete");
5281
+ yield* advance(record.phase);
5684
5282
  return {
5685
5283
  status: "upgraded",
5686
5284
  version: record.targetVersion,
@@ -5770,7 +5368,14 @@ function nodeUpgradePorts(options) {
5770
5368
  write: (record) => Effect.tryPromise({
5771
5369
  try: () => writeUpgradeRecord(record),
5772
5370
  catch: (error) => error
5773
- })
5371
+ }),
5372
+ directories: (home, id) => {
5373
+ const { release, backup } = upgradePaths(home, id);
5374
+ return {
5375
+ release,
5376
+ backup
5377
+ };
5378
+ }
5774
5379
  }), Layer.succeed(UpgradeReceipts, { read: (home) => Effect.tryPromise({
5775
5380
  try: () => options.receipts(home),
5776
5381
  catch: (error) => error
@@ -5787,56 +5392,7 @@ function nodeUpgradePorts(options) {
5787
5392
  }), Layer.succeed(UpgradeIds, { next: () => randomUUID() }));
5788
5393
  }
5789
5394
  //#endregion
5790
- //#region src/bootstrap/upgrade/upgrade-home.ts
5791
- /** Owns one managed process cutover. Application data is retained in its original Home throughout the operation.
5792
- * Bootstrap keeps the process concerns — the realpath resolution, the upgrade lock and the default service
5793
- * composition — and hands the phase machine to the upgrade context's use case. */
5794
- async function upgradeHome(options) {
5795
- const home = {
5796
- ...options.home,
5797
- directory: await realpath(options.home.directory)
5798
- };
5799
- const releaseLock = await acquireUpgradeLock(home.directory, options.lockPlatform);
5800
- try {
5801
- const runner = options.run ?? runCommand;
5802
- const run = (request) => runner({
5803
- ...request,
5804
- ...options.signal ? { signal: options.signal } : {}
5805
- });
5806
- const services = options.services ?? createServiceManager({
5807
- home: home.directory,
5808
- userHome: options.userHome,
5809
- platform: options.platform,
5810
- env: { ...options.env },
5811
- run
5812
- });
5813
- const ports = nodeUpgradePorts({
5814
- run,
5815
- ...options.signal ? { signal: options.signal } : {},
5816
- services,
5817
- packages: options.packages ?? {
5818
- inspect: inspectInstalledRelease,
5819
- latest: resolveLatestVersion,
5820
- prepare: prepareRelease
5821
- },
5822
- backup: options.backup ?? backUpUpgradeHome,
5823
- verifyBackup: options.verifyBackup ?? verifyUpgradeBackup,
5824
- receipts: options.receipts ?? readRuntimeReceipt,
5825
- ...options.now ? { now: options.now } : {},
5826
- ...options.wait ? { wait: options.wait } : {}
5827
- });
5828
- return unwrapExit(await Effect.runPromiseExit(runUpgrade({
5829
- home,
5830
- ...options.signal ? { signal: options.signal } : {},
5831
- progress: options.progress,
5832
- ...options.startupTimeoutMs !== void 0 ? { startupTimeoutMs: options.startupTimeoutMs } : {}
5833
- }).pipe(Effect.provide(ports))));
5834
- } finally {
5835
- await releaseLock();
5836
- }
5837
- }
5838
- //#endregion
5839
- //#region src/bootstrap/cli/rivus-cli.ts
5395
+ //#region src/bootstrap/cli/home-daemon-command.ts
5840
5396
  function resolveHomeRecoveryFileArguments(argv, command, cwd) {
5841
5397
  if (command.type === "inspect") return argv;
5842
5398
  const files = /* @__PURE__ */ new Map([["--recovery-note-file", resolve(cwd, command.noteFilePath)]]);
@@ -5853,6 +5409,68 @@ function resolveHomeRecoveryFileArguments(argv, command, cwd) {
5853
5409
  }
5854
5410
  return resolved;
5855
5411
  }
5412
+ function runHomeDaemonCommand(options, command, daemonArgs) {
5413
+ const commandArgs = options.argv.slice(1);
5414
+ const checkPlugins = command === "check-config" && commandArgs.length === 1 && commandArgs[0] === "--load-plugins";
5415
+ if (command !== "recovery" && !checkPlugins && hasRivusHomeCommandArguments(commandArgs)) return Effect.sync(() => {
5416
+ options.stderr.write(renderRivusHomeCommandUsage(command));
5417
+ return 1;
5418
+ });
5419
+ return resolveHomeDirectoryEffect(options).pipe(Effect.flatMap((directory) => options.homeApi.load(directory)), Effect.tap((home) => Effect.sync(() => options.changeWorkingDirectory(home.workspaceDirectory))), Effect.flatMap((home) => runRivusDaemonCli({
5420
+ ...options,
5421
+ argv: [
5422
+ "--env-file",
5423
+ home.envFilePath,
5424
+ "--bootstrap",
5425
+ home.bootstrap,
5426
+ "--manifest",
5427
+ home.manifestPath,
5428
+ ...daemonArgs
5429
+ ],
5430
+ env: {
5431
+ ...options.env,
5432
+ RIVUS_DEPLOYMENT_STATE_DIR: home.stateDirectory,
5433
+ RIVUS_HOME: home.directory,
5434
+ [RIVUS_HOME_DEPLOYMENT_ENV]: home.directory
5435
+ },
5436
+ pluginPackageManifestPath: options.pluginPackageManifestPath ?? gatewayPackageManifestPath,
5437
+ ...checkPlugins ? { checkPlugins: true } : {},
5438
+ ...command === "start" ? { lifecycle: {
5439
+ started: async () => {
5440
+ if (!options.runtimeProcess) throw new Error("Home start requires the runtime process identity");
5441
+ await writeRuntimeReceipt({
5442
+ ...options.runtimeProcess,
5443
+ home: home.directory,
5444
+ version: RIVUS_RELEASE_DESCRIPTOR.version,
5445
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
5446
+ });
5447
+ },
5448
+ stopped: async () => {
5449
+ if (options.runtimeProcess) await clearRuntimeReceipt(home.directory, options.runtimeProcess.pid);
5450
+ }
5451
+ } } : {}
5452
+ })), Effect.catch((error) => writeError(options, error)));
5453
+ }
5454
+ function runRecoveryCommand(options) {
5455
+ const argv = options.argv.slice(1);
5456
+ const parser = createRivusRecoveryCliParser();
5457
+ for (let index = 0; index < argv.length; index += 1) {
5458
+ const argument = parser.consume(argv[index], argv[index + 1]);
5459
+ if (!argument.handled || argument.error) return Effect.sync(() => {
5460
+ options.stderr.write(renderRivusHomeCommandUsage("recovery"));
5461
+ return 1;
5462
+ });
5463
+ index += argument.consumed;
5464
+ }
5465
+ const parsed = parser.build();
5466
+ if (argv.length === 0 || parsed.error || !parsed.command) return Effect.sync(() => {
5467
+ options.stderr.write(renderRivusHomeCommandUsage("recovery"));
5468
+ return 1;
5469
+ });
5470
+ return runHomeDaemonCommand(options, "recovery", resolveHomeRecoveryFileArguments(argv, parsed.command, options.cwd));
5471
+ }
5472
+ //#endregion
5473
+ //#region src/bootstrap/cli/model-command.ts
5856
5474
  /** The exit code reads the request receipt from the open model response record by name (authoring guide, Validation). */
5857
5475
  const requestReceipt = Schema.Struct({ requestId: Schema.String });
5858
5476
  function modelManagementExitCode(response) {
@@ -5912,37 +5530,243 @@ function runModelCommand(options) {
5912
5530
  return 1;
5913
5531
  })));
5914
5532
  }
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;
5533
+ //#endregion
5534
+ //#region src/bootstrap/cli/setup-command.ts
5535
+ function runSetupCommand(options) {
5536
+ 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))));
5537
+ }
5538
+ function runInitCommand(options) {
5539
+ return withOptionalDirectoryArgument(options, "init", (argument) => {
5540
+ const directory = resolve(options.cwd, argument ?? ".");
5541
+ return Effect.tryPromise({
5542
+ try: () => initializeRivusProject({
5543
+ directory,
5544
+ nodeExecutable: options.nodeExecutable,
5545
+ templateDirectory: gatewayTemplateDirectory
5546
+ }),
5547
+ catch: (error) => error
5548
+ }).pipe(Effect.tap((result) => Effect.sync(() => options.stdout.write(renderRivusProjectInitializationSuccess(result.directory)))), Effect.as(0), Effect.catch((error) => writeError(options, error)));
5549
+ });
5550
+ }
5551
+ function writeDoctorReport(stdout, report, owner) {
5552
+ for (const chunk of renderRivusDoctorReport(report, owner)) stdout.write(chunk);
5553
+ return report.ready ? 0 : 1;
5554
+ }
5555
+ function runDoctorCommand(options) {
5556
+ const parsed = parseRivusDoctorArguments(options.argv.slice(1));
5557
+ if (parsed.help) return Effect.sync(() => {
5558
+ options.stdout.write(renderRivusDoctorUsage());
5559
+ return 0;
5560
+ });
5561
+ if (parsed.error) {
5562
+ const error = parsed.error;
5563
+ return Effect.sync(() => {
5564
+ options.stderr.write(renderRivusDoctorArgumentError(error));
5565
+ return 1;
5566
+ });
5567
+ }
5568
+ if (parsed.directory === void 0) return resolveHomeDirectoryEffect(options).pipe(Effect.flatMap((directory) => options.homeApi.diagnose({
5569
+ directory,
5570
+ env: options.env,
5571
+ ...parsed.envFilePath ? { envFilePath: parsed.envFilePath } : {},
5572
+ nodeVersion: options.nodeVersion
5573
+ })), Effect.map((report) => writeDoctorReport(options.stdout, report, "Home")), Effect.catch((error) => writeError(options, error)));
5574
+ const projectDirectory = parsed.directory;
5575
+ return diagnoseRivusProject({
5576
+ checkSuperagents: checkSuperagentConfigurations,
5577
+ directory: resolve(options.cwd, projectDirectory),
5578
+ env: options.env,
5579
+ ...parsed.envFilePath ? { envFilePath: parsed.envFilePath } : {},
5580
+ nodeVersion: options.nodeVersion
5581
+ }).pipe(Effect.map((report) => writeDoctorReport(options.stdout, report, "project")), Effect.catch((error) => writeError(options, error)));
5582
+ }
5583
+ //#endregion
5584
+ //#region src/bootstrap/cli/superagent-command.ts
5585
+ function runSuperagentCommand(options) {
5586
+ const args = options.argv.slice(1);
5587
+ if (args.length === 1 && (args[0] === "--help" || args[0] === "-h")) return Effect.sync(() => {
5588
+ options.stdout.write(superagentUsage);
5589
+ return 0;
5590
+ });
5591
+ return Effect.gen(function* () {
5592
+ const request = yield* Effect.try({
5593
+ try: () => parseSuperagentArguments(args),
5594
+ catch: (error) => error
5595
+ });
5596
+ const state = options.env.RIVUS_DEPLOYMENT_STATE_DIR?.trim() || (yield* options.homeApi.load(yield* resolveHomeDirectoryEffect(options))).stateDirectory;
5597
+ const response = yield* Effect.tryPromise({
5598
+ try: () => requestLocalJson(superagentControlSocketPath(resolve(options.cwd, state)), request),
5599
+ catch: (error) => error
5600
+ });
5601
+ if (!response.ok) {
5602
+ options.stderr.write(renderRivusCliError(new Error(response.error)));
5603
+ return superagentRejectionExitCode(response.code);
5604
+ }
5605
+ options.stdout.write(JSON.stringify(response.value, null, 2) + "\n");
5606
+ return 0;
5607
+ }).pipe(Effect.catch((error) => superagentTransportError(options, error)));
5608
+ }
5609
+ //#endregion
5610
+ //#region src/bootstrap/cli/worker-hook.ts
5611
+ const decodePayload = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json));
5612
+ const questions = Schema.NonEmptyArray(Schema.Struct({
5613
+ question: Schema.NonEmptyString,
5614
+ multiSelect: Schema.optionalKey(Schema.Boolean),
5615
+ options: Schema.Array(Schema.Struct({
5616
+ label: Schema.NonEmptyString,
5617
+ description: Schema.optionalKey(Schema.String)
5618
+ }))
5619
+ }));
5620
+ const decodeQuestions = Schema.decodeUnknownOption(Schema.Struct({ tool_input: Schema.Struct({ questions }) }));
5621
+ /** What a hook that only observes prints, so that Claude Code proceeds unchanged. */
5622
+ const passThrough = "{}";
5623
+ const denyQuestion = JSON.stringify({ hookSpecificOutput: {
5624
+ hookEventName: "PreToolUse",
5625
+ permissionDecision: "deny",
5626
+ permissionDecisionReason: "The question was sent to the task thread; the answer arrives as the next input. Stop and wait for it."
5627
+ } });
5628
+ function questionText(asked) {
5629
+ 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");
5630
+ }
5631
+ /**
5632
+ * Reads one Claude Code hook payload into the event sent to the worker socket. Raw tool input and output stay in the
5633
+ * hook process: only the lifecycle fields and, for AskUserQuestion, the decoded question text leave it.
5634
+ */
5635
+ function readWorkerHook(stdin, env, at) {
5636
+ const payload = decodePayload(stdin);
5637
+ if (Option.isNone(payload)) return;
5638
+ const event = readHookEvent("claude-code", payload.value, env);
5639
+ if (event.phase === "unknown" || event.nativeEvent === "Notification" && event.phase === "blocked") return;
5640
+ const activity = {
5641
+ phase: event.phase === "blocked" ? "blocked" : event.phase === "finish" && event.scope === "turn" ? "finish" : "activity",
5642
+ ...event.phase === "blocked" && event.blocker !== void 0 ? { blocker: event.blocker } : {},
5643
+ ...event.tool === void 0 ? {} : { tool: event.tool.name },
5644
+ at,
5645
+ ...event.turnId === void 0 ? {} : { turnId: event.turnId }
5646
+ };
5647
+ const asked = event.nativeEvent === "PreToolUse" && event.tool?.name === "AskUserQuestion" ? decodeQuestions(payload.value) : Option.none();
5648
+ return Option.isSome(asked) ? {
5649
+ activity,
5650
+ question: questionText(asked.value.tool_input.questions)
5651
+ } : { activity };
5921
5652
  }
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));
5653
+ /**
5654
+ * Runs `rivus task hook` and returns what it prints. It never fails: a hook that cannot reach Rivus lets Claude Code
5655
+ * proceed, and AskUserQuestion is denied only after the question was recorded, so a rejected question stays in the
5656
+ * terminal.
5657
+ */
5658
+ async function runWorkerHook(stdin, env, at) {
5659
+ const path = env.RIVUS_WORKER_SOCKET;
5660
+ const execution = env.RIVUS_WORKER_KEY;
5661
+ const token = env.RIVUS_WORKER_TOKEN;
5662
+ const event = readWorkerHook(stdin, env, at);
5663
+ if (!path || !execution || !token || event === void 0) return passThrough;
5664
+ try {
5665
+ const outcome = await requestSuperagentWorker(path, {
5666
+ execution,
5667
+ token
5668
+ }, {
5669
+ operation: "event",
5670
+ ...event
5671
+ }, 2e3);
5672
+ return event.question !== void 0 && outcome === "recorded" ? denyQuestion : passThrough;
5673
+ } catch {
5674
+ return passThrough;
5675
+ }
5676
+ }
5677
+ //#endregion
5678
+ //#region src/bootstrap/cli/task-command.ts
5679
+ function runTaskCommand(options) {
5680
+ if (options.argv[1] === "hook" && options.argv.length === 2) return Effect.promise(async () => {
5681
+ const payload = await options.readStdin().catch(() => "");
5682
+ options.stdout.write(await runWorkerHook(payload, options.env, Date.now()) + "\n");
5926
5683
  return 0;
5927
5684
  });
5928
- if (parsed.error) return Effect.sync(() => {
5929
- options.stderr.write(renderRivusDirectoryCommandUsage(command));
5930
- return 1;
5931
- });
5932
- return run(parsed.directory);
5685
+ return Effect.gen(function* () {
5686
+ const [, command, raw, ...rest] = options.argv;
5687
+ const path = options.env.RIVUS_WORKER_SOCKET;
5688
+ const execution = options.env.RIVUS_WORKER_KEY;
5689
+ const token = options.env.RIVUS_WORKER_TOKEN;
5690
+ if (!path || !execution || !token) return yield* writeError(options, /* @__PURE__ */ new Error("This command requires an active Rivus worker execution"));
5691
+ const payload = command === "report" && rest.length === 0 ? raw : command === "call" && rest.length === 1 ? rest[0] : void 0;
5692
+ const request = command === "show" && raw === void 0 ? {
5693
+ operation: "call",
5694
+ name: "task_show",
5695
+ input: {}
5696
+ } : payload !== void 0 && raw !== void 0 ? {
5697
+ operation: "call",
5698
+ name: command === "report" ? "task_report" : raw,
5699
+ input: yield* Effect.try({
5700
+ try: () => Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Json))(payload),
5701
+ catch: (error) => error
5702
+ })
5703
+ } : void 0;
5704
+ if (request === void 0) return yield* writeError(options, /* @__PURE__ */ new Error("Usage: rivus task show | rivus task report '<json>' | rivus task call <name> '<json>'"));
5705
+ const value = yield* Effect.tryPromise({
5706
+ try: () => requestSuperagentWorker(path, {
5707
+ execution,
5708
+ token
5709
+ }, request),
5710
+ catch: (error) => error
5711
+ });
5712
+ options.stdout.write(JSON.stringify(value, null, 2) + "\n");
5713
+ return 0;
5714
+ }).pipe(Effect.catch((error) => error instanceof SuperagentWorkerRejected ? Effect.sync(() => {
5715
+ options.stderr.write(renderRivusCliError(error));
5716
+ return 2;
5717
+ }) : superagentTransportError(options, error)));
5933
5718
  }
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
- });
5719
+ //#endregion
5720
+ //#region src/bootstrap/upgrade/upgrade-home.ts
5721
+ /** Owns one managed process cutover. Application data is retained in its original Home throughout the operation.
5722
+ * Bootstrap keeps the process concerns — the realpath resolution, the upgrade lock and the default service
5723
+ * composition — and hands the phase machine to the upgrade context's use case. */
5724
+ async function upgradeHome(options) {
5725
+ const home = {
5726
+ ...options.home,
5727
+ directory: await realpath(options.home.directory)
5728
+ };
5729
+ const releaseLock = await acquireUpgradeLock(home.directory, options.lockPlatform);
5730
+ try {
5731
+ const runner = options.run ?? runCommand;
5732
+ const run = (request) => runner({
5733
+ ...request,
5734
+ ...options.signal ? { signal: options.signal } : {}
5735
+ });
5736
+ const services = options.services ?? createServiceManager({
5737
+ home: home.directory,
5738
+ userHome: options.userHome,
5739
+ platform: options.platform,
5740
+ env: { ...options.env },
5741
+ run
5742
+ });
5743
+ const ports = nodeUpgradePorts({
5744
+ run,
5745
+ ...options.signal ? { signal: options.signal } : {},
5746
+ services,
5747
+ packages: options.packages ?? {
5748
+ inspect: inspectInstalledRelease,
5749
+ latest: resolveLatestVersion,
5750
+ prepare: prepareRelease
5751
+ },
5752
+ backup: options.backup ?? backUpUpgradeHome,
5753
+ verifyBackup: options.verifyBackup ?? verifyUpgradeBackup,
5754
+ receipts: options.receipts ?? readRuntimeReceipt,
5755
+ ...options.now ? { now: options.now } : {},
5756
+ ...options.wait ? { wait: options.wait } : {}
5757
+ });
5758
+ return unwrapExit(await Effect.runPromiseExit(runUpgrade({
5759
+ home,
5760
+ ...options.signal ? { signal: options.signal } : {},
5761
+ progress: options.progress,
5762
+ ...options.startupTimeoutMs !== void 0 ? { startupTimeoutMs: options.startupTimeoutMs } : {}
5763
+ }).pipe(Effect.provide(ports))));
5764
+ } finally {
5765
+ await releaseLock();
5766
+ }
5945
5767
  }
5768
+ //#endregion
5769
+ //#region src/bootstrap/cli/upgrade-command.ts
5946
5770
  function runUpgradeCommand(options) {
5947
5771
  const parsed = parseUpgradeArguments(options.argv.slice(1));
5948
5772
  if ("help" in parsed) return Effect.sync(() => {
@@ -5982,127 +5806,279 @@ function runUpgradeCommand(options) {
5982
5806
  return 1;
5983
5807
  })));
5984
5808
  }
5985
- function writeDoctorReport(stdout, report, owner) {
5986
- for (const chunk of renderRivusDoctorReport(report, owner)) stdout.write(chunk);
5987
- return report.ready ? 0 : 1;
5809
+ //#endregion
5810
+ //#region src/remote-worker/infra/adapters/worker-bridge-server.ts
5811
+ const decodePingParams = Schema.decodeUnknownSync(Schema.Struct({ ts: Schema.Number }), { onExcessProperty: "error" });
5812
+ const REMOTE_BASE_ENV_KEYS = [
5813
+ "PATH",
5814
+ "HOME",
5815
+ "USER",
5816
+ "LOGNAME",
5817
+ "TMPDIR",
5818
+ "LANG"
5819
+ ];
5820
+ function pickBaseEnvironment(env) {
5821
+ return Object.fromEntries(REMOTE_BASE_ENV_KEYS.flatMap((name) => {
5822
+ const value = env[name];
5823
+ return value === void 0 ? [] : [[name, value]];
5824
+ }));
5988
5825
  }
5989
- function writeError(options, error) {
5990
- return Effect.sync(() => {
5991
- options.stderr.write(renderRivusCliError(error));
5992
- return 1;
5993
- });
5826
+ /**
5827
+ * Rewrites host-originated launch fields onto this remote machine's local environment, worker tools socket and
5828
+ * credential wrappers so macOS/host paths never leak into a Linux remote workspace.
5829
+ */
5830
+ function localizeLaunch(launch, remoteBaseEnv, programs, workerSocketPath) {
5831
+ const environment = {
5832
+ ...remoteBaseEnv,
5833
+ ...launch.environment,
5834
+ PATH: programs.environment.PATH,
5835
+ GH_CONFIG_DIR: programs.environment.GH_CONFIG_DIR,
5836
+ RIVUS_WORKER_DENY_SSH: programs.environment.RIVUS_WORKER_DENY_SSH,
5837
+ GIT_SSH_COMMAND: programs.environment.RIVUS_WORKER_DENY_SSH,
5838
+ RIVUS_WORKER_SOCKET: workerSocketPath
5839
+ };
5840
+ const count = Number(environment.GIT_CONFIG_COUNT ?? "0");
5841
+ for (let index = 0; index < count; index += 1) if (environment[`GIT_CONFIG_KEY_${index}`] === "credential.helper" && environment[`GIT_CONFIG_VALUE_${index}`]) environment[`GIT_CONFIG_VALUE_${index}`] = programs.helper;
5842
+ return {
5843
+ key: launch.key,
5844
+ workerId: launch.workerId,
5845
+ cwd: launch.cwd,
5846
+ title: launch.title,
5847
+ scope: launch.scope,
5848
+ notes: launch.notes ?? void 0,
5849
+ environment,
5850
+ token: launch.token,
5851
+ continueSession: launch.continueSession
5852
+ };
5994
5853
  }
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;
5854
+ /**
5855
+ * Remote-side worker bridge started via `rivus worker-bridge --stdio`: runs local workspace preparation and the local
5856
+ * Herdr executor on the remote machine, while proxying all local `worker-tools.sock` callbacks back over stdio.
5857
+ */
5858
+ async function runWorkerBridgeServer(options) {
5859
+ await mkdir(options.stateRoot, {
5860
+ recursive: true,
5861
+ mode: 448
6000
5862
  });
6001
- if ("error" in parsed) return Effect.sync(() => {
6002
- options.stderr.write(renderRivusAudioCliArgumentError(parsed.error));
6003
- return 1;
5863
+ await chmod(options.stateRoot, 448);
5864
+ const programs = await options.prepareWorkerPrograms(options.stateRoot, options.mcpPath, options.env.PATH ?? "");
5865
+ const remoteBaseEnv = pickBaseEnvironment(options.env);
5866
+ const workerSocketPath = join(options.stateRoot, "worker-tools.sock");
5867
+ const profiles = /* @__PURE__ */ new Map();
5868
+ const executor = createHerdrWorkerExecutor({
5869
+ directory: join(options.stateRoot, "executions"),
5870
+ client: createHerdrSocketClient([], 5e3, options.herdrRoot),
5871
+ profile: (id) => {
5872
+ const profile = profiles.get(id);
5873
+ if (profile === void 0) throw new Error(`Unknown Herdr worker: ${id}`);
5874
+ return profile;
5875
+ },
5876
+ mcpPath: options.mcpPath,
5877
+ workerPath: workerSocketPath
6004
5878
  });
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;
5879
+ function bindLaunch(profile, launch) {
5880
+ profiles.set(profile.id, profile);
5881
+ return localizeLaunch(launch, remoteBaseEnv, programs, workerSocketPath);
5882
+ }
5883
+ let resolveDone;
5884
+ const done = new Promise((resolve) => {
5885
+ resolveDone = resolve;
6030
5886
  });
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);
5887
+ const channel = createStdioRpcChannel({
5888
+ input: options.input,
5889
+ output: options.output,
5890
+ onClose: () => resolveDone(),
5891
+ onRequest: async (method, params, writeChunk) => {
5892
+ switch (method) {
5893
+ case "bridge.hello":
5894
+ decodeHelloParams(params);
5895
+ return { protocol: 1 };
5896
+ case "bridge.ping": {
5897
+ const { ts } = decodePingParams(params);
5898
+ return { ts };
5899
+ }
5900
+ case "workspace.prepare": {
5901
+ const input = decodeWorkspacePrepareParams(params);
5902
+ try {
5903
+ return await options.prepareWorkspace({
5904
+ root: options.workspaceRoot,
5905
+ prepare: input.prepare ?? void 0,
5906
+ shortName: input.shortName,
5907
+ taskId: input.taskId,
5908
+ environment: {
5909
+ ...remoteBaseEnv,
5910
+ ...input.environment,
5911
+ PATH: programs.environment.PATH
5912
+ },
5913
+ allowCreate: input.allowCreate
5914
+ });
5915
+ } catch (error) {
5916
+ const failure = options.readWorkspacePreparationFailure(error);
5917
+ if (failure !== void 0) throw new BridgeRpcError("workspace_preparation_error", failure.message, {
5918
+ path: failure.path,
5919
+ stage: failure.stage
5920
+ });
5921
+ throw error;
5922
+ }
5923
+ }
5924
+ case "workspace.readFile": {
5925
+ const { shortName, path, maxBytes } = decodeWorkspaceReadFileParams(params);
5926
+ const file = await options.readTaskFile(options.workspaceRoot, shortName, path, maxBytes);
5927
+ const bytes = Buffer.from(file.content.buffer, file.content.byteOffset, file.content.byteLength);
5928
+ let offset = 0;
5929
+ while (bytes.length - offset > FILE_CHUNK_BYTES) {
5930
+ await writeChunk(bytes.toString("base64", offset, offset + FILE_CHUNK_BYTES));
5931
+ offset += FILE_CHUNK_BYTES;
5932
+ }
5933
+ return {
5934
+ name: file.name,
5935
+ contentBase64: bytes.toString("base64", offset),
5936
+ ...offset > 0 ? { size: bytes.length } : {}
5937
+ };
5938
+ }
5939
+ case "worker.available": {
5940
+ const { profile } = decodeWorkerAvailableParams(params);
5941
+ profiles.set(profile.id, profile);
5942
+ return executor.available(profile.id, AbortSignal.timeout(8e3)).catch(() => false);
5943
+ }
5944
+ case "worker.start": {
5945
+ const { profile, launch, backend } = decodeWorkerStartParams(params);
5946
+ return await executor.start(bindLaunch(profile, launch), backend ?? void 0);
5947
+ }
5948
+ case "worker.deliver": {
5949
+ const { profile, execution, backend, text } = decodeWorkerDeliverParams(params);
5950
+ return await executor.deliver({
5951
+ execution: bindLaunch(profile, execution),
5952
+ backend,
5953
+ text
5954
+ });
5955
+ }
5956
+ case "worker.observe": {
5957
+ const { profile, launch, backend } = decodeWorkerBackendParams(params);
5958
+ return await executor.observe(bindLaunch(profile, launch), backend) ?? null;
5959
+ }
5960
+ case "worker.readScreen": {
5961
+ const { profile, launch, backend } = decodeWorkerBackendParams(params);
5962
+ return await executor.readScreen(bindLaunch(profile, launch), backend) ?? null;
5963
+ }
5964
+ case "worker.readTerminal": {
5965
+ const { profile, launch, backend, state } = decodeWorkerReadTerminalParams(params);
5966
+ return await executor.readTerminal(bindLaunch(profile, launch), backend, state) ?? null;
5967
+ }
5968
+ case "worker.pressKey": {
5969
+ const { profile, launch, backend, key } = decodeWorkerPressKeyParams(params);
5970
+ const pressed = await executor.pressKey(bindLaunch(profile, launch), backend, key);
5971
+ return {
5972
+ pressed: pressed.pressed,
5973
+ screen: pressed.screen ?? null
5974
+ };
5975
+ }
5976
+ case "worker.readMenu": {
5977
+ const { profile, launch, backend } = decodeWorkerBackendParams(params);
5978
+ const menu = await executor.readMenu(bindLaunch(profile, launch), backend);
5979
+ return menu === void 0 ? null : {
5980
+ signature: menu.signature,
5981
+ text: menu.text,
5982
+ ...menu.workspaceTrust && { workspaceTrust: menu.workspaceTrust }
5983
+ };
5984
+ }
5985
+ case "worker.chooseMenu": {
5986
+ const { profile, launch, backend, signature, number, claimId } = decodeWorkerChooseMenuParams(params);
5987
+ return await executor.chooseMenu(bindLaunch(profile, launch), backend, signature, number, async () => {
5988
+ try {
5989
+ const claimed = await channel.request("worker.claim_menu", { claimId }, { timeoutMs: 1e4 });
5990
+ return decodeMenuClaimResult(claimed);
5991
+ } catch {
5992
+ return false;
5993
+ }
5994
+ });
5995
+ }
5996
+ case "worker.stop": {
5997
+ const { profile, launch } = decodeWorkerBackendParams(params);
5998
+ await executor.stop(bindLaunch(profile, launch));
5999
+ return null;
6000
+ }
6001
+ case "worker.retire": {
6002
+ const { profile, launch, backend } = decodeWorkerRetireParams(params);
6003
+ await executor.retire(bindLaunch(profile, launch), backend ?? void 0);
6004
+ return null;
6005
+ }
6006
+ default: throw new BridgeRpcError("unknown_method", `Unknown worker bridge method: ${method}`);
6062
6007
  }
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)));
6008
+ }
6077
6009
  });
6010
+ const workerSocket = await openLocalJsonSocket(workerSocketPath, (frame) => channel.request("worker.tool_request", { frame }, { timeoutMs: 15e3 }));
6011
+ const onAbort = () => channel.close("Worker bridge aborted");
6012
+ if (options.signal?.aborted) onAbort();
6013
+ else options.signal?.addEventListener("abort", onAbort, { once: true });
6014
+ try {
6015
+ await done;
6016
+ } finally {
6017
+ options.signal?.removeEventListener("abort", onAbort);
6018
+ channel.close("Worker bridge shutting down");
6019
+ await workerSocket.close().catch(() => {});
6020
+ await executor.close().catch(() => {});
6021
+ }
6078
6022
  }
6079
- function runDoctorCommand(options) {
6080
- const parsed = parseRivusDoctorArguments(options.argv.slice(1));
6081
- if (parsed.help) return Effect.sync(() => {
6082
- options.stdout.write(renderRivusDoctorUsage());
6023
+ //#endregion
6024
+ //#region src/bootstrap/cli/worker-bridge-command.ts
6025
+ function runWorkerBridgeCommand(options, bridgeStreams) {
6026
+ const args = options.argv.slice(1);
6027
+ if (args.length === 1 && (args[0] === "--help" || args[0] === "-h")) return Effect.sync(() => {
6028
+ options.stdout.write(workerBridgeUsage);
6083
6029
  return 0;
6084
6030
  });
6085
- if (parsed.error) {
6086
- const error = parsed.error;
6087
- return Effect.sync(() => {
6088
- options.stderr.write(renderRivusDoctorArgumentError(error));
6089
- return 1;
6031
+ return Effect.gen(function* () {
6032
+ const command = yield* Effect.try({
6033
+ try: () => parseWorkerBridgeArguments(args),
6034
+ catch: (error) => error
6090
6035
  });
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)));
6036
+ const sdk = yield* Effect.tryPromise({
6037
+ try: () => import("./dist.js"),
6038
+ catch: (error) => error
6039
+ });
6040
+ const streams = bridgeStreams ?? {
6041
+ input: process.stdin,
6042
+ output: process.stdout
6043
+ };
6044
+ const mcpPath = join(dirname(gatewayPackageManifestPath), "dist", "mcp.js");
6045
+ const controller = new AbortController();
6046
+ const onSignal = () => controller.abort();
6047
+ options.signalSource.on("SIGINT", onSignal);
6048
+ options.signalSource.on("SIGTERM", onSignal);
6049
+ yield* Effect.tryPromise({
6050
+ try: () => runWorkerBridgeServer({
6051
+ herdrRoot: command.herdrRoot,
6052
+ workspaceRoot: command.workspaceRoot,
6053
+ stateRoot: command.stateRoot,
6054
+ mcpPath,
6055
+ env: options.env,
6056
+ input: streams.input,
6057
+ output: streams.output,
6058
+ signal: controller.signal,
6059
+ prepareWorkerPrograms,
6060
+ prepareWorkspace: (input) => sdk.prepareWorkspace({
6061
+ ...input,
6062
+ git: sdk.createGitClient(),
6063
+ commands: sdk.createCommandRunner()
6064
+ }),
6065
+ readTaskFile: sdk.readTaskFile,
6066
+ readWorkspacePreparationFailure: (error) => error instanceof sdk.WorkspacePreparationError ? {
6067
+ path: error.path,
6068
+ stage: error.stage,
6069
+ message: error.message
6070
+ } : void 0
6071
+ }),
6072
+ catch: (error) => error
6073
+ });
6074
+ return 0;
6075
+ }).pipe(Effect.catch((error) => Effect.sync(() => {
6076
+ options.stderr.write(renderRivusCliError(error));
6077
+ return 1;
6078
+ })));
6105
6079
  }
6080
+ //#endregion
6081
+ //#region src/bootstrap/cli/rivus-cli.ts
6106
6082
  function runRivusCli(options) {
6107
6083
  const command = options.argv[0];
6108
6084
  if (command === "setup") return runSetupCommand(options);
@@ -6110,27 +6086,13 @@ function runRivusCli(options) {
6110
6086
  if (command === "start") return runHomeDaemonCommand(options, "start", []);
6111
6087
  if (command === "status") return runHomeDaemonCommand(options, "status", ["--status"]);
6112
6088
  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
- }
6089
+ if (command === "recovery") return runRecoveryCommand(options);
6131
6090
  if (command === "init") return runInitCommand(options);
6132
6091
  if (command === "doctor") return runDoctorCommand(options);
6133
6092
  if (command === "model") return runModelCommand(options);
6093
+ if (command === "superagent") return runSuperagentCommand(options);
6094
+ if (command === "task") return runTaskCommand(options);
6095
+ if (command === "worker-bridge") return runWorkerBridgeCommand(options);
6134
6096
  if (command === "audio") return runAudioCommand(options);
6135
6097
  if (command && !command.startsWith("-")) return Effect.sync(() => {
6136
6098
  options.stderr.write(renderRivusCliUnknownCommand(command));
@@ -6155,6 +6117,7 @@ function runRivusNodeEntrypoint(options) {
6155
6117
  env: options.env,
6156
6118
  ...options.exitAfterSignal !== void 0 ? { exitAfterSignal: options.exitAfterSignal } : {},
6157
6119
  homeApi: createNodeRivusHome({ deploymentInspector: createRivusHomeDeploymentInspector({
6120
+ checkSuperagents: checkSuperagentConfigurations,
6158
6121
  isModelManagementEnabled: parseRivusModelManagementEnabled,
6159
6122
  packageManifestPath: gatewayPackageManifestPath
6160
6123
  }) }),
@@ -6162,6 +6125,7 @@ function runRivusNodeEntrypoint(options) {
6162
6125
  loadBootstrap: (specifier) => import(toImportSpecifier(specifier)),
6163
6126
  nodeExecutable: process.execPath,
6164
6127
  nodeVersion: process.versions.node,
6128
+ readStdin: () => text(process.stdin),
6165
6129
  upgradeHost: {
6166
6130
  platform: process.platform,
6167
6131
  lockPlatform: createNodePlatform()