@zhin.js/core 1.5.15 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +78 -195
- package/lib/ai-completion-contract.d.ts +135 -0
- package/lib/ai-completion-contract.js +69 -0
- package/lib/built/ai-access.d.ts +2 -21
- package/lib/built/ai-access.js +1 -46
- package/lib/built/ai-outbound/index.d.ts +0 -2
- package/lib/built/ai-outbound/index.js +0 -2
- package/lib/built/ai-outbound/prompt.d.ts +2 -0
- package/lib/built/ai-outbound/prompt.js +2 -0
- package/lib/built/ai-outbound/types.d.ts +1 -10
- package/lib/built/ai-trigger.d.ts +39 -78
- package/lib/built/ai-trigger.js +3 -254
- package/lib/built/common-adapter-tools.d.ts +21 -6
- package/lib/built/common-adapter-tools.js +28 -17
- package/lib/built/generic-segment-mapper.js +4 -1
- package/lib/built/html-segment-fallback.d.ts +6 -7
- package/lib/built/html-segment-fallback.js +1 -16
- package/lib/built/html-to-text.d.ts +0 -3
- package/lib/built/html-to-text.js +131 -40
- package/lib/built/interaction-messages.d.ts +1 -0
- package/lib/built/interaction-messages.js +30 -0
- package/lib/built/interactive-segments/action.d.ts +3 -4
- package/lib/built/interactive-segments/action.js +2 -5
- package/lib/built/interactive-segments/index.d.ts +0 -2
- package/lib/built/interactive-segments/index.js +0 -2
- package/lib/built/interactive-segments/keyboard-segment.d.ts +0 -1
- package/lib/built/interactive-segments/keyboard-segment.js +0 -1
- package/lib/built/interactive-segments/onebot-keyboard.d.ts +0 -1
- package/lib/built/interactive-segments/onebot-keyboard.js +0 -2
- package/lib/built/interactive-segments/resolve.d.ts +2 -3
- package/lib/built/interactive-segments/resolve.js +21 -14
- package/lib/built/interactive-segments/types.d.ts +2 -7
- package/lib/built/interactive-segments/types.js +22 -2
- package/lib/built/login-assist.d.ts +13 -11
- package/lib/built/login-assist.js +32 -26
- package/lib/built/message-enrich.d.ts +24 -27
- package/lib/built/message-enrich.js +53 -49
- package/lib/built/outbound-content-arrays.d.ts +4 -0
- package/lib/built/outbound-content-arrays.js +32 -0
- package/lib/built/outbound-media-trust.d.ts +46 -0
- package/lib/built/outbound-media-trust.js +245 -0
- package/lib/built/outbound-media-utils.d.ts +5 -3
- package/lib/built/outbound-media-utils.js +5 -3
- package/lib/built/readable-link.d.ts +4 -0
- package/lib/built/readable-link.js +32 -0
- package/lib/built/rich-segments/markdown-to-text.d.ts +1 -2
- package/lib/built/rich-segments/markdown-to-text.js +141 -17
- package/lib/built/roles.d.ts +141 -12
- package/lib/built/roles.js +253 -52
- package/lib/built/segment-contract/assert.js +8 -2
- package/lib/built/segment-contract/delivery.js +1 -0
- package/lib/built/segment-contract/index.d.ts +3 -3
- package/lib/built/segment-contract/index.js +2 -2
- package/lib/built/segment-contract/json-schema.d.ts +39 -5
- package/lib/built/segment-contract/json-schema.js +207 -24
- package/lib/built/segment-contract/preview.js +8 -1
- package/lib/built/segment-contract/text.js +1 -1
- package/lib/built/segment-contract/types.d.ts +2 -2
- package/lib/built/segment-contract/validate.d.ts +1553 -224
- package/lib/built/segment-contract/validate.js +39 -3
- package/lib/built/tool-access.d.ts +5 -0
- package/lib/built/tool-access.js +17 -0
- package/lib/built/user-interaction.d.ts +5 -4
- package/lib/built/user-interaction.js +64 -52
- package/lib/errors.d.ts +1 -18
- package/lib/errors.js +1 -26
- package/lib/feature/command-public-api.d.ts +5 -0
- package/lib/feature/command-public-api.js +5 -0
- package/lib/feature/command.d.ts +2 -0
- package/lib/feature/command.js +1 -0
- package/lib/feature/component.d.ts +1 -0
- package/lib/feature/component.js +1 -0
- package/lib/feature/handler.d.ts +13 -7
- package/lib/feature/handler.js +2 -1
- package/lib/feature/middleware-public-api.d.ts +6 -0
- package/lib/feature/middleware-public-api.js +6 -0
- package/lib/feature/middleware.d.ts +22 -2
- package/lib/feature/middleware.js +7 -2
- package/lib/im-scene.d.ts +4 -3
- package/lib/im-scene.js +9 -9
- package/lib/im-session-id.d.ts +20 -12
- package/lib/im-session-id.js +8 -8
- package/lib/index.d.ts +19 -48
- package/lib/index.js +14 -41
- package/lib/jsx/intrinsic-elements.d.ts +83 -0
- package/lib/jsx/message-renderer.d.ts +13 -0
- package/lib/jsx/message-renderer.js +128 -0
- package/lib/jsx/message-tags.d.ts +133 -0
- package/lib/jsx/message-tags.js +50 -0
- package/lib/jsx-dev-runtime.d.ts +2 -2
- package/lib/jsx-dev-runtime.js +1 -2
- package/lib/jsx-runtime.d.ts +2 -12
- package/lib/jsx-runtime.js +1 -10
- package/lib/jsx.d.ts +6 -30
- package/lib/jsx.js +3 -93
- package/lib/message.d.ts +0 -40
- package/lib/message.js +1 -27
- package/lib/models/system-log.d.ts +0 -2
- package/lib/models/system-log.js +1 -8
- package/lib/models/user.d.ts +0 -2
- package/lib/models/user.js +1 -7
- package/lib/notice.d.ts +38 -33
- package/lib/notice.js +23 -7
- package/lib/plugin-runtime/im/command-feedback.d.ts +59 -0
- package/lib/plugin-runtime/im/command-feedback.js +148 -0
- package/lib/plugin-runtime/im/contracts.d.ts +217 -32
- package/lib/plugin-runtime/im/contracts.js +141 -23
- package/lib/plugin-runtime/im/conversation-runtime.d.ts +42 -0
- package/lib/plugin-runtime/im/conversation-runtime.js +451 -0
- package/lib/plugin-runtime/im/endpoint-runtime.d.ts +89 -0
- package/lib/plugin-runtime/im/endpoint-runtime.js +381 -0
- package/lib/plugin-runtime/im/feature-gate.d.ts +21 -0
- package/lib/plugin-runtime/im/feature-gate.js +88 -0
- package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
- package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
- package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
- package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
- package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
- package/lib/plugin-runtime/im/host/database-config.js +114 -0
- package/lib/plugin-runtime/im/host/database-host-installer.d.ts +29 -0
- package/lib/plugin-runtime/im/host/database-host-installer.js +442 -0
- package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
- package/lib/plugin-runtime/im/host/database-state.js +91 -0
- package/lib/plugin-runtime/im/host/index.d.ts +8 -0
- package/lib/plugin-runtime/im/host/index.js +8 -0
- package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
- package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
- package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
- package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
- package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +34 -0
- package/lib/plugin-runtime/im/host/sender-enrichment.js +82 -0
- package/lib/plugin-runtime/im/im-runtime.d.ts +40 -111
- package/lib/plugin-runtime/im/im-runtime.js +234 -1059
- package/lib/plugin-runtime/im/inbound-dedup.d.ts +84 -0
- package/lib/plugin-runtime/im/inbound-dedup.js +322 -0
- package/lib/plugin-runtime/im/inbound-origin.d.ts +150 -0
- package/lib/plugin-runtime/im/inbound-origin.js +183 -0
- package/lib/plugin-runtime/im/inbound-runtime.d.ts +59 -0
- package/lib/plugin-runtime/im/inbound-runtime.js +478 -0
- package/lib/plugin-runtime/im/inbound-spine.d.ts +196 -0
- package/lib/plugin-runtime/im/inbound-spine.js +335 -0
- package/lib/plugin-runtime/im/index.d.ts +15 -4
- package/lib/plugin-runtime/im/index.js +11 -4
- package/lib/plugin-runtime/im/interaction-runtime.d.ts +50 -0
- package/lib/plugin-runtime/im/interaction-runtime.js +390 -0
- package/lib/plugin-runtime/im/interactive-router.d.ts +81 -0
- package/lib/plugin-runtime/im/interactive-router.js +382 -0
- package/lib/plugin-runtime/im/message-diagnostics.d.ts +70 -0
- package/lib/plugin-runtime/im/message-diagnostics.js +182 -0
- package/lib/plugin-runtime/im/message-dispatcher.d.ts +18 -4
- package/lib/plugin-runtime/im/message-dispatcher.js +138 -20
- package/lib/plugin-runtime/im/message-events.d.ts +85 -0
- package/lib/plugin-runtime/im/message-events.js +113 -0
- package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +39 -0
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +450 -0
- package/lib/plugin-runtime/im/outbound-renderer.d.ts +52 -3
- package/lib/plugin-runtime/im/outbound-renderer.js +188 -8
- package/lib/plugin-runtime/im/outbound-segments.d.ts +29 -5
- package/lib/plugin-runtime/im/outbound-segments.js +130 -36
- package/lib/plugin-runtime/im/progressive-reply.d.ts +58 -0
- package/lib/plugin-runtime/im/progressive-reply.js +501 -0
- package/lib/plugin-runtime/im/public-api.d.ts +1 -1
- package/lib/request.d.ts +27 -36
- package/lib/request.js +14 -6
- package/lib/side-event/base.d.ts +64 -44
- package/lib/side-event/base.js +72 -19
- package/lib/side-event/index.d.ts +1 -1
- package/lib/side-event/index.js +1 -1
- package/lib/side-event/normalize.d.ts +7 -38
- package/lib/side-event/normalize.js +4 -109
- package/lib/side-event/scene-events.d.ts +40 -0
- package/lib/side-event/scene-events.js +147 -0
- package/lib/side-event/types.d.ts +4 -13
- package/lib/side-event/types.js +1 -55
- package/lib/system-event.d.ts +17 -12
- package/lib/system-event.js +8 -6
- package/lib/types.d.ts +23 -167
- package/lib/utils.d.ts +50 -33
- package/lib/utils.js +12 -185
- package/lib/venue/contracts.d.ts +21 -0
- package/lib/venue/contracts.js +3 -0
- package/lib/venue/floor-controller.d.ts +11 -0
- package/lib/venue/floor-controller.js +63 -0
- package/lib/venue/index.d.ts +13 -0
- package/lib/venue/index.js +11 -0
- package/lib/venue/membership-port.d.ts +23 -0
- package/lib/venue/membership-port.js +141 -0
- package/lib/venue/projector.d.ts +38 -0
- package/lib/venue/projector.js +45 -0
- package/lib/venue/registry.d.ts +16 -0
- package/lib/venue/registry.js +63 -0
- package/lib/venue/router.d.ts +19 -0
- package/lib/venue/router.js +101 -0
- package/lib/venue/send-limiter.d.ts +17 -0
- package/lib/venue/send-limiter.js +73 -0
- package/lib/venue/validator.d.ts +6 -0
- package/lib/venue/validator.js +160 -0
- package/package.json +24 -50
- package/lib/adapter.d.ts +0 -145
- package/lib/adapter.js +0 -377
- package/lib/built/adapter-process.d.ts +0 -58
- package/lib/built/adapter-process.js +0 -128
- package/lib/built/agent-preset.d.ts +0 -64
- package/lib/built/agent-preset.js +0 -79
- package/lib/built/ai-outbound/adapter-access.d.ts +0 -3
- package/lib/built/ai-outbound/adapter-access.js +0 -9
- package/lib/built/ai-outbound/extensions/qq-message.d.ts +0 -3
- package/lib/built/ai-outbound/extensions/qq-message.js +0 -23
- package/lib/built/authorization.d.ts +0 -10
- package/lib/built/authorization.js +0 -76
- package/lib/built/command.d.ts +0 -72
- package/lib/built/command.js +0 -105
- package/lib/built/component.d.ts +0 -67
- package/lib/built/component.js +0 -97
- package/lib/built/config.d.ts +0 -98
- package/lib/built/config.js +0 -372
- package/lib/built/connect-endpoint-instance.d.ts +0 -17
- package/lib/built/connect-endpoint-instance.js +0 -42
- package/lib/built/database.d.ts +0 -68
- package/lib/built/database.js +0 -106
- package/lib/built/dispatcher.d.ts +0 -141
- package/lib/built/dispatcher.js +0 -383
- package/lib/built/endpoint-commands.d.ts +0 -3
- package/lib/built/endpoint-commands.js +0 -99
- package/lib/built/endpoint-lifecycle-service.d.ts +0 -28
- package/lib/built/endpoint-lifecycle-service.js +0 -242
- package/lib/built/endpoint-lifecycle.d.ts +0 -27
- package/lib/built/endpoint-lifecycle.js +0 -36
- package/lib/built/endpoint-manager.d.ts +0 -34
- package/lib/built/html-renderer-loader.d.ts +0 -13
- package/lib/built/html-renderer-loader.js +0 -33
- package/lib/built/inbound-pipeline.d.ts +0 -37
- package/lib/built/inbound-pipeline.js +0 -63
- package/lib/built/inbound-runner.d.ts +0 -22
- package/lib/built/inbound-runner.js +0 -34
- package/lib/built/interactive-segment-contract.d.ts +0 -6
- package/lib/built/interactive-segment-contract.js +0 -9
- package/lib/built/interactive-segments/fallback-store.d.ts +0 -29
- package/lib/built/interactive-segments/fallback-store.js +0 -63
- package/lib/built/interactive-segments/handlers.d.ts +0 -16
- package/lib/built/interactive-segments/handlers.js +0 -74
- package/lib/built/introspection-format.d.ts +0 -10
- package/lib/built/introspection-format.js +0 -28
- package/lib/built/management-command-guard.d.ts +0 -15
- package/lib/built/management-command-guard.js +0 -25
- package/lib/built/message-filter.d.ts +0 -176
- package/lib/built/message-filter.js +0 -239
- package/lib/built/optional-peer-import.d.ts +0 -3
- package/lib/built/optional-peer-import.js +0 -33
- package/lib/built/outbound-media-contract.d.ts +0 -22
- package/lib/built/outbound-media-contract.js +0 -10
- package/lib/built/permission.d.ts +0 -51
- package/lib/built/permission.js +0 -99
- package/lib/built/permit-check.d.ts +0 -7
- package/lib/built/permit-check.js +0 -35
- package/lib/built/permit-parse.d.ts +0 -16
- package/lib/built/permit-parse.js +0 -32
- package/lib/built/platform-permit.d.ts +0 -20
- package/lib/built/platform-permit.js +0 -91
- package/lib/built/queue-im-field-contract.d.ts +0 -32
- package/lib/built/queue-im-field-contract.js +0 -67
- package/lib/built/rich-segments/adapter-policies.d.ts +0 -9
- package/lib/built/rich-segments/adapter-policies.js +0 -27
- package/lib/built/rich-segments/base.d.ts +0 -11
- package/lib/built/rich-segments/base.js +0 -24
- package/lib/built/rich-segments/builtins.d.ts +0 -4
- package/lib/built/rich-segments/builtins.js +0 -40
- package/lib/built/rich-segments/capabilities.d.ts +0 -6
- package/lib/built/rich-segments/capabilities.js +0 -38
- package/lib/built/rich-segments/html-segment.d.ts +0 -15
- package/lib/built/rich-segments/html-segment.js +0 -62
- package/lib/built/rich-segments/index.d.ts +0 -13
- package/lib/built/rich-segments/index.js +0 -13
- package/lib/built/rich-segments/markdown-segment.d.ts +0 -14
- package/lib/built/rich-segments/markdown-segment.js +0 -58
- package/lib/built/rich-segments/qrcode-segment.d.ts +0 -18
- package/lib/built/rich-segments/qrcode-segment.js +0 -73
- package/lib/built/rich-segments/registry.d.ts +0 -16
- package/lib/built/rich-segments/registry.js +0 -52
- package/lib/built/rich-segments/resolve.d.ts +0 -5
- package/lib/built/rich-segments/resolve.js +0 -87
- package/lib/built/rich-segments/tts-segment.d.ts +0 -13
- package/lib/built/rich-segments/tts-segment.js +0 -51
- package/lib/built/rich-segments/types.d.ts +0 -79
- package/lib/built/rich-segments/types.js +0 -17
- package/lib/built/runtime-io.d.ts +0 -9
- package/lib/built/runtime-io.js +0 -67
- package/lib/built/schedule.d.ts +0 -54
- package/lib/built/schedule.js +0 -112
- package/lib/built/schema-endpoint-manager.d.ts +0 -17
- package/lib/built/schema-endpoint-manager.js +0 -73
- package/lib/built/schema-feature.d.ts +0 -77
- package/lib/built/schema-feature.js +0 -130
- package/lib/built/skill.d.ts +0 -120
- package/lib/built/skill.js +0 -151
- package/lib/built/speech-loader.d.ts +0 -14
- package/lib/built/speech-loader.js +0 -32
- package/lib/built/tool.d.ts +0 -151
- package/lib/built/tool.js +0 -388
- package/lib/command.d.ts +0 -50
- package/lib/command.js +0 -106
- package/lib/component.d.ts +0 -26
- package/lib/component.js +0 -583
- package/lib/endpoint-capabilities.d.ts +0 -46
- package/lib/endpoint-capabilities.js +0 -55
- package/lib/endpoint.d.ts +0 -19
- package/lib/endpoint.js +0 -3
- package/lib/host-plugin-registry.d.ts +0 -8
- package/lib/host-plugin-registry.js +0 -12
- package/lib/plugin-context.d.ts +0 -27
- package/lib/plugin-context.js +0 -64
- package/lib/plugin-runtime/im/interactive.d.ts +0 -26
- package/lib/plugin-runtime/im/interactive.js +0 -46
- package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
- package/lib/plugin-runtime/im/login-assist-host.js +0 -6
- package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
- package/lib/plugin-runtime/im/message-bus.js +0 -40
- package/lib/plugin-runtime/im/service-tokens.d.ts +0 -18
- package/lib/plugin-runtime/im/service-tokens.js +0 -13
- package/lib/plugin.d.ts +0 -268
- package/lib/plugin.js +0 -583
- package/lib/schema-interaction.d.ts +0 -117
- package/lib/schema-interaction.js +0 -247
- package/lib/side-event/dispatch.d.ts +0 -15
- package/lib/side-event/dispatch.js +0 -140
- package/lib/tool-zod.d.ts +0 -43
- package/lib/tool-zod.js +0 -184
- /package/lib/{built/endpoint-manager.js → jsx/intrinsic-elements.js} +0 -0
|
@@ -1,70 +1,178 @@
|
|
|
1
|
-
import { createToken,
|
|
1
|
+
import { OwnerOperation, createToken, readLeasedRootResource, generationAdmissionBinder, } from '@zhin.js/plugin-runtime';
|
|
2
2
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { segmentsToPlainText } from '../../built/segment-contract/text.js';
|
|
8
|
-
import { isMiddlewareIndex, middlewareFeatureId } from '@zhin.js/middleware';
|
|
9
|
-
import { isHandlerIndex, handlerFeatureId } from '../../feature/handler.js';
|
|
10
|
-
import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
|
|
11
|
-
import { Message, createOutboundEnvelope, } from './contracts.js';
|
|
12
|
-
import { loginAssistToken } from './login-assist-host.js';
|
|
3
|
+
import { PermissionHost, permissionHostToken } from '@zhin.js/permission';
|
|
4
|
+
import { CommandExecutionBudget, commandExecutionAdmissionToken } from '@zhin.js/command/internal/execution';
|
|
5
|
+
import { endpointEventGatewayToken, getProcessPeerRegistry, } from '@zhin.js/adapter';
|
|
6
|
+
import { imOperationResourcesToken, } from './contracts.js';
|
|
13
7
|
import { LoginAssist } from '../../built/login-assist.js';
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
|
|
8
|
+
import { RuntimeInteractionCoordinator } from './interaction-runtime.js';
|
|
9
|
+
import { ConversationRuntime } from './conversation-runtime.js';
|
|
10
|
+
import { EndpointRuntime, requireAdapters, } from './endpoint-runtime.js';
|
|
11
|
+
import { MessageBus, messageBusToken, RuntimeMessageEventStream, RuntimeSceneEventStream, } from './message-events.js';
|
|
12
|
+
import { OutboundDeliveryRuntime, failedDeliveryReceipt, } from './outbound-delivery-runtime.js';
|
|
13
|
+
import { InboundRuntime } from './inbound-runtime.js';
|
|
14
|
+
import { messageLocale } from './inbound-spine.js';
|
|
15
|
+
import { InboundDeduper } from './inbound-dedup.js';
|
|
16
|
+
import { createInboundOriginClassifier, OutboundLedger, ledgerScopeOf } from './inbound-origin.js';
|
|
17
|
+
import { RuntimeMessageDiagnostics } from './message-diagnostics.js';
|
|
18
|
+
import { createChatRoleSenderEnricher } from '../../built/roles.js';
|
|
19
|
+
/**
|
|
20
|
+
* Plugin Runtime login-assist port(与出站消息服务并列)。
|
|
21
|
+
* 适配器 waitForInput;Console / stdin 经 listPending + submit 消费。
|
|
22
|
+
*/
|
|
23
|
+
export const loginAssistToken = createToken('zhin.im.login-assist');
|
|
23
24
|
/** @public Stable inbound and outbound IM gateway token for Adapter integrations. */
|
|
24
25
|
export const outboundMessageToken = createToken('zhin.im.outbound-message');
|
|
25
|
-
export const ingressRouteToken = createToken('zhin.im.ingress-route');
|
|
26
|
-
export const messagePreviewLimit = 200;
|
|
27
|
-
class UserInteractionTimeoutError extends Error {
|
|
28
|
-
constructor(message) {
|
|
29
|
-
super(message);
|
|
30
|
-
this.name = 'UserInteractionTimeoutError';
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
class UserInteractionSupersededError extends Error {
|
|
34
|
-
constructor() {
|
|
35
|
-
super('User interaction superseded');
|
|
36
|
-
this.name = 'UserInteractionSupersededError';
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
class UserInteractionDeliveryError extends Error {
|
|
40
|
-
constructor(receipt) {
|
|
41
|
-
super(`User interaction delivery failed: ${receipt.failure?.code ?? receipt.status}`);
|
|
42
|
-
this.name = 'UserInteractionDeliveryError';
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
26
|
export class ImRuntime {
|
|
46
|
-
#
|
|
47
|
-
#
|
|
48
|
-
#
|
|
49
|
-
|
|
50
|
-
|
|
27
|
+
#commandExecution = new CommandExecutionBudget();
|
|
28
|
+
#commandOperation = new AsyncLocalStorage();
|
|
29
|
+
#messageDiagnostics = new RuntimeMessageDiagnostics();
|
|
30
|
+
messageDiagnostics = Object.freeze({
|
|
31
|
+
list: (options) => this.#messageDiagnostics.list(options),
|
|
32
|
+
get: (id) => this.#messageDiagnostics.get(id),
|
|
33
|
+
});
|
|
34
|
+
#messageEventStream = new RuntimeMessageEventStream();
|
|
35
|
+
messageEvents = Object.freeze({
|
|
36
|
+
subscribe: (listener) => this.#messageEventStream.subscribe(listener),
|
|
37
|
+
});
|
|
38
|
+
#sceneEventStream = new RuntimeSceneEventStream();
|
|
39
|
+
/** #996: scene facts (mute, join request, poke, …) as soon as they are stored, for wake-up observers. */
|
|
40
|
+
sceneEvents = Object.freeze({
|
|
41
|
+
subscribe: (listener) => this.#sceneEventStream.subscribe(listener),
|
|
42
|
+
});
|
|
43
|
+
#interactions = new RuntimeInteractionCoordinator(undefined, (message) => this.#conversations.markInteractionAnswer(message));
|
|
44
|
+
#conversations;
|
|
45
|
+
#outbound;
|
|
46
|
+
#inbound;
|
|
47
|
+
endpoints;
|
|
51
48
|
#operationSnapshot = new AsyncLocalStorage();
|
|
52
49
|
#snapshots;
|
|
53
|
-
#inboundClaim;
|
|
54
|
-
#enrichSender;
|
|
55
|
-
conversationEvents;
|
|
56
50
|
constructor(options = {}) {
|
|
57
|
-
this.#
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
51
|
+
this.#conversations = new ConversationRuntime(options.conversationEvents);
|
|
52
|
+
const ledger = new OutboundLedger();
|
|
53
|
+
const deduper = options.inboundDeduper ?? new InboundDeduper();
|
|
54
|
+
const registry = options.peerRegistry ?? getProcessPeerRegistry();
|
|
55
|
+
const originClassifier = createInboundOriginClassifier({
|
|
56
|
+
registry,
|
|
57
|
+
ledger,
|
|
58
|
+
});
|
|
59
|
+
this.#outbound = new OutboundDeliveryRuntime({
|
|
60
|
+
diagnostics: this.#messageDiagnostics,
|
|
61
|
+
ledger: (conversation, receipt, payload) => ledger.record(conversation, receipt, payload),
|
|
62
|
+
record: (request, receipt, canonicalContent) => this.#conversations.recordOutbound(request, receipt, canonicalContent),
|
|
63
|
+
recordUpdate: (request, receipt, revision, canonicalContent) => this.#conversations.recordOutboundUpdate(request, receipt, revision, canonicalContent),
|
|
64
|
+
rememberFallback: (conversation, generation, map) => this.#interactions.rememberFallback(conversation, generation, map),
|
|
65
|
+
publish: (event) => this.#messageEventStream.publish(event),
|
|
66
|
+
prepareButtons: (request, snapshot) => this.#interactions.prepareButtons(request, snapshot),
|
|
67
|
+
}, options.renderer);
|
|
68
|
+
this.#inbound = new InboundRuntime({
|
|
69
|
+
commandExecution: this.#commandExecution,
|
|
70
|
+
runCommandOperation: (controller, operation) => this.#commandOperation.run(controller, operation),
|
|
71
|
+
diagnostics: this.#messageDiagnostics,
|
|
72
|
+
interactions: this.#interactions,
|
|
73
|
+
captureOperation: input => this.endpoints.captureOperation(input),
|
|
74
|
+
createOperationResources: input => {
|
|
75
|
+
const snapshots = this.#snapshots;
|
|
76
|
+
if (!snapshots || !snapshots.owns(input.lease) || !input.lease.active)
|
|
77
|
+
throw new Error('IM operation lease is not active');
|
|
78
|
+
return readLeasedRootResource(snapshots, input.lease, imOperationResourcesToken)?.open({ ...input, snapshots });
|
|
79
|
+
},
|
|
80
|
+
inboundClaim: options.inboundClaim,
|
|
81
|
+
originClassifier,
|
|
82
|
+
deduper,
|
|
83
|
+
registry,
|
|
84
|
+
inboundClaimPending: options.inboundClaimPending,
|
|
85
|
+
resolveReplyTarget: (conversation, id) => ledger.matchById(ledgerScopeOf(conversation), id)?.endpointId,
|
|
86
|
+
enrichSender: options.enrichSender ?? createChatRoleSenderEnricher({ roles: () => undefined }),
|
|
87
|
+
acquire: () => this.#acquire(),
|
|
88
|
+
release: (lease) => this.#release(lease),
|
|
89
|
+
deliver: (request, snapshot) => this.#deliver(request, snapshot),
|
|
90
|
+
recordIncoming: (input, sender) => this.#conversations.recordIncoming(input, sender),
|
|
91
|
+
recordNotice: async (notice) => this.#publishSceneEvent(notice, await this.#conversations.recordNotice(notice)),
|
|
92
|
+
recordRequest: async (request) => this.#publishSceneEvent(request, await this.#conversations.recordRequest(request)),
|
|
93
|
+
markInteractionAnswer: (message) => this.#conversations.markInteractionAnswer(message),
|
|
94
|
+
publish: (event) => this.#messageEventStream.publish(event),
|
|
95
|
+
}, options.commandPrefix);
|
|
96
|
+
this.endpoints = new EndpointRuntime({
|
|
97
|
+
acquire: () => this.#acquire(),
|
|
98
|
+
retain: () => this.#retainSnapshot(),
|
|
99
|
+
release: (lease) => this.#release(lease),
|
|
100
|
+
send: (request, snapshot, execution) => this.#deliver(request, snapshot, execution),
|
|
101
|
+
});
|
|
102
|
+
// ADR 0056 §1: `bot:*` permits read the Bot's own standing through the Adapter index cache;
|
|
103
|
+
// the Bot's role events drop the cached answer of that conversation.
|
|
104
|
+
this.permissionHost.setBotStandingResolver((source, lookup) => this.#botStanding(source, lookup));
|
|
105
|
+
// ADR 0056 §5: execution-time re-checks and due timers read the sender's *current* chat role
|
|
106
|
+
// through the same enricher as inbound messages (the role store is in memory).
|
|
107
|
+
const enrichSender = options.enrichSender ?? createChatRoleSenderEnricher({ roles: () => undefined });
|
|
108
|
+
this.permissionHost.setSenderRoleResolver(source => this.#currentSenderRoles(enrichSender, source));
|
|
109
|
+
this.#sceneEventStream.subscribe(signal => this.#invalidateBotStanding(signal));
|
|
110
|
+
}
|
|
111
|
+
#currentSenderRoles(enrich, source) {
|
|
112
|
+
const value = source && typeof source === 'object' ? source : undefined;
|
|
113
|
+
const conversation = value?.conversation;
|
|
114
|
+
const id = value?.sender?.id;
|
|
115
|
+
if (!conversation || typeof conversation !== 'object' || typeof conversation.endpoint?.id !== 'string' || typeof id !== 'string' || !id)
|
|
116
|
+
return undefined;
|
|
117
|
+
let lease;
|
|
118
|
+
try {
|
|
119
|
+
lease = this.#acquire();
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
const sender = enrich({ id }, conversation, lease.value);
|
|
126
|
+
return Object.freeze({ ...(sender?.chatRole ? { chatRole: sender.chatRole } : {}),
|
|
127
|
+
...(sender?.chatRole && sender.chatRoleLevels ? { chatRoleLevels: sender.chatRoleLevels } : {}) });
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
this.#release(lease);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
async #botStanding(source, lookup) {
|
|
134
|
+
const conversation = source && typeof source === 'object' ? source.conversation : undefined;
|
|
135
|
+
if (!conversation || typeof conversation !== 'object' || typeof conversation.endpoint?.id !== 'string' || typeof conversation.id !== 'string')
|
|
136
|
+
return undefined;
|
|
137
|
+
const lease = this.#acquire();
|
|
138
|
+
try {
|
|
139
|
+
const adapters = requireAdapters(lease.value);
|
|
140
|
+
if (typeof adapters.selfStanding !== 'function')
|
|
141
|
+
return undefined;
|
|
142
|
+
return await adapters.selfStanding(conversation.endpoint.id, conversation, lookup);
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
return undefined;
|
|
146
|
+
}
|
|
147
|
+
finally {
|
|
148
|
+
this.#release(lease);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
#invalidateBotStanding(signal) {
|
|
152
|
+
const event = signal.event;
|
|
153
|
+
const conversation = event.conversation;
|
|
154
|
+
if (!conversation || (event.type !== 'member.role_changed' && event.type !== 'member.left' && event.type !== 'member.joined'))
|
|
155
|
+
return;
|
|
156
|
+
const self = event.member?.id !== undefined && signal.selfIds.includes(String(event.member.id));
|
|
157
|
+
if (event.type !== 'member.role_changed' && !self)
|
|
158
|
+
return;
|
|
159
|
+
try {
|
|
160
|
+
const lease = this.#acquire();
|
|
161
|
+
try {
|
|
162
|
+
requireAdapters(lease.value).invalidateSelfStanding?.(conversation.endpoint.id, conversation);
|
|
163
|
+
}
|
|
164
|
+
finally {
|
|
165
|
+
this.#release(lease);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
catch { /* no attached generation: nothing cached */ }
|
|
64
169
|
}
|
|
65
170
|
/** Process composition replaces the bootstrap memory store after required DB activation. */
|
|
66
171
|
replaceConversationEventStore(store) {
|
|
67
|
-
this.
|
|
172
|
+
this.#conversations.replaceStore(store);
|
|
173
|
+
}
|
|
174
|
+
get conversationEventReader() {
|
|
175
|
+
return this.#conversations.reader;
|
|
68
176
|
}
|
|
69
177
|
/** Pins all nested IM operations to the snapshot current at operation ingress. */
|
|
70
178
|
async runWithSnapshotView(operation) {
|
|
@@ -85,29 +193,18 @@ export class ImRuntime {
|
|
|
85
193
|
if (!this.#snapshots?.owns(lease) || !lease.active) {
|
|
86
194
|
return Object.freeze({ status: 'expired', code: 'generation_lease_expired' });
|
|
87
195
|
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
return Object.freeze({ status: 'resolved', reference, value: local });
|
|
92
|
-
}
|
|
196
|
+
const local = await this.#conversations.resolveLocal(reference);
|
|
197
|
+
if (local)
|
|
198
|
+
return local;
|
|
93
199
|
context.signal.throwIfAborted();
|
|
94
200
|
const conversation = reference.kind === 'message' ? reference.message.conversation : reference.conversation;
|
|
95
201
|
return requireAdapters(lease.value).resolveContent(conversation.endpoint.id, reference, context);
|
|
96
202
|
}
|
|
97
203
|
async readConversationContext(conversation, consumer, throughSequence, limit = 50, excludeMessageId) {
|
|
98
|
-
|
|
99
|
-
throw new TypeError('Conversation context throughSequence must be a non-negative integer');
|
|
100
|
-
}
|
|
101
|
-
const cursor = await this.conversationEvents.getCursor(consumer, conversation);
|
|
102
|
-
const events = await this.conversationEvents.listBetween(conversation, cursor, throughSequence, limit);
|
|
103
|
-
const blocks = aggregateConversationContext(events, excludeMessageId);
|
|
104
|
-
return Object.freeze({
|
|
105
|
-
blocks: Object.freeze(blocks),
|
|
106
|
-
cursor: Math.max(cursor, throughSequence),
|
|
107
|
-
});
|
|
204
|
+
return this.#conversations.readContext(conversation, consumer, throughSequence, limit, excludeMessageId);
|
|
108
205
|
}
|
|
109
206
|
async commitConversationContext(conversation, consumer, cursor) {
|
|
110
|
-
await this.
|
|
207
|
+
await this.#conversations.commitContext(conversation, consumer, cursor);
|
|
111
208
|
}
|
|
112
209
|
attach(snapshots) {
|
|
113
210
|
if (this.#snapshots && this.#snapshots !== snapshots) {
|
|
@@ -115,7 +212,7 @@ export class ImRuntime {
|
|
|
115
212
|
}
|
|
116
213
|
this.#snapshots = snapshots;
|
|
117
214
|
}
|
|
118
|
-
permissionHost =
|
|
215
|
+
permissionHost = new PermissionHost();
|
|
119
216
|
messageBus = new MessageBus();
|
|
120
217
|
loginAssist = new LoginAssist();
|
|
121
218
|
install(resources) {
|
|
@@ -123,16 +220,46 @@ export class ImRuntime {
|
|
|
123
220
|
resources.provide(endpointEventGatewayToken, this.endpointEvents);
|
|
124
221
|
resources.provide(loginAssistToken, this.loginAssist);
|
|
125
222
|
resources.provide(permissionHostToken, this.permissionHost);
|
|
223
|
+
resources.provide(commandExecutionAdmissionToken, this.#commandExecution.admission);
|
|
126
224
|
resources.provide(messageBusToken, this.messageBus);
|
|
127
225
|
}
|
|
128
226
|
/** The sole Adapter ingress, also installed as endpointEventGatewayToken. */
|
|
129
227
|
endpointEvents = (() => {
|
|
130
228
|
const self = this;
|
|
229
|
+
const resolveLocale = async (endpoint, senderId) => {
|
|
230
|
+
const lease = self.#acquire();
|
|
231
|
+
try {
|
|
232
|
+
const adapters = requireAdapters(lease.value);
|
|
233
|
+
// Trust the current index's canonical Endpoint identity, never a protocol payload.
|
|
234
|
+
adapters.owner(endpoint.id);
|
|
235
|
+
return await messageLocale(lease.value, {
|
|
236
|
+
endpoint: { id: endpoint.id, adapter: adapters.clientAdapter(endpoint.id) },
|
|
237
|
+
}, senderId);
|
|
238
|
+
}
|
|
239
|
+
finally {
|
|
240
|
+
self.#release(lease);
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
const runWithReceipt = (receive, gate) => self.runWithSnapshotView(async () => {
|
|
244
|
+
const lease = self.#acquire();
|
|
245
|
+
return receive(Object.freeze({ receive: event => {
|
|
246
|
+
if (!lease.active)
|
|
247
|
+
throw new Error('Endpoint receipt scope has ended');
|
|
248
|
+
lease.stopSignal.throwIfAborted();
|
|
249
|
+
return self.#operationSnapshot.run(lease, () => self.#inbound.receive(event, gate));
|
|
250
|
+
} }));
|
|
251
|
+
});
|
|
131
252
|
const gateway = {
|
|
132
|
-
|
|
253
|
+
run: runWithReceipt,
|
|
254
|
+
receive: event => self.runWithSnapshotView(() => self.#inbound.receive(event)),
|
|
255
|
+
resolveLocale,
|
|
133
256
|
[generationAdmissionBinder](gate) {
|
|
257
|
+
const owner = new OwnerOperation(gate, 'Endpoint ingress');
|
|
258
|
+
const run = (receive) => owner.run(() => runWithReceipt(receive, gate));
|
|
134
259
|
return Object.freeze({
|
|
135
|
-
|
|
260
|
+
run,
|
|
261
|
+
receive: event => run(() => self.#inbound.receive(event, gate)),
|
|
262
|
+
resolveLocale: (endpoint, senderId) => run(() => resolveLocale(endpoint, senderId)),
|
|
136
263
|
});
|
|
137
264
|
},
|
|
138
265
|
};
|
|
@@ -141,8 +268,8 @@ export class ImRuntime {
|
|
|
141
268
|
[generationAdmissionBinder](gate) {
|
|
142
269
|
const gateway = {
|
|
143
270
|
send: async (request) => gate.enter(() => this.send(request))
|
|
144
|
-
??
|
|
145
|
-
registerInteractiveHandler: (prefix, handler) => this.#
|
|
271
|
+
?? failedDeliveryReceipt('generation_not_admitted'),
|
|
272
|
+
registerInteractiveHandler: (prefix, handler) => this.#interactions.register(prefix, handler, gate),
|
|
146
273
|
};
|
|
147
274
|
return Object.freeze(gateway);
|
|
148
275
|
}
|
|
@@ -151,304 +278,23 @@ export class ImRuntime {
|
|
|
151
278
|
* 在 Command dispatch 之前路由:action 段 / 数字回跳 / 指令预填 payload。
|
|
152
279
|
*/
|
|
153
280
|
registerInteractiveHandler(prefix, handler) {
|
|
154
|
-
return this.#
|
|
155
|
-
}
|
|
156
|
-
#registerInteractiveHandler(prefix, handler, admission) {
|
|
157
|
-
const entry = Object.freeze({ prefix, handler, admission });
|
|
158
|
-
this.#interactiveHandlers.push(entry);
|
|
159
|
-
return () => {
|
|
160
|
-
const index = this.#interactiveHandlers.indexOf(entry);
|
|
161
|
-
if (index >= 0)
|
|
162
|
-
this.#interactiveHandlers.splice(index, 1);
|
|
163
|
-
};
|
|
164
|
-
}
|
|
165
|
-
// ==========================================================================
|
|
166
|
-
// User interaction claim — 命令/Agent 对话式交互
|
|
167
|
-
// ==========================================================================
|
|
168
|
-
#interactionConversationKey(message, subjectId = message.sender?.id ?? '') {
|
|
169
|
-
return `${conversationRefKey(message.conversation)}:${subjectId}`;
|
|
170
|
-
}
|
|
171
|
-
#resolveInteractionClaim(message) {
|
|
172
|
-
const key = this.#interactionConversationKey(message);
|
|
173
|
-
const claim = this.#interactionClaims.get(key);
|
|
174
|
-
if (!claim)
|
|
175
|
-
return false;
|
|
176
|
-
claim.resolve(resolveRuntimeInteractivePayload(message) ?? message.content);
|
|
177
|
-
return true;
|
|
178
|
-
}
|
|
179
|
-
#claimNextMessage(message, timeout, timeoutText, signal, subjectId) {
|
|
180
|
-
return new Promise((resolve, reject) => {
|
|
181
|
-
if (signal?.aborted) {
|
|
182
|
-
reject(abortError(signal, timeoutText));
|
|
183
|
-
return;
|
|
184
|
-
}
|
|
185
|
-
const key = this.#interactionConversationKey(message, subjectId);
|
|
186
|
-
const existing = this.#interactionClaims.get(key);
|
|
187
|
-
if (existing) {
|
|
188
|
-
clearTimeout(existing.timer);
|
|
189
|
-
existing.reject(new UserInteractionSupersededError());
|
|
190
|
-
}
|
|
191
|
-
const timer = setTimeout(() => {
|
|
192
|
-
settle(undefined, new UserInteractionTimeoutError(timeoutText));
|
|
193
|
-
}, timeout);
|
|
194
|
-
const onAbort = () => settle(undefined, abortError(signal, timeoutText));
|
|
195
|
-
signal?.addEventListener('abort', onAbort, { once: true });
|
|
196
|
-
const settle = (value, error) => {
|
|
197
|
-
if (this.#interactionClaims.get(key) !== claim)
|
|
198
|
-
return;
|
|
199
|
-
this.#interactionClaims.delete(key);
|
|
200
|
-
clearTimeout(timer);
|
|
201
|
-
signal?.removeEventListener('abort', onAbort);
|
|
202
|
-
if (value !== undefined)
|
|
203
|
-
resolve(value);
|
|
204
|
-
else
|
|
205
|
-
reject(error ?? new UserInteractionTimeoutError(timeoutText));
|
|
206
|
-
};
|
|
207
|
-
const claim = {
|
|
208
|
-
resolve: (raw) => settle(raw),
|
|
209
|
-
reject: (error) => settle(undefined, error),
|
|
210
|
-
timer,
|
|
211
|
-
};
|
|
212
|
-
this.#interactionClaims.set(key, claim);
|
|
213
|
-
});
|
|
214
|
-
}
|
|
215
|
-
#buildUserInteraction(message, subjectId) {
|
|
216
|
-
const DEFAULT_TIMEOUT = 3 * 60 * 1000;
|
|
217
|
-
const DEFAULT_TIMEOUT_TEXT = '输入超时';
|
|
218
|
-
const claim = (timeout, timeoutText, signal) => this.#claimNextMessage(message, timeout, timeoutText, signal, subjectId);
|
|
219
|
-
const reply = async (view) => {
|
|
220
|
-
const receipt = await message.$reply(renderUserInteraction(view));
|
|
221
|
-
if (receipt.status !== 'sent')
|
|
222
|
-
throw new UserInteractionDeliveryError(receipt);
|
|
223
|
-
};
|
|
224
|
-
const ask = async (request, progress) => {
|
|
225
|
-
assertUserInteractionRequest(request);
|
|
226
|
-
const timeout = request.timeout ?? DEFAULT_TIMEOUT;
|
|
227
|
-
const timeoutText = request.timeoutText ?? DEFAULT_TIMEOUT_TEXT;
|
|
228
|
-
const deadline = Date.now() + timeout;
|
|
229
|
-
const view = projectUserInteraction(request, progress);
|
|
230
|
-
await reply(view);
|
|
231
|
-
while (true) {
|
|
232
|
-
try {
|
|
233
|
-
const raw = await claim(Math.max(1, deadline - Date.now()), timeoutText, request.signal);
|
|
234
|
-
const result = parseUserInteractionAnswer(request, raw);
|
|
235
|
-
if (result.ok)
|
|
236
|
-
return result.value;
|
|
237
|
-
await reply({
|
|
238
|
-
...view,
|
|
239
|
-
tip: [request.invalidText ?? result.message, view.tip].filter(Boolean).join('\n'),
|
|
240
|
-
});
|
|
241
|
-
}
|
|
242
|
-
catch (error) {
|
|
243
|
-
if (error instanceof UserInteractionTimeoutError && 'default' in request && request.default !== undefined) {
|
|
244
|
-
return request.default;
|
|
245
|
-
}
|
|
246
|
-
if (error instanceof UserInteractionTimeoutError) {
|
|
247
|
-
await reply({ title: '交互已结束', description: error.message });
|
|
248
|
-
}
|
|
249
|
-
throw error;
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
};
|
|
253
|
-
const sequence = async (definition) => {
|
|
254
|
-
if (!definition.title.trim())
|
|
255
|
-
throw new TypeError('User interaction sequence title must not be empty');
|
|
256
|
-
const ids = new Set();
|
|
257
|
-
for (const step of definition.steps) {
|
|
258
|
-
if (!step.id.trim())
|
|
259
|
-
throw new TypeError('User interaction sequence step id must not be empty');
|
|
260
|
-
if (ids.has(step.id))
|
|
261
|
-
throw new TypeError(`Duplicate user interaction sequence step id: ${step.id}`);
|
|
262
|
-
ids.add(step.id);
|
|
263
|
-
}
|
|
264
|
-
const result = {};
|
|
265
|
-
for (let index = 0; index < definition.steps.length; index += 1) {
|
|
266
|
-
const step = definition.steps[index];
|
|
267
|
-
const request = {
|
|
268
|
-
...step,
|
|
269
|
-
timeout: step.timeout ?? definition.timeout,
|
|
270
|
-
timeoutText: step.timeoutText ?? definition.timeoutText,
|
|
271
|
-
invalidText: step.invalidText ?? definition.invalidText,
|
|
272
|
-
signal: step.signal ?? definition.signal,
|
|
273
|
-
};
|
|
274
|
-
result[step.id] = await ask(request, {
|
|
275
|
-
title: definition.title,
|
|
276
|
-
description: definition.description,
|
|
277
|
-
tip: definition.tip,
|
|
278
|
-
index: index + 1,
|
|
279
|
-
total: definition.steps.length,
|
|
280
|
-
});
|
|
281
|
-
}
|
|
282
|
-
return Object.freeze(result);
|
|
283
|
-
};
|
|
284
|
-
return Object.freeze({ ask, sequence });
|
|
281
|
+
return this.#interactions.register(prefix, handler);
|
|
285
282
|
}
|
|
286
283
|
/**
|
|
287
284
|
* User interaction bound to this conversation.
|
|
288
285
|
* `bind.subjectId` waits for that user (e.g. master) instead of the message sender.
|
|
289
286
|
*/
|
|
290
287
|
createInteraction(message, bind) {
|
|
291
|
-
|
|
292
|
-
if (bind && !subjectId)
|
|
293
|
-
return undefined;
|
|
294
|
-
if (typeof message.$reply !== 'function' || !message.conversation)
|
|
295
|
-
return undefined;
|
|
296
|
-
return this.#buildUserInteraction(message, subjectId);
|
|
297
|
-
}
|
|
298
|
-
#createInteractionForSource(source) {
|
|
299
|
-
if (!source || typeof source !== 'object')
|
|
300
|
-
return undefined;
|
|
301
|
-
const msg = source;
|
|
302
|
-
if (typeof msg.$reply !== 'function' || !msg.conversation)
|
|
303
|
-
return undefined;
|
|
304
|
-
return this.#buildUserInteraction(msg);
|
|
305
|
-
}
|
|
306
|
-
/**
|
|
307
|
-
* 订阅消息事件(入站 dispatch 完成后 / 出站发送成功后回调)。
|
|
308
|
-
* 返回注销函数。listener 抛错不会阻断消息链路。
|
|
309
|
-
*/
|
|
310
|
-
onMessage(listener) {
|
|
311
|
-
this.#messageListeners.add(listener);
|
|
312
|
-
return () => { this.#messageListeners.delete(listener); };
|
|
288
|
+
return this.#inbound.createInteraction(message, bind);
|
|
313
289
|
}
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
listener(event);
|
|
318
|
-
}
|
|
319
|
-
catch {
|
|
320
|
-
// listener 异常不得影响消息收发
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
async #receive(source, admission) {
|
|
325
|
-
const input = source.payload;
|
|
326
|
-
const lease = this.#acquire();
|
|
327
|
-
let active = true;
|
|
328
|
-
try {
|
|
329
|
-
const conversation = input.conversation;
|
|
330
|
-
const adapter = conversation.endpoint.id;
|
|
331
|
-
const requester = requireAdapters(lease.value).owner(adapter);
|
|
332
|
-
logger.debug(formatCompact({
|
|
333
|
-
op: 'receive',
|
|
334
|
-
conv: formatConversationLog(conversation),
|
|
335
|
-
sender: `${input.sender?.name || 'undefined'}(${input.sender?.id || 'undefined'})`,
|
|
336
|
-
preview: truncatePreview(input.content),
|
|
337
|
-
}));
|
|
338
|
-
const enrichedSender = this.#enrichSender
|
|
339
|
-
? this.#enrichSender(input.sender, conversation, lease.value)
|
|
340
|
-
: input.sender;
|
|
341
|
-
const message = new Message(conversation, input.content, lease.value.generation, (content, replyRequester = requester, targetConversation) => {
|
|
342
|
-
if (!active)
|
|
343
|
-
throw new Error('Message reply scope has ended');
|
|
344
|
-
const effectiveConversation = targetConversation
|
|
345
|
-
? { endpoint: conversation.endpoint, ...targetConversation }
|
|
346
|
-
: conversation;
|
|
347
|
-
return this.#sendWithSnapshot({
|
|
348
|
-
conversation: effectiveConversation,
|
|
349
|
-
requester: replyRequester,
|
|
350
|
-
content,
|
|
351
|
-
incoming: {
|
|
352
|
-
sender: enrichedSender,
|
|
353
|
-
content: input.content,
|
|
354
|
-
segments: input.segments,
|
|
355
|
-
messageId: input.message?.id,
|
|
356
|
-
timestamp: Date.now(),
|
|
357
|
-
endpointId: input.endpointId,
|
|
358
|
-
mentioned: input.mentioned,
|
|
359
|
-
},
|
|
360
|
-
}, lease.value);
|
|
361
|
-
}, enrichedSender, Object.freeze({ ...input.metadata }), input.segments ? Object.freeze([...input.segments]) : undefined, input.message, input.endpointId, input.mentioned, input.replyTo, () => {
|
|
362
|
-
if (!active)
|
|
363
|
-
throw new Error('Message Client scope has ended');
|
|
364
|
-
return source.client;
|
|
365
|
-
}, source.endpoint.adapter);
|
|
366
|
-
let conversationSequence;
|
|
367
|
-
if (input.message?.id) {
|
|
368
|
-
const appended = await this.conversationEvents.append(Object.freeze({
|
|
369
|
-
eventId: `message:${messageRefKey(input.message)}`,
|
|
370
|
-
conversation,
|
|
371
|
-
timestamp: Date.now(),
|
|
372
|
-
type: 'message.created',
|
|
373
|
-
message: Object.freeze({
|
|
374
|
-
ref: input.message,
|
|
375
|
-
...(enrichedSender ? { actor: Object.freeze({
|
|
376
|
-
id: enrichedSender.id,
|
|
377
|
-
...(enrichedSender.name ? { displayName: enrichedSender.name } : {}),
|
|
378
|
-
}) } : {}),
|
|
379
|
-
segments: Object.freeze(input.segments?.length
|
|
380
|
-
? [...input.segments]
|
|
381
|
-
: [{ type: 'text', data: { text: input.content } }]),
|
|
382
|
-
timestamp: Date.now(),
|
|
383
|
-
...(input.replyTo ? { replyTo: Object.freeze({ conversation, id: input.replyTo.id }) } : {}),
|
|
384
|
-
}),
|
|
385
|
-
}));
|
|
386
|
-
conversationSequence = appended.sequence;
|
|
387
|
-
}
|
|
388
|
-
let result = Object.freeze({ matched: false });
|
|
389
|
-
const claimed = await this.#inboundClaim?.(message) === true;
|
|
390
|
-
if (claimed) {
|
|
391
|
-
result = Object.freeze({ matched: true, command: 'interaction', owner: requester });
|
|
392
|
-
}
|
|
393
|
-
else if (this.#resolveInteractionClaim(message)) {
|
|
394
|
-
result = Object.freeze({ matched: true, command: 'interaction', owner: requester });
|
|
395
|
-
}
|
|
396
|
-
else {
|
|
397
|
-
const interactionFactory = (source) => this.#createInteractionForSource(source);
|
|
398
|
-
await runMiddleware(lease.value, message, async () => {
|
|
399
|
-
const ingressRoute = resolveIngressRoute(lease.value);
|
|
400
|
-
const preRouted = await ingressRoute?.preRoute?.(message, lease, requester, conversationSequence) === true;
|
|
401
|
-
if (preRouted) {
|
|
402
|
-
result = Object.freeze({ matched: true, command: 'pre-route', owner: requester });
|
|
403
|
-
return;
|
|
404
|
-
}
|
|
405
|
-
if (ingressRoute?.shouldRouteBeforeDispatch?.(message) === true) {
|
|
406
|
-
const handled = await ingressRoute.route(message, lease, requester, conversationSequence);
|
|
407
|
-
if (handled) {
|
|
408
|
-
result = Object.freeze({ matched: true, command: 'ai', owner: requester });
|
|
409
|
-
return;
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
|
-
await this.#runHandlers(lease.value, 'message.receive', [
|
|
413
|
-
withEndpointEventPayload(source, message),
|
|
414
|
-
]);
|
|
415
|
-
result = await this.#dispatchInteractive(message, requester, admission)
|
|
416
|
-
?? await this.#dispatcher.dispatch(message, lease.value, interactionFactory);
|
|
417
|
-
if (!result.matched && ingressRoute) {
|
|
418
|
-
logger.debug(formatCompact({ op: 'unmatched', conv: formatConversationLog(conversation) }));
|
|
419
|
-
const handled = await ingressRoute.route(message, lease, requester, conversationSequence);
|
|
420
|
-
if (handled) {
|
|
421
|
-
result = Object.freeze({ matched: true, command: 'ai', owner: requester });
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
}, 'inbound');
|
|
425
|
-
}
|
|
426
|
-
if (result.matched) {
|
|
427
|
-
logger.debug(formatCompact({
|
|
428
|
-
op: 'dispatched',
|
|
429
|
-
conv: formatConversationLog(conversation),
|
|
430
|
-
command: result.command,
|
|
431
|
-
}));
|
|
432
|
-
}
|
|
433
|
-
this.#emitMessage({
|
|
434
|
-
direction: 'inbound',
|
|
435
|
-
conversation,
|
|
436
|
-
...(input.sender !== undefined ? { sender: input.sender } : {}),
|
|
437
|
-
contentPreview: previewText(input.content),
|
|
438
|
-
...(input.message?.id ? { messageId: input.message.id } : {}),
|
|
439
|
-
timestamp: Date.now(),
|
|
440
|
-
});
|
|
441
|
-
return result;
|
|
442
|
-
}
|
|
443
|
-
finally {
|
|
444
|
-
active = false;
|
|
445
|
-
this.#release(lease);
|
|
446
|
-
}
|
|
290
|
+
/** Reads a prompt within the caller's current generation lease; answering uses the original IM ingress. */
|
|
291
|
+
readPendingInteraction(conversation, subjectId, generation) {
|
|
292
|
+
return this.#interactions.readPendingInteraction(conversation, subjectId, generation);
|
|
447
293
|
}
|
|
448
294
|
async send(request) {
|
|
449
295
|
const lease = this.#acquire();
|
|
450
296
|
try {
|
|
451
|
-
return await this.#
|
|
297
|
+
return await this.#deliver(request, lease.value);
|
|
452
298
|
}
|
|
453
299
|
finally {
|
|
454
300
|
this.#release(lease);
|
|
@@ -459,169 +305,7 @@ export class ImRuntime {
|
|
|
459
305
|
if (!this.#snapshots?.owns(lease) || !lease.active) {
|
|
460
306
|
throw new Error('Outbound message generation lease expired');
|
|
461
307
|
}
|
|
462
|
-
return this.#
|
|
463
|
-
}
|
|
464
|
-
async #receiveNotice(source) {
|
|
465
|
-
const notice = source.payload;
|
|
466
|
-
const event = conversationEventFromNotice(notice);
|
|
467
|
-
if (event)
|
|
468
|
-
await this.conversationEvents.append(event);
|
|
469
|
-
await this.#receiveSideEvent(withEndpointEventPayload(source, notice));
|
|
470
|
-
}
|
|
471
|
-
async #receiveRequest(source) {
|
|
472
|
-
await this.#withRequestActionScope(source.payload, async (scoped) => {
|
|
473
|
-
await this.#receiveSideEvent(withEndpointEventPayload(source, scoped));
|
|
474
|
-
});
|
|
475
|
-
}
|
|
476
|
-
async #withRequestActionScope(request, dispatch) {
|
|
477
|
-
let active = true;
|
|
478
|
-
const actions = new Set();
|
|
479
|
-
const run = (action) => {
|
|
480
|
-
if (!active)
|
|
481
|
-
throw new Error('Request action port expired with its generation operation');
|
|
482
|
-
const operation = Promise.resolve().then(action);
|
|
483
|
-
actions.add(operation);
|
|
484
|
-
void operation.then(() => actions.delete(operation), () => actions.delete(operation));
|
|
485
|
-
return operation;
|
|
486
|
-
};
|
|
487
|
-
const scoped = Object.assign(Object.create(Object.getPrototypeOf(request)), request, {
|
|
488
|
-
$approve: async (remark) => run(() => request.$approve(remark)),
|
|
489
|
-
$reject: async (reason) => run(() => request.$reject(reason)),
|
|
490
|
-
});
|
|
491
|
-
try {
|
|
492
|
-
await dispatch(scoped);
|
|
493
|
-
}
|
|
494
|
-
finally {
|
|
495
|
-
active = false;
|
|
496
|
-
await Promise.allSettled([...actions]);
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
async #receiveSystem(source) {
|
|
500
|
-
await this.#receiveSideEvent(source);
|
|
501
|
-
}
|
|
502
|
-
async #receiveSideEvent(event) {
|
|
503
|
-
const lease = this.#acquire();
|
|
504
|
-
try {
|
|
505
|
-
await this.#runHandlers(lease.value, event.name, [event]);
|
|
506
|
-
}
|
|
507
|
-
finally {
|
|
508
|
-
this.#release(lease);
|
|
509
|
-
}
|
|
510
|
-
}
|
|
511
|
-
async receiveEndpointEvent(event, admission) {
|
|
512
|
-
switch (event.name) {
|
|
513
|
-
case 'message.receive':
|
|
514
|
-
return this.#receive(event, admission);
|
|
515
|
-
case 'notice.receive':
|
|
516
|
-
return this.#receiveNotice(event);
|
|
517
|
-
case 'request.receive':
|
|
518
|
-
return this.#receiveRequest(event);
|
|
519
|
-
case 'system.receive':
|
|
520
|
-
return this.#receiveSystem(event);
|
|
521
|
-
default: {
|
|
522
|
-
const lease = this.#acquire();
|
|
523
|
-
try {
|
|
524
|
-
await this.#runHandlers(lease.value, event.name, [event]);
|
|
525
|
-
return undefined;
|
|
526
|
-
}
|
|
527
|
-
finally {
|
|
528
|
-
this.#release(lease);
|
|
529
|
-
}
|
|
530
|
-
}
|
|
531
|
-
}
|
|
532
|
-
}
|
|
533
|
-
/**
|
|
534
|
-
* User interaction bound to a side-event scene (private/group channel derived from
|
|
535
|
-
* `$scene_type` / `$scene_id`). Returns undefined when outbound is unavailable.
|
|
536
|
-
*/
|
|
537
|
-
#createInteractionForSideEvent(payload, snapshot) {
|
|
538
|
-
const adapter = String(payload.$adapter);
|
|
539
|
-
const endpointKey = String(payload.$endpoint);
|
|
540
|
-
if (!adapter || !endpointKey)
|
|
541
|
-
return undefined;
|
|
542
|
-
const channel = sideEventSendChannel(payload);
|
|
543
|
-
const conversation = Object.freeze({
|
|
544
|
-
endpoint: Object.freeze({ adapter, id: endpointKey }),
|
|
545
|
-
kind: channel.type,
|
|
546
|
-
id: channel.id || endpointKey,
|
|
547
|
-
});
|
|
548
|
-
const requester = snapshot.root;
|
|
549
|
-
const source = Object.freeze({
|
|
550
|
-
conversation,
|
|
551
|
-
...(payload.$actor?.id
|
|
552
|
-
? { sender: Object.freeze({ id: payload.$actor.id }) }
|
|
553
|
-
: {}),
|
|
554
|
-
$reply: (content) => this.#sendWithSnapshot({
|
|
555
|
-
conversation,
|
|
556
|
-
requester,
|
|
557
|
-
content,
|
|
558
|
-
}, snapshot),
|
|
559
|
-
});
|
|
560
|
-
return this.#buildUserInteraction(source);
|
|
561
|
-
}
|
|
562
|
-
async #runHandlers(snapshot, event, args) {
|
|
563
|
-
const index = handlers(snapshot);
|
|
564
|
-
if (!index)
|
|
565
|
-
return;
|
|
566
|
-
const options = {
|
|
567
|
-
resolveInteraction: (name, interactionArgs) => {
|
|
568
|
-
const context = interactionArgs[0];
|
|
569
|
-
const payload = context?.payload;
|
|
570
|
-
if (name === 'message.receive' && payload instanceof Message) {
|
|
571
|
-
return this.createInteraction(payload);
|
|
572
|
-
}
|
|
573
|
-
if (name === 'notice.receive'
|
|
574
|
-
|| name === 'request.receive'
|
|
575
|
-
|| name === 'system.receive') {
|
|
576
|
-
return this.#createInteractionForSideEvent(payload, snapshot);
|
|
577
|
-
}
|
|
578
|
-
return undefined;
|
|
579
|
-
},
|
|
580
|
-
};
|
|
581
|
-
await index.dispatch(event, args, options);
|
|
582
|
-
}
|
|
583
|
-
/** Console `endpoint.list` — empty until Adapter Feature projection is ready. */
|
|
584
|
-
listEndpoints() {
|
|
585
|
-
try {
|
|
586
|
-
const lease = this.#acquire();
|
|
587
|
-
try {
|
|
588
|
-
return requireAdapters(lease.value).describe().map((row) => Object.freeze({
|
|
589
|
-
id: String(row.id),
|
|
590
|
-
name: row.name,
|
|
591
|
-
// adapter 列显示平台类型(owner 包名去 scope/adapter- 前缀),不是 slot localName
|
|
592
|
-
adapter: adapterTypeName(lease.value.tree.get(row.owner)?.packageName) ?? row.name,
|
|
593
|
-
owner: row.owner,
|
|
594
|
-
connected: row.connected,
|
|
595
|
-
status: row.status,
|
|
596
|
-
phase: row.phase,
|
|
597
|
-
operations: row.operations,
|
|
598
|
-
managementCapabilities: row.managementCapabilities,
|
|
599
|
-
}));
|
|
600
|
-
}
|
|
601
|
-
finally {
|
|
602
|
-
this.#release(lease);
|
|
603
|
-
}
|
|
604
|
-
}
|
|
605
|
-
catch {
|
|
606
|
-
return Object.freeze([]);
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
/** Exact operation capabilities for one concrete live Endpoint. */
|
|
610
|
-
endpointCapabilities(input) {
|
|
611
|
-
try {
|
|
612
|
-
const lease = this.#acquire();
|
|
613
|
-
try {
|
|
614
|
-
const index = requireAdapters(lease.value);
|
|
615
|
-
const id = index.resolve(input.adapter, input.endpointKey);
|
|
616
|
-
return id ? index.capabilities(id) : undefined;
|
|
617
|
-
}
|
|
618
|
-
finally {
|
|
619
|
-
this.#release(lease);
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
catch {
|
|
623
|
-
return undefined;
|
|
624
|
-
}
|
|
308
|
+
return this.#deliver(request, lease.value);
|
|
625
309
|
}
|
|
626
310
|
/**
|
|
627
311
|
* Console `GET /api/stats` 同源计数:非 root 插件节点 + AdapterIndex endpoints。
|
|
@@ -653,211 +337,31 @@ export class ImRuntime {
|
|
|
653
337
|
});
|
|
654
338
|
}
|
|
655
339
|
}
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
const id = index.resolve(adapter, endpointKey);
|
|
662
|
-
if (!id)
|
|
663
|
-
return null;
|
|
664
|
-
const row = index.describe().find((item) => item.id === id);
|
|
665
|
-
if (!row)
|
|
666
|
-
return null;
|
|
667
|
-
// adapter 与 listEndpoints 对齐:平台类型(owner 包名去 scope/adapter- 前缀),
|
|
668
|
-
// 不是 live name(如 ICQQ uin)。此前误写 row.name 导致 endpoint.info 与 list 不一致。
|
|
669
|
-
return Object.freeze({
|
|
670
|
-
name: row.name,
|
|
671
|
-
adapter: adapterTypeName(lease.value.tree.get(row.owner)?.packageName) ?? row.name,
|
|
672
|
-
connected: row.connected,
|
|
673
|
-
status: row.status,
|
|
674
|
-
phase: row.phase,
|
|
675
|
-
operations: row.operations,
|
|
676
|
-
managementCapabilities: row.managementCapabilities,
|
|
677
|
-
});
|
|
678
|
-
}
|
|
679
|
-
finally {
|
|
680
|
-
this.#release(lease);
|
|
681
|
-
}
|
|
682
|
-
}
|
|
683
|
-
catch {
|
|
684
|
-
return null;
|
|
685
|
-
}
|
|
686
|
-
}
|
|
687
|
-
async sendEndpointMessage(input) {
|
|
688
|
-
const lease = this.#acquire();
|
|
689
|
-
try {
|
|
690
|
-
const index = requireAdapters(lease.value);
|
|
691
|
-
const resolved = index.resolve(input.adapter, input.endpointKey);
|
|
692
|
-
if (!resolved)
|
|
693
|
-
throw new Error('endpoint not found');
|
|
694
|
-
const requester = index.owner(resolved);
|
|
695
|
-
const conversation = {
|
|
696
|
-
endpoint: { id: String(resolved), adapter: String(requester) },
|
|
697
|
-
...input.conversation,
|
|
698
|
-
};
|
|
699
|
-
const content = normalizeConsoleContent(input.content);
|
|
700
|
-
const result = await this.#sendWithSnapshot({
|
|
701
|
-
conversation,
|
|
702
|
-
requester,
|
|
703
|
-
content,
|
|
704
|
-
}, lease.value);
|
|
705
|
-
return { messageId: result.message?.id ?? '' };
|
|
706
|
-
}
|
|
707
|
-
finally {
|
|
708
|
-
this.#release(lease);
|
|
709
|
-
}
|
|
710
|
-
}
|
|
711
|
-
/** Activity-feedback: add a message reaction when the live Endpoint supports it. */
|
|
712
|
-
async addEndpointReaction(input) {
|
|
713
|
-
return this.#withEndpointControl(input.adapter, input.endpointKey, 'reaction', (control) => control.addReaction?.(input.message, input.emoji, {
|
|
714
|
-
sceneType: input.sceneType,
|
|
715
|
-
channelId: input.channelId,
|
|
716
|
-
}) ?? null, null);
|
|
717
|
-
}
|
|
718
|
-
async removeEndpointReaction(input) {
|
|
719
|
-
await this.#withEndpointControl(input.adapter, input.endpointKey, 'reaction', (control) => control.removeReaction?.(input.message, input.reactionId), undefined);
|
|
720
|
-
}
|
|
721
|
-
/** Activity-feedback autoRemove: recall a previously sent status message. */
|
|
722
|
-
async recallEndpointMessage(input) {
|
|
723
|
-
await this.#withEndpointControl(input.adapter, input.endpointKey, 'recall', (control) => control.recall?.(input.message), undefined);
|
|
724
|
-
}
|
|
725
|
-
async editEndpointMessage(input) {
|
|
726
|
-
return this.#withEndpointControl(input.adapter, input.endpointKey, 'edit', (control) => control.edit?.(input.message, input.content) ?? null, null);
|
|
727
|
-
}
|
|
728
|
-
async setEndpointTyping(input) {
|
|
729
|
-
await this.#withEndpointControl(input.adapter, input.endpointKey, 'typing', (control) => control.typing?.(input.conversation, input.active), undefined);
|
|
730
|
-
}
|
|
731
|
-
async #withEndpointControl(adapter, endpointKey, operation, run, fallback) {
|
|
732
|
-
let lease;
|
|
733
|
-
try {
|
|
734
|
-
lease = this.#acquire();
|
|
735
|
-
}
|
|
736
|
-
catch {
|
|
737
|
-
return fallback;
|
|
738
|
-
}
|
|
739
|
-
try {
|
|
740
|
-
const index = requireAdapters(lease.value);
|
|
741
|
-
const id = index.resolve(adapter, endpointKey);
|
|
742
|
-
const control = id ? index.control(id, operation) : undefined;
|
|
743
|
-
return control ? await run(control) : fallback;
|
|
744
|
-
}
|
|
745
|
-
finally {
|
|
746
|
-
this.#release(lease);
|
|
747
|
-
}
|
|
748
|
-
}
|
|
749
|
-
/** Run one management operation while the Endpoint generation stays leased. */
|
|
750
|
-
async withEndpointManagement(adapter, endpointKey, run) {
|
|
751
|
-
let lease;
|
|
752
|
-
try {
|
|
753
|
-
lease = this.#acquire();
|
|
754
|
-
}
|
|
755
|
-
catch {
|
|
756
|
-
return null;
|
|
757
|
-
}
|
|
758
|
-
try {
|
|
759
|
-
const endpoint = requireAdapters(lease.value).connection(adapter, endpointKey);
|
|
760
|
-
if (!endpoint)
|
|
761
|
-
return null;
|
|
762
|
-
return await run(resolveEndpointManagement(endpoint) ?? Object.freeze({}));
|
|
763
|
-
}
|
|
764
|
-
finally {
|
|
765
|
-
this.#release(lease);
|
|
766
|
-
}
|
|
340
|
+
/** All unified outbound entry points observe the actual delivery, never their own caller/drain promise. */
|
|
341
|
+
#deliver(request, snapshot, execution) {
|
|
342
|
+
const delivery = this.#outbound.deliver(request, snapshot, execution);
|
|
343
|
+
this.#commandOperation.getStore()?.trackSend(delivery);
|
|
344
|
+
return delivery;
|
|
767
345
|
}
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
adapters = requireAdapters(snapshot);
|
|
781
|
-
}
|
|
782
|
-
catch (error) {
|
|
783
|
-
return receiptFromEndpointError(error);
|
|
784
|
-
}
|
|
785
|
-
const envelope = createOutboundEnvelope({
|
|
786
|
-
conversation: request.conversation,
|
|
787
|
-
requester: request.requester,
|
|
788
|
-
generation: snapshot.generation,
|
|
789
|
-
clientAdapter: adapters.clientAdapter(adapter),
|
|
790
|
-
}, initialPayload, () => adapters.clientById(adapter));
|
|
791
|
-
let terminalEntered = false;
|
|
792
|
-
let receipt;
|
|
793
|
-
try {
|
|
794
|
-
await runMiddleware(snapshot, envelope, async () => {
|
|
795
|
-
terminalEntered = true;
|
|
796
|
-
let payload;
|
|
797
|
-
try {
|
|
798
|
-
payload = await prepareOutboundPayload(envelope.payload, request.conversation, snapshot, true);
|
|
799
|
-
}
|
|
800
|
-
catch {
|
|
801
|
-
receipt = rejectedReceipt('outbound_payload_rejected');
|
|
802
|
-
return;
|
|
803
|
-
}
|
|
804
|
-
try {
|
|
805
|
-
const result = await requireAdapters(snapshot).send(adapter, {
|
|
806
|
-
conversation: request.conversation,
|
|
807
|
-
payload,
|
|
808
|
-
});
|
|
809
|
-
receipt = receiptFromEndpointResult(result, request.conversation);
|
|
810
|
-
}
|
|
811
|
-
catch (error) {
|
|
812
|
-
receipt = receiptFromEndpointError(error);
|
|
813
|
-
}
|
|
814
|
-
if (receipt?.status === 'sent') {
|
|
815
|
-
if (receipt.message?.id) {
|
|
816
|
-
const segments = conversationSegmentsFromContent(request.content);
|
|
817
|
-
await this.conversationEvents.append(Object.freeze({
|
|
818
|
-
eventId: `message:${messageRefKey(receipt.message)}`,
|
|
819
|
-
conversation: request.conversation,
|
|
820
|
-
timestamp: Date.now(),
|
|
821
|
-
type: 'message.created',
|
|
822
|
-
message: Object.freeze({
|
|
823
|
-
ref: receipt.message,
|
|
824
|
-
segments,
|
|
825
|
-
timestamp: Date.now(),
|
|
826
|
-
}),
|
|
827
|
-
}));
|
|
828
|
-
}
|
|
829
|
-
this.#emitMessage({
|
|
830
|
-
direction: 'outbound',
|
|
831
|
-
conversation: request.conversation,
|
|
832
|
-
requester: request.requester,
|
|
833
|
-
contentPreview: previewText(payload),
|
|
834
|
-
...(receipt.message?.id
|
|
835
|
-
? { messageId: receipt.message.id }
|
|
836
|
-
: {}),
|
|
837
|
-
timestamp: Date.now(),
|
|
838
|
-
});
|
|
839
|
-
}
|
|
840
|
-
}, 'outbound');
|
|
841
|
-
}
|
|
842
|
-
catch {
|
|
843
|
-
return receipt ?? failedReceipt('outbound_middleware_failed');
|
|
844
|
-
}
|
|
845
|
-
if (!terminalEntered) {
|
|
846
|
-
logger.debug(formatCompact({
|
|
847
|
-
op: 'replychain_runtime_send',
|
|
848
|
-
status: 'suppressed',
|
|
849
|
-
reason: 'middleware_stopped_before_terminal',
|
|
850
|
-
conv: formatConversationLog(request.conversation),
|
|
851
|
-
}));
|
|
852
|
-
return suppressedReceipt();
|
|
853
|
-
}
|
|
854
|
-
logger.debug(formatCompact({
|
|
855
|
-
op: 'replychain_runtime_send',
|
|
856
|
-
status: receipt?.status ?? 'missing',
|
|
857
|
-
code: receipt?.failure?.code,
|
|
858
|
-
conv: formatConversationLog(request.conversation),
|
|
346
|
+
#publishSceneEvent(source, stored) {
|
|
347
|
+
if (!stored)
|
|
348
|
+
return;
|
|
349
|
+
const metadata = source.metadata;
|
|
350
|
+
const selfIds = [source.endpointId, metadata.self_id, metadata.selfId]
|
|
351
|
+
.filter((value) => (typeof value === 'string' && value !== '') || typeof value === 'number')
|
|
352
|
+
.map(String);
|
|
353
|
+
this.#sceneEventStream.publish(Object.freeze({
|
|
354
|
+
sequence: stored.sequence,
|
|
355
|
+
event: stored.event,
|
|
356
|
+
...(source.endpointId ? { endpointId: source.endpointId } : {}),
|
|
357
|
+
selfIds: Object.freeze([...new Set(selfIds)]),
|
|
859
358
|
}));
|
|
860
|
-
|
|
359
|
+
}
|
|
360
|
+
#retainSnapshot() {
|
|
361
|
+
if (!this.#snapshots)
|
|
362
|
+
throw new Error('ImRuntime is not attached to a Root');
|
|
363
|
+
const inherited = this.#operationSnapshot.getStore();
|
|
364
|
+
return inherited?.active ? this.#snapshots.retain(inherited) : this.#snapshots.acquire();
|
|
861
365
|
}
|
|
862
366
|
#acquire() {
|
|
863
367
|
const inherited = this.#operationSnapshot.getStore();
|
|
@@ -872,333 +376,4 @@ export class ImRuntime {
|
|
|
872
376
|
return;
|
|
873
377
|
lease.release();
|
|
874
378
|
}
|
|
875
|
-
/**
|
|
876
|
-
* interactive 回跳分发(Command dispatch 之前):action 段 / 中央 fallback
|
|
877
|
-
* 数字回跳 / 指令预填 payload → prefix 最长匹配 handler。
|
|
878
|
-
*/
|
|
879
|
-
async #dispatchInteractive(message, requester, admission) {
|
|
880
|
-
if (this.#interactiveHandlers.length === 0)
|
|
881
|
-
return undefined;
|
|
882
|
-
const payload = resolveRuntimeInteractivePayload(message);
|
|
883
|
-
if (!payload)
|
|
884
|
-
return undefined;
|
|
885
|
-
const handler = findRuntimeInteractiveHandler(this.#interactiveHandlers.filter((entry) => !entry.admission || entry.admission === admission), payload);
|
|
886
|
-
if (!handler)
|
|
887
|
-
return undefined;
|
|
888
|
-
const handled = await handler(message);
|
|
889
|
-
return handled
|
|
890
|
-
? Object.freeze({ matched: true, command: 'interactive', owner: requester })
|
|
891
|
-
: undefined;
|
|
892
|
-
}
|
|
893
|
-
}
|
|
894
|
-
function conversationEventFromNotice(notice) {
|
|
895
|
-
const sceneType = notice.$scene_type;
|
|
896
|
-
const kind = sceneType === 'group' ? 'group'
|
|
897
|
-
: sceneType === 'channel' ? 'channel'
|
|
898
|
-
: sceneType === 'friend' || sceneType === 'private' ? 'private'
|
|
899
|
-
: undefined;
|
|
900
|
-
if (!kind || !notice.$scene_id || !notice.$id)
|
|
901
|
-
return undefined;
|
|
902
|
-
const conversation = Object.freeze({
|
|
903
|
-
endpoint: Object.freeze({ adapter: String(notice.$adapter), id: String(notice.$endpoint) }),
|
|
904
|
-
kind,
|
|
905
|
-
id: String(notice.$scene_id),
|
|
906
|
-
});
|
|
907
|
-
const actor = notice.$actor?.id
|
|
908
|
-
? Object.freeze({ id: String(notice.$actor.id), ...(notice.$actor.name ? { displayName: notice.$actor.name } : {}) })
|
|
909
|
-
: undefined;
|
|
910
|
-
const target = notice.$target?.id
|
|
911
|
-
? Object.freeze({ id: String(notice.$target.id), ...(notice.$target.name ? { displayName: notice.$target.name } : {}) })
|
|
912
|
-
: undefined;
|
|
913
|
-
const base = Object.freeze({
|
|
914
|
-
eventId: `notice:${conversationRefKey(conversation)}:${String(notice.$id)}`,
|
|
915
|
-
conversation,
|
|
916
|
-
timestamp: notice.$timestamp,
|
|
917
|
-
});
|
|
918
|
-
switch (notice.$sub_type) {
|
|
919
|
-
case 'member_increase':
|
|
920
|
-
case 'increase':
|
|
921
|
-
return target ? Object.freeze({ ...base, type: 'member.joined', member: target, ...(actor ? { actor } : {}) }) : undefined;
|
|
922
|
-
case 'member_decrease':
|
|
923
|
-
return target ? Object.freeze({ ...base, type: 'member.left', member: target, ...(actor ? { actor } : {}), reason: actor ? 'removed' : 'left' }) : undefined;
|
|
924
|
-
case 'ban':
|
|
925
|
-
if (!target)
|
|
926
|
-
return undefined;
|
|
927
|
-
return notice.$duration_seconds === 0
|
|
928
|
-
? Object.freeze({ ...base, type: 'member.unmuted', member: target, ...(actor ? { actor } : {}) })
|
|
929
|
-
: Object.freeze({ ...base, type: 'member.muted', member: target, ...(actor ? { actor } : {}), durationSeconds: notice.$duration_seconds ?? 0 });
|
|
930
|
-
case 'admin_change':
|
|
931
|
-
return target && notice.$role && typeof notice.$enabled === 'boolean'
|
|
932
|
-
? Object.freeze({ ...base, type: 'member.role_changed', member: target, ...(actor ? { actor } : {}), role: notice.$role, enabled: notice.$enabled })
|
|
933
|
-
: undefined;
|
|
934
|
-
case 'recall':
|
|
935
|
-
return notice.$message_id
|
|
936
|
-
? Object.freeze({ ...base, type: 'message.recalled', message: Object.freeze({ conversation, id: notice.$message_id }), ...(actor ? { actor } : {}) })
|
|
937
|
-
: undefined;
|
|
938
|
-
case 'emoji_reaction':
|
|
939
|
-
return notice.$message_id && notice.$reaction && notice.$operation
|
|
940
|
-
? Object.freeze({ ...base, type: 'message.reaction_changed', message: Object.freeze({ conversation, id: notice.$message_id }), ...(actor ? { actor } : {}), reaction: notice.$reaction, operation: notice.$operation })
|
|
941
|
-
: undefined;
|
|
942
|
-
case 'poke':
|
|
943
|
-
return Object.freeze({ ...base, type: 'conversation.poked', ...(actor ? { actor } : {}), ...(target ? { target } : {}) });
|
|
944
|
-
default:
|
|
945
|
-
return undefined;
|
|
946
|
-
}
|
|
947
|
-
}
|
|
948
|
-
function describeConversationEvent(event) {
|
|
949
|
-
const actor = 'actor' in event && event.actor ? `${event.actor.displayName ?? event.actor.id} (${event.actor.id})` : undefined;
|
|
950
|
-
switch (event.type) {
|
|
951
|
-
case 'message.recalled': return `${actor ?? 'Someone'} recalled message ${event.message.id}.`;
|
|
952
|
-
case 'message.reaction_changed': return `${actor ?? 'Someone'} ${event.operation} reaction ${event.reaction} on message ${event.message.id}.`;
|
|
953
|
-
case 'conversation.poked': return `${actor ?? 'Someone'} poked ${event.target ? `${event.target.displayName ?? event.target.id} (${event.target.id})` : 'someone'}.`;
|
|
954
|
-
case 'member.joined': return `${event.member.displayName ?? event.member.id} (${event.member.id}) joined the conversation.`;
|
|
955
|
-
case 'member.left': return `${event.member.displayName ?? event.member.id} (${event.member.id}) left the conversation (${event.reason ?? 'left'}).`;
|
|
956
|
-
case 'member.muted': return `${event.member.displayName ?? event.member.id} (${event.member.id}) was muted for ${event.durationSeconds} seconds${actor ? ` by ${actor}` : ''}.`;
|
|
957
|
-
case 'member.unmuted': return `${event.member.displayName ?? event.member.id} (${event.member.id}) was unmuted${actor ? ` by ${actor}` : ''}.`;
|
|
958
|
-
case 'member.role_changed': return `${event.member.displayName ?? event.member.id} (${event.member.id}) role ${event.role} was ${event.enabled ? 'enabled' : 'disabled'}${actor ? ` by ${actor}` : ''}.`;
|
|
959
|
-
case 'message.created': return '';
|
|
960
|
-
}
|
|
961
|
-
}
|
|
962
|
-
function describeConversationMessage(message) {
|
|
963
|
-
const actor = message.actor
|
|
964
|
-
? `${message.actor.displayName ?? message.actor.id} (${message.actor.id})`
|
|
965
|
-
: undefined;
|
|
966
|
-
if (!actor)
|
|
967
|
-
return '';
|
|
968
|
-
const text = segmentsToPlainText(message.segments).trim();
|
|
969
|
-
const attachmentTypes = [...new Set(message.segments
|
|
970
|
-
.filter((segment) => segment.type !== 'text' && segment.type !== 'mention' && segment.type !== 'at')
|
|
971
|
-
.map((segment) => segment.type))];
|
|
972
|
-
const attachmentNote = attachmentTypes.length > 0
|
|
973
|
-
? ` [message also contains ${attachmentTypes.join(', ')} data; inspect its reference before relying on that content]`
|
|
974
|
-
: '';
|
|
975
|
-
return `${actor}: ${text || '(no plain-text content)'}${attachmentNote}`;
|
|
976
|
-
}
|
|
977
|
-
function aggregateConversationContext(events, excludeMessageId) {
|
|
978
|
-
const ordinary = [];
|
|
979
|
-
const noisy = new Map();
|
|
980
|
-
for (const { sequence, event } of events) {
|
|
981
|
-
if (event.type === 'message.created') {
|
|
982
|
-
if (event.message.ref.id === excludeMessageId)
|
|
983
|
-
continue;
|
|
984
|
-
const text = describeConversationMessage(event.message);
|
|
985
|
-
if (!text)
|
|
986
|
-
continue;
|
|
987
|
-
ordinary.push(Object.freeze({
|
|
988
|
-
kind: 'conversation_event',
|
|
989
|
-
sequence,
|
|
990
|
-
eventType: event.type,
|
|
991
|
-
text,
|
|
992
|
-
}));
|
|
993
|
-
continue;
|
|
994
|
-
}
|
|
995
|
-
if (event.type === 'message.reaction_changed' || event.type === 'conversation.poked') {
|
|
996
|
-
const key = event.type === 'message.reaction_changed'
|
|
997
|
-
? `${event.type}:${event.message.id}:${event.actor?.id ?? ''}:${event.reaction}:${event.operation}`
|
|
998
|
-
: `${event.type}:${event.actor?.id ?? ''}:${event.target?.id ?? ''}`;
|
|
999
|
-
const previous = noisy.get(key);
|
|
1000
|
-
noisy.set(key, { sequence, event, count: (previous?.count ?? 0) + 1 });
|
|
1001
|
-
continue;
|
|
1002
|
-
}
|
|
1003
|
-
ordinary.push(Object.freeze({
|
|
1004
|
-
kind: 'conversation_event',
|
|
1005
|
-
sequence,
|
|
1006
|
-
eventType: event.type,
|
|
1007
|
-
text: describeConversationEvent(event),
|
|
1008
|
-
}));
|
|
1009
|
-
}
|
|
1010
|
-
for (const { sequence, event, count } of noisy.values()) {
|
|
1011
|
-
ordinary.push(Object.freeze({
|
|
1012
|
-
kind: 'conversation_event',
|
|
1013
|
-
sequence,
|
|
1014
|
-
eventType: event.type,
|
|
1015
|
-
text: `${describeConversationEvent(event)}${count > 1 ? ` (${count} similar events.)` : ''}`,
|
|
1016
|
-
}));
|
|
1017
|
-
}
|
|
1018
|
-
ordinary.sort((left, right) => left.sequence - right.sequence);
|
|
1019
|
-
return Object.freeze(ordinary);
|
|
1020
|
-
}
|
|
1021
|
-
function resolveIngressRoute(snapshot) {
|
|
1022
|
-
const candidate = snapshot.resources.get(snapshot.root)?.get(ingressRouteToken.id);
|
|
1023
|
-
return candidate
|
|
1024
|
-
&& typeof candidate === 'object'
|
|
1025
|
-
&& typeof candidate.route === 'function'
|
|
1026
|
-
? candidate
|
|
1027
|
-
: undefined;
|
|
1028
|
-
}
|
|
1029
|
-
function requireAdapters(snapshot) {
|
|
1030
|
-
const projection = snapshot.projections.get(adapterFeatureId);
|
|
1031
|
-
if (!isAdapterIndex(projection)) {
|
|
1032
|
-
throw new Error('Adapter Feature projection is not installed');
|
|
1033
|
-
}
|
|
1034
|
-
return projection;
|
|
1035
|
-
}
|
|
1036
|
-
/** Root resources 上的可选 html-renderer Host(未安装时降级为文本)。 */
|
|
1037
|
-
function resolveHtmlRenderer(snapshot) {
|
|
1038
|
-
const host = snapshot.resources.get(snapshot.root)?.get(htmlRendererToken.id);
|
|
1039
|
-
return host && typeof host.render === 'function'
|
|
1040
|
-
? host
|
|
1041
|
-
: undefined;
|
|
1042
|
-
}
|
|
1043
|
-
/**
|
|
1044
|
-
* Sandbox(控制台 UI)按设计直接消费 html 段,不做 html→image/text 规范化。
|
|
1045
|
-
* 通过 adapter 能力 slot 的 owner 包名判断平台类型。
|
|
1046
|
-
*/
|
|
1047
|
-
function isDirectHtmlConsumer(snapshot, adapter) {
|
|
1048
|
-
const owner = snapshot.capabilities.get(adapter)?.owner;
|
|
1049
|
-
return adapterTypeName(snapshot.tree.get(owner)?.packageName) === 'sandbox';
|
|
1050
|
-
}
|
|
1051
|
-
async function prepareOutboundPayload(rendered, conversation, snapshot, finalizeInteractive = false) {
|
|
1052
|
-
const adapter = conversation.endpoint.id;
|
|
1053
|
-
const directHtml = isDirectHtmlConsumer(snapshot, adapter);
|
|
1054
|
-
const markdownResolved = applyOutboundMarkdownPolicy(rendered, resolveOutboundMarkdownPolicy(adapter, snapshot));
|
|
1055
|
-
let payload = directHtml
|
|
1056
|
-
? markdownResolved
|
|
1057
|
-
: await normalizeOutboundPayload(markdownResolved, resolveHtmlRenderer(snapshot), {
|
|
1058
|
-
mediaPolicy: resolveOutboundMediaPolicy(adapter, snapshot),
|
|
1059
|
-
});
|
|
1060
|
-
if (finalizeInteractive) {
|
|
1061
|
-
payload = applyOutboundInteractivePolicy(payload, resolveOutboundInteractivePolicy(adapter, snapshot), (map) => keyboardFallbackStore.remember(runtimeInteractiveConversationKey(conversation), map));
|
|
1062
|
-
}
|
|
1063
|
-
if (!directHtml && Array.isArray(payload))
|
|
1064
|
-
assertCanonicalSegments(payload);
|
|
1065
|
-
return payload;
|
|
1066
|
-
}
|
|
1067
|
-
function receiptFromEndpointResult(messageId, conversation) {
|
|
1068
|
-
return Object.freeze({
|
|
1069
|
-
status: 'sent',
|
|
1070
|
-
message: Object.freeze({ conversation, id: messageId }),
|
|
1071
|
-
});
|
|
1072
|
-
}
|
|
1073
|
-
function receiptFromEndpointError(error) {
|
|
1074
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
1075
|
-
if (/Unknown Adapter Endpoint|does not support outbound/u.test(message)) {
|
|
1076
|
-
return unsupportedReceipt('outbound_unsupported');
|
|
1077
|
-
}
|
|
1078
|
-
if (/not active/u.test(message))
|
|
1079
|
-
return failedReceipt('endpoint_inactive', true);
|
|
1080
|
-
return failedReceipt('endpoint_send_failed', true);
|
|
1081
|
-
}
|
|
1082
|
-
function suppressedReceipt() {
|
|
1083
|
-
return Object.freeze({ status: 'suppressed' });
|
|
1084
|
-
}
|
|
1085
|
-
function unsupportedReceipt(code) {
|
|
1086
|
-
return Object.freeze({
|
|
1087
|
-
status: 'unsupported',
|
|
1088
|
-
failure: Object.freeze({ code, message: 'Outbound delivery is not supported.' }),
|
|
1089
|
-
});
|
|
1090
|
-
}
|
|
1091
|
-
function rejectedReceipt(code) {
|
|
1092
|
-
return Object.freeze({
|
|
1093
|
-
status: 'rejected',
|
|
1094
|
-
failure: Object.freeze({ code, message: 'Outbound payload was rejected.' }),
|
|
1095
|
-
});
|
|
1096
|
-
}
|
|
1097
|
-
function failedReceipt(code, retryable = false) {
|
|
1098
|
-
return Object.freeze({
|
|
1099
|
-
status: 'failed',
|
|
1100
|
-
failure: Object.freeze({
|
|
1101
|
-
code,
|
|
1102
|
-
message: 'Outbound delivery failed.',
|
|
1103
|
-
...(retryable ? { retryable: true } : {}),
|
|
1104
|
-
}),
|
|
1105
|
-
});
|
|
1106
|
-
}
|
|
1107
|
-
/** `@zhin.js/adapter-icqq` → `icqq`;非 adapter 包名原样返回。 */
|
|
1108
|
-
function adapterTypeName(packageName) {
|
|
1109
|
-
if (!packageName)
|
|
1110
|
-
return undefined;
|
|
1111
|
-
return packageName.replace(/^@[^/]+\/adapter-/, '');
|
|
1112
|
-
}
|
|
1113
|
-
function middleware(snapshot) {
|
|
1114
|
-
const projection = snapshot.projections.get(middlewareFeatureId);
|
|
1115
|
-
return isMiddlewareIndex(projection) ? projection : undefined;
|
|
1116
|
-
}
|
|
1117
|
-
async function runMiddleware(snapshot, input, terminal, target) {
|
|
1118
|
-
const index = middleware(snapshot);
|
|
1119
|
-
if (index)
|
|
1120
|
-
await index.run(input, terminal, target);
|
|
1121
|
-
else
|
|
1122
|
-
await terminal();
|
|
1123
|
-
}
|
|
1124
|
-
function handlers(snapshot) {
|
|
1125
|
-
const projection = snapshot.projections.get(handlerFeatureId);
|
|
1126
|
-
return isHandlerIndex(projection) ? projection : undefined;
|
|
1127
|
-
}
|
|
1128
|
-
function normalizeConsoleContent(content) {
|
|
1129
|
-
if (typeof content === 'string')
|
|
1130
|
-
return content;
|
|
1131
|
-
// Array content passes through untouched, matching the legacy console RPC
|
|
1132
|
-
// contract (element arrays must not be stringified to '[object Object]').
|
|
1133
|
-
if (Array.isArray(content))
|
|
1134
|
-
return content;
|
|
1135
|
-
return String(content);
|
|
1136
|
-
}
|
|
1137
|
-
/** 日志用会话摘要(`kind:id@parentKind:parentId#threadId`),不拼 legacy target。 */
|
|
1138
|
-
function formatConversationLog(conversation) {
|
|
1139
|
-
const base = `${conversation.kind}:${conversation.id}`;
|
|
1140
|
-
const parent = conversation.parent
|
|
1141
|
-
? `@${conversation.parent.kind}:${conversation.parent.id}`
|
|
1142
|
-
: '';
|
|
1143
|
-
const thread = conversation.threadId ? `#${conversation.threadId}` : '';
|
|
1144
|
-
return `${base}${parent}${thread}`;
|
|
1145
|
-
}
|
|
1146
|
-
/** 消息内容 → 预览文本(截断 200 字);wire 段取 `data.text`,其余段记 `[type]`。 */
|
|
1147
|
-
function previewText(content) {
|
|
1148
|
-
const text = flattenContent(content);
|
|
1149
|
-
return text.length > messagePreviewLimit
|
|
1150
|
-
? `${text.slice(0, messagePreviewLimit)}…`
|
|
1151
|
-
: text;
|
|
1152
|
-
}
|
|
1153
|
-
function flattenContent(content) {
|
|
1154
|
-
if (typeof content === 'string')
|
|
1155
|
-
return content;
|
|
1156
|
-
if (content == null)
|
|
1157
|
-
return '';
|
|
1158
|
-
if (Array.isArray(content)) {
|
|
1159
|
-
return content.map((item) => flattenContent(item)).join('');
|
|
1160
|
-
}
|
|
1161
|
-
if (typeof content === 'object') {
|
|
1162
|
-
const record = content;
|
|
1163
|
-
const data = record.data;
|
|
1164
|
-
if (typeof record.type === 'string') {
|
|
1165
|
-
if (data && typeof data.text === 'string')
|
|
1166
|
-
return data.text;
|
|
1167
|
-
return `[${record.type}]`;
|
|
1168
|
-
}
|
|
1169
|
-
if (typeof record.text === 'string')
|
|
1170
|
-
return record.text;
|
|
1171
|
-
try {
|
|
1172
|
-
return JSON.stringify(content) ?? '';
|
|
1173
|
-
}
|
|
1174
|
-
catch {
|
|
1175
|
-
return String(content);
|
|
1176
|
-
}
|
|
1177
|
-
}
|
|
1178
|
-
return String(content);
|
|
1179
|
-
}
|
|
1180
|
-
function conversationSegmentsFromContent(content) {
|
|
1181
|
-
if (Array.isArray(content)) {
|
|
1182
|
-
try {
|
|
1183
|
-
assertCanonicalSegments(content);
|
|
1184
|
-
return Object.freeze([...content]);
|
|
1185
|
-
}
|
|
1186
|
-
catch {
|
|
1187
|
-
// Fall through to a truthful text projection of non-canonical output.
|
|
1188
|
-
}
|
|
1189
|
-
}
|
|
1190
|
-
return Object.freeze([{ type: 'text', data: Object.freeze({ text: flattenContent(content) }) }]);
|
|
1191
|
-
}
|
|
1192
|
-
function abortError(signal, fallback) {
|
|
1193
|
-
if (signal?.reason instanceof Error)
|
|
1194
|
-
return signal.reason;
|
|
1195
|
-
return new Error(fallback);
|
|
1196
|
-
}
|
|
1197
|
-
function withEndpointEventPayload(source, payload) {
|
|
1198
|
-
return Object.freeze({
|
|
1199
|
-
name: source.name,
|
|
1200
|
-
payload,
|
|
1201
|
-
endpoint: source.endpoint,
|
|
1202
|
-
client: source.client,
|
|
1203
|
-
});
|
|
1204
379
|
}
|