agent-works 0.16.1

Batteries-included Agent toolbox built on agent-base
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
use std::path::{Path, PathBuf};

use super::super::manifest::ResolvedCapability;
use super::super::registry::{PackageStatus, PluginRegistry, ToolPin, hex_sha256};
use super::build::pin_server_argv;
use super::source::{extract_archive, normalize_relative};
use super::*;
use crate::script_tool::ScriptLawError;

/// Platform-independent absolute path (test criterion under the same law
/// as `Path::is_absolute`).
fn abs(rel: &str) -> PathBuf {
    std::env::current_dir().unwrap().join(rel)
}

/// Whether a path ends with the given trailing components, whatever the
/// platform's separator is (production pushes pinned paths through
/// `Path::components()`, so the separator is the platform's).
fn path_ends_with(path: &str, tail: &[&str]) -> bool {
    let comps: Vec<_> = Path::new(path).components().collect();
    comps.len() >= tail.len()
        && comps[comps.len() - tail.len()..]
            .iter()
            .map(|c| c.as_os_str().to_string_lossy().into_owned())
            .eq(tail.iter().map(|s| s.to_string()))
}

/// Write a script and set the executable bit (unix) — the install law
/// requires directly-executed `run[0]` to be executable.
fn write_script(path: &Path, contents: &str) {
    std::fs::write(path, contents).unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perm = std::fs::metadata(path).unwrap().permissions();
        perm.set_mode(0o755);
        std::fs::set_permissions(path, perm).unwrap();
    }
}

fn write_basic_plugin(dir: &Path) {
    std::fs::create_dir_all(dir.join("scripts")).unwrap();
    std::fs::create_dir_all(dir.join("wasm")).unwrap();
    std::fs::create_dir_all(dir.join("server")).unwrap();
    std::fs::write(
        dir.join("plugin.json"),
        serde_json::json!({
            "schemaVersion": 1,
            "name": "my-tools",
            "version": "0.1.0",
            "tools": [
                {
                    "name": "deploy", "form": "script",
                    "description": "deploy it",
                    "run": ["scripts/deploy.sh", "--env", "${env}"],
                    "parameters": {"env": {"type": "string"}},
                    "timeout_secs": 120
                },
                {
                    "name": "wiki", "form": "mcp",
                    "server": {
                        "command": ["python", "server/main.py"],
                        "env": {"WIKI_TOKEN": "${ENV:WIKI_TOKEN}"}
                    }
                }
            ]
        })
        .to_string(),
    )
    .unwrap();
    write_script(&dir.join("scripts/deploy.sh"), "#!/bin/sh\necho deployed\n");
    std::fs::write(dir.join("server/main.py"), "print('wiki')\n").unwrap();
}

