@zhin.js/core 1.1.34 → 1.1.37
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 +84 -142
- package/lib/built/ai-access.d.ts +36 -0
- package/lib/built/ai-access.js +46 -0
- package/lib/built/ai-outbound/extensions/onebot-keyboard.d.ts +2 -0
- package/lib/built/ai-outbound/extensions/onebot-keyboard.js +67 -0
- package/lib/built/ai-outbound/extensions/qq-message.d.ts +3 -0
- package/lib/built/ai-outbound/extensions/qq-message.js +23 -0
- package/lib/built/ai-outbound/index.d.ts +8 -0
- package/lib/built/ai-outbound/index.js +8 -0
- package/lib/built/ai-outbound/parse.d.ts +13 -0
- package/lib/built/ai-outbound/parse.js +104 -0
- package/lib/built/ai-outbound/plain-mention-rewrite.d.ts +6 -0
- package/lib/built/ai-outbound/plain-mention-rewrite.js +37 -0
- package/lib/built/ai-outbound/prompt.d.ts +11 -0
- package/lib/built/ai-outbound/prompt.js +44 -0
- package/lib/built/ai-outbound/resolve.d.ts +4 -0
- package/lib/built/ai-outbound/resolve.js +64 -0
- package/lib/built/ai-outbound/structured-detect.d.ts +3 -0
- package/lib/built/ai-outbound/structured-detect.js +6 -0
- package/lib/built/ai-outbound/types.d.ts +49 -0
- package/lib/built/ai-outbound/types.js +5 -0
- package/lib/built/ai-trigger.d.ts +12 -17
- package/lib/built/ai-trigger.js +39 -70
- package/lib/built/common-adapter-tools.d.ts +33 -29
- package/lib/built/common-adapter-tools.js +79 -67
- package/lib/built/generated-qrcode.d.ts +24 -0
- package/lib/built/generated-qrcode.js +45 -0
- package/lib/built/generic-segment-mapper.d.ts +4 -0
- package/lib/built/generic-segment-mapper.js +190 -0
- package/lib/built/html-segment-fallback.d.ts +2 -5
- package/lib/built/html-segment-fallback.js +0 -16
- package/lib/built/html-to-text.d.ts +0 -1
- package/lib/built/html-to-text.js +15 -15
- package/lib/built/interactive-segments/action.d.ts +17 -0
- package/lib/built/interactive-segments/action.js +69 -0
- package/lib/built/interactive-segments/button-spec.d.ts +10 -0
- package/lib/built/interactive-segments/button-spec.js +21 -0
- package/lib/built/interactive-segments/index.d.ts +6 -0
- package/lib/built/interactive-segments/index.js +6 -0
- package/lib/built/interactive-segments/keyboard-segment.d.ts +10 -0
- package/lib/built/interactive-segments/keyboard-segment.js +11 -0
- package/lib/built/interactive-segments/onebot-keyboard.d.ts +6 -0
- package/lib/built/interactive-segments/onebot-keyboard.js +49 -0
- package/lib/built/interactive-segments/resolve.d.ts +14 -0
- package/lib/built/interactive-segments/resolve.js +109 -0
- package/lib/built/interactive-segments/types.d.ts +45 -0
- package/lib/built/interactive-segments/types.js +9 -0
- package/lib/built/login-assist.d.ts +43 -16
- package/lib/built/login-assist.js +113 -11
- package/lib/built/message-enrich.d.ts +32 -0
- package/lib/built/message-enrich.js +67 -0
- package/lib/built/outbound-media-utils.d.ts +9 -0
- package/lib/built/outbound-media-utils.js +62 -0
- package/lib/built/queue-im-field-contract.d.ts +7 -2
- package/lib/built/queue-im-field-contract.js +13 -4
- package/lib/built/rich-segments/markdown-to-text.d.ts +3 -0
- package/lib/built/rich-segments/markdown-to-text.js +27 -0
- package/lib/built/roles.d.ts +4 -5
- package/lib/built/roles.js +4 -5
- package/lib/built/segment-contract/assert.d.ts +7 -0
- package/lib/built/segment-contract/assert.js +39 -0
- package/lib/built/segment-contract/delivery.d.ts +5 -0
- package/lib/built/segment-contract/delivery.js +40 -0
- package/lib/built/segment-contract/image.d.ts +5 -0
- package/lib/built/segment-contract/image.js +10 -0
- package/lib/built/segment-contract/index.d.ts +10 -0
- package/lib/built/segment-contract/index.js +9 -0
- package/lib/built/segment-contract/json-schema.d.ts +28 -0
- package/lib/built/segment-contract/json-schema.js +128 -0
- package/lib/built/segment-contract/media.d.ts +12 -0
- package/lib/built/segment-contract/media.js +22 -0
- package/lib/built/segment-contract/mention.d.ts +10 -0
- package/lib/built/segment-contract/mention.js +26 -0
- package/lib/built/segment-contract/preview.d.ts +3 -0
- package/lib/built/segment-contract/preview.js +159 -0
- package/lib/built/segment-contract/text.d.ts +7 -0
- package/lib/built/segment-contract/text.js +34 -0
- package/lib/built/segment-contract/types.d.ts +58 -0
- package/lib/built/segment-contract/types.js +1 -0
- package/lib/built/segment-contract/validate.d.ts +229 -0
- package/lib/built/segment-contract/validate.js +172 -0
- package/lib/built/tool-access.d.ts +5 -0
- package/lib/built/tool-access.js +17 -0
- package/lib/built/user-interaction.d.ts +30 -0
- package/lib/built/user-interaction.js +244 -0
- package/lib/component.d.ts +0 -1
- package/lib/component.js +30 -14
- package/lib/errors.d.ts +2 -3
- package/lib/errors.js +4 -5
- package/lib/feature/adapter.d.ts +2 -0
- package/lib/feature/adapter.js +2 -0
- package/lib/feature/command.d.ts +2 -0
- package/lib/feature/command.js +2 -0
- package/lib/feature/component.d.ts +2 -0
- package/lib/feature/component.js +2 -0
- package/lib/feature/handler.d.ts +48 -0
- package/lib/feature/handler.js +26 -0
- package/lib/feature/middleware.d.ts +2 -0
- package/lib/feature/middleware.js +2 -0
- package/lib/im-scene.d.ts +29 -0
- package/lib/im-scene.js +75 -0
- package/lib/im-session-id.d.ts +39 -0
- package/lib/im-session-id.js +47 -0
- package/lib/index.d.ts +29 -36
- package/lib/index.js +27 -41
- package/lib/jsx-dev-runtime.d.ts +0 -1
- package/lib/jsx-dev-runtime.js +0 -1
- package/lib/jsx-runtime.d.ts +1 -1
- package/lib/jsx-runtime.js +0 -1
- package/lib/jsx.d.ts +19 -22
- package/lib/jsx.js +0 -1
- package/lib/message.d.ts +17 -12
- package/lib/message.js +16 -13
- package/lib/models/system-log.d.ts +0 -3
- package/lib/models/system-log.js +1 -9
- package/lib/models/user.d.ts +0 -3
- package/lib/models/user.js +1 -8
- package/lib/notice.d.ts +16 -60
- package/lib/notice.js +1 -4
- package/lib/plugin-runtime/im/contracts.d.ts +191 -0
- package/lib/plugin-runtime/im/contracts.js +169 -0
- package/lib/plugin-runtime/im/conversation-runtime.d.ts +19 -0
- package/lib/plugin-runtime/im/conversation-runtime.js +312 -0
- package/lib/plugin-runtime/im/endpoint-runtime.d.ts +79 -0
- package/lib/plugin-runtime/im/endpoint-runtime.js +162 -0
- package/lib/plugin-runtime/im/im-runtime.d.ts +84 -0
- package/lib/plugin-runtime/im/im-runtime.js +201 -0
- package/lib/plugin-runtime/im/inbound-runtime.d.ts +31 -0
- package/lib/plugin-runtime/im/inbound-runtime.js +252 -0
- package/lib/plugin-runtime/im/index.d.ts +11 -0
- package/lib/plugin-runtime/im/index.js +9 -0
- package/lib/plugin-runtime/im/ingress-route.d.ts +10 -0
- package/lib/plugin-runtime/im/ingress-route.js +10 -0
- package/lib/plugin-runtime/im/interaction-runtime.d.ts +23 -0
- package/lib/plugin-runtime/im/interaction-runtime.js +181 -0
- package/lib/plugin-runtime/im/interactive-router.d.ts +17 -0
- package/lib/plugin-runtime/im/interactive-router.js +98 -0
- package/lib/plugin-runtime/im/login-assist-host.d.ts +6 -0
- package/lib/plugin-runtime/im/login-assist-host.js +6 -0
- package/lib/plugin-runtime/im/message-bus.d.ts +38 -0
- package/lib/plugin-runtime/im/message-bus.js +40 -0
- package/lib/plugin-runtime/im/message-dispatcher.d.ts +18 -0
- package/lib/plugin-runtime/im/message-dispatcher.js +107 -0
- package/lib/plugin-runtime/im/message-events.d.ts +26 -0
- package/lib/plugin-runtime/im/message-events.js +61 -0
- package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +19 -0
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +165 -0
- package/lib/plugin-runtime/im/outbound-renderer.d.ts +7 -0
- package/lib/plugin-runtime/im/outbound-renderer.js +70 -0
- package/lib/plugin-runtime/im/outbound-segments.d.ts +71 -0
- package/lib/plugin-runtime/im/outbound-segments.js +219 -0
- package/lib/plugin-runtime/im/public-api.d.ts +6 -0
- package/lib/plugin-runtime/im/public-api.js +6 -0
- package/lib/plugin-runtime/im/runtime-middleware.d.ts +3 -0
- package/lib/plugin-runtime/im/runtime-middleware.js +13 -0
- package/lib/request.d.ts +17 -62
- package/lib/request.js +0 -4
- package/lib/side-event/base.d.ts +51 -0
- package/lib/side-event/base.js +30 -0
- package/lib/side-event/dispatch.d.ts +15 -0
- package/lib/side-event/dispatch.js +140 -0
- package/lib/side-event/index.d.ts +4 -0
- package/lib/side-event/index.js +4 -0
- package/lib/side-event/normalize.d.ts +38 -0
- package/lib/side-event/normalize.js +111 -0
- package/lib/side-event/types.d.ts +23 -0
- package/lib/side-event/types.js +55 -0
- package/lib/system-event.d.ts +14 -0
- package/lib/system-event.js +7 -0
- package/lib/types.d.ts +35 -193
- package/lib/types.js +0 -1
- package/lib/utils.d.ts +81 -6
- package/lib/utils.js +54 -25
- package/package.json +94 -16
- package/lib/adapter.d.ts +0 -96
- package/lib/adapter.d.ts.map +0 -1
- package/lib/adapter.js +0 -217
- package/lib/adapter.js.map +0 -1
- package/lib/agent-prompt.d.ts +0 -37
- package/lib/agent-prompt.d.ts.map +0 -1
- package/lib/agent-prompt.js +0 -2
- package/lib/agent-prompt.js.map +0 -1
- package/lib/bot.d.ts +0 -38
- package/lib/bot.d.ts.map +0 -1
- package/lib/bot.js +0 -2
- package/lib/bot.js.map +0 -1
- package/lib/built/adapter-process.d.ts +0 -43
- package/lib/built/adapter-process.d.ts.map +0 -1
- package/lib/built/adapter-process.js +0 -81
- package/lib/built/adapter-process.js.map +0 -1
- package/lib/built/agent-preset.d.ts +0 -65
- package/lib/built/agent-preset.d.ts.map +0 -1
- package/lib/built/agent-preset.js +0 -80
- package/lib/built/agent-preset.js.map +0 -1
- package/lib/built/ai-trigger.d.ts.map +0 -1
- package/lib/built/ai-trigger.js.map +0 -1
- package/lib/built/command.d.ts +0 -68
- package/lib/built/command.d.ts.map +0 -1
- package/lib/built/command.js +0 -92
- package/lib/built/command.js.map +0 -1
- package/lib/built/common-adapter-tools.d.ts.map +0 -1
- package/lib/built/common-adapter-tools.js.map +0 -1
- package/lib/built/component.d.ts +0 -69
- package/lib/built/component.d.ts.map +0 -1
- package/lib/built/component.js +0 -99
- package/lib/built/component.js.map +0 -1
- package/lib/built/config.d.ts +0 -99
- package/lib/built/config.d.ts.map +0 -1
- package/lib/built/config.js +0 -355
- package/lib/built/config.js.map +0 -1
- package/lib/built/cron.d.ts +0 -75
- package/lib/built/cron.d.ts.map +0 -1
- package/lib/built/cron.js +0 -122
- package/lib/built/cron.js.map +0 -1
- package/lib/built/database.d.ts +0 -66
- package/lib/built/database.d.ts.map +0 -1
- package/lib/built/database.js +0 -100
- package/lib/built/database.js.map +0 -1
- package/lib/built/dispatcher.d.ts +0 -139
- package/lib/built/dispatcher.d.ts.map +0 -1
- package/lib/built/dispatcher.js +0 -361
- package/lib/built/dispatcher.js.map +0 -1
- package/lib/built/html-segment-fallback.d.ts.map +0 -1
- package/lib/built/html-segment-fallback.js.map +0 -1
- package/lib/built/html-to-text.d.ts.map +0 -1
- package/lib/built/html-to-text.js.map +0 -1
- package/lib/built/inbound-runner.d.ts +0 -23
- package/lib/built/inbound-runner.d.ts.map +0 -1
- package/lib/built/inbound-runner.js +0 -37
- package/lib/built/inbound-runner.js.map +0 -1
- package/lib/built/login-assist.d.ts.map +0 -1
- package/lib/built/login-assist.js.map +0 -1
- package/lib/built/mcp-mesh-registrar.d.ts +0 -9
- package/lib/built/mcp-mesh-registrar.d.ts.map +0 -1
- package/lib/built/mcp-mesh-registrar.js +0 -17
- package/lib/built/mcp-mesh-registrar.js.map +0 -1
- package/lib/built/message-filter.d.ts +0 -177
- package/lib/built/message-filter.d.ts.map +0 -1
- package/lib/built/message-filter.js +0 -241
- package/lib/built/message-filter.js.map +0 -1
- package/lib/built/permission.d.ts +0 -55
- package/lib/built/permission.d.ts.map +0 -1
- package/lib/built/permission.js +0 -112
- package/lib/built/permission.js.map +0 -1
- package/lib/built/prepend-quote-context.d.ts +0 -35
- package/lib/built/prepend-quote-context.d.ts.map +0 -1
- package/lib/built/prepend-quote-context.js +0 -131
- package/lib/built/prepend-quote-context.js.map +0 -1
- package/lib/built/queue-im-field-contract.d.ts.map +0 -1
- package/lib/built/queue-im-field-contract.js.map +0 -1
- package/lib/built/roles.d.ts.map +0 -1
- package/lib/built/roles.js.map +0 -1
- package/lib/built/runtime-io.d.ts +0 -10
- package/lib/built/runtime-io.d.ts.map +0 -1
- package/lib/built/runtime-io.js +0 -68
- package/lib/built/runtime-io.js.map +0 -1
- package/lib/built/schema-feature.d.ts +0 -78
- package/lib/built/schema-feature.d.ts.map +0 -1
- package/lib/built/schema-feature.js +0 -132
- package/lib/built/schema-feature.js.map +0 -1
- package/lib/built/skill.d.ts +0 -121
- package/lib/built/skill.d.ts.map +0 -1
- package/lib/built/skill.js +0 -152
- package/lib/built/skill.js.map +0 -1
- package/lib/built/tool.d.ts +0 -150
- package/lib/built/tool.d.ts.map +0 -1
- package/lib/built/tool.js +0 -383
- package/lib/built/tool.js.map +0 -1
- package/lib/command.d.ts +0 -42
- package/lib/command.d.ts.map +0 -1
- package/lib/command.js +0 -75
- package/lib/command.js.map +0 -1
- package/lib/component.d.ts.map +0 -1
- package/lib/component.js.map +0 -1
- package/lib/errors.d.ts.map +0 -1
- package/lib/errors.js.map +0 -1
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js.map +0 -1
- package/lib/jsx-dev-runtime.d.ts.map +0 -1
- package/lib/jsx-dev-runtime.js.map +0 -1
- package/lib/jsx-runtime.d.ts.map +0 -1
- package/lib/jsx-runtime.js.map +0 -1
- package/lib/jsx.d.ts.map +0 -1
- package/lib/jsx.js.map +0 -1
- package/lib/message-quote.d.ts +0 -11
- package/lib/message-quote.d.ts.map +0 -1
- package/lib/message-quote.js +0 -91
- package/lib/message-quote.js.map +0 -1
- package/lib/message.d.ts.map +0 -1
- package/lib/message.js.map +0 -1
- package/lib/models/system-log.d.ts.map +0 -1
- package/lib/models/system-log.js.map +0 -1
- package/lib/models/user.d.ts.map +0 -1
- package/lib/models/user.js.map +0 -1
- package/lib/notice.d.ts.map +0 -1
- package/lib/notice.js.map +0 -1
- package/lib/plugin.d.ts +0 -258
- package/lib/plugin.d.ts.map +0 -1
- package/lib/plugin.js +0 -688
- package/lib/plugin.js.map +0 -1
- package/lib/prompt.d.ts +0 -118
- package/lib/prompt.d.ts.map +0 -1
- package/lib/prompt.js +0 -244
- package/lib/prompt.js.map +0 -1
- package/lib/request.d.ts.map +0 -1
- package/lib/request.js.map +0 -1
- package/lib/scheduler/scheduler.d.ts +0 -49
- package/lib/scheduler/scheduler.d.ts.map +0 -1
- package/lib/scheduler/scheduler.js +0 -352
- package/lib/scheduler/scheduler.js.map +0 -1
- package/lib/scheduler/types.d.ts +0 -71
- package/lib/scheduler/types.d.ts.map +0 -1
- package/lib/scheduler/types.js +0 -8
- package/lib/scheduler/types.js.map +0 -1
- package/lib/tool-zod.d.ts +0 -28
- package/lib/tool-zod.d.ts.map +0 -1
- package/lib/tool-zod.js +0 -98
- package/lib/tool-zod.js.map +0 -1
- package/lib/types-generator.d.ts +0 -6
- package/lib/types-generator.d.ts.map +0 -1
- package/lib/types-generator.js +0 -72
- package/lib/types-generator.js.map +0 -1
- package/lib/types.d.ts.map +0 -1
- package/lib/types.js.map +0 -1
- package/lib/utils.d.ts.map +0 -1
- package/lib/utils.js.map +0 -1
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { htmlRendererToken, } from '@zhin.js/plugin-runtime';
|
|
2
|
+
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
3
|
+
import { createOutboundEnvelope } from './contracts.js';
|
|
4
|
+
import { OutboundRenderer } from './outbound-renderer.js';
|
|
5
|
+
import { applyOutboundInteractivePolicy, applyOutboundMarkdownPolicy, normalizeOutboundPayload, resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundMediaPolicy, } from './outbound-segments.js';
|
|
6
|
+
import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
|
|
7
|
+
import { adapterTypeName, requireAdapters } from './endpoint-runtime.js';
|
|
8
|
+
import { formatConversationLog, previewMessageContent } from './message-events.js';
|
|
9
|
+
import { runRuntimeMiddleware } from './runtime-middleware.js';
|
|
10
|
+
const logger = getLogger('im.outbound');
|
|
11
|
+
/** Owns rendering, policy projection, middleware, Endpoint delivery, and delivery facts. */
|
|
12
|
+
export class OutboundDeliveryRuntime {
|
|
13
|
+
context;
|
|
14
|
+
#renderer;
|
|
15
|
+
constructor(context, renderer = new OutboundRenderer()) {
|
|
16
|
+
this.context = context;
|
|
17
|
+
this.#renderer = renderer;
|
|
18
|
+
}
|
|
19
|
+
async deliver(request, snapshot) {
|
|
20
|
+
const adapter = request.conversation.endpoint.id;
|
|
21
|
+
let initialPayload;
|
|
22
|
+
try {
|
|
23
|
+
const rendered = await this.#renderer.render(request.content, request.requester, snapshot, request.conversation, request.incoming);
|
|
24
|
+
initialPayload = await prepareOutboundPayload(rendered, request.conversation, snapshot);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return rejectedDeliveryReceipt('outbound_payload_rejected');
|
|
28
|
+
}
|
|
29
|
+
let adapters;
|
|
30
|
+
try {
|
|
31
|
+
adapters = requireAdapters(snapshot);
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
return receiptFromEndpointError(error);
|
|
35
|
+
}
|
|
36
|
+
const envelope = createOutboundEnvelope({
|
|
37
|
+
conversation: request.conversation,
|
|
38
|
+
requester: request.requester,
|
|
39
|
+
generation: snapshot.generation,
|
|
40
|
+
clientAdapter: adapters.clientAdapter(adapter),
|
|
41
|
+
}, initialPayload, () => adapters.clientById(adapter));
|
|
42
|
+
let terminalEntered = false;
|
|
43
|
+
let receipt;
|
|
44
|
+
try {
|
|
45
|
+
await runRuntimeMiddleware(snapshot, envelope, async () => {
|
|
46
|
+
terminalEntered = true;
|
|
47
|
+
let payload;
|
|
48
|
+
try {
|
|
49
|
+
payload = await prepareOutboundPayload(envelope.payload, request.conversation, snapshot, (map) => this.context.rememberFallback(request.conversation, snapshot.generation, map));
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
receipt = rejectedDeliveryReceipt('outbound_payload_rejected');
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
const result = await requireAdapters(snapshot).send(adapter, {
|
|
57
|
+
conversation: request.conversation,
|
|
58
|
+
payload,
|
|
59
|
+
});
|
|
60
|
+
receipt = receiptFromEndpointResult(result, request.conversation);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
receipt = receiptFromEndpointError(error);
|
|
64
|
+
}
|
|
65
|
+
if (receipt.status === 'sent') {
|
|
66
|
+
await this.context.record(request, receipt);
|
|
67
|
+
this.context.publish({
|
|
68
|
+
direction: 'outbound',
|
|
69
|
+
conversation: request.conversation,
|
|
70
|
+
requester: request.requester,
|
|
71
|
+
contentPreview: previewMessageContent(payload),
|
|
72
|
+
...(receipt.message?.id ? { messageId: receipt.message.id } : {}),
|
|
73
|
+
timestamp: Date.now(),
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
}, 'outbound');
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return receipt ?? failedDeliveryReceipt('outbound_middleware_failed');
|
|
80
|
+
}
|
|
81
|
+
if (!terminalEntered) {
|
|
82
|
+
logger.debug(formatCompact({
|
|
83
|
+
op: 'replychain_runtime_send',
|
|
84
|
+
status: 'suppressed',
|
|
85
|
+
reason: 'middleware_stopped_before_terminal',
|
|
86
|
+
conv: formatConversationLog(request.conversation),
|
|
87
|
+
}));
|
|
88
|
+
return suppressedDeliveryReceipt();
|
|
89
|
+
}
|
|
90
|
+
logger.debug(formatCompact({
|
|
91
|
+
op: 'replychain_runtime_send',
|
|
92
|
+
status: receipt?.status ?? 'missing',
|
|
93
|
+
code: receipt?.failure?.code,
|
|
94
|
+
conv: formatConversationLog(request.conversation),
|
|
95
|
+
}));
|
|
96
|
+
return receipt ?? failedDeliveryReceipt('outbound_delivery_incomplete');
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
export function failedDeliveryReceipt(code, retryable = false) {
|
|
100
|
+
return Object.freeze({
|
|
101
|
+
status: 'failed',
|
|
102
|
+
failure: Object.freeze({
|
|
103
|
+
code,
|
|
104
|
+
message: 'Outbound delivery failed.',
|
|
105
|
+
...(retryable ? { retryable: true } : {}),
|
|
106
|
+
}),
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
async function prepareOutboundPayload(rendered, conversation, snapshot, rememberInteractiveFallback) {
|
|
110
|
+
const adapter = conversation.endpoint.id;
|
|
111
|
+
const directHtml = isDirectHtmlConsumer(snapshot, adapter);
|
|
112
|
+
const markdownResolved = applyOutboundMarkdownPolicy(rendered, resolveOutboundMarkdownPolicy(adapter, snapshot));
|
|
113
|
+
let payload = directHtml
|
|
114
|
+
? markdownResolved
|
|
115
|
+
: await normalizeOutboundPayload(markdownResolved, resolveHtmlRenderer(snapshot), {
|
|
116
|
+
mediaPolicy: resolveOutboundMediaPolicy(adapter, snapshot),
|
|
117
|
+
});
|
|
118
|
+
if (rememberInteractiveFallback) {
|
|
119
|
+
payload = applyOutboundInteractivePolicy(payload, resolveOutboundInteractivePolicy(adapter, snapshot), rememberInteractiveFallback);
|
|
120
|
+
}
|
|
121
|
+
if (!directHtml && Array.isArray(payload))
|
|
122
|
+
assertCanonicalSegments(payload);
|
|
123
|
+
return payload;
|
|
124
|
+
}
|
|
125
|
+
function resolveHtmlRenderer(snapshot) {
|
|
126
|
+
const host = snapshot.resources.get(snapshot.root)?.get(htmlRendererToken.id);
|
|
127
|
+
return host && typeof host.render === 'function'
|
|
128
|
+
? host
|
|
129
|
+
: undefined;
|
|
130
|
+
}
|
|
131
|
+
function isDirectHtmlConsumer(snapshot, adapter) {
|
|
132
|
+
const owner = snapshot.capabilities.get(adapter)?.owner;
|
|
133
|
+
const packageName = owner ? snapshot.tree.get(owner)?.packageName : undefined;
|
|
134
|
+
return adapterTypeName(packageName) === 'sandbox';
|
|
135
|
+
}
|
|
136
|
+
function receiptFromEndpointResult(messageId, conversation) {
|
|
137
|
+
return Object.freeze({
|
|
138
|
+
status: 'sent',
|
|
139
|
+
message: Object.freeze({ conversation, id: messageId }),
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
function receiptFromEndpointError(error) {
|
|
143
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
144
|
+
if (/Unknown Adapter Endpoint|does not support outbound/u.test(message)) {
|
|
145
|
+
return unsupportedDeliveryReceipt('outbound_unsupported');
|
|
146
|
+
}
|
|
147
|
+
if (/not active/u.test(message))
|
|
148
|
+
return failedDeliveryReceipt('endpoint_inactive', true);
|
|
149
|
+
return failedDeliveryReceipt('endpoint_send_failed', true);
|
|
150
|
+
}
|
|
151
|
+
function suppressedDeliveryReceipt() {
|
|
152
|
+
return Object.freeze({ status: 'suppressed' });
|
|
153
|
+
}
|
|
154
|
+
function unsupportedDeliveryReceipt(code) {
|
|
155
|
+
return Object.freeze({
|
|
156
|
+
status: 'unsupported',
|
|
157
|
+
failure: Object.freeze({ code, message: 'Outbound delivery is not supported.' }),
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
function rejectedDeliveryReceipt(code) {
|
|
161
|
+
return Object.freeze({
|
|
162
|
+
status: 'rejected',
|
|
163
|
+
failure: Object.freeze({ code, message: 'Outbound payload was rejected.' }),
|
|
164
|
+
});
|
|
165
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { PluginId, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
2
|
+
import type { ConversationRef } from '@zhin.js/im-contract';
|
|
3
|
+
import { type IncomingContext, type SendContent } from './contracts.js';
|
|
4
|
+
export declare class OutboundRenderer {
|
|
5
|
+
#private;
|
|
6
|
+
render(content: SendContent, requester: PluginId, snapshot: RuntimeSnapshot, conversation?: ConversationRef, incoming?: IncomingContext): Promise<unknown>;
|
|
7
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { componentHostToken } from '@zhin.js/plugin-runtime';
|
|
2
|
+
import { componentFeatureId, isComponentIndex, } from '@zhin.js/component';
|
|
3
|
+
import { isComponentCall, isRawContent, isSegmentContent, } from './contracts.js';
|
|
4
|
+
const maxComponentDepth = 32;
|
|
5
|
+
const TEMPLATE_MARKER = '${';
|
|
6
|
+
export class OutboundRenderer {
|
|
7
|
+
async render(content, requester, snapshot, conversation, incoming) {
|
|
8
|
+
const host = resolveComponentHost(snapshot);
|
|
9
|
+
const ctx = conversation ? buildTemplateContext(conversation, incoming) : undefined;
|
|
10
|
+
return this.#render(content, requester, snapshot, host, ctx, 0);
|
|
11
|
+
}
|
|
12
|
+
async #render(content, requester, snapshot, host, ctx, depth) {
|
|
13
|
+
if (depth > maxComponentDepth)
|
|
14
|
+
throw new Error('Component render depth exceeded 32');
|
|
15
|
+
if (typeof content === 'string')
|
|
16
|
+
return compileText(content, host, ctx);
|
|
17
|
+
if (Array.isArray(content)) {
|
|
18
|
+
return Promise.all(content.map((item) => this.#render(item, requester, snapshot, host, ctx, depth)));
|
|
19
|
+
}
|
|
20
|
+
if (isRawContent(content))
|
|
21
|
+
return content.payload;
|
|
22
|
+
if (isSegmentContent(content)) {
|
|
23
|
+
if (content.type === 'text') {
|
|
24
|
+
const text = content.data?.text;
|
|
25
|
+
if (typeof text === 'string' && text.includes(TEMPLATE_MARKER) && host && ctx) {
|
|
26
|
+
return { ...content, data: { ...content.data, text: host.compileTemplate(text, ctx) } };
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return content;
|
|
30
|
+
}
|
|
31
|
+
if (isComponentCall(content)) {
|
|
32
|
+
const rendered = await requireComponents(snapshot).render(requester, content.name, content.props);
|
|
33
|
+
return this.#render(rendered, requester, snapshot, host, ctx, depth + 1);
|
|
34
|
+
}
|
|
35
|
+
throw new TypeError('Unsupported SendContent');
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function compileText(text, host, ctx) {
|
|
39
|
+
if (!host || !ctx || !text.includes(TEMPLATE_MARKER))
|
|
40
|
+
return text;
|
|
41
|
+
return host.compileTemplate(text, ctx);
|
|
42
|
+
}
|
|
43
|
+
function buildTemplateContext(conversation, incoming) {
|
|
44
|
+
return {
|
|
45
|
+
adapter: conversation.endpoint.adapter,
|
|
46
|
+
endpoint: conversation.endpoint.id,
|
|
47
|
+
kind: conversation.kind,
|
|
48
|
+
conversationId: conversation.id,
|
|
49
|
+
sender: incoming?.sender,
|
|
50
|
+
content: incoming?.content,
|
|
51
|
+
segments: incoming?.segments,
|
|
52
|
+
messageId: incoming?.messageId,
|
|
53
|
+
timestamp: incoming?.timestamp,
|
|
54
|
+
endpointId: incoming?.endpointId,
|
|
55
|
+
mentioned: incoming?.mentioned,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function resolveComponentHost(snapshot) {
|
|
59
|
+
const host = snapshot.resources.get(snapshot.root)?.get(componentHostToken.id);
|
|
60
|
+
return host && typeof host.compileTemplate === 'function'
|
|
61
|
+
? host
|
|
62
|
+
: undefined;
|
|
63
|
+
}
|
|
64
|
+
function requireComponents(snapshot) {
|
|
65
|
+
const projection = snapshot.projections.get(componentFeatureId);
|
|
66
|
+
if (!isComponentIndex(projection)) {
|
|
67
|
+
throw new Error('Component Feature projection is not installed');
|
|
68
|
+
}
|
|
69
|
+
return projection;
|
|
70
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { CapabilityId, HtmlRendererHost, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
2
|
+
import { type InteractivePolicy } from '../../built/interactive-segments/types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Outbound payload normalization for the Plugin Runtime IM pipeline.
|
|
5
|
+
*
|
|
6
|
+
* `raw()` payloads reach adapters as-is; adapters only understand wire
|
|
7
|
+
* segments (`{ type, data }` arrays). A single segment object (non-array)
|
|
8
|
+
* would otherwise fall through to `String(payload)` → '[object Object]'.
|
|
9
|
+
*
|
|
10
|
+
* Segment payloads are normalized to the canonical Segment SSOT
|
|
11
|
+
* (`built/segment-contract`,复用 `toCanonicalSegments`:at→mention、
|
|
12
|
+
* 旧 wire 字段 `{url,file,base64}`→MediaRef)。`html` segments additionally
|
|
13
|
+
* need a Host renderer: image when `@zhin.js/html-renderer` is installed,
|
|
14
|
+
* plain-text fallback otherwise. 渲染产出的 base64 图片按端点声明的媒体
|
|
15
|
+
* 能力(`resolveOutboundMediaPolicy`)协商降级。
|
|
16
|
+
*/
|
|
17
|
+
export interface OutboundSegment {
|
|
18
|
+
readonly type: string;
|
|
19
|
+
readonly data?: Record<string, unknown>;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* 出站媒体能力策略(html→image 渲染产物与 base64/path 媒体段的投递方式):
|
|
23
|
+
* - `base64`:平台接受 base64 直发;
|
|
24
|
+
* - `url-or-text`:平台仅接受 URL 媒体;本层无上传通道,base64/path → 文本降级;
|
|
25
|
+
* - `passthrough`:adapter 自行物化媒体,本层不动。
|
|
26
|
+
*/
|
|
27
|
+
export type OutboundMediaPolicy = 'base64' | 'url-or-text' | 'passthrough';
|
|
28
|
+
/**
|
|
29
|
+
* adapter definition 的 segments policy 声明(必选能力面)。
|
|
30
|
+
* `outboundMedia` 为端点可消费的媒体来源形式数组
|
|
31
|
+
* ('url' | 'path' | 'base64' | 'upload'),映射到投递策略:
|
|
32
|
+
* base64 可直发;无 base64 但端点可自行物化(upload/path)→ passthrough;
|
|
33
|
+
* 仅 url → 非 URL 媒体文本降级。未声明的 adapter 按 ['url'] 兜底。
|
|
34
|
+
*/
|
|
35
|
+
export interface OutboundSegmentsPolicy {
|
|
36
|
+
readonly outboundMedia: readonly ('url' | 'path' | 'base64' | 'upload')[];
|
|
37
|
+
readonly interactive?: InteractivePolicy;
|
|
38
|
+
readonly markdown?: 'native' | 'text';
|
|
39
|
+
}
|
|
40
|
+
export interface NormalizeOutboundOptions {
|
|
41
|
+
/** 缺省 `url-or-text`(未声明 adapter 的保守兜底:仅 URL 媒体可达)。 */
|
|
42
|
+
readonly mediaPolicy?: OutboundMediaPolicy;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* 解析端点的出站媒体策略:读 adapter definition 声明的 `segments.outboundMedia`
|
|
46
|
+
* (多 endpoint 展开的 `slot~entry` id 回退到 slot id 查声明);
|
|
47
|
+
* 未声明回退 `url-or-text`(仅 URL 媒体可达,其余文本降级)。
|
|
48
|
+
*/
|
|
49
|
+
export declare function resolveOutboundMediaPolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): OutboundMediaPolicy;
|
|
50
|
+
export declare function isOutboundSegment(value: unknown): value is OutboundSegment;
|
|
51
|
+
/**
|
|
52
|
+
* 解析端点的出站 interactive 策略:优先读 adapter definition 上声明的
|
|
53
|
+
* `segments.interactive`,否则按平台名查内置表,未知平台回退 'text'。
|
|
54
|
+
*/
|
|
55
|
+
export declare function resolveOutboundInteractivePolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): InteractivePolicy;
|
|
56
|
+
/** Preserve semantic Markdown only when the endpoint explicitly declares native consumption. */
|
|
57
|
+
export declare function resolveOutboundMarkdownPolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): 'native' | 'text';
|
|
58
|
+
export declare function applyOutboundMarkdownPolicy(payload: unknown, policy: 'native' | 'text'): unknown;
|
|
59
|
+
/**
|
|
60
|
+
* keyboard 段降级:'text' 端点把 keyboard 渲染为编号文本,并把有效
|
|
61
|
+
* fallback 映射交给调用方所属的 runtime;'native' 端点透传 keyboard。
|
|
62
|
+
*/
|
|
63
|
+
export declare function applyOutboundInteractivePolicy(payload: unknown, policy: InteractivePolicy, remember?: (map: Record<string, string>) => void): unknown;
|
|
64
|
+
/**
|
|
65
|
+
* Normalize a rendered outbound payload toward canonical wire segments:
|
|
66
|
+
* - segment arrays stay arrays (html segments converted per element,
|
|
67
|
+
* 其余段经 `toCanonicalSegments` 归一为 canonical Segment);
|
|
68
|
+
* - a single segment object is wrapped into a one-element array;
|
|
69
|
+
* - anything else (plain strings, legacy `{ text }` shorthands) passes through.
|
|
70
|
+
*/
|
|
71
|
+
export declare function normalizeOutboundPayload(payload: unknown, renderer?: HtmlRendererHost, options?: NormalizeOutboundOptions): Promise<unknown>;
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { htmlToFallbackText } from '../../built/html-to-text.js';
|
|
2
|
+
import { toCanonicalSegments } from '../../built/generic-segment-mapper.js';
|
|
3
|
+
import { effectiveKeyboardFallbackMap, renderKeyboardAsText, } from '../../built/interactive-segments/resolve.js';
|
|
4
|
+
import { DEFAULT_INTERACTIVE_POLICY, isKeyboardSegment, } from '../../built/interactive-segments/types.js';
|
|
5
|
+
import { isMediaRef } from '../../built/segment-contract/index.js';
|
|
6
|
+
import { markdownToPlainText } from '../../built/rich-segments/markdown-to-text.js';
|
|
7
|
+
const DEFAULT_CARD_WIDTH = 540;
|
|
8
|
+
const DEFAULT_CARD_FILENAME = 'card.png';
|
|
9
|
+
const DEFAULT_MEDIA_POLICY = 'url-or-text';
|
|
10
|
+
/**
|
|
11
|
+
* 解析端点的出站媒体策略:读 adapter definition 声明的 `segments.outboundMedia`
|
|
12
|
+
* (多 endpoint 展开的 `slot~entry` id 回退到 slot id 查声明);
|
|
13
|
+
* 未声明回退 `url-or-text`(仅 URL 媒体可达,其余文本降级)。
|
|
14
|
+
*/
|
|
15
|
+
export function resolveOutboundMediaPolicy(adapter, snapshot) {
|
|
16
|
+
const slot = snapshot.capabilities.get(adapter)
|
|
17
|
+
?? snapshot.capabilities.get(baseSlotCapabilityId(adapter));
|
|
18
|
+
return readDeclaredMediaPolicy(slot?.definition) ?? DEFAULT_MEDIA_POLICY;
|
|
19
|
+
}
|
|
20
|
+
function readDeclaredMediaPolicy(definition) {
|
|
21
|
+
if (!definition || typeof definition !== 'object')
|
|
22
|
+
return undefined;
|
|
23
|
+
const segments = definition.segments;
|
|
24
|
+
if (!segments || typeof segments !== 'object')
|
|
25
|
+
return undefined;
|
|
26
|
+
const declared = segments.outboundMedia;
|
|
27
|
+
if (!Array.isArray(declared))
|
|
28
|
+
return undefined;
|
|
29
|
+
if (declared.includes('base64'))
|
|
30
|
+
return 'base64';
|
|
31
|
+
if (declared.includes('upload') || declared.includes('path'))
|
|
32
|
+
return 'passthrough';
|
|
33
|
+
if (declared.includes('url'))
|
|
34
|
+
return 'url-or-text';
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
export function isOutboundSegment(value) {
|
|
38
|
+
return typeof value === 'object'
|
|
39
|
+
&& value !== null
|
|
40
|
+
&& !Array.isArray(value)
|
|
41
|
+
&& typeof value.type === 'string';
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* 平台名 → 出站 interactive 策略(adapter 未声明 `segments.interactive` 时
|
|
45
|
+
* 的内置来源):telegram / discord 端点自行把 keyboard 编码为原生按钮;
|
|
46
|
+
* 其余平台默认 'text'(编号文本降级)。
|
|
47
|
+
*/
|
|
48
|
+
const OUTBOUND_INTERACTIVE_POLICY_BY_ADAPTER = {
|
|
49
|
+
telegram: 'native',
|
|
50
|
+
discord: 'native',
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* 解析端点的出站 interactive 策略:优先读 adapter definition 上声明的
|
|
54
|
+
* `segments.interactive`,否则按平台名查内置表,未知平台回退 'text'。
|
|
55
|
+
*/
|
|
56
|
+
export function resolveOutboundInteractivePolicy(adapter, snapshot) {
|
|
57
|
+
const slot = snapshot.capabilities.get(adapter)
|
|
58
|
+
?? snapshot.capabilities.get(baseSlotCapabilityId(adapter));
|
|
59
|
+
const declared = readDeclaredInteractivePolicy(slot?.definition);
|
|
60
|
+
if (declared)
|
|
61
|
+
return declared;
|
|
62
|
+
const packageName = slot ? snapshot.tree.get(slot.owner)?.packageName : undefined;
|
|
63
|
+
const adapterType = adapterTypeName(packageName);
|
|
64
|
+
return (adapterType ? OUTBOUND_INTERACTIVE_POLICY_BY_ADAPTER[adapterType] : undefined)
|
|
65
|
+
?? DEFAULT_INTERACTIVE_POLICY;
|
|
66
|
+
}
|
|
67
|
+
/** Preserve semantic Markdown only when the endpoint explicitly declares native consumption. */
|
|
68
|
+
export function resolveOutboundMarkdownPolicy(adapter, snapshot) {
|
|
69
|
+
const slot = snapshot.capabilities.get(adapter)
|
|
70
|
+
?? snapshot.capabilities.get(baseSlotCapabilityId(adapter));
|
|
71
|
+
if (!slot?.definition || typeof slot.definition !== 'object')
|
|
72
|
+
return 'text';
|
|
73
|
+
const segments = slot.definition.segments;
|
|
74
|
+
if (!segments || typeof segments !== 'object')
|
|
75
|
+
return 'text';
|
|
76
|
+
return segments.markdown === 'native' ? 'native' : 'text';
|
|
77
|
+
}
|
|
78
|
+
export function applyOutboundMarkdownPolicy(payload, policy) {
|
|
79
|
+
if (policy === 'native')
|
|
80
|
+
return payload;
|
|
81
|
+
const convert = (item) => {
|
|
82
|
+
if (!item || typeof item !== 'object' || Array.isArray(item))
|
|
83
|
+
return item;
|
|
84
|
+
const segment = item;
|
|
85
|
+
if (segment.type !== 'markdown')
|
|
86
|
+
return item;
|
|
87
|
+
const content = String(segment.data?.content ?? segment.data?.text ?? '');
|
|
88
|
+
return { type: 'text', data: { text: markdownToPlainText(content) } };
|
|
89
|
+
};
|
|
90
|
+
return Array.isArray(payload) ? payload.map(convert) : convert(payload);
|
|
91
|
+
}
|
|
92
|
+
function readDeclaredInteractivePolicy(definition) {
|
|
93
|
+
if (!definition || typeof definition !== 'object')
|
|
94
|
+
return undefined;
|
|
95
|
+
const segments = definition.segments;
|
|
96
|
+
if (!segments || typeof segments !== 'object')
|
|
97
|
+
return undefined;
|
|
98
|
+
const declared = segments.interactive;
|
|
99
|
+
return declared === 'native' || declared === 'text' ? declared : undefined;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* keyboard 段降级:'text' 端点把 keyboard 渲染为编号文本,并把有效
|
|
103
|
+
* fallback 映射交给调用方所属的 runtime;'native' 端点透传 keyboard。
|
|
104
|
+
*/
|
|
105
|
+
export function applyOutboundInteractivePolicy(payload, policy, remember) {
|
|
106
|
+
if (policy !== 'text' || !Array.isArray(payload))
|
|
107
|
+
return payload;
|
|
108
|
+
return payload.map((item) => {
|
|
109
|
+
if (!isKeyboardSegment(item))
|
|
110
|
+
return item;
|
|
111
|
+
const data = item.data;
|
|
112
|
+
remember?.(effectiveKeyboardFallbackMap(data));
|
|
113
|
+
return { type: 'text', data: { text: renderKeyboardAsText(data) } };
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
/** 多 endpoint 展开的 record id(`slot.id~entry`)→ slot id(entry 名禁含 `~`,见 adapter-index)。 */
|
|
117
|
+
function baseSlotCapabilityId(adapter) {
|
|
118
|
+
const tilde = adapter.indexOf('~');
|
|
119
|
+
return (tilde === -1 ? adapter : adapter.slice(0, tilde));
|
|
120
|
+
}
|
|
121
|
+
/** `@zhin.js/adapter-icqq` → `icqq`;非 adapter 包名原样返回。 */
|
|
122
|
+
function adapterTypeName(packageName) {
|
|
123
|
+
if (!packageName)
|
|
124
|
+
return undefined;
|
|
125
|
+
return packageName.replace(/^@[^/]+\/adapter-/, '');
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Normalize a rendered outbound payload toward canonical wire segments:
|
|
129
|
+
* - segment arrays stay arrays (html segments converted per element,
|
|
130
|
+
* 其余段经 `toCanonicalSegments` 归一为 canonical Segment);
|
|
131
|
+
* - a single segment object is wrapped into a one-element array;
|
|
132
|
+
* - anything else (plain strings, legacy `{ text }` shorthands) passes through.
|
|
133
|
+
*/
|
|
134
|
+
export async function normalizeOutboundPayload(payload, renderer, options) {
|
|
135
|
+
const mediaPolicy = options?.mediaPolicy ?? DEFAULT_MEDIA_POLICY;
|
|
136
|
+
if (Array.isArray(payload)) {
|
|
137
|
+
const resolved = await Promise.all(payload.map((item) => normalizeOneSegment(item, renderer, mediaPolicy)));
|
|
138
|
+
return applyOutboundMediaPolicy(resolved, mediaPolicy);
|
|
139
|
+
}
|
|
140
|
+
if (isOutboundSegment(payload)) {
|
|
141
|
+
return applyOutboundMediaPolicy([await normalizeOneSegment(payload, renderer, mediaPolicy)], mediaPolicy);
|
|
142
|
+
}
|
|
143
|
+
return payload;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* 单个出站项 → canonical Segment:
|
|
147
|
+
* - html 段走渲染/文本降级专线(产物已是 canonical 兼容形状,不再过
|
|
148
|
+
* `toCanonicalSegments`,以免 legacy 双写字段被 strip);
|
|
149
|
+
* - 其余项经 `toCanonicalSegments` 归一(字符串→text、at→mention、
|
|
150
|
+
* 旧 wire 字段 `{url,file,base64}`→MediaRef)。
|
|
151
|
+
*/
|
|
152
|
+
async function normalizeOneSegment(item, renderer, mediaPolicy) {
|
|
153
|
+
if (isOutboundSegment(item) && item.type === 'html') {
|
|
154
|
+
return renderHtmlSegment(item, renderer, mediaPolicy);
|
|
155
|
+
}
|
|
156
|
+
return toCanonicalSegments([item])[0];
|
|
157
|
+
}
|
|
158
|
+
async function renderHtmlSegment(segment, renderer, mediaPolicy) {
|
|
159
|
+
const data = segment.data ?? {};
|
|
160
|
+
const html = typeof data.html === 'string' ? data.html : '';
|
|
161
|
+
// url-or-text 端点无法投递 base64 图片(本层无上传通道),直接文本降级,跳过渲染。
|
|
162
|
+
if (html && renderer && mediaPolicy !== 'url-or-text') {
|
|
163
|
+
try {
|
|
164
|
+
const result = await renderer.render(html, {
|
|
165
|
+
width: typeof data.width === 'number' ? data.width : DEFAULT_CARD_WIDTH,
|
|
166
|
+
format: 'png',
|
|
167
|
+
...(typeof data.backgroundColor === 'string'
|
|
168
|
+
? { backgroundColor: data.backgroundColor }
|
|
169
|
+
: {}),
|
|
170
|
+
});
|
|
171
|
+
if (result.format === 'png' && result.data && typeof result.data === 'object') {
|
|
172
|
+
const base64 = Buffer.from(result.data).toString('base64');
|
|
173
|
+
return {
|
|
174
|
+
type: 'image',
|
|
175
|
+
data: {
|
|
176
|
+
media: {
|
|
177
|
+
kind: 'base64',
|
|
178
|
+
value: base64,
|
|
179
|
+
mime_type: 'image/png',
|
|
180
|
+
file_name: typeof data.fileName === 'string' ? data.fileName : DEFAULT_CARD_FILENAME,
|
|
181
|
+
},
|
|
182
|
+
},
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
// 渲染失败 → 文本降级
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return { type: 'text', data: { text: htmlSegmentFallbackText(data, html) } };
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* 媒体协商:仅 `url-or-text` 需要在本层动作——媒体段的非 URL MediaRef
|
|
194
|
+
* (base64 / 本地路径)无法投递,降级为文本(alt / file_name 优先)。
|
|
195
|
+
*/
|
|
196
|
+
const MEDIA_SEGMENT_TYPES = new Set(['image', 'audio', 'video', 'file']);
|
|
197
|
+
function applyOutboundMediaPolicy(segments, mediaPolicy) {
|
|
198
|
+
if (mediaPolicy !== 'url-or-text')
|
|
199
|
+
return segments;
|
|
200
|
+
return segments.map((segment) => {
|
|
201
|
+
if (!MEDIA_SEGMENT_TYPES.has(segment.type))
|
|
202
|
+
return segment;
|
|
203
|
+
const data = segment.data;
|
|
204
|
+
const media = data.media;
|
|
205
|
+
if (!isMediaRef(media) || media.kind === 'url')
|
|
206
|
+
return segment;
|
|
207
|
+
const label = typeof data.alt === 'string' && data.alt
|
|
208
|
+
? data.alt
|
|
209
|
+
: typeof data.name === 'string' && data.name
|
|
210
|
+
? data.name
|
|
211
|
+
: media.file_name ?? `[${segment.type}]`;
|
|
212
|
+
return { type: 'text', data: { text: label } };
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
function htmlSegmentFallbackText(data, html) {
|
|
216
|
+
if (typeof data.text === 'string' && data.text.length > 0)
|
|
217
|
+
return data.text;
|
|
218
|
+
return html ? htmlToFallbackText(html) : '';
|
|
219
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public IM gateway contract exposed from `zhin.js/core/runtime`.
|
|
3
|
+
* @module zhin.js/core/runtime
|
|
4
|
+
*/
|
|
5
|
+
export { outboundMessageToken } from './im-runtime.js';
|
|
6
|
+
export { Message, type ComponentCall, type ConversationAddress, type IncomingContext, type IncomingMessage, type MessageDispatchResult, type OutboundMessageService, type MessageSenderRef, type OutboundEnvelope, type RawContent, type SendContent, type SendRequest, } from './contracts.js';
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
2
|
+
/** Runs the generation-owned middleware projection or the terminal directly. */
|
|
3
|
+
export declare function runRuntimeMiddleware<TInput>(snapshot: RuntimeSnapshot, input: TInput, terminal: () => Promise<void>, target: 'inbound' | 'outbound'): Promise<void>;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { isMiddlewareIndex, middlewareFeatureId } from '@zhin.js/middleware';
|
|
2
|
+
/** Runs the generation-owned middleware projection or the terminal directly. */
|
|
3
|
+
export async function runRuntimeMiddleware(snapshot, input, terminal, target) {
|
|
4
|
+
const index = middleware(snapshot);
|
|
5
|
+
if (index)
|
|
6
|
+
await index.run(input, terminal, target);
|
|
7
|
+
else
|
|
8
|
+
await terminal();
|
|
9
|
+
}
|
|
10
|
+
function middleware(snapshot) {
|
|
11
|
+
const projection = snapshot.projections.get(middlewareFeatureId);
|
|
12
|
+
return isMiddlewareIndex(projection) ? projection : undefined;
|
|
13
|
+
}
|
package/lib/request.d.ts
CHANGED
|
@@ -1,85 +1,40 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import type {
|
|
1
|
+
import type { MaybePromise } from './types.js';
|
|
2
|
+
import type { RequestKind } from './side-event/types.js';
|
|
3
|
+
import type { SideEventBase } from './side-event/base.js';
|
|
4
|
+
export type { RequestKind, ComposedRequestName } from './side-event/types.js';
|
|
3
5
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* 常见 IM 请求事件分类:
|
|
7
|
-
* - friend_add: 好友添加请求
|
|
8
|
-
* - group_add: 主动申请入群
|
|
9
|
-
* - group_invite: 邀请入群请求
|
|
10
|
-
*
|
|
11
|
-
* 适配器可自行扩展更多子类型
|
|
12
|
-
*/
|
|
13
|
-
export type RequestType = 'friend_add' | 'group_add' | 'group_invite' | (string & {});
|
|
14
|
-
/**
|
|
15
|
-
* 请求频道信息
|
|
16
|
-
*/
|
|
17
|
-
export interface RequestChannel {
|
|
18
|
-
id: string;
|
|
19
|
-
type: 'group' | 'private' | 'channel';
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* 请求基础结构
|
|
23
|
-
*
|
|
24
|
-
* 与 MessageBase / NoticeBase 同构设计。
|
|
25
|
-
* 核心区别:Request 提供 `$approve()` 和 `$reject()` 方法,用于快速处理请求。
|
|
6
|
+
* 请求基础结构 — 继承 SideEventBase,附加审批方法。
|
|
26
7
|
*
|
|
27
8
|
* @example
|
|
28
9
|
* ```typescript
|
|
29
|
-
* // 适配器中格式化请求
|
|
30
10
|
* const request = Request.from(rawEvent, {
|
|
31
11
|
* $id: rawEvent.flag,
|
|
32
12
|
* $adapter: 'icqq',
|
|
33
|
-
* $
|
|
34
|
-
* $type: '
|
|
35
|
-
* $
|
|
36
|
-
* $
|
|
13
|
+
* $endpoint: endpointKey,
|
|
14
|
+
* $type: 'request',
|
|
15
|
+
* $scene_id: groupId,
|
|
16
|
+
* $scene_type: 'group',
|
|
17
|
+
* $sub_type: 'invite',
|
|
18
|
+
* $actor: { id: userId, name: '邀请者' },
|
|
37
19
|
* $comment: '请求加群消息',
|
|
38
20
|
* $timestamp: Date.now(),
|
|
39
21
|
* $approve: async (remark?) => { await api.approve(flag, remark); },
|
|
40
22
|
* $reject: async (reason?) => { await api.reject(flag, reason); },
|
|
41
23
|
* });
|
|
24
|
+
* // formatSideEventName(request) === 'request.group.invite'
|
|
42
25
|
* this.adapter.emit('request.receive', request);
|
|
43
26
|
* ```
|
|
44
27
|
*/
|
|
45
|
-
export interface RequestBase {
|
|
46
|
-
|
|
47
|
-
$
|
|
48
|
-
/**
|
|
49
|
-
$
|
|
50
|
-
/** Bot 名称 */
|
|
51
|
-
$bot: string;
|
|
52
|
-
/** 请求类型 */
|
|
53
|
-
$type: RequestType;
|
|
54
|
-
/** 请求子类型 */
|
|
55
|
-
$subType?: string;
|
|
56
|
-
/** 请求发生的频道/群/会话 */
|
|
57
|
-
$channel: RequestChannel;
|
|
58
|
-
/** 请求发送者 */
|
|
59
|
-
$sender: MessageSender;
|
|
60
|
-
/** 请求附言/验证消息 */
|
|
28
|
+
export interface RequestBase extends SideEventBase {
|
|
29
|
+
$adapter: string;
|
|
30
|
+
$type: RequestKind;
|
|
31
|
+
/** 主参与者(必填) */
|
|
32
|
+
$actor: NonNullable<SideEventBase['$actor']>;
|
|
61
33
|
$comment?: string;
|
|
62
|
-
/** 请求时间戳 */
|
|
63
|
-
$timestamp: number;
|
|
64
|
-
/**
|
|
65
|
-
* 同意请求
|
|
66
|
-
* @param remark 备注信息(如好友备注)
|
|
67
|
-
*/
|
|
68
34
|
$approve(remark?: string): MaybePromise<void>;
|
|
69
|
-
/**
|
|
70
|
-
* 拒绝请求
|
|
71
|
-
* @param reason 拒绝原因
|
|
72
|
-
*/
|
|
73
35
|
$reject(reason?: string): MaybePromise<void>;
|
|
74
36
|
}
|
|
75
|
-
/**
|
|
76
|
-
* 完整请求类型,支持平台原始数据扩展
|
|
77
|
-
*/
|
|
78
37
|
export type Request<T extends object = {}> = RequestBase & T;
|
|
79
38
|
export declare namespace Request {
|
|
80
|
-
/**
|
|
81
|
-
* 工具方法:合并自定义字段与基础请求结构
|
|
82
|
-
*/
|
|
83
39
|
function from<T extends object>(input: T, format: RequestBase): Request<T>;
|
|
84
40
|
}
|
|
85
|
-
//# sourceMappingURL=request.d.ts.map
|