Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions apps/rustgis-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -676,6 +676,17 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen
}
let pictures = ask_pictures(args)?;
eprintln!("[{} · {}]", cfg.provider, cfg.model);
if let Ok(asked) = std::env::var(provider::PAUSE_ENV)
&& !asked.trim().is_empty()
&& !provider::Pause::understood(&asked)
{
// A notice, as the app gives it, printed here.
let mark = s.notice_mark();
s.notify(format!("{} is {asked:?}, not a number of steps (1 to 10000) or off: the default is used", provider::PAUSE_ENV), true);
for n in s.notices_since(mark) {
eprintln!("rustgis-cli: {}", n.text);
}
}
let yes = args.iter().any(|a| a == "--yes");
let trace_key = cfg.key.clone();
let mut a = Agent::new(cfg, s);
Expand Down
119 changes: 102 additions & 17 deletions crates/assistant/src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//! what came back ([`Agent::receive`]), runs the model's tool calls against the session, and
//! stops for the user's approval when a call needs it ([`Step::Confirm`]).

use std::collections::VecDeque;
use std::collections::{HashMap, VecDeque};

use crate::attach::Picture;
use crate::provider::{self, Config, HttpRequest, HttpResponse, Note, ToolCall, ToolImage, ToolResult, Turn};
Expand All @@ -15,8 +15,9 @@ use std::sync::{
};
static CONVERSATIONS: AtomicU64 = AtomicU64::new(1);

/// Model requests per user message before the agent stops and reports back.
pub const MAX_STEPS: u32 = 16;
/// How many times the same call, with the same arguments, may fail in one run before the run
/// pauses: a model stuck on it would otherwise spend requests on it until the user notices.
pub const SAME_FAILURES: u32 = 3;

/// What the main assistant is told about subagents, after RustGIS's own instructions.
const DELEGATE_PROMPT: &str = "\n\nSubagents: hand multi-step work whose details needn't stay in this conversation (exploring a \
Expand All @@ -35,7 +36,7 @@ then end with a short report of what you did and found (layer names, numbers, id
all the main assistant sees. Don't ask questions; where something is unclear, make a sensible choice and say which.";

/// Retries per provider request (see [`provider::retry_delay`]), reset after an accepted response.
/// This is not a whole-conversation/run allowance; [`MAX_STEPS`] separately bounds a user run.
/// This is not a whole-conversation/run allowance; [`Config::pause_after`] separately pauses a user run.
pub const MAX_RETRIES: u32 = 3;

/// What the caller does next.
Expand Down Expand Up @@ -166,8 +167,13 @@ pub struct Agent {
allowed: Vec<String>,
/// The agents on this computer the model may delegate to ([`acp`]).
harnesses: Vec<&'static acp::AgentSpec>,
/// Model requests left for this message (a subagent shares its parent's budget).
max_steps: u32,
/// A subagent's model requests: what was left of its parent's for this message, if those are
/// limited. The main assistant's limit is its settings' ([`Config::pause_after`]).
budget: Option<u32>,
/// The run paused ([`Agent::can_continue`]).
paused: bool,
/// The calls that failed in this run and haven't worked since, and how often.
failures: HashMap<(String, String), u32>,
/// Agent threads on this computer, working or waiting for a follow-up.
threads: Vec<Thread>,
threads_started: u32,
Expand Down Expand Up @@ -248,7 +254,9 @@ impl Agent {
threads_started: 0,
delegations: Vec::new(),
reports: Vec::new(),
max_steps: MAX_STEPS,
budget: None,
paused: false,
failures: HashMap::new(),
}
}

