diff --git a/src/agent.rs b/src/agent.rs index fc00d5c..dd702c0 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -676,6 +676,19 @@ fn refresh_own(job: &mut Job, bot_id: u64) -> Option { /// How many times in a row this very call (same tool, same arguments) already came back with the /// very same answer among the latest steps. Waiting tools are left out: there the same answer is /// the point. So is what the person answers: the same question may well get the same answer. +/// What a `browser` / `computer` call without a known action is told: the actions it has, and +/// the shape of a call. +fn bad_action(tool: &str, args: &str) -> String { + let spec = if tool == crate::browser::TOOL { crate::browser::tool(&serde_json::json!({"type": "string"})) } else { computer::specs_for(&["這台".to_string()], "這台", true).into_iter().find(|t| t["name"] == computer::TOOL).unwrap_or_default() }; + let actions: Vec<&str> = spec["parameters"]["properties"]["action"]["enum"].as_array().map(|a| a.iter().filter_map(|x| x.as_str()).collect()).unwrap_or_default(); + let given = match tools::args_of(args)["action"].as_str() { + Some(a) => format!("「{a}」不是它的動作"), + None => "沒有給 action".to_string(), + }; + let example = if tool == crate::browser::TOOL { r#"{"action": "press", "key": "ctrl+Return"}"# } else { r#"{"action": "click", "ref": "12"}"# }; + format!("沒有執行:{tool} 要用 action 指定做什麼,這一步{given}。可以用的有:{}。參數直接放在最外層,例如 {example}。", actions.join("、")) +} + /// 「一律允許」 for this computer's whole screen: what is offered when the desktop can't say /// which app a step lands in (GNOME / KDE on Wayland never can; wlroots can't for a point). const SCREEN_CONTROL_GRANT: &str = "computer:control"; @@ -1351,6 +1364,11 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< // internal per-action tool right here, so every guard below (repeat detection, // approvals, replay, the remote link, the work log) keeps its stable per-action name. for c in out.tool_calls.iter_mut() { + // (Arguments a model wrapped in {"data": …}: read as meant, see unwrapped_args.) + let props = job.req.tools.iter().find(|t| t["name"] == c.name.as_str()).map(|t| &t["parameters"]["properties"]); + if let Some(a) = tools::unwrapped_args(&c.args, props) { + c.args = a; + } computer::expand_call(c); crate::browser::expand_call(c); } @@ -1494,7 +1512,9 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< if matches!(status, ToolStatus::Failed | ToolStatus::Denied) || !repeat_note.is_empty() || output.contains(crate::computer::NOOP_TAG) { trouble.set(true); } - runs.borrow_mut().push((call.name.clone(), status == ToolStatus::Failed, output.chars().take(400).collect())); + // (A safety rule's no counts as failing too: the same block again and again.) + let failed = status == ToolStatus::Failed || (status == ToolStatus::Denied && output.starts_with("被安全規則擋下")); + runs.borrow_mut().push((call.name.clone(), failed, output.chars().take(400).collect())); job.note(crate::oplog::Record::ToolFinished { op: job.op.clone(), call_id: call.id.clone(), status: format!("{status:?}").to_lowercase(), at: crate::model::now_ms() }); send(StreamEvent::ToolStatus(call.id.clone(), status)); let body = noted(&moved, &call.id, output); @@ -1510,6 +1530,12 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< job.note(crate::oplog::Record::ToolStarted { op: job.op.clone(), call_id: call.id.clone(), name: call.name.clone(), args: call.args.clone(), replay: crate::oplog::replay_of(&call.name), at: crate::model::now_ms() }); send(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Running)); }; + // A one-tool call whose action wasn't understood (none, unknown): what it takes. + // ("No such tool", as it used to say, sent a bot trying other tools in circles.) + if call.name == crate::browser::TOOL || call.name == computer::TOOL { + finish(&mut history, &bad_action(&call.name, &call.args), ToolStatus::Failed, None); + continue; + } // Not one of this bot's abilities: it was never offered; say so instead of running it. if let Some(k) = crate::profile::ability_of(&call.name).filter(|k| job.lacks.iter().any(|l| l == k)) { finish(&mut history, &crate::profile::lacking_text(k), ToolStatus::Denied, None); @@ -4057,6 +4083,39 @@ echo 'done送出了' > done.html; (setsid pyt assert_eq!(same_failures(&[run("browser_wait", true, "x"), run("browser_wait", true, "x"), run("browser_wait", true, "x")], "browser_wait"), 0); } + #[test] + fn arguments_wrapped_in_data_are_read_as_meant() { + // What jenny-Host's model sent 65 times: the call inside a JSON string under "data". + let wrapped = r#"{"data":"{\"action\": \"press\", \"key\": \"ctrl+Return\"}"}"#; + let browser = crate::browser::tool(&serde_json::json!({"type": "string"})); + let props = Some(&browser["parameters"]["properties"]); + let mut c = ToolCall { id: "1".into(), name: crate::browser::TOOL.into(), args: tools::unwrapped_args(wrapped, props).unwrap(), status: ToolStatus::Done }; + crate::browser::expand_call(&mut c); + assert_eq!(c.name, "browser_press"); + assert_eq!(tools::args_of(&c.args)["key"], "ctrl+Return"); + // An object under the wrapper too. + assert!(tools::unwrapped_args(r#"{"arguments":{"action":"read"}}"#, props).is_some()); + // Left alone: a field the tool really has (write_terminal's input), plain text, more keys. + let term = serde_json::json!({"input": {"type": "string"}, "id": {"type": "integer"}}); + assert_eq!(tools::unwrapped_args(r#"{"input":"{\"a\":1}"}"#, Some(&term)), None); + assert_eq!(tools::unwrapped_args(r#"{"data":"ctrl+v"}"#, props), None); + assert_eq!(tools::unwrapped_args(r#"{"data":"{}","action":"read"}"#, props), None); + assert_eq!(tools::unwrapped_args(r#"{"action":"read"}"#, props), None); + } + + #[test] + fn a_call_without_a_known_action_is_told_what_the_tool_takes() { + let t = bad_action(crate::browser::TOOL, r#"{"key":"ctrl+v"}"#); + assert!(t.contains("沒有給 action") && t.contains("press") && t.contains("open") && !t.contains("沒有「browser」這個工具"), "{t}"); + let t = bad_action(crate::browser::TOOL, r#"{"action":"paste"}"#); + assert!(t.contains("「paste」不是它的動作"), "{t}"); + let t = bad_action(computer::TOOL, "{}"); + assert!(t.contains("screenshot") && t.contains("click"), "{t}"); + // A safety rule's no, again and again, stops the tool for the turn like a failure. + let blocked = |n: usize| (0..n).map(|_| ("browser".to_string(), true, "被安全規則擋下:沒有「browser」這個工具".to_string())).collect::>(); + assert_eq!(same_failures(&blocked(3), "browser"), SAME_FAILURES_STOP); + } + #[test] fn a_desktop_that_cannot_name_the_app_still_offers_always() { // GNOME / KDE on Wayland: no app name, so the grant is the screen's (it used to be none, diff --git a/src/lock.rs b/src/lock.rs index 7a92725..2ceaa65 100644 --- a/src/lock.rs +++ b/src/lock.rs @@ -99,7 +99,9 @@ mod tests { let other = take_at(&scratch("other"), Duration::ZERO); assert!(other.is_ok(), "another data folder has its own lock"); drop(first); - assert!(take_at(&p, Duration::ZERO).is_ok()); + // (With a moment's wait, as a real start has: another test starting a program right + // then holds a copy of the file — and so the lock — until that program has started.) + assert!(take_at(&p, Duration::from_secs(2)).is_ok()); } /// A copy that is closing (a relaunch) is waited for. diff --git a/src/tools.rs b/src/tools.rs index 798adc8..33462db 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -108,6 +108,27 @@ pub fn args_of(args: &str) -> Value { serde_json::from_str(if args.trim().is_empty() { "{}" } else { args }).unwrap_or(Value::Null) } +/// Fields a model has been seen to wrap a call's arguments in. +const ARG_WRAPPERS: [&str; 7] = ["data", "arguments", "args", "input", "params", "parameters", "kwargs"]; + +/// A call's arguments wrapped once more — {"data": "{\"action\": \"press\", …}"} (a small +/// model through a gateway did that 65 times in one afternoon, and every one read as "no +/// action"), {"arguments": {…}} — unwrapped. Only a lone wrapper that the tool's own schema +/// (`props`, its parameters' properties) doesn't have, holding an object or an object's JSON. +pub fn unwrapped_args(args: &str, props: Option<&Value>) -> Option { + let v: Value = serde_json::from_str(args).ok()?; + let o = v.as_object().filter(|o| o.len() == 1)?; + let (k, inner) = o.iter().next()?; + if !ARG_WRAPPERS.contains(&k.as_str()) || props.is_some_and(|p| p.get(k).is_some()) { + return None; + } + let inner = match inner { + Value::String(s) => serde_json::from_str::(s).ok()?, + other => other.clone(), + }; + inner.is_object().then(|| inner.to_string()) +} + fn arg_str(v: &Value, k: &str) -> String { v.get(k).and_then(Value::as_str).unwrap_or("").to_string() }