@rivus/gateway 0.23.0 → 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,5 +1,6 @@
1
- import { $ as validateTrustedModulePath, A as parseSuperagentArguments, B as createRivusModelManagementWireRequest, D as superagentControlSocketPath, G as renderRivusModelCliArgumentError, K as renderRivusModelCliHelp, L as isRivusModelManagementEnabled, M as superagentUsage, P as parseRivusModelManagementEnabled, Q as resolveNodeRivusPluginModulePath, R as resolveRivusModelSocketPath, T as deploymentStateDirectoryFromEnv, W as parseRivusModelCliArguments, Z as createNodeRivusPluginModuleLoader, _t as createRuntimeCache, a as readRivusAudioInstalledRelease, at as gatewayPackageManifestPath, bt as deepFreeze, c as withoutRivusHomeDeployment, ct as loadMergedLocalEnvFile, dt as toError, et as findTrustedPackageRoot, gt as errorMessage, ht as narrowBackgroundSessionDefinition, i as installRivusAudioTranscriber, it as gatewayPackageDirectory, j as superagentRejectionExitCode, lt as resolveAcpRuntimeEnvironment, mt as createBackgroundSessionToolContracts, n as runRivusAudioProcess, nt as RIVUS_RELEASE_DESCRIPTOR, o as readRivusAudioStatus, q as checkSuperagentConfigurations, rt as gatewayAudioTranscriberAssetDirectory, s as RIVUS_HOME_DEPLOYMENT_ENV, st as gatewayTemplateDirectory, t as runRivusAudioPassthroughProcess, tt as loadRivusDeploymentManifest, u as runRivusRecoveryCliCommand, ut as resolveFeishuEndpointCredentials, vt as disposeRuntimeCacheEntries, yt as invokeRuntimeControl } from "./rivus-audio-process.js";
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
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";
3
4
  import { findPackageJSON, registerHooks } from "node:module";
4
5
  import { createSha256Digest, createStableId } from "@rivus/platform/identity";
5
6
  import { Cause, Context, Deferred, Effect, Exit, Layer, Option, Result, Schema, SchemaGetter, Semaphore } from "effect";
@@ -13,14 +14,14 @@ import { readPersistenceFile, writeAtomicTextFile } from "@rivus/platform/persis
13
14
  import { homedir } from "node:os";
14
15
  import { text } from "node:stream/consumers";
15
16
  import { fileURLToPath, pathToFileURL } from "node:url";
16
- import { spawn } from "node:child_process";
17
- import { isDeepStrictEqual } from "node:util";
18
17
  import { compare, minVersion, parse, satisfies, valid } from "semver";
19
18
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
20
19
  import { randomUUID } from "node:crypto";
21
20
  import { createNodePlatform } from "@rivus/agent-kit/node";
22
21
  import { acquireProcessLock } from "@rivus/agent-kit-collab/process-lock";
23
22
  import { constants as constants$1, realpathSync } from "node:fs";
23
+ import { spawn } from "node:child_process";
24
+ import { isDeepStrictEqual } from "node:util";
24
25
  import { parse as parse$1, stringify } from "yaml";
25
26
  import { readHookEvent } from "@rivus/agent-kit/harness/events";
26
27
  //#region src/agent-host/application/ports.ts
@@ -28,6 +29,7 @@ var AgentInstanceIdentity = class extends Context.Service()("@rivus/gateway/agen
28
29
  var AgentHostRuntimes = class extends Context.Service()("@rivus/gateway/agent-host/AgentHostRuntimes") {};
29
30
  //#endregion
30
31
  //#region src/agent-host/application/services/agent-instance-registry.ts
32
+ /** @internal */
31
33
  var AgentInstanceConflict = class extends Error {
32
34
  name = "AgentInstanceConflict";
33
35
  };
@@ -102,6 +104,7 @@ function makeAgentInstanceRegistry(options = {}) {
102
104
  }
103
105
  //#endregion
104
106
  //#region src/agent-host/application/use-cases/agent-host.ts
107
+ /** @internal */
105
108
  var InvalidAgentHostBinding = class extends Error {
106
109
  name = "InvalidAgentHostBinding";
107
110
  };
@@ -208,9 +211,11 @@ function createEffectRuntimePool(options) {
208
211
  }
209
212
  //#endregion
210
213
  //#region src/agent-host/infra/adapters/effect-agent-runtime-pool.ts
214
+ /** @internal */
211
215
  var AgentInstanceBusy = class extends Error {
212
216
  name = "AgentInstanceBusy";
213
217
  };
218
+ /** @internal */
214
219
  var AgentRuntimeDisposed = class extends Error {
215
220
  name = "AgentRuntimeDisposed";
216
221
  };
@@ -652,6 +657,7 @@ function resolveRivusAgentDefinition$1(runtime, catalog, deployment, providers)
652
657
  tools
653
658
  }), runtimeContributions);
