coyote-ai 0.7.2

An all-in-one, batteries included LLM CLI Tool
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
use super::state::{StateManager, StateRepresentation};
use super::types::ScriptNode;
use crate::config::paths;
use crate::function::Language;
use anyhow::{Context, Result, anyhow, bail};
use serde_json::Value;
use std::collections::HashMap;
use std::env;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;
use tokio::process::Command;
use tokio::time::timeout;

#[cfg(windows)]
const PATH_SEP: &str = ";";
#[cfg(not(windows))]
const PATH_SEP: &str = ":";

#[derive(Clone)]
pub struct ScriptExecutor {
    base_dir: PathBuf,
    extra_envs: HashMap<String, String>,
}

impl ScriptExecutor {
    pub fn new(base_dir: impl Into<PathBuf>) -> Self {
        let base_dir = base_dir.into();
        let extra_envs = build_default_envs(&base_dir);
        Self {
            base_dir,
            extra_envs,
        }
    }

    pub fn with_envs(mut self, envs: HashMap<String, String>) -> Self {
        self.extra_envs.extend(envs);
        self
    }

    pub async fn execute(
        &self,
        node: &ScriptNode,
        state_manager: &mut StateManager,
    ) -> Result<Option<String>> {
        let script_path = self.base_dir.join(&node.script);
        if !script_path.exists() {
            bail!("Script file not found: '{}'", script_path.display());
        }

        let language = detect_language(&script_path)?;
        let state_repr = state_manager.serialize_state()?;

        let mut cmd = build_command(language, &script_path)?;
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());
        cmd.envs(&self.extra_envs);
        cmd.env("AUTO_CONFIRM", "true");
        match &state_repr {
            StateRepresentation::Inline(json) => {
                cmd.env("GRAPH_STATE", json);
            }
            StateRepresentation::File(path) => {
                cmd.env("GRAPH_STATE_FILE", path);
            }
        }

        let timeout_dur = Duration::from_secs(node.timeout);
        let output = timeout(timeout_dur, cmd.output())
            .await
            .with_context(|| {
                format!(
                    "Script '{}' timed out after {}s",
                    script_path.display(),
                    node.timeout
                )
            })?
            .with_context(|| {
                format!(
                    "Failed to spawn script process for '{}'",
                    script_path.display()
                )
            })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            bail!(
                "Script '{}' failed with exit code {:?}:\n{}",
                script_path.display(),
                output.status.code(),
                stderr.trim()
            );
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let json_output = stdout.trim();
        if json_output.is_empty() {
            bail!(
                "Script '{}' produced no output (scripts must emit a single JSON object on stdout)",
                script_path.display()
            );
        }

        let next = state_manager
            .merge_script_output(json_output)
            .with_context(|| {
                format!(
                    "Failed to merge output from script '{}'",
                    script_path.display()
                )
            })?;

        apply_state_updates(node, state_manager);

        Ok(next)
    }
}

fn apply_state_updates(node: &ScriptNode, state_manager: &mut StateManager) {
    let Some(updates) = &node.state_updates else {
        return;
    };

    for (key, template) in updates {
        let value = state_manager.interpolate_lenient(template);
        state_manager
            .state_mut()
            .set(key.clone(), Value::String(value));
    }
}

fn build_default_envs(agent_data_dir: &Path) -> HashMap<String, String> {
    let mut envs = HashMap::new();
    envs.insert(
        "LLM_ROOT_DIR".to_string(),
        paths::config_dir().to_string_lossy().into_owned(),
    );
    envs.insert(
        "LLM_PROMPT_UTILS_FILE".to_string(),
        paths::bash_prompt_utils_file()
            .to_string_lossy()
            .into_owned(),
    );
    envs.insert(
        "LLM_AGENT_DATA_DIR".to_string(),
        agent_data_dir.to_string_lossy().into_owned(),
    );
    envs.insert("CLICOLOR_FORCE".to_string(), "1".to_string());
    envs.insert("FORCE_COLOR".to_string(), "1".to_string());

    if let Ok(current_path) = env::var("PATH") {
        let bin_dir = paths::functions_bin_dir();
        envs.insert(
            "PATH".to_string(),
            format!("{}{}{}", bin_dir.display(), PATH_SEP, current_path),
        );
    }

    envs
}

fn detect_language(script_path: &Path) -> Result<Language> {
    let ext = script_path
        .extension()
        .and_then(|e| e.to_str())
        .ok_or_else(|| anyhow!("Script has no file extension: '{}'", script_path.display()))?
        .to_string();

    match Language::from(&ext) {
        Language::Unsupported => bail!(
            "Unsupported script extension '.{}' for '{}'",
            ext,
            script_path.display()
        ),
        lang => Ok(lang),
    }
}

fn build_command(language: Language, script_path: &Path) -> Result<Command> {
    let (program, prefix_args) = language.direct_invoker().ok_or_else(|| {
        anyhow!(
            "No direct invoker available for script '{}'",
            script_path.display()
        )
    })?;
    let mut cmd = Command::new(program);

    for arg in prefix_args {
        cmd.arg(arg);
    }

    cmd.arg(script_path);
    Ok(cmd)
}