#[tokio::test]
async fn plan_then_commit_installs_and_pins() {
    let tmp = tempfile::tempdir().unwrap();
    let plugins_root = tmp.path().join("plugins");
    let source_dir = tmp.path().join("src-plugin");
    write_basic_plugin(&source_dir);

    let plan = plan_install(&PluginSource::Path(source_dir), &plugins_root)
        .await
        .expect("plan");

    // Review digest: full argv + absolute paths (mechanism side of UX
    // criterion 3).
    let deploy = plan
        .digest
        .tools
        .iter()
        .find(|t| t.identity == "plugin.my-tools.deploy")
        .unwrap();
    // Component-wise join: the production path is re-pushed through
    // `Path::components()`, so the separator is the platform's (`\` on
    // Windows). Joining the whole relative path in one call would keep the
    // literal `/` and never match.
    let run_abs = plugins_root
        .join("my-tools")
        .join("scripts")
        .join("deploy.sh")
        .to_string_lossy()
        .into_owned();
    assert_eq!(deploy.summary, format!("{run_abs} --env ${{env}}"));
    assert_eq!(deploy.timeout_secs, Some(120));

    // Before human confirmation: neither the final directory nor the
    // registry exists.
    assert!(!plugins_root.join("my-tools").exists());
    assert!(!PluginRegistry::path_in(&plugins_root).exists());

    // Standard install trio: env only flows as ${ENV:VAR} references
    // (never resolved).
    let mut registry = PluginRegistry::new();
    let installed = commit_install(&plan, &mut registry).expect("commit");
    assert!(plugins_root.join("my-tools/plugin.json").is_file());
    assert!(registry.get("my-tools").is_some());

    let pins = &registry.get("my-tools").unwrap().tools;
    let script_pin = pins
        .iter()
        .find_map(|t| match t {
            ToolPin::Script { identity, run } if identity == "plugin.my-tools.deploy" => {
                Some(run.clone())
            }
            _ => None,
        })
        .unwrap();
    assert_eq!(script_pin[0], run_abs, "run[0] pinned to an absolute path");
    assert!(matches!(
        &pins[1],
        ToolPin::Mcp { env, command: Some(cmd), .. }
            if env.get("WIKI_TOKEN").map(String::as_str) == Some("${ENV:WIKI_TOKEN}")
                && cmd[0] == "python"
                // The pinned path is spelled with the platform's separator
                // (production pushes it through `Path::components()`), so the
                // tail is asserted component-wise, not as a literal string.
                && path_ends_with(&cmd[1], &["server", "main.py"])
                && Path::new(&cmd[1]).is_absolute()
    ));
    assert_eq!(
        installed.identity_keys,
        vec!["plugin.my-tools.deploy", "plugin.my-tools.wiki"]
    );

    // The manifest hash in the registry matches the one on disk (load-time
    // re-verification passes).
    let report = registry.verify(&plugins_root.join("my-tools"));
    assert_eq!(report.package, PackageStatus::Trusted);
}

#[tokio::test]
async fn discard_leaves_nothing() {
    let tmp = tempfile::tempdir().unwrap();
    let plugins_root = tmp.path().join("plugins");
    let source_dir = tmp.path().join("src-plugin");
    write_basic_plugin(&source_dir);

    let plan = plan_install(&PluginSource::Path(source_dir), &plugins_root)
        .await
        .expect("plan");
    plan.discard();
    assert!(!plugins_root.join("my-tools").exists());
    let leftovers = std::fs::read_dir(&plugins_root)
        .map(|rd| rd.count())
        .unwrap_or(0);
    assert_eq!(leftovers, 0, "staging must be cleaned up too");
}

#[tokio::test]
async fn replace_reinstall_swaps_pin() {
    // "Re-run plugin add to re-review": installing the same name again =
    // replace + re-pin.
    let tmp = tempfile::tempdir().unwrap();
    let plugins_root = tmp.path().join("plugins");
    let source_dir = tmp.path().join("src-plugin");
    write_basic_plugin(&source_dir);

    let mut registry = PluginRegistry::new();
    let plan = plan_install(&PluginSource::Path(source_dir.clone()), &plugins_root)
        .await
        .unwrap();
    commit_install(&plan, &mut registry).unwrap();

    // The author changed the script content and installed again.
    write_script(
        &source_dir.join("scripts/deploy.sh"),
        "#!/bin/sh\necho v2\n",
    );
    let plan = plan_install(&PluginSource::Path(source_dir), &plugins_root)
        .await
        .unwrap();
    commit_install(&plan, &mut registry).unwrap();

    let report = registry.verify(&plugins_root.join("my-tools"));
    assert_eq!(report.package, PackageStatus::Trusted);
}

