@acryldev/tasks 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 acrylblends
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,15 @@
1
- # Temporary Holding Version
1
+ # @acryldev/tasks
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
+ Durable task records: id, owner, input, status, result, trace; appended to a log in the app's home and readable after a restart.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @acryldev/tasks
9
+ ```
10
+
11
+ It is a Cordis plugin: its peer dependency is `@deepseek-ai/cordis`, and an app registers it as a row of its `blend.yaml`.
12
+
13
+ ## Source and license
14
+
15
+ Part of [ACRYL](https://github.com/acryldev/acryl): [`plugins/tasks`](https://github.com/acryldev/acryl/tree/main/plugins/tasks). MIT license.
package/index.ts ADDED
@@ -0,0 +1,246 @@
1
+ /**
2
+ * Durable task records (`ctx.tasks`).
3
+ *
4
+ * The idea comes from Pi Durable (see spec 013, "Ideas from Pi Durable"), kept to what Cordis does not already do: every piece of work
5
+ * gets a record with an id, an optional owner (parent), its input, status, result or error, and timestamps. Each change is appended to
6
+ * `<home>/tasks.jsonl` before the call that made it returns, so nothing is presented as done before it is recorded. At startup the log is
7
+ * folded back into records, and a task still `running` is marked `interrupted`: it is reported, never silently run again, because an
8
+ * external side effect may already have happened. Cancelling a task cancels the tasks it owns and aborts their signals.
9
+ */
10
+
11
+ import { randomUUID } from 'node:crypto'
12
+ import type {} from '@acryldev/instance'
13
+ import { type Context, Service } from '@deepseek-ai/cordis'
14
+ import { openStore, type StoreKind, type TaskChange, type TaskStore } from './store.ts'
15
+
16
+ export interface TasksConfig {
17
+ /** Recorded on every task: the digest of the manifest the app was composed from. */
18
+ manifest?: string
19
+ /** Where changes are kept: a JSON lines file (default) or a SQLite file. */
20
+ store?: StoreKind
21
+ }
22
+
23
+ export type TaskStatus = 'running' | 'completed' | 'failed' | 'cancelled' | 'interrupted'
24
+
25
+ export interface TaskRecord {
26
+ readonly id: string
27
+ readonly kind: string
28
+ readonly parent?: string
29
+ /** The digest of the manifest the app was composed from, so a task traces to the configuration that ran it. */
30
+ readonly manifest?: string
31
+ readonly input: unknown
32
+ readonly status: TaskStatus
33
+ readonly result?: unknown
34
+ readonly error?: string
35
+ /** Free-form progress the owner attached (for example a tool-call trace). */
36
+ readonly detail?: unknown
37
+ readonly createdAt: string
38
+ readonly updatedAt: string
39
+ }
40
+
41
+ /** What the owner of a running task holds. */
42
+ export interface TaskHandle {
43
+ readonly id: string
44
+ /** Aborted when the task, or a task that owns it, is cancelled. */
45
+ readonly signal: AbortSignal
46
+ /** Record progress without changing the status. */
47
+ progress(detail: unknown): void
48
+ complete(result: unknown, detail?: unknown): void
49
+ fail(error: unknown, detail?: unknown): void
50
+ }
51
+
52
+ export interface TaskFilter {
53
+ readonly status?: TaskStatus
54
+ readonly parent?: string
55
+ readonly kind?: string
56
+ }
57
+
58
+ declare module '@deepseek-ai/cordis' {
59
+ interface Context {
60
+ tasks: Tasks
61
+ }
62
+
63
+ interface Events {
64
+ /** A task record changed (after the change was written). */
65
+ 'tasks/changed'(record: TaskRecord): void
66
+ }
67
+ }
68
+
69
+ type Change = Partial<TaskRecord> & { readonly id: string }
70
+ const changeOf = (change: TaskChange) => change as unknown as Change
71
+
72
+ /** The slice of the state service the tasks plugin uses, by name, so it imports nothing from @acryldev/state. */
73
+ interface StateService {
74
+ cell<T>(key: string, initial: T): { set(value: T): void }
75
+ }
76
+
77
+ /** How many of the newest tasks the state cell holds. */
78
+ const STATE_LIMIT = 100
79
+
80
+ const FINAL: ReadonlySet<TaskStatus> = new Set(['completed', 'failed', 'cancelled', 'interrupted'])
81
+ const message = (error: unknown) => (error instanceof Error ? error.message : String(error))
82
+
83
+ export class Tasks extends Service {
84
+ readonly file: string
85
+ /** Tasks found running at startup and marked interrupted. */
86
+ readonly interrupted: readonly string[]
87
+ private readonly records = new Map<string, TaskRecord>()
88
+ private readonly controllers = new Map<string, AbortController>()
89
+
90
+ private readonly store: TaskStore
91
+ private readonly manifest: string | undefined
92
+
93
+ constructor(ctx: Context, config: TasksConfig = {}) {
94
+ super(ctx, 'tasks')
95
+ this.manifest = config.manifest
96
+ const opened = openStore(config.store ?? 'jsonl', ctx.appInstance.home)
97
+ this.file = opened.file
98
+ this.store = opened.store
99
+ // Disposers run newest first, so this one runs last: the store closes after pending work has been recorded.
100
+ ctx.effect(() => () => this.store.close(), 'tasks: close the store')
101
+ this.load()
102
+ const interrupted: string[] = []
103
+ for (const record of this.records.values()) {
104
+ if (record.status === 'running') {
105
+ this.write({
106
+ id: record.id,
107
+ status: 'interrupted',
108
+ error: 'the app stopped while this task was running',
109
+ })
110
+ interrupted.push(record.id)
111
+ }
112
+ }
113
+ this.interrupted = interrupted
114
+ // Work still running when the app stops is cancelled, so its owner's signal fires and the record says what happened.
115
+ ctx.effect(
116
+ () => () => {
117
+ for (const id of [...this.controllers.keys()])
118
+ this.finish(id, { status: 'cancelled', error: 'the app stopped' })
119
+ },
120
+ 'tasks: cancel running work',
121
+ )
122
+ // With the state service mounted, the latest tasks are also a cell: any surface reads them as JSON or streams their changes (`/api/state/tasks`).
123
+ ctx.inject(['state'], (inner) => {
124
+ const state = (inner as unknown as { state: StateService }).state
125
+ const cell = state.cell('tasks', this.list().slice(0, STATE_LIMIT))
126
+ inner.on('tasks/changed', () => cell.set(this.list().slice(0, STATE_LIMIT)))
127
+ })
128
+ }
129
+
130
+ /** Start a task. The record is written before this returns. */
131
+ start(kind: string, input: unknown, options: { parent?: string } = {}): TaskHandle {
132
+ if (options.parent !== undefined && !this.records.has(options.parent))
133
+ throw new Error(`tasks: no task "${options.parent}" to own this one`)
134
+ const id = randomUUID()
135
+ const now = new Date().toISOString()
136
+ const controller = new AbortController()
137
+ if (options.parent !== undefined) {
138
+ const parentSignal = this.controllers.get(options.parent)?.signal
139
+ if (parentSignal?.aborted) controller.abort()
140
+ }
141
+ this.controllers.set(id, controller)
142
+ this.write({
143
+ id,
144
+ kind,
145
+ ...(options.parent === undefined ? {} : { parent: options.parent }),
146
+ ...(this.manifest === undefined ? {} : { manifest: this.manifest }),
147
+ input,
148
+ status: 'running',
149
+ createdAt: now,
150
+ updatedAt: now,
151
+ })
152
+ return {
153
+ id,
154
+ signal: controller.signal,
155
+ progress: (detail) => {
156
+ if (!this.isRunning(id)) return
157
+ this.write({ id, detail })
158
+ },
159
+ complete: (result, detail) =>
160
+ this.finish(id, {
161
+ status: 'completed',
162
+ result,
163
+ ...(detail === undefined ? {} : { detail }),
164
+ }),
165
+ fail: (error, detail) =>
166
+ this.finish(id, {
167
+ status: 'failed',
168
+ error: message(error),
169
+ ...(detail === undefined ? {} : { detail }),
170
+ }),
171
+ }
172
+ }
173
+
174
+ get(id: string): TaskRecord | undefined {
175
+ return this.records.get(id)
176
+ }
177
+
178
+ /** Records, newest first. */
179
+ list(filter: TaskFilter = {}): TaskRecord[] {
180
+ return [...this.records.values()]
181
+ .filter(
182
+ (record) =>
183
+ (filter.status === undefined || record.status === filter.status) &&
184
+ (filter.parent === undefined || record.parent === filter.parent) &&
185
+ (filter.kind === undefined || record.kind === filter.kind),
186
+ )
187
+ .sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0))
188
+ }
189
+
190
+ /** Cancel a running task and every running task it owns, children first. Returns the ids cancelled. */
191
+ cancel(id: string): string[] {
192
+ const cancelled: string[] = []
193
+ const visit = (taskId: string) => {
194
+ for (const child of this.list({ parent: taskId })) visit(child.id)
195
+ if (this.isRunning(taskId)) {
196
+ this.finish(taskId, { status: 'cancelled', error: 'cancelled' })
197
+ cancelled.push(taskId)
198
+ }
199
+ }
200
+ if (!this.records.has(id)) throw new Error(`tasks: no task "${id}"`)
201
+ visit(id)
202
+ return cancelled
203
+ }
204
+
205
+ private isRunning(id: string): boolean {
206
+ return this.records.get(id)?.status === 'running'
207
+ }
208
+
209
+ private finish(id: string, change: Omit<Change, 'id'>): void {
210
+ if (!this.isRunning(id)) return
211
+ this.write({ id, ...change })
212
+ const controller = this.controllers.get(id)
213
+ this.controllers.delete(id)
214
+ controller?.abort()
215
+ }
216
+
217
+ /** Append one change and apply it. The line is on disk before the record changes in memory. */
218
+ private write(change: Change): void {
219
+ const now = new Date().toISOString()
220
+ const line = { updatedAt: now, ...change }
221
+ this.store.append(line)
222
+ const record = this.apply(line)
223
+ this.ctx.emit('tasks/changed', record)
224
+ }
225
+
226
+ private apply(change: Change): TaskRecord {
227
+ const current = this.records.get(change.id)
228
+ const next = { ...(current ?? {}), ...change } as TaskRecord
229
+ if (current && FINAL.has(current.status) && change.status !== undefined) return current
230
+ this.records.set(change.id, next)
231
+ return next
232
+ }
233
+
234
+ private load(): void {
235
+ for (const change of this.store.load()) this.apply(changeOf(change))
236
+ }
237
+ }
238
+
239
+ /** The plugin: mount it after `instance`. */
240
+ export const tasks = {
241
+ name: 'tasks',
242
+ inject: ['appInstance'],
243
+ apply(ctx: Context, config?: TasksConfig) {
244
+ new Tasks(ctx, config ?? {})
245
+ },
246
+ }
package/lib/index.js ADDED
@@ -0,0 +1,231 @@
1
+ import { createRequire } from "node:module";
2
+ import { randomUUID } from "node:crypto";
3
+ import { Service } from "@deepseek-ai/cordis";
4
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
5
+ import { dirname } from "node:path";
6
+ //#region store.ts
7
+ /**
8
+ * Where task changes are kept. A store is an append-only log of changes: `append` must have made the change durable before it
9
+ * returns, and `load` returns every change in the order it was appended. The records are folded from the log, so a new backend only
10
+ * has to keep that promise; `store.test.ts` runs the same conformance suite against every backend.
11
+ */
12
+ /** One JSON object per line in a text file. Easy to read, copy and diff. */
13
+ function jsonlStore(file) {
14
+ return {
15
+ load() {
16
+ if (!existsSync(file)) return [];
17
+ const changes = [];
18
+ for (const line of readFileSync(file, "utf8").split("\n")) {
19
+ if (line.trim() === "") continue;
20
+ try {
21
+ changes.push(JSON.parse(line));
22
+ } catch {}
23
+ }
24
+ return changes;
25
+ },
26
+ append(change) {
27
+ mkdirSync(dirname(file), { recursive: true });
28
+ appendFileSync(file, `${JSON.stringify(change)}\n`);
29
+ },
30
+ close() {}
31
+ };
32
+ }
33
+ /**
34
+ * A SQLite file with one table, `task_changes(seq, id, change)`, appended to and never updated. Writes are synchronous with full
35
+ * durability (`synchronous = FULL`, write-ahead log), so a change is on disk before the call that made it returns. Uses Node's
36
+ * built-in `node:sqlite` (loaded only when this store is used, because Node marks it experimental and warns on load).
37
+ */
38
+ function sqliteStore(file) {
39
+ mkdirSync(dirname(file), { recursive: true });
40
+ const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
41
+ const db = new DatabaseSync(file);
42
+ db.exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;");
43
+ db.exec("CREATE TABLE IF NOT EXISTS task_changes (seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL, change TEXT NOT NULL)");
44
+ const insert = db.prepare("INSERT INTO task_changes (id, change) VALUES (?, ?)");
45
+ const select = db.prepare("SELECT change FROM task_changes ORDER BY seq");
46
+ return {
47
+ load: () => select.all().map((row) => JSON.parse(row.change)),
48
+ append: (change) => void insert.run(change.id, JSON.stringify(change)),
49
+ close: () => db.close()
50
+ };
51
+ }
52
+ function openStore(kind, directory) {
53
+ const file = `${directory}/tasks.${kind === "sqlite" ? "sqlite" : "jsonl"}`;
54
+ return {
55
+ store: kind === "sqlite" ? sqliteStore(file) : jsonlStore(file),
56
+ file
57
+ };
58
+ }
59
+ //#endregion
60
+ //#region index.ts
61
+ /**
62
+ * Durable task records (`ctx.tasks`).
63
+ *
64
+ * The idea comes from Pi Durable (see spec 013, "Ideas from Pi Durable"), kept to what Cordis does not already do: every piece of work
65
+ * gets a record with an id, an optional owner (parent), its input, status, result or error, and timestamps. Each change is appended to
66
+ * `<home>/tasks.jsonl` before the call that made it returns, so nothing is presented as done before it is recorded. At startup the log is
67
+ * folded back into records, and a task still `running` is marked `interrupted`: it is reported, never silently run again, because an
68
+ * external side effect may already have happened. Cancelling a task cancels the tasks it owns and aborts their signals.
69
+ */
70
+ const changeOf = (change) => change;
71
+ /** How many of the newest tasks the state cell holds. */
72
+ const STATE_LIMIT = 100;
73
+ const FINAL = /* @__PURE__ */ new Set([
74
+ "completed",
75
+ "failed",
76
+ "cancelled",
77
+ "interrupted"
78
+ ]);
79
+ const message = (error) => error instanceof Error ? error.message : String(error);
80
+ var Tasks = class extends Service {
81
+ file;
82
+ /** Tasks found running at startup and marked interrupted. */
83
+ interrupted;
84
+ records = /* @__PURE__ */ new Map();
85
+ controllers = /* @__PURE__ */ new Map();
86
+ store;
87
+ manifest;
88
+ constructor(ctx, config = {}) {
89
+ super(ctx, "tasks");
90
+ this.manifest = config.manifest;
91
+ const opened = openStore(config.store ?? "jsonl", ctx.appInstance.home);
92
+ this.file = opened.file;
93
+ this.store = opened.store;
94
+ ctx.effect(() => () => this.store.close(), "tasks: close the store");
95
+ this.load();
96
+ const interrupted = [];
97
+ for (const record of this.records.values()) if (record.status === "running") {
98
+ this.write({
99
+ id: record.id,
100
+ status: "interrupted",
101
+ error: "the app stopped while this task was running"
102
+ });
103
+ interrupted.push(record.id);
104
+ }
105
+ this.interrupted = interrupted;
106
+ ctx.effect(() => () => {
107
+ for (const id of [...this.controllers.keys()]) this.finish(id, {
108
+ status: "cancelled",
109
+ error: "the app stopped"
110
+ });
111
+ }, "tasks: cancel running work");
112
+ ctx.inject(["state"], (inner) => {
113
+ const cell = inner.state.cell("tasks", this.list().slice(0, STATE_LIMIT));
114
+ inner.on("tasks/changed", () => cell.set(this.list().slice(0, STATE_LIMIT)));
115
+ });
116
+ }
117
+ /** Start a task. The record is written before this returns. */
118
+ start(kind, input, options = {}) {
119
+ if (options.parent !== void 0 && !this.records.has(options.parent)) throw new Error(`tasks: no task "${options.parent}" to own this one`);
120
+ const id = randomUUID();
121
+ const now = (/* @__PURE__ */ new Date()).toISOString();
122
+ const controller = new AbortController();
123
+ if (options.parent !== void 0) {
124
+ if ((this.controllers.get(options.parent)?.signal)?.aborted) controller.abort();
125
+ }
126
+ this.controllers.set(id, controller);
127
+ this.write({
128
+ id,
129
+ kind,
130
+ ...options.parent === void 0 ? {} : { parent: options.parent },
131
+ ...this.manifest === void 0 ? {} : { manifest: this.manifest },
132
+ input,
133
+ status: "running",
134
+ createdAt: now,
135
+ updatedAt: now
136
+ });
137
+ return {
138
+ id,
139
+ signal: controller.signal,
140
+ progress: (detail) => {
141
+ if (!this.isRunning(id)) return;
142
+ this.write({
143
+ id,
144
+ detail
145
+ });
146
+ },
147
+ complete: (result, detail) => this.finish(id, {
148
+ status: "completed",
149
+ result,
150
+ ...detail === void 0 ? {} : { detail }
151
+ }),
152
+ fail: (error, detail) => this.finish(id, {
153
+ status: "failed",
154
+ error: message(error),
155
+ ...detail === void 0 ? {} : { detail }
156
+ })
157
+ };
158
+ }
159
+ get(id) {
160
+ return this.records.get(id);
161
+ }
162
+ /** Records, newest first. */
163
+ list(filter = {}) {
164
+ return [...this.records.values()].filter((record) => (filter.status === void 0 || record.status === filter.status) && (filter.parent === void 0 || record.parent === filter.parent) && (filter.kind === void 0 || record.kind === filter.kind)).sort((a, b) => a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0);
165
+ }
166
+ /** Cancel a running task and every running task it owns, children first. Returns the ids cancelled. */
167
+ cancel(id) {
168
+ const cancelled = [];
169
+ const visit = (taskId) => {
170
+ for (const child of this.list({ parent: taskId })) visit(child.id);
171
+ if (this.isRunning(taskId)) {
172
+ this.finish(taskId, {
173
+ status: "cancelled",
174
+ error: "cancelled"
175
+ });
176
+ cancelled.push(taskId);
177
+ }
178
+ };
179
+ if (!this.records.has(id)) throw new Error(`tasks: no task "${id}"`);
180
+ visit(id);
181
+ return cancelled;
182
+ }
183
+ isRunning(id) {
184
+ return this.records.get(id)?.status === "running";
185
+ }
186
+ finish(id, change) {
187
+ if (!this.isRunning(id)) return;
188
+ this.write({
189
+ id,
190
+ ...change
191
+ });
192
+ const controller = this.controllers.get(id);
193
+ this.controllers.delete(id);
194
+ controller?.abort();
195
+ }
196
+ /** Append one change and apply it. The line is on disk before the record changes in memory. */
197
+ write(change) {
198
+ const line = {
199
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
200
+ ...change
201
+ };
202
+ this.store.append(line);
203
+ const record = this.apply(line);
204
+ this.ctx.emit("tasks/changed", record);
205
+ }
206
+ apply(change) {
207
+ const current = this.records.get(change.id);
208
+ const next = {
209
+ ...current ?? {},
210
+ ...change
211
+ };
212
+ if (current && FINAL.has(current.status) && change.status !== void 0) return current;
213
+ this.records.set(change.id, next);
214
+ return next;
215
+ }
216
+ load() {
217
+ for (const change of this.store.load()) this.apply(changeOf(change));
218
+ }
219
+ };
220
+ /** The plugin: mount it after `instance`. */
221
+ const tasks = {
222
+ name: "tasks",
223
+ inject: ["appInstance"],
224
+ apply(ctx, config) {
225
+ new Tasks(ctx, config ?? {});
226
+ }
227
+ };
228
+ //#endregion
229
+ export { Tasks, tasks };
230
+
231
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../store.ts","../index.ts"],"sourcesContent":["/**\n * Where task changes are kept. A store is an append-only log of changes: `append` must have made the change durable before it\n * returns, and `load` returns every change in the order it was appended. The records are folded from the log, so a new backend only\n * has to keep that promise; `store.test.ts` runs the same conformance suite against every backend.\n */\n\nimport { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { dirname } from 'node:path'\n\n/** One change to a task record: its id and the fields that changed. Stores treat it as opaque JSON. */\nexport interface TaskChange {\n readonly id: string\n readonly [field: string]: unknown\n}\n\nexport interface TaskStore {\n /** Every change so far, oldest first. A change that was only partly written (a crash mid-append) is skipped. */\n load(): TaskChange[]\n /** Make one change durable. */\n append(change: TaskChange): void\n /** Release the file. */\n close(): void\n}\n\n/** One JSON object per line in a text file. Easy to read, copy and diff. */\nexport function jsonlStore(file: string): TaskStore {\n return {\n load() {\n if (!existsSync(file)) return []\n const changes: TaskChange[] = []\n for (const line of readFileSync(file, 'utf8').split('\\n')) {\n if (line.trim() === '') continue\n try {\n changes.push(JSON.parse(line) as TaskChange)\n } catch {\n // A torn last line (the app stopped mid-write) is skipped; every complete line before it still counts.\n }\n }\n return changes\n },\n append(change) {\n mkdirSync(dirname(file), { recursive: true })\n appendFileSync(file, `${JSON.stringify(change)}\\n`)\n },\n close() {},\n }\n}\n\n/** The pieces of `node:sqlite` used here. */\ninterface Database {\n exec(sql: string): void\n prepare(sql: string): { run(...values: unknown[]): unknown; all(): Array<{ change: string }> }\n close(): void\n}\n\n/**\n * A SQLite file with one table, `task_changes(seq, id, change)`, appended to and never updated. Writes are synchronous with full\n * durability (`synchronous = FULL`, write-ahead log), so a change is on disk before the call that made it returns. Uses Node's\n * built-in `node:sqlite` (loaded only when this store is used, because Node marks it experimental and warns on load).\n */\nexport function sqliteStore(file: string): TaskStore {\n mkdirSync(dirname(file), { recursive: true })\n const { DatabaseSync } = createRequire(import.meta.url)('node:sqlite') as {\n DatabaseSync: new (path: string) => Database\n }\n const db = new DatabaseSync(file)\n db.exec('PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;')\n db.exec(\n 'CREATE TABLE IF NOT EXISTS task_changes (seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL, change TEXT NOT NULL)',\n )\n const insert = db.prepare('INSERT INTO task_changes (id, change) VALUES (?, ?)')\n const select = db.prepare('SELECT change FROM task_changes ORDER BY seq')\n return {\n load: () => select.all().map((row) => JSON.parse(row.change) as TaskChange),\n append: (change) => void insert.run(change.id, JSON.stringify(change)),\n close: () => db.close(),\n }\n}\n\nexport type StoreKind = 'jsonl' | 'sqlite'\n\nexport function openStore(kind: StoreKind, directory: string): { store: TaskStore; file: string } {\n const file = `${directory}/tasks.${kind === 'sqlite' ? 'sqlite' : 'jsonl'}`\n return { store: kind === 'sqlite' ? sqliteStore(file) : jsonlStore(file), file }\n}\n","/**\n * Durable task records (`ctx.tasks`).\n *\n * The idea comes from Pi Durable (see spec 013, \"Ideas from Pi Durable\"), kept to what Cordis does not already do: every piece of work\n * gets a record with an id, an optional owner (parent), its input, status, result or error, and timestamps. Each change is appended to\n * `<home>/tasks.jsonl` before the call that made it returns, so nothing is presented as done before it is recorded. At startup the log is\n * folded back into records, and a task still `running` is marked `interrupted`: it is reported, never silently run again, because an\n * external side effect may already have happened. Cancelling a task cancels the tasks it owns and aborts their signals.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type {} from '@acryldev/instance'\nimport { type Context, Service } from '@deepseek-ai/cordis'\nimport { openStore, type StoreKind, type TaskChange, type TaskStore } from './store.ts'\n\nexport interface TasksConfig {\n /** Recorded on every task: the digest of the manifest the app was composed from. */\n manifest?: string\n /** Where changes are kept: a JSON lines file (default) or a SQLite file. */\n store?: StoreKind\n}\n\nexport type TaskStatus = 'running' | 'completed' | 'failed' | 'cancelled' | 'interrupted'\n\nexport interface TaskRecord {\n readonly id: string\n readonly kind: string\n readonly parent?: string\n /** The digest of the manifest the app was composed from, so a task traces to the configuration that ran it. */\n readonly manifest?: string\n readonly input: unknown\n readonly status: TaskStatus\n readonly result?: unknown\n readonly error?: string\n /** Free-form progress the owner attached (for example a tool-call trace). */\n readonly detail?: unknown\n readonly createdAt: string\n readonly updatedAt: string\n}\n\n/** What the owner of a running task holds. */\nexport interface TaskHandle {\n readonly id: string\n /** Aborted when the task, or a task that owns it, is cancelled. */\n readonly signal: AbortSignal\n /** Record progress without changing the status. */\n progress(detail: unknown): void\n complete(result: unknown, detail?: unknown): void\n fail(error: unknown, detail?: unknown): void\n}\n\nexport interface TaskFilter {\n readonly status?: TaskStatus\n readonly parent?: string\n readonly kind?: string\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n tasks: Tasks\n }\n\n interface Events {\n /** A task record changed (after the change was written). */\n 'tasks/changed'(record: TaskRecord): void\n }\n}\n\ntype Change = Partial<TaskRecord> & { readonly id: string }\nconst changeOf = (change: TaskChange) => change as unknown as Change\n\n/** The slice of the state service the tasks plugin uses, by name, so it imports nothing from @acryldev/state. */\ninterface StateService {\n cell<T>(key: string, initial: T): { set(value: T): void }\n}\n\n/** How many of the newest tasks the state cell holds. */\nconst STATE_LIMIT = 100\n\nconst FINAL: ReadonlySet<TaskStatus> = new Set(['completed', 'failed', 'cancelled', 'interrupted'])\nconst message = (error: unknown) => (error instanceof Error ? error.message : String(error))\n\nexport class Tasks extends Service {\n readonly file: string\n /** Tasks found running at startup and marked interrupted. */\n readonly interrupted: readonly string[]\n private readonly records = new Map<string, TaskRecord>()\n private readonly controllers = new Map<string, AbortController>()\n\n private readonly store: TaskStore\n private readonly manifest: string | undefined\n\n constructor(ctx: Context, config: TasksConfig = {}) {\n super(ctx, 'tasks')\n this.manifest = config.manifest\n const opened = openStore(config.store ?? 'jsonl', ctx.appInstance.home)\n this.file = opened.file\n this.store = opened.store\n // Disposers run newest first, so this one runs last: the store closes after pending work has been recorded.\n ctx.effect(() => () => this.store.close(), 'tasks: close the store')\n this.load()\n const interrupted: string[] = []\n for (const record of this.records.values()) {\n if (record.status === 'running') {\n this.write({\n id: record.id,\n status: 'interrupted',\n error: 'the app stopped while this task was running',\n })\n interrupted.push(record.id)\n }\n }\n this.interrupted = interrupted\n // Work still running when the app stops is cancelled, so its owner's signal fires and the record says what happened.\n ctx.effect(\n () => () => {\n for (const id of [...this.controllers.keys()])\n this.finish(id, { status: 'cancelled', error: 'the app stopped' })\n },\n 'tasks: cancel running work',\n )\n // With the state service mounted, the latest tasks are also a cell: any surface reads them as JSON or streams their changes (`/api/state/tasks`).\n ctx.inject(['state'], (inner) => {\n const state = (inner as unknown as { state: StateService }).state\n const cell = state.cell('tasks', this.list().slice(0, STATE_LIMIT))\n inner.on('tasks/changed', () => cell.set(this.list().slice(0, STATE_LIMIT)))\n })\n }\n\n /** Start a task. The record is written before this returns. */\n start(kind: string, input: unknown, options: { parent?: string } = {}): TaskHandle {\n if (options.parent !== undefined && !this.records.has(options.parent))\n throw new Error(`tasks: no task \"${options.parent}\" to own this one`)\n const id = randomUUID()\n const now = new Date().toISOString()\n const controller = new AbortController()\n if (options.parent !== undefined) {\n const parentSignal = this.controllers.get(options.parent)?.signal\n if (parentSignal?.aborted) controller.abort()\n }\n this.controllers.set(id, controller)\n this.write({\n id,\n kind,\n ...(options.parent === undefined ? {} : { parent: options.parent }),\n ...(this.manifest === undefined ? {} : { manifest: this.manifest }),\n input,\n status: 'running',\n createdAt: now,\n updatedAt: now,\n })\n return {\n id,\n signal: controller.signal,\n progress: (detail) => {\n if (!this.isRunning(id)) return\n this.write({ id, detail })\n },\n complete: (result, detail) =>\n this.finish(id, {\n status: 'completed',\n result,\n ...(detail === undefined ? {} : { detail }),\n }),\n fail: (error, detail) =>\n this.finish(id, {\n status: 'failed',\n error: message(error),\n ...(detail === undefined ? {} : { detail }),\n }),\n }\n }\n\n get(id: string): TaskRecord | undefined {\n return this.records.get(id)\n }\n\n /** Records, newest first. */\n list(filter: TaskFilter = {}): TaskRecord[] {\n return [...this.records.values()]\n .filter(\n (record) =>\n (filter.status === undefined || record.status === filter.status) &&\n (filter.parent === undefined || record.parent === filter.parent) &&\n (filter.kind === undefined || record.kind === filter.kind),\n )\n .sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0))\n }\n\n /** Cancel a running task and every running task it owns, children first. Returns the ids cancelled. */\n cancel(id: string): string[] {\n const cancelled: string[] = []\n const visit = (taskId: string) => {\n for (const child of this.list({ parent: taskId })) visit(child.id)\n if (this.isRunning(taskId)) {\n this.finish(taskId, { status: 'cancelled', error: 'cancelled' })\n cancelled.push(taskId)\n }\n }\n if (!this.records.has(id)) throw new Error(`tasks: no task \"${id}\"`)\n visit(id)\n return cancelled\n }\n\n private isRunning(id: string): boolean {\n return this.records.get(id)?.status === 'running'\n }\n\n private finish(id: string, change: Omit<Change, 'id'>): void {\n if (!this.isRunning(id)) return\n this.write({ id, ...change })\n const controller = this.controllers.get(id)\n this.controllers.delete(id)\n controller?.abort()\n }\n\n /** Append one change and apply it. The line is on disk before the record changes in memory. */\n private write(change: Change): void {\n const now = new Date().toISOString()\n const line = { updatedAt: now, ...change }\n this.store.append(line)\n const record = this.apply(line)\n this.ctx.emit('tasks/changed', record)\n }\n\n private apply(change: Change): TaskRecord {\n const current = this.records.get(change.id)\n const next = { ...(current ?? {}), ...change } as TaskRecord\n if (current && FINAL.has(current.status) && change.status !== undefined) return current\n this.records.set(change.id, next)\n return next\n }\n\n private load(): void {\n for (const change of this.store.load()) this.apply(changeOf(change))\n }\n}\n\n/** The plugin: mount it after `instance`. */\nexport const tasks = {\n name: 'tasks',\n inject: ['appInstance'],\n apply(ctx: Context, config?: TasksConfig) {\n new Tasks(ct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M,OAAO;GAAE,GAAI,WAAW,CAAC;GAAI,GAAG;EAAO;EAC7C,IAAI,WAAW,MAAM,IAAI,QAAQ,MAAM,KAAK,OAAO,WAAW,KAAA,GAAW,OAAO;EAChF,KAAK,QAAQ,IAAI,OAAO,IAAI,IAAI;EAChC,OAAO;CACT;CAEA,OAAqB;EACnB,KAAK,MAAM,UAAU,KAAK,MAAM,KAAK,GAAG,KAAK,MAAM,SAAS,MAAM,CAAC;CACrE;AACF;;AAGA,MAAa,QAAQ;CACnB,MAAM;CACN,QAAQ,CAAC,aAAa;CACtB,MAAM,KAAc,QAAsB;EACxC,IAAI,MAAM,KAAK,UAAU,CAAC,CAAC;CAC7B;AACF"}
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Durable task records (`ctx.tasks`).
3
+ *
4
+ * The idea comes from Pi Durable (see spec 013, "Ideas from Pi Durable"), kept to what Cordis does not already do: every piece of work
5
+ * gets a record with an id, an optional owner (parent), its input, status, result or error, and timestamps. Each change is appended to
6
+ * `<home>/tasks.jsonl` before the call that made it returns, so nothing is presented as done before it is recorded. At startup the log is
7
+ * folded back into records, and a task still `running` is marked `interrupted`: it is reported, never silently run again, because an
8
+ * external side effect may already have happened. Cancelling a task cancels the tasks it owns and aborts their signals.
9
+ */
10
+ import { type Context, Service } from '@deepseek-ai/cordis';
11
+ import { type StoreKind } from './store.ts';
12
+ export interface TasksConfig {
13
+ /** Recorded on every task: the digest of the manifest the app was composed from. */
14
+ manifest?: string;
15
+ /** Where changes are kept: a JSON lines file (default) or a SQLite file. */
16
+ store?: StoreKind;
17
+ }
18
+ export type TaskStatus = 'running' | 'completed' | 'failed' | 'cancelled' | 'interrupted';
19
+ export interface TaskRecord {
20
+ readonly id: string;
21
+ readonly kind: string;
22
+ readonly parent?: string;
23
+ /** The digest of the manifest the app was composed from, so a task traces to the configuration that ran it. */
24
+ readonly manifest?: string;
25
+ readonly input: unknown;
26
+ readonly status: TaskStatus;
27
+ readonly result?: unknown;
28
+ readonly error?: string;
29
+ /** Free-form progress the owner attached (for example a tool-call trace). */
30
+ readonly detail?: unknown;
31
+ readonly createdAt: string;
32
+ readonly updatedAt: string;
33
+ }
34
+ /** What the owner of a running task holds. */
35
+ export interface TaskHandle {
36
+ readonly id: string;
37
+ /** Aborted when the task, or a task that owns it, is cancelled. */
38
+ readonly signal: AbortSignal;
39
+ /** Record progress without changing the status. */
40
+ progress(detail: unknown): void;
41
+ complete(result: unknown, detail?: unknown): void;
42
+ fail(error: unknown, detail?: unknown): void;
43
+ }
44
+ export interface TaskFilter {
45
+ readonly status?: TaskStatus;
46
+ readonly parent?: string;
47
+ readonly kind?: string;
48
+ }
49
+ declare module '@deepseek-ai/cordis' {
50
+ interface Context {
51
+ tasks: Tasks;
52
+ }
53
+ interface Events {
54
+ /** A task record changed (after the change was written). */
55
+ 'tasks/changed'(record: TaskRecord): void;
56
+ }
57
+ }
58
+ export declare class Tasks extends Service {
59
+ readonly file: string;
60
+ /** Tasks found running at startup and marked interrupted. */
61
+ readonly interrupted: readonly string[];
62
+ private readonly records;
63
+ private readonly controllers;
64
+ private readonly store;
65
+ private readonly manifest;
66
+ constructor(ctx: Context, config?: TasksConfig);
67
+ /** Start a task. The record is written before this returns. */
68
+ start(kind: string, input: unknown, options?: {
69
+ parent?: string;
70
+ }): TaskHandle;
71
+ get(id: string): TaskRecord | undefined;
72
+ /** Records, newest first. */
73
+ list(filter?: TaskFilter): TaskRecord[];
74
+ /** Cancel a running task and every running task it owns, children first. Returns the ids cancelled. */
75
+ cancel(id: string): string[];
76
+ private isRunning;
77
+ private finish;
78
+ /** Append one change and apply it. The line is on disk before the record changes in memory. */
79
+ private write;
80
+ private apply;
81
+ private load;
82
+ }
83
+ /** The plugin: mount it after `instance`. */
84
+ export declare const tasks: {
85
+ name: string;
86
+ inject: string[];
87
+ apply(ctx: Context, config?: TasksConfig): void;
88
+ };
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Where task changes are kept. A store is an append-only log of changes: `append` must have made the change durable before it
3
+ * returns, and `load` returns every change in the order it was appended. The records are folded from the log, so a new backend only
4
+ * has to keep that promise; `store.test.ts` runs the same conformance suite against every backend.
5
+ */
6
+ /** One change to a task record: its id and the fields that changed. Stores treat it as opaque JSON. */
7
+ export interface TaskChange {
8
+ readonly id: string;
9
+ readonly [field: string]: unknown;
10
+ }
11
+ export interface TaskStore {
12
+ /** Every change so far, oldest first. A change that was only partly written (a crash mid-append) is skipped. */
13
+ load(): TaskChange[];
14
+ /** Make one change durable. */
15
+ append(change: TaskChange): void;
16
+ /** Release the file. */
17
+ close(): void;
18
+ }
19
+ /** One JSON object per line in a text file. Easy to read, copy and diff. */
20
+ export declare function jsonlStore(file: string): TaskStore;
21
+ /**
22
+ * A SQLite file with one table, `task_changes(seq, id, change)`, appended to and never updated. Writes are synchronous with full
23
+ * durability (`synchronous = FULL`, write-ahead log), so a change is on disk before the call that made it returns. Uses Node's
24
+ * built-in `node:sqlite` (loaded only when this store is used, because Node marks it experimental and warns on load).
25
+ */
26
+ export declare function sqliteStore(file: string): TaskStore;
27
+ export type StoreKind = 'jsonl' | 'sqlite';
28
+ export declare function openStore(kind: StoreKind, directory: string): {
29
+ store: TaskStore;
30
+ file: string;
31
+ };
@@ -0,0 +1,2 @@
1
+ declare const _default: import("tsdown").UserConfig;
2
+ export default _default;
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@acryldev/tasks",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Durable task records: id, owner, input, status, result, trace; appended to a log in the app's home and readable after a restart.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/acryldev/acryl.git",
9
+ "directory": "plugins/tasks"
10
+ },
11
+ "homepage": "https://github.com/acryldev/acryl/tree/main/plugins/tasks#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/acryldev/acryl/issues"
14
+ },
15
+ "type": "module",
16
+ "engines": {
17
+ "node": "^22.19.0 || >=24.0.0"
18
+ },
19
+ "main": "./lib/index.js",
20
+ "types": "./lib/types/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./lib/types/index.d.ts",
24
+ "default": "./lib/index.js"
25
+ },
26
+ "./package.json": "./package.json"
27
+ },
28
+ "dependencies": {
29
+ "@acryldev/instance": "0.1.2"
30
+ },
31
+ "peerDependencies": {
32
+ "@deepseek-ai/cordis": "^4.0.2"
33
+ },
34
+ "devDependencies": {
35
+ "@deepseek-ai/cordis": "4.0.4",
36
+ "@types/node": "^22.20.0",
37
+ "@acryldev/router": "0.1.0",
38
+ "@acryldev/state": "0.1.0",
39
+ "tsdown": "0.22.2",
40
+ "typescript": "6.0.3"
41
+ },
42
+ "scripts": {
43
+ "build": "tsdown && tsc -p tsconfig.json --emitDeclarationOnly"
44
+ }
6
45
  }
