agent-commander 0.7.0

A Rust library to control agents enclosed in CLI commands like Anthropic Claude Code CLI
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
//! Qwen Code CLI tool configuration
//! Based on <https://github.com/QwenLM/qwen-code>
//! Qwen Code is an open-source AI agent optimized for Qwen3-Coder models

use super::usage::{self, count};
use crate::streaming::parse_json_records;
use crate::tools::launch_options::{json_schema_arg, push_directories, LaunchOptions};
use crate::tools::shell::{build_command_head, escape_arg, lookup_model_alias};
use serde_json::Value;
use std::collections::HashMap;

/// Get the Qwen model map
pub fn get_model_map() -> HashMap<&'static str, &'static str> {
    let mut map = HashMap::new();
    // Pinned Hive Mind catalogue; generated by experiments/sync-model-catalog.py.
    map.insert("qwen3-coder-480a35", "qwen3-coder-480a35");
    map.insert("qwen3-coder-30ba3", "qwen3-coder-30ba3");
    map.insert("coder", "qwen3-coder-480a35");
    map.insert("gpt-4o", "gpt-4o");
    map.insert("gpt-4", "gpt-4");
    map.insert("sonnet", "claude-sonnet-4");
    map.insert("opus", "claude-opus-4");
    map.insert("formal-ai", "formal-ai");
    map.insert("formalai/formal-ai", "formal-ai");
    map.insert("qwen", "qwen3-coder-plus");
    map.insert("qwen-coder", "qwen3-coder-plus");
    map.insert("qwen3", "qwen3-coder-plus");
    map.insert("max", "qwen3.8-max");
    map.insert("qwen-max", "qwen3.8-max");
    map.insert("plus", "qwen3.7-plus");
    map.insert("qwen-plus", "qwen3.7-plus");
    map.insert("flash", "qwen3.8-flash");
    map.insert("qwen-flash", "qwen3.8-flash");
    map.insert("coder-model", "coder-model");
    map.insert("qwen3.8-max", "qwen3.8-max");
    map.insert("qwen3.7-max", "qwen3.7-max");
    map.insert("qwen3.7-plus", "qwen3.7-plus");
    map.insert("qwen3.6-plus", "qwen3.6-plus");
    map.insert("qwen3.5-plus", "qwen3.5-plus");
    map.insert("qwen3.8-flash", "qwen3.8-flash");
    map.insert("qwen3.6-flash", "qwen3.6-flash");
    map.insert("qwen3-coder-plus", "qwen3-coder-plus");
    map.insert("qwen3-coder-next", "qwen3-coder-next");
    map.insert("qwen3-coder", "qwen3-coder");
    map.insert("qwen3-coder-flash", "qwen3-coder-flash");
    map.insert("qwen3.6-coder-plus", "qwen3.6-coder-plus");
    map
}

/// Map model alias to full model ID
///
/// # Arguments
/// * `model` - Model alias or full ID
///
/// # Returns
/// Full model ID
pub fn map_model_to_id(model: &str) -> String {
    lookup_model_alias(&get_model_map(), model).unwrap_or_else(|| model.to_string())
}

/// Qwen command build options
#[derive(Debug, Clone, Default)]
pub struct QwenBuildOptions {
    pub prompt: Option<String>,
    pub prompt_file: Option<String>,
    pub system_prompt: Option<String>,
    pub model: Option<String>,
    pub json: bool,
    pub stream_json: bool,
    pub include_partial_messages: bool,
    pub yolo: bool,
    pub read_only: bool,
    pub resume: Option<String>,
    pub continue_session: bool,
    pub all_files: bool,
    pub include_directories: Vec<String>,
    pub executable: Option<String>,
    pub extra_env: Vec<(String, String)>,
    /// Variables removed from the inherited environment (`env -u`)
    pub unset_env: Vec<String>,
    pub extra_args: Vec<String>,
    pub skip_default_safety_flags: bool,
    /// Shared launch options (reasoning effort, MCP servers, extra directories)
    pub launch: LaunchOptions,
    /// Read stream-json user frames and control requests from stdin
    pub json_input: bool,
    /// The caller writes the prompt to stdin as a frame (live input)
    pub stream_input: bool,
}

impl QwenBuildOptions {
    /// Create new options with sensible defaults
    pub fn new() -> Self {
        Self {
            stream_json: true, // Default to stream-json
            yolo: true,        // Default to auto-approval
            ..Default::default()
        }
    }
}

