@rivus/gateway 0.16.6 → 0.18.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.
Files changed (36) hide show
  1. package/LICENSE +674 -21
  2. package/README.md +25 -0
  3. package/dist/bootstrap/herdr-feishu.d.ts +37 -0
  4. package/dist/bootstrap/herdr-feishu.js +853 -0
  5. package/dist/bootstrap/pi-feishu.d.ts +281 -16
  6. package/dist/bootstrap/pi-feishu.js +17315 -345
  7. package/dist/chunks/background-session-authority.js +2 -38
  8. package/dist/chunks/rivus-daemon-cli.d.ts +1115 -0
  9. package/dist/chunks/rivus-node-entrypoint.js +735 -847
  10. package/dist/chunks/{node-rivus-deployment-manifest.js → runtime-cache.js} +1118 -1476
  11. package/dist/cli.d.ts +2 -1
  12. package/dist/cli.js +1 -0
  13. package/dist/index.d.ts +65 -3
  14. package/dist/index.js +3 -1215
  15. package/dist/mcp.d.ts +7 -63
  16. package/dist/mcp.js +3 -250
  17. package/package.json +21 -13
  18. package/templates/a-share-briefing-analysis.mjs +3 -1
  19. package/templates/a-share-briefing-renderer.mjs +15 -5
  20. package/templates/a-share-index-evidence.mjs +9 -3
  21. package/templates/a-share-market-briefing.mjs +3 -1
  22. package/templates/a-share-overseas-evidence.mjs +12 -4
  23. package/templates/a-share-policy-evidence.mjs +30 -10
  24. package/templates/a-share-sector-evidence.mjs +3 -1
  25. package/templates/acp-stdio-proxy.mjs +10 -4
  26. package/templates/current-weather.mjs +36 -12
  27. package/templates/herdr-feishu.mjs +30 -0
  28. package/templates/html-drive-tools.mjs +36 -12
  29. package/templates/pi-feishu-deployment.bootstrap.ts +1 -3
  30. package/templates/pi-feishu.bootstrap.ts +1 -242
  31. package/templates/rivus-agents.plugin.mjs +3 -1
  32. package/dist/chunks/background-session-control-input.js +0 -45
  33. package/dist/chunks/background-session-service.d.ts +0 -390
  34. package/dist/chunks/index.d.ts +0 -4703
  35. package/dist/chunks/service.js +0 -12112
  36. package/templates/langfuse-drive-e2e.mjs +0 -175
@@ -1,143 +1,11 @@
1
- import { Cause, Deferred, Effect, Exit, Option } from "effect";
2
1
  import { isRivusRuntimeToolId } from "@rivus/runtime";
3
- import { createHash, randomUUID } from "node:crypto";
4
- import { access, chmod, constants, mkdir, open, readFile, rename, stat, unlink } from "node:fs/promises";
2
+ import { dirname, isAbsolute } from "node:path";
3
+ 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";
5
7
  import { createConnection, createServer } from "node:net";
6
- import { dirname, isAbsolute, join } from "node:path";
7
8
  import { readPersistenceFile } from "@rivus/platform/persistence";
8
- import { homedir } from "node:os";
9
- import { fileURLToPath } from "node:url";
10
- //#region src/platform/runtime-pool/runtime-cache.ts
11
- function createRuntimeCache() {
12
- const entries = /* @__PURE__ */ new Map();
13
- const serial = Effect.unsafeMakeSemaphore(1);
14
- const reserve = (key) => serial.withPermits(1)(Effect.gen(function* () {
15
- const current = entries.get(key);
16
- if (current) return {
17
- created: false,
18
- entry: current
19
- };
20
- const entry = {
21
- deferred: yield* Deferred.make(),
22
- initializationStarted: false,
23
- key
24
- };
25
- entries.set(key, entry);
26
- return {
27
- created: true,
28
- entry
29
- };
30
- }));
31
- const start = (entry, create) => Effect.uninterruptible(Effect.gen(function* () {
32
- if (!(yield* serial.withPermits(1)(Effect.sync(() => {
33
- if (entry.initializationStarted) return false;
34
- entry.initializationStarted = true;
35
- return true;
36
- })))) return;
37
- const initialization = create().pipe(Effect.tapError(() => serial.withPermits(1)(Effect.sync(() => {
38
- if (entries.get(entry.key) === entry) entries.delete(entry.key);
39
- }))), Effect.exit, Effect.flatMap((exit) => Deferred.done(entry.deferred, exit)), Effect.asVoid);
40
- yield* Effect.forkDaemon(initialization);
41
- }));
42
- const getOrCreate = (key, create) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
43
- const selected = yield* reserve(key);
44
- yield* start(selected.entry, create);
45
- return {
46
- entry: selected.entry,
47
- runtime: yield* restore(Deferred.await(selected.entry.deferred))
48
- };
49
- }));
50
- return {
51
- drain: () => serial.withPermits(1)(Effect.sync(() => {
52
- const drained = Object.freeze([...entries.values()]);
53
- entries.clear();
54
- return drained;
55
- })),
56
- getExisting: (key) => Effect.gen(function* () {
57
- const entry = yield* serial.withPermits(1)(Effect.sync(() => entries.get(key)));
58
- if (!entry) return void 0;
59
- return {
60
- entry,
61
- runtime: yield* Deferred.await(entry.deferred)
62
- };
63
- }),
64
- getOrCreate,
65
- isCurrent: (key, entry) => serial.withPermits(1)(Effect.sync(() => entries.get(key) === entry)),
66
- reserve,
67
- size: () => serial.withPermits(1)(Effect.sync(() => entries.size)),
68
- start
69
- };
70
- }
71
- function disposeRuntimeCacheEntries(options) {
72
- const disposal = Effect.gen(function* () {
73
- const completions = yield* Effect.forEach(options.entries, (entry) => Effect.gen(function* () {
74
- const completion = yield* Deferred.make();
75
- yield* Effect.forkDaemon(Deferred.await(entry.deferred).pipe(Effect.flatMap(options.dispose), Effect.exit, Effect.flatMap((exit) => Deferred.succeed(completion, exit)), Effect.asVoid));
76
- return completion;
77
- }), { concurrency: "unbounded" });
78
- const failures = (yield* Effect.forEach(completions, Deferred.await, { concurrency: "unbounded" })).filter(Exit.isFailure).map(({ cause }) => Cause.squash(cause));
79
- if (failures.length > 0) return yield* Effect.fail(new AggregateError(failures, options.failureMessage));
80
- });
81
- return options.timeout ? disposal.pipe(Effect.timeoutFail({
82
- duration: options.timeout.milliseconds,
83
- onTimeout: options.timeout.onTimeout
84
- })) : disposal;
85
- }
86
- function invokeRuntimeControl(runtime, control) {
87
- return runtime.pipe(Effect.flatMap((selected) => selected ? control(selected) ?? Effect.succeed(false) : Effect.succeed(false)));
88
- }
89
- //#endregion
90
- //#region src/adapters/agent/runtime/process-agent-runtime-adapter.ts
91
- function toEffectAgentRuntimeInput(input) {
92
- const onUpdate = input.onUpdate;
93
- return {
94
- ...runtimeInputFields(input),
95
- ...onUpdate ? { onUpdate: (update) => Effect.tryPromise({
96
- try: async () => onUpdate(update),
97
- catch: (failure) => failure
98
- }) } : {}
99
- };
100
- }
101
- function toProcessAgentRuntimeInput(input, runEffect) {
102
- const onUpdate = input.onUpdate;
103
- return {
104
- ...runtimeInputFields(input),
105
- ...onUpdate ? { onUpdate: (update) => runEffect(onUpdate(update)) } : {}
106
- };
107
- }
108
- function toEffectAgentRuntime(runtime, runEffect) {
109
- const cancel = runtime.cancel?.bind(runtime);
110
- const dispose = runtime.dispose?.bind(runtime);
111
- const steer = runtime.steer?.bind(runtime);
112
- return {
113
- ...runtime.concurrency ? { concurrency: runtime.concurrency } : {},
114
- ...cancel ? { cancel: (input) => Effect.tryPromise({
115
- try: () => cancel(input),
116
- catch: (failure) => failure
117
- }) } : {},
118
- ...dispose ? { dispose: () => Effect.tryPromise({
119
- try: async () => dispose(),
120
- catch: (failure) => failure
121
- }) } : {},
122
- run: (input) => Effect.tryPromise({
123
- try: () => runtime.run(toProcessAgentRuntimeInput(input, runEffect)),
124
- catch: (failure) => failure
125
- }),
126
- ...steer ? { steer: (input) => Effect.tryPromise({
127
- try: () => steer(input),
128
- catch: (failure) => failure
129
- }) } : {}
130
- };
131
- }
132
- function runtimeInputFields(input) {
133
- return {
134
- ...input.invocation ? { invocation: input.invocation } : {},
135
- ...input.payload === void 0 ? {} : { payload: input.payload },
136
- sessionKey: input.sessionKey,
137
- text: input.text
138
- };
139
- }
140
- //#endregion
141
9
  //#region src/platform/values/deep-freeze.ts
