tiny-agent 0.2.0

一个小而完整的 Rust LLM Agent 运行时:可中断、可恢复、可观测、可插拔的 agent loop / A small but complete LLM agent runtime in Rust — an interruptible, resumable, observable, pluggable agent loop.
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
mod ask_followup_question;
mod bash;
mod check;
mod kill;
mod read_file;
mod read_skill;
mod spawn_agent;
mod write_file;

pub use spawn_agent::register_spawn_agent;

use crate::skills::SkillManager;
use crate::tools::ToolRegistry;
use std::sync::Arc;

/// 把内置工具一次性注册进 registry。
///
/// 工具函数签名都是 `fn(Arc<dyn Sandbox>, Args)`,sandbox 在 `ToolRegistry::call`
/// 时按会话注入,所以这里直接注册函数本身,无需包装闭包。
pub fn register_default_tools(registry: &mut ToolRegistry) {
    registry.register(
        "askFollowupQuestion",
        "向用户提出一个追问,并让 agent 暂停到 WaitingForUser 状态",
        false,
        ask_followup_question::ask_followup_question,
    );
    registry.register(
        "read_file",
        "读取指定文件的内容",
        true,
        read_file::read_file,
    );
    registry.register(
        "write_file",
        "写入或局部编辑文件,支持 write/replace/insert_after/insert_before/append",
        false,
        write_file::write_file,
    );
    registry.register_with_ctx(
        "bash",
        "执行一条 bash 命令。命令在 2 秒内跑完则直接返回 {status:\"completed\", exit_code, output};\
         超过 2 秒未结束则转入后台,返回 {id, status:\"running\", output:<已有输出>}——此时进程仍在跑,\
         请稍后用 check 工具凭 id 回来查看新增输出和最终状态(模型不会被自动通知完成),或用 kill 终止。",
        false,
        bash::bash,
    );
    registry.register_with_ctx(
        "check",
        "查看某个后台任务(bash 返回的 running 任务)自上次以来的新增输出与当前状态。\
         可传 wait_secs 让 check 先等待指定秒数再返回,避免过于频繁轮询。\
         返回 {status:\"running\"|\"completed\", exit_code, output:<新增>}。",
        true,
        check::check,
    );
    registry.register_with_ctx(
        "kill",
        "终止一个后台任务(按 bash 返回的 id)。",
        false,
        kill::kill,
    );
}

pub fn register_skill_tools(registry: &mut ToolRegistry, skills: Arc<SkillManager>) {
    read_skill::register_read_skill(registry, skills);
}

