magi-code 0.96.2

Repository-aware CLI coding agent for terminal work
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! Claude subscription adapter. No host tools run inside Claude CLI.
use super::{
    Provider, ProviderEvent, ProviderRequest,
    anthropic::parse_captured_sse,
    claude_admission::{
        CLAUDE_MAX_REQUEST_DURATION, CLAUDE_STARTUP_TIMEOUT, ClaudeAdmission, claude_error_hint,
        claude_error_with_hint,
    },
    claude_projection::ClaudeProjection,
};
use crate::{cancellation::AgentCancellation, tools::process::terminate_child_tree_and_wait};
use anyhow::{Context, Result, bail};
use serde_json::{Value, json};
use std::{
    io::{BufRead, BufReader, Read, Write},
    process::{Child, Command, Stdio},
    sync::mpsc,
    thread,
    time::{Duration, Instant},
};

const MAX_NATIVE_LINE: u64 = 1024 * 1024;
const NATIVE_PROGRESS_TIMEOUT: Duration = Duration::from_secs(300);

/// `cwd` is the host workspace; Claude CLI reports it as its working directory.
pub(super) struct ClaudeSubscriptionProvider {
    pub(super) cwd: std::path::PathBuf,
}

fn conflicting_native_auth_override() -> Option<&'static str> {
    [
        "ANTHROPIC_API_KEY",
        "ANTHROPIC_AUTH_TOKEN",
        "ANTHROPIC_FOUNDRY_API_KEY",
        "CLAUDE_CODE_USE_BEDROCK",
        "CLAUDE_CODE_USE_VERTEX",
        "CLAUDE_CODE_USE_FOUNDRY",
    ]
    .into_iter()
    .find(|key| std::env::var_os(key).is_some_and(|value| !value.is_empty()))
}

fn configure_cli_effort(command: &mut Command, thinking_level: crate::thinking::ThinkingLevel) {
    if let Some(effort) = thinking_level.explicit_effort() {
        command.args(["--effort", effort]);
    }
}

fn claude_loopback_no_proxy(existing: &str) -> String {
    if existing.is_empty() {
        "127.0.0.1,localhost".to_string()
    } else {
        format!("127.0.0.1,localhost,{existing}")
    }
}

pub(crate) fn cli_subscription_ready() -> bool {
    cli_subscription_status().is_some()
}

/// Returns `claude auth status --json` only when signed in with a claude.ai subscription.
pub(crate) fn cli_subscription_status() -> Option<Value> {
    probe_cli_subscription().ok()
}

/// `claude` from `PATH`, else native installer default `~/.local/bin/claude`
/// (installer does not always put it on `PATH`, e.g. non-login shells or WSL).
fn claude_cli_program() -> std::path::PathBuf {
    let on_path = std::env::var_os("PATH")
        .is_some_and(|path| std::env::split_paths(&path).any(|dir| dir.join("claude").is_file()));
    let native_install = dirs::home_dir().map(|home| home.join(".local/bin/claude"));
    match native_install {
        Some(path) if !on_path && path.is_file() => path,
        _ => "claude".into(),
    }
}

/// Explains why Claude subscription is unavailable so users can fix setup.
pub(crate) fn probe_cli_subscription() -> Result<Value, String> {
    if !cfg!(unix) {
        return Err("Claude subscription requires Unix (macOS, Linux, or WSL)".into());
    }
    if let Some(key) = conflicting_native_auth_override() {
        return Err(format!("unset {key}; it overrides claude.ai login"));
    }
    use crate::tools::process::{BoundedChildProcessLimits, run_bounded_child_process};
    let mut command = Command::new(claude_cli_program());
    command
        .args(["auth", "status", "--json"])
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        command.process_group(0);
    }
    let child = command.spawn().map_err(|error| {
        format!("cannot run `claude` ({error}); install Claude Code and put `claude` on PATH")
    })?;
    let output = run_bounded_child_process(
        child,
        BoundedChildProcessLimits {
            stdout_max_bytes: 8192,
            stderr_max_bytes: 16 * 1024,
            // Cold npm/Node starts, especially under WSL, can exceed a few seconds.
            timeout: Duration::from_secs(10),
            poll_interval: Duration::from_millis(20),
        },
        &AgentCancellation::default(),
    )
    .map_err(|error| format!("`claude auth status --json` failed: {error}"))?;
    if output.timed_out {
        return Err("`claude auth status --json` timed out".into());
    }
    if output.stdout_truncated || output.stderr_truncated {
        return Err("`claude auth status --json` output too large".into());
    }
    if let Some(warning) = output.cleanup_warning {
        return Err(format!("`claude auth status --json` {warning}"));
    }
    if !output.status.is_some_and(|status| status.success()) {
        return Err(
            "`claude auth status --json` exited unsuccessfully; run `claude auth login`".into(),
        );
    }
    let status = serde_json::from_str::<Value>(&output.stdout)
        .map_err(|_| "`claude auth status --json` returned invalid JSON; update Claude Code")?;
    if status.get("loggedIn").and_then(Value::as_bool) != Some(true) {
        return Err("Claude CLI not signed in; run `claude auth login`".into());
    }
    if status.get("authMethod").and_then(Value::as_str) != Some("claude.ai") {
        return Err(
            "Claude CLI not signed in with a claude.ai subscription; run `claude auth login`"
                .into(),
        );
    }
    Ok(status)
}