142
10
  function deepFreeze(value) {
143
11
  if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
@@ -147,630 +15,384 @@ function deepFreeze(value) {
147
15
  return value;
148
16
  }
149
17
  //#endregion
150
- //#region src/bootstrap/deployment/effect-runner.ts
151
- async function runDeploymentProcessEffect(effect) {
152
- const exit = await Effect.runPromiseExit(effect);
153
- if (Exit.isSuccess(exit)) return exit.value;
154
- const failure = Cause.failureOption(exit.cause);
155
- throw Option.isSome(failure) ? failure.value : Cause.squash(exit.cause);
156
- }
157
- //#endregion
158
- //#region src/adapters/cli/model/rivus-model-cli-protocol.ts
159
- const RIVUS_MODEL_CLI_USAGE = `Usage:
160
- rivus model status --json [--request <id>] [--verbose]
161
- rivus model set --model <provider/model> --expected-revision <n> --request <id> --json [--verbose]
162
- rivus model rollback --expected-revision <n> --request <id> --json [--verbose]
163
-
164
- Commands:
165
- status Read the effective and persistent model selection
166
- set Submit one authorized model change
167
- rollback Submit one authorized change to the previous model
168
-
169
- All command results are JSON. A successful set or rollback call means the request
170
- was accepted; query status by request id for the final outcome.
171
- `;
172
- function parseRivusModelCliArguments(argv) {
173
- if (argv.includes("--help") || argv.includes("-h")) return { help: true };
174
- const operation = argv[0];
175
- if (operation !== "status" && operation !== "set" && operation !== "rollback") return { error: "model requires one of status, set, rollback" };
176
- let expectedRevision;
177
- let json = false;
178
- let model;
179
- let requestId;
180
- let verbose = false;
181
- for (let index = 1; index < argv.length; index += 1) {
182
- const argument = argv[index];
183
- if (argument === "--json") {
184
- if (json) return { error: "--json may only be provided once" };
185
- json = true;
186
- continue;
187
- }
188
- if (argument === "--verbose") {
189
- if (verbose) return { error: "--verbose may only be provided once" };
190
- verbose = true;
191
- continue;
192
- }
193
- if (argument === "--request") {
194
- if (requestId !== void 0) return { error: "--request may only be provided once" };
195
- const value = argv[index + 1];
196
- if (!value || value.startsWith("-")) return { error: "--request requires an id" };
197
- requestId = value;
198
- index += 1;
199
- continue;
200
- }
201
- if (argument.startsWith("--request=")) {
202
- if (requestId !== void 0) return { error: "--request may only be provided once" };
203
- requestId = argument.slice(10);
204
- if (!requestId) return { error: "--request requires an id" };
205
- continue;
206
- }
207
- if (argument === "--expected-revision") {
208
- if (expectedRevision !== void 0) return { error: "--expected-revision may only be provided once" };
209
- const value = argv[index + 1];
210
- if (!value || value.startsWith("-")) return { error: "--expected-revision requires a non-negative integer" };
211
- const parsed = parseRevision(value);
212
- if (parsed === void 0) return { error: "--expected-revision requires a non-negative integer" };
213
- expectedRevision = parsed;
214
- index += 1;
215
- continue;
216
- }
217
- if (argument.startsWith("--expected-revision=")) {
218
- if (expectedRevision !== void 0) return { error: "--expected-revision may only be provided once" };
219
- const parsed = parseRevision(argument.slice(20));
220
- if (parsed === void 0) return { error: "--expected-revision requires a non-negative integer" };
221
- expectedRevision = parsed;
222
- continue;
223
- }
224
- if (argument === "--model") {
225
- if (model !== void 0) return { error: "--model may only be provided once" };
226
- const value = argv[index + 1];
227
- if (!value || value.startsWith("-")) return { error: "--model requires provider/model" };
228
- if (!isModelReference(value)) return { error: "--model must be provider/model" };
229
- model = value;
230
- index += 1;
231
- continue;
232
- }
233
- if (argument.startsWith("--model=")) {
234
- if (model !== void 0) return { error: "--model may only be provided once" };
235
- const value = argument.slice(8);
236
- if (!isModelReference(value)) return { error: "--model must be provider/model" };
237
- model = value;
238
- continue;
239
- }
240
- return { error: `Unknown model option: ${argument}` };
241
- }
242
- if (!json) return { error: "model commands require --json" };
243
- if (operation === "status") {
244
- if (model !== void 0) return { error: "status does not accept --model" };
245
- if (expectedRevision !== void 0) return { error: "status does not accept --expected-revision" };
246
- return {
247
- json: true,
248
- operation,
249
- ...requestId !== void 0 ? { requestId } : {},
250
- ...verbose ? { verbose: true } : {}
251
- };
18
+ //#region src/core/application/deployment/manifest/deployment-manifest.ts
19
+ const DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_MS = 3e4;
20
+ const DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_RENEWAL_INTERVAL_MS = 1e4;
21
+ const DEFAULT_MANIFEST_BACKGROUND_SESSION_MAX_CONSECUTIVE_FAILURES = 3;
22
+ const DEFAULT_MANIFEST_BACKGROUND_SESSION_MAX_CONCURRENT_SESSIONS = 4;
23
+ const DEFAULT_MANIFEST_BACKGROUND_SESSION_RETRY_BACKOFF_MS = 3e4;
24
+ const DEFAULT_MANIFEST_BACKGROUND_SESSION_LIFETIME_MS = 864e5;
25
+ const DEFAULT_MANIFEST_BACKGROUND_SESSION_STEP_TIMEOUT_MS = 3e5;
26
+ const DEFAULT_MANIFEST_CARD_STREAM_LEASE_MS = 51e4;
27
+ const DEFAULT_MANIFEST_CONVERSATION_PROGRESS_DISPLAY = "collapsed";
28
+ const MEMORY_SCOPES = [
29
+ "conversation",
30
+ "agent-private",
31
+ "project",
32
+ "shared-user-profile"
33
+ ];
34
+ var InvalidRivusProjectSpace = class extends Error {
35
+ name = "InvalidRivusProjectSpace";
36
+ };
37
+ function validateRivusProjectSpaceDeployments(declarations) {
38
+ const projectSpaceIds = /* @__PURE__ */ new Set();
39
+ for (const declaration of declarations) {
40
+ if (projectSpaceIds.has(declaration.id)) throw new InvalidRivusProjectSpace(`duplicate project space: ${declaration.id}`);
41
+ projectSpaceIds.add(declaration.id);
42
+ validateRivusProjectSpaceDeployment(declaration);
252
43
  }
253
- if (requestId === void 0) return { error: "--request is required for model changes" };
254
- if (expectedRevision === void 0) return { error: "--expected-revision is required for model changes" };
255
- if (operation === "set" && model === void 0) return { error: "--model is required for model set" };
256
- if (operation === "rollback" && model !== void 0) return { error: "rollback does not accept --model" };
257
- return operation === "set" ? {
258
- expectedRevision,
259
- json: true,
260
- model,
261
- operation,
262
- requestId,
263
- ...verbose ? { verbose: true } : {}
264
- } : {
265
- expectedRevision,
266
- json: true,
267
- operation,
268
- requestId,
269
- ...verbose ? { verbose: true } : {}
270
- };
271
- }
272
- function renderRivusModelCliHelp() {
273
- return RIVUS_MODEL_CLI_USAGE;
44
+ return projectSpaceIds;
274
45
  }
275
- function renderRivusModelCliArgumentError(error) {
276
- return `${error}\n\n${RIVUS_MODEL_CLI_USAGE}`;
46
+ function validateRivusProjectSpaceDeployment(declaration) {
47
+ validateRelativeProjectPath(declaration.root, `project space ${declaration.id} root`);
48
+ validateRelativeProjectPath(declaration.workingDirectory, `project space ${declaration.id} working directory`);
49
+ const sources = /* @__PURE__ */ new Set();
50
+ for (const source of declaration.skills.sources) {
51
+ validateRelativeProjectPath(source, `project space ${declaration.id} Skill source`);
52
+ if (sources.has(source)) throw new InvalidRivusProjectSpace(`project space ${declaration.id} contains duplicate Skill source: ${source}`);
53
+ sources.add(source);
54
+ }
277
55
  }
278
- function isModelReference(value) {
279
- return /^[^/\s]+\/[^/\s]+$/.test(value);
56
+ function validateRelativeProjectPath(value, owner) {
57
+ if (value.trim() === "" || isAbsoluteProjectPath(value) || value.includes("\0")) throw new InvalidRivusProjectSpace(`${owner} must be a non-empty relative path`);
280
58
  }
281
- function parseRevision(value) {
282
- if (!/^\d+$/.test(value)) return void 0;
283
- const revision = Number(value);
284
- return Number.isSafeInteger(revision) ? revision : void 0;
59
+ function isAbsoluteProjectPath(value) {
60
+ return value.startsWith("/") || value.startsWith("\\") || /^[a-z]:[\\/]/i.test(value);
285
61
  }
286
- //#endregion
287
- //#region src/adapters/cli/model/rivus-model-management-wire.ts
288
- function createRivusModelManagementWireRequest(command, env) {
289
- const context = optionalString(env.RIVUS_MODEL_CONTEXT);
290
- return {
291
- ...command,
292
- ...context ? { context } : {}
293
- };
294
- }
295
- function parseRivusModelManagementWireRequest(value) {
296
- if (!isRecord$2(value)) throw new Error("model request must be a JSON object");
297
- const operation = value.operation;
298
- if (operation !== "status" && operation !== "set" && operation !== "rollback") throw new Error("model request operation is invalid");
299
- const context = optionalString(value.context);
300
- const requestId = optionalString(value.requestId);
301
- const verbose = value.verbose === true ? true : void 0;
302
- if (operation === "status") {
303
- if (value.json !== true) throw new Error("model request must require JSON output");
304
- return {
305
- json: true,
306
- operation,
307
- ...context ? { context } : {},
308
- ...requestId ? { requestId } : {},
309
- ...verbose ? { verbose: true } : {}
310
- };
311
- }
312
- const expectedRevision = value.expectedRevision;
313
- 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");
314
- if (!requestId) throw new Error("model request requires a request id");
315
- if (operation === "set") {
316
- const model = optionalString(value.model);
317
- if (!model || !/^[^/\s]+\/[^/\s]+$/.test(model)) throw new Error("model request target is invalid");
318
- return {
319
- expectedRevision,
320
- json: true,
321
- model,
322
- operation,
323
- requestId,
324
- ...context ? { context } : {},
325
- ...verbose ? { verbose: true } : {}
326
- };
327
- }
328
- return {
329
- expectedRevision,
330
- json: true,
331
- operation,
332
- requestId,
333
- ...context ? { context } : {},
334
- ...verbose ? { verbose: true } : {}
335
- };
336
- }
337
- function toRivusModelManagementSubmission(request) {
338
- const target = request.operation === "set" ? parseTarget(request.model) : void 0;
339
- return {
340
- expectedRevision: request.expectedRevision,
341
- operation: request.operation,
342
- requestId: request.requestId,
343
- ...target ? { target } : {},
344
- ...request.verbose ? { verbose: true } : {}
345
- };
346
- }
347
- function projectRivusModelCliResponse(value, operation) {
348
- if (!isRecord$2(value)) throw new Error("model handler must return a JSON object");
349
- const response = { schemaVersion: 1 };
350
- copyScalar(response, value, "requestId");
351
- copyScalar(response, value, "revision");
352
- copyScalar(response, value, "source");
353
- copyScalar(response, value, "protocolVersion");
354
- copyScalar(response, value, "runtimeVersion");
355
- copyScalar(response, value, "operation");
356
- copyScalar(response, value, "expectedRevision");
357
- copyScalar(response, value, "phase");
358
- copyScalar(response, value, "reason");
359
- for (const key of [
360
- "actual",
361
- "current",
362
- "persisted",
363
- "previous",
364
- "target"
365
- ]) {
366
- const model = projectModelReference(value[key]);
367
- if (model) response[key] = model;
368
- }
369
- const budget = projectBudget(value.budget);
370
- if (budget) response.budget = budget;
371
- const pending = projectPending(value.pending);
372
- if (pending) response.pending = pending;
373
- const request = projectReceipt(value.request);
374
- if (request) response.request = request;
375
- const error = projectError(value.error);
376
- if (error) response.error = error;
377
- const recoveryRequired = projectError(value.recoveryRequired);
378
- if (recoveryRequired) response.recoveryRequired = recoveryRequired;
379
- const notification = projectNotification(value.notification);
380
- if (notification) response.notification = notification;
381
- const status = value.status;
382
- response.status = isPublicStatus(status) ? status : value.recoveryRequired !== void 0 ? "recovery-required" : operation === "status" && value.pending !== void 0 ? "pending" : operation === "status" ? "applied" : "failed";
383
- return response;
384
- }
385
- function createRivusModelManagementFailure(code, message) {
386
- return {
387
- error: {
388
- code,
389
- message
390
- },
391
- schemaVersion: 1,
392
- status: "failed"
393
- };
394
- }
395
- function projectModelReference(value) {
396
- if (!isRecord$2(value) || typeof value.provider !== "string" || typeof value.model !== "string") return void 0;
397
- const result = {
398
- model: value.model,
399
- provider: value.provider
400
- };
401
- if (typeof value.label === "string") return {
402
- ...result,
403
- label: value.label
404
- };
405
- if (typeof value.bindingRevision === "string") return {
406
- ...result,
407
- bindingRevision: value.bindingRevision
408
- };
409
- return result;
410
- }
411
- function projectPending(value) {
412
- if (!isRecord$2(value)) return void 0;
413
- const result = {};
414
- copyScalar(result, value, "phase");
415
- copyScalar(result, value, "reason");
416
- if (result.reason === void 0 && typeof result.phase === "string") result.reason = result.phase;
417
- copyScalar(result, value, "requestId");
418
- copyScalar(result, value, "updatedAt");
419
- const request = projectReceipt(value.request);
420
- if (request) result.request = request;
421
- const target = projectModelReference(value.target);
422
- if (target) result.target = target;
423
- return Object.keys(result).length > 0 ? result : void 0;
424
- }
425
- function projectReceipt(value) {
426
- if (!isRecord$2(value)) return void 0;
427
- const result = {};
428
- for (const key of [
429
- "requestId",
430
- "revision",
431
- "status",
432
- "phase",
433
- "operation",
434
- "expectedRevision",
435
- "acceptedAt",
436
- "updatedAt"
437
- ]) copyScalar(result, value, key);
438
- const current = projectModelReference(value.current);
439
- if (current) result.current = current;
440
- const previous = projectModelReference(value.previous);
441
- if (previous) result.previous = previous;
442
- const target = projectModelReference(value.target);
443
- if (target) result.target = target;
444
- const budget = projectBudget(value.budget);
445
- if (budget) result.budget = budget;
446
- const error = projectError(value.error);
447
- if (error) result.error = error;
448
- const notification = projectNotification(value.notification);
449
- if (notification) result.notification = notification;
450
- return Object.keys(result).length > 0 ? result : void 0;
451
- }
452
- function projectBudget(value) {
453
- if (!isRecord$2(value)) return void 0;
454
- const result = {};
455
- for (const key of [
456
- "deadlineAt",
457
- "maxOutputTokens",
458
- "maxPaidRequests",
459
- "outputTokens",
460
- "paidRequests"
461
- ]) copyScalar(result, value, key);
462
- return Object.keys(result).length > 0 ? result : void 0;
463
- }
464
- function projectError(value) {
465
- if (!isRecord$2(value) || typeof value.code !== "string" || typeof value.message !== "string") return void 0;
466
- return {
467
- code: value.code,
468
- message: value.message
469
- };
470
- }
471
- function projectNotification(value) {
472
- if (!isRecord$2(value)) return void 0;
473
- const result = {};
474
- copyScalar(result, value, "attempts");
475
- copyScalar(result, value, "lastAttemptAt");
476
- copyScalar(result, value, "status");
477
- return Object.keys(result).length > 0 ? result : void 0;
478
- }
479
- function copyScalar(target, source, key) {
480
- const value = source[key];
481
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") target[key] = value;
482
- }
483
- function parseTarget(value) {
484
- if (!value) throw new Error("model request target is missing");
485
- const separator = value.indexOf("/");
486
- return {
487
- model: value.slice(separator + 1),
488
- provider: value.slice(0, separator)
489
- };
490
- }
491
- function isPublicStatus(value) {
492
- return value === "applied" || value === "failed" || value === "pending" || value === "recovery-required" || value === "restored";
493
- }
494
- function optionalString(value) {
495
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
496
- }
497
- function isRecord$2(value) {
498
- return typeof value === "object" && value !== null && !Array.isArray(value);
499
- }
500
- //#endregion
501
- //#region src/adapters/cli/model/rivus-model-management-socket-server.ts
502
- const MAX_FRAME_BYTES = 64 * 1024;
503
- function createRivusModelManagementSocketServer(options) {
504
- assertAbsoluteSocketPath(options.socketPath);
505
- let server;
506
- let socketIdentity;
507
- let listening = false;
508
- let startPromise;
509
- return {
510
- close: async () => {
511
- if (startPromise) await startPromise.catch(() => void 0);
512
- const current = server;
513
- const identity = socketIdentity;
514
- server = void 0;
515
- socketIdentity = void 0;
516
- if (current && listening) await closeServer(current);
517
- listening = false;
518
- if (identity) await unlinkOwnedSocket(options.socketPath, identity);
519
- },
520
- listening: () => listening,
521
- start: async () => {
522
- if (listening) return;
523
- if (startPromise) return startPromise;
524
- startPromise = startServer(options, (next, identity) => {
525
- server = next;
526
- socketIdentity = identity;
527
- listening = true;
528
- });
529
- try {
530
- await startPromise;
531
- } finally {
532
- startPromise = void 0;
533
- }
534
- }
535
- };
536
- }
537
- async function startServer(options, onStarted) {
538
- await prepareSocketParentDirectory(options.socketPath);
539
- const lockPath = `${options.socketPath}.lock`;
540
- const lock = await acquireStartLock(lockPath);
541
- const next = createServer((socket) => handleConnection(socket, options));
542
- let bound = false;
543
- try {
544
- await prepareSocketPath(options.socketPath);
545
- await listen(next, options.socketPath);
546
- bound = true;
547
- await chmod(options.socketPath, 384);
548
- onStarted(next, await readSocketIdentity(options.socketPath));
549
- } catch (error) {
550
- await closeServer(next).catch(() => void 0);
551
- if (bound) await unlinkSocketIfPresent(options.socketPath);
552
- throw error;
553
- } finally {
554
- await releaseStartLock(lock, lockPath);
555
- }
556
- }
557
- async function handleConnection(socket, options) {
558
- let buffer = "";
559
- let handled = false;
560
- socket.setEncoding("utf8");
561
- socket.on("data", (chunk) => {
562
- if (handled) return;
563
- buffer += chunk;
564
- if (Buffer.byteLength(buffer, "utf8") > MAX_FRAME_BYTES) {
565
- handled = true;
566
- writeResponse(socket, createRivusModelManagementFailure("request_too_large", "model management request is too large"));
567
- return;
568
- }
569
- const newline = buffer.indexOf("\n");
570
- if (newline < 0) return;
571
- handled = true;
572
- handleFrame(buffer.slice(0, newline).trim(), socket, options);
62
+ function parseRivusDeploymentManifest(value) {
63
+ const root = record(value, "manifest");
64
+ exactKeys(root, [
65
+ "agents",
66
+ "automations",
67
+ "backgroundSessions",
68
+ "defaultAgentId",
69
+ "defaultEndpointId",
70
+ "endpoints",
71
+ "plugins",
72
+ "projectSpaces"
73
+ ], "manifest", [
74
+ "automations",
75
+ "backgroundSessions",
76
+ "projectSpaces"
77
+ ]);
78
+ const plugins = array(root.plugins, "manifest.plugins").map((entry, index) => {
79
+ const plugin = record(entry, `manifest.plugins[${index}]`);
80
+ exactKeys(plugin, [
81
+ "id",
82
+ "module",
83
+ "required"
84
+ ], `manifest.plugins[${index}]`);
85
+ return Object.freeze({
86
+ id: string(plugin.id, `manifest.plugins[${index}].id`),
87
+ module: string(plugin.module, `manifest.plugins[${index}].module`),
88
+ required: boolean(plugin.required, `manifest.plugins[${index}].required`)
89
+ });
573
90
  });
574
- socket.on("end", () => {
575
- if (handled || buffer.trim() === "") return;
576
- handled = true;
577
- handleFrame(buffer.trim(), socket, options);
91
+ const agents = array(root.agents, "manifest.agents").map((entry, index) => {
92
+ const agent = record(entry, `manifest.agents[${index}]`);
93
+ exactKeys(agent, [
94
+ "agentId",
95
+ "endpointIds",
96
+ "memory",
97
+ "pluginId",
98
+ "profileId",
99
+ "projectSpaceId",
100
+ "runtimeTools",
101
+ "skills",
102
+ "tools"
103
+ ], `manifest.agents[${index}]`, [
104
+ "memory",
105
+ "projectSpaceId",
106
+ "runtimeTools"
107
+ ]);
108
+ const memory = agent.memory === void 0 ? void 0 : record(agent.memory, `manifest.agents[${index}].memory`);
109
+ if (memory) exactKeys(memory, ["scopes", "tool"], `manifest.agents[${index}].memory`);
110
+ const skills = record(agent.skills, `manifest.agents[${index}].skills`);
111
+ exactKeys(skills, ["allow"], `manifest.agents[${index}].skills`);
112
+ const tools = record(agent.tools, `manifest.agents[${index}].tools`);
113
+ exactKeys(tools, ["allow"], `manifest.agents[${index}].tools`);
114
+ const runtimeTools = agent.runtimeTools === void 0 ? void 0 : record(agent.runtimeTools, `manifest.agents[${index}].runtimeTools`);
115
+ if (runtimeTools) exactKeys(runtimeTools, ["allow"], `manifest.agents[${index}].runtimeTools`);
116
+ return Object.freeze({
117
+ agentId: string(agent.agentId, `manifest.agents[${index}].agentId`),
118
+ endpointIds: Object.freeze(array(agent.endpointIds, `manifest.agents[${index}].endpointIds`).map((item, itemIndex) => string(item, `manifest.agents[${index}].endpointIds[${itemIndex}]`))),
119
+ ...memory ? { memory: Object.freeze({
120
+ scopes: Object.freeze(array(memory.scopes, `manifest.agents[${index}].memory.scopes`).map((item, itemIndex) => memoryScope(item, `manifest.agents[${index}].memory.scopes[${itemIndex}]`))),
121
+ tool: boolean(memory.tool, `manifest.agents[${index}].memory.tool`)
122
+ }) } : {},
123
+ pluginId: string(agent.pluginId, `manifest.agents[${index}].pluginId`),
124
+ profileId: string(agent.profileId, `manifest.agents[${index}].profileId`),
125
+ ...agent.projectSpaceId === void 0 ? {} : { projectSpaceId: string(agent.projectSpaceId, `manifest.agents[${index}].projectSpaceId`) },
126
+ ...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
+ 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
+ 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}]`))) })
129
+ });
578
130
  });
579
- socket.on("error", () => {
580
- handled = true;
131
+ const endpoints = array(root.endpoints, "manifest.endpoints").map((entry, index) => {
132
+ const endpoint = record(entry, `manifest.endpoints[${index}]`);
133
+ exactKeys(endpoint, [
134
+ "agentId",
135
+ "baseUrl",
136
+ "cardStreamLeaseMs",
137
+ "credentialRef",
138
+ "enabled",
139
+ "experimental",
140
+ "groupPolicy",
141
+ "id",
142
+ "progressDisplay",
143
+ "required",
144
+ "sessionNamespace",
145
+ "streamMinIntervalMs"
146
+ ], `manifest.endpoints[${index}]`, [
147
+ "cardStreamLeaseMs",
148
+ "experimental",
149
+ "progressDisplay"
150
+ ]);
151
+ const experimental = endpoint.experimental === void 0 ? void 0 : record(endpoint.experimental, `manifest.endpoints[${index}].experimental`);
152
+ if (experimental) exactKeys(experimental, ["cotMessages"], `manifest.endpoints[${index}].experimental`);
153
+ return Object.freeze({
154
+ agentId: string(endpoint.agentId, `manifest.endpoints[${index}].agentId`),
155
+ baseUrl: string(endpoint.baseUrl, `manifest.endpoints[${index}].baseUrl`),
156
+ cardStreamLeaseMs: endpoint.cardStreamLeaseMs === void 0 ? DEFAULT_MANIFEST_CARD_STREAM_LEASE_MS : positiveInteger(endpoint.cardStreamLeaseMs, `manifest.endpoints[${index}].cardStreamLeaseMs`),
157
+ credentialRef: string(endpoint.credentialRef, `manifest.endpoints[${index}].credentialRef`),
158
+ enabled: boolean(endpoint.enabled, `manifest.endpoints[${index}].enabled`),
159
+ ...experimental ? { experimental: Object.freeze({ cotMessages: boolean(experimental.cotMessages, `manifest.endpoints[${index}].experimental.cotMessages`) }) } : {},
160
+ groupPolicy: groupPolicy(endpoint.groupPolicy, `manifest.endpoints[${index}].groupPolicy`),
161
+ id: string(endpoint.id, `manifest.endpoints[${index}].id`),
162
+ progressDisplay: endpoint.progressDisplay === void 0 ? DEFAULT_MANIFEST_CONVERSATION_PROGRESS_DISPLAY : progressDisplay(endpoint.progressDisplay, `manifest.endpoints[${index}].progressDisplay`),
163
+ required: boolean(endpoint.required, `manifest.endpoints[${index}].required`),
164
+ sessionNamespace: string(endpoint.sessionNamespace, `manifest.endpoints[${index}].sessionNamespace`),
165
+ streamMinIntervalMs: positiveInteger(endpoint.streamMinIntervalMs, `manifest.endpoints[${index}].streamMinIntervalMs`)
166
+ });
167
+ });
168
+ const automations = array(root.automations ?? [], "manifest.automations").map((entry, index) => {
169
+ const automation = record(entry, `manifest.automations[${index}]`);
170
+ exactKeys(automation, [
171
+ "agentId",
172
+ "delivery",
173
+ "enabled",
174
+ "id",
175
+ "required",
176
+ "schedule",
177
+ "templateId",
178
+ "timeZone"
179
+ ], `manifest.automations[${index}]`);
180
+ const delivery = record(automation.delivery, `manifest.automations[${index}].delivery`);
181
+ exactKeys(delivery, [
182
+ "endpointId",
183
+ "targetRef",
184
+ "targetType"
185
+ ], `manifest.automations[${index}].delivery`);
186
+ return Object.freeze({
187
+ agentId: string(automation.agentId, `manifest.automations[${index}].agentId`),
188
+ delivery: Object.freeze({
189
+ endpointId: string(delivery.endpointId, `manifest.automations[${index}].delivery.endpointId`),
190
+ targetRef: string(delivery.targetRef, `manifest.automations[${index}].delivery.targetRef`),
191
+ targetType: automationTargetType(delivery.targetType, `manifest.automations[${index}].delivery.targetType`)
192
+ }),
193
+ enabled: boolean(automation.enabled, `manifest.automations[${index}].enabled`),
194
+ id: string(automation.id, `manifest.automations[${index}].id`),
195
+ required: boolean(automation.required, `manifest.automations[${index}].required`),
196
+ schedule: string(automation.schedule, `manifest.automations[${index}].schedule`),
197
+ templateId: string(automation.templateId, `manifest.automations[${index}].templateId`),
198
+ timeZone: string(automation.timeZone, `manifest.automations[${index}].timeZone`)
199
+ });
200
+ });
201
+ const projectSpaces = array(root.projectSpaces ?? [], "manifest.projectSpaces").map((entry, index) => {
202
+ const projectSpace = record(entry, `manifest.projectSpaces[${index}]`);
203
+ exactKeys(projectSpace, [
204
+ "id",
205
+ "root",
206
+ "skills",
207
+ "workingDirectory"
208
+ ], `manifest.projectSpaces[${index}]`);
209
+ const skills = record(projectSpace.skills, `manifest.projectSpaces[${index}].skills`);
210
+ exactKeys(skills, ["sources"], `manifest.projectSpaces[${index}].skills`);
211
+ return Object.freeze({
212
+ id: string(projectSpace.id, `manifest.projectSpaces[${index}].id`),
213
+ root: string(projectSpace.root, `manifest.projectSpaces[${index}].root`),
214
+ skills: Object.freeze({ sources: Object.freeze(array(skills.sources, `manifest.projectSpaces[${index}].skills.sources`).map((item, itemIndex) => string(item, `manifest.projectSpaces[${index}].skills.sources[${itemIndex}]`))) }),
215
+ workingDirectory: string(projectSpace.workingDirectory, `manifest.projectSpaces[${index}].workingDirectory`)
216
+ });
217
+ });
218
+ const backgroundSessions = root.backgroundSessions === void 0 ? void 0 : parseBackgroundSessions(record(root.backgroundSessions, "manifest.backgroundSessions"));
219
+ return Object.freeze({
220
+ agents: Object.freeze(agents),
221
+ automations: Object.freeze(automations),
222
+ ...backgroundSessions ? { backgroundSessions } : {},
223
+ defaultAgentId: string(root.defaultAgentId, "manifest.defaultAgentId"),
224
+ defaultEndpointId: string(root.defaultEndpointId, "manifest.defaultEndpointId"),
225
+ endpoints: Object.freeze(endpoints),
226
+ plugins: Object.freeze(plugins),
227
+ projectSpaces: Object.freeze(projectSpaces)
581
228
  });
582
229
  }
583
- async function handleFrame(frame, socket, options) {
584
- let response;
585
- let request;
586
- try {
587
- request = parseRivusModelManagementWireRequest(JSON.parse(frame));
588
- } catch (error) {
589
- response = createRivusModelManagementFailure("invalid_request", error instanceof Error ? error.message : "invalid model request");
590
- writeResponse(socket, response);
591
- return;
230
+ function validateRivusDeploymentManifest(manifest) {
231
+ const projectSpaceIds = validateRivusProjectSpaceDeployments(manifest.projectSpaces ?? []);
232
+ const pluginIds = /* @__PURE__ */ new Set();
233
+ for (const plugin of manifest.plugins) {
234
+ if (pluginIds.has(plugin.id)) throw new Error(`duplicate plugin declaration: ${plugin.id}`);
235
+ validateModuleSpecifier(plugin.module);
236
+ pluginIds.add(plugin.id);
592
237
  }
593
- try {
594
- if (request.operation === "status") response = projectRivusModelCliResponse(await options.handlers.status({
595
- ...request.requestId ? { requestId: request.requestId } : {},
596
- ...request.verbose ? { verbose: true } : {}
597
- }), request.operation);
598
- else response = await handleMutation(request, options);
599
- } catch {
600
- response = createRivusModelManagementFailure("handler_failed", "the model management request could not be completed");
238
+ const agentIds = /* @__PURE__ */ new Set();
239
+ const agentById = /* @__PURE__ */ new Map();
240
+ for (const agent of manifest.agents) {
241
+ if (agentIds.has(agent.agentId)) throw new Error(`duplicate agent deployment: ${agent.agentId}`);
242
+ agentIds.add(agent.agentId);
243
+ if (!pluginIds.has(agent.pluginId)) throw new Error(`agent ${agent.agentId} references undeclared plugin: ${agent.pluginId}`);
244
+ if (agent.projectSpaceId && !projectSpaceIds.has(agent.projectSpaceId)) throw new Error(`agent ${agent.agentId} references unknown project space: ${agent.projectSpaceId}`);
245
+ agentById.set(agent.agentId, agent);
601
246
  }
602
- writeResponse(socket, response);
603
- }
604
- async function handleMutation(request, options) {
605
- if (!request.context || !options.resolveTrustedRun) return createRivusModelManagementFailure("trusted_context_required", "a trusted Run context is required for model changes");
606
- let trustedRun;
607
- try {
608
- trustedRun = await options.resolveTrustedRun.resolve(request.context);
609
- } catch {
610
- trustedRun = void 0;
247
+ const endpointIds = /* @__PURE__ */ new Set();
248
+ const sessionNamespaces = /* @__PURE__ */ new Set();
249
+ for (const endpoint of manifest.endpoints) {
250
+ if (endpointIds.has(endpoint.id)) throw new Error(`duplicate endpoint binding: ${endpoint.id}`);
251
+ endpointIds.add(endpoint.id);
252
+ if (sessionNamespaces.has(endpoint.sessionNamespace)) throw new Error(`duplicate endpoint session namespace: ${endpoint.sessionNamespace}`);
253
+ sessionNamespaces.add(endpoint.sessionNamespace);
254
+ const agent = agentById.get(endpoint.agentId);
255
+ if (!agent) throw new Error(`endpoint ${endpoint.id} references unknown agent: ${endpoint.agentId}`);
256
+ if (!agent.endpointIds.includes(endpoint.id)) throw new Error(`endpoint ${endpoint.id} is not declared by agent ${endpoint.agentId}`);
611
257
  }
612
- if (trustedRun === void 0 || trustedRun === null) return createRivusModelManagementFailure("trusted_context_invalid", "the trusted Run context is invalid or expired");
613
- try {
614
- return projectRivusModelCliResponse(await options.handlers.handle(toRivusModelManagementSubmission(request), trustedRun), request.operation);
615
- } catch {
616
- return createRivusModelManagementFailure("handler_failed", "the model management request could not be completed");
258
+ for (const agent of manifest.agents) for (const endpointId of agent.endpointIds) {
259
+ const endpoint = manifest.endpoints.find(({ id }) => id === endpointId);
260
+ if (!endpoint) throw new Error(`agent ${agent.agentId} references unknown endpoint: ${endpointId}`);
261
+ if (endpoint.agentId !== agent.agentId) throw new Error(`endpoint ${endpointId} is bound to a different agent`);
617
262
  }
618
- }
619
- function writeResponse(socket, response) {
620
- try {
621
- socket.end(`${JSON.stringify(response)}\n`);
622
- } catch {
623
- socket.destroy();
263
+ const automationIds = /* @__PURE__ */ new Set();
264
+ for (const automation of manifest.automations ?? []) {
265
+ if (automationIds.has(automation.id)) throw new Error(`duplicate automation binding: ${automation.id}`);
266
+ automationIds.add(automation.id);
267
+ if (!agentById.has(automation.agentId)) throw new Error(`automation ${automation.id} references unknown agent: ${automation.agentId}`);
268
+ const endpoint = manifest.endpoints.find(({ id }) => id === automation.delivery.endpointId);
269
+ if (!endpoint) throw new Error(`automation ${automation.id} references unknown delivery endpoint: ${automation.delivery.endpointId}`);
270
+ if (automation.enabled && !endpoint.enabled) throw new Error(`automation ${automation.id} delivery endpoint must be enabled`);
624
271
  }
272
+ const defaultAgent = agentById.get(manifest.defaultAgentId);
273
+ if (!defaultAgent) throw new Error(`default agent does not exist: ${manifest.defaultAgentId}`);
274
+ const defaultEndpoint = manifest.endpoints.find(({ id }) => id === manifest.defaultEndpointId);
275
+ if (!defaultEndpoint) throw new Error(`default endpoint does not exist: ${manifest.defaultEndpointId}`);
276
+ if (defaultEndpoint.agentId !== defaultAgent.agentId) throw new Error("default endpoint is not bound to the default agent");
277
+ if (!defaultEndpoint.enabled) throw new Error("default endpoint must be enabled");
278
+ if (manifest.backgroundSessions) validateBackgroundSessions(manifest.backgroundSessions);
625
279
  }
626
- async function prepareSocketPath(socketPath) {
627
- try {
628
- const metadata = await stat(socketPath);
629
- if (!metadata.isSocket()) throw new Error(`refusing to replace non-socket model path: ${socketPath}`);
630
- if (await socketIsLive(socketPath)) throw new Error(`model management socket is already active: ${socketPath}`);
631
- const current = await stat(socketPath);
632
- if (current.dev !== metadata.dev || current.ino !== metadata.ino) throw new Error(`model management socket changed while starting: ${socketPath}`);
633
- await unlink(socketPath);
634
- } catch (error) {
635
- if (!isMissing$2(error)) throw error;
636
- }
280
+ function validateBackgroundSessions(config) {
281
+ if (config.required && !config.enabled) throw new Error("backgroundSessions.required requires backgroundSessions.enabled");
282
+ if (config.leaseRenewalIntervalMs >= config.leaseMs) throw new Error("backgroundSessions.leaseRenewalIntervalMs must be shorter than leaseMs");
283
+ if (config.stepTimeoutMs <= 0 || config.maxConcurrentSessions <= 0 || config.leaseMs <= 0) throw new Error("backgroundSessions durations and concurrency must be positive");
284
+ if (config.retryBackoffMs <= 0 || config.sessionLifetimeMs <= 0 || config.maxConsecutiveFailures <= 0) throw new Error("backgroundSessions retry and lifetime limits must be positive");
637
285
  }
638
- async function prepareSocketParentDirectory(socketPath) {
639
- const parent = dirname(socketPath);
640
- await mkdir(parent, {
641
- mode: 448,
642
- recursive: true
643
- });
644
- await chmod(parent, 448);
286
+ function validateModuleSpecifier(moduleSpecifier) {
287
+ const absolutePath = moduleSpecifier.startsWith("/") || moduleSpecifier.startsWith("\\\\") || /^[a-zA-Z]:[\\/]/.test(moduleSpecifier);
288
+ if (moduleSpecifier.trim() === "" || absolutePath || /^[a-z][a-z+.-]*:/i.test(moduleSpecifier) || moduleSpecifier.includes("\0")) throw new Error(`invalid plugin module specifier: ${moduleSpecifier}`);
289
+ if ((moduleSpecifier.startsWith("./") || moduleSpecifier.startsWith("../")) && moduleSpecifier.split(/[\\/]/).includes("..")) throw new Error(`plugin module escapes deployment root: ${moduleSpecifier}`);
645
290
  }
646
- async function socketIsLive(socketPath) {
647
- return new Promise((resolve, reject) => {
648
- const socket = createConnection(socketPath);
649
- let settled = false;
650
- const finish = (result, error) => {
651
- if (settled) return;
652
- settled = true;
653
- socket.destroy();
654
- if (error) reject(error);
655
- else resolve(result);
656
- };
657
- socket.setTimeout(250, () => finish(false, /* @__PURE__ */ new Error("model management socket liveness could not be verified")));
658
- socket.once("connect", () => finish(true));
659
- socket.once("error", (error) => {
660
- if (error.code === "ECONNREFUSED" || error.code === "ENOENT") finish(false);
661
- else finish(false, error);
662
- });
291
+ function parseBackgroundSessions(value) {
292
+ exactKeys(value, [
293
+ "enabled",
294
+ "leaseMs",
295
+ "leaseRenewalIntervalMs",
296
+ "maxConsecutiveFailures",
297
+ "maxConcurrentSessions",
298
+ "required",
299
+ "retryBackoffMs",
300
+ "sessionLifetimeMs",
301
+ "stepTimeoutMs"
302
+ ], "manifest.backgroundSessions", [
303
+ "leaseMs",
304
+ "leaseRenewalIntervalMs",
305
+ "maxConsecutiveFailures",
306
+ "maxConcurrentSessions",
307
+ "retryBackoffMs",
308
+ "sessionLifetimeMs",
309
+ "stepTimeoutMs"
310
+ ]);
311
+ return Object.freeze({
312
+ enabled: boolean(value.enabled, "manifest.backgroundSessions.enabled"),
313
+ leaseMs: positiveInteger(value.leaseMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_MS, "manifest.backgroundSessions.leaseMs"),
314
+ leaseRenewalIntervalMs: positiveInteger(value.leaseRenewalIntervalMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_RENEWAL_INTERVAL_MS, "manifest.backgroundSessions.leaseRenewalIntervalMs"),
315
+ maxConsecutiveFailures: positiveInteger(value.maxConsecutiveFailures ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_MAX_CONSECUTIVE_FAILURES, "manifest.backgroundSessions.maxConsecutiveFailures"),
316
+ maxConcurrentSessions: positiveInteger(value.maxConcurrentSessions ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_MAX_CONCURRENT_SESSIONS, "manifest.backgroundSessions.maxConcurrentSessions"),
317
+ required: boolean(value.required, "manifest.backgroundSessions.required"),
318
+ retryBackoffMs: positiveInteger(value.retryBackoffMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_RETRY_BACKOFF_MS, "manifest.backgroundSessions.retryBackoffMs"),
319
+ sessionLifetimeMs: positiveInteger(value.sessionLifetimeMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_LIFETIME_MS, "manifest.backgroundSessions.sessionLifetimeMs"),
320
+ stepTimeoutMs: positiveInteger(value.stepTimeoutMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_STEP_TIMEOUT_MS, "manifest.backgroundSessions.stepTimeoutMs")
663
321
  });
664
322
  }
665
- async function acquireStartLock(path) {
666
- for (let attempt = 0; attempt < 3; attempt += 1) {
667
- let handle;
668
- try {
669
- handle = await open(path, "wx", 384);
670
- await handle.writeFile(`${process.pid}\n`, "utf8");
671
- const metadata = await handle.stat();
672
- return {
673
- handle,
674
- identity: {
675
- dev: metadata.dev,
676
- ino: metadata.ino
677
- }
678
- };
679
- } catch (error) {
680
- await handle?.close().catch(() => void 0);
681
- if (!isAlreadyExists(error)) throw new Error("model management socket startup is already in progress", { cause: error });
682
- const pid = parseLockOwner(await readPersistenceFile(path));
683
- if (pid === void 0) throw new Error("model management socket startup lock owner could not be verified; manual recovery is required");
684
- if (processIsAlive(pid)) throw new Error("model management socket startup is already in progress");
685
- const reclaimed = `${path}.reclaim-${process.pid}-${randomUUID()}`;
686
- try {
687
- await rename(path, reclaimed);
688
- } catch (reclaimError) {
689
- if (isMissing$2(reclaimError)) continue;
690
- throw new Error("model management socket startup lock could not be reclaimed safely", { cause: reclaimError });
691
- }
692
- await unlink(reclaimed).catch((reclaimError) => {
693
- if (!isMissing$2(reclaimError)) throw reclaimError;
694
- });
695
- }
696
- }
697
- throw new Error("model management socket startup lock changed during stale-owner recovery; manual recovery is required");
323
+ function record(value, path) {
324
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(`${path} must be an object`);
325
+ return value;
698
326
  }
699
- async function releaseStartLock(lock, path) {
700
- await lock.handle.close();
701
- try {
702
- const current = await stat(path);
703
- if (current.dev !== lock.identity.dev || current.ino !== lock.identity.ino) return;
704
- await unlink(path);
705
- } catch (error) {
706
- if (!isMissing$2(error)) throw error;
707
- }
327
+ function array(value, path) {
328
+ if (!Array.isArray(value)) throw new Error(`${path} must be an array`);
329
+ return value;
708
330
  }
709
- async function unlinkSocketIfPresent(socketPath) {
710
- try {
711
- if ((await stat(socketPath)).isSocket()) await unlink(socketPath);
712
- } catch (error) {
713
- if (!isMissing$2(error)) throw error;
714
- }
331
+ function string(value, path) {
332
+ if (typeof value !== "string" || value.trim() === "") throw new Error(`${path} must be a non-empty string`);
333
+ return value;
715
334
  }
716
- async function unlinkOwnedSocket(socketPath, identity) {
717
- try {
718
- const current = await readSocketIdentity(socketPath);
719
- if (current.dev !== identity.dev || current.ino !== identity.ino) return;
720
- await unlink(socketPath);
721
- } catch (error) {
722
- if (!isMissing$2(error)) throw error;
723
- }
335
+ function boolean(value, path) {
336
+ if (typeof value !== "boolean") throw new Error(`${path} must be a boolean`);
337
+ return value;
724
338
  }
725
- async function readSocketIdentity(socketPath) {
726
- const metadata = await stat(socketPath);
727
- return {
728
- dev: metadata.dev,
729
- ino: metadata.ino
730
- };
339
+ function positiveInteger(value, path) {
340
+ if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`${path} must be a positive integer`);
341
+ return value;
731
342
  }
732
- function listen(server, socketPath) {
733
- return new Promise((resolve, reject) => {
734
- const onError = (error) => {
735
- server.off("listening", onListening);
736
- reject(error);
737
- };
738
- const onListening = () => {
739
- server.off("error", onError);
740
- resolve();
741
- };
742
- server.once("error", onError);
743
- server.once("listening", onListening);
744
- server.listen(socketPath);
745
- });
343
+ function memoryScope(value, path) {
344
+ if (typeof value !== "string" || !MEMORY_SCOPES.includes(value)) throw new Error(`${path} must be conversation, agent-private, project, or shared-user-profile`);
345
+ return value;
746
346
  }
747
- function closeServer(server) {
748
- return new Promise((resolve, reject) => {
749
- server.close((error) => error ? reject(error) : resolve());
750
- });
347
+ function groupPolicy(value, path) {
348
+ if (value !== "mention-only" && value !== "ignore-unmentioned" && value !== "default-responder") throw new Error(`${path} must be mention-only, ignore-unmentioned, or default-responder`);
349
+ return value;
751
350
  }
752
- function assertAbsoluteSocketPath(socketPath) {
753
- if (!isAbsolute(socketPath)) throw new Error("model socket path must be absolute");
351
+ function progressDisplay(value, path) {
352
+ if (value !== "hidden" && value !== "collapsed" && value !== "expanded") throw new Error(`${path} must be hidden, collapsed, or expanded`);
353
+ return value;
754
354
  }
755
- function isMissing$2(error) {
756
- return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
355
+ function runtimeToolId(value, path) {
356
+ const id = string(value, path);
357
+ if (!isRivusRuntimeToolId(id)) throw new Error(`${path} must be read, bash, edit, write, grep, find, or ls`);
358
+ return id;
359
+ }
360
+ function uniqueRuntimeTools(ids, path) {
361
+ const result = /* @__PURE__ */ new Set();
362
+ for (const id of ids) {
363
+ if (result.has(id)) throw new Error(`${path} contains duplicate Runtime Tool: ${id}`);
364
+ result.add(id);
365
+ }
366
+ return [...result];
367
+ }
368
+ function automationTargetType(value, path) {
369
+ 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`);
370
+ return value;
757
371
  }
758
- function isAlreadyExists(error) {
759
- return typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST";
372
+ function exactKeys(value, allowed, path, optional = []) {
373
+ const unexpected = Object.keys(value).find((key) => !allowed.includes(key));
374
+ if (unexpected) throw new Error(`${path} contains unsupported field: ${unexpected}`);
375
+ const missing = allowed.find((key) => !optional.includes(key) && !Object.hasOwn(value, key));
376
+ if (missing) throw new Error(`${path} is missing required field: ${missing}`);
760
377
  }
761
- function processIsAlive(pid) {
762
- try {
763
- process.kill(pid, 0);
764
- return true;
765
- } catch (error) {
766
- return typeof error === "object" && error !== null && "code" in error && error.code !== "ESRCH";
767
- }
378
+ //#endregion
379
+ //#region src/adapters/feishu/config/feishu-endpoint-credentials.ts
380
+ var FeishuEndpointCredentialError = class extends Error {
381
+ name = "FeishuEndpointCredentialError";
382
+ };
383
+ function resolveFeishuEndpointCredentials(credentialRef, env) {
384
+ if (!credentialRef.startsWith("env:")) throw new FeishuEndpointCredentialError("Feishu endpoint credentialRef must use env:<PREFIX>");
385
+ const prefix = credentialRef.slice(4);
386
+ if (!/^[A-Z][A-Z0-9_]*$/.test(prefix)) throw new FeishuEndpointCredentialError(`Invalid environment prefix in credentialRef: ${credentialRef}`);
387
+ return Object.freeze({
388
+ appId: required$1(env, `${prefix}_APP_ID`),
389
+ appSecret: required$1(env, `${prefix}_APP_SECRET`)
390
+ });
768
391
  }
769
- function parseLockOwner(value) {
770
- const normalized = value?.trim();
771
- if (!normalized || !/^\d+$/.test(normalized)) return void 0;
772
- const pid = Number(normalized);
773
- return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
392
+ function required$1(env, variable) {
393
+ const value = env[variable]?.trim();
394
+ if (!value) throw new FeishuEndpointCredentialError(`${variable} is required`);
395
+ return value;
774
396
  }
775
397
  //#endregion
776
398
  //#region src/platform/home/config/runtime/local-env-file.ts
@@ -829,822 +451,842 @@ function unescapeDoubleQuotedValue(value) {
829
451
  });
830
452
  }
831
453
  //#endregion
832
- //#region src/platform/home/config/model-management/rivus-model-management-config-migration.ts
833
- const RIVUS_MODEL_MANAGEMENT_ENABLED_ENV = "RIVUS_MODEL_MANAGEMENT_ENABLED";
834
- const RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID_ENV = "RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID";
835
- const RIVUS_MODEL_MANAGEMENT_TENANT_KEY_ENV = "RIVUS_MODEL_MANAGEMENT_TENANT_KEY";
836
- const RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL_ENV = "RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL";
837
- var RivusModelManagementConfigError = class extends Error {
838
- code;
839
- name = "RivusModelManagementConfigError";
840
- constructor(code, message) {
841
- super(message);
842
- this.code = code;
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;
843
462
  }
844
463
  };
845
- /** Parse the Home capability flags without accepting truthy arbitrary strings. */
846
- function parseRivusModelManagementHomeConfig(env) {
847
- const enabled = parseRivusModelManagementEnabled(env[RIVUS_MODEL_MANAGEMENT_ENABLED_ENV]);
848
- const requireApproval = parseStrictBoolean(env[RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL_ENV], RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL_ENV, false);
849
- const ownerOpenId = optional$1(env[RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID_ENV]);
850
- const tenantKey = optional$1(env[RIVUS_MODEL_MANAGEMENT_TENANT_KEY_ENV]);
851
- if (enabled && !ownerOpenId) throw new RivusModelManagementConfigError("owner_missing", `${RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID_ENV} is required when model management is enabled`);
852
- if (enabled && !tenantKey) throw new RivusModelManagementConfigError("tenant_missing", `${RIVUS_MODEL_MANAGEMENT_TENANT_KEY_ENV} is required when model management is enabled`);
853
- return Object.freeze({
854
- enabled,
855
- ...ownerOpenId ? { ownerOpenId } : {},
856
- requireApproval,
857
- ...tenantKey ? { tenantKey } : {}
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
+ };
858
502
  });
859
503
  }
860
- function parseRivusModelManagementEnabled(value) {
861
- return parseStrictBoolean(value, RIVUS_MODEL_MANAGEMENT_ENABLED_ENV, false);
862
- }
863
- function parseStrictBoolean(value, variable, defaultValue) {
864
- if (value === void 0) return defaultValue;
865
- const normalized = value.trim();
866
- if (normalized === "true") return true;
867
- if (normalized === "false") return false;
868
- throw new RivusModelManagementConfigError("invalid_enabled", `${variable} must be true or false`);
869
- }
870
- /**
871
- * Migrate only the legacy model selection at the explicit enable/disable
872
- * boundary. The helper does not read or write managed model state.
873
- */
874
- async function migrateRivusModelManagementConfig(input) {
875
- if (typeof input.managementEnabled !== "boolean") throw new RivusModelManagementConfigError("invalid_enabled", "model management enabled state must be boolean");
876
- if (input.managementEnabled) return enableModelManagement(input);
877
- return disableModelManagement(input, parseModelReference(input.knownGoodProvider, input.knownGoodModel));
878
- }
879
- async function enableModelManagement(input) {
880
- if (hasAmbientModelOverride(input.env)) return {
881
- initialModel: parseConfiguredModel(input.env.PI_MODEL),
882
- source: "ambient",
883
- status: "enabled"
884
- };
885
- return {
886
- initialModel: parseConfiguredModel((await loadEnvFile(requireEnvFilePath(input.envFilePath), input.env)).PI_MODEL),
887
- source: "env-file",
888
- status: "enabled"
889
- };
504
+ function optional(value) {
505
+ const trimmed = value?.trim();
506
+ return trimmed ? trimmed : void 0;
890
507
  }
891
- async function disableModelManagement(input, knownGood) {
892
- const envFilePath = requireEnvFilePath(input.envFilePath);
893
- if (hasAmbientModelOverride(input.env)) throw new RivusModelManagementConfigError("ambient_model_override", "ambient PI_MODEL overrides the original env source and prevents verified model readback");
894
- const original = await readWritableEnvFile(envFilePath);
895
- const existingModel = parseOptionalConfiguredModel((await loadEnvFile(envFilePath, input.env)).PI_MODEL);
896
- if (existingModel && sameModel(existingModel, knownGood)) return {
897
- restoredModel: knownGood,
898
- source: "env-file",
899
- status: "unchanged"
900
- };
901
- const next = replacePiModel(original, knownGood);
902
- try {
903
- await input.writeAtomicTextFile(envFilePath, next, { durable: true });
904
- } catch {
905
- throw new RivusModelManagementConfigError("env_source_write_failed", "the original env source write did not complete with a known durable result");
906
- }
907
- let readBack;
908
- try {
909
- readBack = parseConfiguredModel((await loadMergedLocalEnvFile(envFilePath, input.env)).PI_MODEL);
910
- } catch {
911
- throw new RivusModelManagementConfigError("readback_mismatch", "the original env source could not be verified after restoring PI_MODEL");
912
- }
913
- 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");
914
- return {
915
- restoredModel: knownGood,
916
- source: "env-file",
917
- status: "exported"
918
- };
508
+ function readUtf8File(path) {
509
+ return readFile(path, "utf8");
919
510
  }
920
- function parseModelReference(provider, model) {
921
- if (!isModelPart(provider) || !isModelPart(model)) throw new RivusModelManagementConfigError("invalid_model", "known-good model provider and id are invalid");
922
- return Object.freeze({
923
- model,
924
- provider
925
- });
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
+ }));
926
524
  }
927
- function parseConfiguredModel(value) {
928
- const configured = optional$1(value);
929
- if (!configured) throw new RivusModelManagementConfigError("model_missing", "PI_MODEL is missing from the effective legacy config");
930
- const separator = configured.indexOf("/");
931
- if (separator <= 0 || separator === configured.length - 1 || configured.indexOf("/", separator + 1) !== -1) throw new RivusModelManagementConfigError("invalid_model", "PI_MODEL must use provider/model form");
932
- return parseModelReference(configured.slice(0, separator), configured.slice(separator + 1));
525
+ function formatConfigError(error) {
526
+ return error instanceof Error ? error.message : String(error);
933
527
  }
934
- function parseOptionalConfiguredModel(value) {
935
- if (!optional$1(value)) return void 0;
936
- try {
937
- return parseConfiguredModel(value);
938
- } catch {
939
- return;
940
- }
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`));
941
533
  }
942
- function sameModel(left, right) {
943
- return left.provider === right.provider && left.model === right.model;
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`));
944
538
  }
945
- async function loadEnvFile(envFilePath, env) {
946
- try {
947
- return await loadMergedLocalEnvFile(envFilePath, env);
948
- } catch {
949
- throw new RivusModelManagementConfigError("env_source_unreadable", "the original env source could not be loaded");
950
- }
539
+ function optionalThinkingLevel(value) {
540
+ 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"));
951
544
  }
952
- async function readWritableEnvFile(envFilePath) {
953
- try {
954
- const contents = await readFile(envFilePath, "utf8");
955
- if (((await stat(envFilePath)).mode & 146) === 0) throw new RivusModelManagementConfigError("env_source_unwritable", "the original env source is not writable");
956
- await access(envFilePath, constants.W_OK);
957
- return contents;
958
- } catch (error) {
959
- if (error instanceof RivusModelManagementConfigError) throw error;
960
- if (isPermissionError(error)) throw new RivusModelManagementConfigError("env_source_unwritable", "the original env source is not writable");
961
- throw new RivusModelManagementConfigError("env_source_unreadable", "the original env source is unavailable");
545
+ //#endregion
546
+ //#region src/adapters/deployment/manifest/node-rivus-deployment-manifest.ts
547
+ var RivusDeploymentManifestError = class extends Error {
548
+ manifestPath;
549
+ name = "RivusDeploymentManifestError";
550
+ constructor(manifestPath, message, options) {
551
+ super(message, options);
552
+ this.manifestPath = manifestPath;
962
553
  }
554
+ };
555
+ function loadRivusDeploymentManifest(manifestPath, options = {}) {
556
+ const maxBytes = options.maxBytes ?? 1048576;
557
+ return Effect.tryPromise({
558
+ try: async () => {
559
+ const metadata = await stat(manifestPath);
560
+ if (!metadata.isFile()) throw new Error("deployment manifest must be a regular file");
561
+ if (metadata.size > maxBytes) throw new Error(`deployment manifest exceeds ${maxBytes} byte limit`);
562
+ const bytes = await readFile(manifestPath);
563
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
564
+ return parseRivusDeploymentManifest(JSON.parse(text));
565
+ },
566
+ catch: (cause) => cause instanceof RivusDeploymentManifestError ? cause : new RivusDeploymentManifestError(manifestPath, `failed to load Rivus deployment manifest: ${cause instanceof Error ? cause.message : String(cause)}`, { cause })
567
+ });
963
568
  }
964
- function replacePiModel(contents, model) {
965
- const modelValue = `${model.provider}/${model.model}`;
966
- const parts = contents.split(/(\r\n|\n|\r)/);
967
- let replaced = false;
968
- for (let index = 0; index < parts.length; index += 2) {
969
- const line = parts[index];
970
- if (line === void 0) continue;
971
- const match = line.match(/^(\s*(?:export\s+)?PI_MODEL\s*=\s*)(.*)$/);
972
- if (!match) continue;
973
- const inlineComment = match[2].match(/(\s+#.*)$/)?.[1] ?? "";
974
- parts[index] = `${match[1]}${modelValue}${inlineComment}`;
975
- replaced = true;
569
+ //#endregion
570
+ //#region src/platform/project/setup/gateway-package-resources.ts
571
+ const packageManifestUrl = import.meta.resolve("@rivus/gateway/package.json");
572
+ const packageRootUrl = new URL("./", packageManifestUrl);
573
+ const gatewayPackageDirectory = fileURLToPath(packageRootUrl);
574
+ const gatewayPackageManifestPath = fileURLToPath(new URL("package.json", packageRootUrl));
575
+ const gatewayTemplateDirectory = fileURLToPath(new URL("templates/", packageRootUrl));
576
+ const gatewaySkillsDirectory = fileURLToPath(new URL("skills/", packageRootUrl));
577
+ //#endregion
578
+ //#region src/adapters/cli/model/rivus-model-cli-protocol.ts
579
+ const RIVUS_MODEL_CLI_USAGE = `Usage:
580
+ rivus model status --json [--request <id>] [--verbose]
581
+ rivus model set --model <provider/model> --expected-revision <n> --request <id> --json [--verbose]
582
+ rivus model rollback --expected-revision <n> --request <id> --json [--verbose]
583
+
584
+ Commands:
585
+ status Read the effective and persistent model selection
586
+ set Submit one authorized model change
587
+ rollback Submit one authorized change to the previous model
588
+
589
+ All command results are JSON. A successful set or rollback call means the request
590
+ was accepted; query status by request id for the final outcome.
591
+ `;
592
+ function parseRivusModelCliArguments(argv) {
593
+ if (argv.includes("--help") || argv.includes("-h")) return { help: true };
594
+ const operation = argv[0];
595
+ if (operation !== "status" && operation !== "set" && operation !== "rollback") return { error: "model requires one of status, set, rollback" };
596
+ let expectedRevision;
597
+ let json = false;
598
+ let model;
599
+ let requestId;
600
+ let verbose = false;
601
+ for (let index = 1; index < argv.length; index += 1) {
602
+ const argument = argv[index];
603
+ if (argument === "--json") {
604
+ if (json) return { error: "--json may only be provided once" };
605
+ json = true;
606
+ continue;
607
+ }
608
+ if (argument === "--verbose") {
609
+ if (verbose) return { error: "--verbose may only be provided once" };
610
+ verbose = true;
611
+ continue;
612
+ }
613
+ if (argument === "--request") {
614
+ if (requestId !== void 0) return { error: "--request may only be provided once" };
615
+ const value = argv[index + 1];
616
+ if (!value || value.startsWith("-")) return { error: "--request requires an id" };
617
+ requestId = value;
618
+ index += 1;
619
+ continue;
620
+ }
621
+ if (argument.startsWith("--request=")) {
622
+ if (requestId !== void 0) return { error: "--request may only be provided once" };
623
+ requestId = argument.slice(10);
624
+ if (!requestId) return { error: "--request requires an id" };
625
+ continue;
626
+ }
627
+ if (argument === "--expected-revision") {
628
+ if (expectedRevision !== void 0) return { error: "--expected-revision may only be provided once" };
629
+ const value = argv[index + 1];
630
+ if (!value || value.startsWith("-")) return { error: "--expected-revision requires a non-negative integer" };
631
+ const parsed = parseRevision(value);
632
+ if (parsed === void 0) return { error: "--expected-revision requires a non-negative integer" };
633
+ expectedRevision = parsed;
634
+ index += 1;
635
+ continue;
636
+ }
637
+ if (argument.startsWith("--expected-revision=")) {
638
+ if (expectedRevision !== void 0) return { error: "--expected-revision may only be provided once" };
639
+ const parsed = parseRevision(argument.slice(20));
640
+ if (parsed === void 0) return { error: "--expected-revision requires a non-negative integer" };
641
+ expectedRevision = parsed;
642
+ continue;
643
+ }
644
+ if (argument === "--model") {
645
+ if (model !== void 0) return { error: "--model may only be provided once" };
646
+ const value = argv[index + 1];
647
+ if (!value || value.startsWith("-")) return { error: "--model requires provider/model" };
648
+ if (!isModelReference(value)) return { error: "--model must be provider/model" };
649
+ model = value;
650
+ index += 1;
651
+ continue;
652
+ }
653
+ if (argument.startsWith("--model=")) {
654
+ if (model !== void 0) return { error: "--model may only be provided once" };
655
+ const value = argument.slice(8);
656
+ if (!isModelReference(value)) return { error: "--model must be provider/model" };
657
+ model = value;
658
+ continue;
659
+ }
660
+ return { error: `Unknown model option: ${argument}` };
661
+ }
662
+ if (!json) return { error: "model commands require --json" };
663
+ if (operation === "status") {
664
+ if (model !== void 0) return { error: "status does not accept --model" };
665
+ if (expectedRevision !== void 0) return { error: "status does not accept --expected-revision" };
666
+ return {
667
+ json: true,
668
+ operation,
669
+ ...requestId !== void 0 ? { requestId } : {},
670
+ ...verbose ? { verbose: true } : {}
671
+ };
976
672
  }
977
- if (replaced) return parts.join("");
978
- const newline = contents.includes("\r\n") ? "\r\n" : contents.includes("\n") ? "\n" : "\n";
979
- if (!contents) return `PI_MODEL=${modelValue}${newline}`;
980
- return /(?:\r\n|\n|\r)$/.test(contents) ? `${contents}PI_MODEL=${modelValue}${newline}` : `${contents}${newline}PI_MODEL=${modelValue}`;
981
- }
982
- function requireEnvFilePath(value) {
983
- const normalized = optional$1(value);
984
- if (!normalized) throw new RivusModelManagementConfigError("env_source_missing", "an explicit writable original env source is required for model management migration");
985
- return normalized;
673
+ if (requestId === void 0) return { error: "--request is required for model changes" };
674
+ if (expectedRevision === void 0) return { error: "--expected-revision is required for model changes" };
675
+ if (operation === "set" && model === void 0) return { error: "--model is required for model set" };
676
+ if (operation === "rollback" && model !== void 0) return { error: "rollback does not accept --model" };
677
+ return operation === "set" ? {
678
+ expectedRevision,
679
+ json: true,
680
+ model,
681
+ operation,
682
+ requestId,
683
+ ...verbose ? { verbose: true } : {}
684
+ } : {
685
+ expectedRevision,
686
+ json: true,
687
+ operation,
688
+ requestId,
689
+ ...verbose ? { verbose: true } : {}
690
+ };
986
691
  }
987
- function hasAmbientModelOverride(env) {
988
- return Object.prototype.hasOwnProperty.call(env, "PI_MODEL") && env.PI_MODEL !== void 0;
692
+ function renderRivusModelCliHelp() {
693
+ return RIVUS_MODEL_CLI_USAGE;
989
694
  }
990
- function isModelPart(value) {
991
- return value.trim() === value && value.length > 0 && !/[/\s]/.test(value);
695
+ function renderRivusModelCliArgumentError(error) {
696
+ return `${error}\n\n${RIVUS_MODEL_CLI_USAGE}`;
992
697
  }
993
- function optional$1(value) {
994
- return value?.trim() || void 0;
698
+ function isModelReference(value) {
699
+ return /^[^/\s]+\/[^/\s]+$/.test(value);
995
700
  }
996
- function isPermissionError(error) {
997
- return typeof error === "object" && error !== null && "code" in error && (error.code === "EACCES" || error.code === "EPERM" || error.code === "EROFS");
701
+ function parseRevision(value) {
702
+ if (!/^\d+$/.test(value)) return;
703
+ const revision = Number(value);
704
+ return Number.isSafeInteger(revision) ? revision : void 0;
998
705
  }
999
706
  //#endregion
1000
- //#region src/platform/home/config/model-management/rivus-runtime-management-skill-installer.ts
1001
- const SKILL_NAME = "runtime-management";
1002
- const SKILL_FILE = "SKILL.md";
1003
- const INSTALL_METADATA_FILE = ".rivus-install.json";
1004
- async function installRivusRuntimeManagementSkill(options) {
1005
- const writeAtomicTextFile = options.writeAtomicTextFile;
1006
- const skillDirectory = join(options.homeDirectory ?? homedir(), ".agents", "skills", SKILL_NAME);
1007
- const destination = join(skillDirectory, SKILL_FILE);
1008
- const metadataPath = join(skillDirectory, INSTALL_METADATA_FILE);
1009
- const source = await readFile(options.sourcePath, "utf8");
1010
- const sourceDigest = digest(source);
1011
- await mkdir(skillDirectory, { recursive: true });
1012
- const current = await readOptional(destination);
1013
- if (current === void 0) {
1014
- await writeAtomicTextFile(destination, source, { mode: 384 });
1015
- await writeMetadata(metadataPath, sourceDigest, writeAtomicTextFile);
707
+ //#region src/adapters/cli/model/rivus-model-management-wire.ts
708
+ function createRivusModelManagementWireRequest(command, env) {
709
+ const context = optionalString(env.RIVUS_MODEL_CONTEXT);
710
+ return {
711
+ ...command,
712
+ ...context ? { context } : {}
713
+ };
714
+ }
715
+ function parseRivusModelManagementWireRequest(value) {
716
+ if (!isRecord$1(value)) throw new Error("model request must be a JSON object");
717
+ const operation = value.operation;
718
+ if (operation !== "status" && operation !== "set" && operation !== "rollback") throw new Error("model request operation is invalid");
719
+ const context = optionalString(value.context);
720
+ const requestId = optionalString(value.requestId);
721
+ const verbose = value.verbose === true ? true : void 0;
722
+ if (operation === "status") {
723
+ if (value.json !== true) throw new Error("model request must require JSON output");
1016
724
  return {
1017
- destination,
1018
- requiresRefresh: true,
1019
- sourceDigest,
1020
- status: "installed"
725
+ json: true,
726
+ operation,
727
+ ...context ? { context } : {},
728
+ ...requestId ? { requestId } : {},
729
+ ...verbose ? { verbose: true } : {}
1021
730
  };
1022
731
  }
1023
- const currentDigest = digest(current);
1024
- if (currentDigest === sourceDigest) {
1025
- await writeMetadata(metadataPath, sourceDigest, writeAtomicTextFile);
732
+ const expectedRevision = value.expectedRevision;
733
+ 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");
734
+ if (!requestId) throw new Error("model request requires a request id");
735
+ if (operation === "set") {
736
+ const model = optionalString(value.model);
737
+ if (!model || !/^[^/\s]+\/[^/\s]+$/.test(model)) throw new Error("model request target is invalid");
1026
738
  return {
1027
- destination,
1028
- requiresRefresh: false,
1029
- sourceDigest,
1030
- status: "unchanged"
739
+ expectedRevision,
740
+ json: true,
741
+ model,
742
+ operation,
743
+ requestId,
744
+ ...context ? { context } : {},
745
+ ...verbose ? { verbose: true } : {}
1031
746
  };
1032
747
  }
1033
- if ((await readMetadata(metadataPath))?.installedDigest !== currentDigest) return {
1034
- destination,
1035
- requiresRefresh: false,
1036
- sourceDigest,
1037
- status: "conflict"
1038
- };
1039
- await writeAtomicTextFile(destination, source, { mode: 384 });
1040
- await writeMetadata(metadataPath, sourceDigest, writeAtomicTextFile);
1041
748
  return {
1042
- destination,
1043
- requiresRefresh: true,
1044
- sourceDigest,
1045
- status: "updated"
749
+ expectedRevision,
750
+ json: true,
751
+ operation,
752
+ requestId,
753
+ ...context ? { context } : {},
754
+ ...verbose ? { verbose: true } : {}
1046
755
  };
1047
756
  }
1048
- function digest(value) {
1049
- return createHash("sha256").update(value, "utf8").digest("hex");
1050
- }
1051
- async function readOptional(path) {
1052
- try {
1053
- return await readFile(path, "utf8");
1054
- } catch (error) {
1055
- if (isMissing$1(error)) return void 0;
1056
- throw error;
1057
- }
1058
- }
1059
- async function readMetadata(path) {
1060
- const contents = await readOptional(path);
1061
- if (contents === void 0) return void 0;
1062
- try {
1063
- const value = JSON.parse(contents);
1064
- if (!isRecord$1(value) || typeof value.installedDigest !== "string") return void 0;
1065
- return { installedDigest: value.installedDigest };
1066
- } catch {
1067
- return;
1068
- }
1069
- }
1070
- async function writeMetadata(path, installedDigest, writeAtomicTextFile) {
1071
- await writeAtomicTextFile(path, `${JSON.stringify({
1072
- installedDigest,
1073
- version: 1
1074
- }, null, 2)}\n`, { mode: 384 });
1075
- }
1076
- function isRecord$1(value) {
1077
- return typeof value === "object" && value !== null && !Array.isArray(value);
1078
- }
1079
- function isMissing$1(error) {
1080
- return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
1081
- }
1082
- //#endregion
1083
- //#region src/platform/home/config/model-management/rivus-model-management-cli-launcher.ts
1084
- const BIN_DIRECTORY_NAME = "bin";
1085
- const LAUNCHER_NAME = "rivus";
1086
- const PRIVATE_MODE = 448;
1087
- /**
1088
- * Install the private launcher used by model-management child processes.
1089
- *
1090
- * The launcher contains only fixed absolute executable paths. Per-Run
1091
- * context, credentials, and other authority data stay in the spawn
1092
- * environment owned by the Host and are never persisted in this file.
1093
- */
1094
- async function installRivusModelManagementCliLauncher(options) {
1095
- assertAbsolutePath("directory", options.directory);
1096
- assertAbsolutePath("nodeExecutable", options.nodeExecutable);
1097
- assertAbsolutePath("cliEntryPath", options.cliEntryPath);
1098
- const binDirectory = join(options.directory, BIN_DIRECTORY_NAME);
1099
- const launcherPath = join(binDirectory, LAUNCHER_NAME);
1100
- await mkdir(binDirectory, {
1101
- mode: PRIVATE_MODE,
1102
- recursive: true
1103
- });
1104
- await chmod(binDirectory, PRIVATE_MODE);
1105
- await chmodIfPresent(launcherPath, PRIVATE_MODE);
1106
- await options.writeAtomicTextFile(launcherPath, renderLauncher(options), { mode: PRIVATE_MODE });
1107
- await chmod(launcherPath, PRIVATE_MODE);
1108
- return Object.freeze({
1109
- binDirectory,
1110
- launcherPath
1111
- });
1112
- }
1113
- function renderLauncher(options) {
1114
- return `#!/bin/sh\nexec ${shellQuote(options.nodeExecutable)} ${shellQuote(options.cliEntryPath)} "$@"\n`;
1115
- }
1116
- function shellQuote(value) {
1117
- if (value.includes("\0")) throw new Error("launcher paths must not contain NUL bytes");
1118
- return `'${value.replaceAll("'", "'\\''")}'`;
1119
- }
1120
- function assertAbsolutePath(name, value) {
1121
- if (value.length === 0 || !isAbsolute(value)) throw new Error(`${name} must be an absolute path`);
1122
- if (value.includes("\0")) throw new Error(`${name} must not contain NUL bytes`);
1123
- }
1124
- async function chmodIfPresent(path, mode) {
1125
- try {
1126
- await chmod(path, mode);
1127
- } catch (error) {
1128
- if (isMissing(error)) return;
1129
- throw error;
1130
- }
1131
- }
1132
- function isMissing(error) {
1133
- return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
757
+ function toRivusModelManagementSubmission(request) {
758
+ const target = request.operation === "set" ? parseTarget(request.model) : void 0;
759
+ return {
760
+ expectedRevision: request.expectedRevision,
761
+ operation: request.operation,
762
+ requestId: request.requestId,
763
+ ...target ? { target } : {},
764
+ ...request.verbose ? { verbose: true } : {}
765
+ };
1134
766
  }
1135
- //#endregion
1136
- //#region src/platform/home/config/runtime/rivus-daemon-config.ts
1137
- var RivusDaemonConfigError = class {
1138
- variable;
1139
- message;
1140
- _tag = "RivusDaemonConfigError";
1141
- constructor(variable, message) {
1142
- this.variable = variable;
1143
- this.message = message;
767
+ function projectRivusModelCliResponse(value, operation) {
768
+ if (!isRecord$1(value)) throw new Error("model handler must return a JSON object");
769
+ const response = { schemaVersion: 1 };
770
+ copyScalar(response, value, "requestId");
771
+ copyScalar(response, value, "revision");
772
+ copyScalar(response, value, "source");
773
+ copyScalar(response, value, "protocolVersion");
774
+ copyScalar(response, value, "runtimeVersion");
775
+ copyScalar(response, value, "operation");
776
+ copyScalar(response, value, "expectedRevision");
777
+ copyScalar(response, value, "phase");
778
+ copyScalar(response, value, "reason");
779
+ for (const key of [
780
+ "actual",
781
+ "current",
782
+ "persisted",
783
+ "previous",
784
+ "target"
785
+ ]) {
786
+ const model = projectModelReference(value[key]);
787
+ if (model) response[key] = model;
1144
788
  }
1145
- };
1146
- const DEFAULT_AGENT_ID = "main";
1147
- const DEFAULT_CARD_STREAM_LEASE_MS = 51e4;
1148
- const DEFAULT_FEISHU_BASE_URL = "https://open.feishu.cn";
1149
- const DEFAULT_STREAM_MIN_INTERVAL_MS = 200;
1150
- const THINKING_LEVELS = /* @__PURE__ */ new Set([
1151
- "off",
1152
- "minimal",
1153
- "low",
1154
- "medium",
1155
- "high",
1156
- "xhigh"
1157
- ]);
1158
- function loadRivusDaemonConfig(env, options = {}) {
1159
- return Effect.gen(function* () {
1160
- const appId = yield* required$1(env, "FEISHU_APP_ID");
1161
- const appSecret = yield* required$1(env, "FEISHU_APP_SECRET");
1162
- const streamMinIntervalMs = yield* optionalPositiveInteger(env.FEISHU_STREAM_MIN_INTERVAL_MS, "FEISHU_STREAM_MIN_INTERVAL_MS", DEFAULT_STREAM_MIN_INTERVAL_MS);
1163
- const cardStreamLeaseMs = yield* optionalPositiveInteger(env.FEISHU_CARD_STREAM_LEASE_MS, "FEISHU_CARD_STREAM_LEASE_MS", DEFAULT_CARD_STREAM_LEASE_MS);
1164
- const thinkingLevel = yield* optionalThinkingLevel(env.PI_THINKING_LEVEL);
1165
- const apiKey = yield* optionalPiApiKey(env, options.readTextFile ?? readUtf8File);
1166
- const baseUrl = optional(env.PI_BASE_URL);
1167
- const model = optional(env.PI_MODEL);
1168
- return {
1169
- agentId: optional(env.RIVUS_AGENT_ID) ?? DEFAULT_AGENT_ID,
1170
- feishu: {
1171
- appId,
1172
- appSecret,
1173
- baseUrl: optional(env.FEISHU_BASE_URL) ?? DEFAULT_FEISHU_BASE_URL,
1174
- cardStreamLeaseMs,
1175
- streamMinIntervalMs
1176
- },
1177
- pi: {
1178
- ...apiKey ? { apiKey } : {},
1179
- ...baseUrl ? { baseUrl } : {},
1180
- ...model ? { model } : {},
1181
- ...thinkingLevel ? { thinkingLevel } : {}
1182
- }
1183
- };
1184
- });
789
+ const budget = projectBudget(value.budget);
790
+ if (budget) response.budget = budget;
791
+ const pending = projectPending(value.pending);
792
+ if (pending) response.pending = pending;
793
+ const request = projectReceipt(value.request);
794
+ if (request) response.request = request;
795
+ const error = projectError(value.error);
796
+ if (error) response.error = error;
797
+ const recoveryRequired = projectError(value.recoveryRequired);
798
+ if (recoveryRequired) response.recoveryRequired = recoveryRequired;
799
+ const notification = projectNotification(value.notification);
800
+ if (notification) response.notification = notification;
801
+ const status = value.status;
802
+ response.status = isPublicStatus(status) ? status : value.recoveryRequired !== void 0 ? "recovery-required" : operation === "status" && value.pending !== void 0 ? "pending" : operation === "status" ? "applied" : "failed";
803
+ return response;
1185
804
  }
1186
- function optional(value) {
1187
- const trimmed = value?.trim();
1188
- return trimmed ? trimmed : void 0;
805
+ function createRivusModelManagementFailure(code, message) {
806
+ return {
807
+ error: {
808
+ code,
809
+ message
810
+ },
811
+ schemaVersion: 1,
812
+ status: "failed"
813
+ };
1189
814
  }
1190
- function readUtf8File(path) {
1191
- return readFile(path, "utf8");
815
+ function projectModelReference(value) {
816
+ if (!isRecord$1(value) || typeof value.provider !== "string" || typeof value.model !== "string") return;
817
+ const result = {
818
+ model: value.model,
819
+ provider: value.provider
820
+ };
821
+ if (typeof value.label === "string") return {
822
+ ...result,
823
+ label: value.label
824
+ };
825
+ if (typeof value.bindingRevision === "string") return {
826
+ ...result,
827
+ bindingRevision: value.bindingRevision
828
+ };
829
+ return result;
1192
830
  }
1193
- function optionalPiApiKey(env, readTextFile) {
1194
- const inlineApiKey = optional(env.PI_API_KEY);
1195
- const apiKeyFile = optional(env.PI_API_KEY_FILE);
1196
- if (inlineApiKey && apiKeyFile) return Effect.fail(new RivusDaemonConfigError("PI_API_KEY", "PI_API_KEY and PI_API_KEY_FILE cannot both be set"));
1197
- if (inlineApiKey) return Effect.succeed(inlineApiKey);
1198
- if (!apiKeyFile) return Effect.succeed(void 0);
1199
- return Effect.tryPromise({
1200
- try: async () => readTextFile(apiKeyFile),
1201
- catch: (error) => new RivusDaemonConfigError("PI_API_KEY_FILE", `PI_API_KEY_FILE could not be read: ${formatConfigError(error)}`)
1202
- }).pipe(Effect.flatMap((contents) => {
1203
- const apiKey = optional(contents);
1204
- return apiKey ? Effect.succeed(apiKey) : Effect.fail(new RivusDaemonConfigError("PI_API_KEY_FILE", "PI_API_KEY_FILE must not be empty"));
1205
- }));
831
+ function projectPending(value) {
832
+ if (!isRecord$1(value)) return;
833
+ const result = {};
834
+ copyScalar(result, value, "phase");
835
+ copyScalar(result, value, "reason");
836
+ if (result.reason === void 0 && typeof result.phase === "string") result.reason = result.phase;
837
+ copyScalar(result, value, "requestId");
838
+ copyScalar(result, value, "updatedAt");
839
+ const request = projectReceipt(value.request);
840
+ if (request) result.request = request;
841
+ const target = projectModelReference(value.target);
842
+ if (target) result.target = target;
843
+ return Object.keys(result).length > 0 ? result : void 0;
1206
844
  }
1207
- function formatConfigError(error) {
1208
- return error instanceof Error ? error.message : String(error);
845
+ function projectReceipt(value) {
846
+ if (!isRecord$1(value)) return;
847
+ const result = scalarFields(value, [
848
+ "requestId",
849
+ "revision",
850
+ "status",
851
+ "phase",
852
+ "operation",
853
+ "expectedRevision",
854
+ "acceptedAt",
855
+ "updatedAt"
856
+ ]);
857
+ const current = projectModelReference(value.current);
858
+ if (current) result.current = current;
859
+ const previous = projectModelReference(value.previous);
860
+ if (previous) result.previous = previous;
861
+ const target = projectModelReference(value.target);
862
+ if (target) result.target = target;
863
+ const budget = projectBudget(value.budget);
864
+ if (budget) result.budget = budget;
865
+ const error = projectError(value.error);
866
+ if (error) result.error = error;
867
+ const notification = projectNotification(value.notification);
868
+ if (notification) result.notification = notification;
869
+ return Object.keys(result).length > 0 ? result : void 0;
1209
870
  }
1210
- function optionalPositiveInteger(value, variable, fallback) {
1211
- const normalized = optional(value);
1212
- if (!normalized) return Effect.succeed(fallback);
1213
- if (/^[1-9]\d*$/.test(normalized)) return Effect.succeed(Number(normalized));
1214
- return Effect.fail(new RivusDaemonConfigError(variable, `${variable} must be a positive integer`));
871
+ function projectBudget(value) {
872
+ if (!isRecord$1(value)) return;
873
+ const result = scalarFields(value, [
874
+ "deadlineAt",
875
+ "maxOutputTokens",
876
+ "maxPaidRequests",
877
+ "outputTokens",
878
+ "paidRequests"
879
+ ]);
880
+ return Object.keys(result).length > 0 ? result : void 0;
1215
881
  }
1216
- function required$1(env, variable) {
1217
- const value = optional(env[variable]);
1218
- if (value) return Effect.succeed(value);
1219
- return Effect.fail(new RivusDaemonConfigError(variable, `${variable} is required`));
882
+ function projectError(value) {
883
+ if (!isRecord$1(value) || typeof value.code !== "string" || typeof value.message !== "string") return;
884
+ return {
885
+ code: value.code,
886
+ message: value.message
887
+ };
1220
888
  }
1221
- function optionalThinkingLevel(value) {
1222
- const normalized = optional(value);
1223
- if (!normalized) return Effect.succeed(void 0);
1224
- if (THINKING_LEVELS.has(normalized)) return Effect.succeed(normalized);
1225
- return Effect.fail(new RivusDaemonConfigError("PI_THINKING_LEVEL", "PI_THINKING_LEVEL must be one of off, minimal, low, medium, high, xhigh"));
889
+ function projectNotification(value) {
890
+ if (!isRecord$1(value)) return;
891
+ const result = scalarFields(value, [
892
+ "attempts",
893
+ "lastAttemptAt",
894
+ "status"
895
+ ]);
896
+ return Object.keys(result).length > 0 ? result : void 0;
1226
897
  }
1227
- //#endregion
1228
- //#region src/platform/project/setup/gateway-package-resources.ts
1229
- const packageManifestUrl = import.meta.resolve("@rivus/gateway/package.json");
1230
- const packageRootUrl = new URL("./", packageManifestUrl);
1231
- const gatewayPackageDirectory = fileURLToPath(packageRootUrl);
1232
- const gatewayPackageManifestPath = fileURLToPath(new URL("package.json", packageRootUrl));
1233
- const gatewayTemplateDirectory = fileURLToPath(new URL("templates/", packageRootUrl));
1234
- const gatewaySkillsDirectory = fileURLToPath(new URL("skills/", packageRootUrl));
1235
- //#endregion
1236
- //#region src/platform/project/setup/release-descriptor.ts
1237
- const RIVUS_RELEASE_DESCRIPTOR = Object.freeze({
1238
- version: "0.16.6",
1239
- dependencies: Object.freeze({
1240
- "@earendil-works/pi-coding-agent": "0.84.4",
1241
- "@larksuiteoapi/node-sdk": "1.71.1",
1242
- effect: "^3.21.4"
1243
- })
1244
- });
1245
- //#endregion
1246
- //#region src/core/application/deployment/manifest/deployment-manifest.ts
1247
- const DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_MS = 3e4;
1248
- const DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_RENEWAL_INTERVAL_MS = 1e4;
1249
- const DEFAULT_MANIFEST_BACKGROUND_SESSION_MAX_CONSECUTIVE_FAILURES = 3;
1250
- const DEFAULT_MANIFEST_BACKGROUND_SESSION_MAX_CONCURRENT_SESSIONS = 4;
1251
- const DEFAULT_MANIFEST_BACKGROUND_SESSION_RETRY_BACKOFF_MS = 3e4;
1252
- const DEFAULT_MANIFEST_BACKGROUND_SESSION_LIFETIME_MS = 1440 * 60 * 1e3;
1253
- const DEFAULT_MANIFEST_BACKGROUND_SESSION_STEP_TIMEOUT_MS = 300 * 1e3;
1254
- const DEFAULT_MANIFEST_CARD_STREAM_LEASE_MS = 51e4;
1255
- const DEFAULT_MANIFEST_CONVERSATION_PROGRESS_DISPLAY = "collapsed";
1256
- const MEMORY_SCOPES = [
1257
- "conversation",
1258
- "agent-private",
1259
- "project",
1260
- "shared-user-profile"
1261
- ];
1262
- var InvalidRivusProjectSpace = class extends Error {
1263
- name = "InvalidRivusProjectSpace";
1264
- };
1265
- function validateRivusProjectSpaceDeployments(declarations) {
1266
- const projectSpaceIds = /* @__PURE__ */ new Set();
1267
- for (const declaration of declarations) {
1268
- if (projectSpaceIds.has(declaration.id)) throw new InvalidRivusProjectSpace(`duplicate project space: ${declaration.id}`);
1269
- projectSpaceIds.add(declaration.id);
1270
- validateRivusProjectSpaceDeployment(declaration);
1271
- }
1272
- return projectSpaceIds;
898
+ function scalarFields(source, keys) {
899
+ const result = {};
900
+ for (const key of keys) copyScalar(result, source, key);
901
+ return result;
1273
902
  }
1274
- function validateRivusProjectSpaceDeployment(declaration) {
1275
- validateRelativeProjectPath(declaration.root, `project space ${declaration.id} root`);
1276
- validateRelativeProjectPath(declaration.workingDirectory, `project space ${declaration.id} working directory`);
1277
- const sources = /* @__PURE__ */ new Set();
1278
- for (const source of declaration.skills.sources) {
1279
- validateRelativeProjectPath(source, `project space ${declaration.id} Skill source`);
1280
- if (sources.has(source)) throw new InvalidRivusProjectSpace(`project space ${declaration.id} contains duplicate Skill source: ${source}`);
1281
- sources.add(source);
1282
- }
903
+ function copyScalar(target, source, key) {
904
+ const value = source[key];
905
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") target[key] = value;
1283
906
  }
1284
- function validateRelativeProjectPath(value, owner) {
1285
- if (value.trim() === "" || isAbsoluteProjectPath(value) || value.includes("\0")) throw new InvalidRivusProjectSpace(`${owner} must be a non-empty relative path`);
907
+ function parseTarget(value) {
908
+ if (!value) throw new Error("model request target is missing");
909
+ const separator = value.indexOf("/");
910
+ return {
911
+ model: value.slice(separator + 1),
912
+ provider: value.slice(0, separator)
913
+ };
1286
914
  }
1287
- function isAbsoluteProjectPath(value) {
1288
- return value.startsWith("/") || value.startsWith("\\") || /^[a-z]:[\\/]/i.test(value);
915
+ function isPublicStatus(value) {
916
+ return value === "applied" || value === "failed" || value === "pending" || value === "recovery-required" || value === "restored";
1289
917
  }
1290
- function parseRivusDeploymentManifest(value) {
1291
- const root = record(value, "manifest");
1292
- exactKeys(root, [
1293
- "agents",
1294
- "automations",
1295
- "backgroundSessions",
1296
- "defaultAgentId",
1297
- "defaultEndpointId",
1298
- "endpoints",
1299
- "plugins",
1300
- "projectSpaces"
1301
- ], "manifest", [
1302
- "automations",
1303
- "backgroundSessions",
1304
- "projectSpaces"
1305
- ]);
1306
- const plugins = array(root.plugins, "manifest.plugins").map((entry, index) => {
1307
- const plugin = record(entry, `manifest.plugins[${index}]`);
1308
- exactKeys(plugin, [
1309
- "id",
1310
- "module",
1311
- "required"
1312
- ], `manifest.plugins[${index}]`);
1313
- return Object.freeze({
1314
- id: string(plugin.id, `manifest.plugins[${index}].id`),
1315
- module: string(plugin.module, `manifest.plugins[${index}].module`),
1316
- required: boolean(plugin.required, `manifest.plugins[${index}].required`)
1317
- });
1318
- });
1319
- const agents = array(root.agents, "manifest.agents").map((entry, index) => {
1320
- const agent = record(entry, `manifest.agents[${index}]`);
1321
- exactKeys(agent, [
1322
- "agentId",
1323
- "endpointIds",
1324
- "memory",
1325
- "pluginId",
1326
- "profileId",
1327
- "projectSpaceId",
1328
- "runtimeTools",
1329
- "skills",
1330
- "tools"
1331
- ], `manifest.agents[${index}]`, [
1332
- "memory",
1333
- "projectSpaceId",
1334
- "runtimeTools"
1335
- ]);
1336
- const memory = agent.memory === void 0 ? void 0 : record(agent.memory, `manifest.agents[${index}].memory`);
1337
- if (memory) exactKeys(memory, ["scopes", "tool"], `manifest.agents[${index}].memory`);
1338
- const skills = record(agent.skills, `manifest.agents[${index}].skills`);
1339
- exactKeys(skills, ["allow"], `manifest.agents[${index}].skills`);
1340
- const tools = record(agent.tools, `manifest.agents[${index}].tools`);
1341
- exactKeys(tools, ["allow"], `manifest.agents[${index}].tools`);
1342
- const runtimeTools = agent.runtimeTools === void 0 ? void 0 : record(agent.runtimeTools, `manifest.agents[${index}].runtimeTools`);
1343
- if (runtimeTools) exactKeys(runtimeTools, ["allow"], `manifest.agents[${index}].runtimeTools`);
1344
- return Object.freeze({
1345
- agentId: string(agent.agentId, `manifest.agents[${index}].agentId`),
1346
- endpointIds: Object.freeze(array(agent.endpointIds, `manifest.agents[${index}].endpointIds`).map((item, itemIndex) => string(item, `manifest.agents[${index}].endpointIds[${itemIndex}]`))),
1347
- ...memory ? { memory: Object.freeze({
1348
- scopes: Object.freeze(array(memory.scopes, `manifest.agents[${index}].memory.scopes`).map((item, itemIndex) => memoryScope(item, `manifest.agents[${index}].memory.scopes[${itemIndex}]`))),
1349
- tool: boolean(memory.tool, `manifest.agents[${index}].memory.tool`)
1350
- }) } : {},
1351
- pluginId: string(agent.pluginId, `manifest.agents[${index}].pluginId`),
1352
- profileId: string(agent.profileId, `manifest.agents[${index}].profileId`),
1353
- ...agent.projectSpaceId === void 0 ? {} : { projectSpaceId: string(agent.projectSpaceId, `manifest.agents[${index}].projectSpaceId`) },
1354
- ...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`)) }) } : {},
1355
- 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}]`))) }),
1356
- 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}]`))) })
1357
- });
1358
- });
1359
- const endpoints = array(root.endpoints, "manifest.endpoints").map((entry, index) => {
1360
- const endpoint = record(entry, `manifest.endpoints[${index}]`);
1361
- exactKeys(endpoint, [
1362
- "agentId",
1363
- "baseUrl",
1364
- "cardStreamLeaseMs",
1365
- "credentialRef",
1366
- "enabled",
1367
- "experimental",
1368
- "groupPolicy",
1369
- "id",
1370
- "progressDisplay",
1371
- "required",
1372
- "sessionNamespace",
1373
- "streamMinIntervalMs"
1374
- ], `manifest.endpoints[${index}]`, [
1375
- "cardStreamLeaseMs",
1376
- "experimental",
1377
- "progressDisplay"
1378
- ]);
1379
- const experimental = endpoint.experimental === void 0 ? void 0 : record(endpoint.experimental, `manifest.endpoints[${index}].experimental`);
1380
- if (experimental) exactKeys(experimental, ["cotMessages"], `manifest.endpoints[${index}].experimental`);
1381
- return Object.freeze({
1382
- agentId: string(endpoint.agentId, `manifest.endpoints[${index}].agentId`),
1383
- baseUrl: string(endpoint.baseUrl, `manifest.endpoints[${index}].baseUrl`),
1384
- cardStreamLeaseMs: endpoint.cardStreamLeaseMs === void 0 ? DEFAULT_MANIFEST_CARD_STREAM_LEASE_MS : positiveInteger(endpoint.cardStreamLeaseMs, `manifest.endpoints[${index}].cardStreamLeaseMs`),
1385
- credentialRef: string(endpoint.credentialRef, `manifest.endpoints[${index}].credentialRef`),
1386
- enabled: boolean(endpoint.enabled, `manifest.endpoints[${index}].enabled`),
1387
- ...experimental ? { experimental: Object.freeze({ cotMessages: boolean(experimental.cotMessages, `manifest.endpoints[${index}].experimental.cotMessages`) }) } : {},
1388
- groupPolicy: groupPolicy(endpoint.groupPolicy, `manifest.endpoints[${index}].groupPolicy`),
1389
- id: string(endpoint.id, `manifest.endpoints[${index}].id`),
1390
- progressDisplay: endpoint.progressDisplay === void 0 ? DEFAULT_MANIFEST_CONVERSATION_PROGRESS_DISPLAY : progressDisplay(endpoint.progressDisplay, `manifest.endpoints[${index}].progressDisplay`),
1391
- required: boolean(endpoint.required, `manifest.endpoints[${index}].required`),
1392
- sessionNamespace: string(endpoint.sessionNamespace, `manifest.endpoints[${index}].sessionNamespace`),
1393
- streamMinIntervalMs: positiveInteger(endpoint.streamMinIntervalMs, `manifest.endpoints[${index}].streamMinIntervalMs`)
1394
- });
1395
- });
1396
- const automations = array(root.automations ?? [], "manifest.automations").map((entry, index) => {
1397
- const automation = record(entry, `manifest.automations[${index}]`);
1398
- exactKeys(automation, [
1399
- "agentId",
1400
- "delivery",
1401
- "enabled",
1402
- "id",
1403
- "required",
1404
- "schedule",
1405
- "templateId",
1406
- "timeZone"
1407
- ], `manifest.automations[${index}]`);
1408
- const delivery = record(automation.delivery, `manifest.automations[${index}].delivery`);
1409
- exactKeys(delivery, [
1410
- "endpointId",
1411
- "targetRef",
1412
- "targetType"
1413
- ], `manifest.automations[${index}].delivery`);
1414
- return Object.freeze({
1415
- agentId: string(automation.agentId, `manifest.automations[${index}].agentId`),
1416
- delivery: Object.freeze({
1417
- endpointId: string(delivery.endpointId, `manifest.automations[${index}].delivery.endpointId`),
1418
- targetRef: string(delivery.targetRef, `manifest.automations[${index}].delivery.targetRef`),
1419
- targetType: automationTargetType(delivery.targetType, `manifest.automations[${index}].delivery.targetType`)
1420
- }),
1421
- enabled: boolean(automation.enabled, `manifest.automations[${index}].enabled`),
1422
- id: string(automation.id, `manifest.automations[${index}].id`),
1423
- required: boolean(automation.required, `manifest.automations[${index}].required`),
1424
- schedule: string(automation.schedule, `manifest.automations[${index}].schedule`),
1425
- templateId: string(automation.templateId, `manifest.automations[${index}].templateId`),
1426
- timeZone: string(automation.timeZone, `manifest.automations[${index}].timeZone`)
1427
- });
918
+ function optionalString(value) {
919
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
920
+ }
921
+ function isRecord$1(value) {
922
+ return typeof value === "object" && value !== null && !Array.isArray(value);
923
+ }
924
+ //#endregion
925
+ //#region src/adapters/cli/model/rivus-model-management-socket-server.ts
926
+ const MAX_FRAME_BYTES = 65536;
927
+ function createRivusModelManagementSocketServer(options) {
928
+ assertAbsoluteSocketPath(options.socketPath);
929
+ let server;
930
+ let socketIdentity;
931
+ let listening = false;
932
+ let startPromise;
933
+ return {
934
+ close: async () => {
935
+ if (startPromise) await startPromise.catch(() => void 0);
936
+ const current = server;
937
+ const identity = socketIdentity;
938
+ server = void 0;
939
+ socketIdentity = void 0;
940
+ if (current && listening) await closeServer(current);
941
+ listening = false;
942
+ if (identity) await unlinkOwnedSocket(options.socketPath, identity);
943
+ },
944
+ listening: () => listening,
945
+ start: async () => {
946
+ if (listening) return;
947
+ if (startPromise) return startPromise;
948
+ startPromise = startServer(options, (next, identity) => {
949
+ server = next;
950
+ socketIdentity = identity;
951
+ listening = true;
952
+ });
953
+ try {
954
+ await startPromise;
955
+ } finally {
956
+ startPromise = void 0;
957
+ }
958
+ }
959
+ };
960
+ }
961
+ async function startServer(options, onStarted) {
962
+ await prepareSocketParentDirectory(options.socketPath);
963
+ const lockPath = `${options.socketPath}.lock`;
964
+ const lock = await acquireStartLock(lockPath);
965
+ const next = createServer((socket) => handleConnection(socket, options));
966
+ let bound = false;
967
+ try {
968
+ await prepareSocketPath(options.socketPath);
969
+ await listen(next, options.socketPath);
970
+ bound = true;
971
+ await chmod(options.socketPath, 384);
972
+ onStarted(next, await readSocketIdentity(options.socketPath));
973
+ } catch (error) {
974
+ await closeServer(next).catch(() => void 0);
975
+ if (bound) await unlinkSocketIfPresent(options.socketPath);
976
+ throw error;
977
+ } finally {
978
+ await releaseStartLock(lock, lockPath);
979
+ }
980
+ }
981
+ async function handleConnection(socket, options) {
982
+ let buffer = "";
983
+ let handled = false;
984
+ socket.setEncoding("utf8");
985
+ socket.on("data", (chunk) => {
986
+ if (handled) return;
987
+ buffer += chunk;
988
+ if (Buffer.byteLength(buffer, "utf8") > MAX_FRAME_BYTES) {
989
+ handled = true;
990
+ writeResponse(socket, createRivusModelManagementFailure("request_too_large", "model management request is too large"));
991
+ return;
992
+ }
993
+ const newline = buffer.indexOf("\n");
994
+ if (newline < 0) return;
995
+ handled = true;
996
+ handleFrame(buffer.slice(0, newline).trim(), socket, options);
1428
997
  });
1429
- const projectSpaces = array(root.projectSpaces ?? [], "manifest.projectSpaces").map((entry, index) => {
1430
- const projectSpace = record(entry, `manifest.projectSpaces[${index}]`);
1431
- exactKeys(projectSpace, [
1432
- "id",
1433
- "root",
1434
- "skills",
1435
- "workingDirectory"
1436
- ], `manifest.projectSpaces[${index}]`);
1437
- const skills = record(projectSpace.skills, `manifest.projectSpaces[${index}].skills`);
1438
- exactKeys(skills, ["sources"], `manifest.projectSpaces[${index}].skills`);
1439
- return Object.freeze({
1440
- id: string(projectSpace.id, `manifest.projectSpaces[${index}].id`),
1441
- root: string(projectSpace.root, `manifest.projectSpaces[${index}].root`),
1442
- skills: Object.freeze({ sources: Object.freeze(array(skills.sources, `manifest.projectSpaces[${index}].skills.sources`).map((item, itemIndex) => string(item, `manifest.projectSpaces[${index}].skills.sources[${itemIndex}]`))) }),
1443
- workingDirectory: string(projectSpace.workingDirectory, `manifest.projectSpaces[${index}].workingDirectory`)
1444
- });
998
+ socket.on("end", () => {
999
+ if (handled || buffer.trim() === "") return;
1000
+ handled = true;
1001
+ handleFrame(buffer.trim(), socket, options);
1445
1002
  });
1446
- const backgroundSessions = root.backgroundSessions === void 0 ? void 0 : parseBackgroundSessions(record(root.backgroundSessions, "manifest.backgroundSessions"));
1447
- return Object.freeze({
1448
- agents: Object.freeze(agents),
1449
- automations: Object.freeze(automations),
1450
- ...backgroundSessions ? { backgroundSessions } : {},
1451
- defaultAgentId: string(root.defaultAgentId, "manifest.defaultAgentId"),
1452
- defaultEndpointId: string(root.defaultEndpointId, "manifest.defaultEndpointId"),
1453
- endpoints: Object.freeze(endpoints),
1454
- plugins: Object.freeze(plugins),
1455
- projectSpaces: Object.freeze(projectSpaces)
1003
+ socket.on("error", () => {
1004
+ handled = true;
1456
1005
  });
1457
1006
  }
1458
- function validateRivusDeploymentManifest(manifest) {
1459
- const projectSpaceIds = validateRivusProjectSpaceDeployments(manifest.projectSpaces ?? []);
1460
- const pluginIds = /* @__PURE__ */ new Set();
1461
- for (const plugin of manifest.plugins) {
1462
- if (pluginIds.has(plugin.id)) throw new Error(`duplicate plugin declaration: ${plugin.id}`);
1463
- validateModuleSpecifier(plugin.module);
1464
- pluginIds.add(plugin.id);
1007
+ async function handleFrame(frame, socket, options) {
1008
+ let response;
1009
+ let request;
1010
+ try {
1011
+ request = parseRivusModelManagementWireRequest(JSON.parse(frame));
1012
+ } catch (error) {
1013
+ response = createRivusModelManagementFailure("invalid_request", error instanceof Error ? error.message : "invalid model request");
1014
+ writeResponse(socket, response);
1015
+ return;
1465
1016
  }
1466
- const agentIds = /* @__PURE__ */ new Set();
1467
- const agentById = /* @__PURE__ */ new Map();
1468
- for (const agent of manifest.agents) {
1469
- if (agentIds.has(agent.agentId)) throw new Error(`duplicate agent deployment: ${agent.agentId}`);
1470
- agentIds.add(agent.agentId);
1471
- if (!pluginIds.has(agent.pluginId)) throw new Error(`agent ${agent.agentId} references undeclared plugin: ${agent.pluginId}`);
1472
- if (agent.projectSpaceId && !projectSpaceIds.has(agent.projectSpaceId)) throw new Error(`agent ${agent.agentId} references unknown project space: ${agent.projectSpaceId}`);
1473
- agentById.set(agent.agentId, agent);
1017
+ try {
1018
+ if (request.operation === "status") response = projectRivusModelCliResponse(await options.handlers.status({
1019
+ ...request.requestId ? { requestId: request.requestId } : {},
1020
+ ...request.verbose ? { verbose: true } : {}
1021
+ }), request.operation);
1022
+ else response = await handleMutation(request, options);
1023
+ } catch {
1024
+ response = createRivusModelManagementFailure("handler_failed", "the model management request could not be completed");
1474
1025
  }
1475
- const endpointIds = /* @__PURE__ */ new Set();
1476
- const sessionNamespaces = /* @__PURE__ */ new Set();
1477
- for (const endpoint of manifest.endpoints) {
1478
- if (endpointIds.has(endpoint.id)) throw new Error(`duplicate endpoint binding: ${endpoint.id}`);
1479
- endpointIds.add(endpoint.id);
1480
- if (sessionNamespaces.has(endpoint.sessionNamespace)) throw new Error(`duplicate endpoint session namespace: ${endpoint.sessionNamespace}`);
1481
- sessionNamespaces.add(endpoint.sessionNamespace);
1482
- const agent = agentById.get(endpoint.agentId);
1483
- if (!agent) throw new Error(`endpoint ${endpoint.id} references unknown agent: ${endpoint.agentId}`);
1484
- if (!agent.endpointIds.includes(endpoint.id)) throw new Error(`endpoint ${endpoint.id} is not declared by agent ${endpoint.agentId}`);
1026
+ writeResponse(socket, response);
1027
+ }
1028
+ async function handleMutation(request, options) {
1029
+ if (!request.context || !options.resolveTrustedRun) return createRivusModelManagementFailure("trusted_context_required", "a trusted Run context is required for model changes");
1030
+ let trustedRun;
1031
+ try {
1032
+ trustedRun = await options.resolveTrustedRun.resolve(request.context);
1033
+ } catch {
1034
+ trustedRun = void 0;
1485
1035
  }
1486
- for (const agent of manifest.agents) for (const endpointId of agent.endpointIds) {
1487
- const endpoint = manifest.endpoints.find(({ id }) => id === endpointId);
1488
- if (!endpoint) throw new Error(`agent ${agent.agentId} references unknown endpoint: ${endpointId}`);
1489
- if (endpoint.agentId !== agent.agentId) throw new Error(`endpoint ${endpointId} is bound to a different agent`);
1036
+ if (trustedRun === void 0 || trustedRun === null) return createRivusModelManagementFailure("trusted_context_invalid", "the trusted Run context is invalid or expired");
1037
+ try {
1038
+ return projectRivusModelCliResponse(await options.handlers.handle(toRivusModelManagementSubmission(request), trustedRun), request.operation);
1039
+ } catch {
1040
+ return createRivusModelManagementFailure("handler_failed", "the model management request could not be completed");
1490
1041
  }
1491
- const automationIds = /* @__PURE__ */ new Set();
1492
- for (const automation of manifest.automations ?? []) {
1493
- if (automationIds.has(automation.id)) throw new Error(`duplicate automation binding: ${automation.id}`);
1494
- automationIds.add(automation.id);
1495
- if (!agentById.has(automation.agentId)) throw new Error(`automation ${automation.id} references unknown agent: ${automation.agentId}`);
1496
- const endpoint = manifest.endpoints.find(({ id }) => id === automation.delivery.endpointId);
1497
- if (!endpoint) throw new Error(`automation ${automation.id} references unknown delivery endpoint: ${automation.delivery.endpointId}`);
1498
- if (automation.enabled && !endpoint.enabled) throw new Error(`automation ${automation.id} delivery endpoint must be enabled`);
1042
+ }
1043
+ function writeResponse(socket, response) {
1044
+ try {
1045
+ socket.end(`${JSON.stringify(response)}\n`);
1046
+ } catch {
1047
+ socket.destroy();
1499
1048
  }
1500
- const defaultAgent = agentById.get(manifest.defaultAgentId);
1501
- if (!defaultAgent) throw new Error(`default agent does not exist: ${manifest.defaultAgentId}`);
1502
- const defaultEndpoint = manifest.endpoints.find(({ id }) => id === manifest.defaultEndpointId);
1503
- if (!defaultEndpoint) throw new Error(`default endpoint does not exist: ${manifest.defaultEndpointId}`);
1504
- if (defaultEndpoint.agentId !== defaultAgent.agentId) throw new Error("default endpoint is not bound to the default agent");
1505
- if (!defaultEndpoint.enabled) throw new Error("default endpoint must be enabled");
1506
- if (manifest.backgroundSessions) validateBackgroundSessions(manifest.backgroundSessions);
1507
1049
  }
1508
- function validateBackgroundSessions(config) {
1509
- if (config.required && !config.enabled) throw new Error("backgroundSessions.required requires backgroundSessions.enabled");
1510
- if (config.leaseRenewalIntervalMs >= config.leaseMs) throw new Error("backgroundSessions.leaseRenewalIntervalMs must be shorter than leaseMs");
1511
- if (config.stepTimeoutMs <= 0 || config.maxConcurrentSessions <= 0 || config.leaseMs <= 0) throw new Error("backgroundSessions durations and concurrency must be positive");
1512
- if (config.retryBackoffMs <= 0 || config.sessionLifetimeMs <= 0 || config.maxConsecutiveFailures <= 0) throw new Error("backgroundSessions retry and lifetime limits must be positive");
1050
+ async function prepareSocketPath(socketPath) {
1051
+ try {
1052
+ const metadata = await stat(socketPath);
1053
+ if (!metadata.isSocket()) throw new Error(`refusing to replace non-socket model path: ${socketPath}`);
1054
+ if (await socketIsLive(socketPath)) throw new Error(`model management socket is already active: ${socketPath}`);
1055
+ const current = await stat(socketPath);
1056
+ if (current.dev !== metadata.dev || current.ino !== metadata.ino) throw new Error(`model management socket changed while starting: ${socketPath}`);
1057
+ await unlink(socketPath);
1058
+ } catch (error) {
1059
+ if (!isMissing(error)) throw error;
1060
+ }
1513
1061
  }
1514
- function validateModuleSpecifier(moduleSpecifier) {
1515
- const absolutePath = moduleSpecifier.startsWith("/") || moduleSpecifier.startsWith("\\\\") || /^[a-zA-Z]:[\\/]/.test(moduleSpecifier);
1516
- if (moduleSpecifier.trim() === "" || absolutePath || /^[a-z][a-z+.-]*:/i.test(moduleSpecifier) || moduleSpecifier.includes("\0")) throw new Error(`invalid plugin module specifier: ${moduleSpecifier}`);
1517
- if ((moduleSpecifier.startsWith("./") || moduleSpecifier.startsWith("../")) && moduleSpecifier.split(/[\\/]/).includes("..")) throw new Error(`plugin module escapes deployment root: ${moduleSpecifier}`);
1062
+ async function prepareSocketParentDirectory(socketPath) {
1063
+ const parent = dirname(socketPath);
1064
+ await mkdir(parent, {
1065
+ mode: 448,
1066
+ recursive: true
1067
+ });
1068
+ await chmod(parent, 448);
1518
1069
  }
1519
- function parseBackgroundSessions(value) {
1520
- exactKeys(value, [
1521
- "enabled",
1522
- "leaseMs",
1523
- "leaseRenewalIntervalMs",
1524
- "maxConsecutiveFailures",
1525
- "maxConcurrentSessions",
1526
- "required",
1527
- "retryBackoffMs",
1528
- "sessionLifetimeMs",
1529
- "stepTimeoutMs"
1530
- ], "manifest.backgroundSessions", [
1531
- "leaseMs",
1532
- "leaseRenewalIntervalMs",
1533
- "maxConsecutiveFailures",
1534
- "maxConcurrentSessions",
1535
- "retryBackoffMs",
1536
- "sessionLifetimeMs",
1537
- "stepTimeoutMs"
1538
- ]);
1539
- return Object.freeze({
1540
- enabled: boolean(value.enabled, "manifest.backgroundSessions.enabled"),
1541
- leaseMs: positiveInteger(value.leaseMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_MS, "manifest.backgroundSessions.leaseMs"),
1542
- leaseRenewalIntervalMs: positiveInteger(value.leaseRenewalIntervalMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_LEASE_RENEWAL_INTERVAL_MS, "manifest.backgroundSessions.leaseRenewalIntervalMs"),
1543
- maxConsecutiveFailures: positiveInteger(value.maxConsecutiveFailures ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_MAX_CONSECUTIVE_FAILURES, "manifest.backgroundSessions.maxConsecutiveFailures"),
1544
- maxConcurrentSessions: positiveInteger(value.maxConcurrentSessions ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_MAX_CONCURRENT_SESSIONS, "manifest.backgroundSessions.maxConcurrentSessions"),
1545
- required: boolean(value.required, "manifest.backgroundSessions.required"),
1546
- retryBackoffMs: positiveInteger(value.retryBackoffMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_RETRY_BACKOFF_MS, "manifest.backgroundSessions.retryBackoffMs"),
1547
- sessionLifetimeMs: positiveInteger(value.sessionLifetimeMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_LIFETIME_MS, "manifest.backgroundSessions.sessionLifetimeMs"),
1548
- stepTimeoutMs: positiveInteger(value.stepTimeoutMs ?? DEFAULT_MANIFEST_BACKGROUND_SESSION_STEP_TIMEOUT_MS, "manifest.backgroundSessions.stepTimeoutMs")
1070
+ async function socketIsLive(socketPath) {
1071
+ return new Promise((resolve, reject) => {
1072
+ const socket = createConnection(socketPath);
1073
+ let settled = false;
1074
+ const finish = (result, error) => {
1075
+ if (settled) return;
1076
+ settled = true;
1077
+ socket.destroy();
1078
+ if (error) reject(error);
1079
+ else resolve(result);
1080
+ };
1081
+ socket.setTimeout(250, () => finish(false, /* @__PURE__ */ new Error("model management socket liveness could not be verified")));
1082
+ socket.once("connect", () => finish(true));
1083
+ socket.once("error", (error) => {
1084
+ if (error.code === "ECONNREFUSED" || error.code === "ENOENT") finish(false);
1085
+ else finish(false, error);
1086
+ });
1549
1087
  });
1550
1088
  }
1551
- function record(value, path) {
1552
- if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(`${path} must be an object`);
1553
- return value;
1089
+ async function acquireStartLock(path) {
1090
+ for (let attempt = 0; attempt < 3; attempt += 1) {
1091
+ let handle;
1092
+ try {
1093
+ handle = await open(path, "wx", 384);
1094
+ await handle.writeFile(`${process.pid}\n`, "utf8");
1095
+ const metadata = await handle.stat();
1096
+ return {
1097
+ handle,
1098
+ identity: {
1099
+ dev: metadata.dev,
1100
+ ino: metadata.ino
1101
+ }
1102
+ };
1103
+ } catch (error) {
1104
+ await handle?.close().catch(() => void 0);
1105
+ if (!isAlreadyExists(error)) throw new Error("model management socket startup is already in progress", { cause: error });
1106
+ const pid = parseLockOwner(await readPersistenceFile(path));
1107
+ if (pid === void 0) throw new Error("model management socket startup lock owner could not be verified; manual recovery is required");
1108
+ if (processIsAlive(pid)) throw new Error("model management socket startup is already in progress");
1109
+ const reclaimed = `${path}.reclaim-${process.pid}-${randomUUID()}`;
1110
+ try {
1111
+ await rename(path, reclaimed);
1112
+ } catch (reclaimError) {
1113
+ if (isMissing(reclaimError)) continue;
1114
+ throw new Error("model management socket startup lock could not be reclaimed safely", { cause: reclaimError });
1115
+ }
1116
+ await unlink(reclaimed).catch((reclaimError) => {
1117
+ if (!isMissing(reclaimError)) throw reclaimError;
1118
+ });
1119
+ }
1120
+ }
1121
+ throw new Error("model management socket startup lock changed during stale-owner recovery; manual recovery is required");
1554
1122
  }
1555
- function array(value, path) {
1556
- if (!Array.isArray(value)) throw new Error(`${path} must be an array`);
1557
- return value;
1123
+ async function releaseStartLock(lock, path) {
1124
+ await lock.handle.close();
1125
+ try {
1126
+ const current = await stat(path);
1127
+ if (current.dev !== lock.identity.dev || current.ino !== lock.identity.ino) return;
1128
+ await unlink(path);
1129
+ } catch (error) {
1130
+ if (!isMissing(error)) throw error;
1131
+ }
1558
1132
  }
1559
- function string(value, path) {
1560
- if (typeof value !== "string" || value.trim() === "") throw new Error(`${path} must be a non-empty string`);
1561
- return value;
1133
+ async function unlinkSocketIfPresent(socketPath) {
1134
+ try {
1135
+ if ((await stat(socketPath)).isSocket()) await unlink(socketPath);
1136
+ } catch (error) {
1137
+ if (!isMissing(error)) throw error;
1138
+ }
1562
1139
  }
1563
- function boolean(value, path) {
1564
- if (typeof value !== "boolean") throw new Error(`${path} must be a boolean`);
1565
- return value;
1140
+ async function unlinkOwnedSocket(socketPath, identity) {
1141
+ try {
1142
+ const current = await readSocketIdentity(socketPath);
1143
+ if (current.dev !== identity.dev || current.ino !== identity.ino) return;
1144
+ await unlink(socketPath);
1145
+ } catch (error) {
1146
+ if (!isMissing(error)) throw error;
1147
+ }
1566
1148
  }
1567
- function positiveInteger(value, path) {
1568
- if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`${path} must be a positive integer`);
1569
- return value;
1149
+ async function readSocketIdentity(socketPath) {
1150
+ const metadata = await stat(socketPath);
1151
+ return {
1152
+ dev: metadata.dev,
1153
+ ino: metadata.ino
1154
+ };
1570
1155
  }
1571
- function memoryScope(value, path) {
1572
- if (typeof value !== "string" || !MEMORY_SCOPES.includes(value)) throw new Error(`${path} must be conversation, agent-private, project, or shared-user-profile`);
1573
- return value;
1156
+ function listen(server, socketPath) {
1157
+ return new Promise((resolve, reject) => {
1158
+ const onError = (error) => {
1159
+ server.off("listening", onListening);
1160
+ reject(error);
1161
+ };
1162
+ const onListening = () => {
1163
+ server.off("error", onError);
1164
+ resolve();
1165
+ };
1166
+ server.once("error", onError);
1167
+ server.once("listening", onListening);
1168
+ server.listen(socketPath);
1169
+ });
1574
1170
  }
1575
- function groupPolicy(value, path) {
1576
- if (value !== "mention-only" && value !== "ignore-unmentioned" && value !== "default-responder") throw new Error(`${path} must be mention-only, ignore-unmentioned, or default-responder`);
1577
- return value;
1171
+ function closeServer(server) {
1172
+ return new Promise((resolve, reject) => {
1173
+ server.close((error) => error ? reject(error) : resolve());
1174
+ });
1578
1175
  }
1579
- function progressDisplay(value, path) {
1580
- if (value !== "hidden" && value !== "collapsed" && value !== "expanded") throw new Error(`${path} must be hidden, collapsed, or expanded`);
1581
- return value;
1176
+ function assertAbsoluteSocketPath(socketPath) {
1177
+ if (!isAbsolute(socketPath)) throw new Error("model socket path must be absolute");
1582
1178
  }
1583
- function runtimeToolId(value, path) {
1584
- const id = string(value, path);
1585
- if (!isRivusRuntimeToolId(id)) throw new Error(`${path} must be read, bash, edit, write, grep, find, or ls`);
1586
- return id;
1179
+ function isMissing(error) {
1180
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
1587
1181
  }
1588
- function uniqueRuntimeTools(ids, path) {
1589
- const result = /* @__PURE__ */ new Set();
1590
- for (const id of ids) {
1591
- if (result.has(id)) throw new Error(`${path} contains duplicate Runtime Tool: ${id}`);
1592
- result.add(id);
1593
- }
1594
- return [...result];
1182
+ function isAlreadyExists(error) {
1183
+ return typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST";
1595
1184
  }
1596
- function automationTargetType(value, path) {
1597
- 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`);
1598
- return value;
1185
+ function processIsAlive(pid) {
1186
+ try {
1187
+ process.kill(pid, 0);
1188
+ return true;
1189
+ } catch (error) {
1190
+ return typeof error === "object" && error !== null && "code" in error && error.code !== "ESRCH";
1191
+ }
1599
1192
  }
1600
- function exactKeys(value, allowed, path, optional = []) {
1601
- const unexpected = Object.keys(value).find((key) => !allowed.includes(key));
1602
- if (unexpected) throw new Error(`${path} contains unsupported field: ${unexpected}`);
1603
- const missing = allowed.find((key) => !optional.includes(key) && !Object.hasOwn(value, key));
1604
- if (missing) throw new Error(`${path} is missing required field: ${missing}`);
1193
+ function parseLockOwner(value) {
1194
+ const normalized = value?.trim();
1195
+ if (!normalized || !/^\d+$/.test(normalized)) return;
1196
+ const pid = Number(normalized);
1197
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
1605
1198
  }
1606
1199
  //#endregion
1607
- //#region src/adapters/feishu/config/feishu-endpoint-credentials.ts
1608
- var FeishuEndpointCredentialError = class extends Error {
1609
- name = "FeishuEndpointCredentialError";
1610
- };
1611
- function resolveFeishuEndpointCredentials(credentialRef, env) {
1612
- if (!credentialRef.startsWith("env:")) throw new FeishuEndpointCredentialError("Feishu endpoint credentialRef must use env:<PREFIX>");
1613
- const prefix = credentialRef.slice(4);
1614
- if (!/^[A-Z][A-Z0-9_]*$/.test(prefix)) throw new FeishuEndpointCredentialError(`Invalid environment prefix in credentialRef: ${credentialRef}`);
1615
- return Object.freeze({
1616
- appId: required(env, `${prefix}_APP_ID`),
1617
- appSecret: required(env, `${prefix}_APP_SECRET`)
1618
- });
1619
- }
1620
- function required(env, variable) {
1621
- const value = env[variable]?.trim();
1622
- if (!value) throw new FeishuEndpointCredentialError(`${variable} is required`);
1623
- return value;
1624
- }
1200
+ //#region src/platform/project/setup/release-descriptor.ts
1201
+ const RIVUS_RELEASE_DESCRIPTOR = Object.freeze({
1202
+ version: "0.18.0",
1203
+ dependencies: Object.freeze({
1204
+ "@earendil-works/pi-coding-agent": "0.84.4",
1205
+ "@larksuiteoapi/node-sdk": "1.74.0",
1206
+ effect: "^4.0.0"
1207
+ })
1208
+ });
1625
1209
  //#endregion
1626
- //#region src/adapters/deployment/manifest/node-rivus-deployment-manifest.ts
1627
- var RivusDeploymentManifestError = class extends Error {
1628
- manifestPath;
1629
- name = "RivusDeploymentManifestError";
1630
- constructor(manifestPath, message, options) {
1631
- super(message, options);
1632
- this.manifestPath = manifestPath;
1633
- }
1634
- };
1635
- function loadRivusDeploymentManifest(manifestPath, options = {}) {
1636
- const maxBytes = options.maxBytes ?? 1024 * 1024;
1637
- return Effect.tryPromise({
1638
- try: async () => {
1639
- const metadata = await stat(manifestPath);
1640
- if (!metadata.isFile()) throw new Error("deployment manifest must be a regular file");
1641
- if (metadata.size > maxBytes) throw new Error(`deployment manifest exceeds ${maxBytes} byte limit`);
1642
- const bytes = await readFile(manifestPath);
1643
- const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1644
- return parseRivusDeploymentManifest(JSON.parse(text));
1645
- },
1646
- catch: (cause) => cause instanceof RivusDeploymentManifestError ? cause : new RivusDeploymentManifestError(manifestPath, `failed to load Rivus deployment manifest: ${cause instanceof Error ? cause.message : String(cause)}`, { cause })
1210
+ //#region src/platform/runtime-pool/runtime-cache.ts
1211
+ function createRuntimeCache() {
1212
+ const entries = /* @__PURE__ */ new Map();
1213
+ const serial = Semaphore.makeUnsafe(1);
1214
+ const reserve = (key) => serial.withPermits(1)(Effect.gen(function* () {
1215
+ const current = entries.get(key);
1216
+ if (current) return {
1217
+ created: false,
1218
+ entry: current
1219
+ };
1220
+ const entry = {
1221
+ deferred: yield* Deferred.make(),
1222
+ initializationStarted: false,
1223
+ key
1224
+ };
1225
+ entries.set(key, entry);
1226
+ return {
1227
+ created: true,
1228
+ entry
1229
+ };
1230
+ }));
1231
+ const start = (entry, create) => Effect.uninterruptible(Effect.gen(function* () {
1232
+ if (!(yield* serial.withPermits(1)(Effect.sync(() => {
1233
+ if (entry.initializationStarted) return false;
1234
+ entry.initializationStarted = true;
1235
+ return true;
1236
+ })))) return;
1237
+ const initialization = create().pipe(Effect.tapError(() => serial.withPermits(1)(Effect.sync(() => {
1238
+ if (entries.get(entry.key) === entry) entries.delete(entry.key);
1239
+ }))), Effect.exit, Effect.flatMap((exit) => Deferred.done(entry.deferred, exit)), Effect.asVoid);
1240
+ yield* Effect.forkDetach(initialization, { uninterruptible: "inherit" });
1241
+ }));
1242
+ const getOrCreate = (key, create) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
1243
+ const selected = yield* reserve(key);
1244
+ yield* start(selected.entry, create);
1245
+ return {
1246
+ entry: selected.entry,
1247
+ runtime: yield* restore(Deferred.await(selected.entry.deferred))
1248
+ };
1249
+ }));
1250
+ return {
1251
+ drain: () => serial.withPermits(1)(Effect.sync(() => {
1252
+ const drained = Object.freeze([...entries.values()]);
1253
+ entries.clear();
1254
+ return drained;
1255
+ })),
1256
+ getExisting: (key) => Effect.gen(function* () {
1257
+ const entry = yield* serial.withPermits(1)(Effect.sync(() => entries.get(key)));
1258
+ if (!entry) return;
1259
+ return {
1260
+ entry,
1261
+ runtime: yield* Deferred.await(entry.deferred)
1262
+ };
1263
+ }),
1264
+ getOrCreate,
1265
+ isCurrent: (key, entry) => serial.withPermits(1)(Effect.sync(() => entries.get(key) === entry)),
1266
+ reserve,
1267
+ size: () => serial.withPermits(1)(Effect.sync(() => entries.size)),
1268
+ start
1269
+ };
1270
+ }
1271
+ function disposeRuntimeCacheEntries(options) {
1272
+ const disposal = Effect.gen(function* () {
1273
+ const completions = yield* Effect.forEach(options.entries, (entry) => Effect.gen(function* () {
1274
+ const completion = yield* Deferred.make();
1275
+ 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" });
1276
+ return completion;
1277
+ }), { concurrency: "unbounded" });
1278
+ const failures = (yield* Effect.forEach(completions, Deferred.await, { concurrency: "unbounded" })).filter(Exit.isFailure).map(({ cause }) => Cause.squash(cause));
1279
+ if (failures.length > 0) return yield* Effect.fail(new AggregateError(failures, options.failureMessage));
1647
1280
  });
1281
+ const timeout = options.timeout;
1282
+ return timeout ? disposal.pipe(Effect.timeoutOrElse({
1283
+ duration: timeout.milliseconds,
1284
+ orElse: () => Effect.fail(timeout.onTimeout())
1285
+ })) : disposal;
1286
+ }
1287
+ function invokeRuntimeControl(runtime, control) {
1288
+ return runtime.pipe(Effect.flatMap((selected) => selected ? control(selected) ?? Effect.succeed(false) : Effect.succeed(false)));
1648
1289
  }
1649
1290
  //#endregion
1650
- export { toProcessAgentRuntimeInput as A, parseRivusModelCliArguments as C, deepFreeze as D, runDeploymentProcessEffect as E, disposeRuntimeCacheEntries as M, invokeRuntimeControl as N, toEffectAgentRuntime as O, createRivusModelManagementWireRequest as S, renderRivusModelCliHelp as T, migrateRivusModelManagementConfig as _, InvalidRivusProjectSpace as a, createRivusModelManagementSocketServer as b, RIVUS_RELEASE_DESCRIPTOR as c, gatewaySkillsDirectory as d, gatewayTemplateDirectory as f, installRivusRuntimeManagementSkill as g, installRivusModelManagementCliLauncher as h, resolveFeishuEndpointCredentials as i, createRuntimeCache as j, toEffectAgentRuntimeInput as k, gatewayPackageDirectory as l, loadRivusDaemonConfig as m, loadRivusDeploymentManifest as n, validateRivusDeploymentManifest as o, RivusDaemonConfigError as p, FeishuEndpointCredentialError as r, validateRivusProjectSpaceDeployment as s, RivusDeploymentManifestError as t, gatewayPackageManifestPath as u, parseRivusModelManagementHomeConfig as v, renderRivusModelCliArgumentError as w, createRivusModelManagementFailure as x, loadMergedLocalEnvFile as y };
1291
+ export { deepFreeze as S, loadMergedLocalEnvFile as _, createRivusModelManagementSocketServer as a, validateRivusDeploymentManifest as b, parseRivusModelCliArguments as c, gatewayPackageDirectory as d, gatewayPackageManifestPath as f, loadRivusDaemonConfig as g, loadRivusDeploymentManifest as h, RIVUS_RELEASE_DESCRIPTOR as i, renderRivusModelCliArgumentError as l, gatewayTemplateDirectory as m, disposeRuntimeCacheEntries as n, createRivusModelManagementFailure as o, gatewaySkillsDirectory as p, invokeRuntimeControl as r, createRivusModelManagementWireRequest as s, createRuntimeCache as t, renderRivusModelCliHelp as u, resolveFeishuEndpointCredentials as v, validateRivusProjectSpaceDeployment as x, InvalidRivusProjectSpace as y };
1292
+