@zhin.js/core 1.1.55 → 1.1.57

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 (64) hide show
  1. package/lib/built/generic-segment-mapper.js +2 -0
  2. package/lib/built/html-to-text.js +2 -2
  3. package/lib/built/rich-segments/markdown-to-text.js +19 -0
  4. package/lib/built/segment-contract/validate.d.ts +1442 -300
  5. package/lib/built/user-interaction.js +3 -1
  6. package/lib/index.d.ts +4 -0
  7. package/lib/index.js +3 -0
  8. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +1 -1
  9. package/lib/plugin-runtime/im/command-menu-navigation.js +2 -1
  10. package/lib/plugin-runtime/im/contracts.d.ts +8 -1
  11. package/lib/plugin-runtime/im/contracts.js +20 -1
  12. package/lib/plugin-runtime/im/conversation-runtime.d.ts +2 -2
  13. package/lib/plugin-runtime/im/conversation-runtime.js +6 -4
  14. package/lib/plugin-runtime/im/im-runtime.js +8 -1
  15. package/lib/plugin-runtime/im/inbound-dedup.d.ts +1 -0
  16. package/lib/plugin-runtime/im/inbound-dedup.js +1 -0
  17. package/lib/plugin-runtime/im/inbound-origin.d.ts +27 -0
  18. package/lib/plugin-runtime/im/inbound-runtime.d.ts +8 -1
  19. package/lib/plugin-runtime/im/inbound-runtime.js +79 -2
  20. package/lib/plugin-runtime/im/index.d.ts +2 -0
  21. package/lib/plugin-runtime/im/index.js +2 -0
  22. package/lib/plugin-runtime/im/interaction-runtime.d.ts +7 -6
  23. package/lib/plugin-runtime/im/interaction-runtime.js +85 -24
  24. package/lib/plugin-runtime/im/interactive-router.d.ts +28 -8
  25. package/lib/plugin-runtime/im/interactive-router.js +112 -35
  26. package/lib/plugin-runtime/im/jsx-button-registry.d.ts +16 -2
  27. package/lib/plugin-runtime/im/jsx-button-registry.js +56 -19
  28. package/lib/plugin-runtime/im/message-dispatcher.js +59 -6
  29. package/lib/plugin-runtime/im/operation-resources.d.ts +15 -0
  30. package/lib/plugin-runtime/im/operation-resources.js +2 -0
  31. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +5 -4
  32. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +71 -21
  33. package/lib/plugin-runtime/im/outbound-segments.d.ts +1 -1
  34. package/lib/plugin-runtime/im/outbound-segments.js +2 -20
  35. package/lib/runtime.d.ts +2 -0
  36. package/lib/runtime.js +2 -0
  37. package/lib/side-event/index.d.ts +0 -1
  38. package/lib/side-event/index.js +0 -1
  39. package/lib/side-event/normalize.d.ts +0 -28
  40. package/lib/side-event/normalize.js +0 -100
  41. package/lib/side-event/scene-events.js +1 -1
  42. package/lib/side-event/types.d.ts +0 -6
  43. package/lib/side-event/types.js +1 -57
  44. package/lib/venue/contracts.d.ts +21 -0
  45. package/lib/venue/contracts.js +3 -0
  46. package/lib/venue/floor-controller.d.ts +11 -0
  47. package/lib/venue/floor-controller.js +63 -0
  48. package/lib/venue/index.d.ts +13 -0
  49. package/lib/venue/index.js +11 -0
  50. package/lib/venue/membership-port.d.ts +23 -0
  51. package/lib/venue/membership-port.js +141 -0
  52. package/lib/venue/projector.d.ts +38 -0
  53. package/lib/venue/projector.js +45 -0
  54. package/lib/venue/registry.d.ts +16 -0
  55. package/lib/venue/registry.js +63 -0
  56. package/lib/venue/router.d.ts +19 -0
  57. package/lib/venue/router.js +101 -0
  58. package/lib/venue/send-limiter.d.ts +17 -0
  59. package/lib/venue/send-limiter.js +73 -0
  60. package/lib/venue/validator.d.ts +6 -0
  61. package/lib/venue/validator.js +160 -0
  62. package/package.json +16 -16
  63. package/lib/side-event/dispatch.d.ts +0 -15
  64. package/lib/side-event/dispatch.js +0 -168
