@zhin.js/core 1.1.55 → 1.1.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/lib/built/generic-segment-mapper.js +2 -0
  2. package/lib/built/html-to-text.js +2 -2
  3. package/lib/built/rich-segments/markdown-to-text.js +19 -0
  4. package/lib/built/segment-contract/validate.d.ts +1442 -300
  5. package/lib/built/user-interaction.js +3 -1
  6. package/lib/index.d.ts +4 -0
  7. package/lib/index.js +3 -0
  8. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +1 -1
  9. package/lib/plugin-runtime/im/command-menu-navigation.js +2 -1
  10. package/lib/plugin-runtime/im/contracts.d.ts +8 -1
  11. package/lib/plugin-runtime/im/contracts.js +20 -1
  12. package/lib/plugin-runtime/im/conversation-runtime.d.ts +2 -2
  13. package/lib/plugin-runtime/im/conversation-runtime.js +6 -4
  14. package/lib/plugin-runtime/im/im-runtime.js +8 -1
  15. package/lib/plugin-runtime/im/inbound-dedup.d.ts +1 -0
  16. package/lib/plugin-runtime/im/inbound-dedup.js +1 -0
  17. package/lib/plugin-runtime/im/inbound-origin.d.ts +27 -0
  18. package/lib/plugin-runtime/im/inbound-runtime.d.ts +8 -1
  19. package/lib/plugin-runtime/im/inbound-runtime.js +79 -2
  20. package/lib/plugin-runtime/im/index.d.ts +2 -0
  21. package/lib/plugin-runtime/im/index.js +2 -0
  22. package/lib/plugin-runtime/im/interaction-runtime.d.ts +7 -6
  23. package/lib/plugin-runtime/im/interaction-runtime.js +85 -24
  24. package/lib/plugin-runtime/im/interactive-router.d.ts +28 -8
  25. package/lib/plugin-runtime/im/interactive-router.js +112 -35
  26. package/lib/plugin-runtime/im/jsx-button-registry.d.ts +16 -2
  27. package/lib/plugin-runtime/im/jsx-button-registry.js +56 -19
  28. package/lib/plugin-runtime/im/message-dispatcher.js +59 -6
  29. package/lib/plugin-runtime/im/operation-resources.d.ts +15 -0
  30. package/lib/plugin-runtime/im/operation-resources.js +2 -0
  31. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +5 -4
  32. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +71 -21
  33. package/lib/plugin-runtime/im/outbound-segments.d.ts +1 -1
  34. package/lib/plugin-runtime/im/outbound-segments.js +2 -20
  35. package/lib/runtime.d.ts +2 -0
  36. package/lib/runtime.js +2 -0
  37. package/lib/side-event/index.d.ts +0 -1
  38. package/lib/side-event/index.js +0 -1
  39. package/lib/side-event/normalize.d.ts +0 -28
  40. package/lib/side-event/normalize.js +0 -100
  41. package/lib/side-event/scene-events.js +1 -1
  42. package/lib/side-event/types.d.ts +0 -6
  43. package/lib/side-event/types.js +1 -57
  44. package/lib/venue/contracts.d.ts +21 -0
  45. package/lib/venue/contracts.js +3 -0
  46. package/lib/venue/floor-controller.d.ts +11 -0
  47. package/lib/venue/floor-controller.js +63 -0
  48. package/lib/venue/index.d.ts +13 -0
  49. package/lib/venue/index.js +11 -0
  50. package/lib/venue/membership-port.d.ts +23 -0
  51. package/lib/venue/membership-port.js +141 -0
  52. package/lib/venue/projector.d.ts +38 -0
  53. package/lib/venue/projector.js +45 -0
  54. package/lib/venue/registry.d.ts +16 -0
  55. package/lib/venue/registry.js +63 -0
  56. package/lib/venue/router.d.ts +19 -0
  57. package/lib/venue/router.js +101 -0
  58. package/lib/venue/send-limiter.d.ts +17 -0
  59. package/lib/venue/send-limiter.js +73 -0
  60. package/lib/venue/validator.d.ts +6 -0
  61. package/lib/venue/validator.js +160 -0
  62. package/package.json +16 -16
  63. package/lib/side-event/dispatch.d.ts +0 -15
  64. package/lib/side-event/dispatch.js +0 -168
@@ -1,3 +1,4 @@
1
+ import { readOperationInputResources } from '@zhin.js/feature-kit';
1
2
  import { adapterFeatureId, isAdapterIndex } from '@zhin.js/adapter';
2
3
  import { commandFeatureId, isCommandIndex, } from '@zhin.js/command';
3
4
  import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
