@zhin.js/core 1.1.45 → 1.1.46

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.
Files changed (32) hide show
  1. package/README.md +6 -0
  2. package/lib/built/html-to-text.d.ts +0 -3
  3. package/lib/built/html-to-text.js +130 -39
  4. package/lib/built/interactive-segments/resolve.d.ts +2 -2
  5. package/lib/built/interactive-segments/resolve.js +20 -12
  6. package/lib/built/readable-link.d.ts +4 -0
  7. package/lib/built/readable-link.js +32 -0
  8. package/lib/built/rich-segments/markdown-to-text.d.ts +1 -1
  9. package/lib/built/rich-segments/markdown-to-text.js +123 -11
  10. package/lib/built/user-interaction.d.ts +1 -1
  11. package/lib/built/user-interaction.js +4 -5
  12. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +6 -0
  13. package/lib/plugin-runtime/im/command-menu-navigation.js +33 -0
  14. package/lib/plugin-runtime/im/contracts.d.ts +12 -2
  15. package/lib/plugin-runtime/im/contracts.js +24 -2
  16. package/lib/plugin-runtime/im/im-runtime.d.ts +2 -0
  17. package/lib/plugin-runtime/im/im-runtime.js +24 -4
  18. package/lib/plugin-runtime/im/inbound-runtime.d.ts +5 -0
  19. package/lib/plugin-runtime/im/inbound-runtime.js +193 -135
  20. package/lib/plugin-runtime/im/index.d.ts +1 -0
  21. package/lib/plugin-runtime/im/interaction-operation.d.ts +8 -0
  22. package/lib/plugin-runtime/im/interaction-operation.js +2 -0
  23. package/lib/plugin-runtime/im/interaction-runtime.d.ts +5 -3
  24. package/lib/plugin-runtime/im/interaction-runtime.js +150 -51
  25. package/lib/plugin-runtime/im/message-diagnostics.d.ts +70 -0
  26. package/lib/plugin-runtime/im/message-diagnostics.js +182 -0
  27. package/lib/plugin-runtime/im/message-dispatcher.d.ts +1 -1
  28. package/lib/plugin-runtime/im/message-dispatcher.js +31 -4
  29. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +2 -0
  30. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +7 -0
  31. package/lib/plugin-runtime/im/outbound-segments.js +4 -3
  32. package/package.json +13 -13
@@ -1,4 +1,5 @@
1
- import { operationInputBinding } from '@zhin.js/feature-kit';
1
+ import { operationInputBinding, operationInputSignal } from '@zhin.js/feature-kit';
2
+ import { interactionOperationScope } from './interaction-operation.js';
2
3
  const componentCallBrand = 'zhin.component-call/1';
3
4
  const rawContentBrand = 'zhin.raw-content/1';
