dsh-taskflow 0.1.2 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +44 -0
- package/LICENSE +201 -201
- package/NOTICE +6 -1
- package/README.md +247 -43
- package/README_en.md +34 -61
- package/client.js +2428 -62
- package/docs/DETAIL.md +32 -5
- package/docs/DETAIL.zh-CN.md +13 -3
- package/licenses/Marked-MIT.txt +44 -0
- package/package.json +138 -134
- package/src/application/task-runtime.mjs +123 -114
- package/src/domain/task-service.mjs +247 -178
- package/src/domain/tool-view.mjs +11 -0
- package/src/server/config.mjs +1 -1
- package/src/server/index.mjs +18 -8
- package/src/server/inline-sessions.mjs +171 -0
- package/src/server/planning-check.mjs +105 -0
- package/src/server/prompts.mjs +12 -8
- package/src/server/quick-replies.mjs +88 -0
- package/src/server/rpc.mjs +43 -22
- package/src/server/session-context.mjs +11 -5
- package/src/server/task-actions.mjs +63 -0
- package/src/server/tool-schemas.mjs +33 -0
- package/src/server/tool-views.mjs +36 -8
- package/src/server/tools.mjs +20 -14
|
@@ -1,178 +1,247 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
export
|
|
9
|
-
export function
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
export function
|
|
17
|
-
export function
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
if (
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
if (
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
if (
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
if (
|
|
102
|
-
if (
|
|
103
|
-
|
|
104
|
-
if (
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
if (t.
|
|
128
|
-
if (
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
if (
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
if (
|
|
155
|
-
if (
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
if (
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { normalizeDocuments } from './tool-view.mjs';
|
|
3
|
+
|
|
4
|
+
const terminal = task => ['completed', 'cancelled'].includes(task.status);
|
|
5
|
+
export class TaskflowError extends Error { constructor(code, message) { super(message); this.code = code; } }
|
|
6
|
+
const fail = (code, message) => { throw new TaskflowError(code, message); };
|
|
7
|
+
const text = (value, label, max = 16000) => { if (typeof value !== 'string' || !value.trim() || value.length > max) fail('invalid', `${label} 必须为非空文本(最多 ${max} 字符)`); return value.trim(); };
|
|
8
|
+
export const children = (plan, id) => Object.values(plan.tasks).filter(t => t.parentId === id);
|
|
9
|
+
export function descendants(plan, id) { return children(plan, id).flatMap(t => [t, ...descendants(plan, t.id)]); }
|
|
10
|
+
export function resolveTask(plan, ref) {
|
|
11
|
+
if (Object.hasOwn(plan.tasks, ref)) return plan.tasks[ref];
|
|
12
|
+
const found = Object.values(plan.tasks).filter(t => t.title === ref);
|
|
13
|
+
if (found.length !== 1) fail(found.length ? 'ambiguous' : 'not-found', found.length ? '任务名称重复,请使用任务 ID' : `找不到任务:${ref}`);
|
|
14
|
+
return found[0];
|
|
15
|
+
}
|
|
16
|
+
export function sessionPlan(state, sessionId) { return Object.hasOwn(state.sessions, sessionId) ? state.plans[state.sessions[sessionId]] : undefined; }
|
|
17
|
+
export function ownerOf(plan, task) { const parent = plan.tasks[task.parentId]; return parent ? parent.mode === 'delegate' && parent.executionSessionId ? parent.executionSessionId : ownerOf(plan, parent) : plan.rootSessionId; }
|
|
18
|
+
export function recordParentOf(plan, task) {
|
|
19
|
+
const parent = plan.tasks[task.parentId];
|
|
20
|
+
if (!parent) return plan.rootSessionId;
|
|
21
|
+
// A completed result belongs to the attempt that actually produced it.
|
|
22
|
+
// Parent retries must not duplicate/reparent that successful history.
|
|
23
|
+
const original = task.recordSession?.created && task.recordSession.parentSessionId;
|
|
24
|
+
if (terminal(task) && original && (parent.sessionHistory?.some(h => h.sessionId === original) || parent.recordHistory?.some(h => h.id === original))) return original;
|
|
25
|
+
if (parent.mode === 'inline') return parent.recordSession?.created ? parent.recordSession.id : null;
|
|
26
|
+
return parent.executionSessionId && parent.executionCreated !== false ? parent.executionSessionId : null;
|
|
27
|
+
}
|
|
28
|
+
export function currentTask(plan, sid) {
|
|
29
|
+
const record = Object.values(plan.tasks).find(t => t.recordSession?.id === sid || t.recordHistory?.some(r => r.id === sid));
|
|
30
|
+
if (record) return record;
|
|
31
|
+
const focused = plan.active[sid];
|
|
32
|
+
return focused && plan.tasks[focused] ? plan.tasks[focused] : Object.values(plan.tasks).find(t => t.executionSessionId === sid && t.mode === 'delegate');
|
|
33
|
+
}
|
|
34
|
+
export function delegationDepth(plan, task) {
|
|
35
|
+
let depth = 0;
|
|
36
|
+
for (let sid = ownerOf(plan, task); sid !== plan.rootSessionId;) {
|
|
37
|
+
const parent = Object.values(plan.tasks).find(t => t.mode === 'delegate' && t.executionSessionId === sid);
|
|
38
|
+
if (!parent) break;
|
|
39
|
+
depth++; sid = ownerOf(plan, parent);
|
|
40
|
+
}
|
|
41
|
+
return depth;
|
|
42
|
+
}
|
|
43
|
+
function authorize(plan, sid, task) {
|
|
44
|
+
if (sid === plan.rootSessionId) return;
|
|
45
|
+
const bound = Object.values(plan.tasks).find(t => (t.executionSessionId === sid && t.mode === 'delegate') || t.recordSession?.id === sid);
|
|
46
|
+
if (!bound || (task.id !== bound.id && !descendants(plan, bound.id).some(t => t.id === task.id))) fail('forbidden', '只能操作当前会话负责的任务及其下级');
|
|
47
|
+
}
|
|
48
|
+
function validateGraph(plan) {
|
|
49
|
+
// A parent cannot finish until its descendants finish. Depending on a
|
|
50
|
+
// completed ancestor deadlocks that contract; explain how to model phases.
|
|
51
|
+
for (const t of Object.values(plan.tasks)) {
|
|
52
|
+
const seen = new Set([t.id]);
|
|
53
|
+
for (let parent = plan.tasks[t.parentId]; parent && !seen.has(parent.id); parent = plan.tasks[parent.parentId]) {
|
|
54
|
+
seen.add(parent.id);
|
|
55
|
+
if (t.dependsOn.includes(parent.id)) fail('cycle', `${t.id} 不能依赖父任务或祖先 ${parent.id} 完成:parentId 表示组成归属,dependsOn 表示执行先后;若是先后阶段,请设为同级任务再添加依赖`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const visiting = new Set(), visited = new Set();
|
|
59
|
+
const visit = id => { if (visiting.has(id)) fail('cycle', '任务依赖或层级存在循环'); if (visited.has(id)) return; const t = plan.tasks[id]; if (!t) fail('not-found', `依赖任务不存在:${id}`); visiting.add(id); for (const d of [...t.dependsOn, ...children(plan, id).map(c => c.id)]) visit(d); visiting.delete(id); visited.add(id); };
|
|
60
|
+
Object.keys(plan.tasks).forEach(visit);
|
|
61
|
+
}
|
|
62
|
+
function reopen(plan, task) {
|
|
63
|
+
for (let t = task; t; t = plan.tasks[t.parentId]) {
|
|
64
|
+
if (t.status === 'completed') { t.status = 'pending'; t.version++; t.attempt = null; }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
function stamp(plan, kind, taskId, detail) { plan.version++; plan.updatedAt = new Date().toISOString(); plan.events.push({ id: randomUUID(), kind, taskId, detail, at: plan.updatedAt }); plan.events = plan.events.slice(-500); }
|
|
68
|
+
|
|
69
|
+
export class TaskService {
|
|
70
|
+
constructor(store, options = {}) { this.store = store; this.options = { maxDepth: 2, maxConcurrent: 2, maxTasks: 200, ...options }; this.listeners = new Set(); }
|
|
71
|
+
subscribe(listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
|
|
72
|
+
async change(operation) { const value = await this.store.transaction(operation); for (const listener of this.listeners) { try { listener(); } catch {} } return value; }
|
|
73
|
+
view(sid) { const state = this.store.read(), plan = sessionPlan(state, sid); return { revision: state.revision, plan: plan ?? null, currentTaskId: plan ? currentTask(plan, sid)?.id ?? null : null, tool: plan?.views[sid] ?? null, limits: this.options }; }
|
|
74
|
+
scope(state, sid) { const plan = sessionPlan(state, sid); if (!plan) fail('no-plan', '当前会话尚未建立任务计划'); return plan; }
|
|
75
|
+
continuation(sid, ref, version) {
|
|
76
|
+
const p = this.scope(this.store.read(), sid), t = resolveTask(p, ref); authorize(p, sid, t);
|
|
77
|
+
if (t.version !== version) fail('stale', '任务要求已变更,请刷新后重试');
|
|
78
|
+
if (!['pending', 'paused', 'blocked', 'failed'].includes(t.status)) fail('state', '任务当前不可继续,请刷新状态');
|
|
79
|
+
const ancestors = []; for (let a = p.tasks[t.parentId]; a; a = p.tasks[a.parentId]) ancestors.unshift(a);
|
|
80
|
+
if (ancestors.some(a => a.status === 'cancelled')) fail('cancelled', '父任务已取消');
|
|
81
|
+
return structuredClone({ rootSessionId: p.rootSessionId, task: t, ancestors });
|
|
82
|
+
}
|
|
83
|
+
async create(sid, input) {
|
|
84
|
+
return this.change(state => {
|
|
85
|
+
if (typeof sid !== 'string' || !sid || ['__proto__', 'prototype', 'constructor'].includes(sid)) fail('invalid', '会话 ID 无效');
|
|
86
|
+
if (Object.hasOwn(state.sessions, sid)) fail('exists', '计划已存在,请通过增量操作调整,不能覆盖现有计划');
|
|
87
|
+
const plan = { id: randomUUID(), rootSessionId: sid, title: text(input.title, '标题', 240), goal: text(input.goal, '目标'), version: 1, seq: 0, tasks: {}, active: {}, views: {}, events: [], createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() };
|
|
88
|
+
state.plans[plan.id] = plan; state.sessions[sid] = plan.id;
|
|
89
|
+
this.insert(plan, sid, input.tasks, null); validateGraph(plan); stamp(plan, 'plan', null, '主会话模型生成计划'); return structuredClone(plan);
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
insert(plan, sid, inputs, defaultParent) {
|
|
93
|
+
if (!Array.isArray(inputs) || !inputs.length) fail('invalid', '至少提供一个待办事项');
|
|
94
|
+
if (Object.keys(plan.tasks).length + inputs.length > this.options.maxTasks) fail('limit', '计划已达到任务数量上限');
|
|
95
|
+
const aliases = new Map(), created = [];
|
|
96
|
+
for (const input of inputs) {
|
|
97
|
+
if (input.ref && aliases.has(input.ref)) fail('invalid', '新任务 ref 重复');
|
|
98
|
+
const id = `T-${String(++plan.seq).padStart(3, '0')}`;
|
|
99
|
+
if (input.ref) aliases.set(input.ref, id);
|
|
100
|
+
const complexity = input.complexity ?? 'low';
|
|
101
|
+
if (!['low', 'medium', 'high'].includes(complexity)) fail('invalid', '未知任务复杂度');
|
|
102
|
+
if (input.mode !== undefined && !['inline', 'delegate'].includes(input.mode)) fail('invalid', '未知执行方式');
|
|
103
|
+
const mode = complexity === 'high' && input.independent === true ? 'delegate' : input.mode ?? (complexity !== 'low' && input.independent === true ? 'delegate' : 'inline');
|
|
104
|
+
if (!['inline', 'delegate'].includes(mode)) fail('invalid', '未知执行方式');
|
|
105
|
+
const task = { id, title: text(input.title, '任务标题', 240), instructions: text(input.instructions ?? input.title, '任务要求'), criteria: text(input.criteria ?? '完成任务目标并保存结果', '完成标准'), parentId: defaultParent, dependsOn: [], complexity, independent: input.independent === true, mode, status: 'pending', version: 1, attempts: 0, attempt: null, executionSessionId: null, report: null, history: [] };
|
|
106
|
+
plan.tasks[id] = task; created.push({ task, input });
|
|
107
|
+
}
|
|
108
|
+
for (const { task, input } of created) {
|
|
109
|
+
const resolve = ref => aliases.get(ref) ?? resolveTask(plan, ref).id;
|
|
110
|
+
if (input.parentId != null) task.parentId = resolve(input.parentId);
|
|
111
|
+
if (task.parentId) { const parent = plan.tasks[task.parentId]; authorize(plan, sid, parent); if (parent.status === 'cancelled') fail('cancelled', '不能向已取消任务增补'); }
|
|
112
|
+
else if (sid !== plan.rootSessionId) fail('forbidden', '子会话不能创建根任务');
|
|
113
|
+
if (input.dependsOn !== undefined && !Array.isArray(input.dependsOn)) fail('invalid', 'dependsOn 必须是任务 ID 数组');
|
|
114
|
+
task.dependsOn = [...new Set((input.dependsOn ?? []).map(resolve))];
|
|
115
|
+
}
|
|
116
|
+
validateGraph(plan); for (const { task } of created) if (task.parentId) reopen(plan, plan.tasks[task.parentId]); return created.map(x => structuredClone(x.task));
|
|
117
|
+
}
|
|
118
|
+
async add(sid, inputs, parentRef, expectedVersion) {
|
|
119
|
+
return this.change(state => { const p = this.scope(state, sid); if (expectedVersion != null && p.version !== expectedVersion) fail('stale', '计划已变更,请刷新后重试');
|
|
120
|
+
const parent = parentRef != null ? resolveTask(p, parentRef) : currentTask(p, sid);
|
|
121
|
+
if (parent) authorize(p, sid, parent);
|
|
122
|
+
const made = this.insert(p, sid, inputs, parent?.id ?? null); stamp(p, 'add', parent?.id ?? null, made.map(t => t.id).join(', ')); return made;
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
async update(sid, ref, patch, version) {
|
|
126
|
+
return this.change(state => { const p = this.scope(state, sid), t = resolveTask(p, ref); authorize(p, sid, t);
|
|
127
|
+
if (t.version !== version) fail('stale', '任务要求已变更,请刷新');
|
|
128
|
+
if (!patch || !Object.keys(patch).length || Object.keys(patch).some(k => !['title', 'instructions', 'criteria', 'complexity', 'independent', 'mode', 'dependsOn', 'parentId'].includes(k))) fail('invalid', '任务修改字段无效');
|
|
129
|
+
if (t.status === 'cancelled') fail('cancelled', '已取消任务不可修改');
|
|
130
|
+
for (const k of ['title', 'instructions', 'criteria']) if (patch[k] !== undefined) t[k] = text(patch[k], k, k === 'title' ? 240 : 16000);
|
|
131
|
+
if (patch.complexity !== undefined) { if (!['low', 'medium', 'high'].includes(patch.complexity)) fail('invalid', '未知任务复杂度'); t.complexity = patch.complexity; }
|
|
132
|
+
if (patch.independent !== undefined) { if (typeof patch.independent !== 'boolean') fail('invalid', 'independent 必须为布尔值'); t.independent = patch.independent; }
|
|
133
|
+
if (patch.mode !== undefined) { if (!['inline', 'delegate'].includes(patch.mode)) fail('invalid', '未知执行方式'); t.mode = patch.mode; }
|
|
134
|
+
if (t.complexity === 'high' && t.independent) t.mode = 'delegate';
|
|
135
|
+
if (patch.dependsOn !== undefined) { if (!Array.isArray(patch.dependsOn)) fail('invalid', '依赖必须是数组'); t.dependsOn = patch.dependsOn.map(r => resolveTask(p, r).id); }
|
|
136
|
+
if (patch.parentId !== undefined) {
|
|
137
|
+
if (patch.parentId === null) { if (sid !== p.rootSessionId) fail('forbidden', '只有主会话能移动为根任务'); t.parentId = null; }
|
|
138
|
+
else { const parent = resolveTask(p, patch.parentId); authorize(p, sid, parent); if (parent.status === 'cancelled') fail('cancelled', '不能移动到已取消任务下'); t.parentId = parent.id; }
|
|
139
|
+
}
|
|
140
|
+
validateGraph(p); t.version++; t.attempt = null; t.status = 'paused'; t.history.push({ kind: 'requirements', version: t.version, at: new Date().toISOString() }); if (t.parentId) reopen(p, p.tasks[t.parentId]);
|
|
141
|
+
// Invalidate descendant executions that inherited the old requirements.
|
|
142
|
+
for (const child of descendants(p, t.id)) if (!terminal(child)) { child.version++; child.attempt = null; child.status = 'paused'; }
|
|
143
|
+
stamp(p, 'update', t.id, '要求更新,旧执行结果失效'); return structuredClone(t);
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
async cancel(sid, ref, version) {
|
|
147
|
+
return this.change(state => { const p = this.scope(state, sid), t = resolveTask(p, ref); authorize(p, sid, t); if (version !== t.version) fail('stale', '任务版本已变化');
|
|
148
|
+
for (const item of [t, ...descendants(p, t.id)]) { item.status = 'cancelled'; item.version++; item.attempt = null; item.history.push({ kind: 'cancel', at: new Date().toISOString() }); }
|
|
149
|
+
stamp(p, 'cancel', t.id, '保留任务与会话历史'); return structuredClone(t);
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
async start(sid, ref) {
|
|
153
|
+
return this.change(state => { const p = this.scope(state, sid), t = resolveTask(p, ref); authorize(p, sid, t);
|
|
154
|
+
if (!['pending', 'paused', 'blocked', 'failed'].includes(t.status)) fail('state', '任务当前不可启动');
|
|
155
|
+
if (!t.dependsOn.every(id => p.tasks[id]?.status === 'completed')) fail('dependency', '前置任务尚未完成');
|
|
156
|
+
for (let ancestor = p.tasks[t.parentId]; ancestor; ancestor = p.tasks[ancestor.parentId]) if (ancestor.mode === 'delegate' && (!ancestor.executionSessionId || !['running', 'awaiting_children'].includes(ancestor.status))) fail('owner', '请先启动负责此事项的父任务,不能将下级会话改挂到主会话');
|
|
157
|
+
for (let ancestor = p.tasks[t.parentId]; ancestor; ancestor = p.tasks[ancestor.parentId]) if (ancestor.mode === 'inline' && !ancestor.attempts) fail('owner', '请先启动父任务,再执行其下级,不能为尚未执行的父事项提前创建会话');
|
|
158
|
+
// Resolve the limit synchronously so the model sees inline in start's result,
|
|
159
|
+
// instead of queueing a child that can never run while its parent waits.
|
|
160
|
+
if (t.complexity === 'high' && t.independent) t.mode = 'delegate';
|
|
161
|
+
if (t.mode === 'delegate' && delegationDepth(p, t) >= this.options.maxDepth) { t.mode = 'inline'; t.executionReason = '达到子会话深度上限,在当前会话执行'; }
|
|
162
|
+
else t.executionReason = t.mode === 'delegate' ? '独立事项,委派子会话执行' : '简单或共享上下文事项,在当前会话执行';
|
|
163
|
+
if (t.mode === 'inline' && ownerOf(p, t) !== sid) fail('forbidden', '请在负责此任务的会话执行');
|
|
164
|
+
const ancestors = new Set(); for (let x = p.tasks[t.parentId]; x; x = p.tasks[x.parentId]) ancestors.add(x.id);
|
|
165
|
+
if (t.mode === 'inline' && Object.values(p.tasks).some(x => x.id !== t.id && !ancestors.has(x.id) && x.executionSessionId === sid && x.mode === 'inline' && x.status === 'running')) fail('busy', '当前会话已有执行事项');
|
|
166
|
+
t.status = t.mode === 'delegate' ? 'queued' : 'running'; t.attempt = { id: randomUUID(), version: t.version, number: ++t.attempts };
|
|
167
|
+
if (t.mode === 'inline') { t.executionSessionId = sid; p.active[sid] = t.id; }
|
|
168
|
+
stamp(p, 'start', t.id, t.mode); return structuredClone(t);
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
async bind(planId, taskId, attemptId, childId) {
|
|
172
|
+
return this.change(state => { const p = state.plans[planId], t = p?.tasks[taskId]; if (!t || t.attempt?.id !== attemptId || t.status !== 'queued') fail('stale', '执行已过期');
|
|
173
|
+
if (t.executionSessionId && t.executionSessionId !== childId && t.executionCreated !== false) {
|
|
174
|
+
t.sessionHistory ??= [];
|
|
175
|
+
t.sessionHistory.push({ sessionId: t.executionSessionId, parentSessionId: t.executionParentSessionId || ownerOf(p, t), status: t.report?.status || 'paused' });
|
|
176
|
+
}
|
|
177
|
+
t.executionCreated = false;
|
|
178
|
+
t.executionParentSessionId = ownerOf(p, t); t.status = 'running'; t.executionSessionId = childId; state.sessions[childId] = p.id; p.active[childId] = t.id; stamp(p, 'delegate', t.id, childId);
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
async activationReady(planId, taskId, attemptId) { return this.change(state => { const t = state.plans[planId]?.tasks[taskId]; if (t?.attempt?.id === attemptId) t.executionCreated = true; }); }
|
|
182
|
+
async reserveRecord(planId, taskId) {
|
|
183
|
+
return this.change(state => {
|
|
184
|
+
const p = state.plans[planId], t = p?.tasks[taskId];
|
|
185
|
+
if (!t || t.mode !== 'inline') fail('state', '该事项不是行内任务');
|
|
186
|
+
if (!t.attempts) fail('state', '事项尚未执行,不创建子会话');
|
|
187
|
+
const parentSessionId = recordParentOf(p, t);
|
|
188
|
+
if (!parentSessionId) fail('owner', '父事项会话尚未创建,稍后按原层级建立记录');
|
|
189
|
+
if (t.recordSession?.parentSessionId === parentSessionId) return structuredClone(t.recordSession);
|
|
190
|
+
if (t.recordSession) { t.recordHistory ??= []; t.recordHistory.push({ ...t.recordSession, status: t.report?.status || 'paused' }); }
|
|
191
|
+
t.recordSession = { id: randomUUID(), parentSessionId, created: false };
|
|
192
|
+
state.sessions[t.recordSession.id] = p.id;
|
|
193
|
+
return structuredClone(t.recordSession);
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
async recordReady(planId, taskId, recordId) { return this.change(state => { const p = state.plans[planId], t = p?.tasks[taskId]; if (t?.recordSession?.id === recordId) { t.recordSession.created = true; delete t.recordError; stamp(p, 'record', taskId, '行内事项子会话记录已保存'); } }); }
|
|
197
|
+
async recordError(planId, taskId, message) { return this.change(state => { const t = state.plans[planId]?.tasks[taskId]; if (t) t.recordError = String(message).slice(0, 1000); }); }
|
|
198
|
+
async assessDecomposition(sid, ref, needsSplit, reason) {
|
|
199
|
+
return this.change(state => {
|
|
200
|
+
const p = this.scope(state, sid), t = resolveTask(p, ref); authorize(p, sid, t);
|
|
201
|
+
if (t.executionSessionId !== sid || !['running', 'awaiting_children'].includes(t.status)) fail('state', '只能判断当前执行会话正在负责的事项');
|
|
202
|
+
if (typeof needsSplit !== 'boolean') fail('invalid', '是否拆解必须为布尔值');
|
|
203
|
+
t.decomposition = { version: t.version, needsSplit, reason: text(reason, '拆解依据', 2000), at: new Date().toISOString() };
|
|
204
|
+
stamp(p, 'assess', t.id, needsSplit ? '模型判定需要拆解下级事项' : '模型判定本层直接执行');
|
|
205
|
+
return { taskId: t.id, ...structuredClone(t.decomposition), message: needsSplit ? '请用 taskflow_add 保存下级事项,然后逐项启动;不要重建主计划' : '本层直接执行,完成后提交实际结果' };
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
async wait(sid, ref) { return this.change(state => { const p = this.scope(state, sid), t = resolveTask(p, ref); if (t.executionSessionId !== sid || t.status !== 'running') fail('state', '当前任务未在本会话执行'); t.status = 'awaiting_children'; stamp(p, 'wait', t.id, '等待下级任务,释放并发名额'); }); }
|
|
209
|
+
async resumeWaiting(planId, id) { return this.change(state => { const p = state.plans[planId], t = p.tasks[id]; if (t.status !== 'awaiting_children') return; t.status = 'running'; stamp(p, 'resume', id, '继续本层工作'); }); }
|
|
210
|
+
async settle(sid, ref, attemptId, version, result, fromRuntime = false) {
|
|
211
|
+
return this.change(state => { const p = this.scope(state, sid), t = resolveTask(p, ref); authorize(p, sid, t);
|
|
212
|
+
if (t.version !== version || t.attempt?.id !== attemptId) fail('stale', '旧版本或旧执行结果不能完成当前任务');
|
|
213
|
+
if (t.executionSessionId !== sid) fail('forbidden', '只能由本次执行会话提交结果');
|
|
214
|
+
if (t.mode === 'delegate' && !fromRuntime) fail('final-report', '委派任务请返回最终结构化结果;行内子事项可通过工具完成');
|
|
215
|
+
if (t.status === 'completed' && t.report?.attemptId === attemptId) return structuredClone(t);
|
|
216
|
+
if (!['running', 'awaiting_children'].includes(t.status)) fail('state', '任务当前未在执行');
|
|
217
|
+
if (!['completed', 'failed', 'blocked'].includes(result.status)) fail('invalid', '无效结果状态');
|
|
218
|
+
if (result.status === 'completed' && children(p, t.id).some(c => !terminal(c))) fail('children', '下级任务尚未结束,完成本层剩余工作后再报告');
|
|
219
|
+
const report = { status: result.status, summary: text(result.summary, '完成摘要'), version, attemptId, at: new Date().toISOString() };
|
|
220
|
+
t.report = report; t.history.push(report); t.status = result.status;
|
|
221
|
+
if (p.active[sid] === t.id) { const parent = p.tasks[t.parentId]; if (parent?.executionSessionId === sid && ['running', 'awaiting_children'].includes(parent.status)) p.active[sid] = parent.id; else delete p.active[sid]; }
|
|
222
|
+
if (result.status === 'completed') { const key = `${p.id}:${t.id}:${version}:${attemptId}`; if (!state.outbox.some(n => n.id === key)) state.outbox.push({ id: key, planId: p.id, taskId: t.id, targetSessionId: ownerOf(p, t), report, delivered: false }); }
|
|
223
|
+
stamp(p, result.status, t.id, report.summary); return structuredClone(t);
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
async openView(sid, input) {
|
|
227
|
+
return this.change(state => { const p = this.scope(state, sid); if (!['browser', 'editor', 'terminal', 'plugin', 'orchestration'].includes(input.kind)) fail('invalid', '未知工具视图');
|
|
228
|
+
if (input.expectedId && (p.views[sid]?.id !== input.expectedId || (input.requireOpen && !p.views[sid]?.open))) return;
|
|
229
|
+
if (input.url) { const u = new URL(input.url); if (!['https:', 'http:'].includes(u.protocol) || u.username || u.password) fail('invalid', '浏览器地址必须为不含凭据的 HTTP(S) URL'); }
|
|
230
|
+
if (input.filePath && !normalizeDocuments(input).some(f => f.path === input.filePath)) fail('invalid', '文件路径必须为支持预览的本地或工作区文档路径');
|
|
231
|
+
p.views[sid] = { id: input.id || randomUUID(), kind: input.kind, title: String(input.title ?? input.kind).slice(0, 240), url: input.url ?? null, files: normalizeDocuments(input), phase: ['running', 'failed'].includes(input.phase) ? input.phase : 'ready', autoOpen: input.autoOpen !== false, sourceTool: String(input.sourceTool ?? '').slice(0, 240), content: String(input.content ?? '').slice(0, 100000), open: true, taskId: currentTask(p, sid)?.id ?? null }; stamp(p, 'tool', p.views[sid].taskId, input.kind);
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
async closeView(sid) { return this.change(state => { const p = this.scope(state, sid); if (p.views[sid]) p.views[sid].open = false; }); }
|
|
235
|
+
async focus(sid, ref) { return this.change(state => { const p = this.scope(state, sid), t = resolveTask(p, ref); authorize(p, sid, t); if (ownerOf(p, t) !== sid && t.executionSessionId !== sid) fail('forbidden', '请先切换到此任务负责会话'); p.active[sid] = t.id; }); }
|
|
236
|
+
async reorder(sid, ref, direction, version) {
|
|
237
|
+
return this.change(state => { const p = this.scope(state, sid), t = resolveTask(p, ref); authorize(p, sid, t);
|
|
238
|
+
if (p.version !== version) fail('stale', '计划顺序已变化,请刷新');
|
|
239
|
+
if (![1, -1].includes(direction)) fail('invalid', 'direction 必须为 1 或 -1');
|
|
240
|
+
const all = Object.values(p.tasks), siblings = all.filter(x => x.parentId === t.parentId), target = siblings[siblings.indexOf(t) + direction];
|
|
241
|
+
if (!target) return;
|
|
242
|
+
const a = all.indexOf(t), b = all.indexOf(target); [all[a], all[b]] = [all[b], all[a]];
|
|
243
|
+
p.tasks = Object.fromEntries(all.map(x => [x.id, x])); stamp(p, 'reorder', t.id, direction < 0 ? '同级上移' : '同级下移');
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
async recover() { return this.change(state => { for (const p of Object.values(state.plans)) for (const t of Object.values(p.tasks)) if (['running', 'queued', 'awaiting_children'].includes(t.status)) { t.status = 'paused'; t.attempt = null; stamp(p, 'recovery', t.id, '宿主中断,保留计划;需明确继续执行'); } }); }
|
|
247
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Route explicit file metadata, never prose or shell commands.
|
|
2
|
+
export function documentFormat(path) {
|
|
3
|
+
const ext = typeof path === 'string' ? path.split(/[\\/]/).at(-1).split('.').at(-1).toLowerCase() : '';
|
|
4
|
+
return ['md', 'markdown'].includes(ext) ? 'markdown' : ['xls', 'xlsx', 'csv', 'tsv'].includes(ext) ? 'excel' : ['doc', 'docx'].includes(ext) ? 'word' : ['ppt', 'pptx'].includes(ext) ? 'powerpoint' : ext === 'pdf' ? 'pdf' : null;
|
|
5
|
+
}
|
|
6
|
+
export function documentPath(value) {
|
|
7
|
+
return typeof value === 'string' && value.length <= 4096 && !/[\u0000-\u001f]/.test(value) && (!/^[a-z][a-z\d+.-]*:/i.test(value) || /^[a-z]:[\\/]/i.test(value)) && documentFormat(value) ? value : null;
|
|
8
|
+
}
|
|
9
|
+
export function normalizeDocuments(input) {
|
|
10
|
+
return [...new Set([input.filePath, ...(Array.isArray(input.files) ? input.files : [])].filter(documentPath))].slice(0, 20).map(path => ({ path, format: documentFormat(path) }));
|
|
11
|
+
}
|
package/src/server/config.mjs
CHANGED
|
@@ -4,5 +4,5 @@ import z from '@deepseek-ai/schemastery';
|
|
|
4
4
|
export const Config = z.object({
|
|
5
5
|
dataDir: z.string(), maxDepth: z.number().step(1).min(0).max(8).default(2),
|
|
6
6
|
maxConcurrent: z.number().step(1).min(1).max(16).default(2), maxTasks: z.number().step(1).min(1).max(2000).default(200),
|
|
7
|
-
autoPlan: z.boolean().default(true), provider: z.string().default('spawn'),
|
|
7
|
+
autoPlan: z.boolean().default(true), quickReplies: z.boolean().default(true), provider: z.string().default('spawn'),
|
|
8
8
|
});
|
package/src/server/index.mjs
CHANGED
|
@@ -8,16 +8,20 @@ import { registerTools } from './tools.mjs';
|
|
|
8
8
|
import { registerSessionContext } from './session-context.mjs';
|
|
9
9
|
import { registerToolViews } from './tool-views.mjs';
|
|
10
10
|
import { registerRpc } from './rpc.mjs';
|
|
11
|
+
import { PlanningCheck } from './planning-check.mjs';
|
|
12
|
+
import { TaskActions } from './task-actions.mjs';
|
|
13
|
+
import { InlineSessions } from './inline-sessions.mjs';
|
|
14
|
+
import { QuickReplies } from './quick-replies.mjs';
|
|
11
15
|
export { Config } from './config.mjs';
|
|
12
16
|
export const name = 'taskflow';
|
|
13
|
-
export const inject = ['tools', 'agents', 'sessions', 'systemPrompt', 'subagents'];
|
|
17
|
+
export const inject = ['tools', 'agents', 'sessions', 'systemPrompt', 'subagents', 'llm'];
|
|
14
18
|
|
|
15
19
|
// 生命周期装配入口;状态、调度与宿主 API 适配各自独立。
|
|
16
20
|
export async function apply(ctx, config = {}) {
|
|
17
21
|
const dataDir = config.dataDir || join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'taskflow');
|
|
18
22
|
const store = await new FileStore(dataDir).init();
|
|
19
|
-
let runtime, timer;
|
|
20
|
-
ctx.effect(() => async () => { clearInterval(timer); await runtime?.dispose(); await store.close(); });
|
|
23
|
+
let runtime, actions, records, replies, timer;
|
|
24
|
+
ctx.effect(() => async () => { clearInterval(timer); await replies?.dispose(); await runtime?.dispose(); await actions?.dispose(); await records?.dispose(); await store.close(); });
|
|
21
25
|
const service = new TaskService(store, config); await service.recover();
|
|
22
26
|
const log = error => ctx.logger?.warn?.(`taskflow: ${error.message ?? error}`);
|
|
23
27
|
runtime = new TaskRuntime(service, {
|
|
@@ -26,13 +30,19 @@ export async function apply(ctx, config = {}) {
|
|
|
26
30
|
// Supply both shapes in one call so neither host needs a retry or a second activation.
|
|
27
31
|
start: request => ctx.subagents.startActivation({ provider: config.provider || 'spawn', ...request, request, delivery: 'caller' }),
|
|
28
32
|
notify: createNoticeSender(ctx),
|
|
33
|
+
recordResult: notice => records.result(notice),
|
|
29
34
|
});
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
35
|
+
const planning = new PlanningCheck(service, config.autoPlan !== false);
|
|
36
|
+
actions = new TaskActions(ctx, service);
|
|
37
|
+
records = new InlineSessions(ctx, service, log);
|
|
38
|
+
replies = new QuickReplies(ctx, service, config.quickReplies !== false);
|
|
39
|
+
ctx.provide('taskflow', { service, runtime, planning, actions, records, replies });
|
|
40
|
+
registerTools(ctx, service, runtime, planning, records);
|
|
41
|
+
registerSessionContext(ctx, service, config, planning);
|
|
33
42
|
registerToolViews(ctx, service, log);
|
|
34
|
-
registerRpc(ctx, service);
|
|
43
|
+
registerRpc(ctx, service, planning, actions, replies);
|
|
35
44
|
ctx.on('agent/created', () => { runtime.kick(); return undefined; }, { global: true });
|
|
36
|
-
timer = setInterval(() => runtime.kick(), 3000); timer.unref?.();
|
|
45
|
+
timer = setInterval(() => { runtime.kick(); records.kick(); }, 3000); timer.unref?.();
|
|
46
|
+
records.kick();
|
|
37
47
|
runtime.kick();
|
|
38
48
|
}
|