/// 用单引号包裹字符串,使其能安全地作为单个 shell 参数传递。
pub fn sh_quote(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('\'');
    for ch in s.chars() {
        if ch == '\'' {
            out.push_str("'\\''");
        } else {
            out.push(ch);
        }
    }
    out.push('\'');
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sandbox::{HostSandbox, Sandbox};
    use crate::tools::ToolOutcome;
    use read_file::ReadFileArgs;
    use serde_json::{Value, json};
    use std::sync::Arc;
    use std::time::Duration;
    use tokio::time::Instant;
    use write_file::{WriteFileArgs, WriteFileMode};

    /// 取出普通完成态的 `Value`,测试里断言工具输出时用。
    fn completed(outcome: ToolOutcome) -> Value {
        match outcome {
            ToolOutcome::Completed(value) => value,
            other => panic!("expected Completed, got {other:?}"),
        }
    }

    #[test]
    fn sh_quote_wraps_plain_string() {
        assert_eq!(sh_quote("foo.txt"), "'foo.txt'");
    }

    #[test]
    fn sh_quote_escapes_single_quote() {
        assert_eq!(sh_quote("a'b"), "'a'\\''b'");
    }

    #[tokio::test]
    async fn write_then_read_round_trips_through_sandbox() {
        let sb: Arc<dyn Sandbox> = Arc::new(HostSandbox::new());
        let dir = std::env::temp_dir();
        let path = dir.join(format!("tiny_agent_test_{}.txt", uuid::Uuid::new_v4()));
        let path_str = path.to_string_lossy().to_string();
        let content = "line one\nline 'two'\n";

        let write_args = WriteFileArgs {
            path: path_str.clone(),
            mode: Some(WriteFileMode::Write),
            content: Some(content.to_string()),
            old_string: None,
            new_string: None,
            replace_all: None,
            expected_replacements: None,
        };
        write_file::write_file(sb.clone(), write_args)
            .await
            .unwrap();

        let read_args = ReadFileArgs {
            path: path_str.clone(),
        };
        let out = read_file::read_file(sb.clone(), read_args).await.unwrap();
        assert_eq!(completed(out)["content"], content);

        let _ = tokio::fs::remove_file(&path).await;
    }

    #[tokio::test]
    async fn ask_followup_question_returns_needs_user_interaction() {
        let mut registry = ToolRegistry::new();
        register_default_tools(&mut registry);
        let sb: Arc<dyn Sandbox> = Arc::new(HostSandbox::new());

        let outcome = registry
            .call(
                "askFollowupQuestion",
                json!({
                    "question": "Which file should I edit?",
                    "options": ["src/main.rs", "Cargo.toml"]
                }),
                sb,
                crate::tools::ToolCtx::default(),
            )
            .await
            .unwrap();

        assert!(matches!(
            outcome,
            ToolOutcome::NeedsUserInteraction(interaction)
                if interaction.kind == "followup_question"
                    && interaction.payload["question"] == "Which file should I edit?"
                    && interaction.payload["options"] == json!(["src/main.rs", "Cargo.toml"])
        ));
    }

    #[tokio::test]
    async fn write_file_replaces_unique_old_string() {
        let sb: Arc<dyn Sandbox> = Arc::new(HostSandbox::new());
        let dir = std::env::temp_dir();
        let path = dir.join(format!("tiny_agent_test_{}.txt", uuid::Uuid::new_v4()));
        let path_str = path.to_string_lossy().to_string();

        write_file::write_file(
            sb.clone(),
            WriteFileArgs {
                path: path_str.clone(),
                mode: Some(WriteFileMode::Write),
                content: Some("alpha\nbeta\ngamma\n".to_string()),
                old_string: None,
                new_string: None,
                replace_all: None,
                expected_replacements: None,
            },
        )
        .await
        .unwrap();

        write_file::write_file(
            sb.clone(),
            WriteFileArgs {
                path: path_str.clone(),
                mode: Some(WriteFileMode::Replace),
                content: None,
                old_string: Some("beta".to_string()),
                new_string: Some("BETA".to_string()),
                replace_all: None,
                expected_replacements: None,
            },
        )
        .await
        .unwrap();

        let out = read_file::read_file(
            sb.clone(),
            ReadFileArgs {
                path: path_str.clone(),
            },
        )
        .await
        .unwrap();
        assert_eq!(completed(out)["content"], "alpha\nBETA\ngamma\n");

        let _ = tokio::fs::remove_file(&path).await;
    }

    #[tokio::test]
    async fn write_file_rejects_ambiguous_replace_by_default() {
        let sb: Arc<dyn Sandbox> = Arc::new(HostSandbox::new());
        let dir = std::env::temp_dir();
        let path = dir.join(format!("tiny_agent_test_{}.txt", uuid::Uuid::new_v4()));
        let path_str = path.to_string_lossy().to_string();

        write_file::write_file(
            sb.clone(),
            WriteFileArgs {
                path: path_str.clone(),
                mode: Some(WriteFileMode::Write),
                content: Some("same\nsame\n".to_string()),
                old_string: None,
                new_string: None,
                replace_all: None,
                expected_replacements: None,
            },
        )
        .await
        .unwrap();

        let result = write_file::write_file(
            sb.clone(),
            WriteFileArgs {
                path: path_str.clone(),
                mode: Some(WriteFileMode::Replace),
                content: None,
                old_string: Some("same".to_string()),
                new_string: Some("changed".to_string()),
                replace_all: None,
                expected_replacements: None,
            },
        )
        .await;

        assert!(result.is_err());
        let _ = tokio::fs::remove_file(&path).await;
    }

    #[tokio::test]
    async fn write_file_can_insert_and_append() {
        let sb: Arc<dyn Sandbox> = Arc::new(HostSandbox::new());
        let dir = std::env::temp_dir();
        let path = dir.join(format!("tiny_agent_test_{}.txt", uuid::Uuid::new_v4()));
        let path_str = path.to_string_lossy().to_string();

        write_file::write_file(
            sb.clone(),
            WriteFileArgs {
                path: path_str.clone(),
                mode: Some(WriteFileMode::Write),
                content: Some("fn main() {\n}\n".to_string()),
                old_string: None,
                new_string: None,
                replace_all: None,
                expected_replacements: None,
            },
        )
        .await
        .unwrap();

        write_file::write_file(
            sb.clone(),
            WriteFileArgs {
                path: path_str.clone(),
                mode: Some(WriteFileMode::InsertAfter),
                content: Some("\n    println!(\"hi\");".to_string()),
                old_string: Some("fn main() {".to_string()),
                new_string: None,
                replace_all: None,
                expected_replacements: None,
            },
        )
        .await
        .unwrap();

        write_file::write_file(
            sb.clone(),
            WriteFileArgs {
                path: path_str.clone(),
                mode: Some(WriteFileMode::Append),
                content: Some("// end\n".to_string()),
                old_string: None,
                new_string: None,
                replace_all: None,
                expected_replacements: None,
            },
        )
        .await
        .unwrap();

        let out = read_file::read_file(
            sb.clone(),
            ReadFileArgs {
                path: path_str.clone(),
            },
        )
        .await
        .unwrap();
        assert_eq!(
            completed(out)["content"],
            "fn main() {\n    println!(\"hi\");\n}\n// end\n"
        );

        let _ = tokio::fs::remove_file(&path).await;
    }

    #[tokio::test]
    async fn bash_completes_fast_command_inline() {
        let mut registry = ToolRegistry::new();
        register_default_tools(&mut registry);
        let sb: Arc<dyn Sandbox> = Arc::new(HostSandbox::new());

        let out = registry
            .call(
                "bash",
                json!({ "command": "echo hi" }),
                sb,
                crate::tools::ToolCtx::default(),
            )
            .await
            .unwrap();
        let v = completed(out);
        assert_eq!(v["status"], "completed");
        assert_eq!(v["exit_code"], 0);
        assert!(v["output"].as_str().unwrap().contains("hi"));
    }

    #[tokio::test]
    async fn bash_yields_long_command_then_check_sees_output_and_kill_stops_it() {
        let mut registry = ToolRegistry::new();
        register_default_tools(&mut registry);
        let sb: Arc<dyn Sandbox> = Arc::new(HostSandbox::new());
        // 同一个 ToolCtx 的 TaskManager 是 Arc 共享的:bash 登记的任务,check/kill 能查到。
        let ctx = crate::tools::ToolCtx::default();

        // 先打印一行,再 sleep 超过 2s 让步窗口。
        let out = registry
            .call(
                "bash",
                json!({ "command": "echo first; sleep 5" }),
                sb.clone(),
                ctx.clone(),
            )
            .await
            .unwrap();
        let v = completed(out);
        assert_eq!(v["status"], "running");
        assert!(v["output"].as_str().unwrap().contains("first"));
        let id = v["id"].as_str().unwrap().to_string();

        // check:任务仍在跑(还没到 exit)。
        let cout = registry
            .call("check", json!({ "id": id }), sb.clone(), ctx.clone())
            .await
            .unwrap();
        assert_eq!(completed(cout)["status"], "running");

        // kill:能找到并终止。
        let kout = registry
            .call("kill", json!({ "id": id }), sb.clone(), ctx.clone())
            .await
            .unwrap();
        assert_eq!(completed(kout)["status"], "killed");

        // kill 之后再 check:任务已不在登记表。
        let err = registry.call("check", json!({ "id": id }), sb, ctx).await;
        assert!(err.is_err());
    }

    #[tokio::test]
    async fn check_wait_secs_sleeps_before_polling() {
        let mut registry = ToolRegistry::new();
        register_default_tools(&mut registry);
        let sb: Arc<dyn Sandbox> = Arc::new(HostSandbox::new());
        let ctx = crate::tools::ToolCtx::default();

        let out = registry
            .call(
                "bash",
                json!({ "command": "echo first; sleep 4" }),
                sb.clone(),
                ctx.clone(),
            )
            .await
            .unwrap();
        let id = completed(out)["id"].as_str().unwrap().to_string();

        let started = Instant::now();
        let cout = registry
            .call(
                "check",
                json!({ "id": id, "wait_secs": 1 }),
                sb.clone(),
                ctx.clone(),
            )
            .await
            .unwrap();
        assert!(started.elapsed() >= Duration::from_millis(900));
        assert_eq!(completed(cout)["status"], "running");

        let _ = registry.call("kill", json!({ "id": id }), sb, ctx).await;
    }

    #[tokio::test]
    async fn read_missing_file_returns_err() {
        let sb: Arc<dyn Sandbox> = Arc::new(HostSandbox::new());
        let args = ReadFileArgs {
            path: "/no/such/path/really_missing_12345".to_string(),
        };
        assert!(read_file::read_file(sb, args).await.is_err());
    }
}