@tano.page/workbench 0.15.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 (118) hide show
  1. package/package.json +35 -14
  2. package/src/App.vue +68 -797
  3. package/src/assistant/agent-identities.ts +1 -97
  4. package/src/assistant/agent-task-context.ts +1 -54
  5. package/src/assistant/attachments.ts +1 -1
  6. package/src/assistant/completion.ts +1 -61
  7. package/src/assistant/components/AssistantPanel.vue +1 -1
  8. package/src/assistant/connection-actions.ts +237 -0
  9. package/src/assistant/document-mentions.ts +1 -33
  10. package/src/assistant/engine.ts +1 -585
  11. package/src/assistant/execution.ts +6 -33
  12. package/src/assistant/hash.ts +1 -4
  13. package/src/assistant/language.ts +10 -37
  14. package/src/assistant/plugin-bridge-builder.ts +146 -0
  15. package/src/assistant/prompts.ts +1 -65
  16. package/src/assistant/proposal-actions.ts +336 -0
  17. package/src/assistant/store.ts +87 -554
  18. package/src/assistant/structures.ts +1 -157
  19. package/src/assistant/tasks.ts +8 -94
  20. package/src/assistant/tool-rules.ts +1 -7
  21. package/src/composables/use-workbench-help.ts +177 -0
  22. package/src/composables/use-workbench-lifecycle.ts +249 -0
  23. package/src/composables/use-workbench-settings.ts +185 -0
  24. package/src/composables/use-workbench-shortcuts.ts +37 -1022
  25. package/src/composables/use-workbench-views.ts +325 -0
  26. package/src/documents/components/DocumentActionMenu.vue +279 -0
  27. package/src/documents/components/DocumentInspector.vue +168 -0
  28. package/src/documents/components/DocumentPane.vue +482 -0
  29. package/src/documents/description-merge.ts +1 -9
  30. package/src/files/components/FileMetadataPanel.vue +49 -15
  31. package/src/i18n/locale-catalogs.ts +7 -6
  32. package/src/i18n/locale-registry.ts +8 -6
  33. package/src/i18n/locales/de-DE.json +23 -1
  34. package/src/i18n/locales/en-US.json +23 -1
  35. package/src/i18n/locales/es-ES.json +23 -1
  36. package/src/i18n/locales/ja-JP.json +23 -1
  37. package/src/i18n/locales/zh-TW.json +23 -1
  38. package/src/mail/components/MailAccountDialog.vue +1 -0
  39. package/src/mail/components/MailComposerDialog.vue +1 -0
  40. package/src/mail/components/MailWorkspaceView.vue +1 -0
  41. package/src/mail/components/SidebarMail.vue +1 -0
  42. package/src/objects/content-references.ts +6 -56
  43. package/src/objects/wiki-links.ts +1 -48
  44. package/src/objects/workspace-objects.ts +2 -3
  45. package/src/plans/calendar.ts +2 -2
  46. package/src/plans/components/CalendarAgendaView.vue +165 -0
  47. package/src/plans/components/CalendarFilterBar.vue +128 -0
  48. package/src/plans/components/CalendarMonthView.vue +224 -0
  49. package/src/plans/components/CalendarQuickCreateDialog.vue +269 -0
  50. package/src/plans/components/CalendarTimelineView.vue +517 -0
  51. package/src/plans/components/CalendarTopbarControls.vue +101 -0
  52. package/src/plans/components/CalendarView.vue +162 -2106
  53. package/src/plans/components/CalendarYearView.vue +138 -0
  54. package/src/plans/components/PlanConnectionsDialog.vue +1 -1
  55. package/src/plans/components/calendar-shared.css +192 -0
  56. package/src/plans/composables/use-calendar-interactions.ts +396 -0
  57. package/src/plans/composables/use-calendar-scroll.ts +420 -0
  58. package/src/plugins/components/PluginDetailPage.vue +10 -6
  59. package/src/plugins/components/PluginDeveloperArea.vue +192 -0
  60. package/src/plugins/components/PluginExplorer.vue +6 -4
  61. package/src/plugins/components/PluginImportDialog.vue +1 -1
  62. package/src/plugins/components/PluginInstaller.vue +269 -178
  63. package/src/plugins/components/PluginMaintenance.vue +37 -49
  64. package/src/plugins/components/PluginRepositoryStorage.vue +4 -2
  65. package/src/plugins/components/PluginSettingsForm.vue +2 -1
  66. package/src/plugins/components/PluginsTabPage.vue +61 -0
  67. package/src/plugins/components/plugin-center.css +5 -0
  68. package/src/plugins/data.ts +9 -86
  69. package/src/plugins/editor-plugin-adapters.ts +169 -0
  70. package/src/plugins/plugin-data.ts +2 -3
  71. package/src/plugins/plugin-rpc-router.ts +558 -0
  72. package/src/plugins/plugin-sdk.ts +1 -260
  73. package/src/plugins/plugin-ui-dialogs.ts +167 -0
  74. package/src/plugins/queries.ts +1 -75
  75. package/src/plugins/view-header.ts +2 -7
  76. package/src/runtime.ts +3 -2
  77. package/src/settings/components/SettingsPanel.vue +8 -3
  78. package/src/settings/components/WorkbenchSettings.vue +20 -7
  79. package/src/settings/components/settings-context.ts +1 -1
  80. package/src/settings/settings-tab.ts +1 -0
  81. package/src/shell/command-palette.ts +3 -3
  82. package/src/shell/components/EditorToolbar.vue +8 -9
  83. package/src/shell/components/EditorTools.vue +1 -5
  84. package/src/shell/components/PaneTopbar.vue +393 -0
  85. package/src/shell/components/SelectionToolbar.vue +0 -2
  86. package/src/shell/components/WorkbenchContextMenus.vue +37 -26
  87. package/src/shell/components/WorkbenchModals.vue +22 -18
  88. package/src/shell/components/WorkbenchPanes.vue +358 -1512
  89. package/src/shell/components/WorkbenchSidebar.vue +486 -0
  90. package/src/shell/pane-registry.ts +69 -0
  91. package/src/shell/use-surface-dismissal.ts +219 -0
  92. package/src/shell/use-workbench-commands.ts +599 -0
  93. package/src/shell/use-workbench-keybindings.ts +337 -0
  94. package/src/shell/use-workbench.ts +488 -1081
  95. package/src/shell/workbench-context.ts +30 -3
  96. package/src/stores/workspace-document-io.ts +807 -0
  97. package/src/stores/workspace-file-ops.ts +1 -1
  98. package/src/stores/workspace-knowledge.ts +1 -1
  99. package/src/stores/workspace-lifecycle.ts +459 -0
  100. package/src/stores/workspace-plugins-state.ts +71 -599
  101. package/src/stores/workspace-session.ts +287 -0
  102. package/src/stores/workspace-tabs-layout.ts +1 -1
  103. package/src/stores/workspace-types.ts +50 -0
  104. package/src/stores/workspace.ts +163 -1345
  105. package/src/styles.css +0 -1
  106. package/src/tabs/components/DesktopTabs.vue +19 -11
  107. package/src/windows/AuxiliaryWindows.vue +2 -2
  108. package/src/windows/use-window-event-bridge.ts +152 -0
  109. package/src/workspace/components/TemplateLibrary.vue +1 -1
  110. package/src/workspace/components/WorkspaceIconPicker.vue +5 -4
  111. package/src/workspace/components/WorkspacePickerMenu.vue +317 -0
  112. package/src/assistant/locales/de-DE.json +0 -129
  113. package/src/assistant/locales/en-US.json +0 -129
  114. package/src/assistant/locales/es-ES.json +0 -129
  115. package/src/assistant/locales/ja-JP.json +0 -129
  116. package/src/assistant/locales/zh-CN.json +0 -129
  117. package/src/assistant/locales/zh-TW.json +0 -129
  118. package/src/assistant/task-prompts.json +0 -39
