@zhin.js/core 1.1.57 → 1.1.59

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 (89) hide show
  1. package/lib/built/user-interaction.d.ts +1 -1
  2. package/lib/feature/command.d.ts +2 -4
  3. package/lib/feature/command.js +1 -2
  4. package/lib/feature/middleware.d.ts +2 -2
  5. package/lib/feature/middleware.js +1 -1
  6. package/lib/index.d.ts +1 -1
  7. package/lib/plugin-runtime/im/command-feedback.d.ts +20 -1
  8. package/lib/plugin-runtime/im/command-feedback.js +63 -0
  9. package/lib/plugin-runtime/im/contracts.d.ts +60 -5
  10. package/lib/plugin-runtime/im/contracts.js +6 -2
  11. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +2 -3
  12. package/lib/plugin-runtime/im/endpoint-runtime.js +2 -2
  13. package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
  14. package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
  15. package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
  16. package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
  17. package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
  18. package/lib/plugin-runtime/im/host/database-config.js +114 -0
  19. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +13 -0
  20. package/lib/plugin-runtime/im/host/database-host-installer.js +389 -0
  21. package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
  22. package/lib/plugin-runtime/im/host/database-state.js +91 -0
  23. package/lib/plugin-runtime/im/host/index.d.ts +8 -0
  24. package/lib/plugin-runtime/im/host/index.js +8 -0
  25. package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
  26. package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
  27. package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
  28. package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
  29. package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +33 -0
  30. package/lib/plugin-runtime/im/host/sender-enrichment.js +215 -0
  31. package/lib/plugin-runtime/im/im-runtime.d.ts +7 -3
  32. package/lib/plugin-runtime/im/im-runtime.js +9 -7
  33. package/lib/plugin-runtime/im/inbound-dedup.d.ts +32 -0
  34. package/lib/plugin-runtime/im/inbound-dedup.js +138 -1
  35. package/lib/plugin-runtime/im/inbound-origin.d.ts +24 -2
  36. package/lib/plugin-runtime/im/inbound-origin.js +108 -1
  37. package/lib/plugin-runtime/im/inbound-runtime.d.ts +10 -13
  38. package/lib/plugin-runtime/im/inbound-runtime.js +92 -412
  39. package/lib/plugin-runtime/im/inbound-spine.d.ts +194 -0
  40. package/lib/plugin-runtime/im/inbound-spine.js +333 -0
  41. package/lib/plugin-runtime/im/index.d.ts +5 -7
  42. package/lib/plugin-runtime/im/index.js +5 -6
  43. package/lib/plugin-runtime/im/interaction-runtime.d.ts +4 -7
  44. package/lib/plugin-runtime/im/interaction-runtime.js +5 -8
  45. package/lib/plugin-runtime/im/interactive-router.d.ts +31 -4
  46. package/lib/plugin-runtime/im/interactive-router.js +134 -2
  47. package/lib/plugin-runtime/im/message-dispatcher.d.ts +1 -1
  48. package/lib/plugin-runtime/im/message-dispatcher.js +1 -2
  49. package/lib/plugin-runtime/im/message-events.d.ts +33 -3
  50. package/lib/plugin-runtime/im/message-events.js +34 -0
  51. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +1 -2
  52. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +4 -8
  53. package/lib/plugin-runtime/im/outbound-renderer.d.ts +32 -2
  54. package/lib/plugin-runtime/im/outbound-renderer.js +95 -4
  55. package/package.json +13 -14
  56. package/lib/plugin-runtime/im/captured-endpoint-operation.d.ts +0 -34
  57. package/lib/plugin-runtime/im/captured-endpoint-operation.js +0 -1
  58. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +0 -13
  59. package/lib/plugin-runtime/im/command-menu-navigation.js +0 -43
  60. package/lib/plugin-runtime/im/command-menu-presentation.d.ts +0 -14
  61. package/lib/plugin-runtime/im/command-menu-presentation.js +0 -25
  62. package/lib/plugin-runtime/im/group-rule-violation.d.ts +0 -52
  63. package/lib/plugin-runtime/im/group-rule-violation.js +0 -10
  64. package/lib/plugin-runtime/im/ingress-route.d.ts +0 -10
  65. package/lib/plugin-runtime/im/ingress-route.js +0 -10
  66. package/lib/plugin-runtime/im/interaction-operation.d.ts +0 -12
  67. package/lib/plugin-runtime/im/interaction-operation.js +0 -2
  68. package/lib/plugin-runtime/im/jsx-button-registry.d.ts +0 -31
  69. package/lib/plugin-runtime/im/jsx-button-registry.js +0 -135
  70. package/lib/plugin-runtime/im/locale.d.ts +0 -5
  71. package/lib/plugin-runtime/im/locale.js +0 -12
  72. package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
  73. package/lib/plugin-runtime/im/login-assist-host.js +0 -6
  74. package/lib/plugin-runtime/im/member-welcome.d.ts +0 -8
  75. package/lib/plugin-runtime/im/member-welcome.js +0 -11
  76. package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
  77. package/lib/plugin-runtime/im/message-bus.js +0 -40
  78. package/lib/plugin-runtime/im/operation-endpoint.d.ts +0 -6
  79. package/lib/plugin-runtime/im/operation-endpoint.js +0 -2
  80. package/lib/plugin-runtime/im/operation-resources.d.ts +0 -15
  81. package/lib/plugin-runtime/im/operation-resources.js +0 -2
  82. package/lib/plugin-runtime/im/outbound-ledger.d.ts +0 -24
  83. package/lib/plugin-runtime/im/outbound-ledger.js +0 -114
  84. package/lib/plugin-runtime/im/outbound-presentation.d.ts +0 -19
  85. package/lib/plugin-runtime/im/outbound-presentation.js +0 -41
  86. package/lib/plugin-runtime/im/outbound-projection.d.ts +0 -17
  87. package/lib/plugin-runtime/im/outbound-projection.js +0 -55
  88. package/lib/plugin-runtime/im/runtime-middleware.d.ts +0 -5
  89. package/lib/plugin-runtime/im/runtime-middleware.js +0 -18
