@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.
@@ -0,0 +1,233 @@
1
+ import { Schema } from "effect";
2
+ import { Buffer } from "node:buffer";
3
+ import { createConnection } from "node:net";
4
+ //#region src/agent-host/infra/adapters/local-json-socket.ts
5
+ const limit = 131072;
6
+ const decodeResponse = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Union([Schema.Struct({
7
+ ok: Schema.Literal(true),
8
+ value: Schema.Json
9
+ }), Schema.Struct({
10
+ ok: Schema.Literal(false),
11
+ error: Schema.String,
12
+ code: Schema.optionalKey(Schema.String)
13
+ })])));
14
+ function readLocalJsonFrame(socket, receive) {
15
+ let buffer = Buffer.alloc(0);
16
+ function onData(chunk) {
17
+ buffer = Buffer.concat([buffer, chunk]);
18
+ const end = buffer.indexOf(10);
19
+ if (buffer.length > limit) socket.destroy(/* @__PURE__ */ new Error("Rivus socket frame is too large"));
20
+ else if (end !== -1) {
21
+ socket.off("data", onData);
22
+ receive(buffer.subarray(0, end).toString("utf8"));
23
+ }
24
+ }
25
+ socket.on("data", onData);
26
+ }
27
+ async function requestLocalJson(path, input, timeoutMs = 1e4) {
28
+ return new Promise((resolve, reject) => {
29
+ const socket = createConnection(path);
30
+ socket.setTimeout(timeoutMs, () => socket.destroy(/* @__PURE__ */ new Error("Rivus socket request timed out")));
31
+ socket.once("error", reject);
32
+ socket.once("close", () => reject(/* @__PURE__ */ new Error("Rivus socket closed before replying")));
33
+ readLocalJsonFrame(socket, (frame) => {
34
+ try {
35
+ resolve(decodeResponse(frame));
36
+ } catch (error) {
37
+ reject(error);
38
+ } finally {
39
+ socket.destroy();
40
+ }
41
+ });
42
+ socket.once("connect", () => socket.write(JSON.stringify(input) + "\n"));
43
+ });
44
+ }
45
+ //#endregion
46
+ //#region src/agent-host/infra/adapters/superagent-worker-wire.ts
47
+ const name = Schema.Literals([
48
+ "task_status",
49
+ "task_show",
50
+ "task_report",
51
+ "task_ask",
52
+ "task_read",
53
+ "task_follow",
54
+ "task_unrelated",
55
+ "task_followup",
56
+ "task_ack",
57
+ "task_handback"
58
+ ]);
59
+ const capability = {
60
+ execution: Schema.NonEmptyString,
61
+ token: Schema.NonEmptyString
62
+ };
63
+ const workerActivity = Schema.Struct({
64
+ phase: Schema.Literals([
65
+ "activity",
66
+ "blocked",
67
+ "finish"
68
+ ]),
69
+ blocker: Schema.optionalKey(Schema.Literals([
70
+ "permission",
71
+ "question",
72
+ "elicitation"
73
+ ])),
74
+ tool: Schema.optionalKey(Schema.NonEmptyString),
75
+ at: Schema.Int,
76
+ turnId: Schema.optionalKey(Schema.NonEmptyString)
77
+ });
78
+ const decodeWorkerRequest = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Union([
79
+ Schema.Struct({
80
+ operation: Schema.Literal("list"),
81
+ ...capability
82
+ }),
83
+ Schema.Struct({
84
+ operation: Schema.Literal("credential"),
85
+ repo: Schema.optionalKey(Schema.NonEmptyString),
86
+ ...capability
87
+ }),
88
+ Schema.Struct({
89
+ operation: Schema.Literal("call"),
90
+ name,
91
+ input: Schema.Json,
92
+ ...capability
93
+ }),
94
+ Schema.Struct({
95
+ operation: Schema.Literal("event"),
96
+ activity: workerActivity,
97
+ question: Schema.optionalKey(Schema.NonEmptyString),
98
+ ...capability
99
+ })
100
+ ])), { onExcessProperty: "error" });
101
+ const superagentWorkerTools = [
102
+ {
103
+ name: "task_status",
104
+ description: "Read this assignment and its most recent report",
105
+ properties: {},
106
+ required: []
107
+ },
108
+ {
109
+ name: "task_show",
110
+ description: "Read your original task request, pending inputs, and mandate",
111
+ properties: {},
112
+ required: []
113
+ },
114
+ {
115
+ name: "task_ask",
116
+ description: "Ask one question that requires a human answer. Reuse the exact question when retrying.",
117
+ properties: { question: { type: "string" } },
118
+ required: ["question"]
119
+ },
120
+ {
121
+ name: "task_report",
122
+ description: "Report progress, a question, or completion for this assignment. List the URLs of what you published, such as a pull request you opened, in links.",
123
+ properties: {
124
+ id: { type: "string" },
125
+ state: { enum: [
126
+ "progress",
127
+ "waiting",
128
+ "ready",
129
+ "blocked",
130
+ "failed",
131
+ "dropped"
132
+ ] },
133
+ summary: { type: "string" },
134
+ progress: {
135
+ type: "object",
136
+ properties: {
137
+ done: { type: "string" },
138
+ remaining: { type: "string" },
139
+ branch: { type: "string" }
140
+ },
141
+ required: ["done", "remaining"],
142
+ additionalProperties: false
143
+ },
144
+ question: { type: "string" },
145
+ replyTo: { type: "string" },
146
+ file: {
147
+ type: "string",
148
+ description: "Requested file relative to the task workspace; use with state ready and replyTo."
149
+ },
150
+ links: {
151
+ type: "array",
152
+ items: { type: "string" }
153
+ }
154
+ },
155
+ required: [
156
+ "id",
157
+ "state",
158
+ "summary"
159
+ ]
160
+ },
161
+ {
162
+ name: "task_read",
163
+ description: "Read an authorized source event by triggerId or a subscribed thread by threadKey. Pass the returned before or sourceBefore cursor as before for another page. Source history is reference only.",
164
+ properties: {
165
+ triggerId: { type: "string" },
166
+ threadKey: { type: "string" },
167
+ before: { type: "string" }
168
+ },
169
+ required: []
170
+ },
171
+ {
172
+ name: "task_follow",
173
+ description: "Follow a visible source thread as context for your assignment",
174
+ properties: { threadKey: { type: "string" } },
175
+ required: ["threadKey"]
176
+ },
177
+ {
178
+ name: "task_unrelated",
179
+ description: "Remove a context or attached thread from this assignment. Origin and source-managed threads are protected.",
180
+ properties: { threadKey: { type: "string" } },
181
+ required: ["threadKey"]
182
+ },
183
+ {
184
+ name: "task_ack",
185
+ description: "Acknowledge a trusted input belonging to this assignment",
186
+ properties: { triggerId: { type: "string" } },
187
+ required: ["triggerId"]
188
+ },
189
+ {
190
+ name: "task_handback",
191
+ description: "Return an out-of-scope follow-up to the Router",
192
+ properties: { triggerId: { type: "string" } },
193
+ required: ["triggerId"]
194
+ },
195
+ {
196
+ name: "task_followup",
197
+ description: "Arrange a follow-up for this assignment",
198
+ properties: {
199
+ requestId: { type: "string" },
200
+ dueAt: { type: "integer" },
201
+ note: { type: "string" }
202
+ },
203
+ required: [
204
+ "requestId",
205
+ "dueAt",
206
+ "note"
207
+ ]
208
+ }
209
+ ].map(({ name, description, properties, required }) => ({
210
+ name,
211
+ description,
212
+ inputSchema: {
213
+ type: "object",
214
+ properties,
215
+ required,
216
+ additionalProperties: false
217
+ }
218
+ }));
219
+ var SuperagentWorkerRejected = class extends Error {
220
+ name = "SuperagentWorkerRejected";
221
+ };
222
+ async function requestSuperagentWorker(path, capability, input, timeoutMs = 1e4) {
223
+ const response = await requestLocalJson(path, {
224
+ ...input,
225
+ execution: capability.execution,
226
+ token: capability.token
227
+ }, timeoutMs);
228
+ if (!response.ok) throw new SuperagentWorkerRejected(response.error);
229
+ return response.value;
230
+ }
231
+ //#endregion
232
+ export { readLocalJsonFrame as a, superagentWorkerTools as i, decodeWorkerRequest as n, requestLocalJson as o, requestSuperagentWorker as r, SuperagentWorkerRejected as t };
233
+
package/dist/index.d.ts CHANGED
@@ -1,22 +1,14 @@
1
- import { a as RivusHome, i as RivusHomeApi, n as RivusDeploymentBootstrapFactory, r as RivusDaemonEnv } from "./chunks/rivus-deployment-cli-process.js";
2
- import { A as AutomationLineChart, C as AutomationPresentationSection, D as AutomationPresentationTableColumn, E as AutomationPresentationTableCell, O as AutomationPresentationTrend, S as AutomationPresentationKind, T as AutomationPresentationTable, a as RivusAutomationInput, b as AutomationPresentation, c as RivusAutomationTickContext, d as RivusPluginRegistry, f as RIVUS_PLUGIN_API_VERSION, g as RivusAgentProfile, h as RivusAgentDeployment, k as readAutomationPresentation, l as RivusPlugin, m as ResolvedRivusAgentDefinition, o as RivusAutomationOutput, p as RivusPluginManifest, s as RivusAutomationTemplate, u as RivusPluginCatalog, v as RivusAutomationRetryPolicy, w as AutomationPresentationSource, x as AutomationPresentationItem } from "./chunks/public.js";
3
- import { Context, Effect, Layer, Schema } from "effect";
4
- import "@rivus/runtime";
5
- import { createPiModelRuntime } from "@rivus/runtime/pi";
1
+ import { A as AutomationPresentationTrend, C as AutomationPresentationItem, D as AutomationPresentationTable, E as AutomationPresentationSource, M as AutomationLineChart, O as AutomationPresentationTableCell, S as AutomationPresentation, T as AutomationPresentationSection, a as RivusAutomationTickContext, c as RivusPluginRegistry, g as RivusAgentProfile, h as RivusAgentDeployment, i as RivusAutomationTemplate, j as readAutomationPresentation, k as AutomationPresentationTableColumn, l as RIVUS_PLUGIN_API_VERSION, m as ResolvedRivusAgentDefinition, n as RivusAutomationInput, o as RivusPlugin, r as RivusAutomationOutput, s as RivusPluginCatalog, u as RivusPluginManifest, v as RivusAutomationRetryPolicy, w as AutomationPresentationKind } from "./chunks/public.js";
2
+ import { f as RivusDaemonEnv, i as UpgradeResult, m as RivusHome, n as RivusDeploymentBootstrapFactory, p as RivusHomeApi } from "./chunks/rivus-deployment-cli-process.js";
3
+ import { Effect } from "effect";
6
4
  import { ProcessLockPlatform } from "@rivus/agent-kit-collab/process-lock";
