workflow-build.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. /**
  2. * CocoFlow 工作流编译器(JS 版,替代技能里原来的 build_workflow.py)
  3. * ---------------------------------------------------------------
  4. * 为什么要有这一份:
  5. * 原来的技能让模型跑 `python3 scripts/build_workflow.py`。老师电脑上没有 Python,
  6. * 尤其是 Windows 机器,这条命令必然失败;就算装了也不一定能叫 python3。
  7. * 编译器本身是纯 JSON 变换(不联网、不读平台数据),搬进插件当工具最省事:
  8. * 模型给方案,客户端直接算完落盘,老师什么都不用装。
  9. *
  10. * 与 Python 版的一致性:
  11. * - 校验规则、节点坐标、锚点、连线控制点、字段默认值、时间戳格式全部照抄;
  12. * - 唯一随机的是节点/连线 id(uuid4),和 Python 版一样每次都不同;
  13. * - 输出用 JSON.stringify(…, 2) + 换行,路径已存在时拒绝覆盖(对应 Python 的 "x" 模式)。
  14. * 已用技能里的三份 examples/plans 与 Python 输出逐字段比对过(id/时间戳归一化后相同)。
  15. */
  16. import fs from 'node:fs'
  17. import path from 'node:path'
  18. import { randomUUID } from 'node:crypto'
  19. export class WorkflowError extends Error {
  20. constructor (message) {
  21. super(message)
  22. this.name = 'WorkflowError'
  23. this.kind = 'plan'
  24. }
  25. }
  26. /** 落盘相关的问题(路径不存在、文件已存在),和"方案写错了"要分开说 */
  27. export class WorkflowIOError extends Error {
  28. constructor (message) {
  29. super(message)
  30. this.name = 'WorkflowIOError'
  31. this.kind = 'io'
  32. }
  33. }
  34. function check (condition, message) {
  35. if (!condition) throw new WorkflowError(message)
  36. }
  37. function isObject (value) {
  38. return value !== null && typeof value === 'object' && !Array.isArray(value)
  39. }
  40. function objectFields (value, allowed, where) {
  41. check(isObject(value), `${where} 必须是对象`)
  42. const allow = new Set(allowed.split(/\s+/))
  43. const unknown = Object.keys(value).filter((k) => !allow.has(k)).sort()
  44. check(unknown.length === 0, `${where} 含未支持字段:${unknown.join(', ')}`)
  45. }
  46. function requiredText (value, where) {
  47. check(typeof value === 'string' && value.trim() !== '', `${where} 必须是非空文本`)
  48. return value.trim()
  49. }
  50. function sameSet (a, b) {
  51. if (a.length !== b.length) return false
  52. const setB = new Set(b)
  53. return a.every((item) => setB.has(item))
  54. }
  55. /** 与 Python 的 datetime.now(timezone.utc).replace(microsecond=0).isoformat() 一致 */
  56. function nowStamp () {
  57. return new Date().toISOString().slice(0, 19)
  58. }
  59. export function validate (plan) {
  60. objectFields(plan, 'schemaVersion name model description opening form steps routes', '方案')
  61. check(Number.isInteger(plan.schemaVersion) && plan.schemaVersion === 1, 'schemaVersion 必须为 1')
  62. requiredText(plan.name, 'name')
  63. requiredText(plan.model, 'model')
  64. for (const key of ['description', 'opening']) {
  65. check(typeof (plan[key] ?? '') === 'string', `${key} 必须是文本`)
  66. }
  67. let options = []
  68. const available = new Set()
  69. if ('form' in plan) {
  70. const form = plan.form
  71. objectFields(form, 'label tip options', 'form')
  72. requiredText(form.label, 'form.label')
  73. check(typeof (form.tip ?? '') === 'string', 'form.tip 必须是文本')
  74. options = form.options ?? []
  75. if ('options' in form) {
  76. check(Array.isArray(options) && options.length > 0, 'form.options 必须是非空数组')
  77. for (const option of options) {
  78. check(option === requiredText(option, '表单选项'), '表单选项首尾不能有空白')
  79. }
  80. check(new Set(options).size === options.length, '表单选项不能重复')
  81. }
  82. available.add('form')
  83. }
  84. check(('steps' in plan) !== ('routes' in plan), '请选择 steps 或 routes 其中之一')
  85. let sequences
  86. if ('routes' in plan) {
  87. const routes = plan.routes
  88. check(options.length >= 2, '分流需要至少两个表单选项')
  89. check(Array.isArray(routes) && routes.length > 0, 'routes 必须是非空数组')
  90. const labels = []
  91. for (const route of routes) {
  92. objectFields(route, 'option steps', '分支')
  93. labels.push(requiredText(route.option, '分支选项'))
  94. check(labels[labels.length - 1] === route.option, '分支选项首尾不能有空白')
  95. }
  96. check(sameSet(labels, options), '分支选项必须与表单选项一一对应')
  97. sequences = routes.map((route) => route.steps)
  98. } else {
  99. sequences = [plan.steps]
  100. }
  101. const used = new Set(['form'])
  102. for (const steps of sequences) {
  103. check(Array.isArray(steps) && steps.length > 0, '每条路径至少需要一个智能体')
  104. const upstream = new Set(available)
  105. for (const step of steps) {
  106. objectFields(step, 'key name prompt reads interactive', '智能体')
  107. const key = requiredText(step.key, '智能体 key')
  108. check(/^[a-z][a-z0-9_]*$/.test(key) && key === step.key && !used.has(key), `无效或重复的 key:${key}`)
  109. const name = requiredText(step.name, `${key}.name`)
  110. check(!/[[\]:]/.test(name), `${key}.name 不能包含方括号或半角冒号`)
  111. requiredText(step.prompt, `${key}.prompt`)
  112. const reads = step.reads ?? []
  113. check(Array.isArray(reads) && reads.every((ref) => typeof ref === 'string'), `${key}.reads 必须是文本数组`)
  114. check(
  115. new Set(reads).size === reads.length && reads.every((ref) => upstream.has(ref)),
  116. `${key}.reads 含重复、跨分支或非前置引用`
  117. )
  118. check(typeof (step.interactive ?? false) === 'boolean', `${key}.interactive 必须是布尔值`)
  119. used.add(key)
  120. upstream.add(key)
  121. }
  122. }
  123. }
  124. export function compileWorkflow (plan) {
  125. validate(plan)
  126. const now = nowStamp()
  127. const nodes = []
  128. const edges = []
  129. const form = isObject(plan.form) ? plan.form : null
  130. const horizontal = form !== null
  131. const node = (kind, column, lane, width, height, properties = {}) => {
  132. const x = horizontal ? 200 + 420 * column : 200
  133. const y = horizontal ? lane : 120 + 160 * column
  134. const result = {
  135. id: ({ start_node: 'node_id_1', end_node: 'node_id_2' })[kind] || randomUUID(),
  136. type: kind,
  137. x,
  138. y,
  139. properties: { width, height, isShowDelete: false, ...properties }
  140. }
  141. nodes.push(result)
  142. return result
  143. }
  144. const edge = (source, target, branch = null) => {
  145. const a = source.id
  146. const b = target.id
  147. let sx = source.x
  148. let sy = source.y
  149. let tx = target.x
  150. let ty = target.y
  151. let outAnchor
  152. let inAnchor
  153. let bends
  154. if (horizontal) {
  155. sx += source.properties.width / 2
  156. tx -= target.properties.width / 2
  157. if (branch) {
  158. const [branchIndex, fieldId] = branch
  159. sy += 75 * (branchIndex - (form.options.length - 1) / 2) + 16.5
  160. outAnchor = fieldId
  161. } else {
  162. outAnchor = `${a}_1`
  163. }
  164. if (target.type === 'boss_card') {
  165. ty -= 16.5
  166. inAnchor = 'boss_left_anchors'
  167. } else {
  168. inAnchor = `${b}_3`
  169. }
  170. bends = [{ x: sx + 100, y: sy }, { x: tx - 100, y: ty }]
  171. } else {
  172. sy += source.properties.height / 2
  173. ty -= target.properties.height / 2
  174. outAnchor = `${a}_2`
  175. inAnchor = `${b}_0`
  176. // CocoFlow 的 boss_edge 即使是一条直线也存两个控制点
  177. bends = [{ x: sx, y: sy + 100 }, { x: tx, y: ty - 100 }]
  178. }
  179. const start = { x: sx, y: sy }
  180. const end = { x: tx, y: ty }
  181. edges.push({
  182. id: randomUUID(),
  183. type: 'boss_edge',
  184. properties: {},
  185. sourceNodeId: a,
  186. targetNodeId: b,
  187. sourceAnchorId: outAnchor,
  188. targetAnchorId: inAnchor,
  189. startPoint: start,
  190. endPoint: end,
  191. pointsList: [start, ...bends, end]
  192. })
  193. }
  194. const start = node('start_node', 0, 240, 146, 50, {
  195. input_value: plan.opening ?? '',
  196. background_img: '',
  197. background_music: '',
  198. autoplay: false,
  199. input_mode: 'text'
  200. })
  201. let preceding = start
  202. const lookup = {}
  203. let firstColumn = 1
  204. if (form !== null) {
  205. const options = form.options
  206. const field = {
  207. key: '选项名称:',
  208. value: form.label.trim(),
  209. id: `form_${randomUUID()}`,
  210. inputValue: '',
  211. is_input: options === undefined || options === null,
  212. options: (options ?? ['']).map((value) => ({ value })),
  213. optioned: []
  214. }
  215. if (options === undefined || options === null) field.input = ''
  216. preceding = node('form_card', 1, 240, 282, 117, {
  217. is_run: false,
  218. tableName: '表单卡片',
  219. tip: form.tip ?? '',
  220. fields: options ? [field] : [],
  221. form_card_data: options ? [] : [field],
  222. content: '',
  223. item: { assistantName: '表单卡片' },
  224. variable_name: 'form_card1',
  225. dispo_arr: []
  226. })
  227. lookup.form = preceding
  228. edge(start, preceding)
  229. firstColumn += 1
  230. }
  231. const appendAgents = (steps, source, column, lane, branch = null) => {
  232. let current = source
  233. for (const [index, step] of steps.entries()) {
  234. const refs = []
  235. for (const key of step.reads ?? []) {
  236. const other = lookup[key]
  237. const props = other.properties
  238. refs.push({
  239. desc: `${props.item.assistantName}:${props.variable_name}`,
  240. id: other.id,
  241. type: other.type,
  242. selected: true
  243. })
  244. }
  245. const item = {
  246. // 导入器靠这个 key 区分内嵌智能体
  247. id: randomUUID(),
  248. assistant_id: '',
  249. thread_id: '',
  250. userId: '',
  251. username: '',
  252. organize_id: '',
  253. parentDataId: null,
  254. appId: null,
  255. vector_store_id: '',
  256. file_ids: '',
  257. file_names: '',
  258. folder_ids: '',
  259. folder_names: '',
  260. assistantName: step.name.trim(),
  261. instructions: step.prompt.trim(),
  262. modelType: plan.model.trim(),
  263. description: '',
  264. prologue: null,
  265. isRetrieval: 0,
  266. isCode: 0,
  267. isGoogle: 0,
  268. isDalleImage: 0,
  269. functionNames: '',
  270. functionContents: '[]',
  271. jsonData: null,
  272. isPublish: 0,
  273. isPublishData: 0,
  274. isDelete: false,
  275. isEditable: true,
  276. isAutoReply: false,
  277. isMuti: true,
  278. inputMode: 'text',
  279. outputMode: 'text',
  280. agent_sort: null,
  281. agent_tag: null,
  282. headUrl: null,
  283. status: 0,
  284. createtime: now,
  285. updatetime: now
  286. }
  287. const agent = node('UserTask', column + index, lane, 255, 75, {
  288. createDate: now,
  289. item,
  290. dispo_desc: refs.map((ref) => `[${ref.desc}]`).join(' '),
  291. dispo_arr: refs,
  292. is_export: true,
  293. is_run: false,
  294. is_switch: true,
  295. content: '',
  296. is_history: true,
  297. variable_name: `output${Object.keys(lookup).length + 1}`,
  298. interaction_model: step.interactive ?? false,
  299. is_mon_agent: false
  300. })
  301. lookup[step.key] = agent
  302. edge(current, agent, index === 0 ? branch : null)
  303. current = agent
  304. }
  305. return current
  306. }
  307. let tails
  308. let endColumn
  309. if ('routes' in plan) {
  310. const fields = form.options.map((option) => ({
  311. key: '条件',
  312. value: option,
  313. id: `boss_${randomUUID()}`
  314. }))
  315. const control = node('boss_card', 2, 240, 250, Math.max(233, 8 + 75 * fields.length), {
  316. tableName: '控制卡片',
  317. variable_name: 'boss_card1',
  318. fields,
  319. is_run: false
  320. })
  321. edge(preceding, control)
  322. const paths = new Map(plan.routes.map((route) => [route.option, route.steps]))
  323. tails = []
  324. fields.forEach((field, index) => {
  325. tails.push(appendAgents(paths.get(field.value), control, 3, 120 + 160 * index, [index, field.id]))
  326. })
  327. endColumn = 3 + Math.max(...[...paths.values()].map((steps) => steps.length))
  328. } else {
  329. tails = [appendAgents(plan.steps, preceding, firstColumn, 240)]
  330. endColumn = firstColumn + plan.steps.length
  331. }
  332. const end = node('end_node', endColumn, 240, 146, 50, { input_value: '终点' })
  333. for (const tail of tails) edge(tail, end)
  334. return {
  335. source: 'muti_agent',
  336. id: '',
  337. userid: '',
  338. organizeid: '',
  339. username: '',
  340. muti_name: plan.name.trim(),
  341. description: plan.description ?? '',
  342. headUrl: '',
  343. create_time: now,
  344. update_time: now,
  345. status: 0,
  346. isEditable: true,
  347. isPublish: 0,
  348. isPublishData: 0,
  349. isDelete: false,
  350. knowledge_construction: 0,
  351. dialoguePublishDataId: null,
  352. cardPublishDataId: null,
  353. immersivePublishDataId: null,
  354. content: { nodes, edges }
  355. }
  356. }
  357. /**
  358. * 编译并落盘。已存在的文件不覆盖(和 Python 版的 "x" 模式一致),
  359. * 避免老师第二次生成时把上一次导入过的文件悄悄换掉。
  360. */
  361. export function buildWorkflowFile (plan, outputPath) {
  362. const target = path.resolve(String(outputPath || '').trim())
  363. if (!outputPath || String(outputPath).trim() === '') throw new WorkflowIOError('outputPath 不能为空')
  364. const dir = path.dirname(target)
  365. if (!fs.existsSync(dir)) throw new WorkflowIOError(`目录不存在:${dir}`)
  366. if (fs.existsSync(target)) throw new WorkflowIOError(`文件已存在,换一个名字再生成:${target}`)
  367. const workflow = compileWorkflow(plan)
  368. const payload = `${JSON.stringify(workflow, null, 2)}\n`
  369. fs.writeFileSync(target, payload, { encoding: 'utf8', flag: 'wx' })
  370. return { path: target, bytes: Buffer.byteLength(payload, 'utf8'), workflow }
  371. }