654
659
  }
660
+ /** @internal */
655
661
  function createRivusAgentDefinitionResolver(runtime, providers) {
656
662
  return Object.freeze({ resolve: (catalog, deployment) => resolveRivusAgentDefinition$1(runtime, catalog, deployment, providers) });
657
663
  }
@@ -727,6 +733,7 @@ function validateRivusProjectSpaceDeployment(declaration) {
727
733
  sources.add(source);
728
734
  }
729
735
  }
736
+ /** @internal */
730
737
  function validateRivusProjectSpaceDeployments(declarations) {
731
738
  const projectSpaceIds = /* @__PURE__ */ new Set();
732
739
  for (const declaration of declarations) {
@@ -792,7 +799,8 @@ function validateRivusDeploymentManifest(manifest) {
792
799
  }
793
800
  const boundEndpoints = /* @__PURE__ */ new Set();
794
801
  for (const id of manifest.superagent?.endpointIds ?? []) {
795
- if (!superagentEndpoints.has(id) || boundEndpoints.has(id)) throw new Error(`Superagent endpoint must reference one mode=superagent endpoint: ${id}`);
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}`);
796
804
  boundEndpoints.add(id);
797
805
  }
798
806
  for (const id of superagentEndpoints) if (!boundEndpoints.has(id)) throw new Error(`Superagent endpoint has no source: ${id}`);
@@ -1143,6 +1151,7 @@ function prepareDeployment(input) {
1143
1151
  }
1144
1152
  //#endregion
1145
1153
  //#region src/deployment/application/use-cases/deployment-control.ts
1154
+ /** @internal */
1146
1155
  var RivusDeploymentReadinessError = class extends Error {
1147
1156
  endpointIds;
1148
1157
  name = "RivusDeploymentReadinessError";
@@ -1269,6 +1278,9 @@ function isSlotReady(slot) {
1269
1278
  }
1270
1279
  function makeDeploymentControl(input) {
1271
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));
1272
1284
  const allSlots = [
1273
1285
  ...input.endpointSlots,
1274
1286
  ...input.automationSlots,
@@ -1299,6 +1311,27 @@ function makeDeploymentControl(input) {
1299
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}`));
1300
1312
  return input.host.handleEndpoint(endpointId, request);
1301
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
+ });
1302
1335
  const isReady = () => allSlots.every((slot) => isSlotReady(slot));
