ai-dispatch 8.99.9

Multi-AI CLI team orchestrator
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
//! CLI adapter for user-defined agents loaded from TOML.
//! Exports: CustomAgentConfig, CustomAgent, parse_config.
//! Deps: serde, toml, serde_json, chrono, std::process::Command, crate::types.
#![allow(dead_code)]

use anyhow::Result;
use chrono::Local;
use serde::Deserialize;
use serde_json::Value;
use std::process::Command;

use super::RunOpts;
use crate::types::*;

#[derive(Debug, Clone, Deserialize)]
pub struct CustomAgentFile {
    pub agent: CustomAgentConfig,
}

#[derive(Debug, Clone, Deserialize)]
pub struct CustomAgentConfig {
    pub id: String,
    pub display_name: String,
    pub command: String,
    #[serde(default = "default_prompt_mode")]
    pub prompt_mode: String,
    #[serde(default)]
    pub prompt_flag: String,
    #[serde(default)]
    pub dir_flag: String,
    #[serde(default)]
    pub model_flag: String,
    #[serde(default)]
    pub output_flag: String,
    #[serde(default)]
    pub fixed_args: Vec<String>,
    #[serde(default)]
    pub streaming: bool,
    #[serde(default = "default_output_format")]
    pub output_format: String,
    #[serde(default)]
    pub capabilities: CapabilityScores,
    /// Trust tier: "local" (runs locally), "api" (sends prompts to third-party API)
    #[serde(default = "default_trust_tier")]
    pub trust_tier: String,
    #[serde(default)]
    pub strengths: Vec<String>,
    /// When set (currently only "opencode"), the registry returns an
    /// adapter overlay around the named agent instead of the bash-wrapper
    /// CustomAgent. Required `forced_model` accompanies it.
    #[serde(default)]
    pub delegate_to: Option<String>,
    #[serde(default)]
    pub forced_model: Option<String>,
}

fn default_trust_tier() -> String {
    "api".to_string()
}

#[derive(Debug, Clone, Default, Deserialize)]
pub struct CapabilityScores {
    #[serde(default)]
    pub research: i32,
    #[serde(default = "default_score")]
    pub simple_edit: i32,
    #[serde(default = "default_score")]
    pub complex_impl: i32,
    #[serde(default)]
    pub frontend: i32,
    #[serde(default = "default_score")]
    pub debugging: i32,
    #[serde(default = "default_score")]
    pub testing: i32,
    #[serde(default = "default_score")]
    pub refactoring: i32,
    #[serde(default)]
    pub documentation: i32,
}

fn default_prompt_mode() -> String {
    "arg".to_string()
}

fn default_output_format() -> String {
    "text".to_string()
}

fn default_score() -> i32 {
    3
}

pub struct CustomAgent {
    pub config: CustomAgentConfig,
}

impl super::Agent for CustomAgent {
    fn kind(&self) -> AgentKind {
        AgentKind::Custom
    }

    fn streaming(&self) -> bool {
        self.config.streaming
    }

    fn build_command(&self, prompt: &str, opts: &RunOpts) -> Result<Command> {
        let effective_prompt = apply_read_only_prefix(prompt, opts);
        if opts.read_only {
            aid_warn!("[aid] âš  Custom agent read-only is prompt-level only, not enforced. Use --worktree for isolation.");
        }
        let mut cmd = Command::new(&self.config.command);

        for arg in &self.config.fixed_args {
            cmd.arg(arg);
        }

        if let Some(ref dir) = opts.dir {
            if !self.config.dir_flag.is_empty() {
                cmd.args([&self.config.dir_flag, dir]);
            }
            cmd.current_dir(dir);
        }

        if let Some(ref model) = opts.model
            && !self.config.model_flag.is_empty()
        {
            cmd.args([&self.config.model_flag, model]);
        }

        if let Some(ref output) = opts.output
            && !self.config.output_flag.is_empty()
        {
            cmd.args([&self.config.output_flag, output]);
        }

        match self.config.prompt_mode.as_str() {
            "flag" if !self.config.prompt_flag.is_empty() => {
                cmd.args([&self.config.prompt_flag, &effective_prompt]);
            }
            "flag" => {
                cmd.arg(&effective_prompt);
            }
            "stdin" => {}
            _ => {
                cmd.arg(&effective_prompt);
            }
        }

        Ok(cmd)
    }

    fn parse_event(&self, task_id: &TaskId, line: &str) -> Option<TaskEvent> {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            return None;
        }

