Files
AgentLab/frontend/src/run/derive.ts
T
ThearchyHelios 38addf8f5d 驳回出口与子工作流证据(前端):画布多一个「驳回」出口、走了驳回出口的那一步画「被驳回」、子工作流里的步骤和证据有名字
接后端两个提交(docs/design/orchestration-round/00-总方案.md §2、§3):

- canvas/nodeDefs:会被人驳回的节点多一个「驳回」出口(id rejected,和后端 REJECT_HANDLE 同一个,中性色):人工节点三种
  模式、双盲复算一律给;沙箱代码只在审批策略是每次审批时给;调用工具选了工具、审批策略不是从不审批时给(数据源的查询
  只读,只在明说每次审批时给)。出口跟着配置算:改成不会被驳回时,studio 原有的出口同步把连在驳回出口上的线收掉;补充输入
  改成审批时普通出口的线跟到「批准」
- run/trace:node.finished 带 outcome=rejected 时这一步收成 rejected(exited,记下转到哪几步),下一次执行开始时清掉;
  子工作流里的步骤不另算一路并行
- run/derive:接了驳回出口的关卡按出口路由(驳回出口 / 其余是普通出口,同 compiler._make_router);走了驳回出口的算
  「送出了数据」,下游照常排队、跑完,普通出口那一侧未到达;退回修改时两条出口都算走过;withSubSteps 把子工作流里的
  步骤排在子工作流那一步后面(泳道、航迹的节点列表)
- run/decode:走了驳回出口的那一步状态 rejected、副标题写谁驳回、备注、转到哪一步;终态写「完成(途经驳回)」和途经的
  那几步(run.finished 的 rejected_via),没有途经的一字不变;子工作流里的步骤名接上子工作流的名字
- run/useNodeView:回放时「走了驳回出口」只说被驳回的那一刻
- canvas/NodeCard、pages/runs/TracePane:走了驳回出口的节点卡写「被驳回,转到「X」」,航迹节点卡写出口和转到哪,关键时刻
  多一条「「审批」被驳回,转到「X」」、结局写「运行完成(途经驳回)」
- run/EvidencePanel、types:输入来源写明经哪个子工作流的哪个出口字段;子工作流里的节点(「sub/…」,画布上没有)照证据接口
  给的名字写(node_label、subgraph_label),悬停写 id;停在子工作流入口的写「子工作流的运行输入」
- lib/terms:REJECTED_TEXT 加出口、走出口那一步、途经驳回的说法;EVIDENCE_TEXT 加经子工作流的说法

检查脚本:check-decode(驳回出口的步骤、航迹、走过的边、跑到一半、批准走普通出口;子工作流步骤名)、check-run-states
(reject-exit:卡片状态与剪影、槽里写转到哪、驳回边走过批准边没走、运行成功)、check-studio(各类节点的出口、能连能画、
改配置收掉驳回线、改模式线跟过去)、check-evidence(subgraph:输入来源写明经哪个子工作流、子图节点写名字)
2026-10-18 16:30:39 +08:00

