fix(client): authorize the scoped Pi detail tools

This commit is contained in:
WuYongJie 2026-11-17 15:45:10 +08:00
parent d503bfc3f3
commit a256305a70
3 changed files with 33 additions and 5 deletions

View File

@ -534,7 +534,7 @@ export class DetailPiAgent {
if(recovered?.phase==='received'){
const record={id:round.id,...await scoped.read(round.id)};
const saved=await parseReceipt(record,selected,'native-tools',[]).catch(()=>null);
if(saved&&['stop','toolUse'].includes(saved.stopReason))await scoped.confirm(round.id,record.bodyHash,true,saved.stopReason);
if(saved&&['stop','toolUse'].includes(saved.stopReason))await scoped.confirm(round.id,record.bodyHash,true,saved.stopReason).catch(()=>null);
}
await store.appendEvent({type:'whole_detail_original_checked',id:round.id,slotId,phase:recovered?.phase??'unknown'});
}

View File

@ -303,15 +303,18 @@ export async function runWholeDetailAgents(host, runAgent, loadKnowledge, {pause
textPending=(await canvas.detailCopyFields()).length;
}
const list=slots.filter(slot=>!written.has(slot.id)).map(({id,label})=>({id,label,state:journal.items[id]?.state}));
let stopped;
if(list.length||textPending){
await runAgent('supervisor','你是小壹详情页制作负责人。根据当前资料和固定模板,调用 delegate_image_slots 分派所有待处理图位,给出整套视觉目标和事实要求。若有文案工具,读取待填文字格并按商品事实填写。保留已写文字、品牌版式与已采纳结果。认证、质保、承重、未经证实材质或选配须填待补。等实际回执后报告完成和待补。',
JSON.stringify({product:plan.productEvidence?.brief,facts:plan.productEvidence?.facts,slots:list,textPending}),supervisor).catch(async error=>{
await store.appendEvent({type:'whole_detail_supervisor_stopped',reason:error.message});
stopped=error.message;
await store.appendEvent({type:'whole_detail_supervisor_stopped',reason:stopped});
});
}
const pending=slots.filter(slot=>!written.has(slot.id));
const summary='整套详情页共 '+slots.length+' 个图位,已回填 '+written.size+' 个'
+(textWritten||textPending?',已填写 '+textWritten+' 个文字格,'+textPending+' 个待填':'');
if(stopped&&!written.size&&!textWritten)return {text:summary+'。本次制作暂停:'+stopped};
return {text:pending.length?summary+','+pending.length+' 个待处理。\n'+pending.map(slot=>
'· '+slot.label+':'+(journal.items[slot.id]?.reason||'尚未验收')).join('\n'):summary+'。可在画布预览成品。'};
}

View File

@ -340,7 +340,15 @@ static ENTERPRISE_TOOLS: std::sync::LazyLock<Vec<&'static str>> = std::sync::Laz
.expect("enterprise read-only tool registry")
});
const DETAIL_SUPERVISOR_TOOLS: &[&str] = &["delegate_image_slots", "read_copy_fields", "write_copy_fields"];
const DETAIL_SLOT_TOOLS: &[&str] = &["view_slot", "make_candidate", "review_candidate", "place_candidate", "mark_missing"];
#[cfg(test)]
fn validate_payload(value: &Value, model: &Value) -> R<()> {
validate_scoped_payload(value, model, None)
}
fn validate_scoped_payload(value: &Value, model: &Value, detail_slot: Option<&str>) -> R<()> {
if value["model"] != model["id"] || value["stream"] != true {
return Err("只能调用当前账户已选择的流式对话模型".into());
}
@ -353,7 +361,9 @@ fn validate_payload(value: &Value, model: &Value) -> R<()> {
return Err("输出长度或候选数量超限".into());
}
if let Some(tools) = value["tools"].as_array() {
if tools.len() > ALLOWED_TOOLS.len() + ENTERPRISE_TOOLS.len() {
let expected = detail_slot.map(|slot| if slot == "supervisor" { DETAIL_SUPERVISOR_TOOLS } else { DETAIL_SLOT_TOOLS });
let limit = expected.map_or(ALLOWED_TOOLS.len() + ENTERPRISE_TOOLS.len(), <[_]>::len);
if tools.len() > limit {
return Err("工具数量超限".into());
}
let mut seen = std::collections::HashSet::new();
@ -362,7 +372,11 @@ fn validate_payload(value: &Value, model: &Value) -> R<()> {
let nested = t["function"]["name"].as_str();
if direct.is_some() && nested.is_some() && direct != nested { return Err("工具名称不一致".into()); }
let name = direct.or(nested).ok_or("工具名称无效")?;
if !ALLOWED_TOOLS.contains(&name) && !name.strip_prefix("ekb_").is_some_and(|name| ENTERPRISE_TOOLS.contains(&name)) {
let authorized = expected.map_or_else(
|| ALLOWED_TOOLS.contains(&name) || name.strip_prefix("ekb_").is_some_and(|name| ENTERPRISE_TOOLS.contains(&name)),
|names| names.contains(&name),
);
if !authorized {
return Err("工具未授权".into());
}
if !seen.insert(name) { return Err("工具名称重复".into()); }
@ -600,7 +614,10 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>) -> R<()> {
}
let payload = input["body"].as_str().filter(|s| s.len() <= LIMIT).ok_or("模型输入过大")?;
let value: Value = serde_json::from_str(payload).map_err(|_| "模型输入不是JSON")?;
validate_payload(&value, &model)?;
if detail_slot.is_some() && input["modelRole"] != "detail" {
return Err("工具未授权".into());
}
validate_scoped_payload(&value, &model, detail_slot)?;
let headers = invocation_headers(&input)?;
task = json!({"id":id,"requestId":null,"phase":"dispatched","detailSlot":detail_slot,"modelRole":input["modelRole"].as_str().unwrap_or("chat"),"model":model,"bodyHash":hash(payload),"keyFingerprint":hash(key),"createdAt":now(),"invocationHeaders":headers});
// Durable dispatch barrier BEFORE the one and only POST.
@ -1135,6 +1152,14 @@ mod tests {
let mut payload =
json!({"model":"test-model","stream":true,"max_tokens":100,"messages":[{"role":"user","content":"x"}],"tools":[{"name":"canvas_read"}]});
assert!(validate_payload(&payload, &model).is_ok());
for (scope, tools) in [("supervisor", DETAIL_SUPERVISOR_TOOLS), ("S01-I01", DETAIL_SLOT_TOOLS)] {
let mut scoped = payload.clone();
scoped["tools"] = json!(tools.iter().map(|name| json!({"type":"function","function":{"name":name}})).collect::<Vec<_>>());
assert!(validate_scoped_payload(&scoped, &model, Some(scope)).is_ok());
assert!(validate_scoped_payload(&scoped, &model, None).is_err());
let other_scope = if scope == "supervisor" { "S01-I01" } else { "supervisor" };
assert!(validate_scoped_payload(&scoped, &model, Some(other_scope)).is_err());
}
for name in ["ask_user", "workflow_read", "workflow_navigate", "workflow_propose", "workflow_execute", "codemode", "tool_search", "native_catalog", "native_call", "canvas_preview"] {
payload["tools"][0]["name"] = json!(name);
assert!(validate_payload(&payload, &model).is_ok());