@zhin.js/core 1.1.53 → 1.1.55

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 (41) hide show
  1. package/README.md +13 -26
  2. package/lib/built/interaction-messages.d.ts +1 -1
  3. package/lib/built/login-assist.d.ts +12 -3
  4. package/lib/built/login-assist.js +32 -26
  5. package/lib/feature/handler.d.ts +12 -2
  6. package/lib/feature/handler.js +2 -1
  7. package/lib/index.d.ts +3 -1
  8. package/lib/index.js +2 -0
  9. package/lib/jsx/message-tags.d.ts +3 -3
  10. package/lib/jsx/message-tags.js +3 -0
  11. package/lib/plugin-runtime/im/captured-endpoint-operation.d.ts +34 -0
  12. package/lib/plugin-runtime/im/captured-endpoint-operation.js +1 -0
  13. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +8 -1
  14. package/lib/plugin-runtime/im/command-menu-navigation.js +3 -3
  15. package/lib/plugin-runtime/im/contracts.d.ts +69 -48
  16. package/lib/plugin-runtime/im/contracts.js +65 -58
  17. package/lib/plugin-runtime/im/conversation-runtime.d.ts +2 -0
  18. package/lib/plugin-runtime/im/conversation-runtime.js +41 -4
  19. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +13 -15
  20. package/lib/plugin-runtime/im/endpoint-runtime.js +194 -42
  21. package/lib/plugin-runtime/im/group-rule-violation.d.ts +5 -0
  22. package/lib/plugin-runtime/im/im-runtime.d.ts +3 -0
  23. package/lib/plugin-runtime/im/im-runtime.js +33 -7
  24. package/lib/plugin-runtime/im/inbound-runtime.d.ts +2 -0
  25. package/lib/plugin-runtime/im/inbound-runtime.js +138 -33
  26. package/lib/plugin-runtime/im/index.d.ts +2 -1
  27. package/lib/plugin-runtime/im/interaction-operation.d.ts +5 -1
  28. package/lib/plugin-runtime/im/interaction-runtime.d.ts +12 -2
  29. package/lib/plugin-runtime/im/interaction-runtime.js +50 -35
  30. package/lib/plugin-runtime/im/message-dispatcher.js +2 -2
  31. package/lib/plugin-runtime/im/operation-endpoint.d.ts +6 -0
  32. package/lib/plugin-runtime/im/operation-endpoint.js +2 -0
  33. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +16 -2
  34. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +86 -20
  35. package/lib/plugin-runtime/im/outbound-renderer.d.ts +12 -3
  36. package/lib/plugin-runtime/im/outbound-renderer.js +20 -13
  37. package/lib/plugin-runtime/im/progressive-reply.d.ts +52 -0
  38. package/lib/plugin-runtime/im/progressive-reply.js +495 -0
  39. package/lib/plugin-runtime/im/runtime-middleware.d.ts +2 -0
  40. package/lib/plugin-runtime/im/runtime-middleware.js +5 -0
  41. package/package.json +15 -15
@@ -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
  /**
@@ -28,6 +28,8 @@ export declare class ConversationRuntime {
28
28
  commitContext(conversation: ConversationRef, consumer: string, cursor: number): Promise<void>;
29
29
  recordIncoming(input: IncomingMessage, sender: MessageSenderRef | undefined): Promise<number | undefined>;
30
30
  recordOutbound(request: SendRequest, receipt: DeliveryReceipt, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<void>;
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>;
31
33
  /** Records a normalized notice; returns the stored event (with its sequence) when newly appended. */
32
34
  recordNotice(notice: Notice): Promise<SequencedConversationEvent | undefined>;
