@zhin.js/core 1.1.45 → 1.1.47
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 +6 -0
- package/lib/ai-completion-contract.d.ts +121 -0
- package/lib/ai-completion-contract.js +68 -0
- package/lib/built/ai-outbound/prompt.d.ts +2 -0
- package/lib/built/ai-outbound/prompt.js +2 -0
- package/lib/built/html-to-text.d.ts +0 -3
- package/lib/built/html-to-text.js +130 -39
- package/lib/built/interactive-segments/resolve.d.ts +2 -2
- package/lib/built/interactive-segments/resolve.js +20 -12
- package/lib/built/readable-link.d.ts +4 -0
- package/lib/built/readable-link.js +32 -0
- package/lib/built/rich-segments/markdown-to-text.d.ts +1 -1
- package/lib/built/rich-segments/markdown-to-text.js +123 -11
- package/lib/built/segment-contract/index.d.ts +1 -1
- package/lib/built/segment-contract/index.js +1 -1
- package/lib/built/segment-contract/json-schema.d.ts +30 -1
- package/lib/built/segment-contract/json-schema.js +93 -20
- package/lib/built/segment-contract/validate.d.ts +3 -0
- package/lib/built/segment-contract/validate.js +2 -0
- package/lib/built/user-interaction.d.ts +1 -1
- package/lib/built/user-interaction.js +4 -5
- package/lib/index.d.ts +3 -0
- package/lib/index.js +2 -0
- package/lib/jsx/message-tags.d.ts +1 -0
- package/lib/plugin-runtime/im/command-menu-navigation.d.ts +6 -0
- package/lib/plugin-runtime/im/command-menu-navigation.js +33 -0
- package/lib/plugin-runtime/im/contracts.d.ts +12 -2
- package/lib/plugin-runtime/im/contracts.js +24 -2
- package/lib/plugin-runtime/im/im-runtime.d.ts +2 -0
- package/lib/plugin-runtime/im/im-runtime.js +24 -4
- package/lib/plugin-runtime/im/inbound-runtime.d.ts +5 -0
- package/lib/plugin-runtime/im/inbound-runtime.js +193 -135
- package/lib/plugin-runtime/im/index.d.ts +1 -0
- package/lib/plugin-runtime/im/interaction-operation.d.ts +8 -0
- package/lib/plugin-runtime/im/interaction-operation.js +2 -0
- package/lib/plugin-runtime/im/interaction-runtime.d.ts +5 -3
- package/lib/plugin-runtime/im/interaction-runtime.js +150 -51
- package/lib/plugin-runtime/im/message-diagnostics.d.ts +70 -0
- package/lib/plugin-runtime/im/message-diagnostics.js +182 -0
- package/lib/plugin-runtime/im/message-dispatcher.d.ts +1 -1
- package/lib/plugin-runtime/im/message-dispatcher.js +41 -5
- package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +2 -0
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +7 -0
- package/lib/plugin-runtime/im/outbound-segments.d.ts +8 -0
- package/lib/plugin-runtime/im/outbound-segments.js +25 -4
- package/package.json +13 -13
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import { conversationRefKey } from '@zhin.js/im-contract';
|
|
2
2
|
import { assertUserInteractionRequest, parseUserInteractionAnswer, projectUserInteraction, renderUserInteraction, } from '../../built/user-interaction.js';
|
|
3
|
-
import {
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { generationAdmissionSource, outboundHostToken, PluginOutboundHost } from '@zhin.js/plugin-runtime';
|
|
5
|
+
import { RuntimeMessage } from './contracts.js';
|
|
6
|
+
import { interactionOperationScope } from './interaction-operation.js';
|
|
7
|
+
import { actionPayloadFromSegments, RuntimeInteractiveRouter } from './interactive-router.js';
|
|
4
8
|
import { isJsxButtonPayload, JsxButtonRegistry } from './jsx-button-registry.js';
|
|
9
|
+
const ASK_ACTION_PREFIX = 'zhin:ask:';
|
|
5
10
|
class UserInteractionTimeoutError extends Error {
|
|
6
11
|
constructor(message) {
|
|
7
12
|
super(message);
|
|
@@ -38,6 +43,10 @@ export class RuntimeInteractionCoordinator {
|
|
|
38
43
|
const payload = this.#router.resolvePayload(message);
|
|
39
44
|
if (payload && snapshot && await this.#buttons.dispatch(message, payload, snapshot))
|
|
40
45
|
return true;
|
|
46
|
+
if (payload?.startsWith(ASK_ACTION_PREFIX)) {
|
|
47
|
+
await message.$reply('交互已过期或不可用,请重新发起。');
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
41
50
|
if (this.#router.isExpiredFallback(message)) {
|
|
42
51
|
await message.$reply('交互已过期或不可用,请重新发起。');
|
|
43
52
|
return true;
|
|
@@ -53,11 +62,22 @@ export class RuntimeInteractionCoordinator {
|
|
|
53
62
|
// labelled an expired button. Explicit JSX callbacks still belong to buttons.
|
|
54
63
|
if (isJsxButtonPayload(payload))
|
|
55
64
|
return false;
|
|
65
|
+
const explicit = actionPayloadFromSegments(message.segments);
|
|
66
|
+
// Another feature's callback is not a plain-text answer to this question.
|
|
67
|
+
if (explicit && !explicit.startsWith(ASK_ACTION_PREFIX))
|
|
68
|
+
return false;
|
|
56
69
|
const claim = this.#claims.get(this.#conversationKey(message));
|
|
57
|
-
if (!claim)
|
|
70
|
+
if (!claim || claim.generation !== message.generation)
|
|
58
71
|
return false;
|
|
59
|
-
|
|
60
|
-
|
|
72
|
+
if (payload?.startsWith(ASK_ACTION_PREFIX)) {
|
|
73
|
+
const answer = claim.actions.get(payload);
|
|
74
|
+
if (answer !== undefined)
|
|
75
|
+
return claim.accept(answer);
|
|
76
|
+
// Native stale callbacks never answer a new question. Plain text remains
|
|
77
|
+
// the current question's input even if an old fallback once used its label.
|
|
78
|
+
return explicit ? false : claim.accept(message.content);
|
|
79
|
+
}
|
|
80
|
+
return claim.accept(payload ?? message.content);
|
|
61
81
|
}
|
|
62
82
|
/**
|
|
63
83
|
* Probe used by Room routing: is this message the answer to something pending on this exact
|
|
@@ -66,7 +86,13 @@ export class RuntimeInteractionCoordinator {
|
|
|
66
86
|
* alone does not count. Changes no state.
|
|
67
87
|
*/
|
|
68
88
|
hasPendingAnswer(conversation, senderId, generation, input) {
|
|
69
|
-
|
|
89
|
+
const claim = this.#claims.get(`${conversationRefKey(conversation)}:${senderId}`);
|
|
90
|
+
const explicit = actionPayloadFromSegments(input?.segments);
|
|
91
|
+
if (explicit?.startsWith(ASK_ACTION_PREFIX)
|
|
92
|
+
&& (claim?.generation !== generation || !claim.actions.has(explicit)))
|
|
93
|
+
return false;
|
|
94
|
+
if (claim?.generation === generation
|
|
95
|
+
&& (!explicit || claim.actions.has(explicit)))
|
|
70
96
|
return true;
|
|
71
97
|
return input !== undefined && this.#router.resolvesLiveFallback(conversation, generation, input);
|
|
72
98
|
}
|
|
@@ -76,7 +102,7 @@ export class RuntimeInteractionCoordinator {
|
|
|
76
102
|
return undefined;
|
|
77
103
|
if (typeof message.$reply !== 'function' || !message.conversation)
|
|
78
104
|
return undefined;
|
|
79
|
-
return this.create(message, subjectId);
|
|
105
|
+
return this.create(message, subjectId, message instanceof RuntimeMessage ? message[interactionOperationScope]() : undefined);
|
|
80
106
|
}
|
|
81
107
|
createFromUnknown(source) {
|
|
82
108
|
if (!source || typeof source !== 'object')
|
|
@@ -84,46 +110,66 @@ export class RuntimeInteractionCoordinator {
|
|
|
84
110
|
const message = source;
|
|
85
111
|
if (typeof message.$reply !== 'function' || !message.conversation)
|
|
86
112
|
return undefined;
|
|
87
|
-
return this.
|
|
113
|
+
return this.createForMessage(message);
|
|
88
114
|
}
|
|
89
|
-
create(source, subjectId) {
|
|
115
|
+
create(source, subjectId, operation) {
|
|
90
116
|
const defaultTimeout = 3 * 60 * 1000;
|
|
91
117
|
const defaultTimeoutText = '输入超时';
|
|
92
|
-
const claim = (timeout, timeoutText, signal) => this.#claimNextMessage(source, timeout, timeoutText, signal, subjectId);
|
|
93
|
-
const reply = async (view) => {
|
|
94
|
-
const receipt = await source.$reply(renderUserInteraction(view));
|
|
95
|
-
if (receipt.status !== 'sent')
|
|
96
|
-
throw new UserInteractionDeliveryError(receipt);
|
|
97
|
-
};
|
|
98
118
|
const ask = async (request, progress) => {
|
|
99
119
|
assertUserInteractionRequest(request);
|
|
120
|
+
const assertLifetime = () => {
|
|
121
|
+
for (const lifetime of [request.signal, operation?.retirementSignal])
|
|
122
|
+
lifetime?.throwIfAborted();
|
|
123
|
+
const host = operation?.snapshot.resources.get(operation.owner)?.get(outboundHostToken.id);
|
|
124
|
+
if (host instanceof PluginOutboundHost && host.owner === operation?.owner
|
|
125
|
+
&& host[generationAdmissionSource].some(gate => !gate.active)) {
|
|
126
|
+
throw new Error('User interaction owner retired');
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
assertLifetime();
|
|
100
130
|
const timeout = request.timeout ?? defaultTimeout;
|
|
101
131
|
const timeoutText = request.timeoutText ?? defaultTimeoutText;
|
|
102
132
|
const deadline = Date.now() + timeout;
|
|
103
133
|
const view = projectUserInteraction(request, progress);
|
|
104
|
-
|
|
134
|
+
let prompt = view;
|
|
105
135
|
while (true) {
|
|
136
|
+
const claim = this.#reserveClaim(source, deadline, timeoutText, request.signal, subjectId, operation, view.actions);
|
|
106
137
|
try {
|
|
107
|
-
|
|
138
|
+
claim.check();
|
|
139
|
+
const actions = [...claim.actions.keys()];
|
|
140
|
+
const receipt = await source.$reply(renderUserInteraction(prompt, (_value, index) => actions[index]));
|
|
141
|
+
assertLifetime();
|
|
142
|
+
if (receipt.status !== 'sent')
|
|
143
|
+
throw new UserInteractionDeliveryError(receipt);
|
|
144
|
+
claim.delivered();
|
|
145
|
+
const raw = await claim.answer;
|
|
146
|
+
claim.check();
|
|
108
147
|
const result = parseUserInteractionAnswer(request, raw);
|
|
109
148
|
if (result.ok)
|
|
110
149
|
return result.value;
|
|
111
|
-
|
|
150
|
+
prompt = {
|
|
112
151
|
...view,
|
|
113
152
|
tip: [request.invalidText ?? result.message, view.tip].filter(Boolean).join('\n'),
|
|
114
|
-
}
|
|
153
|
+
};
|
|
115
154
|
}
|
|
116
155
|
catch (error) {
|
|
156
|
+
claim.reject(error instanceof Error ? error : new Error('User interaction failed'));
|
|
157
|
+
// The timeout may have fired while outbound I/O was still pending.
|
|
158
|
+
// A subsequently retired operation must never apply its default.
|
|
159
|
+
assertLifetime();
|
|
117
160
|
if (error instanceof UserInteractionTimeoutError
|
|
118
161
|
&& 'default' in request
|
|
119
162
|
&& request.default !== undefined) {
|
|
120
163
|
return request.default;
|
|
121
164
|
}
|
|
122
165
|
if (error instanceof UserInteractionTimeoutError) {
|
|
123
|
-
await reply({ title: '交互已结束', description: error.message });
|
|
166
|
+
await source.$reply(renderUserInteraction({ title: '交互已结束', description: error.message }));
|
|
124
167
|
}
|
|
125
168
|
throw error;
|
|
126
169
|
}
|
|
170
|
+
finally {
|
|
171
|
+
claim.dispose();
|
|
172
|
+
}
|
|
127
173
|
}
|
|
128
174
|
};
|
|
129
175
|
const sequence = async (definition) => {
|
|
@@ -162,41 +208,94 @@ export class RuntimeInteractionCoordinator {
|
|
|
162
208
|
};
|
|
163
209
|
return Object.freeze({ ask, sequence });
|
|
164
210
|
}
|
|
165
|
-
#
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
211
|
+
#reserveClaim(source, deadline, timeoutText, signal, subjectId, operation, actions) {
|
|
212
|
+
const key = this.#conversationKey(source, subjectId);
|
|
213
|
+
this.#claims.get(key)?.reject(new UserInteractionSupersededError());
|
|
214
|
+
const id = randomUUID();
|
|
215
|
+
const answers = new Map(actions?.map((action, index) => [`${ASK_ACTION_PREFIX}${id}:${index}`, action.value]));
|
|
216
|
+
let resolve;
|
|
217
|
+
let reject;
|
|
218
|
+
const answer = new Promise((yes, no) => { resolve = yes; reject = no; });
|
|
219
|
+
// Prompt delivery may still be pending when cancellation rejects the claim.
|
|
220
|
+
// Observe that rejection immediately without detaching the actual outbound I/O.
|
|
221
|
+
void answer.catch(() => undefined);
|
|
222
|
+
let failure;
|
|
223
|
+
let delivered = false;
|
|
224
|
+
let buffered;
|
|
225
|
+
const unsubscribers = [];
|
|
226
|
+
const dispose = () => {
|
|
227
|
+
if (this.#claims.get(key) === claim)
|
|
228
|
+
this.#claims.delete(key);
|
|
229
|
+
clearTimeout(timer);
|
|
230
|
+
for (const unsubscribe of unsubscribers.splice(0))
|
|
231
|
+
unsubscribe();
|
|
232
|
+
};
|
|
233
|
+
const fail = (error) => {
|
|
234
|
+
if (failure)
|
|
169
235
|
return;
|
|
236
|
+
failure = error;
|
|
237
|
+
dispose();
|
|
238
|
+
reject(error);
|
|
239
|
+
};
|
|
240
|
+
const timer = setTimeout(() => fail(new UserInteractionTimeoutError(timeoutText)), Math.max(1, deadline - Date.now()));
|
|
241
|
+
const claim = {
|
|
242
|
+
generation: operation?.snapshot.generation ?? source.generation,
|
|
243
|
+
actions: answers,
|
|
244
|
+
answer,
|
|
245
|
+
accept: (raw) => {
|
|
246
|
+
if (failure || buffered !== undefined)
|
|
247
|
+
return false;
|
|
248
|
+
if (Date.now() >= deadline) {
|
|
249
|
+
fail(new UserInteractionTimeoutError(timeoutText));
|
|
250
|
+
return false;
|
|
251
|
+
}
|
|
252
|
+
buffered = raw;
|
|
253
|
+
if (delivered)
|
|
254
|
+
resolve(raw);
|
|
255
|
+
return true;
|
|
256
|
+
},
|
|
257
|
+
delivered: () => { if (!failure) {
|
|
258
|
+
delivered = true;
|
|
259
|
+
if (buffered !== undefined)
|
|
260
|
+
resolve(buffered);
|
|
261
|
+
} },
|
|
262
|
+
reject: fail,
|
|
263
|
+
check: () => {
|
|
264
|
+
if (!failure && Date.now() >= deadline)
|
|
265
|
+
fail(new UserInteractionTimeoutError(timeoutText));
|
|
266
|
+
if (failure)
|
|
267
|
+
throw failure;
|
|
268
|
+
},
|
|
269
|
+
dispose,
|
|
270
|
+
};
|
|
271
|
+
this.#claims.set(key, claim);
|
|
272
|
+
if (deadline <= Date.now())
|
|
273
|
+
fail(new UserInteractionTimeoutError(timeoutText));
|
|
274
|
+
for (const lifetime of [signal, operation?.retirementSignal]) {
|
|
275
|
+
if (!lifetime)
|
|
276
|
+
continue;
|
|
277
|
+
const abort = () => fail(abortError(lifetime, 'User interaction operation retired'));
|
|
278
|
+
if (lifetime.aborted) {
|
|
279
|
+
abort();
|
|
280
|
+
break;
|
|
170
281
|
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
282
|
+
lifetime.addEventListener('abort', abort, { once: true });
|
|
283
|
+
unsubscribers.push(() => lifetime.removeEventListener('abort', abort));
|
|
284
|
+
}
|
|
285
|
+
if (!failure && operation) {
|
|
286
|
+
const host = operation.snapshot.resources.get(operation.owner)?.get(outboundHostToken.id);
|
|
287
|
+
// An inherited parent's facade is not authority for the requesting owner.
|
|
288
|
+
if (host instanceof PluginOutboundHost && host.owner === operation.owner) {
|
|
289
|
+
for (const gate of host[generationAdmissionSource]) {
|
|
290
|
+
const unsubscribe = gate.onDeactivate(() => fail(new Error('User interaction owner retired')));
|
|
291
|
+
if (failure)
|
|
292
|
+
unsubscribe();
|
|
293
|
+
else
|
|
294
|
+
unsubscribers.push(unsubscribe);
|
|
295
|
+
}
|
|
176
296
|
}
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
}, timeout);
|
|
180
|
-
const onAbort = () => settle(undefined, abortError(signal, timeoutText));
|
|
181
|
-
signal?.addEventListener('abort', onAbort, { once: true });
|
|
182
|
-
const settle = (value, error) => {
|
|
183
|
-
if (this.#claims.get(key) !== claim)
|
|
184
|
-
return;
|
|
185
|
-
this.#claims.delete(key);
|
|
186
|
-
clearTimeout(timer);
|
|
187
|
-
signal?.removeEventListener('abort', onAbort);
|
|
188
|
-
if (value !== undefined)
|
|
189
|
-
resolve(value);
|
|
190
|
-
else
|
|
191
|
-
reject(error ?? new UserInteractionTimeoutError(timeoutText));
|
|
192
|
-
};
|
|
193
|
-
const claim = {
|
|
194
|
-
resolve: (raw) => settle(raw),
|
|
195
|
-
reject: (error) => settle(undefined, error),
|
|
196
|
-
timer,
|
|
197
|
-
};
|
|
198
|
-
this.#claims.set(key, claim);
|
|
199
|
-
});
|
|
297
|
+
}
|
|
298
|
+
return claim;
|
|
200
299
|
}
|
|
201
300
|
#conversationKey(source, subjectId = source.sender?.id ?? '') {
|
|
202
301
|
return `${conversationRefKey(source.conversation)}:${subjectId}`;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { ConversationRef, DeliveryReceipt } from '@zhin.js/im-contract';
|
|
2
|
+
import type { RuntimeMessageRendering } from './message-events.js';
|
|
3
|
+
import type { CommandExecutionLimit } from '@zhin.js/command';
|
|
4
|
+
export interface RuntimeMessageDiagnosticStep {
|
|
5
|
+
readonly stage: 'received' | 'origin' | 'prefix' | 'middleware' | 'handlers' | 'dispatch' | 'delivery';
|
|
6
|
+
readonly status: 'accepted' | 'human' | 'member' | 'peer_bot' | 'self' | 'unclassified' | 'matched' | 'mismatch' | 'empty_input' | 'commands_unavailable' | 'started' | 'entered' | 'stopped' | 'replaced' | 'completed' | 'unmatched' | 'invalid' | 'denied' | 'limited' | 'executed' | 'interaction' | 'middleware' | 'command' | 'agent' | 'self_echo' | 'duplicate' | 'bot_origin' | 'dedup_error' | 'sent' | 'failed' | 'unsupported' | 'rejected' | 'suppressed' | 'unknown';
|
|
7
|
+
readonly at: number;
|
|
8
|
+
}
|
|
9
|
+
export interface RuntimeMessageDiagnosticDelivery {
|
|
10
|
+
readonly conversation: ConversationRef;
|
|
11
|
+
readonly status: DeliveryReceipt['status'];
|
|
12
|
+
readonly failureCode?: string;
|
|
13
|
+
readonly deliveryUnknown?: boolean;
|
|
14
|
+
readonly rendering?: RuntimeMessageRendering;
|
|
15
|
+
}
|
|
16
|
+
/** Operational facts only: no message body, sender profile, config, or raw exception. */
|
|
17
|
+
export interface RuntimeMessageDiagnostic {
|
|
18
|
+
readonly id: string;
|
|
19
|
+
readonly generation: number;
|
|
20
|
+
readonly conversation: ConversationRef;
|
|
21
|
+
readonly messageId?: string;
|
|
22
|
+
readonly startedAt: number;
|
|
23
|
+
readonly endedAt?: number;
|
|
24
|
+
readonly status: 'processing' | 'completed' | 'failed';
|
|
25
|
+
readonly route?: 'interaction' | 'middleware' | 'command' | 'agent' | 'unmatched' | 'self_echo' | 'duplicate' | 'bot_origin' | 'dedup_error';
|
|
26
|
+
readonly command?: string;
|
|
27
|
+
readonly dispatchStatus?: 'unmatched' | 'invalid' | 'denied' | 'limited' | 'executed';
|
|
28
|
+
readonly limit?: CommandExecutionLimit;
|
|
29
|
+
/** Some evidence exceeded the per-operation bound; the record is not a complete timeline. */
|
|
30
|
+
readonly truncated: boolean;
|
|
31
|
+
readonly steps: readonly RuntimeMessageDiagnosticStep[];
|
|
32
|
+
readonly deliveries: readonly RuntimeMessageDiagnosticDelivery[];
|
|
33
|
+
}
|
|
34
|
+
export interface RuntimeMessageDiagnosticsReader {
|
|
35
|
+
list(options?: Readonly<{
|
|
36
|
+
limit?: number;
|
|
37
|
+
conversation?: ConversationRef;
|
|
38
|
+
messageId?: string;
|
|
39
|
+
}>): readonly RuntimeMessageDiagnostic[];
|
|
40
|
+
get(id: string): RuntimeMessageDiagnostic | undefined;
|
|
41
|
+
}
|
|
42
|
+
/** One ImRuntime owns this bounded projection; it never retains a Snapshot or publication authority. */
|
|
43
|
+
export declare class RuntimeMessageDiagnostics implements RuntimeMessageDiagnosticsReader {
|
|
44
|
+
#private;
|
|
45
|
+
private readonly options;
|
|
46
|
+
constructor(options?: Readonly<{
|
|
47
|
+
now?: () => number;
|
|
48
|
+
ttlMs?: number;
|
|
49
|
+
capacity?: number;
|
|
50
|
+
}>);
|
|
51
|
+
run<T>(operation: () => Promise<T>): Promise<T>;
|
|
52
|
+
begin(generation: number, conversation: ConversationRef, messageId?: string): void;
|
|
53
|
+
/** Replace provisional bound ingress identity after canonical AdapterIndex resolution. */
|
|
54
|
+
identify(conversation: ConversationRef): void;
|
|
55
|
+
step(stage: RuntimeMessageDiagnosticStep['stage'], status: RuntimeMessageDiagnosticStep['status']): void;
|
|
56
|
+
dispatch(result: Readonly<{
|
|
57
|
+
matched: boolean;
|
|
58
|
+
command?: string;
|
|
59
|
+
status?: RuntimeMessageDiagnostic['dispatchStatus'];
|
|
60
|
+
limit?: CommandExecutionLimit;
|
|
61
|
+
}>): void;
|
|
62
|
+
route(route: NonNullable<RuntimeMessageDiagnostic['route']>): void;
|
|
63
|
+
delivery(generation: number, conversation: ConversationRef, receipt: DeliveryReceipt, rendering?: RuntimeMessageRendering): void;
|
|
64
|
+
list(options?: Readonly<{
|
|
65
|
+
limit?: number;
|
|
66
|
+
conversation?: ConversationRef;
|
|
67
|
+
messageId?: string;
|
|
68
|
+
}>): readonly RuntimeMessageDiagnostic[];
|
|
69
|
+
get(id: string): RuntimeMessageDiagnostic | undefined;
|
|
70
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
const MAX_STEPS = 32;
|
|
4
|
+
const MAX_DELIVERIES = 32;
|
|
5
|
+
/** One ImRuntime owns this bounded projection; it never retains a Snapshot or publication authority. */
|
|
6
|
+
export class RuntimeMessageDiagnostics {
|
|
7
|
+
options;
|
|
8
|
+
#records = new Map();
|
|
9
|
+
#operation = new AsyncLocalStorage();
|
|
10
|
+
constructor(options = {}) {
|
|
11
|
+
this.options = options;
|
|
12
|
+
}
|
|
13
|
+
async run(operation) {
|
|
14
|
+
const scope = { active: true };
|
|
15
|
+
return this.#operation.run(scope, async () => {
|
|
16
|
+
let failed = false;
|
|
17
|
+
try {
|
|
18
|
+
return await operation();
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
failed = true;
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
finally {
|
|
25
|
+
scope.active = false;
|
|
26
|
+
if (scope.record) {
|
|
27
|
+
scope.record.status = failed ? 'failed' : 'completed';
|
|
28
|
+
scope.record.endedAt = this.#now();
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
begin(generation, conversation, messageId) {
|
|
34
|
+
const scope = this.#operation.getStore();
|
|
35
|
+
if (!scope?.active)
|
|
36
|
+
return;
|
|
37
|
+
const identity = boundedConversation(conversation);
|
|
38
|
+
if (!identity || (messageId !== undefined && !boundedIdentifier(messageId)))
|
|
39
|
+
return;
|
|
40
|
+
this.#prune();
|
|
41
|
+
const record = {
|
|
42
|
+
id: randomUUID(), generation, conversation: identity,
|
|
43
|
+
...(messageId ? { messageId } : {}), startedAt: this.#now(), status: 'processing', truncated: false, steps: [], deliveries: [],
|
|
44
|
+
};
|
|
45
|
+
scope.record = record;
|
|
46
|
+
this.#records.set(record.id, record);
|
|
47
|
+
const capacity = this.options.capacity ?? 500;
|
|
48
|
+
while (this.#records.size > capacity)
|
|
49
|
+
this.#records.delete(this.#records.keys().next().value);
|
|
50
|
+
this.step('received', 'accepted');
|
|
51
|
+
}
|
|
52
|
+
/** Replace provisional bound ingress identity after canonical AdapterIndex resolution. */
|
|
53
|
+
identify(conversation) {
|
|
54
|
+
const record = this.#current();
|
|
55
|
+
if (!record)
|
|
56
|
+
return;
|
|
57
|
+
const identity = boundedConversation(conversation);
|
|
58
|
+
if (identity)
|
|
59
|
+
record.conversation = identity;
|
|
60
|
+
else
|
|
61
|
+
record.truncated = true;
|
|
62
|
+
}
|
|
63
|
+
step(stage, status) {
|
|
64
|
+
const record = this.#current();
|
|
65
|
+
if (!record)
|
|
66
|
+
return;
|
|
67
|
+
if (record.steps.length < MAX_STEPS)
|
|
68
|
+
record.steps = [...record.steps, { stage, status, at: this.#now() }];
|
|
69
|
+
else
|
|
70
|
+
record.truncated = true;
|
|
71
|
+
}
|
|
72
|
+
dispatch(result) {
|
|
73
|
+
const record = this.#current();
|
|
74
|
+
if (!record)
|
|
75
|
+
return;
|
|
76
|
+
record.route ??= result.matched ? 'command' : 'unmatched';
|
|
77
|
+
if (result.command)
|
|
78
|
+
record.command = result.command.slice(0, 200);
|
|
79
|
+
if (result.status)
|
|
80
|
+
record.dispatchStatus = result.status;
|
|
81
|
+
if (result.status === 'limited' && result.limit)
|
|
82
|
+
record.limit = Object.freeze({ reason: result.limit.reason,
|
|
83
|
+
...(result.limit.retryAfterMs !== undefined ? { retryAfterMs: result.limit.retryAfterMs } : {}) });
|
|
84
|
+
this.step('dispatch', result.status ?? record.route);
|
|
85
|
+
}
|
|
86
|
+
route(route) {
|
|
87
|
+
const record = this.#current();
|
|
88
|
+
if (record)
|
|
89
|
+
record.route = route;
|
|
90
|
+
}
|
|
91
|
+
delivery(generation, conversation, receipt, rendering) {
|
|
92
|
+
const record = this.#current();
|
|
93
|
+
if (!record || record.generation !== generation)
|
|
94
|
+
return;
|
|
95
|
+
const identity = boundedConversation(conversation);
|
|
96
|
+
if (!identity) {
|
|
97
|
+
record.truncated = true;
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (record.deliveries.length < MAX_DELIVERIES)
|
|
101
|
+
record.deliveries = [...record.deliveries, {
|
|
102
|
+
conversation: identity,
|
|
103
|
+
status: receipt.status,
|
|
104
|
+
...(receipt.failure ? { failureCode: safeCode(receipt.failure.code), deliveryUnknown: receipt.failure.deliveryUnknown === true } : {}),
|
|
105
|
+
...(rendering ? { rendering: { forms: [...rendering.forms], fallbacks: [...rendering.fallbacks] } } : {}),
|
|
106
|
+
}];
|
|
107
|
+
else
|
|
108
|
+
record.truncated = true;
|
|
109
|
+
this.step('delivery', receipt.failure?.deliveryUnknown ? 'unknown' : receipt.status);
|
|
110
|
+
}
|
|
111
|
+
list(options = {}) {
|
|
112
|
+
this.#prune();
|
|
113
|
+
const limit = Number.isSafeInteger(options.limit) ? Math.min(100, Math.max(1, options.limit)) : 50;
|
|
114
|
+
const key = options.conversation ? conversationKey(options.conversation) : undefined;
|
|
115
|
+
return Object.freeze([...this.#records.values()].reverse()
|
|
116
|
+
.filter((record) => key === undefined || conversationKey(record.conversation) === key)
|
|
117
|
+
.filter((record) => options.messageId === undefined || record.messageId === options.messageId)
|
|
118
|
+
.slice(0, limit).map(snapshot));
|
|
119
|
+
}
|
|
120
|
+
get(id) {
|
|
121
|
+
this.#prune();
|
|
122
|
+
const record = this.#records.get(id);
|
|
123
|
+
return record ? snapshot(record) : undefined;
|
|
124
|
+
}
|
|
125
|
+
#current() {
|
|
126
|
+
const scope = this.#operation.getStore();
|
|
127
|
+
return scope?.active ? scope.record : undefined;
|
|
128
|
+
}
|
|
129
|
+
#now() { return (this.options.now ?? Date.now)(); }
|
|
130
|
+
#prune() {
|
|
131
|
+
const threshold = this.#now() - (this.options.ttlMs ?? 15 * 60_000);
|
|
132
|
+
for (const [id, record] of this.#records)
|
|
133
|
+
if ((record.endedAt ?? record.startedAt) < threshold)
|
|
134
|
+
this.#records.delete(id);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
function safeCode(code) {
|
|
138
|
+
return deliveryCodes.has(code) ? code : 'delivery_failed';
|
|
139
|
+
}
|
|
140
|
+
const deliveryCodes = new Set(['outbound_payload_rejected', 'outbound_middleware_failed', 'outbound_delivery_incomplete',
|
|
141
|
+
'delivery_unconfirmed', 'outbound_unsupported', 'platform_rejected', 'endpoint_send_failed', 'endpoint_not_found',
|
|
142
|
+
'endpoint_inactive', 'endpoint_disconnected', 'endpoint_timeout', 'unsupported_operation', 'unsupported_media',
|
|
143
|
+
'invalid_destination', 'invalid_payload', 'invalid_recipient', 'invalid_response', 'invalid_message_id',
|
|
144
|
+
'empty_message', 'http_error', 'media_download_failed', 'partial_delivery', 'session_unavailable',
|
|
145
|
+
'token_unavailable', 'endpoint_identity_mismatch', 'card_context_required', 'card_template_required']);
|
|
146
|
+
function freezeConversation(conversation) {
|
|
147
|
+
return Object.freeze({ endpoint: Object.freeze({ id: conversation.endpoint.id, adapter: conversation.endpoint.adapter }),
|
|
148
|
+
kind: conversation.kind, id: conversation.id,
|
|
149
|
+
...(conversation.parent ? { parent: Object.freeze({ kind: conversation.parent.kind, id: conversation.parent.id }) } : {}),
|
|
150
|
+
...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
function boundedIdentifier(value) {
|
|
154
|
+
return typeof value === 'string' && value.length > 0 && value.length <= 2048;
|
|
155
|
+
}
|
|
156
|
+
function boundedConversation(conversation) {
|
|
157
|
+
try {
|
|
158
|
+
const kind = (value) => value === 'private' || value === 'group' || value === 'channel';
|
|
159
|
+
if (!conversation || !boundedIdentifier(conversation.endpoint?.id) || !boundedIdentifier(conversation.endpoint?.adapter)
|
|
160
|
+
|| !kind(conversation.kind) || !boundedIdentifier(conversation.id)
|
|
161
|
+
|| (conversation.parent !== undefined && (!kind(conversation.parent?.kind) || !boundedIdentifier(conversation.parent?.id)))
|
|
162
|
+
|| (conversation.threadId !== undefined && !boundedIdentifier(conversation.threadId)))
|
|
163
|
+
return undefined;
|
|
164
|
+
const copy = freezeConversation(conversation);
|
|
165
|
+
return JSON.stringify(copy).length <= 8192 ? copy : undefined;
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
return undefined;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function conversationKey(conversation) {
|
|
172
|
+
return JSON.stringify([conversation.endpoint.id, conversation.endpoint.adapter, conversation.kind, conversation.id,
|
|
173
|
+
conversation.parent?.kind, conversation.parent?.id, conversation.threadId]);
|
|
174
|
+
}
|
|
175
|
+
function snapshot(record) {
|
|
176
|
+
return Object.freeze({ ...record, steps: Object.freeze(record.steps.map(step => Object.freeze({ ...step }))),
|
|
177
|
+
deliveries: Object.freeze(record.deliveries.map(delivery => Object.freeze({ ...delivery,
|
|
178
|
+
...(delivery.rendering ? { rendering: Object.freeze({ forms: Object.freeze([...delivery.rendering.forms]),
|
|
179
|
+
fallbacks: Object.freeze([...delivery.rendering.fallbacks]) }) } : {}),
|
|
180
|
+
}))),
|
|
181
|
+
});
|
|
182
|
+
}
|
|
@@ -14,5 +14,5 @@ export declare const defaultCommandPrefixResolver: CommandPrefixResolver;
|
|
|
14
14
|
export declare class MessageDispatcher {
|
|
15
15
|
private readonly resolvePrefix;
|
|
16
16
|
constructor(resolvePrefix?: CommandPrefixResolver);
|
|
17
|
-
dispatch(message: Message, snapshot: RuntimeSnapshot, interactionFactory?: UserInteractionFactory): Promise<MessageDispatchResult>;
|
|
17
|
+
dispatch(message: Message, snapshot: RuntimeSnapshot, interactionFactory?: UserInteractionFactory, observe?: (stage: 'prefix' | 'dispatch', status: 'mismatch' | 'matched' | 'empty_input' | 'commands_unavailable' | 'started') => void): Promise<MessageDispatchResult>;
|
|
18
18
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { adapterFeatureId, isAdapterIndex } from '@zhin.js/adapter';
|
|
2
2
|
import { commandFeatureId, isCommandIndex, } from '@zhin.js/command';
|
|
3
3
|
import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
|
|
4
|
+
import { commandMenuReply } from './command-menu-navigation.js';
|
|
4
5
|
const logger = getLogger('command');
|
|
5
6
|
function ownerOfMessage(message, snapshot) {
|
|
6
7
|
// adapter is a platform literal (e.g. terminal), not the Plugin owner.
|
|
@@ -42,23 +43,36 @@ export class MessageDispatcher {
|
|
|
42
43
|
constructor(resolvePrefix = defaultCommandPrefixResolver) {
|
|
43
44
|
this.resolvePrefix = resolvePrefix;
|
|
44
45
|
}
|
|
45
|
-
async dispatch(message, snapshot, interactionFactory) {
|
|
46
|
+
async dispatch(message, snapshot, interactionFactory, observe) {
|
|
47
|
+
const note = (stage, status) => {
|
|
48
|
+
try {
|
|
49
|
+
observe?.(stage, status);
|
|
50
|
+
}
|
|
51
|
+
catch { /* Observation never controls dispatch. */ }
|
|
52
|
+
};
|
|
46
53
|
const prefix = this.resolvePrefix(message, snapshot);
|
|
47
54
|
let input = message.content.trim();
|
|
48
55
|
if (prefix && !input.startsWith(prefix)) {
|
|
56
|
+
note('prefix', 'mismatch');
|
|
49
57
|
return Object.freeze({ matched: false });
|
|
50
58
|
}
|
|
59
|
+
note('prefix', 'matched');
|
|
51
60
|
if (prefix)
|
|
52
61
|
input = input.slice(prefix.length).trim();
|
|
53
|
-
if (!input)
|
|
62
|
+
if (!input) {
|
|
63
|
+
note('dispatch', 'empty_input');
|
|
54
64
|
return Object.freeze({ matched: false });
|
|
65
|
+
}
|
|
55
66
|
const commands = snapshot.projections.get(commandFeatureId);
|
|
56
|
-
if (!isCommandIndex(commands))
|
|
67
|
+
if (!isCommandIndex(commands)) {
|
|
68
|
+
note('dispatch', 'commands_unavailable');
|
|
57
69
|
return Object.freeze({ matched: false });
|
|
70
|
+
}
|
|
58
71
|
const structuredInput = message.segments
|
|
59
72
|
? stripCommandPrefix(message.segments, prefix)
|
|
60
73
|
: undefined;
|
|
61
74
|
const matchInput = structuredInput ?? input;
|
|
75
|
+
note('dispatch', 'started');
|
|
62
76
|
const result = await commands.dispatch(matchInput, message, interactionFactory, prefix, snapshot);
|
|
63
77
|
if (result.status === 'invalid') {
|
|
64
78
|
return Object.freeze({
|
|
@@ -70,6 +84,17 @@ export class MessageDispatcher {
|
|
|
70
84
|
if (result.status === 'denied') {
|
|
71
85
|
return Object.freeze({ ...result, value: '没有权限执行此指令。' });
|
|
72
86
|
}
|
|
87
|
+
if (result.status === 'limited') {
|
|
88
|
+
const reason = result.limit?.reason;
|
|
89
|
+
const waitMs = result.limit?.retryAfterMs;
|
|
90
|
+
const value = reason === 'cooldown'
|
|
91
|
+
? typeof waitMs === 'number' && waitMs > 0
|
|
92
|
+
? `此指令仍在冷却,约 ${Math.ceil(waitMs / 1000)} 秒后再试。` : '此指令仍在冷却,请稍后再试。'
|
|
93
|
+
: reason === 'busy' ? '你的上一条同类指令仍在处理中,请等待执行完成,避免重复触发。'
|
|
94
|
+
: reason === 'capacity' ? '当前繁忙,本次指令未被接纳,请稍后再试。'
|
|
95
|
+
: '当前缺少可信身份或有效执行上下文,本次指令未被接纳。请管理员检查适配器及当前运行状态。';
|
|
96
|
+
return Object.freeze({ ...result, value });
|
|
97
|
+
}
|
|
73
98
|
if (result.matched && result.value !== undefined) {
|
|
74
99
|
if (!result.owner)
|
|
75
100
|
throw new Error('Matched Command is missing its owner');
|
|
@@ -85,23 +110,34 @@ export class MessageDispatcher {
|
|
|
85
110
|
preview: truncatePreview(input),
|
|
86
111
|
}));
|
|
87
112
|
}
|
|
88
|
-
return result
|
|
113
|
+
return result.menu ? Object.freeze({ ...result,
|
|
114
|
+
value: commandMenuReply(result, commands, snapshot, message.conversation, prefix),
|
|
115
|
+
}) : result;
|
|
89
116
|
}
|
|
90
117
|
}
|
|
91
118
|
/**
|
|
92
119
|
* Keep the text and structured views aligned. Falling back to `content` is
|
|
93
120
|
* intentional when an adapter supplies inconsistent segment data.
|
|
121
|
+
*
|
|
122
|
+
* Platforms put a quote (`reply`) segment before the text ("quote a message, then type the
|
|
123
|
+
* command"). Leading quotes are moved after the command text so the command name still
|
|
124
|
+
* matches and a `reply` parameter can still read the quote; `message.replyTo` is untouched.
|
|
94
125
|
*/
|
|
95
126
|
function stripCommandPrefix(segments, prefix) {
|
|
96
127
|
let pendingPrefix = prefix;
|
|
97
128
|
let atStart = true;
|
|
98
129
|
let trimLeading = true;
|
|
99
130
|
const result = [];
|
|
131
|
+
const leadingQuotes = [];
|
|
100
132
|
for (const segment of segments) {
|
|
101
133
|
if (!atStart) {
|
|
102
134
|
result.push(segment);
|
|
103
135
|
continue;
|
|
104
136
|
}
|
|
137
|
+
if (segment.type === 'reply') {
|
|
138
|
+
leadingQuotes.push(segment);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
105
141
|
if (segment.type !== 'text' || typeof segment.data.text !== 'string') {
|
|
106
142
|
if (pendingPrefix)
|
|
107
143
|
return undefined;
|
|
@@ -136,5 +172,5 @@ function stripCommandPrefix(segments, prefix) {
|
|
|
136
172
|
atStart = false;
|
|
137
173
|
result.push({ ...segment, data: { ...segment.data, text } });
|
|
138
174
|
}
|
|
139
|
-
return pendingPrefix ? undefined : result;
|
|
175
|
+
return pendingPrefix ? undefined : [...result, ...leadingQuotes];
|
|
140
176
|
}
|
|
@@ -4,7 +4,9 @@ import { type SendRequest } from './contracts.js';
|
|
|
4
4
|
import { OutboundRenderer } from './outbound-renderer.js';
|
|
5
5
|
import { type RuntimeMessageEvent } from './message-events.js';
|
|
6
6
|
import { type JsxButtonBatch } from './jsx-button-registry.js';
|
|
7
|
+
import type { RuntimeMessageDiagnostics } from './message-diagnostics.js';
|
|
7
8
|
interface OutboundDeliveryContext {
|
|
9
|
+
readonly diagnostics?: RuntimeMessageDiagnostics;
|
|
8
10
|
prepareButtons?(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
|
|
9
11
|
record(request: SendRequest, receipt: DeliveryReceipt): Promise<void>;
|
|
10
12
|
/** Side-channel correlation ledger for inbound origin; failures never affect the receipt. */
|