@trans-ai/trans-code 0.2.4 → 0.3.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,54 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
2
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { createAskModelTool } from './ask-model.js';
6
+ import { createToolSession } from './session.js';
7
+
8
+ const calls: Array<{ role: string; prompt: string; images?: string[] }> = [];
9
+ const stubAsk = async (role: string, prompt: string, images?: string[]) => {
10
+ calls.push({ role, prompt, images });
11
+ return `answer from ${role}`;
12
+ };
13
+ const tool = createAskModelTool(stubAsk);
14
+
15
+ let dir: string;
16
+ beforeEach(() => {
17
+ dir = mkdtempSync(path.join(tmpdir(), 'transcode-askmodel-'));
18
+ calls.length = 0;
19
+ });
20
+ afterEach(() => rmSync(dir, { recursive: true, force: true }));
21
+
22
+ describe('ask_model', () => {
23
+ test('delegates a sub-task to the routed role and returns its answer', async () => {
24
+ const session = createToolSession(dir);
25
+ const output = await tool.execute(
26
+ { role: 'analysis', prompt: '分析这个架构的扩展性' },
27
+ { cwd: dir, session },
28
+ );
29
+ expect(output).toBe('answer from analysis');
30
+ expect(calls[0]?.role).toBe('analysis');
31
+ expect(calls[0]?.prompt).toContain('扩展性');
32
+ });
33
+
34
+ test('passes image paths through for vision roles', async () => {
35
+ const session = createToolSession(dir);
36
+ writeFileSync(path.join(dir, 'shot.png'), Buffer.from([1, 2, 3]));
37
+ await tool.execute(
38
+ { role: 'vision', prompt: '截图里什么报错', images: ['shot.png'] },
39
+ { cwd: dir, session },
40
+ );
41
+ expect(calls[0]?.images?.length).toBe(1);
42
+ expect(calls[0]?.images?.[0]).toContain('shot.png');
43
+ });
44
+
45
+ test('surfaces routing errors with the configured roles listed', async () => {
46
+ const failing = createAskModelTool(async (role) => {
47
+ throw new Error(`Unknown role "${role}". Configured roles: analysis, design`);
48
+ });
49
+ const session = createToolSession(dir);
50
+ await expect(
51
+ failing.execute({ role: 'x', prompt: 'hi' }, { cwd: dir, session }),
52
+ ).rejects.toThrow(/Unknown role "x".*analysis, design/);
53
+ });
54
+ });
@@ -0,0 +1,44 @@
1
+ import { z } from 'zod';
2
+ import type { AgentTool } from './types.js';
3
+
4
+ export type AskRoleFn = (
5
+ role: string,
6
+ prompt: string,
7
+ images?: string[],
8
+ ctx?: { cwd: string },
9
+ ) => Promise<string>;
10
+
11
+ /** Factory so tests can inject a stub; production wires the provider. */
12
+ export function createAskModelTool(askRole: AskRoleFn): AgentTool {
13
+ return {
14
+ name: 'ask_model',
15
+ description:
16
+ 'Delegate a sub-task to a specialized model configured under a role ' +
17
+ '(analysis, design, review, vision, …). The sub-model answers in one shot; ' +
18
+ 'its answer comes back as text here. Use it for deep analysis, design ' +
19
+ 'trade-offs, reviews or describing images instead of doing everything ' +
20
+ 'yourself. images (optional) lists workspace file paths for vision roles.',
21
+ kind: 'think',
22
+ isMutating: false,
23
+ schema: z.object({
24
+ role: z.string().describe('Role name configured via /route'),
25
+ prompt: z.string().describe('The sub-task, fully self-contained'),
26
+ images: z
27
+ .array(z.string())
28
+ .nullable()
29
+ .optional()
30
+ .describe('Workspace image paths for vision roles'),
31
+ }),
32
+ title: (input) => `ask ${String(input.role ?? '')}: ${String(input.prompt ?? '').slice(0, 60)}`,
33
+ async execute(input, ctx) {
34
+ const role = String(input.role ?? '').trim();
35
+ const prompt = String(input.prompt ?? '').trim();
36
+ if (!role || !prompt) throw new Error('Both role and prompt are required.');
37
+ const images = Array.isArray(input.images)
38
+ ? (input.images as string[]).map((file) => String(file))
39
+ : undefined;
40
+ const answer = await askRole(role, prompt, images, { cwd: ctx.cwd });
41
+ return answer.length > 20_000 ? `${answer.slice(0, 20_000)}\n… (truncated)` : answer;
42
+ },
43
+ };
44
+ }
@@ -0,0 +1,115 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
2
+ import { mkdtempSync, rmSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { AIMessage, HumanMessage } from '@langchain/core/messages';
6
+ import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
7
+ import type { AgentLoopOptions, AgentLoopResult } from '../loop.js';
8
+ import { createDispatchAgentTool } from './dispatch.js';
9
+ import { readFileTool } from './files.js';
10
+ import { globTool } from './search.js';
11
+ import { setRouting } from '../../provider/provider.js';
12
+ import { createToolSession } from './session.js';
13
+
14
+ const pool = [readFileTool, globTool];
15
+ const runs: AgentLoopOptions[] = [];
16
+ const runLoopStub = async (options: AgentLoopOptions): Promise<AgentLoopResult> => {
17
+ runs.push(options);
18
+ return {
19
+ stopReason: 'end_turn',
20
+ messages: [new HumanMessage('task'), new AIMessage('调查结论:风险 A 和 B')],
21
+ };
22
+ };
23
+ const noopModel = {} as BaseChatModel;
24
+
25
+ let configDir: string;
26
+ beforeEach(() => {
27
+ configDir = mkdtempSync(path.join(tmpdir(), 'transcode-dispatch-test-'));
28
+ process.env.TRANSCODE_CONFIG_PATH = path.join(configDir, 'config.json');
29
+ runs.length = 0;
30
+ setRouting('research', 'deepseek');
31
+ });
32
+ afterEach(() => {
33
+ delete process.env.TRANSCODE_CONFIG_PATH;
34
+ delete process.env.TRANSCODE_SUBAGENT_MAX_TURNS;
35
+ rmSync(configDir, { recursive: true, force: true });
36
+ });
37
+
38
+ function makeTool() {
39
+ return createDispatchAgentTool({ runLoop: runLoopStub, tools: pool, model: noopModel });
40
+ }
41
+
42
+ describe('dispatch_agent', () => {
43
+ test('runs a nested loop for the routed role and returns its final report', async () => {
44
+ const tool = makeTool();
45
+ const session = createToolSession('/tmp');
46
+ const report = await tool.execute(
47
+ { role: 'research', task: '调查鉴权链路' },
48
+ { cwd: '/tmp', session },
49
+ );
50
+
51
+ expect(report).toBe('调查结论:风险 A 和 B');
52
+ expect(runs.length).toBe(1);
53
+ const run = runs[0]!;
54
+ expect(run.maxTurns).toBe(25);
55
+ expect(String((run.messages[0] as HumanMessage).content)).toBe('调查鉴权链路');
56
+ expect(run.systemPrompt).toMatch(/sub-?agent|子代理/i);
57
+ expect(run.tools?.map((item) => item.name).sort()).toEqual(['glob', 'read_file']);
58
+ });
59
+
60
+ test('is a mutating tool so dispatch requires user authorization', () => {
61
+ const tool = makeTool();
62
+ expect(tool.isMutating).toBe(true);
63
+ expect(tool.isReadOnly?.({ role: 'research', task: 'x' })).toBeFalsy();
64
+ });
65
+
66
+ test('unknown role lists the configured roles', async () => {
67
+ const tool = makeTool();
68
+ const session = createToolSession('/tmp');
69
+ await expect(
70
+ tool.execute({ role: 'nope', task: 'x' }, { cwd: '/tmp', session }),
71
+ ).rejects.toThrow(/Unknown role "nope".*research/);
72
+ });
73
+
74
+ test('unknown tool names in the whitelist are rejected', async () => {
75
+ const tool = makeTool();
76
+ const session = createToolSession('/tmp');
77
+ await expect(
78
+ tool.execute(
79
+ { role: 'research', task: 'x', tools: ['read_file', 'nuclear_launch'] },
80
+ { cwd: '/tmp', session },
81
+ ),
82
+ ).rejects.toThrow(/nuclear_launch/);
83
+ });
84
+
85
+ test('dispatch_agent itself can never be whitelisted (no recursion)', async () => {
86
+ const tool = makeTool();
87
+ const session = createToolSession('/tmp');
88
+ await expect(
89
+ tool.execute(
90
+ { role: 'research', task: 'x', tools: ['dispatch_agent'] },
91
+ { cwd: '/tmp', session },
92
+ ),
93
+ ).rejects.toThrow(/dispatch_agent/);
94
+ });
95
+
96
+ test('TRANSCODE_SUBAGENT_MAX_TURNS overrides the turn cap', async () => {
97
+ process.env.TRANSCODE_SUBAGENT_MAX_TURNS = '7';
98
+ const tool = makeTool();
99
+ const session = createToolSession('/tmp');
100
+ await tool.execute({ role: 'research', task: 'x' }, { cwd: '/tmp', session });
101
+ expect(runs[0]!.maxTurns).toBe(7);
102
+ });
103
+
104
+ test('an empty sub-agent report is an error', async () => {
105
+ const tool = createDispatchAgentTool({
106
+ runLoop: async () => ({ stopReason: 'end_turn', messages: [new HumanMessage('t')] }),
107
+ tools: pool,
108
+ model: noopModel,
109
+ });
110
+ const session = createToolSession('/tmp');
111
+ await expect(
112
+ tool.execute({ role: 'research', task: 'x' }, { cwd: '/tmp', session }),
113
+ ).rejects.toThrow(/报告|report/i);
114
+ });
115
+ });
@@ -0,0 +1,141 @@
1
+ import { z } from 'zod';
2
+ import { HumanMessage } from '@langchain/core/messages';
3
+ import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
4
+ import type { AgentLoopOptions, AgentLoopResult } from '../loop.js';
5
+ import type { AgentTool } from './types.js';
6
+ import { createToolSession } from './session.js';
7
+ import { createModel, getRouting } from '../../provider/provider.js';
8
+
9
+ export interface DispatchDeps {
10
+ runLoop?: (options: AgentLoopOptions) => Promise<AgentLoopResult>;
11
+ /** Tool pool the whitelist selects from; MUST NOT include dispatch itself. */
12
+ tools?: AgentTool[];
13
+ /** Injected model factory (tests). Default: createModel(profile). */
14
+ model?: BaseChatModel | ((profile: string) => BaseChatModel);
15
+ }
16
+
17
+ const DEFAULT_WHITELIST = ['read_file', 'glob', 'grep'];
18
+ const MAX_REPORT_CHARS = 30_000;
19
+
20
+ const SUBAGENT_SYSTEM_PROMPT =
21
+ 'You are a sub-agent. Complete the assigned task using the tools provided, then reply ' +
22
+ 'with a final, self-contained report in the same language as the task. The report is the ' +
23
+ 'only thing the dispatcher sees — include findings, evidence (file:line) and conclusions; ' +
24
+ 'do not ask questions back.';
25
+
26
+ /**
27
+ * dispatch_agent: the main model delegates an investigation-style sub-task to
28
+ * a routed role's model running its own agent loop with a tool whitelist.
29
+ * Context contract: task text in → final report out (the sub-agent sees
30
+ * nothing of the parent conversation). Dispatch itself is a mutating tool,
31
+ * so the user authorizes each dispatch (y/n) in ask mode.
32
+ */
33
+ export function createDispatchAgentTool(deps: DispatchDeps = {}): AgentTool {
34
+ const runLoop = deps.runLoop;
35
+ const pool = deps.tools;
36
+ return {
37
+ name: 'dispatch_agent',
38
+ description:
39
+ 'Dispatch a self-contained sub-task to a sub-agent running a routed role model ' +
40
+ '(configured via /route). The sub-agent explores with the whitelisted tools in its ' +
41
+ 'own loop and returns one final report; it does NOT see this conversation, so the ' +
42
+ 'task must carry all needed context (files, constraints, expected output). ' +
43
+ 'tools defaults to the read-only set (read_file, glob, grep). Use for multi-step ' +
44
+ 'research/investigation; use ask_model for single-shot expert questions.',
45
+ kind: 'execute',
46
+ isMutating: true,
47
+ schema: z.object({
48
+ role: z.string().describe('Role configured via /route (e.g. research, analysis)'),
49
+ task: z.string().describe('Fully self-contained sub-task description'),
50
+ tools: z
51
+ .array(z.string())
52
+ .nullable()
53
+ .optional()
54
+ .describe('Tool whitelist for the sub-agent (default: read_file, glob, grep)'),
55
+ }),
56
+ title: (input) =>
57
+ `dispatch ${String(input.role ?? '')}: ${String(input.task ?? '').slice(0, 60)}`,
58
+ async execute(input, ctx) {
59
+ const role = String(input.role ?? '').trim();
60
+ const task = String(input.task ?? '').trim();
61
+ if (!role || !task) throw new Error('Both role and task are required.');
62
+
63
+ const routing = getRouting();
64
+ const profile = routing[role];
65
+ if (!profile) {
66
+ const names = Object.keys(routing).join(', ');
67
+ throw new Error(
68
+ `Unknown role "${role}". Configured roles: ${names || '(none — set one with /route)'}`,
69
+ );
70
+ }
71
+
72
+ const poolTools = pool;
73
+ if (!poolTools) throw new Error('dispatch_agent is not wired with a tool pool.');
74
+
75
+ const explicit = Array.isArray(input.tools) && input.tools.length > 0
76
+ ? (input.tools as string[]).map((name) => String(name))
77
+ : undefined;
78
+ let requested: string[];
79
+ if (explicit) {
80
+ const missing = explicit.filter((name) => !poolTools.some((item) => item.name === name));
81
+ if (missing.length > 0) {
82
+ throw new Error(
83
+ `Unknown or forbidden tools: ${missing.join(', ')}. ` +
84
+ `Available: ${poolTools.map((item) => item.name).join(', ')}`,
85
+ );
86
+ }
87
+ requested = explicit;
88
+ } else {
89
+ // Default: the read-only set intersected with the wired pool.
90
+ requested = DEFAULT_WHITELIST.filter((name) =>
91
+ poolTools.some((item) => item.name === name),
92
+ );
93
+ }
94
+ const selected = poolTools.filter((item) => requested.includes(item.name));
95
+
96
+ const model =
97
+ typeof deps.model === 'function'
98
+ ? deps.model(profile)
99
+ : deps.model
100
+ ? deps.model
101
+ : createModel(profile).model;
102
+
103
+ const envTurns = Number(process.env.TRANSCODE_SUBAGENT_MAX_TURNS);
104
+ const maxTurns = Number.isFinite(envTurns) && envTurns > 0 ? envTurns : 25;
105
+
106
+ const result = await runLoop!({
107
+ model,
108
+ cwd: ctx.session.cwd,
109
+ messages: [new HumanMessage(task)],
110
+ systemPrompt: SUBAGENT_SYSTEM_PROMPT,
111
+ tools: selected,
112
+ maxTurns,
113
+ toolSession: createToolSession(ctx.session.cwd),
114
+ onEvent: () => {},
115
+ requestPermission: ctx.requestPermission,
116
+ });
117
+
118
+ const lastAi = [...result.messages].reverse().find((message) => message.getType() === 'ai');
119
+ const content = lastAi?.content;
120
+ const report =
121
+ typeof content === 'string'
122
+ ? content
123
+ : Array.isArray(content)
124
+ ? content
125
+ .map((block) =>
126
+ block && typeof block === 'object' && typeof (block as { text?: unknown }).text === 'string'
127
+ ? (block as { text: string }).text
128
+ : '',
129
+ )
130
+ .join('')
131
+ : '';
132
+
133
+ if (!report.trim()) {
134
+ throw new Error(`子代理未产出报告(stopReason: ${result.stopReason})。`);
135
+ }
136
+ return report.length > MAX_REPORT_CHARS
137
+ ? `${report.slice(0, MAX_REPORT_CHARS)}\n… (truncated)`
138
+ : report;
139
+ },
140
+ };
141
+ }
@@ -53,6 +53,34 @@ describe('read_file', () => {
53
53
  expect(output).toContain('short');
54
54
  expect(output.length).toBeLessThan(2400);
55
55
  });
56
+
57
+ test('returns image files as base64 multimodal content', async () => {
58
+ const dir = workspace();
59
+ const session = createToolSession(dir);
60
+ // Minimal fake PNG: magic bytes + payload.
61
+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]);
62
+ writeFileSync(path.join(dir, 'logo.png'), png);
63
+
64
+ const result = await readFileTool.execute({ path: 'logo.png' }, ctx(session));
65
+ expect(typeof result).toBe('object');
66
+ const output = result as { output: string; images?: Array<{ data: string; mediaType: string }> };
67
+ expect(output.images?.length).toBe(1);
68
+ expect(output.images?.[0]?.mediaType).toBe('image/png');
69
+ expect(output.images?.[0]?.data).toBe(png.toString('base64'));
70
+ expect(output.output).toContain('image');
71
+ expect(hasFileBeenRead(session, path.join(dir, 'logo.png'))).toBe(true);
72
+ });
73
+
74
+ test('rejects oversized images instead of blowing up the context', async () => {
75
+ const dir = workspace();
76
+ const session = createToolSession(dir);
77
+ const huge = Buffer.alloc(3_500_000, 7);
78
+ writeFileSync(path.join(dir, 'big.jpg'), huge);
79
+
80
+ await expect(readFileTool.execute({ path: 'big.jpg' }, ctx(session))).rejects.toThrow(
81
+ /3 MB|3MB/,
82
+ );
83
+ });
56
84
  });
