@zhin.js/core 1.1.42 → 1.1.44
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/roles.d.ts +6 -1
- package/lib/built/roles.js +11 -20
- package/lib/built/segment-contract/validate.d.ts +301 -158
- package/lib/built/user-interaction.js +9 -3
- package/lib/feature/middleware-public-api.d.ts +5 -0
- package/lib/feature/middleware-public-api.js +5 -0
- package/lib/feature/middleware.d.ts +20 -2
- package/lib/feature/middleware.js +6 -2
- package/lib/plugin-runtime/im/contracts.d.ts +14 -0
- package/lib/plugin-runtime/im/contracts.js +3 -1
- package/lib/plugin-runtime/im/conversation-runtime.d.ts +13 -1
- package/lib/plugin-runtime/im/conversation-runtime.js +47 -1
- package/lib/plugin-runtime/im/endpoint-runtime.d.ts +8 -3
- package/lib/plugin-runtime/im/endpoint-runtime.js +46 -3
- package/lib/plugin-runtime/im/im-runtime.d.ts +12 -1
- package/lib/plugin-runtime/im/im-runtime.js +18 -1
- package/lib/plugin-runtime/im/inbound-dedup.d.ts +51 -0
- package/lib/plugin-runtime/im/inbound-dedup.js +184 -0
- package/lib/plugin-runtime/im/inbound-origin.d.ts +101 -0
- package/lib/plugin-runtime/im/inbound-origin.js +76 -0
- package/lib/plugin-runtime/im/inbound-runtime.d.ts +16 -2
- package/lib/plugin-runtime/im/inbound-runtime.js +235 -11
- package/lib/plugin-runtime/im/index.d.ts +3 -1
- package/lib/plugin-runtime/im/index.js +1 -0
- package/lib/plugin-runtime/im/interaction-runtime.d.ts +11 -0
- package/lib/plugin-runtime/im/interaction-runtime.js +17 -0
- package/lib/plugin-runtime/im/interactive-router.d.ts +18 -1
- package/lib/plugin-runtime/im/interactive-router.js +62 -8
- package/lib/plugin-runtime/im/jsx-button-registry.js +6 -2
- package/lib/plugin-runtime/im/message-dispatcher.js +10 -0
- package/lib/plugin-runtime/im/message-events.d.ts +7 -0
- package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +2 -0
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +37 -45
- package/lib/plugin-runtime/im/outbound-ledger.d.ts +24 -0
- package/lib/plugin-runtime/im/outbound-ledger.js +114 -0
- package/lib/plugin-runtime/im/outbound-projection.d.ts +15 -0
- package/lib/plugin-runtime/im/outbound-projection.js +55 -0
- package/lib/plugin-runtime/im/outbound-renderer.d.ts +3 -0
- package/lib/plugin-runtime/im/outbound-renderer.js +18 -0
- package/lib/plugin-runtime/im/outbound-segments.d.ts +3 -0
- package/lib/plugin-runtime/im/outbound-segments.js +34 -5
- package/package.json +19 -30
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type ConversationRef } from '@zhin.js/im-contract';
|
|
2
|
+
import type { Segment } from '../../built/segment-contract/types.js';
|
|
2
3
|
import type { Message } from './contracts.js';
|
|
3
4
|
type RuntimeInteractiveHandler = (message: Message) => Promise<boolean> | boolean;
|
|
4
5
|
/**
|
|
@@ -11,7 +12,23 @@ export declare class RuntimeInteractiveRouter<Admission = never> {
|
|
|
11
12
|
constructor(fallbackTtlMs?: number);
|
|
12
13
|
register(prefix: string, handler: RuntimeInteractiveHandler, admission?: Admission): () => void;
|
|
13
14
|
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>, ttlMs?: number): Record<string, string>;
|
|
15
|
+
/**
|
|
16
|
+
* Content-aware probe for Room routing: would this input resolve against an unexpired keyboard
|
|
17
|
+
* fallback on this exact (Endpoint-scoped) conversation and generation? A live keyboard alone is
|
|
18
|
+
* not an answer. With an action segment, only a payload that belongs to one of this
|
|
19
|
+
* conversation's live fallback maps counts; plain text counts only when its label / number maps
|
|
20
|
+
* to a button. Strictly read-only: it never calls `#pruneFallbacks()` and never mutates state;
|
|
21
|
+
* expired entries are simply ignored.
|
|
22
|
+
*/
|
|
23
|
+
resolvesLiveFallback(conversation: ConversationRef, generation: number, input: {
|
|
24
|
+
readonly content: string;
|
|
25
|
+
readonly segments?: readonly Segment[];
|
|
26
|
+
}): boolean;
|
|
14
27
|
resolvePayload(message: Message): string | undefined;
|
|
28
|
+
/** Bounded label-only history: stale text buttons are not mistaken for new input. */
|
|
29
|
+
isExpiredFallback(message: Message): boolean;
|
|
15
30
|
dispatch(message: Message, admission?: Admission): Promise<boolean>;
|
|
16
31
|
}
|
|
32
|
+
/** @internal Payload of the first action segment (platform callback) that carries a non-empty string. */
|
|
33
|
+
export declare function actionPayloadFromSegments(segments: readonly Segment[] | undefined): string | undefined;
|
|
17
34
|
export {};
|
|
@@ -1,12 +1,9 @@
|
|
|
1
|
+
import { conversationRefKey } from '@zhin.js/im-contract';
|
|
1
2
|
import { resolvePayloadFromText } from '../../built/interactive-segments/action.js';
|
|
2
3
|
const DEFAULT_FALLBACK_TTL_MS = 60 * 60 * 1000;
|
|
4
|
+
const MAX_EXPIRED_BATCHES = 1000;
|
|
3
5
|
function interactiveConversationKey(conversation, generation) {
|
|
4
|
-
|
|
5
|
-
const parent = conversation.parent
|
|
6
|
-
? `@${conversation.parent.kind}:${conversation.parent.id}`
|
|
7
|
-
: '';
|
|
8
|
-
const thread = conversation.threadId ? `#${conversation.threadId}` : '';
|
|
9
|
-
return `${generation}:${base}${parent}${thread}`;
|
|
6
|
+
return `${generation}:${conversationRefKey(conversation)}`;
|
|
10
7
|
}
|
|
11
8
|
/**
|
|
12
9
|
* One ImRuntime-owned authority for interactive routing and keyboard fallback state.
|
|
@@ -16,6 +13,7 @@ export class RuntimeInteractiveRouter {
|
|
|
16
13
|
fallbackTtlMs;
|
|
17
14
|
#handlers = [];
|
|
18
15
|
#fallbacks = new Map();
|
|
16
|
+
#expired = [];
|
|
19
17
|
#nextNumber = 1;
|
|
20
18
|
constructor(fallbackTtlMs = DEFAULT_FALLBACK_TTL_MS) {
|
|
21
19
|
this.fallbackTtlMs = fallbackTtlMs;
|
|
@@ -48,6 +46,29 @@ export class RuntimeInteractiveRouter {
|
|
|
48
46
|
this.#fallbacks.set(key, entries);
|
|
49
47
|
return allocated;
|
|
50
48
|
}
|
|
49
|
+
/**
|
|
50
|
+
* Content-aware probe for Room routing: would this input resolve against an unexpired keyboard
|
|
51
|
+
* fallback on this exact (Endpoint-scoped) conversation and generation? A live keyboard alone is
|
|
52
|
+
* not an answer. With an action segment, only a payload that belongs to one of this
|
|
53
|
+
* conversation's live fallback maps counts; plain text counts only when its label / number maps
|
|
54
|
+
* to a button. Strictly read-only: it never calls `#pruneFallbacks()` and never mutates state;
|
|
55
|
+
* expired entries are simply ignored.
|
|
56
|
+
*/
|
|
57
|
+
resolvesLiveFallback(conversation, generation, input) {
|
|
58
|
+
const now = Date.now();
|
|
59
|
+
const entries = this.#fallbacks.get(interactiveConversationKey(conversation, generation));
|
|
60
|
+
const live = entries?.filter(entry => entry.expiresAt > now);
|
|
61
|
+
if (!live?.length)
|
|
62
|
+
return false;
|
|
63
|
+
const actionPayload = actionPayloadFromSegments(input.segments);
|
|
64
|
+
if (actionPayload !== undefined) {
|
|
65
|
+
return live.some(entry => Object.values(entry.map).includes(actionPayload));
|
|
66
|
+
}
|
|
67
|
+
const raw = input.content.trim();
|
|
68
|
+
if (!raw)
|
|
69
|
+
return false;
|
|
70
|
+
return resolvePayloadFromText(raw, Object.assign({}, ...live.map(entry => entry.map))) !== undefined;
|
|
71
|
+
}
|
|
51
72
|
resolvePayload(message) {
|
|
52
73
|
const fromSegments = actionPayloadFromSegments(message.segments);
|
|
53
74
|
if (fromSegments)
|
|
@@ -57,6 +78,23 @@ export class RuntimeInteractiveRouter {
|
|
|
57
78
|
return undefined;
|
|
58
79
|
return resolvePayloadFromText(raw, this.#fallbackMap(message.conversation, message.generation));
|
|
59
80
|
}
|
|
81
|
+
/** Bounded label-only history: stale text buttons are not mistaken for new input. */
|
|
82
|
+
isExpiredFallback(message) {
|
|
83
|
+
if (actionPayloadFromSegments(message.segments) || this.resolvePayload(message))
|
|
84
|
+
return false;
|
|
85
|
+
const key = conversationRefKey(message.conversation);
|
|
86
|
+
const currentKey = interactiveConversationKey(message.conversation, message.generation);
|
|
87
|
+
const matches = (map) => resolvePayloadFromText(message.content, map) !== undefined;
|
|
88
|
+
if (this.#expired.some(entry => entry.conversationKey === key && matches(entry.map)))
|
|
89
|
+
return true;
|
|
90
|
+
// A generation change invalidates even a keyboard whose TTL has not elapsed.
|
|
91
|
+
for (const [batchKey, entries] of this.#fallbacks) {
|
|
92
|
+
if (batchKey !== currentKey && batchKey.slice(batchKey.indexOf(':') + 1) === key
|
|
93
|
+
&& entries.some(entry => matches(entry.map)))
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
60
98
|
async dispatch(message, admission) {
|
|
61
99
|
const payload = this.resolvePayload(message);
|
|
62
100
|
if (!payload)
|
|
@@ -81,15 +119,31 @@ export class RuntimeInteractiveRouter {
|
|
|
81
119
|
#pruneFallbacks() {
|
|
82
120
|
const now = Date.now();
|
|
83
121
|
for (const [key, entries] of this.#fallbacks) {
|
|
84
|
-
const active = entries.filter(entry => entry.expiresAt
|
|
122
|
+
const active = entries.filter(entry => entry.expiresAt > now);
|
|
123
|
+
for (const entry of entries) {
|
|
124
|
+
if (entry.expiresAt > now || entry.expiresAt + this.fallbackTtlMs <= now)
|
|
125
|
+
continue;
|
|
126
|
+
this.#expired.push({
|
|
127
|
+
conversationKey: key.slice(key.indexOf(':') + 1),
|
|
128
|
+
map: Object.freeze(Object.fromEntries(Object.keys(entry.map).map(label => [label, 'expired']))),
|
|
129
|
+
expiresAt: entry.expiresAt + this.fallbackTtlMs,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
85
132
|
if (active.length)
|
|
86
133
|
this.#fallbacks.set(key, active);
|
|
87
134
|
else
|
|
88
135
|
this.#fallbacks.delete(key);
|
|
89
136
|
}
|
|
137
|
+
for (let i = this.#expired.length - 1; i >= 0; i--) {
|
|
138
|
+
if (this.#expired[i].expiresAt <= now)
|
|
139
|
+
this.#expired.splice(i, 1);
|
|
140
|
+
}
|
|
141
|
+
if (this.#expired.length > MAX_EXPIRED_BATCHES)
|
|
142
|
+
this.#expired.splice(0, this.#expired.length - MAX_EXPIRED_BATCHES);
|
|
90
143
|
}
|
|
91
144
|
}
|
|
92
|
-
|
|
145
|
+
/** @internal Payload of the first action segment (platform callback) that carries a non-empty string. */
|
|
146
|
+
export function actionPayloadFromSegments(segments) {
|
|
93
147
|
for (const segment of segments ?? []) {
|
|
94
148
|
if (segment.type !== 'action')
|
|
95
149
|
continue;
|
|
@@ -62,8 +62,12 @@ export class JsxButtonRegistry {
|
|
|
62
62
|
if (active)
|
|
63
63
|
this.#prune(active);
|
|
64
64
|
const binding = active?.get(payload);
|
|
65
|
-
//
|
|
66
|
-
if (!binding
|
|
65
|
+
// Never invoke a retired closure. The reply uses this incoming operation's scope.
|
|
66
|
+
if (!binding) {
|
|
67
|
+
await message.$reply('交互已过期或不可用,请重新发起。');
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
if (binding.conversationKey !== conversationRefKey(message.conversation))
|
|
67
71
|
return true;
|
|
68
72
|
const bound = bindOperationInput(message, binding.requester, snapshot);
|
|
69
73
|
const content = await binding.onClick(bound);
|
|
@@ -60,6 +60,16 @@ export class MessageDispatcher {
|
|
|
60
60
|
: undefined;
|
|
61
61
|
const matchInput = structuredInput ?? input;
|
|
62
62
|
const result = await commands.dispatch(matchInput, message, interactionFactory, prefix, snapshot);
|
|
63
|
+
if (result.status === 'invalid') {
|
|
64
|
+
return Object.freeze({
|
|
65
|
+
...result,
|
|
66
|
+
value: [...(result.issues ?? []).map((issue) => issue.message), result.help]
|
|
67
|
+
.filter(Boolean).join('\n'),
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
if (result.status === 'denied') {
|
|
71
|
+
return Object.freeze({ ...result, value: '没有权限执行此指令。' });
|
|
72
|
+
}
|
|
63
73
|
if (result.matched && result.value !== undefined) {
|
|
64
74
|
if (!result.owner)
|
|
65
75
|
throw new Error('Matched Command is missing its owner');
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import type { PluginId } from '@zhin.js/plugin-runtime';
|
|
2
2
|
import type { ConversationRef } from '@zhin.js/im-contract';
|
|
3
3
|
import type { MessageSenderRef } from './contracts.js';
|
|
4
|
+
export type OutboundFallbackReason = 'renderer_unavailable' | 'renderer_failed' | 'media_unsupported' | 'html_text_policy' | 'markdown_text_policy' | 'interactive_text_policy';
|
|
5
|
+
/** Final payload handed to the Endpoint, not a claim about the remote client's display. */
|
|
6
|
+
export interface RuntimeMessageRendering {
|
|
7
|
+
readonly forms: readonly ('text' | 'image' | 'native')[];
|
|
8
|
+
readonly fallbacks: readonly OutboundFallbackReason[];
|
|
9
|
+
}
|
|
4
10
|
/** Bounded message projection for runtime observers such as Console and Inbox. */
|
|
5
11
|
export interface RuntimeMessageEvent {
|
|
6
12
|
readonly direction: 'inbound' | 'outbound';
|
|
@@ -10,6 +16,7 @@ export interface RuntimeMessageEvent {
|
|
|
10
16
|
readonly contentPreview: string;
|
|
11
17
|
readonly messageId?: string;
|
|
12
18
|
readonly timestamp: number;
|
|
19
|
+
readonly rendering?: RuntimeMessageRendering;
|
|
13
20
|
}
|
|
14
21
|
export interface RuntimeMessageEventSource {
|
|
15
22
|
subscribe(listener: (event: RuntimeMessageEvent) => void): () => void;
|
|
@@ -7,6 +7,8 @@ import { type JsxButtonBatch } from './jsx-button-registry.js';
|
|
|
7
7
|
interface OutboundDeliveryContext {
|
|
8
8
|
prepareButtons?(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
|
|
9
9
|
record(request: SendRequest, receipt: DeliveryReceipt): Promise<void>;
|
|
10
|
+
/** Side-channel correlation ledger for inbound origin; failures never affect the receipt. */
|
|
11
|
+
ledger?(conversation: ConversationRef, receipt: DeliveryReceipt, payload: unknown): void;
|
|
10
12
|
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>): Record<string, string> | void;
|
|
11
13
|
publish(event: RuntimeMessageEvent): void;
|
|
12
14
|
}
|
|
@@ -1,11 +1,9 @@
|
|
|
1
|
-
import { htmlRendererToken, } from '@zhin.js/plugin-runtime';
|
|
2
1
|
import { EndpointDeliveryError } from '@zhin.js/im-contract';
|
|
3
2
|
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
4
3
|
import { isJsxElement } from '@zhin.js/jsx';
|
|
5
4
|
import { createOutboundEnvelope, isComponentCall, isRawContent } from './contracts.js';
|
|
6
5
|
import { OutboundRenderer } from './outbound-renderer.js';
|
|
7
|
-
import {
|
|
8
|
-
import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
|
|
6
|
+
import { projectOutboundPayload } from './outbound-projection.js';
|
|
9
7
|
import { flattenOutboundArray } from '../../built/outbound-content-arrays.js';
|
|
10
8
|
import { requireAdapters } from './endpoint-runtime.js';
|
|
11
9
|
import { formatConversationLog, previewMessageContent } from './message-events.js';
|
|
@@ -26,9 +24,11 @@ export class OutboundDeliveryRuntime {
|
|
|
26
24
|
const buttons = this.context.prepareButtons?.(request, snapshot);
|
|
27
25
|
const renderOptions = { jsxCache, bindButton: buttons?.bind };
|
|
28
26
|
let initialPayload;
|
|
27
|
+
let initialProjection;
|
|
29
28
|
try {
|
|
30
29
|
const rendered = await this.#renderer.render(request.content, request.requester, snapshot, request.conversation, request.incoming, renderOptions);
|
|
31
|
-
|
|
30
|
+
initialProjection = await projectOutboundPayload(rendered, request.conversation, snapshot, { deferInteractive: true });
|
|
31
|
+
initialPayload = initialProjection.payload;
|
|
32
32
|
}
|
|
33
33
|
catch (error) {
|
|
34
34
|
if (error instanceof EndpointDeliveryError && error.code === 'unsupported_operation' && error.disposition === 'not_sent')
|
|
@@ -48,12 +48,22 @@ export class OutboundDeliveryRuntime {
|
|
|
48
48
|
generation: snapshot.generation,
|
|
49
49
|
clientAdapter: adapters.clientAdapter(adapter),
|
|
50
50
|
}, initialPayload, () => adapters.clientById(adapter));
|
|
51
|
+
// Record identities and fallback text before middleware can mutate the array
|
|
52
|
+
// or its segments. Do not copy/serialize media buffers or streams.
|
|
53
|
+
const initialItems = Array.isArray(initialPayload) ? initialPayload.map(item => ({
|
|
54
|
+
item, type: item?.type, text: item?.type === 'text' ? item.data?.text : undefined,
|
|
55
|
+
})) : undefined;
|
|
56
|
+
const retainsInitialProjection = (value) => value === initialPayload
|
|
57
|
+
&& (!initialItems || (Array.isArray(value) && value.length === initialItems.length
|
|
58
|
+
&& initialItems.every(({ item, type, text }, index) => value[index] === item
|
|
59
|
+
&& item?.type === type && (type !== 'text' || item.data?.text === text))));
|
|
51
60
|
let terminalEntered = false;
|
|
52
61
|
let receipt;
|
|
53
62
|
try {
|
|
54
63
|
await runRuntimeMiddleware(snapshot, envelope, async () => {
|
|
55
64
|
terminalEntered = true;
|
|
56
65
|
let payload;
|
|
66
|
+
let projection;
|
|
57
67
|
const buttonPayloads = new Set();
|
|
58
68
|
try {
|
|
59
69
|
// Native payload replacements remain possible; only authoring values need evaluation.
|
|
@@ -61,11 +71,15 @@ export class OutboundDeliveryRuntime {
|
|
|
61
71
|
const replaced = replacement !== initialPayload && needsAuthoringRender(replacement)
|
|
62
72
|
? await this.#renderer.render(replacement, request.requester, snapshot, request.conversation, request.incoming, renderOptions)
|
|
63
73
|
: replacement;
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
74
|
+
projection = await projectOutboundPayload(replaced, request.conversation, snapshot, {
|
|
75
|
+
inheritedFallbacks: retainsInitialProjection(replacement) ? initialProjection.rendering.fallbacks : [],
|
|
76
|
+
rememberFallback: (map) => {
|
|
77
|
+
for (const value of Object.values(map))
|
|
78
|
+
buttonPayloads.add(value);
|
|
79
|
+
return this.context.rememberFallback(request.conversation, snapshot.generation, map);
|
|
80
|
+
},
|
|
68
81
|
});
|
|
82
|
+
payload = projection.payload;
|
|
69
83
|
for (const value of collectButtonPayloads(payload))
|
|
70
84
|
buttonPayloads.add(value);
|
|
71
85
|
}
|
|
@@ -93,8 +107,15 @@ export class OutboundDeliveryRuntime {
|
|
|
93
107
|
revokeButtons?.();
|
|
94
108
|
if (receipt.status === 'sent') {
|
|
95
109
|
await this.context.record(request, receipt);
|
|
110
|
+
try {
|
|
111
|
+
this.context.ledger?.(request.conversation, receipt, payload);
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
logger.warn(`outbound ledger write failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
115
|
+
}
|
|
96
116
|
this.context.publish({
|
|
97
117
|
direction: 'outbound',
|
|
118
|
+
rendering: projection.rendering,
|
|
98
119
|
conversation: request.conversation,
|
|
99
120
|
requester: request.requester,
|
|
100
121
|
contentPreview: previewMessageContent(payload),
|
|
@@ -144,38 +165,6 @@ export function failedDeliveryReceipt(code, retryable = false) {
|
|
|
144
165
|
}),
|
|
145
166
|
});
|
|
146
167
|
}
|
|
147
|
-
async function prepareOutboundPayload(rendered, conversation, snapshot, rememberInteractiveFallback) {
|
|
148
|
-
const adapter = conversation.endpoint.id;
|
|
149
|
-
const markdownResolved = applyOutboundMarkdownPolicy(Array.isArray(rendered) ? flattenOutboundArray(rendered) : rendered, resolveOutboundMarkdownPolicy(adapter, snapshot));
|
|
150
|
-
let payload = await normalizeOutboundPayload(markdownResolved, resolveHtmlRenderer(snapshot), {
|
|
151
|
-
mediaPolicy: resolveOutboundMediaPolicy(adapter, snapshot),
|
|
152
|
-
htmlPolicy: resolveOutboundHtmlPolicy(adapter, snapshot),
|
|
153
|
-
onHtmlFallback: reason => logger.debug(formatCompact({ op: 'html_fallback', reason, generation: snapshot.generation })),
|
|
154
|
-
});
|
|
155
|
-
if (rememberInteractiveFallback) {
|
|
156
|
-
payload = applyOutboundInteractivePolicy(payload, resolveOutboundInteractivePolicy(adapter, snapshot), rememberInteractiveFallback);
|
|
157
|
-
}
|
|
158
|
-
if (Array.isArray(payload)) {
|
|
159
|
-
// Empty text carries no wire content, including HTML's empty fallback.
|
|
160
|
-
// Remove it before canonical validation (required strings reject '').
|
|
161
|
-
payload = payload.filter(item => !(item?.type === 'text' && item.data?.text === ''));
|
|
162
|
-
assertCanonicalSegments(payload);
|
|
163
|
-
}
|
|
164
|
-
const supported = resolveOutboundSupportedSegments(adapter, snapshot);
|
|
165
|
-
const supportedPayload = rememberInteractiveFallback ? payload : applyOutboundInteractivePolicy(payload, resolveOutboundInteractivePolicy(adapter, snapshot));
|
|
166
|
-
if (supported && Array.isArray(supportedPayload)) {
|
|
167
|
-
const unsupported = supportedPayload.find(segment => segment && typeof segment === 'object' && typeof segment.type === 'string' && !supported.includes(segment.type));
|
|
168
|
-
if (unsupported)
|
|
169
|
-
throw new EndpointDeliveryError('unsupported_operation', `Adapter does not support canonical segment ${unsupported.type}`, 'not_sent');
|
|
170
|
-
}
|
|
171
|
-
return payload;
|
|
172
|
-
}
|
|
173
|
-
function resolveHtmlRenderer(snapshot) {
|
|
174
|
-
const host = snapshot.resources.get(snapshot.root)?.get(htmlRendererToken.id);
|
|
175
|
-
return host && typeof host.render === 'function'
|
|
176
|
-
? host
|
|
177
|
-
: undefined;
|
|
178
|
-
}
|
|
179
168
|
function receiptFromEndpointResult(messageId, conversation) {
|
|
180
169
|
if (typeof messageId !== 'string' || messageId.trim() === '') {
|
|
181
170
|
return unknownDeliveryReceipt('delivery_unconfirmed');
|
|
@@ -187,14 +176,17 @@ function receiptFromEndpointResult(messageId, conversation) {
|
|
|
187
176
|
}
|
|
188
177
|
function receiptFromEndpointError(error, attempted = true) {
|
|
189
178
|
if (error instanceof EndpointDeliveryError) {
|
|
179
|
+
// Disposition is transport evidence; an error code alone cannot override it.
|
|
180
|
+
if (error.disposition === 'unknown')
|
|
181
|
+
return unknownDeliveryReceipt(error.code);
|
|
182
|
+
if (error.disposition === 'rejected')
|
|
183
|
+
return rejectedDeliveryReceipt(error.code, 'Endpoint rejected outbound delivery.');
|
|
190
184
|
if (error.code === 'outbound_unsupported' || error.code === 'endpoint_not_found') {
|
|
191
185
|
return unsupportedDeliveryReceipt('outbound_unsupported');
|
|
192
186
|
}
|
|
193
187
|
if (error.code === 'unsupported_operation' && error.disposition === 'not_sent') {
|
|
194
188
|
return unsupportedDeliveryReceipt(error.code);
|
|
195
189
|
}
|
|
196
|
-
if (error.disposition === 'unknown')
|
|
197
|
-
return unknownDeliveryReceipt(error.code);
|
|
198
190
|
return failedDeliveryReceipt(error.code);
|
|
199
191
|
}
|
|
200
192
|
// imhelper ProtocolError exposes stable protocol facts without a Core SDK dependency.
|
|
@@ -202,7 +194,7 @@ function receiptFromEndpointError(error, attempted = true) {
|
|
|
202
194
|
&& error.protocol === 'onebot-v11' && error.kind === 'protocol') {
|
|
203
195
|
const response = error.response;
|
|
204
196
|
if (response && typeof response === 'object' && 'status' in response && response.status === 'failed') {
|
|
205
|
-
return
|
|
197
|
+
return rejectedDeliveryReceipt('platform_rejected', 'Endpoint rejected outbound delivery.');
|
|
206
198
|
}
|
|
207
199
|
}
|
|
208
200
|
// Before the endpoint send boundary no message can have entered a transport.
|
|
@@ -231,9 +223,9 @@ function unsupportedDeliveryReceipt(code) {
|
|
|
231
223
|
failure: Object.freeze({ code, message: 'Outbound delivery is not supported.' }),
|
|
232
224
|
});
|
|
233
225
|
}
|
|
234
|
-
function rejectedDeliveryReceipt(code) {
|
|
226
|
+
function rejectedDeliveryReceipt(code, message = 'Outbound payload was rejected.') {
|
|
235
227
|
return Object.freeze({
|
|
236
228
|
status: 'rejected',
|
|
237
|
-
failure: Object.freeze({ code, message
|
|
229
|
+
failure: Object.freeze({ code, message }),
|
|
238
230
|
});
|
|
239
231
|
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { ConversationRef, DeliveryReceipt } from '@zhin.js/im-contract';
|
|
2
|
+
/**
|
|
3
|
+
* scope 键不含 endpoint id:同一个群里不同 Bot 的 conversationRefKey 不同,
|
|
4
|
+
* 但它们互相的回显仍属同一会话。
|
|
5
|
+
*/
|
|
6
|
+
export declare function ledgerScopeOf(conversation: ConversationRef): string;
|
|
7
|
+
export declare function digestText(text: string): string | undefined;
|
|
8
|
+
export interface LedgerMatch {
|
|
9
|
+
readonly endpointId: string;
|
|
10
|
+
}
|
|
11
|
+
export declare class OutboundLedger {
|
|
12
|
+
#private;
|
|
13
|
+
private readonly now;
|
|
14
|
+
constructor(now?: () => number);
|
|
15
|
+
get size(): number;
|
|
16
|
+
/** 仅在 `receipt.status === 'sent'` 时记录;`payload` 应为最终投影后的 payload。 */
|
|
17
|
+
record(conversation: ConversationRef, receipt: DeliveryReceipt, payload: unknown): void;
|
|
18
|
+
matchById(scope: string, messageId: unknown): LedgerMatch | undefined;
|
|
19
|
+
/**
|
|
20
|
+
* 摘要兜底(“账号 id 对不上”时):30 秒窗口、一次性。
|
|
21
|
+
* 权衡:人类在窗口内原样复读 Bot 刚发的文本,会被当作回显丢弃一次。
|
|
22
|
+
*/
|
|
23
|
+
matchByDigest(scope: string, text: string, now?: number): LedgerMatch | undefined;
|
|
24
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { segmentsToPlainText } from '../../built/segment-contract/text.js';
|
|
3
|
+
/**
|
|
4
|
+
* @internal 出站 ledger:入站 origin 判定的关联层兜底。
|
|
5
|
+
*
|
|
6
|
+
* 只保存 message id 与文本摘要(不存原文),有界内存、短 TTL。
|
|
7
|
+
* 写入发生在 `deliver` 成功之后的旁路,失败不影响 receipt。
|
|
8
|
+
*/
|
|
9
|
+
const MAX_ENTRIES = 2000;
|
|
10
|
+
const TTL_MS = 10 * 60_000;
|
|
11
|
+
const DIGEST_WINDOW_MS = 30_000;
|
|
12
|
+
const MIN_DIGEST_TEXT = 4;
|
|
13
|
+
/**
|
|
14
|
+
* scope 键不含 endpoint id:同一个群里不同 Bot 的 conversationRefKey 不同,
|
|
15
|
+
* 但它们互相的回显仍属同一会话。
|
|
16
|
+
*/
|
|
17
|
+
export function ledgerScopeOf(conversation) {
|
|
18
|
+
return [
|
|
19
|
+
conversation.endpoint.adapter,
|
|
20
|
+
conversation.kind,
|
|
21
|
+
conversation.id,
|
|
22
|
+
conversation.parent?.kind ?? '',
|
|
23
|
+
conversation.parent?.id ?? '',
|
|
24
|
+
conversation.threadId ?? '',
|
|
25
|
+
].join('\0');
|
|
26
|
+
}
|
|
27
|
+
export function digestText(text) {
|
|
28
|
+
const normalized = text.replace(/\s+/g, ' ').trim();
|
|
29
|
+
if (normalized.length < MIN_DIGEST_TEXT)
|
|
30
|
+
return undefined;
|
|
31
|
+
return createHash('sha256').update(normalized).digest('hex').slice(0, 16);
|
|
32
|
+
}
|
|
33
|
+
function payloadText(payload) {
|
|
34
|
+
if (typeof payload === 'string')
|
|
35
|
+
return payload;
|
|
36
|
+
if (Array.isArray(payload)) {
|
|
37
|
+
return segmentsToPlainText(payload.filter((item) => !!item && typeof item === 'object' && typeof item.type === 'string'));
|
|
38
|
+
}
|
|
39
|
+
return '';
|
|
40
|
+
}
|
|
41
|
+
export class OutboundLedger {
|
|
42
|
+
now;
|
|
43
|
+
#entries = [];
|
|
44
|
+
constructor(now = Date.now) {
|
|
45
|
+
this.now = now;
|
|
46
|
+
}
|
|
47
|
+
get size() {
|
|
48
|
+
return this.#entries.length;
|
|
49
|
+
}
|
|
50
|
+
/** 仅在 `receipt.status === 'sent'` 时记录;`payload` 应为最终投影后的 payload。 */
|
|
51
|
+
record(conversation, receipt, payload) {
|
|
52
|
+
if (receipt.status !== 'sent')
|
|
53
|
+
return;
|
|
54
|
+
const at = this.now();
|
|
55
|
+
this.#prune(at);
|
|
56
|
+
const rawId = receipt.message?.id;
|
|
57
|
+
const messageId = rawId === undefined || rawId === null || String(rawId) === '' ? undefined : String(rawId);
|
|
58
|
+
const digest = digestText(payloadText(payload));
|
|
59
|
+
if (messageId === undefined && digest === undefined)
|
|
60
|
+
return;
|
|
61
|
+
this.#entries.push({
|
|
62
|
+
scope: ledgerScopeOf(conversation),
|
|
63
|
+
endpointId: conversation.endpoint.id,
|
|
64
|
+
...(messageId !== undefined ? { messageId } : {}),
|
|
65
|
+
...(digest !== undefined ? { digest } : {}),
|
|
66
|
+
at,
|
|
67
|
+
digestConsumed: false,
|
|
68
|
+
});
|
|
69
|
+
while (this.#entries.length > MAX_ENTRIES)
|
|
70
|
+
this.#entries.shift();
|
|
71
|
+
}
|
|
72
|
+
matchById(scope, messageId) {
|
|
73
|
+
if (typeof messageId !== 'string' && typeof messageId !== 'number')
|
|
74
|
+
return undefined;
|
|
75
|
+
const id = String(messageId);
|
|
76
|
+
if (id === '')
|
|
77
|
+
return undefined;
|
|
78
|
+
const at = this.now();
|
|
79
|
+
for (let i = this.#entries.length - 1; i >= 0; i--) {
|
|
80
|
+
const entry = this.#entries[i];
|
|
81
|
+
if (at - entry.at > TTL_MS)
|
|
82
|
+
continue;
|
|
83
|
+
if (entry.scope === scope && entry.messageId === id)
|
|
84
|
+
return { endpointId: entry.endpointId };
|
|
85
|
+
}
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* 摘要兜底(“账号 id 对不上”时):30 秒窗口、一次性。
|
|
90
|
+
* 权衡:人类在窗口内原样复读 Bot 刚发的文本,会被当作回显丢弃一次。
|
|
91
|
+
*/
|
|
92
|
+
matchByDigest(scope, text, now = this.now()) {
|
|
93
|
+
const digest = digestText(typeof text === 'string' ? text : '');
|
|
94
|
+
if (digest === undefined)
|
|
95
|
+
return undefined;
|
|
96
|
+
for (let i = this.#entries.length - 1; i >= 0; i--) {
|
|
97
|
+
const entry = this.#entries[i];
|
|
98
|
+
if (now - entry.at > DIGEST_WINDOW_MS)
|
|
99
|
+
continue;
|
|
100
|
+
if (entry.digestConsumed || entry.scope !== scope || entry.digest !== digest)
|
|
101
|
+
continue;
|
|
102
|
+
entry.digestConsumed = true;
|
|
103
|
+
return { endpointId: entry.endpointId };
|
|
104
|
+
}
|
|
105
|
+
return undefined;
|
|
106
|
+
}
|
|
107
|
+
#prune(at) {
|
|
108
|
+
let drop = 0;
|
|
109
|
+
while (drop < this.#entries.length && at - this.#entries[drop].at > TTL_MS)
|
|
110
|
+
drop++;
|
|
111
|
+
if (drop > 0)
|
|
112
|
+
this.#entries.splice(0, drop);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
2
|
+
import { type ConversationRef } from '@zhin.js/im-contract';
|
|
3
|
+
import type { OutboundFallbackReason, RuntimeMessageRendering } from './message-events.js';
|
|
4
|
+
export interface OutboundProjection {
|
|
5
|
+
readonly payload: unknown;
|
|
6
|
+
readonly rendering: RuntimeMessageRendering;
|
|
7
|
+
}
|
|
8
|
+
/** Shared by transport and target-aware previews. Does not send or register callbacks. */
|
|
9
|
+
export declare function projectOutboundPayload(rendered: unknown, conversation: ConversationRef, snapshot: RuntimeSnapshot, options?: {
|
|
10
|
+
readonly rememberFallback?: (map: Record<string, string>) => Record<string, string> | void;
|
|
11
|
+
readonly inheritedFallbacks?: readonly OutboundFallbackReason[];
|
|
12
|
+
/** Keep keyboard payloads until outbound middleware has had a chance to replace them. */
|
|
13
|
+
readonly deferInteractive?: boolean;
|
|
14
|
+
readonly signal?: AbortSignal;
|
|
15
|
+
}): Promise<OutboundProjection>;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { htmlRendererToken } from '@zhin.js/plugin-runtime';
|
|
2
|
+
import { EndpointDeliveryError } from '@zhin.js/im-contract';
|
|
3
|
+
import { flattenOutboundArray } from '../../built/outbound-content-arrays.js';
|
|
4
|
+
import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
|
|
5
|
+
import { applyOutboundInteractivePolicy, applyOutboundMarkdownPolicy, normalizeOutboundPayload, resolveOutboundHtmlPolicy, resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundMediaPolicy, resolveOutboundSupportedSegments, } from './outbound-segments.js';
|
|
6
|
+
/** Shared by transport and target-aware previews. Does not send or register callbacks. */
|
|
7
|
+
export async function projectOutboundPayload(rendered, conversation, snapshot, options = {}) {
|
|
8
|
+
options.signal?.throwIfAborted();
|
|
9
|
+
const adapter = conversation.endpoint.id;
|
|
10
|
+
const reasons = new Set(options.inheritedFallbacks);
|
|
11
|
+
const values = Array.isArray(rendered) ? flattenOutboundArray(rendered) : rendered;
|
|
12
|
+
const contains = (type) => (Array.isArray(values) ? values : [values])
|
|
13
|
+
.some(value => value && typeof value === 'object' && value.type === type);
|
|
14
|
+
const markdown = resolveOutboundMarkdownPolicy(adapter, snapshot);
|
|
15
|
+
if (markdown === 'text' && contains('markdown'))
|
|
16
|
+
reasons.add('markdown_text_policy');
|
|
17
|
+
const host = snapshot.resources.get(snapshot.root)?.get(htmlRendererToken.id);
|
|
18
|
+
let payload = await normalizeOutboundPayload(applyOutboundMarkdownPolicy(values, markdown), host, {
|
|
19
|
+
mediaPolicy: resolveOutboundMediaPolicy(adapter, snapshot),
|
|
20
|
+
htmlPolicy: resolveOutboundHtmlPolicy(adapter, snapshot),
|
|
21
|
+
onFallback: reason => reasons.add(reason),
|
|
22
|
+
signal: options.signal,
|
|
23
|
+
});
|
|
24
|
+
options.signal?.throwIfAborted();
|
|
25
|
+
const interactive = resolveOutboundInteractivePolicy(adapter, snapshot);
|
|
26
|
+
if (interactive === 'text' && Array.isArray(payload) && payload.some(item => item?.type === 'keyboard')) {
|
|
27
|
+
reasons.add('interactive_text_policy');
|
|
28
|
+
}
|
|
29
|
+
if (!options.deferInteractive)
|
|
30
|
+
payload = applyOutboundInteractivePolicy(payload, interactive, options.rememberFallback);
|
|
31
|
+
if (Array.isArray(payload)) {
|
|
32
|
+
payload = payload.filter(item => !(item?.type === 'text' && item.data?.text === ''));
|
|
33
|
+
assertCanonicalSegments(payload);
|
|
34
|
+
}
|
|
35
|
+
const supported = resolveOutboundSupportedSegments(adapter, snapshot);
|
|
36
|
+
const supportedPayload = options.deferInteractive ? applyOutboundInteractivePolicy(payload, interactive) : payload;
|
|
37
|
+
if (supported && Array.isArray(supportedPayload)) {
|
|
38
|
+
const unsupported = supportedPayload.find(segment => segment && typeof segment === 'object'
|
|
39
|
+
&& typeof segment.type === 'string' && !supported.includes(segment.type));
|
|
40
|
+
if (unsupported)
|
|
41
|
+
throw new EndpointDeliveryError('unsupported_operation', `Adapter does not support canonical segment ${unsupported.type}`, 'not_sent');
|
|
42
|
+
}
|
|
43
|
+
const forms = new Set();
|
|
44
|
+
for (const item of Array.isArray(payload) ? payload : [payload]) {
|
|
45
|
+
if (typeof item === 'string' || item?.type === 'text')
|
|
46
|
+
forms.add('text');
|
|
47
|
+
else if (item?.type === 'image')
|
|
48
|
+
forms.add('image');
|
|
49
|
+
else if (item != null)
|
|
50
|
+
forms.add('native');
|
|
51
|
+
}
|
|
52
|
+
return Object.freeze({ payload, rendering: Object.freeze({
|
|
53
|
+
forms: Object.freeze([...forms]), fallbacks: Object.freeze([...reasons]),
|
|
54
|
+
}) });
|
|
55
|
+
}
|
|
@@ -3,6 +3,7 @@ import type { ConversationRef } from '@zhin.js/im-contract';
|
|
|
3
3
|
import { type JSXElement } from '@zhin.js/jsx';
|
|
4
4
|
import { type MessageRenderOptions } from '../../jsx/message-renderer.js';
|
|
5
5
|
import { type IncomingContext, type SendContent } from './contracts.js';
|
|
6
|
+
import { type OutboundProjection } from './outbound-projection.js';
|
|
6
7
|
export interface OutboundRenderOptions {
|
|
7
8
|
readonly jsxCache?: WeakMap<JSXElement, Promise<unknown>>;
|
|
8
9
|
readonly bindButton?: MessageRenderOptions['bindButton'];
|
|
@@ -10,5 +11,7 @@ export interface OutboundRenderOptions {
|
|
|
10
11
|
}
|
|
11
12
|
export declare class OutboundRenderer {
|
|
12
13
|
#private;
|
|
14
|
+
/** Target projection only: no middleware, transport or live button registration. */
|
|
15
|
+
preview(content: SendContent, requester: PluginId, snapshot: RuntimeSnapshot, conversation: ConversationRef, options?: Pick<OutboundRenderOptions, 'signal'>): Promise<OutboundProjection>;
|
|
13
16
|
render(content: SendContent, requester: PluginId, snapshot: RuntimeSnapshot, conversation?: ConversationRef, incoming?: IncomingContext, options?: OutboundRenderOptions): Promise<unknown>;
|
|
14
17
|
}
|
|
@@ -4,9 +4,27 @@ import { isNativeMessageTag, renderToSegments } from '../../jsx/message-renderer
|
|
|
4
4
|
import { flattenOutboundArray, MAX_OUTBOUND_ARRAY_DEPTH } from '../../built/outbound-content-arrays.js';
|
|
5
5
|
import { componentFeatureId, isComponentIndex, } from '@zhin.js/component';
|
|
6
6
|
import { isComponentCall, isRawContent, isSegmentContent, } from './contracts.js';
|
|
7
|
+
import { JsxButtonRegistry } from './jsx-button-registry.js';
|
|
8
|
+
import { requireAdapters } from './endpoint-runtime.js';
|
|
9
|
+
import { projectOutboundPayload } from './outbound-projection.js';
|
|
7
10
|
const maxComponentDepth = 32;
|
|
8
11
|
const TEMPLATE_MARKER = '${';
|
|
9
12
|
export class OutboundRenderer {
|
|
13
|
+
/** Target projection only: no middleware, transport or live button registration. */
|
|
14
|
+
async preview(content, requester, snapshot, conversation, options = {}) {
|
|
15
|
+
const adapters = requireAdapters(snapshot);
|
|
16
|
+
const endpointId = conversation.endpoint.id;
|
|
17
|
+
if (adapters.clientAdapter(endpointId) !== conversation.endpoint.adapter)
|
|
18
|
+
throw new Error('Preview endpoint identity mismatch');
|
|
19
|
+
if (!adapters.list().find(item => item.id === endpointId)?.capabilities.includes('outbound')) {
|
|
20
|
+
throw new Error('Preview endpoint does not support outbound messages');
|
|
21
|
+
}
|
|
22
|
+
const buttons = new JsxButtonRegistry().prepare({ content, requester, conversation }, snapshot);
|
|
23
|
+
const rendered = await this.render(content, requester, snapshot, conversation, undefined, { ...options, bindButton: buttons.bind });
|
|
24
|
+
const result = await projectOutboundPayload(rendered, conversation, snapshot, options);
|
|
25
|
+
options.signal?.throwIfAborted();
|
|
26
|
+
return result;
|
|
27
|
+
}
|
|
10
28
|
async render(content, requester, snapshot, conversation, incoming, options = {}) {
|
|
11
29
|
options.signal?.throwIfAborted();
|
|
12
30
|
const host = resolveComponentHost(snapshot);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { CapabilityId, HtmlRendererHost, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
2
2
|
import { type InteractivePolicy } from '../../built/interactive-segments/types.js';
|
|
3
|
+
import type { OutboundFallbackReason } from './message-events.js';
|
|
3
4
|
/**
|
|
4
5
|
* Outbound payload normalization for the Plugin Runtime IM pipeline.
|
|
5
6
|
*
|
|
@@ -39,10 +40,12 @@ export interface OutboundSegmentsPolicy {
|
|
|
39
40
|
readonly html?: 'direct' | 'image' | 'text';
|
|
40
41
|
}
|
|
41
42
|
export interface NormalizeOutboundOptions {
|
|
43
|
+
readonly signal?: AbortSignal;
|
|
42
44
|
/** 缺省 `url-or-text`(未声明 adapter 的保守兜底:仅 URL 媒体可达)。 */
|
|
43
45
|
readonly mediaPolicy?: OutboundMediaPolicy;
|
|
44
46
|
readonly htmlPolicy?: 'direct' | 'image' | 'text';
|
|
45
47
|
readonly onHtmlFallback?: (reason: 'renderer_unavailable' | 'renderer_failed' | 'media_unsupported') => void;
|
|
48
|
+
readonly onFallback?: (reason: OutboundFallbackReason) => void;
|
|
46
49
|
}
|
|
47
50
|
/** HTML transport is an adapter capability, independent of its package name. */
|
|
48
51
|
export declare function resolveOutboundHtmlPolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): 'direct' | 'image' | 'text';
|