@tano.page/protocol 0.14.0 → 0.15.0

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.
package/src/extensions.ts CHANGED
@@ -1,9 +1,14 @@
1
+ import { parseFileIconTheme, type FileIconTheme, type FileIconThemeRef } from './appearance';
1
2
  import { parseObjectPlugin, type ObjectPluginManifest } from './plugins';
2
3
 
3
4
  export const workspacePluginPath = '.tano/plugins.tano.json';
4
5
  export const pluginPackageLimit = 4 * 1024 * 1024;
5
6
  export const pluginStorageLimit = 256 * 1024;
6
7
  export const pluginCacheLimit = 64 * 1024 * 1024;
8
+ /** Target limit for modern portable policies without inline raster PNGs. */
9
+ export const workspacePluginPolicyLimit = 1 * 1024 * 1024;
10
+ /** Backward-compatible read limit for legacy policies containing pre-migration inline PNG icons. */
11
+ export const legacyWorkspacePluginPolicyLimit = 16 * 1024 * 1024;
7
12
  export interface PluginPackageUsage {
8
13
  used: number;
9
14
  limit: number;
@@ -11,13 +16,185 @@ export interface PluginPackageUsage {
11
16
  entries: { integrity: string; pluginId: string; version: string; bytes: number;
12
17
  state: 'pending' | 'ready' | 'deleting'; pinned: boolean; createdAt: string; removable?: boolean }[];
13
18
  }
14
- export const pluginPermissions = ['attachments.read', 'documents.read', 'documents.write', 'objects.read', 'objects.write',
15
- 'relations.read', 'relations.write', 'storage', 'network', 'connections', 'native', 'ui'] as const;
19
+ export const pluginPermissions = ['attachments.read', 'attachments.write', 'documents.read', 'documents.write', 'documents.move', 'documents.trash', 'objects.read', 'objects.write',
20
+ 'relations.read', 'relations.write', 'storage', 'network', 'connections', 'native', 'ui', 'ai.invoke'] as const;
16
21
  export type PluginPermission = typeof pluginPermissions[number];
22
+ export type WorkspacePersonalPluginPolicy = 'allow' | 'read-only' | 'block';
23
+ export interface PluginAttachmentWriteRequest {
24
+ name: string;
25
+ contentBase64: string;
26
+ documentPath?: string;
27
+ mimeType?: string;
28
+ }
29
+ export const pluginAttachmentWriteLimit = 400 * 1024;
30
+ export const pluginAttachmentWriteExtensions = [
31
+ '.png', '.jpg', '.jpeg', '.webp', '.gif', '.svg',
32
+ '.pdf', '.txt', '.csv', '.json', '.bib', '.mermaid',
33
+ '.docx', '.xlsx', '.pptx', '.mp3', '.wav', '.mp4', '.zip',
34
+ ] as const;
17
35
  export type PluginMode = 'required' | 'recommended' | 'optional' | 'disabled';
18
36
  export type PluginMenuLocation = 'workspace' | 'document' | 'file';
19
37
  export interface PluginCommandDefinition { id: string; label: string; shortcut?: string; menus?: PluginMenuLocation[] }
20
- export interface PluginViewDefinition { id: string; label: string; location?: 'panel' | 'tab' | 'sidebar' | 'settings' }
38
+ export interface PluginSlashCommandDefinition {
39
+ id: string;
40
+ label: string;
41
+ command: string;
42
+ description?: string;
43
+ keywords?: string[];
44
+ }
45
+ export interface PluginActiveEditorSnapshot {
46
+ fileId: string;
47
+ path: string;
48
+ mode: 'rich' | 'source';
49
+ readOnly: boolean;
50
+ selection: { from: number; to: number; empty: boolean };
51
+ selectedText: string;
52
+ blockType?: string;
53
+ hash: string;
54
+ }
55
+ export interface PluginFrontmatterPatch {
56
+ set?: Record<string, PluginJson>;
57
+ remove?: string[];
58
+ }
59
+ export interface PluginCodeBlockRendererDefinition {
60
+ languages: string[];
61
+ view: string;
62
+ label?: string;
63
+ height?: number;
64
+ }
65
+ export type PluginEditorDecorationTone = 'info' | 'accent' | 'warning' | 'danger' | 'muted';
66
+ export interface PluginEditorDecoration {
67
+ id?: string;
68
+ from: number;
69
+ to: number;
70
+ tone?: PluginEditorDecorationTone;
71
+ badge?: string;
72
+ tooltip?: string;
73
+ command?: string;
74
+ }
75
+ export type PluginViewLayout = 'contained' | 'fill';
76
+ export const pluginViewLocations = [
77
+ 'panel',
78
+ 'tab',
79
+ 'sidebar',
80
+ 'settings',
81
+ 'documentSidebar',
82
+ 'documentHeader',
83
+ 'documentFooter',
84
+ 'homeTab',
85
+ 'newTab',
86
+ ] as const;
87
+ export type PluginViewLocation = typeof pluginViewLocations[number];
88
+ export interface PluginViewDefinition { id: string; label: string; location?: PluginViewLocation; layout?: PluginViewLayout }
89
+ export type PluginStatusBarAlign = 'left' | 'right';
90
+ export type PluginStatusBarTone = 'default' | 'accent' | 'warning' | 'danger';
91
+ export interface PluginStatusBarItem {
92
+ id: string;
93
+ text: string;
94
+ tooltip?: string;
95
+ align?: PluginStatusBarAlign;
96
+ priority?: number;
97
+ tone?: PluginStatusBarTone;
98
+ command?: string;
99
+ }
100
+ export type PluginUiTone = 'info' | 'success' | 'warning' | 'error';
101
+ export interface PluginUiPickItem {
102
+ id: string;
103
+ label: string;
104
+ description?: string;
105
+ detail?: string;
106
+ }
107
+ export interface PluginUiPickOptions {
108
+ title: string;
109
+ placeholder?: string;
110
+ items: PluginUiPickItem[];
111
+ }
112
+ export interface PluginUiPromptOptions {
113
+ title: string;
114
+ message?: string;
115
+ placeholder?: string;
116
+ defaultValue?: string;
117
+ confirmLabel?: string;
118
+ }
119
+ export interface PluginUiConfirmOptions {
120
+ title: string;
121
+ message?: string;
122
+ confirmLabel?: string;
123
+ cancelLabel?: string;
124
+ danger?: boolean;
125
+ }
126
+ export interface PluginUiToastOptions {
127
+ message: string;
128
+ tone?: PluginUiTone;
129
+ }
130
+ export type PluginFileHandlerMode = 'preview' | 'editor';
131
+ export interface PluginFileHandlerDefinition { extensions: string[]; mode: PluginFileHandlerMode; view: string; command: string }
132
+ export type PluginSettingFieldType = 'string' | 'number' | 'boolean' | 'select';
133
+ export interface PluginSettingField {
134
+ key: string;
135
+ label: string;
136
+ description?: string;
137
+ type: PluginSettingFieldType;
138
+ default?: string | number | boolean;
139
+ options?: { value: string; label: string }[];
140
+ min?: number;
141
+ max?: number;
142
+ required?: boolean;
143
+ }
144
+ export type PluginAssistantToolEffect = 'read' | 'write' | 'external';
145
+ export interface PluginAssistantToolDefinition {
146
+ name: string;
147
+ label: string;
148
+ description: string;
149
+ effect: PluginAssistantToolEffect;
150
+ parameters: Record<string, unknown>;
151
+ }
152
+ export const pluginAssistantContextMaxBytes = 16_000;
153
+ export interface PluginAssistantContextProviderDefinition {
154
+ id: string;
155
+ label: string;
156
+ description: string;
157
+ maxBytes?: number;
158
+ }
159
+ export interface PluginAiCompleteRequest {
160
+ prompt: string;
161
+ system?: string;
162
+ maxTokens?: number;
163
+ temperature?: number;
164
+ }
165
+ export interface PluginAiStructuredRequest extends PluginAiCompleteRequest {
166
+ schema: Record<string, unknown>;
167
+ }
168
+ export interface PluginAiCompleteResult {
169
+ text: string;
170
+ model: string;
171
+ usage?: { input: number; output: number };
172
+ }
173
+ export interface PluginAiStructuredResult<T = unknown> {
174
+ data: T;
175
+ rawText: string;
176
+ model: string;
177
+ usage?: { input: number; output: number };
178
+ }
179
+ export interface PluginServiceDefinition {
180
+ name: string;
181
+ description: string;
182
+ parameters?: Record<string, unknown>;
183
+ returns?: Record<string, unknown>;
184
+ }
185
+ export interface PluginServiceDependency {
186
+ pluginId: string;
187
+ service: string;
188
+ optional?: boolean;
189
+ }
190
+ export type PluginActivationEvent =
191
+ | 'onStartup'
192
+ | `onCommand:${string}`
193
+ | `onView:${string}`
194
+ | `onFile:${string}`
195
+ | `onAssistantTool:${string}`
196
+ | `onAssistantContext:${string}`
197
+ | `onService:${string}`;
21
198
  export interface PluginAutomationDefinition { id: string; label: string }
22
199
  export interface ExecutablePluginManifest extends Omit<ObjectPluginManifest, 'manifestVersion'> {
23
200
  manifestVersion: 2;
@@ -26,14 +203,33 @@ export interface ExecutablePluginManifest extends Omit<ObjectPluginManifest, 'ma
26
203
  networkOrigins: string[];
27
204
  nativeCommands: string[];
28
205
  commands: PluginCommandDefinition[];
206
+ /** Optional editor `/` slash menu entries routing to declared commands. */
207
+ slashCommands?: PluginSlashCommandDefinition[];
29
208
  views: PluginViewDefinition[];
209
+ /** Optional fenced code block languages rendered via isolated sandboxed UI views. */
210
+ codeBlockRenderers?: PluginCodeBlockRendererDefinition[];
211
+ /** Optional file open handlers for attachments (preview) or compound-suffix Markdown (editor). */
212
+ fileHandlers?: PluginFileHandlerDefinition[];
213
+ /** Optional tools contributed to Tano Assistant (write/external tools require proposal confirmation). */
214
+ assistantTools?: PluginAssistantToolDefinition[];
215
+ /** Optional `@mention` domain context providers for Tano Assistant. */
216
+ assistantContextProviders?: PluginAssistantContextProviderDefinition[];
217
+ /** Optional stateless RPC services exposed to other plugins via the host message bus. */
218
+ services?: PluginServiceDefinition[];
219
+ /** Optional declarations of services consumed from other plugins. */
220
+ usesServices?: PluginServiceDependency[];
221
+ /** Optional declarative settings form schema; host renders controls and merges defaults. */
222
+ settingsSchema?: PluginSettingField[];
223
+ /** Optional lazy activation triggers; omitting activates on workspace startup. */
224
+ activationEvents?: PluginActivationEvent[];
30
225
  /** Server entry points require separate workspace authorization; installation never schedules them. */
31
226
  automations?: PluginAutomationDefinition[];
32
227
  }
33
228
  export type PluginManifest = ObjectPluginManifest | ExecutablePluginManifest;
34
229
  export type PluginJson = null | boolean | number | string | PluginJson[] | { [key: string]: PluginJson };
35
230
  export interface PluginUiBundle { html: string; css: string; source: string }
36
- export interface PluginPackage { packageVersion: 1; manifest: PluginManifest; source?: string; ui?: Record<string, PluginUiBundle>; automationSource?: string }
231
+ export interface PluginPackageAssets { icons?: FileIconTheme[] }
232
+ export interface PluginPackage { packageVersion: 1; manifest: PluginManifest; source?: string; ui?: Record<string, PluginUiBundle>; automationSource?: string; assets?: PluginPackageAssets }
37
233
  export interface WorkspacePluginRule {
38
234
  manifest: PluginManifest;
39
235
  mode: PluginMode;
@@ -41,10 +237,17 @@ export interface WorkspacePluginRule {
41
237
  integrity?: string;
42
238
  sourceUrl?: string;
43
239
  settings: Record<string, unknown>;
240
+ /** Optional directory prefix allowlist restricting document/attachment access (each ends with '/'). */
241
+ pathScopes?: string[];
44
242
  history?: PluginVersionReference[];
45
243
  }
46
244
  export interface PluginVersionReference { manifest: PluginManifest; integrity?: string; sourceUrl?: string; recordedAt: string }
47
- export interface WorkspacePluginPolicy { version: 1; plugins: WorkspacePluginRule[] }
245
+ export interface WorkspacePluginPolicy {
246
+ version: 1;
247
+ /** Team workspace policy controlling user-scoped executable (v2) plugins accessing this workspace. */
248
+ personalCodePlugins?: WorkspacePersonalPluginPolicy;
249
+ plugins: WorkspacePluginRule[];
250
+ }
48
251
 
49
252
  export function pluginRecord(value: unknown): value is Record<string, unknown> {
50
253
  return !!value && typeof value === 'object' && !Array.isArray(value);
@@ -74,10 +277,15 @@ export function parsePluginManifest(value: unknown): PluginManifest {
74
277
  if (!pluginRecord(value)) throw new Error('插件清单无效');
75
278
  if (value.manifestVersion === 1) return parseObjectPlugin(JSON.stringify(value));
76
279
  keys(value, ['manifestVersion', 'apiVersion', 'id', 'name', 'version', 'description', 'objectTypes',
77
- 'relationTypes', 'permissions', 'networkOrigins', 'nativeCommands', 'commands', 'views', 'automations', 'appearance']);
280
+ 'relationTypes', 'permissions', 'networkOrigins', 'nativeCommands', 'commands', 'slashCommands', 'views',
281
+ 'codeBlockRenderers', 'fileHandlers', 'assistantTools', 'assistantContextProviders', 'services', 'usesServices',
282
+ 'settingsSchema', 'activationEvents', 'automations', 'appearance', 'engines', 'platforms']);
78
283
  if (value.manifestVersion !== 2 || value.apiVersion !== 1) throw new Error('不支持此插件 API 版本');
79
284
  const base = parseObjectPlugin(JSON.stringify({ manifestVersion: 1, id: value.id, name: value.name,
80
- version: value.version, description: value.description, objectTypes: value.objectTypes ?? [], relationTypes: value.relationTypes ?? [], ...(value.appearance === undefined ? {} : { appearance: value.appearance }) }));
285
+ version: value.version, description: value.description, objectTypes: value.objectTypes ?? [], relationTypes: value.relationTypes ?? [],
286
+ ...(value.appearance === undefined ? {} : { appearance: value.appearance }),
287
+ ...(value.engines === undefined ? {} : { engines: value.engines }),
288
+ ...(value.platforms === undefined ? {} : { platforms: value.platforms }) }));
81
289
  const uniqueStrings = (input: unknown, check: (item: unknown) => boolean, limit = 50): string[] => {
82
290
  if (!Array.isArray(input) || input.length > limit || input.some(item => !check(item)) || new Set(input).size !== input.length)
83
291
  throw new Error('插件权限或扩展入口无效');
@@ -95,7 +303,7 @@ export function parsePluginManifest(value: unknown): PluginManifest {
95
303
  if (!Array.isArray(input) || input.length > limit) throw new Error('插件入口数量无效');
96
304
  const ids = new Set<string>();
97
305
  return input.map(item => {
98
- keys(item, kind === 'command' ? ['id', 'label', 'shortcut', 'menus'] : ['id', 'label', 'location']);
306
+ keys(item, kind === 'command' ? ['id', 'label', 'shortcut', 'menus'] : ['id', 'label', 'location', 'layout']);
99
307
  if (!pluginKey(item.id) || !pluginText(item.label, 80) || ids.has(item.id)) throw new Error('插件入口重复或无效');
100
308
  ids.add(item.id);
101
309
  const entry: PluginCommandDefinition & PluginViewDefinition = { id: item.id, label: item.label };
@@ -108,12 +316,304 @@ export function parsePluginManifest(value: unknown): PluginManifest {
108
316
  }
109
317
  if (kind === 'command' && item.menus !== undefined) entry.menus = uniqueStrings(item.menus, location => typeof location === 'string' && ['workspace', 'document', 'file'].includes(location), 3) as PluginMenuLocation[];
110
318
  if (kind === 'view' && item.location !== undefined) {
111
- if (typeof item.location !== 'string' || !['panel', 'tab', 'sidebar', 'settings'].includes(item.location)) throw new Error('插件视图位置无效');
112
- entry.location = item.location;
319
+ if (typeof item.location !== 'string' || !pluginViewLocations.includes(item.location as PluginViewLocation)) throw new Error('插件视图位置无效');
320
+ entry.location = item.location as PluginViewLocation;
321
+ }
322
+ if (kind === 'view' && item.layout !== undefined) {
323
+ if (typeof item.layout !== 'string' || !['contained', 'fill'].includes(item.layout)) throw new Error('插件视图布局无效');
324
+ if (item.layout === 'fill' && entry.location !== 'tab') throw new Error('只有标签页视图支持全高填充布局');
325
+ entry.layout = item.layout as PluginViewLayout;
113
326
  }
114
327
  return entry;
115
328
  });
116
329
  };
330
+ const commands = contributions(value.commands ?? [], 50, 'command');
331
+ let slashCommands: PluginSlashCommandDefinition[] | undefined;
332
+ if (value.slashCommands !== undefined) {
333
+ if (!Array.isArray(value.slashCommands) || !value.slashCommands.length || value.slashCommands.length > 20)
334
+ throw new Error('插件斜杠命令数量无效');
335
+ const seenSlash = new Set<string>();
336
+ slashCommands = value.slashCommands.map((item: unknown): PluginSlashCommandDefinition => {
337
+ keys(item, ['id', 'label', 'command', 'description', 'keywords']);
338
+ const row = item as Record<string, unknown>;
339
+ if (!pluginKey(row.id) || seenSlash.has(row.id) || !pluginText(row.label, 80))
340
+ throw new Error('插件斜杠命令 ID 重复或名称无效');
341
+ if (typeof row.command !== 'string' || !commands.some(command => command.id === row.command))
342
+ throw new Error('斜杠命令必须引用已声明的插件命令');
343
+ if (row.description !== undefined && !pluginText(row.description, 120))
344
+ throw new Error('插件斜杠命令说明无效');
345
+ const keywords =
346
+ row.keywords === undefined
347
+ ? undefined
348
+ : uniqueStrings(row.keywords, word => pluginText(word, 40), 10);
349
+ seenSlash.add(row.id);
350
+ return {
351
+ id: row.id,
352
+ label: row.label,
353
+ command: row.command,
354
+ ...(row.description !== undefined ? { description: row.description } : {}),
355
+ ...(keywords?.length ? { keywords } : {}),
356
+ };
357
+ });
358
+ }
359
+ const views = contributions(value.views ?? [], 10, 'view');
360
+ let codeBlockRenderers: PluginCodeBlockRendererDefinition[] | undefined;
361
+ if (value.codeBlockRenderers !== undefined) {
362
+ if (!permissions.includes('ui')) throw new Error('代码块渲染器必须声明 ui 权限');
363
+ if (!Array.isArray(value.codeBlockRenderers) || !value.codeBlockRenderers.length || value.codeBlockRenderers.length > 10)
364
+ throw new Error('插件代码块渲染器数量无效');
365
+ const seenLanguages = new Set<string>();
366
+ const reservedLanguages = new Set(['mermaid']);
367
+ codeBlockRenderers = value.codeBlockRenderers.map((item: unknown): PluginCodeBlockRendererDefinition => {
368
+ keys(item, ['languages', 'view', 'label', 'height']);
369
+ const row = item as Record<string, unknown>;
370
+ if (typeof row.view !== 'string' || !views.some(view => view.id === row.view))
371
+ throw new Error('代码块渲染器必须引用已声明的视图');
372
+ if (!Array.isArray(row.languages) || !row.languages.length || row.languages.length > 8)
373
+ throw new Error('代码块渲染器语言数量无效');
374
+ const languages = uniqueStrings(
375
+ row.languages,
376
+ lang =>
377
+ typeof lang === 'string' &&
378
+ /^[a-z][a-z0-9-]{0,31}$/.test(lang) &&
379
+ !reservedLanguages.has(lang) &&
380
+ !seenLanguages.has(lang),
381
+ 8,
382
+ );
383
+ languages.forEach(lang => seenLanguages.add(lang));
384
+ if (row.label !== undefined && !pluginText(row.label, 80)) throw new Error('代码块渲染器名称无效');
385
+ if (
386
+ row.height !== undefined &&
387
+ (typeof row.height !== 'number' || !Number.isInteger(row.height) || row.height < 120 || row.height > 720)
388
+ )
389
+ throw new Error('代码块渲染器高度必须为 120 至 720 像素的整数');
390
+ return {
391
+ languages,
392
+ view: row.view,
393
+ ...(row.label !== undefined ? { label: row.label } : {}),
394
+ ...(row.height !== undefined ? { height: row.height } : {}),
395
+ };
396
+ });
397
+ }
398
+ let fileHandlers: PluginFileHandlerDefinition[] | undefined;
399
+ if (value.fileHandlers !== undefined) {
400
+ if (!Array.isArray(value.fileHandlers) || !value.fileHandlers.length || value.fileHandlers.length > 10) throw new Error('插件文件打开器数量无效');
401
+ const seenExtensions = new Set<string>();
402
+ const reservedPreviewExtensions = new Set(['.md', '.markdown', '.tano']);
403
+ fileHandlers = value.fileHandlers.map(item => {
404
+ keys(item, ['extensions', 'mode', 'view', 'command']);
405
+ if (item.mode !== 'preview' && item.mode !== 'editor') throw new Error('插件文件打开器模式无效');
406
+ if (item.mode === 'editor' && !permissions.includes('documents.read')) throw new Error('Markdown 文件打开器必须声明 documents.read 权限');
407
+ if (item.mode === 'preview' && !permissions.includes('attachments.read')) throw new Error('附件预览打开器必须声明 attachments.read 权限');
408
+ if (typeof item.view !== 'string' || !views.some(view => view.id === item.view && view.location === 'tab')) throw new Error('文件打开器必须引用已声明的标签页视图');
409
+ if (typeof item.command !== 'string' || !commands.some(command => command.id === item.command)) throw new Error('文件打开器必须引用已声明的命令');
410
+ if (!Array.isArray(item.extensions) || !item.extensions.length || item.extensions.length > 16) throw new Error('文件打开器扩展名数量无效');
411
+ const extensions = uniqueStrings(item.extensions, ext => {
412
+ if (typeof ext !== 'string' || seenExtensions.has(ext)) return false;
413
+ if (item.mode === 'editor') return /^\.[a-z0-9][a-z0-9-]{0,30}\.(?:md|markdown)$/.test(ext);
414
+ return /^\.[a-z0-9][a-z0-9-]{0,15}$/.test(ext) && !reservedPreviewExtensions.has(ext);
415
+ }, 16);
416
+ extensions.forEach(ext => seenExtensions.add(ext));
417
+ return { extensions, mode: item.mode as PluginFileHandlerMode, view: item.view, command: item.command };
418
+ });
419
+ }
420
+ let settingsSchema: PluginSettingField[] | undefined;
421
+ if (value.settingsSchema !== undefined) {
422
+ if (!Array.isArray(value.settingsSchema) || !value.settingsSchema.length || value.settingsSchema.length > 30)
423
+ throw new Error('插件设置表单定义数量无效');
424
+ const fieldKeys = new Set<string>();
425
+ settingsSchema = value.settingsSchema.map(item => {
426
+ keys(item, ['key', 'label', 'description', 'type', 'default', 'options', 'min', 'max', 'required']);
427
+ if (!pluginKey(item.key) || fieldKeys.has(item.key) || !pluginText(item.label, 80))
428
+ throw new Error('插件设置字段键或名称无效');
429
+ if (item.description !== undefined && !pluginText(item.description, 200))
430
+ throw new Error('插件设置字段说明无效');
431
+ if (item.required !== undefined && typeof item.required !== 'boolean')
432
+ throw new Error('插件设置字段必填声明无效');
433
+ if (!['string', 'number', 'boolean', 'select'].includes(String(item.type)))
434
+ throw new Error('插件设置字段类型无效');
435
+ const type = item.type as PluginSettingFieldType;
436
+ const field: PluginSettingField = { key: item.key, label: item.label, type };
437
+ if (item.description !== undefined) field.description = item.description;
438
+ if (item.required !== undefined) field.required = item.required;
439
+ if (type === 'select') {
440
+ if (!Array.isArray(item.options) || !item.options.length || item.options.length > 30)
441
+ throw new Error('下拉设置字段必须提供 1 至 30 个选项');
442
+ const optionValues = new Set<string>();
443
+ field.options = item.options.map((opt: unknown) => {
444
+ keys(opt, ['value', 'label']);
445
+ const option = opt as Record<string, unknown>;
446
+ if (!pluginText(option.value, 100) || !pluginText(option.label, 80) || optionValues.has(option.value))
447
+ throw new Error('下拉设置选项无效或重复');
448
+ optionValues.add(option.value);
449
+ return { value: option.value, label: option.label };
450
+ });
451
+ if (item.default !== undefined) {
452
+ if (typeof item.default !== 'string' || !optionValues.has(item.default))
453
+ throw new Error('下拉设置默认值必须在选项列表中');
454
+ field.default = item.default;
455
+ }
456
+ if (item.min !== undefined || item.max !== undefined) throw new Error('只有数字设置字段支持范围限制');
457
+ } else {
458
+ if (item.options !== undefined) throw new Error('只有下拉设置字段支持 options');
459
+ if (type === 'number') {
460
+ if (item.min !== undefined && (typeof item.min !== 'number' || !Number.isFinite(item.min)))
461
+ throw new Error('数字设置最小值无效');
462
+ if (item.max !== undefined && (typeof item.max !== 'number' || !Number.isFinite(item.max)))
463
+ throw new Error('数字设置最大值无效');
464
+ if (item.min !== undefined && item.max !== undefined && item.min > item.max)
465
+ throw new Error('数字设置最小值不能大于最大值');
466
+ if (item.min !== undefined) field.min = item.min;
467
+ if (item.max !== undefined) field.max = item.max;
468
+ if (item.default !== undefined) {
469
+ if (typeof item.default !== 'number' || !Number.isFinite(item.default))
470
+ throw new Error('数字设置默认值无效');
471
+ if ((field.min !== undefined && item.default < field.min) || (field.max !== undefined && item.default > field.max))
472
+ throw new Error('数字设置默认值超出允许范围');
473
+ field.default = item.default;
474
+ }
475
+ } else {
476
+ if (item.min !== undefined || item.max !== undefined) throw new Error('只有数字设置字段支持范围限制');
477
+ if (item.default !== undefined) {
478
+ if (type === 'string' && (typeof item.default !== 'string' || item.default.length > 2000))
479
+ throw new Error('文本设置默认值无效');
480
+ if (type === 'boolean' && typeof item.default !== 'boolean')
481
+ throw new Error('开关设置默认值无效');
482
+ field.default = item.default;
483
+ }
484
+ }
485
+ }
486
+ fieldKeys.add(item.key);
487
+ return field;
488
+ });
489
+ }
490
+ let assistantTools: PluginAssistantToolDefinition[] | undefined;
491
+ if (value.assistantTools !== undefined) {
492
+ if (!Array.isArray(value.assistantTools) || !value.assistantTools.length || value.assistantTools.length > 16)
493
+ throw new Error('插件助手工具数量无效');
494
+ const seenTools = new Set<string>();
495
+ assistantTools = value.assistantTools.map((item: unknown): PluginAssistantToolDefinition => {
496
+ keys(item, ['name', 'label', 'description', 'effect', 'parameters']);
497
+ const row = item as Record<string, unknown>;
498
+ if (typeof row.name !== 'string' || !/^[a-z][a-z0-9_-]{0,47}$/.test(row.name) || seenTools.has(row.name))
499
+ throw new Error('插件助手工具名称重复或无效');
500
+ if (!pluginText(row.label, 60) || !pluginText(row.description, 300))
501
+ throw new Error('插件助手工具标题或说明无效');
502
+ if (row.effect !== 'read' && row.effect !== 'write' && row.effect !== 'external')
503
+ throw new Error('插件助手工具副作用等级无效');
504
+ const parameters = parsePluginJsonSchemaObject(row.parameters);
505
+ seenTools.add(row.name);
506
+ return {
507
+ name: row.name,
508
+ label: row.label,
509
+ description: row.description,
510
+ effect: row.effect,
511
+ parameters,
512
+ };
513
+ });
514
+ }
515
+ let assistantContextProviders: PluginAssistantContextProviderDefinition[] | undefined;
516
+ if (value.assistantContextProviders !== undefined) {
517
+ if (
518
+ !Array.isArray(value.assistantContextProviders) ||
519
+ !value.assistantContextProviders.length ||
520
+ value.assistantContextProviders.length > 8
521
+ )
522
+ throw new Error('插件助手上下文提供者数量无效');
523
+ const seenProviders = new Set<string>();
524
+ assistantContextProviders = value.assistantContextProviders.map(
525
+ (item: unknown): PluginAssistantContextProviderDefinition => {
526
+ keys(item, ['id', 'label', 'description', 'maxBytes']);
527
+ const row = item as Record<string, unknown>;
528
+ if (typeof row.id !== 'string' || !/^[a-z][a-z0-9_-]{0,31}$/.test(row.id) || seenProviders.has(row.id))
529
+ throw new Error('插件助手上下文提供者 ID 重复或无效');
530
+ if (!pluginText(row.label, 60) || !pluginText(row.description, 200))
531
+ throw new Error('插件助手上下文提供者标题或说明无效');
532
+ let maxBytes: number | undefined;
533
+ if (row.maxBytes !== undefined) {
534
+ if (
535
+ typeof row.maxBytes !== 'number' ||
536
+ !Number.isInteger(row.maxBytes) ||
537
+ row.maxBytes < 256 ||
538
+ row.maxBytes > pluginAssistantContextMaxBytes
539
+ )
540
+ throw new Error(`插件上下文上限必须为 256 至 ${pluginAssistantContextMaxBytes} 字节的整数`);
541
+ maxBytes = row.maxBytes;
542
+ }
543
+ seenProviders.add(row.id);
544
+ return {
545
+ id: row.id,
546
+ label: row.label,
547
+ description: row.description,
548
+ ...(maxBytes !== undefined ? { maxBytes } : {}),
549
+ };
550
+ },
551
+ );
552
+ }
553
+ let services: PluginServiceDefinition[] | undefined;
554
+ if (value.services !== undefined) {
555
+ if (!Array.isArray(value.services) || !value.services.length || value.services.length > 16)
556
+ throw new Error('插件公开服务数量无效');
557
+ const seenServices = new Set<string>();
558
+ services = value.services.map((item: unknown): PluginServiceDefinition => {
559
+ keys(item, ['name', 'description', 'parameters', 'returns']);
560
+ const row = item as Record<string, unknown>;
561
+ if (typeof row.name !== 'string' || !/^[a-z][a-z0-9_.-]{0,47}$/.test(row.name) || seenServices.has(row.name))
562
+ throw new Error('插件服务名称重复或无效');
563
+ if (!pluginText(row.description, 240)) throw new Error('插件服务说明无效');
564
+ const parameters = row.parameters !== undefined ? parsePluginJsonSchemaObject(row.parameters) : undefined;
565
+ const returns = row.returns !== undefined ? parsePluginJsonSchemaObject(row.returns) : undefined;
566
+ seenServices.add(row.name);
567
+ return {
568
+ name: row.name,
569
+ description: row.description,
570
+ ...(parameters ? { parameters } : {}),
571
+ ...(returns ? { returns } : {}),
572
+ };
573
+ });
574
+ }
575
+ let usesServices: PluginServiceDependency[] | undefined;
576
+ if (value.usesServices !== undefined) {
577
+ if (!Array.isArray(value.usesServices) || !value.usesServices.length || value.usesServices.length > 20)
578
+ throw new Error('插件依赖服务数量无效');
579
+ const seenDeps = new Set<string>();
580
+ usesServices = value.usesServices.map((item: unknown): PluginServiceDependency => {
581
+ keys(item, ['pluginId', 'service', 'optional']);
582
+ const row = item as Record<string, unknown>;
583
+ if (!pluginKey(row.pluginId) || typeof row.service !== 'string' || !/^[a-z][a-z0-9_.-]{0,47}$/.test(row.service))
584
+ throw new Error('插件依赖服务声明无效');
585
+ if (row.optional !== undefined && typeof row.optional !== 'boolean')
586
+ throw new Error('插件依赖服务 optional 字段必须为布尔值');
587
+ const depKey = `${row.pluginId}:${row.service}`;
588
+ if (seenDeps.has(depKey)) throw new Error('插件依赖服务声明重复');
589
+ seenDeps.add(depKey);
590
+ return {
591
+ pluginId: row.pluginId,
592
+ service: row.service,
593
+ ...(row.optional !== undefined ? { optional: row.optional } : {}),
594
+ };
595
+ });
596
+ }
597
+ let activationEvents: PluginActivationEvent[] | undefined;
598
+ if (value.activationEvents !== undefined) {
599
+ if (!Array.isArray(value.activationEvents) || !value.activationEvents.length || value.activationEvents.length > 20)
600
+ throw new Error('插件激活事件数量无效');
601
+ const declaredExtensions = new Set((fileHandlers ?? []).flatMap(handler => handler.extensions));
602
+ const declaredTools = new Set((assistantTools ?? []).map(tool => tool.name));
603
+ const declaredProviders = new Set((assistantContextProviders ?? []).map(provider => provider.id));
604
+ const declaredServices = new Set((services ?? []).map(service => service.name));
605
+ activationEvents = uniqueStrings(value.activationEvents, item => {
606
+ if (typeof item !== 'string') return false;
607
+ if (item === 'onStartup') return true;
608
+ if (item.startsWith('onCommand:')) return commands.some(command => command.id === item.slice('onCommand:'.length));
609
+ if (item.startsWith('onView:')) return views.some(view => view.id === item.slice('onView:'.length));
610
+ if (item.startsWith('onFile:')) return declaredExtensions.has(item.slice('onFile:'.length));
611
+ if (item.startsWith('onAssistantTool:')) return declaredTools.has(item.slice('onAssistantTool:'.length));
612
+ if (item.startsWith('onAssistantContext:')) return declaredProviders.has(item.slice('onAssistantContext:'.length));
613
+ if (item.startsWith('onService:')) return declaredServices.has(item.slice('onService:'.length));
614
+ return false;
615
+ }, 20) as PluginActivationEvent[];
616
+ }
117
617
  let automations: PluginAutomationDefinition[] | undefined;
118
618
  if (value.automations !== undefined) {
119
619
  if (!Array.isArray(value.automations) || !value.automations.length || value.automations.length > 10) throw new Error('插件自动化入口数量无效');
@@ -125,16 +625,93 @@ export function parsePluginManifest(value: unknown): PluginManifest {
125
625
  });
126
626
  }