        if self.config.output_format == "jsonl"
            && let Ok(value) = serde_json::from_str::<Value>(trimmed)
        {
            let event_type = value
                .get("type")
                .or_else(|| value.get("event"))
                .or_else(|| value.get("kind"))
                .and_then(|v| v.as_str());
            if let Some(et) = event_type {
                let detail = value
                    .get("message")
                    .or_else(|| value.get("text"))
                    .or_else(|| value.get("detail"))
                    .and_then(|v| v.as_str())
                    .unwrap_or(et);
                let kind = match et {
                    t if t.contains("error") => EventKind::Error,
                    t if t.contains("tool") => EventKind::ToolCall,
                    t if t.contains("complet") => EventKind::Completion,
                    _ => EventKind::Reasoning,
                };
                return Some(TaskEvent {
                    task_id: task_id.clone(),
                    timestamp: Local::now(),
                    event_kind: kind,
                    detail: super::truncate::truncate_text(detail, 120),
                    metadata: None,
                });
            }
        }

        Some(TaskEvent {
            task_id: task_id.clone(),
            timestamp: Local::now(),
            event_kind: EventKind::Reasoning,
            detail: super::truncate::truncate_text(trimmed, 120),
            metadata: None,
        })
    }

    fn parse_completion(&self, _output: &str) -> CompletionInfo {
        CompletionInfo {
            tokens: None,
            status: TaskStatus::Done,
            model: None,
            cost_usd: None,
            exit_code: None,
        }
    }
}

pub fn parse_config(toml_content: &str) -> Result<CustomAgentConfig> {
    let file: CustomAgentFile = toml::from_str(toml_content)?;
    Ok(file.agent)
}

fn apply_read_only_prefix(prompt: &str, opts: &RunOpts) -> String {
    if !opts.read_only {
        return prompt.to_string();
    }
    if opts.result_file.is_some() {
        format!(
            "IMPORTANT: READ-ONLY MODE. Do NOT modify, create, or delete any files, EXCEPT the result file specified in this prompt. Only read, analyze, and write your findings to the designated result file.\n\n{}",
            prompt
        )
    } else {
        format!(
            "IMPORTANT: READ-ONLY MODE. Do NOT modify, create, or delete any files. Only read and analyze.\n\n{}",
            prompt
        )
    }
}

#[cfg(test)]
mod tests {
    use super::super::Agent;
    use super::*;
    use crate::types::{EventKind, TaskId};

    fn base_opts() -> RunOpts {
        RunOpts {
            dir: None,
            output: None,
            result_file: None,
            model: None,
            budget: false,
            read_only: false,
            context_files: Vec::new(),
            session_id: None,
            env: None,
            env_forward: None,
        }
    }

    fn base_config(command: &str) -> CustomAgentConfig {
        CustomAgentConfig {
            id: "custom".into(),
            display_name: "Custom Agent".into(),
            command: command.into(),
            prompt_mode: default_prompt_mode(),
            prompt_flag: String::new(),
            dir_flag: String::new(),
            model_flag: String::new(),
            output_flag: String::new(),
            fixed_args: Vec::new(),
            streaming: false,
            output_format: default_output_format(),
            capabilities: CapabilityScores::default(),
            trust_tier: default_trust_tier(),
            strengths: Vec::new(),
            delegate_to: None,
            forced_model: None,
        }
    }

    #[test]
    fn parse_minimal_config() {
        let toml_data = r#"
            [agent]
            id = "aider"
            display_name = "Aider"
            command = "aider"
        "#;
        let config = parse_config(toml_data).unwrap();
        assert_eq!(config.id, "aider");
        assert_eq!(config.prompt_mode, "arg");
        assert_eq!(config.output_format, "text");
        assert_eq!(config.capabilities.simple_edit, 0);
    }

    #[test]
    fn parse_full_config() {
        let toml_data = r#"
            [agent]
            id = "walker"
            display_name = "Walker"
            command = "walker-cli"
            prompt_mode = "flag"
            prompt_flag = "--input"
            dir_flag = "--dir"
            model_flag = "--model"
            output_flag = "--out"
            fixed_args = ["--yes", "--batch"]
            streaming = true
            output_format = "jsonl"

            [agent.capabilities]
            research = 2
            simple_edit = 4
            complex_impl = 8
            frontend = 1
            debugging = 5
            testing = 6
            refactoring = 7
            documentation = 2
        "#;
        let config = parse_config(toml_data).unwrap();
        assert!(config.streaming);
        assert_eq!(config.prompt_mode, "flag");
        assert_eq!(config.capabilities.complex_impl, 8);
        assert_eq!(config.fixed_args.len(), 2);
    }

