@zhin.js/core 1.1.39 → 1.1.41
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/lib/built/ai-trigger.js +2 -2
- package/lib/built/html-segment-fallback.d.ts +4 -2
- package/lib/built/html-segment-fallback.js +1 -1
- package/lib/built/interactive-segments/resolve.js +1 -1
- package/lib/built/interactive-segments/types.d.ts +2 -2
- package/lib/built/interactive-segments/types.js +22 -2
- package/lib/built/outbound-content-arrays.d.ts +4 -0
- package/lib/built/outbound-content-arrays.js +32 -0
- package/lib/built/outbound-media-utils.d.ts +5 -3
- package/lib/built/outbound-media-utils.js +5 -3
- package/lib/built/segment-contract/assert.js +5 -0
- package/lib/built/segment-contract/json-schema.d.ts +1 -1
- package/lib/built/segment-contract/json-schema.js +30 -2
- package/lib/feature/component.d.ts +1 -0
- package/lib/feature/component.js +1 -0
- package/lib/index.d.ts +3 -2
- package/lib/index.js +2 -1
- package/lib/jsx-dev-runtime.d.ts +1 -2
- package/lib/jsx-dev-runtime.js +1 -2
- package/lib/jsx-runtime.d.ts +1 -12
- package/lib/jsx-runtime.js +1 -10
- package/lib/jsx.d.ts +1 -30
- package/lib/jsx.js +1 -93
- package/lib/message.d.ts +0 -11
- package/lib/plugin-runtime/im/contracts.d.ts +14 -6
- package/lib/plugin-runtime/im/contracts.js +28 -6
- package/lib/plugin-runtime/im/endpoint-runtime.d.ts +6 -1
- package/lib/plugin-runtime/im/endpoint-runtime.js +27 -5
- package/lib/plugin-runtime/im/inbound-runtime.js +30 -6
- package/lib/plugin-runtime/im/message-dispatcher.js +28 -5
- package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +1 -1
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +90 -29
- package/lib/plugin-runtime/im/outbound-renderer.d.ts +7 -2
- package/lib/plugin-runtime/im/outbound-renderer.js +31 -6
- package/lib/plugin-runtime/im/outbound-segments.d.ts +7 -0
- package/lib/plugin-runtime/im/outbound-segments.js +33 -6
- package/lib/plugin-runtime/im/runtime-middleware.js +1 -1
- package/lib/types.d.ts +5 -7
- package/lib/utils.d.ts +4 -4
- package/lib/utils.js +9 -17
- package/package.json +16 -14
- package/lib/component.d.ts +0 -26
- package/lib/component.js +0 -583
|
@@ -12,6 +12,9 @@ export class EndpointRuntime {
|
|
|
12
12
|
adapter: adapterTypeName(snapshot.tree.get(row.owner)?.packageName) ?? row.name,
|
|
13
13
|
owner: row.owner,
|
|
14
14
|
connected: row.connected,
|
|
15
|
+
admitted: row.admitted,
|
|
16
|
+
transportState: row.transportState,
|
|
17
|
+
eventDiagnostics: row.eventDiagnostics,
|
|
15
18
|
status: row.status,
|
|
16
19
|
phase: row.phase,
|
|
17
20
|
operations: row.operations,
|
|
@@ -21,14 +24,14 @@ export class EndpointRuntime {
|
|
|
21
24
|
capabilities(input) {
|
|
22
25
|
return this.#withLease((snapshot) => {
|
|
23
26
|
const index = requireAdapters(snapshot);
|
|
24
|
-
const id = index
|
|
27
|
+
const id = resolveEndpointIdentity(snapshot, index, input.adapter, input.endpointKey);
|
|
25
28
|
return id ? index.capabilities(id) : undefined;
|
|
26
29
|
}, undefined);
|
|
27
30
|
}
|
|
28
31
|
get(adapter, endpointKey) {
|
|
29
32
|
return this.#withLease((snapshot) => {
|
|
30
33
|
const index = requireAdapters(snapshot);
|
|
31
|
-
const id = index
|
|
34
|
+
const id = resolveEndpointIdentity(snapshot, index, adapter, endpointKey);
|
|
32
35
|
if (!id)
|
|
33
36
|
return null;
|
|
34
37
|
const row = index.describe().find((item) => item.id === id);
|
|
@@ -38,6 +41,9 @@ export class EndpointRuntime {
|
|
|
38
41
|
name: row.name,
|
|
39
42
|
adapter: adapterTypeName(snapshot.tree.get(row.owner)?.packageName) ?? row.name,
|
|
40
43
|
connected: row.connected,
|
|
44
|
+
admitted: row.admitted,
|
|
45
|
+
transportState: row.transportState,
|
|
46
|
+
eventDiagnostics: row.eventDiagnostics,
|
|
41
47
|
status: row.status,
|
|
42
48
|
phase: row.phase,
|
|
43
49
|
operations: row.operations,
|
|
@@ -49,7 +55,7 @@ export class EndpointRuntime {
|
|
|
49
55
|
const lease = this.context.acquire();
|
|
50
56
|
try {
|
|
51
57
|
const index = requireAdapters(lease.value);
|
|
52
|
-
const resolved = index
|
|
58
|
+
const resolved = resolveEndpointIdentity(lease.value, index, input.adapter, input.endpointKey);
|
|
53
59
|
if (!resolved)
|
|
54
60
|
throw new Error('endpoint not found');
|
|
55
61
|
const requester = index.owner(resolved);
|
|
@@ -95,7 +101,9 @@ export class EndpointRuntime {
|
|
|
95
101
|
return null;
|
|
96
102
|
}
|
|
97
103
|
try {
|
|
98
|
-
const
|
|
104
|
+
const index = requireAdapters(lease.value);
|
|
105
|
+
const id = resolveEndpointIdentity(lease.value, index, adapter, endpointKey);
|
|
106
|
+
const endpoint = id ? index.connection(String(id), String(id)) : undefined;
|
|
99
107
|
if (!endpoint)
|
|
100
108
|
return null;
|
|
101
109
|
return await run(resolveEndpointManagement(endpoint) ?? Object.freeze({}));
|
|
@@ -114,7 +122,7 @@ export class EndpointRuntime {
|
|
|
114
122
|
}
|
|
115
123
|
try {
|
|
116
124
|
const index = requireAdapters(lease.value);
|
|
117
|
-
const id = index
|
|
125
|
+
const id = resolveEndpointIdentity(lease.value, index, adapter, endpointKey);
|
|
118
126
|
const control = id ? index.control(id, operation) : undefined;
|
|
119
127
|
return control ? await run(control) : fallback;
|
|
120
128
|
}
|
|
@@ -148,6 +156,20 @@ export function requireAdapters(snapshot) {
|
|
|
148
156
|
}
|
|
149
157
|
return projection;
|
|
150
158
|
}
|
|
159
|
+
/** Resolves public list identities against the exact operation snapshot; ambiguous aliases never pick an account. */
|
|
160
|
+
export function resolveEndpointIdentity(snapshot, index, adapter, endpointKey) {
|
|
161
|
+
const live = new Map(index.describe().map(row => [row.id, row.name]));
|
|
162
|
+
const matches = index.list().filter(record => {
|
|
163
|
+
const localName = record.id.split('\0').pop() ?? record.id;
|
|
164
|
+
const alias = adapterTypeName(snapshot.tree.get(record.owner)?.packageName);
|
|
165
|
+
const adapterMatches = alias === adapter || record.name === adapter || String(record.id) === adapter
|
|
166
|
+
|| localName === adapter || String(record.owner) === adapter || record.owner.endsWith(`/${adapter}`);
|
|
167
|
+
const endpointMatches = record.name === endpointKey || String(record.id) === endpointKey
|
|
168
|
+
|| record.id.endsWith(`/${endpointKey}`) || live.get(record.id) === endpointKey;
|
|
169
|
+
return adapterMatches && endpointMatches;
|
|
170
|
+
});
|
|
171
|
+
return matches.length === 1 ? matches[0].id : undefined;
|
|
172
|
+
}
|
|
151
173
|
export function adapterTypeName(packageName) {
|
|
152
174
|
if (!packageName)
|
|
153
175
|
return undefined;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isMiddlewareIndex, middlewareFeatureId } from '@zhin.js/middleware';
|
|
1
2
|
import { isHandlerIndex, handlerFeatureId } from '../../feature/handler.js';
|
|
2
3
|
import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
|
|
3
4
|
import { RuntimeNotice } from '../../notice.js';
|
|
@@ -8,7 +9,6 @@ import { defaultCommandPrefixResolver, MessageDispatcher } from './message-dispa
|
|
|
8
9
|
import { requireAdapters } from './endpoint-runtime.js';
|
|
9
10
|
import { formatConversationLog, previewMessageContent, } from './message-events.js';
|
|
10
11
|
import { resolveIngressRoute } from './ingress-route.js';
|
|
11
|
-
import { runRuntimeMiddleware } from './runtime-middleware.js';
|
|
12
12
|
const logger = getLogger('im.inbound');
|
|
13
13
|
/** Owns Endpoint ingress normalization, routing, dispatch, and side-event action scopes. */
|
|
14
14
|
export class InboundRuntime {
|
|
@@ -78,7 +78,10 @@ export class InboundRuntime {
|
|
|
78
78
|
if (!active)
|
|
79
79
|
throw new Error('Message Client scope has ended');
|
|
80
80
|
return source.client;
|
|
81
|
-
}, source.endpoint.adapter)
|
|
81
|
+
}, source.endpoint.adapter, { snapshot: lease.value, assertActive: () => {
|
|
82
|
+
if (!active)
|
|
83
|
+
throw new Error('Message author binding scope has ended');
|
|
84
|
+
} });
|
|
82
85
|
const conversationSequence = await this.context.recordIncoming(input, enrichedSender);
|
|
83
86
|
let result = Object.freeze({ matched: false });
|
|
84
87
|
const claimed = await this.context.inboundClaim?.(message) === true;
|
|
@@ -90,18 +93,18 @@ export class InboundRuntime {
|
|
|
90
93
|
}
|
|
91
94
|
else {
|
|
92
95
|
const interactionFactory = (value) => this.context.interactions.createFromUnknown(value);
|
|
93
|
-
|
|
96
|
+
const terminal = async () => {
|
|
94
97
|
const ingressRoute = resolveIngressRoute(lease.value);
|
|
95
98
|
const preRouted = await ingressRoute?.preRoute?.(message, lease, requester, conversationSequence) === true;
|
|
96
99
|
if (preRouted) {
|
|
97
100
|
result = Object.freeze({ matched: true, command: 'pre-route', owner: requester });
|
|
98
|
-
return;
|
|
101
|
+
return { dispatch: result };
|
|
99
102
|
}
|
|
100
103
|
if (ingressRoute?.shouldRouteBeforeDispatch?.(message) === true) {
|
|
101
104
|
const handled = await ingressRoute.route(message, lease, requester, conversationSequence);
|
|
102
105
|
if (handled) {
|
|
103
106
|
result = Object.freeze({ matched: true, command: 'ai', owner: requester });
|
|
104
|
-
return;
|
|
107
|
+
return { dispatch: result };
|
|
105
108
|
}
|
|
106
109
|
}
|
|
107
110
|
await this.#runHandlers(lease.value, 'message.receive', [
|
|
@@ -119,7 +122,28 @@ export class InboundRuntime {
|
|
|
119
122
|
result = Object.freeze({ matched: true, command: 'ai', owner: requester });
|
|
120
123
|
}
|
|
121
124
|
}
|
|
122
|
-
|
|
125
|
+
return {
|
|
126
|
+
dispatch: result,
|
|
127
|
+
...(result.value !== undefined && result.owner
|
|
128
|
+
? { reply: { owner: result.owner, content: result.value } }
|
|
129
|
+
: {}),
|
|
130
|
+
};
|
|
131
|
+
};
|
|
132
|
+
const middleware = lease.value.projections.get(middlewareFeatureId);
|
|
133
|
+
const outcome = isMiddlewareIndex(middleware)
|
|
134
|
+
? await middleware.runInbound(message, terminal, {
|
|
135
|
+
stop: (owner) => ({ dispatch: { matched: true, command: 'middleware', owner } }),
|
|
136
|
+
replace: (owner, value, downstream) => ({
|
|
137
|
+
dispatch: downstream?.dispatch.matched
|
|
138
|
+
? downstream.dispatch
|
|
139
|
+
: { matched: true, command: 'middleware', owner },
|
|
140
|
+
reply: { owner, content: value },
|
|
141
|
+
}),
|
|
142
|
+
}, lease.value)
|
|
143
|
+
: await terminal();
|
|
144
|
+
result = outcome.dispatch;
|
|
145
|
+
if (outcome.reply)
|
|
146
|
+
await message.$replyFrom(outcome.reply.owner, outcome.reply.content);
|
|
123
147
|
}
|
|
124
148
|
if (result.matched) {
|
|
125
149
|
logger.debug(formatCompact({
|
|
@@ -1,15 +1,31 @@
|
|
|
1
|
+
import { adapterFeatureId, isAdapterIndex } from '@zhin.js/adapter';
|
|
1
2
|
import { commandFeatureId, isCommandIndex, } from '@zhin.js/command';
|
|
2
3
|
import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
|
|
3
4
|
const logger = getLogger('command');
|
|
4
|
-
function ownerOfMessage(message) {
|
|
5
|
-
|
|
5
|
+
function ownerOfMessage(message, snapshot) {
|
|
6
|
+
// adapter is a platform literal (e.g. terminal), not the Plugin owner.
|
|
7
|
+
const slot = snapshot.capabilities.get(message.conversation.endpoint.id);
|
|
8
|
+
if (slot)
|
|
9
|
+
return slot.owner;
|
|
10
|
+
// Expanded endpoint records have identities distinct from their source slot.
|
|
11
|
+
// Resolve their ownership through the generation's canonical AdapterIndex.
|
|
12
|
+
const adapters = snapshot.projections.get(adapterFeatureId);
|
|
13
|
+
if (!isAdapterIndex(adapters))
|
|
14
|
+
return undefined;
|
|
15
|
+
try {
|
|
16
|
+
return adapters.owner(message.conversation.endpoint.id);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
6
21
|
}
|
|
7
22
|
/**
|
|
8
23
|
* 默认解析:读消息所属适配器实例 config 的 `commandPrefix`(默认 `''`);
|
|
9
24
|
* 实例声明 `endpoints` 数组时,按消息 endpoint 名找 entry,`entry.commandPrefix` 覆盖顶层。
|
|
10
25
|
*/
|
|
11
26
|
export const defaultCommandPrefixResolver = (message, snapshot) => {
|
|
12
|
-
const
|
|
27
|
+
const owner = ownerOfMessage(message, snapshot);
|
|
28
|
+
const config = (owner ? snapshot.config.get(owner) : undefined);
|
|
13
29
|
if (!config)
|
|
14
30
|
return '';
|
|
15
31
|
const endpointId = message.endpointId;
|
|
@@ -43,7 +59,7 @@ export class MessageDispatcher {
|
|
|
43
59
|
? stripCommandPrefix(message.segments, prefix)
|
|
44
60
|
: undefined;
|
|
45
61
|
const matchInput = structuredInput ?? input;
|
|
46
|
-
const result = await commands.dispatch(matchInput, message, interactionFactory, prefix);
|
|
62
|
+
const result = await commands.dispatch(matchInput, message, interactionFactory, prefix, snapshot);
|
|
47
63
|
if (result.matched && result.value !== undefined) {
|
|
48
64
|
if (!result.owner)
|
|
49
65
|
throw new Error('Matched Command is missing its owner');
|
|
@@ -52,7 +68,6 @@ export class MessageDispatcher {
|
|
|
52
68
|
command: result.command,
|
|
53
69
|
owner: result.owner,
|
|
54
70
|
}));
|
|
55
|
-
await message.$replyFrom(result.owner, result.value);
|
|
56
71
|
}
|
|
57
72
|
else if (!result.matched) {
|
|
58
73
|
logger.debug(formatCompact({
|
|
@@ -70,6 +85,7 @@ export class MessageDispatcher {
|
|
|
70
85
|
function stripCommandPrefix(segments, prefix) {
|
|
71
86
|
let pendingPrefix = prefix;
|
|
72
87
|
let atStart = true;
|
|
88
|
+
let trimLeading = true;
|
|
73
89
|
const result = [];
|
|
74
90
|
for (const segment of segments) {
|
|
75
91
|
if (!atStart) {
|
|
@@ -84,6 +100,13 @@ function stripCommandPrefix(segments, prefix) {
|
|
|
84
100
|
continue;
|
|
85
101
|
}
|
|
86
102
|
let text = segment.data.text;
|
|
103
|
+
// Match the leading whitespace normalization of message.content without
|
|
104
|
+
// discarding structured arguments when the prefix follows whitespace.
|
|
105
|
+
if (trimLeading) {
|
|
106
|
+
text = text.trimStart();
|
|
107
|
+
if (text)
|
|
108
|
+
trimLeading = false;
|
|
109
|
+
}
|
|
87
110
|
if (pendingPrefix) {
|
|
88
111
|
if (text.startsWith(pendingPrefix)) {
|
|
89
112
|
text = text.slice(pendingPrefix.length);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
2
|
-
import type
|
|
2
|
+
import { type ConversationRef, type DeliveryReceipt } from '@zhin.js/im-contract';
|
|
3
3
|
import { type SendRequest } from './contracts.js';
|
|
4
4
|
import { OutboundRenderer } from './outbound-renderer.js';
|
|
5
5
|
import { type RuntimeMessageEvent } from './message-events.js';
|
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import { htmlRendererToken, } from '@zhin.js/plugin-runtime';
|
|
2
|
+
import { EndpointDeliveryError } from '@zhin.js/im-contract';
|
|
2
3
|
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
3
|
-
import {
|
|
4
|
+
import { isJsxElement } from '@zhin.js/jsx';
|
|
5
|
+
import { createOutboundEnvelope, isComponentCall, isRawContent } from './contracts.js';
|
|
4
6
|
import { OutboundRenderer } from './outbound-renderer.js';
|
|
5
|
-
import { applyOutboundInteractivePolicy, applyOutboundMarkdownPolicy, normalizeOutboundPayload, resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundMediaPolicy, } from './outbound-segments.js';
|
|
7
|
+
import { applyOutboundInteractivePolicy, applyOutboundMarkdownPolicy, normalizeOutboundPayload, resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundMediaPolicy, resolveOutboundHtmlPolicy, resolveOutboundSupportedSegments, } from './outbound-segments.js';
|
|
6
8
|
import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
|
|
7
|
-
import {
|
|
9
|
+
import { flattenOutboundArray } from '../../built/outbound-content-arrays.js';
|
|
10
|
+
import { requireAdapters } from './endpoint-runtime.js';
|
|
8
11
|
import { formatConversationLog, previewMessageContent } from './message-events.js';
|
|
9
12
|
import { runRuntimeMiddleware } from './runtime-middleware.js';
|
|
10
13
|
const logger = getLogger('im.outbound');
|
|
@@ -18,12 +21,15 @@ export class OutboundDeliveryRuntime {
|
|
|
18
21
|
}
|
|
19
22
|
async deliver(request, snapshot) {
|
|
20
23
|
const adapter = request.conversation.endpoint.id;
|
|
24
|
+
const jsxCache = new WeakMap();
|
|
21
25
|
let initialPayload;
|
|
22
26
|
try {
|
|
23
|
-
const rendered = await this.#renderer.render(request.content, request.requester, snapshot, request.conversation, request.incoming);
|
|
27
|
+
const rendered = await this.#renderer.render(request.content, request.requester, snapshot, request.conversation, request.incoming, { jsxCache });
|
|
24
28
|
initialPayload = await prepareOutboundPayload(rendered, request.conversation, snapshot);
|
|
25
29
|
}
|
|
26
|
-
catch {
|
|
30
|
+
catch (error) {
|
|
31
|
+
if (error instanceof EndpointDeliveryError && error.code === 'unsupported_operation' && error.disposition === 'not_sent')
|
|
32
|
+
return receiptFromEndpointError(error, false);
|
|
27
33
|
return rejectedDeliveryReceipt('outbound_payload_rejected');
|
|
28
34
|
}
|
|
29
35
|
let adapters;
|
|
@@ -31,7 +37,7 @@ export class OutboundDeliveryRuntime {
|
|
|
31
37
|
adapters = requireAdapters(snapshot);
|
|
32
38
|
}
|
|
33
39
|
catch (error) {
|
|
34
|
-
return receiptFromEndpointError(error);
|
|
40
|
+
return receiptFromEndpointError(error, false);
|
|
35
41
|
}
|
|
36
42
|
const envelope = createOutboundEnvelope({
|
|
37
43
|
conversation: request.conversation,
|
|
@@ -46,10 +52,20 @@ export class OutboundDeliveryRuntime {
|
|
|
46
52
|
terminalEntered = true;
|
|
47
53
|
let payload;
|
|
48
54
|
try {
|
|
49
|
-
payload
|
|
55
|
+
// Native payload replacements remain possible; only authoring values need evaluation.
|
|
56
|
+
const replacement = envelope.payload;
|
|
57
|
+
const replaced = replacement !== initialPayload && needsAuthoringRender(replacement)
|
|
58
|
+
? await this.#renderer.render(replacement, request.requester, snapshot, request.conversation, request.incoming, { jsxCache })
|
|
59
|
+
: replacement;
|
|
60
|
+
payload = await prepareOutboundPayload(replaced, request.conversation, snapshot, (map) => this.context.rememberFallback(request.conversation, snapshot.generation, map));
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
receipt = error instanceof EndpointDeliveryError && error.code === 'unsupported_operation' && error.disposition === 'not_sent'
|
|
64
|
+
? receiptFromEndpointError(error, false) : rejectedDeliveryReceipt('outbound_payload_rejected');
|
|
65
|
+
return;
|
|
50
66
|
}
|
|
51
|
-
|
|
52
|
-
receipt =
|
|
67
|
+
if (isEmptyOutboundPayload(payload)) {
|
|
68
|
+
receipt = suppressedDeliveryReceipt();
|
|
53
69
|
return;
|
|
54
70
|
}
|
|
55
71
|
try {
|
|
@@ -96,6 +112,15 @@ export class OutboundDeliveryRuntime {
|
|
|
96
112
|
return receipt ?? failedDeliveryReceipt('outbound_delivery_incomplete');
|
|
97
113
|
}
|
|
98
114
|
}
|
|
115
|
+
function isEmptyOutboundPayload(payload) {
|
|
116
|
+
if (payload === '')
|
|
117
|
+
return true;
|
|
118
|
+
return Array.isArray(payload) && payload.every(item => item?.type === 'text' && item.data?.text === '');
|
|
119
|
+
}
|
|
120
|
+
function needsAuthoringRender(value) {
|
|
121
|
+
const isAuthoring = (item) => isJsxElement(item) || isComponentCall(item) || isRawContent(item);
|
|
122
|
+
return Array.isArray(value) ? flattenOutboundArray(value).some(isAuthoring) : isAuthoring(value);
|
|
123
|
+
}
|
|
99
124
|
export function failedDeliveryReceipt(code, retryable = false) {
|
|
100
125
|
return Object.freeze({
|
|
101
126
|
status: 'failed',
|
|
@@ -108,18 +133,28 @@ export function failedDeliveryReceipt(code, retryable = false) {
|
|
|
108
133
|
}
|
|
109
134
|
async function prepareOutboundPayload(rendered, conversation, snapshot, rememberInteractiveFallback) {
|
|
110
135
|
const adapter = conversation.endpoint.id;
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
:
|
|
116
|
-
|
|
117
|
-
});
|
|
136
|
+
const markdownResolved = applyOutboundMarkdownPolicy(Array.isArray(rendered) ? flattenOutboundArray(rendered) : rendered, resolveOutboundMarkdownPolicy(adapter, snapshot));
|
|
137
|
+
let payload = await normalizeOutboundPayload(markdownResolved, resolveHtmlRenderer(snapshot), {
|
|
138
|
+
mediaPolicy: resolveOutboundMediaPolicy(adapter, snapshot),
|
|
139
|
+
htmlPolicy: resolveOutboundHtmlPolicy(adapter, snapshot),
|
|
140
|
+
onHtmlFallback: reason => logger.debug(formatCompact({ op: 'html_fallback', reason, generation: snapshot.generation })),
|
|
141
|
+
});
|
|
118
142
|
if (rememberInteractiveFallback) {
|
|
119
143
|
payload = applyOutboundInteractivePolicy(payload, resolveOutboundInteractivePolicy(adapter, snapshot), rememberInteractiveFallback);
|
|
120
144
|
}
|
|
121
|
-
if (
|
|
145
|
+
if (Array.isArray(payload)) {
|
|
146
|
+
// Empty text carries no wire content, including HTML's empty fallback.
|
|
147
|
+
// Remove it before canonical validation (required strings reject '').
|
|
148
|
+
payload = payload.filter(item => !(item?.type === 'text' && item.data?.text === ''));
|
|
122
149
|
assertCanonicalSegments(payload);
|
|
150
|
+
}
|
|
151
|
+
const supported = resolveOutboundSupportedSegments(adapter, snapshot);
|
|
152
|
+
const supportedPayload = rememberInteractiveFallback ? payload : applyOutboundInteractivePolicy(payload, resolveOutboundInteractivePolicy(adapter, snapshot));
|
|
153
|
+
if (supported && Array.isArray(supportedPayload)) {
|
|
154
|
+
const unsupported = supportedPayload.find(segment => segment && typeof segment === 'object' && typeof segment.type === 'string' && !supported.includes(segment.type));
|
|
155
|
+
if (unsupported)
|
|
156
|
+
throw new EndpointDeliveryError('unsupported_operation', `Adapter does not support canonical segment ${unsupported.type}`, 'not_sent');
|
|
157
|
+
}
|
|
123
158
|
return payload;
|
|
124
159
|
}
|
|
125
160
|
function resolveHtmlRenderer(snapshot) {
|
|
@@ -128,25 +163,51 @@ function resolveHtmlRenderer(snapshot) {
|
|
|
128
163
|
? host
|
|
129
164
|
: undefined;
|
|
130
165
|
}
|
|
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
166
|
function receiptFromEndpointResult(messageId, conversation) {
|
|
167
|
+
if (typeof messageId !== 'string' || messageId.trim() === '') {
|
|
168
|
+
return unknownDeliveryReceipt('delivery_unconfirmed');
|
|
169
|
+
}
|
|
137
170
|
return Object.freeze({
|
|
138
171
|
status: 'sent',
|
|
139
172
|
message: Object.freeze({ conversation, id: messageId }),
|
|
140
173
|
});
|
|
141
174
|
}
|
|
142
|
-
function receiptFromEndpointError(error) {
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
175
|
+
function receiptFromEndpointError(error, attempted = true) {
|
|
176
|
+
if (error instanceof EndpointDeliveryError) {
|
|
177
|
+
if (error.code === 'outbound_unsupported' || error.code === 'endpoint_not_found') {
|
|
178
|
+
return unsupportedDeliveryReceipt('outbound_unsupported');
|
|
179
|
+
}
|
|
180
|
+
if (error.code === 'unsupported_operation' && error.disposition === 'not_sent') {
|
|
181
|
+
return unsupportedDeliveryReceipt(error.code);
|
|
182
|
+
}
|
|
183
|
+
if (error.disposition === 'unknown')
|
|
184
|
+
return unknownDeliveryReceipt(error.code);
|
|
185
|
+
return failedDeliveryReceipt(error.code);
|
|
186
|
+
}
|
|
187
|
+
// imhelper ProtocolError exposes stable protocol facts without a Core SDK dependency.
|
|
188
|
+
if (error && typeof error === 'object' && 'protocol' in error && 'kind' in error && 'response' in error
|
|
189
|
+
&& error.protocol === 'onebot-v11' && error.kind === 'protocol') {
|
|
190
|
+
const response = error.response;
|
|
191
|
+
if (response && typeof response === 'object' && 'status' in response && response.status === 'failed') {
|
|
192
|
+
return failedDeliveryReceipt('platform_rejected');
|
|
193
|
+
}
|
|
146
194
|
}
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
195
|
+
// Before the endpoint send boundary no message can have entered a transport.
|
|
196
|
+
if (!attempted)
|
|
197
|
+
return failedDeliveryReceipt('endpoint_send_failed');
|
|
198
|
+
// Unknown SDK/network failures provide no evidence that replay is safe.
|
|
199
|
+
return unknownDeliveryReceipt('endpoint_send_failed');
|
|
200
|
+
}
|
|
201
|
+
function unknownDeliveryReceipt(code) {
|
|
202
|
+
return Object.freeze({
|
|
203
|
+
status: 'failed',
|
|
204
|
+
failure: Object.freeze({
|
|
205
|
+
code,
|
|
206
|
+
message: 'Message delivery is unconfirmed; resending may duplicate delivery.',
|
|
207
|
+
retryable: false,
|
|
208
|
+
deliveryUnknown: true,
|
|
209
|
+
}),
|
|
210
|
+
});
|
|
150
211
|
}
|
|
151
212
|
function suppressedDeliveryReceipt() {
|
|
152
213
|
return Object.freeze({ status: 'suppressed' });
|
|
@@ -1,7 +1,12 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type PluginId, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
2
2
|
import type { ConversationRef } from '@zhin.js/im-contract';
|
|
3
|
+
import { type JSXElement } from '@zhin.js/jsx';
|
|
3
4
|
import { type IncomingContext, type SendContent } from './contracts.js';
|
|
5
|
+
export interface OutboundRenderOptions {
|
|
6
|
+
readonly jsxCache?: WeakMap<JSXElement, Promise<string>>;
|
|
7
|
+
readonly signal?: AbortSignal;
|
|
8
|
+
}
|
|
4
9
|
export declare class OutboundRenderer {
|
|
5
10
|
#private;
|
|
6
|
-
render(content: SendContent, requester: PluginId, snapshot: RuntimeSnapshot, conversation?: ConversationRef, incoming?: IncomingContext): Promise<unknown>;
|
|
11
|
+
render(content: SendContent, requester: PluginId, snapshot: RuntimeSnapshot, conversation?: ConversationRef, incoming?: IncomingContext, options?: OutboundRenderOptions): Promise<unknown>;
|
|
7
12
|
}
|
|
@@ -1,21 +1,46 @@
|
|
|
1
1
|
import { componentHostToken } from '@zhin.js/plugin-runtime';
|
|
2
|
+
import { isJsxElement, renderToHtml } from '@zhin.js/jsx';
|
|
3
|
+
import { segment } from '../../utils.js';
|
|
4
|
+
import { flattenOutboundArray, MAX_OUTBOUND_ARRAY_DEPTH } from '../../built/outbound-content-arrays.js';
|
|
2
5
|
import { componentFeatureId, isComponentIndex, } from '@zhin.js/component';
|
|
3
6
|
import { isComponentCall, isRawContent, isSegmentContent, } from './contracts.js';
|
|
4
7
|
const maxComponentDepth = 32;
|
|
5
8
|
const TEMPLATE_MARKER = '${';
|
|
6
9
|
export class OutboundRenderer {
|
|
7
|
-
async render(content, requester, snapshot, conversation, incoming) {
|
|
10
|
+
async render(content, requester, snapshot, conversation, incoming, options = {}) {
|
|
11
|
+
options.signal?.throwIfAborted();
|
|
8
12
|
const host = resolveComponentHost(snapshot);
|
|
9
13
|
const ctx = conversation ? buildTemplateContext(conversation, incoming) : undefined;
|
|
10
|
-
|
|
14
|
+
const rendered = await this.#render(content, requester, snapshot, host, ctx, 0, options.jsxCache ?? new WeakMap(), options.signal, new Set());
|
|
15
|
+
options.signal?.throwIfAborted();
|
|
16
|
+
return rendered;
|
|
11
17
|
}
|
|
12
|
-
async #render(content, requester, snapshot, host, ctx, depth) {
|
|
18
|
+
async #render(content, requester, snapshot, host, ctx, depth, jsxCache, signal, arrayAncestors) {
|
|
19
|
+
signal?.throwIfAborted();
|
|
13
20
|
if (depth > maxComponentDepth)
|
|
14
21
|
throw new Error('Component render depth exceeded 32');
|
|
15
22
|
if (typeof content === 'string')
|
|
16
23
|
return compileText(content, host, ctx);
|
|
17
24
|
if (Array.isArray(content)) {
|
|
18
|
-
|
|
25
|
+
if (arrayAncestors.has(content))
|
|
26
|
+
throw new TypeError('Cyclic SendContent array');
|
|
27
|
+
if (arrayAncestors.size >= MAX_OUTBOUND_ARRAY_DEPTH)
|
|
28
|
+
throw new RangeError('SendContent array depth exceeded 512');
|
|
29
|
+
// Each parallel branch gets its own ancestry; repeated sibling arrays are valid.
|
|
30
|
+
const ancestors = new Set(arrayAncestors).add(content);
|
|
31
|
+
const items = await Promise.all(content.map((item) => this.#render(item, requester, snapshot, host, ctx, depth, jsxCache, signal, ancestors)));
|
|
32
|
+
signal?.throwIfAborted();
|
|
33
|
+
return flattenOutboundArray(items);
|
|
34
|
+
}
|
|
35
|
+
if (isJsxElement(content)) {
|
|
36
|
+
let html = jsxCache.get(content);
|
|
37
|
+
if (!html) {
|
|
38
|
+
html = renderToHtml(content);
|
|
39
|
+
jsxCache.set(content, html);
|
|
40
|
+
}
|
|
41
|
+
const rendered = await html;
|
|
42
|
+
signal?.throwIfAborted();
|
|
43
|
+
return rendered ? segment.html({ html: rendered }) : [];
|
|
19
44
|
}
|
|
20
45
|
if (isRawContent(content))
|
|
21
46
|
return content.payload;
|
|
@@ -29,8 +54,8 @@ export class OutboundRenderer {
|
|
|
29
54
|
return content;
|
|
30
55
|
}
|
|
31
56
|
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);
|
|
57
|
+
const rendered = await requireComponents(snapshot).render(requester, content.name, content.props, { snapshot, ...(signal ? { signal } : {}) });
|
|
58
|
+
return this.#render(rendered, requester, snapshot, host, ctx, depth + 1, jsxCache, signal, arrayAncestors);
|
|
34
59
|
}
|
|
35
60
|
throw new TypeError('Unsupported SendContent');
|
|
36
61
|
}
|
|
@@ -36,11 +36,16 @@ export interface OutboundSegmentsPolicy {
|
|
|
36
36
|
readonly outboundMedia: readonly ('url' | 'path' | 'base64' | 'upload')[];
|
|
37
37
|
readonly interactive?: InteractivePolicy;
|
|
38
38
|
readonly markdown?: 'native' | 'text';
|
|
39
|
+
readonly html?: 'direct' | 'image' | 'text';
|
|
39
40
|
}
|
|
40
41
|
export interface NormalizeOutboundOptions {
|
|
41
42
|
/** 缺省 `url-or-text`(未声明 adapter 的保守兜底:仅 URL 媒体可达)。 */
|
|
42
43
|
readonly mediaPolicy?: OutboundMediaPolicy;
|
|
44
|
+
readonly htmlPolicy?: 'direct' | 'image' | 'text';
|
|
45
|
+
readonly onHtmlFallback?: (reason: 'renderer_unavailable' | 'renderer_failed' | 'media_unsupported') => void;
|
|
43
46
|
}
|
|
47
|
+
/** HTML transport is an adapter capability, independent of its package name. */
|
|
48
|
+
export declare function resolveOutboundHtmlPolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): 'direct' | 'image' | 'text';
|
|
44
49
|
/**
|
|
45
50
|
* 解析端点的出站媒体策略:读 adapter definition 声明的 `segments.outboundMedia`
|
|
46
51
|
* (多 endpoint 展开的 `slot~entry` id 回退到 slot id 查声明);
|
|
@@ -53,6 +58,8 @@ export declare function isOutboundSegment(value: unknown): value is OutboundSegm
|
|
|
53
58
|
* `segments.interactive`,否则按平台名查内置表,未知平台回退 'text'。
|
|
54
59
|
*/
|
|
55
60
|
export declare function resolveOutboundInteractivePolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): InteractivePolicy;
|
|
61
|
+
/** Read declared support from this operation's snapshot without requiring live admission. */
|
|
62
|
+
export declare function resolveOutboundSupportedSegments(adapter: CapabilityId, snapshot: RuntimeSnapshot): readonly string[] | undefined;
|
|
56
63
|
/** Preserve semantic Markdown only when the endpoint explicitly declares native consumption. */
|
|
57
64
|
export declare function resolveOutboundMarkdownPolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): 'native' | 'text';
|
|
58
65
|
export declare function applyOutboundMarkdownPolicy(payload: unknown, policy: 'native' | 'text'): unknown;
|
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
import { htmlToFallbackText } from '../../built/html-to-text.js';
|
|
2
|
+
import { flattenOutboundArray } from '../../built/outbound-content-arrays.js';
|
|
2
3
|
import { toCanonicalSegments } from '../../built/generic-segment-mapper.js';
|
|
3
4
|
import { effectiveKeyboardFallbackMap, renderKeyboardAsText, } from '../../built/interactive-segments/resolve.js';
|
|
4
5
|
import { DEFAULT_INTERACTIVE_POLICY, isKeyboardSegment, } from '../../built/interactive-segments/types.js';
|
|
5
6
|
import { isMediaRef } from '../../built/segment-contract/index.js';
|
|
6
7
|
import { markdownToPlainText } from '../../built/rich-segments/markdown-to-text.js';
|
|
8
|
+
/** HTML transport is an adapter capability, independent of its package name. */
|
|
9
|
+
export function resolveOutboundHtmlPolicy(adapter, snapshot) {
|
|
10
|
+
const slot = snapshot.capabilities.get(adapter) ?? snapshot.capabilities.get(baseSlotCapabilityId(adapter));
|
|
11
|
+
const policy = slot?.definition?.segments?.html;
|
|
12
|
+
return policy === 'direct' || policy === 'text' ? policy : 'image';
|
|
13
|
+
}
|
|
7
14
|
const DEFAULT_CARD_WIDTH = 540;
|
|
8
15
|
const DEFAULT_CARD_FILENAME = 'card.png';
|
|
9
16
|
const DEFAULT_MEDIA_POLICY = 'url-or-text';
|
|
@@ -64,6 +71,14 @@ export function resolveOutboundInteractivePolicy(adapter, snapshot) {
|
|
|
64
71
|
return (adapterType ? OUTBOUND_INTERACTIVE_POLICY_BY_ADAPTER[adapterType] : undefined)
|
|
65
72
|
?? DEFAULT_INTERACTIVE_POLICY;
|
|
66
73
|
}
|
|
74
|
+
/** Read declared support from this operation's snapshot without requiring live admission. */
|
|
75
|
+
export function resolveOutboundSupportedSegments(adapter, snapshot) {
|
|
76
|
+
const slot = snapshot.capabilities.get(adapter) ?? snapshot.capabilities.get(baseSlotCapabilityId(adapter));
|
|
77
|
+
if (!slot?.definition || typeof slot.definition !== 'object')
|
|
78
|
+
return undefined;
|
|
79
|
+
const segments = slot.definition.segments;
|
|
80
|
+
return Array.isArray(segments?.supported) && segments.supported.every(type => typeof type === 'string') ? segments.supported : undefined;
|
|
81
|
+
}
|
|
67
82
|
/** Preserve semantic Markdown only when the endpoint explicitly declares native consumption. */
|
|
68
83
|
export function resolveOutboundMarkdownPolicy(adapter, snapshot) {
|
|
69
84
|
const slot = snapshot.capabilities.get(adapter)
|
|
@@ -134,11 +149,11 @@ function adapterTypeName(packageName) {
|
|
|
134
149
|
export async function normalizeOutboundPayload(payload, renderer, options) {
|
|
135
150
|
const mediaPolicy = options?.mediaPolicy ?? DEFAULT_MEDIA_POLICY;
|
|
136
151
|
if (Array.isArray(payload)) {
|
|
137
|
-
const resolved = await Promise.all(payload.map((item) => normalizeOneSegment(item, renderer, mediaPolicy)));
|
|
152
|
+
const resolved = await Promise.all(flattenOutboundArray(payload).map((item) => normalizeOneSegment(item, renderer, mediaPolicy, options)));
|
|
138
153
|
return applyOutboundMediaPolicy(resolved, mediaPolicy);
|
|
139
154
|
}
|
|
140
155
|
if (isOutboundSegment(payload)) {
|
|
141
|
-
return applyOutboundMediaPolicy([await normalizeOneSegment(payload, renderer, mediaPolicy)], mediaPolicy);
|
|
156
|
+
return applyOutboundMediaPolicy([await normalizeOneSegment(payload, renderer, mediaPolicy, options)], mediaPolicy);
|
|
142
157
|
}
|
|
143
158
|
return payload;
|
|
144
159
|
}
|
|
@@ -149,16 +164,24 @@ export async function normalizeOutboundPayload(payload, renderer, options) {
|
|
|
149
164
|
* - 其余项经 `toCanonicalSegments` 归一(字符串→text、at→mention、
|
|
150
165
|
* 旧 wire 字段 `{url,file,base64}`→MediaRef)。
|
|
151
166
|
*/
|
|
152
|
-
async function normalizeOneSegment(item, renderer, mediaPolicy) {
|
|
167
|
+
async function normalizeOneSegment(item, renderer, mediaPolicy, options) {
|
|
153
168
|
if (isOutboundSegment(item) && item.type === 'html') {
|
|
154
|
-
|
|
169
|
+
if (item.data?.html === '') {
|
|
170
|
+
return { type: 'text', data: { text: htmlSegmentFallbackText(item.data, '') } };
|
|
171
|
+
}
|
|
172
|
+
if (options?.htmlPolicy === 'direct')
|
|
173
|
+
return toCanonicalSegments([item])[0];
|
|
174
|
+
return renderHtmlSegment(item, renderer, mediaPolicy, options);
|
|
155
175
|
}
|
|
156
176
|
return toCanonicalSegments([item])[0];
|
|
157
177
|
}
|
|
158
|
-
async function renderHtmlSegment(segment, renderer, mediaPolicy) {
|
|
178
|
+
async function renderHtmlSegment(segment, renderer, mediaPolicy, options) {
|
|
159
179
|
const data = segment.data ?? {};
|
|
160
180
|
const html = typeof data.html === 'string' ? data.html : '';
|
|
161
181
|
// url-or-text 端点无法投递 base64 图片(本层无上传通道),直接文本降级,跳过渲染。
|
|
182
|
+
if (options?.htmlPolicy === 'text') {
|
|
183
|
+
return { type: 'text', data: { text: htmlSegmentFallbackText(data, html) } };
|
|
184
|
+
}
|
|
162
185
|
if (html && renderer && mediaPolicy !== 'url-or-text') {
|
|
163
186
|
try {
|
|
164
187
|
const result = await renderer.render(html, {
|
|
@@ -182,11 +205,15 @@ async function renderHtmlSegment(segment, renderer, mediaPolicy) {
|
|
|
182
205
|
},
|
|
183
206
|
};
|
|
184
207
|
}
|
|
208
|
+
options?.onHtmlFallback?.('renderer_failed');
|
|
185
209
|
}
|
|
186
210
|
catch {
|
|
187
|
-
|
|
211
|
+
options?.onHtmlFallback?.('renderer_failed');
|
|
188
212
|
}
|
|
189
213
|
}
|
|
214
|
+
else if (html) {
|
|
215
|
+
options?.onHtmlFallback?.(mediaPolicy === 'url-or-text' ? 'media_unsupported' : 'renderer_unavailable');
|
|
216
|
+
}
|
|
190
217
|
return { type: 'text', data: { text: htmlSegmentFallbackText(data, html) } };
|
|
191
218
|
}
|
|
192
219
|
/**
|
|
@@ -3,7 +3,7 @@ import { isMiddlewareIndex, middlewareFeatureId } from '@zhin.js/middleware';
|
|
|
3
3
|
export async function runRuntimeMiddleware(snapshot, input, terminal, target) {
|
|
4
4
|
const index = middleware(snapshot);
|
|
5
5
|
if (index)
|
|
6
|
-
await index.run(input, terminal, target);
|
|
6
|
+
await index.run(input, terminal, target, snapshot);
|
|
7
7
|
else
|
|
8
8
|
await terminal();
|
|
9
9
|
}
|