minimal-agent 0.18.21 → 0.18.22

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.
Files changed (127) hide show
  1. package/README.md +16 -3
  2. package/package.json +1 -1
  3. package/plugins/workflow-runner/plugin.js +1 -0
  4. package/plugins/workflow-runner/plugin.ts +1 -0
  5. package/plugins/workflow-runner/src/index.js +1 -0
  6. package/plugins/workflow-runner/src/index.ts +2 -0
  7. package/plugins/workflow-runner/src/runner.js +6 -1
  8. package/plugins/workflow-runner/src/runner.ts +5 -1
  9. package/plugins/workflow-runner/src/types.ts +1 -0
  10. package/plugins/workflow-runner/test/childWorkflow.test.ts +19 -0
  11. package/src/advisor/README.md +7 -3
  12. package/src/advisor/advisorNudge.js +3 -3
  13. package/src/advisor/advisorNudge.ts +3 -3
  14. package/src/advisor/deliveryReview.js +9 -2
  15. package/src/advisor/deliveryReview.ts +10 -2
  16. package/src/cli/args.js +1 -0
  17. package/src/cli/args.ts +1 -0
  18. package/src/cli/headlessTurn.js +143 -0
  19. package/src/cli/headlessTurn.ts +187 -0
  20. package/src/cli/lifecycle.js +52 -0
  21. package/src/cli/lifecycle.ts +59 -0
  22. package/src/cli/print.js +91 -240
  23. package/src/cli/print.ts +99 -301
  24. package/src/cli/quickModelSetup.js +3 -0
  25. package/src/cli/quickModelSetup.tsx +3 -0
  26. package/src/cli/streamJson.js +244 -334
  27. package/src/cli/streamJson.ts +248 -416
  28. package/src/cli/wizards/providerPresets.js +25 -14
  29. package/src/cli/wizards/providerPresets.ts +25 -14
  30. package/src/cli/wizards/providerWizard.js +29 -11
  31. package/src/cli/wizards/providerWizard.tsx +29 -11
  32. package/src/config/configDiagnostics.js +7 -3
  33. package/src/config/configDiagnostics.ts +6 -3
  34. package/src/context/compact.js +40 -10
  35. package/src/context/compact.ts +51 -12
  36. package/src/context/compactResources.js +39 -0
  37. package/src/context/compactResources.ts +35 -0
  38. package/src/context/manualCompact.js +20 -0
  39. package/src/context/manualCompact.ts +28 -0
  40. package/src/llm/client.js +4 -0
  41. package/src/llm/client.ts +4 -0
  42. package/src/llm/messageProvenance.js +1 -1
  43. package/src/llm/messageProvenance.ts +1 -1
  44. package/src/loop/deliveryIntent.js +3 -2
  45. package/src/loop/deliveryIntent.ts +4 -2
  46. package/src/loop/messages.js +1 -0
  47. package/src/loop/messages.ts +1 -0
  48. package/src/loop/options.ts +2 -0
  49. package/src/loop.js +4 -2
  50. package/src/loop.ts +4 -2
  51. package/src/main.js +40 -45
  52. package/src/main.tsx +33 -52
  53. package/src/plugins/artifactDelivery.js +76 -0
  54. package/src/plugins/artifactDelivery.ts +76 -0
  55. package/src/plugins/pluginApi.ts +2 -0
  56. package/src/plugins/pluginRunner.js +2 -0
  57. package/src/plugins/pluginRunner.ts +3 -0
  58. package/src/prompts/delegation.js +1 -1
  59. package/src/prompts/delegation.ts +1 -1
  60. package/src/prompts/policyRegistry.js +7 -6
  61. package/src/prompts/policyRegistry.ts +7 -6
  62. package/src/prompts/promptAssembly.js +2 -2
  63. package/src/prompts/promptAssembly.ts +2 -2
  64. package/src/runtime/requestIntent.js +86 -0
  65. package/src/runtime/requestIntent.ts +66 -0
  66. package/src/runtime/systemEvents.js +10 -1
  67. package/src/runtime/systemEvents.ts +9 -1
  68. package/src/session/commandTranscript.js +76 -0
  69. package/src/session/commandTranscript.ts +77 -0
  70. package/src/session/runTurn.js +24 -3
  71. package/src/session/runTurn.ts +24 -3
  72. package/src/tools/advisor/advisor.js +1 -1
  73. package/src/tools/advisor/advisor.ts +1 -1
  74. package/src/tools/advisor/advisorCoordination.js +3 -2
  75. package/src/tools/advisor/advisorCoordination.ts +3 -2
  76. package/src/tools/advisor/advisorDescription.js +1 -1
  77. package/src/tools/advisor/advisorDescription.ts +1 -1
  78. package/src/tools/agent/README.md +2 -0
  79. package/src/tools/agent/agent.js +3 -0
  80. package/src/tools/agent/agent.ts +3 -0
  81. package/src/tools/agent/agentHandoff.js +2 -1
  82. package/src/tools/agent/agentHandoff.ts +2 -1
  83. package/src/tools/agent/agentTaskService.js +26 -5
  84. package/src/tools/agent/agentTaskService.ts +23 -5
  85. package/src/tools/agent/agentTypes.js +1 -1
  86. package/src/tools/agent/agentTypes.ts +1 -1
  87. package/src/tools/applypatch/applyPatch.js +39 -13
  88. package/src/tools/applypatch/applyPatch.ts +35 -15
  89. package/src/tools/bash/bash.js +3 -0
  90. package/src/tools/bash/bash.ts +3 -0
  91. package/src/tools/download/download.js +147 -11
  92. package/src/tools/download/download.ts +193 -17
  93. package/src/tools/edit/edit.js +4 -4
  94. package/src/tools/edit/edit.ts +4 -4
  95. package/src/tools/edit/multi-edit.js +2 -2
  96. package/src/tools/edit/multi-edit.ts +2 -2
  97. package/src/tools/powershell/powershell.js +2 -0
  98. package/src/tools/powershell/powershell.ts +2 -0
  99. package/src/tools/shared/fileUtils.js +16 -6
  100. package/src/tools/shared/fileUtils.ts +15 -6
  101. package/src/tools/tasks/backgroundTaskService.js +108 -12
  102. package/src/tools/tasks/backgroundTaskService.ts +106 -14
  103. package/src/tools/tasks/taskOutput.js +15 -5
  104. package/src/tools/tasks/taskOutput.ts +13 -5
  105. package/src/tools/tasks/taskStop.js +2 -2
  106. package/src/tools/tasks/taskStop.ts +2 -2
  107. package/src/tools/toolPromptGuides.js +3 -3
  108. package/src/tools/toolPromptGuides.ts +3 -3
  109. package/src/tools/webfetch/webfetch.js +1 -1
  110. package/src/tools/webfetch/webfetch.ts +1 -1
  111. package/src/types.ts +4 -0
  112. package/src/ui/InputBox.js +2 -2
  113. package/src/ui/InputBox.tsx +2 -2
  114. package/src/ui/MessageList.js +2 -0
  115. package/src/ui/MessageList.tsx +2 -0
  116. package/src/ui/README.md +8 -2
  117. package/src/ui/activityPresentation.js +22 -2
  118. package/src/ui/activityPresentation.ts +21 -2
  119. package/src/ui/backgroundWake.js +20 -4
  120. package/src/ui/backgroundWake.ts +19 -4
  121. package/src/ui/commandTranscript.js +2 -69
  122. package/src/ui/commandTranscript.ts +2 -71
  123. package/src/ui/hooks/useChat.js +41 -25
  124. package/src/ui/hooks/useChat.ts +30 -23
  125. package/src/web/protocol.ts +3 -2
  126. package/src/cli/wizards/advisorWizard.js +0 -152
  127. package/src/cli/wizards/advisorWizard.tsx +0 -203
