import { randomUUID } from 'node:crypto'; import { existsSync } from 'node:fs'; import { z } from 'zod'; import type { Tool, ToolCallContext, ToolResult } from '../../types.js'; import { toToolParameters } from '../../utils/zodToJson.js'; import { fileActivityMetadata } from '../shared/fileActivity.js'; import { assertFresh, hashFileBytes, recordRead, type FileReadState } from '../shared/fileState.js'; import { emitFileMutation } from '../shared/fileMutationBus.js'; import { applyLineEnding, atomicWriteFile, encodeTextFile, readTextFile, resolveToolPath } from '../shared/fileUtils.js'; import { filePathField } from '../shared/schemas.js'; import { DEFAULT_MAX_RESULT_SIZE_CHARS } from '../types.js'; type NotebookCell = { id?: string; cell_type: 'code' | 'markdown' | 'raw'; source: string | string[]; metadata?: Record; outputs?: unknown[]; execution_count?: number | null; [key: string]: unknown; }; type Notebook = { cells: NotebookCell[]; [key: string]: unknown }; const inputSchema = z.object({ notebook_path: filePathField('编辑').refine((path) => path.toLowerCase().endsWith('.ipynb'), '必须是 .ipynb 文件'), edit_mode: z.enum(['replace', 'insert', 'delete']), cell_id: z.string().min(1).optional().describe('现有 cell.id,或 Read 输出中的 cell-N 标识。insert 时省略会追加到末尾'), new_source: z.string().optional().describe('replace/insert 后的完整单元格源码'), cell_type: z.enum(['code', 'markdown', 'raw']).optional().describe('insert 时必填;replace 时可用于改变类型'), }).superRefine((value, ctx) => { if (value.edit_mode !== 'insert' && !value.cell_id) ctx.addIssue({ code: 'custom', path: ['cell_id'], message: 'replace/delete 必须提供 cell_id' }); if (value.edit_mode !== 'delete' && value.new_source === undefined) ctx.addIssue({ code: 'custom', path: ['new_source'], message: 'replace/insert 必须提供 new_source' }); if (value.edit_mode === 'insert' && !value.cell_type) ctx.addIssue({ code: 'custom', path: ['cell_type'], message: 'insert 必须提供 cell_type' }); }); type NotebookEditInput = z.infer; function sourceLines(source: string): string[] { const parts = source.match(/[^\r\n]*(?:\r\n|\n|\r)|[^\r\n]+$/g) ?? []; return parts.length > 0 ? parts : ['']; } function findCellIndex(cells: NotebookCell[], id: string): number { const exact = cells.findIndex((cell) => cell.id === id); if (exact >= 0) return exact; const numbered = /^cell-(\d+)$/.exec(id); return numbered ? Number(numbered[1]) - 1 : -1; } async function call(input: NotebookEditInput, state?: FileReadState, cwd?: string): Promise { const resolved = resolveToolPath(input.notebook_path, cwd); if (!resolved.ok) return resolved; const path = resolved.resolvedPath; if (!existsSync(path)) return { ok: false, error: `Notebook 不存在:${path}` }; const freshness = assertFresh(path, {}, state); if (!freshness.ok) return { ok: false, error: freshness.error }; try { const snapshot = await readTextFile(path); const notebook = JSON.parse(snapshot.content) as Notebook; if (!Array.isArray(notebook.cells)) return { ok: false, error: `${path} 不是有效的 Jupyter Notebook:缺少 cells 数组` }; let targetIndex = notebook.cells.length; if (input.cell_id) { targetIndex = findCellIndex(notebook.cells, input.cell_id); if (targetIndex < 0 || targetIndex >= notebook.cells.length) { return { ok: false, error: `找不到单元格 ${input.cell_id}。请重新 Read Notebook 获取最新 cell ID。` }; } } if (input.edit_mode === 'delete') { notebook.cells.splice(targetIndex, 1); } else if (input.edit_mode === 'replace') { const oldCell = notebook.cells[targetIndex]!; const nextType = input.cell_type ?? oldCell.cell_type; notebook.cells[targetIndex] = { ...oldCell, cell_type: nextType, source: sourceLines(input.new_source!), ...(nextType === 'code' ? { outputs: [], execution_count: null } : {}), }; if (nextType !== 'code') { delete notebook.cells[targetIndex]!.outputs; delete notebook.cells[targetIndex]!.execution_count; } if (nextType === 'code') delete notebook.cells[targetIndex]!.attachments; } else { const cell: NotebookCell = { id: randomUUID().replaceAll('-', '').slice(0, 8), cell_type: input.cell_type!, metadata: {}, source: sourceLines(input.new_source!), ...(input.cell_type === 'code' ? { outputs: [], execution_count: null } : {}), }; const insertionIndex = input.cell_id ? targetIndex : notebook.cells.length; notebook.cells.splice(insertionIndex, 0, cell); targetIndex = insertionIndex; } const indent = /^(\s+)"/.exec(snapshot.content.split(/\r?\n/)[1] ?? '')?.[1]?.length ?? 2; let output = JSON.stringify(notebook, null, Math.max(1, Math.min(indent, 4))) + '\n'; output = applyLineEnding(output, snapshot.lineEnding); await atomicWriteFile(path, output, snapshot.encoding); recordRead(path, { contentHash: hashFileBytes(encodeTextFile(output, snapshot.encoding)) }, state); emitFileMutation(path); return { ok: true, content: `${input.edit_mode === 'insert' ? '已插入' : input.edit_mode === 'delete' ? '已删除' : '已更新'} Notebook 单元格(位置 ${targetIndex + 1}):${path}`, metadata: await fileActivityMetadata(path, 'modified', 'not_run', 'support', cwd), }; } catch (error) { return { ok: false, error: `Notebook 编辑失败:${(error as Error).message}` }; } } export const notebookEditTool: Tool = { name: 'NotebookEdit', description: 'Edits one Jupyter Notebook cell without rewriting cells manually. Use Read first to inspect cell IDs. Replace clears stale code outputs; insert creates a stable cell ID; delete removes only the selected cell.', inputSchema, parameters: toToolParameters(inputSchema), isReadOnly: false, isConcurrencySafe: false, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, interruptBehavior: () => 'block', call: (input) => call(input), callWithContext: (input, _signal, context: ToolCallContext) => call(input, context.sessionState?.fileReads, context.cwd), };