dsh-taskflow 0.0.0-stage → 0.1.0

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/package.json CHANGED
@@ -1,6 +1,133 @@
1
- {
2
- "name": "dsh-taskflow",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "dsh-taskflow",
3
+ "version": "0.1.0",
4
+ "description": "智能任务编排:持久层级计划、按需递归子会话与完成通知",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./client": "./client.js",
10
+ "./package.json": "./package.json",
11
+ "./cordis.patch.yml": "./cordis.patch.yml",
12
+ "./icon": "./assets/icon.svg",
13
+ "./locale/*.json": "./locale/*.json"
14
+ },
15
+ "files": [
16
+ "index.js",
17
+ "client.js",
18
+ "src/domain/*.mjs",
19
+ "src/application/*.mjs",
20
+ "src/storage/*.mjs",
21
+ "src/server/*.mjs",
22
+ "assets/icon.svg",
23
+ "assets/icon.png",
24
+ "locale/*.json",
25
+ "cordis.patch.yml",
26
+ "README.md",
27
+ "CHANGELOG.md",
28
+ "NOTICE",
29
+ "LICENSE",
30
+ "licenses/*.txt",
31
+ "docs/DETAIL.md",
32
+ "docs/DETAIL.zh-CN.md"
33
+ ],
34
+ "scripts": {
35
+ "build": "node scripts/build.mjs",
36
+ "build:check": "node scripts/build.mjs --check",
37
+ "test": "node --test test/*.test.mjs",
38
+ "check": "npm run build:check && npm test && npm run check:release",
39
+ "check:release": "node scripts/check-release.mjs",
40
+ "check:package": "node scripts/check-package.mjs",
41
+ "prepack": "npm run build && npm test && npm run check:release",
42
+ "dev": "node scripts/dev.mjs",
43
+ "check:hosts": "node scripts/check-hosts.mjs"
44
+ },
45
+ "engines": {
46
+ "node": ">=24.9.0",
47
+ "dsh": ">=0.2.1-rc.3 <1.0.0-0 || >=0.2.2-0 <1.0.0-0 || >=0.2.3-0 <1.0.0-0 || >=0.3.0-0 <1.0.0-0"
48
+ },
49
+ "dsh": {
50
+ "bundle": {
51
+ "patch": "./cordis.patch.yml"
52
+ },
53
+ "client": {
54
+ "platform": "web",
55
+ "inject": [
56
+ "@deepseek-ai/dsh-client-ui-conversation",
57
+ "@deepseek-ai/dsh-client-ui-workspace",
58
+ "@deepseek-ai/dsh-client-ui-sidebar-right",
59
+ "@deepseek-ai/dsh-client-ui-layout",
60
+ "@deepseek-ai/dsh-client-connection"
61
+ ]
62
+ }
63
+ },
64
+ "peerDependencies": {
65
+ "@deepseek-ai/cordis": "~4.0.5 || ~4.1.0",
66
+ "@deepseek-ai/dsh-llm": ">=0.2.1-rc.3 <1.0.0-0 || >=0.2.2-0 <1.0.0-0 || >=0.2.3-0 <1.0.0-0 || >=0.3.0-0 <1.0.0-0",
67
+ "@deepseek-ai/dsh-tools": ">=0.2.1-rc.3 <1.0.0-0 || >=0.2.2-0 <1.0.0-0 || >=0.2.3-0 <1.0.0-0 || >=0.3.0-0 <1.0.0-0",
68
+ "@deepseek-ai/schemastery": "~3.18.5 || ~3.19.0",
69
+ "react": "^18.3.1",
70
+ "react-dom": "^18.3.1"
71
+ },
72
+ "devDependencies": {
73
+ "@deepseek-ai/cordis": "4.1.0",
74
+ "@deepseek-ai/dsh-agent": "0.2.2-rc.2",
75
+ "@deepseek-ai/dsh-agent-loop": "0.2.2-rc.2",
76
+ "@deepseek-ai/dsh-agent-loop-testkit": "0.2.2-rc.2",
77
+ "@deepseek-ai/dsh-client-connection": "0.2.2-rc.2",
78
+ "@deepseek-ai/dsh-client-ui-conversation": "0.2.2-rc.2",
79
+ "@deepseek-ai/dsh-client-ui-sidebar-right": "0.2.2-rc.2",
80
+ "@deepseek-ai/dsh-client-ui-workspace": "0.2.2-rc.2",
81
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.2",
82
+ "@deepseek-ai/dsh-session": "0.2.2-rc.2",
83
+ "@deepseek-ai/dsh-session-persistence-jsonl": "0.2.2-rc.2",
84
+ "@deepseek-ai/dsh-subagent": "0.2.2-rc.2",
85
+ "@deepseek-ai/dsh-subagent-spawn-in-process": "0.2.2-rc.2",
86
+ "@deepseek-ai/dsh-system-prompt": "0.2.2-rc.2",
87
+ "@deepseek-ai/dsh-tools": "0.2.2-rc.2",
88
+ "@deepseek-ai/schemastery": "3.19.0",
89
+ "esbuild": "0.25.12",
90
+ "jsdom": "26.1.0",
91
+ "react": "18.3.1",
92
+ "react-dom": "18.3.1",
93
+ "yaml": "2.8.1",
94
+ "semver": "7.7.3"
95
+ },
96
+ "license": "(Apache-2.0 AND MIT)",
97
+ "author": "Oak-liuhj",
98
+ "repository": {
99
+ "type": "git",
100
+ "url": "git+https://github.com/Oak-liuhj/dsh-taskflow.git"
101
+ },
102
+ "keywords": [
103
+ "dsh-plugin",
104
+ "deepseek-harness",
105
+ "dsh",
106
+ "taskflow",
107
+ "task-tree",
108
+ "workflow",
109
+ "orchestration",
110
+ "subagents"
111
+ ],
112
+ "homepage": "https://github.com/Oak-liuhj/dsh-taskflow#readme",
113
+ "bugs": {
114
+ "url": "https://github.com/Oak-liuhj/dsh-taskflow/issues"
115
+ },
116
+ "icon": "assets/icon.png",
117
+ "publishConfig": {
118
+ "access": "public",
119
+ "registry": "https://registry.npmjs.org/",
120
+ "tag": "latest"
121
+ },
122
+ "peerDependenciesMeta": {
123
+ "@deepseek-ai/cordis": {
124
+ "optional": true
125
+ },
126
+ "react": {
127
+ "optional": true
128
+ },
129
+ "react-dom": {
130
+ "optional": true
131
+ }
132
+ }
133
+ }
@@ -0,0 +1,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
+ '你可根据难度通过 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
+ }
@@ -0,0 +1,178 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
3
+ const terminal = task => ['completed', 'cancelled'].includes(task.status);
4
+ export class TaskflowError extends Error { constructor(code, message) { super(message); this.code = code; } }
5
+ const fail = (code, message) => { throw new TaskflowError(code, message); };
6
+ const text = (value, label, max = 16000) => { if (typeof value !== 'string' || !value.trim() || value.length > max) fail('invalid', `${label} 必须为非空文本(最多 ${max} 字符)`); return value.trim(); };
7
+ export const children = (plan, id) => Object.values(plan.tasks).filter(t => t.parentId === id);
8
+ export function descendants(plan, id) { return children(plan, id).flatMap(t => [t, ...descendants(plan, t.id)]); }
9
+ export function resolveTask(plan, ref) {
10
+ if (Object.hasOwn(plan.tasks, ref)) return plan.tasks[ref];
11
+ const found = Object.values(plan.tasks).filter(t => t.title === ref);
12
+ if (found.length !== 1) fail(found.length ? 'ambiguous' : 'not-found', found.length ? '任务名称重复,请使用任务 ID' : `找不到任务:${ref}`);
13
+ return found[0];
14
+ }
15
+ export function sessionPlan(state, sessionId) { return Object.hasOwn(state.sessions, sessionId) ? state.plans[state.sessions[sessionId]] : undefined; }
16
+ export function ownerOf(plan, task) { return task.parentId ? plan.tasks[task.parentId].executionSessionId ?? ownerOf(plan, plan.tasks[task.parentId]) : plan.rootSessionId; }
17
+ export function currentTask(plan, sid) {
18
+ const focused = plan.active[sid];
19
+ return focused && plan.tasks[focused] ? plan.tasks[focused] : Object.values(plan.tasks).find(t => t.executionSessionId === sid && t.mode === 'delegate');
20
+ }
21
+ export function delegationDepth(plan, task) {
22
+ let depth = 0;
23
+ for (let sid = ownerOf(plan, task); sid !== plan.rootSessionId;) {
24
+ const parent = Object.values(plan.tasks).find(t => t.mode === 'delegate' && t.executionSessionId === sid);
25
+ if (!parent) break;
26
+ depth++; sid = ownerOf(plan, parent);
27
+ }
28
+ return depth;
29
+ }
30
+ function authorize(plan, sid, task) {
31
+ if (sid === plan.rootSessionId) return;
32
+ const bound = Object.values(plan.tasks).find(t => t.executionSessionId === sid && t.mode === 'delegate');
33
+ if (!bound || (task.id !== bound.id && !descendants(plan, bound.id).some(t => t.id === task.id))) fail('forbidden', '只能操作当前会话负责的任务及其下级');
34
+ }
35
+ function validateGraph(plan) {
36
+ const visiting = new Set(), visited = new Set();
37
+ 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); };
38
+ Object.keys(plan.tasks).forEach(visit);
39
+ }
40
+ function reopen(plan, task) {
41
+ for (let t = task; t; t = plan.tasks[t.parentId]) {
42
+ if (t.status === 'completed') { t.status = 'pending'; t.version++; t.attempt = null; }
43
+ }
44
+ }
45
+ 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); }
46
+
47
+ export class TaskService {
48
+ constructor(store, options = {}) { this.store = store; this.options = { maxDepth: 2, maxConcurrent: 2, maxTasks: 200, ...options }; this.listeners = new Set(); }
49
+ subscribe(listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
50
+ async change(operation) { const value = await this.store.transaction(operation); for (const listener of this.listeners) { try { listener(); } catch {} } return value; }
51
+ 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 }; }
52
+ scope(state, sid) { const plan = sessionPlan(state, sid); if (!plan) fail('no-plan', '当前会话尚未建立任务计划'); return plan; }
53
+ async create(sid, input) {
54
+ return this.change(state => {
55
+ if (typeof sid !== 'string' || !sid || ['__proto__', 'prototype', 'constructor'].includes(sid)) fail('invalid', '会话 ID 无效');
56
+ if (Object.hasOwn(state.sessions, sid)) fail('exists', '计划已存在,请通过增量操作调整,不能覆盖现有计划');
57
+ 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() };
58
+ state.plans[plan.id] = plan; state.sessions[sid] = plan.id;
59
+ this.insert(plan, sid, input.tasks, null); validateGraph(plan); stamp(plan, 'plan', null, '主会话模型生成计划'); return structuredClone(plan);
60
+ });
61
+ }
62
+ insert(plan, sid, inputs, defaultParent) {
63
+ if (!Array.isArray(inputs) || !inputs.length) fail('invalid', '至少提供一个待办事项');
64
+ if (Object.keys(plan.tasks).length + inputs.length > this.options.maxTasks) fail('limit', '计划已达到任务数量上限');
65
+ const aliases = new Map(), created = [];
66
+ for (const input of inputs) {
67
+ if (input.ref && aliases.has(input.ref)) fail('invalid', '新任务 ref 重复');
68
+ const id = `T-${String(++plan.seq).padStart(3, '0')}`;
69
+ if (input.ref) aliases.set(input.ref, id);
70
+ const complexity = input.complexity ?? 'low';
71
+ if (!['low', 'medium', 'high'].includes(complexity)) fail('invalid', '未知任务复杂度');
72
+ const mode = input.mode ?? (complexity !== 'low' && input.independent === true ? 'delegate' : 'inline');
73
+ if (!['inline', 'delegate'].includes(mode)) fail('invalid', '未知执行方式');
74
+ 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: [] };
75
+ plan.tasks[id] = task; created.push({ task, input });
76
+ }
77
+ for (const { task, input } of created) {
78
+ const resolve = ref => aliases.get(ref) ?? resolveTask(plan, ref).id;
79
+ if (input.parentId != null) task.parentId = resolve(input.parentId);
80
+ if (task.parentId) { const parent = plan.tasks[task.parentId]; authorize(plan, sid, parent); if (parent.status === 'cancelled') fail('cancelled', '不能向已取消任务增补'); }
81
+ else if (sid !== plan.rootSessionId) fail('forbidden', '子会话不能创建根任务');
82
+ if (input.dependsOn !== undefined && !Array.isArray(input.dependsOn)) fail('invalid', 'dependsOn 必须是任务 ID 数组');
83
+ task.dependsOn = [...new Set((input.dependsOn ?? []).map(resolve))];
84
+ }
85
+ validateGraph(plan); for (const { task } of created) if (task.parentId) reopen(plan, plan.tasks[task.parentId]); return created.map(x => structuredClone(x.task));
86
+ }
87
+ async add(sid, inputs, parentRef, expectedVersion) {
88
+ return this.change(state => { const p = this.scope(state, sid); if (expectedVersion != null && p.version !== expectedVersion) fail('stale', '计划已变更,请刷新后重试');
89
+ const parent = parentRef != null ? resolveTask(p, parentRef) : currentTask(p, sid);
90
+ if (parent) authorize(p, sid, parent);
91
+ const made = this.insert(p, sid, inputs, parent?.id ?? null); stamp(p, 'add', parent?.id ?? null, made.map(t => t.id).join(', ')); return made;
92
+ });
93
+ }
94
+ async update(sid, ref, patch, version) {
95
+ return this.change(state => { const p = this.scope(state, sid), t = resolveTask(p, ref); authorize(p, sid, t);
96
+ if (t.version !== version) fail('stale', '任务要求已变更,请刷新');
97
+ if (!patch || !Object.keys(patch).length || Object.keys(patch).some(k => !['title', 'instructions', 'criteria', 'complexity', 'independent', 'mode', 'dependsOn', 'parentId'].includes(k))) fail('invalid', '任务修改字段无效');
98
+ if (t.status === 'cancelled') fail('cancelled', '已取消任务不可修改');
99
+ for (const k of ['title', 'instructions', 'criteria']) if (patch[k] !== undefined) t[k] = text(patch[k], k, k === 'title' ? 240 : 16000);
100
+ if (patch.complexity !== undefined) { if (!['low', 'medium', 'high'].includes(patch.complexity)) fail('invalid', '未知任务复杂度'); t.complexity = patch.complexity; }
101
+ if (patch.independent !== undefined) { if (typeof patch.independent !== 'boolean') fail('invalid', 'independent 必须为布尔值'); t.independent = patch.independent; }
102
+ if (patch.mode !== undefined) { if (!['inline', 'delegate'].includes(patch.mode)) fail('invalid', '未知执行方式'); t.mode = patch.mode; }
103
+ if (patch.dependsOn !== undefined) { if (!Array.isArray(patch.dependsOn)) fail('invalid', '依赖必须是数组'); t.dependsOn = patch.dependsOn.map(r => resolveTask(p, r).id); }
104
+ if (patch.parentId !== undefined) {
105
+ if (patch.parentId === null) { if (sid !== p.rootSessionId) fail('forbidden', '只有主会话能移动为根任务'); t.parentId = null; }
106
+ else { const parent = resolveTask(p, patch.parentId); authorize(p, sid, parent); if (parent.status === 'cancelled') fail('cancelled', '不能移动到已取消任务下'); t.parentId = parent.id; }
107
+ }
108
+ 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]);
109
+ // Invalidate descendant executions that inherited the old requirements.
110
+ for (const child of descendants(p, t.id)) if (!terminal(child)) { child.version++; child.attempt = null; child.status = 'paused'; }
111
+ stamp(p, 'update', t.id, '要求更新,旧执行结果失效'); return structuredClone(t);
112
+ });
113
+ }
114
+ async cancel(sid, ref, version) {
115
+ return this.change(state => { const p = this.scope(state, sid), t = resolveTask(p, ref); authorize(p, sid, t); if (version !== t.version) fail('stale', '任务版本已变化');
116
+ 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() }); }
117
+ stamp(p, 'cancel', t.id, '保留任务与会话历史'); return structuredClone(t);
118
+ });
119
+ }
120
+ async start(sid, ref) {
121
+ return this.change(state => { const p = this.scope(state, sid), t = resolveTask(p, ref); authorize(p, sid, t);
122
+ if (!['pending', 'paused', 'blocked', 'failed'].includes(t.status)) fail('state', '任务当前不可启动');
123
+ if (!t.dependsOn.every(id => p.tasks[id]?.status === 'completed')) fail('dependency', '前置任务尚未完成');
124
+ 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', '请先启动负责此事项的父任务,不能将下级会话改挂到主会话');
125
+ // Resolve the limit synchronously so the model sees inline in start's result,
126
+ // instead of queueing a child that can never run while its parent waits.
127
+ if (t.mode === 'delegate' && delegationDepth(p, t) >= this.options.maxDepth) t.mode = 'inline';
128
+ if (t.mode === 'inline' && ownerOf(p, t) !== sid) fail('forbidden', '请在负责此任务的会话执行');
129
+ const ancestors = new Set(); for (let x = p.tasks[t.parentId]; x; x = p.tasks[x.parentId]) ancestors.add(x.id);
130
+ 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', '当前会话已有执行事项');
131
+ t.status = t.mode === 'delegate' ? 'queued' : 'running'; t.attempt = { id: randomUUID(), version: t.version, number: ++t.attempts };
132
+ if (t.mode === 'inline') { t.executionSessionId = sid; p.active[sid] = t.id; }
133
+ stamp(p, 'start', t.id, t.mode); return structuredClone(t);
134
+ });
135
+ }
136
+ async bind(planId, taskId, attemptId, childId) {
137
+ return this.change(state => { const p = state.plans[planId], t = p?.tasks[taskId]; if (!t || t.attempt?.id !== attemptId || t.status !== 'queued') fail('stale', '执行已过期');
138
+ t.status = 'running'; t.executionSessionId = childId; state.sessions[childId] = p.id; p.active[childId] = t.id; stamp(p, 'delegate', t.id, childId);
139
+ });
140
+ }
141
+ 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, '等待下级任务,释放并发名额'); }); }
142
+ 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, '继续本层工作'); }); }
143
+ async settle(sid, ref, attemptId, version, result, fromRuntime = false) {
144
+ return this.change(state => { const p = this.scope(state, sid), t = resolveTask(p, ref); authorize(p, sid, t);
145
+ if (t.version !== version || t.attempt?.id !== attemptId) fail('stale', '旧版本或旧执行结果不能完成当前任务');
146
+ if (t.executionSessionId !== sid) fail('forbidden', '只能由本次执行会话提交结果');
147
+ if (t.mode === 'delegate' && !fromRuntime) fail('final-report', '委派任务请返回最终结构化结果;行内子事项可通过工具完成');
148
+ if (t.status === 'completed' && t.report?.attemptId === attemptId) return structuredClone(t);
149
+ if (!['running', 'awaiting_children'].includes(t.status)) fail('state', '任务当前未在执行');
150
+ if (!['completed', 'failed', 'blocked'].includes(result.status)) fail('invalid', '无效结果状态');
151
+ if (result.status === 'completed' && children(p, t.id).some(c => !terminal(c))) fail('children', '下级任务尚未结束,完成本层剩余工作后再报告');
152
+ const report = { status: result.status, summary: text(result.summary, '完成摘要'), version, attemptId, at: new Date().toISOString() };
153
+ t.report = report; t.history.push(report); t.status = result.status;
154
+ 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]; }
155
+ 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 }); }
156
+ stamp(p, result.status, t.id, report.summary); return structuredClone(t);
157
+ });
158
+ }
159
+ async openView(sid, input) {
160
+ return this.change(state => { const p = this.scope(state, sid); if (!['browser', 'editor', 'terminal', 'plugin', 'orchestration'].includes(input.kind)) fail('invalid', '未知工具视图');
161
+ if (input.url) { const u = new URL(input.url); if (!['https:', 'http:'].includes(u.protocol) || u.username || u.password) fail('invalid', '浏览器地址必须为不含凭据的 HTTP(S) URL'); }
162
+ p.views[sid] = { kind: input.kind, title: String(input.title ?? input.kind).slice(0, 240), url: input.url ?? null, content: String(input.content ?? '').slice(0, 100000), open: true, taskId: currentTask(p, sid)?.id ?? null }; stamp(p, 'tool', p.views[sid].taskId, input.kind);
163
+ });
164
+ }
165
+ async closeView(sid) { return this.change(state => { const p = this.scope(state, sid); if (p.views[sid]) p.views[sid].open = false; }); }
166
+ 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; }); }
167
+ async reorder(sid, ref, direction, version) {
168
+ return this.change(state => { const p = this.scope(state, sid), t = resolveTask(p, ref); authorize(p, sid, t);
169
+ if (p.version !== version) fail('stale', '计划顺序已变化,请刷新');
170
+ if (![1, -1].includes(direction)) fail('invalid', 'direction 必须为 1 或 -1');
171
+ const all = Object.values(p.tasks), siblings = all.filter(x => x.parentId === t.parentId), target = siblings[siblings.indexOf(t) + direction];
172
+ if (!target) return;
173
+ const a = all.indexOf(t), b = all.indexOf(target); [all[a], all[b]] = [all[b], all[a]];
174
+ p.tasks = Object.fromEntries(all.map(x => [x.id, x])); stamp(p, 'reorder', t.id, direction < 0 ? '同级上移' : '同级下移');
175
+ });
176
+ }
177
+ 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, '宿主中断,保留计划;需明确继续执行'); } }); }
178
+ }
@@ -0,0 +1,8 @@
1
+ import z from '@deepseek-ai/schemastery';
2
+
3
+ // 宿主配置边界;业务层只接收解析后的配置值。
4
+ export const Config = z.object({
5
+ dataDir: z.string(), maxDepth: z.number().step(1).min(0).max(8).default(2),
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'),
8
+ });
@@ -0,0 +1,38 @@
1
+ import { join } from 'node:path';
2
+ import { homedir } from 'node:os';
3
+ import { FileStore } from '../storage/task-store.mjs';
4
+ import { TaskService } from '../domain/task-service.mjs';
5
+ import { TaskRuntime } from '../application/task-runtime.mjs';
6
+ import { createNoticeSender } from './notifications.mjs';
7
+ import { registerTools } from './tools.mjs';
8
+ import { registerSessionContext } from './session-context.mjs';
9
+ import { registerToolViews } from './tool-views.mjs';
10
+ import { registerRpc } from './rpc.mjs';
11
+ export { Config } from './config.mjs';
12
+ export const name = 'taskflow';
13
+ export const inject = ['tools', 'agents', 'sessions', 'systemPrompt', 'subagents'];
14
+
15
+ // 生命周期装配入口;状态、调度与宿主 API 适配各自独立。
16
+ export async function apply(ctx, config = {}) {
17
+ const dataDir = config.dataDir || join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'taskflow');
18
+ const store = await new FileStore(dataDir).init();
19
+ let runtime, timer;
20
+ ctx.effect(() => async () => { clearInterval(timer); await runtime?.dispose(); await store.close(); });
21
+ const service = new TaskService(store, config); await service.recover();
22
+ const log = error => ctx.logger?.warn?.(`taskflow: ${error.message ?? error}`);
23
+ runtime = new TaskRuntime(service, {
24
+ agent: sid => ctx.agents.get(sid), log,
25
+ // DSH 0.2.1-rc.3 accepts a nested request; 0.2.2-rc.2+ uses top-level fields.
26
+ // Supply both shapes in one call so neither host needs a retry or a second activation.
27
+ start: request => ctx.subagents.startActivation({ provider: config.provider || 'spawn', ...request, request, delivery: 'caller' }),
28
+ notify: createNoticeSender(ctx),
29
+ });
30
+ ctx.provide('taskflow', { service, runtime });
31
+ registerTools(ctx, service, runtime);
32
+ registerSessionContext(ctx, service, config);
33
+ registerToolViews(ctx, service, log);
34
+ registerRpc(ctx, service);
35
+ ctx.on('agent/created', () => { runtime.kick(); return undefined; }, { global: true });
36
+ timer = setInterval(() => runtime.kick(), 3000); timer.unref?.();
37
+ runtime.kick();
38
+ }
@@ -0,0 +1,19 @@
1
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
2
+
3
+ // 确定消息 ID 与持久 outbox 配合,flush 成功后才确认送达。
4
+ export function createNoticeSender(ctx) {
5
+ return async notice => {
6
+ const agent = ctx.agents.get(notice.targetSessionId); if (!agent) return false;
7
+ const messageId = `taskflow-${notice.id}`;
8
+ const hasMessage = value => value && typeof value === 'object' && (value.id === messageId || Object.values(value).some(v => Array.isArray(v) ? v.some(hasMessage) : v && typeof v === 'object' && hasMessage(v)));
9
+ const seen = agent.session.snapshotEvents().some(hasMessage) || [...agent.inbox.nextStep, ...agent.inbox.nextTurn].some(m => m.id === messageId);
10
+ if (!seen) {
11
+ const message = createUserMessage({ content: [{ type: 'text', text: `任务 ${notice.taskId} 已完成并自动勾选。\n${notice.report.summary}\n无需再次核对或批准;继续当前父任务剩余工作。` }], source: { kind: 'taskflow', form: 'notice', summary: `${notice.taskId} 已完成` } });
12
+ agent.steer({ ...message, id: messageId });
13
+ }
14
+ // Seeing a message in RAM does not prove that an earlier failed flush succeeded.
15
+ if (!await ctx.sessions.flush(agent.session)) throw new Error('完成通知尚未持久化,保留待重送');
16
+ return true;
17
+ };
18
+ }
19
+
@@ -0,0 +1,8 @@
1
+ // 增量计划和直接父通知约定,与持久状态注入一起维护。
2
+ export const PLANNING_PROMPT = `你是持久任务计划的负责人。对需要多个步骤、工具操作或独立执行的请求,先根据实际难度通过 taskflow_plan 规划具体待办;短问答无需计划。已有计划时只做增量变更,不因新一轮对话重建、替换或清空计划,不用 todo_write 充当任务账本。
3
+ 每条事项选择 complexity(low/medium/high)和 independent。简单或共享上下文的事项用 inline,复杂且独立的事项用 delegate。用 taskflow_start 启动;行内执行结束用 taskflow_complete 保存实际结果;委派会话返回最终结构化结果即可。先处理依赖;下层完成后,本层仍需完成自己的剩余工作。不要增加父会话审查或批准步骤。
4
+ 除非缺少必要信息或用户只要求规划,生成清单后按依赖持续执行,不要仅建立计划就停止。先启动负责的父任务,再执行其下级;达到会话深度上限时,以 taskflow_start 返回的 inline 方式在当前会话完成。
5
+ 子会话可通过 taskflow_add 再拆分,受最大深度和全树并发约束。拆分后启动下级,用 taskflow_wait 等待结果(释放并发名额),再继续本层工作。不要使用原生 subagent/workflow 绕过此计划。
6
+ 增补默认挂在当前正在执行或选中的任务下;主会话可明确用 ID 或完整名称指定 parentId。出现重复名称或找不到父任务时应澄清,不得自动改挂其他节点。用户要求修改或取消时调用对应工具,保留其他任务及历史。
7
+ 工具视图默认关闭。需要操作网页、文件、命令或插件时,使用实际宿主工具;可用 taskflow_open_view 展示本次实际工具地址或输出。不要把预览当作浏览器执行器,不得伪造执行或完成结果。`;
8
+
@@ -0,0 +1,22 @@
1
+ // 所有者专用界面 RPC,与模型会话内的权限校验分开。
2
+ export function registerRpc(ctx, service) {
3
+ ctx.inject(['connection'], scope => {
4
+ scope.effect(() => scope.connection.rpc.intercept('/api', method => method === 'taskflow/view' || method === 'taskflow/action', async (method, payload, signal, peer) => {
5
+ if (!peer || (peer !== scope.connection.browserPeer && peer.principal?.kind !== 'owner')) return { ok: false, error: { code: 'forbidden', message: '仅宿主所有者可访问任务计划', details: {} } };
6
+ try {
7
+ if (!payload || typeof payload.sessionId !== 'string' || payload.sessionId.length > 200) throw new Error('缺少有效会话 ID');
8
+ const sid = payload.sessionId;
9
+ if (method === 'taskflow/view') return { ok: true, value: service.view(sid) };
10
+ let value;
11
+ if (payload.action === 'close-view') value = await service.closeView(sid);
12
+ else if (payload.action === 'focus') value = await service.focus(sid, payload.taskId);
13
+ else if (payload.action === 'start') value = await service.start(sid, payload.taskId);
14
+ else if (payload.action === 'cancel') value = await service.cancel(sid, payload.taskId, payload.version);
15
+ else if (payload.action === 'update') value = await service.update(sid, payload.taskId, payload.patch, payload.version);
16
+ else if (payload.action === 'reorder') value = await service.reorder(sid, payload.taskId, payload.direction, payload.expectedVersion);
17
+ else throw new Error('不支持的操作');
18
+ return { ok: true, value: value ?? { ok: true } };
19
+ } catch (error) { return { ok: false, error: { code: error.code ?? 'invalid', message: error.message, details: {} } }; }
20
+ }));
21
+ });
22
+ }
@@ -0,0 +1,17 @@
1
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
2
+ import { PLANNING_PROMPT } from './prompts.mjs';
3
+
4
+ export function registerSessionContext(ctx, service, config) {
5
+ ctx.systemPrompt.section({ name: 'taskflow', order: 155, text: config.autoPlan === false ? PLANNING_PROMPT.replace('对需要多个步骤、工具操作或独立执行的请求,先根据实际难度通过 taskflow_plan 规划具体待办;短问答无需计划。', '仅当用户明确要求任务计划时调用 taskflow_plan。') : PLANNING_PROMPT, interpolate: false });
6
+ ctx.on('agent/pre-step', async ({ agent }, next) => {
7
+ const decision = await next(); if (decision.kind === 'reject') return decision;
8
+ const view = service.view(agent.session.id);
9
+ if (!view.plan && config.autoPlan === false) return decision;
10
+ const content = view.plan ? JSON.stringify({ title: view.plan.title, planVersion: view.plan.version, currentTaskId: view.currentTaskId, tasks: Object.values(view.plan.tasks).map(t => ({ id: t.id, title: t.title, parentId: t.parentId, mode: t.mode, status: t.status, version: t.version, attempt: t.attempt, dependsOn: t.dependsOn })) }) : '本会话尚无持久计划。复杂多步骤任务先调用 taskflow_plan;短问答直接回答。';
11
+ return { ...decision, messages: [...decision.messages, createUserMessage({ content: [{ type: 'text', text: `Taskflow 当前持久状态(不需要重新规划):\n${content}` }], source: { kind: 'taskflow', form: 'notice', summary: '持久任务状态' } })] };
12
+ }, { global: true });
13
+ ctx.tools.guard(exec => {
14
+ const sid = exec.agent?.session.id; if (!sid || !service.view(sid).plan) return;
15
+ if (['subagent', 'subagent_fork', 'workflow'].includes(exec.name)) return '请用 taskflow_add / taskflow_start 委派,保留层级与并发限制';
16
+ });
17
+ }
@@ -0,0 +1,14 @@
1
+ // 展示真实工具输出;执行仍属于原宿主工具。
2
+ export function registerToolViews(ctx, service, log) {
3
+ ctx.on('tools/execute', async (exec, next) => {
4
+ const sid = exec.agent?.session.id;
5
+ if (sid && service.view(sid).plan && !exec.name.startsWith('taskflow_') && !['structured_output', 'todo_write', 'ask_user'].includes(exec.name)) {
6
+ const kind = /browser|navigate|web_page/.test(exec.name) ? 'browser' : /bash|pwsh|terminal|command/.test(exec.name) ? 'terminal' : /^(read|write|edit|str_replace)/.test(exec.name) ? 'editor' : 'plugin';
7
+ if (kind) await service.openView(sid, { kind, title: exec.name, ...(typeof exec.args?.url === 'string' ? { url: exec.args.url } : {}), content: '工具正在执行…' }).catch(log);
8
+ const result = await next();
9
+ if (kind) { const output = (result.content ?? []).filter(b => b.type === 'text').map(b => b.text).join('\n'); if (output) await service.openView(sid, { ...service.view(sid).tool, content: output }).catch(log); }
10
+ return result;
11
+ }
12
+ return next();
13
+ }, { global: true });
14
+ }
@@ -0,0 +1,28 @@
1
+ import { defineTool } from '@deepseek-ai/dsh-tools';
2
+
3
+ const string = description => ({ type: 'string', description });
4
+ const json = description => ({ type: 'json', description });
5
+ const number = description => ({ type: 'number', description });
6
+ const required = schema => ({ ...schema, required: true });
7
+ const jsonOutput = { schema: { type: 'json' }, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] };
8
+ const taskHelp = '任务数组。每项 title/instructions/criteria、complexity:low|medium|high、independent:boolean、mode:inline|delegate;可选 ref 为本批次临时引用,parentId 和 dependsOn 可引用该 ref 或现有任务 ID。';
9
+
10
+
11
+ /** 把模型工具映射到领域服务;不在此保存任务状态。 */
12
+ export function registerTools(ctx, service, runtime) {
13
+ const register = (toolName, description, parameters, execute) => ctx.tools.register(defineTool({
14
+ name: toolName, description, parameters, output: jsonOutput,
15
+ async execute(args, exec) { if (!exec.agent) throw new Error('Taskflow 需要会话上下文'); if (exec.signal.aborted) throw exec.signal.reason; return (await execute(args, exec.agent.session.id, exec)) ?? { ok: true }; },
16
+ presentCall: () => ({ card: 'generic', title: description.split('。')[0] }), presentResult: () => ({ card: 'generic' }),
17
+ }));
18
+ register('taskflow_plan', '规划并保存当前会话的持久层级待办。已有计划不能覆盖;子会话请用 taskflow_add。', { title: required(string('计划标题')), goal: required(string('用户目标与约束')), tasks: required(json(taskHelp)) }, (a, sid) => service.create(sid, a));
19
+ register('taskflow_status', '读取整个持久计划、当前任务、版本和工具视图。不会重置计划。', {}, (_a, sid) => service.view(sid));
20
+ register('taskflow_add', '在当前任务或明确指定父任务下增补待办。目标歧义会拒绝,不改变其他事项。', { tasks: required(json(taskHelp)), parentId: string('可选父任务 ID 或完整名称;不填则为当前任务'), expectedVersion: number('可选计划版本,防止并发增补冲突') }, (a, sid) => service.add(sid, a.tasks, a.parentId, a.expectedVersion));
21
+ register('taskflow_update', '增量修改任务要求。递增版本,中止旧执行;不会重写整棵树。', { taskId: required(string('任务 ID')), version: required(number('当前任务版本')), patch: required(json('仅允许 title/instructions/criteria/complexity/independent/mode/parentId/dependsOn')) }, (a, sid) => service.update(sid, a.taskId, a.patch, a.version));
22
+ register('taskflow_reorder', '调整同级事项顺序,保留任务 ID、执行状态和历史。', { taskId: required(string('任务 ID')), direction: required(number('-1 上移,1 下移')), expectedVersion: required(number('当前计划版本')) }, (a, sid) => service.reorder(sid, a.taskId, a.direction, a.expectedVersion));
23
+ register('taskflow_cancel', '取消任务及其下级,保留历史会话与已交付记录。取消不等于完成。', { taskId: required(string('任务 ID')), version: required(number('当前任务版本')) }, (a, sid) => service.cancel(sid, a.taskId, a.version));
24
+ register('taskflow_start', '启动事项。inline 留在负责会话,delegate 排队并自动创建子会话;可递归。', { taskId: required(string('待启动的任务 ID')) }, (a, sid) => service.start(sid, a.taskId));
25
+ register('taskflow_wait', '等待当前任务下级的执行结果,释放本层并发名额;返回后继续本层工作。', { taskId: required(string('本会话正在执行的任务 ID')) }, (a, sid, exec) => runtime.wait(sid, a.taskId, exec.signal));
26
+ register('taskflow_complete', '保存行内事项的真实执行结果并立即勾选、通知直接父任务。委派任务通过最终结构化输出完成。', { taskId: required(string('任务 ID')), version: required(number('执行要求版本')), attemptId: required(string('taskflow_start 返回的 attempt.id')), summary: required(string('实际完成结果、证据或阻塞原因')), status: string('completed(默认)/blocked/failed') }, (a, sid) => service.settle(sid, a.taskId, a.attemptId, a.version, { status: a.status ?? 'completed', summary: a.summary }));
27
+ register('taskflow_open_view', '按需在会话左侧显示实际工具页面或输出;该工具本身不执行浏览器、命令或文件操作。', { kind: required(string('browser/editor/terminal/plugin/orchestration')), title: string('当前工具标题'), url: string('实际 HTTP(S) 页面地址,可选'), content: string('实际工具输出或文件内容,可选') }, (a, sid) => service.openView(sid, a));
28
+ }