@rivus/gateway 0.16.2

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 (39) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -0
  3. package/dist/bootstrap/pi-feishu.d.ts +20 -0
  4. package/dist/bootstrap/pi-feishu.js +671 -0
  5. package/dist/chunks/background-session-authority.js +230 -0
  6. package/dist/chunks/background-session-control-input.js +45 -0
  7. package/dist/chunks/background-session-service.d.ts +390 -0
  8. package/dist/chunks/index.d.ts +4703 -0
  9. package/dist/chunks/node-rivus-deployment-manifest.js +1650 -0
  10. package/dist/chunks/rivus-node-entrypoint.js +4464 -0
  11. package/dist/chunks/service.js +12112 -0
  12. package/dist/cli.d.ts +1 -0
  13. package/dist/cli.js +16 -0
  14. package/dist/index.d.ts +3 -0
  15. package/dist/index.js +1215 -0
  16. package/dist/mcp.d.ts +92 -0
  17. package/dist/mcp.js +455 -0
  18. package/package.json +64 -0
  19. package/skills/runtime-management/SKILL.md +65 -0
  20. package/templates/a-share-briefing-analysis.mjs +93 -0
  21. package/templates/a-share-briefing-renderer.mjs +257 -0
  22. package/templates/a-share-index-evidence.mjs +99 -0
  23. package/templates/a-share-market-briefing.mjs +83 -0
  24. package/templates/a-share-market-date.mjs +10 -0
  25. package/templates/a-share-overseas-evidence.mjs +86 -0
  26. package/templates/a-share-policy-evidence.mjs +145 -0
  27. package/templates/a-share-provider-response.mjs +21 -0
  28. package/templates/a-share-sector-evidence.mjs +70 -0
  29. package/templates/acp-stdio-proxy.mjs +58 -0
  30. package/templates/current-weather.mjs +117 -0
  31. package/templates/html-drive-tools.mjs +262 -0
  32. package/templates/https-response-reader.mjs +36 -0
  33. package/templates/langfuse-drive-e2e.mjs +175 -0
  34. package/templates/pi-feishu-deployment.bootstrap.ts +3 -0
  35. package/templates/pi-feishu.bootstrap.ts +242 -0
  36. package/templates/rivus-agents.plugin.mjs +290 -0
  37. package/templates/rivus-langfuse-demo.config.json +37 -0
  38. package/templates/rivus-starter.plugin.mjs +47 -0
  39. package/templates/rivus.config.json +114 -0
