@zhin.js/core 1.1.52 → 1.1.54

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 (34) hide show
  1. package/README.md +13 -26
  2. package/lib/built/login-assist.d.ts +12 -3
  3. package/lib/built/login-assist.js +32 -26
  4. package/lib/feature/handler.d.ts +12 -2
  5. package/lib/feature/handler.js +2 -1
  6. package/lib/index.d.ts +3 -1
  7. package/lib/index.js +2 -0
  8. package/lib/plugin-runtime/im/captured-endpoint-operation.d.ts +30 -0
  9. package/lib/plugin-runtime/im/captured-endpoint-operation.js +1 -0
  10. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +8 -1
  11. package/lib/plugin-runtime/im/command-menu-navigation.js +3 -3
  12. package/lib/plugin-runtime/im/contracts.d.ts +69 -48
  13. package/lib/plugin-runtime/im/contracts.js +65 -58
  14. package/lib/plugin-runtime/im/conversation-runtime.d.ts +2 -2
  15. package/lib/plugin-runtime/im/conversation-runtime.js +11 -4
  16. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +9 -14
  17. package/lib/plugin-runtime/im/endpoint-runtime.js +156 -40
  18. package/lib/plugin-runtime/im/group-rule-violation.d.ts +5 -0
  19. package/lib/plugin-runtime/im/im-runtime.d.ts +3 -0
  20. package/lib/plugin-runtime/im/im-runtime.js +30 -5
  21. package/lib/plugin-runtime/im/inbound-runtime.d.ts +2 -0
  22. package/lib/plugin-runtime/im/inbound-runtime.js +138 -33
  23. package/lib/plugin-runtime/im/index.d.ts +1 -1
  24. package/lib/plugin-runtime/im/interaction-operation.d.ts +5 -1
  25. package/lib/plugin-runtime/im/interaction-runtime.d.ts +12 -2
  26. package/lib/plugin-runtime/im/interaction-runtime.js +50 -35
  27. package/lib/plugin-runtime/im/message-dispatcher.js +2 -2
  28. package/lib/plugin-runtime/im/operation-endpoint.d.ts +6 -0
  29. package/lib/plugin-runtime/im/operation-endpoint.js +2 -0
  30. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +2 -2
  31. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +151 -38
  32. package/lib/plugin-runtime/im/outbound-renderer.d.ts +12 -3
  33. package/lib/plugin-runtime/im/outbound-renderer.js +20 -13
  34. package/package.json +14 -14
