import { existsSync } from 'node:fs'; import { readFile, realpath, rm } from 'node:fs/promises'; import { dirname, isAbsolute, relative, resolve, sep } from 'node:path'; import { z } from 'zod'; import { getWorkingDir } from '../../bootstrap/workingDir.js'; import { toToolParameters } from '../../utils/zodToJson.js'; import type { FileActivityMetadata, Tool, ToolCallContext, ToolResult, } from '../../types.js'; import { buildPatchSummary } from '../shared/diffSummary.js'; import { fileActivityMetadata } from '../shared/fileActivity.js'; import { emitFileMutation } from '../shared/fileMutationBus.js'; import { hashFileBytes, recordRead } from '../shared/fileState.js'; import { type FileBomEncoding, atomicWriteFile, encodeTextFile, hasBinaryExtension, readTextFile, } from '../shared/fileUtils.js'; import { DEFAULT_MAX_RESULT_SIZE_CHARS } from '../types.js'; interface PatchHunk { header: string; oldStart?: number; oldCount?: number; endOfFile?: boolean; lines: Array<{ kind: 'context' | 'add' | 'delete'; text: string }>; } type PatchOperation = | { kind: 'add'; path: string; content: string } | { kind: 'delete'; path: string } | { kind: 'update'; path: string; moveTo?: string; hunks: PatchHunk[] }; const schema = z.object({ patch: z.string().min(1).max(10_000_000).describe('Complete Codex-style patch envelope'), }); type ApplyPatchInput = z.infer; function fail(message: string): never { throw new Error(message); } /** Parse the Codex apply_patch envelope without invoking a platform patch binary. */ export function parseApplyPatch(input: string): PatchOperation[] { const lines = input.replaceAll('\r\n', '\n').split('\n'); if (lines[0] !== '*** Begin Patch') fail('补丁必须以 *** Begin Patch 开始'); const operations: PatchOperation[] = []; let index = 1; while (index < lines.length) { const line = lines[index]!; if (line === '*** End Patch') { if (lines.slice(index + 1).some((item) => item.trim())) fail('*** End Patch 后不能再有内容'); if (!operations.length) fail('补丁中没有文件操作'); return operations; } if (line.startsWith('*** Add File: ')) { const path = line.slice('*** Add File: '.length); index += 1; const added: string[] = []; while (index < lines.length && !lines[index]!.startsWith('*** ')) { const contentLine = lines[index]!; if (!contentLine.startsWith('+')) fail(`Add File ${path} 的内容行必须以 + 开头(第 ${index + 1} 行)`); added.push(contentLine.slice(1)); index += 1; } operations.push({ kind: 'add', path, content: added.length ? `${added.join('\n')}\n` : '', }); continue; } if (line.startsWith('*** Delete File: ')) { operations.push({ kind: 'delete', path: line.slice('*** Delete File: '.length), }); index += 1; continue; } if (line.startsWith('*** Update File: ')) { const path = line.slice('*** Update File: '.length); index += 1; let moveTo: string | undefined; if (lines[index]?.startsWith('*** Move to: ')) { moveTo = lines[index]!.slice('*** Move to: '.length); index += 1; } const hunks: PatchHunk[] = []; while (index < lines.length && !lines[index]!.startsWith('*** ')) { const headerLine = lines[index]!; if (!headerLine.startsWith('@@')) fail(`Update File ${path} 缺少 @@ hunk 头(第 ${index + 1} 行)`); const match = /^@@(?: -(\d+)(?:,\d+)? \+\d+(?:,\d+)?)? @@\s*(.*)$/.exec( headerLine, ); const header = match ? match[2]! : headerLine.slice(2).replace(/^\s+|\s+$/g, ''); const oldStart = match?.[1] ? Number(match[1]) : undefined; index += 1; const hunkLines: PatchHunk['lines'] = []; let endOfFile = false; while ( index < lines.length && !lines[index]!.startsWith('@@') && (!lines[index]!.startsWith('*** ') || lines[index] === '*** End of File') ) { const hunkLine = lines[index]!; if (hunkLine === '*** End of File') { endOfFile = true; index += 1; break; } const prefix = hunkLine[0]; if (prefix !== ' ' && prefix !== '+' && prefix !== '-') fail(`hunk 内容行必须以空格、+ 或 - 开头(第 ${index + 1} 行)`); hunkLines.push({ kind: prefix === ' ' ? 'context' : prefix === '+' ? 'add' : 'delete', text: hunkLine.slice(1), }); index += 1; } if (!hunkLines.length) fail(`Update File ${path} 包含空 hunk`); const countMatch = /^@@ -\d+,(\d+)/.exec(headerLine); hunks.push({ header, oldStart, oldCount: countMatch ? Number(countMatch[1]) : undefined, endOfFile, lines: hunkLines }); } if (!hunks.length && !moveTo) fail(`Update File ${path} 没有 hunk`); operations.push({ kind: 'update', path, ...(moveTo ? { moveTo } : {}), hunks, }); continue; } fail(`无法识别补丁指令(第 ${index + 1} 行):${line}`); } fail('补丁缺少 *** End Patch'); } function within(root: string, candidate: string): boolean { const rel = relative(root, candidate); return ( rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`)) ); } async function nearestExistingAncestor(path: string): Promise { let current = path; while (!existsSync(current)) { const parent = dirname(current); if (parent === current) break; current = parent; } return realpath(current); } async function workspacePath(raw: string, cwd: string): Promise { if (!raw || isAbsolute(raw) || raw.includes('\0')) fail(`补丁路径必须是非空的工作区相对路径:${raw}`); const absolute = resolve(cwd, raw); const rel = relative(resolve(cwd), absolute); if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) fail(`补丁路径越过工作区边界:${raw}`); const physicalRoot = await realpath(resolve(cwd)).catch(() => resolve(cwd)); const physicalBoundary = existsSync(absolute) ? await realpath(absolute) : await nearestExistingAncestor(dirname(absolute)); if (!within(physicalRoot, physicalBoundary)) fail(`补丁路径通过符号链接越过工作区边界:${raw}`); if (hasBinaryExtension(absolute)) fail(`ApplyPatch 不支持二进制文件:${raw}`); return absolute; } /** Use the patch grammar and the same workspace validation as staging. Rules * also apply to physical target directories reached through in-root links. */ export async function applyPatchRuleScopes(patch: string, cwd: string): Promise { const scopes = new Set(); for (const operation of parseApplyPatch(patch)) { const targets = operation.kind === 'update' && operation.moveTo ? [operation.path, operation.moveTo] : [operation.path]; for (const target of targets) { const path = await workspacePath(target, cwd); scopes.add(dirname(path)); if (existsSync(path)) scopes.add(dirname(await realpath(path))); else scopes.add(await nearestExistingAncestor(dirname(path))); } } return [...scopes]; } export function applyHunks(original: string, hunks: PatchHunk[]): string { // Keep terminators on their source lines: context is evidence, not replacement text. const lines = Array.from(original.matchAll(/([^\r\n]*)(\r\n|\r|\n|$)/g)) .filter((match) => match[0].length > 0) .map((match) => ({ text: match[1]!, ending: match[2]! })); const preferredEnding = lines.find((line) => line.ending)?.ending ?? '\n'; const trailingNewline = lines.length === 0 || lines.at(-1)!.ending !== ''; let cursor = 0; let lineDelta = 0; for (const hunk of hunks) { if (hunk.header) { const anchor = lines.findIndex( (line, index) => index >= cursor && line.text.includes(hunk.header), ); if (anchor < 0) fail(`找不到 hunk 锚点:${hunk.header}`); cursor = anchor; } const before = hunk.lines .filter((line) => line.kind !== 'add') .map((line) => line.text); const after = hunk.lines .filter((line) => line.kind !== 'delete') .map((line) => line.text); const matchesAt = (start: number) => before.every((line, offset) => lines[start + offset]?.text === line); let at = -1; if (hunk.endOfFile) { const last = lines.length - before.length; if (last >= cursor && matchesAt(last)) at = last; } else if (before.length && hunk.oldStart !== undefined && hunk.oldStart - 1 + lineDelta >= cursor && matchesAt(hunk.oldStart - 1 + lineDelta)) { at = hunk.oldStart - 1 + lineDelta; } else if (!before.length) { at = hunk.oldStart === undefined ? lines.length : Math.max(cursor, Math.min(lines.length, hunk.oldStart - (hunk.oldCount === 0 ? 0 : 1) + lineDelta)); } else { for ( let index = cursor; index <= lines.length - before.length; index += 1 ) { if (matchesAt(index)) { at = index; break; } } if (at < 0 && cursor > 0) { const matches: number[] = []; for (let index = 0; index <= lines.length - before.length; index += 1) if (matchesAt(index)) matches.push(index); if (matches.length === 1) at = matches[0]!; } } if (at < 0) fail(`hunk 上下文与当前文件不匹配:${before.join('\n').slice(0, 240)}`); const touchesEnd = at + before.length === lines.length; let sourceIndex = at; let lastIsAdded = false; const replacement = [] as typeof lines; for (const line of hunk.lines) { if (line.kind === 'context') { replacement.push(lines[sourceIndex++]!); lastIsAdded = false; } else if (line.kind === 'delete') sourceIndex++; else { replacement.push({ text: line.text, ending: preferredEnding }); lastIsAdded = true; } } // Retain our existing no-final-newline contract when rewriting or extending EOF. if (touchesEnd && !trailingNewline && lastIsAdded) { replacement[replacement.length - 1] = { ...replacement.at(-1)!, ending: '' }; } lines.splice(at, before.length, ...replacement); // Appending after an unterminated source line necessarily adds a separator. for (let index = Math.max(0, at - 1); index < Math.min(lines.length - 1, at + replacement.length); index++) { if (!lines[index]!.ending) lines[index] = { ...lines[index]!, ending: preferredEnding }; } cursor = at + after.length; lineDelta += after.length - before.length; } return lines.map((line) => line.text + line.ending).join(''); } interface StagedFile { path: string; label: string; before?: Buffer; beforeText: string; after?: string; encoding: FileBomEncoding; activity: 'created' | 'modified' | 'deleted'; } async function stagePatch( operations: PatchOperation[], cwd: string, ): Promise { const staged: StagedFile[] = []; const touched = new Set(); const claim = (path: string) => { if (touched.has(path)) fail(`同一补丁不能重复操作同一路径:${path}`); touched.add(path); }; for (const operation of operations) { const path = await workspacePath(operation.path, cwd); claim(path); if (operation.kind === 'add') { if (existsSync(path)) fail(`Add File 目标已存在:${operation.path}`); staged.push({ path, label: operation.path, beforeText: '', after: operation.content, encoding: 'utf8', activity: 'created', }); continue; } if (!existsSync(path)) fail( `${operation.kind === 'delete' ? 'Delete' : 'Update'} File 不存在:${operation.path}`, ); const snapshot = await readTextFile(path); if (operation.kind === 'delete') { staged.push({ path, label: operation.path, before: snapshot.bytes, beforeText: snapshot.content, encoding: snapshot.encoding, activity: 'deleted', }); continue; } const updated = applyHunks(snapshot.content, operation.hunks); if (operation.moveTo) { const target = await workspacePath(operation.moveTo, cwd); claim(target); if (existsSync(target)) fail(`Move to 目标已存在:${operation.moveTo}`); staged.push({ path, label: operation.path, before: snapshot.bytes, beforeText: snapshot.content, encoding: snapshot.encoding, activity: 'deleted', }); staged.push({ path: target, label: operation.moveTo, beforeText: '', after: updated, encoding: snapshot.encoding, activity: 'created', }); } else { staged.push({ path, label: operation.path, before: snapshot.bytes, beforeText: snapshot.content, after: updated, encoding: snapshot.encoding, activity: 'modified', }); } } return staged; } async function commit(staged: StagedFile[]): Promise { const committed: StagedFile[] = []; try { for (const file of staged) { if (file.after === undefined) await rm(file.path); else await atomicWriteFile(file.path, file.after, file.encoding); committed.push(file); } } catch (error) { const rollbackErrors: string[] = []; for (const file of committed.reverse()) { try { if (file.before) await atomicWriteFile(file.path, file.before); else await rm(file.path, { force: true }); } catch (rollbackError) { rollbackErrors.push( `${file.label}: ${(rollbackError as Error).message}`, ); } } const suffix = rollbackErrors.length ? `;回滚也有失败:${rollbackErrors.join(';')}` : ';已回滚本次已落盘文件'; throw new Error(`${(error as Error).message}${suffix}`); } } async function call( input: ApplyPatchInput, context?: ToolCallContext, ): Promise { const cwd = context?.cwd ?? getWorkingDir(); let operations: PatchOperation[]; let staged: StagedFile[]; try { operations = parseApplyPatch(input.patch); staged = await stagePatch(operations, cwd); await commit(staged); } catch (error) { return { ok: false, error: `ApplyPatch 失败:${(error as Error).message}` }; } const files: FileActivityMetadata['files'] = []; const summaries: string[] = []; for (const file of staged) { const afterText = file.after ?? ''; const patch = buildPatchSummary(file.beforeText, afterText, file.label); const metadata = await fileActivityMetadata( file.path, file.activity, 'not_run', 'support', cwd, patch, ); if (metadata) files.push(...metadata.files); if (file.after === undefined) context?.sessionState?.fileReads.entries.delete(file.path); else recordRead( file.path, { contentHash: hashFileBytes(encodeTextFile(file.after, file.encoding)), }, context?.sessionState?.fileReads, ); emitFileMutation(file.path); summaries.push( `${file.activity}: ${file.label} (${patch.additions === undefined ? 'diff 未统计' : `+${patch.additions} -${patch.deletions}`})`, ); } return { ok: true, content: `已应用补丁:\n${summaries.map((line) => `- ${line}`).join('\n')}`, ...(files.length ? { metadata: { kind: 'file_activity', files } as FileActivityMetadata } : {}), }; } export const applyPatchTool: Tool = { name: 'ApplyPatch', description: '提交 Codex 格式补丁,必须用 *** Begin Patch / *** End Patch 包络,不接受裸 git diff。支持 Add/Update/Delete File、Move to;路径相对工作区。无旧行、无行号的纯新增 hunk 追加到末尾。保留未修改行的换行符,仅支持无损 UTF-8(可带 BOM)或带 BOM 的 UTF-16LE,其他编码拒绝修改。先校验,写入失败尝试回滚,不保证跨文件断电原子性。', inputSchema: schema, parameters: toToolParameters(schema), isReadOnly: false, isConcurrencySafe: false, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, interruptBehavior: () => 'block', call: (input) => call(input), callWithContext: (input, _signal, context) => call(input, context), };