57
85
 
58
86
  describe('write_file', () => {
@@ -118,6 +146,74 @@ describe('edit_file', () => {
118
146
  expect(readFileSync(path.join(dir, 'prose.md'), 'utf8')).toBe('She said "go" now\n');
119
147
  });
120
148
 
149
+ test('applies multiple edits in one call', async () => {
150
+ const dir = workspace();
151
+ writeFileSync(
152
+ path.join(dir, 'multi.txt'),
153
+ 'alpha\nbeta\ngamma\nbeta\n',
154
+ );
155
+ const session = createToolSession(dir);
156
+
157
+ await read(session, 'multi.txt');
158
+ const result = await editFileTool.execute(
159
+ {
160
+ path: 'multi.txt',
161
+ edits: [
162
+ { old_string: 'alpha', new_string: 'ALPHA' },
163
+ { old_string: 'gamma', new_string: 'GAMMA' },
164
+ { old_string: 'beta\n', new_string: 'BETA\n', replace_all: true },
165
+ ],
166
+ },
167
+ ctx(session),
168
+ );
169
+
170
+ expect(readFileSync(path.join(dir, 'multi.txt'), 'utf8')).toBe('ALPHA\nBETA\nGAMMA\nBETA\n');
171
+ expect(result.output).toContain('Replaced 4 occurrence(s)');
172
+ expect(result.diff).toContain('-alpha');
173
+ expect(result.diff).toContain('+GAMMA');
174
+ });
175
+
176
+ test('multi-edit is atomic: a missing edit leaves the file untouched', async () => {
177
+ const dir = workspace();
178
+ writeFileSync(path.join(dir, 'a.txt'), 'one\ntwo\n');
179
+ const session = createToolSession(dir);
180
+
181
+ await read(session, 'a.txt');
182
+ await expect(
183
+ editFileTool.execute(
184
+ {
185
+ path: 'a.txt',
186
+ edits: [
187
+ { old_string: 'one', new_string: 'ONE' },
188
+ { old_string: 'nope', new_string: 'X' },
189
+ ],
190
+ },
191
+ ctx(session),
192
+ ),
193
+ ).rejects.toThrow(/not found/);
194
+ expect(readFileSync(path.join(dir, 'a.txt'), 'utf8')).toBe('one\ntwo\n');
195
+ });
196
+
197
+ test('multi-edit rejects an old_string contained in an earlier new_string', async () => {
198
+ const dir = workspace();
199
+ writeFileSync(path.join(dir, 'a.txt'), 'one\ntwo\n');
200
+ const session = createToolSession(dir);
201
+
202
+ await read(session, 'a.txt');
203
+ await expect(
204
+ editFileTool.execute(
205
+ {
206
+ path: 'a.txt',
207
+ edits: [
208
+ { old_string: 'one', new_string: 'one plus two' },
209
+ { old_string: 'two', new_string: 'TWO' },
210
+ ],
211
+ },
212
+ ctx(session),
213
+ ),
214
+ ).rejects.toThrow(/substring/);
215
+ });
216
+
121
217
  test('returns a line-numbered snippet around the edit', async () => {
122
218
  const dir = workspace();
123
219
  const lines = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'];
@@ -8,6 +8,33 @@ import { lineDiff } from './diff.js';
8
8
 
9
9
  const SNIPPET_CONTEXT_LINES = 4;
10
10
  const NEW_FILE_DIFF_LINES = 20;
11
+ const MAX_IMAGE_BYTES = 3_000_000;
12
+
13
+ const IMAGE_MEDIA: Record<string, string> = {
14
+ png: 'image/png',
15
+ jpg: 'image/jpeg',
16
+ jpeg: 'image/jpeg',
17
+ gif: 'image/gif',
18
+ webp: 'image/webp',
19
+ };
20
+
21
+ /** Reads workspace image paths into base64 blocks (shared with ask_model). */
22
+ export async function readImageBlocks(
23
+ paths: string[],
24
+ ctx: { cwd: string },
25
+ ): Promise<Array<{ data: string; mediaType: string }>> {
26
+ const blocks: Array<{ data: string; mediaType: string }> = [];
27
+ for (const inputPath of paths) {
28
+ const absolute = resolveInsideWorkspace(ctx.cwd, String(inputPath));
29
+ const mediaType = IMAGE_MEDIA[path.extname(absolute).slice(1).toLowerCase()];
30
+ if (!mediaType) throw new Error(`Not an image file: ${inputPath}`);
31
+ const stat = await fs.stat(absolute);
32
+ if (stat.size > MAX_IMAGE_BYTES) throw new Error(`Image too large (>3MB): ${inputPath}`);
33
+ const buffer = await fs.readFile(absolute);
34
+ blocks.push({ data: buffer.toString('base64'), mediaType });
35
+ }
36
+ return blocks;
37
+ }
11
38
 
12
39
  // Claude-style quote normalization: models emit straight quotes, files often
13
40
  // contain curly ones. Both sides are normalized before matching.
@@ -91,6 +118,24 @@ export const readFileTool: AgentTool = {
91
118
  'Use grep or bash (head/tail) to inspect it.',
92
119
  );
93
120
  }
121
+
122
+ // Images are returned as base64 multimodal blocks for vision models.
123
+ const mediaType = IMAGE_MEDIA[path.extname(absolute).slice(1).toLowerCase()];
124
+ if (mediaType) {
125
+ if (stat.size > MAX_IMAGE_BYTES) {
126
+ throw new Error(
127
+ `Image is ${(stat.size / 1_000_000).toFixed(1)} MB, above the 3 MB limit. ` +
128
+ 'Downscale it before reading.',
129
+ );
130
+ }
131
+ const buffer = await fs.readFile(absolute);
132
+ markFileRead(ctx.session, absolute);
133
+ return {
134
+ output: `[image ${displayPath(ctx.cwd, absolute)}, ${stat.size} bytes, shown visually]`,
135
+ images: [{ data: buffer.toString('base64'), mediaType }],
136
+ };
137
+ }
138
+
94
139
  if (stat.size > MAX_READ_BYTES && !input.offset && !input.limit) {
95
140
  throw new Error(
96
141
  `File is ${stat.size} bytes. Pass offset/limit to read it in chunks.`,
@@ -189,51 +234,88 @@ export const editFileTool: AgentTool = {
189
234
  isMutating: true,
190
235
  schema: z.object({
191
236
  path: z.string().describe('File path, relative to the workspace root'),
192
- old_string: z.string().describe('Exact text to replace'),
193
- new_string: z.string().describe('Replacement text'),
237
+ old_string: z.string().nullable().optional().describe('Exact text to replace (single-edit mode)'),
238
+ new_string: z.string().nullable().optional().describe('Replacement text (single-edit mode)'),
194
239
  replace_all: z.boolean().nullable().optional().describe('Replace every occurrence'),
240
+ edits: z
241
+ .array(
242
+ z.object({
243
+ old_string: z.string().describe('Exact text to replace'),
244
+ new_string: z.string().describe('Replacement text'),
245
+ replace_all: z.boolean().nullable().optional().describe('Replace every occurrence'),
246
+ }),
247
+ )
248
+ .nullable()
249
+ .optional()
250
+ .describe('Multiple edits applied in order (multi-edit mode; preferred for 2+ changes)'),
195
251
  }),
196
252
  title: (input) => `patch: ${String(input.path ?? '')}`,
197
253
  async execute(input, ctx) {
198
254
  const absolute = resolveInsideWorkspace(ctx.cwd, String(input.path));
199
255
  requireRead(ctx.session, absolute, displayPath(ctx.cwd, absolute));
200
256
 
201
- const oldString = String(input.old_string);
202
- const newString = String(input.new_string);
203
- if (oldString === newString) throw new Error('old_string and new_string are identical');
204
-
205
257
  const original = await fs.readFile(absolute, 'utf8');
258
+ const editList = Array.isArray(input.edits)
259
+ ? (input.edits as Array<{ old_string: string; new_string: string; replace_all?: boolean }>)
260
+ : [{ old_string: String(input.old_string), new_string: String(input.new_string), replace_all: input.replace_all === true }];
261
+ if (editList.length === 0) throw new Error('No edits given.');
206
262
 
207
- const actualOld = findActualString(original, oldString);
208
- if (actualOld === null) {
209
- throw new Error('old_string was not found in the file. Read it again and use exact text.');
210
- }
211
- const occurrences = actualOld === '' ? 0 : original.split(actualOld).length - 1;
212
- if (occurrences === 0) {
213
- throw new Error('old_string was not found in the file. Read it again and use exact text.');
214
- }
215
- if (occurrences > 1 && input.replace_all !== true) {
216
- throw new Error(
217
- `old_string appears ${occurrences} times. Pass replace_all=true or include more context.`,
218
- );
263
+ // Validate and apply every edit in memory first: a failure anywhere
264
+ // must leave the file untouched (atomic multi-edit).
265
+ const appliedNewStrings: string[] = [];
266
+ let updated = original;
267
+ let replacedCount = 0;
268
+ for (const edit of editList) {
269
+ const oldString = String(edit.old_string);
270
+ const newString = String(edit.new_string);
271
+ if (oldString === newString) throw new Error('old_string and new_string are identical');
272
+
273
+ const checkOld = oldString.replace(/\n+$/, '');
274
+ for (const previous of appliedNewStrings) {
275
+ if (checkOld !== '' && previous.includes(checkOld)) {
276
+ throw new Error(
277
+ 'Cannot edit file: old_string is a substring of a new_string from a previous edit. ' +
278
+ 'Merge those edits or reorder them.',
279
+ );
280
+ }
281
+ }
282
+
283
+ const actualOld = findActualString(updated, oldString);
284
+ if (actualOld === null) {
285
+ throw new Error('old_string was not found in the file. Read it again and use exact text.');
286
+ }
287
+ const occurrences = actualOld === '' ? 0 : updated.split(actualOld).length - 1;
288
+ if (occurrences === 0) {
289
+ throw new Error('old_string was not found in the file. Read it again and use exact text.');
290
+ }
291
+ if (occurrences > 1 && edit.replace_all !== true) {
292
+ throw new Error(
293
+ `old_string appears ${occurrences} times. Pass replace_all=true or include more context.`,
294
+ );
295
+ }
296
+
297
+ updated =
298
+ edit.replace_all === true
299
+ ? updated.split(actualOld).join(newString)
300
+ : updated.replace(actualOld, () => newString);
301
+ replacedCount += edit.replace_all === true ? occurrences : 1;
302
+ appliedNewStrings.push(newString);
219
303
  }
220
304
 
221
- const updated =
222
- input.replace_all === true
223
- ? original.split(actualOld).join(newString)
224
- : original.replace(actualOld, () => newString);
225
305
  await fs.writeFile(absolute, updated, 'utf8');
226
306
 
227
- const replacedCount = input.replace_all === true ? occurrences : 1;
228
- const before = original.split(actualOld)[0] ?? '';
229
- const replacementLine = before.split(/\r?\n/).length - 1;
230
- const snippetStart = Math.max(0, replacementLine - SNIPPET_CONTEXT_LINES);
231
- const snippet = snippetAfterEdit(original, actualOld, newString, snippetStart);
307
+ let snippet = '';
308
+ if (editList.length === 1) {
309
+ const actualOld = findActualString(original, String(editList[0]!.old_string)) ?? '';
310
+ const before = original.split(actualOld)[0] ?? '';
311
+ const replacementLine = before.split(/\r?\n/).length - 1;
312
+ const snippetStart = Math.max(0, replacementLine - SNIPPET_CONTEXT_LINES);
313
+ snippet = `\n\n${snippetAfterEdit(original, actualOld, String(editList[0]!.new_string), snippetStart)}`;
314
+ }
232
315
 
233
316
  return {
234
317
  output:
235
- `Replaced ${replacedCount} occurrence(s) in ${displayPath(ctx.cwd, absolute)}\n\n` +
236
- `${snippet}`,
318
+ `Replaced ${replacedCount} occurrence(s) in ${displayPath(ctx.cwd, absolute)}${snippet}`,
237
319
  diff: lineDiff(original, updated) || undefined,
238
320
  };
239
321
  },