#[tokio::test]
async fn remove_clears_dir_registry_and_ledger() {
    let tmp = tempfile::tempdir().unwrap();
    let plugins_root = tmp.path().join("plugins");
    let source_dir = tmp.path().join("src-plugin");
    write_basic_plugin(&source_dir);

    let mut registry = PluginRegistry::new();
    let plan = plan_install(&PluginSource::Path(source_dir), &plugins_root)
        .await
        .unwrap();
    let installed = commit_install(&plan, &mut registry).unwrap();

    // Record a ledger tier first (simulate prior use).
    let mut ledger = crate::approval_ledger::ApprovalLedger::new();
    ledger.set_tier(
        "plugin.my-tools.deploy",
        crate::approval_ledger::ApprovalTier::AlwaysAllow,
    );
    ledger.set_tier(
        "plugin.other.search",
        crate::approval_ledger::ApprovalTier::AlwaysAllow,
    );

    let report = remove_plugin(&plugins_root, &mut registry, "my-tools").expect("remove");
    assert!(report.dir_removed);
    assert!(report.registry_removed);
    assert!(registry.get("my-tools").is_none());
    assert!(!installed.plugin_dir.exists());

    // One of the three places: plugin.my-tools.* wiped, others untouched.
    let swept = report.sweep_ledger(&mut ledger);
    assert_eq!(swept, 1);
    assert_eq!(
        ledger.tier_of("plugin.my-tools.deploy"),
        crate::approval_ledger::ApprovalTier::Ask
    );
    assert_eq!(
        ledger.tier_of("plugin.other.search"),
        crate::approval_ledger::ApprovalTier::AlwaysAllow
    );
    assert_eq!(
        report.identity_keys,
        vec!["plugin.my-tools.deploy", "plugin.my-tools.wiki"]
    );
}

#[tokio::test]
async fn remove_unknown_plugin_errors() {
    let tmp = tempfile::tempdir().unwrap();
    let plugins_root = tmp.path().join("plugins");
    let mut registry = PluginRegistry::new();
    let err = remove_plugin(&plugins_root, &mut registry, "ghost").unwrap_err();
    assert!(matches!(err, InstallError::NotInstalled { name } if name == "ghost"));
}

// ── zip-slip / archive channel ────────────────────────────────────

#[test]
fn normalize_relative_rejects_traversal() {
    assert!(normalize_relative(Path::new("ok/inner.txt")).is_some());
    assert!(normalize_relative(Path::new("./ok")).is_some());
    assert!(normalize_relative(Path::new("../escape")).is_none());
    assert!(normalize_relative(Path::new("a/../../b")).is_none());
    assert!(normalize_relative(Path::new("/abs")).is_none());
    assert!(normalize_relative(Path::new("")).is_none());
}

#[test]
fn tar_gz_zip_slip_is_rejected() {
    // Build a tar.gz with a `../evil` entry (bypassing tar::Builder's path
    // law by writing the GNU header directly — exactly how real malicious
    // packages are made).
    let mut raw = Vec::new();
    {
        let encoder = flate2::write::GzEncoder::new(&mut raw, flate2::Compression::default());
        let mut builder = tar::Builder::new(encoder);
        let mut header = tar::Header::new_gnu();
        header.set_size(5);
        header.set_mode(0o644);
        header.set_entry_type(tar::EntryType::Regular);
        header.as_gnu_mut().unwrap().name[..7].copy_from_slice(b"../evil");
        header.set_cksum();
        builder.append(&header, &b"pwned"[..]).expect("append");
        builder.finish().expect("finish");
    }

    let tmp = tempfile::tempdir().unwrap();
    let err = extract_archive(&raw, ArchiveFormat::TarGz, tmp.path()).unwrap_err();
    assert!(
        matches!(err, InstallError::ZipSlip { ref entry } if entry.contains("evil")),
        "{err:?}"
    );
    assert!(!tmp.path().join("../evil").exists());
}

#[test]
fn tar_gz_extracts_clean_archive() {
    let mut raw = Vec::new();
    {
        let encoder = flate2::write::GzEncoder::new(&mut raw, flate2::Compression::default());
        let mut builder = tar::Builder::new(encoder);
        let mut header = tar::Header::new_gnu();
        header.set_size(5);
        header.set_mode(0o644);
        header.set_cksum();
        builder
            .append_data(&mut header, "plugin.json", &b"hello"[..])
            .unwrap();
        builder.finish().unwrap();
    }
    let tmp = tempfile::tempdir().unwrap();
    extract_archive(&raw, ArchiveFormat::TarGz, tmp.path()).unwrap();
    assert_eq!(
        std::fs::read_to_string(tmp.path().join("plugin.json")).unwrap(),
        "hello"
    );
}

// ── source parsing ────────────────────────────────────────────────────

