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
@@ -8,7 +8,7 @@ import { buildPatchSummary } from '../shared/diffSummary.js';
8
8
  import { fileActivityMetadata } from '../shared/fileActivity.js';
9
9
  import { emitFileMutation } from '../shared/fileMutationBus.js';
10
10
  import { hashFileBytes, recordRead } from '../shared/fileState.js';
11
- import { applyLineEnding, atomicWriteFile, encodeTextFile, hasBinaryExtension, readTextFile, } from '../shared/fileUtils.js';
11
+ import { atomicWriteFile, encodeTextFile, hasBinaryExtension, readTextFile, } from '../shared/fileUtils.js';
12
12
  import { DEFAULT_MAX_RESULT_SIZE_CHARS } from '../types.js';
13
13
  const schema = z.object({
14
14
  patch: z.string().min(1).max(10_000_000).describe('Complete Codex-style patch envelope'),
@@ -150,16 +150,17 @@ async function workspacePath(raw, cwd) {
150
150
  return absolute;
151
151
  }
152
152
  export function applyHunks(original, hunks) {
153
- const normalized = original.replaceAll('\r\n', '\n');
154
- const trailingNewline = normalized.endsWith('\n');
155
- const lines = normalized.split('\n');
156
- if (trailingNewline)
157
- lines.pop();
153
+ // Keep terminators on their source lines: context is evidence, not replacement text.
154
+ const lines = Array.from(original.matchAll(/([^\r\n]*)(\r\n|\r|\n|$)/g))
155
+ .filter((match) => match[0].length > 0)
156
+ .map((match) => ({ text: match[1], ending: match[2] }));
157
+ const preferredEnding = lines.find((line) => line.ending)?.ending ?? '\n';
158
+ const trailingNewline = lines.length === 0 || lines.at(-1).ending !== '';
158
159
  let cursor = 0;
159
160
  let lineDelta = 0;
160
161
  for (const hunk of hunks) {
161
162
  if (hunk.header) {
162
- const anchor = lines.findIndex((line, index) => index >= cursor && line.includes(hunk.header));
163
+ const anchor = lines.findIndex((line, index) => index >= cursor && line.text.includes(hunk.header));
163
164
  if (anchor < 0)
164
165
  fail(`找不到 hunk 锚点:${hunk.header}`);
165
166
  cursor = anchor;
@@ -170,7 +171,7 @@ export function applyHunks(original, hunks) {
170
171
  const after = hunk.lines
171
172
  .filter((line) => line.kind !== 'delete')
172
173
  .map((line) => line.text);
173
- const matchesAt = (start) => before.every((line, offset) => lines[start + offset] === line);
174
+ const matchesAt = (start) => before.every((line, offset) => lines[start + offset]?.text === line);
174
175
  let at = -1;
175
176
  if (hunk.endOfFile) {
176
177
  const last = lines.length - before.length;
@@ -183,7 +184,7 @@ export function applyHunks(original, hunks) {
183
184
  else if (!before.length) {
184
185
  at =
185
186
  hunk.oldStart === undefined
186
- ? cursor
187
+ ? lines.length
187
188
  : Math.max(cursor, Math.min(lines.length, hunk.oldStart - (hunk.oldCount === 0 ? 0 : 1) + lineDelta));
188
189
  }
189
190
  else {
@@ -204,11 +205,36 @@ export function applyHunks(original, hunks) {
204
205
  }
205
206
  if (at < 0)
206
207
  fail(`hunk 上下文与当前文件不匹配:${before.join('\n').slice(0, 240)}`);
207
- lines.splice(at, before.length, ...after);
208
+ const touchesEnd = at + before.length === lines.length;
209
+ let sourceIndex = at;
210
+ let lastIsAdded = false;
211
+ const replacement = [];
212
+ for (const line of hunk.lines) {
213
+ if (line.kind === 'context') {
214
+ replacement.push(lines[sourceIndex++]);
215
+ lastIsAdded = false;
216
+ }
217
+ else if (line.kind === 'delete')
218
+ sourceIndex++;
219
+ else {
220
+ replacement.push({ text: line.text, ending: preferredEnding });
221
+ lastIsAdded = true;
222
+ }
223
+ }
224
+ // Retain our existing no-final-newline contract when rewriting or extending EOF.
225
+ if (touchesEnd && !trailingNewline && lastIsAdded) {
226
+ replacement[replacement.length - 1] = { ...replacement.at(-1), ending: '' };
227
+ }
228
+ lines.splice(at, before.length, ...replacement);
229
+ // Appending after an unterminated source line necessarily adds a separator.
230
+ for (let index = Math.max(0, at - 1); index < Math.min(lines.length - 1, at + replacement.length); index++) {
231
+ if (!lines[index].ending)
232
+ lines[index] = { ...lines[index], ending: preferredEnding };
233
+ }
208
234
  cursor = at + after.length;
209
235
  lineDelta += after.length - before.length;
210
236
  }
211
- return `${lines.join('\n')}${trailingNewline ? '\n' : ''}`;
237
+ return lines.map((line) => line.text + line.ending).join('');
212
238
  }
213
239
  async function stagePatch(operations, cwd) {
214
240
  const staged = [];
@@ -248,7 +274,7 @@ async function stagePatch(operations, cwd) {
248
274
  });
249
275
  continue;
250
276
  }
251
- const updated = applyLineEnding(applyHunks(snapshot.content, operation.hunks), snapshot.lineEnding);
277
+ const updated = applyHunks(snapshot.content, operation.hunks);
252
278
  if (operation.moveTo) {
253
279
  const target = await workspacePath(operation.moveTo, cwd);
254
280
  claim(target);
@@ -354,7 +380,7 @@ async function call(input, context) {
354
380
  }
355
381
  export const applyPatchTool = {
356
382
  name: 'ApplyPatch',
357
- description: '提交 Codex 格式补丁,必须用 *** Begin Patch / *** End Patch 包络,不接受裸 git diff。支持 Add/Update/Delete File、Move to;路径相对工作区。先校验,写入失败尝试回滚,不保证跨文件断电原子性。',
383
+ description: '提交 Codex 格式补丁,必须用 *** Begin Patch / *** End Patch 包络,不接受裸 git diff。支持 Add/Update/Delete File、Move to;路径相对工作区。无旧行、无行号的纯新增 hunk 追加到末尾。保留未修改行的换行符,仅支持无损 UTF-8(可带 BOM)或带 BOM 的 UTF-16LE,其他编码拒绝修改。先校验,写入失败尝试回滚,不保证跨文件断电原子性。',
358
384
  inputSchema: schema,
359
385
  parameters: toToolParameters(schema),
360
386
  isReadOnly: false,
@@ -17,7 +17,6 @@ import { emitFileMutation } from '../shared/fileMutationBus.js';
17
17
  import { hashFileBytes, recordRead } from '../shared/fileState.js';
18
18
  import {
19
19
  type FileBomEncoding,
20
- applyLineEnding,
21
20
  atomicWriteFile,
22
21
  encodeTextFile,
23
22
  hasBinaryExtension,
@@ -186,16 +185,18 @@ async function workspacePath(raw: string, cwd: string): Promise<string> {
186
185
  }
187
186
 
188
187
  export function applyHunks(original: string, hunks: PatchHunk[]): string {
189
- const normalized = original.replaceAll('\r\n', '\n');
190
- const trailingNewline = normalized.endsWith('\n');
191
- const lines = normalized.split('\n');
192
- if (trailingNewline) lines.pop();
188
+ // Keep terminators on their source lines: context is evidence, not replacement text.
189
+ const lines = Array.from(original.matchAll(/([^\r\n]*)(\r\n|\r|\n|$)/g))
190
+ .filter((match) => match[0].length > 0)
191
+ .map((match) => ({ text: match[1]!, ending: match[2]! }));
192
+ const preferredEnding = lines.find((line) => line.ending)?.ending ?? '\n';
193
+ const trailingNewline = lines.length === 0 || lines.at(-1)!.ending !== '';
193
194
  let cursor = 0;
194
195
  let lineDelta = 0;
195
196
  for (const hunk of hunks) {
196
197
  if (hunk.header) {
197
198
  const anchor = lines.findIndex(
198
- (line, index) => index >= cursor && line.includes(hunk.header),
199
+ (line, index) => index >= cursor && line.text.includes(hunk.header),
199
200
  );
200
201
  if (anchor < 0) fail(`找不到 hunk 锚点:${hunk.header}`);
201
202
  cursor = anchor;
@@ -207,7 +208,7 @@ export function applyHunks(original: string, hunks: PatchHunk[]): string {
207
208
  .filter((line) => line.kind !== 'delete')
208
209
  .map((line) => line.text);
209
210
  const matchesAt = (start: number) =>
210
- before.every((line, offset) => lines[start + offset] === line);
211
+ before.every((line, offset) => lines[start + offset]?.text === line);
211
212
  let at = -1;
212
213
  if (hunk.endOfFile) {
213
214
  const last = lines.length - before.length;
@@ -217,7 +218,7 @@ export function applyHunks(original: string, hunks: PatchHunk[]): string {
217
218
  } else if (!before.length) {
218
219
  at =
219
220
  hunk.oldStart === undefined
220
- ? cursor
221
+ ? lines.length
221
222
  : Math.max(cursor, Math.min(lines.length, hunk.oldStart - (hunk.oldCount === 0 ? 0 : 1) + lineDelta));
222
223
  } else {
223
224
  for (
@@ -239,11 +240,33 @@ export function applyHunks(original: string, hunks: PatchHunk[]): string {
239
240
  }
240
241
  if (at < 0)
241
242
  fail(`hunk 上下文与当前文件不匹配:${before.join('\n').slice(0, 240)}`);
242
- lines.splice(at, before.length, ...after);
243
+ const touchesEnd = at + before.length === lines.length;
244
+ let sourceIndex = at;
245
+ let lastIsAdded = false;
246
+ const replacement = [] as typeof lines;
247
+ for (const line of hunk.lines) {
248
+ if (line.kind === 'context') {
249
+ replacement.push(lines[sourceIndex++]!);
250
+ lastIsAdded = false;
251
+ } else if (line.kind === 'delete') sourceIndex++;
252
+ else {
253
+ replacement.push({ text: line.text, ending: preferredEnding });
254
+ lastIsAdded = true;
255
+ }
256
+ }
257
+ // Retain our existing no-final-newline contract when rewriting or extending EOF.
258
+ if (touchesEnd && !trailingNewline && lastIsAdded) {
259
+ replacement[replacement.length - 1] = { ...replacement.at(-1)!, ending: '' };
260
+ }
261
+ lines.splice(at, before.length, ...replacement);
262
+ // Appending after an unterminated source line necessarily adds a separator.
263
+ for (let index = Math.max(0, at - 1); index < Math.min(lines.length - 1, at + replacement.length); index++) {
264
+ if (!lines[index]!.ending) lines[index] = { ...lines[index]!, ending: preferredEnding };
265
+ }
243
266
  cursor = at + after.length;
244
267
  lineDelta += after.length - before.length;
245
268
  }
246
- return `${lines.join('\n')}${trailingNewline ? '\n' : ''}`;
269
+ return lines.map((line) => line.text + line.ending).join('');
247
270
  }
248
271
 
249
272
  interface StagedFile {
@@ -297,10 +320,7 @@ async function stagePatch(
297
320
  });
298
321
  continue;
299
322
  }
300
- const updated = applyLineEnding(
301
- applyHunks(snapshot.content, operation.hunks),
302
- snapshot.lineEnding,
303
- );
323
+ const updated = applyHunks(snapshot.content, operation.hunks);
304
324
  if (operation.moveTo) {
305
325
  const target = await workspacePath(operation.moveTo, cwd);
306
326
  claim(target);
@@ -418,7 +438,7 @@ async function call(
418
438
 
419
439
  export const applyPatchTool: Tool<ApplyPatchInput> = {
420
440
  name: 'ApplyPatch',
421
- description: '提交 Codex 格式补丁,必须用 *** Begin Patch / *** End Patch 包络,不接受裸 git diff。支持 Add/Update/Delete File、Move to;路径相对工作区。先校验,写入失败尝试回滚,不保证跨文件断电原子性。',
441
+ description: '提交 Codex 格式补丁,必须用 *** Begin Patch / *** End Patch 包络,不接受裸 git diff。支持 Add/Update/Delete File、Move to;路径相对工作区。无旧行、无行号的纯新增 hunk 追加到末尾。保留未修改行的换行符,仅支持无损 UTF-8(可带 BOM)或带 BOM 的 UTF-16LE,其他编码拒绝修改。先校验,写入失败尝试回滚,不保证跨文件断电原子性。',
422
442
  inputSchema: schema,
423
443
  parameters: toToolParameters(schema),
424
444
  isReadOnly: false,
@@ -315,6 +315,7 @@ const shellNotice = bashShellNotice();
315
315
  const description = `Executes a given bash command and returns its output.
316
316
 
317
317
  Each call starts in the current workspace. A cd or shell variable change affects only that call; shell state and profile loading are not preserved.
318
+ Non-interactive: inherited stdin is closed (EOF), with no PTY or follow-up input channel. Use explicit pipes/redirection or a command's non-interactive flags when it needs input.
318
319
 
319
320
  IMPORTANT: Avoid using this tool to run \`find\`, \`grep\`, \`cat\`, \`head\`, \`tail\`, \`sed\`, \`awk\`, or \`echo\` commands, unless explicitly instructed or after you have verified that a dedicated tool cannot accomplish your task. Instead, use the appropriate dedicated tool as this will provide a much better experience for the user:
320
321
 
@@ -524,6 +525,8 @@ async function call(input, signal, context) {
524
525
  cwd: context?.cwd ?? getWorkingDir(),
525
526
  env: sanitizedChildEnv(),
526
527
  windowsHide: true,
528
+ // This tool has no interactive input channel: readers must observe EOF.
529
+ stdio: ['ignore', 'pipe', 'pipe'],
527
530
  // POSIX:detached 自成进程组,中断时 killTree 的 kill(-pid) 才能掀整组;win32 不 detached(taskkill /T 掀树)。
528
531
  detached: process.platform !== 'win32',
529
532
  };
@@ -341,6 +341,7 @@ const shellNotice = bashShellNotice();
341
341
  const description = `Executes a given bash command and returns its output.
342
342
 
343
343
  Each call starts in the current workspace. A cd or shell variable change affects only that call; shell state and profile loading are not preserved.
344
+ Non-interactive: inherited stdin is closed (EOF), with no PTY or follow-up input channel. Use explicit pipes/redirection or a command's non-interactive flags when it needs input.
344
345
 
345
346
  IMPORTANT: Avoid using this tool to run \`find\`, \`grep\`, \`cat\`, \`head\`, \`tail\`, \`sed\`, \`awk\`, or \`echo\` commands, unless explicitly instructed or after you have verified that a dedicated tool cannot accomplish your task. Instead, use the appropriate dedicated tool as this will provide a much better experience for the user:
346
347
 
@@ -564,6 +565,8 @@ async function call(input: BashInput, signal?: AbortSignal, context?: ToolCallCo
564
565
  cwd: context?.cwd ?? getWorkingDir(),
565
566
  env: sanitizedChildEnv(),
566
567
  windowsHide: true,
568
+ // This tool has no interactive input channel: readers must observe EOF.
569
+ stdio: ['ignore', 'pipe', 'pipe'] as ['ignore', 'pipe', 'pipe'],
567
570
  // POSIX:detached 自成进程组,中断时 killTree 的 kill(-pid) 才能掀整组;win32 不 detached(taskkill /T 掀树)。
568
571
  detached: process.platform !== 'win32',
569
572
  };
@@ -19,19 +19,34 @@
19
19
  * ============================================================
20
20
  */
21
21
  import { z } from 'zod';
22
+ import { randomUUID } from 'node:crypto';
23
+ import { existsSync } from 'node:fs';
24
+ import { mkdir, realpath, link, rm, writeFile } from 'node:fs/promises';
25
+ import { basename, dirname, join, resolve } from 'node:path';
22
26
  import { getWorkingDir } from '../../bootstrap/workingDir.js';
23
27
  import { toToolParameters } from '../../utils/zodToJson.js';
24
28
  import { fileActivityMetadata } from '../shared/fileActivity.js';
25
29
  import { atomicWriteFile, resolveToolPath } from '../shared/fileUtils.js';
26
30
  import { emitFileMutation } from '../shared/fileMutationBus.js';
27
31
  import { readHttpBody } from '../shared/httpBody.js';
32
+ import { mustSettleBackgroundTasks } from '../../runtime/invocationPolicy.js';
33
+ import { startBackgroundOperation } from '../tasks/backgroundTaskService.js';
28
34
  const DEFAULT_TIMEOUT_MS = 60_000;
29
35
  const DEFAULT_MAX_BYTES = 25 * 1024 * 1024;
30
36
  // ---------------- 1. Zod 输入 schema ----------------
31
37
  const inputSchema = z.object({
32
- url: z.string().url().regex(/^https?:\/\//i).describe('http(s) resource URL to download'),
38
+ run_in_background: z
39
+ .boolean()
40
+ .optional()
41
+ .describe('Run as a session-owned background task; only new destination files are allowed. Use TaskOutput/TaskStop. Hosts without continuation support may wait instead.'),
42
+ url: z
43
+ .string()
44
+ .url()
45
+ .regex(/^https?:\/\//i)
46
+ .describe('http(s) resource URL to download'),
33
47
  path: z
34
- .string().min(1)
48
+ .string()
49
+ .min(1)
35
50
  .describe('Destination file path (relative paths anchor to the working dir)'),
36
51
  headers: z
37
52
  .record(z.string())
@@ -51,12 +66,120 @@ const inputSchema = z.object({
51
66
  .describe('Max size in bytes; over this the download is rejected (default: 25MB)'),
52
67
  });
53
68
  const parameters = toToolParameters(inputSchema);
54
- const description = '下载 HTTP(S) 原始字节到指定路径;相对路径基于工作目录,会覆盖已有文件;失败或中断不保留部分下载。';
69
+ const description = '下载 HTTP(S) 原始字节到指定路径;相对路径基于工作目录。前台会覆盖已有文件;run_in_background 仅允许新目标文件,返回 task_id,用 TaskOutput/TaskStop 查询或取消。只有声明自动接续的宿主才会完成后唤醒。取消不等于撤销已完成的写入。';
70
+ const activeDestinations = new Set();
71
+ /** Resolve aliases even when the destination's parent does not exist yet. */
72
+ async function resolveDestination(path) {
73
+ const parent = dirname(path);
74
+ const physical = await realpath(path).catch(async (error) => {
75
+ if (error.code !== 'ENOENT')
76
+ throw error;
77
+ if (parent === path)
78
+ throw error;
79
+ return resolve(await resolveDestination(parent), basename(path));
80
+ });
81
+ return physical;
82
+ }
83
+ /** Publish a fully written new file without replacing a racing writer's file. */
84
+ async function publishNewFile(path, bytes, signal) {
85
+ await mkdir(dirname(path), { recursive: true });
86
+ const temp = join(dirname(path), `.${randomUUID()}.download.tmp`);
87
+ let published = false;
88
+ try {
89
+ await writeFile(temp, bytes, { flag: 'wx' });
90
+ signal.throwIfAborted();
91
+ try {
92
+ await link(temp, path); // Atomic create-if-absent; EEXIST never overwrites.
93
+ }
94
+ catch (error) {
95
+ if (error.code === 'EEXIST')
96
+ throw new Error(`目标已被其他操作创建,未覆盖:${path}`);
97
+ throw new Error(`无法安全发布新文件(需要支持硬链接的文件系统),未覆盖目标:${path};${error.message}`);
98
+ }
99
+ published = true;
100
+ }
101
+ finally {
102
+ try {
103
+ await rm(temp, { force: true, maxRetries: 3, retryDelay: 50 });
104
+ }
105
+ catch (error) {
106
+ throw new Error(`${published ? '目标文件已发布,不能当作未写入重试' : '临时文件未清理'}:${temp};${error.message}`);
107
+ }
108
+ }
109
+ }
55
110
  const defaultDeps = {
56
111
  fetchImpl: globalThis.fetch,
57
112
  };
58
113
  // ---------------- 3. call() ----------------
59
- async function call(input, signal, deps = defaultDeps, cwd = getWorkingDir()) {
114
+ async function call(input, signal, deps = defaultDeps, cwd = getWorkingDir(), context) {
115
+ const destination = resolveToolPath(input.path, cwd);
116
+ if (!destination.ok)
117
+ return destination;
118
+ if (signal?.aborted)
119
+ return { ok: false, error: '[Download] 已取消,未启动' };
120
+ let physical;
121
+ try {
122
+ physical = await resolveDestination(destination.resolvedPath);
123
+ }
124
+ catch (error) {
125
+ return { ok: false, error: `[Download] ${error.message}` };
126
+ }
127
+ const key = process.platform === 'win32' ? physical.toLowerCase() : physical;
128
+ if (activeDestinations.has(key))
129
+ return {
130
+ ok: false,
131
+ error: '[Download] 该目标已有下载任务,拒绝并发覆盖;请先等待或取消原任务。',
132
+ };
133
+ if (input.run_in_background && existsSync(physical))
134
+ return {
135
+ ok: false,
136
+ error: '[Download] 后台下载只允许新目标,文件已存在;请另选路径。',
137
+ };
138
+ activeDestinations.add(key);
139
+ const execute = async (jobSignal) => {
140
+ try {
141
+ return await performDownload({ ...input, path: physical }, jobSignal, deps, cwd);
142
+ }
143
+ finally {
144
+ activeDestinations.delete(key);
145
+ }
146
+ };
147
+ if (input.run_in_background &&
148
+ !mustSettleBackgroundTasks(context?.executionServices?.invocationPolicy)) {
149
+ if (!context?.sessionState) {
150
+ activeDestinations.delete(key);
151
+ return {
152
+ ok: false,
153
+ error: '[Download] 后台下载需要会话宿主;请使用前台模式。',
154
+ };
155
+ }
156
+ try {
157
+ signal?.throwIfAborted();
158
+ const task = await startBackgroundOperation({
159
+ command: `Download → ${destination.resolvedPath}`,
160
+ cwd,
161
+ signal,
162
+ workspaceId: context.workspaceId,
163
+ sessionId: context.sessionId,
164
+ deliveryId: context.deliveryId,
165
+ request: context.backgroundRequest ?? context.currentUserInput,
166
+ }, execute, context.sessionState.backgroundTasks);
167
+ return {
168
+ ok: true,
169
+ content: `后台下载已启动。task_id=${task.id}\n目标:${destination.resolvedPath}\n使用 TaskOutput 查询结果,TaskStop 停止任务;尚未完成下载。`,
170
+ };
171
+ }
172
+ catch (error) {
173
+ activeDestinations.delete(key);
174
+ return {
175
+ ok: false,
176
+ error: `[Download] 后台启动失败:${error.message}`,
177
+ };
178
+ }
179
+ }
180
+ return execute(signal);
181
+ }
182
+ async function performDownload(input, signal, deps, cwd) {
60
183
  const { url, path } = input;
61
184
  const timeout = input.timeout ?? DEFAULT_TIMEOUT_MS;
62
185
  const maxBytes = input.max_bytes ?? DEFAULT_MAX_BYTES;
@@ -78,6 +201,7 @@ async function call(input, signal, deps = defaultDeps, cwd = getWorkingDir()) {
78
201
  const abs = destination.resolvedPath;
79
202
  // 合并外部 signal 与超时
80
203
  const ctrl = new AbortController();
204
+ let committed = false;
81
205
  const timer = setTimeout(() => ctrl.abort(), timeout);
82
206
  const onAbort = () => ctrl.abort();
83
207
  if (signal) {
@@ -90,7 +214,10 @@ async function call(input, signal, deps = defaultDeps, cwd = getWorkingDir()) {
90
214
  ctrl.signal.throwIfAborted();
91
215
  let res;
92
216
  try {
93
- res = await deps.fetchImpl(url, { headers: input.headers, signal: ctrl.signal });
217
+ res = await deps.fetchImpl(url, {
218
+ headers: input.headers,
219
+ signal: ctrl.signal,
220
+ });
94
221
  }
95
222
  catch (e) {
96
223
  const msg = ctrl.signal.aborted
@@ -98,7 +225,10 @@ async function call(input, signal, deps = defaultDeps, cwd = getWorkingDir()) {
98
225
  : e instanceof Error
99
226
  ? e.message
100
227
  : String(e);
101
- return { ok: false, error: `[Download] 请求失败:${msg.replaceAll(url, origin)}(${origin})` };
228
+ return {
229
+ ok: false,
230
+ error: `[Download] 请求失败:${msg.replaceAll(url, origin)}(${origin})`,
231
+ };
102
232
  }
103
233
  if (!res.ok) {
104
234
  void res.body?.cancel().catch(() => undefined);
@@ -124,7 +254,11 @@ async function call(input, signal, deps = defaultDeps, cwd = getWorkingDir()) {
124
254
  };
125
255
  }
126
256
  ctrl.signal.throwIfAborted();
127
- await atomicWriteFile(abs, buf);
257
+ if (input.run_in_background)
258
+ await publishNewFile(abs, buf, ctrl.signal);
259
+ else
260
+ await atomicWriteFile(abs, buf);
261
+ committed = true;
128
262
  emitFileMutation(abs);
129
263
  const ctype = res.headers.get('content-type') ?? 'unknown';
130
264
  return {
@@ -134,7 +268,10 @@ async function call(input, signal, deps = defaultDeps, cwd = getWorkingDir()) {
134
268
  };
135
269
  }
136
270
  catch (error) {
137
- return { ok: false, error: `[Download] ${ctrl.signal.aborted ? '下载超时或被中断' : error.message.replaceAll(url, origin)}(${origin})` };
271
+ return {
272
+ ok: false,
273
+ error: `[Download] ${committed ? `文件已写入 ${abs},后处理失败,禁止当作未写入盲目重试。` : ''}${ctrl.signal.aborted ? '下载超时或被中断;' : ''}${(error instanceof Error ? error.message : String(error)).replaceAll(url, origin)}(${origin})`,
274
+ };
138
275
  }
139
276
  finally {
140
277
  clearTimeout(timer);
@@ -148,11 +285,10 @@ export const downloadTool = {
148
285
  inputSchema,
149
286
  parameters,
150
287
  isReadOnly: false,
151
- // Two downloads may overwrite the same destination; the scheduler does
152
- // not yet acquire per-path locks.
288
+ // Admission is path-locked across sessions; foreground writes still stay serialized.
153
289
  isConcurrencySafe: false,
154
290
  call,
155
- callWithContext: (input, signal, context) => call(input, signal, defaultDeps, context.cwd),
291
+ callWithContext: (input, signal, context) => call(input, signal, defaultDeps, context.cwd, context),
156
292
  };
157
293
  // 供单测:直接调 call 注入 deps。
158
294
  export const _downloadCall = call;