impl Provider for ClaudeSubscriptionProvider {
    fn stream_cancellable(
        &self,
        request: ProviderRequest,
        cancellation: &AgentCancellation,
        on_event: &mut dyn FnMut(ProviderEvent) -> Result<()>,
    ) -> Result<()> {
        cancellation.check()?;
        if cfg!(not(unix)) {
            bail!("Claude subscription process-tree cleanup requires Unix");
        }
        let estimated_tokens = crate::context::project_provider_request_input_tokens(
            super::CLAUDE_SUBSCRIPTION_PROVIDER,
            &request,
        )
        .tokens;
        let ceiling = super::CLAUDE_SUBSCRIPTION_MAX_PROMPT_TOKENS;
        if estimated_tokens > ceiling {
            bail!(
                "Claude CLI prompt is estimated at {estimated_tokens} tokens, exceeding its {ceiling}-token limit; compact the session, shorten the input, or use another provider; no CLI request was sent"
            );
        }
        let projection = ClaudeProjection::from_request(&request)?;
        let root = tempfile::tempdir().context("creating Claude request directory")?;
        let system = root.path().join("system.md");
        let manifest = root.path().join("tools.json");
        let settings = root.path().join("settings.json");
        std::fs::write(&system, &projection.system)?;
        std::fs::write(&manifest, serde_json::to_vec(&projection.manifest)?)?;
        std::fs::write(
            &settings,
            serde_json::to_vec(&json!({"env":{
                "CLAUDE_CODE_EXTRA_BODY": serde_json::to_string(&projection.extra_body)?
            }}))?,
        )?;
        let host_messages = projection
            .frames
            .iter()
            .map(|frame| frame["message"].clone())
            .collect();
        let relay = ClaudeAdmission::start(cancellation, host_messages)?;
        let executable = std::env::current_exe()?;
        let mcp = json!({"mcpServers":{"magi":{"command":executable,"env":{
            "MAGI_CLAUDE_INERT_MCP_INVENTORY":manifest
        }}}});
        let no_proxy = std::env::var("NO_PROXY")
            .or_else(|_| std::env::var("no_proxy"))
            .unwrap_or_default();
        let mut command = Command::new(claude_cli_program());
        command
            .args([
                "-p",
                "--model",
                &request.model,
                "--input-format",
                "stream-json",
                "--output-format",
                "stream-json",
                "--verbose",
                "--include-partial-messages",
                "--tools",
                "",
                "--system-prompt-file",
            ])
            .arg(&system)
            .args(["--settings"])
            .arg(&settings)
            .args([
                "--setting-sources",
                "",
                "--strict-mcp-config",
                "--disable-slash-commands",
                "--max-turns",
                "1",
                "--permission-mode",
                "dontAsk",
                "--no-session-persistence",
                "--mcp-config",
                &mcp.to_string(),
            ])
            .current_dir(&self.cwd)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .env("ANTHROPIC_BASE_URL", &relay.url)
            .env("NO_PROXY", claude_loopback_no_proxy(&no_proxy))
            .env("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1")
            .env("CLAUDE_CODE_MAX_RETRIES", "0")
            .env("DISABLE_AUTO_COMPACT", "1")
            .env("DISABLE_COMPACT", "1")
            .env("ENABLE_TOOL_SEARCH", "false")
            .env("CLAUDE_CODE_TOTAL_TOKENS_REMINDER", "off")
            .env_remove("CLAUDE_CODE_EXTRA_BODY");
        if let Some(key) = conflicting_native_auth_override() {
            bail!(
                "Claude subscription refuses conflicting native authentication or backend override: {key}"
            );
        }
        #[cfg(unix)]
        {
            use std::os::unix::process::CommandExt;
            command.process_group(0);
        }
        configure_cli_effort(&mut command, request.thinking_level);
        let child = command
            .spawn()
            .context("Claude CLI not installed; install and sign in to Claude Code")?;
        let mut child = OwnedChild(Some(child));
        let stdout = child
            .0
            .as_mut()
            .context("Claude child missing")?
            .stdout
            .take()
            .context("Claude CLI missing stdout")?;
        let stderr = child
            .0
            .as_mut()
            .context("Claude child missing")?
            .stderr
            .take()
            .context("Claude CLI missing stderr")?;
        let stderr_reader = thread::spawn(move || {
            let mut source = stderr;
            let mut captured = Vec::new();
            let mut buffer = [0u8; 4096];
            while let Ok(count) = source.read(&mut buffer) {
                if count == 0 {
                    break;
                }
                let remaining = 4096usize.saturating_sub(captured.len());
                captured.extend_from_slice(&buffer[..count.min(remaining)]);
            }
            captured
        });
        let (sender, receiver) = mpsc::sync_channel(16);
        let reader = thread::spawn(move || {
            let mut source = BufReader::new(stdout);
            loop {
                let mut line = Vec::new();
                let next = source
                    .by_ref()
                    .take(MAX_NATIVE_LINE + 1)
                    .read_until(b'\n', &mut line);
                let finished =
                    matches!(next, Ok(0) | Err(_)) || line.len() as u64 > MAX_NATIVE_LINE;
                if sender
                    .send(if finished { None } else { Some(line) })
                    .is_err()
                    || finished
                {
                    break;
                }
            }
        });
        let outcome = run_native(
            child.0.as_mut().context("Claude child missing")?,
            &receiver,
            &projection.frames,
            cancellation,
            NativeDeadline::new(
                CLAUDE_STARTUP_TIMEOUT,
                request
                    .semantic_progress_timeout()
                    .unwrap_or(NATIVE_PROGRESS_TIMEOUT),
                CLAUDE_MAX_REQUEST_DURATION,
            ),
        );
        // Always terminate descendants before checking relay status, even on successful CLI exit.
        let cleanup = child
            .0
            .take()
            .map(|mut process| terminate_child_tree_and_wait(&mut process))
            .context("Claude child missing")?;
        drop(receiver);
        let _ = reader.join();
        let stderr = stderr_reader.join().unwrap_or_default();
        let stderr_hint = claude_error_hint(&stderr);
        cancellation.check()?;
        let cleanup = cleanup?;
        if let Some(warning) = cleanup.cleanup_warning {
            bail!("Claude process cleanup failed: {warning}");
        }
        let completion = outcome.map_err(|error| claude_error_with_hint(error, stderr_hint))?;
        let hint = completion.error_hint.or(stderr_hint);
        let response = relay
            .finish()
            .map_err(|error| claude_error_with_hint(error, hint))?;
        if !(completion.assistant && completion.result && completion.stop) {
            return Err(claude_error_with_hint(
                anyhow::anyhow!(
                    "Claude CLI missing assistant, result, or message_stop; check Claude CLI version and login"
                ),
                hint,
            ));
        }
        let _ = response.denied;
        let mut events = parse_captured_sse(&response.body)?;
        let tool_boundary = completion.subtype == "error_max_turns"
            && events
                .iter()
                .any(|event| matches!(event, ProviderEvent::ToolCall(_)));
        if completion.is_error && !tool_boundary {
            return Err(claude_error_with_hint(
                anyhow::anyhow!("Claude CLI returned an error; check Claude CLI version and login"),
                hint,
            ));
        }
        if completion.subtype != "success" && !tool_boundary {
            bail!("Claude CLI did not complete successfully");
        }
        if !cleanup
            .status
            .is_some_and(|status| status.success() || (tool_boundary && status.code() == Some(1)))
        {
            bail!("Claude CLI exited unsuccessfully");
        }
        let names: std::collections::HashSet<&str> = projection
            .manifest
            .iter()
            .filter_map(|tool| tool.get("name").and_then(Value::as_str))
            .collect();
        for event in &mut events {
            match event {
                ProviderEvent::ToolCall(call) => {
                    call.name = host_tool_name(&call.name, &names)?.to_owned();
                }
                ProviderEvent::ResponseItem(item)
                    if item.get("type").and_then(Value::as_str) == Some("function_call") =>
                {
                    let name = item.get("name").and_then(Value::as_str).unwrap_or("");
                    item["name"] = json!(host_tool_name(name, &names)?);
                }
                _ => {}
            }
        }
        for event in events {
            cancellation.check()?;
            on_event(event)?;
        }
        Ok(())
    }
}

