//! The agent's gatekeeper (`docs/agent-environment.md`): one program per //! task, started by the terminal for `agent …`, sealed (`abi::SPAWN_SEALED`): //! no network, no service by name, no file by path. Its rights are the //! handles the terminal gave it: the model service, the display server's //! confirmation, its log, and the services and files the person named on //! the command line. Nothing else has a name in the prompt. //! //! It is the only thing that talks to the model and the only thing that //! acts for it. Everything the model says is a request: a tool call is //! checked against the verb its service described, counted against the //! budget, confirmed by the person on the trusted path when its effect //! says so, sent as the same message the person's own command would send, //! and written to the task's append-only log with the call that undoes it. //! `agent undo` replays those, newest first. //! //! The taint rule: once the task has read text the person has no reason to //! trust — the answer of a verb that says it is untrusted (the network, //! someone who is not a contact), or a file it was given, which another //! program may have written — every action that reaches others asks the //! person, each time, saying where that text came from. Private data, //! untrusted text and a way out then never meet in one task unchecked. //! //! The handles, after the command's own streams, are named in order by the //! start message's `AGENT_GRANTS`: `model`, `confirm`, `log`, then //! `service:` and `file:`. #![no_std] #![no_main] extern crate alloc; use alloc::string::String; use alloc::vec::Vec; use core::cell::{Cell, RefCell}; use pinnacle_json::Value; use pinnacle_records::verbs::{self, Confirm, Description, Effect}; use pinnacle_rt::fs::File; use pinnacle_rt::output::Output; use pinnacle_rt::{Channel, Handle}; use pinnacle_ui::confirm::{self, Question}; use pinnacle_ui::model::{self, Event}; /// The most actions a task takes, unless the terminal says fewer. const ACTIONS: u32 = 20; /// The most bytes a task sends the model, all its turns together. const BYTES: u64 = 512 * 1024; /// The most of a tool's answer the model is shown. const RESULT_MAX: usize = 8 * 1024; /// The largest file whose old content is kept to undo a write. const PRE_IMAGE_MAX: usize = 256 * 1024; const SYSTEM: &str = "You act for the person at this Pinnacle device, through the tools you are given and no \ others. Each tool is a verb of a service on the device, or a file the person gave you. Everything you ask \ is checked, logged and may be refused; the person is asked before anything leaves the device. Do what was \ asked, then say in a sentence or two what you did."; struct Service { channel: Channel, description: Description, /// On a contact's device (`name@contact`): its answers are another /// machine's, untrusted whatever its description says. remote: bool, } struct Given { name: String, file: File, } struct Task { out: Output, model: Channel, confirm: Channel, log: File, services: Vec, files: Vec, /// Actions taken: cells, as a tool borrows the task while it acts. actions: Cell, max_actions: u32, bytes: u64, /// Tools the person allowed for the rest of the task (shared effects). allowed: RefCell>, /// The tool whose answer was the first untrusted text the task read. tainted: RefCell>, request: String, } /// A tool the model may call: a service's verb, or a file tool. enum Tool<'a> { Verb(&'a Service, &'a verbs::Verb), Read(&'a Given), Write(&'a Given), } #[unsafe(no_mangle)] fn main(argument: u64) -> u64 { let out = Output::start(argument); let Some(mut task) = Task::new(out) else { return 1; }; if task.request == "undo" { return task.undo(); } task.run() } impl Task { fn new(mut out: Output) -> Option { let env = |key: &str| out.env.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone()); let names = env("AGENT_GRANTS").unwrap_or_default(); let max_actions = env("AGENT_ACTIONS") .and_then(|v| v.parse().ok()) .unwrap_or(ACTIONS); let request = out.args.iter().skip(1).cloned().collect::>().join(" "); let mut handles = core::mem::take(&mut out.extra).into_iter(); let mut take = |what: &str| -> Option { let h = handles.next(); if h.is_none() { pinnacle_rt::println!("agent: no {what} given"); } h }; let mut grants = names.split(' ').filter(|n| !n.is_empty()); if grants.next() != Some("model") || grants.next() != Some("confirm") || grants.next() != Some("log") { out.status(1, "Started without its grants: the terminal starts the agent"); return None; } let model = Channel(take("model")?); let confirm = Channel(take("confirm")?); let log = File(take("log")?); let (mut services, mut files) = (Vec::new(), Vec::new()); for grant in grants { let handle = take(grant)?; if let Some(name) = grant.strip_prefix("service:") { let channel = Channel(handle); match pinnacle_ui::verbs::describe_on(&channel) { Some(description) => services.push(Service { channel, description, remote: name.contains('@'), }), None => { out.text(&alloc::format!("{name} does not say what it can do: left out")); } } } else if let Some(name) = grant.strip_prefix("file:") { files.push(Given { name: name.into(), file: File(handle), }); } } Some(Task { out, model, confirm, log, services, files, actions: Cell::new(0), max_actions, bytes: 0, allowed: RefCell::new(Vec::new()), tainted: RefCell::new(None), request, }) } /// Adds an entry to the task's log. fn keep(&self, entry: Value) { let empty = self.log.stat().is_some_and(|s| s.size == 0); let mut entry = entry; entry.set("time", pinnacle_rt::clock().into()); let body = alloc::format!("{entry}"); if self .log .append(&pinnacle_records::log::entry(body.as_bytes(), empty)) .is_none() { pinnacle_rt::println!("agent: the log refused an entry"); } } /// The tools, as the model's API takes them: every verb of every /// service given, and a read and a write tool when files were. fn tools(&self) -> Value { let mut tools = Vec::new(); for s in &self.services { for v in &s.description.verbs { let mut about = v.about.clone(); about += &alloc::format!(" ({}.)", v.effect.describe()); tools.push(Value::object([ ( "name", alloc::format!("{}__{}", s.description.service, v.name).into(), ), ("description", about.into()), ("input_schema", v.input_schema()), ])); } } if !self.files.is_empty() { let names: Vec = self.files.iter().map(|f| f.name.as_str().into()).collect(); let file = Value::object([("type", "string".into()), ("enum", Value::Array(names))]); let schema = |extra: Option<(&str, Value)>| { let mut props = alloc::vec![(String::from("file"), file.clone())]; let mut required = alloc::vec![Value::from("file")]; if let Some((name, v)) = extra { props.push((name.into(), v)); required.push(name.into()); } Value::object([ ("type", "object".into()), ("properties", Value::Object(props)), ("required", Value::Array(required)), ("additionalProperties", false.into()), ]) }; tools.push(Value::object([ ("name", "file_read".into()), ( "description", "The text of a file the person gave you. (Only reads.)".into(), ), ("input_schema", schema(None)), ])); tools.push(Value::object([ ("name", "file_write".into()), ( "description", "Replace a file the person gave you with new text. (Changes its own data.)".into(), ), ( "input_schema", schema(Some(("text", Value::object([("type", "string".into())])))), ), ])); } Value::Array(tools) } fn tool(&self, name: &str, input: &Value) -> Option> { if let Some((service, verb)) = name.split_once("__") { let s = self.services.iter().find(|s| s.description.service == service)?; return Some(Tool::Verb(s, s.description.verb(verb)?)); } let file = self .files .iter() .find(|f| Some(f.name.as_str()) == input.get("file").as_str())?; match name { "file_read" => Some(Tool::Read(file)), "file_write" => Some(Tool::Write(file)), _ => None, } } fn run(&mut self) -> u64 { // The starter wrote what was asked and given as the log's first // entry (`pinnacle_ui::command::begin_log`). let mut messages = alloc::vec![Value::object([ ("role", "user".into()), ("content", self.request.as_str().into()), ])]; let tools = self.tools(); loop { let request = Value::object([ ("system", SYSTEM.into()), ("messages", Value::Array(messages.clone())), ("tools", tools.clone()), ("max_tokens", 2048u64.into()), ]); let size = alloc::format!("{request}").len() as u64; if self.bytes + size > BYTES { return self.end(1, "Its budget of what it may send the model is spent"); } self.bytes += size; let mut text = String::new(); let mut calls = Vec::new(); let end = model::ask(&self.model, &request, 120_000, |e| { match e { Event::Text(piece) => text.push_str(piece), Event::Call { id, name, input } => calls.push((id.clone(), name.clone(), input.clone())), _ => {} } true }); if let Event::Error(why) = end { if !text.is_empty() { self.out.text(&text); } return self.end(1, &why); } if !text.is_empty() { self.out.text(&text); } let mut content = Vec::new(); if !text.is_empty() { content.push(Value::object([("type", "text".into()), ("text", text.into())])); } for (id, name, input) in &calls { content.push(Value::object([ ("type", "tool_use".into()), ("id", id.as_str().into()), ("name", name.as_str().into()), ("input", input.clone()), ])); } messages.push(Value::object([ ("role", "assistant".into()), ("content", Value::Array(content)), ])); if calls.is_empty() { return self.end(0, ""); } let mut results = Vec::new(); for (id, name, input) in calls { let (answer, failed) = self.act(&name, &input); results.push(Value::object([ ("type", "tool_result".into()), ("tool_use_id", id.into()), ("content", answer.into()), ("is_error", failed.into()), ])); } messages.push(Value::object([ ("role", "user".into()), ("content", Value::Array(results)), ])); } } fn end(&self, code: u64, why: &str) -> u64 { let summary = alloc::format!( "{} action{}, {} KB to the model{}{}", self.actions.get(), if self.actions.get() == 1 { "" } else { "s" }, self.bytes.div_ceil(1024), if why.is_empty() { "" } else { ": " }, why ); self.keep(Value::object([("end", summary.as_str().into())])); self.out.status(code, &summary) } /// One tool call: checked, counted, confirmed where its effect says, /// done, and logged. What the model is told, and whether it failed. fn act(&self, name: &str, input: &Value) -> (String, bool) { let refuse = |task: &Task, why: &str| { task.out.text(&alloc::format!("✗ {name}: {why}")); task.keep(Value::object([ ("tool", name.into()), ("args", input.clone()), ("refused", why.into()), ])); (String::from(why), true) }; let Some(tool) = self.tool(name, input) else { return refuse(self, "there is no such tool"); }; let (effect, untrusted) = match &tool { Tool::Verb(s, v) => { if let Err(why) = v.check(input) { return refuse(self, &why); } (v.effect, v.untrusted || s.remote) } // Another program may have written it. Tool::Read(_) => (Effect::Reads, true), Tool::Write(_) => { if input.get("text").as_str().is_none() { return refuse(self, "text must be text"); } (Effect::Own, false) } }; if self.actions.get() >= self.max_actions { return refuse(self, "the task's budget of actions is spent"); } // Asked of the person by the effect; after untrusted text, each time // for anything that reaches others. let tainted = self.tainted.borrow().is_some() && effect >= Effect::Shared; let ask = match effect.confirm() { _ if tainted => true, Confirm::Never => false, Confirm::OncePerTask => !self.allowed.borrow().iter().any(|a| a == name), Confirm::EachTime => true, }; if ask { let question = self.question(&tool, input, effect); if !confirm::ask(&self.confirm, &question) { return refuse(self, "the person did not allow it"); } if effect.confirm() == Confirm::OncePerTask && !tainted { self.allowed.borrow_mut().push(name.into()); } } self.actions.set(self.actions.get() + 1); let (answer, ok, undo) = match tool { Tool::Verb(s, v) => { let result = pinnacle_ui::verbs::call(&s.channel, &v.name, input.clone(), Vec::new()); (result.text(), result.ok, result.undo) } Tool::Read(f) => match f.file.read() { Some(data) => (String::from_utf8_lossy(&data).into_owned(), true, None), None => ("it could not be read".into(), false, None), }, Tool::Write(f) => { let before = f.file.read().unwrap_or_default(); let undo = (before.len() <= PRE_IMAGE_MAX).then(|| { Value::object([ ("file", f.name.as_str().into()), ("text", String::from_utf8_lossy(&before).into_owned().into()), ]) }); let text = input.get("text").as_str().unwrap_or(""); match f.file.replace(text.as_bytes()) { true => (alloc::format!("{} written", f.name), true, undo), false => ("it could not be written".into(), false, None), } } }; if ok && untrusted && self.tainted.borrow().is_none() { *self.tainted.borrow_mut() = Some(name.into()); self.out.text(&alloc::format!( "! {name} answered with text from outside: from now on the person is asked before anything reaches others" )); } let mut entry = Value::object([ ("tool", name.into()), ("args", input.clone()), ("effect", effect.name().into()), ("ok", ok.into()), ("result", clip(&answer, 500).into()), ]); if let Some(undo) = undo { entry.set("undo", undo); } if untrusted { entry.set("untrusted", true.into()); } self.keep(entry); let mark = if ok { "✓" } else { "✗" }; self.out.text(&alloc::format!( "{mark} {name} {} — {}", clip(&alloc::format!("{input}"), 200), clip(&answer, 200) )); (clip(&answer, RESULT_MAX), !ok) } /// What the person is asked: about the effect, with what the task read. fn question(&self, tool: &Tool, input: &Value, effect: Effect) -> Question { let (service, verb) = match tool { Tool::Verb(s, v) => (s.description.service.as_str(), v.name.as_str()), Tool::Read(_) => ("a file", "read"), Tool::Write(_) => ("a file", "write"), }; let args = input .as_object() .unwrap_or(&[]) .iter() .map(|(k, v)| match v.as_str() { Some(s) => alloc::format!("{k}: {}", clip(s, 120)), None => alloc::format!("{k}: {v}"), }) .collect::>() .join(", "); let source = match &*self.tainted.borrow() { Some(from) => alloc::format!(", after reading text from {from} that is not yours to trust?"), None => "?".into(), }; Question { app: "terminal".into(), question: alloc::format!("{}: {verb} — {args}{source}", pinnacle_ui::verbs::title(service)), detail: alloc::format!( "{}. You asked: “{}”. {} action{} so far.", effect.describe(), clip(&self.request, 300), self.actions.get(), if self.actions.get() == 1 { "" } else { "s" } ), } } /// Undoes the task whose log this is: each action with an inverse, /// newest first, through the services and files given again. fn undo(&mut self) -> u64 { let data = self.log.read().unwrap_or_default(); let entries: Vec = pinnacle_records::log::entries(&data) .unwrap_or_default() .into_iter() .filter_map(|e| pinnacle_json::parse(core::str::from_utf8(e).ok()?).ok()) .collect(); if entries.iter().any(|e| e.get("undone").as_bool() == Some(true)) { return self.out.status(1, "It was undone already"); } let task = entries.iter().find_map(|e| e.get("task").as_str()).unwrap_or(""); self.out.text(&alloc::format!("Undoing “{task}”")); let (mut undone, mut failed) = (0, 0); for e in entries.iter().rev() { let undo = e.get("undo"); if undo.is_null() { continue; } let tool = e.get("tool").as_str().unwrap_or(""); let ok = if tool == "file_write" { let name = undo.get("file").as_str().unwrap_or(""); let text = undo.get("text").as_str().unwrap_or(""); self.files .iter() .find(|f| f.name == name) .is_some_and(|f| f.file.replace(text.as_bytes())) } else { let service = tool.split_once("__").map_or("", |(s, _)| s); let verb = undo.get("verb").as_str().unwrap_or(""); match self.services.iter().find(|s| s.description.service == service) { Some(s) => { pinnacle_ui::verbs::call(&s.channel, verb, undo.get("args").clone(), Vec::new()).ok } None => false, } }; let mark = if ok { "↶" } else { "✗" }; self.out.text(&alloc::format!( "{mark} {tool} {}", clip(&alloc::format!("{}", e.get("args")), 200) )); if ok { undone += 1; } else { failed += 1; } } self.keep(Value::object([("undone", true.into())])); let summary = alloc::format!( "{undone} undone{}", if failed > 0 { ", some could not be" } else { "" } ); self.out.status(u64::from(failed > 0), &summary) } } /// The first `n` characters of `s`, an ellipsis after when there were more. fn clip(s: &str, n: usize) -> String { match s.char_indices().nth(n) { Some((at, _)) => alloc::format!("{}…", &s[..at]), None => s.into(), } }