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
@@ -2,11 +2,20 @@ import { randomUUID } from 'node:crypto';
2
2
  import { existsSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import type { PluginRuntimeContext } from '../../../src/plugin-sdk.js';
5
- import { resolveSessionFile } from '../../../src/plugin-sdk.js';
5
+ import {
6
+ resolveSessionFile,
7
+ createSessionState,
8
+ disposeDetachedSessionState,
9
+ } from '../../../src/plugin-sdk.js';
6
10
  import { releaseSchedulerLock, tryAcquireSchedulerLock } from './lock.js';
7
- import { countScheduleSlots, latestScheduleRunMs, nextScheduleRunMs } from './scheduleEngine.js';
11
+ import {
12
+ countScheduleSlots,
13
+ latestScheduleRunMs,
14
+ nextScheduleRunMs,
15
+ } from './scheduleEngine.js';
8
16
  import {
9
17
  appendMissed,
18
+ activeRuns,
10
19
  appendRun,
11
20
  cronDataRoot,
12
21
  cronLockFile,
@@ -17,8 +26,16 @@ import {
17
26
  updateTask,
18
27
  } from './store.js';
19
28
  import { listRunTaskIds } from './runs.js';
20
- import { enqueueRun, requestRun, requestStop, stopRequested } from './requests.js';
29
+ import {
30
+ enqueueRun,
31
+ requestRun,
32
+ requestStop,
33
+ stopRequested,
34
+ } from './requests.js';
21
35
  import type { CronRunRecord, CronTask } from './types.js';
36
+ import { taskTransaction } from './transaction.js';
37
+ import { executionOutcome } from '../../../src/session/executionOutcome.js';
38
+ import { backgroundCompletionFields } from '../../../src/runtime/backgroundCompletion.js';
22
39
 
23
40
  export const RECONCILE_MS = 1_000;
24
41
  export function boundedWakeDelay(at: number, now = Date.now()): number {
@@ -41,7 +58,18 @@ export class Scheduler {
41
58
  private tick: Promise<void> | null = null;
42
59
  private stopPromise: Promise<void> | null = null;
43
60
 
44
- constructor(private readonly ctx: PluginRuntimeContext) {}
61
+ constructor(
62
+ private readonly ctx: PluginRuntimeContext,
63
+ private readonly limits = { concurrency: 4, timeoutMs: 10 * 60_000 },
64
+ ) {
65
+ if (
66
+ !Number.isInteger(limits.concurrency) ||
67
+ limits.concurrency < 1 ||
68
+ !Number.isFinite(limits.timeoutMs) ||
69
+ limits.timeoutMs < 1
70
+ )
71
+ throw new Error('无效的调度并发或超时限制');
72
+ }
45
73
  start(): void {
46
74
  if (this.started) return;
47
75
  this.started = true;
@@ -80,7 +108,8 @@ export class Scheduler {
80
108
  if (temporary) {
81
109
  await Promise.allSettled([...this.executions.values()]);
82
110
  if (this.dueTimer) clearTimeout(this.dueTimer);
83
- if (this.ownsLock) await releaseSchedulerLock(cronLockFile(), this.owner);
111
+ if (this.ownsLock)
112
+ await releaseSchedulerLock(cronLockFile(), this.owner);
84
113
  this.ownsLock = false;
85
114
  }
86
115
  }
@@ -110,14 +139,19 @@ export class Scheduler {
110
139
  if (this.stopping) return;
111
140
  // Deleted schedules no longer appear in listTasks, but their stop requests still apply.
112
141
  for (const [id, run] of this.activeRuns)
113
- if (await stopRequested(run.id)) this.controllers.get(id)?.abort('用户停止本次执行');
142
+ if (await stopRequested(run.id))
143
+ this.controllers.get(id)?.abort('用户停止本次执行');
114
144
  if (!this.ownsLock) {
115
- this.ownsLock = await tryAcquireSchedulerLock(cronLockFile(), this.owner, () => {
116
- this.ownsLock = false;
117
- this.executionController.abort('调度租约丢失');
118
- // Never reacquire while old work may still be executing.
119
- void this.stop();
120
- });
145
+ this.ownsLock = await tryAcquireSchedulerLock(
146
+ cronLockFile(),
147
+ this.owner,
148
+ () => {
149
+ this.ownsLock = false;
150
+ this.executionController.abort('调度租约丢失');
151
+ // Never reacquire while old work may still be executing.
152
+ void this.stop();
153
+ },
154
+ );
121
155
  if (!this.ownsLock) return;
122
156
  await this.recover();
123
157
  await this.recordMissedTasks();
@@ -126,19 +160,20 @@ export class Scheduler {
126
160
  const tasks = await listTasks();
127
161
  for (const task of tasks) {
128
162
  await this.processDueTask(task, Date.now());
129
- const runs = await recentRuns(task.id, Infinity);
163
+ const runs = await activeRuns(task.id);
130
164
  for (const run of runs) {
131
165
  if (run.status === 'running' && (await stopRequested(run.id)))
132
166
  this.controllers.get(task.id)?.abort('用户停止本次执行');
133
167
  }
134
168
  if (this.executions.has(task.id)) continue;
135
169
  const queued = runs.filter((r) => r.status === 'queued').at(-1);
136
- if (queued) this.launchTask(task, queued);
170
+ if (queued && this.executions.size < this.limits.concurrency)
171
+ this.launchTask(task, queued);
137
172
  }
138
173
  const ids = new Set(tasks.map((t) => t.id));
139
174
  for (const id of await listRunTaskIds(join(cronDataRoot(), 'runs')))
140
175
  if (!ids.has(id)) {
141
- for (const run of await recentRuns(id, Infinity))
176
+ for (const run of await activeRuns(id))
142
177
  if (run.status === 'queued')
143
178
  await appendRun({
144
179
  ...run,
@@ -158,7 +193,8 @@ export class Scheduler {
158
193
  status: 'interrupted',
159
194
  finishedAt: new Date().toISOString(),
160
195
  attentionReason: 'failure',
161
- error: '上次宿主退出,执行结果未知。请检查会话和产物后决定是否重跑。',
196
+ error:
197
+ '上次宿主退出,执行结果未知。请检查会话和产物后决定是否重跑。',
162
198
  });
163
199
  else if (run.status === 'queued' && !(await getTask(id)))
164
200
  await appendRun({
@@ -172,15 +208,32 @@ export class Scheduler {
172
208
  if (task) {
173
209
  const runs = await recentRuns(id, Infinity);
174
210
  const successes = runs.filter((r) => r.status === 'success').length;
175
- const failures = runs.filter((r) => r.status === 'failure' && r.owner).length;
176
- if (successes > task.stats.successCount || failures > task.stats.failureCount)
211
+ const failures = runs.filter(
212
+ (r) => r.status === 'failure' && r.owner,
213
+ ).length;
214
+ const currentPlanFinished = runs.some(
215
+ (r) =>
216
+ (r.planId ?? r.snapshot?.planId ?? r.taskId) ===
217
+ (task.planId ?? task.id) &&
218
+ (r.status === 'success' || (r.status === 'failure' && r.owner)),
219
+ );
220
+ if (
221
+ successes > task.stats.successCount ||
222
+ failures > task.stats.failureCount
223
+ )
177
224
  await updateTask(id, (t) => {
178
225
  const successCount = Math.max(t.stats.successCount, successes);
179
226
  const failureCount = Math.max(t.stats.failureCount, failures);
180
- const runCount = Math.max(t.stats.runCount, successCount + failureCount);
227
+ const runCount = Math.max(
228
+ t.stats.runCount,
229
+ successCount + failureCount,
230
+ );
181
231
  return {
182
232
  ...t,
183
- ...((t.kind === 'once' && runCount > 0) || (t.maxRuns && runCount >= t.maxRuns)
233
+ ...((t.planId === task.planId &&
234
+ t.kind === 'once' &&
235
+ currentPlanFinished) ||
236
+ (t.planId === task.planId && t.maxRuns && runCount >= t.maxRuns)
184
237
  ? { status: 'completed' as const }
185
238
  : {}),
186
239
  stats: { ...t.stats, runCount, successCount, failureCount },
@@ -193,61 +246,93 @@ export class Scheduler {
193
246
  return Date.parse(task.schedule.lastScheduledFor ?? task.createdAt);
194
247
  }
195
248
  private async processDueTask(task: CronTask, now: number): Promise<void> {
196
- if (task.status !== 'active' || task.runtime.bindingStatus !== 'bound') return;
197
- if (task.expiresAt && !task.permanent && Date.parse(task.expiresAt) <= now) return;
198
- const latest = latestScheduleRunMs(task.schedule, now - (task.schedule.jitterMs ?? 0));
199
- const base = this.lastProcessedMs(task);
200
- if (latest === null || latest <= base) return;
201
- const count = countScheduleSlots(task.schedule, base, latest);
202
- const busy =
203
- this.executions.has(task.id) ||
204
- (await recentRuns(task.id, Infinity)).some(
205
- (r) => r.status === 'queued' || r.status === 'running',
249
+ return taskTransaction(cronDataRoot(), task.id, async () => {
250
+ const current = await getTask(task.id);
251
+ if (
252
+ !current ||
253
+ (current.planId ?? current.id) !== (task.planId ?? task.id)
254
+ )
255
+ return;
256
+ task = current;
257
+ if (task.status !== 'active' || task.runtime.bindingStatus !== 'bound')
258
+ return;
259
+ if (
260
+ task.expiresAt &&
261
+ !task.permanent &&
262
+ Date.parse(task.expiresAt) <= now
263
+ )
264
+ return;
265
+ const latest = latestScheduleRunMs(
266
+ task.schedule,
267
+ now - (task.schedule.jitterMs ?? 0),
206
268
  );
207
- if (busy) {
208
- await this.markMissed(task, latest, count, 'overlap');
209
- return;
210
- }
211
- // Persist before advancing the cursor. A crash in between deduplicates by slot ID.
212
- await enqueueRun(task, undefined, new Date(latest).toISOString());
213
- if (count > 1) await this.appendMissed(task, latest, count - 1, 'offline');
214
- await updateTask(task.id, (current) => ({
215
- ...current,
216
- schedule: {
217
- ...current.schedule,
218
- lastScheduledFor: new Date(latest).toISOString(),
219
- lastFiredAt: new Date().toISOString(),
220
- },
221
- stats: {
222
- ...current.stats,
223
- skippedCount: current.stats.skippedCount + Math.max(0, count - 1),
224
- },
225
- }));
269
+ const base = this.lastProcessedMs(task);
270
+ if (latest === null || latest <= base) return;
271
+ const count = countScheduleSlots(task.schedule, base, latest);
272
+ const busy =
273
+ this.executions.has(task.id) ||
274
+ (await activeRuns(task.id)).some(
275
+ (r) => r.status === 'queued' || r.status === 'running',
276
+ );
277
+ if (busy) {
278
+ await this.markMissed(task, latest, count, 'overlap');
279
+ return;
280
+ }
281
+ // Persist before advancing the cursor. A crash in between deduplicates by slot ID.
282
+ await enqueueRun(task, undefined, new Date(latest).toISOString());
283
+ if (count > 1)
284
+ await this.appendMissed(task, latest, count - 1, 'offline');
285
+ await updateTask(task.id, (current) => ({
286
+ ...current,
287
+ schedule: {
288
+ ...current.schedule,
289
+ lastScheduledFor: new Date(latest).toISOString(),
290
+ lastFiredAt: new Date().toISOString(),
291
+ },
292
+ stats: {
293
+ ...current.stats,
294
+ skippedCount: current.stats.skippedCount + Math.max(0, count - 1),
295
+ },
296
+ }));
297
+ });
226
298
  }
227
299
  private async recordMissedTasks(): Promise<void> {
228
300
  const now = Date.now();
229
- for (const task of await listTasks()) {
230
- if (task.status !== 'active' || task.catchUp === 'latest') continue;
231
- const latest = latestScheduleRunMs(task.schedule, now - (task.schedule.jitterMs ?? 0));
232
- if (latest === null || latest <= this.lastProcessedMs(task)) continue;
233
- // Do not discard a slot already durably queued before a crash.
234
- if (
235
- (await recentRuns(task.id, Infinity)).some(
236
- (r) => r.scheduledFor === new Date(latest).toISOString(),
237
- )
238
- ) {
239
- await updateTask(task.id, (t) => ({
240
- ...t,
241
- schedule: { ...t.schedule, lastScheduledFor: new Date(latest).toISOString() },
242
- }));
243
- continue;
244
- }
245
- await this.markMissed(
246
- task,
247
- latest,
248
- countScheduleSlots(task.schedule, this.lastProcessedMs(task), latest),
249
- 'offline',
250
- );
301
+ for (const snapshot of await listTasks()) {
302
+ await taskTransaction(cronDataRoot(), snapshot.id, async () => {
303
+ const task = await getTask(snapshot.id);
304
+ if (!task || task.status !== 'active' || task.catchUp === 'latest')
305
+ return;
306
+ const latest = latestScheduleRunMs(
307
+ task.schedule,
308
+ now - (task.schedule.jitterMs ?? 0),
309
+ );
310
+ if (latest === null || latest <= this.lastProcessedMs(task)) return;
311
+ // Do not discard a slot already durably queued before a crash.
312
+ if (
313
+ (await recentRuns(task.id, Infinity)).some(
314
+ (r) =>
315
+ r.scheduledFor === new Date(latest).toISOString() &&
316
+ (r.planId ?? r.snapshot?.planId ?? task.id) ===
317
+ (task.planId ?? task.id),
318
+ )
319
+ ) {
320
+ await updateTask(task.id, (t) => ({
321
+ ...t,
322
+ schedule: {
323
+ ...t.schedule,
324
+ lastScheduledFor: new Date(latest).toISOString(),
325
+ },
326
+ }));
327
+ return;
328
+ }
329
+ await this.markMissed(
330
+ task,
331
+ latest,
332
+ countScheduleSlots(task.schedule, this.lastProcessedMs(task), latest),
333
+ 'offline',
334
+ );
335
+ });
251
336
  }
252
337
  }
253
338
  private async markMissed(
@@ -256,13 +341,25 @@ export class Scheduler {
256
341
  count: number,
257
342
  reason: 'offline' | 'overlap',
258
343
  ): Promise<void> {
259
- await this.appendMissed(task, latest, count, reason);
260
- await updateTask(task.id, (t) => ({
261
- ...t,
262
- ...(t.kind === 'once' ? { status: 'paused' as const } : {}),
263
- schedule: { ...t.schedule, lastScheduledFor: new Date(latest).toISOString() },
264
- stats: { ...t.stats, skippedCount: t.stats.skippedCount + count },
265
- }));
344
+ return taskTransaction(cronDataRoot(), task.id, async () => {
345
+ const current = await getTask(task.id);
346
+ if (
347
+ !current ||
348
+ current.planId !== task.planId ||
349
+ current.status !== 'active'
350
+ )
351
+ return;
352
+ await this.appendMissed(task, latest, count, reason);
353
+ await updateTask(task.id, (t) => ({
354
+ ...t,
355
+ ...(t.kind === 'once' ? { status: 'paused' as const } : {}),
356
+ schedule: {
357
+ ...t.schedule,
358
+ lastScheduledFor: new Date(latest).toISOString(),
359
+ },
360
+ stats: { ...t.stats, skippedCount: t.stats.skippedCount + count },
361
+ }));
362
+ });
266
363
  }
267
364
  private async appendMissed(
268
365
  task: CronTask,
@@ -277,7 +374,9 @@ export class Scheduler {
277
374
  scheduledFor: new Date(latest).toISOString(),
278
375
  detectedAt: new Date().toISOString(),
279
376
  actionPreview:
280
- task.action.type === 'prompt' ? task.action.prompt : `/workflow ${task.action.command}`,
377
+ task.action.type === 'prompt'
378
+ ? task.action.prompt
379
+ : `/workflow ${task.action.command}`,
281
380
  reason,
282
381
  missedCount: count,
283
382
  });
@@ -289,9 +388,13 @@ export class Scheduler {
289
388
  for (const t of await listTasks())
290
389
  if (t.status === 'active' && t.runtime.bindingStatus === 'bound') {
291
390
  const next = nextScheduleRunMs(t.schedule, this.lastProcessedMs(t));
292
- if (next !== null) earliest = Math.min(earliest, next + (t.schedule.jitterMs ?? 0));
391
+ if (next !== null)
392
+ earliest = Math.min(earliest, next + (t.schedule.jitterMs ?? 0));
293
393
  }
294
- this.dueTimer = setTimeout(() => this.wake(), Math.max(25, boundedWakeDelay(earliest)));
394
+ this.dueTimer = setTimeout(
395
+ () => this.wake(),
396
+ Math.max(25, boundedWakeDelay(earliest)),
397
+ );
295
398
  this.dueTimer.unref?.();
296
399
  }
297
400
  private launchTask(task: CronTask, run: CronRunRecord): void {
@@ -314,19 +417,51 @@ export class Scheduler {
314
417
  run: CronRunRecord,
315
418
  controller: AbortController,
316
419
  ): Promise<void> {
420
+ const claimed = await taskTransaction(cronDataRoot(), task.id, async () => {
421
+ if (
422
+ !(await getTask(task.id)) ||
423
+ (await stopRequested(run.id)) ||
424
+ !run.snapshot
425
+ ) {
426
+ await appendRun({
427
+ ...run,
428
+ status: 'cancelled',
429
+ finishedAt: new Date().toISOString(),
430
+ error: !run.snapshot
431
+ ? '旧队列缺少执行快照,请核实后重新运行'
432
+ : '计划已删除或执行已停止',
433
+ });
434
+ return false;
435
+ }
436
+ run = { ...run, owner: this.owner, status: 'running' };
437
+ await appendRun(run);
438
+ return true;
439
+ });
440
+ if (!claimed) return;
441
+ task = run.snapshot!;
317
442
  if (await stopRequested(run.id)) {
318
- await appendRun({ ...run, status: 'cancelled', finishedAt: new Date().toISOString() });
443
+ await appendRun({
444
+ ...run,
445
+ status: 'cancelled',
446
+ finishedAt: new Date().toISOString(),
447
+ });
319
448
  return;
320
449
  }
321
450
  if (
322
451
  task.runtime.sessionMode !== 'fresh' &&
323
- !existsSync(await resolveSessionFile(task.runtime.cwd, task.runtime.sessionId))
452
+ !existsSync(
453
+ await resolveSessionFile(task.runtime.cwd, task.runtime.sessionId),
454
+ )
324
455
  ) {
325
- await updateTask(task.id, (t) => ({
326
- ...t,
327
- status: 'paused',
328
- runtime: { ...t.runtime, bindingStatus: 'needs_binding' },
329
- }));
456
+ await updateTask(task.id, (t) =>
457
+ t.planId !== task.planId
458
+ ? t
459
+ : {
460
+ ...t,
461
+ status: 'paused',
462
+ runtime: { ...t.runtime, bindingStatus: 'needs_binding' },
463
+ },
464
+ );
330
465
  await appendMissed({
331
466
  id: `missing-${run.id}`,
332
467
  taskId: task.id,
@@ -346,36 +481,69 @@ export class Scheduler {
346
481
  });
347
482
  return;
348
483
  }
484
+ const timeout = new AbortController();
485
+ const timer = setTimeout(
486
+ () => timeout.abort('计划执行超时'),
487
+ this.limits.timeoutMs,
488
+ );
349
489
  const signal = AbortSignal.any([
350
490
  controller.signal,
491
+ timeout.signal,
351
492
  this.executionController.signal,
352
493
  ...(this.ctx.signal ? [this.ctx.signal] : []),
353
494
  ]);
354
495
  const started = Date.now();
355
- run = { ...run, owner: this.owner, status: 'running' };
356
- await appendRun(run);
496
+ this.notify(
497
+ `定时任务开始:${task.name} · ${run.id} · 会话 ${run.sessionId}`,
498
+ );
357
499
  let result = '';
358
500
  let error: string | undefined;
359
501
  let ok = false;
502
+ let outcome = executionOutcome([]);
503
+ const executionState = createSessionState();
360
504
  try {
361
505
  const response = await this.ctx.runAgentTurn({
362
506
  executionId: run.id,
363
507
  input:
364
- task.action.type === 'workflow' ? `/workflow ${task.action.command}` : task.action.prompt,
508
+ task.action.type === 'workflow'
509
+ ? `/workflow ${task.action.command}`
510
+ : task.action.prompt,
365
511
  provider: this.ctx.provider,
366
512
  cwd: run.cwd,
367
513
  sessionId: run.sessionId,
368
514
  maxTurns: task.runtime.maxTurns,
369
515
  model: task.runtime.model,
370
516
  signal,
517
+ sessionState: executionState,
371
518
  });
372
519
  result = response.result;
373
- error = response.error;
374
- ok = response.ok;
520
+ outcome = executionOutcome(response.events);
521
+ const background = backgroundCompletionFields(
522
+ executionState.backgroundTasks,
523
+ );
524
+ if (background.pendingBackground?.length) {
525
+ outcome = {
526
+ ...outcome,
527
+ completionStatus: 'delivery_incomplete',
528
+ error:
529
+ '仍有后台任务未收口;定时回合结束时将停止残留进程,请在任务内等待并核实结果',
530
+ };
531
+ }
532
+ error = response.error ?? outcome.error;
533
+ ok = response.ok && !error;
375
534
  } catch (cause) {
376
535
  error = cause instanceof Error ? cause.message : String(cause);
536
+ } finally {
537
+ clearTimeout(timer);
538
+ await disposeDetachedSessionState(executionState);
377
539
  }
378
- const status = signal.aborted ? 'cancelled' : ok ? 'success' : 'failure';
540
+ const status = timeout.signal.aborted
541
+ ? 'failure'
542
+ : signal.aborted
543
+ ? 'cancelled'
544
+ : ok
545
+ ? 'success'
546
+ : 'failure';
379
547
  const finishedAt = new Date().toISOString();
380
548
  await appendRun({
381
549
  ...run,
@@ -384,13 +552,20 @@ export class Scheduler {
384
552
  durationMs: Date.now() - started,
385
553
  result,
386
554
  resultPreview: result.slice(0, 1000),
555
+ completionStatus: outcome.completionStatus,
556
+ managedStatus: outcome.managedStatus,
387
557
  error: signal.aborted ? String(signal.reason) : error,
388
558
  ...(status === 'failure' ? { attentionReason: 'failure' as const } : {}),
389
559
  });
560
+ if (task.notifications === 'all' || status !== 'success')
561
+ this.notify(
562
+ `定时任务${status === 'success' ? '完成' : status === 'cancelled' ? '已取消' : '需要处理'}:${task.name} · ${run.id}。/cron show ${task.id} 查看结果${error ? `:${error}` : ''}`,
563
+ );
390
564
  // Persistence failures cannot re-enter the execution catch and double-count an attempt.
391
565
  await updateTask(task.id, (t) => ({
392
566
  ...t,
393
567
  ...(status !== 'cancelled' &&
568
+ (t.planId ?? t.id) === (task.planId ?? task.id) &&
394
569
  (t.kind === 'once' || (t.maxRuns && t.stats.runCount + 1 >= t.maxRuns))
395
570
  ? { status: 'completed' as const }
396
571
  : {}),
@@ -408,4 +583,12 @@ export class Scheduler {
408
583
  },
409
584
  }));
410
585
  }
586
+
587
+ private notify(message: string): void {
588
+ try {
589
+ this.ctx.notify?.(message);
590
+ } catch {
591
+ /* Presentation cannot change execution outcome. */
592
+ }
593
+ }
411
594
  }