381 lines
16 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { NodeState, NodeTrace, Trace } from './trace'
/**
* 图结构上的推导:拓扑序、哪些边真的走过、哪些节点在排队 / 被阻断 / 没走到。
*
* 和 trace.ts 分开:航迹只认事件,这里只认图。"没亮的那几个节点"光看事件分不
* 出是还没轮到、被分支绕开了,还是因为上游失败被堵住了——它们都只是"没有事件"。
* 三种情况要做的事完全不同,所以得对照图推出来。
*
* 规则跟后端编译器对齐(compiler.py):
* - 回边从入口起 DFS 认,和 back_edges 一致。循环体连回循环节点的那条不算依赖。
* - 路由节点(分支、循环、带通过/驳回出口的人工审批)只放行它选中的那个出口;
* 选中的出口没连线时走 default。其余节点的出边全部放行。
* - 有两个以上上游的节点是 defer 汇合:等其余任务都跑完再跑一次,没走的那路不等。
*/
export interface GraphLike {
nodes: { id: string; type?: string; data?: { nodeType?: string; config?: Record<string, any> } }[]
edges: { id?: string; source: string; target: string; sourceHandle?: string | null }[]
}
type GraphEdgeLike = GraphLike['edges'][number]
export interface Topology {
/** 去掉回边后的拓扑序 */
order: string[]
/** 拓扑层级:入口是 0,往下每层 +1(取最长路径)。一次性时刻按它错开 */
rank: Record<string, number>
/** 回边的 edgeKey */
back: Set<string>
entries: string[]
}
export const edgeKey = (e: GraphEdgeLike): string =>
`${e.source}|${e.target}|${e.sourceHandle ?? ''}`
/** 画布上的边都有 id;GraphSpec 里的边可能没有,退到 edgeKey */
export const edgeIdOf = (e: GraphEdgeLike): string => e.id ?? edgeKey(e)
/**
* 节点类型。画布上的 FlowNode 的 type 是 React Flow 的渲染器键(一律 'card'),
* 真正的类型在 data.nodeType;GraphSpec 的节点没有 data.nodeType,type 就是类型
*/
const typeOf = (n: GraphLike['nodes'][number]): string | undefined => n.data?.nodeType ?? n.type
const topoCache = new WeakMap<object, { nodes: object; topo: Topology }>()
/**
* 拓扑序与回边。
*
* 缓存按边数组的引用:运行期间图不变,每条事件都重算一遍没有必要;
* 改图会换数组,缓存自然失效。
*/
export function topology(graph: GraphLike): Topology {
const hit = topoCache.get(graph.edges)
if (hit && hit.nodes === graph.nodes) return hit.topo
const ids = graph.nodes.map((n) => n.id)
const known = new Set(ids)
const edges = graph.edges.filter((e) => known.has(e.source) && known.has(e.target))
const hasIncoming = new Set(edges.map((e) => e.target))
const inputs = graph.nodes.filter((n) => typeOf(n) === 'input').map((n) => n.id)
const entries = inputs.length ? inputs : ids.filter((id) => !hasIncoming.has(id))
const adj = new Map<string, GraphEdgeLike[]>()
for (const e of edges) {
const list = adj.get(e.source)
if (list) list.push(e)
else adj.set(e.source, [e])
}
// 迭代式 DFS(和后端 back_edges 同一个算法):几百个节点的图不该因为递归深度出事
const WHITE = 0, GREY = 1, BLACK = 2
const color = new Map(ids.map((id) => [id, WHITE]))
const back = new Set<string>()
for (const root of [...entries, ...ids]) {
if (color.get(root) !== WHITE) continue
const stack: [string, number][] = [[root, 0]]
color.set(root, GREY)
while (stack.length) {
const top = stack[stack.length - 1]
const out = adj.get(top[0]) ?? []
if (top[1] >= out.length) {
color.set(top[0], BLACK)
stack.pop()
continue
}
const e = out[top[1]]
top[1] += 1
const c = color.get(e.target)
if (c === GREY) back.add(edgeKey(e))
else if (c === WHITE) {
color.set(e.target, GREY)
stack.push([e.target, 0])
}
}
}
const indeg = new Map(ids.map((id) => [id, 0]))
for (const e of edges) if (!back.has(edgeKey(e))) indeg.set(e.target, (indeg.get(e.target) ?? 0) + 1)
const rank: Record<string, number> = {}
const queue = ids.filter((id) => !indeg.get(id))
queue.forEach((id) => { rank[id] = 0 })
const order: string[] = []
while (queue.length) {
const id = queue.shift()!
order.push(id)
for (const e of adj.get(id) ?? []) {
if (back.has(edgeKey(e))) continue
rank[e.target] = Math.max(rank[e.target] ?? 0, rank[id] + 1)
const left = (indeg.get(e.target) ?? 0) - 1
indeg.set(e.target, left)
if (left === 0) queue.push(e.target)
}
}
// 去掉回边后必然无环;万一有漏网的,按原顺序补在后面,不丢节点
for (const id of ids) if (!order.includes(id)) { order.push(id); rank[id] ??= 0 }
const topo = { order, rank, back, entries }
topoCache.set(graph.edges, { nodes: graph.nodes, topo })
return topo
}
/**
* 拓扑序里插上图上没有的那几个节点:子工作流里的步骤(节点 id「子工作流节点 id/…」,docs/design/orchestration-round/00-总方案.md
* §2)排在它们的子工作流节点后面(嵌套的接在上一层后面),别的(老运行里改过图的)照旧排在最后。泳道、航迹的节点列表用它
*/
export function withSubSteps(order: string[], ids: string[]): string[] {
const known = new Set(order)
const extra = ids.filter((id) => !known.has(id))
if (!extra.length) return order
const under = new Map<string, string[]>()
const rest: string[] = []
for (const id of extra) {
const cut = id.lastIndexOf('/')
const parent = cut > 0 ? id.slice(0, cut) : ''
if (parent && (known.has(parent) || extra.includes(parent))) {
const list = under.get(parent)
if (list) list.push(id)
else under.set(parent, [id])
} else rest.push(id)
}
const out: string[] = []
const put = (id: string) => {
out.push(id)
for (const child of under.get(id) ?? []) put(child)
}
for (const id of order) put(id)
for (const id of rest) put(id)
return out
}
const continueOnError = (n: GraphLike['nodes'][number] | undefined): boolean =>
n?.data?.config?.on_error === 'continue'
/** 会被人驳回、能接「驳回」出口的节点(后端 engine/schema.GATE_TYPES)。出口 id 同 canvas/nodeDefs 的 REJECT_HANDLE */
const GATE_TYPES = new Set(['human', 'tool', 'code', 'dual_check'])
const REJECT = 'rejected'
/**
* 审批模式以外的关卡接了驳回出口:只有两条路,驳回出口和其余的(普通出口)。和 compiler.py 的 _make_router 一致:
* 驳回出口以外的出口一律当 default
*/
function gateRouted(node: GraphLike['nodes'][number] | undefined, outHandles: Set<string>): boolean {
const type = node ? typeOf(node) : undefined
if (!type || !GATE_TYPES.has(type) || !outHandles.has(REJECT)) return false
return !(type === 'human' && (node?.data?.config?.mode ?? 'approve') === 'approve')
}
/**
* 这个节点是不是按出口路由的。和 compiler.py 的 needs_routing 一致:分支、循环,
* 出口里有通过/驳回的人工审批,以及接了「驳回」出口的关卡。图里没带类型时,看它做过的决定能不能对上
* 某个出口。
*/
function isRouting(node: GraphLike['nodes'][number] | undefined, outHandles: Set<string>,
n: NodeTrace | undefined): boolean {
const type = node ? typeOf(node) : undefined
if (type === 'branch' || type === 'loop') return true
if (type === 'human') return outHandles.has('approved') || outHandles.has(REJECT)
if (type && GATE_TYPES.has(type)) return outHandles.has(REJECT)
if (type) return false
const decision = n?.takenHandle
return decision != null && (outHandles.has(decision) || outHandles.has('default'))
}
interface Ctx {
byId: Map<string, GraphLike['nodes'][number]>
out: Map<string, GraphEdgeLike[]>
handles: Map<string, Set<string>>
}
const ctxCache = new WeakMap<object, { nodes: object; ctx: Ctx }>()
function contextOf(graph: GraphLike): Ctx {
const hit = ctxCache.get(graph.edges)
if (hit && hit.nodes === graph.nodes) return hit.ctx
const byId = new Map(graph.nodes.map((n) => [n.id, n]))
const out = new Map<string, GraphEdgeLike[]>()
const handles = new Map<string, Set<string>>()
for (const e of graph.edges) {
const list = out.get(e.source)
if (list) list.push(e)
else out.set(e.source, [e])
const set = handles.get(e.source) ?? new Set<string>()
set.add(e.sourceHandle || 'default')
handles.set(e.source, set)
}
const ctx = { byId, out, handles }
ctxCache.set(graph.edges, { nodes: graph.nodes, ctx })
return ctx
}
/** 出口 handle 是否放行:decision 是节点做的某一次决定(undefined = 没做决定)。gate:接了驳回出口的关卡(gateRouted) */
function handleOpen(e: GraphEdgeLike, routing: boolean, decision: string | undefined,
outHandles: Set<string>, gate = false): boolean {
if (!routing) return true
const raw = e.sourceHandle || 'default'
const h = gate && raw !== REJECT ? 'default' : raw
// 路由节点没做出决定(被 skip_if 跳过):路由函数拿到 None,只走 default
if (decision == null) return h === 'default'
if (h === decision) return true
return h === 'default' && !outHandles.has(decision)
}
/** 源节点已经把数据送出来了:跑完、被跳过、容错失败、被驳回后走了驳回出口,或者循环容器正放行 body */
function sourcePassed(n: NodeTrace | undefined, node: GraphLike['nodes'][number] | undefined): boolean {
if (!n) return false
if (n.looping) return true
return n.state === 'done' || n.state === 'skipped'
|| (n.state === 'rejected' && n.exited === true)
|| (n.state === 'failed' && continueOnError(node))
}
/** 这条边此刻是否"已送达":源已放行,且(路由节点的话)当前的决定选的就是它 */
export function edgeFired(trace: Trace, graph: GraphLike, e: GraphEdgeLike): boolean {
const ctx = contextOf(graph)
const src = trace.nodes[e.source]
const node = ctx.byId.get(e.source)
if (!sourcePassed(src, node)) return false
const hs = ctx.handles.get(e.source) ?? new Set<string>()
return handleOpen(e, isRouting(node, hs, src), src?.takenHandle, hs, gateRouted(node, hs))
}
/**
* 当前正在流动的边:目标此刻真的在执行、这条边确实送达了。
*
* 只算执行中的目标——指向等待审批节点的边不算:流程是停住的,边上还有光点
* 往里流,看着像"数据在流",和事实相反。循环容器在两轮之间也不算。
*/
export function activeEdgesOf(trace: Trace, graph: GraphLike): string[] {
const out: string[] = []
for (const e of graph.edges) {
const target = trace.nodes[e.target]
if (!target || target.state !== 'running' || target.looping) continue
if (edgeFired(trace, graph, e)) out.push(edgeIdOf(e))
}
return out
}
/**
* 停住的边:目标正停在审批上、这条边确实送达了。画布把它画成静止的闸门,
* 和"正在流动"分开——流程在等人,不是在跑。
*/
export function heldEdgesOf(trace: Trace, graph: GraphLike): string[] {
const out: string[] = []
for (const e of graph.edges) {
if (trace.nodes[e.target]?.state !== 'waiting') continue
if (edgeFired(trace, graph, e)) out.push(edgeIdOf(e))
}
return out
}
const STARTED = new Set<NodeState>(['running', 'waiting', 'done', 'failed', 'skipped', 'cancelled', 'suspended', 'rejected'])
/**
* 这次运行实际走过的边:源放行过这条出口(循环里任何一轮都算),目标也确实开跑过。
* 跑完之后用它留下执行路径,而不是只点亮分支出口那一条。
*/
export function walkedEdges(trace: Trace, graph: GraphLike): Set<string> {
const ctx = contextOf(graph)
const walked = new Set<string>()
for (const e of graph.edges) {
const src = trace.nodes[e.source]
const dst = trace.nodes[e.target]
if (!src?.count && src?.state !== 'skipped') continue
if (!dst || !(dst.count > 0 || STARTED.has(dst.state))) continue
const hs = ctx.handles.get(e.source) ?? new Set<string>()
const node = ctx.byId.get(e.source)
const routing = isRouting(node, hs, src)
const gate = gateRouted(node, hs)
// 接了驳回出口的关卡:有时走驳回出口(taken 里有 rejected),有时正常结束(没有决定,或者补充输入写的 approved)。
// 「退回修改」里同一个关卡先被驳回、再被批准,两条出口都走过
const decisions = src.taken?.length
? (gate && src.count > src.taken.filter((t) => t === REJECT).length ? [...src.taken, undefined] : src.taken)
: [undefined]
if (decisions.some((dec) => handleOpen(e, routing, dec, hs, gate))) walked.add(edgeIdOf(e))
}
return walked
}
const PENDING = new Set<NodeState>(['idle', 'queued', 'blocked', 'unreached'])
/**
* 推导每个节点的状态,覆盖图上的全部节点(没有事件的也在)。
*
* - 终态(成功 / 失败 / 取消):没跑过的节点,在某个失败节点下游的是 blocked
* (on_error=continue 的失败不往下传),其余是 unreached(分支落空、运行被
* 停在半路)。
* - 进行中:没跑过、但至少有一条入边已送达的是 queued——单入边的是马上要跑,
* 汇合节点是在等另一路(defer:等其余任务跑完再跑一次)。
* - 挂起 / 空闲:不推导。挂起的运行还能接着跑,这时候说"没走到"为时过早。
*/
export function deriveStates(trace: Trace, graph: GraphLike): Record<string, NodeState> {
const ctx = contextOf(graph)
const states: Record<string, NodeState> = {}
for (const n of graph.nodes) states[n.id] = trace.nodes[n.id]?.state ?? 'idle'
const phase = trace.phase
if (phase === 'succeeded' || phase === 'failed' || phase === 'cancelled') {
const blocked = new Set<string>()
const seeds = graph.nodes.filter((n) =>
trace.nodes[n.id]?.state === 'failed' && !continueOnError(n)).map((n) => n.id)
// 顺着出边一路往下(含回边:循环体里失败了,循环的 done 出口之后也走不到了)。
// 跑过的节点保持原样,只标没跑过的
const queue = [...seeds]
const seen = new Set(queue)
while (queue.length) {
const id = queue.shift()!
for (const e of ctx.out.get(id) ?? []) {
if (seen.has(e.target) || !(e.target in states)) continue
seen.add(e.target)
if (PENDING.has(states[e.target])) blocked.add(e.target)
queue.push(e.target)
}
}
for (const id of Object.keys(states)) {
if (PENDING.has(states[id])) states[id] = blocked.has(id) ? 'blocked' : 'unreached'
}
return states
}
if (phase === 'queued' || phase === 'running' || phase === 'waiting') {
const incoming = new Map<string, GraphEdgeLike[]>()
for (const e of graph.edges) {
const list = incoming.get(e.target)
if (list) list.push(e)
else incoming.set(e.target, [e])
}
for (const id of Object.keys(states)) {
if (states[id] !== 'idle' && states[id] !== 'queued') continue
const fired = (incoming.get(id) ?? []).some((e) => edgeFired(trace, graph, e))
states[id] = fired ? 'queued' : 'idle'
}
return states
}
for (const id of Object.keys(states)) if (states[id] === 'queued') states[id] = 'idle'
return states
}
/**
* 把推导结果写回航迹。只动推导类状态(idle / queued / blocked / unreached)
* 之间的切换,事件给出的状态原样不动;没有变化时返回同一个引用。
*/
export function applyDerived(trace: Trace, graph: GraphLike): Trace {
const states = deriveStates(trace, graph)
let nodes: Record<string, NodeTrace> | null = null
for (const [id, state] of Object.entries(states)) {
const cur = trace.nodes[id]
const before = cur?.state ?? 'idle'
if (before === state || !PENDING.has(before) || !PENDING.has(state)) continue
if (!cur && state === 'idle') continue
nodes ??= { ...trace.nodes }
nodes[id] = cur
? { ...cur, state }
: { id, state, count: 0, tokensIn: 0, tokensOut: 0, costUsd: 0, tools: 0, toolsRunning: 0,
segments: [] }
}
return nodes ? { ...trace, nodes } : trace
}