package/plugin.json ADDED
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "tasks",
3
+ "description": "Durable task records: id, owner, input, status, result, trace; appended to a log in the app's home and readable after a restart.",
4
+ "requires": ["instance"],
5
+ "inject": ["appInstance"],
6
+ "provides": ["tasks"],
7
+ "dependencies": {
8
+ "@deepseek-ai/cordis": "4.0.4"
9
+ },
10
+ "mount": "mount it after instance: root.plugin(tasks, {}); the agent records every run as a task when it is present",
11
+ "entries": {
12
+ "": "index.ts"
13
+ }
14
+ }
package/store.ts ADDED
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Where task changes are kept. A store is an append-only log of changes: `append` must have made the change durable before it
3
+ * returns, and `load` returns every change in the order it was appended. The records are folded from the log, so a new backend only
4
+ * has to keep that promise; `store.test.ts` runs the same conformance suite against every backend.
5
+ */
6
+
7
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
8
+ import { createRequire } from 'node:module'
9
+ import { dirname } from 'node:path'
10
+
11
+ /** One change to a task record: its id and the fields that changed. Stores treat it as opaque JSON. */
12
+ export interface TaskChange {
13
+ readonly id: string
14
+ readonly [field: string]: unknown
15
+ }
16
+
17
+ export interface TaskStore {
18
+ /** Every change so far, oldest first. A change that was only partly written (a crash mid-append) is skipped. */
19
+ load(): TaskChange[]
20
+ /** Make one change durable. */
21
+ append(change: TaskChange): void
22
+ /** Release the file. */
23
+ close(): void
24
+ }
25
+
26
+ /** One JSON object per line in a text file. Easy to read, copy and diff. */
27
+ export function jsonlStore(file: string): TaskStore {
28
+ return {
29
+ load() {
30
+ if (!existsSync(file)) return []
31
+ const changes: TaskChange[] = []
32
+ for (const line of readFileSync(file, 'utf8').split('\n')) {
33
+ if (line.trim() === '') continue
34
+ try {
35
+ changes.push(JSON.parse(line) as TaskChange)
36
+ } catch {
37
+ // A torn last line (the app stopped mid-write) is skipped; every complete line before it still counts.
38
+ }
39
+ }
40
+ return changes
41
+ },
42
+ append(change) {
43
+ mkdirSync(dirname(file), { recursive: true })
44
+ appendFileSync(file, `${JSON.stringify(change)}\n`)
45
+ },
46
+ close() {},
47
+ }
48
+ }
49
+
50
+ /** The pieces of `node:sqlite` used here. */
51
+ interface Database {
52
+ exec(sql: string): void
53
+ prepare(sql: string): { run(...values: unknown[]): unknown; all(): Array<{ change: string }> }
54
+ close(): void
55
+ }
56
+
57
+ /**
58
+ * A SQLite file with one table, `task_changes(seq, id, change)`, appended to and never updated. Writes are synchronous with full
59
+ * durability (`synchronous = FULL`, write-ahead log), so a change is on disk before the call that made it returns. Uses Node's
60
+ * built-in `node:sqlite` (loaded only when this store is used, because Node marks it experimental and warns on load).
61
+ */
62
+ export function sqliteStore(file: string): TaskStore {
63
+ mkdirSync(dirname(file), { recursive: true })
64
+ const { DatabaseSync } = createRequire(import.meta.url)('node:sqlite') as {
65
+ DatabaseSync: new (path: string) => Database
66
+ }
67
+ const db = new DatabaseSync(file)
68
+ db.exec('PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;')
69
+ db.exec(
70
+ 'CREATE TABLE IF NOT EXISTS task_changes (seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL, change TEXT NOT NULL)',
71
+ )
72
+ const insert = db.prepare('INSERT INTO task_changes (id, change) VALUES (?, ?)')
73
+ const select = db.prepare('SELECT change FROM task_changes ORDER BY seq')
74
+ return {
75
+ load: () => select.all().map((row) => JSON.parse(row.change) as TaskChange),
76
+ append: (change) => void insert.run(change.id, JSON.stringify(change)),
77
+ close: () => db.close(),
78
+ }
79
+ }
80
+
81
+ export type StoreKind = 'jsonl' | 'sqlite'
82
+
83
+ export function openStore(kind: StoreKind, directory: string): { store: TaskStore; file: string } {
84
+ const file = `${directory}/tasks.${kind === 'sqlite' ? 'sqlite' : 'jsonl'}`
85
+ return { store: kind === 'sqlite' ? sqliteStore(file) : jsonlStore(file), file }
86
+ }
@@ -0,0 +1,82 @@
1
+ import assert from 'node:assert/strict'
2
+ import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import { afterEach, describe, test } from 'node:test'
6
+ import { jsonlStore, openStore, type StoreKind, sqliteStore, type TaskStore } from '../store.ts'
7
+
8
+ const dirs: string[] = []
9
+ afterEach(() => {
10
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
11
+ })
12
+ const directory = () => {
13
+ const dir = mkdtempSync(join(tmpdir(), 'store-test-'))
14
+ dirs.push(dir)
15
+ return dir
16
+ }
17
+
18
+ /** The promise every backend keeps, run against each one. */
19
+ for (const kind of ['jsonl', 'sqlite'] as StoreKind[]) {
20
+ describe(`task store conformance: ${kind}`, () => {
21
+ const open = (dir: string): TaskStore => openStore(kind, dir).store
22
+
23
+ test('an empty store loads nothing', () => {
24
+ const store = open(directory())
25
+ assert.deepEqual(store.load(), [])
26
+ store.close()
27
+ })
28
+
29
+ test('changes come back in the order they were appended, with their fields intact', () => {
30
+ const store = open(directory())
31
+ const changes = [
32
+ { id: 'b', status: 'running', input: { text: 'line one\nline two "quoted" \u00e9\u4e2d' } },
33
+ { id: 'a', status: 'running', detail: [1, { nested: true }, null] },
34
+ { id: 'b', status: 'completed', result: 0 },
35
+ ]
36
+ for (const change of changes) store.append(change)
37
+ assert.deepEqual(store.load(), changes)
38
+ store.close()
39
+ })
40
+
41
+ test('a change is durable before append returns: a second reader sees it, and so does a reopened store', () => {
42
+ const dir = directory()
43
+ const writer = open(dir)
44
+ writer.append({ id: 'x', status: 'running' })
45
+ assert.deepEqual(open(dir).load(), [{ id: 'x', status: 'running' }])
46
+ writer.close()
47
+ const reopened = open(dir)
48
+ reopened.append({ id: 'x', status: 'completed' })
49
+ assert.equal(reopened.load().length, 2)
50
+ reopened.close()
51
+ })
52
+
53
+ test('a thousand changes keep their order', () => {
54
+ const store = open(directory())
55
+ for (let index = 0; index < 1000; index++) store.append({ id: `t${index}`, n: index })
56
+ const loaded = store.load()
57
+ assert.equal(loaded.length, 1000)
58
+ assert.deepEqual(
59
+ loaded.map((change) => change.n),
60
+ Array.from({ length: 1000 }, (_, index) => index),
61
+ )
62
+ store.close()
63
+ })
64
+ })
65
+ }
66
+
67
+ test('jsonl: a torn last line is skipped and every complete line before it still counts', () => {
68
+ const dir = directory()
69
+ const file = join(dir, 'tasks.jsonl')
70
+ writeFileSync(file, '{"id":"a","status":"running"}\n')
71
+ appendFileSync(file, '{"id":"b","stat')
72
+ assert.deepEqual(jsonlStore(file).load(), [{ id: 'a', status: 'running' }])
73
+ })
74
+
75
+ test('sqlite: the log is append-only in one table', () => {
76
+ const dir = directory()
77
+ const store = sqliteStore(join(dir, 'tasks.sqlite'))
78
+ store.append({ id: 'a' })
79
+ store.append({ id: 'a', status: 'done' })
80
+ assert.equal(store.load().length, 2)
81
+ store.close()
82
+ })
@@ -0,0 +1,3 @@
1
+ // The same tests, against the SQLite store: the backend must not change what the tasks plugin does.
2
+ process.env.TASKS_TEST_STORE = 'sqlite'
3
+ await import('./tasks.test.ts')
@@ -0,0 +1,152 @@
1
+ import assert from 'node:assert/strict'
2
+ import { appendFileSync, mkdtempSync, rmSync } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import { afterEach, test } from 'node:test'
6
+ import { instance, pinnedInstance } from '@acryldev/instance'
7
+ import * as router from '@acryldev/router'
8
+ import * as state from '@acryldev/state'
9
+ import { Context } from '@deepseek-ai/cordis'
10
+ import { tasks } from '../index.ts'
11
+ import { openStore, type StoreKind } from '../store.ts'
12
+
13
+ /** Which backend this run uses: tasks.sqlite.test.ts runs this whole file again against SQLite. */
14
+ const KIND = (process.env.TASKS_TEST_STORE ?? 'jsonl') as StoreKind
15
+
16
+ const cleanup: Array<() => Promise<void> | void> = []
17
+ afterEach(async () => {
18
+ for (const step of cleanup.splice(0)) await step()
19
+ })
20
+
21
+ async function boot(home = mkdtempSync(join(tmpdir(), 'tasks-test-'))) {
22
+ const root = new Context()
23
+ const fibers = [root.plugin(instance, pinnedInstance(home)), root.plugin(tasks, { store: KIND })]
24
+ for (const fiber of fibers) await fiber.await()
25
+ const stop = async () => {
26
+ for (const fiber of [...fibers].reverse()) await fiber.dispose()
27
+ }
28
+ return { root, home, stop }
29
+ }
30
+
31
+ test('a task is recorded before start returns, and its result before complete returns', async () => {
32
+ const { root, home, stop } = await boot()
33
+ cleanup.push(stop, () => rmSync(home, { recursive: true, force: true }))
34
+ const task = root.tasks.start('build', { what: 'hello' })
35
+ // On disk before start returns: a second reader of the same store already sees it.
36
+ assert.ok(
37
+ openStore(KIND, home)
38
+ .store.load()
39
+ .some((change) => change.id === task.id),
40
+ )
41
+ task.complete({ ok: true }, { steps: 2 })
42
+ const record = root.tasks.get(task.id)
43
+ assert.deepEqual(
44
+ [record?.status, record?.result, record?.detail],
45
+ ['completed', { ok: true }, { steps: 2 }],
46
+ )
47
+ task.fail('too late')
48
+ assert.equal(root.tasks.get(task.id)?.status, 'completed')
49
+ })
50
+
51
+ test('cancelling a task cancels what it owns and aborts their signals', async () => {
52
+ const { root, home, stop } = await boot()
53
+ cleanup.push(stop, () => rmSync(home, { recursive: true, force: true }))
54
+ const parent = root.tasks.start('run', {})
55
+ const child = root.tasks.start('tool', {}, { parent: parent.id })
56
+ assert.deepEqual(root.tasks.cancel(parent.id).sort(), [child.id, parent.id].sort())
57
+ assert.equal(child.signal.aborted, true)
58
+ assert.deepEqual(
59
+ root.tasks.list({ parent: parent.id }).map((record) => record.status),
60
+ ['cancelled'],
61
+ )
62
+ assert.throws(() => root.tasks.start('tool', {}, { parent: 'nobody' }), /no task/)
63
+ })
64
+
65
+ test('after a restart, records are back and work that was running is marked interrupted, not run again', async () => {
66
+ const home = mkdtempSync(join(tmpdir(), 'tasks-test-'))
67
+ cleanup.push(() => rmSync(home, { recursive: true, force: true }))
68
+ const first = await boot(home)
69
+ const done = first.root.tasks.start('build', {})
70
+ done.complete('ok')
71
+ first.root.tasks.start('deploy', {})
72
+ // Simulate a crash: the process ends without disposing, and the last line is torn.
73
+ if (KIND === 'jsonl') appendFileSync(join(home, 'tasks.jsonl'), '{"id":"torn"')
74
+ const second = await boot(home)
75
+ cleanup.push(second.stop)
76
+ assert.equal(second.root.tasks.get(done.id)?.status, 'completed')
77
+ assert.deepEqual(
78
+ second.root.tasks.list({ status: 'interrupted' }).map((record) => record.kind),
79
+ ['deploy'],
80
+ )
81
+ assert.equal(second.root.tasks.interrupted.length, 1)
82
+ await first.stop()
83
+ })
84
+
85
+ test('stopping the app cancels running work and says so', async () => {
86
+ const { root, home, stop } = await boot()
87
+ cleanup.push(() => rmSync(home, { recursive: true, force: true }))
88
+ const service = root.tasks
89
+ const task = service.start('long', {})
90
+ await stop()
91
+ assert.equal(task.signal.aborted, true)
92
+ assert.deepEqual(
93
+ [service.get(task.id)?.status, service.get(task.id)?.error],
94
+ ['cancelled', 'the app stopped'],
95
+ )
96
+ })
97
+
98
+ test('every task carries the digest of the manifest the app was composed from', async () => {
99
+ const home = mkdtempSync(join(tmpdir(), 'tasks-test-'))
100
+ cleanup.push(() => rmSync(home, { recursive: true, force: true }))
101
+ const root = new Context()
102
+ const fibers = [
103
+ root.plugin(instance, pinnedInstance(home)),
104
+ root.plugin(tasks, { manifest: 'sha256:abc', store: KIND }),
105
+ ]
106
+ for (const fiber of fibers) await fiber.await()
107
+ const task = root.tasks.start('build', {})
108
+ assert.equal(root.tasks.get(task.id)?.manifest, 'sha256:abc')
109
+ assert.ok(
110
+ openStore(KIND, home)
111
+ .store.load()
112
+ .some((change) => change.manifest === 'sha256:abc'),
113
+ )
114
+ task.complete('ok')
115
+ for (const fiber of [...fibers].reverse()) await fiber.dispose()
116
+ })
117
+
118
+ test('with the state service mounted, the latest tasks are a cell that follows every change and is readable on the router', async () => {
119
+ const home = mkdtempSync(join(tmpdir(), 'tasks-test-'))
120
+ const root = new Context()
121
+ const fibers = [
122
+ root.plugin(instance, pinnedInstance(home)),
123
+ root.plugin(router),
124
+ root.plugin(state),
125
+ root.plugin(tasks, { store: KIND }),
126
+ ]
127
+ for (const fiber of fibers) await fiber.await()
128
+ cleanup.push(async () => {
129
+ for (const fiber of [...fibers].reverse()) await fiber.dispose()
130
+ rmSync(home, { recursive: true, force: true })
131
+ })
132
+ const cell = root.state.find<Array<{ id: string; status: string }>>('tasks')
133
+ assert.ok(cell, 'the tasks cell exists')
134
+ assert.deepEqual(cell.get(), [])
135
+
136
+ const handle = root.tasks.start('demo', { n: 1 })
137
+ assert.deepEqual(
138
+ cell.get().map((record) => record.status),
139
+ ['running'],
140
+ )
141
+ handle.complete({ done: true })
142
+ assert.deepEqual(
143
+ cell.get().map((record) => record.status),
144
+ ['completed'],
145
+ )
146
+
147
+ const reply = await root.router.request('/api/state/tasks')
148
+ assert.equal(reply.status, 200)
149
+ const body = (await reply.json()) as { key: string; value: Array<{ kind: string }> }
150
+ assert.equal(body.key, 'tasks')
151
+ assert.equal(body.value[0]?.kind, 'demo')
152
+ })
package/tsconfig.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2024",
4
+ "lib": ["ES2024", "DOM", "DOM.Iterable"],
5
+ "module": "NodeNext",
6
+ "moduleResolution": "NodeNext",
7
+ "allowImportingTsExtensions": true,
8
+ "erasableSyntaxOnly": true,
9
+ "rootDir": ".",
10
+ "outDir": "lib",
11
+ "declaration": true,
12
+ "declarationDir": "lib/types",
13
+ "esModuleInterop": true,
14
+ "strict": true,
15
+ "noImplicitOverride": true,
16
+ "verbatimModuleSyntax": true,
17
+ "skipLibCheck": true,
18
+ "types": ["node"]
19
+ },
20
+ "include": ["*.ts"]
21
+ }
@@ -0,0 +1,23 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { defineConfig } from 'tsdown'
3
+
4
+ /** The package's importable files, exactly as `plugin.json`'s `entries` names them (the copy path uses the same table). */
5
+ const { entries } = JSON.parse(readFileSync(new URL('./plugin.json', import.meta.url), 'utf8')) as {
6
+ entries: Record<string, string>
7
+ }
8
+ const entry = Object.fromEntries(
9
+ Object.entries(entries).map(([, file]) => [file.replace(/.ts$/, ''), file]),
10
+ )
11
+
12
+ export default defineConfig({
13
+ name: '@acryldev/tasks',
14
+ entry,
15
+ outDir: 'lib',
16
+ format: 'esm',
17
+ platform: 'node',
18
+ target: 'es2024',
19
+ fixedExtension: false,
20
+ dts: false,
21
+ clean: true,
22
+ sourcemap: true,
23
+ })