@rivus/gateway 0.22.3 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,226 @@
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",
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
+ pullRequest: { type: "string" }
147
+ },
148
+ required: [
149
+ "id",
150
+ "state",
151
+ "summary"
152
+ ]
153
+ },
154
+ {
155
+ name: "task_read",
156
+ 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.",
157
+ properties: {
158
+ triggerId: { type: "string" },
159
+ threadKey: { type: "string" },
160
+ before: { type: "string" }
161
+ },
162
+ required: []
163
+ },
164
+ {
165
+ name: "task_follow",
166
+ description: "Follow a visible source thread as context for your assignment",
167
+ properties: { threadKey: { type: "string" } },
168
+ required: ["threadKey"]
169
+ },
170
+ {
171
+ name: "task_unrelated",
172
+ description: "Remove a context or attached thread from this assignment. Origin and source-managed threads are protected.",
173
+ properties: { threadKey: { type: "string" } },
174
+ required: ["threadKey"]
175
+ },
176
+ {
177
+ name: "task_ack",
178
+ description: "Acknowledge a trusted input belonging to this assignment",
179
+ properties: { triggerId: { type: "string" } },
180
+ required: ["triggerId"]
181
+ },
182
+ {
183
+ name: "task_handback",
184
+ description: "Return an out-of-scope follow-up to the Router",
185
+ properties: { triggerId: { type: "string" } },
186
+ required: ["triggerId"]
187
+ },
188
+ {
189
+ name: "task_followup",
190
+ description: "Arrange a follow-up for this assignment",
191
+ properties: {
192
+ requestId: { type: "string" },
193
+ dueAt: { type: "integer" },
194
+ note: { type: "string" }
195
+ },
196
+ required: [
197
+ "requestId",
198
+ "dueAt",
199
+ "note"
200
+ ]
201
+ }
202
+ ].map(({ name, description, properties, required }) => ({
203
+ name,
204
+ description,
205
+ inputSchema: {
206
+ type: "object",
207
+ properties,
208
+ required,
209
+ additionalProperties: false
210
+ }
211
+ }));
212
+ var SuperagentWorkerRejected = class extends Error {
213
+ name = "SuperagentWorkerRejected";
214
+ };
215
+ async function requestSuperagentWorker(path, capability, input, timeoutMs = 1e4) {
216
+ const response = await requestLocalJson(path, {
217
+ ...input,
218
+ execution: capability.execution,
219
+ token: capability.token
220
+ }, timeoutMs);
221
+ if (!response.ok) throw new SuperagentWorkerRejected(response.error);
222
+ return response.value;
223
+ }
224
+ //#endregion
225
+ export { readLocalJsonFrame as a, superagentWorkerTools as i, decodeWorkerRequest as n, requestLocalJson as o, requestSuperagentWorker as r, SuperagentWorkerRejected as t };
226
+
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 { _ as readAutomationPresentation } from "./chunks/rivus-audio-process.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({
@@ -0,0 +1,194 @@
1
+ import { Schema } from "effect";
2
+ //#region ../superagent/dist/chunks/spi.d.ts
3
+ //#region src/work/domain/audience/audience.d.ts
4
+ type Audience = "public" | "internal" | `private:${string}:${string}` | `group:${string}:${string}`;
5
+ /** The code host's variables and Git configuration for one Task's worker. */
6
+ interface WorkerEnvironment {
7
+ readonly variables: Readonly<Record<string, string>>;
8
+ readonly gitConfig?: ReadonlyArray<readonly [key: string, value: string]>;
9
+ }
10
+ //#endregion
11
+ //#region src/work/domain/trigger/adapters/input.d.ts
12
+ declare const triggerInput: Schema.Struct<{
13
+ readonly sourceEventId: Schema.NonEmptyString;
14
+ readonly kind: Schema.Literals<readonly ["message", "comment", "review", "ci", "thread_closed", "thread_open", "timer", "edit", "delete"]>;
15
+ readonly threads: Schema.NonEmptyArray<Schema.NonEmptyString>;
16
+ readonly actor: Schema.Struct<{
17
+ readonly id: Schema.NonEmptyString;
18
+ readonly kind: Schema.Literals<readonly ["person", "bot", "self", "system"]>;
19
+ }>;
20
+ readonly addressed: Schema.optionalKey<Schema.Literals<readonly ["mention", "direct", "watch", "observed"]>>;
21
+ readonly audience: Schema.Union<readonly [Schema.Literals<readonly ["public", "internal", "private"]>, Schema.TemplateLiteral<readonly ["group:", Schema.NonEmptyString]>]>;
22
+ readonly occurredAt: Schema.DateFromString;
23
+ readonly text: Schema.String;
24
+ readonly replyTarget: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
25
+ readonly closeOutcome: Schema.optionalKey<Schema.Literals<readonly ["closed", "merged"]>>;
26
+ }>;
27
+ type TriggerInput = typeof triggerInput.Encoded;
28
+ //#endregion
29
+ //#region src/work/domain/trigger/adapters/message-change-input.d.ts
30
+ declare const messageChange: Schema.Struct<{
31
+ readonly originalSourceEventId: Schema.NonEmptyString;
32
+ readonly kind: Schema.Literals<readonly ["edit", "delete"]>;
33
+ readonly occurredAt: Schema.DateFromString;
34
+ readonly text: Schema.String;
35
+ readonly thread: Schema.optionalKey<Schema.NonEmptyString>;
36
+ }>;
37
+ type MessageChangeInput = typeof messageChange.Encoded;
38
+ //#endregion
39
+ //#region src/work/domain/reply/notice-text.d.ts
40
+ /** The language of the fixed texts the host writes to a source; a source declares it, English by default. */
41
+ type ReplyLocale = "en" | "zh";
42
+ //#endregion
43
+ //#region src/source/domain/reply/delivery.d.ts
44
+ /** What a source reports after one send attempt. */
45
+ type SendResult = {
46
+ readonly status: "sent";
47
+ readonly remoteId: string;
48
+ } | {
49
+ readonly status: "gone" | "retry" | "unknown";
50
+ readonly reason: string;
51
+ };
52
+ //#endregion
53
+ //#region src/source/application/spi.d.ts
54
+ interface ReplyRequest {
55
+ readonly id: string;
56
+ readonly generation: number;
57
+ readonly firstAttemptAt: number;
58
+ readonly thread: string;
59
+ readonly audience: Audience;
60
+ readonly target: Readonly<Record<string, string>>;
61
+ readonly text: string;
62
+ }
63
+ interface SourceHealth {
64
+ readonly state: "ready" | "degraded" | "failed";
65
+ readonly reason: string | undefined;
66
+ }
67
+ interface ThreadPage {
68
+ readonly events: readonly TriggerInput[];
69
+ readonly changes?: readonly MessageChangeInput[];
70
+ readonly cursor: string | undefined;
71
+ }
72
+ /** Host services a source kind may use. */
73
+ interface SourceHost {
74
+ /** The secret a configuration reference names, or `undefined` when it is not set; throws on a malformed reference. */
75
+ secret(this: void, ref: string): string | undefined;
76
+ }
77
+ /**
78
+ * The repository host behind a source: the account that opens the pull requests of Tasks. Superagent accepts at most
79
+ * one. Pull requests themselves are a Superagent concept; the code host verifies and binds them.
80
+ */
81
+ interface CodeHost {
82
+ /** The repositories this host serves; each must also be a configured Superagent repository. */
83
+ readonly repositories: readonly string[];
84
+ /** The repository a native thread of this source belongs to, such as `owner/name`. */
85
+ repository(this: void, thread: string): string | undefined;
86
+ /** Binds the pull request a worker reported; `false` when it cannot be verified now. */
87
+ claimPullRequest(this: void, taskId: string, branch: string, url: string): Promise<boolean>;
88
+ /** Finds and binds the Task's own pull requests for its branch in the Task's repository. */
89
+ discoverPullRequest(this: void, taskId: string, branch: string, repository: string): Promise<boolean>;
90
+ /** The credential a worker's Git or CLI request receives for `repo`, or `undefined` to refuse it. */
91
+ credential(this: void, repo: string | undefined): {
92
+ readonly username: string;
93
+ readonly token: string;
94
+ } | undefined;
95
+ /** Variables and Git settings for a Task's worker; `undefined` until the source has verified its account. */
96
+ environment(this: void, task: {
97
+ readonly id: string;
98
+ readonly branch: string;
99
+ }): WorkerEnvironment | undefined;
100
+ }
101
+ interface SuperagentSource {
102
+ prepare?(signal: AbortSignal): Promise<void>;
103
+ start(signal: AbortSignal): Promise<void>;
104
+ send(reply: ReplyRequest): Promise<SendResult>;
105
+ readThread?(thread: string, cursor?: string, signal?: AbortSignal): Promise<ThreadPage>;
106
+ /**
107
+ * How replies to this source are written. A `messaging` source is where people chat with the bot, so it also
108
+ * receives the notice when all of a Task's pull requests close; `maxWords`, `maxCharacters` (UTF-16 code units,
109
+ * prefix included) and `prefix` apply to every reply.
110
+ * `locale` is the language of the host's fixed notices there, English by default.
111
+ */
112
+ readonly reply?: {
113
+ readonly messaging?: boolean;
114
+ readonly maxWords?: number;
115
+ readonly maxCharacters?: number;
116
+ readonly prefix?: string;
117
+ readonly locale?: ReplyLocale;
118
+ };
119
+ /**
120
+ * Where to start a direct chat with an allowlisted actor, for the host's notices about watched threads: a native
121
+ * thread key and the address `send` receives. `undefined` when this source cannot reach the actor.
122
+ */
123
+ directTarget?(this: void, actor: string): {
124
+ readonly thread: string;
125
+ readonly address: Readonly<Record<string, string>>;
126
+ } | undefined;
127
+ /** A readable label for a native thread on Router cards, and its web address when it has one. */
128
+ describeThread?(this: void, thread: string): {
129
+ readonly label?: string;
130
+ readonly url?: string;
131
+ };
132
+ readonly codeHost?: CodeHost;
133
+ }
134
+ interface SourceState {
135
+ get<T, Encoded>(key: string, schema: Schema.Codec<T, Encoded>): Promise<T | undefined>;
136
+ set<T, Encoded>(key: string, schema: Schema.Codec<T, Encoded>, value: T): Promise<void>;
137
+ }
138
+ interface SuperagentSourceContext<Config> {
139
+ /** The kind's own configuration, decoded by its `config` Schema. */
140
+ readonly config: Config;
141
+ readonly host: SourceHost;
142
+ receive(trigger: TriggerInput, options?: {
143
+ readonly filtered?: string;
144
+ }): Promise<"stored" | "duplicate" | "filtered">;
145
+ receiveMessageChange?(this: void, change: MessageChangeInput): Promise<"stored" | "duplicate" | "unknown" | "pending">;
146
+ isSubscribed(thread: string): boolean;
147
+ polledThreads(): Promise<readonly string[]>;
148
+ /** Durable source state. A missing key reads as `undefined`; a value of another shape fails naming its key. */
149
+ readonly state: SourceState;
150
+ openTaskForBranch?(branch: string): string | undefined;
151
+ bindOwnedThreads?(taskId: string, threads: readonly string[]): Promise<void>;
152
+ bindThread(taskId: string, thread: string, own: boolean): Promise<void>;
153
+ report(health: SourceHealth): void;
154
+ }
155
+ /**
156
+ * A kind of trigger source, such as GitHub or Feishu. A configured source is `{ id, kind, allowedActors, ...fields }`:
157
+ * Superagent decodes the shared fields, and `config` decodes the remaining fields, rejecting unknown ones.
158
+ */
159
+ interface SuperagentSourceKind<Config = unknown> {
160
+ /** An identifier matching `^[a-z0-9][a-z0-9_-]*$`; `timer` is reserved for internal follow-ups. */
161
+ readonly kind: string;
162
+ readonly config: Schema.Codec<Config, unknown>;
163
+ /**
164
+ * Maps a configured `allowedActors` entry to the form this kind's triggers carry, such as a lowercase login. Sources
165
+ * already emit actor IDs in that form.
166
+ */
167
+ normalizeActor?(this: void, id: string): string;
168
+ /** Checks what the source needs from the host before startup, such as its credential; throws when unmet. */
169
+ preflight?(this: void, config: Config, host: SourceHost): void;
170
+ /**
171
+ * The kind emits watch candidates (`addressed: "watch"`): events from people outside the allowlist that the Router
172
+ * judges against the owner's instructions. A Superagent with such a source must configure an `owner`.
173
+ */
174
+ readonly watches?: boolean;
175
+ /**
176
+ * The kind emits observed candidates (`addressed: "observed"`): messages, comments and reviews that do not address
177
+ * the bot, offered because the source observes where they happened. Intake keeps the mark only for an actor on the
178
+ * source's `allowedActors`; anyone else's event arrives as the unaddressed event it is.
179
+ */
180
+ readonly observes?: boolean;
181
+ create(this: void, context: SuperagentSourceContext<Config>): SuperagentSource;
182
+ }
183
+ /**
184
+ * A named set of source kinds that a deployment loads. Kind names must be unique across the presets a deployment
185
+ * names; the trigger kinds a source emits stay Superagent's fixed set.
186
+ */
187
+ interface SuperagentSourcePreset {
188
+ /** A readable name for error messages, such as `builtin` or the package name. */
189
+ readonly id: string;
190
+ readonly sourceKinds: readonly SuperagentSourceKind[];
191
+ }
192
+ //#endregion
193
+ export type { CodeHost, MessageChangeInput, ReplyRequest, SendResult, SourceHost, SuperagentSource, SuperagentSourceContext, SuperagentSourceKind, SuperagentSourcePreset, TriggerInput, WorkerEnvironment };
194
+ export {};
@@ -0,0 +1,2 @@
1
+ export {};
2
+