1303
1336
  const readinessFailure = () => {
1304
1337
  const endpointIds = input.endpointSlots.filter((slot) => slot.definition.enabled && slot.definition.required && !isSlotReady(slot)).map((slot) => slot.definition.id);
@@ -1347,29 +1380,14 @@ function makeDeploymentControl(input) {
1347
1380
  lifecycle = transitionDeploymentControlLifecycle(lifecycle, "starting");
1348
1381
  return Effect.gen(function* () {
1349
1382
  let degraded = input.deployment.plugins.some(({ status: pluginStatus }) => pluginStatus === "failed");
1350
- for (const slot of input.endpointSlots) degraded = (yield* startSlot(slot, slot.agentEnabled, `endpoint ${slot.definition.id}`, () => Effect.gen(function* () {
1351
- const instance = yield* input.host.resolveEndpoint(slot.definition.id);
1352
- const agentDefinition = input.definitions.get(slot.definition.agentId);
1353
- const projectSpace = agentDefinition?.projectSpaceId ? input.projectSpaces.get(agentDefinition.projectSpaceId) : void 0;
1354
- return yield* input.endpointFactory.create({
1355
- agentId: slot.definition.agentId,
1356
- cancel: (request) => input.host.cancelEndpoint(slot.definition.id, request),
1357
- definition: slot.definition,
1358
- endpointId: slot.definition.id,
1359
- handle: (request) => handleEndpoint(slot.definition.id, request),
1360
- instanceId: instance.instanceId,
1361
- ...agentDefinition ? { runtimeDefinition: agentDefinition } : {},
1362
- ...projectSpace ? { projectSpace } : {},
1363
- ...agentDefinition?.projectSpaceId ? { projectSpaceId: agentDefinition.projectSpaceId } : {},
1364
- steer: (request) => input.host.steerEndpoint(slot.definition.id, request)
1365
- });
1366
- }))) || degraded;
1383
+ degraded = (yield* startEndpoints(otherEndpoints)) || degraded;
1367
1384
  let superagentFailure;
1368
1385
  if (input.superagent !== void 0) {
1369
1386
  const started = yield* Effect.exit(input.superagent.start());
1370
1387
  if (Exit.isFailure(started)) superagentFailure = Cause.squash(started.cause);
1371
1388
  degraded = Exit.isFailure(started) || started.value || degraded;
1372
1389
  }
1390
+ degraded = (yield* startEndpoints(sharedEndpoints)) || degraded;
1373
1391
  for (const slot of input.automationSlots) {
1374
1392
  const resolvedDefinition = slot.resolvedDefinition;
1375
1393
  const deliverySlot = endpointById.get(slot.definition.delivery.endpointId);
@@ -1429,11 +1447,12 @@ function makeDeploymentControl(input) {
1429
1447
  const errors = [];
1430
1448
  if (input.backgroundSessionSlot) yield* stopSlots([input.backgroundSessionSlot], errors);
1431
1449
  yield* stopSlots(input.automationSlots, errors);
1450
+ yield* stopSlots(sharedEndpoints, errors);
1432
1451
  if (input.superagent !== void 0) {
1433
1452
  const result = yield* Effect.exit(input.superagent.stop());
1434
1453
  if (Exit.isFailure(result)) errors.push(Cause.squash(result.cause));
1435
1454
  }
1436
- yield* stopSlots(input.endpointSlots, errors);
1455
+ yield* stopSlots(otherEndpoints, errors);
1437
1456
  const hostExit = yield* Effect.exit(input.host.dispose());
1438
1457
  if (Exit.isFailure(hostExit)) errors.push(Cause.squash(hostExit.cause));
1439
1458
  lifecycle = transitionDeploymentControlLifecycle(lifecycle, errors.length === 0 ? "stopped" : "cleanup-required");
@@ -1455,6 +1474,70 @@ function createRivusDeploymentControl(input) {
1455
1474
  });
1456
1475
  }
1457
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
1458
1541
  //#region src/home/infra/adapters/config/rivus-home-config.ts
1459
1542
  /**
1460
1543
  * Config fields are read tolerantly (authoring guide, Validation): a field whose value has the wrong type is
@@ -1532,70 +1615,6 @@ function loadRivusHome(directoryPath) {
1532
1615
  });
1533
1616
  }
1534
1617
  //#endregion
1535
- //#region src/home/infra/adapters/doctor/rivus-home-doctor.ts
1536
- function checkNodeRuntime(version) {
1537
- const range = "^24.11.0 || ^26.13.1";
1538
- const supported = satisfies(version, range);
1539
- return {
1540
- name: "node",
1541
- status: supported ? "pass" : "fail",
1542
- message: supported ? `Node.js ${version} satisfies ${range}` : `Node.js ${range} is required; current version is ${version}`
1543
- };
1544
- }
1545
- function checkWorkspace(home, findMissingWorkspacePaths) {
1546
- return findMissingWorkspacePaths(home).pipe(Effect.map((missing) => missing.length === 0 ? {
1547
- message: "Workspace instructions, Memory, Skills, and work directories are present",
1548
- name: "workspace",
1549
- status: "pass"
1550
- } : {
1551
- message: `Workspace paths are missing: ${missing.join(", ")}`,
1552
- name: "workspace",
1553
- status: "fail"
1554
- }));
1555
- }
1556
- function blockedCheck(name, owner) {
1557
- return {
1558
- message: `${owner} cannot be checked until config.json is valid`,
1559
- name,
1560
- status: "fail"
1561
- };
1562
- }
1563
- function report(directory, checks) {
1564
- return {
1565
- checks,
1566
- directory,
1567
- ready: checks.every(({ status }) => status === "pass")
1568
- };
1569
- }
1570
- function diagnoseRivusHome(input, options) {
1571
- return Effect.gen(function* () {
1572
- const checks = [checkNodeRuntime(input.nodeVersion)];
1573
- const loaded = yield* options.load(input.directory).pipe(Effect.result);
1574
- if (Result.isFailure(loaded)) {
1575
- checks.push({
1576
- message: `Rivus Home is invalid: ${loaded.failure.message}`,
1577
- name: "home",
1578
- status: "fail"
1579
- }, blockedCheck("workspace", "Workspace"), blockedCheck("manifest", "manifest"), blockedCheck("modules", "modules"), blockedCheck("credentials", "credentials"));
1580
- return report(input.directory, checks);
1581
- }
1582
- const home = loaded.success;
1583
- checks.push({
1584
- message: "config.json is valid and contained in Rivus Home",
1585
- name: "home",
1586
- status: "pass"
1587
- });
1588
- checks.push(yield* checkWorkspace(home, options.findMissingWorkspacePaths));
1589
- const deployment = yield* options.deploymentInspector.inspect({
1590
- env: input.env,
1591
- ...input.envFilePath ? { envFilePath: input.envFilePath } : {},
1592
- home
1593
- });
1594
- checks.push(deployment.manifest, deployment.modules, deployment.credentials);
1595
- return report(input.directory, checks);
1596
- });
1597
- }
1598
- //#endregion
1599
1618
  //#region src/home/infra/adapters/setup/rivus-home-layout.ts
1600
1619
  const HOME_DIRECTORIES = Object.freeze([
1601
1620
  "logs",
@@ -2428,7 +2447,10 @@ const RELEASE_PACKAGES = [
2428
2447
  ];
2429
2448
  let installed = false;
2430
2449
  let resolvingReleasePackage = false;
2431
- /** 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
+ */
2432
2454
  function releasePackageOf(specifier) {
2433
2455
  return RELEASE_PACKAGES.find((name) => specifier === name || specifier.startsWith(`${name}/`));
2434
2456
  }
@@ -2446,6 +2468,7 @@ function copyOutsideRoots(path, releaseRoots) {
2446
2468
  * recognized by its `node_modules/<name>/` directory, which also matches pnpm's `.pnpm/.../node_modules/<name>/`.
2447
2469
  * A match is rechecked by real path, because `--preserve-symlinks` reports files of the running copy by link paths
2448
2470
  * while the running roots are real paths.
2471
+ * @internal
2449
2472
  */
2450
2473
  function foreignReleasePackageOf(path, releaseRoots) {
2451
2474
  if (!copyOutsideRoots(path, releaseRoots)) return;
@@ -2516,6 +2539,7 @@ const RIVUS_CLI_USAGE = `Usage:
2516
2539
  rivus model <status|set|rollback> ...
2517
2540
  rivus superagent <command> ...
2518
2541
  rivus task <show|report|call> ...
2542
+ rivus worker-bridge --stdio --herdr-root <path> --workspace-root <path> --state-root <path>
2519
2543
  rivus audio <install|status|transcribe> ...
2520
2544
  rivus --bootstrap <module> [--manifest <rivus.config.json>] [options]
2521
2545
 
@@ -2532,6 +2556,8 @@ Commands:
2532
2556
  model Query or change the managed default model through the current Home
2533
2557
  superagent Inspect or control the Superagent and its tasks
2534
2558
  task Call tools for the current worker execution
2559
+ worker-bridge
2560
+ Serve a remote Superagent worker bridge over standard input and output
2535
2561
  audio Install, inspect, or run the managed audio transcriber of the current Home
2536
2562
 
2537
2563
  Run rivus --help for the complete daemon option list.
@@ -3134,6 +3160,49 @@ function renderRivusAudioCliNotInstalled() {
3134
3160
  return "audio transcriber is not installed; run: rivus audio install\n";
3135
3161
  }
3136
3162
  //#endregion
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;
3194
+ }
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");
3203
+ }
3204
+ }
3205
+ //#endregion
3137
3206
  //#region src/cli/lib/upgrade/upgrade-cli-protocol.ts
3138
3207
  const UPGRADE_USAGE = `Usage: rivus upgrade [--json]
3139
3208
 
@@ -3525,7 +3594,10 @@ function superagentTransportError(options, error) {
3525
3594
  }
3526
3595
  //#endregion
3527
3596
  //#region src/bootstrap/cli/audio-command.ts
3528
- /** Runs one parsed `rivus audio` command and returns its exit code; installation failures are thrown. */
3597
+ /**
3598
+ * Runs one parsed `rivus audio` command and returns its exit code; installation failures are thrown.
3599
+ * @internal
3600
+ */
3529
3601
  async function runRivusAudioCliCommand(command, context) {
3530
3602
  if (command.operation === "install") {
3531
3603
  const result = await installRivusAudioTranscriber({
@@ -5735,6 +5807,277 @@ function runUpgradeCommand(options) {
5735
5807
  })));
5736
5808
  }
5737
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
+ }));
5825
+ }
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
+ };
5853
+ }
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
5862
+ });
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
5878
+ });
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;
5886
+ });
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}`);
6007
+ }
6008
+ }
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
+ }
6022
+ }
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);
6029
+ return 0;
6030
+ });
6031
+ return Effect.gen(function* () {
6032
+ const command = yield* Effect.try({
6033
+ try: () => parseWorkerBridgeArguments(args),
6034
+ catch: (error) => error
6035
+ });
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
+ })));
6079
+ }
6080
+ //#endregion
5738
6081
  //#region src/bootstrap/cli/rivus-cli.ts
5739
6082
  function runRivusCli(options) {
5740
6083
  const command = options.argv[0];
@@ -5749,6 +6092,7 @@ function runRivusCli(options) {
5749
6092
  if (command === "model") return runModelCommand(options);
5750
6093
  if (command === "superagent") return runSuperagentCommand(options);
5751
6094
  if (command === "task") return runTaskCommand(options);
6095
+ if (command === "worker-bridge") return runWorkerBridgeCommand(options);
5752
6096
  if (command === "audio") return runAudioCommand(options);
5753
6097
  if (command && !command.startsWith("-")) return Effect.sync(() => {
5754
6098
  options.stderr.write(renderRivusCliUnknownCommand(command));