fn host_tool_name<'a>(
    name: &'a str,
    inventory: &std::collections::HashSet<&str>,
) -> Result<&'a str> {
    const PREFIX: &str = "mcp__magi__";
    let printable = if name.len() <= PREFIX.len() + 50
        && name
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
    {
        name
    } else {
        "[invalid tool name]"
    };
    let Some(host_name) = name.strip_prefix(PREFIX) else {
        bail!(
            "Claude CLI returned tool with unexpected name `{printable}` (expected {PREFIX} prefix)"
        );
    };
    if !inventory.contains(host_name) {
        bail!(
            "Claude CLI returned tool outside host inventory: `{printable}` (not provided for this request)"
        );
    }
    Ok(host_name)
}

struct OwnedChild(Option<Child>);
impl Drop for OwnedChild {
    fn drop(&mut self) {
        if let Some(mut child) = self.0.take() {
            let _ = terminate_child_tree_and_wait(&mut child);
        }
    }
}

struct NativeDeadline {
    startup_deadline: Instant,
    progress_deadline: Option<Instant>,
    overall_deadline: Instant,
    progress_timeout: Duration,
}

impl NativeDeadline {
    fn new(startup: Duration, progress: Duration, overall: Duration) -> Self {
        let now = Instant::now();
        Self {
            startup_deadline: now + startup,
            progress_deadline: None,
            overall_deadline: now + overall,
            progress_timeout: progress,
        }
    }

