@tano.page/protocol 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.
@@ -0,0 +1,129 @@
1
+ {
2
+ "starters": {
3
+ "summary": "摘要這篇筆記",
4
+ "polish": "潤飾這篇筆記",
5
+ "translate": "翻譯這篇筆記",
6
+ "tasks": "擷取待辦事項"
7
+ },
8
+ "progress": {
9
+ "starting": "正在啟動 CLI",
10
+ "connecting": "正在連線模型",
11
+ "thinking": "正在思考",
12
+ "generating": "正在生成",
13
+ "retrying": "連線中斷,正在重試",
14
+ "validating": "正在核對回答",
15
+ "protocol": "正在自動適配介面協議",
16
+ "maxTokens": "正在自動適配輸出上限引數",
17
+ "usage": "正在自動適配流式用量引數",
18
+ "reading": "正在讀取參考文件",
19
+ "round": "正在整理結果 · 第 {0} 輪",
20
+ "waiting": "等待輸入",
21
+ "executing": "正在執行 · {0}"
22
+ },
23
+ "tools": {
24
+ "ask_user": "詢問使用者",
25
+ "propose_create": "建立文件建議",
26
+ "propose_edit": "修改文件建議",
27
+ "propose_delete": "刪除文件建議",
28
+ "propose_rename": "重新命名文件建議",
29
+ "propose_move": "移動文件建議",
30
+ "edit_document": "修改文件",
31
+ "create_document": "建立文件",
32
+ "delete_document": "刪除文件",
33
+ "rename_document": "重新命名文件",
34
+ "move_document": "移動文件",
35
+ "create_event": "建立事件",
36
+ "create_relation": "新增關係",
37
+ "update_task": "修改任務",
38
+ "update_assignment": "調整負責人",
39
+ "change_relation": "維護關係",
40
+ "search_documents": "搜尋文件",
41
+ "read_document": "讀取文件",
42
+ "read_workspace_objects": "讀取工作區物件",
43
+ "read_reference_context": "讀取引用",
44
+ "query_tasks": "查詢任務",
45
+ "propose_event": "建立事件建議",
46
+ "propose_relation": "建立關係建議",
47
+ "propose_task_update": "修改任務建議",
48
+ "propose_assignment": "調整負責人建議",
49
+ "propose_relation_change": "維護關係建議",
50
+ "inspect_plugins": "檢視已啟用外掛",
51
+ "inspect_plugin_logs": "檢視外掛執行日誌",
52
+ "open_plugin_view": "開啟外掛檢視"
53
+ },
54
+ "result": {
55
+ "toolCall": "工具呼叫",
56
+ "stoppedSaved": "已停止,已完成的修改已保留",
57
+ "stoppedUnchanged": "已停止,未修改原文",
58
+ "conflict": "修改存在衝突或結果待核對,請在對話中檢視",
59
+ "partial": "部分修改已儲存;",
60
+ "failed": "請求失敗,請在對話中檢視詳情",
61
+ "review": "已生成修改建議,請在對話中審閱",
62
+ "completed": "我已完成更新。",
63
+ "empty": "助理未返回內容,可在對話中重試"
64
+ },
65
+ "demo": {
66
+ "clarifying": "我會先了解這篇文件的目標,再根據你的回答安排內容。你也可以跳過暫時不確定的問題。",
67
+ "topic": "這篇文件想寫什麼?",
68
+ "audience": "這篇文件寫給誰看?",
69
+ "audienceOptions": [
70
+ "自己",
71
+ "團隊",
72
+ "客戶"
73
+ ],
74
+ "goal": "你希望讀者瞭解什麼,或採取什麼行動?",
75
+ "format": "你想要完整草稿,還是先看大綱?",
76
+ "formatOptions": [
77
+ "完整草稿",
78
+ "先看大綱"
79
+ ],
80
+ "context": "有哪些筆記、資料或要求需要參考?",
81
+ "missingTopic": "還不知道這篇文件要寫什麼,文件保持空白。你可以隨時告訴我主題,我再繼續起草。",
82
+ "draft": "## 草稿(瀏覽器示範)\n\n主題:{0}\n\n## 主要內容\n\n待補充\n\n## 下一步\n\n- [ ] 補充具體資訊\n\n> 這是模擬草稿,用於示範詢問使用者後繼續執行。\n",
83
+ "draftReason": "根據使用者回答示範初始化當前文件。",
84
+ "record": "模擬記錄",
85
+ "tablePreview": "瀏覽器示範將新增一條模擬記錄,用於驗證資料表編輯。[来源:S1]",
86
+ "tableReason": "瀏覽器模擬資料表編輯,新增一條模擬記錄。",
87
+ "editPreview": "正在生成一項模擬修改。[来源:S1]",
88
+ "editAddition": "這是一條模擬補充內容。",
89
+ "editReason": "瀏覽器模擬修改,用於檔案操作示範。",
90
+ "saved": "模擬修改已儲存到瀏覽器示範儲存,可在檔案變更清單中檢視。",
91
+ "review": "建議尚未寫入,採納後才會儲存。",
92
+ "unknown": "此次操作結果待核對,請檢查檔案變更清單。",
93
+ "failed": "此次操作未完成,請檢查檔案變更清單中的原因。",
94
+ "read": "瀏覽器模擬回答:已讀取「{0}」。",
95
+ "noSources": "瀏覽器模擬回答:當前沒有參考文件。"
96
+ },
97
+ "chatAction": "對話",
98
+ "activity": {
99
+ "title": "思考與執行過程",
100
+ "working": "正在思考與執行",
101
+ "calls": "{0} 次工具呼叫",
102
+ "failures": "{0} 次失敗",
103
+ "running": "執行中",
104
+ "succeeded": "已完成",
105
+ "failed": "失敗",
106
+ "interrupted": "已中斷"
107
+ },
108
+ "run": {
109
+ "waiting": "等待你的回答",
110
+ "incomplete": "任務尚未確認全部完成,未獲得完整的最終回答。",
111
+ "succeeded": "已完成 {0} 次工具呼叫",
112
+ "failed": "失敗 {0} 次",
113
+ "interrupted": "中斷 {0} 次",
114
+ "saved": "已儲存的修改",
115
+ "review": "待審閱的建議",
116
+ "uncertain": "尚待核對的操作",
117
+ "reasons": {
118
+ "completed": "本次執行已結束",
119
+ "cancelled": "已停止",
120
+ "interrupted": "上次執行已中斷",
121
+ "round_limit": "已達到請求輪數上限",
122
+ "no_progress": "已暫停:連續多輪未取得進展",
123
+ "output_limit": "回答達到輸出上限",
124
+ "incomplete": "響應未完整返回",
125
+ "empty_response": "未收到最終回答",
126
+ "error": "本次執行未完成"
127
+ }
128
+ }
129
+ }
@@ -0,0 +1,175 @@
1
+ import { canonicalPluginJson, matchesPluginPathScopes, pluginRecord } from '../extensions';
2
+ import type { WorkspaceObject } from '../objects';
3
+ import { isMarkdown } from '../paths';
4
+ import type { WorkspaceRelation } from '../relations';
5
+ import type { Workspace } from '../types';
6
+ import { isWorkspaceInternalPath } from '../workspace-paths';
7
+ import type {
8
+ PluginDocumentEntry,
9
+ PluginEvent,
10
+ PluginPage,
11
+ PluginPageOptions,
12
+ PluginTextEdit,
13
+ } from './plugin-sdk';
14
+
15
+ export async function assistantHash(content: string) {
16
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(content));
17
+ return [...new Uint8Array(digest)].map(byte => byte.toString(16).padStart(2, '0')).join('');
18
+ }
19
+
20
+ export function pluginQueryOptions(value: unknown, allowed: readonly string[]) {
21
+ const options = value === undefined ? {} : value;
22
+ if (!pluginRecord(options) || Object.keys(options).some(key => ![...allowed, 'limit', 'cursor', 'direction'].includes(key))) throw new Error('查询参数无效');
23
+ if (options.limit !== undefined && (!Number.isInteger(options.limit) || Number(options.limit) < 1 || Number(options.limit) > 100)) throw new Error('每页数量必须为 1 至 100');
24
+ if (options.cursor !== undefined && (typeof options.cursor !== 'string' || options.cursor.length > 100)) throw new Error('分页游标无效');
25
+ if (options.direction !== undefined && !['asc', 'desc'].includes(String(options.direction))) throw new Error('查询排序方向无效');
26
+ return options;
27
+ }
28
+
29
+ export function queryText(value: unknown, limit = 200): string | undefined {
30
+ if (value === undefined) return undefined;
31
+ if (typeof value !== 'string' || value.length > limit) throw new Error('查询文本无效');
32
+ return value;
33
+ }
34
+
35
+ export function queryBoolean(value: unknown): boolean | undefined {
36
+ if (value !== undefined && typeof value !== 'boolean') throw new Error('查询条件必须为布尔值');
37
+ return value as boolean | undefined;
38
+ }
39
+
40
+ export const compareQueryText = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;
41
+
42
+ /** Cursors never contain workspace data and are bound to an execution instance and query revision. */
43
+ export class PluginQueryPager {
44
+ private cursors = new Map<string, { scope: string; signature: string; offset: number; expires: number }>();
45
+ clear() { this.cursors.clear(); }
46
+ async page<T, R = T>(scope: string, method: string, options: PluginPageOptions, revision: unknown, rows: T[],
47
+ project: (row: T) => Promise<R | undefined> = async row => row as unknown as R,
48
+ assertCurrent: () => void = () => {}, scanLimit = Number.POSITIVE_INFINITY): Promise<PluginPage<R>> {
49
+ const { cursor, ...query } = options;
50
+ const signature = await assistantHash(canonicalPluginJson([method, query, revision]));
51
+ assertCurrent();
52
+ for (const [key, value] of this.cursors) if (value.expires < Date.now()) this.cursors.delete(key);
53
+ const previous = cursor ? this.cursors.get(cursor) : undefined;
54
+ if (cursor && (!previous || previous.scope !== scope || previous.signature !== signature)) throw new Error('查询结果已变化或分页已过期,请从第一页重新查询');
55
+ let offset = previous?.offset ?? 0, scanned = 0, bytes = 0;
56
+ const items: R[] = [], limit = options.limit ?? 50;
57
+ while (offset < rows.length && items.length < limit && scanned < scanLimit) {
58
+ assertCurrent();
59
+ const item = await project(rows[offset]!);
60
+ assertCurrent();
61
+ if (item !== undefined) {
62
+ const size = new TextEncoder().encode(JSON.stringify(item)).length;
63
+ if (size > 256 * 1024) throw new Error('单条查询结果超过 256 KB,请缩小对象内容');
64
+ if (bytes + size > 256 * 1024) break;
65
+ items.push(item); bytes += size;
66
+ }
67
+ offset++; scanned++;
68
+ }
69
+ const result: PluginPage<R> = { items };
70
+ if (scanLimit === Number.POSITIVE_INFINITY) result.total = rows.length;
71
+ if (offset < rows.length) {
72
+ result.nextCursor = crypto.randomUUID();
73
+ this.cursors.set(result.nextCursor, { scope, signature, offset, expires: Date.now() + 60_000 });
74
+ if (this.cursors.size > 128) this.cursors.delete(this.cursors.keys().next().value!);
75
+ }
76
+ return result;
77
+ }
78
+ }
79
+
80
+ export function applyPluginTextEdits(content: string, value: unknown): string {
81
+ if (!Array.isArray(value) || !value.length || value.length > 100) throw new Error('编辑事务需要 1 至 100 个修改');
82
+ const edits: PluginTextEdit[] = value.map(edit => {
83
+ if (!pluginRecord(edit) || Object.keys(edit).some(key => !['from', 'to', 'insert'].includes(key)) ||
84
+ !Number.isInteger(edit.from) || !Number.isInteger(edit.to) || Number(edit.from) < 0 || Number(edit.to) < Number(edit.from) ||
85
+ Number(edit.to) > content.length || typeof edit.insert !== 'string') throw new Error('编辑范围无效');
86
+ const splitsSurrogate = (offset: number) => /[\uD800-\uDBFF]/.test(content[offset - 1] ?? '') && /[\uDC00-\uDFFF]/.test(content[offset] ?? '');
87
+ if (splitsSurrogate(Number(edit.from)) || splitsSurrogate(Number(edit.to))) throw new Error('编辑范围不能拆分 Unicode 字符');
88
+ return edit as unknown as PluginTextEdit;
89
+ }).sort((a, b) => a.from - b.from || a.to - b.to);
90
+ for (let i = 1; i < edits.length; i++) if (edits[i]!.from < edits[i - 1]!.to || edits[i]!.from === edits[i - 1]!.from) throw new Error('编辑范围不能重叠');
91
+ let next = content;
92
+ for (const edit of edits.reverse()) next = next.slice(0, edit.from) + edit.insert + next.slice(edit.to);
93
+ if (next.length > 512000) throw new Error('编辑后的文档超过大小限制');
94
+ return next;
95
+ }
96
+
97
+ /** Deltas expose identities only; permission checks occur again before delivery in the host. */
98
+ export function pluginChanges(type: Exclude<PluginEvent['type'], 'workspace.changed'>, before: Map<string, string>, after: Map<string, string>): PluginEvent | undefined {
99
+ const changes: { id: string; kind: 'created' | 'updated' | 'deleted' }[] = [];
100
+ for (const [id, stamp] of after) if (before.get(id) !== stamp) changes.push({ id, kind: before.has(id) ? 'updated' : 'created' });
101
+ for (const id of before.keys()) if (!after.has(id)) changes.push({ id, kind: 'deleted' });
102
+ if (!changes.length) return;
103
+ return changes.length > 100 ? { type, changes: [], reset: true } : { type, changes };
104
+ }
105
+
106
+ export interface PluginQueryContext {
107
+ workspace: Workspace;
108
+ objects: { object: WorkspaceObject; snapshot: { hash: string } }[];
109
+ relations: WorkspaceRelation[];
110
+ drafts: { id: string; content: string; conflict?: unknown; missing: boolean }[];
111
+ read(path: string): Promise<{ content: string }>;
112
+ assertCurrent(): void;
113
+ /** Host revision, for stores whose timestamp and size alone do not identify a content version. */
114
+ revision?: unknown;
115
+ }
116
+
117
+ export async function queryPluginData(method: string, params: Record<string, unknown>, pager: PluginQueryPager, context: PluginQueryContext) {
118
+ const { workspace, objects, relations, drafts, assertCurrent } = context;
119
+ const scope = `${workspace.id}:${String(params.queryScope)}`;
120
+ const pathScopes = Array.isArray(params.pathScopes) ? (params.pathScopes as string[]) : undefined;
121
+ if (method === 'documents.query' || method === 'documents.search') {
122
+ const options = pluginQueryOptions(params.options, method === 'documents.search' ? ['query', 'pathPrefix', 'readOnly'] : ['query', 'pathPrefix', 'readOnly', 'sort']);
123
+ const query = queryText(options.query) ?? '', prefix = queryText(options.pathPrefix, 1000) ?? '', readOnly = queryBoolean(options.readOnly);
124
+ if (options.sort !== undefined && !['path', 'name', 'modified'].includes(String(options.sort))) throw new Error('文档排序字段无效');
125
+ if (method === 'documents.search' && !query.trim()) throw new Error('请输入搜索文本');
126
+ const rows = workspace.files.filter(row => row.kind === 'file' && isMarkdown(row.path) && !isWorkspaceInternalPath(row.path) &&
127
+ matchesPluginPathScopes(row.path, pathScopes) &&
128
+ row.path.startsWith(prefix) && (readOnly === undefined || !!(workspace.readOnly || row.readOnly) === readOnly) &&
129
+ (method === 'documents.search' || `${row.path}\n${row.name}`.toLowerCase().includes(query.toLowerCase())));
130
+ const sort = String(options.sort ?? 'path'), direction = options.direction === 'desc' ? -1 : 1;
131
+ rows.sort((a, b) => direction * ((sort === 'modified' ? a.modified - b.modified : compareQueryText(sort === 'name' ? a.name : a.path, sort === 'name' ? b.name : b.path)) || compareQueryText(a.id, b.id)));
132
+ const metadata = (row: typeof rows[number]): PluginDocumentEntry => ({ id: row.id, name: row.name, path: row.path, readOnly: !!(workspace.readOnly || row.readOnly) });
133
+ const revision = [context.revision ?? null, rows.map(row => [row.id, row.path, row.name, row.modified, row.size, metadata(row).readOnly]),
134
+ method === 'documents.search' ? drafts.map(row => [row.id, row.content, !!row.conflict, row.missing]) : []];
135
+ if (method === 'documents.query') return pager.page(scope, method, options as PluginPageOptions, revision, rows, async row => metadata(row), assertCurrent);
136
+ const draftsById = new Map(drafts.map(draft => [draft.id, draft]));
137
+ const skipped: string[] = [];
138
+ const pattern = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'iu');
139
+ const page = await pager.page(scope, method, options as PluginPageOptions, revision, rows, async row => {
140
+ const draft = draftsById.get(row.id);
141
+ if (draft?.conflict || draft?.missing || (!draft && row.size > 512000)) { skipped.push(row.id); return; }
142
+ assertCurrent();
143
+ const content = draft?.content ?? (await context.read(row.path)).content;
144
+ assertCurrent();
145
+ if (content.length > 512000) { skipped.push(row.id); return; }
146
+ const match = pattern.exec(content);
147
+ if (!match) return;
148
+ return { ...metadata(row), snippet: content.slice(Math.max(0, match.index - 60), match.index + query.length + 120), offset: match.index, hash: await assistantHash(content) };
149
+ }, assertCurrent, 25);
150
+ return { ...page, skipped };
151
+ }
152
+ if (method === 'objects.query') {
153
+ const options = pluginQueryOptions(params.options, ['query', 'type', 'archived', 'properties', 'sort']);
154
+ const query = (queryText(options.query) ?? '').toLowerCase(), type = queryText(options.type), archived = queryBoolean(options.archived);
155
+ if (options.sort !== undefined && !['name', 'type', 'id'].includes(String(options.sort))) throw new Error('对象排序字段无效');
156
+ const properties = options.properties ?? {};
157
+ if (!pluginRecord(properties) || Object.keys(properties).length > 10 || Object.entries(properties).some(([key, value]) => key.length > 100 ||
158
+ (value !== null && !['string', 'number', 'boolean'].includes(typeof value)) || (typeof value === 'number' && !Number.isFinite(value)) ||
159
+ (typeof value === 'string' && value.length > 200))) throw new Error('属性筛选只支持最多 10 个标量条件');
160
+ const rows = objects.filter(({ object }) => (!type || object.type === type) && (archived === undefined || object.archived === archived) &&
161
+ `${object.name}\n${object.description}`.toLowerCase().includes(query) && Object.entries(properties).every(([key, value]) => Object.hasOwn(object.properties, key) && object.properties[key] === value));
162
+ const sort = (options.sort ?? 'name') as 'name' | 'type' | 'id', direction = options.direction === 'desc' ? -1 : 1;
163
+ rows.sort((a, b) => direction * (compareQueryText(a.object[sort], b.object[sort]) || compareQueryText(a.object.id, b.object.id)));
164
+ return pager.page(scope, method, options as PluginPageOptions, rows.map(row => [row.object.id, row.snapshot.hash]), rows,
165
+ async row => ({ id: row.object.id, object: JSON.parse(JSON.stringify(row.object)), hash: row.snapshot.hash }), assertCurrent);
166
+ }
167
+ if (method === 'relations.query') {
168
+ const options = pluginQueryOptions(params.options, ['type', 'sourceId', 'targetId']);
169
+ const type = queryText(options.type), source = queryText(options.sourceId), target = queryText(options.targetId);
170
+ const rows = relations.filter(row => (!type || row.type === type) && (!source || row.source.id === source) && (!target || row.target.id === target));
171
+ rows.sort((a, b) => (options.direction === 'desc' ? -1 : 1) * compareQueryText(a.id, b.id));
172
+ return pager.page(scope, method, options as PluginPageOptions, canonicalPluginJson(rows), rows, async row => JSON.parse(JSON.stringify(row)), assertCurrent);
173
+ }
174
+ throw new Error('不支持此查询');
175
+ }
@@ -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
+ }
package/src/objects.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { FileEntry } from './types';
2
2
  import { isMarkdown } from './paths';
3
- import { isWorkspaceInternalPath } from './workspace-paths';
3
+ import { isWorkspaceInternalPath, objectDirectory } from './workspace-paths';
4
4
  import { isShortId } from './short-id';
5
5
  import { coreObjectTypes, objectTypeRegistry, validObjectType } from './object-types';
6
6
  import { parseTaskReview } from './task-review';
@@ -35,8 +35,8 @@ export interface ReferenceTarget extends ReferenceIdentity {
35
35
  properties?: Record<string, unknown>;
36
36
  }
37
37
  export const objectSuffix = '.tano.json';
38
- export const isObjectPath = (path: string) => path.endsWith(objectSuffix) &&
39
- (!path.startsWith('.tano/') || path.startsWith('.tano/objects/'));
38
+ export const isObjectPath = (path: string) =>
39
+ path.startsWith(`${objectDirectory}/`) && path.endsWith(objectSuffix);
40
40
  export const referenceTypeLabel = (type: string) =>
41
41
  objectTypeRegistry.get(type)?.label ?? `未启用类型(${type})`;
42
42
  export function parseObject(content: string): WorkspaceObject {