@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.
- package/LICENSE +21 -0
- package/README.md +6 -0
- package/dist/bootstrap/pi-feishu.d.ts +20 -0
- package/dist/bootstrap/pi-feishu.js +671 -0
- package/dist/chunks/background-session-authority.js +230 -0
- package/dist/chunks/background-session-control-input.js +45 -0
- package/dist/chunks/background-session-service.d.ts +390 -0
- package/dist/chunks/index.d.ts +4703 -0
- package/dist/chunks/node-rivus-deployment-manifest.js +1650 -0
- package/dist/chunks/rivus-node-entrypoint.js +4464 -0
- package/dist/chunks/service.js +12112 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +16 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +1215 -0
- package/dist/mcp.d.ts +92 -0
- package/dist/mcp.js +455 -0
- package/package.json +64 -0
- package/skills/runtime-management/SKILL.md +65 -0
- package/templates/a-share-briefing-analysis.mjs +93 -0
- package/templates/a-share-briefing-renderer.mjs +257 -0
- package/templates/a-share-index-evidence.mjs +99 -0
- package/templates/a-share-market-briefing.mjs +83 -0
- package/templates/a-share-market-date.mjs +10 -0
- package/templates/a-share-overseas-evidence.mjs +86 -0
- package/templates/a-share-policy-evidence.mjs +145 -0
- package/templates/a-share-provider-response.mjs +21 -0
- package/templates/a-share-sector-evidence.mjs +70 -0
- package/templates/acp-stdio-proxy.mjs +58 -0
- package/templates/current-weather.mjs +117 -0
- package/templates/html-drive-tools.mjs +262 -0
- package/templates/https-response-reader.mjs +36 -0
- package/templates/langfuse-drive-e2e.mjs +175 -0
- package/templates/pi-feishu-deployment.bootstrap.ts +3 -0
- package/templates/pi-feishu.bootstrap.ts +242 -0
- package/templates/rivus-agents.plugin.mjs +290 -0
- package/templates/rivus-langfuse-demo.config.json +37 -0
- package/templates/rivus-starter.plugin.mjs +47 -0
- package/templates/rivus.config.json +114 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1215 @@
|
|
|
1
|
+
import { $ as FeishuCotProtocolError, $n as AUTOMATION_SUPPRESSION_PREFIX, $t as UnsupportedFeishuMessage, A as DEFAULT_BACKGROUND_SESSION_SUPERVISOR_INTERVAL_MS, An as readPiModelManagementGrant, At as createFeishuCardRolloverSupervisor, B as createBackgroundSessionService$1, Bn as ModelChangeRequestConflict, Bt as isRetryableFeishuMessageError, C as DEFAULT_BACKGROUND_SESSION_LEASE_MS, Cn as openPiModelManagementDeployment, Ct as FeishuOpenApiError, D as DEFAULT_BACKGROUND_SESSION_MAX_CONSECUTIVE_FAILURES, Dn as RIVUS_MODEL_SOCKET_ENV, Dt as createFeishuTenantAccessTokenProvider, E as DEFAULT_BACKGROUND_SESSION_MAX_CONCURRENT_SESSIONS, En as RIVUS_MODEL_CONTEXT_ENV, Et as FeishuTenantAccessTokenError, F as BACKGROUND_SESSION_DELIVERY_JSONL_VERSION, Fn as createModelChangeAuthorization, Ft as activeCardPresentation, G as createFeishuPresentationPreparation, Gn as toEffectAgentHostRuntime, Gt as createFeishuMessageWorker, H as BackgroundSessionRepositoryCorrupted, Hn as ModelStateCorrupted, Ht as createFeishuCardActionCallbackResponse, I as openJsonlBackgroundSessionDeliveryStore, In as MODEL_STATE_SCHEMA_VERSION, It as isCardPresentationHandoffDue, J as openJsonlRecoveryControl, Jn as runAgentHostSyncEffect, Jt as createFeishuAgentDaemon, K as createFeishuDeploymentEndpoint, Kn as toEffectAgentRuntimeInput, Kt as shouldAcceptFeishuEndpointMessage, L as createBackgroundSessionDeliveryStore, Ln as ModelChangeAuthorizationRejected, Lt as createFeishuWebSocketDaemon, M as createBackgroundSessionSupervisor, Mn as ModelChangeBoundaryDeadlineError, Mt as DEFAULT_CARD_STREAM_LEASE_MS, N as createBackgroundSessionRepository, Nn as createModelChangeRunBoundary, Nt as CardPresentationTransitionDenied, O as DEFAULT_BACKGROUND_SESSION_RETRY_BACKOFF_MS, On as createPiModelManagementBashSpawnHook, Ot as createRateLimitedFeishuPublisher, P as openJsonlBackgroundSessionRepository, Pn as createModelChangeCoordinator, Pt as acceptsCardPresentationProgress, Q as createAgentsMdInstructionsProvider, Qn as readAutomationPresentation, Qt as InvalidFeishuMessageContent, R as BACKGROUND_SESSION_JSONL_VERSION, Rn as ModelChangeBusy, Rt as createLazyFeishuWebSocketEventDispatcher, S as resolveFeishuDeliveryChatId, Sn as createPiManagedRunGatewayProvider, St as createFeishuAgentRunCard, T as DEFAULT_BACKGROUND_SESSION_LIFETIME_MS, Tn as RIVUS_MODEL_CHANGE_TOOL_ID, Tt as createFeishuOpenApiClient, U as AgentMemoryError, Un as createBackgroundSessionHostTools, Ut as createFeishuCardActionErrorResponse, V as BackgroundSessionRepositoryConflict, Vn as ModelChangeRevisionConflict, Vt as createFeishuEventHandlers, W as createAgentMemoryService, Wn as toCompatibilityAgentRuntimeInput, Wt as createFeishuWorkerLoop, X as ToolInvocationDenied, Xn as InvalidAutomationPresentation, Xt as describeFeishuMessageIntake, Y as openJsonlToolOperationLedger, Yn as AUTOMATION_PRESENTATION_SCHEMA_VERSION, Yt as createAgentCommandFromFeishuMessage, Z as createToolBroker, Zn as createAutomationPresentation, Zt as readFeishuSessionResetDirective, _ as openJsonAutomationTickRepository, _n as openJsonlFeishuCardDeliveryLedger, _t as createConfiguredFeishuCardKitPublisher, a as createInMemoryHumanInteractionRepository, an as UnsupportedFeishuCardAction, ar as BackgroundSessionCallerDenied, at as createInMemoryCardPresentationRepository, b as createBackgroundSessionCard, bn as createFeishuStreamProjector, bt as FEISHU_AGENT_CARD_ELEMENT_ID, c as createConfiguredFeishuAutomationCardSender, cn as SessionSchedulerCapacityExceeded, cr as sessionIdFromSessionKey, ct as InvalidFeishuTopicContext, d as createHumanInteractionToolApprovalGateway, dn as openJsonFeishuSessionStore, dr as createBackgroundSession$1, dt as createConfiguredFeishuMessageReactionSender, en as readFeishuMessageContent, er as createAutomationScheduler, et as createFeishuCotPublisher, f as createHumanInteractionEndpointRegistry, fn as createFeishuSessionStore, fr as createMessageGateway, ft as createConfiguredFeishuTextReplySender, g as runDeploymentControlEffect, gn as createFeishuInboxRepository, gr as hasInspectableRunProgress, gt as createFeishuCardTargetPreparation, h as loadRivusDeploymentManifest, hn as createRecoveryControl, hr as RUN_PRESENTATION_SCHEMA_VERSION, ht as createFeishuCardKitOpenApiTargetCreator, i as createFeishuHumanInteractionPresenter, in as InvalidFeishuCardAction, ir as createHumanInteractionService, it as createJsonFileFeishuCardTargetRegistry, j as resolveBackgroundSessionSupervisorIntervalMs, jn as createModelManagementControl, jt as createFeishuCardRollover, k as DEFAULT_BACKGROUND_SESSION_STEP_TIMEOUT_MS, kn as createPiModelRunContextRegistry, kt as createCoalescingFeishuPublisher, l as createRoutedHumanInteractionToolApprovalService, ln as SessionSchedulerDisposed, lr as terminalDeliveryId, lt as createFeishuTopicContextResolver, m as toHumanInteractionSnapshot, mn as readTenantKey, mr as createPresentedValue, mt as createConfiguredFeishuCardKitTargetCreator, n as createConfiguredFeishuHumanInteractionPresenter, nn as createFeishuConversationId, nr as AutomationMandateError, nt as FeishuCardTargetRegistryStoreError, o as createJsonlHumanInteractionRepository, on as createAgentCommandFromFeishuCardAction, or as createBackgroundSessionService, ot as CardPresentationNotFound, p as toHumanInteractionAggregate, pn as openJsonlFeishuInboxRepository, pr as createRunPresentationProjector$1, pt as createConfiguredFeishuCardRolloverRuntime, q as createAgentHarnessPooledRuntime, qn as runAgentHostEffect, qt as createFeishuMessageQueue, r as createFeishuHumanInteractionCard, rn as createFeishuSessionKey, rr as createAutomationMandateStore$1, rt as createInMemoryFeishuCardTargetRegistry, s as HumanInteractionRepositoryError, sn as createJsonFetchRequest, sr as progressDeliveryId, st as createCardPresentationService, t as createHumanInteractionService$1, tn as InvalidFeishuSessionReference, tr as createDailyAutomationSchedule, tt as FeishuCardTargetNotFound, u as createHumanInteractionModelChangeApproval, un as createSessionScheduler, ur as restoreBackgroundSession, ut as composeFeishuTopicPrompt, v as createScheduledAutomation, vn as createFeishuCardDeliveryLedger, vt as createFeishuCardKitPublisher, w as DEFAULT_BACKGROUND_SESSION_LEASE_RENEWAL_INTERVAL_MS, wn as PiModelRunContextError, wt as createConfiguredFeishuOpenApiClient, x as createConfiguredFeishuBackgroundSessionDelivery, xn as DEFAULT_CONVERSATION_PROGRESS_DISPLAY, xt as FEISHU_AGENT_CARD_PROGRESS_ELEMENT_ID, y as openJsonlAgentMemoryService, yn as createFeishuCardDeliveryReconciler, yt as createFeishuCardKitOpenApiClient, z as isBackgroundSessionState, zn as ModelChangeNotFound, zt as createInterruptedRunReplayGuard } from "./chunks/service.js";
|
|
2
|
+
import { a as backgroundSessionToolIds, c as isBackgroundSessionToolId, d as createBackgroundSessionKey, f as createBackgroundSessionStepSourceMessageId, i as BACKGROUND_SESSION_TOOL_VERSION, l as narrowBackgroundSessionDefinition$1, n as BACKGROUND_SESSION_TOOL_IDS, o as createBackgroundSessionToolContracts, r as BACKGROUND_SESSION_TOOL_PLUGIN_ID, s as extendBackgroundSessionDefinition$1, t as BACKGROUND_SESSION_START_TOOL_ID, u as BACKGROUND_SESSION_SESSION_KEY_PREFIX } from "./chunks/background-session-authority.js";
|
|
3
|
+
import { A as InvalidRivusPlugin, C as createRivusHostToolDescriptorProvider, D as validateRivusCatalogIdentifier, E as createRivusPluginCatalog$1, F as InvalidAgentHostBinding, I as createEffectAgentHost, L as AgentInstanceConflict, M as AgentInstanceBusy, N as AgentRuntimeDisposed, O as validateRivusCatalogRegistration, P as createAgentHostRuntimePool, R as createEffectAgentInstanceRegistry, S as initializeRivusProject, T as createRivusToolGrantSetOperations, _ as formatRivusEnvFile, a as resolveRivusProjectSpace, b as loadNodeRivusPluginModule$1, c as RivusDeploymentReadinessError, d as RivusPluginLoadError, f as resolveRivusDeployment, g as createRivusEnvFromOpenClawConfig, h as OpenClawEnvImportError, i as createRivusDeploymentCliProcess, j as RIVUS_PLUGIN_API_VERSION, k as validateRivusPluginManifest, l as createRivusDeploymentControl, m as createRivusDaemonShutdownController, n as runRivusCli, o as RivusDeploymentAutomationReadinessError, p as createProcessDeploymentControlPorts, r as runRivusDaemonCli, s as RivusDeploymentBackgroundSessionReadinessError, t as runRivusNodeEntrypoint, u as RivusDeploymentDaemonLifecycleError, v as diagnoseRivusProject, w as createRivusAgentCatalog$1, x as resolveRivusPluginModule, y as createNodeRivusPluginModuleLoader$1 } from "./chunks/rivus-node-entrypoint.js";
|
|
4
|
+
import { D as deepFreeze, E as runDeploymentProcessEffect, a as InvalidRivusProjectSpace, c as RIVUS_RELEASE_DESCRIPTOR, i as resolveFeishuEndpointCredentials, k as toEffectAgentRuntimeInput$1, m as loadRivusDaemonConfig, o as validateRivusDeploymentManifest, p as RivusDaemonConfigError, r as FeishuEndpointCredentialError, t as RivusDeploymentManifestError } from "./chunks/node-rivus-deployment-manifest.js";
|
|
5
|
+
import { Cause, Effect, Exit, Option } from "effect";
|
|
6
|
+
import { InvalidInvocationAuthority, createInvocationAuthority, createLegacyAgentHarness, resolveInvocationAuthority, restoreAgentHistory } from "@rivus/runtime";
|
|
7
|
+
import { createRandomId, createSha256Digest, createStableId } from "@rivus/platform/identity";
|
|
8
|
+
import { dirname } from "node:path";
|
|
9
|
+
import { createServer } from "node:http";
|
|
10
|
+
//#region src/core/application/automation/outcome/commit-automation-outcome.ts
|
|
11
|
+
function commitAutomationOutcome(command) {
|
|
12
|
+
return command.repository.commit({
|
|
13
|
+
outcome: command.outcome,
|
|
14
|
+
stateUpdate: command.stateUpdate,
|
|
15
|
+
tickId: command.tickId
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region src/adapters/compatibility/agent-host/agent-instance-registry.ts
|
|
20
|
+
function createAgentInstanceRegistry(options = {}) {
|
|
21
|
+
const registry = createEffectAgentInstanceRegistry({
|
|
22
|
+
createInstanceId: (input) => createStableId("instance", input),
|
|
23
|
+
createRuntimeGenerationId: (input) => createStableId("generation", input)
|
|
24
|
+
}, options);
|
|
25
|
+
return {
|
|
26
|
+
resolveAutomation: (automationId, definition) => runAgentHostSyncEffect(registry.resolveAutomation(automationId, definition)),
|
|
27
|
+
resolveBackgroundSession: (agentId, definition) => runAgentHostSyncEffect(registry.resolveBackgroundSession(agentId, definition)),
|
|
28
|
+
resolveEndpoint: (endpointId, definition) => runAgentHostSyncEffect(registry.resolveEndpoint(endpointId, definition)),
|
|
29
|
+
snapshot: () => runAgentHostSyncEffect(registry.snapshot())
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/adapters/compatibility/agent-host/agent-runtime-pool.ts
|
|
34
|
+
function createAgentRuntimePool(options) {
|
|
35
|
+
const pool = createAgentHostRuntimePool({ create: (instance) => Effect.tryPromise({
|
|
36
|
+
try: async () => toEffectAgentHostRuntime(await options.createRuntime(instance)),
|
|
37
|
+
catch: (error) => error
|
|
38
|
+
}) }, options.disposeTimeoutMs);
|
|
39
|
+
return {
|
|
40
|
+
registry: options.registry,
|
|
41
|
+
cancel: (instance, input) => runAgentHostEffect(pool.cancel(instance, input)),
|
|
42
|
+
disposeAll: () => runAgentHostEffect(pool.disposeAll().pipe(Effect.mapError(toCompatibilityDisposalError))),
|
|
43
|
+
run: (instance, input) => runAgentHostEffect(pool.run(instance, toEffectAgentRuntimeInput(input))),
|
|
44
|
+
steer: (instance, input) => runAgentHostEffect(pool.steer(instance, input))
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function toCompatibilityDisposalError(error) {
|
|
48
|
+
if (error instanceof AggregateError && error.errors.length === 1) return error.errors[0];
|
|
49
|
+
if (error instanceof AgentRuntimeDisposed) return new Error(error.message.replace(/^agent runtime /, "Agent runtime "));
|
|
50
|
+
return error;
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
//#region src/adapters/compatibility/agent-host/rivus-agent-host.ts
|
|
54
|
+
var InvalidRivusEndpointBinding = class extends Error {
|
|
55
|
+
name = "InvalidRivusEndpointBinding";
|
|
56
|
+
};
|
|
57
|
+
function createRivusAgentHost(options) {
|
|
58
|
+
const host = runAgentHostSyncEffect(createEffectAgentHost({
|
|
59
|
+
...options.automations ? { automations: options.automations } : {},
|
|
60
|
+
...options.backgroundSessions ? { backgroundSessions: options.backgroundSessions } : {},
|
|
61
|
+
definitions: options.definitions,
|
|
62
|
+
endpoints: options.endpoints,
|
|
63
|
+
registry: toEffectRegistry(options.runtimePool),
|
|
64
|
+
runtime: toEffectRuntimePort(options.runtimePool)
|
|
65
|
+
}).pipe(Effect.mapError(mapHostError)));
|
|
66
|
+
return {
|
|
67
|
+
cancelBackgroundSession: (agentId, input) => runHostEffect(host.cancelBackgroundSession(agentId, input)),
|
|
68
|
+
cancelEndpoint: (endpointId, input) => runHostEffect(host.cancelEndpoint(endpointId, input)),
|
|
69
|
+
handleAutomation: (automationId, input) => runHostEffect(host.handleAutomation(automationId, toEffectAgentRuntimeInput(input))),
|
|
70
|
+
handleBackgroundSession: (agentId, input) => runHostEffect(host.handleBackgroundSession(agentId, toEffectAgentRuntimeInput(input))),
|
|
71
|
+
handleEndpoint: (endpointId, input) => runHostEffect(host.handleEndpoint(endpointId, toEffectAgentRuntimeInput(input))),
|
|
72
|
+
resolveAutomation: (automationId) => runHostSync(host.resolveAutomation(automationId)),
|
|
73
|
+
resolveBackgroundSession: (agentId) => runHostSync(host.resolveBackgroundSession(agentId)),
|
|
74
|
+
resolveEndpoint: (endpointId) => runHostSync(host.resolveEndpoint(endpointId)),
|
|
75
|
+
steerEndpoint: (endpointId, input) => runHostEffect(host.steerEndpoint(endpointId, input))
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
function toEffectRegistry(pool) {
|
|
79
|
+
const registry = pool.registry;
|
|
80
|
+
const sync = (read) => Effect.try({
|
|
81
|
+
try: read,
|
|
82
|
+
catch: (error) => error instanceof AgentInstanceConflict ? error : new AgentInstanceConflict(String(error))
|
|
83
|
+
});
|
|
84
|
+
return {
|
|
85
|
+
resolveAutomation: (automationId, definition) => sync(() => registry.resolveAutomation(automationId, definition)),
|
|
86
|
+
resolveBackgroundSession: (agentId, definition) => sync(() => registry.resolveBackgroundSession(agentId, definition)),
|
|
87
|
+
resolveEndpoint: (endpointId, definition) => sync(() => registry.resolveEndpoint(endpointId, definition)),
|
|
88
|
+
snapshot: () => Effect.sync(() => registry.snapshot())
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
function toEffectRuntimePort(pool) {
|
|
92
|
+
return {
|
|
93
|
+
cancel: (instance, input) => Effect.tryPromise({
|
|
94
|
+
try: () => pool.cancel(instance, input),
|
|
95
|
+
catch: (error) => error
|
|
96
|
+
}),
|
|
97
|
+
disposeAll: () => Effect.tryPromise({
|
|
98
|
+
try: () => pool.disposeAll(),
|
|
99
|
+
catch: (error) => error
|
|
100
|
+
}),
|
|
101
|
+
run: (instance, input) => Effect.tryPromise({
|
|
102
|
+
try: () => pool.run(instance, toCompatibilityAgentRuntimeInput(input)),
|
|
103
|
+
catch: (error) => error
|
|
104
|
+
}),
|
|
105
|
+
steer: (instance, input) => Effect.tryPromise({
|
|
106
|
+
try: () => pool.steer(instance, input),
|
|
107
|
+
catch: (error) => error
|
|
108
|
+
})
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
function runHostEffect(effect) {
|
|
112
|
+
return runAgentHostEffect(effect.pipe(Effect.mapError(mapHostError)));
|
|
113
|
+
}
|
|
114
|
+
function runHostSync(effect) {
|
|
115
|
+
return runAgentHostSyncEffect(effect.pipe(Effect.mapError(mapHostError)));
|
|
116
|
+
}
|
|
117
|
+
function mapHostError(error) {
|
|
118
|
+
return error instanceof InvalidAgentHostBinding ? new InvalidRivusEndpointBinding(error.message) : error;
|
|
119
|
+
}
|
|
120
|
+
//#endregion
|
|
121
|
+
//#region src/adapters/compatibility/agent-catalog/rivus-agent-catalog.ts
|
|
122
|
+
const runtime = Object.freeze({
|
|
123
|
+
digest: createSha256Digest,
|
|
124
|
+
deepFreeze
|
|
125
|
+
});
|
|
126
|
+
function createRivusPluginCatalog() {
|
|
127
|
+
return createRivusPluginCatalog$1(runtime);
|
|
128
|
+
}
|
|
129
|
+
function createRivusAgentCatalog(options = {}) {
|
|
130
|
+
return createRivusAgentCatalog$1(options.toolDescriptorProviders ?? [], runtime);
|
|
131
|
+
}
|
|
132
|
+
function createCompatibleRivusAgentCatalog(options = {}) {
|
|
133
|
+
return createRivusAgentCatalog$1([createRivusHostToolDescriptorProvider({ backgroundSessions: options.backgroundSessions === true })], runtime);
|
|
134
|
+
}
|
|
135
|
+
function resolveRivusAgentDefinition(catalog, deployment, options = {}) {
|
|
136
|
+
return createCompatibleRivusAgentCatalog(options).resolve(catalog, deployment);
|
|
137
|
+
}
|
|
138
|
+
//#endregion
|
|
139
|
+
//#region src/platform/daemon/process/rivus-daemon-process.ts
|
|
140
|
+
function createRivusDaemonProcess(options) {
|
|
141
|
+
let running = false;
|
|
142
|
+
let stopped = false;
|
|
143
|
+
return {
|
|
144
|
+
running: () => running,
|
|
145
|
+
start: () => Effect.tryPromise({
|
|
146
|
+
try: async () => {
|
|
147
|
+
if (running) return;
|
|
148
|
+
stopped = false;
|
|
149
|
+
await options.transport.start();
|
|
150
|
+
try {
|
|
151
|
+
options.workerLoop.start();
|
|
152
|
+
running = true;
|
|
153
|
+
} catch (error) {
|
|
154
|
+
await options.transport.stop();
|
|
155
|
+
running = false;
|
|
156
|
+
throw error;
|
|
157
|
+
}
|
|
158
|
+
},
|
|
159
|
+
catch: (error) => error
|
|
160
|
+
}),
|
|
161
|
+
stop: () => Effect.tryPromise({
|
|
162
|
+
try: async () => {
|
|
163
|
+
if (!running && stopped) return;
|
|
164
|
+
if (running) await Promise.resolve(options.workerLoop.stop());
|
|
165
|
+
await options.transport.stop();
|
|
166
|
+
running = false;
|
|
167
|
+
stopped = true;
|
|
168
|
+
},
|
|
169
|
+
catch: (error) => error
|
|
170
|
+
})
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
//#endregion
|
|
174
|
+
//#region src/platform/daemon/transport/rivus-daemon-transport.ts
|
|
175
|
+
function createCompositeRivusDaemonTransport(options) {
|
|
176
|
+
const transports = [...options.transports];
|
|
177
|
+
let running = false;
|
|
178
|
+
let stopped = false;
|
|
179
|
+
return {
|
|
180
|
+
running: () => running,
|
|
181
|
+
start: async () => {
|
|
182
|
+
if (running) return;
|
|
183
|
+
stopped = false;
|
|
184
|
+
const started = [];
|
|
185
|
+
try {
|
|
186
|
+
for (const transport of transports) {
|
|
187
|
+
await transport.start();
|
|
188
|
+
started.push(transport);
|
|
189
|
+
}
|
|
190
|
+
running = true;
|
|
191
|
+
} catch (error) {
|
|
192
|
+
for (const transport of started.reverse()) await transport.stop();
|
|
193
|
+
running = false;
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
},
|
|
197
|
+
stop: async () => {
|
|
198
|
+
if (!running && stopped) return;
|
|
199
|
+
for (const transport of [...transports].reverse()) await transport.stop();
|
|
200
|
+
running = false;
|
|
201
|
+
stopped = true;
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
//#endregion
|
|
206
|
+
//#region src/platform/daemon/status/daemon-status-reporter.ts
|
|
207
|
+
function createDaemonStatusReporter(options) {
|
|
208
|
+
return { status: () => options.restoreHistory().pipe(Effect.map((history) => {
|
|
209
|
+
const availability = options.availability?.();
|
|
210
|
+
const activeRun = availability?.busy ? availability.activeRun : options.activeRun?.();
|
|
211
|
+
const activeRunId = availability?.busy ? availability.activeRunId : activeRun?.runId ?? options.activeRunId?.();
|
|
212
|
+
const activeRunState = availability?.busy ? availability.activeState : options.activeRunState?.();
|
|
213
|
+
const activeSessionKey = availability?.busy ? availability.activeSessionKey : activeRun?.sessionKey;
|
|
214
|
+
return {
|
|
215
|
+
agentId: options.agentId,
|
|
216
|
+
...options.cardPresentations ? { cards: options.cardPresentations() } : {},
|
|
217
|
+
harness: {
|
|
218
|
+
...activeRunId !== void 0 ? { activeRunId } : {},
|
|
219
|
+
...activeRunState !== void 0 ? { activeRunState } : {},
|
|
220
|
+
...activeSessionKey !== void 0 ? { activeSessionKey } : {},
|
|
221
|
+
busy: activeRunId !== void 0
|
|
222
|
+
},
|
|
223
|
+
history,
|
|
224
|
+
process: { running: options.processRunning() },
|
|
225
|
+
queue: { pending: options.pending() },
|
|
226
|
+
...options.receiveStatus ? { receive: options.receiveStatus() } : {},
|
|
227
|
+
transport: { running: options.transportRunning() },
|
|
228
|
+
workerLoop: { running: options.workerLoopRunning() }
|
|
229
|
+
};
|
|
230
|
+
})) };
|
|
231
|
+
}
|
|
232
|
+
//#endregion
|
|
233
|
+
//#region src/adapters/compatibility/daemon/rivus-daemon-status.ts
|
|
234
|
+
function createRivusDaemonStatusReporter(options) {
|
|
235
|
+
return createDaemonStatusReporter(options);
|
|
236
|
+
}
|
|
237
|
+
//#endregion
|
|
238
|
+
//#region src/adapters/http/daemon/rivus-daemon-status-http-server.ts
|
|
239
|
+
function createDaemonStatusHttpServer(options) {
|
|
240
|
+
const host = options.host ?? "127.0.0.1";
|
|
241
|
+
const path = options.path ?? "/status";
|
|
242
|
+
let server;
|
|
243
|
+
let running = false;
|
|
244
|
+
return {
|
|
245
|
+
running: () => running,
|
|
246
|
+
start: async () => {
|
|
247
|
+
if (running) return;
|
|
248
|
+
server = createServer((request, response) => {
|
|
249
|
+
handleRequest(request, response, path, options.statusReporter);
|
|
250
|
+
});
|
|
251
|
+
await listen(server, host, options.port);
|
|
252
|
+
running = true;
|
|
253
|
+
},
|
|
254
|
+
stop: async () => {
|
|
255
|
+
if (!running || !server) return;
|
|
256
|
+
await close(server);
|
|
257
|
+
running = false;
|
|
258
|
+
server = void 0;
|
|
259
|
+
},
|
|
260
|
+
url: () => {
|
|
261
|
+
const address = server?.address();
|
|
262
|
+
if (!running || !address || typeof address === "string") return;
|
|
263
|
+
return `http://${host}:${address.port}`;
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
async function handleRequest(request, response, path, statusReporter) {
|
|
268
|
+
if (request.method !== "GET" || requestPath(request) !== path) {
|
|
269
|
+
writeJson(response, 404, { error: "not_found" });
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
try {
|
|
273
|
+
writeJson(response, 200, await Effect.runPromise(statusReporter.status()));
|
|
274
|
+
} catch (error) {
|
|
275
|
+
writeJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
function requestPath(request) {
|
|
279
|
+
return new URL(request.url ?? "/", "http://localhost").pathname;
|
|
280
|
+
}
|
|
281
|
+
function writeJson(response, statusCode, body) {
|
|
282
|
+
response.writeHead(statusCode, {
|
|
283
|
+
"cache-control": "no-store",
|
|
284
|
+
"content-type": "application/json; charset=utf-8"
|
|
285
|
+
});
|
|
286
|
+
response.end(`${JSON.stringify(body)}\n`);
|
|
287
|
+
}
|
|
288
|
+
function listen(server, host, port) {
|
|
289
|
+
return new Promise((resolve, reject) => {
|
|
290
|
+
const onError = (error) => {
|
|
291
|
+
server.off("listening", onListening);
|
|
292
|
+
reject(error);
|
|
293
|
+
};
|
|
294
|
+
const onListening = () => {
|
|
295
|
+
server.off("error", onError);
|
|
296
|
+
resolve();
|
|
297
|
+
};
|
|
298
|
+
server.once("error", onError);
|
|
299
|
+
server.once("listening", onListening);
|
|
300
|
+
server.listen(port, host);
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
function close(server) {
|
|
304
|
+
return new Promise((resolve, reject) => {
|
|
305
|
+
server.close((error) => {
|
|
306
|
+
if (error) {
|
|
307
|
+
reject(error);
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
resolve();
|
|
311
|
+
});
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
//#endregion
|
|
315
|
+
//#region src/adapters/compatibility/daemon/rivus-daemon-status-http-server.ts
|
|
316
|
+
function createRivusDaemonStatusHttpServer(options) {
|
|
317
|
+
return createDaemonStatusHttpServer(options);
|
|
318
|
+
}
|
|
319
|
+
//#endregion
|
|
320
|
+
//#region src/adapters/feishu/runtime/feishu-receive-runtime.ts
|
|
321
|
+
function createFeishuReceiveRuntime(options) {
|
|
322
|
+
let lastAccepted;
|
|
323
|
+
let lastHandled;
|
|
324
|
+
const handleMessage = (payload, handleOptions) => {
|
|
325
|
+
const effect = options.daemon.handleMessage(payload, handleOptions).pipe(Effect.tap((result) => describeHandledFeishuMessage(payload, result, options.harness, options.observation.agentId, options.observation.botOpenId, options.sessionStore).pipe(Effect.tap((intake) => Effect.gen(function* () {
|
|
326
|
+
const observedAt = yield* options.observation.clock.now;
|
|
327
|
+
lastHandled = {
|
|
328
|
+
intake,
|
|
329
|
+
messageId: payload.event.message.message_id,
|
|
330
|
+
observedAt,
|
|
331
|
+
result
|
|
332
|
+
};
|
|
333
|
+
})))));
|
|
334
|
+
return options.observation.periodicFlush ? options.observation.periodicFlush.withPeriodicFlush(effect) : effect;
|
|
335
|
+
};
|
|
336
|
+
const accept = (delivery, payload, acceptOptions) => delivery.accept(payload, acceptOptions).pipe(Effect.tap((accepted) => Effect.gen(function* () {
|
|
337
|
+
const observedAt = yield* options.observation.clock.now;
|
|
338
|
+
lastAccepted = {
|
|
339
|
+
accepted,
|
|
340
|
+
message: summarizeReceiveMessage(payload),
|
|
341
|
+
observedAt
|
|
342
|
+
};
|
|
343
|
+
})));
|
|
344
|
+
const createEventHandlers = (delivery) => createFeishuEventHandlers({
|
|
345
|
+
cardActions: options.daemon,
|
|
346
|
+
queue: {
|
|
347
|
+
accept: (payload) => accept(delivery, payload),
|
|
348
|
+
pending: () => delivery.pending()
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
const replayReceiveMessage = (delivery, payload, replayOptions) => Effect.gen(function* () {
|
|
352
|
+
const intakeOptions = {
|
|
353
|
+
agentId: options.observation.agentId,
|
|
354
|
+
...options.observation.botOpenId ? { botOpenId: options.observation.botOpenId } : {},
|
|
355
|
+
sessionStore: options.sessionStore
|
|
356
|
+
};
|
|
357
|
+
const reset = yield* readFeishuSessionResetDirective(payload, intakeOptions);
|
|
358
|
+
const initialIntake = reset ? void 0 : yield* describeFeishuMessageIntake(payload, intakeOptions);
|
|
359
|
+
const accepted = yield* accept(delivery, payload, replayOptions);
|
|
360
|
+
const drained = yield* delivery.drainAvailable();
|
|
361
|
+
const handledIntake = lastHandled?.messageId === payload.event.message.message_id ? lastHandled.intake : void 0;
|
|
362
|
+
let intake;
|
|
363
|
+
if (handledIntake) intake = handledIntake;
|
|
364
|
+
else if (reset) {
|
|
365
|
+
const sessionKey = yield* options.sessionStore.current(reset.baseSessionKey);
|
|
366
|
+
intake = reset.prompt ? {
|
|
367
|
+
commandType: "prompt",
|
|
368
|
+
messageId: payload.event.message.message_id,
|
|
369
|
+
sessionKey,
|
|
370
|
+
sessionReference: reset.sessionReference,
|
|
371
|
+
text: reset.prompt
|
|
372
|
+
} : {
|
|
373
|
+
commandType: "new_session",
|
|
374
|
+
messageId: payload.event.message.message_id,
|
|
375
|
+
previousSessionKey: reset.previousSessionKey,
|
|
376
|
+
sessionKey,
|
|
377
|
+
sessionReference: reset.sessionReference
|
|
378
|
+
};
|
|
379
|
+
} else intake = initialIntake;
|
|
380
|
+
return {
|
|
381
|
+
accepted,
|
|
382
|
+
drained,
|
|
383
|
+
intake
|
|
384
|
+
};
|
|
385
|
+
});
|
|
386
|
+
return {
|
|
387
|
+
accept,
|
|
388
|
+
createEventHandlers,
|
|
389
|
+
handleMessage,
|
|
390
|
+
receiveStatus: () => ({
|
|
391
|
+
...lastAccepted ? { lastAccepted } : {},
|
|
392
|
+
...lastHandled ? { lastHandled } : {}
|
|
393
|
+
}),
|
|
394
|
+
replayReceiveMessage
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
function describeHandledFeishuMessage(payload, result, harness, agentId, botOpenId, sessionStore) {
|
|
398
|
+
const sessionReference = {
|
|
399
|
+
agentId,
|
|
400
|
+
chatId: payload.event.message.chat_id,
|
|
401
|
+
tenantKey: readTenantKey(payload),
|
|
402
|
+
...payload.event.message.thread_id ? { threadId: payload.event.message.thread_id } : {}
|
|
403
|
+
};
|
|
404
|
+
if ("finalText" in result) {
|
|
405
|
+
const state = harness.getRunState(result.runId);
|
|
406
|
+
if (state?.sessionKey && state.prompt !== void 0) return Effect.succeed({
|
|
407
|
+
commandType: "prompt",
|
|
408
|
+
messageId: result.messageId,
|
|
409
|
+
sessionKey: state.sessionKey,
|
|
410
|
+
sessionReference,
|
|
411
|
+
text: state.prompt
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
if ("reset" in result) return Effect.succeed({
|
|
415
|
+
commandType: "new_session",
|
|
416
|
+
messageId: result.messageId,
|
|
417
|
+
previousSessionKey: result.previousSessionKey,
|
|
418
|
+
sessionKey: result.sessionKey,
|
|
419
|
+
sessionReference
|
|
420
|
+
});
|
|
421
|
+
return describeFeishuMessageIntake(payload, {
|
|
422
|
+
agentId,
|
|
423
|
+
...botOpenId ? { botOpenId } : {},
|
|
424
|
+
sessionStore
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
function summarizeReceiveMessage(payload) {
|
|
428
|
+
const tenantKey = readTenantKey(payload);
|
|
429
|
+
return {
|
|
430
|
+
chatId: payload.event.message.chat_id,
|
|
431
|
+
messageId: payload.event.message.message_id,
|
|
432
|
+
...tenantKey ? { tenantKey } : {},
|
|
433
|
+
...payload.event.message.thread_id ? { threadId: payload.event.message.thread_id } : {}
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
//#endregion
|
|
437
|
+
//#region src/bootstrap/feishu/agent-runtime.ts
|
|
438
|
+
function createFeishuAgentRuntime(options) {
|
|
439
|
+
const sessionStore = options.sessionStore ?? createFeishuSessionStore();
|
|
440
|
+
const harness = createLegacyAgentHarness({
|
|
441
|
+
clock: options.clock,
|
|
442
|
+
...options.eventSinks ? { eventSinks: options.eventSinks } : {},
|
|
443
|
+
...options.initialEvents ? { initialEvents: options.initialEvents } : {},
|
|
444
|
+
...options.initialRunStates ? { initialRunStates: options.initialRunStates } : {},
|
|
445
|
+
loop: options.loop,
|
|
446
|
+
...options.runTimeoutMs === void 0 ? {} : { runTimeoutMs: options.runTimeoutMs },
|
|
447
|
+
runIds: options.runIds
|
|
448
|
+
});
|
|
449
|
+
const daemon = createFeishuAgentDaemon({
|
|
450
|
+
...options.acknowledgeSteering ? { acknowledgeSteering: options.acknowledgeSteering } : {},
|
|
451
|
+
agentId: options.agentId,
|
|
452
|
+
...options.botOpenId ? { botOpenId: options.botOpenId } : {},
|
|
453
|
+
dedupe: true,
|
|
454
|
+
...options.finalizeRun ? { finalizeRun: options.finalizeRun } : {},
|
|
455
|
+
harness,
|
|
456
|
+
...options.prepareRun ? { prepareRun: options.prepareRun } : {},
|
|
457
|
+
...options.promptContext ? { promptContext: options.promptContext } : {},
|
|
458
|
+
publish: options.publish,
|
|
459
|
+
...options.reply ? { reply: options.reply } : {},
|
|
460
|
+
sessionStore
|
|
461
|
+
});
|
|
462
|
+
const receive = createFeishuReceiveRuntime({
|
|
463
|
+
observation: options,
|
|
464
|
+
daemon,
|
|
465
|
+
harness,
|
|
466
|
+
sessionStore
|
|
467
|
+
});
|
|
468
|
+
const queue = createFeishuMessageQueue({
|
|
469
|
+
handleMessage: (payload, handleOptions) => receive.handleMessage(payload, handleOptions),
|
|
470
|
+
prepareControl: (payload) => daemon.prepareControlMessage(payload),
|
|
471
|
+
...options.inboxRepository ? { repository: options.inboxRepository } : {},
|
|
472
|
+
...options.initialEvents ? { shouldSkipReplay: createInterruptedRunReplayGuard(options.initialEvents, {
|
|
473
|
+
agentId: options.agentId,
|
|
474
|
+
...options.botOpenId ? { botOpenId: options.botOpenId } : {},
|
|
475
|
+
sessionStore
|
|
476
|
+
}) } : {},
|
|
477
|
+
shouldRetryError: isRetryableFeishuMessageError
|
|
478
|
+
});
|
|
479
|
+
const worker = createFeishuMessageWorker({ queue });
|
|
480
|
+
const delivery = {
|
|
481
|
+
accept: (payload, handleOptions) => queue.accept(payload, handleOptions),
|
|
482
|
+
drainAvailable: () => worker.drainAvailable(),
|
|
483
|
+
pending: () => queue.pending()
|
|
484
|
+
};
|
|
485
|
+
return {
|
|
486
|
+
drainAvailable: () => worker.drainAvailable(),
|
|
487
|
+
drainOne: () => queue.drainOne(),
|
|
488
|
+
handlers: receive.createEventHandlers(delivery),
|
|
489
|
+
harness,
|
|
490
|
+
pending: () => queue.pending(),
|
|
491
|
+
queue,
|
|
492
|
+
receiveStatus: () => receive.receiveStatus(),
|
|
493
|
+
replayReceiveMessage: (payload, replayOptions) => receive.replayReceiveMessage(delivery, payload, replayOptions),
|
|
494
|
+
worker
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
//#endregion
|
|
498
|
+
//#region src/bootstrap/feishu/rivus-daemon-bootstrap.ts
|
|
499
|
+
const DEFAULT_WORKER_INTERVAL_MS = 250;
|
|
500
|
+
function restoreConfiguredRivusDaemonBootstrap(options) {
|
|
501
|
+
return options.eventLog.readAll().pipe(Effect.map((events) => createConfiguredRivusDaemonBootstrap({
|
|
502
|
+
...options,
|
|
503
|
+
initialEvents: [...options.initialEvents ?? [], ...events]
|
|
504
|
+
})));
|
|
505
|
+
}
|
|
506
|
+
function createConfiguredRivusDaemonBootstrap(options) {
|
|
507
|
+
const openApiClient = createConfiguredFeishuOpenApiClient({
|
|
508
|
+
config: options.config,
|
|
509
|
+
request: options.request
|
|
510
|
+
});
|
|
511
|
+
const cardRollover = createConfiguredFeishuCardRolloverRuntime({
|
|
512
|
+
cardTargets: options.cardTargets,
|
|
513
|
+
client: openApiClient,
|
|
514
|
+
clock: options.clock,
|
|
515
|
+
config: options.config,
|
|
516
|
+
...options.cardLedger ? { ledger: options.cardLedger } : {},
|
|
517
|
+
...options.flushIntervalMs === void 0 ? {} : { flushIntervalMs: options.flushIntervalMs },
|
|
518
|
+
...options.observeCardRollover ? { observe: options.observeCardRollover } : {},
|
|
519
|
+
...options.onWorkerError ? { onError: options.onWorkerError } : {},
|
|
520
|
+
sleep: options.sleep,
|
|
521
|
+
...options.cardRolloverIntervalMs === void 0 ? {} : { supervisorIntervalMs: options.cardRolloverIntervalMs }
|
|
522
|
+
});
|
|
523
|
+
const publisher = cardRollover.rollover;
|
|
524
|
+
const replies = createConfiguredFeishuTextReplySender({
|
|
525
|
+
client: openApiClient,
|
|
526
|
+
config: options.config
|
|
527
|
+
});
|
|
528
|
+
const reactions = createConfiguredFeishuMessageReactionSender({
|
|
529
|
+
client: openApiClient,
|
|
530
|
+
config: options.config
|
|
531
|
+
});
|
|
532
|
+
const promptContext = createFeishuTopicContextResolver({
|
|
533
|
+
baseUrl: options.config.feishu.baseUrl,
|
|
534
|
+
client: openApiClient
|
|
535
|
+
});
|
|
536
|
+
const prepareRun = (run) => cardRollover.prepareRun(run);
|
|
537
|
+
const runtime = createFeishuAgentRuntime({
|
|
538
|
+
acknowledgeSteering: (messageId) => reactions.add(messageId),
|
|
539
|
+
agentId: options.config.agentId,
|
|
540
|
+
...options.botOpenId ? { botOpenId: options.botOpenId } : {},
|
|
541
|
+
clock: options.clock,
|
|
542
|
+
eventSinks: [options.eventLog],
|
|
543
|
+
finalizeRun: (runId) => cardRollover.rollover.releaseRun(runId),
|
|
544
|
+
...options.inboxRepository ? { inboxRepository: options.inboxRepository } : {},
|
|
545
|
+
...options.initialEvents ? { initialEvents: options.initialEvents } : {},
|
|
546
|
+
...options.initialRunStates ? { initialRunStates: options.initialRunStates } : {},
|
|
547
|
+
loop: options.loop,
|
|
548
|
+
prepareRun,
|
|
549
|
+
promptContext,
|
|
550
|
+
publish: (action) => publisher.publish(action),
|
|
551
|
+
reply: (messageId, text) => replies.reply(messageId, text),
|
|
552
|
+
...options.runTimeoutMs === void 0 ? {} : { runTimeoutMs: options.runTimeoutMs },
|
|
553
|
+
runIds: options.runIds
|
|
554
|
+
});
|
|
555
|
+
const websocketTransport = createFeishuWebSocketDaemon({
|
|
556
|
+
client: options.websocketClient,
|
|
557
|
+
eventDispatcher: options.eventDispatcher,
|
|
558
|
+
runtime
|
|
559
|
+
});
|
|
560
|
+
const workerLoop = createFeishuWorkerLoop({
|
|
561
|
+
drainAvailable: () => runtime.drainAvailable(),
|
|
562
|
+
intervalMs: options.workerIntervalMs ?? DEFAULT_WORKER_INTERVAL_MS,
|
|
563
|
+
...options.onWorkerError ? { onError: options.onWorkerError } : {},
|
|
564
|
+
sleep: options.sleep
|
|
565
|
+
});
|
|
566
|
+
const restoreHistoryFromLog = () => restoreAgentHistory(options.eventLog);
|
|
567
|
+
let processRef;
|
|
568
|
+
let transport = createCompositeRivusDaemonTransport({ transports: [websocketTransport, cardRollover.transport] });
|
|
569
|
+
const statusReporter = createDaemonStatusReporter({
|
|
570
|
+
agentId: options.config.agentId,
|
|
571
|
+
availability: () => runtime.harness.getAvailability(),
|
|
572
|
+
pending: () => runtime.pending(),
|
|
573
|
+
processRunning: () => processRef?.running() ?? false,
|
|
574
|
+
cardPresentations: () => cardRollover.rollover.status(),
|
|
575
|
+
receiveStatus: () => runtime.receiveStatus(),
|
|
576
|
+
restoreHistory: restoreHistoryFromLog,
|
|
577
|
+
transportRunning: () => transport.running(),
|
|
578
|
+
workerLoopRunning: () => workerLoop.running()
|
|
579
|
+
});
|
|
580
|
+
const statusTransport = options.createStatusTransport?.(statusReporter);
|
|
581
|
+
if (statusTransport) transport = createCompositeRivusDaemonTransport({ transports: [
|
|
582
|
+
websocketTransport,
|
|
583
|
+
cardRollover.transport,
|
|
584
|
+
statusTransport
|
|
585
|
+
] });
|
|
586
|
+
const process = createRivusDaemonProcess({
|
|
587
|
+
transport,
|
|
588
|
+
workerLoop
|
|
589
|
+
});
|
|
590
|
+
processRef = process;
|
|
591
|
+
return {
|
|
592
|
+
cardRollover,
|
|
593
|
+
cardTargets: options.cardTargets,
|
|
594
|
+
eventLog: options.eventLog,
|
|
595
|
+
process,
|
|
596
|
+
promptText: (command) => runtime.harness.promptText(command),
|
|
597
|
+
publisher,
|
|
598
|
+
restoreHistory: restoreHistoryFromLog,
|
|
599
|
+
runtime,
|
|
600
|
+
status: () => statusReporter.status(),
|
|
601
|
+
statusReporter,
|
|
602
|
+
transport,
|
|
603
|
+
websocketTransport,
|
|
604
|
+
workerLoop
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
//#endregion
|
|
608
|
+
//#region src/adapters/compatibility/run-presentation/run-presentation-projector.ts
|
|
609
|
+
function createRunPresentationProjector() {
|
|
610
|
+
const projector = createRunPresentationProjector$1();
|
|
611
|
+
return {
|
|
612
|
+
apply: (event, canonicalText) => projector.apply(event, canonicalText),
|
|
613
|
+
snapshot: (runId) => projector.snapshot(runId)
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
//#endregion
|
|
617
|
+
//#region src/adapters/compatibility/card-presentation/feishu-card-presentation-store.ts
|
|
618
|
+
var FeishuCardPresentationNotFound = class {
|
|
619
|
+
runId;
|
|
620
|
+
_tag = "FeishuCardPresentationNotFound";
|
|
621
|
+
constructor(runId) {
|
|
622
|
+
this.runId = runId;
|
|
623
|
+
}
|
|
624
|
+
};
|
|
625
|
+
function createFeishuCardPresentationStore(options = {}) {
|
|
626
|
+
const persist = options.persist;
|
|
627
|
+
return translateService(createCardPresentationService(createInMemoryCardPresentationRepository({
|
|
628
|
+
...options.initial === void 0 ? {} : { initial: options.initial },
|
|
629
|
+
...persist === void 0 ? {} : { persist: (chains) => Effect.tryPromise({
|
|
630
|
+
try: () => persist(chains),
|
|
631
|
+
catch: (error) => error
|
|
632
|
+
}) }
|
|
633
|
+
})));
|
|
634
|
+
}
|
|
635
|
+
function translateService(service) {
|
|
636
|
+
const translate = (effect) => effect.pipe(Effect.mapError((error) => error instanceof CardPresentationNotFound ? new FeishuCardPresentationNotFound(error.runId) : error));
|
|
637
|
+
return {
|
|
638
|
+
bind: (binding) => translate(service.bind(binding)),
|
|
639
|
+
beginHandoff: (input) => translate(service.beginHandoff(input)).pipe(Effect.map((result) => ({
|
|
640
|
+
presentation: result.presentation,
|
|
641
|
+
started: result.started
|
|
642
|
+
}))),
|
|
643
|
+
chain: (runId) => service.chain(runId),
|
|
644
|
+
chains: () => service.chains(),
|
|
645
|
+
compensateInterruptedHandoffs: (compensatedAt) => translate(service.compensateInterruptedHandoffs(compensatedAt)),
|
|
646
|
+
completeHandoff: (input) => translate(service.completeHandoff(input)),
|
|
647
|
+
failHandoff: (input) => translate(service.failHandoff(input)),
|
|
648
|
+
markTerminal: (input) => translate(service.markTerminal(input)),
|
|
649
|
+
release: (runId) => translate(service.release(runId)),
|
|
650
|
+
size: () => service.size()
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
//#endregion
|
|
654
|
+
//#region src/adapters/feishu/delivery/cot/feishu-periodic-flush.ts
|
|
655
|
+
function createFeishuPeriodicFlush(options) {
|
|
656
|
+
const loop = Effect.forever(Effect.gen(function* () {
|
|
657
|
+
yield* options.sleep(options.intervalMs);
|
|
658
|
+
yield* options.flush();
|
|
659
|
+
}));
|
|
660
|
+
return { withPeriodicFlush: (effect) => Effect.raceFirst(effect, loop) };
|
|
661
|
+
}
|
|
662
|
+
//#endregion
|
|
663
|
+
//#region src/core/application/background-session/ports/background-session-delivery-store.ts
|
|
664
|
+
var BackgroundSessionDeliveryConflict = class extends Error {
|
|
665
|
+
name = "BackgroundSessionDeliveryConflict";
|
|
666
|
+
constructor(deliveryId, message) {
|
|
667
|
+
super(`${deliveryId}: ${message}`);
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
//#endregion
|
|
671
|
+
//#region src/adapters/compatibility/background-session/authority.ts
|
|
672
|
+
function extendBackgroundSessionDefinition(definition) {
|
|
673
|
+
return extendBackgroundSessionDefinition$1(definition, createSha256Digest);
|
|
674
|
+
}
|
|
675
|
+
function narrowBackgroundSessionDefinition(definition) {
|
|
676
|
+
return narrowBackgroundSessionDefinition$1(definition, createSha256Digest);
|
|
677
|
+
}
|
|
678
|
+
//#endregion
|
|
679
|
+
//#region src/adapters/compatibility/background-session/transitions.ts
|
|
680
|
+
function isBackgroundSessionTerminalPhase(phase) {
|
|
681
|
+
return phase === "stopped" || phase === "completed" || phase === "failed" || phase === "reconciliation-required";
|
|
682
|
+
}
|
|
683
|
+
var BackgroundSessionTransitionDenied = class extends Error {
|
|
684
|
+
sessionId;
|
|
685
|
+
name = "BackgroundSessionTransitionDenied";
|
|
686
|
+
constructor(sessionId, message) {
|
|
687
|
+
super(message);
|
|
688
|
+
this.sessionId = sessionId;
|
|
689
|
+
}
|
|
690
|
+
};
|
|
691
|
+
function isDomainTransitionError(error) {
|
|
692
|
+
if (!(error instanceof Error) || error.name !== "BackgroundSessionTransitionDenied") return false;
|
|
693
|
+
return typeof error.sessionId === "string";
|
|
694
|
+
}
|
|
695
|
+
function mapDomainError(error) {
|
|
696
|
+
if (isDomainTransitionError(error)) throw new BackgroundSessionTransitionDenied(error.sessionId, error.message);
|
|
697
|
+
throw error;
|
|
698
|
+
}
|
|
699
|
+
function runTransition(operation) {
|
|
700
|
+
try {
|
|
701
|
+
return operation();
|
|
702
|
+
} catch (error) {
|
|
703
|
+
mapDomainError(error);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
function createBackgroundSession(input) {
|
|
707
|
+
return runTransition(() => createBackgroundSession$1(input).toSnapshot());
|
|
708
|
+
}
|
|
709
|
+
function claimBackgroundSession(state, input) {
|
|
710
|
+
return runTransition(() => restoreBackgroundSession(state).claim(input).state.toSnapshot());
|
|
711
|
+
}
|
|
712
|
+
function renewBackgroundSessionLease(state, lease) {
|
|
713
|
+
return runTransition(() => restoreBackgroundSession(state).renewLease(lease).state.toSnapshot());
|
|
714
|
+
}
|
|
715
|
+
function releaseBackgroundSessionLease(state) {
|
|
716
|
+
return runTransition(() => restoreBackgroundSession(state).releaseLease().state.toSnapshot());
|
|
717
|
+
}
|
|
718
|
+
function suspendBackgroundSession(state, input) {
|
|
719
|
+
return runTransition(() => restoreBackgroundSession(state).suspend(input).state.toSnapshot());
|
|
720
|
+
}
|
|
721
|
+
function completeBackgroundSessionStep(state, input) {
|
|
722
|
+
return runTransition(() => restoreBackgroundSession(state).completeStep(input).state.toSnapshot());
|
|
723
|
+
}
|
|
724
|
+
function failBackgroundSessionStep(state, input) {
|
|
725
|
+
return runTransition(() => restoreBackgroundSession(state).failStep(input).state.toSnapshot());
|
|
726
|
+
}
|
|
727
|
+
function requestBackgroundSessionStop(state, input) {
|
|
728
|
+
return runTransition(() => restoreBackgroundSession(state).requestStop(input).state.toSnapshot());
|
|
729
|
+
}
|
|
730
|
+
function completeBackgroundSessionStop(state, input) {
|
|
731
|
+
return runTransition(() => restoreBackgroundSession(state).completeStop(input).state.toSnapshot());
|
|
732
|
+
}
|
|
733
|
+
function parkBackgroundSessionForReconciliation(state, input) {
|
|
734
|
+
return runTransition(() => restoreBackgroundSession(state).parkForReconciliation(input).state.toSnapshot());
|
|
735
|
+
}
|
|
736
|
+
function resolveBackgroundSessionReconciliation(state, input) {
|
|
737
|
+
return runTransition(() => restoreBackgroundSession(state).resolveReconciliation(input).state.toSnapshot());
|
|
738
|
+
}
|
|
739
|
+
function appendBackgroundSessionInput(state, input) {
|
|
740
|
+
return runTransition(() => restoreBackgroundSession(state).appendInput(input).state.toSnapshot());
|
|
741
|
+
}
|
|
742
|
+
function requeueInterruptedBackgroundSessionStep(state, input) {
|
|
743
|
+
return runTransition(() => restoreBackgroundSession(state).requeueInterruptedStep(input).state.toSnapshot());
|
|
744
|
+
}
|
|
745
|
+
function isBackgroundSessionDue(state, now) {
|
|
746
|
+
return restoreBackgroundSession(state).isDue(now);
|
|
747
|
+
}
|
|
748
|
+
function isBackgroundSessionLeaseExpired(state, now) {
|
|
749
|
+
return restoreBackgroundSession(state).isLeaseExpired(now);
|
|
750
|
+
}
|
|
751
|
+
//#endregion
|
|
752
|
+
//#region src/adapters/compatibility/automation/automation-mandate-store.ts
|
|
753
|
+
function createAutomationMandateStore() {
|
|
754
|
+
return createAutomationMandateStore$1({
|
|
755
|
+
mandateId: (binding) => createStableId("mandate", binding),
|
|
756
|
+
tickId: (mandateId, occurrence) => createStableId("tick", {
|
|
757
|
+
id: mandateId,
|
|
758
|
+
occurrence
|
|
759
|
+
})
|
|
760
|
+
});
|
|
761
|
+
}
|
|
762
|
+
//#endregion
|
|
763
|
+
//#region src/adapters/compatibility/automation/outcome/outcome-transaction.ts
|
|
764
|
+
const preparePluginState = Symbol("preparePluginState");
|
|
765
|
+
const commitPluginState = Symbol("commitPluginState");
|
|
766
|
+
const prepareDeliveryJob = Symbol("prepareDeliveryJob");
|
|
767
|
+
const commitDeliveryJob = Symbol("commitDeliveryJob");
|
|
768
|
+
//#endregion
|
|
769
|
+
//#region src/adapters/compatibility/automation/outcome/plugin-state-store.ts
|
|
770
|
+
var PluginStateConflict = class extends Error {
|
|
771
|
+
name = "PluginStateConflict";
|
|
772
|
+
};
|
|
773
|
+
function createPluginStateStore() {
|
|
774
|
+
const records = /* @__PURE__ */ new Map();
|
|
775
|
+
const id = (p, a, k) => `${p}/${a}/${k}`;
|
|
776
|
+
const store = {
|
|
777
|
+
[commitPluginState]: (prepared) => {
|
|
778
|
+
records.set(prepared.key, prepared.record);
|
|
779
|
+
},
|
|
780
|
+
[preparePluginState]: (input) => {
|
|
781
|
+
const key = id(input.pluginId, input.agentId, input.key);
|
|
782
|
+
if ((records.get(key)?.revision ?? 0) !== input.expectedRevision) throw new PluginStateConflict("plugin state revision conflict");
|
|
783
|
+
return {
|
|
784
|
+
key,
|
|
785
|
+
record: Object.freeze({
|
|
786
|
+
agentId: input.agentId,
|
|
787
|
+
key: input.key,
|
|
788
|
+
pluginId: input.pluginId,
|
|
789
|
+
revision: input.expectedRevision + 1,
|
|
790
|
+
value: input.value
|
|
791
|
+
})
|
|
792
|
+
};
|
|
793
|
+
},
|
|
794
|
+
get: (pluginId, agentId, key) => records.get(id(pluginId, agentId, key)),
|
|
795
|
+
put: (input) => {
|
|
796
|
+
const prepared = store[preparePluginState](input);
|
|
797
|
+
store[commitPluginState](prepared);
|
|
798
|
+
return prepared.record;
|
|
799
|
+
}
|
|
800
|
+
};
|
|
801
|
+
return store;
|
|
802
|
+
}
|
|
803
|
+
//#endregion
|
|
804
|
+
//#region src/core/application/automation/outcome/delivery-job-transition.ts
|
|
805
|
+
var DeliveryJobTransitionDenied = class extends Error {
|
|
806
|
+
name = "DeliveryJobTransitionDenied";
|
|
807
|
+
};
|
|
808
|
+
function recordDeliveryJobAttempt(current, result, receiptId) {
|
|
809
|
+
if (current.status !== "pending") throw new DeliveryJobTransitionDenied(`Automation delivery job cannot transition while ${current.status}`);
|
|
810
|
+
if (result.kind === "uncertain") return Object.freeze({
|
|
811
|
+
...current,
|
|
812
|
+
status: "reconciliation-required"
|
|
813
|
+
});
|
|
814
|
+
if (!receiptId) throw new DeliveryJobTransitionDenied("delivered Automation job requires a receipt ID");
|
|
815
|
+
return Object.freeze({
|
|
816
|
+
...current,
|
|
817
|
+
receiptId,
|
|
818
|
+
status: "delivered"
|
|
819
|
+
});
|
|
820
|
+
}
|
|
821
|
+
//#endregion
|
|
822
|
+
//#region src/adapters/compatibility/automation/outcome/delivery-outbox.ts
|
|
823
|
+
var DeliveryOutboxError = class extends Error {
|
|
824
|
+
name = "DeliveryOutboxError";
|
|
825
|
+
};
|
|
826
|
+
function createDeliveryOutbox() {
|
|
827
|
+
const jobs = /* @__PURE__ */ new Map();
|
|
828
|
+
const outbox = {
|
|
829
|
+
[commitDeliveryJob]: (job) => {
|
|
830
|
+
jobs.set(job.id, job);
|
|
831
|
+
},
|
|
832
|
+
[prepareDeliveryJob]: (input) => jobs.get(input.id) ?? Object.freeze({
|
|
833
|
+
...input,
|
|
834
|
+
status: "pending"
|
|
835
|
+
}),
|
|
836
|
+
enqueue: (input) => {
|
|
837
|
+
const job = outbox[prepareDeliveryJob](input);
|
|
838
|
+
outbox[commitDeliveryJob](job);
|
|
839
|
+
return job;
|
|
840
|
+
},
|
|
841
|
+
recordAttempt: (id, result) => {
|
|
842
|
+
const current = jobs.get(id);
|
|
843
|
+
if (!current) throw new DeliveryOutboxError(`unknown delivery job: ${id}`);
|
|
844
|
+
const next = recordDeliveryJobAttempt(current, result, result.kind === "delivered" ? createStableId("receipt", {
|
|
845
|
+
id,
|
|
846
|
+
providerMessageId: result.providerMessageId
|
|
847
|
+
}) : void 0);
|
|
848
|
+
jobs.set(id, next);
|
|
849
|
+
return next;
|
|
850
|
+
},
|
|
851
|
+
snapshot: () => Object.freeze([...jobs.values()])
|
|
852
|
+
};
|
|
853
|
+
return outbox;
|
|
854
|
+
}
|
|
855
|
+
//#endregion
|
|
856
|
+
//#region src/core/application/delegation/grant/delegation-service.ts
|
|
857
|
+
var DelegationDenied = class extends Error {
|
|
858
|
+
name = "DelegationDenied";
|
|
859
|
+
};
|
|
860
|
+
function createDelegationService$1(options) {
|
|
861
|
+
const edges = options.edges.map((edge) => Object.freeze({
|
|
862
|
+
...edge,
|
|
863
|
+
toolIds: Object.freeze([...edge.toolIds])
|
|
864
|
+
}));
|
|
865
|
+
return Object.freeze({ delegate: (request) => Effect.try({
|
|
866
|
+
catch: toDelegationFailure,
|
|
867
|
+
try: () => createGrant(edges, options.grantOperations, options.createId, request)
|
|
868
|
+
}) });
|
|
869
|
+
}
|
|
870
|
+
function createGrant(edges, grantOperations, createId, request) {
|
|
871
|
+
const caller = resolveInvocationAuthority(request.callerAuthority);
|
|
872
|
+
const edge = authorizePeerDelegation(edges, caller.agentId, request);
|
|
873
|
+
const toolGrantSet = grantOperations.narrow(caller.toolGrantSet, [
|
|
874
|
+
edge.toolIds,
|
|
875
|
+
request.targetToolGrantSet.toolIds,
|
|
876
|
+
request.requestedToolIds
|
|
877
|
+
]);
|
|
878
|
+
const id = `delegation:${createId()}`;
|
|
879
|
+
return Object.freeze({
|
|
880
|
+
authority: createInvocationAuthority({
|
|
881
|
+
agentId: request.targetAgentId,
|
|
882
|
+
instanceId: request.targetInstanceId,
|
|
883
|
+
runId: id,
|
|
884
|
+
sessionKey: caller.sessionKey,
|
|
885
|
+
sourceMessageId: caller.sourceMessageId,
|
|
886
|
+
tenantKey: caller.tenantKey,
|
|
887
|
+
toolGrantSet
|
|
888
|
+
}),
|
|
889
|
+
id,
|
|
890
|
+
request: Object.freeze({ ...request }),
|
|
891
|
+
toolGrantSet
|
|
892
|
+
});
|
|
893
|
+
}
|
|
894
|
+
function authorizePeerDelegation(edges, callerAgentId, request) {
|
|
895
|
+
const edge = edges.find((candidate) => candidate.fromAgentId === callerAgentId && candidate.toAgentId === request.targetAgentId);
|
|
896
|
+
if (!edge) throw new DelegationDenied("peer delegation edge is not configured");
|
|
897
|
+
if (!Number.isInteger(request.hopCount) || request.hopCount < 0) throw new DelegationDenied("delegation hop count must be a non-negative integer");
|
|
898
|
+
if (!Number.isFinite(request.budget) || request.budget < 0) throw new DelegationDenied("delegation budget must be a non-negative finite number");
|
|
899
|
+
if (request.hopCount > edge.maxHops) throw new DelegationDenied("delegation hop limit exceeded");
|
|
900
|
+
if (request.budget > edge.maxBudget) throw new DelegationDenied("delegation budget exceeded");
|
|
901
|
+
return edge;
|
|
902
|
+
}
|
|
903
|
+
function toDelegationFailure(error) {
|
|
904
|
+
if (error instanceof DelegationDenied || error instanceof InvalidInvocationAuthority) return error;
|
|
905
|
+
return new DelegationDenied("delegation grant could not be created", { cause: error });
|
|
906
|
+
}
|
|
907
|
+
//#endregion
|
|
908
|
+
//#region src/adapters/compatibility/delegation/runtime/effect-runner.ts
|
|
909
|
+
function runDelegationEffect(effect) {
|
|
910
|
+
const exit = Effect.runSyncExit(effect);
|
|
911
|
+
if (Exit.isSuccess(exit)) return exit.value;
|
|
912
|
+
const failure = Cause.failureOption(exit.cause);
|
|
913
|
+
throw Option.isSome(failure) ? failure.value : Cause.squash(exit.cause);
|
|
914
|
+
}
|
|
915
|
+
//#endregion
|
|
916
|
+
//#region src/adapters/compatibility/delegation/delegation-service.ts
|
|
917
|
+
const grantOperations$1 = createRivusToolGrantSetOperations({
|
|
918
|
+
digest: createSha256Digest,
|
|
919
|
+
deepFreeze
|
|
920
|
+
});
|
|
921
|
+
function createDelegationService(options) {
|
|
922
|
+
const service = createDelegationService$1({
|
|
923
|
+
...options,
|
|
924
|
+
createId: createRandomId,
|
|
925
|
+
grantOperations: grantOperations$1
|
|
926
|
+
});
|
|
927
|
+
return Object.freeze({ delegate: (request) => runDelegationEffect(service.delegate(request)) });
|
|
928
|
+
}
|
|
929
|
+
function intersectToolIds(sets) {
|
|
930
|
+
return grantOperations$1.intersect(sets);
|
|
931
|
+
}
|
|
932
|
+
//#endregion
|
|
933
|
+
//#region src/core/application/delegation/subagent/subagent-coordinator.ts
|
|
934
|
+
var ParentDelegationCancelled = class extends Error {
|
|
935
|
+
name = "ParentDelegationCancelled";
|
|
936
|
+
};
|
|
937
|
+
function createSubagentCoordinator$1(options) {
|
|
938
|
+
const records = /* @__PURE__ */ new Map();
|
|
939
|
+
const cancelledParents = /* @__PURE__ */ new Set();
|
|
940
|
+
const serial = Effect.unsafeMakeSemaphore(1);
|
|
941
|
+
return Object.freeze({
|
|
942
|
+
cancelParent: (parentRunId) => serial.withPermits(1)(Effect.gen(function* () {
|
|
943
|
+
cancelledParents.add(parentRunId);
|
|
944
|
+
const active = [...records.values()].filter((record) => record.parentRunId === parentRunId && record.status === "active");
|
|
945
|
+
yield* Effect.forEach(active, (record) => options.cancellation.cancel(record).pipe(Effect.tap(() => Effect.sync(() => {
|
|
946
|
+
records.set(record.id, Object.freeze({
|
|
947
|
+
...record,
|
|
948
|
+
status: "cancelled"
|
|
949
|
+
}));
|
|
950
|
+
}))), {
|
|
951
|
+
concurrency: 1,
|
|
952
|
+
discard: true
|
|
953
|
+
});
|
|
954
|
+
})),
|
|
955
|
+
get: (id) => records.get(id),
|
|
956
|
+
spawn: (request) => serial.withPermits(1)(Effect.try({
|
|
957
|
+
catch: toSubagentFailure,
|
|
958
|
+
try: () => prepareSubagent(request, options.grantOperations, options.createId)
|
|
959
|
+
}).pipe(Effect.flatMap((record) => {
|
|
960
|
+
if (cancelledParents.has(record.parentRunId)) return Effect.fail(new ParentDelegationCancelled(`parent run is cancelled: ${record.parentRunId}`));
|
|
961
|
+
return options.runner.start(record).pipe(Effect.tap(() => Effect.sync(() => {
|
|
962
|
+
records.set(record.id, record);
|
|
963
|
+
})), Effect.as(record));
|
|
964
|
+
})))
|
|
965
|
+
});
|
|
966
|
+
}
|
|
967
|
+
function prepareSubagent(request, grantOperations, createId) {
|
|
968
|
+
const parent = resolveInvocationAuthority(request.parentAuthority);
|
|
969
|
+
const id = `subagent:${createId()}`;
|
|
970
|
+
const toolGrantSet = grantOperations.narrow(parent.toolGrantSet, [
|
|
971
|
+
request.requestedToolIds,
|
|
972
|
+
request.childProfileToolIds,
|
|
973
|
+
request.childDeploymentToolIds
|
|
974
|
+
]);
|
|
975
|
+
return Object.freeze({
|
|
976
|
+
authority: createInvocationAuthority({
|
|
977
|
+
agentId: request.childAgentId,
|
|
978
|
+
instanceId: id,
|
|
979
|
+
runId: id,
|
|
980
|
+
sessionKey: parent.sessionKey,
|
|
981
|
+
sourceMessageId: parent.sourceMessageId,
|
|
982
|
+
tenantKey: parent.tenantKey,
|
|
983
|
+
toolGrantSet
|
|
984
|
+
}),
|
|
985
|
+
capabilities: Object.freeze({
|
|
986
|
+
privateMemory: false,
|
|
987
|
+
senderIdentity: false,
|
|
988
|
+
shell: false
|
|
989
|
+
}),
|
|
990
|
+
childAgentId: request.childAgentId,
|
|
991
|
+
id,
|
|
992
|
+
parentRunId: parent.runId,
|
|
993
|
+
status: "active",
|
|
994
|
+
toolGrantSet: Object.freeze({
|
|
995
|
+
revision: toolGrantSet.revision,
|
|
996
|
+
toolIds: Object.freeze([...toolGrantSet.toolIds])
|
|
997
|
+
})
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
function toSubagentFailure(error) {
|
|
1001
|
+
return error instanceof Error ? error : new InvalidInvocationAuthority("subagent authority could not be created");
|
|
1002
|
+
}
|
|
1003
|
+
//#endregion
|
|
1004
|
+
//#region src/adapters/compatibility/delegation/subagent-coordinator.ts
|
|
1005
|
+
const grantOperations = createRivusToolGrantSetOperations({
|
|
1006
|
+
digest: createSha256Digest,
|
|
1007
|
+
deepFreeze
|
|
1008
|
+
});
|
|
1009
|
+
function createSubagentCoordinator() {
|
|
1010
|
+
return adaptEffectSubagentCoordinator(createSubagentCoordinator$1({
|
|
1011
|
+
cancellation: { cancel: () => Effect.void },
|
|
1012
|
+
createId: createRandomId,
|
|
1013
|
+
grantOperations,
|
|
1014
|
+
runner: { start: () => Effect.void }
|
|
1015
|
+
}));
|
|
1016
|
+
}
|
|
1017
|
+
function adaptEffectSubagentCoordinator(coordinator) {
|
|
1018
|
+
return Object.freeze({
|
|
1019
|
+
cancelParent: (parentRunId) => runDelegationEffect(coordinator.cancelParent(parentRunId)),
|
|
1020
|
+
get: (id) => coordinator.get(id),
|
|
1021
|
+
spawn: (request) => runDelegationEffect(coordinator.spawn(request))
|
|
1022
|
+
});
|
|
1023
|
+
}
|
|
1024
|
+
//#endregion
|
|
1025
|
+
//#region src/adapters/compatibility/deployment-control/rivus-plugin-loader.ts
|
|
1026
|
+
function loadRivusDeployment(options) {
|
|
1027
|
+
return runDeploymentControlEffect(resolveRivusDeployment({
|
|
1028
|
+
agentCatalog: createCompatibleRivusAgentCatalog({ backgroundSessions: options.manifest.backgroundSessions?.enabled === true }),
|
|
1029
|
+
createStableId,
|
|
1030
|
+
deepFreeze,
|
|
1031
|
+
deploymentRoot: options.deploymentRoot,
|
|
1032
|
+
manifest: options.manifest,
|
|
1033
|
+
pluginLoader: createCompatibilityRivusPluginLoader(options.loadModule)
|
|
1034
|
+
}));
|
|
1035
|
+
}
|
|
1036
|
+
function createCompatibilityRivusPluginLoader(loadModule) {
|
|
1037
|
+
return { load: (request) => Effect.tryPromise({
|
|
1038
|
+
try: () => Promise.resolve(loadModule(request)),
|
|
1039
|
+
catch: toError$1
|
|
1040
|
+
}).pipe(Effect.flatMap(resolveRivusPluginModule)) };
|
|
1041
|
+
}
|
|
1042
|
+
function toError$1(error) {
|
|
1043
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
1044
|
+
}
|
|
1045
|
+
//#endregion
|
|
1046
|
+
//#region src/adapters/compatibility/deployment-control/node-rivus-plugin-module-loader.ts
|
|
1047
|
+
function createNodeRivusPluginModuleLoader(options = {}) {
|
|
1048
|
+
const loader = createNodeRivusPluginModuleLoader$1(options);
|
|
1049
|
+
return (request) => runDeploymentControlEffect(loader.load(request));
|
|
1050
|
+
}
|
|
1051
|
+
function loadNodeRivusPluginModule(request, options = {}) {
|
|
1052
|
+
return runDeploymentControlEffect(loadNodeRivusPluginModule$1(request, options));
|
|
1053
|
+
}
|
|
1054
|
+
//#endregion
|
|
1055
|
+
//#region src/adapters/compatibility/deployment-control/rivus-deployment-daemon.ts
|
|
1056
|
+
function toCompatibilityDaemon(control) {
|
|
1057
|
+
return {
|
|
1058
|
+
deployment: control.deployment,
|
|
1059
|
+
handleDefault: (input) => runDeploymentControlEffect(control.handleDefault(toEffectAgentRuntimeInput$1(input))),
|
|
1060
|
+
handleEndpoint: (endpointId, input) => runDeploymentControlEffect(control.handleEndpoint(endpointId, toEffectAgentRuntimeInput$1(input))),
|
|
1061
|
+
runDefaultAgent: (input) => runDeploymentControlEffect(control.runDefaultAgent(toEffectAgentRuntimeInput$1(input))),
|
|
1062
|
+
running: () => control.running(),
|
|
1063
|
+
start: () => runDeploymentControlEffect(control.start()),
|
|
1064
|
+
status: () => control.status(),
|
|
1065
|
+
stop: () => runDeploymentControlEffect(control.stop())
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
//#endregion
|
|
1069
|
+
//#region src/bootstrap/deployment/rivus-deployment-daemon.ts
|
|
1070
|
+
function createRivusDeploymentDaemon(options) {
|
|
1071
|
+
const loadModule = options.loadModule;
|
|
1072
|
+
const assemblyInput = {
|
|
1073
|
+
...createProcessDeploymentControlPorts({
|
|
1074
|
+
...options.createAutomation ? { createAutomation: options.createAutomation } : {},
|
|
1075
|
+
...options.createBackgroundSession ? { createBackgroundSession: options.createBackgroundSession } : {},
|
|
1076
|
+
createEndpoint: options.createEndpoint,
|
|
1077
|
+
createRuntime: options.createRuntime
|
|
1078
|
+
}, options.manifest.backgroundSessions?.enabled === true, runDeploymentProcessEffect),
|
|
1079
|
+
deploymentRoot: options.deploymentRoot,
|
|
1080
|
+
...options.initialInstanceRecords ? { initialInstanceRecords: options.initialInstanceRecords } : {},
|
|
1081
|
+
manifest: options.manifest,
|
|
1082
|
+
pluginLoader: createCompatibilityRivusPluginLoader(loadModule),
|
|
1083
|
+
...options.resolveProjectSpace ? { projectSpaceResolver: { resolve: (input) => Effect.tryPromise({
|
|
1084
|
+
try: () => Promise.resolve(options.resolveProjectSpace(input)),
|
|
1085
|
+
catch: toError
|
|
1086
|
+
}) } } : {}
|
|
1087
|
+
};
|
|
1088
|
+
return runDeploymentProcessEffect(Effect.gen(function* () {
|
|
1089
|
+
const deployment = yield* resolveRivusDeployment({
|
|
1090
|
+
agentCatalog: assemblyInput.agentCatalog,
|
|
1091
|
+
createStableId,
|
|
1092
|
+
deepFreeze,
|
|
1093
|
+
deploymentRoot: assemblyInput.deploymentRoot,
|
|
1094
|
+
manifest: assemblyInput.manifest,
|
|
1095
|
+
pluginLoader: assemblyInput.pluginLoader
|
|
1096
|
+
});
|
|
1097
|
+
return yield* createRivusDeploymentControl({
|
|
1098
|
+
...assemblyInput,
|
|
1099
|
+
deployment,
|
|
1100
|
+
digest: createSha256Digest
|
|
1101
|
+
});
|
|
1102
|
+
})).then(toCompatibilityDaemon);
|
|
1103
|
+
}
|
|
1104
|
+
function toError(error) {
|
|
1105
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
1106
|
+
}
|
|
1107
|
+
//#endregion
|
|
1108
|
+
//#region src/bootstrap/deployment/configured-rivus-deployment-daemon.ts
|
|
1109
|
+
async function createConfiguredRivusDeploymentDaemon(options) {
|
|
1110
|
+
const manifest = await loadRivusDeploymentManifest(options.manifestPath, options.manifestOptions);
|
|
1111
|
+
return createRivusDeploymentDaemon({
|
|
1112
|
+
...options.createAutomation ? { createAutomation: options.createAutomation } : {},
|
|
1113
|
+
...options.createBackgroundSession ? { createBackgroundSession: options.createBackgroundSession } : {},
|
|
1114
|
+
createEndpoint: options.createEndpoint,
|
|
1115
|
+
createRuntime: options.createRuntime,
|
|
1116
|
+
deploymentRoot: dirname(options.manifestPath),
|
|
1117
|
+
...options.initialInstanceRecords ? { initialInstanceRecords: options.initialInstanceRecords } : {},
|
|
1118
|
+
loadModule: createNodeRivusPluginModuleLoader(options.pluginPackageManifestPath ? { packageManifestPath: options.pluginPackageManifestPath } : {}),
|
|
1119
|
+
manifest,
|
|
1120
|
+
resolveProjectSpace: (input) => resolveRivusProjectSpace(input)
|
|
1121
|
+
});
|
|
1122
|
+
}
|
|
1123
|
+
//#endregion
|
|
1124
|
+
//#region src/adapters/compatibility/human-interaction/transitions.ts
|
|
1125
|
+
var HumanInteractionTransitionDenied = class extends Error {
|
|
1126
|
+
name = "HumanInteractionTransitionDenied";
|
|
1127
|
+
};
|
|
1128
|
+
function transitionHumanInteraction(interaction, transition) {
|
|
1129
|
+
const root = toHumanInteractionAggregate(interaction);
|
|
1130
|
+
try {
|
|
1131
|
+
if (transition.type === "resolve") return toHumanInteractionSnapshot(root.resolve(transition).state);
|
|
1132
|
+
if (transition.type === "consume-approval") return toHumanInteractionSnapshot(root.consume(transition).state);
|
|
1133
|
+
return toHumanInteractionSnapshot(root.cancel(transition).state);
|
|
1134
|
+
} catch (error) {
|
|
1135
|
+
if (error instanceof Error && error.name === "HumanInteractionTransitionDenied") throw new HumanInteractionTransitionDenied(error.message);
|
|
1136
|
+
throw error;
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
//#endregion
|
|
1140
|
+
//#region src/adapters/compatibility/automation/outcome/effect-runner.ts
|
|
1141
|
+
function runAutomationOutcomeEffect(effect) {
|
|
1142
|
+
const exit = Effect.runSyncExit(effect);
|
|
1143
|
+
if (Exit.isSuccess(exit)) return exit.value;
|
|
1144
|
+
const failure = Cause.failureOption(exit.cause);
|
|
1145
|
+
throw Option.isSome(failure) ? failure.value : Cause.squash(exit.cause);
|
|
1146
|
+
}
|
|
1147
|
+
//#endregion
|
|
1148
|
+
//#region src/adapters/compatibility/automation/outcome/commit-automation-outcome.ts
|
|
1149
|
+
function commitAutomationOutcome$1(input) {
|
|
1150
|
+
return runAutomationOutcomeEffect(commitAutomationOutcome({
|
|
1151
|
+
outcome: input.outcome,
|
|
1152
|
+
repository: compatibilityRepository(input),
|
|
1153
|
+
stateUpdate: input.stateUpdate,
|
|
1154
|
+
tickId: input.tickId
|
|
1155
|
+
}));
|
|
1156
|
+
}
|
|
1157
|
+
function compatibilityRepository(input) {
|
|
1158
|
+
return {
|
|
1159
|
+
commit: (command) => Effect.sync(() => commitCompatibilityStores({
|
|
1160
|
+
...input,
|
|
1161
|
+
outcome: command.outcome,
|
|
1162
|
+
stateUpdate: command.stateUpdate,
|
|
1163
|
+
tickId: command.tickId
|
|
1164
|
+
})),
|
|
1165
|
+
recordDeliveryAttempt: () => Effect.fail(new DeliveryOutboxError("delivery attempts use the DeliveryOutbox facade"))
|
|
1166
|
+
};
|
|
1167
|
+
}
|
|
1168
|
+
function commitCompatibilityStores(input) {
|
|
1169
|
+
if (!isTransactionalState(input.state) || !isTransactionalOutbox(input.outbox)) return commitLegacyOutcome(input);
|
|
1170
|
+
const state = input.state;
|
|
1171
|
+
const preparedState = state[preparePluginState](input.stateUpdate);
|
|
1172
|
+
if (input.outcome.kind === "suppressed") {
|
|
1173
|
+
state[commitPluginState](preparedState);
|
|
1174
|
+
return Object.freeze({ state: preparedState.record });
|
|
1175
|
+
}
|
|
1176
|
+
const outbox = input.outbox;
|
|
1177
|
+
const preparedJob = outbox[prepareDeliveryJob](createDeliveryJob(input.outcome, input.tickId));
|
|
1178
|
+
state[commitPluginState](preparedState);
|
|
1179
|
+
outbox[commitDeliveryJob](preparedJob);
|
|
1180
|
+
return Object.freeze({
|
|
1181
|
+
job: preparedJob,
|
|
1182
|
+
state: preparedState.record
|
|
1183
|
+
});
|
|
1184
|
+
}
|
|
1185
|
+
function commitLegacyOutcome(input) {
|
|
1186
|
+
if ((input.state.get(input.stateUpdate.pluginId, input.stateUpdate.agentId, input.stateUpdate.key)?.revision ?? 0) !== input.stateUpdate.expectedRevision) throw new DeliveryOutboxError("plugin state revision conflict before outcome commit");
|
|
1187
|
+
const state = input.state.put(input.stateUpdate);
|
|
1188
|
+
if (input.outcome.kind === "suppressed") return Object.freeze({ state });
|
|
1189
|
+
const job = input.outbox.enqueue(createDeliveryJob(input.outcome, input.tickId));
|
|
1190
|
+
return Object.freeze({
|
|
1191
|
+
job,
|
|
1192
|
+
state
|
|
1193
|
+
});
|
|
1194
|
+
}
|
|
1195
|
+
function createDeliveryJob(outcome, tickId) {
|
|
1196
|
+
return {
|
|
1197
|
+
body: outcome.body,
|
|
1198
|
+
id: createStableId("delivery", {
|
|
1199
|
+
kind: outcome.kind,
|
|
1200
|
+
target: outcome.target,
|
|
1201
|
+
tickId
|
|
1202
|
+
}),
|
|
1203
|
+
kind: outcome.kind,
|
|
1204
|
+
target: outcome.target,
|
|
1205
|
+
tickId
|
|
1206
|
+
};
|
|
1207
|
+
}
|
|
1208
|
+
function isTransactionalState(store) {
|
|
1209
|
+
return preparePluginState in store && commitPluginState in store;
|
|
1210
|
+
}
|
|
1211
|
+
function isTransactionalOutbox(outbox) {
|
|
1212
|
+
return prepareDeliveryJob in outbox && commitDeliveryJob in outbox;
|
|
1213
|
+
}
|
|
1214
|
+
//#endregion
|
|
1215
|
+
export { AUTOMATION_PRESENTATION_SCHEMA_VERSION, AUTOMATION_SUPPRESSION_PREFIX, AgentInstanceBusy, AgentInstanceConflict, AgentMemoryError, AgentRuntimeDisposed, AutomationMandateError, BACKGROUND_SESSION_DELIVERY_JSONL_VERSION, BACKGROUND_SESSION_JSONL_VERSION, BACKGROUND_SESSION_SESSION_KEY_PREFIX, BACKGROUND_SESSION_START_TOOL_ID, BACKGROUND_SESSION_TOOL_IDS, BACKGROUND_SESSION_TOOL_PLUGIN_ID, BACKGROUND_SESSION_TOOL_VERSION, BackgroundSessionCallerDenied, BackgroundSessionDeliveryConflict, BackgroundSessionRepositoryConflict, BackgroundSessionRepositoryCorrupted, BackgroundSessionTransitionDenied, CardPresentationTransitionDenied, DEFAULT_BACKGROUND_SESSION_LEASE_MS, DEFAULT_BACKGROUND_SESSION_LEASE_RENEWAL_INTERVAL_MS, DEFAULT_BACKGROUND_SESSION_LIFETIME_MS, DEFAULT_BACKGROUND_SESSION_MAX_CONCURRENT_SESSIONS, DEFAULT_BACKGROUND_SESSION_MAX_CONSECUTIVE_FAILURES, DEFAULT_BACKGROUND_SESSION_RETRY_BACKOFF_MS, DEFAULT_BACKGROUND_SESSION_STEP_TIMEOUT_MS, DEFAULT_BACKGROUND_SESSION_SUPERVISOR_INTERVAL_MS, DEFAULT_CARD_STREAM_LEASE_MS, DEFAULT_CONVERSATION_PROGRESS_DISPLAY, DelegationDenied, DeliveryOutboxError, FEISHU_AGENT_CARD_ELEMENT_ID, FEISHU_AGENT_CARD_PROGRESS_ELEMENT_ID, FeishuCardPresentationNotFound, FeishuCardTargetNotFound, FeishuCardTargetRegistryStoreError, FeishuCotProtocolError, FeishuEndpointCredentialError, FeishuOpenApiError, FeishuTenantAccessTokenError, HumanInteractionRepositoryError, HumanInteractionTransitionDenied, InvalidAgentHostBinding, InvalidAutomationPresentation, InvalidFeishuCardAction, InvalidFeishuMessageContent, InvalidFeishuSessionReference, InvalidFeishuTopicContext, InvalidRivusEndpointBinding, InvalidRivusPlugin, InvalidRivusProjectSpace, MODEL_STATE_SCHEMA_VERSION, ModelChangeAuthorizationRejected, ModelChangeBoundaryDeadlineError, ModelChangeBusy, ModelChangeNotFound, ModelChangeRequestConflict, ModelChangeRevisionConflict, ModelStateCorrupted, OpenClawEnvImportError, PiModelRunContextError, PluginStateConflict, RIVUS_MODEL_CHANGE_TOOL_ID, RIVUS_MODEL_CONTEXT_ENV, RIVUS_MODEL_SOCKET_ENV, RIVUS_PLUGIN_API_VERSION, RIVUS_RELEASE_DESCRIPTOR, RUN_PRESENTATION_SCHEMA_VERSION, RivusDaemonConfigError, RivusDeploymentAutomationReadinessError, RivusDeploymentBackgroundSessionReadinessError, RivusDeploymentDaemonLifecycleError, RivusDeploymentManifestError, RivusDeploymentReadinessError, RivusPluginLoadError, SessionSchedulerCapacityExceeded, SessionSchedulerDisposed, ToolInvocationDenied, UnsupportedFeishuCardAction, UnsupportedFeishuMessage, acceptsCardPresentationProgress, activeCardPresentation, appendBackgroundSessionInput, backgroundSessionToolIds, claimBackgroundSession, commitAutomationOutcome, commitAutomationOutcome$1 as commitLegacyAutomationOutcome, completeBackgroundSessionStep, completeBackgroundSessionStop, composeFeishuTopicPrompt, createAgentCommandFromFeishuCardAction, createAgentCommandFromFeishuMessage, createAgentHarnessPooledRuntime, createAgentHostRuntimePool, createAgentInstanceRegistry, createAgentMemoryService, createAgentRuntimePool, createAgentsMdInstructionsProvider, createAutomationMandateStore, createAutomationPresentation, createAutomationScheduler, createBackgroundSession, createBackgroundSessionCard, createBackgroundSessionDeliveryStore, createBackgroundSessionHostTools, createBackgroundSessionKey, createBackgroundSessionRepository, createBackgroundSessionService, createBackgroundSessionStepSourceMessageId, createBackgroundSessionSupervisor, createBackgroundSessionToolContracts, createCoalescingFeishuPublisher, createCompatibleRivusAgentCatalog, createCompositeRivusDaemonTransport, createConfiguredFeishuAutomationCardSender, createConfiguredFeishuBackgroundSessionDelivery, createConfiguredFeishuCardKitPublisher, createConfiguredFeishuCardKitTargetCreator, createConfiguredFeishuCardRolloverRuntime, createConfiguredFeishuHumanInteractionPresenter, createConfiguredFeishuMessageReactionSender, createConfiguredFeishuOpenApiClient, createConfiguredFeishuTextReplySender, createConfiguredRivusDaemonBootstrap, createConfiguredRivusDeploymentDaemon, createDailyAutomationSchedule, createDelegationService, createDeliveryOutbox, createEffectAgentHost, createEffectAgentInstanceRegistry, createFeishuAgentDaemon, createFeishuAgentRunCard, createFeishuAgentRuntime, createFeishuCardActionCallbackResponse, createFeishuCardActionErrorResponse, createFeishuCardDeliveryLedger, createFeishuCardDeliveryReconciler, createFeishuCardKitOpenApiClient, createFeishuCardKitOpenApiTargetCreator, createFeishuCardKitPublisher, createFeishuCardPresentationStore, createFeishuCardRollover, createFeishuCardRolloverSupervisor, createFeishuCardTargetPreparation, createFeishuConversationId, createFeishuCotPublisher, createFeishuDeploymentEndpoint, createFeishuEventHandlers, createFeishuHumanInteractionCard, createFeishuHumanInteractionPresenter, createFeishuInboxRepository, createFeishuMessageQueue, createFeishuMessageWorker, createFeishuOpenApiClient, createFeishuPeriodicFlush, createFeishuPresentationPreparation, createFeishuSessionKey, createFeishuSessionStore, createFeishuStreamProjector, createFeishuTenantAccessTokenProvider, createFeishuTopicContextResolver, createFeishuWebSocketDaemon, createFeishuWorkerLoop, createHumanInteractionEndpointRegistry, createHumanInteractionModelChangeApproval, createHumanInteractionService, createHumanInteractionToolApprovalGateway, createInMemoryFeishuCardTargetRegistry, createInMemoryHumanInteractionRepository, createJsonFetchRequest, createJsonFileFeishuCardTargetRegistry, createJsonlHumanInteractionRepository, createLazyFeishuWebSocketEventDispatcher, createBackgroundSessionService$1 as createLegacyBackgroundSessionService, createHumanInteractionService$1 as createLegacyHumanInteractionService, createMessageGateway, createModelChangeAuthorization, createModelChangeCoordinator, createModelChangeRunBoundary, createModelManagementControl, createPiManagedRunGatewayProvider, createPiModelManagementBashSpawnHook, createPiModelRunContextRegistry, createPluginStateStore, createPresentedValue, createRateLimitedFeishuPublisher, createRecoveryControl, createRivusAgentCatalog, createRivusAgentHost, createRivusDaemonProcess, createRivusDaemonShutdownController, createRivusDaemonStatusHttpServer, createRivusDaemonStatusReporter, createRivusDeploymentCliProcess, createRivusDeploymentDaemon, createRivusEnvFromOpenClawConfig, createRivusPluginCatalog, createRoutedHumanInteractionToolApprovalService, createRunPresentationProjector, createScheduledAutomation, createSessionScheduler, createSubagentCoordinator, createToolBroker, describeFeishuMessageIntake, diagnoseRivusProject, extendBackgroundSessionDefinition, failBackgroundSessionStep, formatRivusEnvFile, hasInspectableRunProgress, initializeRivusProject, intersectToolIds, isBackgroundSessionDue, isBackgroundSessionLeaseExpired, isBackgroundSessionState, isBackgroundSessionTerminalPhase, isBackgroundSessionToolId, isCardPresentationHandoffDue, loadNodeRivusPluginModule, loadRivusDaemonConfig, loadRivusDeployment, loadRivusDeploymentManifest, narrowBackgroundSessionDefinition, openJsonAutomationTickRepository, openJsonFeishuSessionStore, openJsonlAgentMemoryService, openJsonlBackgroundSessionDeliveryStore, openJsonlBackgroundSessionRepository, openJsonlFeishuCardDeliveryLedger, openJsonlFeishuInboxRepository, openJsonlRecoveryControl, openJsonlToolOperationLedger, openPiModelManagementDeployment, parkBackgroundSessionForReconciliation, progressDeliveryId, readAutomationPresentation, readFeishuMessageContent, readPiModelManagementGrant, releaseBackgroundSessionLease, renewBackgroundSessionLease, requestBackgroundSessionStop, requeueInterruptedBackgroundSessionStep, resolveBackgroundSessionReconciliation, resolveBackgroundSessionSupervisorIntervalMs, resolveFeishuDeliveryChatId, resolveFeishuEndpointCredentials, resolveRivusAgentDefinition, resolveRivusProjectSpace, restoreConfiguredRivusDaemonBootstrap, runRivusCli, runRivusDaemonCli, runRivusNodeEntrypoint, sessionIdFromSessionKey, shouldAcceptFeishuEndpointMessage, suspendBackgroundSession, terminalDeliveryId, transitionHumanInteraction, validateRivusCatalogIdentifier, validateRivusCatalogRegistration, validateRivusDeploymentManifest, validateRivusPluginManifest };
|