@@ -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 } from '@zhin.js/feature-kit';
3
+ import { operationInputBinding, operationInputSignal, 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';
@@ -38,6 +38,9 @@ export function isSegmentContent(value) {
38
38
  }
39
39
  /** @internal Generation-scoped implementation of the public Message contract. */
40
40
  export class RuntimeMessage {
41
+ locale;
42
+ commandPrefix;
43
+ commandMenu;
41
44
  conversation;
42
45
  content;
43
46
  generation;
@@ -49,51 +52,32 @@ export class RuntimeMessage {
49
52
  mentioned;
50
53
  replyTo;
51
54
  clientAdapter;
52
- locale;
53
- commandPrefix;
54
- commandMenu;
55
- #resolveClient;
56
- #reply;
57
- #author;
58
- #snapshot;
59
- #assertActive;
60
- #retirementSignal;
61
- #registerOperationView;
62
55
  origin;
63
- /** @internal Constructed only by the generation-owned IM Runtime. */
64
- constructor(conversation, content, generation, reply, sender, metadata = Object.freeze({}),
65
- /**
66
- * 结构化段视图(与 `content` 纯文本视图同源,见 IncomingMessage.segments)。
67
- * Command dispatcher 优先使用此字段,以支持 mention、image 等结构化参数。
68
- */
69
- segments,
70
- /** 结构化入站消息身份(平台原生 message id 经 MessageRef 传递)。 */
71
- message, endpointId, mentioned, replyTo, client = () => {
72
- throw new Error('Message has no Endpoint Client context');
73
- }, clientAdapter, binding = {}) {
56
+ #facts;
57
+ #operation;
58
+ #session;
59
+ /** Core owns these immutable facts; author rebinding shares them and the captured operation. */
60
+ constructor(facts, operation) {
61
+ this.#facts = Object.freeze(facts);
62
+ this.#operation = Object.freeze(operation);
63
+ const { conversation, content, sender, segments, message, endpointId, mentioned, replyTo } = facts;
64
+ const { reply } = operation;
74
65
  this.conversation = conversation;
75
66
  this.content = content;
76
- this.generation = generation;
67
+ this.generation = operation.generation;
77
68
  this.sender = sender;
78
- this.metadata = metadata;
69
+ this.metadata = facts.metadata ?? Object.freeze({});
79
70
  this.segments = segments;
80
71
  this.message = message;
81
72
  this.endpointId = endpointId;
82
73
  this.mentioned = mentioned;
83
74
  this.replyTo = replyTo;
84
- this.clientAdapter = clientAdapter;
85
- this.locale = resolveLocale(binding.locale);
86
- this.origin = binding.origin;
87
- this.#resolveClient = client;
88
- this.#reply = reply;
89
- this.#author = binding.requester;
90
- this.#snapshot = binding.snapshot;
91
- this.#assertActive = binding.assertActive;
92
- this.#retirementSignal = binding.retirementSignal;
93
- this.#registerOperationView = binding.registerOperationView;
94
- if (binding.snapshot)
95
- binding.registerOperationView?.(this, binding.requester ?? binding.snapshot.root);
96
- const requester = binding.requester;
75
+ this.clientAdapter = operation.clientAdapter;
76
+ this.locale = resolveLocale(operation.presentation?.locale);
77
+ this.origin = operation.origin;
78
+ if (operation.snapshot)
79
+ operation.registerOperationView?.(this, operation.requester ?? operation.snapshot.root);
80
+ const requester = operation.requester;
97
81
  this.$reply = (content) => requester === undefined ? reply(content) : reply(content, requester);
98
82
  this.$replyFrom = (requester, content) => reply(content, requester);
99
83
  this.$sendTo = (target, content) => reply(content, requester, target);
@@ -127,38 +111,59 @@ export class RuntimeMessage {
127
111
  ...(threadId ? { threadId } : {}),
128
112
  });
129
113
  };
130
- const commands = binding.commands ?? binding.resolveCommands?.(this);
114
+ const commands = operation.presentation?.commands ?? operation.presentation?.resolveCommands?.(this);
131
115
  this.commandPrefix = commands?.prefix;
132
116
  this.commandMenu = commands?.menu;
117
+ if (operation.session) {
118
+ this.#session = Object.freeze({ ...operation.session,
119
+ reply: (value) => this.$reply(value),
120
+ });
121
+ }
133
122
  Object.freeze(this);
134
123
  }
124
+ /** The same captured data, with reply authority rebound by operationInputBinding. */
125
+ [operationSession]() {
126
+ this.#operation.assertActive?.();
127
+ return this.#session;
128
+ }
135
129
  /** @internal A frozen view whose sends retain the current author's exact operation. */
