@alpacachen/dsh-kanban 1.11.2 → 1.12.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.
@@ -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
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Workflows",
4
+ "description": "Workflows inside Kanban: Agent-authored stages with editable models, automatic execution, human review, rework and native execution chats. Uses DSH tools and authorization. Requires DSH 0.2.2-rc.3."
5
+ }
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "工作流",
4
+ "description": "Kanban 内置工作流:由 Agent 配置流程,用户在详情调整阶段模型,任务按流程自动执行,支持人工审核、返工与执行过程查看。工具与授权沿用 DSH。需要 DSH 0.2.2-rc.3。"
5
+ }
6
+ }
@@ -0,0 +1,160 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { validateWorkflowCommand } from './review-api.js'
3
+
4
+ const ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/
5
+ const fail = (code, message) => { throw Object.assign(new Error(message), { code }) }
6
+ const invalid = () => fail('WF_INVALID_INPUT', 'Invalid workflow tool request.')
7
+ const id = value => { if (typeof value !== 'string' || !ID.test(value)) invalid(); return value }
8
+ const identifier = description => ({ type: 'string', description })
9
+ const requestId = identifier('Optional idempotency key. Reuse an explicit key when retrying; omission creates a new key.')
10
+
11
+ const definitionSchema = {
12
+ type: 'object', additionalProperties: false,
13
+ properties: {
14
+ description: { type: 'string', description: 'Purpose of the reusable workflow.' },
15
+ inputLabel: { type: 'string', description: 'Short label for task input.' },
16
+ inputHint: { type: 'string', description: 'Describe the material the user should supply.' },
17
+ stages: { type: 'array', minItems: 1, maxItems: 16, items: {
18
+ type: 'object', additionalProperties: false, required: ['id', 'kind', 'title'],
19
+ properties: {
20
+ id: { type: 'string', description: 'Stable unique stage id. Preserve ids for unchanged stages.' },
21
+ kind: { type: 'string', enum: ['agent', 'review'] },
22
+ title: { type: 'string', description: 'Short stage name.' },
23
+ prompt: { type: 'string', description: 'Required non-empty instructions and expected deliverable for agent stages; optional human checklist for review stages. Review status is shown by Workflow: keep changing approval labels out of deliverable filenames, titles and body; use generation time for provenance.' },
24
+ returnStageId: { type: 'string', description: 'Required for review stages: a fixed earlier agent-stage id to return to. Omit on agent stages.' },
25
+ },
26
+ } },
27
+ }, required: ['stages'],
28
+ }
29
+ const agentDefinition = definition => {
30
+ if (!definition || typeof definition !== 'object' || Array.isArray(definition)
31
+ || Object.keys(definition).some(key => !Object.hasOwn(definitionSchema.properties, key)) || !Array.isArray(definition.stages)) invalid()
32
+ for (const stage of definition.stages) {
33
+ if (!stage || typeof stage !== 'object' || Array.isArray(stage)
34
+ || Object.keys(stage).some(key => !Object.hasOwn(definitionSchema.properties.stages.items.properties, key))) invalid()
35
+ }
36
+ return definition
37
+ }
38
+ const agentWorkflow = value => {
39
+ if (!value.definition?.stages) return value
40
+ return { ...value, definition: { ...value.definition, stages: value.definition.stages.map(({ modelSelection: _model, ...stage }) => stage) } }
41
+ }
42
+ const sessionSelection = exec => {
43
+ const selection = exec.agent.model?.current()
44
+ if (!selection?.provider || !selection?.model) fail('WF_MODEL_UNAVAILABLE', '当前聊天没有可用的模型配置,请先在聊天中选择模型。')
45
+ return { provider: selection.provider, model: selection.model, ...(selection.reasoningEffort === undefined ? {} : { reasoningEffort: selection.reasoningEffort }) }
46
+ }
47
+
48
+ /** Register ordinary management actions, never publication, permissions, or review authority. */
49
+ export function mountWorkflowManagementTools(ctx, core) {
50
+ const disposers = []
51
+ const inWorkspace = (value, workspace) => {
52
+ if (!value || value.workspaceId !== workspace.id) fail('WF_WORKSPACE_MISMATCH', 'This item does not belong to the current workspace.')
53
+ return value
54
+ }
55
+ const register = (name, description, properties, required, run) => {
56
+ const dispose = ctx.tools.register({
57
+ name, description,
58
+ parameters: { type: 'object', properties, required, additionalProperties: false },
59
+ // DSH's enforced output subset accepts boolean additionalProperties and real JSON values.
60
+ output: { schema: { type: 'object', additionalProperties: true },
61
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] },
62
+ async execute(args, exec) {
63
+ try {
64
+ if (!args || typeof args !== 'object' || Array.isArray(args)
65
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(args))
66
+ || Reflect.ownKeys(args).some(key => !Object.prototype.hasOwnProperty.call(properties, key)
67
+ || !Object.prototype.hasOwnProperty.call(Object.getOwnPropertyDescriptor(args, key), 'value'))) invalid()
68
+ if (!exec?.agent?.session || typeof exec.agent.id !== 'string' || !exec.agent.id) {
69
+ fail('WF_AGENT_REQUIRED', 'A Workflow tool requires an initiating agent.')
70
+ }
71
+ exec.signal?.throwIfAborted()
72
+ const cwd = ctx.workingDirectory.get(exec.agent.session)
73
+ const workspace = await ctx.workspaceRegistry.resolveByPath(cwd)
74
+ if (!workspace) fail('WF_WORKSPACE_MISSING', 'The current project is not a registered workspace.')
75
+ exec.signal?.throwIfAborted()
76
+ const actor = Object.freeze({ kind: 'agent', id: exec.agent.id, source: 'workflow-management-tool' })
77
+ return await run(args, workspace, actor, exec)
78
+ } catch (error) {
79
+ exec?.signal?.throwIfAborted()
80
+ if (typeof error?.code === 'string' && /^WF_[A-Z_]+$/.test(error.code)
81
+ && typeof error.message === 'string' && error.message.length <= 2000) {
82
+ fail(error.code, error.message)
83
+ }
84
+ fail('WF_INTERNAL', 'The workflow operation could not be completed.')
85
+ }
86
+ },
87
+ })
88
+ disposers.push(dispose)
89
+ }
90
+ try {
91
+ register('workflow_list', 'List workflows in the current project. Does not start tasks or approve anything.', {}, [],
92
+ async (_args, workspace) => ({ workspaceId: workspace.id,
93
+ workflows: (await core.listWorkflows(workspace.id)).map(value => agentWorkflow(inWorkspace(value, workspace))) }))
94
+ register('workflow_list_tasks', 'Read task history for one Workflow in the current project. Compare workflowVersionId/versionNumber before attributing old failures to the current definition. Does not run, retry or modify tasks.', {
95
+ workflowId: identifier('Workflow id in the current project.'),
96
+ }, ['workflowId'], async (args, workspace) => {
97
+ const workflow = inWorkspace(await core.getWorkflow(id(args.workflowId)), workspace)
98
+ const overview = await core.listTasks(workspace.id)
99
+ return { workflowId: workflow.id, currentVersionId: workflow.versionId, currentVersionNumber: workflow.versionNumber,
100
+ tasks: overview.tasks.filter(task => task.workflowId === workflow.id).sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)) }
101
+ })
102
+ register('workflow_create', 'Create a reusable Workflow in the current project. It is immediately available for tasks; creating a workflow does not execute it.', {
103
+ requestId, name: { type: 'string', description: 'Workflow name, at most 200 characters.' },
104
+ definition: definitionSchema,
105
+ }, ['name', 'definition'], async (args, workspace, actor, exec) => {
106
+ const request = validateWorkflowCommand('createWorkflow', { ...args, definition: agentDefinition(args.definition), workspaceId: workspace.id,
107
+ requestId: args.requestId === undefined ? randomUUID() : args.requestId })
108
+ return agentWorkflow(inWorkspace(await core.createWorkflow(request, actor, sessionSelection(exec)), workspace))
109
+ })
110
+ register('workflow_update', 'Replace a Workflow definition in the current project. Read workflow_list first and use its exact revision. Preserve unchanged stage ids. Review stages require an earlier agent returnStageId. Changes apply only to new tasks. Does not start tasks.', {
111
+ requestId, workflowId: identifier('Workflow id in the current project.'),
112
+ expectedRevision: { type: 'integer', minimum: 1, description: 'Exact current revision from workflow_list. On conflict, read the latest definition and reapply only the requested edits; never blindly retry.' },
113
+ name: { type: 'string', description: 'Workflow name, at most 200 characters.' },
114
+ definition: definitionSchema,
115
+ }, ['workflowId', 'expectedRevision', 'name', 'definition'], async (args, workspace, actor, exec) => {
116
+ const request = validateWorkflowCommand('updateWorkflow', { ...args, definition: agentDefinition(args.definition),
117
+ requestId: args.requestId === undefined ? randomUUID() : args.requestId })
118
+ inWorkspace(await core.getWorkflow(id(args.workflowId)), workspace)
119
+ return agentWorkflow(inWorkspace(await core.updateWorkflow(request, actor, sessionSelection(exec)), workspace))
120
+ })
121
+ register('workflow_create_task', 'Start an actual task from an Workflow in the current project. This calls the configured model, may incur costs, and uses the normal DSH Agent tools and authorization. It never approves reviews.', {
122
+ requestId, workflowId: identifier('Workflow id in this project.'),
123
+ expectedVersionId: identifier('Optional definition version to bind. Preserve this version and requestId when retrying. If omitted, the Host freezes the version on first creation and reuses its receipt on retry.'),
124
+ text: { type: 'string', description: 'Task input text.' },
125
+ }, ['workflowId', 'text'], async (args, workspace, actor, exec) => {
126
+ inWorkspace(await core.getWorkflow(id(args.workflowId)), workspace)
127
+ // Core resolves receipts before consulting the current definition and freezes
128
+ // an omitted version on first creation. Explicit version pins pass unchanged.
129
+ const request = validateWorkflowCommand('createTask', { ...args, workspaceId: workspace.id,
130
+ requestId: args.requestId === undefined ? randomUUID() : args.requestId })
131
+ exec.signal?.throwIfAborted()
132
+ return inWorkspace(await core.createTask(request, actor), workspace)
133
+ })
134
+ register('workflow_get_task', 'Read task progress and report metadata in the current project. Request includeOutputText only when full reports are needed; stage conversations are available through workflow_get_stage_trace. Human review decisions remain user-only.', {
135
+ taskId: identifier('Task id in the current project.'),
136
+ includeOutputText: { type: 'boolean', description: 'Read full effective report bodies on demand. Default false.' },
137
+ }, ['taskId'], async (args, workspace) => {
138
+ if (args.includeOutputText !== undefined && typeof args.includeOutputText !== 'boolean') invalid()
139
+ const task = inWorkspace(await core.getTask(id(args.taskId)), workspace)
140
+ return args.includeOutputText === true ? core.getTask(task.id, { includeOutputText: true }) : task
141
+ })
142
+ register('workflow_get_stage_trace', 'Read the persisted conversation and measured timings of one Task stage, without resuming its Session. Use workflow_get_task to find stage/attempt ids. Timings include stage elapsed, model response boundaries/first-output waiting, and tool call-to-result intervals; tools may overlap and waiting may include authorization. Missing timings are null. Read the summary first, then page entries with nextFromSeq. Transport headers and connection configuration are omitted.', {
143
+ taskId: identifier('Task id in this project.'), stageId: identifier('Stage id from this Task’s frozen stages, not the latest workflow.'),
144
+ attemptId: identifier('Optional exact execution attempt. Omit for the latest attempt of this stage.'),
145
+ fromSeq: { type: 'integer', minimum: 0, description: 'Optional event cursor; use nextFromSeq for the next page.' },
146
+ limit: { type: 'integer', minimum: 1, maximum: 200, description: 'Conversation entries per page; default 50. Summary covers the whole persisted attempt.' },
147
+ }, ['taskId', 'stageId'], async (args, workspace, _actor, exec) => {
148
+ const taskId = id(args.taskId), stageId = args.stageId
149
+ if (typeof stageId !== 'string' || !/^[a-zA-Z0-9_.-]{1,64}$/.test(stageId)) invalid()
150
+ inWorkspace(await core.getTask(taskId), workspace)
151
+ if (args.attemptId !== undefined) id(args.attemptId)
152
+ return core.getStageTrace({ taskId, stageId, ...(args.attemptId === undefined ? {} : { attemptId: args.attemptId }),
153
+ ...(args.fromSeq === undefined ? {} : { fromSeq: args.fromSeq }), ...(args.limit === undefined ? {} : { limit: args.limit }) }, exec.signal)
154
+ })
155
+ } catch (error) {
156
+ for (const dispose of disposers.reverse()) dispose()
157
+ throw error
158
+ }
159
+ return () => { for (const dispose of disposers.splice(0).reverse()) dispose() }
160
+ }
@@ -0,0 +1,75 @@
1
+ import { execFileSync } from 'node:child_process'
2
+
3
+ export const PROCESS_POLICY = 'single-process-journal/v1'
4
+ const fail = (code, message) => Object.assign(new Error(message), { code })
5
+ const validPid = pid => Number.isSafeInteger(pid) && pid > 1 && pid <= 2147483647
6
+
7
+ /** Read birth metadata only, never process arguments or environment. */
8
+ export function readProcessIdentity(pid) {
9
+ if (!validPid(pid)) throw fail('WF_RECOVERY_UNCONFIRMED', '执行进程的记录无效,不能自动恢复。')
10
+ const exists = () => {
11
+ try { process.kill(pid, 0); return true }
12
+ catch (error) { if (error.code === 'ESRCH') return false; throw fail('WF_RECOVERY_UNCONFIRMED', '无法确认原进程是否已经停止。') }
13
+ }
14
+ if (!exists()) return null
15
+ try {
16
+ const startedAt = execFileSync('/bin/ps', ['-p', String(pid), '-o', 'lstart='], {
17
+ encoding: 'utf8', timeout: 1500, maxBuffer: 4096,
18
+ env: { PATH: '/usr/bin:/bin', LANG: 'C', LC_ALL: 'C', TZ: 'UTC' },
19
+ stdio: ['ignore', 'pipe', 'pipe'],
20
+ }).trim()
21
+ if (!/^[A-Za-z]{3}\s+[A-Za-z]{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4}$/.test(startedAt)) {
22
+ if (!exists()) return null
23
+ throw new Error('Unrecognized process metadata')
24
+ }
25
+ return { pid, startedAt }
26
+ } catch {
27
+ if (!exists()) return null
28
+ throw fail('WF_RECOVERY_UNCONFIRMED', '无法读取可靠的进程启动记录,未执行停止或解锁操作。')
29
+ }
30
+ }
31
+
32
+ /** Only after the original Host is gone can its complete, pre-dispatch journal
33
+ * prove that no additional worker can start. Never treat PID reuse as ownership. */
34
+ export async function confirmStoppedExecution({ attempt, processes, stop = false }, {
35
+ identify = readProcessIdentity, signalProcess = (pid, signal) => process.kill(pid, signal),
36
+ } = {}) {
37
+ const snapshot = attempt.executorSnapshot
38
+ if (snapshot?.stopPolicy !== PROCESS_POLICY || !validPid(snapshot.hostProcess?.pid)
39
+ || typeof snapshot.hostProcess.startedAt !== 'string' || !Array.isArray(processes) || processes.length > 256) {
40
+ throw fail('WF_RECOVERY_UNSUPPORTED', '这次旧执行没有完整的进程安全记录,不能自动释放其工作区。')
41
+ }
42
+ const same = (current, expected) => current?.pid === expected.pid && current.startedAt === expected.startedAt
43
+ if (same(identify(snapshot.hostProcess.pid), snapshot.hostProcess)) {
44
+ throw fail('WF_RECOVERY_RESTART_REQUIRED', '原执行环境仍在运行。请先重启 DSH,再核对旧执行;不会据此直接重跑任务。')
45
+ }
46
+ const remaining = () => processes.filter(entry => {
47
+ if (!validPid(entry.pid) || typeof entry.startedAt !== 'string' || !entry.startedAt) {
48
+ throw fail('WF_RECOVERY_UNCONFIRMED', '进程记录不完整,不能自动恢复。')
49
+ }
50
+ return same(identify(entry.pid), entry)
51
+ })
52
+ const send = (entry, signal) => {
53
+ if (entry.pid === process.pid) throw fail('WF_RECOVERY_UNCONFIRMED', '不能停止当前宿主进程。')
54
+ // Recheck birth identity immediately before every signal, including SIGKILL.
55
+ if (!same(identify(entry.pid), entry)) return
56
+ try { signalProcess(entry.pid, signal) }
57
+ catch (error) { if (error.code !== 'ESRCH') throw fail('WF_RECOVERY_UNCONFIRMED', '原进程暂时无法停止,工作区仍保持占用。') }
58
+ }
59
+ let running = remaining()
60
+ if (running.length && !stop) throw fail('WF_RECOVERY_RUNNING', '原命令仍在运行。请先终止该任务,再重新核对;工作区尚未释放。')
61
+ if (running.length) {
62
+ running.forEach(entry => send(entry, 'SIGTERM'))
63
+ const deadline = Date.now() + 2500
64
+ const forceAt = Date.now() + 750
65
+ let forced = false
66
+ while ((running = remaining()).length && Date.now() < deadline) {
67
+ if (!forced && Date.now() >= forceAt) { running.forEach(entry => send(entry, 'SIGKILL')); forced = true }
68
+ await new Promise(resolve => setTimeout(resolve, 100))
69
+ }
70
+ if (running.length) throw fail('WF_RECOVERY_RUNNING', '原命令尚未确认停止,工作区仍保持占用。请稍后重新核对。')
71
+ }
72
+ return { kind: 'workflow-process-journal', attemptId: attempt.id, sessionId: attempt.sessionId, requestId: attempt.requestId,
73
+ hostProcess: { ...snapshot.hostProcess }, processes: processes.map(item => ({ ...item })),
74
+ hostStopped: true, processesStopped: true, quiescent: true, ownedJobCount: 0 }
75
+ }