Read-only mirror of github.com/ondeinference/ed.
Mirrored from https://github.com/ondeinference/ed.git
Synced Nov 23, 01:00 UTC
Add ed-claude, Claude on the Anthropic API key
Anthropic serves the OpenAI chat-completions API, so ed-acp's own client and workspace tools work unchanged. ClaudeAuth supplies the endpoint, the stored key and a model; the key lives in a 0600 env-style file in the agent's config dir and the process environment is never read. AuthProvider gains models(), so a provider can offer a fixed picker list when its endpoint's /models is missing or wants other credentials. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Seto Elkahfi committed
Nov 1, 2026 at 12:16 UTC
73b30f121300096836928677ab1250dcae46f4e1
10 files changed
+621
-6
Cargo.lock
+15
@@ -2096,6 +2096,21 @@ dependencies = [
2096
"uuid 1.27.0",
2097
]
2098
2099
+[[package]]
2100
+name = "ed-claude"
2101
+version = "1.3.5"
2102
+dependencies = [
2103
+ "agent-client-protocol",
2104
+ "anyhow",
2105
+ "async-trait",
2106
+ "directories",
2107
+ "ed-acp",
2108
+ "ed-acp-testkit",
2109
+ "serde_json",
2110
+ "tokio",
2111
+ "tracing",
2112
+]
2113
+
2114
[[package]]
2115
name = "ed-mcp"
2116
version = "1.3.5"
Cargo.toml
+2
@@ -10,6 +10,7 @@ members = [
10
"crates/ed-acp-tui",
11
"crates/ed-acp-testkit",
12
"crates/ed-onde-account",
13
+ "crates/ed-claude",
14
"uniffi-bindgen",
15
]
16
@@ -66,6 +67,7 @@ ed-acp-tauri = { version = "1.3.5", path = "crates/ed-acp-tauri" }
67
ed-acp-tui = { version = "1.3.5", path = "crates/ed-acp-tui" }
68
ed-acp-testkit = { version = "1.3.5", path = "crates/ed-acp-testkit" }
69
ed-onde-account = { version = "1.3.5", path = "crates/ed-onde-account" }
70
+ed-claude = { version = "1.3.5", path = "crates/ed-claude" }
71
72
# gemm-common (via candle, via onde) depends on sysctl for every
73
# `target_vendor = "apple"`, but sysctl 0.6.0 only has a `sys` module behind
crates/ed-acp/src/agent.rs
+9
-6
@@ -517,12 +517,15 @@ impl AcpServer {
517
let llm = self.llm();
518
let default = llm.model().to_string();
519
// An explicit list wins; editors show this list as the model picker.
520
- let configured: Vec<String> = std::env::var(self.env.var("MODELS"))
521
- .unwrap_or_default()
522
- .split(',')
523
- .map(|m| m.trim().to_string())
524
- .filter(|m| !m.is_empty())
525
- .collect();
520
+ let configured: Vec<String> = match self.auth.as_ref().and_then(|a| a.models()) {
521
+ Some(models) => models,
522
+ None => std::env::var(self.env.var("MODELS"))
523
+ .unwrap_or_default()
524
+ .split(',')
525
+ .map(|m| m.trim().to_string())
526
+ .filter(|m| !m.is_empty())
527
+ .collect(),
528
+ };
529
let mut ids = if !configured.is_empty() {
530
configured
531
} else {
crates/ed-acp/src/auth.rs
+7
@@ -43,6 +43,13 @@ pub trait AuthProvider: Send + Sync {
43
/// is picked up without a restart.
44
fn llm_config(&self) -> Option<LlmConfig>;
45
46
+ /// The models to offer in the picker, when the provider knows them without asking the
47
+ /// endpoint (one whose `/models` is missing or needs other credentials). `None` leaves it
48
+ /// to `<PREFIX>_MODELS`, then the endpoint.
49
+ fn models(&self) -> Option<Vec<String>> {
50
+ None
51
+ }
52
+
53
/// Run the sign-in. An existing session passes. An `Err` is shown to the user as is.
54
async fn authenticate(&self, ctx: AuthCtx<'_>) -> agent_client_protocol::Result<()>;
55
crates/ed-claude/Cargo.toml
new
+25
@@ -0,0 +1,25 @@
1
+[package]
2
+name = "ed-claude"
3
+description = "Claude as an ed-acp agent: a coding-agent profile that talks to the Anthropic API with the user's own key, for hosts that run agents in process."
4
+keywords = ["claude", "anthropic", "agent", "acp"]
5
+categories = ["development-tools"]
6
+version.workspace = true
7
+edition = "2024"
8
+rust-version.workspace = true
9
+license.workspace = true
10
+authors.workspace = true
11
+repository.workspace = true
12
+homepage.workspace = true
13
+
14
+[dependencies]
15
+ed-acp.workspace = true
16
+agent-client-protocol.workspace = true
17
+anyhow.workspace = true
18
+async-trait.workspace = true
19
+serde_json.workspace = true
20
+directories.workspace = true
21
+tracing.workspace = true
22
+
23
+[dev-dependencies]
24
+ed-acp-testkit.workspace = true
25
+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
crates/ed-claude/src/auth.rs
new
+108
@@ -0,0 +1,108 @@
1
+//! [`ClaudeAuth`]: the Anthropic API key as an `ed-acp` [`AuthProvider`].
2
+
3
+use std::path::PathBuf;
4
+
5
+use agent_client_protocol::schema::v1::{AuthMethod, AuthMethodAgent, ErrorCode};
6
+use async_trait::async_trait;
7
+use ed_acp::{AuthCtx, AuthProvider, LlmConfig, Provider};
8
+
9
+use crate::credentials;
10
+
11
+/// The id of the auth method, as the client sends it in `authenticate`.
12
+pub const METHOD_ID: &str = "anthropic-api-key";
13
+
14
+/// Anthropic's OpenAI-compatible endpoint.
15
+pub const BASE_URL: &str = "https://api.anthropic.com/v1";
16
+
17
+/// The model a session starts on when none is stored.
18
+pub const DEFAULT_MODEL: &str = "claude-sonnet-5-5";
19
+
20
+/// The models offered in the picker. Fixed here because Anthropic's `/models` may want an
21
+/// `x-api-key` header the compatibility layer doesn't take from a bearer.
22
+pub const MODELS: [&str; 3] = [DEFAULT_MODEL, "claude-opus-5-5", "claude-haiku-5-5"];
23
+
24
+/// The message `authenticate` fails with when no key is stored. A host UI that sees it asks the
25
+/// user for a key and stores it with [`credentials::store_api_key`]; `ed-acp-tauri` supports
26
+/// only URL elicitation, so the key can't be collected through the protocol.
27
+pub const API_KEY_NEEDED: &str = "Add your Anthropic API key to use Claude.";
28
+
29
+#[derive(Debug, Clone, Default)]
30
+pub struct ClaudeAuth {
31
+ base_url: Option<String>,
32
+ dir: Option<PathBuf>,
33
+}
34
+
35
+impl ClaudeAuth {
36
+ pub fn new() -> Self {
37
+ Self::default()
38
+ }
39
+
40
+ /// Talk to another endpoint, e.g. a proxy or a test server.
41
+ pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
42
+ self.base_url = Some(base_url.into().trim_end_matches('/').to_string());
43
+ self
44
+ }
45
+
46
+ /// Read the key from `dir` instead of the process-wide [`credentials::dir`].
47
+ pub fn with_dir(mut self, dir: PathBuf) -> Self {
48
+ self.dir = Some(dir);
49
+ self
50
+ }
51
+
52
+ fn stored(&self) -> Option<credentials::Stored> {
53
+ match &self.dir {
54
+ Some(dir) => credentials::load_from(dir),
55
+ None => credentials::load(),
56
+ }
57
+ }
58
+}
59
+
60
+#[async_trait]
61
+impl AuthProvider for ClaudeAuth {
62
+ fn method(&self) -> AuthMethod {
63
+ AuthMethod::Agent(
64
+ AuthMethodAgent::new(METHOD_ID, "Use an Anthropic API key")
65
+ .description("Claude through the Anthropic API, billed to your API key."),
66
+ )
67
+ }
68
+
69
+ fn llm_config(&self) -> Option<LlmConfig> {
70
+ let stored = self.stored()?;
71
+ let model = stored
72
+ .model
73
+ .filter(|m| MODELS.contains(&m.as_str()))
74
+ .unwrap_or_else(|| DEFAULT_MODEL.to_string());
75
+ Some(LlmConfig {
76
+ provider: Provider::OpenAi,
77
+ base_url: self
78
+ .base_url
79
+ .clone()
80
+ .unwrap_or_else(|| BASE_URL.to_string()),
81
+ api_key: Some(stored.api_key),
82
+ model,
83
+ })
84
+ }
85
+
86
+ fn models(&self) -> Option<Vec<String>> {
87
+ Some(MODELS.iter().map(|m| m.to_string()).collect())
88
+ }
89
+
90
+ async fn authenticate(&self, _ctx: AuthCtx<'_>) -> agent_client_protocol::Result<()> {
91
+ if self.stored().is_some() {
92
+ return Ok(());
93
+ }
94
+ Err(agent_client_protocol::Error::new(
95
+ ErrorCode::InternalError.into(),
96
+ API_KEY_NEEDED.to_string(),
97
+ ))
98
+ }
99
+
100
+ async fn logout(&self) -> anyhow::Result<()> {
101
+ let removed = match &self.dir {
102
+ Some(dir) => credentials::clear_in(dir),
103
+ None => credentials::clear(),
104
+ };
105
+ tracing::info!("logout: stored Anthropic key removed: {removed}");
106
+ Ok(())
107
+ }
108
+}
crates/ed-claude/src/credentials.rs
new
+170
@@ -0,0 +1,170 @@
1
+//! The stored Anthropic API key and chosen model.
2
+//!
3
+//! An `env`-style file (`ED_CLAUDE_API_KEY=...`, `ED_CLAUDE_MODEL=...`) at mode 0600 in the
4
+//! agent's config dir. A host sets that dir once with [`set_dir`]; in a sandboxed app it is
5
+//! inside the container, so the app never shares a key with anything outside it. The
6
+//! functions here only read that file, never the process environment.
7
+
8
+use std::path::{Path, PathBuf};
9
+use std::sync::OnceLock;
10
+
11
+use directories::BaseDirs;
12
+
13
+use crate::profile::INFO;
14
+
15
+const FILE: &str = "env";
16
+const KEY_VAR: &str = "ED_CLAUDE_API_KEY";
17
+const MODEL_VAR: &str = "ED_CLAUDE_MODEL";
18
+
19
+static DIR: OnceLock<PathBuf> = OnceLock::new();
20
+
21
+/// What is stored: the key, and the model chosen with it.
22
+#[derive(Debug, Clone, PartialEq, Eq)]
23
+pub struct Stored {
24
+ pub api_key: String,
25
+ pub model: Option<String>,
26
+}
27
+
28
+/// Keep the key in `dir` instead of the platform config dir. The first call wins.
29
+pub fn set_dir(dir: PathBuf) {
30
+ if let Err(rejected) = DIR.set(dir) {
31
+ tracing::warn!(
32
+ "ed-claude config dir is already {:?}; ignoring {rejected:?}",
33
+ DIR.get()
34
+ );
35
+ }
36
+}
37
+
38
+/// The dir [`set_dir`] chose, else `<config dir>/edclaude`.
39
+pub fn dir() -> Option<PathBuf> {
40
+ if let Some(dir) = DIR.get() {
41
+ return Some(dir.clone());
42
+ }
43
+ Some(BaseDirs::new()?.config_dir().join(INFO.env.dir_name))
44
+}
45
+
46
+/// Store `api_key`, and `model` when given, replacing what was there.
47
+pub fn store_api_key(api_key: &str, model: Option<&str>) -> Result<(), String> {
48
+ let dir = dir().ok_or("cannot resolve the config directory")?;
49
+ store_in(&dir, api_key, model)
50
+}
51
+
52
+/// The stored key and model, or `None` when no key is stored.
53
+pub fn load() -> Option<Stored> {
54
+ load_from(&dir()?)
55
+}
56
+
57
+/// Delete the stored key. Returns `true` if a file was removed.
58
+pub fn clear() -> bool {
59
+ dir().is_some_and(|dir| clear_in(&dir))
60
+}
61
+
62
+/// For tests of this crate and its dependents: store into `dir` rather than the shared one.
63
+#[doc(hidden)]
64
+pub fn store_in_for_tests(dir: &Path, api_key: &str, model: Option<&str>) {
65
+ store_in(dir, api_key, model).expect("store");
66
+}
67
+
68
+pub(crate) fn store_in(dir: &Path, api_key: &str, model: Option<&str>) -> Result<(), String> {
69
+ let api_key = api_key.trim();
70
+ if api_key.is_empty() || api_key.contains(['\n', '\r']) {
71
+ return Err("the API key is empty or spans lines".to_string());
72
+ }
73
+ std::fs::create_dir_all(dir).map_err(|e| format!("create {dir:?}: {e}"))?;
74
+ let mut body = format!("{KEY_VAR}={api_key}\n");
75
+ if let Some(model) = model.map(str::trim).filter(|m| !m.is_empty()) {
76
+ body.push_str(&format!("{MODEL_VAR}={model}\n"));
77
+ }
78
+ let path = dir.join(FILE);
79
+ write_private(&path, &body).map_err(|e| format!("write {path:?}: {e}"))
80
+}
81
+
82
+pub(crate) fn load_from(dir: &Path) -> Option<Stored> {
83
+ let text = std::fs::read_to_string(dir.join(FILE)).ok()?;
84
+ let value = |name: &str| {
85
+ text.lines()
86
+ .find_map(|line| line.strip_prefix(name)?.strip_prefix('='))
87
+ .map(str::trim)
88
+ .filter(|v| !v.is_empty())
89
+ .map(str::to_string)
90
+ };
91
+ Some(Stored {
92
+ api_key: value(KEY_VAR)?,
93
+ model: value(MODEL_VAR),
94
+ })
95
+}
96
+
97
+pub(crate) fn clear_in(dir: &Path) -> bool {
98
+ std::fs::remove_file(dir.join(FILE)).is_ok()
99
+}
100
+
101
+#[cfg(unix)]
102
+fn write_private(path: &Path, contents: &str) -> std::io::Result<()> {
103
+ use std::io::Write;
104
+ use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
105
+ // Created at 0600 so the key is never readable by others, even briefly.
106
+ let mut file = std::fs::OpenOptions::new()
107
+ .write(true)
108
+ .create(true)
109
+ .truncate(true)
110
+ .mode(0o600)
111
+ .open(path)?;
112
+ file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
113
+ file.write_all(contents.as_bytes())
114
+}
115
+
116
+#[cfg(not(unix))]
117
+fn write_private(path: &Path, contents: &str) -> std::io::Result<()> {
118
+ std::fs::write(path, contents)
119
+}
120
+
121
+#[cfg(test)]
122
+mod tests {
123
+ use super::*;
124
+
125
+ fn scratch(name: &str) -> PathBuf {
126
+ let dir = std::env::temp_dir().join(format!("ed-claude-{name}-{}", std::process::id()));
127
+ let _ = std::fs::remove_dir_all(&dir);
128
+ dir
129
+ }
130
+
131
+ #[test]
132
+ fn round_trips_the_key_and_model() {
133
+ let dir = scratch("roundtrip");
134
+ assert_eq!(load_from(&dir), None);
135
+ store_in(&dir, " sk-ant-1 ", Some("claude-opus-5-5")).unwrap();
136
+ assert_eq!(
137
+ load_from(&dir),
138
+ Some(Stored {
139
+ api_key: "sk-ant-1".into(),
140
+ model: Some("claude-opus-5-5".into())
141
+ })
142
+ );
143
+ store_in(&dir, "sk-ant-2", None).unwrap();
144
+ assert_eq!(load_from(&dir).unwrap().model, None);
145
+ assert!(clear_in(&dir));
146
+ assert_eq!(load_from(&dir), None);
147
+ let _ = std::fs::remove_dir_all(&dir);
148
+ }
149
+
150
+ #[test]
151
+ fn rejects_a_key_that_would_corrupt_the_file() {
152
+ let dir = scratch("reject");
153
+ assert!(store_in(&dir, "", None).is_err());
154
+ assert!(store_in(&dir, "a\nED_CLAUDE_MODEL=x", None).is_err());
155
+ }
156
+
157
+ #[cfg(unix)]
158
+ #[test]
159
+ fn the_file_is_private() {
160
+ use std::os::unix::fs::PermissionsExt;
161
+ let dir = scratch("mode");
162
+ store_in(&dir, "sk-ant-1", None).unwrap();
163
+ let mode = std::fs::metadata(dir.join(FILE))
164
+ .unwrap()
165
+ .permissions()
166
+ .mode();
167
+ assert_eq!(mode & 0o777, 0o600);
168
+ let _ = std::fs::remove_dir_all(&dir);
169
+ }
170
+}
crates/ed-claude/src/lib.rs
new
+17
@@ -0,0 +1,17 @@
1
+//! Claude as an `ed-acp` agent, for hosts that run agents in process.
2
+//!
3
+//! Anthropic serves the OpenAI chat-completions API at `https://api.anthropic.com/v1/`, with
4
+//! streaming and tool calls, so `ed-acp`'s own client, workspace tools, permissions and
5
+//! `fs/*` work unchanged. [`ClaudeAuth`] supplies the endpoint, the user's API key and a model
6
+//! through [`AuthProvider::llm_config`]. The environment is never read: the key and model come
7
+//! from the file [`credentials`] keeps, so nothing collides with `OPENAI_*` or `ONDE_*`.
8
+//!
9
+//! This is the API-key mode only. A Claude.ai subscription goes through Anthropic's own
10
+//! `claude` CLI, which a host runs as an external agent instead.
11
+
12
+pub mod auth;
13
+pub mod credentials;
14
+pub mod profile;
15
+
16
+pub use auth::{API_KEY_NEEDED, ClaudeAuth, DEFAULT_MODEL, MODELS};
17
+pub use profile::{Claude, INFO};
crates/ed-claude/src/profile.rs
new
+151
@@ -0,0 +1,151 @@
1
+//! Claude's [`Profile`]: who the agent is, its prompt, and the workspace tools.
2
+
3
+use std::sync::Arc;
4
+
5
+use async_trait::async_trait;
6
+use ed_acp::{
7
+ AgentInfo, AuthProvider, DescribeCtx, LlmEnv, Profile, PromptCtx, ToolCtx, ToolOutcome,
8
+ Toolset, WorkspaceTools,
9
+};
10
+use serde_json::Value;
11
+
12
+use crate::auth::{ClaudeAuth, DEFAULT_MODEL};
13
+
14
+pub const INFO: AgentInfo = AgentInfo {
15
+ name: "claude",
16
+ display_name: "Claude",
17
+ version: env!("CARGO_PKG_VERSION"),
18
+ env: LlmEnv {
19
+ prefix: "ED_CLAUDE",
20
+ dir_name: "edclaude",
21
+ default_model: DEFAULT_MODEL,
22
+ },
23
+};
24
+
25
+const NO_SHELL_NOTE: &str = "\n\nThis host cannot run commands: there is no run_command tool, \
26
+ and no git or shell. When something needs a command, say which one and let the user run it.";
27
+
28
+/// Claude as an `ed-acp` agent that uses the user's Anthropic API key.
29
+#[derive(Debug, Clone)]
30
+pub struct Claude {
31
+ shell: bool,
32
+ auth: ClaudeAuth,
33
+}
34
+
35
+impl Claude {
36
+ /// With the workspace tools, `run_command` included.
37
+ pub fn new() -> Self {
38
+ Self {
39
+ shell: true,
40
+ auth: ClaudeAuth::new(),
41
+ }
42
+ }
43
+
44
+ /// For hosts that cannot start processes (an iOS app, a sandboxed Mac app): the workspace
45
+ /// tools without `run_command`, and a prompt that says so.
46
+ pub fn without_shell() -> Self {
47
+ Self {
48
+ shell: false,
49
+ auth: ClaudeAuth::new(),
50
+ }
51
+ }
52
+
53
+ /// Use `auth` instead of the default, e.g. one pointed at another endpoint.
54
+ pub fn with_auth(mut self, auth: ClaudeAuth) -> Self {
55
+ self.auth = auth;
56
+ self
57
+ }
58
+}
59
+
60
+impl Default for Claude {
61
+ fn default() -> Self {
62
+ Self::new()
63
+ }
64
+}
65
+
66
+/// `WorkspaceTools` minus `run_command`.
67
+struct FileTools;
68
+
69
+#[async_trait]
70
+impl Toolset for FileTools {
71
+ fn definitions(&self) -> Vec<Value> {
72
+ WorkspaceTools
73
+ .definitions()
74
+ .into_iter()
75
+ .filter(|d| d["function"]["name"] != "run_command")
76
+ .collect()
77
+ }
78
+
79
+ fn handles(&self, name: &str) -> bool {
80
+ name != "run_command" && WorkspaceTools.handles(name)
81
+ }
82
+
83
+ fn describe(
84
+ &self,
85
+ name: &str,
86
+ args: &Value,
87
+ ctx: &DescribeCtx<'_>,
88
+ ) -> (
89
+ String,
90
+ agent_client_protocol::schema::v1::ToolKind,
91
+ Vec<agent_client_protocol::schema::v1::ToolCallLocation>,
92
+ ) {
93
+ WorkspaceTools.describe(name, args, ctx)
94
+ }
95
+
96
+ async fn execute(
97
+ &self,
98
+ ctx: &ToolCtx,
99
+ tool_call_id: &str,
100
+ name: &str,
101
+ args: Value,
102
+ ) -> anyhow::Result<ToolOutcome> {
103
+ if name == "run_command" {
104
+ anyhow::bail!("This host cannot run commands.");
105
+ }
106
+ WorkspaceTools.execute(ctx, tool_call_id, name, args).await
107
+ }
108
+}
109
+
110
+#[async_trait]
111
+impl Profile for Claude {
112
+ fn info(&self) -> AgentInfo {
113
+ INFO
114
+ }
115
+
116
+ fn system_prompt(&self, ctx: &PromptCtx<'_>) -> String {
117
+ let tools = if self.shell {
118
+ "read_file, write_file, edit_file, list_directory and run_command"
119
+ } else {
120
+ "read_file, write_file, edit_file and list_directory"
121
+ };
122
+ let mut prompt = format!(
123
+ "You are Claude, an autonomous coding agent working inside the user's editor.\n\
124
+ Use your tools to inspect and change the project: read files before editing them, \
125
+ prefer edit_file for small changes, and use write_file to create files. Your tools \
126
+ are {tools}, plus those of any connected MCP servers. Keep answers concise and use \
127
+ Markdown."
128
+ );
129
+ if !self.shell {
130
+ prompt.push_str(NO_SHELL_NOTE);
131
+ }
132
+ prompt.push_str(&format!("\n\nWorking directory: {}", ctx.cwd.display()));
133
+ if ctx.roots.len() > 1 {
134
+ let roots: Vec<String> = ctx.roots.iter().map(|r| r.display().to_string()).collect();
135
+ prompt.push_str(&format!("\nProject roots: {}", roots.join(", ")));
136
+ }
137
+ prompt
138
+ }
139
+
140
+ fn auth(&self) -> Option<Arc<dyn AuthProvider>> {
141
+ Some(Arc::new(self.auth.clone()))
142
+ }
143
+
144
+ fn toolsets(&self) -> Vec<Arc<dyn Toolset>> {
145
+ if self.shell {
146
+ vec![Arc::new(WorkspaceTools)]
147
+ } else {
148
+ vec![Arc::new(FileTools)]
149
+ }
150
+ }
151
+}
crates/ed-claude/tests/turn.rs
new
+117
@@ -0,0 +1,117 @@
1
+//! `Claude` against a mock OpenAI-compatible endpoint: the stored key becomes the bearer, a
2
+//! streamed tool-call turn round-trips, and the process environment is never consulted.
3
+
4
+use std::sync::Arc;
5
+
6
+use agent_client_protocol::schema::ProtocolVersion;
7
+use agent_client_protocol::schema::v1::{
8
+ ContentBlock, InitializeRequest, NewSessionRequest, PromptRequest, StopReason, TextContent,
9
+};
10
+use agent_client_protocol::{Agent, Channel, Client, ConnectionTo};
11
+use ed_acp::{AuthProvider, ServeOptions};
12
+use ed_acp_testkit::{MockStats, Script, Step, TEST_KEY, start_mock_llm, temp_dir};
13
+use ed_claude::{Claude, ClaudeAuth, DEFAULT_MODEL, MODELS, credentials};
14
+use serde_json::json;
15
+
16
+#[test]
17
+fn no_key_means_no_llm_config_even_with_provider_env_set() {
18
+ let dir = temp_dir("ed-claude-nokey");
19
+ // SAFETY: only this test touches these variables, and nothing reads them concurrently.
20
+ unsafe {
21
+ std::env::set_var("OPENAI_API_KEY", "sk-from-env");
22
+ std::env::set_var("ED_CLAUDE_API_KEY", "sk-from-env");
23
+ std::env::set_var("ONDE_API_KEY", "app:secret");
24
+ }
25
+ let auth = ClaudeAuth::new().with_dir(dir.clone());
26
+ assert!(auth.llm_config().is_none());
27
+ unsafe {
28
+ std::env::remove_var("OPENAI_API_KEY");
29
+ std::env::remove_var("ED_CLAUDE_API_KEY");
30
+ std::env::remove_var("ONDE_API_KEY");
31
+ }
32
+}
33
+
34
+#[test]
35
+fn llm_config_uses_the_stored_key_and_model() {
36
+ let dir = temp_dir("ed-claude-config");
37
+ let auth = ClaudeAuth::new().with_dir(dir.clone());
38
+ credentials::store_in_for_tests(&dir, "sk-ant-1", Some("claude-opus-5-5"));
39
+ let config = auth.llm_config().expect("config");
40
+ assert_eq!(config.base_url, "https://api.anthropic.com/v1");
41
+ assert_eq!(config.api_key.as_deref(), Some("sk-ant-1"));
42
+ assert_eq!(config.model, "claude-opus-5-5");
43
+
44
+ // A model outside the offered list falls back to the default.
45
+ credentials::store_in_for_tests(&dir, "sk-ant-1", Some("gpt-4o"));
46
+ assert_eq!(auth.llm_config().unwrap().model, DEFAULT_MODEL);
47
+ assert_eq!(auth.models().unwrap(), MODELS.map(String::from).to_vec());
48
+}
49
+
50
+#[tokio::test]
51
+async fn a_streamed_tool_call_turn_round_trips() {
52
+ let data = temp_dir("ed-claude-data");
53
+ let key_dir = temp_dir("ed-claude-keys");
54
+ let work = temp_dir("ed-claude-work");
55
+ std::fs::write(work.join("hello.txt"), "hi").unwrap();
56
+ // SAFETY: set before the agent starts; only the data dir, no credentials.
57
+ unsafe { std::env::set_var("ED_CLAUDE_DATA_DIR", &data) };
58
+ credentials::store_in_for_tests(&key_dir, TEST_KEY, None);
59
+
60
+ let stats = Arc::new(MockStats::default());
61
+ let script = Script(vec![
62
+ Step::ToolCall {
63
+ name: "list_directory",
64
+ arguments: json!({"path": "."}),
65
+ },
66
+ Step::Final("done"),
67
+ ]);
68
+ let base = start_mock_llm(script, stats.clone()).await;
69
+ let auth = ClaudeAuth::new().with_base_url(base).with_dir(key_dir);
70
+
71
+ let (agent_end, client_end) = Channel::duplex();
72
+ let opts = ServeOptions {
73
+ yolo: true,
74
+ surface: "app",
75
+ };
76
+ tokio::spawn(ed_acp::serve(
77
+ Arc::new(Claude::without_shell().with_auth(auth)),
78
+ opts,
79
+ agent_end,
80
+ ));
81
+
82
+ let stop = Client
83
+ .builder()
84
+ .connect_with(client_end, |conn: ConnectionTo<Agent>| async move {
85
+ conn.send_request(InitializeRequest::new(ProtocolVersion::V1))
86
+ .block_task()
87
+ .await?;
88
+ let session = conn
89
+ .send_request(NewSessionRequest::new(work.clone()))
90
+ .block_task()
91
+ .await?;
92
+ let reply = conn
93
+ .send_request(PromptRequest::new(
94
+ session.session_id,
95
+ vec![ContentBlock::Text(TextContent::new("list the files"))],
96
+ ))
97
+ .block_task()
98
+ .await?;
99
+ Ok(reply.stop_reason)
100
+ })
101
+ .await
102
+ .expect("turn");
103
+
104
+ assert_eq!(stop, StopReason::EndTurn);
105
+ assert!(*stats.saw_bearer.lock().unwrap(), "the key is the bearer");
106
+ let payloads = stats.payloads.lock().unwrap();
107
+ assert_eq!(payloads.len(), 2, "tool call, then the answer");
108
+ assert_eq!(payloads[0]["model"], DEFAULT_MODEL);
109
+ let names: Vec<_> = payloads[0]["tools"]
110
+ .as_array()
111
+ .unwrap()
112
+ .iter()
113
+ .map(|t| t["function"]["name"].as_str().unwrap().to_string())
114
+ .collect();
115
+ assert!(names.contains(&"edit_file".to_string()));
116
+ assert!(!names.contains(&"run_command".to_string()), "no shell");
117
+}