mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-25 07:12:21 +00:00
工具审批三档、智能体护栏取代固定 12 步、检查脚本分道并行
MCP / 自定义工具的审批三档(tools/trust.py) - 平台看不出这两类工具做什么,以前审批关卡一律当它们安全、照跑不误。现在默认每次调用都等审批; 工具页可以逐个改成「始终允许 · 门控把关」或「始终允许」,审批卡上的「始终允许」等于前者 - 门控把关:每次调用先由门控模型审一遍工具说明、参数和节点任务;判可疑、出错、超时、答不成格式, 一律交还给人,不会变成放行。判定包进 checkpoint,审批恢复重放时不再问一遍 - agent 节点、工具节点、协作团队三处关卡都接上;团队成员停不下来等人,门控没放行的调用不执行 - 每次运行在发起时快照档位(runs.tool_trust),恢复和接着跑沿用同一份;正式运行不看档位,一律等审批; 升级前发起的运行照旧不问——它们可能正停在某个审批上,多问一次答复就会对错号 - 接口:GET /api/tools 带 trust / trust_key,PUT /api/tools/trust;设置新增门控模型;新事件 tool.gated - 界面:工具页三选一、审批卡「始终允许」、设置页门控模型、运行记录解码 tool.gated; 顺手修了 MCP 工具详情 404、工具审批被驳回却显示成放行 智能体护栏(engine/guards.py),取代固定的「最多 12 步」 - 步数只留兜底:默认 100,设置里可改;以前画布自动写进节点的 12 按「没填」处理 - 同一个工具、同样的参数第二次不再执行,把上次的结果交还给它;连续 3 步拿不到新信息就收尾 - 每个节点的令牌预算(默认 200 万)和金额预算(默认不限),都可以在设置里改成不限 - 上下文用到窗口的 60% 先压缩早期的工具结果,到 85% 就收尾;临近任何一个上限先提醒模型一次 - 下游结构化校验失败时写明是上游哪个 agent 提前收了尾;复核信号带上收尾原因, 问数据页只在真是步数用满时才给「放宽步数重跑」 - 上限在发起时快照(runs.agent_limits);升级前发起的运行一字不改走旧逻辑 检查脚本 - check-all 默认 4 道并行:量时间最多的两项互不重叠;并行时没过的最后单独重跑一遍,重跑才过的 单列成「偶发」。16 项全量从约 21 分钟降到约 7 分钟(加上一次重跑约 10 分钟);--lanes 1 回到串行 顺带修的 - 设置接口里的 limits 改为只读:库里存着旧版设置页写进去的一份(max_agent_steps: 25),从不生效, 却盖住了真实上限,问数据页照着错的数许诺 - test_kb 里嵌入模型那条测试不再真连 api.openai.com(代理慢时一条要等近 4 分钟) - check-stream 读滚动容器前先等它挂上,并行跑时不再偶发 验证(沙箱):tsc 干净,生产构建通过,pytest 1655 passed(两遍),check-all 16 项检查、3562 项全过; 新增后端测试 53 条,关键逻辑做了 22 处变异验证、全部抓到。
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import type {
|
||||
Approval, Conversation, ConversationDetail, ConversationTurn, CustomTool, DataSource, EvidenceGraph,
|
||||
EvidenceSegmentDetail, GraphSpec, KbDocument, MemoryItem, Provider, ReviewResult, Run, RunEvent, RunStatus,
|
||||
Skill, ToolChange, ToolInfo, ValidationIssue, VarIssue, Variable, Workflow, WorkflowVersion,
|
||||
Skill, ToolChange, ToolInfo, ToolTrust, ValidationIssue, VarIssue, Variable, Workflow, WorkflowVersion,
|
||||
} from '../types'
|
||||
import { localActor } from '../lib/actor'
|
||||
import { VALIDATION_TITLE, describeValidation } from '../lib/validation'
|
||||
@@ -487,7 +487,12 @@ export const api = {
|
||||
post<Run>(`/runs/${id}/continue`, { graph: graph ?? null }),
|
||||
// 等审批的运行直接收成 cancelled;在跑的要等引擎收尾,先回 stopping
|
||||
cancel: (id: string) => post<{ ok: boolean; status?: 'stopping' | 'cancelled' }>(`/runs/${id}/cancel`),
|
||||
resume: (id: string, response: any) => post<Run>(`/runs/${id}/resume`, { response }),
|
||||
/**
|
||||
* 回复审批。approvalId 指明回复的是哪一条(一次运行里可能有几条同时等着)。
|
||||
* 审批卡的「始终允许」走这里:response 多带 always,/approvals/{id}/decide 的请求体没有这一项
|
||||
*/
|
||||
resume: (id: string, response: any, approvalId?: string) =>
|
||||
post<Run>(`/runs/${id}/resume`, approvalId ? { response, approval_id: approvalId } : { response }),
|
||||
events: (id: string, after = 0) => get<RunEvent[]>(`/runs/${id}/events?after=${after}`),
|
||||
state: (id: string) => get<any>(`/runs/${id}/state`),
|
||||
history: (id: string) => get<any[]>(`/runs/${id}/history`),
|
||||
@@ -535,6 +540,9 @@ export const api = {
|
||||
/** 危险工具要 confirm,否则后端回 409,detail 写明它会做什么 */
|
||||
run: (name: string, args: Record<string, any>, opts?: { confirm?: boolean }) =>
|
||||
post<any>(`/tools/${name}/run`, opts?.confirm ? { args, confirm: true } : { args }),
|
||||
/** MCP / 自定义工具的信任档。key 是 ToolInfo.trust_key;设回 ask 等于删掉这一条 */
|
||||
setTrust: (key: string, trust: ToolTrust) =>
|
||||
put<{ key: string; trust: ToolTrust }>('/tools/trust', { key, trust }),
|
||||
},
|
||||
customTools: {
|
||||
/** 每行带 problem:库里存着的参数定义写坏了时是一句中文,绑了它的节点一定失败 */
|
||||
|
||||
@@ -175,7 +175,21 @@ export const NODE_DEFS: Record<NodeType, NodeDef> = {
|
||||
{ key: 'prompt', label: '任务', type: 'prompt' },
|
||||
{ key: 'tools', label: '可用工具', type: 'tools' },
|
||||
{ key: 'skills', label: '挂载 Skill', type: 'skills' },
|
||||
{ key: 'max_steps', label: '最大步数', type: 'number', min: 1, max: 100 },
|
||||
{
|
||||
key: 'max_steps', label: '最大步数', type: 'number', min: 1, max: 100, placeholder: '跟随设置',
|
||||
help: '只是兜底。重复调用、连续几步没拿到新信息、预算用完、上下文快满时,它会先按查到的部分收尾。'
|
||||
+ '留空跟随「设置 → 运行默认值」;以前默认写进来的 12 也按留空处理',
|
||||
},
|
||||
{
|
||||
key: 'budget_tokens', label: '令牌预算', type: 'number', min: 1000, step: 10000, advanced: true,
|
||||
placeholder: '跟随设置',
|
||||
help: '这个节点最多用多少令牌(输入加输出),用完就按查到的部分收尾。留空跟随设置,设置里可以改成不限',
|
||||
},
|
||||
{
|
||||
key: 'budget_usd', label: '金额预算(美元)', type: 'number', min: 0.01, step: 0.1, advanced: true,
|
||||
placeholder: '跟随设置',
|
||||
help: '按模型目录里的价格估算。目录里没有价格的模型估不出金额,只能靠令牌预算',
|
||||
},
|
||||
{
|
||||
key: 'approval', label: '审批策略', type: 'select', options: APPROVAL_OPTIONS,
|
||||
help: '需要审批时运行会暂停,等你在运行面板或记录页的审批卡上处理',
|
||||
@@ -188,7 +202,7 @@ export const NODE_DEFS: Record<NodeType, NodeDef> = {
|
||||
...MODEL_FIELDS,
|
||||
...COMMON_TAIL,
|
||||
],
|
||||
defaults: { max_steps: 12, tools: [], parallel_tools: false },
|
||||
defaults: { tools: [], parallel_tools: false },
|
||||
},
|
||||
supervisor: {
|
||||
type: 'supervisor', label: NODE_TYPE_LABEL.supervisor, category: '模型', icon: Users,
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
* 枚举值(formal / degraded / withheld 等)不动,只换显示。
|
||||
*/
|
||||
|
||||
import type { NodeType } from '../types'
|
||||
import type { NodeType, ToolTrust } from '../types'
|
||||
import { formatNumber } from './format'
|
||||
|
||||
export const TERMS = {
|
||||
@@ -231,3 +231,63 @@ export const EVIDENCE_TEXT = {
|
||||
docOtherRun: '证据文档不是这次运行写的,按普通文本显示',
|
||||
ambiguous: (candidates: string[]) => `出处不唯一:候选 ${candidates.join('、')}`,
|
||||
} as const
|
||||
|
||||
/**
|
||||
* MCP / 自定义工具的信任档:工具页的三选一、工具徽标、审批卡的「始终允许」共用这一份。
|
||||
* 「始终允许」只指 always;审批卡上那个按钮设的是 gated,按钮字短,说明里写全
|
||||
*/
|
||||
export const TOOL_TRUST_VALUES: readonly ToolTrust[] = ['ask', 'gated', 'always']
|
||||
|
||||
export const TOOL_TRUST_LABEL: Record<ToolTrust, string> = {
|
||||
ask: '等审批',
|
||||
gated: '始终允许 · 门控把关',
|
||||
always: '始终允许',
|
||||
}
|
||||
|
||||
/** 每一档悬停看的那句:它在运行时具体怎么做 */
|
||||
export const TOOL_TRUST_HINT: Record<ToolTrust, string> = {
|
||||
ask: '每次调用都停下来等你批。协作团队里的成员停不下来,这次调用不执行',
|
||||
gated: '每次调用先让门控模型看一眼参数:它放行就直接执行,判可疑、没答上来都交给你批',
|
||||
always: '不问你,直接执行',
|
||||
}
|
||||
|
||||
export const TOOL_TRUST_TEXT = {
|
||||
title: '运行时审批',
|
||||
/** 三选一的读屏名字 */
|
||||
groupLabel: (tool: string) => `${tool} 的运行时审批`,
|
||||
explain: '默认每次都等你批;门控把关是每次先让一个小模型看参数,可疑的仍然交给你;正式运行不看这个设置,一律等审批。',
|
||||
/** 工具徽标:ask 和 gated 各一个,always 不挂 */
|
||||
badgeAsk: '运行时需审批',
|
||||
badgeGated: '门控把关',
|
||||
badgeGatedHint: '在探索运行里调用它之前,先让门控模型看一眼参数,判可疑的仍然停下来等人工审批。正式运行一律等审批。',
|
||||
saveFailed: (tool: string) => `${tool} 的运行时审批没改成,已恢复原样`,
|
||||
/** 审批卡 */
|
||||
alwaysButton: '始终允许',
|
||||
alwaysHint: (tool: string) =>
|
||||
`批准这次,并把 ${tool} 设为「始终允许 · 门控把关」:本节点后面的调用和以后的运行不再问你,由门控模型逐次把关;可以在工具页改回`,
|
||||
alwaysDone: (tool: string) => `已放行,运行继续;${tool} 以后由门控模型把关`,
|
||||
} as const
|
||||
|
||||
/** 设置页「运行默认值」里的门控模型 */
|
||||
export const TOOL_GATE_TEXT = {
|
||||
label: '门控模型',
|
||||
provider: '门控模型 · 接入',
|
||||
model: '门控模型 · 模型',
|
||||
hint: '工具设成「始终允许 · 门控把关」时,每次调用前由它看一眼参数。留空就用默认接入的默认模型。每次调用都会多问它一次,建议选又快又便宜的小模型。',
|
||||
providerDefault: '默认接入',
|
||||
modelDefault: '留空:用接入的默认模型',
|
||||
} as const
|
||||
|
||||
/** 设置页「运行默认值」里 agent 护栏那一组(后端 engine/guards.py) */
|
||||
export const AGENT_GUARD_TEXT = {
|
||||
label: '智能体护栏',
|
||||
hint: '智能体不再被一个固定步数掐断:同样的调用第二次不执行、连续 3 步没拿到新信息、预算用完、上下文快满时,它会按查到的部分收尾。这里是每个智能体节点的默认上限,节点上可以单独改。只影响以后发起的运行。',
|
||||
steps: '默认最大步数',
|
||||
stepsHint: '只是兜底,正常任务碰不到',
|
||||
tokens: '令牌预算(每个节点)',
|
||||
tokensHint: '输入加输出。留空表示不限',
|
||||
usd: '金额预算(美元)',
|
||||
usdHint: '按模型目录里的价格估算;没登记价格的模型估不出来,只能靠令牌预算',
|
||||
unlimited: '不限:费用只受步数兜底和上下文约束',
|
||||
unlimitedShort: '不限',
|
||||
} as const
|
||||
|
||||
@@ -569,14 +569,16 @@ function Remedies({ conversationId, turnId, last, onRephrase, readOnly }: {
|
||||
const turn = useChat((s) => s.byConversation[conversationId]?.find((t) => t.id === turnId))
|
||||
const busy = useChat((s) => isBusy(s.byConversation[conversationId]))
|
||||
const { retryTurn, continueTurn, ask, recheck, setScope } = useChat.getState()
|
||||
const cap = useStepCap()
|
||||
const { cap, fallback } = useStepCap()
|
||||
const [resuming, setResuming] = useState(false)
|
||||
if (!turn) return null
|
||||
|
||||
const kind = remedyOf(turn)
|
||||
const graphful = (turn.graph?.nodes?.length ?? 0) > 0
|
||||
const stepSignal = turn.review?.signals.some((s) => s.kind === 'step_limit' || s.kind === 'step_limit_settled')
|
||||
const current = agentSteps(turn.graph)
|
||||
// 只有「步数用满」放宽步数才对症:因为停滞、预算、上下文收的尾,加步数只会原样再撞一次
|
||||
const stepSignal = turn.review?.signals.some((s) => (s.kind === 'step_limit' || s.kind === 'step_limit_settled')
|
||||
&& (!s.reason || s.reason === 'steps'))
|
||||
const current = fallback ? agentSteps(turn.graph, fallback) : null
|
||||
const target = current && cap ? Math.min(cap, Math.max(current * 2, current + 8)) : null
|
||||
const canContinue = !!turn.run?.id && (kind === 'suspended'
|
||||
|| (kind === 'failed' && turn.runStatus === 'failed' && turn.failure?.continuable !== false))
|
||||
@@ -788,19 +790,26 @@ function AttemptHistory({ attempts }: { attempts: Attempt[] }) {
|
||||
)
|
||||
}
|
||||
|
||||
/** 设置里 agent 步数的全局上限:「放宽步数」不能许一个后端会截掉的数 */
|
||||
let stepCapCache: Promise<number | null> | null = null
|
||||
function useStepCap(): number | null {
|
||||
const [cap, setCap] = useState<number | null>(null)
|
||||
/**
|
||||
* 设置里 agent 步数的全局上限(「放宽步数」不能许一个后端会截掉的数),和没配步数的节点
|
||||
* 跟随的默认值(运行默认值里的「默认最大步数」;老后端没有这一项,按以前的 12)
|
||||
*/
|
||||
type StepLimits = { cap: number | null; fallback: number | null }
|
||||
let stepCapCache: Promise<StepLimits> | null = null
|
||||
function useStepCap(): StepLimits {
|
||||
const [limits, setLimits] = useState<StepLimits>({ cap: null, fallback: null })
|
||||
useEffect(() => {
|
||||
stepCapCache ??= api.settings.get()
|
||||
.then((s) => Number(s?.limits?.max_agent_steps) || null)
|
||||
.catch(() => { stepCapCache = null; return null })
|
||||
.then((s) => ({
|
||||
cap: Number(s?.limits?.max_agent_steps) || null,
|
||||
fallback: Number(s?.run?.agent_max_steps) || 12,
|
||||
}))
|
||||
.catch(() => { stepCapCache = null; return { cap: null, fallback: null } })
|
||||
let alive = true
|
||||
void stepCapCache.then((v) => { if (alive) setCap(v) })
|
||||
void stepCapCache.then((v) => { if (alive) setLimits(v) })
|
||||
return () => { alive = false }
|
||||
}, [])
|
||||
return cap
|
||||
return limits
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
@@ -22,6 +22,7 @@ import type { Provider } from '../types'
|
||||
import { normalizeTheme } from '../lib/theme'
|
||||
import { useLeaveGuard } from '../lib/leave'
|
||||
import { localActor, setLocalActor } from '../lib/actor'
|
||||
import { AGENT_GUARD_TEXT, TOOL_GATE_TEXT } from '../lib/terms'
|
||||
import type { ThemePref } from '../lib/theme'
|
||||
|
||||
// 提到模块级:tab 名同时是 URL 的最后一段,两处各写一份迟早对不上。
|
||||
@@ -600,12 +601,16 @@ function ProviderEditor({ provider, catalog, onClose, onSaved }: {
|
||||
*/
|
||||
function PrefsTab() {
|
||||
const collections = useCatalog((s) => s.collections)
|
||||
const providers = useCatalog((s) => s.providers)
|
||||
const [values, setValues] = useState<Record<string, any> | null>(null)
|
||||
const [loadError, setLoadError] = useState<unknown>(null)
|
||||
const [scopes, setScopes] = useState<{ scope: string; count: number }[]>([])
|
||||
// 署名存在 localStorage,保存后成为新的基线,不再算作改动
|
||||
const savedActor = useRef<string>(localActor() ?? '')
|
||||
const [draft, setDraft] = useState<{ actor: string; scope: string; collection: string; confirm: boolean } | null>(null)
|
||||
const [draft, setDraft] = useState<{
|
||||
actor: string; scope: string; collection: string; confirm: boolean; gateProvider: string; gateModel: string
|
||||
steps: string; budgetTokens: string; budgetUsd: string
|
||||
} | null>(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [savedFlash, setSavedFlash] = useState(0)
|
||||
const [saveError, setSaveError] = useState<unknown>(null)
|
||||
@@ -628,8 +633,30 @@ function PrefsTab() {
|
||||
scope: values?.run?.default_memory_scope ?? 'default',
|
||||
collection: values?.run?.default_collection ?? 'default',
|
||||
confirm: values?.run?.confirm_dangerous_tools ?? true,
|
||||
// 门控模型:null(老后端没有这两项也一样)= 用默认接入的默认模型,表单里是空串
|
||||
gateProvider: values?.run?.tool_gate_provider ?? '',
|
||||
gateModel: values?.run?.tool_gate_model ?? '',
|
||||
// agent 护栏(后端 engine/guards.py)。表单里是字符串:预算空串 = 不限(存 null)
|
||||
steps: String(values?.run?.agent_max_steps ?? 100),
|
||||
budgetTokens: values?.run?.agent_budget_tokens == null ? '' : String(values.run.agent_budget_tokens),
|
||||
budgetUsd: values?.run?.agent_budget_usd == null ? '' : String(values.run.agent_budget_usd),
|
||||
}
|
||||
const cur = draft ?? saved
|
||||
const stepCap = Number(values?.limits?.max_agent_steps) || 100
|
||||
// 只校验改过的:存着的值不合规(比如服务端的硬上限后来调小了)不该挡住别的设置保存,
|
||||
// 后端发起运行时本来就按硬上限截
|
||||
const guardErrors = {
|
||||
steps: cur.steps === saved.steps
|
||||
|| (/^\d+$/.test(cur.steps.trim()) && Number(cur.steps) >= 1 && Number(cur.steps) <= stepCap)
|
||||
? undefined : `填 1 到 ${stepCap} 的整数(${stepCap} 是服务端的硬上限,由环境变量 AGENTLAB_MAX_AGENT_STEPS 定)`,
|
||||
budgetTokens: cur.budgetTokens === saved.budgetTokens || cur.budgetTokens.trim() === ''
|
||||
|| (/^\d+$/.test(cur.budgetTokens.trim()) && Number(cur.budgetTokens) >= 1000)
|
||||
? undefined : '填不少于 1000 的整数,或者留空表示不限',
|
||||
budgetUsd: cur.budgetUsd === saved.budgetUsd || cur.budgetUsd.trim() === ''
|
||||
|| (Number(cur.budgetUsd) > 0 && Number.isFinite(Number(cur.budgetUsd)))
|
||||
? undefined : '填大于 0 的金额,或者留空表示不限',
|
||||
}
|
||||
const guardInvalid = Object.values(guardErrors).some(Boolean)
|
||||
const changed = (Object.keys(saved) as (keyof typeof saved)[]).filter((k) => cur[k] !== saved[k])
|
||||
const dirty = values ? changed.length : 0
|
||||
// 外壳唯一的 blocker 在地址(pathname)变化时问:切标签、导航、⌘K、⌥ 数字、后退都算
|
||||
@@ -651,7 +678,7 @@ function PrefsTab() {
|
||||
* 有改动才 PUT——只改了署名时不必碰服务端,断线时也存得上
|
||||
*/
|
||||
const save = async () => {
|
||||
if (!values || !dirty) return
|
||||
if (!values || !dirty || guardInvalid) return
|
||||
setSaving(true)
|
||||
setSaveError(null)
|
||||
const actor = cur.actor.trim()
|
||||
@@ -668,6 +695,11 @@ function PrefsTab() {
|
||||
default_memory_scope: cur.scope,
|
||||
default_collection: cur.collection,
|
||||
confirm_dangerous_tools: cur.confirm,
|
||||
tool_gate_provider: cur.gateProvider || null,
|
||||
tool_gate_model: cur.gateModel.trim() || null,
|
||||
agent_max_steps: Number(cur.steps),
|
||||
agent_budget_tokens: cur.budgetTokens.trim() === '' ? null : Number(cur.budgetTokens),
|
||||
agent_budget_usd: cur.budgetUsd.trim() === '' ? null : Number(cur.budgetUsd),
|
||||
}
|
||||
const out = await api.settings.put({ run })
|
||||
setValues((v) => ({ ...(v ?? {}), run: out?.run ?? run }))
|
||||
@@ -686,6 +718,18 @@ function PrefsTab() {
|
||||
const scopeOptions = [...new Set(['default', ...scopes.map((s) => s.scope), cur.scope])]
|
||||
const collectionNames = collections.map((c) => c.collection)
|
||||
const collectionMissing = !collectionNames.includes(cur.collection)
|
||||
// 门控模型留空时后端的挑法(resolve_provider):第一个启用的真实接入,没有就第一个启用的
|
||||
const enabledProviders = providers.filter((p) => p.enabled)
|
||||
const defaultProvider = enabledProviders.find((p) => p.kind !== 'mock') ?? enabledProviders[0]
|
||||
const gateProvider = cur.gateProvider ? providers.find((p) => p.name === cur.gateProvider) : defaultProvider
|
||||
const gateProviderMissing = !!cur.gateProvider && providers.length > 0 && !gateProvider
|
||||
const gateModels = (gateProvider?.models ?? []).map((m) => m.id)
|
||||
const pickGateProvider = (name: string) => {
|
||||
// 换了接入,原来填的模型不在新接入的清单里就清掉:拿 A 家的模型名去调 B 家必然失败
|
||||
const next = name ? providers.find((p) => p.name === name) : defaultProvider
|
||||
const keep = !cur.gateModel || (next?.models ?? []).some((m) => m.id === cur.gateModel) || next?.default_model === cur.gateModel
|
||||
edit({ gateProvider: name, ...(keep ? {} : { gateModel: '' }) })
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl space-y-6 pb-20">
|
||||
@@ -757,6 +801,68 @@ function PrefsTab() {
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
<div className="mt-4" role="group" aria-labelledby="pref-gate-label" aria-describedby="pref-gate-hint" data-gate-model>
|
||||
<div id="pref-gate-label" className="text-xs font-medium">{TOOL_GATE_TEXT.label}</div>
|
||||
<p id="pref-gate-hint" className="mb-2 mt-0.5 text-2xs leading-relaxed text-faint">{TOOL_GATE_TEXT.hint}</p>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Field label={TOOL_GATE_TEXT.provider} htmlFor="pref-gate-provider"
|
||||
error={gateProviderMissing ? `「${cur.gateProvider}」这个接入不存在:门控模型答不上来,每次调用都会交给你审批` : undefined}>
|
||||
{(p) => (
|
||||
<select {...p} className="field" value={cur.gateProvider} onChange={(e) => pickGateProvider(e.target.value)}>
|
||||
<option value="">
|
||||
{TOOL_GATE_TEXT.providerDefault}{defaultProvider ? `(现在是 ${defaultProvider.name})` : ''}
|
||||
</option>
|
||||
{gateProviderMissing && <option value={cur.gateProvider}>{cur.gateProvider}(不存在)</option>}
|
||||
{providers.map((pv) => (
|
||||
<option key={pv.id} value={pv.name}>{pv.name}{pv.enabled ? '' : '(已停用)'}</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</Field>
|
||||
<Field label={TOOL_GATE_TEXT.model} htmlFor="pref-gate-model"
|
||||
hint={gateProvider?.default_model ? `留空就用 ${gateProvider.default_model}` : undefined}>
|
||||
{(p) => (
|
||||
<>
|
||||
<input {...p} className="field mono text-xs" value={cur.gateModel} list="pref-gate-models"
|
||||
placeholder={TOOL_GATE_TEXT.modelDefault} spellCheck={false}
|
||||
onChange={(e) => edit({ gateModel: e.target.value })} />
|
||||
<datalist id="pref-gate-models">
|
||||
{gateModels.map((m) => <option key={m} value={m} />)}
|
||||
</datalist>
|
||||
</>
|
||||
)}
|
||||
</Field>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4" role="group" aria-labelledby="pref-guard-label" aria-describedby="pref-guard-hint" data-agent-guard>
|
||||
<div id="pref-guard-label" className="text-xs font-medium">{AGENT_GUARD_TEXT.label}</div>
|
||||
<p id="pref-guard-hint" className="mb-2 mt-0.5 text-2xs leading-relaxed text-faint">{AGENT_GUARD_TEXT.hint}</p>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<Field label={AGENT_GUARD_TEXT.steps} htmlFor="pref-guard-steps" error={guardErrors.steps}
|
||||
hint={AGENT_GUARD_TEXT.stepsHint}>
|
||||
{(p) => (
|
||||
<input {...p} className="field tnum" inputMode="numeric" value={cur.steps}
|
||||
onChange={(e) => edit({ steps: e.target.value })} />
|
||||
)}
|
||||
</Field>
|
||||
<Field label={AGENT_GUARD_TEXT.tokens} htmlFor="pref-guard-tokens" error={guardErrors.budgetTokens}
|
||||
hint={cur.budgetTokens.trim() === '' ? AGENT_GUARD_TEXT.unlimited : AGENT_GUARD_TEXT.tokensHint}>
|
||||
{(p) => (
|
||||
<input {...p} className="field tnum" inputMode="numeric" value={cur.budgetTokens}
|
||||
placeholder={AGENT_GUARD_TEXT.unlimitedShort}
|
||||
onChange={(e) => edit({ budgetTokens: e.target.value })} />
|
||||
)}
|
||||
</Field>
|
||||
<Field label={AGENT_GUARD_TEXT.usd} htmlFor="pref-guard-usd" error={guardErrors.budgetUsd}
|
||||
hint={cur.budgetUsd.trim() === '' ? AGENT_GUARD_TEXT.unlimited : AGENT_GUARD_TEXT.usdHint}>
|
||||
{(p) => (
|
||||
<input {...p} className="field tnum" inputMode="decimal" value={cur.budgetUsd}
|
||||
placeholder={AGENT_GUARD_TEXT.unlimitedShort}
|
||||
onChange={(e) => edit({ budgetUsd: e.target.value })} />
|
||||
)}
|
||||
</Field>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
@@ -774,7 +880,11 @@ function PrefsTab() {
|
||||
<span className="text-xs">
|
||||
有 <span className="tnum">{dirty}</span> 项未保存
|
||||
<span className="ml-1.5 text-2xs text-faint">
|
||||
{changed.map((k) => ({ actor: '署名', scope: '记忆作用域', collection: '知识库', confirm: '危险工具的默认审批策略' })[k]).join('、')}
|
||||
{changed.map((k) => ({
|
||||
actor: '署名', scope: '记忆作用域', collection: '知识库', confirm: '危险工具的默认审批策略',
|
||||
gateProvider: '门控模型的接入', gateModel: '门控模型',
|
||||
steps: '默认最大步数', budgetTokens: '令牌预算', budgetUsd: '金额预算',
|
||||
})[k]).join('、')}
|
||||
</span>
|
||||
</span>
|
||||
{saveError != null && (
|
||||
@@ -783,7 +893,9 @@ function PrefsTab() {
|
||||
<span className="flex-1" />
|
||||
<button className="btn btn-sm btn-ghost" disabled={saving}
|
||||
onClick={() => { setDraft(null); setSaveError(null) }}>放弃</button>
|
||||
<button className="btn btn-sm btn-primary" disabled={saving} onClick={() => void save()}>
|
||||
<button className="btn btn-sm btn-primary" disabled={saving || guardInvalid}
|
||||
title={guardInvalid ? '护栏那几项有没填对的,改好再保存' : undefined}
|
||||
onClick={() => void save()}>
|
||||
{saving ? <Spinner size={11} /> : <Check size={12} aria-hidden />} 保存设置
|
||||
</button>
|
||||
</>
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
|
||||
import { AlertTriangle, Play, Plug, Plus, RefreshCw, Search, Terminal, Wand2, Wrench } from 'lucide-react'
|
||||
import { AlertTriangle, Play, Plug, Plus, RefreshCw, Search, ShieldCheck, Terminal, Wand2, Wrench } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { api, ApiError } from '../api/client'
|
||||
import { useCatalog, useOnReconnect } from '../store/catalog'
|
||||
import {
|
||||
confirmDialog, deferDelete, DeleteButton, EmptyState, ErrorState, Field, HealthPill, JsonInput, Kbd, Modal,
|
||||
PageHeader, SectionBar, Skeleton, Spinner, StatusBadge, TabPanel, Tabs, toast, useTabRoute, withoutDeferred,
|
||||
PageHeader, SectionBar, Skeleton, Spinner, StatusBadge, TabPanel, Tabs, toast, useRadioGroup, useTabRoute, withoutDeferred,
|
||||
} from '../components/ui'
|
||||
import { humanizeError } from '../lib/errors'
|
||||
import { formatDuration } from '../lib/format'
|
||||
import { customToolEditPath } from '../lib/explain'
|
||||
import { checkHealth, forgetHealth, healthFromServer, useHealth } from '../lib/health'
|
||||
import type { HealthRecord } from '../lib/health'
|
||||
import { ariaShortcut, matchShortcut } from '../lib/keys'
|
||||
import { workflowList, workflowsMentioning } from '../lib/mentions'
|
||||
import { TOOL_TRUST_HINT, TOOL_TRUST_LABEL, TOOL_TRUST_TEXT, TOOL_TRUST_VALUES } from '../lib/terms'
|
||||
import { useRunClock } from '../run/useRunClock'
|
||||
import type { ToolInfo } from '../types'
|
||||
import type { ToolInfo, ToolTrust } from '../types'
|
||||
|
||||
// 提到模块级:tab 名同时是 URL 的最后一段,两处各写一份迟早对不上
|
||||
const TABS = [
|
||||
@@ -164,7 +166,8 @@ function ToolLibrary() {
|
||||
return (
|
||||
<button
|
||||
key={t.id}
|
||||
onClick={() => navigate(`/tools/library/${t.id}`)}
|
||||
// MCP 工具的 id 是 mcp:服务名/工具名,带斜杠:不转义就对不上 /tools/:tab/:id,落到 404
|
||||
onClick={() => navigate(`/tools/library/${encodeURIComponent(t.id)}`)}
|
||||
aria-current={on ? 'true' : undefined}
|
||||
className={clsx(
|
||||
'relative w-full rounded-md px-2 py-1.5 text-left hover:bg-hover',
|
||||
@@ -203,6 +206,16 @@ function ToolLibrary() {
|
||||
</div>
|
||||
<p className="mb-3 text-xs leading-relaxed text-dim">{picked.description}</p>
|
||||
|
||||
{hasTrust(picked) && (
|
||||
<div className="mb-3 rounded-lg border bg-panel px-2.5 py-2" data-trust-block>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-xs font-medium">{TOOL_TRUST_TEXT.title}</span>
|
||||
<TrustControl tool={picked} />
|
||||
</div>
|
||||
<p className="mt-1 text-2xs leading-relaxed text-faint">{TOOL_TRUST_TEXT.explain}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{picked.problem && (
|
||||
<div role="alert" className="mb-3 flex items-start gap-2 rounded-lg border px-2.5 py-2 text-xs leading-relaxed" data-tool-problem-detail
|
||||
style={{ borderColor: 'color-mix(in srgb, var(--st-failed) 40%, var(--border))', background: 'var(--st-failed-soft)' }}>
|
||||
@@ -281,16 +294,28 @@ function ProblemChip({ problem }: { problem: string }) {
|
||||
|
||||
/**
|
||||
* 「运行时需审批」只给真会停下来等人的工具打(后端的 runtime_approval)。
|
||||
* 自定义和 MCP 工具在工作流里运行时审批关卡认不出它们,就明说「运行时不审批」——
|
||||
* 以前它们也挂着「需确认」,标签说的不是实话,给人虚假的安全感。
|
||||
*
|
||||
* MCP / 自定义工具按信任档说:等审批挂「运行时需审批」,门控把关挂「门控把关」,
|
||||
* 始终允许什么都不挂——它就是不会停。老后端没有信任档,那时审批关卡认不出它们,
|
||||
* 就明说「运行时不审批」:以前它们也挂着「需确认」,标签说的不是实话,给人虚假的安全感。
|
||||
*/
|
||||
function ApprovalTag({ tool, long = false }: { tool: ToolInfo; long?: boolean }) {
|
||||
const needs = tool.runtime_approval ?? (tool.source === 'builtin' && tool.dangerous)
|
||||
const trust = tool.source !== 'builtin' ? tool.trust : undefined
|
||||
if (trust === 'always') return null
|
||||
if (trust === 'gated') {
|
||||
return (
|
||||
<span className="chip shrink-0" title={TOOL_TRUST_TEXT.badgeGatedHint} data-trust-badge="gated">
|
||||
<ShieldCheck size={10} aria-hidden />{TOOL_TRUST_TEXT.badgeGated}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
const needs = trust === 'ask' || (tool.runtime_approval ?? (tool.source === 'builtin' && tool.dangerous))
|
||||
if (needs) {
|
||||
return (
|
||||
<span className="chip shrink-0" style={{ color: 'var(--st-waiting)', borderColor: 'color-mix(in srgb, var(--st-waiting) 40%, transparent)' }}
|
||||
data-trust-badge={trust ? 'ask' : undefined}
|
||||
title="在工作流里跑到它会停下来等人工审批(审批策略为「危险工具」时)。在工具库里直接执行不经审批,执行前会先说明它要做什么。">
|
||||
<StatusBadge status="waiting" size={10} decorative />运行时需审批
|
||||
<StatusBadge status="waiting" size={10} decorative />{TOOL_TRUST_TEXT.badgeAsk}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -305,6 +330,69 @@ function ApprovalTag({ tool, long = false }: { tool: ToolInfo; long?: boolean })
|
||||
return null
|
||||
}
|
||||
|
||||
/** 后端给了信任档的才显示三选一:内置工具没有,老后端也没有 */
|
||||
const hasTrust = (tool: ToolInfo | undefined | null): tool is ToolInfo & { trust: ToolTrust } =>
|
||||
!!tool && tool.source !== 'builtin' && typeof tool.trust === 'string'
|
||||
|
||||
/** MCP 工具的 name 只是裸名(search),同名的可能来自几台服务:说全称 */
|
||||
const toolLabel = (tool: ToolInfo) => (tool.source === 'mcp' ? tool.id : tool.name)
|
||||
|
||||
/** 同一个工具最近一次改档的序号:只有最后那次请求的结果算数 */
|
||||
const trustSeq = new Map<string, number>()
|
||||
|
||||
/**
|
||||
* 改信任档:先改 catalog 里的这一项(工具库、自定义工具、MCP 三处读的都是它),再 PUT;
|
||||
* 失败就改回去,并说原因。连点几档时,前面那次请求的失败不回退:界面上已经是后来
|
||||
* 选的那一档,退回去反而和最后那次请求对不上
|
||||
*/
|
||||
async function setToolTrust(tool: ToolInfo, next: ToolTrust) {
|
||||
const key = tool.trust_key ?? tool.id
|
||||
if (tool.trust === next) return
|
||||
const prev = { trust: tool.trust, runtime_approval: tool.runtime_approval }
|
||||
const seq = (trustSeq.get(key) ?? 0) + 1
|
||||
trustSeq.set(key, seq)
|
||||
const patch = (fields: Partial<ToolInfo>) => useCatalog.setState((s) => ({
|
||||
tools: s.tools.map((t) => ((t.trust_key ?? t.id) === key && t.source === tool.source ? { ...t, ...fields } : t)),
|
||||
}))
|
||||
patch({ trust: next, runtime_approval: next !== 'always' })
|
||||
try {
|
||||
const out = await api.tools.setTrust(key, next)
|
||||
// 后端可能把值规范过(比如 key 在表里已经删了):以它回的为准
|
||||
if (trustSeq.get(key) === seq && out?.trust && out.trust !== next && TOOL_TRUST_VALUES.includes(out.trust)) {
|
||||
patch({ trust: out.trust, runtime_approval: out.trust !== 'always' })
|
||||
}
|
||||
} catch (e) {
|
||||
if (trustSeq.get(key) !== seq) return
|
||||
patch(prev)
|
||||
const h = humanizeError(e)
|
||||
toast.error(`${TOOL_TRUST_TEXT.saveFailed(toolLabel(tool))}:${h.reason ? `${h.title},${h.reason}` : h.title}`,
|
||||
{ detail: h.raw })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 信任档三选一。整组一个 Tab 位、方向键切换(useRadioGroup),选中即保存:
|
||||
* 这是偏好不是表单,和主题一样不设「保存」按钮。没有信任档的(内置、老后端)不画
|
||||
*/
|
||||
function TrustControl({ tool }: { tool: ToolInfo | null | undefined }) {
|
||||
const radio = useRadioGroup(TOOL_TRUST_VALUES, tool?.trust, (v) => { if (tool) void setToolTrust(tool, v) })
|
||||
if (!hasTrust(tool)) return null
|
||||
return (
|
||||
<span role="radiogroup" aria-label={TOOL_TRUST_TEXT.groupLabel(toolLabel(tool))}
|
||||
className="inline-flex shrink-0 whitespace-nowrap rounded-md border p-px"
|
||||
data-trust-control={tool.trust_key ?? tool.id} data-trust={tool.trust}>
|
||||
{TOOL_TRUST_VALUES.map((v) => (
|
||||
<button key={v} type="button" {...radio(v)} title={TOOL_TRUST_HINT[v]}
|
||||
className={clsx('rounded px-1.5 text-2xs leading-5 transition-colors',
|
||||
v === tool.trust ? 'bg-accent-soft text-fg' : 'text-faint hover:text-dim')}
|
||||
onClick={() => void setToolTrust(tool, v)}>
|
||||
{TOOL_TRUST_LABEL[v]}
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行 / 试跑的结果。
|
||||
*
|
||||
@@ -472,6 +560,9 @@ const PARAMS_NONE = { type: 'object', properties: {}, required: [] }
|
||||
|
||||
function CustomTools() {
|
||||
const refresh = useCatalog((s) => s.refresh)
|
||||
// 信任档在工具目录(GET /tools)里,按名字对上。停用的不在目录里,也就没有这一项
|
||||
const catalogTools = useCatalog((s) => s.tools)
|
||||
const trustOf = (row: any) => catalogTools.find((t) => t.source === 'custom' && t.id === row.name && hasTrust(t))
|
||||
const navigate = useNavigate()
|
||||
const [params, setParams] = useSearchParams()
|
||||
const [rows, setRows] = useState<any[] | null>(null)
|
||||
@@ -530,6 +621,11 @@ function CustomTools() {
|
||||
/>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{rows.some(trustOf) && (
|
||||
<p className="text-2xs leading-relaxed text-faint" data-trust-explain>
|
||||
{TOOL_TRUST_TEXT.title}:{TOOL_TRUST_TEXT.explain}
|
||||
</p>
|
||||
)}
|
||||
{rows.map((row) => (
|
||||
<div key={row.id} className="flex items-center gap-2 rounded-lg border bg-panel px-3 py-2.5">
|
||||
<div className="min-w-0 flex-1">
|
||||
@@ -543,6 +639,7 @@ function CustomTools() {
|
||||
? <div className="truncate text-xs" style={{ color: 'var(--st-failed)' }} title={row.problem}>{row.problem}</div>
|
||||
: <div className="truncate text-xs text-faint">{row.description || '没写描述:模型不知道什么时候该用它'}</div>}
|
||||
</div>
|
||||
<TrustControl tool={trustOf(row)} />
|
||||
<button className="btn btn-sm" disabled={!row.enabled}
|
||||
title={row.enabled ? '去工具库里带参数试跑' : '停用的工具不在工具库里'}
|
||||
onClick={() => navigate(`/tools/library/${row.name}`)}>
|
||||
@@ -879,6 +976,11 @@ function McpServers() {
|
||||
/>
|
||||
) : (
|
||||
<div className="space-y-2.5">
|
||||
{tools.some((t) => t.source === 'mcp' && hasTrust(t)) && (
|
||||
<p className="text-2xs leading-relaxed text-faint" data-trust-explain>
|
||||
{TOOL_TRUST_TEXT.title}:{TOOL_TRUST_TEXT.explain}
|
||||
</p>
|
||||
)}
|
||||
{rows.map((row) => (
|
||||
<McpCard key={row.id} row={row} onEdit={() => setEditing(row)} onRemove={() => void remove(row)}
|
||||
onProbed={async () => { await load(); await refresh() }} />
|
||||
@@ -906,6 +1008,8 @@ function McpCard({ row, onEdit, onRemove, onProbed }: {
|
||||
}) {
|
||||
const key = `mcp:${row.id}`
|
||||
const { record: shown, checkingSince } = useHealth(key, mcpServerRecord(row))
|
||||
// 这台服务的工具,逐个设信任档(键是 mcp:服务名/工具名)
|
||||
const trusted = useCatalog((s) => s.tools).filter((t) => t.source === 'mcp' && t.id.startsWith(`mcp:${row.name}/`) && hasTrust(t))
|
||||
const probe = async () => {
|
||||
await checkHealth(key, async () => {
|
||||
const t0 = performance.now()
|
||||
@@ -940,6 +1044,17 @@ function McpCard({ row, onEdit, onRemove, onProbed }: {
|
||||
<div className="mono mt-1.5 break-all text-2xs text-faint">
|
||||
{row.transport === 'stdio' ? `${row.command ?? ''} ${(row.args ?? []).join(' ')}` : row.url}
|
||||
</div>
|
||||
{trusted.length > 0 && (
|
||||
<ul className="mt-2 rounded-md border bg-bg" aria-label={`${row.name} 的工具`}>
|
||||
{trusted.map((t) => (
|
||||
<li key={t.id} className="flex items-center gap-2 border-b border-[var(--hairline)] px-2.5 py-1.5 last:border-0">
|
||||
<span className="mono shrink-0 text-xs">{t.name}</span>
|
||||
<span className="min-w-0 flex-1 truncate text-2xs text-faint" title={t.description}>{t.description}</span>
|
||||
<TrustControl tool={t} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{shown && !shown.ok && !checkingSince && (
|
||||
<ErrorState compact error={shown} onRetry={() => void probe()} className="mt-2" />
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { Ban, Check, Hand, PenLine, Wrench } from 'lucide-react'
|
||||
import { Ban, Check, CheckCheck, Hand, PenLine, Wrench } from 'lucide-react'
|
||||
import { api } from '../api/client'
|
||||
import { useStudio } from '../store/studio'
|
||||
import { useCatalog } from '../store/catalog'
|
||||
@@ -8,7 +8,7 @@ import { NODE_DEFS } from '../canvas/nodeDefs'
|
||||
import { StatusDot, useToast } from '../components/ui'
|
||||
import { useLocalActor } from '../lib/actor'
|
||||
import { formatDateTime, formatSpan, formatTime, parseServerTime } from '../lib/format'
|
||||
import { runClassLabel, runName } from '../lib/terms'
|
||||
import { runClassLabel, runName, TOOL_TRUST_TEXT } from '../lib/terms'
|
||||
import { useRunClock } from './useRunClock'
|
||||
import { Markdown } from './Markdown'
|
||||
import type { Approval } from '../types'
|
||||
@@ -54,23 +54,39 @@ export function ApprovalCard({ approval, onResolved, showWorkflow = true }: {
|
||||
const age = created ? now - created.getTime() : undefined
|
||||
const stale = age != null && age > 24 * 3_600_000
|
||||
const approveMode = approval.mode === 'approve'
|
||||
// 探索运行里 MCP / 自定义工具的审批才带它(契约:payload.trust_key)。没有就和以前一模一样
|
||||
const trustKey: string | undefined = approveMode
|
||||
? (typeof payload.trust_key === 'string' && payload.trust_key) || undefined
|
||||
: undefined
|
||||
|
||||
const decide = async (approved: boolean) => {
|
||||
/**
|
||||
* always:「始终允许」——批准这次,并让后端把这个工具设成门控把关。/approvals/{id}/decide
|
||||
* 的请求体没有 always,所以走 /runs/{id}/resume,带上 approval_id 指明是哪一条
|
||||
*/
|
||||
const decide = async (approved: boolean, always = false) => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await api.approvals.decide(approval.id, {
|
||||
approved,
|
||||
note,
|
||||
...(!approveMode ? { value } : {}),
|
||||
})
|
||||
if (always && trustKey) {
|
||||
await api.runs.resume(approval.run_id, { approved: true, always: true, note }, approval.id)
|
||||
} else {
|
||||
await api.approvals.decide(approval.id, {
|
||||
approved,
|
||||
note,
|
||||
...(!approveMode ? { value } : {}),
|
||||
})
|
||||
}
|
||||
await refreshApprovals()
|
||||
// 工具页的信任档跟着变了(后端设成了门控把关):目录重拉一次,那边不显示旧档
|
||||
if (always && trustKey) void useCatalog.getState().reload('tools')
|
||||
// 恢复后重新接上事件流:调用方给了 onResolved 就听它的
|
||||
if (onResolved) await onResolved(approval.run_id)
|
||||
else await attachRun(approval.run_id)
|
||||
// 驳回在"补充输入/编辑草稿"模式下会终止整个运行(图上没有 rejected 那条
|
||||
// 出口边),说清楚比笼统一句"已驳回"诚实
|
||||
toast(
|
||||
approved
|
||||
always && trustKey
|
||||
? TOOL_TRUST_TEXT.alwaysDone(trustKey)
|
||||
: approved
|
||||
? '已放行,运行继续'
|
||||
: approveMode ? '已驳回,走驳回那条出口' : '已驳回,本次运行终止',
|
||||
'ok',
|
||||
@@ -158,6 +174,13 @@ export function ApprovalCard({ approval, onResolved, showWorkflow = true }: {
|
||||
<button className="btn btn-primary flex-1 justify-center" disabled={busy} onClick={() => decide(true)}>
|
||||
<Check size={12} aria-hidden /> {approveMode ? '通过' : '提交'}
|
||||
</button>
|
||||
{trustKey && (
|
||||
<button className="btn flex-1 justify-center" disabled={busy} data-approval-always
|
||||
title={TOOL_TRUST_TEXT.alwaysHint(trustKey)} aria-describedby={`approval-always-${approval.id}`}
|
||||
onClick={() => decide(true, true)}>
|
||||
<CheckCheck size={12} aria-hidden /> {TOOL_TRUST_TEXT.alwaysButton}
|
||||
</button>
|
||||
)}
|
||||
<button className="btn btn-danger flex-1 justify-center" disabled={busy} onClick={() => decide(false)}>
|
||||
<Ban size={12} aria-hidden /> {approveMode ? '驳回' : '驳回并终止'}
|
||||
</button>
|
||||
@@ -168,6 +191,11 @@ export function ApprovalCard({ approval, onResolved, showWorkflow = true }: {
|
||||
? '通过 → 接着往下跑;驳回 → 走「驳回」那条出口'
|
||||
: '提交 → 用你填的内容接着跑;驳回 → 这次运行到此终止'}
|
||||
</div>
|
||||
{trustKey && (
|
||||
<div id={`approval-always-${approval.id}`} className="mt-0.5 text-2xs leading-relaxed text-dim">
|
||||
{TOOL_TRUST_TEXT.alwaysButton} → {TOOL_TRUST_TEXT.alwaysHint(trustKey)}
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-1 flex items-center gap-1 text-2xs leading-relaxed"
|
||||
style={actor ? { color: 'var(--text-dim)' } : { color: 'var(--st-waiting)' }}>
|
||||
<PenLine size={10} aria-hidden className="shrink-0" />
|
||||
|
||||
@@ -644,6 +644,20 @@ function queryTitle(sql: string, source: string): string {
|
||||
return clip(`查询 ${what}${how ? ` · ${how}` : ''}`)
|
||||
}
|
||||
|
||||
/** 审批行末尾:批的时候点了「始终允许」,这个工具之后不再问人 */
|
||||
const ALWAYS_NOTE = ',并设为「始终允许 · 门控把关」'
|
||||
|
||||
/**
|
||||
* 门控模型(工具信任档「始终允许 · 门控把关」)对一次调用的结论。team:协作团队里拦下的,
|
||||
* 成员停不下来等人,这次调用不执行。没有工具名(老数据、字段缺了)就说「一次工具调用」
|
||||
*/
|
||||
function gateTitle(tool: string, verdict: 'allow' | 'escalate' | 'team', reason: string): string {
|
||||
const what = tool ? ` ${tool}` : '一次工具调用'
|
||||
const head = verdict === 'allow' ? `门控放行${what}`
|
||||
: `门控拦下${what},${verdict === 'team' ? '协作团队里不执行' : '交给人工审批'}`
|
||||
return reason ? `${head}:${reason}` : head
|
||||
}
|
||||
|
||||
/**
|
||||
* 几种「看着跑完了、其实没做成」的状况(NI-3/4/5)。后端这几条日志是写给排查的,原样
|
||||
* 贴出来是一串标记和术语,而且不说该去哪儿改——这里说成人话,并给出下一步。
|
||||
@@ -1027,6 +1041,11 @@ export function decodeRun(events: RunEvent[], final?: RunFinal, opts?: DecodeOpt
|
||||
const teams = new Map<string, TeamRunEx>()
|
||||
/** node_id → 校验节点最近一次修复。被作废的说明(repair_invented)折进这一行 */
|
||||
const repairs = new Map<string, Step>()
|
||||
/**
|
||||
* node_id → 门控拦下、还没见到下文的调用。下文是 human.requested(agent、工具节点:交给人批),
|
||||
* 或者 code 为 tool_needs_approval 的 log(协作团队:成员停不下来,这次不执行)
|
||||
*/
|
||||
const escalated = new Map<string, { step: Step; tool: string; reason: string }[]>()
|
||||
/** node_id → 起止时刻。用来事后认出"哪几个节点是同时跑的" */
|
||||
const spans = new Map<string, { start: number; end: number; ms: number }>()
|
||||
|
||||
@@ -1093,12 +1112,12 @@ export function decodeRun(events: RunEvent[], final?: RunFinal, opts?: DecodeOpt
|
||||
const what = approved === false ? '驳回了' : '放行了'
|
||||
return who ? `${who} ${what}` : `已${what.slice(0, 2)}`
|
||||
}
|
||||
const closeInterrupt = (key: string, approved: unknown, note: string, actor?: unknown): boolean => {
|
||||
const closeInterrupt = (key: string, approved: unknown, note: string, actor?: unknown, always = false): boolean => {
|
||||
const step = openInterrupts.get(key)
|
||||
if (!step) return false
|
||||
step.status = 'done'
|
||||
step.level = undefined
|
||||
step.title = `${step.title} → ${verdict(approved, actor)}`
|
||||
step.title = `${step.title} → ${verdict(approved, actor)}${always ? ALWAYS_NOTE : ''}`
|
||||
if (note) step.detail = [step.detail, `备注:${note}`].filter(Boolean).join('\n')
|
||||
openInterrupts.delete(key)
|
||||
return true
|
||||
@@ -1456,6 +1475,31 @@ export function decodeRun(events: RunEvent[], final?: RunFinal, opts?: DecodeOpt
|
||||
break
|
||||
}
|
||||
|
||||
case 'tool.gated': {
|
||||
// 放行是安静的一行(接着就是正常的工具调用);拦下的要人看见,并说清交给了谁。
|
||||
// 要调什么是那次模型调用答出来的,问门控时它已经做完了(同 tool.start)
|
||||
closeLlm(nodeId, 'done', at)
|
||||
const tool = typeof d.tool === 'string' ? d.tool : ''
|
||||
const reason = typeof d.reason === 'string' ? d.reason.trim() : ''
|
||||
const allow = d.verdict === 'allow'
|
||||
const full = gateTitle(tool, allow ? 'allow' : 'escalate', reason)
|
||||
const step: Step = {
|
||||
id: `gt-${seq}`, seq, kind: 'note', nodeId, status: 'done', code: 'tool_gated',
|
||||
level: allow ? 'info' : 'warn',
|
||||
title: clip(full, 120),
|
||||
...(full.length > 120 ? { detail: reason } : {}),
|
||||
...(d.agent ? { sub: `${d.agent} 调用` } : {}),
|
||||
meta: [typeof d.model === 'string' && d.model ? `门控 ${d.model}` : '', dur(num(d.duration_ms)) ?? '']
|
||||
.filter(Boolean).join(' · ') || undefined,
|
||||
}
|
||||
push(step, nodeId)
|
||||
if (!allow) {
|
||||
const key = nodeId ?? '_'
|
||||
escalated.set(key, [...(escalated.get(key) ?? []), { step, tool, reason }])
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
case 'sandbox.start':
|
||||
pendingTools.set(`sandbox-${nodeId ?? seq}`, (() => {
|
||||
const step: Step = {
|
||||
@@ -1514,6 +1558,8 @@ export function decodeRun(events: RunEvent[], final?: RunFinal, opts?: DecodeOpt
|
||||
// 节点重放又来一条 human.requested(LangGraph 的重放语义,不是 bug)。
|
||||
// 三条都指向同一次"等你确认",界面上只该有一条。
|
||||
trackTeam(event)
|
||||
// 门控拦下的那次调用交到了人手里:「交给人工审批」说的是实话,不会再等协作团队那条 log
|
||||
escalated.delete(nodeId ?? '_')
|
||||
const payload = d.payload ?? d
|
||||
const key = String(payload.node_id ?? nodeId ?? '_')
|
||||
if (openInterrupts.has(key)) { // 同一次中断的后续事件
|
||||
@@ -1545,16 +1591,20 @@ export function decodeRun(events: RunEvent[], final?: RunFinal, opts?: DecodeOpt
|
||||
}
|
||||
|
||||
case 'human.resolved': {
|
||||
const r = d.response ?? {}
|
||||
const approved = typeof r === 'object' ? r.approved : undefined
|
||||
const note = typeof r === 'object' ? String(r.note ?? '') : ''
|
||||
// 人工节点把答复包在 response 里;agent / 工具节点的工具审批是平铺的 {tool, approved, note, always}。
|
||||
// 以前只读 response,工具审批被驳回也写成「放行了」
|
||||
const r = d.response && typeof d.response === 'object' ? d.response : d
|
||||
const approved = r.approved
|
||||
const note = String(r.note ?? '')
|
||||
// 审批卡上点的是「始终允许」:批了这次,这个工具之后改由门控把关
|
||||
const always = r.always === true || d.always === true
|
||||
const actor = d.actor !== undefined ? d.actor : resumedActor
|
||||
if (closeInterrupt(String(nodeId ?? '_'), approved, note, actor)) break
|
||||
if (closeInterrupt(String(nodeId ?? '_'), approved, note, actor, always)) break
|
||||
// 没有对应的待决审批(历史事件不全、或者审批发生在别处)——
|
||||
// 还是要把决定说出来,只是没地方折进去
|
||||
push({
|
||||
id: `hr-${seq}`, seq, kind: 'human', nodeId, status: 'done',
|
||||
title: verdict(approved, actor),
|
||||
title: `${verdict(approved, actor)}${always ? ALWAYS_NOTE : ''}`,
|
||||
detail: note || undefined,
|
||||
}, nodeId)
|
||||
break
|
||||
@@ -1751,6 +1801,24 @@ export function decodeRun(events: RunEvent[], final?: RunFinal, opts?: DecodeOpt
|
||||
nodeId)
|
||||
break
|
||||
}
|
||||
if (d.code === 'tool_needs_approval') {
|
||||
// 门控刚拦下的调用落在协作团队里:成员停不下来等人,这次调用不执行。折进门控那一行,
|
||||
// 改口说「协作团队里不执行」,而不是先说交给人工、再冒出一行不执行。成员并行时几条
|
||||
// 可能交错,按日志带的 tool 认(老后端没有这个字段,按原话里的工具名认);认不出就是最近那一条
|
||||
const list = escalated.get(nodeId ?? '_')
|
||||
if (list?.length) {
|
||||
const named = typeof d.tool === 'string' && d.tool ? d.tool : ''
|
||||
let i = list.length - 1
|
||||
for (let j = list.length - 1; j >= 0; j -= 1) {
|
||||
if (list[j].tool && (named ? list[j].tool === named : message.includes(list[j].tool))) { i = j; break }
|
||||
}
|
||||
const [gate] = list.splice(i, 1)
|
||||
const full = gateTitle(gate.tool, 'team', gate.reason)
|
||||
gate.step.title = clip(full, 120)
|
||||
gate.step.detail = [full.length > 120 ? gate.reason : '', message].filter(Boolean).join('\n') || undefined
|
||||
break
|
||||
}
|
||||
}
|
||||
// 其余 info 是给排查用的,不进主流程——但 warn/error 用户必须看到
|
||||
if (level === 'info' || !message) break
|
||||
const code = typeof d.code === 'string' && d.code ? d.code : undefined
|
||||
|
||||
@@ -1138,11 +1138,17 @@ function attemptOf(t: ChatTurn): Attempt {
|
||||
return { ...base, outcome: 'done', summary: '上一次的答案' }
|
||||
}
|
||||
|
||||
/** 图里 agent 节点的步数上限(取最大的那个)。没配就是后端的默认 12 */
|
||||
export function agentSteps(graph: GraphSpec | null | undefined): number | null {
|
||||
/**
|
||||
* 图里 agent 节点的步数上限(取最大的那个)。没配的跟随设置里的默认值 fallback;
|
||||
* 以前画布自动写进去的 12 后端按「没配」处理(engine/guards.py),这里口径一致
|
||||
*/
|
||||
export function agentSteps(graph: GraphSpec | null | undefined, fallback: number): number | null {
|
||||
const agents = (graph?.nodes ?? []).filter((n: any) => n.type === 'agent')
|
||||
if (!agents.length) return null
|
||||
return Math.max(...agents.map((n: any) => Number(n.data?.config?.max_steps) || 12))
|
||||
return Math.max(...agents.map((n: any) => {
|
||||
const steps = Number(n.data?.config?.max_steps)
|
||||
return steps > 0 && steps !== 12 ? steps : fallback
|
||||
}))
|
||||
}
|
||||
|
||||
function withMaxSteps(graph: GraphSpec, steps: number): GraphSpec {
|
||||
|
||||
+24
-1
@@ -125,6 +125,10 @@ export interface Approval {
|
||||
node_id: string
|
||||
mode: 'approve' | 'input' | 'edit'
|
||||
title: string
|
||||
/**
|
||||
* 工具审批的 payload 是 {kind: 'tool_approval', tool, args, title}。探索运行里 MCP /
|
||||
* 自定义工具的审批另带 trust_key(同 ToolInfo.trust_key):有它,审批卡才给「始终允许」
|
||||
*/
|
||||
payload: Record<string, any>
|
||||
status: string
|
||||
response: Record<string, any>
|
||||
@@ -165,6 +169,13 @@ export interface Provider extends ServerHealth {
|
||||
has_key: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* MCP / 自定义工具在探索运行里的信任档(节点审批策略为「仅危险工具」时才看它):
|
||||
* ask 每次等人批(默认);gated 每次先问门控模型,它判可疑的仍交给人;always 直接执行。
|
||||
* 正式运行不看它,一律按 ask
|
||||
*/
|
||||
export type ToolTrust = 'ask' | 'gated' | 'always'
|
||||
|
||||
export interface ToolInfo {
|
||||
id: string
|
||||
name: string
|
||||
@@ -172,8 +183,15 @@ export interface ToolInfo {
|
||||
category: string
|
||||
source: 'builtin' | 'custom' | 'mcp'
|
||||
dangerous: boolean
|
||||
/** 运行时是否真的会因它停下来等审批。MCP 与自定义工具目前不会,界面别说它「需确认」 */
|
||||
/**
|
||||
* 运行时可能停下来等审批。MCP / 自定义工具:ask、gated 为 true,always 为 false;
|
||||
* 更老的后端一律给 false(那时审批关卡认不出它们)
|
||||
*/
|
||||
runtime_approval?: boolean
|
||||
/** 只有 MCP / 自定义工具有,老后端不给:没有它就不显示信任档控件 */
|
||||
trust?: ToolTrust
|
||||
/** 改信任档时用的键(PUT /api/tools/trust),等于 id */
|
||||
trust_key?: string
|
||||
schema: Record<string, any>
|
||||
/**
|
||||
* 只有自定义工具有:库里存着的参数定义哪里写坏了(一句中文)。绑了它的节点运行时
|
||||
@@ -487,6 +505,11 @@ export interface ReviewSignal {
|
||||
detail: string
|
||||
/** broken = 答案不可信;degraded = 能用但有缺口 */
|
||||
severity: 'broken' | 'degraded'
|
||||
/**
|
||||
* agent 为什么提前收尾(后端 engine/guards.py):steps / stall / budget_tokens / budget_usd / context。
|
||||
* 老运行没有。只有 steps(或者没有这个字段的老运行)放宽步数才对症
|
||||
*/
|
||||
reason?: string
|
||||
}
|
||||
|
||||
export interface ReviewResult {
|
||||
|
||||
Reference in New Issue
Block a user