136
130
  [operationInputBinding](owner, snapshot) {
137
- this.#assertActive?.();
138
- if (snapshot.generation !== this.generation || (this.#snapshot && snapshot !== this.#snapshot)) {
131
+ this.#operation.assertActive?.();
132
+ if (snapshot.generation !== this.generation || (this.#operation.snapshot && snapshot !== this.#operation.snapshot)) {
139
133
  throw new Error('Message author binding belongs to another generation operation');
140
134
  }
141
135
  if (!snapshot.tree.has(owner))
142
136
  throw new Error(`Unknown Message author: ${owner}`);
143
- if (this.#author === owner && this.#snapshot === snapshot)
137
+ if (this.#operation.requester === owner && this.#operation.snapshot === snapshot)
144
138
  return this;
145
- 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, locale: this.locale,
146
- ...(this.commandPrefix !== undefined ? { commands: { prefix: this.commandPrefix, menu: this.commandMenu } } : {}),
147
- assertActive: this.#assertActive, origin: this.origin,
148
- retirementSignal: this.#retirementSignal, registerOperationView: this.#registerOperationView });
139
+ return new RuntimeMessage(this.#facts, {
140
+ ...this.#operation,
141
+ requester: owner,
142
+ snapshot,
143
+ presentation: {
144
+ locale: this.locale,
145
+ ...(this.commandPrefix !== undefined
146
+ ? { commands: { prefix: this.commandPrefix, menu: this.commandMenu } }
147
+ : {}),
148
+ },
149
+ });
149
150
  }
150
- /** @internal Retirement notification; ordinary leased sends may still drain. */
151
+ /** @internal Explicit operation cancellation; replacement alone does not end accepted work. */
151
152
  [operationInputSignal]() {
152
- this.#assertActive?.();
153
- return this.#retirementSignal;
153
+ this.#operation.assertActive?.();
154
+ return this.#operation.signal;
154
155
  }
155
156
  /** @internal The command/handler author's actual leased operation. */
156
157
  [interactionOperationScope]() {
157
- this.#assertActive?.();
158
- return this.#snapshot ? {
159
- snapshot: this.#snapshot,
160
- owner: this.#author ?? this.#snapshot.root,
161
- retirementSignal: this.#retirementSignal,
158
+ this.#operation.assertActive?.();
159
+ return this.#operation.snapshot ? {
160
+ snapshot: this.#operation.snapshot,
161
+ owner: this.#operation.requester ?? this.#operation.snapshot.root,
162
+ signal: this.#operation.signal,
163
+ ...(this.#operation.captureInteraction ? { retain: () => {
164
+ this.#operation.assertActive?.();
165
+ return this.#operation.captureInteraction(this.#operation.requester ?? this.#operation.snapshot.root);
166
+ } } : {}),
162
167
  } : undefined;
163
168
  }
164
169
  /** 平台原生消息 id(`message` 未提供时为 undefined)。 */
@@ -166,12 +171,12 @@ export class RuntimeMessage {
166
171
  return this.message?.id;
167
172
  }
168
173
  formatCommand(localPath, owner) {
169
- this.#assertActive?.();
170
- if (!this.#snapshot)
174
+ this.#operation.assertActive?.();
175
+ if (!this.#operation.snapshot)
171
176
  return undefined;
172
- const commands = this.#snapshot.projections.get(commandFeatureId);
177
+ const commands = this.#operation.snapshot.projections.get(commandFeatureId);
173
178
  return isCommandIndex(commands)
174
- ? commands.formatCommand(owner ?? this.#author ?? this.#snapshot.root, localPath, this.commandPrefix, this.locale)
179
+ ? commands.formatCommand(owner ?? this.#operation.requester ?? this.#operation.snapshot.root, localPath, this.commandPrefix, this.locale)
175
180
  : undefined;
176
181
  }
177
182
  $reply;
@@ -180,7 +185,9 @@ export class RuntimeMessage {
180
185
  * generation-scoped; retaining the returned Client after dispatch is invalid.
181
186
  */
182
187
  get $client() {
183
- return this.#resolveClient();
188
+ if (!this.#operation.client)
189
+ throw new Error('Message has no Endpoint Client context');
190
+ return this.#operation.client();
184
191
  }
185
192
  $replyFrom;
186
193
  /**
@@ -1,4 +1,4 @@
1
- import { type ConversationContextBlock, type ConversationEventReader, type ConversationEventStore, type ConversationReference, type ConversationResolution, type ConversationRef, type DeliveryReceipt, type MessageRef, type SequencedConversationEvent } from '@zhin.js/im-contract';
1
+ import { type ConversationContextBlock, type ConversationEventReader, type ConversationEventStore, type ConversationReference, type ConversationResolution, type ConversationRef, type DeliveryReceipt, type MessageRef, type SequencedConversationEvent, type Segment } from '@zhin.js/im-contract';
2
2
  import type { Notice } from '../../notice.js';
3
3
  import type { Request } from '../../request.js';
4
4
  import type { IncomingMessage, MessageSenderRef, SendRequest } from './contracts.js';
@@ -27,7 +27,7 @@ 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): Promise<void>;
30
+ recordOutbound(request: SendRequest, receipt: DeliveryReceipt, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<void>;
31
31
  /** Records a normalized notice; returns the stored event (with its sequence) when newly appended. */
32
32
  recordNotice(notice: Notice): Promise<SequencedConversationEvent | undefined>;
33
33
  /** Join requests / invitations into a group or channel become `scene.join_requested` (#996). */
@@ -26,7 +26,7 @@ export class ConversationRuntime {
26
26
  if (reference.kind !== 'message')
27
27
  return undefined;
28
28
  const message = await this.#events.getMessage(reference.message);
29
- return message
29
+ return message && message.contentStatus !== 'unavailable'
30
30
  ? Object.freeze({ status: 'resolved', reference, value: message })
31
31
  : undefined;
32
32
  }
@@ -113,7 +113,7 @@ export class ConversationRuntime {
113
113
  }));
114
114
  return appended.sequence;
115
115
  }
116
- async recordOutbound(request, receipt) {
116
+ async recordOutbound(request, receipt, canonicalContent) {
117
117
  if (receipt.status !== 'sent' || !receipt.message?.id)
118
118
  return;
119
119
  const timestamp = Date.now();
@@ -124,8 +124,12 @@ export class ConversationRuntime {
124
124
  type: 'message.created',
125
125
  message: Object.freeze({
126
126
  ref: receipt.message,
127
- segments: segmentsFromContent(request.content),
127
+ segments: canonicalContent === 'unavailable' ? [] : canonicalContent ?? segmentsFromContent(request.content),
128
+ ...(canonicalContent === 'unavailable' ? { contentStatus: 'unavailable' } : {}),
128
129
  timestamp,
130
+ ...(canonicalContent !== 'unavailable' && canonicalContent?.length && canonicalContent.every(segment => segment.type === 'text') && receipt.outboundTextDigest ? {
131
+ outboundTextDigest: receipt.outboundTextDigest,
132
+ } : {}),
129
133
  }),
130
134
  }));
131
135
  }
@@ -308,6 +312,8 @@ function aggregateConversationContext(events, excluded) {
308
312
  sequence,
309
313
  eventType: event.type,
310
314
  text,
315
+ message: event.message.ref,
316
+ ...(event.message.outboundTextDigest ? { messageTextDigest: event.message.outboundTextDigest } : {}),
311
317
  }));
312
318
  continue;
313
319
  }