127
627
  return { ...base, manifestVersion: 2, apiVersion: 1, permissions, networkOrigins, nativeCommands,
128
- commands: contributions(value.commands ?? [], 50, 'command'), views: contributions(value.views ?? [], 10, 'view'),
628
+ commands,
629
+ ...(slashCommands ? { slashCommands } : {}),
630
+ views,
631
+ ...(codeBlockRenderers ? { codeBlockRenderers } : {}),
632
+ ...(fileHandlers ? { fileHandlers } : {}),
633
+ ...(assistantTools ? { assistantTools } : {}),
634
+ ...(assistantContextProviders ? { assistantContextProviders } : {}),
635
+ ...(services ? { services } : {}),
636
+ ...(usesServices ? { usesServices } : {}),
637
+ ...(settingsSchema ? { settingsSchema } : {}),
638
+ ...(activationEvents ? { activationEvents } : {}),
129
639
  ...(automations ? { automations } : {}) };
130
640
  }
641
+ export function resolvePluginSettingsWithDefaults(
642
+ settings: Record<string, unknown>,
643
+ schema?: readonly PluginSettingField[],
644
+ ): Record<string, unknown> {
645
+ const result = parsePluginSettings(settings);
646
+ if (!schema?.length) return result;
647
+ for (const field of schema) {
648
+ if (result[field.key] === undefined && field.default !== undefined) result[field.key] = field.default;
649
+ }
650
+ return result;
651
+ }
652
+ export function validatePluginSettingsAgainstSchema(
653
+ settings: Record<string, unknown>,
654
+ schema?: readonly PluginSettingField[],
655
+ ): Record<string, unknown> {
656
+ const parsed = parsePluginSettings(settings);
657
+ if (!schema?.length) return parsed;
658
+ for (const field of schema) {
659
+ const val = parsed[field.key];
660
+ if (val === undefined || val === null || val === '') {
661
+ if (field.required && field.default === undefined)
662
+ throw new Error(`插件设置项「${field.label}」为必填项`);
663
+ continue;
664
+ }
665
+ if (field.type === 'string' && typeof val !== 'string')
666
+ throw new Error(`插件设置项「${field.label}」必须为文本`);
667
+ if (field.type === 'boolean' && typeof val !== 'boolean')
668
+ throw new Error(`插件设置项「${field.label}」必须为布尔值`);
669
+ if (field.type === 'number') {
670
+ if (typeof val !== 'number' || !Number.isFinite(val))
671
+ throw new Error(`插件设置项「${field.label}」必须为数字`);
672
+ if (field.min !== undefined && val < field.min)
673
+ throw new Error(`插件设置项「${field.label}」不能小于 ${field.min}`);
674
+ if (field.max !== undefined && val > field.max)
675
+ throw new Error(`插件设置项「${field.label}」不能大于 ${field.max}`);
676
+ }
677
+ if (field.type === 'select') {
678
+ if (typeof val !== 'string' || !field.options?.some(opt => opt.value === val))
679
+ throw new Error(`插件设置项「${field.label}」取值不在允许选项中`);
680
+ }
681
+ }
682
+ return parsed;
683
+ }
684
+ export function matchPluginFileExtension(path: string, extension: string): boolean {
685
+ const normalized = path.replaceAll('\\', '/');
686
+ const name = normalized.slice(normalized.lastIndexOf('/') + 1).toLowerCase();
687
+ const suffix = extension.toLowerCase();
688
+ return suffix.startsWith('.') && name.length > suffix.length && name.endsWith(suffix);
689
+ }
131
690
  export function parsePluginPackage(content: string): PluginPackage {
132
691
  if (new TextEncoder().encode(content).length > pluginPackageLimit) throw new Error('插件包不能超过 4 MiB');
133
692
  const value = JSON.parse(content);
134
693
  if (value?.manifestVersion === 1) return { packageVersion: 1, manifest: parsePluginManifest(value) };
135
- keys(value, ['packageVersion', 'manifest', 'source', 'ui', 'automationSource']);
694
+ keys(value, ['packageVersion', 'manifest', 'source', 'ui', 'automationSource', 'assets']);
136
695
  if (value.packageVersion !== 1) throw new Error('不支持此插件包版本');
137
696
  const manifest = parsePluginManifest(value.manifest);
697
+ const iconRefs = manifest.appearance?.iconRefs ?? [];
698
+ let assets: PluginPackageAssets | undefined;
699
+ if (value.assets !== undefined) {
700
+ keys(value.assets, ['icons']);
701
+ if (!Array.isArray(value.assets.icons) || !value.assets.icons.length || value.assets.icons.length > 12)
702
+ throw new Error('插件静态图标资产无效');
703
+ const icons: FileIconTheme[] = value.assets.icons.map((item: unknown) => parseFileIconTheme(item));
704
+ if (new Set(icons.map(theme => theme.id)).size !== icons.length) throw new Error('插件静态图标资产 ID 重复');
705
+ if (icons.length !== iconRefs.length) throw new Error('插件静态图标资产与清单 iconRefs 不一致');
706
+ for (const ref of iconRefs) {
707
+ const target = icons.find(theme => theme.id === ref.id);
708
+ if (!target || target.label !== ref.label || (ref.notice !== undefined && target.notice !== ref.notice))
709
+ throw new Error('插件静态图标资产与清单声明不匹配');
710
+ }
711
+ assets = { icons };
712
+ } else if (iconRefs.length) {
713
+ throw new Error('声明了 iconRefs 的插件包必须附带 assets.icons');
714
+ }
138
715
  if (manifest.manifestVersion === 2) {
139
716
  if (typeof value.source !== 'string' || !value.source.trim()) throw new Error('代码插件缺少入口脚本');
140
717
  const ui: Record<string, PluginUiBundle> = {};
@@ -149,14 +726,76 @@ export function parsePluginPackage(content: string): PluginPackage {
149
726
  ui[id] = { html: bundle.html, css: bundle.css, source: bundle.source };
150
727
  }
151
728
  }
729
+ if (manifest.codeBlockRenderers?.length) {
730
+ for (const renderer of manifest.codeBlockRenderers) {
731
+ if (!Object.hasOwn(ui, renderer.view))
732
+ throw new Error(`代码块渲染器引用的视图「${renderer.view}」缺少 UI 界面包`);
733
+ }
734
+ }
152
735
  if (manifest.automations?.length) {
153
736
  if (typeof value.automationSource !== 'string' || !value.automationSource.trim()) throw new Error('自动化插件缺少服务端入口脚本');
154
737
  } else if (value.automationSource !== undefined) throw new Error('服务端脚本必须声明自动化入口');
155
738
  return { packageVersion: 1, manifest, source: value.source, ...(value.ui === undefined ? {} : { ui }),
156
- ...(value.automationSource === undefined ? {} : { automationSource: value.automationSource }) };
739
+ ...(value.automationSource === undefined ? {} : { automationSource: value.automationSource }),
740
+ ...(assets ? { assets } : {}) };
157
741
  }