#[cfg(test)]
mod tests {
    use super::super::MAX_STATE_SIZE_BYTES;
    use super::*;
    use crate::utils::temp_file;
    use indoc::formatdoc;
    use serde_json::json;
    use std::collections::HashMap;
    use std::env::temp_dir;
    use std::fs;

    fn cmd_available(name: &str) -> bool {
        which::which(name).is_ok()
    }

    fn write_script(contents: &str, ext: &str) -> (PathBuf, PathBuf) {
        let dir = temp_file("-graph-script-test-", "");
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join(format!("script.{ext}"));
        fs::write(&path, contents).unwrap();
        (dir, path)
    }

    fn cleanup(dir: &Path) {
        let _ = fs::remove_dir_all(dir);
    }

    fn node_for(script_filename: &str, timeout: u64) -> ScriptNode {
        ScriptNode {
            script: script_filename.into(),
            state_updates: None,
            fallback: None,
            timeout,
        }
    }

    #[tokio::test]
    async fn bash_script_merges_json_output_into_state() {
        if !cmd_available("bash") {
            eprintln!("skipping: bash not available");
            return;
        }
        let (dir, path) = write_script(
            r#"#!/bin/bash
echo '{"quality": 0.85, "issues": 3, "_next": "approve"}'
"#,
            "sh",
        );
        let mut state = StateManager::new(HashMap::new());
        let executor = ScriptExecutor::new(&dir);

        let next = executor
            .execute(
                &node_for(path.file_name().unwrap().to_str().unwrap(), 5),
                &mut state,
            )
            .await
            .unwrap();

        assert_eq!(next.as_deref(), Some("approve"));
        assert_eq!(state.state().get("quality"), Some(&json!(0.85)));
        assert_eq!(state.state().get("issues"), Some(&json!(3)));
        assert!(state.state().get("_next").is_none());
        cleanup(&dir);
    }

    #[tokio::test]
    async fn bash_script_can_read_state_from_env() {
        if !cmd_available("bash") || !cmd_available("python3") {
            eprintln!("skipping: bash or python3 not available");
            return;
        }
        let (dir, path) = write_script(
            r#"#!/bin/bash
NAME=$(python3 -c 'import json,os; print(json.loads(os.environ["GRAPH_STATE"])["name"])')
printf '{"greeting": "hello %s"}' "$NAME"
"#,
            "sh",
        );
        let mut initial = HashMap::new();
        initial.insert("name".into(), json!("alice"));
        let mut state = StateManager::new(initial);
        let executor = ScriptExecutor::new(&dir);

        let _ = executor
            .execute(
                &node_for(path.file_name().unwrap().to_str().unwrap(), 5),
                &mut state,
            )
            .await
            .unwrap();

        assert_eq!(state.state().get("greeting"), Some(&json!("hello alice")));
        cleanup(&dir);
    }

    #[tokio::test]
    async fn script_without_next_returns_none() {
        if !cmd_available("bash") {
            return;
        }
        let (dir, path) = write_script(
            r#"#!/bin/bash
echo '{"ok": true}'
"#,
            "sh",
        );
        let mut state = StateManager::new(HashMap::new());
        let executor = ScriptExecutor::new(&dir);

        let next = executor
            .execute(
                &node_for(path.file_name().unwrap().to_str().unwrap(), 5),
                &mut state,
            )
            .await
            .unwrap();

        assert!(next.is_none());
        assert_eq!(state.state().get("ok"), Some(&json!(true)));
        cleanup(&dir);
    }

    #[tokio::test]
    async fn state_updates_apply_after_json_merge() {
        if !cmd_available("bash") {
            return;
        }
        let (dir, path) = write_script(
            r#"#!/bin/bash
echo '{"raw": "hello"}'
"#,
            "sh",
        );
        let mut node = node_for(path.file_name().unwrap().to_str().unwrap(), 5);
        let mut updates = HashMap::new();
        updates.insert("decorated".into(), "[{{raw}}]".into());
        node.state_updates = Some(updates);

        let mut state = StateManager::new(HashMap::new());
        let executor = ScriptExecutor::new(&dir);
        executor.execute(&node, &mut state).await.unwrap();

        assert_eq!(state.state().get("raw"), Some(&json!("hello")));
        assert_eq!(state.state().get("decorated"), Some(&json!("[hello]")));
        cleanup(&dir);
    }

    #[tokio::test]
    async fn missing_script_file_errors_before_spawning() {
        let mut state = StateManager::new(HashMap::new());
        let executor = ScriptExecutor::new(temp_dir());

        let err = executor
            .execute(&node_for("__does_not_exist__.sh", 5), &mut state)
            .await
            .unwrap_err()
            .to_string();

        assert!(err.contains("Script file not found"), "got: {err}");
    }

    #[tokio::test]
    async fn empty_stdout_errors() {
        if !cmd_available("bash") {
            return;
        }
        let (dir, path) = write_script("#!/bin/bash\n", "sh");
        let mut state = StateManager::new(HashMap::new());
        let executor = ScriptExecutor::new(&dir);

        let err = executor
            .execute(
                &node_for(path.file_name().unwrap().to_str().unwrap(), 5),
                &mut state,
            )
            .await
            .unwrap_err()
            .to_string();

        assert!(err.contains("produced no output"), "got: {err}");
        cleanup(&dir);
    }

