@zhin.js/core 1.1.52 → 1.1.53
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/plugin-runtime/im/conversation-runtime.d.ts +2 -2
- package/lib/plugin-runtime/im/conversation-runtime.js +11 -4
- package/lib/plugin-runtime/im/im-runtime.js +1 -1
- package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +2 -2
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +111 -29
- package/package.json +10 -10
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type ConversationContextBlock, type ConversationEventReader, type ConversationEventStore, type ConversationReference, type ConversationResolution, type ConversationRef, type DeliveryReceipt, type MessageRef, type SequencedConversationEvent } from '@zhin.js/im-contract';
|
|
1
|
+
import { type ConversationContextBlock, type ConversationEventReader, type ConversationEventStore, type ConversationReference, type ConversationResolution, type ConversationRef, type DeliveryReceipt, type MessageRef, type SequencedConversationEvent, type Segment } from '@zhin.js/im-contract';
|
|
2
2
|
import type { Notice } from '../../notice.js';
|
|
3
3
|
import type { Request } from '../../request.js';
|
|
4
4
|
import type { IncomingMessage, MessageSenderRef, SendRequest } from './contracts.js';
|
|
@@ -27,7 +27,7 @@ export declare class ConversationRuntime {
|
|
|
27
27
|
markInteractionAnswer(message: MessageRef): void;
|
|
28
28
|
commitContext(conversation: ConversationRef, consumer: string, cursor: number): Promise<void>;
|
|
29
29
|
recordIncoming(input: IncomingMessage, sender: MessageSenderRef | undefined): Promise<number | undefined>;
|
|
30
|
-
recordOutbound(request: SendRequest, receipt: DeliveryReceipt): Promise<void>;
|
|
30
|
+
recordOutbound(request: SendRequest, receipt: DeliveryReceipt, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<void>;
|
|
31
31
|
/** Records a normalized notice; returns the stored event (with its sequence) when newly appended. */
|
|
32
32
|
recordNotice(notice: Notice): Promise<SequencedConversationEvent | undefined>;
|
|
33
33
|
/** Join requests / invitations into a group or channel become `scene.join_requested` (#996). */
|
|
@@ -26,7 +26,7 @@ export class ConversationRuntime {
|
|
|
26
26
|
if (reference.kind !== 'message')
|
|
27
27
|
return undefined;
|
|
28
28
|
const message = await this.#events.getMessage(reference.message);
|
|
29
|
-
return message
|
|
29
|
+
return message && message.contentStatus !== 'unavailable'
|
|
30
30
|
? Object.freeze({ status: 'resolved', reference, value: message })
|
|
31
31
|
: undefined;
|
|
32
32
|
}
|
|
@@ -113,7 +113,7 @@ export class ConversationRuntime {
|
|
|
113
113
|
}));
|
|
114
114
|
return appended.sequence;
|
|
115
115
|
}
|
|
116
|
-
async recordOutbound(request, receipt) {
|
|
116
|
+
async recordOutbound(request, receipt, canonicalContent) {
|
|
117
117
|
if (receipt.status !== 'sent' || !receipt.message?.id)
|
|
118
118
|
return;
|
|
119
119
|
const timestamp = Date.now();
|
|
@@ -124,8 +124,12 @@ export class ConversationRuntime {
|
|
|
124
124
|
type: 'message.created',
|
|
125
125
|
message: Object.freeze({
|
|
126
126
|
ref: receipt.message,
|
|
127
|
-
segments: segmentsFromContent(request.content),
|
|
127
|
+
segments: canonicalContent === 'unavailable' ? [] : canonicalContent ?? segmentsFromContent(request.content),
|
|
128
|
+
...(canonicalContent === 'unavailable' ? { contentStatus: 'unavailable' } : {}),
|
|
128
129
|
timestamp,
|
|
130
|
+
...(canonicalContent !== 'unavailable' && canonicalContent?.length && canonicalContent.every(segment => segment.type === 'text') && receipt.outboundTextDigest ? {
|
|
131
|
+
outboundTextDigest: receipt.outboundTextDigest,
|
|
132
|
+
} : {}),
|
|
129
133
|
}),
|
|
130
134
|
}));
|
|
131
135
|
}
|
|
@@ -308,6 +312,8 @@ function aggregateConversationContext(events, excluded) {
|
|
|
308
312
|
sequence,
|
|
309
313
|
eventType: event.type,
|
|
310
314
|
text,
|
|
315
|
+
message: event.message.ref,
|
|
316
|
+
...(event.message.outboundTextDigest ? { messageTextDigest: event.message.outboundTextDigest } : {}),
|
|
311
317
|
}));
|
|
312
318
|
continue;
|
|
313
319
|
}
|
|
@@ -388,7 +394,8 @@ function describeConversationMessage(message) {
|
|
|
388
394
|
const attachmentNote = attachmentTypes.length > 0
|
|
389
395
|
? ` [message also contains ${attachmentTypes.join(', ')} data; inspect its reference before relying on that content]`
|
|
390
396
|
: '';
|
|
391
|
-
return `${actor} [message_id=${JSON.stringify(message.ref.id)}]: ${
|
|
397
|
+
return `${actor} [message_id=${JSON.stringify(message.ref.id)}]: ${message.contentStatus === 'unavailable'
|
|
398
|
+
? '[Message content unavailable; inspect its reference.]' : text || '(no plain-text content)'}${attachmentNote}`;
|
|
392
399
|
}
|
|
393
400
|
function segmentsFromContent(content) {
|
|
394
401
|
if (Array.isArray(content)) {
|
|
@@ -55,7 +55,7 @@ export class ImRuntime {
|
|
|
55
55
|
this.#outbound = new OutboundDeliveryRuntime({
|
|
56
56
|
diagnostics: this.#messageDiagnostics,
|
|
57
57
|
ledger: (conversation, receipt, payload) => ledger.record(conversation, receipt, payload),
|
|
58
|
-
record: (request, receipt) => this.#conversations.recordOutbound(request, receipt),
|
|
58
|
+
record: (request, receipt, canonicalContent) => this.#conversations.recordOutbound(request, receipt, canonicalContent),
|
|
59
59
|
rememberFallback: (conversation, generation, map) => this.#interactions.rememberFallback(conversation, generation, map),
|
|
60
60
|
publish: (event) => this.#messageEventStream.publish(event),
|
|
61
61
|
prepareButtons: (request, snapshot) => this.#interactions.prepareButtons(request, snapshot),
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
2
|
-
import { type ConversationRef, type DeliveryReceipt } from '@zhin.js/im-contract';
|
|
2
|
+
import { type ConversationRef, type DeliveryReceipt, type Segment } 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';
|
|
@@ -8,7 +8,7 @@ import type { RuntimeMessageDiagnostics } from './message-diagnostics.js';
|
|
|
8
8
|
interface OutboundDeliveryContext {
|
|
9
9
|
readonly diagnostics?: RuntimeMessageDiagnostics;
|
|
10
10
|
prepareButtons?(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
|
|
11
|
-
record(request: SendRequest, receipt: DeliveryReceipt): Promise<void>;
|
|
11
|
+
record(request: SendRequest, receipt: DeliveryReceipt, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<void>;
|
|
12
12
|
/** Side-channel correlation ledger for inbound origin; failures never affect the receipt. */
|
|
13
13
|
ledger?(conversation: ConversationRef, receipt: DeliveryReceipt, payload: unknown): void;
|
|
14
14
|
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>): Record<string, string> | void;
|
|
@@ -1,6 +1,10 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
1
2
|
import { resolveLocale } from '@zhin.js/plugin-runtime';
|
|
2
3
|
import { projectLocale } from './locale.js';
|
|
3
4
|
import { EndpointDeliveryError } from '@zhin.js/im-contract';
|
|
5
|
+
import { isCanonicalSegment } from '../../built/segment-contract/assert.js';
|
|
6
|
+
import { collectSegmentMedia } from '../../built/segment-contract/media.js';
|
|
7
|
+
import { isStrictCanonicalSegment } from '../../built/segment-contract/validate.js';
|
|
4
8
|
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
5
9
|
import { isJsxElement } from '@zhin.js/jsx';
|
|
6
10
|
import { createOutboundEnvelope, isComponentCall, isRawContent } from './contracts.js';
|
|
@@ -117,36 +121,51 @@ export class OutboundDeliveryRuntime {
|
|
|
117
121
|
return;
|
|
118
122
|
}
|
|
119
123
|
const revokeButtons = buttons?.activate(buttonPayloads);
|
|
124
|
+
const canonicalContent = typeof payload === 'string'
|
|
125
|
+
? [{ type: 'text', data: { text: payload } }]
|
|
126
|
+
: Array.isArray(payload) && payload.every(isCanonicalSegment) ? payload : undefined;
|
|
127
|
+
// Capture known canonical content before the endpoint can mutate it.
|
|
128
|
+
// Inline rendering bytes and opaque extensions never become new history.
|
|
129
|
+
const contentSources = canonicalContent?.map(snapshotHistorySource);
|
|
130
|
+
const payloadLength = Array.isArray(payload) ? payload.length : 1;
|
|
120
131
|
try {
|
|
121
132
|
const result = await requireAdapters(snapshot).send(adapter, {
|
|
122
133
|
conversation: request.conversation,
|
|
123
134
|
locale: resolveLocale(request.locale ?? projectLocale(snapshot)),
|
|
124
135
|
payload,
|
|
125
136
|
});
|
|
126
|
-
receipt = receiptFromEndpointResult(result, request.conversation);
|
|
137
|
+
receipt = receiptFromEndpointResult(result, request.conversation, payloadLength);
|
|
127
138
|
}
|
|
128
139
|
catch (error) {
|
|
129
|
-
receipt = receiptFromEndpointError(error);
|
|
140
|
+
receipt = receiptFromEndpointError(error, true, request.conversation, payloadLength);
|
|
130
141
|
}
|
|
131
|
-
|
|
142
|
+
const evidence = projectPartEvidence(receipt, contentSources);
|
|
143
|
+
receipt = evidence.receipt;
|
|
144
|
+
if (receipt.status !== 'sent' && !receipt.failure?.deliveryUnknown && !receipt.parts?.length)
|
|
132
145
|
revokeButtons?.();
|
|
133
|
-
|
|
134
|
-
|
|
146
|
+
for (const part of evidence.parts) {
|
|
147
|
+
const partReceipt = { status: 'sent', ...(part.part.message ? { message: part.part.message } : {}),
|
|
148
|
+
...(part.part.outboundTextDigest ? { outboundTextDigest: part.part.outboundTextDigest } : {}) };
|
|
149
|
+
if (part.part.message) {
|
|
150
|
+
await this.context.record(request, partReceipt, part.content ?? (receipt.parts ? 'unavailable' : undefined));
|
|
151
|
+
}
|
|
135
152
|
try {
|
|
136
|
-
this.context.ledger?.(request.conversation,
|
|
153
|
+
this.context.ledger?.(request.conversation, partReceipt, part.content ?? (receipt.parts ? undefined : payload));
|
|
137
154
|
}
|
|
138
155
|
catch (error) {
|
|
139
156
|
logger.warn(`outbound ledger write failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
140
157
|
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
158
|
+
if (part.part.message)
|
|
159
|
+
this.context.publish({
|
|
160
|
+
direction: 'outbound',
|
|
161
|
+
rendering: projection.rendering,
|
|
162
|
+
conversation: request.conversation,
|
|
163
|
+
requester: request.requester,
|
|
164
|
+
contentPreview: part.content ? previewMessageContent(part.content)
|
|
165
|
+
: receipt.parts ? '[Message content unavailable; inspect its reference.]' : previewMessageContent(payload),
|
|
166
|
+
messageId: part.part.message.id,
|
|
167
|
+
timestamp: Date.now(),
|
|
168
|
+
});
|
|
150
169
|
}
|
|
151
170
|
}, 'outbound');
|
|
152
171
|
}
|
|
@@ -190,29 +209,44 @@ export function failedDeliveryReceipt(code, retryable = false) {
|
|
|
190
209
|
}),
|
|
191
210
|
});
|
|
192
211
|
}
|
|
193
|
-
function receiptFromEndpointResult(
|
|
194
|
-
if (typeof
|
|
212
|
+
function receiptFromEndpointResult(result, conversation, payloadLength) {
|
|
213
|
+
if (typeof result !== 'string') {
|
|
214
|
+
const parts = normalizeEndpointParts(result?.parts, conversation, payloadLength);
|
|
215
|
+
if (!parts.length)
|
|
216
|
+
return unknownDeliveryReceipt('delivery_unconfirmed');
|
|
217
|
+
const message = parts.find(part => part.message)?.message;
|
|
218
|
+
if (!message)
|
|
219
|
+
return Object.freeze({ ...unknownDeliveryReceipt('delivery_unconfirmed'), parts });
|
|
220
|
+
return Object.freeze({ status: 'sent', ...(message ? { message } : {}), parts });
|
|
221
|
+
}
|
|
222
|
+
if (result.trim() === '') {
|
|
195
223
|
return unknownDeliveryReceipt('delivery_unconfirmed');
|
|
196
224
|
}
|
|
197
225
|
return Object.freeze({
|
|
198
226
|
status: 'sent',
|
|
199
|
-
message: Object.freeze({ conversation, id:
|
|
227
|
+
message: Object.freeze({ conversation, id: result }),
|
|
200
228
|
});
|
|
201
229
|
}
|
|
202
|
-
function receiptFromEndpointError(error, attempted = true) {
|
|
230
|
+
function receiptFromEndpointError(error, attempted = true, conversation, payloadLength) {
|
|
203
231
|
if (error instanceof EndpointDeliveryError) {
|
|
232
|
+
const parts = attempted && conversation ? normalizeEndpointParts(error.parts, conversation, payloadLength) : [];
|
|
204
233
|
// Disposition is transport evidence; an error code alone cannot override it.
|
|
234
|
+
let receipt;
|
|
205
235
|
if (error.disposition === 'unknown')
|
|
206
|
-
|
|
207
|
-
if (error.disposition === 'rejected')
|
|
208
|
-
|
|
209
|
-
if (error.code === 'outbound_unsupported' || error.code === 'endpoint_not_found')
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
236
|
+
receipt = unknownDeliveryReceipt(error.code);
|
|
237
|
+
else if (error.disposition === 'rejected')
|
|
238
|
+
receipt = rejectedDeliveryReceipt(error.code, 'Endpoint rejected outbound delivery.');
|
|
239
|
+
else if (error.code === 'outbound_unsupported' || error.code === 'endpoint_not_found')
|
|
240
|
+
receipt = unsupportedDeliveryReceipt('outbound_unsupported');
|
|
241
|
+
else if (error.code === 'unsupported_operation')
|
|
242
|
+
receipt = unsupportedDeliveryReceipt(error.code);
|
|
243
|
+
else
|
|
244
|
+
receipt = failedDeliveryReceipt(error.code);
|
|
245
|
+
if (!parts.length)
|
|
246
|
+
return receipt;
|
|
247
|
+
const message = parts.find(part => part.message)?.message;
|
|
248
|
+
return Object.freeze({ ...receipt, ...(message ? { message } : {}), parts,
|
|
249
|
+
failure: Object.freeze({ ...receipt.failure, retryable: false }) });
|
|
216
250
|
}
|
|
217
251
|
// imhelper ProtocolError exposes stable protocol facts without a Core SDK dependency.
|
|
218
252
|
if (error && typeof error === 'object' && 'protocol' in error && 'kind' in error && 'response' in error
|
|
@@ -228,6 +262,54 @@ function receiptFromEndpointError(error, attempted = true) {
|
|
|
228
262
|
// Unknown SDK/network failures provide no evidence that replay is safe.
|
|
229
263
|
return unknownDeliveryReceipt('endpoint_send_failed');
|
|
230
264
|
}
|
|
265
|
+
/** Unknown identities stay as slots; a bad mapping cannot erase a real platform id. */
|
|
266
|
+
function normalizeEndpointParts(parts, conversation, payloadLength) {
|
|
267
|
+
if (!Array.isArray(parts))
|
|
268
|
+
return [];
|
|
269
|
+
return Object.freeze(Array.from(parts, part => {
|
|
270
|
+
const indices = Array.isArray(part?.sourceIndices) ? [...part.sourceIndices] : undefined;
|
|
271
|
+
return Object.freeze({
|
|
272
|
+
...(typeof part?.messageId === 'string' && part.messageId.trim() !== ''
|
|
273
|
+
? { message: Object.freeze({ conversation, id: part.messageId }) } : {}),
|
|
274
|
+
...(indices && payloadLength !== undefined
|
|
275
|
+
&& indices.every((index) => typeof index === 'number' && Number.isSafeInteger(index) && index >= 0 && index < payloadLength)
|
|
276
|
+
? { sourceIndices: Object.freeze(indices) } : {}),
|
|
277
|
+
});
|
|
278
|
+
}));
|
|
279
|
+
}
|
|
280
|
+
function snapshotHistorySource(segment) {
|
|
281
|
+
// Forward entries and opaque card/extensions have no bounded, simple content contract here.
|
|
282
|
+
if (!isStrictCanonicalSegment(segment) || segment.type === 'forward')
|
|
283
|
+
return undefined;
|
|
284
|
+
if (collectSegmentMedia([segment]).some(({ media }) => media.kind === 'base64' || media.value.startsWith('data:')))
|
|
285
|
+
return undefined;
|
|
286
|
+
const values = [...Object.values(segment.data), ...Object.values(segment.platform ?? {})];
|
|
287
|
+
if (values.some(value => ArrayBuffer.isView(value) || value instanceof ArrayBuffer))
|
|
288
|
+
return undefined;
|
|
289
|
+
try {
|
|
290
|
+
return structuredClone(segment);
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
return undefined;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
function projectPartEvidence(receipt, sources) {
|
|
297
|
+
const parts = receipt.parts ?? (receipt.status === 'sent' ? [{ message: receipt.message,
|
|
298
|
+
...(sources ? { sourceIndices: sources.map((_, index) => index) } : {}) }] : []);
|
|
299
|
+
const projected = parts.map(part => {
|
|
300
|
+
const selected = part.sourceIndices?.length && sources ? part.sourceIndices.map(index => sources[index]) : undefined;
|
|
301
|
+
const content = selected?.every((segment) => segment !== undefined) ? selected : undefined;
|
|
302
|
+
const outboundTextDigest = content?.every((segment) => segment.type === 'text')
|
|
303
|
+
? createHash('sha256').update(content.map(segment => segment.data.text).join('')).digest('hex') : undefined;
|
|
304
|
+
return { part: Object.freeze({ ...part, ...(outboundTextDigest ? { outboundTextDigest } : {}) }), ...(content ? { content } : {}) };
|
|
305
|
+
});
|
|
306
|
+
return {
|
|
307
|
+
receipt: { ...receipt, ...(receipt.parts ? { parts: Object.freeze(projected.map(part => part.part)) } : {}),
|
|
308
|
+
...(receipt.status === 'sent' && projected.length === 1 && projected[0]?.part.outboundTextDigest
|
|
309
|
+
? { outboundTextDigest: projected[0].part.outboundTextDigest } : {}) },
|
|
310
|
+
parts: projected,
|
|
311
|
+
};
|
|
312
|
+
}
|
|
231
313
|
function unknownDeliveryReceipt(code) {
|
|
232
314
|
return Object.freeze({
|
|
233
315
|
status: 'failed',
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zhin.js/core",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.53",
|
|
4
4
|
"description": "Zhin机器人核心框架",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./lib/index.js",
|
|
@@ -57,29 +57,29 @@
|
|
|
57
57
|
"dependencies": {
|
|
58
58
|
"qrcode": "^1.5.4",
|
|
59
59
|
"segment-matcher": "^1.0.5",
|
|
60
|
-
"@zhin.js/
|
|
61
|
-
"@zhin.js/adapter": "1.1.24",
|
|
62
|
-
"@zhin.js/component": "1.1.10",
|
|
60
|
+
"@zhin.js/adapter": "1.1.25",
|
|
63
61
|
"@zhin.js/database": "1.1.5",
|
|
64
62
|
"@zhin.js/handler": "1.1.9",
|
|
65
|
-
"@zhin.js/
|
|
63
|
+
"@zhin.js/component": "1.1.10",
|
|
64
|
+
"@zhin.js/command": "1.1.11",
|
|
66
65
|
"@zhin.js/interaction": "1.1.2",
|
|
66
|
+
"@zhin.js/im-contract": "1.1.9",
|
|
67
67
|
"@zhin.js/kernel": "1.1.5",
|
|
68
|
-
"@zhin.js/middleware": "1.1.10",
|
|
69
68
|
"@zhin.js/logger": "1.1.2",
|
|
70
69
|
"@zhin.js/plugin-runtime": "1.1.17",
|
|
71
|
-
"@zhin.js/
|
|
72
|
-
"@zhin.js/
|
|
70
|
+
"@zhin.js/middleware": "1.1.10",
|
|
71
|
+
"@zhin.js/permission": "1.1.9",
|
|
73
72
|
"@zhin.js/schema": "1.1.4",
|
|
73
|
+
"@zhin.js/jsx": "1.1.8",
|
|
74
74
|
"@zhin.js/feature-kit": "1.1.9",
|
|
75
|
-
"@zhin.js/
|
|
75
|
+
"@zhin.js/schedule-feature": "1.1.9"
|
|
76
76
|
},
|
|
77
77
|
"devDependencies": {
|
|
78
78
|
"@types/node": "^26.1.2",
|
|
79
79
|
"@types/qrcode": "^1.5.6",
|
|
80
80
|
"ajv": "8.18.0",
|
|
81
81
|
"typescript": "^6.0.3",
|
|
82
|
-
"@zhin.js/ai": "1.1.
|
|
82
|
+
"@zhin.js/ai": "1.1.48"
|
|
83
83
|
},
|
|
84
84
|
"repository": {
|
|
85
85
|
"type": "git",
|