Merge pull request #17: feat(agents): provider catalog, chat runs, and Write with identity
@@ -11,6 +11,7 @@ serde_json.workspace = true
11
11
thiserror.workspace = true
12
12
tokio.workspace = true
13
13
uuid.workspace = true
14
reqwest = { version = "0.13", default-features = false, features = ["rustls", "json"] }
14
15
15
16
[dev-dependencies]
16
17
tempfile.workspace = true
@@ -11,6 +11,7 @@ serde_json.workspace = true11
thiserror.workspace = true11
thiserror.workspace = true12
tokio.workspace = true12
tokio.workspace = true13
uuid.workspace = true13
uuid.workspace = true14
reqwest = { version = "0.13", default-features = false, features = ["rustls", "json"] }14
15
15
[dev-dependencies]16
[dev-dependencies]16
tempfile.workspace = true17
tempfile.workspace = true@@ -0,0 +1,171 @@
1
use std::path::{Path, PathBuf};
2
3
use crate::profile::{AgentProfile, Environment};
4
5
#[derive(Clone, Debug, PartialEq, Eq)]
6
pub struct CliHit {
7
pub profile: AgentProfile,
8
pub binary: PathBuf,
9
}
10
11
struct Template {
12
names: &'static [&'static str],
13
build: fn() -> AgentProfile,
14
cursor: bool,
15
}
16
17
pub fn scan_clis() -> Vec<CliHit> {
18
let templates = [
19
Template {
20
names: &["claude"],
21
build: AgentProfile::claude_host,
22
cursor: false,
23
},
24
Template {
25
names: &["copilot"],
26
build: AgentProfile::copilot_host,
27
cursor: false,
28
},
29
Template {
30
names: &["codex"],
31
build: AgentProfile::codex_host,
32
cursor: false,
33
},
34
Template {
35
names: &["cursor-agent", "agent"],
36
build: AgentProfile::cursor_host,
37
cursor: true,
38
},
39
Template {
40
names: &["agy"],
41
build: AgentProfile::agy_host,
42
cursor: false,
43
},
44
];
45
templates
46
.into_iter()
47
.filter_map(|template| {
48
let binary = find_binary(template.names, template.cursor)?;
49
let program = binary
50
.file_name()
51
.and_then(|name| name.to_str())
52
.unwrap_or(template.names[0]);
53
let mut profile = with_program((template.build)(), program);
54
if !cfg!(windows) {
55
profile.open_session_command.clear();
56
}
57
profile.environment = Environment::Host;
58
Some(CliHit { profile, binary })
59
})
60
.collect()
61
}
62
63
/// A bare program name is looked up on `PATH` and in `~/.local/bin`.
64
/// A desktop session often omits the user bin directory, so `claude` and
65
/// `cursor-agent` exist for the shell but not for the app.
66
pub fn resolve_program(program: &str) -> Option<PathBuf> {
67
let path = Path::new(program);
68
if path.is_absolute() || program.contains('/') || program.contains('\\') {
69
return path.is_file().then(|| path.to_path_buf());
70
}
71
for directory in candidate_dirs() {
72
if let Some(found) = executable(&directory, program) {
73
return Some(found);
74
}
75
}
76
None
77
}
78
79
pub fn already_installed(existing: &[AgentProfile], hit: &AgentProfile) -> bool {
80
let program = hit.command_program();
81
existing.iter().any(|agent| {
82
agent.is_command()
83
&& agent.environment == hit.environment
84
&& agent.command_program() == program
85
})
86
}
87
88
fn with_program(mut profile: AgentProfile, program: &str) -> AgentProfile {
89
let rest = profile.command.split_once(' ').map(|(_, rest)| rest);
90
profile.command = match rest {
91
Some(rest) => format!("{program} {rest}"),
92
None => program.to_owned(),
93
};
94
profile
95
}
96
97
fn candidate_dirs() -> Vec<PathBuf> {
98
let mut dirs = Vec::new();
99
if let Some(path) = std::env::var_os("PATH") {
100
dirs.extend(std::env::split_paths(&path));
101
}
102
if let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) {
103
let home = PathBuf::from(home);
104
dirs.push(home.join(".local").join("bin"));
105
}
106
dirs
107
}
108
109
fn find_binary(names: &[&str], cursor: bool) -> Option<PathBuf> {
110
for directory in candidate_dirs() {
111
for name in names {
112
if let Some(path) = executable(&directory, name) {
113
if cursor && *name == "agent" && !looks_like_cursor(&path) {
114
continue;
115
}
116
return Some(path);
117
}
118
}
119
}
120
None
121
}
122
123
fn executable(directory: &Path, name: &str) -> Option<PathBuf> {
124
["", ".exe", ".cmd"].into_iter().find_map(|extension| {
125
let path = directory.join(format!("{name}{extension}"));
126
path.is_file().then_some(path)
127
})
128
}
129
130
fn looks_like_cursor(path: &Path) -> bool {
131
let linked = std::fs::read_link(path).unwrap_or_else(|_| path.to_path_buf());
132
let text = format!("{} {}", path.display(), linked.display());
133
text.contains("cursor-agent")
134
}
135
136
#[cfg(test)]
137
mod tests {
138
use super::*;
139
140
#[test]
141
fn a_wsl_claude_does_not_hide_the_host_binary() {
142
let wsl = AgentProfile::claude_wsl();
143
let host = AgentProfile::claude_host();
144
assert!(!already_installed(&[wsl], &host));
145
assert!(already_installed(&[host.clone()], &host));
146
}
147
148
#[test]
149
fn an_absolute_program_is_used_and_a_missing_name_is_not() {
150
let directory = std::env::temp_dir().join(format!("agents-resolve-{}", std::process::id()));
151
let _ = std::fs::remove_dir_all(&directory);
152
std::fs::create_dir_all(&directory).unwrap();
153
let binary = directory.join("claude");
154
std::fs::write(&binary, b"").unwrap();
155
assert_eq!(
156
resolve_program(binary.to_str().unwrap()).as_deref(),
157
Some(binary.as_path())
158
);
159
assert!(resolve_program("definitely-not-a-real-program").is_none());
160
let _ = std::fs::remove_dir_all(&directory);
161
}
162
163
#[test]
164
fn the_program_token_is_replaced_and_the_rest_stays() {
165
let profile = with_program(AgentProfile::cursor_host(), "cursor-agent");
166
assert_eq!(
167
profile.command,
168
"cursor-agent -p --trust --approve-mcps {prompt}"
169
);
170
}
171
}
@@ -0,0 +1,171 @@1
use std::path::{Path, PathBuf};2
3
use crate::profile::{AgentProfile, Environment};4
5
#[derive(Clone, Debug, PartialEq, Eq)]6
pub struct CliHit {7
pub profile: AgentProfile,8
pub binary: PathBuf,9
}10
11
struct Template {12
names: &'static [&'static str],13
build: fn() -> AgentProfile,14
cursor: bool,15
}16
17
pub fn scan_clis() -> Vec<CliHit> {18
let templates = [19
Template {20
names: &["claude"],21
build: AgentProfile::claude_host,22
cursor: false,23
},24
Template {25
names: &["copilot"],26
build: AgentProfile::copilot_host,27
cursor: false,28
},29
Template {30
names: &["codex"],31
build: AgentProfile::codex_host,32
cursor: false,33
},34
Template {35
names: &["cursor-agent", "agent"],36
build: AgentProfile::cursor_host,37
cursor: true,38
},39
Template {40
names: &["agy"],41
build: AgentProfile::agy_host,42
cursor: false,43
},44
];45
templates46
.into_iter()47
.filter_map(|template| {48
let binary = find_binary(template.names, template.cursor)?;49
let program = binary50
.file_name()51
.and_then(|name| name.to_str())52
.unwrap_or(template.names[0]);53
let mut profile = with_program((template.build)(), program);54
if !cfg!(windows) {55
profile.open_session_command.clear();56
}57
profile.environment = Environment::Host;58
Some(CliHit { profile, binary })59
})60
.collect()61
}62
63
/// A bare program name is looked up on `PATH` and in `~/.local/bin`.64
/// A desktop session often omits the user bin directory, so `claude` and65
/// `cursor-agent` exist for the shell but not for the app.66
pub fn resolve_program(program: &str) -> Option<PathBuf> {67
let path = Path::new(program);68
if path.is_absolute() || program.contains('/') || program.contains('\\') {69
return path.is_file().then(|| path.to_path_buf());70
}71
for directory in candidate_dirs() {72
if let Some(found) = executable(&directory, program) {73
return Some(found);74
}75
}76
None77
}78
79
pub fn already_installed(existing: &[AgentProfile], hit: &AgentProfile) -> bool {80
let program = hit.command_program();81
existing.iter().any(|agent| {82
agent.is_command()83
&& agent.environment == hit.environment84
&& agent.command_program() == program85
})86
}87
88
fn with_program(mut profile: AgentProfile, program: &str) -> AgentProfile {89
let rest = profile.command.split_once(' ').map(|(_, rest)| rest);90
profile.command = match rest {91
Some(rest) => format!("{program} {rest}"),92
None => program.to_owned(),93
};94
profile95
}96
97
fn candidate_dirs() -> Vec<PathBuf> {98
let mut dirs = Vec::new();99
if let Some(path) = std::env::var_os("PATH") {100
dirs.extend(std::env::split_paths(&path));101
}102
if let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) {103
let home = PathBuf::from(home);104
dirs.push(home.join(".local").join("bin"));105
}106
dirs107
}108
109
fn find_binary(names: &[&str], cursor: bool) -> Option<PathBuf> {110
for directory in candidate_dirs() {111
for name in names {112
if let Some(path) = executable(&directory, name) {113
if cursor && *name == "agent" && !looks_like_cursor(&path) {114
continue;115
}116
return Some(path);117
}118
}119
}120
None121
}122
123
fn executable(directory: &Path, name: &str) -> Option<PathBuf> {124
["", ".exe", ".cmd"].into_iter().find_map(|extension| {125
let path = directory.join(format!("{name}{extension}"));126
path.is_file().then_some(path)127
})128
}129
130
fn looks_like_cursor(path: &Path) -> bool {131
let linked = std::fs::read_link(path).unwrap_or_else(|_| path.to_path_buf());132
let text = format!("{} {}", path.display(), linked.display());133
text.contains("cursor-agent")134
}135
136
#[cfg(test)]137
mod tests {138
use super::*;139
140
#[test]141
fn a_wsl_claude_does_not_hide_the_host_binary() {142
let wsl = AgentProfile::claude_wsl();143
let host = AgentProfile::claude_host();144
assert!(!already_installed(&[wsl], &host));145
assert!(already_installed(&[host.clone()], &host));146
}147
148
#[test]149
fn an_absolute_program_is_used_and_a_missing_name_is_not() {150
let directory = std::env::temp_dir().join(format!("agents-resolve-{}", std::process::id()));151
let _ = std::fs::remove_dir_all(&directory);152
std::fs::create_dir_all(&directory).unwrap();153
let binary = directory.join("claude");154
std::fs::write(&binary, b"").unwrap();155
assert_eq!(156
resolve_program(binary.to_str().unwrap()).as_deref(),157
Some(binary.as_path())158
);159
assert!(resolve_program("definitely-not-a-real-program").is_none());160
let _ = std::fs::remove_dir_all(&directory);161
}162
163
#[test]164
fn the_program_token_is_replaced_and_the_rest_stays() {165
let profile = with_program(AgentProfile::cursor_host(), "cursor-agent");166
assert_eq!(167
profile.command,168
"cursor-agent -p --trust --approve-mcps {prompt}"169
);170
}171
}@@ -0,0 +1,568 @@
1
use serde_json::{Value, json};
2
3
use crate::profile::{AgentBackend, AgentProfile};
4
5
const TURN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
6
const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
7
const ANTHROPIC_VERSION: &str = "2023-06-01";
8
const ANTHROPIC_URL: &str = "https://api.anthropic.com/v1/messages";
9
const MAX_TOKENS: u32 = 4096;
10
11
#[derive(Clone, Debug, PartialEq, Eq)]
12
pub struct ToolSpec {
13
pub name: String,
14
pub description: String,
15
pub parameters: Value,
16
}
17
18
#[derive(Clone, Debug, PartialEq, Eq)]
19
pub struct ToolCall {
20
pub id: String,
21
pub name: String,
22
pub arguments: String,
23
}
24
25
#[derive(Clone, Debug, PartialEq, Eq)]
26
pub enum ChatRole {
27
User,
28
Assistant,
29
Tool,
30
}
31
32
#[derive(Clone, Debug, PartialEq, Eq)]
33
pub struct ChatMessage {
34
pub role: ChatRole,
35
pub text: String,
36
pub tool_calls: Vec<ToolCall>,
37
pub tool_call_id: String,
38
}
39
40
impl ChatMessage {
41
pub fn user(text: impl Into<String>) -> Self {
42
Self {
43
role: ChatRole::User,
44
text: text.into(),
45
tool_calls: Vec::new(),
46
tool_call_id: String::new(),
47
}
48
}
49
50
pub fn assistant(text: impl Into<String>, tool_calls: Vec<ToolCall>) -> Self {
51
Self {
52
role: ChatRole::Assistant,
53
text: text.into(),
54
tool_calls,
55
tool_call_id: String::new(),
56
}
57
}
58
59
pub fn tool(id: impl Into<String>, text: impl Into<String>) -> Self {
60
Self {
61
role: ChatRole::Tool,
62
text: text.into(),
63
tool_calls: Vec::new(),
64
tool_call_id: id.into(),
65
}
66
}
67
}
68
69
#[derive(Clone, Debug, PartialEq, Eq)]
70
pub enum ChatReply {
71
Text(String),
72
Tools { text: String, calls: Vec<ToolCall> },
73
}
74
75
pub async fn complete_text(
76
profile: &AgentProfile,
77
system: &str,
78
user: &str,
79
) -> Result<String, String> {
80
match next_turn(profile, system, &[ChatMessage::user(user)], &[]).await? {
81
ChatReply::Text(text) => Ok(text),
82
ChatReply::Tools { text, .. } => Ok(text),
83
}
84
}
85
86
pub async fn next_turn(
87
profile: &AgentProfile,
88
system: &str,
89
messages: &[ChatMessage],
90
tools: &[ToolSpec],
91
) -> Result<ChatReply, String> {
92
let body = match &profile.backend {
93
AgentBackend::OpenAi { .. } => openai_body(system, messages, tools),
94
AgentBackend::Anthropic { .. } => anthropic_body(profile, system, messages, tools)?,
95
AgentBackend::Command => return Err("this agent is a command, not a chat API".to_owned()),
96
};
97
let value = post(profile, &body).await?;
98
match &profile.backend {
99
AgentBackend::OpenAi { .. } => parse_openai(&value),
100
AgentBackend::Anthropic { .. } => parse_anthropic(&value),
101
AgentBackend::Command => unreachable!(),
102
}
103
}
104
105
const MODEL_LIST_LIMIT: usize = 400;
106
107
pub async fn list_models(profile: &AgentProfile) -> Result<Vec<String>, String> {
108
let (url, key, anthropic) = models_endpoint(profile)?;
109
let value = get(&key, &url, anthropic).await?;
110
let mut names = model_names(&value);
111
names.sort_by(|left, right| left.to_ascii_lowercase().cmp(&right.to_ascii_lowercase()));
112
names.dedup();
113
names.truncate(MODEL_LIST_LIMIT);
114
if names.is_empty() {
115
return Err("the endpoint listed no models".to_owned());
116
}
117
Ok(names)
118
}
119
120
pub async fn probe_backend(profile: &AgentProfile) -> Result<String, String> {
121
let names = list_models(profile).await?;
122
Ok(match names.len() {
123
1 => names[0].clone(),
124
2..=4 => names.join(", "),
125
count => format!("{count} models"),
126
})
127
}
128
129
fn models_endpoint(profile: &AgentProfile) -> Result<(String, String, bool), String> {
130
match &profile.backend {
131
AgentBackend::OpenAi {
132
base_url, api_key, ..
133
} => Ok((models_url(base_url), api_key.clone(), false)),
134
AgentBackend::Anthropic { api_key, .. } => {
135
if api_key.trim().is_empty() {
136
return Err("the Anthropic key is empty".to_owned());
137
}
138
Ok((
139
"https://api.anthropic.com/v1/models".to_owned(),
140
api_key.clone(),
141
true,
142
))
143
}
144
AgentBackend::Command => Err("this agent is a command".to_owned()),
145
}
146
}
147
148
fn openai_body(system: &str, messages: &[ChatMessage], tools: &[ToolSpec]) -> Value {
149
let mut chat = Vec::new();
150
if !system.is_empty() {
151
chat.push(json!({"role": "system", "content": system}));
152
}
153
for message in messages {
154
match message.role {
155
ChatRole::User => chat.push(json!({"role": "user", "content": message.text})),
156
ChatRole::Tool => chat.push(json!({
157
"role": "tool",
158
"tool_call_id": message.tool_call_id,
159
"content": message.text,
160
})),
161
ChatRole::Assistant => {
162
let mut row = json!({"role": "assistant", "content": message.text});
163
if !message.tool_calls.is_empty() {
164
row["tool_calls"] = Value::Array(
165
message
166
.tool_calls
167
.iter()
168
.map(|call| {
169
json!({
170
"id": call.id,
171
"type": "function",
172
"function": { "name": call.name, "arguments": call.arguments },
173
})
174
})
175
.collect(),
176
);
177
}
178
chat.push(row);
179
}
180
}
181
}
182
let mut body = json!({"messages": chat, "stream": false});
183
if !tools.is_empty() {
184
body["tools"] = Value::Array(
185
tools
186
.iter()
187
.map(|tool| {
188
json!({
189
"type": "function",
190
"function": {
191
"name": tool.name,
192
"description": tool.description,
193
"parameters": tool.parameters,
194
}
195
})
196
})
197
.collect(),
198
);
199
}
200
body
201
}
202
203
fn anthropic_body(
204
profile: &AgentProfile,
205
system: &str,
206
messages: &[ChatMessage],
207
tools: &[ToolSpec],
208
) -> Result<Value, String> {
209
let AgentBackend::Anthropic { model, .. } = &profile.backend else {
210
return Err("not an Anthropic profile".to_owned());
211
};
212
let mut chat = Vec::new();
213
for message in messages {
214
match message.role {
215
ChatRole::User => chat.push(json!({"role": "user", "content": message.text})),
216
ChatRole::Tool => chat.push(json!({
217
"role": "user",
218
"content": [{
219
"type": "tool_result",
220
"tool_use_id": message.tool_call_id,
221
"content": message.text,
222
}]
223
})),
224
ChatRole::Assistant => {
225
let mut content = Vec::new();
226
if !message.text.is_empty() {
227
content.push(json!({"type": "text", "text": message.text}));
228
}
229
for call in &message.tool_calls {
230
let input = serde_json::from_str::<Value>(&call.arguments)
231
.unwrap_or(Value::Object(Default::default()));
232
content.push(json!({
233
"type": "tool_use",
234
"id": call.id,
235
"name": call.name,
236
"input": input,
237
}));
238
}
239
chat.push(json!({"role": "assistant", "content": content}));
240
}
241
}
242
}
243
let mut body = json!({
244
"model": model,
245
"max_tokens": MAX_TOKENS,
246
"messages": chat,
247
});
248
if !system.is_empty() {
249
body["system"] = Value::String(system.to_owned());
250
}
251
if !tools.is_empty() {
252
body["tools"] = Value::Array(
253
tools
254
.iter()
255
.map(|tool| {
256
json!({
257
"name": tool.name,
258
"description": tool.description,
259
"input_schema": tool.parameters,
260
})
261
})
262
.collect(),
263
);
264
}
265
Ok(body)
266
}
267
268
fn chat_url(base_url: &str) -> String {
269
let base = base_url.trim().trim_end_matches('/');
270
if base.ends_with("/chat/completions") {
271
return base.to_owned();
272
}
273
// Ollama answers the OpenAI route only under /v1. The model list also
274
// accepts the bare port, so a base without /v1 still has to land there.
275
if base.contains(":11434") {
276
let origin = base.strip_suffix("/v1").unwrap_or(base);
277
return format!("{origin}/v1/chat/completions");
278
}
279
format!("{base}/chat/completions")
280
}
281
282
fn models_url(base_url: &str) -> String {
283
let base = base_url.trim().trim_end_matches('/');
284
if base.contains(":11434") {
285
let origin = base.trim_end_matches("/v1");
286
format!("{origin}/api/tags")
287
} else {
288
format!("{base}/models")
289
}
290
}
291
292
async fn post(profile: &AgentProfile, body: &Value) -> Result<Value, String> {
293
let (url, key, anthropic, model) = endpoint(profile)?;
294
let mut payload = body.clone();
295
if !anthropic {
296
payload["model"] = Value::String(model);
297
}
298
let client = client(TURN_TIMEOUT)?;
299
let mut request = client.post(url).json(&payload);
300
request = authorize(request, &key, anthropic);
301
read_json(request).await
302
}
303
304
async fn get(key: &str, url: &str, anthropic: bool) -> Result<Value, String> {
305
let client = client(PROBE_TIMEOUT)?;
306
let request = authorize(client.get(url), key, anthropic);
307
read_json(request).await
308
}
309
310
fn endpoint(profile: &AgentProfile) -> Result<(String, String, bool, String), String> {
311
match &profile.backend {
312
AgentBackend::OpenAi {
313
base_url,
314
model,
315
api_key,
316
} => {
317
if model.trim().is_empty() {
318
return Err("choose a model first".to_owned());
319
}
320
Ok((chat_url(base_url), api_key.clone(), false, model.clone()))
321
}
322
AgentBackend::Anthropic { model, api_key } => {
323
if api_key.trim().is_empty() {
324
return Err("the Anthropic key is empty".to_owned());
325
}
326
if model.trim().is_empty() {
327
return Err("choose a model first".to_owned());
328
}
329
Ok((
330
ANTHROPIC_URL.to_owned(),
331
api_key.clone(),
332
true,
333
model.clone(),
334
))
335
}
336
AgentBackend::Command => Err("this agent is a command".to_owned()),
337
}
338
}
339
340
fn client(timeout: std::time::Duration) -> Result<reqwest::Client, String> {
341
reqwest::Client::builder()
342
.timeout(timeout)
343
.build()
344
.map_err(|error| error.to_string())
345
}
346
347
fn authorize(
348
request: reqwest::RequestBuilder,
349
key: &str,
350
anthropic: bool,
351
) -> reqwest::RequestBuilder {
352
if anthropic {
353
return request
354
.header("x-api-key", key)
355
.header("anthropic-version", ANTHROPIC_VERSION);
356
}
357
if key.trim().is_empty() {
358
request
359
} else {
360
request.bearer_auth(key)
361
}
362
}
363
364
async fn read_json(request: reqwest::RequestBuilder) -> Result<Value, String> {
365
let response = request.send().await.map_err(|error| error.to_string())?;
366
let status = response.status();
367
let bytes = response.bytes().await.map_err(|error| error.to_string())?;
368
let value: Value = serde_json::from_slice(&bytes).map_err(|_| {
369
let body = String::from_utf8_lossy(&bytes);
370
let snippet: String = body.trim().chars().take(180).collect();
371
if snippet.is_empty() {
372
format!("HTTP {status} with an empty body")
373
} else {
374
format!("HTTP {status}: {snippet}")
375
}
376
})?;
377
if !status.is_success() {
378
return Err(api_error(&value).unwrap_or_else(|| format!("HTTP {status}")));
379
}
380
Ok(value)
381
}
382
383
fn api_error(value: &Value) -> Option<String> {
384
value["error"]["message"]
385
.as_str()
386
.or_else(|| value["error"].as_str())
387
.map(str::to_owned)
388
}
389
390
pub(crate) fn parse_openai(value: &Value) -> Result<ChatReply, String> {
391
if let Some(message) = api_error(value) {
392
return Err(message);
393
}
394
let message = &value["choices"][0]["message"];
395
let text = message["content"].as_str().unwrap_or("").trim().to_owned();
396
let calls = message["tool_calls"]
397
.as_array()
398
.map(|calls| {
399
calls
400
.iter()
401
.filter_map(|call| {
402
let name = call["function"]["name"].as_str()?;
403
let arguments = call["function"]["arguments"].as_str().unwrap_or("{}");
404
Some(ToolCall {
405
id: call["id"].as_str().unwrap_or(name).to_owned(),
406
name: name.to_owned(),
407
arguments: arguments.to_owned(),
408
})
409
})
410
.collect::<Vec<_>>()
411
})
412
.unwrap_or_default();
413
if calls.is_empty() {
414
if text.is_empty() {
415
return Err("the model returned an empty answer".to_owned());
416
}
417
Ok(ChatReply::Text(text))
418
} else {
419
Ok(ChatReply::Tools { text, calls })
420
}
421
}
422
423
pub(crate) fn parse_anthropic(value: &Value) -> Result<ChatReply, String> {
424
if let Some(message) = api_error(value) {
425
return Err(message);
426
}
427
let mut text = String::new();
428
let mut calls = Vec::new();
429
for block in value["content"].as_array().into_iter().flatten() {
430
match block["type"].as_str() {
431
Some("text") => {
432
if !text.is_empty() {
433
text.push('\n');
434
}
435
text.push_str(block["text"].as_str().unwrap_or(""));
436
}
437
Some("tool_use") => {
438
let name = block["name"].as_str().unwrap_or("");
439
if name.is_empty() {
440
continue;
441
}
442
let input = &block["input"];
443
calls.push(ToolCall {
444
id: block["id"].as_str().unwrap_or(name).to_owned(),
445
name: name.to_owned(),
446
arguments: input.to_string(),
447
});
448
}
449
_ => {}
450
}
451
}
452
let text = text.trim().to_owned();
453
if calls.is_empty() {
454
if text.is_empty() {
455
return Err("the model returned an empty answer".to_owned());
456
}
457
Ok(ChatReply::Text(text))
458
} else {
459
Ok(ChatReply::Tools { text, calls })
460
}
461
}
462
463
fn model_names(value: &Value) -> Vec<String> {
464
let list = value["models"]
465
.as_array()
466
.or_else(|| value["data"].as_array());
467
list.map(|models| {
468
models
469
.iter()
470
.filter_map(|model| {
471
model["name"]
472
.as_str()
473
.or_else(|| model["id"].as_str())
474
.map(str::to_owned)
475
})
476
.collect()
477
})
478
.unwrap_or_default()
479
}
480
481
#[cfg(test)]
482
mod tests {
483
use super::*;
484
485
#[test]
486
fn openai_text_and_tool_calls_parse() {
487
let text = parse_openai(&json!({
488
"choices": [{"message": {"content": " hello "}}]
489
}))
490
.unwrap();
491
assert_eq!(text, ChatReply::Text("hello".to_owned()));
492
let tools = parse_openai(&json!({
493
"choices": [{"message": {
494
"content": "",
495
"tool_calls": [{
496
"id": "c1",
497
"function": {"name": "propose_message", "arguments": "{\"text\":\"hi\"}"}
498
}]
499
}}]
500
}))
501
.unwrap();
502
assert_eq!(
503
tools,
504
ChatReply::Tools {
505
text: String::new(),
506
calls: vec![ToolCall {
507
id: "c1".to_owned(),
508
name: "propose_message".to_owned(),
509
arguments: "{\"text\":\"hi\"}".to_owned(),
510
}],
511
}
512
);
513
}
514
515
#[test]
516
fn anthropic_text_and_tool_use_parse() {
517
let text = parse_anthropic(&json!({
518
"content": [{"type": "text", "text": "done"}]
519
}))
520
.unwrap();
521
assert_eq!(text, ChatReply::Text("done".to_owned()));
522
let tools = parse_anthropic(&json!({
523
"content": [
524
{"type": "text", "text": "looking"},
525
{"type": "tool_use", "id": "t1", "name": "list_chats", "input": {"limit": 1}}
526
]
527
}))
528
.unwrap();
529
match tools {
530
ChatReply::Tools { text, calls } => {
531
assert_eq!(text, "looking");
532
assert_eq!(calls[0].name, "list_chats");
533
assert_eq!(calls[0].arguments, "{\"limit\":1}");
534
}
535
other => panic!("{other:?}"),
536
}
537
}
538
539
#[test]
540
fn model_lists_keep_ollama_names_and_openai_ids() {
541
let ollama = model_names(&json!({
542
"models": [{"name": "llama3.2:latest"}, {"name": "qwen2.5:7b"}]
543
}));
544
assert_eq!(ollama, ["llama3.2:latest", "qwen2.5:7b"]);
545
let openai = model_names(&json!({"data": [{"id": "gpt-4o"}, {"id": "gpt-4o-mini"}]}));
546
assert_eq!(openai, ["gpt-4o", "gpt-4o-mini"]);
547
let many = model_names(&json!({
548
"data": (0..12).map(|index| json!({"id": format!("m{index}")})).collect::<Vec<_>>()
549
}));
550
assert_eq!(many.len(), 12);
551
}
552
553
#[test]
554
fn ollama_models_use_the_native_tags_path() {
555
assert_eq!(
556
models_url("http://127.0.0.1:11434/v1"),
557
"http://127.0.0.1:11434/api/tags"
558
);
559
assert_eq!(
560
chat_url("http://127.0.0.1:11434/v1"),
561
"http://127.0.0.1:11434/v1/chat/completions"
562
);
563
assert_eq!(
564
chat_url("http://mac-01.lan:11434"),
565
"http://mac-01.lan:11434/v1/chat/completions"
566
);
567
}
568
}
@@ -0,0 +1,568 @@1
use serde_json::{Value, json};2
3
use crate::profile::{AgentBackend, AgentProfile};4
5
const TURN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);6
const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);7
const ANTHROPIC_VERSION: &str = "2023-06-01";8
const ANTHROPIC_URL: &str = "https://api.anthropic.com/v1/messages";9
const MAX_TOKENS: u32 = 4096;10
11
#[derive(Clone, Debug, PartialEq, Eq)]12
pub struct ToolSpec {13
pub name: String,14
pub description: String,15
pub parameters: Value,16
}17
18
#[derive(Clone, Debug, PartialEq, Eq)]19
pub struct ToolCall {20
pub id: String,21
pub name: String,22
pub arguments: String,23
}24
25
#[derive(Clone, Debug, PartialEq, Eq)]26
pub enum ChatRole {27
User,28
Assistant,29
Tool,30
}31
32
#[derive(Clone, Debug, PartialEq, Eq)]33
pub struct ChatMessage {34
pub role: ChatRole,35
pub text: String,36
pub tool_calls: Vec<ToolCall>,37
pub tool_call_id: String,38
}39
40
impl ChatMessage {41
pub fn user(text: impl Into<String>) -> Self {42
Self {43
role: ChatRole::User,44
text: text.into(),45
tool_calls: Vec::new(),46
tool_call_id: String::new(),47
}48
}49
50
pub fn assistant(text: impl Into<String>, tool_calls: Vec<ToolCall>) -> Self {51
Self {52
role: ChatRole::Assistant,53
text: text.into(),54
tool_calls,55
tool_call_id: String::new(),56
}57
}58
59
pub fn tool(id: impl Into<String>, text: impl Into<String>) -> Self {60
Self {61
role: ChatRole::Tool,62
text: text.into(),63
tool_calls: Vec::new(),64
tool_call_id: id.into(),65
}66
}67
}68
69
#[derive(Clone, Debug, PartialEq, Eq)]70
pub enum ChatReply {71
Text(String),72
Tools { text: String, calls: Vec<ToolCall> },73
}74
75
pub async fn complete_text(76
profile: &AgentProfile,77
system: &str,78
user: &str,79
) -> Result<String, String> {80
match next_turn(profile, system, &[ChatMessage::user(user)], &[]).await? {81
ChatReply::Text(text) => Ok(text),82
ChatReply::Tools { text, .. } => Ok(text),83
}84
}85
86
pub async fn next_turn(87
profile: &AgentProfile,88
system: &str,89
messages: &[ChatMessage],90
tools: &[ToolSpec],91
) -> Result<ChatReply, String> {92
let body = match &profile.backend {93
AgentBackend::OpenAi { .. } => openai_body(system, messages, tools),94
AgentBackend::Anthropic { .. } => anthropic_body(profile, system, messages, tools)?,95
AgentBackend::Command => return Err("this agent is a command, not a chat API".to_owned()),96
};97
let value = post(profile, &body).await?;98
match &profile.backend {99
AgentBackend::OpenAi { .. } => parse_openai(&value),100
AgentBackend::Anthropic { .. } => parse_anthropic(&value),101
AgentBackend::Command => unreachable!(),102
}103
}104
105
const MODEL_LIST_LIMIT: usize = 400;106
107
pub async fn list_models(profile: &AgentProfile) -> Result<Vec<String>, String> {108
let (url, key, anthropic) = models_endpoint(profile)?;109
let value = get(&key, &url, anthropic).await?;110
let mut names = model_names(&value);111
names.sort_by(|left, right| left.to_ascii_lowercase().cmp(&right.to_ascii_lowercase()));112
names.dedup();113
names.truncate(MODEL_LIST_LIMIT);114
if names.is_empty() {115
return Err("the endpoint listed no models".to_owned());116
}117
Ok(names)118
}119
120
pub async fn probe_backend(profile: &AgentProfile) -> Result<String, String> {121
let names = list_models(profile).await?;122
Ok(match names.len() {123
1 => names[0].clone(),124
2..=4 => names.join(", "),125
count => format!("{count} models"),126
})127
}128
129
fn models_endpoint(profile: &AgentProfile) -> Result<(String, String, bool), String> {130
match &profile.backend {131
AgentBackend::OpenAi {132
base_url, api_key, ..133
} => Ok((models_url(base_url), api_key.clone(), false)),134
AgentBackend::Anthropic { api_key, .. } => {135
if api_key.trim().is_empty() {136
return Err("the Anthropic key is empty".to_owned());137
}138
Ok((139
"https://api.anthropic.com/v1/models".to_owned(),140
api_key.clone(),141
true,142
))143
}144
AgentBackend::Command => Err("this agent is a command".to_owned()),145
}146
}147
148
fn openai_body(system: &str, messages: &[ChatMessage], tools: &[ToolSpec]) -> Value {149
let mut chat = Vec::new();150
if !system.is_empty() {151
chat.push(json!({"role": "system", "content": system}));152
}153
for message in messages {154
match message.role {155
ChatRole::User => chat.push(json!({"role": "user", "content": message.text})),156
ChatRole::Tool => chat.push(json!({157
"role": "tool",158
"tool_call_id": message.tool_call_id,159
"content": message.text,160
})),161
ChatRole::Assistant => {162
let mut row = json!({"role": "assistant", "content": message.text});163
if !message.tool_calls.is_empty() {164
row["tool_calls"] = Value::Array(165
message166
.tool_calls167
.iter()168
.map(|call| {169
json!({170
"id": call.id,171
"type": "function",172
"function": { "name": call.name, "arguments": call.arguments },173
})174
})175
.collect(),176
);177
}178
chat.push(row);179
}180
}181
}182
let mut body = json!({"messages": chat, "stream": false});183
if !tools.is_empty() {184
body["tools"] = Value::Array(185
tools186
.iter()187
.map(|tool| {188
json!({189
"type": "function",190
"function": {191
"name": tool.name,192
"description": tool.description,193
"parameters": tool.parameters,194
}195
})196
})197
.collect(),198
);199
}200
body201
}202
203
fn anthropic_body(204
profile: &AgentProfile,205
system: &str,206
messages: &[ChatMessage],207
tools: &[ToolSpec],208
) -> Result<Value, String> {209
let AgentBackend::Anthropic { model, .. } = &profile.backend else {210
return Err("not an Anthropic profile".to_owned());211
};212
let mut chat = Vec::new();213
for message in messages {214
match message.role {215
ChatRole::User => chat.push(json!({"role": "user", "content": message.text})),216
ChatRole::Tool => chat.push(json!({217
"role": "user",218
"content": [{219
"type": "tool_result",220
"tool_use_id": message.tool_call_id,221
"content": message.text,222
}]223
})),224
ChatRole::Assistant => {225
let mut content = Vec::new();226
if !message.text.is_empty() {227
content.push(json!({"type": "text", "text": message.text}));228
}229
for call in &message.tool_calls {230
let input = serde_json::from_str::<Value>(&call.arguments)231
.unwrap_or(Value::Object(Default::default()));232
content.push(json!({233
"type": "tool_use",234
"id": call.id,235
"name": call.name,236
"input": input,237
}));238
}239
chat.push(json!({"role": "assistant", "content": content}));240
}241
}242
}243
let mut body = json!({244
"model": model,245
"max_tokens": MAX_TOKENS,246
"messages": chat,247
});248
if !system.is_empty() {249
body["system"] = Value::String(system.to_owned());250
}251
if !tools.is_empty() {252
body["tools"] = Value::Array(253
tools254
.iter()255
.map(|tool| {256
json!({257
"name": tool.name,258
"description": tool.description,259
"input_schema": tool.parameters,260
})261
})262
.collect(),263
);264
}265
Ok(body)266
}267
268
fn chat_url(base_url: &str) -> String {269
let base = base_url.trim().trim_end_matches('/');270
if base.ends_with("/chat/completions") {271
return base.to_owned();272
}273
// Ollama answers the OpenAI route only under /v1. The model list also274
// accepts the bare port, so a base without /v1 still has to land there.275
if base.contains(":11434") {276
let origin = base.strip_suffix("/v1").unwrap_or(base);277
return format!("{origin}/v1/chat/completions");278
}279
format!("{base}/chat/completions")280
}281
282
fn models_url(base_url: &str) -> String {283
let base = base_url.trim().trim_end_matches('/');284
if base.contains(":11434") {285
let origin = base.trim_end_matches("/v1");286
format!("{origin}/api/tags")287
} else {288
format!("{base}/models")289
}290
}291
292
async fn post(profile: &AgentProfile, body: &Value) -> Result<Value, String> {293
let (url, key, anthropic, model) = endpoint(profile)?;294
let mut payload = body.clone();295
if !anthropic {296
payload["model"] = Value::String(model);297
}298
let client = client(TURN_TIMEOUT)?;299
let mut request = client.post(url).json(&payload);300
request = authorize(request, &key, anthropic);301
read_json(request).await302
}303
304
async fn get(key: &str, url: &str, anthropic: bool) -> Result<Value, String> {305
let client = client(PROBE_TIMEOUT)?;306
let request = authorize(client.get(url), key, anthropic);307
read_json(request).await308
}309
310
fn endpoint(profile: &AgentProfile) -> Result<(String, String, bool, String), String> {311
match &profile.backend {312
AgentBackend::OpenAi {313
base_url,314
model,315
api_key,316
} => {317
if model.trim().is_empty() {318
return Err("choose a model first".to_owned());319
}320
Ok((chat_url(base_url), api_key.clone(), false, model.clone()))321
}322
AgentBackend::Anthropic { model, api_key } => {323
if api_key.trim().is_empty() {324
return Err("the Anthropic key is empty".to_owned());325
}326
if model.trim().is_empty() {327
return Err("choose a model first".to_owned());328
}329
Ok((330
ANTHROPIC_URL.to_owned(),331
api_key.clone(),332
true,333
model.clone(),334
))335
}336
AgentBackend::Command => Err("this agent is a command".to_owned()),337
}338
}339
340
fn client(timeout: std::time::Duration) -> Result<reqwest::Client, String> {341
reqwest::Client::builder()342
.timeout(timeout)343
.build()344
.map_err(|error| error.to_string())345
}346
347
fn authorize(348
request: reqwest::RequestBuilder,349
key: &str,350
anthropic: bool,351
) -> reqwest::RequestBuilder {352
if anthropic {353
return request354
.header("x-api-key", key)355
.header("anthropic-version", ANTHROPIC_VERSION);356
}357
if key.trim().is_empty() {358
request359
} else {360
request.bearer_auth(key)361
}362
}363
364
async fn read_json(request: reqwest::RequestBuilder) -> Result<Value, String> {365
let response = request.send().await.map_err(|error| error.to_string())?;366
let status = response.status();367
let bytes = response.bytes().await.map_err(|error| error.to_string())?;368
let value: Value = serde_json::from_slice(&bytes).map_err(|_| {369
let body = String::from_utf8_lossy(&bytes);370
let snippet: String = body.trim().chars().take(180).collect();371
if snippet.is_empty() {372
format!("HTTP {status} with an empty body")373
} else {374
format!("HTTP {status}: {snippet}")375
}376
})?;377
if !status.is_success() {378
return Err(api_error(&value).unwrap_or_else(|| format!("HTTP {status}")));379
}380
Ok(value)381
}382
383
fn api_error(value: &Value) -> Option<String> {384
value["error"]["message"]385
.as_str()386
.or_else(|| value["error"].as_str())387
.map(str::to_owned)388
}389
390
pub(crate) fn parse_openai(value: &Value) -> Result<ChatReply, String> {391
if let Some(message) = api_error(value) {392
return Err(message);393
}394
let message = &value["choices"][0]["message"];395
let text = message["content"].as_str().unwrap_or("").trim().to_owned();396
let calls = message["tool_calls"]397
.as_array()398
.map(|calls| {399
calls400
.iter()401
.filter_map(|call| {402
let name = call["function"]["name"].as_str()?;403
let arguments = call["function"]["arguments"].as_str().unwrap_or("{}");404
Some(ToolCall {405
id: call["id"].as_str().unwrap_or(name).to_owned(),406
name: name.to_owned(),407
arguments: arguments.to_owned(),408
})409
})410
.collect::<Vec<_>>()411
})412
.unwrap_or_default();413
if calls.is_empty() {414
if text.is_empty() {415
return Err("the model returned an empty answer".to_owned());416
}417
Ok(ChatReply::Text(text))418
} else {419
Ok(ChatReply::Tools { text, calls })420
}421
}422
423
pub(crate) fn parse_anthropic(value: &Value) -> Result<ChatReply, String> {424
if let Some(message) = api_error(value) {425
return Err(message);426
}427
let mut text = String::new();428
let mut calls = Vec::new();429
for block in value["content"].as_array().into_iter().flatten() {430
match block["type"].as_str() {431
Some("text") => {432
if !text.is_empty() {433
text.push('\n');434
}435
text.push_str(block["text"].as_str().unwrap_or(""));436
}437
Some("tool_use") => {438
let name = block["name"].as_str().unwrap_or("");439
if name.is_empty() {440
continue;441
}442
let input = &block["input"];443
calls.push(ToolCall {444
id: block["id"].as_str().unwrap_or(name).to_owned(),445
name: name.to_owned(),446
arguments: input.to_string(),447
});448
}449
_ => {}450
}451
}452
let text = text.trim().to_owned();453
if calls.is_empty() {454
if text.is_empty() {455
return Err("the model returned an empty answer".to_owned());456
}457
Ok(ChatReply::Text(text))458
} else {459
Ok(ChatReply::Tools { text, calls })460
}461
}462
463
fn model_names(value: &Value) -> Vec<String> {464
let list = value["models"]465
.as_array()466
.or_else(|| value["data"].as_array());467
list.map(|models| {468
models469
.iter()470
.filter_map(|model| {471
model["name"]472
.as_str()473
.or_else(|| model["id"].as_str())474
.map(str::to_owned)475
})476
.collect()477
})478
.unwrap_or_default()479
}480
481
#[cfg(test)]482
mod tests {483
use super::*;484
485
#[test]486
fn openai_text_and_tool_calls_parse() {487
let text = parse_openai(&json!({488
"choices": [{"message": {"content": " hello "}}]489
}))490
.unwrap();491
assert_eq!(text, ChatReply::Text("hello".to_owned()));492
let tools = parse_openai(&json!({493
"choices": [{"message": {494
"content": "",495
"tool_calls": [{496
"id": "c1",497
"function": {"name": "propose_message", "arguments": "{\"text\":\"hi\"}"}498
}]499
}}]500
}))501
.unwrap();502
assert_eq!(503
tools,504
ChatReply::Tools {505
text: String::new(),506
calls: vec![ToolCall {507
id: "c1".to_owned(),508
name: "propose_message".to_owned(),509
arguments: "{\"text\":\"hi\"}".to_owned(),510
}],511
}512
);513
}514
515
#[test]516
fn anthropic_text_and_tool_use_parse() {517
let text = parse_anthropic(&json!({518
"content": [{"type": "text", "text": "done"}]519
}))520
.unwrap();521
assert_eq!(text, ChatReply::Text("done".to_owned()));522
let tools = parse_anthropic(&json!({523
"content": [524
{"type": "text", "text": "looking"},525
{"type": "tool_use", "id": "t1", "name": "list_chats", "input": {"limit": 1}}526
]527
}))528
.unwrap();529
match tools {530
ChatReply::Tools { text, calls } => {531
assert_eq!(text, "looking");532
assert_eq!(calls[0].name, "list_chats");533
assert_eq!(calls[0].arguments, "{\"limit\":1}");534
}535
other => panic!("{other:?}"),536
}537
}538
539
#[test]540
fn model_lists_keep_ollama_names_and_openai_ids() {541
let ollama = model_names(&json!({542
"models": [{"name": "llama3.2:latest"}, {"name": "qwen2.5:7b"}]543
}));544
assert_eq!(ollama, ["llama3.2:latest", "qwen2.5:7b"]);545
let openai = model_names(&json!({"data": [{"id": "gpt-4o"}, {"id": "gpt-4o-mini"}]}));546
assert_eq!(openai, ["gpt-4o", "gpt-4o-mini"]);547
let many = model_names(&json!({548
"data": (0..12).map(|index| json!({"id": format!("m{index}")})).collect::<Vec<_>>()549
}));550
assert_eq!(many.len(), 12);551
}552
553
#[test]554
fn ollama_models_use_the_native_tags_path() {555
assert_eq!(556
models_url("http://127.0.0.1:11434/v1"),557
"http://127.0.0.1:11434/api/tags"558
);559
assert_eq!(560
chat_url("http://127.0.0.1:11434/v1"),561
"http://127.0.0.1:11434/v1/chat/completions"562
);563
assert_eq!(564
chat_url("http://mac-01.lan:11434"),565
"http://mac-01.lan:11434/v1/chat/completions"566
);567
}568
}@@ -287,7 +287,7 @@ pub fn kill_process_invocation(process_id: u32, session_id: &str) -> Option<Invo
287
287
}
288
288
289
289
pub fn supports_resume(profile: &AgentProfile) -> bool {
290
profile.command.contains(SESSION_FLAG)
290
profile.is_command() && profile.command.contains(SESSION_FLAG)
291
291
}
292
292
293
293
pub fn resume_invocation(
@@ -287,7 +287,7 @@ pub fn kill_process_invocation(process_id: u32, session_id: &str) -> Option<Invo287
}287
}288
288
289
pub fn supports_resume(profile: &AgentProfile) -> bool {289
pub fn supports_resume(profile: &AgentProfile) -> bool {290
profile.command.contains(SESSION_FLAG)290
profile.is_command() && profile.command.contains(SESSION_FLAG)291
}291
}292
292
293
pub fn resume_invocation(293
pub fn resume_invocation(@@ -1,4 +1,6 @@
1
1
mod action;
2
mod catalog;
3
mod chat;
2
4
mod context;
3
5
mod desktop_sessions;
4
6
mod inbox;
@@ -11,6 +13,11 @@ mod settings;
11
13
mod template;
12
14
13
15
pub use action::AgentAction;
16
pub use catalog::{CliHit, already_installed, resolve_program, scan_clis};
17
pub use chat::{
18
ChatMessage, ChatReply, ToolCall, ToolSpec, complete_text, list_models, next_turn,
19
probe_backend,
20
};
14
21
pub use context::{MessageContext, ThreadMessage, build_prompt, build_session_prompt};
15
22
pub use desktop_sessions::{DesktopSession, desktop_sessions};
16
23
pub use inbox::{DeliveryError, deliver, inbox_frame};
@@ -20,7 +27,7 @@ pub use invocation::{
20
27
version_check_invocation, wsl_path, wsl_stop_invocation, wsl_unc_distro,
21
28
};
22
29
pub use parse::{OutputParser, RunEvent, parse_line};
23
pub use profile::{AgentProfile, Environment, OutputFormat};
30
pub use profile::{AgentBackend, AgentProfile, Environment, OutputFormat};
24
31
pub use runner::{
25
32
RunOutcome, RunStatus, RunUpdate, probe, run, run_stop_invocation, run_stop_invocation_within,
26
33
};
@@ -1,4 +1,6 @@1
mod action;1
mod action;2
mod catalog;3
mod chat;2
mod context;4
mod context;3
mod desktop_sessions;5
mod desktop_sessions;4
mod inbox;6
mod inbox;@@ -11,6 +13,11 @@ mod settings;11
mod template;13
mod template;12
14
13
pub use action::AgentAction;15
pub use action::AgentAction;16
pub use catalog::{CliHit, already_installed, resolve_program, scan_clis};17
pub use chat::{18
ChatMessage, ChatReply, ToolCall, ToolSpec, complete_text, list_models, next_turn,19
probe_backend,20
};14
pub use context::{MessageContext, ThreadMessage, build_prompt, build_session_prompt};21
pub use context::{MessageContext, ThreadMessage, build_prompt, build_session_prompt};15
pub use desktop_sessions::{DesktopSession, desktop_sessions};22
pub use desktop_sessions::{DesktopSession, desktop_sessions};16
pub use inbox::{DeliveryError, deliver, inbox_frame};23
pub use inbox::{DeliveryError, deliver, inbox_frame};@@ -20,7 +27,7 @@ pub use invocation::{20
version_check_invocation, wsl_path, wsl_stop_invocation, wsl_unc_distro,27
version_check_invocation, wsl_path, wsl_stop_invocation, wsl_unc_distro,21
};28
};22
pub use parse::{OutputParser, RunEvent, parse_line};29
pub use parse::{OutputParser, RunEvent, parse_line};23
pub use profile::{AgentProfile, Environment, OutputFormat};30
pub use profile::{AgentBackend, AgentProfile, Environment, OutputFormat};24
pub use runner::{31
pub use runner::{25
RunOutcome, RunStatus, RunUpdate, probe, run, run_stop_invocation, run_stop_invocation_within,32
RunOutcome, RunStatus, RunUpdate, probe, run, run_stop_invocation, run_stop_invocation_within,26
};33
};@@ -29,6 +29,25 @@ pub enum OutputFormat {
29
29
Text,
30
30
}
31
31
32
/// Where a run is answered. Missing JSON stays a command, so older settings keep working.
33
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
34
#[serde(tag = "type", rename_all = "snake_case")]
35
pub enum AgentBackend {
36
#[default]
37
Command,
38
OpenAi {
39
base_url: String,
40
model: String,
41
#[serde(default)]
42
api_key: String,
43
},
44
Anthropic {
45
model: String,
46
#[serde(default)]
47
api_key: String,
48
},
49
}
50
32
51
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
33
52
#[serde(default)]
34
53
pub struct AgentProfile {
@@ -39,9 +58,38 @@ pub struct AgentProfile {
39
58
pub output: OutputFormat,
40
59
pub open_session_command: String,
41
60
pub mcp_config_flag: String,
61
pub backend: AgentBackend,
42
62
}
43
63
44
64
impl AgentProfile {
65
pub fn is_command(&self) -> bool {
66
matches!(self.backend, AgentBackend::Command)
67
}
68
69
pub fn is_chat(&self) -> bool {
70
!self.is_command()
71
}
72
73
pub fn backend_label(&self) -> String {
74
match &self.backend {
75
AgentBackend::Command => String::new(),
76
AgentBackend::OpenAi {
77
base_url, model, ..
78
} => {
79
let model = if model.is_empty() { "no model" } else { model };
80
format!("{model} · {base_url}")
81
}
82
AgentBackend::Anthropic { model, .. } => {
83
let model = if model.is_empty() { "no model" } else { model };
84
format!("Anthropic · {model}")
85
}
86
}
87
}
88
89
pub fn command_program(&self) -> &str {
90
self.command.split_whitespace().next().unwrap_or("")
91
}
92
45
93
pub(crate) fn migrate_open_session_command(&mut self) {
46
94
let replacement = match self.open_session_command.as_str() {
47
95
LEGACY_CLAUDE_WSL_OPEN_SESSION => CLAUDE_WSL_OPEN_SESSION,
@@ -60,6 +108,7 @@ impl AgentProfile {
60
108
output: OutputFormat::ClaudeStreamJson,
61
109
open_session_command: CLAUDE_WSL_OPEN_SESSION.to_string(),
62
110
mcp_config_flag: "--mcp-config".to_string(),
111
backend: AgentBackend::Command,
63
112
}
64
113
}
65
114
@@ -72,6 +121,112 @@ impl AgentProfile {
72
121
output: OutputFormat::ClaudeStreamJson,
73
122
open_session_command: "wt.exe -d {cwd} claude --resume {session_id}".to_string(),
74
123
mcp_config_flag: "--mcp-config".to_string(),
124
backend: AgentBackend::Command,
125
}
126
}
127
128
pub fn copilot_host() -> Self {
129
Self {
130
id: "copilot-host".to_string(),
131
name: "Copilot CLI".to_string(),
132
environment: Environment::Host,
133
command: COPILOT_COMMAND.to_string(),
134
output: OutputFormat::CopilotJsonl,
135
open_session_command: "wt.exe -d {cwd} copilot --resume {session_id}".to_string(),
136
mcp_config_flag: "--additional-mcp-config".to_string(),
137
backend: AgentBackend::Command,
138
}
139
}
140
141
pub fn codex_host() -> Self {
142
Self {
143
id: "codex".to_string(),
144
name: "Codex CLI".to_string(),
145
environment: Environment::Host,
146
command: "codex exec --skip-git-repo-check {prompt}".to_string(),
147
output: OutputFormat::Text,
148
..Self::default()
149
}
150
}
151
152
pub fn cursor_host() -> Self {
153
Self {
154
id: "cursor".to_string(),
155
name: "Cursor CLI".to_string(),
156
environment: Environment::Host,
157
command: "agent -p --trust --approve-mcps {prompt}".to_string(),
158
output: OutputFormat::Text,
159
..Self::default()
160
}
161
}
162
163
pub fn agy_host() -> Self {
164
Self {
165
id: "agy".to_string(),
166
name: "Antigravity CLI".to_string(),
167
environment: Environment::Host,
168
command: "agy -p {prompt}".to_string(),
169
output: OutputFormat::Text,
170
..Self::default()
171
}
172
}
173
174
pub fn ollama() -> Self {
175
Self::open_ai("ollama", "Ollama", "http://127.0.0.1:11434/v1", "", "")
176
}
177
178
pub fn openai() -> Self {
179
Self::open_ai(
180
"openai",
181
"OpenAI",
182
"https://api.openai.com/v1",
183
"gpt-4o",
184
"",
185
)
186
}
187
188
pub fn openrouter() -> Self {
189
Self::open_ai(
190
"openrouter",
191
"OpenRouter",
192
"https://openrouter.ai/api/v1",
193
"openrouter/auto",
194
"",
195
)
196
}
197
198
pub fn openai_compatible() -> Self {
199
Self::open_ai(
200
"openai-compatible",
201
"OpenAI-compatible",
202
"http://127.0.0.1:8080/v1",
203
"",
204
"",
205
)
206
}
207
208
pub fn anthropic() -> Self {
209
Self {
210
id: "anthropic".to_string(),
211
name: "Anthropic".to_string(),
212
backend: AgentBackend::Anthropic {
213
model: "claude-sonnet-4-5".to_string(),
214
api_key: String::new(),
215
},
216
..Self::default()
217
}
218
}
219
220
fn open_ai(id: &str, name: &str, base_url: &str, model: &str, api_key: &str) -> Self {
221
Self {
222
id: id.to_string(),
223
name: name.to_string(),
224
backend: AgentBackend::OpenAi {
225
base_url: base_url.to_string(),
226
model: model.to_string(),
227
api_key: api_key.to_string(),
228
},
229
..Self::default()
75
230
}
76
231
}
77
232
@@ -84,6 +239,7 @@ impl AgentProfile {
84
239
output: OutputFormat::CopilotJsonl,
85
240
open_session_command: COPILOT_WSL_OPEN_SESSION.to_string(),
86
241
mcp_config_flag: "--additional-mcp-config".to_string(),
242
backend: AgentBackend::Command,
87
243
}
88
244
}
89
245
}
@@ -29,6 +29,25 @@ pub enum OutputFormat {29
Text,29
Text,30
}30
}31
31
32
/// Where a run is answered. Missing JSON stays a command, so older settings keep working.33
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]34
#[serde(tag = "type", rename_all = "snake_case")]35
pub enum AgentBackend {36
#[default]37
Command,38
OpenAi {39
base_url: String,40
model: String,41
#[serde(default)]42
api_key: String,43
},44
Anthropic {45
model: String,46
#[serde(default)]47
api_key: String,48
},49
}50
32
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]51
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]33
#[serde(default)]52
#[serde(default)]34
pub struct AgentProfile {53
pub struct AgentProfile {@@ -39,9 +58,38 @@ pub struct AgentProfile {39
pub output: OutputFormat,58
pub output: OutputFormat,40
pub open_session_command: String,59
pub open_session_command: String,41
pub mcp_config_flag: String,60
pub mcp_config_flag: String,61
pub backend: AgentBackend,42
}62
}43
63
44
impl AgentProfile {64
impl AgentProfile {65
pub fn is_command(&self) -> bool {66
matches!(self.backend, AgentBackend::Command)67
}68
69
pub fn is_chat(&self) -> bool {70
!self.is_command()71
}72
73
pub fn backend_label(&self) -> String {74
match &self.backend {75
AgentBackend::Command => String::new(),76
AgentBackend::OpenAi {77
base_url, model, ..78
} => {79
let model = if model.is_empty() { "no model" } else { model };80
format!("{model} · {base_url}")81
}82
AgentBackend::Anthropic { model, .. } => {83
let model = if model.is_empty() { "no model" } else { model };84
format!("Anthropic · {model}")85
}86
}87
}88
89
pub fn command_program(&self) -> &str {90
self.command.split_whitespace().next().unwrap_or("")91
}92
45
pub(crate) fn migrate_open_session_command(&mut self) {93
pub(crate) fn migrate_open_session_command(&mut self) {46
let replacement = match self.open_session_command.as_str() {94
let replacement = match self.open_session_command.as_str() {47
LEGACY_CLAUDE_WSL_OPEN_SESSION => CLAUDE_WSL_OPEN_SESSION,95
LEGACY_CLAUDE_WSL_OPEN_SESSION => CLAUDE_WSL_OPEN_SESSION,@@ -60,6 +108,7 @@ impl AgentProfile {60
output: OutputFormat::ClaudeStreamJson,108
output: OutputFormat::ClaudeStreamJson,61
open_session_command: CLAUDE_WSL_OPEN_SESSION.to_string(),109
open_session_command: CLAUDE_WSL_OPEN_SESSION.to_string(),62
mcp_config_flag: "--mcp-config".to_string(),110
mcp_config_flag: "--mcp-config".to_string(),111
backend: AgentBackend::Command,63
}112
}64
}113
}65
114
@@ -72,6 +121,112 @@ impl AgentProfile {72
output: OutputFormat::ClaudeStreamJson,121
output: OutputFormat::ClaudeStreamJson,73
open_session_command: "wt.exe -d {cwd} claude --resume {session_id}".to_string(),122
open_session_command: "wt.exe -d {cwd} claude --resume {session_id}".to_string(),74
mcp_config_flag: "--mcp-config".to_string(),123
mcp_config_flag: "--mcp-config".to_string(),124
backend: AgentBackend::Command,125
}126
}127
128
pub fn copilot_host() -> Self {129
Self {130
id: "copilot-host".to_string(),131
name: "Copilot CLI".to_string(),132
environment: Environment::Host,133
command: COPILOT_COMMAND.to_string(),134
output: OutputFormat::CopilotJsonl,135
open_session_command: "wt.exe -d {cwd} copilot --resume {session_id}".to_string(),136
mcp_config_flag: "--additional-mcp-config".to_string(),137
backend: AgentBackend::Command,138
}139
}140
141
pub fn codex_host() -> Self {142
Self {143
id: "codex".to_string(),144
name: "Codex CLI".to_string(),145
environment: Environment::Host,146
command: "codex exec --skip-git-repo-check {prompt}".to_string(),147
output: OutputFormat::Text,148
..Self::default()149
}150
}151
152
pub fn cursor_host() -> Self {153
Self {154
id: "cursor".to_string(),155
name: "Cursor CLI".to_string(),156
environment: Environment::Host,157
command: "agent -p --trust --approve-mcps {prompt}".to_string(),158
output: OutputFormat::Text,159
..Self::default()160
}161
}162
163
pub fn agy_host() -> Self {164
Self {165
id: "agy".to_string(),166
name: "Antigravity CLI".to_string(),167
environment: Environment::Host,168
command: "agy -p {prompt}".to_string(),169
output: OutputFormat::Text,170
..Self::default()171
}172
}173
174
pub fn ollama() -> Self {175
Self::open_ai("ollama", "Ollama", "http://127.0.0.1:11434/v1", "", "")176
}177
178
pub fn openai() -> Self {179
Self::open_ai(180
"openai",181
"OpenAI",182
"https://api.openai.com/v1",183
"gpt-4o",184
"",185
)186
}187
188
pub fn openrouter() -> Self {189
Self::open_ai(190
"openrouter",191
"OpenRouter",192
"https://openrouter.ai/api/v1",193
"openrouter/auto",194
"",195
)196
}197
198
pub fn openai_compatible() -> Self {199
Self::open_ai(200
"openai-compatible",201
"OpenAI-compatible",202
"http://127.0.0.1:8080/v1",203
"",204
"",205
)206
}207
208
pub fn anthropic() -> Self {209
Self {210
id: "anthropic".to_string(),211
name: "Anthropic".to_string(),212
backend: AgentBackend::Anthropic {213
model: "claude-sonnet-4-5".to_string(),214
api_key: String::new(),215
},216
..Self::default()217
}218
}219
220
fn open_ai(id: &str, name: &str, base_url: &str, model: &str, api_key: &str) -> Self {221
Self {222
id: id.to_string(),223
name: name.to_string(),224
backend: AgentBackend::OpenAi {225
base_url: base_url.to_string(),226
model: model.to_string(),227
api_key: api_key.to_string(),228
},229
..Self::default()75
}230
}76
}231
}77
232
@@ -84,6 +239,7 @@ impl AgentProfile {84
output: OutputFormat::CopilotJsonl,239
output: OutputFormat::CopilotJsonl,85
open_session_command: COPILOT_WSL_OPEN_SESSION.to_string(),240
open_session_command: COPILOT_WSL_OPEN_SESSION.to_string(),86
mcp_config_flag: "--additional-mcp-config".to_string(),241
mcp_config_flag: "--additional-mcp-config".to_string(),242
backend: AgentBackend::Command,87
}243
}88
}244
}89
}245
}@@ -1,4 +1,5 @@
1
1
use std::collections::VecDeque;
2
use std::path::PathBuf;
2
3
use std::process::Stdio;
3
4
use std::sync::{Arc, Mutex};
4
5
@@ -40,17 +41,37 @@ pub struct RunOutcome {
40
41
}
41
42
42
43
fn command_for(invocation: &Invocation) -> Command {
43
let mut command = Command::new(&invocation.program);
44
let program = crate::catalog::resolve_program(&invocation.program)
45
.unwrap_or_else(|| PathBuf::from(&invocation.program));
46
let mut command = Command::new(program);
44
47
command.args(&invocation.args);
45
48
if let Some(cwd) = &invocation.cwd {
46
49
command.current_dir(cwd);
47
50
}
51
prepend_user_bin(&mut command);
48
52
command.kill_on_drop(true);
49
53
#[cfg(windows)]
50
54
command.creation_flags(0x0800_0000);
51
55
command
52
56
}
53
57
58
fn prepend_user_bin(command: &mut Command) {
59
let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) else {
60
return;
61
};
62
let bin = PathBuf::from(home).join(".local").join("bin");
63
if !bin.is_dir() {
64
return;
65
}
66
let mut paths = vec![bin];
67
if let Some(path) = std::env::var_os("PATH") {
68
paths.extend(std::env::split_paths(&path));
69
}
70
if let Ok(joined) = std::env::join_paths(paths) {
71
command.env("PATH", joined);
72
}
73
}
74
54
75
#[cfg(windows)]
55
76
fn taskkill_tree(process_id: u32) -> Invocation {
56
77
Invocation {
@@ -1,4 +1,5 @@1
use std::collections::VecDeque;1
use std::collections::VecDeque;2
use std::path::PathBuf;2
use std::process::Stdio;3
use std::process::Stdio;3
use std::sync::{Arc, Mutex};4
use std::sync::{Arc, Mutex};4
5
@@ -40,17 +41,37 @@ pub struct RunOutcome {40
}41
}41
42
42
fn command_for(invocation: &Invocation) -> Command {43
fn command_for(invocation: &Invocation) -> Command {43
let mut command = Command::new(&invocation.program);44
let program = crate::catalog::resolve_program(&invocation.program)45
.unwrap_or_else(|| PathBuf::from(&invocation.program));46
let mut command = Command::new(program);44
command.args(&invocation.args);47
command.args(&invocation.args);45
if let Some(cwd) = &invocation.cwd {48
if let Some(cwd) = &invocation.cwd {46
command.current_dir(cwd);49
command.current_dir(cwd);47
}50
}51
prepend_user_bin(&mut command);48
command.kill_on_drop(true);52
command.kill_on_drop(true);49
#[cfg(windows)]53
#[cfg(windows)]50
command.creation_flags(0x0800_0000);54
command.creation_flags(0x0800_0000);51
command55
command52
}56
}53
57
58
fn prepend_user_bin(command: &mut Command) {59
let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) else {60
return;61
};62
let bin = PathBuf::from(home).join(".local").join("bin");63
if !bin.is_dir() {64
return;65
}66
let mut paths = vec![bin];67
if let Some(path) = std::env::var_os("PATH") {68
paths.extend(std::env::split_paths(&path));69
}70
if let Ok(joined) = std::env::join_paths(paths) {71
command.env("PATH", joined);72
}73
}74
54
#[cfg(windows)]75
#[cfg(windows)]55
fn taskkill_tree(process_id: u32) -> Invocation {76
fn taskkill_tree(process_id: u32) -> Invocation {56
Invocation {77
Invocation {@@ -3,7 +3,7 @@ use std::collections::HashMap;
3
3
use serde::{Deserialize, Serialize};
4
4
5
5
use crate::action::AgentAction;
6
use crate::profile::AgentProfile;
6
use crate::profile::{AgentBackend, AgentProfile};
7
7
use crate::template::{is_known_placeholder, placeholders_in};
8
8
9
9
pub const SETTINGS_KEY: &str = "agents.settings";
@@ -20,6 +20,8 @@ pub enum SettingsProblem {
20
20
item_id: String,
21
21
placeholder: String,
22
22
},
23
#[error("agent {agent_id} has an empty model")]
24
EmptyModel { agent_id: String },
23
25
}
24
26
25
27
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -29,6 +31,8 @@ pub struct AgentSettings {
29
31
pub actions: Vec<AgentAction>,
30
32
pub resume_interrupted_runs: bool,
31
33
pub recent_working_dirs: HashMap<String, Vec<String>>,
34
/// Empty means Microsoft Copilot. Otherwise the id of a chat profile.
35
pub write_with: String,
32
36
}
33
37
34
38
impl Default for AgentSettings {
@@ -41,6 +45,7 @@ impl Default for AgentSettings {
41
45
],
42
46
resume_interrupted_runs: true,
43
47
recent_working_dirs: HashMap::new(),
48
write_with: String::new(),
44
49
}
45
50
}
46
51
}
@@ -59,6 +64,16 @@ fn check_placeholders(item_id: &str, texts: &[&str], problems: &mut Vec<Settings
59
64
}
60
65
61
66
impl AgentSettings {
67
/// Chat profile chosen under «Write with», or `None` for Microsoft Copilot.
68
pub fn write_with_profile(&self) -> Option<&AgentProfile> {
69
if self.write_with.is_empty() {
70
return None;
71
}
72
self.agents
73
.iter()
74
.find(|agent| agent.id == self.write_with && agent.is_chat())
75
}
76
62
77
pub fn to_json(&self) -> String {
63
78
serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string())
64
79
}
@@ -90,11 +105,22 @@ impl AgentSettings {
90
105
pub fn validate(&self) -> Vec<SettingsProblem> {
91
106
let mut problems = Vec::new();
92
107
for agent in &self.agents {
93
if agent.command.trim().is_empty() {
108
if agent.is_command() && agent.command.trim().is_empty() {
94
109
problems.push(SettingsProblem::EmptyCommand {
95
110
agent_id: agent.id.clone(),
96
111
});
97
112
}
113
let model = match &agent.backend {
114
AgentBackend::OpenAi { model, .. } | AgentBackend::Anthropic { model, .. } => {
115
model.as_str()
116
}
117
AgentBackend::Command => "",
118
};
119
if agent.is_chat() && model.trim().is_empty() {
120
problems.push(SettingsProblem::EmptyModel {
121
agent_id: agent.id.clone(),
122
});
123
}
98
124
check_placeholders(
99
125
&agent.id,
100
126
&[&agent.command, &agent.open_session_command],
@@ -235,4 +261,55 @@ mod tests {
235
261
placeholder: "nope".to_string(),
236
262
}));
237
263
}
264
265
#[test]
266
fn a_profile_without_backend_stays_a_command() {
267
let loaded = AgentSettings::from_json(
268
r#"{"agents":[{"id":"legacy","name":"Legacy","command":"claude -p"}]}"#,
269
)
270
.unwrap();
271
assert!(loaded.agents[0].is_command());
272
assert!(loaded.write_with.is_empty());
273
}
274
275
#[test]
276
fn chat_profiles_need_a_model_and_write_with_round_trips() {
277
let mut settings = AgentSettings::default();
278
settings.agents.push(AgentProfile::ollama());
279
assert!(settings.validate().contains(&SettingsProblem::EmptyModel {
280
agent_id: "ollama".to_string(),
281
}));
282
settings.agents.last_mut().unwrap().backend = AgentBackend::OpenAi {
283
base_url: "http://127.0.0.1:11434/v1".to_owned(),
284
model: "qwen3.5:9b".to_owned(),
285
api_key: String::new(),
286
};
287
settings.write_with = "ollama".to_owned();
288
let loaded = AgentSettings::from_json(&settings.to_json()).unwrap();
289
assert_eq!(loaded.write_with, "ollama");
290
assert!(loaded.validate().is_empty());
291
}
292
293
#[test]
294
fn write_with_profile_is_none_for_microsoft_and_missing_ids() {
295
let mut settings = AgentSettings::default();
296
assert!(settings.write_with_profile().is_none());
297
settings.write_with = "missing".to_owned();
298
assert!(settings.write_with_profile().is_none());
299
settings.agents.push(AgentProfile::ollama());
300
settings.agents.last_mut().unwrap().backend = AgentBackend::OpenAi {
301
base_url: "http://127.0.0.1:11434/v1".to_owned(),
302
model: "qwen3.5:9b".to_owned(),
303
api_key: String::new(),
304
};
305
settings.write_with = "ollama".to_owned();
306
assert_eq!(
307
settings
308
.write_with_profile()
309
.map(|profile| profile.name.as_str()),
310
Some("Ollama")
311
);
312
settings.write_with = "claude".to_owned();
313
assert!(settings.write_with_profile().is_none());
314
}
238
315
}
@@ -3,7 +3,7 @@ use std::collections::HashMap;3
use serde::{Deserialize, Serialize};3
use serde::{Deserialize, Serialize};4
4
5
use crate::action::AgentAction;5
use crate::action::AgentAction;6
use crate::profile::AgentProfile;6
use crate::profile::{AgentBackend, AgentProfile};7
use crate::template::{is_known_placeholder, placeholders_in};7
use crate::template::{is_known_placeholder, placeholders_in};8
8
9
pub const SETTINGS_KEY: &str = "agents.settings";9
pub const SETTINGS_KEY: &str = "agents.settings";@@ -20,6 +20,8 @@ pub enum SettingsProblem {20
item_id: String,20
item_id: String,21
placeholder: String,21
placeholder: String,22
},22
},23
#[error("agent {agent_id} has an empty model")]24
EmptyModel { agent_id: String },23
}25
}24
26
25
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]27
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]@@ -29,6 +31,8 @@ pub struct AgentSettings {29
pub actions: Vec<AgentAction>,31
pub actions: Vec<AgentAction>,30
pub resume_interrupted_runs: bool,32
pub resume_interrupted_runs: bool,31
pub recent_working_dirs: HashMap<String, Vec<String>>,33
pub recent_working_dirs: HashMap<String, Vec<String>>,34
/// Empty means Microsoft Copilot. Otherwise the id of a chat profile.35
pub write_with: String,32
}36
}33
37
34
impl Default for AgentSettings {38
impl Default for AgentSettings {@@ -41,6 +45,7 @@ impl Default for AgentSettings {41
],45
],42
resume_interrupted_runs: true,46
resume_interrupted_runs: true,43
recent_working_dirs: HashMap::new(),47
recent_working_dirs: HashMap::new(),48
write_with: String::new(),44
}49
}45
}50
}46
}51
}@@ -59,6 +64,16 @@ fn check_placeholders(item_id: &str, texts: &[&str], problems: &mut Vec<Settings59
}64
}60
65
61
impl AgentSettings {66
impl AgentSettings {67
/// Chat profile chosen under «Write with», or `None` for Microsoft Copilot.68
pub fn write_with_profile(&self) -> Option<&AgentProfile> {69
if self.write_with.is_empty() {70
return None;71
}72
self.agents73
.iter()74
.find(|agent| agent.id == self.write_with && agent.is_chat())75
}76
62
pub fn to_json(&self) -> String {77
pub fn to_json(&self) -> String {63
serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string())78
serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string())64
}79
}@@ -90,11 +105,22 @@ impl AgentSettings {90
pub fn validate(&self) -> Vec<SettingsProblem> {105
pub fn validate(&self) -> Vec<SettingsProblem> {91
let mut problems = Vec::new();106
let mut problems = Vec::new();92
for agent in &self.agents {107
for agent in &self.agents {93
if agent.command.trim().is_empty() {108
if agent.is_command() && agent.command.trim().is_empty() {94
problems.push(SettingsProblem::EmptyCommand {109
problems.push(SettingsProblem::EmptyCommand {95
agent_id: agent.id.clone(),110
agent_id: agent.id.clone(),96
});111
});97
}112
}113
let model = match &agent.backend {114
AgentBackend::OpenAi { model, .. } | AgentBackend::Anthropic { model, .. } => {115
model.as_str()116
}117
AgentBackend::Command => "",118
};119
if agent.is_chat() && model.trim().is_empty() {120
problems.push(SettingsProblem::EmptyModel {121
agent_id: agent.id.clone(),122
});123
}98
check_placeholders(124
check_placeholders(99
&agent.id,125
&agent.id,100
&[&agent.command, &agent.open_session_command],126
&[&agent.command, &agent.open_session_command],@@ -235,4 +261,55 @@ mod tests {235
placeholder: "nope".to_string(),261
placeholder: "nope".to_string(),236
}));262
}));237
}263
}264
265
#[test]266
fn a_profile_without_backend_stays_a_command() {267
let loaded = AgentSettings::from_json(268
r#"{"agents":[{"id":"legacy","name":"Legacy","command":"claude -p"}]}"#,269
)270
.unwrap();271
assert!(loaded.agents[0].is_command());272
assert!(loaded.write_with.is_empty());273
}274
275
#[test]276
fn chat_profiles_need_a_model_and_write_with_round_trips() {277
let mut settings = AgentSettings::default();278
settings.agents.push(AgentProfile::ollama());279
assert!(settings.validate().contains(&SettingsProblem::EmptyModel {280
agent_id: "ollama".to_string(),281
}));282
settings.agents.last_mut().unwrap().backend = AgentBackend::OpenAi {283
base_url: "http://127.0.0.1:11434/v1".to_owned(),284
model: "qwen3.5:9b".to_owned(),285
api_key: String::new(),286
};287
settings.write_with = "ollama".to_owned();288
let loaded = AgentSettings::from_json(&settings.to_json()).unwrap();289
assert_eq!(loaded.write_with, "ollama");290
assert!(loaded.validate().is_empty());291
}292
293
#[test]294
fn write_with_profile_is_none_for_microsoft_and_missing_ids() {295
let mut settings = AgentSettings::default();296
assert!(settings.write_with_profile().is_none());297
settings.write_with = "missing".to_owned();298
assert!(settings.write_with_profile().is_none());299
settings.agents.push(AgentProfile::ollama());300
settings.agents.last_mut().unwrap().backend = AgentBackend::OpenAi {301
base_url: "http://127.0.0.1:11434/v1".to_owned(),302
model: "qwen3.5:9b".to_owned(),303
api_key: String::new(),304
};305
settings.write_with = "ollama".to_owned();306
assert_eq!(307
settings308
.write_with_profile()309
.map(|profile| profile.name.as_str()),310
Some("Ollama")311
);312
settings.write_with = "claude".to_owned();313
assert!(settings.write_with_profile().is_none());314
}238
}315
}@@ -0,0 +1,106 @@
1
use agents::{
2
ChatMessage, ChatReply, McpEndpoint, RunEvent, RunOutcome, RunStatus, RunUpdate, ToolSpec,
3
next_turn,
4
};
5
use tokio::sync::{mpsc, oneshot};
6
7
use mcp::{ListedTool, ToolSession};
8
9
const SYSTEM: &str = "You help with one Teams message. Use the tools to read what you need and to propose a reply or a reaction. You never send anything yourself.";
10
const ROUNDS: usize = 8;
11
12
pub async fn run_chat(
13
profile: agents::AgentProfile,
14
prompt: String,
15
endpoint: Option<McpEndpoint>,
16
events: mpsc::UnboundedSender<RunUpdate>,
17
mut stop: oneshot::Receiver<()>,
18
) -> RunOutcome {
19
let session = match endpoint {
20
Some(endpoint) => {
21
match ToolSession::connect(&mcp::McpEndpoint {
22
url: endpoint.url,
23
token: endpoint.token,
24
})
25
.await
26
{
27
Ok(session) => Some(session),
28
Err(error) => {
29
let _ = events.send(RunUpdate::Event(RunEvent::Step(format!(
30
"MCP tools unavailable: {error}"
31
))));
32
None
33
}
34
}
35
}
36
None => None,
37
};
38
let specs = match &session {
39
Some(session) => session
40
.tools()
41
.await
42
.unwrap_or_default()
43
.into_iter()
44
.map(spec)
45
.collect(),
46
None => Vec::new(),
47
};
48
let mut messages = vec![ChatMessage::user(prompt)];
49
let mut stop_armed = true;
50
for _ in 0..ROUNDS {
51
let turn = tokio::select! {
52
biased;
53
result = &mut stop, if stop_armed => {
54
if result.is_ok() {
55
return RunOutcome { status: RunStatus::Stopped, exit_code: None };
56
}
57
stop_armed = false;
58
continue;
59
}
60
turn = next_turn(&profile, SYSTEM, &messages, &specs) => turn,
61
};
62
match turn {
63
Err(message) => return failed(message),
64
Ok(ChatReply::Text(text)) => {
65
let _ = events.send(RunUpdate::Event(RunEvent::Text(text.clone())));
66
return RunOutcome {
67
status: RunStatus::Completed { final_text: text },
68
exit_code: None,
69
};
70
}
71
Ok(ChatReply::Tools { text, calls }) => {
72
messages.push(ChatMessage::assistant(text, calls.clone()));
73
for call in calls {
74
let _ = events.send(RunUpdate::Event(RunEvent::Step(call.name.clone())));
75
let result = match &session {
76
Some(session) => session
77
.call(&call.name, &call.arguments)
78
.await
79
.unwrap_or_else(|error| error),
80
None => "tools are not available".to_owned(),
81
};
82
messages.push(ChatMessage::tool(call.id, result));
83
}
84
}
85
}
86
}
87
failed("stopped after too many tool calls".to_owned())
88
}
89
90
fn spec(tool: ListedTool) -> ToolSpec {
91
ToolSpec {
92
name: tool.name,
93
description: tool.description,
94
parameters: tool.parameters,
95
}
96
}
97
98
fn failed(message: String) -> RunOutcome {
99
RunOutcome {
100
status: RunStatus::Failed {
101
message,
102
stderr_tail: Vec::new(),
103
},
104
exit_code: None,
105
}
106
}
@@ -0,0 +1,106 @@1
use agents::{2
ChatMessage, ChatReply, McpEndpoint, RunEvent, RunOutcome, RunStatus, RunUpdate, ToolSpec,3
next_turn,4
};5
use tokio::sync::{mpsc, oneshot};6
7
use mcp::{ListedTool, ToolSession};8
9
const SYSTEM: &str = "You help with one Teams message. Use the tools to read what you need and to propose a reply or a reaction. You never send anything yourself.";10
const ROUNDS: usize = 8;11
12
pub async fn run_chat(13
profile: agents::AgentProfile,14
prompt: String,15
endpoint: Option<McpEndpoint>,16
events: mpsc::UnboundedSender<RunUpdate>,17
mut stop: oneshot::Receiver<()>,18
) -> RunOutcome {19
let session = match endpoint {20
Some(endpoint) => {21
match ToolSession::connect(&mcp::McpEndpoint {22
url: endpoint.url,23
token: endpoint.token,24
})25
.await26
{27
Ok(session) => Some(session),28
Err(error) => {29
let _ = events.send(RunUpdate::Event(RunEvent::Step(format!(30
"MCP tools unavailable: {error}"31
))));32
None33
}34
}35
}36
None => None,37
};38
let specs = match &session {39
Some(session) => session40
.tools()41
.await42
.unwrap_or_default()43
.into_iter()44
.map(spec)45
.collect(),46
None => Vec::new(),47
};48
let mut messages = vec![ChatMessage::user(prompt)];49
let mut stop_armed = true;50
for _ in 0..ROUNDS {51
let turn = tokio::select! {52
biased;53
result = &mut stop, if stop_armed => {54
if result.is_ok() {55
return RunOutcome { status: RunStatus::Stopped, exit_code: None };56
}57
stop_armed = false;58
continue;59
}60
turn = next_turn(&profile, SYSTEM, &messages, &specs) => turn,61
};62
match turn {63
Err(message) => return failed(message),64
Ok(ChatReply::Text(text)) => {65
let _ = events.send(RunUpdate::Event(RunEvent::Text(text.clone())));66
return RunOutcome {67
status: RunStatus::Completed { final_text: text },68
exit_code: None,69
};70
}71
Ok(ChatReply::Tools { text, calls }) => {72
messages.push(ChatMessage::assistant(text, calls.clone()));73
for call in calls {74
let _ = events.send(RunUpdate::Event(RunEvent::Step(call.name.clone())));75
let result = match &session {76
Some(session) => session77
.call(&call.name, &call.arguments)78
.await79
.unwrap_or_else(|error| error),80
None => "tools are not available".to_owned(),81
};82
messages.push(ChatMessage::tool(call.id, result));83
}84
}85
}86
}87
failed("stopped after too many tool calls".to_owned())88
}89
90
fn spec(tool: ListedTool) -> ToolSpec {91
ToolSpec {92
name: tool.name,93
description: tool.description,94
parameters: tool.parameters,95
}96
}97
98
fn failed(message: String) -> RunOutcome {99
RunOutcome {100
status: RunStatus::Failed {101
message,102
stderr_tail: Vec::new(),103
},104
exit_code: None,105
}106
}@@ -118,6 +118,64 @@ pub fn preview_prompt(
118
118
))
119
119
}
120
120
121
/// Newest non-deleted messages of a chat, oldest-first, capped at [`THREAD_LIMIT`].
122
pub fn recent_thread(state: &AppState, conversation_id: &str) -> Vec<ThreadMessage> {
123
let names = local_names(state);
124
let sender_of = |entry: &MessageRecord| {
125
entry
126
.sender_name
127
.clone()
128
.filter(|name| !name.trim().is_empty())
129
.or_else(|| {
130
entry
131
.sender_id
132
.as_ref()
133
.and_then(|user_id| names.get(user_id).cloned())
134
})
135
.unwrap_or_else(|| UNKNOWN_SENDER.to_owned())
136
};
137
let mut records = state
138
.store
139
.messages(conversation_id, None, THREAD_LIMIT)
140
.unwrap_or_default();
141
records.retain(|entry| !entry.deleted);
142
let skipped = records.len().saturating_sub(THREAD_LIMIT);
143
records
144
.into_iter()
145
.skip(skipped)
146
.map(|entry| ThreadMessage {
147
sender: sender_of(&entry),
148
text: message_text(&entry),
149
time: entry
150
.created_at
151
.with_timezone(&Local)
152
.format(TIME_FORMAT)
153
.to_string(),
154
})
155
.collect()
156
}
157
158
pub fn chat_title(state: &AppState, conversation_id: &str) -> String {
159
selection_for(&state.sidebar, conversation_id)
160
.as_ref()
161
.map(|selection| selection_title(&state.sidebar, selection))
162
.unwrap_or_else(|| "Chat".to_owned())
163
}
164
165
/// Plain-text ask for a local write-with profile: chat title, recent thread, question.
166
pub fn ask_prompt(chat: &str, thread: &[ThreadMessage], question: &str) -> String {
167
let thread_block = if thread.is_empty() {
168
"(no messages yet)".to_owned()
169
} else {
170
thread
171
.iter()
172
.map(|entry| format!("{} ({}): {}", entry.sender, entry.time, entry.text))
173
.collect::<Vec<_>>()
174
.join("\n")
175
};
176
format!("Chat \"{chat}\"\n\n{thread_block}\n\nQuestion: {question}")
177
}
178
121
179
#[cfg(test)]
122
180
mod tests {
123
181
use std::sync::Arc;
@@ -240,4 +298,22 @@ mod tests {
240
298
assert!(prompt.starts_with("Ada asked me in the Teams chat \"Ops\""));
241
299
assert!(prompt.contains("session_id \"(session id)\""));
242
300
}
301
302
#[test]
303
fn recent_thread_keeps_the_newest_twenty_non_deleted() {
304
let mut records: Vec<MessageRecord> = (0..25)
305
.map(|minute| message(&format!("m{minute}"), None, minute, "Ada"))
306
.collect();
307
records[0].deleted = true;
308
let state = state_with(&records);
309
let thread = recent_thread(&state, "19:chat");
310
assert_eq!(thread.len(), 20);
311
assert_eq!(thread[0].text, "text m5");
312
assert_eq!(thread[19].text, "text m24");
313
assert_eq!(chat_title(&state, "19:chat"), "Ops");
314
let prompt = ask_prompt("Ops", &thread, "Summarize this chat");
315
assert!(prompt.contains("Chat \"Ops\""));
316
assert!(prompt.contains("text m5"));
317
assert!(prompt.contains("Question: Summarize this chat"));
318
}
243
319
}
@@ -118,6 +118,64 @@ pub fn preview_prompt(118
))118
))119
}119
}120
120
121
/// Newest non-deleted messages of a chat, oldest-first, capped at [`THREAD_LIMIT`].122
pub fn recent_thread(state: &AppState, conversation_id: &str) -> Vec<ThreadMessage> {123
let names = local_names(state);124
let sender_of = |entry: &MessageRecord| {125
entry126
.sender_name127
.clone()128
.filter(|name| !name.trim().is_empty())129
.or_else(|| {130
entry131
.sender_id132
.as_ref()133
.and_then(|user_id| names.get(user_id).cloned())134
})135
.unwrap_or_else(|| UNKNOWN_SENDER.to_owned())136
};137
let mut records = state138
.store139
.messages(conversation_id, None, THREAD_LIMIT)140
.unwrap_or_default();141
records.retain(|entry| !entry.deleted);142
let skipped = records.len().saturating_sub(THREAD_LIMIT);143
records144
.into_iter()145
.skip(skipped)146
.map(|entry| ThreadMessage {147
sender: sender_of(&entry),148
text: message_text(&entry),149
time: entry150
.created_at151
.with_timezone(&Local)152
.format(TIME_FORMAT)153
.to_string(),154
})155
.collect()156
}157
158
pub fn chat_title(state: &AppState, conversation_id: &str) -> String {159
selection_for(&state.sidebar, conversation_id)160
.as_ref()161
.map(|selection| selection_title(&state.sidebar, selection))162
.unwrap_or_else(|| "Chat".to_owned())163
}164
165
/// Plain-text ask for a local write-with profile: chat title, recent thread, question.166
pub fn ask_prompt(chat: &str, thread: &[ThreadMessage], question: &str) -> String {167
let thread_block = if thread.is_empty() {168
"(no messages yet)".to_owned()169
} else {170
thread171
.iter()172
.map(|entry| format!("{} ({}): {}", entry.sender, entry.time, entry.text))173
.collect::<Vec<_>>()174
.join("\n")175
};176
format!("Chat \"{chat}\"\n\n{thread_block}\n\nQuestion: {question}")177
}178
121
#[cfg(test)]179
#[cfg(test)]122
mod tests {180
mod tests {123
use std::sync::Arc;181
use std::sync::Arc;@@ -240,4 +298,22 @@ mod tests {240
assert!(prompt.starts_with("Ada asked me in the Teams chat \"Ops\""));298
assert!(prompt.starts_with("Ada asked me in the Teams chat \"Ops\""));241
assert!(prompt.contains("session_id \"(session id)\""));299
assert!(prompt.contains("session_id \"(session id)\""));242
}300
}301
302
#[test]303
fn recent_thread_keeps_the_newest_twenty_non_deleted() {304
let mut records: Vec<MessageRecord> = (0..25)305
.map(|minute| message(&format!("m{minute}"), None, minute, "Ada"))306
.collect();307
records[0].deleted = true;308
let state = state_with(&records);309
let thread = recent_thread(&state, "19:chat");310
assert_eq!(thread.len(), 20);311
assert_eq!(thread[0].text, "text m5");312
assert_eq!(thread[19].text, "text m24");313
assert_eq!(chat_title(&state, "19:chat"), "Ops");314
let prompt = ask_prompt("Ops", &thread, "Summarize this chat");315
assert!(prompt.contains("Chat \"Ops\""));316
assert!(prompt.contains("text m5"));317
assert!(prompt.contains("Question: Summarize this chat"));318
}243
}319
}@@ -1,3 +1,4 @@
1
mod chat_run;
1
2
pub mod demo;
2
3
#[cfg(any(test, feature = "test-support"))]
3
4
pub mod fixtures;
@@ -11,7 +12,7 @@ pub mod store;
11
12
use std::path::PathBuf;
12
13
use std::time::Duration;
13
14
14
use agents::{AgentAction, Environment};
15
use agents::{AgentAction, AgentProfile, Environment};
15
16
pub use app_base::agents::{lanes, settings_problems};
16
17
pub use app_ui_kit::{settings_controls, spinner};
17
18
use directories::ProjectDirs;
@@ -43,6 +44,15 @@ pub fn runs_handle(cx: &App) -> Option<Entity<AgentRuns>> {
43
44
.map(|handle| handle.0.clone())
44
45
}
45
46
47
/// Chat profile for «Write with», or `None` when Microsoft Copilot is selected.
48
pub fn local_writer(cx: &App) -> Option<AgentProfile> {
49
runs_handle(cx)?
50
.read(cx)
51
.settings()
52
.write_with_profile()
53
.cloned()
54
}
55
46
56
pub fn agents_enabled(cx: &App) -> bool {
47
57
runs_handle(cx).is_some_and(|runs| !runs.read(cx).settings().actions.is_empty())
48
58
}
@@ -203,7 +213,13 @@ fn open_run_session(run: &AgentRun, cx: &mut App) {
203
213
204
214
pub fn environment_label(environment: &Environment) -> String {
205
215
match environment {
206
Environment::Host => "Windows".to_owned(),
216
Environment::Host => {
217
if cfg!(windows) {
218
"Windows".to_owned()
219
} else {
220
"This computer".to_owned()
221
}
222
}
207
223
Environment::Wsl { distro: None } => "WSL".to_owned(),
208
224
Environment::Wsl {
209
225
distro: Some(distro),
@@ -1,3 +1,4 @@1
mod chat_run;1
pub mod demo;2
pub mod demo;2
#[cfg(any(test, feature = "test-support"))]3
#[cfg(any(test, feature = "test-support"))]3
pub mod fixtures;4
pub mod fixtures;@@ -11,7 +12,7 @@ pub mod store;11
use std::path::PathBuf;12
use std::path::PathBuf;12
use std::time::Duration;13
use std::time::Duration;13
14
14
use agents::{AgentAction, Environment};15
use agents::{AgentAction, AgentProfile, Environment};15
pub use app_base::agents::{lanes, settings_problems};16
pub use app_base::agents::{lanes, settings_problems};16
pub use app_ui_kit::{settings_controls, spinner};17
pub use app_ui_kit::{settings_controls, spinner};17
use directories::ProjectDirs;18
use directories::ProjectDirs;@@ -43,6 +44,15 @@ pub fn runs_handle(cx: &App) -> Option<Entity<AgentRuns>> {43
.map(|handle| handle.0.clone())44
.map(|handle| handle.0.clone())44
}45
}45
46
47
/// Chat profile for «Write with», or `None` when Microsoft Copilot is selected.48
pub fn local_writer(cx: &App) -> Option<AgentProfile> {49
runs_handle(cx)?50
.read(cx)51
.settings()52
.write_with_profile()53
.cloned()54
}55
46
pub fn agents_enabled(cx: &App) -> bool {56
pub fn agents_enabled(cx: &App) -> bool {47
runs_handle(cx).is_some_and(|runs| !runs.read(cx).settings().actions.is_empty())57
runs_handle(cx).is_some_and(|runs| !runs.read(cx).settings().actions.is_empty())48
}58
}@@ -203,7 +213,13 @@ fn open_run_session(run: &AgentRun, cx: &mut App) {203
213
204
pub fn environment_label(environment: &Environment) -> String {214
pub fn environment_label(environment: &Environment) -> String {205
match environment {215
match environment {206
Environment::Host => "Windows".to_owned(),216
Environment::Host => {217
if cfg!(windows) {218
"Windows".to_owned()219
} else {220
"This computer".to_owned()221
}222
}207
Environment::Wsl { distro: None } => "WSL".to_owned(),223
Environment::Wsl { distro: None } => "WSL".to_owned(),208
Environment::Wsl {224
Environment::Wsl {209
distro: Some(distro),225
distro: Some(distro),@@ -838,14 +838,22 @@ impl AgentRuns {
838
838
return;
839
839
};
840
840
let prompt = run.pending_prompt.clone().unwrap_or_default();
841
let planned = self.launch_plan(&run, &prompt, cx);
842
if let Some(run) = self.run_mut(run_id) {
843
run.pending_prompt = None;
844
if run.current_step == QUEUED_STEP {
845
run.started_at = Utc::now();
846
run.push_step("Starting".to_owned());
847
}
841
if let Some(profile) = self
842
.settings
843
.agents
844
.iter()
845
.find(|agent| agent.id == run.agent_id)
846
.cloned()
847
.filter(|profile| profile.is_chat())
848
{
849
self.mark_launching(run_id);
850
let endpoint = mcp_bridge::endpoint(cx);
851
self.spawn_chat(run_id, profile, prompt, endpoint, cx);
852
self.persist(cx);
853
return;
848
854
}
855
let planned = self.launch_plan(&run, &prompt, cx);
856
self.mark_launching(run_id);
849
857
match planned {
850
858
Ok((plan, format)) => self.spawn(run_id, plan, format, cx),
851
859
Err(message) => self.finish(
@@ -898,6 +906,54 @@ impl AgentRuns {
898
906
.map_err(|error| error.to_string())
899
907
}
900
908
909
fn mark_launching(&mut self, run_id: u64) {
910
if let Some(run) = self.run_mut(run_id) {
911
run.pending_prompt = None;
912
if run.current_step == QUEUED_STEP {
913
run.started_at = Utc::now();
914
run.push_step("Starting".to_owned());
915
}
916
}
917
}
918
919
fn spawn_chat(
920
&mut self,
921
run_id: u64,
922
profile: AgentProfile,
923
prompt: String,
924
endpoint: Option<McpEndpoint>,
925
cx: &mut Context<Self>,
926
) {
927
let (updates_sender, mut updates) = mpsc::unbounded_channel();
928
let (stop_sender, stop_receiver) = oneshot::channel();
929
self.stops.insert(run_id, stop_sender);
930
if let Some(run) = self.run_mut(run_id) {
931
run.launch_session_id = Some(run.session_id.clone());
932
run.launched = true;
933
}
934
let outcome = runtime::spawn(super::chat_run::run_chat(
935
profile,
936
prompt,
937
endpoint,
938
updates_sender,
939
stop_receiver,
940
));
941
cx.spawn(async move |this, cx| {
942
while let Some(update) = updates.recv().await {
943
if this
944
.update(cx, |runs, cx| runs.apply_update(run_id, update, cx))
945
.is_err()
946
{
947
return;
948
}
949
}
950
let outcome = outcome.await.ok();
951
this.update(cx, |runs, cx| runs.finish(run_id, outcome, cx))
952
.ok();
953
})
954
.detach();
955
}
956
901
957
fn spawn(
902
958
&mut self,
903
959
run_id: u64,
@@ -1211,7 +1267,7 @@ pub(super) mod tests {
1211
1267
use std::sync::Arc;
1212
1268
use std::time::Duration;
1213
1269
1214
use agents::{AgentAction, AgentProfile, AgentSettings, Environment, OutputFormat};
1270
use agents::{AgentAction, AgentProfile, AgentSettings};
1215
1271
use chrono::TimeZone;
1216
1272
use store::{MessageRecord, Store};
1217
1273
@@ -1237,11 +1293,8 @@ pub(super) mod tests {
1237
1293
let profile = AgentProfile {
1238
1294
id: "fake".to_owned(),
1239
1295
name: "Fake".to_owned(),
1240
environment: Environment::Host,
1241
1296
command: command.to_owned(),
1242
output: OutputFormat::ClaudeStreamJson,
1243
open_session_command: String::new(),
1244
mcp_config_flag: String::new(),
1297
..AgentProfile::default()
1245
1298
};
1246
1299
let action = AgentAction {
1247
1300
id: "ask".to_owned(),
@@ -838,14 +838,22 @@ impl AgentRuns {838
return;838
return;839
};839
};840
let prompt = run.pending_prompt.clone().unwrap_or_default();840
let prompt = run.pending_prompt.clone().unwrap_or_default();841
let planned = self.launch_plan(&run, &prompt, cx);841
if let Some(profile) = self842
if let Some(run) = self.run_mut(run_id) {842
.settings843
run.pending_prompt = None;843
.agents844
if run.current_step == QUEUED_STEP {844
.iter()845
run.started_at = Utc::now();845
.find(|agent| agent.id == run.agent_id)846
run.push_step("Starting".to_owned());846
.cloned()847
}847
.filter(|profile| profile.is_chat())848
{849
self.mark_launching(run_id);850
let endpoint = mcp_bridge::endpoint(cx);851
self.spawn_chat(run_id, profile, prompt, endpoint, cx);852
self.persist(cx);853
return;848
}854
}855
let planned = self.launch_plan(&run, &prompt, cx);856
self.mark_launching(run_id);849
match planned {857
match planned {850
Ok((plan, format)) => self.spawn(run_id, plan, format, cx),858
Ok((plan, format)) => self.spawn(run_id, plan, format, cx),851
Err(message) => self.finish(859
Err(message) => self.finish(@@ -898,6 +906,54 @@ impl AgentRuns {898
.map_err(|error| error.to_string())906
.map_err(|error| error.to_string())899
}907
}900
908
909
fn mark_launching(&mut self, run_id: u64) {910
if let Some(run) = self.run_mut(run_id) {911
run.pending_prompt = None;912
if run.current_step == QUEUED_STEP {913
run.started_at = Utc::now();914
run.push_step("Starting".to_owned());915
}916
}917
}918
919
fn spawn_chat(920
&mut self,921
run_id: u64,922
profile: AgentProfile,923
prompt: String,924
endpoint: Option<McpEndpoint>,925
cx: &mut Context<Self>,926
) {927
let (updates_sender, mut updates) = mpsc::unbounded_channel();928
let (stop_sender, stop_receiver) = oneshot::channel();929
self.stops.insert(run_id, stop_sender);930
if let Some(run) = self.run_mut(run_id) {931
run.launch_session_id = Some(run.session_id.clone());932
run.launched = true;933
}934
let outcome = runtime::spawn(super::chat_run::run_chat(935
profile,936
prompt,937
endpoint,938
updates_sender,939
stop_receiver,940
));941
cx.spawn(async move |this, cx| {942
while let Some(update) = updates.recv().await {943
if this944
.update(cx, |runs, cx| runs.apply_update(run_id, update, cx))945
.is_err()946
{947
return;948
}949
}950
let outcome = outcome.await.ok();951
this.update(cx, |runs, cx| runs.finish(run_id, outcome, cx))952
.ok();953
})954
.detach();955
}956
901
fn spawn(957
fn spawn(902
&mut self,958
&mut self,903
run_id: u64,959
run_id: u64,@@ -1211,7 +1267,7 @@ pub(super) mod tests {1211
use std::sync::Arc;1267
use std::sync::Arc;1212
use std::time::Duration;1268
use std::time::Duration;1213
1269
1214
use agents::{AgentAction, AgentProfile, AgentSettings, Environment, OutputFormat};1270
use agents::{AgentAction, AgentProfile, AgentSettings};1215
use chrono::TimeZone;1271
use chrono::TimeZone;1216
use store::{MessageRecord, Store};1272
use store::{MessageRecord, Store};1217
1273
@@ -1237,11 +1293,8 @@ pub(super) mod tests {1237
let profile = AgentProfile {1293
let profile = AgentProfile {1238
id: "fake".to_owned(),1294
id: "fake".to_owned(),1239
name: "Fake".to_owned(),1295
name: "Fake".to_owned(),1240
environment: Environment::Host,1241
command: command.to_owned(),1296
command: command.to_owned(),1242
output: OutputFormat::ClaudeStreamJson,1297
..AgentProfile::default()1243
open_session_command: String::new(),1244
mcp_config_flag: String::new(),1245
};1298
};1246
let action = AgentAction {1299
let action = AgentAction {1247
id: "ask".to_owned(),1300
id: "ask".to_owned(),@@ -1,6 +1,6 @@
1
1
use std::rc::Rc;
2
2
3
use agents::{Environment, OutputFormat};
3
use agents::{AgentBackend, Environment, OutputFormat};
4
4
use gpui_kit::assets::IconName;
5
5
use gpui_kit::component::{ActiveTheme as _, h_flex, input::Textarea, v_flex};
6
6
use gpui_kit::prelude::FluentBuilder as _;
@@ -27,9 +27,17 @@ const PLACEHOLDER_CHIPS: [&str; 9] = [
27
27
"agent",
28
28
];
29
29
30
fn host_label() -> &'static str {
31
if cfg!(windows) {
32
"Windows"
33
} else {
34
"This computer"
35
}
36
}
37
30
38
fn environment_choices() -> [(&'static str, Environment); 3] {
31
39
[
32
("Windows", Environment::Host),
40
(host_label(), Environment::Host),
33
41
("WSL - default distro", Environment::Wsl { distro: None }),
34
42
(
35
43
"WSL - named distro",
@@ -115,7 +123,7 @@ impl AgentsSettings {
115
123
let environment_label = environment_choices()
116
124
.into_iter()
117
125
.find(|(_, environment)| same_environment_kind(environment, &profile.environment))
118
.map_or("Windows", |(label, _)| label);
126
.map_or(host_label(), |(label, _)| label);
119
127
let output_entries: Vec<MenuEntry> = output_choices()
120
128
.into_iter()
121
129
.map(|(label, output)| {
@@ -137,12 +145,68 @@ impl AgentsSettings {
137
145
let open_problem =
138
146
placeholder_problem(&problems, &profile.id, &profile.open_session_command);
139
147
let named_distro = matches!(profile.environment, Environment::Wsl { distro: Some(_) });
148
let chat = profile.is_chat();
140
149
let status = match &self.probe {
141
150
Probe::Idle => None,
142
Probe::Running => Some(("Testing...".to_owned(), theme::text_muted())),
143
Probe::Found(line) => Some((format!("Found: {line}"), theme::green())),
151
Probe::Running => Some((
152
if chat {
153
"Loading models...".to_owned()
154
} else {
155
"Testing...".to_owned()
156
},
157
theme::text_muted(),
158
)),
159
Probe::Found(line) => Some((
160
if chat {
161
line.clone()
162
} else {
163
format!("Found: {line}")
164
},
165
theme::green(),
166
)),
144
167
Probe::Missing(error) => Some((error.clone(), theme::red_soft())),
145
168
};
169
let shows_base = matches!(profile.backend, AgentBackend::OpenAi { .. });
170
let key_saved = match &profile.backend {
171
AgentBackend::OpenAi { api_key, .. } | AgentBackend::Anthropic { api_key, .. } => {
172
!api_key.is_empty()
173
}
174
AgentBackend::Command => false,
175
};
176
let model_problem = problems.iter().find_map(|problem| match problem {
177
agents::SettingsProblem::EmptyModel { agent_id } if agent_id == &profile.id => {
178
Some("Choose a model".to_owned())
179
}
180
_ => None,
181
});
182
let current_model = form_state.model.read(cx).value().trim().to_owned();
183
let mut model_names = self.models.clone();
184
if !current_model.is_empty() && !model_names.iter().any(|name| name == ¤t_model) {
185
model_names.insert(0, current_model.clone());
186
}
187
let model_entries: Vec<MenuEntry> = model_names
188
.iter()
189
.map(|name| {
190
let this = this.clone();
191
let label = name.clone();
192
let chosen = label.clone();
193
let selected = label == current_model;
194
let choose: Choice = Rc::new(move |window, cx| {
195
let name = chosen.clone();
196
this.update(cx, |this, cx| this.set_model(name, window, cx))
197
});
198
MenuEntry {
199
label,
200
selected,
201
choose,
202
}
203
})
204
.collect();
205
let model_label = if current_model.is_empty() {
206
"Choose a model".to_owned()
207
} else {
208
current_model
209
};
146
210
let test_this = this.clone();
147
211
let delete_this = this.clone();
148
212
v_flex()
@@ -156,22 +220,76 @@ impl AgentsSettings {
156
220
None,
157
221
)
158
222
.into_any_element(),
159
field(
160
"Runs in",
161
dropdown(
162
"agent-environment",
163
environment_label.to_owned(),
164
environment_entries,
165
),
166
Some(hint(
167
"Windows or a WSL distro. Paths below are in that system.",
168
)),
169
None,
170
)
171
.into_any_element(),
172
223
div()
173
224
.w_full()
174
.when(named_distro, |slot| {
225
.when(chat && shows_base, |slot| {
226
slot.child(field(
227
"Base URL",
228
text_field(&form_state.base_url, true, false, cx),
229
Some(hint("OpenAI-compatible, including /v1.")),
230
None,
231
))
232
})
233
.into_any_element(),
234
div()
235
.w_full()
236
.when(chat && !model_entries.is_empty(), |slot| {
237
slot.child(field(
238
"Installed models",
239
dropdown("agent-model", model_label, model_entries),
240
Some(hint("Loaded from the endpoint. The choice fills Model.")),
241
None,
242
))
243
})
244
.into_any_element(),
245
div()
246
.w_full()
247
.when(chat, |slot| {
248
slot.child(field(
249
"Model",
250
text_field(&form_state.model, true, model_problem.is_some(), cx),
251
Some(hint(
252
"Pick a loaded model, or type an id. Leave the URL or key field to reload.",
253
)),
254
model_problem.clone(),
255
))
256
})
257
.into_any_element(),
258
div()
259
.w_full()
260
.when(chat, |slot| {
261
slot.child(field(
262
"API key",
263
text_field(&form_state.api_key, true, false, cx),
264
Some(hint(if key_saved {
265
"A key is saved. Type a new one to replace it. Ollama can stay empty."
266
} else {
267
"Stored in the local app database. Ollama can stay empty."
268
})),
269
None,
270
))
271
})
272
.into_any_element(),
273
div()
274
.w_full()
275
.when(!chat, |slot| {
276
slot.child(field(
277
"Runs in",
278
dropdown(
279
"agent-environment",
280
environment_label.to_owned(),
281
environment_entries,
282
),
283
Some(hint(
284
"This computer or a WSL distro. Paths below are in that system.",
285
)),
286
None,
287
))
288
})
289
.into_any_element(),
290
div()
291
.w_full()
292
.when(!chat && named_distro, |slot| {
175
293
slot.child(field(
176
294
"Distro name",
177
295
text_field(&form_state.distro, false, false, cx),
@@ -180,38 +298,54 @@ impl AgentsSettings {
180
298
))
181
299
})
182
300
.into_any_element(),
183
field(
184
"Command",
185
text_field(&form_state.command, true, command_problem.is_some(), cx),
186
Some(hint(
187
"The prompt goes to stdin unless the command has {prompt}.",
188
)),
189
command_problem,
190
)
191
.into_any_element(),
192
field(
193
"Output",
194
dropdown("agent-output", output_label.to_owned(), output_entries),
195
Some(hint("Plain text shows only the time and the last line.")),
196
None,
197
)
198
.into_any_element(),
199
field(
200
"MCP config flag",
201
text_field(&form_state.mcp_flag, true, false, cx),
202
Some(hint(
203
"Passes the Teams MCP endpoint to the agent. Empty = none.",
204
)),
205
None,
206
)
207
.into_any_element(),
208
field(
209
"Open session",
210
text_field(&form_state.open_session, true, open_problem.is_some(), cx),
211
Some(hint("Available: {cwd} and {session_id}.")),
212
open_problem,
213
)
214
.into_any_element(),
301
div()
302
.w_full()
303
.when(!chat, |slot| {
304
slot.child(field(
305
"Command",
306
text_field(&form_state.command, true, command_problem.is_some(), cx),
307
Some(hint(
308
"The prompt goes to stdin unless the command has {prompt}.",
309
)),
310
command_problem,
311
))
312
})
313
.into_any_element(),
314
div()
315
.w_full()
316
.when(!chat, |slot| {
317
slot.child(field(
318
"Output",
319
dropdown("agent-output", output_label.to_owned(), output_entries),
320
Some(hint("Plain text shows only the time and the last line.")),
321
None,
322
))
323
})
324
.into_any_element(),
325
div()
326
.w_full()
327
.when(!chat, |slot| {
328
slot.child(field(
329
"MCP config flag",
330
text_field(&form_state.mcp_flag, true, false, cx),
331
Some(hint(
332
"Passes the Teams MCP endpoint to the agent. Empty = none.",
333
)),
334
None,
335
))
336
})
337
.into_any_element(),
338
div()
339
.w_full()
340
.when(!chat, |slot| {
341
slot.child(field(
342
"Open session",
343
text_field(&form_state.open_session, true, open_problem.is_some(), cx),
344
Some(hint("Available: {cwd} and {session_id}.")),
345
open_problem,
346
))
347
})
348
.into_any_element(),
215
349
h_flex()
216
350
.w_full()
217
351
.gap(px(8.))
@@ -1,6 +1,6 @@1
use std::rc::Rc;1
use std::rc::Rc;2
2
3
use agents::{Environment, OutputFormat};3
use agents::{AgentBackend, Environment, OutputFormat};4
use gpui_kit::assets::IconName;4
use gpui_kit::assets::IconName;5
use gpui_kit::component::{ActiveTheme as _, h_flex, input::Textarea, v_flex};5
use gpui_kit::component::{ActiveTheme as _, h_flex, input::Textarea, v_flex};6
use gpui_kit::prelude::FluentBuilder as _;6
use gpui_kit::prelude::FluentBuilder as _;@@ -27,9 +27,17 @@ const PLACEHOLDER_CHIPS: [&str; 9] = [27
"agent",27
"agent",28
];28
];29
29
30
fn host_label() -> &'static str {31
if cfg!(windows) {32
"Windows"33
} else {34
"This computer"35
}36
}37
30
fn environment_choices() -> [(&'static str, Environment); 3] {38
fn environment_choices() -> [(&'static str, Environment); 3] {31
[39
[32
("Windows", Environment::Host),40
(host_label(), Environment::Host),33
("WSL - default distro", Environment::Wsl { distro: None }),41
("WSL - default distro", Environment::Wsl { distro: None }),34
(42
(35
"WSL - named distro",43
"WSL - named distro",@@ -115,7 +123,7 @@ impl AgentsSettings {115
let environment_label = environment_choices()123
let environment_label = environment_choices()116
.into_iter()124
.into_iter()117
.find(|(_, environment)| same_environment_kind(environment, &profile.environment))125
.find(|(_, environment)| same_environment_kind(environment, &profile.environment))118
.map_or("Windows", |(label, _)| label);126
.map_or(host_label(), |(label, _)| label);119
let output_entries: Vec<MenuEntry> = output_choices()127
let output_entries: Vec<MenuEntry> = output_choices()120
.into_iter()128
.into_iter()121
.map(|(label, output)| {129
.map(|(label, output)| {@@ -137,12 +145,68 @@ impl AgentsSettings {137
let open_problem =145
let open_problem =138
placeholder_problem(&problems, &profile.id, &profile.open_session_command);146
placeholder_problem(&problems, &profile.id, &profile.open_session_command);139
let named_distro = matches!(profile.environment, Environment::Wsl { distro: Some(_) });147
let named_distro = matches!(profile.environment, Environment::Wsl { distro: Some(_) });148
let chat = profile.is_chat();140
let status = match &self.probe {149
let status = match &self.probe {141
Probe::Idle => None,150
Probe::Idle => None,142
Probe::Running => Some(("Testing...".to_owned(), theme::text_muted())),151
Probe::Running => Some((143
Probe::Found(line) => Some((format!("Found: {line}"), theme::green())),152
if chat {153
"Loading models...".to_owned()154
} else {155
"Testing...".to_owned()156
},157
theme::text_muted(),158
)),159
Probe::Found(line) => Some((160
if chat {161
line.clone()162
} else {163
format!("Found: {line}")164
},165
theme::green(),166
)),144
Probe::Missing(error) => Some((error.clone(), theme::red_soft())),167
Probe::Missing(error) => Some((error.clone(), theme::red_soft())),145
};168
};169
let shows_base = matches!(profile.backend, AgentBackend::OpenAi { .. });170
let key_saved = match &profile.backend {171
AgentBackend::OpenAi { api_key, .. } | AgentBackend::Anthropic { api_key, .. } => {172
!api_key.is_empty()173
}174
AgentBackend::Command => false,175
};176
let model_problem = problems.iter().find_map(|problem| match problem {177
agents::SettingsProblem::EmptyModel { agent_id } if agent_id == &profile.id => {178
Some("Choose a model".to_owned())179
}180
_ => None,181
});182
let current_model = form_state.model.read(cx).value().trim().to_owned();183
let mut model_names = self.models.clone();184
if !current_model.is_empty() && !model_names.iter().any(|name| name == ¤t_model) {185
model_names.insert(0, current_model.clone());186
}187
let model_entries: Vec<MenuEntry> = model_names188
.iter()189
.map(|name| {190
let this = this.clone();191
let label = name.clone();192
let chosen = label.clone();193
let selected = label == current_model;194
let choose: Choice = Rc::new(move |window, cx| {195
let name = chosen.clone();196
this.update(cx, |this, cx| this.set_model(name, window, cx))197
});198
MenuEntry {199
label,200
selected,201
choose,202
}203
})204
.collect();205
let model_label = if current_model.is_empty() {206
"Choose a model".to_owned()207
} else {208
current_model209
};146
let test_this = this.clone();210
let test_this = this.clone();147
let delete_this = this.clone();211
let delete_this = this.clone();148
v_flex()212
v_flex()@@ -156,22 +220,76 @@ impl AgentsSettings {156
None,220
None,157
)221
)158
.into_any_element(),222
.into_any_element(),159
field(160
"Runs in",161
dropdown(162
"agent-environment",163
environment_label.to_owned(),164
environment_entries,165
),166
Some(hint(167
"Windows or a WSL distro. Paths below are in that system.",168
)),169
None,170
)171
.into_any_element(),172
div()223
div()173
.w_full()224
.w_full()174
.when(named_distro, |slot| {225
.when(chat && shows_base, |slot| {226
slot.child(field(227
"Base URL",228
text_field(&form_state.base_url, true, false, cx),229
Some(hint("OpenAI-compatible, including /v1.")),230
None,231
))232
})233
.into_any_element(),234
div()235
.w_full()236
.when(chat && !model_entries.is_empty(), |slot| {237
slot.child(field(238
"Installed models",239
dropdown("agent-model", model_label, model_entries),240
Some(hint("Loaded from the endpoint. The choice fills Model.")),241
None,242
))243
})244
.into_any_element(),245
div()246
.w_full()247
.when(chat, |slot| {248
slot.child(field(249
"Model",250
text_field(&form_state.model, true, model_problem.is_some(), cx),251
Some(hint(252
"Pick a loaded model, or type an id. Leave the URL or key field to reload.",253
)),254
model_problem.clone(),255
))256
})257
.into_any_element(),258
div()259
.w_full()260
.when(chat, |slot| {261
slot.child(field(262
"API key",263
text_field(&form_state.api_key, true, false, cx),264
Some(hint(if key_saved {265
"A key is saved. Type a new one to replace it. Ollama can stay empty."266
} else {267
"Stored in the local app database. Ollama can stay empty."268
})),269
None,270
))271
})272
.into_any_element(),273
div()274
.w_full()275
.when(!chat, |slot| {276
slot.child(field(277
"Runs in",278
dropdown(279
"agent-environment",280
environment_label.to_owned(),281
environment_entries,282
),283
Some(hint(284
"This computer or a WSL distro. Paths below are in that system.",285
)),286
None,287
))288
})289
.into_any_element(),290
div()291
.w_full()292
.when(!chat && named_distro, |slot| {175
slot.child(field(293
slot.child(field(176
"Distro name",294
"Distro name",177
text_field(&form_state.distro, false, false, cx),295
text_field(&form_state.distro, false, false, cx),@@ -180,38 +298,54 @@ impl AgentsSettings {180
))298
))181
})299
})182
.into_any_element(),300
.into_any_element(),183
field(301
div()184
"Command",302
.w_full()185
text_field(&form_state.command, true, command_problem.is_some(), cx),303
.when(!chat, |slot| {186
Some(hint(304
slot.child(field(187
"The prompt goes to stdin unless the command has {prompt}.",305
"Command",188
)),306
text_field(&form_state.command, true, command_problem.is_some(), cx),189
command_problem,307
Some(hint(190
)308
"The prompt goes to stdin unless the command has {prompt}.",191
.into_any_element(),309
)),192
field(310
command_problem,193
"Output",311
))194
dropdown("agent-output", output_label.to_owned(), output_entries),312
})195
Some(hint("Plain text shows only the time and the last line.")),313
.into_any_element(),196
None,314
div()197
)315
.w_full()198
.into_any_element(),316
.when(!chat, |slot| {199
field(317
slot.child(field(200
"MCP config flag",318
"Output",201
text_field(&form_state.mcp_flag, true, false, cx),319
dropdown("agent-output", output_label.to_owned(), output_entries),202
Some(hint(320
Some(hint("Plain text shows only the time and the last line.")),203
"Passes the Teams MCP endpoint to the agent. Empty = none.",321
None,204
)),322
))205
None,323
})206
)324
.into_any_element(),207
.into_any_element(),325
div()208
field(326
.w_full()209
"Open session",327
.when(!chat, |slot| {210
text_field(&form_state.open_session, true, open_problem.is_some(), cx),328
slot.child(field(211
Some(hint("Available: {cwd} and {session_id}.")),329
"MCP config flag",212
open_problem,330
text_field(&form_state.mcp_flag, true, false, cx),213
)331
Some(hint(214
.into_any_element(),332
"Passes the Teams MCP endpoint to the agent. Empty = none.",333
)),334
None,335
))336
})337
.into_any_element(),338
div()339
.w_full()340
.when(!chat, |slot| {341
slot.child(field(342
"Open session",343
text_field(&form_state.open_session, true, open_problem.is_some(), cx),344
Some(hint("Available: {cwd} and {session_id}.")),345
open_problem,346
))347
})348
.into_any_element(),215
h_flex()349
h_flex()216
.w_full()350
.w_full()217
.gap(px(8.))351
.gap(px(8.))@@ -539,7 +539,9 @@ fn proposal_marker(pending: &PendingProposal, row_group: SharedString) -> Div {
539
539
PendingKind::Reply { .. } => {
540
540
marker.child(icon(IconName::MessageCircle, 10., theme::text_muted()))
541
541
}
542
PendingKind::Reaction { glyph, .. } => marker.child(glyph.clone()),
542
PendingKind::Reaction { glyph, .. } => marker
543
.font_family(theme::EMOJI_FONT_FAMILY)
544
.child(glyph.clone()),
543
545
}
544
546
}
545
547
@@ -552,7 +554,9 @@ fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
552
554
.font_weight(FontWeight::BOLD)
553
555
.child("@"),
554
556
Kind::Reaction => match entry.glyphs.first() {
555
Some(glyph) => marker.child(glyph.clone()),
557
Some(glyph) => marker
558
.font_family(theme::EMOJI_FONT_FAMILY)
559
.child(glyph.clone()),
556
560
None => marker.child(muted_icon(IconName::Heart)),
557
561
},
558
562
Kind::MissedCall => marker.child(icon(IconName::PhoneOff, 10., theme::red())),
@@ -539,7 +539,9 @@ fn proposal_marker(pending: &PendingProposal, row_group: SharedString) -> Div {539
PendingKind::Reply { .. } => {539
PendingKind::Reply { .. } => {540
marker.child(icon(IconName::MessageCircle, 10., theme::text_muted()))540
marker.child(icon(IconName::MessageCircle, 10., theme::text_muted()))541
}541
}542
PendingKind::Reaction { glyph, .. } => marker.child(glyph.clone()),542
PendingKind::Reaction { glyph, .. } => marker543
.font_family(theme::EMOJI_FONT_FAMILY)544
.child(glyph.clone()),543
}545
}544
}546
}545
547
@@ -552,7 +554,9 @@ fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {552
.font_weight(FontWeight::BOLD)554
.font_weight(FontWeight::BOLD)553
.child("@"),555
.child("@"),554
Kind::Reaction => match entry.glyphs.first() {556
Kind::Reaction => match entry.glyphs.first() {555
Some(glyph) => marker.child(glyph.clone()),557
Some(glyph) => marker558
.font_family(theme::EMOJI_FONT_FAMILY)559
.child(glyph.clone()),556
None => marker.child(muted_icon(IconName::Heart)),560
None => marker.child(muted_icon(IconName::Heart)),557
},561
},558
Kind::MissedCall => marker.child(icon(IconName::PhoneOff, 10., theme::red())),562
Kind::MissedCall => marker.child(icon(IconName::PhoneOff, 10., theme::red())),@@ -17,18 +17,17 @@ use app_ui_kit::spinner::spinner;
17
17
pub const REWRITE_BUTTON_TAG: &str = "composer/actions/copilot";
18
18
pub const REWRITE_PANEL_TAG: &str = "composer/copilot";
19
19
const BUTTON_LABEL: &str = "Write with Copilot";
20
const REWRITE_SYSTEM: &str = "You rewrite a Teams chat draft. Reply with only the new message text. Keep the meaning. Do not add a preamble. Write in the same language as the draft.";
21
const SWITCH_HINT: &str = "Choose another model under Settings > Agents, Write with.";
20
22
const CLOSE_LABEL: &str = "Close";
21
23
const ADJUST_LABEL: &str = "Adjust";
22
24
const CUSTOM_LABEL: &str = "Customised";
23
25
const CUSTOM_PLACEHOLDER: &str = "Describe how to adjust it, e.g. make it sound friendlier";
24
26
const REPLACE_LABEL: &str = "Replace";
25
27
const DISCLAIMER: &str = "AI-generated content may be incorrect";
26
const WORKING: &str = "Copilot is writing ...";
27
const FAILED: &str = "Copilot could not rewrite this:";
28
const EMPTY_DRAFT: &str = "Type a message first, then let Copilot rewrite it.";
29
const TEXT_ONLY: &str =
30
"Copilot rewrites text only. Move images and tables out of the message first.";
28
const COPILOT_NAME: &str = "Copilot";
31
29
const BUTTON_ICON: &str = "auto_fix_high";
30
const LOCAL_BUTTON_ICON: &str = "smart_toy";
32
31
const PANEL_WIDTH: f32 = 600.;
33
32
const PANEL_PADDING: f32 = 16.;
34
33
const PANEL_RADIUS: f32 = 10.;
@@ -79,7 +78,7 @@ impl Composer {
79
78
fn rewrite_available(&self, cx: &App) -> bool {
80
79
let state = self.app.read(cx);
81
80
self.editing.is_none()
82
&& (state.mode.demo || state.engine.is_some())
81
&& (state.mode.demo || local_writer(cx).is_some() || state.engine.is_some())
83
82
&& self
84
83
.conversation_id
85
84
.as_deref()
@@ -101,6 +100,12 @@ impl Composer {
101
100
return None;
102
101
}
103
102
let open = self.rewrite.open;
103
let writer = local_writer(cx);
104
let local = writer.is_some();
105
let tooltip = writer
106
.as_ref()
107
.map(|profile| format!("Rewrite with {}", profile.name))
108
.unwrap_or_else(|| BUTTON_LABEL.to_owned());
104
109
Some(
105
110
div()
106
111
.id("composer-copilot")
@@ -114,9 +119,13 @@ impl Composer {
114
119
.cursor_pointer()
115
120
.when(open, |button| button.bg(theme::popup_hover()))
116
121
.hover(|button| button.bg(theme::popup_hover()))
117
.popup_trigger_tooltip_text(open, BUTTON_LABEL)
122
.popup_trigger_tooltip_text(open, tooltip)
118
123
.child(symbol(
119
BUTTON_ICON,
124
if local {
125
LOCAL_BUTTON_ICON
126
} else {
127
BUTTON_ICON
128
},
120
129
COMPOSER_ICON_SIZE,
121
130
if open {
122
131
theme::accent_text()
@@ -156,17 +165,19 @@ impl Composer {
156
165
let Some(chat_id) = self.conversation_id.clone() else {
157
166
return;
158
167
};
168
let writer = writer_display_name(cx);
169
let failed = failed_rewrite(&writer);
159
170
let refusal = if draft.is_blank() {
160
Some(EMPTY_DRAFT)
171
Some(empty_draft_message(&writer))
161
172
} else if draft.text().contains([OBJECT_MARK, TABLE_MARK]) {
162
Some(TEXT_ONLY)
173
Some(text_only_message(&writer))
163
174
} else {
164
175
None
165
176
};
166
177
if let Some(refusal) = refusal {
167
178
self.rewrite.result = Some(RewriteResult {
168
179
action,
169
answer: RewriteAnswer::Failed(refusal.to_owned()),
180
answer: RewriteAnswer::Failed(refusal),
170
181
});
171
182
cx.notify();
172
183
return;
@@ -177,6 +188,31 @@ impl Composer {
177
188
});
178
189
cx.notify();
179
190
let user_html = draft.to_html();
191
let plain = draft.plain_text();
192
if !demo && let Some(profile) = local_writer(cx) {
193
let instruction = rewrite_instruction(&action, &plain);
194
let receiver = runtime::spawn(async move {
195
agents::complete_text(&profile, REWRITE_SYSTEM, &instruction).await
196
});
197
cx.spawn(async move |this, cx| {
198
let answer = match receiver.await {
199
Ok(Ok(text)) => RewriteAnswer::Ready(Draft::from_markdown(&text)),
200
Ok(Err(error)) => RewriteAnswer::Failed(format!("{failed} {error}")),
201
Err(error) => RewriteAnswer::Failed(format!("{failed} {error}")),
202
};
203
this.update(cx, |this, cx| {
204
if this.rewrite.generation == generation
205
&& let Some(result) = this.rewrite.result.as_mut()
206
{
207
result.answer = answer;
208
cx.notify();
209
}
210
})
211
.ok();
212
})
213
.detach();
214
return;
215
}
180
216
let receiver = (!demo).then_some(engine).flatten().map(|engine| {
181
217
runtime::spawn(async move { engine.rewrite_draft(&chat_id, &user_html, action).await })
182
218
});
@@ -191,8 +227,10 @@ impl Composer {
191
227
Ok(Ok(html)) => {
192
228
RewriteAnswer::Ready(Draft::from_spans(&html_to_spans(&html)).trimmed())
193
229
}
194
Ok(Err(error)) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
195
Err(error) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
230
Ok(Err(error)) => {
231
RewriteAnswer::Failed(format!("{failed} {error} {SWITCH_HINT}"))
232
}
233
Err(error) => RewriteAnswer::Failed(format!("{failed} {error} {SWITCH_HINT}")),
196
234
},
197
235
};
198
236
this.update(cx, |this, cx| {
@@ -464,7 +502,7 @@ impl Composer {
464
502
div()
465
503
.text_size(px(14.))
466
504
.text_color(theme::text_soft())
467
.child(WORKING),
505
.child(working_message(&writer_display_name(cx))),
468
506
),
469
507
),
470
508
RewriteAnswer::Failed(reason) => card.child(
@@ -515,6 +553,49 @@ impl Composer {
515
553
}
516
554
}
517
555
556
fn local_writer(cx: &App) -> Option<agents::AgentProfile> {
557
crate::agents::local_writer(cx)
558
}
559
560
fn writer_display_name(cx: &App) -> String {
561
local_writer(cx)
562
.map(|profile| profile.name)
563
.unwrap_or_else(|| COPILOT_NAME.to_owned())
564
}
565
566
fn working_message(name: &str) -> String {
567
format!("{name} is writing ...")
568
}
569
570
fn failed_rewrite(name: &str) -> String {
571
format!("{name} could not rewrite this:")
572
}
573
574
fn empty_draft_message(name: &str) -> String {
575
format!("Type a message first, then let {name} rewrite it.")
576
}
577
578
fn text_only_message(name: &str) -> String {
579
format!("{name} rewrites text only. Move images and tables out of the message first.")
580
}
581
582
fn rewrite_instruction(action: &ComposeAction, draft: &str) -> String {
583
let ask = match action {
584
ComposeAction::Rewrite => "Rewrite it so it is clearer.",
585
ComposeAction::Proofread => "Proofread it. Fix spelling and grammar.",
586
ComposeAction::Adjust(adjustment) => match adjustment {
587
ComposeAdjustment::Concise => "Make it shorter.",
588
ComposeAdjustment::Longer => "Make it a bit longer.",
589
ComposeAdjustment::Casual => "Make it more casual.",
590
ComposeAdjustment::Professional => "Make it more professional.",
591
ComposeAdjustment::Confident => "Make it more confident.",
592
ComposeAdjustment::Enthusiastic => "Make it more enthusiastic.",
593
},
594
ComposeAction::Custom(prompt) => prompt.as_str(),
595
};
596
format!("{ask}\n\n{draft}")
597
}
598
518
599
fn demo_rewrite(text: &str) -> String {
519
600
let trimmed = text.trim().trim_end_matches(['.', '!', '?']);
520
601
let mut characters = trimmed.chars();
@@ -17,18 +17,17 @@ use app_ui_kit::spinner::spinner;17
pub const REWRITE_BUTTON_TAG: &str = "composer/actions/copilot";17
pub const REWRITE_BUTTON_TAG: &str = "composer/actions/copilot";18
pub const REWRITE_PANEL_TAG: &str = "composer/copilot";18
pub const REWRITE_PANEL_TAG: &str = "composer/copilot";19
const BUTTON_LABEL: &str = "Write with Copilot";19
const BUTTON_LABEL: &str = "Write with Copilot";20
const REWRITE_SYSTEM: &str = "You rewrite a Teams chat draft. Reply with only the new message text. Keep the meaning. Do not add a preamble. Write in the same language as the draft.";21
const SWITCH_HINT: &str = "Choose another model under Settings > Agents, Write with.";20
const CLOSE_LABEL: &str = "Close";22
const CLOSE_LABEL: &str = "Close";21
const ADJUST_LABEL: &str = "Adjust";23
const ADJUST_LABEL: &str = "Adjust";22
const CUSTOM_LABEL: &str = "Customised";24
const CUSTOM_LABEL: &str = "Customised";23
const CUSTOM_PLACEHOLDER: &str = "Describe how to adjust it, e.g. make it sound friendlier";25
const CUSTOM_PLACEHOLDER: &str = "Describe how to adjust it, e.g. make it sound friendlier";24
const REPLACE_LABEL: &str = "Replace";26
const REPLACE_LABEL: &str = "Replace";25
const DISCLAIMER: &str = "AI-generated content may be incorrect";27
const DISCLAIMER: &str = "AI-generated content may be incorrect";26
const WORKING: &str = "Copilot is writing ...";28
const COPILOT_NAME: &str = "Copilot";27
const FAILED: &str = "Copilot could not rewrite this:";28
const EMPTY_DRAFT: &str = "Type a message first, then let Copilot rewrite it.";29
const TEXT_ONLY: &str =30
"Copilot rewrites text only. Move images and tables out of the message first.";31
const BUTTON_ICON: &str = "auto_fix_high";29
const BUTTON_ICON: &str = "auto_fix_high";30
const LOCAL_BUTTON_ICON: &str = "smart_toy";32
const PANEL_WIDTH: f32 = 600.;31
const PANEL_WIDTH: f32 = 600.;33
const PANEL_PADDING: f32 = 16.;32
const PANEL_PADDING: f32 = 16.;34
const PANEL_RADIUS: f32 = 10.;33
const PANEL_RADIUS: f32 = 10.;@@ -79,7 +78,7 @@ impl Composer {79
fn rewrite_available(&self, cx: &App) -> bool {78
fn rewrite_available(&self, cx: &App) -> bool {80
let state = self.app.read(cx);79
let state = self.app.read(cx);81
self.editing.is_none()80
self.editing.is_none()82
&& (state.mode.demo || state.engine.is_some())81
&& (state.mode.demo || local_writer(cx).is_some() || state.engine.is_some())83
&& self82
&& self84
.conversation_id83
.conversation_id85
.as_deref()84
.as_deref()@@ -101,6 +100,12 @@ impl Composer {101
return None;100
return None;102
}101
}103
let open = self.rewrite.open;102
let open = self.rewrite.open;103
let writer = local_writer(cx);104
let local = writer.is_some();105
let tooltip = writer106
.as_ref()107
.map(|profile| format!("Rewrite with {}", profile.name))108
.unwrap_or_else(|| BUTTON_LABEL.to_owned());104
Some(109
Some(105
div()110
div()106
.id("composer-copilot")111
.id("composer-copilot")@@ -114,9 +119,13 @@ impl Composer {114
.cursor_pointer()119
.cursor_pointer()115
.when(open, |button| button.bg(theme::popup_hover()))120
.when(open, |button| button.bg(theme::popup_hover()))116
.hover(|button| button.bg(theme::popup_hover()))121
.hover(|button| button.bg(theme::popup_hover()))117
.popup_trigger_tooltip_text(open, BUTTON_LABEL)122
.popup_trigger_tooltip_text(open, tooltip)118
.child(symbol(123
.child(symbol(119
BUTTON_ICON,124
if local {125
LOCAL_BUTTON_ICON126
} else {127
BUTTON_ICON128
},120
COMPOSER_ICON_SIZE,129
COMPOSER_ICON_SIZE,121
if open {130
if open {122
theme::accent_text()131
theme::accent_text()@@ -156,17 +165,19 @@ impl Composer {156
let Some(chat_id) = self.conversation_id.clone() else {165
let Some(chat_id) = self.conversation_id.clone() else {157
return;166
return;158
};167
};168
let writer = writer_display_name(cx);169
let failed = failed_rewrite(&writer);159
let refusal = if draft.is_blank() {170
let refusal = if draft.is_blank() {160
Some(EMPTY_DRAFT)171
Some(empty_draft_message(&writer))161
} else if draft.text().contains([OBJECT_MARK, TABLE_MARK]) {172
} else if draft.text().contains([OBJECT_MARK, TABLE_MARK]) {162
Some(TEXT_ONLY)173
Some(text_only_message(&writer))163
} else {174
} else {164
None175
None165
};176
};166
if let Some(refusal) = refusal {177
if let Some(refusal) = refusal {167
self.rewrite.result = Some(RewriteResult {178
self.rewrite.result = Some(RewriteResult {168
action,179
action,169
answer: RewriteAnswer::Failed(refusal.to_owned()),180
answer: RewriteAnswer::Failed(refusal),170
});181
});171
cx.notify();182
cx.notify();172
return;183
return;@@ -177,6 +188,31 @@ impl Composer {177
});188
});178
cx.notify();189
cx.notify();179
let user_html = draft.to_html();190
let user_html = draft.to_html();191
let plain = draft.plain_text();192
if !demo && let Some(profile) = local_writer(cx) {193
let instruction = rewrite_instruction(&action, &plain);194
let receiver = runtime::spawn(async move {195
agents::complete_text(&profile, REWRITE_SYSTEM, &instruction).await196
});197
cx.spawn(async move |this, cx| {198
let answer = match receiver.await {199
Ok(Ok(text)) => RewriteAnswer::Ready(Draft::from_markdown(&text)),200
Ok(Err(error)) => RewriteAnswer::Failed(format!("{failed} {error}")),201
Err(error) => RewriteAnswer::Failed(format!("{failed} {error}")),202
};203
this.update(cx, |this, cx| {204
if this.rewrite.generation == generation205
&& let Some(result) = this.rewrite.result.as_mut()206
{207
result.answer = answer;208
cx.notify();209
}210
})211
.ok();212
})213
.detach();214
return;215
}180
let receiver = (!demo).then_some(engine).flatten().map(|engine| {216
let receiver = (!demo).then_some(engine).flatten().map(|engine| {181
runtime::spawn(async move { engine.rewrite_draft(&chat_id, &user_html, action).await })217
runtime::spawn(async move { engine.rewrite_draft(&chat_id, &user_html, action).await })182
});218
});@@ -191,8 +227,10 @@ impl Composer {191
Ok(Ok(html)) => {227
Ok(Ok(html)) => {192
RewriteAnswer::Ready(Draft::from_spans(&html_to_spans(&html)).trimmed())228
RewriteAnswer::Ready(Draft::from_spans(&html_to_spans(&html)).trimmed())193
}229
}194
Ok(Err(error)) => RewriteAnswer::Failed(format!("{FAILED} {error}")),230
Ok(Err(error)) => {195
Err(error) => RewriteAnswer::Failed(format!("{FAILED} {error}")),231
RewriteAnswer::Failed(format!("{failed} {error} {SWITCH_HINT}"))232
}233
Err(error) => RewriteAnswer::Failed(format!("{failed} {error} {SWITCH_HINT}")),196
},234
},197
};235
};198
this.update(cx, |this, cx| {236
this.update(cx, |this, cx| {@@ -464,7 +502,7 @@ impl Composer {464
div()502
div()465
.text_size(px(14.))503
.text_size(px(14.))466
.text_color(theme::text_soft())504
.text_color(theme::text_soft())467
.child(WORKING),505
.child(working_message(&writer_display_name(cx))),468
),506
),469
),507
),470
RewriteAnswer::Failed(reason) => card.child(508
RewriteAnswer::Failed(reason) => card.child(@@ -515,6 +553,49 @@ impl Composer {515
}553
}516
}554
}517
555
556
fn local_writer(cx: &App) -> Option<agents::AgentProfile> {557
crate::agents::local_writer(cx)558
}559
560
fn writer_display_name(cx: &App) -> String {561
local_writer(cx)562
.map(|profile| profile.name)563
.unwrap_or_else(|| COPILOT_NAME.to_owned())564
}565
566
fn working_message(name: &str) -> String {567
format!("{name} is writing ...")568
}569
570
fn failed_rewrite(name: &str) -> String {571
format!("{name} could not rewrite this:")572
}573
574
fn empty_draft_message(name: &str) -> String {575
format!("Type a message first, then let {name} rewrite it.")576
}577
578
fn text_only_message(name: &str) -> String {579
format!("{name} rewrites text only. Move images and tables out of the message first.")580
}581
582
fn rewrite_instruction(action: &ComposeAction, draft: &str) -> String {583
let ask = match action {584
ComposeAction::Rewrite => "Rewrite it so it is clearer.",585
ComposeAction::Proofread => "Proofread it. Fix spelling and grammar.",586
ComposeAction::Adjust(adjustment) => match adjustment {587
ComposeAdjustment::Concise => "Make it shorter.",588
ComposeAdjustment::Longer => "Make it a bit longer.",589
ComposeAdjustment::Casual => "Make it more casual.",590
ComposeAdjustment::Professional => "Make it more professional.",591
ComposeAdjustment::Confident => "Make it more confident.",592
ComposeAdjustment::Enthusiastic => "Make it more enthusiastic.",593
},594
ComposeAction::Custom(prompt) => prompt.as_str(),595
};596
format!("{ask}\n\n{draft}")597
}598
518
fn demo_rewrite(text: &str) -> String {599
fn demo_rewrite(text: &str) -> String {519
let trimmed = text.trim().trim_end_matches(['.', '!', '?']);600
let trimmed = text.trim().trim_end_matches(['.', '!', '?']);520
let mut characters = trimmed.chars();601
let mut characters = trimmed.chars();@@ -110,7 +110,7 @@ impl ConversationView {
110
110
} else {
111
111
open_details
112
112
};
113
let copilot_label = self.copilot_label();
113
let copilot_label = self.copilot_label(cx);
114
114
Some(
115
115
Button::new(CHAT_HEADER_MORE_TAG)
116
116
.icon(IconName::Ellipsis)
@@ -121,7 +121,7 @@ impl ConversationView {
121
121
.debug_selector(|| CHAT_HEADER_MORE_TAG.into())
122
122
.dropdown_menu(move |popup, window, cx| {
123
123
let popup = if overflow {
124
overflow_items(popup, view.clone(), copilot_label, details_label)
124
overflow_items(popup, view.clone(), copilot_label.clone(), details_label)
125
125
} else {
126
126
popup
127
127
};
@@ -140,7 +140,7 @@ impl ConversationView {
140
140
fn overflow_items(
141
141
popup: PopupMenu,
142
142
view: WeakEntity<ConversationView>,
143
copilot_label: &'static str,
143
copilot_label: String,
144
144
details_label: &'static str,
145
145
) -> PopupMenu {
146
146
let (find_view, details_view) = (view.clone(), view.clone());
@@ -110,7 +110,7 @@ impl ConversationView {110
} else {110
} else {111
open_details111
open_details112
};112
};113
let copilot_label = self.copilot_label();113
let copilot_label = self.copilot_label(cx);114
Some(114
Some(115
Button::new(CHAT_HEADER_MORE_TAG)115
Button::new(CHAT_HEADER_MORE_TAG)116
.icon(IconName::Ellipsis)116
.icon(IconName::Ellipsis)@@ -121,7 +121,7 @@ impl ConversationView {121
.debug_selector(|| CHAT_HEADER_MORE_TAG.into())121
.debug_selector(|| CHAT_HEADER_MORE_TAG.into())122
.dropdown_menu(move |popup, window, cx| {122
.dropdown_menu(move |popup, window, cx| {123
let popup = if overflow {123
let popup = if overflow {124
overflow_items(popup, view.clone(), copilot_label, details_label)124
overflow_items(popup, view.clone(), copilot_label.clone(), details_label)125
} else {125
} else {126
popup126
popup127
};127
};@@ -140,7 +140,7 @@ impl ConversationView {140
fn overflow_items(140
fn overflow_items(141
popup: PopupMenu,141
popup: PopupMenu,142
view: WeakEntity<ConversationView>,142
view: WeakEntity<ConversationView>,143
copilot_label: &'static str,143
copilot_label: String,144
details_label: &'static str,144
details_label: &'static str,145
) -> PopupMenu {145
) -> PopupMenu {146
let (find_view, details_view) = (view.clone(), view.clone());146
let (find_view, details_view) = (view.clone(), view.clone());@@ -7,23 +7,20 @@ use gpui_kit::prelude::FluentBuilder as _;
7
7
use gpui_kit::*;
8
8
9
9
use super::ConversationView;
10
use crate::agents::message_context;
10
11
use crate::app_state::Selection;
11
12
use crate::render::{layout_card_blocks, render_blocks};
12
13
use crate::runtime;
13
14
use crate::theme;
14
15
use crate::views::scroll_edge::with_top_edge;
16
use crate::views::widgets::symbol;
15
17
16
18
pub const COPILOT_PANE_TAG: &str = "shell/islands/copilot";
17
19
const COPILOT_SCROLL_DIVIDER: &str = "shell/islands/copilot/divider-scroll";
18
const TITLE: &str = "Copilot";
19
const OPEN_LABEL: &str = "Open Copilot";
20
const CLOSE_LABEL: &str = "Close Copilot";
21
const PLACEHOLDER: &str = "Message Copilot";
22
const WORKING: &str = "Copilot is reading the chat ...";
23
const UNAVAILABLE: &str = "Copilot needs a signed-in account.";
24
const FAILED: &str = "Copilot could not answer:";
20
const COPILOT_NAME: &str = "Copilot";
25
21
const GREETING: &str = "Hi, how can I help?";
26
22
const LOGO_ASSET: &str = "symbols/copilot_color.svg";
23
const LOCAL_ICON: &str = "smart_toy";
27
24
const LOGO_BUTTON: f32 = 18.;
28
25
const LOGO_TITLE: f32 = 20.;
29
26
const INPUT_MIN_HEIGHT: f32 = 72.;
@@ -40,6 +37,7 @@ const PANE_PADDING: f32 = 16.;
40
37
const HEADER_HEIGHT: f32 = 48.;
41
38
const BUTTON_SIZE: f32 = 32.;
42
39
const BUBBLE_RADIUS: f32 = 8.;
40
const ASK_SYSTEM: &str = "You answer questions about a Teams chat. Use only the messages provided. Do not invent messages. Reply in plain text. Answer in the same language as the chat messages.";
43
41
44
42
#[derive(Default)]
45
43
pub(super) struct CopilotPane {
@@ -70,25 +68,28 @@ impl ConversationView {
70
68
}
71
69
}
72
70
73
pub(super) fn copilot_label(&self) -> &'static str {
71
pub(super) fn copilot_label(&self, cx: &App) -> String {
72
let name = writer_display_name(cx);
74
73
if self.copilot.open {
75
CLOSE_LABEL
74
format!("Close {name}")
76
75
} else {
77
OPEN_LABEL
76
format!("Open {name}")
78
77
}
79
78
}
80
79
81
80
pub(super) fn copilot_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
82
81
self.copilot_chat_id()?;
83
82
let open = self.copilot.open;
83
let local = crate::agents::local_writer(cx).is_some();
84
let label = self.copilot_label(cx);
84
85
Some(
85
86
Button::new("copilot-toggle")
86
.child(copilot_logo(LOGO_BUTTON))
87
.child(identity_mark(local, LOGO_BUTTON, theme::text_muted()))
87
88
.ghost()
88
89
.size(px(BUTTON_SIZE))
89
90
.rounded(px(8.))
90
91
.when(open, |button| button.selected(true))
91
.tooltip(if open { CLOSE_LABEL } else { OPEN_LABEL })
92
.tooltip(label)
92
93
.on_click(cx.listener(|this, _, window, cx| this.toggle_copilot(window, cx)))
93
94
.into_any_element(),
94
95
)
@@ -97,7 +98,8 @@ impl ConversationView {
97
98
pub(super) fn toggle_copilot(&mut self, window: &mut Window, cx: &mut Context<Self>) {
98
99
self.copilot.open = !self.copilot.open;
99
100
if self.copilot.open && self.copilot.input.is_none() {
100
let input = cx.new(|cx| InputState::new(window, cx).placeholder(PLACEHOLDER));
101
let placeholder = format!("Message {}", writer_display_name(cx));
102
let input = cx.new(|cx| InputState::new(window, cx).placeholder(placeholder));
101
103
let subscription = cx.subscribe_in(
102
104
&input,
103
105
window,
@@ -152,16 +154,57 @@ impl ConversationView {
152
154
});
153
155
self.copilot.scroll.scroll_to_bottom();
154
156
cx.notify();
157
let failed = failed_answer(&writer_display_name(cx));
158
if let Some(profile) = crate::agents::local_writer(cx) {
159
let state = self.app.read(cx);
160
let chat = message_context::chat_title(state, &chat_id);
161
let thread = message_context::recent_thread(state, &chat_id);
162
let user = message_context::ask_prompt(&chat, &thread, &prompt);
163
let receiver =
164
runtime::spawn(
165
async move { agents::complete_text(&profile, ASK_SYSTEM, &user).await },
166
);
167
cx.spawn(async move |this, cx| {
168
let answer = match receiver.await {
169
Ok(Ok(text)) => Ok(text),
170
Ok(Err(error)) => Err(error),
171
Err(error) => Err(error.to_string()),
172
};
173
this.update(cx, |this, cx| {
174
this.settle_copilot(
175
generation,
176
index,
177
answer.map_err(|error| format!("{failed} {error}")),
178
cx,
179
)
180
})
181
.ok();
182
})
183
.detach();
184
return;
185
}
155
186
let Some(engine) = self.app.read(cx).engine.clone() else {
156
self.settle_copilot(generation, index, Err(UNAVAILABLE.to_owned()), cx);
187
self.settle_copilot(
188
generation,
189
index,
190
Err(unavailable_message(&writer_display_name(cx))),
191
cx,
192
);
157
193
return;
158
194
};
159
195
let receiver = runtime::spawn(async move { engine.ask_copilot(&chat_id, &prompt).await });
160
196
cx.spawn(async move |this, cx| {
161
197
let answer = match receiver.await {
162
198
Ok(Ok(text)) => Ok(text),
163
Ok(Err(error)) => Err(error.to_string()),
164
Err(error) => Err(error.to_string()),
199
Ok(Err(error)) => Err(format!(
200
"{failed} {}",
201
error
202
.to_string()
203
.split(" (https://")
204
.next()
205
.unwrap_or_default()
206
)),
207
Err(error) => Err(format!("{failed} {error}")),
165
208
};
166
209
this.update(cx, |this, cx| {
167
210
this.settle_copilot(generation, index, answer, cx)
@@ -186,10 +229,7 @@ impl ConversationView {
186
229
};
187
230
turn.answer = match answer {
188
231
Ok(text) => CopilotAnswer::Ready(text),
189
Err(error) => CopilotAnswer::Failed(format!(
190
"{FAILED} {}",
191
error.split(" (https://").next().unwrap_or_default()
192
)),
232
Err(error) => CopilotAnswer::Failed(error),
193
233
};
194
234
self.copilot.scroll.scroll_to_bottom();
195
235
cx.notify();
@@ -200,6 +240,8 @@ impl ConversationView {
200
240
return None;
201
241
}
202
242
self.copilot_chat_id()?;
243
let local = crate::agents::local_writer(cx).is_some();
244
let name = writer_display_name(cx);
203
245
let busy = self
204
246
.copilot
205
247
.turns
@@ -215,6 +257,7 @@ impl ConversationView {
215
257
.bg(theme::surface_raised())
216
258
.child(Input::new(input).appearance(false).bordered(false))
217
259
});
260
let working = working_message(&name);
218
261
let content = if self.copilot.turns.is_empty() {
219
262
let suggestions =
220
263
v_flex()
@@ -265,6 +308,7 @@ impl ConversationView {
265
308
body = body.child(prompt_bubble(&turn.prompt)).child(answer_view(
266
309
index,
267
310
&turn.answer,
311
&working,
268
312
cx,
269
313
));
270
314
}
@@ -315,13 +359,13 @@ impl ConversationView {
315
359
h_flex()
316
360
.gap(px(8.))
317
361
.items_center()
318
.child(copilot_logo(LOGO_TITLE))
362
.child(identity_mark(local, LOGO_TITLE, theme::text()))
319
363
.child(
320
364
div()
321
365
.text_size(px(15.))
322
366
.font_weight(FontWeight::SEMIBOLD)
323
367
.text_color(theme::text())
324
.child(TITLE),
368
.child(name),
325
369
),
326
370
)
327
371
.child(
@@ -330,7 +374,7 @@ impl ConversationView {
330
374
.ghost()
331
375
.size(px(BUTTON_SIZE))
332
376
.rounded(px(8.))
333
.tooltip(CLOSE_LABEL)
377
.tooltip(format!("Close {}", writer_display_name(cx)))
334
378
.on_click(cx.listener(|this, _, _, cx| {
335
379
this.copilot.open = false;
336
380
cx.notify();
@@ -344,8 +388,33 @@ impl ConversationView {
344
388
}
345
389
}
346
390
347
fn copilot_logo(size: f32) -> Img {
348
img(LOGO_ASSET).size(px(size)).flex_none()
391
fn writer_display_name(cx: &App) -> String {
392
crate::agents::local_writer(cx)
393
.map(|profile| profile.name)
394
.unwrap_or_else(|| COPILOT_NAME.to_owned())
395
}
396
397
fn working_message(name: &str) -> String {
398
format!("{name} is reading the chat ...")
399
}
400
401
fn failed_answer(name: &str) -> String {
402
format!("{name} could not answer:")
403
}
404
405
fn unavailable_message(name: &str) -> String {
406
format!("{name} needs a signed-in account.")
407
}
408
409
fn identity_mark(local: bool, size: f32, color: Hsla) -> AnyElement {
410
if local {
411
symbol(LOCAL_ICON, size, color).into_any_element()
412
} else {
413
img(LOGO_ASSET)
414
.size(px(size))
415
.flex_none()
416
.into_any_element()
417
}
349
418
}
350
419
351
420
fn prompt_bubble(prompt: &str) -> Div {
@@ -362,12 +431,12 @@ fn prompt_bubble(prompt: &str) -> Div {
362
431
)
363
432
}
364
433
365
fn answer_view(index: usize, answer: &CopilotAnswer, cx: &App) -> AnyElement {
434
fn answer_view(index: usize, answer: &CopilotAnswer, working: &str, cx: &App) -> AnyElement {
366
435
match answer {
367
436
CopilotAnswer::Waiting => div()
368
437
.text_size(px(13.))
369
438
.text_color(theme::text_muted())
370
.child(WORKING)
439
.child(working.to_owned())
371
440
.into_any_element(),
372
441
CopilotAnswer::Failed(error) => div()
373
442
.text_size(px(13.))
@@ -7,23 +7,20 @@ use gpui_kit::prelude::FluentBuilder as _;7
use gpui_kit::*;7
use gpui_kit::*;8
8
9
use super::ConversationView;9
use super::ConversationView;10
use crate::agents::message_context;10
use crate::app_state::Selection;11
use crate::app_state::Selection;11
use crate::render::{layout_card_blocks, render_blocks};12
use crate::render::{layout_card_blocks, render_blocks};12
use crate::runtime;13
use crate::runtime;13
use crate::theme;14
use crate::theme;14
use crate::views::scroll_edge::with_top_edge;15
use crate::views::scroll_edge::with_top_edge;16
use crate::views::widgets::symbol;15
17
16
pub const COPILOT_PANE_TAG: &str = "shell/islands/copilot";18
pub const COPILOT_PANE_TAG: &str = "shell/islands/copilot";17
const COPILOT_SCROLL_DIVIDER: &str = "shell/islands/copilot/divider-scroll";19
const COPILOT_SCROLL_DIVIDER: &str = "shell/islands/copilot/divider-scroll";18
const TITLE: &str = "Copilot";20
const COPILOT_NAME: &str = "Copilot";19
const OPEN_LABEL: &str = "Open Copilot";20
const CLOSE_LABEL: &str = "Close Copilot";21
const PLACEHOLDER: &str = "Message Copilot";22
const WORKING: &str = "Copilot is reading the chat ...";23
const UNAVAILABLE: &str = "Copilot needs a signed-in account.";24
const FAILED: &str = "Copilot could not answer:";25
const GREETING: &str = "Hi, how can I help?";21
const GREETING: &str = "Hi, how can I help?";26
const LOGO_ASSET: &str = "symbols/copilot_color.svg";22
const LOGO_ASSET: &str = "symbols/copilot_color.svg";23
const LOCAL_ICON: &str = "smart_toy";27
const LOGO_BUTTON: f32 = 18.;24
const LOGO_BUTTON: f32 = 18.;28
const LOGO_TITLE: f32 = 20.;25
const LOGO_TITLE: f32 = 20.;29
const INPUT_MIN_HEIGHT: f32 = 72.;26
const INPUT_MIN_HEIGHT: f32 = 72.;@@ -40,6 +37,7 @@ const PANE_PADDING: f32 = 16.;40
const HEADER_HEIGHT: f32 = 48.;37
const HEADER_HEIGHT: f32 = 48.;41
const BUTTON_SIZE: f32 = 32.;38
const BUTTON_SIZE: f32 = 32.;42
const BUBBLE_RADIUS: f32 = 8.;39
const BUBBLE_RADIUS: f32 = 8.;40
const ASK_SYSTEM: &str = "You answer questions about a Teams chat. Use only the messages provided. Do not invent messages. Reply in plain text. Answer in the same language as the chat messages.";43
41
44
#[derive(Default)]42
#[derive(Default)]45
pub(super) struct CopilotPane {43
pub(super) struct CopilotPane {@@ -70,25 +68,28 @@ impl ConversationView {70
}68
}71
}69
}72
70
73
pub(super) fn copilot_label(&self) -> &'static str {71
pub(super) fn copilot_label(&self, cx: &App) -> String {72
let name = writer_display_name(cx);74
if self.copilot.open {73
if self.copilot.open {75
CLOSE_LABEL74
format!("Close {name}")76
} else {75
} else {77
OPEN_LABEL76
format!("Open {name}")78
}77
}79
}78
}80
79
81
pub(super) fn copilot_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {80
pub(super) fn copilot_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {82
self.copilot_chat_id()?;81
self.copilot_chat_id()?;83
let open = self.copilot.open;82
let open = self.copilot.open;83
let local = crate::agents::local_writer(cx).is_some();84
let label = self.copilot_label(cx);84
Some(85
Some(85
Button::new("copilot-toggle")86
Button::new("copilot-toggle")86
.child(copilot_logo(LOGO_BUTTON))87
.child(identity_mark(local, LOGO_BUTTON, theme::text_muted()))87
.ghost()88
.ghost()88
.size(px(BUTTON_SIZE))89
.size(px(BUTTON_SIZE))89
.rounded(px(8.))90
.rounded(px(8.))90
.when(open, |button| button.selected(true))91
.when(open, |button| button.selected(true))91
.tooltip(if open { CLOSE_LABEL } else { OPEN_LABEL })92
.tooltip(label)92
.on_click(cx.listener(|this, _, window, cx| this.toggle_copilot(window, cx)))93
.on_click(cx.listener(|this, _, window, cx| this.toggle_copilot(window, cx)))93
.into_any_element(),94
.into_any_element(),94
)95
)@@ -97,7 +98,8 @@ impl ConversationView {97
pub(super) fn toggle_copilot(&mut self, window: &mut Window, cx: &mut Context<Self>) {98
pub(super) fn toggle_copilot(&mut self, window: &mut Window, cx: &mut Context<Self>) {98
self.copilot.open = !self.copilot.open;99
self.copilot.open = !self.copilot.open;99
if self.copilot.open && self.copilot.input.is_none() {100
if self.copilot.open && self.copilot.input.is_none() {100
let input = cx.new(|cx| InputState::new(window, cx).placeholder(PLACEHOLDER));101
let placeholder = format!("Message {}", writer_display_name(cx));102
let input = cx.new(|cx| InputState::new(window, cx).placeholder(placeholder));101
let subscription = cx.subscribe_in(103
let subscription = cx.subscribe_in(102
&input,104
&input,103
window,105
window,@@ -152,16 +154,57 @@ impl ConversationView {152
});154
});153
self.copilot.scroll.scroll_to_bottom();155
self.copilot.scroll.scroll_to_bottom();154
cx.notify();156
cx.notify();157
let failed = failed_answer(&writer_display_name(cx));158
if let Some(profile) = crate::agents::local_writer(cx) {159
let state = self.app.read(cx);160
let chat = message_context::chat_title(state, &chat_id);161
let thread = message_context::recent_thread(state, &chat_id);162
let user = message_context::ask_prompt(&chat, &thread, &prompt);163
let receiver =164
runtime::spawn(165
async move { agents::complete_text(&profile, ASK_SYSTEM, &user).await },166
);167
cx.spawn(async move |this, cx| {168
let answer = match receiver.await {169
Ok(Ok(text)) => Ok(text),170
Ok(Err(error)) => Err(error),171
Err(error) => Err(error.to_string()),172
};173
this.update(cx, |this, cx| {174
this.settle_copilot(175
generation,176
index,177
answer.map_err(|error| format!("{failed} {error}")),178
cx,179
)180
})181
.ok();182
})183
.detach();184
return;185
}155
let Some(engine) = self.app.read(cx).engine.clone() else {186
let Some(engine) = self.app.read(cx).engine.clone() else {156
self.settle_copilot(generation, index, Err(UNAVAILABLE.to_owned()), cx);187
self.settle_copilot(188
generation,189
index,190
Err(unavailable_message(&writer_display_name(cx))),191
cx,192
);157
return;193
return;158
};194
};159
let receiver = runtime::spawn(async move { engine.ask_copilot(&chat_id, &prompt).await });195
let receiver = runtime::spawn(async move { engine.ask_copilot(&chat_id, &prompt).await });160
cx.spawn(async move |this, cx| {196
cx.spawn(async move |this, cx| {161
let answer = match receiver.await {197
let answer = match receiver.await {162
Ok(Ok(text)) => Ok(text),198
Ok(Ok(text)) => Ok(text),163
Ok(Err(error)) => Err(error.to_string()),199
Ok(Err(error)) => Err(format!(164
Err(error) => Err(error.to_string()),200
"{failed} {}",201
error202
.to_string()203
.split(" (https://")204
.next()205
.unwrap_or_default()206
)),207
Err(error) => Err(format!("{failed} {error}")),165
};208
};166
this.update(cx, |this, cx| {209
this.update(cx, |this, cx| {167
this.settle_copilot(generation, index, answer, cx)210
this.settle_copilot(generation, index, answer, cx)@@ -186,10 +229,7 @@ impl ConversationView {186
};229
};187
turn.answer = match answer {230
turn.answer = match answer {188
Ok(text) => CopilotAnswer::Ready(text),231
Ok(text) => CopilotAnswer::Ready(text),189
Err(error) => CopilotAnswer::Failed(format!(232
Err(error) => CopilotAnswer::Failed(error),190
"{FAILED} {}",191
error.split(" (https://").next().unwrap_or_default()192
)),193
};233
};194
self.copilot.scroll.scroll_to_bottom();234
self.copilot.scroll.scroll_to_bottom();195
cx.notify();235
cx.notify();@@ -200,6 +240,8 @@ impl ConversationView {200
return None;240
return None;201
}241
}202
self.copilot_chat_id()?;242
self.copilot_chat_id()?;243
let local = crate::agents::local_writer(cx).is_some();244
let name = writer_display_name(cx);203
let busy = self245
let busy = self204
.copilot246
.copilot205
.turns247
.turns@@ -215,6 +257,7 @@ impl ConversationView {215
.bg(theme::surface_raised())257
.bg(theme::surface_raised())216
.child(Input::new(input).appearance(false).bordered(false))258
.child(Input::new(input).appearance(false).bordered(false))217
});259
});260
let working = working_message(&name);218
let content = if self.copilot.turns.is_empty() {261
let content = if self.copilot.turns.is_empty() {219
let suggestions =262
let suggestions =220
v_flex()263
v_flex()@@ -265,6 +308,7 @@ impl ConversationView {265
body = body.child(prompt_bubble(&turn.prompt)).child(answer_view(308
body = body.child(prompt_bubble(&turn.prompt)).child(answer_view(266
index,309
index,267
&turn.answer,310
&turn.answer,311
&working,268
cx,312
cx,269
));313
));270
}314
}@@ -315,13 +359,13 @@ impl ConversationView {315
h_flex()359
h_flex()316
.gap(px(8.))360
.gap(px(8.))317
.items_center()361
.items_center()318
.child(copilot_logo(LOGO_TITLE))362
.child(identity_mark(local, LOGO_TITLE, theme::text()))319
.child(363
.child(320
div()364
div()321
.text_size(px(15.))365
.text_size(px(15.))322
.font_weight(FontWeight::SEMIBOLD)366
.font_weight(FontWeight::SEMIBOLD)323
.text_color(theme::text())367
.text_color(theme::text())324
.child(TITLE),368
.child(name),325
),369
),326
)370
)327
.child(371
.child(@@ -330,7 +374,7 @@ impl ConversationView {330
.ghost()374
.ghost()331
.size(px(BUTTON_SIZE))375
.size(px(BUTTON_SIZE))332
.rounded(px(8.))376
.rounded(px(8.))333
.tooltip(CLOSE_LABEL)377
.tooltip(format!("Close {}", writer_display_name(cx)))334
.on_click(cx.listener(|this, _, _, cx| {378
.on_click(cx.listener(|this, _, _, cx| {335
this.copilot.open = false;379
this.copilot.open = false;336
cx.notify();380
cx.notify();@@ -344,8 +388,33 @@ impl ConversationView {344
}388
}345
}389
}346
390
347
fn copilot_logo(size: f32) -> Img {391
fn writer_display_name(cx: &App) -> String {348
img(LOGO_ASSET).size(px(size)).flex_none()392
crate::agents::local_writer(cx)393
.map(|profile| profile.name)394
.unwrap_or_else(|| COPILOT_NAME.to_owned())395
}396
397
fn working_message(name: &str) -> String {398
format!("{name} is reading the chat ...")399
}400
401
fn failed_answer(name: &str) -> String {402
format!("{name} could not answer:")403
}404
405
fn unavailable_message(name: &str) -> String {406
format!("{name} needs a signed-in account.")407
}408
409
fn identity_mark(local: bool, size: f32, color: Hsla) -> AnyElement {410
if local {411
symbol(LOCAL_ICON, size, color).into_any_element()412
} else {413
img(LOGO_ASSET)414
.size(px(size))415
.flex_none()416
.into_any_element()417
}349
}418
}350
419
351
fn prompt_bubble(prompt: &str) -> Div {420
fn prompt_bubble(prompt: &str) -> Div {@@ -362,12 +431,12 @@ fn prompt_bubble(prompt: &str) -> Div {362
)431
)363
}432
}364
433
365
fn answer_view(index: usize, answer: &CopilotAnswer, cx: &App) -> AnyElement {434
fn answer_view(index: usize, answer: &CopilotAnswer, working: &str, cx: &App) -> AnyElement {366
match answer {435
match answer {367
CopilotAnswer::Waiting => div()436
CopilotAnswer::Waiting => div()368
.text_size(px(13.))437
.text_size(px(13.))369
.text_color(theme::text_muted())438
.text_color(theme::text_muted())370
.child(WORKING)439
.child(working.to_owned())371
.into_any_element(),440
.into_any_element(),372
CopilotAnswer::Failed(error) => div()441
CopilotAnswer::Failed(error) => div()373
.text_size(px(13.))442
.text_size(px(13.))@@ -11,7 +11,7 @@ base64.workspace = true
11
11
chrono.workspace = true
12
12
percent-encoding.workspace = true
13
13
rand = "0.9"
14
rmcp = { version = "=3.5.1", features = ["server", "macros", "transport-streamable-http-server"] }
14
rmcp = { version = "=3.5.1", features = ["server", "client", "macros", "transport-streamable-http-server", "transport-streamable-http-client-reqwest"] }
15
15
serde.workspace = true
16
16
serde_json = { workspace = true, features = ["raw_value"] }
17
17
store.workspace = true
@@ -11,7 +11,7 @@ base64.workspace = true11
chrono.workspace = true11
chrono.workspace = true12
percent-encoding.workspace = true12
percent-encoding.workspace = true13
rand = "0.9"13
rand = "0.9"14
rmcp = { version = "=3.5.1", features = ["server", "macros", "transport-streamable-http-server"] }14
rmcp = { version = "=3.5.1", features = ["server", "client", "macros", "transport-streamable-http-server", "transport-streamable-http-client-reqwest"] }15
serde.workspace = true15
serde.workspace = true16
serde_json = { workspace = true, features = ["raw_value"] }16
serde_json = { workspace = true, features = ["raw_value"] }17
store.workspace = true17
store.workspace = true@@ -3,6 +3,7 @@ mod hub;
3
3
pub mod install;
4
4
mod meetings;
5
5
mod policy;
6
mod remote;
6
7
mod server;
7
8
mod settings;
8
9
mod source;
@@ -14,6 +15,7 @@ pub use hub::{
14
15
ProposalMention, ReactionOutcome, ReactionProposal, UiEvent,
15
16
};
16
17
pub use policy::{Access, AgentPolicy, ConversationKind, DEFAULT_PORT};
18
pub use remote::{ListedTool, ToolSession};
17
19
pub use server::{ServerError, ServerHandle, start};
18
20
pub use settings::{
19
21
load as load_policy, load_or_create_token, regenerate_token, save as save_policy,
@@ -3,6 +3,7 @@ mod hub;3
pub mod install;3
pub mod install;4
mod meetings;4
mod meetings;5
mod policy;5
mod policy;6
mod remote;6
mod server;7
mod server;7
mod settings;8
mod settings;8
mod source;9
mod source;@@ -14,6 +15,7 @@ pub use hub::{14
ProposalMention, ReactionOutcome, ReactionProposal, UiEvent,15
ProposalMention, ReactionOutcome, ReactionProposal, UiEvent,15
};16
};16
pub use policy::{Access, AgentPolicy, ConversationKind, DEFAULT_PORT};17
pub use policy::{Access, AgentPolicy, ConversationKind, DEFAULT_PORT};18
pub use remote::{ListedTool, ToolSession};17
pub use server::{ServerError, ServerHandle, start};19
pub use server::{ServerError, ServerHandle, start};18
pub use settings::{20
pub use settings::{19
load as load_policy, load_or_create_token, regenerate_token, save as save_policy,21
load as load_policy, load_or_create_token, regenerate_token, save as save_policy,@@ -0,0 +1,73 @@
1
use rmcp::ServiceExt;
2
use rmcp::model::{CallToolRequestParams, ClientConfig};
3
use rmcp::transport::StreamableHttpClientTransport;
4
use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;
5
use serde_json::{Map, Value};
6
7
use crate::McpEndpoint;
8
9
#[derive(Clone, Debug, PartialEq)]
10
pub struct ListedTool {
11
pub name: String,
12
pub description: String,
13
pub parameters: Value,
14
}
15
16
pub struct ToolSession {
17
client: rmcp::service::RunningService<rmcp::RoleClient, ClientConfig>,
18
}
19
20
impl ToolSession {
21
pub async fn connect(endpoint: &McpEndpoint) -> Result<Self, String> {
22
let transport = StreamableHttpClientTransport::from_config(
23
StreamableHttpClientTransportConfig::with_uri(endpoint.url.clone())
24
.auth_header(endpoint.token.clone()),
25
);
26
let client = ClientConfig::default()
27
.serve(transport)
28
.await
29
.map_err(|error| error.to_string())?;
30
Ok(Self { client })
31
}
32
33
pub async fn tools(&self) -> Result<Vec<ListedTool>, String> {
34
let tools = self
35
.client
36
.list_all_tools()
37
.await
38
.map_err(|error| error.to_string())?;
39
Ok(tools
40
.into_iter()
41
.map(|tool| ListedTool {
42
name: tool.name.to_string(),
43
description: tool.description.unwrap_or_default().to_string(),
44
parameters: Value::Object(tool.input_schema.as_ref().clone()),
45
})
46
.collect())
47
}
48
49
pub async fn call(&self, name: &str, arguments: &str) -> Result<String, String> {
50
let parsed: Value = serde_json::from_str(arguments).unwrap_or(Value::Object(Map::new()));
51
let arguments = parsed.as_object().cloned().unwrap_or_default();
52
let params = CallToolRequestParams::new(name.to_owned()).with_arguments(arguments);
53
let result = self
54
.client
55
.call_tool(params)
56
.await
57
.map_err(|error| error.to_string())?;
58
let text = result
59
.content
60
.iter()
61
.filter_map(|content| content.as_text().map(|text| text.text.clone()))
62
.collect::<Vec<_>>()
63
.join("\n");
64
if result.is_error == Some(true) {
65
return Err(if text.is_empty() {
66
format!("{name} failed")
67
} else {
68
text
69
});
70
}
71
Ok(text)
72
}
73
}
@@ -0,0 +1,73 @@1
use rmcp::ServiceExt;2
use rmcp::model::{CallToolRequestParams, ClientConfig};3
use rmcp::transport::StreamableHttpClientTransport;4
use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;5
use serde_json::{Map, Value};6
7
use crate::McpEndpoint;8
9
#[derive(Clone, Debug, PartialEq)]10
pub struct ListedTool {11
pub name: String,12
pub description: String,13
pub parameters: Value,14
}15
16
pub struct ToolSession {17
client: rmcp::service::RunningService<rmcp::RoleClient, ClientConfig>,18
}19
20
impl ToolSession {21
pub async fn connect(endpoint: &McpEndpoint) -> Result<Self, String> {22
let transport = StreamableHttpClientTransport::from_config(23
StreamableHttpClientTransportConfig::with_uri(endpoint.url.clone())24
.auth_header(endpoint.token.clone()),25
);26
let client = ClientConfig::default()27
.serve(transport)28
.await29
.map_err(|error| error.to_string())?;30
Ok(Self { client })31
}32
33
pub async fn tools(&self) -> Result<Vec<ListedTool>, String> {34
let tools = self35
.client36
.list_all_tools()37
.await38
.map_err(|error| error.to_string())?;39
Ok(tools40
.into_iter()41
.map(|tool| ListedTool {42
name: tool.name.to_string(),43
description: tool.description.unwrap_or_default().to_string(),44
parameters: Value::Object(tool.input_schema.as_ref().clone()),45
})46
.collect())47
}48
49
pub async fn call(&self, name: &str, arguments: &str) -> Result<String, String> {50
let parsed: Value = serde_json::from_str(arguments).unwrap_or(Value::Object(Map::new()));51
let arguments = parsed.as_object().cloned().unwrap_or_default();52
let params = CallToolRequestParams::new(name.to_owned()).with_arguments(arguments);53
let result = self54
.client55
.call_tool(params)56
.await57
.map_err(|error| error.to_string())?;58
let text = result59
.content60
.iter()61
.filter_map(|content| content.as_text().map(|text| text.text.clone()))62
.collect::<Vec<_>>()63
.join("\n");64
if result.is_error == Some(true) {65
return Err(if text.is_empty() {66
format!("{name} failed")67
} else {68
text69
});70
}71
Ok(text)72
}73
}