@@ -388,7 +394,8 @@ function describeConversationMessage(message) {
388
394
  const attachmentNote = attachmentTypes.length > 0
389
395
  ? ` [message also contains ${attachmentTypes.join(', ')} data; inspect its reference before relying on that content]`
390
396
  : '';
391
- return `${actor} [message_id=${JSON.stringify(message.ref.id)}]: ${text || '(no plain-text content)'}${attachmentNote}`;
397
+ return `${actor} [message_id=${JSON.stringify(message.ref.id)}]: ${message.contentStatus === 'unavailable'
398
+ ? '[Message content unavailable; inspect its reference.]' : text || '(no plain-text content)'}${attachmentNote}`;
392
399
  }
393
400
  function segmentsFromContent(content) {
394
401
  if (Array.isArray(content)) {
@@ -1,5 +1,7 @@
1
- import { AdapterIndex, type AdapterEndpointPhase, type AdapterOperation, type Endpoint, type EndpointTransportState, type EndpointManagement, type EndpointManagementCapability } from '@zhin.js/adapter';
2
- import { type DeliveryTarget, type CapabilityId, type PluginId, type RuntimeSnapshot, type SnapshotLease, type Locale } from '@zhin.js/plugin-runtime';
1
+ import type { CaptureEndpointOperationInput, CapturedEndpointOperation } from './captured-endpoint-operation.js';
2
+ export type { CaptureEndpointOperationInput, CapturedEndpointOperation } from './captured-endpoint-operation.js';
3
+ import { AdapterIndex, type AdapterEndpointPhase, type AdapterOperation, type AdapterEndpointSummary, type EndpointTransportState, type EndpointManagement, type EndpointManagementCapability } from '@zhin.js/adapter';
4
+ import { type DeliveryTarget, type PluginId, type RuntimeSnapshot, type SnapshotLease, type Locale } from '@zhin.js/plugin-runtime';
3
5
  import { type ConversationRef, type DeliveryReceipt, type EndpointCapabilities, type MessageRef } from '@zhin.js/im-contract';
4
6
  import type { ConversationAddress, SendRequest } from './contracts.js';
5
7
  export interface EndpointRuntimeSummary {
@@ -11,7 +13,7 @@ export interface EndpointRuntimeSummary {
11
13
  readonly connected: boolean;
12
14
  readonly admitted: boolean;
13
15
  readonly transportState: EndpointTransportState | 'unknown';
14
- readonly eventDiagnostics: Endpoint['eventDiagnostics'];
16
+ readonly eventDiagnostics: AdapterEndpointSummary['eventDiagnostics'];
15
17
  readonly status: 'online' | 'offline';
16
18
  readonly phase: AdapterEndpointPhase;
17
19
  readonly operations: readonly AdapterOperation[];
@@ -26,35 +28,29 @@ export interface RuntimeEndpointSendInput {
26
28
  readonly content: unknown;
27
29
  }
28
30
  export interface RuntimeEndpointReactionInput {
29
- readonly adapter: string;
30
- readonly endpointKey: string;
31
31
  readonly message: MessageRef;
32
32
  readonly emoji: string;
33
33
  readonly sceneType?: string;
34
34
  readonly channelId?: string;
35
35
  }
36
36
  export interface RuntimeEndpointRemoveReactionInput {
37
- readonly adapter: string;
38
- readonly endpointKey: string;
39
37
  readonly message: MessageRef;
40
38
  readonly reactionId: string;
41
39
  }
42
40
  export interface RuntimeEndpointMessageInput {
43
- readonly adapter: string;
44
- readonly endpointKey: string;
45
41
  readonly message: MessageRef;
46
42
  }
47
43
  export interface RuntimeEndpointEditInput extends RuntimeEndpointMessageInput {
48
44
  readonly content: unknown;
49
45
  }
50
46
  export interface RuntimeEndpointTypingInput {
51
- readonly adapter: string;
52
- readonly endpointKey: string;
53
47
  readonly conversation: ConversationRef;
54
48
  readonly active?: boolean;
55
49
  }
56
50
  interface EndpointRuntimeContext {
57
51
  acquire(): SnapshotLease;
52
+ /** Independently retain the current operation snapshot for detached source work. */
53
+ retain(): SnapshotLease;
58
54
  release(lease: SnapshotLease): void;
59
55
  send(request: SendRequest, snapshot: RuntimeSnapshot): Promise<DeliveryReceipt>;
60
56
  }
@@ -69,6 +65,8 @@ export declare class EndpointRuntime {
69
65
  readonly endpointKey: string;
70
66
  }): EndpointCapabilities | undefined;
71
67
  get(adapter: string, endpointKey: string): EndpointRuntimeDetail | null;
68
+ /** Retain the actual ingress Client instead of resolving the latest account when work settles. */
69
+ captureOperation(input: CaptureEndpointOperationInput): CapturedEndpointOperation;
72
70
  send(input: RuntimeEndpointSendInput): Promise<{
73
71
  messageId: string;
74
72
  }>;
@@ -86,7 +84,4 @@ export declare class EndpointRuntime {
86
84
  withManagement<T>(adapter: string, endpointKey: string, run: (management: EndpointManagement) => T | Promise<T>): Promise<T | null>;
87
85
  }
88
86
  export declare function requireAdapters(snapshot: RuntimeSnapshot): AdapterIndex;
89
- /** Resolves public list identities against the exact operation snapshot; ambiguous aliases never pick an account. */
90
- export declare function resolveEndpointIdentity(snapshot: RuntimeSnapshot, index: AdapterIndex, adapter: string, endpointKey: string): CapabilityId | undefined;
91
87
  export declare function adapterTypeName(packageName: string | undefined): string | undefined;
92
- export {};
@@ -1,4 +1,5 @@
1
- import { adapterFeatureId, isAdapterIndex, resolveEndpointManagement, } from '@zhin.js/adapter';
1
+ import { operationEndpoint } from './operation-endpoint.js';
2
+ import { adapterFeatureId, isAdapterIndex, } from '@zhin.js/adapter';
2
3
  import { normalizeDeliveryTarget } from '@zhin.js/plugin-runtime';
3
4
  import { EndpointDeliveryError, } from '@zhin.js/im-contract';
4
5
  /** Owns generation-leased Endpoint discovery, control, management, and Console delivery. */
@@ -27,14 +28,14 @@ export class EndpointRuntime {
27
28
  capabilities(input) {
28
29
  return this.#withLease((snapshot) => {
29
30
  const index = requireAdapters(snapshot);
30
- const id = resolveEndpointIdentity(snapshot, index, input.adapter, input.endpointKey);
31
+ const id = index.resolve(input.adapter, input.endpointKey);
31
32
  return id ? index.capabilities(id) : undefined;
32
33
  }, undefined);
33
34
  }
34
35
  get(adapter, endpointKey) {
35
36
  return this.#withLease((snapshot) => {
36
37
  const index = requireAdapters(snapshot);
37
- const id = resolveEndpointIdentity(snapshot, index, adapter, endpointKey);
38
+ const id = index.resolve(adapter, endpointKey);
38
39
  if (!id)
39
40
  return null;
40
41
  const row = index.describe().find((item) => item.id === id);
@@ -55,11 +56,116 @@ export class EndpointRuntime {
55
56
  });
56
57
  }, null);
