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
@@ -1,12 +1,15 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { existsSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
- import { resolveSessionFile } from '../../../src/plugin-sdk.js';
4
+ import { resolveSessionFile, createSessionState, disposeDetachedSessionState, } from '../../../src/plugin-sdk.js';
5
5
  import { releaseSchedulerLock, tryAcquireSchedulerLock } from './lock.js';
6
- import { countScheduleSlots, latestScheduleRunMs, nextScheduleRunMs } from './scheduleEngine.js';
7
- import { appendMissed, appendRun, cronDataRoot, cronLockFile, getTask, listTasks, recentRuns, subscribeTaskChanges, updateTask, } from './store.js';
6
+ import { countScheduleSlots, latestScheduleRunMs, nextScheduleRunMs, } from './scheduleEngine.js';
7
+ import { appendMissed, activeRuns, appendRun, cronDataRoot, cronLockFile, getTask, listTasks, recentRuns, subscribeTaskChanges, updateTask, } from './store.js';
8
8
  import { listRunTaskIds } from './runs.js';
9
- import { enqueueRun, requestRun, requestStop, stopRequested } from './requests.js';
9
+ import { enqueueRun, requestRun, requestStop, stopRequested, } from './requests.js';
10
+ import { taskTransaction } from './transaction.js';
11
+ import { executionOutcome } from '../../../src/session/executionOutcome.js';
12
+ import { backgroundCompletionFields } from '../../../src/runtime/backgroundCompletion.js';
10
13
  export const RECONCILE_MS = 1_000;
11
14
  export function boundedWakeDelay(at, now = Date.now()) {
12
15
  return Math.min(RECONCILE_MS, Math.max(0, at - now));
@@ -14,6 +17,7 @@ export function boundedWakeDelay(at, now = Date.now()) {
14
17
  /** One owner per state root; all hosts submit the same durable requests. */
15
18
  export class Scheduler {
16
19
  ctx;
20
+ limits;
17
21
  dueTimer = null;
18
22
  reconcileTimer = null;
19
23
  unsubscribeStore = null;
@@ -27,8 +31,14 @@ export class Scheduler {
27
31
  stopping = false;
28
32
  tick = null;
29
33
  stopPromise = null;
30
- constructor(ctx) {
34
+ constructor(ctx, limits = { concurrency: 4, timeoutMs: 10 * 60_000 }) {
31
35
  this.ctx = ctx;
36
+ this.limits = limits;
37
+ if (!Number.isInteger(limits.concurrency) ||
38
+ limits.concurrency < 1 ||
39
+ !Number.isFinite(limits.timeoutMs) ||
40
+ limits.timeoutMs < 1)
41
+ throw new Error('无效的调度并发或超时限制');
32
42
  }
33
43
  start() {
34
44
  if (this.started)
@@ -127,7 +137,7 @@ export class Scheduler {
127
137
  const tasks = await listTasks();
128
138
  for (const task of tasks) {
129
139
  await this.processDueTask(task, Date.now());
130
- const runs = await recentRuns(task.id, Infinity);
140
+ const runs = await activeRuns(task.id);
131
141
  for (const run of runs) {
132
142
  if (run.status === 'running' && (await stopRequested(run.id)))
133
143
  this.controllers.get(task.id)?.abort('用户停止本次执行');
@@ -135,13 +145,13 @@ export class Scheduler {
135
145
  if (this.executions.has(task.id))
136
146
  continue;
137
147
  const queued = runs.filter((r) => r.status === 'queued').at(-1);
138
- if (queued)
148
+ if (queued && this.executions.size < this.limits.concurrency)
139
149
  this.launchTask(task, queued);
140
150
  }
141
151
  const ids = new Set(tasks.map((t) => t.id));
142
152
  for (const id of await listRunTaskIds(join(cronDataRoot(), 'runs')))
143
153
  if (!ids.has(id)) {
144
- for (const run of await recentRuns(id, Infinity))
154
+ for (const run of await activeRuns(id))
145
155
  if (run.status === 'queued')
146
156
  await appendRun({
147
157
  ...run,
@@ -176,14 +186,21 @@ export class Scheduler {
176
186
  const runs = await recentRuns(id, Infinity);
177
187
  const successes = runs.filter((r) => r.status === 'success').length;
178
188
  const failures = runs.filter((r) => r.status === 'failure' && r.owner).length;
179
- if (successes > task.stats.successCount || failures > task.stats.failureCount)
189
+ const currentPlanFinished = runs.some((r) => (r.planId ?? r.snapshot?.planId ?? r.taskId) ===
190
+ (task.planId ?? task.id) &&
191
+ (r.status === 'success' || (r.status === 'failure' && r.owner)));
192
+ if (successes > task.stats.successCount ||
193
+ failures > task.stats.failureCount)
180
194
  await updateTask(id, (t) => {
181
195
  const successCount = Math.max(t.stats.successCount, successes);
182
196
  const failureCount = Math.max(t.stats.failureCount, failures);
183
197
  const runCount = Math.max(t.stats.runCount, successCount + failureCount);
184
198
  return {
185
199
  ...t,
186
- ...((t.kind === 'once' && runCount > 0) || (t.maxRuns && runCount >= t.maxRuns)
200
+ ...((t.planId === task.planId &&
201
+ t.kind === 'once' &&
202
+ currentPlanFinished) ||
203
+ (t.planId === task.planId && t.maxRuns && runCount >= t.maxRuns)
187
204
  ? { status: 'completed' }
188
205
  : {}),
189
206
  stats: { ...t.stats, runCount, successCount, failureCount },
@@ -196,65 +213,92 @@ export class Scheduler {
196
213
  return Date.parse(task.schedule.lastScheduledFor ?? task.createdAt);
197
214
  }
198
215
  async processDueTask(task, now) {
199
- if (task.status !== 'active' || task.runtime.bindingStatus !== 'bound')
200
- return;
201
- if (task.expiresAt && !task.permanent && Date.parse(task.expiresAt) <= now)
202
- return;
203
- const latest = latestScheduleRunMs(task.schedule, now - (task.schedule.jitterMs ?? 0));
204
- const base = this.lastProcessedMs(task);
205
- if (latest === null || latest <= base)
206
- return;
207
- const count = countScheduleSlots(task.schedule, base, latest);
208
- const busy = this.executions.has(task.id) ||
209
- (await recentRuns(task.id, Infinity)).some((r) => r.status === 'queued' || r.status === 'running');
210
- if (busy) {
211
- await this.markMissed(task, latest, count, 'overlap');
212
- return;
213
- }
214
- // Persist before advancing the cursor. A crash in between deduplicates by slot ID.
215
- await enqueueRun(task, undefined, new Date(latest).toISOString());
216
- if (count > 1)
217
- await this.appendMissed(task, latest, count - 1, 'offline');
218
- await updateTask(task.id, (current) => ({
219
- ...current,
220
- schedule: {
221
- ...current.schedule,
222
- lastScheduledFor: new Date(latest).toISOString(),
223
- lastFiredAt: new Date().toISOString(),
224
- },
225
- stats: {
226
- ...current.stats,
227
- skippedCount: current.stats.skippedCount + Math.max(0, count - 1),
228
- },
229
- }));
216
+ return taskTransaction(cronDataRoot(), task.id, async () => {
217
+ const current = await getTask(task.id);
218
+ if (!current ||
219
+ (current.planId ?? current.id) !== (task.planId ?? task.id))
220
+ return;
221
+ task = current;
222
+ if (task.status !== 'active' || task.runtime.bindingStatus !== 'bound')
223
+ return;
224
+ if (task.expiresAt &&
225
+ !task.permanent &&
226
+ Date.parse(task.expiresAt) <= now)
227
+ return;
228
+ const latest = latestScheduleRunMs(task.schedule, now - (task.schedule.jitterMs ?? 0));
229
+ const base = this.lastProcessedMs(task);
230
+ if (latest === null || latest <= base)
231
+ return;
232
+ const count = countScheduleSlots(task.schedule, base, latest);
233
+ const busy = this.executions.has(task.id) ||
234
+ (await activeRuns(task.id)).some((r) => r.status === 'queued' || r.status === 'running');
235
+ if (busy) {
236
+ await this.markMissed(task, latest, count, 'overlap');
237
+ return;
238
+ }
239
+ // Persist before advancing the cursor. A crash in between deduplicates by slot ID.
240
+ await enqueueRun(task, undefined, new Date(latest).toISOString());
241
+ if (count > 1)
242
+ await this.appendMissed(task, latest, count - 1, 'offline');
243
+ await updateTask(task.id, (current) => ({
244
+ ...current,
245
+ schedule: {
246
+ ...current.schedule,
247
+ lastScheduledFor: new Date(latest).toISOString(),
248
+ lastFiredAt: new Date().toISOString(),
249
+ },
250
+ stats: {
251
+ ...current.stats,
252
+ skippedCount: current.stats.skippedCount + Math.max(0, count - 1),
253
+ },
254
+ }));
255
+ });
230
256
  }
231
257
  async recordMissedTasks() {
232
258
  const now = Date.now();
233
- for (const task of await listTasks()) {
234
- if (task.status !== 'active' || task.catchUp === 'latest')
235
- continue;
236
- const latest = latestScheduleRunMs(task.schedule, now - (task.schedule.jitterMs ?? 0));
237
- if (latest === null || latest <= this.lastProcessedMs(task))
238
- continue;
239
- // Do not discard a slot already durably queued before a crash.
240
- if ((await recentRuns(task.id, Infinity)).some((r) => r.scheduledFor === new Date(latest).toISOString())) {
241
- await updateTask(task.id, (t) => ({
242
- ...t,
243
- schedule: { ...t.schedule, lastScheduledFor: new Date(latest).toISOString() },
244
- }));
245
- continue;
246
- }
247
- await this.markMissed(task, latest, countScheduleSlots(task.schedule, this.lastProcessedMs(task), latest), 'offline');
259
+ for (const snapshot of await listTasks()) {
260
+ await taskTransaction(cronDataRoot(), snapshot.id, async () => {
261
+ const task = await getTask(snapshot.id);
262
+ if (!task || task.status !== 'active' || task.catchUp === 'latest')
263
+ return;
264
+ const latest = latestScheduleRunMs(task.schedule, now - (task.schedule.jitterMs ?? 0));
265
+ if (latest === null || latest <= this.lastProcessedMs(task))
266
+ return;
267
+ // Do not discard a slot already durably queued before a crash.
268
+ if ((await recentRuns(task.id, Infinity)).some((r) => r.scheduledFor === new Date(latest).toISOString() &&
269
+ (r.planId ?? r.snapshot?.planId ?? task.id) ===
270
+ (task.planId ?? task.id))) {
271
+ await updateTask(task.id, (t) => ({
272
+ ...t,
273
+ schedule: {
274
+ ...t.schedule,
275
+ lastScheduledFor: new Date(latest).toISOString(),
276
+ },
277
+ }));
278
+ return;
279
+ }
280
+ await this.markMissed(task, latest, countScheduleSlots(task.schedule, this.lastProcessedMs(task), latest), 'offline');
281
+ });
248
282
  }
249
283
  }
250
284
  async markMissed(task, latest, count, reason) {
251
- await this.appendMissed(task, latest, count, reason);
252
- await updateTask(task.id, (t) => ({
253
- ...t,
254
- ...(t.kind === 'once' ? { status: 'paused' } : {}),
255
- schedule: { ...t.schedule, lastScheduledFor: new Date(latest).toISOString() },
256
- stats: { ...t.stats, skippedCount: t.stats.skippedCount + count },
257
- }));
285
+ return taskTransaction(cronDataRoot(), task.id, async () => {
286
+ const current = await getTask(task.id);
287
+ if (!current ||
288
+ current.planId !== task.planId ||
289
+ current.status !== 'active')
290
+ return;
291
+ await this.appendMissed(task, latest, count, reason);
292
+ await updateTask(task.id, (t) => ({
293
+ ...t,
294
+ ...(t.kind === 'once' ? { status: 'paused' } : {}),
295
+ schedule: {
296
+ ...t.schedule,
297
+ lastScheduledFor: new Date(latest).toISOString(),
298
+ },
299
+ stats: { ...t.stats, skippedCount: t.stats.skippedCount + count },
300
+ }));
301
+ });
258
302
  }
259
303
  async appendMissed(task, latest, count, reason) {
260
304
  await appendMissed({
@@ -263,7 +307,9 @@ export class Scheduler {
263
307
  taskName: task.name,
264
308
  scheduledFor: new Date(latest).toISOString(),
265
309
  detectedAt: new Date().toISOString(),
266
- actionPreview: task.action.type === 'prompt' ? task.action.prompt : `/workflow ${task.action.command}`,
310
+ actionPreview: task.action.type === 'prompt'
311
+ ? task.action.prompt
312
+ : `/workflow ${task.action.command}`,
267
313
  reason,
268
314
  missedCount: count,
269
315
  });
@@ -299,17 +345,44 @@ export class Scheduler {
299
345
  this.executions.set(task.id, promise);
300
346
  }
301
347
  async runTask(task, run, controller) {
348
+ const claimed = await taskTransaction(cronDataRoot(), task.id, async () => {
349
+ if (!(await getTask(task.id)) ||
350
+ (await stopRequested(run.id)) ||
351
+ !run.snapshot) {
352
+ await appendRun({
353
+ ...run,
354
+ status: 'cancelled',
355
+ finishedAt: new Date().toISOString(),
356
+ error: !run.snapshot
357
+ ? '旧队列缺少执行快照,请核实后重新运行'
358
+ : '计划已删除或执行已停止',
359
+ });
360
+ return false;
361
+ }
362
+ run = { ...run, owner: this.owner, status: 'running' };
363
+ await appendRun(run);
364
+ return true;
365
+ });
366
+ if (!claimed)
367
+ return;
368
+ task = run.snapshot;
302
369
  if (await stopRequested(run.id)) {
303
- await appendRun({ ...run, status: 'cancelled', finishedAt: new Date().toISOString() });
370
+ await appendRun({
371
+ ...run,
372
+ status: 'cancelled',
373
+ finishedAt: new Date().toISOString(),
374
+ });
304
375
  return;
305
376
  }
306
377
  if (task.runtime.sessionMode !== 'fresh' &&
307
378
  !existsSync(await resolveSessionFile(task.runtime.cwd, task.runtime.sessionId))) {
308
- await updateTask(task.id, (t) => ({
309
- ...t,
310
- status: 'paused',
311
- runtime: { ...t.runtime, bindingStatus: 'needs_binding' },
312
- }));
379
+ await updateTask(task.id, (t) => t.planId !== task.planId
380
+ ? t
381
+ : {
382
+ ...t,
383
+ status: 'paused',
384
+ runtime: { ...t.runtime, bindingStatus: 'needs_binding' },
385
+ });
313
386
  await appendMissed({
314
387
  id: `missing-${run.id}`,
315
388
  taskId: task.id,
@@ -329,36 +402,62 @@ export class Scheduler {
329
402
  });
330
403
  return;
331
404
  }
405
+ const timeout = new AbortController();
406
+ const timer = setTimeout(() => timeout.abort('计划执行超时'), this.limits.timeoutMs);
332
407
  const signal = AbortSignal.any([
333
408
  controller.signal,
409
+ timeout.signal,
334
410
  this.executionController.signal,
335
411
  ...(this.ctx.signal ? [this.ctx.signal] : []),
336
412
  ]);
337
413
  const started = Date.now();
338
- run = { ...run, owner: this.owner, status: 'running' };
339
- await appendRun(run);
414
+ this.notify(`定时任务开始:${task.name} · ${run.id} · 会话 ${run.sessionId}`);
340
415
  let result = '';
341
416
  let error;
342
417
  let ok = false;
418
+ let outcome = executionOutcome([]);
419
+ const executionState = createSessionState();
343
420
  try {
344
421
  const response = await this.ctx.runAgentTurn({
345
422
  executionId: run.id,
346
- input: task.action.type === 'workflow' ? `/workflow ${task.action.command}` : task.action.prompt,
423
+ input: task.action.type === 'workflow'
424
+ ? `/workflow ${task.action.command}`
425
+ : task.action.prompt,
347
426
  provider: this.ctx.provider,
348
427
  cwd: run.cwd,
349
428
  sessionId: run.sessionId,
350
429
  maxTurns: task.runtime.maxTurns,
351
430
  model: task.runtime.model,
352
431
  signal,
432
+ sessionState: executionState,
353
433
  });
354
434
  result = response.result;
355
- error = response.error;
356
- ok = response.ok;
435
+ outcome = executionOutcome(response.events);
436
+ const background = backgroundCompletionFields(executionState.backgroundTasks);
437
+ if (background.pendingBackground?.length) {
438
+ outcome = {
439
+ ...outcome,
440
+ completionStatus: 'delivery_incomplete',
441
+ error: '仍有后台任务未收口;定时回合结束时将停止残留进程,请在任务内等待并核实结果',
442
+ };
443
+ }
444
+ error = response.error ?? outcome.error;
445
+ ok = response.ok && !error;
357
446
  }
358
447
  catch (cause) {
359
448
  error = cause instanceof Error ? cause.message : String(cause);
360
449
  }
361
- const status = signal.aborted ? 'cancelled' : ok ? 'success' : 'failure';
450
+ finally {
451
+ clearTimeout(timer);
452
+ await disposeDetachedSessionState(executionState);
453
+ }
454
+ const status = timeout.signal.aborted
455
+ ? 'failure'
456
+ : signal.aborted
457
+ ? 'cancelled'
458
+ : ok
459
+ ? 'success'
460
+ : 'failure';
362
461
  const finishedAt = new Date().toISOString();
363
462
  await appendRun({
364
463
  ...run,
@@ -367,13 +466,18 @@ export class Scheduler {
367
466
  durationMs: Date.now() - started,
368
467
  result,
369
468
  resultPreview: result.slice(0, 1000),
469
+ completionStatus: outcome.completionStatus,
470
+ managedStatus: outcome.managedStatus,
370
471
  error: signal.aborted ? String(signal.reason) : error,
371
472
  ...(status === 'failure' ? { attentionReason: 'failure' } : {}),
372
473
  });
474
+ if (task.notifications === 'all' || status !== 'success')
475
+ this.notify(`定时任务${status === 'success' ? '完成' : status === 'cancelled' ? '已取消' : '需要处理'}:${task.name} · ${run.id}。/cron show ${task.id} 查看结果${error ? `:${error}` : ''}`);
373
476
  // Persistence failures cannot re-enter the execution catch and double-count an attempt.
374
477
  await updateTask(task.id, (t) => ({
375
478
  ...t,
376
479
  ...(status !== 'cancelled' &&
480
+ (t.planId ?? t.id) === (task.planId ?? task.id) &&
377
481
  (t.kind === 'once' || (t.maxRuns && t.stats.runCount + 1 >= t.maxRuns))
378
482
  ? { status: 'completed' }
379
483
  : {}),
@@ -391,4 +495,12 @@ export class Scheduler {
391
495
  },
392
496
  }));
393
497
  }
498
+ notify(message) {
499
+ try {
500
+ this.ctx.notify?.(message);
501
+ }
502
+ catch {
503
+ /* Presentation cannot change execution outcome. */
504
+ }
505
+ }
394
506
  }