158
742
  if (value.source !== undefined || value.ui !== undefined || value.automationSource !== undefined) throw new Error('声明式插件不能携带脚本');
159
- return { packageVersion: 1, manifest };
743
+ return { packageVersion: 1, manifest, ...(assets ? { assets } : {}) };
744
+ }
745
+
746
+ export function isRasterIconTheme(theme: FileIconTheme): boolean {
747
+ return Object.values(theme.icons).some(icon => icon.image !== undefined || icon.lightImage !== undefined);
748
+ }
749
+
750
+ export function hasRasterIconAssets(manifest: PluginManifest): boolean {
751
+ return !!manifest.appearance?.icons?.some(isRasterIconTheme);
752
+ }
753
+
754
+ /** Moves heavy raster PNG icon themes out of manifest.appearance.icons into pkg.assets.icons + manifest.appearance.iconRefs. */
755
+ export function externalizeHeavyIconAssets(pkg: PluginPackage): PluginPackage {
756
+ const inlineIcons = pkg.manifest.appearance?.icons;
757
+ if (!inlineIcons?.some(isRasterIconTheme)) return pkg;
758
+ const keptInline: FileIconTheme[] = [];
759
+ const externalIcons: FileIconTheme[] = [...(pkg.assets?.icons ?? [])];
760
+ const refs: FileIconThemeRef[] = [...(pkg.manifest.appearance?.iconRefs ?? [])];
761
+ for (const theme of inlineIcons) {
762
+ if (isRasterIconTheme(theme)) {
763
+ externalIcons.push(theme);
764
+ refs.push({ id: theme.id, label: theme.label, ...(theme.notice === undefined ? {} : { notice: theme.notice }) });
765
+ } else {
766
+ keptInline.push(theme);
767
+ }
768
+ }
769
+ const { icons: _removed, ...restAppearance } = pkg.manifest.appearance!;
770
+ const manifest: PluginManifest = {
771
+ ...pkg.manifest,
772
+ appearance: {
773
+ ...restAppearance,
774
+ ...(keptInline.length ? { icons: keptInline } : {}),
775
+ iconRefs: refs,
776
+ },
777
+ };
778
+ return parsePluginPackage(JSON.stringify({ ...pkg, manifest, assets: { icons: externalIcons } }));
779
+ }
780
+
781
+ /** Hydrates externalized pkg.assets.icons into an in-memory manifest copy for AppearanceController/FileIconRegistry. */
782
+ export function hydratePluginPackageAssets(manifest: PluginManifest, pkg?: PluginPackage): PluginManifest {
783
+ const externalIcons = pkg?.assets?.icons;
784
+ if (!externalIcons?.length || !manifest.appearance?.iconRefs?.length) return manifest;
785
+ const existing = manifest.appearance.icons ?? [];
786
+ const existingIds = new Set(existing.map(theme => theme.id));
787
+ const merged = [...existing, ...externalIcons.filter(theme => !existingIds.has(theme.id))];
788
+ const mergedIds = new Set(merged.map(theme => theme.id));
789
+ const remainingRefs = manifest.appearance.iconRefs.filter(ref => !mergedIds.has(ref.id));
790
+ const { iconRefs: _hydratedRefs, ...restAppearance } = manifest.appearance;
791
+ return {
792
+ ...manifest,
793
+ appearance: {
794
+ ...restAppearance,
795
+ icons: merged,
796
+ ...(remainingRefs.length ? { iconRefs: remainingRefs } : {}),
797
+ },
798
+ };
160
799
  }
