sashiko 0.2.1

Agentic code review system for Linux kernel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
// Copyright 2026 The Sashiko Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! AI provider that shells out to the `claude` CLI instead of calling the API directly.
//! This uses the local Claude Code installation (subscription auth) rather than API credits.
//!
//! ## Safety
//!
//! The `claude --print` flag runs in text-completion mode: no tools, no file
//! access, no session persistence, no network calls. The CLI reads a prompt
//! from stdin and writes a response to stdout — it cannot modify the
//! filesystem or execute commands. This makes it inherently safe for use as
//! a completion backend without any additional sandboxing.

use anyhow::Result;
use async_trait::async_trait;
use serde_json::Value;
use std::process::Stdio;
use std::time::Duration;
use tokio::io::AsyncWriteExt;
use tokio::process::Command;
use tokio::time::timeout;
use tracing::{debug, warn};

use crate::ai::{
    AiProvider, AiRequest, AiResponse, AiResponseFormat, AiRole, AiUsage, ProviderCapabilities,
    ToolCall,
};

pub struct ClaudeCliProvider {
    pub model: String,
    pub effort: Option<String>,
}

#[async_trait]
impl AiProvider for ClaudeCliProvider {
    async fn generate_content(&self, request: AiRequest) -> Result<AiResponse> {
        let prompt = build_prompt(&request);

        debug!("claude-cli prompt length: {} chars", prompt.len());

        let mut args = vec![
            "--print".to_string(),
            "--output-format".to_string(),
            "json".to_string(),
            "--no-session-persistence".to_string(),
        ];

        args.push("--model".to_string());
        args.push(self.model.clone());

        if let Some(effort) = &self.effort {
            args.push("--effort".to_string());
            args.push(effort.clone());
        }

        let mut child = Command::new("claude")
            .args(&args)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .map_err(|e| anyhow::anyhow!("Failed to spawn claude CLI: {}. Is it installed?", e))?;

        // Write prompt to stdin then close it
        if let Some(mut stdin) = child.stdin.take() {
            stdin.write_all(prompt.as_bytes()).await?;
            stdin.flush().await?;
        }

        // 10-minute timeout per CLI call — a hung claude process won't block forever
        let output = timeout(Duration::from_secs(600), child.wait_with_output())
            .await
            .map_err(|_| anyhow::anyhow!("claude CLI timed out after 10 minutes"))?
            .map_err(|e| anyhow::anyhow!("claude CLI wait error: {}", e))?;

        if !output.stderr.is_empty() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            for line in stderr.lines() {
                if !line.trim().is_empty() {
                    debug!("[claude-cli stderr] {}", line);
                }
            }
        }

        let raw = String::from_utf8_lossy(&output.stdout);

        if !output.status.success() {
            // Try to extract the actual error message from the JSON output.
            // The CLI emits a JSON object with is_error=true and the reason
            // in the "result" field even when it exits non-zero.
            if let Ok(outer) = serde_json::from_str::<Value>(&raw)
                && let Some(msg) = outer["result"].as_str()
            {
                anyhow::bail!("claude CLI error: {}", msg);
            }
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!(
                "claude CLI exited with {}: {}",
                output.status,
                stderr.trim()
            );
        }
        let outer: Value = serde_json::from_str(&raw).map_err(|e| {
            anyhow::anyhow!(
                "Failed to parse claude CLI JSON output: {}\nRaw: {}",
                e,
                &raw[..raw.len().min(200)]
            )
        })?;

        if outer["is_error"].as_bool().unwrap_or(false) {
            anyhow::bail!(
                "claude CLI returned error: {}",
                outer["result"].as_str().unwrap_or("unknown error")
            );
        }

        let result_text = outer["result"].as_str().unwrap_or("").trim().to_string();

        // Parse usage from the outer JSON
        let usage = parse_usage(&outer);

