@zhin.js/core 1.1.56 → 1.1.58

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 (117) 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.d.ts +1 -1
  6. package/lib/built/user-interaction.js +3 -1
  7. package/lib/feature/command.d.ts +2 -4
  8. package/lib/feature/command.js +1 -2
  9. package/lib/feature/middleware.d.ts +2 -2
  10. package/lib/feature/middleware.js +1 -1
  11. package/lib/index.d.ts +2 -1
  12. package/lib/index.js +2 -0
  13. package/lib/plugin-runtime/im/command-feedback.d.ts +20 -1
  14. package/lib/plugin-runtime/im/command-feedback.js +63 -0
  15. package/lib/plugin-runtime/im/contracts.d.ts +60 -5
  16. package/lib/plugin-runtime/im/contracts.js +6 -2
  17. package/lib/plugin-runtime/im/conversation-runtime.d.ts +2 -2
  18. package/lib/plugin-runtime/im/conversation-runtime.js +6 -4
  19. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +2 -3
  20. package/lib/plugin-runtime/im/endpoint-runtime.js +2 -2
  21. package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
  22. package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
  23. package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
  24. package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
  25. package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
  26. package/lib/plugin-runtime/im/host/database-config.js +114 -0
  27. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +13 -0
  28. package/lib/plugin-runtime/im/host/database-host-installer.js +389 -0
  29. package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
  30. package/lib/plugin-runtime/im/host/database-state.js +91 -0
  31. package/lib/plugin-runtime/im/host/index.d.ts +8 -0
  32. package/lib/plugin-runtime/im/host/index.js +8 -0
  33. package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
  34. package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
  35. package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
  36. package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
  37. package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +33 -0
  38. package/lib/plugin-runtime/im/host/sender-enrichment.js +215 -0
  39. package/lib/plugin-runtime/im/im-runtime.d.ts +7 -3
  40. package/lib/plugin-runtime/im/im-runtime.js +9 -7
  41. package/lib/plugin-runtime/im/inbound-dedup.d.ts +33 -0
  42. package/lib/plugin-runtime/im/inbound-dedup.js +139 -1
  43. package/lib/plugin-runtime/im/inbound-origin.d.ts +51 -2
  44. package/lib/plugin-runtime/im/inbound-origin.js +108 -1
  45. package/lib/plugin-runtime/im/inbound-runtime.d.ts +10 -13
  46. package/lib/plugin-runtime/im/inbound-runtime.js +88 -349
  47. package/lib/plugin-runtime/im/inbound-spine.d.ts +194 -0
  48. package/lib/plugin-runtime/im/inbound-spine.js +333 -0
  49. package/lib/plugin-runtime/im/index.d.ts +5 -7
  50. package/lib/plugin-runtime/im/index.js +5 -6
  51. package/lib/plugin-runtime/im/interaction-runtime.d.ts +8 -10
  52. package/lib/plugin-runtime/im/interaction-runtime.js +86 -28
  53. package/lib/plugin-runtime/im/interactive-router.d.ts +55 -8
  54. package/lib/plugin-runtime/im/interactive-router.js +244 -35
  55. package/lib/plugin-runtime/im/message-dispatcher.d.ts +1 -1
  56. package/lib/plugin-runtime/im/message-dispatcher.js +58 -7
  57. package/lib/plugin-runtime/im/message-events.d.ts +33 -3
  58. package/lib/plugin-runtime/im/message-events.js +34 -0
  59. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +4 -4
  60. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +75 -29
  61. package/lib/plugin-runtime/im/outbound-renderer.d.ts +32 -2
  62. package/lib/plugin-runtime/im/outbound-renderer.js +95 -4
  63. package/lib/runtime.d.ts +2 -0
  64. package/lib/runtime.js +2 -0
  65. package/lib/venue/contracts.d.ts +21 -0
  66. package/lib/venue/contracts.js +3 -0
  67. package/lib/venue/floor-controller.d.ts +11 -0
  68. package/lib/venue/floor-controller.js +63 -0
  69. package/lib/venue/index.d.ts +13 -0
  70. package/lib/venue/index.js +11 -0
  71. package/lib/venue/membership-port.d.ts +23 -0
  72. package/lib/venue/membership-port.js +141 -0
  73. package/lib/venue/projector.d.ts +38 -0
  74. package/lib/venue/projector.js +45 -0
  75. package/lib/venue/registry.d.ts +16 -0
  76. package/lib/venue/registry.js +63 -0
  77. package/lib/venue/router.d.ts +19 -0
  78. package/lib/venue/router.js +101 -0
  79. package/lib/venue/send-limiter.d.ts +17 -0
  80. package/lib/venue/send-limiter.js +73 -0
  81. package/lib/venue/validator.d.ts +6 -0
  82. package/lib/venue/validator.js +160 -0
  83. package/package.json +16 -17
  84. package/lib/plugin-runtime/im/captured-endpoint-operation.d.ts +0 -34
  85. package/lib/plugin-runtime/im/captured-endpoint-operation.js +0 -1
  86. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +0 -13
  87. package/lib/plugin-runtime/im/command-menu-navigation.js +0 -43
  88. package/lib/plugin-runtime/im/command-menu-presentation.d.ts +0 -14
  89. package/lib/plugin-runtime/im/command-menu-presentation.js +0 -25
  90. package/lib/plugin-runtime/im/group-rule-violation.d.ts +0 -52
  91. package/lib/plugin-runtime/im/group-rule-violation.js +0 -10
  92. package/lib/plugin-runtime/im/ingress-route.d.ts +0 -10
  93. package/lib/plugin-runtime/im/ingress-route.js +0 -10
  94. package/lib/plugin-runtime/im/interaction-operation.d.ts +0 -12
  95. package/lib/plugin-runtime/im/interaction-operation.js +0 -2
  96. package/lib/plugin-runtime/im/jsx-button-registry.d.ts +0 -17
  97. package/lib/plugin-runtime/im/jsx-button-registry.js +0 -98
  98. package/lib/plugin-runtime/im/locale.d.ts +0 -5
  99. package/lib/plugin-runtime/im/locale.js +0 -12
  100. package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
  101. package/lib/plugin-runtime/im/login-assist-host.js +0 -6
  102. package/lib/plugin-runtime/im/member-welcome.d.ts +0 -8
  103. package/lib/plugin-runtime/im/member-welcome.js +0 -11
  104. package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
  105. package/lib/plugin-runtime/im/message-bus.js +0 -40
  106. package/lib/plugin-runtime/im/operation-endpoint.d.ts +0 -6
  107. package/lib/plugin-runtime/im/operation-endpoint.js +0 -2
  108. package/lib/plugin-runtime/im/operation-resources.d.ts +0 -15
  109. package/lib/plugin-runtime/im/operation-resources.js +0 -2
  110. package/lib/plugin-runtime/im/outbound-ledger.d.ts +0 -24
  111. package/lib/plugin-runtime/im/outbound-ledger.js +0 -114
  112. package/lib/plugin-runtime/im/outbound-presentation.d.ts +0 -19
  113. package/lib/plugin-runtime/im/outbound-presentation.js +0 -41
  114. package/lib/plugin-runtime/im/outbound-projection.d.ts +0 -17
  115. package/lib/plugin-runtime/im/outbound-projection.js +0 -55
  116. package/lib/plugin-runtime/im/runtime-middleware.d.ts +0 -5
  117. package/lib/plugin-runtime/im/runtime-middleware.js +0 -18
