mirror of
https://github.com/block/buzz.git
synced 2026-11-16 06:11:34 +00:00
## Summary Genericizes the agent effort write-side so Goose participates in the same canonical effort contract as buzz-agent. A spawn bridge translates the canonical key to whatever the target harness expects at launch time. Read/write/spawn paths all derive their vocabulary from runtime metadata rather than a hardcoded buzz-agent list. ## What changed ### Rust — config bridge + spawn path - `apply_spawn_effort_env` in `effort.rs`: production command-boundary seam — writes baked env, runs the effort projection, strips per-runtime suppress set, and emits exactly one projected key. - `apply_effort_to_spawn_command` in `runtime.rs`: thin wrapper returning a `#[must_use] EffortApplied(())` token (private field — unforgeable outside the function). `spawn_agent_child` calls it as `let effort = apply_effort_to_spawn_command(...)` and passes `effort` to `spawn_with_effort_proof`. Deleting the call is a compile error: `effort` is undefined at the `spawn_with_effort_proof` site. Deleting `apply_spawn_effort_env` inside the wrapper turns the production-sequence tests RED. - `apply_record_field_updates` in `agent_models_update.rs`: returns `Result<RecordFieldsApplied, String>` (`#[must_use]` token). `update_managed_agent` calls it as `let applied = apply_record_field_updates(...)?` then passes `applied` to `stamp_record_updated_at`. Deleting the call is a compile error: `applied` is undefined at the `stamp_record_updated_at` site. - Unknown/custom-runtime passthrough: `apply_effort_launch_to_command` skips the suppress loop when `preserve_passthrough && value.is_none()`, preserving ambient ACP sentinels. - `EnvVarGuard`: prior value stored as `OsString` (`var_os`) so non-Unicode values are restored exactly on Drop. A single `PROCESS_ENV_MUTEX` in `managed_agents/mod.rs` is shared by `lock_path_mutex()` and `lock_env_mutex()` — any two tests calling either helper are mutually exclusive with each other. Tests in other modules (`app_state_tests`, `agent_config_tests`, `reader_tests`) maintain their own independent locks and are not in this domain. - Dead-code: `strip_effort_keys_from_command` marked `#[cfg(test)]`; import path in `effort_cmd_tests.rs` fixed. - Windows CI fix: platform-gated variants for inherited-env tests. ### TypeScript — renderer + model cleanup - `AgentConfigFields` orphan-model cleanup effect: the `isHarnessNativeEffort` early-return was skipping the model clear on provider→Custom transitions. Refined to: return early only when model is already null; clear model once while preserving the harness-native effort key (Carl P2). - Provider-empty convergence: when model is null and effort is native, the cleanup effect returns early (nothing to clear) — prevents spurious `onConfigChange` loop. - `EffortSelectField` / `humanizeEffortLabel`: runtime-native option labels title-cased (`off` → `Off`) with raw canonical values preserved for round-trip fidelity. - `AgentConfigFields`: drives effort renderer from `selectedRuntime.effortCanonicalValues` (harness-native path) or the model/provider catalog (buzz-agent/provider path), selected by `isHarnessNativeEffort`. ### Docs - `desktop/src/features/agents/AGENTS.md` item 14: updated from deleted `persistAgentEffortLevel` direct-write contract to the shipped Save-gated `update_managed_agent.effortLevel` path. Consistent with `EffortPickerField`'s own doc comment. ### Tests - `agent_models_update_tests.rs`: seam tests via `apply_record_field_updates` — non-local rejects, local set/clear, ordering invariant, ACP-sentinel sweep. `record_field_updates_persist_effort_to_disk` (renamed from the prior false-claim name) drives load→apply→stamp→save→load via a mock AppHandle + tempdir, asserting `effort_level` persists to disk. Manual HOME/XDG restore replaced with RAII `EnvVarGuard` (panic-safe, `OsString`-exact). - `effort_cmd_tests.rs` / `effort_tests.rs`: production-sequence seam tests via `apply_effort_to_spawn_command`. Spawns `/usr/bin/env` to verify child's real env. `EnvVarGuard` for panic-safe restore. Windows twin using `cmd /c set`. - `effortAutoClear.test.mjs`: five mounted stateful journeys via `AgentConfigFields` with `useCustomSelect=true`. Covers: custom trigger shows "Off" at mount; provider-empty mount is a stable fixed point; provider→Custom switch converges; stale Anthropic model cleared on Custom switch with Goose effort preserved (Carl P2 regression); Settings-style Save/reread preserves effort. - `agentDefaultsEditor.test.mjs`: two full Save/Next journey tests through the real production parent trees. Both start with `GOOSE_THINKING_EFFORT: "low"` and operate the real Popover-based effort control (click trigger → click "off" option) before Save/Next, asserting zero writes after selection. The `set_global_agent_config` stub captures the submitted payload; each test asserts raw `GOOSE_THINKING_EFFORT: "off"` in the captured config. The stub stores its canonical response from the actual payload; the fresh remount's `get_global_agent_config` returns that stored object (not a hand-written fixture), then asserts "Off" shown. The `DefaultConfigStep` test starts with `isDirty: false` — the real-control effort selection calls `onConfigChange → updateDraft → isDirtyRef=true`, making the `commit()` on Next load-bearing. ## Mutation evidence - Delete `let effort = apply_effort_to_spawn_command(...)` call from `spawn_agent_child` → compile error: `error[E0425]: cannot find value `effort`` at `spawn_with_effort_proof` site. - Delete `let applied = apply_record_field_updates(...)?` from `update_managed_agent` → compile error: `error[E0425]: cannot find value `applied`` at `stamp_record_updated_at` site. - Delete `apply_spawn_effort_env` from inside `apply_effort_to_spawn_command` wrapper → `production_sequence_goose_inherited_collision_resolved_in_child` RED. - Revert `isHarnessNativeEffort &&` guard in cleanup `useEffect` to bare `if (isHarnessNativeEffort) return` → stale model not cleared → Carl P2 regression test RED. - Remove `isHarnessNativeEffort ||` from the nothing-to-clear condition → provider-empty mount emits `onConfigChange` → loop test RED. - Remove `isHarnessNativeEffort` branch in `AgentConfigFields.tsx:634-636` → both `agentDefaultsEditor.test.mjs` mount assertions fail: trigger shows "Select" instead of initial effort label. - Remove `preserve_passthrough` guard in `apply_effort_launch_to_command` → `production_sequence_custom_inherited_acp_sentinel_survives` RED. - Drop `GOOSE_THINKING_EFFORT` from the `set_global_agent_config` stub payload → payload assertion in `agentDefaultsEditor.test.mjs` fails (`undefined !== "off"`) → RED (verified). - Remove the effort-select dirtying steps from the `DefaultConfigStep` test (so `isDirty` stays false) → `commit()` is a no-op → write-count assertion after Next fails (0 instead of 1) → RED. --------- Signed-off-by: Will Pfleger <pfleger.will@gmail.com> Signed-off-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Signed-off-by: Hayt <9e1c23a3fd83f61da34420e4e88ff1b16e45cafcc0cd9019eb07d4ecfa8ca9b0@buzz.block.builderlab.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Co-authored-by: Hayt <9e1c23a3fd83f61da34420e4e88ff1b16e45cafcc0cd9019eb07d4ecfa8ca9b0@buzz.block.builderlab.xyz>
789 lines
26 KiB
Rust
789 lines
26 KiB
Rust
use std::collections::{BTreeMap, HashSet};
|
|
|
|
use nostr::Keys;
|
|
use serde::Deserialize;
|
|
use tauri::{AppHandle, State};
|
|
|
|
use super::agent_model_process::run_agent_models_command;
|
|
use super::managed_agent_definition::apply_model_provider_prompt_update;
|
|
// The map-only lookup is reached solely from the base-URL helpers that exist for
|
|
// their unit tests; discovery itself always goes through the process-env variant.
|
|
use super::agent_models_env::{
|
|
effective_discovery_provider, env_or_process_value, redaction_env_with_value, DiscoveryProvider,
|
|
};
|
|
#[cfg(test)]
|
|
use super::agent_models_env::{env_value, env_value_or_process_if_absent};
|
|
use super::agent_update_rollback::{rollback_failed_agent_update, AgentUpdateRollback};
|
|
|
|
use crate::{
|
|
app_state::AppState,
|
|
managed_agents::{
|
|
current_instance_id, discovery_env_with_baked_floor, find_managed_agent_mut,
|
|
known_acp_runtime, load_global_agent_config, load_managed_agents, load_personas,
|
|
managed_agent_avatar_url, missing_command_message, normalize_agent_args, resolve_command,
|
|
save_managed_agents, sync_managed_agent_processes, try_regenerate_nest, AgentModelInfo,
|
|
AgentModelsResponse, ManagedAgentRecord, UpdateManagedAgentRequest,
|
|
UpdateManagedAgentResponse, DEFAULT_ACP_COMMAND,
|
|
},
|
|
relay::{relay_ws_url_with_override, sync_managed_agent_profile},
|
|
};
|
|
|
|
/// Query available models from an agent via `buzz-acp models --json`.
|
|
///
|
|
/// Spawns a short-lived subprocess (no relay connection needed). The subprocess
|
|
/// starts the agent, queries its model catalog, and exits. ~2-5s total.
|
|
#[tauri::command]
|
|
pub async fn get_agent_models(
|
|
pubkey: String,
|
|
app: AppHandle,
|
|
state: State<'_, AppState>,
|
|
) -> Result<AgentModelsResponse, String> {
|
|
let (resolved_acp, agent_command, discovery) = {
|
|
let _store_guard = state
|
|
.managed_agents_store_lock
|
|
.lock()
|
|
.map_err(|e| e.to_string())?;
|
|
let mut records = load_managed_agents(&app)?;
|
|
let mut runtimes = state
|
|
.managed_agent_processes
|
|
.lock()
|
|
.map_err(|e| e.to_string())?;
|
|
let (sync_changed, exited_pubkeys) =
|
|
sync_managed_agent_processes(&mut records, &mut runtimes, ¤t_instance_id(&app));
|
|
if sync_changed {
|
|
save_managed_agents(&app, &records)?;
|
|
}
|
|
for pubkey in &exited_pubkeys {
|
|
state.clear_agent_session_caches(pubkey);
|
|
}
|
|
|
|
let record = records
|
|
.iter()
|
|
.find(|r| r.pubkey == pubkey)
|
|
.ok_or_else(|| format!("agent {pubkey} not found"))?;
|
|
|
|
let resolved = resolve_command(&record.acp_command)
|
|
.ok_or_else(|| missing_command_message(&record.acp_command, "ACP harness command"))?;
|
|
|
|
// Resolve the effective harness from the linked persona (mirrors spawn),
|
|
// so model discovery runs against the persona's current harness, not the
|
|
// frozen record snapshot. An explicit per-agent override wins.
|
|
let personas = load_personas(&app).unwrap_or_default();
|
|
let global = load_global_agent_config(&app).unwrap_or_default();
|
|
|
|
// Single pure helper — descriptor + authoritative model/provider
|
|
// resolver, packaged so the linked-agent regression test binds the
|
|
// exact values this command consumes. Returns Err on dangling harness
|
|
// id, propagating it to the caller.
|
|
let discovery = agent_model_discovery_config(record, &personas, &global)
|
|
.map_err(|e| model_discovery_error(&pubkey, &e))?;
|
|
|
|
let resolved_agent = resolve_command(&discovery.command)
|
|
.map(|p| p.display().to_string())
|
|
.unwrap_or_else(|| discovery.command.clone());
|
|
|
|
(resolved, resolved_agent, discovery)
|
|
}; // store lock released — subprocess runs without holding the lock
|
|
|
|
let AgentModelDiscoveryConfig {
|
|
args: agent_args,
|
|
model: persisted_model,
|
|
provider: saved_provider,
|
|
provider_env_var,
|
|
env: merged_env,
|
|
command: _,
|
|
} = discovery;
|
|
|
|
let merged_env = discovery_env_with_baked_floor(merged_env);
|
|
// Resolve against the baked/process env when the record saved no provider,
|
|
// so a build-provided provider still gets live discovery.
|
|
let effective_provider =
|
|
effective_discovery_provider(saved_provider.as_deref(), provider_env_var, &merged_env);
|
|
if let Some(models) = discover_openrouter_models(
|
|
&state.http_client,
|
|
&effective_provider,
|
|
&merged_env,
|
|
persisted_model.clone(),
|
|
)
|
|
.await?
|
|
{
|
|
return Ok(models);
|
|
}
|
|
|
|
if let Some(models) = discover_openai_compatible_models(
|
|
&state.http_client,
|
|
&effective_provider,
|
|
&merged_env,
|
|
persisted_model.clone(),
|
|
)
|
|
.await?
|
|
{
|
|
return Ok(models);
|
|
}
|
|
|
|
if let Some(models) = discover_anthropic_models(
|
|
&state.http_client,
|
|
&effective_provider,
|
|
&merged_env,
|
|
persisted_model.clone(),
|
|
)
|
|
.await?
|
|
{
|
|
return Ok(models);
|
|
}
|
|
|
|
if let Some(models) = discover_databricks_models(
|
|
&state.http_client,
|
|
&effective_provider,
|
|
&merged_env,
|
|
persisted_model.clone(),
|
|
DatabricksAuthIntent::InteractiveModelPicker,
|
|
)
|
|
.await?
|
|
{
|
|
return Ok(models);
|
|
}
|
|
|
|
run_agent_models_command(
|
|
resolved_acp,
|
|
agent_command,
|
|
agent_args,
|
|
persisted_model,
|
|
merged_env,
|
|
)
|
|
.await
|
|
}
|
|
|
|
/// Error copy for a failed harness resolution during model discovery.
|
|
///
|
|
/// Routes through `user_facing_harness_error` so a dangling harness id renders
|
|
/// as a sentence, never as the raw `DANGLING_HARNESS_ID:` sentinel — the same
|
|
/// contract spawn and summary rows honor.
|
|
fn model_discovery_error(pubkey: &str, error: &str) -> String {
|
|
format!(
|
|
"cannot discover models for {pubkey}: {}",
|
|
crate::managed_agents::user_facing_harness_error(error)
|
|
)
|
|
}
|
|
|
|
#[path = "agent_models_discovery_config.rs"]
|
|
mod discovery_config;
|
|
use discovery_config::{
|
|
agent_model_discovery_config, draft_agent_model_discovery_env, AgentModelDiscoveryConfig,
|
|
};
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct DiscoverAgentModelsInput {
|
|
#[serde(default)]
|
|
pub acp_command: Option<String>,
|
|
pub agent_command: String,
|
|
#[serde(default)]
|
|
pub agent_args: Vec<String>,
|
|
#[serde(default)]
|
|
pub provider: Option<String>,
|
|
#[serde(default)]
|
|
pub env_vars: BTreeMap<String, String>,
|
|
/// Definition-level env from the harness definition (custom/preset).
|
|
/// Merged below user `env_vars` so user overrides always win.
|
|
#[serde(default)]
|
|
pub definition_env: BTreeMap<String, String>,
|
|
}
|
|
|
|
/// Query available models from an unsaved agent configuration.
|
|
///
|
|
/// This powers the new-agent dialog before a persona/agent record exists. It
|
|
/// mirrors the saved-agent discovery command, but derives runtime/provider/env
|
|
/// from the current form state instead of loading a persisted record.
|
|
#[tauri::command]
|
|
pub async fn discover_agent_models(
|
|
input: DiscoverAgentModelsInput,
|
|
state: State<'_, AppState>,
|
|
) -> Result<AgentModelsResponse, String> {
|
|
crate::managed_agents::validate_user_env_keys(&input.env_vars)?;
|
|
// Also validate definition_env (caller-supplied, same trust level as env_vars).
|
|
crate::managed_agents::validate_user_env_keys(&input.definition_env)?;
|
|
|
|
let acp_command = input
|
|
.acp_command
|
|
.as_deref()
|
|
.map(str::trim)
|
|
.filter(|value| !value.is_empty())
|
|
.unwrap_or(DEFAULT_ACP_COMMAND);
|
|
let resolved_acp = resolve_command(acp_command)
|
|
.ok_or_else(|| missing_command_message(acp_command, "ACP harness command"))?;
|
|
|
|
let agent_command = input.agent_command.trim();
|
|
if agent_command.is_empty() {
|
|
return Err("agent command is required for model discovery".to_string());
|
|
}
|
|
let agent_args = normalize_agent_args(agent_command, input.agent_args);
|
|
let resolved_agent = resolve_command(agent_command)
|
|
.map(|p| p.display().to_string())
|
|
.unwrap_or_else(|| agent_command.to_string());
|
|
|
|
let runtime_meta = known_acp_runtime(agent_command);
|
|
let merged_env = draft_agent_model_discovery_env(
|
|
agent_command,
|
|
input.provider.as_deref(),
|
|
&input.definition_env,
|
|
&input.env_vars,
|
|
);
|
|
let merged_env = discovery_env_with_baked_floor(merged_env);
|
|
// Recover a build-provided provider when the form has none, so the create
|
|
// dialog discovers live models instead of falling through to the subprocess.
|
|
let effective_provider = effective_discovery_provider(
|
|
input.provider.as_deref(),
|
|
runtime_meta.and_then(|meta| meta.provider_env_var),
|
|
&merged_env,
|
|
);
|
|
|
|
// Buzz shared compute discovery must not depend on the local OpenAI ingress: that
|
|
// client endpoint is started only after a live target is selected.
|
|
#[cfg(feature = "mesh-llm")]
|
|
if input.provider.as_deref().map(str::trim)
|
|
== Some(crate::managed_agents::RELAY_MESH_PROVIDER_ID)
|
|
{
|
|
let events = crate::relay::query_relay(
|
|
&state,
|
|
&[
|
|
crate::mesh_llm::mesh_status_filter(),
|
|
crate::mesh_llm::relay_membership_filter(),
|
|
],
|
|
)
|
|
.await
|
|
.map_err(|error| format!("Buzz shared compute model discovery failed: {error}"))?;
|
|
let availability = crate::mesh_llm::availability_from_events(events);
|
|
if availability.models.is_empty() {
|
|
return Err(availability.reason.unwrap_or_else(|| {
|
|
"No live Buzz shared compute models are available".to_string()
|
|
}));
|
|
}
|
|
return Ok(AgentModelsResponse {
|
|
agent_name: crate::managed_agents::RELAY_MESH_PROVIDER_ID.to_string(),
|
|
agent_version: "relay-availability".to_string(),
|
|
models: availability
|
|
.models
|
|
.into_iter()
|
|
.map(|model| AgentModelInfo {
|
|
id: model.id,
|
|
name: model.name,
|
|
description: None,
|
|
})
|
|
.collect(),
|
|
agent_default_model: None,
|
|
selected_model: None,
|
|
supports_switching: true,
|
|
});
|
|
}
|
|
#[cfg(not(feature = "mesh-llm"))]
|
|
if input.provider.as_deref().map(str::trim)
|
|
== Some(crate::managed_agents::RELAY_MESH_PROVIDER_ID)
|
|
{
|
|
return Err("Buzz shared compute is not available in this build".to_string());
|
|
}
|
|
|
|
if let Some(models) =
|
|
discover_openrouter_models(&state.http_client, &effective_provider, &merged_env, None)
|
|
.await?
|
|
{
|
|
return Ok(models);
|
|
}
|
|
|
|
if let Some(models) = discover_openai_compatible_models(
|
|
&state.http_client,
|
|
&effective_provider,
|
|
&merged_env,
|
|
None,
|
|
)
|
|
.await?
|
|
{
|
|
return Ok(models);
|
|
}
|
|
|
|
if let Some(models) =
|
|
discover_anthropic_models(&state.http_client, &effective_provider, &merged_env, None)
|
|
.await?
|
|
{
|
|
return Ok(models);
|
|
}
|
|
|
|
if let Some(models) = discover_databricks_models(
|
|
&state.http_client,
|
|
&effective_provider,
|
|
&merged_env,
|
|
None,
|
|
DatabricksAuthIntent::PassiveDraftDiscovery,
|
|
)
|
|
.await?
|
|
{
|
|
return Ok(models);
|
|
}
|
|
|
|
run_agent_models_command(resolved_acp, resolved_agent, agent_args, None, merged_env).await
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
struct OpenAiModelListResponse {
|
|
data: Vec<OpenAiModelListItem>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
struct OpenAiModelListItem {
|
|
id: String,
|
|
#[serde(default)]
|
|
created: Option<i64>,
|
|
}
|
|
|
|
#[path = "agent_models_openrouter.rs"]
|
|
mod openrouter;
|
|
use openrouter::discover_openrouter_models;
|
|
#[cfg(test)]
|
|
use openrouter::{
|
|
filter_openrouter_models, is_openrouter_provider, openrouter_models_url,
|
|
OpenRouterModelListItem, OpenRouterModelListResponse,
|
|
};
|
|
|
|
fn is_openai_compatible_provider(provider: Option<&str>) -> bool {
|
|
matches!(
|
|
provider
|
|
.map(str::trim)
|
|
.map(str::to_ascii_lowercase)
|
|
.as_deref(),
|
|
Some("openai" | "openai-compat")
|
|
)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
fn openai_compatible_models_url(env: &BTreeMap<String, String>) -> String {
|
|
let base_url = env_value(env, "OPENAI_COMPAT_BASE_URL")
|
|
.unwrap_or_else(|| "https://api.openai.com/v1".to_string());
|
|
format!("{}/models", base_url.trim_end_matches('/'))
|
|
}
|
|
|
|
fn openai_compatible_models_url_for_discovery(env: &BTreeMap<String, String>) -> String {
|
|
let base_url = env_or_process_value(env, "OPENAI_COMPAT_BASE_URL")
|
|
.unwrap_or_else(|| "https://api.openai.com/v1".to_string());
|
|
format!("{}/models", base_url.trim_end_matches('/'))
|
|
}
|
|
|
|
fn is_agent_text_model_id(id: &str) -> bool {
|
|
let lower = id.to_ascii_lowercase();
|
|
if [
|
|
"audio",
|
|
"dall-e",
|
|
"embedding",
|
|
"image",
|
|
"moderation",
|
|
"realtime",
|
|
"speech",
|
|
"transcribe",
|
|
"tts",
|
|
"whisper",
|
|
]
|
|
.iter()
|
|
.any(|needle| lower.contains(needle))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
lower.starts_with("gpt-") || lower.starts_with('o') || lower.starts_with("chatgpt-")
|
|
}
|
|
|
|
fn openai_dated_snapshot_alias(id: &str) -> Option<String> {
|
|
let (base, date) = id.rsplit_once('-')?;
|
|
if date.len() != 2 || !date.chars().all(|character| character.is_ascii_digit()) {
|
|
return None;
|
|
}
|
|
let (base, month) = base.rsplit_once('-')?;
|
|
if month.len() != 2 || !month.chars().all(|character| character.is_ascii_digit()) {
|
|
return None;
|
|
}
|
|
let (base, year) = base.rsplit_once('-')?;
|
|
if year.len() != 4 || !year.chars().all(|character| character.is_ascii_digit()) {
|
|
return None;
|
|
}
|
|
|
|
Some(base.to_string())
|
|
}
|
|
|
|
fn openai_model_display_name(id: &str) -> String {
|
|
let canonical = openai_dated_snapshot_alias(id).unwrap_or_else(|| id.to_string());
|
|
if let Some(rest) = canonical.strip_prefix("chatgpt-") {
|
|
return format!("ChatGPT {}", title_case_model_suffix(rest));
|
|
}
|
|
if let Some(rest) = canonical.strip_prefix("gpt-") {
|
|
return format!("GPT-{}", title_case_model_suffix(rest));
|
|
}
|
|
|
|
canonical
|
|
}
|
|
|
|
fn title_case_model_suffix(value: &str) -> String {
|
|
value
|
|
.split('-')
|
|
.enumerate()
|
|
.map(|(index, part)| {
|
|
let part = if part.eq_ignore_ascii_case("pro") {
|
|
"Pro".to_string()
|
|
} else if part.eq_ignore_ascii_case("mini") {
|
|
"mini".to_string()
|
|
} else if part.eq_ignore_ascii_case("nano") {
|
|
"nano".to_string()
|
|
} else {
|
|
part.to_string()
|
|
};
|
|
|
|
if index == 0 {
|
|
part
|
|
} else {
|
|
format!(" {part}")
|
|
}
|
|
})
|
|
.collect::<String>()
|
|
}
|
|
|
|
fn normalize_openai_compatible_models(
|
|
response: OpenAiModelListResponse,
|
|
provider: Option<&str>,
|
|
) -> Vec<AgentModelInfo> {
|
|
let mut seen = HashSet::new();
|
|
let mut items = response.data;
|
|
let filter_to_openai_text_models = matches!(
|
|
provider
|
|
.map(str::trim)
|
|
.map(str::to_ascii_lowercase)
|
|
.as_deref(),
|
|
Some("openai")
|
|
);
|
|
let all_ids = items
|
|
.iter()
|
|
.map(|item| item.id.clone())
|
|
.collect::<HashSet<String>>();
|
|
items.sort_by(|left, right| {
|
|
right
|
|
.created
|
|
.cmp(&left.created)
|
|
.then_with(|| left.id.cmp(&right.id))
|
|
});
|
|
|
|
items
|
|
.into_iter()
|
|
.filter(|item| !filter_to_openai_text_models || is_agent_text_model_id(&item.id))
|
|
.filter(|item| match openai_dated_snapshot_alias(&item.id) {
|
|
Some(alias) if filter_to_openai_text_models => !all_ids.contains(&alias),
|
|
Some(_) | None => true,
|
|
})
|
|
.filter(|item| seen.insert(item.id.clone()))
|
|
.map(|item| AgentModelInfo {
|
|
name: Some(openai_model_display_name(&item.id)),
|
|
id: item.id,
|
|
description: None,
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
async fn discover_openai_compatible_models(
|
|
client: &reqwest::Client,
|
|
provider: &DiscoveryProvider,
|
|
env: &BTreeMap<String, String>,
|
|
selected_model: Option<String>,
|
|
) -> Result<Option<AgentModelsResponse>, String> {
|
|
let relay_mesh =
|
|
provider.as_deref().map(str::trim) == Some(crate::managed_agents::RELAY_MESH_PROVIDER_ID);
|
|
if !relay_mesh && !is_openai_compatible_provider(provider.as_deref()) {
|
|
return Ok(None);
|
|
}
|
|
|
|
let api_key = if relay_mesh {
|
|
crate::managed_agents::RELAY_MESH_API_KEY_PLACEHOLDER.to_string()
|
|
} else {
|
|
match provider.required_env(env, "OPENAI_COMPAT_API_KEY")? {
|
|
Some(api_key) => api_key,
|
|
None => return Ok(None),
|
|
}
|
|
};
|
|
let redaction_env = redaction_env_with_value(env, "OPENAI_COMPAT_API_KEY", &api_key);
|
|
let url = if relay_mesh {
|
|
format!("{}/models", crate::managed_agents::RELAY_MESH_API_BASE_URL)
|
|
} else {
|
|
openai_compatible_models_url_for_discovery(env)
|
|
};
|
|
let response = client
|
|
.get(&url)
|
|
.bearer_auth(&api_key)
|
|
.send()
|
|
.await
|
|
.map_err(|error| format!("OpenAI model discovery request failed: {error}"))?;
|
|
let status = response.status();
|
|
if !status.is_success() {
|
|
let body = response.text().await.unwrap_or_default();
|
|
let body = crate::managed_agents::redact_env_values_in(&body, &redaction_env);
|
|
return Err(format!("OpenAI model discovery HTTP {status}: {body}"));
|
|
}
|
|
|
|
let response = response
|
|
.json::<OpenAiModelListResponse>()
|
|
.await
|
|
.map_err(|error| format!("OpenAI model discovery response parse failed: {error}"))?;
|
|
let models = normalize_openai_compatible_models(response, provider.as_deref());
|
|
if models.is_empty() {
|
|
return Err("OpenAI model discovery returned no compatible text models".to_string());
|
|
}
|
|
|
|
Ok(Some(AgentModelsResponse {
|
|
agent_name: provider.as_deref().unwrap_or("openai").trim().to_string(),
|
|
agent_version: "models-api".to_string(),
|
|
models,
|
|
agent_default_model: None,
|
|
selected_model,
|
|
supports_switching: true,
|
|
}))
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
struct AnthropicModelListResponse {
|
|
data: Vec<AnthropicModelListItem>,
|
|
#[serde(default)]
|
|
has_more: bool,
|
|
#[serde(default)]
|
|
last_id: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
struct AnthropicModelListItem {
|
|
id: String,
|
|
#[serde(default)]
|
|
display_name: Option<String>,
|
|
}
|
|
|
|
fn is_anthropic_provider(provider: Option<&str>) -> bool {
|
|
matches!(
|
|
provider
|
|
.map(str::trim)
|
|
.map(str::to_ascii_lowercase)
|
|
.as_deref(),
|
|
Some("anthropic")
|
|
)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
fn anthropic_models_url(env: &BTreeMap<String, String>) -> String {
|
|
let base_url = env_value(env, "ANTHROPIC_BASE_URL")
|
|
.unwrap_or_else(|| "https://api.anthropic.com".to_string());
|
|
anthropic_models_url_from_base(&base_url)
|
|
}
|
|
|
|
fn anthropic_models_url_for_discovery(env: &BTreeMap<String, String>) -> String {
|
|
let base_url = env_or_process_value(env, "ANTHROPIC_BASE_URL")
|
|
.unwrap_or_else(|| "https://api.anthropic.com".to_string());
|
|
anthropic_models_url_from_base(&base_url)
|
|
}
|
|
|
|
fn anthropic_models_url_from_base(base_url: &str) -> String {
|
|
let base_url = base_url.trim_end_matches('/');
|
|
if base_url.ends_with("/v1") {
|
|
format!("{base_url}/models")
|
|
} else {
|
|
format!("{base_url}/v1/models")
|
|
}
|
|
}
|
|
|
|
fn normalize_anthropic_models(response: AnthropicModelListResponse) -> Vec<AgentModelInfo> {
|
|
let mut seen = HashSet::new();
|
|
response
|
|
.data
|
|
.into_iter()
|
|
.filter(|item| seen.insert(item.id.clone()))
|
|
.map(|item| AgentModelInfo {
|
|
id: item.id,
|
|
name: item.display_name,
|
|
description: None,
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
async fn fetch_anthropic_model_page(
|
|
client: &reqwest::Client,
|
|
url: &str,
|
|
api_key: &str,
|
|
after_id: Option<&str>,
|
|
env: &BTreeMap<String, String>,
|
|
) -> Result<AnthropicModelListResponse, String> {
|
|
let mut request = client
|
|
.get(url)
|
|
.header("x-api-key", api_key)
|
|
.header("anthropic-version", "2023-06-01");
|
|
if let Some(after_id) = after_id {
|
|
request = request.query(&[("after_id", after_id)]);
|
|
}
|
|
|
|
let response = request
|
|
.send()
|
|
.await
|
|
.map_err(|error| format!("Anthropic model discovery request failed: {error}"))?;
|
|
let status = response.status();
|
|
if !status.is_success() {
|
|
let body = response.text().await.unwrap_or_default();
|
|
let body = crate::managed_agents::redact_env_values_in(&body, env);
|
|
return Err(format!("Anthropic model discovery HTTP {status}: {body}"));
|
|
}
|
|
|
|
response
|
|
.json::<AnthropicModelListResponse>()
|
|
.await
|
|
.map_err(|error| format!("Anthropic model discovery response parse failed: {error}"))
|
|
}
|
|
|
|
async fn discover_anthropic_models(
|
|
client: &reqwest::Client,
|
|
provider: &DiscoveryProvider,
|
|
env: &BTreeMap<String, String>,
|
|
selected_model: Option<String>,
|
|
) -> Result<Option<AgentModelsResponse>, String> {
|
|
if !is_anthropic_provider(provider.as_deref()) {
|
|
return Ok(None);
|
|
}
|
|
|
|
let api_key = match provider.required_env(env, "ANTHROPIC_API_KEY")? {
|
|
Some(api_key) => api_key,
|
|
None => return Ok(None),
|
|
};
|
|
let redaction_env = redaction_env_with_value(env, "ANTHROPIC_API_KEY", &api_key);
|
|
let url = anthropic_models_url_for_discovery(env);
|
|
let mut models = Vec::new();
|
|
let mut after_id: Option<String> = None;
|
|
for _ in 0..20 {
|
|
let response =
|
|
fetch_anthropic_model_page(client, &url, &api_key, after_id.as_deref(), &redaction_env)
|
|
.await?;
|
|
let has_more = response.has_more;
|
|
after_id = response.last_id.clone();
|
|
models.extend(normalize_anthropic_models(response));
|
|
if !has_more {
|
|
break;
|
|
}
|
|
if after_id.as_deref().unwrap_or_default().is_empty() {
|
|
return Err("Anthropic model discovery pagination did not return last_id".to_string());
|
|
}
|
|
}
|
|
let mut seen = HashSet::new();
|
|
models.retain(|model| seen.insert(model.id.clone()));
|
|
if models.is_empty() {
|
|
return Err("Anthropic model discovery returned no models".to_string());
|
|
}
|
|
|
|
Ok(Some(AgentModelsResponse {
|
|
agent_name: provider
|
|
.as_deref()
|
|
.unwrap_or("anthropic")
|
|
.trim()
|
|
.to_string(),
|
|
agent_version: "models-api".to_string(),
|
|
models,
|
|
agent_default_model: None,
|
|
selected_model,
|
|
supports_switching: true,
|
|
}))
|
|
}
|
|
|
|
#[path = "agent_models_databricks.rs"]
|
|
mod databricks;
|
|
#[cfg(test)]
|
|
use databricks::{
|
|
databricks_models_response, databricks_sign_in_required_error, databricks_static_token_error,
|
|
is_databricks_provider, should_start_interactive_auth,
|
|
};
|
|
use databricks::{discover_databricks_models, DatabricksAuthIntent};
|
|
|
|
#[path = "agent_models_update.rs"]
|
|
mod update;
|
|
pub use update::update_managed_agent;
|
|
pub(super) use update::{flush_managed_agent_policy, managed_agent_access_policy_changed};
|
|
|
|
// ── Model normalization ───────────────────────────────────────────────────────
|
|
|
|
/// Normalize raw `buzz-acp models --json` output into a typed DTO for the frontend.
|
|
///
|
|
/// Merges models from both ACP paths (stable configOptions + unstable SessionModelState),
|
|
/// deduplicates by ID (stable takes precedence), and returns a unified list.
|
|
pub(super) fn normalize_agent_models(
|
|
raw: &serde_json::Value,
|
|
persisted_model: Option<String>,
|
|
) -> AgentModelsResponse {
|
|
let agent_name = raw["agent"]["name"]
|
|
.as_str()
|
|
.unwrap_or("unknown")
|
|
.to_string();
|
|
let agent_version = raw["agent"]["version"]
|
|
.as_str()
|
|
.unwrap_or("unknown")
|
|
.to_string();
|
|
|
|
let mut models: Vec<AgentModelInfo> = Vec::new();
|
|
let mut seen_ids: HashSet<String> = HashSet::new();
|
|
|
|
// 1. Stable configOptions (preferred). Only entries with category "model"
|
|
// are model options — the CLI pre-filters, but we're defensive here.
|
|
if let Some(config_options) = raw["stable"]["configOptions"].as_array() {
|
|
for opt in config_options {
|
|
if opt.get("category").and_then(|c| c.as_str()) != Some("model") {
|
|
continue;
|
|
}
|
|
if let Some(options) = opt.get("options").and_then(|v| v.as_array()) {
|
|
for o in options {
|
|
if let Some(value) = o.get("value").and_then(|v| v.as_str()) {
|
|
if seen_ids.insert(value.to_string()) {
|
|
models.push(AgentModelInfo {
|
|
id: value.to_string(),
|
|
name: o
|
|
.get("displayName")
|
|
.and_then(|v| v.as_str())
|
|
.map(str::to_string),
|
|
description: None,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// 2. Unstable availableModels (fallback — skip duplicates from stable).
|
|
let mut agent_default_model: Option<String> = None;
|
|
if let Some(unstable) = raw.get("unstable") {
|
|
agent_default_model = unstable["currentModelId"].as_str().map(str::to_string);
|
|
if let Some(available) = unstable["availableModels"].as_array() {
|
|
for m in available {
|
|
if let Some(id) = m.get("modelId").and_then(|v| v.as_str()) {
|
|
if seen_ids.insert(id.to_string()) {
|
|
models.push(AgentModelInfo {
|
|
id: id.to_string(),
|
|
name: m.get("name").and_then(|v| v.as_str()).map(str::to_string),
|
|
description: m
|
|
.get("description")
|
|
.and_then(|v| v.as_str())
|
|
.map(str::to_string),
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
let supports_switching = !models.is_empty();
|
|
|
|
AgentModelsResponse {
|
|
agent_name,
|
|
agent_version,
|
|
models,
|
|
agent_default_model,
|
|
selected_model: persisted_model,
|
|
supports_switching,
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "agent_models_tests.rs"]
|
|
mod tests;
|