use std::path::{Path, PathBuf};
use super::events::Event;
use super::{claude, codex, opencode};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Agent {
OpenCode,
Codex,
ClaudeCode,
}
impl Agent {
pub const ALL: [Self; 3] = [Self::OpenCode, Self::Codex, Self::ClaudeCode];
pub const NAMES: [&'static str; 3] = ["opencode", "codex", "claude-code"];
pub fn parse(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|agent| agent.name() == name)
}
pub fn name(self) -> &'static str {
match self {
Self::OpenCode => "opencode",
Self::Codex => "codex",
Self::ClaudeCode => "claude-code",
}
}
pub fn program(self) -> &'static str {
match self {
Self::OpenCode => "opencode",
Self::Codex => "codex",
Self::ClaudeCode => "claude",
}
}
pub fn read(self, line: &str) -> Vec<Event> {
let Ok(serde_json::Value::Object(event)) = serde_json::from_str(line) else {
return Vec::new();
};
match self {
Self::OpenCode => opencode::read(&event),
Self::Codex => codex::read(&event),
Self::ClaudeCode => claude::read(&event),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
ReadOnly,
Write,
}
impl Mode {
pub const NAMES: [&'static str; 2] = ["read-only", "write"];
pub fn parse(name: &str) -> Option<Self> {
match name {
"read-only" => Some(Self::ReadOnly),
"write" => Some(Self::Write),
_ => None,
}
}
pub fn name(self) -> &'static str {
match self {
Self::ReadOnly => "read-only",
Self::Write => "write",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CodexKey {
pub key: &'static str,
pub disabled: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct McpServer {
pub command: String,
pub args: Vec<String>,
pub mounted: bool,
}
pub const SERVER_KEY: &str = "neosian-memory";
pub const READ_ONLY_TOOLS: [&str; 10] = [
"list_skills",
"load_skill",
"recall_turn",
"search_history",
"docs",
"memory_history",
"search_memory",
"upkeep_review",
"knowledge",
"changes",
];
pub struct Request<'a> {
pub agent: Agent,
pub mode: Mode,
pub model: Option<&'a str>,
pub directory: &'a Path,
pub resume: Option<&'a str>,
pub new_session: &'a str,
pub private: &'a Path,
pub codex_keys: &'a [CodexKey],
pub opencode_config: Option<&'a str>,
pub parent: Option<&'a str>,
pub server: Option<&'a McpServer>,
pub codex_off: &'a [String],
}
#[derive(Debug, PartialEq, Eq)]
pub struct Plan {
pub argv: Vec<String>,
pub env: Vec<(String, String)>,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Unplanned {
OpenCodeConfig,
}
pub const PARENT_ENV: &str = "NEOSIAN_HARNESS_PARENT";
pub const SESSION_ENV: &str = "NEOSIAN_HARNESS_SESSION";
pub fn plan(request: &Request) -> Result<Plan, Unplanned> {
let mut plan = match request.agent {
Agent::ClaudeCode => claude::plan(request),
Agent::Codex => codex::plan(request),
Agent::OpenCode => opencode::plan(request)?,
};
let directory = request.directory.display().to_string();
plan.env
.push((super::CHILD_ENV.to_string(), "1".to_string()));
plan.env.push(("PWD".to_string(), directory));
if let Some(parent) = request.parent {
plan.env.push((PARENT_ENV.to_string(), parent.to_string()));
}
let known = match (request.resume, request.agent) {
(Some(session), _) => Some(session),
(None, Agent::ClaudeCode) => Some(request.new_session),
(None, _) => None,
};
if let Some(session) = known {
plan.env
.push((SESSION_ENV.to_string(), session.to_string()));
}
Ok(plan)
}
pub fn which(program: &str, path: Option<&std::ffi::OsStr>) -> Option<PathBuf> {
let path = path?;
std::env::split_paths(path)
.filter(|entry| entry.is_absolute())
.flat_map(|entry| {
let plain = entry.join(program);
let windows = ["exe", "cmd", "bat"].map(|ext| plain.with_extension(ext));
std::iter::once(plain).chain(windows)
})
.find(|candidate| executable(candidate))
}
fn executable(path: &Path) -> bool {
if !path.is_file() {
return false;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
path.metadata()
.is_ok_and(|m| m.permissions().mode() & 0o111 != 0)
}
#[cfg(not(unix))]
{
true
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum Placed {
Missing,
NotAllowed(PathBuf),
NeedListed,
}
pub fn place(
given: Option<&str>,
server: &Path,
home: Option<&Path>,
listed: &[PathBuf],
) -> Result<PathBuf, Placed> {
let canonical = |path: &Path| path.canonicalize().ok().filter(|path| path.is_dir());
let own = canonical(server);
let home = home
.filter(|home| !home.as_os_str().is_empty())
.and_then(canonical);
let own_ok = own.as_ref().filter(|own| {
home.as_ref()
.is_some_and(|home| own.starts_with(home) && *own != home)
});
let Some(given) = given else {
return own_ok.cloned().ok_or(Placed::NeedListed);
};
let path = canonical(&server.join(given)).ok_or(Placed::Missing)?;
if own_ok == Some(&path) || listed.contains(&path) {
return Ok(path);
}
Err(Placed::NotAllowed(path))
}
pub fn home() -> Option<PathBuf> {
std::env::var_os("HOME")
.filter(|home| !home.is_empty())
.map(PathBuf::from)
}
pub fn bare_key(name: &str) -> bool {
!name.is_empty()
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || "_-".contains(c))
}
pub fn model_ok(model: &str) -> bool {
(1..=128).contains(&model.len())
&& model.starts_with(|c: char| c.is_ascii_alphanumeric())
&& model
.chars()
.all(|c| c.is_ascii_alphanumeric() || "._:/@#+-".contains(c))
}
pub fn session_ok(session: &str) -> bool {
crate::conversation::ids::parse_conversation_id(session).is_ok()
&& session.starts_with(|c: char| c.is_ascii_alphanumeric())
}
pub const PROMPT_BYTES: usize = 256 * 1024;
pub fn prompt_ok(prompt: &str) -> bool {
(1..=PROMPT_BYTES).contains(&prompt.len())
}
#[cfg(test)]
mod inputs;
#[cfg(test)]
mod read_only;
#[cfg(test)]
mod tests;