@@ -1,52 +0,0 @@
1
- import type { ConversationRef } from '@zhin.js/im-contract';
2
- /** 插件可上报的违规类型(`flood` 由宿主本地检测,不经插件)。 @public */
3
- export type GroupRuleViolationTrigger = 'advertising' | 'abuse';
4
- /** @public */
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
- }>;
11
- /** 违规消息所在的群会话(`kind` 必须是 `group`)。 */
12
- readonly conversation: ConversationRef;
13
- readonly memberId: string;
14
- readonly memberName?: string;
15
- /** 入站消息上的平台角色(群主 / 管理员豁免)。 */
16
- readonly memberRoles?: readonly unknown[];
17
- readonly trigger: GroupRuleViolationTrigger;
18
- /** 原消息发出时间(毫秒)。 */
19
- readonly sentAt: number;
20
- readonly messageId?: string;
21
- /** 命中证据(原文摘录)。 */
22
- readonly evidence?: readonly string[];
23
- /**
24
- * 入群不久即发广告:不按阶梯,直接出一张踢人审批卡(每次人批,绝不自动踢)。
25
- * 只对 `advertising` 生效。
26
- */
27
- readonly newcomer?: boolean;
28
- /** `remind` / `warn` 档的附加动作:撤回原消息(调用方绑定到这条原消息)。 */
29
- readonly recall?: () => Promise<void>;
30
- }
31
- /**
32
- * `handled`:执行器已按规则处理(含被控制面 / 豁免 / 冷却跳过),调用方不得再自行提醒或处罚。
33
- * `no_rule`:该群该类型没有可用规则,调用方可退回只提醒 / 警告。
34
- * @public
35
- */
36
- export type GroupRuleViolationOutcome = 'handled' | 'no_rule';
37
- /** 迁移结果:`created` 新建了待确认规则;`exists` 该群该类型已有规则(任意状态);`unavailable` 规则存储不可用。 @public */
38
- export type GroupRuleDefaultOutcome = 'created' | 'exists' | 'unavailable';
39
- /** @public */
40
- export interface GroupRuleViolationSink {
41
- report(violation: GroupRuleViolationReport): Promise<GroupRuleViolationOutcome>;
42
- /**
43
- * 迁移:该群该类型还没有任何规则时,按默认模板(提醒 → 警告 → 禁言 600 秒,冷静期 30 分钟)
44
- * 生成一条 `pending` 规则并在群里出预览卡,等群主 / 管理员确认一次。已有任意状态的规则则不动。
45
- */
46
- ensureDefaultRule(input: Readonly<{
47
- conversation: ConversationRef;
48
- trigger: GroupRuleViolationTrigger;
49
- }>): Promise<GroupRuleDefaultOutcome>;
50
- }
51
- /** @public */
52
- export declare const groupRuleViolationToken: import("@zhin.js/plugin-runtime").Token<GroupRuleViolationSink>;
@@ -1,10 +0,0 @@
1
- /**
2
- * 群管违规上报(ADR 0039 §5,切片 E)。
3
- *
4
- * content-moderation 等插件只负责「判定违规」,「判定后做什么」交给 Agent host 的群规执行器:
5
- * 按该群生效规则的阶梯执行提醒 / 警告 / 禁言(以规则批准作硬闸批准)/ 建议踢人(每次人批出卡)。
6
- * Agent host 在根作用域提供本 token;未装 Agent(没有本资源)时插件只能提醒 / 警告,不能禁言或踢人。
7
- */
8
- import { createToken } from '@zhin.js/plugin-runtime';
9
- /** @public */
10
- export const groupRuleViolationToken = createToken('zhin.im.group-rule-violations');
@@ -1,10 +0,0 @@
1
- import { type PluginId, type RuntimeSnapshot, type SnapshotLease } from '@zhin.js/plugin-runtime';
2
- import type { Message } from './contracts.js';
3
- /** Generation-owned hooks before ordinary dispatch and after it misses. */
4
- export interface IngressRoute {
5
- preRoute?(message: Message, lease: SnapshotLease, requester: PluginId, conversationSequence: number | undefined): Promise<boolean>;
6
- shouldRouteBeforeDispatch?(message: Message): boolean;
7
- route(message: Message, lease: SnapshotLease, requester: PluginId, conversationSequence: number | undefined): Promise<boolean>;
8
- }
9
- export declare const ingressRouteToken: import("@zhin.js/plugin-runtime").Token<IngressRoute>;
10
- export declare function resolveIngressRoute(snapshot: RuntimeSnapshot): IngressRoute | undefined;
@@ -1,10 +0,0 @@
1
- import { createToken, } from '@zhin.js/plugin-runtime';
2
- export const ingressRouteToken = createToken('zhin.im.ingress-route');
3
- export function resolveIngressRoute(snapshot) {
4
- const candidate = snapshot.resources.get(snapshot.root)?.get(ingressRouteToken.id);
5
- return candidate
6
- && typeof candidate === 'object'
7
- && typeof candidate.route === 'function'
8
- ? candidate
9
- : undefined;
10
- }
@@ -1,12 +0,0 @@
1
- import type { CapturedEndpointOperation } from './captured-endpoint-operation.js';
2
- import type { PluginId, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
3
- /** Core-only trusted operation binding; never read from message metadata. */
4
- export declare const interactionOperationScope: unique symbol;
5
- export interface InteractionOperationScope {
6
- readonly snapshot: RuntimeSnapshot;
7
- readonly owner: PluginId;
8
- /** Explicit stop/source/caller lifetime; not an HMR replacement notification. */
9
- readonly signal?: AbortSignal;
10
- /** Pin one actual source Client and independently owned snapshot until the question settles. */
11
- readonly retain?: () => CapturedEndpointOperation;
12
- }
@@ -1,2 +0,0 @@
1
- /** Core-only trusted operation binding; never read from message metadata. */
2
- export const interactionOperationScope = Symbol('InteractionOperationScope');
@@ -1,31 +0,0 @@
1
- import { type Segment } from '@zhin.js/im-contract';
2
- import type { PluginId, PluginNodeSnapshot, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
3
- import type { ButtonProps } from '../../jsx/message-tags.js';
4
- import type { Message, SendRequest } from './contracts.js';
5
- export declare function isJsxButtonPayload(payload: string | undefined): boolean;
6
- export interface PluginIncarnationRef {
7
- readonly requester: PluginId;
8
- readonly snapshot: RuntimeSnapshot;
9
- readonly node: PluginNodeSnapshot | undefined;
10
- readonly signal?: AbortSignal;
11
- }
12
- /**
13
- * Checks whether the plugin incarnation that registered a callback/interaction
14
- * is still live in `currentSnapshot`.
15
- * Survives HMR of unrelated plugins (where another plugin's node in `tree` changed
16
- * while `origin.node` is unchanged), while retiring if the owning plugin was reloaded/removed,
17
- * its endpoint signal aborted, or the runtime performed a full-generation retirement.
18
- */
19
- export declare function isPluginIncarnationAlive(origin: PluginIncarnationRef, currentSnapshot: RuntimeSnapshot): boolean;
20
- export interface JsxButtonBatch {
21
- bind(props: ButtonProps): Segment;
22
- /** Publish callbacks immediately before transport; revoke them on definitive non-delivery. */
23
- activate(payloads: ReadonlySet<string>): () => void;
24
- }
25
- /** Plugin-incarnation-owned callbacks: survive unrelated plugin HMR; retired when owning plugin reloads. */
26
- export declare class JsxButtonRegistry {
27
- #private;
28
- prepare(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
29
- dispatch(message: Message, payload: string, snapshot: RuntimeSnapshot): Promise<boolean>;
30
- }
31
- export declare function collectButtonPayloads(payload: unknown): Set<string>;
@@ -1,135 +0,0 @@
1
- import { interactionMessages as t } from '../../built/interaction-messages.js';
2
- import { randomUUID } from 'node:crypto';
3
- import { jsx } from '@zhin.js/jsx';
4
- import { conversationRefKey } from '@zhin.js/im-contract';
5
- import { bindOperationInput } from '@zhin.js/feature-kit';
6
- import { operationEndpoint } from './operation-endpoint.js';
7
- import { isKeyboardSegment } from '../../built/interactive-segments/types.js';
8
- const PREFIX = 'zhin:jsx:';
9
- const BUTTON_TTL_MS = 60 * 60 * 1000;
10
- export function isJsxButtonPayload(payload) {
11
- return payload?.startsWith(PREFIX) === true;
12
- }
13
- function hasIdenticalPluginTree(left, right) {
14
- if (left === right)
15
- return true;
16
- if (left.size !== right.size)
17
- return false;
18
- for (const [id, node] of left) {
19
- if (right.get(id) !== node)
20
- return false;
21
- }
22
- return true;
23
- }
24
- /**
25
- * Checks whether the plugin incarnation that registered a callback/interaction
26
- * is still live in `currentSnapshot`.
27
- * Survives HMR of unrelated plugins (where another plugin's node in `tree` changed
28
- * while `origin.node` is unchanged), while retiring if the owning plugin was reloaded/removed,
29
- * its endpoint signal aborted, or the runtime performed a full-generation retirement.
30
- */
31
- export function isPluginIncarnationAlive(origin, currentSnapshot) {
32
- if (origin.signal?.aborted) {
33
- return false;
34
- }
35
- if (origin.snapshot === currentSnapshot) {
36
- return true;
37
- }
38
- if (!origin.node || hasIdenticalPluginTree(origin.snapshot.tree, currentSnapshot.tree)) {
39
- return false;
40
- }
41
- const currentNode = currentSnapshot.tree.get(origin.requester);
42
- return currentNode !== undefined && currentNode === origin.node;
43
- }
44
- /** Plugin-incarnation-owned callbacks: survive unrelated plugin HMR; retired when owning plugin reloads. */
45
- export class JsxButtonRegistry {
46
- #bindings = new Map();
47
- prepare(request, snapshot) {
48
- const pending = new Map();
49
- const node = snapshot.tree.get(request.requester);
50
- const signal = request[operationEndpoint]?.signal;
51
- return {
52
- bind: (props) => {
53
- const { onClick, payload: manualPayload, children, label, id, ...options } = props;
54
- if (onClick !== undefined && typeof onClick !== 'function')
55
- throw new TypeError('Button onClick must be a function');
56
- if (onClick && manualPayload !== undefined)
57
- throw new TypeError('Button accepts onClick or payload, not both');
58
- if (!onClick && typeof manualPayload !== 'string')
59
- throw new TypeError('Button requires onClick or payload');
60
- const payload = onClick ? `${PREFIX}${randomUUID()}` : manualPayload;
61
- if (onClick && !props.disabled)
62
- pending.set(payload, {
63
- onClick,
64
- requester: request.requester,
65
- snapshot,
66
- node,
67
- ...(signal ? { signal } : {}),
68
- conversationKey: conversationRefKey(request.conversation),
69
- expiresAt: 0,
70
- });
71
- return { type: 'keyboard', data: { rows: [[{
72
- ...options,
73
- id: id ?? randomUUID(),
74
- label: label ?? children,
75
- payload,
76
- ...(onClick ? { mode: 'callback' } : {}),
77
- }]] } };
78
- },
79
- activate: (payloads) => {
80
- const activated = [];
81
- this.#prune(snapshot);
82
- for (const [payload, binding] of pending) {
83
- if (!payloads.has(payload))
84
- continue;
85
- this.#bindings.set(payload, { ...binding, expiresAt: Date.now() + BUTTON_TTL_MS });
86
- activated.push(payload);
87
- }
88
- pending.clear();
89
- return () => { for (const payload of activated)
90
- this.#bindings.delete(payload); };
91
- },
92
- };
93
- }
94
- async dispatch(message, payload, snapshot) {
95
- if (!isJsxButtonPayload(payload))
96
- return false;
97
- this.#prune(snapshot);
98
- const binding = this.#bindings.get(payload);
99
- // Never invoke a retired closure. The reply uses this incoming operation's scope.
100
- if (!binding || !isPluginIncarnationAlive(binding, snapshot)) {
101
- if (binding)
102
- this.#bindings.delete(payload);
103
- await message.$reply(t(message.locale, 'expired'));
104
- return true;
105
- }
106
- if (binding.conversationKey !== conversationRefKey(message.conversation))
107
- return true;
108
- const bound = bindOperationInput(message, binding.requester, snapshot);
109
- const content = await binding.onClick(bound);
110
- if (typeof content === 'number')
111
- await bound.$reply(jsx('text', { text: String(content) }));
112
- else if (content != null && typeof content !== 'boolean')
113
- await bound.$reply(content);
114
- return true;
115
- }
116
- #prune(currentSnapshot) {
117
- const now = Date.now();
118
- for (const [payload, binding] of this.#bindings) {
119
- if (binding.expiresAt <= now || (currentSnapshot && !isPluginIncarnationAlive(binding, currentSnapshot))) {
120
- this.#bindings.delete(payload);
121
- }
122
- }
123
- }
124
- }
125
- export function collectButtonPayloads(payload) {
126
- const result = new Set();
127
- for (const item of Array.isArray(payload) ? payload : [payload]) {
128
- if (isKeyboardSegment(item)) {
129
- for (const row of item.data.rows)
130
- for (const button of row)
131
- result.add(button.payload);
132
- }
133
- }
134
- return result;
135
- }
@@ -1,5 +0,0 @@
1
- import { type Locale, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
- import type { ConversationRef } from '@zhin.js/im-contract';
3
- export declare function projectLocale(snapshot: RuntimeSnapshot): Locale;
4
- /** Resolve once per operation; callbacks retain the original operation's language. */
5
- export declare function messageLocale(snapshot: RuntimeSnapshot, conversation: Pick<ConversationRef, 'endpoint'>, senderId?: string): Promise<Locale>;
@@ -1,12 +0,0 @@
1
- import { projectLocaleToken, resolveLocale, userLocalePreferencesToken } from '@zhin.js/plugin-runtime';
2
- export function projectLocale(snapshot) {
3
- return resolveLocale(snapshot.resources.get(snapshot.root)?.get(projectLocaleToken.id)
4
- ?? snapshot.config.get(snapshot.root)?.locale);
5
- }
6
- /** Resolve once per operation; callbacks retain the original operation's language. */
7
- export async function messageLocale(snapshot, conversation, senderId) {
8
- const preferences = snapshot.resources.get(snapshot.root)?.get(userLocalePreferencesToken.id);
9
- return senderId && preferences
10
- ? await preferences.get(conversation.endpoint, senderId) ?? projectLocale(snapshot)
11
- : projectLocale(snapshot);
12
- }
@@ -1,6 +0,0 @@
1
- import { LoginAssist } from '../../built/login-assist.js';
2
- /**
3
- * Plugin Runtime login-assist port(与出站消息服务并列)。
4
- * 适配器 waitForInput;Console / stdin 经 listPending + submit 消费。
5
- */
6
- export declare const loginAssistToken: import("@zhin.js/plugin-runtime").Token<LoginAssist>;
@@ -1,6 +0,0 @@
1
- import { createToken } from '@zhin.js/plugin-runtime';
2
- /**
3
- * Plugin Runtime login-assist port(与出站消息服务并列)。
4
- * 适配器 waitForInput;Console / stdin 经 listPending + submit 消费。
5
- */
6
- export const loginAssistToken = createToken('zhin.im.login-assist');
@@ -1,8 +0,0 @@
1
- import type { ConversationRef } from '@zhin.js/im-contract';
2
- /** @public */
3
- export interface MemberWelcomeOwner {
4
- /** 该会话的入群欢迎是否已由会话级欢迎接管(session-ops `welcome.enabled`)。只读内存,不发送、不写审计。 */
5
- ownsWelcome(conversation: ConversationRef): boolean;
6
- }
7
- /** @public */
8
- export declare const memberWelcomeOwnerToken: import("@zhin.js/plugin-runtime").Token<MemberWelcomeOwner>;
@@ -1,11 +0,0 @@
1
- /**
2
- * 入群欢迎归属(#1012 A9 方案②)。
3
- *
4
- * Agent 会话级欢迎(ADR 0037 切片 A,session-ops `welcome.enabled` + MemberLifecycle)由 Agent host 在根作用域提供本 token。
5
- * 插件里的旧欢迎(如 group-suite `welcomeMessage`)发送前先问归属:已被会话级欢迎接管的会话,插件不再发送,
6
- * 欢迎统一走 MemberLifecycle(合并窗口、小时上限、控制面、session-gate),避免同一次入群双发。
7
- * 未装 Agent(没有本资源)时插件保持原行为。
8
- */
9
- import { createToken } from '@zhin.js/plugin-runtime';
10
- /** @public */
11
- export const memberWelcomeOwnerToken = createToken('zhin.im.member-welcome-owner');
@@ -1,38 +0,0 @@
1
- /**
2
- * Generation-owned IM lifecycle event bus.
3
- *
4
- * Runtime services resolve this bus through Scope+Token and never depend on a
5
- * process-global event owner.
6
- */
7
- import type { DeliveryReceipt } from '@zhin.js/im-contract';
8
- import type { Message, OutboundEnvelope, SendContent } from './contracts.js';
9
- export interface EndpointEvent {
10
- readonly adapter: string;
11
- readonly endpointKey: string;
12
- readonly error?: Error;
13
- }
14
- export interface MessageBusEventMap {
15
- 'message.receive': [message: Message];
16
- 'before.sendMessage': [envelope: OutboundEnvelope];
17
- 'message.send': [payload: {
18
- adapter: string;
19
- endpointKey: string;
20
- content: SendContent;
21
- receipt: DeliveryReceipt;
22
- }];
23
- 'endpoint.connect': [event: EndpointEvent];
24
- 'endpoint.disconnect': [event: EndpointEvent];
25
- 'endpoint.error': [event: EndpointEvent];
26
- }
27
- export type MessageBusEventName = keyof MessageBusEventMap;
28
- export declare class MessageBus {
29
- private readonly emitter;
30
- constructor();
31
- on<E extends MessageBusEventName>(event: E, listener: (...args: MessageBusEventMap[E]) => void): () => void;
32
- once<E extends MessageBusEventName>(event: E, listener: (...args: MessageBusEventMap[E]) => void): () => void;
33
- emit<E extends MessageBusEventName>(event: E, ...args: MessageBusEventMap[E]): void;
34
- off<E extends MessageBusEventName>(event: E, listener: (...args: MessageBusEventMap[E]) => void): void;
35
- listenerCount(event: MessageBusEventName): number;
36
- removeAllListeners(event?: MessageBusEventName): void;
37
- }
38
- export declare const messageBusToken: import("@zhin.js/plugin-runtime").Token<MessageBus>;
@@ -1,40 +0,0 @@
1
- /**
2
- * Generation-owned IM lifecycle event bus.
3
- *
4
- * Runtime services resolve this bus through Scope+Token and never depend on a
5
- * process-global event owner.
6
- */
7
- import { EventEmitter } from 'node:events';
8
- import { createToken } from '@zhin.js/plugin-runtime';
9
- export class MessageBus {
10
- emitter = new EventEmitter();
11
- constructor() {
12
- this.emitter.setMaxListeners(50);
13
- }
14
- on(event, listener) {
15
- this.emitter.on(event, listener);
16
- return () => this.emitter.off(event, listener);
17
- }
18
- once(event, listener) {
19
- this.emitter.once(event, listener);
20
- return () => this.emitter.off(event, listener);
21
- }
22
- emit(event, ...args) {
23
- this.emitter.emit(event, ...args);
24
- }
25
- off(event, listener) {
26
- this.emitter.off(event, listener);
27
- }
28
- listenerCount(event) {
29
- return this.emitter.listenerCount(event);
30
- }
31
- removeAllListeners(event) {
32
- if (event) {
33
- this.emitter.removeAllListeners(event);
34
- }
35
- else {
36
- this.emitter.removeAllListeners();
37
- }
38
- }
39
- }
40
- export const messageBusToken = createToken('zhin.im.message-bus');
@@ -1,6 +0,0 @@
1
- import type { EndpointChildLease } from '@zhin.js/adapter';
2
- /** Internal send binding retained by one inbound operation; never a wire/config field. */
3
- export declare const operationEndpoint: unique symbol;
4
- export interface OperationEndpointSource {
5
- readonly [operationEndpoint]?: EndpointChildLease;
6
- }
@@ -1,2 +0,0 @@
1
- /** Internal send binding retained by one inbound operation; never a wire/config field. */
2
- export const operationEndpoint = Symbol('zhin.im.operation-endpoint');
@@ -1,15 +0,0 @@
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>;
@@ -1,2 +0,0 @@
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');
@@ -1,24 +0,0 @@
1
- import type { ConversationRef, DeliveryReceipt } from '@zhin.js/im-contract';
2
- /**
3
- * scope 键不含 endpoint id:同一个群里不同 Bot 的 conversationRefKey 不同,
4
- * 但它们互相的回显仍属同一会话。
5
- */
6
- export declare function ledgerScopeOf(conversation: ConversationRef): string;
7
- export declare function digestText(text: string): string | undefined;
8
- export interface LedgerMatch {
9
- readonly endpointId: string;
10
- }
11
- export declare class OutboundLedger {
12
- #private;
13
- private readonly now;
14
- constructor(now?: () => number);
15
- get size(): number;
16
- /** 仅在 `receipt.status === 'sent'` 时记录;`payload` 应为最终投影后的 payload。 */
17
- record(conversation: ConversationRef, receipt: DeliveryReceipt, payload: unknown): void;
18
- matchById(scope: string, messageId: unknown): LedgerMatch | undefined;
19
- /**
20
- * 摘要兜底(“账号 id 对不上”时):30 秒窗口、一次性。
21
- * 权衡:人类在窗口内原样复读 Bot 刚发的文本,会被当作回显丢弃一次。
22
- */
23
- matchByDigest(scope: string, text: string, now?: number): LedgerMatch | undefined;
24
- }
@@ -1,114 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import { segmentsToPlainText } from '../../built/segment-contract/text.js';
3
- /**
4
- * @internal 出站 ledger:入站 origin 判定的关联层兜底。
5
- *
6
- * 只保存 message id 与文本摘要(不存原文),有界内存、短 TTL。
7
- * 写入发生在 `deliver` 成功之后的旁路,失败不影响 receipt。
8
- */
9
- const MAX_ENTRIES = 2000;
10
- const TTL_MS = 10 * 60_000;
11
- const DIGEST_WINDOW_MS = 30_000;
12
- const MIN_DIGEST_TEXT = 4;
13
- /**
14
- * scope 键不含 endpoint id:同一个群里不同 Bot 的 conversationRefKey 不同,
15
- * 但它们互相的回显仍属同一会话。
16
- */
17
- export function ledgerScopeOf(conversation) {
18
- return [
19
- conversation.endpoint.adapter,
20
- conversation.kind,
21
- conversation.id,
22
- conversation.parent?.kind ?? '',
23
- conversation.parent?.id ?? '',
24
- conversation.threadId ?? '',
25
- ].join('\0');
26
- }
27
- export function digestText(text) {
28
- const normalized = text.replace(/\s+/g, ' ').trim();
29
- if (normalized.length < MIN_DIGEST_TEXT)
30
- return undefined;
31
- return createHash('sha256').update(normalized).digest('hex').slice(0, 16);
32
- }
33
- function payloadText(payload) {
34
- if (typeof payload === 'string')
35
- return payload;
36
- if (Array.isArray(payload)) {
37
- return segmentsToPlainText(payload.filter((item) => !!item && typeof item === 'object' && typeof item.type === 'string'));
38
- }
39
- return '';
40
- }
41
- export class OutboundLedger {
42
- now;
43
- #entries = [];
44
- constructor(now = Date.now) {
45
- this.now = now;
46
- }
47
- get size() {
48
- return this.#entries.length;
49
- }
50
- /** 仅在 `receipt.status === 'sent'` 时记录;`payload` 应为最终投影后的 payload。 */
51
- record(conversation, receipt, payload) {
52
- if (receipt.status !== 'sent')
53
- return;
54
- const at = this.now();
55
- this.#prune(at);
56
- const rawId = receipt.message?.id;
57
- const messageId = rawId === undefined || rawId === null || String(rawId) === '' ? undefined : String(rawId);
58
- const digest = digestText(payloadText(payload));
59
- if (messageId === undefined && digest === undefined)
60
- return;
61
- this.#entries.push({
62
- scope: ledgerScopeOf(conversation),
63
- endpointId: conversation.endpoint.id,
64
- ...(messageId !== undefined ? { messageId } : {}),
65
- ...(digest !== undefined ? { digest } : {}),
66
- at,
67
- digestConsumed: false,
68
- });
69
- while (this.#entries.length > MAX_ENTRIES)
70
- this.#entries.shift();
71
- }
72
- matchById(scope, messageId) {
73
- if (typeof messageId !== 'string' && typeof messageId !== 'number')
74
- return undefined;
75
- const id = String(messageId);
76
- if (id === '')
77
- return undefined;
78
- const at = this.now();
79
- for (let i = this.#entries.length - 1; i >= 0; i--) {
80
- const entry = this.#entries[i];
81
- if (at - entry.at > TTL_MS)
82
- continue;
83
- if (entry.scope === scope && entry.messageId === id)
84
- return { endpointId: entry.endpointId };
85
- }
86
- return undefined;
87
- }
88
- /**
89
- * 摘要兜底(“账号 id 对不上”时):30 秒窗口、一次性。
90
- * 权衡:人类在窗口内原样复读 Bot 刚发的文本,会被当作回显丢弃一次。
91
- */
92
- matchByDigest(scope, text, now = this.now()) {
93
- const digest = digestText(typeof text === 'string' ? text : '');
94
- if (digest === undefined)
95
- return undefined;
96
- for (let i = this.#entries.length - 1; i >= 0; i--) {
97
- const entry = this.#entries[i];
98
- if (now - entry.at > DIGEST_WINDOW_MS)
99
- continue;
100
- if (entry.digestConsumed || entry.scope !== scope || entry.digest !== digest)
101
- continue;
102
- entry.digestConsumed = true;
103
- return { endpointId: entry.endpointId };
104
- }
105
- return undefined;
106
- }
107
- #prune(at) {
108
- let drop = 0;
109
- while (drop < this.#entries.length && at - this.#entries[drop].at > TTL_MS)
110
- drop++;
111
- if (drop > 0)
112
- this.#entries.splice(0, drop);
113
- }
114
- }
@@ -1,19 +0,0 @@
1
- import type { ConversationRef } from '@zhin.js/im-contract';
2
- import { type PluginId, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
3
- /** Keep the adapter's presentation or prefer its existing readable text fallback. */
4
- export type OutboundPresentationMode = 'default' | 'text';
5
- export interface OutboundPresentationPreferences {
6
- readonly html?: OutboundPresentationMode;
7
- readonly markdown?: OutboundPresentationMode;
8
- readonly interactive?: OutboundPresentationMode;
9
- }
10
- export interface OutboundPresentationContext {
11
- readonly conversation: ConversationRef;
12
- readonly requester: PluginId;
13
- readonly generation: number;
14
- }
15
- /** A synchronous, side-effect-free decision, shared by delivery and target previews. */
16
- export type OutboundPresentation = (context: OutboundPresentationContext) => OutboundPresentationPreferences | undefined;
17
- export declare const outboundPresentationToken: import("@zhin.js/plugin-runtime").Token<OutboundPresentation>;
18
- /** Resolve once per operation; replacements reuse this detached, immutable decision. */
19
- export declare function resolveOutboundPresentation(snapshot: RuntimeSnapshot, conversation: ConversationRef, requester: PluginId): OutboundPresentationPreferences | undefined;
@@ -1,41 +0,0 @@
1
- import { formatCompact, getLogger } from '@zhin.js/logger';
2
- import { createToken } from '@zhin.js/plugin-runtime';
3
- export const outboundPresentationToken = createToken('zhin.outbound-presentation', 'Root-selected outbound presentation within the adapter capability boundary');
4
- const logger = getLogger('im.outbound');
5
- /** Resolve once per operation; replacements reuse this detached, immutable decision. */
6
- export function resolveOutboundPresentation(snapshot, conversation, requester) {
7
- const policy = snapshot.resources.get(snapshot.root)?.get(outboundPresentationToken.id);
8
- if (policy === undefined)
9
- return undefined;
10
- try {
11
- const view = Object.freeze({
12
- endpoint: Object.freeze({ id: conversation.endpoint.id, adapter: conversation.endpoint.adapter }),
13
- kind: conversation.kind,
14
- id: conversation.id,
15
- ...(conversation.parent ? { parent: Object.freeze({ kind: conversation.parent.kind, id: conversation.parent.id }) } : {}),
16
- ...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
17
- });
18
- const result = policy(Object.freeze({ conversation: view, requester, generation: snapshot.generation }));
19
- if (result === undefined)
20
- return undefined;
21
- if (result && typeof result === 'object' && 'then' in result) {
22
- // An accidentally async policy is outside the contract. Consume a possible
23
- // rejection without waiting for it or applying a later decision to this send.
24
- void Promise.resolve(result).catch(() => undefined);
25
- throw new TypeError('Outbound presentation must be synchronous');
26
- }
27
- if (!result || typeof result !== 'object')
28
- throw new TypeError('Invalid outbound presentation');
29
- const { html, markdown, interactive } = result;
30
- for (const value of [html, markdown, interactive]) {
31
- if (value !== undefined && value !== 'default' && value !== 'text')
32
- throw new TypeError('Invalid outbound presentation mode');
33
- }
34
- return Object.freeze({ html, markdown, interactive });
35
- }
36
- catch {
37
- // Never log the callback error, content or user-provided values; do not retry it.
38
- logger.warn(formatCompact({ op: 'outbound_presentation', status: 'fallback', reason: 'policy_failed', generation: snapshot.generation }));
39
- return undefined;
40
- }
41
- }