@tano.page/protocol 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.
- package/manifest.schema.json +448 -0
- package/package.json +21 -4
- package/src/appearance.ts +19 -4
- package/src/assistant.ts +35 -4
- package/src/domain/agent-identities.ts +110 -0
- package/src/domain/agent-inbox.ts +148 -0
- package/src/domain/assistant-completion.ts +61 -0
- package/src/domain/assistant-engine.ts +614 -0
- package/src/domain/assistant-execution.ts +43 -0
- package/src/domain/assistant-files.ts +19 -0
- package/src/domain/assistant-history.ts +90 -0
- package/src/domain/assistant-language.ts +112 -0
- package/src/domain/assistant-prompts.ts +70 -0
- package/src/domain/assistant-structures.ts +179 -0
- package/src/domain/assistant-task-prompts.json +39 -0
- package/src/domain/assistant-tasks.ts +114 -0
- package/src/domain/locales/de-DE.json +129 -0
- package/src/domain/locales/en-US.json +129 -0
- package/src/domain/locales/es-ES.json +129 -0
- package/src/domain/locales/ja-JP.json +129 -0
- package/src/domain/locales/zh-CN.json +129 -0
- package/src/domain/locales/zh-TW.json +129 -0
- package/src/domain/plugin-data.ts +175 -0
- package/src/domain/plugin-sdk.ts +300 -0
- package/src/domain/untrusted-data.ts +17 -0
- package/src/domain/workspace-comments.ts +148 -0
- package/src/extensions.ts +1100 -19
- package/src/frontmatter.ts +60 -1
- package/src/index.ts +3 -0
- package/src/object-types.ts +30 -20
- package/src/objects.ts +3 -4
- package/src/plan-item.ts +78 -0
- package/src/plugin-archive.ts +395 -0
- package/src/plugin-compat.ts +156 -0
- package/src/plugins.ts +12 -0
- package/src/relations.ts +1 -5
- package/src/task-repeat.ts +55 -8
- package/src/task-review.ts +11 -2
- package/src/view-engine.ts +1 -1
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
/** Public, browser-first SDK. Import types only; the runtime supplies `tano` to activate(). */
|
|
2
|
+
import type {
|
|
3
|
+
appearanceVersion,
|
|
4
|
+
LayoutThemeDefinition,
|
|
5
|
+
ShapeTokens,
|
|
6
|
+
ThemeTokens,
|
|
7
|
+
} from '../appearance';
|
|
8
|
+
import type {
|
|
9
|
+
ExecutablePluginManifest,
|
|
10
|
+
PluginActivationEvent,
|
|
11
|
+
PluginActiveEditorSnapshot,
|
|
12
|
+
PluginAiCompleteRequest,
|
|
13
|
+
PluginAiCompleteResult,
|
|
14
|
+
PluginAiStructuredRequest,
|
|
15
|
+
PluginAiStructuredResult,
|
|
16
|
+
PluginAssistantContextProviderDefinition,
|
|
17
|
+
PluginAssistantToolDefinition,
|
|
18
|
+
PluginAssistantToolEffect,
|
|
19
|
+
PluginAttachmentWriteRequest,
|
|
20
|
+
PluginCodeBlockRendererDefinition,
|
|
21
|
+
PluginEditorDecoration,
|
|
22
|
+
PluginEditorDecorationTone,
|
|
23
|
+
PluginFileHandlerDefinition,
|
|
24
|
+
PluginFileHandlerMode,
|
|
25
|
+
PluginFrontmatterPatch,
|
|
26
|
+
PluginJson,
|
|
27
|
+
PluginManifest,
|
|
28
|
+
PluginPackage,
|
|
29
|
+
PluginPackageAssets,
|
|
30
|
+
PluginPermission,
|
|
31
|
+
PluginServiceDefinition,
|
|
32
|
+
PluginServiceDependency,
|
|
33
|
+
PluginSettingField,
|
|
34
|
+
PluginSettingFieldType,
|
|
35
|
+
PluginSlashCommandDefinition,
|
|
36
|
+
PluginStatusBarAlign,
|
|
37
|
+
PluginStatusBarItem,
|
|
38
|
+
PluginStatusBarTone,
|
|
39
|
+
PluginUiBundle,
|
|
40
|
+
PluginUiConfirmOptions,
|
|
41
|
+
PluginUiPickItem,
|
|
42
|
+
PluginUiPickOptions,
|
|
43
|
+
PluginUiPromptOptions,
|
|
44
|
+
PluginUiToastOptions,
|
|
45
|
+
PluginUiTone,
|
|
46
|
+
PluginViewDefinition,
|
|
47
|
+
PluginViewLayout,
|
|
48
|
+
PluginViewLocation,
|
|
49
|
+
PluginViewNode,
|
|
50
|
+
WorkspacePersonalPluginPolicy,
|
|
51
|
+
} from '../extensions';
|
|
52
|
+
import type { WorkspaceObject } from '../objects';
|
|
53
|
+
import type { PluginArchiveV2 } from '../plugin-archive';
|
|
54
|
+
import type { PluginEngines, PluginErrorCode, PluginPlatform } from '../plugin-compat';
|
|
55
|
+
import type { PluginConnectionRequest, PluginConnectionResponse } from '../plugin-connections';
|
|
56
|
+
import type { WorkspaceRelation } from '../relations';
|
|
57
|
+
|
|
58
|
+
export type {
|
|
59
|
+
PluginManifest,
|
|
60
|
+
ExecutablePluginManifest,
|
|
61
|
+
PluginPackage,
|
|
62
|
+
PluginPackageAssets,
|
|
63
|
+
PluginArchiveV2,
|
|
64
|
+
PluginServiceDefinition,
|
|
65
|
+
PluginServiceDependency,
|
|
66
|
+
PluginPermission,
|
|
67
|
+
PluginViewDefinition,
|
|
68
|
+
PluginViewLocation,
|
|
69
|
+
PluginViewLayout,
|
|
70
|
+
PluginStatusBarAlign,
|
|
71
|
+
PluginStatusBarTone,
|
|
72
|
+
PluginStatusBarItem,
|
|
73
|
+
PluginUiTone,
|
|
74
|
+
PluginUiPickItem,
|
|
75
|
+
PluginUiPickOptions,
|
|
76
|
+
PluginUiPromptOptions,
|
|
77
|
+
PluginUiConfirmOptions,
|
|
78
|
+
PluginUiToastOptions,
|
|
79
|
+
PluginSlashCommandDefinition,
|
|
80
|
+
PluginActiveEditorSnapshot,
|
|
81
|
+
PluginFrontmatterPatch,
|
|
82
|
+
PluginCodeBlockRendererDefinition,
|
|
83
|
+
PluginEditorDecorationTone,
|
|
84
|
+
PluginEditorDecoration,
|
|
85
|
+
PluginAttachmentWriteRequest,
|
|
86
|
+
WorkspacePersonalPluginPolicy,
|
|
87
|
+
PluginAssistantToolEffect,
|
|
88
|
+
PluginAssistantToolDefinition,
|
|
89
|
+
PluginAssistantContextProviderDefinition,
|
|
90
|
+
PluginAiCompleteRequest,
|
|
91
|
+
PluginAiStructuredRequest,
|
|
92
|
+
PluginAiCompleteResult,
|
|
93
|
+
PluginAiStructuredResult,
|
|
94
|
+
PluginFileHandlerMode,
|
|
95
|
+
PluginFileHandlerDefinition,
|
|
96
|
+
PluginSettingFieldType,
|
|
97
|
+
PluginSettingField,
|
|
98
|
+
PluginActivationEvent,
|
|
99
|
+
PluginPlatform,
|
|
100
|
+
PluginEngines,
|
|
101
|
+
PluginErrorCode,
|
|
102
|
+
PluginViewNode,
|
|
103
|
+
PluginJson,
|
|
104
|
+
PluginUiBundle,
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
export interface PluginResolvedTheme {
|
|
108
|
+
version: typeof appearanceVersion;
|
|
109
|
+
mode: 'light' | 'dark';
|
|
110
|
+
tokens: Readonly<ThemeTokens>;
|
|
111
|
+
layout?: Readonly<LayoutThemeDefinition>;
|
|
112
|
+
shape: Readonly<{ id: string; label: string; tokens: Readonly<ShapeTokens> }>;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface PluginViewHeader {
|
|
116
|
+
title: string;
|
|
117
|
+
status?: string;
|
|
118
|
+
statusAfter?: string;
|
|
119
|
+
previewInfo?: { label: string; detail: string };
|
|
120
|
+
actions: { id: string; label: string; icon?: 'open' | 'previous' | 'next' | 'minus' | 'plus' | 'fit' | 'info'; disabled?: boolean; accept?: string; group?: string }[];
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export interface PluginAssistantCallContext {
|
|
124
|
+
workspaceId: string;
|
|
125
|
+
activeFileId?: string;
|
|
126
|
+
}
|
|
127
|
+
export interface PluginAssistantContextResult {
|
|
128
|
+
title?: string;
|
|
129
|
+
content: string;
|
|
130
|
+
metadata?: PluginJson;
|
|
131
|
+
}
|
|
132
|
+
export interface PluginHostInfo {
|
|
133
|
+
coreVersion: string;
|
|
134
|
+
apiVersion: string;
|
|
135
|
+
platform: PluginPlatform;
|
|
136
|
+
capabilities: string[];
|
|
137
|
+
}
|
|
138
|
+
export interface TanoPluginError extends Error {
|
|
139
|
+
readonly code: PluginErrorCode;
|
|
140
|
+
readonly retryable: boolean;
|
|
141
|
+
}
|
|
142
|
+
/** Runs inside the custom UI frame; workspace access stays in the plugin's Worker. */
|
|
143
|
+
export interface TanoPluginViewApi {
|
|
144
|
+
/** Read-only host appearance, also applied as CSS variables inside the isolated UI. */
|
|
145
|
+
theme(): PluginResolvedTheme;
|
|
146
|
+
onTheme(handler: (theme: PluginResolvedTheme) => void): () => void;
|
|
147
|
+
postMessage(message: PluginJson): Promise<void>;
|
|
148
|
+
onState(handler: (state: PluginJson) => void): () => void;
|
|
149
|
+
}
|
|
150
|
+
export interface PluginDocument { id: string; path: string; content: string; hash: string }
|
|
151
|
+
export interface PluginObjectSnapshot { id: string; object: WorkspaceObject; hash: string }
|
|
152
|
+
export interface PluginPage<T> { items: T[]; nextCursor?: string; total?: number; skipped?: string[] }
|
|
153
|
+
export interface PluginPageOptions { limit?: number; cursor?: string; direction?: 'asc' | 'desc' }
|
|
154
|
+
export interface PluginDocumentQuery extends PluginPageOptions { query?: string; pathPrefix?: string; readOnly?: boolean; sort?: 'path' | 'name' | 'modified' }
|
|
155
|
+
export interface PluginObjectQuery extends PluginPageOptions { query?: string; type?: string; archived?: boolean; properties?: Record<string, string | number | boolean | null>; sort?: 'name' | 'type' | 'id' }
|
|
156
|
+
export interface PluginRelationQuery extends PluginPageOptions { type?: string; sourceId?: string; targetId?: string }
|
|
157
|
+
export interface PluginDocumentEntry { id: string; name: string; path: string; readOnly: boolean }
|
|
158
|
+
export interface PluginSearchHit extends PluginDocumentEntry { snippet: string; offset: number; hash: string }
|
|
159
|
+
/** Offsets are UTF-16 indices into the exact content returned by read(). Edits must not overlap. */
|
|
160
|
+
export interface PluginTextEdit { from: number; to: number; insert: string }
|
|
161
|
+
export interface PluginAutomationExecution {
|
|
162
|
+
runId: string;
|
|
163
|
+
automationId: string;
|
|
164
|
+
trigger: 'manual' | 'schedule' | 'webhook';
|
|
165
|
+
scheduledAt: string;
|
|
166
|
+
/** Owner-configured task parameters, unchanged by external delivery. */
|
|
167
|
+
payload: PluginJson;
|
|
168
|
+
/** Untrusted external JSON, present only for a Webhook trigger. */
|
|
169
|
+
webhook?: PluginJson;
|
|
170
|
+
}
|
|
171
|
+
/** A server run has no editor UI, device storage, native commands or foreground event subscriptions. */
|
|
172
|
+
export type TanoAutomationApi = Pick<TanoPluginApi, 'context' | 'objects' | 'relations' | 'network' | 'connections'> & {
|
|
173
|
+
documents: Omit<TanoPluginApi['documents'], 'open'>;
|
|
174
|
+
};
|
|
175
|
+
export interface PluginGitEntry { path: string; index: string; worktree: string; originalPath: string | null }
|
|
176
|
+
export interface PluginGitStatus { branch: string | null; detached: boolean; entries: PluginGitEntry[] }
|
|
177
|
+
export interface PluginGitDiff { path: string; staged: boolean; patch: string }
|
|
178
|
+
export interface PluginGitCommit { id: string; shortId: string; author: string; date: string; subject: string }
|
|
179
|
+
export interface PluginGitLog { path: string | null; commits: PluginGitCommit[] }
|
|
180
|
+
export type PluginChangeKind = 'created' | 'updated' | 'deleted';
|
|
181
|
+
export type PluginEvent = { type: 'workspace.changed'; fileId?: string } | {
|
|
182
|
+
type: 'documents.changed' | 'objects.changed' | 'relations.changed';
|
|
183
|
+
changes: { id: string; kind: PluginChangeKind }[];
|
|
184
|
+
/** Too many changes for a delta: discard cached query results and query again. */
|
|
185
|
+
reset?: boolean;
|
|
186
|
+
};
|
|
187
|
+
export interface TanoPluginApi {
|
|
188
|
+
/** Read-only binary snapshot in bounded base64 chunks, plus optional bounded attachment write. */
|
|
189
|
+
attachments: {
|
|
190
|
+
read(fileId: string, offset?: number, revision?: string): Promise<{ path: string; revision: string; offset: number; total: number; chunk: string }>;
|
|
191
|
+
write(request: PluginAttachmentWriteRequest): Promise<{ path: string; name: string; image: boolean; url: string }>;
|
|
192
|
+
};
|
|
193
|
+
context(): Promise<{ workspaceId: string; pluginId: string; settings: Record<string, unknown> }>;
|
|
194
|
+
/** Host runtime version, platform mode, and supported capabilities for graceful feature detection. */
|
|
195
|
+
hostInfo(): Promise<PluginHostInfo>;
|
|
196
|
+
/** Register a graceful cleanup handler invoked before the host terminates this plugin instance. */
|
|
197
|
+
lifecycle: { onDeactivate(handler: () => void | Promise<void>): () => void };
|
|
198
|
+
/** Read-only access to binary assets bundled inside this plugin's own v2 ZIP package (`assets/bin/*`). */
|
|
199
|
+
assets: {
|
|
200
|
+
list(): Promise<string[]>;
|
|
201
|
+
read(path: string): Promise<{ path: string; bytes: number; base64: string }>;
|
|
202
|
+
};
|
|
203
|
+
documents: {
|
|
204
|
+
list(): Promise<PluginDocumentEntry[]>;
|
|
205
|
+
query(options?: PluginDocumentQuery): Promise<PluginPage<PluginDocumentEntry>>;
|
|
206
|
+
/** Literal full-text search. An empty page can still carry nextCursor. */
|
|
207
|
+
search(query: string, options?: Omit<PluginDocumentQuery, 'query' | 'sort'>): Promise<PluginPage<PluginSearchHit>>;
|
|
208
|
+
read(fileId: string): Promise<PluginDocument>;
|
|
209
|
+
write(fileId: string, content: string, baseHash: string): Promise<{ id: string; hash: string; status: 'applied' | 'saved' }>;
|
|
210
|
+
edit(fileId: string, edits: PluginTextEdit[], baseHash: string): Promise<{ id: string; hash: string; status: 'applied' | 'saved' }>;
|
|
211
|
+
create(path: string, content: string): Promise<{ id: string; path: string }>;
|
|
212
|
+
move(fileId: string, destination: string, baseHash: string): Promise<{ id: string; path: string }>;
|
|
213
|
+
trash(fileId: string, baseHash: string): Promise<{ id: string; path: string; trashed: true }>;
|
|
214
|
+
open(fileId: string): Promise<void>;
|
|
215
|
+
frontmatter: {
|
|
216
|
+
read(fileId: string): Promise<{ id: string; hasFrontmatter: boolean; data: Record<string, PluginJson>; hash: string }>;
|
|
217
|
+
update(
|
|
218
|
+
fileId: string,
|
|
219
|
+
patch: PluginFrontmatterPatch,
|
|
220
|
+
baseHash: string,
|
|
221
|
+
): Promise<{ id: string; hash: string; data: Record<string, PluginJson>; status: 'applied' | 'saved' }>;
|
|
222
|
+
};
|
|
223
|
+
};
|
|
224
|
+
/** Active editor selection, single-step undoable cursor transactions, and declarative decorations. */
|
|
225
|
+
editor: {
|
|
226
|
+
active(): Promise<PluginActiveEditorSnapshot | null>;
|
|
227
|
+
insert(text: string): Promise<{ fileId: string; hash: string; status: 'applied' }>;
|
|
228
|
+
replaceSelection(text: string): Promise<{ fileId: string; hash: string; status: 'applied' }>;
|
|
229
|
+
setDecorations(fileId: string, decorations: PluginEditorDecoration[]): Promise<void>;
|
|
230
|
+
clearDecorations(fileId?: string): Promise<void>;
|
|
231
|
+
};
|
|
232
|
+
objects: {
|
|
233
|
+
list(): Promise<PluginObjectSnapshot[]>;
|
|
234
|
+
query(options?: PluginObjectQuery): Promise<PluginPage<PluginObjectSnapshot>>;
|
|
235
|
+
read(objectId: string): Promise<PluginObjectSnapshot>;
|
|
236
|
+
create(object: Pick<WorkspaceObject, 'type' | 'name' | 'description' | 'properties' | 'archived'>): Promise<WorkspaceObject>;
|
|
237
|
+
update(object: WorkspaceObject, baseHash: string): Promise<WorkspaceObject>;
|
|
238
|
+
};
|
|
239
|
+
relations: { list(): Promise<WorkspaceRelation[]>; query(options?: PluginRelationQuery): Promise<PluginPage<WorkspaceRelation>>; add(relation: WorkspaceRelation): Promise<void>; remove(relation: WorkspaceRelation): Promise<void> };
|
|
240
|
+
/** Device-local application state. User content belongs in documents and objects. */
|
|
241
|
+
storage: { get(key: string): Promise<unknown>; set(key: string, value: unknown): Promise<void>; remove(key: string): Promise<void>; usage(): Promise<{ used: number; limit: number }> };
|
|
242
|
+
network: { get(url: string): Promise<string> };
|
|
243
|
+
/** Host injects the current user's separately granted credential; keys never enter the SDK. */
|
|
244
|
+
connections: { request(origin: string, request: PluginConnectionRequest): Promise<PluginConnectionResponse> };
|
|
245
|
+
native: {
|
|
246
|
+
invoke(command: 'git.status', args?: Record<string, never>): Promise<PluginGitStatus>;
|
|
247
|
+
invoke(command: 'git.diff', args: { path: string; staged?: boolean }): Promise<PluginGitDiff>;
|
|
248
|
+
invoke(command: 'git.log', args?: { path?: string; limit?: number }): Promise<PluginGitLog>;
|
|
249
|
+
invoke(command: string, args?: unknown): Promise<unknown>;
|
|
250
|
+
};
|
|
251
|
+
commands: { register(id: string, handler: (context?: { fileId?: string; workspaceId: string; viewAlreadyOpen?: boolean }) => void | Promise<void>): Promise<void> };
|
|
252
|
+
views: {
|
|
253
|
+
/** Host-rendered controls at the right of this view's breadcrumb row. */
|
|
254
|
+
setHeader(id: string, header: PluginViewHeader): Promise<void>;
|
|
255
|
+
render(id: string, tree: PluginViewNode): Promise<void>;
|
|
256
|
+
renderCustom(id: string, state: PluginJson): Promise<void>;
|
|
257
|
+
open(id: string): Promise<void>;
|
|
258
|
+
onAction(id: string, handler: (event: { action: string; values: Record<string, string> }) => void | Promise<void>): () => void;
|
|
259
|
+
onMessage(id: string, handler: (message: PluginJson) => void | Promise<void>): () => void;
|
|
260
|
+
};
|
|
261
|
+
/** Host-managed lightweight UI primitives and status bar items; no iframe frontend required. */
|
|
262
|
+
ui: {
|
|
263
|
+
pick(options: PluginUiPickOptions): Promise<string | null>;
|
|
264
|
+
prompt(options: PluginUiPromptOptions): Promise<string | null>;
|
|
265
|
+
confirm(options: PluginUiConfirmOptions): Promise<boolean>;
|
|
266
|
+
toast(message: string, tone?: PluginUiTone): Promise<void>;
|
|
267
|
+
setStatusBar(item: PluginStatusBarItem): Promise<void>;
|
|
268
|
+
removeStatusBar(id: string): Promise<void>;
|
|
269
|
+
};
|
|
270
|
+
/** Host-managed model completion using the user's configured connection; API keys never enter the sandbox. */
|
|
271
|
+
ai: {
|
|
272
|
+
complete(request: PluginAiCompleteRequest): Promise<PluginAiCompleteResult>;
|
|
273
|
+
structured<T = PluginJson>(request: PluginAiStructuredRequest): Promise<PluginAiStructuredResult<T>>;
|
|
274
|
+
};
|
|
275
|
+
/** Register handlers for manifest-declared assistantTools and assistantContextProviders. */
|
|
276
|
+
assistant: {
|
|
277
|
+
registerTool(
|
|
278
|
+
name: string,
|
|
279
|
+
handler: (args: Record<string, unknown>, context: PluginAssistantCallContext) => PluginJson | Promise<PluginJson>,
|
|
280
|
+
): Promise<void>;
|
|
281
|
+
registerContextProvider(
|
|
282
|
+
id: string,
|
|
283
|
+
handler: (
|
|
284
|
+
query: string,
|
|
285
|
+
context: PluginAssistantCallContext,
|
|
286
|
+
) => PluginAssistantContextResult | string | Promise<PluginAssistantContextResult | string>,
|
|
287
|
+
): Promise<void>;
|
|
288
|
+
};
|
|
289
|
+
/** Stateless cross-plugin RPC message bus (zero shared memory). */
|
|
290
|
+
services: {
|
|
291
|
+
register(
|
|
292
|
+
name: string,
|
|
293
|
+
handler: (payload: PluginJson, caller: { pluginId: string }) => PluginJson | Promise<PluginJson>,
|
|
294
|
+
): Promise<void>;
|
|
295
|
+
call<T = PluginJson>(pluginId: string, service: string, payload?: PluginJson): Promise<T>;
|
|
296
|
+
available(pluginId: string, service: string): Promise<boolean>;
|
|
297
|
+
};
|
|
298
|
+
events: { subscribe(handler: (event: PluginEvent) => void | Promise<void>, options?: { types?: PluginEvent['type'][]; ids?: string[] }): () => void };
|
|
299
|
+
notify(message: string): Promise<void>;
|
|
300
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export const PLUGIN_UNTRUSTED_START = '[UNTRUSTED_PLUGIN_DATA';
|
|
2
|
+
export const PLUGIN_UNTRUSTED_END = '[/UNTRUSTED_PLUGIN_DATA]';
|
|
3
|
+
|
|
4
|
+
/** Escape any spoofed boundary tokens so untrusted tool/plugin output cannot break out. */
|
|
5
|
+
export function sanitizePluginBoundaryText(value: string): string {
|
|
6
|
+
return value
|
|
7
|
+
.replaceAll(PLUGIN_UNTRUSTED_START, '[ESCAPED_UNTRUSTED_PLUGIN_DATA')
|
|
8
|
+
.replaceAll(PLUGIN_UNTRUSTED_END, '[/ESCAPED_UNTRUSTED_PLUGIN_DATA]');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Wrap untrusted plugin/tool-supplied data in explicit boundary markers before sending to an LLM. */
|
|
12
|
+
export function wrapUntrustedPluginData(pluginId: string, source: string, payload: unknown): string {
|
|
13
|
+
const safePluginId = pluginId.replace(/[^a-zA-Z0-9._-]/g, '_');
|
|
14
|
+
const safeSource = source.replace(/[^a-zA-Z0-9._:-]/g, '_');
|
|
15
|
+
const body = typeof payload === 'string' ? payload : JSON.stringify(payload);
|
|
16
|
+
return `${PLUGIN_UNTRUSTED_START} plugin="${safePluginId}" source="${safeSource}"]\n${sanitizePluginBoundaryText(body)}\n${PLUGIN_UNTRUSTED_END}`;
|
|
17
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import {
|
|
2
|
+
emptyCommentFile,
|
|
3
|
+
parseCommentFile,
|
|
4
|
+
rebaseCommentMentions,
|
|
5
|
+
type CommentAnchor,
|
|
6
|
+
type CommentFile,
|
|
7
|
+
type CommentKind,
|
|
8
|
+
type CommentMention,
|
|
9
|
+
type CommentMessage,
|
|
10
|
+
type CommentThread,
|
|
11
|
+
} from '../comments';
|
|
12
|
+
import { commentDataPath } from '../workspace-paths';
|
|
13
|
+
import type { Workspace, WorkspaceAdapter } from '../types';
|
|
14
|
+
|
|
15
|
+
export interface CommentAuthor { id: string; name: string }
|
|
16
|
+
export type CommentStorage = Pick<WorkspaceAdapter, 'refresh' | 'read' | 'write' | 'create'>;
|
|
17
|
+
export interface CommentMessageEdit { messageId: string; expectedBody: string; body: string; mentions?: CommentMention[] }
|
|
18
|
+
export interface CommentMessageRemoval {
|
|
19
|
+
messageId: string;
|
|
20
|
+
expectedBody: string;
|
|
21
|
+
expectedMessages?: { id: string; body: string }[];
|
|
22
|
+
}
|
|
23
|
+
const pendingWrites = new WeakMap<CommentStorage, Map<string, Promise<unknown>>>();
|
|
24
|
+
export type CommentChange =
|
|
25
|
+
| { type: 'start'; id: string; body: string; author: CommentAuthor; anchor?: CommentAnchor; mentions?: CommentMention[]; agentTaskId?: string }
|
|
26
|
+
| { type: 'reply'; threadId: string; id: string; body: string; author: CommentAuthor; replyTo?: string; mentions?: CommentMention[]; agentTaskId?: string }
|
|
27
|
+
| { type: 'resolve'; threadId: string; resolved: boolean }
|
|
28
|
+
| ({ type: 'edit'; threadId: string; authorId: string } & CommentMessageEdit)
|
|
29
|
+
| ({ type: 'delete'; threadId: string; authorId: string } & CommentMessageRemoval)
|
|
30
|
+
| { type: 'reanchor'; threadId: string; expectedBaseHash: string; anchor: CommentAnchor | null };
|
|
31
|
+
|
|
32
|
+
function message(id: string, body: string, author: CommentAuthor, mentions?: CommentMention[], replyTo?: string): CommentMessage {
|
|
33
|
+
return { id, body: body.trim(), authorId: author.id, authorName: author.name, createdAt: Date.now(),
|
|
34
|
+
...(mentions?.length ? { mentions: rebaseCommentMentions(mentions, body, body.trim()) } : {}), ...(replyTo ? { replyTo } : {}) };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Each edit is reapplied to the newest file, so independent replies survive a CAS conflict. */
|
|
38
|
+
export function applyCommentChange(file: CommentFile, change: CommentChange): CommentFile {
|
|
39
|
+
const next = structuredClone(file);
|
|
40
|
+
if (change.type === 'start') {
|
|
41
|
+
if (next.threads.some(thread => thread.id === change.id)) return next;
|
|
42
|
+
if (!change.body.trim()) throw new Error('请输入评论内容');
|
|
43
|
+
if (next.kind === 'annotation' && !change.anchor) throw new Error('请先选择要批注的内容');
|
|
44
|
+
if (next.kind === 'discussion' && change.anchor) throw new Error('整篇讨论不需要局部锚点');
|
|
45
|
+
const createdAt = Date.now();
|
|
46
|
+
next.threads.push({ id: change.id, ...(change.anchor ? { anchor: change.anchor } : {}),
|
|
47
|
+
messages: [{ ...message(change.id, change.body, change.author, change.mentions),
|
|
48
|
+
...(change.agentTaskId ? { agentTaskId: change.agentTaskId } : {}) }], resolved: false,
|
|
49
|
+
detached: false, createdAt });
|
|
50
|
+
} else {
|
|
51
|
+
const thread = next.threads.find(item => item.id === change.threadId);
|
|
52
|
+
if (!thread && change.type === 'delete') return next;
|
|
53
|
+
if (!thread) throw new Error('评论已被移除,请刷新后重试');
|
|
54
|
+
if (change.type === 'reply') {
|
|
55
|
+
if (thread.messages.some(item => item.id === change.id)) return next;
|
|
56
|
+
if (!change.body.trim()) throw new Error('请输入回复内容');
|
|
57
|
+
thread.messages.push({ ...message(change.id, change.body, change.author, change.mentions, change.replyTo),
|
|
58
|
+
...(change.agentTaskId ? { agentTaskId: change.agentTaskId } : {}) });
|
|
59
|
+
} else if (change.type === 'resolve') thread.resolved = change.resolved;
|
|
60
|
+
else if (change.type === 'edit' || change.type === 'delete') {
|
|
61
|
+
const index = thread.messages.findIndex(item => item.id === change.messageId);
|
|
62
|
+
const current = thread.messages[index];
|
|
63
|
+
if (!current && change.type === 'delete') return next;
|
|
64
|
+
if (!current) throw new Error('评论已被移除,请刷新后重试');
|
|
65
|
+
if (current.authorId !== change.authorId) throw new Error('只能编辑或删除自己发表的评论');
|
|
66
|
+
if (current.body !== change.expectedBody) throw new Error('评论已由其他编辑更新,请刷新后重试;输入内容仍保留');
|
|
67
|
+
if (change.type === 'edit') {
|
|
68
|
+
if (!change.body.trim()) throw new Error('请输入评论内容');
|
|
69
|
+
current.mentions = change.mentions === undefined
|
|
70
|
+
? rebaseCommentMentions(current.mentions ?? [], current.body, change.body.trim())
|
|
71
|
+
: rebaseCommentMentions(change.mentions, change.body, change.body.trim());
|
|
72
|
+
current.body = change.body.trim();
|
|
73
|
+
current.updatedAt = Date.now();
|
|
74
|
+
} else if (index === 0) {
|
|
75
|
+
if (!change.expectedMessages || change.expectedMessages.length !== thread.messages.length ||
|
|
76
|
+
thread.messages.some((item, i) => item.id !== change.expectedMessages![i]?.id ||
|
|
77
|
+
item.body !== change.expectedMessages![i]?.body))
|
|
78
|
+
throw new Error('评论或回复已变化,请刷新后重新确认删除');
|
|
79
|
+
next.threads = next.threads.filter(item => item.id !== thread.id);
|
|
80
|
+
} else {
|
|
81
|
+
thread.messages.splice(index, 1);
|
|
82
|
+
for (const item of thread.messages) if (item.replyTo === change.messageId) delete item.replyTo;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
if (!thread.anchor || thread.anchor.baseHash !== change.expectedBaseHash)
|
|
87
|
+
throw new Error('批注锚点已由其他编辑更新,请刷新后重试');
|
|
88
|
+
if (change.anchor) thread.anchor = change.anchor;
|
|
89
|
+
thread.detached = !change.anchor;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return parseCommentFile(JSON.stringify(next), next.kind, next.fileId);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function loadCommentFile(adapter: CommentStorage, kind: CommentKind, fileId: string, workspaceSnapshot?: Workspace) {
|
|
96
|
+
const path = commentDataPath(kind, fileId);
|
|
97
|
+
const workspace = workspaceSnapshot ?? await adapter.refresh();
|
|
98
|
+
if (!workspace.files.some(file => file.kind === 'file' && file.path === path))
|
|
99
|
+
return { file: emptyCommentFile(kind, fileId), hash: null as string | null };
|
|
100
|
+
const snapshot = await adapter.read(path);
|
|
101
|
+
return { file: parseCommentFile(snapshot.content, kind, fileId), hash: snapshot.hash };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export async function saveCommentChange(
|
|
105
|
+
adapter: CommentStorage,
|
|
106
|
+
kind: CommentKind,
|
|
107
|
+
fileId: string,
|
|
108
|
+
change: CommentChange,
|
|
109
|
+
) {
|
|
110
|
+
const path = commentDataPath(kind, fileId);
|
|
111
|
+
let queued = pendingWrites.get(adapter);
|
|
112
|
+
if (!queued) { queued = new Map(); pendingWrites.set(adapter, queued); }
|
|
113
|
+
const previous = queued.get(path);
|
|
114
|
+
const save = async () => {
|
|
115
|
+
await previous?.catch(() => {});
|
|
116
|
+
return writeCommentChange(adapter, kind, fileId, path, change);
|
|
117
|
+
};
|
|
118
|
+
const result = save();
|
|
119
|
+
queued.set(path, result);
|
|
120
|
+
try { return await result; }
|
|
121
|
+
finally { if (queued.get(path) === result) queued.delete(path); }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function writeCommentChange(
|
|
125
|
+
adapter: CommentStorage, kind: CommentKind, fileId: string, path: string, change: CommentChange,
|
|
126
|
+
) {
|
|
127
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
128
|
+
const current = await loadCommentFile(adapter, kind, fileId);
|
|
129
|
+
const updated = applyCommentChange(current.file, change);
|
|
130
|
+
const content = `${JSON.stringify(updated, null, 2)}\n`;
|
|
131
|
+
if (current.hash) {
|
|
132
|
+
const result = await adapter.write(path, content, current.hash);
|
|
133
|
+
if (result.status === 'saved') return updated;
|
|
134
|
+
if (result.status === 'missing') continue;
|
|
135
|
+
} else {
|
|
136
|
+
try { await adapter.create(path, content); return updated; }
|
|
137
|
+
catch (error) {
|
|
138
|
+
const refreshed = await adapter.refresh();
|
|
139
|
+
if (!refreshed.files.some(file => file.path === path)) throw error;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
throw new Error('评论同时被修改,请稍后重试;输入内容仍保留');
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function visibleThreads(file: CommentFile): CommentThread[] {
|
|
147
|
+
return file.threads.filter(thread => !thread.detached);
|
|
148
|
+
}
|