@@ -0,0 +1,1650 @@
1
+ import { Cause, Deferred, Effect, Exit, Option } from "effect";
2
+ 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";
5
+ import { createConnection, createServer } from "node:net";
6
+ import { dirname, isAbsolute, join } from "node:path";
7
+ 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
+ //#region src/platform/values/deep-freeze.ts
142
+ function deepFreeze(value) {
143
+ if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
144
+ Object.freeze(value);
145
+ for (const child of Object.values(value)) deepFreeze(child);
146
+ }
147
+ return value;
148
+ }
149
+ //#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
+ };
252
+ }
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;
274
+ }
275
+ function renderRivusModelCliArgumentError(error) {
276
+ return `${error}\n\n${RIVUS_MODEL_CLI_USAGE}`;
277
+ }
278
+ function isModelReference(value) {
279
+ return /^[^/\s]+\/[^/\s]+$/.test(value);
280
+ }
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;
285
+ }
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);
573
+ });
574
+ socket.on("end", () => {
575
+ if (handled || buffer.trim() === "") return;
576
+ handled = true;
577
+ handleFrame(buffer.trim(), socket, options);
578
+ });
579
+ socket.on("error", () => {
580
+ handled = true;
581
+ });
582
+ }
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;
592
+ }
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");
601
+ }
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;
611
+ }
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");
617
+ }
618
+ }
619
+ function writeResponse(socket, response) {
620
+ try {
621
+ socket.end(`${JSON.stringify(response)}\n`);
622
+ } catch {
623
+ socket.destroy();
624
+ }
625
+ }
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
+ }
637
+ }
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);
645
+ }
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
+ });
663
+ });
664
+ }
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");
698
+ }
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
+ }
708
+ }
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
+ }
715
+ }
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
+ }
724
+ }
725
+ async function readSocketIdentity(socketPath) {
726
+ const metadata = await stat(socketPath);
727
+ return {
728
+ dev: metadata.dev,
729
+ ino: metadata.ino
730
+ };
731
+ }
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
+ });
746
+ }
747
+ function closeServer(server) {
748
+ return new Promise((resolve, reject) => {
749
+ server.close((error) => error ? reject(error) : resolve());
750
+ });
751
+ }
752
+ function assertAbsoluteSocketPath(socketPath) {
753
+ if (!isAbsolute(socketPath)) throw new Error("model socket path must be absolute");
754
+ }
755
+ function isMissing$2(error) {
756
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
757
+ }
758
+ function isAlreadyExists(error) {
759
+ return typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST";
760
+ }
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
+ }
768
+ }
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;
774
+ }
775
+ //#endregion
776
+ //#region src/platform/home/config/runtime/local-env-file.ts
777
+ var LocalEnvFileError = class extends Error {
778
+ constructor(message) {
779
+ super(message);
780
+ this.name = "LocalEnvFileError";
781
+ }
782
+ };
783
+ async function loadMergedLocalEnvFile(filePath, overrideEnv) {
784
+ return mergeRivusDaemonEnv(await loadLocalEnvFile(filePath), overrideEnv);
785
+ }
786
+ async function loadLocalEnvFile(filePath) {
787
+ return parseLocalEnvFile(await readFile(filePath, "utf8"));
788
+ }
789
+ function parseLocalEnvFile(contents) {
790
+ const env = {};
791
+ const lines = contents.split(/\r?\n/);
792
+ for (let index = 0; index < lines.length; index += 1) {
793
+ const trimmed = lines[index].trim();
794
+ if (!trimmed || trimmed.startsWith("#")) continue;
795
+ const match = (trimmed.startsWith("export ") ? trimmed.slice(7).trimStart() : trimmed).match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
796
+ if (!match) throw new LocalEnvFileError(`Invalid env file line ${index + 1}`);
797
+ const key = match[1];
798
+ const rawValue = match[2];
799
+ env[key] = parseEnvValue(rawValue, index + 1);
800
+ }
801
+ return env;
802
+ }
803
+ function mergeRivusDaemonEnv(fileEnv, overrideEnv) {
804
+ const merged = { ...fileEnv };
805
+ for (const [key, value] of Object.entries(overrideEnv)) if (value !== void 0) merged[key] = value;
806
+ return merged;
807
+ }
808
+ function parseEnvValue(rawValue, lineNumber) {
809
+ const value = rawValue.trim();
810
+ if (!value) return "";
811
+ if (value.startsWith("'")) {
812
+ if (!value.endsWith("'")) throw new LocalEnvFileError(`Invalid single-quoted env value on line ${lineNumber}`);
813
+ return value.slice(1, -1).replaceAll("'\\''", "'");
814
+ }
815
+ if (value.startsWith("\"")) {
816
+ if (!value.endsWith("\"")) throw new LocalEnvFileError(`Invalid double-quoted env value on line ${lineNumber}`);
817
+ return unescapeDoubleQuotedValue(value.slice(1, -1));
818
+ }
819
+ return value;
820
+ }
821
+ function unescapeDoubleQuotedValue(value) {
822
+ return value.replace(/\\(["\\nrt])/g, (_match, escaped) => {
823
+ switch (escaped) {
824
+ case "n": return "\n";
825
+ case "r": return "\r";
826
+ case "t": return " ";
827
+ default: return escaped;
828
+ }
829
+ });
830
+ }
831
+ //#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;
843
+ }
844
+ };
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 } : {}
858
+ });
859
+ }
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
+ };
890
+ }
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
+ };
919
+ }
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
+ });
926
+ }
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));
933
+ }
934
+ function parseOptionalConfiguredModel(value) {
935
+ if (!optional$1(value)) return void 0;
936
+ try {
937
+ return parseConfiguredModel(value);
938
+ } catch {
939
+ return;
940
+ }
941
+ }
942
+ function sameModel(left, right) {
943
+ return left.provider === right.provider && left.model === right.model;
944
+ }
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
+ }
951
+ }
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");
962
+ }
963
+ }
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;
976
+ }
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;
986
+ }
987
+ function hasAmbientModelOverride(env) {
988
+ return Object.prototype.hasOwnProperty.call(env, "PI_MODEL") && env.PI_MODEL !== void 0;
989
+ }
990
+ function isModelPart(value) {
991
+ return value.trim() === value && value.length > 0 && !/[/\s]/.test(value);
992
+ }
993
+ function optional$1(value) {
994
+ return value?.trim() || void 0;
995
+ }
996
+ function isPermissionError(error) {
997
+ return typeof error === "object" && error !== null && "code" in error && (error.code === "EACCES" || error.code === "EPERM" || error.code === "EROFS");
998
+ }
999
+ //#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);
1016
+ return {
1017
+ destination,
1018
+ requiresRefresh: true,
1019
+ sourceDigest,
1020
+ status: "installed"
1021
+ };
1022
+ }
1023
+ const currentDigest = digest(current);
1024
+ if (currentDigest === sourceDigest) {
1025
+ await writeMetadata(metadataPath, sourceDigest, writeAtomicTextFile);
1026
+ return {
1027
+ destination,
1028
+ requiresRefresh: false,
1029
+ sourceDigest,
1030
+ status: "unchanged"
1031
+ };
1032
+ }
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
+ return {
1042
+ destination,
1043
+ requiresRefresh: true,
1044
+ sourceDigest,
1045
+ status: "updated"
1046
+ };
1047
+ }
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";
1134
+ }
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;
1144
+ }
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
+ });
1185
+ }
1186
+ function optional(value) {
1187
+ const trimmed = value?.trim();
1188
+ return trimmed ? trimmed : void 0;
1189
+ }
1190
+ function readUtf8File(path) {
1191
+ return readFile(path, "utf8");
1192
+ }
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
+ }));
1206
+ }
1207
+ function formatConfigError(error) {
1208
+ return error instanceof Error ? error.message : String(error);
1209
+ }
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`));
1215
+ }
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`));
1220
+ }
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"));
1226
+ }
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.2",
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;
1273
+ }
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
+ }
1283
+ }
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`);
1286
+ }
1287
+ function isAbsoluteProjectPath(value) {
1288
+ return value.startsWith("/") || value.startsWith("\\") || /^[a-z]:[\\/]/i.test(value);
1289
+ }
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
+ });
1428
+ });
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
+ });
1445
+ });
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)
1456
+ });
1457
+ }
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);
1465
+ }
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);
1474
+ }
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}`);
1485
+ }
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`);
1490
+ }
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`);
1499
+ }
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
+ }
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");
1513
+ }
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}`);
1518
+ }
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")
1549
+ });
1550
+ }
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;
1554
+ }
1555
+ function array(value, path) {
1556
+ if (!Array.isArray(value)) throw new Error(`${path} must be an array`);
1557
+ return value;
1558
+ }
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;
1562
+ }
1563
+ function boolean(value, path) {
1564
+ if (typeof value !== "boolean") throw new Error(`${path} must be a boolean`);
1565
+ return value;
1566
+ }
1567
+ function positiveInteger(value, path) {
1568
+ if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`${path} must be a positive integer`);
1569
+ return value;
1570
+ }
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;
1574
+ }
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;
1578
+ }
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;
1582
+ }
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;
1587
+ }
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];
1595
+ }
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;
1599
+ }
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}`);
1605
+ }
1606
+ //#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
+ }
1625
+ //#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 })
1647
+ });
1648
+ }
1649
+ //#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 };