    #[test]
    fn build_command_with_arg_mode() {
        let mut config = base_config("agent-cli");
        config.fixed_args.push("--yes".into());
        let agent = CustomAgent { config };
        let cmd = agent.build_command("ask", &base_opts()).unwrap();
        let args: Vec<_> = cmd
            .get_args()
            .map(|arg| arg.to_string_lossy().into_owned())
            .collect();
        assert_eq!(args, vec!["--yes", "ask"]);
    }

    #[test]
    fn build_command_with_flag_mode() {
        let mut config = base_config("agent-cli");
        config.prompt_mode = "flag".into();
        config.prompt_flag = "--message".into();
        config.fixed_args.push("--ready".into());
        let agent = CustomAgent { config };
        let args: Vec<_> = agent
            .build_command("prompt", &base_opts())
            .unwrap()
            .get_args()
            .map(|arg| arg.to_string_lossy().into_owned())
            .collect();
        assert_eq!(args, vec!["--ready", "--message", "prompt"]);
    }

    #[test]
    fn custom_agent_kind_is_custom() {
        let agent = CustomAgent {
            config: base_config("agent-cli"),
        };
        assert_eq!(agent.kind(), AgentKind::Custom);
    }

    #[test]
    fn build_command_read_only_prepends_warning_to_prompt() {
        let agent = CustomAgent {
            config: base_config("agent-cli"),
        };
        let mut opts = base_opts();
        opts.read_only = true;
        let cmd = agent.build_command("ask", &opts).unwrap();
        let args: Vec<_> = cmd
            .get_args()
            .map(|arg| arg.to_string_lossy().into_owned())
            .collect();
        assert!(args.last().unwrap().contains("READ-ONLY MODE"));
        assert!(args.last().unwrap().ends_with("\n\nask"));
    }

    #[test]
    fn build_command_read_only_with_result_file_uses_exception_text() {
        let agent = CustomAgent {
            config: base_config("agent-cli"),
        };
        let mut opts = base_opts();
        opts.read_only = true;
        opts.result_file = Some("result.md".into());
        let cmd = agent.build_command("audit", &opts).unwrap();
        let last = cmd
            .get_args()
            .last()
            .map(|arg| arg.to_string_lossy().into_owned())
            .unwrap();
        assert!(last.contains("EXCEPT the result file"));
    }

    #[test]
    fn build_command_normal_mode_does_not_mutate_prompt() {
        let agent = CustomAgent {
            config: base_config("agent-cli"),
        };
        let cmd = agent.build_command("hello", &base_opts()).unwrap();
        let args: Vec<_> = cmd
            .get_args()
            .map(|arg| arg.to_string_lossy().into_owned())
            .collect();
        assert_eq!(args, vec!["hello"]);
    }

    #[test]
    fn build_command_with_dir() {
        let mut config = base_config("agent-cli");
        config.dir_flag = "--dir".into();
        let mut opts = base_opts();
        opts.dir = Some("/tmp/work".into());
        let cmd = CustomAgent { config }
            .build_command("prompt", &opts)
            .unwrap();
        let args: Vec<_> = cmd
            .get_args()
            .map(|arg| arg.to_string_lossy().into_owned())
            .collect();
        assert_eq!(&args[..2], ["--dir".to_string(), "/tmp/work".to_string()]);
        let current_dir = cmd
            .get_current_dir()
            .map(|p| p.to_string_lossy().into_owned());
        assert_eq!(current_dir, Some("/tmp/work".to_string()));
    }

    #[test]
    fn parse_event_jsonl() {
        let mut config = base_config("agent-cli");
        config.output_format = "jsonl".into();
        let agent = CustomAgent { config };
        let task_id = TaskId("t-0001".into());
        let line = r#"{"type":"completion","message":"done"}"#;
        let event = agent.parse_event(&task_id, line).unwrap();
        assert_eq!(event.event_kind, EventKind::Completion);
        assert_eq!(event.detail, "done");
    }

    #[test]
    fn parse_event_text() {
        let config = base_config("agent-cli");
        let agent = CustomAgent { config };
        let task_id = TaskId("t-0002".into());
        let event = agent.parse_event(&task_id, " step ").unwrap();
        assert_eq!(event.event_kind, EventKind::Reasoning);
        assert_eq!(event.detail, "step");
    }
}