dsh-taskflow 0.1.2 → 0.1.3

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.
@@ -1,114 +1,123 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { children, ownerOf } from '../domain/task-service.mjs';
3
-
4
- export const RESULT_SCHEMA = { type: 'object', additionalProperties: false, required: ['status', 'summary'], properties: {
5
- status: { type: 'string', enum: ['completed', 'blocked', 'failed'] },
6
- summary: { type: 'string' },
7
- } };
8
-
9
- /** One scheduler for the whole tree. Waiting ancestors relinquish their slots. */
10
- export class TaskRuntime {
11
- constructor(service, host) {
12
- this.service = service; this.host = host; this.runs = new Map(); this.waiters = new Map(); this.stopped = false; this.pumping = false;
13
- this.unsubscribe = service.subscribe(() => this.kick());
14
- }
15
- kick() { if (this.stopped || this.scheduled) return; this.scheduled = true; queueMicrotask(() => { this.scheduled = false; this.pump().catch(error => this.host.log?.(error)); }); }
16
- slots() { return [...this.runs.values()].filter(run => run.holdsSlot).length; }
17
- async pump() {
18
- if (this.stopped) return; if (this.pumping) { this.rerun = true; return; } this.pumping = true;
19
- try {
20
- let state = this.service.store.read();
21
- for (const [key, run] of this.runs) {
22
- const task = state.plans[run.planId]?.tasks[run.taskId];
23
- if (!task || task.attempt?.id !== run.attemptId || task.status === 'cancelled') { run.controller.abort(); continue; }
24
- if (task.status === 'awaiting_children') run.holdsSlot = false;
25
- }
26
- await this.deliver();
27
- for (const [key, wait] of this.waiters) {
28
- const p = state.plans[wait.planId], t = p?.tasks[wait.taskId];
29
- if (!t || t.attempt?.id !== wait.attemptId) { this.waiters.delete(key); wait.reject(new Error('等待任务的执行版本已失效')); continue; }
30
- // Return pending inline work to its responsible model; waiting for it
31
- // inside that same model call would deadlock the conversation.
32
- const pending = children(p, t.id).filter(c => ['running', 'queued', 'awaiting_children'].includes(c.status) && !(c.mode === 'inline' && c.executionSessionId === wait.sessionId));
33
- if (!pending.length && this.slots() < this.service.options.maxConcurrent) {
34
- const run = this.runs.get(key); if (run) run.holdsSlot = true;
35
- this.waiters.delete(key); await this.service.resumeWaiting(p.id, t.id); wait.resolve(children(p, t.id).map(c => ({ id: c.id, status: c.status, report: c.report })));
36
- }
37
- }
38
- state = this.service.store.read();
39
- for (const p of Object.values(state.plans)) for (const t of Object.values(p.tasks)) {
40
- if (this.stopped || this.slots() >= this.service.options.maxConcurrent) break;
41
- if (t.mode !== 'delegate' || t.status !== 'queued' || !t.dependsOn.every(id => p.tasks[id]?.status === 'completed')) continue;
42
- const key = `${p.id}:${t.id}`; if (this.runs.has(key)) continue;
43
- const parentSessionId = ownerOf(p, t), parent = this.host.agent(parentSessionId);
44
- if (!parent) continue;
45
- let depth = 0; for (let sid = parentSessionId; sid !== p.rootSessionId;) { const bound = Object.values(p.tasks).find(x => x.mode === 'delegate' && x.executionSessionId === sid); if (!bound) break; depth++; sid = ownerOf(p, bound); }
46
- if (depth >= this.service.options.maxDepth) {
47
- await this.service.change(s => { const live = s.plans[p.id].tasks[t.id]; if (live.attempt?.id === t.attempt.id) { live.mode = 'inline'; live.status = 'pending'; live.attempt = null; } });
48
- continue;
49
- }
50
- const run = { planId: p.id, taskId: t.id, attemptId: t.attempt.id, holdsSlot: true, controller: new AbortController() };
51
- this.runs.set(key, run);
52
- run.promise = this.perform(p, t, parent, run).catch(error => this.host.log?.(error)).finally(() => { this.runs.delete(key); this.kick(); });
53
- }
54
- await this.deliver();
55
- } finally { this.pumping = false; if (this.rerun) { this.rerun = false; this.kick(); } }
56
- }
57
- async perform(plan, task, parent, run) {
58
- const childId = randomUUID(); let activation;
59
- try {
60
- // Persist the reserved child binding before it can call any taskflow tool.
61
- await this.service.bind(plan.id, task.id, run.attemptId, childId);
62
- activation = await this.host.start({ childId, parent, signal: run.controller.signal, maxDepth: this.service.options.maxDepth,
63
- label: `${task.id} ${task.title}`, outputSchema: RESULT_SCHEMA,
64
- prompt: [{ type: 'text', text: [
65
- `你负责 ${task.id}:${task.title}。`, `整体目标:${plan.goal}`, `执行要求:${task.instructions}`, `完成标准:${task.criteria}`,
66
- '你可根据难度通过 taskflow_add 增加下级事项,再用 taskflow_start 启动。简单事项留在本会话。',
67
- '有下级事项时先用 taskflow_wait 等待其结果,再完成本层剩余工作。完成下级不代表你已完成。',
68
- '最终返回结构化结果 {"status":"completed|blocked|failed","summary":"实际结果与证据"}。不需父会话复核。',
69
- '只能报告实际完成的工作;失败或缺少输入时返回 failed/blocked。不要调用原生委派工具绕过任务树。',
70
- `依赖结果:${JSON.stringify(task.dependsOn.map(id => ({ id, report: plan.tasks[id].report })))}`,
71
- ].join('\n') }],
72
- });
73
- if (activation.childId !== childId) throw new Error('宿主未使用已持久化的子会话 ID');
74
- run.activation = activation;
75
- const result = await activation.result;
76
- if (result.stopReason !== 'completed') throw new Error(`子任务停止:${result.stopReason}`);
77
- const report = result.structured;
78
- if (!report || !['completed', 'blocked', 'failed'].includes(report.status) || typeof report.summary !== 'string') throw new Error('子任务缺少有效的结构化结果');
79
- await this.service.settle(childId, task.id, run.attemptId, task.version, report, true);
80
- } catch (error) {
81
- try { await this.service.settle(childId, task.id, run.attemptId, task.version, { status: 'failed', summary: String(error.message) }, true); }
82
- catch (settleError) { if (settleError.code !== 'stale' && settleError.code !== 'state') this.host.log?.(settleError); }
83
- } finally {
84
- try { await activation?.dispose(); } catch (error) { this.host.log?.(error); }
85
- }
86
- }
87
- async wait(sid, taskId, signal) {
88
- const view = this.service.view(sid), t = view.plan.tasks[taskId], key = `${view.plan.id}:${taskId}`;
89
- if (this.waiters.has(key)) throw new Error('该任务已在等待下级结果');
90
- await this.service.wait(sid, taskId);
91
- const result = new Promise((resolve, reject) => {
92
- const abort = () => { this.waiters.delete(key); reject(new Error('等待已取消')); };
93
- this.waiters.set(key, { planId: view.plan.id, sessionId: sid, taskId, attemptId: t.attempt.id, resolve: value => { signal?.removeEventListener('abort', abort); resolve(value); }, reject: error => { signal?.removeEventListener('abort', abort); reject(error); } });
94
- if (signal?.aborted) abort(); else signal?.addEventListener('abort', abort, { once: true });
95
- });
96
- this.kick(); return result;
97
- }
98
- async deliver() {
99
- for (const notice of this.service.store.read().outbox.filter(n => !n.delivered)) {
100
- const task = this.service.store.read().plans[notice.planId]?.tasks[notice.taskId];
101
- if (!task || task.status !== 'completed' || task.version !== notice.report.version || task.attempt?.id !== notice.report.attemptId) {
102
- await this.service.store.transaction(s => { const n = s.outbox.find(n => n.id === notice.id); if (n) { n.delivered = true; n.superseded = true; } });
103
- continue;
104
- }
105
- try { if (await this.host.notify(notice) !== false) await this.service.store.transaction(s => { const live = s.outbox.find(n => n.id === notice.id); if (live) live.delivered = true; }); }
106
- catch (error) { this.host.log?.(error); }
107
- }
108
- }
109
- async dispose() {
110
- this.stopped = true; this.unsubscribe(); for (const wait of this.waiters.values()) wait.reject(new Error('Taskflow 已卸载')); this.waiters.clear();
111
- for (const run of this.runs.values()) { run.controller.abort(); await run.activation?.dispose().catch(error => this.host.log?.(error)); }
112
- await Promise.allSettled([...this.runs.values()].map(run => run.promise));
113
- }
114
- }
1
+ import { randomUUID } from 'node:crypto';
2
+ import { children, ownerOf } from '../domain/task-service.mjs';
3
+
4
+ export const RESULT_SCHEMA = { type: 'object', additionalProperties: false, required: ['status', 'summary'], properties: {
5
+ status: { type: 'string', enum: ['completed', 'blocked', 'failed'] },
6
+ summary: { type: 'string' },
7
+ } };
8
+
9
+ /** One scheduler for the whole tree. Waiting ancestors relinquish their slots. */
10
+ export class TaskRuntime {
11
+ constructor(service, host) {
12
+ this.service = service; this.host = host; this.runs = new Map(); this.waiters = new Map(); this.stopped = false; this.pumping = false;
13
+ this.unsubscribe = service.subscribe(() => this.kick());
14
+ }
15
+ kick() { if (this.stopped || this.scheduled) return; this.scheduled = true; queueMicrotask(() => { this.scheduled = false; this.pump().catch(error => this.host.log?.(error)); }); }
16
+ slots() { return [...this.runs.values()].filter(run => run.holdsSlot).length; }
17
+ async pump() {
18
+ if (this.stopped) return; if (this.pumping) { this.rerun = true; return; } this.pumping = true;
19
+ try {
20
+ let state = this.service.store.read();
21
+ for (const [key, run] of this.runs) {
22
+ const task = state.plans[run.planId]?.tasks[run.taskId];
23
+ if (!task || task.attempt?.id !== run.attemptId || task.status === 'cancelled') { run.controller.abort(); continue; }
24
+ if (task.status === 'awaiting_children') run.holdsSlot = false;
25
+ }
26
+ await this.deliver();
27
+ for (const [key, wait] of this.waiters) {
28
+ const p = state.plans[wait.planId], t = p?.tasks[wait.taskId];
29
+ if (!t || t.attempt?.id !== wait.attemptId) { this.waiters.delete(key); wait.reject(new Error('等待任务的执行版本已失效')); continue; }
30
+ // Return pending inline work to its responsible model; waiting for it
31
+ // inside that same model call would deadlock the conversation.
32
+ const pending = children(p, t.id).filter(c => ['running', 'queued', 'awaiting_children'].includes(c.status) && !(c.mode === 'inline' && c.executionSessionId === wait.sessionId));
33
+ if (!pending.length && this.slots() < this.service.options.maxConcurrent) {
34
+ const run = this.runs.get(key); if (run) run.holdsSlot = true;
35
+ this.waiters.delete(key); await this.service.resumeWaiting(p.id, t.id); wait.resolve(children(p, t.id).map(c => ({ id: c.id, status: c.status, report: c.report })));
36
+ }
37
+ }
38
+ state = this.service.store.read();
39
+ for (const p of Object.values(state.plans)) for (const t of Object.values(p.tasks)) {
40
+ if (this.stopped || this.slots() >= this.service.options.maxConcurrent) break;
41
+ if (t.mode !== 'delegate' || t.status !== 'queued' || !t.dependsOn.every(id => p.tasks[id]?.status === 'completed')) continue;
42
+ const key = `${p.id}:${t.id}`; if (this.runs.has(key)) continue;
43
+ const parentSessionId = ownerOf(p, t), parent = this.host.agent(parentSessionId);
44
+ if (!parent) continue;
45
+ let depth = 0; for (let sid = parentSessionId; sid !== p.rootSessionId;) { const bound = Object.values(p.tasks).find(x => x.mode === 'delegate' && x.executionSessionId === sid); if (!bound) break; depth++; sid = ownerOf(p, bound); }
46
+ if (depth >= this.service.options.maxDepth) {
47
+ await this.service.change(s => { const live = s.plans[p.id].tasks[t.id]; if (live.attempt?.id === t.attempt.id) { live.mode = 'inline'; live.status = 'pending'; live.attempt = null; } });
48
+ continue;
49
+ }
50
+ const run = { planId: p.id, taskId: t.id, attemptId: t.attempt.id, holdsSlot: true, controller: new AbortController() };
51
+ this.runs.set(key, run);
52
+ run.promise = this.perform(p, t, parent, run).catch(error => this.host.log?.(error)).finally(() => { this.runs.delete(key); this.kick(); });
53
+ }
54
+ await this.deliver();
55
+ } finally { this.pumping = false; if (this.rerun) { this.rerun = false; this.kick(); } }
56
+ }
57
+ async perform(plan, task, parent, run) {
58
+ const childId = randomUUID(); let activation;
59
+ try {
60
+ // Persist the reserved child binding before it can call any taskflow tool.
61
+ await this.service.bind(plan.id, task.id, run.attemptId, childId);
62
+ activation = await this.host.start({ childId, parent, signal: run.controller.signal, maxDepth: this.service.options.maxDepth,
63
+ label: `${task.id} ${task.title}`, outputSchema: RESULT_SCHEMA,
64
+ prompt: [{ type: 'text', text: [
65
+ `你负责 ${task.id}:${task.title}。`, `整体目标:${plan.goal}`, `执行要求:${task.instructions}`, `完成标准:${task.criteria}`,
66
+ `本事项复杂度:${task.complexity}。执行前先判断是否需要拆解:需要则 taskflow_add 在本事项下增加具体子事项,再逐项 taskflow_start;无需拆解则 taskflow_assess(needsPlan:false, reason, taskId:"${task.id}") 保存判断依据。子事项执行时也要按自身复杂度判断,可再次拆解孙事项。简单事项留在本会话。`,
67
+ '先 taskflow_status 读取现有下级,按原 ID 继续未完成事项;保留完成记录,不重复规划。high 且 independent=true 的事项应委派;不要将其强制标为 inline。',
68
+ `本次任务历史结果:${task.report?.summary ?? '无'}。现有下级:${JSON.stringify(children(plan, task.id).map(t => ({ id: t.id, status: t.status, report: t.report })))}`,
69
+ '有下级事项时先用 taskflow_wait 等待其结果,再完成本层剩余工作。完成下级不代表你已完成。',
70
+ '实际执行过程、关键发现与阶段结果保留在当前子会话,通过 taskflow_progress 保存;不要把中间过程逐条发回父任务。最终结果保存到本子会话后,仅通知直接父任务完成摘要与证据。',
71
+ '最终返回结构化结果 {"status":"completed|blocked|failed","summary":"实际结果与证据"}。不需父会话复核。',
72
+ '只能报告实际完成的工作;失败或缺少输入时返回 failed/blocked。不要调用原生委派工具绕过任务树。',
73
+ `依赖结果:${JSON.stringify(task.dependsOn.map(id => ({ id, report: plan.tasks[id].report })))}`,
74
+ ].join('\n') }],
75
+ });
76
+ if (activation.childId !== childId) throw new Error('宿主未使用已持久化的子会话 ID');
77
+ run.activation = activation;
78
+ await this.service.activationReady(plan.id, task.id, run.attemptId);
79
+ const result = await activation.result;
80
+ if (result.stopReason !== 'completed') throw new Error(`子任务停止:${result.stopReason}`);
81
+ const report = result.structured;
82
+ if (!report || !['completed', 'blocked', 'failed'].includes(report.status) || typeof report.summary !== 'string') throw new Error('子任务缺少有效的结构化结果');
83
+ await this.service.settle(childId, task.id, run.attemptId, task.version, report, true);
84
+ } catch (error) {
85
+ try { await this.service.settle(childId, task.id, run.attemptId, task.version, { status: 'failed', summary: String(error.message) }, true); }
86
+ catch (settleError) { if (settleError.code !== 'stale' && settleError.code !== 'state') this.host.log?.(settleError); }
87
+ } finally {
88
+ try { await activation?.dispose(); } catch (error) { this.host.log?.(error); }
89
+ }
90
+ }
91
+ async wait(sid, taskId, signal) {
92
+ const view = this.service.view(sid), t = view.plan.tasks[taskId], key = `${view.plan.id}:${taskId}`;
93
+ if (this.waiters.has(key)) throw new Error('该任务已在等待下级结果');
94
+ await this.service.wait(sid, taskId);
95
+ const result = new Promise((resolve, reject) => {
96
+ const abort = () => { this.waiters.delete(key); reject(new Error('等待已取消')); };
97
+ this.waiters.set(key, { planId: view.plan.id, sessionId: sid, taskId, attemptId: t.attempt.id, resolve: value => { signal?.removeEventListener('abort', abort); resolve(value); }, reject: error => { signal?.removeEventListener('abort', abort); reject(error); } });
98
+ if (signal?.aborted) abort(); else signal?.addEventListener('abort', abort, { once: true });
99
+ });
100
+ this.kick(); return result;
101
+ }
102
+ async deliver() {
103
+ for (const notice of this.service.store.read().outbox.filter(n => !n.delivered)) {
104
+ const task = this.service.store.read().plans[notice.planId]?.tasks[notice.taskId];
105
+ if (!task || task.status !== 'completed' || task.version !== notice.report.version || task.attempt?.id !== notice.report.attemptId) {
106
+ await this.service.store.transaction(s => { const n = s.outbox.find(n => n.id === notice.id); if (n) { n.delivered = true; n.superseded = true; } });
107
+ continue;
108
+ }
109
+ try {
110
+ if (await this.host.recordResult?.(notice) === false) continue;
111
+ const current = this.service.store.read().plans[notice.planId]?.tasks[notice.taskId];
112
+ if (current?.status !== 'completed' || current.version !== notice.report.version || current.attempt?.id !== notice.report.attemptId) continue;
113
+ if (await this.host.notify(notice) !== false) await this.service.store.transaction(s => { const live = s.outbox.find(n => n.id === notice.id); if (live) live.delivered = true; });
114
+ }
115
+ catch (error) { this.host.log?.(error); }
116
+ }
117
+ }
118
+ async dispose() {
119
+ this.stopped = true; this.unsubscribe(); for (const wait of this.waiters.values()) wait.reject(new Error('Taskflow 已卸载')); this.waiters.clear();
120
+ for (const run of this.runs.values()) { run.controller.abort(); await run.activation?.dispose().catch(error => this.host.log?.(error)); }
121
+ await Promise.allSettled([...this.runs.values()].map(run => run.promise));
122
+ }
123
+ }