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.
- package/README.md +16 -3
- package/package.json +1 -1
- package/plugins/cron-runner/README.md +23 -0
- package/plugins/cron-runner/commands/cron.md +7 -1
- package/plugins/cron-runner/plugin.js +9 -2
- package/plugins/cron-runner/plugin.ts +10 -2
- package/plugins/cron-runner/src/commands.js +112 -25
- package/plugins/cron-runner/src/commands.ts +154 -33
- package/plugins/cron-runner/src/contract.js +70 -0
- package/plugins/cron-runner/src/contract.ts +70 -0
- package/plugins/cron-runner/src/requests.js +22 -13
- package/plugins/cron-runner/src/requests.ts +34 -14
- package/plugins/cron-runner/src/runs.js +63 -10
- package/plugins/cron-runner/src/runs.ts +107 -15
- package/plugins/cron-runner/src/scheduler.js +188 -76
- package/plugins/cron-runner/src/scheduler.ts +277 -94
- package/plugins/cron-runner/src/schema.js +52 -17
- package/plugins/cron-runner/src/schema.ts +73 -22
- package/plugins/cron-runner/src/service.js +29 -8
- package/plugins/cron-runner/src/service.ts +71 -18
- package/plugins/cron-runner/src/store.js +92 -30
- package/plugins/cron-runner/src/store.ts +156 -53
- package/plugins/cron-runner/src/transaction.js +24 -0
- package/plugins/cron-runner/src/transaction.ts +36 -0
- package/plugins/cron-runner/src/types.ts +30 -4
- package/plugins/cron-runner/test/lifecycle.test.ts +419 -0
- package/plugins/cron-runner/test/plugin-integration.test.ts +3 -2
- package/plugins/cron-runner/test/reliability.test.ts +2 -2
- package/plugins/cron-runner/test/store-and-scheduler.test.ts +9 -7
- package/plugins/workflow-runner/plugin.js +1 -0
- package/plugins/workflow-runner/plugin.ts +1 -0
- package/plugins/workflow-runner/src/index.js +1 -0
- package/plugins/workflow-runner/src/index.ts +2 -0
- package/plugins/workflow-runner/src/runner.js +6 -1
- package/plugins/workflow-runner/src/runner.ts +5 -1
- package/plugins/workflow-runner/src/types.ts +1 -0
- package/plugins/workflow-runner/test/api.test.ts +1 -0
- package/plugins/workflow-runner/test/apiCapabilities.test.ts +4 -0
- package/plugins/workflow-runner/test/apiConcurrencyGate.test.ts +1 -0
- package/plugins/workflow-runner/test/childWorkflow.test.ts +19 -0
- package/plugins/workflow-runner/test/embeddedExecution.test.ts +23 -3
- package/src/advisor/README.md +17 -6
- package/src/advisor/advisorNudge.js +23 -3
- package/src/advisor/advisorNudge.ts +20 -3
- package/src/advisor/deliveryReview.js +9 -2
- package/src/advisor/deliveryReview.ts +10 -2
- package/src/cli/args.js +1 -0
- package/src/cli/args.ts +1 -0
- package/src/cli/headlessTurn.js +143 -0
- package/src/cli/headlessTurn.ts +187 -0
- package/src/cli/lifecycle.js +52 -0
- package/src/cli/lifecycle.ts +59 -0
- package/src/cli/print.js +91 -240
- package/src/cli/print.ts +99 -301
- package/src/cli/quickModelSetup.js +3 -0
- package/src/cli/quickModelSetup.tsx +3 -0
- package/src/cli/streamJson.js +244 -334
- package/src/cli/streamJson.ts +248 -416
- package/src/cli/wizards/contextAdvisorWizard.js +0 -7
- package/src/cli/wizards/contextAdvisorWizard.tsx +0 -11
- package/src/cli/wizards/providerPresets.js +25 -14
- package/src/cli/wizards/providerPresets.ts +25 -14
- package/src/cli/wizards/providerWizard.js +29 -11
- package/src/cli/wizards/providerWizard.tsx +29 -11
- package/src/config/configDefaults.js +2 -2
- package/src/config/configDefaults.ts +2 -2
- package/src/config/configDiagnostics.js +7 -3
- package/src/config/configDiagnostics.ts +6 -3
- package/src/config/configFile.ts +1 -1
- package/src/context/compact.js +40 -10
- package/src/context/compact.ts +51 -12
- package/src/context/compactResources.js +39 -0
- package/src/context/compactResources.ts +35 -0
- package/src/context/manualCompact.js +20 -0
- package/src/context/manualCompact.ts +28 -0
- package/src/llm/client.js +4 -0
- package/src/llm/client.ts +4 -0
- package/src/llm/messageProvenance.js +1 -1
- package/src/llm/messageProvenance.ts +1 -1
- package/src/loop/README.md +4 -2
- package/src/loop/deliveryIntent.js +3 -2
- package/src/loop/deliveryIntent.ts +4 -2
- package/src/loop/messages.js +1 -0
- package/src/loop/messages.ts +1 -0
- package/src/loop/options.ts +2 -0
- package/src/loop.js +10 -2
- package/src/loop.ts +9 -2
- package/src/main.js +40 -45
- package/src/main.tsx +33 -52
- package/src/plugin-sdk.js +1 -1
- package/src/plugin-sdk.ts +1 -1
- package/src/plugins/artifactDelivery.js +76 -0
- package/src/plugins/artifactDelivery.ts +76 -0
- package/src/plugins/pluginApi.ts +4 -0
- package/src/plugins/pluginRunner.js +2 -0
- package/src/plugins/pluginRunner.ts +3 -0
- package/src/prompts/delegation.js +2 -2
- package/src/prompts/delegation.ts +2 -2
- package/src/prompts/policyRegistry.js +7 -5
- package/src/prompts/policyRegistry.ts +7 -5
- package/src/prompts/promptAssembly.js +2 -2
- package/src/prompts/promptAssembly.ts +2 -2
- package/src/runtime/requestIntent.js +86 -0
- package/src/runtime/requestIntent.ts +66 -0
- package/src/runtime/systemEvents.js +10 -1
- package/src/runtime/systemEvents.ts +9 -1
- package/src/session/commandTranscript.js +76 -0
- package/src/session/commandTranscript.ts +77 -0
- package/src/session/executionOutcome.js +25 -0
- package/src/session/executionOutcome.ts +34 -0
- package/src/session/runAgentTurn.js +8 -1
- package/src/session/runAgentTurn.ts +10 -1
- package/src/session/runTurn.js +40 -15
- package/src/session/runTurn.ts +38 -12
- package/src/session/sessionState.js +7 -2
- package/src/session/sessionState.ts +7 -2
- package/src/team/onlineToolContract.js +1 -0
- package/src/team/onlineToolContract.ts +1 -0
- package/src/tools/advisor/advisor.js +73 -30
- package/src/tools/advisor/advisor.ts +73 -33
- package/src/tools/advisor/advisorCoordination.js +44 -0
- package/src/tools/advisor/advisorCoordination.ts +45 -0
- package/src/tools/advisor/advisorDescription.js +1 -1
- package/src/tools/advisor/advisorDescription.ts +1 -1
- package/src/tools/agent/README.md +2 -0
- package/src/tools/agent/agent.js +7 -3
- package/src/tools/agent/agent.ts +7 -3
- package/src/tools/agent/agentHandoff.js +2 -1
- package/src/tools/agent/agentHandoff.ts +2 -1
- package/src/tools/agent/agentTaskService.js +26 -5
- package/src/tools/agent/agentTaskService.ts +25 -5
- package/src/tools/agent/agentTypes.js +2 -2
- package/src/tools/agent/agentTypes.ts +2 -2
- package/src/tools/agent/baselineAttach.js +14 -7
- package/src/tools/agent/baselineAttach.ts +14 -7
- package/src/tools/applypatch/applyPatch.js +39 -13
- package/src/tools/applypatch/applyPatch.ts +35 -15
- package/src/tools/bash/bash.js +3 -0
- package/src/tools/bash/bash.ts +3 -0
- package/src/tools/capabilities.js +1 -0
- package/src/tools/capabilities.ts +1 -0
- package/src/tools/download/download.js +147 -11
- package/src/tools/download/download.ts +193 -17
- package/src/tools/edit/edit.js +4 -4
- package/src/tools/edit/edit.ts +4 -4
- package/src/tools/edit/multi-edit.js +2 -2
- package/src/tools/edit/multi-edit.ts +2 -2
- package/src/tools/index.js +2 -0
- package/src/tools/index.ts +2 -0
- package/src/tools/powershell/powershell.js +2 -0
- package/src/tools/powershell/powershell.ts +2 -0
- package/src/tools/schedule/schedule.js +184 -0
- package/src/tools/schedule/schedule.ts +214 -0
- package/src/tools/shared/fileUtils.js +16 -6
- package/src/tools/shared/fileUtils.ts +15 -6
- package/src/tools/tasks/backgroundTaskService.js +108 -12
- package/src/tools/tasks/backgroundTaskService.ts +106 -14
- package/src/tools/tasks/taskOutput.js +15 -5
- package/src/tools/tasks/taskOutput.ts +13 -5
- package/src/tools/tasks/taskStop.js +2 -2
- package/src/tools/tasks/taskStop.ts +2 -2
- package/src/tools/toolPromptGuides.js +4 -3
- package/src/tools/toolPromptGuides.ts +4 -3
- package/src/tools/webfetch/webfetch.js +1 -1
- package/src/tools/webfetch/webfetch.ts +1 -1
- package/src/types.ts +6 -0
- package/src/ui/App.js +3 -1
- package/src/ui/App.tsx +2 -0
- package/src/ui/InputBox.js +2 -2
- package/src/ui/InputBox.tsx +2 -2
- package/src/ui/LiveArea.js +6 -1
- package/src/ui/LiveArea.tsx +6 -1
- package/src/ui/MessageList.js +2 -0
- package/src/ui/MessageList.tsx +2 -0
- package/src/ui/README.md +8 -2
- package/src/ui/activityPresentation.js +23 -3
- package/src/ui/activityPresentation.ts +22 -3
- package/src/ui/backgroundWake.js +20 -4
- package/src/ui/backgroundWake.ts +19 -4
- package/src/ui/commandTranscript.js +2 -69
- package/src/ui/commandTranscript.ts +2 -71
- package/src/ui/hooks/useBackgroundAgents.js +33 -0
- package/src/ui/hooks/useBackgroundAgents.ts +36 -0
- package/src/ui/hooks/useChat.js +46 -25
- package/src/ui/hooks/useChat.ts +36 -23
- package/src/web/protocol.ts +5 -2
- package/src/cli/wizards/advisorWizard.js +0 -152
- package/src/cli/wizards/advisorWizard.tsx +0 -203
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { constants, copyFile, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { constants, copyFile, mkdir, readFile, rename, writeFile, } from 'node:fs/promises';
|
|
3
3
|
import { agentStateDir } from '../../../src/plugin-sdk.js';
|
|
4
4
|
import { dirname, join } from 'node:path';
|
|
5
5
|
import { cronToHuman } from './cronTime.js';
|
|
@@ -7,6 +7,8 @@ import { intervalToHuman, nextScheduleRunMs } from './scheduleEngine.js';
|
|
|
7
7
|
import { schedulerLockFile, withStoreLock } from './lock.js';
|
|
8
8
|
import { appendMissed as appendMissedRecord, appendRun as appendRunRecord, listMissed as listMissedRecords, markMissedRead as markMissedRecordsRead, markRunsRead as markRunRecordsRead, recentRuns as readRecentRuns, } from './runs.js';
|
|
9
9
|
import { normalizeTask } from './schema.js';
|
|
10
|
+
import { taskTransaction, outsideTaskTransaction } from './transaction.js';
|
|
11
|
+
import { requestStop } from './requests.js';
|
|
10
12
|
function root() {
|
|
11
13
|
return process.env.MINIMAL_AGENT_CRON_RUNNER_HOME
|
|
12
14
|
? join(process.env.MINIMAL_AGENT_CRON_RUNNER_HOME, 'cron-runner')
|
|
@@ -24,8 +26,16 @@ function missedFile() {
|
|
|
24
26
|
let mutationQueue = Promise.resolve();
|
|
25
27
|
const taskChangeListeners = new Set();
|
|
26
28
|
function notifyTaskChanges() {
|
|
27
|
-
|
|
28
|
-
listener
|
|
29
|
+
outsideTaskTransaction(() => {
|
|
30
|
+
for (const listener of taskChangeListeners) {
|
|
31
|
+
try {
|
|
32
|
+
listener();
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
/* Notifications cannot roll back a durable mutation. */
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
});
|
|
29
39
|
}
|
|
30
40
|
export function subscribeTaskChanges(listener) {
|
|
31
41
|
taskChangeListeners.add(listener);
|
|
@@ -64,7 +74,8 @@ export async function migrateCronTasks() {
|
|
|
64
74
|
!('type' in task.schedule) ||
|
|
65
75
|
!task.runtime?.bindingStatus ||
|
|
66
76
|
(task.version !== 2 &&
|
|
67
|
-
(task.runtime.sessionMode === 'fresh' ||
|
|
77
|
+
(task.runtime.sessionMode === 'fresh' ||
|
|
78
|
+
task.runtime.sessionId?.startsWith('cron-'))));
|
|
68
79
|
});
|
|
69
80
|
if (!needsMigration)
|
|
70
81
|
return false;
|
|
@@ -134,7 +145,10 @@ export async function upsertTask(task, ifAbsent = false) {
|
|
|
134
145
|
const idx = tasks.findIndex((t) => t.id === task.id);
|
|
135
146
|
if (idx >= 0 && ifAbsent)
|
|
136
147
|
return tasks[idx];
|
|
137
|
-
const saved = refreshNextRun({
|
|
148
|
+
const saved = refreshNextRun({
|
|
149
|
+
...task,
|
|
150
|
+
updatedAt: new Date().toISOString(),
|
|
151
|
+
});
|
|
138
152
|
if (idx >= 0)
|
|
139
153
|
tasks[idx] = saved;
|
|
140
154
|
else
|
|
@@ -145,7 +159,7 @@ export async function upsertTask(task, ifAbsent = false) {
|
|
|
145
159
|
});
|
|
146
160
|
}
|
|
147
161
|
export async function updateTask(id, updater) {
|
|
148
|
-
return await enqueueMutation(async () => {
|
|
162
|
+
return await taskTransaction(root(), id, () => enqueueMutation(async () => {
|
|
149
163
|
const tasks = await readTasks();
|
|
150
164
|
const idx = tasks.findIndex((task) => task.id === id);
|
|
151
165
|
if (idx < 0)
|
|
@@ -159,17 +173,20 @@ export async function updateTask(id, updater) {
|
|
|
159
173
|
await writeTasksFile(tasks);
|
|
160
174
|
notifyTaskChanges();
|
|
161
175
|
return saved;
|
|
162
|
-
});
|
|
176
|
+
}));
|
|
163
177
|
}
|
|
164
178
|
export async function deleteTask(id) {
|
|
165
|
-
return await
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
179
|
+
return await taskTransaction(root(), id, async () => {
|
|
180
|
+
await requestStop(id);
|
|
181
|
+
return enqueueMutation(async () => {
|
|
182
|
+
const tasks = await readTasks();
|
|
183
|
+
const next = tasks.filter((t) => t.id !== id);
|
|
184
|
+
if (next.length === tasks.length)
|
|
185
|
+
return false;
|
|
186
|
+
await writeTasksFile(next);
|
|
187
|
+
notifyTaskChanges();
|
|
188
|
+
return true;
|
|
189
|
+
});
|
|
173
190
|
});
|
|
174
191
|
}
|
|
175
192
|
export async function getTask(idOrPrefix) {
|
|
@@ -188,6 +205,9 @@ export async function appendRun(record) {
|
|
|
188
205
|
export async function recentRuns(taskId, limit = 5) {
|
|
189
206
|
return await readRecentRuns(runsDir(), taskId, limit);
|
|
190
207
|
}
|
|
208
|
+
export async function activeRuns(taskId) {
|
|
209
|
+
return readRecentRuns(runsDir(), taskId, Infinity, true);
|
|
210
|
+
}
|
|
191
211
|
export async function markRunsRead(taskId) {
|
|
192
212
|
await markRunRecordsRead(runsDir(), taskId);
|
|
193
213
|
}
|
|
@@ -226,6 +246,7 @@ export function createTask(input) {
|
|
|
226
246
|
return refreshNextRun({
|
|
227
247
|
version: 2,
|
|
228
248
|
revision: 0,
|
|
249
|
+
planId: randomUUID(),
|
|
229
250
|
catchUp: input.catchUp ?? 'skip',
|
|
230
251
|
notifications: input.notifications ?? 'all',
|
|
231
252
|
id,
|
|
@@ -243,7 +264,9 @@ export function createTask(input) {
|
|
|
243
264
|
environment: 'project',
|
|
244
265
|
sessionId: input.sessionId ?? 'default',
|
|
245
266
|
sessionMode: input.sessionMode ?? 'persistent',
|
|
246
|
-
bindingStatus: input.sessionMode === 'fresh' ||
|
|
267
|
+
bindingStatus: input.sessionMode === 'fresh' ||
|
|
268
|
+
!input.sessionId ||
|
|
269
|
+
!input.sessionId.startsWith('cron-')
|
|
247
270
|
? 'bound'
|
|
248
271
|
: 'needs_binding',
|
|
249
272
|
...(input.model ? { model: input.model } : {}),
|
|
@@ -261,7 +284,9 @@ export function createTask(input) {
|
|
|
261
284
|
}
|
|
262
285
|
export function refreshNextRun(task, fromMs = Date.now()) {
|
|
263
286
|
const expired = task.expiresAt && !task.permanent && Date.parse(task.expiresAt) <= fromMs;
|
|
264
|
-
const next = task.status === 'active' && !expired
|
|
287
|
+
const next = task.status === 'active' && !expired
|
|
288
|
+
? nextScheduleRunMs(task.schedule, fromMs)
|
|
289
|
+
: null;
|
|
265
290
|
return {
|
|
266
291
|
...task,
|
|
267
292
|
...(expired ? { status: 'completed' } : {}),
|
|
@@ -273,18 +298,25 @@ export function refreshNextRun(task, fromMs = Date.now()) {
|
|
|
273
298
|
? cronToHuman(task.schedule.cron)
|
|
274
299
|
: intervalToHuman(task.schedule.intervalMs),
|
|
275
300
|
jitterMs: typeof task.schedule.jitterMs === 'number' ? task.schedule.jitterMs : 0,
|
|
276
|
-
...(next
|
|
301
|
+
...(next
|
|
302
|
+
? { nextRunAt: new Date(next).toISOString() }
|
|
303
|
+
: { nextRunAt: undefined }),
|
|
277
304
|
},
|
|
278
305
|
};
|
|
279
306
|
}
|
|
280
307
|
/** Update only user-editable fields while preserving scheduler cursors, stats and creation time. */
|
|
281
308
|
export async function patchTask(patch) {
|
|
282
309
|
return await updateTask(patch.id, (current) => {
|
|
283
|
-
if (patch.expectedRevision !== undefined &&
|
|
310
|
+
if (patch.expectedRevision !== undefined &&
|
|
311
|
+
patch.expectedRevision !== (current.revision ?? 0))
|
|
284
312
|
throw new Error('任务已被其他操作更新,请刷新后再编辑。');
|
|
285
313
|
const nextSchedule = patch.schedule
|
|
286
314
|
? patch.schedule.type === 'once'
|
|
287
|
-
? {
|
|
315
|
+
? {
|
|
316
|
+
type: 'once',
|
|
317
|
+
at: patch.schedule.at,
|
|
318
|
+
human: `一次 · ${patch.schedule.at}`,
|
|
319
|
+
}
|
|
288
320
|
: patch.schedule.type === 'cron'
|
|
289
321
|
? {
|
|
290
322
|
...current.schedule,
|
|
@@ -311,23 +343,42 @@ export async function patchTask(patch) {
|
|
|
311
343
|
...current.runtime,
|
|
312
344
|
...patch.runtime,
|
|
313
345
|
sessionMode: patch.runtime.sessionMode ?? current.runtime.sessionMode,
|
|
314
|
-
bindingStatus: patch.runtime.sessionId &&
|
|
346
|
+
bindingStatus: patch.runtime.sessionId &&
|
|
347
|
+
!patch.runtime.sessionId.startsWith('cron-')
|
|
315
348
|
? 'bound'
|
|
316
349
|
: current.runtime.bindingStatus,
|
|
317
350
|
}
|
|
318
|
-
: current.runtime;
|
|
351
|
+
: { ...current.runtime };
|
|
319
352
|
if (runtime.sessionMode === 'fresh')
|
|
320
353
|
runtime.bindingStatus = 'bound';
|
|
321
354
|
if (patch.clearMaxTurns)
|
|
322
355
|
runtime.maxTurns = undefined;
|
|
323
|
-
if ((patch.status ?? current.status) === 'active' &&
|
|
356
|
+
if ((patch.status ?? current.status) === 'active' &&
|
|
357
|
+
runtime.bindingStatus !== 'bound')
|
|
324
358
|
throw new Error('请先重新绑定工作目录会话');
|
|
325
359
|
const identity = (schedule) => JSON.stringify(schedule.type === 'once'
|
|
326
360
|
? [schedule.type, schedule.at]
|
|
327
361
|
: schedule.type === 'cron'
|
|
328
|
-
? [
|
|
329
|
-
|
|
362
|
+
? [
|
|
363
|
+
schedule.type,
|
|
364
|
+
schedule.cron,
|
|
365
|
+
schedule.timezone,
|
|
366
|
+
schedule.jitterMs ?? 0,
|
|
367
|
+
]
|
|
368
|
+
: [
|
|
369
|
+
schedule.type,
|
|
370
|
+
schedule.intervalMs,
|
|
371
|
+
schedule.anchorAt,
|
|
372
|
+
schedule.jitterMs ?? 0,
|
|
373
|
+
]);
|
|
330
374
|
const changed = identity(nextSchedule) !== identity(current.schedule);
|
|
375
|
+
const executionChanged = changed ||
|
|
376
|
+
(patch.action !== undefined &&
|
|
377
|
+
JSON.stringify(patch.action) !== JSON.stringify(current.action)) ||
|
|
378
|
+
JSON.stringify(runtime) !== JSON.stringify(current.runtime) ||
|
|
379
|
+
(patch.kind !== undefined && patch.kind !== current.kind) ||
|
|
380
|
+
(patch.maxRuns !== undefined && patch.maxRuns !== current.maxRuns) ||
|
|
381
|
+
patch.clearMaxRuns;
|
|
331
382
|
const reactivating = patch.status === 'active' && current.status !== 'active';
|
|
332
383
|
if (nextSchedule.type === 'once' &&
|
|
333
384
|
(patch.status ?? current.status) === 'active' &&
|
|
@@ -344,6 +395,7 @@ export async function patchTask(patch) {
|
|
|
344
395
|
return {
|
|
345
396
|
...current,
|
|
346
397
|
version: 2,
|
|
398
|
+
planId: executionChanged ? randomUUID() : (current.planId ?? current.id),
|
|
347
399
|
...(patch.catchUp ? { catchUp: patch.catchUp } : {}),
|
|
348
400
|
...(patch.notifications ? { notifications: patch.notifications } : {}),
|
|
349
401
|
...(patch.name !== undefined ? { name: patch.name.trim() } : {}),
|
|
@@ -353,14 +405,24 @@ export async function patchTask(patch) {
|
|
|
353
405
|
: { description: undefined }
|
|
354
406
|
: {}),
|
|
355
407
|
...(patch.status !== undefined ? { status: patch.status } : {}),
|
|
356
|
-
...(patch.schedule
|
|
357
|
-
? {
|
|
408
|
+
...(patch.schedule
|
|
409
|
+
? {
|
|
410
|
+
kind: patch.schedule.type === 'once'
|
|
411
|
+
? 'once'
|
|
412
|
+
: (patch.kind ?? 'recurring'),
|
|
413
|
+
}
|
|
358
414
|
: patch.kind !== undefined
|
|
359
415
|
? { kind: patch.kind }
|
|
360
416
|
: {}),
|
|
361
|
-
...(patch.permanent !== undefined
|
|
362
|
-
|
|
363
|
-
|
|
417
|
+
...(patch.permanent !== undefined
|
|
418
|
+
? { permanent: patch.permanent || undefined }
|
|
419
|
+
: {}),
|
|
420
|
+
...(patch.expiresAt !== undefined
|
|
421
|
+
? { expiresAt: patch.expiresAt || undefined }
|
|
422
|
+
: {}),
|
|
423
|
+
...(patch.maxRuns !== undefined
|
|
424
|
+
? { maxRuns: patch.maxRuns || undefined }
|
|
425
|
+
: {}),
|
|
364
426
|
...(patch.clearMaxRuns ? { maxRuns: undefined } : {}),
|
|
365
427
|
schedule: nextSchedule,
|
|
366
428
|
...(patch.action ? { action: patch.action } : {}),
|
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
constants,
|
|
4
|
+
copyFile,
|
|
5
|
+
mkdir,
|
|
6
|
+
readFile,
|
|
7
|
+
rename,
|
|
8
|
+
writeFile,
|
|
9
|
+
} from 'node:fs/promises';
|
|
3
10
|
import { agentStateDir } from '../../../src/plugin-sdk.js';
|
|
4
11
|
import { dirname, join } from 'node:path';
|
|
5
12
|
import type {
|
|
@@ -21,6 +28,8 @@ import {
|
|
|
21
28
|
recentRuns as readRecentRuns,
|
|
22
29
|
} from './runs.js';
|
|
23
30
|
import { normalizeTask } from './schema.js';
|
|
31
|
+
import { taskTransaction, outsideTaskTransaction } from './transaction.js';
|
|
32
|
+
import { requestStop } from './requests.js';
|
|
24
33
|
|
|
25
34
|
function root(): string {
|
|
26
35
|
return process.env.MINIMAL_AGENT_CRON_RUNNER_HOME
|
|
@@ -44,7 +53,15 @@ let mutationQueue: Promise<void> = Promise.resolve();
|
|
|
44
53
|
const taskChangeListeners = new Set<() => void>();
|
|
45
54
|
|
|
46
55
|
function notifyTaskChanges(): void {
|
|
47
|
-
|
|
56
|
+
outsideTaskTransaction(() => {
|
|
57
|
+
for (const listener of taskChangeListeners) {
|
|
58
|
+
try {
|
|
59
|
+
listener();
|
|
60
|
+
} catch {
|
|
61
|
+
/* Notifications cannot roll back a durable mutation. */
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
});
|
|
48
65
|
}
|
|
49
66
|
|
|
50
67
|
export function subscribeTaskChanges(listener: () => void): () => void {
|
|
@@ -76,7 +93,8 @@ export async function migrateCronTasks(): Promise<boolean> {
|
|
|
76
93
|
} catch {
|
|
77
94
|
throw new Error(`计划任务 JSON 损坏,原件未修改:${tasksFile()}`);
|
|
78
95
|
}
|
|
79
|
-
if (!Array.isArray(parsed.tasks))
|
|
96
|
+
if (!Array.isArray(parsed.tasks))
|
|
97
|
+
throw new Error(`计划任务缺少 tasks 数组:${tasksFile()}`);
|
|
80
98
|
const needsMigration = parsed.tasks.some((value) => {
|
|
81
99
|
const task = value as Partial<CronTask>;
|
|
82
100
|
return (
|
|
@@ -84,7 +102,8 @@ export async function migrateCronTasks(): Promise<boolean> {
|
|
|
84
102
|
!('type' in task.schedule) ||
|
|
85
103
|
!task.runtime?.bindingStatus ||
|
|
86
104
|
(task.version !== 2 &&
|
|
87
|
-
(task.runtime.sessionMode === 'fresh' ||
|
|
105
|
+
(task.runtime.sessionMode === 'fresh' ||
|
|
106
|
+
task.runtime.sessionId?.startsWith('cron-')))
|
|
88
107
|
);
|
|
89
108
|
});
|
|
90
109
|
if (!needsMigration) return false;
|
|
@@ -101,7 +120,9 @@ export async function migrateCronTasks(): Promise<boolean> {
|
|
|
101
120
|
const migrated = parsed.tasks.map(normalizeTask);
|
|
102
121
|
if (migrated.some((task) => !task))
|
|
103
122
|
throw new Error('计划任务数据损坏,已保留原件;迁移未写入。');
|
|
104
|
-
await writeTasksFile(
|
|
123
|
+
await writeTasksFile(
|
|
124
|
+
(migrated as CronTask[]).map((task) => ({ ...task, version: 2 })),
|
|
125
|
+
);
|
|
105
126
|
notifyTaskChanges();
|
|
106
127
|
return true;
|
|
107
128
|
});
|
|
@@ -124,7 +145,9 @@ async function readTasks(fromMs = Date.now()): Promise<CronTask[]> {
|
|
|
124
145
|
);
|
|
125
146
|
} catch (error) {
|
|
126
147
|
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
|
|
127
|
-
throw new Error(
|
|
148
|
+
throw new Error(
|
|
149
|
+
`无法读取计划任务 ${tasksFile()},原件未修改:${String(error)}`,
|
|
150
|
+
);
|
|
128
151
|
}
|
|
129
152
|
}
|
|
130
153
|
|
|
@@ -138,7 +161,11 @@ async function writeTasksFile(tasks: CronTask[]): Promise<void> {
|
|
|
138
161
|
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
139
162
|
await writeFile(
|
|
140
163
|
tmp,
|
|
141
|
-
JSON.stringify(
|
|
164
|
+
JSON.stringify(
|
|
165
|
+
{ tasks: tasks.map((task) => refreshNextRun(task)) },
|
|
166
|
+
null,
|
|
167
|
+
2,
|
|
168
|
+
),
|
|
142
169
|
'utf8',
|
|
143
170
|
);
|
|
144
171
|
await rename(tmp, file);
|
|
@@ -161,12 +188,18 @@ export async function writeTasks(tasks: CronTask[]): Promise<void> {
|
|
|
161
188
|
});
|
|
162
189
|
}
|
|
163
190
|
|
|
164
|
-
export async function upsertTask(
|
|
191
|
+
export async function upsertTask(
|
|
192
|
+
task: CronTask,
|
|
193
|
+
ifAbsent = false,
|
|
194
|
+
): Promise<CronTask> {
|
|
165
195
|
return await enqueueMutation(async () => {
|
|
166
196
|
const tasks = await readTasks();
|
|
167
197
|
const idx = tasks.findIndex((t) => t.id === task.id);
|
|
168
198
|
if (idx >= 0 && ifAbsent) return tasks[idx]!;
|
|
169
|
-
const saved = refreshNextRun({
|
|
199
|
+
const saved = refreshNextRun({
|
|
200
|
+
...task,
|
|
201
|
+
updatedAt: new Date().toISOString(),
|
|
202
|
+
});
|
|
170
203
|
if (idx >= 0) tasks[idx] = saved;
|
|
171
204
|
else tasks.push(saved);
|
|
172
205
|
await writeTasksFile(tasks);
|
|
@@ -179,34 +212,41 @@ export async function updateTask(
|
|
|
179
212
|
id: string,
|
|
180
213
|
updater: (task: CronTask) => CronTask,
|
|
181
214
|
): Promise<CronTask | undefined> {
|
|
182
|
-
return await
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
215
|
+
return await taskTransaction(root(), id, () =>
|
|
216
|
+
enqueueMutation(async () => {
|
|
217
|
+
const tasks = await readTasks();
|
|
218
|
+
const idx = tasks.findIndex((task) => task.id === id);
|
|
219
|
+
if (idx < 0) return undefined;
|
|
220
|
+
const saved = refreshNextRun({
|
|
221
|
+
...updater(tasks[idx]!),
|
|
222
|
+
revision: (tasks[idx]!.revision ?? 0) + 1,
|
|
223
|
+
updatedAt: new Date().toISOString(),
|
|
224
|
+
});
|
|
225
|
+
tasks[idx] = saved;
|
|
226
|
+
await writeTasksFile(tasks);
|
|
227
|
+
notifyTaskChanges();
|
|
228
|
+
return saved;
|
|
229
|
+
}),
|
|
230
|
+
);
|
|
196
231
|
}
|
|
197
232
|
|
|
198
233
|
export async function deleteTask(id: string): Promise<boolean> {
|
|
199
|
-
return await
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
234
|
+
return await taskTransaction(root(), id, async () => {
|
|
235
|
+
await requestStop(id);
|
|
236
|
+
return enqueueMutation(async () => {
|
|
237
|
+
const tasks = await readTasks();
|
|
238
|
+
const next = tasks.filter((t) => t.id !== id);
|
|
239
|
+
if (next.length === tasks.length) return false;
|
|
240
|
+
await writeTasksFile(next);
|
|
241
|
+
notifyTaskChanges();
|
|
242
|
+
return true;
|
|
243
|
+
});
|
|
206
244
|
});
|
|
207
245
|
}
|
|
208
246
|
|
|
209
|
-
export async function getTask(
|
|
247
|
+
export async function getTask(
|
|
248
|
+
idOrPrefix: string,
|
|
249
|
+
): Promise<CronTask | undefined> {
|
|
210
250
|
const tasks = await listTasks();
|
|
211
251
|
const exact = tasks.find((t) => t.id === idOrPrefix);
|
|
212
252
|
if (exact) return exact;
|
|
@@ -219,10 +259,17 @@ export async function appendRun(record: CronRunRecord): Promise<void> {
|
|
|
219
259
|
await appendRunRecord(runsDir(), record);
|
|
220
260
|
}
|
|
221
261
|
|
|
222
|
-
export async function recentRuns(
|
|
262
|
+
export async function recentRuns(
|
|
263
|
+
taskId: string,
|
|
264
|
+
limit = 5,
|
|
265
|
+
): Promise<CronRunRecord[]> {
|
|
223
266
|
return await readRecentRuns(runsDir(), taskId, limit);
|
|
224
267
|
}
|
|
225
268
|
|
|
269
|
+
export async function activeRuns(taskId: string): Promise<CronRunRecord[]> {
|
|
270
|
+
return readRecentRuns(runsDir(), taskId, Infinity, true);
|
|
271
|
+
}
|
|
272
|
+
|
|
226
273
|
export async function markRunsRead(taskId?: string): Promise<void> {
|
|
227
274
|
await markRunRecordsRead(runsDir(), taskId);
|
|
228
275
|
}
|
|
@@ -286,6 +333,7 @@ export function createTask(input: {
|
|
|
286
333
|
return refreshNextRun({
|
|
287
334
|
version: 2,
|
|
288
335
|
revision: 0,
|
|
336
|
+
planId: randomUUID(),
|
|
289
337
|
catchUp: input.catchUp ?? 'skip',
|
|
290
338
|
notifications: input.notifications ?? 'all',
|
|
291
339
|
id,
|
|
@@ -304,7 +352,9 @@ export function createTask(input: {
|
|
|
304
352
|
sessionId: input.sessionId ?? 'default',
|
|
305
353
|
sessionMode: input.sessionMode ?? 'persistent',
|
|
306
354
|
bindingStatus:
|
|
307
|
-
input.sessionMode === 'fresh' ||
|
|
355
|
+
input.sessionMode === 'fresh' ||
|
|
356
|
+
!input.sessionId ||
|
|
357
|
+
!input.sessionId.startsWith('cron-')
|
|
308
358
|
? 'bound'
|
|
309
359
|
: 'needs_binding',
|
|
310
360
|
...(input.model ? { model: input.model } : {}),
|
|
@@ -322,9 +372,12 @@ export function createTask(input: {
|
|
|
322
372
|
}
|
|
323
373
|
|
|
324
374
|
export function refreshNextRun(task: CronTask, fromMs = Date.now()): CronTask {
|
|
325
|
-
const expired =
|
|
375
|
+
const expired =
|
|
376
|
+
task.expiresAt && !task.permanent && Date.parse(task.expiresAt) <= fromMs;
|
|
326
377
|
const next =
|
|
327
|
-
task.status === 'active' && !expired
|
|
378
|
+
task.status === 'active' && !expired
|
|
379
|
+
? nextScheduleRunMs(task.schedule, fromMs)
|
|
380
|
+
: null;
|
|
328
381
|
return {
|
|
329
382
|
...task,
|
|
330
383
|
...(expired ? { status: 'completed' as const } : {}),
|
|
@@ -336,20 +389,32 @@ export function refreshNextRun(task: CronTask, fromMs = Date.now()): CronTask {
|
|
|
336
389
|
: task.schedule.type === 'cron'
|
|
337
390
|
? cronToHuman(task.schedule.cron)
|
|
338
391
|
: intervalToHuman(task.schedule.intervalMs),
|
|
339
|
-
jitterMs:
|
|
340
|
-
|
|
392
|
+
jitterMs:
|
|
393
|
+
typeof task.schedule.jitterMs === 'number' ? task.schedule.jitterMs : 0,
|
|
394
|
+
...(next
|
|
395
|
+
? { nextRunAt: new Date(next).toISOString() }
|
|
396
|
+
: { nextRunAt: undefined }),
|
|
341
397
|
},
|
|
342
398
|
};
|
|
343
399
|
}
|
|
344
400
|
|
|
345
401
|
/** Update only user-editable fields while preserving scheduler cursors, stats and creation time. */
|
|
346
|
-
export async function patchTask(
|
|
402
|
+
export async function patchTask(
|
|
403
|
+
patch: CronTaskPatch,
|
|
404
|
+
): Promise<CronTask | undefined> {
|
|
347
405
|
return await updateTask(patch.id, (current) => {
|
|
348
|
-
if (
|
|
406
|
+
if (
|
|
407
|
+
patch.expectedRevision !== undefined &&
|
|
408
|
+
patch.expectedRevision !== (current.revision ?? 0)
|
|
409
|
+
)
|
|
349
410
|
throw new Error('任务已被其他操作更新,请刷新后再编辑。');
|
|
350
411
|
const nextSchedule = patch.schedule
|
|
351
412
|
? patch.schedule.type === 'once'
|
|
352
|
-
? {
|
|
413
|
+
? {
|
|
414
|
+
type: 'once' as const,
|
|
415
|
+
at: patch.schedule.at,
|
|
416
|
+
human: `一次 · ${patch.schedule.at}`,
|
|
417
|
+
}
|
|
353
418
|
: patch.schedule.type === 'cron'
|
|
354
419
|
? {
|
|
355
420
|
...current.schedule,
|
|
@@ -378,39 +443,66 @@ export async function patchTask(patch: CronTaskPatch): Promise<CronTask | undefi
|
|
|
378
443
|
...patch.runtime,
|
|
379
444
|
sessionMode: patch.runtime.sessionMode ?? current.runtime.sessionMode,
|
|
380
445
|
bindingStatus:
|
|
381
|
-
patch.runtime.sessionId &&
|
|
446
|
+
patch.runtime.sessionId &&
|
|
447
|
+
!patch.runtime.sessionId.startsWith('cron-')
|
|
382
448
|
? ('bound' as const)
|
|
383
449
|
: current.runtime.bindingStatus,
|
|
384
450
|
}
|
|
385
|
-
: current.runtime;
|
|
451
|
+
: { ...current.runtime };
|
|
386
452
|
if (runtime.sessionMode === 'fresh') runtime.bindingStatus = 'bound';
|
|
387
453
|
if (patch.clearMaxTurns) runtime.maxTurns = undefined;
|
|
388
|
-
if (
|
|
454
|
+
if (
|
|
455
|
+
(patch.status ?? current.status) === 'active' &&
|
|
456
|
+
runtime.bindingStatus !== 'bound'
|
|
457
|
+
)
|
|
389
458
|
throw new Error('请先重新绑定工作目录会话');
|
|
390
459
|
const identity = (schedule: CronTask['schedule']) =>
|
|
391
460
|
JSON.stringify(
|
|
392
461
|
schedule.type === 'once'
|
|
393
462
|
? [schedule.type, schedule.at]
|
|
394
463
|
: schedule.type === 'cron'
|
|
395
|
-
? [
|
|
396
|
-
|
|
464
|
+
? [
|
|
465
|
+
schedule.type,
|
|
466
|
+
schedule.cron,
|
|
467
|
+
schedule.timezone,
|
|
468
|
+
schedule.jitterMs ?? 0,
|
|
469
|
+
]
|
|
470
|
+
: [
|
|
471
|
+
schedule.type,
|
|
472
|
+
schedule.intervalMs,
|
|
473
|
+
schedule.anchorAt,
|
|
474
|
+
schedule.jitterMs ?? 0,
|
|
475
|
+
],
|
|
397
476
|
);
|
|
398
477
|
const changed = identity(nextSchedule) !== identity(current.schedule);
|
|
399
|
-
const
|
|
478
|
+
const executionChanged =
|
|
479
|
+
changed ||
|
|
480
|
+
(patch.action !== undefined &&
|
|
481
|
+
JSON.stringify(patch.action) !== JSON.stringify(current.action)) ||
|
|
482
|
+
JSON.stringify(runtime) !== JSON.stringify(current.runtime) ||
|
|
483
|
+
(patch.kind !== undefined && patch.kind !== current.kind) ||
|
|
484
|
+
(patch.maxRuns !== undefined && patch.maxRuns !== current.maxRuns) ||
|
|
485
|
+
patch.clearMaxRuns;
|
|
486
|
+
const reactivating =
|
|
487
|
+
patch.status === 'active' && current.status !== 'active';
|
|
400
488
|
if (
|
|
401
489
|
nextSchedule.type === 'once' &&
|
|
402
490
|
(patch.status ?? current.status) === 'active' &&
|
|
403
491
|
(changed || reactivating) &&
|
|
404
492
|
Date.parse(nextSchedule.at) <= Date.now()
|
|
405
493
|
)
|
|
406
|
-
throw new Error(
|
|
494
|
+
throw new Error(
|
|
495
|
+
'重新启用一次性任务时,请设置未来的执行时间;立即执行请使用运行按钮。',
|
|
496
|
+
);
|
|
407
497
|
if (changed || (reactivating && nextSchedule.type !== 'once')) {
|
|
408
498
|
nextSchedule.lastScheduledFor = new Date().toISOString();
|
|
409
|
-
if (nextSchedule.type === 'once')
|
|
499
|
+
if (nextSchedule.type === 'once')
|
|
500
|
+
nextSchedule.lastScheduledFor = undefined;
|
|
410
501
|
} else nextSchedule.lastScheduledFor = current.schedule.lastScheduledFor;
|
|
411
502
|
return {
|
|
412
503
|
...current,
|
|
413
504
|
version: 2,
|
|
505
|
+
planId: executionChanged ? randomUUID() : (current.planId ?? current.id),
|
|
414
506
|
...(patch.catchUp ? { catchUp: patch.catchUp } : {}),
|
|
415
507
|
...(patch.notifications ? { notifications: patch.notifications } : {}),
|
|
416
508
|
...(patch.name !== undefined ? { name: patch.name.trim() } : {}),
|
|
@@ -420,14 +512,25 @@ export async function patchTask(patch: CronTaskPatch): Promise<CronTask | undefi
|
|
|
420
512
|
: { description: undefined }
|
|
421
513
|
: {}),
|
|
422
514
|
...(patch.status !== undefined ? { status: patch.status } : {}),
|
|
423
|
-
...(patch.schedule
|
|
424
|
-
? {
|
|
515
|
+
...(patch.schedule
|
|
516
|
+
? {
|
|
517
|
+
kind:
|
|
518
|
+
patch.schedule.type === 'once'
|
|
519
|
+
? ('once' as const)
|
|
520
|
+
: (patch.kind ?? ('recurring' as const)),
|
|
521
|
+
}
|
|
425
522
|
: patch.kind !== undefined
|
|
426
523
|
? { kind: patch.kind }
|
|
427
524
|
: {}),
|
|
428
|
-
...(patch.permanent !== undefined
|
|
429
|
-
|
|
430
|
-
|
|
525
|
+
...(patch.permanent !== undefined
|
|
526
|
+
? { permanent: patch.permanent || undefined }
|
|
527
|
+
: {}),
|
|
528
|
+
...(patch.expiresAt !== undefined
|
|
529
|
+
? { expiresAt: patch.expiresAt || undefined }
|
|
530
|
+
: {}),
|
|
531
|
+
...(patch.maxRuns !== undefined
|
|
532
|
+
? { maxRuns: patch.maxRuns || undefined }
|
|
533
|
+
: {}),
|
|
431
534
|
...(patch.clearMaxRuns ? { maxRuns: undefined } : {}),
|
|
432
535
|
schedule: nextSchedule,
|
|
433
536
|
...(patch.action ? { action: patch.action } : {}),
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { withStoreLock } from './lock.js';
|
|
5
|
+
const held = new AsyncLocalStorage();
|
|
6
|
+
/** Event listeners start independent operations, not children of the writer. */
|
|
7
|
+
export function outsideTaskTransaction(work) {
|
|
8
|
+
return held.run(new Map(), work);
|
|
9
|
+
}
|
|
10
|
+
/** Cross-process, reentrant task transaction. Never hold this during model execution. */
|
|
11
|
+
export async function taskTransaction(root, id, work) {
|
|
12
|
+
const key = join(root, 'transactions', createHash('sha256').update(id).digest('hex'));
|
|
13
|
+
if (held.getStore()?.get(key)?.active)
|
|
14
|
+
return work();
|
|
15
|
+
return withStoreLock(key, async () => {
|
|
16
|
+
const token = { active: true };
|
|
17
|
+
try {
|
|
18
|
+
return await held.run(new Map([...(held.getStore() ?? []), [key, token]]), work);
|
|
19
|
+
}
|
|
20
|
+
finally {
|
|
21
|
+
token.active = false;
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
}
|