57
58
  }
59
+ /** Retain the actual ingress Client instead of resolving the latest account when work settles. */
60
+ captureOperation(input) {
61
+ const target = normalizeDeliveryTarget(input.target);
62
+ const snapshot = this.context.retain();
63
+ let child;
64
+ try {
65
+ const index = requireAdapters(snapshot.value);
66
+ const id = target.endpoint.id;
67
+ if (index.clientAdapter(id) !== target.endpoint.adapter) {
68
+ throw new EndpointDeliveryError('endpoint_identity_mismatch', 'Source belongs to another adapter.', 'not_sent');
69
+ }
70
+ const callerSignal = input.signal
71
+ ? AbortSignal.any([snapshot.stopSignal, input.signal]) : snapshot.stopSignal;
72
+ child = index.acquireInbound(id, input.client, callerSignal);
73
+ const captured = child;
74
+ let released = false;
75
+ let calls = 0;
76
+ const releaseResources = () => {
77
+ try {
78
+ captured.release();
79
+ }
80
+ finally {
81
+ if (snapshot.active)
82
+ this.context.release(snapshot);
83
+ }
84
+ };
85
+ const assertActive = () => {
86
+ if (released || !snapshot.active)
87
+ throw new EndpointDeliveryError('operation_scope_ended', 'Retained operation has ended.', 'not_sent');
88
+ captured.assertActive();
89
+ };
90
+ // The capture stops admitting on release; accepted calls retain its source and Root to drain.
91
+ const retainCall = () => {
92
+ calls += 1;
93
+ return () => { if (--calls === 0 && released)
94
+ releaseResources(); };
95
+ };
96
+ const scope = { assertActive, signal: captured.signal, retain: retainCall };
97
+ const requester = input.requester ?? index.owner(id);
98
+ const capabilities = index.capabilities(id);
99
+ const declared = ['recall', 'edit', 'reaction', 'typing'].find(operation => capabilities.operations?.[operation]);
100
+ const port = declared ? index.control(id, declared, scope) : undefined;
101
+ const controls = port && Object.freeze({
102
+ ...(port.recall ? { recall: async (request) => {
103
+ assertSameEndpoint(target, request.message.conversation);
104
+ return port.recall(request);
105
+ } } : {}),
106
+ ...(port.edit ? { edit: async (request) => {
107
+ assertSameEndpoint(target, request.message.conversation);
108
+ return port.edit(request);
109
+ } } : {}),
110
+ ...(port.addReaction ? { addReaction: async (request) => {
111
+ assertSameEndpoint(target, request.message.conversation);
112
+ return port.addReaction(request);
113
+ } } : {}),
114
+ ...(port.removeReaction ? { removeReaction: async (request) => {
115
+ assertSameEndpoint(target, request.message.conversation);
116
+ return port.removeReaction(request);
117
+ } } : {}),
118
+ ...(port.typing ? { typing: async (request) => {
119
+ assertSameEndpoint(target, request.conversation);
120
+ return port.typing(request);
121
+ } } : {}),
122
+ });
123
+ return Object.freeze({
124
+ target, signal: captured.signal, control: controls,
125
+ management: index.management(id, scope),
126
+ send: async (content, options) => {
127
+ assertActive();
128
+ // Retain the source authority, while each send owns its caller cancellation.
129
+ const releaseCall = retainCall();
130
+ try {
131
+ const sendLease = index.acquire(id, options?.signal
132
+ ? AbortSignal.any([captured.signal, options.signal]) : captured.signal, captured.endpoint);
133
+ try {
134
+ return await this.context.send({ conversation: target, requester, content,
135
+ ...(options?.locale ? { locale: options.locale } : {}), [operationEndpoint]: sendLease }, snapshot.value);
136
+ }
137
+ finally {
138
+ sendLease.release();
139
+ }
140
+ }
141
+ finally {
142
+ releaseCall();
143
+ }
144
+ },
145
+ release: () => {
146
+ if (released)
147
+ return;
148
+ released = true;
149
+ if (!calls)
150
+ releaseResources();
151
+ },
152
+ });
153
+ }
154
+ catch (error) {
155
+ try {
156
+ child?.release();
157
+ }
158
+ finally {
159
+ this.context.release(snapshot);
160
+ }
161
+ throw error;
162
+ }
163
+ }
58
164
  async send(input) {
59
165
  const lease = this.context.acquire();
60
166
  try {
61
167
  const index = requireAdapters(lease.value);
62
- const resolved = resolveEndpointIdentity(lease.value, index, input.adapter, input.endpointKey);
168
+ const resolved = index.resolve(input.adapter, input.endpointKey);
63
169
  if (!resolved)
64
170
  throw new Error('endpoint not found');
65
171
  const requester = index.owner(resolved);
@@ -112,22 +218,26 @@ export class EndpointRuntime {
112
218
  }
113
219
  }
114
220
  async addReaction(input) {
115
- return this.#withControl(input.adapter, input.endpointKey, 'reaction', (control) => control.addReaction?.(input.message, input.emoji, {
116
- sceneType: input.sceneType,
117
- channelId: input.channelId,
118
- }) ?? null, null);
221
+ return this.#withControl({ target: input.message.conversation, method: 'addReaction',
222
+ run: control => control.addReaction({ message: input.message, emoji: input.emoji, hint: {
223
+ sceneType: input.sceneType, channelId: input.channelId,
224
+ } }) });
119
225
  }
