@zhin.js/core 1.1.45 → 1.1.47

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 (46) hide show
  1. package/README.md +6 -0
  2. package/lib/ai-completion-contract.d.ts +121 -0
  3. package/lib/ai-completion-contract.js +68 -0
  4. package/lib/built/ai-outbound/prompt.d.ts +2 -0
  5. package/lib/built/ai-outbound/prompt.js +2 -0
  6. package/lib/built/html-to-text.d.ts +0 -3
  7. package/lib/built/html-to-text.js +130 -39
  8. package/lib/built/interactive-segments/resolve.d.ts +2 -2
  9. package/lib/built/interactive-segments/resolve.js +20 -12
  10. package/lib/built/readable-link.d.ts +4 -0
  11. package/lib/built/readable-link.js +32 -0
  12. package/lib/built/rich-segments/markdown-to-text.d.ts +1 -1
  13. package/lib/built/rich-segments/markdown-to-text.js +123 -11
  14. package/lib/built/segment-contract/index.d.ts +1 -1
  15. package/lib/built/segment-contract/index.js +1 -1
  16. package/lib/built/segment-contract/json-schema.d.ts +30 -1
  17. package/lib/built/segment-contract/json-schema.js +93 -20
  18. package/lib/built/segment-contract/validate.d.ts +3 -0
  19. package/lib/built/segment-contract/validate.js +2 -0
  20. package/lib/built/user-interaction.d.ts +1 -1
  21. package/lib/built/user-interaction.js +4 -5
  22. package/lib/index.d.ts +3 -0
  23. package/lib/index.js +2 -0
  24. package/lib/jsx/message-tags.d.ts +1 -0
  25. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +6 -0
  26. package/lib/plugin-runtime/im/command-menu-navigation.js +33 -0
  27. package/lib/plugin-runtime/im/contracts.d.ts +12 -2
  28. package/lib/plugin-runtime/im/contracts.js +24 -2
  29. package/lib/plugin-runtime/im/im-runtime.d.ts +2 -0
  30. package/lib/plugin-runtime/im/im-runtime.js +24 -4
  31. package/lib/plugin-runtime/im/inbound-runtime.d.ts +5 -0
  32. package/lib/plugin-runtime/im/inbound-runtime.js +193 -135
  33. package/lib/plugin-runtime/im/index.d.ts +1 -0
  34. package/lib/plugin-runtime/im/interaction-operation.d.ts +8 -0
  35. package/lib/plugin-runtime/im/interaction-operation.js +2 -0
  36. package/lib/plugin-runtime/im/interaction-runtime.d.ts +5 -3
  37. package/lib/plugin-runtime/im/interaction-runtime.js +150 -51
  38. package/lib/plugin-runtime/im/message-diagnostics.d.ts +70 -0
  39. package/lib/plugin-runtime/im/message-diagnostics.js +182 -0
  40. package/lib/plugin-runtime/im/message-dispatcher.d.ts +1 -1
  41. package/lib/plugin-runtime/im/message-dispatcher.js +41 -5
  42. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +2 -0
  43. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +7 -0
  44. package/lib/plugin-runtime/im/outbound-segments.d.ts +8 -0
  45. package/lib/plugin-runtime/im/outbound-segments.js +25 -4
  46. package/package.json +13 -13
