@alpacachen/dsh-kanban 1.11.3 → 1.12.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/README.md +78 -49
- package/README.zh.md +77 -48
- package/cordis.patch.yml +2 -0
- package/docs/guide.md +1 -1
- package/docs/guide.zh.md +1 -1
- package/docs/readme/workflow-en-mobile.svg +28 -0
- package/docs/readme/workflow-en.svg +28 -0
- package/docs/readme/workflow-zh-mobile.svg +28 -0
- package/docs/readme/workflow-zh.svg +28 -0
- package/docs/testing-images.md +12 -0
- package/docs/workflow-guide.en.md +87 -0
- package/docs/workflow-guide.md +87 -0
- package/docs/workflow-model.schema.sql +303 -0
- package/docs/workflow-validation.md +82 -0
- package/lib/client.js +1024 -17
- package/package.json +24 -8
- package/workflow/dsh-adapter.js +206 -0
- package/workflow/index.js +334 -0
- package/workflow/locale/en.json +6 -0
- package/workflow/locale/zh.json +6 -0
- package/workflow/management-tools.js +160 -0
- package/workflow/recovery.js +75 -0
- package/workflow/review-api.js +296 -0
- package/workflow/runner.js +347 -0
- package/workflow/stage-trace.js +65 -0
- package/workflow/store.js +900 -0
- package/workflow/task-files.js +133 -0
- package/docs/readme/cover-en-mobile.png +0 -0
- package/docs/readme/cover-en.png +0 -0
- package/docs/readme/cover-zh-mobile.png +0 -0
- package/docs/readme/cover-zh.png +0 -0
package/package.json
CHANGED
|
@@ -1,18 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alpacachen/dsh-kanban",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "1.12.1",
|
|
4
|
+
"description": "Human-led Kanban and AI-run workflows for DeepSeek Harness, with native execution, human review and task artifacts.",
|
|
5
5
|
"type": "module",
|
|
6
|
+
"engines": {
|
|
7
|
+
"dsh": "0.2.2-rc.3"
|
|
8
|
+
},
|
|
6
9
|
"main": "index.js",
|
|
7
10
|
"exports": {
|
|
8
11
|
".": "./index.js",
|
|
9
12
|
"./client": "./lib/client.js",
|
|
13
|
+
"./workflow": "./workflow/index.js",
|
|
14
|
+
"./workflow/locale/*.json": "./workflow/locale/*.json",
|
|
15
|
+
"./workflow/icon": "./image.png",
|
|
10
16
|
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
11
17
|
"./package.json": "./package.json"
|
|
12
18
|
},
|
|
13
19
|
"files": [
|
|
14
20
|
"index.js",
|
|
15
21
|
"search.js",
|
|
22
|
+
"workflow",
|
|
23
|
+
"docs/workflow-model.schema.sql",
|
|
24
|
+
"docs/workflow-validation.md",
|
|
25
|
+
"docs/workflow-guide.md",
|
|
26
|
+
"docs/workflow-guide.en.md",
|
|
16
27
|
"lib/client.js",
|
|
17
28
|
"cordis.patch.yml",
|
|
18
29
|
"README.md",
|
|
@@ -22,7 +33,8 @@
|
|
|
22
33
|
"docs/testing-images.md",
|
|
23
34
|
"docs/guide.md",
|
|
24
35
|
"docs/guide.zh.md",
|
|
25
|
-
"docs/readme
|
|
36
|
+
"docs/readme/board-*.png",
|
|
37
|
+
"docs/readme/*.svg",
|
|
26
38
|
"LICENSE"
|
|
27
39
|
],
|
|
28
40
|
"scripts": {
|
|
@@ -46,6 +58,7 @@
|
|
|
46
58
|
"@radix-ui/react-separator": "^1.1.2",
|
|
47
59
|
"@radix-ui/react-slot": "^1.1.2",
|
|
48
60
|
"@radix-ui/react-tooltip": "^1.1.8",
|
|
61
|
+
"@xyflow/react": "^12.12.1",
|
|
49
62
|
"clsx": "^2.1.1",
|
|
50
63
|
"lucide-react": "^1.34.0"
|
|
51
64
|
},
|
|
@@ -59,8 +72,10 @@
|
|
|
59
72
|
"@deepseek-ai/dsh-api-workspace-controller": "0.2.2-rc.3",
|
|
60
73
|
"@deepseek-ai/dsh-client-locale": "0.2.2-rc.3",
|
|
61
74
|
"@deepseek-ai/dsh-client-store": "0.2.2-rc.3",
|
|
75
|
+
"@deepseek-ai/dsh-client-ui-chat": "0.2.2-rc.3",
|
|
62
76
|
"@deepseek-ai/dsh-client-ui-conversation": "0.2.2-rc.3",
|
|
63
77
|
"@deepseek-ai/dsh-client-ui-layout": "0.2.2-rc.3",
|
|
78
|
+
"@deepseek-ai/dsh-client-ui-model-selection": "0.2.2-rc.3",
|
|
64
79
|
"@deepseek-ai/dsh-client-ui-primitives": "0.2.2-rc.3",
|
|
65
80
|
"@deepseek-ai/dsh-client-ui-renderer": "0.2.2-rc.3",
|
|
66
81
|
"@deepseek-ai/dsh-client-ui-session": "0.2.2-rc.3",
|
|
@@ -97,7 +112,10 @@
|
|
|
97
112
|
"dsh",
|
|
98
113
|
"dsh-plugin",
|
|
99
114
|
"kanban",
|
|
100
|
-
"plugin"
|
|
115
|
+
"plugin",
|
|
116
|
+
"workflow",
|
|
117
|
+
"ai-agent",
|
|
118
|
+
"human-in-the-loop"
|
|
101
119
|
],
|
|
102
120
|
"dsh": {
|
|
103
121
|
"bundle": {
|
|
@@ -115,7 +133,8 @@
|
|
|
115
133
|
"@deepseek-ai/dsh-client-ui-primitives",
|
|
116
134
|
"@deepseek-ai/dsh-client-ui-renderer",
|
|
117
135
|
"@deepseek-ai/dsh-client-ui-session",
|
|
118
|
-
"@deepseek-ai/dsh-client-ui-workspace"
|
|
136
|
+
"@deepseek-ai/dsh-client-ui-workspace",
|
|
137
|
+
"@deepseek-ai/dsh-client-store"
|
|
119
138
|
]
|
|
120
139
|
},
|
|
121
140
|
"compatibility": {
|
|
@@ -128,8 +147,5 @@
|
|
|
128
147
|
"desktop"
|
|
129
148
|
]
|
|
130
149
|
}
|
|
131
|
-
},
|
|
132
|
-
"engines": {
|
|
133
|
-
"dsh": "0.2.2-rc.3"
|
|
134
150
|
}
|
|
135
151
|
}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
export const NATIVE_POLICY = 'dsh-native/v1'
|
|
4
|
+
const failure = (code, message) => Object.assign(new Error(message), { code })
|
|
5
|
+
const textInput = value => typeof value === 'string' && value.trim().length > 0
|
|
6
|
+
|
|
7
|
+
export class DshExecutionError extends Error {
|
|
8
|
+
constructor(code, message, evidence, cause) {
|
|
9
|
+
super(message, { cause })
|
|
10
|
+
this.name = 'DshExecutionError'
|
|
11
|
+
this.code = code
|
|
12
|
+
this.evidence = { ...evidence, completed: false }
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// DSH owns tools, retries, compaction and authorization. Verify the stage receipt
|
|
17
|
+
// and terminal report without imposing a second tool-dispatch policy.
|
|
18
|
+
function resultFromLog(header, events, request) {
|
|
19
|
+
const refuse = () => { throw failure('WORKFLOW_LOG_UNKNOWN', 'The stage has no verified completed result.') }
|
|
20
|
+
if (header.id !== request.sessionId || (request.cwd && header.cwd !== request.cwd)
|
|
21
|
+
|| !Array.isArray(events) || events.some((event, i) => event.seq !== i)) refuse()
|
|
22
|
+
const inputs = events.filter(event => event.type === 'user/message' && event.data.source?.rpcId === request.requestId)
|
|
23
|
+
if (inputs.length !== 1) refuse()
|
|
24
|
+
const input = inputs[0]
|
|
25
|
+
if ((request.messageId && input.data.id !== request.messageId)
|
|
26
|
+
|| input.data.content?.length !== 1 || input.data.content[0].type !== 'text'
|
|
27
|
+
|| (request.prompt !== undefined && input.data.content[0].text !== request.prompt)) refuse()
|
|
28
|
+
const start = events.findLast(event => event.type === 'turn/start' && event.seq < input.seq)
|
|
29
|
+
const end = events.find(event => event.type === 'turn/end' && event.data.turn === start?.data.turn && event.seq > input.seq)
|
|
30
|
+
if (!start || !end) refuse()
|
|
31
|
+
const reason = end.data.reason
|
|
32
|
+
if (reason?.kind === 'error') throw failure(reason.error?.code === 'TRANSPORT' ? 'WORKFLOW_NETWORK_FAILED' : 'WORKFLOW_MODEL_FAILED', 'Native model execution failed.')
|
|
33
|
+
if (reason?.kind === 'interrupted') throw failure('WORKFLOW_MODEL_INTERRUPTED', 'Native model execution was interrupted.')
|
|
34
|
+
if (reason?.kind === 'max-tokens') throw failure('WORKFLOW_MODEL_INCOMPLETE', 'Native model output is incomplete.')
|
|
35
|
+
if (reason?.kind !== 'completed') refuse()
|
|
36
|
+
const reply = events.findLast(event => event.type === 'assistant/message' && event.data.turn === start.data.turn
|
|
37
|
+
&& event.seq > input.seq && event.seq < end.seq)
|
|
38
|
+
if (!reply || reply.data.interrupted || reply.data.message?.content?.some(block => block.type === 'tool-call')) refuse()
|
|
39
|
+
const text = reply.data.message.content.filter(block => block.type === 'text').map(block => block.text).join('\n')
|
|
40
|
+
if (!textInput(text)) refuse()
|
|
41
|
+
return { text, sessionId: header.id, messageId: input.data.id, turnNumber: start.data.turn,
|
|
42
|
+
evidence: { policy: NATIVE_POLICY, userSeq: input.seq, assistantSeq: reply.seq, endSeq: end.seq,
|
|
43
|
+
endReason: 'completed', toolInvocationCount: events.filter(event => event.type === 'tool/call' && event.seq > input.seq && event.seq < end.seq).length,
|
|
44
|
+
outputSha256: createHash('sha256').update(text).digest('hex') } }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function readPersistedSession(persistence, sessionId, signal) {
|
|
48
|
+
const handle = await persistence.open(sessionId, 'read', { signal })
|
|
49
|
+
try { return { header: handle.header, events: (await handle.read(0, undefined, { signal })).events } }
|
|
50
|
+
finally { await handle.close() }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Reconcile under native Session ownership, without dispatching or cancelling later chat turns. */
|
|
54
|
+
export async function withStoppedNativeExecution(ctx, attempt, commit, { confirmedStopped = false } = {}) {
|
|
55
|
+
const agents = ctx.get('agents'), sessions = ctx.get('sessions'), persistence = ctx.get('sessionPersistence'), jobs = ctx.get('jobs')
|
|
56
|
+
const busy = () => { throw failure('WF_RECOVERY_RUNNING', '执行会话或关联作业仍在工作,请先停止该会话,再重新核对任务。') }
|
|
57
|
+
const assertNoJobs = () => {
|
|
58
|
+
if (jobs.list(attempt.sessionId).some(job => job.owner === attempt.sessionId && ['running', 'stopping'].includes(job.status))) busy()
|
|
59
|
+
}
|
|
60
|
+
const settle = async (handle, ownership, signal) => {
|
|
61
|
+
signal?.throwIfAborted(); assertNoJobs()
|
|
62
|
+
const { events } = await handle.read(0, undefined, { signal })
|
|
63
|
+
if (handle.header.id !== attempt.sessionId || attempt.executorSnapshot.cwd && handle.header.cwd !== attempt.executorSnapshot.cwd
|
|
64
|
+
|| !Array.isArray(events) || events.some((event, index) => event.seq !== index)) throw failure('WF_RECOVERY_UNCONFIRMED', '执行会话记录不完整或与任务不匹配,未释放执行位置。')
|
|
65
|
+
const inputs = events.filter(event => event.type === 'user/message' && event.data.source?.rpcId === attempt.requestId)
|
|
66
|
+
const input = inputs[0]
|
|
67
|
+
const start = input && events.findLast(event => event.type === 'turn/start' && event.seq < input.seq)
|
|
68
|
+
if (inputs.length > 1 || input && (!start || attempt.messageId && input.data.id !== attempt.messageId
|
|
69
|
+
|| attempt.turnNumber != null && start.data.turn !== attempt.turnNumber
|
|
70
|
+
|| input.data.content?.length !== 1 || input.data.content[0].type !== 'text' || input.data.content[0].text !== attempt.prompt)
|
|
71
|
+
|| !input && events.some(event => event.type === 'user/message')) throw failure('WF_RECOVERY_UNCONFIRMED', '无法关联这次阶段的原始输入,未释放执行位置。')
|
|
72
|
+
const end = start && events.find(event => event.type === 'turn/end' && event.seq > input.seq && event.data.turn === start.data.turn)
|
|
73
|
+
// A cold Session lock cannot prove that commands survived neither SIGKILL nor a crash.
|
|
74
|
+
if (ownership === 'exclusive-session' && (attempt.state === 'unknown' || input && !end) && !confirmedStopped) {
|
|
75
|
+
throw failure('WF_RECOVERY_CONFIRM_REQUIRED', '原 DSH 已退出,但旧命令可能仍在运行。请先核对并确认旧操作已停止,再恢复或结束任务。')
|
|
76
|
+
}
|
|
77
|
+
signal?.throwIfAborted(); assertNoJobs()
|
|
78
|
+
return commit({ kind: 'dsh-native-stop', attemptId: attempt.id, sessionId: attempt.sessionId, requestId: attempt.requestId,
|
|
79
|
+
messageId: input?.data.id ?? attempt.messageId ?? null, turnNumber: start?.data.turn ?? attempt.turnNumber ?? null, userSeq: input?.seq ?? null, endSeq: end?.seq ?? null,
|
|
80
|
+
endReason: end?.data.reason?.kind ?? 'owner_released', ownership, operatorConfirmedStopped: confirmedStopped, logLastSeq: events.at(-1)?.seq ?? -1, quiescent: true, ownedJobCount: 0 })
|
|
81
|
+
}
|
|
82
|
+
const agent = agents.get(attempt.sessionId)
|
|
83
|
+
if (agent) {
|
|
84
|
+
if (agent.phase.kind !== 'idle') busy()
|
|
85
|
+
return agent.runMaintenance(async signal => {
|
|
86
|
+
assertNoJobs()
|
|
87
|
+
if (!await sessions.flush(agent.session)) throw failure('WF_RECOVERY_UNCONFIRMED', '执行会话暂时无法保存,请稍后重新核对。')
|
|
88
|
+
const handle = await persistence.open(attempt.sessionId, 'read', { signal })
|
|
89
|
+
try { return await settle(handle, 'live-idle', signal) } finally { await handle.close() }
|
|
90
|
+
})
|
|
91
|
+
}
|
|
92
|
+
let handle
|
|
93
|
+
if (!await persistence.stat(attempt.sessionId) && attempt.messageId == null && attempt.turnNumber == null) {
|
|
94
|
+
if (agents.get(attempt.sessionId)) busy()
|
|
95
|
+
assertNoJobs()
|
|
96
|
+
return commit({ kind: 'dsh-native-stop', attemptId: attempt.id, sessionId: attempt.sessionId, requestId: attempt.requestId,
|
|
97
|
+
messageId: null, turnNumber: null, userSeq: null, endSeq: null, endReason: 'not_dispatched', ownership: 'session-absent',
|
|
98
|
+
logLastSeq: -1, quiescent: true, ownedJobCount: 0 })
|
|
99
|
+
}
|
|
100
|
+
try { handle = await persistence.open(attempt.sessionId, 'write') }
|
|
101
|
+
catch { throw failure('WF_RECOVERY_UNCONFIRMED', '暂时无法取得原执行会话的独占所有权,请稍后重新核对。') }
|
|
102
|
+
try {
|
|
103
|
+
if (agents.get(attempt.sessionId)) busy()
|
|
104
|
+
return await settle(handle, 'exclusive-session')
|
|
105
|
+
} finally { await handle.close() }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function createDshExecutor(ownerCtx, { modelSelection, installModelSelection } = {}) {
|
|
109
|
+
const required = (name, methods) => {
|
|
110
|
+
const service = ownerCtx.get(name)
|
|
111
|
+
if (!service || methods.some(method => typeof service[method] !== 'function')) {
|
|
112
|
+
throw failure('WORKFLOW_CONTRACT_UNAVAILABLE', `Required DSH capability is unavailable: ${name}`)
|
|
113
|
+
}
|
|
114
|
+
return service
|
|
115
|
+
}
|
|
116
|
+
const agents = required('agents', ['create', 'get', 'withoutInitiator'])
|
|
117
|
+
const sessions = required('sessions', ['get', 'flush'])
|
|
118
|
+
const persistence = required('sessionPersistence', ['stat', 'open'])
|
|
119
|
+
const presets = required('agentPresets', ['resolve', 'mount'])
|
|
120
|
+
const jobs = required('jobs', ['list'])
|
|
121
|
+
const active = new Map(), submitted = new Set()
|
|
122
|
+
let closed = false
|
|
123
|
+
const runningJobs = sessionId => jobs.list(sessionId).filter(job => job.owner === sessionId && ['running', 'stopping'].includes(job.status))
|
|
124
|
+
const readRaw = (sessionId, signal) => readPersistedSession(persistence, sessionId, signal)
|
|
125
|
+
const cancel = attemptId => {
|
|
126
|
+
const record = active.get(attemptId)
|
|
127
|
+
if (!record) return { requested: false }
|
|
128
|
+
record.cancelled = true
|
|
129
|
+
record.abort.abort()
|
|
130
|
+
record.handle?.agent.cancel({ kind: 'user' }, { keepInbox: false })
|
|
131
|
+
return { requested: true }
|
|
132
|
+
}
|
|
133
|
+
async function run({ attemptId, sessionId, requestId, prompt, cwd, modelSelection: taskModelSelection, onBound, onObserved, signal }) {
|
|
134
|
+
if (![attemptId, sessionId, requestId, prompt, cwd].every(textInput)) throw new TypeError('Stage identities, prompt and working directory are required')
|
|
135
|
+
const evidence = { kind: 'dsh-session-log', policy: NATIVE_POLICY, attemptId, sessionId, requestId,
|
|
136
|
+
messageId: null, turnNumber: null, completed: false, flushConfirmed: false, quiescent: false, ownedJobCount: 0, toolInvocationCount: 0 }
|
|
137
|
+
if (closed || submitted.has(attemptId) || submitted.has(sessionId)) throw new DshExecutionError('WORKFLOW_REUSE_FORBIDDEN', 'Stage execution already submitted or executor closed', evidence)
|
|
138
|
+
submitted.add(attemptId); submitted.add(sessionId)
|
|
139
|
+
const record = { abort: new AbortController(), cancelled: false, handle: null }
|
|
140
|
+
record.done = new Promise(resolve => { record.finish = resolve })
|
|
141
|
+
active.set(attemptId, record)
|
|
142
|
+
const abort = () => cancel(attemptId)
|
|
143
|
+
signal?.addEventListener('abort', abort, { once: true })
|
|
144
|
+
if (signal?.aborted) abort()
|
|
145
|
+
let issue, result, created = false
|
|
146
|
+
const message = { id: randomUUID(), role: 'user', content: [{ type: 'text', text: prompt }], source: { kind: 'user', rpcId: requestId } }
|
|
147
|
+
evidence.messageId = message.id
|
|
148
|
+
try {
|
|
149
|
+
record.abort.signal.throwIfAborted()
|
|
150
|
+
if (agents.get(sessionId) || sessions.get(sessionId) || await persistence.stat(sessionId)) throw failure('WORKFLOW_REUSE_FORBIDDEN', 'Existing session cannot be dispatched again')
|
|
151
|
+
const preset = await presets.resolve()
|
|
152
|
+
const selection = structuredClone(taskModelSelection ?? modelSelection ?? required('agentDefaultModel', ['currentSelection']).currentSelection())
|
|
153
|
+
record.handle = await agents.withoutInitiator(() => agents.create({ sessionId, meta: { cwd, agentPreset: preset.id },
|
|
154
|
+
agentOptions: selection, signal: record.abort.signal,
|
|
155
|
+
setup: async agentCtx => {
|
|
156
|
+
installModelSelection?.(agentCtx)
|
|
157
|
+
await presets.mount(agentCtx, preset.id)
|
|
158
|
+
} }))
|
|
159
|
+
created = true
|
|
160
|
+
const agent = record.handle.agent
|
|
161
|
+
if (!await sessions.flush(agent.session)) throw failure('WORKFLOW_FLUSH_UNAVAILABLE', 'Session persistence is unavailable')
|
|
162
|
+
await onBound?.({ attemptId, sessionId, requestId, messageId: message.id })
|
|
163
|
+
const remove = agent.ctx.on('session/event', (session, event) => {
|
|
164
|
+
if (session !== agent.session || event.type !== 'turn/start') return
|
|
165
|
+
evidence.turnNumber = event.data.turn
|
|
166
|
+
})
|
|
167
|
+
try {
|
|
168
|
+
record.abort.signal.throwIfAborted()
|
|
169
|
+
agent.followup(message)
|
|
170
|
+
await agent.whenIdle()
|
|
171
|
+
} finally { remove?.() }
|
|
172
|
+
if (record.cancelled) throw failure('WORKFLOW_CANCELLED', 'Stage cancelled')
|
|
173
|
+
await onObserved?.({ attemptId, sessionId, requestId, messageId: message.id, turnNumber: evidence.turnNumber })
|
|
174
|
+
evidence.flushConfirmed = await sessions.flush(agent.session)
|
|
175
|
+
if (!evidence.flushConfirmed) throw failure('WORKFLOW_FLUSH_UNAVAILABLE', 'Session persistence is unavailable')
|
|
176
|
+
const raw = await readRaw(sessionId)
|
|
177
|
+
result = resultFromLog(raw.header, raw.events, { sessionId, requestId, messageId: message.id, prompt, cwd })
|
|
178
|
+
Object.assign(evidence, result.evidence)
|
|
179
|
+
} catch (error) { issue = error }
|
|
180
|
+
finally {
|
|
181
|
+
try {
|
|
182
|
+
if (record.handle) await record.handle.dispose()
|
|
183
|
+
evidence.ownedJobCount = runningJobs(sessionId).length
|
|
184
|
+
evidence.quiescent = !agents.get(sessionId) && evidence.ownedJobCount === 0
|
|
185
|
+
if (!created && issue?.code === 'WORKFLOW_REUSE_FORBIDDEN') evidence.quiescent = false
|
|
186
|
+
} catch (error) { issue ??= error; evidence.quiescent = false }
|
|
187
|
+
signal?.removeEventListener('abort', abort)
|
|
188
|
+
active.delete(attemptId)
|
|
189
|
+
record.finish()
|
|
190
|
+
}
|
|
191
|
+
if (record.cancelled) issue = failure('WORKFLOW_CANCELLED', 'Stage cancelled')
|
|
192
|
+
if (issue || !result || !evidence.quiescent) throw new DshExecutionError(issue?.code ?? 'WORKFLOW_EXECUTION_UNKNOWN', issue?.message ?? 'Stage execution is not complete', evidence, issue)
|
|
193
|
+
evidence.completed = true
|
|
194
|
+
return { ...result, evidence }
|
|
195
|
+
}
|
|
196
|
+
return { run, cancel,
|
|
197
|
+
async inspectReadonly(request) {
|
|
198
|
+
const evidence = { kind: 'dsh-session-log', ...request, completed: false, quiescent: false, flushConfirmed: false }
|
|
199
|
+
if (!await persistence.stat(request.sessionId, { signal: request.signal })) return { status: 'missing', evidence }
|
|
200
|
+
const raw = await readRaw(request.sessionId, request.signal)
|
|
201
|
+
try { return { status: 'completed-evidence', ...resultFromLog(raw.header, raw.events, request) } }
|
|
202
|
+
catch (error) { return { status: 'unknown', code: error.code, evidence } }
|
|
203
|
+
},
|
|
204
|
+
async dispose() { closed = true; const records = [...active.entries()]; for (const [id] of records) cancel(id); await Promise.all(records.map(([, record]) => record.done)) },
|
|
205
|
+
}
|
|
206
|
+
}
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { createRequire } from 'node:module'
|
|
3
|
+
import { realpath } from 'node:fs/promises'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { pathToFileURL } from 'node:url'
|
|
6
|
+
import { projectStageTrace, stageEventWindow } from './stage-trace.js'
|
|
7
|
+
import { openWorkflowStore } from './store.js'
|
|
8
|
+
import { ensureTaskDirectory, listTaskFiles, taskFilePath, deleteTaskFile } from './task-files.js'
|
|
9
|
+
import { createDshExecutor, NATIVE_POLICY, readPersistedSession, withStoppedNativeExecution } from './dsh-adapter.js'
|
|
10
|
+
import { createWorkflowRunner, PROJECT_POLICY, readArtifactText } from './runner.js'
|
|
11
|
+
import { mountWorkflowReviewApi, validateWorkflowCommand } from './review-api.js'
|
|
12
|
+
import { mountWorkflowManagementTools } from './management-tools.js'
|
|
13
|
+
import { PROCESS_POLICY, readProcessIdentity, confirmStoppedExecution } from './recovery.js'
|
|
14
|
+
|
|
15
|
+
export const name = 'dsh-kanban-workflow'
|
|
16
|
+
export const inject = ['profileContext', 'agents', 'sessions', 'sessionPersistence',
|
|
17
|
+
'agentPresets', 'agentDefaultModel', 'llm', 'jobs', 'attachments', 'workspaceRegistry', 'connection', 'typertGateway', 'tools', 'workingDirectory']
|
|
18
|
+
|
|
19
|
+
const MODEL_UNAVAILABLE = '暂时无法确认当前模型配置,请刷新后重试;不会自动切换模型或推理档位。'
|
|
20
|
+
const executionModel = selection => selection ? Object.fromEntries(['provider', 'model', 'reasoningEffort']
|
|
21
|
+
.filter(key => typeof selection[key] === 'string').map(key => [key, selection[key]])) : null
|
|
22
|
+
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex')
|
|
23
|
+
const fail = (code, message) => { throw Object.assign(new Error(message), { code }) }
|
|
24
|
+
|
|
25
|
+
export function taskSummary(task) {
|
|
26
|
+
return { id: task.id, workspaceId: task.workspaceId, workflowId: task.workflowId, workflowName: task.workflowName,
|
|
27
|
+
versionNumber: task.versionNumber, workflowVersionId: task.workflowVersionId, title: task.title, inputText: task.input.text, state: task.state, canRetry: task.canRetry === true,
|
|
28
|
+
revision: task.revision, stageTitle: task.currentStage.title, createdAt: task.createdAt, updatedAt: task.updatedAt }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function publicWorkflow(workflow) {
|
|
32
|
+
const { id, workspaceId, name, description, revision, definition, versionId, versionNumber, taskCount, createdAt, updatedAt } = workflow
|
|
33
|
+
return { id, workspaceId, name, description, revision, definition, versionId, versionNumber, taskCount, createdAt, updatedAt }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function artifactMetadata(task, artifact) {
|
|
37
|
+
const attempt = task.attempts.find(item => item.id === artifact.attemptId)
|
|
38
|
+
const stageId = task.visits.find(item => item.id === attempt?.visitId)?.stageId ?? ''
|
|
39
|
+
return { id: artifact.id, label: artifact.label, contentHash: artifact.contentHash, byteLength: artifact.byteLength,
|
|
40
|
+
stageId, createdAt: artifact.createdAt, effective: task.effectiveArtifacts.some(item => item.id === artifact.id) }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Explicit projections: never expose owner fencing tokens, native paths or snapshot references. */
|
|
44
|
+
export async function publicTask(task, attachments, { includeOutputText = true, executing = false } = {}) {
|
|
45
|
+
const outputs = await Promise.all(task.effectiveArtifacts.map(async artifact => {
|
|
46
|
+
const metadata = artifactMetadata(task, artifact)
|
|
47
|
+
if (!includeOutputText) return metadata
|
|
48
|
+
try { return { ...metadata, text: await readArtifactText(attachments, artifact), unavailable: false } }
|
|
49
|
+
catch { return { ...metadata, text: '', unavailable: true } }
|
|
50
|
+
}))
|
|
51
|
+
const attention = task.attention ? { ...(task.attention.code === undefined ? {} : { code: task.attention.code }),
|
|
52
|
+
message: task.attention.message ?? (task.canRetry
|
|
53
|
+
? '本阶段未能完成,原输入和上游成果已保留。修复原因后可重试此阶段。'
|
|
54
|
+
: '上次执行尚未确认停止。为避免重复操作,不能直接重试;请先核对执行记录和项目中的实际改动。') } : null
|
|
55
|
+
return { ...taskSummary(task), input: task.input, attention,
|
|
56
|
+
executionModel: executionModel(task.currentStage?.modelSelection ?? task.executionConfig?.modelSelection),
|
|
57
|
+
stages: task.definition.stages.map(({ id, title, kind, prompt, returnStageId, modelSelection }) => ({ id, title, kind,
|
|
58
|
+
...(prompt === undefined ? {} : { prompt }), ...(returnStageId === undefined ? {} : { returnStageId }),
|
|
59
|
+
...(modelSelection ? { modelSelection: executionModel(modelSelection) } : {}) })),
|
|
60
|
+
currentStageId: task.currentStage.id, outputs, feedback: task.feedback,
|
|
61
|
+
canReview: task.state === 'waiting_review' && outputs.length > 0 && outputs.every(item => !item.unavailable),
|
|
62
|
+
canReconcile: !executing && ['running', 'needs_attention', 'terminating'].includes(task.state) && task.attempts.some(attempt =>
|
|
63
|
+
attempt.quiescedAt == null && (attempt.state === 'unknown' && attempt.executorSnapshot.stopPolicy === PROCESS_POLICY
|
|
64
|
+
|| ['prepared', 'running', 'unknown'].includes(attempt.state) && attempt.executorSnapshot.policy === NATIVE_POLICY)),
|
|
65
|
+
review: task.review ? { id: task.review.id, subjectHash: task.review.subjectHash,
|
|
66
|
+
returnStageId: task.review.returnStageId, requestedAt: task.review.requestedAt } : null,
|
|
67
|
+
visits: task.visits.map(({ id, stageId, outcome, openedAt, closedAt }) => ({ id, stageId, state: outcome, startedAt: openedAt, finishedAt: closedAt })),
|
|
68
|
+
attempts: task.attempts.map(attempt => ({ id: attempt.id, sessionId: attempt.sessionId,
|
|
69
|
+
stageId: task.visits.find(visit => visit.id === attempt.visitId)?.stageId ?? '', state: attempt.state,
|
|
70
|
+
startedAt: attempt.createdAt, finishedAt: attempt.settledAt, quiescedAt: attempt.quiescedAt,
|
|
71
|
+
error: attempt.error ? `${attempt.error.code ?? 'WF_EXECUTION_FAILED'}: ${attempt.error.message ?? '执行未完成'}` : null })),
|
|
72
|
+
artifactHistory: task.artifacts.map(artifact => artifactMetadata(task, artifact)),
|
|
73
|
+
reviews: task.reviews.map(({ id, visitId, state, feedback, subject, requestedAt, decidedAt }) => ({ id, stageId: task.visits.find(visit => visit.id === visitId)?.stageId ?? '', state, feedback, artifactIds: subject.artifactIds, requestedAt, decidedAt })),
|
|
74
|
+
events: task.events.map(({ id, kind, sequence, createdAt }) => ({ id, kind, sequence, createdAt })),
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** One business implementation shared by authenticated UI and narrowly scoped management tools. */
|
|
79
|
+
export function createWorkflowCore({ store, runner, attachments, workspaceRegistry, currentModel, profileDir,
|
|
80
|
+
confirmStopped = confirmStoppedExecution,
|
|
81
|
+
reconcileNative,
|
|
82
|
+
readSessionLog, firstTokenTime, modelInfoFor = async () => null, assertOpen = () => {} }) {
|
|
83
|
+
const validate = (method, request) => validateWorkflowCommand(method, request)
|
|
84
|
+
const workspaceBinding = async workspaceId => {
|
|
85
|
+
const workspace = workspaceRegistry.get(workspaceId)
|
|
86
|
+
if (!workspace || await workspace.status() !== 'ok') fail('WF_WORKSPACE_MISSING', '所选工作区不可用,请检查目录或重新选择。')
|
|
87
|
+
const rootPath = await realpath(workspace.path)
|
|
88
|
+
return { workspaceId: workspace.id, rootPath, executionScope: hash([profileDir, rootPath]) }
|
|
89
|
+
}
|
|
90
|
+
const readModelInfo = async (selection, signal) => {
|
|
91
|
+
signal?.throwIfAborted()
|
|
92
|
+
try {
|
|
93
|
+
const info = await modelInfoFor(selection, signal)
|
|
94
|
+
signal?.throwIfAborted()
|
|
95
|
+
return info
|
|
96
|
+
} catch {
|
|
97
|
+
signal?.throwIfAborted()
|
|
98
|
+
fail('WF_MODEL_UNAVAILABLE', MODEL_UNAVAILABLE)
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const requireModel = async (selection, signal) => {
|
|
102
|
+
const info = await readModelInfo(selection, signal)
|
|
103
|
+
// Null preserves legacy embedders; the live Host always resolves exact-model metadata.
|
|
104
|
+
if (!info) return
|
|
105
|
+
if (selection?.reasoningEffort !== undefined && !info.reasoning?.efforts?.some(item => item.id === selection.reasoningEffort)) {
|
|
106
|
+
fail('WF_MODEL_UNSUPPORTED', '此模型不支持所选推理档位,请刷新并明确选择可用档位;不会自动降级。')
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const viewTask = async (task, includeOutputText = false) => {
|
|
110
|
+
const view = await publicTask(task, attachments, { includeOutputText, executing: runner.isExecutingTask?.(task.id) === true })
|
|
111
|
+
if (runner.hasPendingSettlement?.(task.id)) view.attention = { code: 'WF_SETTLEMENT_PENDING', message: 'AI 已结束执行,结果保存暂未完成,正在自动重试保存。不会重新执行模型;也可以核对后终止。' }
|
|
112
|
+
return view
|
|
113
|
+
}
|
|
114
|
+
const core = {
|
|
115
|
+
async listTasks(workspaceId) {
|
|
116
|
+
assertOpen()
|
|
117
|
+
return { tasks: store.listTaskSummaries(workspaceId), status: runner.status() }
|
|
118
|
+
},
|
|
119
|
+
listWorkflows(workspaceId) { assertOpen(); return store.listWorkflows(workspaceId).map(publicWorkflow) },
|
|
120
|
+
getWorkflow(workflowId) { assertOpen(); return publicWorkflow(store.getWorkflow(workflowId)) },
|
|
121
|
+
async getTask(taskId, { includeOutputText = false } = {}) { assertOpen(); return viewTask(store.getTask(taskId), includeOutputText) },
|
|
122
|
+
async getStageTrace({ taskId, stageId, attemptId, fromSeq = 0, limit = 50 }, signal) {
|
|
123
|
+
assertOpen(); signal?.throwIfAborted()
|
|
124
|
+
if (!Number.isSafeInteger(fromSeq) || fromSeq < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 200) fail('WF_INVALID_INPUT', 'Invalid trace page.')
|
|
125
|
+
const task = store.getTask(taskId), visits = task.visits.filter(visit => visit.stageId === stageId)
|
|
126
|
+
const attempts = task.attempts.filter(attempt => visits.some(visit => visit.id === attempt.visitId))
|
|
127
|
+
const attempt = attemptId ? attempts.find(attempt => attempt.id === attemptId) : attempts.at(-1)
|
|
128
|
+
if (!attempt) fail('WF_TRACE_NOT_FOUND', '此阶段还没有对应的执行记录。')
|
|
129
|
+
if (!readSessionLog) fail('WF_TRACE_UNAVAILABLE', '当前 DSH 暂时无法读取阶段会话日志。')
|
|
130
|
+
let log
|
|
131
|
+
try { log = await readSessionLog(attempt.sessionId, signal) } catch { signal?.throwIfAborted(); fail('WF_TRACE_UNAVAILABLE', '阶段会话日志暂不可用,可能尚未保存或已被清理。') }
|
|
132
|
+
if (log.header?.id !== attempt.sessionId || !Array.isArray(log.events)) fail('WF_TRACE_UNAVAILABLE', '阶段会话日志与执行记录不匹配。')
|
|
133
|
+
return projectStageTrace(task, attempt, stageEventWindow(log.events, attempt), { fromSeq, limit, firstTokenTime })
|
|
134
|
+
},
|
|
135
|
+
async getTaskFiles(taskId) { assertOpen(); return listTaskFiles(store.getTask(taskId)) },
|
|
136
|
+
async deleteTaskFile(input, actor) {
|
|
137
|
+
assertOpen()
|
|
138
|
+
if (actor?.kind !== 'user') fail('WF_HUMAN_REQUIRED', '请在任务产物列表中确认删除文件。')
|
|
139
|
+
const request = validate('deleteTaskFile', input)
|
|
140
|
+
return deleteTaskFile(store.getTask(request.taskId), request.path, request.expectedVersion)
|
|
141
|
+
},
|
|
142
|
+
async getTaskFile(taskId, path) {
|
|
143
|
+
assertOpen()
|
|
144
|
+
const task = store.getTask(taskId), file = await taskFilePath(task, path)
|
|
145
|
+
return file
|
|
146
|
+
},
|
|
147
|
+
async getArtifact(taskId, artifactId) {
|
|
148
|
+
assertOpen()
|
|
149
|
+
const task = store.getTask(taskId)
|
|
150
|
+
const artifact = task.artifacts.find(item => item.id === artifactId)
|
|
151
|
+
if (!artifact) fail('WF_ARTIFACT_NOT_FOUND', '此成果不属于该任务。')
|
|
152
|
+
try { return { ...artifactMetadata(task, artifact), text: await readArtifactText(attachments, artifact) } }
|
|
153
|
+
catch { fail('WF_ARTIFACT_UNAVAILABLE', '保存的成果暂时无法读取,请检查附件存储后重试。') }
|
|
154
|
+
},
|
|
155
|
+
async createWorkflow(input, actor, selection) {
|
|
156
|
+
assertOpen()
|
|
157
|
+
const request = validate('createWorkflow', input)
|
|
158
|
+
const existing = store.getCreateWorkflowBinding(request.requestId)
|
|
159
|
+
if (existing && existing.workspaceId !== request.workspaceId) fail('WF_IDEMPOTENCY_CONFLICT', '此请求已经用于另一个工作区。')
|
|
160
|
+
const binding = existing ?? await workspaceBinding(request.workspaceId)
|
|
161
|
+
assertOpen()
|
|
162
|
+
return publicWorkflow(store.createWorkflow({ ...request, ...binding }, actor, selection))
|
|
163
|
+
},
|
|
164
|
+
updateWorkflow(input, actor, selection) {
|
|
165
|
+
assertOpen()
|
|
166
|
+
return publicWorkflow(store.updateWorkflow(validate('updateWorkflow', input), actor, selection))
|
|
167
|
+
},
|
|
168
|
+
deleteWorkflow(input, actor) {
|
|
169
|
+
assertOpen()
|
|
170
|
+
if (actor.kind !== 'user') fail('WF_HUMAN_REQUIRED', '请在工作流页面确认删除。')
|
|
171
|
+
return store.deleteWorkflow(validate('deleteWorkflow', input), actor)
|
|
172
|
+
},
|
|
173
|
+
async deleteTask(input, actor) {
|
|
174
|
+
assertOpen()
|
|
175
|
+
if (actor?.kind !== 'user') fail('WF_HUMAN_REQUIRED', '请在任务列表中确认删除。')
|
|
176
|
+
const result = store.deleteTask(validate('deleteTask', input), actor)
|
|
177
|
+
const complete = await runner.cleanupDeletedTasks()
|
|
178
|
+
return complete ? result : { ...result, cleanupPending: true }
|
|
179
|
+
},
|
|
180
|
+
async createTask(input, actor) {
|
|
181
|
+
assertOpen()
|
|
182
|
+
const request = validate('createTask', input)
|
|
183
|
+
const committed = store.getCreateTaskSnapshot(request.requestId)
|
|
184
|
+
const workflowId = request.workflowId ?? committed?.workflowId
|
|
185
|
+
if (!workflowId) fail('WF_WORKFLOW_REQUIRED', '请先选择一个工作流,再创建任务。')
|
|
186
|
+
if (committed && (committed.workspaceId !== request.workspaceId || committed.workflowId !== workflowId)) fail('WF_IDEMPOTENCY_CONFLICT', '此请求已经用于另一个工作流或工作区。')
|
|
187
|
+
let executionConfig, expectedVersionId
|
|
188
|
+
if (committed) {
|
|
189
|
+
executionConfig = committed.executionConfig
|
|
190
|
+
expectedVersionId = request.expectedVersionId ?? ([PROJECT_POLICY, NATIVE_POLICY].includes(executionConfig.policy) ? committed.workflowVersionId : undefined)
|
|
191
|
+
} else {
|
|
192
|
+
const workflow = store.getWorkflow(workflowId)
|
|
193
|
+
if (workflow.workspaceId !== request.workspaceId) fail('WF_WORKSPACE_MISMATCH', '该工作流不属于当前工作区。')
|
|
194
|
+
expectedVersionId = request.expectedVersionId ?? workflow.versionId ?? undefined
|
|
195
|
+
if (expectedVersionId !== undefined && expectedVersionId !== workflow.versionId) fail('WF_VERSION_CHANGED', '流程已更新,请刷新后再创建任务。')
|
|
196
|
+
const agentStages = workflow.definition.stages.filter(stage => stage.kind === 'agent')
|
|
197
|
+
const fallback = agentStages.some(stage => !stage.modelSelection) ? currentModel() : agentStages[0]?.modelSelection
|
|
198
|
+
const selections = agentStages.map(stage => stage.modelSelection ?? fallback)
|
|
199
|
+
if (selections.some(selection => !selection?.provider || !selection?.model)) fail('WF_MODEL_UNAVAILABLE', '请通过 Agent 为工作流阶段配置模型,或在 DSH 设置默认模型。')
|
|
200
|
+
for (const selection of new Map(selections.map(selection => [JSON.stringify(selection), selection])).values()) await requireModel(selection)
|
|
201
|
+
await workspaceBinding(workflow.workspaceId)
|
|
202
|
+
executionConfig = { policy: NATIVE_POLICY, modelSelection: fallback }
|
|
203
|
+
}
|
|
204
|
+
assertOpen()
|
|
205
|
+
const task = store.createTask({ requestId: request.requestId, workflowId,
|
|
206
|
+
title: request.title, input: { text: request.text }, executionConfig,
|
|
207
|
+
...(expectedVersionId ? { expectedVersionId } : {}) }, actor)
|
|
208
|
+
if (!committed) await ensureTaskDirectory(task)
|
|
209
|
+
void runner.kick()
|
|
210
|
+
return viewTask(task)
|
|
211
|
+
},
|
|
212
|
+
async decideReview(request, actor) {
|
|
213
|
+
assertOpen()
|
|
214
|
+
if (actor?.kind !== 'user') fail('WF_HUMAN_REQUIRED', '审核决定必须由用户在工作流页面确认。')
|
|
215
|
+
const before = store.getTask(request.taskId)
|
|
216
|
+
if (request.decision === 'approved' && before.revision === request.expectedRevision && before.review?.id === request.reviewId) {
|
|
217
|
+
try { await Promise.all(before.effectiveArtifacts.map(artifact => readArtifactText(attachments, artifact))) }
|
|
218
|
+
catch { fail('WF_ARTIFACT_UNAVAILABLE', '审核成果无法读取,不能批准。请先检查附件存储。') }
|
|
219
|
+
}
|
|
220
|
+
assertOpen()
|
|
221
|
+
const task = store.decideReview(request, actor)
|
|
222
|
+
void runner.kick()
|
|
223
|
+
return viewTask(task)
|
|
224
|
+
},
|
|
225
|
+
async retryTask(input, actor) {
|
|
226
|
+
assertOpen()
|
|
227
|
+
const request = validate('retryTask', input)
|
|
228
|
+
const before = store.getTask(request.taskId)
|
|
229
|
+
// A stale revision may be a committed receipt; let the Store replay it first.
|
|
230
|
+
if (before.revision === request.expectedRevision) {
|
|
231
|
+
await requireModel(before.currentStage?.modelSelection ?? before.executionConfig?.modelSelection)
|
|
232
|
+
}
|
|
233
|
+
assertOpen()
|
|
234
|
+
const task = store.retryTask(request, actor)
|
|
235
|
+
void runner.kick()
|
|
236
|
+
return viewTask(task)
|
|
237
|
+
},
|
|
238
|
+
async reconcileTask(input, actor) {
|
|
239
|
+
assertOpen()
|
|
240
|
+
if (actor?.kind !== 'user') fail('WF_HUMAN_REQUIRED', '请在工作流页面核对旧执行。')
|
|
241
|
+
const request = validate('reconcileTask', input)
|
|
242
|
+
// Finish any in-flight report writes before releasing this Task's execution ownership.
|
|
243
|
+
await runner.settleTask?.(request.taskId)
|
|
244
|
+
assertOpen()
|
|
245
|
+
const task = store.getTask(request.taskId)
|
|
246
|
+
if (task.revision !== request.expectedRevision) {
|
|
247
|
+
const restored = store.reconcileTask(request, actor)
|
|
248
|
+
void runner.kick()
|
|
249
|
+
return viewTask(restored)
|
|
250
|
+
}
|
|
251
|
+
const pending = task.attempts.filter(attempt => ['prepared', 'running', 'unknown'].includes(attempt.state) && attempt.quiescedAt == null)
|
|
252
|
+
if (pending.length !== 1) fail('WF_RECOVERY_UNSUPPORTED', '此任务没有可核对的单一中断执行。')
|
|
253
|
+
const attempt = pending[0]
|
|
254
|
+
if (attempt.executorSnapshot.policy === NATIVE_POLICY && attempt.executorSnapshot.stopPolicy === undefined) {
|
|
255
|
+
if (!reconcileNative) fail('WF_RECOVERY_UNSUPPORTED', '当前执行环境暂时无法核对原生会话。')
|
|
256
|
+
const restored = await reconcileNative(attempt, evidence => {
|
|
257
|
+
assertOpen()
|
|
258
|
+
return store.reconcileTask(request, actor, evidence)
|
|
259
|
+
}, { confirmedStopped: request.confirmedStopped === true })
|
|
260
|
+
void runner.kick()
|
|
261
|
+
return viewTask(restored)
|
|
262
|
+
}
|
|
263
|
+
const evidence = await confirmStopped({ attempt, processes: store.getAttemptProcesses(attempt.id) })
|
|
264
|
+
assertOpen()
|
|
265
|
+
const restored = store.reconcileTask(request, actor, evidence)
|
|
266
|
+
void runner.kick()
|
|
267
|
+
return viewTask(restored)
|
|
268
|
+
},
|
|
269
|
+
async terminateTask(input, actor) {
|
|
270
|
+
assertOpen()
|
|
271
|
+
const request = validate('terminateTask', input)
|
|
272
|
+
const task = store.terminateTask(request, actor)
|
|
273
|
+
if (task.state === 'terminating') {
|
|
274
|
+
const canceled = await runner.cancelTask(task.id)
|
|
275
|
+
const current = store.getTask(task.id)
|
|
276
|
+
const pending = current.attempts.filter(attempt => ['prepared', 'running', 'unknown'].includes(attempt.state) && attempt.quiescedAt == null)
|
|
277
|
+
if (!canceled?.requested && current.state === 'terminating' && pending.length === 1) {
|
|
278
|
+
if (pending[0].executorSnapshot.policy === NATIVE_POLICY && pending[0].executorSnapshot.stopPolicy === undefined) {
|
|
279
|
+
return core.reconcileTask({ taskId: task.id, expectedRevision: current.revision, requestId: `stop:${hash(request.requestId)}`, ...(request.confirmedStopped === undefined ? {} : { confirmedStopped: request.confirmedStopped }) }, actor)
|
|
280
|
+
}
|
|
281
|
+
if (pending[0].executorSnapshot.stopPolicy !== PROCESS_POLICY) fail('WF_RECOVERY_UNSUPPORTED', '此执行缺少可核对的停止记录。')
|
|
282
|
+
if (actor?.kind !== 'user') fail('WF_HUMAN_REQUIRED', '停止旧执行必须由用户确认。')
|
|
283
|
+
const attempt = pending[0]
|
|
284
|
+
const evidence = await confirmStopped({ attempt, processes: store.getAttemptProcesses(attempt.id), stop: true })
|
|
285
|
+
assertOpen()
|
|
286
|
+
store.reconcileTask({ taskId: task.id, expectedRevision: current.revision,
|
|
287
|
+
requestId: `stop:${hash(request.requestId)}` }, actor, evidence)
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
void runner.kick()
|
|
291
|
+
return viewTask(store.getTask(task.id))
|
|
292
|
+
},
|
|
293
|
+
}
|
|
294
|
+
return core
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export async function apply(ctx) {
|
|
298
|
+
const runtimeRequire = createRequire(ctx.profileContext.installAnchor)
|
|
299
|
+
const protocol = await import(pathToFileURL(runtimeRequire.resolve('@deepseek-ai/dsh-typert-protocol')).href)
|
|
300
|
+
// Keep the deployed store path; this upgrade must not strand existing Tasks.
|
|
301
|
+
const store = openWorkflowStore(join(ctx.profileContext.dir, 'workflow-poc', 'workflow.sqlite'))
|
|
302
|
+
let executor, runner, apiFiber, removeTools
|
|
303
|
+
let closing = false
|
|
304
|
+
const assertOpen = () => { if (closing) fail('WF_STOPPING', '工作流正在停止,请准备就绪后重试。') }
|
|
305
|
+
const cleanup = async () => {
|
|
306
|
+
closing = true
|
|
307
|
+
removeTools?.()
|
|
308
|
+
await apiFiber?.dispose()
|
|
309
|
+
if (runner) await runner.dispose()
|
|
310
|
+
else await executor?.dispose()
|
|
311
|
+
store.close()
|
|
312
|
+
}
|
|
313
|
+
try {
|
|
314
|
+
const { assistantStreamFirstTokenTime } = await import(pathToFileURL(runtimeRequire.resolve('@deepseek-ai/dsh-llm')).href)
|
|
315
|
+
const { installModelSelection } = await import(pathToFileURL(runtimeRequire.resolve('@deepseek-ai/dsh-agent')).href)
|
|
316
|
+
executor = createDshExecutor(ctx, { installModelSelection })
|
|
317
|
+
runner = createWorkflowRunner({ store, executor, attachments: ctx.attachments, workspaceRegistry: ctx.workspaceRegistry,
|
|
318
|
+
onError: error => console.warn('Workflow:', error?.code ?? 'WF_INTERNAL') })
|
|
319
|
+
const core = createWorkflowCore({ store, runner, attachments: ctx.attachments, workspaceRegistry: ctx.workspaceRegistry,
|
|
320
|
+
readSessionLog: (id, signal) => readPersistedSession(ctx.sessionPersistence, id, signal), firstTokenTime: assistantStreamFirstTokenTime,
|
|
321
|
+
reconcileNative: (attempt, commit, options) => withStoppedNativeExecution(ctx, attempt, commit, options),
|
|
322
|
+
currentModel: () => { try { return ctx.agentDefaultModel.currentSelection() } catch { return null } },
|
|
323
|
+
modelInfoFor: (selection, signal) => ctx.llm.resolveModelInfo(selection.provider, selection.model, signal),
|
|
324
|
+
profileDir: ctx.profileContext.dir, assertOpen })
|
|
325
|
+
await runner.start()
|
|
326
|
+
apiFiber = mountWorkflowReviewApi(ctx, core, protocol)
|
|
327
|
+
await apiFiber
|
|
328
|
+
removeTools = mountWorkflowManagementTools(ctx, core)
|
|
329
|
+
return cleanup
|
|
330
|
+
} catch (error) {
|
|
331
|
+
await cleanup()
|
|
332
|
+
throw error
|
|
333
|
+
}
|
|
334
|
+
}
|