/// Build command line arguments for Qwen Code
///
/// # Arguments
/// * `options` - Build options
///
/// # Returns
/// Vector of CLI arguments
pub fn build_args(options: &QwenBuildOptions) -> Vec<String> {
    let mut args = Vec::new();

    // Prompt (triggers headless mode)
    if let Some(ref prompt) = options.prompt {
        args.push("-p".to_string());
        args.push(prompt.clone());
    }

    // Model configuration
    if let Some(ref model) = options.model {
        let mapped_model = map_model_to_id(model);
        args.push("--model".to_string());
        args.push(mapped_model);
    }

    // Output format - prefer stream-json for real-time streaming
    if options.stream_json {
        args.push("--output-format".to_string());
        args.push("stream-json".to_string());
    } else if options.json {
        args.push("--output-format".to_string());
        args.push("json".to_string());
    }

    // Live input: qwen keeps reading Claude-shaped user frames and control
    // requests from stdin (requires stream-json output).
    if options.json_input {
        args.push("--input-format".to_string());
        args.push("stream-json".to_string());
    }

    // Include partial messages for real-time UI updates
    if options.include_partial_messages && options.stream_json {
        args.push("--include-partial-messages".to_string());
    }

    if options.read_only {
        args.push("--approval-mode".to_string());
        args.push("plan".to_string());
    } else if options.yolo && !options.skip_default_safety_flags {
        // Auto-approve all actions for autonomous execution
        args.push("--yolo".to_string());
    }

    // Session management
    if let Some(ref resume) = options.resume {
        args.push("--resume".to_string());
        args.push(resume.clone());
    } else if options.continue_session {
        args.push("--continue".to_string());
    }

    // Context options
    if options.all_files {
        args.push("--all-files".to_string());
    }

    push_directories(
        &mut args,
        "--include-directories",
        &options.include_directories,
    );
    push_directories(
        &mut args,
        "--include-directories",
        &options.launch.additional_directories,
    );
    if let Some(ref mcp_config) = options.launch.mcp_config {
        args.push("--mcp-config".to_string());
        args.push(mcp_config.clone());
    }
    // A JSON literal; qwen reads a value starting with `@` as a file path. The
    // answer is reported as `structured_result` on the result message.
    if let Some(ref file) = options.launch.json_schema_file {
        args.push("--json-schema".to_string());
        args.push(format!("@{file}"));
    } else if let Some(ref json_schema) = options.launch.json_schema {
        args.push("--json-schema".to_string());
        args.push(json_schema_arg(json_schema));
    }

    args.extend(options.extra_args.clone());

    args
}

/// Build complete command string for Qwen Code
///
/// # Arguments
/// * `options` - Build options
///
/// # Returns
/// Complete command string
pub fn build_command(options: &QwenBuildOptions) -> String {
    // Create a modified options with combined prompts
    let mut combined_options = options.clone();

    // Combine system prompt with user prompt if provided
    if options.prompt_file.is_some() || options.stream_input {
        combined_options.prompt = None;
    } else {
        match (&options.system_prompt, &options.prompt) {
            (Some(sys), Some(prompt)) => {
                combined_options.prompt = Some(format!("{}\n\n{}", sys, prompt));
            }
            (Some(sys), None) => {
                combined_options.prompt = Some(sys.clone());
            }
            _ => {}
        }
    }
    combined_options.system_prompt = None;

    let args = build_args(&combined_options);
    let args_str: Vec<String> = args.iter().map(|a| escape_arg(a)).collect();
    let executable = options.executable.as_deref().unwrap_or("qwen");
    let command = format!(
        "{} {}",
        build_command_head(executable, &[], &[], &[]),
        args_str.join(" ")
    )
    .trim()
    .to_string();

    match &options.prompt_file {
        Some(prompt_file) if !options.stream_input => {
            format!("cat {} | {}", escape_arg(prompt_file), command)
        }
        _ => command,
    }
}

/// Parse JSON messages from Qwen Code output
/// Qwen Code outputs NDJSON (newline-delimited JSON) in stream-json mode
///
/// # Arguments
/// * `output` - Raw output string
///
/// # Returns
/// Vector of parsed JSON messages
pub fn parse_output(output: &str) -> Vec<Value> {
    parse_json_records(output)
}

