@zhin.js/core 1.1.41 → 1.1.43
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/interactive-segments/action.js +1 -1
- package/lib/built/roles.d.ts +6 -1
- package/lib/built/roles.js +11 -20
- package/lib/built/segment-contract/assert.js +1 -1
- package/lib/built/segment-contract/json-schema.js +1 -1
- 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/jsx/intrinsic-elements.d.ts +83 -0
- package/lib/jsx/intrinsic-elements.js +1 -0
- package/lib/jsx/message-renderer.d.ts +13 -0
- package/lib/jsx/message-renderer.js +128 -0
- package/lib/jsx/message-tags.d.ts +126 -0
- package/lib/jsx/message-tags.js +47 -0
- package/lib/jsx-dev-runtime.d.ts +2 -1
- package/lib/jsx-dev-runtime.js +1 -1
- package/lib/jsx-runtime.d.ts +2 -1
- package/lib/jsx-runtime.js +1 -1
- package/lib/jsx.d.ts +5 -0
- package/lib/jsx.js +2 -0
- 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 +19 -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 +238 -14
- 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 +17 -3
- package/lib/plugin-runtime/im/interaction-runtime.js +31 -3
- package/lib/plugin-runtime/im/interactive-router.d.ts +19 -2
- package/lib/plugin-runtime/im/interactive-router.js +80 -23
- package/lib/plugin-runtime/im/jsx-button-registry.d.ts +17 -0
- package/lib/plugin-runtime/im/jsx-button-registry.js +97 -0
- 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 +5 -1
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +49 -44
- 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 +6 -1
- package/lib/plugin-runtime/im/outbound-renderer.js +51 -12
- package/lib/plugin-runtime/im/outbound-segments.d.ts +4 -1
- package/lib/plugin-runtime/im/outbound-segments.js +37 -7
- package/package.json +16 -16
|
@@ -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,8 @@ export class RuntimeInteractiveRouter {
|
|
|
16
13
|
fallbackTtlMs;
|
|
17
14
|
#handlers = [];
|
|
18
15
|
#fallbacks = new Map();
|
|
16
|
+
#expired = [];
|
|
17
|
+
#nextNumber = 1;
|
|
19
18
|
constructor(fallbackTtlMs = DEFAULT_FALLBACK_TTL_MS) {
|
|
20
19
|
this.fallbackTtlMs = fallbackTtlMs;
|
|
21
20
|
}
|
|
@@ -35,13 +34,40 @@ export class RuntimeInteractiveRouter {
|
|
|
35
34
|
};
|
|
36
35
|
}
|
|
37
36
|
rememberFallback(conversation, generation, map, ttlMs = this.fallbackTtlMs) {
|
|
38
|
-
if (Object.keys(map).length === 0)
|
|
39
|
-
return;
|
|
40
37
|
this.#pruneFallbacks();
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
38
|
+
const key = interactiveConversationKey(conversation, generation);
|
|
39
|
+
const allocated = {};
|
|
40
|
+
for (const [label, payload] of Object.entries(map)) {
|
|
41
|
+
allocated[/^\d+$/.test(label) ? String(this.#nextNumber++) : label] = payload;
|
|
42
|
+
}
|
|
43
|
+
// One runtime counter survives expiry/generation changes without retaining conversation IDs.
|
|
44
|
+
const entries = this.#fallbacks.get(key) ?? [];
|
|
45
|
+
entries.push(Object.freeze({ map: Object.freeze({ ...allocated }), expiresAt: Date.now() + ttlMs }));
|
|
46
|
+
this.#fallbacks.set(key, entries);
|
|
47
|
+
return allocated;
|
|
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;
|
|
45
71
|
}
|
|
46
72
|
resolvePayload(message) {
|
|
47
73
|
const fromSegments = actionPayloadFromSegments(message.segments);
|
|
@@ -52,6 +78,23 @@ export class RuntimeInteractiveRouter {
|
|
|
52
78
|
return undefined;
|
|
53
79
|
return resolvePayloadFromText(raw, this.#fallbackMap(message.conversation, message.generation));
|
|
54
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
|
+
}
|
|
55
98
|
async dispatch(message, admission) {
|
|
56
99
|
const payload = this.resolvePayload(message);
|
|
57
100
|
if (!payload)
|
|
@@ -69,24 +112,38 @@ export class RuntimeInteractiveRouter {
|
|
|
69
112
|
}
|
|
70
113
|
#fallbackMap(conversation, generation) {
|
|
71
114
|
const key = interactiveConversationKey(conversation, generation);
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
if (entry.expiresAt < Date.now()) {
|
|
76
|
-
this.#fallbacks.delete(key);
|
|
77
|
-
return undefined;
|
|
78
|
-
}
|
|
79
|
-
return entry.map;
|
|
115
|
+
this.#pruneFallbacks();
|
|
116
|
+
const entries = this.#fallbacks.get(key);
|
|
117
|
+
return entries ? Object.assign({}, ...entries.map(entry => entry.map)) : undefined;
|
|
80
118
|
}
|
|
81
119
|
#pruneFallbacks() {
|
|
82
120
|
const now = Date.now();
|
|
83
|
-
for (const [key,
|
|
84
|
-
|
|
121
|
+
for (const [key, entries] of this.#fallbacks) {
|
|
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
|
+
}
|
|
132
|
+
if (active.length)
|
|
133
|
+
this.#fallbacks.set(key, active);
|
|
134
|
+
else
|
|
85
135
|
this.#fallbacks.delete(key);
|
|
86
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);
|
|
87
143
|
}
|
|
88
144
|
}
|
|
89
|
-
|
|
145
|
+
/** @internal Payload of the first action segment (platform callback) that carries a non-empty string. */
|
|
146
|
+
export function actionPayloadFromSegments(segments) {
|
|
90
147
|
for (const segment of segments ?? []) {
|
|
91
148
|
if (segment.type !== 'action')
|
|
92
149
|
continue;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type Segment } from '@zhin.js/im-contract';
|
|
2
|
+
import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
3
|
+
import type { ButtonProps } from '../../jsx/message-tags.js';
|
|
4
|
+
import type { Message, SendRequest } from './contracts.js';
|
|
5
|
+
export declare function isJsxButtonPayload(payload: string | undefined): boolean;
|
|
6
|
+
export interface JsxButtonBatch {
|
|
7
|
+
bind(props: ButtonProps): Segment;
|
|
8
|
+
/** Publish callbacks immediately before transport; revoke them on definitive non-delivery. */
|
|
9
|
+
activate(payloads: ReadonlySet<string>): () => void;
|
|
10
|
+
}
|
|
11
|
+
/** Snapshot-owned callbacks: retired generations are unreachable and can be collected. */
|
|
12
|
+
export declare class JsxButtonRegistry {
|
|
13
|
+
#private;
|
|
14
|
+
prepare(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
|
|
15
|
+
dispatch(message: Message, payload: string, snapshot: RuntimeSnapshot): Promise<boolean>;
|
|
16
|
+
}
|
|
17
|
+
export declare function collectButtonPayloads(payload: unknown): Set<string>;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { jsx } from '@zhin.js/jsx';
|
|
3
|
+
import { conversationRefKey } from '@zhin.js/im-contract';
|
|
4
|
+
import { bindOperationInput } from '@zhin.js/feature-kit';
|
|
5
|
+
import { isKeyboardSegment } from '../../built/interactive-segments/types.js';
|
|
6
|
+
const PREFIX = 'zhin:jsx:';
|
|
7
|
+
const BUTTON_TTL_MS = 60 * 60 * 1000;
|
|
8
|
+
export function isJsxButtonPayload(payload) {
|
|
9
|
+
return payload?.startsWith(PREFIX) === true;
|
|
10
|
+
}
|
|
11
|
+
/** Snapshot-owned callbacks: retired generations are unreachable and can be collected. */
|
|
12
|
+
export class JsxButtonRegistry {
|
|
13
|
+
#bindings = new WeakMap();
|
|
14
|
+
prepare(request, snapshot) {
|
|
15
|
+
const pending = new Map();
|
|
16
|
+
return {
|
|
17
|
+
bind: (props) => {
|
|
18
|
+
const { onClick, payload: manualPayload, children, label, id, ...options } = props;
|
|
19
|
+
if (onClick !== undefined && typeof onClick !== 'function')
|
|
20
|
+
throw new TypeError('Button onClick must be a function');
|
|
21
|
+
if (onClick && manualPayload !== undefined)
|
|
22
|
+
throw new TypeError('Button accepts onClick or payload, not both');
|
|
23
|
+
if (!onClick && typeof manualPayload !== 'string')
|
|
24
|
+
throw new TypeError('Button requires onClick or payload');
|
|
25
|
+
const payload = onClick ? `${PREFIX}${randomUUID()}` : manualPayload;
|
|
26
|
+
if (onClick && !props.disabled)
|
|
27
|
+
pending.set(payload, {
|
|
28
|
+
onClick, requester: request.requester, conversationKey: conversationRefKey(request.conversation),
|
|
29
|
+
expiresAt: 0,
|
|
30
|
+
});
|
|
31
|
+
return { type: 'keyboard', data: { rows: [[{
|
|
32
|
+
...options,
|
|
33
|
+
id: id ?? randomUUID(),
|
|
34
|
+
label: label ?? children,
|
|
35
|
+
payload,
|
|
36
|
+
...(onClick ? { mode: 'callback' } : {}),
|
|
37
|
+
}]] } };
|
|
38
|
+
},
|
|
39
|
+
activate: (payloads) => {
|
|
40
|
+
let active = this.#bindings.get(snapshot);
|
|
41
|
+
const activated = [];
|
|
42
|
+
if (active)
|
|
43
|
+
this.#prune(active);
|
|
44
|
+
for (const [payload, binding] of pending) {
|
|
45
|
+
if (!payloads.has(payload))
|
|
46
|
+
continue;
|
|
47
|
+
if (!active)
|
|
48
|
+
this.#bindings.set(snapshot, active = new Map());
|
|
49
|
+
active.set(payload, { ...binding, expiresAt: Date.now() + BUTTON_TTL_MS });
|
|
50
|
+
activated.push(payload);
|
|
51
|
+
}
|
|
52
|
+
pending.clear();
|
|
53
|
+
return () => { for (const payload of activated)
|
|
54
|
+
active?.delete(payload); };
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
async dispatch(message, payload, snapshot) {
|
|
59
|
+
if (!isJsxButtonPayload(payload))
|
|
60
|
+
return false;
|
|
61
|
+
const active = this.#bindings.get(snapshot);
|
|
62
|
+
if (active)
|
|
63
|
+
this.#prune(active);
|
|
64
|
+
const binding = active?.get(payload);
|
|
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))
|
|
71
|
+
return true;
|
|
72
|
+
const bound = bindOperationInput(message, binding.requester, snapshot);
|
|
73
|
+
const content = await binding.onClick(bound);
|
|
74
|
+
if (typeof content === 'number')
|
|
75
|
+
await bound.$reply(jsx('text', { text: String(content) }));
|
|
76
|
+
else if (content != null && typeof content !== 'boolean')
|
|
77
|
+
await bound.$reply(content);
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
#prune(bindings) {
|
|
81
|
+
const now = Date.now();
|
|
82
|
+
for (const [payload, binding] of bindings)
|
|
83
|
+
if (binding.expiresAt <= now)
|
|
84
|
+
bindings.delete(payload);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
export function collectButtonPayloads(payload) {
|
|
88
|
+
const result = new Set();
|
|
89
|
+
for (const item of Array.isArray(payload) ? payload : [payload]) {
|
|
90
|
+
if (isKeyboardSegment(item)) {
|
|
91
|
+
for (const row of item.data.rows)
|
|
92
|
+
for (const button of row)
|
|
93
|
+
result.add(button.payload);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return result;
|
|
97
|
+
}
|
|
@@ -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;
|
|
@@ -3,9 +3,13 @@ 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';
|
|
6
|
+
import { type JsxButtonBatch } from './jsx-button-registry.js';
|
|
6
7
|
interface OutboundDeliveryContext {
|
|
8
|
+
prepareButtons?(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
|
|
7
9
|
record(request: SendRequest, receipt: DeliveryReceipt): Promise<void>;
|
|
8
|
-
|
|
10
|
+
/** Side-channel correlation ledger for inbound origin; failures never affect the receipt. */
|
|
11
|
+
ledger?(conversation: ConversationRef, receipt: DeliveryReceipt, payload: unknown): void;
|
|
12
|
+
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>): Record<string, string> | void;
|
|
9
13
|
publish(event: RuntimeMessageEvent): void;
|
|
10
14
|
}
|
|
11
15
|
/** Owns rendering, policy projection, middleware, Endpoint delivery, and delivery facts. */
|
|
@@ -1,15 +1,14 @@
|
|
|
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';
|
|
12
10
|
import { runRuntimeMiddleware } from './runtime-middleware.js';
|
|
11
|
+
import { collectButtonPayloads } from './jsx-button-registry.js';
|
|
13
12
|
const logger = getLogger('im.outbound');
|
|
14
13
|
/** Owns rendering, policy projection, middleware, Endpoint delivery, and delivery facts. */
|
|
15
14
|
export class OutboundDeliveryRuntime {
|
|
@@ -22,10 +21,14 @@ export class OutboundDeliveryRuntime {
|
|
|
22
21
|
async deliver(request, snapshot) {
|
|
23
22
|
const adapter = request.conversation.endpoint.id;
|
|
24
23
|
const jsxCache = new WeakMap();
|
|
24
|
+
const buttons = this.context.prepareButtons?.(request, snapshot);
|
|
25
|
+
const renderOptions = { jsxCache, bindButton: buttons?.bind };
|
|
25
26
|
let initialPayload;
|
|
27
|
+
let initialProjection;
|
|
26
28
|
try {
|
|
27
|
-
const rendered = await this.#renderer.render(request.content, request.requester, snapshot, request.conversation, request.incoming,
|
|
28
|
-
|
|
29
|
+
const rendered = await this.#renderer.render(request.content, request.requester, snapshot, request.conversation, request.incoming, renderOptions);
|
|
30
|
+
initialProjection = await projectOutboundPayload(rendered, request.conversation, snapshot, { deferInteractive: true });
|
|
31
|
+
initialPayload = initialProjection.payload;
|
|
29
32
|
}
|
|
30
33
|
catch (error) {
|
|
31
34
|
if (error instanceof EndpointDeliveryError && error.code === 'unsupported_operation' && error.disposition === 'not_sent')
|
|
@@ -45,19 +48,40 @@ export class OutboundDeliveryRuntime {
|
|
|
45
48
|
generation: snapshot.generation,
|
|
46
49
|
clientAdapter: adapters.clientAdapter(adapter),
|
|
47
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))));
|
|
48
60
|
let terminalEntered = false;
|
|
49
61
|
let receipt;
|
|
50
62
|
try {
|
|
51
63
|
await runRuntimeMiddleware(snapshot, envelope, async () => {
|
|
52
64
|
terminalEntered = true;
|
|
53
65
|
let payload;
|
|
66
|
+
let projection;
|
|
67
|
+
const buttonPayloads = new Set();
|
|
54
68
|
try {
|
|
55
69
|
// Native payload replacements remain possible; only authoring values need evaluation.
|
|
56
70
|
const replacement = envelope.payload;
|
|
57
71
|
const replaced = replacement !== initialPayload && needsAuthoringRender(replacement)
|
|
58
|
-
? await this.#renderer.render(replacement, request.requester, snapshot, request.conversation, request.incoming,
|
|
72
|
+
? await this.#renderer.render(replacement, request.requester, snapshot, request.conversation, request.incoming, renderOptions)
|
|
59
73
|
: replacement;
|
|
60
|
-
|
|
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
|
+
},
|
|
81
|
+
});
|
|
82
|
+
payload = projection.payload;
|
|
83
|
+
for (const value of collectButtonPayloads(payload))
|
|
84
|
+
buttonPayloads.add(value);
|
|
61
85
|
}
|
|
62
86
|
catch (error) {
|
|
63
87
|
receipt = error instanceof EndpointDeliveryError && error.code === 'unsupported_operation' && error.disposition === 'not_sent'
|
|
@@ -68,6 +92,7 @@ export class OutboundDeliveryRuntime {
|
|
|
68
92
|
receipt = suppressedDeliveryReceipt();
|
|
69
93
|
return;
|
|
70
94
|
}
|
|
95
|
+
const revokeButtons = buttons?.activate(buttonPayloads);
|
|
71
96
|
try {
|
|
72
97
|
const result = await requireAdapters(snapshot).send(adapter, {
|
|
73
98
|
conversation: request.conversation,
|
|
@@ -78,10 +103,19 @@ export class OutboundDeliveryRuntime {
|
|
|
78
103
|
catch (error) {
|
|
79
104
|
receipt = receiptFromEndpointError(error);
|
|
80
105
|
}
|
|
106
|
+
if (receipt.status !== 'sent' && !receipt.failure?.deliveryUnknown)
|
|
107
|
+
revokeButtons?.();
|
|
81
108
|
if (receipt.status === 'sent') {
|
|
82
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
|
+
}
|
|
83
116
|
this.context.publish({
|
|
84
117
|
direction: 'outbound',
|
|
118
|
+
rendering: projection.rendering,
|
|
85
119
|
conversation: request.conversation,
|
|
86
120
|
requester: request.requester,
|
|
87
121
|
contentPreview: previewMessageContent(payload),
|
|
@@ -131,38 +165,6 @@ export function failedDeliveryReceipt(code, retryable = false) {
|
|
|
131
165
|
}),
|
|
132
166
|
});
|
|
133
167
|
}
|
|
134
|
-
async function prepareOutboundPayload(rendered, conversation, snapshot, rememberInteractiveFallback) {
|
|
135
|
-
const adapter = conversation.endpoint.id;
|
|
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
|
-
});
|
|
142
|
-
if (rememberInteractiveFallback) {
|
|
143
|
-
payload = applyOutboundInteractivePolicy(payload, resolveOutboundInteractivePolicy(adapter, snapshot), rememberInteractiveFallback);
|
|
144
|
-
}
|
|
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 === ''));
|
|
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
|
-
}
|
|
158
|
-
return payload;
|
|
159
|
-
}
|
|
160
|
-
function resolveHtmlRenderer(snapshot) {
|
|
161
|
-
const host = snapshot.resources.get(snapshot.root)?.get(htmlRendererToken.id);
|
|
162
|
-
return host && typeof host.render === 'function'
|
|
163
|
-
? host
|
|
164
|
-
: undefined;
|
|
165
|
-
}
|
|
166
168
|
function receiptFromEndpointResult(messageId, conversation) {
|
|
167
169
|
if (typeof messageId !== 'string' || messageId.trim() === '') {
|
|
168
170
|
return unknownDeliveryReceipt('delivery_unconfirmed');
|
|
@@ -174,14 +176,17 @@ function receiptFromEndpointResult(messageId, conversation) {
|
|
|
174
176
|
}
|
|
175
177
|
function receiptFromEndpointError(error, attempted = true) {
|
|
176
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.');
|
|
177
184
|
if (error.code === 'outbound_unsupported' || error.code === 'endpoint_not_found') {
|
|
178
185
|
return unsupportedDeliveryReceipt('outbound_unsupported');
|
|
179
186
|
}
|
|
180
187
|
if (error.code === 'unsupported_operation' && error.disposition === 'not_sent') {
|
|
181
188
|
return unsupportedDeliveryReceipt(error.code);
|
|
182
189
|
}
|
|
183
|
-
if (error.disposition === 'unknown')
|
|
184
|
-
return unknownDeliveryReceipt(error.code);
|
|
185
190
|
return failedDeliveryReceipt(error.code);
|
|
186
191
|
}
|
|
187
192
|
// imhelper ProtocolError exposes stable protocol facts without a Core SDK dependency.
|
|
@@ -189,7 +194,7 @@ function receiptFromEndpointError(error, attempted = true) {
|
|
|
189
194
|
&& error.protocol === 'onebot-v11' && error.kind === 'protocol') {
|
|
190
195
|
const response = error.response;
|
|
191
196
|
if (response && typeof response === 'object' && 'status' in response && response.status === 'failed') {
|
|
192
|
-
return
|
|
197
|
+
return rejectedDeliveryReceipt('platform_rejected', 'Endpoint rejected outbound delivery.');
|
|
193
198
|
}
|
|
194
199
|
}
|
|
195
200
|
// Before the endpoint send boundary no message can have entered a transport.
|
|
@@ -218,9 +223,9 @@ function unsupportedDeliveryReceipt(code) {
|
|
|
218
223
|
failure: Object.freeze({ code, message: 'Outbound delivery is not supported.' }),
|
|
219
224
|
});
|
|
220
225
|
}
|
|
221
|
-
function rejectedDeliveryReceipt(code) {
|
|
226
|
+
function rejectedDeliveryReceipt(code, message = 'Outbound payload was rejected.') {
|
|
222
227
|
return Object.freeze({
|
|
223
228
|
status: 'rejected',
|
|
224
|
-
failure: Object.freeze({ code, message
|
|
229
|
+
failure: Object.freeze({ code, message }),
|
|
225
230
|
});
|
|
226
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>;
|