Expand Down Expand Up @@ -304,7 +312,8 @@ impl Agent {
/// When the assistant is free and threads have reported: their reports, as a message the
/// model answers (it tells the user what came of the work).
pub fn deliver(&mut self, s: &Session) -> Option<Step> {
if self.busy() || self.reports.is_empty() {
// A paused run goes on when the user says so, not when a thread reports.
if self.busy() || self.paused || self.reports.is_empty() {
return None;
}
Some(self.guard(|a| {
Expand Down Expand Up @@ -335,7 +344,7 @@ impl Agent {
}
_ => a.turns.push(Turn::User(message, Vec::new())),
}
a.steps = 0;
a.begin_run();
a.retries = 0;
a.overflow_compacted = false;
a.send()
Expand All @@ -353,7 +362,8 @@ impl Agent {
child.no_reasoning = self.no_reasoning.clone();
child.no_images = self.no_images.clone();
// The budget is the main assistant's: what's left of it for this message.
child.max_steps = self.max_steps.saturating_sub(self.steps).max(1);
// The reply that delegates is a step too, counted once its calls are answered.
child.budget = self.limit().map(|n| n.saturating_sub(self.steps.saturating_add(1)));
child.base_system = system_prompt(s) + SUBAGENT_PROMPT;
child.set_skills(self.skills.clone());
child
Expand Down Expand Up @@ -465,6 +475,42 @@ impl Agent {
Scope::assistant(self.conversation, self.live.clone())
}

/// Whether the run paused and can go on ([`Agent::resume`]).
pub fn can_continue(&self) -> bool {
// The next request answers the results waiting for the model, or their summary when the
// conversation was compacted meanwhile.
self.paused && !self.busy() && matches!(self.turns.last(), Some(Turn::Results(_) | Turn::User(..)))
}

/// Goes on with a paused run as if it hadn't paused, for as many steps again. Does nothing
/// when there is none.
pub fn resume(&mut self, s: &Session) -> Step {
if !self.can_continue() {
return Step::Done;
}
self.guard(|a| {
a.always.retain(|r| r.belongs_to_generation(s.project_generation()));
if !a.live.0.load(Ordering::SeqCst) {
a.live = Arc::new(tools::Live::default());
}
a.begin_run();
a.overflow_compacted = false;
a.send()
})
}

/// Steps and failures are counted afresh.
fn begin_run(&mut self) {
self.steps = 0;
self.paused = false;
self.failures.clear();
}

/// The steps after which this run pauses; `None` for no limit.
fn limit(&self) -> Option<u32> {
if self.depth == 0 { self.config.pause_after() } else { self.budget }
}

/// Changes in the generation tell a caller its response is stale.
pub fn generation(&self) -> u64 {
self.generation
Expand All @@ -477,7 +523,7 @@ impl Agent {
self.turns.clear();
self.transcript.clear();
self.state = State::Idle;
self.steps = 0;
self.begin_run();
self.last_context.clear();
self.always.clear();
self.pending_policy = None;
Expand Down Expand Up @@ -577,7 +623,7 @@ impl Agent {
}
_ => self.turns.push(Turn::User(message, pictures)),
}
self.steps = 0;
self.begin_run();
self.retries = 0;
self.overflow_compacted = false;
self.send()
Expand Down Expand Up @@ -979,11 +1025,21 @@ impl Agent {
let State::Calls(_, results) = std::mem::replace(&mut self.state, State::Idle) else { return Step::Done };
self.turns.push(Turn::Results(results));
self.steps += 1;
if self.steps >= self.max_steps {
self.transcript.push(Entry::Note(Note::with(
"Stopped after {steps} steps; say \"continue\" to go on.",
[("steps", self.max_steps.to_string())],
)));
if let Some(((name, args), n)) = self.failures.iter().find(|(_, n)| **n >= SAME_FAILURES) {
let note = Note::with(
"Paused: the same action failed {n} times ({action}).",
[("n", n.to_string()), ("action", tools::clip(&format!("{name} {args}"), 80))],
);
self.transcript.push(Entry::Note(note));
self.paused = true;
return Step::Done;
}
if self.limit().is_some_and(|most| self.steps >= most) {
// A subagent's steps are its parent's, which pauses in its turn and says so.
if self.depth == 0 {
self.transcript.push(Entry::Note(Note::with("Paused after {steps} steps.", [("steps", self.steps.to_string())])));
}
self.paused = true;
return Step::Done;
}
self.send()
Expand All @@ -1006,7 +1062,15 @@ impl Agent {
("The user declined this action. Don't retry it; ask what they'd like instead.".to_string(), true, Vec::new())
};
let shown = if allow { content.clone() } else { "Declined".to_string() };
let key = (call.name.clone(), call.args.to_string());
self.record(call, content, shown, error, images);
// The user declining it isn't the call failing.
if !allow && let Some(n) = self.failures.get_mut(&key) {
*n = n.saturating_sub(1);
if *n == 0 {
self.failures.remove(&key);
}
}
// A call that turned the AI Assistant off ends its reply: the calls after it aren't run.
if was_on && !s.extensions().is_on(rustgis_engine::extensions::ASSISTANT.id) {
let why = "Not run: an earlier call turned the AI Assistant off.";
Expand All @@ -1025,6 +1089,12 @@ impl Agent {

/// A call's result, for the transcript and the next request.
fn record(&mut self, call: ToolCall, content: String, shown: String, error: bool, images: Vec<ToolImage>) {
let key = (call.name.clone(), call.args.to_string());
if error {
*self.failures.entry(key).or_default() += 1;
} else {
self.failures.remove(&key);
}
self.transcript.push(Entry::Tool { name: call.name.clone(), summary: tools::summary(&call), result: shown, error });
if let State::Calls(_, results) = &mut self.state {
results.push(ToolResult { id: call.id, name: call.name, content, error, images });
Expand Down Expand Up @@ -1111,6 +1181,11 @@ impl Agent {
self.record_front(e.clone(), e, true);
return self.drain(s);
}
if self.limit().is_some_and(|n| self.steps.saturating_add(1) >= n) {
let e = "this message's steps ran out before the subagent could start".to_string();
self.record_front(e.clone(), e, true);
return self.drain(s);
}
let mut child = Box::new(self.subagent(s, allowed));
let step = child.ask(&task, s);
self.child = Some(child);
Expand Down Expand Up @@ -1172,6 +1247,13 @@ impl Agent {

/// A subagent's report: its last reply, or what stopped it.
fn report(&self) -> (String, bool) {
if self.paused {
let why = match self.failures.iter().find(|(_, n)| **n >= SAME_FAILURES) {
Some(((name, args), n)) => format!("the same call failed {n} times: {}", tools::clip(&format!("{name} {args}"), 200)),
None => "this message's steps ran out".to_string(),
};
return (format!("The subagent stopped before it finished ({why}). What it had done stays."), true);
}
match self.transcript.iter().rev().find(|e| matches!(e, Entry::Assistant(_) | Entry::Error(_))) {
Some(Entry::Assistant(text)) => (text.clone(), false),
Some(Entry::Error(e)) => (format!("The subagent stopped: {e}"), true),
Expand Down Expand Up @@ -1224,6 +1306,7 @@ impl Agent {
pub fn project_replaced(&mut self) {
self.stop();
self.state = State::Idle;
self.paused = false;
self.always.clear();
self.last_context.clear();
self.preview = None;
Expand All @@ -1238,6 +1321,8 @@ impl Agent {
pub fn stop(&mut self) {
self.live.0.store(false, Ordering::SeqCst);
self.pending_policy = None;
// A paused run is ended too: Continue doesn't come back for it.
self.paused = false;
if !self.busy() {
return;
}
Expand Down
83 changes: 79 additions & 4 deletions crates/assistant/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,55 @@ pub struct Config {
pub openrouter_private: bool,
/// Requested tool output token estimate (default 10,000); the 24,000-token hard limit still applies.
pub tool_output_token_limit: usize,
/// When a run pauses to ask whether to go on ([`Config::pause_after`]).
pub pause: Pause,
}

/// The steps (replies that call tools) after which a run pauses when each request is billed.
pub const METERED_STEPS: u32 = 50;

/// The environment variable that sets when runs pause.
pub const PAUSE_ENV: &str = "RUSTGIS_ASSISTANT_PAUSE_AFTER";

/// The most steps a pause may be set to.
pub const MAX_PAUSE: u32 = 10_000;

/// When a run pauses to ask whether to go on.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Pause {
/// After [`METERED_STEPS`] where requests are billed, never on a plan or a local model.
#[default]
ByBilling,
Never,
/// After this many steps.
After(u32),
}

impl Pause {
/// The choice as the preferences keep it, and as `RUSTGIS_ASSISTANT_PAUSE_AFTER` gives it: a
/// number of steps, `off` or `default`. Anything else is the default too.
pub fn from_pref(text: Option<&str>) -> Pause {
match text.map(str::trim) {
Some("off") => Pause::Never,
Some(n) => n.parse().ok().filter(|n| (1..=MAX_PAUSE).contains(n)).map_or(Pause::ByBilling, Pause::After),
None => Pause::ByBilling,
}
}

/// Whether `text` is a choice [`Pause::from_pref`] reads, not one it falls back from.
pub fn understood(text: &str) -> bool {
matches!(text.trim(), "off" | "default") || Pause::from_pref(Some(text)) != Pause::ByBilling
}

/// The choice in the form the preferences keep.
pub fn to_pref(self) -> String {
match self {
// Not empty: an empty preference counts as unset, so the environment's would win.
Pause::ByBilling => "default".into(),
Pause::Never => "off".into(),
Pause::After(n) => n.to_string(),
}
}
}

impl std::fmt::Debug for Config {
Expand Down Expand Up @@ -271,6 +320,22 @@ impl Config {
.and_then(|s| s.parse().ok())
.filter(|n| *n > 0)
.unwrap_or(crate::tools::DEFAULT_OUTPUT_TOKENS),
pause: Pause::from_pref(env(PAUSE_ENV).as_deref()),
}
}

/// Whether each request is billed: not those on a ChatGPT plan, nor to a server on this
/// computer or its network.
pub fn metered(&self) -> bool {
!self.login() && !local_url(&self.base_url)
Comment thread
Mavrick-F marked this conversation as resolved.
Resolved
}

/// The steps after which a run pauses to ask whether to go on; `None` for never.
pub fn pause_after(&self) -> Option<u32> {
match self.pause {
Pause::ByBilling => self.metered().then_some(METERED_STEPS),
Pause::Never => None,
Pause::After(n) => Some(n.max(1)),
}
}

Expand Down Expand Up @@ -589,9 +654,18 @@ pub fn allowed_url(url: &str) -> bool {
if authority.is_empty() || authority.contains('@') {
return false;
}
if https {
return true;
}
https || local_authority(authority)
}

/// Whether `url` is a server on this computer or the local network.
fn local_url(url: &str) -> bool {
let url = url.trim();
let rest = url.strip_prefix("https://").or_else(|| url.strip_prefix("http://"));
rest.and_then(|r| r.split(['/', '?', '#']).next()).is_some_and(|a| !a.contains('@') && local_authority(a))
}

/// Whether an address's host (and port) is this computer or the local network.
fn local_authority(authority: &str) -> bool {
let host = if let Some(v6) = authority.strip_prefix('[') {
v6.split(']').next().unwrap_or("")
} else {
Expand Down Expand Up @@ -771,7 +845,8 @@ pub const NOTE_TEMPLATES: &[&str] = &[
"Pictures you attached don't go to {agent}: it gets the task's text only.",
"{name}: the picture can't be encoded ({why})",
"{name}: the picture is too heavy to send, even drawn small",
"Stopped after {steps} steps; say \"continue\" to go on.",
"Paused after {steps} steps.",
"Paused: the same action failed {n} times ({action}).",
"Stopped.",
];

Expand Down
Loading
Loading