@@ -0,0 +1,160 @@
1
+ const VALID_SCENE_TYPES = new Set(['private', 'group', 'channel']);
2
+ const VALID_VISIBILITY_MODES = new Set(['visible', 'summary', 'backstage']);
3
+ export class VenueValidationError extends Error {
4
+ issues;
5
+ constructor(issues) {
6
+ super(`Invalid venue definitions:\n${issues.map((issue) => ` - ${issue}`).join('\n')}`);
7
+ this.name = 'VenueValidationError';
8
+ this.issues = Object.freeze([...issues]);
9
+ }
10
+ }
11
+ function isNonEmptyString(value) {
12
+ return typeof value === 'string' && value.trim().length > 0;
13
+ }
14
+ export function validateVenueDefinitions(venues) {
15
+ if (!Array.isArray(venues)) {
16
+ throw new VenueValidationError(['venues must be an array']);
17
+ }
18
+ const issues = [];
19
+ const seenVenueIds = new Set();
20
+ const seenConversations = [];
21
+ for (let i = 0; i < venues.length; i++) {
22
+ const venue = venues[i];
23
+ const label = isNonEmptyString(venue?.id) ? `venue "${venue.id.trim()}"` : `venues[${i}]`;
24
+ if (!venue || typeof venue !== 'object') {
25
+ issues.push(`${label}: must be an object`);
26
+ continue;
27
+ }
28
+ if (!isNonEmptyString(venue.id)) {
29
+ issues.push(`${label}: id must be a non-empty string`);
30
+ }
31
+ else {
32
+ const id = venue.id.trim();
33
+ if (seenVenueIds.has(id)) {
34
+ issues.push(`${label}: duplicate venue id "${id}"`);
35
+ }
36
+ else {
37
+ seenVenueIds.add(id);
38
+ }
39
+ }
40
+ const conv = venue.conversation;
41
+ if (!conv || typeof conv !== 'object') {
42
+ issues.push(`${label}: conversation is required`);
43
+ }
44
+ else {
45
+ const platformOk = isNonEmptyString(conv.platform);
46
+ const sceneIdOk = isNonEmptyString(conv.sceneId);
47
+ if (!platformOk) {
48
+ issues.push(`${label}: conversation.platform must be a non-empty string`);
49
+ }
50
+ if (!sceneIdOk) {
51
+ issues.push(`${label}: conversation.sceneId must be a non-empty string`);
52
+ }
53
+ if (conv.sceneType !== undefined && !VALID_SCENE_TYPES.has(conv.sceneType)) {
54
+ issues.push(`${label}: conversation.sceneType must be one of "private", "group", "channel"`);
55
+ }
56
+ if (conv.threadId !== undefined && !isNonEmptyString(conv.threadId)) {
57
+ issues.push(`${label}: conversation.threadId must be a non-empty string when provided`);
58
+ }
59
+ if (platformOk && sceneIdOk) {
60
+ const platform = conv.platform.trim();
61
+ const sceneType = conv.sceneType;
62
+ const sceneId = conv.sceneId.trim();
63
+ const threadId = conv.threadId?.trim() ?? '';
64
+ const conflict = seenConversations.find((existing) => existing.platform === platform
65
+ && existing.sceneId === sceneId
66
+ && existing.threadId === threadId
67
+ && (existing.sceneType === undefined || sceneType === undefined || existing.sceneType === sceneType));
68
+ if (conflict) {
69
+ issues.push(`${label}: duplicate conversation (${platform}/${sceneType ?? '*'}/${sceneId}${threadId ? `/${threadId}` : ''}) already bound by venue "${conflict.venueId}"`);
70
+ }
71
+ else {
72
+ seenConversations.push({
73
+ venueId: isNonEmptyString(venue.id) ? venue.id.trim() : `venues[${i}]`,
74
+ platform,
75
+ sceneType,
76
+ sceneId,
77
+ threadId,
78
+ });
79
+ }
80
+ }
81
+ }
82
+ const memberAgents = new Set();
83
+ const memberEndpoints = new Set();
84
+ const memberNamesLower = new Set();
85
+ if (!Array.isArray(venue.members) || venue.members.length === 0) {
86
+ issues.push(`${label}: members must be a non-empty array`);
87
+ }
88
+ else {
89
+ for (let m = 0; m < venue.members.length; m++) {
90
+ const member = venue.members[m];
91
+ const memberLabel = `${label}.members[${m}]`;
92
+ if (!member || typeof member !== 'object') {
93
+ issues.push(`${memberLabel}: must be an object`);
94
+ continue;
95
+ }
96
+ if (!isNonEmptyString(member.agent)) {
97
+ issues.push(`${memberLabel}: agent must be a non-empty string`);
98
+ }
99
+ else {
100
+ const agent = member.agent.trim();
101
+ if (memberAgents.has(agent)) {
102
+ issues.push(`${memberLabel}: duplicate member agent "${agent}" in venue`);
103
+ }
104
+ else {
105
+ memberAgents.add(agent);
106
+ memberNamesLower.add(agent.toLowerCase());
107
+ }
108
+ }
109
+ if (!isNonEmptyString(member.botEndpoint)) {
110
+ issues.push(`${memberLabel}: botEndpoint must be a non-empty string`);
111
+ }
112
+ else {
113
+ const endpoint = member.botEndpoint.trim();
114
+ if (memberEndpoints.has(endpoint)) {
115
+ issues.push(`${memberLabel}: duplicate member botEndpoint "${endpoint}" in venue`);
116
+ }
117
+ else {
118
+ memberEndpoints.add(endpoint);
119
+ }
120
+ }
121
+ if (member.aliases !== undefined) {
122
+ if (!Array.isArray(member.aliases)) {
123
+ issues.push(`${memberLabel}: aliases must be an array of strings`);
124
+ }
125
+ else {
126
+ for (let a = 0; a < member.aliases.length; a++) {
127
+ const alias = member.aliases[a];
128
+ if (!isNonEmptyString(alias)) {
129
+ issues.push(`${memberLabel}.aliases[${a}]: alias must be a non-empty string`);
130
+ }
131
+ else {
132
+ const lower = alias.trim().toLowerCase();
133
+ if (memberNamesLower.has(lower)) {
134
+ issues.push(`${memberLabel}.aliases[${a}]: duplicate alias "${alias}" in venue`);
135
+ }
136
+ else {
137
+ memberNamesLower.add(lower);
138
+ }
139
+ }
140
+ }
141
+ }
142
+ }
143
+ }
144
+ }
145
+ if (venue.entry !== undefined) {
146
+ if (!isNonEmptyString(venue.entry)) {
147
+ issues.push(`${label}: entry must be a non-empty string when specified`);
148
+ }
149
+ else if (memberAgents.size > 0 && !memberAgents.has(venue.entry.trim())) {
150
+ issues.push(`${label}: entry "${venue.entry}" does not match any member agent in venue`);
151
+ }
152
+ }
153
+ if (venue.visibility !== undefined && !VALID_VISIBILITY_MODES.has(venue.visibility)) {
154
+ issues.push(`${label}: visibility must be "visible", "summary", or "backstage"`);
155
+ }
156
+ }
157
+ if (issues.length > 0) {
158
+ throw new VenueValidationError(issues);
159
+ }
160
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhin.js/core",
3
- "version": "1.1.56",
3
+ "version": "1.1.58",
4
4
  "description": "Zhin机器人核心框架",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -57,29 +57,28 @@
57
57
  "dependencies": {
58
58
  "qrcode": "^1.5.4",
59
59
  "segment-matcher": "^1.0.5",
60
- "@zhin.js/command": "1.1.14",
61
- "@zhin.js/component": "1.1.13",
62
- "@zhin.js/adapter": "1.1.28",
63
- "@zhin.js/handler": "1.1.12",
64
- "@zhin.js/im-contract": "1.1.11",
65
- "@zhin.js/database": "1.1.6",
66
- "@zhin.js/interaction": "1.1.2",
67
- "@zhin.js/kernel": "1.1.5",
60
+ "@zhin.js/adapter": "1.1.30",
61
+ "@zhin.js/command": "1.1.16",
62
+ "@zhin.js/component": "1.1.15",
63
+ "@zhin.js/database": "1.1.7",
64
+ "@zhin.js/handler": "1.1.14",
65
+ "@zhin.js/im-contract": "1.1.13",
66
+ "@zhin.js/kernel": "1.1.6",
68
67
  "@zhin.js/logger": "1.1.2",
69
- "@zhin.js/middleware": "1.1.13",
70
- "@zhin.js/permission": "1.1.12",
71
- "@zhin.js/plugin-runtime": "1.1.20",
72
- "@zhin.js/schedule-feature": "1.1.12",
73
- "@zhin.js/schema": "1.1.4",
74
- "@zhin.js/jsx": "1.1.10",
75
- "@zhin.js/feature-kit": "1.1.12"
68
+ "@zhin.js/middleware": "1.1.15",
69
+ "@zhin.js/permission": "1.1.14",
70
+ "@zhin.js/plugin-runtime": "1.1.22",
71
+ "@zhin.js/schedule-feature": "1.1.14",
72
+ "@zhin.js/schema": "1.1.5",
73
+ "@zhin.js/jsx": "1.1.12",
74
+ "@zhin.js/feature-kit": "1.1.14"
76
75
  },
77
76
  "devDependencies": {
78
77
  "@types/node": "^26.1.2",
79
78
  "@types/qrcode": "^1.5.6",
80
79
  "ajv": "8.18.0",
81
80
  "typescript": "^6.0.3",
82
- "@zhin.js/ai": "1.1.51"
81
+ "@zhin.js/ai": "1.1.53"
83
82
  },
84
83
  "repository": {
85
84
  "type": "git",
@@ -1,34 +0,0 @@
1
- import type { EndpointControl, EndpointManagement } from '@zhin.js/adapter';
2
- import type { ConversationRef, DeliveryReceipt, SelfProfilePort } from '@zhin.js/im-contract';
3
- import type { Locale, PluginId } from '@zhin.js/plugin-runtime';
4
- import type { SendContent } from './contracts.js';
5
- import type { CoreReplyStream, OpenReplyStreamOptions } from './progressive-reply.js';
6
- /** Capture while the source Message/event is active, before handing work to an asynchronous owner. */
7
- export interface CaptureEndpointOperationInput {
8
- /** Canonical complete source address; never an account alias. */
9
- readonly target: ConversationRef;
10
- /** Actual source Client, checked against the selected account incarnation. */
11
- readonly client: unknown;
12
- /** Lifetime of the work that is retaining the source operation. */
13
- readonly signal?: AbortSignal;
14
- /** Author supplied by trusted composition or the owner-bound Host facade. */
15
- readonly requester?: PluginId;
16
- }
17
- /** Retained execution authority for one concrete Client; consumers must release it in finally. */
18
- export interface CapturedEndpointOperation {
19
- readonly target: ConversationRef;
20
- readonly signal: AbortSignal;
21
- /** The same guarded semantic ports as ordinary calls, pinned to the retained Client. */
22
- readonly control?: EndpointControl;
23
- readonly management?: EndpointManagement;
24
- /** Current account facts and approved mutations, under the same retained operation. */
25
- readonly profile?: SelfProfilePort;
26
- /** Uses the ordinary renderer/middleware/delivery pipeline with the captured author. */
27
- send(content: SendContent, options?: Readonly<{
28
- locale?: Locale;
29
- signal?: AbortSignal;
30
- }>): Promise<DeliveryReceipt>;
31
- openReplyStream?(options?: OpenReplyStreamOptions): CoreReplyStream | undefined;
32
- /** Stops new calls and releases source/Root leases after accepted calls drain; never stops the account. */
33
- release(): void;
34
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,13 +0,0 @@
1
- import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
- import type { CommandDispatchResult, CommandIndex } from '@zhin.js/command';
3
- import type { ConversationRef } from '@zhin.js/im-contract';
4
- import type { SendContent } from './contracts.js';
5
- /** Rendering dependencies for one menu response; callbacks retain the same generation. */
6
- export interface CommandMenuReplyContext {
7
- readonly commands: CommandIndex;
8
- readonly snapshot: RuntimeSnapshot;
9
- readonly conversation: ConversationRef;
10
- readonly prefix: string;
11
- }
12
- /** IM-only presentation: Command remains independent of JSX, adapters and callback registries. */
13
- export declare function commandMenuReply(result: CommandDispatchResult, { commands, snapshot, conversation, prefix }: CommandMenuReplyContext): Promise<SendContent>;
@@ -1,43 +0,0 @@
1
- import { readOperationInputResources } from '@zhin.js/feature-kit';
2
- import { createMessages } from '@zhin.js/plugin-runtime';
3
- import { Fragment, jsx } from '@zhin.js/jsx';
4
- import { resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundSupportedSegments } from './outbound-segments.js';
5
- import { presentCommandMenu } from './command-menu-presentation.js';
6
- const menuMessages = createMessages({
7
- page: { 'zh-CN': '**指令菜单** · 第 {page}/{pages} 页', en: '**Command menu** · Page {page}/{pages}' },
8
- previous: { 'zh-CN': '上一页', en: 'Previous' },
9
- next: { 'zh-CN': '下一页', en: 'Next' },
10
- });
11
- /** IM-only presentation: Command remains independent of JSX, adapters and callback registries. */
12
- export async function commandMenuReply(result, { commands, snapshot, conversation, prefix }) {
13
- // Only validated menus carry this metadata; other command return values stay opaque.
14
- const menu = result.menu;
15
- if (!menu)
16
- return result.value;
17
- const content = await presentCommandMenu(menu, result.value, snapshot, conversation);
18
- if (menu.pages <= 1)
19
- return content;
20
- const endpoint = conversation.endpoint.id;
21
- const supported = resolveOutboundSupportedSegments(endpoint, snapshot);
22
- if (resolveOutboundMarkdownPolicy(endpoint, snapshot) !== 'native'
23
- || resolveOutboundInteractivePolicy(endpoint, snapshot) !== 'native'
24
- || supported && (!supported.includes('markdown') || !supported.includes('keyboard')))
25
- return content;
26
- const button = (page, label, disabled) => jsx('button', {
27
- label, disabled, style: disabled ? 'secondary' : 'primary',
28
- onClick: async (message) => {
29
- if (disabled)
30
- return [];
31
- const input = `${menu.keyword}${menu.pluginKey ? ` ${menu.pluginKey}` : ''} --page ${page}`;
32
- const next = await commands.dispatch({ input: input, source: message, commandPrefix: prefix, snapshot: snapshot, locale: menu.locale, operation: readOperationInputResources(message, snapshot) });
33
- return commandMenuReply(next, { commands: commands, snapshot: snapshot, conversation: message.conversation, prefix: prefix });
34
- },
35
- });
36
- return [content,
37
- { type: 'markdown', data: { content: menuMessages(menu.locale, 'page', { page: menu.page, pages: menu.pages }) } },
38
- jsx(Fragment, { children: [
39
- button(menu.page - 1, menuMessages(menu.locale, 'previous'), menu.page === 1),
40
- button(menu.page + 1, menuMessages(menu.locale, 'next'), menu.page === menu.pages),
41
- ] }),
42
- ];
43
- }
@@ -1,14 +0,0 @@
1
- import type { CommandMenuPage } from '@zhin.js/command';
2
- import type { ConversationRef } from '@zhin.js/im-contract';
3
- import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
4
- import type { SendContent } from './contracts.js';
5
- export interface CommandMenuPresentationInput {
6
- readonly page: CommandMenuPage;
7
- readonly conversation: ConversationRef;
8
- readonly generation: number;
9
- }
10
- /** Root-selected menu content. `undefined` retains the built-in presentation. */
11
- export type CommandMenuPresenter = (input: CommandMenuPresentationInput) => SendContent | undefined | Promise<SendContent | undefined>;
12
- export declare const commandMenuPresentationToken: import("@zhin.js/plugin-runtime").Token<CommandMenuPresenter>;
13
- /** The current Root owns both the selected presenter and the resulting content. */
14
- export declare function presentCommandMenu(page: CommandMenuPage, fallback: SendContent, snapshot: RuntimeSnapshot, conversation: ConversationRef): Promise<SendContent>;
@@ -1,25 +0,0 @@
1
- import { formatCompact, getLogger } from '@zhin.js/logger';
2
- import { createToken } from '@zhin.js/plugin-runtime';
3
- export const commandMenuPresentationToken = createToken('zhin.command-menu-presentation', 'Root-selected command menu presentation; framework pagination remains unchanged');
4
- const logger = getLogger('command');
5
- /** The current Root owns both the selected presenter and the resulting content. */
6
- export async function presentCommandMenu(page, fallback, snapshot, conversation) {
7
- const presenter = snapshot.resources.get(snapshot.root)?.get(commandMenuPresentationToken.id);
8
- if (!presenter)
9
- return fallback;
10
- try {
11
- const view = Object.freeze({
12
- endpoint: Object.freeze({ id: conversation.endpoint.id, adapter: conversation.endpoint.adapter }),
13
- kind: conversation.kind, id: conversation.id,
14
- ...(conversation.parent ? { parent: Object.freeze({ kind: conversation.parent.kind, id: conversation.parent.id }) } : {}),
15
- ...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
16
- });
17
- const content = await presenter(Object.freeze({ page, conversation: view, generation: snapshot.generation }));
18
- return content === undefined ? fallback : content;
19
- }
20
- catch {
21
- // A presentation failure must not expose content, re-run commands or cause a second send.
22
- logger.warn(formatCompact({ op: 'command_menu_presentation', status: 'fallback', reason: 'presenter_failed', generation: snapshot.generation }));
23
- return fallback;
24
- }
25
- }
@@ -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,17 +0,0 @@
1
- import { type Segment } from '@zhin.js/im-contract';
2
- import type { 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 JsxButtonBatch {
7
- bind(props: ButtonProps): Segment;
8
- /** Publish callbacks immediately before transport; revoke them on definitive non-delivery. */
9
- activate(payloads: ReadonlySet<string>): () => void;
10
- }
11
- /** Snapshot-owned callbacks: retired generations are unreachable and can be collected. */
12
- export declare class JsxButtonRegistry {
13
- #private;
14
- prepare(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
15
- dispatch(message: Message, payload: string, snapshot: RuntimeSnapshot): Promise<boolean>;
16
- }
17
- export declare function collectButtonPayloads(payload: unknown): Set<string>;
@@ -1,98 +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 { isKeyboardSegment } from '../../built/interactive-segments/types.js';
7
- const PREFIX = 'zhin:jsx:';
8
- const BUTTON_TTL_MS = 60 * 60 * 1000;
9
- export function isJsxButtonPayload(payload) {
10
- return payload?.startsWith(PREFIX) === true;
11
- }
12
- /** Snapshot-owned callbacks: retired generations are unreachable and can be collected. */
13
- export class JsxButtonRegistry {
14
- #bindings = new WeakMap();
15
- prepare(request, snapshot) {
16
- const pending = new Map();
17
- return {
18
- bind: (props) => {
19
- const { onClick, payload: manualPayload, children, label, id, ...options } = props;
20
- if (onClick !== undefined && typeof onClick !== 'function')
21
- throw new TypeError('Button onClick must be a function');
22
- if (onClick && manualPayload !== undefined)
23
- throw new TypeError('Button accepts onClick or payload, not both');
24
- if (!onClick && typeof manualPayload !== 'string')
25
- throw new TypeError('Button requires onClick or payload');
26
- const payload = onClick ? `${PREFIX}${randomUUID()}` : manualPayload;
27
- if (onClick && !props.disabled)
28
- pending.set(payload, {
29
- onClick, requester: request.requester, conversationKey: conversationRefKey(request.conversation),
30
- expiresAt: 0,
31
- });
32
- return { type: 'keyboard', data: { rows: [[{
33
- ...options,
34
- id: id ?? randomUUID(),
35
- label: label ?? children,
36
- payload,
37
- ...(onClick ? { mode: 'callback' } : {}),
38
- }]] } };
39
- },
40
- activate: (payloads) => {
41
- let active = this.#bindings.get(snapshot);
42
- const activated = [];
43
- if (active)
44
- this.#prune(active);
45
- for (const [payload, binding] of pending) {
46
- if (!payloads.has(payload))
47
- continue;
48
- if (!active)
49
- this.#bindings.set(snapshot, active = new Map());
50
- active.set(payload, { ...binding, expiresAt: Date.now() + BUTTON_TTL_MS });
51
- activated.push(payload);
52
- }
53
- pending.clear();
54
- return () => { for (const payload of activated)
55
- active?.delete(payload); };
56
- },
57
- };
58
- }
59
- async dispatch(message, payload, snapshot) {
60
- if (!isJsxButtonPayload(payload))
61
- return false;
62
- const active = this.#bindings.get(snapshot);
63
- if (active)
64
- this.#prune(active);
65
- const binding = active?.get(payload);
66
- // Never invoke a retired closure. The reply uses this incoming operation's scope.
67
- if (!binding) {
68
- await message.$reply(t(message.locale, 'expired'));
69
- return true;
70
- }
71
- if (binding.conversationKey !== conversationRefKey(message.conversation))
72
- return true;
73
- const bound = bindOperationInput(message, binding.requester, snapshot);
74
- const content = await binding.onClick(bound);
75
- if (typeof content === 'number')
76
- await bound.$reply(jsx('text', { text: String(content) }));
77
- else if (content != null && typeof content !== 'boolean')
78
- await bound.$reply(content);
79
- return true;
80
- }
81
- #prune(bindings) {
82
- const now = Date.now();
83
- for (const [payload, binding] of bindings)
84
- if (binding.expiresAt <= now)
85
- bindings.delete(payload);
86
- }
87
- }
88
- export function collectButtonPayloads(payload) {
89
- const result = new Set();
90
- for (const item of Array.isArray(payload) ? payload : [payload]) {
91
- if (isKeyboardSegment(item)) {
92
- for (const row of item.data.rows)
93
- for (const button of row)
94
- result.add(button.payload);
95
- }
96
- }
97
- return result;
98
- }
@@ -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');