use serde::Serialize;
use serde_json::{Map, Value};
pub(crate) mod activity;
pub(crate) mod agents;
pub(crate) mod app_key;
pub(crate) mod billing_part;
pub(crate) mod billing_topup;
pub(crate) mod bus;
pub(crate) mod bus_presence;
pub(crate) mod capabilities;
pub(crate) mod chat_part;
pub(crate) mod chat_sign;
pub(crate) mod cloud_cpao;
pub(crate) mod cloud_exchange;
pub(crate) mod cloud_gateway;
pub(crate) mod cloud_models;
pub(crate) mod cloud_usage;
pub(crate) mod context_part;
pub(crate) mod daemon;
pub(crate) mod decisions_part;
pub(crate) mod docs;
pub(crate) mod engine_files;
pub(crate) mod evidence;
pub(crate) mod kinds;
pub(crate) mod knowledge;
pub(crate) mod knowledge_write;
pub(crate) mod lease_part;
pub(crate) mod leases;
pub(crate) mod link;
pub(crate) mod members_part;
pub(crate) mod pickup_part;
pub(crate) mod plan_part;
pub(crate) mod policies;
pub(crate) mod policy_layers;
pub(crate) mod presence;
pub(crate) mod providers;
pub(crate) mod queens;
pub(crate) mod report_sign;
pub(crate) mod routes;
pub(crate) mod session;
pub(crate) mod session_usage;
pub(crate) mod status;
pub(crate) mod sync;
pub(crate) mod task_receipt;
pub(crate) mod tasks;
pub(crate) mod tasks_part;
pub(crate) mod tasks_sign;
pub(crate) mod team_stop_part;
pub(crate) mod unlink_part;
pub(crate) mod usage;
pub(crate) mod vaults;
#[cfg(test)]
mod tests;
pub(crate) const CONTRACT: &str = "local-read/1";
pub(crate) struct Part {
pub routes: &'static [routes::Route],
pub kinds: &'static [&'static str],
pub commands: &'static [(&'static str, &'static [&'static str])],
pub answer: fn(&str, &[String], Via) -> Answer,
}
pub(crate) const PARTS: &[Part] = &[
Part {
routes: tasks_part::ROUTES,
kinds: tasks_part::KINDS,
commands: tasks_part::COMMANDS,
answer: tasks_part::answer,
},
Part {
routes: pickup_part::ROUTES,
kinds: pickup_part::KINDS,
commands: pickup_part::COMMANDS,
answer: pickup_part::answer,
},
Part {
routes: team_stop_part::ROUTES,
kinds: team_stop_part::KINDS,
commands: team_stop_part::COMMANDS,
answer: team_stop_part::answer,
},
Part {
routes: sync::ROUTES,
kinds: sync::KINDS,
commands: sync::COMMANDS,
answer: sync::answer,
},
Part {
routes: report_sign::ROUTES,
kinds: report_sign::KINDS,
commands: report_sign::COMMANDS,
answer: report_sign::answer,
},
Part {
routes: context_part::ROUTES,
kinds: context_part::KINDS,
commands: context_part::COMMANDS,
answer: context_part::answer,
},
Part {
routes: policy_layers::ROUTES,
kinds: policy_layers::KINDS,
commands: policy_layers::COMMANDS,
answer: policy_layers::answer,
},
Part {
routes: task_receipt::ROUTES,
kinds: task_receipt::KINDS,
commands: task_receipt::COMMANDS,
answer: task_receipt::answer,
},
Part {
routes: session_usage::ROUTES,
kinds: session_usage::KINDS,
commands: session_usage::COMMANDS,
answer: session_usage::answer,
},
Part {
routes: engine_files::ROUTES,
kinds: engine_files::KINDS,
commands: engine_files::COMMANDS,
answer: engine_files::answer,
},
Part {
routes: chat_part::ROUTES,
kinds: chat_part::KINDS,
commands: chat_part::COMMANDS,
answer: chat_part::answer,
},
Part {
routes: lease_part::ROUTES,
kinds: lease_part::KINDS,
commands: lease_part::COMMANDS,
answer: lease_part::answer,
},
Part {
routes: decisions_part::ROUTES,
kinds: decisions_part::KINDS,
commands: decisions_part::COMMANDS,
answer: decisions_part::answer,
},
Part {
routes: members_part::ROUTES,
kinds: members_part::KINDS,
commands: members_part::COMMANDS,
answer: members_part::answer,
},
Part {
routes: billing_part::ROUTES,
kinds: billing_part::KINDS,
commands: billing_part::COMMANDS,
answer: billing_part::answer,
},
Part {
routes: cloud_models::ROUTES,
kinds: cloud_models::KINDS,
commands: cloud_models::COMMANDS,
answer: cloud_models::answer,
},
Part {
routes: billing_topup::ROUTES,
kinds: billing_topup::KINDS,
commands: billing_topup::COMMANDS,
answer: billing_topup::answer,
},
Part {
routes: plan_part::ROUTES,
kinds: plan_part::KINDS,
commands: plan_part::COMMANDS,
answer: plan_part::answer,
},
Part {
routes: unlink_part::ROUTES,
kinds: unlink_part::KINDS,
commands: unlink_part::COMMANDS,
answer: unlink_part::answer,
},
];
pub(crate) fn part_of(kind: &str) -> Option<&'static Part> {
PARTS.iter().find(|p| p.kinds.contains(&kind))
}
pub(crate) fn wants_json(args: &[String]) -> bool {
args.iter().any(|a| a == "--json")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Code {
InvalidArgument,
NoProject,
NotConnected,
NoVault,
NotFound,
Forbidden,
Withheld,
AnchorGone,
Conflict,
Unavailable,
RateLimited,
PlanRequired,
InvalidState,
InvalidField,
SsoRequired,
NotOffered,
EmailUnverified,
PolicyDenied,
Internal,
NoComputer,
BalanceEmpty,
ComputerExists,
ComputerBusy,
ComputerProviderUnavailable,
ComputerNotAvailable,
ConfirmationRequired,
AppOnly,
ChatKeyMissing,
SignatureInvalid,
FrameExpired,
FrameUnknown,
SignatureRequired,
}
impl Code {
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::InvalidArgument => "invalid_argument",
Self::NoProject => "no_project",
Self::NotConnected => "not_connected",
Self::NoVault => "no_vault",
Self::NotFound => "not_found",
Self::Forbidden => "forbidden",
Self::Withheld => "withheld",
Self::AnchorGone => "anchor_gone",
Self::Conflict => "conflict",
Self::Unavailable => "unavailable",
Self::RateLimited => "rate_limited",
Self::PlanRequired => "plan_required",
Self::InvalidState => "invalid_state",
Self::InvalidField => "invalid_field",
Self::SsoRequired => "sso_required",
Self::NotOffered => "not_offered",
Self::EmailUnverified => "email_unverified",
Self::PolicyDenied => "policy_denied",
Self::Internal => "internal",
Self::NoComputer => "no_computer",
Self::BalanceEmpty => "balance_empty",
Self::ComputerExists => "computer_exists",
Self::ComputerBusy => "computer_busy",
Self::ComputerProviderUnavailable => "computer_provider_unavailable",
Self::ComputerNotAvailable => "computer_not_available",
Self::ConfirmationRequired => "confirmation_required",
Self::AppOnly => "app_only",
Self::ChatKeyMissing => "chat_key_missing",
Self::SignatureInvalid => "signature_invalid",
Self::FrameExpired => "frame_expired",
Self::FrameUnknown => "frame_unknown",
Self::SignatureRequired => "signature_required",
}
}
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 details: Option<Value>,
pub reason: Option<&'static str>,
pub detail: Option<Map<String, Value>>,
}
impl Failure {
pub(crate) fn new(code: Code, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
details: None,
reason: None,
detail: None,
}
}
pub(crate) fn with_details(mut self, details: Value) -> Self {
self.details = Some(details);
self
}
pub(crate) fn with_reason(self, reason: &'static str) -> Self {
Self {
reason: Some(reason),
..self
}
}
pub(crate) fn with_detail(mut self, detail: Map<String, Value>) -> Self {
self.detail = (!detail.is_empty()).then_some(detail);
self
}
pub(crate) fn invalid(message: impl Into<String>) -> Self {
Self::new(Code::InvalidArgument, message)
}
}
impl From<lean_ctx_cloud::CloudError> for Failure {
fn from(error: lean_ctx_cloud::CloudError) -> Self {
use lean_ctx_cloud::CloudError as E;
let code = match &error {
E::NotConnected | E::LeaseLapsed | E::Revoked(_) | E::Unauthorized => {
Code::NotConnected
}
E::NotFound => Code::NotFound,
E::Forbidden | E::PlanRequired(_) => Code::Forbidden,
E::RateLimited { .. } => Code::RateLimited,
E::Offline(_) => Code::Unavailable,
E::PolicyDenied(denial) => {
return decisions_part::policy_refusal::denied(
decisions_part::policy_refusal::POLICY_DENIED,
denial.member.as_deref(),
denial.level.as_deref(),
denial.action.as_deref(),
);
}
_ if error.is_transient() => Code::Unavailable,
_ => Code::Internal,
};
Self::new(code, error.to_string())
}
}
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 {
let mut error = Map::new();
error.insert("code".into(), failure.code.as_str().into());
error.insert("message".into(), failure.message.clone().into());
if let Some(reason) = failure.reason {
error.insert("reason".into(), reason.into());
}
for (key, value) in failure.detail.iter().flatten() {
error.entry(key.clone()).or_insert_with(|| value.clone());
}
if let Some(details) = &failure.details {
error.insert("details".into(), details.clone());
}
document("error", &serde_json::json!({ "error": error }))
}
pub(crate) fn fail(failure: &Failure) -> ! {
println!("{}", error_document(failure));
std::process::exit(failure.code.exit_status());
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Via {
Cli,
#[cfg_attr(not(feature = "http-server"), allow(dead_code))]
Socket,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Answer {
pub text: String,
pub failed: Option<Code>,
pub notice: Option<String>,
released: bool,
withheld: bool,
}
impl Answer {
pub(crate) fn failure(failure: &Failure) -> Self {
Self {
text: error_document(failure),
failed: Some(failure.code),
notice: None,
released: false,
withheld: false,
}
}
pub(crate) fn unreceipted() -> Self {
Self {
text: String::new(),
failed: Some(Code::Withheld),
notice: None,
released: true,
withheld: true,
}
}
#[cfg_attr(not(feature = "http-server"), allow(dead_code))]
pub(crate) fn body(&self) -> Option<&str> {
(!self.withheld).then_some(self.text.as_str())
}
}
pub(crate) fn answer<T: Serialize>(
kind: &str,
build: impl FnOnce() -> Result<T, Failure>,
) -> Answer {
match build() {
Ok(body) => Answer {
text: document(kind, &body),
failed: None,
notice: None,
released: false,
withheld: false,
},
Err(failure) => Answer::failure(&failure),
}
}
pub(crate) const MASKED_NOTICE: &str = "[lean-ctx gateway: content redacted]";
const FOLDERLESS_ROOT: &str = std::path::MAIN_SEPARATOR_STR;
fn tool_run<'a>(tool: &'a str, project_root: &'a str, via: Via) -> super::common::CliToolRun<'a> {
let project_root = if project_root.is_empty() {
FOLDERLESS_ROOT
} else {
project_root
};
let run = super::common::CliToolRun::new(tool, project_root, None);
match via {
Via::Cli => run.refuse_with(withheld_document),
Via::Socket => run.to_transport().refuse_with(withheld_document),
}
}
pub(crate) fn released_per_project<R, K>(
tool: &str,
reader_root: &str,
records: super::common::Records,
rows: Vec<R>,
root_of: impl Fn(&R) -> &str,
key_of: impl Fn(&R) -> K,
) -> (Vec<R>, usize)
where
R: Serialize + serde::de::DeserializeOwned,
K: Ord,
{
let total = rows.len();
let mut order: Vec<(String, K)> = Vec::with_capacity(total);
let mut groups: std::collections::BTreeMap<String, Vec<R>> = std::collections::BTreeMap::new();
for row in rows {
let Some(root) = row_release_root(root_of(&row), reader_root) else {
continue;
};
order.push((root.clone(), key_of(&row)));
groups.entry(root).or_default().push(row);
}
let mut released: std::collections::BTreeMap<(String, K), std::collections::VecDeque<R>> =
std::collections::BTreeMap::new();
for (root, group) in groups {
let run = super::common::CliToolRun::new(tool, &root, None).per_record(records);
let (document, _) = run.acquire(|| {
let rows = serde_json::to_value(&group).ok()?;
let document = records.path.iter().rev().fold(rows, |inner, key| {
Value::Object(Map::from_iter([((*key).to_owned(), inner)]))
});
run.released_preview(serde_json::to_string(&document).ok()?)
.ok()
});
let rows = document
.and_then(|document| serde_json::from_str::<Value>(&document).ok())
.and_then(|mut document| {
let mut at = &mut document;
for key in records.path {
at = at.get_mut(*key)?;
}
serde_json::from_value::<Vec<R>>(at.take()).ok()
})
.unwrap_or_default();
for row in rows {
released
.entry((root.clone(), key_of(&row)))
.or_default()
.push_back(row);
}
}
let kept: Vec<R> = order
.into_iter()
.filter_map(|place| {
released
.get_mut(&place)
.and_then(std::collections::VecDeque::pop_front)
})
.collect();
let withheld = total.saturating_sub(kept.len());
(kept, withheld)
}
pub(crate) fn row_release_root(row_root: &str, reader_root: &str) -> Option<String> {
if row_root.is_empty() {
Some(reader_root.to_owned())
} else if std::path::Path::new(row_root).is_dir() {
Some(row_root.to_owned())
} else {
None
}
}
fn withheld_document(reason: &str) -> String {
error_document(&Failure::new(Code::Withheld, reason))
}
pub(crate) fn answer_released<T: Serialize>(
tool: &str,
project_root: &str,
kind: &str,
via: Via,
build: impl FnOnce() -> Result<T, Failure>,
) -> Answer {
answer_released_run(&tool_run(tool, project_root, via), kind, via, build)
}
pub(crate) fn answer_released_records<T: Serialize>(
tool: &str,
project_root: &str,
kind: &str,
via: Via,
records: super::common::Records,
build: impl FnOnce() -> Result<T, Failure>,
) -> Answer {
let run = tool_run(tool, project_root, via).per_record(records);
answer_released_run(&run, kind, via, build)
}
fn answer_released_run<T: Serialize>(
run: &super::common::CliToolRun<'_>,
kind: &str,
via: Via,
build: impl FnOnce() -> Result<T, Failure>,
) -> Answer {
let mut failed: Option<Code> = None;
let mut built: Option<String> = None;
let released = run.deliver_json(|| {
let text = match build() {
Ok(body) => document(kind, &body),
Err(failure) => {
failed = Some(failure.code);
error_document(&failure)
}
};
built = Some(text.clone());
text
});
released_answer(released, built.as_deref(), failed, via)
}
fn released_answer(
released: Result<String, String>,
built: Option<&str>,
failed: Option<Code>,
via: Via,
) -> Answer {
match released {
Ok(text) => Answer {
notice: (built != Some(text.as_str())).then(|| MASKED_NOTICE.to_owned()),
text,
failed,
released: true,
withheld: false,
},
Err(reason) => {
let unreceipted =
reason == lean_ctx::core::context_admission::receipt_store::not_persisted_notice();
if unreceipted {
return match via {
Via::Cli => Answer {
text: reason,
..Answer::unreceipted()
},
Via::Socket => Answer::unreceipted(),
};
}
Answer {
text: withheld_document(&reason),
failed: Some(Code::Withheld),
notice: None,
released: true,
withheld: false,
}
}
}
}
pub(crate) fn answer_released_write<T: Serialize>(
tool: &str,
project_root: &str,
kind: &str,
via: Via,
preview: &Value,
write: impl FnOnce() -> Result<T, Failure>,
) -> Answer {
let run = tool_run(tool, project_root, via);
let mut failed: Option<Code> = None;
let mut built: Option<String> = None;
let released = run.deliver_json(|| {
let outcome = match run.would_release(document(kind, preview)) {
Err(reason) => Err(Failure::new(Code::Withheld, reason)),
Ok(()) => write(),
};
let text = match outcome {
Ok(body) => document(kind, &body),
Err(failure) => {
failed = Some(failure.code);
error_document(&failure)
}
};
built = Some(text.clone());
text
});
released_answer(released, built.as_deref(), failed, via)
}
pub(crate) fn release_text_write(
tool: &str,
project_root: &str,
kind: &str,
preview: &Value,
) -> Result<(), Failure> {
let run = tool_run(tool, project_root, Via::Cli);
let (released, _capture) = run.acquire(|| run.would_release(document(kind, preview)));
released.map_err(|reason| {
Failure::new(
Code::Withheld,
format!("withheld by the release check, nothing was written: {reason}"),
)
})
}
pub(crate) fn request_preview(args: &[String], names: &[&str]) -> Value {
let mut out = Map::new();
for name in names {
let values = flags(args, name).unwrap_or_default();
let key = name.trim_start_matches('-').replace('-', "_");
match values.as_slice() {
[] => {}
[one] => {
out.insert(key, Value::String((*one).to_owned()));
}
many => {
out.insert(
key,
Value::Array(
many.iter()
.map(|v| Value::String((*v).to_owned()))
.collect(),
),
);
}
}
}
Value::Object(out)
}
pub(crate) fn print(answer: &Answer) {
if answer.withheld {
super::common::exit_withheld(&answer.text);
}
if answer.released && answer.failed == Some(Code::Withheld) {
super::common::exit_refused(&answer.text);
}
if answer.released {
super::common::print_released(&answer.text);
} else {
println!("{}", answer.text);
}
if let Some(code) = answer.failed {
std::process::exit(code.exit_status());
}
}
pub(crate) fn emit<T: Serialize>(kind: &str, build: impl FnOnce() -> Result<T, Failure>) {
print(&answer(kind, build));
}
pub(crate) fn emit_released<T: Serialize>(
tool: &str,
project_root: &str,
kind: &str,
build: impl FnOnce() -> Result<T, Failure>,
) {
print(&answer_released(tool, project_root, kind, Via::Cli, build));
}
pub(crate) fn flag<'a>(args: &'a [String], name: &str) -> Result<Option<&'a str>, Failure> {
let attached = args
.iter()
.find_map(|a| a.strip_prefix(name).and_then(|rest| rest.strip_prefix('=')));
if let Some(value) = attached {
return if value.is_empty() {
Err(Failure::invalid(format!("{name} needs a value")))
} else {
Ok(Some(value))
};
}
match args.iter().position(|a| a == name) {
None => Ok(None),
Some(i) => args
.get(i + 1)
.filter(|v| !v.starts_with("--"))
.map(|v| Some(v.as_str()))
.ok_or_else(|| Failure::invalid(format!("{name} needs a value"))),
}
}
pub(crate) fn flags<'a>(args: &'a [String], name: &str) -> Result<Vec<&'a str>, Failure> {
let mut out = Vec::new();
for (i, arg) in args.iter().enumerate() {
if arg != name {
continue;
}
match args.get(i + 1).filter(|v| !v.starts_with("--")) {
Some(value) => out.push(value.as_str()),
None => return Err(Failure::invalid(format!("{name} needs a value"))),
}
}
Ok(out)
}
const VALUE_FLAGS: &[&str] = &[
"--depth",
"--direction",
"--findings",
"--by",
"--title",
"--goal",
"--acceptance",
"--reason",
"--confirm",
"--note",
"--summary",
"--evidence",
"--verdict",
"--tokens",
"--project-root",
"--path",
"--root",
"--state",
"--role",
"--category",
"--query",
"--limit",
"--since",
"--to",
"--thread",
"--message",
"--contract",
"--minutes",
"--session",
"--project",
"--kind",
"--from",
"--as",
"--priority",
"--labels",
"--session-id",
"--name",
"--expires-in-hours",
"--agent",
"--resource-kind",
"--resource",
"--lease",
"--days",
"--id",
"--key",
"--value",
"--confidence",
"--relation",
"--output",
"--request-id",
"--vault",
"--level",
"--expected-revision",
"--op",
"--rule",
];
pub(crate) fn positionals(args: &[String]) -> Vec<&str> {
split_positionals(args).0
}
pub(crate) fn split_positionals(args: &[String]) -> (Vec<&str>, Vec<&str>) {
let (mut positional, mut flags) = (Vec::new(), Vec::new());
let mut value = false;
for arg in args {
if value {
value = false;
flags.push(arg.as_str());
} else if arg.starts_with("--") {
value = !arg.contains('=') && VALUE_FLAGS.contains(&arg.as_str());
flags.push(arg.as_str());
} else {
positional.push(arg.as_str());
}
}
(positional, flags)
}
pub(crate) fn limit(args: &[String], default: usize, max: usize) -> Result<usize, Failure> {
match flag(args, "--limit")? {
None => Ok(default),
Some(raw) => raw
.parse::<usize>()
.ok()
.filter(|n| (1..=max).contains(n))
.ok_or_else(|| Failure::invalid(format!("--limit is 1-{max}"))),
}
}
pub(crate) fn named_roots(args: &[String]) -> Result<Vec<(&'static str, String)>, Failure> {
let mut out = Vec::new();
for (i, arg) in args.iter().enumerate() {
let (name, value) = if let Some(v) = arg.strip_prefix("--root=") {
("--root", Some(v))
} else if let Some(v) = arg.strip_prefix("--project-root=") {
("--project-root", Some(v))
} else if arg == "--root" || arg == "--project-root" {
(
if arg == "--root" {
"--root"
} else {
"--project-root"
},
args.get(i + 1)
.map(String::as_str)
.filter(|v| !v.starts_with("--")),
)
} else {
continue;
};
let value = value
.map(str::trim)
.filter(|v| !v.is_empty())
.ok_or_else(|| Failure::invalid(format!("{name} needs a value")))?;
let root = super::common::detect_project_root(&[format!("--project-root={value}")]);
out.push((name, root));
}
Ok(out)
}
pub(crate) fn named_root(args: &[String]) -> Result<Option<String>, Failure> {
let mut named: Option<String> = None;
for (_, root) in named_roots(args)? {
match &named {
Some(first) if *first != root => {
return Err(Failure::invalid(format!(
"--root and --project-root name different folders ({first}, {root}); name one"
)));
}
_ => named = Some(root),
}
}
Ok(named)
}
pub(crate) fn project_root(args: &[String]) -> Result<String, Failure> {
let root = match named_root(args)? {
Some(root) => root,
None => super::common::detect_project_root(args),
};
if lean_ctx::core::pathutil::is_broad_or_unsafe_root(std::path::Path::new(&root)) {
return Err(Failure::new(
Code::NoProject,
format!("{root} is not a project"),
));
}
Ok(root)
}
pub(crate) use super::knowledge_shared::rfc3339;