@tano.page/protocol 0.0.0-stage → 0.9.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Zixi Wang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@tano.page/protocol",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.9.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./src/index.ts",
7
+ "./frontmatter": "./src/frontmatter.ts",
8
+ "./markdown-file-metadata": "./src/markdown-file-metadata.ts"
9
+ },
10
+ "license": "MIT",
11
+ "files": [
12
+ "src",
13
+ "LICENSE"
14
+ ],
15
+ "dependencies": {
16
+ "yaml": "^2.9.1"
17
+ },
18
+ "publishConfig": {
19
+ "registry": "https://registry.npmjs.org/",
20
+ "access": "public"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/Dramwig/Tano.git"
25
+ },
26
+ "tanoCore": {
27
+ "sourceCommit": "18c6d69c1b0c818a84519bd6e051259cd485410c",
28
+ "version": "0.9.0",
29
+ "importName": "@tano/protocol"
30
+ }
31
+ }
@@ -0,0 +1,70 @@
1
+ import type { ObjectViewQuery } from './view-engine';
2
+ import type { WorkspaceObject } from './objects';
3
+ import type { DataField, DataRow, DataView } from './data-tables';
4
+ import type { CellResult } from './data-table-query';
5
+ import type { WorkspaceRelation } from './relations';
6
+ import type { FileDatabaseQuery } from './file-database';
7
+ import type { FileMetadata } from './file-metadata';
8
+
9
+ export const AGENT_GATEWAY_VERSION = 1;
10
+ /** Set by the host process, never by workspace content or tool arguments. */
11
+ export interface AgentGatewayPolicy {
12
+ access: 'read' | 'review' | 'write';
13
+ /** Public-file directory prefixes. An empty prefix authorizes the whole workspace. */
14
+ directories: string[];
15
+ /** Independently authorized semantic record types. */
16
+ objectTypes: string[];
17
+ }
18
+ export interface GatewayRevision {
19
+ workspaceId: string;
20
+ fileId: string;
21
+ path: string;
22
+ sha256: string;
23
+ }
24
+ export interface GatewayPage<T> { items: T[]; total: number; nextOffset: number | null }
25
+ export interface GatewayFileSnapshot extends GatewayRevision { encoding: 'utf8' | 'base64'; content: string }
26
+ export interface GatewayFileInfo extends GatewayRevision { size: number; modified: number; handler: string; metadata: FileMetadata; metadataHash: string | null }
27
+ export interface GatewayObjectSnapshot extends GatewayRevision { object: WorkspaceObject }
28
+ export interface GatewayTablePage extends GatewayRevision, GatewayPage<DataRow & { computed: Record<string, CellResult> }> {
29
+ tableId: string; name: string; fields: DataField[]; view: DataView;
30
+ }
31
+ export interface GatewayEdit {
32
+ /** Existing resources must use the ID and hash returned by a read. */
33
+ fileId?: string;
34
+ path: string;
35
+ expectedHash: string | null;
36
+ content: string;
37
+ reason: string;
38
+ }
39
+ export interface GatewayBatch {
40
+ operationId: string;
41
+ edits: GatewayEdit[];
42
+ }
43
+ export interface GatewayOperation {
44
+ operationId: string;
45
+ atomic: false;
46
+ written: boolean;
47
+ items: { proposalId: string; status: string; written: boolean }[];
48
+ }
49
+ /** Transport-neutral SDK. The transport returns decoded tool JSON or rejects on isError. */
50
+ export class AgentGatewayClient {
51
+ constructor(private readonly call: (name: string, args: Record<string, unknown>) => Promise<unknown>) {}
52
+ static fromMcp(client: { callTool(request: { name: string; arguments: Record<string, unknown> }): Promise<unknown> }) {
53
+ return new AgentGatewayClient(async (name, args) => {
54
+ const response = await client.callTool({ name, arguments: args }) as { isError?: boolean; content?: { type: string; text?: string }[] };
55
+ const body = response.content?.find(item => item.type === 'text')?.text;
56
+ if (!body || response.isError) throw new Error(body ?? 'Gateway returned no result');
57
+ return JSON.parse(body);
58
+ });
59
+ }
60
+ capabilities() { return this.call('tano_gateway_capabilities', {}) as Promise<{ version: number; workspaceId: string; policy: AgentGatewayPolicy; batchAtomic: false }> ; }
61
+ files(query = '', offset = 0, limit = 100, database?: FileDatabaseQuery) { return this.call('tano_query_files', { query, offset, limit, database }) as Promise<GatewayPage<GatewayFileInfo> & { complete: boolean; errors: { path: string; error: string }[] }>; }
62
+ read(fileId: string) { return this.call('tano_read_file', { fileId }) as Promise<GatewayFileSnapshot>; }
63
+ objects(query?: ObjectViewQuery, offset = 0, limit = 100) { return this.call('tano_query_objects', { query, offset, limit }) as Promise<GatewayPage<GatewayObjectSnapshot>>; }
64
+ table(fileId: string, viewId?: string, offset = 0, limit = 100) { return this.call('tano_query_table', { fileId, viewId, offset, limit }) as Promise<GatewayTablePage>; }
65
+ relations() { return this.call('tano_query_relations', {}) as Promise<{ workspaceId: string; sha256: string | null; relations: WorkspaceRelation[] }>; }
66
+ propose(batch: GatewayBatch) { return this.call('tano_propose_changes', { ...batch }) as Promise<GatewayOperation>; }
67
+ operation(operationId: string) { return this.call('tano_get_operation', { operationId }) as Promise<GatewayOperation>; }
68
+ activity(offset = 0, limit = 100) { return this.call('tano_list_activity', { offset, limit }); }
69
+ activityEntry(id: string) { return this.call('tano_read_activity', { id }); }
70
+ }
package/src/agent.ts ADDED
@@ -0,0 +1,23 @@
1
+ export interface AgentChange {
2
+ id: string;
3
+ path: string;
4
+ client: string;
5
+ instanceId: string;
6
+ operation: 'create' | 'write';
7
+ createdAt: number;
8
+ status: 'prepared' | 'applied' | 'failed';
9
+ beforeHash: string | null;
10
+ afterHash: string;
11
+ error: string;
12
+ }
13
+ export interface AgentChangeDetail extends AgentChange {
14
+ beforeContent: string | null;
15
+ afterContent: string | null;
16
+ }
17
+ export interface AgentSetup {
18
+ config: { mcpServers: Record<string, { command: string; args: string[] }> };
19
+ bundled: boolean;
20
+ }
21
+ export function workspaceAgentGuide(name: string, purpose: string, language: 'zh' | 'en') {
22
+ return `# ${name.replace(/[\r\n]/g, ' ').trim() || 'Tano workspace'}\n\n${purpose.trim() ? `${purpose.trim()}\n\n` : ''}## Shared workspace\n\nThis folder is shared by humans and agents using Tano / 同页. It is a **File-Native Workspace**: real files are the content source of truth, Objects add stable semantics and relations, and Views are rebuildable projections.\n\n- ${language === 'zh' ? '默认使用简体中文回复和撰写正文,保留已有文档的语言。' : 'Use English by default; preserve each existing document’s language.'}\n- Read the current file before editing. Keep unrelated text, YAML frontmatter, image references and formatting intact.\n- Use stable workspace and file IDs for references; paths are display locations and may change.\n- Other people or agents may be editing at the same time. If the file changes after you read it, reread and merge your intended changes. Never silently replace newer content.\n- With Tano MCP, use the sha256 returned by tano_read_document as expectedHash for tano_write_document. A mismatch requires rereading and reviewing the changes.\n- Prefer small, focused changes. Keep files UTF-8 and use relative links for workspace attachments.\n- Do not copy file contents into an Object or View. Link back to the source file and preserve its revision.\n- Do not edit .tano/config.json, Tano application caches, conflict copies or recovered drafts unless explicitly requested.\n- Do not delete or rename documents unless requested. Preserve both versions when resolving a conflict.\n- Summarize changed paths and the reason for each change. Do not claim tests or checks that were not run.\n\n## Attribution\n\nOrdinary filesystem changes have an unknown author. Tano MCP records its own tool calls and content hashes; the connecting client name is self-reported and does not prove a person or model’s identity.\n`;
23
+ }
@@ -0,0 +1,330 @@
1
+ export const ASSISTANT_PROTOCOL_VERSION = 12;
2
+
3
+
4
+ export type AssistantReasoningEffort = 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra';
5
+ export type AssistantReasoningSelection = AssistantReasoningEffort | 'cli-default';
6
+
7
+ export function isAssistantReasoningSelection(value: unknown): value is AssistantReasoningSelection {
8
+ return typeof value === 'string' && ['cli-default', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'].includes(value);
9
+ }
10
+
11
+ export interface AssistantConnection {
12
+ id: string;
13
+ name: string;
14
+ kind?: 'api' | 'codex-cli' | 'claude-cli';
15
+ cliPath?: string;
16
+ /** Legacy connection default, used when restoring a conversation without its own selection. */
17
+ reasoningEffort?: AssistantReasoningEffort;
18
+ endpoint: string;
19
+ protocol?: 'chat-completions' | 'responses';
20
+ autoAdapt?: boolean;
21
+ tools: boolean;
22
+ maxOutputTokens: number;
23
+ hasKey: boolean;
24
+ /** Configured by the hosting application. */
25
+ managed?: boolean;
26
+ }
27
+
28
+ export interface AssistantSource {
29
+ id: string;
30
+ workspaceId: string;
31
+ fileId: string;
32
+ path: string;
33
+ content: string;
34
+ hash: string;
35
+ origin: 'draft' | 'disk';
36
+ selection?: { text: string; from?: number; to?: number };
37
+ }
38
+
39
+ export type AssistantProposalStatus = 'ready' | 'applying' | 'applied' | 'rejected' | 'conflicted' | 'unknown';
40
+ export interface AssistantPreview {
41
+ before: string;
42
+ after: string;
43
+ diskHash: string | null;
44
+ path: string;
45
+ destination?: string;
46
+ }
47
+ export interface AssistantProposal {
48
+ id: string;
49
+ runId: string;
50
+ workspaceId: string;
51
+ kind: 'edit' | 'create' | 'delete' | 'rename' | 'move' | 'object' | 'relation';
52
+ fileId?: string;
53
+ path: string;
54
+ destination?: string;
55
+ base: string;
56
+ content: string;
57
+ reason: string;
58
+ status: AssistantProposalStatus;
59
+ /** Omitted on legacy and manually reviewed proposals. */
60
+ execution?: 'direct';
61
+ preview?: AssistantPreview;
62
+ applied?: { before: string; after: string; hash: string; fileId: string };
63
+ error?: string;
64
+ /** Once published, per-edit review belongs to the portable document records. */
65
+ suggestionGroupId?: string;
66
+ }
67
+
68
+ /** Application-recorded receipts; never inferred from the model's answer. */
69
+ export interface AssistantToolResult {
70
+ name: string;
71
+ status: 'succeeded' | 'failed';
72
+ proposalId?: string;
73
+ error?: string;
74
+ }
75
+
76
+ /** Ordered display events. Text ranges refer to content; tool outcomes refer to real receipts. */
77
+ export type AssistantActivity =
78
+ | { kind: 'text'; start: number; end: number; phase: 'pending' | 'working' | 'answer' }
79
+ | { kind: 'tool'; name: string; status: 'running' | 'succeeded' | 'failed' | 'interrupted'; resultIndex?: number }
80
+ | { kind: 'input'; inputId: string };
81
+
82
+ export type AssistantTerminationReason = 'completed' | 'cancelled' | 'interrupted' | 'round_limit' | 'no_progress' | 'output_limit' | 'incomplete' | 'empty_response' | 'error';
83
+
84
+ export interface AssistantQuestion {
85
+ id: string;
86
+ question: string;
87
+ options?: string[];
88
+ }
89
+ export interface AssistantQuestionAnswer {
90
+ questionId: string;
91
+ /** Null means the user explicitly skipped this question. */
92
+ answer: string | null;
93
+ }
94
+ export interface AssistantUserInput {
95
+ id: string;
96
+ questions: AssistantQuestion[];
97
+ answers?: AssistantQuestionAnswer[];
98
+ status: 'pending' | 'answered' | 'cancelled';
99
+ /** Position in the assistant's text where this interaction occurred. */
100
+ contentOffset: number;
101
+ }
102
+
103
+ export function parseAssistantQuestions(value: unknown): AssistantQuestion[] {
104
+ if (!Array.isArray(value) || !value.length || value.length > 8) throw new Error('一次可询问 1 至 8 个问题');
105
+ const ids = new Set<string>();
106
+ return value.map(item => {
107
+ if (!item || typeof item !== 'object' || Array.isArray(item) ||
108
+ Object.keys(item).some(key => !['id', 'question', 'options'].includes(key)) ||
109
+ typeof item.id !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(item.id) || ids.has(item.id) ||
110
+ typeof item.question !== 'string' || !item.question.trim() || item.question.length > 1000 ||
111
+ (item.options !== undefined && (!Array.isArray(item.options) || item.options.length > 8 ||
112
+ item.options.some((option: unknown) => typeof option !== 'string' || !option.trim() || option.length > 200) ||
113
+ new Set(item.options).size !== item.options.length))) throw new Error('询问用户的问题格式无效');
114
+ ids.add(item.id);
115
+ return { id: item.id, question: item.question, ...(item.options?.length ? { options: [...item.options] } : {}) };
116
+ });
117
+ }
118
+ export function parseAssistantAnswers(value: unknown, questions: readonly AssistantQuestion[]): AssistantQuestionAnswer[] {
119
+ if (!Array.isArray(value) || value.length !== questions.length) throw new Error('请回答或跳过每个问题');
120
+ return questions.map((question, index) => {
121
+ const item = value[index];
122
+ if (!item || item.questionId !== question.id || Object.keys(item).some(key => !['questionId', 'answer'].includes(key)) ||
123
+ (item.answer !== null && (typeof item.answer !== 'string' || !item.answer.trim() || item.answer.length > 4000)))
124
+ throw new Error('用户回答格式无效');
125
+ return { questionId: question.id, answer: item.answer };
126
+ });
127
+ }
128
+
129
+ export interface AssistantMessage {
130
+ id: string;
131
+ role: 'user' | 'assistant';
132
+ content: string;
133
+ createdAt: number;
134
+ sources?: AssistantSource[];
135
+ /** Initial source IDs attached to the preceding user message; later tool reads are excluded. */
136
+ attachedSourceIds?: string[];
137
+ proposals?: AssistantProposal[];
138
+ toolResults?: AssistantToolResult[];
139
+ activity?: AssistantActivity[];
140
+ userInputs?: AssistantUserInput[];
141
+ usage?: { input: number; output: number };
142
+ state?: 'running' | 'waiting' | 'completed' | 'cancelled' | 'failed' | 'interrupted';
143
+ /** Written only by the executor when the whole run ends, independently of text phase. */
144
+ termination?: { reason: AssistantTerminationReason };
145
+ error?: string;
146
+ model?: string;
147
+ rules?: string[];
148
+ timing?: { firstContentMs?: number; totalMs: number };
149
+ }
150
+
151
+ export interface AssistantSession {
152
+ version: 1;
153
+ id: string;
154
+ workspaceId: string;
155
+ title: string;
156
+ createdAt: number;
157
+ updatedAt: number;
158
+ revision: number;
159
+ messages: AssistantMessage[];
160
+ connectionId?: string;
161
+ model?: string;
162
+ external?: boolean;
163
+ reasoningEffort?: AssistantReasoningSelection;
164
+ }
165
+
166
+ export interface AssistantToolCall {
167
+ id: string;
168
+ type: 'function';
169
+ function: { name: string; arguments: string };
170
+ }
171
+ export interface AssistantWireMessage {
172
+ role: 'system' | 'user' | 'assistant' | 'tool';
173
+ content: string | null;
174
+ tool_calls?: AssistantToolCall[];
175
+ tool_call_id?: string;
176
+ /** Transient Responses output, including reasoning needed by the next tool round. */
177
+ responseItems?: Record<string, unknown>[];
178
+ }
179
+ export interface AssistantRequest {
180
+ model: string;
181
+ reasoningEffort?: AssistantReasoningSelection;
182
+ messages: AssistantWireMessage[];
183
+ tools?: { type: 'function'; function: { name: string; description: string; parameters: Record<string, unknown> } }[];
184
+ }
185
+ export interface AssistantTransport {
186
+ canConfigure?: boolean;
187
+ connections(): Promise<AssistantConnection[]>;
188
+ models(connectionId: string, signal: AbortSignal): Promise<string[]>;
189
+ saveConnection(connection: Omit<AssistantConnection, 'hasKey'>, key?: string): Promise<void>;
190
+ removeConnection(id: string): Promise<void>;
191
+ request(connectionId: string, request: AssistantRequest, signal: AbortSignal, chunk: (bytes: Uint8Array) => void): Promise<void>;
192
+ loadSessions(workspaceId: string): Promise<AssistantSession[]>;
193
+ saveSession(session: AssistantSession): Promise<number>;
194
+ deleteSession(workspaceId: string, id: string, expectedRevision: number): Promise<void>;
195
+ loadExternalSessions?(workspaceId: string): Promise<AssistantSession[]>;
196
+ recordExternalResult?(session: AssistantSession): Promise<void>;
197
+ readonly demo?: boolean;
198
+ }
199
+
200
+ export function isAssistantModelId(value: unknown): value is string {
201
+ return typeof value === 'string' && value.length > 0 && value.length <= 200 && value.trim() === value &&
202
+ !/[\u0000-\u001f\u007f-\u009f]/.test(value);
203
+ }
204
+
205
+ /** Validate persisted data before allowing it back into execution or review. */
206
+ export function parseAssistantSession(value: unknown): AssistantSession {
207
+ const session = value as AssistantSession;
208
+ const text = (value: unknown, limit: number) => typeof value === 'string' && value.length <= limit;
209
+ if (!session || session.version !== 1 || !text(session.id, 80) || !/^[a-z0-9-]{8,80}$/i.test(session.id) ||
210
+ !text(session.workspaceId, 120) || !text(session.title, 200) ||
211
+ !Number.isFinite(session.createdAt) || !Number.isFinite(session.updatedAt) ||
212
+ !Number.isSafeInteger(session.revision) || session.revision < 0 ||
213
+ (session.connectionId !== undefined && (!text(session.connectionId, 80) || !session.connectionId.trim())) ||
214
+ (session.model !== undefined && !isAssistantModelId(session.model)) ||
215
+ (session.reasoningEffort !== undefined && !isAssistantReasoningSelection(session.reasoningEffort)) ||
216
+ !Array.isArray(session.messages) || session.messages.length > 300 || (session.external !== undefined && typeof session.external !== 'boolean'))
217
+ throw new Error('助手会话格式无效,原记录已保留');
218
+ const ids = new Set<string>();
219
+ for (const message of session.messages) {
220
+ if (!message || !text(message.id, 80) || ids.has(message.id) ||
221
+ !['user', 'assistant'].includes(message.role) || !text(message.content, 1_000_000) ||
222
+ !Number.isFinite(message.createdAt) ||
223
+ (message.state && !['running', 'waiting', 'completed', 'cancelled', 'failed', 'interrupted'].includes(message.state)) ||
224
+ (message.termination !== undefined && (!message.termination || message.role !== 'assistant' ||
225
+ !['completed', 'cancelled', 'interrupted', 'round_limit', 'no_progress', 'output_limit', 'incomplete', 'empty_response', 'error'].includes(message.termination.reason) ||
226
+ !['completed', 'cancelled', 'failed', 'interrupted'].includes(message.state ?? '') ||
227
+ (message.termination.reason === 'completed') !== (message.state === 'completed'))) ||
228
+ (message.sources && (!Array.isArray(message.sources) || message.sources.length > 30)) ||
229
+ (message.attachedSourceIds !== undefined && (message.role !== 'assistant' || !Array.isArray(message.attachedSourceIds) ||
230
+ message.attachedSourceIds.length > 20 || new Set(message.attachedSourceIds).size !== message.attachedSourceIds.length ||
231
+ message.attachedSourceIds.some(id => !text(id, 80) || !message.sources?.some(source => source?.id === id)))) ||
232
+ (message.proposals && (!Array.isArray(message.proposals) || message.proposals.length > 30)) ||
233
+ (message.timing !== undefined && (!message.timing || Array.isArray(message.timing) || !Number.isFinite(message.timing.totalMs) || message.timing.totalMs < 0 ||
234
+ (message.timing.firstContentMs !== undefined && (!Number.isFinite(message.timing.firstContentMs) ||
235
+ message.timing.firstContentMs < 0 || message.timing.firstContentMs > message.timing.totalMs)))) ||
236
+ (message.rules && (!Array.isArray(message.rules) || message.rules.length > 2 || message.rules.some(path => !text(path, 220)))))
237
+ throw new Error('助手消息格式无效,原记录已保留');
238
+ ids.add(message.id);
239
+ if (message.userInputs !== undefined) {
240
+ if (message.role !== 'assistant' || !Array.isArray(message.userInputs) || message.userInputs.length > 8)
241
+ throw new Error('助手提问记录格式无效');
242
+ const inputIds = new Set<string>();
243
+ let offset = 0;
244
+ for (const input of message.userInputs) {
245
+ if (!input || !text(input.id, 80) || !input.id || inputIds.has(input.id) ||
246
+ !['pending', 'answered', 'cancelled'].includes(input.status) ||
247
+ !Number.isSafeInteger(input.contentOffset) || input.contentOffset < offset || input.contentOffset > message.content.length)
248
+ throw new Error('助手提问记录格式无效');
249
+ inputIds.add(input.id); offset = input.contentOffset;
250
+ const questions = parseAssistantQuestions(input.questions);
251
+ if (input.status === 'answered') parseAssistantAnswers(input.answers, questions);
252
+ else if (input.answers !== undefined) throw new Error('未完成的提问不能记录为用户回答');
253
+ }
254
+ }
255
+ if (message.toolResults !== undefined) {
256
+ if (message.role !== 'assistant' || !Array.isArray(message.toolResults) || message.toolResults.length > 160 ||
257
+ message.toolResults.some(result => !result || !text(result.name, 80) || !result.name ||
258
+ !['succeeded', 'failed'].includes(result.status) ||
259
+ (result.status === 'failed' ? !text(result.error, 2000) || !result.error : result.error !== undefined) ||
260
+ (result.proposalId !== undefined && (!text(result.proposalId, 80) || !message.proposals?.some(proposal => proposal?.id === result.proposalId)))))
261
+ throw new Error('助手工具回执格式无效,原记录已保留');
262
+ }
263
+ if (message.activity !== undefined) {
264
+ if (message.role !== 'assistant' || !Array.isArray(message.activity) || message.activity.length > 200)
265
+ throw new Error('助手执行过程格式无效');
266
+ let end = 0;
267
+ let answered = false;
268
+ const receipts = new Set<number>();
269
+ const inputs = new Set<string>();
270
+ for (const item of message.activity) {
271
+ if (!item) throw new Error('助手执行过程顺序无效');
272
+ if (item.kind === 'text') {
273
+ if (!Number.isSafeInteger(item.start) || !Number.isSafeInteger(item.end) || item.start < end ||
274
+ item.end < item.start || item.end > message.content.length || !['pending', 'working', 'answer'].includes(item.phase))
275
+ throw new Error('助手执行过程正文范围无效');
276
+ if (answered && item.phase !== 'answer') throw new Error('助手执行过程顺序无效');
277
+ end = item.end;
278
+ answered = answered || item.phase === 'answer';
279
+ } else if (item.kind === 'tool') {
280
+ if (!text(item.name, 80) || !item.name || !['running', 'succeeded', 'failed', 'interrupted'].includes(item.status))
281
+ throw new Error('助手执行过程工具格式无效');
282
+ if (item.status === 'succeeded' || item.status === 'failed') {
283
+ const result = message.toolResults?.[item.resultIndex!];
284
+ if (!Number.isSafeInteger(item.resultIndex) || item.resultIndex! < 0 || receipts.has(item.resultIndex!) ||
285
+ !result || result.name !== item.name || result.status !== item.status)
286
+ throw new Error('助手执行过程与工具回执不一致');
287
+ receipts.add(item.resultIndex!);
288
+ } else if (item.resultIndex !== undefined) throw new Error('未完成的工具不能记录成功回执');
289
+ } else if (item.kind === 'input') {
290
+ if (!text(item.inputId, 80) || inputs.has(item.inputId) || !message.userInputs?.some(input => input.id === item.inputId))
291
+ throw new Error('助手执行过程提问记录无效');
292
+ inputs.add(item.inputId);
293
+ } else throw new Error('助手执行过程类型无效');
294
+ }
295
+ if (receipts.size !== (message.toolResults?.length ?? 0) || inputs.size !== (message.userInputs?.length ?? 0))
296
+ throw new Error('助手执行过程缺少回执或提问记录');
297
+ }
298
+ for (const source of message.sources ?? []) {
299
+ if (!source || source.workspaceId !== session.workspaceId || !text(source.id, 80) ||
300
+ !text(source.fileId, 80) || !text(source.path, 220) || !text(source.content, 512_000) ||
301
+ !text(source.hash, 128) || !['draft', 'disk'].includes(source.origin) ||
302
+ (source.selection && (!text(source.selection.text, 100_000) ||
303
+ (source.selection.from !== undefined && (!Number.isSafeInteger(source.selection.from) ||
304
+ !Number.isSafeInteger(source.selection.to) || source.selection.from < 0 ||
305
+ source.selection.to! <= source.selection.from || source.selection.to! > source.content.length)))))
306
+ throw new Error('助手上下文格式无效,原记录已保留');
307
+ }
308
+ for (const proposal of message.proposals ?? []) {
309
+ if (!proposal || proposal.workspaceId !== session.workspaceId || !text(proposal.id, 80) ||
310
+ !text(proposal.runId, 80) || !['edit', 'create', 'delete', 'rename', 'move', 'object', 'relation'].includes(proposal.kind) ||
311
+ !['ready', 'applying', 'applied', 'rejected', 'conflicted', 'unknown'].includes(proposal.status) ||
312
+ (proposal.execution !== undefined && proposal.execution !== 'direct') ||
313
+ !text(proposal.path, 220) || !text(proposal.base, 512_000) || !text(proposal.content, 512_000) ||
314
+ !text(proposal.reason, 4000) || (proposal.suggestionGroupId !== undefined && (proposal.kind !== 'edit' || !text(proposal.suggestionGroupId, 80))) || ((['edit', 'delete', 'rename', 'move'].includes(proposal.kind) || (proposal.kind === 'object' && proposal.base !== '')) && !text(proposal.fileId, 80)) ||
315
+ (['rename', 'move'].includes(proposal.kind) ? !text(proposal.destination, 220) || !proposal.destination : proposal.destination !== undefined) ||
316
+ (proposal.preview && (!text(proposal.preview.before, 512_000) ||
317
+ !text(proposal.preview.after, 512_000) || !text(proposal.preview.path, 220) ||
318
+ (proposal.preview.destination !== undefined && (!['rename', 'move'].includes(proposal.kind) || !text(proposal.preview.destination, 220))) ||
319
+ (proposal.preview.diskHash !== null && !text(proposal.preview.diskHash, 128)))) ||
320
+ (proposal.applied && (!text(proposal.applied.before, 512_000) ||
321
+ !text(proposal.applied.after, 512_000) || !text(proposal.applied.hash, 128) ||
322
+ !text(proposal.applied.fileId, 80))))
323
+ throw new Error('助手修改记录格式无效,原记录已保留');
324
+ }
325
+ }
326
+ const parsed = structuredClone(session) as AssistantSession & { executionMode?: unknown };
327
+ // Old conversation mode choices must not override the user's current request.
328
+ delete parsed.executionMode;
329
+ return parsed;
330
+ }
@@ -0,0 +1,100 @@
1
+ /** Portable document discussions and content-bound annotations. */
2
+ export type CommentKind = 'annotation' | 'discussion';
3
+
4
+ export interface CommentSpan {
5
+ from: number;
6
+ to: number;
7
+ text: string;
8
+ }
9
+
10
+ /** Offsets are in the projected visible text or in the raw Markdown source. */
11
+ export interface CommentAnchor {
12
+ basis: 'prose' | 'source';
13
+ baseHash: string;
14
+ spans: CommentSpan[];
15
+ prefix: string;
16
+ suffix: string;
17
+ }
18
+
19
+ export interface CommentMessage {
20
+ id: string;
21
+ authorId: string;
22
+ authorName: string;
23
+ body: string;
24
+ createdAt: number;
25
+ updatedAt?: number;
26
+ replyTo?: string;
27
+ mentions?: CommentMention[];
28
+ }
29
+
30
+ /** Explicit person references remain portable; account bindings belong to Cloud. */
31
+ export interface CommentMention { personId: string; text: string }
32
+
33
+ export interface CommentThread {
34
+ id: string;
35
+ anchor?: CommentAnchor;
36
+ messages: CommentMessage[];
37
+ resolved: boolean;
38
+ detached: boolean;
39
+ createdAt: number;
40
+ }
41
+
42
+ export interface CommentFile {
43
+ version: 1;
44
+ kind: CommentKind;
45
+ fileId: string;
46
+ threads: CommentThread[];
47
+ }
48
+
49
+ const validId = (value: unknown) => typeof value === 'string' && /^[0-9a-z-]{8,80}$/i.test(value);
50
+ const validText = (value: unknown, max: number) =>
51
+ typeof value === 'string' && value.length <= max && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(value);
52
+
53
+ export function emptyCommentFile(kind: CommentKind, fileId: string): CommentFile {
54
+ if (!/^[0-9a-f]{6}$/.test(fileId)) throw new Error('文档身份无效');
55
+ return { version: 1, kind, fileId, threads: [] };
56
+ }
57
+
58
+ export function parseCommentFile(content: string, kind: CommentKind, fileId: string): CommentFile {
59
+ const value: unknown = JSON.parse(content);
60
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('评论文件格式无效');
61
+ const file = value as CommentFile;
62
+ if (file.version !== 1 || file.kind !== kind || file.fileId !== fileId ||
63
+ !Array.isArray(file.threads) || file.threads.length > 2000)
64
+ throw new Error('评论文件身份或格式无效');
65
+ const threadIds = new Set<string>();
66
+ for (const thread of file.threads) {
67
+ if (!thread || !validId(thread.id) || threadIds.has(thread.id) ||
68
+ !Array.isArray(thread.messages) || thread.messages.length < 1 || thread.messages.length > 1000 ||
69
+ typeof thread.resolved !== 'boolean' || typeof thread.detached !== 'boolean' ||
70
+ !Number.isFinite(thread.createdAt)) throw new Error('评论串格式无效');
71
+ threadIds.add(thread.id);
72
+ if (kind === 'annotation') {
73
+ const anchor = thread.anchor;
74
+ if (!anchor || !['prose', 'source'].includes(anchor.basis) ||
75
+ typeof anchor.baseHash !== 'string' || anchor.baseHash.length > 128 ||
76
+ !Array.isArray(anchor.spans) || anchor.spans.length < 1 || anchor.spans.length > 1000 ||
77
+ !validText(anchor.prefix, 256) || !validText(anchor.suffix, 256) ||
78
+ anchor.spans.some(span => !span || !Number.isSafeInteger(span.from) ||
79
+ !Number.isSafeInteger(span.to) || span.from < 0 || span.to <= span.from ||
80
+ !validText(span.text, 100_000) || span.text.length !== span.to - span.from))
81
+ throw new Error('批注锚点格式无效');
82
+ } else if (thread.anchor !== undefined) throw new Error('整篇讨论不能包含局部锚点');
83
+ const messageIds = new Set<string>();
84
+ for (const message of thread.messages) {
85
+ if (!message || !validId(message.id) || messageIds.has(message.id) ||
86
+ !validText(message.authorId, 120) || !validText(message.authorName, 120) ||
87
+ !validText(message.body, 20_000) || !message.body.trim() ||
88
+ !Number.isFinite(message.createdAt) ||
89
+ (message.updatedAt !== undefined && !Number.isFinite(message.updatedAt))) throw new Error('评论内容格式无效');
90
+ if (message.replyTo !== undefined && (!validId(message.replyTo) || message.replyTo === message.id ||
91
+ !thread.messages.some(item => item.id === message.replyTo))) throw new Error('回复目标无效');
92
+ if (message.mentions !== undefined && (!Array.isArray(message.mentions) || message.mentions.length > 100 ||
93
+ message.mentions.some(item => !item || !/^[0-9a-f]{6}$/.test(item.personId) ||
94
+ !validText(item.text, 120) || !item.text.startsWith('@') || item.text.length < 2 ||
95
+ !message.body.includes(item.text)))) throw new Error('提及人物格式无效');
96
+ messageIds.add(message.id);
97
+ }
98
+ }
99
+ return file;
100
+ }