120
226
  async removeReaction(input) {
121
- await this.#withControl(input.adapter, input.endpointKey, 'reaction', (control) => control.removeReaction?.(input.message, input.reactionId), undefined);
227
+ await this.#withControl({ target: input.message.conversation, method: 'removeReaction',
228
+ run: control => control.removeReaction({ message: input.message, reactionId: input.reactionId }) });
122
229
  }
123
230
  async recall(input) {
124
- await this.#withControl(input.adapter, input.endpointKey, 'recall', (control) => control.recall?.(input.message), undefined);
231
+ await this.#withControl({ target: input.message.conversation, method: 'recall',
232
+ run: control => control.recall({ message: input.message }) });
125
233
  }
126
234
  async edit(input) {
127
- return this.#withControl(input.adapter, input.endpointKey, 'edit', (control) => control.edit?.(input.message, input.content) ?? null, null);
235
+ return this.#withControl({ target: input.message.conversation, method: 'edit',
236
+ run: control => control.edit({ message: input.message, content: input.content }) });
128
237
  }
129
238
  async typing(input) {
130
- await this.#withControl(input.adapter, input.endpointKey, 'typing', (control) => control.typing?.(input.conversation, input.active), undefined);
239
+ await this.#withControl({ target: input.conversation, method: 'typing',
240
+ run: control => control.typing({ conversation: input.conversation, active: input.active }) });
131
241
  }