161
800
 
162
801
  /** Validate at both the worker and custom-view boundaries, including non-JSON structured-clone values. */
@@ -175,24 +814,35 @@ export function parsePluginJson(value: unknown, limit = 128 * 1024): PluginJson
175
814
  return JSON.parse(content);
176
815
  }
177
816
  export function parsePluginPolicy(content: string): WorkspacePluginPolicy {
178
- if (new TextEncoder().encode(content).length > 16 * 1024 * 1024) throw new Error('工作区插件规则不能超过 16 MiB');
817
+ const bytes = new TextEncoder().encode(content).length;
818
+ const hasLegacyInlinePng = content.includes('data:image/png;base64,');
819
+ const limit = hasLegacyInlinePng ? legacyWorkspacePluginPolicyLimit : workspacePluginPolicyLimit;
820
+ if (bytes > limit) throw new Error(hasLegacyInlinePng ? '工作区插件规则不能超过 16 MiB' : '工作区插件规则不能超过 1 MiB');
179
821
  const value = JSON.parse(content);
180
- keys(value, ['version', 'plugins']);
822
+ keys(value, ['version', 'personalCodePlugins', 'plugins']);
181
823
  if (value.version !== 1 || !Array.isArray(value.plugins) || value.plugins.length > 100) throw new Error('工作区插件规则无效');
824
+ let personalCodePlugins: WorkspacePersonalPluginPolicy | undefined;
825
+ if (value.personalCodePlugins !== undefined) {
826
+ if (!['allow', 'read-only', 'block'].includes(String(value.personalCodePlugins)))
827
+ throw new Error('个人代码插件访问策略无效');
828
+ personalCodePlugins = value.personalCodePlugins as WorkspacePersonalPluginPolicy;
829
+ }
182
830
  const ids = new Set<string>();
183
831
  const plugins = value.plugins.map((item: unknown): WorkspacePluginRule => {
184
- keys(item, ['manifest', 'mode', 'integrity', 'sourceUrl', 'settings', 'history']);
832
+ keys(item, ['manifest', 'mode', 'integrity', 'sourceUrl', 'settings', 'pathScopes', 'history']);
185
833
  const row = item as Record<string, unknown>;
186
834
  const manifest = parsePluginManifest(row.manifest);
187
835
  if (ids.has(manifest.id) || !['required', 'recommended', 'optional', 'disabled'].includes(String(row.mode))) throw new Error('插件规则重复或模式无效');
188
836
  ids.add(manifest.id);
189
837
  if (row.integrity !== undefined && (typeof row.integrity !== 'string' || !/^[a-f0-9]{64}$/.test(row.integrity))) throw new Error('插件内容摘要无效');
190
838
  if (manifest.manifestVersion === 2 && !row.integrity) throw new Error('代码插件必须锁定内容摘要');
839
+ if (manifest.appearance?.iconRefs?.length && !row.integrity) throw new Error('包含外置图标资产的插件必须锁定内容摘要');
191
840
  if (row.sourceUrl !== undefined) {
192
841
  if (!pluginText(row.sourceUrl, 2048)) throw new Error('插件下载地址无效');
193
842
  const url = new URL(row.sourceUrl);
194
843
  if (url.protocol !== 'https:' || url.username || url.password || url.hash) throw new Error('插件下载地址必须为 HTTPS');
195
844
  }
845
+ const pathScopes = row.pathScopes === undefined ? undefined : parsePluginPathScopes(row.pathScopes);
196
846
  let history: PluginVersionReference[] | undefined;
197
847
  if (row.history !== undefined) {
198
848
  if (!Array.isArray(row.history) || row.history.length > 10) throw new Error('插件最多保留 10 个历史版本');
@@ -204,10 +854,12 @@ export function parsePluginPolicy(content: string): WorkspacePluginPolicy {
204
854
  return { manifest: previous.manifest, ...(previous.integrity ? { integrity: previous.integrity } : {}), ...(previous.sourceUrl ? { sourceUrl: previous.sourceUrl } : {}), recordedAt: value.recordedAt };
205
855
  });
206
856
  }
207
- return { manifest, mode: row.mode as PluginMode, settings: parsePluginSettings(row.settings ?? {}), ...(history ? { history } : {}),
857
+ return { manifest, mode: row.mode as PluginMode, settings: parsePluginSettings(row.settings ?? {}),
858
+ ...(pathScopes?.length ? { pathScopes } : {}),
859
+ ...(history ? { history } : {}),
208
860
  ...(row.integrity ? { integrity: row.integrity as string } : {}), ...(row.sourceUrl ? { sourceUrl: row.sourceUrl as string } : {}) };
209
861
  });
210
- return { version: 1, plugins };
862
+ return { version: 1, ...(personalCodePlugins ? { personalCodePlugins } : {}), plugins };
211
863
  }
