@rivus/gateway 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,13 @@
1
+ import { Cause, Deferred, Effect, Exit, Option, Result, Schema, SchemaIssue, Semaphore } from "effect";
1
2
  import { isRivusRuntimeToolId } from "@rivus/runtime";
2
- import { dirname, isAbsolute } from "node:path";
3
+ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve } from "node:path";
3
4
  import { fileURLToPath } from "node:url";
4
- import { Cause, Deferred, Effect, Exit, Semaphore } from "effect";
5
- import { chmod, mkdir, open, readFile, rename, stat, unlink } from "node:fs/promises";
6
- import { randomUUID } from "node:crypto";
7
- import { readPersistenceFile } from "@rivus/platform/persistence";
5
+ import { access, chmod, constants, cp, mkdir, open, readFile, readdir, rename, rm, rmdir, stat, unlink, writeFile } from "node:fs/promises";
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import { isPathWithin } from "@rivus/platform/filesystem";
8
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
9
+ import { readPersistenceFile, writeAtomicTextFile } from "@rivus/platform/persistence";
10
+ import { spawn } from "node:child_process";
8
11
  import { createConnection, createServer } from "node:net";
9
12
  //#region src/platform/values/deep-freeze.ts
10
13
  function deepFreeze(value) {
@@ -15,6 +18,198 @@ function deepFreeze(value) {
15
18
  return value;
16
19
  }
17
20
  //#endregion
21
+ //#region src/core/application/background-session/authority/background-session-authority.ts
22
+ const BACKGROUND_SESSION_START_TOOL_ID = "background.start";
23
+ const BACKGROUND_SESSION_TOOL_PLUGIN_ID = "rivus-core";
24
+ const BACKGROUND_SESSION_TOOL_VERSION = "1.0.0";
25
+ const BACKGROUND_SESSION_TOOL_DIGESTS = {
26
+ "background.list": "sha256:c935847595e406d55ca889875b38db66bb1d4d7a34d7b0fb2b85aecf9478c149",
27
+ "background.send": "sha256:b7ed492e45c794dc286f7f66aca8d046082d11dfdc8787eaf5604765b68a7735",
28
+ "background.start": "sha256:773690e47f6eef1f1b289216e94cf98e548382d6cffb7b2f034c3ed0635dfcbb",
29
+ "background.status": "sha256:6aaa328d6cd97d8755a63abbe97286f1061fd2f238f68b1e576ed9a1d2b7e6b1",
30
+ "background.stop": "sha256:aa0bfdf0c9394058bfcbd8662e7bedd59055f9ddad51c2a1bb61666bd67ebfcb",
31
+ "background.wait": "sha256:4a0dc80e933ad3c99b6d58421ac9ef733157e39e0ac9b6ad87ac6e65ceaedaab"
32
+ };
33
+ function createBackgroundSessionToolContracts() {
34
+ return [
35
+ Object.freeze({
36
+ description: "Start a background agent session. Use when the request must wait for external changes, observe over time, or continue working after the foreground run ends. Returns a stable session id immediately; the foreground response can finish here. The detached session continues with the granted Skills, CLI, Tools, Project Space, and Memory of this agent.",
37
+ digest: BACKGROUND_SESSION_TOOL_DIGESTS["background.start"],
38
+ id: "background.start",
39
+ idempotency: "supported",
40
+ inputSchema: Object.freeze({
41
+ additionalProperties: false,
42
+ properties: Object.freeze({
43
+ displayName: {
44
+ type: "string",
45
+ maxLength: 200
46
+ },
47
+ prompt: {
48
+ type: "string",
49
+ minLength: 1,
50
+ maxLength: 2e4
51
+ }
52
+ }),
53
+ required: ["prompt"],
54
+ type: "object"
55
+ }),
56
+ pluginId: BACKGROUND_SESSION_TOOL_PLUGIN_ID,
57
+ risk: "mutate",
58
+ version: BACKGROUND_SESSION_TOOL_VERSION
59
+ }),
60
+ Object.freeze({
61
+ description: "Pause the current background session durably and end the current step. Call with delayMs to resume after a delay, with until to resume at an absolute ISO time, or with neither to wait for user input. After this call no further tool calls are accepted in this step.",
62
+ digest: BACKGROUND_SESSION_TOOL_DIGESTS["background.wait"],
63
+ id: "background.wait",
64
+ idempotency: "supported",
65
+ inputSchema: Object.freeze({
66
+ additionalProperties: false,
67
+ properties: Object.freeze({
68
+ delayMs: {
69
+ type: "integer",
70
+ minimum: 1e3,
71
+ maximum: 864e5
72
+ },
73
+ reason: {
74
+ type: "string",
75
+ maxLength: 500
76
+ },
77
+ until: {
78
+ type: "string",
79
+ maxLength: 64
80
+ }
81
+ }),
82
+ type: "object"
83
+ }),
84
+ pluginId: BACKGROUND_SESSION_TOOL_PLUGIN_ID,
85
+ risk: "mutate",
86
+ version: BACKGROUND_SESSION_TOOL_VERSION
87
+ }),
88
+ Object.freeze({
89
+ description: "List background sessions owned by this conversation, newest first. Optionally filter by phase and limit the number of results.",
90
+ digest: BACKGROUND_SESSION_TOOL_DIGESTS["background.list"],
91
+ id: "background.list",
92
+ idempotency: "supported",
93
+ inputSchema: Object.freeze({
94
+ additionalProperties: false,
95
+ properties: Object.freeze({
96
+ limit: {
97
+ type: "integer",
98
+ minimum: 1,
99
+ maximum: 50
100
+ },
101
+ phase: {
102
+ enum: [
103
+ "queued",
104
+ "running",
105
+ "waiting",
106
+ "input-required",
107
+ "stopping",
108
+ "stopped",
109
+ "completed",
110
+ "failed",
111
+ "reconciliation-required"
112
+ ],
113
+ type: "string"
114
+ }
115
+ }),
116
+ type: "object"
117
+ }),
118
+ pluginId: BACKGROUND_SESSION_TOOL_PLUGIN_ID,
119
+ risk: "observe",
120
+ version: BACKGROUND_SESSION_TOOL_VERSION
121
+ }),
122
+ Object.freeze({
123
+ description: "Return the current phase, step counts, wake time, and result of one background session owned by this conversation.",
124
+ digest: BACKGROUND_SESSION_TOOL_DIGESTS["background.status"],
125
+ id: "background.status",
126
+ idempotency: "supported",
127
+ inputSchema: Object.freeze({
128
+ additionalProperties: false,
129
+ properties: Object.freeze({ sessionId: {
130
+ type: "string",
131
+ minLength: 1,
132
+ maxLength: 200
133
+ } }),
134
+ required: ["sessionId"],
135
+ type: "object"
136
+ }),
137
+ pluginId: BACKGROUND_SESSION_TOOL_PLUGIN_ID,
138
+ risk: "observe",
139
+ version: BACKGROUND_SESSION_TOOL_VERSION
140
+ }),
141
+ Object.freeze({
142
+ description: "Send new user instruction text to a background session owned by this conversation and wake it. The input is delivered exactly once in the next step.",
143
+ digest: BACKGROUND_SESSION_TOOL_DIGESTS["background.send"],
144
+ id: "background.send",
145
+ idempotency: "supported",
146
+ inputSchema: Object.freeze({
147
+ additionalProperties: false,
148
+ properties: Object.freeze({
149
+ message: {
150
+ type: "string",
151
+ minLength: 1,
152
+ maxLength: 2e4
153
+ },
154
+ sessionId: {
155
+ type: "string",
156
+ minLength: 1,
157
+ maxLength: 200
158
+ }
159
+ }),
160
+ required: ["message", "sessionId"],
161
+ type: "object"
162
+ }),
163
+ pluginId: BACKGROUND_SESSION_TOOL_PLUGIN_ID,
164
+ risk: "mutate",
165
+ version: BACKGROUND_SESSION_TOOL_VERSION
166
+ }),
167
+ Object.freeze({
168
+ description: "Stop a background session owned by this conversation. Persists the cancellation, aborts the active step and its owned process, and delivers a terminal notice.",
169
+ digest: BACKGROUND_SESSION_TOOL_DIGESTS["background.stop"],
170
+ id: "background.stop",
171
+ idempotency: "supported",
172
+ inputSchema: Object.freeze({
173
+ additionalProperties: false,
174
+ properties: Object.freeze({
175
+ reason: {
176
+ type: "string",
177
+ maxLength: 500
178
+ },
179
+ sessionId: {
180
+ type: "string",
181
+ minLength: 1,
182
+ maxLength: 200
183
+ }
184
+ }),
185
+ required: ["sessionId"],
186
+ type: "object"
187
+ }),
188
+ pluginId: BACKGROUND_SESSION_TOOL_PLUGIN_ID,
189
+ risk: "mutate",
190
+ version: BACKGROUND_SESSION_TOOL_VERSION
191
+ })
192
+ ];
193
+ }
194
+ function narrowBackgroundSessionDefinition(definition, digest) {
195
+ const childToolIds = definition.toolGrantSet.toolIds.filter((id) => id !== BACKGROUND_SESSION_START_TOOL_ID);
196
+ const toolGrantSet = Object.freeze({
197
+ revision: grantRevision(digest, definition.toolGrantSet.revision, childToolIds),
198
+ toolIds: Object.freeze(childToolIds)
199
+ });
200
+ return Object.freeze({
201
+ ...definition,
202
+ tools: Object.freeze(definition.tools.filter(({ id }) => id !== BACKGROUND_SESSION_START_TOOL_ID)),
203
+ toolGrantSet
204
+ });
205
+ }
206
+ function grantRevision(digest, parentRevision, toolIds) {
207
+ return digest(JSON.stringify({
208
+ parentRevision,
209
+ toolIds: [...toolIds].sort()
210
+ }));
211
+ }
212
+ //#endregion
18
213
  //#region src/core/application/deployment/manifest/deployment-manifest.ts
19
214
  const DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_MS = 3e4;
20
215
  const DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_RENEWAL_INTERVAL_MS = 1e4;
@@ -97,12 +292,14 @@ function parseRivusDeploymentManifest(value) {
97
292
  "pluginId",
98
293
  "profileId",
99
294
  "projectSpaceId",
295
+ "runtime",
100
296
  "runtimeTools",
101
297
  "skills",
102
298
  "tools"
103
299
  ], `manifest.agents[${index}]`, [
104
300
  "memory",
105
301
  "projectSpaceId",
302
+ "runtime",
106
303
  "runtimeTools"
107
304
  ]);