@@ -20,6 +20,10 @@
20
20
  */
21
21
 
22
22
  import { z } from 'zod';
23
+ import { randomUUID } from 'node:crypto';
24
+ import { existsSync } from 'node:fs';
25
+ import { mkdir, realpath, link, rm, writeFile } from 'node:fs/promises';
26
+ import { basename, dirname, join, resolve } from 'node:path';
23
27
 
24
28
  import type { Tool, ToolCallContext, ToolResult } from '../../types.js';
25
29
  import { getWorkingDir } from '../../bootstrap/workingDir.js';
@@ -28,20 +32,37 @@ import { fileActivityMetadata } from '../shared/fileActivity.js';
28
32
  import { atomicWriteFile, resolveToolPath } from '../shared/fileUtils.js';
29
33
  import { emitFileMutation } from '../shared/fileMutationBus.js';
30
34
  import { readHttpBody } from '../shared/httpBody.js';
35
+ import { mustSettleBackgroundTasks } from '../../runtime/invocationPolicy.js';
36
+ import { startBackgroundOperation } from '../tasks/backgroundTaskService.js';
31
37
 
32
38
  const DEFAULT_TIMEOUT_MS = 60_000;
33
39
  const DEFAULT_MAX_BYTES = 25 * 1024 * 1024;