    fn check(&self) -> Result<()> {
        let now = Instant::now();
        if now >= self.overall_deadline {
            bail!("Claude CLI exceeded overall time limit");
        }
        if now >= self.progress_deadline.unwrap_or(self.startup_deadline) {
            if self.progress_deadline.is_some() {
                bail!("Claude CLI timed out waiting for progress");
            }
            bail!("Claude CLI startup timed out waiting for output");
        }
        Ok(())
    }

    fn observe(&mut self, event: &Value) {
        if native_event_has_progress(event) {
            self.progress_deadline = Some(Instant::now() + self.progress_timeout);
        }
    }
}

// Count generated content, not pings, startup metadata, or history replay acknowledgments.
// Output remains withheld until the complete upstream response has been validated.
fn native_event_has_progress(event: &Value) -> bool {
    if event.get("type").and_then(Value::as_str) != Some("stream_event") {
        return false;
    }
    let event = &event["event"];
    let nonempty = |value: &Value| value.as_str().is_some_and(|text| !text.is_empty());
    match event.get("type").and_then(Value::as_str) {
        Some("content_block_start") => {
            let block = &event["content_block"];
            match block.get("type").and_then(Value::as_str) {
                Some("tool_use") => nonempty(&block["id"]) && nonempty(&block["name"]),
                Some("text") => nonempty(&block["text"]),
                Some("thinking") => nonempty(&block["thinking"]),
                Some("redacted_thinking") => nonempty(&block["data"]),
                _ => false,
            }
        }
        Some("content_block_delta") => {
            let delta = &event["delta"];
            let field = match delta.get("type").and_then(Value::as_str) {
                Some("text_delta") => "text",
                Some("thinking_delta") => "thinking",
                Some("signature_delta") => "signature",
                Some("redacted_thinking_delta") => "data",
                Some("input_json_delta") => "partial_json",
                _ => return false,
            };
            nonempty(&delta[field])
        }
        _ => false,
    }
}

