| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395 |
- /**
- * CocoFlow 工作流编译器(JS 版,替代技能里原来的 build_workflow.py)
- * ---------------------------------------------------------------
- * 为什么要有这一份:
- * 原来的技能让模型跑 `python3 scripts/build_workflow.py`。老师电脑上没有 Python,
- * 尤其是 Windows 机器,这条命令必然失败;就算装了也不一定能叫 python3。
- * 编译器本身是纯 JSON 变换(不联网、不读平台数据),搬进插件当工具最省事:
- * 模型给方案,客户端直接算完落盘,老师什么都不用装。
- *
- * 与 Python 版的一致性:
- * - 校验规则、节点坐标、锚点、连线控制点、字段默认值、时间戳格式全部照抄;
- * - 唯一随机的是节点/连线 id(uuid4),和 Python 版一样每次都不同;
- * - 输出用 JSON.stringify(…, 2) + 换行,路径已存在时拒绝覆盖(对应 Python 的 "x" 模式)。
- * 已用技能里的三份 examples/plans 与 Python 输出逐字段比对过(id/时间戳归一化后相同)。
- */
- import fs from 'node:fs'
- import path from 'node:path'
- import { randomUUID } from 'node:crypto'
- export class WorkflowError extends Error {
- constructor (message) {
- super(message)
- this.name = 'WorkflowError'
- this.kind = 'plan'
- }
- }
- /** 落盘相关的问题(路径不存在、文件已存在),和"方案写错了"要分开说 */
- export class WorkflowIOError extends Error {
- constructor (message) {
- super(message)
- this.name = 'WorkflowIOError'
- this.kind = 'io'
- }
- }
- function check (condition, message) {
- if (!condition) throw new WorkflowError(message)
- }
- function isObject (value) {
- return value !== null && typeof value === 'object' && !Array.isArray(value)
- }
- function objectFields (value, allowed, where) {
- check(isObject(value), `${where} 必须是对象`)
- const allow = new Set(allowed.split(/\s+/))
- const unknown = Object.keys(value).filter((k) => !allow.has(k)).sort()
- check(unknown.length === 0, `${where} 含未支持字段:${unknown.join(', ')}`)
- }
- function requiredText (value, where) {
- check(typeof value === 'string' && value.trim() !== '', `${where} 必须是非空文本`)
- return value.trim()
- }
- function sameSet (a, b) {
- if (a.length !== b.length) return false
- const setB = new Set(b)
- return a.every((item) => setB.has(item))
- }
- /** 与 Python 的 datetime.now(timezone.utc).replace(microsecond=0).isoformat() 一致 */
- function nowStamp () {
- return new Date().toISOString().slice(0, 19)
- }
- export function validate (plan) {
- objectFields(plan, 'schemaVersion name model description opening form steps routes', '方案')
- check(Number.isInteger(plan.schemaVersion) && plan.schemaVersion === 1, 'schemaVersion 必须为 1')
- requiredText(plan.name, 'name')
- requiredText(plan.model, 'model')
- for (const key of ['description', 'opening']) {
- check(typeof (plan[key] ?? '') === 'string', `${key} 必须是文本`)
- }
- let options = []
- const available = new Set()
- if ('form' in plan) {
- const form = plan.form
- objectFields(form, 'label tip options', 'form')
- requiredText(form.label, 'form.label')
- check(typeof (form.tip ?? '') === 'string', 'form.tip 必须是文本')
- options = form.options ?? []
- if ('options' in form) {
- check(Array.isArray(options) && options.length > 0, 'form.options 必须是非空数组')
- for (const option of options) {
- check(option === requiredText(option, '表单选项'), '表单选项首尾不能有空白')
- }
- check(new Set(options).size === options.length, '表单选项不能重复')
- }
- available.add('form')
- }
- check(('steps' in plan) !== ('routes' in plan), '请选择 steps 或 routes 其中之一')
- let sequences
- if ('routes' in plan) {
- const routes = plan.routes
- check(options.length >= 2, '分流需要至少两个表单选项')
- check(Array.isArray(routes) && routes.length > 0, 'routes 必须是非空数组')
- const labels = []
- for (const route of routes) {
- objectFields(route, 'option steps', '分支')
- labels.push(requiredText(route.option, '分支选项'))
- check(labels[labels.length - 1] === route.option, '分支选项首尾不能有空白')
- }
- check(sameSet(labels, options), '分支选项必须与表单选项一一对应')
- sequences = routes.map((route) => route.steps)
- } else {
- sequences = [plan.steps]
- }
- const used = new Set(['form'])
- for (const steps of sequences) {
- check(Array.isArray(steps) && steps.length > 0, '每条路径至少需要一个智能体')
- const upstream = new Set(available)
- for (const step of steps) {
- objectFields(step, 'key name prompt reads interactive', '智能体')
- const key = requiredText(step.key, '智能体 key')
- check(/^[a-z][a-z0-9_]*$/.test(key) && key === step.key && !used.has(key), `无效或重复的 key:${key}`)
- const name = requiredText(step.name, `${key}.name`)
- check(!/[[\]:]/.test(name), `${key}.name 不能包含方括号或半角冒号`)
- requiredText(step.prompt, `${key}.prompt`)
- const reads = step.reads ?? []
- check(Array.isArray(reads) && reads.every((ref) => typeof ref === 'string'), `${key}.reads 必须是文本数组`)
- check(
- new Set(reads).size === reads.length && reads.every((ref) => upstream.has(ref)),
- `${key}.reads 含重复、跨分支或非前置引用`
- )
- check(typeof (step.interactive ?? false) === 'boolean', `${key}.interactive 必须是布尔值`)
- used.add(key)
- upstream.add(key)
- }
- }
- }
- export function compileWorkflow (plan) {
- validate(plan)
- const now = nowStamp()
- const nodes = []
- const edges = []
- const form = isObject(plan.form) ? plan.form : null
- const horizontal = form !== null
- const node = (kind, column, lane, width, height, properties = {}) => {
- const x = horizontal ? 200 + 420 * column : 200
- const y = horizontal ? lane : 120 + 160 * column
- const result = {
- id: ({ start_node: 'node_id_1', end_node: 'node_id_2' })[kind] || randomUUID(),
- type: kind,
- x,
- y,
- properties: { width, height, isShowDelete: false, ...properties }
- }
- nodes.push(result)
- return result
- }
- const edge = (source, target, branch = null) => {
- const a = source.id
- const b = target.id
- let sx = source.x
- let sy = source.y
- let tx = target.x
- let ty = target.y
- let outAnchor
- let inAnchor
- let bends
- if (horizontal) {
- sx += source.properties.width / 2
- tx -= target.properties.width / 2
- if (branch) {
- const [branchIndex, fieldId] = branch
- sy += 75 * (branchIndex - (form.options.length - 1) / 2) + 16.5
- outAnchor = fieldId
- } else {
- outAnchor = `${a}_1`
- }
- if (target.type === 'boss_card') {
- ty -= 16.5
- inAnchor = 'boss_left_anchors'
- } else {
- inAnchor = `${b}_3`
- }
- bends = [{ x: sx + 100, y: sy }, { x: tx - 100, y: ty }]
- } else {
- sy += source.properties.height / 2
- ty -= target.properties.height / 2
- outAnchor = `${a}_2`
- inAnchor = `${b}_0`
- // CocoFlow 的 boss_edge 即使是一条直线也存两个控制点
- bends = [{ x: sx, y: sy + 100 }, { x: tx, y: ty - 100 }]
- }
- const start = { x: sx, y: sy }
- const end = { x: tx, y: ty }
- edges.push({
- id: randomUUID(),
- type: 'boss_edge',
- properties: {},
- sourceNodeId: a,
- targetNodeId: b,
- sourceAnchorId: outAnchor,
- targetAnchorId: inAnchor,
- startPoint: start,
- endPoint: end,
- pointsList: [start, ...bends, end]
- })
- }
- const start = node('start_node', 0, 240, 146, 50, {
- input_value: plan.opening ?? '',
- background_img: '',
- background_music: '',
- autoplay: false,
- input_mode: 'text'
- })
- let preceding = start
- const lookup = {}
- let firstColumn = 1
- if (form !== null) {
- const options = form.options
- const field = {
- key: '选项名称:',
- value: form.label.trim(),
- id: `form_${randomUUID()}`,
- inputValue: '',
- is_input: options === undefined || options === null,
- options: (options ?? ['']).map((value) => ({ value })),
- optioned: []
- }
- if (options === undefined || options === null) field.input = ''
- preceding = node('form_card', 1, 240, 282, 117, {
- is_run: false,
- tableName: '表单卡片',
- tip: form.tip ?? '',
- fields: options ? [field] : [],
- form_card_data: options ? [] : [field],
- content: '',
- item: { assistantName: '表单卡片' },
- variable_name: 'form_card1',
- dispo_arr: []
- })
- lookup.form = preceding
- edge(start, preceding)
- firstColumn += 1
- }
- const appendAgents = (steps, source, column, lane, branch = null) => {
- let current = source
- for (const [index, step] of steps.entries()) {
- const refs = []
- for (const key of step.reads ?? []) {
- const other = lookup[key]
- const props = other.properties
- refs.push({
- desc: `${props.item.assistantName}:${props.variable_name}`,
- id: other.id,
- type: other.type,
- selected: true
- })
- }
- const item = {
- // 导入器靠这个 key 区分内嵌智能体
- id: randomUUID(),
- assistant_id: '',
- thread_id: '',
- userId: '',
- username: '',
- organize_id: '',
- parentDataId: null,
- appId: null,
- vector_store_id: '',
- file_ids: '',
- file_names: '',
- folder_ids: '',
- folder_names: '',
- assistantName: step.name.trim(),
- instructions: step.prompt.trim(),
- modelType: plan.model.trim(),
- description: '',
- prologue: null,
- isRetrieval: 0,
- isCode: 0,
- isGoogle: 0,
- isDalleImage: 0,
- functionNames: '',
- functionContents: '[]',
- jsonData: null,
- isPublish: 0,
- isPublishData: 0,
- isDelete: false,
- isEditable: true,
- isAutoReply: false,
- isMuti: true,
- inputMode: 'text',
- outputMode: 'text',
- agent_sort: null,
- agent_tag: null,
- headUrl: null,
- status: 0,
- createtime: now,
- updatetime: now
- }
- const agent = node('UserTask', column + index, lane, 255, 75, {
- createDate: now,
- item,
- dispo_desc: refs.map((ref) => `[${ref.desc}]`).join(' '),
- dispo_arr: refs,
- is_export: true,
- is_run: false,
- is_switch: true,
- content: '',
- is_history: true,
- variable_name: `output${Object.keys(lookup).length + 1}`,
- interaction_model: step.interactive ?? false,
- is_mon_agent: false
- })
- lookup[step.key] = agent
- edge(current, agent, index === 0 ? branch : null)
- current = agent
- }
- return current
- }
- let tails
- let endColumn
- if ('routes' in plan) {
- const fields = form.options.map((option) => ({
- key: '条件',
- value: option,
- id: `boss_${randomUUID()}`
- }))
- const control = node('boss_card', 2, 240, 250, Math.max(233, 8 + 75 * fields.length), {
- tableName: '控制卡片',
- variable_name: 'boss_card1',
- fields,
- is_run: false
- })
- edge(preceding, control)
- const paths = new Map(plan.routes.map((route) => [route.option, route.steps]))
- tails = []
- fields.forEach((field, index) => {
- tails.push(appendAgents(paths.get(field.value), control, 3, 120 + 160 * index, [index, field.id]))
- })
- endColumn = 3 + Math.max(...[...paths.values()].map((steps) => steps.length))
- } else {
- tails = [appendAgents(plan.steps, preceding, firstColumn, 240)]
- endColumn = firstColumn + plan.steps.length
- }
- const end = node('end_node', endColumn, 240, 146, 50, { input_value: '终点' })
- for (const tail of tails) edge(tail, end)
- return {
- source: 'muti_agent',
- id: '',
- userid: '',
- organizeid: '',
- username: '',
- muti_name: plan.name.trim(),
- description: plan.description ?? '',
- headUrl: '',
- create_time: now,
- update_time: now,
- status: 0,
- isEditable: true,
- isPublish: 0,
- isPublishData: 0,
- isDelete: false,
- knowledge_construction: 0,
- dialoguePublishDataId: null,
- cardPublishDataId: null,
- immersivePublishDataId: null,
- content: { nodes, edges }
- }
- }
- /**
- * 编译并落盘。已存在的文件不覆盖(和 Python 版的 "x" 模式一致),
- * 避免老师第二次生成时把上一次导入过的文件悄悄换掉。
- */
- export function buildWorkflowFile (plan, outputPath) {
- const target = path.resolve(String(outputPath || '').trim())
- if (!outputPath || String(outputPath).trim() === '') throw new WorkflowIOError('outputPath 不能为空')
- const dir = path.dirname(target)
- if (!fs.existsSync(dir)) throw new WorkflowIOError(`目录不存在:${dir}`)
- if (fs.existsSync(target)) throw new WorkflowIOError(`文件已存在,换一个名字再生成:${target}`)
- const workflow = compileWorkflow(plan)
- const payload = `${JSON.stringify(workflow, null, 2)}\n`
- fs.writeFileSync(target, payload, { encoding: 'utf8', flag: 'wx' })
- return { path: target, bytes: Buffer.byteLength(payload, 'utf8'), workflow }
- }
|