@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,6 +1,7 @@
|
|
|
1
1
|
import { createToken, generationAdmissionBinder, } from '@zhin.js/plugin-runtime';
|
|
2
2
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
3
|
import { PermissionHost, permissionHostToken } from '@zhin.js/permission';
|
|
4
|
+
import { CommandExecutionBudget, commandExecutionAdmissionToken } from '@zhin.js/command/internal/execution';
|
|
4
5
|
import { MessageBus, messageBusToken } from './message-bus.js';
|
|
5
6
|
import { endpointEventGatewayToken, getProcessPeerRegistry, } from '@zhin.js/adapter';
|
|
6
7
|
import { loginAssistToken } from './login-assist-host.js';
|
|
@@ -14,9 +15,17 @@ import { InboundRuntime } from './inbound-runtime.js';
|
|
|
14
15
|
import { InboundDeduper } from './inbound-dedup.js';
|
|
15
16
|
import { OutboundLedger, ledgerScopeOf } from './outbound-ledger.js';
|
|
16
17
|
import { createInboundOriginClassifier } from './inbound-origin.js';
|
|
18
|
+
import { RuntimeMessageDiagnostics } from './message-diagnostics.js';
|
|
17
19
|
/** @public Stable inbound and outbound IM gateway token for Adapter integrations. */
|
|
18
20
|
export const outboundMessageToken = createToken('zhin.im.outbound-message');
|
|
19
21
|
export class ImRuntime {
|
|
22
|
+
#commandExecution = new CommandExecutionBudget();
|
|
23
|
+
#commandOperation = new AsyncLocalStorage();
|
|
24
|
+
#messageDiagnostics = new RuntimeMessageDiagnostics();
|
|
25
|
+
messageDiagnostics = Object.freeze({
|
|
26
|
+
list: (options) => this.#messageDiagnostics.list(options),
|
|
27
|
+
get: (id) => this.#messageDiagnostics.get(id),
|
|
28
|
+
});
|
|
20
29
|
#messageEventStream = new RuntimeMessageEventStream();
|
|
21
30
|
messageEvents = Object.freeze({
|
|
22
31
|
subscribe: (listener) => this.#messageEventStream.subscribe(listener),
|
|
@@ -38,6 +47,7 @@ export class ImRuntime {
|
|
|
38
47
|
ledger,
|
|
39
48
|
});
|
|
40
49
|
this.#outbound = new OutboundDeliveryRuntime({
|
|
50
|
+
diagnostics: this.#messageDiagnostics,
|
|
41
51
|
ledger: (conversation, receipt, payload) => ledger.record(conversation, receipt, payload),
|
|
42
52
|
record: (request, receipt) => this.#conversations.recordOutbound(request, receipt),
|
|
43
53
|
rememberFallback: (conversation, generation, map) => this.#interactions.rememberFallback(conversation, generation, map),
|
|
@@ -45,6 +55,9 @@ export class ImRuntime {
|
|
|
45
55
|
prepareButtons: (request, snapshot) => this.#interactions.prepareButtons(request, snapshot),
|
|
46
56
|
}, options.renderer);
|
|
47
57
|
this.#inbound = new InboundRuntime({
|
|
58
|
+
commandExecution: this.#commandExecution,
|
|
59
|
+
runCommandOperation: (controller, operation) => this.#commandOperation.run(controller, operation),
|
|
60
|
+
diagnostics: this.#messageDiagnostics,
|
|
48
61
|
interactions: this.#interactions,
|
|
49
62
|
inboundClaim: options.inboundClaim,
|
|
50
63
|
originClassifier,
|
|
@@ -55,7 +68,7 @@ export class ImRuntime {
|
|
|
55
68
|
enrichSender: options.enrichSender,
|
|
56
69
|
acquire: () => this.#acquire(),
|
|
57
70
|
release: (lease) => this.#release(lease),
|
|
58
|
-
deliver: (request, snapshot) => this.#
|
|
71
|
+
deliver: (request, snapshot) => this.#deliver(request, snapshot),
|
|
59
72
|
recordIncoming: (input, sender) => this.#conversations.recordIncoming(input, sender),
|
|
60
73
|
recordNotice: (notice) => this.#conversations.recordNotice(notice),
|
|
61
74
|
markInteractionAnswer: (message) => this.#conversations.markInteractionAnswer(message),
|
|
@@ -64,7 +77,7 @@ export class ImRuntime {
|
|
|
64
77
|
this.endpoints = new EndpointRuntime({
|
|
65
78
|
acquire: () => this.#acquire(),
|
|
66
79
|
release: (lease) => this.#release(lease),
|
|
67
|
-
send: (request, snapshot) => this.#
|
|
80
|
+
send: (request, snapshot) => this.#deliver(request, snapshot),
|
|
68
81
|
});
|
|
69
82
|
}
|
|
70
83
|
/** Process composition replaces the bootstrap memory store after required DB activation. */
|
|
@@ -120,6 +133,7 @@ export class ImRuntime {
|
|
|
120
133
|
resources.provide(endpointEventGatewayToken, this.endpointEvents);
|
|
121
134
|
resources.provide(loginAssistToken, this.loginAssist);
|
|
122
135
|
resources.provide(permissionHostToken, this.permissionHost);
|
|
136
|
+
resources.provide(commandExecutionAdmissionToken, this.#commandExecution.admission);
|
|
123
137
|
resources.provide(messageBusToken, this.messageBus);
|
|
124
138
|
}
|
|
125
139
|
/** The sole Adapter ingress, also installed as endpointEventGatewayToken. */
|
|
@@ -160,7 +174,7 @@ export class ImRuntime {
|
|
|
160
174
|
async send(request) {
|
|
161
175
|
const lease = this.#acquire();
|
|
162
176
|
try {
|
|
163
|
-
return await this.#
|
|
177
|
+
return await this.#deliver(request, lease.value);
|
|
164
178
|
}
|
|
165
179
|
finally {
|
|
166
180
|
this.#release(lease);
|
|
@@ -171,7 +185,7 @@ export class ImRuntime {
|
|
|
171
185
|
if (!this.#snapshots?.owns(lease) || !lease.active) {
|
|
172
186
|
throw new Error('Outbound message generation lease expired');
|
|
173
187
|
}
|
|
174
|
-
return this.#
|
|
188
|
+
return this.#deliver(request, lease.value);
|
|
175
189
|
}
|
|
176
190
|
/**
|
|
177
191
|
* Console `GET /api/stats` 同源计数:非 root 插件节点 + AdapterIndex endpoints。
|
|
@@ -203,6 +217,12 @@ export class ImRuntime {
|
|
|
203
217
|
});
|
|
204
218
|
}
|
|
205
219
|
}
|
|
220
|
+
/** All unified outbound entry points observe the actual delivery, never their own caller/drain promise. */
|
|
221
|
+
#deliver(request, snapshot) {
|
|
222
|
+
const delivery = this.#outbound.deliver(request, snapshot);
|
|
223
|
+
this.#commandOperation.getStore()?.trackSend(delivery);
|
|
224
|
+
return delivery;
|
|
225
|
+
}
|
|
206
226
|
#acquire() {
|
|
207
227
|
const inherited = this.#operationSnapshot.getStore();
|
|
208
228
|
if (inherited?.active)
|
|
@@ -2,14 +2,19 @@ import type { GenerationAdmissionGate, RuntimeSnapshot, SnapshotLease } from '@z
|
|
|
2
2
|
import type { EndpointEvent, PeerRegistry } from '@zhin.js/adapter';
|
|
3
3
|
import type { DeliveryReceipt } from '@zhin.js/im-contract';
|
|
4
4
|
import type { UserInteraction } from '@zhin.js/interaction';
|
|
5
|
+
import type { CommandExecutionBudget, CommandOperationController } from '@zhin.js/command/internal/execution';
|
|
5
6
|
import { type Notice } from '../../notice.js';
|
|
6
7
|
import { type Message, type IncomingMessage, type MessageSenderRef, type SendRequest } from './contracts.js';
|
|
8
|
+
import type { RuntimeMessageDiagnostics } from './message-diagnostics.js';
|
|
7
9
|
import type { RuntimeInteractionCoordinator } from './interaction-runtime.js';
|
|
8
10
|
import { type RuntimeMessageEvent } from './message-events.js';
|
|
9
11
|
import type { InboundDeduper } from './inbound-dedup.js';
|
|
10
12
|
import { type InboundOriginClassifier } from './inbound-origin.js';
|
|
11
13
|
type InboundInteractionPort = Pick<RuntimeInteractionCoordinator<GenerationAdmissionGate>, 'create' | 'createForMessage' | 'createFromUnknown' | 'dispatch' | 'resolveClaim'> & Partial<Pick<RuntimeInteractionCoordinator<GenerationAdmissionGate>, 'hasPendingAnswer'>>;
|
|
12
14
|
interface InboundRuntimeContext {
|
|
15
|
+
readonly commandExecution?: CommandExecutionBudget;
|
|
16
|
+
runCommandOperation?<T>(controller: CommandOperationController, operation: () => T): T;
|
|
17
|
+
readonly diagnostics?: RuntimeMessageDiagnostics;
|
|
13
18
|
readonly interactions: InboundInteractionPort;
|
|
14
19
|
readonly inboundClaim?: (message: Message) => boolean | Promise<boolean>;
|
|
15
20
|
/** Trusted origin classifier. Absent: messages carry no origin (legacy behavior). */
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { isMiddlewareIndex, middlewareFeatureId } from '@zhin.js/middleware';
|
|
2
2
|
import { isHandlerIndex, handlerFeatureId } from '../../feature/handler.js';
|
|
3
|
+
import { bindOperationInput } from '@zhin.js/feature-kit';
|
|
3
4
|
import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
|
|
4
5
|
import { RuntimeNotice } from '../../notice.js';
|
|
5
6
|
import { RuntimeRequest } from '../../request.js';
|
|
@@ -29,7 +30,9 @@ export class InboundRuntime {
|
|
|
29
30
|
async receive(event, admission) {
|
|
30
31
|
switch (event.name) {
|
|
31
32
|
case 'message.receive':
|
|
32
|
-
return this
|
|
33
|
+
return this.context.diagnostics
|
|
34
|
+
? this.context.diagnostics.run(() => this.#receiveMessage(event, admission))
|
|
35
|
+
: this.#receiveMessage(event, admission);
|
|
33
36
|
case 'notice.receive':
|
|
34
37
|
return this.#receiveCanonicalEndpointEvent(event);
|
|
35
38
|
case 'request.receive':
|
|
@@ -75,8 +78,13 @@ export class InboundRuntime {
|
|
|
75
78
|
const receivedAt = Date.now();
|
|
76
79
|
const lease = this.context.acquire();
|
|
77
80
|
let active = true;
|
|
81
|
+
let commandOperation;
|
|
78
82
|
try {
|
|
79
83
|
const adapter = source.endpoint.id;
|
|
84
|
+
this.context.diagnostics?.begin(lease.value.generation, {
|
|
85
|
+
...source.payload.conversation,
|
|
86
|
+
endpoint: { id: source.endpoint.id, adapter: source.endpoint.adapter },
|
|
87
|
+
}, source.payload.message?.id);
|
|
80
88
|
const adapters = requireAdapters(lease.value);
|
|
81
89
|
const requester = adapters.owner(adapter);
|
|
82
90
|
// Routing identity belongs to the bound Endpoint, never to a protocol
|
|
@@ -87,6 +95,7 @@ export class InboundRuntime {
|
|
|
87
95
|
const input = Object.freeze({ ...source.payload, conversation,
|
|
88
96
|
...(source.payload.message ? { message: Object.freeze({ ...source.payload.message, conversation }) } : {}),
|
|
89
97
|
});
|
|
98
|
+
this.context.diagnostics?.identify(conversation);
|
|
90
99
|
logger.debug(formatCompact({
|
|
91
100
|
op: 'receive',
|
|
92
101
|
conv: formatConversationLog(conversation),
|
|
@@ -106,7 +115,9 @@ export class InboundRuntime {
|
|
|
106
115
|
content: input.content,
|
|
107
116
|
}, roomMembership);
|
|
108
117
|
const origin = classified?.origin;
|
|
118
|
+
this.context.diagnostics?.step('origin', origin ?? 'unclassified');
|
|
109
119
|
if (origin === 'self') {
|
|
120
|
+
this.context.diagnostics?.route('self_echo');
|
|
110
121
|
logger.debug(formatCompact({
|
|
111
122
|
op: 'self_echo',
|
|
112
123
|
conv: formatConversationLog(conversation),
|
|
@@ -220,13 +231,13 @@ export class InboundRuntime {
|
|
|
220
231
|
}
|
|
221
232
|
}
|
|
222
233
|
const mentioned = routedTarget ? true : input.mentioned;
|
|
223
|
-
const
|
|
234
|
+
const operationReply = (content, replyRequester = requester, targetConversation) => {
|
|
224
235
|
if (!active)
|
|
225
236
|
throw new Error('Message reply scope has ended');
|
|
226
237
|
const effectiveConversation = targetConversation
|
|
227
238
|
? { ...targetConversation, endpoint: conversation.endpoint }
|
|
228
239
|
: conversation;
|
|
229
|
-
|
|
240
|
+
const deliver = () => this.context.deliver({
|
|
230
241
|
conversation: effectiveConversation,
|
|
231
242
|
requester: replyRequester,
|
|
232
243
|
content,
|
|
@@ -240,48 +251,167 @@ export class InboundRuntime {
|
|
|
240
251
|
mentioned,
|
|
241
252
|
},
|
|
242
253
|
}, lease.value);
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
}
|
|
254
|
+
// A held Message may reply from another async caller while its operation is
|
|
255
|
+
// draining. Restore that Message's private controller, not the caller's scope.
|
|
256
|
+
return commandOperation && this.context.runCommandOperation
|
|
257
|
+
? this.context.runCommandOperation(commandOperation, deliver) : deliver();
|
|
258
|
+
};
|
|
259
|
+
commandOperation = this.context.commandExecution?.openOperation({
|
|
260
|
+
snapshot: lease.value, conversation, senderId: enrichedSender?.id,
|
|
261
|
+
retirementSignal: lease.retirementSignal, reply: (owner, text) => operationReply(text, owner),
|
|
262
|
+
});
|
|
263
|
+
const execute = async () => {
|
|
264
|
+
const message = new RuntimeMessage(conversation, input.content, lease.value.generation, operationReply, enrichedSender, Object.freeze({ ...input.metadata }), input.segments ? Object.freeze([...input.segments]) : undefined, input.message, input.endpointId, mentioned, input.replyTo, () => {
|
|
248
265
|
if (!active)
|
|
249
|
-
throw new Error('Message
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
266
|
+
throw new Error('Message Client scope has ended');
|
|
267
|
+
return source.client;
|
|
268
|
+
}, source.endpoint.adapter, { snapshot: lease.value, retirementSignal: lease.retirementSignal, registerOperationView: commandOperation?.bind, assertActive: () => {
|
|
269
|
+
if (!active)
|
|
270
|
+
throw new Error('Message author binding scope has ended');
|
|
271
|
+
}, ...(origin ? { origin } : {}) });
|
|
272
|
+
const conversationSequence = await this.context.recordIncoming(input, enrichedSender);
|
|
273
|
+
let result = Object.freeze({ matched: false });
|
|
274
|
+
let reply;
|
|
275
|
+
if (recordOnly === 'duplicate') {
|
|
276
|
+
this.context.diagnostics?.route('duplicate');
|
|
277
|
+
// Duplicate of a message already routed via another Endpoint: history only,
|
|
278
|
+
// no publish (avoids N copies in the console message feed).
|
|
279
|
+
logger.debug(formatCompact({
|
|
280
|
+
op: 'inbound_duplicate',
|
|
281
|
+
conv: formatConversationLog(conversation),
|
|
282
|
+
basis: recordOnly,
|
|
283
|
+
}));
|
|
284
|
+
return result;
|
|
285
|
+
}
|
|
286
|
+
if (recordOnly === 'dedup_error') {
|
|
287
|
+
this.context.diagnostics?.route('dedup_error');
|
|
288
|
+
// Undecidable: record only and never route (no duplicate routing), but publish so
|
|
289
|
+
// the console feed still shows the message and a persistent failure is visible.
|
|
290
|
+
this.context.publish({
|
|
291
|
+
direction: 'inbound',
|
|
292
|
+
conversation,
|
|
293
|
+
...(input.sender !== undefined ? { sender: input.sender } : {}),
|
|
294
|
+
contentPreview: previewMessageContent(input.content),
|
|
295
|
+
...(input.message?.id ? { messageId: input.message.id } : {}),
|
|
296
|
+
timestamp: receivedAt,
|
|
297
|
+
});
|
|
298
|
+
return result;
|
|
299
|
+
}
|
|
300
|
+
if (origin === 'member' || origin === 'peer_bot') {
|
|
301
|
+
this.context.diagnostics?.route('bot_origin');
|
|
302
|
+
// Bot-origin messages are recorded as chat history only: no claim, handlers,
|
|
303
|
+
// commands, middleware or ingress route (prevents bot-to-bot loops).
|
|
304
|
+
logger.debug(formatCompact({
|
|
305
|
+
op: 'bot_origin_recorded',
|
|
306
|
+
conv: formatConversationLog(conversation),
|
|
307
|
+
origin,
|
|
308
|
+
basis: classified?.basis,
|
|
309
|
+
}));
|
|
310
|
+
this.context.publish({
|
|
311
|
+
direction: 'inbound',
|
|
312
|
+
conversation,
|
|
313
|
+
...(input.sender !== undefined ? { sender: input.sender } : {}),
|
|
314
|
+
contentPreview: previewMessageContent(input.content),
|
|
315
|
+
...(input.message?.id ? { messageId: input.message.id } : {}),
|
|
316
|
+
timestamp: receivedAt,
|
|
317
|
+
});
|
|
318
|
+
return result;
|
|
319
|
+
}
|
|
320
|
+
const claimed = await this.context.inboundClaim?.(message) === true;
|
|
321
|
+
if (claimed) {
|
|
322
|
+
this.context.diagnostics?.route('interaction');
|
|
323
|
+
result = interactionResult(requester);
|
|
324
|
+
}
|
|
325
|
+
else if (this.context.interactions.resolveClaim(message)) {
|
|
326
|
+
this.context.diagnostics?.route('interaction');
|
|
327
|
+
if (input.message)
|
|
328
|
+
this.context.markInteractionAnswer?.(input.message);
|
|
329
|
+
result = interactionResult(requester);
|
|
330
|
+
}
|
|
331
|
+
else {
|
|
332
|
+
const interactionFactory = (value) => this.context.interactions.createFromUnknown(value);
|
|
333
|
+
const terminal = async () => {
|
|
334
|
+
const ingressRoute = resolveIngressRoute(lease.value);
|
|
335
|
+
const preRouted = await ingressRoute?.preRoute?.(message, lease, requester, conversationSequence) === true;
|
|
336
|
+
if (preRouted) {
|
|
337
|
+
this.context.diagnostics?.route('agent');
|
|
338
|
+
result = Object.freeze({ matched: true, command: 'pre-route', owner: requester });
|
|
339
|
+
return { dispatch: result };
|
|
340
|
+
}
|
|
341
|
+
if (ingressRoute?.shouldRouteBeforeDispatch?.(message) === true) {
|
|
342
|
+
const handled = await ingressRoute.route(message, lease, requester, conversationSequence);
|
|
343
|
+
if (handled) {
|
|
344
|
+
this.context.diagnostics?.route('agent');
|
|
345
|
+
result = Object.freeze({ matched: true, command: 'ai', owner: requester });
|
|
346
|
+
return { dispatch: result };
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
this.context.diagnostics?.step('handlers', 'started');
|
|
350
|
+
await this.#runHandlers(lease, 'message.receive', [
|
|
351
|
+
withEndpointEventPayload(source, message),
|
|
352
|
+
]);
|
|
353
|
+
this.context.diagnostics?.step('handlers', 'completed');
|
|
354
|
+
const interactive = await this.#dispatchInteractive(message, requester, admission, lease.value);
|
|
355
|
+
if (interactive)
|
|
356
|
+
this.context.diagnostics?.route('interaction');
|
|
357
|
+
result = interactive ?? await this.#dispatcher.dispatch(message, lease.value, interactionFactory, (stage, status) => this.context.diagnostics?.step(stage, status));
|
|
358
|
+
if (!result.matched && ingressRoute) {
|
|
359
|
+
logger.debug(formatCompact({
|
|
360
|
+
op: 'unmatched',
|
|
361
|
+
conv: formatConversationLog(conversation),
|
|
362
|
+
}));
|
|
363
|
+
const handled = await ingressRoute.route(message, lease, requester, conversationSequence);
|
|
364
|
+
if (handled) {
|
|
365
|
+
this.context.diagnostics?.route('agent');
|
|
366
|
+
result = Object.freeze({ matched: true, command: 'ai', owner: requester });
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
return {
|
|
370
|
+
dispatch: result,
|
|
371
|
+
...(result.value !== undefined && result.owner
|
|
372
|
+
? { reply: { owner: result.owner, content: result.value } }
|
|
373
|
+
: {}),
|
|
374
|
+
};
|
|
375
|
+
};
|
|
376
|
+
const middleware = lease.value.projections.get(middlewareFeatureId);
|
|
377
|
+
if (isMiddlewareIndex(middleware))
|
|
378
|
+
this.context.diagnostics?.step('middleware', 'entered');
|
|
379
|
+
const outcome = isMiddlewareIndex(middleware)
|
|
380
|
+
? await middleware.runInbound(message, terminal, {
|
|
381
|
+
stop: (owner) => {
|
|
382
|
+
this.context.diagnostics?.route('middleware');
|
|
383
|
+
this.context.diagnostics?.step('middleware', 'stopped');
|
|
384
|
+
return { dispatch: { matched: true, command: 'middleware', owner } };
|
|
385
|
+
},
|
|
386
|
+
replace: (owner, value, downstream) => {
|
|
387
|
+
this.context.diagnostics?.step('middleware', 'replaced');
|
|
388
|
+
if (!downstream?.dispatch.matched)
|
|
389
|
+
this.context.diagnostics?.route('middleware');
|
|
390
|
+
return {
|
|
391
|
+
dispatch: downstream?.dispatch.matched
|
|
392
|
+
? downstream.dispatch
|
|
393
|
+
: { matched: true, command: 'middleware', owner },
|
|
394
|
+
reply: { owner, content: value },
|
|
395
|
+
};
|
|
396
|
+
},
|
|
397
|
+
}, lease.value)
|
|
398
|
+
: await terminal();
|
|
399
|
+
result = outcome.dispatch;
|
|
400
|
+
if (isMiddlewareIndex(middleware))
|
|
401
|
+
this.context.diagnostics?.step('middleware', 'completed');
|
|
402
|
+
reply = outcome.reply;
|
|
403
|
+
}
|
|
404
|
+
this.context.diagnostics?.dispatch(result);
|
|
405
|
+
await commandOperation?.stopProgress();
|
|
406
|
+
if (reply)
|
|
407
|
+
await message.$replyFrom(reply.owner, reply.content);
|
|
408
|
+
if (result.matched) {
|
|
409
|
+
logger.debug(formatCompact({
|
|
410
|
+
op: 'dispatched',
|
|
411
|
+
conv: formatConversationLog(conversation),
|
|
412
|
+
command: result.command,
|
|
413
|
+
}));
|
|
414
|
+
}
|
|
285
415
|
this.context.publish({
|
|
286
416
|
direction: 'inbound',
|
|
287
417
|
conversation,
|
|
@@ -291,90 +421,18 @@ export class InboundRuntime {
|
|
|
291
421
|
timestamp: receivedAt,
|
|
292
422
|
});
|
|
293
423
|
return result;
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
result = interactionResult(requester);
|
|
298
|
-
}
|
|
299
|
-
else if (this.context.interactions.resolveClaim(message)) {
|
|
300
|
-
if (input.message)
|
|
301
|
-
this.context.markInteractionAnswer?.(input.message);
|
|
302
|
-
result = interactionResult(requester);
|
|
303
|
-
}
|
|
304
|
-
else {
|
|
305
|
-
const interactionFactory = (value) => this.context.interactions.createFromUnknown(value);
|
|
306
|
-
const terminal = async () => {
|
|
307
|
-
const ingressRoute = resolveIngressRoute(lease.value);
|
|
308
|
-
const preRouted = await ingressRoute?.preRoute?.(message, lease, requester, conversationSequence) === true;
|
|
309
|
-
if (preRouted) {
|
|
310
|
-
result = Object.freeze({ matched: true, command: 'pre-route', owner: requester });
|
|
311
|
-
return { dispatch: result };
|
|
312
|
-
}
|
|
313
|
-
if (ingressRoute?.shouldRouteBeforeDispatch?.(message) === true) {
|
|
314
|
-
const handled = await ingressRoute.route(message, lease, requester, conversationSequence);
|
|
315
|
-
if (handled) {
|
|
316
|
-
result = Object.freeze({ matched: true, command: 'ai', owner: requester });
|
|
317
|
-
return { dispatch: result };
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
await this.#runHandlers(lease.value, 'message.receive', [
|
|
321
|
-
withEndpointEventPayload(source, message),
|
|
322
|
-
]);
|
|
323
|
-
result = await this.#dispatchInteractive(message, requester, admission, lease.value)
|
|
324
|
-
?? await this.#dispatcher.dispatch(message, lease.value, interactionFactory);
|
|
325
|
-
if (!result.matched && ingressRoute) {
|
|
326
|
-
logger.debug(formatCompact({
|
|
327
|
-
op: 'unmatched',
|
|
328
|
-
conv: formatConversationLog(conversation),
|
|
329
|
-
}));
|
|
330
|
-
const handled = await ingressRoute.route(message, lease, requester, conversationSequence);
|
|
331
|
-
if (handled) {
|
|
332
|
-
result = Object.freeze({ matched: true, command: 'ai', owner: requester });
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
return {
|
|
336
|
-
dispatch: result,
|
|
337
|
-
...(result.value !== undefined && result.owner
|
|
338
|
-
? { reply: { owner: result.owner, content: result.value } }
|
|
339
|
-
: {}),
|
|
340
|
-
};
|
|
341
|
-
};
|
|
342
|
-
const middleware = lease.value.projections.get(middlewareFeatureId);
|
|
343
|
-
const outcome = isMiddlewareIndex(middleware)
|
|
344
|
-
? await middleware.runInbound(message, terminal, {
|
|
345
|
-
stop: (owner) => ({ dispatch: { matched: true, command: 'middleware', owner } }),
|
|
346
|
-
replace: (owner, value, downstream) => ({
|
|
347
|
-
dispatch: downstream?.dispatch.matched
|
|
348
|
-
? downstream.dispatch
|
|
349
|
-
: { matched: true, command: 'middleware', owner },
|
|
350
|
-
reply: { owner, content: value },
|
|
351
|
-
}),
|
|
352
|
-
}, lease.value)
|
|
353
|
-
: await terminal();
|
|
354
|
-
result = outcome.dispatch;
|
|
355
|
-
if (outcome.reply)
|
|
356
|
-
await message.$replyFrom(outcome.reply.owner, outcome.reply.content);
|
|
357
|
-
}
|
|
358
|
-
if (result.matched) {
|
|
359
|
-
logger.debug(formatCompact({
|
|
360
|
-
op: 'dispatched',
|
|
361
|
-
conv: formatConversationLog(conversation),
|
|
362
|
-
command: result.command,
|
|
363
|
-
}));
|
|
364
|
-
}
|
|
365
|
-
this.context.publish({
|
|
366
|
-
direction: 'inbound',
|
|
367
|
-
conversation,
|
|
368
|
-
...(input.sender !== undefined ? { sender: input.sender } : {}),
|
|
369
|
-
contentPreview: previewMessageContent(input.content),
|
|
370
|
-
...(input.message?.id ? { messageId: input.message.id } : {}),
|
|
371
|
-
timestamp: receivedAt,
|
|
372
|
-
});
|
|
373
|
-
return result;
|
|
424
|
+
};
|
|
425
|
+
return commandOperation && this.context.runCommandOperation
|
|
426
|
+
? await this.context.runCommandOperation(commandOperation, execute) : await execute();
|
|
374
427
|
}
|
|
375
428
|
finally {
|
|
376
|
-
|
|
377
|
-
|
|
429
|
+
try {
|
|
430
|
+
await commandOperation?.finish();
|
|
431
|
+
}
|
|
432
|
+
finally {
|
|
433
|
+
active = false;
|
|
434
|
+
this.context.release(lease);
|
|
435
|
+
}
|
|
378
436
|
}
|
|
379
437
|
}
|
|
380
438
|
async #receiveCanonicalEndpointEvent(source) {
|
|
@@ -394,7 +452,7 @@ export class InboundRuntime {
|
|
|
394
452
|
},
|
|
395
453
|
};
|
|
396
454
|
const dispatch = async (payload) => {
|
|
397
|
-
await this.#runHandlers(lease
|
|
455
|
+
await this.#runHandlers(lease, source.name, [withEndpointEventPayload(source, payload)]);
|
|
398
456
|
};
|
|
399
457
|
if (source.payload.type !== source.name.split('.')[0]) {
|
|
400
458
|
throw new TypeError('Endpoint event payload type does not match its gateway event');
|
|
@@ -424,38 +482,38 @@ export class InboundRuntime {
|
|
|
424
482
|
async #receiveSideEvent(event) {
|
|
425
483
|
const lease = this.context.acquire();
|
|
426
484
|
try {
|
|
427
|
-
await this.#runHandlers(lease
|
|
485
|
+
await this.#runHandlers(lease, event.name, [event]);
|
|
428
486
|
}
|
|
429
487
|
finally {
|
|
430
488
|
this.context.release(lease);
|
|
431
489
|
}
|
|
432
490
|
}
|
|
433
|
-
async #runHandlers(
|
|
491
|
+
async #runHandlers(lease, event, args) {
|
|
492
|
+
const snapshot = lease.value;
|
|
434
493
|
const index = handlers(snapshot);
|
|
435
494
|
if (!index)
|
|
436
495
|
return;
|
|
437
496
|
const options = {
|
|
438
497
|
snapshot,
|
|
439
|
-
resolveInteraction: (name, interactionArgs) => {
|
|
498
|
+
resolveInteraction: (name, interactionArgs, owner) => {
|
|
440
499
|
const eventContext = interactionArgs[0];
|
|
441
500
|
const payload = eventContext?.payload;
|
|
442
501
|
if (name === 'message.receive' && payload instanceof RuntimeMessage) {
|
|
443
|
-
return this.
|
|
502
|
+
return this.context.interactions.createFromUnknown(bindOperationInput(payload, owner, snapshot));
|
|
444
503
|
}
|
|
445
504
|
if (name === 'notice.receive'
|
|
446
505
|
|| name === 'request.receive') {
|
|
447
|
-
return this.#createInteractionForSideEvent(payload, snapshot);
|
|
506
|
+
return this.#createInteractionForSideEvent(payload, snapshot, owner, lease.retirementSignal);
|
|
448
507
|
}
|
|
449
508
|
return undefined;
|
|
450
509
|
},
|
|
451
510
|
};
|
|
452
511
|
await index.dispatch(event, args, options);
|
|
453
512
|
}
|
|
454
|
-
#createInteractionForSideEvent(payload, snapshot) {
|
|
513
|
+
#createInteractionForSideEvent(payload, snapshot, requester, retirementSignal) {
|
|
455
514
|
const conversation = payload.conversation;
|
|
456
515
|
if (!conversation)
|
|
457
516
|
return undefined;
|
|
458
|
-
const requester = snapshot.root;
|
|
459
517
|
const source = Object.freeze({
|
|
460
518
|
conversation,
|
|
461
519
|
...(payload.actor?.id
|
|
@@ -467,7 +525,7 @@ export class InboundRuntime {
|
|
|
467
525
|
content,
|
|
468
526
|
}, snapshot),
|
|
469
527
|
});
|
|
470
|
-
return this.context.interactions.create(source);
|
|
528
|
+
return this.context.interactions.create(source, undefined, { snapshot, owner: requester, retirementSignal });
|
|
471
529
|
}
|
|
472
530
|
async #dispatchInteractive(message, requester, admission, snapshot) {
|
|
473
531
|
const handled = await this.context.interactions.dispatch(message, admission, snapshot);
|
|
@@ -8,6 +8,7 @@ export * from './im-runtime.js';
|
|
|
8
8
|
export * from './login-assist-host.js';
|
|
9
9
|
export * from './message-bus.js';
|
|
10
10
|
export * from './message-dispatcher.js';
|
|
11
|
+
export type { RuntimeMessageDiagnostic, RuntimeMessageDiagnosticStep, RuntimeMessageDiagnosticDelivery, RuntimeMessageDiagnosticsReader, } from './message-diagnostics.js';
|
|
11
12
|
export type { RuntimeMessageEvent, RuntimeMessageEventSource, RuntimeMessageRendering, OutboundFallbackReason, } from './message-events.js';
|
|
12
13
|
export * from './outbound-renderer.js';
|
|
13
14
|
export * from './outbound-segments.js';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { PluginId, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
2
|
+
/** Core-only trusted operation binding; never read from message metadata. */
|
|
3
|
+
export declare const interactionOperationScope: unique symbol;
|
|
4
|
+
export interface InteractionOperationScope {
|
|
5
|
+
readonly snapshot: RuntimeSnapshot;
|
|
6
|
+
readonly owner: PluginId;
|
|
7
|
+
readonly retirementSignal?: AbortSignal;
|
|
8
|
+
}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { type ConversationRef, type DeliveryReceipt } from '@zhin.js/im-contract';
|
|
2
2
|
import type { UserInteraction } from '@zhin.js/interaction';
|
|
3
|
-
import type
|
|
4
|
-
import type
|
|
3
|
+
import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
4
|
+
import { type Message, type MessageSenderRef, type SendContent, type SendRequest } from './contracts.js';
|
|
5
|
+
import { type InteractionOperationScope } from './interaction-operation.js';
|
|
5
6
|
import { RuntimeInteractiveRouter } from './interactive-router.js';
|
|
6
7
|
import type { Segment } from '../../built/segment-contract/types.js';
|
|
7
8
|
import { type JsxButtonBatch } from './jsx-button-registry.js';
|
|
8
9
|
export interface UserInteractionSource {
|
|
10
|
+
readonly generation?: number;
|
|
9
11
|
readonly conversation: ConversationRef;
|
|
10
12
|
readonly sender?: MessageSenderRef;
|
|
11
13
|
readonly $reply: (content: SendContent) => Promise<DeliveryReceipt>;
|
|
@@ -33,5 +35,5 @@ export declare class RuntimeInteractionCoordinator<Admission = never> {
|
|
|
33
35
|
readonly subjectId: string;
|
|
34
36
|
}): UserInteraction | undefined;
|
|
35
37
|
createFromUnknown(source: unknown): UserInteraction | undefined;
|
|
36
|
-
create(source: UserInteractionSource, subjectId?: string): UserInteraction;
|
|
38
|
+
create(source: UserInteractionSource, subjectId?: string, operation?: InteractionOperationScope): UserInteraction;
|
|
37
39
|
}
|