@zhin.js/core 1.1.42 → 1.1.44

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 (42) hide show
  1. package/lib/built/roles.d.ts +6 -1
  2. package/lib/built/roles.js +11 -20
  3. package/lib/built/segment-contract/validate.d.ts +301 -158
  4. package/lib/built/user-interaction.js +9 -3
  5. package/lib/feature/middleware-public-api.d.ts +5 -0
  6. package/lib/feature/middleware-public-api.js +5 -0
  7. package/lib/feature/middleware.d.ts +20 -2
  8. package/lib/feature/middleware.js +6 -2
  9. package/lib/plugin-runtime/im/contracts.d.ts +14 -0
  10. package/lib/plugin-runtime/im/contracts.js +3 -1
  11. package/lib/plugin-runtime/im/conversation-runtime.d.ts +13 -1
  12. package/lib/plugin-runtime/im/conversation-runtime.js +47 -1
  13. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +8 -3
  14. package/lib/plugin-runtime/im/endpoint-runtime.js +46 -3
  15. package/lib/plugin-runtime/im/im-runtime.d.ts +12 -1
  16. package/lib/plugin-runtime/im/im-runtime.js +18 -1
  17. package/lib/plugin-runtime/im/inbound-dedup.d.ts +51 -0
  18. package/lib/plugin-runtime/im/inbound-dedup.js +184 -0
  19. package/lib/plugin-runtime/im/inbound-origin.d.ts +101 -0
  20. package/lib/plugin-runtime/im/inbound-origin.js +76 -0
  21. package/lib/plugin-runtime/im/inbound-runtime.d.ts +16 -2
  22. package/lib/plugin-runtime/im/inbound-runtime.js +235 -11
  23. package/lib/plugin-runtime/im/index.d.ts +3 -1
  24. package/lib/plugin-runtime/im/index.js +1 -0
  25. package/lib/plugin-runtime/im/interaction-runtime.d.ts +11 -0
  26. package/lib/plugin-runtime/im/interaction-runtime.js +17 -0
  27. package/lib/plugin-runtime/im/interactive-router.d.ts +18 -1
  28. package/lib/plugin-runtime/im/interactive-router.js +62 -8
  29. package/lib/plugin-runtime/im/jsx-button-registry.js +6 -2
  30. package/lib/plugin-runtime/im/message-dispatcher.js +10 -0
  31. package/lib/plugin-runtime/im/message-events.d.ts +7 -0
  32. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +2 -0
  33. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +37 -45
  34. package/lib/plugin-runtime/im/outbound-ledger.d.ts +24 -0
  35. package/lib/plugin-runtime/im/outbound-ledger.js +114 -0
  36. package/lib/plugin-runtime/im/outbound-projection.d.ts +15 -0
  37. package/lib/plugin-runtime/im/outbound-projection.js +55 -0
  38. package/lib/plugin-runtime/im/outbound-renderer.d.ts +3 -0
  39. package/lib/plugin-runtime/im/outbound-renderer.js +18 -0
  40. package/lib/plugin-runtime/im/outbound-segments.d.ts +3 -0
  41. package/lib/plugin-runtime/im/outbound-segments.js +34 -5
  42. package/package.json +19 -30