108
305
  const memory = agent.memory === void 0 ? void 0 : record(agent.memory, `manifest.agents[${index}].memory`);
@@ -123,6 +320,7 @@ function parseRivusDeploymentManifest(value) {
123
320
  pluginId: string(agent.pluginId, `manifest.agents[${index}].pluginId`),
124
321
  profileId: string(agent.profileId, `manifest.agents[${index}].profileId`),
125
322
  ...agent.projectSpaceId === void 0 ? {} : { projectSpaceId: string(agent.projectSpaceId, `manifest.agents[${index}].projectSpaceId`) },
323
+ ...agent.runtime === void 0 ? {} : { runtime: parseAgentRuntime(agent.runtime, `manifest.agents[${index}].runtime`) },
126
324
  ...runtimeTools ? { runtimeTools: Object.freeze({ allow: Object.freeze(uniqueRuntimeTools(array(runtimeTools.allow, `manifest.agents[${index}].runtimeTools.allow`).map((item, itemIndex) => runtimeToolId(item, `manifest.agents[${index}].runtimeTools.allow[${itemIndex}]`)), `manifest.agents[${index}].runtimeTools.allow`)) }) } : {},
127
325
  skills: Object.freeze({ allow: Object.freeze(array(skills.allow, `manifest.agents[${index}].skills.allow`).map((item, itemIndex) => string(item, `manifest.agents[${index}].skills.allow[${itemIndex}]`))) }),
128
326
  tools: Object.freeze({ allow: Object.freeze(array(tools.allow, `manifest.agents[${index}].tools.allow`).map((item, itemIndex) => string(item, `manifest.agents[${index}].tools.allow[${itemIndex}]`))) })
@@ -132,6 +330,7 @@ function parseRivusDeploymentManifest(value) {
132
330
  const endpoint = record(entry, `manifest.endpoints[${index}]`);
133
331
  exactKeys(endpoint, [
134
332
  "agentId",
333
+ "allowedActors",
135
334
  "baseUrl",
136
335
  "cardStreamLeaseMs",
137
336
  "credentialRef",
@@ -144,6 +343,7 @@ function parseRivusDeploymentManifest(value) {
144
343
  "sessionNamespace",
145
344
  "streamMinIntervalMs"
146
345
  ], `manifest.endpoints[${index}]`, [
346
+ "allowedActors",
147
347
  "cardStreamLeaseMs",
148
348
  "experimental",
149
349
  "progressDisplay"
@@ -152,6 +352,7 @@ function parseRivusDeploymentManifest(value) {
152
352
  if (experimental) exactKeys(experimental, ["cotMessages"], `manifest.endpoints[${index}].experimental`);
153
353
  return Object.freeze({
154
354
  agentId: string(endpoint.agentId, `manifest.endpoints[${index}].agentId`),
355
+ ...endpoint.allowedActors === void 0 ? {} : { allowedActors: Object.freeze(parseAllowedActors(endpoint.allowedActors, `manifest.endpoints[${index}].allowedActors`)) },
155
356
  baseUrl: string(endpoint.baseUrl, `manifest.endpoints[${index}].baseUrl`),
156
357
  cardStreamLeaseMs: endpoint.cardStreamLeaseMs === void 0 ? DEFAULT_MANIFEST_CARD_STREAM_LEASE_MS : positiveInteger(endpoint.cardStreamLeaseMs, `manifest.endpoints[${index}].cardStreamLeaseMs`),
157
358
  credentialRef: string(endpoint.credentialRef, `manifest.endpoints[${index}].credentialRef`),
@@ -242,6 +443,12 @@ function validateRivusDeploymentManifest(manifest) {
242
443
  agentIds.add(agent.agentId);
243
444
  if (!pluginIds.has(agent.pluginId)) throw new Error(`agent ${agent.agentId} references undeclared plugin: ${agent.pluginId}`);
244
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
+ }
245
452
  agentById.set(agent.agentId, agent);
246
453
  }
247
454
  const endpointIds = /* @__PURE__ */ new Set();
@@ -249,10 +456,12 @@ function validateRivusDeploymentManifest(manifest) {
249
456
  for (const endpoint of manifest.endpoints) {
250
457
  if (endpointIds.has(endpoint.id)) throw new Error(`duplicate endpoint binding: ${endpoint.id}`);
251
458
  endpointIds.add(endpoint.id);
459
+ if (endpoint.allowedActors !== void 0) parseAllowedActors(endpoint.allowedActors, `endpoint ${endpoint.id} allowedActors`);
252
460
  if (sessionNamespaces.has(endpoint.sessionNamespace)) throw new Error(`duplicate endpoint session namespace: ${endpoint.sessionNamespace}`);
253
461
  sessionNamespaces.add(endpoint.sessionNamespace);
254
462
  const agent = agentById.get(endpoint.agentId);
255
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}`);
256
465
  if (!agent.endpointIds.includes(endpoint.id)) throw new Error(`endpoint ${endpoint.id} is not declared by agent ${endpoint.agentId}`);
257
466
  }
258
467
  for (const agent of manifest.agents) for (const endpointId of agent.endpointIds) {
@@ -277,6 +486,46 @@ function validateRivusDeploymentManifest(manifest) {
277
486
  if (!defaultEndpoint.enabled) throw new Error("default endpoint must be enabled");
278
487
  if (manifest.backgroundSessions) validateBackgroundSessions(manifest.backgroundSessions);
279
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
+ }
280
529
  function validateBackgroundSessions(config) {
281
530
  if (config.required && !config.enabled) throw new Error("backgroundSessions.required requires backgroundSessions.enabled");
282
531
  if (config.leaseRenewalIntervalMs >= config.leaseMs) throw new Error("backgroundSessions.leaseRenewalIntervalMs must be shorter than leaseMs");
@@ -385,11 +634,11 @@ function resolveFeishuEndpointCredentials(credentialRef, env) {
385
634
  const prefix = credentialRef.slice(4);
386
635
  if (!/^[A-Z][A-Z0-9_]*$/.test(prefix)) throw new FeishuEndpointCredentialError(`Invalid environment prefix in credentialRef: ${credentialRef}`);
387
636
  return Object.freeze({
388
- appId: required$1(env, `${prefix}_APP_ID`),
389
- appSecret: required$1(env, `${prefix}_APP_SECRET`)
637
+ appId: required(env, `${prefix}_APP_ID`),
638
+ appSecret: required(env, `${prefix}_APP_SECRET`)
390
639
  });
391
640
  }
392
- function required$1(env, variable) {
641
+ function required(env, variable) {
393
642
  const value = env[variable]?.trim();
394
643
  if (!value) throw new FeishuEndpointCredentialError(`${variable} is required`);
395
644
  return value;
@@ -451,96 +700,194 @@ function unescapeDoubleQuotedValue(value) {
451
700
  });
452
701
  }
453
702
  //#endregion
454
- //#region src/platform/home/config/runtime/rivus-daemon-config.ts
455
- var RivusDaemonConfigError = class {
456
- variable;
457
- message;
458
- _tag = "RivusDaemonConfigError";
459
- constructor(variable, message) {
460
- this.variable = variable;
461
- this.message = message;
703
+ //#region src/platform/home/config/model-management/rivus-model-management-config-migration.ts
704
+ const RIVUS_MODEL_MANAGEMENT_ENABLED_ENV = "RIVUS_MODEL_MANAGEMENT_ENABLED";
705
+ const RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID_ENV = "RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID";
706
+ const RIVUS_MODEL_MANAGEMENT_TENANT_KEY_ENV = "RIVUS_MODEL_MANAGEMENT_TENANT_KEY";
707
+ const RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL_ENV = "RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL";
708
+ var RivusModelManagementConfigError = class extends Error {
709
+ code;
710
+ name = "RivusModelManagementConfigError";
711
+ constructor(code, message) {
712
+ super(message);
713
+ this.code = code;
462
714
  }
463
715
  };
464
- const DEFAULT_AGENT_ID = "main";
465
- const DEFAULT_CARD_STREAM_LEASE_MS = 51e4;
466
- const DEFAULT_FEISHU_BASE_URL = "https://open.feishu.cn";
467
- const DEFAULT_STREAM_MIN_INTERVAL_MS = 200;
468
- const THINKING_LEVELS = /* @__PURE__ */ new Set([
469
- "off",
470
- "minimal",
471
- "low",
472
- "medium",
473
- "high",
474
- "xhigh"
475
- ]);
476
- function loadRivusDaemonConfig(env, options = {}) {
477
- return Effect.gen(function* () {
478
- const appId = yield* required(env, "FEISHU_APP_ID");
479
- const appSecret = yield* required(env, "FEISHU_APP_SECRET");
480
- const streamMinIntervalMs = yield* optionalPositiveInteger(env.FEISHU_STREAM_MIN_INTERVAL_MS, "FEISHU_STREAM_MIN_INTERVAL_MS", DEFAULT_STREAM_MIN_INTERVAL_MS);
481
- const cardStreamLeaseMs = yield* optionalPositiveInteger(env.FEISHU_CARD_STREAM_LEASE_MS, "FEISHU_CARD_STREAM_LEASE_MS", DEFAULT_CARD_STREAM_LEASE_MS);
482
- const thinkingLevel = yield* optionalThinkingLevel(env.PI_THINKING_LEVEL);
483
- const apiKey = yield* optionalPiApiKey(env, options.readTextFile ?? readUtf8File);
484
- const baseUrl = optional(env.PI_BASE_URL);
485
- const model = optional(env.PI_MODEL);
486
- return {
487
- agentId: optional(env.RIVUS_AGENT_ID) ?? DEFAULT_AGENT_ID,
488
- feishu: {
489
- appId,
490
- appSecret,
491
- baseUrl: optional(env.FEISHU_BASE_URL) ?? DEFAULT_FEISHU_BASE_URL,
492
- cardStreamLeaseMs,
493
- streamMinIntervalMs
494
- },
495
- pi: {
496
- ...apiKey ? { apiKey } : {},
497
- ...baseUrl ? { baseUrl } : {},
498
- ...model ? { model } : {},
499
- ...thinkingLevel ? { thinkingLevel } : {}
500
- }
501
- };
716
+ /** Parse the Home capability flags without accepting truthy arbitrary strings. */
717
+ function parseRivusModelManagementHomeConfig(env) {
718
+ const enabled = parseRivusModelManagementEnabled(env[RIVUS_MODEL_MANAGEMENT_ENABLED_ENV]);
719
+ const requireApproval = parseStrictBoolean(env[RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL_ENV], RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL_ENV, false);
720
+ const ownerOpenId = optional(env[RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID_ENV]);
721
+ const tenantKey = optional(env[RIVUS_MODEL_MANAGEMENT_TENANT_KEY_ENV]);
722
+ if (enabled && !ownerOpenId) throw new RivusModelManagementConfigError("owner_missing", `${RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID_ENV} is required when model management is enabled`);
723
+ if (enabled && !tenantKey) throw new RivusModelManagementConfigError("tenant_missing", `${RIVUS_MODEL_MANAGEMENT_TENANT_KEY_ENV} is required when model management is enabled`);
724
+ return Object.freeze({
725
+ enabled,
726
+ ...ownerOpenId ? { ownerOpenId } : {},
727
+ requireApproval,
728
+ ...tenantKey ? { tenantKey } : {}
502
729
  });
503
730
  }
504
- function optional(value) {
505
- const trimmed = value?.trim();
506
- return trimmed ? trimmed : void 0;
507
- }
508
- function readUtf8File(path) {
509
- return readFile(path, "utf8");
510
- }
511
- function optionalPiApiKey(env, readTextFile) {
512
- const inlineApiKey = optional(env.PI_API_KEY);
513
- const apiKeyFile = optional(env.PI_API_KEY_FILE);
514
- if (inlineApiKey && apiKeyFile) return Effect.fail(new RivusDaemonConfigError("PI_API_KEY", "PI_API_KEY and PI_API_KEY_FILE cannot both be set"));
515
- if (inlineApiKey) return Effect.succeed(inlineApiKey);
516
- if (!apiKeyFile) return Effect.succeed(void 0);
517
- return Effect.tryPromise({
518
- try: async () => readTextFile(apiKeyFile),
519
- catch: (error) => new RivusDaemonConfigError("PI_API_KEY_FILE", `PI_API_KEY_FILE could not be read: ${formatConfigError(error)}`)
520
- }).pipe(Effect.flatMap((contents) => {
521
- const apiKey = optional(contents);
522
- return apiKey ? Effect.succeed(apiKey) : Effect.fail(new RivusDaemonConfigError("PI_API_KEY_FILE", "PI_API_KEY_FILE must not be empty"));
523
- }));
731
+ function parseRivusModelManagementEnabled(value) {
732
+ return parseStrictBoolean(value, RIVUS_MODEL_MANAGEMENT_ENABLED_ENV, false);
524
733
  }
525
- function formatConfigError(error) {
526
- return error instanceof Error ? error.message : String(error);
734
+ function parseStrictBoolean(value, variable, defaultValue) {
735
+ if (value === void 0) return defaultValue;
736
+ const normalized = value.trim();
737
+ if (normalized === "true") return true;
738
+ if (normalized === "false") return false;
739
+ throw new RivusModelManagementConfigError("invalid_enabled", `${variable} must be true or false`);
527
740
  }
528
- function optionalPositiveInteger(value, variable, fallback) {
529
- const normalized = optional(value);
530
- if (!normalized) return Effect.succeed(fallback);
531
- if (/^[1-9]\d*$/.test(normalized)) return Effect.succeed(Number(normalized));
532
- return Effect.fail(new RivusDaemonConfigError(variable, `${variable} must be a positive integer`));
741
+ /**
742
+ * Migrate only the legacy model selection at the explicit enable/disable
743
+ * boundary. The helper does not read or write managed model state.
744
+ */
745
+ async function migrateRivusModelManagementConfig(input) {
746
+ if (typeof input.managementEnabled !== "boolean") throw new RivusModelManagementConfigError("invalid_enabled", "model management enabled state must be boolean");
747
+ if (input.managementEnabled) return enableModelManagement(input);
748
+ return disableModelManagement(input, parseModelReference(input.knownGoodProvider, input.knownGoodModel));
749
+ }
750
+ async function enableModelManagement(input) {
751
+ if (hasAmbientModelOverride(input.env)) return {
752
+ initialModel: parseConfiguredModel(input.env.PI_MODEL),
753
+ source: "ambient",
754
+ status: "enabled"
755
+ };
756
+ return {
757
+ initialModel: parseConfiguredModel((await loadEnvFile(requireEnvFilePath(input.envFilePath), input.env)).PI_MODEL),
758
+ source: "env-file",
759
+ status: "enabled"
760
+ };
533
761
  }
534
- function required(env, variable) {
535
- const value = optional(env[variable]);
536
- if (value) return Effect.succeed(value);
537
- return Effect.fail(new RivusDaemonConfigError(variable, `${variable} is required`));
762
+ async function disableModelManagement(input, knownGood) {
763
+ const envFilePath = requireEnvFilePath(input.envFilePath);
764
+ if (hasAmbientModelOverride(input.env)) throw new RivusModelManagementConfigError("ambient_model_override", "ambient PI_MODEL overrides the original env source and prevents verified model readback");
765
+ const original = await readWritableEnvFile(envFilePath);
766
+ const existingModel = parseOptionalConfiguredModel((await loadEnvFile(envFilePath, input.env)).PI_MODEL);
767
+ if (existingModel && sameModel(existingModel, knownGood)) return {
768
+ restoredModel: knownGood,
769
+ source: "env-file",
770
+ status: "unchanged"
771
+ };
772
+ const next = replacePiModel(original, knownGood);
773
+ try {
774
+ await input.writeAtomicTextFile(envFilePath, next, { durable: true });
775
+ } catch {
776
+ throw new RivusModelManagementConfigError("env_source_write_failed", "the original env source write did not complete with a known durable result");
777
+ }
778
+ let readBack;
779
+ try {
780
+ readBack = parseConfiguredModel((await loadMergedLocalEnvFile(envFilePath, input.env)).PI_MODEL);
781
+ } catch {
782
+ throw new RivusModelManagementConfigError("readback_mismatch", "the original env source could not be verified after restoring PI_MODEL");
783
+ }
784
+ 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");
785
+ return {
786
+ restoredModel: knownGood,
787
+ source: "env-file",
788
+ status: "exported"
789
+ };
538
790
  }
539
- function optionalThinkingLevel(value) {
791
+ function parseModelReference(provider, model) {
792
+ if (!isModelPart(provider) || !isModelPart(model)) throw new RivusModelManagementConfigError("invalid_model", "known-good model provider and id are invalid");
793
+ return Object.freeze({
794
+ model,
795
+ provider
796
+ });
797
+ }
798
+ function parseConfiguredModel(value) {
799
+ const configured = optional(value);
800
+ if (!configured) throw new RivusModelManagementConfigError("model_missing", "PI_MODEL is missing from the effective legacy config");
801
+ const separator = configured.indexOf("/");
802
+ if (separator <= 0 || separator === configured.length - 1 || configured.indexOf("/", separator + 1) !== -1) throw new RivusModelManagementConfigError("invalid_model", "PI_MODEL must use provider/model form");
803
+ return parseModelReference(configured.slice(0, separator), configured.slice(separator + 1));
804
+ }
805
+ function parseOptionalConfiguredModel(value) {
806
+ if (!optional(value)) return;
807
+ try {
808
+ return parseConfiguredModel(value);
809
+ } catch {
810
+ return;
811
+ }
812
+ }
813
+ function sameModel(left, right) {
814
+ return left.provider === right.provider && left.model === right.model;
815
+ }
816
+ async function loadEnvFile(envFilePath, env) {
817
+ try {
818
+ return await loadMergedLocalEnvFile(envFilePath, env);
819
+ } catch {
820
+ throw new RivusModelManagementConfigError("env_source_unreadable", "the original env source could not be loaded");
821
+ }
822
+ }
823
+ async function readWritableEnvFile(envFilePath) {
824
+ try {
825
+ const contents = await readFile(envFilePath, "utf8");
826
+ if (((await stat(envFilePath)).mode & 146) === 0) throw new RivusModelManagementConfigError("env_source_unwritable", "the original env source is not writable");
827
+ await access(envFilePath, constants.W_OK);
828
+ return contents;
829
+ } catch (error) {
830
+ if (error instanceof RivusModelManagementConfigError) throw error;
831
+ if (isPermissionError(error)) throw new RivusModelManagementConfigError("env_source_unwritable", "the original env source is not writable");
832
+ throw new RivusModelManagementConfigError("env_source_unreadable", "the original env source is unavailable");
833
+ }
834
+ }
835
+ function replacePiModel(contents, model) {
836
+ const modelValue = `${model.provider}/${model.model}`;
837
+ const parts = contents.split(/(\r\n|\n|\r)/);
838
+ let replaced = false;
839
+ for (let index = 0; index < parts.length; index += 2) {
840
+ const line = parts[index];
841
+ if (line === void 0) continue;
842
+ const match = line.match(/^(\s*(?:export\s+)?PI_MODEL\s*=\s*)(.*)$/);
843
+ if (!match) continue;
844
+ const inlineComment = match[2].match(/(\s+#.*)$/)?.[1] ?? "";
845
+ parts[index] = `${match[1]}${modelValue}${inlineComment}`;
846
+ replaced = true;
847
+ }
848
+ if (replaced) return parts.join("");
849
+ const newline = contents.includes("\r\n") ? "\r\n" : contents.includes("\n") ? "\n" : "\n";
850
+ if (!contents) return `PI_MODEL=${modelValue}${newline}`;
851
+ return /(?:\r\n|\n|\r)$/.test(contents) ? `${contents}PI_MODEL=${modelValue}${newline}` : `${contents}${newline}PI_MODEL=${modelValue}`;
852
+ }
853
+ function requireEnvFilePath(value) {
540
854
  const normalized = optional(value);
541
- if (!normalized) return Effect.succeed(void 0);
542
- if (THINKING_LEVELS.has(normalized)) return Effect.succeed(normalized);
543
- return Effect.fail(new RivusDaemonConfigError("PI_THINKING_LEVEL", "PI_THINKING_LEVEL must be one of off, minimal, low, medium, high, xhigh"));
855
+ if (!normalized) throw new RivusModelManagementConfigError("env_source_missing", "an explicit writable original env source is required for model management migration");
856
+ return normalized;
857
+ }
858
+ function hasAmbientModelOverride(env) {
859
+ return Object.prototype.hasOwnProperty.call(env, "PI_MODEL") && env.PI_MODEL !== void 0;
860
+ }
861
+ function isModelPart(value) {
862
+ return value.trim() === value && value.length > 0 && !/[/\s]/.test(value);
863
+ }
864
+ function optional(value) {
865
+ return value?.trim() || void 0;
866
+ }
867
+ function isPermissionError(error) {
868
+ return typeof error === "object" && error !== null && "code" in error && (error.code === "EACCES" || error.code === "EPERM" || error.code === "EROFS");
869
+ }
870
+ //#endregion
871
+ //#region src/platform/home/config/runtime/acp-runtime-environment.ts
872
+ async function resolveAcpRuntimeEnvironment(runtime, environment) {
873
+ const env = {};
874
+ for (const [name, reference] of Object.entries(runtime.env ?? {})) {
875
+ const variable = reference.slice(4);
876
+ const value = environment[variable];
877
+ if (value === void 0) throw new Error(`runtime.env.${name} references missing environment variable ${variable}`);
878
+ env[name] = value;
879
+ }
880
+ 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));
881
+ for (const candidate of candidates) try {
882
+ if ((await stat(candidate)).isFile()) {
883
+ await access(candidate, constants.X_OK);
884
+ return {
885
+ command: isAbsolute(candidate) ? candidate : join(process.cwd(), candidate),
886
+ env
887
+ };
888
+ }
889
+ } catch {}
890
+ throw new Error("runtime.command must resolve to an executable file");
544
891
  }
545
892
  //#endregion
546
893
  //#region src/adapters/deployment/manifest/node-rivus-deployment-manifest.ts
@@ -576,6 +923,526 @@ const gatewayTemplateDirectory = fileURLToPath(new URL("templates/", packageRoot
576
923
  const gatewaySkillsDirectory = fileURLToPath(new URL("skills/", packageRootUrl));
577
924
  const gatewayAudioTranscriberAssetDirectory = fileURLToPath(new URL("assets/audio-transcriber/", packageRootUrl));
578
925
  //#endregion
926
+ //#region src/adapters/audio/managed/rivus-audio-install-lock.ts
927
+ var RivusAudioInstallInProgressError = class extends Error {
928
+ constructor() {
929
+ super("another audio transcriber installation is in progress");
930
+ this.name = "RivusAudioInstallInProgressError";
931
+ }
932
+ };
933
+ const lockOwnerSchema = Schema.fromJsonString(Schema.Struct({
934
+ pid: Schema.Int,
935
+ startedAt: Schema.Number,
936
+ token: Schema.NonEmptyString
937
+ }));
938
+ /**
939
+ * Takes the installation lock at `path`: a directory holding one owner record named by the owner's token. The record
940
+ * is written into a private draft directory that is then renamed onto `path`, which succeeds only while `path` is
941
+ * absent or empty, so a reader never observes a partially written lock. A lock whose pid is dead, whose record is
942
+ * unreadable, or which is older than `maxAgeMs` is reclaimed by removing that record by name and then `path` only
943
+ * while it is empty, so a reclaim based on an outdated reading never removes another installer's live lock.
944
+ */
945
+ async function acquireRivusAudioInstallLock(path, options) {
946
+ const now = options.now ?? Date.now;
947
+ const isProcessAlive = options.isProcessAlive ?? isLiveProcess;
948
+ const owner = {
949
+ pid: process.pid,
950
+ startedAt: now(),
951
+ token: randomUUID()
952
+ };
953
+ const draft = `${path}.${owner.token}.draft`;
954
+ await mkdir(draft, { mode: 448 });
955
+ try {
956
+ await writeFile(join(draft, owner.token), `${JSON.stringify(owner)}\n`, {
957
+ flag: "wx",
958
+ mode: 384
959
+ });
960
+ for (let attempt = 0; attempt < 3; attempt += 1) {
961
+ if (await tryPublish(draft, path)) return { release: () => removeRecords(path, [owner.token]) };
962
+ const records = await readLockRecords(path);
963
+ if (records.some(({ owner: held }) => held !== void 0 && held.pid !== process.pid && isProcessAlive(held.pid) && now() - held.startedAt < options.maxAgeMs)) throw new RivusAudioInstallInProgressError();
964
+ await removeRecords(path, records.map(({ name }) => name));
965
+ }
966
+ } finally {
967
+ await rm(draft, {
968
+ force: true,
969
+ recursive: true
970
+ }).catch(() => void 0);
971
+ }
972
+ throw new RivusAudioInstallInProgressError();
973
+ }
974
+ async function tryPublish(draft, path) {
975
+ try {
976
+ await rename(draft, path);
977
+ return true;
978
+ } catch (error) {
979
+ if (hasErrorCode(error, "EEXIST") || hasErrorCode(error, "ENOTEMPTY")) return false;
980
+ throw error;
981
+ }
982
+ }
983
+ async function readLockRecords(path) {
984
+ const names = await readdir(path).catch((error) => {
985
+ if (hasErrorCode(error, "ENOENT")) return [];
986
+ throw error;
987
+ });
988
+ return Promise.all(names.map(async (name) => {
989
+ const text = await readPersistenceFile(join(path, name));
990
+ return {
991
+ name,
992
+ owner: text === void 0 ? void 0 : Option.getOrUndefined(Schema.decodeUnknownOption(lockOwnerSchema)(text))
993
+ };
994
+ }));
995
+ }
996
+ /**
997
+ * Removes the named owner records and then the lock directory only if nothing else is in it, so a record that another
998
+ * installer published meanwhile keeps the lock held.
999
+ */
1000
+ async function removeRecords(path, names) {
1001
+ await Promise.all(names.map((name) => unlink(join(path, name)).catch(ignoreErrorCodes("ENOENT"))));
1002
+ await rmdir(path).catch(ignoreErrorCodes("ENOENT", "ENOTEMPTY", "EEXIST"));
1003
+ }
1004
+ function ignoreErrorCodes(...codes) {
1005
+ return (error) => {
1006
+ if (!codes.some((code) => hasErrorCode(error, code))) throw error;
1007
+ };
1008
+ }
1009
+ function isLiveProcess(pid) {
1010
+ try {
1011
+ process.kill(pid, 0);
1012
+ return true;
1013
+ } catch (error) {
1014
+ return hasErrorCode(error, "EPERM");
1015
+ }
1016
+ }
1017
+ function hasErrorCode(error, code) {
1018
+ return error?.code === code;
1019
+ }
1020
+ //#endregion
1021
+ //#region src/adapters/audio/managed/rivus-audio-release.ts
1022
+ const RIVUS_AUDIO_MANIFEST_FILE = "manifest.json";
1023
+ const RIVUS_AUDIO_RELEASES_DIRECTORY = "releases";
1024
+ const manifestSchema = Schema.fromJsonString(Schema.Struct({
1025
+ id: Schema.NonEmptyString,
1026
+ smoke: Schema.Struct({
1027
+ expect: Schema.NonEmptyString,
1028
+ input: Schema.NonEmptyString
1029
+ })
1030
+ }));
1031
+ const currentSchema = Schema.fromJsonString(Schema.Struct({
1032
+ digest: Schema.optional(Schema.NonEmptyString),
1033
+ id: Schema.NonEmptyString,
1034
+ release: Schema.NonEmptyString
1035
+ }));
1036
+ function rivusAudioCurrentPath(installRoot) {
1037
+ return join(installRoot, "current.json");
1038
+ }
1039
+ async function readRivusAudioReleaseManifest(directory) {
1040
+ const path = join(directory, RIVUS_AUDIO_MANIFEST_FILE);
1041
+ const manifest = Option.getOrUndefined(Schema.decodeUnknownOption(manifestSchema)(await readFile(path, "utf8")));
1042
+ if (manifest === void 0 || !isStrictlyWithin(directory, resolve(directory, manifest.smoke.input))) throw new Error(`audio transcriber manifest is invalid: ${path}`);
1043
+ return manifest;
1044
+ }
1045
+ /**
1046
+ * Whether an entry of the asset directory, at any depth, belongs in a release. Dependencies come from the shrinkwrap
1047
+ * and colocated tests stay out of the published package, so a release never contains either and a workspace checkout
1048
+ * produces the same release and digest as the published package.
1049
+ */
1050
+ function isRivusAudioReleaseAsset(name) {
1051
+ return name !== "node_modules" && !name.endsWith(".test.ts");
1052
+ }
1053
+ /**
1054
+ * Digests the asset files that an installation copies, so an asset change reinstalls the transcriber even when the
1055
+ * manifest id stays the same.
1056
+ */
1057
+ async function readRivusAudioAssetDigest(directory) {
1058
+ const hash = createHash("sha256");
1059
+ for (const file of (await listAssetFiles(directory, "")).sort()) {
1060
+ const content = await readFile(join(directory, file));
1061
+ hash.update(`${file}\0${String(content.length)}\0`).update(content);
1062
+ }
1063
+ return hash.digest("hex");
1064
+ }
1065
+ /**
1066
+ * Reads the release that current.json selects. A missing or malformed record, a release outside `releases/`, or a
1067
+ * missing release directory all mean "not installed", which a reinstall repairs.
1068
+ */
1069
+ async function readRivusAudioInstalledRelease(installRoot) {
1070
+ const text = await readPersistenceFile(rivusAudioCurrentPath(installRoot));
1071
+ const current = text === void 0 ? void 0 : Option.getOrUndefined(Schema.decodeUnknownOption(currentSchema)(text));
1072
+ if (current === void 0) return;
1073
+ const directory = resolve(installRoot, current.release);
1074
+ if (!isStrictlyWithin(join(installRoot, "releases"), directory)) return;
1075
+ return await stat(directory).then((info) => info.isDirectory(), () => false) ? {
1076
+ ...current.digest === void 0 ? {} : { digest: current.digest },
1077
+ directory,
1078
+ id: current.id,
1079
+ release: current.release
1080
+ } : void 0;
1081
+ }
1082
+ async function readRivusAudioStatus(installRoot, assetDirectory) {
1083
+ const expected = await readRivusAudioReleaseManifest(assetDirectory);
1084
+ const expectedDigest = await readRivusAudioAssetDigest(assetDirectory);
1085
+ const installed = await readRivusAudioInstalledRelease(installRoot);
1086
+ return installed === void 0 ? {
1087
+ installed: false,
1088
+ expectedId: expected.id,
1089
+ expectedDigest,
1090
+ upToDate: false
1091
+ } : {
1092
+ installed: true,
1093
+ id: installed.id,
1094
+ ...installed.digest === void 0 ? {} : { digest: installed.digest },
1095
+ release: installed.directory,
1096
+ expectedId: expected.id,
1097
+ expectedDigest,
1098
+ upToDate: installed.id === expected.id && installed.digest === expectedDigest
1099
+ };
1100
+ }
1101
+ /** Lists the release asset files by relative path with "/" separators. */
1102
+ async function listAssetFiles(root, prefix) {
1103
+ const entries = await readdir(join(root, prefix), { withFileTypes: true });
1104
+ return (await Promise.all(entries.filter((entry) => isRivusAudioReleaseAsset(entry.name)).map(async (entry) => {
1105
+ const path = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
1106
+ return entry.isDirectory() ? listAssetFiles(root, path) : [path];
1107
+ }))).flat();
1108
+ }
1109
+ function isStrictlyWithin(root, candidate) {
1110
+ return candidate !== resolve(root) && isPathWithin(root, candidate);
1111
+ }
1112
+ //#endregion
1113
+ //#region src/adapters/audio/managed/rivus-audio-installer.ts
1114
+ const INSTALL_DEADLINE_MS = 15e5;
1115
+ const NPM_TIMEOUT_MS = 3e5;
1116
+ const FETCH_TIMEOUT_MS = 12e5;
1117
+ const SMOKE_TIMEOUT_MS = 3e5;
1118
+ const STALE_LOCK_MS = 2 * INSTALL_DEADLINE_MS;
1119
+ const LOCK_POLL_MS = 2e3;
1120
+ const STAGING_PREFIX = "staging-";
1121
+ var RivusAudioInstallStepError = class extends Error {
1122
+ step;
1123
+ constructor(step, reason, output = "") {
1124
+ const detail = output.trim().slice(-4e3);
1125
+ super(`audio transcriber installation failed at ${step}: ${reason}${detail ? `\n${detail}` : ""}`);
1126
+ this.name = "RivusAudioInstallStepError";
1127
+ this.step = step;
1128
+ }
1129
+ };
1130
+ /**
1131
+ * Builds a release in a staging directory beside `releases/`, smoke-tests it, then publishes it by renaming the
1132
+ * directory and atomically replacing current.json. A failure before current.json changes leaves the previous release
1133
+ * selected and removes the staging directory. While another installer holds the lock, this one waits within its
1134
+ * deadline and then rechecks current.json, so it does not rebuild a release that installer just published.
1135
+ */
1136
+ async function installRivusAudioTranscriber(options) {
1137
+ const now = options.now ?? Date.now;
1138
+ const deadlineMs = options.deadlineMs ?? INSTALL_DEADLINE_MS;
1139
+ const deadline = {
1140
+ at: now() + deadlineMs,
1141
+ ms: deadlineMs,
1142
+ now
1143
+ };
1144
+ const root = resolve(options.installRoot);
1145
+ await mkdir(root, { recursive: true });
1146
+ const lock = await acquireLockWhenFree(root, options, deadline);
1147
+ try {
1148
+ await removeInterruptedStaging(root);
1149
+ const previous = await readRivusAudioInstalledRelease(root);
1150
+ if (!options.force && options.reuseInstalledRelease && previous) return {
1151
+ status: "already-installed",
1152
+ id: previous.id,
1153
+ release: previous.directory
1154
+ };
1155
+ const manifest = await readRivusAudioReleaseManifest(options.assetDirectory);
1156
+ const digest = await readRivusAudioAssetDigest(options.assetDirectory);
1157
+ if (!options.force && previous?.id === manifest.id && previous.digest === digest) return {
1158
+ status: "already-installed",
1159
+ id: previous.id,
1160
+ release: previous.directory
1161
+ };
1162
+ const release = await buildRelease(root, manifest, digest, options, deadline);
1163
+ await pruneReleases(root, [release, previous?.directory]);
1164
+ return {
1165
+ status: "installed",
1166
+ id: manifest.id,
1167
+ release
1168
+ };
1169
+ } finally {
1170
+ await lock.release().catch(() => void 0);
1171
+ }
1172
+ }
1173
+ async function acquireLockWhenFree(root, options, deadline) {
1174
+ const sleep = options.sleep ?? ((ms) => sleepUnlessAborted(ms, options.signal));
1175
+ for (;;) {
1176
+ try {
1177
+ return await acquireRivusAudioInstallLock(join(root, "install.lock"), {
1178
+ maxAgeMs: STALE_LOCK_MS,
1179
+ ...options.isProcessAlive ? { isProcessAlive: options.isProcessAlive } : {}
1180
+ });
1181
+ } catch (error) {
1182
+ if (!(error instanceof RivusAudioInstallInProgressError)) throw error;
1183
+ }
1184
+ const remainingMs = deadline.at - deadline.now();
1185
+ if (remainingMs <= 0) throw new Error("another audio transcriber installation did not finish in time");
1186
+ await sleep(Math.min(LOCK_POLL_MS, remainingMs));
1187
+ if (options.signal?.aborted) throw new Error("audio transcriber installation was interrupted while waiting for another installation");
1188
+ }
1189
+ }
1190
+ function sleepUnlessAborted(ms, signal) {
1191
+ return setTimeout$1(ms, void 0, signal ? { signal } : {}).catch(() => void 0);
1192
+ }
1193
+ async function buildRelease(root, manifest, digest, options, deadline) {
1194
+ const staging = join(root, `${STAGING_PREFIX}${randomUUID()}`);
1195
+ const release = join(root, RIVUS_AUDIO_RELEASES_DIRECTORY, `${manifest.id.replaceAll(/[^\w.-]/g, "_")}-${digest.slice(0, 12)}-${randomUUID().slice(0, 8)}`);
1196
+ const env = withNodeOnPath(options.env, options.nodeExecutable);
1197
+ let renamed = false;
1198
+ try {
1199
+ await cp(options.assetDirectory, staging, {
1200
+ filter: (source) => isRivusAudioReleaseAsset(basename(source)),
1201
+ recursive: true
1202
+ }).catch((error) => {
1203
+ throw new RivusAudioInstallStepError("copy assets", errorMessage(error));
1204
+ });
1205
+ await runStep(options, deadline, "npm ci", {
1206
+ args: [
1207
+ "ci",
1208
+ "--ignore-scripts",
1209
+ "--omit=dev",
1210
+ "--no-audit",
1211
+ "--no-fund"
1212
+ ],
1213
+ command: "npm",
1214
+ cwd: staging,
1215
+ env,
1216
+ timeoutMs: NPM_TIMEOUT_MS
1217
+ });
1218
+ await runStep(options, deadline, "model download", {
1219
+ args: [
1220
+ "fetch-model.mjs",
1221
+ RIVUS_AUDIO_MANIFEST_FILE,
1222
+ "model"
1223
+ ],
1224
+ command: options.nodeExecutable,
1225
+ cwd: staging,
1226
+ env,
1227
+ timeoutMs: FETCH_TIMEOUT_MS
1228
+ });
1229
+ const { RIVUS_AUDIO_LANGUAGE: _language, ...smokeEnv } = env;
1230
+ const smoke = await runStep(options, deadline, "smoke test", {
1231
+ args: ["transcribe.mjs", resolve(staging, manifest.smoke.input)],
1232
+ command: options.nodeExecutable,
1233
+ cwd: staging,
1234
+ env: smokeEnv,
1235
+ timeoutMs: SMOKE_TIMEOUT_MS
1236
+ });
1237
+ if (smoke.stderrTail !== "") throw new RivusAudioInstallStepError("smoke test", "the transcriber wrote to stderr", smoke.stderrTail);
1238
+ if (!smoke.stdout.includes(manifest.smoke.expect)) throw new RivusAudioInstallStepError("smoke test", `the transcript does not contain ${JSON.stringify(manifest.smoke.expect)}`, smoke.stdout);
1239
+ await mkdir(dirname(release), { recursive: true });
1240
+ await rename(staging, release);
1241
+ renamed = true;
1242
+ await writeAtomicTextFile(rivusAudioCurrentPath(root), `${JSON.stringify({
1243
+ id: manifest.id,
1244
+ digest,
1245
+ release: relative(root, release)
1246
+ })}\n`, { durable: true });
1247
+ return release;
1248
+ } catch (error) {
1249
+ if ((renamed ? await readRivusAudioInstalledRelease(root).then((installed) => installed?.directory, () => void 0) : void 0) !== release) await rm(renamed ? release : staging, {
1250
+ force: true,
1251
+ recursive: true
1252
+ }).catch(() => void 0);
1253
+ throw error instanceof RivusAudioInstallStepError ? error : new RivusAudioInstallStepError("publish", errorMessage(error));
1254
+ }
1255
+ }
1256
+ async function runStep(options, deadline, step, request) {
1257
+ if (options.signal?.aborted) throw new RivusAudioInstallStepError(step, "interrupted");
1258
+ const deadlineReason = `the installation did not finish within ${seconds(deadline.ms)} s`;
1259
+ const remainingMs = deadline.at - deadline.now();
1260
+ if (remainingMs <= 0) throw new RivusAudioInstallStepError(step, deadlineReason);
1261
+ const timeoutMs = Math.min(request.timeoutMs, remainingMs);
1262
+ const result = await options.runProcess({
1263
+ ...request,
1264
+ timeoutMs,
1265
+ ...options.signal ? { signal: options.signal } : {}
1266
+ }).catch((error) => {
1267
+ throw new RivusAudioInstallStepError(step, `could not start ${request.command}: ${errorMessage(error)}`);
1268
+ });
1269
+ if (result.outcome === "timed-out") throw new RivusAudioInstallStepError(step, timeoutMs < request.timeoutMs ? deadlineReason : `timed out after ${seconds(request.timeoutMs)} s`, result.stderrTail);
1270
+ if (result.outcome === "interrupted") throw new RivusAudioInstallStepError(step, "interrupted", result.stderrTail);
1271
+ if (result.exitCode !== 0) throw new RivusAudioInstallStepError(step, `exited with code ${String(result.exitCode)}`, result.stderrTail);
1272
+ return result;
1273
+ }
1274
+ async function removeInterruptedStaging(root) {
1275
+ const entries = await readdir(root);
1276
+ await Promise.all(entries.filter((name) => name.startsWith(STAGING_PREFIX)).map((name) => join(root, name)).map((path) => rm(path, {
1277
+ force: true,
1278
+ maxRetries: 5,
1279
+ recursive: true
1280
+ }).catch((error) => {
1281
+ throw new RivusAudioInstallStepError("staging cleanup", `could not remove the staging directory of an interrupted installation, ${path}: ${errorMessage(error)}`);
1282
+ })));
1283
+ }
1284
+ /** Keeps the new and the previous release, so a transcription that started before the switch can still finish. */
1285
+ async function pruneReleases(root, keep) {
1286
+ const directory = join(root, RIVUS_AUDIO_RELEASES_DIRECTORY);
1287
+ const kept = new Set(keep.filter((path) => path !== void 0));
1288
+ const entries = await readdir(directory).catch(() => []);
1289
+ await Promise.all(entries.map((name) => join(directory, name)).filter((path) => !kept.has(path)).map((path) => rm(path, {
1290
+ force: true,
1291
+ recursive: true
1292
+ }).catch(() => void 0)));
1293
+ }
1294
+ /** npm may be missing from a service PATH, but it is installed beside the running Node executable. */
1295
+ function withNodeOnPath(env, nodeExecutable) {
1296
+ const nodeDirectory = dirname(nodeExecutable);
1297
+ return {
1298
+ ...env,
1299
+ PATH: env.PATH ? `${nodeDirectory}${delimiter}${env.PATH}` : nodeDirectory
1300
+ };
1301
+ }
1302
+ function seconds(ms) {
1303
+ return String(ms / 1e3);
1304
+ }
1305
+ function errorMessage(error) {
1306
+ return error instanceof Error ? error.message : String(error);
1307
+ }
1308
+ //#endregion
1309
+ //#region src/adapters/audio/managed/rivus-audio-process.ts
1310
+ const OUTPUT_LIMIT = 65536;
1311
+ const KILL_GRACE_MS = 2e3;
1312
+ /**
1313
+ * Deployment transcription on POSIX owns an isolated group, including wrapper descendants that inherit its pipes.
1314
+ * Managed steps stay in the caller's group and must not spawn children: npm uses --ignore-scripts and plain Node assets.
1315
+ */
1316
+ function runRivusAudioProcess(request) {
1317
+ return new Promise((resolve, reject) => {
1318
+ const stdoutChunks = [];
1319
+ let stdoutBytes = 0;
1320
+ let stdoutTruncated = false;
1321
+ let stderrTail = "";
1322
+ const stderrHeadChunks = [];
1323
+ let stderrHeadBytes = 0;
1324
+ const isolated = request.processGroup === "isolated" && process.platform !== "win32";
1325
+ const child = spawnAudioProcess(request, (text) => {
1326
+ const bytes = Buffer.from(text);
1327
+ const remaining = OUTPUT_LIMIT - stdoutBytes;
1328
+ stdoutTruncated ||= bytes.length > remaining;
1329
+ if (remaining > 0) {
1330
+ const chunk = bytes.subarray(0, remaining);
1331
+ stdoutChunks.push(chunk);
1332
+ stdoutBytes += chunk.length;
1333
+ }
1334
+ }, (text) => {
1335
+ stderrTail = (stderrTail + text).slice(-65536);
1336
+ const prefix = Buffer.from(text).subarray(0, Math.max(0, 4096 - stderrHeadBytes));
1337
+ if (prefix.length > 0) {
1338
+ stderrHeadChunks.push(prefix);
1339
+ stderrHeadBytes += prefix.length;
1340
+ }
1341
+ });
1342
+ let outcome = "exited";
1343
+ let exitCode = null;
1344
+ let exited = false;
1345
+ let closed = false;
1346
+ let escalation;
1347
+ let termination;
1348
+ let finishTermination;
1349
+ const signalChild = (signal) => {
1350
+ try {
1351
+ if (isolated && child.pid !== void 0) process.kill(-child.pid, signal);
1352
+ else child.kill(signal);
1353
+ } catch {}
1354
+ };
1355
+ const stop = (reason) => {
1356
+ if (closed || !isolated && exited || outcome !== "exited") return;
1357
+ outcome = reason;
1358
+ if (isolated) termination = new Promise((resolveTermination) => {
1359
+ finishTermination = resolveTermination;
1360
+ });
1361
+ signalChild("SIGTERM");
1362
+ escalation = setTimeout(() => {
1363
+ signalChild("SIGKILL");
1364
+ finishTermination?.();
1365
+ }, KILL_GRACE_MS);
1366
+ };
1367
+ const onAbort = () => stop("interrupted");
1368
+ const timeout = setTimeout(() => stop("timed-out"), request.timeoutMs);
1369
+ const finish = () => {
1370
+ clearTimeout(timeout);
1371
+ clearTimeout(escalation);
1372
+ request.signal?.removeEventListener("abort", onAbort);
1373
+ };
1374
+ request.signal?.addEventListener("abort", onAbort, { once: true });
1375
+ if (request.signal?.aborted) onAbort();
1376
+ child.once("exit", (code) => {
1377
+ exited = true;
1378
+ exitCode = code;
1379
+ });
1380
+ child.once("error", (error) => {
1381
+ finish();
1382
+ reject(error);
1383
+ });
1384
+ child.once("close", async () => {
1385
+ closed = true;
1386
+ if (termination) {
1387
+ try {
1388
+ process.kill(-child.pid, 0);
1389
+ } catch {
1390
+ clearTimeout(escalation);
1391
+ finishTermination?.();
1392
+ }
1393
+ await termination;
1394
+ }
1395
+ finish();
1396
+ const stdout = new TextDecoder().decode(Buffer.concat(stdoutChunks), { stream: true });
1397
+ const stderrHead = new TextDecoder().decode(Buffer.concat(stderrHeadChunks), { stream: true });
1398
+ resolve({
1399
+ exitCode,
1400
+ outcome,
1401
+ stderrTail,
1402
+ stderrHead,
1403
+ stdout,
1404
+ ...stdoutTruncated ? { stdoutTruncated: true } : {}
1405
+ });
1406
+ });
1407
+ });
1408
+ }
1409
+ /** Streams the transcriber's stdout and stderr to the caller and resolves with its exit code. */
1410
+ function runRivusAudioPassthroughProcess(request) {
1411
+ return new Promise((resolve, reject) => {
1412
+ const child = spawnAudioProcess(request, (text) => request.stdout.write(text), (text) => request.stderr.write(text));
1413
+ const onAbort = () => {
1414
+ child.kill("SIGTERM");
1415
+ };
1416
+ request.signal?.addEventListener("abort", onAbort, { once: true });
1417
+ child.once("error", (error) => {
1418
+ request.signal?.removeEventListener("abort", onAbort);
1419
+ reject(error);
1420
+ });
1421
+ child.once("close", (code) => {
1422
+ request.signal?.removeEventListener("abort", onAbort);
1423
+ resolve(code);
1424
+ });
1425
+ });
1426
+ }
1427
+ /**
1428
+ * Managed steps retain service-level group termination; deployment wrappers get a separately terminable group.
1429
+ */
1430
+ function spawnAudioProcess(request, onStdout, onStderr) {
1431
+ const child = spawn(request.command, [...request.args], {
1432
+ cwd: request.cwd,
1433
+ env: { ...request.env },
1434
+ detached: request.processGroup === "isolated" && process.platform !== "win32",
1435
+ stdio: [
1436
+ "ignore",
1437
+ "pipe",
1438
+ "pipe"
1439
+ ]
1440
+ });
1441
+ child.stdout.setEncoding("utf8").on("data", onStdout);
1442
+ child.stderr.setEncoding("utf8").on("data", onStderr);
1443
+ return child;
1444
+ }
1445
+ //#endregion
579
1446
  //#region src/adapters/cli/model/rivus-model-cli-protocol.ts
580
1447
  const RIVUS_MODEL_CLI_USAGE = `Usage:
581
1448
  rivus model status --json [--request <id>] [--verbose]
@@ -1200,7 +2067,7 @@ function parseLockOwner(value) {
1200
2067
  //#endregion
1201
2068
  //#region src/platform/project/setup/release-descriptor.ts
1202
2069
  const RIVUS_RELEASE_DESCRIPTOR = Object.freeze({
1203
- version: "0.19.0",
2070
+ version: "0.20.0",
1204
2071
  dependencies: Object.freeze({
1205
2072
  "@earendil-works/pi-coding-agent": "0.84.4",
1206
2073
  "@larksuiteoapi/node-sdk": "1.74.0",
@@ -1301,5 +2168,5 @@ function withoutRivusHomeDeployment(env) {
1301
2168
  return rest;
1302
2169
  }
1303
2170
  //#endregion
1304
- export { validateRivusDeploymentManifest as C, InvalidRivusProjectSpace as S, deepFreeze as T, gatewayTemplateDirectory as _, invokeRuntimeControl as a, loadMergedLocalEnvFile as b, createRivusModelManagementFailure as c, renderRivusModelCliArgumentError as d, renderRivusModelCliHelp as f, gatewaySkillsDirectory as g, gatewayPackageManifestPath as h, disposeRuntimeCacheEntries as i, createRivusModelManagementWireRequest as l, gatewayPackageDirectory as m, withoutRivusHomeDeployment as n, RIVUS_RELEASE_DESCRIPTOR as o, gatewayAudioTranscriberAssetDirectory as p, createRuntimeCache as r, createRivusModelManagementSocketServer as s, RIVUS_HOME_DEPLOYMENT_ENV as t, parseRivusModelCliArguments as u, loadRivusDeploymentManifest as v, validateRivusProjectSpaceDeployment as w, resolveFeishuEndpointCredentials as x, loadRivusDaemonConfig as y };
2171
+ export { resolveFeishuEndpointCredentials as A, gatewayTemplateDirectory as C, parseRivusModelManagementEnabled as D, migrateRivusModelManagementConfig as E, narrowBackgroundSessionDefinition as F, deepFreeze as I, validateRivusDeploymentManifest as M, validateRivusProjectSpaceDeployment as N, parseRivusModelManagementHomeConfig as O, createBackgroundSessionToolContracts as P, gatewaySkillsDirectory as S, resolveAcpRuntimeEnvironment as T, readRivusAudioInstalledRelease as _, invokeRuntimeControl as a, gatewayPackageDirectory as b, createRivusModelManagementFailure as c, renderRivusModelCliArgumentError as d, renderRivusModelCliHelp as f, installRivusAudioTranscriber as g, RivusAudioInstallStepError as h, disposeRuntimeCacheEntries as i, InvalidRivusProjectSpace as j, loadMergedLocalEnvFile as k, createRivusModelManagementWireRequest as l, runRivusAudioProcess as m, withoutRivusHomeDeployment as n, RIVUS_RELEASE_DESCRIPTOR as o, runRivusAudioPassthroughProcess as p, createRuntimeCache as r, createRivusModelManagementSocketServer as s, RIVUS_HOME_DEPLOYMENT_ENV as t, parseRivusModelCliArguments as u, readRivusAudioStatus as v, loadRivusDeploymentManifest as w, gatewayPackageManifestPath as x, gatewayAudioTranscriberAssetDirectory as y };
1305
2172