        // Parse the inner response — tool calls or content
        parse_inner_response(&result_text, usage)
    }

    fn estimate_tokens(&self, request: &AiRequest) -> usize {
        let chars: usize = request
            .messages
            .iter()
            .filter_map(|m| m.content.as_ref())
            .map(|c| c.len())
            .sum();
        chars / 4
    }

    fn get_capabilities(&self) -> ProviderCapabilities {
        ProviderCapabilities {
            model_name: self.model.clone(),
            context_window_size: context_window_for_model(&self.model),
        }
    }
}

/// Pick the context window to advertise for a given model name. The value is
/// currently metadata only (no consumer gates on it), so the mapping is coarse.
/// Opus 4.7 ships with a 1M window by default via Claude Code, and any model
/// can be selected with the `[1m]` suffix to opt into the 1M variant.
/// Verified against Claude Code 2.1.132 for opus-4-7, sonnet-4-6, sonnet-4-6[1m],
/// haiku-4-5.
fn context_window_for_model(model: &str) -> usize {
    if model.contains("[1m]") || model.contains("opus-4-7") {
        1_000_000
    } else {
        200_000
    }
}

/// Build the full text prompt from the AiRequest.
/// Embeds system prompt, conversation history, tool definitions, and instructions.
pub fn build_prompt(request: &AiRequest) -> String {
    let mut out = String::new();

    // System prompt
    if let Some(sys) = &request.system {
        out.push_str("<system>\n");
        out.push_str(sys);
        out.push_str("\n</system>\n\n");
    }

    // Conversation history
    for msg in &request.messages {
        match &msg.role {
            AiRole::System => {
                // Already handled above; skip embedded system messages
            }
            AiRole::User => {
                out.push_str("<user>\n");
                if let Some(c) = &msg.content {
                    out.push_str(c);
                }
                out.push_str("\n</user>\n\n");
            }
            AiRole::Assistant => {
                out.push_str("<assistant>\n");
                if let Some(c) = &msg.content {
                    out.push_str(c);
                }
                if let Some(calls) = &msg.tool_calls {
                    for call in calls {
                        out.push_str(&format!(
                            "<tool_call id=\"{}\" name=\"{}\">\n{}\n</tool_call>\n",
                            call.id, call.function_name, call.arguments
                        ));
                    }
                }
                out.push_str("</assistant>\n\n");
            }
            AiRole::Tool => {
                let id = msg.tool_call_id.as_deref().unwrap_or("?");
                out.push_str(&format!("<tool_result id=\"{}\">\n", id));
                if let Some(c) = &msg.content {
                    out.push_str(c);
                }
                out.push_str("\n</tool_result>\n\n");
            }
        }
    }

    // Tool definitions and response instructions
    if let Some(tools) = &request.tools
        && !tools.is_empty()
    {
        out.push_str("<available_tools>\n");
        for tool in tools {
            out.push_str(&format!(
                "- name: {}\n  description: {}\n  parameters: {}\n\n",
                tool.name, tool.description, tool.parameters
            ));
        }
        out.push_str("</available_tools>\n\n");
        out.push_str(
            "RESPONSE FORMAT: You MUST respond with a SINGLE valid JSON object only (no markdown, no explanation).\n\
             To call tools: {\"tool_calls\": [{\"id\": \"c1\", \"function_name\": \"TOOL_NAME\", \"arguments\": {ARGS}}, {\"id\": \"c2\", \"function_name\": \"OTHER_TOOL\", \"arguments\": {ARGS2}}]}\n\
             Put ALL tool calls in ONE tool_calls array. Do NOT output multiple JSON objects.\n\
             For your final answer: {\"content\": \"YOUR RESPONSE\"}\n\
             Do not mix both. Output exactly one JSON object.\n",
        );
    } else if matches!(request.response_format, Some(AiResponseFormat::Json { .. })) {
        // No tools but JSON format required (e.g. Phase 0, Planning).
        if let Some(AiResponseFormat::Json {
            schema: Some(schema),
        }) = &request.response_format
        {
            out.push_str(&format!(
                "RESPONSE FORMAT: You MUST respond with valid JSON only matching this schema: {}. \
                 Do not include any explanation, markdown, or code fences — output raw JSON.\n",
                serde_json::to_string(schema).unwrap_or_default()
            ));
        } else {
            out.push_str(
                "RESPONSE FORMAT: You MUST respond with valid JSON only. \
                 Do not include any explanation, markdown, or code fences — output raw JSON.\n",
            );
        }
    }

    out
}

