@zhin.js/core 1.1.54 → 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/lib/built/interaction-messages.d.ts +1 -1
- 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 +5 -1
- 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 +4 -1
- package/lib/plugin-runtime/im/endpoint-runtime.js +38 -2
- package/lib/plugin-runtime/im/im-runtime.js +4 -3
- package/lib/plugin-runtime/im/index.d.ts +1 -0
- package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +16 -2
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +49 -14
- 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
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const interactionMessages: (locale: import("@zhin.js/plugin-runtime").Locale | undefined, key: "number" | "fallback" | "
|
|
1
|
+
export declare const interactionMessages: (locale: import("@zhin.js/plugin-runtime").Locale | undefined, key: "number" | "fallback" | "minLength" | "maxLength" | "pattern" | "integer" | "min" | "max" | "confirmOrCancel" | "select" | "invalidSelection" | "minSelections" | "maxSelections" | "minItems" | "maxItems" | "invalidNumbers" | "invalidBooleans" | "confirm" | "cancel" | "confirmation" | "selection" | "multiple" | "list" | "ended" | "expired" | "timeout", values?: import("@zhin.js/plugin-runtime").MessageValues) => string;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type JSXElement, type JSXRenderable } from '@zhin.js/jsx';
|
|
2
2
|
import type { MediaRef, Segment } from '@zhin.js/im-contract';
|
|
3
3
|
import type { Message, SendContent } from '../plugin-runtime/im/contracts.js';
|
|
4
|
-
import type { ButtonData } from '../built/interactive-segments/types.js';
|
|
4
|
+
import type { ActionSegmentData, ButtonData, KeyboardSegmentData } from '../built/interactive-segments/types.js';
|
|
5
5
|
export type TextProps = {
|
|
6
6
|
readonly text: string;
|
|
7
7
|
readonly children?: never;
|
|
@@ -107,8 +107,8 @@ export declare const Dice: (props: {
|
|
|
107
107
|
export declare const Rps: (props: {
|
|
108
108
|
readonly result?: number;
|
|
109
109
|
}) => JSXElement;
|
|
110
|
-
export declare const Keyboard: (props:
|
|
111
|
-
export declare const Action: (props:
|
|
110
|
+
export declare const Keyboard: (props: KeyboardSegmentData) => JSXElement;
|
|
111
|
+
export declare const Action: (props: ActionSegmentData) => JSXElement;
|
|
112
112
|
export declare const Link: (props: {
|
|
113
113
|
readonly url: string;
|
|
114
114
|
readonly text?: string;
|
package/lib/jsx/message-tags.js
CHANGED
|
@@ -40,6 +40,9 @@ export const Forward = nativeTag('forward');
|
|
|
40
40
|
export const Share = nativeTag('share');
|
|
41
41
|
export const Dice = nativeTag('dice');
|
|
42
42
|
export const Rps = nativeTag('rps');
|
|
43
|
+
// Explicit annotations keep the emitted .d.ts on the leaf type module. Inferred, they
|
|
44
|
+
// print as import("../index.js"), dragging the whole core entry (and @zhin.js/ai,
|
|
45
|
+
// database drivers) into every packed consumer that only imports a feature subpath.
|
|
43
46
|
export const Keyboard = nativeTag('keyboard');
|
|
44
47
|
export const Action = nativeTag('action');
|
|
45
48
|
export const Link = nativeTag('link');
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { EndpointControl, EndpointManagement } from '@zhin.js/adapter';
|
|
2
|
-
import type { ConversationRef, DeliveryReceipt } from '@zhin.js/im-contract';
|
|
2
|
+
import type { ConversationRef, DeliveryReceipt, SelfProfilePort } from '@zhin.js/im-contract';
|
|
3
3
|
import type { Locale, PluginId } from '@zhin.js/plugin-runtime';
|
|
4
4
|
import type { SendContent } from './contracts.js';
|
|
5
|
+
import type { CoreReplyStream, OpenReplyStreamOptions } from './progressive-reply.js';
|
|
5
6
|
/** Capture while the source Message/event is active, before handing work to an asynchronous owner. */
|
|
6
7
|
export interface CaptureEndpointOperationInput {
|
|
7
8
|
/** Canonical complete source address; never an account alias. */
|
|
@@ -20,11 +21,14 @@ export interface CapturedEndpointOperation {
|
|
|
20
21
|
/** The same guarded semantic ports as ordinary calls, pinned to the retained Client. */
|
|
21
22
|
readonly control?: EndpointControl;
|
|
22
23
|
readonly management?: EndpointManagement;
|
|
24
|
+
/** Current account facts and approved mutations, under the same retained operation. */
|
|
25
|
+
readonly profile?: SelfProfilePort;
|
|
23
26
|
/** Uses the ordinary renderer/middleware/delivery pipeline with the captured author. */
|
|
24
27
|
send(content: SendContent, options?: Readonly<{
|
|
25
28
|
locale?: Locale;
|
|
26
29
|
signal?: AbortSignal;
|
|
27
30
|
}>): Promise<DeliveryReceipt>;
|
|
31
|
+
openReplyStream?(options?: OpenReplyStreamOptions): CoreReplyStream | undefined;
|
|
28
32
|
/** Stops new calls and releases source/Root leases after accepted calls drain; never stops the account. */
|
|
29
33
|
release(): void;
|
|
30
34
|
}
|
|
@@ -28,6 +28,8 @@ export declare class ConversationRuntime {
|
|
|
28
28
|
commitContext(conversation: ConversationRef, consumer: string, cursor: number): Promise<void>;
|
|
29
29
|
recordIncoming(input: IncomingMessage, sender: MessageSenderRef | undefined): Promise<number | undefined>;
|
|
30
30
|
recordOutbound(request: SendRequest, receipt: DeliveryReceipt, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<void>;
|
|
31
|
+
/** Records a confirmed replacement body without inventing another physical message. */
|
|
32
|
+
recordOutboundUpdate(request: SendRequest, receipt: DeliveryReceipt, revision: number, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<void>;
|
|
31
33
|
/** Records a normalized notice; returns the stored event (with its sequence) when newly appended. */
|
|
32
34
|
recordNotice(notice: Notice): Promise<SequencedConversationEvent | undefined>;
|
|
33
35
|
/** 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 && message.contentStatus !== 'unavailable'
|
|
29
|
+
return message && !message.recalled && message.contentStatus !== 'unavailable'
|
|
30
30
|
? Object.freeze({ status: 'resolved', reference, value: message })
|
|
31
31
|
: undefined;
|
|
32
32
|
}
|
|
@@ -42,14 +42,14 @@ export class ConversationRuntime {
|
|
|
42
42
|
const excluded = new Set(excludeMessageId ? [excludeMessageId] : []);
|
|
43
43
|
for (const entry of events) {
|
|
44
44
|
// Only message timestamps are runtime-assigned; notice clocks are adapter-defined.
|
|
45
|
-
if (entry.event.type === 'message.created' && entry.event.timestamp < notBefore)
|
|
45
|
+
if ((entry.event.type === 'message.created' || entry.event.type === 'message.updated') && entry.event.timestamp < notBefore)
|
|
46
46
|
continue;
|
|
47
47
|
if (await this.#isOwnRecall(entry.event)) {
|
|
48
48
|
if (entry.event.type === 'message.recalled')
|
|
49
49
|
excluded.add(entry.event.message.id);
|
|
50
50
|
continue;
|
|
51
51
|
}
|
|
52
|
-
if (entry.event.type === 'message.created'
|
|
52
|
+
if ((entry.event.type === 'message.created' || entry.event.type === 'message.updated')
|
|
53
53
|
&& this.#interactionAnswers.has(messageRefKey(entry.event.message.ref)))
|
|
54
54
|
continue;
|
|
55
55
|
relevant.push(entry);
|
|
@@ -133,6 +133,24 @@ export class ConversationRuntime {
|
|
|
133
133
|
}),
|
|
134
134
|
}));
|
|
135
135
|
}
|
|
136
|
+
/** Records a confirmed replacement body without inventing another physical message. */
|
|
137
|
+
async recordOutboundUpdate(request, receipt, revision, canonicalContent) {
|
|
138
|
+
if (receipt.status !== 'sent' || !receipt.message?.id)
|
|
139
|
+
return;
|
|
140
|
+
const original = await this.#events.getMessage(receipt.message);
|
|
141
|
+
if (!original)
|
|
142
|
+
throw new Error('Cannot record an update before its original message');
|
|
143
|
+
const { contentStatus: _status, outboundTextDigest: _digest, ...identity } = original;
|
|
144
|
+
await this.#events.append(Object.freeze({
|
|
145
|
+
eventId: `message:${messageRefKey(receipt.message)}:revision:${revision}`,
|
|
146
|
+
conversation: request.conversation, timestamp: Date.now(), type: 'message.updated',
|
|
147
|
+
message: Object.freeze({ ...identity, revision,
|
|
148
|
+
segments: canonicalContent === 'unavailable' ? [] : canonicalContent ?? segmentsFromContent(request.content),
|
|
149
|
+
...(canonicalContent === 'unavailable' ? { contentStatus: 'unavailable' } : {}),
|
|
150
|
+
...(canonicalContent !== 'unavailable' && canonicalContent?.length && canonicalContent.every(segment => segment.type === 'text') && receipt.outboundTextDigest
|
|
151
|
+
? { outboundTextDigest: receipt.outboundTextDigest } : {}), }),
|
|
152
|
+
}));
|
|
153
|
+
}
|
|
136
154
|
/** Records a normalized notice; returns the stored event (with its sequence) when newly appended. */
|
|
137
155
|
async recordNotice(notice) {
|
|
138
156
|
const event = conversationEventFromNotice(notice);
|
|
@@ -297,11 +315,29 @@ function conversationEventFromNotice(notice) {
|
|
|
297
315
|
function aggregateConversationContext(events, excluded) {
|
|
298
316
|
const ordinary = [];
|
|
299
317
|
const noisy = new Map();
|
|
318
|
+
const latestMessages = new Map();
|
|
319
|
+
const recalled = new Set();
|
|
320
|
+
for (const entry of events) {
|
|
321
|
+
const event = entry.event;
|
|
322
|
+
if (event.type === 'message.recalled')
|
|
323
|
+
recalled.add(messageRefKey(event.message));
|
|
324
|
+
if (event.type !== 'message.created' && event.type !== 'message.updated')
|
|
325
|
+
continue;
|
|
326
|
+
const key = messageRefKey(event.message.ref), previous = latestMessages.get(key);
|
|
327
|
+
if (recalled.has(key))
|
|
328
|
+
continue;
|
|
329
|
+
const previousRevision = previous && (previous.event.type === 'message.created' || previous.event.type === 'message.updated')
|
|
330
|
+
? previous.event.message.revision ?? 0 : -1;
|
|
331
|
+
if ((event.message.revision ?? 0) > previousRevision)
|
|
332
|
+
latestMessages.set(key, entry);
|
|
333
|
+
}
|
|
300
334
|
for (const { sequence, event } of events) {
|
|
301
335
|
// #996: these reach the model only through the short ephemeral `[Scene events]` block.
|
|
302
336
|
if (SCENE_ONLY_EVENT_TYPES.has(event.type))
|
|
303
337
|
continue;
|
|
304
|
-
if (event.type === 'message.created') {
|
|
338
|
+
if (event.type === 'message.created' || event.type === 'message.updated') {
|
|
339
|
+
if (latestMessages.get(messageRefKey(event.message.ref))?.sequence !== sequence)
|
|
340
|
+
continue;
|
|
305
341
|
if (excluded.has(event.message.ref.id))
|
|
306
342
|
continue;
|
|
307
343
|
const text = describeConversationMessage(event.message);
|
|
@@ -365,6 +401,7 @@ function describeConversationEvent(event) {
|
|
|
365
401
|
case 'member.role_changed':
|
|
366
402
|
return `${event.member.displayName ?? event.member.id} (${event.member.id}) role ${event.role} was ${event.enabled ? 'enabled' : 'disabled'}${actor ? ` by ${actor}` : ''}.`;
|
|
367
403
|
case 'message.created':
|
|
404
|
+
case 'message.updated':
|
|
368
405
|
case 'scene.join_requested':
|
|
369
406
|
case 'scene.notice_updated':
|
|
370
407
|
case 'member.card_changed':
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { OutboundDeliveryExecution } from './outbound-delivery-runtime.js';
|
|
1
2
|
import type { CaptureEndpointOperationInput, CapturedEndpointOperation } from './captured-endpoint-operation.js';
|
|
2
3
|
export type { CaptureEndpointOperationInput, CapturedEndpointOperation } from './captured-endpoint-operation.js';
|
|
3
4
|
import { AdapterIndex, type AdapterEndpointPhase, type AdapterOperation, type AdapterEndpointSummary, type EndpointTransportState, type EndpointManagement, type EndpointManagementCapability } from '@zhin.js/adapter';
|
|
@@ -52,7 +53,7 @@ interface EndpointRuntimeContext {
|
|
|
52
53
|
/** Independently retain the current operation snapshot for detached source work. */
|
|
53
54
|
retain(): SnapshotLease;
|
|
54
55
|
release(lease: SnapshotLease): void;
|
|
55
|
-
send(request: SendRequest, snapshot: RuntimeSnapshot): Promise<DeliveryReceipt>;
|
|
56
|
+
send(request: SendRequest, snapshot: RuntimeSnapshot, execution?: OutboundDeliveryExecution): Promise<DeliveryReceipt>;
|
|
56
57
|
}
|
|
57
58
|
/** Owns generation-leased Endpoint discovery, control, management, and Console delivery. */
|
|
58
59
|
export declare class EndpointRuntime {
|
|
@@ -69,12 +70,14 @@ export declare class EndpointRuntime {
|
|
|
69
70
|
captureOperation(input: CaptureEndpointOperationInput): CapturedEndpointOperation;
|
|
70
71
|
send(input: RuntimeEndpointSendInput): Promise<{
|
|
71
72
|
messageId: string;
|
|
73
|
+
receipt: DeliveryReceipt;
|
|
72
74
|
}>;
|
|
73
75
|
/** Resolves a persisted identity exactly in the current operation generation. */
|
|
74
76
|
sendTarget(target: DeliveryTarget, content: unknown, requester?: PluginId, options?: Readonly<{
|
|
75
77
|
locale?: Locale;
|
|
76
78
|
}>): Promise<{
|
|
77
79
|
messageId: string;
|
|
80
|
+
receipt: DeliveryReceipt;
|
|
78
81
|
}>;
|
|
79
82
|
addReaction(input: RuntimeEndpointReactionInput): Promise<string | null>;
|
|
80
83
|
removeReaction(input: RuntimeEndpointRemoveReactionInput): Promise<void>;
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { operationEndpoint } from './operation-endpoint.js';
|
|
2
|
+
import { createCoreReplyStream } from './progressive-reply.js';
|
|
3
|
+
import { supportsIncrementalOutbound } from './runtime-middleware.js';
|
|
2
4
|
import { adapterFeatureId, isAdapterIndex, } from '@zhin.js/adapter';
|
|
3
5
|
import { normalizeDeliveryTarget } from '@zhin.js/plugin-runtime';
|
|
4
6
|
import { EndpointDeliveryError, } from '@zhin.js/im-contract';
|
|
@@ -123,6 +125,7 @@ export class EndpointRuntime {
|
|
|
123
125
|
return Object.freeze({
|
|
124
126
|
target, signal: captured.signal, control: controls,
|
|
125
127
|
management: index.management(id, scope),
|
|
128
|
+
profile: index.profile(id, scope),
|
|
126
129
|
send: async (content, options) => {
|
|
127
130
|
assertActive();
|
|
128
131
|
// Retain the source authority, while each send owns its caller cancellation.
|
|
@@ -142,6 +145,37 @@ export class EndpointRuntime {
|
|
|
142
145
|
releaseCall();
|
|
143
146
|
}
|
|
144
147
|
},
|
|
148
|
+
openReplyStream: (options = {}) => {
|
|
149
|
+
assertActive();
|
|
150
|
+
if (!captured.streaming || !supportsIncrementalOutbound(snapshot.value, target.endpoint.adapter))
|
|
151
|
+
return undefined;
|
|
152
|
+
if (captured.streaming.supports?.({ conversation: target, source: options.source }) === false)
|
|
153
|
+
return undefined;
|
|
154
|
+
const releaseCall = retainCall();
|
|
155
|
+
let streamLease;
|
|
156
|
+
try {
|
|
157
|
+
streamLease = index.acquire(id, captured.signal, captured.endpoint);
|
|
158
|
+
const retained = streamLease;
|
|
159
|
+
return createCoreReplyStream({ endpoint: retained, streaming: retained.streaming, options,
|
|
160
|
+
deliver: (content, execution) => {
|
|
161
|
+
// Opening admitted this whole stream; capture.release only closes new admission.
|
|
162
|
+
retained.assertActive();
|
|
163
|
+
return this.context.send({ conversation: target, requester, content,
|
|
164
|
+
...(options.locale ? { locale: options.locale } : {}), [operationEndpoint]: retained }, snapshot.value, execution);
|
|
165
|
+
},
|
|
166
|
+
release: () => { try {
|
|
167
|
+
retained.release();
|
|
168
|
+
}
|
|
169
|
+
finally {
|
|
170
|
+
releaseCall();
|
|
171
|
+
} }, });
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
streamLease?.release();
|
|
175
|
+
releaseCall();
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
},
|
|
145
179
|
release: () => {
|
|
146
180
|
if (released)
|
|
147
181
|
return;
|
|
@@ -333,9 +367,11 @@ function normalizeConsoleContent(content) {
|
|
|
333
367
|
function requireSentReceipt(result) {
|
|
334
368
|
if (result.status !== 'sent') {
|
|
335
369
|
throw new EndpointDeliveryError(result.failure?.code ?? `outbound_${result.status}`, result.failure?.message ?? 'Outbound delivery was suppressed.', result.failure?.deliveryUnknown ? 'unknown'
|
|
336
|
-
: result.status === 'rejected' ? 'rejected' : 'not_sent'
|
|
370
|
+
: result.status === 'rejected' ? 'rejected' : 'not_sent', { receipt: result, ...(result.parts ? { parts: result.parts.map(part => ({
|
|
371
|
+
...(part.message ? { messageId: part.message.id } : {}), ...(part.sourceIndices ? { sourceIndices: part.sourceIndices } : {}),
|
|
372
|
+
})) } : {}) });
|
|
337
373
|
}
|
|
338
|
-
return { messageId: result.message?.id ?? '' };
|
|
374
|
+
return { messageId: result.message?.id ?? '', receipt: result };
|
|
339
375
|
}
|
|
340
376
|
/** A canonical message/address cannot be redirected by a second endpoint selector. */
|
|
341
377
|
function assertSameEndpoint(expected, actual) {
|
|
@@ -56,6 +56,7 @@ export class ImRuntime {
|
|
|
56
56
|
diagnostics: this.#messageDiagnostics,
|
|
57
57
|
ledger: (conversation, receipt, payload) => ledger.record(conversation, receipt, payload),
|
|
58
58
|
record: (request, receipt, canonicalContent) => this.#conversations.recordOutbound(request, receipt, canonicalContent),
|
|
59
|
+
recordUpdate: (request, receipt, revision, canonicalContent) => this.#conversations.recordOutboundUpdate(request, receipt, revision, canonicalContent),
|
|
59
60
|
rememberFallback: (conversation, generation, map) => this.#interactions.rememberFallback(conversation, generation, map),
|
|
60
61
|
publish: (event) => this.#messageEventStream.publish(event),
|
|
61
62
|
prepareButtons: (request, snapshot) => this.#interactions.prepareButtons(request, snapshot),
|
|
@@ -86,7 +87,7 @@ export class ImRuntime {
|
|
|
86
87
|
acquire: () => this.#acquire(),
|
|
87
88
|
retain: () => this.#retainSnapshot(),
|
|
88
89
|
release: (lease) => this.#release(lease),
|
|
89
|
-
send: (request, snapshot) => this.#deliver(request, snapshot),
|
|
90
|
+
send: (request, snapshot, execution) => this.#deliver(request, snapshot, execution),
|
|
90
91
|
});
|
|
91
92
|
}
|
|
92
93
|
/** Process composition replaces the bootstrap memory store after required DB activation. */
|
|
@@ -260,8 +261,8 @@ export class ImRuntime {
|
|
|
260
261
|
}
|
|
261
262
|
}
|
|
262
263
|
/** All unified outbound entry points observe the actual delivery, never their own caller/drain promise. */
|
|
263
|
-
#deliver(request, snapshot) {
|
|
264
|
-
const delivery = this.#outbound.deliver(request, snapshot);
|
|
264
|
+
#deliver(request, snapshot, execution) {
|
|
265
|
+
const delivery = this.#outbound.deliver(request, snapshot, execution);
|
|
265
266
|
this.#commandOperation.getStore()?.trackSend(delivery);
|
|
266
267
|
return delivery;
|
|
267
268
|
}
|
|
@@ -14,6 +14,7 @@ export type { RuntimeMessageDiagnostic, RuntimeMessageDiagnosticStep, RuntimeMes
|
|
|
14
14
|
export type { RuntimeMessageEvent, RuntimeMessageEventSource, RuntimeMessageRendering, RuntimeSceneEventSignal, RuntimeSceneEventSource, OutboundFallbackReason, } from './message-events.js';
|
|
15
15
|
export * from './outbound-renderer.js';
|
|
16
16
|
export * from './outbound-segments.js';
|
|
17
|
+
export type { CoreReplyStream, OpenReplyStreamOptions, ReplyStreamSnapshot, ConfirmedReplyContent } from './progressive-reply.js';
|
|
17
18
|
export * from '../../notice.js';
|
|
18
19
|
export * from '../../request.js';
|
|
19
20
|
export * from '../../system-event.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
2
|
-
import { type ConversationRef, type DeliveryReceipt, type Segment } from '@zhin.js/im-contract';
|
|
2
|
+
import { type ConversationRef, type DeliveryReceipt, type DeliveryPart, type EndpointSendResult, 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';
|
|
@@ -9,17 +9,31 @@ interface OutboundDeliveryContext {
|
|
|
9
9
|
readonly diagnostics?: RuntimeMessageDiagnostics;
|
|
10
10
|
prepareButtons?(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
|
|
11
11
|
record(request: SendRequest, receipt: DeliveryReceipt, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<void>;
|
|
12
|
+
recordUpdate?(request: SendRequest, receipt: DeliveryReceipt, revision: number, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<void>;
|
|
12
13
|
/** Side-channel correlation ledger for inbound origin; failures never affect the receipt. */
|
|
13
14
|
ledger?(conversation: ConversationRef, receipt: DeliveryReceipt, payload: unknown): void;
|
|
14
15
|
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>): Record<string, string> | void;
|
|
15
16
|
publish(event: RuntimeMessageEvent): void;
|
|
16
17
|
}
|
|
18
|
+
/** Internal transport continuation. Rendering, policy and middleware still own every submitted revision. */
|
|
19
|
+
export interface OutboundDeliveryExecution {
|
|
20
|
+
send(request: import('@zhin.js/adapter').EndpointSendRequest): Promise<{
|
|
21
|
+
readonly result?: EndpointSendResult;
|
|
22
|
+
readonly confirmedContent?: readonly Segment[];
|
|
23
|
+
readonly contentUnavailable?: true;
|
|
24
|
+
}>;
|
|
25
|
+
history(): 'create' | 'skip' | Readonly<{
|
|
26
|
+
revision: number;
|
|
27
|
+
}>;
|
|
28
|
+
confirmed(part: DeliveryPart, content: readonly Segment[] | undefined): void;
|
|
29
|
+
}
|
|
17
30
|
/** Owns rendering, policy projection, middleware, Endpoint delivery, and delivery facts. */
|
|
18
31
|
export declare class OutboundDeliveryRuntime {
|
|
19
32
|
#private;
|
|
20
33
|
private readonly context;
|
|
21
34
|
constructor(context: OutboundDeliveryContext, renderer?: OutboundRenderer);
|
|
22
|
-
deliver(request: SendRequest, snapshot: RuntimeSnapshot): Promise<DeliveryReceipt>;
|
|
35
|
+
deliver(request: SendRequest, snapshot: RuntimeSnapshot, execution?: OutboundDeliveryExecution): Promise<DeliveryReceipt>;
|
|
23
36
|
}
|
|
24
37
|
export declare function failedDeliveryReceipt(code: string, retryable?: boolean): DeliveryReceipt;
|
|
38
|
+
export declare function receiptFromEndpointError(error: unknown, attempted?: boolean, conversation?: ConversationRef, payloadLength?: number): DeliveryReceipt;
|
|
25
39
|
export {};
|
|
@@ -35,13 +35,13 @@ export class OutboundDeliveryRuntime {
|
|
|
35
35
|
this.context = context;
|
|
36
36
|
this.#renderer = renderer;
|
|
37
37
|
}
|
|
38
|
-
async deliver(request, snapshot) {
|
|
38
|
+
async deliver(request, snapshot, execution) {
|
|
39
39
|
let rendering;
|
|
40
|
-
const receipt = await this.#deliver(request, snapshot, value => { rendering = value; });
|
|
40
|
+
const receipt = await this.#deliver(request, snapshot, value => { rendering = value; }, execution);
|
|
41
41
|
this.context.diagnostics?.delivery(snapshot.generation, request.conversation, receipt, rendering);
|
|
42
42
|
return receipt;
|
|
43
43
|
}
|
|
44
|
-
async #deliver(request, snapshot, observeRendering) {
|
|
44
|
+
async #deliver(request, snapshot, observeRendering, execution) {
|
|
45
45
|
const adapter = request.conversation.endpoint.id;
|
|
46
46
|
const boundEndpoint = request[operationEndpoint];
|
|
47
47
|
if (boundEndpoint && boundEndpoint.canonicalId !== adapter)
|
|
@@ -154,7 +154,8 @@ export class OutboundDeliveryRuntime {
|
|
|
154
154
|
: Array.isArray(payload) && payload.every(isCanonicalSegment) ? payload : undefined;
|
|
155
155
|
// Capture known canonical content before the endpoint can mutate it.
|
|
156
156
|
// Inline rendering bytes and opaque extensions never become new history.
|
|
157
|
-
|
|
157
|
+
let contentSources = canonicalContent?.map(snapshotHistorySource);
|
|
158
|
+
let contentUnavailable = false;
|
|
158
159
|
const payloadLength = Array.isArray(payload) ? payload.length : 1;
|
|
159
160
|
try {
|
|
160
161
|
const sendRequest = {
|
|
@@ -162,10 +163,25 @@ export class OutboundDeliveryRuntime {
|
|
|
162
163
|
locale: resolveLocale(request.locale ?? projectLocale(snapshot)),
|
|
163
164
|
payload,
|
|
164
165
|
};
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
166
|
+
if (execution) {
|
|
167
|
+
const transported = await execution.send(sendRequest);
|
|
168
|
+
if (transported.confirmedContent) {
|
|
169
|
+
contentSources = transported.confirmedContent.map(snapshotHistorySource);
|
|
170
|
+
// Explicit physical evidence must never fall back to the planned logical body.
|
|
171
|
+
contentUnavailable = !contentSources.length || contentSources.some(source => source === undefined);
|
|
172
|
+
}
|
|
173
|
+
if (transported.contentUnavailable) {
|
|
174
|
+
contentSources = undefined;
|
|
175
|
+
contentUnavailable = true;
|
|
176
|
+
}
|
|
177
|
+
receipt = transported.result === undefined ? suppressedDeliveryReceipt()
|
|
178
|
+
: receiptFromEndpointResult(transported.result, request.conversation, contentSources?.length ?? payloadLength);
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
const result = boundEndpoint ? await boundEndpoint.send(sendRequest)
|
|
182
|
+
: await requireAdapters(snapshot).send(adapter, sendRequest);
|
|
183
|
+
receipt = receiptFromEndpointResult(result, request.conversation, payloadLength);
|
|
184
|
+
}
|
|
169
185
|
}
|
|
170
186
|
catch (error) {
|
|
171
187
|
receipt = receiptFromEndpointError(error, true, request.conversation, payloadLength);
|
|
@@ -175,25 +191,36 @@ export class OutboundDeliveryRuntime {
|
|
|
175
191
|
if (receipt.status !== 'sent' && !receipt.failure?.deliveryUnknown && !receipt.parts?.length)
|
|
176
192
|
revokeButtons?.();
|
|
177
193
|
for (const part of evidence.parts) {
|
|
194
|
+
execution?.confirmed(part.part, part.content);
|
|
178
195
|
const partReceipt = { status: 'sent', ...(part.part.message ? { message: part.part.message } : {}),
|
|
179
196
|
...(part.part.outboundTextDigest ? { outboundTextDigest: part.part.outboundTextDigest } : {}) };
|
|
180
|
-
|
|
181
|
-
|
|
197
|
+
const history = execution?.history() ?? 'create';
|
|
198
|
+
if (part.part.message && history !== 'skip') {
|
|
199
|
+
try {
|
|
200
|
+
const content = part.content ?? (contentUnavailable || receipt.parts ? 'unavailable' : undefined);
|
|
201
|
+
if (history === 'create')
|
|
202
|
+
await this.context.record(request, partReceipt, content);
|
|
203
|
+
else
|
|
204
|
+
await this.context.recordUpdate?.(request, partReceipt, history.revision, content);
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
logger.warn(formatCompact({ op: 'outbound_history_failed', error: error instanceof Error ? error.message : String(error) }));
|
|
208
|
+
}
|
|
182
209
|
}
|
|
183
210
|
try {
|
|
184
|
-
this.context.ledger?.(request.conversation, partReceipt, part.content ?? (receipt.parts ? undefined : payload));
|
|
211
|
+
this.context.ledger?.(request.conversation, partReceipt, part.content ?? (contentUnavailable || receipt.parts ? undefined : payload));
|
|
185
212
|
}
|
|
186
213
|
catch (error) {
|
|
187
214
|
logger.warn(`outbound ledger write failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
188
215
|
}
|
|
189
|
-
if (part.part.message)
|
|
216
|
+
if (part.part.message && history !== 'skip')
|
|
190
217
|
this.context.publish({
|
|
191
218
|
direction: 'outbound',
|
|
192
219
|
rendering: projection.rendering,
|
|
193
220
|
conversation: request.conversation,
|
|
194
221
|
requester: request.requester,
|
|
195
222
|
contentPreview: part.content ? previewMessageContent(part.content)
|
|
196
|
-
: receipt.parts ? '[Message content unavailable; inspect its reference.]' : previewMessageContent(payload),
|
|
223
|
+
: contentUnavailable || receipt.parts ? '[Message content unavailable; inspect its reference.]' : previewMessageContent(payload),
|
|
197
224
|
messageId: part.part.message.id,
|
|
198
225
|
timestamp: Date.now(),
|
|
199
226
|
});
|
|
@@ -258,7 +285,7 @@ function receiptFromEndpointResult(result, conversation, payloadLength) {
|
|
|
258
285
|
message: Object.freeze({ conversation, id: result }),
|
|
259
286
|
});
|
|
260
287
|
}
|
|
261
|
-
function receiptFromEndpointError(error, attempted = true, conversation, payloadLength) {
|
|
288
|
+
export function receiptFromEndpointError(error, attempted = true, conversation, payloadLength) {
|
|
262
289
|
if (error instanceof EndpointDeliveryError) {
|
|
263
290
|
const parts = attempted && conversation ? normalizeEndpointParts(error.parts, conversation, payloadLength) : [];
|
|
264
291
|
// Disposition is transport evidence; an error code alone cannot override it.
|
|
@@ -309,6 +336,14 @@ function normalizeEndpointParts(parts, conversation, payloadLength) {
|
|
|
309
336
|
}));
|
|
310
337
|
}
|
|
311
338
|
function snapshotHistorySource(segment) {
|
|
339
|
+
if (segment.type === 'markdown') {
|
|
340
|
+
const data = segment.data;
|
|
341
|
+
// The AI authoring contract has one closed Markdown shape. Core extensions remain opaque.
|
|
342
|
+
if (Object.keys(segment).length !== 2 || !Object.hasOwn(segment, 'type') || !Object.hasOwn(segment, 'data')
|
|
343
|
+
|| Object.keys(data).length !== 1 || !Object.hasOwn(data, 'content') || typeof data.content !== 'string')
|
|
344
|
+
return undefined;
|
|
345
|
+
return { type: 'markdown', data: { content: data.content } };
|
|
346
|
+
}
|
|
312
347
|
// Forward entries and opaque card/extensions have no bounded, simple content contract here.
|
|
313
348
|
if (!isStrictCanonicalSegment(segment) || segment.type === 'forward')
|
|
314
349
|
return undefined;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type EndpointStreaming, type EndpointChildLease, type EndpointStreamSource } from '@zhin.js/adapter';
|
|
2
|
+
import { type DeliveryReceipt, type MessageRef, type Segment } from '@zhin.js/im-contract';
|
|
3
|
+
import type { Locale } from '@zhin.js/plugin-runtime';
|
|
4
|
+
import type { SendContent } from './contracts.js';
|
|
5
|
+
import { type OutboundDeliveryExecution } from './outbound-delivery-runtime.js';
|
|
6
|
+
/** Host-owned keys identify content, independently of model-authored or platform identifiers. */
|
|
7
|
+
export interface ReplyStreamSnapshot {
|
|
8
|
+
readonly revision: number;
|
|
9
|
+
readonly messages: readonly {
|
|
10
|
+
readonly key: string;
|
|
11
|
+
readonly complete: boolean;
|
|
12
|
+
readonly segments: readonly {
|
|
13
|
+
readonly key: string;
|
|
14
|
+
readonly complete: boolean;
|
|
15
|
+
readonly value: Segment;
|
|
16
|
+
}[];
|
|
17
|
+
}[];
|
|
18
|
+
}
|
|
19
|
+
export interface OpenReplyStreamOptions {
|
|
20
|
+
readonly locale?: Locale;
|
|
21
|
+
readonly source?: EndpointStreamSource;
|
|
22
|
+
readonly maxBufferedBytes?: number;
|
|
23
|
+
/** Revalidate trusted reply admission immediately before every platform submission. */
|
|
24
|
+
readonly beforeSubmit?: () => void;
|
|
25
|
+
/** Resource authorization/materialization; this must not submit an external message. */
|
|
26
|
+
readonly prepare?: (segments: readonly Segment[], signal: AbortSignal) => Promise<readonly Segment[]>;
|
|
27
|
+
}
|
|
28
|
+
export interface ConfirmedReplyContent {
|
|
29
|
+
/** Stable physical container key; one logical message can produce several containers. */
|
|
30
|
+
readonly key: string;
|
|
31
|
+
readonly segments: readonly Segment[];
|
|
32
|
+
readonly message?: MessageRef;
|
|
33
|
+
}
|
|
34
|
+
export interface CoreReplyStream {
|
|
35
|
+
readonly minIntervalMs?: number;
|
|
36
|
+
readonly receipt: DeliveryReceipt;
|
|
37
|
+
readonly confirmed: readonly ConfirmedReplyContent[];
|
|
38
|
+
/** Coalesces replaceable candidates; does not allocate a Promise for every model token. */
|
|
39
|
+
update(snapshot: ReplyStreamSnapshot): void;
|
|
40
|
+
finish(snapshot: ReplyStreamSnapshot): Promise<DeliveryReceipt>;
|
|
41
|
+
cancel(): Promise<DeliveryReceipt>;
|
|
42
|
+
}
|
|
43
|
+
interface ProgressiveReplyContext {
|
|
44
|
+
readonly endpoint: EndpointChildLease;
|
|
45
|
+
readonly streaming: EndpointStreaming;
|
|
46
|
+
readonly options: OpenReplyStreamOptions;
|
|
47
|
+
readonly deliver: (content: SendContent, execution: OutboundDeliveryExecution) => Promise<DeliveryReceipt>;
|
|
48
|
+
readonly release: () => void;
|
|
49
|
+
}
|
|
50
|
+
/** One producer, one sending pump, and one replaceable candidate rather than a queue per token. */
|
|
51
|
+
export declare function createCoreReplyStream(context: ProgressiveReplyContext): CoreReplyStream;
|
|
52
|
+
export {};
|
|
@@ -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/
|
|
61
|
-
"@zhin.js/
|
|
62
|
-
"@zhin.js/component": "1.1.11",
|
|
60
|
+
"@zhin.js/command": "1.1.13",
|
|
61
|
+
"@zhin.js/component": "1.1.12",
|
|
63
62
|
"@zhin.js/database": "1.1.5",
|
|
64
|
-
"@zhin.js/handler": "1.1.
|
|
65
|
-
"@zhin.js/
|
|
63
|
+
"@zhin.js/handler": "1.1.11",
|
|
64
|
+
"@zhin.js/adapter": "1.1.27",
|
|
66
65
|
"@zhin.js/interaction": "1.1.2",
|
|
67
|
-
"@zhin.js/
|
|
66
|
+
"@zhin.js/im-contract": "1.1.10",
|
|
68
67
|
"@zhin.js/logger": "1.1.2",
|
|
69
|
-
"@zhin.js/middleware": "1.1.
|
|
70
|
-
"@zhin.js/permission": "1.1.
|
|
71
|
-
"@zhin.js/
|
|
72
|
-
"@zhin.js/schedule-feature": "1.1.
|
|
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",
|
|
73
72
|
"@zhin.js/schema": "1.1.4",
|
|
74
|
-
"@zhin.js/jsx": "1.1.
|
|
75
|
-
"@zhin.js/feature-kit": "1.1.
|
|
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": "^2.
|
|
111
|
+
"api": "^2.1.0"
|
|
112
112
|
},
|
|
113
113
|
{
|
|
114
114
|
"package": "@zhin.js/command",
|