@rivus/agent 0.16.1 → 0.16.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,888 +1,3 @@
1
- import { createPiManagedSessionContext } from "../src/adapters/pi/model-management/pi-managed-session-context.js";
2
- import { ensurePiModel } from "../src/adapters/pi/model-management/pi-model-resolution.js";
3
- import { openPiModelManagementDeployment } from "../src/bootstrap/deployment/model-management/pi-model-management-deployment.js";
4
- import { mkdir, readFile, stat } from "node:fs/promises";
5
- import { createHash, randomUUID } from "node:crypto";
6
- import { homedir } from "node:os";
7
- import { join, relative } from "node:path";
8
- import { Effect } from "effect";
9
- import * as Lark from "@larksuiteoapi/node-sdk";
10
- import { createAgentSession, ModelRuntime, SessionManager, SettingsManager } from "@earendil-works/pi-coding-agent";
11
- import {
12
- createAgentsMdInstructionsProvider,
13
- createAgentHarness,
14
- createAgentHarnessPooledRuntime,
15
- createBackgroundSessionHostTools,
16
- createBackgroundSessionService,
17
- createBackgroundSessionStepSourceMessageId,
18
- createBackgroundSessionSupervisor,
19
- createRivusMemoryToolDescriptor,
20
- createConfiguredFeishuAutomationCardSender,
21
- createConfiguredFeishuBackgroundSessionDelivery,
22
- createConfiguredFeishuCardRolloverRuntime,
23
- createConfiguredFeishuHumanInteractionPresenter,
24
- createConfiguredFeishuOpenApiClient,
25
- createConfiguredFeishuTextReplySender,
26
- createFeishuCotPublisher,
27
- createFeishuDeploymentEndpoint,
28
- createFeishuPresentationPreparation,
29
- createFeishuTopicContextResolver,
30
- createSystemClock,
31
- createFeishuCardDeliveryReconciler,
32
- createHumanInteractionEndpointRegistry,
33
- createHumanInteractionService,
34
- createHumanInteractionToolApprovalGateway,
35
- createHumanInteractionModelChangeApproval,
36
- createJsonFetchRequest,
37
- createJsonFileFeishuCardTargetRegistry,
38
- createJsonlAgentEventLog,
39
- createJsonlHumanInteractionRepository,
40
- createLangfuseAgentTelemetry,
41
- createLazyFeishuWebSocketEventDispatcher,
42
- createPiAgentLoop,
43
- createProjectMemoryPromptPreparer,
44
- createPiSessionRegistry,
45
- createRoutedHumanInteractionToolApprovalService,
46
- createSessionScheduler,
47
- AUTOMATION_SUPPRESSION_PREFIX,
48
- createScheduledAutomation,
49
- createToolBroker,
50
- createUuidRunIds,
51
- createWorkspaceRootHandle,
52
- loadRivusDeploymentManifest,
53
- mergePiProviderBaseUrlOverride,
54
- openJsonlBackgroundSessionDeliveryStore,
55
- openJsonlBackgroundSessionRepository,
56
- resolveBackgroundSessionSupervisorIntervalMs,
57
- resolveFeishuDeliveryChatId,
58
- openJsonlFeishuCardDeliveryLedger,
59
- openJsonlFeishuInboxRepository,
60
- openJsonFeishuSessionStore,
61
- openJsonlAgentMemoryService,
62
- openJsonAutomationTickRepository,
63
- openJsonlToolOperationLedger,
64
- openJsonlRecoveryControl,
65
- readAutomationPresentation,
66
- resolveFeishuEndpointCredentials,
67
- resolveLangfuseTelemetryConfig,
68
- type CreateRivusDeploymentBackgroundSessionInput,
69
- type CreateRivusDeploymentEndpointInput,
70
- type CreateRivusDeploymentAutomationInput,
71
- type CreateRivusDeploymentRuntimeInput,
72
- type ConfiguredFeishuOpenApiResponse,
73
- type FeishuAgentRunPreparation,
74
- type FeishuBackgroundSessionDelivery,
75
- type FeishuWebSocketClient,
76
- type RivusDaemonConfig,
77
- type RivusDaemonEnv,
78
- type RivusEndpointDeployment,
79
- type RivusDeploymentBackgroundSession,
80
- type RivusDeploymentBootstrapContext,
81
- type RivusThinkingLevel
82
- } from "@rivus/agent";
83
- import {
84
- createPiBashTool,
85
- createPiSkillReadTools,
86
- createPiSessionResources,
87
- createPiSkillRuntime,
88
- resolvePiSessionToolNames,
89
- createPiToolNameResolver,
90
- createPiToolProxyDefinitions,
91
- validatePiSkillCommand
92
- } from "@rivus/agent/pi";
93
-
94
- type PiSessionOptions = NonNullable<Parameters<typeof createAgentSession>[0]>;
95
-
96
- const STATE_DIR = process.env.RIVUS_DEPLOYMENT_STATE_DIR?.trim() || ".rivus/deployment";
97
- const PI_AGENT_DIR = join(STATE_DIR, "pi-agent");
98
- const PI_AUTH_FILE = join(STATE_DIR, "pi-auth.json");
99
- const PI_MODELS_FILE = join(STATE_DIR, "pi-models.json");
100
- const THINKING_LEVELS = new Set<RivusThinkingLevel>(["off", "minimal", "low", "medium", "high", "xhigh"]);
101
-
102
- export async function createRivusDeploymentAdapters(context: RivusDeploymentBootstrapContext) {
103
- await mkdir(PI_AGENT_DIR, { recursive: true });
104
- const hasManagedState = await stat(join(STATE_DIR, "model-management", "model-state.json")).then(
105
- () => true,
106
- (error: NodeJS.ErrnoException) => {
107
- if (error.code === "ENOENT") return false;
108
- throw error;
109
- }
110
- );
111
- const deferModel = context.env.RIVUS_MODEL_MANAGEMENT_ENABLED?.trim() === "true" || hasManagedState;
112
- const piOptions = await createPiSessionOptions(context, deferModel);
113
- const telemetryConfig = resolveLangfuseTelemetryConfig(context.env);
114
- let telemetry: ReturnType<typeof createLangfuseAgentTelemetry> | undefined;
115
- const memory = await openJsonlAgentMemoryService({
116
- filePath: join(STATE_DIR, "memory", "agent-memory.jsonl")
117
- });
118
- const memoryTenantId = context.env.RIVUS_MEMORY_TENANT_ID?.trim() || "local";
119
- const request = createJsonFetchRequest();
120
- const createOpenApiClient = (config: RivusDaemonConfig) =>
121
- createConfiguredFeishuOpenApiClient({
122
- config,
123
- request: (input) => request(input).pipe(Effect.map((response) => response as ConfiguredFeishuOpenApiResponse))
124
- });
125
- const interactionRegistry = createHumanInteractionEndpointRegistry();
126
- const manifest = await loadRivusDeploymentManifest(context.manifestPath);
127
- const defaultEndpoint = manifest.endpoints.find((endpoint) => endpoint.id === manifest.defaultEndpointId)!;
128
- const management = await openPiModelManagementDeployment({
129
- agentId: manifest.defaultAgentId,
130
- approval: createHumanInteractionModelChangeApproval({
131
- endpointId: manifest.defaultEndpointId,
132
- registry: interactionRegistry
133
- }),
134
- agentCount: manifest.agents.length,
135
- endpointId: manifest.defaultEndpointId,
136
- env: context.env,
137
- environmentOverrides: context.environmentOverrides ?? process.env,
138
- ...(context.envFilePath ? { envFilePath: context.envFilePath } : {}),
139
- modelAuthPath: PI_AUTH_FILE,
140
- modelCatalogPath: PI_MODELS_FILE,
141
- modelRuntime: piOptions.modelRuntime!,
142
- reply: (messageId, text) => {
143
- const config = createEndpointConfig(defaultEndpoint, manifest.defaultAgentId, context.env);
144
- return createConfiguredFeishuTextReplySender({ config, client: createOpenApiClient(config) }).reply(
145
- messageId,
146
- text
147
- );
148
- },
149
- stateDirectory: STATE_DIR,
150
- thinkingLevel: piOptions.thinkingLevel ?? "medium"
151
- });
152
- try {
153
- telemetry = telemetryConfig ? createLangfuseAgentTelemetry(telemetryConfig) : undefined;
154
- if (management && !management.enabled) {
155
- piOptions.model = await ensurePiModel({
156
- modelRuntime: piOptions.modelRuntime!,
157
- modelsPath: PI_MODELS_FILE,
158
- target: management.model
159
- });
160
- }
161
- if (management?.enabled && management.recoveryRequired) {
162
- console.error("Model management requires recovery; business Runs are paused. Query rivus model status --json.");
163
- }
164
- if (management?.enabled && management.skillInstallation.status === "conflict") {
165
- console.error("The runtime-management Skill has local edits; its installed instructions were preserved.");
166
- }
167
- const backgroundSessionsConfig = manifest.backgroundSessions;
168
- const sessionRepository = backgroundSessionsConfig?.enabled
169
- ? await openJsonlBackgroundSessionRepository({
170
- filePath: join(STATE_DIR, "background-sessions", "sessions.jsonl")
171
- })
172
- : undefined;
173
- const sessionDeliveries = backgroundSessionsConfig?.enabled
174
- ? await openJsonlBackgroundSessionDeliveryStore({
175
- filePath: join(STATE_DIR, "background-sessions", "deliveries.jsonl")
176
- })
177
- : undefined;
178
- const deliveryClients = new Map<string, FeishuBackgroundSessionDelivery>();
179
- const backgroundService = backgroundSessionsConfig?.enabled
180
- ? createBackgroundSessionService({
181
- clock: { now: () => new Date().toISOString() },
182
- deliveries: sessionDeliveries!,
183
- repository: sessionRepository!
184
- })
185
- : undefined;
186
- const createBackgroundSessionAdapter = (
187
- input: CreateRivusDeploymentBackgroundSessionInput
188
- ): RivusDeploymentBackgroundSession => {
189
- const resolveDeliverySender = async (endpointId: string): Promise<FeishuBackgroundSessionDelivery> => {
190
- const existing = deliveryClients.get(endpointId);
191
- if (existing) return existing;
192
- const endpoint = manifest.endpoints.find(({ id }) => id === endpointId);
193
- if (!endpoint) throw new Error(`background session delivery endpoint not found: ${endpointId}`);
194
- const config = createEndpointConfig(endpoint, endpoint.agentId, context.env);
195
- const sender = createConfiguredFeishuBackgroundSessionDelivery({
196
- client: createOpenApiClient(config),
197
- config
198
- });
199
- deliveryClients.set(endpointId, sender);
200
- return sender;
201
- };
202
- const supervisor = createBackgroundSessionSupervisor({
203
- clock: { now: () => new Date().toISOString() },
204
- config: {
205
- intervalMs: resolveBackgroundSessionSupervisorIntervalMs(input.config.leaseMs),
206
- leaseMs: input.config.leaseMs,
207
- leaseRenewalIntervalMs: input.config.leaseRenewalIntervalMs,
208
- maxConcurrentSessions: input.config.maxConcurrentSessions,
209
- maxConsecutiveFailures: input.config.maxConsecutiveFailures,
210
- retryBackoffMs: input.config.retryBackoffMs,
211
- sessionLifetimeMs: input.config.sessionLifetimeMs
212
- },
213
- deliveries: sessionDeliveries!,
214
- deliver: async (delivery) => {
215
- const session = await sessionRepository!.get(delivery.sessionId);
216
- if (!session) throw new Error(`background session not found for delivery: ${delivery.sessionId}`);
217
- if (!session.origin.conversationId) {
218
- throw new Error(`background session has no delivery conversation: ${delivery.sessionId}`);
219
- }
220
- const sender = await resolveDeliverySender(session.origin.endpointId);
221
- return sender.deliver({
222
- chatId: resolveFeishuDeliveryChatId(session.origin.conversationId),
223
- deliveryId: delivery.deliveryId,
224
- displayName: session.displayName,
225
- kind: delivery.kind,
226
- sessionId: session.sessionId,
227
- text: delivery.text
228
- });
229
- },
230
- onError: (error) => {
231
- console.error("Background session supervisor failed", error);
232
- },
233
- repository: sessionRepository!,
234
- runStep: async ({ session, signal, wakeText }) => {
235
- let runId: string | undefined;
236
- const invocation = {
237
- allowedActorOpenIds: session.origin.allowedActorOpenIds,
238
- ...(session.origin.conversationId ? { conversationId: session.origin.conversationId } : {}),
239
- endpointId: session.origin.endpointId,
240
- kind: "background-session" as const,
241
- ...(session.origin.memory ? { memory: session.origin.memory } : {}),
242
- sessionId: session.sessionId,
243
- sourceMessageId: createBackgroundSessionStepSourceMessageId(session.sessionId, session.stepCount + 1),
244
- tenantKey: session.origin.tenantKey
245
- };
246
- const abortPromise = new Promise<never>((_resolve, reject) => {
247
- signal.addEventListener(
248
- "abort",
249
- () => {
250
- if (runId) {
251
- void input.cancel({
252
- agentId: session.authority.agentId,
253
- reason: "background session step aborted",
254
- runId,
255
- sessionKey: session.authority.sessionKey
256
- });
257
- }
258
- reject(new Error("background session step aborted"));
259
- },
260
- { once: true }
261
- );
262
- });
263
- const runPromise = input
264
- .run({
265
- agentId: session.authority.agentId,
266
- invocation,
267
- onUpdate: (update) => {
268
- if (update.event.type === "agent_run_accepted" && !runId) {
269
- runId = update.event.runId;
270
- }
271
- },
272
- sessionKey: session.authority.sessionKey,
273
- text: wakeText
274
- })
275
- .then((result) => readStepRunResult(result));
276
- return Promise.race([runPromise, abortPromise]);
277
- },
278
- sleep
279
- });
280
- let running = false;
281
- return {
282
- running: () => running,
283
- status: () => supervisor.status(),
284
- start: async () => {
285
- await Effect.runPromise(supervisor.recover());
286
- await Effect.runPromise(supervisor.start());
287
- running = true;
288
- },
289
- stop: async () => {
290
- await Effect.runPromise(supervisor.stop());
291
- running = false;
292
- }
293
- };
294
- };
295
- return {
296
- dispose: async () => {
297
- if (management?.enabled) await management.close();
298
- await telemetry?.shutdown();
299
- },
300
- createRecoveryControl: () =>
301
- openJsonlRecoveryControl({
302
- endpointsDirectory: join(STATE_DIR, "endpoints"),
303
- instancesDirectory: join(STATE_DIR, "instances")
304
- }),
305
- createBackgroundSession: backgroundSessionsConfig?.enabled
306
- ? (input: CreateRivusDeploymentBackgroundSessionInput) => createBackgroundSessionAdapter(input)
307
- : undefined,
308
- createAutomation: async (input: CreateRivusDeploymentAutomationInput) => {
309
- const config = createEndpointConfig(input.deliveryEndpoint, input.definition.agentId, context.env);
310
- const openApiClient = createOpenApiClient(config);
311
- const sender = createConfiguredFeishuAutomationCardSender({
312
- client: openApiClient,
313
- config
314
- });
315
- const repository = await openJsonAutomationTickRepository({
316
- filePath: join(
317
- STATE_DIR,
318
- "automations",
319
- createHash("sha256").update(input.automationId).digest("hex").slice(0, 16),
320
- "ticks.json"
321
- )
322
- });
323
- const target = resolveAutomationTarget(input.definition.delivery.targetRef, context.env);
324
- const automation = createScheduledAutomation({
325
- automationId: input.automationId,
326
- binding: {
327
- agentId: input.definition.agentId,
328
- bindingId: input.automationId,
329
- delivery: {
330
- endpointId: input.definition.delivery.endpointId,
331
- targetKey: createHash("sha256").update(target).digest("hex"),
332
- targetType: input.definition.delivery.targetType
333
- },
334
- schedule: input.definition.schedule,
335
- servicePrincipalId: `automation:${input.automationId}`,
336
- skillGrantRevision: input.definition.runtimeDefinition.skillGrantSet.revision,
337
- skillIds: input.definition.template.requestedSkillIds,
338
- templateId: input.definition.templateId,
339
- timeZone: input.definition.timeZone,
340
- toolIds: input.definition.template.requestedToolIds
341
- },
342
- createInput: input.definition.template.createInput,
343
- deliver: ({ body, idempotencyKey, presentation }) =>
344
- Effect.runPromise(
345
- sender.send({
346
- idempotencyKey,
347
- receiveId: target,
348
- receiveIdType: input.definition.delivery.targetType,
349
- markdown: body,
350
- ...(presentation === undefined ? {} : { presentation })
351
- })
352
- ),
353
- onError: () => {
354
- console.error(`Scheduled Automation ${input.automationId} failed; it will retry`);
355
- },
356
- repository,
357
- run: async (runInput) => {
358
- const result = readAutomationRunResult(await input.run(runInput));
359
- const projected =
360
- result.body === undefined
361
- ? undefined
362
- : input.definition.template.createPresentation?.({
363
- occurrence: runInput.occurrence,
364
- text: result.body
365
- });
366
- const presentation = projected ? readAutomationPresentation(projected) : undefined;
367
- return { ...result, ...(presentation === undefined ? {} : { presentation }) };
368
- }
369
- });
370
- return automation;
371
- },
372
- createEndpoint: async (input: CreateRivusDeploymentEndpointInput) => {
373
- const credentials = resolveFeishuEndpointCredentials(input.definition.credentialRef, context.env);
374
- const botOpenId = await resolveFeishuBotOpenId(credentials, input.definition.baseUrl);
375
- const endpointState = join(STATE_DIR, "endpoints", input.endpointId);
376
- const cardTargets = createJsonFileFeishuCardTargetRegistry({
377
- filePath: join(endpointState, "feishu-card-targets.json")
378
- });
379
- const cardLedger = await openJsonlFeishuCardDeliveryLedger({
380
- filePath: join(endpointState, "feishu-card-delivery.jsonl")
381
- });
382
- const inbox = await openJsonlFeishuInboxRepository({ filePath: join(endpointState, "feishu-inbox.jsonl") });
383
- const sessionStore = await openJsonFeishuSessionStore({
384
- filePath: join(endpointState, "feishu-session-store.json")
385
- });
386
- const config = createEndpointConfig(input.definition, input.agentId, context.env);
387
- const openApiClient = createOpenApiClient(config);
388
- const promptContext = createFeishuTopicContextResolver({
389
- baseUrl: input.definition.baseUrl,
390
- client: openApiClient
391
- });
392
- const cotPublisher = input.definition.experimental?.cotMessages
393
- ? createFeishuCotPublisher({
394
- baseUrl: resolveExperimentalCotBaseUrl(context.env),
395
- client: openApiClient,
396
- minIntervalMs: input.definition.streamMinIntervalMs
397
- })
398
- : undefined;
399
- const interactions = createHumanInteractionService({
400
- clock: { now: () => new Date().toISOString() },
401
- presenter: createConfiguredFeishuHumanInteractionPresenter({
402
- client: openApiClient,
403
- config
404
- }),
405
- repository: createJsonlHumanInteractionRepository({
406
- filePath: join(endpointState, "human-interactions.jsonl")
407
- })
408
- });
409
- const cardRollover = createConfiguredFeishuCardRolloverRuntime({
410
- agentName: input.agentId,
411
- cardTargets,
412
- client: openApiClient,
413
- clock: createSystemClock(),
414
- config,
415
- ledger: cardLedger,
416
- onError: (error) => {
417
- console.error(`Feishu card rollover failed for endpoint ${input.endpointId}`, error);
418
- },
419
- ...(input.definition.progressDisplay === undefined
420
- ? {}
421
- : { progressDisplay: input.definition.progressDisplay }),
422
- sleep,
423
- title: input.agentId
424
- });
425
- const publisher = cardRollover.rollover;
426
- const endpointEvents = createJsonlAgentEventLog({
427
- filePath: join(STATE_DIR, "instances", input.instanceId, "agent-events.jsonl")
428
- });
429
- const endpointInitialEvents = await Effect.runPromise(endpointEvents.readAll());
430
- await Effect.runPromise(
431
- createFeishuCardDeliveryReconciler({
432
- events: endpointInitialEvents,
433
- ledger: cardLedger,
434
- publish: (action) => publisher.publish(action)
435
- }).reconcile()
436
- );
437
- const replies = createConfiguredFeishuTextReplySender({
438
- client: openApiClient,
439
- config
440
- });
441
- const prepareCardTarget = (run: FeishuAgentRunPreparation) => cardRollover.prepareRun(run);
442
- const endpoint = createFeishuDeploymentEndpoint({
443
- agentId: input.agentId,
444
- botOpenId,
445
- cardRollover: cardRollover.transport,
446
- finalizeRun: (runId) => cardRollover.rollover.releaseRun(runId),
447
- cancel: input.cancel,
448
- endpointId: input.endpointId,
449
- eventDispatcher: createLazyFeishuWebSocketEventDispatcher(() => new Lark.EventDispatcher({})),
450
- groupPolicy: input.definition.groupPolicy,
451
- handle: input.handle,
452
- inboxRepository: inbox,
453
- initialEvents: endpointInitialEvents,
454
- interactions,
455
- maxPendingMessages: 100,
456
- memoryTenantId,
457
- ...(input.projectSpaceId ? { projectSpaceId: input.projectSpaceId } : {}),
458
- onCapacityExceeded: (payload) =>
459
- replies.reply(payload.event.message.message_id, "Rivus is busy. Please retry in a moment."),
460
- prepareRun: createFeishuPresentationPreparation({
461
- ...(cotPublisher ? { cotPublisher } : {}),
462
- prepareCardTarget,
463
- reportCotError: (operation, error) => reportCotError(input.endpointId, operation, error)
464
- }),
465
- promptContext,
466
- publish: (action) => publisher.publish(action),
467
- reply: (messageId, text) => replies.reply(messageId, text),
468
- sessionStore,
469
- ...(input.steer ? { steer: input.steer } : {}),
470
- ...(cotPublisher
471
- ? {
472
- publishRunUpdate: (update) =>
473
- cotPublisher
474
- .publish(update)
475
- .pipe(Effect.catchAll((error) => reportCotError(input.endpointId, "update", error)))
476
- }
477
- : {}),
478
- sessionNamespace: input.definition.sessionNamespace,
479
- sleep,
480
- websocketClient: createLazyFeishuWebSocketClient(credentials, input.definition.baseUrl),
481
- workerConcurrency: 4
482
- });
483
- interactionRegistry.register(input.endpointId, interactions);
484
- return endpoint;
485
- },
486
- createRuntime: async (input: CreateRivusDeploymentRuntimeInput) => {
487
- const instanceState = join(STATE_DIR, "instances", input.instanceId);
488
- await mkdir(instanceState, { recursive: true });
489
- const eventLog = createJsonlAgentEventLog({ filePath: join(instanceState, "agent-events.jsonl") });
490
- const initialEvents = await Effect.runPromise(eventLog.readAll());
491
- const broker = createToolBroker({
492
- approvals: createRoutedHumanInteractionToolApprovalService(interactionRegistry),
493
- catalog: input.catalog,
494
- hostTools: [
495
- ...(input.definition.memory.tool ? [createRivusMemoryToolDescriptor({ memory })] : []),
496
- ...(backgroundService
497
- ? [
498
- ...createBackgroundSessionHostTools({
499
- createSessionId: () => `bg-${randomUUID()}`,
500
- definition: input.definition,
501
- service: backgroundService
502
- })
503
- ]
504
- : [])
505
- ],
506
- operations: await openJsonlToolOperationLedger({ filePath: join(instanceState, "tool-operations.jsonl") }),
507
- policy: { current: async () => ({ epoch: 1, revokedToolIds: [] }) }
508
- });
509
- const resolveToolName = createPiToolNameResolver(input.definition.tools);
510
- const skillRuntime = createPiSkillRuntime(input.definition.skills);
511
- const workingDirectory = input.projectSpace?.workingDirectory ?? process.cwd();
512
- const runContexts = management?.enabled
513
- ? management.createRunContexts({
514
- agentId: input.agentId,
515
- instanceId: input.instanceId,
516
- toolGrantSet: input.definition.toolGrantSet
517
- })
518
- : undefined;
519
- const workspaceRoot = input.projectSpace?.root ?? process.cwd();
520
- const workspaceInstructions = await createAgentsMdInstructionsProvider().resolve({
521
- maxBytes: 64 * 1024,
522
- workingDirectory: relative(workspaceRoot, workingDirectory) || ".",
523
- workspaceRoot: await createWorkspaceRootHandle(workspaceRoot)
524
- });
525
- const prepareProjectMemory =
526
- input.projectSpace && input.definition.memory.scopes.includes("project")
527
- ? createProjectMemoryPromptPreparer({
528
- agentId: input.agentId,
529
- memory,
530
- projectId: input.projectSpace.id
531
- })
532
- : undefined;
533
- const sessionRegistry = createPiSessionRegistry({
534
- createSession: async (firstInput) => {
535
- let activeInput = firstInput;
536
- const resources = await createPiSessionResources({
537
- agentDir: PI_AGENT_DIR,
538
- appendSystemPromptOverride: () =>
539
- [workspaceInstructions.content, skillRuntime.prompt].filter((content) => content.length > 0),
540
- cwd: workingDirectory,
541
- homeDirectory: homedir(),
542
- ...(input.projectSpace ? { projectSkillPaths: input.projectSpace.skillPaths } : {}),
543
- systemPromptOverride: () => input.definition.systemPrompt
544
- });
545
- const managedContext =
546
- management?.enabled && runContexts && input.definition.runtimeToolGrantSet.toolIds.includes("bash")
547
- ? createPiManagedSessionContext({
548
- ...(resources.bashToolOptions ? { bashToolOptions: resources.bashToolOptions } : {}),
549
- binDirectory: management.binDirectory,
550
- contexts: runContexts.registry,
551
- cwd: workingDirectory,
552
- nodeExecutable: process.execPath,
553
- socketPath: management.socketPath
554
- })
555
- : undefined;
556
- const bashTool = input.definition.runtimeToolGrantSet.toolIds.includes("bash")
557
- ? (managedContext?.tool ?? createPiBashTool(workingDirectory, resources.bashToolOptions))
558
- : undefined;
559
- const customTools = [
560
- ...(bashTool ? [bashTool] : []),
561
- ...createPiSkillReadTools({
562
- cwd: workingDirectory,
563
- runtimeToolIds: input.definition.runtimeToolGrantSet.toolIds,
564
- skillPaths: resources.skillNames.size > 0 ? resources.skillPaths : []
565
- }),
566
- ...createPiToolProxyDefinitions({
567
- agentId: input.agentId,
568
- approvals: createHumanInteractionToolApprovalGateway({ registry: interactionRegistry }),
569
- broker,
570
- getActiveInput: () => activeInput,
571
- instanceId: input.instanceId,
572
- memoryScopes: input.definition.memory.scopes,
573
- toolGrantSet: input.definition.toolGrantSet,
574
- tools: input.definition.tools
575
- }),
576
- ...(skillRuntime.tool ? [skillRuntime.tool] : [])
577
- ];
578
- const nativeToolIds = bashTool
579
- ? input.definition.runtimeToolGrantSet.toolIds.filter((toolId) => toolId !== "bash")
580
- : input.definition.runtimeToolGrantSet.toolIds;
581
- const activeToolNames = resolvePiSessionToolNames(nativeToolIds, customTools);
582
- const result = await createAgentSession(
583
- resources.withSessionOptions({
584
- ...piOptions,
585
- ...(management?.enabled ? management.runtime.getSessionOptions() : {}),
586
- customTools,
587
- excludeTools: [],
588
- sessionManager: SessionManager.create(workingDirectory, join(instanceState, "sessions")),
589
- tools: [...activeToolNames]
590
- })
591
- );
592
- return {
593
- activate: (loopInput) => {
594
- activeInput = loopInput;
595
- managedContext?.activate(loopInput);
596
- },
597
- deactivate: () => managedContext?.deactivate(),
598
- dispose: () => result.session.dispose(),
599
- preparePrompt: async (loopInput) => {
600
- validatePiSkillCommand(loopInput.text, resources.skillNames);
601
- return prepareProjectMemory ? prepareProjectMemory(loopInput) : loopInput.text;
602
- },
603
- resolveToolName,
604
- refreshResources: () => resources.refresh(),
605
- session: result.session
606
- };
607
- }
608
- });
609
- const unregisterModels = management?.enabled
610
- ? management.runtime.registerSessionRegistry(sessionRegistry)
611
- : undefined;
612
- const loop = createPiAgentLoop({
613
- supportsSteering: true,
614
- disposeSessionAfterRun: false,
615
- ...(management?.enabled ? { runBoundary: management.boundary } : {}),
616
- ...(telemetry ? { modelContentObserver: telemetry.modelContentObserver } : {}),
617
- resolveSession: (loopInput) => sessionRegistry.resolve(loopInput)
618
- });
619
- const scheduler = createSessionScheduler({
620
- createRuntime: (sessionKey) =>
621
- createAgentHarnessPooledRuntime(
622
- createAgentHarness({
623
- clock: createSystemClock(),
624
- eventSinks: telemetry ? [eventLog, telemetry.sink] : [eventLog],
625
- initialEvents: eventsForSession(initialEvents, sessionKey),
626
- loop,
627
- runIds: createUuidRunIds(),
628
- ...(input.binding.kind === "background-session" && backgroundSessionsConfig
629
- ? { runTimeoutMs: backgroundSessionsConfig.stepTimeoutMs }
630
- : {})
631
- })
632
- ),
633
- maxConcurrentSessions:
634
- input.binding.kind === "background-session" ? (backgroundSessionsConfig?.maxConcurrentSessions ?? 4) : 4,
635
- maxQueuedRuns: 32
636
- });
637
- return {
638
- ...scheduler,
639
- dispose: async () => {
640
- await scheduler.dispose?.();
641
- await sessionRegistry.disposeAll();
642
- unregisterModels?.();
643
- runContexts?.unregister();
644
- }
645
- };
646
- }
647
- };
648
- } catch (error) {
649
- await Promise.allSettled([management?.enabled ? management.close() : Promise.resolve(), telemetry?.shutdown()]);
650
- throw error;
651
- }
652
- }
653
-
654
- function eventsForSession<T extends { readonly runId: string; readonly sessionKey?: string }>(
655
- events: ReadonlyArray<T>,
656
- sessionKey: string
657
- ): ReadonlyArray<T> {
658
- const runIds = new Set(events.filter((event) => event.sessionKey === sessionKey).map((event) => event.runId));
659
- return events.filter((event) => runIds.has(event.runId));
660
- }
661
-
662
- function resolveAutomationTarget(targetRef: string, env: Readonly<Record<string, string | undefined>>): string {
663
- if (!targetRef.startsWith("env:")) throw new Error("Automation delivery targetRef must use env:<VARIABLE>");
664
- const variable = targetRef.slice("env:".length);
665
- if (!/^[A-Z][A-Z0-9_]*$/.test(variable)) throw new Error(`Invalid Automation delivery targetRef: ${targetRef}`);
666
- const target = env[variable]?.trim();
667
- if (!target) throw new Error(`${variable} is required`);
668
- return target;
669
- }
670
-
671
- function resolveExperimentalCotBaseUrl(env: Readonly<Record<string, string | undefined>>): string {
672
- const baseUrl = env.RIVUS_FEISHU_COT_BASE_URL?.trim();
673
- if (!baseUrl) {
674
- throw new Error("RIVUS_FEISHU_COT_BASE_URL is required when experimental.cotMessages is enabled");
675
- }
676
- return baseUrl;
677
- }
678
-
679
- function reportCotError(endpointId: string, operation: string, error: unknown): Effect.Effect<void> {
680
- return Effect.sync(() => {
681
- const detail = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
682
- console.error(`Experimental Feishu COT ${operation} failed for endpoint ${endpointId}: ${detail}`);
683
- });
684
- }
685
-
686
- function readAutomationRunResult(result: unknown): {
687
- readonly body?: string;
688
- readonly runId: string;
689
- readonly suppressedReason?: string;
690
- } {
691
- const { finalText, runId } = readStepRunResult(result);
692
- const trimmedText = finalText.trim();
693
- if (trimmedText.startsWith(AUTOMATION_SUPPRESSION_PREFIX)) {
694
- const reason = trimmedText.slice(AUTOMATION_SUPPRESSION_PREFIX.length).trim();
695
- if (!reason) throw new Error("Scheduled Automation suppression requires a reason");
696
- return { runId, suppressedReason: reason };
697
- }
698
- if (!trimmedText) throw new Error("Scheduled Automation Agent Run did not produce final text");
699
- return { body: finalText, runId };
700
- }
701
-
702
- function readStepRunResult(result: unknown): { readonly finalText: string; readonly runId: string } {
703
- if (
704
- result !== null &&
705
- typeof result === "object" &&
706
- "finalText" in result &&
707
- typeof result.finalText === "string" &&
708
- "runId" in result &&
709
- typeof result.runId === "string" &&
710
- result.runId.trim() !== ""
711
- ) {
712
- return { finalText: result.finalText, runId: result.runId };
713
- }
714
- throw new Error("Background session Agent Run did not produce a runId and final text");
715
- }
716
-
717
- function createLazyFeishuWebSocketClient(
718
- credentials: {
719
- readonly appId: string;
720
- readonly appSecret: string;
721
- },
722
- domain: string
723
- ): FeishuWebSocketClient {
724
- let client: Lark.WSClient | undefined;
725
- let connected = false;
726
- return {
727
- connected: () => connected,
728
- close: () => {
729
- client?.close();
730
- client = undefined;
731
- connected = false;
732
- },
733
- start: (options) =>
734
- new Promise<void>((resolve, reject) => {
735
- let settled = false;
736
- const settle = (callback: () => void) => {
737
- if (settled) return;
738
- settled = true;
739
- clearTimeout(timeout);
740
- callback();
741
- };
742
- const timeout = setTimeout(
743
- () => settle(() => reject(new Error("Feishu WebSocket handshake timed out after 15000ms"))),
744
- 15_000
745
- );
746
- client ??= new Lark.WSClient({
747
- ...credentials,
748
- domain,
749
- handshakeTimeoutMs: 10_000,
750
- onError: (error) => {
751
- connected = false;
752
- settle(() => reject(error));
753
- },
754
- onReady: () => {
755
- connected = true;
756
- settle(resolve);
757
- },
758
- onReconnected: () => {
759
- connected = true;
760
- },
761
- onReconnecting: () => {
762
- connected = false;
763
- }
764
- });
765
- void client.start(options as Parameters<Lark.WSClient["start"]>[0]).catch((error: unknown) => {
766
- connected = false;
767
- settle(() => reject(error));
768
- });
769
- })
770
- };
771
- }
772
-
773
- async function resolveFeishuBotOpenId(
774
- credentials: {
775
- readonly appId: string;
776
- readonly appSecret: string;
777
- },
778
- domain: string
779
- ): Promise<string> {
780
- const response = (await new Lark.Client({ ...credentials, domain }).request({
781
- method: "GET",
782
- url: "/open-apis/bot/v3/info"
783
- })) as { readonly bot?: { readonly open_id?: string }; readonly code?: number; readonly msg?: string };
784
- const openId = response.bot?.open_id;
785
- if (response.code !== 0 || !openId) {
786
- throw new Error(`Feishu bot identity lookup failed: ${response.msg ?? "response missing bot.open_id"}`);
787
- }
788
- return openId;
789
- }
790
-
791
- async function createPiSessionOptions(
792
- context: RivusDeploymentBootstrapContext,
793
- deferModel = false
794
- ): Promise<PiSessionOptions> {
795
- const modelReference = optional(context.env.PI_MODEL);
796
- const configuredModel = modelReference ? parseModelReference(modelReference) : undefined;
797
- const provider = configuredModel?.provider;
798
- const apiKey = await resolvePiApiKey(context.env);
799
- const baseUrl = optional(context.env.PI_BASE_URL);
800
- if ((apiKey || baseUrl) && !provider) {
801
- throw new Error("PI_API_KEY and PI_BASE_URL require PI_MODEL in provider/model form");
802
- }
803
- if (baseUrl && !deferModel) await writeProviderBaseUrlOverride(provider!, baseUrl);
804
- const modelRuntime = await ModelRuntime.create({
805
- allowModelNetwork: false,
806
- authPath: PI_AUTH_FILE,
807
- modelsPath: baseUrl || deferModel ? PI_MODELS_FILE : null
808
- });
809
- if (apiKey) await modelRuntime.setRuntimeApiKey(provider!, apiKey);
810
- const model =
811
- configuredModel && !deferModel
812
- ? modelRuntime.getModel(configuredModel.provider, configuredModel.modelId)
813
- : undefined;
814
- if (modelReference && !model && !deferModel)
815
- throw new Error(`PI_MODEL ${modelReference} was not found in the Pi model runtime`);
816
- const settings = deferModel
817
- ? SettingsManager.create(process.cwd(), PI_AGENT_DIR, { projectTrusted: false })
818
- : undefined;
819
- const thinkingLevel =
820
- readThinkingLevel(context.env.PI_THINKING_LEVEL) ??
821
- (configuredModel
822
- ? settings?.getModelThinkingLevel(configuredModel.provider, configuredModel.modelId)
823
- : undefined) ??
824
- settings?.getDefaultThinkingLevel();
825
- return {
826
- cwd: process.cwd(),
827
- modelRuntime,
828
- ...(model ? { model } : {}),
829
- ...(thinkingLevel ? { thinkingLevel } : {})
830
- };
831
- }
832
-
833
- function createEndpointConfig(
834
- definition: RivusEndpointDeployment,
835
- agentId: string,
836
- env: RivusDaemonEnv
837
- ): RivusDaemonConfig {
838
- return {
839
- agentId,
840
- feishu: {
841
- ...resolveFeishuEndpointCredentials(definition.credentialRef, env),
842
- baseUrl: definition.baseUrl,
843
- cardStreamLeaseMs: definition.cardStreamLeaseMs,
844
- streamMinIntervalMs: definition.streamMinIntervalMs
845
- },
846
- pi: {}
847
- };
848
- }
849
-
850
- async function resolvePiApiKey(env: Readonly<Record<string, string | undefined>>): Promise<string | undefined> {
851
- const inline = optional(env.PI_API_KEY);
852
- const filePath = optional(env.PI_API_KEY_FILE);
853
- if (inline && filePath) throw new Error("PI_API_KEY and PI_API_KEY_FILE cannot both be set");
854
- if (inline) return inline;
855
- if (!filePath) return undefined;
856
- const contents = optional(await readFile(filePath, "utf8"));
857
- if (!contents) throw new Error("PI_API_KEY_FILE must not be empty");
858
- return contents;
859
- }
860
-
861
- function optional(value: string | undefined): string | undefined {
862
- return value?.trim() || undefined;
863
- }
864
-
865
- function parseModelReference(reference: string): { readonly modelId: string; readonly provider: string } {
866
- const separator = reference.indexOf("/");
867
- if (separator <= 0 || separator === reference.length - 1) {
868
- throw new Error("PI_MODEL must use provider/model form, for example zai/glm-5.2");
869
- }
870
- return { modelId: reference.slice(separator + 1), provider: reference.slice(0, separator) };
871
- }
872
-
873
- function readThinkingLevel(value: string | undefined): RivusThinkingLevel | undefined {
874
- const level = optional(value);
875
- if (!level) return undefined;
876
- if (!THINKING_LEVELS.has(level as RivusThinkingLevel)) {
877
- throw new Error("PI_THINKING_LEVEL must be one of off, minimal, low, medium, high, xhigh");
878
- }
879
- return level as RivusThinkingLevel;
880
- }
881
-
882
- function sleep(ms: number): Effect.Effect<void> {
883
- return Effect.promise(() => new Promise((resolve) => setTimeout(resolve, ms)));
884
- }
885
-
886
- async function writeProviderBaseUrlOverride(provider: string, baseUrl: string): Promise<void> {
887
- await mergePiProviderBaseUrlOverride({ baseUrl, filePath: PI_MODELS_FILE, provider });
888
- }
1
+ // Projects initialized by Gateway keep the historical bootstrap specifier while
2
+ // the implementation remains in the Gateway package canonical owner.
3
+ export { createRivusDeploymentAdapters } from "@rivus/agent/bootstrap/pi-feishu";