@@ -44,7 +44,9 @@ export function renderUserInteraction(view, actionPayload = (value) => value, lo
44
44
  view.tip?.trim() ? quoteTip(view.tip.trim()) : undefined,
45
45
  ].filter((part) => !!part).join('\n\n');
46
46
  const actions = view.actions ?? [];
47
- if (actions.length === 0) {
47
+ const hasInlineOptionList = actions.length > 0
48
+ && actions.every((action, index) => view.description?.includes(`${index + 1}. ${action.label}`));
49
+ if (actions.length === 0 || hasInlineOptionList) {
48
50
  return [{ type: 'markdown', data: { content: markdown } }];
49
51
  }
50
52
  const buttons = actions.map((action, index) => ({
package/lib/index.d.ts CHANGED
@@ -47,3 +47,7 @@ export type { ConversationRef, DeliveryReceipt } from '@zhin.js/im-contract';
47
47
  export { conversationRefKey } from '@zhin.js/im-contract';
48
48
  export { readOperationSession } from '@zhin.js/feature-kit';
49
49
  export type { CapabilityContext, OperationClientPort, OperationSession, OperationScene, OperationSender, OperationMessage, OperationMessageRef } from '@zhin.js/feature-kit';
50
+ /** ADR 0044: adapter capability types, re-exported so the agent layer reads them through core. */
51
+ export type { TurnCapabilities, AdapterCapabilityProfile, CapabilityFacts } from '@zhin.js/adapter';
52
+ export { adapterFeatureId, isAdapterIndex } from '@zhin.js/adapter';
53
+ export * from './venue/index.js';
package/lib/index.js CHANGED
@@ -44,3 +44,6 @@ export { Schema } from '@zhin.js/schema';
44
44
  export { ScheduleEngine, Scheduler, } from '@zhin.js/kernel';
45
45
  export { conversationRefKey } from '@zhin.js/im-contract';
46
46
  export { readOperationSession } from '@zhin.js/feature-kit';
47
+ export { adapterFeatureId, isAdapterIndex } from '@zhin.js/adapter';
48
+ // ── Venue 模块 (ADR 0048 H4) ──────────────────────────────────────────
49
+ export * from './venue/index.js';
@@ -1,6 +1,6 @@
1
+ import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
1
2
  import type { CommandDispatchResult, CommandIndex } from '@zhin.js/command';
2
3
  import type { ConversationRef } from '@zhin.js/im-contract';
3
- import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
4
4
  import type { SendContent } from './contracts.js';
5
5
  /** Rendering dependencies for one menu response; callbacks retain the same generation. */
6
6
  export interface CommandMenuReplyContext {
@@ -1,3 +1,4 @@
1
+ import { readOperationInputResources } from '@zhin.js/feature-kit';
1
2
  import { createMessages } from '@zhin.js/plugin-runtime';
2
3
  import { Fragment, jsx } from '@zhin.js/jsx';
3
4
  import { resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundSupportedSegments } from './outbound-segments.js';
@@ -28,7 +29,7 @@ export async function commandMenuReply(result, { commands, snapshot, conversatio
28
29
  if (disabled)
29
30
  return [];
30
31
  const input = `${menu.keyword}${menu.pluginKey ? ` ${menu.pluginKey}` : ''} --page ${page}`;
31
- const next = await commands.dispatch({ input: input, source: message, commandPrefix: prefix, snapshot: snapshot, locale: menu.locale });
32
+ const next = await commands.dispatch({ input: input, source: message, commandPrefix: prefix, snapshot: snapshot, locale: menu.locale, operation: readOperationInputResources(message, snapshot) });
32
33
  return commandMenuReply(next, { commands: commands, snapshot: snapshot, conversation: message.conversation, prefix: prefix });
33
34
  },
34
35
  });
@@ -2,7 +2,7 @@ import type { CapturedEndpointOperation } from './captured-endpoint-operation.js
2
2
  import type { JSXElement } from '@zhin.js/jsx';
3
3
  import { type CommandMenuPage } from '@zhin.js/command';
4
4
  import { type PluginId, type RuntimeSnapshot, type Locale } from '@zhin.js/plugin-runtime';
5
- import { operationInputBinding, operationInputSignal, operationSession, type OperationSession } from '@zhin.js/feature-kit';
5
+ import { operationInputBinding, operationInputSignal, operationInputResources, operationSession, type OperationSession, type OperationResourceView, type CapabilityOperationFactory } from '@zhin.js/feature-kit';
6
6
  import type { ConversationRef, DeliveryReceipt, MessageRef } from '@zhin.js/im-contract';
7
7
  import type { MessageOrigin } from './inbound-origin.js';
8
8
  import type { OperationEndpointSource } from './operation-endpoint.js';
@@ -194,6 +194,11 @@ export interface RuntimeMessageOperation {
194
194
  readonly signal?: AbortSignal;
195
195
  readonly captureInteraction?: (owner: PluginId) => CapturedEndpointOperation;
196
196
  readonly session?: RuntimeMessageSessionBinding;
197
+ readonly createOperationResources?: (input: Readonly<{
198
+ message: RuntimeMessage;
199
+ owner: PluginId;
200
+ signal: AbortSignal;
201
+ }>) => OperationResourceView | undefined;
197
202
  readonly registerOperationView?: (view: object, owner: PluginId) => void;
198
203
  readonly presentation?: RuntimeMessagePresentation;
199
204
  }
@@ -225,6 +230,8 @@ export declare class RuntimeMessage implements MessageBase {
225
230
  [operationSession](): OperationSession<string> | undefined;
226
231
  /** @internal A frozen view whose sends retain the current author's exact operation. */
227
232
  [operationInputBinding](owner: PluginId, snapshot: RuntimeSnapshot): RuntimeMessage;
233
+ /** @internal Metadata fields cannot replace this actual leased operation factory. */
234
+ [operationInputResources](snapshot: RuntimeSnapshot): CapabilityOperationFactory | undefined;
228
235
  /** @internal Explicit operation cancellation; replacement alone does not end accepted work. */
229
236
  [operationInputSignal](): AbortSignal | undefined;
230
237
  /** @internal The command/handler author's actual leased operation. */
@@ -1,6 +1,6 @@
1
1
  import { commandFeatureId, isCommandIndex } from '@zhin.js/command';
2
2
  import { resolveLocale } from '@zhin.js/plugin-runtime';
3
- import { operationInputBinding, operationInputSignal, operationSession } from '@zhin.js/feature-kit';
3
+ import { operationInputBinding, operationInputSignal, operationInputResources, operationSession } from '@zhin.js/feature-kit';
4
4
  import { interactionOperationScope } from './interaction-operation.js';
5
5
  const componentCallBrand = 'zhin.component-call/1';
6
6
  const rawContentBrand = 'zhin.raw-content/1';
@@ -148,6 +148,25 @@ export class RuntimeMessage {
148
148
  },
149
149
  });
150
150
  }
151
+ /** @internal Metadata fields cannot replace this actual leased operation factory. */
152
+ [operationInputResources](snapshot) {
153
+ this.#operation.assertActive?.();
154
+ if (snapshot !== this.#operation.snapshot || snapshot.generation !== this.generation) {
155
+ throw new Error('Message resources belong to another generation operation');
156
+ }
157
+ if (!this.#operation.createOperationResources)
158
+ return undefined;
159
+ const signal = this.#operation.signal ?? new AbortController().signal;
160
+ return Object.freeze({ signal, create: (input) => {
161
+ this.#operation.assertActive?.();
162
+ if (!snapshot.tree.has(input.owner))
163
+ throw new Error(`Unknown operation owner: ${input.owner}`);
164
+ const actualSignal = input.signal === signal ? signal : AbortSignal.any([signal, input.signal]);
165
+ return Object.freeze({ signal: actualSignal, resources: this.#operation.createOperationResources?.({
166
+ message: this, owner: input.owner, signal: actualSignal,
167
+ }) });
168
+ } });
169
+ }
151
170
  /** @internal Explicit operation cancellation; replacement alone does not end accepted work. */
152
171
  [operationInputSignal]() {
153
172
  this.#operation.assertActive?.();
@@ -27,9 +27,9 @@ export declare class ConversationRuntime {
27
27
  markInteractionAnswer(message: MessageRef): void;
28
28
  commitContext(conversation: ConversationRef, consumer: string, cursor: number): Promise<void>;
29
29
  recordIncoming(input: IncomingMessage, sender: MessageSenderRef | undefined): Promise<number | undefined>;
30
- recordOutbound(request: SendRequest, receipt: DeliveryReceipt, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<void>;
30
+ recordOutbound(request: SendRequest, receipt: DeliveryReceipt, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<number | undefined>;
31
31
  /** Records a confirmed replacement body without inventing another physical message. */
32
- recordOutboundUpdate(request: SendRequest, receipt: DeliveryReceipt, revision: number, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<void>;
32
+ recordOutboundUpdate(request: SendRequest, receipt: DeliveryReceipt, revision: number, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<number | undefined>;
33
33
  /** Records a normalized notice; returns the stored event (with its sequence) when newly appended. */
34
34
  recordNotice(notice: Notice): Promise<SequencedConversationEvent | undefined>;
35
35
  /** Join requests / invitations into a group or channel become `scene.join_requested` (#996). */
@@ -115,9 +115,9 @@ export class ConversationRuntime {
115
115
  }
116
116
  async recordOutbound(request, receipt, canonicalContent) {
117
117
  if (receipt.status !== 'sent' || !receipt.message?.id)
118
- return;
118
+ return undefined;
119
119
  const timestamp = Date.now();
120
- await this.#events.append(Object.freeze({
120
+ const appended = await this.#events.append(Object.freeze({
121
121
  eventId: `message:${messageRefKey(receipt.message)}`,
122
122
  conversation: request.conversation,
123
123
  timestamp,
@@ -132,16 +132,17 @@ export class ConversationRuntime {
132
132
  } : {}),
133
133
  }),
134
134
  }));
135
+ return appended.sequence;
135
136
  }
136
137
  /** Records a confirmed replacement body without inventing another physical message. */
137
138
  async recordOutboundUpdate(request, receipt, revision, canonicalContent) {
138
139
  if (receipt.status !== 'sent' || !receipt.message?.id)
139
- return;
140
+ return undefined;
140
141
  const original = await this.#events.getMessage(receipt.message);
141
142
  if (!original)
142
143
  throw new Error('Cannot record an update before its original message');
143
144
  const { contentStatus: _status, outboundTextDigest: _digest, ...identity } = original;
144
- await this.#events.append(Object.freeze({
145
+ const appended = await this.#events.append(Object.freeze({
145
146
  eventId: `message:${messageRefKey(receipt.message)}:revision:${revision}`,
146
147
  conversation: request.conversation, timestamp: Date.now(), type: 'message.updated',
147
148
  message: Object.freeze({ ...identity, revision,
@@ -150,6 +151,7 @@ export class ConversationRuntime {
150
151
  ...(canonicalContent !== 'unavailable' && canonicalContent?.length && canonicalContent.every(segment => segment.type === 'text') && receipt.outboundTextDigest
151
152
  ? { outboundTextDigest: receipt.outboundTextDigest } : {}), }),
152
153
  }));