7
- //#region src/automation/domain/automation-occurrence/errors/rivus-automation-failure.d.ts
5
+ //#region src/automation/domain/automation-occurrence/errors.d.ts
8
6
  export declare class RivusAutomationFailure extends Error {
9
7
  readonly name = "RivusAutomationFailure";
10
8
  readonly code: string;
11
9
  constructor(code: string, message?: string, options?: ErrorOptions);
12
10
  }
13
11
  //#endregion
14
- //#region src/bootstrap/catalog/rivus-agent-catalog.d.ts
15
- export declare function createRivusPluginCatalog(): RivusPluginCatalog;
16
- export declare function resolveRivusAgentDefinition(catalog: RivusPluginCatalog, deployment: RivusAgentDeployment, options?: {
17
- readonly backgroundSessions?: boolean;
18
- }): ResolvedRivusAgentDefinition;
19
- //#endregion
20
12
  //#region src/model-management/infra/adapters/cli/rivus-model-cli-protocol.d.ts
21
13
  type RivusModelCliCommand = RivusModelCliStatusCommand | RivusModelCliSetCommand | RivusModelCliRollbackCommand;
22
14
  interface RivusModelCliStatusCommand {
@@ -47,6 +39,12 @@ interface RivusModelManagementSocketClient {
47
39
  execute(command: RivusModelCliCommand): Promise<RivusModelCliResponse>;
48
40
  }
49
41
  //#endregion
42
+ //#region src/bootstrap/catalog/rivus-agent-catalog.d.ts
43
+ export declare function createRivusPluginCatalog(): RivusPluginCatalog;
44
+ export declare function resolveRivusAgentDefinition(catalog: RivusPluginCatalog, deployment: RivusAgentDeployment, options?: {
45
+ readonly backgroundSessions?: boolean;
46
+ }): ResolvedRivusAgentDefinition;
47
+ //#endregion
50
48
  //#region src/bootstrap/daemon/process/rivus-daemon-shutdown-controller.d.ts
51
49
  type RivusDaemonShutdownSignal = "SIGINT" | "SIGTERM";
52
50
  interface RivusDaemonSignalSource {
@@ -76,19 +74,6 @@ interface RivusDaemonCliOptions {
76
74
  };
77
75
  }
78
76
  //#endregion
79
- //#region src/upgrade/application/use-cases/run-upgrade.d.ts
80
- interface UpgradeResult {
81
- readonly status: "upgraded" | "current";
82
- readonly version: string;
83
- readonly previousVersion: string;
84
- readonly home: string;
85
- readonly service: string;
86
- readonly pid: number;
87
- readonly executable: string;
88
- readonly backup?: string;
89
- readonly operationId?: string;
90
- }
91
- //#endregion
92
77
  //#region src/bootstrap/upgrade/upgrade-home.d.ts
93
78
  interface UpgradeHomeInvocation {
94
79
  readonly home: RivusHome;
@@ -109,6 +94,8 @@ interface RivusCliOptions extends RivusDaemonCliOptions {
109
94
  readonly homeDirectory: string;
110
95
  readonly nodeExecutable: string;
111
96
  readonly nodeVersion: string;
97
+ /** Reads all of stdin; only `rivus task hook` calls it. */
98
+ readonly readStdin: () => Promise<string>;
112
99
  readonly modelManagementClient?: RivusModelManagementSocketClient;
113
100
  readonly runtimeProcess?: {
114
101
  readonly pid: number;
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
+ import { X as readAutomationPresentation } from "./chunks/superagent-worker-programs.js";
1
2
  import { i as RIVUS_PLUGIN_API_VERSION, n as createRivusPluginCatalog, r as resolveRivusAgentDefinition, t as runRivusNodeEntrypoint } from "./chunks/rivus-node-entrypoint.js";
2
- import { n as RivusAutomationFailure, t as readAutomationPresentation } from "./chunks/automation-presentation.js";
3
+ import { t as RivusAutomationFailure } from "./chunks/errors.js";
3
4
  export { RIVUS_PLUGIN_API_VERSION, RivusAutomationFailure, createRivusPluginCatalog, readAutomationPresentation, resolveRivusAgentDefinition, runRivusNodeEntrypoint };
4
5
 
package/dist/mcp.js CHANGED
@@ -1,5 +1,8 @@
1
+ import { r as requestSuperagentWorker } from "./chunks/superagent-worker-wire.js";
1
2
  import { Schema } from "effect";
3
+ import { isAbsolute } from "node:path";
2
4
  import { pathToFileURL } from "node:url";
5
+ import { spawn } from "node:child_process";
3
6
  //#region src/agent-host/infra/adapters/host-tool-mcp-server.ts
4
7
  const requestSchema = Schema.Struct({
5
8
  jsonrpc: Schema.Literal("2.0"),
@@ -49,24 +52,6 @@ async function runMcpServer(options) {
49
52
  const body = JSON.stringify(message);
50
53
  options.output.write(`${body}\n`);
51
54
  };
52
- const forward = async (operation, body) => {
53
- const response = await options.fetchImplementation(new URL(`/v1/tools/${operation}`, options.controlUrl), {
54
- method: "POST",
55
- headers: {
56
- authorization: `Bearer ${options.controlToken}`,
57
- "content-type": "application/json"
58
- },
59
- body: JSON.stringify({
60
- ...body,
61
- capability: options.capability
62
- })
63
- });
64
- const envelope = await response.json();
65
- if (!Schema.is(controlResponseSchema)(envelope)) throw new RivusHostToolMcpError("invalid host-tool control response");
66
- if (!envelope.ok) throw new RivusHostToolMcpError(envelope.error.message);
67
- if (!response.ok) throw new RivusHostToolMcpError(`host-tool control failed with ${response.status}`);
68
- return envelope.result;
69
- };
70
55
  for await (const message of readMcpMessages(options.input)) {
71
56
  if (!Schema.is(requestSchema)(message)) continue;
72
57
  const { method } = message;
@@ -91,7 +76,7 @@ async function runMcpServer(options) {
91
76
  });
92
77
  break;
93
78
  case "tools/list": {
94
- const tools = await forward("list", {});
79
+ const tools = await options.forward({ operation: "list" });
95
80
  send({
96
81
  jsonrpc: "2.0",
97
82
  id: message.id,
@@ -102,7 +87,8 @@ async function runMcpServer(options) {
102
87
  case "tools/call": {
103
88
  const params = message.params;
104
89
  if (!Schema.is(callParamsSchema)(params)) throw new RivusHostToolMcpError("invalid tools/call parameters");
105
- const result = await forward("call", {
90
+ const result = await options.forward({
91
+ operation: "call",
106
92
  callId: `${Date.now()}:${String(message.id)}`,
107
93
  toolName: params.name,
108
94
  input: params.arguments ?? {}
@@ -149,16 +135,89 @@ function createRivusHostToolMcpServer(options) {
149
135
  name: options.serverName ?? "rivus-host-tools",
150
136
  version: options.serverVersion ?? "1.0.0"
151
137
  };
138
+ const forward = async ({ operation, ...body }) => {
139
+ const response = await fetchImplementation(new URL(`/v1/tools/${operation}`, options.controlUrl), {
140
+ method: "POST",
141
+ headers: {
142
+ authorization: `Bearer ${options.controlToken}`,
143
+ "content-type": "application/json"
144
+ },
145
+ body: JSON.stringify({
146
+ ...body,
147
+ capability: options.capability
148
+ })
149
+ });
150
+ const envelope = await response.json();
151
+ if (!Schema.is(controlResponseSchema)(envelope)) throw new RivusHostToolMcpError("invalid host-tool control response");
152
+ if (!envelope.ok) throw new RivusHostToolMcpError(envelope.error.message);
153
+ if (!response.ok) throw new RivusHostToolMcpError(`host-tool control failed with ${response.status}`);
154
+ return envelope.result;
155
+ };
152
156
  return { run: () => runMcpServer({
153
- capability: options.capability,
154
- controlToken: options.controlToken,
155
- controlUrl: options.controlUrl,
156
- fetchImplementation,
157
+ forward,
157
158
  input,
158
159
  output,
159
160
  serverInfo
160
161
  }) };
161
162
  }
163
+ function createRivusWorkerMcpServer(options) {
164
+ return { run: () => runMcpServer({
165
+ forward: options.forward,
166
+ input: options.input ?? process.stdin,
167
+ output: options.output ?? process.stdout,
168
+ serverInfo: {
169
+ name: "rivus-worker",
170
+ version: RIVUS_HOST_TOOL_MCP_SERVER_VERSION
171
+ }
172
+ }) };
173
+ }
174
+ //#endregion
175
+ //#region src/bootstrap/mcp/superagent-credential-program.ts
176
+ const decodeCredential = Schema.decodeUnknownSync(Schema.NullOr(Schema.Struct({
177
+ username: Schema.String.check(Schema.isPattern(/^[a-z0-9-]+$/iu)),
178
+ token: Schema.String.check(Schema.isPattern(/^[^\r\n]+$/u))
179
+ })));
180
+ async function runSuperagentCredentialProgram(mode, args, capability) {
181
+ if (mode === "--git-credential") {
182
+ if (args[0] !== "get") return 0;
183
+ let frame = "";
184
+ for await (const chunk of process.stdin) {
185
+ frame += String(chunk);
186
+ if (frame.length > 8192) return 1;
187
+ if (frame.includes("\n\n")) break;
188
+ }
189
+ const fields = new URLSearchParams(frame.split("\n").filter(Boolean).map((line) => {
190
+ const equals = line.indexOf("=");
191
+ return equals === -1 ? [line, ""] : [line.slice(0, equals), line.slice(equals + 1)];
192
+ }));
193
+ const repo = fields.get("path")?.replace(/\.git$/u, "");
194
+ if (fields.get("protocol") !== "https" || fields.get("host") !== "github.com" || repo === void 0) return 0;
195
+ const credential = decodeCredential(await requestSuperagentWorker(capability.path, capability, {
196
+ operation: "credential",
197
+ repo
198
+ }));
199
+ if (credential !== null) process.stdout.write(`username=${credential.username}\npassword=${credential.token}\n\n`);
200
+ return 0;
201
+ }
202
+ const [program, ...ghArgs] = args;
203
+ if (program === void 0 || !isAbsolute(program)) return 1;
204
+ const credential = decodeCredential(await requestSuperagentWorker(capability.path, capability, { operation: "credential" }));
205
+ if (credential === null) {
206
+ process.stderr.write("Rivus provides no GitHub credential for this task, so gh cannot run.\n");
207
+ return 1;
208
+ }
209
+ return new Promise((resolve) => {
210
+ const child = spawn(program, ghArgs, {
211
+ env: {
212
+ ...process.env,
213
+ GH_TOKEN: credential.token
214
+ },
215
+ stdio: "inherit"
216
+ });
217
+ child.once("error", () => resolve(1));
218
+ child.once("exit", (code) => resolve(code ?? 1));
219
+ });
220
+ }
162
221
  //#endregion
163
222
  //#region src/bootstrap/mcp/rivus-mcp-entrypoint.ts
164
223
  function requireEnv(name) {
@@ -167,6 +226,32 @@ function requireEnv(name) {
167
226
  return value;
168
227
  }
169
228
  async function runRivusHostToolMcpServer(options = {}) {
229
+ const mode = process.argv[2];
230
+ if (mode === "--git-credential" || mode === "--gh") {
231
+ process.exitCode = await runSuperagentCredentialProgram(mode, process.argv.slice(3), {
232
+ path: requireEnv("RIVUS_WORKER_SOCKET"),
233
+ execution: requireEnv("RIVUS_WORKER_KEY"),
234
+ token: requireEnv("RIVUS_WORKER_TOKEN")
235
+ });
236
+ return;
237
+ }
238
+ if (mode === "--worker") {
239
+ const path = requireEnv("RIVUS_WORKER_SOCKET");
240
+ const capability = {
241
+ execution: requireEnv("RIVUS_WORKER_KEY"),
242
+ token: requireEnv("RIVUS_WORKER_TOKEN")
243
+ };
244
+ await createRivusWorkerMcpServer({
245
+ forward: (request) => requestSuperagentWorker(path, capability, request.operation === "list" ? request : {
246
+ operation: "call",
247
+ name: request.toolName,
248
+ input: request.input
249
+ }),
250
+ ...options.input === void 0 ? {} : { input: options.input },
251
+ ...options.output === void 0 ? {} : { output: options.output }
252
+ }).run();
253
+ return;
254
+ }
170
255
  const controlUrl = requireEnv("RIVUS_MCP_CONTROL_URL");
171
256
  const controlToken = requireEnv("RIVUS_MCP_CONTROL_TOKEN");
172
257
  await createRivusHostToolMcpServer({