package/README.md CHANGED
@@ -131,6 +131,12 @@ return segment.html({
131
131
 
132
132
  ## 验证
133
133
 
134
+ 命令可通过 `execution` 显式开启冷却、并发预算与一次进度反馈,详见
135
+ [`@zhin.js/command`](../command/README.md#可选执行预算)。Core 在真实入站 operation 上绑定身份,
136
+ Root Resource 保存跨 generation 的预算;外层 finally 在所有已启动发送排空后释放。
137
+ retirement signal 只停止尚未启动的提示,不释放仍在执行的占用,也不取消普通旧 lease 的发送。
138
+ 诊断 `dispatchStatus: 'limited'` 与 `limit` 表示准入拒绝,不是权限授权或平台投递失败。
139
+
134
140
  ```bash
135
141
  pnpm --filter @zhin.js/core build
136
142
  pnpm exec vitest run packages/im/core/tests packages/im/adapter/tests
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Plugin-facing contract for tool-free text completion (#804, #877).
3
+ *
4
+ * Lives in core so plugins can import it from the `zhin.js` main entry without installing the
5
+ * optional `@zhin.js/agent`. The agent provides {@link aiCompletionToken} only when an AI host is
6
+ * configured; check with {@link hasResource} (or `context.has?.(token)`) before `use()`.
7
+ */
8
+ import { type Token } from '@zhin.js/plugin-runtime';
9
+ /** Who a completion is billed to (`onBehalfOf`). `groupId` is `${platform}:${endpoint}:${sceneId}` in group / channel chats. */
10
+ export interface UsageSubject {
11
+ readonly userId: string;
12
+ /** Stable group key (platform + endpoint + group id); undefined in private chats. */
13
+ readonly groupId?: string;
14
+ readonly owner: boolean;
15
+ }
16
+ export interface AiCompletionUntrustedInput {
17
+ /** Where the text came from, e.g. `group-chat`; shown to the model as the block's source. */
18
+ readonly source: string;
19
+ readonly text: string;
20
+ }
21
+ export interface AiCompletionInput {
22
+ /** Required label for logs and usage attribution, e.g. `summarize-chat`. */
23
+ readonly purpose: string;
24
+ /** Trusted instructions written by the plugin. */
25
+ readonly system?: string;
26
+ /** Trusted input written by the plugin. */
27
+ readonly prompt: string;
28
+ /** Untrusted content (group chat, web pages, files); always rendered as data, never as instructions. */
29
+ readonly untrusted?: readonly AiCompletionUntrustedInput[];
30
+ /** Agent binding whose provider / model is used; defaults to `zhin`. */
31
+ readonly agent?: string;
32
+ /** Model id on the binding's provider; defaults to the binding's model. */
33
+ readonly model?: string;
34
+ readonly maxTokens?: number;
35
+ readonly temperature?: number;
36
+ /** Per-request timeout in ms; defaults to the provider resilience setting. */
37
+ readonly timeoutMs?: number;
38
+ readonly signal?: AbortSignal;
39
+ /** The IM user (and group) this call is made for; counts against their usage quota. */
40
+ readonly onBehalfOf?: UsageSubject;
41
+ }
42
+ /** Token cost breakdown; structurally identical to `@zhin.js/ai` `TokenCost`. */
43
+ export interface AiCompletionTokenCost {
44
+ input: number;
45
+ output: number;
46
+ cacheRead: number;
47
+ cacheWrite: number;
48
+ total: number;
49
+ }
50
+ /** Token usage; structurally identical to `@zhin.js/ai` `TokenUsage` (asserted by agent type tests). */
51
+ export interface AiCompletionTokenUsage {
52
+ input: number;
53
+ output: number;
54
+ cacheRead: number;
55
+ cacheWrite: number;
56
+ totalTokens: number;
57
+ reasoning?: number;
58
+ cost: AiCompletionTokenCost;
59
+ }
60
+ export interface AiCompletionResult {
61
+ readonly text: string;
62
+ /** Model that actually answered (may be a fallback). */
63
+ readonly model: string;
64
+ readonly durationMs: number;
65
+ readonly usage?: AiCompletionTokenUsage;
66
+ }
67
+ export interface AiCompletion {
68
+ completeText(input: AiCompletionInput): Promise<AiCompletionResult>;
69
+ }
70
+ /**
71
+ * Generation-owned plain text completion for plugins, provided by `@zhin.js/agent` when an AI host
72
+ * is configured; absent otherwise. Importing it never loads the agent.
73
+ */
74
+ export declare const aiCompletionToken: Token<AiCompletion>;
75
+ /** Shape of the agent's `AiCompletionQuotaError`, recognisable without importing `@zhin.js/agent`. */
76
+ export interface AiCompletionQuotaErrorLike extends Error {
77
+ readonly name: 'AiCompletionQuotaError';
78
+ readonly scope: 'user' | 'group';
79
+ readonly retryAfterSeconds: number;
80
+ }
81
+ /** True for the agent's quota error (`message` is user-facing); works without importing `@zhin.js/agent`. */
82
+ export declare function isAiCompletionQuotaError(error: unknown): error is AiCompletionQuotaErrorLike;
83
+ /** Usage quota group key shared by Agent turns and plugin completions. */
84
+ export declare function usageGroupId(platform: string, endpoint: string, sceneId: string): string;
85
+ /** Minimal structural input: core `Message`, `CommandMessage` and `@zhin.js/testing` fakes all fit. */
86
+ export interface UsageSubjectSource {
87
+ readonly conversation: Readonly<{
88
+ endpoint: Readonly<{
89
+ adapter: string;
90
+ id: string;
91
+ }>;
92
+ kind: string;
93
+ id: string;
94
+ }>;
95
+ readonly sender?: Readonly<{
96
+ id?: string;
97
+ roles?: readonly string[];
98
+ }>;
99
+ readonly clientAdapter?: string;
100
+ readonly endpointId?: string;
101
+ }
102
+ /**
103
+ * The {@link UsageSubject} for a call made on behalf of a message's sender, with the same rules as
104
+ * Agent turns (so both count against one quota bucket): platform = `clientAdapter` or the endpoint
105
+ * adapter, endpoint = `endpointId` or the endpoint id, `groupId` only in group / channel chats,
106
+ * `owner` when the sender has the `master` role.
107
+ *
108
+ * Returns `undefined` when the message has no sender (e.g. system events); omit `onBehalfOf` then.
109
+ * Throws `TypeError` for a malformed conversation (missing platform / endpoint / id, unknown kind).
110
+ */
111
+ export declare function usageSubjectFromMessage(message: UsageSubjectSource): UsageSubject | undefined;
112
+ /** Any context that resolves resources: setup `resources` (Scope), capability / construction contexts. */
113
+ export interface ResourceReader {
114
+ use<T>(token: Token<T>): T;
115
+ has?(token: Token<unknown>): boolean;
116
+ }
117
+ /**
118
+ * True when `context.use(token)` would succeed. Uses `context.has` when the context provides it and
119
+ * otherwise probes `use()`, so it also works with older or hand-written contexts.
120
+ */
121
+ export declare function hasResource(context: ResourceReader, token: Token<unknown>): boolean;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Plugin-facing contract for tool-free text completion (#804, #877).
3
+ *
4
+ * Lives in core so plugins can import it from the `zhin.js` main entry without installing the
5
+ * optional `@zhin.js/agent`. The agent provides {@link aiCompletionToken} only when an AI host is
6
+ * configured; check with {@link hasResource} (or `context.has?.(token)`) before `use()`.
7
+ */
8
+ import { createToken } from '@zhin.js/plugin-runtime';
9
+ /**
10
+ * Generation-owned plain text completion for plugins, provided by `@zhin.js/agent` when an AI host
11
+ * is configured; absent otherwise. Importing it never loads the agent.
12
+ */
13
+ export const aiCompletionToken = createToken('zhin.agent.ai-completion', 'Tool-free text completion with retry and fallback, for plugins');
14
+ /** True for the agent's quota error (`message` is user-facing); works without importing `@zhin.js/agent`. */
15
+ export function isAiCompletionQuotaError(error) {
16
+ return error instanceof Error && error.name === 'AiCompletionQuotaError'
17
+ && (error.scope === 'user' || error.scope === 'group')
18
+ && typeof error.retryAfterSeconds === 'number';
19
+ }
20
+ /** Usage quota group key shared by Agent turns and plugin completions. */
21
+ export function usageGroupId(platform, endpoint, sceneId) {
22
+ return `${platform}:${endpoint}:${sceneId}`;
23
+ }
24
+ /**
25
+ * The {@link UsageSubject} for a call made on behalf of a message's sender, with the same rules as
26
+ * Agent turns (so both count against one quota bucket): platform = `clientAdapter` or the endpoint
27
+ * adapter, endpoint = `endpointId` or the endpoint id, `groupId` only in group / channel chats,
28
+ * `owner` when the sender has the `master` role.
29
+ *
30
+ * Returns `undefined` when the message has no sender (e.g. system events); omit `onBehalfOf` then.
31
+ * Throws `TypeError` for a malformed conversation (missing platform / endpoint / id, unknown kind).
32
+ */
33
+ export function usageSubjectFromMessage(message) {
34
+ const userId = String(message.sender?.id ?? '').trim();
35
+ if (!userId)
36
+ return undefined;
37
+ const { conversation } = message;
38
+ const kind = conversation.kind;
39
+ if (kind !== 'private' && kind !== 'group' && kind !== 'channel') {
40
+ throw new TypeError(`usageSubjectFromMessage: unsupported conversation kind ${String(kind)}`);
41
+ }
42
+ const platform = String(message.clientAdapter ?? conversation.endpoint.adapter ?? '').trim();
43
+ const endpoint = String(message.endpointId ?? conversation.endpoint.id ?? '').trim();
44
+ const sceneId = String(conversation.id ?? '').trim();
45
+ if (!platform || !endpoint || !sceneId) {
46
+ throw new TypeError('usageSubjectFromMessage: conversation platform, endpoint and id are required');
47
+ }
48
+ return Object.freeze({
49
+ userId,
50
+ ...(kind === 'private' ? {} : { groupId: usageGroupId(platform, endpoint, sceneId) }),
51
+ owner: message.sender?.roles?.includes('master') ?? false,
52
+ });
53
+ }
54
+ /**
55
+ * True when `context.use(token)` would succeed. Uses `context.has` when the context provides it and
56
+ * otherwise probes `use()`, so it also works with older or hand-written contexts.
57
+ */
58
+ export function hasResource(context, token) {
59
+ if (typeof context.has === 'function')
60
+ return context.has(token);
61
+ try {
62
+ context.use(token);
63
+ return true;
64
+ }
65
+ catch {
66
+ return false;
67
+ }
68
+ }
@@ -1,6 +1,8 @@
1
1
  import type { AiOutboundCapabilities, AiOutboundExtensionDefinition } from './types.js';
2
2
  export declare const AI_OUTBOUND_JSON_EXAMPLE = "{\"mentions\":[\"researcher\",\"210723495\"],\"text\":\"\u6B63\u6587\"}";
3
+ /** @deprecated Legacy `{mentions,text}` format; Agent replies use the canonical `{segments}` contract (`buildAiOutboundJsonSchema`). */
3
4
  export declare function buildCoreAiOutboundPromptHint(capabilities?: AiOutboundCapabilities): string;
5
+ /** @deprecated Legacy `{mentions,text}` format; Agent replies use the canonical `{segments}` contract (`buildAiOutboundJsonSchema`). */
4
6
  export declare function buildAiOutboundPromptHint(input: {
5
7
  capabilities?: AiOutboundCapabilities;
6
8
  extensions?: readonly AiOutboundExtensionDefinition[];
@@ -1,4 +1,5 @@
1
1
  export const AI_OUTBOUND_JSON_EXAMPLE = '{"mentions":["researcher","210723495"],"text":"正文"}';
2
+ /** @deprecated Legacy `{mentions,text}` format; Agent replies use the canonical `{segments}` contract (`buildAiOutboundJsonSchema`). */
2
3
  export function buildCoreAiOutboundPromptHint(capabilities) {
3
4
  const lines = [
4
5
  'When your reply must @ peers, send rich media, buttons, or delegate — output JSON only (no Markdown wrapper):',
@@ -14,6 +15,7 @@ export function buildCoreAiOutboundPromptHint(capabilities) {
14
15
  }
15
16
  return lines.join('\n');
16
17
  }
18
+ /** @deprecated Legacy `{mentions,text}` format; Agent replies use the canonical `{segments}` contract (`buildAiOutboundJsonSchema`). */
17
19
  export function buildAiOutboundPromptHint(input) {
18
20
  const lines = [];
19
21
  if (input.rosterLines?.length) {
@@ -1,6 +1,3 @@
1
- /**
2
- * 将 HTML 转为纯文本(无回溯密集正则,供 CodeQL / SSRF 工具链使用)。
3
- */
4
1
  export type HtmlToPlainTextOptions = {
5
2
  maxInputLength?: number;
6
3
  };
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * 将 HTML 转为纯文本(无回溯密集正则,供 CodeQL / SSRF 工具链使用)。
3
3
  */
4
+ import { readableLinkTarget, decodeReadableEntities as decodeCommonEntities } from './readable-link.js';
4
5
  const DEFAULT_MAX_INPUT = 2 * 1024 * 1024;
5
6
  const BLOCK_TAGS = ['script', 'style', 'svg', 'nav', 'footer', 'header', 'form'];
6
7
  function findTagClose(html, from) {
@@ -78,25 +79,6 @@ function stripRemainingTags(html) {
78
79
  }
79
80
  return out;
80
81
  }
81
- function decodeCommonEntities(text) {
82
- return text.replace(/&(#x[0-9a-fA-F]+|#\d+|nbsp|amp|lt|gt|quot|apos);/gi, (entity) => {
83
- const key = entity.slice(1, -1).toLowerCase();
84
- if (key === 'nbsp')
85
- return ' ';
86
- if (key === 'amp')
87
- return '&';
88
- if (key === 'lt')
89
- return '<';
90
- if (key === 'gt')
91
- return '>';
92
- if (key === 'quot')
93
- return '"';
94
- if (key === 'apos')
95
- return "'";
96
- const n = key.startsWith('#x') ? parseInt(key.slice(2), 16) : Number(key.slice(1));
97
- return Number.isFinite(n) && n >= 0 && n <= 0x10ffff ? String.fromCodePoint(n) : '';
98
- });
99
- }
100
82
  /**
101
83
  * HTML → 纯文本:先剥离 script/style 等块,再去标签与实体。
102
84
  */
@@ -139,28 +121,137 @@ export function htmlToPlainTextWithBlockBreaks(html, options) {
139
121
  export function htmlToFallbackText(html, options) {
140
122
  const maxLen = options?.maxInputLength ?? DEFAULT_MAX_INPUT;
141
123
  let work = html.length > maxLen ? html.slice(0, maxLen) : html;
142
- work = work
143
- .replace(/<br\s*\/?>/gi, '\n')
144
- .replace(/<h1[^>]*>/gi, '\n# ')
145
- .replace(/<h2[^>]*>/gi, '\n## ')
146
- .replace(/<h3[^>]*>/gi, '\n### ')
147
- .replace(/<h4[^>]*>/gi, '\n#### ')
148
- .replace(/<h5[^>]*>/gi, '\n##### ')
149
- .replace(/<h6[^>]*>/gi, '\n###### ')
150
- .replace(/<li[^>]*>/gi, '\n- ')
151
- .replace(/<\/p>/gi, '\n\n')
152
- .replace(/<\/div>/gi, '\n')
153
- .replace(/<\/li>/gi, '\n')
154
- .replace(/<\/tr>/gi, '\n')
155
- .replace(/<\/h[1-6]>/gi, '\n\n');
156
124
  for (const tag of BLOCK_TAGS) {
157
125
  work = removeBalancedBlocks(work, tag);
158
126
  }
159
127
  work = removeHtmlComments(work);
160
- work = stripRemainingTags(work);
161
- work = decodeCommonEntities(work);
162
- return work
163
- .replace(/[ \t]+/g, ' ')
164
- .replace(/\n{3,}/g, '\n\n')
165
- .trim();
128
+ const out = [];
129
+ const lists = [];
130
+ let anchor;
131
+ let cells = 0;
132
+ let pre = false;
133
+ for (let i = 0; i < work.length;) {
134
+ if (work[i] !== '<') {
135
+ const next = work.indexOf('<', i);
136
+ const text = decodeCommonEntities(work.slice(i, next === -1 ? work.length : next));
137
+ out.push(pre ? text : text.replace(/\s+/gu, ' '));
138
+ i = next === -1 ? work.length : next;
139
+ continue;
140
+ }
141
+ // Respect quoted attributes, so href/title values may contain '>'.
142
+ let end = i + 1;
143
+ let quote = '';
144
+ for (; end < work.length; end++) {
145
+ const character = work[end];
146
+ if (quote) {
147
+ if (character === quote)
148
+ quote = '';
149
+ }
150
+ else if (character === '"' || character === "'")
151
+ quote = character;
152
+ else if (character === '>')
153
+ break;
154
+ }
155
+ if (end === work.length)
156
+ break;
157
+ const token = work.slice(i + 1, end);
158
+ const match = /^\s*(\/?)\s*([a-z][\w:-]*)/iu.exec(token);
159
+ i = end + 1;
160
+ if (!match)
161
+ continue;
162
+ const closing = match[1] === '/';
163
+ const tag = match[2].toLowerCase();
164
+ if (tag === 'a') {
165
+ if (closing) {
166
+ if (anchor) {
167
+ const label = out.slice(anchor.start).join('').trim();
168
+ if (label !== anchor.target)
169
+ out.push(label ? ` (${anchor.target})` : anchor.target);
170
+ }
171
+ anchor = undefined;
172
+ }
173
+ else {
174
+ const target = readableLinkTarget(decodeCommonEntities(readHtmlAttribute(token, 'href') ?? ''));
175
+ anchor = target ? { target, start: out.length } : undefined;
176
+ }
177
+ }
178
+ else if (tag === 'img' && !closing) {
179
+ const alt = decodeCommonEntities(readHtmlAttribute(token, 'alt') ?? '').trim();
180
+ out.push(alt ? `[图片:${alt}]` : '[图片]');
181
+ }
182
+ else if (tag === 'ul' || tag === 'ol') {
183
+ if (closing) {
184
+ lists.pop();
185
+ out.push('\n');
186
+ }
187
+ else {
188
+ const start = Number(readHtmlAttribute(token, 'start'));
189
+ lists.push({ ordered: tag === 'ol', next: Number.isSafeInteger(start) && start > 0 ? start : 1 });
190
+ }
191
+ }
192
+ else if (tag === 'li') {
193
+ if (closing)
194
+ out.push('\n');
195
+ else {
196
+ const list = lists.at(-1);
197
+ out.push(`\n${' '.repeat(Math.min(32, Math.max(0, lists.length - 1)))}${list?.ordered ? `${list.next++}.` : '-'} `);
198
+ }
199
+ }
200
+ else if (tag === 'tr') {
201
+ cells = 0;
202
+ out.push('\n');
203
+ }
204
+ else if ((tag === 'td' || tag === 'th') && !closing) {
205
+ if (cells++)
206
+ out.push(' | ');
207
+ }
208
+ else if (tag === 'pre') {
209
+ pre = !closing;
210
+ out.push('\n');
211
+ }
212
+ else if (tag === 'br' || tag === 'hr')
213
+ out.push('\n');
214
+ else if (/^h[1-6]$/u.test(tag))
215
+ out.push(closing ? '\n\n' : `\n${'#'.repeat(Number(tag[1]))} `);
216
+ else if (['p', 'div', 'section', 'article', 'table', 'blockquote'].includes(tag)) {
217
+ if (closing)
218
+ out.push(tag === 'p' ? '\n\n' : '\n');
219
+ }
220
+ }
221
+ return out.join('').replace(/[ \t]+\n/gu, '\n').replace(/\n{3,}/gu, '\n\n').trim()
222
+ + (html.length > maxLen ? '\n\n[内容过长,已省略后续内容;请缩小查询范围或分页查看。]' : '');
223
+ }
224
+ /** Linear attribute scan, independent of attribute length and quote characters. */
225
+ function readHtmlAttribute(token, requested) {
226
+ let i = token.search(/\s/u);
227
+ if (i < 0)
228
+ return undefined;
229
+ while (i < token.length) {
230
+ while (i < token.length && /[\s/]/u.test(token[i]))
231
+ i++;
232
+ const start = i;
233
+ while (i < token.length && !/[\s=/>]/u.test(token[i]))
234
+ i++;
235
+ const name = token.slice(start, i).toLowerCase();
236
+ while (i < token.length && /\s/u.test(token[i]))
237
+ i++;
238
+ if (token[i] !== '=') {
239
+ if (i === start)
240
+ i++;
241
+ continue;
242
+ }
243
+ i++;
244
+ while (i < token.length && /\s/u.test(token[i]))
245
+ i++;
246
+ const quote = token[i] === '"' || token[i] === "'" ? token[i++] : undefined;
247
+ const valueStart = i;
248
+ while (i < token.length && (quote ? token[i] !== quote : !/[\s>]/u.test(token[i])))
249
+ i++;
250
+ const value = token.slice(valueStart, i);
251
+ if (quote)
252
+ i++;
253
+ if (name === requested)
254
+ return value;
255
+ }
256
+ return undefined;
166
257
  }
@@ -2,13 +2,13 @@ import type { SendContent } from '../../types.js';
2
2
  import { type InteractivePolicy, type KeyboardSegmentData } from './types.js';
3
3
  /**
4
4
  * keyboard 的有效 fallback 映射:显式 `fallback.map` 优先;否则按按钮顺序
5
- * 自动编号(与 {@link renderKeyboardAsText} 的自动编号一致,含 disabled 按钮)。
5
+ * 自动编号(与 {@link renderKeyboardAsText} 一致);disabled 不产生可执行映射。
6
6
  */
7
7
  export declare function effectiveKeyboardFallbackMap(data: KeyboardSegmentData): Record<string, string>;
8
8
  /** 收集 content 中所有 keyboard 段的有效 fallback 映射(文本降级前调用)。 */
9
9
  export declare function collectKeyboardFallbackMaps(content: SendContent | undefined): Record<string, string>[];
10
10
  /** keyboard 段 → 编号文本('text' 策略端点的中央降级渲染)。 */
11
- export declare function renderKeyboardAsText(data: KeyboardSegmentData): string;
11
+ export declare function renderKeyboardAsText(data: KeyboardSegmentData, allocatedMap?: Readonly<Record<string, string>>): string;
12
12
  export declare function hasKeyboardSegment(content: SendContent | undefined): boolean;
13
13
  /** 按 Adapter interactivePolicy 将 keyboard 段转为 native 保留或文本降级 */
14
14
  export declare function resolveKeyboardSegments(content: SendContent, policy: InteractivePolicy): SendContent;
@@ -23,15 +23,20 @@ function packSegments(out) {
23
23
  }
24
24
  /**
25
25
  * keyboard 的有效 fallback 映射:显式 `fallback.map` 优先;否则按按钮顺序
26
- * 自动编号(与 {@link renderKeyboardAsText} 的自动编号一致,含 disabled 按钮)。
26
+ * 自动编号(与 {@link renderKeyboardAsText} 一致);disabled 不产生可执行映射。
27
27
  */
28
28
  export function effectiveKeyboardFallbackMap(data) {
29
+ const buttons = data.rows.flat();
30
+ const enabled = new Set(buttons.filter(button => !button.disabled).map(button => button.payload));
31
+ // Disabling one presentation does not disable another explicitly enabled button for the same action.
32
+ const disabledOnly = new Set(buttons.filter(button => button.disabled && !enabled.has(button.payload)).map(button => button.payload));
29
33
  const map = data.fallback?.map ?? {};
30
34
  if (Object.keys(map).length > 0)
31
- return { ...map };
35
+ return Object.fromEntries(Object.entries(map).filter(([, payload]) => !disabledOnly.has(payload)));
32
36
  const out = {};
33
- data.rows.flat().forEach((btn, idx) => {
34
- out[String(idx + 1)] = btn.payload;
37
+ buttons.forEach((btn, idx) => {
38
+ if (!btn.disabled)
39
+ out[String(idx + 1)] = btn.payload;
35
40
  });
36
41
  return out;
37
42
  }
@@ -50,24 +55,27 @@ export function collectKeyboardFallbackMaps(content) {
50
55
  return maps;
51
56
  }
52
57
  /** keyboard 段 → 编号文本('text' 策略端点的中央降级渲染)。 */
53
- export function renderKeyboardAsText(data) {
58
+ export function renderKeyboardAsText(data, allocatedMap) {
54
59
  const lines = [];
55
60
  const flat = data.rows.flat();
56
- if (data.fallback?.hint) {
61
+ const entries = Object.entries(allocatedMap ?? effectiveKeyboardFallbackMap(data)).sort(([a], [b]) => Number(a) - Number(b));
62
+ if (!entries.length) {
63
+ lines.push('当前无可用操作。');
64
+ }
65
+ else if (data.fallback?.hint) {
57
66
  lines.push(data.fallback.hint);
58
67
  }
59
68
  else {
60
69
  lines.push('请选择(回复数字):');
61
70
  }
62
- const map = data.fallback?.map ?? {};
63
- const entries = Object.keys(map).length > 0
64
- ? Object.entries(map).sort(([a], [b]) => Number(a) - Number(b))
65
- : flat.map((btn, idx) => [String(idx + 1), btn.payload]);
66
71
  for (const [key, payload] of entries) {
67
- const btn = flat.find((b) => b.payload === payload);
72
+ const btn = flat.find((b) => !b.disabled && b.payload === payload);
68
73
  const label = btn?.label ?? '·';
69
- lines.push(`${key}. ${label}${btn?.disabled ? ' (不可用)' : ''}`);
74
+ lines.push(`${key}. ${label}`);
70
75
  }
76
+ for (const button of flat)
77
+ if (button.disabled)
78
+ lines.push(`— ${button.label} (不可用)`);
71
79
  return lines.join('\n');
72
80
  }
73
81
  export function hasKeyboardSegment(content) {
@@ -0,0 +1,4 @@
1
+ /** Only portable, explicit user-facing links survive rich-message text fallback. */
2
+ export declare function readableLinkTarget(value: string): string | undefined;
3
+ /** Decode entities once; encoded markup remains literal text, never parsed again. */
4
+ export declare function decodeReadableEntities(text: string): string;
@@ -0,0 +1,32 @@
1
+ /** Only portable, explicit user-facing links survive rich-message text fallback. */
2
+ export function readableLinkTarget(value) {
3
+ const target = value.trim();
4
+ for (const character of target) {
5
+ const code = character.codePointAt(0);
6
+ if (code <= 32 || code === 127)
7
+ return undefined;
8
+ }
9
+ try {
10
+ const url = new URL(target);
11
+ if (!['http:', 'https:', 'mailto:', 'tel:'].includes(url.protocol))
12
+ return undefined;
13
+ // Embedded credentials should never be copied into a chat transcript.
14
+ if (url.username || url.password)
15
+ return undefined;
16
+ return target;
17
+ }
18
+ catch {
19
+ return undefined;
20
+ }
21
+ }
22
+ /** Decode entities once; encoded markup remains literal text, never parsed again. */
23
+ export function decodeReadableEntities(text) {
24
+ return text.replace(/&(#x[0-9a-fA-F]+|#\d+|nbsp|amp|lt|gt|quot|apos);/gi, (entity) => {
25
+ const key = entity.slice(1, -1).toLowerCase();
26
+ const named = { nbsp: ' ', amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
27
+ if (named[key] !== undefined)
28
+ return named[key];
29
+ const value = key.startsWith('#x') ? parseInt(key.slice(2), 16) : Number(key.slice(1));
30
+ return Number.isFinite(value) && value >= 0 && value <= 0x10ffff ? String.fromCodePoint(value) : '';
31
+ });
32
+ }
@@ -1,3 +1,3 @@
1
- /** 将 Markdown 转为可读纯文本(出站 text 降级用) */
1
+ /** 将 Markdown 转为可读纯文本(出站 text 降级用)。代码内容不参与格式剥离。 */
2
2
  export declare function markdownToPlainText(md: string): string;
3
3
  export declare function markdownToHtmlForRender(md: string): string;