fn receive(
    receiver: &mpsc::Receiver<Option<Vec<u8>>>,
    cancel: &AgentCancellation,
    deadline: &NativeDeadline,
) -> Result<Option<Value>> {
    loop {
        cancel.check()?;
        deadline.check()?;
        let wait = deadline
            .progress_deadline
            .unwrap_or(deadline.startup_deadline)
            .min(deadline.overall_deadline)
            .saturating_duration_since(Instant::now())
            .min(Duration::from_millis(100));
        let received = receiver.recv_timeout(wait);
        cancel.check()?;
        deadline.check()?;
        match received {
            Ok(Some(line)) => {
                return serde_json::from_slice(&line)
                    .map(Some)
                    .context("invalid Claude CLI stream-json output");
            }
            Ok(None) | Err(mpsc::RecvTimeoutError::Disconnected) => return Ok(None),
            Err(mpsc::RecvTimeoutError::Timeout) => {}
        }
    }
}

fn replay_acknowledged(event: &Value) -> Result<bool> {
    if event.get("type").and_then(Value::as_str) != Some("result") {
        return Ok(false);
    }
    if event.get("num_turns").and_then(Value::as_u64) != Some(0)
        || event.get("is_error").and_then(Value::as_bool) == Some(true)
    {
        let hint = event
            .get("result")
            .and_then(Value::as_str)
            .and_then(|message| claude_error_hint(message.as_bytes()));
        return Err(claude_error_with_hint(
            anyhow::anyhow!(
                "Claude CLI does not support zero-turn history replay; check Claude CLI version"
            ),
            hint,
        ));
    }
    Ok(true)
}

struct NativeCompletion {
    assistant: bool,
    result: bool,
    stop: bool,
    subtype: String,
    is_error: bool,
    error_hint: Option<&'static str>,
}

fn run_native(
    child: &mut Child,
    receiver: &mpsc::Receiver<Option<Vec<u8>>>,
    frames: &[Value],
    cancellation: &AgentCancellation,
    mut deadline: NativeDeadline,
) -> Result<NativeCompletion> {
    let mut stdin = child.stdin.take().context("Claude CLI missing stdin")?;
    #[cfg(unix)]
    {
        use std::os::fd::AsRawFd;
        crate::tools::process::set_nonblocking(stdin.as_raw_fd())?;
    }
    for frame in frames {
        let mut encoded = serde_json::to_vec(frame)?;
        encoded.push(b'\n');
        let mut remaining = encoded.as_slice();
        while !remaining.is_empty() {
            cancellation.check()?;
            deadline.check().context("writing Claude CLI stdin")?;
            match stdin.write(remaining) {
                Ok(0) => bail!("Claude CLI stdin closed"),
                Ok(count) => remaining = &remaining[count..],
                Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                    thread::sleep(Duration::from_millis(10));
                }
                Err(_) => bail!("Claude CLI stdin write failed"),
            }
        }
        if frame.get("shouldQuery") == Some(&Value::Bool(false)) {
            loop {
                let event = receive(receiver, cancellation, &deadline)?
                    .context("Claude CLI exited before replay acknowledgment")?;
                if replay_acknowledged(&event)? {
                    break;
                }
            }
        }
    }
    drop(stdin);
    let mut completion = NativeCompletion {
        assistant: false,
        result: false,
        stop: false,
        subtype: String::new(),
        is_error: false,
        error_hint: None,
    };
    while let Some(event) = receive(receiver, cancellation, &deadline)? {
        deadline.observe(&event);
        match event.get("type").and_then(Value::as_str) {
            Some("assistant") => {
                if event.get("error").is_some() || event.pointer("/message/error").is_some() {
                    completion.is_error = true;
                }
                completion.assistant = true;
            }
            Some("result") => {
                if completion.result {
                    bail!("Claude CLI returned multiple results");
                }
                completion.result = true;
                completion.is_error |= event.get("is_error").and_then(Value::as_bool) == Some(true);
                if completion.is_error {
                    completion.error_hint = event
                        .get("result")
                        .and_then(Value::as_str)
                        .and_then(|message| claude_error_hint(message.as_bytes()));
                }
                completion.subtype = event
                    .get("subtype")
                    .and_then(Value::as_str)
                    .unwrap_or("")
                    .to_owned();
            }
            Some("stream_event")
                if event.pointer("/event/type").and_then(Value::as_str) == Some("message_stop") =>
            {
                completion.stop = true;
            }
            _ => {}
        }
    }
    Ok(completion)
}