Files
sausage/host/tests/core_ext.rs
T

162 lines
5.6 KiB
Rust

//! Core world extensions execute through the snapshot loader and the actual VFS.
use sausage::{
exec::{Command, Exec, Options, Stream},
world::World,
};
use std::{path::Path, sync::Arc};
const BUNDLE: &str = include_str!("../js/core-ext-test-bundle.js");
struct Author(Arc<dyn Exec>);
#[async_trait::async_trait]
impl Exec for Author {
async fn exec(
&self,
command: Command,
mut options: Options,
output: &mut (dyn for<'a> FnMut(Stream, &'a [u8]) + Send),
) -> anyhow::Result<i32> {
for (key, value) in [
("GIT_AUTHOR_NAME", "Test"),
("GIT_AUTHOR_EMAIL", "test@example.com"),
("GIT_COMMITTER_NAME", "Test"),
("GIT_COMMITTER_EMAIL", "test@example.com"),
] {
options.env.push((key.into(), value.into()));
}
self.0.exec(command, options, output).await
}
}
fn copy_tree(from: &Path, to: &Path) -> anyhow::Result<()> {
std::fs::create_dir_all(to)?;
for entry in std::fs::read_dir(from)? {
let entry = entry?;
let dest = to.join(entry.file_name());
if entry.file_type()?.is_dir() {
copy_tree(&entry.path(), &dest)?;
} else {
std::fs::copy(entry.path(), dest)?;
}
}
Ok(())
}
fn write(root: &Path, path: &str, text: &str) -> anyhow::Result<()> {
let path = root.join(path);
std::fs::create_dir_all(path.parent().unwrap())?;
std::fs::write(path, text)?;
Ok(())
}
#[tokio::test(flavor = "current_thread")]
async fn core_extensions() -> anyhow::Result<()> {
let repo = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap();
let userland = repo.join("userland");
let target = Path::new(env!("CARGO_TARGET_TMPDIR")).parent().unwrap();
if !userland.join("cwd-init/init.o").exists() {
assert!(
std::process::Command::new("nu")
.args(["--no-config-file", "cwd-init/build.nu"])
.current_dir(&userland)
.status()?
.success()
);
}
assert!(
std::process::Command::new("cargo")
.args(["build", "--release", "-p", "git", "--manifest-path"])
.arg(userland.join("Cargo.toml"))
.args(["--target", "wasm32-wasip2", "--target-dir"])
.arg(target)
.args(["-j", "2", "--locked"])
.current_dir(&userland)
.status()?
.success()
);
let dir = tempfile::tempdir()?;
let world = World::open(dir.path())?;
let disk = dir.path().join("world");
std::fs::create_dir_all(disk.join("bin"))?;
std::fs::copy(
target.join("wasm32-wasip2/release/git.wasm"),
disk.join("bin/git.wasm"),
)?;
let source = disk.join("src/sausage");
for name in ["core", "models", "prompt", "conversations"] {
copy_tree(
&repo.join("extensions").join(name),
&source.join("extensions").join(name),
)?;
}
write(
&source,
"agents/worker.md",
"---\nname: worker\ndescription: Worker\nfamily: fast\ntools: [read]\n---\nWorker body",
)?;
write(
&source,
"agents/models.json",
r#"{"default":{"model":"faux/faux-1"},"fast":{"model":"faux/faux-1","thinking":"low"}}"#,
)?;
write(
&source,
"skills/builtin/SKILL.md",
"---\nname: builtin-skill\ndescription: Builtin skill\n---\nInstructions",
)?;
write(
&source,
"extensions/fixture/server.ts",
r#"import {defineExtension,defineTool} from '@earendil-works/pi-durable';
import {obj} from '@earendil-works/pi-schema';
import {State} from '../conversations/api.ts';
export const order=500;
export default host=>{host.implement({name:'models.pin'},{pin:async()=>globalThis.modelPin});host.onOpen(async()=>{globalThis.core={selection:host.need({name:'models'}),conversations:host.need({name:'conversations'}),State,metadata:host.metadata}});return defineExtension({name:'fixture',tools:['read','write'].map(name=>defineTool({name,description:name,parameters:obj({}),execute:async()=>({output:[]})}))})};"#,
)?;
write(&disk, "AGENTS.md", "Outside instructions")?;
write(&disk, "project/.git/HEAD", "ref: refs/heads/main")?;
write(&disk, "project/AGENTS.md", "Root instructions")?;
write(&disk, "project/sub/AGENTS.md", "Nested instructions")?;
write(
&disk,
"project/.sausage/agents/worker.md",
"---\nname: worker\naddTools: [write]\n---\nProject body",
)?;
write(
&disk,
"project/.sausage/skills/project/SKILL.md",
"---\nname: project-skill\ndescription: Project skill\n---\nInstructions",
)?;
assert!(
std::process::Command::new("git")
.args(["init", "-b", "main"])
.arg(&source)
.status()?
.success()
);
assert!(
std::process::Command::new("git")
.args(["add", "."])
.current_dir(&source)
.status()?
.success()
);
assert!(
std::process::Command::new("git")
.args([
"-c",
"user.name=Test",
"-c",
"user.email=test@example.com",
"commit",
"--no-gpg-sign",
"-m",
"core fixtures"
])
.current_dir(&source)
.status()?
.success()
);
let exec: Arc<dyn Exec> = Arc::new(Author(sausage::process::exec(World {
root: world.root.clone(),
host_dir: world.host_dir.clone(),
processes: world.processes.clone(),
})?));
sausage::harness::run_module(world, exec, BUNDLE).await
}