154
+ return appended.sequence;
153
155
  }
154
156
  /** Records a normalized notice; returns the stored event (with its sequence) when newly appended. */
155
157
  async recordNotice(notice) {
@@ -1,4 +1,5 @@
1
- import { OwnerOperation, createToken, generationAdmissionBinder, } from '@zhin.js/plugin-runtime';
1
+ import { imOperationResourcesToken } from './operation-resources.js';
2
+ import { OwnerOperation, createToken, readLeasedRootResource, generationAdmissionBinder, } from '@zhin.js/plugin-runtime';
2
3
  import { AsyncLocalStorage } from 'node:async_hooks';
3
4
  import { PermissionHost, permissionHostToken } from '@zhin.js/permission';
4
5
  import { CommandExecutionBudget, commandExecutionAdmissionToken } from '@zhin.js/command/internal/execution';
@@ -67,6 +68,12 @@ export class ImRuntime {
67
68
  diagnostics: this.#messageDiagnostics,
68
69
  interactions: this.#interactions,
69
70
  captureOperation: input => this.endpoints.captureOperation(input),
71
+ createOperationResources: input => {
72
+ const snapshots = this.#snapshots;
73
+ if (!snapshots || !snapshots.owns(input.lease) || !input.lease.active)
74
+ throw new Error('IM operation lease is not active');
75
+ return readLeasedRootResource(snapshots, input.lease, imOperationResourcesToken)?.open({ ...input, snapshots });
76
+ },
70
77
  inboundClaim: options.inboundClaim,
71
78
  originClassifier,
72
79
  deduper,
@@ -1,4 +1,5 @@
1
1
  import type { ConversationRef } from '@zhin.js/im-contract';
2
+ export { roomMembershipToken, type ResolvedRoomInfo, type RoomArbitrationInput, type RoomClaimInput, type RoomInboundRouteInput, type RoomMembershipPort, type RoomReadinessResult, type RoomRouteDecision, } from './inbound-origin.js';
2
3
  export type InboundClaim = 'first' | 'same_endpoint' | 'duplicate' | 'unkeyed';
3
4
  /** Room Router decision as seen by the deduper (the Endpoint ids only). */
4
5
  export interface InboundArbitrationDecision {
@@ -1,4 +1,5 @@
1
1
  import { ledgerScopeOf } from './outbound-ledger.js';
2
+ export { roomMembershipToken, } from './inbound-origin.js';
2
3
  /**
3
4
  * @internal 入站去重:同一条人类群消息会到达 N 个成员 Endpoint,
4
5
  * 按 平台 + 会话 + 发送者 + 平台消息 id 只放行第一个 Endpoint,其余仅记录。
@@ -7,6 +7,27 @@ export type MessageOrigin = 'self' | 'member' | 'peer_bot' | 'human';
7
7
  /** @internal */
8
8
  export declare const MESSAGE_ORIGINS: readonly MessageOrigin[];
9
9
  export declare function isMessageOrigin(value: unknown): value is MessageOrigin;
10
+ export interface RoomClaimInput {
11
+ readonly platform: string;
12
+ readonly sceneType?: string;
13
+ readonly sceneId: string;
14
+ readonly threadId?: string;
15
+ }
16
+ export interface RoomArbitrationInput extends RoomClaimInput {
17
+ readonly endpointId: string;
18
+ readonly rawText?: string;
19
+ readonly mentions?: readonly string[];
20
+ readonly replyToSenderId?: string;
21
+ }
22
+ export interface ResolvedRoomInfo {
23
+ readonly roomId: string;
24
+ readonly defaultEndpointId: string;
25
+ readonly memberEndpoints: readonly string[];
26
+ }
27
+ export interface RoomReadinessResult {
28
+ readonly ready: boolean;
29
+ readonly unreadyEndpoints?: readonly string[];
30
+ }
10
31
  /**
11
32
  * Room 成员端口。由 Room 激活(后续条目,workroom)通过 root resources 提供;
12
33
  * 未提供时没有任何 member:Registry 命中的账号全部是 `peer_bot`。
@@ -41,6 +62,12 @@ export interface RoomMembershipPort {
41
62
  * `fallbackEndpointIds` 中的成员在宽限期后按优先级接管。决策按消息缓存,每条消息只决定一次。
42
63
  */
43
64
  route?(input: RoomInboundRouteInput): RoomRouteDecision | undefined;
65
+ /** Resolve a conversation to its Venue / Room definition summary. */
66
+ resolveRoom?(input: RoomClaimInput): ResolvedRoomInfo | undefined;
67
+ /** Check whether an endpoint in a Venue / Room is directly addressed by @mention or reply. */
68
+ isAddressedEndpoint?(input: RoomArbitrationInput): boolean;
69
+ /** Fail-closed readiness check for Venue member endpoints (ADR 0048 §3.4 invariant 7). */
70
+ isRoomReady?(input: RoomClaimInput): RoomReadinessResult;
44
71
  }
45
72
  /** core 用可信数据构造的路由输入;不信任正文。 */
46
73
  export interface RoomInboundRouteInput {
@@ -1,6 +1,7 @@
1
1
  import type { CaptureEndpointOperationInput, CapturedEndpointOperation } from './captured-endpoint-operation.js';
2
- import type { GenerationAdmissionGate, RuntimeSnapshot, SnapshotLease } from '@zhin.js/plugin-runtime';
2
+ import type { GenerationAdmissionGate, PluginId, RuntimeSnapshot, SnapshotLease } from '@zhin.js/plugin-runtime';
3
3
  import type { EndpointEvent, PeerRegistry } from '@zhin.js/adapter';
4
+ import { type OperationResourceView } from '@zhin.js/feature-kit';
4
5
  import type { DeliveryReceipt } from '@zhin.js/im-contract';
5
6
  import type { UserInteraction } from '@zhin.js/interaction';
6
7
  import type { CommandExecutionBudget, CommandOperationController } from '@zhin.js/command/internal/execution';
@@ -19,6 +20,12 @@ interface InboundRuntimeContext {
19
20
  readonly diagnostics?: RuntimeMessageDiagnostics;
20
21
  readonly interactions: InboundInteractionPort;
21
22
  captureOperation(input: CaptureEndpointOperationInput): CapturedEndpointOperation;
23
+ createOperationResources?(input: Readonly<{
24
+ lease: SnapshotLease;
25
+ message: import('./contracts.js').RuntimeMessage;
26
+ owner: PluginId;
27
+ signal: AbortSignal;
28
+ }>): OperationResourceView | undefined;
22
29
  readonly inboundClaim?: (message: Message) => boolean | Promise<boolean>;
23
30
  /** Trusted origin classifier. Absent: messages carry no origin (legacy behavior). */
24
31
  readonly originClassifier?: InboundOriginClassifier;
@@ -135,6 +135,23 @@ export class InboundRuntime {
135
135
  }));
136
136
  return Object.freeze({ matched: false });
137
137
  }
138
+ if (typeof roomMembership?.isRoomReady === 'function') {
139
+ const readiness = roomMembership.isRoomReady({
140
+ platform: conversation.endpoint.adapter,
141
+ sceneType: conversation.kind,
142
+ sceneId: conversation.id,
143
+ ...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
144
+ });
145
+ if (!readiness.ready) {
146
+ logger.warn(formatCompact({
147
+ op: 'venue_unready',
148
+ conv: formatConversationLog(conversation),
149
+ unreadyEndpoints: readiness.unreadyEndpoints?.join(',') ?? '',
150
+ reason: 'Venue member endpoints have not reported selfUserId yet',
151
+ }));
152
+ return Object.freeze({ matched: false });
153
+ }
154
+ }
138
155
  // Must stay synchronous and before any await: concurrent arrivals of the same
139
156
  // message from N Endpoints are decided atomically. Only human origin claims,
140
157
  // so bot-origin messages never consume the key. Scoped to Room conversations:
@@ -242,10 +259,12 @@ export class InboundRuntime {
242
259
  }
243
260
  const mentioned = routedTarget ? true : input.mentioned;
244
261
  const locale = await messageLocale(lease.value, conversation, enrichedSender?.id);
262
+ let operationReplied = false;
245
263
  const operationReply = (content, replyRequester = requester, targetConversation) => {
246
264
  if (!active)
247
265
  throw new Error('Message reply scope has ended');
248
266
  boundEndpoint.assertActive();
267
+ operationReplied = true;
249
268
  const effectiveConversation = targetConversation
250
269
  ? { ...targetConversation, endpoint: conversation.endpoint }
251
270
  : conversation;
@@ -332,6 +351,7 @@ export class InboundRuntime {
332
351
  captureInteraction: owner => this.context.captureOperation({ target: conversation,
333
352
  client: source.client, requester: owner, signal: boundEndpoint.signal }),
334
353
  registerOperationView: commandOperation?.bind,
354
+ createOperationResources: request => this.context.createOperationResources?.({ ...request, lease }),
335
355
  assertActive: () => {
336
356
  if (!active)
337
357
  throw new Error('Message author binding scope has ended');
@@ -404,12 +424,18 @@ export class InboundRuntime {
404
424
  }
405
425
  else {
406
426
  const interactionFactory = (value) => this.context.interactions.createFromUnknown(value);
407
- const terminal = async () => {
427
+ const terminal = async (control) => {
408
428
  const ingressRoute = resolveIngressRoute(lease.value);
409
429
  const preRouted = await ingressRoute?.preRoute?.(message, lease, requester, conversationSequence) === true;
410
430
  if (preRouted) {
411
431
  this.context.diagnostics?.route('agent');
412
432
  result = Object.freeze({ matched: true, command: 'pre-route', owner: requester });
433
+ await control?.reportDispatch({
434
+ matched: true,
435
+ path: 'handler',
436
+ handlerId: 'pre-route',
437
+ replied: operationReplied,
438
+ });
413
439
  return { dispatch: result };
414
440
  }
415
441
  if (ingressRoute?.shouldRouteBeforeDispatch?.(message) === true) {
@@ -417,14 +443,22 @@ export class InboundRuntime {
417
443
  if (handled) {
418
444
  this.context.diagnostics?.route('agent');
419
445
  result = Object.freeze({ matched: true, command: 'ai', owner: requester });
446
+ await control?.reportDispatch({
447
+ matched: true,
448
+ path: 'handler',
449
+ handlerId: 'ai',
450
+ replied: operationReplied,
451
+ });
420
452
  return { dispatch: result };
421
453
  }
422
454
  }
455
+ const repliedBeforeHandlers = operationReplied;
423
456
  this.context.diagnostics?.step('handlers', 'started');
424
457
  await this.#runHandlers({ lease, event: 'message.receive', args: [
425
458
  withEndpointEventPayload(source, message),
426
459
  ], signal: operationSignal });
427
460
  this.context.diagnostics?.step('handlers', 'completed');
461
+ const repliedDuringHandlers = !repliedBeforeHandlers && operationReplied;
428
462
  const interactive = await this.#dispatchInteractive({ message, requester, admission, snapshot: lease.value });
429
463
  if (interactive)
430
464
  this.context.diagnostics?.route('interaction');
@@ -443,6 +477,47 @@ export class InboundRuntime {
443
477
  }
444
478
  const response = dispatched?.reply ?? (interactive?.value !== undefined && interactive.owner
445
479
  ? { owner: interactive.owner, content: interactive.value } : undefined);
480
+ const replied = operationReplied || response !== undefined;
481
+ if (interactive) {
482
+ await control?.reportDispatch({
483
+ matched: true,
484
+ path: 'button',
485
+ handlerId: interactive.command ?? 'interactive',
486
+ replied,
487
+ });
488
+ }
489
+ else if (dispatched?.dispatch.matched) {
490
+ await control?.reportDispatch({
491
+ matched: true,
492
+ path: 'command',
493
+ ...(dispatched.dispatch.command ? { handlerId: dispatched.dispatch.command } : {}),
494
+ replied,
495
+ });
496
+ }
497
+ else if (result.matched) {
498
+ await control?.reportDispatch({
499
+ matched: true,
500
+ path: 'handler',
501
+ ...(result.command ? { handlerId: result.command } : {}),
502
+ replied,
503
+ });
504
+ }
505
+ else if (repliedDuringHandlers) {
506
+ const handlerName = handlers(lease.value)?.list().find(descriptor => descriptor.event === 'message.receive')?.name ?? 'message.receive';
507
+ await control?.reportDispatch({
508
+ matched: true,
509
+ path: 'handler',
510
+ handlerId: handlerName,
511
+ replied: true,
512
+ });
513
+ }
514
+ else {
515
+ await control?.reportDispatch({
516
+ matched: false,
517
+ path: 'none',
518
+ replied,
519
+ });
520
+ }
446
521
  return {
447
522
  dispatch: result,
448
523
  ...(response ? { reply: response } : {}),
@@ -657,7 +732,9 @@ function resolveRoomMembership(snapshot) {
657
732
  const candidate = snapshot.resources.get(snapshot.root)?.get(roomMembershipToken.id);
658
733
  return candidate
659
734
  && typeof candidate === 'object'
660
- && typeof candidate.isMember === 'function'
735
+ && (typeof candidate.isMember === 'function'
736
+ || typeof candidate.resolveRoom === 'function'
737
+ || typeof candidate.isRoomReady === 'function')
661
738
  ? candidate
662
739
  : undefined;
663
740
  }
@@ -5,6 +5,7 @@ export * from './ingress-route.js';
5
5
  export { isMessageOrigin, roomMembershipToken } from './inbound-origin.js';
6
6
  export type { MessageOrigin, RoomInboundRouteInput, RoomMembershipPort, RoomRouteDecision, } from './inbound-origin.js';
7
7
  export * from './im-runtime.js';
8
+ export * from './operation-resources.js';
8
9
  export * from './login-assist-host.js';
9
10
  export * from './group-rule-violation.js';
10
11
  export * from './member-welcome.js';
@@ -18,3 +19,4 @@ export type { CoreReplyStream, OpenReplyStreamOptions, ReplyStreamSnapshot, Conf
18
19
  export * from '../../notice.js';
19
20
  export * from '../../request.js';
20
21
  export * from '../../system-event.js';
22
+ export * from '../../venue/index.js';
@@ -3,6 +3,7 @@ export { EndpointRuntime } from './endpoint-runtime.js';
3
3
  export * from './ingress-route.js';
4
4
  export { isMessageOrigin, roomMembershipToken } from './inbound-origin.js';
5
5
  export * from './im-runtime.js';
6
+ export * from './operation-resources.js';
6
7
  export * from './login-assist-host.js';
7
8
  export * from './group-rule-violation.js';
8
9
  export * from './member-welcome.js';
@@ -13,3 +14,4 @@ export * from './outbound-segments.js';
13
14
  export * from '../../notice.js';
14
15
  export * from '../../request.js';
15
16
  export * from '../../system-event.js';
17
+ export * from '../../venue/index.js';
@@ -3,9 +3,10 @@ import { type ConversationRef, type DeliveryReceipt, type MessageRef } from '@zh
3
3
  import type { UserInteraction } from '@zhin.js/interaction';
4
4
  import { type Message, type MessageSenderRef, type SendContent, type SendRequest } from './contracts.js';
5
5
  import { type InteractionOperationScope } from './interaction-operation.js';
6
- import { RuntimeInteractiveRouter } from './interactive-router.js';
6
+ import { RuntimeInteractiveRouter, type RememberFallbackContext } from './interactive-router.js';
7
7
  import type { Segment } from '../../built/segment-contract/types.js';
8
- import { type JsxButtonBatch } from './jsx-button-registry.js';
8
+ import { type JsxButtonBatch, type PluginIncarnationRef } from './jsx-button-registry.js';
9
+ export { isPluginIncarnationAlive, type PluginIncarnationRef } from './jsx-button-registry.js';
9
10
  /** A live conversational prompt; its callbacks still require the original subject and generation. */
10
11
  export interface PendingUserInteraction {
11
12
  readonly id: string;
@@ -28,10 +29,10 @@ export declare class RuntimeInteractionCoordinator<Admission = never> {
28
29
  /** `markPrompt` keeps a delivered prompt out of conversation context, like its answer. */
29
30
  constructor(router?: RuntimeInteractiveRouter<Admission>, markPrompt?: (message: MessageRef) => void);
30
31
  register(prefix: string, handler: (message: Message) => Promise<boolean> | boolean, admission?: Admission): () => void;
31
- rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>): Record<string, string>;
32
+ rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>, ttlMsOrContext?: number | RememberFallbackContext | PluginIncarnationRef): Record<string, string>;
32
33
  dispatch(message: Message, admission?: Admission, snapshot?: RuntimeSnapshot): Promise<boolean>;
33
34
  prepareButtons(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
34
- resolveClaim(message: Message): boolean;
35
+ resolveClaim(message: Message, snapshot?: RuntimeSnapshot): boolean;
35
36
  /**
36
37
  * Probe used by Room routing: is this message the answer to something pending on this exact
37
38
  * (Endpoint-scoped) conversation? True when the sender has a pending conversational claim, or
@@ -41,9 +42,9 @@ export declare class RuntimeInteractionCoordinator<Admission = never> {
41
42
  hasPendingAnswer(conversation: ConversationRef, senderId: string, generation: number, input?: {
42
43
  readonly content: string;
43
44
  readonly segments?: readonly Segment[];
44
- }): boolean;
45
+ }, snapshot?: RuntimeSnapshot): boolean;
45
46
  /** Read-only current prompt; never re-delivers, renews its deadline or accepts an answer. */
46
- readPendingInteraction(conversation: ConversationRef, subjectId: string, generation: number): PendingUserInteraction | undefined;
47
+ readPendingInteraction(conversation: ConversationRef, subjectId: string, generation: number, snapshot?: RuntimeSnapshot): PendingUserInteraction | undefined;
47
48
  createForMessage(message: Message, bind?: {
48
49
  readonly subjectId: string;
49
50
  }): UserInteraction | undefined;