@@ -0,0 +1,558 @@
1
+ import type { Ref } from 'vue';
2
+ import type { WorkspaceCapabilities } from '@tano/editor/runtime';
3
+ import { mergeMarkdown } from '@tano/markdown';
4
+ import {
5
+ isMarkdown,
6
+ isWorkspaceInternalPath,
7
+ matchesPluginPathScopes,
8
+ objectDirectory,
9
+ parseObject,
10
+ parsePluginAttachmentWrite,
11
+ pluginRecord,
12
+ referenceKey,
13
+ validateObjectProperties,
14
+ validatePath,
15
+ validateRelation,
16
+ type FileEntry,
17
+ type FileRegistry,
18
+ type FileSnapshot,
19
+ type PluginAiCompleteRequest,
20
+ type PluginAiCompleteResult,
21
+ type PluginAiStructuredRequest,
22
+ type PluginAiStructuredResult,
23
+ type ReferenceTarget,
24
+ type RelationTypeDefinition,
25
+ type Workspace,
26
+ type WorkspaceAdapter,
27
+ type WorkspaceRelation,
28
+ } from '@tano/protocol';
29
+ import { assistantHash } from '../assistant/hash';
30
+ import type { useDocumentIndex } from '../documents/document-index';
31
+ import { documentDirty as dirty, type OpenDocument } from '../documents/document-session';
32
+ import { nativeAttachments } from '../files/attachments';
33
+ import { t } from '../i18n/i18n';
34
+ import { mergeObject, saveObject, type ObjectRecord } from '../objects/workspace-objects';
35
+ import { saveRelationChange } from '../objects/workspace-relations';
36
+ import type { WorkbenchRuntime } from '../runtime';
37
+ import type { PluginAttachmentReader } from './attachment-reader';
38
+ import type { PluginQueryPager } from './data';
39
+ import { queryPluginData } from './queries';
40
+
41
+ export interface PluginEditorBridge {
42
+ applyEdit(id: string, before: string, after: string): Promise<boolean>;
43
+ activeEditor?(): {
44
+ fileId: string;
45
+ mode: 'rich' | 'source';
46
+ readOnly: boolean;
47
+ selection: { from: number; to: number; empty: boolean };
48
+ selectedText: string;
49
+ blockType?: string;
50
+ } | null;
51
+ applySelectionEdit?(id: string, text: string, mode: 'insert' | 'replace'): Promise<boolean>;
52
+ }
53
+
54
+ export type PluginAiRunner = (options: {
55
+ pluginId: string;
56
+ pluginName: string;
57
+ structured: boolean;
58
+ request: PluginAiCompleteRequest | PluginAiStructuredRequest;
59
+ signal: AbortSignal;
60
+ }) => Promise<PluginAiCompleteResult | PluginAiStructuredResult>;
61
+
62
+ export interface PluginRpcContext {
63
+ adapter: WorkspaceAdapter;
64
+ runtime: WorkbenchRuntime;
65
+ workspace: Ref<Workspace | null>;
66
+ fileRegistry: Ref<FileRegistry | null>;
67
+ documents: Ref<OpenDocument[]>;
68
+ documentIndex: ReturnType<typeof useDocumentIndex>;
69
+ capabilities: Ref<WorkspaceCapabilities>;
70
+ objects: Ref<ObjectRecord[]>;
71
+ relations: Ref<WorkspaceRelation[]>;
72
+ relationError: Ref<string>;
73
+ getRelationBase: () => FileSnapshot | null;
74
+ relationDefinitions: Ref<RelationTypeDefinition[]>;
75
+ referenceTargets: Ref<ReferenceTarget[]>;
76
+ pluginAttachmentReader: PluginAttachmentReader;
77
+ pluginQueryPager: PluginQueryPager;
78
+ getPluginEditorBridge: () => PluginEditorBridge | undefined;
79
+ getPluginAiRunner: () => PluginAiRunner | undefined;
80
+ openPluginDialog: (
81
+ method: 'ui.pick' | 'ui.prompt' | 'ui.confirm',
82
+ params: Record<string, unknown>,
83
+ ) => Promise<string | boolean | null>;
84
+ showPluginToast: (params: Record<string, unknown>) => void;
85
+ openPluginView: (pluginId: string, viewId: string) => void | Promise<void>;
86
+ serial: <T>(task: () => Promise<T>) => Promise<T>;
87
+ writable: () => void;
88
+ refreshObjects: () => Promise<void>;
89
+ openInternal: (file: FileEntry, replaceId?: string, current?: () => boolean) => Promise<void>;
90
+ saveInternal: (doc: OpenDocument) => Promise<void>;
91
+ ensureTabNavigation: (tabId: string, targetId?: string) => void;
92
+ touchNavigation: () => void;
93
+ }
94
+
95
+ function resolveDocumentText(value: unknown) {
96
+ if (typeof value !== 'string' || value.length > 512000)
97
+ throw new Error('插件文档内容无效或过大');
98
+ return value;
99
+ }
100
+
101
+ function resolveScopedMarkdownFile(
102
+ ctx: PluginRpcContext,
103
+ fileId: unknown,
104
+ pathScopes: string[] | undefined,
105
+ ): FileEntry {
106
+ const entry = ctx.fileRegistry.value?.get(String(fileId));
107
+ if (!entry || !isMarkdown(entry.path) || isWorkspaceInternalPath(entry.path))
108
+ throw new Error('文档不存在或不可访问');
109
+ if (!matchesPluginPathScopes(entry.path, pathScopes))
110
+ throw new Error('文档路径不在插件授权目录范围内');
111
+ return entry;
112
+ }
113
+
114
+ async function handleEditorRpc(
115
+ ctx: PluginRpcContext,
116
+ method: 'editor.active' | 'editor.insert' | 'editor.replaceSelection',
117
+ params: Record<string, unknown>,
118
+ pathScopes: string[] | undefined,
119
+ expected: string | undefined,
120
+ assertInstance: () => void,
121
+ ): Promise<unknown> {
122
+ if (method === 'editor.active') {
123
+ assertInstance();
124
+ if (!expected || ctx.workspace.value?.id !== expected) throw new Error(t('工作区已切换'));
125
+ const snapshot = ctx.getPluginEditorBridge()?.activeEditor?.();
126
+ if (!snapshot) return null;
127
+ const entry = ctx.fileRegistry.value?.get(snapshot.fileId);
128
+ if (!entry || !isMarkdown(entry.path) || isWorkspaceInternalPath(entry.path)) return null;
129
+ if (!matchesPluginPathScopes(entry.path, pathScopes)) return null;
130
+ const doc = ctx.documentIndex.byId.value.get(entry.id);
131
+ const content = doc ? doc.content : (await ctx.adapter.read(entry.path)).content;
132
+ assertInstance();
133
+ return {
134
+ fileId: entry.id,
135
+ path: entry.path,
136
+ mode: snapshot.mode,
137
+ readOnly: !!(ctx.workspace.value?.readOnly || entry.readOnly || snapshot.readOnly),
138
+ selection: snapshot.selection,
139
+ selectedText: snapshot.selectedText,
140
+ ...(snapshot.blockType ? { blockType: snapshot.blockType } : {}),
141
+ hash: await assistantHash(content),
142
+ };
143
+ }
144
+ return ctx.serial(async () => {
145
+ assertInstance();
146
+ if (!expected || ctx.workspace.value?.id !== expected) throw new Error(t('工作区已切换'));
147
+ ctx.writable();
148
+ const bridge = ctx.getPluginEditorBridge();
149
+ const snapshot = bridge?.activeEditor?.();
150
+ if (!snapshot || !bridge?.applySelectionEdit)
151
+ throw new Error('当前没有可编辑的活动文档');
152
+ const entry = ctx.fileRegistry.value?.get(snapshot.fileId);
153
+ if (!entry || !isMarkdown(entry.path) || isWorkspaceInternalPath(entry.path))
154
+ throw new Error('当前没有可编辑的活动文档');
155
+ if (!matchesPluginPathScopes(entry.path, pathScopes))
156
+ throw new Error('文档路径不在插件授权目录范围内');
157
+ if (entry.readOnly || snapshot.readOnly) throw new Error('你对这篇文档只有阅读权限');
158
+ const doc = ctx.documentIndex.byId.value.get(entry.id);
159
+ if (doc?.conflict || doc?.missing) throw new Error('请先处理文档已有冲突');
160
+ const editing = ctx.runtime.extensions?.()?.editing;
161
+ if (editing?.isManaging(entry.id)) {
162
+ throw new Error('当前协作会话暂不支持直接插入选区,请使用 documents.edit');
163
+ }
164
+ const ok = await bridge.applySelectionEdit(
165
+ entry.id,
166
+ String(params.text ?? ''),
167
+ method === 'editor.insert' ? 'insert' : 'replace',
168
+ );
169
+ if (!ok) throw new Error('当前编辑器无法应用选区修改');
170
+ assertInstance();
171
+ const updated = ctx.documentIndex.byId.value.get(entry.id);
172
+ const content = updated ? updated.content : (await ctx.adapter.read(entry.path)).content;
173
+ return {
174
+ fileId: entry.id,
175
+ hash: await assistantHash(content),
176
+ status: 'applied',
177
+ };
178
+ });
179
+ }
180
+
181
+ async function handleDocumentWriteRpc(
182
+ ctx: PluginRpcContext,
183
+ method: 'documents.create' | 'documents.move' | 'documents.trash' | 'documents.write',
184
+ params: Record<string, unknown>,
185
+ pathScopes: string[] | undefined,
186
+ current: Workspace,
187
+ assertCurrent: () => void,
188
+ ): Promise<unknown> {
189
+ if (method === 'documents.create') {
190
+ const path = resolveDocumentText(params.path);
191
+ if (!isMarkdown(path) || validatePath(path)) throw new Error('新文档路径无效');
192
+ if (!matchesPluginPathScopes(path, pathScopes))
193
+ throw new Error('新文档路径不在插件授权目录范围内');
194
+ assertCurrent();
195
+ await ctx.adapter.create(path, resolveDocumentText(params.content));
196
+ ctx.workspace.value = await ctx.adapter.refresh();
197
+ const entry = ctx.fileRegistry.value?.at(path)!;
198
+ return { id: entry.id, path };
199
+ }
200
+ if (method === 'documents.move') {
201
+ const entry = resolveScopedMarkdownFile(ctx, params.fileId, pathScopes);
202
+ if (entry.readOnly) throw new Error('你对这篇文档只有阅读权限');
203
+ const destination = resolveDocumentText(params.destination);
204
+ if (!isMarkdown(destination) || validatePath(destination) || isWorkspaceInternalPath(destination))
205
+ throw new Error('目标文档路径无效');
206
+ if (!matchesPluginPathScopes(destination, pathScopes))
207
+ throw new Error('目标路径不在插件授权目录范围内');
208
+ if (destination === entry.path) return { id: entry.id, path: entry.path };
209
+ if (current.files.some((row) => row.path === destination))
210
+ throw new Error('目标路径已存在同名文件');
211
+ if (!pluginRecord(params.base) || params.base.id !== entry.id || typeof params.base.content !== 'string')
212
+ throw new Error('文档版本无效');
213
+ const doc = ctx.documentIndex.byId.value.get(entry.id);
214
+ if (doc?.conflict || doc?.missing) throw new Error('请先处理文档已有冲突');
215
+ if (doc && dirty(doc)) throw new Error('文档存在未保存修改,请先保存后再移动');
216
+ const disk = await ctx.adapter.read(entry.path);
217
+ if (disk.content !== params.base.content)
218
+ throw new Error('文档内容已变化,请重新读取后再移动');
219
+ assertCurrent();
220
+ if (ctx.adapter.changeFile) {
221
+ const result = await ctx.adapter.changeFile({
222
+ workspaceId: current.id,
223
+ fileId: entry.id,
224
+ path: entry.path,
225
+ expectedHash: disk.hash,
226
+ destination,
227
+ });
228
+ if (result.status !== 'saved') throw new Error('文档内容已变化或不存在,请重新读取后再移动');
229
+ } else {
230
+ await ctx.adapter.move(entry.path, destination, 'file');
231
+ }
232
+ assertCurrent();
233
+ ctx.workspace.value = await ctx.adapter.refresh();
234
+ if (doc) doc.path = destination;
235
+ return { id: entry.id, path: destination };
236
+ }
237
+ if (method === 'documents.trash') {
238
+ const entry = resolveScopedMarkdownFile(ctx, params.fileId, pathScopes);
239
+ if (entry.readOnly) throw new Error('你对这篇文档只有阅读权限');
240
+ if (!pluginRecord(params.base) || params.base.id !== entry.id || typeof params.base.content !== 'string')
241
+ throw new Error('文档版本无效');
242
+ const doc = ctx.documentIndex.byId.value.get(entry.id);
243
+ if (doc?.conflict || doc?.missing) throw new Error('请先处理文档已有冲突');
244
+ if (doc && dirty(doc)) throw new Error('文档存在未保存修改,请先保存后再移入回收站');
245
+ const disk = await ctx.adapter.read(entry.path);
246
+ if (disk.content !== params.base.content)
247
+ throw new Error('文档内容已变化,请重新读取后再移入回收站');
248
+ assertCurrent();
249
+ if (ctx.adapter.changeFile) {
250
+ const result = await ctx.adapter.changeFile({
251
+ workspaceId: current.id,
252
+ fileId: entry.id,
253
+ path: entry.path,
254
+ expectedHash: disk.hash,
255
+ });
256
+ if (result.status !== 'saved') throw new Error('文档内容已变化或不存在,请重新读取后再移入回收站');
257
+ } else {
258
+ await ctx.adapter.remove(entry.path);
259
+ }
260
+ assertCurrent();
261
+ ctx.workspace.value = await ctx.adapter.refresh();
262
+ if (doc) doc.missing = true;
263
+ return { id: entry.id, path: entry.path, trashed: true };
264
+ }
265
+ // documents.write
266
+ const entry = resolveScopedMarkdownFile(ctx, params.fileId, pathScopes);
267
+ if (entry.readOnly) throw new Error('你对这篇文档只有阅读权限');
268
+ if (!pluginRecord(params.base) || params.base.id !== entry.id)
269
+ throw new Error('文档版本无效');
270
+ const base = resolveDocumentText(params.base.content);
271
+ const desired = resolveDocumentText(params.content);
272
+ const disk = await ctx.adapter.read(entry.path);
273
+ const doc = ctx.documentIndex.byId.value.get(entry.id);
274
+ if (doc?.conflict || doc?.missing) throw new Error('请先处理文档已有冲突');
275
+ const live = doc
276
+ ? mergeMarkdown(doc.base.content, doc.content, disk.content)
277
+ : { clean: true, content: disk.content };
278
+ const merged = mergeMarkdown(base, desired, live.content);
279
+ if (!live.clean || !merged.clean) {
280
+ const copyPath = entry.path.replace(
281
+ /\.(md|markdown)$/i,
282
+ `.plugin-conflict-${crypto.randomUUID().slice(0, 8)}.md`,
283
+ );
284
+ assertCurrent();
285
+ await ctx.adapter.create(copyPath, desired);
286
+ throw new Error(t('文档有重叠修改,插件版本已保存在 {0}', [copyPath]));
287
+ }
288
+ const editing = ctx.runtime.extensions?.()?.editing;
289
+ if (editing?.isManaging(entry.id)) {
290
+ if (!editing.applyPluginEdit)
291
+ throw new Error('当前协作会话不支持插件编辑,请退出协作后重试');
292
+ assertCurrent();
293
+ const applied = await editing.applyPluginEdit(entry.id, live.content, merged.content);
294
+ assertCurrent();
295
+ return {
296
+ id: entry.id,
297
+ hash: await assistantHash(applied ?? merged.content),
298
+ status: 'applied',
299
+ };
300
+ }
301
+ const bridge = ctx.getPluginEditorBridge();
302
+ if (doc && bridge && (await bridge.applyEdit(entry.id, doc.content, merged.content))) {
303
+ return { id: entry.id, hash: await assistantHash(doc.content), status: 'applied' };
304
+ }
305
+ if (doc) {
306
+ doc.content = merged.content;
307
+ doc.base = disk;
308
+ assertCurrent();
309
+ await ctx.saveInternal(doc);
310
+ if (doc.error || doc.conflict || dirty(doc))
311
+ throw new Error(doc.error ?? '插件修改已保留为草稿,请处理冲突后保存');
312
+ return { id: entry.id, hash: await assistantHash(doc.content), status: 'saved' };
313
+ }
314
+ assertCurrent();
315
+ const result = await ctx.adapter.write(entry.path, merged.content, disk.hash);
316
+ if (result.status !== 'saved') {
317
+ const copyPath = entry.path.replace(
318
+ /\.(md|markdown)$/i,
319
+ `.plugin-conflict-${crypto.randomUUID().slice(0, 8)}.md`,
320
+ );
321
+ await ctx.adapter.create(copyPath, desired);
322
+ throw new Error(t('保存时文件发生变化,插件版本已保存在 {0}', [copyPath]));
323
+ }
324
+ return { id: entry.id, hash: await assistantHash(result.snapshot.content), status: 'saved' };
325
+ }
326
+
327
+ async function handleObjectRelationWriteRpc(
328
+ ctx: PluginRpcContext,
329
+ method: 'objects.create' | 'objects.update' | 'relations.add' | 'relations.remove',
330
+ params: Record<string, unknown>,
331
+ current: Workspace,
332
+ assertCurrent: () => void,
333
+ ): Promise<unknown> {
334
+ if (!ctx.capabilities.value.features.objectReferences) throw new Error('工作区对象功能已关闭');
335
+ if (method === 'objects.create' || method === 'objects.update') {
336
+ if (!pluginRecord(params.object)) throw new Error('对象无效');
337
+ const draft = JSON.parse(JSON.stringify(params.object));
338
+ if (method === 'objects.create') {
339
+ if (!ctx.adapter.reserveObjectId) throw new Error('存储适配器不支持对象身份分配');
340
+ const id = await ctx.adapter.reserveObjectId(ctx.objects.value.map((row) => row.object.id));
341
+ const object = parseObject(JSON.stringify({ ...draft, version: 1, id }));
342
+ validateObjectProperties(object.type, object.properties);
343
+ assertCurrent();
344
+ await ctx.adapter.create(
345
+ `${objectDirectory}/${id}.tano.json`,
346
+ JSON.stringify(object, null, 2) + '\n',
347
+ );
348
+ ctx.workspace.value = await ctx.adapter.refresh();
349
+ await ctx.refreshObjects();
350
+ return object;
351
+ }
352
+ if (!pluginRecord(params.base) || !pluginRecord(params.base.object))
353
+ throw new Error('对象版本无效');
354
+ const record = ctx.objects.value.find((row) => row.object.id === draft.id);
355
+ if (!record) throw new Error('对象不存在');
356
+ if (current.files.find((row) => row.path === record.path)?.readOnly)
357
+ throw new Error('对象只读');
358
+ const object = parseObject(JSON.stringify(draft));
359
+ validateObjectProperties(object.type, object.properties);
360
+ const merged = mergeObject(
361
+ parseObject(JSON.stringify(params.base.object)),
362
+ object,
363
+ record.object,
364
+ );
365
+ const preserve = async () => {
366
+ const path = `.tano/conflicts/plugin-object-${crypto.randomUUID()}.json`;
367
+ assertCurrent();
368
+ await ctx.adapter.create(
369
+ path,
370
+ JSON.stringify({ version: 1, pluginProposal: object, base: params.base }, null, 2) + '\n',
371
+ );
372
+ return path;
373
+ };
374
+ if (!merged)
375
+ throw new Error(t('对象已有重叠修改,插件版本已保存在 {0}', [await preserve()]));
376
+ let saved: ObjectRecord;
377
+ try {
378
+ assertCurrent();
379
+ saved = await saveObject(ctx.adapter, record, merged);
380
+ } catch (error) {
381
+ throw new Error(t('{0} 插件版本已保存在 {1}', [String(error), await preserve()]));
382
+ }
383
+ ctx.workspace.value = await ctx.adapter.refresh();
384
+ await ctx.refreshObjects();
385
+ return saved.object;
386
+ }
387
+ if (ctx.relationError.value) throw new Error(ctx.relationError.value);
388
+ const relation = params.relation as WorkspaceRelation;
389
+ validateRelation(relation, ctx.relationDefinitions.value);
390
+ for (const endpoint of [relation.source, relation.target])
391
+ if (!ctx.referenceTargets.value.some((target) => referenceKey(target) === referenceKey(endpoint)))
392
+ throw new Error('关系端点不存在或不可访问');
393
+ assertCurrent();
394
+ await saveRelationChange(
395
+ ctx.adapter,
396
+ ctx.getRelationBase(),
397
+ method === 'relations.add' ? { add: relation } : { remove: relation },
398
+ );
399
+ ctx.workspace.value = await ctx.adapter.refresh();
400
+ await ctx.refreshObjects();
401
+ return null;
402
+ }
403
+
404
+ export async function dispatchPluginRpcCall(
405
+ ctx: PluginRpcContext,
406
+ method: string,
407
+ params: Record<string, unknown>,
408
+ assertInstance: () => void,
409
+ ): Promise<unknown> {
410
+ const expected = ctx.workspace.value?.id;
411
+ if (method === 'ui.pick' || method === 'ui.prompt' || method === 'ui.confirm') {
412
+ assertInstance();
413
+ if (!expected || ctx.workspace.value?.id !== expected) throw new Error(t('工作区已切换'));
414
+ return ctx.openPluginDialog(method, params);
415
+ }
416
+ if (method === 'ui.toast') {
417
+ assertInstance();
418
+ if (!expected || ctx.workspace.value?.id !== expected) throw new Error(t('工作区已切换'));
419
+ ctx.showPluginToast(params);
420
+ return null;
421
+ }
422
+ if (method === 'ai.complete' || method === 'ai.structured') {
423
+ assertInstance();
424
+ if (!expected || ctx.workspace.value?.id !== expected) throw new Error(t('工作区已切换'));
425
+ const aiRunner = ctx.getPluginAiRunner();
426
+ if (!aiRunner) throw new Error('当前环境尚未配置同页助手模型连接');
427
+ const signal = params.signal instanceof AbortSignal ? params.signal : new AbortController().signal;
428
+ return aiRunner({
429
+ pluginId: String(params.pluginId ?? ''),
430
+ pluginName: String(params.pluginName ?? ''),
431
+ structured: method === 'ai.structured',
432
+ request: params.request as PluginAiCompleteRequest | PluginAiStructuredRequest,
433
+ signal,
434
+ });
435
+ }
436
+ const pathScopes = Array.isArray(params.pathScopes) ? (params.pathScopes as string[]) : undefined;
437
+ if (method === 'editor.active' || method === 'editor.insert' || method === 'editor.replaceSelection') {
438
+ return handleEditorRpc(ctx, method, params, pathScopes, expected, assertInstance);
439
+ }
440
+ return ctx.serial(async () => {
441
+ const assertCurrent = () => {
442
+ assertInstance();
443
+ if (!expected || ctx.workspace.value?.id !== expected) throw new Error(t('工作区已切换'));
444
+ };
445
+ assertCurrent();
446
+ const attachmentService =
447
+ ctx.runtime.attachments ??
448
+ (ctx.runtime.native && ctx.adapter.mode === 'desktop' ? nativeAttachments : undefined);
449
+ if (method === 'attachments.read')
450
+ return ctx.pluginAttachmentReader.read(
451
+ ctx.workspace.value!,
452
+ params,
453
+ attachmentService,
454
+ assertCurrent,
455
+ );
456
+ if (method === 'attachments.write') {
457
+ ctx.writable();
458
+ if (!attachmentService?.importAttachment)
459
+ throw new Error('当前宿主不支持写入附件');
460
+ const parsed = parsePluginAttachmentWrite(params.request);
461
+ const targetDocPath = parsed.documentPath || (pathScopes?.length ? `${pathScopes[0]!}note.md` : '');
462
+ if (pathScopes?.length && !matchesPluginPathScopes(targetDocPath, pathScopes))
463
+ throw new Error('附件目标目录不在插件授权目录范围内');
464
+ const fileBytes = new Uint8Array(parsed.bytes);
465
+ const uploadFile = new File([fileBytes], parsed.name, { type: parsed.mimeType });
466
+ assertCurrent();
467
+ const imported = await attachmentService.importAttachment(
468
+ ctx.workspace.value!.id,
469
+ targetDocPath,
470
+ uploadFile,
471
+ parsed.image,
472
+ );
473
+ assertCurrent();
474
+ ctx.workspace.value = await ctx.adapter.refresh();
475
+ return imported;
476
+ }
477
+ ctx.workspace.value = await ctx.adapter.refresh();
478
+ await ctx.refreshObjects();
479
+ assertCurrent();
480
+ const current = ctx.workspace.value!;
481
+ if (method === 'views.open') {
482
+ await ctx.openPluginView(String(params.pluginId), String(params.viewId));
483
+ return null;
484
+ }
485
+ if (method.endsWith('.query') || method === 'documents.search')
486
+ return queryPluginData(method, params, ctx.pluginQueryPager, {
487
+ workspace: current,
488
+ objects: ctx.objects.value,
489
+ relations: ctx.relations.value,
490
+ drafts: ctx.documents.value,
491
+ read: (path) => ctx.adapter.read(path),
492
+ assertCurrent,
493
+ });
494
+ if (method === 'documents.list')
495
+ return current.files
496
+ .filter(
497
+ (row) =>
498
+ row.kind === 'file' &&
499
+ isMarkdown(row.path) &&
500
+ !isWorkspaceInternalPath(row.path) &&
501
+ matchesPluginPathScopes(row.path, pathScopes),
502
+ )
503
+ .map(({ id, path, name, readOnly }) => ({
504
+ id,
505
+ path,
506
+ name,
507
+ readOnly: current.readOnly || readOnly || false,
508
+ }));
509
+ if (method === 'documents.read') {
510
+ const entry = resolveScopedMarkdownFile(ctx, params.fileId, pathScopes);
511
+ const disk = await ctx.adapter.read(entry.path);
512
+ const doc = ctx.documentIndex.byId.value.get(entry.id);
513
+ if (doc?.conflict || doc?.missing) throw new Error('文档存在冲突,请先处理');
514
+ const content = resolveDocumentText(doc?.content ?? disk.content);
515
+ return { id: entry.id, path: entry.path, content, hash: await assistantHash(content) };
516
+ }
517
+ if (method === 'documents.open') {
518
+ await ctx.openInternal(resolveScopedMarkdownFile(ctx, params.fileId, pathScopes));
519
+ ctx.ensureTabNavigation(String(params.fileId), String(params.fileId));
520
+ ctx.touchNavigation();
521
+ return null;
522
+ }
523
+ if (method === 'objects.list')
524
+ return ctx.objects.value.map((record) => ({
525
+ id: record.object.id,
526
+ object: JSON.parse(JSON.stringify(record.object)),
527
+ hash: record.snapshot.hash,
528
+ }));
529
+ if (method === 'objects.read') {
530
+ const record = ctx.objects.value.find((row) => row.object.id === params.objectId);
531
+ if (!record) throw new Error('对象不存在或不可访问');
532
+ return {
533
+ id: record.object.id,
534
+ object: JSON.parse(JSON.stringify(record.object)),
535
+ hash: record.snapshot.hash,
536
+ };
537
+ }
538
+ if (method === 'relations.list') return JSON.parse(JSON.stringify(ctx.relations.value));
539
+ ctx.writable();
540
+ if (
541
+ method === 'documents.create' ||
542
+ method === 'documents.move' ||
543
+ method === 'documents.trash' ||
544
+ method === 'documents.write'
545
+ ) {
546
+ return handleDocumentWriteRpc(ctx, method, params, pathScopes, current, assertCurrent);
547
+ }
548
+ if (
549
+ method === 'objects.create' ||
550
+ method === 'objects.update' ||
551
+ method === 'relations.add' ||
552
+ method === 'relations.remove'
553
+ ) {
554
+ return handleObjectRelationWriteRpc(ctx, method, params, current, assertCurrent);
555
+ }
556
+ throw new Error('不支持此插件 API');
557
+ });
558
+ }