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
@@ -7,25 +7,30 @@ import {
7
7
  listMissed,
8
8
  listTasks,
9
9
  recentRuns,
10
- patchTask,
11
- upsertTask,
12
10
  } from './store.js';
13
11
  import type { CronTask } from './types.js';
14
12
  import type { Scheduler } from './scheduler.js';
15
13
  import { validateCron, validateIsoDate } from './schema.js';
16
14
  import { requestRun, requestStop } from './requests.js';
15
+ import { createCronFromDraft, updateCronFromPatch } from './service.js';
16
+
17
+ export interface CronCommandContext {
18
+ cwd: string;
19
+ sessionId?: string;
20
+ }
17
21
 
18
22
  export async function handleCronCommand(
19
23
  commandName: string,
20
24
  args: string,
21
25
  scheduler: Scheduler | null,
26
+ context?: CronCommandContext,
22
27
  ): Promise<string> {
23
28
  if (commandName === 'crons') return await formatTaskList(await listTasks());
24
29
 
25
30
  const argv = tokenize(args);
26
31
  const action = argv.shift() ?? 'list';
27
32
  if (action === 'list') return await formatTaskList(await listTasks());
28
- if (action === 'create') return await createFromArgs(argv);
33
+ if (action === 'create') return await createFromArgs(argv, context);
29
34
  if (action === 'pause' || action === 'resume')
30
35
  return await setStatus(argv[0], action === 'resume' ? 'active' : 'paused');
31
36
  if (action === 'delete' || action === 'remove') return await remove(argv[0]);
@@ -41,7 +46,7 @@ export async function handleCronCommand(
41
46
  }
42
47
  if (action === 'missed') return await formatMissed();
43
48
  if (action === 'help') return helpText();
44
- const shortcut = await createFromShortcut(action, argv);
49
+ const shortcut = await createFromShortcut(action, argv, context);
45
50
  if (shortcut) return shortcut;
46
51
  if (/^\d+\S*$/.test(action)) {
47
52
  return `无效间隔:${action}。支持 1m、2h、1d、1w(最小 1 分钟)。`;
@@ -49,11 +54,16 @@ export async function handleCronCommand(
49
54
  return `未知 /cron 子命令:${action}\n\n${helpText()}`;
50
55
  }
51
56
 
52
- async function createFromArgs(argv: string[]): Promise<string> {
57
+ async function createFromArgs(
58
+ argv: string[],
59
+ context?: CronCommandContext,
60
+ ): Promise<string> {
53
61
  const opts = parseOptions(argv);
54
62
  const cron = opts.cron;
55
63
  const at = opts.at;
56
- const intervalMs = opts.interval ? parseIntervalShortcut(opts.interval) : undefined;
64
+ const intervalMs = opts.interval
65
+ ? parseIntervalShortcut(opts.interval)
66
+ : undefined;
57
67
  const name = opts.name;
58
68
  const prompt = opts.prompt;
59
69
  const workflow = opts.workflow;
@@ -66,18 +76,26 @@ async function createFromArgs(argv: string[]): Promise<string> {
66
76
  }
67
77
  if (at && (!Number.isFinite(Date.parse(at)) || Date.parse(at) <= Date.now()))
68
78
  return 'at 必须是未来的 ISO 日期时间。';
69
- const timezone = opts.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
79
+ const timezone =
80
+ opts.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
70
81
  try {
71
82
  new Intl.DateTimeFormat('en', { timeZone: timezone }).format();
72
83
  } catch {
73
84
  return '无效的 IANA 时区';
74
85
  }
75
- const maxTurns = opts.maxTurns ? Number.parseInt(opts.maxTurns, 10) : undefined;
76
- if (opts.maxTurns && (!Number.isFinite(maxTurns) || maxTurns! <= 0)) {
86
+ if (
87
+ [cron, at, opts.interval].filter(Boolean).length !== 1 ||
88
+ [prompt, workflow].filter(Boolean).length !== 1
89
+ )
90
+ return '必须且只能指定一种计划和一种执行内容';
91
+ if (!opts.session && !context?.sessionId && opts.freshSession !== 'true')
92
+ return '缺少当前会话;请指定 --session 或 --fresh-session,不能自动绑定 default。';
93
+ const maxTurns = opts.maxTurns ? Number(opts.maxTurns) : undefined;
94
+ if (opts.maxTurns && (!Number.isInteger(maxTurns) || maxTurns! <= 0)) {
77
95
  return `无效 maxTurns:${opts.maxTurns}`;
78
96
  }
79
- const maxRuns = opts.maxRuns ? Number.parseInt(opts.maxRuns, 10) : undefined;
80
- if (opts.maxRuns && (!Number.isFinite(maxRuns) || maxRuns! <= 0)) {
97
+ const maxRuns = opts.maxRuns ? Number(opts.maxRuns) : undefined;
98
+ if (opts.maxRuns && (!Number.isInteger(maxRuns) || maxRuns! <= 0)) {
81
99
  return `无效 max-runs:${opts.maxRuns}(须是正整数,跑满这么多次后自动完成)`;
82
100
  }
83
101
  if (opts.expiresAt) {
@@ -91,10 +109,10 @@ async function createFromArgs(argv: string[]): Promise<string> {
91
109
  at,
92
110
  intervalMs: intervalMs ?? undefined,
93
111
  timezone,
94
- sessionId: opts.session,
112
+ sessionId: opts.session ?? context?.sessionId,
95
113
  catchUp: opts.catchUp === 'latest' ? 'latest' : 'skip',
96
114
  notifications: opts.notifications === 'failures' ? 'failures' : 'all',
97
- cwd: getWorkingDir(),
115
+ cwd: context?.cwd ?? getWorkingDir(),
98
116
  ...(opts.model ? { model: opts.model } : {}),
99
117
  ...(maxTurns ? { maxTurns } : {}),
100
118
  kind: opts.once === 'true' ? 'once' : 'recurring',
@@ -106,14 +124,20 @@ async function createFromArgs(argv: string[]): Promise<string> {
106
124
  ? { type: 'workflow', command: workflow }
107
125
  : { type: 'prompt', prompt: prompt! },
108
126
  });
109
- await upsertTask(task);
127
+ await saveCommandTask(task);
110
128
  return `已创建 cron:${task.id}\n${await formatTask(task)}`;
111
129
  }
112
130
 
113
- async function createFromShortcut(head: string, rest: string[]): Promise<string | null> {
131
+ async function createFromShortcut(
132
+ head: string,
133
+ rest: string[],
134
+ context?: CronCommandContext,
135
+ ): Promise<string | null> {
114
136
  const parsed = parseShortcutSchedule(head, rest);
115
137
  if (!parsed) return null;
116
138
  if ('error' in parsed) return parsed.error;
139
+ if (!context?.sessionId)
140
+ return '缺少当前会话;请指定 --session 或 --fresh-session,不能自动绑定 default。';
117
141
  const task = createTask({
118
142
  name: parsed.name,
119
143
  ...(parsed.description ? { description: parsed.description } : {}),
@@ -122,13 +146,47 @@ async function createFromShortcut(head: string, rest: string[]): Promise<string
122
146
  ? { intervalMs: parsed.intervalMs, anchorAt: new Date().toISOString() }
123
147
  : {}),
124
148
  timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'local',
125
- cwd: getWorkingDir(),
149
+ cwd: context.cwd,
150
+ sessionId: context.sessionId,
126
151
  action: parsed.action,
127
152
  });
128
- await upsertTask(task);
153
+ await saveCommandTask(task);
129
154
  return `已创建 cron:${task.id}\n${await formatTask(task)}`;
130
155
  }
131
156
 
157
+ async function saveCommandTask(task: CronTask): Promise<void> {
158
+ const schedule =
159
+ task.schedule.type === 'once'
160
+ ? { type: 'once' as const, at: task.schedule.at }
161
+ : task.schedule.type === 'cron'
162
+ ? {
163
+ type: 'cron' as const,
164
+ cron: task.schedule.cron,
165
+ timezone: task.schedule.timezone,
166
+ }
167
+ : {
168
+ type: 'interval' as const,
169
+ intervalMs: task.schedule.intervalMs,
170
+ anchorAt: task.schedule.anchorAt,
171
+ };
172
+ const { environment, bindingStatus, ...runtime } = task.runtime;
173
+ const saved = await createCronFromDraft({
174
+ name: task.name,
175
+ description: task.description,
176
+ status: task.status,
177
+ kind: task.kind,
178
+ catchUp: task.catchUp,
179
+ notifications: task.notifications,
180
+ permanent: task.permanent,
181
+ expiresAt: task.expiresAt,
182
+ maxRuns: task.maxRuns,
183
+ schedule,
184
+ runtime,
185
+ action: task.action,
186
+ });
187
+ Object.assign(task, saved);
188
+ }
189
+
132
190
  export function parseShortcutSchedule(
133
191
  head: string,
134
192
  rest: string[],
@@ -190,18 +248,25 @@ export function parseIntervalShortcut(text: string): number | null {
190
248
  ? 60 * 60_000
191
249
  : 60_000;
192
250
  const intervalMs = value * multiplier;
193
- return Number.isSafeInteger(intervalMs) && intervalMs >= 60_000 ? intervalMs : null;
251
+ return Number.isSafeInteger(intervalMs) && intervalMs >= 60_000
252
+ ? intervalMs
253
+ : null;
194
254
  }
195
255
 
196
256
  function parseShortcutAction(
197
257
  tokens: string[],
198
- ): { action: CronTask['action']; description?: string; name: string } | { error: string } {
258
+ ):
259
+ | { action: CronTask['action']; description?: string; name: string }
260
+ | { error: string } {
199
261
  if (tokens.length === 0) {
200
262
  return {
201
- error: '请在时间后面写提示词或 workflow。\n例如:/cron 1d /workflow research 生成中文新闻稿',
263
+ error:
264
+ '请在时间后面写提示词或 workflow。\n例如:/cron 1d /workflow research 生成中文新闻稿',
202
265
  };
203
266
  }
204
- const markerIndex = tokens.findIndex((token) => token === '/workflow' || token === 'workflow');
267
+ const markerIndex = tokens.findIndex(
268
+ (token) => token === '/workflow' || token === 'workflow',
269
+ );
205
270
  if (markerIndex < 0) {
206
271
  const prompt = tokens.join(' ').trim();
207
272
  return { action: { type: 'prompt', prompt }, name: deriveName(prompt) };
@@ -218,7 +283,9 @@ function parseShortcutAction(
218
283
  }
219
284
 
220
285
  function serializeTokens(tokens: string[]): string {
221
- return tokens.map((token) => (/\s|["'\\]/.test(token) ? JSON.stringify(token) : token)).join(' ');
286
+ return tokens
287
+ .map((token) => (/\s|["'\\]/.test(token) ? JSON.stringify(token) : token))
288
+ .join(' ');
222
289
  }
223
290
 
224
291
  function parseClockTime(text: string): { hour: number; minute: number } | null {
@@ -232,20 +299,30 @@ function parseClockTime(text: string): { hour: number; minute: number } | null {
232
299
 
233
300
  function weekdayNumber(day: string): number {
234
301
  return (
235
- ({ 日: 0, 天: 0, 一: 1, 二: 2, 三: 3, 四: 4, 五: 5, 六: 6 } as Record<string, number>)[day] ?? 1
302
+ (
303
+ { 日: 0, 天: 0, 一: 1, 二: 2, 三: 3, 四: 4, 五: 5, 六: 6 } as Record<
304
+ string,
305
+ number
306
+ >
307
+ )[day] ?? 1
236
308
  );
237
309
  }
238
310
 
239
311
  function deriveName(prompt: string): string {
240
312
  const compact = prompt.replace(/\s+/g, ' ').trim();
241
- return compact.length > 18 ? `${compact.slice(0, 18)}...` : compact || 'cron task';
313
+ return compact.length > 18
314
+ ? `${compact.slice(0, 18)}...`
315
+ : compact || 'cron task';
242
316
  }
243
317
 
244
- async function setStatus(id: string | undefined, status: CronTask['status']): Promise<string> {
318
+ async function setStatus(
319
+ id: string | undefined,
320
+ status: CronTask['status'],
321
+ ): Promise<string> {
245
322
  if (!id) return '请提供任务 id。';
246
323
  const task = await getTask(id);
247
324
  if (!task) return `未找到任务:${id}`;
248
- await patchTask({ id: task.id, status });
325
+ await updateCronFromPatch({ id: task.id, status });
249
326
  return `已${status === 'active' ? '恢复' : '暂停'} ${task.id}`;
250
327
  }
251
328
 
@@ -269,7 +346,10 @@ async function show(id: string | undefined): Promise<string> {
269
346
  return `${await formatTask(task)}\n${runLines}`;
270
347
  }
271
348
 
272
- async function runNow(id: string | undefined, scheduler: Scheduler | null): Promise<string> {
349
+ async function runNow(
350
+ id: string | undefined,
351
+ scheduler: Scheduler | null,
352
+ ): Promise<string> {
273
353
  if (!id) return '请提供任务 id。';
274
354
  if (!scheduler) return 'cron scheduler 尚未启动;请在 TUI 中运行。';
275
355
  const task = await getTask(id);
@@ -294,19 +374,24 @@ async function formatMissed(): Promise<string> {
294
374
  async function formatTaskList(tasks: CronTask[]): Promise<string> {
295
375
  if (tasks.length === 0) return '暂无 cron 任务。';
296
376
  const missed = await listMissed(1);
297
- const header = missed.length > 0 ? `提示:有错过任务,可用 /cron missed 查看。\n\n` : '';
377
+ const header =
378
+ missed.length > 0 ? `提示:有错过任务,可用 /cron missed 查看。\n\n` : '';
298
379
  const body = await Promise.all(tasks.map(formatTask));
299
380
  return `${header}${body.join('\n\n')}`;
300
381
  }
301
382
 
302
383
  async function formatTask(task: CronTask): Promise<string> {
303
384
  const action =
304
- task.action.type === 'workflow' ? `/workflow ${task.action.command}` : task.action.prompt;
385
+ task.action.type === 'workflow'
386
+ ? `/workflow ${task.action.command}`
387
+ : task.action.prompt;
305
388
  const runs = await recentRuns(task.id, 1);
306
- const recent = runs[0] ? `${runs[0].status}${runs[0].error ? ` · ${runs[0].error}` : ''}` : '-';
389
+ const recent = runs[0]
390
+ ? `${runs[0].status}${runs[0].error ? ` · ${runs[0].error}` : ''}`
391
+ : '-';
307
392
  return [
308
393
  `${task.id} · ${task.name}`,
309
- `状态:${task.status === 'active' ? '活跃' : '暂停'}`,
394
+ `状态:${task.status === 'active' ? '活跃' : task.status === 'completed' ? '已完成' : '暂停'}`,
310
395
  `类型:${task.kind === 'once' ? '一次性' : task.maxRuns ? `限 ${task.maxRuns} 次` : '重复'}`,
311
396
  `下次运行:${formatDateTime(task.schedule.nextRunAt)}`,
312
397
  `上次运行时间:${formatDateTime(task.stats.lastRunAt)}`,
@@ -358,7 +443,11 @@ function tokenize(input: string): string[] {
358
443
  for (let i = 0; i < input.length; i++) {
359
444
  const ch = input[i]!;
360
445
  if (quote) {
361
- if (ch === '\\' && i + 1 < input.length) {
446
+ if (
447
+ ch === '\\' &&
448
+ i + 1 < input.length &&
449
+ (input[i + 1] === quote || input[i + 1] === '\\')
450
+ ) {
362
451
  cur += input[++i]!;
363
452
  } else if (ch === quote) {
364
453
  quote = null;
@@ -380,6 +469,7 @@ function tokenize(input: string): string[] {
380
469
  }
381
470
  cur += ch;
382
471
  }
472
+ if (quote) throw new Error('命令引号未闭合');
383
473
  if (cur) out.push(cur);
384
474
  return out;
385
475
  }
@@ -388,15 +478,46 @@ function parseOptions(argv: string[]): Record<string, string> {
388
478
  const map: Record<string, string> = {};
389
479
  for (let i = 0; i < argv.length; i++) {
390
480
  const key = argv[i]!;
391
- if (!key.startsWith('--')) continue;
481
+ if (!key.startsWith('--')) throw new Error(`无效参数:${key}`);
482
+ const allowed = [
483
+ 'name',
484
+ 'description',
485
+ 'cron',
486
+ 'at',
487
+ 'interval',
488
+ 'prompt',
489
+ 'workflow',
490
+ 'timezone',
491
+ 'session',
492
+ 'catchUp',
493
+ 'notifications',
494
+ 'model',
495
+ 'maxTurns',
496
+ 'once',
497
+ 'permanent',
498
+ 'expiresAt',
499
+ 'maxRuns',
500
+ 'freshSession',
501
+ ];
502
+ const name = toCamel(key.slice(2));
503
+ if (!allowed.includes(name) || name in map)
504
+ throw new Error(`未知或重复参数:${key}`);
392
505
  const value = argv[i + 1];
393
506
  if (!value || value.startsWith('--')) {
507
+ if (!['once', 'permanent', 'freshSession'].includes(name))
508
+ throw new Error(`参数缺少值:${key}`);
394
509
  map[toCamel(key.slice(2))] = 'true';
395
510
  continue;
396
511
  }
397
512
  map[toCamel(key.slice(2))] = value;
398
513
  i++;
399
514
  }
515
+ if (map.catchUp && !['skip', 'latest'].includes(map.catchUp))
516
+ throw new Error('catch-up 必须是 skip 或 latest');
517
+ if (map.notifications && !['all', 'failures'].includes(map.notifications))
518
+ throw new Error('notifications 必须是 all 或 failures');
519
+ if (map.session && map.freshSession)
520
+ throw new Error('session 与 fresh-session 不能同时指定');
400
521
  return map;
401
522
  }
402
523
 
@@ -0,0 +1,70 @@
1
+ import { z } from 'zod';
2
+ const text = z.string().trim().min(1);
3
+ const date = text.refine((v) => Number.isFinite(Date.parse(v)), '无效日期');
4
+ export const scheduleSchema = z.discriminatedUnion('type', [
5
+ z
6
+ .object({
7
+ type: z.literal('once'),
8
+ at: date,
9
+ jitterMs: z.number().finite().nonnegative().optional(),
10
+ })
11
+ .strict(),
12
+ z
13
+ .object({
14
+ type: z.literal('cron'),
15
+ cron: text,
16
+ timezone: text,
17
+ jitterMs: z.number().finite().nonnegative().optional(),
18
+ })
19
+ .strict(),
20
+ z
21
+ .object({
22
+ type: z.literal('interval'),
23
+ intervalMs: z.number().finite().min(60_000),
24
+ anchorAt: date.optional(),
25
+ jitterMs: z.number().finite().nonnegative().optional(),
26
+ })
27
+ .strict(),
28
+ ]);
29
+ export const actionSchema = z.discriminatedUnion('type', [
30
+ z.object({ type: z.literal('prompt'), prompt: text }).strict(),
31
+ z.object({ type: z.literal('workflow'), command: text }).strict(),
32
+ ]);
33
+ const runtime = z
34
+ .object({
35
+ cwd: text,
36
+ sessionId: text.optional(),
37
+ sessionMode: z.enum(['persistent', 'fresh']).optional(),
38
+ model: text.optional(),
39
+ maxTurns: z.number().int().positive().optional(),
40
+ })
41
+ .strict();
42
+ export const draftSchema = z
43
+ .object({
44
+ id: text.optional(),
45
+ name: text,
46
+ description: z.string().optional(),
47
+ status: z.enum(['active', 'paused', 'completed']),
48
+ kind: z.enum(['once', 'recurring']),
49
+ permanent: z.boolean().optional(),
50
+ expiresAt: date.optional(),
51
+ maxRuns: z.number().int().positive().optional(),
52
+ catchUp: z.enum(['skip', 'latest']).optional(),
53
+ notifications: z.enum(['all', 'failures']).optional(),
54
+ schedule: scheduleSchema,
55
+ action: actionSchema,
56
+ runtime,
57
+ })
58
+ .strict();
59
+ export const patchSchema = draftSchema
60
+ .omit({ id: true, runtime: true })
61
+ .partial()
62
+ .extend({
63
+ id: text,
64
+ runtime: runtime.partial().optional(),
65
+ expiresAt: z.union([date, z.literal('')]).optional(),
66
+ expectedRevision: z.number().int().nonnegative().optional(),
67
+ clearMaxRuns: z.boolean().optional(),
68
+ clearMaxTurns: z.boolean().optional(),
69
+ })
70
+ .strict();
@@ -0,0 +1,70 @@
1
+ import { z } from 'zod';
2
+ const text = z.string().trim().min(1);
3
+ const date = text.refine((v) => Number.isFinite(Date.parse(v)), '无效日期');
4
+ export const scheduleSchema = z.discriminatedUnion('type', [
5
+ z
6
+ .object({
7
+ type: z.literal('once'),
8
+ at: date,
9
+ jitterMs: z.number().finite().nonnegative().optional(),
10
+ })
11
+ .strict(),
12
+ z
13
+ .object({
14
+ type: z.literal('cron'),
15
+ cron: text,
16
+ timezone: text,
17
+ jitterMs: z.number().finite().nonnegative().optional(),
18
+ })
19
+ .strict(),
20
+ z
21
+ .object({
22
+ type: z.literal('interval'),
23
+ intervalMs: z.number().finite().min(60_000),
24
+ anchorAt: date.optional(),
25
+ jitterMs: z.number().finite().nonnegative().optional(),
26
+ })
27
+ .strict(),
28
+ ]);
29
+ export const actionSchema = z.discriminatedUnion('type', [
30
+ z.object({ type: z.literal('prompt'), prompt: text }).strict(),
31
+ z.object({ type: z.literal('workflow'), command: text }).strict(),
32
+ ]);
33
+ const runtime = z
34
+ .object({
35
+ cwd: text,
36
+ sessionId: text.optional(),
37
+ sessionMode: z.enum(['persistent', 'fresh']).optional(),
38
+ model: text.optional(),
39
+ maxTurns: z.number().int().positive().optional(),
40
+ })
41
+ .strict();
42
+ export const draftSchema = z
43
+ .object({
44
+ id: text.optional(),
45
+ name: text,
46
+ description: z.string().optional(),
47
+ status: z.enum(['active', 'paused', 'completed']),
48
+ kind: z.enum(['once', 'recurring']),
49
+ permanent: z.boolean().optional(),
50
+ expiresAt: date.optional(),
51
+ maxRuns: z.number().int().positive().optional(),
52
+ catchUp: z.enum(['skip', 'latest']).optional(),
53
+ notifications: z.enum(['all', 'failures']).optional(),
54
+ schedule: scheduleSchema,
55
+ action: actionSchema,
56
+ runtime,
57
+ })
58
+ .strict();
59
+ export const patchSchema = draftSchema
60
+ .omit({ id: true, runtime: true })
61
+ .partial()
62
+ .extend({
63
+ id: text,
64
+ runtime: runtime.partial().optional(),
65
+ expiresAt: z.union([date, z.literal('')]).optional(),
66
+ expectedRevision: z.number().int().nonnegative().optional(),
67
+ clearMaxRuns: z.boolean().optional(),
68
+ clearMaxTurns: z.boolean().optional(),
69
+ })
70
+ .strict();
@@ -1,12 +1,15 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
- import { appendRun, cronDataRoot, getTask, recentRuns } from './store.js';
5
- import { withStoreLock } from './lock.js';
4
+ import { appendRun, cronDataRoot, getTask, recentRuns, activeRuns, } from './store.js';
5
+ import { taskTransaction } from './transaction.js';
6
6
  export async function enqueueRun(task, requestId = randomUUID(), scheduledFor) {
7
- return withStoreLock(join(cronDataRoot(), 'requests'), async () => {
7
+ return taskTransaction(cronDataRoot(), task.id, async () => {
8
+ const current = await getTask(task.id);
9
+ if (!current || (current.planId ?? current.id) !== (task.planId ?? task.id))
10
+ throw new Error('计划已删除或修改,请重新读取后执行');
8
11
  const id = `run-${createHash('sha256')
9
- .update(`${task.id}:${scheduledFor ?? requestId}`)
12
+ .update(`${task.id}:${scheduledFor ? `${task.planId ?? task.id}:${scheduledFor}` : requestId}`)
10
13
  .digest('hex')
11
14
  .slice(0, 24)}`;
12
15
  const runs = await recentRuns(task.id, Infinity);
@@ -24,8 +27,12 @@ export async function enqueueRun(task, requestId = randomUUID(), scheduledFor) {
24
27
  startedAt: new Date().toISOString(),
25
28
  status: 'queued',
26
29
  cwd: task.runtime.cwd,
27
- sessionId: task.runtime.sessionMode === 'fresh' ? `scheduled-${randomUUID()}` : task.runtime.sessionId,
30
+ sessionId: task.runtime.sessionMode === 'fresh'
31
+ ? `scheduled-${randomUUID()}`
32
+ : task.runtime.sessionId,
28
33
  model: task.runtime.model,
34
+ snapshot: structuredClone(task),
35
+ planId: task.planId ?? task.id,
29
36
  };
30
37
  await appendRun(run);
31
38
  return run;
@@ -41,14 +48,16 @@ function stopPath(runId) {
41
48
  return join(cronDataRoot(), 'requests', `${createHash('sha256').update(runId).digest('hex')}.stop`);
42
49
  }
43
50
  export async function requestStop(taskId) {
44
- for (const run of await recentRuns(taskId, Infinity))
45
- if (run.status === 'queued' || run.status === 'running') {
46
- const file = stopPath(run.id);
47
- await mkdir(join(cronDataRoot(), 'requests'), { recursive: true });
48
- const tmp = `${file}.${randomUUID()}.tmp`;
49
- await writeFile(tmp, new Date().toISOString());
50
- await rename(tmp, file);
51
- }
51
+ return taskTransaction(cronDataRoot(), taskId, async () => {
52
+ for (const run of await activeRuns(taskId))
53
+ if (run.status === 'queued' || run.status === 'running') {
54
+ const file = stopPath(run.id);
55
+ await mkdir(join(cronDataRoot(), 'requests'), { recursive: true });
56
+ const tmp = `${file}.${randomUUID()}.tmp`;
57
+ await writeFile(tmp, new Date().toISOString());
58
+ await rename(tmp, file);
59
+ }
60
+ });
52
61
  }
53
62
  export async function stopRequested(runId) {
54
63
  try {
@@ -1,8 +1,14 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
- import { appendRun, cronDataRoot, getTask, recentRuns } from './store.js';
5
- import { withStoreLock } from './lock.js';
4
+ import {
5
+ appendRun,
6
+ cronDataRoot,
7
+ getTask,
8
+ recentRuns,
9
+ activeRuns,
10
+ } from './store.js';
11
+ import { taskTransaction } from './transaction.js';
6
12
  import type { CronRunRecord, CronTask } from './types.js';
7
13
 
8
14
  export async function enqueueRun(
@@ -10,9 +16,14 @@ export async function enqueueRun(
10
16
  requestId: string = randomUUID(),
11
17
  scheduledFor?: string,
12
18
  ): Promise<CronRunRecord> {
13
- return withStoreLock(join(cronDataRoot(), 'requests'), async () => {
19
+ return taskTransaction(cronDataRoot(), task.id, async () => {
20
+ const current = await getTask(task.id);
21
+ if (!current || (current.planId ?? current.id) !== (task.planId ?? task.id))
22
+ throw new Error('计划已删除或修改,请重新读取后执行');
14
23
  const id = `run-${createHash('sha256')
15
- .update(`${task.id}:${scheduledFor ?? requestId}`)
24
+ .update(
25
+ `${task.id}:${scheduledFor ? `${task.planId ?? task.id}:${scheduledFor}` : requestId}`,
26
+ )
16
27
  .digest('hex')
17
28
  .slice(0, 24)}`;
18
29
  const runs = await recentRuns(task.id, Infinity);
@@ -31,15 +42,22 @@ export async function enqueueRun(
31
42
  status: 'queued',
32
43
  cwd: task.runtime.cwd,
33
44
  sessionId:
34
- task.runtime.sessionMode === 'fresh' ? `scheduled-${randomUUID()}` : task.runtime.sessionId,
45
+ task.runtime.sessionMode === 'fresh'
46
+ ? `scheduled-${randomUUID()}`
47
+ : task.runtime.sessionId,
35
48
  model: task.runtime.model,
49
+ snapshot: structuredClone(task),
50
+ planId: task.planId ?? task.id,
36
51
  };
37
52
  await appendRun(run);
38
53
  return run;
39
54
  });
40
55
  }
41
56
 
42
- export async function requestRun(id: string, requestId?: string): Promise<CronRunRecord> {
57
+ export async function requestRun(
58
+ id: string,
59
+ requestId?: string,
60
+ ): Promise<CronRunRecord> {
43
61
  const task = await getTask(id);
44
62
  if (!task) throw new Error(`未找到计划任务:${id}`);
45
63
  return enqueueRun(task, requestId);
@@ -52,14 +70,16 @@ function stopPath(runId: string) {
52
70
  );
53
71
  }
54
72
  export async function requestStop(taskId: string): Promise<void> {
55
- for (const run of await recentRuns(taskId, Infinity))
56
- if (run.status === 'queued' || run.status === 'running') {
57
- const file = stopPath(run.id);
58
- await mkdir(join(cronDataRoot(), 'requests'), { recursive: true });
59
- const tmp = `${file}.${randomUUID()}.tmp`;
60
- await writeFile(tmp, new Date().toISOString());
61
- await rename(tmp, file);
62
- }
73
+ return taskTransaction(cronDataRoot(), taskId, async () => {
74
+ for (const run of await activeRuns(taskId))
75
+ if (run.status === 'queued' || run.status === 'running') {
76
+ const file = stopPath(run.id);
77
+ await mkdir(join(cronDataRoot(), 'requests'), { recursive: true });
78
+ const tmp = `${file}.${randomUUID()}.tmp`;
79
+ await writeFile(tmp, new Date().toISOString());
80
+ await rename(tmp, file);
81
+ }
82
+ });
63
83
  }
64
84
  export async function stopRequested(runId: string): Promise<boolean> {
65
85
  try {