@tano.page/workbench 0.14.0 → 0.16.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.
Files changed (248) hide show
  1. package/package.json +50 -16
  2. package/src/App.vue +82 -752
  3. package/src/appearance/appearance.ts +14 -4
  4. package/src/appearance/components/ThemePresetPreview.vue +52 -8
  5. package/src/appearance/interface-font.ts +99 -0
  6. package/src/appearance/theme.ts +26 -10
  7. package/src/appearance/use-interface-font.ts +30 -0
  8. package/src/assets/mail-provider-icons/NOTICE.txt +27 -0
  9. package/src/assets/mail-provider-icons/aliyun-mail.svg +3 -0
  10. package/src/assets/mail-provider-icons/gmail.svg +1 -0
  11. package/src/assets/mail-provider-icons/icloud.svg +12 -0
  12. package/src/assets/mail-provider-icons/netease-126.svg +5 -0
  13. package/src/assets/mail-provider-icons/netease-163.svg +5 -0
  14. package/src/assets/mail-provider-icons/qq.svg +9 -0
  15. package/src/assets/mail-provider-icons/tencent-exmail.svg +4 -0
  16. package/src/assistant/agent-identities.ts +1 -97
  17. package/src/assistant/agent-task-context.ts +1 -54
  18. package/src/assistant/attachments.ts +1 -1
  19. package/src/assistant/completion.ts +1 -61
  20. package/src/assistant/components/AssistantChangeList.vue +98 -21
  21. package/src/assistant/components/AssistantPanel.vue +425 -8
  22. package/src/assistant/components/PluginToolProposalCard.vue +235 -0
  23. package/src/assistant/connection-actions.ts +237 -0
  24. package/src/assistant/document-mentions.ts +1 -33
  25. package/src/assistant/engine.ts +1 -532
  26. package/src/assistant/execution.ts +6 -33
  27. package/src/assistant/files.ts +5 -13
  28. package/src/assistant/hash.ts +1 -4
  29. package/src/assistant/inbox.ts +1 -148
  30. package/src/assistant/language.ts +10 -37
  31. package/src/assistant/mention-autocomplete.ts +69 -0
  32. package/src/assistant/plugin-bridge-builder.ts +146 -0
  33. package/src/assistant/prompts.ts +1 -58
  34. package/src/assistant/proposal-actions.ts +336 -0
  35. package/src/assistant/results.ts +20 -86
  36. package/src/assistant/store.ts +167 -327
  37. package/src/assistant/structures.ts +1 -155
  38. package/src/assistant/tasks.ts +8 -96
  39. package/src/assistant/tool-rules.ts +1 -7
  40. package/src/assistant/workspace-bridge.ts +1 -1
  41. package/src/composables/use-document-actions.ts +38 -20
  42. package/src/composables/use-file-tree-controller.ts +7 -12
  43. package/src/composables/use-workbench-help.ts +177 -0
  44. package/src/composables/use-workbench-history.ts +2 -4
  45. package/src/composables/use-workbench-lifecycle.ts +249 -0
  46. package/src/composables/use-workbench-modals.ts +6 -1
  47. package/src/composables/use-workbench-outline.ts +0 -5
  48. package/src/composables/use-workbench-settings.ts +185 -0
  49. package/src/composables/use-workbench-shortcuts.ts +40 -1021
  50. package/src/composables/use-workbench-views.ts +325 -0
  51. package/src/data-tables/data-tables.ts +1 -2
  52. package/src/documents/components/DocumentActionMenu.vue +279 -0
  53. package/src/documents/components/DocumentHistoryPanel.vue +3 -1
  54. package/src/documents/components/DocumentInspector.vue +168 -0
  55. package/src/documents/components/DocumentPane.vue +482 -0
  56. package/src/documents/description-merge.ts +1 -9
  57. package/src/features.ts +1 -0
  58. package/src/files/components/FileMetadataPanel.vue +49 -15
  59. package/src/fonts/Inter-Latin-Italic.woff2 +0 -0
  60. package/src/fonts/Inter-Latin.woff2 +0 -0
  61. package/src/fonts/TanoUISansSC-Bold.woff2 +0 -0
  62. package/src/fonts/TanoUISansSC-Medium.woff2 +0 -0
  63. package/src/fonts/TanoUISansSC-Regular.woff2 +0 -0
  64. package/src/help/help-milestones.ts +3 -5
  65. package/src/i18n/locale-catalogs.ts +7 -6
  66. package/src/i18n/locale-registry.ts +8 -6
  67. package/src/i18n/locales/de-DE.json +371 -3
  68. package/src/i18n/locales/en-US.json +371 -2
  69. package/src/i18n/locales/es-ES.json +371 -3
  70. package/src/i18n/locales/ja-JP.json +370 -2
  71. package/src/i18n/locales/zh-TW.json +370 -2
  72. package/src/mail/components/MailAccountDialog.vue +450 -0
  73. package/src/mail/components/MailComposerDialog.vue +326 -0
  74. package/src/mail/components/MailProviderIcon.vue +30 -0
  75. package/src/mail/components/MailWorkspaceView.vue +821 -0
  76. package/src/mail/components/SidebarMail.vue +134 -0
  77. package/src/mail/mail-avatar.ts +17 -0
  78. package/src/mail/mail-bridge.ts +68 -0
  79. package/src/mail/mail-calendar.ts +208 -0
  80. package/src/mail/mail-markdown.ts +195 -0
  81. package/src/mail/types.ts +226 -0
  82. package/src/objects/components/ObjectDetailModal.vue +1001 -0
  83. package/src/objects/content-references.ts +6 -56
  84. package/src/objects/wiki-links.ts +1 -48
  85. package/src/objects/workspace-objects.ts +3 -4
  86. package/src/plan-sync/types.ts +6 -3
  87. package/src/plans/calendar-interaction.ts +194 -0
  88. package/src/plans/calendar.ts +65 -9
  89. package/src/plans/components/CalendarAgendaView.vue +165 -0
  90. package/src/plans/components/CalendarDayPopover.vue +172 -39
  91. package/src/plans/components/CalendarFilterBar.vue +128 -0
  92. package/src/plans/components/CalendarMonthView.vue +224 -0
  93. package/src/plans/components/CalendarQuickCreateDialog.vue +269 -0
  94. package/src/plans/components/CalendarTimelineView.vue +517 -0
  95. package/src/plans/components/CalendarTopbarControls.vue +101 -0
  96. package/src/plans/components/CalendarView.vue +264 -748
  97. package/src/plans/components/CalendarYearView.vue +138 -0
  98. package/src/plans/components/PlanArchiveDialog.vue +295 -0
  99. package/src/plans/components/PlanConnectionsDialog.vue +1 -1
  100. package/src/plans/components/PlanDateField.vue +6 -4
  101. package/src/plans/components/PlanDetailPanel.vue +227 -32
  102. package/src/plans/components/PlanEventList.vue +16 -4
  103. package/src/plans/components/SidebarPlan.vue +22 -15
  104. package/src/plans/components/TaskRepeatControls.vue +169 -30
  105. package/src/plans/components/calendar-shared.css +192 -0
  106. package/src/plans/composables/use-calendar-interactions.ts +396 -0
  107. package/src/plans/composables/use-calendar-scroll.ts +420 -0
  108. package/src/plans/local-reminders.ts +149 -0
  109. package/src/plans/personal-plans.ts +10 -1
  110. package/src/plans/plan-date.ts +8 -1
  111. package/src/plans/plan-migration.ts +95 -0
  112. package/src/plans/recurrence.ts +95 -0
  113. package/src/plans/task-repeat.ts +8 -8
  114. package/src/plans/timeline-layout.ts +92 -0
  115. package/src/plugins/assistant-bridge.ts +520 -0
  116. package/src/plugins/attachment-reader.ts +3 -1
  117. package/src/plugins/cache-storage.ts +42 -2
  118. package/src/plugins/components/PluginAutomations.vue +3 -3
  119. package/src/plugins/components/PluginCatalogBrowser.vue +17 -8
  120. package/src/plugins/components/PluginChangeSummary.vue +16 -3
  121. package/src/plugins/components/PluginConnections.vue +1 -1
  122. package/src/plugins/components/PluginCustomView.vue +2 -2
  123. package/src/plugins/components/PluginDetailPage.vue +136 -57
  124. package/src/plugins/components/PluginDeveloperArea.vue +192 -0
  125. package/src/plugins/components/PluginDocumentSlot.vue +63 -0
  126. package/src/plugins/components/PluginExplorer.vue +21 -25
  127. package/src/plugins/components/PluginImportDialog.vue +410 -0
  128. package/src/plugins/components/PluginInstaller.vue +273 -288
  129. package/src/plugins/components/PluginListItem.vue +3 -0
  130. package/src/plugins/components/PluginMaintenance.vue +37 -34
  131. package/src/plugins/components/PluginRepositoryStorage.vue +4 -2
  132. package/src/plugins/components/PluginRuntimePanel.vue +3 -3
  133. package/src/plugins/components/PluginSettingsForm.vue +112 -0
  134. package/src/plugins/components/PluginStatusBar.vue +161 -0
  135. package/src/plugins/components/PluginSurface.vue +18 -6
  136. package/src/plugins/components/PluginUiDialog.vue +452 -0
  137. package/src/plugins/components/PluginsTabPage.vue +61 -0
  138. package/src/plugins/components/plugin-center.css +5 -0
  139. package/src/plugins/data.ts +9 -86
  140. package/src/plugins/editor-plugin-adapters.ts +169 -0
  141. package/src/plugins/excalidraw/bundle.tano-plugin.json +1 -1
  142. package/src/plugins/excalidraw/manifest.json +12 -1
  143. package/src/plugins/host.ts +662 -43
  144. package/src/plugins/native.ts +2 -10
  145. package/src/plugins/overlay-mapping.ts +125 -0
  146. package/src/plugins/packages.ts +73 -1
  147. package/src/plugins/plugin-data.ts +2 -3
  148. package/src/plugins/plugin-permissions.ts +57 -0
  149. package/src/plugins/plugin-rpc-router.ts +558 -0
  150. package/src/plugins/plugin-sdk.ts +1 -94
  151. package/src/plugins/plugin-ui-dialogs.ts +167 -0
  152. package/src/plugins/policy.ts +53 -3
  153. package/src/plugins/presentation-preview/bundle.tano-plugin.json +1 -1
  154. package/src/plugins/presentation-preview/manifest.json +2 -1
  155. package/src/plugins/queries.ts +1 -73
  156. package/src/plugins/sandbox.ts +15 -1
  157. package/src/plugins/use-plugin-actions.ts +67 -20
  158. package/src/plugins/user-plugins.ts +254 -0
  159. package/src/plugins/view-header.ts +2 -7
  160. package/src/plugins/word-preview/bundle.tano-plugin.json +1 -1
  161. package/src/plugins/word-preview/manifest.json +13 -1
  162. package/src/plugins/workbench.ts +175 -2
  163. package/src/plugins/worker.js +105 -8
  164. package/src/plugins/workspace-plugin-runtime.ts +23 -7
  165. package/src/plugins/workspace-plugins.ts +212 -21
  166. package/src/runtime.ts +103 -4
  167. package/src/settings/components/SettingsAppearancePage.vue +46 -0
  168. package/src/settings/components/SettingsDocumentsPage.vue +0 -1
  169. package/src/settings/components/SettingsPanel.vue +8 -3
  170. package/src/settings/components/WorkbenchSettings.vue +20 -7
  171. package/src/settings/components/settings-context.ts +1 -1
  172. package/src/settings/components/settings-search.ts +2 -3
  173. package/src/settings/settings-tab.ts +1 -0
  174. package/src/shell/command-palette.ts +3 -3
  175. package/src/shell/components/EditorToolbar.vue +8 -9
  176. package/src/shell/components/EditorTools.vue +1 -5
  177. package/src/shell/components/PaneTopbar.vue +393 -0
  178. package/src/shell/components/SelectionToolbar.vue +0 -2
  179. package/src/shell/components/SidebarNavigation.vue +22 -2
  180. package/src/shell/components/WorkbenchContextMenus.vue +58 -34
  181. package/src/shell/components/WorkbenchModals.vue +47 -62
  182. package/src/shell/components/WorkbenchPanes.vue +371 -1342
  183. package/src/shell/components/WorkbenchSidebar.vue +486 -0
  184. package/src/shell/components/WorkspaceBreadcrumb.vue +6 -14
  185. package/src/shell/components/WorkspaceViewSwitcher.vue +12 -7
  186. package/src/shell/pane-registry.ts +69 -0
  187. package/src/shell/use-surface-dismissal.ts +219 -0
  188. package/src/shell/use-workbench-commands.ts +599 -0
  189. package/src/shell/use-workbench-keybindings.ts +337 -0
  190. package/src/shell/use-workbench.ts +531 -1153
  191. package/src/shell/workbench-async-components.ts +14 -5
  192. package/src/shell/workbench-context.ts +30 -3
  193. package/src/stores/mail.ts +414 -0
  194. package/src/stores/plan-sync.ts +2 -1
  195. package/src/stores/plans.ts +2 -9
  196. package/src/stores/workspace-document-io.ts +807 -0
  197. package/src/stores/workspace-file-ops.ts +1 -1
  198. package/src/stores/workspace-knowledge.ts +2 -114
  199. package/src/stores/workspace-lifecycle.ts +459 -0
  200. package/src/stores/workspace-plugins-state.ts +254 -259
  201. package/src/stores/workspace-session.ts +287 -0
  202. package/src/stores/workspace-tabs-layout.ts +6 -44
  203. package/src/stores/workspace-types.ts +50 -0
  204. package/src/stores/workspace.ts +184 -1363
  205. package/src/styles/agent-diff-modals.css +0 -7
  206. package/src/styles/dark-theme.css +3 -3
  207. package/src/styles/inspector.css +0 -59
  208. package/src/styles/layout-themes.css +346 -0
  209. package/src/styles/mail.css +1568 -0
  210. package/src/styles/mobile.css +2 -2
  211. package/src/styles/recent-and-media.css +0 -17
  212. package/src/styles/theme-contract.css +3 -3
  213. package/src/styles/workbench-shell.css +110 -17
  214. package/src/styles/workspace-states.css +9 -33
  215. package/src/styles.css +0 -1
  216. package/src/tabs/components/DesktopTabs.vue +19 -14
  217. package/src/tabs/components/NewTabPicker.vue +10 -4
  218. package/src/tabs/tab-label.ts +0 -1
  219. package/src/windows/AuxiliaryWindows.vue +2 -2
  220. package/src/windows/use-window-event-bridge.ts +152 -0
  221. package/src/workspace/components/TemplateLibrary.vue +1 -1
  222. package/src/workspace/components/WorkspaceGeneralSettings.vue +0 -13
  223. package/src/workspace/components/WorkspaceIconPicker.vue +30 -7
  224. package/src/workspace/components/WorkspacePickerMenu.vue +317 -0
  225. package/src/workspace/workspace-comments.ts +11 -151
  226. package/src/workspace/workspace-welcome.ts +1 -1
  227. package/src/assistant/locales/de-DE.json +0 -126
  228. package/src/assistant/locales/en-US.json +0 -126
  229. package/src/assistant/locales/es-ES.json +0 -126
  230. package/src/assistant/locales/ja-JP.json +0 -126
  231. package/src/assistant/locales/zh-CN.json +0 -126
  232. package/src/assistant/locales/zh-TW.json +0 -126
  233. package/src/assistant/task-prompts.json +0 -39
  234. package/src/documents/components/FormulaMenu.vue +0 -50
  235. package/src/files/components/FileDatabasePage.vue +0 -152
  236. package/src/files/components/FolderHomeIcon.vue +0 -12
  237. package/src/objects/components/ObjectDatabasePage.vue +0 -100
  238. package/src/objects/components/ObjectPanel.vue +0 -554
  239. package/src/plans/components/PersonalPlanDialog.vue +0 -105
  240. package/src/shell/components/WorkspaceViewPage.vue +0 -127
  241. package/src/shell/components/WorkspaceViewTab.vue +0 -24
  242. package/src/styles/object-panel.css +0 -163
  243. package/src/workspace/components/GitInspectionPanel.vue +0 -35
  244. package/src/workspace/components/WorkspaceSyncPanel.vue +0 -50
  245. package/src/workspace/welcome-slogans.ts +0 -11
  246. package/src/workspace/workspace-git.ts +0 -35
  247. package/src/workspace/workspace-sync.ts +0 -46
  248. package/src/workspace/workspace-views.ts +0 -48
