会议模式:按 UE 蓝图语义重做(exec 执行链 + data 数据线)+ while 循环节点
用户指出"不只是视觉,他是有个执行链的",查了官方文档 (https://dev.epicgames.com/documentation/unreal-engine/nodes-in-unreal-engine#pins) 之后发现:我之前**只学了长相没学语义**。 蓝图里引脚分两类,作用完全不同: exec 执行引脚(白色三角):**决定执行顺序**。激活输入 → 节点执行 → 激活输出继续。 data 数据引脚(彩色圆点):传值。 我的引擎原来是"谁连着谁就按拓扑序跑",两种作用混在一根线上。现在拆开了。 【边分两种】 kind='exec' 决定顺序;kind='data' 只传值。 老会议里没有 kind 的边当 exec,并且"没有数据入边时就用 exec 上游的输出"—— 所以以前那种"一根线连到底"的图行为完全不变(回归 40/40 可以证明)。 【端口按语义重排】 start 源:没有输入,只有数据输出 agent ▶ 入 / ▶ 出 + 数据入 / 数据出 judge ▶ 入 / **真▶ 假▶ 两条 exec 出**(相当于 Branch)+ 数据入 var ▶ 入 / ▶ 出 + 数据入(**没有数据出**——存进去的值不从它往下传) readvar **纯节点**(蓝图里的 Get):没有 exec 引脚,只有数据出。 值是被需要的节点**拉取**的,自己不在执行链上 end ▶ 入 + 数据入 while ▶ 入 / **循环体▶ 结束▶** + 数据入(条件) ★ "读变量只有输出"原来是这个意思:它是纯节点,压根没有 exec 引脚。 我一开始只按"有没有输入"去理解,做了个"变量被写入时唤醒读变量"的机制 —— 那是错的,纯节点的值是**拉取**的。删掉唤醒逻辑之后, Node 侧漏删了一处,对拍立刻报"rd 混进了执行链"(Python 侧没有)。 两处不一致就是这么被抓出来的。 【while 节点】 和 C 的 while 一样:先判断、再执行循环体,条件为假跳出。 data 入 条件(bool,每轮重新求值,一般来自"读变量") exec 出 循环体 / 结束 引擎的三处关键处理: 1. **嵌套 walk**:循环体必须是"整段跑完再回到判断"。用平铺队列做不到 —— 队列先进先出,循环体第一个节点刚入队 while 自己就被弹出来了, 判断会在循环体还没跑的时候重来一遍。所以循环体是一次嵌套的 walk。 2. **循环头边界(stop_at)**:嵌套 walk 跑到 while 自己就立刻返回。 不设这个边界的话它会一路跑回循环头、一层层递归下去 (踩过:序列是 s,w0,wh,a,e,w1,循环只转一圈就乱了)。 3. **每轮重置循环体的执行计数**:不重置的话循环体里的节点第二轮就被 maxRuns(默认 1)挡在门外,循环等于没用。 while 自己也不受 maxRuns 管 —— 转几轮是条件说了算。 另外兜了 MAX_LOOP_ITERS=200 的轮次上限,并且**会明确告诉用户"已达上限强制结束"**, 不静默停 —— 静默停会让人以为"条件写对了但没生效"。 【验证】 - 引擎回归:40/40,Node 与 Python **16/16 逐用例一致**(exec/data 重构没破坏既有语义) - while 端到端实测: exec seq: s, w0, wh, a, w1, wh, a, w1, wh, a, w1, wh, e body rounds: 3 第 1 轮:条件='3' → 继续循环 第 2 轮:条件='2' → 继续循环 第 3 轮:条件='1' → 继续循环 第 4 轮:条件='0' → 结束循环 n 从 3 递减到 0,转 3 轮后跳出,和 C 的 while(n--) 一致。 - 会议 HTTP 端到端 13/13 【这一轮没做完的,如实说明】 - **Node 侧引擎还没有 while 节点**(Python 有了)。两边的 exec/data 重构都做完了, 对拍 16/16 一致;但 while 是 Python 独有的,还没写 Node 镜像。 - **界面还没跟上**:节点卡片上现在是"▶ 执行引脚(白三角)+ 彩色圆点数据引脚", 但 while 节点的两种 exec 出线(循环体/结束)还没画; 节点配置面板里也没有 while 的说明。 - 这两块下一步补,补完再加 while 的验收用例把两边钉死。
This commit is contained in:
@@ -54,6 +54,8 @@ import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.TransformOrigin
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.StrokeCap
|
||||
import androidx.compose.ui.graphics.PathEffect
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
@@ -258,10 +260,9 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
var meeting by remember { mutableStateOf(initial) }
|
||||
var configTarget by remember { mutableStateOf<MeetingNode?>(null) }
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
// 正在连线的源节点(两步点选的第一个"点")
|
||||
// 正在连线:记 (源节点id, 出边分支)。
|
||||
// 判断节点有真/假两个输出端口,只记节点 id 分不清是从哪个口拉出来的。
|
||||
var linkingFrom by remember { mutableStateOf<Pair<String, String>?>(null) }
|
||||
// 正在连线:记"从哪条引脚拉出来的"(节点 + 引脚种类 + 分支)。
|
||||
// 判断节点有真/假两条 exec 出线,只记节点 id 分不清是从哪个口拉出来的。
|
||||
var linkingFrom by remember { mutableStateOf<LinkFrom?>(null) }
|
||||
var running by remember { mutableStateOf(false) }
|
||||
var runInput by remember { mutableStateOf("") }
|
||||
var runError by remember { mutableStateOf("") }
|
||||
@@ -398,7 +399,6 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
.fillMaxWidth()
|
||||
.pointerInput(Unit) {
|
||||
val nodeW = NODE_W.dp.toPx()
|
||||
val nodeH = NODE_H.dp.toPx()
|
||||
val portHit = PORT_HIT.dp.toPx()
|
||||
// 画布的像素尺寸按**真实密度**算,不再拍一个 2.75
|
||||
val contentW = CANVAS_W.dp.toPx()
|
||||
@@ -416,21 +416,21 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
|
||||
fun nodeAt(c: Offset): MeetingNode? = nodesSnapshot.value.lastOrNull { n ->
|
||||
c.x >= n.x.dp.toPx() && c.x <= n.x.dp.toPx() + nodeW &&
|
||||
c.y >= n.y.dp.toPx() && c.y <= n.y.dp.toPx() + nodeH
|
||||
c.y >= n.y.dp.toPx() && c.y <= n.y.dp.toPx() + nodeHeight(n).dp.toPx()
|
||||
}
|
||||
|
||||
/** 命中哪个端口。返回 (节点, 分支, 是输出端);输入端的 branch 恒为空串 */
|
||||
fun portAt(c: Offset): Triple<MeetingNode, String, Boolean>? {
|
||||
/** 命中哪个引脚。返回 (节点, 引脚, 是输出端) */
|
||||
fun portAt(c: Offset): Triple<MeetingNode, PinSpec, Boolean>? {
|
||||
for (n in nodesSnapshot.value.asReversed()) {
|
||||
// 先看输出端口(判断节点有两个)
|
||||
for (b in outBranches(n)) {
|
||||
if ((portOut(n, b).let { o -> Offset(o.x.dp.toPx(), o.y.dp.toPx()) } - c).getDistance() <= portHit) {
|
||||
return Triple(n, b, true)
|
||||
}
|
||||
outputPins(n).forEachIndexed { i, pin ->
|
||||
val p = pinPos(n, i, isOutput = true)
|
||||
val pp = Offset(p.x.dp.toPx(), p.y.dp.toPx())
|
||||
if ((pp - c).getDistance() <= portHit) return Triple(n, pin, true)
|
||||
}
|
||||
if (!hasInput(n)) continue
|
||||
if ((portIn(n).let { o -> Offset(o.x.dp.toPx(), o.y.dp.toPx()) } - c).getDistance() <= portHit) {
|
||||
return Triple(n, "", false)
|
||||
inputPins(n).forEachIndexed { i, pin ->
|
||||
val p = pinPos(n, i, isOutput = false)
|
||||
val pp = Offset(p.x.dp.toPx(), p.y.dp.toPx())
|
||||
if ((pp - c).getDistance() <= portHit) return Triple(n, pin, false)
|
||||
}
|
||||
}
|
||||
return null
|
||||
@@ -519,7 +519,7 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
// 屏幕上移动 1px,画布坐标只移动 1/scale ——
|
||||
// 不除的话放大后节点会"跑得比手指快"
|
||||
dragX = (dragX + delta.x / scale).coerceIn(0f, CANVAS_W - NODE_W)
|
||||
dragY = (dragY + delta.y / scale).coerceIn(0f, CANVAS_H - NODE_H)
|
||||
dragY = (dragY + delta.y / scale).coerceIn(0f, CANVAS_H - nodeHeight(hit))
|
||||
updateNode(hit.copy(x = dragX, y = dragY))
|
||||
}
|
||||
// 空白处单指拖动:什么都不做(平移要两指)
|
||||
@@ -531,31 +531,54 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
// ------- 没怎么动 = 点击 -------
|
||||
val linking = linkingSnapshot.value
|
||||
when {
|
||||
// 点输出端口:开始/取消连线
|
||||
// 点输出引脚:开始 / 取消连线
|
||||
portHitAtDown != null && portHitAtDown.third -> {
|
||||
val (n, b, _) = portHitAtDown
|
||||
linkingFrom = if (linking?.first == n.id && linking.second == b) {
|
||||
null
|
||||
} else {
|
||||
n.id to b
|
||||
}
|
||||
val (n, pin, _) = portHitAtDown
|
||||
val key = LinkFrom(n.id, pin.kind, pin.key)
|
||||
linkingFrom = if (linking == key) null else key
|
||||
}
|
||||
// 点输入端:完成连线
|
||||
// 点输入引脚:完成连线(**只接同种引脚**)
|
||||
portHitAtDown != null && linking != null -> {
|
||||
val (n, _, _) = portHitAtDown
|
||||
val from = linking.first
|
||||
// 没有输入端的节点(start / readvar)不该被连——
|
||||
// 端口都没画,理论上点不到,这里是双保险
|
||||
if (from != n.id && hasInput(n)) {
|
||||
// 同一条出边只留一条:再连一次是"改接",不是"多连一条"
|
||||
val kept = meeting.edges.filterNot {
|
||||
it.from == from && it.branch == linking.second
|
||||
val (n, pin, _) = portHitAtDown
|
||||
val from = linking.nodeId
|
||||
val fromKind = linking.kind
|
||||
val branch = linking.branch
|
||||
// ★ exec 只能接 exec、data 只能接 data。
|
||||
// 蓝图里接错类型会直接报"类型不兼容" ——
|
||||
// 这里静默不接(引脚本来就没画在一起,点错很难)。
|
||||
// 把"执行顺序"和"传值"混在一根线上,
|
||||
// 整套语义就垮了,所以这条必须守住。
|
||||
if (from != n.id && pin.kind == fromKind) {
|
||||
// ★ 判断节点的真假 exec 分支:一条分支只留一条线,
|
||||
// 再连一次是"改接"(不然会有两条"真",
|
||||
// 跑起来走哪条全看队列顺序,根本说不清)。
|
||||
//
|
||||
// 其他引脚**不是**这样:智能体的 exec / data 输出
|
||||
// 都可以同时给好几个下游("多路"),所以那里是**追加**。
|
||||
// 之前把判断的"改接"逻辑套到了所有引脚上,
|
||||
// 结果智能体只能连一个下游 ——
|
||||
// 用户报的"输出节点也能拓展"就是这个。
|
||||
val isBranch = fromKind == "exec"
|
||||
&& (branch == "true" || branch == "false")
|
||||
val dup = meeting.edges.any {
|
||||
it.from == from && it.to == n.id &&
|
||||
it.branch == branch && it.kind == fromKind
|
||||
}
|
||||
if (!dup) {
|
||||
val kept = if (isBranch) {
|
||||
meeting.edges.filterNot {
|
||||
it.from == from && it.branch == branch &&
|
||||
it.kind == "exec"
|
||||
}
|
||||
} else {
|
||||
meeting.edges
|
||||
}
|
||||
meeting = meeting.copy(
|
||||
edges = kept + MeetingEdge(from, n.id, branch, fromKind),
|
||||
)
|
||||
dirty = true
|
||||
persist()
|
||||
}
|
||||
meeting = meeting.copy(
|
||||
edges = kept + MeetingEdge(from, n.id, linking.second),
|
||||
)
|
||||
dirty = true
|
||||
persist()
|
||||
}
|
||||
linkingFrom = null
|
||||
}
|
||||
@@ -583,67 +606,120 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
translationY = panY
|
||||
},
|
||||
) {
|
||||
// 连线和端口画在节点底下
|
||||
// 连线和引脚画在节点底下
|
||||
Canvas(Modifier.fillMaxSize()) {
|
||||
val px = { o: Offset -> Offset(o.x.dp.toPx(), o.y.dp.toPx()) }
|
||||
|
||||
meeting.edges.forEach { edge ->
|
||||
val a = meeting.nodes.firstOrNull { it.id == edge.from } ?: return@forEach
|
||||
val b = meeting.nodes.firstOrNull { it.id == edge.to } ?: return@forEach
|
||||
// ★ 从**端口的实际位置**画起,不是从节点中心 ——
|
||||
// 判断节点两条出边一个在上一个在下,都从中心出发就分不清了
|
||||
val start = portOut(a, edge.branch).let { o -> Offset(o.x.dp.toPx(), o.y.dp.toPx()) }
|
||||
val end = portIn(b).let { o -> Offset(o.x.dp.toPx(), o.y.dp.toPx()) }
|
||||
val color = when (edge.branch) {
|
||||
"true" -> Color(0xFF34A853)
|
||||
"false" -> Color(0xFFEA4335)
|
||||
else -> Color(0xFFBFC4CC)
|
||||
}
|
||||
drawLine(
|
||||
color = color,
|
||||
start = start,
|
||||
end = end,
|
||||
strokeWidth = 2.dp.toPx(),
|
||||
pathEffect = if (edge.branch == "false") {
|
||||
PathEffect.dashPathEffect(floatArrayOf(10f, 10f))
|
||||
} else {
|
||||
null
|
||||
},
|
||||
)
|
||||
// 箭头
|
||||
val angle = kotlin.math.atan2((end.y - start.y), (end.x - start.x))
|
||||
val len = 12.dp.toPx()
|
||||
drawLine(
|
||||
color = color,
|
||||
start = end,
|
||||
end = Offset(
|
||||
end.x - len * kotlin.math.cos(angle - 0.4f),
|
||||
end.y - len * kotlin.math.sin(angle - 0.4f),
|
||||
),
|
||||
strokeWidth = 2.dp.toPx(),
|
||||
)
|
||||
}
|
||||
|
||||
// 端口圆点。画在最上层,用户看得见"从哪儿拉出去、往哪儿接进来"。
|
||||
meeting.nodes.forEach { node ->
|
||||
if (hasInput(node)) {
|
||||
val inP = portIn(node).let { o -> Offset(o.x.dp.toPx(), o.y.dp.toPx()) }
|
||||
drawCircle(Color.White, radius = (PORT_R + 1.5f).dp.toPx(), center = inP)
|
||||
drawCircle(Color(0xFFBFC4CC), radius = PORT_R.dp.toPx(), center = inP)
|
||||
}
|
||||
|
||||
outBranches(node).forEach { branch ->
|
||||
val p = portOut(node, branch).let { o -> Offset(o.x.dp.toPx(), o.y.dp.toPx()) }
|
||||
val c = when (branch) {
|
||||
// ★ 从**引脚的准确位置**出发,不是从节点中心 ——
|
||||
// 判断节点两条出线一行一个,都从中心出发就分不清谁是谁
|
||||
val start = px(portOut(a, edge.kind, edge.branch))
|
||||
val end = px(portIn(b, edge.kind))
|
||||
// ★ 执行线白色(蓝图里 exec 线就是白的),数据线按分支上色。
|
||||
// 两种线一眼能分开,不然"哪些决定顺序、哪些只是传值"看不出来。
|
||||
val color = if (edge.kind == "data") {
|
||||
when (edge.branch) {
|
||||
"true" -> Color(0xFF34A853)
|
||||
"false" -> Color(0xFFEA4335)
|
||||
else -> Color(0xFF8AB4F8)
|
||||
}
|
||||
} else {
|
||||
when (edge.branch) {
|
||||
"true" -> Color(0xFF34A853)
|
||||
"false" -> Color(0xFFEA4335)
|
||||
else -> EXEC_BORDER
|
||||
}
|
||||
}
|
||||
// ★ 三次贝塞尔,像 UE 蓝图那样:控制点水平拉开,
|
||||
// 线从引脚水平出发、水平接入。直线在节点错位时
|
||||
// 会斜着穿过别的节点,看着像连错了。
|
||||
val dx = maxOf(36.dp.toPx(), kotlin.math.abs(end.x - start.x) * 0.5f)
|
||||
val path = Path().apply {
|
||||
moveTo(start.x, start.y)
|
||||
cubicTo(start.x + dx, start.y, end.x - dx, end.y, end.x, end.y)
|
||||
}
|
||||
drawPath(
|
||||
path = path,
|
||||
color = color,
|
||||
style = Stroke(
|
||||
width = 2.5.dp.toPx(),
|
||||
cap = androidx.compose.ui.graphics.StrokeCap.Round,
|
||||
pathEffect = if (edge.branch == "false") {
|
||||
PathEffect.dashPathEffect(floatArrayOf(9f, 9f))
|
||||
} else {
|
||||
null
|
||||
},
|
||||
),
|
||||
)
|
||||
// 箭头:**永远朝右**。
|
||||
//
|
||||
// 这条三次贝塞尔的控制点是 (start+dx, ·) 和 (end-dx, ·),
|
||||
// 所以 t=1 处的切线方向恒为 (dx, 0) —— 水平向右,
|
||||
// 和起点/终点的高低差无关。蓝图里的箭头也是这样水平扎进引脚的。
|
||||
//
|
||||
// 之前按"起点到终点"的斜率算角度,横向距离小的时候
|
||||
// atan2 会算出接近 180°,箭头翻过去和后一条边叠成蝴蝶结。
|
||||
val angle = 0f
|
||||
val len = 8.dp.toPx()
|
||||
val arrow = Path().apply {
|
||||
moveTo(end.x, end.y)
|
||||
lineTo(
|
||||
end.x - len * kotlin.math.cos(angle - 0.45f),
|
||||
end.y - len * kotlin.math.sin(angle - 0.45f),
|
||||
)
|
||||
lineTo(
|
||||
end.x - len * kotlin.math.cos(angle + 0.45f),
|
||||
end.y - len * kotlin.math.sin(angle + 0.45f),
|
||||
)
|
||||
close()
|
||||
}
|
||||
drawPath(arrow, color)
|
||||
}
|
||||
|
||||
// 引脚。画在最上层,用户看得见"从哪儿拉出去、往哪儿接进来"。
|
||||
meeting.nodes.forEach { node ->
|
||||
inputPins(node).forEachIndexed { i, pin ->
|
||||
val p = px(pinPos(node, i, isOutput = false))
|
||||
if (pin.kind == "exec") {
|
||||
drawExecPin(p, PORT_R.dp.toPx(), filled = true)
|
||||
} else {
|
||||
drawCircle(Color.White, radius = (PORT_R + 1.5f).dp.toPx(), center = p)
|
||||
drawCircle(Color(0xFF9AA0A6), radius = PORT_R.dp.toPx(), center = p)
|
||||
}
|
||||
}
|
||||
outputPins(node).forEachIndexed { i, pin ->
|
||||
val p = px(pinPos(node, i, isOutput = true))
|
||||
val c = when {
|
||||
pin.kind == "exec" && pin.key == "true" -> Color(0xFF34A853)
|
||||
pin.kind == "exec" && pin.key == "false" -> Color(0xFFEA4335)
|
||||
pin.kind == "exec" -> EXEC_BORDER
|
||||
else -> nodeColor(node.type)
|
||||
}
|
||||
val active = linkingFrom?.let { it.first == node.id && it.second == branch } == true
|
||||
drawCircle(Color.White, radius = (PORT_R + 1.5f).dp.toPx(), center = p)
|
||||
drawCircle(
|
||||
color = c,
|
||||
radius = (if (active) PORT_R + 2f else PORT_R).dp.toPx(),
|
||||
center = p,
|
||||
)
|
||||
// linkingFrom 编码是 "节点id\u0000种类\u0000分支"
|
||||
val active = linkingFrom?.let {
|
||||
it.nodeId == node.id && it.kind == pin.kind && it.branch == pin.key
|
||||
} == true
|
||||
if (pin.kind == "exec") {
|
||||
drawExecPin(p, (if (active) PORT_R + 1.5f else PORT_R).dp.toPx(), filled = true, tint = c)
|
||||
} else {
|
||||
drawCircle(Color.White, radius = (PORT_R + 1.5f).dp.toPx(), center = p)
|
||||
drawCircle(
|
||||
color = c,
|
||||
radius = (if (active) PORT_R + 2f else PORT_R).dp.toPx(),
|
||||
center = p,
|
||||
)
|
||||
}
|
||||
// 正在连线的那个引脚加一圈外环,"我点的是这个"要看得见
|
||||
if (active) {
|
||||
drawCircle(
|
||||
color = (if (pin.kind == "exec") c else c).copy(alpha = 0.35f),
|
||||
radius = (PORT_R + 5f).dp.toPx(),
|
||||
center = p,
|
||||
style = Stroke(width = 2.dp.toPx()),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -655,8 +731,9 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
node = node,
|
||||
status = status,
|
||||
output = nodeOutputs[node.id] ?: "",
|
||||
linking = linkingFrom?.first == node.id,
|
||||
linking = linkingFrom?.nodeId == node.id,
|
||||
inDegree = meeting.edges.count { it.to == node.id },
|
||||
outDegree = meeting.edges.count { it.from == node.id },
|
||||
modifier = Modifier.offset(node.x.dp, node.y.dp),
|
||||
)
|
||||
}
|
||||
@@ -797,58 +874,156 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
}
|
||||
|
||||
/**
|
||||
* 端口的几何位置(单位 dp,和节点坐标同一套)。
|
||||
* 一个引脚。照 UE 蓝图分两类:
|
||||
*
|
||||
* ★ 判断节点有**两个输出端口**:真在上、假在下。
|
||||
* 以前是"一个节点一个连线按钮,真假由程序猜"(第一条连 true、第二条连 false)——
|
||||
* 用户根本不知道自己在连哪条,也没法只连一条。改成真端口之后所见即所得。
|
||||
* exec 执行引脚(白色三角):**决定执行顺序**。激活输入 → 节点执行 → 激活输出继续。
|
||||
* data 数据引脚(彩色圆点):传值。
|
||||
*
|
||||
* key 是"这条引脚对应哪个分支"(判断节点用 true/false),label 是画在节点上的字。
|
||||
* 蓝图里引脚都带标签 —— 光靠位置猜是哪个口太费劲。
|
||||
*/
|
||||
private fun portIn(node: MeetingNode): Offset =
|
||||
Offset(node.x, node.y + NODE_H / 2f)
|
||||
|
||||
private fun portOut(node: MeetingNode, branch: String): Offset {
|
||||
val y = when (branch) {
|
||||
"true" -> node.y + NODE_H * 0.30f
|
||||
"false" -> node.y + NODE_H * 0.70f
|
||||
else -> node.y + NODE_H / 2f
|
||||
}
|
||||
return Offset(node.x + NODE_W, y)
|
||||
}
|
||||
|
||||
/** 端口圆点的半径(画多大)与命中半径(点多准)。命中范围要大一圈,手指没那么准。 */
|
||||
private const val PORT_R = 6f
|
||||
private const val PORT_HIT = 22f
|
||||
private data class PinSpec(
|
||||
val kind: String,
|
||||
val key: String,
|
||||
val label: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* 哪些节点有输入/输出端口。
|
||||
* 左边一列的引脚(从上到下)。
|
||||
*
|
||||
* ★ 这不是画得好不好看的问题,是**数据流语义**:
|
||||
* start 源:没有输入,只有输出
|
||||
* readvar 源:读变量是"取数据",不该被人喂东西进来,只有输出
|
||||
* var 汇:写变量是"存数据",只管收,没有输出
|
||||
* end 汇:最终输出,只管收
|
||||
* agent / judge 中间节点,进出都有
|
||||
*
|
||||
* 端口画错了用户就会连出跑不通的图(想接进"读变量"却发现没口),
|
||||
* 比报错还难受 —— 所以这里严格按语义来。
|
||||
* ★ 读变量**没有 exec 入**:它是纯节点(蓝图里的 Get),不在执行链上,
|
||||
* 值是被需要的节点运行时拉取的 —— 这就是"读变量只有输出"的真正原因。
|
||||
*/
|
||||
private fun hasInput(node: MeetingNode): Boolean = when (node.type) {
|
||||
"start", "readvar" -> false
|
||||
else -> true
|
||||
private fun inputPins(node: MeetingNode): List<PinSpec> = when (node.type) {
|
||||
"start", "readvar" -> emptyList()
|
||||
"judge", "var" -> listOf(
|
||||
PinSpec("exec", "", "▶"),
|
||||
PinSpec("data", "", "值"),
|
||||
)
|
||||
else -> listOf(
|
||||
PinSpec("exec", "", "▶"),
|
||||
PinSpec("data", "", "输入"),
|
||||
)
|
||||
}
|
||||
|
||||
private fun hasOutput(node: MeetingNode): Boolean = when (node.type) {
|
||||
"end", "var" -> false
|
||||
else -> true
|
||||
/**
|
||||
* 右边一列的引脚(从上到下)。
|
||||
*
|
||||
* ★ 判断节点有**两条 exec 出线**(真/假)—— 相当于蓝图里的 Branch。
|
||||
* ★ 写变量**没有 data 出线**(存进去的值不从它往下传),但有 exec 出线
|
||||
* (蓝图里 Set 节点就是 exec 进 → exec 出)。
|
||||
*/
|
||||
private fun outputPins(node: MeetingNode): List<PinSpec> = when (node.type) {
|
||||
"end" -> emptyList()
|
||||
"readvar" -> listOf(PinSpec("data", "", "值"))
|
||||
"judge" -> listOf(
|
||||
PinSpec("exec", "true", "真 ▶"),
|
||||
PinSpec("exec", "false", "假 ▶"),
|
||||
)
|
||||
"var" -> listOf(PinSpec("exec", "", "▶"))
|
||||
"start" -> listOf(PinSpec("data", "", "输出"))
|
||||
else -> listOf(
|
||||
PinSpec("exec", "", "▶"),
|
||||
PinSpec("data", "", "输出"),
|
||||
)
|
||||
}
|
||||
|
||||
/** 输入端口永远只有一个;输出端口按分支给(普通节点一个,判断节点真假两个) */
|
||||
private fun outBranches(node: MeetingNode): List<String> = when {
|
||||
!hasOutput(node) -> emptyList()
|
||||
node.type == "judge" -> listOf("true", "false")
|
||||
else -> listOf("")
|
||||
/* ---- UE 蓝图式的节点尺寸:标题栏 + 引脚行 + 内容区 ---- */
|
||||
|
||||
/** 顶部彩色标题栏的高度 */
|
||||
private const val HEADER_H = 24f
|
||||
/** 一行引脚占的高度 */
|
||||
private const val PIN_ROW_H = 18f
|
||||
/** 引脚下面的内容区(预览文字 + 路数) */
|
||||
private const val BODY_H = 38f
|
||||
|
||||
/** 引脚画多大 / 点多准。命中范围要大一圈,手指没那么准。 */
|
||||
private const val PORT_R = 5.5f
|
||||
private const val PORT_HIT = 19f
|
||||
|
||||
/** 节点高矮跟着引脚数走:判断节点两行出线、智能体进出各有两种,就高一些 */
|
||||
private fun nodeHeight(node: MeetingNode): Float {
|
||||
val rows = maxOf(inputPins(node).size, outputPins(node).size, 1)
|
||||
return HEADER_H + rows * PIN_ROW_H + BODY_H
|
||||
}
|
||||
|
||||
/**
|
||||
* 引脚的几何位置(dp,和节点坐标同一套)。
|
||||
*
|
||||
* 第 index 个引脚在标题栏下面第 index 行、垂直居中。
|
||||
* 输入贴左边、输出贴右边 —— 和蓝图一致,连线从节点边缘出发 / 接入。
|
||||
*/
|
||||
private fun pinPos(node: MeetingNode, index: Int, isOutput: Boolean): Offset {
|
||||
val y = node.y + HEADER_H + PIN_ROW_H * index + PIN_ROW_H / 2f
|
||||
val x = if (isOutput) node.x + NODE_W else node.x
|
||||
return Offset(x, y)
|
||||
}
|
||||
|
||||
/** 按 (种类, 分支) 找输出引脚的序号;找不到就退回第一条(老数据容错) */
|
||||
private fun outPinIndex(node: MeetingNode, kind: String, branch: String): Int {
|
||||
val pins = outputPins(node)
|
||||
val exact = pins.indexOfFirst { it.kind == kind && (it.kind != "exec" || it.key == branch) }
|
||||
if (exact >= 0) return exact
|
||||
val byBranch = pins.indexOfFirst { it.kind == "exec" && it.key == branch }
|
||||
return if (byBranch >= 0) byBranch else 0
|
||||
}
|
||||
|
||||
/**
|
||||
* 输入端口的位置。
|
||||
*
|
||||
* data 线接"值/输入"那条;exec 线接"▶"那条。
|
||||
* 找不到对应种类时退回第一条 —— 老会议里没有 kind 字段,边一律当 exec,
|
||||
* 而老图的节点只有一条入线,退回第一条正好对上。
|
||||
*/
|
||||
private fun portIn(node: MeetingNode, kind: String): Offset {
|
||||
val pins = inputPins(node)
|
||||
val index = pins.indexOfFirst { it.kind == kind }
|
||||
return pinPos(node, if (index >= 0) index else 0, isOutput = false)
|
||||
}
|
||||
|
||||
/** 输出端口的位置 */
|
||||
private fun portOut(node: MeetingNode, kind: String, branch: String): Offset =
|
||||
pinPos(node, outPinIndex(node, kind, branch), isOutput = true)
|
||||
|
||||
/**
|
||||
* 正在连线时记住"从哪条引脚拉出来的"。
|
||||
*
|
||||
* ★ 用数据类而不是拼字符串:一开始拼了 `"$id\u0000$kind\u0000$branch"`,
|
||||
* 结果转义在几道工具链里被搞乱,编译报了一堆 Char/String 不匹配。
|
||||
* 三个字段就该用三个字段,别为了省事把结构化数据拍成字符串。
|
||||
*/
|
||||
private data class LinkFrom(val nodeId: String, val kind: String, val branch: String)
|
||||
|
||||
/** 执行引脚画成白色三角、数据引脚画成彩色圆点 —— 蓝图就靠这个一眼分辨 */
|
||||
private val EXEC_COLOR = Color(0xFFE8EAED)
|
||||
private val EXEC_BORDER = Color(0xFF5F6368)
|
||||
|
||||
/**
|
||||
* 画一个执行引脚(蓝图里那种白色小三角)。
|
||||
*
|
||||
* ★ 为什么非得是三角而不是圆点:蓝图里"执行"和"数据"是两种完全不同的东西 ——
|
||||
* 一个**决定执行顺序**、一个只传值。形状不同才能在缩小之后也分得开;
|
||||
* 只靠颜色的话,色弱用户、或者图缩小了就完全分不清了,
|
||||
* 而这两种线接错等于整套语义都垮了。
|
||||
*/
|
||||
private fun androidx.compose.ui.graphics.drawscope.DrawScope.drawExecPin(
|
||||
center: Offset,
|
||||
radius: Float,
|
||||
filled: Boolean,
|
||||
tint: Color = EXEC_BORDER,
|
||||
) {
|
||||
val h = radius * 1.5f
|
||||
val path = Path().apply {
|
||||
moveTo(center.x - h * 0.55f, center.y - h)
|
||||
lineTo(center.x + h * 0.75f, center.y)
|
||||
lineTo(center.x - h * 0.55f, center.y + h)
|
||||
close()
|
||||
}
|
||||
if (filled) drawPath(path, Color.White)
|
||||
drawPath(path, tint, style = Stroke(width = 1.6.dp.toPx()))
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 平移范围的钳制。
|
||||
*
|
||||
@@ -1177,13 +1352,20 @@ private fun NodeCard(
|
||||
linking: Boolean,
|
||||
/** 接到这个节点的连线数(多路输入要显示出来) */
|
||||
inDegree: Int,
|
||||
/** 从这个节点出去的连线数(多路输出也要显示) */
|
||||
outDegree: Int,
|
||||
modifier: Modifier,
|
||||
) {
|
||||
val accent = nodeColor(node.type)
|
||||
val ins = inputPins(node)
|
||||
val outs = outputPins(node)
|
||||
val rows = maxOf(ins.size, outs.size, 1)
|
||||
|
||||
Column(
|
||||
modifier
|
||||
.size(NODE_W.dp, NODE_H.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.width(NODE_W.dp)
|
||||
.height(nodeHeight(node).dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(doubaoSurface())
|
||||
.border(
|
||||
width = if (linking) 2.dp else 1.dp,
|
||||
@@ -1191,73 +1373,127 @@ private fun NodeCard(
|
||||
linking -> Doubao.Blue
|
||||
status == "running" -> accent
|
||||
status == "error" -> MaterialTheme.colorScheme.error
|
||||
else -> accent.copy(alpha = 0.45f)
|
||||
else -> accent.copy(alpha = 0.55f)
|
||||
},
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
)
|
||||
// 拖动节点 / 平移画布 / 点击(开配置、点端口连线)**全部**由父级
|
||||
// 拖动节点 / 平移画布 / 点击(开配置、点引脚连线)**全部**由父级
|
||||
// 统一处理(见上面画布那段的长注释)。这里一个手势识别器都不挂 ——
|
||||
// 多个叠一起必然互相抢,这个坑前面踩过两次了。
|
||||
.padding(8.dp),
|
||||
,
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(Modifier.size(7.dp).clip(CircleShape).background(accent))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
// ★ 彩色标题栏 —— 蓝图节点的招牌长相。
|
||||
// 一眼就能按颜色分出"这是个判断节点还是智能体",
|
||||
// 不用去读小字(图一大,字根本看不清)。
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(HEADER_H.dp)
|
||||
.background(accent)
|
||||
.padding(horizontal = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
node.title.ifBlank {
|
||||
when (node.type) {
|
||||
"start" -> "初始输入"
|
||||
"judge" -> "判断"
|
||||
"end" -> "最终输出"
|
||||
"var" -> "写变量"
|
||||
"readvar" -> "读变量"
|
||||
else -> "智能体"
|
||||
}
|
||||
},
|
||||
fontSize = 13.sp,
|
||||
fontSize = 10.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
color = Color.White,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (status == "running") {
|
||||
Text("…", fontSize = 13.sp, color = accent)
|
||||
} else if (status == "done") {
|
||||
Text("✓", fontSize = 12.sp, color = Color(0xFF34A853))
|
||||
// 状态标记放标题栏里:不占正文空间
|
||||
when (status) {
|
||||
"running" -> Text("…", fontSize = 11.sp, color = Color.White)
|
||||
"done" -> Text("✓", fontSize = 10.sp, color = Color.White)
|
||||
"error" -> Text("!", fontSize = 11.sp, color = Color.White)
|
||||
"stopped" -> Text("■", fontSize = 9.sp, color = Color.White)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
when {
|
||||
output.isNotBlank() -> output
|
||||
node.type == "agent" -> if (node.agentId.isBlank()) "未选智能体" else "已选智能体"
|
||||
node.type == "judge" -> node.judgeKind
|
||||
node.text.isNotBlank() -> node.text
|
||||
else -> "点一下配置"
|
||||
},
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
lineHeight = 13.sp,
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
// 接到这个节点的连线数。智能体的输入是**可以接多路**的(多路按顺序
|
||||
// 拼成一段文本),把条数写出来,用户才知道自己接了几路、有没有漏。
|
||||
if (inDegree > 0) {
|
||||
Text("← $inDegree 路", fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
if (node.maxRuns != 1) {
|
||||
// 会重复的节点标出来:不然图上看着和普通节点一样,
|
||||
// 跑起来发现它转了三轮会很意外
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Text(
|
||||
if (node.maxRuns == 0) "∞" else "×${node.maxRuns}",
|
||||
fontSize = 10.sp,
|
||||
color = if (node.maxRuns == 0) Color(0xFFF29900) else doubaoTextSecondary(),
|
||||
fontSize = 9.sp,
|
||||
color = Color.White.copy(alpha = 0.85f),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ★ 引脚行:左输入、右输出,各自带标签。
|
||||
// 标签紧贴引脚那一侧 —— 蓝图的习惯,视线从引脚扫进去就能读到。
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height((rows * PIN_ROW_H).dp),
|
||||
) {
|
||||
ins.forEachIndexed { i, pin ->
|
||||
Text(
|
||||
pin.label,
|
||||
fontSize = 9.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopStart)
|
||||
.offset(x = 7.dp, y = (PIN_ROW_H * i + 4f).dp),
|
||||
)
|
||||
}
|
||||
outs.forEachIndexed { i, pin ->
|
||||
Text(
|
||||
pin.label,
|
||||
fontSize = 9.sp,
|
||||
color = when (pin.key) {
|
||||
"true" -> Color(0xFF34A853)
|
||||
"false" -> Color(0xFFEA4335)
|
||||
else -> doubaoTextSecondary()
|
||||
},
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.offset(x = (-7).dp, y = (PIN_ROW_H * i + 4f).dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 内容区:节点配置摘要 + 运行时的输出
|
||||
Text(
|
||||
when {
|
||||
output.isNotBlank() -> output
|
||||
node.type == "agent" -> buildString {
|
||||
append(if (node.agentId.isBlank()) "未选智能体" else "已选智能体")
|
||||
if (node.saveToVar.isNotBlank()) append(" · 存→${node.saveToVar}")
|
||||
}
|
||||
node.type == "judge" -> node.judgeKind
|
||||
node.type == "var" -> node.varName.ifBlank { "没填变量名" }
|
||||
node.type == "readvar" -> node.varName.ifBlank { "没填变量名" }
|
||||
node.text.isNotBlank() -> node.text
|
||||
else -> "点一下配置"
|
||||
},
|
||||
fontSize = 9.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
lineHeight = 12.sp,
|
||||
modifier = Modifier.padding(horizontal = 6.dp),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
// 进出路数写在最底下:多路是智能体的常态,不显示用户不知道自己接全没有
|
||||
Text(
|
||||
buildString {
|
||||
if (inDegree > 0) append("← $inDegree")
|
||||
if (inDegree > 0 && outDegree > 0) append(" ")
|
||||
if (outDegree > 0) append("$outDegree →")
|
||||
},
|
||||
fontSize = 8.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ import paths
|
||||
|
||||
_lock = threading.Lock()
|
||||
|
||||
NODE_TYPES = ('start', 'agent', 'judge', 'end', 'var', 'readvar')
|
||||
NODE_TYPES = ('start', 'agent', 'judge', 'end', 'var', 'readvar', 'while')
|
||||
|
||||
# 判断节点支持的条件。**结构化而不是表达式**,理由见文件头。
|
||||
JUDGE_KINDS = (
|
||||
@@ -55,6 +55,50 @@ JUDGE_KINDS = (
|
||||
('ai', '让模型判断'),
|
||||
)
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# while 循环
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# 和 C 的 while 一样:**先判断、再执行循环体**,条件为假就跳出。
|
||||
# exec 入 ▶ 进入循环
|
||||
# data 入 条件 bool,每轮重新求值(所以条件一般来自"读变量")
|
||||
# exec 出 循环体 条件为真时走这条
|
||||
# exec 出 结束 条件为假时走这条
|
||||
# data 出 无
|
||||
#
|
||||
# 为什么不能靠"循环体连回 while"来实现:那样每轮都要用户多画一根回边,
|
||||
# 而且"从上面进来"和"从循环体回来"分不开,很容易连成死循环。
|
||||
# 这里由**引擎**负责"循环体跑完自动回来重新判断"(UE 蓝图的 While Loop
|
||||
# 也是这么做的,body 出线是特殊的 deferred 引脚)。
|
||||
|
||||
# 单次运行里,一个 while 节点最多转多少轮。
|
||||
# 不是"限制用户",是防止条件永远为真把额度和时间烧光 ——
|
||||
# 正常写循环根本碰不到这个数。
|
||||
MAX_LOOP_ITERS = 200
|
||||
|
||||
|
||||
class _Aborted(Exception):
|
||||
"""用户点了停止 / 客户端断开。用异常从嵌套的 walk 里一次性跳出来。"""
|
||||
|
||||
# 条件为真怎么判:接受 bool、'true'/'1'/'yes'/非空字符串
|
||||
TRUE_WORDS = ('true', '1', 'yes', 'y', 'on', '是', '真')
|
||||
|
||||
|
||||
def truthy(value) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if value is None:
|
||||
return False
|
||||
if isinstance(value, (int, float)):
|
||||
return value != 0
|
||||
text = str(value).strip().lower()
|
||||
if not text:
|
||||
return False
|
||||
# 空数组/对象那种字符串也当假
|
||||
if text in ('false', '0', 'no', 'n', 'off', '否', '假', 'none', 'null', '[]', '{}'):
|
||||
return False
|
||||
return True
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 变量
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -372,10 +416,25 @@ def _sanitize_edges(edges: list, nodes: list) -> list:
|
||||
continue
|
||||
# 源必须有输出端口,目标必须有输入端口
|
||||
if by_id[src]['type'] in ('end', 'var'):
|
||||
continue
|
||||
# end / var 没有**数据**出线;但它们有 exec 出线(比如 Set 节点
|
||||
# 存完继续往下走),所以这里只挡数据线
|
||||
if str(e.get('kind') or '') == DATA:
|
||||
continue
|
||||
if by_id[dst]['type'] in ('start', 'readvar'):
|
||||
continue
|
||||
out.append({'from': src, 'to': dst, 'branch': str(e.get('branch') or '')})
|
||||
|
||||
kind = _kind(e)
|
||||
# ★ 从"读变量"出来的线**一律当数据线**:它是纯节点(蓝图里的 Get),
|
||||
# 输出天然是数据,不该拿它当执行链的一环。
|
||||
# 让保存时自动推断,用户就不用去理解两种线的区别也能连对。
|
||||
if by_id[src]['type'] == 'readvar':
|
||||
kind = DATA
|
||||
# 进"写变量"的线也是数据线(它要的是值,不是执行信号 —— 虽然它也有 exec 入,
|
||||
# 但用户往它身上连多半是想存这个东西)
|
||||
if by_id[dst]['type'] == 'var' and str(e.get('kind') or '') == '':
|
||||
kind = DATA
|
||||
|
||||
out.append({'from': src, 'to': dst, 'branch': str(e.get('branch') or ''), 'kind': kind})
|
||||
return out
|
||||
|
||||
|
||||
@@ -391,14 +450,117 @@ def _outgoing(edges: list, node_id: str) -> list:
|
||||
return [e for e in edges if e.get('from') == node_id]
|
||||
|
||||
|
||||
def _collect_input(node_id: str, edges: list, outputs: dict) -> str:
|
||||
"""一个节点的输入 = 它所有上游节点的输出拼起来。
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 两种连线(照 UE 蓝图的语义)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# 蓝图里引脚分两类,作用完全不同:
|
||||
# 执行引脚(exec)白色:**决定执行顺序**。激活输入 → 节点执行 → 激活输出继续往下。
|
||||
# 数据引脚(data)彩色:传值。谁把它们连起来,谁在执行时就能拿到对方的值。
|
||||
#
|
||||
# 我一开始只把节点画成蓝图的样子、引擎还是"谁连着谁就按拓扑序跑",
|
||||
# 那是**只学了长相没学语义**。真正的蓝图里:
|
||||
# - 顺序完全由 exec 链决定,数据线不决定顺序;
|
||||
# - 读变量这种"纯节点"(Get)**没有 exec 引脚**,它的值是被需要的人
|
||||
# **拉取**的,自己不在执行链上 —— 这正是"读变量只有输出"的真正原因。
|
||||
#
|
||||
# 兼容:老会议里没有 kind 字段的边,当成 exec 处理,并且"没有数据入边时
|
||||
# 就用 exec 上游的输出"当输入 —— 这样以前那种"一根线连到底"的图行为不变。
|
||||
|
||||
多条入边就按连线顺序拼 —— 这样"多个智能体的意见汇总给判断节点"
|
||||
不需要额外的合并节点。
|
||||
EXEC = 'exec'
|
||||
DATA = 'data'
|
||||
|
||||
|
||||
def _kind(edge: dict) -> str:
|
||||
return DATA if edge.get('kind') == DATA else EXEC
|
||||
|
||||
|
||||
def _exec_in(edges: list, node_id: str) -> list:
|
||||
return [e for e in _incoming(edges, node_id) if _kind(e) == EXEC]
|
||||
|
||||
|
||||
def _exec_out(edges: list, node_id: str, branch: str = None) -> list:
|
||||
out = [e for e in _outgoing(edges, node_id) if _kind(e) == EXEC]
|
||||
if branch is None:
|
||||
return out
|
||||
return [e for e in out if (e.get('branch') or 'true') == branch]
|
||||
|
||||
|
||||
def _data_in(edges: list, node_id: str) -> list:
|
||||
return [e for e in _incoming(edges, node_id) if _kind(e) == DATA]
|
||||
|
||||
|
||||
def _data_out(edges: list, node_id: str) -> list:
|
||||
return [e for e in _outgoing(edges, node_id) if _kind(e) == DATA]
|
||||
|
||||
|
||||
def _reachable_exec(edges: list, seeds: list, stop: str = None) -> set:
|
||||
"""
|
||||
从 seeds 出发、只沿 **exec** 边走,能走到的所有节点。
|
||||
|
||||
stop 是循环头:走到它就停,不要把它算进去 —— 循环体是"回到循环头之前"
|
||||
的那一段,把循环头自己算进来会把它的执行计数也清掉。
|
||||
"""
|
||||
seen = set()
|
||||
stack = list(seeds)
|
||||
while stack:
|
||||
nid = stack.pop()
|
||||
if nid in seen or (stop is not None and nid == stop):
|
||||
continue
|
||||
seen.add(nid)
|
||||
stack.extend(e['to'] for e in _exec_out(edges, nid))
|
||||
return seen
|
||||
|
||||
|
||||
def _collect_data_only(node_id: str, edges: list, outputs: dict, variables: dict,
|
||||
by_id: dict) -> str:
|
||||
"""
|
||||
只取**数据入线**的值,不回退到 exec 上游。
|
||||
|
||||
而循环体上一轮的输出往往是非空文本 —— 那条件就永远为真,直接变成死循环。
|
||||
条件拿不到就当空串(= 假),跳出循环,这是最安全的默认。
|
||||
"""
|
||||
parts = []
|
||||
for e in _incoming(edges, node_id):
|
||||
for e in _data_in(edges, node_id):
|
||||
src = e.get('from')
|
||||
node = by_id.get(src)
|
||||
if node and node['type'] == 'readvar':
|
||||
value = variables.get(str(node.get('varName') or '').strip(), '')
|
||||
else:
|
||||
value = outputs.get(src, '')
|
||||
if value:
|
||||
parts.append(str(value))
|
||||
return '\n\n'.join(parts).strip()
|
||||
|
||||
|
||||
def _collect_input(node_id: str, edges: list, outputs: dict, variables: dict,
|
||||
by_id: dict) -> str:
|
||||
"""
|
||||
算出这个节点的输入文本。
|
||||
|
||||
优先级:
|
||||
1. **数据入边**:把上游的值拼起来(多条按连线顺序)。
|
||||
其中"读变量"是纯节点,在**被读取的这一刻**才求值 ——
|
||||
它不在执行链上,所以不能靠 outputs 里有没有它来判断。
|
||||
2. 没有数据入边时,用 **exec 上游的输出**。
|
||||
这一步是为了省事:最简单的"一根线连到底"不该逼用户连两根线。
|
||||
"""
|
||||
parts = []
|
||||
for e in _data_in(edges, node_id):
|
||||
src = e.get('from')
|
||||
node = by_id.get(src)
|
||||
if node and node['type'] == 'readvar':
|
||||
# 纯节点:现取现值
|
||||
value = variables.get(str(node.get('varName') or '').strip(), '')
|
||||
else:
|
||||
value = outputs.get(src, '')
|
||||
if value:
|
||||
parts.append(str(value))
|
||||
if parts:
|
||||
return '\n\n'.join(parts).strip()
|
||||
|
||||
# 回退:exec 上游的输出
|
||||
for e in _exec_in(edges, node_id):
|
||||
text = outputs.get(e.get('from'))
|
||||
if text:
|
||||
parts.append(str(text))
|
||||
@@ -460,17 +622,14 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str,
|
||||
|
||||
emit({'type': 'meeting_start', 'nodes': len(nodes), 'edges': len(edges)})
|
||||
|
||||
# 入口:优先 start 节点;没有就从"没有入边"的节点开始。
|
||||
# 入口:优先 start 节点;没有就从"没有 exec 入边"的节点开始。
|
||||
#
|
||||
# ★ 读变量节点**不算入口**:它没有输入端口,是"变量被写入时"才触发的。
|
||||
# 把它当入口的话,一上来就会读出一个空值 —— 顺序完全反了。
|
||||
# ★ 读变量是**纯节点**(蓝图里的 Get),不在执行链上 —— 它的值是被
|
||||
# 需要的节点在运行时"拉"过去的,所以不能当入口,也不进队列。
|
||||
starts = [n for n in nodes if n['type'] == 'start']
|
||||
if not starts:
|
||||
starts = [n for n in nodes
|
||||
if not _incoming(edges, n['id']) and n['type'] != 'readvar']
|
||||
if not starts:
|
||||
# 整张图只有读变量节点:那就让它跑一次(读到的可能是空的)
|
||||
starts = [n for n in nodes if n['type'] == 'readvar']
|
||||
if n['type'] != 'readvar' and not _exec_in(edges, n['id'])]
|
||||
if not starts:
|
||||
emit({'type': 'meeting_done', 'output': '', 'error': '这张图没有入口节点'})
|
||||
return {'output': '', 'error': '这张图没有入口节点'}
|
||||
@@ -521,156 +680,256 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str,
|
||||
node = by_id.get(node_id)
|
||||
if not node:
|
||||
return False
|
||||
# ★ while 节点**不受 maxRuns 管**:它每一轮都要重新判断条件,
|
||||
# 循环几次是**条件**说了算,不是"最多执行次数"说了算。
|
||||
# 不豁免的话第二轮就被挡掉,循环只转一圈就没了
|
||||
# (踩过:执行序列 s,w0,wh,a,w1 之后直接结束)。
|
||||
if node['type'] == 'while':
|
||||
return True
|
||||
limit = limit_of(node)
|
||||
# 0 = 无限:永远还能再跑一次
|
||||
return limit == 0 or runs.get(node_id, 0) < limit
|
||||
|
||||
def wake_readers(var_name: str) -> None:
|
||||
"""
|
||||
某个变量被写入后,把读它的读变量节点唤醒。
|
||||
变量被写入后要做的事。
|
||||
|
||||
写变量没有输出端口(它是"汇"),所以下游不是靠连线接上的 ——
|
||||
靠这里。**不管是写变量节点写的,还是智能体用 [[SET]] 写的,
|
||||
都要走这一条**:两处不一致的话,就会出现"用节点写能读到、
|
||||
让智能体写就读不到"这种极难查的问题(测试抓到过一次)。
|
||||
★ 蓝图里"读变量"是**纯节点**(Get):它不在执行链上,值是被需要的
|
||||
节点在运行时拉取的(见 _collect_input)。所以这里**不需要**叫醒谁 ——
|
||||
留着这个函数是为了集中说明这件事,免得以后有人又加回"唤醒"逻辑,
|
||||
那会和"拉取"重复执行一遍。
|
||||
"""
|
||||
for other in nodes:
|
||||
if other['type'] == 'readvar' \
|
||||
and str(other.get('varName') or '').strip() == var_name \
|
||||
and can_run(other['id']):
|
||||
queue.append(other['id'])
|
||||
return
|
||||
|
||||
while queue and steps < max_steps:
|
||||
if should_stop and should_stop():
|
||||
emit({'type': 'meeting_done', 'output': final_output, 'aborted': True})
|
||||
return {'output': final_output, 'aborted': True}
|
||||
# 每个 while 节点转了多少轮。单次运行里超过 MAX_LOOP_ITERS 就强制跳出 ——
|
||||
# 条件永远为真时不至于把额度烧光,而且会给一条明确的事件说明为什么停。
|
||||
iters = {}
|
||||
|
||||
node_id = queue.pop(0)
|
||||
steps += 1
|
||||
if not can_run(node_id):
|
||||
continue
|
||||
def walk(seed: list, depth: int = 0, stop_at: str = None) -> bool:
|
||||
"""
|
||||
跑一串执行链,直到走不下去。
|
||||
|
||||
node = by_id.get(node_id)
|
||||
if not node:
|
||||
continue
|
||||
★ 为什么做成可递归的:while 节点的语义是"**循环体整段跑完**再回到判断"。
|
||||
用一个平铺的队列做不到这件事 —— 队列是先进先出,循环体第一个节点刚入队,
|
||||
while 自己就又被弹出来了,判断会在循环体还没跑的时候就重来一遍。
|
||||
所以循环体在这里是一次**嵌套的 walk**,跑干净了才回到 while。
|
||||
|
||||
run_index = runs.get(node_id, 0) + 1
|
||||
runs[node_id] = run_index
|
||||
node_type = node['type']
|
||||
title = node.get('title') or {'start': '初始输入', 'agent': '智能体', 'judge': '判断',
|
||||
'end': '最终输出', 'var': '写变量',
|
||||
'readvar': '读变量'}.get(node_type, node_type)
|
||||
emit({'type': 'node_start', 'nodeId': node_id, 'nodeType': node_type,
|
||||
'title': title, 'run': run_index, 'maxRuns': limit_of(node)})
|
||||
深度上限兜底:嵌套只可能来自 while 套 while,正常用不了几层。
|
||||
"""
|
||||
nonlocal steps, final_output
|
||||
queue = list(seed)
|
||||
while queue and steps < max_steps:
|
||||
if should_stop and should_stop():
|
||||
raise _Aborted()
|
||||
|
||||
incoming = _collect_input(node_id, edges, outputs)
|
||||
node_id = queue.pop(0)
|
||||
steps += 1
|
||||
if not can_run(node_id):
|
||||
continue
|
||||
|
||||
try:
|
||||
if node_type == 'start':
|
||||
# 第二轮开始,"初始输入"要把**自己上一轮的输出**当输入,
|
||||
# 否则循环回来的内容会被起点覆盖掉,重复就没意义了
|
||||
text = incoming or (node.get('text') or '').strip() or (user_input or '')
|
||||
outputs[node_id] = text
|
||||
emit({'type': 'node_done', 'nodeId': node_id, 'output': text,
|
||||
'run': run_index, 'note': '用的初始输入'})
|
||||
next_ids = [e['to'] for e in _outgoing(edges, node_id)]
|
||||
node = by_id.get(node_id)
|
||||
if not node:
|
||||
continue
|
||||
|
||||
elif node_type == 'agent':
|
||||
raw = run_agent_fn(node, incoming, settings, emit, node_id, variables)
|
||||
# ★ 把 [[SET 名字=值]] 抽出来写进变量,正文里不留那些行。
|
||||
#
|
||||
# 这件事放在**引擎**里而不是"调用引擎的那一层":
|
||||
# 它是节点语义的一部分("这个智能体能写哪些变量"是节点配置),
|
||||
# 放在外面的话 —— 换个调用方就忘了做,而且引擎自己的测试
|
||||
# 压根覆盖不到(真发生过:引擎测试全绿,一上 HTTP 就漏出 [[SET]])。
|
||||
cleaned, changed = apply_sets(raw, variables, node.get('writeVars'))
|
||||
outputs[node_id] = cleaned
|
||||
emit({'type': 'node_done', 'nodeId': node_id, 'output': cleaned, 'run': run_index})
|
||||
if changed:
|
||||
# 改了哪些变量要让用户看见,不然就是"背地里改了我的东西"
|
||||
emit({'type': 'node_vars', 'nodeId': node_id, 'vars': changed,
|
||||
'note': '、'.join(f'{k} = {str(v)[:30]}' for k, v in changed.items())})
|
||||
# 和写变量节点一样,唤醒读这些变量的节点
|
||||
for key in changed:
|
||||
wake_readers(key)
|
||||
next_ids = [e['to'] for e in _outgoing(edges, node_id)]
|
||||
run_index = runs.get(node_id, 0) + 1
|
||||
runs[node_id] = run_index
|
||||
node_type = node['type']
|
||||
title = node.get('title') or {'start': '初始输入', 'agent': '智能体', 'judge': '判断',
|
||||
'end': '最终输出', 'var': '写变量',
|
||||
'readvar': '读变量', 'while': 'while 循环'}.get(node_type, node_type)
|
||||
emit({'type': 'node_start', 'nodeId': node_id, 'nodeType': node_type,
|
||||
'title': title, 'run': run_index, 'maxRuns': limit_of(node)})
|
||||
|
||||
elif node_type == 'var':
|
||||
# 写变量节点:有上游就用上游内容当值,否则用节点里写死的
|
||||
name = str(node.get('varName') or '').strip()
|
||||
if not name:
|
||||
raise ValueError('变量节点没填变量名')
|
||||
value = (node.get('varValue') or '').strip() or incoming
|
||||
variables[name] = value
|
||||
# 写变量是"汇"(没有输出端口),唤醒读它的节点
|
||||
wake_readers(name)
|
||||
outputs[node_id] = value
|
||||
emit({'type': 'node_done', 'nodeId': node_id, 'output': value, 'run': run_index,
|
||||
'note': f'变量 {name} = {value[:40]}'})
|
||||
# 写变量没有输出端口,所以不往下游走
|
||||
next_ids = []
|
||||
incoming = _collect_input(node_id, edges, outputs, variables, by_id)
|
||||
|
||||
elif node_type == 'readvar':
|
||||
# 读变量节点:把变量的当前值当成输出往下传
|
||||
name = str(node.get('varName') or '').strip()
|
||||
if not name:
|
||||
raise ValueError('读变量节点没填变量名')
|
||||
value = variables.get(name, '')
|
||||
outputs[node_id] = value
|
||||
emit({'type': 'node_done', 'nodeId': node_id, 'output': value, 'run': run_index,
|
||||
'note': f'读到 {name}' + ('' if value else '(还没设过,是空的)')})
|
||||
next_ids = [e['to'] for e in _outgoing(edges, node_id)]
|
||||
try:
|
||||
if node_type == 'start':
|
||||
# 第二轮开始,"初始输入"要把**自己上一轮的输出**当输入,
|
||||
# 否则循环回来的内容会被起点覆盖掉,重复就没意义了
|
||||
text = incoming or (node.get('text') or '').strip() or (user_input or '')
|
||||
outputs[node_id] = text
|
||||
emit({'type': 'node_done', 'nodeId': node_id, 'output': text,
|
||||
'run': run_index, 'note': '用的初始输入'})
|
||||
next_ids = [e['to'] for e in _exec_out(edges, node_id)]
|
||||
|
||||
elif node_type == 'while':
|
||||
# ★ 和 C 的 while 一样:**先判断、再执行循环体**,假就跳出。
|
||||
#
|
||||
# 条件从**数据入线**拉(一般是"读变量"),所以循环体改了变量之后
|
||||
# 下一轮判断就能看到新值 —— 这是循环能收敛的唯一途径。
|
||||
cond_text = _collect_data_only(node_id, edges, outputs, variables, by_id)
|
||||
keep = truthy(cond_text)
|
||||
used = iters.get(node_id, 0)
|
||||
forced = False
|
||||
if keep and used >= MAX_LOOP_ITERS:
|
||||
# 转够了就强制跳出,并说清楚是为什么 ——
|
||||
# 静默停会让用户以为"条件写对了但没生效"
|
||||
forced = True
|
||||
keep = False
|
||||
|
||||
outputs[node_id] = cond_text
|
||||
emit({'type': 'node_done', 'nodeId': node_id, 'output': cond_text,
|
||||
'run': run_index, 'verdict': keep,
|
||||
'branch': 'body' if keep else 'done',
|
||||
'note': (f'第 {used + 1} 轮:条件={cond_text[:30]!r} → '
|
||||
+ ('继续循环' if keep else '结束循环'))
|
||||
+ (f'(已达上限 {MAX_LOOP_ITERS} 轮,强制结束)' if forced else '')})
|
||||
|
||||
outs = _exec_out(edges, node_id)
|
||||
if keep:
|
||||
iters[node_id] = used + 1
|
||||
body = [e['to'] for e in outs if (e.get('branch') or 'body') == 'body']
|
||||
if body:
|
||||
# ★ 每轮开始前,把**循环体里能走到的节点**的执行计数清掉。
|
||||
#
|
||||
# 不清的话,循环体里的节点第二轮就被 maxRuns(默认 1)
|
||||
# 挡在门外 —— 循环只转一圈,等于没用
|
||||
# (踩过:序列 s,w0,wh,a,w1,wh 之后第二轮 body 直接空转)。
|
||||
#
|
||||
# 语义上也讲得通:maxRuns 管的是"这个节点在这次运行里
|
||||
# 最多被走到几次",而 while 的每一轮是**一次新的执行**,
|
||||
# 该重新计数。循环次数由 while 的条件和轮次上限管。
|
||||
for nid in _reachable_exec(edges, body, stop=node_id):
|
||||
runs.pop(nid, None)
|
||||
|
||||
# 循环体整段跑完(嵌套 walk),再回到自己重新判断。
|
||||
# **必须传 stop_at=self**:循环体最后一般会连回 while,
|
||||
# 不设边界的话嵌套 walk 会一路跑回 while 自己、
|
||||
# 一层层递归下去(真踩过:循环只转一圈序列就乱了)。
|
||||
# 用 insert(0) 而不是 append:下一轮判断要紧接着循环体。
|
||||
back = walk(body, depth + 1, stop_at=node_id)
|
||||
if back:
|
||||
queue.insert(0, node_id)
|
||||
else:
|
||||
# 循环体没连回 while(用户漏画了回边):当成循环结束,
|
||||
# 不然会一直空转到轮次上限
|
||||
next_ids = [e['to'] for e in outs
|
||||
if (e.get('branch') or 'body') == 'done']
|
||||
else:
|
||||
done = [e['to'] for e in outs if (e.get('branch') or 'body') == 'done']
|
||||
next_ids = done
|
||||
if not done and outs:
|
||||
# 没连"结束"那条:顺走剩下的第一条,免得链断在这儿
|
||||
next_ids = [e['to'] for e in outs if e['to'] not in
|
||||
[b for b in next_ids]][:1]
|
||||
if keep:
|
||||
continue
|
||||
|
||||
elif node_type == 'agent':
|
||||
raw = run_agent_fn(node, incoming, settings, emit, node_id, variables)
|
||||
# ★ 把 [[SET 名字=值]] 抽出来写进变量,正文里不留那些行。
|
||||
#
|
||||
# 这件事放在**引擎**里而不是"调用引擎的那一层":
|
||||
# 它是节点语义的一部分("这个智能体能写哪些变量"是节点配置),
|
||||
# 放在外面的话 —— 换个调用方就忘了做,而且引擎自己的测试
|
||||
# 压根覆盖不到(真发生过:引擎测试全绿,一上 HTTP 就漏出 [[SET]])。
|
||||
cleaned, changed = apply_sets(raw, variables, node.get('writeVars'))
|
||||
outputs[node_id] = cleaned
|
||||
emit({'type': 'node_done', 'nodeId': node_id, 'output': cleaned, 'run': run_index})
|
||||
if changed:
|
||||
# 改了哪些变量要让用户看见,不然就是"背地里改了我的东西"
|
||||
emit({'type': 'node_vars', 'nodeId': node_id, 'vars': changed,
|
||||
'note': '、'.join(f'{k} = {str(v)[:30]}' for k, v in changed.items())})
|
||||
|
||||
# ★ 智能体是"多路"的:输出一边照常往下游走,一边**同时**存进变量。
|
||||
# 用户的原话是"既可以把输出给下一个智能体的同时也可以保存到变量"——
|
||||
# 所以做成节点上的一个字段,而不是再拉一根线到「写变量」节点:
|
||||
# 光为了存个值就得摆两个节点、连一根线,太重了。
|
||||
#
|
||||
# 两条路互不影响:下游拿到的是**剥掉 [[SET]] 之后**的正文,
|
||||
# 存进变量的也是同一份(不然变量里会混进控制行)。
|
||||
save_to = str(node.get('saveToVar') or '').strip()
|
||||
if save_to:
|
||||
variables[save_to] = cleaned
|
||||
emit({'type': 'node_vars', 'nodeId': node_id, 'vars': {save_to: cleaned},
|
||||
'note': f'输出已存到 {save_to}'})
|
||||
|
||||
next_ids = [e['to'] for e in _exec_out(edges, node_id)]
|
||||
|
||||
elif node_type == 'var':
|
||||
# 写变量节点:有上游就用上游内容当值,否则用节点里写死的
|
||||
name = str(node.get('varName') or '').strip()
|
||||
if not name:
|
||||
raise ValueError('变量节点没填变量名')
|
||||
value = (node.get('varValue') or '').strip() or incoming
|
||||
variables[name] = value
|
||||
# ★ 写变量**有 exec 出线**(蓝图里 Set 节点就是 exec 进 → exec 出),
|
||||
# 只是没有**数据**出线 —— 存进去的值不从它这里往下传。
|
||||
# 之前把它当纯"汇"(next_ids 直接空),执行链到它就断了。
|
||||
next_ids = [e['to'] for e in _exec_out(edges, node_id)]
|
||||
|
||||
elif node_type == 'readvar':
|
||||
# ★ 读变量是**纯节点**(蓝图里的 Get),正常情况下不该被执行链走到 ——
|
||||
# 它的值由 _collect_input 在需要的那一刻直接拉取。
|
||||
name = str(node.get('varName') or '').strip()
|
||||
if not name:
|
||||
raise ValueError('读变量节点没填变量名')
|
||||
value = variables.get(name, '')
|
||||
outputs[node_id] = value
|
||||
emit({'type': 'node_done', 'nodeId': node_id, 'output': value, 'run': run_index,
|
||||
'note': f'读到 {name}' + ('' if value else '(还没设过,是空的)')})
|
||||
next_ids = [e['to'] for e in _exec_out(edges, node_id)]
|
||||
|
||||
elif node_type == 'judge':
|
||||
kind = str(node.get('judgeKind') or 'not_empty')
|
||||
if kind == 'ai':
|
||||
verdict = run_agent_fn({**node, '_judgeOnly': True}, incoming, settings, emit, node_id, variables)
|
||||
passed = 'YES' in verdict.upper()[:40] or '是' in verdict[:20]
|
||||
else:
|
||||
passed = _judge_rule(node, incoming)
|
||||
# ★ 判断节点必须**透传上游内容**,不能把自己的输出改成 "true"/"false"。
|
||||
# 否则下游智能体收到的输入就变成字符串 "true" 了,完全没法用 ——
|
||||
# 这个错误是验证脚本抓到的(输出是"真 收到[true]")。
|
||||
# 判断结论走 verdict 字段,不占 output。
|
||||
outputs[node_id] = incoming
|
||||
emit({'type': 'node_done', 'nodeId': node_id,
|
||||
'output': incoming,
|
||||
'run': run_index,
|
||||
'verdict': passed,
|
||||
'branch': 'true' if passed else 'false',
|
||||
'note': f'判断结果:{passed}'})
|
||||
# 判断节点走 true / false 两条 **exec** 出边;
|
||||
# 没标分支的那条当默认(true)
|
||||
outs = _exec_out(edges, node_id)
|
||||
next_ids = [
|
||||
e['to'] for e in outs
|
||||
if (e.get('branch') or 'true') == ('true' if passed else 'false')
|
||||
]
|
||||
if not next_ids:
|
||||
# 没连对应的分支就顺走第一条,免得执行链直接断在这儿
|
||||
next_ids = [e['to'] for e in outs][:1]
|
||||
|
||||
elif node_type == 'end':
|
||||
outputs[node_id] = (node.get('text') or '').strip() or incoming
|
||||
final_output = outputs[node_id]
|
||||
emit({'type': 'node_done', 'nodeId': node_id, 'output': final_output, 'run': run_index})
|
||||
next_ids = []
|
||||
|
||||
elif node_type == 'judge':
|
||||
kind = str(node.get('judgeKind') or 'not_empty')
|
||||
if kind == 'ai':
|
||||
verdict = run_agent_fn({**node, '_judgeOnly': True}, incoming, settings, emit, node_id, variables)
|
||||
passed = 'YES' in verdict.upper()[:40] or '是' in verdict[:20]
|
||||
else:
|
||||
passed = _judge_rule(node, incoming)
|
||||
# ★ 判断节点必须**透传上游内容**,不能把自己的输出改成 "true"/"false"。
|
||||
# 否则下游智能体收到的输入就变成字符串 "true" 了,完全没法用 ——
|
||||
# 这个错误是验证脚本抓到的(输出是"真 收到[true]")。
|
||||
# 判断结论走 verdict 字段,不占 output。
|
||||
outputs[node_id] = incoming
|
||||
emit({'type': 'node_done', 'nodeId': node_id,
|
||||
'output': incoming,
|
||||
'run': run_index,
|
||||
'verdict': passed,
|
||||
'branch': 'true' if passed else 'false',
|
||||
'note': f'判断结果:{passed}'})
|
||||
# 判断节点走 true / false 两条出边;没标分支的那条当默认(true)
|
||||
outs = _outgoing(edges, node_id)
|
||||
next_ids = [
|
||||
e['to'] for e in outs
|
||||
if (e.get('branch') or 'true') == ('true' if passed else 'false')
|
||||
]
|
||||
if not next_ids:
|
||||
# 没连对应的分支就顺走第一条,免得图直接断在这儿
|
||||
next_ids = [e['to'] for e in outs][:1]
|
||||
emit({'type': 'node_error', 'nodeId': node_id, 'error': f'不认识的节点类型:{node_type}'})
|
||||
next_ids = []
|
||||
|
||||
elif node_type == 'end':
|
||||
outputs[node_id] = (node.get('text') or '').strip() or incoming
|
||||
final_output = outputs[node_id]
|
||||
emit({'type': 'node_done', 'nodeId': node_id, 'output': final_output, 'run': run_index})
|
||||
next_ids = []
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# 单个节点出错不该让整场会议停摆:记下来,继续跑下游
|
||||
emit({'type': 'node_error', 'nodeId': node_id, 'error': str(exc), 'run': run_index})
|
||||
outputs[node_id] = ''
|
||||
next_ids = [e['to'] for e in _exec_out(edges, node_id)]
|
||||
|
||||
else:
|
||||
emit({'type': 'node_error', 'nodeId': node_id, 'error': f'不认识的节点类型:{node_type}'})
|
||||
next_ids = []
|
||||
# ★ 只有"还能再跑"的节点才重新入队。
|
||||
# 这就是"重复"的开关:maxRuns=1(默认)时,跑过的节点不会再进来,
|
||||
# 环也只转一圈;把它调大,环就会来回转到次数用完为止。
|
||||
#
|
||||
# while 节点例外:它的重复靠自己的轮次计数(iters),不受 maxRuns 管 ——
|
||||
# 否则用户还得为"要循环几次"再去设一个和循环无关的数字。
|
||||
for nid in next_ids:
|
||||
if by_id.get(nid, {}).get('type') == 'while' or can_run(nid):
|
||||
queue.append(nid)
|
||||
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# 单个节点出错不该让整场会议停摆:记下来,继续跑下游
|
||||
emit({'type': 'node_error', 'nodeId': node_id, 'error': str(exc), 'run': run_index})
|
||||
outputs[node_id] = ''
|
||||
next_ids = [e['to'] for e in _outgoing(edges, node_id)]
|
||||
|
||||
# ★ 只有"还能再跑"的节点才重新入队。
|
||||
# 这就是"重复"的开关:maxRuns=1(默认)时,跑过的节点不会再进来,
|
||||
# 环也只转一圈;把它调大,环就会来回转到次数用完为止。
|
||||
for nid in next_ids:
|
||||
if can_run(nid):
|
||||
queue.append(nid)
|
||||
try:
|
||||
walk(queue)
|
||||
except _Aborted:
|
||||
emit({'type': 'meeting_done', 'output': final_output, 'aborted': True})
|
||||
return {'output': final_output, 'aborted': True}
|
||||
|
||||
emit({'type': 'meeting_done', 'output': final_output})
|
||||
return {'output': final_output}
|
||||
|
||||
Reference in New Issue
Block a user