33
35
  /** 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 && message.contentStatus !== 'unavailable'
29
+ return message && !message.recalled && message.contentStatus !== 'unavailable'
30
30
  ? Object.freeze({ status: 'resolved', reference, value: message })
31
31
  : undefined;
32
32
  }
@@ -42,14 +42,14 @@ export class ConversationRuntime {
42
42
  const excluded = new Set(excludeMessageId ? [excludeMessageId] : []);
43
43
  for (const entry of events) {
44
44
  // Only message timestamps are runtime-assigned; notice clocks are adapter-defined.
45
- if (entry.event.type === 'message.created' && entry.event.timestamp < notBefore)
45
+ if ((entry.event.type === 'message.created' || entry.event.type === 'message.updated') && entry.event.timestamp < notBefore)
46
46
  continue;
47
47
  if (await this.#isOwnRecall(entry.event)) {
48
48
  if (entry.event.type === 'message.recalled')
49
49
  excluded.add(entry.event.message.id);
50
50
  continue;
51
51
  }
52
- if (entry.event.type === 'message.created'
52
+ if ((entry.event.type === 'message.created' || entry.event.type === 'message.updated')
53
53
  && this.#interactionAnswers.has(messageRefKey(entry.event.message.ref)))
54
54
  continue;
55
55
  relevant.push(entry);
@@ -133,6 +133,24 @@ export class ConversationRuntime {
133
133
  }),
134
134
  }));
135
135
  }
136
+ /** Records a confirmed replacement body without inventing another physical message. */
137
+ async recordOutboundUpdate(request, receipt, revision, canonicalContent) {
138
+ if (receipt.status !== 'sent' || !receipt.message?.id)
139
+ return;
140
+ const original = await this.#events.getMessage(receipt.message);
141
+ if (!original)
142
+ throw new Error('Cannot record an update before its original message');
143
+ const { contentStatus: _status, outboundTextDigest: _digest, ...identity } = original;
144
+ await this.#events.append(Object.freeze({
145
+ eventId: `message:${messageRefKey(receipt.message)}:revision:${revision}`,
146
+ conversation: request.conversation, timestamp: Date.now(), type: 'message.updated',
147
+ message: Object.freeze({ ...identity, revision,
148
+ segments: canonicalContent === 'unavailable' ? [] : canonicalContent ?? segmentsFromContent(request.content),
149
+ ...(canonicalContent === 'unavailable' ? { contentStatus: 'unavailable' } : {}),
150
+ ...(canonicalContent !== 'unavailable' && canonicalContent?.length && canonicalContent.every(segment => segment.type === 'text') && receipt.outboundTextDigest
151
+ ? { outboundTextDigest: receipt.outboundTextDigest } : {}), }),
152
+ }));
153
+ }
136
154
  /** Records a normalized notice; returns the stored event (with its sequence) when newly appended. */
