@zhin.js/core 1.1.53 → 1.1.55
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -26
- package/lib/built/interaction-messages.d.ts +1 -1
- package/lib/built/login-assist.d.ts +12 -3
- package/lib/built/login-assist.js +32 -26
- package/lib/feature/handler.d.ts +12 -2
- package/lib/feature/handler.js +2 -1
- package/lib/index.d.ts +3 -1
- package/lib/index.js +2 -0
- package/lib/jsx/message-tags.d.ts +3 -3
- package/lib/jsx/message-tags.js +3 -0
- package/lib/plugin-runtime/im/captured-endpoint-operation.d.ts +34 -0
- package/lib/plugin-runtime/im/captured-endpoint-operation.js +1 -0
- package/lib/plugin-runtime/im/command-menu-navigation.d.ts +8 -1
- package/lib/plugin-runtime/im/command-menu-navigation.js +3 -3
- package/lib/plugin-runtime/im/contracts.d.ts +69 -48
- package/lib/plugin-runtime/im/contracts.js +65 -58
- package/lib/plugin-runtime/im/conversation-runtime.d.ts +2 -0
- package/lib/plugin-runtime/im/conversation-runtime.js +41 -4
- package/lib/plugin-runtime/im/endpoint-runtime.d.ts +13 -15
- package/lib/plugin-runtime/im/endpoint-runtime.js +194 -42
- package/lib/plugin-runtime/im/group-rule-violation.d.ts +5 -0
- package/lib/plugin-runtime/im/im-runtime.d.ts +3 -0
- package/lib/plugin-runtime/im/im-runtime.js +33 -7
- package/lib/plugin-runtime/im/inbound-runtime.d.ts +2 -0
- package/lib/plugin-runtime/im/inbound-runtime.js +138 -33
- package/lib/plugin-runtime/im/index.d.ts +2 -1
- package/lib/plugin-runtime/im/interaction-operation.d.ts +5 -1
- package/lib/plugin-runtime/im/interaction-runtime.d.ts +12 -2
- package/lib/plugin-runtime/im/interaction-runtime.js +50 -35
- package/lib/plugin-runtime/im/message-dispatcher.js +2 -2
- package/lib/plugin-runtime/im/operation-endpoint.d.ts +6 -0
- package/lib/plugin-runtime/im/operation-endpoint.js +2 -0
- package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +16 -2
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +86 -20
- package/lib/plugin-runtime/im/outbound-renderer.d.ts +12 -3
- package/lib/plugin-runtime/im/outbound-renderer.js +20 -13
- package/lib/plugin-runtime/im/progressive-reply.d.ts +52 -0
- package/lib/plugin-runtime/im/progressive-reply.js +495 -0
- package/lib/plugin-runtime/im/runtime-middleware.d.ts +2 -0
- package/lib/plugin-runtime/im/runtime-middleware.js +5 -0
- package/package.json +15 -15
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { createEndpointOperation } from '@zhin.js/adapter';
|
|
3
|
+
import { EndpointDeliveryError, isMediaRef } from '@zhin.js/im-contract';
|
|
4
|
+
import { receiptFromEndpointError } from './outbound-delivery-runtime.js';
|
|
5
|
+
/** One producer, one sending pump, and one replaceable candidate rather than a queue per token. */
|
|
6
|
+
export function createCoreReplyStream(context) {
|
|
7
|
+
const cancellation = new AbortController();
|
|
8
|
+
const signal = AbortSignal.any([context.endpoint.signal, cancellation.signal]);
|
|
9
|
+
const groups = new Map();
|
|
10
|
+
const confirmed = new Map();
|
|
11
|
+
const maxBufferedBytes = context.options.maxBufferedBytes ?? 1024 * 1024;
|
|
12
|
+
let receipt = { status: 'suppressed' };
|
|
13
|
+
let failure;
|
|
14
|
+
let pending, pumping, terminal;
|
|
15
|
+
let revision = -1, cancelled = false, finished = false, settled = false, released = false, submitted = false, lastSubmission = 0;
|
|
16
|
+
const parts = () => [...confirmed.values()].map(part => ({ ...(part.message ? { message: part.message } : {}) }));
|
|
17
|
+
const decorate = (value) => ({ ...value, ...(parts().length ? { parts: parts(), message: parts().find(part => part.message)?.message } : {}) });
|
|
18
|
+
const release = () => {
|
|
19
|
+
if (released)
|
|
20
|
+
return;
|
|
21
|
+
released = true;
|
|
22
|
+
context.endpoint.signal.removeEventListener('abort', onAbort);
|
|
23
|
+
context.release();
|
|
24
|
+
};
|
|
25
|
+
const fail = (value) => {
|
|
26
|
+
if (failure)
|
|
27
|
+
return;
|
|
28
|
+
failure = value;
|
|
29
|
+
receipt = decorate(value);
|
|
30
|
+
pending = undefined;
|
|
31
|
+
// Local teardown cannot replace the original delivery evidence or prevent cancellation.
|
|
32
|
+
for (const state of groups.values()) {
|
|
33
|
+
try {
|
|
34
|
+
state.physical?.native.cancel();
|
|
35
|
+
}
|
|
36
|
+
catch { /* No external operation is retried. */ }
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
const remember = (key, part, content) => {
|
|
40
|
+
confirmed.set(key, Object.freeze({ key, segments: content ?? [], ...(part.message ? { message: part.message } : {}) }));
|
|
41
|
+
};
|
|
42
|
+
const prepare = (segments) => context.options.prepare
|
|
43
|
+
? createEndpointOperation({ signal }).prepare(() => context.options.prepare(segments, signal)) : Promise.resolve(segments);
|
|
44
|
+
const wait = async () => {
|
|
45
|
+
if (!lastSubmission)
|
|
46
|
+
return;
|
|
47
|
+
for (;;) {
|
|
48
|
+
const remaining = (context.streaming.minIntervalMs ?? 0) - (Date.now() - lastSubmission);
|
|
49
|
+
if (remaining <= 0)
|
|
50
|
+
return;
|
|
51
|
+
await new Promise((resolve, reject) => {
|
|
52
|
+
// Node clamps larger delays to 1 ms; keep the original deadline across timer chunks.
|
|
53
|
+
const timer = setTimeout(done, Math.min(remaining, 2_147_483_647));
|
|
54
|
+
function done() { signal.removeEventListener('abort', abort); resolve(); }
|
|
55
|
+
function abort() { clearTimeout(timer); signal.removeEventListener('abort', abort); reject(new EndpointDeliveryError('endpoint_inactive', 'Reply stream ended', 'not_sent')); }
|
|
56
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
57
|
+
if (signal.aborted)
|
|
58
|
+
abort();
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
const external = async (call) => {
|
|
63
|
+
await wait();
|
|
64
|
+
signal.throwIfAborted();
|
|
65
|
+
context.endpoint.assertActive();
|
|
66
|
+
context.options.beforeSubmit?.();
|
|
67
|
+
lastSubmission = Date.now();
|
|
68
|
+
submitted = true;
|
|
69
|
+
try {
|
|
70
|
+
return await createEndpointOperation({ signal }).run(call);
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
submitted = false;
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
const finishPhysical = async (physical, text, conversation) => {
|
|
77
|
+
try {
|
|
78
|
+
return { ack: await external(() => physical.native.finish(text)) };
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
let ack;
|
|
82
|
+
try {
|
|
83
|
+
ack = physical.native.lastAcknowledgement;
|
|
84
|
+
}
|
|
85
|
+
catch { /* A local inspection must preserve the original close error. */ }
|
|
86
|
+
if (!ack || ack.status !== 'sent' || typeof ack.messageId !== 'string' || !ack.messageId.trim() || typeof ack.acceptedText !== 'string'
|
|
87
|
+
|| !text.startsWith(ack.acceptedText) || !ack.acceptedText.startsWith(physical.accepted)
|
|
88
|
+
|| physical.message && (ack.messageId !== physical.message.id || ack.acceptedText === physical.accepted))
|
|
89
|
+
throw error;
|
|
90
|
+
// Persist a verified body update through normal delivery, while keeping the close failure terminal.
|
|
91
|
+
return { ack, failure: receiptFromEndpointError(error, true, conversation) };
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
const sendAtomic = async (group, state) => {
|
|
95
|
+
if (!group.complete || state.done)
|
|
96
|
+
return;
|
|
97
|
+
const content = await prepare(group.segments);
|
|
98
|
+
let index = 0;
|
|
99
|
+
const result = await context.deliver(content, {
|
|
100
|
+
send: async (request) => ({ result: await external(() => context.endpoint.send({ ...request, signal })) }),
|
|
101
|
+
history: () => 'create', confirmed: (part, value) => remember(`${group.key}/${index++}`, part, value),
|
|
102
|
+
});
|
|
103
|
+
if (result.status !== 'sent') {
|
|
104
|
+
fail(result);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
state.done = true;
|
|
108
|
+
receipt = decorate(failure ?? { status: 'sent' });
|
|
109
|
+
};
|
|
110
|
+
const sendText = async (group, state) => {
|
|
111
|
+
if (state.done)
|
|
112
|
+
return;
|
|
113
|
+
const prepared = await prepare(group.segments);
|
|
114
|
+
let continueContainer = true;
|
|
115
|
+
while (continueContainer && !cancelled && !failure) {
|
|
116
|
+
continueContainer = false;
|
|
117
|
+
let ack;
|
|
118
|
+
let closeFailure;
|
|
119
|
+
let history = 'skip';
|
|
120
|
+
let physicalKey = `${group.key}/${state.containers}`;
|
|
121
|
+
let confirmedPart = 0;
|
|
122
|
+
let renderedLength = state.consumed;
|
|
123
|
+
const result = await context.deliver(prepared, {
|
|
124
|
+
send: async (request) => {
|
|
125
|
+
const projection = streamText(request.payload);
|
|
126
|
+
if (!projection)
|
|
127
|
+
throw new EndpointDeliveryError('unsupported_stream_payload', 'Incremental middleware produced an incompatible message', 'rejected');
|
|
128
|
+
const full = projection.text;
|
|
129
|
+
renderedLength = full.length;
|
|
130
|
+
if (!full.startsWith(state.accepted))
|
|
131
|
+
throw new EndpointDeliveryError('stream_prefix_changed', 'A published source prefix cannot be rewritten', 'rejected');
|
|
132
|
+
if (!state.physical && state.consumed === full.length && state.consumed > 0) {
|
|
133
|
+
state.done = group.complete;
|
|
134
|
+
ack = { status: 'buffered', acceptedText: '' };
|
|
135
|
+
return {};
|
|
136
|
+
}
|
|
137
|
+
if (state.unsupported) {
|
|
138
|
+
ack = { status: 'buffered', acceptedText: '' };
|
|
139
|
+
if (!group.complete)
|
|
140
|
+
return {};
|
|
141
|
+
history = 'create';
|
|
142
|
+
state.done = true;
|
|
143
|
+
return { result: await external(() => context.endpoint.send({ ...request, signal })) };
|
|
144
|
+
}
|
|
145
|
+
const originOffset = state.consumed;
|
|
146
|
+
const remaining = full.slice(originOffset);
|
|
147
|
+
const prefix = state.consumed ? [] : projection.prefix;
|
|
148
|
+
const prefixKey = JSON.stringify(prefix);
|
|
149
|
+
if (!state.physical) {
|
|
150
|
+
if (!state.consumed) {
|
|
151
|
+
const reply = projection.prefix.find(segment => segment.type === 'reply');
|
|
152
|
+
const data = reply?.data;
|
|
153
|
+
state.replyTo = typeof data?.message_id === 'string' ? data.message_id : undefined;
|
|
154
|
+
}
|
|
155
|
+
const native = context.streaming.open({ conversation: request.conversation, format: projection.format,
|
|
156
|
+
prefix, source: context.options.source, locale: request.locale, signal,
|
|
157
|
+
...(state.consumed ? { continuation: { precedingText: full.slice(0, state.consumed),
|
|
158
|
+
...(state.replyTo ? { replyTo: state.replyTo } : {}) } } : {}),
|
|
159
|
+
});
|
|
160
|
+
if (!native) {
|
|
161
|
+
if (state.consumed)
|
|
162
|
+
throw new EndpointDeliveryError('stream_continuation_unsupported', 'A confirmed reply cannot fall back by replaying its source prefix', 'not_sent');
|
|
163
|
+
state.unsupported = true;
|
|
164
|
+
ack = { status: 'buffered', acceptedText: '' };
|
|
165
|
+
if (!group.complete)
|
|
166
|
+
return {};
|
|
167
|
+
history = 'create';
|
|
168
|
+
state.done = true;
|
|
169
|
+
return { result: await external(() => context.endpoint.send({ ...request, signal })) };
|
|
170
|
+
}
|
|
171
|
+
state.physical = { key: physicalKey, native, format: projection.format, prefixKey, accepted: '', revision: 0, closed: false };
|
|
172
|
+
}
|
|
173
|
+
const physical = state.physical;
|
|
174
|
+
if (physical.format !== projection.format || physical.prefixKey !== prefixKey) {
|
|
175
|
+
throw new EndpointDeliveryError('stream_projection_changed', 'A physical stream cannot change its format or addressing prefix', 'rejected');
|
|
176
|
+
}
|
|
177
|
+
physicalKey = physical.key;
|
|
178
|
+
const close = group.complete;
|
|
179
|
+
const text = remaining;
|
|
180
|
+
if (!close && text === physical.accepted) {
|
|
181
|
+
ack = { status: 'buffered', acceptedText: physical.accepted };
|
|
182
|
+
return {};
|
|
183
|
+
}
|
|
184
|
+
if (close) {
|
|
185
|
+
const completed = await finishPhysical(physical, text, request.conversation);
|
|
186
|
+
ack = completed.ack;
|
|
187
|
+
closeFailure = completed.failure;
|
|
188
|
+
}
|
|
189
|
+
else
|
|
190
|
+
ack = await external(() => physical.native.write(text));
|
|
191
|
+
if (!text.startsWith(ack.acceptedText) || !ack.acceptedText.startsWith(physical.accepted)) {
|
|
192
|
+
throw new EndpointDeliveryError('stream_ack_invalid', 'Endpoint returned an invalid confirmed prefix', 'unknown');
|
|
193
|
+
}
|
|
194
|
+
if (ack.status === 'buffered' && ack.acceptedText !== physical.accepted) {
|
|
195
|
+
throw new EndpointDeliveryError('stream_ack_invalid', 'A buffered update cannot confirm new content', 'unknown');
|
|
196
|
+
}
|
|
197
|
+
if (ack.status === 'sent' && !ack.messageId?.trim())
|
|
198
|
+
throw new EndpointDeliveryError('delivery_unconfirmed', 'Stream returned no confirmed message identity', 'unknown');
|
|
199
|
+
if (ack.status === 'sent' && physical.message && physical.message.id !== ack.messageId) {
|
|
200
|
+
throw new EndpointDeliveryError('stream_identity_changed', 'A physical stream changed its message identity', 'unknown');
|
|
201
|
+
}
|
|
202
|
+
if (close && ack.status !== 'sent')
|
|
203
|
+
throw new EndpointDeliveryError('delivery_unconfirmed', 'Final reply was not confirmed as a saved message', 'unknown');
|
|
204
|
+
physical.accepted = ack.acceptedText;
|
|
205
|
+
state.accepted = full.slice(0, state.consumed) + ack.acceptedText;
|
|
206
|
+
if (ack.status === 'sent') {
|
|
207
|
+
history = physical.message ? { revision: physical.revision + 1 } : 'create';
|
|
208
|
+
physical.revision += 1;
|
|
209
|
+
physical.message = { conversation: request.conversation, id: ack.messageId };
|
|
210
|
+
}
|
|
211
|
+
if (!closeFailure && close && !ack.exhausted && ack.acceptedText === text) {
|
|
212
|
+
physical.closed = true;
|
|
213
|
+
state.consumed += ack.acceptedText.length;
|
|
214
|
+
state.physical = undefined;
|
|
215
|
+
state.containers += 1;
|
|
216
|
+
state.done = group.complete && state.consumed === full.length;
|
|
217
|
+
}
|
|
218
|
+
else if (!closeFailure && ack.exhausted) {
|
|
219
|
+
if (!ack.acceptedText.length)
|
|
220
|
+
throw new EndpointDeliveryError('stream_capacity_exhausted', 'No source progress is possible in this container', 'not_sent');
|
|
221
|
+
if (close) {
|
|
222
|
+
physical.closed = true;
|
|
223
|
+
state.consumed += ack.acceptedText.length;
|
|
224
|
+
state.physical = undefined;
|
|
225
|
+
state.containers += 1;
|
|
226
|
+
state.done = group.complete && state.consumed === full.length;
|
|
227
|
+
}
|
|
228
|
+
continueContainer = !state.done;
|
|
229
|
+
}
|
|
230
|
+
const confirmedContent = [...(originOffset ? [] : projection.prefix),
|
|
231
|
+
projection.format === 'text' ? { type: 'text', data: { text: ack.acceptedText } }
|
|
232
|
+
: { type: 'markdown', data: { content: ack.acceptedText } }];
|
|
233
|
+
return ack.status === 'sent' ? { result: ack.messageId,
|
|
234
|
+
...(ack.contentUnavailable || !ack.confirmedContent && projection.format === 'markdown' && (originOffset > 0 || ack.exhausted)
|
|
235
|
+
? { contentUnavailable: true }
|
|
236
|
+
: { confirmedContent: ack.confirmedContent ?? confirmedContent }),
|
|
237
|
+
} : {};
|
|
238
|
+
},
|
|
239
|
+
history: () => history,
|
|
240
|
+
confirmed: (part, value) => remember(confirmedPart++ ? `${physicalKey}/${confirmedPart}` : physicalKey, part, value),
|
|
241
|
+
});
|
|
242
|
+
if (closeFailure) {
|
|
243
|
+
fail(closeFailure);
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
if (result.status !== 'sent' && (!ack || result.failure)) {
|
|
247
|
+
fail(result);
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if (result.status === 'sent')
|
|
251
|
+
receipt = decorate(failure ?? { status: 'sent' });
|
|
252
|
+
if (ack?.exhausted && state.physical && !state.physical.closed) {
|
|
253
|
+
// Finish this exact accepted prefix before attempting another physical container.
|
|
254
|
+
const physical = state.physical;
|
|
255
|
+
const body = physical.accepted;
|
|
256
|
+
const result = await context.deliver(prepared, {
|
|
257
|
+
send: async (request) => {
|
|
258
|
+
const projection = streamText(request.payload);
|
|
259
|
+
if (!projection)
|
|
260
|
+
throw new EndpointDeliveryError('unsupported_stream_payload', 'Cannot close transformed reply', 'rejected');
|
|
261
|
+
if (!projection.text.startsWith(state.accepted) || projection.format !== physical.format
|
|
262
|
+
|| JSON.stringify(state.consumed ? [] : projection.prefix) !== physical.prefixKey) {
|
|
263
|
+
throw new EndpointDeliveryError('stream_projection_changed', 'Container completion changed previously accepted content or addressing', 'rejected');
|
|
264
|
+
}
|
|
265
|
+
const completed = await finishPhysical(physical, body, request.conversation);
|
|
266
|
+
const end = completed.ack;
|
|
267
|
+
closeFailure = completed.failure;
|
|
268
|
+
if (end.acceptedText !== body || end.status !== 'sent' || !end.messageId)
|
|
269
|
+
throw new EndpointDeliveryError('delivery_unconfirmed', 'Container completion is unconfirmed', 'unknown');
|
|
270
|
+
if (physical.message && end.messageId !== physical.message.id)
|
|
271
|
+
throw new EndpointDeliveryError('stream_identity_changed', 'Container completion changed its message identity', 'unknown');
|
|
272
|
+
return { result: end.messageId,
|
|
273
|
+
...(end.contentUnavailable || !end.confirmedContent && projection.format === 'markdown'
|
|
274
|
+
? { contentUnavailable: true }
|
|
275
|
+
: { confirmedContent: end.confirmedContent ?? [...(state.consumed ? [] : projection.prefix),
|
|
276
|
+
projection.format === 'text' ? { type: 'text', data: { text: body } } : { type: 'markdown', data: { content: body } }] }),
|
|
277
|
+
};
|
|
278
|
+
},
|
|
279
|
+
history: () => physical.message ? { revision: physical.revision + 1 } : 'create',
|
|
280
|
+
confirmed: (part, value) => remember(physical.key, part, value),
|
|
281
|
+
});
|
|
282
|
+
if (closeFailure) {
|
|
283
|
+
fail(closeFailure);
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
if (result.status !== 'sent') {
|
|
287
|
+
fail(result);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
receipt = decorate({ status: 'sent' });
|
|
291
|
+
physical.closed = true;
|
|
292
|
+
state.consumed += body.length;
|
|
293
|
+
state.physical = undefined;
|
|
294
|
+
state.containers += 1;
|
|
295
|
+
state.done = group.complete && state.consumed === renderedLength;
|
|
296
|
+
continueContainer = state.consumed < renderedLength;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
const pump = async () => {
|
|
301
|
+
try {
|
|
302
|
+
while (pending && !cancelled && !failure) {
|
|
303
|
+
await wait();
|
|
304
|
+
if (cancelled)
|
|
305
|
+
break;
|
|
306
|
+
const current = pending;
|
|
307
|
+
pending = undefined;
|
|
308
|
+
const candidates = replyGroups(current);
|
|
309
|
+
// Validate the entire published prefix before a newly inserted group can submit anything.
|
|
310
|
+
for (const state of groups.values()) {
|
|
311
|
+
if (!state.committed)
|
|
312
|
+
continue;
|
|
313
|
+
const { position, source } = state.committed, candidate = candidates[position];
|
|
314
|
+
if (!candidate || candidate.key !== source.key || candidate.format !== source.format
|
|
315
|
+
|| state.done && !isDeepStrictEqual(candidate.segments, source.segments)) {
|
|
316
|
+
throw new EndpointDeliveryError('stream_prefix_changed', 'A published reply group cannot be rewritten, removed or reordered', 'rejected');
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
for (const [position, group] of candidates.entries()) {
|
|
320
|
+
if (cancelled || failure)
|
|
321
|
+
break;
|
|
322
|
+
const state = groups.get(group.key) ?? { consumed: 0, containers: 0, accepted: '' };
|
|
323
|
+
groups.set(group.key, state);
|
|
324
|
+
if (group.format)
|
|
325
|
+
await sendText(group, state);
|
|
326
|
+
else
|
|
327
|
+
await sendAtomic(group, state);
|
|
328
|
+
if (state.done || state.physical)
|
|
329
|
+
state.committed = { position, source: group };
|
|
330
|
+
if (!group.complete)
|
|
331
|
+
break;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
if (!cancelled)
|
|
337
|
+
fail(receiptFromEndpointError(error, submitted));
|
|
338
|
+
}
|
|
339
|
+
finally {
|
|
340
|
+
pumping = undefined;
|
|
341
|
+
if (cancelled || finished || failure)
|
|
342
|
+
release();
|
|
343
|
+
else if (pending)
|
|
344
|
+
start();
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
const start = () => { pumping ??= pump(); };
|
|
348
|
+
const admit = (snapshot) => {
|
|
349
|
+
if (semanticSnapshotBytes(snapshot) > maxBufferedBytes) {
|
|
350
|
+
fail({ status: 'failed', failure: { code: 'stream_buffer_limit', message: 'Reply snapshot exceeds the configured resource limit', retryable: false,
|
|
351
|
+
...(submitted ? { deliveryUnknown: true } : {}) } });
|
|
352
|
+
cancellation.abort();
|
|
353
|
+
if (!pumping)
|
|
354
|
+
release();
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
revision = snapshot.revision;
|
|
358
|
+
pending = snapshot;
|
|
359
|
+
start();
|
|
360
|
+
};
|
|
361
|
+
const update = (snapshot) => {
|
|
362
|
+
if (cancelled || finished || failure || snapshot.revision <= revision)
|
|
363
|
+
return;
|
|
364
|
+
admit(snapshot);
|
|
365
|
+
};
|
|
366
|
+
const cancel = () => {
|
|
367
|
+
if (settled)
|
|
368
|
+
return terminal ?? Promise.resolve(receipt);
|
|
369
|
+
if (!cancelled) {
|
|
370
|
+
cancelled = true;
|
|
371
|
+
pending = undefined;
|
|
372
|
+
fail({ status: 'failed', failure: { code: 'cancelled', message: 'Reply stream cancelled', retryable: false,
|
|
373
|
+
...(submitted ? { deliveryUnknown: true } : {}) } });
|
|
374
|
+
cancellation.abort();
|
|
375
|
+
release();
|
|
376
|
+
}
|
|
377
|
+
return Promise.resolve(receipt);
|
|
378
|
+
};
|
|
379
|
+
const onAbort = () => { void cancel(); };
|
|
380
|
+
context.endpoint.signal.addEventListener('abort', onAbort, { once: true });
|
|
381
|
+
if (context.endpoint.signal.aborted)
|
|
382
|
+
void cancel();
|
|
383
|
+
return Object.freeze({
|
|
384
|
+
minIntervalMs: context.streaming.minIntervalMs,
|
|
385
|
+
get receipt() { return receipt; }, get confirmed() { return Object.freeze([...confirmed.values()]); },
|
|
386
|
+
update,
|
|
387
|
+
finish(snapshot) {
|
|
388
|
+
if (terminal)
|
|
389
|
+
return terminal;
|
|
390
|
+
if (cancelled || failure)
|
|
391
|
+
return Promise.resolve(receipt);
|
|
392
|
+
if (snapshot.messages.some(message => !message.complete || message.segments.some(segment => !segment.complete))) {
|
|
393
|
+
fail({ status: 'failed', failure: { code: 'incomplete_reply', message: 'Final reply contains incomplete content', retryable: false,
|
|
394
|
+
...(submitted ? { deliveryUnknown: true } : {}) } });
|
|
395
|
+
cancellation.abort();
|
|
396
|
+
finished = true;
|
|
397
|
+
settled = true;
|
|
398
|
+
release();
|
|
399
|
+
return Promise.resolve(receipt);
|
|
400
|
+
}
|
|
401
|
+
if (snapshot.revision >= revision)
|
|
402
|
+
admit(snapshot);
|
|
403
|
+
finished = true;
|
|
404
|
+
terminal = (async () => {
|
|
405
|
+
await pumping;
|
|
406
|
+
if (!failure && pending) {
|
|
407
|
+
start();
|
|
408
|
+
await pumping;
|
|
409
|
+
}
|
|
410
|
+
for (const state of groups.values())
|
|
411
|
+
if (!failure && !state.done && state.physical) {
|
|
412
|
+
fail({ status: 'failed', failure: { code: 'incomplete_reply', message: 'Final reply did not close all content', retryable: false } });
|
|
413
|
+
break;
|
|
414
|
+
}
|
|
415
|
+
settled = true;
|
|
416
|
+
release();
|
|
417
|
+
return decorate(receipt);
|
|
418
|
+
})();
|
|
419
|
+
return terminal;
|
|
420
|
+
}, cancel,
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
function semanticSnapshotBytes(snapshot) {
|
|
424
|
+
return Buffer.byteLength(JSON.stringify(snapshot, (key, value) => key === 'media' && isMediaRef(value)
|
|
425
|
+
&& (value.kind === 'base64' || value.value.startsWith('data:')) ? { ...value, value: '[inline media]' } : value));
|
|
426
|
+
}
|
|
427
|
+
function streamText(payload) {
|
|
428
|
+
const segments = typeof payload === 'string' ? [{ type: 'text', data: { text: payload } }]
|
|
429
|
+
: Array.isArray(payload) ? payload : [];
|
|
430
|
+
const prefix = [], text = [];
|
|
431
|
+
let format;
|
|
432
|
+
for (const segment of segments) {
|
|
433
|
+
if (!format && (segment.type === 'reply' || segment.type === 'mention')) {
|
|
434
|
+
prefix.push(segment);
|
|
435
|
+
continue;
|
|
436
|
+
}
|
|
437
|
+
if (segment.type !== 'text' && segment.type !== 'markdown' || format && format !== segment.type)
|
|
438
|
+
return undefined;
|
|
439
|
+
format = segment.type;
|
|
440
|
+
const data = segment.data;
|
|
441
|
+
const value = segment.type === 'text' ? data.text : data.content;
|
|
442
|
+
if (typeof value !== 'string')
|
|
443
|
+
return undefined;
|
|
444
|
+
text.push(value);
|
|
445
|
+
}
|
|
446
|
+
return format ? { format, text: text.join(''), prefix } : undefined;
|
|
447
|
+
}
|
|
448
|
+
function replyGroups(snapshot) {
|
|
449
|
+
const groups = [];
|
|
450
|
+
for (const message of snapshot.messages) {
|
|
451
|
+
// Rendered buttons are canonical keyboards and must remain attached to their logical body.
|
|
452
|
+
if (message.segments.some(segment => segment.value.type === 'keyboard')) {
|
|
453
|
+
const complete = message.complete && message.segments.every(segment => segment.complete);
|
|
454
|
+
groups.push({ key: `${message.key}/interactive`, segments: message.segments.map(segment => segment.value), complete });
|
|
455
|
+
if (!complete)
|
|
456
|
+
break;
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
let prefix = [], current;
|
|
460
|
+
const flush = (closed) => { if (current) {
|
|
461
|
+
groups.push({ ...current, complete: closed && current.complete });
|
|
462
|
+
current = undefined;
|
|
463
|
+
} };
|
|
464
|
+
for (const segment of message.segments) {
|
|
465
|
+
const value = segment.value;
|
|
466
|
+
if (value.type === 'text' || value.type === 'markdown') {
|
|
467
|
+
if (current && current.format !== value.type)
|
|
468
|
+
flush(true);
|
|
469
|
+
current ??= { key: `${message.key}/${segment.key}`, segments: prefix, format: value.type, complete: true };
|
|
470
|
+
prefix = [];
|
|
471
|
+
current.segments.push(value);
|
|
472
|
+
current.complete &&= segment.complete;
|
|
473
|
+
}
|
|
474
|
+
else {
|
|
475
|
+
flush(true);
|
|
476
|
+
if (value.type === 'mention' || value.type === 'reply')
|
|
477
|
+
prefix.push(value);
|
|
478
|
+
else {
|
|
479
|
+
groups.push({ key: `${message.key}/${segment.key}`, segments: [...prefix, value], complete: segment.complete });
|
|
480
|
+
prefix = [];
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
if (!segment.complete) {
|
|
484
|
+
flush(false);
|
|
485
|
+
return groups;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
flush(message.complete);
|
|
489
|
+
if (prefix.length && message.complete)
|
|
490
|
+
groups.push({ key: `${message.key}/prefix`, segments: prefix, complete: true });
|
|
491
|
+
if (!message.complete)
|
|
492
|
+
break;
|
|
493
|
+
}
|
|
494
|
+
return groups;
|
|
495
|
+
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
2
2
|
/** Runs the generation-owned middleware projection or the terminal directly. */
|
|
3
3
|
export declare function runRuntimeMiddleware<TInput>(snapshot: RuntimeSnapshot, input: TInput, terminal: () => Promise<void>, target: 'inbound' | 'outbound'): Promise<void>;
|
|
4
|
+
/** Legacy outbound middleware sees one complete reply unless its author explicitly supports revisions. */
|
|
5
|
+
export declare function supportsIncrementalOutbound(snapshot: RuntimeSnapshot, adapter: string): boolean;
|
|
@@ -11,3 +11,8 @@ function middleware(snapshot) {
|
|
|
11
11
|
const projection = snapshot.projections.get(middlewareFeatureId);
|
|
12
12
|
return isMiddlewareIndex(projection) ? projection : undefined;
|
|
13
13
|
}
|
|
14
|
+
/** Legacy outbound middleware sees one complete reply unless its author explicitly supports revisions. */
|
|
15
|
+
export function supportsIncrementalOutbound(snapshot, adapter) {
|
|
16
|
+
return middleware(snapshot)?.list().every(record => record.target !== 'outbound'
|
|
17
|
+
|| record.adapter !== undefined && record.adapter !== adapter || record.incremental === true) ?? true;
|
|
18
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zhin.js/core",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.55",
|
|
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/
|
|
60
|
+
"@zhin.js/command": "1.1.13",
|
|
61
|
+
"@zhin.js/component": "1.1.12",
|
|
61
62
|
"@zhin.js/database": "1.1.5",
|
|
62
|
-
"@zhin.js/handler": "1.1.
|
|
63
|
-
"@zhin.js/
|
|
64
|
-
"@zhin.js/command": "1.1.11",
|
|
63
|
+
"@zhin.js/handler": "1.1.11",
|
|
64
|
+
"@zhin.js/adapter": "1.1.27",
|
|
65
65
|
"@zhin.js/interaction": "1.1.2",
|
|
66
|
-
"@zhin.js/im-contract": "1.1.
|
|
67
|
-
"@zhin.js/kernel": "1.1.5",
|
|
66
|
+
"@zhin.js/im-contract": "1.1.10",
|
|
68
67
|
"@zhin.js/logger": "1.1.2",
|
|
69
|
-
"@zhin.js/
|
|
70
|
-
"@zhin.js/
|
|
71
|
-
"@zhin.js/
|
|
68
|
+
"@zhin.js/middleware": "1.1.12",
|
|
69
|
+
"@zhin.js/permission": "1.1.11",
|
|
70
|
+
"@zhin.js/kernel": "1.1.5",
|
|
71
|
+
"@zhin.js/schedule-feature": "1.1.11",
|
|
72
72
|
"@zhin.js/schema": "1.1.4",
|
|
73
|
-
"@zhin.js/jsx": "1.1.
|
|
74
|
-
"@zhin.js/feature-kit": "1.1.
|
|
75
|
-
"@zhin.js/
|
|
73
|
+
"@zhin.js/jsx": "1.1.9",
|
|
74
|
+
"@zhin.js/feature-kit": "1.1.11",
|
|
75
|
+
"@zhin.js/plugin-runtime": "1.1.19"
|
|
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.50"
|
|
83
83
|
},
|
|
84
84
|
"repository": {
|
|
85
85
|
"type": "git",
|
|
@@ -108,7 +108,7 @@
|
|
|
108
108
|
"features": [
|
|
109
109
|
{
|
|
110
110
|
"package": "@zhin.js/adapter",
|
|
111
|
-
"api": "^1.0
|
|
111
|
+
"api": "^2.1.0"
|
|
112
112
|
},
|
|
113
113
|
{
|
|
114
114
|
"package": "@zhin.js/command",
|