dsh-workflow-execute 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +36 -2
- package/client/bundle.js +3647 -0
- package/client/index.js +3360 -0
- package/cordis.patch.yml +13 -0
- package/package.json +62 -4
- package/scripts/build-client.mjs +85 -0
- package/scripts/fix-tests.mjs +71 -0
- package/scripts/make-yaml-bundle.mjs +21 -0
- package/scripts/patch-client-comp.mjs +196 -0
- package/scripts/patch-client-exec.mjs +147 -0
- package/scripts/patch-client-i18n.mjs +43 -0
- package/scripts/patch-flow.mjs +205 -0
- package/scripts/yaml-bundle.js +139 -0
- package/src/archive.js +81 -0
- package/src/artifacts.js +263 -0
- package/src/execution.js +746 -0
- package/src/index.js +212 -0
- package/src/prompt.js +24 -0
- package/src/routes.js +324 -0
- package/src/runs.js +237 -0
- package/src/store.js +482 -0
- package/src/tools.js +197 -0
- package/src/validate.js +258 -0
- package/src/zip.js +85 -0
package/src/index.js
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* dsh-workflow-execute — Host half(工作流管理)。
|
|
5
|
+
*
|
|
6
|
+
* 把「工作流」(Process:多阶段·多环节 agent 工作流模板)接进 dsh:
|
|
7
|
+
* - 存储:我的库 ~/.ntd/processes(默认根,可改)+ 内置库 ~/.ntd/bundled/processes(只读),
|
|
8
|
+
* fs.watch 实时同步;根目录可在设置里改(dsh settings 服务,缺席时退回 JSON 文件)。
|
|
9
|
+
* - 路由:/dsh-workflow-execute/*(JSON + SSE),供浏览器半边使用。
|
|
10
|
+
* - 工具:workflow_list / workflow_get / workflow_validate / workflow_save(tools 服务在时注册)。
|
|
11
|
+
* - 提示:systemPrompt 段落(服务在时注册)。
|
|
12
|
+
* - AI 生成:kit 宿主执行器(agents 服务在时可用)。
|
|
13
|
+
*
|
|
14
|
+
* 零 @deepseek-ai/dsh-* 运行时依赖:所有宿主能力都走 ctx.* 服务;schemastery 沿
|
|
15
|
+
* dsh 全局安装的副本加载(settings 服务要求它的 schema 形状)。
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const fsP = require('node:fs/promises')
|
|
19
|
+
const { join, resolve } = require('node:path')
|
|
20
|
+
const { homedir } = require('node:os')
|
|
21
|
+
const { createShareRunJob } = require('@weibaohui/dsh-plugin-kit')
|
|
22
|
+
const { ProcessStore, StoreError } = require('./store.js')
|
|
23
|
+
const { RunStore } = require('./runs.js')
|
|
24
|
+
const { ExecutionService } = require('./execution.js')
|
|
25
|
+
const { parseProcessYaml, validateProcess } = require('./validate.js')
|
|
26
|
+
const { registerRoutes } = require('./routes.js')
|
|
27
|
+
const { registerTools } = require('./tools.js')
|
|
28
|
+
const { SECTION_NAME, SECTION_ORDER, PROCESS_PROTOCOL } = require('./prompt.js')
|
|
29
|
+
|
|
30
|
+
const SETTINGS_NS = 'dsh-workflow-execute'
|
|
31
|
+
|
|
32
|
+
function loadSchemastery() {
|
|
33
|
+
const { createRequire } = require('node:module')
|
|
34
|
+
for (const prefix of [process.env.DSH_GLOBAL_PREFIX, join(homedir(), '.local')].filter(Boolean)) {
|
|
35
|
+
const hostCopy = join(prefix, 'lib', 'node_modules', '@deepseek-ai', 'dsh', 'node_modules', '@deepseek-ai', 'schemastery', 'lib', 'index.cjs')
|
|
36
|
+
try { return createRequire(hostCopy)(hostCopy) } catch { /* 下一个候选 */ }
|
|
37
|
+
}
|
|
38
|
+
try { return require('@deepseek-ai/schemastery') } catch { return null }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function dshHome() { return process.env.DSH_HOME ? resolve(process.env.DSH_HOME) : join(homedir(), '.dsh') }
|
|
42
|
+
/** 工作流库根(rjWorkflow):新名 RJ_WORKFLOW_HOME,旧 NTD_HOME 仍认(迁移兼容)。 */
|
|
43
|
+
function rjWorkflowHome() {
|
|
44
|
+
const raw = process.env.RJ_WORKFLOW_HOME || process.env.NTD_HOME
|
|
45
|
+
return raw ? resolve(raw) : join(homedir(), '.rjWorkflow')
|
|
46
|
+
}
|
|
47
|
+
/** 旧版根目录(~/.ntd),仅用于首次迁移探测。 */
|
|
48
|
+
function legacyNtdHome() { return process.env.NTD_HOME ? resolve(process.env.NTD_HOME) : join(homedir(), '.ntd') }
|
|
49
|
+
|
|
50
|
+
function defaultSettings() {
|
|
51
|
+
return {
|
|
52
|
+
userRoot: join(rjWorkflowHome(), 'workflows'),
|
|
53
|
+
bundledRoot: join(rjWorkflowHome(), 'bundled', 'workflows'),
|
|
54
|
+
maxDepth: 3,
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 库目录迁移:新根不存在、旧 ~/.ntd/processes 有内容时复制过去(只复制,不动旧库)。
|
|
60
|
+
* 返回是否发生过迁移,调用方据此决定是否重扫。
|
|
61
|
+
*/
|
|
62
|
+
async function migrateLegacyRoots(settings, logger) {
|
|
63
|
+
const targets = [
|
|
64
|
+
{ to: settings.userRoot, from: join(legacyNtdHome(), 'processes') },
|
|
65
|
+
{ to: settings.bundledRoot, from: join(legacyNtdHome(), 'bundled', 'processes') },
|
|
66
|
+
]
|
|
67
|
+
let migrated = false
|
|
68
|
+
for (const { to, from } of targets) {
|
|
69
|
+
if (to === from) continue
|
|
70
|
+
try {
|
|
71
|
+
const exists = await fsP.stat(to).then(() => true).catch(() => false)
|
|
72
|
+
if (exists) continue
|
|
73
|
+
const legacy = await fsP.stat(from).then(() => true).catch(() => false)
|
|
74
|
+
if (!legacy) continue
|
|
75
|
+
await fsP.mkdir(join(to, '..'), { recursive: true })
|
|
76
|
+
await fsP.cp(from, to, { recursive: true })
|
|
77
|
+
migrated = true
|
|
78
|
+
logger.info && logger.info(`dsh-workflow-execute: 已把 ${from} 复制到 ${to}`)
|
|
79
|
+
} catch (e) {
|
|
80
|
+
logger.warn && logger.warn(`dsh-workflow-execute: 迁移 ${from} → ${to} 失败:${e && e.message}`)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return migrated
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function sanitizeSettings(patch, base) {
|
|
87
|
+
const next = { ...base }
|
|
88
|
+
if (patch && typeof patch === 'object') {
|
|
89
|
+
if (typeof patch.userRoot === 'string' && patch.userRoot.trim() !== '') next.userRoot = expandHome(patch.userRoot.trim())
|
|
90
|
+
if (typeof patch.bundledRoot === 'string' && patch.bundledRoot.trim() !== '') next.bundledRoot = expandHome(patch.bundledRoot.trim())
|
|
91
|
+
if (Number.isInteger(patch.maxDepth) && patch.maxDepth >= 1 && patch.maxDepth <= 6) next.maxDepth = patch.maxDepth
|
|
92
|
+
}
|
|
93
|
+
return next
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function expandHome(p) {
|
|
97
|
+
return p === '~' ? homedir() : p.startsWith('~/') ? join(homedir(), p.slice(2)) : p
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
module.exports = {
|
|
101
|
+
name: 'dsh-workflow-execute',
|
|
102
|
+
// 静态注入(系列惯例):apply 在这些服务就绪后才运行。动态 ctx.inject(['settings'])
|
|
103
|
+
// 在 apply 内不触发(hermes-loop 记录的平台坑),所以全部静态声明。
|
|
104
|
+
inject: ['webServer', 'tools', 'systemPrompt', 'settings', 'agents', 'agentDefaultModel', 'sessions', 'workspaceRegistry', 'llm', 'skills', 'connection'],
|
|
105
|
+
__test: { defaultSettings, sanitizeSettings, expandHome, migrateLegacyRoots },
|
|
106
|
+
|
|
107
|
+
apply(ctx, rawConfig) {
|
|
108
|
+
const config = rawConfig && typeof rawConfig === 'object' ? rawConfig : {}
|
|
109
|
+
const logger = ctx.logger || console
|
|
110
|
+
const Schema = loadSchemastery()
|
|
111
|
+
|
|
112
|
+
// ── 设置:dsh settings 服务优先,缺席退回 JSON 文件 ──
|
|
113
|
+
const base = sanitizeSettings(config, defaultSettings())
|
|
114
|
+
const fallbackFile = join(dshHome(), 'dsh-workflow-execute', 'settings.json')
|
|
115
|
+
let fileOverrides = {}
|
|
116
|
+
let settingsScope = null
|
|
117
|
+
const settingsSvc = ctx.settings
|
|
118
|
+
if (Schema && settingsSvc && typeof settingsSvc.register === 'function') {
|
|
119
|
+
try {
|
|
120
|
+
settingsScope = settingsSvc.register(SETTINGS_NS, Schema.object({
|
|
121
|
+
userRoot: Schema.string(),
|
|
122
|
+
bundledRoot: Schema.string(),
|
|
123
|
+
maxDepth: Schema.number(),
|
|
124
|
+
}), { base })
|
|
125
|
+
} catch (e) { logger.warn && logger.warn(`dsh-workflow-execute: settings register: ${e && e.message}`) }
|
|
126
|
+
}
|
|
127
|
+
const fileLoaded = fsP.readFile(fallbackFile, 'utf8').then((raw) => { fileOverrides = JSON.parse(raw) || {} }).catch(() => {})
|
|
128
|
+
const settings = {
|
|
129
|
+
get() {
|
|
130
|
+
if (settingsScope && typeof settingsScope.get === 'function') {
|
|
131
|
+
const v = settingsScope.get()
|
|
132
|
+
if (v && typeof v === 'object') return sanitizeSettings(v, base)
|
|
133
|
+
}
|
|
134
|
+
return sanitizeSettings(fileOverrides, base)
|
|
135
|
+
},
|
|
136
|
+
async set(patch) {
|
|
137
|
+
const cur = settings.get()
|
|
138
|
+
const next = sanitizeSettings(patch, cur)
|
|
139
|
+
if (process.env.DSH_WORKFLOW_EXECUTE_SETTINGS_DEBUG) console.error(`[dsh-workflow-execute][set] caller=${String(new Error().stack).split(String.fromCharCode(10))[2]} patch=${JSON.stringify(patch)} cur=${JSON.stringify(cur)} next=${JSON.stringify(next)}`)
|
|
140
|
+
if (settingsScope) {
|
|
141
|
+
if (typeof settingsScope.replace === 'function') await settingsScope.replace(next)
|
|
142
|
+
else if (typeof settingsScope.update === 'function') await settingsScope.update(next)
|
|
143
|
+
if (process.env.DSH_WORKFLOW_EXECUTE_SETTINGS_DEBUG) console.error(`[dsh-workflow-execute][set] after replace scope.get=${JSON.stringify((() => { try { return settingsScope.get() } catch (e) { return String(e) } })())}`)
|
|
144
|
+
} else {
|
|
145
|
+
fileOverrides = next
|
|
146
|
+
await fsP.mkdir(join(fallbackFile, '..'), { recursive: true })
|
|
147
|
+
await fsP.writeFile(fallbackFile, JSON.stringify(next, null, 2), 'utf8')
|
|
148
|
+
}
|
|
149
|
+
return settings.get()
|
|
150
|
+
},
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// ── 存储 ──
|
|
154
|
+
const store = new ProcessStore({
|
|
155
|
+
roots: () => { const s = settings.get(); return { user: s.userRoot, bundled: s.bundledRoot } },
|
|
156
|
+
options: () => ({ maxDepth: settings.get().maxDepth }),
|
|
157
|
+
logger,
|
|
158
|
+
})
|
|
159
|
+
void fileLoaded
|
|
160
|
+
.then(() => migrateLegacyRoots(settings.get(), logger))
|
|
161
|
+
.then(() => { store.startWatch(); return store.load() })
|
|
162
|
+
|
|
163
|
+
// ── 运行台账 + 执行驱动(v0.2)──
|
|
164
|
+
const runs = new RunStore(join(dshHome(), 'dsh-workflow-execute', 'runs.json'), logger)
|
|
165
|
+
const execution = new ExecutionService({ ctx, runs, settings, logger })
|
|
166
|
+
ctx.effect(() => () => { execution.dispose(); store.dispose() }, 'dsh-workflow-execute: store+execution dispose')
|
|
167
|
+
ctx.effect(() => () => { /* runs 的 persist 定时器 unref,无需显式清理 */ }, 'dsh-workflow-execute: runs')
|
|
168
|
+
void runs.load().then(() => execution.tick())
|
|
169
|
+
const createRun = async ({ processId, workspaceId, model, provider, userInput, sessionMode }) => {
|
|
170
|
+
if (runs.byStatus('queued', 'running').length >= 20) throw new StoreError('invalid_input', '排队/运行中的运行过多(上限 20)')
|
|
171
|
+
const item = await store.get(processId)
|
|
172
|
+
const parsed = parseProcessYaml(item.yaml)
|
|
173
|
+
const result = validateProcess(parsed)
|
|
174
|
+
if (result.errors.length > 0) {
|
|
175
|
+
throw new StoreError('invalid', '工作流有校验错误,不能发起运行', { diagnostics: { errors: result.errors, warnings: result.warnings } })
|
|
176
|
+
}
|
|
177
|
+
const snapshot = parsed.data
|
|
178
|
+
const { map } = require('./runs.js').indexLinks(snapshot)
|
|
179
|
+
if (map.size === 0) throw new StoreError('invalid', '工作流没有任何环节,无法运行')
|
|
180
|
+
const run = runs.create({
|
|
181
|
+
processId, workspaceId, model, provider, userInput,
|
|
182
|
+
sessionMode: sessionMode === 'multi' ? 'multi' : 'single',
|
|
183
|
+
processName: result.meta.name || item.meta.name,
|
|
184
|
+
displayName: result.meta.display_name || result.meta.name || item.meta.name,
|
|
185
|
+
snapshotYaml: item.yaml, snapshot,
|
|
186
|
+
})
|
|
187
|
+
execution.tick()
|
|
188
|
+
return run
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// ── AI 生成(kit 宿主执行器:同进程 agents 会话,输出流式可见)──
|
|
192
|
+
const jobs = new Map()
|
|
193
|
+
const runAi = (prompt) => {
|
|
194
|
+
const dir = settings.get().userRoot
|
|
195
|
+
const svc = ctx.agents && ctx.agentDefaultModel ? { agents: ctx.agents, agentDefaultModel: ctx.agentDefaultModel, sessions: ctx.sessions } : undefined
|
|
196
|
+
const job = createShareRunJob({ prompt, dir, jobs, logger, services: svc })
|
|
197
|
+
// 任务表只留最近 50 条
|
|
198
|
+
if (jobs.size > 50) { const oldest = jobs.keys().next().value; jobs.delete(oldest) }
|
|
199
|
+
return job
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ── 路由 ──
|
|
203
|
+
ctx.effect(() => registerRoutes(ctx, { store, settings, jobs, runAi, runs, execution, createRun, logger }), 'dsh-workflow-execute: routes')
|
|
204
|
+
|
|
205
|
+
// ── 工具 / 提示词 ──
|
|
206
|
+
ctx.effect(() => {
|
|
207
|
+
const disposers = registerTools(ctx.tools, { store })
|
|
208
|
+
return () => { for (const d of disposers) { try { d() } catch {} } }
|
|
209
|
+
}, 'dsh-workflow-execute: tools')
|
|
210
|
+
ctx.effect(() => ctx.systemPrompt.section({ name: SECTION_NAME, order: SECTION_ORDER, text: PROCESS_PROTOCOL }), 'dsh-workflow-execute: protocol section')
|
|
211
|
+
},
|
|
212
|
+
}
|
package/src/prompt.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* dsh-workflow-execute — systemPrompt 段落:告诉 agent 工作流库存在、怎么查、按工作流推进的约定。
|
|
5
|
+
* 刻意短(< 40 行),不占上下文。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const SECTION_NAME = 'dsh-workflow-execute'
|
|
9
|
+
const SECTION_ORDER = 620
|
|
10
|
+
|
|
11
|
+
const PROCESS_PROTOCOL = `## 工作流库(dsh-workflow-execute)
|
|
12
|
+
|
|
13
|
+
本环境装有工作流库:「工作流」= Process,一份多阶段(phase)、多环节(link)的 agent 工作流模板。
|
|
14
|
+
用户提到「工作流 / 按工作流执行 / 工作流模板 / process template」时:
|
|
15
|
+
|
|
16
|
+
1. 先 \`workflow_list\` 看有哪些工作流(我的库可写,内置库只读),再 \`workflow_get\` 读结构摘要(outline)。
|
|
17
|
+
2. 按工作流推进:一个环节一个交付。读环节的 prompt / expert / skills / expected_artifacts,做完自检 gates;
|
|
18
|
+
门禁不过按 on_gate_fail 流转(break 停下问用户;<环节 id> 或 goto:<环节 id> 回到该环节),返工不超过 max_rework;
|
|
19
|
+
通过则按 on_success(next / end / <环节 id>)进入下一环节。每个阶段结束对照 acceptance_criteria 汇报。
|
|
20
|
+
3. 新建或修改工作流时先 \`workflow_validate\` 自检,再 \`workflow_save\` 写入我的库;已存在的文件必须显式 overwrite=true 才能覆盖。
|
|
21
|
+
内置库不可写——要改内置工作流,先复制成我的库里的新工作流。
|
|
22
|
+
`
|
|
23
|
+
|
|
24
|
+
module.exports = { SECTION_NAME, SECTION_ORDER, PROCESS_PROTOCOL }
|
package/src/routes.js
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* dsh-workflow-execute — HTTP + SSE 路由(host 侧)。前缀 /dsh-workflow-execute。
|
|
5
|
+
*
|
|
6
|
+
* GET /state 列表快照 {revision, roots, processes[]}
|
|
7
|
+
* GET /item?id= 单条 {meta, yaml, parsed, diagnostics, hash}
|
|
8
|
+
* POST /validate {yaml} {errors[], warnings[], meta}
|
|
9
|
+
* POST /save {mode,...} create / update(baseHash 乐观锁) / copy → 200 | 400 invalid | 409 conflict/exists | 403 readonly
|
|
10
|
+
* POST /rename {id,newName} 改显示名 process.display_name(文件名 / id 不变)
|
|
11
|
+
* POST /delete {id} 移入 .trash
|
|
12
|
+
* POST /import {files,overwrite}
|
|
13
|
+
* GET /export?id= | ?all=1 | ?source=user 单 yaml / zip
|
|
14
|
+
* GET /skeleton?name= 新建空白骨架 yaml
|
|
15
|
+
* GET|POST /settings 根目录与开关
|
|
16
|
+
* GET /models 模型下拉目录 {default, providers[]}(llm 服务缺席降级空)
|
|
17
|
+
* GET /skills dsh 技能目录 {skills[]}(skills 服务缺席降级空)
|
|
18
|
+
* GET /events SSE:hello{revision} / change{revision} / 25s 心跳
|
|
19
|
+
* POST /ai-generate {prompt} → {jobId}(kit 宿主执行器;服务缺席 503)
|
|
20
|
+
* GET /jobs?id= {status, output, code, sessionId}
|
|
21
|
+
* GET /runs 运行列表 {revision, runs[]}
|
|
22
|
+
* GET /run?id= 运行详情(含完整 trail)
|
|
23
|
+
* GET /run-file?run=&path= 产物预览 {file: {content, binary, truncated, size, additions, deletions, diff}}
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
const { StoreError, safeName } = require('./store.js')
|
|
27
|
+
const { runSummary } = require('./runs.js')
|
|
28
|
+
const { readArtifactText, declaredArtifactsOf, resolveDeclaredArtifacts } = require('./artifacts.js')
|
|
29
|
+
const { skeletonYaml } = require('./validate.js')
|
|
30
|
+
const { buildZip } = require('./zip.js')
|
|
31
|
+
const { randomUUID } = require('node:crypto')
|
|
32
|
+
|
|
33
|
+
// 共享事件推送枢纽(@weibaohui/dsh-plugin-kit ≥0.4):库缺席(未安装)时为
|
|
34
|
+
// undefined,广播回退自有 SSE 通道——独立安装不受影响。
|
|
35
|
+
let ensureHostHub
|
|
36
|
+
try { ({ ensureHostHub } = require('@weibaohui/dsh-plugin-kit')) } catch { /* 库缺席 */ }
|
|
37
|
+
|
|
38
|
+
const PREFIX = '/dsh-workflow-execute'
|
|
39
|
+
const MAX_BODY_BYTES = 4 * 1024 * 1024
|
|
40
|
+
const SSE_HEARTBEAT_MS = 25_000
|
|
41
|
+
|
|
42
|
+
const STATUS_BY_CODE = {
|
|
43
|
+
invalid: 400, invalid_input: 400, invalid_name: 400, invalid_path: 400, invalid_id: 400,
|
|
44
|
+
not_found: 404, conflict: 409, exists: 409, readonly: 403, unavailable: 503,
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function sendJson(res, status, payload) {
|
|
48
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
49
|
+
res.end(JSON.stringify(payload))
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function sendError(res, error) {
|
|
53
|
+
const code = error && error.code && STATUS_BY_CODE[error.code] ? error.code : (error instanceof StoreError ? error.code : 'internal')
|
|
54
|
+
const status = STATUS_BY_CODE[code] || 500
|
|
55
|
+
const body = { error: String(error && error.message || error), code }
|
|
56
|
+
if (error && error.diagnostics) body.diagnostics = error.diagnostics
|
|
57
|
+
if (error && error.currentHash) body.currentHash = error.currentHash
|
|
58
|
+
sendJson(res, status, body)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function readJsonBody(req) {
|
|
62
|
+
const chunks = []
|
|
63
|
+
let received = 0
|
|
64
|
+
for await (const chunk of req) {
|
|
65
|
+
received += chunk.length
|
|
66
|
+
if (received > MAX_BODY_BYTES) throw new StoreError('invalid_input', '请求体过大')
|
|
67
|
+
chunks.push(chunk)
|
|
68
|
+
}
|
|
69
|
+
if (chunks.length === 0) return {}
|
|
70
|
+
try { return JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { throw new StoreError('invalid_input', '请求体不是合法 JSON') }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function contentDisposition(filename) {
|
|
74
|
+
const ascii = filename.replace(/[^\x20-\x7e]/g, '_').replace(/"/g, '')
|
|
75
|
+
return `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(filename)}`
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* @param ctx host 上下文(需 webServer)
|
|
80
|
+
* @param deps { store, settings: {get(), set(patch)}, jobs: Map, runAi: (prompt) => job | null, logger }
|
|
81
|
+
* @returns disposer
|
|
82
|
+
*/
|
|
83
|
+
function registerRoutes(ctx, deps) {
|
|
84
|
+
const { store, settings, jobs, runs, logger } = deps
|
|
85
|
+
const clients = new Set()
|
|
86
|
+
|
|
87
|
+
const broadcast = (event, data) => {
|
|
88
|
+
// 共享事件枢纽(dsh-plugin-kit ≥0.4)在就优先发布——页面只占一条 SSE;
|
|
89
|
+
// 库缺席回退自有 SSE 通道。帧形状 {event, data} 与自有 SSE 语义一致。
|
|
90
|
+
try {
|
|
91
|
+
const hub = ensureHostHub && ensureHostHub(ctx, { webServer: ctx.webServer, connection: ctx.connection })
|
|
92
|
+
if (hub && typeof hub.publish === 'function') hub.publish('dsh-workflow-execute', { event, data })
|
|
93
|
+
} catch { /* 枢纽缺席不影响自有通道 */ }
|
|
94
|
+
const frame = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`
|
|
95
|
+
for (const res of clients) { try { res.write(frame) } catch { clients.delete(res) } }
|
|
96
|
+
}
|
|
97
|
+
const sendChange = () => broadcast('change', { revision: store.revision, runsRevision: runs.revision })
|
|
98
|
+
const unsubscribe = store.subscribe(sendChange)
|
|
99
|
+
const unsubscribeRuns = runs.subscribe(sendChange)
|
|
100
|
+
const heartbeat = setInterval(() => {
|
|
101
|
+
for (const res of clients) { try { res.write(': ping\n\n') } catch { clients.delete(res) } }
|
|
102
|
+
}, SSE_HEARTBEAT_MS)
|
|
103
|
+
if (typeof heartbeat.unref === 'function') heartbeat.unref()
|
|
104
|
+
|
|
105
|
+
const sse = (req, res) => {
|
|
106
|
+
res.writeHead(200, {
|
|
107
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
108
|
+
'cache-control': 'no-store, no-transform',
|
|
109
|
+
connection: 'keep-alive',
|
|
110
|
+
'x-accel-buffering': 'no',
|
|
111
|
+
})
|
|
112
|
+
res.write(`event: hello\ndata: ${JSON.stringify({ revision: store.revision })}\n\n`)
|
|
113
|
+
clients.add(res)
|
|
114
|
+
req.on('close', () => { clients.delete(res) })
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const handler = async (req, res) => {
|
|
118
|
+
// 与其它 host 路由一致的信任栅栏:connection 服务的 Host/Origin 检查
|
|
119
|
+
// 加浏览器认证,防止本机任意网页跨站调用。
|
|
120
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
121
|
+
if (rejection !== undefined) {
|
|
122
|
+
res.writeHead(rejection)
|
|
123
|
+
res.end()
|
|
124
|
+
return
|
|
125
|
+
}
|
|
126
|
+
const url = new URL(req.url || '/', 'http://dsh.local')
|
|
127
|
+
const idx = url.pathname.indexOf(PREFIX)
|
|
128
|
+
const sub = (idx >= 0 ? url.pathname.slice(idx + PREFIX.length) : url.pathname).replace(/\/+$/, '') || '/'
|
|
129
|
+
const method = req.method || 'GET'
|
|
130
|
+
try {
|
|
131
|
+
if (sub === '/events' && method === 'GET') return sse(req, res)
|
|
132
|
+
if (sub === '/state' && method === 'GET') {
|
|
133
|
+
if (store.revision === 0) await store.load()
|
|
134
|
+
return sendJson(res, 200, store.snapshot())
|
|
135
|
+
}
|
|
136
|
+
if (sub === '/item' && method === 'GET') {
|
|
137
|
+
const id = url.searchParams.get('id')
|
|
138
|
+
if (!id) throw new StoreError('invalid_input', '缺少 id')
|
|
139
|
+
return sendJson(res, 200, await store.get(id))
|
|
140
|
+
}
|
|
141
|
+
if (sub === '/validate' && method === 'POST') {
|
|
142
|
+
const body = await readJsonBody(req)
|
|
143
|
+
return sendJson(res, 200, await store.validate(body.yaml))
|
|
144
|
+
}
|
|
145
|
+
if (sub === '/save' && method === 'POST') {
|
|
146
|
+
const body = await readJsonBody(req)
|
|
147
|
+
return sendJson(res, 200, await store.save(body))
|
|
148
|
+
}
|
|
149
|
+
if (sub === '/rename' && method === 'POST') {
|
|
150
|
+
const body = await readJsonBody(req)
|
|
151
|
+
return sendJson(res, 200, await store.rename(body.id, body.newName))
|
|
152
|
+
}
|
|
153
|
+
if (sub === '/delete' && method === 'POST') {
|
|
154
|
+
const body = await readJsonBody(req)
|
|
155
|
+
return sendJson(res, 200, await store.remove(body.id))
|
|
156
|
+
}
|
|
157
|
+
if (sub === '/import' && method === 'POST') {
|
|
158
|
+
const body = await readJsonBody(req)
|
|
159
|
+
return sendJson(res, 200, { results: await store.importFiles(body.files, { overwrite: body.overwrite === true }) })
|
|
160
|
+
}
|
|
161
|
+
if (sub === '/skeleton' && method === 'GET') {
|
|
162
|
+
const name = safeName(url.searchParams.get('name') || 'new-process')
|
|
163
|
+
return sendJson(res, 200, { yaml: skeletonYaml({ name, displayName: url.searchParams.get('displayName') || name, guid: randomUUID() }) })
|
|
164
|
+
}
|
|
165
|
+
if (sub === '/export' && method === 'GET') {
|
|
166
|
+
const id = url.searchParams.get('id')
|
|
167
|
+
if (id) {
|
|
168
|
+
const item = await store.get(id)
|
|
169
|
+
res.writeHead(200, { 'content-type': 'application/yaml; charset=utf-8', 'content-disposition': contentDisposition(`${item.meta.fileName}.yaml`), 'cache-control': 'no-store' })
|
|
170
|
+
return res.end(item.yaml)
|
|
171
|
+
}
|
|
172
|
+
const source = url.searchParams.get('source')
|
|
173
|
+
const entries = await store.exportEntries(source ? (e) => e.source === source : undefined)
|
|
174
|
+
if (entries.length === 0) throw new StoreError('not_found', '没有可导出的工作流')
|
|
175
|
+
const zip = buildZip(entries)
|
|
176
|
+
const stamp = new Date().toISOString().slice(0, 10)
|
|
177
|
+
res.writeHead(200, { 'content-type': 'application/zip', 'content-disposition': contentDisposition(`dsh-workflow-execute-${source || 'all'}-${stamp}.zip`), 'content-length': zip.length, 'cache-control': 'no-store' })
|
|
178
|
+
return res.end(zip)
|
|
179
|
+
}
|
|
180
|
+
if (sub === '/settings' && method === 'GET') {
|
|
181
|
+
return sendJson(res, 200, { settings: settings.get(), effectiveRoots: store.roots() })
|
|
182
|
+
}
|
|
183
|
+
if (sub === '/settings' && method === 'POST') {
|
|
184
|
+
const body = await readJsonBody(req)
|
|
185
|
+
const next = await settings.set(body)
|
|
186
|
+
await store.rerootAndReload()
|
|
187
|
+
return sendJson(res, 200, { settings: next, effectiveRoots: store.roots() })
|
|
188
|
+
}
|
|
189
|
+
if (sub === '/workspaces' && method === 'GET') {
|
|
190
|
+
const registry = ctx.workspaceRegistry
|
|
191
|
+
const workspaces = registry && typeof registry.list === 'function'
|
|
192
|
+
? registry.list().map((w) => ({ id: w.id, title: w.title || w.path }))
|
|
193
|
+
: []
|
|
194
|
+
return sendJson(res, 200, { workspaces })
|
|
195
|
+
}
|
|
196
|
+
// GET /models — 模型下拉目录(llm.listProviders + 逐家 listModels;缺席降级空目录;dsh-kb 同款)
|
|
197
|
+
if (sub === '/models' && method === 'GET') {
|
|
198
|
+
const out = { default: null, providers: [] }
|
|
199
|
+
try {
|
|
200
|
+
if (ctx.agentDefaultModel && typeof ctx.agentDefaultModel.currentSelection === 'function')
|
|
201
|
+
out.default = ctx.agentDefaultModel.currentSelection()
|
|
202
|
+
} catch { }
|
|
203
|
+
try {
|
|
204
|
+
const providers = ctx.llm && typeof ctx.llm.listProviders === 'function' ? ctx.llm.listProviders() : []
|
|
205
|
+
for (const p of providers || []) {
|
|
206
|
+
let models = []
|
|
207
|
+
try { models = (await ctx.llm.listModels(p.id)) || [] } catch { }
|
|
208
|
+
out.providers.push({ id: p.id, name: p.name || p.id, models: models.map((m) => ({ id: m.id, name: m.name || m.id })) })
|
|
209
|
+
}
|
|
210
|
+
} catch { }
|
|
211
|
+
return sendJson(res, 200, out)
|
|
212
|
+
}
|
|
213
|
+
// GET /skills — dsh 技能目录(ctx.skills.snapshot;缺席降级空目录)
|
|
214
|
+
if (sub === '/skills' && method === 'GET') {
|
|
215
|
+
const out = []
|
|
216
|
+
try {
|
|
217
|
+
const snapshot = ctx.skills && typeof ctx.skills.snapshot === 'function' ? await ctx.skills.snapshot({}) : null
|
|
218
|
+
for (const s of (snapshot && snapshot.skills) || []) {
|
|
219
|
+
if (s.invocation && s.invocation.modelInvocable === false) continue
|
|
220
|
+
out.push({ name: String(s.name || ''), description: typeof s.description === 'string' ? s.description.slice(0, 120) : '' })
|
|
221
|
+
}
|
|
222
|
+
} catch (e) { logger && logger.warn && logger.warn(`dsh-workflow-execute: skills snapshot: ${e && e.message}`) }
|
|
223
|
+
out.sort((a, b) => a.name.localeCompare(b.name))
|
|
224
|
+
return sendJson(res, 200, { skills: out })
|
|
225
|
+
}
|
|
226
|
+
if (sub === '/runs' && method === 'GET') {
|
|
227
|
+
return sendJson(res, 200, { revision: runs.revision, runs: runs.list().map(runSummary) })
|
|
228
|
+
}
|
|
229
|
+
if (sub === '/run' && method === 'GET') {
|
|
230
|
+
const run = runs.detail(url.searchParams.get('id') || '')
|
|
231
|
+
if (!run) throw new StoreError('not_found', '运行不存在')
|
|
232
|
+
return sendJson(res, 200, { run })
|
|
233
|
+
}
|
|
234
|
+
// GET /run-file?run=&path= — 产物预览(路径须在该运行产物列表内,且落在运行工作区内)
|
|
235
|
+
if (sub === '/run-file' && method === 'GET') {
|
|
236
|
+
const run = runs.get(url.searchParams.get('run') || '')
|
|
237
|
+
if (!run) throw new StoreError('not_found', '运行不存在')
|
|
238
|
+
const artifacts = []
|
|
239
|
+
for (const t of run.trail || []) for (const a of t.artifacts || []) artifacts.push(a)
|
|
240
|
+
const cwd = deps.execution.runCwd(run)
|
|
241
|
+
// 声明过但没观察到写入的产物也要能预览(会话可能用 shell 重定向写文件)
|
|
242
|
+
artifacts.push(...await resolveDeclaredArtifacts({ cwd, declared: declaredArtifactsOf(run.snapshot) }))
|
|
243
|
+
const file = await readArtifactText({ cwd, artifacts, path: url.searchParams.get('path') || '' })
|
|
244
|
+
return sendJson(res, 200, { file })
|
|
245
|
+
}
|
|
246
|
+
// GET /run-link-files?run=&link= — 某环节的产物清单(工作流声明的 ∪ 会话里观察到的),带是否已生成
|
|
247
|
+
if (sub === '/run-link-files' && method === 'GET') {
|
|
248
|
+
const run = runs.get(url.searchParams.get('run') || '')
|
|
249
|
+
if (!run) throw new StoreError('not_found', '运行不存在')
|
|
250
|
+
const linkId = url.searchParams.get('link') || ''
|
|
251
|
+
const cwd = deps.execution.runCwd(run)
|
|
252
|
+
const declared = await resolveDeclaredArtifacts({ cwd, declared: declaredArtifactsOf(run.snapshot, linkId) })
|
|
253
|
+
const seen = new Set()
|
|
254
|
+
const files = []
|
|
255
|
+
for (const a of declared) {
|
|
256
|
+
if (!a || !a.path || seen.has(a.path)) continue
|
|
257
|
+
seen.add(a.path)
|
|
258
|
+
files.push(a)
|
|
259
|
+
}
|
|
260
|
+
for (const t of run.trail || []) {
|
|
261
|
+
if (linkId && t.linkId !== linkId) continue
|
|
262
|
+
for (const a of t.artifacts || []) {
|
|
263
|
+
if (!a || !a.path) continue
|
|
264
|
+
const i = seen.has(a.path) ? files.findIndex((f) => f.path === a.path) : -1
|
|
265
|
+
if (i >= 0) files[i] = { ...files[i], ...a }
|
|
266
|
+
else { seen.add(a.path); files.push(a) }
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return sendJson(res, 200, { files })
|
|
270
|
+
}
|
|
271
|
+
if (sub === '/run-create' && method === 'POST') {
|
|
272
|
+
const body = await readJsonBody(req)
|
|
273
|
+
return sendJson(res, 200, { run: runSummary(await deps.createRun(body)) })
|
|
274
|
+
}
|
|
275
|
+
// POST /run-delete {id} — 删除一条已结束的运行记录
|
|
276
|
+
if (sub === '/run-delete' && method === 'POST') {
|
|
277
|
+
const body = await readJsonBody(req)
|
|
278
|
+
return sendJson(res, 200, await deps.runs.remove(body.id))
|
|
279
|
+
}
|
|
280
|
+
if (sub === '/run-action' && method === 'POST') {
|
|
281
|
+
const body = await readJsonBody(req)
|
|
282
|
+
const actions = {
|
|
283
|
+
pause: () => deps.execution.actionPause(body.id),
|
|
284
|
+
resume: () => deps.execution.actionResume(body.id),
|
|
285
|
+
stop: () => deps.execution.actionStop(body.id),
|
|
286
|
+
'resolve-break': () => deps.execution.actionResolveBreak(body.id, body.decision),
|
|
287
|
+
'skip-link': () => deps.execution.actionSkipLink(body.id, body.linkId),
|
|
288
|
+
'retry-link': () => deps.execution.actionRetryLink(body.id, body.linkId),
|
|
289
|
+
}
|
|
290
|
+
const fn = actions[body.action]
|
|
291
|
+
if (!fn) throw new StoreError('invalid_input', '未知动作 "' + body.action + '"')
|
|
292
|
+
return sendJson(res, 200, { run: runSummary(fn()) })
|
|
293
|
+
}
|
|
294
|
+
if (sub === '/ai-generate' && method === 'POST') {
|
|
295
|
+
if (typeof deps.runAi !== 'function') throw new StoreError('unavailable', '当前组合缺少 agents 服务,无法 AI 生成')
|
|
296
|
+
const body = await readJsonBody(req)
|
|
297
|
+
if (typeof body.prompt !== 'string' || body.prompt.trim() === '') throw new StoreError('invalid_input', '缺少 prompt')
|
|
298
|
+
const job = deps.runAi(body.prompt)
|
|
299
|
+
return sendJson(res, 200, { jobId: job.id })
|
|
300
|
+
}
|
|
301
|
+
if (sub === '/jobs' && method === 'GET') {
|
|
302
|
+
const job = jobs.get(url.searchParams.get('id') || '')
|
|
303
|
+
if (!job) throw new StoreError('not_found', '任务不存在')
|
|
304
|
+
return sendJson(res, 200, { status: job.status, output: job.output, code: job.code, sessionId: job.sessionId })
|
|
305
|
+
}
|
|
306
|
+
sendJson(res, 404, { error: 'not found', code: 'not_found' })
|
|
307
|
+
} catch (error) {
|
|
308
|
+
if (!(error instanceof StoreError) && logger && logger.warn) logger.warn(`dsh-workflow-execute: ${method} ${sub}: ${error && error.stack || error}`)
|
|
309
|
+
sendError(res, error)
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const disposeRoute = ctx.webServer.register({ kind: 'prefix', path: PREFIX, handler })
|
|
314
|
+
return () => {
|
|
315
|
+
unsubscribe()
|
|
316
|
+
unsubscribeRuns()
|
|
317
|
+
clearInterval(heartbeat)
|
|
318
|
+
for (const res of clients) { try { res.end() } catch {} }
|
|
319
|
+
clients.clear()
|
|
320
|
+
if (typeof disposeRoute === 'function') disposeRoute()
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
module.exports = { registerRoutes, PREFIX, readJsonBody, sendJson, sendError }
|