@@ -1,5 +1,44 @@
1
- import { canonicalPluginJson, parsePluginView, parsePluginJson, parsePluginSettings, pluginKey, pluginRecord, pluginText, pluginStorageLimit } from '@tano/protocol';
2
- import type { ExecutablePluginManifest, PluginCommandDefinition, PluginViewDefinition, PluginPermission, PluginViewNode, PluginJson, PluginUiBundle, Workspace } from '@tano/protocol';
1
+ import {
2
+ canonicalPluginJson,
3
+ checkPluginCompatibility,
4
+ classifyPluginError,
5
+ parsePluginAiRequest,
6
+ parsePluginEditorDecorations,
7
+ parsePluginFrontmatterPatch,
8
+ parsePluginStatusBarItem,
9
+ parsePluginUiConfirmOptions,
10
+ parsePluginUiPickOptions,
11
+ parsePluginUiPromptOptions,
12
+ parsePluginUiToastOptions,
13
+ parsePluginView,
14
+ parsePluginJson,
15
+ pluginAssistantContextMaxBytes,
16
+ pluginKey,
17
+ pluginRecord,
18
+ pluginText,
19
+ pluginStorageLimit,
20
+ resolvePluginSettingsWithDefaults,
21
+ TANO_PLUGIN_API_VERSION,
22
+ validateAgainstPluginJsonSchema,
23
+ } from '@tano/protocol';
24
+ import { patchFrontmatterMarkdown, readFrontmatterData } from '@tano/protocol/frontmatter';
25
+ import type {
26
+ ExecutablePluginManifest,
27
+ PluginAssistantContextProviderDefinition,
28
+ PluginAssistantToolDefinition,
29
+ PluginCommandDefinition,
30
+ PluginEditorDecoration,
31
+ PluginHostEnvironment,
32
+ PluginStatusBarItem,
33
+ PluginViewDefinition,
34
+ PluginPermission,
35
+ PluginViewNode,
36
+ PluginJson,
37
+ PluginUiBundle,
38
+ Workspace,
39
+ WorkspacePersonalPluginPolicy,
40
+ } from '@tano/protocol';
41
+ import workbenchPackage from '../../package.json';
3
42
  import type { InstalledObjectPlugin } from './workspace-plugins';