#[test]
fn source_parse_channels() {
    assert_eq!(
        PluginSource::parse("https://x.example/my-tools.git").unwrap(),
        PluginSource::Git {
            url: "https://x.example/my-tools.git".into(),
            rev: None
        }
    );
    assert_eq!(
        PluginSource::parse("git@github.com:me/my-tools.git").unwrap(),
        PluginSource::Git {
            url: "git@github.com:me/my-tools.git".into(),
            rev: None
        }
    );
    assert_eq!(
        PluginSource::parse("https://x.example/my-tools.tar.gz").unwrap(),
        PluginSource::ArchiveUrl {
            url: "https://x.example/my-tools.tar.gz".into(),
            format: ArchiveFormat::TarGz
        }
    );
    assert!(matches!(
        PluginSource::parse("https://x.example/page.html"),
        Err(InstallError::BadRequest { .. })
    ));
    assert!(matches!(
        PluginSource::parse("/definitely/not/here"),
        Err(InstallError::BadRequest { .. })
    ));
    assert_eq!(
        PluginSource::parse("packs/my-tools.zip").unwrap(),
        PluginSource::ArchivePath {
            path: PathBuf::from("packs/my-tools.zip"),
            format: ArchiveFormat::Zip
        }
    );
}

#[test]
fn pin_server_argv_pins_paths_keeps_interpreters() {
    let root = abs("plugin-root-test");
    let pinned = pin_server_argv(
        &[
            "python".into(),
            "server/main.py".into(),
            abs("/usr/bin/python3").to_string_lossy().into_owned(),
        ],
        &root,
    )
    .unwrap();
    assert_eq!(pinned[0], "python", "bare-name interpreter kept as-is");
    assert_eq!(
        pinned[1],
        root.join("server")
            .join("main.py")
            .to_string_lossy()
            .into_owned(),
        "in-package relative path pinned absolute"
    );
    assert!(
        Path::new(&pinned[2]).is_absolute(),
        "explicit absolute interpreter kept as-is"
    );

    // Path-shaped arguments that escape the plugin root are rejected.
    let err = pin_server_argv(&["python".into(), "../evil.py".into()], &root).unwrap_err();
    assert!(
        matches!(err, ScriptLawError::EscapedPluginRoot { .. }),
        "{err:?}"
    );
}

#[tokio::test]
async fn wasm_missing_at_install_is_reported() {
    // plugin.json lists a wasm tool but the .wasm is missing → cannot
    // install (fail-closed); a half package is never pinned into the
    // registry.
    let tmp = tempfile::tempdir().unwrap();
    let plugins_root = tmp.path().join("plugins");
    let source_dir = tmp.path().join("src-plugin");
    std::fs::create_dir_all(&source_dir).unwrap();
    std::fs::write(
            source_dir.join("plugin.json"),
            serde_json::json!({
                "schemaVersion": 1, "name": "my-tools", "version": "0.1.0",
                "tools": [{"name": "search", "form": "wasm", "module": "wasm/s.wasm", "description": "d"}]
            })
            .to_string(),
        )
        .unwrap();

    let err = plan_install(&PluginSource::Path(source_dir), &plugins_root)
        .await
        .unwrap_err();
    assert!(matches!(err, InstallError::Io(_)), "{err:?}");
}

#[tokio::test]
async fn script_missing_at_install_is_reported() {
    // Same law as missing wasm files: the manifest lists a script tool but
    // the file is absent (acceptance fixture: a missing script file must
    // block a half-package install) → cannot install, and the error says
    // which file is missing.
    let tmp = tempfile::tempdir().unwrap();
    let plugins_root = tmp.path().join("plugins");
    let source_dir = tmp.path().join("src-plugin");
    std::fs::create_dir_all(source_dir.join("scripts")).unwrap();
    std::fs::write(
        source_dir.join("plugin.json"),
        serde_json::json!({
            "schemaVersion": 1, "name": "my-tools", "version": "0.1.0",
            "tools": [{
                "name": "deploy", "form": "script",
                "description": "deploy it",
                "run": ["scripts/deploy.sh", "--env", "${env}"],
                "parameters": {"env": {"type": "string"}}
            }]
        })
        .to_string(),
    )
    .unwrap();

    let err = plan_install(&PluginSource::Path(source_dir), &plugins_root)
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("scripts/deploy.sh") && err.to_string().contains("does not exist"),
        "missing files must be named: {err}"
    );
}

