@zhin.js/core 1.5.16 → 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
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { bindOperationInput } from '@zhin.js/feature-kit';
|
|
3
|
+
import { conversationRefKey } from '@zhin.js/im-contract';
|
|
4
|
+
import { jsx } from '@zhin.js/jsx';
|
|
5
|
+
import { interactionMessages as t } from '../../built/interaction-messages.js';
|
|
6
|
+
import { resolvePayloadFromText } from '../../built/interactive-segments/action.js';
|
|
7
|
+
import { isKeyboardSegment } from '../../built/interactive-segments/types.js';
|
|
8
|
+
import { operationEndpoint } from './contracts.js';
|
|
9
|
+
import { assertPermitSyntax, describeDeniedPermit, permissionHostToken, toPermissionSubject } from '@zhin.js/permission';
|
|
10
|
+
const JSX_BUTTON_PREFIX = 'zhin:jsx:';
|
|
11
|
+
const JSX_BUTTON_TTL_MS = 60 * 60 * 1000;
|
|
12
|
+
export function isJsxButtonPayload(payload) {
|
|
13
|
+
return payload?.startsWith(JSX_BUTTON_PREFIX) === true;
|
|
14
|
+
}
|
|
15
|
+
function hasIdenticalPluginTree(left, right) {
|
|
16
|
+
if (left === right)
|
|
17
|
+
return true;
|
|
18
|
+
if (left.size !== right.size)
|
|
19
|
+
return false;
|
|
20
|
+
for (const [id, node] of left) {
|
|
21
|
+
if (right.get(id) !== node)
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
return true;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Checks whether the plugin incarnation that registered a callback/interaction
|
|
28
|
+
* is still live in `currentSnapshot`.
|
|
29
|
+
* Survives HMR of unrelated plugins (where another plugin's node in `tree` changed
|
|
30
|
+
* while `origin.node` is unchanged), while retiring if the owning plugin was reloaded/removed,
|
|
31
|
+
* its endpoint signal aborted, or the runtime performed a full-generation retirement.
|
|
32
|
+
*/
|
|
33
|
+
export function isPluginIncarnationAlive(origin, currentSnapshot) {
|
|
34
|
+
if (origin.signal?.aborted) {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
if (origin.snapshot === currentSnapshot) {
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
if (!origin.node || hasIdenticalPluginTree(origin.snapshot.tree, currentSnapshot.tree)) {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
const currentNode = currentSnapshot.tree.get(origin.requester);
|
|
44
|
+
return currentNode !== undefined && currentNode === origin.node;
|
|
45
|
+
}
|
|
46
|
+
/** Plugin-incarnation-owned callbacks: survive unrelated plugin HMR; retired when owning plugin reloads. */
|
|
47
|
+
export class JsxButtonRegistry {
|
|
48
|
+
#bindings = new Map();
|
|
49
|
+
prepare(request, snapshot) {
|
|
50
|
+
const pending = new Map();
|
|
51
|
+
const node = snapshot.tree.get(request.requester);
|
|
52
|
+
const signal = request[operationEndpoint]?.signal;
|
|
53
|
+
return {
|
|
54
|
+
bind: (props) => {
|
|
55
|
+
const { onClick, payload: manualPayload, children, label, id, permit, ...options } = props;
|
|
56
|
+
if (permit !== undefined) {
|
|
57
|
+
if (!Array.isArray(permit) || !onClick)
|
|
58
|
+
throw new TypeError('Button permit applies to onClick buttons and must be a string array');
|
|
59
|
+
assertPermitSyntax(permit, 'Button');
|
|
60
|
+
}
|
|
61
|
+
if (onClick !== undefined && typeof onClick !== 'function')
|
|
62
|
+
throw new TypeError('Button onClick must be a function');
|
|
63
|
+
if (onClick && manualPayload !== undefined)
|
|
64
|
+
throw new TypeError('Button accepts onClick or payload, not both');
|
|
65
|
+
if (!onClick && typeof manualPayload !== 'string')
|
|
66
|
+
throw new TypeError('Button requires onClick or payload');
|
|
67
|
+
const payload = onClick ? `${JSX_BUTTON_PREFIX}${randomUUID()}` : manualPayload;
|
|
68
|
+
if (onClick && !props.disabled)
|
|
69
|
+
pending.set(payload, {
|
|
70
|
+
onClick,
|
|
71
|
+
...(permit?.length ? { permit: Object.freeze([...permit]) } : {}),
|
|
72
|
+
requester: request.requester,
|
|
73
|
+
snapshot,
|
|
74
|
+
node,
|
|
75
|
+
...(signal ? { signal } : {}),
|
|
76
|
+
conversationKey: conversationRefKey(request.conversation),
|
|
77
|
+
expiresAt: 0,
|
|
78
|
+
});
|
|
79
|
+
return { type: 'keyboard', data: { rows: [[{
|
|
80
|
+
...options,
|
|
81
|
+
id: id ?? randomUUID(),
|
|
82
|
+
label: label ?? children,
|
|
83
|
+
payload,
|
|
84
|
+
...(onClick ? { mode: 'callback' } : {}),
|
|
85
|
+
}]] } };
|
|
86
|
+
},
|
|
87
|
+
activate: (payloads) => {
|
|
88
|
+
const activated = [];
|
|
89
|
+
this.#prune(snapshot);
|
|
90
|
+
for (const [payload, binding] of pending) {
|
|
91
|
+
if (!payloads.has(payload))
|
|
92
|
+
continue;
|
|
93
|
+
this.#bindings.set(payload, { ...binding, expiresAt: Date.now() + JSX_BUTTON_TTL_MS });
|
|
94
|
+
activated.push(payload);
|
|
95
|
+
}
|
|
96
|
+
pending.clear();
|
|
97
|
+
return () => { for (const payload of activated)
|
|
98
|
+
this.#bindings.delete(payload); };
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
async dispatch(message, payload, snapshot) {
|
|
103
|
+
if (!isJsxButtonPayload(payload))
|
|
104
|
+
return false;
|
|
105
|
+
this.#prune(snapshot);
|
|
106
|
+
const binding = this.#bindings.get(payload);
|
|
107
|
+
// Never invoke a retired closure. The reply uses this incoming operation's scope.
|
|
108
|
+
if (!binding || !isPluginIncarnationAlive(binding, snapshot)) {
|
|
109
|
+
if (binding)
|
|
110
|
+
this.#bindings.delete(payload);
|
|
111
|
+
await message.$reply(t(message.locale, 'expired'));
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
if (binding.conversationKey !== conversationRefKey(message.conversation))
|
|
115
|
+
return true;
|
|
116
|
+
if (binding.permit) {
|
|
117
|
+
// ADR 0056 §5: the clicker, not the sender of the original message, must meet the permit.
|
|
118
|
+
const host = snapshot.resources.get(snapshot.root)?.get(permissionHostToken.id);
|
|
119
|
+
const denied = host && typeof host.firstDenied === 'function'
|
|
120
|
+
? await host.firstDenied(binding.permit, toPermissionSubject(message), { source: message }).catch(() => binding.permit[0])
|
|
121
|
+
: binding.permit[0];
|
|
122
|
+
if (denied !== undefined) {
|
|
123
|
+
await message.$reply(t(message.locale, 'denied', { reason: describeDeniedPermit(denied, message.locale) }));
|
|
124
|
+
return true;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const bound = bindOperationInput(message, binding.requester, snapshot);
|
|
128
|
+
const content = await binding.onClick(bound);
|
|
129
|
+
if (typeof content === 'number')
|
|
130
|
+
await bound.$reply(jsx('text', { text: String(content) }));
|
|
131
|
+
else if (content != null && typeof content !== 'boolean')
|
|
132
|
+
await bound.$reply(content);
|
|
133
|
+
return true;
|
|
134
|
+
}
|
|
135
|
+
#prune(currentSnapshot) {
|
|
136
|
+
const now = Date.now();
|
|
137
|
+
for (const [payload, binding] of this.#bindings) {
|
|
138
|
+
if (binding.expiresAt <= now || (currentSnapshot && !isPluginIncarnationAlive(binding, currentSnapshot))) {
|
|
139
|
+
this.#bindings.delete(payload);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
export function collectButtonPayloads(payload) {
|
|
145
|
+
const result = new Set();
|
|
146
|
+
for (const item of Array.isArray(payload) ? payload : [payload]) {
|
|
147
|
+
if (isKeyboardSegment(item)) {
|
|
148
|
+
for (const row of item.data.rows)
|
|
149
|
+
for (const button of row)
|
|
150
|
+
result.add(button.payload);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return result;
|
|
154
|
+
}
|
|
155
|
+
const DEFAULT_FALLBACK_TTL_MS = 60 * 60 * 1000;
|
|
156
|
+
const MAX_EXPIRED_BATCHES = 1000;
|
|
157
|
+
/**
|
|
158
|
+
* One ImRuntime-owned authority for interactive routing and keyboard fallback state.
|
|
159
|
+
* No handler or conversation state escapes to another runtime instance.
|
|
160
|
+
*/
|
|
161
|
+
export class RuntimeInteractiveRouter {
|
|
162
|
+
#handlers = [];
|
|
163
|
+
#fallbacks = new Map();
|
|
164
|
+
#expired = [];
|
|
165
|
+
#conversationNumbers = new Map();
|
|
166
|
+
#fallbackTtlMs;
|
|
167
|
+
#numberingScope;
|
|
168
|
+
#nextNumber = 1;
|
|
169
|
+
constructor(optionsOrTtlMs = DEFAULT_FALLBACK_TTL_MS, options) {
|
|
170
|
+
if (typeof optionsOrTtlMs === 'number') {
|
|
171
|
+
this.#fallbackTtlMs = optionsOrTtlMs;
|
|
172
|
+
this.#numberingScope = options?.numberingScope ?? 'router';
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
this.#fallbackTtlMs = optionsOrTtlMs.fallbackTtlMs ?? DEFAULT_FALLBACK_TTL_MS;
|
|
176
|
+
this.#numberingScope = optionsOrTtlMs.numberingScope ?? 'router';
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
register(prefix, handler, admission) {
|
|
180
|
+
if (!prefix)
|
|
181
|
+
throw new TypeError('Interactive handler prefix must not be empty');
|
|
182
|
+
const entry = Object.freeze({
|
|
183
|
+
prefix,
|
|
184
|
+
handler,
|
|
185
|
+
admission,
|
|
186
|
+
});
|
|
187
|
+
this.#handlers.push(entry);
|
|
188
|
+
return () => {
|
|
189
|
+
const index = this.#handlers.indexOf(entry);
|
|
190
|
+
if (index >= 0)
|
|
191
|
+
this.#handlers.splice(index, 1);
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
rememberFallback(conversation, generation, map, ttlMsOrContext) {
|
|
195
|
+
this.#pruneFallbacks();
|
|
196
|
+
const ttlMs = typeof ttlMsOrContext === 'number'
|
|
197
|
+
? ttlMsOrContext
|
|
198
|
+
: (ttlMsOrContext && 'ttlMs' in ttlMsOrContext && ttlMsOrContext.ttlMs !== undefined
|
|
199
|
+
? ttlMsOrContext.ttlMs
|
|
200
|
+
: this.#fallbackTtlMs);
|
|
201
|
+
const incarnation = ttlMsOrContext && typeof ttlMsOrContext === 'object'
|
|
202
|
+
? ('requester' in ttlMsOrContext && 'snapshot' in ttlMsOrContext
|
|
203
|
+
? ttlMsOrContext
|
|
204
|
+
: ttlMsOrContext.incarnation)
|
|
205
|
+
: undefined;
|
|
206
|
+
const key = conversationRefKey(conversation);
|
|
207
|
+
const entries = this.#fallbacks.get(key) ?? [];
|
|
208
|
+
if (this.#numberingScope === 'conversation'
|
|
209
|
+
&& !entries.some(entry => this.#isEntryLive(entry, generation, incarnation?.snapshot))) {
|
|
210
|
+
this.#conversationNumbers.delete(key);
|
|
211
|
+
}
|
|
212
|
+
const allocated = {};
|
|
213
|
+
for (const [label, payload] of Object.entries(map)) {
|
|
214
|
+
allocated[/^\d+$/.test(label) ? String(this.#allocateNumber(key)) : label] = payload;
|
|
215
|
+
}
|
|
216
|
+
entries.push(Object.freeze({
|
|
217
|
+
generation,
|
|
218
|
+
...(incarnation ? { incarnation } : {}),
|
|
219
|
+
map: Object.freeze({ ...allocated }),
|
|
220
|
+
expiresAt: Date.now() + ttlMs,
|
|
221
|
+
}));
|
|
222
|
+
this.#fallbacks.set(key, entries);
|
|
223
|
+
return allocated;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Content-aware probe for Room routing: would this input resolve against an unexpired keyboard
|
|
227
|
+
* fallback on this exact (Endpoint-scoped) conversation and generation? A live keyboard alone is
|
|
228
|
+
* not an answer. With an action segment, only a payload that belongs to one of this
|
|
229
|
+
* conversation's live fallback maps counts; plain text counts only when its label / number maps
|
|
230
|
+
* to a button. Strictly read-only: it never calls `#pruneFallbacks()` and never mutates state;
|
|
231
|
+
* expired entries are simply ignored.
|
|
232
|
+
*/
|
|
233
|
+
resolvesLiveFallback(conversation, generation, input, snapshot) {
|
|
234
|
+
const now = Date.now();
|
|
235
|
+
const entries = this.#fallbacks.get(conversationRefKey(conversation));
|
|
236
|
+
const live = entries?.filter(entry => entry.expiresAt > now && this.#isEntryLive(entry, generation, snapshot));
|
|
237
|
+
if (!live?.length)
|
|
238
|
+
return false;
|
|
239
|
+
const actionPayload = actionPayloadFromSegments(input.segments);
|
|
240
|
+
if (actionPayload !== undefined) {
|
|
241
|
+
return live.some(entry => Object.values(entry.map).includes(actionPayload));
|
|
242
|
+
}
|
|
243
|
+
const raw = input.content.trim();
|
|
244
|
+
if (!raw)
|
|
245
|
+
return false;
|
|
246
|
+
return resolvePayloadFromText(raw, Object.assign({}, ...live.map(entry => entry.map))) !== undefined;
|
|
247
|
+
}
|
|
248
|
+
resolvePayload(message, contextOrFallbackGeneration, explicitSnapshot) {
|
|
249
|
+
const fromSegments = actionPayloadFromSegments(message.segments);
|
|
250
|
+
if (fromSegments)
|
|
251
|
+
return fromSegments;
|
|
252
|
+
const raw = message.content.trim();
|
|
253
|
+
if (!raw)
|
|
254
|
+
return undefined;
|
|
255
|
+
let fallbackGeneration = message.generation;
|
|
256
|
+
let snapshot = explicitSnapshot;
|
|
257
|
+
if (typeof contextOrFallbackGeneration === 'number') {
|
|
258
|
+
fallbackGeneration = contextOrFallbackGeneration;
|
|
259
|
+
}
|
|
260
|
+
else if (contextOrFallbackGeneration && typeof contextOrFallbackGeneration === 'object') {
|
|
261
|
+
if ('tree' in contextOrFallbackGeneration && 'generation' in contextOrFallbackGeneration) {
|
|
262
|
+
snapshot = contextOrFallbackGeneration;
|
|
263
|
+
}
|
|
264
|
+
else {
|
|
265
|
+
if (contextOrFallbackGeneration.fallbackGeneration !== undefined) {
|
|
266
|
+
fallbackGeneration = contextOrFallbackGeneration.fallbackGeneration;
|
|
267
|
+
}
|
|
268
|
+
if (contextOrFallbackGeneration.snapshot !== undefined) {
|
|
269
|
+
snapshot = contextOrFallbackGeneration.snapshot;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return resolvePayloadFromText(raw, this.#fallbackMap(message.conversation, message.generation, snapshot)
|
|
274
|
+
?? (fallbackGeneration !== message.generation
|
|
275
|
+
? this.#fallbackMap(message.conversation, fallbackGeneration, snapshot)
|
|
276
|
+
: undefined));
|
|
277
|
+
}
|
|
278
|
+
/** Bounded label-only history: stale text buttons are not mistaken for new input. */
|
|
279
|
+
isExpiredFallback(message, snapshot, options) {
|
|
280
|
+
if (actionPayloadFromSegments(message.segments) || this.resolvePayload(message, { snapshot }))
|
|
281
|
+
return false;
|
|
282
|
+
const key = conversationRefKey(message.conversation);
|
|
283
|
+
const matches = (map) => resolvePayloadFromText(message.content, map) !== undefined;
|
|
284
|
+
const ignoreTtlExpired = options?.ignoreTtlExpiredBareGroupNumbers === true
|
|
285
|
+
&& message.conversation.kind !== 'private'
|
|
286
|
+
&& /^\d+$/u.test(message.content.trim())
|
|
287
|
+
&& !(message.segments ?? []).some(segment => segment.type === 'mention'
|
|
288
|
+
|| segment.type === 'at'
|
|
289
|
+
|| segment.type === 'reply'
|
|
290
|
+
|| segment.type === 'action');
|
|
291
|
+
const now = Date.now();
|
|
292
|
+
if (!ignoreTtlExpired && this.#expired.some(entry => entry.conversationKey === key && matches(entry.map)))
|
|
293
|
+
return true;
|
|
294
|
+
// A generation change (or owning plugin reload) invalidates even a keyboard whose TTL has not elapsed.
|
|
295
|
+
const entries = this.#fallbacks.get(key);
|
|
296
|
+
if (entries?.some(entry => (!ignoreTtlExpired || entry.expiresAt > now)
|
|
297
|
+
&& !this.#isEntryLive(entry, message.generation, snapshot)
|
|
298
|
+
&& matches(entry.map))) {
|
|
299
|
+
return true;
|
|
300
|
+
}
|
|
301
|
+
return false;
|
|
302
|
+
}
|
|
303
|
+
async dispatch(message, admission, snapshot) {
|
|
304
|
+
const payload = this.resolvePayload(message, { snapshot });
|
|
305
|
+
if (!payload)
|
|
306
|
+
return false;
|
|
307
|
+
let match;
|
|
308
|
+
for (const entry of this.#handlers) {
|
|
309
|
+
if (entry.admission && entry.admission !== admission)
|
|
310
|
+
continue;
|
|
311
|
+
if (payload.startsWith(entry.prefix)
|
|
312
|
+
&& (!match || entry.prefix.length > match.prefix.length)) {
|
|
313
|
+
match = entry;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
return match ? Boolean(await match.handler(message)) : false;
|
|
317
|
+
}
|
|
318
|
+
#allocateNumber(conversationKey) {
|
|
319
|
+
if (this.#numberingScope === 'conversation') {
|
|
320
|
+
const next = this.#conversationNumbers.get(conversationKey) ?? 1;
|
|
321
|
+
this.#conversationNumbers.set(conversationKey, next + 1);
|
|
322
|
+
if (this.#conversationNumbers.size > MAX_EXPIRED_BATCHES) {
|
|
323
|
+
const oldest = this.#conversationNumbers.keys().next().value;
|
|
324
|
+
if (oldest !== undefined)
|
|
325
|
+
this.#conversationNumbers.delete(oldest);
|
|
326
|
+
}
|
|
327
|
+
return next;
|
|
328
|
+
}
|
|
329
|
+
return this.#nextNumber++;
|
|
330
|
+
}
|
|
331
|
+
#isEntryLive(entry, generation, snapshot) {
|
|
332
|
+
if (entry.incarnation && snapshot) {
|
|
333
|
+
return isPluginIncarnationAlive(entry.incarnation, snapshot);
|
|
334
|
+
}
|
|
335
|
+
if (entry.incarnation?.signal?.aborted) {
|
|
336
|
+
return false;
|
|
337
|
+
}
|
|
338
|
+
return entry.generation === generation;
|
|
339
|
+
}
|
|
340
|
+
#fallbackMap(conversation, generation, snapshot) {
|
|
341
|
+
const key = conversationRefKey(conversation);
|
|
342
|
+
this.#pruneFallbacks();
|
|
343
|
+
const entries = this.#fallbacks.get(key)?.filter(entry => this.#isEntryLive(entry, generation, snapshot));
|
|
344
|
+
return entries?.length ? Object.assign({}, ...entries.map(entry => entry.map)) : undefined;
|
|
345
|
+
}
|
|
346
|
+
#pruneFallbacks() {
|
|
347
|
+
const now = Date.now();
|
|
348
|
+
for (const [key, entries] of this.#fallbacks) {
|
|
349
|
+
const active = entries.filter(entry => entry.expiresAt > now);
|
|
350
|
+
for (const entry of entries) {
|
|
351
|
+
if (entry.expiresAt > now || entry.expiresAt + this.#fallbackTtlMs <= now)
|
|
352
|
+
continue;
|
|
353
|
+
this.#expired.push({
|
|
354
|
+
conversationKey: key,
|
|
355
|
+
map: Object.freeze(Object.fromEntries(Object.keys(entry.map).map(label => [label, 'expired']))),
|
|
356
|
+
expiresAt: entry.expiresAt + this.#fallbackTtlMs,
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
if (active.length)
|
|
360
|
+
this.#fallbacks.set(key, active);
|
|
361
|
+
else
|
|
362
|
+
this.#fallbacks.delete(key);
|
|
363
|
+
}
|
|
364
|
+
for (let i = this.#expired.length - 1; i >= 0; i--) {
|
|
365
|
+
if (this.#expired[i].expiresAt <= now)
|
|
366
|
+
this.#expired.splice(i, 1);
|
|
367
|
+
}
|
|
368
|
+
if (this.#expired.length > MAX_EXPIRED_BATCHES)
|
|
369
|
+
this.#expired.splice(0, this.#expired.length - MAX_EXPIRED_BATCHES);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
/** @internal Payload of the first action segment (platform callback) that carries a non-empty string. */
|
|
373
|
+
export function actionPayloadFromSegments(segments) {
|
|
374
|
+
for (const segment of segments ?? []) {
|
|
375
|
+
if (segment.type !== 'action')
|
|
376
|
+
continue;
|
|
377
|
+
const payload = segment.data?.payload;
|
|
378
|
+
if (typeof payload === 'string' && payload)
|
|
379
|
+
return payload;
|
|
380
|
+
}
|
|
381
|
+
return undefined;
|
|
382
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { ConversationRef, DeliveryReceipt } from '@zhin.js/im-contract';
|
|
2
|
+
import type { RuntimeMessageRendering } from './message-events.js';
|
|
3
|
+
import type { CommandExecutionLimit } from '@zhin.js/command';
|
|
4
|
+
export interface RuntimeMessageDiagnosticStep {
|
|
5
|
+
readonly stage: 'received' | 'origin' | 'prefix' | 'middleware' | 'handlers' | 'dispatch' | 'delivery';
|
|
6
|
+
readonly status: 'accepted' | 'human' | 'member' | 'peer_bot' | 'self' | 'unclassified' | 'matched' | 'mismatch' | 'empty_input' | 'commands_unavailable' | 'started' | 'entered' | 'stopped' | 'replaced' | 'completed' | 'unmatched' | 'invalid' | 'denied' | 'limited' | 'executed' | 'interaction' | 'middleware' | 'command' | 'agent' | 'self_echo' | 'duplicate' | 'bot_origin' | 'dedup_error' | 'sent' | 'failed' | 'unsupported' | 'rejected' | 'suppressed' | 'unknown';
|
|
7
|
+
readonly at: number;
|
|
8
|
+
}
|
|
9
|
+
export interface RuntimeMessageDiagnosticDelivery {
|
|
10
|
+
readonly conversation: ConversationRef;
|
|
11
|
+
readonly status: DeliveryReceipt['status'];
|
|
12
|
+
readonly failureCode?: string;
|
|
13
|
+
readonly deliveryUnknown?: boolean;
|
|
14
|
+
readonly rendering?: RuntimeMessageRendering;
|
|
15
|
+
}
|
|
16
|
+
/** Operational facts only: no message body, sender profile, config, or raw exception. */
|
|
17
|
+
export interface RuntimeMessageDiagnostic {
|
|
18
|
+
readonly id: string;
|
|
19
|
+
readonly generation: number;
|
|
20
|
+
readonly conversation: ConversationRef;
|
|
21
|
+
readonly messageId?: string;
|
|
22
|
+
readonly startedAt: number;
|
|
23
|
+
readonly endedAt?: number;
|
|
24
|
+
readonly status: 'processing' | 'completed' | 'failed';
|
|
25
|
+
readonly route?: 'interaction' | 'middleware' | 'command' | 'agent' | 'unmatched' | 'self_echo' | 'duplicate' | 'bot_origin' | 'dedup_error';
|
|
26
|
+
readonly command?: string;
|
|
27
|
+
readonly dispatchStatus?: 'unmatched' | 'invalid' | 'denied' | 'limited' | 'executed';
|
|
28
|
+
readonly limit?: CommandExecutionLimit;
|
|
29
|
+
/** Some evidence exceeded the per-operation bound; the record is not a complete timeline. */
|
|
30
|
+
readonly truncated: boolean;
|
|
31
|
+
readonly steps: readonly RuntimeMessageDiagnosticStep[];
|
|
32
|
+
readonly deliveries: readonly RuntimeMessageDiagnosticDelivery[];
|
|
33
|
+
}
|
|
34
|
+
export interface RuntimeMessageDiagnosticsReader {
|
|
35
|
+
list(options?: Readonly<{
|
|
36
|
+
limit?: number;
|
|
37
|
+
conversation?: ConversationRef;
|
|
38
|
+
messageId?: string;
|
|
39
|
+
}>): readonly RuntimeMessageDiagnostic[];
|
|
40
|
+
get(id: string): RuntimeMessageDiagnostic | undefined;
|
|
41
|
+
}
|
|
42
|
+
/** One ImRuntime owns this bounded projection; it never retains a Snapshot or publication authority. */
|
|
43
|
+
export declare class RuntimeMessageDiagnostics implements RuntimeMessageDiagnosticsReader {
|
|
44
|
+
#private;
|
|
45
|
+
private readonly options;
|
|
46
|
+
constructor(options?: Readonly<{
|
|
47
|
+
now?: () => number;
|
|
48
|
+
ttlMs?: number;
|
|
49
|
+
capacity?: number;
|
|
50
|
+
}>);
|
|
51
|
+
run<T>(operation: () => Promise<T>): Promise<T>;
|
|
52
|
+
begin(generation: number, conversation: ConversationRef, messageId?: string): void;
|
|
53
|
+
/** Replace provisional bound ingress identity after canonical AdapterIndex resolution. */
|
|
54
|
+
identify(conversation: ConversationRef): void;
|
|
55
|
+
step(stage: RuntimeMessageDiagnosticStep['stage'], status: RuntimeMessageDiagnosticStep['status']): void;
|
|
56
|
+
dispatch(result: Readonly<{
|
|
57
|
+
matched: boolean;
|
|
58
|
+
command?: string;
|
|
59
|
+
status?: RuntimeMessageDiagnostic['dispatchStatus'];
|
|
60
|
+
limit?: CommandExecutionLimit;
|
|
61
|
+
}>): void;
|
|
62
|
+
route(route: NonNullable<RuntimeMessageDiagnostic['route']>): void;
|
|
63
|
+
delivery(generation: number, conversation: ConversationRef, receipt: DeliveryReceipt, rendering?: RuntimeMessageRendering): void;
|
|
64
|
+
list(options?: Readonly<{
|
|
65
|
+
limit?: number;
|
|
66
|
+
conversation?: ConversationRef;
|
|
67
|
+
messageId?: string;
|
|
68
|
+
}>): readonly RuntimeMessageDiagnostic[];
|
|
69
|
+
get(id: string): RuntimeMessageDiagnostic | undefined;
|
|
70
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
const MAX_STEPS = 32;
|
|
4
|
+
const MAX_DELIVERIES = 32;
|
|
5
|
+
/** One ImRuntime owns this bounded projection; it never retains a Snapshot or publication authority. */
|
|
6
|
+
export class RuntimeMessageDiagnostics {
|
|
7
|
+
options;
|
|
8
|
+
#records = new Map();
|
|
9
|
+
#operation = new AsyncLocalStorage();
|
|
10
|
+
constructor(options = {}) {
|
|
11
|
+
this.options = options;
|
|
12
|
+
}
|
|
13
|
+
async run(operation) {
|
|
14
|
+
const scope = { active: true };
|
|
15
|
+
return this.#operation.run(scope, async () => {
|
|
16
|
+
let failed = false;
|
|
17
|
+
try {
|
|
18
|
+
return await operation();
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
failed = true;
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
finally {
|
|
25
|
+
scope.active = false;
|
|
26
|
+
if (scope.record) {
|
|
27
|
+
scope.record.status = failed ? 'failed' : 'completed';
|
|
28
|
+
scope.record.endedAt = this.#now();
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
begin(generation, conversation, messageId) {
|
|
34
|
+
const scope = this.#operation.getStore();
|
|
35
|
+
if (!scope?.active)
|
|
36
|
+
return;
|
|
37
|
+
const identity = boundedConversation(conversation);
|
|
38
|
+
if (!identity || (messageId !== undefined && !boundedIdentifier(messageId)))
|
|
39
|
+
return;
|
|
40
|
+
this.#prune();
|
|
41
|
+
const record = {
|
|
42
|
+
id: randomUUID(), generation, conversation: identity,
|
|
43
|
+
...(messageId ? { messageId } : {}), startedAt: this.#now(), status: 'processing', truncated: false, steps: [], deliveries: [],
|
|
44
|
+
};
|
|
45
|
+
scope.record = record;
|
|
46
|
+
this.#records.set(record.id, record);
|
|
47
|
+
const capacity = this.options.capacity ?? 500;
|
|
48
|
+
while (this.#records.size > capacity)
|
|
49
|
+
this.#records.delete(this.#records.keys().next().value);
|
|
50
|
+
this.step('received', 'accepted');
|
|
51
|
+
}
|
|
52
|
+
/** Replace provisional bound ingress identity after canonical AdapterIndex resolution. */
|
|
53
|
+
identify(conversation) {
|
|
54
|
+
const record = this.#current();
|
|
55
|
+
if (!record)
|
|
56
|
+
return;
|
|
57
|
+
const identity = boundedConversation(conversation);
|
|
58
|
+
if (identity)
|
|
59
|
+
record.conversation = identity;
|
|
60
|
+
else
|
|
61
|
+
record.truncated = true;
|
|
62
|
+
}
|
|
63
|
+
step(stage, status) {
|
|
64
|
+
const record = this.#current();
|
|
65
|
+
if (!record)
|
|
66
|
+
return;
|
|
67
|
+
if (record.steps.length < MAX_STEPS)
|
|
68
|
+
record.steps = [...record.steps, { stage, status, at: this.#now() }];
|
|
69
|
+
else
|
|
70
|
+
record.truncated = true;
|
|
71
|
+
}
|
|
72
|
+
dispatch(result) {
|
|
73
|
+
const record = this.#current();
|
|
74
|
+
if (!record)
|
|
75
|
+
return;
|
|
76
|
+
record.route ??= result.matched ? 'command' : 'unmatched';
|
|
77
|
+
if (result.command)
|
|
78
|
+
record.command = result.command.slice(0, 200);
|
|
79
|
+
if (result.status)
|
|
80
|
+
record.dispatchStatus = result.status;
|
|
81
|
+
if (result.status === 'limited' && result.limit)
|
|
82
|
+
record.limit = Object.freeze({ reason: result.limit.reason,
|
|
83
|
+
...(result.limit.retryAfterMs !== undefined ? { retryAfterMs: result.limit.retryAfterMs } : {}) });
|
|
84
|
+
this.step('dispatch', result.status ?? record.route);
|
|
85
|
+
}
|
|
86
|
+
route(route) {
|
|
87
|
+
const record = this.#current();
|
|
88
|
+
if (record)
|
|
89
|
+
record.route = route;
|
|
90
|
+
}
|
|
91
|
+
delivery(generation, conversation, receipt, rendering) {
|
|
92
|
+
const record = this.#current();
|
|
93
|
+
if (!record || record.generation !== generation)
|
|
94
|
+
return;
|
|
95
|
+
const identity = boundedConversation(conversation);
|
|
96
|
+
if (!identity) {
|
|
97
|
+
record.truncated = true;
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (record.deliveries.length < MAX_DELIVERIES)
|
|
101
|
+
record.deliveries = [...record.deliveries, {
|
|
102
|
+
conversation: identity,
|
|
103
|
+
status: receipt.status,
|
|
104
|
+
...(receipt.failure ? { failureCode: safeCode(receipt.failure.code), deliveryUnknown: receipt.failure.deliveryUnknown === true } : {}),
|
|
105
|
+
...(rendering ? { rendering: { forms: [...rendering.forms], fallbacks: [...rendering.fallbacks] } } : {}),
|
|
106
|
+
}];
|
|
107
|
+
else
|
|
108
|
+
record.truncated = true;
|
|
109
|
+
this.step('delivery', receipt.failure?.deliveryUnknown ? 'unknown' : receipt.status);
|
|
110
|
+
}
|
|
111
|
+
list(options = {}) {
|
|
112
|
+
this.#prune();
|
|
113
|
+
const limit = Number.isSafeInteger(options.limit) ? Math.min(100, Math.max(1, options.limit)) : 50;
|
|
114
|
+
const key = options.conversation ? conversationKey(options.conversation) : undefined;
|
|
115
|
+
return Object.freeze([...this.#records.values()].reverse()
|
|
116
|
+
.filter((record) => key === undefined || conversationKey(record.conversation) === key)
|
|
117
|
+
.filter((record) => options.messageId === undefined || record.messageId === options.messageId)
|
|
118
|
+
.slice(0, limit).map(snapshot));
|
|
119
|
+
}
|
|
120
|
+
get(id) {
|
|
121
|
+
this.#prune();
|
|
122
|
+
const record = this.#records.get(id);
|
|
123
|
+
return record ? snapshot(record) : undefined;
|
|
124
|
+
}
|
|
125
|
+
#current() {
|
|
126
|
+
const scope = this.#operation.getStore();
|
|
127
|
+
return scope?.active ? scope.record : undefined;
|
|
128
|
+
}
|
|
129
|
+
#now() { return (this.options.now ?? Date.now)(); }
|
|
130
|
+
#prune() {
|
|
131
|
+
const threshold = this.#now() - (this.options.ttlMs ?? 15 * 60_000);
|
|
132
|
+
for (const [id, record] of this.#records)
|
|
133
|
+
if ((record.endedAt ?? record.startedAt) < threshold)
|
|
134
|
+
this.#records.delete(id);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
function safeCode(code) {
|
|
138
|
+
return deliveryCodes.has(code) ? code : 'delivery_failed';
|
|
139
|
+
}
|
|
140
|
+
const deliveryCodes = new Set(['outbound_payload_rejected', 'outbound_middleware_failed', 'outbound_delivery_incomplete',
|
|
141
|
+
'delivery_unconfirmed', 'outbound_unsupported', 'platform_rejected', 'endpoint_send_failed', 'endpoint_not_found',
|
|
142
|
+
'endpoint_inactive', 'endpoint_disconnected', 'endpoint_timeout', 'unsupported_operation', 'unsupported_media',
|
|
143
|
+
'invalid_destination', 'invalid_payload', 'invalid_recipient', 'invalid_response', 'invalid_message_id',
|
|
144
|
+
'empty_message', 'http_error', 'media_download_failed', 'partial_delivery', 'session_unavailable',
|
|
145
|
+
'token_unavailable', 'endpoint_identity_mismatch', 'card_context_required', 'card_template_required']);
|
|
146
|
+
function freezeConversation(conversation) {
|
|
147
|
+
return Object.freeze({ endpoint: Object.freeze({ id: conversation.endpoint.id, adapter: conversation.endpoint.adapter }),
|
|
148
|
+
kind: conversation.kind, id: conversation.id,
|
|
149
|
+
...(conversation.parent ? { parent: Object.freeze({ kind: conversation.parent.kind, id: conversation.parent.id }) } : {}),
|
|
150
|
+
...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
function boundedIdentifier(value) {
|
|
154
|
+
return typeof value === 'string' && value.length > 0 && value.length <= 2048;
|
|
155
|
+
}
|
|
156
|
+
function boundedConversation(conversation) {
|
|
157
|
+
try {
|
|
158
|
+
const kind = (value) => value === 'private' || value === 'group' || value === 'channel';
|
|
159
|
+
if (!conversation || !boundedIdentifier(conversation.endpoint?.id) || !boundedIdentifier(conversation.endpoint?.adapter)
|
|
160
|
+
|| !kind(conversation.kind) || !boundedIdentifier(conversation.id)
|
|
161
|
+
|| (conversation.parent !== undefined && (!kind(conversation.parent?.kind) || !boundedIdentifier(conversation.parent?.id)))
|
|
162
|
+
|| (conversation.threadId !== undefined && !boundedIdentifier(conversation.threadId)))
|
|
163
|
+
return undefined;
|
|
164
|
+
const copy = freezeConversation(conversation);
|
|
165
|
+
return JSON.stringify(copy).length <= 8192 ? copy : undefined;
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
return undefined;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function conversationKey(conversation) {
|
|
172
|
+
return JSON.stringify([conversation.endpoint.id, conversation.endpoint.adapter, conversation.kind, conversation.id,
|
|
173
|
+
conversation.parent?.kind, conversation.parent?.id, conversation.threadId]);
|
|
174
|
+
}
|
|
175
|
+
function snapshot(record) {
|
|
176
|
+
return Object.freeze({ ...record, steps: Object.freeze(record.steps.map(step => Object.freeze({ ...step }))),
|
|
177
|
+
deliveries: Object.freeze(record.deliveries.map(delivery => Object.freeze({ ...delivery,
|
|
178
|
+
...(delivery.rendering ? { rendering: Object.freeze({ forms: Object.freeze([...delivery.rendering.forms]),
|
|
179
|
+
fallbacks: Object.freeze([...delivery.rendering.fallbacks]) }) } : {}),
|
|
180
|
+
}))),
|
|
181
|
+
});
|
|
182
|
+
}
|
|
@@ -1,11 +1,19 @@
|
|
|
1
|
-
import type { UserInteractionFactory } from '@zhin.js/
|
|
2
|
-
import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
3
|
-
import type { Message, MessageDispatchResult } from './contracts.js';
|
|
1
|
+
import type { UserInteractionFactory } from '@zhin.js/im-contract';
|
|
2
|
+
import type { PluginId, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
3
|
+
import type { Message, MessageDispatchResult, SendContent } from './contracts.js';
|
|
4
4
|
/**
|
|
5
5
|
* 命令前缀解析器:返回该消息要求的命令前缀。
|
|
6
6
|
* `''` 表示无前缀(任意文本都尝试按命令匹配)。
|
|
7
7
|
*/
|
|
8
8
|
export type CommandPrefixResolver = (message: Message, snapshot: RuntimeSnapshot) => string;
|
|
9
|
+
/** @internal Keep command facts separate from the author of the rendered reply. */
|
|
10
|
+
export interface MessageDispatchOutcome {
|
|
11
|
+
readonly dispatch: MessageDispatchResult;
|
|
12
|
+
readonly reply?: {
|
|
13
|
+
readonly owner: PluginId;
|
|
14
|
+
readonly content: SendContent;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
9
17
|
/**
|
|
10
18
|
* 默认解析:读消息所属适配器实例 config 的 `commandPrefix`(默认 `''`);
|
|
11
19
|
* 实例声明 `endpoints` 数组时,按消息 endpoint 名找 entry,`entry.commandPrefix` 覆盖顶层。
|
|
@@ -14,5 +22,11 @@ export declare const defaultCommandPrefixResolver: CommandPrefixResolver;
|
|
|
14
22
|
export declare class MessageDispatcher {
|
|
15
23
|
private readonly resolvePrefix;
|
|
16
24
|
constructor(resolvePrefix?: CommandPrefixResolver);
|
|
17
|
-
|
|
25
|
+
commandEnvironment(message: Message, snapshot: RuntimeSnapshot): Readonly<{
|
|
26
|
+
prefix: string;
|
|
27
|
+
menu?: string;
|
|
28
|
+
}>;
|
|
29
|
+
dispatch(message: Message, snapshot: RuntimeSnapshot, interactionFactory?: UserInteractionFactory, observe?: (stage: 'prefix' | 'dispatch', status: 'mismatch' | 'matched' | 'empty_input' | 'commands_unavailable' | 'started') => void): Promise<MessageDispatchResult>;
|
|
30
|
+
/** @internal The inbound runtime retains reply authorship without changing command facts. */
|
|
31
|
+
dispatchWithReply(message: Message, snapshot: RuntimeSnapshot, interactionFactory?: UserInteractionFactory, observe?: (stage: 'prefix' | 'dispatch', status: 'mismatch' | 'matched' | 'empty_input' | 'commands_unavailable' | 'started') => void): Promise<MessageDispatchOutcome>;
|
|
18
32
|
}
|