@@ -1,2 +1,20 @@
1
- /** Authoring API for Middleware Feature — implementation in `@zhin.js/middleware`. */
2
- export * from '@zhin.js/middleware';
1
+ /**
2
+ * IM authoring defaults; the underlying Feature remains transport independent.
3
+ * @module zhin.js/middleware
4
+ */
5
+ export type { MiddlewareContinuation, MiddlewareDefinitionBase, MiddlewareNext, MiddlewarePhase, MiddlewareTarget, OutboundMiddlewareNext, } from '@zhin.js/middleware';
6
+ import { type MiddlewareAuthoringDefinition, type MiddlewareContext as FeatureMiddlewareContext, type MiddlewareDefinition as FeatureMiddlewareDefinition } from '@zhin.js/middleware';
7
+ import type { Message, OutboundEnvelope } from '../plugin-runtime/im/contracts.js';
8
+ export type MiddlewareContext<TInput = Message, TConfig = unknown, TAdapter extends string | undefined = undefined> = FeatureMiddlewareContext<TInput, TConfig, TAdapter>;
9
+ export type MiddlewareDefinition<TInput = Message, TConfig = unknown, TAdapter extends string | undefined = string | undefined> = FeatureMiddlewareDefinition<TInput, TConfig, TAdapter>;
10
+ /** Incoming IM middleware receives Message; outbound middleware receives its envelope. */
11
+ export declare function defineMiddleware<TInput = OutboundEnvelope, TConfig = unknown>(definition: Extract<MiddlewareAuthoringDefinition<TInput, TConfig>, {
12
+ readonly target: 'outbound';
13
+ }>): Readonly<Extract<FeatureMiddlewareDefinition<TInput, TConfig>, {
14
+ readonly target: 'outbound';
15
+ }>>;
16
+ export declare function defineMiddleware<TInput = Message, TConfig = unknown>(definition: Extract<MiddlewareAuthoringDefinition<TInput, TConfig>, {
17
+ readonly target?: 'inbound';
18
+ }>): Readonly<Extract<FeatureMiddlewareDefinition<TInput, TConfig>, {
19
+ readonly target: 'inbound';
20
+ }>>;
@@ -1,2 +1,6 @@
1
- /** Authoring API for Middleware Feature — implementation in `@zhin.js/middleware`. */
2
- export * from '@zhin.js/middleware';
1
+ import { defineMiddleware as defineFeatureMiddleware, } from '@zhin.js/middleware';
2
+ export function defineMiddleware(definition) {
3
+ // Both overloads deliberately delegate the same validation and feature brand.
4
+ const define = defineFeatureMiddleware;
5
+ return define(definition);
6
+ }
@@ -2,6 +2,7 @@ import type { JSXElement } from '@zhin.js/jsx';
2
2
  import type { PluginId, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
3
3
  import { operationInputBinding } from '@zhin.js/feature-kit';
4
4
  import type { ConversationRef, DeliveryReceipt, MessageRef } from '@zhin.js/im-contract';
5
+ import type { MessageOrigin } from './inbound-origin.js';
5
6
  import type { MediaRef, Segment } from '../../built/segment-contract/types.js';
6
7
  export type { MediaRef, Segment };
7
8
  declare const componentCallBrand: "zhin.component-call/1";
@@ -101,6 +102,12 @@ export interface OutboundMessageService {
101
102
  }
102
103
  export interface MessageDispatchResult {
103
104
  readonly matched: boolean;
105
+ readonly status?: 'unmatched' | 'invalid' | 'denied' | 'executed';
106
+ readonly issues?: readonly Readonly<{
107
+ field: string;
108
+ message: string;
109
+ }>[];
110
+ readonly help?: string;
104
111
  readonly command?: string;
105
112
  readonly owner?: PluginId;
106
113
  readonly value?: unknown;
@@ -111,6 +118,11 @@ export interface MessageBase extends IncomingMessage {
111
118
  readonly metadata: Readonly<Record<string, unknown>>;
112
119
  readonly id?: string;
113
120
  readonly clientAdapter?: string;
121
+ /**
122
+ * 入站来源(self / member / peer_bot / human),仅由 InboundRuntime 可信判定写入;
123
+ * 合成消息(Console / Sandbox / 定时任务)为 undefined。绝不从 metadata / 正文读取。
124
+ */
125
+ readonly origin?: MessageOrigin;
114
126
  readonly $client: unknown;
115
127
  readonly $reply: (content: SendContent) => Promise<DeliveryReceipt>;
116
128
  readonly $replyFrom: (requester: PluginId, content: SendContent) => Promise<DeliveryReceipt>;
@@ -145,6 +157,7 @@ export declare class RuntimeMessage implements MessageBase {
145
157
  readonly id: string;
146
158
  } | undefined;
147
159
  readonly clientAdapter?: string | undefined;
160
+ readonly origin?: MessageOrigin;
148
161
  /** @internal Constructed only by the generation-owned IM Runtime. */
149
162
  constructor(conversation: ConversationRef, content: string, generation: number, reply: (content: SendContent, requester?: PluginId, targetConversation?: ConversationAddress) => Promise<DeliveryReceipt>, sender?: MessageSenderRef | undefined, metadata?: Readonly<Record<string, unknown>>,
150
163
  /**
@@ -159,6 +172,7 @@ export declare class RuntimeMessage implements MessageBase {
159
172
  requester?: PluginId;
160
173
  snapshot?: RuntimeSnapshot;
161
174
  assertActive?: () => void;
175
+ origin?: MessageOrigin;
162
176
  }>);
163
177
  /** @internal A frozen view whose sends retain the current author's exact operation. */
164
178
  [operationInputBinding](owner: PluginId, snapshot: RuntimeSnapshot): RuntimeMessage;
@@ -51,6 +51,7 @@ export class RuntimeMessage {
51
51
  #author;
52
52
  #snapshot;
53
53
  #assertActive;
54
+ origin;
54
55
  /** @internal Constructed only by the generation-owned IM Runtime. */
55
56
  constructor(conversation, content, generation, reply, sender, metadata = Object.freeze({}),
56
57
  /**
@@ -73,6 +74,7 @@ export class RuntimeMessage {
73
74
  this.mentioned = mentioned;
74
75
  this.replyTo = replyTo;
75
76
  this.clientAdapter = clientAdapter;
77
+ this.origin = binding.origin;
76
78
  this.#resolveClient = client;
77
79
  this.#reply = reply;
78
80
  this.#author = binding.requester;
@@ -124,7 +126,7 @@ export class RuntimeMessage {
124
126
  throw new Error(`Unknown Message author: ${owner}`);
125
127
  if (this.#author === owner && this.#snapshot === snapshot)
126
128
  return this;
127
- 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 });
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 });
128
130
  }
129
131
  /** 平台原生消息 id(`message` 未提供时为 undefined)。 */
130
132
  get id() {
@@ -1,6 +1,11 @@
1
- import { type ConversationContextBlock, type ConversationEventReader, type ConversationEventStore, type ConversationReference, type ConversationResolution, type ConversationRef, type DeliveryReceipt } from '@zhin.js/im-contract';
1
+ import { type ConversationContextBlock, type ConversationEventReader, type ConversationEventStore, type ConversationReference, type ConversationResolution, type ConversationRef, type DeliveryReceipt, type MessageRef } from '@zhin.js/im-contract';
2
2
  import type { Notice } from '../../notice.js';
3
3
  import type { IncomingMessage, MessageSenderRef, SendRequest } from './contracts.js';
4
+ /**
5
+ * Backlog messages older than this are dropped from the next turn's context:
6
+ * a stale command from hours ago is not something the current reply should answer.
7
+ */
8
+ export declare const CONVERSATION_CONTEXT_MAX_AGE_MS: number;
4
9
  /** Owns one ImRuntime's conversation fact store, projections, and consumer cursors. */
5
10
  export declare class ConversationRuntime {
6
11
  #private;
@@ -12,6 +17,13 @@ export declare class ConversationRuntime {
12
17
  blocks: readonly ConversationContextBlock[];
13
18
  cursor: number;
14
19
  }>>;
20
+ /**
21
+ * An answer to an interaction prompt (an approval `y`, a menu choice) was
22
+ * already handled by that prompt; replaying it as background would invite
23
+ * the model to answer it again. Kept in memory and bounded: the context age
24
+ * window makes older answers irrelevant anyway.
25
+ */
26
+ markInteractionAnswer(message: MessageRef): void;
15
27
  commitContext(conversation: ConversationRef, consumer: string, cursor: number): Promise<void>;
16
28
  recordIncoming(input: IncomingMessage, sender: MessageSenderRef | undefined): Promise<number | undefined>;
17
29
  recordOutbound(request: SendRequest, receipt: DeliveryReceipt): Promise<void>;
@@ -1,9 +1,17 @@
1
1
  import { MemoryConversationEventStore, conversationRefKey, messageRefKey, } from '@zhin.js/im-contract';
2
2
  import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
3
3
  import { segmentsToPlainText } from '../../built/segment-contract/text.js';
4
+ /**
5
+ * Backlog messages older than this are dropped from the next turn's context:
6
+ * a stale command from hours ago is not something the current reply should answer.
7
+ */
8
+ export const CONVERSATION_CONTEXT_MAX_AGE_MS = 30 * 60 * 1000;
9
+ const MAX_TRACKED_INTERACTION_ANSWERS = 1_000;
4
10
  /** Owns one ImRuntime's conversation fact store, projections, and consumer cursors. */
5
11
  export class ConversationRuntime {
6
12
  #events;
13
+ /** Messages consumed as answers to an interaction prompt (e.g. an approval reply). */
14
+ #interactionAnswers = new Set();
7
15
  constructor(events = new MemoryConversationEventStore()) {
8
16
  this.#events = events;
9
17
  }
@@ -27,11 +35,49 @@ export class ConversationRuntime {
27
35
  }
28
36
  const cursor = await this.#events.getCursor(consumer, conversation);
29
37
  const events = await this.#events.listBetween(conversation, cursor, throughSequence, limit);
38
+ const notBefore = Date.now() - CONVERSATION_CONTEXT_MAX_AGE_MS;
39
+ const relevant = [];
40
+ for (const entry of events) {
41
+ // Only message timestamps are runtime-assigned; notice clocks are adapter-defined.
42
+ if (entry.event.type === 'message.created' && entry.event.timestamp < notBefore)
43
+ continue;
44
+ if (await this.#isOwnRecall(entry.event))
45
+ continue;
46
+ if (entry.event.type === 'message.created'
47
+ && this.#interactionAnswers.has(messageRefKey(entry.event.message.ref)))
48
+ continue;
49
+ relevant.push(entry);
50
+ }
30
51
  return Object.freeze({
31
- blocks: aggregateConversationContext(events, excludeMessageId),
52
+ blocks: aggregateConversationContext(relevant, excludeMessageId),
32
53
  cursor: Math.max(cursor, throughSequence),
33
54
  });
34
55
  }
56
+ /**
57
+ * The bot recalling its own outbound message (e.g. an activity indicator with
58
+ * autoRemove) is self-generated noise, not a conversation fact for the model.
59
+ * Outbound messages are recorded without an actor, which identifies them here.
60
+ */
61
+ async #isOwnRecall(event) {
62
+ if (event.type !== 'message.recalled')
63
+ return false;
64
+ const recalled = await this.#events.getMessage(event.message);
65
+ return recalled !== undefined && recalled.actor === undefined;
66
+ }
67
+ /**
68
+ * An answer to an interaction prompt (an approval `y`, a menu choice) was
69
+ * already handled by that prompt; replaying it as background would invite
70
+ * the model to answer it again. Kept in memory and bounded: the context age
71
+ * window makes older answers irrelevant anyway.
72
+ */
73
+ markInteractionAnswer(message) {
74
+ this.#interactionAnswers.add(messageRefKey(message));
75
+ if (this.#interactionAnswers.size > MAX_TRACKED_INTERACTION_ANSWERS) {
76
+ const oldest = this.#interactionAnswers.values().next().value;
77
+ if (oldest !== undefined)
78
+ this.#interactionAnswers.delete(oldest);
79
+ }
80
+ }
35
81
  commitContext(conversation, consumer, cursor) {
36
82
  return this.#events.commitCursor(consumer, conversation, cursor);
37
83
  }
@@ -1,9 +1,10 @@
1
1
  import { AdapterIndex, type AdapterEndpointPhase, type AdapterOperation, type Endpoint, type EndpointTransportState, type EndpointManagement, type EndpointManagementCapability } from '@zhin.js/adapter';
2
- import type { RuntimeSnapshot, SnapshotLease } from '@zhin.js/plugin-runtime';
3
- import type { ConversationRef, DeliveryReceipt, EndpointCapabilities, MessageRef } from '@zhin.js/im-contract';
2
+ import { type DeliveryTarget, type CapabilityId, type PluginId, type RuntimeSnapshot, type SnapshotLease } from '@zhin.js/plugin-runtime';
3
+ import { type ConversationRef, type DeliveryReceipt, type EndpointCapabilities, type MessageRef } from '@zhin.js/im-contract';
4
4
  import type { ConversationAddress, SendRequest } from './contracts.js';
5
5
  export interface EndpointRuntimeSummary {
6
6
  readonly id: string;
7
+ readonly endpoint: ConversationRef['endpoint'];
7
8
  readonly name: string;
8
9
  readonly adapter: string;
9
10
  readonly owner: string;
@@ -70,6 +71,10 @@ export declare class EndpointRuntime {
70
71
  send(input: RuntimeEndpointSendInput): Promise<{
71
72
  messageId: string;
72
73
  }>;
74
+ /** Resolves a persisted identity exactly in the current operation generation. */
75
+ sendTarget(target: DeliveryTarget, content: unknown, requester?: PluginId): Promise<{
76
+ messageId: string;
77
+ }>;
73
78
  addReaction(input: RuntimeEndpointReactionInput): Promise<string | null>;
74
79
  removeReaction(input: RuntimeEndpointRemoveReactionInput): Promise<void>;
75
80
  recall(input: RuntimeEndpointMessageInput): Promise<void>;
@@ -79,6 +84,6 @@ export declare class EndpointRuntime {
79
84
  }
80
85
  export declare function requireAdapters(snapshot: RuntimeSnapshot): AdapterIndex;
81
86
  /** Resolves public list identities against the exact operation snapshot; ambiguous aliases never pick an account. */
82
- export declare function resolveEndpointIdentity(snapshot: RuntimeSnapshot, index: AdapterIndex, adapter: string, endpointKey: string): import("@zhin.js/plugin-runtime").CapabilityId | undefined;
87
+ export declare function resolveEndpointIdentity(snapshot: RuntimeSnapshot, index: AdapterIndex, adapter: string, endpointKey: string): CapabilityId | undefined;
83
88
  export declare function adapterTypeName(packageName: string | undefined): string | undefined;
84
89
  export {};
@@ -1,4 +1,6 @@
1
1
  import { adapterFeatureId, isAdapterIndex, resolveEndpointManagement, } from '@zhin.js/adapter';
2
+ import { normalizeDeliveryTarget } from '@zhin.js/plugin-runtime';
3
+ import { EndpointDeliveryError, } from '@zhin.js/im-contract';
2
4
  /** Owns generation-leased Endpoint discovery, control, management, and Console delivery. */
3
5
  export class EndpointRuntime {
4
6
  context;
@@ -8,6 +10,7 @@ export class EndpointRuntime {
8
10
  list() {
9
11
  return this.#withLease((snapshot) => requireAdapters(snapshot).describe().map((row) => Object.freeze({
10
12
  id: String(row.id),
13
+ endpoint: Object.freeze({ id: String(row.id), adapter: requireAdapters(snapshot).clientAdapter(row.id) }),
11
14
  name: row.name,
12
15
  adapter: adapterTypeName(snapshot.tree.get(row.owner)?.packageName) ?? row.name,
13
16
  owner: row.owner,
@@ -39,6 +42,7 @@ export class EndpointRuntime {
39
42
  return null;
40
43
  return Object.freeze({
41
44
  name: row.name,
45
+ endpoint: Object.freeze({ id: String(row.id), adapter: index.clientAdapter(row.id) }),
42
46
  adapter: adapterTypeName(snapshot.tree.get(row.owner)?.packageName) ?? row.name,
43
47
  connected: row.connected,
44
48
  admitted: row.admitted,
@@ -60,15 +64,46 @@ export class EndpointRuntime {
60
64
  throw new Error('endpoint not found');
61
65
  const requester = index.owner(resolved);
62
66
  const conversation = {
63
- endpoint: { id: String(resolved), adapter: String(requester) },
64
67
  ...input.conversation,
68
+ endpoint: { id: String(resolved), adapter: index.clientAdapter(resolved) },
65
69
  };
66
70
  const result = await this.context.send({
67
71
  conversation,
68
72
  requester,
69
73
  content: normalizeConsoleContent(input.content),
70
74
  }, lease.value);
71
- return { messageId: result.message?.id ?? '' };
75
+ return requireSentReceipt(result);
76
+ }
77
+ finally {
78
+ this.context.release(lease);
79
+ }
80
+ }
81
+ /** Resolves a persisted identity exactly in the current operation generation. */
82
+ async sendTarget(target, content, requester) {
83
+ const conversation = normalizeDeliveryTarget(target);
84
+ const lease = this.context.acquire();
85
+ try {
86
+ const index = requireAdapters(lease.value);
87
+ const id = conversation.endpoint.id;
88
+ let owner;
89
+ let adapter;
90
+ try {
91
+ owner = index.owner(id);
92
+ adapter = index.clientAdapter(id);
93
+ }
94
+ catch {
95
+ throw new EndpointDeliveryError('endpoint_not_found', 'The saved delivery endpoint no longer exists.', 'not_sent');
96
+ }
97
+ if (adapter !== conversation.endpoint.adapter) {
98
+ throw new EndpointDeliveryError('endpoint_identity_mismatch', 'The saved delivery endpoint belongs to a different adapter.', 'not_sent');
99
+ }
100
+ const result = await this.context.send({
101
+ conversation,
102
+ requester: requester ?? owner,
103
+ // The unified renderer validates JSX, components and native Segments.
104
+ content: content,
105
+ }, lease.value);
106
+ return requireSentReceipt(result);
72
107
  }
73
108
  finally {
74
109
  this.context.release(lease);
@@ -162,7 +197,8 @@ export function resolveEndpointIdentity(snapshot, index, adapter, endpointKey) {
162
197
  const matches = index.list().filter(record => {
163
198
  const localName = record.id.split('\0').pop() ?? record.id;
164
199
  const alias = adapterTypeName(snapshot.tree.get(record.owner)?.packageName);
165
- const adapterMatches = alias === adapter || record.name === adapter || String(record.id) === adapter
200
+ const adapterMatches = index.clientAdapter(record.id) === adapter
201
+ || alias === adapter || record.name === adapter || String(record.id) === adapter
166
202
  || localName === adapter || String(record.owner) === adapter || record.owner.endsWith(`/${adapter}`);
167
203
  const endpointMatches = record.name === endpointKey || String(record.id) === endpointKey
168
204
  || record.id.endsWith(`/${endpointKey}`) || live.get(record.id) === endpointKey;
@@ -182,3 +218,10 @@ function normalizeConsoleContent(content) {
182
218
  return content;
183
219
  return String(content);
184
220
  }
221
+ function requireSentReceipt(result) {
222
+ if (result.status !== 'sent') {
223
+ throw new EndpointDeliveryError(result.failure?.code ?? `outbound_${result.status}`, result.failure?.message ?? 'Outbound delivery was suppressed.', result.failure?.deliveryUnknown ? 'unknown'
224
+ : result.status === 'rejected' ? 'rejected' : 'not_sent');
225
+ }
226
+ return { messageId: result.message?.id ?? '' };
227
+ }
@@ -1,7 +1,7 @@
1
1
  import { Scope, generationAdmissionBinder, type GenerationAdmissionGate, type RuntimeSnapshot, type SnapshotLease, type SnapshotReader } from '@zhin.js/plugin-runtime';
2
2
  import { PermissionHost } from '@zhin.js/permission';
3
3
  import { MessageBus } from './message-bus.js';
4
- import { type EndpointContentResolveContext, type EndpointEventGateway } from '@zhin.js/adapter';
4
+ import { type EndpointContentResolveContext, type EndpointEventGateway, type PeerRegistry } from '@zhin.js/adapter';
5
5
  import { type ConversationEventStore, type ConversationEventReader, type ConversationContextBlock, type ConversationReference, type ConversationResolution, type ConversationRef, type DeliveryReceipt } from '@zhin.js/im-contract';
6
6
  import { Message, type IncomingMessage, type OutboundMessageService, type MessageSenderRef, type SendRequest } from './contracts.js';
7
7
  import { LoginAssist } from '../../built/login-assist.js';
@@ -9,6 +9,7 @@ import type { UserInteraction } from '@zhin.js/interaction';
9
9
  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
+ import { InboundDeduper } from './inbound-dedup.js';
12
13
  /** @public Stable inbound and outbound IM gateway token for Adapter integrations. */
13
14
  export declare const outboundMessageToken: import("@zhin.js/plugin-runtime").Token<OutboundMessageService>;
14
15
  export interface ImRuntimeOptions {
@@ -21,6 +22,16 @@ export interface ImRuntimeOptions {
21
22
  readonly conversationEvents?: ConversationEventStore;
22
23
  /** Process-root ingress claim (pending interaction, authentication challenge, etc.). */
23
24
  readonly inboundClaim?: (message: Message) => boolean | Promise<boolean>;
25
+ /**
26
+ * 探测 `inboundClaim` 这类进程级 prompt 在该 Endpoint 上、对该发送者是否有待回答项。
27
+ * Room Router 用它把消息送到持有待回答状态的成员 Endpoint。必须同步、无副作用。
28
+ * 仓库内没有生产实现;缺省按 false(即 inboundClaim 的待回答不参与 Room 路由)。
29
+ */
30
+ readonly inboundClaimPending?: (conversation: ConversationRef, senderId: string) => boolean;
31
+ /** 覆盖进程级 Peer Registry(测试用,避免污染单例)。 */
32
+ readonly peerRegistry?: Pick<PeerRegistry, 'lookup' | 'isReady' | 'selfOf'>;
33
+ /** @internal 覆盖入站去重器(测试用);去重仅作用于 Room 会话。 */
34
+ readonly inboundDeduper?: Pick<InboundDeduper, 'claim'> & Partial<Pick<InboundDeduper, 'arbitrate'>>;
24
35
  /**
25
36
  * 入站 sender 增强:在构造 Message 前,将框架级角色(master / trusted)
26
37
  * 合并到 sender.roles,使整个下游链路(命令分发、agent ingress 等)都能读到完整角色。
@@ -2,7 +2,7 @@ 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
4
  import { MessageBus, messageBusToken } from './message-bus.js';
5
- import { endpointEventGatewayToken, } from '@zhin.js/adapter';
5
+ import { endpointEventGatewayToken, getProcessPeerRegistry, } from '@zhin.js/adapter';
6
6
  import { loginAssistToken } from './login-assist-host.js';
7
7
  import { LoginAssist } from '../../built/login-assist.js';
8
8
  import { RuntimeInteractionCoordinator } from './interaction-runtime.js';
@@ -11,6 +11,9 @@ import { EndpointRuntime, requireAdapters, } from './endpoint-runtime.js';
11
11
  import { RuntimeMessageEventStream, } from './message-events.js';
12
12
  import { OutboundDeliveryRuntime, failedDeliveryReceipt, } from './outbound-delivery-runtime.js';
13
13
  import { InboundRuntime } from './inbound-runtime.js';
14
+ import { InboundDeduper } from './inbound-dedup.js';
15
+ import { OutboundLedger, ledgerScopeOf } from './outbound-ledger.js';
16
+ import { createInboundOriginClassifier } from './inbound-origin.js';
14
17
  /** @public Stable inbound and outbound IM gateway token for Adapter integrations. */
15
18
  export const outboundMessageToken = createToken('zhin.im.outbound-message');
16
19
  export class ImRuntime {
@@ -27,7 +30,15 @@ export class ImRuntime {
27
30
  #snapshots;
28
31
  constructor(options = {}) {
29
32
  this.#conversations = new ConversationRuntime(options.conversationEvents);
33
+ const ledger = new OutboundLedger();
34
+ const deduper = options.inboundDeduper ?? new InboundDeduper();
35
+ const registry = options.peerRegistry ?? getProcessPeerRegistry();
36
+ const originClassifier = createInboundOriginClassifier({
37
+ registry,
38
+ ledger,
39
+ });
30
40
  this.#outbound = new OutboundDeliveryRuntime({
41
+ ledger: (conversation, receipt, payload) => ledger.record(conversation, receipt, payload),
31
42
  record: (request, receipt) => this.#conversations.recordOutbound(request, receipt),
32
43
  rememberFallback: (conversation, generation, map) => this.#interactions.rememberFallback(conversation, generation, map),
33
44
  publish: (event) => this.#messageEventStream.publish(event),
@@ -36,12 +47,18 @@ export class ImRuntime {
36
47
  this.#inbound = new InboundRuntime({
37
48
  interactions: this.#interactions,
38
49
  inboundClaim: options.inboundClaim,
50
+ originClassifier,
51
+ deduper,
52
+ registry,
53
+ inboundClaimPending: options.inboundClaimPending,
54
+ resolveReplyTarget: (conversation, id) => ledger.matchById(ledgerScopeOf(conversation), id)?.endpointId,
39
55
  enrichSender: options.enrichSender,
40
56
  acquire: () => this.#acquire(),
41
57
  release: (lease) => this.#release(lease),
42
58
  deliver: (request, snapshot) => this.#outbound.deliver(request, snapshot),
43
59
  recordIncoming: (input, sender) => this.#conversations.recordIncoming(input, sender),
44
60
  recordNotice: (notice) => this.#conversations.recordNotice(notice),
61
+ markInteractionAnswer: (message) => this.#conversations.markInteractionAnswer(message),
45
62
  publish: (event) => this.#messageEventStream.publish(event),
46
63
  }, options.commandPrefix);
47
64
  this.endpoints = new EndpointRuntime({
@@ -0,0 +1,51 @@
1
+ import type { ConversationRef } from '@zhin.js/im-contract';
2
+ export type InboundClaim = 'first' | 'same_endpoint' | 'duplicate' | 'unkeyed';
3
+ /** Room Router decision as seen by the deduper (the Endpoint ids only). */
4
+ export interface InboundArbitrationDecision {
5
+ readonly target: string;
6
+ /** Takeover candidates after the target, by priority. */
7
+ readonly fallbacks: readonly string[];
8
+ }
9
+ export type InboundArbitration =
10
+ /** Not keyed (private chat / no sender / no message id): caller keeps per-Endpoint handling. */
11
+ {
12
+ readonly kind: 'unkeyed';
13
+ }
14
+ /** Handle this copy. `routed` is true when the Room Router chose (or a fallback took over for) this Endpoint. */
15
+ | {
16
+ readonly kind: 'handle';
17
+ readonly routed: boolean;
18
+ } | {
19
+ readonly kind: 'duplicate';
20
+ }
21
+ /** Non-target copy that arrived before the target: wait for the target or the grace period. */
22
+ | {
23
+ readonly kind: 'wait';
24
+ readonly target: string;
25
+ /** False when this Endpoint is neither the target nor in `fallbacks` (lowest-priority takeover candidate). */
26
+ readonly listed: boolean;
27
+ readonly settle: () => Promise<'handle' | 'duplicate'>;
28
+ };
29
+ export declare class InboundDeduper {
30
+ #private;
31
+ private readonly now;
32
+ private readonly graceMs;
33
+ constructor(now?: () => number, graceMs?: number);
34
+ get size(): number;
35
+ /**
36
+ * 不变量:本方法完全同步,调用方必须在任何 await 之前调用,
37
+ * 这样 N 个 Endpoint 的并发到达会被原子地判定。
38
+ */
39
+ claim(conversation: ConversationRef, senderId: string, messageId: unknown): InboundClaim;
40
+ /**
41
+ * Room 内按 Router 决策仲裁:目标 Endpoint 的副本处理,其余副本只记录;
42
+ * 但目标可能根本没收到副本(如 Telegram 隐私模式),所以非目标副本不是立刻丢弃,
43
+ * 而是等待目标到达,宽限期(`graceMs`)后由优先级最高的已到达成员 Endpoint 接管。
44
+ *
45
+ * 与 `claim` 同样完全同步(返回的 `settle` 才是异步的),必须在任何 await 之前调用。
46
+ * `compute` 仅在第一个副本到达时调用一次,结果(含 undefined)按消息缓存。
47
+ * `compute` 返回 undefined(无可用成员)时退化为 `claim` 语义:先到先得,同 Endpoint 重投仍处理。
48
+ * decision 之外的 Endpoint 视为最低优先级的接管候选;非成员由 hasRoom 在 core 之外过滤。
49
+ */
50
+ arbitrate(conversation: ConversationRef, senderId: string, messageId: unknown, compute: () => InboundArbitrationDecision | undefined): InboundArbitration;
51
+ }
@@ -0,0 +1,184 @@
1
+ import { ledgerScopeOf } from './outbound-ledger.js';
2
+ /**
3
+ * @internal 入站去重:同一条人类群消息会到达 N 个成员 Endpoint,
4
+ * 按 平台 + 会话 + 发送者 + 平台消息 id 只放行第一个 Endpoint,其余仅记录。
5
+ *
6
+ * 只对 group / channel 生效。私聊刻意排除:部分平台(如 OneBot)的消息 id 是
7
+ * 账号级的,两个 Bot 在同一私聊里可能拿到相同 id 的不同消息,去重会误合并。
8
+ * 缺少发送者或消息 id 时同样不去重(保持原有路由行为)。
9
+ */
10
+ const TTL_MS = 60_000;
11
+ const MAX_ENTRIES = 2000;
12
+ const DEFAULT_GRACE_MS = 2000;
13
+ export class InboundDeduper {
14
+ now;
15
+ graceMs;
16
+ #entries = new Map();
17
+ #arbitrations = new Map();
18
+ constructor(now = Date.now, graceMs = DEFAULT_GRACE_MS) {
19
+ this.now = now;
20
+ this.graceMs = graceMs;
21
+ }
22
+ get size() {
23
+ return this.#entries.size;
24
+ }
25
+ /**
26
+ * 不变量:本方法完全同步,调用方必须在任何 await 之前调用,
27
+ * 这样 N 个 Endpoint 的并发到达会被原子地判定。
28
+ */
29
+ claim(conversation, senderId, messageId) {
30
+ const key = this.#keyOf(conversation, senderId, messageId);
31
+ if (key === undefined)
32
+ return 'unkeyed';
33
+ const at = this.now();
34
+ this.#prune(at);
35
+ const existing = this.#entries.get(key);
36
+ if (existing) {
37
+ return existing.endpointId === conversation.endpoint.id ? 'same_endpoint' : 'duplicate';
38
+ }
39
+ this.#entries.set(key, { endpointId: conversation.endpoint.id, at });
40
+ while (this.#entries.size > MAX_ENTRIES) {
41
+ const oldest = this.#entries.keys().next().value;
42
+ if (oldest === undefined)
43
+ break;
44
+ this.#entries.delete(oldest);
45
+ }
46
+ return 'first';
47
+ }
48
+ /**
49
+ * Room 内按 Router 决策仲裁:目标 Endpoint 的副本处理,其余副本只记录;
50
+ * 但目标可能根本没收到副本(如 Telegram 隐私模式),所以非目标副本不是立刻丢弃,
51
+ * 而是等待目标到达,宽限期(`graceMs`)后由优先级最高的已到达成员 Endpoint 接管。
52
+ *
53
+ * 与 `claim` 同样完全同步(返回的 `settle` 才是异步的),必须在任何 await 之前调用。
54
+ * `compute` 仅在第一个副本到达时调用一次,结果(含 undefined)按消息缓存。
55
+ * `compute` 返回 undefined(无可用成员)时退化为 `claim` 语义:先到先得,同 Endpoint 重投仍处理。
56
+ * decision 之外的 Endpoint 视为最低优先级的接管候选;非成员由 hasRoom 在 core 之外过滤。
57
+ */
58
+ arbitrate(conversation, senderId, messageId, compute) {
59
+ const key = this.#keyOf(conversation, senderId, messageId);
60
+ if (key === undefined)
61
+ return { kind: 'unkeyed' };
62
+ const at = this.now();
63
+ this.#prune(at);
64
+ const endpointId = conversation.endpoint.id;
65
+ let entry = this.#arbitrations.get(key);
66
+ if (!entry) {
67
+ entry = {
68
+ at,
69
+ decision: compute(),
70
+ firstEndpoint: endpointId,
71
+ targetSeen: false,
72
+ takenOverBy: undefined,
73
+ waiters: [],
74
+ timer: undefined,
75
+ };
76
+ this.#arbitrations.set(key, entry);
77
+ while (this.#arbitrations.size > MAX_ENTRIES) {
78
+ const oldest = this.#arbitrations.keys().next().value;
79
+ if (oldest === undefined)
80
+ break;
81
+ this.#evict(oldest);
82
+ }
83
+ }
84
+ const { decision } = entry;
85
+ if (!decision) {
86
+ return entry.firstEndpoint === endpointId
87
+ ? { kind: 'handle', routed: false }
88
+ : { kind: 'duplicate' };
89
+ }
90
+ if (endpointId === decision.target) {
91
+ if (entry.takenOverBy !== undefined)
92
+ return { kind: 'duplicate' };
93
+ entry.targetSeen = true;
94
+ this.#settleWaiters(entry, 'duplicate');
95
+ return { kind: 'handle', routed: true };
96
+ }
97
+ if (entry.takenOverBy !== undefined) {
98
+ return entry.takenOverBy === endpointId ? { kind: 'handle', routed: true } : { kind: 'duplicate' };
99
+ }
100
+ if (entry.targetSeen)
101
+ return { kind: 'duplicate' };
102
+ const target = entry.waiters;
103
+ const settle = new Promise((resolve) => {
104
+ target.push({ endpointId, resolve });
105
+ });
106
+ if (entry.timer === undefined) {
107
+ const owned = entry;
108
+ owned.timer = setTimeout(() => this.#takeOver(owned), this.graceMs);
109
+ owned.timer.unref?.();
110
+ }
111
+ return {
112
+ kind: 'wait',
113
+ target: decision.target,
114
+ listed: decision.fallbacks.includes(endpointId),
115
+ settle: () => settle,
116
+ };
117
+ }
118
+ #keyOf(conversation, senderId, messageId) {
119
+ if (conversation.kind !== 'group' && conversation.kind !== 'channel')
120
+ return undefined;
121
+ if (typeof senderId !== 'string' || senderId === '')
122
+ return undefined;
123
+ if (typeof messageId !== 'string' && typeof messageId !== 'number')
124
+ return undefined;
125
+ const id = String(messageId);
126
+ if (id === '')
127
+ return undefined;
128
+ return `${ledgerScopeOf(conversation)}\0${senderId}\0${id}`;
129
+ }
130
+ #settleWaiters(entry, outcome) {
131
+ if (entry.timer !== undefined)
132
+ clearTimeout(entry.timer);
133
+ entry.timer = undefined;
134
+ const waiters = entry.waiters;
135
+ entry.waiters = [];
136
+ for (const waiter of waiters)
137
+ waiter.resolve(outcome);
138
+ }
139
+ /** Synchronous: the best-priority waiting copy takes over unless the target showed up or someone already did. */
140
+ #takeOver(entry) {
141
+ if (entry.timer !== undefined)
142
+ clearTimeout(entry.timer);
143
+ entry.timer = undefined;
144
+ const waiters = entry.waiters;
145
+ entry.waiters = [];
146
+ const decision = entry.decision;
147
+ if (!decision || entry.targetSeen || entry.takenOverBy !== undefined || waiters.length === 0) {
148
+ for (const waiter of waiters)
149
+ waiter.resolve('duplicate');
150
+ return;
151
+ }
152
+ const rank = (id) => {
153
+ const index = decision.fallbacks.indexOf(id);
154
+ return index === -1 ? decision.fallbacks.length : index;
155
+ };
156
+ let winner = waiters[0];
157
+ for (const waiter of waiters) {
158
+ if (rank(waiter.endpointId) < rank(winner.endpointId))
159
+ winner = waiter;
160
+ }
161
+ entry.takenOverBy = winner.endpointId;
162
+ for (const waiter of waiters)
163
+ waiter.resolve(waiter === winner ? 'handle' : 'duplicate');
164
+ }
165
+ /** Dropping an entry must not strand a waiting copy: resolve it by taking over now. */
166
+ #evict(key) {
167
+ const entry = this.#arbitrations.get(key);
168
+ this.#arbitrations.delete(key);
169
+ if (entry)
170
+ this.#takeOver(entry);
171
+ }
172
+ #prune(at) {
173
+ for (const [key, entry] of this.#arbitrations) {
174
+ if (at - entry.at <= TTL_MS)
175
+ break;
176
+ this.#evict(key);
177
+ }
178
+ for (const [key, entry] of this.#entries) {
179
+ if (at - entry.at <= TTL_MS)
180
+ break;
181
+ this.#entries.delete(key);
182
+ }
183
+ }
184
+ }