Skip to main content

rinne_workers/adapters/
claude_code.rs

1//! Claude Code adapter (`CONTEXT.md` §9, §16).
2//!
3//! Drives the native `claude -p --output-format json` call, which honors the
4//! Pro/Max subscription login — never the ACP adapter, which would force an
5//! Anthropic API key (`CONTEXT.md` §9). The footgun guard for a stray
6//! `ANTHROPIC_API_KEY` lives in `doctor` (Phase 1).
7
8use std::path::Path;
9use std::time::Duration;
10
11use serde_json::{json, Map, Value};
12
13use rinne_core::worker::{
14    AuthMode, Capability, LatencyProfile, McpServerSpec, McpTransportKind, QuotaModel, Transport,
15    Usage, WorkerDescriptor, WorkerEvent, WorkerFamily,
16};
17use rinne_core::{Result, RinneError};
18
19use super::common::{HarnessAdapter, ParsedHarness, Provision};
20use crate::transport::subprocess::SubprocessOutput;
21
22/// Construct a Claude Code harness worker.
23pub fn worker() -> HarnessAdapter {
24    HarnessAdapter {
25        descriptor: descriptor(),
26        program: "claude".to_string(),
27        build_args,
28        plan_args: Some(plan_args),
29        parse,
30        line_mapper,
31        prompt_via_stdin: false,
32        default_timeout: Duration::from_secs(600),
33        provisioner: Some(provision),
34    }
35}
36
37/// Lean argv for the planner role: a plain `claude -p "<prompt>"` print, with no
38/// `stream-json`/`--verbose` (which some CLI versions reject, and which we don't
39/// need just to read a JSON plan). stdout is the answer text.
40fn plan_args(prompt: &str, model: Option<&str>) -> Vec<String> {
41    let mut args = vec!["-p".into(), prompt.into()];
42    if let Some(m) = model {
43        args.push("--model".into());
44        args.push(m.into());
45    }
46    args
47}
48
49fn descriptor() -> WorkerDescriptor {
50    WorkerDescriptor {
51        name: "claude-code".to_string(),
52        family: WorkerFamily::Harness,
53        capabilities: vec![
54            Capability::CodeEdit,
55            Capability::RepoAware,
56            Capability::CodeReview,
57            Capability::Reasoning,
58            Capability::LongContext,
59            Capability::Writing,
60            Capability::ToolRun,
61        ],
62        auth_mode: AuthMode::Subscription,
63        // Conservative subscription rate-limit window; tuned by live quota state
64        // in the scheduler (Phase 3).
65        quota: QuotaModel {
66            capacity: 200_000.0,
67            refill_per_minute: 20_000.0,
68        },
69        latency: LatencyProfile::Medium,
70        transport: Transport::SubprocessJson,
71        // Claude `--model` aliases, listed cheap→strong (the cascade ladder).
72        models: vec!["haiku".into(), "sonnet".into(), "opus".into()],
73    }
74}
75
76fn build_args(prompt: &str, model: Option<&str>) -> Vec<String> {
77    // `stream-json` emits one NDJSON event per line as work happens, so the user
78    // sees reads/edits/commands live instead of one blob at the end. `--verbose`
79    // is required to stream events under `-p`.
80    let mut args = vec![
81        "-p".into(),
82        prompt.into(),
83        "--output-format".into(),
84        "stream-json".into(),
85        "--verbose".into(),
86    ];
87    if let Some(m) = model {
88        args.push("--model".into());
89        args.push(m.into());
90    }
91    args
92}
93
94/// Parse Claude Code's stream-json output: find the terminal `result` event
95/// (a line with `"type":"result"` or a `result` field) and extract its fields.
96fn parse(out: &SubprocessOutput) -> ParsedHarness {
97    for line in out.stdout.lines().rev() {
98        let line = line.trim();
99        if line.is_empty() {
100            continue;
101        }
102        let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
103            continue;
104        };
105        let is_result = value.get("type").and_then(|t| t.as_str()) == Some("result")
106            || value.get("result").is_some();
107        if !is_result {
108            continue;
109        }
110
111        let result = value
112            .get("result")
113            .and_then(|v| v.as_str())
114            .map(|s| s.to_string())
115            .unwrap_or_default();
116        let session_id = value
117            .get("session_id")
118            .and_then(|v| v.as_str())
119            .map(|s| s.to_string());
120        let is_error = value.get("is_error").and_then(|v| v.as_bool()).unwrap_or(false);
121        let usage = value
122            .get("usage")
123            .map(|u| Usage {
124                prompt_tokens: u.get("input_tokens").and_then(|v| v.as_u64()).unwrap_or(0),
125                completion_tokens: u.get("output_tokens").and_then(|v| v.as_u64()).unwrap_or(0),
126                wall_ms: 0,
127            })
128            .unwrap_or_default();
129        return ParsedHarness {
130            result,
131            session_id,
132            usage,
133            is_error,
134        };
135    }
136    ParsedHarness::raw(&out.stdout)
137}
138
139/// Map one NDJSON stream event into live worker events. An assistant message can
140/// carry several content blocks (text + tool uses), so this returns a vector.
141fn line_mapper(line: &str) -> Vec<WorkerEvent> {
142    let line = line.trim();
143    if line.is_empty() {
144        return Vec::new();
145    }
146    let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
147        return Vec::new();
148    };
149
150    match value.get("type").and_then(|t| t.as_str()) {
151        // The init event names the model the harness is actually running.
152        Some("system") => {
153            if value.get("subtype").and_then(|s| s.as_str()) == Some("init") {
154                if let Some(model) = value.get("model").and_then(|m| m.as_str()) {
155                    return vec![WorkerEvent::Message(format!("model: {}", short_model(model)))];
156                }
157            }
158            return Vec::new();
159        }
160        // Assistant messages carry text + tool uses (handled below).
161        Some("assistant") => {}
162        // Suppress tool_result and the final result event (parsed separately).
163        _ => return Vec::new(),
164    }
165
166    let Some(content) = value.pointer("/message/content").and_then(|c| c.as_array()) else {
167        return Vec::new();
168    };
169
170    let mut events = Vec::new();
171    for block in content {
172        match block.get("type").and_then(|t| t.as_str()) {
173            Some("text") => {
174                if let Some(text) = block.get("text").and_then(|t| t.as_str()) {
175                    let text = text.trim();
176                    if !text.is_empty() {
177                        events.push(WorkerEvent::Message(text.to_string()));
178                    }
179                }
180            }
181            Some("tool_use") => {
182                let name = block.get("name").and_then(|n| n.as_str()).unwrap_or("tool");
183                let input = block.get("input").cloned().unwrap_or(serde_json::Value::Null);
184                events.push(tool_event(name, &input));
185            }
186            _ => {}
187        }
188    }
189    events
190}
191
192/// Render a Claude tool call as a friendly, harness-style line.
193fn tool_event(name: &str, input: &serde_json::Value) -> WorkerEvent {
194    let s = |k: &str| input.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string();
195    match name {
196        "Read" => WorkerEvent::Reading(short_path(&s("file_path"))),
197        "Write" => WorkerEvent::Editing(format!("writing {}", short_path(&s("file_path")))),
198        "Edit" | "MultiEdit" | "NotebookEdit" => {
199            WorkerEvent::Editing(format!("editing {}", short_path(&s("file_path"))))
200        }
201        "Bash" => {
202            let desc = s("description");
203            let cmd = s("command");
204            WorkerEvent::ToolUse(if desc.is_empty() { truncate(&cmd, 80) } else { desc })
205        }
206        "Glob" => WorkerEvent::ToolUse(format!("glob {}", s("pattern"))),
207        "Grep" => WorkerEvent::ToolUse(format!("grep {}", s("pattern"))),
208        "Task" => WorkerEvent::ToolUse(format!("subagent: {}", s("description"))),
209        "TodoWrite" => WorkerEvent::Message("updating plan".into()),
210        "WebSearch" => WorkerEvent::ToolUse(format!("web search {}", s("query"))),
211        "WebFetch" => WorkerEvent::ToolUse(format!("fetch {}", s("url"))),
212        other => WorkerEvent::ToolUse(other.to_string()),
213    }
214}
215
216/// Friendly model label: `claude-opus-4-8[1m]` → `opus-4-8`.
217fn short_model(m: &str) -> String {
218    m.split_once("[1m]")
219        .map(|(a, _)| a)
220        .unwrap_or(m)
221        .strip_prefix("claude-")
222        .unwrap_or(m)
223        .to_string()
224}
225
226/// Show the last two path segments so lines stay readable.
227fn short_path(p: &str) -> String {
228    let parts: Vec<&str> = p.rsplit('/').take(2).collect();
229    parts.into_iter().rev().collect::<Vec<_>>().join("/")
230}
231
232fn truncate(s: &str, max: usize) -> String {
233    if s.chars().count() <= max {
234        s.to_string()
235    } else {
236        s.chars().take(max).collect::<String>() + "…"
237    }
238}
239
240/// Provision a node's MCP servers into a `claude` invocation (`MCP_SKILLS.md`
241/// §6). Writes a `.mcp.json`-shaped config and returns `--mcp-config <path>`
242/// `--strict-mcp-config` (only our servers) and `--allowedTools mcp__<server>…`
243/// (pre-approve the tools for the non-interactive `-p` run).
244///
245/// Secrets stay off disk: a token is written as a `${VAR}` reference and the
246/// real value is set on the subprocess environment, which Claude expands.
247fn provision(servers: &[McpServerSpec], scratch: &Path) -> Result<Provision> {
248    let mut mcp_servers = Map::new();
249    let mut env = Vec::new();
250    let mut allowed = Vec::new();
251
252    for (i, s) in servers.iter().enumerate() {
253        allowed.push(format!("mcp__{}", s.name));
254        let mut entry = Map::new();
255        match s.transport {
256            McpTransportKind::Stdio => {
257                entry.insert("command".into(), json!(s.command.clone().unwrap_or_default()));
258                entry.insert("args".into(), json!(s.args));
259                let mut env_map = Map::new();
260                for (k, v) in &s.env {
261                    env_map.insert(k.clone(), json!(v));
262                }
263                if let Some(token) = &s.token {
264                    // The server reads its token from its auth env var; reference
265                    // it through a host env var so the value never lands in the file.
266                    if let Some(var) = s.stdio_auth_env().or_else(|| s.token_env.clone()) {
267                        let host_var = host_env_var(i, &s.name);
268                        env_map.insert(var, json!(format!("${{{host_var}}}")));
269                        env.push((host_var, token.clone()));
270                    }
271                }
272                if !env_map.is_empty() {
273                    entry.insert("env".into(), Value::Object(env_map));
274                }
275            }
276            McpTransportKind::Http => {
277                entry.insert("type".into(), json!("http"));
278                entry.insert("url".into(), json!(s.url.clone().unwrap_or_default()));
279                let mut headers = Map::new();
280                for (k, v) in &s.headers {
281                    headers.insert(k.clone(), json!(v));
282                }
283                if let Some(token) = &s.token {
284                    // The configured auth header (bearer by default, or a custom
285                    // API-key header), with the token via env expansion.
286                    let (header, prefix) = s.http_auth();
287                    let host_var = host_env_var(i, &s.name);
288                    headers.insert(header, json!(format!("{prefix}${{{host_var}}}")));
289                    env.push((host_var, token.clone()));
290                }
291                if !headers.is_empty() {
292                    entry.insert("headers".into(), Value::Object(headers));
293                }
294            }
295        }
296        mcp_servers.insert(s.name.clone(), Value::Object(entry));
297    }
298
299    let config = json!({ "mcpServers": Value::Object(mcp_servers) });
300    std::fs::create_dir_all(scratch)
301        .map_err(|e| RinneError::Worker(format!("could not create MCP scratch dir: {e}")))?;
302    let path = scratch.join(format!("mcp-{}-{}.json", std::process::id(), unique_suffix()));
303    std::fs::write(&path, serde_json::to_vec_pretty(&config).unwrap_or_default())
304        .map_err(|e| RinneError::Worker(format!("could not write MCP config: {e}")))?;
305
306    let args = vec![
307        "--mcp-config".to_string(),
308        path.display().to_string(),
309        "--strict-mcp-config".to_string(),
310        "--allowedTools".to_string(),
311        allowed.join(","),
312    ];
313    Ok(Provision {
314        args,
315        env,
316        cleanup: Some(path),
317    })
318}
319
320/// A host environment variable name to carry a server's token to the subprocess.
321/// The index keeps the name unique even when two server names differ only by
322/// punctuation (e.g. `fs.x` and `fs-x` both sanitize to `FS_X`).
323fn host_env_var(index: usize, server: &str) -> String {
324    let up: String = server
325        .chars()
326        .map(|c| if c.is_alphanumeric() { c.to_ascii_uppercase() } else { '_' })
327        .collect();
328    format!("RINNE_MCP_{index}_{up}_TOKEN")
329}
330
331/// A process-unique suffix for the scratch config filename (no `rand` dep).
332fn unique_suffix() -> u128 {
333    std::time::SystemTime::now()
334        .duration_since(std::time::UNIX_EPOCH)
335        .map(|d| d.as_nanos())
336        .unwrap_or(0)
337}
338
339/// Find the last top-level JSON object in mixed output (some CLIs prepend logs).
340pub(crate) fn last_json_object(s: &str) -> Option<serde_json::Value> {
341    // Try whole-string parse first (the common case).
342    if let Ok(v) = serde_json::from_str::<serde_json::Value>(s.trim()) {
343        if v.is_object() {
344            return Some(v);
345        }
346    }
347    // Otherwise scan lines from the end for a parseable object.
348    for line in s.lines().rev() {
349        let line = line.trim();
350        if line.starts_with('{') {
351            if let Ok(v) = serde_json::from_str::<serde_json::Value>(line) {
352                return Some(v);
353            }
354        }
355    }
356    None
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362
363    fn out(stdout: &str) -> SubprocessOutput {
364        SubprocessOutput {
365            stdout: stdout.to_string(),
366            stderr: String::new(),
367            exit_code: Some(0),
368            status: rinne_core::worker::ExecStatus::Success,
369            wall_ms: 5,
370        }
371    }
372
373    #[test]
374    fn parses_claude_json_result() {
375        let json = r#"{"type":"result","is_error":false,"result":"pong","session_id":"abc","usage":{"input_tokens":12,"output_tokens":3}}"#;
376        let p = parse(&out(json));
377        assert_eq!(p.result, "pong");
378        assert_eq!(p.session_id.as_deref(), Some("abc"));
379        assert_eq!(p.usage.prompt_tokens, 12);
380        assert_eq!(p.usage.completion_tokens, 3);
381        assert!(!p.is_error);
382    }
383
384    #[test]
385    fn flags_is_error_true() {
386        let json = r#"{"is_error":true,"result":"boom"}"#;
387        let p = parse(&out(json));
388        assert!(p.is_error);
389    }
390
391    #[test]
392    fn falls_back_to_raw_on_non_json() {
393        let p = parse(&out("not json at all"));
394        assert_eq!(p.result, "not json at all");
395        assert!(!p.is_error);
396    }
397
398    #[test]
399    fn finds_json_after_log_lines() {
400        let mixed = "INFO starting\nWARN something\n{\"result\":\"hi\"}";
401        let p = parse(&out(mixed));
402        assert_eq!(p.result, "hi");
403    }
404
405    #[test]
406    fn provision_writes_config_and_keeps_tokens_off_disk() {
407        let dir = std::env::temp_dir().join(format!("rinne-prov-{}", std::process::id()));
408        let _ = std::fs::remove_dir_all(&dir);
409        let servers = vec![
410            McpServerSpec {
411                name: "fs".into(),
412                transport: McpTransportKind::Stdio,
413                command: Some("npx".into()),
414                args: vec!["-y".into(), "server".into()],
415                env: vec![],
416                url: None,
417                headers: vec![],
418                token_env: Some("GITHUB_TOKEN".into()),
419                token: Some("secret123".into()),
420                auth: Some("env".into()),
421                auth_header: Some("GITHUB_TOKEN".into()),
422            },
423            McpServerSpec {
424                name: "remote".into(),
425                transport: McpTransportKind::Http,
426                command: None,
427                args: vec![],
428                env: vec![],
429                url: Some("https://x/mcp".into()),
430                headers: vec![],
431                token_env: Some("REMOTE_TOKEN".into()),
432                token: Some("bearer456".into()),
433                auth: Some("bearer".into()),
434                auth_header: None,
435            },
436            McpServerSpec {
437                name: "keyed".into(),
438                transport: McpTransportKind::Http,
439                command: None,
440                args: vec![],
441                env: vec![],
442                url: Some("https://y/mcp".into()),
443                headers: vec![],
444                token_env: Some("KEYED_TOKEN".into()),
445                token: Some("apikey789".into()),
446                auth: Some("apikey".into()),
447                auth_header: Some("X-Custom-Key".into()),
448            },
449        ];
450
451        let p = provision(&servers, &dir).unwrap();
452
453        // The flags pre-approve each server's tools and pin to our config only.
454        assert!(p.args.contains(&"--mcp-config".to_string()));
455        assert!(p.args.contains(&"--strict-mcp-config".to_string()));
456        let i = p.args.iter().position(|a| a == "--allowedTools").unwrap();
457        assert!(p.args[i + 1].contains("mcp__fs"));
458        assert!(p.args[i + 1].contains("mcp__remote"));
459
460        // Tokens travel via the subprocess environment, never the file. The
461        // var names are index-prefixed to stay unique across servers.
462        assert!(p.env.iter().any(|(k, v)| k == "RINNE_MCP_0_FS_TOKEN" && v == "secret123"));
463        assert!(p.env.iter().any(|(k, v)| k == "RINNE_MCP_1_REMOTE_TOKEN" && v == "bearer456"));
464
465        let content = std::fs::read_to_string(p.cleanup.as_ref().unwrap()).unwrap();
466        assert!(!content.contains("secret123"), "stdio token must not be on disk");
467        assert!(!content.contains("bearer456"), "http token must not be on disk");
468        assert!(content.contains("${RINNE_MCP_0_FS_TOKEN}"));
469        assert!(content.contains("Bearer ${RINNE_MCP_1_REMOTE_TOKEN}"));
470
471        let v: serde_json::Value = serde_json::from_str(&content).unwrap();
472        assert_eq!(v["mcpServers"]["fs"]["command"], "npx");
473        assert_eq!(v["mcpServers"]["fs"]["env"]["GITHUB_TOKEN"], "${RINNE_MCP_0_FS_TOKEN}");
474        assert_eq!(v["mcpServers"]["remote"]["type"], "http");
475        assert_eq!(v["mcpServers"]["remote"]["url"], "https://x/mcp");
476        // The api-key server uses its custom header (no `Bearer ` prefix).
477        assert!(!content.contains("apikey789"), "api-key token must not be on disk");
478        assert_eq!(
479            v["mcpServers"]["keyed"]["headers"]["X-Custom-Key"],
480            "${RINNE_MCP_2_KEYED_TOKEN}"
481        );
482
483        let _ = std::fs::remove_dir_all(&dir);
484    }
485
486    #[test]
487    fn provision_errors_gracefully_when_scratch_cannot_be_created() {
488        // A regular file standing where the scratch directory's parent should be:
489        // `create_dir_all` under it fails, and provisioning must return an error
490        // (the adapter then runs the node without tools) rather than panic.
491        let blocker = std::env::temp_dir().join(format!("rinne-prov-blocker-{}", std::process::id()));
492        let _ = std::fs::remove_file(&blocker);
493        std::fs::write(&blocker, b"x").unwrap();
494        let scratch = blocker.join("mcp");
495
496        let servers = vec![McpServerSpec {
497            name: "fs".into(),
498            transport: McpTransportKind::Stdio,
499            command: Some("npx".into()),
500            args: vec![],
501            env: vec![],
502            url: None,
503            headers: vec![],
504            token_env: None,
505            token: None,
506            auth: None,
507            auth_header: None,
508        }];
509        assert!(provision(&servers, &scratch).is_err());
510
511        let _ = std::fs::remove_file(&blocker);
512    }
513}