137
155
  async recordNotice(notice) {
138
156
  const event = conversationEventFromNotice(notice);
@@ -297,11 +315,29 @@ function conversationEventFromNotice(notice) {
297
315
  function aggregateConversationContext(events, excluded) {
298
316
  const ordinary = [];
299
317
  const noisy = new Map();
318
+ const latestMessages = new Map();
319
+ const recalled = new Set();
320
+ for (const entry of events) {
321
+ const event = entry.event;
322
+ if (event.type === 'message.recalled')
323
+ recalled.add(messageRefKey(event.message));
324
+ if (event.type !== 'message.created' && event.type !== 'message.updated')
325
+ continue;
326
+ const key = messageRefKey(event.message.ref), previous = latestMessages.get(key);
327
+ if (recalled.has(key))
328
+ continue;
329
+ const previousRevision = previous && (previous.event.type === 'message.created' || previous.event.type === 'message.updated')
330
+ ? previous.event.message.revision ?? 0 : -1;
331
+ if ((event.message.revision ?? 0) > previousRevision)
332
+ latestMessages.set(key, entry);
333
+ }
300
334
  for (const { sequence, event } of events) {
301
335
  // #996: these reach the model only through the short ephemeral `[Scene events]` block.
302
336
  if (SCENE_ONLY_EVENT_TYPES.has(event.type))
303
337
  continue;
304
- if (event.type === 'message.created') {
338
+ if (event.type === 'message.created' || event.type === 'message.updated') {
339
+ if (latestMessages.get(messageRefKey(event.message.ref))?.sequence !== sequence)
340
+ continue;
305
341
  if (excluded.has(event.message.ref.id))
306
342
  continue;
307
343
  const text = describeConversationMessage(event.message);
@@ -365,6 +401,7 @@ function describeConversationEvent(event) {
365
401
  case 'member.role_changed':
366
402
  return `${event.member.displayName ?? event.member.id} (${event.member.id}) role ${event.role} was ${event.enabled ? 'enabled' : 'disabled'}${actor ? ` by ${actor}` : ''}.`;
367
403
  case 'message.created':
404
+ case 'message.updated':
368
405
  case 'scene.join_requested':
369
406
  case 'scene.notice_updated':
370
407
  case 'member.card_changed':
@@ -1,5 +1,8 @@
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 { OutboundDeliveryExecution } from './outbound-delivery-runtime.js';
2
+ import type { CaptureEndpointOperationInput, CapturedEndpointOperation } from './captured-endpoint-operation.js';
3
+ export type { CaptureEndpointOperationInput, CapturedEndpointOperation } from './captured-endpoint-operation.js';
4
+ import { AdapterIndex, type AdapterEndpointPhase, type AdapterOperation, type AdapterEndpointSummary, type EndpointTransportState, type EndpointManagement, type EndpointManagementCapability } from '@zhin.js/adapter';
5
+ import { type DeliveryTarget, type PluginId, type RuntimeSnapshot, type SnapshotLease, type Locale } from '@zhin.js/plugin-runtime';
3
6
  import { type ConversationRef, type DeliveryReceipt, type EndpointCapabilities, type MessageRef } from '@zhin.js/im-contract';
4
7
  import type { ConversationAddress, SendRequest } from './contracts.js';
5
8
  export interface EndpointRuntimeSummary {
@@ -11,7 +14,7 @@ export interface EndpointRuntimeSummary {
11
14
  readonly connected: boolean;
12
15
  readonly admitted: boolean;
13
16
  readonly transportState: EndpointTransportState | 'unknown';
14
- readonly eventDiagnostics: Endpoint['eventDiagnostics'];
17
+ readonly eventDiagnostics: AdapterEndpointSummary['eventDiagnostics'];
15
18
  readonly status: 'online' | 'offline';
16
19
  readonly phase: AdapterEndpointPhase;
17
20
  readonly operations: readonly AdapterOperation[];
@@ -26,37 +29,31 @@ export interface RuntimeEndpointSendInput {
26
29
  readonly content: unknown;
27
30
  }
28
31
  export interface RuntimeEndpointReactionInput {
29
- readonly adapter: string;
30
- readonly endpointKey: string;
31
32
  readonly message: MessageRef;
32
33
  readonly emoji: string;
33
34
  readonly sceneType?: string;
34
35
  readonly channelId?: string;
35
36
  }
36
37
  export interface RuntimeEndpointRemoveReactionInput {
37
- readonly adapter: string;
38
- readonly endpointKey: string;
39
38
  readonly message: MessageRef;
40
39
  readonly reactionId: string;
41
40
  }
42
41
  export interface RuntimeEndpointMessageInput {
43
- readonly adapter: string;
44
- readonly endpointKey: string;
45
42
  readonly message: MessageRef;
46
43
  }
47
44
  export interface RuntimeEndpointEditInput extends RuntimeEndpointMessageInput {
48
45
  readonly content: unknown;
49
46
  }
50
47
  export interface RuntimeEndpointTypingInput {
51
- readonly adapter: string;
52
- readonly endpointKey: string;
53
48
  readonly conversation: ConversationRef;
54
49
  readonly active?: boolean;
55
50
  }
56
51
  interface EndpointRuntimeContext {
57
52
  acquire(): SnapshotLease;
53
+ /** Independently retain the current operation snapshot for detached source work. */
54
+ retain(): SnapshotLease;
58
55
  release(lease: SnapshotLease): void;
59
- send(request: SendRequest, snapshot: RuntimeSnapshot): Promise<DeliveryReceipt>;
56
+ send(request: SendRequest, snapshot: RuntimeSnapshot, execution?: OutboundDeliveryExecution): Promise<DeliveryReceipt>;
60
57
  }
61
58
  /** Owns generation-leased Endpoint discovery, control, management, and Console delivery. */
62
59
  export declare class EndpointRuntime {
@@ -69,14 +66,18 @@ export declare class EndpointRuntime {
69
66
  readonly endpointKey: string;
70
67
  }): EndpointCapabilities | undefined;
71
68
  get(adapter: string, endpointKey: string): EndpointRuntimeDetail | null;
69
+ /** Retain the actual ingress Client instead of resolving the latest account when work settles. */
70
+ captureOperation(input: CaptureEndpointOperationInput): CapturedEndpointOperation;
72
71
  send(input: RuntimeEndpointSendInput): Promise<{
73
72
  messageId: string;
73
+ receipt: DeliveryReceipt;
74
74
  }>;
75
75
  /** Resolves a persisted identity exactly in the current operation generation. */
76
76
  sendTarget(target: DeliveryTarget, content: unknown, requester?: PluginId, options?: Readonly<{
77
77
  locale?: Locale;
78
78
  }>): Promise<{
79
79
  messageId: string;
80
+ receipt: DeliveryReceipt;
80
81
  }>;
81
82
  addReaction(input: RuntimeEndpointReactionInput): Promise<string | null>;
82
83
  removeReaction(input: RuntimeEndpointRemoveReactionInput): Promise<void>;
@@ -86,7 +87,4 @@ export declare class EndpointRuntime {
86
87
  withManagement<T>(adapter: string, endpointKey: string, run: (management: EndpointManagement) => T | Promise<T>): Promise<T | null>;
87
88
  }
88
89
  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
90
  export declare function adapterTypeName(packageName: string | undefined): string | undefined;
92
- export {};