返回 CodeWhale
agent_profiles.rs
根目录 / crates / tui / src / agent_profiles.rs
1 use anyhow::{Context, Result, anyhow, bail};
2 use clap::{Args, Parser, Subcommand};
3 use codewhale_engine::fleet::profile::{
4 AgentProfile, FleetProfileScope, parse_agent_profile_text, read_agent_profile_document,
5 save_agent_profile_document, set_markdown_profile_route,
6 };
7 use codewhale_engine::fleet::roster::{FleetRoster, ProfileOrigin, project_agent_profiles_enabled};
8 use codewhale_runtime::config::{Config, is_workspace_trusted};
9 use std::path::Path;
10
11 #[derive(Args, Clone, Debug)]
12 pub(crate) struct AgentProfilesArgs {
13 #[command(subcommand)]
14 command: Option<AgentProfilesCommand>,
15 }
16
17 #[derive(Clone, Debug, Subcommand)]
18 enum AgentProfilesCommand {
19 #[command(about = "List saved agent profiles")]
20 List,
21 #[command(about = "Inspect a profile by stable ID")]
22 Show { id: String },
23 #[command(about = "Save an exact provider and model in a profile")]
24 Route {
25 id: String,
26 provider: String,
27 model: String,
28 },
29 }
30
31 #[derive(Parser)]
32 #[command(name = "/agents")]
33 struct AgentProfilesSlash {
34 #[command(flatten)]
35 args: AgentProfilesArgs,
36 }
37
38 pub(crate) fn parse_slash(input: &str) -> Result<AgentProfilesArgs> {
39 let parsed = AgentProfilesSlash::try_parse_from(
40 std::iter::once("/agents").chain(input.split_whitespace()),
41 )?;
42 Ok(parsed.args)
43 }
44
45 pub(crate) fn run(
46 workspace: &Path,
47 config: &Config,
48 plugins: &codewhale_plugins::PluginRegistry,
49 args: AgentProfilesArgs,
50 ) -> Result<String> {
51 let profiles = FleetRoster::load_agent_library(&config.fleet_config(), workspace, plugins);
52 match args.command.unwrap_or(AgentProfilesCommand::List) {
53 AgentProfilesCommand::List => {
54 let rows: Vec<_> = profiles
55 .members()
56 .iter()
57 .filter(|profile| profile.origin != ProfileOrigin::BuiltIn)
58 .map(profile_summary)
59 .chain(profiles.profile_load_issues().iter().map(|issue| {
60 format!(
61 "{} · invalid {} profile · {}",
62 display(&issue.id),
63 issue.origin,
64 display(&issue.source.display().to_string())
65 )
66 }))
67 .collect();
68 if rows.is_empty() {
69 return Ok(
70 "No saved profiles. Add a Markdown or TOML file in your agents directory."
71 .into(),
72 );
73 }
74 Ok(rows.join("\n"))
75 }
76 AgentProfilesCommand::Show { id } => {
77 let profile = profiles
78 .resolve_member(&format!("member:{id}"))?
79 .with_context(|| format!("Agent profile {:?} is unavailable", display(&id)))?;
80 Ok(format!(
81 "{}\n\n{}\n{}",
82 profile_summary(profile),
83 display(profile.description.as_deref().unwrap_or("")),
84 display(&profile.source.display().to_string())
85 ))
86 }
87 AgentProfilesCommand::Route {
88 id,
89 provider,
90 model,
91 } => {
92 let profile = profiles
93 .resolve_member(&format!("member:{id}"))?
94 .with_context(|| format!("Agent profile {:?} is unavailable", display(&id)))?;
95 let scope = match profile.origin {
96 ProfileOrigin::Personal => FleetProfileScope::Personal,
97 ProfileOrigin::Workspace
98 if project_agent_profiles_enabled() && is_workspace_trusted(workspace) =>
99 {
100 FleetProfileScope::Project
101 }
102 _ => bail!("Edit a personal or trusted project profile to save a route"),
103 };
104 let raw = read_agent_profile_document(scope, workspace, &profile.source)?
105 .context("Profile moved on disk. Reopen /agents and retry.")?;
106 let snapshot = parse_agent_profile_text(&profile.source, &raw)?;
107 anyhow::ensure!(
108 snapshot.id == profile.id,
109 "Profile identity changed. Reopen /agents before saving."
110 );
111 anyhow::ensure!(
112 snapshot.profile.external_agent.is_none(),
113 "External agent profiles own their own model routing"
114 );
115 anyhow::ensure!(
116 !model.eq_ignore_ascii_case("auto"),
117 "Choose a concrete model"
118 );
119 let identity = config
120 .resolve_provider_pin_identity(&provider)
121 .map_err(|_| anyhow!("Provider is unavailable: {}", display(&provider)))?;
122 if identity.provider == codewhale_config::ProviderKind::OpencodeGo {
123 tokio::runtime::Handle::try_current()?.block_on(
124 codewhale_engine::provider_lake::update_provider_catalog(config, &identity),
125 );
126 let status = codewhale_engine::provider_catalog_live::status_for_route(
127 identity.provider,
128 identity.key.as_str(),
129 &config.base_url_for_route(&identity),
130 );
131 anyhow::ensure!(
132 matches!(status, codewhale_config::catalog::CatalogStatus::Fresh),
133 "Go inventory {} is unavailable ({status:?})",
134 identity.key
135 );
136 }
137 let route = codewhale_engine::route_runtime::resolve_runtime_route_for_identity(
138 config,
139 &identity,
140 Some(&model),
141 )
142 .map_err(anyhow::Error::msg)?
143 .validate()
144 .map_err(anyhow::Error::msg)?;
145 let provider = route.identity.key.as_str();
146 let model = route.candidate.wire_model_id().as_str();
147 let next = if profile.source.extension().is_some_and(|ext| ext == "md") {
148 set_markdown_profile_route(
149 &profile.source,
150 &raw,
151 Some(provider),
152 Some(model),
153 snapshot.profile.reasoning_effort.as_deref(),
154 )?
155 } else {
156 let mut document: toml_edit::DocumentMut = raw.parse()?;
157 for alias in ["model", "model_hint", "model_id"] {
158 document.remove(alias);
159 }
160 document["provider"] = toml_edit::value(provider);
161 document["model"] = toml_edit::value(model);
162 document.to_string()
163 };
164 if scope == FleetProfileScope::Project {
165 anyhow::ensure!(
166 is_workspace_trusted(workspace),
167 "Project trust changed. Reopen /agents before saving."
168 );
169 }
170 save_agent_profile_document(
171 scope,
172 workspace,
173 &profile.source,
174 Some(&raw),
175 &profile.id,
176 &next,
177 )?;
178 Ok(format!(
179 "{} · {} / {}",
180 display(&profile.id),
181 display(provider),
182 display(model)
183 ))
184 }
185 }
186 }
187
188 fn profile_summary(profile: &AgentProfile) -> String {
189 format!(
190 "{} · {} · {} · {} / {}",
191 display(&profile.id),
192 profile.origin,
193 display(&profile.profile.role.name),
194 display(profile.profile.provider.as_deref().unwrap_or("inherit")),
195 display(profile.profile.model.as_deref().unwrap_or("inherit"))
196 )
197 }
198
199 fn display(text: &str) -> String {
200 text.chars().filter(|c| !c.is_control()).take(240).collect()
201 }
202
203 #[cfg(test)]
204 mod tests {
205 use super::*;
206
207 #[test]
208 fn profile_library_reads_markdown_and_toml_without_starting_a_run() {
209 let _home = codewhale_runtime::test_support::SealedHome::new();
210 let directory = codewhale_engine::fleet::profile::personal_agent_profile_dir().unwrap();
211 std::fs::create_dir_all(&directory).unwrap();
212 std::fs::write(
213 directory.join("scope-review.md"),
214 "---\nname: scope-review\ndescription: Review changes\n---\nLook for regressions.\n",
215 )
216 .unwrap();
217 std::fs::write(
218 directory.join("scope-build.toml"),
219 "id = \"scope-build\"\nmodel = \"deepseek-v4-pro\"\n",
220 )
221 .unwrap();
222 let workspace = tempfile::tempdir().unwrap();
223 let config = Config::default();
224 let plugins = codewhale_plugins::PluginRegistry::empty(workspace.path());
225 let list = run(
226 workspace.path(),
227 &config,
228 &plugins,
229 parse_slash("").unwrap(),
230 )
231 .unwrap();
232 assert!(list.contains("scope-review"), "{list}");
233 assert!(list.contains("scope-build"), "{list}");
234 let details = run(
235 workspace.path(),
236 &config,
237 &plugins,
238 parse_slash("show scope-review").unwrap(),
239 )
240 .unwrap();
241 assert!(details.contains("Review changes"), "{details}");
242 assert!(!workspace.path().join(".codewhale/fleet.jsonl").exists());
243 }
244 }
245
245 lines RUST