fn parse_usage(outer: &Value) -> Option<AiUsage> {
    let u = &outer["usage"];
    if u.is_null() {
        return None;
    }
    let input = u["input_tokens"].as_u64().unwrap_or(0) as usize;
    let output = u["output_tokens"].as_u64().unwrap_or(0) as usize;
    let cached = u["cache_read_input_tokens"].as_u64().unwrap_or(0) as usize;
    Some(AiUsage {
        prompt_tokens: input,
        completion_tokens: output,
        total_tokens: input + output,
        cached_tokens: Some(cached),
    })
}

pub fn parse_inner_response(text: &str, usage: Option<AiUsage>) -> Result<AiResponse> {
    // Try extracting JSON (might be in a markdown code block)
    let json_str = extract_json(text);

    if let Ok(v) = serde_json::from_str::<Value>(&json_str) {
        return parse_single_json(&v, &json_str, usage);
    }

    // Try JSONL: multiple JSON objects on separate lines (model sometimes emits
    // separate tool_calls objects per line instead of one combined object)
    let mut merged_tool_calls: Vec<ToolCall> = Vec::new();
    let mut had_json = false;
    for line in json_str.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        if let Ok(v) = serde_json::from_str::<Value>(trimmed) {
            had_json = true;
            if let Some(calls) = v["tool_calls"].as_array() {
                for c in calls {
                    if let Some(tc) = parse_tool_call(c) {
                        merged_tool_calls.push(tc);
                    }
                }
            }
        }
    }

    if !merged_tool_calls.is_empty() {
        debug!(
            "claude-cli: merged {} tool calls from JSONL response",
            merged_tool_calls.len()
        );
        return Ok(AiResponse {
            content: None,
            thought: None,
            thought_signature: None,
            tool_calls: Some(merged_tool_calls),
            usage,
            truncated: false,
        });
    }

    if had_json {
        // Had valid JSON lines but no tool calls — return original text as content
        // (json_str from extract_json may be mangled if text had multiple objects)
        return Ok(AiResponse {
            content: Some(text.to_string()),
            thought: None,
            thought_signature: None,
            tool_calls: None,
            usage,
            truncated: false,
        });
    }

    // Not parseable as JSON — return raw text
    warn!("claude-cli response not valid JSON, returning as raw content");
    Ok(AiResponse {
        content: Some(text.to_string()),
        thought: None,
        thought_signature: None,
        tool_calls: None,
        usage,
        truncated: false,
    })
}

fn parse_tool_call(c: &Value) -> Option<ToolCall> {
    let id = c["id"].as_str().unwrap_or("c1").to_string();
    let name = c["function_name"].as_str()?.to_string();
    let args = c["arguments"].clone();
    Some(ToolCall {
        id,
        function_name: name,
        arguments: args,
        thought_signature: None,
    })
}

fn parse_single_json(v: &Value, json_str: &str, usage: Option<AiUsage>) -> Result<AiResponse> {
    // Tool calls?
    if let Some(calls) = v["tool_calls"].as_array() {
        let tool_calls: Vec<ToolCall> = calls.iter().filter_map(parse_tool_call).collect();

        if !tool_calls.is_empty() {
            return Ok(AiResponse {
                content: None,
                thought: None,
                thought_signature: None,
                tool_calls: Some(tool_calls),
                usage,
                truncated: false,
            });
        }
    }

    // Content field?
    if let Some(content) = v["content"].as_str() {
        return Ok(AiResponse {
            content: Some(content.to_string()),
            thought: None,
            thought_signature: None,
            tool_calls: None,
            usage,
            truncated: false,
        });
    }

    // Any other JSON — return it as content string (e.g. {"concerns": [...]})
    Ok(AiResponse {
        content: Some(json_str.to_string()),
        thought: None,
        thought_signature: None,
        tool_calls: None,
        usage,
        truncated: false,
    })
}