132
242
  async withManagement(adapter, endpointKey, run) {
133
243
  let lease;
@@ -139,29 +249,44 @@ export class EndpointRuntime {
139
249
  }
140
250
  try {
141
251
  const index = requireAdapters(lease.value);
142
- const id = resolveEndpointIdentity(lease.value, index, adapter, endpointKey);
252
+ const id = index.resolve(adapter, endpointKey);
143
253
  const endpoint = id ? index.connection(String(id), String(id)) : undefined;
144
254
  if (!endpoint)
145
255
  return null;
146
- return await run(resolveEndpointManagement(endpoint) ?? Object.freeze({}));
256
+ return await run(index.management(id, { assertActive: () => {
257
+ if (!lease.active)
258
+ throw new EndpointDeliveryError('operation_scope_ended', 'Management operation scope has ended', 'not_sent');
259
+ } }) ?? Object.freeze({}));
147
260
  }
148
261
  finally {
149
262
  this.context.release(lease);
150
263
  }
151
264
  }
152
- async #withControl(adapter, endpointKey, operation, run, fallback) {
153
- let lease;
154
- try {
155
- lease = this.context.acquire();
156
- }
157
- catch {
158
- return fallback;
159
- }
265
+ async #withControl({ target: source, method, run }) {
266
+ const target = normalizeDeliveryTarget(source);
267
+ const lease = this.context.acquire();
160
268
  try {
161
269
  const index = requireAdapters(lease.value);
162
- const id = resolveEndpointIdentity(lease.value, index, adapter, endpointKey);
163
- const control = id ? index.control(id, operation) : undefined;
164
- return control ? await run(control) : fallback;
270
+ const id = target.endpoint.id;
271
+ let actualAdapter;
272
+ try {
273
+ actualAdapter = index.clientAdapter(id);
274
+ }
275
+ catch {
276
+ throw new EndpointDeliveryError('endpoint_not_found', 'The referenced account no longer exists.', 'not_sent');
277
+ }
278
+ if (actualAdapter !== target.endpoint.adapter) {
279
+ throw new EndpointDeliveryError('endpoint_identity_mismatch', 'Message reference belongs to another adapter.', 'not_sent');
280
+ }
281
+ const operation = method === 'addReaction' || method === 'removeReaction' ? 'reaction' : method;
282
+ const control = index.control(id, operation, { assertActive: () => {
283
+ if (!lease.active)
284
+ throw new EndpointDeliveryError('operation_scope_ended', 'Control operation has ended.', 'not_sent');
285
+ } });
286
+ if (!control || typeof control[method] !== 'function') {
287
+ throw new EndpointDeliveryError('unsupported_operation', `Endpoint does not support ${method}.`, 'not_sent');
288
+ }
289
+ return await run(control);
165
290
  }
