@alpacachen/dsh-kanban 1.11.3 → 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.
- 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 +85 -0
- package/docs/workflow-model.schema.sql +303 -0
- package/docs/workflow-validation.md +82 -0
- package/lib/client.js +989 -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 +348 -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
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
export const WORKFLOW_REVIEW_NAMESPACE = 'workflowReview'
|
|
2
|
+
|
|
3
|
+
const USER_ACTOR = Object.freeze({ kind: 'user', id: 'owner', source: 'workflow-review-ui' })
|
|
4
|
+
const ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/
|
|
5
|
+
const HASH = /^(?:sha256:)?[a-f0-9]{64}$/
|
|
6
|
+
const DECISIONS = new Set(['approved', 'returned', 'terminated'])
|
|
7
|
+
const REVIEW_FIELDS = new Set([
|
|
8
|
+
'taskId', 'reviewId', 'subjectHash', 'expectedRevision', 'requestId', 'decision', 'feedback',
|
|
9
|
+
])
|
|
10
|
+
|
|
11
|
+
const COMMAND_FIELDS = {
|
|
12
|
+
createTask: ['requestId', 'workspaceId', 'workflowId', 'expectedVersionId', 'title', 'text', 'modelSelection'],
|
|
13
|
+
terminateTask: ['requestId', 'taskId', 'expectedRevision', 'confirmedStopped'],
|
|
14
|
+
deleteTask: ['requestId', 'taskId', 'expectedRevision'],
|
|
15
|
+
deleteTaskFile: ['requestId', 'taskId', 'path', 'expectedVersion'],
|
|
16
|
+
retryTask: ['requestId', 'taskId', 'expectedRevision'],
|
|
17
|
+
reconcileTask: ['requestId', 'taskId', 'expectedRevision', 'confirmedStopped'],
|
|
18
|
+
createWorkflow: ['requestId', 'workspaceId', 'name', 'definition'],
|
|
19
|
+
updateWorkflow: ['requestId', 'workflowId', 'expectedRevision', 'name', 'definition'],
|
|
20
|
+
deleteWorkflow: ['requestId', 'workflowId', 'expectedRevision'],
|
|
21
|
+
}
|
|
22
|
+
const commandInvalid = () => {
|
|
23
|
+
throw Object.assign(new Error('Invalid workflow request.'), { code: 'WF_INVALID_INPUT' })
|
|
24
|
+
}
|
|
25
|
+
const commandObject = (value, allowed) => {
|
|
26
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)
|
|
27
|
+
|| ![Object.prototype, null].includes(Object.getPrototypeOf(value))
|
|
28
|
+
|| Reflect.ownKeys(value).some(key => !allowed.includes(key)
|
|
29
|
+
|| !Object.prototype.hasOwnProperty.call(Object.getOwnPropertyDescriptor(value, key), 'value'))) commandInvalid()
|
|
30
|
+
return value
|
|
31
|
+
}
|
|
32
|
+
const commandId = (value) => {
|
|
33
|
+
if (typeof value !== 'string' || !ID.test(value)) commandInvalid()
|
|
34
|
+
return value
|
|
35
|
+
}
|
|
36
|
+
const commandText = (value, max, allowEmpty = false) => {
|
|
37
|
+
if (typeof value !== 'string' || value.length > max || (!allowEmpty && !value.trim())) commandInvalid()
|
|
38
|
+
return value
|
|
39
|
+
}
|
|
40
|
+
const commandSelection = (value) => {
|
|
41
|
+
const selection = commandObject(value, ['provider', 'model', 'reasoningEffort'])
|
|
42
|
+
commandText(selection.provider, 200)
|
|
43
|
+
commandText(selection.model, 200)
|
|
44
|
+
if (selection.reasoningEffort !== undefined) commandText(selection.reasoningEffort, 80, true)
|
|
45
|
+
return { ...selection }
|
|
46
|
+
}
|
|
47
|
+
const commandDefinition = (value) => {
|
|
48
|
+
const definition = commandObject(value, ['description', 'inputLabel', 'inputHint', 'stages', 'permissions'])
|
|
49
|
+
for (const [field, max] of [['description', 4000], ['inputLabel', 200], ['inputHint', 4000]]) {
|
|
50
|
+
if (definition[field] !== undefined) commandText(definition[field], max, true)
|
|
51
|
+
}
|
|
52
|
+
// The store validates complete stage definitions before saving.
|
|
53
|
+
if (!Array.isArray(definition.stages) || definition.stages.length > 16) commandInvalid()
|
|
54
|
+
// Accept the obsolete key from older clients, but it no longer grants or denies tools.
|
|
55
|
+
try {
|
|
56
|
+
if (JSON.stringify(definition).length > 2 * 1024 * 1024) commandInvalid()
|
|
57
|
+
} catch { commandInvalid() }
|
|
58
|
+
const { permissions: _obsoletePermissions, ...current } = definition
|
|
59
|
+
return current
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Input validation only: it neither grants authority nor makes user-only commands agent-callable. */
|
|
63
|
+
export function validateWorkflowCommand(method, value) {
|
|
64
|
+
if (typeof method !== 'string' || !Object.prototype.hasOwnProperty.call(COMMAND_FIELDS, method)) commandInvalid()
|
|
65
|
+
const request = commandObject(value, COMMAND_FIELDS[method])
|
|
66
|
+
const parsed = {}
|
|
67
|
+
// Generation is a read-only preview, so it may omit an idempotency key.
|
|
68
|
+
parsed.requestId = commandId(request.requestId)
|
|
69
|
+
if (COMMAND_FIELDS[method].includes('workspaceId')) parsed.workspaceId = commandId(request.workspaceId)
|
|
70
|
+
if (COMMAND_FIELDS[method].includes('workflowId') && (method !== 'createTask' || request.workflowId !== undefined)) {
|
|
71
|
+
parsed.workflowId = commandId(request.workflowId)
|
|
72
|
+
}
|
|
73
|
+
if (COMMAND_FIELDS[method].includes('taskId')) parsed.taskId = commandId(request.taskId)
|
|
74
|
+
if (COMMAND_FIELDS[method].includes('expectedRevision')) {
|
|
75
|
+
if (!Number.isSafeInteger(request.expectedRevision) || request.expectedRevision < 1) commandInvalid()
|
|
76
|
+
parsed.expectedRevision = request.expectedRevision
|
|
77
|
+
}
|
|
78
|
+
if (request.confirmedStopped !== undefined) {
|
|
79
|
+
if (typeof request.confirmedStopped !== 'boolean') commandInvalid()
|
|
80
|
+
parsed.confirmedStopped = request.confirmedStopped
|
|
81
|
+
}
|
|
82
|
+
if (method === 'deleteTaskFile') { parsed.path = commandText(request.path, 10000); parsed.expectedVersion = commandText(request.expectedVersion, 300) }
|
|
83
|
+
if (method === 'createTask') {
|
|
84
|
+
if (request.expectedVersionId !== undefined) parsed.expectedVersionId = commandId(request.expectedVersionId)
|
|
85
|
+
parsed.text = commandText(request.text, Infinity)
|
|
86
|
+
parsed.title = request.title === undefined ? parsed.text.trim().slice(0, 200) : commandText(request.title, 200)
|
|
87
|
+
// Accepted for old clients; new tasks resolve models from the workflow stages.
|
|
88
|
+
if (request.modelSelection !== undefined) parsed.modelSelection = commandSelection(request.modelSelection)
|
|
89
|
+
}
|
|
90
|
+
if (method === 'createWorkflow' || method === 'updateWorkflow') {
|
|
91
|
+
parsed.name = commandText(request.name, 200)
|
|
92
|
+
parsed.definition = commandDefinition(request.definition)
|
|
93
|
+
}
|
|
94
|
+
return parsed
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Mount browser-only Remote methods over the shared DSH Gateway, not a new HTTP route.
|
|
99
|
+
* `protocol` is the installed public @deepseek-ai/dsh-typert-protocol module supplied
|
|
100
|
+
* by the Host entry. This file neither resolves packages nor registers Agent tools.
|
|
101
|
+
*
|
|
102
|
+
* Client calls: connection.rpc.call('/api', 'workflowReview/decideReview',
|
|
103
|
+
* { args: { request: { taskId, reviewId, subjectHash, expectedRevision,
|
|
104
|
+
* requestId, decision, feedback } } })
|
|
105
|
+
* Other methods: getTask with { args: { taskId } }, listTasks with { args: {} }.
|
|
106
|
+
*
|
|
107
|
+
* Core owns transactions, authorization of the review subject, state transitions,
|
|
108
|
+
* idempotency and persistence. Its WF_* errors must contain user-safe messages.
|
|
109
|
+
* Browser-peer admission is not proof of a physical click or a full-access sandbox.
|
|
110
|
+
* Returns the Cordis plugin fiber; its owner disposes it with the surrounding plugin.
|
|
111
|
+
*/
|
|
112
|
+
export function mountWorkflowReviewApi(ctx, core, protocol) {
|
|
113
|
+
const { Remote, RemoteError, TypertRemoteService } = protocol
|
|
114
|
+
for (const method of ['decideReview', 'getTask', 'listTasks']) {
|
|
115
|
+
if (typeof core?.[method] !== 'function') throw new TypeError(`Workflow core requires ${method}`)
|
|
116
|
+
}
|
|
117
|
+
if ([Remote, RemoteError, TypertRemoteService].some(value => typeof value !== 'function')) {
|
|
118
|
+
throw new TypeError('Workflow review API requires the installed Typert protocol')
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const invalid = (field) => {
|
|
122
|
+
throw new RemoteError('workflow/invalid-input', 'Invalid workflow review request.', { field })
|
|
123
|
+
}
|
|
124
|
+
const id = (value, field) => {
|
|
125
|
+
if (typeof value !== 'string' || !ID.test(value)) invalid(field)
|
|
126
|
+
return value
|
|
127
|
+
}
|
|
128
|
+
const parseReview = (value) => {
|
|
129
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)
|
|
130
|
+
|| ![Object.prototype, null].includes(Object.getPrototypeOf(value))) invalid('request')
|
|
131
|
+
if (Reflect.ownKeys(value).some(key => !REVIEW_FIELDS.has(key))) invalid('request')
|
|
132
|
+
const { taskId, reviewId, subjectHash, expectedRevision, requestId, decision, feedback = '' } = value
|
|
133
|
+
if (typeof subjectHash !== 'string' || !HASH.test(subjectHash)) invalid('subjectHash')
|
|
134
|
+
if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) invalid('expectedRevision')
|
|
135
|
+
if (!DECISIONS.has(decision)) invalid('decision')
|
|
136
|
+
if (typeof feedback !== 'string' || feedback.length > 10000
|
|
137
|
+
|| (decision === 'returned' && !feedback.trim())) invalid('feedback')
|
|
138
|
+
return {
|
|
139
|
+
taskId: id(taskId, 'taskId'),
|
|
140
|
+
reviewId: id(reviewId, 'reviewId'),
|
|
141
|
+
subjectHash,
|
|
142
|
+
expectedRevision,
|
|
143
|
+
requestId: id(requestId, 'requestId'),
|
|
144
|
+
decision,
|
|
145
|
+
feedback,
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const admit = (callCtx, method) => {
|
|
150
|
+
const invocation = callCtx.invocation
|
|
151
|
+
const browserPeer = callCtx.connection.browserPeer
|
|
152
|
+
if (!invocation || !browserPeer || invocation.peer !== browserPeer
|
|
153
|
+
|| browserPeer.principal?.kind !== 'owner'
|
|
154
|
+
|| browserPeer.signal?.aborted !== false
|
|
155
|
+
|| invocation.service !== WORKFLOW_REVIEW_NAMESPACE
|
|
156
|
+
|| invocation.request?.namespace !== WORKFLOW_REVIEW_NAMESPACE
|
|
157
|
+
|| invocation.request?.method !== method) {
|
|
158
|
+
throw new RemoteError('workflow/browser-required', 'This operation requires the authenticated Workflow UI.', {})
|
|
159
|
+
}
|
|
160
|
+
if (invocation.signal?.aborted !== false) {
|
|
161
|
+
throw new RemoteError('workflow/cancelled', 'The workflow request was cancelled.', {})
|
|
162
|
+
}
|
|
163
|
+
return USER_ACTOR
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const invokeCore = async (operation, ...args) => {
|
|
167
|
+
try {
|
|
168
|
+
return await core[operation](...args)
|
|
169
|
+
} catch (error) {
|
|
170
|
+
// Only core's documented, user-safe business errors cross the boundary.
|
|
171
|
+
if (typeof error?.code === 'string' && /^WF_[A-Z][A-Z0-9_]{0,79}$/.test(error.code)
|
|
172
|
+
&& typeof error.message === 'string' && error.message.length <= 2000) {
|
|
173
|
+
throw new RemoteError(`workflow/${error.code.slice(3).toLowerCase().replaceAll('_', '-')}`,
|
|
174
|
+
error.message, { code: error.code })
|
|
175
|
+
}
|
|
176
|
+
throw new RemoteError('workflow/internal', 'The workflow operation could not be completed.', {})
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const parseCommand = (method, request) => {
|
|
181
|
+
try { return validateWorkflowCommand(method, request) } catch { invalid('request') }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const initializers = []
|
|
185
|
+
class WorkflowReviewApi extends TypertRemoteService {
|
|
186
|
+
static inject = ['connection', 'typertGateway']
|
|
187
|
+
|
|
188
|
+
constructor(serviceCtx) {
|
|
189
|
+
super(serviceCtx, WORKFLOW_REVIEW_NAMESPACE)
|
|
190
|
+
for (const initialize of initializers) initialize.call(this)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async decideReview(request) {
|
|
194
|
+
const actor = admit(this.ctx, 'decideReview')
|
|
195
|
+
return invokeCore('decideReview', parseReview(request), actor)
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async getTask(taskId) {
|
|
199
|
+
admit(this.ctx, 'getTask')
|
|
200
|
+
return invokeCore('getTask', id(taskId, 'taskId'))
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async listTasks(workspaceId) {
|
|
204
|
+
admit(this.ctx, 'listTasks')
|
|
205
|
+
return workspaceId === undefined ? invokeCore('listTasks') : invokeCore('listTasks', id(workspaceId, 'workspaceId'))
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async createTask(request) {
|
|
209
|
+
const actor = admit(this.ctx, 'createTask')
|
|
210
|
+
return invokeCore('createTask', parseCommand('createTask', request), actor)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async terminateTask(request) {
|
|
214
|
+
const actor = admit(this.ctx, 'terminateTask')
|
|
215
|
+
return invokeCore('terminateTask', parseCommand('terminateTask', request), actor)
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async retryTask(request) {
|
|
219
|
+
const actor = admit(this.ctx, 'retryTask')
|
|
220
|
+
return invokeCore('retryTask', parseCommand('retryTask', request), actor)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async reconcileTask(request) {
|
|
224
|
+
const actor = admit(this.ctx, 'reconcileTask')
|
|
225
|
+
// Only Host core may collect OS evidence and decide whether recovery is safe.
|
|
226
|
+
return invokeCore('reconcileTask', parseCommand('reconcileTask', request), actor)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async listWorkflows(workspaceId) {
|
|
230
|
+
admit(this.ctx, 'listWorkflows')
|
|
231
|
+
return invokeCore('listWorkflows', id(workspaceId, 'workspaceId'))
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async getWorkflow(workflowId) {
|
|
235
|
+
admit(this.ctx, 'getWorkflow')
|
|
236
|
+
return invokeCore('getWorkflow', id(workflowId, 'workflowId'))
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async getTaskFiles(taskId) {
|
|
240
|
+
admit(this.ctx, 'getTaskFiles')
|
|
241
|
+
return invokeCore('getTaskFiles', id(taskId, 'taskId'))
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async getTaskFile(taskId, path) {
|
|
245
|
+
admit(this.ctx, 'getTaskFile')
|
|
246
|
+
if (typeof path !== 'string' || !path || path.length > 10000) invalid('path')
|
|
247
|
+
return invokeCore('getTaskFile', id(taskId, 'taskId'), path)
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async getArtifact(taskId, artifactId) {
|
|
251
|
+
admit(this.ctx, 'getArtifact')
|
|
252
|
+
return invokeCore('getArtifact', id(taskId, 'taskId'), id(artifactId, 'artifactId'))
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
async createWorkflow(request) {
|
|
257
|
+
const actor = admit(this.ctx, 'createWorkflow')
|
|
258
|
+
return invokeCore('createWorkflow', parseCommand('createWorkflow', request), actor)
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async updateWorkflow(request) {
|
|
262
|
+
const actor = admit(this.ctx, 'updateWorkflow')
|
|
263
|
+
return invokeCore('updateWorkflow', parseCommand('updateWorkflow', request), actor)
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
async deleteTaskFile(request) {
|
|
268
|
+
const actor = admit(this.ctx, 'deleteTaskFile')
|
|
269
|
+
return invokeCore('deleteTaskFile', parseCommand('deleteTaskFile', request), actor)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async deleteTask(request) {
|
|
273
|
+
const actor = admit(this.ctx, 'deleteTask')
|
|
274
|
+
return invokeCore('deleteTask', parseCommand('deleteTask', request), actor)
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async deleteWorkflow(request) {
|
|
278
|
+
const actor = admit(this.ctx, 'deleteWorkflow')
|
|
279
|
+
return invokeCore('deleteWorkflow', parseCommand('deleteWorkflow', request), actor)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// Invoke the public standard decorator API from plain ESM; do not copy private markers.
|
|
285
|
+
const methods = ['decideReview', 'getTask', 'listTasks']
|
|
286
|
+
for (const name of [...Object.keys(COMMAND_FIELDS), 'listWorkflows', 'getWorkflow', 'getArtifact', 'getTaskFiles', 'getTaskFile']) {
|
|
287
|
+
if (typeof core[name] === 'function') methods.push(name)
|
|
288
|
+
}
|
|
289
|
+
for (const name of methods) {
|
|
290
|
+
Remote(WorkflowReviewApi.prototype[name], {
|
|
291
|
+
kind: 'method', name, private: false, static: false,
|
|
292
|
+
addInitializer(initialize) { initializers.push(initialize) },
|
|
293
|
+
})
|
|
294
|
+
}
|
|
295
|
+
return ctx.plugin(WorkflowReviewApi)
|
|
296
|
+
}
|