dsh-background-task-engine 0.0.0-stage → 1.0.1

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 (58) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/LICENSE +21 -0
  3. package/README.md +263 -2
  4. package/README.zh.md +179 -0
  5. package/cordis.patch.yml +20 -0
  6. package/dist/config.d.ts +86 -0
  7. package/dist/config.js +106 -0
  8. package/dist/domain/records.d.ts +543 -0
  9. package/dist/domain/records.js +135 -0
  10. package/dist/domain/state.d.ts +61 -0
  11. package/dist/domain/state.js +128 -0
  12. package/dist/errors.d.ts +38 -0
  13. package/dist/errors.js +99 -0
  14. package/dist/host.d.ts +165 -0
  15. package/dist/host.js +56 -0
  16. package/dist/index.d.ts +60 -0
  17. package/dist/index.js +78 -0
  18. package/dist/prompt/guidance.d.ts +30 -0
  19. package/dist/prompt/guidance.js +62 -0
  20. package/dist/services/audit.d.ts +39 -0
  21. package/dist/services/audit.js +48 -0
  22. package/dist/services/engine.d.ts +435 -0
  23. package/dist/services/engine.js +150 -0
  24. package/dist/services/run-service.d.ts +145 -0
  25. package/dist/services/run-service.js +569 -0
  26. package/dist/services/schedule-adapter.d.ts +92 -0
  27. package/dist/services/schedule-adapter.js +220 -0
  28. package/dist/services/task-service.d.ts +146 -0
  29. package/dist/services/task-service.js +490 -0
  30. package/dist/storage/repository.d.ts +65 -0
  31. package/dist/storage/repository.js +194 -0
  32. package/dist/storage/spec.d.ts +97 -0
  33. package/dist/storage/spec.js +149 -0
  34. package/dist/tools/run-tools.d.ts +14 -0
  35. package/dist/tools/run-tools.js +402 -0
  36. package/dist/tools/schedule-tool.d.ts +11 -0
  37. package/dist/tools/schedule-tool.js +238 -0
  38. package/dist/tools/shared.d.ts +108 -0
  39. package/dist/tools/shared.js +278 -0
  40. package/dist/tools/task-tools.d.ts +7 -0
  41. package/dist/tools/task-tools.js +321 -0
  42. package/dist/utils/id.d.ts +8 -0
  43. package/dist/utils/id.js +29 -0
  44. package/dist/utils/page.d.ts +36 -0
  45. package/dist/utils/page.js +71 -0
  46. package/dist/utils/text.d.ts +20 -0
  47. package/dist/utils/text.js +46 -0
  48. package/dist/utils/time.d.ts +7 -0
  49. package/dist/utils/time.js +38 -0
  50. package/docs/API-COMPATIBILITY-AUDIT.md +203 -0
  51. package/docs/DETAIL.md +1 -0
  52. package/docs/DETAIL.zh.md +1 -0
  53. package/docs/TEST-REPORT.md +232 -0
  54. package/docs/preview.svg +68 -0
  55. package/icon.svg +23 -0
  56. package/locale/en.json +7 -0
  57. package/locale/zh.json +7 -0
  58. package/package.json +71 -4
