Skip to content
Merged
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
10 changes: 9 additions & 1 deletion crates/agent/examples/probe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,13 +251,21 @@ fn main() {
provider,
binary,
Default::default(),
Default::default(),
agent::CatalogRefresh {
account_usage: true,
..Default::default()
},
&Default::default(),
)
.await
{
Ok(listing) => {
println!("{}", serde_json::to_string_pretty(&listing.models).unwrap());
match listing.account_usage {
Some(Ok(usage)) => eprintln!("account usage: {usage}"),
Some(Err(error)) => eprintln!("account usage failed: {error}"),
None => {}
}
for problem in listing.problems {
eprintln!("{problem}");
}
Expand Down
86 changes: 64 additions & 22 deletions crates/agent/src/acp_session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2241,7 +2241,13 @@ async fn emit_provider_options(
events: &Sender<AgentEvent>,
emit_empty: bool,
) {
let event = state.lock_recover().provider_options();
let (event, models) = {
let mut state = state.lock_recover();
(state.provider_options(), state.changed_models())
};
if let Some(models) = models {
let _ = events.send(AgentEvent::ProviderModels { models }).await;
}
if matches!(
&event,
AgentEvent::ProviderOptions { descriptors, .. } if descriptors.is_empty()
Expand Down Expand Up @@ -2528,6 +2534,32 @@ impl OptionRegistry {
.find(|record| record.selection.id == MODEL_OPTION_ID)
.and_then(|record| record.selection.value.as_str().map(str::to_string))
}

/// The choices of the agent's model option, the one it is set to marked
/// as the default.
fn models(&self) -> Vec<crate::ModelSpec> {
self.records
.iter()
.find_map(|record| match &record.descriptor {
OptionDescriptor::Select {
options,
default_value,
..
} if record.selection.id == MODEL_OPTION_ID => Some(
options
.iter()
.map(|option| crate::ModelSpec {
is_default: default_value.as_deref() == Some(option.value.as_str()),
id: option.value.clone(),
display_name: option.label.clone(),
options: Vec::new(),
})
.collect(),
),
_ => None,
})
.unwrap_or_default()
}
}

/// What `session/new` offered an ACP agent's sessions on `provider`: the
Expand All @@ -2539,28 +2571,17 @@ pub(crate) fn catalog(
) -> crate::AcpCatalog {
let mut registry = OptionRegistry::new(provider);
registry.ingest(modes, config_options);
let mut catalog = crate::AcpCatalog::default();
for record in registry.records {
match record.descriptor {
OptionDescriptor::Select {
options,
default_value,
..
} if record.selection.id == MODEL_OPTION_ID => {
catalog.models = options
.into_iter()
.map(|option| crate::ModelSpec {
is_default: default_value.as_deref() == Some(option.value.as_str()),
id: option.value,
display_name: option.label,
options: Vec::new(),
})
.collect();
}
descriptor => catalog.options.push(descriptor),
}
crate::AcpCatalog {
models: registry.models(),
options: registry
.records
.into_iter()
.map(|record| record.descriptor)
.filter(|descriptor| {
!matches!(descriptor, OptionDescriptor::Select { id, .. } if id == MODEL_OPTION_ID)
})
.collect(),
}
catalog
}

fn descriptor_id(descriptor: &OptionDescriptor) -> &str {
Expand Down Expand Up @@ -2630,6 +2651,8 @@ pub(crate) struct State {
terminals: HashMap<String, Arc<Terminal>>,
usage: Option<TokenUsage>,
options: OptionRegistry,
/// The models last sent as [`AgentEvent::ProviderModels`].
reported_models: Vec<crate::ModelSpec>,
/// [`Dialect::owned_config_options`].
owned_options: &'static [&'static str],
/// A turn the agent started while another was still open.
Expand Down Expand Up @@ -2664,6 +2687,7 @@ impl State {
terminals: HashMap::new(),
usage: None,
options: OptionRegistry::new(provider),
reported_models: Vec::new(),
owned_options: &[],
next_turn: None,
modes: None,
Expand Down Expand Up @@ -2854,6 +2878,21 @@ impl State {
self.options.select(id, Value::String(mode.0.to_string()));
}

/// The agent's models when they are not the ones last reported. Only an
/// agent from the registry lists its models in its model option alone;
/// the native ACP harnesses each have a catalog of their own.
fn changed_models(&mut self) -> Option<Vec<crate::ModelSpec>> {
if self.options.provider != ProviderKind::Acp {
return None;
}
let models = self.options.models();
if models == self.reported_models {
return None;
}
self.reported_models.clone_from(&models);
Some(models)
}

fn provider_options(&self) -> AgentEvent {
let surfaced = || {
self.options.records.iter().filter(|record| {
Expand Down Expand Up @@ -3076,6 +3115,9 @@ impl State {
let previous_model = self.options.current_model();
self.options.ingest(None, Some(&update.config_options));
let mut events = vec![self.provider_options()];
if let Some(models) = self.changed_models() {
events.push(AgentEvent::ProviderModels { models });
}
if let Some(model) = self.options.current_model()
&& Some(model.as_str()) != previous_model.as_deref()
{
Expand Down
44 changes: 44 additions & 0 deletions crates/agent/src/acp_session/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -692,6 +692,50 @@ fn modes_and_categorized_config_become_provider_options() {
}
}

/// A registry agent may answer `session/new` before it knows its models and
/// push them in a `config_option_update` (ACP schema: `SessionConfigOption`
/// of category `model`). The session reports them when they arrive, and not
/// again while they stay the same.
#[test]
fn an_agents_models_are_reported_when_its_model_option_brings_them() {
let mut state = State::new(ProviderKind::Acp, PathBuf::from("/workspace"));
let pushed = || {
update(json!({
"sessionUpdate": "config_option_update",
"configOptions": [{
"id": "model",
"name": "Model",
"category": "model",
"type": "select",
"currentValue": "sonnet",
"options": [
{ "value": "sonnet", "name": "Sonnet" },
{ "value": "opus", "name": "Opus" }
]
}]
}))
};
let reported = |events: Vec<AgentEvent>| {
events.into_iter().find_map(|event| match event {
AgentEvent::ProviderModels { models } => Some(
models
.into_iter()
.map(|model| (model.id, model.display_name, model.is_default))
.collect::<Vec<_>>(),
),
_ => None,
})
};
assert_eq!(
reported(state.apply_update(pushed())),
Some(vec![
("sonnet".into(), "Sonnet".into(), true),
("opus".into(), "Opus".into(), false),
])
);
assert_eq!(reported(state.apply_update(pushed())), None);
}

/// An ACP agent's mode, from `modes` or a config option of category `mode`,
/// says what runs without asking, so the composer's permission control
/// carries it. Cursor and Grok have a permission control of their own,
Expand Down
1 change: 1 addition & 0 deletions crates/agent/src/claude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3254,6 +3254,7 @@ pub async fn list_models(
Ok(crate::ModelListing {
models: crate::claude_manifest::current().models_for_version(version),
problems: crate::claude_manifest::problems(),
account_usage: None,
})
}

Expand Down
88 changes: 61 additions & 27 deletions crates/agent/src/codex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,19 +235,32 @@ pub async fn start(opts: SessionOptions) -> Result<SessionHandle, AgentError> {
}

/// Spawn `codex app-server`, page through `model/list` (initial `{}`, then
/// `{cursor}` until `nextCursor` is empty), and tear the process down.
/// `{cursor}` until `nextCursor` is empty), read the account's rate limits
/// when `read_usage`, and tear the process down. Every `codex app-server`
/// fetches Codex's model catalog over the network as it starts (0.174.0),
/// whatever it is then asked, so the one started for the models answers for
/// the usage too.
pub async fn list_models(
binary_path: Option<PathBuf>,
launch_env: LaunchEnv,
read_usage: bool,
processes: &crate::SessionProcesses,
) -> Result<Vec<ModelSpec>, AgentError> {
) -> Result<(Vec<ModelSpec>, Option<Result<Value, AgentError>>), AgentError> {
let (child, mut stdin, lines, mut stderr_tail) =
spawn_server(binary_path.as_deref(), &[], &launch_env)?;
let child = processes.hold(child);
let windows = home_dir(&launch_env)
.map(|home| model_windows::read(&home))
.unwrap_or_default();
let result = collect_models(&mut stdin, &lines, &windows).await;
let result = async {
initialize(&mut stdin, &lines).await?;
let mut next_id = 2;
let entries =
list_models_raw(&mut stdin, &lines, &mut next_id, false, &mut Vec::new()).await?;
let usage = match read_usage {
true => Some(request_rate_limits(&mut stdin, &lines, next_id).await),
false => None,
};
Ok((map_models(&entries, &launch_env), usage))
}
.await;
finish_one_shot(child, stdin, &mut stderr_tail, result).await
}

Expand All @@ -261,16 +274,24 @@ pub async fn read_rate_limits(
spawn_server(binary_path.as_deref(), &[], &launch_env)?;
let result = async {
initialize(&mut stdin, &lines).await?;
send_json(
&mut stdin,
&json!({ "id": 2, "method": "account/rateLimits/read", "params": {} }),
)?;
wait_for_response(&lines, 2).await
request_rate_limits(&mut stdin, &lines, 2).await
}
.await;
finish_one_shot(child, stdin, &mut stderr_tail, result).await
}

async fn request_rate_limits(
stdin: &mut BufWriter<ChildStdin>,
lines: &Receiver<ChildOutput>,
id: i64,
) -> Result<Value, AgentError> {
send_json(
stdin,
&json!({ "id": id, "method": "account/rateLimits/read", "params": {} }),
)?;
wait_for_response(lines, id).await
}

/// Stop a server started for one request, and fold its death into the
/// request's error.
async fn finish_one_shot<T>(
Expand Down Expand Up @@ -336,20 +357,19 @@ pub fn home_dir(launch_env: &LaunchEnv) -> Option<PathBuf> {
})
}

async fn collect_models(
stdin: &mut BufWriter<ChildStdin>,
lines: &Receiver<ChildOutput>,
windows: &HashMap<String, model_windows::ModelWindows>,
) -> Result<Vec<ModelSpec>, AgentError> {
initialize(stdin, lines).await?;
let entries = list_models_raw(stdin, lines, &mut 2, false, &mut Vec::new()).await?;
Ok(entries
/// The `model/list` entries the picker shows, each with the context windows
/// Codex caches under the home `launch_env` gives it.
fn map_models(entries: &[Value], launch_env: &LaunchEnv) -> Vec<ModelSpec> {
let windows = home_dir(launch_env)
.map(|home| model_windows::read(&home))
.unwrap_or_default();
entries
.iter()
.filter_map(|model| {
let slug = model.get("model").and_then(Value::as_str);
map_model(model, slug.and_then(|slug| windows.get(slug)))
})
.collect())
.collect()
}

/// Every `model/list` entry, page after page (initial `{}`, then `{cursor}`
Expand Down Expand Up @@ -911,6 +931,7 @@ async fn run_actor(
config_effort,
service_tier: reported_tier,
model_efforts,
models,
next_id,
provider_commands,
permission_descriptor,
Expand Down Expand Up @@ -1007,6 +1028,12 @@ async fn run_actor(
commands: provider_commands,
})
.await;
if let Some(models) = models {
actor
.events
.emit(AgentEvent::ProviderModels { models })
.await;
}
for message in warnings {
actor.events.emit(AgentEvent::Warning { message }).await;
}
Expand Down Expand Up @@ -1594,6 +1621,8 @@ struct OpenedThread {
/// `serviceTier` as the answer gave it: the tier in effect, `None` for none.
service_tier: Option<String>,
model_efforts: ModelEfforts,
/// The models `model/list` offers the picker; `None` when it failed.
models: Option<Vec<ModelSpec>>,
next_id: i64,
provider_commands: Vec<ProviderCommand>,
permission_descriptor: OptionDescriptor,
Expand Down Expand Up @@ -1692,13 +1721,17 @@ async fn initialize_and_open_thread(
Vec::new()
});
next_id += 1;
let model_efforts = list_models_raw(stdin, lines, &mut next_id, true, &mut said)
.await
.map(|entries| ModelEfforts::from_list(&entries))
.unwrap_or_else(|err| {
warnings.push(format!("Codex model/list failed: {err}"));
ModelEfforts::default()
});
let (model_efforts, models) =
match list_models_raw(stdin, lines, &mut next_id, true, &mut said).await {
Ok(entries) => (
ModelEfforts::from_list(&entries),
Some(map_models(&entries, &opts.launch_env)),
),
Err(err) => {
warnings.push(format!("Codex model/list failed: {err}"));
(ModelEfforts::default(), None)
}
};
// Without a chosen model Codex ran the configured one or its default; a
// chosen one hides which, and the list's default stands in.
let default_model = match &opts.model {
Expand All @@ -1716,6 +1749,7 @@ async fn initialize_and_open_thread(
config_effort,
service_tier,
model_efforts,
models,
next_id,
provider_commands,
permission_descriptor,
Expand Down
1 change: 1 addition & 0 deletions crates/agent/src/codex/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1647,6 +1647,7 @@ fn startup_failure_reports_exit_status_and_stderr_tail() {
env: vec![("LC_ALL".into(), "C".into())],
home: None,
},
false,
&Default::default(),
))
.unwrap_err()
Expand Down
Loading
Loading