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.
- package/CHANGELOG.md +91 -0
- package/LICENSE +21 -0
- package/README.md +263 -2
- package/README.zh.md +179 -0
- package/cordis.patch.yml +20 -0
- package/dist/config.d.ts +86 -0
- package/dist/config.js +106 -0
- package/dist/domain/records.d.ts +543 -0
- package/dist/domain/records.js +135 -0
- package/dist/domain/state.d.ts +61 -0
- package/dist/domain/state.js +128 -0
- package/dist/errors.d.ts +38 -0
- package/dist/errors.js +99 -0
- package/dist/host.d.ts +165 -0
- package/dist/host.js +56 -0
- package/dist/index.d.ts +60 -0
- package/dist/index.js +78 -0
- package/dist/prompt/guidance.d.ts +30 -0
- package/dist/prompt/guidance.js +62 -0
- package/dist/services/audit.d.ts +39 -0
- package/dist/services/audit.js +48 -0
- package/dist/services/engine.d.ts +435 -0
- package/dist/services/engine.js +150 -0
- package/dist/services/run-service.d.ts +145 -0
- package/dist/services/run-service.js +569 -0
- package/dist/services/schedule-adapter.d.ts +92 -0
- package/dist/services/schedule-adapter.js +220 -0
- package/dist/services/task-service.d.ts +146 -0
- package/dist/services/task-service.js +490 -0
- package/dist/storage/repository.d.ts +65 -0
- package/dist/storage/repository.js +194 -0
- package/dist/storage/spec.d.ts +97 -0
- package/dist/storage/spec.js +149 -0
- package/dist/tools/run-tools.d.ts +14 -0
- package/dist/tools/run-tools.js +402 -0
- package/dist/tools/schedule-tool.d.ts +11 -0
- package/dist/tools/schedule-tool.js +238 -0
- package/dist/tools/shared.d.ts +108 -0
- package/dist/tools/shared.js +278 -0
- package/dist/tools/task-tools.d.ts +7 -0
- package/dist/tools/task-tools.js +321 -0
- package/dist/utils/id.d.ts +8 -0
- package/dist/utils/id.js +29 -0
- package/dist/utils/page.d.ts +36 -0
- package/dist/utils/page.js +71 -0
- package/dist/utils/text.d.ts +20 -0
- package/dist/utils/text.js +46 -0
- package/dist/utils/time.d.ts +7 -0
- package/dist/utils/time.js +38 -0
- package/docs/API-COMPATIBILITY-AUDIT.md +203 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/TEST-REPORT.md +232 -0
- package/docs/preview.svg +68 -0
- package/icon.svg +23 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +71 -4
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persisted record schemas (PRD 5.x, 7.3).
|
|
3
|
+
*
|
|
4
|
+
* Everything written to the StorageDomain is validated by these zod schemas
|
|
5
|
+
* before it is stored and again when the domain is opened, so a corrupted or
|
|
6
|
+
* hand-edited record fails loudly instead of silently degrading behaviour.
|
|
7
|
+
*/
|
|
8
|
+
import { z } from 'zod';
|
|
9
|
+
/** Bumped only when the persisted shape changes; drives the migration runner. */
|
|
10
|
+
export const SCHEMA_VERSION = 1;
|
|
11
|
+
/**
|
|
12
|
+
* StorageDomain unit name.
|
|
13
|
+
*
|
|
14
|
+
* The host's `UNIT_NAME_RE` is `/^[a-z][a-z0-9_]*$/` (verified against the
|
|
15
|
+
* installed @deepseek-ai/dsh-storage), so the domain id uses underscores even
|
|
16
|
+
* though the npm package name uses hyphens. The two are deliberately different
|
|
17
|
+
* values: the package name is the npm identity, this is the storage unit.
|
|
18
|
+
*/
|
|
19
|
+
export const DOMAIN_NAME = 'dsh_background_task_engine';
|
|
20
|
+
export const TASK_STATUSES = ['active', 'paused', 'archived'];
|
|
21
|
+
export const RUN_STATUSES = [
|
|
22
|
+
'queued',
|
|
23
|
+
'running',
|
|
24
|
+
'blocked',
|
|
25
|
+
'succeeded',
|
|
26
|
+
'failed',
|
|
27
|
+
'interrupted',
|
|
28
|
+
'skipped',
|
|
29
|
+
];
|
|
30
|
+
export const STEP_STATUSES = ['pending', 'running', 'completed', 'failed', 'skipped'];
|
|
31
|
+
export const TRIGGER_TYPES = ['manual', 'schedule'];
|
|
32
|
+
const idSchema = z.string().min(4).max(64);
|
|
33
|
+
const timestampSchema = z.string().min(20).max(40);
|
|
34
|
+
export const stepErrorSchema = z.object({
|
|
35
|
+
code: z.string().min(1).max(64),
|
|
36
|
+
message: z.string().min(1).max(2000),
|
|
37
|
+
});
|
|
38
|
+
export const stepDefinitionSchema = z.object({
|
|
39
|
+
stepId: idSchema,
|
|
40
|
+
title: z.string().min(1).max(120),
|
|
41
|
+
instruction: z.string().min(1).max(8000),
|
|
42
|
+
completionCriteria: z.string().max(2000).optional(),
|
|
43
|
+
order: z.number().int().min(1).max(10),
|
|
44
|
+
required: z.boolean(),
|
|
45
|
+
});
|
|
46
|
+
export const scheduleRefSchema = z.object({
|
|
47
|
+
scheduleId: z.string().min(1).max(128),
|
|
48
|
+
/** Original timing kind requested by the user (at / every / rrule). */
|
|
49
|
+
timingKind: z.string().min(1).max(32),
|
|
50
|
+
timing: z.record(z.unknown()),
|
|
51
|
+
state: z.enum(['active', 'paused', 'unlinked']),
|
|
52
|
+
title: z.string().max(120),
|
|
53
|
+
createdAt: timestampSchema,
|
|
54
|
+
updatedAt: timestampSchema,
|
|
55
|
+
lastError: stepErrorSchema.optional(),
|
|
56
|
+
});
|
|
57
|
+
export const taskRecordSchema = z.object({
|
|
58
|
+
taskId: idSchema,
|
|
59
|
+
title: z.string().min(2).max(80),
|
|
60
|
+
description: z.string().max(2000).optional(),
|
|
61
|
+
status: z.enum(TASK_STATUSES),
|
|
62
|
+
revision: z.number().int().min(1),
|
|
63
|
+
ownerSessionId: z.string().min(1).max(256),
|
|
64
|
+
steps: z.array(stepDefinitionSchema).min(1).max(10),
|
|
65
|
+
scheduleRef: scheduleRefSchema.optional(),
|
|
66
|
+
createdAt: timestampSchema,
|
|
67
|
+
updatedAt: timestampSchema,
|
|
68
|
+
schemaVersion: z.number().int().min(1),
|
|
69
|
+
});
|
|
70
|
+
export const templateSnapshotSchema = z.object({
|
|
71
|
+
revision: z.number().int().min(1),
|
|
72
|
+
title: z.string().min(1).max(80),
|
|
73
|
+
steps: z.array(stepDefinitionSchema).min(1).max(10),
|
|
74
|
+
});
|
|
75
|
+
export const runRecordSchema = z.object({
|
|
76
|
+
runId: idSchema,
|
|
77
|
+
taskId: idSchema,
|
|
78
|
+
taskRevision: z.number().int().min(1),
|
|
79
|
+
/** Owner of the task; every tool entry point compares this with the caller. */
|
|
80
|
+
taskOwnerSessionId: z.string().min(1).max(256),
|
|
81
|
+
/** Session that started the run (equals owner in V1.0). */
|
|
82
|
+
sessionId: z.string().min(1).max(256),
|
|
83
|
+
status: z.enum(RUN_STATUSES),
|
|
84
|
+
triggerType: z.enum(TRIGGER_TYPES),
|
|
85
|
+
scheduleId: z.string().max(128).optional(),
|
|
86
|
+
occurrenceKey: z.string().max(256).optional(),
|
|
87
|
+
idempotencyKey: z.string().max(300).optional(),
|
|
88
|
+
currentStepId: idSchema.optional(),
|
|
89
|
+
progress: z.number().int().min(0).max(100),
|
|
90
|
+
requiredTotal: z.number().int().min(0).max(10),
|
|
91
|
+
requiredCompleted: z.number().int().min(0).max(10),
|
|
92
|
+
totalSteps: z.number().int().min(1).max(10),
|
|
93
|
+
startedAt: timestampSchema,
|
|
94
|
+
updatedAt: timestampSchema,
|
|
95
|
+
finishedAt: timestampSchema.optional(),
|
|
96
|
+
summary: z.string().max(20000).optional(),
|
|
97
|
+
error: stepErrorSchema.optional(),
|
|
98
|
+
resumesRunId: idSchema.optional(),
|
|
99
|
+
templateSnapshot: templateSnapshotSchema,
|
|
100
|
+
schemaVersion: z.number().int().min(1),
|
|
101
|
+
});
|
|
102
|
+
export const runStepRecordSchema = z.object({
|
|
103
|
+
runId: idSchema,
|
|
104
|
+
stepId: idSchema,
|
|
105
|
+
taskId: idSchema,
|
|
106
|
+
order: z.number().int().min(1).max(10),
|
|
107
|
+
title: z.string().min(1).max(120),
|
|
108
|
+
required: z.boolean(),
|
|
109
|
+
status: z.enum(STEP_STATUSES),
|
|
110
|
+
attempt: z.number().int().min(0).max(100),
|
|
111
|
+
startedAt: timestampSchema.optional(),
|
|
112
|
+
finishedAt: timestampSchema.optional(),
|
|
113
|
+
summary: z.string().max(20000).optional(),
|
|
114
|
+
error: stepErrorSchema.optional(),
|
|
115
|
+
/** Set when a resume carries a completed step over into the new run. */
|
|
116
|
+
carryOverFromRunId: idSchema.optional(),
|
|
117
|
+
updatedAt: timestampSchema,
|
|
118
|
+
});
|
|
119
|
+
export const globalStateSchema = z.object({
|
|
120
|
+
schemaVersion: z.number().int().min(1),
|
|
121
|
+
/** migrationId -> ISO timestamp; presence means "already applied". */
|
|
122
|
+
appliedMigrations: z.record(z.string()),
|
|
123
|
+
lastRecoveryScanAt: timestampSchema.optional(),
|
|
124
|
+
lastPruneAt: timestampSchema.optional(),
|
|
125
|
+
});
|
|
126
|
+
/** Table names, kept in one place so spec and repository cannot drift. */
|
|
127
|
+
export const TABLES = {
|
|
128
|
+
tasks: 'tasks',
|
|
129
|
+
runs: 'task_runs',
|
|
130
|
+
steps: 'task_run_steps',
|
|
131
|
+
};
|
|
132
|
+
/** Composite key for one step record: one row per (runId, stepId). */
|
|
133
|
+
export function stepKey(runId, stepId) {
|
|
134
|
+
return `${runId}/${stepId}`;
|
|
135
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Task/Run/Step state machines (PRD 4.7, 7.3).
|
|
3
|
+
*
|
|
4
|
+
* Every transition goes through `assertRunTransition` / `assertStepTransition`
|
|
5
|
+
* so an illegal change (e.g. failed -> running, or re-finishing a finished run)
|
|
6
|
+
* is rejected no matter which tool triggered it.
|
|
7
|
+
*/
|
|
8
|
+
import type { RunStatus, StepStatus, TaskStatus } from './records.js';
|
|
9
|
+
/** Runs that still occupy a concurrency slot. */
|
|
10
|
+
export declare const ACTIVE_RUN_STATUSES: readonly RunStatus[];
|
|
11
|
+
/** Runs that can no longer receive progress reports. */
|
|
12
|
+
export declare const TERMINAL_RUN_STATUSES: readonly RunStatus[];
|
|
13
|
+
/** Runs a resume may start from. `blocked` is recoverable, not finished. */
|
|
14
|
+
export declare const RESUMABLE_RUN_STATUSES: readonly RunStatus[];
|
|
15
|
+
export declare function isRunStatus(value: unknown): value is RunStatus;
|
|
16
|
+
export declare function isStepStatus(value: unknown): value is StepStatus;
|
|
17
|
+
export declare function isTaskStatus(value: unknown): value is TaskStatus;
|
|
18
|
+
export declare function isTerminalRun(status: RunStatus): boolean;
|
|
19
|
+
export declare function isActiveRun(status: RunStatus): boolean;
|
|
20
|
+
export declare function canTransitionRun(from: RunStatus, to: RunStatus): boolean;
|
|
21
|
+
export declare function assertRunTransition(from: RunStatus, to: RunStatus, context: string): void;
|
|
22
|
+
export declare function assertStepTransition(from: StepStatus, to: StepStatus, stepId: string): void;
|
|
23
|
+
/**
|
|
24
|
+
* Progress is derived from persisted step records only (PRD 11.4), counting
|
|
25
|
+
* required steps that are completed. Skipped/failed required steps never
|
|
26
|
+
* contribute, so a run cannot look "nearly done" while blocking.
|
|
27
|
+
*/
|
|
28
|
+
export declare function computeProgress(steps: ReadonlyArray<{
|
|
29
|
+
required: boolean;
|
|
30
|
+
status: StepStatus;
|
|
31
|
+
}>): {
|
|
32
|
+
progress: number;
|
|
33
|
+
requiredTotal: number;
|
|
34
|
+
requiredCompleted: number;
|
|
35
|
+
};
|
|
36
|
+
/** First step, in order, that still needs work. */
|
|
37
|
+
export declare function firstPendingStep(steps: ReadonlyArray<{
|
|
38
|
+
stepId: string;
|
|
39
|
+
order: number;
|
|
40
|
+
status: StepStatus;
|
|
41
|
+
}>): string | undefined;
|
|
42
|
+
/** All required steps completed => the run may be reported as succeeded. */
|
|
43
|
+
export declare function requiredStepsSettled(steps: ReadonlyArray<{
|
|
44
|
+
required: boolean;
|
|
45
|
+
status: StepStatus;
|
|
46
|
+
stepId: string;
|
|
47
|
+
order: number;
|
|
48
|
+
}>): {
|
|
49
|
+
ok: boolean;
|
|
50
|
+
blockers: string[];
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Linear execution guard (PRD 9.1 step 3): a step may only start when every
|
|
54
|
+
* earlier required step is completed or skipped.
|
|
55
|
+
*/
|
|
56
|
+
export declare function assertLinearStart(steps: ReadonlyArray<{
|
|
57
|
+
stepId: string;
|
|
58
|
+
order: number;
|
|
59
|
+
required: boolean;
|
|
60
|
+
status: StepStatus;
|
|
61
|
+
}>, stepId: string): void;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Task/Run/Step state machines (PRD 4.7, 7.3).
|
|
3
|
+
*
|
|
4
|
+
* Every transition goes through `assertRunTransition` / `assertStepTransition`
|
|
5
|
+
* so an illegal change (e.g. failed -> running, or re-finishing a finished run)
|
|
6
|
+
* is rejected no matter which tool triggered it.
|
|
7
|
+
*/
|
|
8
|
+
import { TaskEngineError } from '../errors.js';
|
|
9
|
+
import { RUN_STATUSES, STEP_STATUSES, TASK_STATUSES } from './records.js';
|
|
10
|
+
/** Runs that still occupy a concurrency slot. */
|
|
11
|
+
export const ACTIVE_RUN_STATUSES = ['queued', 'running'];
|
|
12
|
+
/** Runs that can no longer receive progress reports. */
|
|
13
|
+
export const TERMINAL_RUN_STATUSES = [
|
|
14
|
+
'succeeded',
|
|
15
|
+
'failed',
|
|
16
|
+
'interrupted',
|
|
17
|
+
'skipped',
|
|
18
|
+
];
|
|
19
|
+
/** Runs a resume may start from. `blocked` is recoverable, not finished. */
|
|
20
|
+
export const RESUMABLE_RUN_STATUSES = ['failed', 'interrupted', 'blocked'];
|
|
21
|
+
export function isRunStatus(value) {
|
|
22
|
+
return typeof value === 'string' && RUN_STATUSES.includes(value);
|
|
23
|
+
}
|
|
24
|
+
export function isStepStatus(value) {
|
|
25
|
+
return typeof value === 'string' && STEP_STATUSES.includes(value);
|
|
26
|
+
}
|
|
27
|
+
export function isTaskStatus(value) {
|
|
28
|
+
return typeof value === 'string' && TASK_STATUSES.includes(value);
|
|
29
|
+
}
|
|
30
|
+
export function isTerminalRun(status) {
|
|
31
|
+
return TERMINAL_RUN_STATUSES.includes(status);
|
|
32
|
+
}
|
|
33
|
+
export function isActiveRun(status) {
|
|
34
|
+
return ACTIVE_RUN_STATUSES.includes(status);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Allowed TaskRun transitions.
|
|
38
|
+
*
|
|
39
|
+
* - queued -> running | interrupted | skipped
|
|
40
|
+
* - running -> succeeded | failed | blocked | interrupted
|
|
41
|
+
* - blocked -> failed | interrupted (never back to running: PRD 4.7 forbids
|
|
42
|
+
* it, a resume must create a new TaskRun with resumesRunId)
|
|
43
|
+
* - terminal states are final.
|
|
44
|
+
*/
|
|
45
|
+
const RUN_TRANSITIONS = {
|
|
46
|
+
queued: ['running', 'interrupted', 'skipped', 'failed'],
|
|
47
|
+
running: ['succeeded', 'failed', 'blocked', 'interrupted'],
|
|
48
|
+
blocked: ['failed', 'interrupted'],
|
|
49
|
+
succeeded: [],
|
|
50
|
+
failed: [],
|
|
51
|
+
interrupted: [],
|
|
52
|
+
skipped: [],
|
|
53
|
+
};
|
|
54
|
+
const STEP_TRANSITIONS = {
|
|
55
|
+
pending: ['running', 'skipped', 'failed'],
|
|
56
|
+
running: ['completed', 'failed', 'skipped'],
|
|
57
|
+
completed: [],
|
|
58
|
+
failed: [],
|
|
59
|
+
skipped: [],
|
|
60
|
+
};
|
|
61
|
+
export function canTransitionRun(from, to) {
|
|
62
|
+
if (from === to)
|
|
63
|
+
return false;
|
|
64
|
+
return RUN_TRANSITIONS[from].includes(to);
|
|
65
|
+
}
|
|
66
|
+
export function assertRunTransition(from, to, context) {
|
|
67
|
+
// Terminal wins over every other rule: a finished run can never move again,
|
|
68
|
+
// not even to the state it already holds.
|
|
69
|
+
if (isTerminalRun(from)) {
|
|
70
|
+
throw new TaskEngineError('TASK_RUN_ALREADY_FINISHED', `运行已结束(${from}),不能再变更为 ${to};如需继续请使用 task_resume 创建新的运行`);
|
|
71
|
+
}
|
|
72
|
+
if (from === to) {
|
|
73
|
+
throw new TaskEngineError('TASK_ALREADY_RUNNING', `运行已处于 ${from} 状态(${context})`);
|
|
74
|
+
}
|
|
75
|
+
if (!canTransitionRun(from, to)) {
|
|
76
|
+
throw new TaskEngineError('TASK_STEP_ORDER_INVALID', `非法状态转换 ${from} → ${to}(${context})`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
export function assertStepTransition(from, to, stepId) {
|
|
80
|
+
if (from === to) {
|
|
81
|
+
throw new TaskEngineError('TASK_STEP_ORDER_INVALID', `步骤 ${stepId} 已处于 ${from} 状态,不能重复报告 ${to}`);
|
|
82
|
+
}
|
|
83
|
+
if (!STEP_TRANSITIONS[from].includes(to)) {
|
|
84
|
+
throw new TaskEngineError('TASK_STEP_ORDER_INVALID', `步骤 ${stepId} 不能从 ${from} 变更为 ${to}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Progress is derived from persisted step records only (PRD 11.4), counting
|
|
89
|
+
* required steps that are completed. Skipped/failed required steps never
|
|
90
|
+
* contribute, so a run cannot look "nearly done" while blocking.
|
|
91
|
+
*/
|
|
92
|
+
export function computeProgress(steps) {
|
|
93
|
+
const required = steps.filter((step) => step.required);
|
|
94
|
+
const completed = required.filter((step) => step.status === 'completed').length;
|
|
95
|
+
const total = required.length;
|
|
96
|
+
const progress = total === 0 ? 0 : Math.min(100, Math.floor((completed / total) * 100));
|
|
97
|
+
return { progress, requiredTotal: total, requiredCompleted: completed };
|
|
98
|
+
}
|
|
99
|
+
/** First step, in order, that still needs work. */
|
|
100
|
+
export function firstPendingStep(steps) {
|
|
101
|
+
const sorted = [...steps].sort((a, b) => a.order - b.order);
|
|
102
|
+
return sorted.find((step) => step.status === 'pending' || step.status === 'running')?.stepId;
|
|
103
|
+
}
|
|
104
|
+
/** All required steps completed => the run may be reported as succeeded. */
|
|
105
|
+
export function requiredStepsSettled(steps) {
|
|
106
|
+
const blockers = steps
|
|
107
|
+
.filter((step) => step.required && step.status !== 'completed')
|
|
108
|
+
.sort((a, b) => a.order - b.order)
|
|
109
|
+
.map((step) => `${step.order}. ${step.stepId} (${step.status})`);
|
|
110
|
+
return { ok: blockers.length === 0, blockers };
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Linear execution guard (PRD 9.1 step 3): a step may only start when every
|
|
114
|
+
* earlier required step is completed or skipped.
|
|
115
|
+
*/
|
|
116
|
+
export function assertLinearStart(steps, stepId) {
|
|
117
|
+
const target = steps.find((step) => step.stepId === stepId);
|
|
118
|
+
if (!target) {
|
|
119
|
+
throw new TaskEngineError('TASK_STEP_ORDER_INVALID', `步骤 ${stepId} 不属于本次运行`);
|
|
120
|
+
}
|
|
121
|
+
const earlierBlocking = steps
|
|
122
|
+
.filter((step) => step.order < target.order && step.status !== 'completed' && step.status !== 'skipped')
|
|
123
|
+
.sort((a, b) => a.order - b.order);
|
|
124
|
+
if (earlierBlocking.length > 0) {
|
|
125
|
+
const names = earlierBlocking.map((step) => `${step.order}.${step.stepId}(${step.status})`).join(', ');
|
|
126
|
+
throw new TaskEngineError('TASK_STEP_ORDER_INVALID', `必须按 order 顺序执行:步骤 ${target.order} 之前的 ${names} 尚未结束`);
|
|
127
|
+
}
|
|
128
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stable error codes, error payloads and message sanitisation.
|
|
3
|
+
*
|
|
4
|
+
* The 13 codes below are the PRD (chapter 6.5) contract. Two additional codes
|
|
5
|
+
* cover cases the PRD table does not name but that must never be reported as a
|
|
6
|
+
* misleading PRD code:
|
|
7
|
+
* - TASK_INVALID_ARGUMENTS: a tool argument failed schema/limit validation.
|
|
8
|
+
* - TASK_INTERNAL_ERROR: an unexpected runtime failure (bug / IO).
|
|
9
|
+
* They are documented in README.md and docs/API-COMPATIBILITY-AUDIT.md.
|
|
10
|
+
*/
|
|
11
|
+
export type TaskErrorCode = 'TASK_NOT_FOUND' | 'TASK_ALREADY_RUNNING' | 'TASK_REVISION_CONFLICT' | 'TASK_INVALID_STEPS' | 'TASK_RUN_NOT_FOUND' | 'TASK_RUN_ALREADY_FINISHED' | 'TASK_STEP_ORDER_INVALID' | 'TASK_PERMISSION_DENIED' | 'TASK_SCHEDULE_UNAVAILABLE' | 'TASK_SCHEDULE_FAILED' | 'TASK_STORAGE_ERROR' | 'TASK_RUN_INTERRUPTED' | 'TASK_MAX_CONCURRENCY' | 'TASK_INVALID_ARGUMENTS' | 'TASK_INTERNAL_ERROR';
|
|
12
|
+
export declare const TASK_ERROR_CODES: readonly TaskErrorCode[];
|
|
13
|
+
export interface TaskErrorPayload {
|
|
14
|
+
code: TaskErrorCode;
|
|
15
|
+
message: string;
|
|
16
|
+
retryable: boolean;
|
|
17
|
+
relatedRunId?: string;
|
|
18
|
+
}
|
|
19
|
+
export declare class TaskEngineError extends Error {
|
|
20
|
+
readonly code: TaskErrorCode;
|
|
21
|
+
readonly retryable: boolean;
|
|
22
|
+
readonly relatedRunId?: string;
|
|
23
|
+
readonly details?: Record<string, unknown>;
|
|
24
|
+
constructor(code: TaskErrorCode, message: string, options?: {
|
|
25
|
+
retryable?: boolean;
|
|
26
|
+
relatedRunId?: string;
|
|
27
|
+
details?: Record<string, unknown>;
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Remove host paths, stack frames and credentials from any message that may
|
|
32
|
+
* reach the model (PRD 10.3 / 12.3: errors must not leak paths, stacks or
|
|
33
|
+
* other Sessions' data).
|
|
34
|
+
*/
|
|
35
|
+
export declare function sanitizeMessage(input: string, maxLength?: number): string;
|
|
36
|
+
/** Normalise any thrown value into the plugin's uniform error payload. */
|
|
37
|
+
export declare function toErrorPayload(error: unknown): TaskErrorPayload;
|
|
38
|
+
export declare function invalidArguments(message: string): TaskEngineError;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stable error codes, error payloads and message sanitisation.
|
|
3
|
+
*
|
|
4
|
+
* The 13 codes below are the PRD (chapter 6.5) contract. Two additional codes
|
|
5
|
+
* cover cases the PRD table does not name but that must never be reported as a
|
|
6
|
+
* misleading PRD code:
|
|
7
|
+
* - TASK_INVALID_ARGUMENTS: a tool argument failed schema/limit validation.
|
|
8
|
+
* - TASK_INTERNAL_ERROR: an unexpected runtime failure (bug / IO).
|
|
9
|
+
* They are documented in README.md and docs/API-COMPATIBILITY-AUDIT.md.
|
|
10
|
+
*/
|
|
11
|
+
export const TASK_ERROR_CODES = [
|
|
12
|
+
'TASK_NOT_FOUND',
|
|
13
|
+
'TASK_ALREADY_RUNNING',
|
|
14
|
+
'TASK_REVISION_CONFLICT',
|
|
15
|
+
'TASK_INVALID_STEPS',
|
|
16
|
+
'TASK_RUN_NOT_FOUND',
|
|
17
|
+
'TASK_RUN_ALREADY_FINISHED',
|
|
18
|
+
'TASK_STEP_ORDER_INVALID',
|
|
19
|
+
'TASK_PERMISSION_DENIED',
|
|
20
|
+
'TASK_SCHEDULE_UNAVAILABLE',
|
|
21
|
+
'TASK_SCHEDULE_FAILED',
|
|
22
|
+
'TASK_STORAGE_ERROR',
|
|
23
|
+
'TASK_RUN_INTERRUPTED',
|
|
24
|
+
'TASK_MAX_CONCURRENCY',
|
|
25
|
+
'TASK_INVALID_ARGUMENTS',
|
|
26
|
+
'TASK_INTERNAL_ERROR',
|
|
27
|
+
];
|
|
28
|
+
/** Codes callers may safely retry with the same arguments. */
|
|
29
|
+
const RETRYABLE = new Set([
|
|
30
|
+
'TASK_ALREADY_RUNNING',
|
|
31
|
+
'TASK_REVISION_CONFLICT',
|
|
32
|
+
'TASK_MAX_CONCURRENCY',
|
|
33
|
+
'TASK_SCHEDULE_FAILED',
|
|
34
|
+
'TASK_STORAGE_ERROR',
|
|
35
|
+
]);
|
|
36
|
+
export class TaskEngineError extends Error {
|
|
37
|
+
code;
|
|
38
|
+
retryable;
|
|
39
|
+
relatedRunId;
|
|
40
|
+
details;
|
|
41
|
+
constructor(code, message, options = {}) {
|
|
42
|
+
super(sanitizeMessage(message));
|
|
43
|
+
this.name = 'TaskEngineError';
|
|
44
|
+
this.code = code;
|
|
45
|
+
this.retryable = options.retryable ?? RETRYABLE.has(code);
|
|
46
|
+
if (options.relatedRunId !== undefined)
|
|
47
|
+
this.relatedRunId = options.relatedRunId;
|
|
48
|
+
if (options.details !== undefined)
|
|
49
|
+
this.details = options.details;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Remove host paths, stack frames and credentials from any message that may
|
|
54
|
+
* reach the model (PRD 10.3 / 12.3: errors must not leak paths, stacks or
|
|
55
|
+
* other Sessions' data).
|
|
56
|
+
*/
|
|
57
|
+
export function sanitizeMessage(input, maxLength = 800) {
|
|
58
|
+
let text = String(input ?? '');
|
|
59
|
+
// Drop stack frames entirely.
|
|
60
|
+
text = text
|
|
61
|
+
.split('\n')
|
|
62
|
+
.filter((line) => !/^\s+at\s/.test(line))
|
|
63
|
+
.join(' ');
|
|
64
|
+
// Redact credential-looking assignments.
|
|
65
|
+
text = text.replace(/\b(api[_-]?key|access[_-]?token|refresh[_-]?token|token|secret|password|authorization|bearer)\b(\s*[:=]\s*|\s+)(\S+)/gi, (_m, key) => `${key}: [redacted]`);
|
|
66
|
+
// Redact absolute POSIX paths (home dirs, app bundles, node_modules).
|
|
67
|
+
text = text.replace(/\/(?:Users|home|Applications|private|var|opt|usr|tmp)\/[^\s"'`)]*/g, '<path>');
|
|
68
|
+
text = text.replace(/\b[A-Za-z]:\\[^\s"'`)]*/g, '<path>');
|
|
69
|
+
text = text.replace(/\s+/g, ' ').trim();
|
|
70
|
+
if (text.length > maxLength)
|
|
71
|
+
text = `${text.slice(0, maxLength)}…`;
|
|
72
|
+
return text;
|
|
73
|
+
}
|
|
74
|
+
/** Normalise any thrown value into the plugin's uniform error payload. */
|
|
75
|
+
export function toErrorPayload(error) {
|
|
76
|
+
if (error instanceof TaskEngineError) {
|
|
77
|
+
const payload = {
|
|
78
|
+
code: error.code,
|
|
79
|
+
message: error.message,
|
|
80
|
+
retryable: error.retryable,
|
|
81
|
+
};
|
|
82
|
+
if (error.relatedRunId !== undefined)
|
|
83
|
+
payload.relatedRunId = error.relatedRunId;
|
|
84
|
+
return payload;
|
|
85
|
+
}
|
|
86
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
87
|
+
const isMissingKey = /missing-key/.test(message);
|
|
88
|
+
if (isMissingKey) {
|
|
89
|
+
return { code: 'TASK_NOT_FOUND', message: '记录不存在或已被清理', retryable: false };
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
code: 'TASK_INTERNAL_ERROR',
|
|
93
|
+
message: sanitizeMessage(message || '未知错误'),
|
|
94
|
+
retryable: false,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
export function invalidArguments(message) {
|
|
98
|
+
return new TaskEngineError('TASK_INVALID_ARGUMENTS', message);
|
|
99
|
+
}
|
package/dist/host.d.ts
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structural declarations of the DeepSeek Harness (DSH) Cordis plugin surface
|
|
3
|
+
* used by this plugin.
|
|
4
|
+
*
|
|
5
|
+
* The plugin is loaded from a profile directory where only `zod` and
|
|
6
|
+
* `@deepseek-ai/schemastery` resolve; `@deepseek-ai/dsh-*` packages are NOT
|
|
7
|
+
* importable (verified with `require.resolve` in
|
|
8
|
+
* docs/API-COMPATIBILITY-AUDIT.md). The host contract is therefore expressed
|
|
9
|
+
* structurally: we depend on the documented public shape, never on a private
|
|
10
|
+
* module path, and every optional capability is feature-detected at runtime.
|
|
11
|
+
*
|
|
12
|
+
* Anything added here must be backed by an entry in
|
|
13
|
+
* docs/API-COMPATIBILITY-AUDIT.md (file + symbol + verified version).
|
|
14
|
+
*/
|
|
15
|
+
export type Disposer = () => void;
|
|
16
|
+
/** A model-visible content block produced by a tool's `output.render`. */
|
|
17
|
+
export interface ContentBlock {
|
|
18
|
+
type: 'text';
|
|
19
|
+
text: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The JSON Schema subset accepted by dsh-tools `assertSupportedJsonSchema`.
|
|
23
|
+
* Keys outside this set (minLength, pattern, maximum, format, ...) throw at
|
|
24
|
+
* registration time, so range/length rules are enforced in code instead.
|
|
25
|
+
*/
|
|
26
|
+
export interface JsonSchemaNode {
|
|
27
|
+
type?: 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';
|
|
28
|
+
oneOf?: JsonSchemaNode[];
|
|
29
|
+
properties?: Record<string, JsonSchemaNode>;
|
|
30
|
+
required?: string[];
|
|
31
|
+
additionalProperties?: boolean;
|
|
32
|
+
items?: JsonSchemaNode;
|
|
33
|
+
enum?: Array<string | number | boolean | null>;
|
|
34
|
+
const?: string | number | boolean | null;
|
|
35
|
+
description?: string;
|
|
36
|
+
title?: string;
|
|
37
|
+
default?: unknown;
|
|
38
|
+
examples?: unknown[];
|
|
39
|
+
}
|
|
40
|
+
/** Tool execution context handed to `execute(args, exec)` by dsh-tools. */
|
|
41
|
+
export interface ToolRunContextLike {
|
|
42
|
+
readonly callId?: string;
|
|
43
|
+
readonly name?: string;
|
|
44
|
+
readonly arguments?: unknown;
|
|
45
|
+
readonly signal?: AbortSignal;
|
|
46
|
+
/** Live agent face. `agent.id` and `agent.session.id` are both SessionIds. */
|
|
47
|
+
readonly agent?: {
|
|
48
|
+
readonly id?: string;
|
|
49
|
+
readonly session?: {
|
|
50
|
+
readonly id?: string;
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/** Public tool definition shape (dsh-tools `ToolDefinition`). */
|
|
55
|
+
export interface ToolDefinitionLike {
|
|
56
|
+
name: string;
|
|
57
|
+
description: string;
|
|
58
|
+
parameters: Record<string, unknown>;
|
|
59
|
+
output: {
|
|
60
|
+
schema: JsonSchemaNode;
|
|
61
|
+
render(args: unknown, value: unknown): ContentBlock[];
|
|
62
|
+
};
|
|
63
|
+
execute(args: unknown, exec: ToolRunContextLike): Promise<unknown>;
|
|
64
|
+
timeoutMs?: number;
|
|
65
|
+
isConcurrencySafe?: boolean;
|
|
66
|
+
}
|
|
67
|
+
/** `ctx.tools` */
|
|
68
|
+
export interface ToolsServiceLike {
|
|
69
|
+
register(definition: ToolDefinitionLike): Disposer;
|
|
70
|
+
}
|
|
71
|
+
/** One table handle inside an opened StorageDomain. Reads are synchronous. */
|
|
72
|
+
export interface KvTableLike<V> {
|
|
73
|
+
get(key: string): V | undefined;
|
|
74
|
+
entries(): IterableIterator<[string, V]>;
|
|
75
|
+
keys(): IterableIterator<string>;
|
|
76
|
+
readonly size: number;
|
|
77
|
+
put(key: string, value: V): Promise<void>;
|
|
78
|
+
delete(key: string): Promise<boolean>;
|
|
79
|
+
deleteMany(keys: string[]): Promise<number>;
|
|
80
|
+
update(key: string, mutator: (current: V) => V): Promise<V>;
|
|
81
|
+
}
|
|
82
|
+
/** An opened StorageDomain handle. Records are shared immutables: never mutate. */
|
|
83
|
+
export interface DomainLike {
|
|
84
|
+
readonly name: string;
|
|
85
|
+
table<V>(name: string): KvTableLike<V>;
|
|
86
|
+
close(): Promise<void>;
|
|
87
|
+
}
|
|
88
|
+
/** `ctx.storageDomain` (DomainFacility). */
|
|
89
|
+
export interface DomainFacilityLike {
|
|
90
|
+
open(spec: unknown): Promise<DomainLike>;
|
|
91
|
+
get(name: string): DomainLike | undefined;
|
|
92
|
+
}
|
|
93
|
+
/** Public subset of `ctx.schedule` (ScheduleService) used by this plugin. */
|
|
94
|
+
export interface ScheduleRecordLike {
|
|
95
|
+
id: string;
|
|
96
|
+
title: string;
|
|
97
|
+
prompt: string;
|
|
98
|
+
scheduledAt?: string;
|
|
99
|
+
status?: 'active' | 'paused' | 'ended';
|
|
100
|
+
target?: Record<string, unknown>;
|
|
101
|
+
createdAt?: string;
|
|
102
|
+
updatedAt?: string;
|
|
103
|
+
executionActive?: boolean;
|
|
104
|
+
[key: string]: unknown;
|
|
105
|
+
}
|
|
106
|
+
export interface ScheduleEditResultLike {
|
|
107
|
+
id: string;
|
|
108
|
+
deleted?: boolean;
|
|
109
|
+
code?: string;
|
|
110
|
+
[key: string]: unknown;
|
|
111
|
+
}
|
|
112
|
+
export interface ScheduleRunResultLike {
|
|
113
|
+
id: string;
|
|
114
|
+
code?: string;
|
|
115
|
+
[key: string]: unknown;
|
|
116
|
+
}
|
|
117
|
+
export interface ScheduleServiceLike {
|
|
118
|
+
create(request: unknown, actorSessionId?: string, signal?: AbortSignal): Promise<ScheduleRecordLike>;
|
|
119
|
+
edit(request: unknown, actorSessionId?: string, signal?: AbortSignal): Promise<ScheduleEditResultLike>;
|
|
120
|
+
view(request: unknown): Promise<ScheduleRecordLike | {
|
|
121
|
+
id: string;
|
|
122
|
+
code: string;
|
|
123
|
+
}>;
|
|
124
|
+
run(request: unknown, signal?: AbortSignal): Promise<ScheduleRunResultLike>;
|
|
125
|
+
list(request?: unknown): Promise<{
|
|
126
|
+
items: ScheduleRecordLike[];
|
|
127
|
+
}>;
|
|
128
|
+
}
|
|
129
|
+
export interface LoggerLike {
|
|
130
|
+
debug(...args: unknown[]): void;
|
|
131
|
+
info(...args: unknown[]): void;
|
|
132
|
+
warn(...args: unknown[]): void;
|
|
133
|
+
error(...args: unknown[]): void;
|
|
134
|
+
}
|
|
135
|
+
/** The Cordis context slice this plugin touches. */
|
|
136
|
+
export interface HostContextLike {
|
|
137
|
+
get?(name: string): unknown;
|
|
138
|
+
/**
|
|
139
|
+
* Cordis scoped injection: `callback` runs once every dependency is
|
|
140
|
+
* available, and its registrations are disposed with the scope.
|
|
141
|
+
*/
|
|
142
|
+
inject(deps: string[], callback: (ctx: HostContextLike) => void): unknown;
|
|
143
|
+
emit?(event: string, ...args: unknown[]): unknown;
|
|
144
|
+
on?(event: string, listener: (...args: unknown[]) => void): Disposer;
|
|
145
|
+
effect?(setup: () => Disposer | void): void;
|
|
146
|
+
logger?: LoggerLike;
|
|
147
|
+
tools?: ToolsServiceLike;
|
|
148
|
+
storageDomain?: DomainFacilityLike;
|
|
149
|
+
schedule?: ScheduleServiceLike;
|
|
150
|
+
}
|
|
151
|
+
export interface PluginApplyTarget {
|
|
152
|
+
(ctx: HostContextLike, config?: unknown): void;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Read an OPTIONAL host service.
|
|
156
|
+
*
|
|
157
|
+
* Cordis only exposes an injected service as a context property; touching a
|
|
158
|
+
* property that was not declared in `inject` throws
|
|
159
|
+
* `cannot get property "<name>" without inject`. Schedule is optional (PRD
|
|
160
|
+
* FR-012: manual tasks still work without it), so it is resolved with
|
|
161
|
+
* `ctx.get(name)` and a failure means "not mounted".
|
|
162
|
+
*/
|
|
163
|
+
export declare function optionalService<T>(ctx: HostContextLike, name: string): T | undefined;
|
|
164
|
+
/** Extract the calling SessionId from a tool run context. */
|
|
165
|
+
export declare function sessionIdOf(exec: ToolRunContextLike): string | undefined;
|
package/dist/host.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structural declarations of the DeepSeek Harness (DSH) Cordis plugin surface
|
|
3
|
+
* used by this plugin.
|
|
4
|
+
*
|
|
5
|
+
* The plugin is loaded from a profile directory where only `zod` and
|
|
6
|
+
* `@deepseek-ai/schemastery` resolve; `@deepseek-ai/dsh-*` packages are NOT
|
|
7
|
+
* importable (verified with `require.resolve` in
|
|
8
|
+
* docs/API-COMPATIBILITY-AUDIT.md). The host contract is therefore expressed
|
|
9
|
+
* structurally: we depend on the documented public shape, never on a private
|
|
10
|
+
* module path, and every optional capability is feature-detected at runtime.
|
|
11
|
+
*
|
|
12
|
+
* Anything added here must be backed by an entry in
|
|
13
|
+
* docs/API-COMPATIBILITY-AUDIT.md (file + symbol + verified version).
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* Read an OPTIONAL host service.
|
|
17
|
+
*
|
|
18
|
+
* Cordis only exposes an injected service as a context property; touching a
|
|
19
|
+
* property that was not declared in `inject` throws
|
|
20
|
+
* `cannot get property "<name>" without inject`. Schedule is optional (PRD
|
|
21
|
+
* FR-012: manual tasks still work without it), so it is resolved with
|
|
22
|
+
* `ctx.get(name)` and a failure means "not mounted".
|
|
23
|
+
*/
|
|
24
|
+
export function optionalService(ctx, name) {
|
|
25
|
+
try {
|
|
26
|
+
const getter = ctx.get;
|
|
27
|
+
if (typeof getter === 'function') {
|
|
28
|
+
const value = getter.call(ctx, name);
|
|
29
|
+
if (value !== undefined && value !== null)
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
/* not mounted, or not readable at this point in the lifecycle */
|
|
35
|
+
}
|
|
36
|
+
try {
|
|
37
|
+
const value = ctx[name];
|
|
38
|
+
if (value !== undefined && value !== null)
|
|
39
|
+
return value;
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
/* property access without inject throws: treat as absent */
|
|
43
|
+
}
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
/** Extract the calling SessionId from a tool run context. */
|
|
47
|
+
export function sessionIdOf(exec) {
|
|
48
|
+
const agent = exec?.agent;
|
|
49
|
+
const fromSession = agent?.session?.id;
|
|
50
|
+
if (typeof fromSession === 'string' && fromSession.length > 0)
|
|
51
|
+
return fromSession;
|
|
52
|
+
const fromAgent = agent?.id;
|
|
53
|
+
if (typeof fromAgent === 'string' && fromAgent.length > 0)
|
|
54
|
+
return fromAgent;
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|