@rivus/gateway 0.21.2 → 0.22.1
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/README.md +4 -1
- package/assets/audio-transcriber/fetch-model.mjs +63 -70
- package/assets/audio-transcriber/transcribe.mjs +38 -47
- package/assets/installation-policy.json +4 -3
- package/dist/bootstrap/feishu.d.ts +4 -2
- package/dist/bootstrap/feishu.js +19389 -17389
- package/dist/bootstrap/herdr-feishu.d.ts +1 -7
- package/dist/bootstrap/herdr-feishu.js +23 -12
- package/dist/chunks/automation-presentation.js +58 -60
- package/dist/chunks/feishu-receive-message.js +113 -0
- package/dist/chunks/herdr-feishu-runtime.js +1011 -626
- package/dist/chunks/public.d.ts +278 -0
- package/dist/chunks/public2.d.ts +10 -0
- package/dist/chunks/rivus-deployment-cli-process.d.ts +127 -455
- package/dist/chunks/rivus-home-deployment-env.js +1342 -1781
- package/dist/chunks/rivus-node-entrypoint.js +4574 -4199
- package/dist/index.d.ts +23 -11
- package/dist/mcp.d.ts +10 -9
- package/dist/mcp.js +43 -43
- package/package.json +18 -11
- package/templates/a-share-briefing-analysis.mjs +32 -34
- package/templates/a-share-briefing-renderer.mjs +175 -186
- package/templates/a-share-index-evidence.mjs +50 -54
- package/templates/a-share-market-briefing.mjs +37 -39
- package/templates/a-share-overseas-evidence.mjs +35 -39
- package/templates/a-share-policy-evidence.mjs +90 -96
- package/templates/a-share-sector-evidence.mjs +32 -35
- package/templates/acp-stdio-proxy.mjs +21 -22
- package/templates/current-weather.mjs +56 -58
- package/templates/html-drive-tools.mjs +130 -141
- package/templates/rivus-agents.plugin.mjs +55 -57
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import { Cause, Deferred, Effect, Exit, Option, Result, Schema, SchemaIssue, Semaphore } from "effect";
|
|
2
2
|
import { isRivusRuntimeToolId } from "@rivus/runtime";
|
|
3
|
+
import { readPersistenceFile, writeAtomicTextFile } from "@rivus/platform/persistence";
|
|
3
4
|
import { basename, delimiter, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
4
5
|
import { fileURLToPath } from "node:url";
|
|
5
|
-
import { access,
|
|
6
|
+
import { access, constants, cp, mkdir, readFile, readdir, rename, rm, stat } from "node:fs/promises";
|
|
7
|
+
import { isNodeErrorWithCode, isPathWithin } from "@rivus/platform/filesystem";
|
|
6
8
|
import { createHash, randomUUID } from "node:crypto";
|
|
7
|
-
import {
|
|
8
|
-
import { isPathWithin } from "@rivus/platform/filesystem";
|
|
9
|
-
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
9
|
+
import { acquireProcessLock } from "@rivus/agent-kit-collab/process-lock";
|
|
10
10
|
import { spawn } from "node:child_process";
|
|
11
|
-
import {
|
|
12
|
-
//#region src/
|
|
11
|
+
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
12
|
+
//#region src/lib/deep-freeze.ts
|
|
13
13
|
function deepFreeze(value) {
|
|
14
14
|
if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
|
|
15
15
|
Object.freeze(value);
|
|
@@ -18,7 +18,7 @@ function deepFreeze(value) {
|
|
|
18
18
|
return value;
|
|
19
19
|
}
|
|
20
20
|
//#endregion
|
|
21
|
-
//#region src/
|
|
21
|
+
//#region src/background-session/domain/background-session/services/background-session-authority.ts
|
|
22
22
|
const BACKGROUND_SESSION_START_TOOL_ID = "background.start";
|
|
23
23
|
const BACKGROUND_SESSION_TOOL_PLUGIN_ID = "rivus-core";
|
|
24
24
|
const BACKGROUND_SESSION_TOOL_VERSION = "1.0.0";
|
|
@@ -191,6 +191,12 @@ function createBackgroundSessionToolContracts() {
|
|
|
191
191
|
})
|
|
192
192
|
];
|
|
193
193
|
}
|
|
194
|
+
function grantRevision(digest, parentRevision, toolIds) {
|
|
195
|
+
return digest(JSON.stringify({
|
|
196
|
+
parentRevision,
|
|
197
|
+
toolIds: [...toolIds].sort()
|
|
198
|
+
}));
|
|
199
|
+
}
|
|
194
200
|
function narrowBackgroundSessionDefinition(definition, digest) {
|
|
195
201
|
const childToolIds = definition.toolGrantSet.toolIds.filter((id) => id !== BACKGROUND_SESSION_START_TOOL_ID);
|
|
196
202
|
const toolGrantSet = Object.freeze({
|
|
@@ -203,14 +209,8 @@ function narrowBackgroundSessionDefinition(definition, digest) {
|
|
|
203
209
|
toolGrantSet
|
|
204
210
|
});
|
|
205
211
|
}
|
|
206
|
-
function grantRevision(digest, parentRevision, toolIds) {
|
|
207
|
-
return digest(JSON.stringify({
|
|
208
|
-
parentRevision,
|
|
209
|
-
toolIds: [...toolIds].sort()
|
|
210
|
-
}));
|
|
211
|
-
}
|
|
212
212
|
//#endregion
|
|
213
|
-
//#region src/
|
|
213
|
+
//#region src/deployment/domain/manifest/adapters/deployment-manifest.ts
|
|
214
214
|
const DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_MS = 3e4;
|
|
215
215
|
const DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_RENEWAL_INTERVAL_MS = 1e4;
|
|
216
216
|
const DEFAULT_MANIFEST_BACKGROUND_SESSION_MAX_CONSECUTIVE_FAILURES = 3;
|
|
@@ -229,14 +229,11 @@ const MEMORY_SCOPES = [
|
|
|
229
229
|
var InvalidRivusProjectSpace = class extends Error {
|
|
230
230
|
name = "InvalidRivusProjectSpace";
|
|
231
231
|
};
|
|
232
|
-
function
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
validateRivusProjectSpaceDeployment(declaration);
|
|
238
|
-
}
|
|
239
|
-
return projectSpaceIds;
|
|
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`);
|
|
240
237
|
}
|
|
241
238
|
function validateRivusProjectSpaceDeployment(declaration) {
|
|
242
239
|
validateRelativeProjectPath(declaration.root, `project space ${declaration.id} root`);
|
|
@@ -248,11 +245,218 @@ function validateRivusProjectSpaceDeployment(declaration) {
|
|
|
248
245
|
sources.add(source);
|
|
249
246
|
}
|
|
250
247
|
}
|
|
251
|
-
function
|
|
252
|
-
|
|
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;
|
|
253
256
|
}
|
|
254
|
-
|
|
255
|
-
|
|
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
|
+
});
|
|
256
460
|
}
|
|
257
461
|
function parseRivusDeploymentManifest(value) {
|
|
258
462
|
const root = record(value, "manifest");
|
|
@@ -428,207 +632,16 @@ function parseRivusDeploymentManifest(value) {
|
|
|
428
632
|
projectSpaces: Object.freeze(projectSpaces)
|
|
429
633
|
});
|
|
430
634
|
}
|
|
431
|
-
function validateRivusDeploymentManifest(manifest) {
|
|
432
|
-
const projectSpaceIds = validateRivusProjectSpaceDeployments(manifest.projectSpaces ?? []);
|
|
433
|
-
const pluginIds = /* @__PURE__ */ new Set();
|
|
434
|
-
for (const plugin of manifest.plugins) {
|
|
435
|
-
if (pluginIds.has(plugin.id)) throw new Error(`duplicate plugin declaration: ${plugin.id}`);
|
|
436
|
-
validateModuleSpecifier(plugin.module);
|
|
437
|
-
pluginIds.add(plugin.id);
|
|
438
|
-
}
|
|
439
|
-
const agentIds = /* @__PURE__ */ new Set();
|
|
440
|
-
const agentById = /* @__PURE__ */ new Map();
|
|
441
|
-
for (const agent of manifest.agents) {
|
|
442
|
-
if (agentIds.has(agent.agentId)) throw new Error(`duplicate agent deployment: ${agent.agentId}`);
|
|
443
|
-
agentIds.add(agent.agentId);
|
|
444
|
-
if (!pluginIds.has(agent.pluginId)) throw new Error(`agent ${agent.agentId} references undeclared plugin: ${agent.pluginId}`);
|
|
445
|
-
if (agent.projectSpaceId && !projectSpaceIds.has(agent.projectSpaceId)) throw new Error(`agent ${agent.agentId} references unknown project space: ${agent.projectSpaceId}`);
|
|
446
|
-
if (agent.runtime) {
|
|
447
|
-
const runtime = parseAgentRuntime(agent.runtime, `agent ${agent.agentId} runtime`);
|
|
448
|
-
if (agent.runtimeTools !== void 0) throw new Error(`ACP agent ${agent.agentId} must not declare runtimeTools`);
|
|
449
|
-
if (agent.skills.allow.length > 0) throw new Error(`ACP agent ${agent.agentId} skills.allow must be empty`);
|
|
450
|
-
if (runtime.args.includes("--yolo") && !runtime.unattended) throw new Error(`ACP agent ${agent.agentId} runtime.args --yolo requires unattended: true`);
|
|
451
|
-
}
|
|
452
|
-
agentById.set(agent.agentId, agent);
|
|
453
|
-
}
|
|
454
|
-
const endpointIds = /* @__PURE__ */ new Set();
|
|
455
|
-
const sessionNamespaces = /* @__PURE__ */ new Set();
|
|
456
|
-
for (const endpoint of manifest.endpoints) {
|
|
457
|
-
if (endpointIds.has(endpoint.id)) throw new Error(`duplicate endpoint binding: ${endpoint.id}`);
|
|
458
|
-
endpointIds.add(endpoint.id);
|
|
459
|
-
if (endpoint.allowedActors !== void 0) parseAllowedActors(endpoint.allowedActors, `endpoint ${endpoint.id} allowedActors`);
|
|
460
|
-
if (sessionNamespaces.has(endpoint.sessionNamespace)) throw new Error(`duplicate endpoint session namespace: ${endpoint.sessionNamespace}`);
|
|
461
|
-
sessionNamespaces.add(endpoint.sessionNamespace);
|
|
462
|
-
const agent = agentById.get(endpoint.agentId);
|
|
463
|
-
if (!agent) throw new Error(`endpoint ${endpoint.id} references unknown agent: ${endpoint.agentId}`);
|
|
464
|
-
if (agent.runtime?.unattended && !endpoint.allowedActors?.length) throw new Error(`unattended ACP agent ${agent.agentId} requires non-empty allowedActors on endpoint ${endpoint.id}`);
|
|
465
|
-
if (!agent.endpointIds.includes(endpoint.id)) throw new Error(`endpoint ${endpoint.id} is not declared by agent ${endpoint.agentId}`);
|
|
466
|
-
}
|
|
467
|
-
for (const agent of manifest.agents) for (const endpointId of agent.endpointIds) {
|
|
468
|
-
const endpoint = manifest.endpoints.find(({ id }) => id === endpointId);
|
|
469
|
-
if (!endpoint) throw new Error(`agent ${agent.agentId} references unknown endpoint: ${endpointId}`);
|
|
470
|
-
if (endpoint.agentId !== agent.agentId) throw new Error(`endpoint ${endpointId} is bound to a different agent`);
|
|
471
|
-
}
|
|
472
|
-
const automationIds = /* @__PURE__ */ new Set();
|
|
473
|
-
for (const automation of manifest.automations ?? []) {
|
|
474
|
-
if (automationIds.has(automation.id)) throw new Error(`duplicate automation binding: ${automation.id}`);
|
|
475
|
-
automationIds.add(automation.id);
|
|
476
|
-
if (!agentById.has(automation.agentId)) throw new Error(`automation ${automation.id} references unknown agent: ${automation.agentId}`);
|
|
477
|
-
const endpoint = manifest.endpoints.find(({ id }) => id === automation.delivery.endpointId);
|
|
478
|
-
if (!endpoint) throw new Error(`automation ${automation.id} references unknown delivery endpoint: ${automation.delivery.endpointId}`);
|
|
479
|
-
if (automation.enabled && !endpoint.enabled) throw new Error(`automation ${automation.id} delivery endpoint must be enabled`);
|
|
480
|
-
}
|
|
481
|
-
const defaultAgent = agentById.get(manifest.defaultAgentId);
|
|
482
|
-
if (!defaultAgent) throw new Error(`default agent does not exist: ${manifest.defaultAgentId}`);
|
|
483
|
-
const defaultEndpoint = manifest.endpoints.find(({ id }) => id === manifest.defaultEndpointId);
|
|
484
|
-
if (!defaultEndpoint) throw new Error(`default endpoint does not exist: ${manifest.defaultEndpointId}`);
|
|
485
|
-
if (defaultEndpoint.agentId !== defaultAgent.agentId) throw new Error("default endpoint is not bound to the default agent");
|
|
486
|
-
if (!defaultEndpoint.enabled) throw new Error("default endpoint must be enabled");
|
|
487
|
-
if (manifest.backgroundSessions) validateBackgroundSessions(manifest.backgroundSessions);
|
|
488
|
-
}
|
|
489
|
-
const nonBlankRuntimeString = Schema.String.check(Schema.makeFilter((value) => value.trim() !== ""));
|
|
490
|
-
const agentRuntimeSchema = Schema.Struct({
|
|
491
|
-
type: Schema.Literal("acp"),
|
|
492
|
-
command: nonBlankRuntimeString,
|
|
493
|
-
args: Schema.optional(Schema.Array(Schema.String)),
|
|
494
|
-
env: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
495
|
-
permissions: Schema.optional(Schema.Literals(["ask", "deny"])),
|
|
496
|
-
steering: Schema.optional(Schema.Literals(["disabled", "cancel-and-reprompt"])),
|
|
497
|
-
unattended: Schema.optional(Schema.Boolean),
|
|
498
|
-
initializationTimeoutMs: Schema.optional(Schema.Number)
|
|
499
|
-
});
|
|
500
|
-
function parseAgentRuntime(value, path) {
|
|
501
|
-
const runtime = decodeRuntimeField(agentRuntimeSchema, value, path);
|
|
502
|
-
const env = runtime.env ?? {};
|
|
503
|
-
for (const [key, reference] of Object.entries(env)) {
|
|
504
|
-
if (!/^[A-Z_][A-Z0-9_]*$/.test(key)) throw new Error(`${path}.env contains invalid variable name: ${key}`);
|
|
505
|
-
if (!/^env:[A-Z_][A-Z0-9_]*$/.test(reference)) throw new Error(`${path}.env.${key} must reference env:NAME`);
|
|
506
|
-
}
|
|
507
|
-
return Object.freeze({
|
|
508
|
-
args: Object.freeze([...runtime.args ?? []]),
|
|
509
|
-
command: runtime.command,
|
|
510
|
-
env: Object.freeze({ ...env }),
|
|
511
|
-
initializationTimeoutMs: positiveInteger(runtime.initializationTimeoutMs === void 0 ? 1e4 : runtime.initializationTimeoutMs, `${path}.initializationTimeoutMs`),
|
|
512
|
-
permissions: runtime.permissions ?? "ask",
|
|
513
|
-
steering: runtime.steering ?? "disabled",
|
|
514
|
-
type: "acp",
|
|
515
|
-
unattended: runtime.unattended ?? false
|
|
516
|
-
});
|
|
517
|
-
}
|
|
518
|
-
function parseAllowedActors(value, path) {
|
|
519
|
-
const actors = [...decodeRuntimeField(Schema.Array(nonBlankRuntimeString), value, path)];
|
|
520
|
-
if (new Set(actors).size !== actors.length) throw new Error(`${path} contains duplicate actor`);
|
|
521
|
-
return actors;
|
|
522
|
-
}
|
|
523
|
-
function decodeRuntimeField(schema, value, path) {
|
|
524
|
-
const decoded = Schema.decodeUnknownResult(schema, { onExcessProperty: "error" })(value);
|
|
525
|
-
if (Result.isSuccess(decoded)) return decoded.success;
|
|
526
|
-
const issue = SchemaIssue.makeFormatterStandardSchemaV1()(decoded.failure.issue).issues[0];
|
|
527
|
-
throw new Error(`${path} ${JSON.stringify(issue.path ?? [])} contains invalid or unsupported input`);
|
|
528
|
-
}
|
|
529
|
-
function validateBackgroundSessions(config) {
|
|
530
|
-
if (config.required && !config.enabled) throw new Error("backgroundSessions.required requires backgroundSessions.enabled");
|
|
531
|
-
if (config.leaseRenewalIntervalMs >= config.leaseMs) throw new Error("backgroundSessions.leaseRenewalIntervalMs must be shorter than leaseMs");
|
|
532
|
-
if (config.stepTimeoutMs <= 0 || config.maxConcurrentSessions <= 0 || config.leaseMs <= 0) throw new Error("backgroundSessions durations and concurrency must be positive");
|
|
533
|
-
if (config.retryBackoffMs <= 0 || config.sessionLifetimeMs <= 0 || config.maxConsecutiveFailures <= 0) throw new Error("backgroundSessions retry and lifetime limits must be positive");
|
|
534
|
-
}
|
|
535
|
-
function validateModuleSpecifier(moduleSpecifier) {
|
|
536
|
-
const absolutePath = moduleSpecifier.startsWith("/") || moduleSpecifier.startsWith("\\\\") || /^[a-zA-Z]:[\\/]/.test(moduleSpecifier);
|
|
537
|
-
if (moduleSpecifier.trim() === "" || absolutePath || /^[a-z][a-z+.-]*:/i.test(moduleSpecifier) || moduleSpecifier.includes("\0")) throw new Error(`invalid plugin module specifier: ${moduleSpecifier}`);
|
|
538
|
-
if ((moduleSpecifier.startsWith("./") || moduleSpecifier.startsWith("../")) && moduleSpecifier.split(/[\\/]/).includes("..")) throw new Error(`plugin module escapes deployment root: ${moduleSpecifier}`);
|
|
539
|
-
}
|
|
540
|
-
function parseBackgroundSessions(value) {
|
|
541
|
-
exactKeys(value, [
|
|
542
|
-
"enabled",
|
|
543
|
-
"leaseMs",
|
|
544
|
-
"leaseRenewalIntervalMs",
|
|
545
|
-
"maxConsecutiveFailures",
|
|
546
|
-
"maxConcurrentSessions",
|
|
547
|
-
"required",
|
|
548
|
-
"retryBackoffMs",
|
|
549
|
-
"sessionLifetimeMs",
|
|
550
|
-
"stepTimeoutMs"
|
|
551
|
-
], "manifest.backgroundSessions", [
|
|
552
|
-
"leaseMs",
|
|
553
|
-
"leaseRenewalIntervalMs",
|
|
554
|
-
"maxConsecutiveFailures",
|
|
555
|
-
"maxConcurrentSessions",
|
|
556
|
-
"retryBackoffMs",
|
|
557
|
-
"sessionLifetimeMs",
|
|
558
|
-
"stepTimeoutMs"
|
|
559
|
-
]);
|
|
560
|
-
return Object.freeze({
|
|
561
|
-
enabled: boolean(value.enabled, "manifest.backgroundSessions.enabled"),
|
|
562
|
-
leaseMs: positiveInteger(value.leaseMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_MS, "manifest.backgroundSessions.leaseMs"),
|
|
563
|
-
leaseRenewalIntervalMs: positiveInteger(value.leaseRenewalIntervalMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_RENEWAL_INTERVAL_MS, "manifest.backgroundSessions.leaseRenewalIntervalMs"),
|
|
564
|
-
maxConsecutiveFailures: positiveInteger(value.maxConsecutiveFailures ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_MAX_CONSECUTIVE_FAILURES, "manifest.backgroundSessions.maxConsecutiveFailures"),
|
|
565
|
-
maxConcurrentSessions: positiveInteger(value.maxConcurrentSessions ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_MAX_CONCURRENT_SESSIONS, "manifest.backgroundSessions.maxConcurrentSessions"),
|
|
566
|
-
required: boolean(value.required, "manifest.backgroundSessions.required"),
|
|
567
|
-
retryBackoffMs: positiveInteger(value.retryBackoffMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_RETRY_BACKOFF_MS, "manifest.backgroundSessions.retryBackoffMs"),
|
|
568
|
-
sessionLifetimeMs: positiveInteger(value.sessionLifetimeMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_LIFETIME_MS, "manifest.backgroundSessions.sessionLifetimeMs"),
|
|
569
|
-
stepTimeoutMs: positiveInteger(value.stepTimeoutMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_STEP_TIMEOUT_MS, "manifest.backgroundSessions.stepTimeoutMs")
|
|
570
|
-
});
|
|
571
|
-
}
|
|
572
|
-
function record(value, path) {
|
|
573
|
-
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(`${path} must be an object`);
|
|
574
|
-
return value;
|
|
575
|
-
}
|
|
576
|
-
function array(value, path) {
|
|
577
|
-
if (!Array.isArray(value)) throw new Error(`${path} must be an array`);
|
|
578
|
-
return value;
|
|
579
|
-
}
|
|
580
|
-
function string(value, path) {
|
|
581
|
-
if (typeof value !== "string" || value.trim() === "") throw new Error(`${path} must be a non-empty string`);
|
|
582
|
-
return value;
|
|
583
|
-
}
|
|
584
|
-
function boolean(value, path) {
|
|
585
|
-
if (typeof value !== "boolean") throw new Error(`${path} must be a boolean`);
|
|
586
|
-
return value;
|
|
587
|
-
}
|
|
588
|
-
function positiveInteger(value, path) {
|
|
589
|
-
if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`${path} must be a positive integer`);
|
|
590
|
-
return value;
|
|
591
|
-
}
|
|
592
|
-
function memoryScope(value, path) {
|
|
593
|
-
if (typeof value !== "string" || !MEMORY_SCOPES.includes(value)) throw new Error(`${path} must be conversation, agent-private, project, or shared-user-profile`);
|
|
594
|
-
return value;
|
|
595
|
-
}
|
|
596
|
-
function groupPolicy(value, path) {
|
|
597
|
-
if (value !== "mention-only" && value !== "ignore-unmentioned" && value !== "default-responder") throw new Error(`${path} must be mention-only, ignore-unmentioned, or default-responder`);
|
|
598
|
-
return value;
|
|
599
|
-
}
|
|
600
|
-
function progressDisplay(value, path) {
|
|
601
|
-
if (value !== "hidden" && value !== "collapsed" && value !== "expanded") throw new Error(`${path} must be hidden, collapsed, or expanded`);
|
|
602
|
-
return value;
|
|
603
|
-
}
|
|
604
|
-
function runtimeToolId(value, path) {
|
|
605
|
-
const id = string(value, path);
|
|
606
|
-
if (!isRivusRuntimeToolId(id)) throw new Error(`${path} must be read, bash, edit, write, grep, find, or ls`);
|
|
607
|
-
return id;
|
|
608
|
-
}
|
|
609
|
-
function uniqueRuntimeTools(ids, path) {
|
|
610
|
-
const result = /* @__PURE__ */ new Set();
|
|
611
|
-
for (const id of ids) {
|
|
612
|
-
if (result.has(id)) throw new Error(`${path} contains duplicate Runtime Tool: ${id}`);
|
|
613
|
-
result.add(id);
|
|
614
|
-
}
|
|
615
|
-
return [...result];
|
|
616
|
-
}
|
|
617
|
-
function automationTargetType(value, path) {
|
|
618
|
-
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`);
|
|
619
|
-
return value;
|
|
620
|
-
}
|
|
621
|
-
function exactKeys(value, allowed, path, optional = []) {
|
|
622
|
-
const unexpected = Object.keys(value).find((key) => !allowed.includes(key));
|
|
623
|
-
if (unexpected) throw new Error(`${path} contains unsupported field: ${unexpected}`);
|
|
624
|
-
const missing = allowed.find((key) => !optional.includes(key) && !Object.hasOwn(value, key));
|
|
625
|
-
if (missing) throw new Error(`${path} is missing required field: ${missing}`);
|
|
626
|
-
}
|
|
627
635
|
//#endregion
|
|
628
|
-
//#region src/
|
|
636
|
+
//#region src/deployment/domain/endpoint/feishu-endpoint-credentials.ts
|
|
629
637
|
var FeishuEndpointCredentialError = class extends Error {
|
|
630
638
|
name = "FeishuEndpointCredentialError";
|
|
631
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
|
+
}
|
|
632
645
|
function resolveFeishuEndpointCredentials(credentialRef, env) {
|
|
633
646
|
if (!credentialRef.startsWith("env:")) throw new FeishuEndpointCredentialError("Feishu endpoint credentialRef must use env:<PREFIX>");
|
|
634
647
|
const prefix = credentialRef.slice(4);
|
|
@@ -638,226 +651,50 @@ function resolveFeishuEndpointCredentials(credentialRef, env) {
|
|
|
638
651
|
appSecret: required(env, `${prefix}_APP_SECRET`)
|
|
639
652
|
});
|
|
640
653
|
}
|
|
641
|
-
function required(env, variable) {
|
|
642
|
-
const value = env[variable]?.trim();
|
|
643
|
-
if (!value) throw new FeishuEndpointCredentialError(`${variable} is required`);
|
|
644
|
-
return value;
|
|
645
|
-
}
|
|
646
|
-
//#endregion
|
|
647
|
-
//#region src/platform/home/upgrade/upgrade-journal.ts
|
|
648
|
-
const recordSchema = Schema.fromJsonString(Schema.Struct({
|
|
649
|
-
schemaVersion: Schema.Literal(1),
|
|
650
|
-
id: Schema.NonEmptyString,
|
|
651
|
-
home: Schema.NonEmptyString,
|
|
652
|
-
sourceVersion: Schema.NonEmptyString,
|
|
653
|
-
targetVersion: Schema.NonEmptyString,
|
|
654
|
-
sourceCommand: Schema.Array(Schema.NonEmptyString),
|
|
655
|
-
service: Schema.Struct({
|
|
656
|
-
kind: Schema.Literals(["launchd", "systemd"]),
|
|
657
|
-
id: Schema.NonEmptyString,
|
|
658
|
-
definitionPath: Schema.NonEmptyString
|
|
659
|
-
}),
|
|
660
|
-
phase: Schema.Literals([
|
|
661
|
-
"preparing",
|
|
662
|
-
"prepared",
|
|
663
|
-
"stopping",
|
|
664
|
-
"stopped",
|
|
665
|
-
"backed-up",
|
|
666
|
-
"switching",
|
|
667
|
-
"starting",
|
|
668
|
-
"complete"
|
|
669
|
-
]),
|
|
670
|
-
createdAt: Schema.NonEmptyString,
|
|
671
|
-
startedAfter: Schema.optional(Schema.NonEmptyString)
|
|
672
|
-
}));
|
|
673
|
-
function upgradePaths(home, id) {
|
|
674
|
-
const directory = join(home, ".rivus-upgrade");
|
|
675
|
-
return {
|
|
676
|
-
directory,
|
|
677
|
-
journal: join(directory, "operation.json"),
|
|
678
|
-
release: join(directory, "releases", id ?? ""),
|
|
679
|
-
backup: join(directory, "backups", id ?? "")
|
|
680
|
-
};
|
|
681
|
-
}
|
|
682
|
-
async function readUpgradeRecord(home) {
|
|
683
|
-
const text = await readPersistenceFile(upgradePaths(home).journal);
|
|
684
|
-
if (text === void 0) return;
|
|
685
|
-
const record = Schema.decodeUnknownSync(recordSchema)(text);
|
|
686
|
-
if (record.home !== home || !/^[a-f\d-]{36}$/.test(record.id)) throw new Error("upgrade journal belongs to another Home or has an invalid operation id");
|
|
687
|
-
return record;
|
|
688
|
-
}
|
|
689
|
-
async function writeUpgradeRecord(record) {
|
|
690
|
-
const paths = upgradePaths(record.home);
|
|
691
|
-
await mkdir(paths.directory, {
|
|
692
|
-
recursive: true,
|
|
693
|
-
mode: 448
|
|
694
|
-
});
|
|
695
|
-
await writeAtomicTextFile(paths.journal, `${JSON.stringify(record)}\n`, {
|
|
696
|
-
durable: true,
|
|
697
|
-
mode: 384
|
|
698
|
-
});
|
|
699
|
-
}
|
|
700
|
-
const ownerSchema = Schema.fromJsonString(Schema.Struct({
|
|
701
|
-
pid: Schema.Int,
|
|
702
|
-
token: Schema.NonEmptyString
|
|
703
|
-
}));
|
|
704
|
-
/** Publishes a complete owner atomically; stale reclamation removes only the owner token actually observed. */
|
|
705
|
-
async function acquireUpgradeLock(home, options) {
|
|
706
|
-
const root = upgradePaths(home).directory;
|
|
707
|
-
await mkdir(root, {
|
|
708
|
-
recursive: true,
|
|
709
|
-
mode: 448
|
|
710
|
-
});
|
|
711
|
-
const token = randomUUID();
|
|
712
|
-
const lock = join(root, "lock");
|
|
713
|
-
const draft = join(root, `.lock-${token}`);
|
|
714
|
-
await mkdir(draft, { mode: 448 });
|
|
715
|
-
try {
|
|
716
|
-
await writeFile(join(draft, token), JSON.stringify({
|
|
717
|
-
pid: options.pid,
|
|
718
|
-
token
|
|
719
|
-
}), {
|
|
720
|
-
flag: "wx",
|
|
721
|
-
mode: 384
|
|
722
|
-
});
|
|
723
|
-
for (let attempt = 0; attempt < 3; attempt++) {
|
|
724
|
-
try {
|
|
725
|
-
await rename(draft, lock);
|
|
726
|
-
return async () => {
|
|
727
|
-
await unlink(join(lock, token));
|
|
728
|
-
await rmdir(lock).catch((error) => {
|
|
729
|
-
if (!hasCode(error, "ENOTEMPTY")) throw error;
|
|
730
|
-
});
|
|
731
|
-
};
|
|
732
|
-
} catch (error) {
|
|
733
|
-
if (!hasCode(error, "ENOTEMPTY") && !hasCode(error, "EEXIST")) throw error;
|
|
734
|
-
}
|
|
735
|
-
let names;
|
|
736
|
-
try {
|
|
737
|
-
names = await readdir(lock);
|
|
738
|
-
} catch (error) {
|
|
739
|
-
if (hasCode(error, "ENOENT")) continue;
|
|
740
|
-
throw error;
|
|
741
|
-
}
|
|
742
|
-
if (names.length !== 1) throw new Error("upgrade lock owner is uninspectable; preserve it for recovery");
|
|
743
|
-
const name = names[0];
|
|
744
|
-
let owner;
|
|
745
|
-
try {
|
|
746
|
-
owner = Schema.decodeUnknownSync(ownerSchema)(await readFile(join(lock, name), "utf8"));
|
|
747
|
-
} catch (error) {
|
|
748
|
-
if (hasCode(error, "ENOENT")) continue;
|
|
749
|
-
throw new Error("upgrade lock owner is uninspectable", { cause: error });
|
|
750
|
-
}
|
|
751
|
-
if (owner.token !== name || owner.pid <= 0 || options.isProcessAlive(owner.pid)) throw new Error("another upgrade owns this Home; wait for that invocation to finish");
|
|
752
|
-
await unlink(join(lock, name)).catch((error) => {
|
|
753
|
-
if (!hasCode(error, "ENOENT")) throw error;
|
|
754
|
-
});
|
|
755
|
-
await rmdir(lock).catch((error) => {
|
|
756
|
-
if (!hasCode(error, "ENOENT") && !hasCode(error, "ENOTEMPTY")) throw error;
|
|
757
|
-
});
|
|
758
|
-
}
|
|
759
|
-
throw new Error("upgrade lock changed concurrently; retry after the current invocation finishes");
|
|
760
|
-
} finally {
|
|
761
|
-
await rm(draft, {
|
|
762
|
-
recursive: true,
|
|
763
|
-
force: true
|
|
764
|
-
});
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
function hasCode(error, code) {
|
|
768
|
-
return Schema.is(Schema.Struct({ code: Schema.Literal(code) }))(error);
|
|
769
|
-
}
|
|
770
654
|
//#endregion
|
|
771
|
-
//#region src/
|
|
772
|
-
|
|
773
|
-
const
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
startedAt: Schema.String.check(Schema.makeFilter((value) => Number.isFinite(Date.parse(value))))
|
|
780
|
-
});
|
|
781
|
-
async function writeRuntimeReceipt(input) {
|
|
782
|
-
const receipt = Schema.decodeUnknownSync(runtimeReceiptSchema)({
|
|
783
|
-
...input,
|
|
784
|
-
home: await realpath(input.home),
|
|
785
|
-
executable: await realpath(input.executable),
|
|
786
|
-
schemaVersion: 1
|
|
787
|
-
});
|
|
788
|
-
const directory = join(receipt.home, ".rivus-upgrade");
|
|
789
|
-
await mkdir(directory, {
|
|
790
|
-
mode: 448,
|
|
791
|
-
recursive: true
|
|
792
|
-
});
|
|
793
|
-
await chmod(directory, 448);
|
|
794
|
-
const path = join(directory, "runtime.json");
|
|
795
|
-
await chmod(path, 384).catch((error) => {
|
|
796
|
-
if (!isMissing$1(error)) throw error;
|
|
797
|
-
});
|
|
798
|
-
await writeAtomicTextFile(path, `${JSON.stringify(receipt)}\n`, {
|
|
799
|
-
durable: true,
|
|
800
|
-
mode: 384
|
|
801
|
-
});
|
|
802
|
-
}
|
|
803
|
-
async function readRuntimeReceipt(home) {
|
|
804
|
-
let canonicalHome;
|
|
805
|
-
let raw;
|
|
806
|
-
try {
|
|
807
|
-
canonicalHome = await realpath(home);
|
|
808
|
-
raw = await readFile(join(canonicalHome, ".rivus-upgrade", "runtime.json"), "utf8");
|
|
809
|
-
} catch (error) {
|
|
810
|
-
if (isMissing$1(error)) return;
|
|
811
|
-
throw error;
|
|
812
|
-
}
|
|
813
|
-
try {
|
|
814
|
-
const receipt = Schema.decodeUnknownSync(runtimeReceiptSchema)(JSON.parse(raw));
|
|
815
|
-
return receipt.home === canonicalHome ? receipt : void 0;
|
|
816
|
-
} catch {
|
|
817
|
-
return;
|
|
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;
|
|
818
663
|
}
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
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");
|
|
828
675
|
}
|
|
829
676
|
//#endregion
|
|
830
|
-
//#region src/
|
|
677
|
+
//#region src/home/infra/adapters/config/local-env-file.ts
|
|
831
678
|
var LocalEnvFileError = class extends Error {
|
|
832
679
|
constructor(message) {
|
|
833
680
|
super(message);
|
|
834
681
|
this.name = "LocalEnvFileError";
|
|
835
682
|
}
|
|
836
683
|
};
|
|
837
|
-
|
|
838
|
-
|
|
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;
|
|
839
688
|
}
|
|
840
|
-
|
|
841
|
-
return
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
const match = (trimmed.startsWith("export ") ? trimmed.slice(7).trimStart() : trimmed).match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
|
|
850
|
-
if (!match) throw new LocalEnvFileError(`Invalid env file line ${index + 1}`);
|
|
851
|
-
const key = match[1];
|
|
852
|
-
const rawValue = match[2];
|
|
853
|
-
env[key] = parseEnvValue(rawValue, index + 1);
|
|
854
|
-
}
|
|
855
|
-
return env;
|
|
856
|
-
}
|
|
857
|
-
function mergeRivusDaemonEnv(fileEnv, overrideEnv) {
|
|
858
|
-
const merged = { ...fileEnv };
|
|
859
|
-
for (const [key, value] of Object.entries(overrideEnv)) if (value !== void 0) merged[key] = value;
|
|
860
|
-
return merged;
|
|
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
|
+
});
|
|
861
698
|
}
|
|
862
699
|
function parseEnvValue(rawValue, lineNumber) {
|
|
863
700
|
const value = rawValue.trim();
|
|
@@ -872,208 +709,47 @@ function parseEnvValue(rawValue, lineNumber) {
|
|
|
872
709
|
}
|
|
873
710
|
return value;
|
|
874
711
|
}
|
|
875
|
-
function
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
}
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
//#region src/platform/home/config/model-management/rivus-model-management-config-migration.ts
|
|
887
|
-
const RIVUS_MODEL_MANAGEMENT_ENABLED_ENV = "RIVUS_MODEL_MANAGEMENT_ENABLED";
|
|
888
|
-
const RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID_ENV = "RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID";
|
|
889
|
-
const RIVUS_MODEL_MANAGEMENT_TENANT_KEY_ENV = "RIVUS_MODEL_MANAGEMENT_TENANT_KEY";
|
|
890
|
-
const RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL_ENV = "RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL";
|
|
891
|
-
var RivusModelManagementConfigError = class extends Error {
|
|
892
|
-
code;
|
|
893
|
-
name = "RivusModelManagementConfigError";
|
|
894
|
-
constructor(code, message) {
|
|
895
|
-
super(message);
|
|
896
|
-
this.code = code;
|
|
897
|
-
}
|
|
898
|
-
};
|
|
899
|
-
/** Parse the Home capability flags without accepting truthy arbitrary strings. */
|
|
900
|
-
function parseRivusModelManagementHomeConfig(env) {
|
|
901
|
-
const enabled = parseRivusModelManagementEnabled(env[RIVUS_MODEL_MANAGEMENT_ENABLED_ENV]);
|
|
902
|
-
const requireApproval = parseStrictBoolean(env[RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL_ENV], RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL_ENV, false);
|
|
903
|
-
const ownerOpenId = optional(env[RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID_ENV]);
|
|
904
|
-
const tenantKey = optional(env[RIVUS_MODEL_MANAGEMENT_TENANT_KEY_ENV]);
|
|
905
|
-
if (enabled && !ownerOpenId) throw new RivusModelManagementConfigError("owner_missing", `${RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID_ENV} is required when model management is enabled`);
|
|
906
|
-
if (enabled && !tenantKey) throw new RivusModelManagementConfigError("tenant_missing", `${RIVUS_MODEL_MANAGEMENT_TENANT_KEY_ENV} is required when model management is enabled`);
|
|
907
|
-
return Object.freeze({
|
|
908
|
-
enabled,
|
|
909
|
-
...ownerOpenId ? { ownerOpenId } : {},
|
|
910
|
-
requireApproval,
|
|
911
|
-
...tenantKey ? { tenantKey } : {}
|
|
912
|
-
});
|
|
913
|
-
}
|
|
914
|
-
function parseRivusModelManagementEnabled(value) {
|
|
915
|
-
return parseStrictBoolean(value, RIVUS_MODEL_MANAGEMENT_ENABLED_ENV, false);
|
|
916
|
-
}
|
|
917
|
-
function parseStrictBoolean(value, variable, defaultValue) {
|
|
918
|
-
if (value === void 0) return defaultValue;
|
|
919
|
-
const normalized = value.trim();
|
|
920
|
-
if (normalized === "true") return true;
|
|
921
|
-
if (normalized === "false") return false;
|
|
922
|
-
throw new RivusModelManagementConfigError("invalid_enabled", `${variable} must be true or false`);
|
|
923
|
-
}
|
|
924
|
-
/**
|
|
925
|
-
* Migrate only the legacy model selection at the explicit enable/disable
|
|
926
|
-
* boundary. The helper does not read or write managed model state.
|
|
927
|
-
*/
|
|
928
|
-
async function migrateRivusModelManagementConfig(input) {
|
|
929
|
-
if (typeof input.managementEnabled !== "boolean") throw new RivusModelManagementConfigError("invalid_enabled", "model management enabled state must be boolean");
|
|
930
|
-
if (input.managementEnabled) return enableModelManagement(input);
|
|
931
|
-
return disableModelManagement(input, parseModelReference(input.knownGoodProvider, input.knownGoodModel));
|
|
932
|
-
}
|
|
933
|
-
async function enableModelManagement(input) {
|
|
934
|
-
if (hasAmbientModelOverride(input.env)) return {
|
|
935
|
-
initialModel: parseConfiguredModel(input.env.PI_MODEL),
|
|
936
|
-
source: "ambient",
|
|
937
|
-
status: "enabled"
|
|
938
|
-
};
|
|
939
|
-
return {
|
|
940
|
-
initialModel: parseConfiguredModel((await loadEnvFile(requireEnvFilePath(input.envFilePath), input.env)).PI_MODEL),
|
|
941
|
-
source: "env-file",
|
|
942
|
-
status: "enabled"
|
|
943
|
-
};
|
|
944
|
-
}
|
|
945
|
-
async function disableModelManagement(input, knownGood) {
|
|
946
|
-
const envFilePath = requireEnvFilePath(input.envFilePath);
|
|
947
|
-
if (hasAmbientModelOverride(input.env)) throw new RivusModelManagementConfigError("ambient_model_override", "ambient PI_MODEL overrides the original env source and prevents verified model readback");
|
|
948
|
-
const original = await readWritableEnvFile(envFilePath);
|
|
949
|
-
const existingModel = parseOptionalConfiguredModel((await loadEnvFile(envFilePath, input.env)).PI_MODEL);
|
|
950
|
-
if (existingModel && sameModel(existingModel, knownGood)) return {
|
|
951
|
-
restoredModel: knownGood,
|
|
952
|
-
source: "env-file",
|
|
953
|
-
status: "unchanged"
|
|
954
|
-
};
|
|
955
|
-
const next = replacePiModel(original, knownGood);
|
|
956
|
-
try {
|
|
957
|
-
await input.writeAtomicTextFile(envFilePath, next, { durable: true });
|
|
958
|
-
} catch {
|
|
959
|
-
throw new RivusModelManagementConfigError("env_source_write_failed", "the original env source write did not complete with a known durable result");
|
|
960
|
-
}
|
|
961
|
-
let readBack;
|
|
962
|
-
try {
|
|
963
|
-
readBack = parseConfiguredModel((await loadMergedLocalEnvFile(envFilePath, input.env)).PI_MODEL);
|
|
964
|
-
} catch {
|
|
965
|
-
throw new RivusModelManagementConfigError("readback_mismatch", "the original env source could not be verified after restoring PI_MODEL");
|
|
966
|
-
}
|
|
967
|
-
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");
|
|
968
|
-
return {
|
|
969
|
-
restoredModel: knownGood,
|
|
970
|
-
source: "env-file",
|
|
971
|
-
status: "exported"
|
|
972
|
-
};
|
|
973
|
-
}
|
|
974
|
-
function parseModelReference(provider, model) {
|
|
975
|
-
if (!isModelPart(provider) || !isModelPart(model)) throw new RivusModelManagementConfigError("invalid_model", "known-good model provider and id are invalid");
|
|
976
|
-
return Object.freeze({
|
|
977
|
-
model,
|
|
978
|
-
provider
|
|
979
|
-
});
|
|
980
|
-
}
|
|
981
|
-
function parseConfiguredModel(value) {
|
|
982
|
-
const configured = optional(value);
|
|
983
|
-
if (!configured) throw new RivusModelManagementConfigError("model_missing", "PI_MODEL is missing from the effective legacy config");
|
|
984
|
-
const separator = configured.indexOf("/");
|
|
985
|
-
if (separator <= 0 || separator === configured.length - 1 || configured.indexOf("/", separator + 1) !== -1) throw new RivusModelManagementConfigError("invalid_model", "PI_MODEL must use provider/model form");
|
|
986
|
-
return parseModelReference(configured.slice(0, separator), configured.slice(separator + 1));
|
|
987
|
-
}
|
|
988
|
-
function parseOptionalConfiguredModel(value) {
|
|
989
|
-
if (!optional(value)) return;
|
|
990
|
-
try {
|
|
991
|
-
return parseConfiguredModel(value);
|
|
992
|
-
} catch {
|
|
993
|
-
return;
|
|
994
|
-
}
|
|
995
|
-
}
|
|
996
|
-
function sameModel(left, right) {
|
|
997
|
-
return left.provider === right.provider && left.model === right.model;
|
|
998
|
-
}
|
|
999
|
-
async function loadEnvFile(envFilePath, env) {
|
|
1000
|
-
try {
|
|
1001
|
-
return await loadMergedLocalEnvFile(envFilePath, env);
|
|
1002
|
-
} catch {
|
|
1003
|
-
throw new RivusModelManagementConfigError("env_source_unreadable", "the original env source could not be loaded");
|
|
1004
|
-
}
|
|
1005
|
-
}
|
|
1006
|
-
async function readWritableEnvFile(envFilePath) {
|
|
1007
|
-
try {
|
|
1008
|
-
const contents = await readFile(envFilePath, "utf8");
|
|
1009
|
-
if (((await stat(envFilePath)).mode & 146) === 0) throw new RivusModelManagementConfigError("env_source_unwritable", "the original env source is not writable");
|
|
1010
|
-
await access(envFilePath, constants.W_OK);
|
|
1011
|
-
return contents;
|
|
1012
|
-
} catch (error) {
|
|
1013
|
-
if (error instanceof RivusModelManagementConfigError) throw error;
|
|
1014
|
-
if (isPermissionError(error)) throw new RivusModelManagementConfigError("env_source_unwritable", "the original env source is not writable");
|
|
1015
|
-
throw new RivusModelManagementConfigError("env_source_unreadable", "the original env source is unavailable");
|
|
1016
|
-
}
|
|
1017
|
-
}
|
|
1018
|
-
function replacePiModel(contents, model) {
|
|
1019
|
-
const modelValue = `${model.provider}/${model.model}`;
|
|
1020
|
-
const parts = contents.split(/(\r\n|\n|\r)/);
|
|
1021
|
-
let replaced = false;
|
|
1022
|
-
for (let index = 0; index < parts.length; index += 2) {
|
|
1023
|
-
const line = parts[index];
|
|
1024
|
-
if (line === void 0) continue;
|
|
1025
|
-
const match = line.match(/^(\s*(?:export\s+)?PI_MODEL\s*=\s*)(.*)$/);
|
|
1026
|
-
if (!match) continue;
|
|
1027
|
-
const inlineComment = match[2].match(/(\s+#.*)$/)?.[1] ?? "";
|
|
1028
|
-
parts[index] = `${match[1]}${modelValue}${inlineComment}`;
|
|
1029
|
-
replaced = true;
|
|
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);
|
|
1030
723
|
}
|
|
1031
|
-
|
|
1032
|
-
const newline = contents.includes("\r\n") ? "\r\n" : contents.includes("\n") ? "\n" : "\n";
|
|
1033
|
-
if (!contents) return `PI_MODEL=${modelValue}${newline}`;
|
|
1034
|
-
return /(?:\r\n|\n|\r)$/.test(contents) ? `${contents}PI_MODEL=${modelValue}${newline}` : `${contents}${newline}PI_MODEL=${modelValue}`;
|
|
1035
|
-
}
|
|
1036
|
-
function requireEnvFilePath(value) {
|
|
1037
|
-
const normalized = optional(value);
|
|
1038
|
-
if (!normalized) throw new RivusModelManagementConfigError("env_source_missing", "an explicit writable original env source is required for model management migration");
|
|
1039
|
-
return normalized;
|
|
1040
|
-
}
|
|
1041
|
-
function hasAmbientModelOverride(env) {
|
|
1042
|
-
return Object.prototype.hasOwnProperty.call(env, "PI_MODEL") && env.PI_MODEL !== void 0;
|
|
1043
|
-
}
|
|
1044
|
-
function isModelPart(value) {
|
|
1045
|
-
return value.trim() === value && value.length > 0 && !/[/\s]/.test(value);
|
|
724
|
+
return env;
|
|
1046
725
|
}
|
|
1047
|
-
function
|
|
1048
|
-
return
|
|
726
|
+
async function loadLocalEnvFile(filePath) {
|
|
727
|
+
return parseLocalEnvFile(await readFile(filePath, "utf8"));
|
|
1049
728
|
}
|
|
1050
|
-
function
|
|
1051
|
-
return
|
|
729
|
+
async function loadMergedLocalEnvFile(filePath, overrideEnv) {
|
|
730
|
+
return mergeRivusDaemonEnv(await loadLocalEnvFile(filePath), overrideEnv);
|
|
1052
731
|
}
|
|
1053
732
|
//#endregion
|
|
1054
|
-
//#region src/
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
} catch {}
|
|
1073
|
-
throw new Error("runtime.command must resolve to an executable file");
|
|
1074
|
-
}
|
|
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.1",
|
|
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
|
+
});
|
|
1075
751
|
//#endregion
|
|
1076
|
-
//#region src/adapters/
|
|
752
|
+
//#region src/deployment/infra/adapters/manifest/node-rivus-deployment-manifest.ts
|
|
1077
753
|
var RivusDeploymentManifestError = class extends Error {
|
|
1078
754
|
manifestPath;
|
|
1079
755
|
name = "RivusDeploymentManifestError";
|
|
@@ -1097,1246 +773,1131 @@ function loadRivusDeploymentManifest(manifestPath, options = {}) {
|
|
|
1097
773
|
});
|
|
1098
774
|
}
|
|
1099
775
|
//#endregion
|
|
1100
|
-
//#region src/
|
|
1101
|
-
const
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
const lockOwnerSchema = Schema.fromJsonString(Schema.Struct({
|
|
1117
|
-
pid: Schema.Int,
|
|
1118
|
-
startedAt: Schema.Number,
|
|
1119
|
-
token: Schema.NonEmptyString
|
|
1120
|
-
}));
|
|
1121
|
-
/**
|
|
1122
|
-
* Takes the installation lock at `path`: a directory holding one owner record named by the owner's token. The record
|
|
1123
|
-
* is written into a private draft directory that is then renamed onto `path`, which succeeds only while `path` is
|
|
1124
|
-
* absent or empty, so a reader never observes a partially written lock. A lock whose pid is dead, whose record is
|
|
1125
|
-
* unreadable, or which is older than `maxAgeMs` is reclaimed by removing that record by name and then `path` only
|
|
1126
|
-
* while it is empty, so a reclaim based on an outdated reading never removes another installer's live lock.
|
|
1127
|
-
*/
|
|
1128
|
-
async function acquireRivusAudioInstallLock(path, options) {
|
|
1129
|
-
const now = options.now ?? Date.now;
|
|
1130
|
-
const isProcessAlive = options.isProcessAlive ?? isLiveProcess;
|
|
1131
|
-
const owner = {
|
|
1132
|
-
pid: process.pid,
|
|
1133
|
-
startedAt: now(),
|
|
1134
|
-
token: randomUUID()
|
|
1135
|
-
};
|
|
1136
|
-
const draft = `${path}.${owner.token}.draft`;
|
|
1137
|
-
await mkdir(draft, { mode: 448 });
|
|
1138
|
-
try {
|
|
1139
|
-
await writeFile(join(draft, owner.token), `${JSON.stringify(owner)}\n`, {
|
|
1140
|
-
flag: "wx",
|
|
1141
|
-
mode: 384
|
|
1142
|
-
});
|
|
1143
|
-
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
1144
|
-
if (await tryPublish(draft, path)) return { release: () => removeRecords(path, [owner.token]) };
|
|
1145
|
-
const records = await readLockRecords(path);
|
|
1146
|
-
if (records.some(({ owner: held }) => held !== void 0 && held.pid !== process.pid && isProcessAlive(held.pid) && now() - held.startedAt < options.maxAgeMs)) throw new RivusAudioInstallInProgressError();
|
|
1147
|
-
await removeRecords(path, records.map(({ name }) => name));
|
|
1148
|
-
}
|
|
1149
|
-
} finally {
|
|
1150
|
-
await rm(draft, {
|
|
1151
|
-
force: true,
|
|
1152
|
-
recursive: true
|
|
1153
|
-
}).catch(() => void 0);
|
|
1154
|
-
}
|
|
1155
|
-
throw new RivusAudioInstallInProgressError();
|
|
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;
|
|
1156
792
|
}
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
await rename(draft, path);
|
|
1160
|
-
return true;
|
|
1161
|
-
} catch (error) {
|
|
1162
|
-
if (hasErrorCode(error, "EEXIST") || hasErrorCode(error, "ENOTEMPTY")) return false;
|
|
1163
|
-
throw error;
|
|
1164
|
-
}
|
|
793
|
+
function renderRivusModelCliArgumentError(error) {
|
|
794
|
+
return `${error}\n\n${RIVUS_MODEL_CLI_USAGE}`;
|
|
1165
795
|
}
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
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" };
|
|
1173
878
|
return {
|
|
1174
|
-
|
|
1175
|
-
|
|
879
|
+
json: true,
|
|
880
|
+
operation,
|
|
881
|
+
...requestId !== void 0 ? { requestId } : {},
|
|
882
|
+
...verbose ? { verbose: true } : {}
|
|
1176
883
|
};
|
|
1177
|
-
}
|
|
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
|
+
};
|
|
1178
903
|
}
|
|
904
|
+
//#endregion
|
|
905
|
+
//#region src/model-management/infra/adapters/cli/rivus-model-management-wire.ts
|
|
1179
906
|
/**
|
|
1180
|
-
*
|
|
1181
|
-
*
|
|
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.
|
|
1182
909
|
*/
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
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
|
+
};
|
|
1186
1008
|
}
|
|
1187
|
-
function
|
|
1188
|
-
|
|
1189
|
-
|
|
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
|
|
1190
1022
|
};
|
|
1023
|
+
return result;
|
|
1191
1024
|
}
|
|
1192
|
-
function
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
}
|
|
1197
|
-
return hasErrorCode(error, "EPERM");
|
|
1198
|
-
}
|
|
1025
|
+
function projectError(value) {
|
|
1026
|
+
return value ? {
|
|
1027
|
+
code: value.code,
|
|
1028
|
+
message: value.message
|
|
1029
|
+
} : void 0;
|
|
1199
1030
|
}
|
|
1200
|
-
function
|
|
1201
|
-
|
|
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
|
+
}
|
|
1202
1036
|
}
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
const
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
id: Schema.NonEmptyString,
|
|
1209
|
-
smoke: Schema.Struct({
|
|
1210
|
-
expect: Schema.NonEmptyString,
|
|
1211
|
-
input: Schema.NonEmptyString
|
|
1212
|
-
})
|
|
1213
|
-
}));
|
|
1214
|
-
const currentSchema = Schema.fromJsonString(Schema.Struct({
|
|
1215
|
-
digest: Schema.optional(Schema.NonEmptyString),
|
|
1216
|
-
id: Schema.NonEmptyString,
|
|
1217
|
-
release: Schema.NonEmptyString
|
|
1218
|
-
}));
|
|
1219
|
-
function rivusAudioCurrentPath(installRoot) {
|
|
1220
|
-
return join(installRoot, "current.json");
|
|
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;
|
|
1221
1042
|
}
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1043
|
+
function projectBudget(value) {
|
|
1044
|
+
return scalarSection(value, [
|
|
1045
|
+
"deadlineAt",
|
|
1046
|
+
"maxOutputTokens",
|
|
1047
|
+
"maxPaidRequests",
|
|
1048
|
+
"outputTokens",
|
|
1049
|
+
"paidRequests"
|
|
1050
|
+
]);
|
|
1227
1051
|
}
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
return name !== "node_modules" && !name.endsWith(".test.ts");
|
|
1052
|
+
function projectNotification(value) {
|
|
1053
|
+
return scalarSection(value, [
|
|
1054
|
+
"attempts",
|
|
1055
|
+
"lastAttemptAt",
|
|
1056
|
+
"status"
|
|
1057
|
+
]);
|
|
1235
1058
|
}
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
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;
|
|
1245
1079
|
}
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
const text = await readPersistenceFile(rivusAudioCurrentPath(installRoot));
|
|
1254
|
-
const current = text === void 0 ? void 0 : Option.getOrUndefined(Schema.decodeUnknownOption(currentSchema)(text));
|
|
1255
|
-
if (current === void 0) return;
|
|
1256
|
-
const directory = resolve(installRoot, current.release);
|
|
1257
|
-
if (!isStrictlyWithin(join(installRoot, "releases"), directory)) return;
|
|
1258
|
-
return await stat(directory).then((info) => info.isDirectory(), () => false) ? {
|
|
1259
|
-
...current.digest === void 0 ? {} : { digest: current.digest },
|
|
1260
|
-
directory,
|
|
1261
|
-
id: current.id,
|
|
1262
|
-
release: current.release
|
|
1263
|
-
} : void 0;
|
|
1264
|
-
}
|
|
1265
|
-
async function readRivusAudioStatus(installRoot, assetDirectory) {
|
|
1266
|
-
const expected = await readRivusAudioReleaseManifest(assetDirectory);
|
|
1267
|
-
const expectedDigest = await readRivusAudioAssetDigest(assetDirectory);
|
|
1268
|
-
const installed = await readRivusAudioInstalledRelease(installRoot);
|
|
1269
|
-
return installed === void 0 ? {
|
|
1270
|
-
installed: false,
|
|
1271
|
-
expectedId: expected.id,
|
|
1272
|
-
expectedDigest,
|
|
1273
|
-
upToDate: false
|
|
1274
|
-
} : {
|
|
1275
|
-
installed: true,
|
|
1276
|
-
id: installed.id,
|
|
1277
|
-
...installed.digest === void 0 ? {} : { digest: installed.digest },
|
|
1278
|
-
release: installed.directory,
|
|
1279
|
-
expectedId: expected.id,
|
|
1280
|
-
expectedDigest,
|
|
1281
|
-
upToDate: installed.id === expected.id && installed.digest === expectedDigest
|
|
1282
|
-
};
|
|
1283
|
-
}
|
|
1284
|
-
/** Lists the release asset files by relative path with "/" separators. */
|
|
1285
|
-
async function listAssetFiles(root, prefix) {
|
|
1286
|
-
const entries = await readdir(join(root, prefix), { withFileTypes: true });
|
|
1287
|
-
return (await Promise.all(entries.filter((entry) => isRivusAudioReleaseAsset(entry.name)).map(async (entry) => {
|
|
1288
|
-
const path = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
|
|
1289
|
-
return entry.isDirectory() ? listAssetFiles(root, path) : [path];
|
|
1290
|
-
}))).flat();
|
|
1291
|
-
}
|
|
1292
|
-
function isStrictlyWithin(root, candidate) {
|
|
1293
|
-
return candidate !== resolve(root) && isPathWithin(root, candidate);
|
|
1294
|
-
}
|
|
1295
|
-
//#endregion
|
|
1296
|
-
//#region src/adapters/audio/managed/rivus-audio-installer.ts
|
|
1297
|
-
const INSTALL_DEADLINE_MS = 15e5;
|
|
1298
|
-
const NPM_TIMEOUT_MS = 3e5;
|
|
1299
|
-
const FETCH_TIMEOUT_MS = 12e5;
|
|
1300
|
-
const SMOKE_TIMEOUT_MS = 3e5;
|
|
1301
|
-
const STALE_LOCK_MS = 2 * INSTALL_DEADLINE_MS;
|
|
1302
|
-
const LOCK_POLL_MS = 2e3;
|
|
1303
|
-
const STAGING_PREFIX = "staging-";
|
|
1304
|
-
var RivusAudioInstallStepError = class extends Error {
|
|
1305
|
-
step;
|
|
1306
|
-
constructor(step, reason, output = "") {
|
|
1307
|
-
const detail = output.trim().slice(-4e3);
|
|
1308
|
-
super(`audio transcriber installation failed at ${step}: ${reason}${detail ? `\n${detail}` : ""}`);
|
|
1309
|
-
this.name = "RivusAudioInstallStepError";
|
|
1310
|
-
this.step = step;
|
|
1311
|
-
}
|
|
1312
|
-
};
|
|
1313
|
-
/**
|
|
1314
|
-
* Builds a release in a staging directory beside `releases/`, smoke-tests it, then publishes it by renaming the
|
|
1315
|
-
* directory and atomically replacing current.json. A failure before current.json changes leaves the previous release
|
|
1316
|
-
* selected and removes the staging directory. While another installer holds the lock, this one waits within its
|
|
1317
|
-
* deadline and then rechecks current.json, so it does not rebuild a release that installer just published.
|
|
1318
|
-
*/
|
|
1319
|
-
async function installRivusAudioTranscriber(options) {
|
|
1320
|
-
const now = options.now ?? Date.now;
|
|
1321
|
-
const deadlineMs = options.deadlineMs ?? INSTALL_DEADLINE_MS;
|
|
1322
|
-
const deadline = {
|
|
1323
|
-
at: now() + deadlineMs,
|
|
1324
|
-
ms: deadlineMs,
|
|
1325
|
-
now
|
|
1326
|
-
};
|
|
1327
|
-
const root = resolve(options.installRoot);
|
|
1328
|
-
await mkdir(root, { recursive: true });
|
|
1329
|
-
const lock = await acquireLockWhenFree(root, options, deadline);
|
|
1330
|
-
try {
|
|
1331
|
-
await removeInterruptedStaging(root);
|
|
1332
|
-
const previous = await readRivusAudioInstalledRelease(root);
|
|
1333
|
-
if (!options.force && options.reuseInstalledRelease && previous) return {
|
|
1334
|
-
status: "already-installed",
|
|
1335
|
-
id: previous.id,
|
|
1336
|
-
release: previous.directory
|
|
1337
|
-
};
|
|
1338
|
-
const manifest = await readRivusAudioReleaseManifest(options.assetDirectory);
|
|
1339
|
-
const digest = await readRivusAudioAssetDigest(options.assetDirectory);
|
|
1340
|
-
if (!options.force && previous?.id === manifest.id && previous.digest === digest) return {
|
|
1341
|
-
status: "already-installed",
|
|
1342
|
-
id: previous.id,
|
|
1343
|
-
release: previous.directory
|
|
1344
|
-
};
|
|
1345
|
-
const release = await buildRelease(root, manifest, digest, options, deadline);
|
|
1346
|
-
await pruneReleases(root, [release, previous?.directory]);
|
|
1347
|
-
return {
|
|
1348
|
-
status: "installed",
|
|
1349
|
-
id: manifest.id,
|
|
1350
|
-
release
|
|
1351
|
-
};
|
|
1352
|
-
} finally {
|
|
1353
|
-
await lock.release().catch(() => void 0);
|
|
1354
|
-
}
|
|
1355
|
-
}
|
|
1356
|
-
async function acquireLockWhenFree(root, options, deadline) {
|
|
1357
|
-
const sleep = options.sleep ?? ((ms) => sleepUnlessAborted(ms, options.signal));
|
|
1358
|
-
for (;;) {
|
|
1359
|
-
try {
|
|
1360
|
-
return await acquireRivusAudioInstallLock(join(root, "install.lock"), {
|
|
1361
|
-
maxAgeMs: STALE_LOCK_MS,
|
|
1362
|
-
...options.isProcessAlive ? { isProcessAlive: options.isProcessAlive } : {}
|
|
1363
|
-
});
|
|
1364
|
-
} catch (error) {
|
|
1365
|
-
if (!(error instanceof RivusAudioInstallInProgressError)) throw error;
|
|
1366
|
-
}
|
|
1367
|
-
const remainingMs = deadline.at - deadline.now();
|
|
1368
|
-
if (remainingMs <= 0) throw new Error("another audio transcriber installation did not finish in time");
|
|
1369
|
-
await sleep(Math.min(LOCK_POLL_MS, remainingMs));
|
|
1370
|
-
if (options.signal?.aborted) throw new Error("audio transcriber installation was interrupted while waiting for another installation");
|
|
1371
|
-
}
|
|
1372
|
-
}
|
|
1373
|
-
function sleepUnlessAborted(ms, signal) {
|
|
1374
|
-
return setTimeout$1(ms, void 0, signal ? { signal } : {}).catch(() => void 0);
|
|
1375
|
-
}
|
|
1376
|
-
async function buildRelease(root, manifest, digest, options, deadline) {
|
|
1377
|
-
const staging = join(root, `${STAGING_PREFIX}${randomUUID()}`);
|
|
1378
|
-
const release = join(root, RIVUS_AUDIO_RELEASES_DIRECTORY, `${manifest.id.replaceAll(/[^\w.-]/g, "_")}-${digest.slice(0, 12)}-${randomUUID().slice(0, 8)}`);
|
|
1379
|
-
const env = withNodeOnPath(options.env, options.nodeExecutable);
|
|
1380
|
-
let renamed = false;
|
|
1381
|
-
try {
|
|
1382
|
-
await cp(options.assetDirectory, staging, {
|
|
1383
|
-
filter: (source) => isRivusAudioReleaseAsset(basename(source)),
|
|
1384
|
-
recursive: true
|
|
1385
|
-
}).catch((error) => {
|
|
1386
|
-
throw new RivusAudioInstallStepError("copy assets", errorMessage(error));
|
|
1387
|
-
});
|
|
1388
|
-
await runStep(options, deadline, "npm ci", {
|
|
1389
|
-
args: [
|
|
1390
|
-
"ci",
|
|
1391
|
-
"--ignore-scripts",
|
|
1392
|
-
"--omit=dev",
|
|
1393
|
-
"--no-audit",
|
|
1394
|
-
"--no-fund"
|
|
1395
|
-
],
|
|
1396
|
-
command: "npm",
|
|
1397
|
-
cwd: staging,
|
|
1398
|
-
env,
|
|
1399
|
-
timeoutMs: NPM_TIMEOUT_MS
|
|
1400
|
-
});
|
|
1401
|
-
await runStep(options, deadline, "model download", {
|
|
1402
|
-
args: [
|
|
1403
|
-
"fetch-model.mjs",
|
|
1404
|
-
RIVUS_AUDIO_MANIFEST_FILE,
|
|
1405
|
-
"model"
|
|
1406
|
-
],
|
|
1407
|
-
command: options.nodeExecutable,
|
|
1408
|
-
cwd: staging,
|
|
1409
|
-
env,
|
|
1410
|
-
timeoutMs: FETCH_TIMEOUT_MS
|
|
1411
|
-
});
|
|
1412
|
-
const { RIVUS_AUDIO_LANGUAGE: _language, ...smokeEnv } = env;
|
|
1413
|
-
const smoke = await runStep(options, deadline, "smoke test", {
|
|
1414
|
-
args: ["transcribe.mjs", resolve(staging, manifest.smoke.input)],
|
|
1415
|
-
command: options.nodeExecutable,
|
|
1416
|
-
cwd: staging,
|
|
1417
|
-
env: smokeEnv,
|
|
1418
|
-
timeoutMs: SMOKE_TIMEOUT_MS
|
|
1419
|
-
});
|
|
1420
|
-
if (smoke.stderrTail !== "") throw new RivusAudioInstallStepError("smoke test", "the transcriber wrote to stderr", smoke.stderrTail);
|
|
1421
|
-
if (!smoke.stdout.includes(manifest.smoke.expect)) throw new RivusAudioInstallStepError("smoke test", `the transcript does not contain ${JSON.stringify(manifest.smoke.expect)}`, smoke.stdout);
|
|
1422
|
-
await mkdir(dirname(release), { recursive: true });
|
|
1423
|
-
await rename(staging, release);
|
|
1424
|
-
renamed = true;
|
|
1425
|
-
await writeAtomicTextFile(rivusAudioCurrentPath(root), `${JSON.stringify({
|
|
1426
|
-
id: manifest.id,
|
|
1427
|
-
digest,
|
|
1428
|
-
release: relative(root, release)
|
|
1429
|
-
})}\n`, { durable: true });
|
|
1430
|
-
return release;
|
|
1431
|
-
} catch (error) {
|
|
1432
|
-
if ((renamed ? await readRivusAudioInstalledRelease(root).then((installed) => installed?.directory, () => void 0) : void 0) !== release) await rm(renamed ? release : staging, {
|
|
1433
|
-
force: true,
|
|
1434
|
-
recursive: true
|
|
1435
|
-
}).catch(() => void 0);
|
|
1436
|
-
throw error instanceof RivusAudioInstallStepError ? error : new RivusAudioInstallStepError("publish", errorMessage(error));
|
|
1437
|
-
}
|
|
1438
|
-
}
|
|
1439
|
-
async function runStep(options, deadline, step, request) {
|
|
1440
|
-
if (options.signal?.aborted) throw new RivusAudioInstallStepError(step, "interrupted");
|
|
1441
|
-
const deadlineReason = `the installation did not finish within ${seconds(deadline.ms)} s`;
|
|
1442
|
-
const remainingMs = deadline.at - deadline.now();
|
|
1443
|
-
if (remainingMs <= 0) throw new RivusAudioInstallStepError(step, deadlineReason);
|
|
1444
|
-
const timeoutMs = Math.min(request.timeoutMs, remainingMs);
|
|
1445
|
-
const result = await options.runProcess({
|
|
1446
|
-
...request,
|
|
1447
|
-
timeoutMs,
|
|
1448
|
-
...options.signal ? { signal: options.signal } : {}
|
|
1449
|
-
}).catch((error) => {
|
|
1450
|
-
throw new RivusAudioInstallStepError(step, `could not start ${request.command}: ${errorMessage(error)}`);
|
|
1451
|
-
});
|
|
1452
|
-
if (result.outcome === "timed-out") throw new RivusAudioInstallStepError(step, timeoutMs < request.timeoutMs ? deadlineReason : `timed out after ${seconds(request.timeoutMs)} s`, result.stderrTail);
|
|
1453
|
-
if (result.outcome === "interrupted") throw new RivusAudioInstallStepError(step, "interrupted", result.stderrTail);
|
|
1454
|
-
if (result.exitCode !== 0) throw new RivusAudioInstallStepError(step, `exited with code ${String(result.exitCode)}`, result.stderrTail);
|
|
1455
|
-
return result;
|
|
1456
|
-
}
|
|
1457
|
-
async function removeInterruptedStaging(root) {
|
|
1458
|
-
const entries = await readdir(root);
|
|
1459
|
-
await Promise.all(entries.filter((name) => name.startsWith(STAGING_PREFIX)).map((name) => join(root, name)).map((path) => rm(path, {
|
|
1460
|
-
force: true,
|
|
1461
|
-
maxRetries: 5,
|
|
1462
|
-
recursive: true
|
|
1463
|
-
}).catch((error) => {
|
|
1464
|
-
throw new RivusAudioInstallStepError("staging cleanup", `could not remove the staging directory of an interrupted installation, ${path}: ${errorMessage(error)}`);
|
|
1465
|
-
})));
|
|
1466
|
-
}
|
|
1467
|
-
/** Keeps the new and the previous release, so a transcription that started before the switch can still finish. */
|
|
1468
|
-
async function pruneReleases(root, keep) {
|
|
1469
|
-
const directory = join(root, RIVUS_AUDIO_RELEASES_DIRECTORY);
|
|
1470
|
-
const kept = new Set(keep.filter((path) => path !== void 0));
|
|
1471
|
-
const entries = await readdir(directory).catch(() => []);
|
|
1472
|
-
await Promise.all(entries.map((name) => join(directory, name)).filter((path) => !kept.has(path)).map((path) => rm(path, {
|
|
1473
|
-
force: true,
|
|
1474
|
-
recursive: true
|
|
1475
|
-
}).catch(() => void 0)));
|
|
1476
|
-
}
|
|
1477
|
-
/** npm may be missing from a service PATH, but it is installed beside the running Node executable. */
|
|
1478
|
-
function withNodeOnPath(env, nodeExecutable) {
|
|
1479
|
-
const nodeDirectory = dirname(nodeExecutable);
|
|
1480
|
-
return {
|
|
1481
|
-
...env,
|
|
1482
|
-
PATH: env.PATH ? `${nodeDirectory}${delimiter}${env.PATH}` : nodeDirectory
|
|
1483
|
-
};
|
|
1484
|
-
}
|
|
1485
|
-
function seconds(ms) {
|
|
1486
|
-
return String(ms / 1e3);
|
|
1487
|
-
}
|
|
1488
|
-
function errorMessage(error) {
|
|
1489
|
-
return error instanceof Error ? error.message : String(error);
|
|
1490
|
-
}
|
|
1491
|
-
//#endregion
|
|
1492
|
-
//#region src/adapters/audio/managed/rivus-audio-process.ts
|
|
1493
|
-
const OUTPUT_LIMIT = 65536;
|
|
1494
|
-
const KILL_GRACE_MS = 2e3;
|
|
1495
|
-
/**
|
|
1496
|
-
* Deployment transcription on POSIX owns an isolated group, including wrapper descendants that inherit its pipes.
|
|
1497
|
-
* Managed steps stay in the caller's group and must not spawn children: npm uses --ignore-scripts and plain Node assets.
|
|
1498
|
-
*/
|
|
1499
|
-
function runRivusAudioProcess(request) {
|
|
1500
|
-
return new Promise((resolve, reject) => {
|
|
1501
|
-
const stdoutChunks = [];
|
|
1502
|
-
let stdoutBytes = 0;
|
|
1503
|
-
let stdoutTruncated = false;
|
|
1504
|
-
let stderrTail = "";
|
|
1505
|
-
const stderrHeadChunks = [];
|
|
1506
|
-
let stderrHeadBytes = 0;
|
|
1507
|
-
const isolated = request.processGroup === "isolated" && process.platform !== "win32";
|
|
1508
|
-
const child = spawnAudioProcess(request, (text) => {
|
|
1509
|
-
const bytes = Buffer.from(text);
|
|
1510
|
-
const remaining = OUTPUT_LIMIT - stdoutBytes;
|
|
1511
|
-
stdoutTruncated ||= bytes.length > remaining;
|
|
1512
|
-
if (remaining > 0) {
|
|
1513
|
-
const chunk = bytes.subarray(0, remaining);
|
|
1514
|
-
stdoutChunks.push(chunk);
|
|
1515
|
-
stdoutBytes += chunk.length;
|
|
1516
|
-
}
|
|
1517
|
-
}, (text) => {
|
|
1518
|
-
stderrTail = (stderrTail + text).slice(-65536);
|
|
1519
|
-
const prefix = Buffer.from(text).subarray(0, Math.max(0, 4096 - stderrHeadBytes));
|
|
1520
|
-
if (prefix.length > 0) {
|
|
1521
|
-
stderrHeadChunks.push(prefix);
|
|
1522
|
-
stderrHeadBytes += prefix.length;
|
|
1523
|
-
}
|
|
1524
|
-
});
|
|
1525
|
-
let outcome = "exited";
|
|
1526
|
-
let exitCode = null;
|
|
1527
|
-
let exited = false;
|
|
1528
|
-
let closed = false;
|
|
1529
|
-
let escalation;
|
|
1530
|
-
let termination;
|
|
1531
|
-
let finishTermination;
|
|
1532
|
-
const signalChild = (signal) => {
|
|
1533
|
-
try {
|
|
1534
|
-
if (isolated && child.pid !== void 0) process.kill(-child.pid, signal);
|
|
1535
|
-
else child.kill(signal);
|
|
1536
|
-
} catch {}
|
|
1537
|
-
};
|
|
1538
|
-
const stop = (reason) => {
|
|
1539
|
-
if (closed || !isolated && exited || outcome !== "exited") return;
|
|
1540
|
-
outcome = reason;
|
|
1541
|
-
if (isolated) termination = new Promise((resolveTermination) => {
|
|
1542
|
-
finishTermination = resolveTermination;
|
|
1543
|
-
});
|
|
1544
|
-
signalChild("SIGTERM");
|
|
1545
|
-
escalation = setTimeout(() => {
|
|
1546
|
-
signalChild("SIGKILL");
|
|
1547
|
-
finishTermination?.();
|
|
1548
|
-
}, KILL_GRACE_MS);
|
|
1549
|
-
};
|
|
1550
|
-
const onAbort = () => stop("interrupted");
|
|
1551
|
-
const timeout = setTimeout(() => stop("timed-out"), request.timeoutMs);
|
|
1552
|
-
const finish = () => {
|
|
1553
|
-
clearTimeout(timeout);
|
|
1554
|
-
clearTimeout(escalation);
|
|
1555
|
-
request.signal?.removeEventListener("abort", onAbort);
|
|
1556
|
-
};
|
|
1557
|
-
request.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1558
|
-
if (request.signal?.aborted) onAbort();
|
|
1559
|
-
child.once("exit", (code) => {
|
|
1560
|
-
exited = true;
|
|
1561
|
-
exitCode = code;
|
|
1562
|
-
});
|
|
1563
|
-
child.once("error", (error) => {
|
|
1564
|
-
finish();
|
|
1565
|
-
reject(error);
|
|
1566
|
-
});
|
|
1567
|
-
child.once("close", async () => {
|
|
1568
|
-
closed = true;
|
|
1569
|
-
if (termination) {
|
|
1570
|
-
try {
|
|
1571
|
-
process.kill(-child.pid, 0);
|
|
1572
|
-
} catch {
|
|
1573
|
-
clearTimeout(escalation);
|
|
1574
|
-
finishTermination?.();
|
|
1575
|
-
}
|
|
1576
|
-
await termination;
|
|
1577
|
-
}
|
|
1578
|
-
finish();
|
|
1579
|
-
const stdout = new TextDecoder().decode(Buffer.concat(stdoutChunks), { stream: true });
|
|
1580
|
-
const stderrHead = new TextDecoder().decode(Buffer.concat(stderrHeadChunks), { stream: true });
|
|
1581
|
-
resolve({
|
|
1582
|
-
exitCode,
|
|
1583
|
-
outcome,
|
|
1584
|
-
stderrTail,
|
|
1585
|
-
stderrHead,
|
|
1586
|
-
stdout,
|
|
1587
|
-
...stdoutTruncated ? { stdoutTruncated: true } : {}
|
|
1588
|
-
});
|
|
1589
|
-
});
|
|
1590
|
-
});
|
|
1591
|
-
}
|
|
1592
|
-
/** Streams the transcriber's stdout and stderr to the caller and resolves with its exit code. */
|
|
1593
|
-
function runRivusAudioPassthroughProcess(request) {
|
|
1594
|
-
return new Promise((resolve, reject) => {
|
|
1595
|
-
const child = spawnAudioProcess(request, (text) => request.stdout.write(text), (text) => request.stderr.write(text));
|
|
1596
|
-
const onAbort = () => {
|
|
1597
|
-
child.kill("SIGTERM");
|
|
1598
|
-
};
|
|
1599
|
-
request.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1600
|
-
child.once("error", (error) => {
|
|
1601
|
-
request.signal?.removeEventListener("abort", onAbort);
|
|
1602
|
-
reject(error);
|
|
1603
|
-
});
|
|
1604
|
-
child.once("close", (code) => {
|
|
1605
|
-
request.signal?.removeEventListener("abort", onAbort);
|
|
1606
|
-
resolve(code);
|
|
1607
|
-
});
|
|
1608
|
-
});
|
|
1609
|
-
}
|
|
1610
|
-
/**
|
|
1611
|
-
* Managed steps retain service-level group termination; deployment wrappers get a separately terminable group.
|
|
1612
|
-
*/
|
|
1613
|
-
function spawnAudioProcess(request, onStdout, onStderr) {
|
|
1614
|
-
const child = spawn(request.command, [...request.args], {
|
|
1615
|
-
cwd: request.cwd,
|
|
1616
|
-
env: { ...request.env },
|
|
1617
|
-
detached: request.processGroup === "isolated" && process.platform !== "win32",
|
|
1618
|
-
stdio: [
|
|
1619
|
-
"ignore",
|
|
1620
|
-
"pipe",
|
|
1621
|
-
"pipe"
|
|
1622
|
-
]
|
|
1623
|
-
});
|
|
1624
|
-
child.stdout.setEncoding("utf8").on("data", onStdout);
|
|
1625
|
-
child.stderr.setEncoding("utf8").on("data", onStderr);
|
|
1626
|
-
return child;
|
|
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;
|
|
1627
1087
|
}
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
if (
|
|
1645
|
-
const
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
if (!value || value.startsWith("-")) return { error: "--request requires an id" };
|
|
1668
|
-
requestId = value;
|
|
1669
|
-
index += 1;
|
|
1670
|
-
continue;
|
|
1671
|
-
}
|
|
1672
|
-
if (argument.startsWith("--request=")) {
|
|
1673
|
-
if (requestId !== void 0) return { error: "--request may only be provided once" };
|
|
1674
|
-
requestId = argument.slice(10);
|
|
1675
|
-
if (!requestId) return { error: "--request requires an id" };
|
|
1676
|
-
continue;
|
|
1677
|
-
}
|
|
1678
|
-
if (argument === "--expected-revision") {
|
|
1679
|
-
if (expectedRevision !== void 0) return { error: "--expected-revision may only be provided once" };
|
|
1680
|
-
const value = argv[index + 1];
|
|
1681
|
-
if (!value || value.startsWith("-")) return { error: "--expected-revision requires a non-negative integer" };
|
|
1682
|
-
const parsed = parseRevision(value);
|
|
1683
|
-
if (parsed === void 0) return { error: "--expected-revision requires a non-negative integer" };
|
|
1684
|
-
expectedRevision = parsed;
|
|
1685
|
-
index += 1;
|
|
1686
|
-
continue;
|
|
1687
|
-
}
|
|
1688
|
-
if (argument.startsWith("--expected-revision=")) {
|
|
1689
|
-
if (expectedRevision !== void 0) return { error: "--expected-revision may only be provided once" };
|
|
1690
|
-
const parsed = parseRevision(argument.slice(20));
|
|
1691
|
-
if (parsed === void 0) return { error: "--expected-revision requires a non-negative integer" };
|
|
1692
|
-
expectedRevision = parsed;
|
|
1693
|
-
continue;
|
|
1694
|
-
}
|
|
1695
|
-
if (argument === "--model") {
|
|
1696
|
-
if (model !== void 0) return { error: "--model may only be provided once" };
|
|
1697
|
-
const value = argv[index + 1];
|
|
1698
|
-
if (!value || value.startsWith("-")) return { error: "--model requires provider/model" };
|
|
1699
|
-
if (!isModelReference(value)) return { error: "--model must be provider/model" };
|
|
1700
|
-
model = value;
|
|
1701
|
-
index += 1;
|
|
1702
|
-
continue;
|
|
1703
|
-
}
|
|
1704
|
-
if (argument.startsWith("--model=")) {
|
|
1705
|
-
if (model !== void 0) return { error: "--model may only be provided once" };
|
|
1706
|
-
const value = argument.slice(8);
|
|
1707
|
-
if (!isModelReference(value)) return { error: "--model must be provider/model" };
|
|
1708
|
-
model = value;
|
|
1709
|
-
continue;
|
|
1710
|
-
}
|
|
1711
|
-
return { error: `Unknown model option: ${argument}` };
|
|
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;
|
|
1712
1127
|
}
|
|
1713
|
-
|
|
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;
|
|
1714
1178
|
if (operation === "status") {
|
|
1715
|
-
if (
|
|
1716
|
-
if (expectedRevision !== void 0) return { error: "status does not accept --expected-revision" };
|
|
1179
|
+
if (value.json !== true) throw new Error("model request must require JSON output");
|
|
1717
1180
|
return {
|
|
1718
1181
|
json: true,
|
|
1719
1182
|
operation,
|
|
1720
|
-
...
|
|
1183
|
+
...context ? { context } : {},
|
|
1184
|
+
...requestId ? { requestId } : {},
|
|
1721
1185
|
...verbose ? { verbose: true } : {}
|
|
1722
1186
|
};
|
|
1723
1187
|
}
|
|
1724
|
-
|
|
1725
|
-
if (expectedRevision
|
|
1726
|
-
if (
|
|
1727
|
-
if (operation === "
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
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 {
|
|
1736
1205
|
expectedRevision,
|
|
1737
1206
|
json: true,
|
|
1738
1207
|
operation,
|
|
1739
1208
|
requestId,
|
|
1209
|
+
...context ? { context } : {},
|
|
1740
1210
|
...verbose ? { verbose: true } : {}
|
|
1741
1211
|
};
|
|
1742
1212
|
}
|
|
1743
|
-
|
|
1744
|
-
|
|
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`);
|
|
1745
1233
|
}
|
|
1746
|
-
function
|
|
1747
|
-
return
|
|
1234
|
+
function parseRivusModelManagementEnabled(value) {
|
|
1235
|
+
return parseStrictBoolean(value, RIVUS_MODEL_MANAGEMENT_ENABLED_ENV, false);
|
|
1748
1236
|
}
|
|
1749
|
-
function
|
|
1750
|
-
return
|
|
1237
|
+
function sameModel(left, right) {
|
|
1238
|
+
return left.provider === right.provider && left.model === right.model;
|
|
1751
1239
|
}
|
|
1752
|
-
function
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
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
|
+
}
|
|
1756
1246
|
}
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
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");
|
|
1761
1363
|
return {
|
|
1762
|
-
|
|
1763
|
-
|
|
1364
|
+
restoredModel: knownGood,
|
|
1365
|
+
source: "env-file",
|
|
1366
|
+
status: "exported"
|
|
1764
1367
|
};
|
|
1765
1368
|
}
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
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);
|
|
1775
1395
|
return {
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
...context ? { context } : {},
|
|
1779
|
-
...requestId ? { requestId } : {},
|
|
1780
|
-
...verbose ? { verbose: true } : {}
|
|
1396
|
+
created: true,
|
|
1397
|
+
entry
|
|
1781
1398
|
};
|
|
1782
|
-
}
|
|
1783
|
-
const
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
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);
|
|
1789
1414
|
return {
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
model,
|
|
1793
|
-
operation,
|
|
1794
|
-
requestId,
|
|
1795
|
-
...context ? { context } : {},
|
|
1796
|
-
...verbose ? { verbose: true } : {}
|
|
1415
|
+
entry: selected.entry,
|
|
1416
|
+
runtime: yield* restore(Deferred.await(selected.entry.deferred))
|
|
1797
1417
|
};
|
|
1798
|
-
}
|
|
1799
|
-
return {
|
|
1800
|
-
expectedRevision,
|
|
1801
|
-
json: true,
|
|
1802
|
-
operation,
|
|
1803
|
-
requestId,
|
|
1804
|
-
...context ? { context } : {},
|
|
1805
|
-
...verbose ? { verbose: true } : {}
|
|
1806
|
-
};
|
|
1807
|
-
}
|
|
1808
|
-
function toRivusModelManagementSubmission(request) {
|
|
1809
|
-
const target = request.operation === "set" ? parseTarget(request.model) : void 0;
|
|
1418
|
+
}));
|
|
1810
1419
|
return {
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
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
|
|
1816
1438
|
};
|
|
1817
1439
|
}
|
|
1818
|
-
function
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
"persisted",
|
|
1834
|
-
"previous",
|
|
1835
|
-
"target"
|
|
1836
|
-
]) {
|
|
1837
|
-
const model = projectModelReference(value[key]);
|
|
1838
|
-
if (model) response[key] = model;
|
|
1839
|
-
}
|
|
1840
|
-
const budget = projectBudget(value.budget);
|
|
1841
|
-
if (budget) response.budget = budget;
|
|
1842
|
-
const pending = projectPending(value.pending);
|
|
1843
|
-
if (pending) response.pending = pending;
|
|
1844
|
-
const request = projectReceipt(value.request);
|
|
1845
|
-
if (request) response.request = request;
|
|
1846
|
-
const error = projectError(value.error);
|
|
1847
|
-
if (error) response.error = error;
|
|
1848
|
-
const recoveryRequired = projectError(value.recoveryRequired);
|
|
1849
|
-
if (recoveryRequired) response.recoveryRequired = recoveryRequired;
|
|
1850
|
-
const notification = projectNotification(value.notification);
|
|
1851
|
-
if (notification) response.notification = notification;
|
|
1852
|
-
const status = value.status;
|
|
1853
|
-
response.status = isPublicStatus(status) ? status : value.recoveryRequired !== void 0 ? "recovery-required" : operation === "status" && value.pending !== void 0 ? "pending" : operation === "status" ? "applied" : "failed";
|
|
1854
|
-
return response;
|
|
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;
|
|
1855
1455
|
}
|
|
1856
|
-
function
|
|
1857
|
-
return
|
|
1858
|
-
error: {
|
|
1859
|
-
code,
|
|
1860
|
-
message
|
|
1861
|
-
},
|
|
1862
|
-
schemaVersion: 1,
|
|
1863
|
-
status: "failed"
|
|
1864
|
-
};
|
|
1456
|
+
function invokeRuntimeControl(runtime, control) {
|
|
1457
|
+
return runtime.pipe(Effect.flatMap((selected) => selected ? control(selected) ?? Effect.succeed(false) : Effect.succeed(false)));
|
|
1865
1458
|
}
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
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() };
|
|
1881
1479
|
}
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
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");
|
|
1895
1498
|
}
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
"operation",
|
|
1904
|
-
"expectedRevision",
|
|
1905
|
-
"acceptedAt",
|
|
1906
|
-
"updatedAt"
|
|
1907
|
-
]);
|
|
1908
|
-
const current = projectModelReference(value.current);
|
|
1909
|
-
if (current) result.current = current;
|
|
1910
|
-
const previous = projectModelReference(value.previous);
|
|
1911
|
-
if (previous) result.previous = previous;
|
|
1912
|
-
const target = projectModelReference(value.target);
|
|
1913
|
-
if (target) result.target = target;
|
|
1914
|
-
const budget = projectBudget(value.budget);
|
|
1915
|
-
if (budget) result.budget = budget;
|
|
1916
|
-
const error = projectError(value.error);
|
|
1917
|
-
if (error) result.error = error;
|
|
1918
|
-
const notification = projectNotification(value.notification);
|
|
1919
|
-
if (notification) result.notification = notification;
|
|
1920
|
-
return Object.keys(result).length > 0 ? result : void 0;
|
|
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");
|
|
1921
1506
|
}
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
const
|
|
1925
|
-
|
|
1926
|
-
"
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
"paidRequests"
|
|
1930
|
-
]);
|
|
1931
|
-
return Object.keys(result).length > 0 ? result : void 0;
|
|
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();
|
|
1932
1514
|
}
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
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");
|
|
1939
1526
|
}
|
|
1940
|
-
function
|
|
1941
|
-
|
|
1942
|
-
const result = scalarFields(value, [
|
|
1943
|
-
"attempts",
|
|
1944
|
-
"lastAttemptAt",
|
|
1945
|
-
"status"
|
|
1946
|
-
]);
|
|
1947
|
-
return Object.keys(result).length > 0 ? result : void 0;
|
|
1527
|
+
function isStrictlyWithin(root, candidate) {
|
|
1528
|
+
return candidate !== resolve(root) && isPathWithin(root, candidate);
|
|
1948
1529
|
}
|
|
1949
|
-
function
|
|
1950
|
-
const
|
|
1951
|
-
|
|
1952
|
-
|
|
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;
|
|
1953
1535
|
}
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
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;
|
|
1957
1552
|
}
|
|
1958
|
-
function
|
|
1959
|
-
|
|
1960
|
-
const
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
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
|
|
1964
1570
|
};
|
|
1965
1571
|
}
|
|
1966
|
-
|
|
1967
|
-
|
|
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);
|
|
1968
1591
|
}
|
|
1969
|
-
function
|
|
1970
|
-
|
|
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
|
+
}
|
|
1971
1606
|
}
|
|
1972
|
-
|
|
1973
|
-
|
|
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)));
|
|
1974
1616
|
}
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
const
|
|
1978
|
-
function createRivusModelManagementSocketServer(options) {
|
|
1979
|
-
assertAbsoluteSocketPath(options.socketPath);
|
|
1980
|
-
let server;
|
|
1981
|
-
let socketIdentity;
|
|
1982
|
-
let listening = false;
|
|
1983
|
-
let startPromise;
|
|
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);
|
|
1984
1620
|
return {
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
const current = server;
|
|
1988
|
-
const identity = socketIdentity;
|
|
1989
|
-
server = void 0;
|
|
1990
|
-
socketIdentity = void 0;
|
|
1991
|
-
if (current && listening) await closeServer(current);
|
|
1992
|
-
listening = false;
|
|
1993
|
-
if (identity) await unlinkOwnedSocket(options.socketPath, identity);
|
|
1994
|
-
},
|
|
1995
|
-
listening: () => listening,
|
|
1996
|
-
start: async () => {
|
|
1997
|
-
if (listening) return;
|
|
1998
|
-
if (startPromise) return startPromise;
|
|
1999
|
-
startPromise = startServer(options, (next, identity) => {
|
|
2000
|
-
server = next;
|
|
2001
|
-
socketIdentity = identity;
|
|
2002
|
-
listening = true;
|
|
2003
|
-
});
|
|
2004
|
-
try {
|
|
2005
|
-
await startPromise;
|
|
2006
|
-
} finally {
|
|
2007
|
-
startPromise = void 0;
|
|
2008
|
-
}
|
|
2009
|
-
}
|
|
1621
|
+
...env,
|
|
1622
|
+
PATH: env.PATH ? `${nodeDirectory}${delimiter}${env.PATH}` : nodeDirectory
|
|
2010
1623
|
};
|
|
2011
1624
|
}
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
const lockPath = `${options.socketPath}.lock`;
|
|
2015
|
-
const lock = await acquireStartLock(lockPath);
|
|
2016
|
-
const next = createServer((socket) => handleConnection(socket, options));
|
|
2017
|
-
let bound = false;
|
|
2018
|
-
try {
|
|
2019
|
-
await prepareSocketPath(options.socketPath);
|
|
2020
|
-
await listen(next, options.socketPath);
|
|
2021
|
-
bound = true;
|
|
2022
|
-
await chmod(options.socketPath, 384);
|
|
2023
|
-
onStarted(next, await readSocketIdentity(options.socketPath));
|
|
2024
|
-
} catch (error) {
|
|
2025
|
-
await closeServer(next).catch(() => void 0);
|
|
2026
|
-
if (bound) await unlinkSocketIfPresent(options.socketPath);
|
|
2027
|
-
throw error;
|
|
2028
|
-
} finally {
|
|
2029
|
-
await releaseStartLock(lock, lockPath);
|
|
2030
|
-
}
|
|
1625
|
+
function seconds(ms) {
|
|
1626
|
+
return String(ms / 1e3);
|
|
2031
1627
|
}
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
handleFrame(buffer.slice(0, newline).trim(), socket, options);
|
|
2048
|
-
});
|
|
2049
|
-
socket.on("end", () => {
|
|
2050
|
-
if (handled || buffer.trim() === "") return;
|
|
2051
|
-
handled = true;
|
|
2052
|
-
handleFrame(buffer.trim(), socket, options);
|
|
2053
|
-
});
|
|
2054
|
-
socket.on("error", () => {
|
|
2055
|
-
handled = true;
|
|
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)}`);
|
|
2056
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;
|
|
2057
1648
|
}
|
|
2058
|
-
async function
|
|
2059
|
-
|
|
2060
|
-
|
|
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;
|
|
2061
1654
|
try {
|
|
2062
|
-
|
|
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;
|
|
2063
1704
|
} catch (error) {
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
if (request.operation === "status") response = projectRivusModelCliResponse(await options.handlers.status({
|
|
2070
|
-
...request.requestId ? { requestId: request.requestId } : {},
|
|
2071
|
-
...request.verbose ? { verbose: true } : {}
|
|
2072
|
-
}), request.operation);
|
|
2073
|
-
else response = await handleMutation(request, options);
|
|
2074
|
-
} catch {
|
|
2075
|
-
response = createRivusModelManagementFailure("handler_failed", "the model management request could not be completed");
|
|
2076
|
-
}
|
|
2077
|
-
writeResponse(socket, response);
|
|
2078
|
-
}
|
|
2079
|
-
async function handleMutation(request, options) {
|
|
2080
|
-
if (!request.context || !options.resolveTrustedRun) return createRivusModelManagementFailure("trusted_context_required", "a trusted Run context is required for model changes");
|
|
2081
|
-
let trustedRun;
|
|
2082
|
-
try {
|
|
2083
|
-
trustedRun = await options.resolveTrustedRun.resolve(request.context);
|
|
2084
|
-
} catch {
|
|
2085
|
-
trustedRun = void 0;
|
|
2086
|
-
}
|
|
2087
|
-
if (trustedRun === void 0 || trustedRun === null) return createRivusModelManagementFailure("trusted_context_invalid", "the trusted Run context is invalid or expired");
|
|
2088
|
-
try {
|
|
2089
|
-
return projectRivusModelCliResponse(await options.handlers.handle(toRivusModelManagementSubmission(request), trustedRun), request.operation);
|
|
2090
|
-
} catch {
|
|
2091
|
-
return createRivusModelManagementFailure("handler_failed", "the model management request could not be completed");
|
|
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));
|
|
2092
1710
|
}
|
|
2093
1711
|
}
|
|
2094
|
-
function
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
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
|
+
})));
|
|
2100
1721
|
}
|
|
2101
|
-
|
|
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);
|
|
2102
1739
|
try {
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
if (
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
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);
|
|
2111
1763
|
}
|
|
2112
1764
|
}
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
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
|
+
]
|
|
2118
1782
|
});
|
|
2119
|
-
|
|
1783
|
+
child.stdout.setEncoding("utf8").on("data", onStdout);
|
|
1784
|
+
child.stderr.setEncoding("utf8").on("data", onStderr);
|
|
1785
|
+
return child;
|
|
2120
1786
|
}
|
|
2121
|
-
|
|
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) {
|
|
2122
1792
|
return new Promise((resolve, reject) => {
|
|
2123
|
-
const
|
|
2124
|
-
let
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
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
|
+
}
|
|
2137
1816
|
});
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
let
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
const metadata = await handle.stat();
|
|
2147
|
-
return {
|
|
2148
|
-
handle,
|
|
2149
|
-
identity: {
|
|
2150
|
-
dev: metadata.dev,
|
|
2151
|
-
ino: metadata.ino
|
|
2152
|
-
}
|
|
2153
|
-
};
|
|
2154
|
-
} catch (error) {
|
|
2155
|
-
await handle?.close().catch(() => void 0);
|
|
2156
|
-
if (!isAlreadyExists(error)) throw new Error("model management socket startup is already in progress", { cause: error });
|
|
2157
|
-
const pid = parseLockOwner(await readPersistenceFile(path));
|
|
2158
|
-
if (pid === void 0) throw new Error("model management socket startup lock owner could not be verified; manual recovery is required");
|
|
2159
|
-
if (processIsAlive(pid)) throw new Error("model management socket startup is already in progress");
|
|
2160
|
-
const reclaimed = `${path}.reclaim-${process.pid}-${randomUUID()}`;
|
|
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) => {
|
|
2161
1825
|
try {
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
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;
|
|
2169
1835
|
});
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
await lock.handle.close();
|
|
2176
|
-
try {
|
|
2177
|
-
const current = await stat(path);
|
|
2178
|
-
if (current.dev !== lock.identity.dev || current.ino !== lock.identity.ino) return;
|
|
2179
|
-
await unlink(path);
|
|
2180
|
-
} catch (error) {
|
|
2181
|
-
if (!isMissing(error)) throw error;
|
|
2182
|
-
}
|
|
2183
|
-
}
|
|
2184
|
-
async function unlinkSocketIfPresent(socketPath) {
|
|
2185
|
-
try {
|
|
2186
|
-
if ((await stat(socketPath)).isSocket()) await unlink(socketPath);
|
|
2187
|
-
} catch (error) {
|
|
2188
|
-
if (!isMissing(error)) throw error;
|
|
2189
|
-
}
|
|
2190
|
-
}
|
|
2191
|
-
async function unlinkOwnedSocket(socketPath, identity) {
|
|
2192
|
-
try {
|
|
2193
|
-
const current = await readSocketIdentity(socketPath);
|
|
2194
|
-
if (current.dev !== identity.dev || current.ino !== identity.ino) return;
|
|
2195
|
-
await unlink(socketPath);
|
|
2196
|
-
} catch (error) {
|
|
2197
|
-
if (!isMissing(error)) throw error;
|
|
2198
|
-
}
|
|
2199
|
-
}
|
|
2200
|
-
async function readSocketIdentity(socketPath) {
|
|
2201
|
-
const metadata = await stat(socketPath);
|
|
2202
|
-
return {
|
|
2203
|
-
dev: metadata.dev,
|
|
2204
|
-
ino: metadata.ino
|
|
2205
|
-
};
|
|
2206
|
-
}
|
|
2207
|
-
function listen(server, socketPath) {
|
|
2208
|
-
return new Promise((resolve, reject) => {
|
|
2209
|
-
const onError = (error) => {
|
|
2210
|
-
server.off("listening", onListening);
|
|
2211
|
-
reject(error);
|
|
1836
|
+
signalChild("SIGTERM");
|
|
1837
|
+
escalation = setTimeout(() => {
|
|
1838
|
+
signalChild("SIGKILL");
|
|
1839
|
+
finishTermination?.();
|
|
1840
|
+
}, KILL_GRACE_MS);
|
|
2212
1841
|
};
|
|
2213
|
-
const
|
|
2214
|
-
|
|
2215
|
-
|
|
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);
|
|
2216
1848
|
};
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
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
|
+
});
|
|
2220
1882
|
});
|
|
2221
1883
|
}
|
|
2222
|
-
|
|
1884
|
+
/** Streams the transcriber's stdout and stderr to the caller and resolves with its exit code. */
|
|
1885
|
+
function runRivusAudioPassthroughProcess(request) {
|
|
2223
1886
|
return new Promise((resolve, reject) => {
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
function assertAbsoluteSocketPath(socketPath) {
|
|
2228
|
-
if (!isAbsolute(socketPath)) throw new Error("model socket path must be absolute");
|
|
2229
|
-
}
|
|
2230
|
-
function isMissing(error) {
|
|
2231
|
-
return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
|
|
2232
|
-
}
|
|
2233
|
-
function isAlreadyExists(error) {
|
|
2234
|
-
return typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST";
|
|
2235
|
-
}
|
|
2236
|
-
function processIsAlive(pid) {
|
|
2237
|
-
try {
|
|
2238
|
-
process.kill(pid, 0);
|
|
2239
|
-
return true;
|
|
2240
|
-
} catch (error) {
|
|
2241
|
-
return typeof error === "object" && error !== null && "code" in error && error.code !== "ESRCH";
|
|
2242
|
-
}
|
|
2243
|
-
}
|
|
2244
|
-
function parseLockOwner(value) {
|
|
2245
|
-
const normalized = value?.trim();
|
|
2246
|
-
if (!normalized || !/^\d+$/.test(normalized)) return;
|
|
2247
|
-
const pid = Number(normalized);
|
|
2248
|
-
return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
|
|
2249
|
-
}
|
|
2250
|
-
//#endregion
|
|
2251
|
-
//#region src/platform/project/setup/release-descriptor.ts
|
|
2252
|
-
const RIVUS_RELEASE_DESCRIPTOR = Object.freeze({
|
|
2253
|
-
version: "0.21.2",
|
|
2254
|
-
dependencies: Object.freeze({
|
|
2255
|
-
"@earendil-works/pi-coding-agent": "0.84.4",
|
|
2256
|
-
"@larksuiteoapi/node-sdk": "1.74.0",
|
|
2257
|
-
effect: "^4.0.0"
|
|
2258
|
-
})
|
|
2259
|
-
});
|
|
2260
|
-
//#endregion
|
|
2261
|
-
//#region src/platform/runtime-pool/runtime-cache.ts
|
|
2262
|
-
function createRuntimeCache() {
|
|
2263
|
-
const entries = /* @__PURE__ */ new Map();
|
|
2264
|
-
const serial = Semaphore.makeUnsafe(1);
|
|
2265
|
-
const reserve = (key) => serial.withPermits(1)(Effect.gen(function* () {
|
|
2266
|
-
const current = entries.get(key);
|
|
2267
|
-
if (current) return {
|
|
2268
|
-
created: false,
|
|
2269
|
-
entry: current
|
|
2270
|
-
};
|
|
2271
|
-
const entry = {
|
|
2272
|
-
deferred: yield* Deferred.make(),
|
|
2273
|
-
initializationStarted: false,
|
|
2274
|
-
key
|
|
2275
|
-
};
|
|
2276
|
-
entries.set(key, entry);
|
|
2277
|
-
return {
|
|
2278
|
-
created: true,
|
|
2279
|
-
entry
|
|
2280
|
-
};
|
|
2281
|
-
}));
|
|
2282
|
-
const start = (entry, create) => Effect.uninterruptible(Effect.gen(function* () {
|
|
2283
|
-
if (!(yield* serial.withPermits(1)(Effect.sync(() => {
|
|
2284
|
-
if (entry.initializationStarted) return false;
|
|
2285
|
-
entry.initializationStarted = true;
|
|
2286
|
-
return true;
|
|
2287
|
-
})))) return;
|
|
2288
|
-
const initialization = create().pipe(Effect.tapError(() => serial.withPermits(1)(Effect.sync(() => {
|
|
2289
|
-
if (entries.get(entry.key) === entry) entries.delete(entry.key);
|
|
2290
|
-
}))), Effect.exit, Effect.flatMap((exit) => Deferred.done(entry.deferred, exit)), Effect.asVoid);
|
|
2291
|
-
yield* Effect.forkDetach(initialization, { uninterruptible: "inherit" });
|
|
2292
|
-
}));
|
|
2293
|
-
const getOrCreate = (key, create) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
|
|
2294
|
-
const selected = yield* reserve(key);
|
|
2295
|
-
yield* start(selected.entry, create);
|
|
2296
|
-
return {
|
|
2297
|
-
entry: selected.entry,
|
|
2298
|
-
runtime: yield* restore(Deferred.await(selected.entry.deferred))
|
|
1887
|
+
const child = spawnAudioProcess(request, (text) => request.stdout.write(text), (text) => request.stderr.write(text));
|
|
1888
|
+
const onAbort = () => {
|
|
1889
|
+
child.kill("SIGTERM");
|
|
2299
1890
|
};
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
if (!entry) return;
|
|
2310
|
-
return {
|
|
2311
|
-
entry,
|
|
2312
|
-
runtime: yield* Deferred.await(entry.deferred)
|
|
2313
|
-
};
|
|
2314
|
-
}),
|
|
2315
|
-
getOrCreate,
|
|
2316
|
-
isCurrent: (key, entry) => serial.withPermits(1)(Effect.sync(() => entries.get(key) === entry)),
|
|
2317
|
-
reserve,
|
|
2318
|
-
size: () => serial.withPermits(1)(Effect.sync(() => entries.size)),
|
|
2319
|
-
start
|
|
2320
|
-
};
|
|
2321
|
-
}
|
|
2322
|
-
function disposeRuntimeCacheEntries(options) {
|
|
2323
|
-
const disposal = Effect.gen(function* () {
|
|
2324
|
-
const completions = yield* Effect.forEach(options.entries, (entry) => Effect.gen(function* () {
|
|
2325
|
-
const completion = yield* Deferred.make();
|
|
2326
|
-
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" });
|
|
2327
|
-
return completion;
|
|
2328
|
-
}), { concurrency: "unbounded" });
|
|
2329
|
-
const failures = (yield* Effect.forEach(completions, Deferred.await, { concurrency: "unbounded" })).filter(Exit.isFailure).map(({ cause }) => Cause.squash(cause));
|
|
2330
|
-
if (failures.length > 0) return yield* Effect.fail(new AggregateError(failures, options.failureMessage));
|
|
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
|
+
});
|
|
2331
1900
|
});
|
|
2332
|
-
const timeout = options.timeout;
|
|
2333
|
-
return timeout ? disposal.pipe(Effect.timeoutOrElse({
|
|
2334
|
-
duration: timeout.milliseconds,
|
|
2335
|
-
orElse: () => Effect.fail(timeout.onTimeout())
|
|
2336
|
-
})) : disposal;
|
|
2337
|
-
}
|
|
2338
|
-
function invokeRuntimeControl(runtime, control) {
|
|
2339
|
-
return runtime.pipe(Effect.flatMap((selected) => selected ? control(selected) ?? Effect.succeed(false) : Effect.succeed(false)));
|
|
2340
1901
|
}
|
|
2341
1902
|
//#endregion
|
|
2342
1903
|
//#region src/bootstrap/daemon/rivus-home-deployment-env.ts
|
|
@@ -2351,5 +1912,5 @@ function withoutRivusHomeDeployment(env) {
|
|
|
2351
1912
|
return rest;
|
|
2352
1913
|
}
|
|
2353
1914
|
//#endregion
|
|
2354
|
-
export {
|
|
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 };
|
|
2355
1916
|
|