212
864
 
213
865
  /** Bounded host-rendered UI: plugin strings never become HTML, CSS or event handlers. */
@@ -237,3 +889,432 @@ export function parsePluginView(value: unknown): PluginViewNode {
237
889
  if (JSON.stringify(value).length > 256 * 1024) throw new Error('插件视图过大');
238
890
  return visit(value, 0);
239
891
  }
892
+
893
+ function pluginMultilineText(value: unknown, max: number): value is string {
894
+ return typeof value === 'string' && value.length > 0 && value.length <= max && !/[\u0000-\u0009\u000b-\u001f]/.test(value);
895
+ }
896
+
897
+ export function parsePluginStatusBarItem(value: unknown): PluginStatusBarItem {
898
+ keys(value, ['id', 'text', 'tooltip', 'align', 'priority', 'tone', 'command']);
899
+ const item = value as Record<string, unknown>;
900
+ if (!pluginKey(item.id) || !pluginText(item.text, 60)) throw new Error('插件状态栏项 ID 或文本无效');
901
+ if (item.tooltip !== undefined && !pluginText(item.tooltip, 200)) throw new Error('插件状态栏提示无效');
902
+ if (item.align !== undefined && item.align !== 'left' && item.align !== 'right')
903
+ throw new Error('插件状态栏对齐方式无效');
904
+ if (
905
+ item.priority !== undefined &&
906
+ (typeof item.priority !== 'number' || !Number.isInteger(item.priority) || item.priority < -1000 || item.priority > 1000)
907
+ )
908
+ throw new Error('插件状态栏优先级必须为 -1000 至 1000 的整数');
909
+ if (item.tone !== undefined && !['default', 'accent', 'warning', 'danger'].includes(String(item.tone)))
910
+ throw new Error('插件状态栏样式类型无效');
911
+ if (item.command !== undefined && !pluginKey(item.command)) throw new Error('插件状态栏命令标识无效');
912
+ return {
913
+ id: item.id,
914
+ text: item.text,
915
+ ...(item.tooltip !== undefined ? { tooltip: item.tooltip } : {}),
916
+ align: (item.align as PluginStatusBarAlign | undefined) ?? 'right',
917
+ priority: (item.priority as number | undefined) ?? 0,
918
+ tone: (item.tone as PluginStatusBarTone | undefined) ?? 'default',
919
+ ...(item.command !== undefined ? { command: item.command } : {}),
920
+ };
921
+ }
922
+
923
+ export function parsePluginUiPickOptions(value: unknown): PluginUiPickOptions {
924
+ keys(value, ['title', 'placeholder', 'items']);
925
+ const opts = value as Record<string, unknown>;
926
+ if (!pluginText(opts.title, 120)) throw new Error('选择框标题无效');
927
+ if (opts.placeholder !== undefined && !pluginText(opts.placeholder, 120)) throw new Error('选择框占位提示无效');
928
+ if (!Array.isArray(opts.items) || !opts.items.length || opts.items.length > 200)
929
+ throw new Error('选择框必须提供 1 至 200 个选项');
930
+ const seen = new Set<string>();
931
+ const items = opts.items.map((raw: unknown): PluginUiPickItem => {
932
+ keys(raw, ['id', 'label', 'description', 'detail']);
933
+ const entry = raw as Record<string, unknown>;
934
+ if (!pluginText(entry.id, 120) || seen.has(entry.id) || !pluginText(entry.label, 120))
935
+ throw new Error('选择框选项 ID 重复或名称无效');
936
+ seen.add(entry.id);
937
+ if (entry.description !== undefined && !pluginText(entry.description, 160)) throw new Error('选择框选项摘要无效');
938
+ if (entry.detail !== undefined && !pluginText(entry.detail, 240)) throw new Error('选择框选项详情无效');
939
+ return {
940
+ id: entry.id,
941
+ label: entry.label,
942
+ ...(entry.description !== undefined ? { description: entry.description } : {}),
943
+ ...(entry.detail !== undefined ? { detail: entry.detail } : {}),
944
+ };
945
+ });
946
+ return {
947
+ title: opts.title,
948
+ ...(opts.placeholder !== undefined ? { placeholder: opts.placeholder } : {}),
949
+ items,
950
+ };
951
+ }
952
+
953
+ export function parsePluginUiPromptOptions(value: unknown): PluginUiPromptOptions {
954
+ keys(value, ['title', 'message', 'placeholder', 'defaultValue', 'confirmLabel']);
955
+ const opts = value as Record<string, unknown>;
956
+ if (!pluginText(opts.title, 120)) throw new Error('输入框标题无效');
957
+ if (opts.message !== undefined && !pluginMultilineText(opts.message, 500)) throw new Error('输入框说明无效');
958
+ if (opts.placeholder !== undefined && !pluginText(opts.placeholder, 120)) throw new Error('输入框占位提示无效');
959
+ if (opts.defaultValue !== undefined && (typeof opts.defaultValue !== 'string' || opts.defaultValue.length > 2000 || /[\u0000-\u001f]/.test(opts.defaultValue)))
960
+ throw new Error('输入框默认值无效');
961
+ if (opts.confirmLabel !== undefined && !pluginText(opts.confirmLabel, 40)) throw new Error('输入框确认按钮文案无效');
962
+ return {
963
+ title: opts.title,
964
+ ...(opts.message !== undefined ? { message: opts.message } : {}),
965
+ ...(opts.placeholder !== undefined ? { placeholder: opts.placeholder } : {}),
966
+ ...(opts.defaultValue !== undefined ? { defaultValue: opts.defaultValue } : {}),
967
+ ...(opts.confirmLabel !== undefined ? { confirmLabel: opts.confirmLabel } : {}),
968
+ };
969
+ }
970
+
971
+ export function parsePluginUiConfirmOptions(value: unknown): PluginUiConfirmOptions {
972
+ keys(value, ['title', 'message', 'confirmLabel', 'cancelLabel', 'danger']);
973
+ const opts = value as Record<string, unknown>;
974
+ if (!pluginText(opts.title, 120)) throw new Error('确认框标题无效');
975
+ if (opts.message !== undefined && !pluginMultilineText(opts.message, 500)) throw new Error('确认框说明无效');
976
+ if (opts.confirmLabel !== undefined && !pluginText(opts.confirmLabel, 40)) throw new Error('确认框确认按钮文案无效');
977
+ if (opts.cancelLabel !== undefined && !pluginText(opts.cancelLabel, 40)) throw new Error('确认框取消按钮文案无效');
978
+ if (opts.danger !== undefined && typeof opts.danger !== 'boolean') throw new Error('确认框危险标记无效');
979
+ return {
980
+ title: opts.title,
981
+ ...(opts.message !== undefined ? { message: opts.message } : {}),
982
+ ...(opts.confirmLabel !== undefined ? { confirmLabel: opts.confirmLabel } : {}),
983
+ ...(opts.cancelLabel !== undefined ? { cancelLabel: opts.cancelLabel } : {}),
984
+ ...(opts.danger !== undefined ? { danger: opts.danger } : {}),
985
+ };
986
+ }
987
+
988
+ export function parsePluginUiToastOptions(value: unknown): PluginUiToastOptions {
989
+ keys(value, ['message', 'tone']);
990
+ const opts = value as Record<string, unknown>;
991
+ if (!pluginText(opts.message, 300)) throw new Error('提示消息无效');
992
+ if (opts.tone !== undefined && !['info', 'success', 'warning', 'error'].includes(String(opts.tone)))
993
+ throw new Error('提示消息类型无效');
994
+ return {
995
+ message: opts.message,
996
+ tone: (opts.tone as PluginUiTone | undefined) ?? 'info',
997
+ };
998
+ }
999
+
1000
+ export function parsePluginFrontmatterPatch(value: unknown): PluginFrontmatterPatch {
1001
+ keys(value, ['set', 'remove']);
1002
+ const patch = value as Record<string, unknown>;
1003
+ let set: Record<string, PluginJson> | undefined;
1004
+ let remove: string[] | undefined;
1005
+ if (patch.set !== undefined) {
1006
+ if (!pluginRecord(patch.set)) throw new Error('frontmatter.set 必须为键值对对象');
1007
+ const entries = Object.entries(patch.set);
1008
+ if (entries.length > 50) throw new Error('单次最多更新 50 个文档属性');
1009
+ const normalized: Record<string, PluginJson> = {};
1010
+ for (const [key, raw] of entries) {
1011
+ const trimmed = key.trim();
1012
+ if (!trimmed || trimmed !== key || !pluginText(trimmed, 100))
1013
+ throw new Error(`文档属性名无效:${key}`);
1014
+ normalized[trimmed] = parsePluginJson(raw, 16 * 1024);
1015
+ }
1016
+ if (entries.length) set = normalized;
1017
+ }
1018
+ if (patch.remove !== undefined) {
1019
+ if (!Array.isArray(patch.remove) || patch.remove.length > 50)
1020
+ throw new Error('frontmatter.remove 必须为不超过 50 项的属性名数组');
1021
+ const seen = new Set<string>();
1022
+ const list: string[] = [];
1023
+ for (const item of patch.remove) {
1024
+ if (typeof item !== 'string' || !item.trim() || item.trim() !== item || !pluginText(item, 100) || seen.has(item))
1025
+ throw new Error('frontmatter.remove 包含无效或重复的属性名');
1026
+ seen.add(item);
1027
+ list.push(item);
1028
+ }
1029
+ if (list.length) remove = list;
1030
+ }
1031
+ if (!set && !remove) throw new Error('frontmatter 更新必须指定 set 或 remove');
1032
+ return { ...(set ? { set } : {}), ...(remove ? { remove } : {}) };
1033
+ }
1034
+
1035
+ export function parsePluginEditorDecorations(value: unknown): PluginEditorDecoration[] {
1036
+ if (!Array.isArray(value) || value.length > 200) throw new Error('插件编辑器装饰数量不能超过 200 项');
1037
+ return value.map((raw: unknown): PluginEditorDecoration => {
1038
+ keys(raw, ['id', 'from', 'to', 'tone', 'badge', 'tooltip', 'command']);
1039
+ const item = raw as Record<string, unknown>;
1040
+ if (item.id !== undefined && !pluginKey(item.id)) throw new Error('插件装饰 ID 无效');
1041
+ if (
1042
+ typeof item.from !== 'number' ||
1043
+ typeof item.to !== 'number' ||
1044
+ !Number.isSafeInteger(item.from) ||
1045
+ !Number.isSafeInteger(item.to) ||
1046
+ item.from < 0 ||
1047
+ item.to < item.from
1048
+ )
1049
+ throw new Error('插件装饰偏移范围无效');
1050
+ if (item.tone !== undefined && !['info', 'accent', 'warning', 'danger', 'muted'].includes(String(item.tone)))
1051
+ throw new Error('插件装饰样式类型无效');
1052
+ if (item.badge !== undefined && !pluginText(item.badge, 48)) throw new Error('插件装饰徽章文本无效');
1053
+ if (item.tooltip !== undefined && !pluginText(item.tooltip, 200)) throw new Error('插件装饰提示文本无效');
1054
+ if (item.command !== undefined && !pluginKey(item.command)) throw new Error('插件装饰命令标识无效');
1055
+ if (item.to === item.from && item.badge === undefined)
1056
+ throw new Error('空范围装饰必须提供 badge 文本');
1057
+ return {
1058
+ ...(item.id !== undefined ? { id: item.id } : {}),
1059
+ from: item.from,
1060
+ to: item.to,
1061
+ tone: (item.tone as PluginEditorDecorationTone | undefined) ?? 'accent',
1062
+ ...(item.badge !== undefined ? { badge: item.badge } : {}),
1063
+ ...(item.tooltip !== undefined ? { tooltip: item.tooltip } : {}),
1064
+ ...(item.command !== undefined ? { command: item.command } : {}),
1065
+ };
1066
+ });
1067
+ }
1068
+
1069
+ export function parsePluginPathScopes(value: unknown): string[] | undefined {
1070
+ if (value === undefined || value === null) return undefined;
1071
+ if (!Array.isArray(value) || value.length > 20) throw new Error('插件目录权限范围最多支持 20 项');
1072
+ if (!value.length) return undefined;
1073
+ const seen = new Set<string>();
1074
+ const normalized: string[] = [];
1075
+ for (const raw of value) {
1076
+ if (typeof raw !== 'string' || !pluginText(raw, 200)) throw new Error('插件目录权限路径无效');
1077
+ const trimmed = raw.trim().replace(/\/+$/, '');
1078
+ if (
1079
+ !trimmed ||
1080
+ trimmed.startsWith('/') ||
1081
+ trimmed.includes('\\') ||
1082
+ trimmed.includes('//') ||
1083
+ trimmed.split('/').some(seg => !seg || seg === '.' || seg === '..' || seg === '.tano')
1084
+ )
1085
+ throw new Error(`插件目录权限路径不合法:${raw}`);
1086
+ const scope = `${trimmed}/`;
1087
+ if (!seen.has(scope)) {
1088
+ seen.add(scope);
1089
+ normalized.push(scope);
1090
+ }
1091
+ }
1092
+ return normalized.length ? normalized : undefined;
1093
+ }
1094
+
1095
+ export function matchesPluginPathScopes(path: string, scopes?: readonly string[]): boolean {
1096
+ if (!scopes?.length) return true;
1097
+ const normalized = path.replaceAll('\\', '/').replace(/^\/+/, '');
1098
+ return scopes.some(scope => normalized.startsWith(scope));
1099
+ }
1100
+
1101
+ export function parsePluginAttachmentWrite(value: unknown): {
1102
+ name: string;
1103
+ bytes: Uint8Array;
1104
+ documentPath: string;
1105
+ mimeType: string;
1106
+ image: boolean;
1107
+ } {
1108
+ keys(value, ['name', 'contentBase64', 'documentPath', 'mimeType']);
1109
+ const input = value as Record<string, unknown>;
1110
+ if (!pluginText(input.name, 160) || /[\\/]/.test(input.name) || input.name === '.' || input.name === '..')
1111
+ throw new Error('附件文件名无效');
1112
+ const lower = input.name.toLowerCase();
1113
+ const ext = pluginAttachmentWriteExtensions.find(suffix => lower.length > suffix.length && lower.endsWith(suffix));
1114
+ if (!ext) throw new Error('不支持写入此类型的附件文件');
1115
+ if (typeof input.contentBase64 !== 'string' || !input.contentBase64.length || input.contentBase64.length > 560 * 1024)
1116
+ throw new Error('附件内容无效或超过 400 KiB 写入上限');
1117
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(input.contentBase64) || input.contentBase64.length % 4 !== 0)
1118
+ throw new Error('附件 Base64 编码无效');
1119
+ let binary: string;
1120
+ try {
1121
+ binary = atob(input.contentBase64);
1122
+ } catch {
1123
+ throw new Error('附件 Base64 解码失败');
1124
+ }
1125
+ if (binary.length === 0 || binary.length > pluginAttachmentWriteLimit)
1126
+ throw new Error('附件内容不能为空且不能超过 400 KiB');
1127
+ const bytes = new Uint8Array(binary.length);
1128
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
1129
+ let documentPath = '';
1130
+ if (input.documentPath !== undefined) {
1131
+ if (typeof input.documentPath !== 'string' || input.documentPath.length > 500 || /[\u0000-\u001f\\]/.test(input.documentPath))
1132
+ throw new Error('关联文档路径无效');
1133
+ if (input.documentPath.startsWith('/') || input.documentPath.split('/').some(seg => seg === '..' || seg === '.tano'))
1134
+ throw new Error('关联文档路径不合法');
1135
+ documentPath = input.documentPath;
1136
+ }
1137
+ const mimeType =
1138
+ input.mimeType !== undefined
1139
+ ? (() => {
1140
+ if (!pluginText(input.mimeType, 100) || !/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/i.test(input.mimeType))
1141
+ throw new Error('附件 MIME 类型无效');
1142
+ return input.mimeType;
1143
+ })()
1144
+ : 'application/octet-stream';
1145
+ const image = ['.png', '.jpg', '.jpeg', '.webp', '.gif', '.svg'].includes(ext);
1146
+ return { name: input.name, bytes, documentPath, mimeType, image };
1147
+ }
1148
+
1149
+ const allowedJsonSchemaTypes = new Set(['string', 'number', 'integer', 'boolean', 'array', 'object', 'null']);
1150
+ function sanitizeJsonSchemaNode(value: unknown, depth = 0): Record<string, unknown> {
1151
+ if (depth > 4 || !pluginRecord(value)) throw new Error('JSON Schema 节点无效或嵌套过深');
1152
+ const node: Record<string, unknown> = {};
1153
+ const allowedKeys = [
1154
+ 'type', 'description', 'enum', 'properties', 'required', 'additionalProperties',
1155
+ 'items', 'minLength', 'maxLength', 'minimum', 'maximum', 'minItems', 'maxItems',
1156
+ ];
1157
+ for (const key of Object.keys(value)) {
1158
+ if (!allowedKeys.includes(key)) throw new Error(`JSON Schema 包含不支持的字段:${key}`);
1159
+ }
1160
+ if (value.type !== undefined) {
1161
+ if (typeof value.type === 'string') {
1162
+ if (!allowedJsonSchemaTypes.has(value.type)) throw new Error('JSON Schema 字段类型不受支持');
1163
+ node.type = value.type;
1164
+ } else if (Array.isArray(value.type) && value.type.length > 0 && value.type.length <= 2) {
1165
+ if (value.type.some(item => typeof item !== 'string' || !allowedJsonSchemaTypes.has(item)))
1166
+ throw new Error('JSON Schema 联合类型不受支持');
1167
+ node.type = [...value.type];
1168
+ } else {
1169
+ throw new Error('JSON Schema type 格式无效');
1170
+ }
1171
+ }
1172
+ if (value.description !== undefined) {
1173
+ if (!pluginText(value.description, 300)) throw new Error('JSON Schema 说明无效');
1174
+ node.description = value.description;
1175
+ }
1176
+ if (value.enum !== undefined) {
1177
+ if (!Array.isArray(value.enum) || !value.enum.length || value.enum.length > 32)
1178
+ throw new Error('JSON Schema 枚举数量无效');
1179
+ if (value.enum.some(item => !['string', 'number', 'boolean'].includes(typeof item) && item !== null))
1180
+ throw new Error('JSON Schema 枚举项类型无效');
1181
+ node.enum = [...value.enum];
1182
+ }
1183
+ if (value.properties !== undefined) {
1184
+ if (!pluginRecord(value.properties)) throw new Error('JSON Schema properties 必须是对象');
1185
+ const entries = Object.entries(value.properties);
1186
+ if (entries.length > 20) throw new Error('JSON Schema 属性数量超过 20 个上限');
1187
+ const props: Record<string, unknown> = {};
1188
+ for (const [propKey, propSchema] of entries) {
1189
+ if (!/^[a-zA-Z0-9_.-]{1,64}$/.test(propKey)) throw new Error('JSON Schema 属性键无效');
1190
+ props[propKey] = sanitizeJsonSchemaNode(propSchema, depth + 1);
1191
+ }
1192
+ node.properties = props;
1193
+ }
1194
+ if (value.required !== undefined) {
1195
+ const props = (node.properties as Record<string, unknown> | undefined) ?? {};
1196
+ if (
1197
+ !Array.isArray(value.required) ||
1198
+ value.required.length > 20 ||
1199
+ value.required.some(item => typeof item !== 'string' || !Object.prototype.hasOwnProperty.call(props, item)) ||
1200
+ new Set(value.required).size !== value.required.length
1201
+ )
1202
+ throw new Error('JSON Schema required 必须引用已声明的 properties');
1203
+ node.required = [...value.required];
1204
+ }
1205
+ if (value.additionalProperties !== undefined) {
1206
+ if (typeof value.additionalProperties !== 'boolean') throw new Error('JSON Schema additionalProperties 必须为布尔值');
1207
+ node.additionalProperties = value.additionalProperties;
1208
+ }
1209
+ if (value.items !== undefined) {
1210
+ node.items = sanitizeJsonSchemaNode(value.items, depth + 1);
1211
+ }
1212
+ for (const bound of ['minLength', 'maxLength', 'minimum', 'maximum', 'minItems', 'maxItems'] as const) {
1213
+ if (value[bound] !== undefined) {
1214
+ if (typeof value[bound] !== 'number' || !Number.isFinite(value[bound]))
1215
+ throw new Error(`JSON Schema ${bound} 必须为有效数字`);
1216
+ node[bound] = value[bound];
1217
+ }
1218
+ }
1219
+ return node;
1220
+ }
1221
+
1222
+ export function parsePluginJsonSchemaObject(value: unknown): Record<string, unknown> {
1223
+ const schema = sanitizeJsonSchemaNode(value, 0);
1224
+ if (schema.type !== 'object' || !pluginRecord(schema.properties))
1225
+ throw new Error('JSON Schema 顶层必须为 type: "object" 且声明 properties');
1226
+ if (schema.additionalProperties === undefined) schema.additionalProperties = false;
1227
+ if (JSON.stringify(schema).length > 8192) throw new Error('JSON Schema 大小不能超过 8 KiB');
1228
+ return schema;
1229
+ }
1230
+
1231
+ function matchesSchemaType(value: unknown, expected: string): boolean {
1232
+ if (expected === 'null') return value === null;
1233
+ if (expected === 'array') return Array.isArray(value);
1234
+ if (expected === 'object') return pluginRecord(value);
1235
+ if (expected === 'integer') return typeof value === 'number' && Number.isInteger(value);
1236
+ if (expected === 'number') return typeof value === 'number' && Number.isFinite(value);
1237
+ return typeof value === expected;
1238
+ }
1239
+
1240
+ export function validateAgainstPluginJsonSchema(data: unknown, schema: Record<string, unknown>, path = '$'): void {
1241
+ if (schema.type !== undefined) {
1242
+ const allowed = Array.isArray(schema.type) ? (schema.type as string[]) : [String(schema.type)];
1243
+ if (!allowed.some(type => matchesSchemaType(data, type)))
1244
+ throw new Error(`结构化输出字段 ${path} 类型不匹配,期望 ${allowed.join(' | ')}`);
1245
+ }
1246
+ if (Array.isArray(schema.enum) && !schema.enum.includes(data))
1247
+ throw new Error(`结构化输出字段 ${path} 不在允许的枚举范围内`);
1248
+ if (pluginRecord(data) && pluginRecord(schema.properties)) {
1249
+ const props = schema.properties as Record<string, Record<string, unknown>>;
1250
+ if (Array.isArray(schema.required)) {
1251
+ for (const req of schema.required) {
1252
+ if (typeof req === 'string' && !Object.prototype.hasOwnProperty.call(data, req))
1253
+ throw new Error(`结构化输出缺少必填字段 ${path}.${req}`);
1254
+ }
1255
+ }
1256
+ if (schema.additionalProperties === false) {
1257
+ for (const key of Object.keys(data)) {
1258
+ if (!Object.prototype.hasOwnProperty.call(props, key))
1259
+ throw new Error(`结构化输出包含未声明字段 ${path}.${key}`);
1260
+ }
1261
+ }
1262
+ for (const [key, propSchema] of Object.entries(props)) {
1263
+ if (Object.prototype.hasOwnProperty.call(data, key)) {
1264
+ validateAgainstPluginJsonSchema(data[key], propSchema, `${path}.${key}`);
1265
+ }
1266
+ }
1267
+ }
1268
+ if (Array.isArray(data) && pluginRecord(schema.items)) {
1269
+ for (let i = 0; i < data.length; i++) {
1270
+ validateAgainstPluginJsonSchema(data[i], schema.items as Record<string, unknown>, `${path}[${i}]`);
1271
+ }
1272
+ }
1273
+ }
1274
+
1275
+ export function parsePluginAiRequest(
1276
+ value: unknown,
1277
+ structured: false,
1278
+ ): PluginAiCompleteRequest;
1279
+ export function parsePluginAiRequest(
1280
+ value: unknown,
1281
+ structured: true,
1282
+ ): PluginAiStructuredRequest;
1283
+ export function parsePluginAiRequest(
1284
+ value: unknown,
1285
+ structured: boolean,
1286
+ ): PluginAiCompleteRequest | PluginAiStructuredRequest {
1287
+ keys(value, structured ? ['prompt', 'system', 'maxTokens', 'temperature', 'schema'] : ['prompt', 'system', 'maxTokens', 'temperature']);
1288
+ const input = value as Record<string, unknown>;
1289
+ if (typeof input.prompt !== 'string' || !input.prompt.trim() || input.prompt.length > 32_000)
1290
+ throw new Error('AI 请求 prompt 不能为空且不能超过 32000 字符');
1291
+ let system: string | undefined;
1292
+ if (input.system !== undefined) {
1293
+ if (typeof input.system !== 'string' || input.system.length > 4_000)
1294
+ throw new Error('AI 请求 system 提示不能超过 4000 字符');
1295
+ if (input.system.trim()) system = input.system;
1296
+ }
1297
+ let maxTokens: number | undefined;
1298
+ if (input.maxTokens !== undefined) {
1299
+ if (typeof input.maxTokens !== 'number' || !Number.isInteger(input.maxTokens) || input.maxTokens < 1 || input.maxTokens > 4096)
1300
+ throw new Error('AI 请求 maxTokens 必须为 1 至 4096 的整数');
1301
+ maxTokens = input.maxTokens;
1302
+ }
1303
+ let temperature: number | undefined;
1304
+ if (input.temperature !== undefined) {
1305
+ if (typeof input.temperature !== 'number' || !Number.isFinite(input.temperature) || input.temperature < 0 || input.temperature > 2)
1306
+ throw new Error('AI 请求 temperature 必须在 0 至 2 之间');
1307
+ temperature = input.temperature;
1308
+ }
1309
+ const base: PluginAiCompleteRequest = {
1310
+ prompt: input.prompt,
1311
+ ...(system !== undefined ? { system } : {}),
1312
+ ...(maxTokens !== undefined ? { maxTokens } : {}),
1313
+ ...(temperature !== undefined ? { temperature } : {}),
1314
+ };
1315
+ if (!structured) return base;
1316
+ return {
1317
+ ...base,
1318
+ schema: parsePluginJsonSchemaObject(input.schema),
1319
+ };
1320
+ }