use std::error::Error;
use std::path::Path;
use std::sync::{Arc, mpsc};
use std::time::Duration;
use airsl::mlua::{self, Lua, Table, Value};
use airsl::{Engine, HostModule, InstallContext, ModuleName, Script};
use serde_json::{Value as Json, json};
use crate::host::caller::{caller, locate};
use crate::host::engine::build_engine;
use crate::host::events::{Dispatched, Event, dispatch};
use crate::host::failure::{Raised, wrap};
use crate::host::files::LuaFiles;
use crate::host::module::AgentstacksModule;
use crate::host::read::ReadSnapshot;
use crate::host::state::{Loan, Phase, RunState, SharedState};
use crate::port::{FakeFileTree, Workspace};
use crate::types::extension::Extension;
use crate::types::frontmatter::{AgentMeta, SkillMeta};
use crate::types::hooks::{HookEvent, MatchValue};
use crate::types::manifest::PackVersion;
use crate::types::name::{ItemName, PackName, ToolName};
use crate::types::op::{
ItemId, OpPath, PlanAction, PlanAgent, PlanFile, PlanHook, PlanInput, PlanNative,
PlanNativeHook, PlanPack, PlanSkill, Proposals, ValuesInput, ValuesPack,
};
use crate::types::plan::Reads;
use crate::types::report::{Diagnostic, FieldError, Location};
use crate::types::tokens::Var;
use crate::types::tree::TreePath;
fn manifest(reads: &[&str]) -> String {
let listed: Vec<String> = reads.iter().map(|path| format!("{path:?}")).collect();
format!(
"[extension]\nname = \"claude\"\nversion = \"0.1.0\"\napi = 0\ndescription = \"d\"\nentry = \"adapter.lua\"\nreads = [{}]\n",
listed.join(", ")
)
}
pub(super) fn tree(reads: &[&str], files: &[(&str, &[u8])]) -> FakeFileTree {
let mut tree = FakeFileTree::new("ext").file("extension.toml", manifest(reads).as_bytes());
for (path, bytes) in files {
tree = tree.file(path, bytes);
}
tree
}
pub(super) fn load(tree: &FakeFileTree) -> Result<Extension, Box<dyn Error>> {
Extension::load(tree).map_err(|refusals| {
let shown: Vec<String> = refusals.into_iter().map(|d| d.to_string()).collect();
shown.join("; ").into()
})
}
pub(super) fn lua_files(files: &[(&str, &[u8])]) -> Result<Arc<LuaFiles>, Box<dyn Error>> {
let mut all: Vec<(&str, &[u8])> = files.to_vec();
if !all.iter().any(|(path, _)| *path == "adapter.lua") {
all.push(("adapter.lua", b""));
}
let tree = tree(&[], &all);
let extension = load(&tree)?;
let read = LuaFiles::read(&tree, &extension).map_err(|refusals| {
let shown: Vec<String> = refusals.into_iter().map(|d| d.to_string()).collect();
shown.join("; ")
})?;
Ok(Arc::new(read))
}
pub(super) fn finishes_within<T: Send + 'static>(
limit: Duration,
work: impl FnOnce() -> T + Send + 'static,
) -> Option<T> {
let (sender, receiver) = mpsc::channel();
std::thread::spawn(move || {
let _ = sender.send(work());
});
receiver.recv_timeout(limit).ok()
}
pub(super) struct Planned {
pub(super) result: Result<Dispatched, String>,
pub(super) proposals: Proposals,
pub(super) reads: Reads,
}
pub(super) struct Rig {
engine: Engine,
state: SharedState,
tool: ToolName,
entry: TreePath,
reads: Vec<OpPath>,
}
impl Rig {
pub(super) fn new() -> Result<Self, Box<dyn Error>> {
Self::with(&[], &[])
}
pub(super) fn with(reads: &[&str], files: &[(&str, &[u8])]) -> Result<Self, Box<dyn Error>> {
let tool = ToolName::new("claude")?;
let state = SharedState::new(tool.clone());
let engine = build_engine(AgentstacksModule::new(state.clone(), lua_files(files)?)?)?;
let reads = reads
.iter()
.map(|path| OpPath::new(path))
.collect::<Result<Vec<_>, _>>()?;
Ok(Self {
engine,
state,
tool,
entry: TreePath::from_parts(&["adapter.lua"]),
reads,
})
}
pub(super) fn run(&self, source: &str) -> Result<(), String> {
let script = Script::from_source(source, self.entry.as_str()).map_err(|e| e.to_string())?;
self.engine.eval(&script).map_err(|e| self.shown(&e))
}
pub(super) fn text(&self, source: &str) -> Result<String, String> {
let script = Script::from_source(source, self.entry.as_str()).map_err(|e| e.to_string())?;
self.engine
.eval_to::<String>(&script)
.map_err(|e| self.shown(&e))
}
pub(super) fn recorded(&self) -> usize {
self.state.with(|run| run.take_recorded().len())
}
pub(super) fn refusals(&self) -> Vec<String> {
let found = self.state.with(RunState::take_recorded);
found.into_iter().map(|d| d.to_string()).collect()
}
pub(super) fn dispatch(&self, event: Event, payload: &Json) -> Result<Dispatched, String> {
if event == Event::Values {
self.state.with(|run| run.set_phase(Phase::Values));
}
let dispatched = dispatch(&self.engine, event, payload).map_err(|e| self.shown(&e));
self.state.with(|run| run.set_phase(Phase::Load));
dispatched
}
pub(super) fn plan<W: Workspace>(
&self,
input: &PlanInput,
proposals: Proposals,
workspace: &W,
) -> Planned {
let loan = Loan {
input: input.clone(),
proposals,
snapshot: ReadSnapshot::take(workspace, &self.reads),
reads: Reads::default(),
};
self.state.with(|run| run.begin_plan(loan));
let result = dispatch(&self.engine, Event::Plan, &json!({})).map_err(|e| self.shown(&e));
let loan = self.state.with(RunState::end_plan);
let (proposals, reads) = loan.map_or_else(
|| (Proposals::new(), Reads::default()),
|loan| (loan.proposals, loan.reads),
);
Planned {
result,
proposals,
reads,
}
}
fn shown(&self, error: &airsl::Error) -> String {
wrap(&self.tool, &self.entry, error)
.map_or_else(|| "(recorded)".to_owned(), |d| d.to_string())
}
}
#[derive(Debug)]
pub(super) struct Probe {
name: ModuleName,
tool: ToolName,
}
impl Probe {
pub(super) fn new(tool: ToolName) -> airsl::Result<Self> {
Ok(Self {
name: ModuleName::new("probe")?,
tool,
})
}
fn fill(&self, lua: &Lua, table: &Table) -> mlua::Result<()> {
let tool = self.tool.clone();
let at = lua.create_function(move |lua, ()| Ok(locate(lua, &tool).to_string()))?;
table.set("where", at)?;
let tool = self.tool.clone();
let origin = lua.create_function(move |lua, ()| {
let shown = |place: Option<Location>| place.map(|l| l.to_string()).unwrap_or_default();
Ok(caller(lua)
.map(|caller| caller.origin(&tool))
.map_or_else(String::new, |origin| {
format!("{}|{}", shown(origin.location()), shown(origin.site()))
}))
})?;
table.set("origin", origin)?;
let module = lua.create_function(|lua, (source, path): (String, String)| {
lua.load(source)
.set_name(format!("@{path}"))
.call::<Value>(())
})?;
table.set("module", module)?;
let recorded = lua.create_function(|_, text: String| -> mlua::Result<()> {
Err(Raised::recorded(text).into_lua())
})?;
table.set("raise_recorded", recorded)?;
let tool = self.tool.clone();
let ordinary = lua.create_function(move |lua, ()| -> mlua::Result<()> {
let refusal = Diagnostic::new(locate(lua, &tool), FieldError::Required);
Err(Raised::ordinary(refusal).into_lua())
})?;
table.set("raise_ordinary", ordinary)
}
}
impl HostModule for Probe {
fn name(&self) -> &ModuleName {
&self.name
}
fn install(
&self,
lua: &Lua,
table: &Table,
_context: &InstallContext<'_>,
) -> airsl::Result<()> {
self.fill(lua, table)
.map_err(|error| airsl::Error::lua("probe", error))
}
}
fn document(name: &str, lines: &str) -> String {
format!("---\nname: {name}\n{lines}---\nbody\n")
}
fn payload_file(id: ItemId, rel: &str, text: Option<&str>) -> PlanFile {
PlanFile {
id,
rel: TreePath::from_parts(&[rel]),
text: text.map(str::to_owned),
}
}
pub(super) fn plan_input() -> Result<PlanInput, Box<dyn Error>> {
let core = PackName::new("core")?;
let status = ItemName::new("status")?;
let coder = ItemName::new("coder")?;
let claude = ToolName::new("claude")?;
let skill_meta = SkillMeta::parse(
Path::new("SKILL.md"),
&document(
"status",
"description: Shows the status\ninvocation: user\n",
),
&status,
)
.map_err(|found| format!("{found:?}"))?;
let agent_meta = AgentMeta::parse(
Path::new("coder.md"),
&document("coder", "description: Writes code\nmodel: balanced\n"),
&coder,
)
.map_err(|found| format!("{found:?}"))?;
let skill = PlanSkill {
id: ItemId::skill(&core, &status),
name: status.clone(),
dir: OpPath::new(".claude/skills/status")?,
meta: skill_meta,
files: vec![
payload_file(
ItemId::skill_file(&core, &status, &TreePath::from_parts(&["SKILL.md"])),
"SKILL.md",
Some("body"),
),
payload_file(
ItemId::skill_file(&core, &status, &TreePath::from_parts(&["logo.png"])),
"logo.png",
None,
),
],
};
let agent = PlanAgent {
id: ItemId::agent(&core, &coder),
name: coder.clone(),
meta: agent_meta,
text: "body".to_owned(),
};
let hooks = vec![
PlanHook {
id: ItemId::hook(&core, 0),
event: HookEvent::ToolBefore,
matches: Some(vec![MatchValue::Read, MatchValue::Edit, MatchValue::Write]),
agents: None,
action: PlanAction::Lua {
may_block: false,
command: vec!["airsl".to_owned(), "run".to_owned(), "x".to_owned()],
},
},
PlanHook {
id: ItemId::hook(&core, 1),
event: HookEvent::SessionEnd,
matches: None,
agents: None,
action: PlanAction::Message {
text: "Reminder".to_owned(),
},
},
];
let native = PlanNative {
files: vec![payload_file(
ItemId::native_file(&core, &claude, &TreePath::from_parts(&["x.md"])),
"x.md",
Some("x"),
)],
hooks: vec![PlanNativeHook {
id: ItemId::native_hook(&core, 0),
event: "SubagentStop".to_owned(),
matches: Some(vec!["Edit".to_owned(), "Write".to_owned()]),
action: PlanAction::Lua {
may_block: false,
command: vec!["airsl".to_owned(), "run".to_owned(), "y".to_owned()],
},
}],
};
Ok(PlanInput {
tool: claude,
root: OpPath::new(".claude/agentstacks")?,
packs: vec![PlanPack {
name: core,
version: PackVersion::new("0.3.0")?,
skills: vec![skill],
agents: vec![agent],
hooks,
native,
}],
})
}
pub(super) fn values_input() -> Result<ValuesInput, Box<dyn Error>> {
Ok(ValuesInput {
tool: ToolName::new("claude")?,
packs: vec![ValuesPack {
name: PackName::new("core")?,
version: PackVersion::new("0.3.0")?,
skills: vec![ItemName::new("status")?],
agents: vec![ItemName::new("coder")?],
}],
vars: vec![Var::SessionId, Var::Tmpdir],
})
}
pub(super) fn extension(
entry: &str,
reads: &[&str],
files: &[(&str, &[u8])],
) -> Result<(Extension, FakeFileTree), Box<dyn Error>> {
let mut all: Vec<(&str, &[u8])> = vec![("adapter.lua", entry.as_bytes())];
all.extend_from_slice(files);
let tree = tree(reads, &all);
let loaded = load(&tree)?;
Ok((loaded, tree))
}