@rivus/gateway 0.22.2 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bootstrap/feishu.d.ts +42 -3
- package/dist/bootstrap/feishu.js +12378 -12609
- package/dist/bootstrap/herdr-feishu.d.ts +8 -1
- package/dist/bootstrap/herdr-feishu.js +1 -1
- package/dist/chunks/dist.js +9052 -0
- package/dist/chunks/errors.js +13 -0
- package/dist/chunks/feishu-receive-message.js +1 -1
- package/dist/chunks/herdr-feishu-runtime.js +524 -415
- package/dist/chunks/public.d.ts +93 -63
- package/dist/chunks/public2.d.ts +0 -7
- package/dist/chunks/rivus-audio-process.js +5290 -0
- package/dist/chunks/rivus-deployment-cli-process.d.ts +136 -353
- package/dist/chunks/rivus-node-entrypoint.js +1244 -1624
- package/dist/chunks/superagent-worker-wire.js +226 -0
- package/dist/index.d.ts +12 -25
- package/dist/index.js +2 -1
- package/dist/mcp.js +109 -24
- package/dist/superagent.d.ts +194 -0
- package/dist/superagent.js +2 -0
- package/package.json +17 -5
- package/dist/chunks/automation-presentation.js +0 -263
- package/dist/chunks/rivus-home-deployment-env.js +0 -1916
|
@@ -1,1916 +0,0 @@
|
|
|
1
|
-
import { Cause, Deferred, Effect, Exit, Option, Result, Schema, SchemaIssue, Semaphore } from "effect";
|
|
2
|
-
import { isRivusRuntimeToolId } from "@rivus/runtime";
|
|
3
|
-
import { readPersistenceFile, writeAtomicTextFile } from "@rivus/platform/persistence";
|
|
4
|
-
import { basename, delimiter, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
5
|
-
import { fileURLToPath } from "node:url";
|
|
6
|
-
import { access, constants, cp, mkdir, readFile, readdir, rename, rm, stat } from "node:fs/promises";
|
|
7
|
-
import { isNodeErrorWithCode, isPathWithin } from "@rivus/platform/filesystem";
|
|
8
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
9
|
-
import { acquireProcessLock } from "@rivus/agent-kit-collab/process-lock";
|
|
10
|
-
import { spawn } from "node:child_process";
|
|
11
|
-
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
12
|
-
//#region src/lib/deep-freeze.ts
|
|
13
|
-
function deepFreeze(value) {
|
|
14
|
-
if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
|
|
15
|
-
Object.freeze(value);
|
|
16
|
-
for (const child of Object.values(value)) deepFreeze(child);
|
|
17
|
-
}
|
|
18
|
-
return value;
|
|
19
|
-
}
|
|
20
|
-
//#endregion
|
|
21
|
-
//#region src/background-session/domain/background-session/services/background-session-authority.ts
|
|
22
|
-
const BACKGROUND_SESSION_START_TOOL_ID = "background.start";
|
|
23
|
-
const BACKGROUND_SESSION_TOOL_PLUGIN_ID = "rivus-core";
|
|
24
|
-
const BACKGROUND_SESSION_TOOL_VERSION = "1.0.0";
|
|
25
|
-
const BACKGROUND_SESSION_TOOL_DIGESTS = {
|
|
26
|
-
"background.list": "sha256:c935847595e406d55ca889875b38db66bb1d4d7a34d7b0fb2b85aecf9478c149",
|
|
27
|
-
"background.send": "sha256:b7ed492e45c794dc286f7f66aca8d046082d11dfdc8787eaf5604765b68a7735",
|
|
28
|
-
"background.start": "sha256:773690e47f6eef1f1b289216e94cf98e548382d6cffb7b2f034c3ed0635dfcbb",
|
|
29
|
-
"background.status": "sha256:6aaa328d6cd97d8755a63abbe97286f1061fd2f238f68b1e576ed9a1d2b7e6b1",
|
|
30
|
-
"background.stop": "sha256:aa0bfdf0c9394058bfcbd8662e7bedd59055f9ddad51c2a1bb61666bd67ebfcb",
|
|
31
|
-
"background.wait": "sha256:4a0dc80e933ad3c99b6d58421ac9ef733157e39e0ac9b6ad87ac6e65ceaedaab"
|
|
32
|
-
};
|
|
33
|
-
function createBackgroundSessionToolContracts() {
|
|
34
|
-
return [
|
|
35
|
-
Object.freeze({
|
|
36
|
-
description: "Start a background agent session. Use when the request must wait for external changes, observe over time, or continue working after the foreground run ends. Returns a stable session id immediately; the foreground response can finish here. The detached session continues with the granted Skills, CLI, Tools, Project Space, and Memory of this agent.",
|
|
37
|
-
digest: BACKGROUND_SESSION_TOOL_DIGESTS["background.start"],
|
|
38
|
-
id: "background.start",
|
|
39
|
-
idempotency: "supported",
|
|
40
|
-
inputSchema: Object.freeze({
|
|
41
|
-
additionalProperties: false,
|
|
42
|
-
properties: Object.freeze({
|
|
43
|
-
displayName: {
|
|
44
|
-
type: "string",
|
|
45
|
-
maxLength: 200
|
|
46
|
-
},
|
|
47
|
-
prompt: {
|
|
48
|
-
type: "string",
|
|
49
|
-
minLength: 1,
|
|
50
|
-
maxLength: 2e4
|
|
51
|
-
}
|
|
52
|
-
}),
|
|
53
|
-
required: ["prompt"],
|
|
54
|
-
type: "object"
|
|
55
|
-
}),
|
|
56
|
-
pluginId: BACKGROUND_SESSION_TOOL_PLUGIN_ID,
|
|
57
|
-
risk: "mutate",
|
|
58
|
-
version: BACKGROUND_SESSION_TOOL_VERSION
|
|
59
|
-
}),
|
|
60
|
-
Object.freeze({
|
|
61
|
-
description: "Pause the current background session durably and end the current step. Call with delayMs to resume after a delay, with until to resume at an absolute ISO time, or with neither to wait for user input. After this call no further tool calls are accepted in this step.",
|
|
62
|
-
digest: BACKGROUND_SESSION_TOOL_DIGESTS["background.wait"],
|
|
63
|
-
id: "background.wait",
|
|
64
|
-
idempotency: "supported",
|
|
65
|
-
inputSchema: Object.freeze({
|
|
66
|
-
additionalProperties: false,
|
|
67
|
-
properties: Object.freeze({
|
|
68
|
-
delayMs: {
|
|
69
|
-
type: "integer",
|
|
70
|
-
minimum: 1e3,
|
|
71
|
-
maximum: 864e5
|
|
72
|
-
},
|
|
73
|
-
reason: {
|
|
74
|
-
type: "string",
|
|
75
|
-
maxLength: 500
|
|
76
|
-
},
|
|
77
|
-
until: {
|
|
78
|
-
type: "string",
|
|
79
|
-
maxLength: 64
|
|
80
|
-
}
|
|
81
|
-
}),
|
|
82
|
-
type: "object"
|
|
83
|
-
}),
|
|
84
|
-
pluginId: BACKGROUND_SESSION_TOOL_PLUGIN_ID,
|
|
85
|
-
risk: "mutate",
|
|
86
|
-
version: BACKGROUND_SESSION_TOOL_VERSION
|
|
87
|
-
}),
|
|
88
|
-
Object.freeze({
|
|
89
|
-
description: "List background sessions owned by this conversation, newest first. Optionally filter by phase and limit the number of results.",
|
|
90
|
-
digest: BACKGROUND_SESSION_TOOL_DIGESTS["background.list"],
|
|
91
|
-
id: "background.list",
|
|
92
|
-
idempotency: "supported",
|
|
93
|
-
inputSchema: Object.freeze({
|
|
94
|
-
additionalProperties: false,
|
|
95
|
-
properties: Object.freeze({
|
|
96
|
-
limit: {
|
|
97
|
-
type: "integer",
|
|
98
|
-
minimum: 1,
|
|
99
|
-
maximum: 50
|
|
100
|
-
},
|
|
101
|
-
phase: {
|
|
102
|
-
enum: [
|
|
103
|
-
"queued",
|
|
104
|
-
"running",
|
|
105
|
-
"waiting",
|
|
106
|
-
"input-required",
|
|
107
|
-
"stopping",
|
|
108
|
-
"stopped",
|
|
109
|
-
"completed",
|
|
110
|
-
"failed",
|
|
111
|
-
"reconciliation-required"
|
|
112
|
-
],
|
|
113
|
-
type: "string"
|
|
114
|
-
}
|
|
115
|
-
}),
|
|
116
|
-
type: "object"
|
|
117
|
-
}),
|
|
118
|
-
pluginId: BACKGROUND_SESSION_TOOL_PLUGIN_ID,
|
|
119
|
-
risk: "observe",
|
|
120
|
-
version: BACKGROUND_SESSION_TOOL_VERSION
|
|
121
|
-
}),
|
|
122
|
-
Object.freeze({
|
|
123
|
-
description: "Return the current phase, step counts, wake time, and result of one background session owned by this conversation.",
|
|
124
|
-
digest: BACKGROUND_SESSION_TOOL_DIGESTS["background.status"],
|
|
125
|
-
id: "background.status",
|
|
126
|
-
idempotency: "supported",
|
|
127
|
-
inputSchema: Object.freeze({
|
|
128
|
-
additionalProperties: false,
|
|
129
|
-
properties: Object.freeze({ sessionId: {
|
|
130
|
-
type: "string",
|
|
131
|
-
minLength: 1,
|
|
132
|
-
maxLength: 200
|
|
133
|
-
} }),
|
|
134
|
-
required: ["sessionId"],
|
|
135
|
-
type: "object"
|
|
136
|
-
}),
|
|
137
|
-
pluginId: BACKGROUND_SESSION_TOOL_PLUGIN_ID,
|
|
138
|
-
risk: "observe",
|
|
139
|
-
version: BACKGROUND_SESSION_TOOL_VERSION
|
|
140
|
-
}),
|
|
141
|
-
Object.freeze({
|
|
142
|
-
description: "Send new user instruction text to a background session owned by this conversation and wake it. The input is delivered exactly once in the next step.",
|
|
143
|
-
digest: BACKGROUND_SESSION_TOOL_DIGESTS["background.send"],
|
|
144
|
-
id: "background.send",
|
|
145
|
-
idempotency: "supported",
|
|
146
|
-
inputSchema: Object.freeze({
|
|
147
|
-
additionalProperties: false,
|
|
148
|
-
properties: Object.freeze({
|
|
149
|
-
message: {
|
|
150
|
-
type: "string",
|
|
151
|
-
minLength: 1,
|
|
152
|
-
maxLength: 2e4
|
|
153
|
-
},
|
|
154
|
-
sessionId: {
|
|
155
|
-
type: "string",
|
|
156
|
-
minLength: 1,
|
|
157
|
-
maxLength: 200
|
|
158
|
-
}
|
|
159
|
-
}),
|
|
160
|
-
required: ["message", "sessionId"],
|
|
161
|
-
type: "object"
|
|
162
|
-
}),
|
|
163
|
-
pluginId: BACKGROUND_SESSION_TOOL_PLUGIN_ID,
|
|
164
|
-
risk: "mutate",
|
|
165
|
-
version: BACKGROUND_SESSION_TOOL_VERSION
|
|
166
|
-
}),
|
|
167
|
-
Object.freeze({
|
|
168
|
-
description: "Stop a background session owned by this conversation. Persists the cancellation, aborts the active step and its owned process, and delivers a terminal notice.",
|
|
169
|
-
digest: BACKGROUND_SESSION_TOOL_DIGESTS["background.stop"],
|
|
170
|
-
id: "background.stop",
|
|
171
|
-
idempotency: "supported",
|
|
172
|
-
inputSchema: Object.freeze({
|
|
173
|
-
additionalProperties: false,
|
|
174
|
-
properties: Object.freeze({
|
|
175
|
-
reason: {
|
|
176
|
-
type: "string",
|
|
177
|
-
maxLength: 500
|
|
178
|
-
},
|
|
179
|
-
sessionId: {
|
|
180
|
-
type: "string",
|
|
181
|
-
minLength: 1,
|
|
182
|
-
maxLength: 200
|
|
183
|
-
}
|
|
184
|
-
}),
|
|
185
|
-
required: ["sessionId"],
|
|
186
|
-
type: "object"
|
|
187
|
-
}),
|
|
188
|
-
pluginId: BACKGROUND_SESSION_TOOL_PLUGIN_ID,
|
|
189
|
-
risk: "mutate",
|
|
190
|
-
version: BACKGROUND_SESSION_TOOL_VERSION
|
|
191
|
-
})
|
|
192
|
-
];
|
|
193
|
-
}
|
|
194
|
-
function grantRevision(digest, parentRevision, toolIds) {
|
|
195
|
-
return digest(JSON.stringify({
|
|
196
|
-
parentRevision,
|
|
197
|
-
toolIds: [...toolIds].sort()
|
|
198
|
-
}));
|
|
199
|
-
}
|
|
200
|
-
function narrowBackgroundSessionDefinition(definition, digest) {
|
|
201
|
-
const childToolIds = definition.toolGrantSet.toolIds.filter((id) => id !== BACKGROUND_SESSION_START_TOOL_ID);
|
|
202
|
-
const toolGrantSet = Object.freeze({
|
|
203
|
-
revision: grantRevision(digest, definition.toolGrantSet.revision, childToolIds),
|
|
204
|
-
toolIds: Object.freeze(childToolIds)
|
|
205
|
-
});
|
|
206
|
-
return Object.freeze({
|
|
207
|
-
...definition,
|
|
208
|
-
tools: Object.freeze(definition.tools.filter(({ id }) => id !== BACKGROUND_SESSION_START_TOOL_ID)),
|
|
209
|
-
toolGrantSet
|
|
210
|
-
});
|
|
211
|
-
}
|
|
212
|
-
//#endregion
|
|
213
|
-
//#region src/deployment/domain/manifest/adapters/deployment-manifest.ts
|
|
214
|
-
const DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_MS = 3e4;
|
|
215
|
-
const DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_RENEWAL_INTERVAL_MS = 1e4;
|
|
216
|
-
const DEFAULT_MANIFEST_BACKGROUND_SESSION_MAX_CONSECUTIVE_FAILURES = 3;
|
|
217
|
-
const DEFAULT_MANIFEST_BACKGROUND_SESSION_MAX_CONCURRENT_SESSIONS = 4;
|
|
218
|
-
const DEFAULT_MANIFEST_BACKGROUND_SESSION_RETRY_BACKOFF_MS = 3e4;
|
|
219
|
-
const DEFAULT_MANIFEST_BACKGROUND_SESSION_LIFETIME_MS = 864e5;
|
|
220
|
-
const DEFAULT_MANIFEST_BACKGROUND_SESSION_STEP_TIMEOUT_MS = 3e5;
|
|
221
|
-
const DEFAULT_MANIFEST_CARD_STREAM_LEASE_MS = 51e4;
|
|
222
|
-
const DEFAULT_MANIFEST_CONVERSATION_PROGRESS_DISPLAY = "collapsed";
|
|
223
|
-
const MEMORY_SCOPES = [
|
|
224
|
-
"conversation",
|
|
225
|
-
"agent-private",
|
|
226
|
-
"project",
|
|
227
|
-
"shared-user-profile"
|
|
228
|
-
];
|
|
229
|
-
var InvalidRivusProjectSpace = class extends Error {
|
|
230
|
-
name = "InvalidRivusProjectSpace";
|
|
231
|
-
};
|
|
232
|
-
function isAbsoluteProjectPath(value) {
|
|
233
|
-
return value.startsWith("/") || value.startsWith("\\") || /^[a-z]:[\\/]/i.test(value);
|
|
234
|
-
}
|
|
235
|
-
function validateRelativeProjectPath(value, owner) {
|
|
236
|
-
if (value.trim() === "" || isAbsoluteProjectPath(value) || value.includes("\0")) throw new InvalidRivusProjectSpace(`${owner} must be a non-empty relative path`);
|
|
237
|
-
}
|
|
238
|
-
function validateRivusProjectSpaceDeployment(declaration) {
|
|
239
|
-
validateRelativeProjectPath(declaration.root, `project space ${declaration.id} root`);
|
|
240
|
-
validateRelativeProjectPath(declaration.workingDirectory, `project space ${declaration.id} working directory`);
|
|
241
|
-
const sources = /* @__PURE__ */ new Set();
|
|
242
|
-
for (const source of declaration.skills.sources) {
|
|
243
|
-
validateRelativeProjectPath(source, `project space ${declaration.id} Skill source`);
|
|
244
|
-
if (sources.has(source)) throw new InvalidRivusProjectSpace(`project space ${declaration.id} contains duplicate Skill source: ${source}`);
|
|
245
|
-
sources.add(source);
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
function validateRivusProjectSpaceDeployments(declarations) {
|
|
249
|
-
const projectSpaceIds = /* @__PURE__ */ new Set();
|
|
250
|
-
for (const declaration of declarations) {
|
|
251
|
-
if (projectSpaceIds.has(declaration.id)) throw new InvalidRivusProjectSpace(`duplicate project space: ${declaration.id}`);
|
|
252
|
-
projectSpaceIds.add(declaration.id);
|
|
253
|
-
validateRivusProjectSpaceDeployment(declaration);
|
|
254
|
-
}
|
|
255
|
-
return projectSpaceIds;
|
|
256
|
-
}
|
|
257
|
-
const nonBlankRuntimeString = Schema.String.check(Schema.makeFilter((value) => value.trim() !== ""));
|
|
258
|
-
const agentRuntimeSchema = Schema.Struct({
|
|
259
|
-
type: Schema.Literal("acp"),
|
|
260
|
-
command: nonBlankRuntimeString,
|
|
261
|
-
args: Schema.optional(Schema.Array(Schema.String)),
|
|
262
|
-
env: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
263
|
-
permissions: Schema.optional(Schema.Literals(["ask", "deny"])),
|
|
264
|
-
steering: Schema.optional(Schema.Literals(["disabled", "cancel-and-reprompt"])),
|
|
265
|
-
unattended: Schema.optional(Schema.Boolean),
|
|
266
|
-
initializationTimeoutMs: Schema.optional(Schema.Number)
|
|
267
|
-
});
|
|
268
|
-
function decodeRuntimeField(schema, value, path) {
|
|
269
|
-
const decoded = Schema.decodeUnknownResult(schema, { onExcessProperty: "error" })(value);
|
|
270
|
-
if (Result.isSuccess(decoded)) return decoded.success;
|
|
271
|
-
const issue = SchemaIssue.makeFormatterStandardSchemaV1()(decoded.failure.issue).issues[0];
|
|
272
|
-
throw new Error(`${path} ${JSON.stringify(issue.path ?? [])} contains invalid or unsupported input`);
|
|
273
|
-
}
|
|
274
|
-
function parseAllowedActors(value, path) {
|
|
275
|
-
const actors = [...decodeRuntimeField(Schema.Array(nonBlankRuntimeString), value, path)];
|
|
276
|
-
if (new Set(actors).size !== actors.length) throw new Error(`${path} contains duplicate actor`);
|
|
277
|
-
return actors;
|
|
278
|
-
}
|
|
279
|
-
function validateBackgroundSessions(config) {
|
|
280
|
-
if (config.required && !config.enabled) throw new Error("backgroundSessions.required requires backgroundSessions.enabled");
|
|
281
|
-
if (config.leaseRenewalIntervalMs >= config.leaseMs) throw new Error("backgroundSessions.leaseRenewalIntervalMs must be shorter than leaseMs");
|
|
282
|
-
if (config.stepTimeoutMs <= 0 || config.maxConcurrentSessions <= 0 || config.leaseMs <= 0) throw new Error("backgroundSessions durations and concurrency must be positive");
|
|
283
|
-
if (config.retryBackoffMs <= 0 || config.sessionLifetimeMs <= 0 || config.maxConsecutiveFailures <= 0) throw new Error("backgroundSessions retry and lifetime limits must be positive");
|
|
284
|
-
}
|
|
285
|
-
function validateModuleSpecifier(moduleSpecifier) {
|
|
286
|
-
const absolutePath = moduleSpecifier.startsWith("/") || moduleSpecifier.startsWith("\\\\") || /^[a-zA-Z]:[\\/]/.test(moduleSpecifier);
|
|
287
|
-
if (moduleSpecifier.trim() === "" || absolutePath || /^[a-z][a-z+.-]*:/i.test(moduleSpecifier) || moduleSpecifier.includes("\0")) throw new Error(`invalid plugin module specifier: ${moduleSpecifier}`);
|
|
288
|
-
if ((moduleSpecifier.startsWith("./") || moduleSpecifier.startsWith("../")) && moduleSpecifier.split(/[\\/]/).includes("..")) throw new Error(`plugin module escapes deployment root: ${moduleSpecifier}`);
|
|
289
|
-
}
|
|
290
|
-
/**
|
|
291
|
-
* Object gate for one manifest section, not a field reader: every section below is read
|
|
292
|
-
* field-by-field with `<path>`-specific error texts and `exactKeys` ordering, which one
|
|
293
|
-
* closed Struct cannot express. `Schema.Record(Schema.String, Schema.Unknown)` is
|
|
294
|
-
* deliberately used only as that gate; a hand-written `typeof … === "object"` guard is
|
|
295
|
-
* forbidden (authoring guide, Validation).
|
|
296
|
-
*/
|
|
297
|
-
const manifestSectionGate = Schema.Record(Schema.String, Schema.Unknown);
|
|
298
|
-
function record(value, path) {
|
|
299
|
-
if (!Schema.is(manifestSectionGate)(value)) throw new Error(`${path} must be an object`);
|
|
300
|
-
return value;
|
|
301
|
-
}
|
|
302
|
-
function array(value, path) {
|
|
303
|
-
if (!Array.isArray(value)) throw new Error(`${path} must be an array`);
|
|
304
|
-
return value;
|
|
305
|
-
}
|
|
306
|
-
function string(value, path) {
|
|
307
|
-
if (typeof value !== "string" || value.trim() === "") throw new Error(`${path} must be a non-empty string`);
|
|
308
|
-
return value;
|
|
309
|
-
}
|
|
310
|
-
function boolean(value, path) {
|
|
311
|
-
if (typeof value !== "boolean") throw new Error(`${path} must be a boolean`);
|
|
312
|
-
return value;
|
|
313
|
-
}
|
|
314
|
-
function positiveInteger(value, path) {
|
|
315
|
-
if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`${path} must be a positive integer`);
|
|
316
|
-
return value;
|
|
317
|
-
}
|
|
318
|
-
function parseAgentRuntime(value, path) {
|
|
319
|
-
const runtime = decodeRuntimeField(agentRuntimeSchema, value, path);
|
|
320
|
-
const env = runtime.env ?? {};
|
|
321
|
-
for (const [key, reference] of Object.entries(env)) {
|
|
322
|
-
if (!/^[A-Z_][A-Z0-9_]*$/.test(key)) throw new Error(`${path}.env contains invalid variable name: ${key}`);
|
|
323
|
-
if (!/^env:[A-Z_][A-Z0-9_]*$/.test(reference)) throw new Error(`${path}.env.${key} must reference env:NAME`);
|
|
324
|
-
}
|
|
325
|
-
return Object.freeze({
|
|
326
|
-
args: Object.freeze([...runtime.args ?? []]),
|
|
327
|
-
command: runtime.command,
|
|
328
|
-
env: Object.freeze({ ...env }),
|
|
329
|
-
initializationTimeoutMs: positiveInteger(runtime.initializationTimeoutMs === void 0 ? 1e4 : runtime.initializationTimeoutMs, `${path}.initializationTimeoutMs`),
|
|
330
|
-
permissions: runtime.permissions ?? "ask",
|
|
331
|
-
steering: runtime.steering ?? "disabled",
|
|
332
|
-
type: "acp",
|
|
333
|
-
unattended: runtime.unattended ?? false
|
|
334
|
-
});
|
|
335
|
-
}
|
|
336
|
-
function validateRivusDeploymentManifest(manifest) {
|
|
337
|
-
const projectSpaceIds = validateRivusProjectSpaceDeployments(manifest.projectSpaces ?? []);
|
|
338
|
-
const pluginIds = /* @__PURE__ */ new Set();
|
|
339
|
-
for (const plugin of manifest.plugins) {
|
|
340
|
-
if (pluginIds.has(plugin.id)) throw new Error(`duplicate plugin declaration: ${plugin.id}`);
|
|
341
|
-
validateModuleSpecifier(plugin.module);
|
|
342
|
-
pluginIds.add(plugin.id);
|
|
343
|
-
}
|
|
344
|
-
const agentIds = /* @__PURE__ */ new Set();
|
|
345
|
-
const agentById = /* @__PURE__ */ new Map();
|
|
346
|
-
for (const agent of manifest.agents) {
|
|
347
|
-
if (agentIds.has(agent.agentId)) throw new Error(`duplicate agent deployment: ${agent.agentId}`);
|
|
348
|
-
agentIds.add(agent.agentId);
|
|
349
|
-
if (!pluginIds.has(agent.pluginId)) throw new Error(`agent ${agent.agentId} references undeclared plugin: ${agent.pluginId}`);
|
|
350
|
-
if (agent.projectSpaceId && !projectSpaceIds.has(agent.projectSpaceId)) throw new Error(`agent ${agent.agentId} references unknown project space: ${agent.projectSpaceId}`);
|
|
351
|
-
if (agent.runtime) {
|
|
352
|
-
const runtime = parseAgentRuntime(agent.runtime, `agent ${agent.agentId} runtime`);
|
|
353
|
-
if (agent.runtimeTools !== void 0) throw new Error(`ACP agent ${agent.agentId} must not declare runtimeTools`);
|
|
354
|
-
if (agent.skills.allow.length > 0) throw new Error(`ACP agent ${agent.agentId} skills.allow must be empty`);
|
|
355
|
-
if (runtime.args.includes("--yolo") && !runtime.unattended) throw new Error(`ACP agent ${agent.agentId} runtime.args --yolo requires unattended: true`);
|
|
356
|
-
}
|
|
357
|
-
agentById.set(agent.agentId, agent);
|
|
358
|
-
}
|
|
359
|
-
const endpointIds = /* @__PURE__ */ new Set();
|
|
360
|
-
const sessionNamespaces = /* @__PURE__ */ new Set();
|
|
361
|
-
for (const endpoint of manifest.endpoints) {
|
|
362
|
-
if (endpointIds.has(endpoint.id)) throw new Error(`duplicate endpoint binding: ${endpoint.id}`);
|
|
363
|
-
endpointIds.add(endpoint.id);
|
|
364
|
-
if (endpoint.allowedActors !== void 0) parseAllowedActors(endpoint.allowedActors, `endpoint ${endpoint.id} allowedActors`);
|
|
365
|
-
if (sessionNamespaces.has(endpoint.sessionNamespace)) throw new Error(`duplicate endpoint session namespace: ${endpoint.sessionNamespace}`);
|
|
366
|
-
sessionNamespaces.add(endpoint.sessionNamespace);
|
|
367
|
-
const agent = agentById.get(endpoint.agentId);
|
|
368
|
-
if (!agent) throw new Error(`endpoint ${endpoint.id} references unknown agent: ${endpoint.agentId}`);
|
|
369
|
-
if (agent.runtime?.unattended && !endpoint.allowedActors?.length) throw new Error(`unattended ACP agent ${agent.agentId} requires non-empty allowedActors on endpoint ${endpoint.id}`);
|
|
370
|
-
if (!agent.endpointIds.includes(endpoint.id)) throw new Error(`endpoint ${endpoint.id} is not declared by agent ${endpoint.agentId}`);
|
|
371
|
-
}
|
|
372
|
-
for (const agent of manifest.agents) for (const endpointId of agent.endpointIds) {
|
|
373
|
-
const endpoint = manifest.endpoints.find(({ id }) => id === endpointId);
|
|
374
|
-
if (!endpoint) throw new Error(`agent ${agent.agentId} references unknown endpoint: ${endpointId}`);
|
|
375
|
-
if (endpoint.agentId !== agent.agentId) throw new Error(`endpoint ${endpointId} is bound to a different agent`);
|
|
376
|
-
}
|
|
377
|
-
const automationIds = /* @__PURE__ */ new Set();
|
|
378
|
-
for (const automation of manifest.automations ?? []) {
|
|
379
|
-
if (automationIds.has(automation.id)) throw new Error(`duplicate automation binding: ${automation.id}`);
|
|
380
|
-
automationIds.add(automation.id);
|
|
381
|
-
if (!agentById.has(automation.agentId)) throw new Error(`automation ${automation.id} references unknown agent: ${automation.agentId}`);
|
|
382
|
-
const endpoint = manifest.endpoints.find(({ id }) => id === automation.delivery.endpointId);
|
|
383
|
-
if (!endpoint) throw new Error(`automation ${automation.id} references unknown delivery endpoint: ${automation.delivery.endpointId}`);
|
|
384
|
-
if (automation.enabled && !endpoint.enabled) throw new Error(`automation ${automation.id} delivery endpoint must be enabled`);
|
|
385
|
-
}
|
|
386
|
-
const defaultAgent = agentById.get(manifest.defaultAgentId);
|
|
387
|
-
if (!defaultAgent) throw new Error(`default agent does not exist: ${manifest.defaultAgentId}`);
|
|
388
|
-
const defaultEndpoint = manifest.endpoints.find(({ id }) => id === manifest.defaultEndpointId);
|
|
389
|
-
if (!defaultEndpoint) throw new Error(`default endpoint does not exist: ${manifest.defaultEndpointId}`);
|
|
390
|
-
if (defaultEndpoint.agentId !== defaultAgent.agentId) throw new Error("default endpoint is not bound to the default agent");
|
|
391
|
-
if (!defaultEndpoint.enabled) throw new Error("default endpoint must be enabled");
|
|
392
|
-
if (manifest.backgroundSessions) validateBackgroundSessions(manifest.backgroundSessions);
|
|
393
|
-
}
|
|
394
|
-
function memoryScope(value, path) {
|
|
395
|
-
if (typeof value !== "string" || !MEMORY_SCOPES.includes(value)) throw new Error(`${path} must be conversation, agent-private, project, or shared-user-profile`);
|
|
396
|
-
return value;
|
|
397
|
-
}
|
|
398
|
-
function groupPolicy(value, path) {
|
|
399
|
-
if (value !== "mention-only" && value !== "ignore-unmentioned" && value !== "default-responder") throw new Error(`${path} must be mention-only, ignore-unmentioned, or default-responder`);
|
|
400
|
-
return value;
|
|
401
|
-
}
|
|
402
|
-
function progressDisplay(value, path) {
|
|
403
|
-
if (value !== "hidden" && value !== "collapsed" && value !== "expanded") throw new Error(`${path} must be hidden, collapsed, or expanded`);
|
|
404
|
-
return value;
|
|
405
|
-
}
|
|
406
|
-
function runtimeToolId(value, path) {
|
|
407
|
-
const id = string(value, path);
|
|
408
|
-
if (!isRivusRuntimeToolId(id)) throw new Error(`${path} must be read, bash, edit, write, grep, find, or ls`);
|
|
409
|
-
return id;
|
|
410
|
-
}
|
|
411
|
-
function uniqueRuntimeTools(ids, path) {
|
|
412
|
-
const result = /* @__PURE__ */ new Set();
|
|
413
|
-
for (const id of ids) {
|
|
414
|
-
if (result.has(id)) throw new Error(`${path} contains duplicate Runtime Tool: ${id}`);
|
|
415
|
-
result.add(id);
|
|
416
|
-
}
|
|
417
|
-
return [...result];
|
|
418
|
-
}
|
|
419
|
-
function automationTargetType(value, path) {
|
|
420
|
-
if (value !== "chat_id" && value !== "open_id" && value !== "user_id" && value !== "union_id" && value !== "email") throw new Error(`${path} must be chat_id, open_id, user_id, union_id, or email`);
|
|
421
|
-
return value;
|
|
422
|
-
}
|
|
423
|
-
function exactKeys(value, allowed, path, optional = []) {
|
|
424
|
-
const unexpected = Object.keys(value).find((key) => !allowed.includes(key));
|
|
425
|
-
if (unexpected) throw new Error(`${path} contains unsupported field: ${unexpected}`);
|
|
426
|
-
const missing = allowed.find((key) => !optional.includes(key) && !Object.hasOwn(value, key));
|
|
427
|
-
if (missing) throw new Error(`${path} is missing required field: ${missing}`);
|
|
428
|
-
}
|
|
429
|
-
function parseBackgroundSessions(value) {
|
|
430
|
-
exactKeys(value, [
|
|
431
|
-
"enabled",
|
|
432
|
-
"leaseMs",
|
|
433
|
-
"leaseRenewalIntervalMs",
|
|
434
|
-
"maxConsecutiveFailures",
|
|
435
|
-
"maxConcurrentSessions",
|
|
436
|
-
"required",
|
|
437
|
-
"retryBackoffMs",
|
|
438
|
-
"sessionLifetimeMs",
|
|
439
|
-
"stepTimeoutMs"
|
|
440
|
-
], "manifest.backgroundSessions", [
|
|
441
|
-
"leaseMs",
|
|
442
|
-
"leaseRenewalIntervalMs",
|
|
443
|
-
"maxConsecutiveFailures",
|
|
444
|
-
"maxConcurrentSessions",
|
|
445
|
-
"retryBackoffMs",
|
|
446
|
-
"sessionLifetimeMs",
|
|
447
|
-
"stepTimeoutMs"
|
|
448
|
-
]);
|
|
449
|
-
return Object.freeze({
|
|
450
|
-
enabled: boolean(value.enabled, "manifest.backgroundSessions.enabled"),
|
|
451
|
-
leaseMs: positiveInteger(value.leaseMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_MS, "manifest.backgroundSessions.leaseMs"),
|
|
452
|
-
leaseRenewalIntervalMs: positiveInteger(value.leaseRenewalIntervalMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_RENEWAL_INTERVAL_MS, "manifest.backgroundSessions.leaseRenewalIntervalMs"),
|
|
453
|
-
maxConsecutiveFailures: positiveInteger(value.maxConsecutiveFailures ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_MAX_CONSECUTIVE_FAILURES, "manifest.backgroundSessions.maxConsecutiveFailures"),
|
|
454
|
-
maxConcurrentSessions: positiveInteger(value.maxConcurrentSessions ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_MAX_CONCURRENT_SESSIONS, "manifest.backgroundSessions.maxConcurrentSessions"),
|
|
455
|
-
required: boolean(value.required, "manifest.backgroundSessions.required"),
|
|
456
|
-
retryBackoffMs: positiveInteger(value.retryBackoffMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_RETRY_BACKOFF_MS, "manifest.backgroundSessions.retryBackoffMs"),
|
|
457
|
-
sessionLifetimeMs: positiveInteger(value.sessionLifetimeMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_LIFETIME_MS, "manifest.backgroundSessions.sessionLifetimeMs"),
|
|
458
|
-
stepTimeoutMs: positiveInteger(value.stepTimeoutMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_STEP_TIMEOUT_MS, "manifest.backgroundSessions.stepTimeoutMs")
|
|
459
|
-
});
|
|
460
|
-
}
|
|
461
|
-
function parseRivusDeploymentManifest(value) {
|
|
462
|
-
const root = record(value, "manifest");
|
|
463
|
-
exactKeys(root, [
|
|
464
|
-
"agents",
|
|
465
|
-
"automations",
|
|
466
|
-
"backgroundSessions",
|
|
467
|
-
"defaultAgentId",
|
|
468
|
-
"defaultEndpointId",
|
|
469
|
-
"endpoints",
|
|
470
|
-
"plugins",
|
|
471
|
-
"projectSpaces"
|
|
472
|
-
], "manifest", [
|
|
473
|
-
"automations",
|
|
474
|
-
"backgroundSessions",
|
|
475
|
-
"projectSpaces"
|
|
476
|
-
]);
|
|
477
|
-
const plugins = array(root.plugins, "manifest.plugins").map((entry, index) => {
|
|
478
|
-
const plugin = record(entry, `manifest.plugins[${index}]`);
|
|
479
|
-
exactKeys(plugin, [
|
|
480
|
-
"id",
|
|
481
|
-
"module",
|
|
482
|
-
"required"
|
|
483
|
-
], `manifest.plugins[${index}]`);
|
|
484
|
-
return Object.freeze({
|
|
485
|
-
id: string(plugin.id, `manifest.plugins[${index}].id`),
|
|
486
|
-
module: string(plugin.module, `manifest.plugins[${index}].module`),
|
|
487
|
-
required: boolean(plugin.required, `manifest.plugins[${index}].required`)
|
|
488
|
-
});
|
|
489
|
-
});
|
|
490
|
-
const agents = array(root.agents, "manifest.agents").map((entry, index) => {
|
|
491
|
-
const agent = record(entry, `manifest.agents[${index}]`);
|
|
492
|
-
exactKeys(agent, [
|
|
493
|
-
"agentId",
|
|
494
|
-
"endpointIds",
|
|
495
|
-
"memory",
|
|
496
|
-
"pluginId",
|
|
497
|
-
"profileId",
|
|
498
|
-
"projectSpaceId",
|
|
499
|
-
"runtime",
|
|
500
|
-
"runtimeTools",
|
|
501
|
-
"skills",
|
|
502
|
-
"tools"
|
|
503
|
-
], `manifest.agents[${index}]`, [
|
|
504
|
-
"memory",
|
|
505
|
-
"projectSpaceId",
|
|
506
|
-
"runtime",
|
|
507
|
-
"runtimeTools"
|
|
508
|
-
]);
|
|
509
|
-
const memory = agent.memory === void 0 ? void 0 : record(agent.memory, `manifest.agents[${index}].memory`);
|
|
510
|
-
if (memory) exactKeys(memory, ["scopes", "tool"], `manifest.agents[${index}].memory`);
|
|
511
|
-
const skills = record(agent.skills, `manifest.agents[${index}].skills`);
|
|
512
|
-
exactKeys(skills, ["allow"], `manifest.agents[${index}].skills`);
|
|
513
|
-
const tools = record(agent.tools, `manifest.agents[${index}].tools`);
|
|
514
|
-
exactKeys(tools, ["allow"], `manifest.agents[${index}].tools`);
|
|
515
|
-
const runtimeTools = agent.runtimeTools === void 0 ? void 0 : record(agent.runtimeTools, `manifest.agents[${index}].runtimeTools`);
|
|
516
|
-
if (runtimeTools) exactKeys(runtimeTools, ["allow"], `manifest.agents[${index}].runtimeTools`);
|
|
517
|
-
return Object.freeze({
|
|
518
|
-
agentId: string(agent.agentId, `manifest.agents[${index}].agentId`),
|
|
519
|
-
endpointIds: Object.freeze(array(agent.endpointIds, `manifest.agents[${index}].endpointIds`).map((item, itemIndex) => string(item, `manifest.agents[${index}].endpointIds[${itemIndex}]`))),
|
|
520
|
-
...memory ? { memory: Object.freeze({
|
|
521
|
-
scopes: Object.freeze(array(memory.scopes, `manifest.agents[${index}].memory.scopes`).map((item, itemIndex) => memoryScope(item, `manifest.agents[${index}].memory.scopes[${itemIndex}]`))),
|
|
522
|
-
tool: boolean(memory.tool, `manifest.agents[${index}].memory.tool`)
|
|
523
|
-
}) } : {},
|
|
524
|
-
pluginId: string(agent.pluginId, `manifest.agents[${index}].pluginId`),
|
|
525
|
-
profileId: string(agent.profileId, `manifest.agents[${index}].profileId`),
|
|
526
|
-
...agent.projectSpaceId === void 0 ? {} : { projectSpaceId: string(agent.projectSpaceId, `manifest.agents[${index}].projectSpaceId`) },
|
|
527
|
-
...agent.runtime === void 0 ? {} : { runtime: parseAgentRuntime(agent.runtime, `manifest.agents[${index}].runtime`) },
|
|
528
|
-
...runtimeTools ? { runtimeTools: Object.freeze({ allow: Object.freeze(uniqueRuntimeTools(array(runtimeTools.allow, `manifest.agents[${index}].runtimeTools.allow`).map((item, itemIndex) => runtimeToolId(item, `manifest.agents[${index}].runtimeTools.allow[${itemIndex}]`)), `manifest.agents[${index}].runtimeTools.allow`)) }) } : {},
|
|
529
|
-
skills: Object.freeze({ allow: Object.freeze(array(skills.allow, `manifest.agents[${index}].skills.allow`).map((item, itemIndex) => string(item, `manifest.agents[${index}].skills.allow[${itemIndex}]`))) }),
|
|
530
|
-
tools: Object.freeze({ allow: Object.freeze(array(tools.allow, `manifest.agents[${index}].tools.allow`).map((item, itemIndex) => string(item, `manifest.agents[${index}].tools.allow[${itemIndex}]`))) })
|
|
531
|
-
});
|
|
532
|
-
});
|
|
533
|
-
const endpoints = array(root.endpoints, "manifest.endpoints").map((entry, index) => {
|
|
534
|
-
const endpoint = record(entry, `manifest.endpoints[${index}]`);
|
|
535
|
-
exactKeys(endpoint, [
|
|
536
|
-
"agentId",
|
|
537
|
-
"allowedActors",
|
|
538
|
-
"baseUrl",
|
|
539
|
-
"cardStreamLeaseMs",
|
|
540
|
-
"credentialRef",
|
|
541
|
-
"enabled",
|
|
542
|
-
"experimental",
|
|
543
|
-
"groupPolicy",
|
|
544
|
-
"id",
|
|
545
|
-
"progressDisplay",
|
|
546
|
-
"required",
|
|
547
|
-
"sessionNamespace",
|
|
548
|
-
"streamMinIntervalMs"
|
|
549
|
-
], `manifest.endpoints[${index}]`, [
|
|
550
|
-
"allowedActors",
|
|
551
|
-
"cardStreamLeaseMs",
|
|
552
|
-
"experimental",
|
|
553
|
-
"progressDisplay"
|
|
554
|
-
]);
|
|
555
|
-
const experimental = endpoint.experimental === void 0 ? void 0 : record(endpoint.experimental, `manifest.endpoints[${index}].experimental`);
|
|
556
|
-
if (experimental) exactKeys(experimental, ["cotMessages"], `manifest.endpoints[${index}].experimental`);
|
|
557
|
-
return Object.freeze({
|
|
558
|
-
agentId: string(endpoint.agentId, `manifest.endpoints[${index}].agentId`),
|
|
559
|
-
...endpoint.allowedActors === void 0 ? {} : { allowedActors: Object.freeze(parseAllowedActors(endpoint.allowedActors, `manifest.endpoints[${index}].allowedActors`)) },
|
|
560
|
-
baseUrl: string(endpoint.baseUrl, `manifest.endpoints[${index}].baseUrl`),
|
|
561
|
-
cardStreamLeaseMs: endpoint.cardStreamLeaseMs === void 0 ? DEFAULT_MANIFEST_CARD_STREAM_LEASE_MS : positiveInteger(endpoint.cardStreamLeaseMs, `manifest.endpoints[${index}].cardStreamLeaseMs`),
|
|
562
|
-
credentialRef: string(endpoint.credentialRef, `manifest.endpoints[${index}].credentialRef`),
|
|
563
|
-
enabled: boolean(endpoint.enabled, `manifest.endpoints[${index}].enabled`),
|
|
564
|
-
...experimental ? { experimental: Object.freeze({ cotMessages: boolean(experimental.cotMessages, `manifest.endpoints[${index}].experimental.cotMessages`) }) } : {},
|
|
565
|
-
groupPolicy: groupPolicy(endpoint.groupPolicy, `manifest.endpoints[${index}].groupPolicy`),
|
|
566
|
-
id: string(endpoint.id, `manifest.endpoints[${index}].id`),
|
|
567
|
-
progressDisplay: endpoint.progressDisplay === void 0 ? DEFAULT_MANIFEST_CONVERSATION_PROGRESS_DISPLAY : progressDisplay(endpoint.progressDisplay, `manifest.endpoints[${index}].progressDisplay`),
|
|
568
|
-
required: boolean(endpoint.required, `manifest.endpoints[${index}].required`),
|
|
569
|
-
sessionNamespace: string(endpoint.sessionNamespace, `manifest.endpoints[${index}].sessionNamespace`),
|
|
570
|
-
streamMinIntervalMs: positiveInteger(endpoint.streamMinIntervalMs, `manifest.endpoints[${index}].streamMinIntervalMs`)
|
|
571
|
-
});
|
|
572
|
-
});
|
|
573
|
-
const automations = array(root.automations ?? [], "manifest.automations").map((entry, index) => {
|
|
574
|
-
const automation = record(entry, `manifest.automations[${index}]`);
|
|
575
|
-
exactKeys(automation, [
|
|
576
|
-
"agentId",
|
|
577
|
-
"delivery",
|
|
578
|
-
"enabled",
|
|
579
|
-
"id",
|
|
580
|
-
"required",
|
|
581
|
-
"schedule",
|
|
582
|
-
"templateId",
|
|
583
|
-
"timeZone"
|
|
584
|
-
], `manifest.automations[${index}]`);
|
|
585
|
-
const delivery = record(automation.delivery, `manifest.automations[${index}].delivery`);
|
|
586
|
-
exactKeys(delivery, [
|
|
587
|
-
"endpointId",
|
|
588
|
-
"targetRef",
|
|
589
|
-
"targetType"
|
|
590
|
-
], `manifest.automations[${index}].delivery`);
|
|
591
|
-
return Object.freeze({
|
|
592
|
-
agentId: string(automation.agentId, `manifest.automations[${index}].agentId`),
|
|
593
|
-
delivery: Object.freeze({
|
|
594
|
-
endpointId: string(delivery.endpointId, `manifest.automations[${index}].delivery.endpointId`),
|
|
595
|
-
targetRef: string(delivery.targetRef, `manifest.automations[${index}].delivery.targetRef`),
|
|
596
|
-
targetType: automationTargetType(delivery.targetType, `manifest.automations[${index}].delivery.targetType`)
|
|
597
|
-
}),
|
|
598
|
-
enabled: boolean(automation.enabled, `manifest.automations[${index}].enabled`),
|
|
599
|
-
id: string(automation.id, `manifest.automations[${index}].id`),
|
|
600
|
-
required: boolean(automation.required, `manifest.automations[${index}].required`),
|
|
601
|
-
schedule: string(automation.schedule, `manifest.automations[${index}].schedule`),
|
|
602
|
-
templateId: string(automation.templateId, `manifest.automations[${index}].templateId`),
|
|
603
|
-
timeZone: string(automation.timeZone, `manifest.automations[${index}].timeZone`)
|
|
604
|
-
});
|
|
605
|
-
});
|
|
606
|
-
const projectSpaces = array(root.projectSpaces ?? [], "manifest.projectSpaces").map((entry, index) => {
|
|
607
|
-
const projectSpace = record(entry, `manifest.projectSpaces[${index}]`);
|
|
608
|
-
exactKeys(projectSpace, [
|
|
609
|
-
"id",
|
|
610
|
-
"root",
|
|
611
|
-
"skills",
|
|
612
|
-
"workingDirectory"
|
|
613
|
-
], `manifest.projectSpaces[${index}]`);
|
|
614
|
-
const skills = record(projectSpace.skills, `manifest.projectSpaces[${index}].skills`);
|
|
615
|
-
exactKeys(skills, ["sources"], `manifest.projectSpaces[${index}].skills`);
|
|
616
|
-
return Object.freeze({
|
|
617
|
-
id: string(projectSpace.id, `manifest.projectSpaces[${index}].id`),
|
|
618
|
-
root: string(projectSpace.root, `manifest.projectSpaces[${index}].root`),
|
|
619
|
-
skills: Object.freeze({ sources: Object.freeze(array(skills.sources, `manifest.projectSpaces[${index}].skills.sources`).map((item, itemIndex) => string(item, `manifest.projectSpaces[${index}].skills.sources[${itemIndex}]`))) }),
|
|
620
|
-
workingDirectory: string(projectSpace.workingDirectory, `manifest.projectSpaces[${index}].workingDirectory`)
|
|
621
|
-
});
|
|
622
|
-
});
|
|
623
|
-
const backgroundSessions = root.backgroundSessions === void 0 ? void 0 : parseBackgroundSessions(record(root.backgroundSessions, "manifest.backgroundSessions"));
|
|
624
|
-
return Object.freeze({
|
|
625
|
-
agents: Object.freeze(agents),
|
|
626
|
-
automations: Object.freeze(automations),
|
|
627
|
-
...backgroundSessions ? { backgroundSessions } : {},
|
|
628
|
-
defaultAgentId: string(root.defaultAgentId, "manifest.defaultAgentId"),
|
|
629
|
-
defaultEndpointId: string(root.defaultEndpointId, "manifest.defaultEndpointId"),
|
|
630
|
-
endpoints: Object.freeze(endpoints),
|
|
631
|
-
plugins: Object.freeze(plugins),
|
|
632
|
-
projectSpaces: Object.freeze(projectSpaces)
|
|
633
|
-
});
|
|
634
|
-
}
|
|
635
|
-
//#endregion
|
|
636
|
-
//#region src/deployment/domain/endpoint/feishu-endpoint-credentials.ts
|
|
637
|
-
var FeishuEndpointCredentialError = class extends Error {
|
|
638
|
-
name = "FeishuEndpointCredentialError";
|
|
639
|
-
};
|
|
640
|
-
function required(env, variable) {
|
|
641
|
-
const value = env[variable]?.trim();
|
|
642
|
-
if (!value) throw new FeishuEndpointCredentialError(`${variable} is required`);
|
|
643
|
-
return value;
|
|
644
|
-
}
|
|
645
|
-
function resolveFeishuEndpointCredentials(credentialRef, env) {
|
|
646
|
-
if (!credentialRef.startsWith("env:")) throw new FeishuEndpointCredentialError("Feishu endpoint credentialRef must use env:<PREFIX>");
|
|
647
|
-
const prefix = credentialRef.slice(4);
|
|
648
|
-
if (!/^[A-Z][A-Z0-9_]*$/.test(prefix)) throw new FeishuEndpointCredentialError(`Invalid environment prefix in credentialRef: ${credentialRef}`);
|
|
649
|
-
return Object.freeze({
|
|
650
|
-
appId: required(env, `${prefix}_APP_ID`),
|
|
651
|
-
appSecret: required(env, `${prefix}_APP_SECRET`)
|
|
652
|
-
});
|
|
653
|
-
}
|
|
654
|
-
//#endregion
|
|
655
|
-
//#region src/home/infra/adapters/config/acp-runtime-environment.ts
|
|
656
|
-
async function resolveAcpRuntimeEnvironment(runtime, environment) {
|
|
657
|
-
const env = {};
|
|
658
|
-
for (const [name, reference] of Object.entries(runtime.env ?? {})) {
|
|
659
|
-
const variable = reference.slice(4);
|
|
660
|
-
const value = environment[variable];
|
|
661
|
-
if (value === void 0) throw new Error(`runtime.env.${name} references missing environment variable ${variable}`);
|
|
662
|
-
env[name] = value;
|
|
663
|
-
}
|
|
664
|
-
const candidates = isAbsolute(runtime.command) ? [runtime.command] : runtime.command.includes("/") || runtime.command.includes("\\") ? [] : (env.PATH ?? "/usr/bin:/bin").split(delimiter).map((directory) => join(directory, runtime.command));
|
|
665
|
-
for (const candidate of candidates) try {
|
|
666
|
-
if ((await stat(candidate)).isFile()) {
|
|
667
|
-
await access(candidate, constants.X_OK);
|
|
668
|
-
return {
|
|
669
|
-
command: isAbsolute(candidate) ? candidate : join(process.cwd(), candidate),
|
|
670
|
-
env
|
|
671
|
-
};
|
|
672
|
-
}
|
|
673
|
-
} catch {}
|
|
674
|
-
throw new Error("runtime.command must resolve to an executable file");
|
|
675
|
-
}
|
|
676
|
-
//#endregion
|
|
677
|
-
//#region src/home/infra/adapters/config/local-env-file.ts
|
|
678
|
-
var LocalEnvFileError = class extends Error {
|
|
679
|
-
constructor(message) {
|
|
680
|
-
super(message);
|
|
681
|
-
this.name = "LocalEnvFileError";
|
|
682
|
-
}
|
|
683
|
-
};
|
|
684
|
-
function mergeRivusDaemonEnv(fileEnv, overrideEnv) {
|
|
685
|
-
const merged = { ...fileEnv };
|
|
686
|
-
for (const [key, value] of Object.entries(overrideEnv)) if (value !== void 0) merged[key] = value;
|
|
687
|
-
return merged;
|
|
688
|
-
}
|
|
689
|
-
function unescapeDoubleQuotedValue(value) {
|
|
690
|
-
return value.replace(/\\(["\\nrt])/g, (_match, escaped) => {
|
|
691
|
-
switch (escaped) {
|
|
692
|
-
case "n": return "\n";
|
|
693
|
-
case "r": return "\r";
|
|
694
|
-
case "t": return " ";
|
|
695
|
-
default: return escaped;
|
|
696
|
-
}
|
|
697
|
-
});
|
|
698
|
-
}
|
|
699
|
-
function parseEnvValue(rawValue, lineNumber) {
|
|
700
|
-
const value = rawValue.trim();
|
|
701
|
-
if (!value) return "";
|
|
702
|
-
if (value.startsWith("'")) {
|
|
703
|
-
if (!value.endsWith("'")) throw new LocalEnvFileError(`Invalid single-quoted env value on line ${lineNumber}`);
|
|
704
|
-
return value.slice(1, -1).replaceAll("'\\''", "'");
|
|
705
|
-
}
|
|
706
|
-
if (value.startsWith("\"")) {
|
|
707
|
-
if (!value.endsWith("\"")) throw new LocalEnvFileError(`Invalid double-quoted env value on line ${lineNumber}`);
|
|
708
|
-
return unescapeDoubleQuotedValue(value.slice(1, -1));
|
|
709
|
-
}
|
|
710
|
-
return value;
|
|
711
|
-
}
|
|
712
|
-
function parseLocalEnvFile(contents) {
|
|
713
|
-
const env = {};
|
|
714
|
-
const lines = contents.split(/\r?\n/);
|
|
715
|
-
for (let index = 0; index < lines.length; index += 1) {
|
|
716
|
-
const trimmed = lines[index].trim();
|
|
717
|
-
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
718
|
-
const match = (trimmed.startsWith("export ") ? trimmed.slice(7).trimStart() : trimmed).match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
|
|
719
|
-
if (!match) throw new LocalEnvFileError(`Invalid env file line ${index + 1}`);
|
|
720
|
-
const key = match[1];
|
|
721
|
-
const rawValue = match[2];
|
|
722
|
-
env[key] = parseEnvValue(rawValue, index + 1);
|
|
723
|
-
}
|
|
724
|
-
return env;
|
|
725
|
-
}
|
|
726
|
-
async function loadLocalEnvFile(filePath) {
|
|
727
|
-
return parseLocalEnvFile(await readFile(filePath, "utf8"));
|
|
728
|
-
}
|
|
729
|
-
async function loadMergedLocalEnvFile(filePath, overrideEnv) {
|
|
730
|
-
return mergeRivusDaemonEnv(await loadLocalEnvFile(filePath), overrideEnv);
|
|
731
|
-
}
|
|
732
|
-
//#endregion
|
|
733
|
-
//#region src/home/infra/adapters/project/gateway-package-resources.ts
|
|
734
|
-
const packageManifestUrl = import.meta.resolve("@rivus/gateway/package.json");
|
|
735
|
-
const packageRootUrl = new URL("./", packageManifestUrl);
|
|
736
|
-
const gatewayPackageDirectory = fileURLToPath(packageRootUrl);
|
|
737
|
-
const gatewayPackageManifestPath = fileURLToPath(new URL("package.json", packageRootUrl));
|
|
738
|
-
const gatewayTemplateDirectory = fileURLToPath(new URL("templates/", packageRootUrl));
|
|
739
|
-
const gatewaySkillsDirectory = fileURLToPath(new URL("skills/", packageRootUrl));
|
|
740
|
-
const gatewayAudioTranscriberAssetDirectory = fileURLToPath(new URL("assets/audio-transcriber/", packageRootUrl));
|
|
741
|
-
//#endregion
|
|
742
|
-
//#region src/home/infra/adapters/project/release-descriptor.ts
|
|
743
|
-
const RIVUS_RELEASE_DESCRIPTOR = Object.freeze({
|
|
744
|
-
version: "0.22.2",
|
|
745
|
-
dependencies: Object.freeze({
|
|
746
|
-
"@earendil-works/pi-coding-agent": "0.84.4",
|
|
747
|
-
"@larksuiteoapi/node-sdk": "1.74.0",
|
|
748
|
-
effect: "4.1.1"
|
|
749
|
-
})
|
|
750
|
-
});
|
|
751
|
-
//#endregion
|
|
752
|
-
//#region src/deployment/infra/adapters/manifest/node-rivus-deployment-manifest.ts
|
|
753
|
-
var RivusDeploymentManifestError = class extends Error {
|
|
754
|
-
manifestPath;
|
|
755
|
-
name = "RivusDeploymentManifestError";
|
|
756
|
-
constructor(manifestPath, message, options) {
|
|
757
|
-
super(message, options);
|
|
758
|
-
this.manifestPath = manifestPath;
|
|
759
|
-
}
|
|
760
|
-
};
|
|
761
|
-
function loadRivusDeploymentManifest(manifestPath, options = {}) {
|
|
762
|
-
const maxBytes = options.maxBytes ?? 1048576;
|
|
763
|
-
return Effect.tryPromise({
|
|
764
|
-
try: async () => {
|
|
765
|
-
const metadata = await stat(manifestPath);
|
|
766
|
-
if (!metadata.isFile()) throw new Error("deployment manifest must be a regular file");
|
|
767
|
-
if (metadata.size > maxBytes) throw new Error(`deployment manifest exceeds ${maxBytes} byte limit`);
|
|
768
|
-
const bytes = await readFile(manifestPath);
|
|
769
|
-
const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
770
|
-
return parseRivusDeploymentManifest(JSON.parse(text));
|
|
771
|
-
},
|
|
772
|
-
catch: (cause) => cause instanceof RivusDeploymentManifestError ? cause : new RivusDeploymentManifestError(manifestPath, `failed to load Rivus deployment manifest: ${cause instanceof Error ? cause.message : String(cause)}`, { cause })
|
|
773
|
-
});
|
|
774
|
-
}
|
|
775
|
-
//#endregion
|
|
776
|
-
//#region src/model-management/infra/adapters/cli/rivus-model-cli-protocol.ts
|
|
777
|
-
const RIVUS_MODEL_CLI_USAGE = `Usage:
|
|
778
|
-
rivus model status --json [--request <id>] [--verbose]
|
|
779
|
-
rivus model set --model <provider/model> --expected-revision <n> --request <id> --json [--verbose]
|
|
780
|
-
rivus model rollback --expected-revision <n> --request <id> --json [--verbose]
|
|
781
|
-
|
|
782
|
-
Commands:
|
|
783
|
-
status Read the effective and persistent model selection
|
|
784
|
-
set Submit one authorized model change
|
|
785
|
-
rollback Submit one authorized change to the previous model
|
|
786
|
-
|
|
787
|
-
All command results are JSON. A successful set or rollback call means the request
|
|
788
|
-
was accepted; query status by request id for the final outcome.
|
|
789
|
-
`;
|
|
790
|
-
function renderRivusModelCliHelp() {
|
|
791
|
-
return RIVUS_MODEL_CLI_USAGE;
|
|
792
|
-
}
|
|
793
|
-
function renderRivusModelCliArgumentError(error) {
|
|
794
|
-
return `${error}\n\n${RIVUS_MODEL_CLI_USAGE}`;
|
|
795
|
-
}
|
|
796
|
-
function isModelReference(value) {
|
|
797
|
-
return /^[^/\s]+\/[^/\s]+$/.test(value);
|
|
798
|
-
}
|
|
799
|
-
function parseRevision(value) {
|
|
800
|
-
if (!/^\d+$/.test(value)) return;
|
|
801
|
-
const revision = Number(value);
|
|
802
|
-
return Number.isSafeInteger(revision) ? revision : void 0;
|
|
803
|
-
}
|
|
804
|
-
function parseRivusModelCliArguments(argv) {
|
|
805
|
-
if (argv.includes("--help") || argv.includes("-h")) return { help: true };
|
|
806
|
-
const operation = argv[0];
|
|
807
|
-
if (operation !== "status" && operation !== "set" && operation !== "rollback") return { error: "model requires one of status, set, rollback" };
|
|
808
|
-
let expectedRevision;
|
|
809
|
-
let json = false;
|
|
810
|
-
let model;
|
|
811
|
-
let requestId;
|
|
812
|
-
let verbose = false;
|
|
813
|
-
for (let index = 1; index < argv.length; index += 1) {
|
|
814
|
-
const argument = argv[index];
|
|
815
|
-
if (argument === "--json") {
|
|
816
|
-
if (json) return { error: "--json may only be provided once" };
|
|
817
|
-
json = true;
|
|
818
|
-
continue;
|
|
819
|
-
}
|
|
820
|
-
if (argument === "--verbose") {
|
|
821
|
-
if (verbose) return { error: "--verbose may only be provided once" };
|
|
822
|
-
verbose = true;
|
|
823
|
-
continue;
|
|
824
|
-
}
|
|
825
|
-
if (argument === "--request") {
|
|
826
|
-
if (requestId !== void 0) return { error: "--request may only be provided once" };
|
|
827
|
-
const value = argv[index + 1];
|
|
828
|
-
if (!value || value.startsWith("-")) return { error: "--request requires an id" };
|
|
829
|
-
requestId = value;
|
|
830
|
-
index += 1;
|
|
831
|
-
continue;
|
|
832
|
-
}
|
|
833
|
-
if (argument.startsWith("--request=")) {
|
|
834
|
-
if (requestId !== void 0) return { error: "--request may only be provided once" };
|
|
835
|
-
requestId = argument.slice(10);
|
|
836
|
-
if (!requestId) return { error: "--request requires an id" };
|
|
837
|
-
continue;
|
|
838
|
-
}
|
|
839
|
-
if (argument === "--expected-revision") {
|
|
840
|
-
if (expectedRevision !== void 0) return { error: "--expected-revision may only be provided once" };
|
|
841
|
-
const value = argv[index + 1];
|
|
842
|
-
if (!value || value.startsWith("-")) return { error: "--expected-revision requires a non-negative integer" };
|
|
843
|
-
const parsed = parseRevision(value);
|
|
844
|
-
if (parsed === void 0) return { error: "--expected-revision requires a non-negative integer" };
|
|
845
|
-
expectedRevision = parsed;
|
|
846
|
-
index += 1;
|
|
847
|
-
continue;
|
|
848
|
-
}
|
|
849
|
-
if (argument.startsWith("--expected-revision=")) {
|
|
850
|
-
if (expectedRevision !== void 0) return { error: "--expected-revision may only be provided once" };
|
|
851
|
-
const parsed = parseRevision(argument.slice(20));
|
|
852
|
-
if (parsed === void 0) return { error: "--expected-revision requires a non-negative integer" };
|
|
853
|
-
expectedRevision = parsed;
|
|
854
|
-
continue;
|
|
855
|
-
}
|
|
856
|
-
if (argument === "--model") {
|
|
857
|
-
if (model !== void 0) return { error: "--model may only be provided once" };
|
|
858
|
-
const value = argv[index + 1];
|
|
859
|
-
if (!value || value.startsWith("-")) return { error: "--model requires provider/model" };
|
|
860
|
-
if (!isModelReference(value)) return { error: "--model must be provider/model" };
|
|
861
|
-
model = value;
|
|
862
|
-
index += 1;
|
|
863
|
-
continue;
|
|
864
|
-
}
|
|
865
|
-
if (argument.startsWith("--model=")) {
|
|
866
|
-
if (model !== void 0) return { error: "--model may only be provided once" };
|
|
867
|
-
const value = argument.slice(8);
|
|
868
|
-
if (!isModelReference(value)) return { error: "--model must be provider/model" };
|
|
869
|
-
model = value;
|
|
870
|
-
continue;
|
|
871
|
-
}
|
|
872
|
-
return { error: `Unknown model option: ${argument}` };
|
|
873
|
-
}
|
|
874
|
-
if (!json) return { error: "model commands require --json" };
|
|
875
|
-
if (operation === "status") {
|
|
876
|
-
if (model !== void 0) return { error: "status does not accept --model" };
|
|
877
|
-
if (expectedRevision !== void 0) return { error: "status does not accept --expected-revision" };
|
|
878
|
-
return {
|
|
879
|
-
json: true,
|
|
880
|
-
operation,
|
|
881
|
-
...requestId !== void 0 ? { requestId } : {},
|
|
882
|
-
...verbose ? { verbose: true } : {}
|
|
883
|
-
};
|
|
884
|
-
}
|
|
885
|
-
if (requestId === void 0) return { error: "--request is required for model changes" };
|
|
886
|
-
if (expectedRevision === void 0) return { error: "--expected-revision is required for model changes" };
|
|
887
|
-
if (operation === "set" && model === void 0) return { error: "--model is required for model set" };
|
|
888
|
-
if (operation === "rollback" && model !== void 0) return { error: "rollback does not accept --model" };
|
|
889
|
-
return operation === "set" ? {
|
|
890
|
-
expectedRevision,
|
|
891
|
-
json: true,
|
|
892
|
-
model,
|
|
893
|
-
operation,
|
|
894
|
-
requestId,
|
|
895
|
-
...verbose ? { verbose: true } : {}
|
|
896
|
-
} : {
|
|
897
|
-
expectedRevision,
|
|
898
|
-
json: true,
|
|
899
|
-
operation,
|
|
900
|
-
requestId,
|
|
901
|
-
...verbose ? { verbose: true } : {}
|
|
902
|
-
};
|
|
903
|
-
}
|
|
904
|
-
//#endregion
|
|
905
|
-
//#region src/model-management/infra/adapters/cli/rivus-model-management-wire.ts
|
|
906
|
-
/**
|
|
907
|
-
* Object gate for a wire request: the parser reports its fields in a fixed order with one error text each, which a
|
|
908
|
-
* single decode cannot express (authoring guide, Validation). Handler responses decode through `handlerResponse` below.
|
|
909
|
-
*/
|
|
910
|
-
const wireRequestGate = Schema.Record(Schema.String, Schema.Unknown);
|
|
911
|
-
const absent = () => Effect.succeed(Option.none());
|
|
912
|
-
/** A wrong-typed response field reads as absent, as the CLI projection always treated it. */
|
|
913
|
-
const tolerant = (schema) => Schema.optionalKey(schema.pipe(Schema.catchDecoding(absent)));
|
|
914
|
-
const text = tolerant(Schema.String);
|
|
915
|
-
const scalar = tolerant(Schema.Union([
|
|
916
|
-
Schema.String,
|
|
917
|
-
Schema.Number,
|
|
918
|
-
Schema.Boolean
|
|
919
|
-
]));
|
|
920
|
-
const modelReference = Schema.Struct({
|
|
921
|
-
bindingRevision: text,
|
|
922
|
-
label: text,
|
|
923
|
-
model: Schema.String,
|
|
924
|
-
provider: Schema.String
|
|
925
|
-
});
|
|
926
|
-
const errorSection = Schema.Struct({
|
|
927
|
-
code: Schema.String,
|
|
928
|
-
message: Schema.String
|
|
929
|
-
});
|
|
930
|
-
const budgetSection = Schema.Struct({
|
|
931
|
-
deadlineAt: scalar,
|
|
932
|
-
maxOutputTokens: scalar,
|
|
933
|
-
maxPaidRequests: scalar,
|
|
934
|
-
outputTokens: scalar,
|
|
935
|
-
paidRequests: scalar
|
|
936
|
-
});
|
|
937
|
-
const notificationSection = Schema.Struct({
|
|
938
|
-
attempts: scalar,
|
|
939
|
-
lastAttemptAt: scalar,
|
|
940
|
-
status: scalar
|
|
941
|
-
});
|
|
942
|
-
const receiptSection = Schema.Struct({
|
|
943
|
-
acceptedAt: scalar,
|
|
944
|
-
budget: tolerant(budgetSection),
|
|
945
|
-
current: tolerant(modelReference),
|
|
946
|
-
error: tolerant(errorSection),
|
|
947
|
-
expectedRevision: scalar,
|
|
948
|
-
notification: tolerant(notificationSection),
|
|
949
|
-
operation: scalar,
|
|
950
|
-
phase: scalar,
|
|
951
|
-
previous: tolerant(modelReference),
|
|
952
|
-
requestId: scalar,
|
|
953
|
-
revision: scalar,
|
|
954
|
-
status: scalar,
|
|
955
|
-
target: tolerant(modelReference),
|
|
956
|
-
updatedAt: scalar
|
|
957
|
-
});
|
|
958
|
-
const pendingSection = Schema.Struct({
|
|
959
|
-
phase: scalar,
|
|
960
|
-
reason: scalar,
|
|
961
|
-
request: tolerant(receiptSection),
|
|
962
|
-
requestId: scalar,
|
|
963
|
-
target: tolerant(modelReference),
|
|
964
|
-
updatedAt: scalar
|
|
965
|
-
});
|
|
966
|
-
const publicStatus = Schema.Literals([
|
|
967
|
-
"applied",
|
|
968
|
-
"failed",
|
|
969
|
-
"pending",
|
|
970
|
-
"recovery-required",
|
|
971
|
-
"restored"
|
|
972
|
-
]);
|
|
973
|
-
const handlerResponse = Schema.Struct({
|
|
974
|
-
actual: tolerant(modelReference),
|
|
975
|
-
budget: tolerant(budgetSection),
|
|
976
|
-
current: tolerant(modelReference),
|
|
977
|
-
error: tolerant(errorSection),
|
|
978
|
-
expectedRevision: scalar,
|
|
979
|
-
notification: tolerant(notificationSection),
|
|
980
|
-
operation: scalar,
|
|
981
|
-
pending: Schema.optionalKey(Schema.Unknown),
|
|
982
|
-
persisted: tolerant(modelReference),
|
|
983
|
-
phase: scalar,
|
|
984
|
-
previous: tolerant(modelReference),
|
|
985
|
-
protocolVersion: scalar,
|
|
986
|
-
reason: scalar,
|
|
987
|
-
recoveryRequired: Schema.optionalKey(Schema.Unknown),
|
|
988
|
-
request: tolerant(receiptSection),
|
|
989
|
-
requestId: scalar,
|
|
990
|
-
revision: scalar,
|
|
991
|
-
runtimeVersion: scalar,
|
|
992
|
-
source: scalar,
|
|
993
|
-
status: tolerant(publicStatus),
|
|
994
|
-
target: tolerant(modelReference)
|
|
995
|
-
});
|
|
996
|
-
const decodeHandlerResponse = Schema.decodeUnknownOption(handlerResponse);
|
|
997
|
-
const decodePendingSection = Schema.decodeUnknownOption(pendingSection);
|
|
998
|
-
const decodeErrorSection = Schema.decodeUnknownOption(errorSection);
|
|
999
|
-
function createRivusModelManagementFailure(code, message) {
|
|
1000
|
-
return {
|
|
1001
|
-
error: {
|
|
1002
|
-
code,
|
|
1003
|
-
message
|
|
1004
|
-
},
|
|
1005
|
-
schemaVersion: 1,
|
|
1006
|
-
status: "failed"
|
|
1007
|
-
};
|
|
1008
|
-
}
|
|
1009
|
-
function projectModelReference(value) {
|
|
1010
|
-
if (!value) return;
|
|
1011
|
-
const result = {
|
|
1012
|
-
model: value.model,
|
|
1013
|
-
provider: value.provider
|
|
1014
|
-
};
|
|
1015
|
-
if (value.label !== void 0) return {
|
|
1016
|
-
...result,
|
|
1017
|
-
label: value.label
|
|
1018
|
-
};
|
|
1019
|
-
if (value.bindingRevision !== void 0) return {
|
|
1020
|
-
...result,
|
|
1021
|
-
bindingRevision: value.bindingRevision
|
|
1022
|
-
};
|
|
1023
|
-
return result;
|
|
1024
|
-
}
|
|
1025
|
-
function projectError(value) {
|
|
1026
|
-
return value ? {
|
|
1027
|
-
code: value.code,
|
|
1028
|
-
message: value.message
|
|
1029
|
-
} : void 0;
|
|
1030
|
-
}
|
|
1031
|
-
function copyScalars(target, source, keys) {
|
|
1032
|
-
for (const key of keys) {
|
|
1033
|
-
const value = source[key];
|
|
1034
|
-
if (value !== void 0) target[key] = value;
|
|
1035
|
-
}
|
|
1036
|
-
}
|
|
1037
|
-
function scalarSection(value, keys) {
|
|
1038
|
-
if (!value) return;
|
|
1039
|
-
const result = {};
|
|
1040
|
-
copyScalars(result, value, keys);
|
|
1041
|
-
return Object.keys(result).length > 0 ? result : void 0;
|
|
1042
|
-
}
|
|
1043
|
-
function projectBudget(value) {
|
|
1044
|
-
return scalarSection(value, [
|
|
1045
|
-
"deadlineAt",
|
|
1046
|
-
"maxOutputTokens",
|
|
1047
|
-
"maxPaidRequests",
|
|
1048
|
-
"outputTokens",
|
|
1049
|
-
"paidRequests"
|
|
1050
|
-
]);
|
|
1051
|
-
}
|
|
1052
|
-
function projectNotification(value) {
|
|
1053
|
-
return scalarSection(value, [
|
|
1054
|
-
"attempts",
|
|
1055
|
-
"lastAttemptAt",
|
|
1056
|
-
"status"
|
|
1057
|
-
]);
|
|
1058
|
-
}
|
|
1059
|
-
function projectReceipt(value) {
|
|
1060
|
-
if (!value) return;
|
|
1061
|
-
const result = {};
|
|
1062
|
-
copyScalars(result, value, [
|
|
1063
|
-
"requestId",
|
|
1064
|
-
"revision",
|
|
1065
|
-
"status",
|
|
1066
|
-
"phase",
|
|
1067
|
-
"operation",
|
|
1068
|
-
"expectedRevision",
|
|
1069
|
-
"acceptedAt",
|
|
1070
|
-
"updatedAt"
|
|
1071
|
-
]);
|
|
1072
|
-
for (const key of [
|
|
1073
|
-
"current",
|
|
1074
|
-
"previous",
|
|
1075
|
-
"target"
|
|
1076
|
-
]) {
|
|
1077
|
-
const model = projectModelReference(value[key]);
|
|
1078
|
-
if (model) result[key] = model;
|
|
1079
|
-
}
|
|
1080
|
-
const budget = projectBudget(value.budget);
|
|
1081
|
-
if (budget) result.budget = budget;
|
|
1082
|
-
const error = projectError(value.error);
|
|
1083
|
-
if (error) result.error = error;
|
|
1084
|
-
const notification = projectNotification(value.notification);
|
|
1085
|
-
if (notification) result.notification = notification;
|
|
1086
|
-
return Object.keys(result).length > 0 ? result : void 0;
|
|
1087
|
-
}
|
|
1088
|
-
function projectPending(raw) {
|
|
1089
|
-
const decoded = decodePendingSection(raw);
|
|
1090
|
-
if (Option.isNone(decoded)) return;
|
|
1091
|
-
const value = decoded.value;
|
|
1092
|
-
const result = {};
|
|
1093
|
-
copyScalars(result, value, ["phase", "reason"]);
|
|
1094
|
-
if (result.reason === void 0 && typeof value.phase === "string") result.reason = value.phase;
|
|
1095
|
-
copyScalars(result, value, ["requestId", "updatedAt"]);
|
|
1096
|
-
const request = projectReceipt(value.request);
|
|
1097
|
-
if (request) result.request = request;
|
|
1098
|
-
const target = projectModelReference(value.target);
|
|
1099
|
-
if (target) result.target = target;
|
|
1100
|
-
return Object.keys(result).length > 0 ? result : void 0;
|
|
1101
|
-
}
|
|
1102
|
-
function projectRivusModelCliResponse(value, operation) {
|
|
1103
|
-
const decoded = decodeHandlerResponse(value);
|
|
1104
|
-
if (Option.isNone(decoded)) throw new Error("model handler must return a JSON object");
|
|
1105
|
-
const handler = decoded.value;
|
|
1106
|
-
const response = { schemaVersion: 1 };
|
|
1107
|
-
copyScalars(response, handler, [
|
|
1108
|
-
"requestId",
|
|
1109
|
-
"revision",
|
|
1110
|
-
"source",
|
|
1111
|
-
"protocolVersion",
|
|
1112
|
-
"runtimeVersion",
|
|
1113
|
-
"operation",
|
|
1114
|
-
"expectedRevision",
|
|
1115
|
-
"phase",
|
|
1116
|
-
"reason"
|
|
1117
|
-
]);
|
|
1118
|
-
for (const key of [
|
|
1119
|
-
"actual",
|
|
1120
|
-
"current",
|
|
1121
|
-
"persisted",
|
|
1122
|
-
"previous",
|
|
1123
|
-
"target"
|
|
1124
|
-
]) {
|
|
1125
|
-
const model = projectModelReference(handler[key]);
|
|
1126
|
-
if (model) response[key] = model;
|
|
1127
|
-
}
|
|
1128
|
-
const budget = projectBudget(handler.budget);
|
|
1129
|
-
if (budget) response.budget = budget;
|
|
1130
|
-
const pending = projectPending(handler.pending);
|
|
1131
|
-
if (pending) response.pending = pending;
|
|
1132
|
-
const request = projectReceipt(handler.request);
|
|
1133
|
-
if (request) response.request = request;
|
|
1134
|
-
const error = projectError(handler.error);
|
|
1135
|
-
if (error) response.error = error;
|
|
1136
|
-
const recoveryRequired = projectError(Option.getOrUndefined(decodeErrorSection(handler.recoveryRequired)));
|
|
1137
|
-
if (recoveryRequired) response.recoveryRequired = recoveryRequired;
|
|
1138
|
-
const notification = projectNotification(handler.notification);
|
|
1139
|
-
if (notification) response.notification = notification;
|
|
1140
|
-
response.status = handler.status ?? (handler.recoveryRequired !== void 0 ? "recovery-required" : operation === "status" && handler.pending !== void 0 ? "pending" : operation === "status" ? "applied" : "failed");
|
|
1141
|
-
return response;
|
|
1142
|
-
}
|
|
1143
|
-
function parseTarget(value) {
|
|
1144
|
-
if (!value) throw new Error("model request target is missing");
|
|
1145
|
-
const separator = value.indexOf("/");
|
|
1146
|
-
return {
|
|
1147
|
-
model: value.slice(separator + 1),
|
|
1148
|
-
provider: value.slice(0, separator)
|
|
1149
|
-
};
|
|
1150
|
-
}
|
|
1151
|
-
function toRivusModelManagementSubmission(request) {
|
|
1152
|
-
const target = request.operation === "set" ? parseTarget(request.model) : void 0;
|
|
1153
|
-
return {
|
|
1154
|
-
expectedRevision: request.expectedRevision,
|
|
1155
|
-
operation: request.operation,
|
|
1156
|
-
requestId: request.requestId,
|
|
1157
|
-
...target ? { target } : {},
|
|
1158
|
-
...request.verbose ? { verbose: true } : {}
|
|
1159
|
-
};
|
|
1160
|
-
}
|
|
1161
|
-
function optionalString(value) {
|
|
1162
|
-
return typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
1163
|
-
}
|
|
1164
|
-
function createRivusModelManagementWireRequest(command, env) {
|
|
1165
|
-
const context = optionalString(env.RIVUS_MODEL_CONTEXT);
|
|
1166
|
-
return {
|
|
1167
|
-
...command,
|
|
1168
|
-
...context ? { context } : {}
|
|
1169
|
-
};
|
|
1170
|
-
}
|
|
1171
|
-
function parseRivusModelManagementWireRequest(value) {
|
|
1172
|
-
if (!Schema.is(wireRequestGate)(value)) throw new Error("model request must be a JSON object");
|
|
1173
|
-
const operation = value.operation;
|
|
1174
|
-
if (operation !== "status" && operation !== "set" && operation !== "rollback") throw new Error("model request operation is invalid");
|
|
1175
|
-
const context = optionalString(value.context);
|
|
1176
|
-
const requestId = optionalString(value.requestId);
|
|
1177
|
-
const verbose = value.verbose === true ? true : void 0;
|
|
1178
|
-
if (operation === "status") {
|
|
1179
|
-
if (value.json !== true) throw new Error("model request must require JSON output");
|
|
1180
|
-
return {
|
|
1181
|
-
json: true,
|
|
1182
|
-
operation,
|
|
1183
|
-
...context ? { context } : {},
|
|
1184
|
-
...requestId ? { requestId } : {},
|
|
1185
|
-
...verbose ? { verbose: true } : {}
|
|
1186
|
-
};
|
|
1187
|
-
}
|
|
1188
|
-
const expectedRevision = value.expectedRevision;
|
|
1189
|
-
if (value.json !== true || typeof expectedRevision !== "number" || !Number.isSafeInteger(expectedRevision) || expectedRevision < 0) throw new Error("model request has an invalid expected revision or output mode");
|
|
1190
|
-
if (!requestId) throw new Error("model request requires a request id");
|
|
1191
|
-
if (operation === "set") {
|
|
1192
|
-
const model = optionalString(value.model);
|
|
1193
|
-
if (!model || !/^[^/\s]+\/[^/\s]+$/.test(model)) throw new Error("model request target is invalid");
|
|
1194
|
-
return {
|
|
1195
|
-
expectedRevision,
|
|
1196
|
-
json: true,
|
|
1197
|
-
model,
|
|
1198
|
-
operation,
|
|
1199
|
-
requestId,
|
|
1200
|
-
...context ? { context } : {},
|
|
1201
|
-
...verbose ? { verbose: true } : {}
|
|
1202
|
-
};
|
|
1203
|
-
}
|
|
1204
|
-
return {
|
|
1205
|
-
expectedRevision,
|
|
1206
|
-
json: true,
|
|
1207
|
-
operation,
|
|
1208
|
-
requestId,
|
|
1209
|
-
...context ? { context } : {},
|
|
1210
|
-
...verbose ? { verbose: true } : {}
|
|
1211
|
-
};
|
|
1212
|
-
}
|
|
1213
|
-
//#endregion
|
|
1214
|
-
//#region src/model-management/infra/adapters/config/rivus-model-management-config-migration.ts
|
|
1215
|
-
const RIVUS_MODEL_MANAGEMENT_ENABLED_ENV = "RIVUS_MODEL_MANAGEMENT_ENABLED";
|
|
1216
|
-
const RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID_ENV = "RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID";
|
|
1217
|
-
const RIVUS_MODEL_MANAGEMENT_TENANT_KEY_ENV = "RIVUS_MODEL_MANAGEMENT_TENANT_KEY";
|
|
1218
|
-
const RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL_ENV = "RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL";
|
|
1219
|
-
var RivusModelManagementConfigError = class extends Error {
|
|
1220
|
-
code;
|
|
1221
|
-
name = "RivusModelManagementConfigError";
|
|
1222
|
-
constructor(code, message) {
|
|
1223
|
-
super(message);
|
|
1224
|
-
this.code = code;
|
|
1225
|
-
}
|
|
1226
|
-
};
|
|
1227
|
-
function parseStrictBoolean(value, variable, defaultValue) {
|
|
1228
|
-
if (value === void 0) return defaultValue;
|
|
1229
|
-
const normalized = value.trim();
|
|
1230
|
-
if (normalized === "true") return true;
|
|
1231
|
-
if (normalized === "false") return false;
|
|
1232
|
-
throw new RivusModelManagementConfigError("invalid_enabled", `${variable} must be true or false`);
|
|
1233
|
-
}
|
|
1234
|
-
function parseRivusModelManagementEnabled(value) {
|
|
1235
|
-
return parseStrictBoolean(value, RIVUS_MODEL_MANAGEMENT_ENABLED_ENV, false);
|
|
1236
|
-
}
|
|
1237
|
-
function sameModel(left, right) {
|
|
1238
|
-
return left.provider === right.provider && left.model === right.model;
|
|
1239
|
-
}
|
|
1240
|
-
async function loadEnvFile(envFilePath, env) {
|
|
1241
|
-
try {
|
|
1242
|
-
return await loadMergedLocalEnvFile(envFilePath, env);
|
|
1243
|
-
} catch {
|
|
1244
|
-
throw new RivusModelManagementConfigError("env_source_unreadable", "the original env source could not be loaded");
|
|
1245
|
-
}
|
|
1246
|
-
}
|
|
1247
|
-
async function readWritableEnvFile(envFilePath) {
|
|
1248
|
-
try {
|
|
1249
|
-
const contents = await readFile(envFilePath, "utf8");
|
|
1250
|
-
if (((await stat(envFilePath)).mode & 146) === 0) throw new RivusModelManagementConfigError("env_source_unwritable", "the original env source is not writable");
|
|
1251
|
-
await access(envFilePath, constants.W_OK);
|
|
1252
|
-
return contents;
|
|
1253
|
-
} catch (error) {
|
|
1254
|
-
if (error instanceof RivusModelManagementConfigError) throw error;
|
|
1255
|
-
if (isNodeErrorWithCode(error, "EACCES") || isNodeErrorWithCode(error, "EPERM") || isNodeErrorWithCode(error, "EROFS")) throw new RivusModelManagementConfigError("env_source_unwritable", "the original env source is not writable");
|
|
1256
|
-
throw new RivusModelManagementConfigError("env_source_unreadable", "the original env source is unavailable");
|
|
1257
|
-
}
|
|
1258
|
-
}
|
|
1259
|
-
function replacePiModel(contents, model) {
|
|
1260
|
-
const modelValue = `${model.provider}/${model.model}`;
|
|
1261
|
-
const parts = contents.split(/(\r\n|\n|\r)/);
|
|
1262
|
-
let replaced = false;
|
|
1263
|
-
for (let index = 0; index < parts.length; index += 2) {
|
|
1264
|
-
const line = parts[index];
|
|
1265
|
-
if (line === void 0) continue;
|
|
1266
|
-
const match = line.match(/^(\s*(?:export\s+)?PI_MODEL\s*=\s*)(.*)$/);
|
|
1267
|
-
if (!match) continue;
|
|
1268
|
-
const inlineComment = match[2].match(/(\s+#.*)$/)?.[1] ?? "";
|
|
1269
|
-
parts[index] = `${match[1]}${modelValue}${inlineComment}`;
|
|
1270
|
-
replaced = true;
|
|
1271
|
-
}
|
|
1272
|
-
if (replaced) return parts.join("");
|
|
1273
|
-
const newline = contents.includes("\r\n") ? "\r\n" : contents.includes("\n") ? "\n" : "\n";
|
|
1274
|
-
if (!contents) return `PI_MODEL=${modelValue}${newline}`;
|
|
1275
|
-
return /(?:\r\n|\n|\r)$/.test(contents) ? `${contents}PI_MODEL=${modelValue}${newline}` : `${contents}${newline}PI_MODEL=${modelValue}`;
|
|
1276
|
-
}
|
|
1277
|
-
function hasAmbientModelOverride(env) {
|
|
1278
|
-
return Object.prototype.hasOwnProperty.call(env, "PI_MODEL") && env.PI_MODEL !== void 0;
|
|
1279
|
-
}
|
|
1280
|
-
function isModelPart(value) {
|
|
1281
|
-
return value.trim() === value && value.length > 0 && !/[/\s]/.test(value);
|
|
1282
|
-
}
|
|
1283
|
-
function parseModelReference(provider, model) {
|
|
1284
|
-
if (!isModelPart(provider) || !isModelPart(model)) throw new RivusModelManagementConfigError("invalid_model", "known-good model provider and id are invalid");
|
|
1285
|
-
return Object.freeze({
|
|
1286
|
-
model,
|
|
1287
|
-
provider
|
|
1288
|
-
});
|
|
1289
|
-
}
|
|
1290
|
-
function optional(value) {
|
|
1291
|
-
return value?.trim() || void 0;
|
|
1292
|
-
}
|
|
1293
|
-
/** Parse the Home capability flags without accepting truthy arbitrary strings. */
|
|
1294
|
-
function parseRivusModelManagementHomeConfig(env) {
|
|
1295
|
-
const enabled = parseRivusModelManagementEnabled(env[RIVUS_MODEL_MANAGEMENT_ENABLED_ENV]);
|
|
1296
|
-
const requireApproval = parseStrictBoolean(env[RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL_ENV], RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL_ENV, false);
|
|
1297
|
-
const ownerOpenId = optional(env[RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID_ENV]);
|
|
1298
|
-
const tenantKey = optional(env[RIVUS_MODEL_MANAGEMENT_TENANT_KEY_ENV]);
|
|
1299
|
-
if (enabled && !ownerOpenId) throw new RivusModelManagementConfigError("owner_missing", `${RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID_ENV} is required when model management is enabled`);
|
|
1300
|
-
if (enabled && !tenantKey) throw new RivusModelManagementConfigError("tenant_missing", `${RIVUS_MODEL_MANAGEMENT_TENANT_KEY_ENV} is required when model management is enabled`);
|
|
1301
|
-
return Object.freeze({
|
|
1302
|
-
enabled,
|
|
1303
|
-
...ownerOpenId ? { ownerOpenId } : {},
|
|
1304
|
-
requireApproval,
|
|
1305
|
-
...tenantKey ? { tenantKey } : {}
|
|
1306
|
-
});
|
|
1307
|
-
}
|
|
1308
|
-
function parseConfiguredModel(value) {
|
|
1309
|
-
const configured = optional(value);
|
|
1310
|
-
if (!configured) throw new RivusModelManagementConfigError("model_missing", "PI_MODEL is missing from the effective legacy config");
|
|
1311
|
-
const separator = configured.indexOf("/");
|
|
1312
|
-
if (separator <= 0 || separator === configured.length - 1 || configured.indexOf("/", separator + 1) !== -1) throw new RivusModelManagementConfigError("invalid_model", "PI_MODEL must use provider/model form");
|
|
1313
|
-
return parseModelReference(configured.slice(0, separator), configured.slice(separator + 1));
|
|
1314
|
-
}
|
|
1315
|
-
function parseOptionalConfiguredModel(value) {
|
|
1316
|
-
if (!optional(value)) return;
|
|
1317
|
-
try {
|
|
1318
|
-
return parseConfiguredModel(value);
|
|
1319
|
-
} catch {
|
|
1320
|
-
return;
|
|
1321
|
-
}
|
|
1322
|
-
}
|
|
1323
|
-
function requireEnvFilePath(value) {
|
|
1324
|
-
const normalized = optional(value);
|
|
1325
|
-
if (!normalized) throw new RivusModelManagementConfigError("env_source_missing", "an explicit writable original env source is required for model management migration");
|
|
1326
|
-
return normalized;
|
|
1327
|
-
}
|
|
1328
|
-
async function enableModelManagement(input) {
|
|
1329
|
-
if (hasAmbientModelOverride(input.env)) return {
|
|
1330
|
-
initialModel: parseConfiguredModel(input.env.PI_MODEL),
|
|
1331
|
-
source: "ambient",
|
|
1332
|
-
status: "enabled"
|
|
1333
|
-
};
|
|
1334
|
-
return {
|
|
1335
|
-
initialModel: parseConfiguredModel((await loadEnvFile(requireEnvFilePath(input.envFilePath), input.env)).PI_MODEL),
|
|
1336
|
-
source: "env-file",
|
|
1337
|
-
status: "enabled"
|
|
1338
|
-
};
|
|
1339
|
-
}
|
|
1340
|
-
async function disableModelManagement(input, knownGood) {
|
|
1341
|
-
const envFilePath = requireEnvFilePath(input.envFilePath);
|
|
1342
|
-
if (hasAmbientModelOverride(input.env)) throw new RivusModelManagementConfigError("ambient_model_override", "ambient PI_MODEL overrides the original env source and prevents verified model readback");
|
|
1343
|
-
const original = await readWritableEnvFile(envFilePath);
|
|
1344
|
-
const existingModel = parseOptionalConfiguredModel((await loadEnvFile(envFilePath, input.env)).PI_MODEL);
|
|
1345
|
-
if (existingModel && sameModel(existingModel, knownGood)) return {
|
|
1346
|
-
restoredModel: knownGood,
|
|
1347
|
-
source: "env-file",
|
|
1348
|
-
status: "unchanged"
|
|
1349
|
-
};
|
|
1350
|
-
const next = replacePiModel(original, knownGood);
|
|
1351
|
-
try {
|
|
1352
|
-
await input.writeAtomicTextFile(envFilePath, next, { durable: true });
|
|
1353
|
-
} catch {
|
|
1354
|
-
throw new RivusModelManagementConfigError("env_source_write_failed", "the original env source write did not complete with a known durable result");
|
|
1355
|
-
}
|
|
1356
|
-
let readBack;
|
|
1357
|
-
try {
|
|
1358
|
-
readBack = parseConfiguredModel((await loadMergedLocalEnvFile(envFilePath, input.env)).PI_MODEL);
|
|
1359
|
-
} catch {
|
|
1360
|
-
throw new RivusModelManagementConfigError("readback_mismatch", "the original env source could not be verified after restoring PI_MODEL");
|
|
1361
|
-
}
|
|
1362
|
-
if (readBack.provider !== knownGood.provider || readBack.model !== knownGood.model) throw new RivusModelManagementConfigError("readback_mismatch", "the original env source did not read back the known-good PI_MODEL");
|
|
1363
|
-
return {
|
|
1364
|
-
restoredModel: knownGood,
|
|
1365
|
-
source: "env-file",
|
|
1366
|
-
status: "exported"
|
|
1367
|
-
};
|
|
1368
|
-
}
|
|
1369
|
-
/**
|
|
1370
|
-
* Migrate only the legacy model selection at the explicit enable/disable
|
|
1371
|
-
* boundary. The helper does not read or write managed model state.
|
|
1372
|
-
*/
|
|
1373
|
-
async function migrateRivusModelManagementConfig(input) {
|
|
1374
|
-
if (typeof input.managementEnabled !== "boolean") throw new RivusModelManagementConfigError("invalid_enabled", "model management enabled state must be boolean");
|
|
1375
|
-
if (input.managementEnabled) return enableModelManagement(input);
|
|
1376
|
-
return disableModelManagement(input, parseModelReference(input.knownGoodProvider, input.knownGoodModel));
|
|
1377
|
-
}
|
|
1378
|
-
//#endregion
|
|
1379
|
-
//#region src/agent-host/infra/adapters/runtime-cache.ts
|
|
1380
|
-
function createRuntimeCache() {
|
|
1381
|
-
const entries = /* @__PURE__ */ new Map();
|
|
1382
|
-
const serial = Semaphore.makeUnsafe(1);
|
|
1383
|
-
const reserve = (key) => serial.withPermits(1)(Effect.gen(function* () {
|
|
1384
|
-
const current = entries.get(key);
|
|
1385
|
-
if (current) return {
|
|
1386
|
-
created: false,
|
|
1387
|
-
entry: current
|
|
1388
|
-
};
|
|
1389
|
-
const entry = {
|
|
1390
|
-
deferred: yield* Deferred.make(),
|
|
1391
|
-
initializationStarted: false,
|
|
1392
|
-
key
|
|
1393
|
-
};
|
|
1394
|
-
entries.set(key, entry);
|
|
1395
|
-
return {
|
|
1396
|
-
created: true,
|
|
1397
|
-
entry
|
|
1398
|
-
};
|
|
1399
|
-
}));
|
|
1400
|
-
const start = (entry, create) => Effect.uninterruptible(Effect.gen(function* () {
|
|
1401
|
-
if (!(yield* serial.withPermits(1)(Effect.sync(() => {
|
|
1402
|
-
if (entry.initializationStarted) return false;
|
|
1403
|
-
entry.initializationStarted = true;
|
|
1404
|
-
return true;
|
|
1405
|
-
})))) return;
|
|
1406
|
-
const initialization = create().pipe(Effect.tapError(() => serial.withPermits(1)(Effect.sync(() => {
|
|
1407
|
-
if (entries.get(entry.key) === entry) entries.delete(entry.key);
|
|
1408
|
-
}))), Effect.exit, Effect.flatMap((exit) => Deferred.done(entry.deferred, exit)), Effect.asVoid);
|
|
1409
|
-
yield* Effect.forkDetach(initialization, { uninterruptible: "inherit" });
|
|
1410
|
-
}));
|
|
1411
|
-
const getOrCreate = (key, create) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
|
|
1412
|
-
const selected = yield* reserve(key);
|
|
1413
|
-
yield* start(selected.entry, create);
|
|
1414
|
-
return {
|
|
1415
|
-
entry: selected.entry,
|
|
1416
|
-
runtime: yield* restore(Deferred.await(selected.entry.deferred))
|
|
1417
|
-
};
|
|
1418
|
-
}));
|
|
1419
|
-
return {
|
|
1420
|
-
drain: () => serial.withPermits(1)(Effect.sync(() => {
|
|
1421
|
-
const drained = Object.freeze([...entries.values()]);
|
|
1422
|
-
entries.clear();
|
|
1423
|
-
return drained;
|
|
1424
|
-
})),
|
|
1425
|
-
getExisting: (key) => Effect.gen(function* () {
|
|
1426
|
-
const entry = yield* serial.withPermits(1)(Effect.sync(() => entries.get(key)));
|
|
1427
|
-
if (!entry) return;
|
|
1428
|
-
return {
|
|
1429
|
-
entry,
|
|
1430
|
-
runtime: yield* Deferred.await(entry.deferred)
|
|
1431
|
-
};
|
|
1432
|
-
}),
|
|
1433
|
-
getOrCreate,
|
|
1434
|
-
isCurrent: (key, entry) => serial.withPermits(1)(Effect.sync(() => entries.get(key) === entry)),
|
|
1435
|
-
reserve,
|
|
1436
|
-
size: () => serial.withPermits(1)(Effect.sync(() => entries.size)),
|
|
1437
|
-
start
|
|
1438
|
-
};
|
|
1439
|
-
}
|
|
1440
|
-
function disposeRuntimeCacheEntries(options) {
|
|
1441
|
-
const disposal = Effect.gen(function* () {
|
|
1442
|
-
const completions = yield* Effect.forEach(options.entries, (entry) => Effect.gen(function* () {
|
|
1443
|
-
const completion = yield* Deferred.make();
|
|
1444
|
-
yield* Effect.forkDetach(Deferred.await(entry.deferred).pipe(Effect.flatMap(options.dispose), Effect.exit, Effect.flatMap((exit) => Deferred.succeed(completion, exit)), Effect.asVoid), { uninterruptible: "inherit" });
|
|
1445
|
-
return completion;
|
|
1446
|
-
}), { concurrency: "unbounded" });
|
|
1447
|
-
const failures = (yield* Effect.forEach(completions, Deferred.await, { concurrency: "unbounded" })).filter(Exit.isFailure).map(({ cause }) => Cause.squash(cause));
|
|
1448
|
-
if (failures.length > 0) return yield* Effect.fail(new AggregateError(failures, options.failureMessage));
|
|
1449
|
-
});
|
|
1450
|
-
const timeout = options.timeout;
|
|
1451
|
-
return timeout ? disposal.pipe(Effect.timeoutOrElse({
|
|
1452
|
-
duration: timeout.milliseconds,
|
|
1453
|
-
orElse: () => Effect.fail(timeout.onTimeout())
|
|
1454
|
-
})) : disposal;
|
|
1455
|
-
}
|
|
1456
|
-
function invokeRuntimeControl(runtime, control) {
|
|
1457
|
-
return runtime.pipe(Effect.flatMap((selected) => selected ? control(selected) ?? Effect.succeed(false) : Effect.succeed(false)));
|
|
1458
|
-
}
|
|
1459
|
-
//#endregion
|
|
1460
|
-
//#region src/audio-transcription/infra/adapters/managed/rivus-audio-install-lock.ts
|
|
1461
|
-
var RivusAudioInstallInProgressError = class extends Error {
|
|
1462
|
-
constructor() {
|
|
1463
|
-
super("another audio transcriber installation is in progress");
|
|
1464
|
-
this.name = "RivusAudioInstallInProgressError";
|
|
1465
|
-
}
|
|
1466
|
-
};
|
|
1467
|
-
/**
|
|
1468
|
-
* Takes the installation lock at `path`: an exclusive kernel lock on the SQLite
|
|
1469
|
-
* database file, held until `release` or until the holding process exits or
|
|
1470
|
-
* crashes — the kernel releases a crashed holder's lock at once, so there is no
|
|
1471
|
-
* pid- or age-based reclamation. The lock file stays on disk after release and a
|
|
1472
|
-
* legacy `install.lock/` directory is never read; both can be deleted manually.
|
|
1473
|
-
*/
|
|
1474
|
-
async function acquireRivusAudioInstallLock(path, platform) {
|
|
1475
|
-
const acquired = await acquireProcessLock(platform, path);
|
|
1476
|
-
if (!acquired.ok) throw new RivusAudioInstallInProgressError();
|
|
1477
|
-
const lock = acquired.value;
|
|
1478
|
-
return { release: () => lock.release() };
|
|
1479
|
-
}
|
|
1480
|
-
//#endregion
|
|
1481
|
-
//#region src/audio-transcription/infra/adapters/managed/rivus-audio-release.ts
|
|
1482
|
-
const RIVUS_AUDIO_MANIFEST_FILE = "manifest.json";
|
|
1483
|
-
const RIVUS_AUDIO_RELEASES_DIRECTORY = "releases";
|
|
1484
|
-
const manifestSchema = Schema.fromJsonString(Schema.Struct({
|
|
1485
|
-
id: Schema.NonEmptyString,
|
|
1486
|
-
smoke: Schema.Struct({
|
|
1487
|
-
expect: Schema.NonEmptyString,
|
|
1488
|
-
input: Schema.NonEmptyString
|
|
1489
|
-
})
|
|
1490
|
-
}));
|
|
1491
|
-
const currentSchema = Schema.fromJsonString(Schema.Struct({
|
|
1492
|
-
digest: Schema.optional(Schema.NonEmptyString),
|
|
1493
|
-
id: Schema.NonEmptyString,
|
|
1494
|
-
release: Schema.NonEmptyString
|
|
1495
|
-
}));
|
|
1496
|
-
function rivusAudioCurrentPath(installRoot) {
|
|
1497
|
-
return join(installRoot, "current.json");
|
|
1498
|
-
}
|
|
1499
|
-
/**
|
|
1500
|
-
* Whether an entry of the asset directory, at any depth, belongs in a release. Dependencies come from the shrinkwrap
|
|
1501
|
-
* and colocated tests stay out of the published package, so a release never contains either and a workspace checkout
|
|
1502
|
-
* produces the same release and digest as the published package.
|
|
1503
|
-
*/
|
|
1504
|
-
function isRivusAudioReleaseAsset(name) {
|
|
1505
|
-
return name !== "node_modules" && !name.endsWith(".test.ts");
|
|
1506
|
-
}
|
|
1507
|
-
/** Lists the release asset files by relative path with "/" separators. */
|
|
1508
|
-
async function listAssetFiles(root, prefix) {
|
|
1509
|
-
const entries = await readdir(join(root, prefix), { withFileTypes: true });
|
|
1510
|
-
return (await Promise.all(entries.filter((entry) => isRivusAudioReleaseAsset(entry.name)).map(async (entry) => {
|
|
1511
|
-
const path = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
|
|
1512
|
-
return entry.isDirectory() ? listAssetFiles(root, path) : [path];
|
|
1513
|
-
}))).flat();
|
|
1514
|
-
}
|
|
1515
|
-
/**
|
|
1516
|
-
* Digests the asset files that an installation copies, so an asset change reinstalls the transcriber even when the
|
|
1517
|
-
* manifest id stays the same.
|
|
1518
|
-
*/
|
|
1519
|
-
async function readRivusAudioAssetDigest(directory) {
|
|
1520
|
-
const hash = createHash("sha256");
|
|
1521
|
-
for (const file of (await listAssetFiles(directory, "")).sort()) {
|
|
1522
|
-
const content = await readFile(join(directory, file));
|
|
1523
|
-
hash.update(`${file}\0${String(content.length)}\0`).update(content);
|
|
1524
|
-
}
|
|
1525
|
-
return hash.digest("hex");
|
|
1526
|
-
}
|
|
1527
|
-
function isStrictlyWithin(root, candidate) {
|
|
1528
|
-
return candidate !== resolve(root) && isPathWithin(root, candidate);
|
|
1529
|
-
}
|
|
1530
|
-
async function readRivusAudioReleaseManifest(directory) {
|
|
1531
|
-
const path = join(directory, RIVUS_AUDIO_MANIFEST_FILE);
|
|
1532
|
-
const manifest = Option.getOrUndefined(Schema.decodeUnknownOption(manifestSchema)(await readFile(path, "utf8")));
|
|
1533
|
-
if (manifest === void 0 || !isStrictlyWithin(directory, resolve(directory, manifest.smoke.input))) throw new Error(`audio transcriber manifest is invalid: ${path}`);
|
|
1534
|
-
return manifest;
|
|
1535
|
-
}
|
|
1536
|
-
/**
|
|
1537
|
-
* Reads the release that current.json selects. A missing or malformed record, a release outside `releases/`, or a
|
|
1538
|
-
* missing release directory all mean "not installed", which a reinstall repairs.
|
|
1539
|
-
*/
|
|
1540
|
-
async function readRivusAudioInstalledRelease(installRoot) {
|
|
1541
|
-
const text = await readPersistenceFile(rivusAudioCurrentPath(installRoot));
|
|
1542
|
-
const current = text === void 0 ? void 0 : Option.getOrUndefined(Schema.decodeUnknownOption(currentSchema)(text));
|
|
1543
|
-
if (current === void 0) return;
|
|
1544
|
-
const directory = resolve(installRoot, current.release);
|
|
1545
|
-
if (!isStrictlyWithin(join(installRoot, "releases"), directory)) return;
|
|
1546
|
-
return await stat(directory).then((info) => info.isDirectory(), () => false) ? {
|
|
1547
|
-
...current.digest === void 0 ? {} : { digest: current.digest },
|
|
1548
|
-
directory,
|
|
1549
|
-
id: current.id,
|
|
1550
|
-
release: current.release
|
|
1551
|
-
} : void 0;
|
|
1552
|
-
}
|
|
1553
|
-
async function readRivusAudioStatus(installRoot, assetDirectory) {
|
|
1554
|
-
const expected = await readRivusAudioReleaseManifest(assetDirectory);
|
|
1555
|
-
const expectedDigest = await readRivusAudioAssetDigest(assetDirectory);
|
|
1556
|
-
const installed = await readRivusAudioInstalledRelease(installRoot);
|
|
1557
|
-
return installed === void 0 ? {
|
|
1558
|
-
installed: false,
|
|
1559
|
-
expectedId: expected.id,
|
|
1560
|
-
expectedDigest,
|
|
1561
|
-
upToDate: false
|
|
1562
|
-
} : {
|
|
1563
|
-
installed: true,
|
|
1564
|
-
id: installed.id,
|
|
1565
|
-
...installed.digest === void 0 ? {} : { digest: installed.digest },
|
|
1566
|
-
release: installed.directory,
|
|
1567
|
-
expectedId: expected.id,
|
|
1568
|
-
expectedDigest,
|
|
1569
|
-
upToDate: installed.id === expected.id && installed.digest === expectedDigest
|
|
1570
|
-
};
|
|
1571
|
-
}
|
|
1572
|
-
//#endregion
|
|
1573
|
-
//#region src/audio-transcription/infra/adapters/managed/rivus-audio-installer.ts
|
|
1574
|
-
const INSTALL_DEADLINE_MS = 15e5;
|
|
1575
|
-
const NPM_TIMEOUT_MS = 3e5;
|
|
1576
|
-
const FETCH_TIMEOUT_MS = 12e5;
|
|
1577
|
-
const SMOKE_TIMEOUT_MS = 3e5;
|
|
1578
|
-
const LOCK_POLL_MS = 2e3;
|
|
1579
|
-
const STAGING_PREFIX = "staging-";
|
|
1580
|
-
var RivusAudioInstallStepError = class extends Error {
|
|
1581
|
-
step;
|
|
1582
|
-
constructor(step, reason, output = "") {
|
|
1583
|
-
const detail = output.trim().slice(-4e3);
|
|
1584
|
-
super(`audio transcriber installation failed at ${step}: ${reason}${detail ? `\n${detail}` : ""}`);
|
|
1585
|
-
this.name = "RivusAudioInstallStepError";
|
|
1586
|
-
this.step = step;
|
|
1587
|
-
}
|
|
1588
|
-
};
|
|
1589
|
-
function sleepUnlessAborted(ms, signal) {
|
|
1590
|
-
return setTimeout$1(ms, void 0, signal ? { signal } : {}).catch(() => void 0);
|
|
1591
|
-
}
|
|
1592
|
-
async function acquireLockWhenFree(root, options, deadline) {
|
|
1593
|
-
const sleep = options.sleep ?? ((ms) => sleepUnlessAborted(ms, options.signal));
|
|
1594
|
-
const lockPath = join(root, "install.process-lock");
|
|
1595
|
-
for (;;) {
|
|
1596
|
-
try {
|
|
1597
|
-
return await acquireRivusAudioInstallLock(lockPath, options.platform);
|
|
1598
|
-
} catch (error) {
|
|
1599
|
-
if (!(error instanceof RivusAudioInstallInProgressError)) throw error;
|
|
1600
|
-
}
|
|
1601
|
-
const remainingMs = deadline.at - deadline.now();
|
|
1602
|
-
if (remainingMs <= 0) throw new Error("another audio transcriber installation did not finish in time");
|
|
1603
|
-
await sleep(Math.min(LOCK_POLL_MS, remainingMs));
|
|
1604
|
-
if (options.signal?.aborted) throw new Error("audio transcriber installation was interrupted while waiting for another installation");
|
|
1605
|
-
}
|
|
1606
|
-
}
|
|
1607
|
-
/** Keeps the new and the previous release, so a transcription that started before the switch can still finish. */
|
|
1608
|
-
async function pruneReleases(root, keep) {
|
|
1609
|
-
const directory = join(root, RIVUS_AUDIO_RELEASES_DIRECTORY);
|
|
1610
|
-
const kept = new Set(keep.filter((path) => path !== void 0));
|
|
1611
|
-
const entries = await readdir(directory).catch(() => []);
|
|
1612
|
-
await Promise.all(entries.map((name) => join(directory, name)).filter((path) => !kept.has(path)).map((path) => rm(path, {
|
|
1613
|
-
force: true,
|
|
1614
|
-
recursive: true
|
|
1615
|
-
}).catch(() => void 0)));
|
|
1616
|
-
}
|
|
1617
|
-
/** npm may be missing from a service PATH, but it is installed beside the running Node executable. */
|
|
1618
|
-
function withNodeOnPath(env, nodeExecutable) {
|
|
1619
|
-
const nodeDirectory = dirname(nodeExecutable);
|
|
1620
|
-
return {
|
|
1621
|
-
...env,
|
|
1622
|
-
PATH: env.PATH ? `${nodeDirectory}${delimiter}${env.PATH}` : nodeDirectory
|
|
1623
|
-
};
|
|
1624
|
-
}
|
|
1625
|
-
function seconds(ms) {
|
|
1626
|
-
return String(ms / 1e3);
|
|
1627
|
-
}
|
|
1628
|
-
function errorMessage(error) {
|
|
1629
|
-
return error instanceof Error ? error.message : String(error);
|
|
1630
|
-
}
|
|
1631
|
-
async function runStep(options, deadline, step, request) {
|
|
1632
|
-
if (options.signal?.aborted) throw new RivusAudioInstallStepError(step, "interrupted");
|
|
1633
|
-
const deadlineReason = `the installation did not finish within ${seconds(deadline.ms)} s`;
|
|
1634
|
-
const remainingMs = deadline.at - deadline.now();
|
|
1635
|
-
if (remainingMs <= 0) throw new RivusAudioInstallStepError(step, deadlineReason);
|
|
1636
|
-
const timeoutMs = Math.min(request.timeoutMs, remainingMs);
|
|
1637
|
-
const result = await options.runProcess({
|
|
1638
|
-
...request,
|
|
1639
|
-
timeoutMs,
|
|
1640
|
-
...options.signal ? { signal: options.signal } : {}
|
|
1641
|
-
}).catch((error) => {
|
|
1642
|
-
throw new RivusAudioInstallStepError(step, `could not start ${request.command}: ${errorMessage(error)}`);
|
|
1643
|
-
});
|
|
1644
|
-
if (result.outcome === "timed-out") throw new RivusAudioInstallStepError(step, timeoutMs < request.timeoutMs ? deadlineReason : `timed out after ${seconds(request.timeoutMs)} s`, result.stderrTail);
|
|
1645
|
-
if (result.outcome === "interrupted") throw new RivusAudioInstallStepError(step, "interrupted", result.stderrTail);
|
|
1646
|
-
if (result.exitCode !== 0) throw new RivusAudioInstallStepError(step, `exited with code ${String(result.exitCode)}`, result.stderrTail);
|
|
1647
|
-
return result;
|
|
1648
|
-
}
|
|
1649
|
-
async function buildRelease(root, manifest, digest, options, deadline) {
|
|
1650
|
-
const staging = join(root, `${STAGING_PREFIX}${randomUUID()}`);
|
|
1651
|
-
const release = join(root, RIVUS_AUDIO_RELEASES_DIRECTORY, `${manifest.id.replaceAll(/[^\w.-]/g, "_")}-${digest.slice(0, 12)}-${randomUUID().slice(0, 8)}`);
|
|
1652
|
-
const env = withNodeOnPath(options.env, options.nodeExecutable);
|
|
1653
|
-
let renamed = false;
|
|
1654
|
-
try {
|
|
1655
|
-
await cp(options.assetDirectory, staging, {
|
|
1656
|
-
filter: (source) => isRivusAudioReleaseAsset(basename(source)),
|
|
1657
|
-
recursive: true
|
|
1658
|
-
}).catch((error) => {
|
|
1659
|
-
throw new RivusAudioInstallStepError("copy assets", errorMessage(error));
|
|
1660
|
-
});
|
|
1661
|
-
await runStep(options, deadline, "npm ci", {
|
|
1662
|
-
args: [
|
|
1663
|
-
"ci",
|
|
1664
|
-
"--ignore-scripts",
|
|
1665
|
-
"--omit=dev",
|
|
1666
|
-
"--no-audit",
|
|
1667
|
-
"--no-fund"
|
|
1668
|
-
],
|
|
1669
|
-
command: "npm",
|
|
1670
|
-
cwd: staging,
|
|
1671
|
-
env,
|
|
1672
|
-
timeoutMs: NPM_TIMEOUT_MS
|
|
1673
|
-
});
|
|
1674
|
-
await runStep(options, deadline, "model download", {
|
|
1675
|
-
args: [
|
|
1676
|
-
"fetch-model.mjs",
|
|
1677
|
-
RIVUS_AUDIO_MANIFEST_FILE,
|
|
1678
|
-
"model"
|
|
1679
|
-
],
|
|
1680
|
-
command: options.nodeExecutable,
|
|
1681
|
-
cwd: staging,
|
|
1682
|
-
env,
|
|
1683
|
-
timeoutMs: FETCH_TIMEOUT_MS
|
|
1684
|
-
});
|
|
1685
|
-
const { RIVUS_AUDIO_LANGUAGE: _language, ...smokeEnv } = env;
|
|
1686
|
-
const smoke = await runStep(options, deadline, "smoke test", {
|
|
1687
|
-
args: ["transcribe.mjs", resolve(staging, manifest.smoke.input)],
|
|
1688
|
-
command: options.nodeExecutable,
|
|
1689
|
-
cwd: staging,
|
|
1690
|
-
env: smokeEnv,
|
|
1691
|
-
timeoutMs: SMOKE_TIMEOUT_MS
|
|
1692
|
-
});
|
|
1693
|
-
if (smoke.stderrTail !== "") throw new RivusAudioInstallStepError("smoke test", "the transcriber wrote to stderr", smoke.stderrTail);
|
|
1694
|
-
if (!smoke.stdout.includes(manifest.smoke.expect)) throw new RivusAudioInstallStepError("smoke test", `the transcript does not contain ${JSON.stringify(manifest.smoke.expect)}`, smoke.stdout);
|
|
1695
|
-
await mkdir(dirname(release), { recursive: true });
|
|
1696
|
-
await rename(staging, release);
|
|
1697
|
-
renamed = true;
|
|
1698
|
-
await writeAtomicTextFile(rivusAudioCurrentPath(root), `${JSON.stringify({
|
|
1699
|
-
id: manifest.id,
|
|
1700
|
-
digest,
|
|
1701
|
-
release: relative(root, release)
|
|
1702
|
-
})}\n`, { durable: true });
|
|
1703
|
-
return release;
|
|
1704
|
-
} catch (error) {
|
|
1705
|
-
if ((renamed ? await readRivusAudioInstalledRelease(root).then((installed) => installed?.directory, () => void 0) : void 0) !== release) await rm(renamed ? release : staging, {
|
|
1706
|
-
force: true,
|
|
1707
|
-
recursive: true
|
|
1708
|
-
}).catch(() => void 0);
|
|
1709
|
-
throw error instanceof RivusAudioInstallStepError ? error : new RivusAudioInstallStepError("publish", errorMessage(error));
|
|
1710
|
-
}
|
|
1711
|
-
}
|
|
1712
|
-
async function removeInterruptedStaging(root) {
|
|
1713
|
-
const entries = await readdir(root);
|
|
1714
|
-
await Promise.all(entries.filter((name) => name.startsWith(STAGING_PREFIX)).map((name) => join(root, name)).map((path) => rm(path, {
|
|
1715
|
-
force: true,
|
|
1716
|
-
maxRetries: 5,
|
|
1717
|
-
recursive: true
|
|
1718
|
-
}).catch((error) => {
|
|
1719
|
-
throw new RivusAudioInstallStepError("staging cleanup", `could not remove the staging directory of an interrupted installation, ${path}: ${errorMessage(error)}`);
|
|
1720
|
-
})));
|
|
1721
|
-
}
|
|
1722
|
-
/**
|
|
1723
|
-
* Builds a release in a staging directory beside `releases/`, smoke-tests it, then publishes it by renaming the
|
|
1724
|
-
* directory and atomically replacing current.json. A failure before current.json changes leaves the previous release
|
|
1725
|
-
* selected and removes the staging directory. While another installer holds the lock, this one waits within its
|
|
1726
|
-
* deadline and then rechecks current.json, so it does not rebuild a release that installer just published.
|
|
1727
|
-
*/
|
|
1728
|
-
async function installRivusAudioTranscriber(options) {
|
|
1729
|
-
const now = options.now ?? Date.now;
|
|
1730
|
-
const deadlineMs = options.deadlineMs ?? INSTALL_DEADLINE_MS;
|
|
1731
|
-
const deadline = {
|
|
1732
|
-
at: now() + deadlineMs,
|
|
1733
|
-
ms: deadlineMs,
|
|
1734
|
-
now
|
|
1735
|
-
};
|
|
1736
|
-
const root = resolve(options.installRoot);
|
|
1737
|
-
await mkdir(root, { recursive: true });
|
|
1738
|
-
const lock = await acquireLockWhenFree(root, options, deadline);
|
|
1739
|
-
try {
|
|
1740
|
-
await removeInterruptedStaging(root);
|
|
1741
|
-
const previous = await readRivusAudioInstalledRelease(root);
|
|
1742
|
-
if (!options.force && options.reuseInstalledRelease && previous) return {
|
|
1743
|
-
status: "already-installed",
|
|
1744
|
-
id: previous.id,
|
|
1745
|
-
release: previous.directory
|
|
1746
|
-
};
|
|
1747
|
-
const manifest = await readRivusAudioReleaseManifest(options.assetDirectory);
|
|
1748
|
-
const digest = await readRivusAudioAssetDigest(options.assetDirectory);
|
|
1749
|
-
if (!options.force && previous?.id === manifest.id && previous.digest === digest) return {
|
|
1750
|
-
status: "already-installed",
|
|
1751
|
-
id: previous.id,
|
|
1752
|
-
release: previous.directory
|
|
1753
|
-
};
|
|
1754
|
-
const release = await buildRelease(root, manifest, digest, options, deadline);
|
|
1755
|
-
await pruneReleases(root, [release, previous?.directory]);
|
|
1756
|
-
return {
|
|
1757
|
-
status: "installed",
|
|
1758
|
-
id: manifest.id,
|
|
1759
|
-
release
|
|
1760
|
-
};
|
|
1761
|
-
} finally {
|
|
1762
|
-
await lock.release().catch(() => void 0);
|
|
1763
|
-
}
|
|
1764
|
-
}
|
|
1765
|
-
//#endregion
|
|
1766
|
-
//#region src/audio-transcription/infra/adapters/managed/rivus-audio-process.ts
|
|
1767
|
-
const OUTPUT_LIMIT = 65536;
|
|
1768
|
-
const KILL_GRACE_MS = 2e3;
|
|
1769
|
-
/**
|
|
1770
|
-
* Managed steps retain service-level group termination; deployment wrappers get a separately terminable group.
|
|
1771
|
-
*/
|
|
1772
|
-
function spawnAudioProcess(request, onStdout, onStderr) {
|
|
1773
|
-
const child = spawn(request.command, [...request.args], {
|
|
1774
|
-
cwd: request.cwd,
|
|
1775
|
-
env: { ...request.env },
|
|
1776
|
-
detached: request.processGroup === "isolated" && process.platform !== "win32",
|
|
1777
|
-
stdio: [
|
|
1778
|
-
"ignore",
|
|
1779
|
-
"pipe",
|
|
1780
|
-
"pipe"
|
|
1781
|
-
]
|
|
1782
|
-
});
|
|
1783
|
-
child.stdout.setEncoding("utf8").on("data", onStdout);
|
|
1784
|
-
child.stderr.setEncoding("utf8").on("data", onStderr);
|
|
1785
|
-
return child;
|
|
1786
|
-
}
|
|
1787
|
-
/**
|
|
1788
|
-
* Deployment transcription on POSIX owns an isolated group, including wrapper descendants that inherit its pipes.
|
|
1789
|
-
* Managed steps stay in the caller's group and must not spawn children: npm uses --ignore-scripts and plain Node assets.
|
|
1790
|
-
*/
|
|
1791
|
-
function runRivusAudioProcess(request) {
|
|
1792
|
-
return new Promise((resolve, reject) => {
|
|
1793
|
-
const stdoutChunks = [];
|
|
1794
|
-
let stdoutBytes = 0;
|
|
1795
|
-
let stdoutTruncated = false;
|
|
1796
|
-
let stderrTail = "";
|
|
1797
|
-
const stderrHeadChunks = [];
|
|
1798
|
-
let stderrHeadBytes = 0;
|
|
1799
|
-
const isolated = request.processGroup === "isolated" && process.platform !== "win32";
|
|
1800
|
-
const child = spawnAudioProcess(request, (text) => {
|
|
1801
|
-
const bytes = Buffer.from(text);
|
|
1802
|
-
const remaining = OUTPUT_LIMIT - stdoutBytes;
|
|
1803
|
-
stdoutTruncated ||= bytes.length > remaining;
|
|
1804
|
-
if (remaining > 0) {
|
|
1805
|
-
const chunk = bytes.subarray(0, remaining);
|
|
1806
|
-
stdoutChunks.push(chunk);
|
|
1807
|
-
stdoutBytes += chunk.length;
|
|
1808
|
-
}
|
|
1809
|
-
}, (text) => {
|
|
1810
|
-
stderrTail = (stderrTail + text).slice(-65536);
|
|
1811
|
-
const prefix = Buffer.from(text).subarray(0, Math.max(0, 4096 - stderrHeadBytes));
|
|
1812
|
-
if (prefix.length > 0) {
|
|
1813
|
-
stderrHeadChunks.push(prefix);
|
|
1814
|
-
stderrHeadBytes += prefix.length;
|
|
1815
|
-
}
|
|
1816
|
-
});
|
|
1817
|
-
let outcome = "exited";
|
|
1818
|
-
let exitCode = null;
|
|
1819
|
-
let exited = false;
|
|
1820
|
-
let closed = false;
|
|
1821
|
-
let escalation;
|
|
1822
|
-
let termination;
|
|
1823
|
-
let finishTermination;
|
|
1824
|
-
const signalChild = (signal) => {
|
|
1825
|
-
try {
|
|
1826
|
-
if (isolated && child.pid !== void 0) process.kill(-child.pid, signal);
|
|
1827
|
-
else child.kill(signal);
|
|
1828
|
-
} catch {}
|
|
1829
|
-
};
|
|
1830
|
-
const stop = (reason) => {
|
|
1831
|
-
if (closed || !isolated && exited || outcome !== "exited") return;
|
|
1832
|
-
outcome = reason;
|
|
1833
|
-
if (isolated) termination = new Promise((resolveTermination) => {
|
|
1834
|
-
finishTermination = resolveTermination;
|
|
1835
|
-
});
|
|
1836
|
-
signalChild("SIGTERM");
|
|
1837
|
-
escalation = setTimeout(() => {
|
|
1838
|
-
signalChild("SIGKILL");
|
|
1839
|
-
finishTermination?.();
|
|
1840
|
-
}, KILL_GRACE_MS);
|
|
1841
|
-
};
|
|
1842
|
-
const onAbort = () => stop("interrupted");
|
|
1843
|
-
const timeout = setTimeout(() => stop("timed-out"), request.timeoutMs);
|
|
1844
|
-
const finish = () => {
|
|
1845
|
-
clearTimeout(timeout);
|
|
1846
|
-
clearTimeout(escalation);
|
|
1847
|
-
request.signal?.removeEventListener("abort", onAbort);
|
|
1848
|
-
};
|
|
1849
|
-
request.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1850
|
-
if (request.signal?.aborted) onAbort();
|
|
1851
|
-
child.once("exit", (code) => {
|
|
1852
|
-
exited = true;
|
|
1853
|
-
exitCode = code;
|
|
1854
|
-
});
|
|
1855
|
-
child.once("error", (error) => {
|
|
1856
|
-
finish();
|
|
1857
|
-
reject(error);
|
|
1858
|
-
});
|
|
1859
|
-
child.once("close", async () => {
|
|
1860
|
-
closed = true;
|
|
1861
|
-
if (termination) {
|
|
1862
|
-
try {
|
|
1863
|
-
process.kill(-child.pid, 0);
|
|
1864
|
-
} catch {
|
|
1865
|
-
clearTimeout(escalation);
|
|
1866
|
-
finishTermination?.();
|
|
1867
|
-
}
|
|
1868
|
-
await termination;
|
|
1869
|
-
}
|
|
1870
|
-
finish();
|
|
1871
|
-
const stdout = new TextDecoder().decode(Buffer.concat(stdoutChunks), { stream: true });
|
|
1872
|
-
const stderrHead = new TextDecoder().decode(Buffer.concat(stderrHeadChunks), { stream: true });
|
|
1873
|
-
resolve({
|
|
1874
|
-
exitCode,
|
|
1875
|
-
outcome,
|
|
1876
|
-
stderrTail,
|
|
1877
|
-
stderrHead,
|
|
1878
|
-
stdout,
|
|
1879
|
-
...stdoutTruncated ? { stdoutTruncated: true } : {}
|
|
1880
|
-
});
|
|
1881
|
-
});
|
|
1882
|
-
});
|
|
1883
|
-
}
|
|
1884
|
-
/** Streams the transcriber's stdout and stderr to the caller and resolves with its exit code. */
|
|
1885
|
-
function runRivusAudioPassthroughProcess(request) {
|
|
1886
|
-
return new Promise((resolve, reject) => {
|
|
1887
|
-
const child = spawnAudioProcess(request, (text) => request.stdout.write(text), (text) => request.stderr.write(text));
|
|
1888
|
-
const onAbort = () => {
|
|
1889
|
-
child.kill("SIGTERM");
|
|
1890
|
-
};
|
|
1891
|
-
request.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1892
|
-
child.once("error", (error) => {
|
|
1893
|
-
request.signal?.removeEventListener("abort", onAbort);
|
|
1894
|
-
reject(error);
|
|
1895
|
-
});
|
|
1896
|
-
child.once("close", (code) => {
|
|
1897
|
-
request.signal?.removeEventListener("abort", onAbort);
|
|
1898
|
-
resolve(code);
|
|
1899
|
-
});
|
|
1900
|
-
});
|
|
1901
|
-
}
|
|
1902
|
-
//#endregion
|
|
1903
|
-
//#region src/bootstrap/daemon/rivus-home-deployment-env.ts
|
|
1904
|
-
/**
|
|
1905
|
-
* Holds the Home directory of a daemon that a Home command (`rivus start`, `status`, `check-config`) runs, and marks
|
|
1906
|
-
* the deployment as a Home deployment. Only those commands set it: a project deployment drops it from the inherited
|
|
1907
|
-
* environment and from its env file, so an operator's exported RIVUS_HOME never turns a project into a Home.
|
|
1908
|
-
*/
|
|
1909
|
-
const RIVUS_HOME_DEPLOYMENT_ENV = "RIVUS_HOME_DEPLOYMENT_DIR";
|
|
1910
|
-
function withoutRivusHomeDeployment(env) {
|
|
1911
|
-
const { [RIVUS_HOME_DEPLOYMENT_ENV]: _homeDirectory, ...rest } = env;
|
|
1912
|
-
return rest;
|
|
1913
|
-
}
|
|
1914
|
-
//#endregion
|
|
1915
|
-
export { loadMergedLocalEnvFile as A, loadRivusDeploymentManifest as C, gatewayPackageManifestPath as D, gatewayPackageDirectory as E, validateRivusDeploymentManifest as F, validateRivusProjectSpaceDeployment as I, createBackgroundSessionToolContracts as L, resolveFeishuEndpointCredentials as M, InvalidRivusProjectSpace as N, gatewaySkillsDirectory as O, parseRivusDeploymentManifest as P, narrowBackgroundSessionDefinition as R, renderRivusModelCliHelp as S, gatewayAudioTranscriberAssetDirectory as T, parseRivusModelManagementWireRequest as _, RivusAudioInstallStepError as a, parseRivusModelCliArguments as b, readRivusAudioStatus as c, invokeRuntimeControl as d, migrateRivusModelManagementConfig as f, createRivusModelManagementWireRequest as g, createRivusModelManagementFailure as h, runRivusAudioProcess as i, resolveAcpRuntimeEnvironment as j, gatewayTemplateDirectory as k, createRuntimeCache as l, parseRivusModelManagementHomeConfig as m, withoutRivusHomeDeployment as n, installRivusAudioTranscriber as o, parseRivusModelManagementEnabled as p, runRivusAudioPassthroughProcess as r, readRivusAudioInstalledRelease as s, RIVUS_HOME_DEPLOYMENT_ENV as t, disposeRuntimeCacheEntries as u, projectRivusModelCliResponse as v, RIVUS_RELEASE_DESCRIPTOR as w, renderRivusModelCliArgumentError as x, toRivusModelManagementSubmission as y, deepFreeze as z };
|
|
1916
|
-
|