use serde::Serialize;
use serde_json::{Map, Value};
mod exec;
mod fs;
#[cfg(test)]
mod tests;
pub(crate) const CONTRACT: &str = "client-calls/1";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Code {
InvalidArgument,
NoProject,
Forbidden,
Withheld,
NotFound,
TooLarge,
Internal,
}
impl Code {
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::InvalidArgument => "invalid_argument",
Self::NoProject => "no_project",
Self::Forbidden => "forbidden",
Self::Withheld => "withheld",
Self::NotFound => "not_found",
Self::TooLarge => "too_large",
Self::Internal => "internal",
}
}
pub(crate) fn exit_status(self) -> i32 {
if self == Self::InvalidArgument { 2 } else { 1 }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Failure {
pub code: Code,
pub message: String,
pub audited: bool,
}
impl Failure {
pub(crate) fn new(code: Code, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
audited: false,
}
}
pub(crate) fn recorded(mut self) -> Self {
self.audited = true;
self
}
pub(crate) fn invalid(message: impl Into<String>) -> Self {
Self::new(Code::InvalidArgument, message)
}
}
pub(crate) fn document(kind: &str, body: &impl Serialize) -> String {
let mut out = Map::new();
out.insert("contract".into(), CONTRACT.into());
out.insert("kind".into(), kind.into());
if let Ok(Value::Object(fields)) = serde_json::to_value(body) {
for (key, value) in fields {
out.entry(key).or_insert(value);
}
}
Value::Object(out).to_string()
}
pub(crate) fn error_document(failure: &Failure) -> String {
document(
"error",
&serde_json::json!({
"error": { "code": failure.code.as_str(), "message": failure.message }
}),
)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Caller {
pub session: String,
pub agent: String,
pub project_root: String,
}
const MAX_ATTRIBUTION: usize = 200;
impl Caller {
pub(crate) fn from_args(args: &[String], project_root: &str) -> Result<Self, Failure> {
let one = |name: &str| -> Result<String, Failure> {
let value = super::local_read::flag(args, name)
.map_err(|f| Failure::invalid(f.message))?
.ok_or_else(|| Failure::invalid(format!("{name} is required")))?;
if value.trim().is_empty()
|| value.len() > MAX_ATTRIBUTION
|| value.chars().any(char::is_control)
{
return Err(Failure::invalid(format!(
"{name} must be 1-{MAX_ATTRIBUTION} bytes without control characters"
)));
}
Ok(value.to_owned())
};
Ok(Self {
session: one("--session")?,
agent: one("--agent")?,
project_root: project_root.to_owned(),
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Outcome {
Done,
Cancelled,
Jailed,
Denied,
Failed,
}
pub(crate) fn audit_with(
tool: &str,
caller: &Caller,
target: &str,
outcome: Outcome,
text: Option<String>,
) {
use lean_ctx::core::activity;
use lean_ctx::core::audit_trail::{AuditEntryData, AuditEventType, hash_input, record};
let mut input = Map::new();
input.insert("target".into(), Value::from(target));
let (event_type, label) = match outcome {
Outcome::Done => (AuditEventType::ToolCall, "done"),
Outcome::Cancelled => (AuditEventType::ToolCall, "cancelled"),
Outcome::Failed => (AuditEventType::ToolCall, "failed"),
Outcome::Jailed => (AuditEventType::PathJailViolation, "jailed"),
Outcome::Denied => (AuditEventType::ToolDenied, "denied"),
};
record(AuditEntryData {
agent_id: caller.agent.clone(),
tool: tool.to_owned(),
action: Some(format!("session={} outcome={label}", caller.session)),
input_hash: hash_input(&input),
output_tokens: 0,
role: lean_ctx::core::roles::active_role_name(),
event_type,
});
let kind = match tool {
"client.fs_read" => activity::Kind::FileRead,
"client.fs_write" => activity::Kind::FileWrite,
_ => activity::Kind::Shell,
};
let outcome = match outcome {
Outcome::Done => activity::Outcome::Ok,
Outcome::Cancelled => activity::Outcome::Cancelled,
Outcome::Failed => activity::Outcome::Error,
Outcome::Jailed | Outcome::Denied => activity::Outcome::Denied,
};
let mut draft = activity::Draft::new(
caller.session.as_str(),
caller.agent.as_str(),
caller.project_root.as_str(),
kind,
activity::Source::Acp,
)
.tool(tool)
.target(target)
.outcome(outcome);
if let Some(text) = text {
draft = draft.text(text);
}
activity::record(draft);
}
pub(crate) fn audit_failure(
tool: &str,
caller: &Caller,
target: &str,
failure: Failure,
) -> Failure {
if failure.audited {
return failure;
}
let outcome = match failure.code {
Code::Forbidden | Code::Withheld => Outcome::Denied,
_ => Outcome::Failed,
};
audit_with(
tool,
caller,
target,
outcome,
Some(failure.code.as_str().to_owned()),
);
failure.recorded()
}
pub(crate) fn audit(tool: &str, caller: &Caller, target: &str, outcome: Outcome) {
audit_with(tool, caller, target, outcome, None);
}
pub(crate) fn project_root(args: &[String]) -> Result<String, Failure> {
super::local_read::project_root(args).map_err(|f| Failure::new(Code::NoProject, f.message))
}
pub(crate) fn emit_released<T: Serialize>(
tool: &str,
project_root: &str,
kind: &str,
build: impl FnOnce() -> Result<T, Failure>,
) -> ! {
let mut failed: Option<Code> = None;
let released =
super::common::CliToolRun::new(tool, project_root, None).deliver_json(|| match build() {
Ok(body) => document(kind, &body),
Err(failure) => {
failed = Some(failure.code);
error_document(&failure)
}
});
match released {
Ok(text) => {
super::common::print_released(&text);
std::process::exit(failed.map_or(0, Code::exit_status));
}
Err(reason) => super::common::exit_withheld(&reason),
}
}
pub(crate) fn fail(failure: &Failure) -> ! {
println!("{}", error_document(failure));
std::process::exit(failure.code.exit_status());
}
const USAGE: &str = "Usage: lean-ctx client <fs-read|fs-write|exec> --json --session <id> --agent <id> [--project-root <dir>] …
fs-read --path <abs> [--line N] [--limit N]
fs-write --path <abs> (content on stdin, UTF-8)
exec [--cwd <dir>] [--env K=V]… [--output-byte-limit N] -- <cmd> [args…]
Contract: docs/contracts/client-calls-v1.md (\"client-calls/1\")";
pub(crate) fn cmd_client(args: &[String]) {
let Some((sub, rest)) = args.split_first() else {
eprintln!("{USAGE}");
std::process::exit(2);
};
let sub = sub.as_str();
if matches!(sub, "help" | "--help" | "-h") {
println!("{USAGE}");
return;
}
let flags_end = rest.iter().position(|a| a == "--").unwrap_or(rest.len());
let flag_args = &rest[..flags_end];
if !flag_args.iter().any(|a| a == "--json") {
eprintln!("{USAGE}");
std::process::exit(2);
}
let caller = match project_root(flag_args).and_then(|root| Caller::from_args(flag_args, &root))
{
Ok(caller) => caller,
Err(failure) => fail(&failure),
};
match sub {
"fs-read" => fs::cmd_fs_read(flag_args, &caller),
"fs-write" => fs::cmd_fs_write(flag_args, &caller),
"exec" => {
let command = rest.get(flags_end + 1..).unwrap_or_default();
exec::cmd_exec(flag_args, command, &caller);
}
other => fail(&Failure::invalid(format!(
"unknown client call {other:?} (fs-read, fs-write, exec)"
))),
}
}