166
291
  finally {
167
292
  this.context.release(lease);
@@ -193,21 +318,6 @@ export function requireAdapters(snapshot) {
193
318
  }
194
319
  return projection;
195
320
  }
196
- /** Resolves public list identities against the exact operation snapshot; ambiguous aliases never pick an account. */
197
- export function resolveEndpointIdentity(snapshot, index, adapter, endpointKey) {
198
- const live = new Map(index.describe().map(row => [row.id, row.name]));
199
- const matches = index.list().filter(record => {
200
- const localName = record.id.split('\0').pop() ?? record.id;
201
- const alias = adapterTypeName(snapshot.tree.get(record.owner)?.packageName);
202
- const adapterMatches = index.clientAdapter(record.id) === adapter
203
- || alias === adapter || record.name === adapter || String(record.id) === adapter
204
- || localName === adapter || String(record.owner) === adapter || record.owner.endsWith(`/${adapter}`);
205
- const endpointMatches = record.name === endpointKey || String(record.id) === endpointKey
206
- || record.id.endsWith(`/${endpointKey}`) || live.get(record.id) === endpointKey;
207
- return adapterMatches && endpointMatches;
208
- });
209
- return matches.length === 1 ? matches[0].id : undefined;
210
- }
211
321
  export function adapterTypeName(packageName) {
212
322
  if (!packageName)
213
323
  return undefined;
@@ -227,3 +337,9 @@ function requireSentReceipt(result) {
227
337
  }
228
338
  return { messageId: result.message?.id ?? '' };
229
339
  }
340
+ /** A canonical message/address cannot be redirected by a second endpoint selector. */
341
+ function assertSameEndpoint(expected, actual) {
342
+ if (expected.endpoint.id !== actual.endpoint.id || expected.endpoint.adapter !== actual.endpoint.adapter) {
343
+ throw new EndpointDeliveryError('endpoint_identity_mismatch', 'Message reference belongs to another Endpoint.', 'not_sent');
344
+ }
345
+ }
@@ -3,6 +3,11 @@ import type { ConversationRef } from '@zhin.js/im-contract';
3
3
  export type GroupRuleViolationTrigger = 'advertising' | 'abuse';
4
4
  /** @public */
5
5
  export interface GroupRuleViolationReport {
6
+ /** Runtime-only authority captured from the actual incoming Client; never persist this object. */
7
+ readonly source: Readonly<{
8
+ client: unknown;
9
+ signal: AbortSignal;
10
+ }>;
6
11
  /** 违规消息所在的群会话(`kind` 必须是 `group`)。 */
7
12
  readonly conversation: ConversationRef;
8
13
  readonly memberId: string;
@@ -7,6 +7,7 @@ import { Message, type IncomingMessage, type OutboundMessageService, type Messag
7
7
  import { LoginAssist } from '../../built/login-assist.js';
8
8
  import type { UserInteraction } from '@zhin.js/interaction';
9
9
  import type { OutboundRenderer } from './outbound-renderer.js';
10
+ import { type PendingUserInteraction } from './interaction-runtime.js';
10
11
  import { EndpointRuntime } from './endpoint-runtime.js';
11
12
  import { type RuntimeMessageEventSource, type RuntimeSceneEventSource } from './message-events.js';
12
13
  import { InboundDeduper } from './inbound-dedup.js';
@@ -82,6 +83,8 @@ export declare class ImRuntime implements OutboundMessageService {
82
83
  createInteraction(message: Message, bind?: {
83
84
  readonly subjectId: string;
84
85
  }): UserInteraction | undefined;
86
+ /** Reads a prompt within the caller's current generation lease; answering uses the original IM ingress. */
87
+ readPendingInteraction(conversation: ConversationRef, subjectId: string, generation: number): PendingUserInteraction | undefined;
85
88
  send(request: SendRequest): Promise<DeliveryReceipt>;
86
89
  /** Sends through the exact generation lease that admitted the current operation. */
87
90
  sendWithSnapshotLease(lease: SnapshotLease, request: SendRequest): Promise<DeliveryReceipt>;