34
40
 
35
41
  // ---------------- 1. Zod 输入 schema ----------------
36
42
  const inputSchema = z.object({
37
- url: z.string().url().regex(/^https?:\/\//i).describe('http(s) resource URL to download'),
43
+ run_in_background: z
44
+ .boolean()
45
+ .optional()
46
+ .describe(
47
+ 'Run as a session-owned background task; only new destination files are allowed. Use TaskOutput/TaskStop. Hosts without continuation support may wait instead.',
48
+ ),
49
+ url: z
50
+ .string()
51
+ .url()
52
+ .regex(/^https?:\/\//i)
53
+ .describe('http(s) resource URL to download'),
38
54
  path: z
39
- .string().min(1)
40
- .describe('Destination file path (relative paths anchor to the working dir)'),
55
+ .string()
56
+ .min(1)
57
+ .describe(
58
+ 'Destination file path (relative paths anchor to the working dir)',
59
+ ),
41
60
  headers: z
42
61
  .record(z.string())
43
62
  .optional()
44
- .describe('Optional request headers for the resource (e.g. Referer or User-Agent)'),
63
+ .describe(
64
+ 'Optional request headers for the resource (e.g. Referer or User-Agent)',
65
+ ),
45
66
  timeout: z
46
67
  .number()
47
68
  .int()
@@ -53,13 +74,64 @@ const inputSchema = z.object({
53
74
  .int()
54
75
  .positive()
55
76
  .optional()
56
- .describe('Max size in bytes; over this the download is rejected (default: 25MB)'),
77
+ .describe(
78
+ 'Max size in bytes; over this the download is rejected (default: 25MB)',
79
+ ),
57
80
  });
58
81
  type DownloadInput = z.infer<typeof inputSchema>;
59
82
 
60
83
  const parameters = toToolParameters(inputSchema);
61
84
 
62
- const description = '下载 HTTP(S) 原始字节到指定路径;相对路径基于工作目录,会覆盖已有文件;失败或中断不保留部分下载。';
85
+ const description =
86
+ '下载 HTTP(S) 原始字节到指定路径;相对路径基于工作目录。前台会覆盖已有文件;run_in_background 仅允许新目标文件,返回 task_id,用 TaskOutput/TaskStop 查询或取消。只有声明自动接续的宿主才会完成后唤醒。取消不等于撤销已完成的写入。';
87
+
88
+ const activeDestinations = new Set<string>();
89
+
90
+ /** Resolve aliases even when the destination's parent does not exist yet. */
91
+ async function resolveDestination(path: string): Promise<string> {
92
+ const parent = dirname(path);
93
+ const physical = await realpath(path).catch(
94
+ async (error: NodeJS.ErrnoException) => {
95
+ if (error.code !== 'ENOENT') throw error;
96
+ if (parent === path) throw error;
97
+ return resolve(await resolveDestination(parent), basename(path));
98
+ },
99
+ );
100
+ return physical;
101
+ }
102
+
103
+ /** Publish a fully written new file without replacing a racing writer's file. */
104
+ async function publishNewFile(
105
+ path: string,
106
+ bytes: Uint8Array,
107
+ signal: AbortSignal,
108
+ ): Promise<void> {
109
+ await mkdir(dirname(path), { recursive: true });
110
+ const temp = join(dirname(path), `.${randomUUID()}.download.tmp`);
111
+ let published = false;
112
+ try {
113
+ await writeFile(temp, bytes, { flag: 'wx' });
114
+ signal.throwIfAborted();
115
+ try {
116
+ await link(temp, path); // Atomic create-if-absent; EEXIST never overwrites.
117
+ } catch (error) {
118
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST')
119
+ throw new Error(`目标已被其他操作创建,未覆盖:${path}`);
120
+ throw new Error(
121
+ `无法安全发布新文件(需要支持硬链接的文件系统),未覆盖目标:${path};${(error as Error).message}`,
122
+ );
123
+ }
124
+ published = true;
125
+ } finally {
126
+ try {
127
+ await rm(temp, { force: true, maxRetries: 3, retryDelay: 50 });
128
+ } catch (error) {
129
+ throw new Error(
130
+ `${published ? '目标文件已发布,不能当作未写入重试' : '临时文件未清理'}:${temp};${(error as Error).message}`,
131
+ );
132
+ }
133
+ }
134
+ }
63
135
 
64
136
  // ---------------- 2. 依赖注入(仅测试) ----------------
65
137
  interface FetchResponseLike {
@@ -89,17 +161,103 @@ async function call(
89
161
  signal?: AbortSignal,
90
162
  deps: DownloadDeps = defaultDeps,
91
163
  cwd = getWorkingDir(),
164
+ context?: ToolCallContext,
165
+ ): Promise<ToolResult> {
166
+ const destination = resolveToolPath(input.path, cwd);
167
+ if (!destination.ok) return destination;
168
+ if (signal?.aborted) return { ok: false, error: '[Download] 已取消,未启动' };
169
+ let physical: string;
170
+ try {
171
+ physical = await resolveDestination(destination.resolvedPath);
172
+ } catch (error) {
173
+ return { ok: false, error: `[Download] ${(error as Error).message}` };
174
+ }
175
+ const key = process.platform === 'win32' ? physical.toLowerCase() : physical;
176
+ if (activeDestinations.has(key))
177
+ return {
178
+ ok: false,
179
+ error:
180
+ '[Download] 该目标已有下载任务,拒绝并发覆盖;请先等待或取消原任务。',
181
+ };
182
+ if (input.run_in_background && existsSync(physical))
183
+ return {
184
+ ok: false,
185
+ error: '[Download] 后台下载只允许新目标,文件已存在;请另选路径。',
186
+ };
187
+ activeDestinations.add(key);
188
+ const execute = async (jobSignal?: AbortSignal) => {
189
+ try {
190
+ return await performDownload(
191
+ { ...input, path: physical },
192
+ jobSignal,
193
+ deps,
194
+ cwd,
195
+ );
196
+ } finally {
197
+ activeDestinations.delete(key);
198
+ }
199
+ };
200
+ if (
201
+ input.run_in_background &&
202
+ !mustSettleBackgroundTasks(context?.executionServices?.invocationPolicy)
203
+ ) {
204
+ if (!context?.sessionState) {
205
+ activeDestinations.delete(key);
206
+ return {
207
+ ok: false,
208
+ error: '[Download] 后台下载需要会话宿主;请使用前台模式。',
209
+ };
210
+ }
211
+ try {
212
+ signal?.throwIfAborted();
213
+ const task = await startBackgroundOperation(
214
+ {
215
+ command: `Download → ${destination.resolvedPath}`,
216
+ cwd,
217
+ signal,
218
+ workspaceId: context.workspaceId,
219
+ sessionId: context.sessionId,
220
+ deliveryId: context.deliveryId,
221
+ request: context.backgroundRequest ?? context.currentUserInput,
222
+ },
223
+ execute,
224
+ context.sessionState.backgroundTasks,
225
+ );
226
+ return {
227
+ ok: true,
228
+ content: `后台下载已启动。task_id=${task.id}\n目标:${destination.resolvedPath}\n使用 TaskOutput 查询结果,TaskStop 停止任务;尚未完成下载。`,
229
+ };
230
+ } catch (error) {
231
+ activeDestinations.delete(key);
232
+ return {
233
+ ok: false,
234
+ error: `[Download] 后台启动失败:${(error as Error).message}`,
235
+ };
236
+ }
237
+ }
238
+ return execute(signal);
239
+ }
240
+
241
+ async function performDownload(
242
+ input: DownloadInput,
243
+ signal: AbortSignal | undefined,
244
+ deps: DownloadDeps,
245
+ cwd: string,
92
246
  ): Promise<ToolResult> {
93
247
  const { url, path } = input;
94
248
  const timeout = input.timeout ?? DEFAULT_TIMEOUT_MS;
95
249
  const maxBytes = input.max_bytes ?? DEFAULT_MAX_BYTES;
96
- if (!/^https?:\/\//i.test(url)) return { ok: false, error: '[Download] 仅支持 HTTP(S) URL' };
250
+ if (!/^https?:\/\//i.test(url))
251
+ return { ok: false, error: '[Download] 仅支持 HTTP(S) URL' };
97
252
  let origin: string;
98
253
  try {
99
254
  const target = new URL(url);
100
- if (target.username || target.password) return { ok: false, error: '[Download] URL 中不能包含用户名或密码' };
255
+ if (target.username || target.password)
256
+ return { ok: false, error: '[Download] URL 中不能包含用户名或密码' };
101
257
  origin = target.origin;
102
- } catch { return { ok: false, error: '[Download] URL 格式无效' }; }
258
+ } catch {
259
+ return { ok: false, error: '[Download] URL 格式无效' };
260
+ }
103
261
 
104
262
  const destination = resolveToolPath(path, cwd);
105
263
  if (!destination.ok) return destination;
@@ -107,6 +265,7 @@ async function call(
107
265
 
108
266
  // 合并外部 signal 与超时
109
267
  const ctrl = new AbortController();
268
+ let committed = false;
110
269
  const timer = setTimeout(() => ctrl.abort(), timeout);
111
270
  const onAbort = () => ctrl.abort();
112
271
  if (signal) {
@@ -118,14 +277,20 @@ async function call(
118
277
  ctrl.signal.throwIfAborted();
119
278
  let res: FetchResponseLike;
120
279
  try {
121
- res = await deps.fetchImpl(url, { headers: input.headers, signal: ctrl.signal });
280
+ res = await deps.fetchImpl(url, {
281
+ headers: input.headers,
282
+ signal: ctrl.signal,
283
+ });
122
284
  } catch (e) {
123
285
  const msg = ctrl.signal.aborted
124
286
  ? `下载超时(${timeout}ms)或被中断`
125
287
  : e instanceof Error
126
288
  ? e.message
127
289
  : String(e);
128
- return { ok: false, error: `[Download] 请求失败:${msg.replaceAll(url, origin)}(${origin})` };
290
+ return {
291
+ ok: false,
292
+ error: `[Download] 请求失败:${msg.replaceAll(url, origin)}(${origin})`,
293
+ };
129
294
  }
130
295
 
131
296
  if (!res.ok) {
@@ -155,17 +320,28 @@ async function call(
155
320
  }
156
321
 
157
322
  ctrl.signal.throwIfAborted();
158
- await atomicWriteFile(abs, buf);
323
+ if (input.run_in_background) await publishNewFile(abs, buf, ctrl.signal);
324
+ else await atomicWriteFile(abs, buf);
325
+ committed = true;
159
326
  emitFileMutation(abs);
160
327
 
161
328
  const ctype = res.headers.get('content-type') ?? 'unknown';
162
329
  return {
163
330
  ok: true,
164
331
  content: `DOWNLOADED: ${buf.byteLength} 字节 → ${abs}(${ctype})`,
165
- metadata: await fileActivityMetadata(abs, 'generated', 'not_run', 'support', cwd),
332
+ metadata: await fileActivityMetadata(
333
+ abs,
334
+ 'generated',
335
+ 'not_run',
336
+ 'support',
337
+ cwd,
338
+ ),
166
339
  };
167
340
  } catch (error) {
168
- return { ok: false, error: `[Download] ${ctrl.signal.aborted ? '下载超时或被中断' : (error as Error).message.replaceAll(url, origin)}(${origin})` };
341
+ return {
342
+ ok: false,
343
+ error: `[Download] ${committed ? `文件已写入 ${abs},后处理失败,禁止当作未写入盲目重试。` : ''}${ctrl.signal.aborted ? '下载超时或被中断;' : ''}${(error instanceof Error ? error.message : String(error)).replaceAll(url, origin)}(${origin})`,
344
+ };
169
345
  } finally {
170
346
  clearTimeout(timer);
171
347
  signal?.removeEventListener('abort', onAbort);
@@ -179,11 +355,11 @@ export const downloadTool: Tool<DownloadInput> = {
179
355
  inputSchema,
180
356
  parameters,
181
357
  isReadOnly: false,
182
- // Two downloads may overwrite the same destination; the scheduler does
183
- // not yet acquire per-path locks.
358
+ // Admission is path-locked across sessions; foreground writes still stay serialized.
184
359
  isConcurrencySafe: false,
185
360
  call,
186
- callWithContext: (input, signal, context: ToolCallContext) => call(input, signal, defaultDeps, context.cwd),
361
+ callWithContext: (input, signal, context: ToolCallContext) =>
362
+ call(input, signal, defaultDeps, context.cwd, context),
187
363
  };
188
364
 
189
365
  // 供单测:直接调 call 注入 deps。
@@ -137,10 +137,10 @@ async function call(input, state, cwd) {
137
137
  }
138
138
  // 5e. 引号风格归一化:处理模型输出的直引号 vs 文件中的弯引号差异
139
139
  let searchTarget = applyLineEnding(old_string, originalLineEnding);
140
- let processedNewString = new_string;
140
+ let processedNewString = applyLineEnding(new_string, originalLineEnding);
141
141
  const actualOld = findActualString(original, searchTarget);
142
142
  if (actualOld !== null && actualOld !== searchTarget) {
143
- processedNewString = preserveQuoteStyle(searchTarget, actualOld, new_string);
143
+ processedNewString = preserveQuoteStyle(searchTarget, actualOld, processedNewString);
144
144
  searchTarget = actualOld;
145
145
  }
146
146
  // splitCount = 出现次数
@@ -166,8 +166,8 @@ async function call(input, state, cwd) {
166
166
  const replaced = replaceAll
167
167
  ? splitReplaceAll(original, searchTarget, processedNewString)
168
168
  : original.replace(searchTarget, () => processedNewString); // 只替换第一处(已确认 occurrences === 1)
169
- // 5f. 保持原文件行尾符风格
170
- const normalizedReplaced = applyLineEnding(replaced, originalLineEnding);
169
+ // Only normalize inserted text; untouched mixed line endings must survive.
170
+ const normalizedReplaced = replaced;
171
171
  try {
172
172
  await commitEdit(filePath, editSnapshot, normalizedReplaced);
173
173
  recordRead(filePath, {
@@ -168,10 +168,10 @@ async function call(input: EditInput, state?: FileReadState, cwd?: string): Prom
168
168
 
169
169
  // 5e. 引号风格归一化:处理模型输出的直引号 vs 文件中的弯引号差异
170
170
  let searchTarget = applyLineEnding(old_string, originalLineEnding);
171
- let processedNewString = new_string;
171
+ let processedNewString = applyLineEnding(new_string, originalLineEnding);
172
172
  const actualOld = findActualString(original, searchTarget);
173
173
  if (actualOld !== null && actualOld !== searchTarget) {
174
- processedNewString = preserveQuoteStyle(searchTarget, actualOld, new_string);
174
+ processedNewString = preserveQuoteStyle(searchTarget, actualOld, processedNewString);
175
175
  searchTarget = actualOld;
176
176
  }
177
177
 
@@ -200,8 +200,8 @@ async function call(input: EditInput, state?: FileReadState, cwd?: string): Prom
200
200
  ? splitReplaceAll(original, searchTarget, processedNewString)
201
201
  : original.replace(searchTarget, () => processedNewString); // 只替换第一处(已确认 occurrences === 1)
202
202
 
203
- // 5f. 保持原文件行尾符风格
204
- const normalizedReplaced = applyLineEnding(replaced, originalLineEnding);
203
+ // Only normalize inserted text; untouched mixed line endings must survive.
204
+ const normalizedReplaced = replaced;
205
205
 
206
206
  try {
207
207
  await commitEdit(filePath, editSnapshot, normalizedReplaced);
@@ -167,8 +167,8 @@ async function call(input, state, cwd) {
167
167
  ? splitReplaceAll(currentContent, searchTarget, processedNewString)
168
168
  : currentContent.replace(searchTarget, () => processedNewString);
169
169
  }
170
- // 4g. 全部成功 → 保持原文件行尾符风格,写盘
171
- const finalContent = applyLineEnding(currentContent, lineEnding);
170
+ // Replacement strings were normalized above; do not rewrite untouched lines.
171
+ const finalContent = currentContent;
172
172
  try {
173
173
  await commitEdit(filePath, editSnapshot, finalContent);
174
174
  recordRead(filePath, {
@@ -193,8 +193,8 @@ async function call(input: MultiEditInput, state?: FileReadState, cwd?: string):
193
193
  : currentContent.replace(searchTarget, () => processedNewString);
194
194
  }
195
195
 
196
- // 4g. 全部成功 → 保持原文件行尾符风格,写盘
197
- const finalContent = applyLineEnding(currentContent, lineEnding);
196
+ // Replacement strings were normalized above; do not rewrite untouched lines.
197
+ const finalContent = currentContent;
198
198
 
199
199
  try {
200
200
  await commitEdit(filePath, editSnapshot, finalContent);
@@ -135,6 +135,7 @@ async function call(input, signal, context) {
135
135
  env: sanitizedChildEnv(),
136
136
  windowsHide: true,
137
137
  detached: false,
138
+ stdio: ['ignore', 'pipe', 'pipe'],
138
139
  });
139
140
  let finished = false;
140
141
  const store = new ToolOutputStore({
@@ -210,6 +211,7 @@ async function call(input, signal, context) {
210
211
  export const powerShellTool = {
211
212
  name: 'PowerShell',
212
213
  description: `Executes native PowerShell on Windows. Use for Windows-specific administration and scripts; use run_in_background for long builds, tests, or servers, then TaskOutput/TaskStop.
214
+ Non-interactive: inherited stdin is closed (EOF); there is no PTY or follow-up input channel. Supply input through explicit pipes/redirection or non-interactive flags.
213
215
 
214
216
  # Safety - two levels, from strict to lenient
215
217
 
@@ -158,6 +158,7 @@ async function call(
158
158
  env: sanitizedChildEnv(),
159
159
  windowsHide: true,
160
160
  detached: false,
161
+ stdio: ['ignore', 'pipe', 'pipe'],
161
162
  });
162
163
  let finished = false;
163
164
  const store = new ToolOutputStore({
@@ -239,6 +240,7 @@ async function call(
239
240
  export const powerShellTool: Tool<PowerShellInput> = {
240
241
  name: 'PowerShell',
241
242
  description: `Executes native PowerShell on Windows. Use for Windows-specific administration and scripts; use run_in_background for long builds, tests, or servers, then TaskOutput/TaskStop.
243
+ Non-interactive: inherited stdin is closed (EOF); there is no PTY or follow-up input channel. Supply input through explicit pipes/redirection or non-interactive flags.
242
244
 
243
245
  # Safety - two levels, from strict to lenient
244
246
 
@@ -174,7 +174,7 @@ export async function tryAutoSnapshot(filePath) {
174
174
  // 4. 读全文(已知 <= 32KB)
175
175
  let content;
176
176
  try {
177
- content = await readFile(filePath, 'utf8');
177
+ content = (await readTextFile(filePath)).content;
178
178
  }
179
179
  catch {
180
180
  return { ok: false, reason: 'unreadable' };
@@ -194,17 +194,27 @@ export async function tryAutoSnapshot(filePath) {
194
194
  export async function readTextFile(filePath) {
195
195
  const bytes = await readFile(filePath);
196
196
  let encoding = 'utf8';
197
- let content;
197
+ let offset = 0;
198
198
  if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xfe) {
199
199
  encoding = 'utf16le';
200
- content = bytes.subarray(2).toString('utf16le');
200
+ offset = 2;
201
201
  }
202
202
  else if (bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) {
203
203
  encoding = 'utf8-bom';
204
- content = bytes.subarray(3).toString('utf8');
204
+ offset = 3;
205
205
  }
206
- else {
207
- content = bytes.toString('utf8');
206
+ let content;
207
+ try {
208
+ // Strip only the encoding marker above, not a second, literal U+FEFF.
209
+ content = new TextDecoder(encoding === 'utf16le' ? 'utf-16le' : 'utf-8', {
210
+ fatal: true,
211
+ ignoreBOM: true,
212
+ }).decode(bytes.subarray(offset));
213
+ if (!encodeTextFile(content, encoding).equals(bytes))
214
+ throw new Error('lossy decoding');
215
+ }
216
+ catch {
217
+ throw new Error(`文件无法无损解码,拒绝修改:${filePath}。仅支持 UTF-8(可带 BOM)或带 BOM 的 UTF-16LE;请先确认编码并转换。`);
208
218
  }
209
219
  return { content, encoding, lineEnding: detectLineEndingsForString(content), bytes };
210
220
  }
@@ -220,7 +220,7 @@ export async function tryAutoSnapshot(filePath: string): Promise<AutoSnapshotRes
220
220
  // 4. 读全文(已知 <= 32KB)
221
221
  let content: string;
222
222
  try {
223
- content = await readFile(filePath, 'utf8');
223
+ content = (await readTextFile(filePath)).content;
224
224
  } catch {
225
225
  return { ok: false, reason: 'unreadable' };
226
226
  }
@@ -254,15 +254,24 @@ export interface TextFileSnapshot {
254
254
  export async function readTextFile(filePath: string): Promise<TextFileSnapshot> {
255
255
  const bytes = await readFile(filePath);
256
256
  let encoding: FileBomEncoding = 'utf8';
257
- let content: string;
257
+ let offset = 0;
258
258
  if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xfe) {
259
259
  encoding = 'utf16le';
260
- content = bytes.subarray(2).toString('utf16le');
260
+ offset = 2;
261
261
  } else if (bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) {
262
262
  encoding = 'utf8-bom';
263
- content = bytes.subarray(3).toString('utf8');
264
- } else {
265
- content = bytes.toString('utf8');
263
+ offset = 3;
264
+ }
265
+ let content: string;
266
+ try {
267
+ // Strip only the encoding marker above, not a second, literal U+FEFF.
268
+ content = new TextDecoder(encoding === 'utf16le' ? 'utf-16le' : 'utf-8', {
269
+ fatal: true,
270
+ ignoreBOM: true,
271
+ }).decode(bytes.subarray(offset));
272
+ if (!encodeTextFile(content, encoding).equals(bytes)) throw new Error('lossy decoding');
273
+ } catch {
274
+ throw new Error(`文件无法无损解码,拒绝修改:${filePath}。仅支持 UTF-8(可带 BOM)或带 BOM 的 UTF-16LE;请先确认编码并转换。`);
266
275
  }
267
276
  return { content, encoding, lineEnding: detectLineEndingsForString(content), bytes };
268
277
  }