@@ -34,10 +35,21 @@ export const defaultCommandPrefixResolver = (message, snapshot) => {
34
35
  const config = (owner ? snapshot.config.get(owner) : undefined);
35
36
  if (!config)
36
37
  return '';
37
- const endpointId = message.endpointId;
38
- if (endpointId && Array.isArray(config.endpoints)) {
39
- const entry = config.endpoints.find((item) => !!item && typeof item === 'object'
40
- && item.id === endpointId);
38
+ const adapters = snapshot.projections.get(adapterFeatureId);
39
+ const endpointCapabilityId = message.conversation.endpoint.id;
40
+ const desiredEndpointId = isAdapterIndex(adapters)
41
+ ? adapters.endpointEntry(endpointCapabilityId)?.desired.endpointId
42
+ : undefined;
43
+ const candidateIds = new Set([message.endpointId, desiredEndpointId].filter((v) => typeof v === 'string' && v.length > 0));
44
+ if (candidateIds.size > 0 && Array.isArray(config.endpoints)) {
45
+ const entry = config.endpoints.find((item) => {
46
+ if (!item || typeof item !== 'object')
47
+ return false;
48
+ const id = item.id;
49
+ const name = item.name;
50
+ return (typeof id === 'string' && candidateIds.has(id))
51
+ || (typeof name === 'string' && candidateIds.has(name));
52
+ });
41
53
  if (typeof entry?.commandPrefix === 'string')
42
54
  return entry.commandPrefix;
43
55
  }
@@ -65,7 +77,7 @@ export class MessageDispatcher {
65
77
  catch { /* Observation never controls dispatch. */ }
66
78
  };
67
79
  const prefix = message.commandPrefix ?? this.resolvePrefix(message, snapshot);
68
- let input = message.content.trim();
80
+ let input = normalizeCommandInputText(message);
69
81
  if (prefix && !input.startsWith(prefix)) {
70
82
  note('prefix', 'mismatch');
71
83
  return dispatchOutcome(Object.freeze({ matched: false }));
@@ -87,7 +99,7 @@ export class MessageDispatcher {
87
99
  : undefined;
88
100
  const matchInput = structuredInput ?? input;
89
101
  note('dispatch', 'started');
90
- const result = await commands.dispatch({ input: matchInput, source: message, interactionFactory: interactionFactory, commandPrefix: prefix, snapshot: snapshot });
102
+ const result = await commands.dispatch({ input: matchInput, source: message, interactionFactory: interactionFactory, commandPrefix: prefix, snapshot: snapshot, operation: readOperationInputResources(message, snapshot) });
91
103
  const feedback = await renderCommandFeedback(result, message, snapshot);
92
104
  if (feedback)
93
105
  return dispatchOutcome(Object.freeze({ ...result, value: feedback.content }), feedback.owner);
@@ -119,10 +131,48 @@ export class MessageDispatcher {
119
131
  * command"). Leading quotes are moved after the command text so the command name still
120
132
  * matches and a `reply` parameter can still read the quote; `message.replyTo` is untouched.
121
133
  */
134
+ function hasTextAfterLeadingMentions(segments) {
135
+ let seenMention = false;
136
+ for (const segment of segments) {
137
+ if (segment.type === 'reply')
138
+ continue;
139
+ if (segment.type === 'mention' || segment.type === 'at') {
140
+ seenMention = true;
141
+ continue;
142
+ }
143
+ return seenMention && segment.type === 'text' && typeof segment.data.text === 'string' && segment.data.text.trim().length > 0;
144
+ }
145
+ return false;
146
+ }
147
+ function normalizeCommandInputText(message) {
148
+ const raw = message.content.trim();
149
+ const segments = message.segments;
150
+ if (segments && hasTextAfterLeadingMentions(segments)) {
151
+ let atStart = true;
152
+ const textParts = [];
153
+ for (const segment of segments) {
154
+ if (atStart && (segment.type === 'reply' || segment.type === 'mention' || segment.type === 'at')) {
155
+ continue;
156
+ }
157
+ atStart = false;
158
+ if (segment.type === 'text' && typeof segment.data?.text === 'string') {
159
+ textParts.push(segment.data.text);
160
+ }
161
+ }
162
+ const candidate = textParts.join('').trim();
163
+ if (candidate)
164
+ return candidate;
165
+ }
166
+ if (message.conversation?.kind !== 'private' && /^(?:@\S+\s+)+/u.test(raw)) {
167
+ return raw.replace(/^(?:@\S+\s+)+/u, '').trim();
168
+ }
169
+ return raw;
170
+ }
122
171
  function stripCommandPrefix(segments, prefix) {
123
172
  let pendingPrefix = prefix;
124
173
  let atStart = true;
125
174
  let trimLeading = true;
175
+ const skipLeadingMentions = hasTextAfterLeadingMentions(segments);
126
176
  const result = [];
127
177
  const leadingQuotes = [];
128
178
  for (const segment of segments) {
@@ -134,6 +184,9 @@ function stripCommandPrefix(segments, prefix) {
134
184
  leadingQuotes.push(segment);
135
185
  continue;
136
186
  }
187
+ if (skipLeadingMentions && (segment.type === 'mention' || segment.type === 'at')) {
188
+ continue;
189
+ }
137
190
  if (segment.type !== 'text' || typeof segment.data.text !== 'string') {
138
191
  if (pendingPrefix)
139
192
  return undefined;
@@ -0,0 +1,15 @@
1
+ import { type PluginId, type SnapshotLease, type SnapshotReader } from '@zhin.js/plugin-runtime';
2
+ import type { OperationResourceView } from '@zhin.js/feature-kit';
3
+ import type { RuntimeMessage } from './contracts.js';
4
+ /** Trusted composition port. Only Core supplies the controlled message and real held lease. */
5
+ export interface ImOperationResourcesInput {
6
+ readonly lease: SnapshotLease;
7
+ readonly snapshots: SnapshotReader;
8
+ readonly message: RuntimeMessage;
9
+ readonly owner: PluginId;
10
+ readonly signal: AbortSignal;
11
+ }
12
+ export interface ImOperationResourcesPort {
13
+ open(input: ImOperationResourcesInput): OperationResourceView | undefined;
14
+ }
15
+ export declare const imOperationResourcesToken: import("@zhin.js/plugin-runtime").Token<ImOperationResourcesPort>;
@@ -0,0 +1,2 @@
1
+ import { createRootPrivateToken } from '@zhin.js/plugin-runtime';
2
+ export const imOperationResourcesToken = createRootPrivateToken('zhin.im.operation-resources', 'Host resources for one authorized IM capability operation');
@@ -3,16 +3,17 @@ import { type ConversationRef, type DeliveryReceipt, type DeliveryPart, type End
3
3
  import { type SendRequest } from './contracts.js';
4
4
  import { OutboundRenderer } from './outbound-renderer.js';
5
5
  import { type RuntimeMessageEvent } from './message-events.js';
6
- import { type JsxButtonBatch } from './jsx-button-registry.js';
6
+ import { type JsxButtonBatch, type PluginIncarnationRef } from './jsx-button-registry.js';
7
+ import type { RememberFallbackContext } from './interactive-router.js';
7
8
  import type { RuntimeMessageDiagnostics } from './message-diagnostics.js';
8
9
  interface OutboundDeliveryContext {
9
10
  readonly diagnostics?: RuntimeMessageDiagnostics;
10
11
  prepareButtons?(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
11
- record(request: SendRequest, receipt: DeliveryReceipt, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<void>;
12
- recordUpdate?(request: SendRequest, receipt: DeliveryReceipt, revision: number, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<void>;
12
+ record(request: SendRequest, receipt: DeliveryReceipt, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<number | undefined | void>;
13
+ recordUpdate?(request: SendRequest, receipt: DeliveryReceipt, revision: number, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<number | undefined | void>;
13
14
  /** Side-channel correlation ledger for inbound origin; failures never affect the receipt. */
14
15
  ledger?(conversation: ConversationRef, receipt: DeliveryReceipt, payload: unknown): void;
15
- rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>): Record<string, string> | void;
16
+ rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>, context?: number | RememberFallbackContext | PluginIncarnationRef): Record<string, string> | void;
16
17
  publish(event: RuntimeMessageEvent): void;
17
18
  }
18
19
  /** Internal transport continuation. Rendering, policy and middleware still own every submitted revision. */
@@ -92,13 +92,25 @@ export class OutboundDeliveryRuntime {
92
92
  });
93
93
  // Record identities and fallback text before middleware can mutate the array
94
94
  // or its segments. Do not copy/serialize media buffers or streams.
95
+ const initialSegmentSet = new Set(Array.isArray(initialPayload) ? initialPayload : []);
95
96
  const initialItems = Array.isArray(initialPayload) ? initialPayload.map(item => ({
96
97
  item, type: item?.type, text: item?.type === 'text' ? item.data?.text : undefined,
97
98
  })) : undefined;
98
- const retainsInitialProjection = (value) => value === initialPayload
99
- && (!initialItems || (Array.isArray(value) && value.length === initialItems.length
99
+ const retainsInitialProjection = (value) => (value === initialPayload && !initialItems)
100
+ || (!!initialItems && initialItems.length > 0 && Array.isArray(value)
101
+ && value.length === initialItems.length
100
102
  && initialItems.every(({ item, type, text }, index) => value[index] === item
101
- && item?.type === type && (type !== 'text' || item.data?.text === text))));
103
+ && item?.type === type && (type !== 'text' || item.data?.text === text)));
104
+ const retainsInitialSegments = (value) => retainsInitialProjection(value)
105
+ || (!!initialItems && initialItems.length > 0 && Array.isArray(value)
106
+ && initialItems.every(({ item, type, text }) => value.includes(item)
107
+ && item?.type === type && (type !== 'text' || item.data?.text === text)));
108
+ const fallbackIncarnation = {
109
+ requester: request.requester,
110
+ snapshot,
111
+ node: snapshot.tree.get(request.requester),
112
+ ...(boundEndpoint?.signal ? { signal: boundEndpoint.signal } : {}),
113
+ };
102
114
  let terminalEntered = false;
103
115
  let receipt;
104
116
  try {
@@ -108,24 +120,42 @@ export class OutboundDeliveryRuntime {
108
120
  let projection;
109
121
  const buttonPayloads = new Set();
110
122
  try {
111
- // Native payload replacements remain possible; only authoring values need evaluation.
123
+ // Native payload replacements and in-place array mutations remain possible; only authoring values need evaluation.
112
124
  const replacement = envelope.payload;
113
- const replaced = replacement !== initialPayload && needsAuthoringRender(replacement)
114
- ? await this.#renderer.render(replacement, {
115
- requester: request.requester,
116
- snapshot: snapshot,
117
- conversation: request.conversation,
118
- incoming: request.incoming,
119
- ...renderOptions,
120
- })
121
- : replacement;
125
+ const renderItemOptions = {
126
+ requester: request.requester,
127
+ snapshot: snapshot,
128
+ conversation: request.conversation,
129
+ incoming: request.incoming,
130
+ ...renderOptions,
131
+ };
132
+ let replaced = replacement;
133
+ if (needsAuthoringRender(replacement)) {
134
+ if (Array.isArray(replacement) && initialSegmentSet.size > 0 && replacement.some(item => initialSegmentSet.has(item))) {
135
+ const renderedItems = [];
136
+ for (const item of flattenOutboundArray(replacement)) {
137
+ if (initialSegmentSet.has(item) || !needsAuthoringRender(item)) {
138
+ renderedItems.push(item);
139
+ }
140
+ else {
141
+ renderedItems.push(await this.#renderer.render(item, renderItemOptions));
142
+ }
143
+ }
144
+ replaced = flattenOutboundArray(renderedItems);
145
+ }
146
+ else {
147
+ replaced = await this.#renderer.render(replacement, renderItemOptions);
148
+ }
149
+ }
122
150
  projection = await projectOutboundPayload(replaced, request.conversation, snapshot, {
123
151
  presentation, signal: renderOptions.signal,
124
- inheritedFallbacks: retainsInitialProjection(replacement) ? initialProjection.rendering.fallbacks : [],
152
+ inheritedFallbacks: retainsInitialSegments(replaced) ? initialProjection.rendering.fallbacks : [],
125
153
  rememberFallback: (map) => {
126
154
  for (const value of Object.values(map))
127
155
  buttonPayloads.add(value);
128
- return this.context.rememberFallback(request.conversation, snapshot.generation, map);
156
+ return this.context.rememberFallback(request.conversation, snapshot.generation, map, {
157
+ incarnation: fallbackIncarnation,
158
+ });
129
159
  },
130
160
  });
131
161
  payload = projection.payload;
@@ -190,25 +220,38 @@ export class OutboundDeliveryRuntime {
190
220
  receipt = evidence.receipt;
191
221
  if (receipt.status !== 'sent' && !receipt.failure?.deliveryUnknown && !receipt.parts?.length)
192
222
  revokeButtons?.();
223
+ const recordedParts = [];
224
+ let firstSequence;
193
225
  for (const part of evidence.parts) {
194
- execution?.confirmed(part.part, part.content);
195
226
  const partReceipt = { status: 'sent', ...(part.part.message ? { message: part.part.message } : {}),
196
227
  ...(part.part.outboundTextDigest ? { outboundTextDigest: part.part.outboundTextDigest } : {}) };
197
228
  const history = execution?.history() ?? 'create';
229
+ let partSequence;
198
230
  if (part.part.message && history !== 'skip') {
199
231
  try {
200
232
  const content = part.content ?? (contentUnavailable || receipt.parts ? 'unavailable' : undefined);
201
- if (history === 'create')
202
- await this.context.record(request, partReceipt, content);
203
- else
204
- await this.context.recordUpdate?.(request, partReceipt, history.revision, content);
233
+ const seq = history === 'create'
234
+ ? await this.context.record(request, partReceipt, content)
235
+ : await this.context.recordUpdate?.(request, partReceipt, history.revision, content);
236
+ if (typeof seq === 'number') {
237
+ partSequence = seq;
238
+ firstSequence ??= seq;
239
+ }
205
240
  }
206
241
  catch (error) {
207
242
  logger.warn(formatCompact({ op: 'outbound_history_failed', error: error instanceof Error ? error.message : String(error) }));
208
243
  }
209
244
  }
245
+ const enrichedPart = partSequence !== undefined
246
+ ? Object.freeze({ ...part.part, conversationSequence: partSequence })
247
+ : part.part;
248
+ recordedParts.push(enrichedPart);
249
+ execution?.confirmed(enrichedPart, part.content);
250
+ const enrichedPartReceipt = partSequence !== undefined
251
+ ? { ...partReceipt, conversationSequence: partSequence }
252
+ : partReceipt;
210
253
  try {
211
- this.context.ledger?.(request.conversation, partReceipt, part.content ?? (contentUnavailable || receipt.parts ? undefined : payload));
254
+ this.context.ledger?.(request.conversation, enrichedPartReceipt, part.content ?? (contentUnavailable || receipt.parts ? undefined : payload));
212
255
  }
213
256
  catch (error) {
214
257
  logger.warn(`outbound ledger write failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -225,6 +268,13 @@ export class OutboundDeliveryRuntime {
225
268
  timestamp: Date.now(),
226
269
  });
227
270
  }
271
+ if (firstSequence !== undefined || (receipt.parts && recordedParts.length > 0)) {
272
+ receipt = Object.freeze({
273
+ ...receipt,
274
+ ...(receipt.parts ? { parts: Object.freeze(recordedParts) } : {}),
275
+ ...(firstSequence !== undefined ? { conversationSequence: firstSequence } : {}),
276
+ });
277
+ }
228
278
  }, 'outbound');
229
279
  }
230
280
  catch {
@@ -59,7 +59,7 @@ export declare function resolveOutboundMediaPolicy(adapter: CapabilityId, snapsh
59
59
  export declare function isOutboundSegment(value: unknown): value is OutboundSegment;
60
60
  /**
61
61
  * 解析端点的出站 interactive 策略:优先读 adapter definition 上声明的
62
- * `segments.interactive`,否则按平台名查内置表,未知平台回退 'text'。
62
+ * `segments.interactive`(ADR 0044:原生按钮由 adapter 自己声明,core 不认平台名),否则回退 'text'。
63
63
  */
64
64
  export declare function resolveOutboundInteractivePolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): InteractivePolicy;
65
65
  /** Read declared support from this operation's snapshot without requiring live admission. */
@@ -47,18 +47,9 @@ export function isOutboundSegment(value) {
47
47
  && !Array.isArray(value)
48
48
  && typeof value.type === 'string';
49
49
  }
50
- /**
51
- * 平台名 → 出站 interactive 策略(adapter 未声明 `segments.interactive` 时
52
- * 的内置来源):telegram / discord 端点自行把 keyboard 编码为原生按钮;
53
- * 其余平台默认 'text'(编号文本降级)。
54
- */
55
- const OUTBOUND_INTERACTIVE_POLICY_BY_ADAPTER = {
56
- telegram: 'native',
57
- discord: 'native',
58
- };
59
50
  /**
60
51
  * 解析端点的出站 interactive 策略:优先读 adapter definition 上声明的
61
- * `segments.interactive`,否则按平台名查内置表,未知平台回退 'text'。
52
+ * `segments.interactive`(ADR 0044:原生按钮由 adapter 自己声明,core 不认平台名),否则回退 'text'。
62
53
  */
63
54
  export function resolveOutboundInteractivePolicy(adapter, snapshot) {
64
55
  const slot = snapshot.capabilities.get(adapter)
@@ -66,10 +57,7 @@ export function resolveOutboundInteractivePolicy(adapter, snapshot) {
66
57
  const declared = readDeclaredInteractivePolicy(slot?.definition);
67
58
  if (declared)
68
59
  return declared;
69
- const packageName = slot ? snapshot.tree.get(slot.owner)?.packageName : undefined;
70
- const adapterType = adapterTypeName(packageName);
71
- return (adapterType ? OUTBOUND_INTERACTIVE_POLICY_BY_ADAPTER[adapterType] : undefined)
72
- ?? DEFAULT_INTERACTIVE_POLICY;
60
+ return DEFAULT_INTERACTIVE_POLICY;
73
61
  }
74
62
  /** Read declared support from this operation's snapshot without requiring live admission. */
75
63
  export function resolveOutboundSupportedSegments(adapter, snapshot) {
@@ -190,12 +178,6 @@ function baseSlotCapabilityId(adapter) {
190
178
  const tilde = adapter.indexOf('~');
191
179
  return (tilde === -1 ? adapter : adapter.slice(0, tilde));
192
180
  }
193
- /** `@zhin.js/adapter-icqq` → `icqq`;非 adapter 包名原样返回。 */
194
- function adapterTypeName(packageName) {
195
- if (!packageName)
196
- return undefined;
197
- return packageName.replace(/^@[^/]+\/adapter-/, '');
198
- }
199
181
  /**
200
182
  * Normalize a rendered outbound payload toward canonical wire segments:
201
183
  * - segment arrays stay arrays (html segments converted per element,
@@ -0,0 +1,2 @@
1
+ export * from './plugin-runtime/im/index.js';
2
+ export * from './venue/index.js';
package/lib/runtime.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './plugin-runtime/im/index.js';
2
+ export * from './venue/index.js';
@@ -1,5 +1,4 @@
1
1
  export * from './base.js';
2
2
  export * from './types.js';
3
3
  export * from './normalize.js';
4
- export * from './dispatch.js';
5
4
  export * from './scene-events.js';
@@ -1,5 +1,4 @@
1
1
  export * from './base.js';
2
2
  export * from './types.js';
3
3
  export * from './normalize.js';
4
- export * from './dispatch.js';
5
4
  export * from './scene-events.js';
@@ -1,34 +1,6 @@
1
1
  import type { IncomingNotice } from '../notice.js';
2
2
  import type { IncomingRequest } from '../request.js';
3
3
  import type { IncomingSystemEvent } from '../system-event.js';
4
- import { type SideEventParts } from './types.js';
5
- export type SideEventPlatform = 'onebot' | 'icqq' | 'napcat' | 'kook' | (string & {});
6
- export interface OneBotLikeRawEvent {
7
- notice_type?: string;
8
- request_type?: string;
9
- sub_type?: string;
10
- group_id?: number | string;
11
- user_id?: number | string;
12
- operator_id?: number | string;
13
- flag?: string;
14
- time?: number;
15
- self_id?: number | string;
16
- [key: string]: unknown;
17
- }
18
- /** 去重用:notice / request 无稳定 id 时组合键 */
19
- export declare function resolveSideEventDedupeKey(data: OneBotLikeRawEvent, kind: 'notice' | 'request'): string;
20
- /**
21
- * 将平台原始 notice_type 映射为标准 `scene_type` + `sub_type`。
22
- */
23
- export declare function mapNoticeParts(platform: SideEventPlatform, raw: string, options?: {
24
- sub_type?: string;
25
- is_group?: boolean;
26
- notify_handler?: (subType: string | undefined, isGroup: boolean) => SideEventParts;
27
- }): SideEventParts;
28
- /**
29
- * 将平台原始 request_type 映射为标准 `scene_type` + `sub_type`。
30
- */
31
- export declare function mapRequestParts(_platform: SideEventPlatform, raw: string, subType?: string): SideEventParts;
32
4
  export declare function senderFromId(id: unknown, name?: string): {
33
5
  id: string;
34
6
  name: string;
@@ -1,103 +1,3 @@
1
- import { parseSideEventName } from './base.js';
2
- import { KOOK_NOTICE_PARTS_MAP, ONEBOT_NOTICE_PARTS_MAP, SLACK_NOTICE_PARTS_MAP } from './types.js';
3
- /** 去重用:notice / request 无稳定 id 时组合键 */
4
- export function resolveSideEventDedupeKey(data, kind) {
5
- if (data.flag != null && String(data.flag) !== '') {
6
- return `${kind}:${data.flag}`;
7
- }
8
- const time = data.time ?? 0;
9
- const type = data.notice_type ?? data.request_type ?? kind;
10
- const scope = data.group_id ?? data.user_id ?? '';
11
- const sub = data.sub_type ?? '';
12
- // 群事件的 scope 是群号:不带成员和操作人时,同一群的两次入群(平台不给 time 时尤甚)会撞成同一个键,后一次被当重复丢掉。
13
- const member = data.group_id != null ? (data.user_id ?? '') : '';
14
- const operator = data.operator_id ?? '';
15
- return `${kind}:${time}_${type}_${scope}_${sub}_${member}_${operator}`;
16
- }
17
- function resolveNotifyNoticeParts(subType, isGroup) {
18
- if (subType === 'poke') {
19
- return isGroup
20
- ? { scene_type: 'group', sub_type: 'poke' }
21
- : { scene_type: 'friend', sub_type: 'poke' };
22
- }
23
- if (subType === 'input_status')
24
- return { scene_type: 'notify', sub_type: 'input_status' };
25
- // 群头衔变更属于群场景(否则没有 conversation,进不了 conversation_events)
26
- if (subType === 'title')
27
- return { scene_type: isGroup ? 'group' : 'notify', sub_type: 'title_change' };
28
- if (subType === 'profile_like')
29
- return { scene_type: 'notify', sub_type: 'profile_like' };
30
- return { scene_type: 'notify', sub_type: subType ?? 'unknown' };
31
- }
32
- function resolveEssenceNoticeParts(subType) {
33
- return subType === 'add'
34
- ? { scene_type: 'group', sub_type: 'essence_add' }
35
- : { scene_type: 'group', sub_type: 'essence_delete' };
36
- }
37
- /**
38
- * 将平台原始 notice_type 映射为标准 `scene_type` + `sub_type`。
39
- */
40
- export function mapNoticeParts(platform, raw, options) {
41
- const subType = options?.sub_type;
42
- const isGroup = options?.is_group ?? false;
43
- if (platform === 'kook') {
44
- return KOOK_NOTICE_PARTS_MAP[raw] ?? { scene_type: 'kook', sub_type: raw };
45
- }
46
- if (platform === 'slack') {
47
- return SLACK_NOTICE_PARTS_MAP[raw] ?? { scene_type: 'slack', sub_type: raw };
48
- }
49
- if (raw === 'notify') {
50
- const handler = options?.notify_handler ?? resolveNotifyNoticeParts;
51
- return handler(subType, isGroup);
52
- }
53
- if (raw === 'essence') {
54
- return resolveEssenceNoticeParts(subType);
55
- }
56
- if (platform === 'icqq' && (raw === 'group' || raw === 'friend') && subType) {
57
- return ONEBOT_NOTICE_PARTS_MAP[`${raw}.${subType}`] ?? { scene_type: raw, sub_type: subType };
58
- }
59
- if (ONEBOT_NOTICE_PARTS_MAP[raw]) {
60
- return ONEBOT_NOTICE_PARTS_MAP[raw];
61
- }
62
- if (raw.startsWith('notice.')) {
63
- const parsed = parseSideEventName(raw);
64
- if (parsed.scene_type && parsed.sub_type) {
65
- return { scene_type: parsed.scene_type, sub_type: parsed.sub_type };
66
- }
67
- const suffix = raw.slice('notice.'.length).replace(/\./g, '_');
68
- if (ONEBOT_NOTICE_PARTS_MAP[suffix])
69
- return ONEBOT_NOTICE_PARTS_MAP[suffix];
70
- return { scene_type: parsed.scene_type ?? 'unknown', sub_type: parsed.sub_type ?? suffix };
71
- }
72
- if (platform === 'icqq' || platform === 'onebot' || platform === 'napcat') {
73
- const dotted = raw.replace(/_/g, '.');
74
- const parsed = parseSideEventName(`notice.${dotted}`);
75
- return {
76
- scene_type: parsed.scene_type ?? dotted.split('.')[0] ?? 'unknown',
77
- sub_type: parsed.sub_type ?? (dotted.split('.').slice(1).join('.') || raw),
78
- };
79
- }
80
- return { scene_type: platform, sub_type: raw };
81
- }
82
- /**
83
- * 将平台原始 request_type 映射为标准 `scene_type` + `sub_type`。
84
- */
85
- export function mapRequestParts(_platform, raw, subType) {
86
- if (raw === 'friend' || raw.startsWith('friend')) {
87
- return { scene_type: 'friend', sub_type: 'add' };
88
- }
89
- if (raw === 'group' || raw.startsWith('group')) {
90
- return { scene_type: 'group', sub_type: subType === 'invite' ? 'invite' : 'add' };
91
- }
92
- if (raw.startsWith('request.')) {
93
- const parsed = parseSideEventName(raw);
94
- return {
95
- scene_type: parsed.scene_type ?? 'unknown',
96
- sub_type: parsed.sub_type ?? 'unknown',
97
- };
98
- }
99
- return { scene_type: raw, sub_type: subType ?? 'unknown' };
100
- }
101
1
  export function senderFromId(id, name) {
102
2
  if (id == null || id === '')
103
3
  return undefined;
@@ -28,7 +28,7 @@ export const SCENE_EVENT_TEXT_MAX = 40;
28
28
  export function isSceneEvent(event) {
29
29
  return SCENE_EVENT_TYPES.includes(event.type);
30
30
  }
31
- /** OneBot 等平台以 user_id 0 表示「全员」。 */
31
+ /** 部分平台以 user_id 0 表示「全员」。 */
32
32
  const WHOLE_SCENE_IDS = new Set(['0', 'all']);
33
33
  /**
34
34
  * 事件优先级;不是场景事件时返回 undefined。
@@ -12,9 +12,3 @@ export interface SideEventParts {
12
12
  scene_type: string;
13
13
  sub_type: string;
14
14
  }
15
- /** OneBot / icqq 等平台 notice_type 原始值 → 标准 scene_type + sub_type */
16
- export declare const ONEBOT_NOTICE_PARTS_MAP: Record<string, SideEventParts>;
17
- /** KOOK extra.type 原始值 → 标准 scene_type + sub_type */
18
- export declare const KOOK_NOTICE_PARTS_MAP: Record<string, SideEventParts>;
19
- /** Slack event type 原始值 → 标准 scene_type + sub_type */
20
- export declare const SLACK_NOTICE_PARTS_MAP: Record<string, SideEventParts>;
@@ -1,57 +1 @@
1
- /** OneBot / icqq 等平台 notice_type 原始值 → 标准 scene_type + sub_type */
2
- export const ONEBOT_NOTICE_PARTS_MAP = {
3
- group_increase: { scene_type: 'group', sub_type: 'member_increase' },
4
- group_decrease: { scene_type: 'group', sub_type: 'member_decrease' },
5
- group_admin: { scene_type: 'group', sub_type: 'admin_change' },
6
- group_ban: { scene_type: 'group', sub_type: 'ban' },
7
- group_recall: { scene_type: 'group', sub_type: 'recall' },
8
- friend_recall: { scene_type: 'friend', sub_type: 'recall' },
9
- friend_add: { scene_type: 'friend', sub_type: 'increase' },
10
- group_upload: { scene_type: 'group', sub_type: 'upload' },
11
- group_transfer: { scene_type: 'group', sub_type: 'transfer' },
12
- group_card: { scene_type: 'group', sub_type: 'card_change' },
13
- group_msg_emoji_like: { scene_type: 'group', sub_type: 'emoji_reaction' },
14
- 'group.increase': { scene_type: 'group', sub_type: 'member_increase' },
15
- 'group.decrease': { scene_type: 'group', sub_type: 'member_decrease' },
16
- 'group.admin': { scene_type: 'group', sub_type: 'admin_change' },
17
- 'group.ban': { scene_type: 'group', sub_type: 'ban' },
18
- 'group.recall': { scene_type: 'group', sub_type: 'recall' },
19
- 'friend.increase': { scene_type: 'friend', sub_type: 'increase' },
20
- 'friend.decrease': { scene_type: 'friend', sub_type: 'recall' },
21
- 'friend.recall': { scene_type: 'friend', sub_type: 'recall' },
22
- // icqq: notice_type=group + sub_type(#996 状态感知补齐)
23
- 'group.poke': { scene_type: 'group', sub_type: 'poke' },
24
- 'group.reaction': { scene_type: 'group', sub_type: 'emoji_reaction' },
25
- 'group.transfer': { scene_type: 'group', sub_type: 'transfer' },
26
- 'group.card': { scene_type: 'group', sub_type: 'card_change' },
27
- 'group.notice': { scene_type: 'group', sub_type: 'notice_updated' },
28
- group_notice: { scene_type: 'group', sub_type: 'notice_updated' },
29
- };
30
- /** KOOK extra.type 原始值 → 标准 scene_type + sub_type */
31
- export const KOOK_NOTICE_PARTS_MAP = {
32
- joined_guild: { scene_type: 'group', sub_type: 'member_increase' },
33
- exited_guild: { scene_type: 'group', sub_type: 'member_decrease' },
34
- deleted_message: { scene_type: 'group', sub_type: 'recall' },
35
- deleted_private_message: { scene_type: 'friend', sub_type: 'recall' },
36
- added_reaction: { scene_type: 'group', sub_type: 'emoji_reaction' },
37
- deleted_reaction: { scene_type: 'group', sub_type: 'emoji_reaction' },
38
- private_added_reaction: { scene_type: 'group', sub_type: 'emoji_reaction' },
39
- private_deleted_reaction: { scene_type: 'group', sub_type: 'emoji_reaction' },
40
- };
41
- /** Slack event type 原始值 → 标准 scene_type + sub_type */
42
- export const SLACK_NOTICE_PARTS_MAP = {
43
- member_joined_channel: { scene_type: 'group', sub_type: 'member_increase' },
44
- member_left_channel: { scene_type: 'group', sub_type: 'member_decrease' },
45
- reaction_added: { scene_type: 'group', sub_type: 'emoji_reaction' },
46
- reaction_removed: { scene_type: 'group', sub_type: 'emoji_reaction' },
47
- message_deleted: { scene_type: 'group', sub_type: 'recall' },
48
- channel_archive: { scene_type: 'slack', sub_type: 'channel_archive' },
49
- channel_unarchive: { scene_type: 'slack', sub_type: 'channel_unarchive' },
50
- channel_rename: { scene_type: 'slack', sub_type: 'channel_rename' },
51
- channel_created: { scene_type: 'slack', sub_type: 'channel_created' },
52
- channel_deleted: { scene_type: 'slack', sub_type: 'channel_deleted' },
53
- pin_added: { scene_type: 'slack', sub_type: 'pin_added' },
54
- pin_removed: { scene_type: 'slack', sub_type: 'pin_removed' },
55
- app_home_opened: { scene_type: 'slack', sub_type: 'app_home_opened' },
56
- team_join: { scene_type: 'friend', sub_type: 'increase' },
57
- };
1
+ export {};
@@ -0,0 +1,21 @@
1
+ export type VenueVisibilityMode = 'visible' | 'summary' | 'backstage';
2
+ export interface VenueConversationConfig {
3
+ readonly platform: string;
4
+ readonly sceneType?: 'private' | 'group' | 'channel';
5
+ readonly sceneId: string;
6
+ readonly threadId?: string;
7
+ }
8
+ export interface VenueMemberConfig {
9
+ readonly agent: string;
10
+ readonly botEndpoint: string;
11
+ readonly aliases?: readonly string[];
12
+ }
13
+ export interface VenueDefinition {
14
+ readonly id: string;
15
+ readonly label?: string;
16
+ readonly conversation: VenueConversationConfig;
17
+ readonly members: readonly VenueMemberConfig[];
18
+ readonly entry?: string;
19
+ readonly visibility?: VenueVisibilityMode;
20
+ }
21
+ export declare function resolveVenueVisibility(venue: VenueDefinition): VenueVisibilityMode;
@@ -0,0 +1,3 @@
1
+ export function resolveVenueVisibility(venue) {
2
+ return venue.visibility ?? (venue.conversation.sceneType === 'private' ? 'backstage' : 'visible');
3
+ }
@@ -0,0 +1,11 @@
1
+ export interface VenueFloorControllerOptions {
2
+ readonly minIntervalMs?: number;
3
+ readonly now?: () => number;
4
+ readonly sleep?: (ms: number) => Promise<void>;
5
+ }
6
+ export interface VenueFloorController {
7
+ withFloor<T>(venueId: string, actor: string, fn: () => Promise<T> | T): Promise<T>;
8
+ activeSpeaker(venueId: string): string | undefined;
9
+ pendingCount(venueId: string): number;
10
+ }
11
+ export declare function createVenueFloorController(options?: VenueFloorControllerOptions): VenueFloorController;