minimal-agent 0.18.20 → 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 (188) hide show
  1. package/README.md +16 -3
  2. package/package.json +1 -1
  3. package/plugins/cron-runner/README.md +23 -0
  4. package/plugins/cron-runner/commands/cron.md +7 -1
  5. package/plugins/cron-runner/plugin.js +9 -2
  6. package/plugins/cron-runner/plugin.ts +10 -2
  7. package/plugins/cron-runner/src/commands.js +112 -25
  8. package/plugins/cron-runner/src/commands.ts +154 -33
  9. package/plugins/cron-runner/src/contract.js +70 -0
  10. package/plugins/cron-runner/src/contract.ts +70 -0
  11. package/plugins/cron-runner/src/requests.js +22 -13
  12. package/plugins/cron-runner/src/requests.ts +34 -14
  13. package/plugins/cron-runner/src/runs.js +63 -10
  14. package/plugins/cron-runner/src/runs.ts +107 -15
  15. package/plugins/cron-runner/src/scheduler.js +188 -76
  16. package/plugins/cron-runner/src/scheduler.ts +277 -94
  17. package/plugins/cron-runner/src/schema.js +52 -17
  18. package/plugins/cron-runner/src/schema.ts +73 -22
  19. package/plugins/cron-runner/src/service.js +29 -8
  20. package/plugins/cron-runner/src/service.ts +71 -18
  21. package/plugins/cron-runner/src/store.js +92 -30
  22. package/plugins/cron-runner/src/store.ts +156 -53
  23. package/plugins/cron-runner/src/transaction.js +24 -0
  24. package/plugins/cron-runner/src/transaction.ts +36 -0
  25. package/plugins/cron-runner/src/types.ts +30 -4
  26. package/plugins/cron-runner/test/lifecycle.test.ts +419 -0
  27. package/plugins/cron-runner/test/plugin-integration.test.ts +3 -2
  28. package/plugins/cron-runner/test/reliability.test.ts +2 -2
  29. package/plugins/cron-runner/test/store-and-scheduler.test.ts +9 -7
  30. package/plugins/workflow-runner/plugin.js +1 -0
  31. package/plugins/workflow-runner/plugin.ts +1 -0
  32. package/plugins/workflow-runner/src/index.js +1 -0
  33. package/plugins/workflow-runner/src/index.ts +2 -0
  34. package/plugins/workflow-runner/src/runner.js +6 -1
  35. package/plugins/workflow-runner/src/runner.ts +5 -1
  36. package/plugins/workflow-runner/src/types.ts +1 -0
  37. package/plugins/workflow-runner/test/api.test.ts +1 -0
  38. package/plugins/workflow-runner/test/apiCapabilities.test.ts +4 -0
  39. package/plugins/workflow-runner/test/apiConcurrencyGate.test.ts +1 -0
  40. package/plugins/workflow-runner/test/childWorkflow.test.ts +19 -0
  41. package/plugins/workflow-runner/test/embeddedExecution.test.ts +23 -3
  42. package/src/advisor/README.md +17 -6
  43. package/src/advisor/advisorNudge.js +23 -3
  44. package/src/advisor/advisorNudge.ts +20 -3
  45. package/src/advisor/deliveryReview.js +9 -2
  46. package/src/advisor/deliveryReview.ts +10 -2
  47. package/src/cli/args.js +1 -0
  48. package/src/cli/args.ts +1 -0
  49. package/src/cli/headlessTurn.js +143 -0
  50. package/src/cli/headlessTurn.ts +187 -0
  51. package/src/cli/lifecycle.js +52 -0
  52. package/src/cli/lifecycle.ts +59 -0
  53. package/src/cli/print.js +91 -240
  54. package/src/cli/print.ts +99 -301
  55. package/src/cli/quickModelSetup.js +3 -0
  56. package/src/cli/quickModelSetup.tsx +3 -0
  57. package/src/cli/streamJson.js +244 -334
  58. package/src/cli/streamJson.ts +248 -416
  59. package/src/cli/wizards/contextAdvisorWizard.js +0 -7
  60. package/src/cli/wizards/contextAdvisorWizard.tsx +0 -11
  61. package/src/cli/wizards/providerPresets.js +25 -14
  62. package/src/cli/wizards/providerPresets.ts +25 -14
  63. package/src/cli/wizards/providerWizard.js +29 -11
  64. package/src/cli/wizards/providerWizard.tsx +29 -11
  65. package/src/config/configDefaults.js +2 -2
  66. package/src/config/configDefaults.ts +2 -2
  67. package/src/config/configDiagnostics.js +7 -3
  68. package/src/config/configDiagnostics.ts +6 -3
  69. package/src/config/configFile.ts +1 -1
  70. package/src/context/compact.js +40 -10
  71. package/src/context/compact.ts +51 -12
  72. package/src/context/compactResources.js +39 -0
  73. package/src/context/compactResources.ts +35 -0
  74. package/src/context/manualCompact.js +20 -0
  75. package/src/context/manualCompact.ts +28 -0
  76. package/src/llm/client.js +4 -0
  77. package/src/llm/client.ts +4 -0
  78. package/src/llm/messageProvenance.js +1 -1
  79. package/src/llm/messageProvenance.ts +1 -1
  80. package/src/loop/README.md +4 -2
  81. package/src/loop/deliveryIntent.js +3 -2
  82. package/src/loop/deliveryIntent.ts +4 -2
  83. package/src/loop/messages.js +1 -0
  84. package/src/loop/messages.ts +1 -0
  85. package/src/loop/options.ts +2 -0
  86. package/src/loop.js +10 -2
  87. package/src/loop.ts +9 -2
  88. package/src/main.js +40 -45
  89. package/src/main.tsx +33 -52
  90. package/src/plugin-sdk.js +1 -1
  91. package/src/plugin-sdk.ts +1 -1
  92. package/src/plugins/artifactDelivery.js +76 -0
  93. package/src/plugins/artifactDelivery.ts +76 -0
  94. package/src/plugins/pluginApi.ts +4 -0
  95. package/src/plugins/pluginRunner.js +2 -0
  96. package/src/plugins/pluginRunner.ts +3 -0
  97. package/src/prompts/delegation.js +2 -2
  98. package/src/prompts/delegation.ts +2 -2
  99. package/src/prompts/policyRegistry.js +7 -5
  100. package/src/prompts/policyRegistry.ts +7 -5
  101. package/src/prompts/promptAssembly.js +2 -2
  102. package/src/prompts/promptAssembly.ts +2 -2
  103. package/src/runtime/requestIntent.js +86 -0
  104. package/src/runtime/requestIntent.ts +66 -0
  105. package/src/runtime/systemEvents.js +10 -1
  106. package/src/runtime/systemEvents.ts +9 -1
  107. package/src/session/commandTranscript.js +76 -0
  108. package/src/session/commandTranscript.ts +77 -0
  109. package/src/session/executionOutcome.js +25 -0
  110. package/src/session/executionOutcome.ts +34 -0
  111. package/src/session/runAgentTurn.js +8 -1
  112. package/src/session/runAgentTurn.ts +10 -1
  113. package/src/session/runTurn.js +40 -15
  114. package/src/session/runTurn.ts +38 -12
  115. package/src/session/sessionState.js +7 -2
  116. package/src/session/sessionState.ts +7 -2
  117. package/src/team/onlineToolContract.js +1 -0
  118. package/src/team/onlineToolContract.ts +1 -0
  119. package/src/tools/advisor/advisor.js +73 -30
  120. package/src/tools/advisor/advisor.ts +73 -33
  121. package/src/tools/advisor/advisorCoordination.js +44 -0
  122. package/src/tools/advisor/advisorCoordination.ts +45 -0
  123. package/src/tools/advisor/advisorDescription.js +1 -1
  124. package/src/tools/advisor/advisorDescription.ts +1 -1
  125. package/src/tools/agent/README.md +2 -0
  126. package/src/tools/agent/agent.js +7 -3
  127. package/src/tools/agent/agent.ts +7 -3
  128. package/src/tools/agent/agentHandoff.js +2 -1
  129. package/src/tools/agent/agentHandoff.ts +2 -1
  130. package/src/tools/agent/agentTaskService.js +26 -5
  131. package/src/tools/agent/agentTaskService.ts +25 -5
  132. package/src/tools/agent/agentTypes.js +2 -2
  133. package/src/tools/agent/agentTypes.ts +2 -2
  134. package/src/tools/agent/baselineAttach.js +14 -7
  135. package/src/tools/agent/baselineAttach.ts +14 -7
  136. package/src/tools/applypatch/applyPatch.js +39 -13
  137. package/src/tools/applypatch/applyPatch.ts +35 -15
  138. package/src/tools/bash/bash.js +3 -0
  139. package/src/tools/bash/bash.ts +3 -0
  140. package/src/tools/capabilities.js +1 -0
  141. package/src/tools/capabilities.ts +1 -0
  142. package/src/tools/download/download.js +147 -11
  143. package/src/tools/download/download.ts +193 -17
  144. package/src/tools/edit/edit.js +4 -4
  145. package/src/tools/edit/edit.ts +4 -4
  146. package/src/tools/edit/multi-edit.js +2 -2
  147. package/src/tools/edit/multi-edit.ts +2 -2
  148. package/src/tools/index.js +2 -0
  149. package/src/tools/index.ts +2 -0
  150. package/src/tools/powershell/powershell.js +2 -0
  151. package/src/tools/powershell/powershell.ts +2 -0
  152. package/src/tools/schedule/schedule.js +184 -0
  153. package/src/tools/schedule/schedule.ts +214 -0
  154. package/src/tools/shared/fileUtils.js +16 -6
  155. package/src/tools/shared/fileUtils.ts +15 -6
  156. package/src/tools/tasks/backgroundTaskService.js +108 -12
  157. package/src/tools/tasks/backgroundTaskService.ts +106 -14
  158. package/src/tools/tasks/taskOutput.js +15 -5
  159. package/src/tools/tasks/taskOutput.ts +13 -5
  160. package/src/tools/tasks/taskStop.js +2 -2
  161. package/src/tools/tasks/taskStop.ts +2 -2
  162. package/src/tools/toolPromptGuides.js +4 -3
  163. package/src/tools/toolPromptGuides.ts +4 -3
  164. package/src/tools/webfetch/webfetch.js +1 -1
  165. package/src/tools/webfetch/webfetch.ts +1 -1
  166. package/src/types.ts +6 -0
  167. package/src/ui/App.js +3 -1
  168. package/src/ui/App.tsx +2 -0
  169. package/src/ui/InputBox.js +2 -2
  170. package/src/ui/InputBox.tsx +2 -2
  171. package/src/ui/LiveArea.js +6 -1
  172. package/src/ui/LiveArea.tsx +6 -1
  173. package/src/ui/MessageList.js +2 -0
  174. package/src/ui/MessageList.tsx +2 -0
  175. package/src/ui/README.md +8 -2
  176. package/src/ui/activityPresentation.js +23 -3
  177. package/src/ui/activityPresentation.ts +22 -3
  178. package/src/ui/backgroundWake.js +20 -4
  179. package/src/ui/backgroundWake.ts +19 -4
  180. package/src/ui/commandTranscript.js +2 -69
  181. package/src/ui/commandTranscript.ts +2 -71
  182. package/src/ui/hooks/useBackgroundAgents.js +33 -0
  183. package/src/ui/hooks/useBackgroundAgents.ts +36 -0
  184. package/src/ui/hooks/useChat.js +46 -25
  185. package/src/ui/hooks/useChat.ts +36 -23
  186. package/src/web/protocol.ts +5 -2
  187. package/src/cli/wizards/advisorWizard.js +0 -152
  188. 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);