    #[tokio::test]
    async fn non_json_output_errors() {
        if !cmd_available("bash") {
            return;
        }
        let (dir, path) = write_script(
            &formatdoc! {r#"
                #!/bin/bash
                echo "not json at all"
            "#},
            "sh",
        );
        let mut state = StateManager::new(HashMap::new());
        let executor = ScriptExecutor::new(&dir);

        let err = executor
            .execute(
                &node_for(path.file_name().unwrap().to_str().unwrap(), 5),
                &mut state,
            )
            .await
            .unwrap_err()
            .to_string();

        assert!(err.contains("merge output"), "got: {err}");
        cleanup(&dir);
    }

    #[tokio::test]
    async fn non_zero_exit_errors_and_includes_stderr() {
        if !cmd_available("bash") {
            return;
        }
        let (dir, path) = write_script(
            &formatdoc! {r#"
                #!/bin/bash
                echo "bad happened" >&2
                exit 7
            "#},
            "sh",
        );
        let mut state = StateManager::new(HashMap::new());
        let executor = ScriptExecutor::new(&dir);

        let err = executor
            .execute(
                &node_for(path.file_name().unwrap().to_str().unwrap(), 5),
                &mut state,
            )
            .await
            .unwrap_err()
            .to_string();

        assert!(err.contains("exit code"), "got: {err}");
        assert!(err.contains("bad happened"), "got: {err}");
        cleanup(&dir);
    }

    #[tokio::test]
    async fn execution_timeout_is_enforced() {
        if !cmd_available("bash") {
            return;
        }
        let (dir, path) = write_script(
            r#"#!/bin/bash
sleep 5
echo '{"ok":true}'
"#,
            "sh",
        );
        let mut state = StateManager::new(HashMap::new());
        let executor = ScriptExecutor::new(&dir);

        let err = executor
            .execute(
                &node_for(path.file_name().unwrap().to_str().unwrap(), 1),
                &mut state,
            )
            .await
            .unwrap_err()
            .to_string();

        assert!(err.contains("timed out"), "got: {err}");
        cleanup(&dir);
    }

    #[tokio::test]
    async fn large_state_is_delivered_via_file_env_var() {
        if !cmd_available("bash") || !cmd_available("python3") {
            return;
        }
        let big = "x".repeat(MAX_STATE_SIZE_BYTES + 1024);
        let mut initial = HashMap::new();
        initial.insert("blob".into(), json!(big));

        let (dir, path) = write_script(
            r#"#!/bin/bash
if [ -n "$GRAPH_STATE_FILE" ]; then
    LEN=$(python3 -c 'import json,os; print(len(json.load(open(os.environ["GRAPH_STATE_FILE"]))["blob"]))')
    printf '{"blob_len": %s, "via_file": true}' "$LEN"
elif [ -n "$GRAPH_STATE" ]; then
    echo '{"via_file": false}'
fi
"#,
            "sh",
        );

        let mut state = StateManager::new(initial);
        let executor = ScriptExecutor::new(&dir);
        executor
            .execute(
                &node_for(path.file_name().unwrap().to_str().unwrap(), 10),
                &mut state,
            )
            .await
            .unwrap();

        assert_eq!(state.state().get("via_file"), Some(&json!(true)));
        let len = state.state().get("blob_len").unwrap().as_i64().unwrap();
        assert_eq!(len as usize, big.len());
        cleanup(&dir);
    }

    #[tokio::test]
    async fn python_script_can_emit_routing_and_state() {
        if !cmd_available("python3") {
            eprintln!("skipping: python3 not available");
            return;
        }
        let (dir, path) = write_script(
            r#"import os, json
state = json.loads(os.environ["GRAPH_STATE"])
print(json.dumps({
    "_next": "next_node",
    "doubled": state.get("n", 0) * 2,
}))
"#,
            "py",
        );
        let mut initial = HashMap::new();
        initial.insert("n".into(), json!(21));
        let mut state = StateManager::new(initial);

        let executor = ScriptExecutor::new(&dir);
        let next = executor
            .execute(
                &node_for(path.file_name().unwrap().to_str().unwrap(), 5),
                &mut state,
            )
            .await
            .unwrap();

        assert_eq!(next.as_deref(), Some("next_node"));
        assert_eq!(state.state().get("doubled"), Some(&json!(42)));
        cleanup(&dir);
    }

    #[tokio::test]
    async fn unknown_extension_is_rejected() {
        let (dir, path) = write_script("echo hi", "xyz");
        let mut state = StateManager::new(HashMap::new());
        let executor = ScriptExecutor::new(&dir);

        let err = executor
            .execute(
                &node_for(path.file_name().unwrap().to_str().unwrap(), 5),
                &mut state,
            )
            .await
            .unwrap_err()
            .to_string();

        assert!(
            err.contains("Unsupported script extension '.xyz'"),
            "got: {err}"
        );
        cleanup(&dir);
    }
}