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,220 @@
1
+ /**
2
+ * DSH Schedule adapter (PRD 4.5, 8.3, FR-002, FR-008; acceptance 14.3).
3
+ *
4
+ * The plugin never implements its own scheduler: occurrences, catch-up and
5
+ * delivery are owned by `ctx.schedule`. This adapter only
6
+ * - translates the plugin's timing input into a documented host timing,
7
+ * - stores the returned scheduleId on the task (`scheduleRef`),
8
+ * - maps host failures onto TASK_SCHEDULE_* codes so a failed rule update is
9
+ * never reported as success.
10
+ *
11
+ * When `ctx.schedule` is not mounted every method throws
12
+ * TASK_SCHEDULE_UNAVAILABLE and manual task execution keeps working
13
+ * (PRD FR-012).
14
+ */
15
+ import { TaskEngineError, sanitizeMessage } from '../errors.js';
16
+ import { buildSchedulePrompt } from '../prompt/guidance.js';
17
+ import { isOlderThanMinutes } from '../utils/time.js';
18
+ const DEFAULT_TIME_ZONE = 'Asia/Shanghai';
19
+ const DAY_CODES = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'];
20
+ function pad(value) {
21
+ return String(value).padStart(2, '0');
22
+ }
23
+ function assertIntegerInRange(value, min, max, field) {
24
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < min || value > max) {
25
+ throw new TaskEngineError('TASK_INVALID_ARGUMENTS', `${field} 必须是 ${min}–${max} 的整数`);
26
+ }
27
+ return value;
28
+ }
29
+ function buildRruleFromWallClock(timeZone, hour, minute, weeklyDay) {
30
+ const now = new Date();
31
+ const stamp = `${now.getUTCFullYear()}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}T${pad(hour)}${pad(minute)}00`;
32
+ const rule = weeklyDay === undefined ? 'FREQ=DAILY' : `FREQ=WEEKLY;BYDAY=${DAY_CODES[weeklyDay]}`;
33
+ return `DTSTART;TZID=${timeZone}:${stamp}\nRRULE:${rule}`;
34
+ }
35
+ /**
36
+ * Translate validated timing input into the host's documented timing shapes.
37
+ * Only `at`, `every`, `rrule` and `cron` are passed through; daily/weekly are
38
+ * expressed as an equivalent RRULE so the plugin depends on one less host shape.
39
+ */
40
+ export function toHostTiming(input) {
41
+ switch (input.kind) {
42
+ case 'at': {
43
+ const millis = Date.parse(input.at);
44
+ if (!Number.isFinite(millis)) {
45
+ throw new TaskEngineError('TASK_INVALID_ARGUMENTS', 'at 必须是可解析的 RFC3339 时间,例如 2026-12-01T09:00:00+08:00');
46
+ }
47
+ if (millis < Date.now() - 60_000) {
48
+ throw new TaskEngineError('TASK_INVALID_ARGUMENTS', 'at 必须晚于当前时间');
49
+ }
50
+ return { kind: 'at', at: new Date(millis).toISOString() };
51
+ }
52
+ case 'every': {
53
+ const seconds = assertIntegerInRange(input.everySeconds, 30, 30 * 24 * 3600, 'everySeconds');
54
+ return { kind: 'every', every_seconds: seconds };
55
+ }
56
+ case 'rrule': {
57
+ const rule = String(input.rrule ?? '').trim();
58
+ if (!/RRULE:/i.test(rule)) {
59
+ throw new TaskEngineError('TASK_INVALID_ARGUMENTS', 'rrule 必须包含 RRULE: 行');
60
+ }
61
+ if (rule.length > 1000) {
62
+ throw new TaskEngineError('TASK_INVALID_ARGUMENTS', 'rrule 过长(最多 1000 字符)');
63
+ }
64
+ return { kind: 'rrule', rrule: rule };
65
+ }
66
+ case 'cron': {
67
+ const expression = String(input.expression ?? '').trim();
68
+ if (expression.split(/\s+/).length !== 5) {
69
+ throw new TaskEngineError('TASK_INVALID_ARGUMENTS', 'cron 表达式必须是 5 段(分 时 日 月 周)');
70
+ }
71
+ const timeZone = input.timeZone ?? DEFAULT_TIME_ZONE;
72
+ return { kind: 'cron', cron: { expression, time_zone: timeZone } };
73
+ }
74
+ case 'daily': {
75
+ const hour = assertIntegerInRange(input.hour, 0, 23, 'hour');
76
+ const minute = assertIntegerInRange(input.minute, 0, 59, 'minute');
77
+ const timeZone = input.timeZone ?? DEFAULT_TIME_ZONE;
78
+ return { kind: 'rrule', rrule: buildRruleFromWallClock(timeZone, hour, minute) };
79
+ }
80
+ case 'weekly': {
81
+ const dayOfWeek = assertIntegerInRange(input.dayOfWeek, 0, 6, 'dayOfWeek');
82
+ const hour = assertIntegerInRange(input.hour, 0, 23, 'hour');
83
+ const minute = assertIntegerInRange(input.minute, 0, 59, 'minute');
84
+ const timeZone = input.timeZone ?? DEFAULT_TIME_ZONE;
85
+ return { kind: 'rrule', rrule: buildRruleFromWallClock(timeZone, hour, minute, dayOfWeek) };
86
+ }
87
+ default:
88
+ throw new TaskEngineError('TASK_INVALID_ARGUMENTS', '不支持的 timing.kind');
89
+ }
90
+ }
91
+ export function describeTiming(timing) {
92
+ const value = timing;
93
+ switch (value.kind) {
94
+ case 'at':
95
+ return `一次性 · ${String(value.at ?? '')}`;
96
+ case 'every':
97
+ return `间隔 · 每 ${String(value.everySeconds ?? value.every_seconds ?? '?')} 秒`;
98
+ case 'rrule':
99
+ return `重复规则 · ${String(value.rrule ?? '').replace(/\n/g, ' ')}`;
100
+ case 'cron':
101
+ return `Cron · ${String(value.cron?.expression ?? value.expression ?? '')}`;
102
+ case 'daily':
103
+ return `每天 · ${pad(Number(value.hour ?? 0))}:${pad(Number(value.minute ?? 0))} (${String(value.timeZone ?? DEFAULT_TIME_ZONE)})`;
104
+ case 'weekly':
105
+ return `每周 ${DAY_CODES[Number(value.dayOfWeek ?? 0)] ?? '?'} · ${pad(Number(value.hour ?? 0))}:${pad(Number(value.minute ?? 0))}`;
106
+ default:
107
+ return String(value.kind ?? 'unknown');
108
+ }
109
+ }
110
+ export class ScheduleAdapter {
111
+ schedule;
112
+ log;
113
+ constructor(schedule, log) {
114
+ this.schedule = schedule;
115
+ this.log = log;
116
+ }
117
+ get available() {
118
+ return typeof this.schedule?.create === 'function' && typeof this.schedule?.edit === 'function';
119
+ }
120
+ require() {
121
+ if (!this.available || !this.schedule) {
122
+ throw new TaskEngineError('TASK_SCHEDULE_UNAVAILABLE', '当前宿主未挂载 Schedule 能力,定时任务不可用;手动任务仍可正常执行');
123
+ }
124
+ return this.schedule;
125
+ }
126
+ async create(input) {
127
+ const schedule = this.require();
128
+ const hostTiming = toHostTiming(input.timing);
129
+ const title = `后台任务 · ${input.taskTitle}`.slice(0, 120);
130
+ const prompt = buildSchedulePrompt({ taskId: input.taskId, taskTitle: input.taskTitle });
131
+ try {
132
+ const entry = await schedule.create({
133
+ title,
134
+ prompt,
135
+ timing: hostTiming,
136
+ target: { kind: 'session', sessionId: input.sessionId },
137
+ }, input.sessionId);
138
+ if (!entry || typeof entry.id !== 'string' || entry.id.length === 0) {
139
+ throw new TaskEngineError('TASK_SCHEDULE_FAILED', 'Schedule 创建未返回有效 scheduleId');
140
+ }
141
+ return { scheduleId: entry.id, entry };
142
+ }
143
+ catch (error) {
144
+ throw this.wrap('创建定时规则', error);
145
+ }
146
+ }
147
+ async update(input) {
148
+ const schedule = this.require();
149
+ const patch = {};
150
+ if (input.patch.timing)
151
+ patch.timing = toHostTiming(input.patch.timing);
152
+ if (input.patch.title)
153
+ patch.title = input.patch.title.slice(0, 120);
154
+ if (input.patch.prompt)
155
+ patch.prompt = input.patch.prompt;
156
+ if (input.patch.active !== undefined)
157
+ patch.active = input.patch.active;
158
+ try {
159
+ const result = await schedule.edit({ id: input.scheduleId, action: 'update', patch }, input.sessionId);
160
+ if (result.code) {
161
+ throw new TaskEngineError('TASK_SCHEDULE_FAILED', `Schedule 更新失败:${String(result.code)}`);
162
+ }
163
+ return result;
164
+ }
165
+ catch (error) {
166
+ throw this.wrap('更新定时规则', error);
167
+ }
168
+ }
169
+ async remove(scheduleId, sessionId) {
170
+ const schedule = this.require();
171
+ try {
172
+ const result = await schedule.edit({ id: scheduleId, action: 'delete' }, sessionId);
173
+ if (result.deleted)
174
+ return { deleted: true, alreadyGone: false };
175
+ const code = result.code;
176
+ if (code === 'schedule_not_found')
177
+ return { deleted: false, alreadyGone: true };
178
+ throw new TaskEngineError('TASK_SCHEDULE_FAILED', `Schedule 删除失败:${code ?? 'unknown'}`);
179
+ }
180
+ catch (error) {
181
+ throw this.wrap('删除定时规则', error);
182
+ }
183
+ }
184
+ async view(scheduleId) {
185
+ const schedule = this.require();
186
+ const result = (await schedule.view({ id: scheduleId }));
187
+ if (result.code === 'schedule_not_found')
188
+ return undefined;
189
+ return result;
190
+ }
191
+ async runNow(scheduleId) {
192
+ const schedule = this.require();
193
+ try {
194
+ const result = await schedule.run({ id: scheduleId });
195
+ if (result.code === 'schedule_execution_pending') {
196
+ return { pending: true };
197
+ }
198
+ return { pending: false, entry: result };
199
+ }
200
+ catch (error) {
201
+ throw this.wrap('立即运行定时规则', error);
202
+ }
203
+ }
204
+ wrap(action, error) {
205
+ if (error instanceof TaskEngineError)
206
+ return error;
207
+ const message = error instanceof Error ? error.message : String(error);
208
+ if (/schedule\/input-invalid|input-invalid/.test(message)) {
209
+ return new TaskEngineError('TASK_SCHEDULE_FAILED', `${action}失败:Schedule 认为参数非法(${sanitizeMessage(message, 200)})`);
210
+ }
211
+ if (/schedule\/target-archived|target-archived/.test(message)) {
212
+ return new TaskEngineError('TASK_SCHEDULE_FAILED', `${action}失败:目标 Session 已归档,请在本会话重新创建定时规则`);
213
+ }
214
+ return new TaskEngineError('TASK_SCHEDULE_FAILED', `${action}失败:${sanitizeMessage(message, 300)}`);
215
+ }
216
+ }
217
+ /** Loose staleness helper used by diagnostics (kept here to avoid cycles). */
218
+ export function scheduleLooksStale(scheduledAt, minutes) {
219
+ return isOlderThanMinutes(scheduledAt, minutes);
220
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Task template service: create / list / get / update / archive and the
3
+ * Schedule linkage (PRD 4.2, 5.1, FR-001, FR-002, FR-003).
4
+ *
5
+ * All persistence goes through Repository; all state changes are audited; every
6
+ * entry point takes the caller SessionId and verifies ownership first.
7
+ */
8
+ import { z } from 'zod';
9
+ import type { EngineConfig } from '../config.js';
10
+ import { type RunRecord, type ScheduleRef, type TaskRecord, type TaskStatus } from '../domain/records.js';
11
+ import type { Repository } from '../storage/repository.js';
12
+ import type { AuditTrail } from './audit.js';
13
+ import { type ScheduleAdapter, type TimingInput } from './schedule-adapter.js';
14
+ declare const stepInputSchema: z.ZodObject<{
15
+ title: z.ZodString;
16
+ instruction: z.ZodString;
17
+ completionCriteria: z.ZodOptional<z.ZodString>;
18
+ required: z.ZodOptional<z.ZodBoolean>;
19
+ }, "strip", z.ZodTypeAny, {
20
+ title: string;
21
+ instruction: string;
22
+ completionCriteria?: string | undefined;
23
+ required?: boolean | undefined;
24
+ }, {
25
+ title: string;
26
+ instruction: string;
27
+ completionCriteria?: string | undefined;
28
+ required?: boolean | undefined;
29
+ }>;
30
+ export type StepInput = z.infer<typeof stepInputSchema>;
31
+ export interface CreateTaskInput {
32
+ sessionId: string;
33
+ title?: string;
34
+ description?: string;
35
+ steps?: StepInput[];
36
+ copyFromTaskId?: string;
37
+ }
38
+ export interface UpdateTaskInput {
39
+ sessionId: string;
40
+ taskId: string;
41
+ expectedRevision: number;
42
+ title?: string;
43
+ description?: string;
44
+ steps?: StepInput[];
45
+ status?: 'active' | 'paused';
46
+ }
47
+ export interface ListTasksInput {
48
+ sessionId: string;
49
+ status?: TaskStatus;
50
+ query?: string;
51
+ limit?: number;
52
+ cursor?: string;
53
+ }
54
+ export interface TaskSummaryRow {
55
+ taskId: string;
56
+ title: string;
57
+ status: TaskStatus;
58
+ revision: number;
59
+ stepCount: number;
60
+ updatedAt: string;
61
+ schedule: {
62
+ scheduleId: string;
63
+ state: ScheduleRef['state'];
64
+ timing: string;
65
+ } | null;
66
+ lastRun: {
67
+ runId: string;
68
+ status: string;
69
+ startedAt: string;
70
+ } | null;
71
+ }
72
+ export declare class TaskService {
73
+ private readonly repo;
74
+ private readonly config;
75
+ private readonly audit;
76
+ private readonly schedules;
77
+ private readonly now;
78
+ constructor(repo: Repository, config: EngineConfig, audit: AuditTrail, schedules: ScheduleAdapter, now?: () => string);
79
+ create(input: CreateTaskInput): Promise<TaskRecord>;
80
+ private normaliseSteps;
81
+ list(input: ListTasksInput): {
82
+ items: TaskSummaryRow[];
83
+ nextCursor?: string;
84
+ };
85
+ private toSummaryRow;
86
+ get(owner: string, taskId: string, options?: {
87
+ includeRuns?: boolean;
88
+ }): {
89
+ task: TaskRecord;
90
+ recentRuns: RunRecord[];
91
+ };
92
+ update(input: UpdateTaskInput): Promise<TaskRecord>;
93
+ private applyStatusWithSchedule;
94
+ private patchScheduleRef;
95
+ archive(input: {
96
+ sessionId: string;
97
+ taskId: string;
98
+ expectedRevision: number;
99
+ }): Promise<TaskRecord>;
100
+ scheduleCreate(input: {
101
+ sessionId: string;
102
+ taskId: string;
103
+ timing: TimingInput;
104
+ }): Promise<TaskRecord & {
105
+ scheduleId: string;
106
+ }>;
107
+ scheduleUpdate(input: {
108
+ sessionId: string;
109
+ taskId: string;
110
+ timing: TimingInput;
111
+ }): Promise<TaskRecord>;
112
+ scheduleSetActive(input: {
113
+ sessionId: string;
114
+ taskId: string;
115
+ active: boolean;
116
+ }): Promise<{
117
+ task: TaskRecord;
118
+ changed: boolean;
119
+ }>;
120
+ scheduleDelete(input: {
121
+ sessionId: string;
122
+ taskId: string;
123
+ }): Promise<{
124
+ task: TaskRecord;
125
+ alreadyGone: boolean;
126
+ }>;
127
+ scheduleStatus(input: {
128
+ sessionId: string;
129
+ taskId: string;
130
+ }): Promise<{
131
+ ref: ScheduleRef | null;
132
+ live: {
133
+ status?: string;
134
+ scheduledAt?: string;
135
+ title?: string;
136
+ } | null;
137
+ available: boolean;
138
+ }>;
139
+ scheduleRunNow(input: {
140
+ sessionId: string;
141
+ taskId: string;
142
+ }): Promise<{
143
+ pending: boolean;
144
+ }>;
145
+ }
146
+ export {};