@@ -0,0 +1,402 @@
1
+ /**
2
+ * Execution tools: task_run / task_run_begin / task_step_report /
3
+ * task_run_finish / task_run_history / task_resume (PRD 5.3–5.6, 6.3, FR-005..FR-008).
4
+ */
5
+ import { z } from 'zod';
6
+ import { isFailure } from './shared.js';
7
+ import { EXECUTION_PROTOCOL } from '../prompt/guidance.js';
8
+ import { elapsedLabel } from '../utils/time.js';
9
+ import { shortId } from '../utils/id.js';
10
+ import { RUN_STATUSES } from '../domain/records.js';
11
+ import { buildTool, out, progressLine, renderGeneric, runView, RUN_FIELDS, } from './shared.js';
12
+ const ERROR_INPUT = {
13
+ type: 'object',
14
+ additionalProperties: false,
15
+ properties: {
16
+ code: { type: 'string', description: '简短错误码,例如 GIT_UNREACHABLE。' },
17
+ message: { type: 'string', description: '真实错误摘要(不要包含密钥或凭据)。' },
18
+ },
19
+ required: ['message'],
20
+ };
21
+ const errorInput = z.object({
22
+ code: z.string().trim().max(64).optional(),
23
+ message: z.string().trim().min(1).max(2000),
24
+ });
25
+ function renderRun(args, value) {
26
+ const record = value;
27
+ if (isFailure(value))
28
+ return renderGeneric(args, value);
29
+ const steps = (record.steps ?? []);
30
+ const mark = (status) => status === 'completed' ? '✓' : status === 'running' ? '●' : status === 'failed' ? '✗' : status === 'skipped' ? '–' : '○';
31
+ const lines = [
32
+ `运行 ${String(record.runId ?? '')} · ${String(record.status ?? '')} · 进度 ${String(record.progress ?? 0)}%`,
33
+ `任务 ${String(record.title ?? record.taskId ?? '')}(revision ${String(record.taskRevision ?? '')})`,
34
+ ];
35
+ if (record.deduplicated === true)
36
+ lines.push('该幂等键已存在运行,未重复创建(返回已有记录)');
37
+ for (const step of steps) {
38
+ const suffix = step.errorSummary ? ` — ${String(step.errorSummary)}` : '';
39
+ lines.push(`${mark(String(step.status ?? 'pending'))} ${String(step.order ?? '')}. ${String(step.title ?? '')}${suffix}`);
40
+ }
41
+ if (record.summary)
42
+ lines.push(`摘要:${String(record.summary)}`);
43
+ if (record.errorSummary)
44
+ lines.push(`错误:${String(record.errorSummary)}`);
45
+ return [{ type: 'text', text: lines.join('\n') }];
46
+ }
47
+ export function createRunTools(engine) {
48
+ const run = buildTool({
49
+ name: 'task_run',
50
+ description: '手动启动一次任务执行,创建独立的 TaskRun 并返回步骤指令。这是 FR-005 的入口:返回后由当前 Agent 在当前授权上下文中逐步执行。'
51
+ + '同一任务已有活动运行时返回 TASK_ALREADY_RUNNING 并附上现有 runId。\n\n' + EXECUTION_PROTOCOL,
52
+ parameters: {
53
+ taskId: { type: 'string', description: '要执行的任务 ID。' },
54
+ manualRunId: {
55
+ type: 'string',
56
+ description: '可选幂等键:同一个 manualRunId 重复提交不会产生第二个运行。',
57
+ },
58
+ defer: {
59
+ type: 'boolean',
60
+ description: 'true 时创建为 queued,需再调用 task_run_begin 认领;默认直接进入 running。',
61
+ },
62
+ triggerType: { type: 'string', enum: ['manual', 'schedule'], description: '触发来源,手动执行默认 manual。' },
63
+ },
64
+ args: z.object({
65
+ taskId: z.string().trim().min(4).max(64),
66
+ manualRunId: z.string().trim().min(1).max(200).optional(),
67
+ defer: z.boolean().optional(),
68
+ triggerType: z.enum(['manual', 'schedule']).optional(),
69
+ }),
70
+ output: out({ ...RUN_FIELDS, title: { type: 'string' }, deduplicated: { type: 'boolean' } }, ['runId', 'status']),
71
+ render: renderRun,
72
+ async execute(args, active) {
73
+ const result = await active.runService.start({
74
+ sessionId: String(args.sessionId),
75
+ taskId: String(args.taskId),
76
+ manualRunId: args.manualRunId,
77
+ defer: args.defer === true,
78
+ triggerType: args.triggerType ?? 'manual',
79
+ source: 'task_run',
80
+ });
81
+ return { ...runView(result.run, result.steps), deduplicated: result.deduplicated };
82
+ },
83
+ }, engine);
84
+ const begin = buildTool({
85
+ name: 'task_run_begin',
86
+ description: '认领/开始一次运行:可用 taskId 新开一次执行,也可用 runId 把 queued 运行切换为 running。'
87
+ + '收到 Schedule 投递消息时,把消息原文放进 triggerPayload,插件会自动识别 taskId、scheduleId 与 occurrenceKey,并用 scheduleId+occurrenceKey 去重。'
88
+ + '返回 runId、模板快照与步骤列表。\n\n' + EXECUTION_PROTOCOL,
89
+ parameters: {
90
+ taskId: { type: 'string', description: '任务 ID;省略时必须能从 triggerPayload 识别。' },
91
+ runId: { type: 'string', description: '已有 queued 运行的 ID;提供时只做 queued → running。' },
92
+ triggerPayload: {
93
+ type: 'string',
94
+ description: '触发消息原文(含 task_id_json / schedule_id_json / occurrence_at),用于定时触发识别。',
95
+ },
96
+ triggerType: { type: 'string', enum: ['manual', 'schedule'], description: '触发来源;省略时按是否识别到定时载荷推断。' },
97
+ scheduleId: { type: 'string', description: '显式指定 Schedule ID(通常无需手填)。' },
98
+ occurrenceKey: { type: 'string', description: '显式指定本次投递的唯一键(通常取自 occurrence_at)。' },
99
+ idempotencyKey: { type: 'string', description: '自定义幂等键;相同键不会重复创建运行。' },
100
+ },
101
+ args: z.object({
102
+ taskId: z.string().trim().min(4).max(64).optional(),
103
+ runId: z.string().trim().min(4).max(64).optional(),
104
+ triggerPayload: z.string().max(20000).optional(),
105
+ triggerType: z.enum(['manual', 'schedule']).optional(),
106
+ scheduleId: z.string().trim().max(128).optional(),
107
+ occurrenceKey: z.string().trim().max(256).optional(),
108
+ idempotencyKey: z.string().trim().max(280).optional(),
109
+ }).refine((value) => Boolean(value.taskId || value.runId || value.triggerPayload), {
110
+ message: '需要提供 taskId、runId 或 triggerPayload 之一',
111
+ }),
112
+ output: out({ ...RUN_FIELDS, title: { type: 'string' }, deduplicated: { type: 'boolean' } }, ['runId', 'status']),
113
+ render: (args, value) => {
114
+ const rendered = renderRun(args, value);
115
+ const record = value;
116
+ if (!isFailure(value)) {
117
+ rendered.push({
118
+ type: 'text',
119
+ text: '下一步:按 order 顺序对每个步骤调用 task_step_report(action="started" / "completed"),'
120
+ + '全部必需步骤完成后调用 task_run_finish(status="succeeded")。',
121
+ });
122
+ }
123
+ return rendered;
124
+ },
125
+ async execute(args, active) {
126
+ const sessionId = String(args.sessionId);
127
+ if (args.runId) {
128
+ const result = await active.runService.begin({
129
+ sessionId,
130
+ runId: String(args.runId),
131
+ source: 'task_run_begin',
132
+ });
133
+ return { ...runView(result.run, result.steps), deduplicated: result.deduplicated };
134
+ }
135
+ const result = await active.runService.start({
136
+ sessionId,
137
+ taskId: args.taskId,
138
+ triggerPayload: args.triggerPayload,
139
+ triggerType: args.triggerType,
140
+ scheduleId: args.scheduleId,
141
+ occurrenceKey: args.occurrenceKey,
142
+ idempotencyKey: args.idempotencyKey,
143
+ source: 'task_run_begin',
144
+ });
145
+ return { ...runView(result.run, result.steps), deduplicated: result.deduplicated };
146
+ },
147
+ }, engine);
148
+ const stepReport = buildTool({
149
+ name: 'task_step_report',
150
+ description: '上报某一步骤的状态:started / completed / failed / skipped。步骤必须按 order 顺序推进,且只能报告快照内存在的 stepId。'
151
+ + '所有进度都由持久化记录计算(completed 必需步骤数 / 必需步骤总数),不依赖调用方自报。',
152
+ parameters: {
153
+ runId: { type: 'string', description: '运行 ID。' },
154
+ stepId: { type: 'string', description: '步骤 ID(来自 task_run_begin 返回的步骤列表)。' },
155
+ action: {
156
+ type: 'string',
157
+ enum: ['started', 'completed', 'failed', 'skipped'],
158
+ description: 'started 开始;completed 满足 completionCriteria 后才可报告;failed 必须给出 error;skipped 表示本次不执行。',
159
+ },
160
+ summary: { type: 'string', description: '基于实际结果的简短摘要(最多 2000 字符,超长自动截断)。' },
161
+ error: ERROR_INPUT,
162
+ },
163
+ args: z.object({
164
+ runId: z.string().trim().min(4).max(64),
165
+ stepId: z.string().trim().min(4).max(64),
166
+ action: z.enum(['started', 'completed', 'failed', 'skipped']),
167
+ summary: z.string().trim().max(2000).optional(),
168
+ error: errorInput.optional(),
169
+ }),
170
+ output: out({
171
+ ...RUN_FIELDS,
172
+ stepId: { type: 'string' },
173
+ stepStatus: { type: 'string' },
174
+ progress: { type: 'integer' },
175
+ nextStepId: { type: 'string' },
176
+ }, ['runId', 'stepId', 'stepStatus', 'progress']),
177
+ render: (args, value) => {
178
+ const record = value;
179
+ if (isFailure(value))
180
+ return renderGeneric(args, value);
181
+ const steps = (record.steps ?? []);
182
+ const mark = (status) => status === 'completed' ? '✓' : status === 'running' ? '●' : status === 'failed' ? '✗' : status === 'skipped' ? '–' : '○';
183
+ const lines = [
184
+ `步骤 ${String(record.stepId ?? '')} → ${String(record.stepStatus ?? '')}`,
185
+ `进度 ${String(record.progress ?? 0)}%`,
186
+ ];
187
+ for (const step of steps)
188
+ lines.push(`${mark(String(step.status ?? ''))} ${String(step.order ?? '')}. ${String(step.title ?? '')}`);
189
+ if (record.nextStepId)
190
+ lines.push(`下一步:${String(record.nextStepId)}`);
191
+ else
192
+ lines.push('所有步骤已结束,请调用 task_run_finish 提交运行结果。');
193
+ return [{ type: 'text', text: lines.join('\n') }];
194
+ },
195
+ async execute(args, active) {
196
+ const result = await active.runService.reportStep({
197
+ sessionId: String(args.sessionId),
198
+ runId: String(args.runId),
199
+ stepId: String(args.stepId),
200
+ action: args.action,
201
+ summary: args.summary,
202
+ error: args.error,
203
+ });
204
+ const nextStepId = result.run.currentStepId;
205
+ return {
206
+ ...runView(result.run, active.runService.stepsOf(result.run.runId)),
207
+ stepId: result.step.stepId,
208
+ stepStatus: result.step.status,
209
+ progress: result.run.progress,
210
+ ...(nextStepId ? { nextStepId } : {}),
211
+ };
212
+ },
213
+ }, engine);
214
+ const finish = buildTool({
215
+ name: 'task_run_finish',
216
+ description: '提交运行结果,把 TaskRun 置为 succeeded / failed / blocked / interrupted / skipped。'
217
+ + 'succeeded 要求全部必需步骤都已 completed;failed 要求先有失败步骤或给出 error;blocked 必须在 summary 中写明等待事项。'
218
+ + '阻断类状态(blocked)不是终态,可用 task_resume 创建新运行继续。',
219
+ parameters: {
220
+ runId: { type: 'string', description: '运行 ID。' },
221
+ status: {
222
+ type: 'string',
223
+ enum: ['succeeded', 'failed', 'blocked', 'interrupted', 'skipped'],
224
+ description: '终态结果;blocked 表示等待用户处理。',
225
+ },
226
+ summary: { type: 'string', description: '结果摘要(最多 2000 字符)。' },
227
+ error: ERROR_INPUT,
228
+ },
229
+ args: z.object({
230
+ runId: z.string().trim().min(4).max(64),
231
+ status: z.enum(['succeeded', 'failed', 'blocked', 'interrupted', 'skipped']),
232
+ summary: z.string().trim().max(2000).optional(),
233
+ error: errorInput.optional(),
234
+ }),
235
+ output: out(RUN_FIELDS, ['runId', 'status']),
236
+ render: (args, value) => {
237
+ const record = value;
238
+ if (isFailure(value))
239
+ return renderGeneric(args, value);
240
+ const icon = record.status === 'succeeded' ? '✅' : record.status === 'blocked' ? '⏸' : record.status === 'failed' ? '❌' : '⚠️';
241
+ const lines = [
242
+ `${icon} 运行 ${String(record.runId ?? '')} → ${String(record.status ?? '')}`,
243
+ `进度 ${String(record.progress ?? 0)}%(${String(record.completedRequired ?? 0)}/${String(record.totalRequired ?? 0)} 必需步骤)`,
244
+ `耗时 ${String(record.duration ?? elapsedLabel(String(record.startedAt ?? ''), String(record.finishedAt ?? '')))}`,
245
+ ];
246
+ if (record.summary)
247
+ lines.push(`摘要:${String(record.summary)}`);
248
+ if (record.errorSummary)
249
+ lines.push(`错误:${String(record.errorSummary)}`);
250
+ return [{ type: 'text', text: lines.join('\n') }];
251
+ },
252
+ async execute(args, active) {
253
+ const updated = await active.runService.finish({
254
+ sessionId: String(args.sessionId),
255
+ runId: String(args.runId),
256
+ status: args.status,
257
+ summary: args.summary,
258
+ error: args.error,
259
+ });
260
+ return runView(updated, active.runService.stepsOf(updated.runId));
261
+ },
262
+ }, engine);
263
+ const history = buildTool({
264
+ name: 'task_run_history',
265
+ description: '查询某个任务的运行历史(默认每页 20 条,最多 100 条),包含状态、进度、耗时、摘要与步骤状态。'
266
+ + '只返回保留期内的记录(默认 90 天)。',
267
+ parameters: {
268
+ taskId: { type: 'string', description: '任务 ID。' },
269
+ status: { type: 'string', enum: [...RUN_STATUSES], description: '按运行状态筛选。' },
270
+ limit: { type: 'integer', description: '每页条数,1–100,默认 20。' },
271
+ cursor: { type: 'string', description: '上一页返回的 nextCursor。' },
272
+ },
273
+ args: z.object({
274
+ taskId: z.string().trim().min(4).max(64),
275
+ status: z.enum(RUN_STATUSES).optional(),
276
+ limit: z.number().int().min(1).max(100).optional(),
277
+ cursor: z.string().max(200).optional(),
278
+ }),
279
+ output: out({
280
+ items: {
281
+ type: 'array',
282
+ items: {
283
+ type: 'object',
284
+ additionalProperties: true,
285
+ properties: {
286
+ runId: { type: 'string' },
287
+ status: { type: 'string' },
288
+ triggerType: { type: 'string' },
289
+ progress: { type: 'integer' },
290
+ startedAt: { type: 'string' },
291
+ finishedAt: { type: 'string' },
292
+ summary: { type: 'string' },
293
+ errorSummary: { type: 'string' },
294
+ resumesRunId: { type: 'string' },
295
+ steps: { type: 'array', items: { type: 'object', additionalProperties: true } },
296
+ },
297
+ },
298
+ },
299
+ nextCursor: { type: 'string' },
300
+ }, ['items']),
301
+ render: (args, value) => {
302
+ const record = value;
303
+ if (isFailure(value))
304
+ return renderGeneric(args, value);
305
+ const items = (record.items ?? []);
306
+ if (items.length === 0)
307
+ return [{ type: 'text', text: '(没有运行记录)' }];
308
+ const lines = items.map((item) => `${shortId(String(item.runId ?? ''))} ${String(item.status ?? '')} ${String(item.progress ?? 0)}% `
309
+ + `${String(item.triggerType ?? '')} ${String(item.startedAt ?? '').slice(0, 19).replace('T', ' ')}`
310
+ + (item.summary ? ` ${String(item.summary).slice(0, 40)}` : ''));
311
+ if (record.nextCursor)
312
+ lines.push(`下一页:cursor=${String(record.nextCursor)}`);
313
+ return [{ type: 'text', text: lines.join('\n') }];
314
+ },
315
+ execute(args, active) {
316
+ const page = active.runService.history({
317
+ sessionId: String(args.sessionId),
318
+ taskId: String(args.taskId),
319
+ status: args.status,
320
+ limit: args.limit,
321
+ cursor: args.cursor,
322
+ });
323
+ return {
324
+ items: page.items.map((item) => ({
325
+ runId: item.runId,
326
+ status: item.status,
327
+ triggerType: item.triggerType,
328
+ taskRevision: item.taskRevision,
329
+ progress: item.progress,
330
+ startedAt: item.startedAt,
331
+ ...(item.finishedAt ? { finishedAt: item.finishedAt } : {}),
332
+ ...(item.summary ? { summary: item.summary } : {}),
333
+ ...(item.error ? { errorSummary: `${item.error.code}: ${item.error.message}` } : {}),
334
+ ...(item.resumesRunId ? { resumesRunId: item.resumesRunId } : {}),
335
+ steps: item.steps,
336
+ })),
337
+ ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),
338
+ };
339
+ },
340
+ }, engine);
341
+ const resume = buildTool({
342
+ name: 'task_resume',
343
+ description: '人工恢复一次 failed / interrupted / blocked 的运行。恢复总是创建新的 TaskRun 并 write resumesRunId,'
344
+ + '已完成步骤不会重复执行,从第一个未完成步骤继续。若原运行有失败步骤(可能已产生外部副作用),必须提供 confirmation 才允许恢复,插件绝不自动重放。',
345
+ parameters: {
346
+ runId: { type: 'string', description: '要恢复的原运行 ID。' },
347
+ confirmation: {
348
+ type: 'string',
349
+ description: '用户对"旧执行已终止、重复执行副作用可接受"的确认原文;有失败步骤时必填。',
350
+ },
351
+ },
352
+ args: z.object({
353
+ runId: z.string().trim().min(4).max(64),
354
+ confirmation: z.string().trim().max(2000).optional(),
355
+ }),
356
+ output: out({ ...RUN_FIELDS, deduplicated: { type: 'boolean' } }, ['runId', 'status']),
357
+ render: (args, value) => {
358
+ const record = value;
359
+ if (isFailure(value))
360
+ return renderGeneric(args, value);
361
+ const steps = (record.steps ?? []);
362
+ const lines = [
363
+ `已创建恢复运行 ${String(record.runId ?? '')}(来自 ${String(record.resumesRunId ?? '')})`,
364
+ `进度 ${String(record.progress ?? 0)}%(${String(record.completedRequired ?? 0)}/${String(record.totalRequired ?? 0)})`,
365
+ ];
366
+ const pending = steps.filter((step) => step.status === 'pending');
367
+ if (pending.length > 0) {
368
+ lines.push('待执行步骤:');
369
+ for (const step of pending)
370
+ lines.push(`· ${String(step.order ?? '')}. ${String(step.title ?? '')} (${String(step.stepId ?? '')})`);
371
+ }
372
+ else {
373
+ lines.push('没有待执行步骤(全部已完成),可直接 task_run_finish(succeeded)。');
374
+ }
375
+ return [{ type: 'text', text: lines.join('\n') }];
376
+ },
377
+ async execute(args, active) {
378
+ const result = await active.runService.resume({
379
+ sessionId: String(args.sessionId),
380
+ runId: String(args.runId),
381
+ confirmation: args.confirmation,
382
+ });
383
+ return { ...runView(result.run, result.steps), deduplicated: result.deduplicated };
384
+ },
385
+ }, engine);
386
+ return [run, begin, stepReport, finish, history, resume];
387
+ }
388
+ /** Progress text helper exported for the diagnostics tool. */
389
+ export function describeRunProgress(run) {
390
+ return progressLine({
391
+ runId: '',
392
+ taskId: '',
393
+ taskRevision: 1,
394
+ status: run.status,
395
+ triggerType: 'manual',
396
+ sessionId: '',
397
+ progress: run.progress,
398
+ requiredCompleted: run.requiredCompleted,
399
+ requiredTotal: run.requiredTotal,
400
+ startedAt: '',
401
+ });
402
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * task_schedule: manage the link between a task template and a native DSH
3
+ * Schedule entry (PRD FR-002, 14.3).
4
+ *
5
+ * The plugin owns the reference, the host owns the rule. When `ctx.schedule` is
6
+ * not mounted this tool returns TASK_SCHEDULE_UNAVAILABLE while manual runs keep
7
+ * working (PRD FR-012).
8
+ */
9
+ import type { ToolDefinitionLike } from '../host.js';
10
+ import type { TaskEngine } from '../services/engine.js';
11
+ export declare function createScheduleTool(engine: () => TaskEngine): ToolDefinitionLike;
@@ -0,0 +1,238 @@
1
+ /**
2
+ * task_schedule: manage the link between a task template and a native DSH
3
+ * Schedule entry (PRD FR-002, 14.3).
4
+ *
5
+ * The plugin owns the reference, the host owns the rule. When `ctx.schedule` is
6
+ * not mounted this tool returns TASK_SCHEDULE_UNAVAILABLE while manual runs keep
7
+ * working (PRD FR-012).
8
+ */
9
+ import { z } from 'zod';
10
+ import { buildTool, out, renderGeneric, taskView, TASK_FIELDS, isFailure } from './shared.js';
11
+ import { oneLine } from '../utils/text.js';
12
+ const TIMING_SCHEMA = {
13
+ type: 'object',
14
+ additionalProperties: false,
15
+ properties: {
16
+ kind: {
17
+ type: 'string',
18
+ enum: ['at', 'every', 'rrule', 'cron', 'daily', 'weekly'],
19
+ description: '定时类型:at 一次性时间点;every 固定间隔;rrule 重复规则;cron 5 段表达式;daily 每天;weekly 每周。',
20
+ },
21
+ at: { type: 'string', description: 'kind=at 时必填:RFC3339 时间,例如 2026-12-01T09:00:00+08:00。' },
22
+ everySeconds: { type: 'integer', description: 'kind=every 时必填:间隔秒数(30–2592000)。' },
23
+ rrule: { type: 'string', description: 'kind=rrule 时必填:DTSTART 行 + RRULE 行,用换行分隔。' },
24
+ expression: { type: 'string', description: 'kind=cron 时必填:5 段 Cron,例如 "0 9 * * 1-5"。' },
25
+ timeZone: { type: 'string', description: 'IANA 时区,默认 Asia/Shanghai。' },
26
+ hour: { type: 'integer', description: 'kind=daily/weekly 时使用:0–23。' },
27
+ minute: { type: 'integer', description: 'kind=daily/weekly 时使用:0–59。' },
28
+ dayOfWeek: { type: 'integer', description: 'kind=weekly 时使用:0=周日 … 6=周六。' },
29
+ },
30
+ required: ['kind'],
31
+ };
32
+ const timingSchema = z.object({
33
+ kind: z.enum(['at', 'every', 'rrule', 'cron', 'daily', 'weekly']),
34
+ at: z.string().trim().max(64).optional(),
35
+ everySeconds: z.number().int().min(30).max(2_592_000).optional(),
36
+ rrule: z.string().max(1000).optional(),
37
+ expression: z.string().trim().max(200).optional(),
38
+ timeZone: z.string().trim().max(64).optional(),
39
+ hour: z.number().int().min(0).max(23).optional(),
40
+ minute: z.number().int().min(0).max(59).optional(),
41
+ dayOfWeek: z.number().int().min(0).max(6).optional(),
42
+ });
43
+ function toTiming(input) {
44
+ const kind = String(input.kind);
45
+ switch (kind) {
46
+ case 'at':
47
+ return { kind: 'at', at: String(input.at ?? '') };
48
+ case 'every':
49
+ return { kind: 'every', everySeconds: Number(input.everySeconds ?? 0) };
50
+ case 'rrule':
51
+ return { kind: 'rrule', rrule: String(input.rrule ?? '') };
52
+ case 'cron':
53
+ return {
54
+ kind: 'cron',
55
+ expression: String(input.expression ?? ''),
56
+ ...(input.timeZone ? { timeZone: String(input.timeZone) } : {}),
57
+ };
58
+ case 'daily':
59
+ return {
60
+ kind: 'daily',
61
+ hour: Number(input.hour ?? 0),
62
+ minute: Number(input.minute ?? 0),
63
+ ...(input.timeZone ? { timeZone: String(input.timeZone) } : {}),
64
+ };
65
+ case 'weekly':
66
+ return {
67
+ kind: 'weekly',
68
+ dayOfWeek: Number(input.dayOfWeek ?? 0),
69
+ hour: Number(input.hour ?? 0),
70
+ minute: Number(input.minute ?? 0),
71
+ ...(input.timeZone ? { timeZone: String(input.timeZone) } : {}),
72
+ };
73
+ default:
74
+ throw new Error(`不支持的 timing.kind: ${kind}`);
75
+ }
76
+ }
77
+ export function createScheduleTool(engine) {
78
+ return buildTool({
79
+ name: 'task_schedule',
80
+ description: '管理任务模板与 DSH 原生定时规则的关联:create 创建并关联、update 修改规则、pause / resume 暂停恢复、delete 解除关联、run_now 立即运行一次、status 查看宿主真实状态。'
81
+ + '插件只保存 scheduleId 引用,不复制 Cron 状态;Schedule 不可用时返回 TASK_SCHEDULE_UNAVAILABLE,手动 task_run 仍可正常使用。',
82
+ parameters: {
83
+ taskId: { type: 'string', description: '任务 ID。' },
84
+ action: {
85
+ type: 'string',
86
+ enum: ['create', 'update', 'pause', 'resume', 'delete', 'run_now', 'status'],
87
+ description: '要执行的操作。',
88
+ },
89
+ timing: TIMING_SCHEMA,
90
+ scheduleRule: {
91
+ type: 'string',
92
+ description: '可选:直接给出重复规则的简写,等价于 timing.kind=rrule 的 rrule 字段。',
93
+ },
94
+ },
95
+ args: z.object({
96
+ taskId: z.string().trim().min(4).max(64),
97
+ action: z.enum(['create', 'update', 'pause', 'resume', 'delete', 'run_now', 'status']),
98
+ timing: timingSchema.optional(),
99
+ scheduleRule: z.string().trim().max(1000).optional(),
100
+ }),
101
+ output: out({
102
+ ...TASK_FIELDS,
103
+ action: { type: 'string' },
104
+ scheduleId: { type: 'string' },
105
+ scheduleAvailable: { type: 'boolean' },
106
+ liveStatus: { type: 'string' },
107
+ nextOccurrence: { type: 'string' },
108
+ note: { type: 'string' },
109
+ }, ['action']),
110
+ render: (args, value) => {
111
+ const record = value;
112
+ if (isFailure(value))
113
+ return renderGeneric(args, value);
114
+ const lines = [`操作:${String(record.action ?? '')}`];
115
+ if (record.taskId)
116
+ lines.push(`任务:${oneLine(String(record.title ?? ''), 40)}(${String(record.taskId)})`);
117
+ if (record.scheduleId)
118
+ lines.push(`scheduleId:${String(record.scheduleId)}`);
119
+ if (record.liveStatus)
120
+ lines.push(`宿主状态:${String(record.liveStatus)}`);
121
+ if (record.nextOccurrence)
122
+ lines.push(`下次触发:${String(record.nextOccurrence)}`);
123
+ if (record.note)
124
+ lines.push(String(record.note));
125
+ if (record.scheduleAvailable === false)
126
+ lines.push('当前宿主未挂载 Schedule,定时功能不可用(手动执行不受影响)。');
127
+ return [{ type: 'text', text: lines.join('\n') }];
128
+ },
129
+ async execute(args, active) {
130
+ const sessionId = String(args.sessionId);
131
+ const taskId = String(args.taskId);
132
+ const action = String(args.action);
133
+ const timing = args.timing;
134
+ if (action !== 'status' && !active.scheduleAdapter.available) {
135
+ return {
136
+ action,
137
+ scheduleAvailable: false,
138
+ note: '当前宿主未挂载 ctx.schedule,定时功能不可用;请用 task_run 手动执行任务,或在启用 Schedule 后重试。',
139
+ ...(await safeTask(active, sessionId, taskId)),
140
+ };
141
+ }
142
+ switch (action) {
143
+ case 'create': {
144
+ const created = await active.taskService.scheduleCreate({
145
+ sessionId,
146
+ taskId,
147
+ timing: scheduleRuleOf(timing, args.scheduleRule),
148
+ });
149
+ return {
150
+ ...taskView(created),
151
+ action,
152
+ scheduleAvailable: true,
153
+ scheduleId: created.scheduleId,
154
+ note: '定时规则已创建并关联;到期投递只表示已触发,TaskRun 状态仍需由 task_run_begin / task_run_finish 更新。',
155
+ };
156
+ }
157
+ case 'update': {
158
+ const updated = await active.taskService.scheduleUpdate({
159
+ sessionId,
160
+ taskId,
161
+ timing: scheduleRuleOf(timing, args.scheduleRule),
162
+ });
163
+ return { ...taskView(updated), action, scheduleAvailable: true };
164
+ }
165
+ case 'pause': {
166
+ const result = await active.taskService.scheduleSetActive({ sessionId, taskId, active: false });
167
+ return {
168
+ ...taskView(result.task),
169
+ action,
170
+ scheduleAvailable: true,
171
+ note: result.changed ? '定时规则已暂停' : '定时规则此前已处于暂停状态',
172
+ };
173
+ }
174
+ case 'resume': {
175
+ const result = await active.taskService.scheduleSetActive({ sessionId, taskId, active: true });
176
+ return {
177
+ ...taskView(result.task),
178
+ action,
179
+ scheduleAvailable: true,
180
+ note: result.changed ? '定时规则已恢复,按下一个未来时间点触发' : '定时规则此前已在运行',
181
+ };
182
+ }
183
+ case 'delete': {
184
+ const result = await active.taskService.scheduleDelete({ sessionId, taskId });
185
+ return {
186
+ ...taskView(result.task),
187
+ action,
188
+ scheduleAvailable: true,
189
+ note: result.alreadyGone ? '宿主中已无该定时规则,仅解除本地关联' : '定时规则已删除,本地关联已解除',
190
+ };
191
+ }
192
+ case 'run_now': {
193
+ const result = await active.taskService.scheduleRunNow({ sessionId, taskId });
194
+ return {
195
+ ...taskView(await taskOf(active, sessionId, taskId)),
196
+ action,
197
+ scheduleAvailable: true,
198
+ note: result.pending
199
+ ? '该定时规则已有一次执行占用投递位,本次未重复投递'
200
+ : '已请求宿主立即投递一次;投递成功不等于任务完成,仍需走 task_run_begin',
201
+ };
202
+ }
203
+ case 'status':
204
+ default: {
205
+ const status = await active.taskService.scheduleStatus({ sessionId, taskId });
206
+ const task = await taskOf(active, sessionId, taskId);
207
+ return {
208
+ ...taskView(task),
209
+ action: 'status',
210
+ scheduleAvailable: status.available,
211
+ ...(status.ref ? { scheduleId: status.ref.scheduleId, liveStatus: String(status.live?.status ?? status.ref.state) } : {}),
212
+ ...(status.live?.scheduledAt ? { nextOccurrence: status.live.scheduledAt } : {}),
213
+ ...(status.ref ? {} : { note: '该任务尚未关联定时规则' }),
214
+ };
215
+ }
216
+ }
217
+ },
218
+ }, engine);
219
+ }
220
+ function scheduleRuleOf(timing, scheduleRule) {
221
+ if (timing && timing.kind)
222
+ return toTiming(timing);
223
+ if (scheduleRule)
224
+ return { kind: 'rrule', rrule: scheduleRule };
225
+ throw new Error('需要提供 timing 或 scheduleRule');
226
+ }
227
+ async function taskOf(active, sessionId, taskId) {
228
+ return active.taskService.get(sessionId, taskId, { includeRuns: false }).task;
229
+ }
230
+ async function safeTask(active, sessionId, taskId) {
231
+ try {
232
+ const task = await taskOf(active, sessionId, taskId);
233
+ return { taskId: task.taskId, title: task.title, status: task.status };
234
+ }
235
+ catch {
236
+ return {};
237
+ }
238
+ }