4
5
  export function component(name, props) {
@@ -51,6 +52,8 @@ export class RuntimeMessage {
51
52
  #author;
52
53
  #snapshot;
53
54
  #assertActive;
55
+ #retirementSignal;
56
+ #registerOperationView;
54
57
  origin;
55
58
  /** @internal Constructed only by the generation-owned IM Runtime. */
56
59
  constructor(conversation, content, generation, reply, sender, metadata = Object.freeze({}),
@@ -80,6 +83,10 @@ export class RuntimeMessage {
80
83
  this.#author = binding.requester;
81
84
  this.#snapshot = binding.snapshot;
82
85
  this.#assertActive = binding.assertActive;
86
+ this.#retirementSignal = binding.retirementSignal;
87
+ this.#registerOperationView = binding.registerOperationView;
88
+ if (binding.snapshot)
89
+ binding.registerOperationView?.(this, binding.requester ?? binding.snapshot.root);
83
90
  const requester = binding.requester;
84
91
  this.$reply = (content) => requester === undefined ? reply(content) : reply(content, requester);
85
92
  this.$replyFrom = (requester, content) => reply(content, requester);
@@ -126,7 +133,22 @@ export class RuntimeMessage {
126
133
  throw new Error(`Unknown Message author: ${owner}`);
127
134
  if (this.#author === owner && this.#snapshot === snapshot)
128
135
  return this;
129
- return new RuntimeMessage(this.conversation, this.content, this.generation, this.#reply, this.sender, this.metadata, this.segments, this.message, this.endpointId, this.mentioned, this.replyTo, this.#resolveClient, this.clientAdapter, { requester: owner, snapshot, assertActive: this.#assertActive, origin: this.origin });
136
+ return new RuntimeMessage(this.conversation, this.content, this.generation, this.#reply, this.sender, this.metadata, this.segments, this.message, this.endpointId, this.mentioned, this.replyTo, this.#resolveClient, this.clientAdapter, { requester: owner, snapshot, assertActive: this.#assertActive, origin: this.origin,
137
+ retirementSignal: this.#retirementSignal, registerOperationView: this.#registerOperationView });
138
+ }
139
+ /** @internal Retirement notification; ordinary leased sends may still drain. */
140
+ [operationInputSignal]() {
141
+ this.#assertActive?.();
142
+ return this.#retirementSignal;
143
+ }
144
+ /** @internal The command/handler author's actual leased operation. */
145
+ [interactionOperationScope]() {
146
+ this.#assertActive?.();
147
+ return this.#snapshot ? {
148
+ snapshot: this.#snapshot,
149
+ owner: this.#author ?? this.#snapshot.root,
150
+ retirementSignal: this.#retirementSignal,
151
+ } : undefined;
130
152
  }
131
153
  /** 平台原生消息 id(`message` 未提供时为 undefined)。 */
132
154
  get id() {
@@ -10,6 +10,7 @@ import type { OutboundRenderer } from './outbound-renderer.js';
10
10
  import { EndpointRuntime } from './endpoint-runtime.js';
11
11
  import { type RuntimeMessageEventSource } from './message-events.js';
12
12
  import { InboundDeduper } from './inbound-dedup.js';
13
+ import { type RuntimeMessageDiagnosticsReader } from './message-diagnostics.js';
13
14
  /** @public Stable inbound and outbound IM gateway token for Adapter integrations. */
14
15
  export declare const outboundMessageToken: import("@zhin.js/plugin-runtime").Token<OutboundMessageService>;
15
16
  export interface ImRuntimeOptions {
@@ -42,6 +43,7 @@ export interface ImRuntimeOptions {
42
43
  }
43
44
  export declare class ImRuntime implements OutboundMessageService {
44
45
  #private;
46
+ readonly messageDiagnostics: RuntimeMessageDiagnosticsReader;
45
47
  readonly messageEvents: RuntimeMessageEventSource;
46
48
  readonly endpoints: EndpointRuntime;
47
49
  constructor(options?: ImRuntimeOptions);
@@ -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.#outbound.deliver(request, snapshot),
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.#outbound.deliver(request, snapshot),
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.#outbound.deliver(request, lease.value);
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.#outbound.deliver(request, lease.value);
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.#receiveMessage(event, admission);
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 message = new RuntimeMessage(conversation, input.content, lease.value.generation, (content, replyRequester = requester, targetConversation) => {
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
- return this.context.deliver({
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
- }, enrichedSender, Object.freeze({ ...input.metadata }), input.segments ? Object.freeze([...input.segments]) : undefined, input.message, input.endpointId, mentioned, input.replyTo, () => {
244
- if (!active)
245
- throw new Error('Message Client scope has ended');
246
- return source.client;
247
- }, source.endpoint.adapter, { snapshot: lease.value, assertActive: () => {
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 author binding scope has ended');
250
- }, ...(origin ? { origin } : {}) });
251
- const conversationSequence = await this.context.recordIncoming(input, enrichedSender);
252
- let result = Object.freeze({ matched: false });
253
- if (recordOnly === 'duplicate') {
254
- // Duplicate of a message already routed via another Endpoint: history only,
255
- // no publish (avoids N copies in the console message feed).
256
- logger.debug(formatCompact({
257
- op: 'inbound_duplicate',
258
- conv: formatConversationLog(conversation),
259
- basis: recordOnly,
260
- }));
261
- return result;
262
- }
263
- if (recordOnly === 'dedup_error') {
264
- // Undecidable: record only and never route (no duplicate routing), but publish so
265
- // the console feed still shows the message and a persistent failure is visible.
266
- this.context.publish({
267
- direction: 'inbound',
268
- conversation,
269
- ...(input.sender !== undefined ? { sender: input.sender } : {}),
270
- contentPreview: previewMessageContent(input.content),
271
- ...(input.message?.id ? { messageId: input.message.id } : {}),
272
- timestamp: receivedAt,
273
- });
274
- return result;
275
- }
276
- if (origin === 'member' || origin === 'peer_bot') {
277
- // Bot-origin messages are recorded as chat history only: no claim, handlers,
278
- // commands, middleware or ingress route (prevents bot-to-bot loops).
279
- logger.debug(formatCompact({
280
- op: 'bot_origin_recorded',
281
- conv: formatConversationLog(conversation),
282
- origin,
283
- basis: classified?.basis,
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
- const claimed = await this.context.inboundClaim?.(message) === true;
296
- if (claimed) {
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
- active = false;
377
- this.context.release(lease);
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.value, source.name, [withEndpointEventPayload(source, payload)]);
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.value, event.name, [event]);
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(snapshot, event, args) {
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.createInteraction(payload);
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
+ }
@@ -0,0 +1,2 @@
1
+ /** Core-only trusted operation binding; never read from message metadata. */
2
+ export const interactionOperationScope = Symbol('InteractionOperationScope');