@@ -55,6 +55,7 @@ import { webfetchTool } from './webfetch/webfetch.js';
55
55
  import { webSearchTool } from './websearch/websearch.js';
56
56
  import { enterWorktreeTool, exitWorktreeTool, } from './worktree/sessionWorktree.js';
57
57
  import { writeTool } from './write/write.js';
58
+ import { scheduleTool } from './schedule/schedule.js';
58
59
  /** 所有内置工具(顺序 = 给 LLM 呈现的顺序,不影响代码执行,但会影响模型的优先级直觉) */
59
60
  export const ALL_TOOLS = attachBuiltinPromptGuides([
60
61
  readTool,
@@ -115,6 +116,7 @@ export const ALL_TOOLS = attachBuiltinPromptGuides([
115
116
  memoryMaintenanceTool,
116
117
  searchSkillsTool,
117
118
  optimizeConversationTool,
119
+ scheduleTool,
118
120
  ]);
119
121
  assertCapabilityRegistry(ALL_TOOLS.map((tool) => tool.name));
120
122
  /** 按名字查表 */
@@ -82,6 +82,7 @@ import {
82
82
  exitWorktreeTool,
83
83
  } from './worktree/sessionWorktree.js';
84
84
  import { writeTool } from './write/write.js';
85
+ import { scheduleTool } from './schedule/schedule.js';
85
86
 
86
87
  /** 所有内置工具(顺序 = 给 LLM 呈现的顺序,不影响代码执行,但会影响模型的优先级直觉) */
87
88
  export const ALL_TOOLS: Tool[] = attachBuiltinPromptGuides([
@@ -143,6 +144,7 @@ export const ALL_TOOLS: Tool[] = attachBuiltinPromptGuides([
143
144
  memoryMaintenanceTool,
144
145
  searchSkillsTool,
145
146
  optimizeConversationTool,
147
+ scheduleTool,
146
148
  ]);
147
149
 
148
150
  assertCapabilityRegistry(ALL_TOOLS.map((tool) => tool.name));
@@ -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
 
@@ -0,0 +1,184 @@
1
+ import { resolve } from 'node:path';
2
+ import { z } from 'zod';
3
+ import { toToolParameters } from '../../utils/zodToJson.js';
4
+ import { actionSchema, scheduleSchema, } from '../../../plugins/cron-runner/src/contract.js';
5
+ const text = z.string().trim().min(1);
6
+ const changes = z
7
+ .object({
8
+ name: text.optional(),
9
+ schedule: scheduleSchema.optional(),
10
+ execution: actionSchema.optional(),
11
+ maxRuns: z.number().int().positive().optional(),
12
+ })
13
+ .strict();
14
+ const requestSchema = z.discriminatedUnion('action', [
15
+ z.object({ action: z.literal('list') }).strict(),
16
+ z
17
+ .object({
18
+ action: z.literal('create'),
19
+ requestId: text,
20
+ name: text,
21
+ schedule: scheduleSchema,
22
+ execution: actionSchema,
23
+ sessionMode: z.enum(['persistent', 'fresh']).optional(),
24
+ catchUp: z.enum(['skip', 'latest']).optional(),
25
+ maxRuns: z.number().int().positive().optional(),
26
+ })
27
+ .strict(),
28
+ z
29
+ .object({
30
+ action: z.literal('update'),
31
+ id: text,
32
+ expectedRevision: z.number().int().nonnegative(),
33
+ changes,
34
+ })
35
+ .strict(),
36
+ z
37
+ .object({
38
+ action: z.enum(['show', 'delete', 'pause', 'resume', 'stop']),
39
+ id: text,
40
+ })
41
+ .strict(),
42
+ z.object({ action: z.literal('run'), id: text, requestId: text }).strict(),
43
+ ]);
44
+ // Keep a provider-portable object root. Validation and generated per-action
45
+ // required-field guidance still come from the strict discriminated variants.
46
+ const actionHelp = requestSchema.options
47
+ .map((option) => {
48
+ const action = option.shape.action;
49
+ const names = action instanceof z.ZodLiteral ? [action.value] : action.options;
50
+ const fields = Object.entries(option.shape).filter(([key]) => key !== 'action');
51
+ return `${names.join('/')}:${fields.map(([key, value]) => `${key}${value.isOptional() ? '(可选)' : '(必填)'}`).join(', ') || '无额外字段'}`;
52
+ })
53
+ .join('\n');
54
+ const schema = requestSchema.options[1]
55
+ .partial()
56
+ .extend({
57
+ action: z
58
+ .enum([
59
+ 'list',
60
+ 'create',
61
+ 'update',
62
+ 'show',
63
+ 'delete',
64
+ 'pause',
65
+ 'resume',
66
+ 'stop',
67
+ 'run',
68
+ ])
69
+ .describe(actionHelp),
70
+ id: text.optional(),
71
+ expectedRevision: z.number().int().nonnegative().optional(),
72
+ changes: changes.optional(),
73
+ })
74
+ .strict()
75
+ .superRefine((input, ctx) => {
76
+ const result = requestSchema.safeParse(input);
77
+ if (!result.success)
78
+ for (const issue of result.error.issues)
79
+ ctx.addIssue(issue);
80
+ });
81
+ export const scheduleTool = {
82
+ name: 'Schedule',
83
+ description: '管理当前工作区的持久化定时任务。仅在用户明确要求创建/修改/删除/执行时操作,讨论不是授权。先 list/show 找真实 ID;重试 create/run 复用 requestId。创建以持久化回执为准,报告 ID、时区、下次时间及会话。pause 仅暂停未来触发;stop 停止当前/排队执行;delete 同时删除计划并请求停止执行。宿主必须持续运行,持久化不代表关机后执行。不要通过 Bash 或写 JSON 绕过此工具;定时任务本身不得扩大授权或创建新计划。',
84
+ inputSchema: schema,
85
+ parameters: toToolParameters(schema),
86
+ isReadOnly: false,
87
+ isConcurrencySafe: false,
88
+ availableInModes: ['private'],
89
+ availableOnSurfaces: ['tui', 'desktop', 'cli'],
90
+ resolveAvailability: (runtime) => ({
91
+ available: runtime.profile === 'main' && runtime.owner === 'local-owner',
92
+ signature: `schedule-v1:${runtime.profile}:${runtime.owner}`,
93
+ }),
94
+ gateRequest: (input) => ({
95
+ isReadOnly: input?.action === 'list' || input?.action === 'show',
96
+ }),
97
+ call: async () => ({ ok: false, error: 'Schedule 需要本地主会话宿主' }),
98
+ callWithContext: async (raw, signal, ctx) => {
99
+ const parsed = schema.safeParse(raw);
100
+ if (!parsed.success)
101
+ return {
102
+ ok: false,
103
+ error: parsed.error.message,
104
+ disposition: 'not_executed',
105
+ };
106
+ if (!ctx.cwd ||
107
+ !ctx.sessionId ||
108
+ !['tui', 'desktop', 'cli'].includes(ctx.surface ?? '') ||
109
+ ctx.agentHandoff ||
110
+ (ctx.conversationMode && ctx.conversationMode !== 'private') ||
111
+ ctx.owner !== 'local-owner')
112
+ return {
113
+ ok: false,
114
+ error: '仅授权的本地主会话可管理计划;后台、子 Agent 和群会话不可用',
115
+ disposition: 'not_executed',
116
+ };
117
+ const input = requestSchema.parse(parsed.data);
118
+ signal?.throwIfAborted();
119
+ const service = await import('../../../plugins/cron-runner/src/service.js');
120
+ const store = await import('../../../plugins/cron-runner/src/store.js');
121
+ const requests = await import('../../../plugins/cron-runner/src/requests.js');
122
+ const { getCronScheduler } = await import('../../../plugins/cron-runner/plugin.js');
123
+ const scope = (cwd) => process.platform === 'win32' ? resolve(cwd).toLowerCase() : resolve(cwd);
124
+ const receipt = (value) => ({
125
+ ok: true,
126
+ content: JSON.stringify(value),
127
+ });
128
+ if (input.action === 'list')
129
+ return receipt((await service.listCronTasks()).filter((row) => scope(row.task.runtime.cwd) === scope(ctx.cwd)));
130
+ if (input.action === 'create') {
131
+ const task = await service.createCronFromDraft({
132
+ name: input.name,
133
+ status: 'active',
134
+ kind: input.schedule.type === 'once' ? 'once' : 'recurring',
135
+ schedule: input.schedule,
136
+ action: input.execution,
137
+ catchUp: input.catchUp,
138
+ maxRuns: input.maxRuns,
139
+ runtime: {
140
+ cwd: ctx.cwd,
141
+ sessionId: ctx.sessionId,
142
+ sessionMode: input.sessionMode,
143
+ },
144
+ }, JSON.stringify([scope(ctx.cwd), ctx.sessionId, input.requestId]));
145
+ return receipt({
146
+ task,
147
+ hostRunning: !!getCronScheduler(),
148
+ notice: '需要保持 Desktop/TUI 调度宿主运行',
149
+ });
150
+ }
151
+ const task = await store.getTask(input.id);
152
+ if (!task || scope(task.runtime.cwd) !== scope(ctx.cwd))
153
+ return { ok: false, error: '当前工作区未找到计划' };
154
+ if (input.action === 'show')
155
+ return receipt({ task, runs: await store.recentRuns(task.id, 5) });
156
+ if (input.action === 'delete')
157
+ return receipt({ deleted: await store.deleteTask(task.id), id: task.id });
158
+ if (input.action === 'stop') {
159
+ await requests.requestStop(task.id);
160
+ getCronScheduler()?.wake();
161
+ return receipt({ stopRequested: task.id });
162
+ }
163
+ if (input.action === 'run') {
164
+ if (!getCronScheduler())
165
+ return { ok: false, error: '调度宿主未启动,未加入执行队列' };
166
+ const run = await requests.requestRun(task.id, JSON.stringify([ctx.sessionId, input.requestId]));
167
+ getCronScheduler()?.wake();
168
+ return receipt({ id: run.id, status: run.status });
169
+ }
170
+ if (input.action === 'update') {
171
+ const { execution, ...patch } = input.changes;
172
+ return receipt(await service.updateCronFromPatch({
173
+ ...patch,
174
+ id: task.id,
175
+ expectedRevision: input.expectedRevision,
176
+ ...(execution ? { action: execution } : {}),
177
+ }));
178
+ }
179
+ return receipt(await service.updateCronFromPatch({
180
+ id: task.id,
181
+ status: input.action === 'pause' ? 'paused' : 'active',
182
+ }));
183
+ },
184
+ };