/// Extract JSON from text that may be wrapped in markdown fences.
/// Returns the content inside the first fenced block, or the original text trimmed.
/// Does NOT try to find outermost braces — that can silently produce invalid JSON
/// when the text contains multiple objects (e.g. JSONL), which the JSONL fallback
/// in parse_inner_response handles better.
fn extract_json(text: &str) -> String {
    // Strip markdown fences — handle both LF and CRLF, and optional language tag
    let normalized = text.replace("\r\n", "\n");
    for fence_start in &["```json\n", "```JSON\n", "```\n"] {
        if let Some(start) = normalized.find(fence_start) {
            let after = &normalized[start + fence_start.len()..];
            if let Some(end) = after.find("\n```") {
                return after[..end].trim().to_string();
            }
        }
    }
    normalized.trim().to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ai::{AiMessage, AiRequest, AiResponseFormat, AiRole, AiTool};
    use serde_json::json;

    fn make_request(messages: Vec<AiMessage>) -> AiRequest {
        AiRequest {
            system: None,
            messages,
            tools: None,
            temperature: None,
            response_format: None,
            context_tag: None,
        }
    }

    fn simple_user_msg() -> Vec<AiMessage> {
        vec![AiMessage {
            role: AiRole::User,
            content: Some("hi".to_string()),
            thought: None,
            thought_signature: None,
            tool_calls: None,
            tool_call_id: None,
        }]
    }

    #[test]
    fn test_build_prompt_json_format_without_tools() {
        let mut req = make_request(simple_user_msg());
        req.response_format = Some(AiResponseFormat::Json { schema: None });

        let prompt = build_prompt(&req);
        assert!(prompt.contains("RESPONSE FORMAT"));
        assert!(prompt.contains("valid JSON only"));
        assert!(!prompt.contains("tool_calls"));
    }

    #[test]
    fn test_build_prompt_json_format_with_schema() {
        let mut req = make_request(simple_user_msg());
        req.response_format = Some(AiResponseFormat::Json {
            schema: Some(
                json!({"type": "object", "properties": {"selected_prompts": {"type": "array"}}}),
            ),
        });

        let prompt = build_prompt(&req);
        assert!(prompt.contains("RESPONSE FORMAT"));
        assert!(prompt.contains("selected_prompts"));
        assert!(prompt.contains("matching this schema"));
    }

    #[test]
    fn test_build_prompt_with_tools_includes_format() {
        let mut req = make_request(simple_user_msg());
        req.tools = Some(vec![AiTool {
            name: "git_log".to_string(),
            description: "Show git log".to_string(),
            parameters: json!({"type": "object"}),
        }]);

        let prompt = build_prompt(&req);
        assert!(prompt.contains("RESPONSE FORMAT"));
        assert!(prompt.contains("tool_calls"));
        assert!(prompt.contains("<available_tools>"));
    }

    #[test]
    fn test_build_prompt_text_format_no_instruction() {
        let mut req = make_request(simple_user_msg());
        req.response_format = Some(AiResponseFormat::Text);

        let prompt = build_prompt(&req);
        assert!(!prompt.contains("RESPONSE FORMAT"));
    }

    #[test]
    fn test_build_prompt_no_format_no_instruction() {
        let req = make_request(simple_user_msg());

        let prompt = build_prompt(&req);
        assert!(!prompt.contains("RESPONSE FORMAT"));
    }
}