4
43
  import { PluginPackageCache, fetchPluginText, pluginApplicationStorage, type PluginPackageRepository } from './packages';
5
44
  import { createPluginSandbox, type PluginSandbox, type PluginSandboxFactory } from './sandbox';
@@ -12,6 +51,7 @@ import { parsePluginConnectionRequest, pluginConnectionOrigin, type PluginConnec
12
51
 
13
52
  export interface PluginRuntimeServices {
14
53
  principal?: string;
54
+ host?: PluginHostEnvironment;
15
55
  repository?: PluginPackageRepository;
16
56
  catalog?: PluginCatalogProvider;
17
57
  connections?: PluginConnectionProvider;
@@ -22,9 +62,14 @@ export interface PluginRuntimeServices {
22
62
  }
23
63
  export interface PluginNativeContext { workspaceId: string; pluginId: string; integrity: string; signal: AbortSignal }
24
64
  export interface PluginRuntimeState {
25
- id: string; instanceId: string; name: string; status: 'loading' | 'running' | 'blocked' | 'error'; message: string;
65
+ id: string; instanceId: string; name: string; status: 'idle' | 'loading' | 'running' | 'blocked' | 'error'; message: string;
26
66
  commands: PluginCommandDefinition[];
27
67
  views: (PluginViewDefinition & { header?: PluginViewHeader; tree?: PluginViewNode; custom?: { bundle: PluginUiBundle; state: PluginJson } })[];
68
+ assistantTools?: PluginAssistantToolDefinition[];
69
+ assistantContextProviders?: PluginAssistantContextProviderDefinition[];
70
+ statusBar?: PluginStatusBarItem[];
71
+ decorations?: Record<string, PluginEditorDecoration[]>;
72
+ uiBundles?: Record<string, PluginUiBundle>;
28
73
  logs?: { time: string; level: 'info' | 'warn' | 'error'; message: string }[];
29
74
  }
30
75
  export interface PluginAccess {
@@ -33,23 +78,46 @@ export interface PluginAccess {
33
78
  interface Session {
34
79
  stamp: string; integrity: string; state: PluginRuntimeState; manifest: ExecutablePluginManifest; controller: AbortController;
35
80
  sandbox?: PluginSandbox; timer?: ReturnType<typeof setTimeout>; inFlight: number;
36
- invocation: number; pending: Map<number, { resolve: () => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }>;
81
+ invocation: number; pending: Map<number, { resolve: (value?: unknown) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }>;
37
82
  reads: Map<string, unknown>; storage: string; seen: Set<number>; windowStart: number; calls: number;
38
83
  ui?: Record<string, PluginUiBundle>;
84
+ start?: () => void;
85
+ readyWaiters: { resolve: () => void; reject: (error: Error) => void }[];
86
+ activeDialog: boolean;
87
+ activeAiCall: boolean;
88
+ registeredServices: Set<string>;
89
+ serviceCallDepth: number;
90
+ scope?: 'system' | 'workspace' | 'user';
91
+ personalCodePolicy?: WorkspacePersonalPluginPolicy;
92
+ pathScopes?: string[];
39
93
  }
94
+ const writePermissions = new Set<PluginPermission>([
95
+ 'attachments.write',
96
+ 'documents.write',
97
+ 'documents.move',
98
+ 'documents.trash',
99
+ 'objects.write',
100
+ 'relations.write',
101
+ ]);
40
102
  const permissions: Record<string, PluginPermission> = {
41
103
  'views.setHeader': 'ui',
42
104
  'attachments.read': 'attachments.read',
105
+ 'attachments.write': 'attachments.write',
43
106
  'views.renderCustom': 'ui',
44
107
  'documents.list': 'documents.read', 'documents.read': 'documents.read', 'documents.open': 'documents.read',
45
108
  'documents.write': 'documents.write', 'documents.create': 'documents.write',
109
+ 'documents.move': 'documents.move', 'documents.trash': 'documents.trash',
46
110
  'documents.query': 'documents.read', 'documents.search': 'documents.read', 'documents.edit': 'documents.write',
111
+ 'documents.frontmatter.read': 'documents.read', 'documents.frontmatter.update': 'documents.write',
112
+ 'editor.active': 'documents.read', 'editor.insert': 'documents.write', 'editor.replaceSelection': 'documents.write',
113
+ 'editor.setDecorations': 'documents.read', 'editor.clearDecorations': 'documents.read',
47
114
  'objects.query': 'objects.read', 'relations.query': 'relations.read',
48
115
  'objects.list': 'objects.read', 'objects.read': 'objects.read', 'objects.create': 'objects.write', 'objects.update': 'objects.write',
49
116
  'relations.list': 'relations.read', 'relations.add': 'relations.write', 'relations.remove': 'relations.write',
50
117
  'storage.get': 'storage', 'storage.set': 'storage', 'network.get': 'network', 'native.invoke': 'native',
51
118
  'storage.remove': 'storage', 'storage.usage': 'storage',
52
119
  'connections.request': 'connections',
120
+ 'ai.complete': 'ai.invoke', 'ai.structured': 'ai.invoke',
53
121
  };
54
122
  export class PluginExecutionHost {
55
123
  private workspace = '';
@@ -58,7 +126,23 @@ export class PluginExecutionHost {
58
126
  constructor(private access: PluginAccess, private changed: (states: PluginRuntimeState[]) => void,
59
127
  private services: PluginRuntimeServices = {}, private storage: Pick<Storage, 'getItem' | 'setItem'> = pluginApplicationStorage(),
60
128
  private factory: PluginSandboxFactory = createPluginSandbox) {}
61
- private publish() { this.changed([...this.sessions.values()].map(session => ({ ...session.state, logs: [...(this.logs.get(session.manifest.id) ?? [])], commands: [...session.state.commands], views: [...session.state.views] }))); }
129
+ private publish() {
130
+ this.changed(
131
+ [...this.sessions.values()].map(session => ({
132
+ ...session.state,
133
+ logs: [...(this.logs.get(session.manifest.id) ?? [])],
134
+ commands: [...session.state.commands],
135
+ views: [...session.state.views],
136
+ assistantTools: [...(session.state.assistantTools ?? [])],
137
+ assistantContextProviders: [...(session.state.assistantContextProviders ?? [])],
138
+ statusBar: [...(session.state.statusBar ?? [])],
139
+ decorations: session.state.decorations
140
+ ? Object.fromEntries(Object.entries(session.state.decorations).map(([k, v]) => [k, [...v]]))
141
+ : undefined,
142
+ uiBundles: session.state.uiBundles ? { ...session.state.uiBundles } : undefined,
143
+ })),
144
+ );
145
+ }
62
146
  private log(session: Session, level: 'info' | 'warn' | 'error', message: unknown) {
63
147
  const entries = this.logs.get(session.manifest.id) ?? [];
64
148
  entries.push({ time: new Date().toISOString(), level, message: String(message).slice(0, 1500) });
@@ -70,45 +154,200 @@ export class PluginExecutionHost {
70
154
  const key = `tano.plugin-data.v1.${encodeURIComponent(this.services.principal ?? 'device')}.${encodeURIComponent(workspaceId)}.${pluginId}`;
71
155
  return { used: new TextEncoder().encode(this.storage.getItem(key) ?? '{}').length, limit: pluginStorageLimit };
72
156
  }
73
- private stop(session: Session) {
74
- session.controller.abort(); clearTimeout(session.timer); session.sandbox?.dispose();
157
+ private hostEnvironment(): PluginHostEnvironment {
158
+ return this.services.host ?? { coreVersion: workbenchPackage.version, platform: 'web' };
159
+ }
160
+ private hostCapabilities(): string[] {
161
+ return [
162
+ 'documents',
163
+ 'documents.frontmatter',
164
+ 'documents.move',
165
+ 'documents.trash',
166
+ 'editor.active',
167
+ 'editor.insert',
168
+ 'editor.replaceSelection',
169
+ 'editor.slashCommands',
170
+ 'editor.decorations',
171
+ 'editor.codeBlockRenderers',
172
+ 'objects',
173
+ 'relations',
174
+ 'attachments.read',
175
+ 'attachments.write',
176
+ 'security.pathScopes',
177
+ 'security.personalCodePlugins',
178
+ 'ai.invoke',
179
+ 'assistant.tools',
180
+ 'assistant.contextProviders',
181
+ 'services.rpc',
182
+ 'package.v2.zip',
183
+ 'assets.binary',
184
+ 'views.homeTab',
185
+ 'views.newTab',
186
+ 'ui',
187
+ 'ui.dialogs',
188
+ 'ui.statusBar',
189
+ 'views.documentSidebar',
190
+ 'views.documentHeader',
191
+ 'views.documentFooter',
192
+ 'fileHandlers',
193
+ 'settingsSchema',
194
+ 'activationEvents',
195
+ 'lifecycle.deactivate',
196
+ 'storage',
197
+ 'network',
198
+ ...(this.services.connections ? ['connections'] : []),
199
+ ...(this.services.connections?.oauth ? ['oauth'] : []),
200
+ ...(this.services.automations ? ['automations'] : []),
201
+ ...Object.keys(this.services.native ?? {}).map(command => `native:${command}`),
202
+ ];
203
+ }
204
+ private settleWaiters(session: Session, error?: Error) {
205
+ const waiters = session.readyWaiters.splice(0);
206
+ for (const waiter of waiters) if (error) waiter.reject(error); else waiter.resolve();
207
+ }
208
+ private stop(session: Session, graceful = true) {
209
+ const wasRunning = session.state.status === 'running';
210
+ session.activeDialog = false;
211
+ session.activeAiCall = false;
212
+ session.registeredServices.clear();
213
+ session.serviceCallDepth = 0;
214
+ session.controller.abort(); clearTimeout(session.timer);
215
+ if (graceful && wasRunning && session.sandbox?.gracefulDispose) session.sandbox.gracefulDispose();
216
+ else session.sandbox?.dispose();
217
+ this.settleWaiters(session, new Error('插件已停止'));
75
218
  for (const pending of session.pending.values()) { clearTimeout(pending.timer); pending.reject(new Error('插件已停止')); }
76
- session.pending.clear(); session.state.commands = []; session.state.views = []; session.reads.clear();
219
+ session.pending.clear(); session.state.commands = []; session.state.views = []; session.state.assistantTools = []; session.state.assistantContextProviders = []; session.state.statusBar = [];
220
+ session.state.decorations = undefined; session.state.uiBundles = undefined; session.reads.clear();
77
221
  }
78
222
  dispose() { for (const session of this.sessions.values()) this.stop(session); this.sessions.clear(); this.logs.clear(); this.workspace = ''; this.publish(); }
79
223
  invalidate(id: string) { const session = this.sessions.get(id); if (session) this.stop(session); this.sessions.delete(id); this.publish(); }
80
- sync(workspace: Workspace, plugins: InstalledObjectPlugin[]) {
224
+ private activateSession(session: Session, workspaceId: string, installation: InstalledObjectPlugin, rule: NonNullable<InstalledObjectPlugin['rule']>) {
225
+ if (session.controller.signal.aborted || session.state.status === 'loading' || session.state.status === 'running') return;
226
+ session.state.status = 'loading'; session.state.message = '正在校验并加载';
227
+ // Clear pre-populated idle commands so the running plugin explicitly registers its live handlers.
228
+ session.state.commands = [];
229
+ session.state.assistantTools = [];
230
+ session.state.assistantContextProviders = [];
231
+ this.publish();
232
+ const fail = (message: string) => {
233
+ if (session.controller.signal.aborted) return;
234
+ this.stop(session, false); session.state.status = 'error'; session.state.message = message.slice(0, 1000); this.log(session, 'error', message);
235
+ };
236
+ session.timer = setTimeout(() => fail('插件启动超时,已停止运行'), 15000);
237
+ const packageSource = installation.system ? resolveSystemPlugin(rule)
238
+ : new PluginPackageCache(this.storage).resolve(
239
+ workspaceId,
240
+ rule,
241
+ session.controller.signal,
242
+ installation.scope === 'user' ? undefined : this.services.repository,
243
+ );
244
+ void packageSource.then(pkg => {
245
+ if (session.controller.signal.aborted) return;
246
+ session.ui = pkg.ui;
247
+ session.state.uiBundles = pkg.ui ? { ...pkg.ui } : undefined;
248
+ session.sandbox = this.factory(pkg.source!, message => this.receive(session, workspaceId, rule.settings, message, fail), fail);
249
+ }).catch(error => fail(String(error)));
250
+ }
251
+ ensureActivated(pluginId: string): Promise<void> {
252
+ const session = this.sessions.get(pluginId);
253
+ if (!session) return Promise.reject(new Error('插件尚未运行'));
254
+ if (session.state.status === 'running') return Promise.resolve();
255
+ if (session.state.status === 'idle' && session.start) {
256
+ const start = session.start;
257
+ session.start = undefined;
258
+ return new Promise<void>((resolve, reject) => {
259
+ session.readyWaiters.push({ resolve, reject });
260
+ start();
261
+ });
262
+ }
263
+ if (session.state.status === 'loading') {
264
+ return new Promise<void>((resolve, reject) => { session.readyWaiters.push({ resolve, reject }); });
265
+ }
266
+ return Promise.reject(new Error(session.state.message || '插件尚未运行'));
267
+ }
268
+ sync(workspace: Workspace, plugins: InstalledObjectPlugin[], safeMode = false) {
81
269
  const scope = `${workspace.id}:${workspace.path}`;
82
270
  if (this.workspace !== scope) { this.dispose(); this.workspace = scope; }
83
271
  const active = new Set<string>();
272
+ const hostEnv = this.hostEnvironment();
84
273
  for (const installation of plugins) {
85
274
  const { manifest, rule } = installation;
86
275
  if (manifest.manifestVersion !== 2 || !installation.enabled || !rule) continue;
87
276
  active.add(manifest.id);
88
- const stamp = canonicalPluginJson([rule, installation.authorized, workspace.readOnly]);
277
+ const pathScopes = installation.pathScopes ?? rule.pathScopes;
278
+ const stamp = canonicalPluginJson([
279
+ rule,
280
+ installation.authorized,
281
+ installation.scope,
282
+ installation.personalCodePolicy,
283
+ pathScopes,
284
+ workspace.readOnly,
285
+ hostEnv,
286
+ safeMode && !installation.system,
287
+ ]);
89
288
  if (this.sessions.get(manifest.id)?.stamp === stamp) continue;
90
289
  const prior = this.sessions.get(manifest.id); if (prior) this.stop(prior);
91
- const session: Session = { stamp, integrity: rule.integrity ?? '', manifest, controller: new AbortController(), inFlight: 0, invocation: 0, pending: new Map(), reads: new Map(), seen: new Set(), windowStart: Date.now(), calls: 0,
290
+ const safeBlocked = safeMode && !installation.system;
291
+ const session: Session = {
292
+ stamp,
293
+ integrity: rule.integrity ?? '',
294
+ manifest,
295
+ controller: new AbortController(),
296
+ inFlight: 0,
297
+ invocation: 0,
298
+ pending: new Map(),
299
+ reads: new Map(),
300
+ seen: new Set(),
301
+ windowStart: Date.now(),
302
+ calls: 0,
303
+ readyWaiters: [],
304
+ activeDialog: false,
305
+ activeAiCall: false,
306
+ registeredServices: new Set(),
307
+ serviceCallDepth: 0,
308
+ scope: installation.scope,
309
+ personalCodePolicy: installation.personalCodePolicy,
310
+ pathScopes: pathScopes?.length ? [...pathScopes] : undefined,
92
311
  storage: `tano.plugin-data.v1.${encodeURIComponent(this.services.principal ?? 'device')}.${encodeURIComponent(workspace.id)}.${manifest.id}`,
93
- state: { id: manifest.id, instanceId: crypto.randomUUID(), name: manifest.name, status: 'blocked', message: '等待此设备授权', commands: [], views: [] } };
312
+ state: {
313
+ id: manifest.id,
314
+ instanceId: crypto.randomUUID(),
315
+ name: manifest.name,
316
+ status: 'blocked',
317
+ message: safeBlocked
318
+ ? '安全模式已启用,已跳过第三方代码插件'
319
+ : installation.scope === 'user' && installation.personalCodePolicy === 'block'
320
+ ? '此工作区管理员策略禁止个人代码插件访问工作区数据'
321
+ : '等待此设备授权',
322
+ commands: [],
323
+ views: [],
324
+ assistantTools: [],
325
+ assistantContextProviders: [],
326
+ statusBar: [],
327
+ },
328
+ };
94
329
  this.sessions.set(manifest.id, session);
330
+ if (safeBlocked) continue;
331
+ if (installation.scope === 'user' && installation.personalCodePolicy === 'block') continue;
95
332
  if (!installation.authorized) continue;
333
+ const compatibility = checkPluginCompatibility(manifest, hostEnv);
334
+ if (!compatibility.compatible) {
335
+ session.state.message = compatibility.reason ?? '当前运行环境不兼容此插件'; continue;
336
+ }
96
337
  if (manifest.nativeCommands.some(command => !this.services.native || !Object.hasOwn(this.services.native, command))) {
97
338
  session.state.message = '当前运行环境不提供此插件要求的本机能力'; continue;
98
339
  }
99
- session.state.status = 'loading'; session.state.message = '正在校验并加载';
100
- const fail = (message: string) => {
101
- if (session.controller.signal.aborted) return;
102
- this.stop(session); session.state.status = 'error'; session.state.message = message.slice(0, 1000); this.log(session, 'error', message);
103
- };
104
- session.timer = setTimeout(() => fail('插件启动超时,已停止运行'), 15000);
105
- const packageSource = installation.system ? resolveSystemPlugin(rule)
106
- : new PluginPackageCache(this.storage).resolve(workspace.id, rule, session.controller.signal, this.services.repository);
107
- void packageSource.then(pkg => {
108
- if (session.controller.signal.aborted) return;
109
- session.ui = pkg.ui;
110
- session.sandbox = this.factory(pkg.source!, message => this.receive(session, workspace.id, rule.settings, message, fail), fail);
111
- }).catch(error => fail(String(error)));
340
+ const lazy = !!manifest.activationEvents?.length && !manifest.activationEvents.includes('onStartup');
341
+ if (lazy) {
342
+ session.state.status = 'idle';
343
+ session.state.message = '按需激活(等待触发)';
344
+ session.state.commands = [...manifest.commands];
345
+ session.state.assistantTools = [...(manifest.assistantTools ?? [])];
346
+ session.state.assistantContextProviders = [...(manifest.assistantContextProviders ?? [])];
347
+ session.start = () => this.activateSession(session, workspace.id, installation, rule);
348
+ continue;
349
+ }
350
+ this.activateSession(session, workspace.id, installation, rule);
112
351
  }
113
352
  for (const [id, session] of this.sessions) if (!active.has(id)) { this.stop(session); this.sessions.delete(id); }
114
353
  this.publish();
@@ -122,12 +361,12 @@ export class PluginExecutionHost {
122
361
  if (++session.calls > 200) { fail('插件消息超过资源限制,已停止运行'); return; }
123
362
  try { if (JSON.stringify(message).length > 600 * 1024) throw new Error(); }
124
363
  catch { fail('插件消息格式无效或超过大小限制,已停止运行'); return; }
125
- if (message.type === 'ready') { clearTimeout(session.timer); session.state.status = 'running'; session.state.message = ''; this.log(session, 'info', `已启动 ${session.manifest.version}`); return; }
364
+ if (message.type === 'ready') { clearTimeout(session.timer); session.state.status = 'running'; session.state.message = ''; this.settleWaiters(session); this.log(session, 'info', `已启动 ${session.manifest.version}`); return; }
126
365
  if (message.type === 'failed') { fail(String(message.error)); return; }
127
366
  if (message.type === 'log') { this.log(session, message.level === 'warn' ? 'warn' : message.level === 'info' ? 'info' : 'error', message.message ?? message.error); return; }
128
367
  if (message.type === 'invoked') {
129
368
  const pending = session.pending.get(Number(message.id));
130
- if (pending) { clearTimeout(pending.timer); session.pending.delete(Number(message.id)); if (message.error) { this.log(session, 'error', message.error); pending.reject(new Error(String(message.error))); } else pending.resolve(); }
369
+ if (pending) { clearTimeout(pending.timer); session.pending.delete(Number(message.id)); if (message.error) { this.log(session, 'error', message.error); pending.reject(new Error(String(message.error))); } else pending.resolve(message.result); }
131
370
  return;
132
371
  }
133
372
  if (message.type !== 'call' || !Number.isSafeInteger(message.id) || typeof message.method !== 'string' || !pluginRecord(message.params)) return;
@@ -139,22 +378,129 @@ export class PluginExecutionHost {
139
378
  void this.dispatch(session, workspaceId, settings, message.method, message.params).then(result => {
140
379
  this.assert(session); session.sandbox?.send({ type: 'result', id, result });
141
380
  }).catch(error => {
142
- if (!session.controller.signal.aborted) { this.log(session, 'error', `${message.method}: ${String(error)}`); session.sandbox?.send({ type: 'result', id, error: String(error) }); }
381
+ if (!session.controller.signal.aborted) {
382
+ const classified = classifyPluginError(error);
383
+ this.log(session, 'error', `${message.method}: ${classified.message}`);
384
+ session.sandbox?.send({ type: 'result', id, error: classified.message, code: classified.code, retryable: classified.retryable });
385
+ }
143
386
  }).finally(() => { session.inFlight--; });
144
387
  }
145
388
  private async dispatch(session: Session, workspaceId: string, settings: Record<string, unknown>, method: string, params: Record<string, unknown>) {
146
389
  this.assert(session);
147
390
  const permission = permissions[method];
148
391
  if (permission && !session.manifest.permissions.includes(permission)) throw new Error(`插件没有 ${permission} 权限`);
392
+ if (session.scope === 'user' && session.personalCodePolicy === 'read-only' && permission && writePermissions.has(permission))
393
+ throw new Error('此工作区管理员策略仅允许个人代码插件只读访问');
149
394
  // Workspace rules can be reactive Vue state. MessagePort requires plain data,
150
395
  // and plugins must receive a detached settings snapshot rather than host state.
151
- if (method === 'context') return { workspaceId, pluginId: session.manifest.id, settings: parsePluginSettings(settings) };
396
+ if (method === 'context') {
397
+ return {
398
+ workspaceId,
399
+ pluginId: session.manifest.id,
400
+ settings: resolvePluginSettingsWithDefaults(settings, session.manifest.settingsSchema),
401
+ };
402
+ }
403
+ if (method === 'hostInfo') {
404
+ const env = this.hostEnvironment();
405
+ return {
406
+ coreVersion: env.coreVersion,
407
+ apiVersion: TANO_PLUGIN_API_VERSION,
408
+ platform: env.platform,
409
+ capabilities: this.hostCapabilities(),
410
+ };
411
+ }
152
412
  if (method === 'commands.register') {
153
413
  const command = session.manifest.commands.find(item => item.id === params.id);
154
414
  if (!command) throw new Error('命令没有在清单中声明');
155
415
  if (!session.state.commands.some(item => item.id === command.id)) session.state.commands.push(command);
156
416
  this.publish(); return null;
157
417
  }
418
+ if (method === 'assistant.registerTool') {
419
+ const tool = session.manifest.assistantTools?.find(item => item.name === params.name);
420
+ if (!tool) throw new Error('助手工具没有在清单中声明');
421
+ const list = session.state.assistantTools ?? [];
422
+ if (!list.some(item => item.name === tool.name)) session.state.assistantTools = [...list, tool];
423
+ this.publish(); return null;
424
+ }
425
+ if (method === 'assistant.registerContextProvider') {
426
+ const provider = session.manifest.assistantContextProviders?.find(item => item.id === params.id);
427
+ if (!provider) throw new Error('助手上下文提供者没有在清单中声明');
428
+ const list = session.state.assistantContextProviders ?? [];
429
+ if (!list.some(item => item.id === provider.id)) session.state.assistantContextProviders = [...list, provider];
430
+ this.publish(); return null;
431
+ }
432
+ if (method === 'services.register') {
433
+ const serviceDef = session.manifest.services?.find(item => item.name === params.name);
434
+ if (!serviceDef) throw new Error('插件服务没有在清单中声明');
435
+ session.registeredServices.add(serviceDef.name);
436
+ return null;
437
+ }
438
+ if (method === 'services.available') {
439
+ const targetId = String(params.pluginId ?? '');
440
+ const serviceName = String(params.service ?? '');
441
+ const declaredDep = session.manifest.usesServices?.some(
442
+ dep => dep.pluginId === targetId && dep.service === serviceName,
443
+ );
444
+ if (!declaredDep) throw new Error('目标插件服务未在清单 usesServices 中声明');
445
+ const target = this.sessions.get(targetId);
446
+ if (!target || (target.state.status !== 'running' && target.state.status !== 'idle')) return false;
447
+ return !!target.manifest.services?.some(item => item.name === serviceName);
448
+ }
449
+ if (method === 'services.call') {
450
+ const targetId = String(params.pluginId ?? '');
451
+ const serviceName = String(params.service ?? '');
452
+ const declaredDep = session.manifest.usesServices?.some(
453
+ dep => dep.pluginId === targetId && dep.service === serviceName,
454
+ );
455
+ if (!declaredDep) throw new Error('目标插件服务未在清单 usesServices 中声明');
456
+ if (targetId === session.manifest.id) throw new Error('不能通过跨插件服务总线递归调用自身');
457
+ if (session.serviceCallDepth >= 4) throw new Error('跨插件服务调用深度超过限制(可能存在循环依赖)');
458
+ let target = this.sessions.get(targetId);
459
+ if (!target || target.state.status === 'blocked' || target.state.status === 'error') {
460
+ throw new Error(`服务提供方插件 ${targetId} 未启用或未授权`);
461
+ }
462
+ const serviceDef = target.manifest.services?.find(item => item.name === serviceName);
463
+ if (!serviceDef) throw new Error(`插件 ${targetId} 未声明服务 ${serviceName}`);
464
+ const payload = parsePluginJson(params.payload ?? null, 64 * 1024);
465
+ if (serviceDef.parameters) {
466
+ validateAgainstPluginJsonSchema(payload, serviceDef.parameters);
467
+ }
468
+ if (target.state.status === 'idle' || target.state.status === 'loading') {
469
+ await this.ensureActivated(targetId);
470
+ this.assert(session);
471
+ target = this.sessions.get(targetId);
472
+ if (!target || target.state.status !== 'running') {
473
+ throw new Error(`服务提供方插件 ${targetId} 激活失败`);
474
+ }
475
+ }
476
+ if (target.pending.size >= 32) throw new Error('目标插件服务请求过多,请稍后重试');
477
+ const id = ++target.invocation;
478
+ target.serviceCallDepth = Math.max(target.serviceCallDepth, session.serviceCallDepth + 1);
479
+ try {
480
+ const raw = await new Promise<unknown>((resolve, reject) => {
481
+ const timer = setTimeout(() => {
482
+ target!.pending.delete(id);
483
+ reject(new Error(`跨插件服务 ${targetId}.${serviceName} 调用超时`));
484
+ }, 15000);
485
+ target!.pending.set(id, { resolve, reject, timer });
486
+ target!.sandbox?.send({
487
+ type: 'invoke',
488
+ id,
489
+ kind: 'service',
490
+ name: serviceName,
491
+ payload: { args: payload, callerPluginId: session.manifest.id },
492
+ });
493
+ });
494
+ this.assert(session);
495
+ const result = parsePluginJson(raw ?? null, 64 * 1024);
496
+ if (serviceDef.returns) {
497
+ validateAgainstPluginJsonSchema(result, serviceDef.returns);
498
+ }
499
+ return result;
500
+ } finally {
501
+ target.serviceCallDepth = Math.max(0, target.serviceCallDepth - 1);
502
+ }
503
+ }
158
504
  if (method === 'views.render') {
159
505
  const definition = session.manifest.views.find(item => item.id === params.id);
160
506
  if (!definition) throw new Error('视图没有在清单中声明');
@@ -184,6 +530,75 @@ export class PluginExecutionHost {
184
530
  if (!definition) throw new Error('视图没有在清单中声明');
185
531
  return this.access.call('views.open', { pluginId: session.manifest.id, viewId: definition.id }, () => this.assert(session));
186
532
  }
533
+ if (method === 'ui.setStatusBar') {
534
+ const item = parsePluginStatusBarItem(params.item);
535
+ if (item.command && !session.manifest.commands.some(cmd => cmd.id === item.command))
536
+ throw new Error('状态栏绑定的命令没有在清单中声明');
537
+ const existing = session.state.statusBar ?? [];
538
+ const next = [...existing.filter(row => row.id !== item.id), item];
539
+ if (next.length > 4) throw new Error('单个插件最多只能注册 4 个状态栏项');
540
+ session.state.statusBar = next;
541
+ this.publish();
542
+ return null;
543
+ }
544
+ if (method === 'ui.removeStatusBar') {
545
+ if (!pluginKey(params.id)) throw new Error('插件状态栏项 ID 无效');
546
+ session.state.statusBar = (session.state.statusBar ?? []).filter(row => row.id !== params.id);
547
+ this.publish();
548
+ return null;
549
+ }
550
+ if (method === 'ui.toast') {
551
+ const toast = parsePluginUiToastOptions(params);
552
+ session.state.message = toast.message;
553
+ this.publish();
554
+ await this.access.call(
555
+ 'ui.toast',
556
+ { pluginId: session.manifest.id, pluginName: session.manifest.name, message: toast.message, tone: toast.tone },
557
+ () => this.assert(session),
558
+ ).catch(() => {});
559
+ return null;
560
+ }
561
+ if (method === 'ui.pick' || method === 'ui.prompt' || method === 'ui.confirm') {
562
+ const parsedOptions =
563
+ method === 'ui.pick'
564
+ ? parsePluginUiPickOptions(params.options)
565
+ : method === 'ui.prompt'
566
+ ? parsePluginUiPromptOptions(params.options)
567
+ : parsePluginUiConfirmOptions(params.options);
568
+ if (session.activeDialog) throw new Error('已有进行中的交互弹窗,请等待用户完成');
569
+ session.activeDialog = true;
570
+ try {
571
+ const answer = await this.access.call(
572
+ method,
573
+ {
574
+ pluginId: session.manifest.id,
575
+ pluginName: session.manifest.name,
576
+ instanceId: session.state.instanceId,
577
+ options: parsedOptions,
578
+ signal: session.controller.signal,
579
+ },
580
+ () => this.assert(session),
581
+ );
582
+ this.assert(session);
583
+ if (method === 'ui.confirm') return Boolean(answer);
584
+ return typeof answer === 'string' ? answer : null;
585
+ } finally {
586
+ session.activeDialog = false;
587
+ }
588
+ }
589
+ if (method === 'assets.list') {
590
+ const cache = new PluginPackageCache(this.storage);
591
+ return cache.listBinaryAssets(session.integrity);
592
+ }
593
+ if (method === 'assets.read') {
594
+ if (typeof params.path !== 'string' || !params.path.trim()) {
595
+ throw new Error('插件资产路径无效');
596
+ }
597
+ const cache = new PluginPackageCache(this.storage);
598
+ const asset = await cache.getBinaryAsset(session.integrity, params.path);
599
+ if (!asset) throw new Error(`插件包中不存在资产:${params.path}`);
600
+ return asset;
601
+ }
187
602
  if (method === 'notify') {
188
603
  if (!pluginText(params.message, 1000)) throw new Error('插件通知无效');
189
604
  session.state.message = params.message; this.publish(); return null;
@@ -221,7 +636,79 @@ export class PluginExecutionHost {
221
636
  const result = await this.services.native[command](params.args, { workspaceId, pluginId: session.manifest.id, integrity: session.integrity, signal: session.controller.signal });
222
637
  this.assert(session); return parsePluginJson(result, 300 * 1024);
223
638
  }
224
- if (method === 'documents.write' || method === 'documents.edit' || method === 'objects.update') {
639
+ if (method === 'ai.complete' || method === 'ai.structured') {
640
+ const structured = method === 'ai.structured';
641
+ const request = structured
642
+ ? parsePluginAiRequest(params.request, true)
643
+ : parsePluginAiRequest(params.request, false);
644
+ if (session.activeAiCall) throw new Error('插件已有进行中的 AI 推理请求,请等待完成');
645
+ session.activeAiCall = true;
646
+ try {
647
+ const result = await this.access.call(
648
+ method,
649
+ {
650
+ pluginId: session.manifest.id,
651
+ pluginName: session.manifest.name,
652
+ request,
653
+ signal: AbortSignal.any([session.controller.signal, AbortSignal.timeout(60_000)]),
654
+ },
655
+ () => this.assert(session),
656
+ );
657
+ this.assert(session);
658
+ return parsePluginJson(result, 256 * 1024);
659
+ } finally {
660
+ session.activeAiCall = false;
661
+ }
662
+ }
663
+ if (method === 'editor.setDecorations') {
664
+ if (!pluginText(params.fileId, 80)) throw new Error('目标文档 ID 无效');
665
+ const items = parsePluginEditorDecorations(params.decorations);
666
+ for (const item of items) {
667
+ if (item.command && !session.manifest.commands.some(cmd => cmd.id === item.command))
668
+ throw new Error('插件装饰绑定的命令没有在清单中声明');
669
+ }
670
+ const next = { ...(session.state.decorations ?? {}) };
671
+ if (!items.length) delete next[params.fileId];
672
+ else {
673
+ next[params.fileId] = items;
674
+ if (Object.keys(next).length > 20) throw new Error('单个插件最多同时装饰 20 篇文档');
675
+ }
676
+ session.state.decorations = Object.keys(next).length ? next : undefined;
677
+ this.publish();
678
+ return null;
679
+ }
680
+ if (method === 'editor.clearDecorations') {
681
+ if (params.fileId !== undefined) {
682
+ if (!pluginText(params.fileId, 80)) throw new Error('目标文档 ID 无效');
683
+ if (session.state.decorations) {
684
+ const next = { ...session.state.decorations };
685
+ delete next[params.fileId];
686
+ session.state.decorations = Object.keys(next).length ? next : undefined;
687
+ }
688
+ } else {
689
+ session.state.decorations = undefined;
690
+ }
691
+ this.publish();
692
+ return null;
693
+ }
694
+ if (method === 'editor.insert' || method === 'editor.replaceSelection') {
695
+ if (typeof params.text !== 'string' || params.text.length > 200 * 1024)
696
+ throw new Error('编辑器插入文本无效或超过 200 KB 限制');
697
+ params = { text: params.text };
698
+ }
699
+ const frontmatterRead = method === 'documents.frontmatter.read';
700
+ let frontmatterWriteData: Record<string, unknown> | undefined;
701
+ if (frontmatterRead) {
702
+ method = 'documents.read';
703
+ }
704
+ if (
705
+ method === 'documents.write' ||
706
+ method === 'documents.edit' ||
707
+ method === 'documents.frontmatter.update' ||
708
+ method === 'documents.move' ||
709
+ method === 'documents.trash' ||
710
+ method === 'objects.update'
711
+ ) {
225
712
  const key = `${method.startsWith('documents') ? 'document' : 'object'}:${String(params.fileId ?? (pluginRecord(params.object) ? params.object.id : ''))}:${String(params.baseHash)}`;
226
713
  const base = session.reads.get(key);
227
714
  if (!base) throw new Error('请先读取目标内容,再使用返回的版本摘要修改');
@@ -230,9 +717,22 @@ export class PluginExecutionHost {
230
717
  if (!pluginRecord(base) || typeof base.content !== 'string') throw new Error('编辑基线无效');
231
718
  params = { ...params, content: applyPluginTextEdits(base.content, params.edits) };
232
719
  method = 'documents.write';
720
+ } else if (method === 'documents.frontmatter.update') {
721
+ if (!pluginRecord(base) || typeof base.content !== 'string') throw new Error('编辑基线无效');
722
+ const patch = parsePluginFrontmatterPatch(params.patch);
723
+ const patchedContent = patchFrontmatterMarkdown(base.content, patch);
724
+ frontmatterWriteData = readFrontmatterData(patchedContent).data;
725
+ params = { ...params, content: patchedContent };
726
+ method = 'documents.write';
233
727
  }
234
728
  }
235
729
  if (method.endsWith('.query') || method === 'documents.search' || method === 'attachments.read') params = { ...params, queryScope: session.state.instanceId };
730
+ if (
731
+ session.pathScopes?.length &&
732
+ (method.startsWith('documents.') || method.startsWith('editor.') || method.startsWith('attachments.'))
733
+ ) {
734
+ params = { ...params, pathScopes: session.pathScopes };
735
+ }
236
736
  const result = await this.access.call(method, params, () => this.assert(session));
237
737
  this.assert(session);
238
738
  const remember = (kind: string, value: unknown) => {
@@ -240,36 +740,155 @@ export class PluginExecutionHost {
240
740
  session.reads.set(`${kind}:${String(value.id)}:${value.hash}`, value);
241
741
  if (session.reads.size > 32) session.reads.delete(session.reads.keys().next().value!);
242
742
  };
243
- if (method === 'documents.read') remember('document', result);
743
+ if (method === 'documents.read') {
744
+ remember('document', result);
745
+ if (frontmatterRead && pluginRecord(result) && typeof result.content === 'string') {
746
+ const parsed = readFrontmatterData(result.content);
747
+ return {
748
+ id: result.id,
749
+ hasFrontmatter: parsed.hasFrontmatter,
750
+ data: parsed.data,
751
+ hash: result.hash,
752
+ };
753
+ }
754
+ }
755
+ if (frontmatterWriteData !== undefined && pluginRecord(result)) {
756
+ return { ...result, data: frontmatterWriteData };
757
+ }
244
758
  if (method === 'objects.read') remember('object', result);
245
759
  if (method === 'objects.list' && Array.isArray(result)) result.forEach(value => remember('object', value));
246
760
  if (method === 'objects.query' && pluginRecord(result) && Array.isArray(result.items)) result.items.forEach(value => remember('object', value));
247
761
  return result;
248
762
  }
249
- invoke(pluginId: string, kind: 'command' | 'action' | 'message' | 'diagnostic', name: string, payload?: unknown, instanceId?: string) {
250
- const session = this.sessions.get(pluginId);
251
- if (!session || session.state.status !== 'running') return Promise.reject(new Error('插件尚未运行'));
252
- if (instanceId && session.state.instanceId !== instanceId) return Promise.reject(new Error('插件运行版本已变化,请重新打开界面'));
253
- if (session.pending.size >= 32) return Promise.reject(new Error('插件操作过多,请稍后重试'));
763
+ async invoke(pluginId: string, kind: 'command' | 'action' | 'message' | 'diagnostic', name: string, payload?: unknown, instanceId?: string) {
764
+ let session = this.sessions.get(pluginId);
765
+ if (!session) throw new Error('插件尚未运行');
766
+ if (instanceId && session.state.instanceId !== instanceId) throw new Error('插件运行版本已变化,请重新打开界面');
767
+ if ((session.state.status === 'idle' || session.state.status === 'loading') && kind !== 'diagnostic') {
768
+ await this.ensureActivated(pluginId);
769
+ session = this.sessions.get(pluginId);
770
+ if (!session || (instanceId && session.state.instanceId !== instanceId)) throw new Error('插件运行版本已变化,请重新打开界面');
771
+ }
772
+ if (session.state.status !== 'running') throw new Error('插件尚未运行');
773
+ if (session.pending.size >= 32) throw new Error('插件操作过多,请稍后重试');
774
+ const hasUiTarget =
775
+ session.state.views.some(view => view.id === name && view.custom) ||
776
+ (!!session.ui && Object.hasOwn(session.ui, name) && !!session.manifest.codeBlockRenderers?.some(r => r.view === name));
254
777
  if (kind === 'diagnostic') {
255
- if (!session.state.views.some(view => view.id === name && view.custom) || !pluginRecord(payload) || typeof payload.message !== 'string') return Promise.reject(new Error('插件界面日志无效'));
778
+ if (!hasUiTarget || !pluginRecord(payload) || typeof payload.message !== 'string') throw new Error('插件界面日志无效');
256
779
  if (Date.now() - session.windowStart > 1000) { session.windowStart = Date.now(); session.calls = 0; }
257
- if (++session.calls > 200) return Promise.reject(new Error('插件日志超过速率限制'));
780
+ if (++session.calls > 200) throw new Error('插件日志超过速率限制');
258
781
  this.log(session, payload.level === 'warn' ? 'warn' : payload.level === 'error' ? 'error' : 'info', `[界面 ${name}] ${payload.message.slice(0, 1400)}`);
259
- return Promise.resolve();
782
+ return;
260
783
  }
261
784
  if (kind === 'message') {
262
- if (!session.state.views.some(view => view.id === name && view.custom)) return Promise.reject(new Error('插件界面已关闭'));
263
- try { payload = parsePluginJson(payload, 16 * 1024); } catch (error) { return Promise.reject(error); }
785
+ if (!hasUiTarget) throw new Error('插件界面已关闭');
786
+ payload = parsePluginJson(payload, 16 * 1024);
264
787
  }
265
788
  this.assert(session);
266
789
  const id = ++session.invocation;
790
+ const deadline = Date.now() + 300000;
267
791
  return new Promise<void>((resolve, reject) => {
792
+ const arm = () =>
793
+ setTimeout(() => {
794
+ if (session!.activeDialog && Date.now() < deadline && !session!.controller.signal.aborted) {
795
+ const entry = session!.pending.get(id);
796
+ if (entry) entry.timer = arm();
797
+ return;
798
+ }
799
+ this.stop(session!, false); session!.state.status = 'error'; session!.state.message = '插件操作超时,已停止运行'; this.log(session!, 'error', session!.state.message); reject(new Error(session!.state.message));
800
+ }, 30000);
801
+ const timer = arm();
802
+ session!.pending.set(id, { resolve: () => resolve(), reject, timer }); session!.sandbox?.send({ type: 'invoke', id, kind, name, payload });
803
+ });
804
+ }
805
+ async invokeAssistantTool(
806
+ pluginId: string,
807
+ toolName: string,
808
+ args: Record<string, unknown>,
809
+ context: { workspaceId: string; activeFileId?: string },
810
+ ): Promise<PluginJson> {
811
+ let session = this.sessions.get(pluginId);
812
+ if (!session) throw new Error('插件尚未运行');
813
+ const definition = session.manifest.assistantTools?.find(item => item.name === toolName);
814
+ if (!definition) throw new Error('助手工具没有在插件清单中声明');
815
+ if (session.scope === 'user' && session.personalCodePolicy === 'block')
816
+ throw new Error('此工作区管理员策略禁止个人代码插件运行');
817
+ if (session.scope === 'user' && session.personalCodePolicy === 'read-only' && definition.effect === 'write')
818
+ throw new Error('此工作区管理员策略仅允许个人代码插件只读访问');
819
+ validateAgainstPluginJsonSchema(args, definition.parameters);
820
+ if (session.state.status === 'idle' || session.state.status === 'loading') {
821
+ await this.ensureActivated(pluginId);
822
+ session = this.sessions.get(pluginId);
823
+ if (!session) throw new Error('插件运行实例已失效');
824
+ }
825
+ if (session.state.status !== 'running') throw new Error(session.state.message || '插件尚未运行');
826
+ if (session.pending.size >= 32) throw new Error('插件操作过多,请稍后重试');
827
+ this.assert(session);
828
+ const id = ++session.invocation;
829
+ const raw = await new Promise<unknown>((resolve, reject) => {
268
830
  const timer = setTimeout(() => {
269
- this.stop(session); session.state.status = 'error'; session.state.message = '插件操作超时,已停止运行'; this.log(session, 'error', session.state.message); reject(new Error(session.state.message));
831
+ session!.pending.delete(id);
832
+ reject(new Error('插件助手工具执行超时'));
270
833
  }, 30000);
271
- session.pending.set(id, { resolve, reject, timer }); session.sandbox?.send({ type: 'invoke', id, kind, name, payload });
834
+ session!.pending.set(id, { resolve, reject, timer });
835
+ session!.sandbox?.send({ type: 'invoke', id, kind: 'assistant-tool', name: toolName, payload: { args, context } });
272
836
  });
837
+ return parsePluginJson(raw ?? null, 32 * 1024);
838
+ }
839
+ async queryAssistantContext(
840
+ pluginId: string,
841
+ providerId: string,
842
+ query: string,
843
+ context: { workspaceId: string; activeFileId?: string },
844
+ ): Promise<{ title: string; content: string; metadata?: PluginJson }> {
845
+ let session = this.sessions.get(pluginId);
846
+ if (!session) throw new Error('插件尚未运行');
847
+ const definition = session.manifest.assistantContextProviders?.find(item => item.id === providerId);
848
+ if (!definition) throw new Error('助手上下文提供者没有在插件清单中声明');
849
+ if (session.scope === 'user' && session.personalCodePolicy === 'block')
850
+ throw new Error('此工作区管理员策略禁止个人代码插件运行');
851
+ if (session.state.status === 'idle' || session.state.status === 'loading') {
852
+ await this.ensureActivated(pluginId);
853
+ session = this.sessions.get(pluginId);
854
+ if (!session) throw new Error('插件运行实例已失效');
855
+ }
856
+ if (session.state.status !== 'running') throw new Error(session.state.message || '插件尚未运行');
857
+ if (session.pending.size >= 32) throw new Error('插件操作过多,请稍后重试');
858
+ this.assert(session);
859
+ const id = ++session.invocation;
860
+ const raw = await new Promise<unknown>((resolve, reject) => {
861
+ const timer = setTimeout(() => {
862
+ session!.pending.delete(id);
863
+ reject(new Error('插件上下文读取超时'));
864
+ }, 10000);
865
+ session!.pending.set(id, { resolve, reject, timer });
866
+ session!.sandbox?.send({
867
+ type: 'invoke',
868
+ id,
869
+ kind: 'assistant-context',
870
+ name: providerId,
871
+ payload: { query: query.slice(0, 500), context },
872
+ });
873
+ });
874
+ const maxBytes = Math.min(definition.maxBytes ?? pluginAssistantContextMaxBytes, pluginAssistantContextMaxBytes);
875
+ let title = definition.label;
876
+ let content = '';
877
+ let metadata: PluginJson | undefined;
878
+ if (typeof raw === 'string') {
879
+ content = raw;
880
+ } else if (pluginRecord(raw) && typeof raw.content === 'string') {
881
+ if (typeof raw.title === 'string' && raw.title.trim()) title = raw.title.trim().slice(0, 80);
882
+ content = raw.content;
883
+ if (raw.metadata !== undefined) metadata = parsePluginJson(raw.metadata, 4096);
884
+ } else {
885
+ throw new Error('插件上下文返回值无效');
886
+ }
887
+ const encoded = new TextEncoder().encode(content);
888
+ if (encoded.length > maxBytes) {
889
+ content = new TextDecoder('utf-8', { fatal: false }).decode(encoded.subarray(0, maxBytes)) + '\n...[已按上下文上限截断]';
890
+ }
891
+ return { title, content, ...(metadata !== undefined ? { metadata } : {}) };
273
892
  }
274
893
  notify(event: PluginEvent) {
275
894
  const permission = event.type === 'documents.changed' ? 'documents.read' : event.type === 'objects.changed' ? 'objects.read' : event.type === 'relations.changed' ? 'relations.read' : undefined;