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

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 +77 -0
  2. package/LICENSE +21 -0
  3. package/README.md +255 -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 +200 -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,194 @@
1
+ /**
2
+ * Repository layer: the only place that talks to StorageDomain tables.
3
+ *
4
+ * Rules encoded here (PRD 7.3, 8.4):
5
+ * - records are immutable; every write produces a new validated object
6
+ * - read-modify-write goes through `table.update`, whose mutator runs inside
7
+ * the domain's per-key chain, so two concurrent calls cannot interleave
8
+ * - ownership is verified on read (`requireOwnedTask` / `requireOwnedRun`)
9
+ * - step records are keyed `runId/stepId`: one row per (runId, stepId)
10
+ */
11
+ import { TaskEngineError } from '../errors.js';
12
+ import { TABLES, globalStateSchema, runRecordSchema, runStepRecordSchema, stepKey, taskRecordSchema, } from '../domain/records.js';
13
+ import { META_KEY } from './spec.js';
14
+ export class Repository {
15
+ domain;
16
+ now;
17
+ tasks;
18
+ runs;
19
+ steps;
20
+ meta;
21
+ constructor(domain, now = () => new Date().toISOString()) {
22
+ this.domain = domain;
23
+ this.now = now;
24
+ this.tasks = domain.table(TABLES.tasks);
25
+ this.runs = domain.table(TABLES.runs);
26
+ this.steps = domain.table(TABLES.steps);
27
+ this.meta = domain.table('meta');
28
+ }
29
+ // ----------------------------------------------------------------- tasks
30
+ getTask(taskId) {
31
+ return this.tasks.get(taskId);
32
+ }
33
+ requireTask(taskId) {
34
+ const task = this.tasks.get(taskId);
35
+ if (!task) {
36
+ throw new TaskEngineError('TASK_NOT_FOUND', `任务 ${taskId} 不存在或已被清理`);
37
+ }
38
+ return task;
39
+ }
40
+ /**
41
+ * Ownership gate for every tool entry point (PRD 10.1). A record owned by a
42
+ * different Session is reported as "not found" so the error cannot be used to
43
+ * probe another Session's data.
44
+ */
45
+ requireOwnedTask(taskId, sessionId) {
46
+ const task = this.tasks.get(taskId);
47
+ if (!task || task.ownerSessionId !== sessionId) {
48
+ throw new TaskEngineError('TASK_NOT_FOUND', `任务 ${taskId} 不存在或不属于当前会话`);
49
+ }
50
+ return task;
51
+ }
52
+ listTasks() {
53
+ return [...this.tasks.entries()].map(([, task]) => task);
54
+ }
55
+ listTasksByOwner(ownerSessionId) {
56
+ return this.listTasks().filter((task) => task.ownerSessionId === ownerSessionId);
57
+ }
58
+ countUnarchivedTasks(ownerSessionId) {
59
+ return this.listTasksByOwner(ownerSessionId).filter((task) => task.status !== 'archived').length;
60
+ }
61
+ async insertTask(record) {
62
+ const parsed = taskRecordSchema.parse(record);
63
+ await this.tasks.put(parsed.taskId, parsed);
64
+ return parsed;
65
+ }
66
+ /**
67
+ * Atomic task mutation with optimistic locking. The revision check runs inside
68
+ * the domain's update chain, so a stale `expectedRevision` can never win.
69
+ */
70
+ async mutateTask(taskId, expectedRevision, mutate) {
71
+ try {
72
+ return await this.tasks.update(taskId, (current) => {
73
+ if (expectedRevision !== undefined && current.revision !== expectedRevision) {
74
+ throw new TaskEngineError('TASK_REVISION_CONFLICT', `任务 ${taskId} 的 revision 已变化:期望 ${expectedRevision},实际 ${current.revision};请先 task_get 再重试`, { retryable: true, details: { expectedRevision, actualRevision: current.revision } });
75
+ }
76
+ const next = mutate({ ...current });
77
+ return taskRecordSchema.parse({ ...next, updatedAt: next.updatedAt || this.now() });
78
+ });
79
+ }
80
+ catch (error) {
81
+ throw this.normaliseWriteError(error, 'TASK_NOT_FOUND', `任务 ${taskId} 不存在或已被清理`);
82
+ }
83
+ }
84
+ // ------------------------------------------------------------------ runs
85
+ getRun(runId) {
86
+ return this.runs.get(runId);
87
+ }
88
+ requireRun(runId) {
89
+ const run = this.runs.get(runId);
90
+ if (!run)
91
+ throw new TaskEngineError('TASK_RUN_NOT_FOUND', `运行 ${runId} 不存在或已被清理`);
92
+ return run;
93
+ }
94
+ requireOwnedRun(runId, sessionId) {
95
+ const run = this.runs.get(runId);
96
+ if (!run || run.taskOwnerSessionId !== sessionId) {
97
+ throw new TaskEngineError('TASK_RUN_NOT_FOUND', `运行 ${runId} 不存在或不属于当前会话`);
98
+ }
99
+ return run;
100
+ }
101
+ listRuns() {
102
+ return [...this.runs.entries()].map(([, run]) => run);
103
+ }
104
+ listRunsByTask(taskId) {
105
+ return this.listRuns()
106
+ .filter((run) => run.taskId === taskId)
107
+ .sort((a, b) => (a.startedAt < b.startedAt ? 1 : a.startedAt > b.startedAt ? -1 : a.runId < b.runId ? 1 : -1));
108
+ }
109
+ listActiveRunsByOwner(ownerSessionId) {
110
+ return this.listRuns().filter((run) => run.taskOwnerSessionId === ownerSessionId && (run.status === 'queued' || run.status === 'running'));
111
+ }
112
+ listActiveRunsByTask(taskId) {
113
+ return this.listRuns().filter((run) => run.taskId === taskId && (run.status === 'queued' || run.status === 'running'));
114
+ }
115
+ findRunByIdempotencyKey(taskId, idempotencyKey) {
116
+ return this.listRunsByTask(taskId).find((run) => run.idempotencyKey === idempotencyKey);
117
+ }
118
+ async insertRun(record) {
119
+ const parsed = runRecordSchema.parse(record);
120
+ await this.runs.put(parsed.runId, parsed);
121
+ return parsed;
122
+ }
123
+ async mutateRun(runId, mutate) {
124
+ try {
125
+ return await this.runs.update(runId, (current) => {
126
+ const next = mutate({ ...current });
127
+ return runRecordSchema.parse({ ...next, updatedAt: this.now() });
128
+ });
129
+ }
130
+ catch (error) {
131
+ throw this.normaliseWriteError(error, 'TASK_RUN_NOT_FOUND', `运行 ${runId} 不存在或已被清理`);
132
+ }
133
+ }
134
+ // ----------------------------------------------------------------- steps
135
+ getStep(runId, stepId) {
136
+ return this.steps.get(stepKey(runId, stepId));
137
+ }
138
+ listSteps(runId) {
139
+ return [...this.steps.entries()]
140
+ .filter(([key]) => key.startsWith(`${runId}/`))
141
+ .map(([, step]) => step)
142
+ .sort((a, b) => a.order - b.order);
143
+ }
144
+ async putStep(record) {
145
+ const parsed = runStepRecordSchema.parse(record);
146
+ await this.steps.put(stepKey(parsed.runId, parsed.stepId), parsed);
147
+ return parsed;
148
+ }
149
+ /**
150
+ * Steps are written before the run record on every transition, so a crash
151
+ * leaves the run short of its terminal write (recoverable: the startup scan
152
+ * marks it interrupted) rather than reporting progress that was never stored.
153
+ */
154
+ async putSteps(records) {
155
+ for (const record of records) {
156
+ await this.putStep(record);
157
+ }
158
+ }
159
+ async mutateStep(runId, stepId, mutate) {
160
+ const key = stepKey(runId, stepId);
161
+ try {
162
+ return await this.steps.update(key, (current) => {
163
+ const next = mutate({ ...current });
164
+ return runStepRecordSchema.parse({ ...next, updatedAt: this.now() });
165
+ });
166
+ }
167
+ catch (error) {
168
+ throw this.normaliseWriteError(error, 'TASK_STEP_ORDER_INVALID', `步骤 ${stepId} 不属于运行 ${runId}`);
169
+ }
170
+ }
171
+ async deleteRunCascade(runId) {
172
+ const stepKeys = [...this.steps.keys()].filter((key) => key.startsWith(`${runId}/`));
173
+ const stepsDeleted = stepKeys.length > 0 ? await this.steps.deleteMany(stepKeys) : 0;
174
+ const runDeleted = await this.runs.delete(runId);
175
+ return { stepsDeleted, runDeleted };
176
+ }
177
+ // ------------------------------------------------------------------ meta
178
+ readMetaState() {
179
+ return this.meta.get(META_KEY);
180
+ }
181
+ async writeMetaState(state) {
182
+ await this.meta.put(META_KEY, globalStateSchema.parse(state));
183
+ }
184
+ // --------------------------------------------------------------- helpers
185
+ normaliseWriteError(error, notFoundCode, notFoundMessage) {
186
+ if (error instanceof TaskEngineError)
187
+ return error;
188
+ const message = error instanceof Error ? error.message : String(error);
189
+ if (/missing-key/.test(message)) {
190
+ return new TaskEngineError(notFoundCode, notFoundMessage);
191
+ }
192
+ return error;
193
+ }
194
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * StorageDomain declaration, migration runner and startup integrity checks
3
+ * (PRD 4.10, 7.3, 7.4, FR-010, FR-012).
4
+ *
5
+ * `ctx.storageDomain` is the only persistence backend. There is deliberately no
6
+ * in-memory fallback: without a StorageDomain the engine refuses to start
7
+ * (PRD FR-012, 16.3).
8
+ */
9
+ import type { DomainLike } from '../host.js';
10
+ import { type GlobalState, type RunRecord, type RunStepRecord, type TaskRecord } from '../domain/records.js';
11
+ export interface DomainSpecLike {
12
+ name: string;
13
+ version: number;
14
+ layout?: 'single' | 'per-record';
15
+ compatibleVersions?: readonly number[];
16
+ tables: Record<string, {
17
+ valueSchema: {
18
+ parse(value: unknown): unknown;
19
+ safeParse(value: unknown): {
20
+ success: boolean;
21
+ };
22
+ };
23
+ }>;
24
+ }
25
+ /**
26
+ * The domain descriptor.
27
+ *
28
+ * Four tables, not three: `meta` holds the schema version, the idempotent
29
+ * migration ledger and recovery/prune timestamps (PRD 7.4 requires the version
30
+ * and an "already applied" marker to be persisted; the PRD 4.10 table list
31
+ * covers the model tables only).
32
+ */
33
+ /**
34
+ * Host rule for domain and table names
35
+ * (`@deepseek-ai/dsh-storage` UNIT_NAME_RE). Hyphens are rejected, which is why
36
+ * DOMAIN_NAME uses underscores.
37
+ */
38
+ export declare const UNIT_NAME_PATTERN: RegExp;
39
+ export declare function createDomainSpec(): DomainSpecLike;
40
+ export declare const META_KEY = "global";
41
+ export interface DomainTables {
42
+ tasks: {
43
+ get(key: string): TaskRecord | undefined;
44
+ };
45
+ runs: {
46
+ get(key: string): RunRecord | undefined;
47
+ };
48
+ steps: {
49
+ get(key: string): RunStepRecord | undefined;
50
+ };
51
+ meta: {
52
+ get(key: string): GlobalState | undefined;
53
+ put(key: string, value: GlobalState): Promise<void>;
54
+ };
55
+ }
56
+ export interface MigrationContext {
57
+ domain: DomainLike;
58
+ readMeta(): GlobalState | undefined;
59
+ writeMeta(state: GlobalState): Promise<void>;
60
+ }
61
+ export interface Migration {
62
+ id: string;
63
+ description: string;
64
+ /** Must be safe to re-run: the ledger marker is written only after success. */
65
+ apply(context: MigrationContext): Promise<void>;
66
+ }
67
+ /**
68
+ * Ordered migrations. v1 has no historical shape to migrate; the runner is in
69
+ * place so a future schema change is a data edit plus one entry here.
70
+ */
71
+ export declare const MIGRATIONS: readonly Migration[];
72
+ export declare function createMigrationContext(domain: DomainLike): MigrationContext;
73
+ export interface MigrationReport {
74
+ applied: string[];
75
+ alreadyApplied: string[];
76
+ schemaVersion: number;
77
+ }
78
+ /**
79
+ * Apply pending migrations exactly once each. A failed migration throws: the
80
+ * caller then refuses to open the domain for writes (PRD 7.4).
81
+ */
82
+ export declare function runMigrations(domain: DomainLike, migrations?: readonly Migration[], now?: () => string): Promise<MigrationReport>;
83
+ export declare function readMeta(domain: DomainLike): GlobalState | undefined;
84
+ export declare function writeMeta(domain: DomainLike, patch: Partial<GlobalState>): Promise<void>;
85
+ export interface IntegrityReport {
86
+ ok: boolean;
87
+ runCount: number;
88
+ stepCount: number;
89
+ taskCount: number;
90
+ issues: string[];
91
+ }
92
+ /**
93
+ * Startup verification (PRD 7.3): every run references an existing task and
94
+ * every step belongs to an existing run with a stepId present in the run's
95
+ * template snapshot. Issues are reported, never silently repaired.
96
+ */
97
+ export declare function verifyIntegrity(domain: DomainLike): IntegrityReport;
@@ -0,0 +1,149 @@
1
+ /**
2
+ * StorageDomain declaration, migration runner and startup integrity checks
3
+ * (PRD 4.10, 7.3, 7.4, FR-010, FR-012).
4
+ *
5
+ * `ctx.storageDomain` is the only persistence backend. There is deliberately no
6
+ * in-memory fallback: without a StorageDomain the engine refuses to start
7
+ * (PRD FR-012, 16.3).
8
+ */
9
+ import { TaskEngineError } from '../errors.js';
10
+ import { DOMAIN_NAME, SCHEMA_VERSION, TABLES, globalStateSchema, runRecordSchema, runStepRecordSchema, taskRecordSchema, } from '../domain/records.js';
11
+ /**
12
+ * The domain descriptor.
13
+ *
14
+ * Four tables, not three: `meta` holds the schema version, the idempotent
15
+ * migration ledger and recovery/prune timestamps (PRD 7.4 requires the version
16
+ * and an "already applied" marker to be persisted; the PRD 4.10 table list
17
+ * covers the model tables only).
18
+ */
19
+ /**
20
+ * Host rule for domain and table names
21
+ * (`@deepseek-ai/dsh-storage` UNIT_NAME_RE). Hyphens are rejected, which is why
22
+ * DOMAIN_NAME uses underscores.
23
+ */
24
+ export const UNIT_NAME_PATTERN = /^[a-z][a-z0-9_]*$/;
25
+ export function createDomainSpec() {
26
+ return {
27
+ name: DOMAIN_NAME,
28
+ version: SCHEMA_VERSION,
29
+ tables: {
30
+ [TABLES.tasks]: { valueSchema: taskRecordSchema },
31
+ [TABLES.runs]: { valueSchema: runRecordSchema },
32
+ [TABLES.steps]: { valueSchema: runStepRecordSchema },
33
+ meta: { valueSchema: globalStateSchema },
34
+ },
35
+ };
36
+ }
37
+ export const META_KEY = 'global';
38
+ /**
39
+ * Ordered migrations. v1 has no historical shape to migrate; the runner is in
40
+ * place so a future schema change is a data edit plus one entry here.
41
+ */
42
+ export const MIGRATIONS = [];
43
+ export function createMigrationContext(domain) {
44
+ const meta = domain.table('meta');
45
+ return {
46
+ domain,
47
+ readMeta: () => meta.get(META_KEY),
48
+ writeMeta: async (state) => {
49
+ await meta.put(META_KEY, globalStateSchema.parse(state));
50
+ },
51
+ };
52
+ }
53
+ /**
54
+ * Apply pending migrations exactly once each. A failed migration throws: the
55
+ * caller then refuses to open the domain for writes (PRD 7.4).
56
+ */
57
+ export async function runMigrations(domain, migrations = MIGRATIONS, now = () => new Date().toISOString()) {
58
+ const context = createMigrationContext(domain);
59
+ const existing = context.readMeta();
60
+ if (existing && existing.schemaVersion > SCHEMA_VERSION) {
61
+ throw new TaskEngineError('TASK_STORAGE_ERROR', `存储版本 ${existing.schemaVersion} 高于插件支持的 ${SCHEMA_VERSION},请升级插件而不是降级`);
62
+ }
63
+ const state = existing ?? {
64
+ schemaVersion: SCHEMA_VERSION,
65
+ appliedMigrations: {},
66
+ };
67
+ const applied = [];
68
+ const alreadyApplied = [];
69
+ for (const migration of migrations) {
70
+ if (state.appliedMigrations[migration.id]) {
71
+ alreadyApplied.push(migration.id);
72
+ continue;
73
+ }
74
+ try {
75
+ await migration.apply(context);
76
+ }
77
+ catch (error) {
78
+ const message = error instanceof Error ? error.message : String(error);
79
+ throw new TaskEngineError('TASK_STORAGE_ERROR', `迁移 ${migration.id} 失败,已停止写入新结构:${message}`);
80
+ }
81
+ applied.push(migration.id);
82
+ state.appliedMigrations[migration.id] = now();
83
+ // Marker is persisted only after the migration body succeeded, so a crash
84
+ // mid-migration re-runs an idempotent migration instead of skipping it.
85
+ await context.writeMeta({ ...state, schemaVersion: SCHEMA_VERSION });
86
+ }
87
+ if (applied.length === 0) {
88
+ const next = { ...state, schemaVersion: SCHEMA_VERSION };
89
+ if (!existing || existing.schemaVersion !== SCHEMA_VERSION || Object.keys(state.appliedMigrations).length !== Object.keys(existing.appliedMigrations).length) {
90
+ await context.writeMeta(next);
91
+ }
92
+ }
93
+ return { applied, alreadyApplied, schemaVersion: SCHEMA_VERSION };
94
+ }
95
+ export function readMeta(domain) {
96
+ return domain.table('meta').get(META_KEY);
97
+ }
98
+ export async function writeMeta(domain, patch) {
99
+ const meta = domain.table('meta');
100
+ const current = meta.get(META_KEY) ?? { schemaVersion: SCHEMA_VERSION, appliedMigrations: {} };
101
+ await meta.put(META_KEY, globalStateSchema.parse({ ...current, ...patch, schemaVersion: current.schemaVersion }));
102
+ }
103
+ /**
104
+ * Startup verification (PRD 7.3): every run references an existing task and
105
+ * every step belongs to an existing run with a stepId present in the run's
106
+ * template snapshot. Issues are reported, never silently repaired.
107
+ */
108
+ export function verifyIntegrity(domain) {
109
+ const tasks = domain.table(TABLES.tasks);
110
+ const runs = domain.table(TABLES.runs);
111
+ const steps = domain.table(TABLES.steps);
112
+ const issues = [];
113
+ let runCount = 0;
114
+ let stepCount = 0;
115
+ let taskCount = 0;
116
+ for (const [taskId, task] of tasks.entries()) {
117
+ taskCount += 1;
118
+ if (task.taskId !== taskId)
119
+ issues.push(`任务记录键不一致: ${taskId} != ${task.taskId}`);
120
+ }
121
+ for (const run of runs.entries()) {
122
+ runCount += 1;
123
+ const [, record] = run;
124
+ if (!tasks.get(record.taskId)) {
125
+ issues.push(`运行 ${record.runId} 引用了不存在的任务 ${record.taskId}`);
126
+ }
127
+ if (!Array.isArray(record.templateSnapshot?.steps) || record.templateSnapshot.steps.length === 0) {
128
+ issues.push(`运行 ${record.runId} 缺少模板快照`);
129
+ }
130
+ }
131
+ const knownStepIds = new Map();
132
+ for (const [runId, run] of runs.entries()) {
133
+ knownStepIds.set(runId, new Set(run.templateSnapshot.steps.map((step) => step.stepId)));
134
+ }
135
+ for (const [key, step] of steps.entries()) {
136
+ stepCount += 1;
137
+ const sep = key.indexOf('/');
138
+ const runId = sep >= 0 ? key.slice(0, sep) : '';
139
+ const allowed = knownStepIds.get(runId);
140
+ if (!allowed) {
141
+ issues.push(`步骤记录 ${key} 引用了不存在的运行`);
142
+ continue;
143
+ }
144
+ if (!allowed.has(step.stepId)) {
145
+ issues.push(`步骤记录 ${key} 的 stepId 不在运行快照内`);
146
+ }
147
+ }
148
+ return { ok: issues.length === 0, runCount, stepCount, taskCount, issues };
149
+ }
@@ -0,0 +1,14 @@
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 type { ToolDefinitionLike } from '../host.js';
6
+ import type { TaskEngine } from '../services/engine.js';
7
+ export declare function createRunTools(engine: () => TaskEngine): ToolDefinitionLike[];
8
+ /** Progress text helper exported for the diagnostics tool. */
9
+ export declare function describeRunProgress(run: {
10
+ status: string;
11
+ progress: number;
12
+ requiredCompleted: number;
13
+ requiredTotal: number;
14
+ }): string;