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
package/CHANGELOG.md ADDED
@@ -0,0 +1,91 @@
1
+ # Changelog
2
+
3
+ All notable changes to `dsh-background-task-engine` are documented here.
4
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and
5
+ the project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [1.0.1] — 2026-11-26
8
+
9
+ Documentation-only release.
10
+
11
+ ### Fixed
12
+
13
+ - README install instructions now put the npm spec first and explain that a
14
+ directory install needs `npm install` run first, because the plugin imports
15
+ `@deepseek-ai/schemastery`. Without it the loader fails with
16
+ `ERR_MODULE_NOT_FOUND` — observed and recorded while installing 1.0.0.
17
+ - Added the npm version badge.
18
+
19
+ ## [1.0.0] — 2026-11-26
20
+
21
+ First release. Verified against DeepSeek Harness `0.2.2-rc.3`
22
+ (see `docs/API-COMPATIBILITY-AUDIT.md` and `docs/TEST-REPORT.md`).
23
+
24
+ ### Added
25
+
26
+ - **Task templates**: create / list / get / update / archive, copy-from-template,
27
+ 1–10 ordered steps, `revision` optimistic locking with `TASK_REVISION_CONFLICT`
28
+ on a stale `expectedRevision`, and soft archive that keeps all run history.
29
+ - **Runs**: one TaskRun per execution with a frozen template snapshot, so later
30
+ template edits cannot change an in-flight run. Manual start, an explicit
31
+ `queued → running` two-phase start, and delivery-driven start.
32
+ - **Steps**: strictly linear progression by `order`; `started` / `completed` /
33
+ `failed` / `skipped` reports; progress always recomputed from persisted step
34
+ rows as `floor(completed required / required total × 100)`.
35
+ - **Recovery**: `blocked` runs are recoverable; `task_resume` creates a new run
36
+ with `resumesRunId`, carries completed steps over, and resumes at the first
37
+ unfinished step. A resume over a failed step (which may have had side effects)
38
+ requires an explicit `confirmation`.
39
+ - **Startup scan**: `queued`/`running` runs untouched for
40
+ `staleRunAfterMinutes` become `interrupted` with their running step marked
41
+ failed-and-unverified; nothing is restarted automatically.
42
+ - **Idempotency**: `manualRunId` for manual runs;
43
+ `schedule:<scheduleId>:<occurrenceKey>` for deliveries, so a duplicated
44
+ delivery returns the existing run instead of starting a second execution.
45
+ - **Concurrency limits**: `maxParallelRunsPerTask` (fixed at 1) and
46
+ `maxActiveRunsPerOwner`, both checked before a run is created.
47
+ - **Session isolation**: every entry point compares the caller's Session with the
48
+ record owner; another Session's record reports `TASK_NOT_FOUND`.
49
+ - **Persistence**: StorageDomain unit `dsh_background_task_engine` (schema v1)
50
+ with `tasks`, `task_runs`, `task_run_steps` and a `meta` ledger; idempotent
51
+ migration runner, startup integrity verification, and a 90-day retention prune
52
+ that never touches active runs or templates.
53
+ - **Schedule integration**: optional native linkage through `ctx.schedule`
54
+ (`create` / `update` / `pause` / `resume` / `delete` / `run_now` / `status`).
55
+ Host failures map to `TASK_SCHEDULE_FAILED` and are never reported as success;
56
+ a missing Schedule yields `TASK_SCHEDULE_UNAVAILABLE` while manual runs keep
57
+ working. `daily`/`weekly` inputs are expressed as an equivalent `RRULE`.
58
+ - **12 tools**: `task_create`, `task_list`, `task_get`, `task_update`,
59
+ `task_archive`, `task_schedule`, `task_run`, `task_run_begin`,
60
+ `task_step_report`, `task_run_finish`, `task_run_history`, `task_resume` —
61
+ each with an input schema, a canonical output schema and a renderer.
62
+ - **Uniform error envelope** with the 13 PRD codes plus
63
+ `TASK_INVALID_ARGUMENTS` and `TASK_INTERNAL_ERROR`; all messages sanitised
64
+ (no stacks, host paths or credentials).
65
+ - **Display resources**: localized `meta.title` / `meta.description`
66
+ (en + zh), a detail document, and an original SVG icon.
67
+ - **Docs**: README (en + zh) covering install, tools, protocol, model, config,
68
+ errors, security, upgrade and troubleshooting; API compatibility audit; test
69
+ report.
70
+
71
+ ### Verification
72
+
73
+ - Published as `dsh-background-task-engine@1.0.0` on npm; the registry copy was
74
+ installed into a real profile and reports `application: applied`.
75
+ - 81 tests across domain, storage, rendering and integration suites.
76
+ - Real-host runs against the installed DSH `0.2.2-rc.3` packages: mount, full
77
+ manual loop, restart persistence, stale-run recovery, resume.
78
+ - The published artifact was re-verified from a fresh clone: rebuild is
79
+ byte-identical, tests pass, and the npm tarball installs and registers all 12
80
+ tools.
81
+
82
+ ### Known limitations
83
+
84
+ - Schedule delivery could not be exercised end-to-end in-process: the real
85
+ `ScheduleService` needs `agents`, `sessions`, `sessionPersistence` and a
86
+ session controller that only the full application composes. The adapter is
87
+ covered against a double implementing the documented contract.
88
+ - The `json` backend stores the whole domain as one document, so write cost grows
89
+ with retained runs; the 90-day prune bounds it.
90
+ - `domain/changed` is an in-process event; a second host process observes writes
91
+ after reopening the domain, not live.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dsh-background-task-engine contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,264 @@
1
- # Temporary Holding Version
1
+ # dsh-background-task-engine
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/dsh-background-task-engine)](https://www.npmjs.com/package/dsh-background-task-engine)
4
+ [![license](https://img.shields.io/github/license/yzzshanyin-rgb/dsh-background-task-engine)](LICENSE)
5
+
6
+ Durable background task engine for **DeepSeek Harness (DSH)**: reusable task
7
+ templates, ordered linear steps, one persisted run ledger, progress and history
8
+ queries, explicit failure/interruption recovery, and optional linkage to native
9
+ DSH Schedule.
10
+
11
+ It does not reimplement a scheduler, an agent loop, a job registry or a storage
12
+ backend — it composes the Host's own `ctx.schedule`, `ctx.storageDomain` and
13
+ `ctx.tools`.
14
+
15
+ - [Install](#install)
16
+ - [Tools](#tools)
17
+ - [Execution protocol](#execution-protocol)
18
+ - [Data model](#data-model)
19
+ - [Configuration](#configuration)
20
+ - [Errors](#errors)
21
+ - [Security](#security)
22
+ - [Upgrade](#upgrade)
23
+ - [Troubleshooting](#troubleshooting)
24
+ - [Development](#development)
25
+
26
+ ## Install
27
+
28
+ Requirements: DSH **0.2.2-rc.3** or a compatible release with
29
+ `ctx.storageDomain` mounted (the stock base bundle does this with
30
+ `storage-domain backend: json`).
31
+
32
+ ```sh
33
+ # from npm (published 1.0.0)
34
+ dsh plugin --profile <name> add dsh-background-task-engine
35
+
36
+ # or from a local checkout
37
+ dsh plugin --profile <name> add /absolute/path/to/dsh-background-task-engine
38
+ ```
39
+
40
+ When installing from a directory path, run `npm install` in that directory first:
41
+ the plugin imports `@deepseek-ai/schemastery`, and a missing `node_modules` makes
42
+ the loader fail with `ERR_MODULE_NOT_FOUND`. The registry spec carries its own
43
+ dependencies and needs no checkout.
44
+
45
+ Then restart the app. Confirm in **Plugins** that the row
46
+ `background-task-engine` is enabled; the row shows this bundle's title,
47
+ description and icon.
48
+
49
+ The bundle patch is intentionally empty apart from the plugin row, so installing
50
+ it does not change any other setting:
51
+
52
+ ```yaml
53
+ - insert:
54
+ - id: background-task-engine
55
+ name: 'dsh-background-task-engine'
56
+ config: { ... }
57
+ ```
58
+
59
+ ## Tools
60
+
61
+ Twelve model-facing tools, all returning
62
+ `{ success: true, ... }` or `{ success: false, error: { code, message, retryable, relatedRunId? } }`.
63
+
64
+ | Tool | Purpose | Key arguments |
65
+ |---|---|---|
66
+ | `task_create` | Create a template (1–10 steps) | `title`, `description?`, `steps[]`, `copyFromTaskId?` |
67
+ | `task_list` | List this Session's templates | `status?`, `query?`, `limit?`, `cursor?` |
68
+ | `task_get` | Read one template + recent runs | `taskId`, `includeRuns?` |
69
+ | `task_update` | Edit title/description/steps/status | `taskId`, `expectedRevision`, `changes` |
70
+ | `task_archive` | Soft-archive; history preserved | `taskId`, `expectedRevision` |
71
+ | `task_schedule` | Manage the native schedule link | `taskId`, `action`, `timing?`, `scheduleRule?` |
72
+ | `task_run` | Start a manual run now | `taskId`, `manualRunId?`, `defer?` |
73
+ | `task_run_begin` | Claim a run (task or queued run or delivery payload) | `taskId?`, `runId?`, `triggerPayload?`, `scheduleId?`, `occurrenceKey?`, `idempotencyKey?` |
74
+ | `task_step_report` | Report a step | `runId`, `stepId`, `action`, `summary?`, `error?` |
75
+ | `task_run_finish` | Submit the run result | `runId`, `status`, `summary?`, `error?` |
76
+ | `task_run_history` | Page run history | `taskId`, `status?`, `limit?`, `cursor?` |
77
+ | `task_resume` | Recover a failed/interrupted/blocked run | `runId`, `confirmation?` |
78
+
79
+ `task_schedule` actions: `create`, `update`, `pause`, `resume`, `delete`,
80
+ `run_now`, `status`. Timing input accepts `at`, `every`, `rrule`, `cron`,
81
+ `daily`, `weekly`; `daily`/`weekly` are translated to an equivalent `RRULE` so
82
+ the plugin depends on fewer host shapes. The plugin stores only `scheduleId`
83
+ plus a small reference — never a copy of cron state.
84
+
85
+ ## Execution protocol
86
+
87
+ A run is executed **by the calling Agent in its own authorized context**. There
88
+ is no worker process, and a `followup` receipt is never treated as completion.
89
+
90
+ 1. `task_run` or `task_run_begin` → `runId` + snapshot + step list.
91
+ 2. For each step in `order`: `task_step_report(action:"started")`.
92
+ 3. `task_step_report(action:"completed" | "failed" | "skipped")` with a real
93
+ summary. `completed` requires the step's `completionCriteria` to be met.
94
+ 4. Missing input, a pending approval, or an unmet external condition →
95
+ `task_run_finish(status:"blocked", summary:"…")` naming what is awaited.
96
+ 5. All required steps completed → `task_run_finish(status:"succeeded")`.
97
+ 6. A failure → `task_step_report(action:"failed", error:{…})` **then**
98
+ `task_run_finish(status:"failed")`.
99
+
100
+ Progress is always `floor(completed required steps / required steps × 100)` and is
101
+ recomputed from persisted step rows — never from caller claims.
102
+
103
+ ### Scheduled runs
104
+
105
+ A `task_schedule` create stores a prompt carrying `task_id_json` on the host
106
+ schedule. When a delivery arrives:
107
+
108
+ ```text
109
+ task_run_begin({ triggerPayload: "<the delivered message>" })
110
+ ```
111
+
112
+ The tool extracts `task_id_json`, `schedule_id_json` and `occurrence_at`, then
113
+ uses `schedule:<scheduleId>:<occurrence>` as the idempotency key. A duplicated
114
+ delivery returns the existing run with `deduplicated: true` instead of starting a
115
+ second execution. **Delivery proves the message was enqueued — not that the run
116
+ finished.**
117
+
118
+ ## Data model
119
+
120
+ StorageDomain unit `dsh_background_task_engine`, schema version `1`
121
+ (the underscore form is required: the host's unit-name rule is
122
+ `/^[a-z][a-z0-9_]*$/`).
123
+
124
+ | Table | Key | Contents |
125
+ |---|---|---|
126
+ | `tasks` | `taskId` | template, status, revision, owner Session, steps, schedule reference |
127
+ | `task_runs` | `runId` | status, trigger, snapshot, progress, times, summary/error, `resumesRunId` |
128
+ | `task_run_steps` | `runId/stepId` | per-run step status, attempt, times, summary/error |
129
+ | `meta` | `global` | `schemaVersion`, applied-migration ledger, recovery/prune timestamps |
130
+
131
+ Status machines:
132
+
133
+ ```text
134
+ Task active → paused → active active/paused → archived (final)
135
+ TaskRun queued → running → succeeded | failed | blocked | interrupted
136
+ queued → skipped
137
+ blocked → failed | interrupted (never back to running)
138
+ ```
139
+
140
+ `failed`, `succeeded`, `interrupted` and `skipped` are terminal. Recovery always
141
+ creates a **new** run with `resumesRunId`; completed steps are carried over, the
142
+ run continues at the first unfinished step, and a run whose failed step may have
143
+ had side effects requires an explicit `confirmation`.
144
+
145
+ Retention: terminal runs older than `historyRetentionDays` (default 90) are
146
+ pruned with their step rows at startup. Active runs, templates and audit events
147
+ are never pruned.
148
+
149
+ ## Configuration
150
+
151
+ Exported as `Config` (Schemastery) and validated again at load; out-of-range
152
+ values fail the load rather than being clamped.
153
+
154
+ | Key | Default | Range | Meaning |
155
+ |---|---|---|---|
156
+ | `maxTasksPerOwner` | 100 | 1–1000 | unarchived templates per Session |
157
+ | `maxStepsPerTask` | 10 | 1–10 | steps per template (V1.0 is linear) |
158
+ | `maxActiveRunsPerOwner` | 3 | 1–20 | concurrent queued/running runs per Session |
159
+ | `maxParallelRunsPerTask` | 1 | 1 | parallel runs of one task (fixed in V1.0) |
160
+ | `defaultTimeoutMinutes` | 60 | 1–1440 | timeout used for identification only |
161
+ | `staleRunAfterMinutes` | 30 | 1–1440 | age at which a startup scan marks a run `interrupted` |
162
+ | `historyRetentionDays` | 90 | 1–3650 | terminal run retention |
163
+ | `maxSummaryChars` | 2000 | 100–10000 | summary truncation bound |
164
+
165
+ ## Errors
166
+
167
+ | Code | Meaning | Retryable |
168
+ |---|---|---|
169
+ | `TASK_NOT_FOUND` | task missing, or not owned by this Session | no |
170
+ | `TASK_ALREADY_RUNNING` | the task already has an active run | after it ends |
171
+ | `TASK_REVISION_CONFLICT` | `expectedRevision` is stale | re-read, then retry |
172
+ | `TASK_INVALID_STEPS` | bad step definition / count | fix arguments |
173
+ | `TASK_RUN_NOT_FOUND` | run missing or not owned by this Session | no |
174
+ | `TASK_RUN_ALREADY_FINISHED` | run is terminal | start a new run |
175
+ | `TASK_STEP_ORDER_INVALID` | out-of-order, unknown, or duplicate step report | fix order |
176
+ | `TASK_PERMISSION_DENIED` | archived/paused task, or missing resume confirmation | no |
177
+ | `TASK_SCHEDULE_UNAVAILABLE` | Schedule not mounted | after the host provides it |
178
+ | `TASK_SCHEDULE_FAILED` | host schedule operation failed | inspect host state |
179
+ | `TASK_STORAGE_ERROR` | StorageDomain missing, failed, or incompatible | after the host is fixed |
180
+ | `TASK_RUN_INTERRUPTED` | execution lost, marked interrupted | `task_resume` |
181
+ | `TASK_MAX_CONCURRENCY` | per-Session active-run cap reached | after a run ends |
182
+ | `TASK_INVALID_ARGUMENTS` | argument failed validation | fix arguments |
183
+ | `TASK_INTERNAL_ERROR` | unexpected runtime failure | no |
184
+
185
+ The first 13 are the PRD's stable codes; the last two are additive so an
186
+ unexpected failure is never reported as a misleading PRD code.
187
+
188
+ ## Security
189
+
190
+ - **Session isolation.** Every tool entry point resolves the caller Session from
191
+ `exec.agent.session.id` and compares it with the record owner. A record owned by
192
+ another Session is reported as `TASK_NOT_FOUND`, so the error cannot be used to
193
+ probe other Sessions' data.
194
+ - **No privilege escalation.** The engine never adds shell, file, browser or
195
+ network capability. Every action runs through the Agent's already-authorized
196
+ tools and existing approval flow.
197
+ - **Templates are data.** Step `instruction` text is user content with no
198
+ elevated authority; a template cannot change system prompts, permissions or
199
+ tool access. External text is rendered as untrusted single-line text.
200
+ - **No leakage.** Error messages are sanitised: stack frames dropped, absolute
201
+ paths replaced with `<path>`, credential-looking assignments redacted.
202
+ - **No code injection.** Task arguments cannot carry JavaScript, dynamic imports
203
+ or scripts; there is no evaluator anywhere in the plugin.
204
+ - Scheduling is bound to the creating Session, so a scheduled run executes in the
205
+ Session that owns the task.
206
+
207
+ ## Upgrade
208
+
209
+ 1. Bump the bundle; the plugin row keeps its config.
210
+ 2. On next start the engine opens the domain, compares the stored
211
+ `meta.schemaVersion`, and runs any pending migration once each, recording a
212
+ marker **only after** the migration succeeds.
213
+ 3. A stored version **higher** than the plugin supports is refused with
214
+ `TASK_STORAGE_ERROR` — downgrading is not silently allowed.
215
+
216
+ v1.0.0 ships an empty migration set (the baseline shape needs none); the runner
217
+ and ledger exist so a future shape change is a data edit plus one entry.
218
+
219
+ ## Troubleshooting
220
+
221
+ | Symptom | Cause | Fix |
222
+ |---|---|---|
223
+ | Every tool returns `TASK_STORAGE_ERROR` mentioning `ctx.storageDomain` | the Host has no StorageDomain mounted | enable `storage` + `storage-json` + `storage-domain` in the profile |
224
+ | `invalid unit name '…'` | a domain/table name with a hyphen | the unit must match `/^[a-z][a-z0-9_]*$/` (this plugin uses `dsh_background_task_engine`) |
225
+ | `TASK_SCHEDULE_UNAVAILABLE` | `ctx.schedule` is not mounted | scheduling is optional; manual runs still work |
226
+ | Row did not activate: *cannot get property "…" without inject* | a plugin read an optional service as a property | resolve optional services via `ctx.get` |
227
+ | `TASK_REVISION_CONFLICT` | two edits raced | `task_get`, then retry with the current `revision` |
228
+ | A run is `interrupted` after a restart | the Host stopped mid-run; nothing is auto-restarted | `task_resume` with a confirmation if a step may have had side effects |
229
+ | Install rejected: *dsh.bundle.patch must be a file path* | flat manifest form | use `"dsh": { "bundle": { "patch": "./cordis.patch.yml" } }` |
230
+
231
+ ## Development
232
+
233
+ ```sh
234
+ npm install
235
+ npm run build # tsc -> dist/
236
+ npm run typecheck
237
+ npm test # 81 tests
238
+ ```
239
+
240
+ Layout:
241
+
242
+ ```text
243
+ src/
244
+ index.ts plugin entry: name / inject / Config / apply
245
+ host.ts structural host contract (no host package imports)
246
+ config.ts Schemastery Config + resolveConfig
247
+ errors.ts stable codes, payloads, message sanitisation
248
+ domain/records.ts zod record schemas
249
+ domain/state.ts TaskRun/StepRun state machines, progress, ordering
250
+ storage/spec.ts domain declaration, migrations, integrity check
251
+ storage/repository.ts the only reader/writer of domain tables
252
+ services/ audit, task, run, schedule adapter, engine
253
+ tools/ 12 tool definitions + shared plumbing
254
+ prompt/guidance.ts execution protocol and delivery parsing
255
+ tests/ domain, storage, rendering, integration (+ fakes)
256
+ docs/ API compatibility audit, test report, detail page
257
+ ```
258
+
259
+ Verification records: `docs/API-COMPATIBILITY-AUDIT.md` (host capability audit,
260
+ including the real-stack runs) and `docs/TEST-REPORT.md` (all 81 assertions).
261
+
262
+ ## License
263
+
264
+ MIT — see [LICENSE](LICENSE).
package/README.zh.md ADDED
@@ -0,0 +1,179 @@
1
+ # dsh-background-task-engine
2
+
3
+ DeepSeek Harness 的**后台任务引擎**:可复用的任务模板、有序线性步骤、单次运行账本、进度与历史查询、失败/中断后的人工恢复,以及可选的 DSH 原生定时关联。
4
+
5
+ 它不实现调度器、Agent Loop、作业注册表或存储后端,而是复用 Host 自身的 `ctx.schedule`、`ctx.storageDomain` 与 `ctx.tools`。
6
+
7
+ - [安装](#安装)
8
+ - [工具](#工具)
9
+ - [执行协议](#执行协议)
10
+ - [数据模型](#数据模型)
11
+ - [配置](#配置)
12
+ - [错误码](#错误码)
13
+ - [安全](#安全)
14
+ - [升级](#升级)
15
+ - [排障](#排障)
16
+ - [开发](#开发)
17
+
18
+ ## 安装
19
+
20
+ 要求:DSH **0.2.2-rc.3** 或兼容版本,且已挂载 `ctx.storageDomain`(官方 base bundle 默认以 `storage-domain backend: json` 挂载)。
21
+
22
+ ```sh
23
+ # 本地目录
24
+ dsh plugin --profile <名称> add /绝对路径/dsh-background-task-engine
25
+
26
+ # 或从 npm
27
+ dsh plugin --profile <名称> add dsh-background-task-engine
28
+ ```
29
+
30
+ 重启应用后,在 **插件** 页面确认 `background-task-engine` 一行已启用,并显示本包的标题、描述与图标。
31
+
32
+ ## 工具
33
+
34
+ 12 个模型可见工具,统一返回 `{ success: true, ... }` 或 `{ success: false, error: { code, message, retryable, relatedRunId? } }`。
35
+
36
+ | 工具 | 用途 | 关键参数 |
37
+ |---|---|---|
38
+ | `task_create` | 创建模板(1–10 步) | `title`、`description?`、`steps[]`、`copyFromTaskId?` |
39
+ | `task_list` | 列出本会话模板 | `status?`、`query?`、`limit?`、`cursor?` |
40
+ | `task_get` | 查看模板与最近运行 | `taskId`、`includeRuns?` |
41
+ | `task_update` | 修改标题/描述/步骤/状态 | `taskId`、`expectedRevision`、变更字段 |
42
+ | `task_archive` | 软归档,保留历史 | `taskId`、`expectedRevision` |
43
+ | `task_schedule` | 管理原生定时关联 | `taskId`、`action`、`timing?`、`scheduleRule?` |
44
+ | `task_run` | 立即手动执行 | `taskId`、`manualRunId?`、`defer?` |
45
+ | `task_run_begin` | 认领一次运行 | `taskId?`、`runId?`、`triggerPayload?`、`scheduleId?`、`occurrenceKey?`、`idempotencyKey?` |
46
+ | `task_step_report` | 上报步骤 | `runId`、`stepId`、`action`、`summary?`、`error?` |
47
+ | `task_run_finish` | 提交运行结果 | `runId`、`status`、`summary?`、`error?` |
48
+ | `task_run_history` | 分页查询运行历史 | `taskId`、`status?`、`limit?`、`cursor?` |
49
+ | `task_resume` | 恢复失败/中断/阻塞运行 | `runId`、`confirmation?` |
50
+
51
+ `task_schedule` 的 action:`create`、`update`、`pause`、`resume`、`delete`、`run_now`、`status`。timing 支持 `at`、`every`、`rrule`、`cron`、`daily`、`weekly`;其中 `daily`/`weekly` 会转换成等价的 `RRULE`,以减少对宿主 shapes 的依赖。插件只保存 `scheduleId` 与少量引用,不复制任何 Cron 状态。
52
+
53
+ ## 执行协议
54
+
55
+ 运行由**调用方 Agent 在自己的授权上下文中**执行,没有独立 worker 进程,也不会把 followup 回执当作完成凭证。
56
+
57
+ 1. `task_run` 或 `task_run_begin` → 取得 `runId`、模板快照与步骤列表。
58
+ 2. 按 `order` 顺序对每一步调用 `task_step_report(action:"started")`。
59
+ 3. 结束时报告 `completed` / `failed` / `skipped` 并给出真实摘要;`completed` 必须满足该步骤的 `completionCriteria`。
60
+ 4. 缺少输入、等待审批或外部条件不满足 → `task_run_finish(status:"blocked", summary:"…")`,说明在等什么。
61
+ 5. 全部必需步骤 completed → `task_run_finish(status:"succeeded")`。
62
+ 6. 失败 → 先 `task_step_report(action:"failed", error:{…})`,再 `task_run_finish(status:"failed")`。
63
+
64
+ 进度恒为 `floor(已完成必需步骤数 / 必需步骤总数 × 100)`,且始终由已持久化的步骤记录重算,不采信调用方自报。
65
+
66
+ ### 定时触发
67
+
68
+ `task_schedule` 创建时会把带 `task_id_json` 的提示词写入宿主定时任务。投递到达后:
69
+
70
+ ```text
71
+ task_run_begin({ triggerPayload: "<投递消息原文>" })
72
+ ```
73
+
74
+ 工具会从中提取 `task_id_json`、`schedule_id_json` 与 `occurrence_at`,并以 `schedule:<scheduleId>:<occurrence>` 作为幂等键。重复投递返回已有运行并标记 `deduplicated: true`,不会重复启动。**投递只证明消息入队,不代表运行完成。**
75
+
76
+ ## 数据模型
77
+
78
+ StorageDomain 单元 `dsh_background_task_engine`,schema 版本 `1`(必须使用下划线形式:宿主的单元名规则是 `/^[a-z][a-z0-9_]*$/`)。
79
+
80
+ | 表 | 主键 | 内容 |
81
+ |---|---|---|
82
+ | `tasks` | `taskId` | 模板、状态、revision、所属会话、步骤、定时引用 |
83
+ | `task_runs` | `runId` | 状态、触发来源、快照、进度、时间、摘要/错误、`resumesRunId` |
84
+ | `task_run_steps` | `runId/stepId` | 本次运行的步骤状态、尝试次数、时间、摘要/错误 |
85
+ | `meta` | `global` | `schemaVersion`、迁移台账、恢复/清理时间 |
86
+
87
+ 状态机:
88
+
89
+ ```text
90
+ Task active → paused → active active/paused → archived(终态)
91
+ TaskRun queued → running → succeeded | failed | blocked | interrupted
92
+ queued → skipped
93
+ blocked → failed | interrupted (绝不回到 running)
94
+ ```
95
+
96
+ `succeeded`、`failed`、`interrupted`、`skipped` 为终态。恢复总是创建**新的**运行并写 `resumesRunId`;已完成步骤被结转,从第一个未完成步骤继续;若失败步骤可能已产生副作用,必须提供 `confirmation`。
97
+
98
+ 保留策略:超过 `historyRetentionDays`(默认 90 天)的终态运行及其步骤行会在启动时清理。活动运行、任务模板与审计事件永不清理。
99
+
100
+ ## 配置
101
+
102
+ 以 `Config`(Schemastery)导出,加载时二次校验;越界值会使加载失败而不是被静默截断。
103
+
104
+ | 配置项 | 默认 | 范围 | 含义 |
105
+ |---|---|---|---|
106
+ | `maxTasksPerOwner` | 100 | 1–1000 | 每个会话未归档模板上限 |
107
+ | `maxStepsPerTask` | 10 | 1–10 | 单任务步骤上限(V1.0 为线性) |
108
+ | `maxActiveRunsPerOwner` | 3 | 1–20 | 每个会话并发 queued/running 上限 |
109
+ | `maxParallelRunsPerTask` | 1 | 1 | 同一任务并行运行数(V1.0 固定) |
110
+ | `defaultTimeoutMinutes` | 60 | 1–1440 | 超时识别阈值(仅用于识别) |
111
+ | `staleRunAfterMinutes` | 30 | 1–1440 | 启动扫描判定 `interrupted` 的失联时长 |
112
+ | `historyRetentionDays` | 90 | 1–3650 | 终态运行保留天数 |
113
+ | `maxSummaryChars` | 2000 | 100–10000 | 摘要截断上限 |
114
+
115
+ ## 错误码
116
+
117
+ | 错误码 | 含义 | 可重试 |
118
+ |---|---|---|
119
+ | `TASK_NOT_FOUND` | 任务不存在或不属于当前会话 | 否 |
120
+ | `TASK_ALREADY_RUNNING` | 已有活动运行 | 运行结束后 |
121
+ | `TASK_REVISION_CONFLICT` | `expectedRevision` 已过期 | 重新读取后重试 |
122
+ | `TASK_INVALID_STEPS` | 步骤定义或数量非法 | 修正参数 |
123
+ | `TASK_RUN_NOT_FOUND` | 运行不存在或不属于当前会话 | 否 |
124
+ | `TASK_RUN_ALREADY_FINISHED` | 运行已终态 | 创建新运行 |
125
+ | `TASK_STEP_ORDER_INVALID` | 顺序错误、未知步骤或重复上报 | 修正顺序 |
126
+ | `TASK_PERMISSION_DENIED` | 任务已归档/暂停,或缺少恢复确认 | 否 |
127
+ | `TASK_SCHEDULE_UNAVAILABLE` | Schedule 未挂载 | 宿主提供后 |
128
+ | `TASK_SCHEDULE_FAILED` | 宿主定时操作失败 | 核对宿主状态 |
129
+ | `TASK_STORAGE_ERROR` | StorageDomain 缺失、失败或不兼容 | 宿主修复后 |
130
+ | `TASK_RUN_INTERRUPTED` | 执行丢失,已标记中断 | 用 `task_resume` |
131
+ | `TASK_MAX_CONCURRENCY` | 达到会话并发上限 | 运行结束后 |
132
+ | `TASK_INVALID_ARGUMENTS` | 参数校验失败 | 修正参数 |
133
+ | `TASK_INTERNAL_ERROR` | 未预期的运行时错误 | 否 |
134
+
135
+ 前 13 个是 PRD 稳定错误码;后两个为补充,确保意外失败不会被误报成 PRD 错误码。
136
+
137
+ ## 安全
138
+
139
+ - **会话隔离**:每个工具入口都从 `exec.agent.session.id` 解析调用方并与记录归属比对;他人会话的记录一律报 `TASK_NOT_FOUND`,避免被用来探测。
140
+ - **不提升权限**:插件不新增 Shell、文件、浏览器或网络能力;所有动作沿用 Agent 已授权的工具与既有审批流程。
141
+ - **模板是数据**:步骤 `instruction` 是用户内容,不具更高权限;模板无法改变系统提示、权限或工具可用性。外部文本按不可信单行文本渲染。
142
+ - **不泄露**:错误信息经净化处理——丢弃堆栈、把绝对路径替换为 `<path>`、脱敏疑似凭据。
143
+ - **不可注入代码**:任务参数不能携带 JavaScript、动态 import 或脚本,插件内不存在任何求值器。
144
+ - 定时任务绑定创建时的会话,因此到期执行发生在拥有该任务的会话内。
145
+
146
+ ## 升级
147
+
148
+ 1. 升级 bundle,插件行保留其 provenance 与配置。
149
+ 2. 下次启动时引擎打开 domain、比对 `meta.schemaVersion`,逐条执行尚未应用的迁移;每条迁移**成功之后**才写入台账标记。
150
+ 3. 若存储版本**高于**插件支持版本,直接以 `TASK_STORAGE_ERROR` 拒绝——不允许静默降级。
151
+
152
+ v1.0.0 附带空迁移集(基线结构无需迁移),但运行器与台账已就位,未来结构变更只需新增一条迁移。
153
+
154
+ ## 排障
155
+
156
+ | 现象 | 原因 | 处理 |
157
+ |---|---|---|
158
+ | 所有工具报 `TASK_STORAGE_ERROR`(提到 `ctx.storageDomain`) | Host 未挂载 StorageDomain | 在 profile 中启用 `storage` + `storage-json` + `storage-domain` |
159
+ | `invalid unit name '…'` | domain/表名含连字符 | 单元名必须匹配 `/^[a-z][a-z0-9_]*$/`(本插件用 `dsh_background_task_engine`) |
160
+ | `TASK_SCHEDULE_UNAVAILABLE` | 未挂载 `ctx.schedule` | 定时是可选项,手动执行不受影响 |
161
+ | 插件行未激活:*cannot get property "…" without inject* | 以属性方式读取可选服务 | 可选服务应通过 `ctx.get` 获取 |
162
+ | `TASK_REVISION_CONFLICT` | 两次修改竞争 | 先 `task_get` 取最新 `revision` 再改 |
163
+ | 重启后运行变成 `interrupted` | Host 中途停止,且不会自动重启 | 若失败步骤可能有副作用,带 `confirmation` 调用 `task_resume` |
164
+ | 安装被拒:*dsh.bundle.patch must be a file path* | 清单用了扁平写法 | 使用 `"dsh": { "bundle": { "patch": "./cordis.patch.yml" } }` |
165
+
166
+ ## 开发
167
+
168
+ ```sh
169
+ npm install
170
+ npm run build # tsc -> dist/
171
+ npm run typecheck
172
+ npm test # 81 个用例
173
+ ```
174
+
175
+ 目录结构与验证记录见英文 README;宿主能力审计见 `docs/API-COMPATIBILITY-AUDIT.md`,全部 81 条断言见 `docs/TEST-REPORT.md`。
176
+
177
+ ## 许可证
178
+
179
+ MIT,见 [LICENSE](LICENSE)。
@@ -0,0 +1,20 @@
1
+ # dsh-background-task-engine bundle patch.
2
+ #
3
+ # The patch registers the plugin into a profile. `plugin_manager install_bundle`
4
+ # appends this row to the profile's cordis.patch.yml and installs the package.
5
+ #
6
+ # `config` mirrors src/config.ts (Schemastery). Every value below is validated
7
+ # again at load time; out-of-range values fail the plugin load instead of being
8
+ # silently clamped.
9
+ - insert:
10
+ - id: background-task-engine
11
+ name: 'dsh-background-task-engine'
12
+ config:
13
+ maxTasksPerOwner: 100
14
+ maxStepsPerTask: 10
15
+ maxActiveRunsPerOwner: 3
16
+ maxParallelRunsPerTask: 1
17
+ defaultTimeoutMinutes: 60
18
+ staleRunAfterMinutes: 30
19
+ historyRetentionDays: 90
20
+ maxSummaryChars: 2000
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Configuration schema (PRD 4.4 / FR-012).
3
+ *
4
+ * Exported as `Config` so the DSH loader validates profile config before the
5
+ * plugin is applied. `resolveConfig` re-validates and fills defaults so the
6
+ * engine never runs with out-of-range numbers even when it is constructed
7
+ * directly (tests, embedded use).
8
+ */
9
+ import Schema from '@deepseek-ai/schemastery';
10
+ export interface EngineConfig {
11
+ maxTasksPerOwner: number;
12
+ maxStepsPerTask: number;
13
+ maxActiveRunsPerOwner: number;
14
+ maxParallelRunsPerTask: number;
15
+ defaultTimeoutMinutes: number;
16
+ staleRunAfterMinutes: number;
17
+ historyRetentionDays: number;
18
+ maxSummaryChars: number;
19
+ }
20
+ export declare const CONFIG_LIMITS: {
21
+ readonly maxTasksPerOwner: {
22
+ readonly min: 1;
23
+ readonly max: 1000;
24
+ readonly default: 100;
25
+ };
26
+ readonly maxStepsPerTask: {
27
+ readonly min: 1;
28
+ readonly max: 10;
29
+ readonly default: 10;
30
+ };
31
+ readonly maxActiveRunsPerOwner: {
32
+ readonly min: 1;
33
+ readonly max: 20;
34
+ readonly default: 3;
35
+ };
36
+ readonly maxParallelRunsPerTask: {
37
+ readonly min: 1;
38
+ readonly max: 1;
39
+ readonly default: 1;
40
+ };
41
+ readonly defaultTimeoutMinutes: {
42
+ readonly min: 1;
43
+ readonly max: 1440;
44
+ readonly default: 60;
45
+ };
46
+ readonly staleRunAfterMinutes: {
47
+ readonly min: 1;
48
+ readonly max: 1440;
49
+ readonly default: 30;
50
+ };
51
+ readonly historyRetentionDays: {
52
+ readonly min: 1;
53
+ readonly max: 3650;
54
+ readonly default: 90;
55
+ };
56
+ readonly maxSummaryChars: {
57
+ readonly min: 100;
58
+ readonly max: 10000;
59
+ readonly default: 2000;
60
+ };
61
+ };
62
+ export declare const Config: Schema<Schemastery.ObjectS<NoInfer<{
63
+ maxTasksPerOwner: Schema<number, number, "defined">;
64
+ maxStepsPerTask: Schema<number, number, "defined">;
65
+ maxActiveRunsPerOwner: Schema<number, number, "defined">;
66
+ maxParallelRunsPerTask: Schema<number, number, "defined">;
67
+ defaultTimeoutMinutes: Schema<number, number, "defined">;
68
+ staleRunAfterMinutes: Schema<number, number, "defined">;
69
+ historyRetentionDays: Schema<number, number, "defined">;
70
+ maxSummaryChars: Schema<number, number, "defined">;
71
+ }>>, Schemastery.ObjectT<NoInfer<{
72
+ maxTasksPerOwner: Schema<number, number, "defined">;
73
+ maxStepsPerTask: Schema<number, number, "defined">;
74
+ maxActiveRunsPerOwner: Schema<number, number, "defined">;
75
+ maxParallelRunsPerTask: Schema<number, number, "defined">;
76
+ defaultTimeoutMinutes: Schema<number, number, "defined">;
77
+ staleRunAfterMinutes: Schema<number, number, "defined">;
78
+ historyRetentionDays: Schema<number, number, "defined">;
79
+ maxSummaryChars: Schema<number, number, "defined">;
80
+ }>>, "plain">;
81
+ export declare const DEFAULT_CONFIG: EngineConfig;
82
+ /**
83
+ * Validate a raw config object. Throws (with a message naming the key and the
84
+ * allowed range) instead of clamping, so a misconfigured profile fails loudly.
85
+ */
86
+ export declare function resolveConfig(raw?: unknown): EngineConfig;