/// Extract session ID from Qwen Code output
///
/// # Arguments
/// * `output` - Raw output string
///
/// # Returns
/// Session ID or None
pub fn extract_session_id(output: &str) -> Option<String> {
    let messages = parse_output(output);

    for msg in messages {
        // Check for session_id format
        if let Some(session_id) = msg.get("session_id").and_then(|v| v.as_str()) {
            return Some(session_id.to_string());
        }
        // Also check for sessionId format
        if let Some(session_id) = msg.get("sessionId").and_then(|v| v.as_str()) {
            return Some(session_id.to_string());
        }
    }

    None
}

/// Usage statistics for Qwen Code
#[derive(Debug, Clone, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct QwenUsage {
    pub input_tokens: u64,
    pub output_tokens: u64,
    pub total_tokens: u64,
    pub cache_read_tokens: u64,
    pub reasoning_tokens: u64,
    pub cache_creation_tokens: u64,
}

/// Extract usage statistics from Qwen Code output
///
/// # Arguments
/// * `output` - Raw output string
///
/// # Returns
/// Usage statistics
pub fn extract_usage(output: &str) -> QwenUsage {
    let messages = parse_output(output);
    let mut result = QwenUsage::default();
    for record in usage::records("qwen", &messages) {
        result.input_tokens += count(record, usage::INPUT);
        result.output_tokens += count(record, usage::OUTPUT);
        result.cache_read_tokens += count(record, usage::CACHE_READ);
        result.reasoning_tokens += count(record, usage::REASONING);
        result.cache_creation_tokens += count(record, usage::CACHE_WRITE);
        result.total_tokens += count(record, usage::TOTAL);
    }
    if result.total_tokens == 0 {
        result.total_tokens = result.input_tokens
            + result.output_tokens
            + result.cache_read_tokens
            + result.cache_creation_tokens;
    }
    result
}

/// Error detection result
#[derive(Debug, Clone, Default)]
pub struct QwenErrorResult {
    pub has_error: bool,
    pub error_type: Option<String>,
    pub message: Option<String>,
}

/// Detect errors in Qwen Code output
///
/// # Arguments
/// * `output` - Raw output string
///
/// # Returns
/// Error detection result
pub fn detect_errors(output: &str) -> QwenErrorResult {
    let messages = parse_output(output);

    for msg in messages {
        // Check for type: "error"
        if let Some(msg_type) = msg.get("type").and_then(|v| v.as_str()) {
            if msg_type == "error" {
                return QwenErrorResult {
                    has_error: true,
                    error_type: Some(msg_type.to_string()),
                    message: msg
                        .get("message")
                        .and_then(|v| v.as_str())
                        .or_else(|| msg.get("error").and_then(|v| v.as_str()))
                        .map(|s| s.to_string())
                        .or_else(|| Some("Unknown error".to_string())),
                };
            }
        }

        // Check for error field
        if let Some(error) = msg.get("error").and_then(|v| v.as_str()) {
            return QwenErrorResult {
                has_error: true,
                error_type: Some("error".to_string()),
                message: Some(error.to_string()),
            };
        }
    }

    QwenErrorResult::default()
}

/// Qwen Code tool configuration
#[derive(Debug, Clone)]
pub struct QwenTool {
    pub name: &'static str,
    pub display_name: &'static str,
    pub executable: &'static str,
    pub supports_json_output: bool,
    pub supports_json_input: bool,
    pub supports_system_prompt: bool,
    pub supports_resume: bool,
    pub supports_continue_session: bool,
    pub supports_yolo: bool,
    pub supports_all_files: bool,
    pub supports_include_directories: bool,
    pub supports_include_partial_messages: bool,
    pub supports_read_only: bool,
    pub supports_ask: bool,
    pub default_model: &'static str,
}

impl Default for QwenTool {
    fn default() -> Self {
        Self {
            name: "qwen",
            display_name: "Qwen Code CLI",
            executable: "qwen",
            supports_json_output: true,
            supports_json_input: true, // Qwen Code supports stream-json input format
            supports_system_prompt: false, // System prompt is combined with user prompt
            supports_resume: true,     // Supports --resume and --continue
            supports_continue_session: true, // Supports --continue for most recent session
            supports_yolo: true,       // Supports --yolo for auto-approval
            supports_all_files: true,  // Supports --all-files
            supports_include_directories: true, // Supports --include-directories
            supports_include_partial_messages: true, // Supports --include-partial-messages
            supports_read_only: true,  // Supports --approval-mode plan
            supports_ask: false, // Headless mode has no relayable per-command JSON approval handshake
            default_model: "qwen3-coder-plus",
        }
    }
}