#[cfg(unix)]
#[tokio::test]
async fn script_not_executable_at_install_is_reported() {
    // `run[0]` is the script body itself, executed directly — no
    // executable bit = it would not run even if installed, so reject at
    // install time (chmod +x and come back).
    let tmp = tempfile::tempdir().unwrap();
    let plugins_root = tmp.path().join("plugins");
    let source_dir = tmp.path().join("src-plugin");
    std::fs::create_dir_all(source_dir.join("scripts")).unwrap();
    std::fs::write(
        source_dir.join("plugin.json"),
        serde_json::json!({
            "schemaVersion": 1, "name": "my-tools", "version": "0.1.0",
            "tools": [{
                "name": "deploy", "form": "script",
                "description": "deploy it",
                "run": ["scripts/deploy.sh"]
            }]
        })
        .to_string(),
    )
    .unwrap();
    std::fs::write(source_dir.join("scripts/deploy.sh"), "#!/bin/sh\necho hi\n").unwrap();
    // 0644 — no executable bit.

    let err = plan_install(&PluginSource::Path(source_dir), &plugins_root)
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("not executable"),
        "a missing executable bit must be stated clearly: {err}"
    );
}

#[tokio::test]
async fn script_interpreter_form_checks_the_script_arg_not_the_interpreter() {
    // Interpreter form: the executable bit is checked on the interpreter
    // (PATH resolution, not the installer's business), but the script
    // argument must be in the package.
    let tmp = tempfile::tempdir().unwrap();
    let plugins_root = tmp.path().join("plugins");
    let source_dir = tmp.path().join("src-plugin");
    std::fs::create_dir_all(source_dir.join("scripts")).unwrap();
    std::fs::write(
        source_dir.join("plugin.json"),
        serde_json::json!({
            "schemaVersion": 1, "name": "my-tools", "version": "0.1.0",
            "tools": [{
                "name": "deploy", "form": "script",
                "description": "deploy it",
                "run": ["cmd", "/c", "scripts/deploy.bat"]
            }]
        })
        .to_string(),
    )
    .unwrap();

    let err = plan_install(&PluginSource::Path(source_dir), &plugins_root)
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("deploy.bat") && err.to_string().contains("does not exist"),
        "the interpreter form checks the script argument: {err}"
    );
}

#[tokio::test]
async fn capability_pinned_with_resolved_values() {
    let tmp = tempfile::tempdir().unwrap();
    let plugins_root = tmp.path().join("plugins");
    let source_dir = tmp.path().join("src-plugin");
    std::fs::create_dir_all(source_dir.join("wasm")).unwrap();
    std::fs::write(source_dir.join("wasm/s.wasm"), b"wasm-bytes").unwrap();
    std::fs::write(
        source_dir.join("plugin.json"),
        serde_json::json!({
            "schemaVersion": 1, "name": "my-tools", "version": "0.1.0",
            "tools": [{
                "name": "search", "form": "wasm", "module": "wasm/s.wasm", "description": "d",
                "capabilities": [
                    {"type": "fs:read", "paths": ["./data"]},
                    {"type": "net:http", "hosts": ["API.Example.com"]}
                ]
            }]
        })
        .to_string(),
    )
    .unwrap();

    let plan = plan_install(&PluginSource::Path(source_dir), &plugins_root)
        .await
        .expect("plan");
    match &plan.pin.tools[0] {
        ToolPin::Wasm {
            capabilities,
            wasm_sha256,
            module,
            ..
        } => {
            let data_abs = plugins_root
                .join("my-tools")
                .join("data")
                .to_string_lossy()
                .into_owned();
            assert_eq!(
                capabilities,
                &vec![
                    ResolvedCapability::FsRead {
                        paths: vec![data_abs]
                    },
                    ResolvedCapability::NetHttp {
                        hosts: vec!["api.example.com".into()]
                    }
                ]
            );
            assert_eq!(*wasm_sha256, hex_sha256(b"wasm-bytes"));
            assert!(Path::new(module).is_absolute());
        }
        other => panic!("expected wasm pin, got {other:?}"),
    }
}