Repository navigation
Expand file tree
/
Copy pathdocument-read.ts
More file actions
422 lines (402 loc) · 14.3 KB
/
Copy pathdocument-read.ts
File metadata and controls
422 lines (402 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
export type DocumentReadQuery = {
view?: "outline" | "content";
offset?: number;
limit?: number;
blockId?: string;
slideId?: string;
sheetId?: string;
elementId?: string;
startRow?: number;
endRow?: number;
startColumn?: number;
endColumn?: number;
};
function clip(text: string, max: number) {
return text.length > max ? `${text.slice(0, max)}…` : text;
}
function previewText(value: unknown, max = 80): string {
const parts: string[] = [];
const walk = (node: unknown) => {
if (parts.join("").length >= max) return;
if (typeof node === "string") {
parts.push(node);
return;
}
if (!node || typeof node !== "object") return;
if (Array.isArray(node)) {
node.forEach(walk);
return;
}
const n = node as Record<string, unknown>;
if (typeof n.text === "string") parts.push(n.text);
if (typeof n.code === "string") parts.push(n.code);
if (typeof n.label === "string") parts.push(n.label);
if (Array.isArray(n.children)) n.children.forEach(walk);
if (Array.isArray(n.paragraphs)) n.paragraphs.forEach(walk);
if (Array.isArray(n.cells)) n.cells.forEach(walk);
};
walk(value);
return clip(parts.join(""), max);
}
function walkRich(
value: unknown,
visit: (node: Record<string, unknown>, parent: Record<string, unknown> | null) => void,
parent: Record<string, unknown> | null = null,
) {
if (!value || typeof value !== "object") return;
if (Array.isArray(value)) {
for (const item of value) walkRich(item, visit, parent);
return;
}
const node = value as Record<string, unknown>;
visit(node, parent);
if (Array.isArray(node.children)) {
for (const child of node.children) walkRich(child, visit, node);
}
}
/** text 改的是段落。模型常把单元格 id 当成 blockId。 */
export function textTargetId(value: unknown, blockId: string) {
let paragraphId = blockId;
walkRich(value, (node) => {
if (node.type === "table-cell" && node.id === blockId) {
const paragraph = (node.children as any[] | undefined)?.find(
(child) => child?.type === "paragraph" && child.id,
);
if (paragraph?.id) paragraphId = paragraph.id;
}
});
return paragraphId;
}
/** setCellContent 要单元格 id。模型常把格内段落 id 当成 cellId。 */
export function cellTargetId(value: unknown, cellId: string) {
let resolved = cellId;
walkRich(value, (node, parent) => {
if (node.id === cellId && parent?.type === "table-cell" && parent.id)
resolved = String(parent.id);
});
return resolved;
}
function findById(value: unknown, id: string): unknown {
if (!value || typeof value !== "object") return null;
if (Array.isArray(value)) {
for (const item of value) {
const found = findById(item, id);
if (found) return found;
}
return null;
}
const node = value as Record<string, unknown>;
if (node.id === id) return node;
if (Array.isArray(node.children)) return findById(node.children, id);
return null;
}
function richOutline(value: unknown) {
const blocks = Array.isArray(value) ? value : [];
return {
blockCount: blocks.length,
blocks: blocks.slice(0, 200).map((block: any) => {
const node: Record<string, unknown> = {
id: block?.id,
type: block?.type,
preview: previewText(block, 80),
textLength: richTextLength(block),
};
if (block?.title) node.title = block.title;
if (block?.type === "code-block") node.language = block.language;
if (block?.type === "table")
node.rows = (block.children ?? []).slice(0, 12).map((row: any) => ({
id: row?.id,
cells: (row?.children ?? []).slice(0, 12).map((cell: any) => ({
id: cell?.id,
rowId: cell?.rowId,
columnId: cell?.columnId,
paragraphId: (cell?.children ?? []).find(
(child: any) => child?.type === "paragraph",
)?.id,
textLength: richTextLength(cell),
preview: previewText(cell, 40),
})),
}));
if (block?.type === "flowchart")
node.nodes = (block.nodes ?? []).slice(0, 40).map((n: any) => ({
id: n?.id,
label: n?.label,
}));
if (block?.type === "mindmap")
node.mind = {
id: block.mindData?.nodeData?.id,
topic: block.mindData?.nodeData?.topic,
};
if (block?.type === "columns")
node.columns = (block.children ?? []).map((c: any) => ({
id: c?.id,
type: c?.type,
}));
return node;
}),
};
}
/** Native rich-text offsets count UTF-16 code units across text leaves, including links. */
export function richTextLength(value: unknown): number {
if (!value || typeof value !== "object") return 0;
const node = value as { text?: unknown; children?: unknown[] };
if (typeof node.text === "string") return node.text.length;
return Array.isArray(node.children)
? node.children.reduce<number>((total, child) => total + richTextLength(child), 0)
: 0;
}
function markdownOutline(text: string) {
const headings: { index: number; level: number; text: string }[] = [];
for (const match of text.matchAll(/^(#{1,6})\s+(.+)$/gm))
headings.push({
index: match.index ?? 0,
level: match[1]!.length,
text: clip(match[2]!.trim(), 80),
});
return { length: text.length, headings, preview: clip(text, 400) };
}
function canvasNodes(nodes: any[] | undefined, depth = 0, parentId: string | null = null): unknown[] {
if (!nodes?.length || depth > 8) return [];
return nodes.slice(0, 200).map((n) => ({
id: n?.id,
parentId,
tag: n?.tag,
name: n?.name,
kind: n?.data?.kind,
parentTopicId: n?.data?.kind === "mind-node" ? n.data.parentId : undefined,
root: n?.data?.kind === "mind-node" ? n.data.root : undefined,
cellRow: n?.data?.kind === "table-cell" ? n.data.row : undefined,
cellColumn: n?.data?.kind === "table-cell" ? n.data.column : undefined,
rowSpan: n?.data?.rowSpan, columnSpan: n?.data?.columnSpan, coveredBy: n?.data?.coveredBy,
sourceId: n?.data?.sourceId, targetId: n?.data?.targetId,
labelId: n?.data?.labelId, ownerId: n?.data?.ownerId,
containerType: n?.data?.containerType,
rows: n?.data?.kind === "table" ? n.data.rows : undefined,
columns: n?.data?.kind === "table" ? n.data.columns : undefined,
textLength: typeof n?.text === "string" ? n.text.length : undefined,
childCount: n?.children?.length,
childrenTruncated: n?.children?.length > 200 || (depth >= 8 && n?.children?.length > 0),
x: n?.x,
y: n?.y,
width: n?.width,
height: n?.height,
text: typeof n?.text === "string" ? clip(n.text, 40) : undefined,
children: Array.isArray(n?.children)
? canvasNodes(n.children, depth + 1, n.id)
: undefined,
}));
}
function canvasOutline(value: any) {
const children = value?.scene?.children ?? value?.children ?? [];
return { childCount: children.length, children: canvasNodes(children) };
}
function presentationOutline(value: any) {
const order = value?.slideOrder ?? [];
return {
size: value?.size,
slideOrder: order,
slides: order.slice(0, 40).map((id: string) => {
const slide = value?.slides?.[id] ?? {};
const elementOrder = slide.elementOrder ?? Object.keys(slide.elements ?? {});
return {
id,
name: slide.name,
hidden: slide.hidden, sectionId: slide.sectionId,
elementCount: elementOrder.length,
elementsTruncated: elementOrder.length > 40,
elementOrder,
elements: elementOrder.slice(0, 40).map((eid: string) => {
const el = slide.elements?.[eid];
return {
id: eid,
type: el?.type,
transform: el?.transform,
...(el?.type === "table" ? { rows: el.cells?.length, columns: el.cells?.[0]?.length,
rowIds: el.rowIds, columnIds: el.columnIds, merges: el.merges,
previewCells: el.cells?.slice(0, 4).map((row: string[]) => row.slice(0, 5).map(value => clip(value, 40))),
} : {}),
preview: previewText(el, 60),
};
}),
};
}),
};
}
function previewCell(cell: unknown) {
if (!cell || typeof cell !== "object") return cell;
const next: Record<string, unknown> = { ...(cell as Record<string, unknown>) };
if (typeof next.v === "string") next.v = clip(next.v, 40);
if (typeof next.f === "string") next.f = clip(next.f, 40);
return next;
}
function usedCells(
cellData: Record<string, Record<string, unknown>> | undefined,
range?: {
startRow?: number;
endRow?: number;
startColumn?: number;
endColumn?: number;
},
) {
const cells: Record<string, Record<string, unknown>> = {};
for (const [rowKey, cols] of Object.entries(cellData ?? {})) {
const row = Number(rowKey);
if (range?.startRow != null && row < range.startRow) continue;
if (range?.endRow != null && row > range.endRow) continue;
for (const [colKey, cell] of Object.entries(cols ?? {})) {
const column = Number(colKey);
if (range?.startColumn != null && column < range.startColumn) continue;
if (range?.endColumn != null && column > range.endColumn) continue;
if (cell == null) continue;
cells[rowKey] ??= {};
cells[rowKey]![colKey] = cell;
}
}
return cells;
}
function spreadsheetOutline(value: any) {
const sheetOrder = value?.sheetOrder ?? [];
return {
sheetOrder,
sheets: sheetOrder.slice(0, 8).map((sheetId: string) => {
const sheet = value?.sheets?.[sheetId] ?? {};
const cells = usedCells(sheet.cellData);
const positions = Object.entries(cells).flatMap(([row, cols]) =>
Object.keys(cols ?? {}).map((column) => ({
row: Number(row),
column: Number(column),
})),
);
const rows = positions.map((p) => p.row);
const cols = positions.map((p) => p.column);
return {
sheetId,
name: sheet.name,
rowCount: sheet.rowCount,
columnCount: sheet.columnCount,
used: {
rows: rows.length ? { min: Math.min(...rows), max: Math.max(...rows) } : null,
columns: cols.length
? { min: Math.min(...cols), max: Math.max(...cols) }
: null,
cellCount: positions.length,
},
preview: Object.fromEntries(
Object.entries(cells)
.slice(0, 16)
.map(([row, rowCells]) => [
row,
Object.fromEntries(
Object.entries(rowCells)
.slice(0, 8)
.map(([column, cell]) => [column, previewCell(cell)]),
),
]),
),
};
}),
};
}
export function documentOutline(format: string, value: unknown) {
if (format === "rich_text") return richOutline(value);
if (format === "markdown") return markdownOutline(String(value ?? ""));
if (format === "canvas") return canvasOutline(value);
if (format === "presentation") return presentationOutline(value);
if (format === "spreadsheet") return spreadsheetOutline(value);
return { preview: clip(JSON.stringify(value ?? null), 400) };
}
function regionValue(
format: string,
value: unknown,
query: DocumentReadQuery,
): { value?: unknown; error?: string } {
if (format === "rich_text" && query.blockId) {
const block = findById(value, query.blockId);
return block
? { value: block }
: { error: `找不到 blockId ${query.blockId}。先 document_read 默认 outline。` };
}
if (format === "canvas" && query.elementId) {
const scene = (value as any)?.scene?.children ?? (value as any)?.children;
const element = findById(scene, query.elementId);
return element
? { value: element }
: {
error: `找不到 elementId ${query.elementId}。先 document_read 默认 outline。`,
};
}
if (format === "presentation" && query.slideId) {
const doc = value as any;
const slide = doc?.slides?.[query.slideId];
if (!slide) return { error: `找不到 slideId ${query.slideId}。可用 ${JSON.stringify(doc?.slideOrder ?? [])}。` };
if (query.elementId) {
const element = slide.elements?.[query.elementId];
return element ? { value: { size: doc.size, slideId: query.slideId, element } }
: { error: `找不到 elementId ${query.elementId};请读取该页 elementOrder。` };
}
return { value: { size: doc.size, slideId: query.slideId, slide } };
}
if (format === "presentation" && query.elementId)
return { error: "读取 PPT 元素时请同时提供 slideId 和 elementId。" };
if (format === "spreadsheet" && query.sheetId) {
const doc = value as any;
const sheet = doc?.sheets?.[query.sheetId];
if (!sheet)
return {
error: `找不到 sheetId ${query.sheetId}。可用 sheetOrder ${JSON.stringify(doc?.sheetOrder ?? [])}。`,
};
return {
value: {
sheetId: query.sheetId,
name: sheet.name,
rowCount: sheet.rowCount,
columnCount: sheet.columnCount,
cells: usedCells(sheet.cellData, query),
},
};
}
return { value };
}
function paginate(value: unknown, offset: number, limit: number) {
const content = JSON.stringify(value);
return {
content: content.slice(offset, offset + limit),
nextOffset: offset + limit < content.length ? offset + limit : null,
};
}
function hasRegion(query: DocumentReadQuery) {
return Boolean(
query.blockId || query.slideId || query.sheetId || query.elementId,
);
}
/** Executor default is outline. Reviewer and explicit view=content still paginate native JSON. */
export function documentReadPayload(
format: string,
value: unknown,
query: DocumentReadQuery = {},
): {
view: "outline" | "content";
outline?: unknown;
content?: string;
nextOffset: number | null;
error?: string;
} {
const offset = Math.max(0, query.offset ?? 0);
const limit = Math.min(30000, Math.max(100, query.limit ?? 16000));
if (hasRegion(query)) {
const region = regionValue(format, value, query);
if (region.error)
return { view: "content" as const, error: region.error, nextOffset: null };
return {
view: "content" as const,
...paginate(region.value, offset, limit),
};
}
if ((query.view ?? "outline") === "outline")
return {
view: "outline" as const,
outline: documentOutline(format, value),
nextOffset: null,
};
return { view: "content" as const, ...paginate(value, offset, limit) };
}