use std::io::{BufRead as _, Write as _};
use std::path::Path;
use lean_ctx_time::UtcDateTime;
use serde_json::{Value, json};
use super::cloud_cmd::{flag_value, plan_name};
use lean_ctx_cloud::CloudConfigExt as _;
use lean_ctx_cloud::auth::{
EnrollmentToken, Session, SetupAnnouncement, announce_setup, enroll_with_token,
finish_device_flow, start_device_flow_for,
};
use lean_ctx_cloud::connect::{self as steps, ProjectStep};
use lean_ctx_cloud::consent::ConsentError;
use lean_ctx_cloud::mapping::MapError;
use lean_ctx_cloud::state::InstanceRecord;
use lean_ctx_cloud::status::report;
use lean_ctx_cloud::transport::CloudClient;
use lean_ctx_cloud::vault::VaultMap;
use lean_ctx_cloud::{CloudConfig, CloudError, CloudStore};
use lean_ctx_protocol::cloud::enroll::{DeviceCodeV1, MAX_INSTANCE_LABEL_CHARS, TrialPlan};
use lean_ctx_protocol::cloud::lease::CloudLeaseV1;
fn default_label() -> String {
let host = gethostname::gethostname()
.to_string_lossy()
.trim()
.to_string();
let host: String = host
.chars()
.filter(|c| !c.is_control())
.take(MAX_INSTANCE_LABEL_CHARS)
.collect();
if host.trim().is_empty() {
"lean-ctx".into()
} else {
host
}
}
fn name_the_root(
error: CloudError,
trust: &lean_ctx_cloud::root_cert::ConnectTrust,
origin: &str,
) -> CloudError {
use lean_ctx_cloud::lease::ROOT_MISMATCH;
let CloudError::Protocol(message) = error else {
return error;
};
let Some(rest) = message.strip_prefix(ROOT_MISMATCH) else {
return CloudError::Protocol(message);
};
let which = if trust.unvouched {
format!(
"the development root key from `[cloud] root_key` in your lean-ctx config. For {origin}, remove `root_key` from `[cloud]` so lean-ctx uses the production root it carries, or set it to the root key of that LeanCTX Cloud server"
)
} else if trust.certificate.is_some() {
format!(
"the root the certificate of {origin} names. Ask the operator of that LeanCTX Cloud server to renew its root certificate"
)
} else {
format!(
"the production root key built into lean-ctx {}. Update lean-ctx; for a self-hosted LeanCTX Cloud server, set `[cloud] root_key` to its root key",
env!("CARGO_PKG_VERSION")
)
};
CloudError::Protocol(format!(
"{origin} answered with a key set not signed by {which}{rest}"
))
}
pub(super) const ENROLLMENT_TOKEN_ENV: &str = "LEAN_CTX_CLOUD_ENROLLMENT_TOKEN";
const ENROLLMENT_TOKEN_STDIN: &str = "--enrollment-token-stdin";
const ENROLLMENT_TOKEN_MAX_LINE: u64 = 1024;
fn enrollment_token(
args: &[String],
stdin: &mut dyn std::io::BufRead,
env: Option<std::ffi::OsString>,
) -> Result<Option<EnrollmentToken>, CloudError> {
if args
.iter()
.any(|a| a == "--enrollment-token" || a.starts_with("--enrollment-token="))
{
return Err(CloudError::Config(format!(
"an enrollment token is never passed on the command line, where other users can read it: pipe it to `{ENROLLMENT_TOKEN_STDIN}` or set {ENROLLMENT_TOKEN_ENV}"
)));
}
if args.iter().any(|a| a == ENROLLMENT_TOKEN_STDIN) {
let mut line = zeroize::Zeroizing::new(String::new());
std::io::Read::take(stdin, ENROLLMENT_TOKEN_MAX_LINE)
.read_line(&mut line)
.map_err(|e| {
CloudError::Local(format!(
"read the enrollment token from stdin: {}",
e.kind()
))
})?;
if line.trim().is_empty() {
return Err(CloudError::Config(format!(
"{ENROLLMENT_TOKEN_STDIN}: stdin held no enrollment token"
)));
}
return EnrollmentToken::parse(&line).map(Some);
}
let Some(raw) = env.filter(|v| !v.is_empty()) else {
return Ok(None);
};
let raw = zeroize::Zeroizing::new(raw.into_string().map_err(|_| {
CloudError::Config(format!(
"{ENROLLMENT_TOKEN_ENV}: the enrollment token is malformed (not UTF-8)"
))
})?);
EnrollmentToken::parse(&raw).map(Some)
}
fn trial_choice(args: &[String]) -> Result<Option<TrialPlan>, CloudError> {
let plan = flag_value(args, "--plan")?;
match (args.iter().any(|a| a == "--trial"), plan) {
(false, None) => Ok(None),
(false, Some(_)) => Err(CloudError::Config(
"--plan is only valid with --trial".into(),
)),
(true, None) => Ok(Some(TrialPlan::Personal)),
(true, Some(plan)) => TrialPlan::parse(plan).map(Some).ok_or_else(|| {
let shown: String = plan.chars().filter(|c| !c.is_control()).take(32).collect();
CloudError::Config(format!("--plan {shown}: choose personal or team"))
}),
}
}
fn trial_aware(error: CloudError, trial: Option<TrialPlan>) -> CloudError {
if trial.is_some() {
error.for_trial()
} else {
error
}
}
fn code_event(code: &DeviceCodeV1) -> Value {
json!({
"event": "code",
"verification_uri": code.verification_uri,
"verification_uri_complete": code.verification_uri_complete,
"user_code": code.user_code,
"expires_in": code.expires_in,
})
}
fn connected_event(lease: &CloudLeaseV1) -> Value {
json!({
"event": "connected",
"plan": lease.plan,
"trial_ends_at": lean_ctx_cloud::status::trial_ends_at(lease),
})
}
fn error_event(error: &CloudError) -> Value {
json!({
"event": "error",
"code": error.event_code(),
"message": error.to_string(),
})
}
fn emit(event: &Value) {
let mut out = std::io::stdout().lock();
let _ = writeln!(out, "{event}");
let _ = out.flush();
}
fn take_enrollment_token(args: &[String]) -> Result<Option<EnrollmentToken>, CloudError> {
let env = std::env::var_os(ENROLLMENT_TOKEN_ENV);
let had_env = env.is_some();
let token = enrollment_token(args, &mut std::io::stdin().lock(), env);
if had_env {
unsafe { std::env::remove_var(ENROLLMENT_TOKEN_ENV) };
}
token
}
fn origin_for(config: &CloudConfig, args: &[String]) -> Result<String, CloudError> {
match flag_value(args, "--url")? {
Some(url) => lean_ctx_cloud::config::normalize_origin(url),
None => config.origin(),
}
}
pub(super) fn run(config: &CloudConfig, args: &[String]) -> Result<(), CloudError> {
if args.iter().any(|a| a == "--json") {
if let Err(error) = run_json(config, args) {
emit(&error_event(&error));
std::process::exit(1);
}
return Ok(());
}
let token = take_enrollment_token(args)?;
let trial = trial_choice(args)?;
let store = CloudStore::open()?;
let origin = origin_for(config, args)?;
if let Some(existing) = store.instance()? {
let current = report(&store, config, UtcDateTime::now());
if current.connected() {
println!(
"Already connected to {} as {} ({}). Run `lean-ctx cloud disconnect` first to switch.",
existing.url, existing.label, existing.org_name
);
let session = lean_ctx_cloud::root_cert::trust_root(&store, config, &existing.url)
.and_then(|root| Session::load(store, root));
return match session {
Ok(session) => {
let outcome = after_login(config, &session, &existing, args)?;
print_done(&existing, &outcome);
Ok(())
}
Err(error) => {
tracing::info!("cloud connect: {error}");
Ok(())
}
};
}
}
let chosen: Option<String> = flag_value(args, "--label")?
.map(|label| label.chars().take(MAX_INSTANCE_LABEL_CHARS).collect());
let label = chosen.clone().unwrap_or_else(default_label);
let client = CloudClient::new(&origin)?;
println!("LeanCTX Cloud — connect this machine");
let trust = lean_ctx_cloud::root_cert::for_connect(&client, config, &origin)
.map_err(|error| unreachable(error, &origin))?;
if trust.unvouched {
println!(
"(Development LeanCTX Cloud server: its root key comes from `[cloud] root_key` in your config.)"
);
}
let root = trust.root;
let here = project_here();
let (early, named, announced, enrolled) = if let Some(token) = &token {
println!("\nStep 1 of 3 · Enroll this machine with your team's enrollment token");
print!(" Enrolling…");
let _ = std::io::stdout().flush();
let enrolled = enroll_with_token(&store, &client, token, &label, &root)
.map_err(|error| unreachable(error, &origin));
(None, None, false, enrolled)
} else {
let code = start_device_flow_for(&client, chosen.as_deref(), trial)
.map_err(|error| unreachable(error, &origin))?;
let early = here
.as_ref()
.filter(|_| code.offers_device_setup())
.and_then(|_| share_before_approval(config, args));
let mut announce_config = config.clone();
if early == Some(false) {
steps::without_sharing(&mut announce_config);
}
let named = here.as_deref().filter(|_| early == Some(true));
let announced =
announce_setup(&client, &code, &setup_announcement(&announce_config, named));
println!("\nStep 1 of 3 · Approve this machine in your browser");
if args.iter().any(|a| a == "--no-browser")
|| std::env::var_os("LEAN_CTX_NO_BROWSER").is_some()
{
println!(
" Open this link on any device: {}",
code.verification_uri_complete
);
} else {
let _ = open_browser(&code.verification_uri_complete);
println!(" We opened: {}", code.verification_uri_complete);
}
println!(
" Check the code {} in the browser: it must be the same (valid {} minutes).",
code.user_code,
code.expires_in.div_ceil(60).max(1)
);
if let Some(plan) = trial {
println!(
" There you sign in and start your {} trial for this machine.",
trial_plan_name(plan)
);
} else if announced {
println!(
" There you sign in, choose the workspace and confirm what this machine shares."
);
} else {
println!(" There you sign in and choose the workspace for this machine.");
}
print!(" Waiting for you to approve…");
let _ = std::io::stdout().flush();
let enrolled =
finish_device_flow(&store, &client, &code, &label, &root, &std::thread::sleep)
.map_err(|error| trial_aware(error, trial));
(early, named, announced, enrolled)
};
let (instance, sharing) = enrolled
.map_err(|error| name_the_root(error, &trust, &origin))
.map_err(|error| {
println!();
if matches!(&error, CloudError::QuotaExceeded(q) if q.cooling_slot()) {
println!("Instances: {origin} (Settings › Connected instances)");
}
lean_ctx_cloud::throttle::note(
&store,
lean_ctx_cloud::throttle::Scope::Connect,
error,
UtcDateTime::now(),
)
})?;
println!(
"{}",
if token.is_some() {
" enrolled."
} else {
" approved."
}
);
if let Some(certificate) = &trust.certificate {
lean_ctx_cloud::root_cert::store_certificate(&store, certificate)?;
}
lean_ctx_cloud::revoked::clear(&store)?;
lean_ctx_cloud::throttle::clear_connect(&store);
let session = Session::load(store, root)?;
session.client()?;
println!(
"\nStep 2 of 3 · Connected {} to {} ({} plan).",
instance.label,
instance.workspace_label(),
plan_name(&session.lease.lease.plan)
);
if let Some(trial) = lean_ctx_cloud::status::trial_line(&session.lease.lease) {
println!(" {trial}.");
}
if let Some(line) = lean_ctx::daemon_autostart::supervision_line(
lean_ctx::daemon_autostart::ensure_supervised(true),
) {
println!("{line}");
}
announce_and_pull(&session);
let sharing = sharing.filter(|_| project_here().is_some() && named.is_some());
let answer = match sharing {
Some(Some(share)) => Some((share, Some(steps::SOURCE_BROWSER))),
_ => early.map(|share| (share, None)),
};
let mut device = false;
if let Some((share, source)) = answer {
if !share {
lean_ctx::core::config::Config::update_global(|c| steps::without_sharing(&mut c.cloud))
.map_err(|e| CloudError::Local(format!("record the answer: {e}")))?;
}
steps::record_from(
&session.store,
&instance.org_id,
share,
UtcDateTime::now(),
source,
)?;
device = share && source.is_some();
}
let config = if answer.is_some_and(|(share, _)| !share) {
let mut off = config.clone();
steps::without_sharing(&mut off);
off
} else {
config.clone()
};
let outcome = after_login_with(&config, &session, &instance, args, device, announced)?;
if announced {
report_setup(&session, &outcome);
}
print_done(&instance, &outcome);
engine_metrics_notice(&config, &session, &instance);
if session
.lease
.lease
.grants(lean_ctx_protocol::cloud::lease::CloudRight::Runtime)
&& !config.runtime_consent
{
if lean_ctx::core::host_env::stdin_is_terminal()
&& super::prompt::confirm(RUNTIME_QUESTION, false)
{
return install_runtime(true);
}
println!(
" Optional: `lean-ctx cloud runtime install` adds the LeanCTX Intelligence runtime your plan includes; it enforces {}'s policies on this machine.",
instance.org_name
);
}
Ok(())
}
fn announce_and_pull(session: &Session) {
if let Err(error) = lean_ctx_cloud::workers::register::announce_instance(session) {
tracing::info!("cloud instance card: {error}");
}
if lean_ctx_cloud::bus::relay_v2::speaks_v2(&session.store)
&& session
.lease
.lease
.grants(lean_ctx_protocol::cloud::lease::CloudRight::PolicyPull)
&& let Err(error) = lean_ctx_cloud::policy::pull(session)
{
tracing::info!("cloud policy at connect: {error}");
}
}
fn trial_plan_name(plan: TrialPlan) -> &'static str {
match plan {
TrialPlan::Personal => "Personal",
TrialPlan::Team => "Team",
}
}
fn run_json(config: &CloudConfig, args: &[String]) -> Result<(), CloudError> {
let token = take_enrollment_token(args)?;
let trial = trial_choice(args)?;
let store = CloudStore::open()?;
let origin = origin_for(config, args)?;
if store.instance()?.is_some() {
let current = report(&store, config, UtcDateTime::now());
if let (true, Some(lease)) = (current.connected(), ¤t.lease) {
emit(&connected_event(lease));
return Ok(());
}
}
let chosen: Option<String> = flag_value(args, "--label")?
.map(|label| label.chars().take(MAX_INSTANCE_LABEL_CHARS).collect());
let label = chosen.clone().unwrap_or_else(default_label);
let client = CloudClient::new(&origin)?;
let trust = lean_ctx_cloud::root_cert::for_connect(&client, config, &origin)?;
let root = trust.root;
let enrolled = if let Some(token) = &token {
enroll_with_token(&store, &client, token, &label, &root)
} else {
let code = start_device_flow_for(&client, chosen.as_deref(), trial)?;
emit(&code_event(&code));
if !args.iter().any(|a| a == "--no-browser") {
let _ = open_browser(&code.verification_uri_complete);
}
finish_device_flow(&store, &client, &code, &label, &root, &std::thread::sleep)
.map_err(|error| trial_aware(error, trial))
};
enrolled
.map_err(|error| name_the_root(error, &trust, &origin))
.map_err(|error| {
lean_ctx_cloud::throttle::note(
&store,
lean_ctx_cloud::throttle::Scope::Connect,
error,
UtcDateTime::now(),
)
})?;
if let Some(certificate) = &trust.certificate {
lean_ctx_cloud::root_cert::store_certificate(&store, certificate)?;
}
lean_ctx_cloud::revoked::clear(&store)?;
lean_ctx_cloud::throttle::clear_connect(&store);
let session = Session::load(store, root)?;
session.client()?;
let _ = lean_ctx::daemon_autostart::ensure_supervised(true);
announce_and_pull(&session);
emit(&connected_event(&session.lease.lease));
Ok(())
}
fn unreachable(error: CloudError, origin: &str) -> CloudError {
match error {
CloudError::Offline(_) => CloudError::Refused(format!(
"can't reach LeanCTX Cloud at {origin}. Check your connection and try again; LeanCTX keeps working locally meanwhile."
)),
other => other,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Outcome {
NoProject,
Shared { ns: String, name: String },
KeptLocal(String),
Waiting,
Retry(String),
}
fn engine_metrics_notice(config: &CloudConfig, session: &Session, instance: &InstanceRecord) {
use lean_ctx_cloud::metrics_v2::{self, gate, upload};
if !upload::released(&instance.url) || !config.metrics_upload {
return;
}
let workspace = instance.workspace_label();
let web_url = instance
.web_url
.clone()
.unwrap_or_else(|| instance.url.clone());
let lease = &session.lease.lease;
let sharing = gate::decide(&session.store, config, instance, lease, UtcDateTime::now());
let needs =
gate::needs_confirmation(lease.plan) && !sharing.is_on() && upload::released(&instance.url);
println!(
"\n{}",
metrics_v2::disclosure(&workspace, &web_url, &sharing, needs)
);
let terminal = lean_ctx::core::host_env::stdin_is_terminal()
&& std::io::IsTerminal::is_terminal(&std::io::stdout());
if needs
&& terminal
&& super::prompt::confirm("Share instance metrics with this workspace?", false)
{
match upload::confirm(session) {
Ok(_) => println!("Instance metrics confirmed for {workspace}."),
Err(error) => eprintln!("cloud: instance metrics not confirmed: {error}"),
}
}
}
fn after_login(
config: &CloudConfig,
session: &Session,
instance: &InstanceRecord,
args: &[String],
) -> Result<Outcome, CloudError> {
after_login_with(config, session, instance, args, false, false)
}
fn project_here() -> Option<String> {
let cwd = std::env::current_dir().ok()?;
let root = lean_ctx::core::protocol::detect_project_root_or_cwd(&cwd.to_string_lossy());
lean_ctx_cloud::vault::project_identity(Path::new(&root))?;
Some(root)
}
fn setup_announcement(config: &CloudConfig, root: Option<&str>) -> SetupAnnouncement {
let project = root.map(|root| {
let root = Path::new(root);
let name: String = project_name(root)
.chars()
.filter(|c| !c.is_control())
.take(64)
.collect();
let remote = lean_ctx_cloud::identity_v2::origin_remote(root)
.filter(|r| (1..=500).contains(&r.chars().count()));
(name, remote)
});
SetupAnnouncement {
project: project.filter(|(name, _)| !name.trim().is_empty()),
shares: steps::share_codes(config),
}
}
fn report_setup(session: &Session, outcome: &Outcome) {
use lean_ctx_protocol::cloud::enroll::{DEVICE_SETUP_RESULT_SCHEMA, DeviceSetupResultV1};
let (state, vault) = match outcome {
Outcome::Shared { ns, name } => ("shared", Some(format!("{ns}/{name}"))),
Outcome::NoProject => ("no_project", None),
Outcome::KeptLocal(_) => ("kept_local", None),
Outcome::Waiting | Outcome::Retry(_) => ("failed", None),
};
let body = DeviceSetupResultV1 {
schema: DEVICE_SETUP_RESULT_SCHEMA.into(),
state: state.into(),
vault,
};
let sent = serde_json::to_value(&body)
.map_err(|e| CloudError::Local(e.to_string()))
.and_then(|body| session.with_client(|client| client.post("/device/setup/result", &body)));
if let Err(error) = sent {
tracing::info!("cloud device setup result: {error}");
}
}
fn after_login_with(
config: &CloudConfig,
session: &Session,
instance: &InstanceRecord,
args: &[String],
device: bool,
announced: bool,
) -> Result<Outcome, CloudError> {
if project_here().is_none() {
return Ok(Outcome::NoProject);
}
let Some(shared) = confirm_sharing(config, &session.store, instance, args, announced)? else {
return Ok(Outcome::Waiting);
};
if !shared {
return Ok(Outcome::KeptLocal(format!(
"nothing from this machine is shared with {}",
instance.org_name
)));
}
let cwd = std::env::current_dir().map_err(|e| CloudError::Local(e.to_string()))?;
let root = lean_ctx::core::protocol::detect_project_root_or_cwd(&cwd.to_string_lossy());
let config = lean_ctx::core::config::Config::load().cloud.clone();
Ok(map_project(&config, session, Path::new(&root), device))
}
fn project_name(root: &Path) -> String {
root.file_name().map_or_else(
|| root.display().to_string(),
|n| n.to_string_lossy().into_owned(),
)
}
fn print_done(instance: &InstanceRecord, outcome: &Outcome) {
let web = instance
.web_url
.clone()
.unwrap_or_else(|| instance.url.clone());
let web = web.trim_end_matches('/');
let cwd = std::env::current_dir().unwrap_or_default();
let root = lean_ctx::core::protocol::detect_project_root_or_cwd(&cwd.to_string_lossy());
let project = project_name(Path::new(&root));
let org = &instance.org_name;
println!();
match outcome {
Outcome::Shared { ns, name } => {
println!(
"Done. Your agents now share what they learn about {project} with your team in {org}."
);
println!(" Open: {web}/o/{ns}/v/{name}/");
println!(" Next: Keep working as usual; LeanCTX syncs in the background.");
println!(" Another project? Run `lean-ctx cloud connect` there.");
}
Outcome::NoProject => {
println!(
"Done. This machine is connected to {org}. This folder is not a project LeanCTX can share (it has no git remote)."
);
println!(" Open: {web}/app/");
println!(" Next: Run `lean-ctx cloud connect` inside a project to share it.");
}
Outcome::KeptLocal(why) => {
println!("Done. {project} stays on this machine: {why}.");
println!(" Your agents still use {org}'s knowledge and policies.");
println!(" Open: {web}/app/");
println!(
" Changed your mind? Run `lean-ctx cloud connect` here again in your own terminal: it asks again."
);
}
Outcome::Waiting => {
println!(
"Almost done. {project} stays on this machine until you confirm it yourself: run `lean-ctx cloud connect` here, in your own terminal (agents cannot confirm it)."
);
println!(" Open: {web}/app/");
}
Outcome::Retry(why) => {
println!(
"Connected, but {project} is not set up yet: {why}. LeanCTX tries again in the background; nothing leaves this machine before that."
);
println!(" Open: {web}/app/");
}
}
}
fn decided_line(decided: &steps::SharingDecision, org: &str) -> String {
match (decided.source.as_deref(), decided.shared) {
(Some(steps::SOURCE_BROWSER), true) => {
format!("answered in the browser: shared with {org}.")
}
(Some(steps::SOURCE_BROWSER), false) => {
"answered in the browser: not shared. Nothing from this machine is shared.".into()
}
(_, true) => format!("Sharing with {org} is on: you confirmed it."),
(_, false) => format!("Sharing with {org} is off: you said no."),
}
}
fn asks_again(decided: &steps::SharingDecision, terminal: bool) -> bool {
!decided.shared && terminal
}
fn yes_answers_sharing(args: &[String], announced: bool) -> bool {
!announced && super::prompt::wants_yes(args)
}
fn share_before_approval(config: &CloudConfig, args: &[String]) -> Option<bool> {
let assume_yes = super::prompt::wants_yes(args);
if !assume_yes && !lean_ctx::core::host_env::stdin_is_terminal() {
return None;
}
println!("\nBefore you approve · Share this project");
println!(" With the workspace you choose, this machine would share:");
for item in steps::shared_items(config) {
println!(" - {item}");
}
Some(super::prompt::confirm(
"Share this project? A yes sends its folder name and git remote to LeanCTX Cloud now, so the approval page can show it",
assume_yes,
))
}
fn confirm_sharing(
config: &CloudConfig,
store: &CloudStore,
instance: &InstanceRecord,
args: &[String],
announced: bool,
) -> Result<Option<bool>, CloudError> {
println!("\nStep 3 of 3 · Share this project");
if let Some(decided) = steps::decision(store, &instance.org_id) {
println!(" {}", decided_line(&decided, &instance.org_name));
let terminal = lean_ctx::core::host_env::stdin_is_terminal();
if !asks_again(&decided, terminal) {
return Ok(Some(decided.shared));
}
if !super::prompt::confirm("Share it with the workspace now?", false) {
return Ok(Some(false));
}
lean_ctx::core::config::Config::update_global(|c| steps::with_sharing(&mut c.cloud))
.map_err(|e| CloudError::Local(format!("record the answer: {e}")))?;
steps::record(store, &instance.org_id, true, UtcDateTime::now())?;
return Ok(Some(true));
}
let items = steps::shared_items(config);
if items.is_empty() {
println!(
" This machine shares nothing with {}: every upload is switched off in your `[cloud]` settings.",
instance.org_name
);
return Ok(Some(false));
}
let assume_yes = yes_answers_sharing(args, announced);
if announced && super::prompt::wants_yes(args) {
println!(
" --yes does not answer this: LeanCTX Cloud asks about sharing on the approval page."
);
}
if !assume_yes && !lean_ctx::core::host_env::stdin_is_terminal() {
println!(
" Nobody could answer here (no terminal), so sharing with {} follows your `[cloud]` settings until you do.",
instance.org_name
);
return Ok(None);
}
println!(
" Your agents share what they learn with your team in {}. From this machine that is:",
instance.org_name
);
for item in &items {
println!(" - {item}");
}
println!(
" Either way your agents get the workspace's knowledge and policies, and local tools never depend on LeanCTX Cloud."
);
let shared = super::prompt::confirm("Share this with the workspace?", assume_yes);
if !shared {
lean_ctx::core::config::Config::update_global(|c| steps::without_sharing(&mut c.cloud))
.map_err(|e| CloudError::Local(format!("record the answer: {e}")))?;
println!(
" Nothing is shared. Turn single channels on later with `lean-ctx config set cloud.<key> true`."
);
}
steps::record(store, &instance.org_id, shared, UtcDateTime::now())?;
Ok(Some(shared))
}
fn map_project(config: &CloudConfig, session: &Session, root: &Path, device: bool) -> Outcome {
match lean_ctx_cloud::resolution::forget_stale_at(session.store.data_dir(), root) {
Ok(Some(stale)) => println!(" Note: {}; resolving it again.", stale.describe()),
Ok(None) => {}
Err(error) => return Outcome::Retry(error.to_string()),
}
let outcome = map_project_step(config, session, root, device);
if let Outcome::Shared { ns, name } = &outcome {
let ours = lean_ctx_protocol::cloud::vault::VaultRefV1 {
ns: ns.clone(),
name: name.clone(),
};
if let Some(other) = lean_ctx_cloud::mapping::bound_elsewhere(session, root, &ours) {
println!(
" Warning: LeanCTX Cloud binds this repository to the vault {}/{} (another Instance of {} resolved it there), but this machine syncs it with {ns}/{name}. One repository in two vaults splits its knowledge: run `lean-ctx cloud link {}/{}` here, or move it in LeanCTX Cloud.",
other.ns, other.name, session.instance.org_name, other.ns, other.name
);
}
}
outcome
}
fn map_project_step(config: &CloudConfig, session: &Session, root: &Path, device: bool) -> Outcome {
let project = project_name(root);
let org = &session.instance.org_name;
match steps::project_step(&VaultMap::load(session.store.data_dir()), root) {
ProjectStep::None => Outcome::NoProject,
ProjectStep::Known(vault) => {
println!(" This project syncs with the vault {vault}.");
let (ns, name) = vault.split_once('/').unwrap_or(("", vault.as_str()));
Outcome::Shared {
ns: ns.to_string(),
name: name.to_string(),
}
}
ProjectStep::Resolve => {
let resolve =
|| lean_ctx_cloud::knowledge::pull::resolve_project(session, config, root);
let mut result = resolve();
if device
&& let Err(MapError::Consent(ConsentError::Required { consent_id, .. })) = &result
{
match answer_on_device_page(config, session, consent_id) {
Ok(()) => result = resolve(),
Err(error) => println!(" cloud: {error}"),
}
}
if let Err(MapError::Consent(ConsentError::Required { consent_id, .. })) = &result
&& lean_ctx::core::host_env::stdin_is_terminal()
{
println!(
" {project} has not shared anything with {org} yet. Confirm it once: what your agents learn here then goes into this project's vault in {org} (the one it already has there, or a new one)."
);
let approve = ["approve".to_string(), consent_id.clone()];
match super::cloud_consent_cmd::run(config, &approve) {
Ok(()) => result = resolve(),
Err(error) => println!(" cloud: {error}"),
}
}
match result {
Ok(record) => {
println!(
" This project syncs with the vault {}/{}.",
record.ns, record.name
);
Outcome::Shared {
ns: record.ns,
name: record.name,
}
}
Err(MapError::Consent(ConsentError::Denied)) => {
Outcome::KeptLocal("you said no to sharing it".into())
}
Err(MapError::Consent(_)) => Outcome::Waiting,
Err(MapError::Cloud(CloudError::Refused(why)))
if why.starts_with("vault_mismatch") =>
{
Outcome::KeptLocal(why)
}
Err(error) => Outcome::Retry(format!(
"it has no vault yet ({error}); `lean-ctx cloud link <workspace>/<vault>` names one"
)),
}
}
}
}
fn answer_on_device_page(
config: &CloudConfig,
session: &Session,
consent_id: &str,
) -> Result<(), CloudError> {
use lean_ctx_cloud::consent::broker::{Broker, Trust};
use lean_ctx_cloud::consent::web::WebRun;
let store = &session.store;
let broker = Broker::open(store, Trust::load(store, config));
let now = || u64::try_from(UtcDateTime::now().timestamp_millis()).unwrap_or_default();
let run = WebRun {
broker: &broker,
data_dir: store.data_dir(),
now: &now,
sleep: &std::thread::sleep,
open: &|_| {},
};
let record = session.with_client(|client| {
Ok(run.run_device(client, consent_id, &mut || {
println!(" One more question is waiting for you on the browser page.");
}))
})??;
if record.state == lean_ctx_cloud::consent::State::Approved {
Ok(())
} else {
Err(ConsentError::Denied.into())
}
}
const RUNTIME_QUESTION: &str = "Your plan includes the LeanCTX Intelligence runtime (proprietary, from the signed LeanCTX channel); it enforces your workspace's policy on this machine. Install it now?";
pub(super) fn install_runtime(consented: bool) -> Result<(), CloudError> {
if !super::prompt::confirm(RUNTIME_QUESTION, consented) {
return Err(CloudError::Config(
"the runtime was not installed: no consent".into(),
));
}
lean_ctx::core::config::Config::update_global(|config| config.cloud.runtime_consent = true)
.map_err(|e| CloudError::Local(format!("record the consent: {e}")))?;
let result = lean_ctx::core::intelligence_runtime::run(&[
"sync-configured".to_string(),
"--accept-proprietary".to_string(),
])
.map_err(|e| CloudError::Local(format!("runtime install: {e}")))?;
println!("{result}");
Ok(())
}
pub(super) fn open_browser(url: &str) -> std::io::Result<()> {
if std::env::var_os("LEAN_CTX_NO_BROWSER").is_some() {
return Ok(());
}
#[cfg(target_os = "macos")]
let mut command = std::process::Command::new("open");
#[cfg(windows)]
let mut command = {
let mut c = std::process::Command::new("rundll32");
c.arg("url.dll,FileProtocolHandler");
c
};
#[cfg(not(any(target_os = "macos", windows)))]
let mut command = std::process::Command::new("xdg-open");
command
.arg(url)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.map(|_| ())
}
#[cfg(test)]
mod tests {
use super::*;
fn decided(shared: bool, source: Option<&str>) -> steps::SharingDecision {
steps::SharingDecision {
schema: steps::SHARING_SCHEMA.into(),
org_id: "org_a".into(),
shared,
decided_at: "2026-10-26T09:00:00Z".into(),
source: source.map(str::to_string),
}
}
#[test]
fn step_three_says_when_the_browser_answered() {
assert_eq!(
decided_line(&decided(true, Some("browser")), "Acme"),
"answered in the browser: shared with Acme."
);
assert!(
decided_line(&decided(false, Some("browser")), "Acme")
.starts_with("answered in the browser: not shared")
);
assert_eq!(
decided_line(&decided(true, None), "Acme"),
"Sharing with Acme is on: you confirmed it."
);
}
#[test]
fn a_recorded_no_is_asked_again_in_a_terminal_only() {
assert!(asks_again(&decided(false, Some("browser")), true));
assert!(asks_again(&decided(false, None), true));
assert!(!asks_again(&decided(false, None), false), "no terminal");
assert!(!asks_again(&decided(true, None), true), "a yes stands");
}
const TOKEN: &str = "het_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
const OTHER: &str = "het_fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210";
fn token_from(args: &[&str], stdin: &str, env: Option<&str>) -> Result<Option<String>, String> {
let args: Vec<String> = args.iter().map(|a| (*a).to_string()).collect();
enrollment_token(
&args,
&mut std::io::Cursor::new(stdin.as_bytes()),
env.map(std::ffi::OsString::from),
)
.map(|t| t.map(|t| format!("{t:?}")))
.map_err(|e| e.to_string())
}
#[test]
fn the_enrollment_token_comes_from_stdin_first_then_the_environment() {
assert_eq!(token_from(&[], "", None), Ok(None), "no token: device flow");
assert_eq!(
token_from(&[], TOKEN, Some("")),
Ok(None),
"empty env is unset"
);
let some = Ok(Some("EnrollmentToken(het_…)".to_string()));
assert_eq!(token_from(&[], "", Some(TOKEN)), some);
assert_eq!(
token_from(&["--enrollment-token-stdin"], &format!("{TOKEN}\n"), None),
some
);
let stdin_wins = token_from(&["--enrollment-token-stdin"], "nope\n", Some(OTHER));
assert!(stdin_wins.is_err_and(|e| e.contains("malformed")));
assert_eq!(
token_from(
&["--enrollment-token-stdin"],
&format!("{TOKEN}\n"),
Some("bad")
),
some
);
assert_eq!(
token_from(
&["--enrollment-token-stdin"],
&format!("{TOKEN}\n{OTHER}\n"),
None
),
some
);
assert!(
token_from(&["--enrollment-token-stdin"], "\n", Some(TOKEN))
.is_err_and(|e| e.contains("stdin held no enrollment token"))
);
}
#[test]
fn the_enrollment_token_is_never_taken_from_argv_nor_echoed() {
let inline = format!("--enrollment-token={TOKEN}");
for args in [vec!["--enrollment-token", TOKEN], vec![inline.as_str()]] {
let error = token_from(&args, "", None).expect_err("argv refused");
assert!(
error.contains("never passed on the command line"),
"{error}"
);
assert!(!error.contains(&TOKEN[4..]), "{error}");
}
let bad = format!("{}x", &TOKEN[..TOKEN.len() - 1]);
for error in [
token_from(&[], "", Some(&bad)).unwrap_err(),
token_from(&["--enrollment-token-stdin"], &bad, None).unwrap_err(),
] {
assert!(error.contains("malformed"), "{error}");
assert!(!error.contains(&bad[4..20]), "{error}");
}
let long = "a".repeat(4096);
let error = token_from(&["--enrollment-token-stdin"], &long, None).unwrap_err();
assert!(!error.contains(&long[..64]), "{error}");
}
fn strings(args: &[&str]) -> Vec<String> {
args.iter().map(|a| (*a).to_string()).collect()
}
#[test]
fn trial_flags_default_to_personal_and_plan_needs_trial() {
assert_eq!(trial_choice(&strings(&[])), Ok(None));
assert_eq!(
trial_choice(&strings(&["--trial", "--yes"])),
Ok(Some(TrialPlan::Personal))
);
assert_eq!(
trial_choice(&strings(&["--trial", "--plan", "team"])),
Ok(Some(TrialPlan::Team))
);
let alone = trial_choice(&strings(&["--plan", "team"])).unwrap_err();
assert_eq!(alone.event_code(), "config");
assert!(alone.to_string().contains("only valid with --trial"));
let other = trial_choice(&strings(&["--trial", "--plan", "enterprise"])).unwrap_err();
assert!(other.to_string().contains("choose personal or team"));
assert!(trial_choice(&strings(&["--trial", "--plan"])).is_err());
}
fn lease(trial_ends_at: Option<&str>) -> CloudLeaseV1 {
let envelope: Value = serde_json::from_str(
&std::fs::read_to_string(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../lean-ctx-protocol/tests/fixtures/cloud/lease_envelope.response.json"
))
.unwrap(),
)
.unwrap();
let mut lease = envelope["lease"].clone();
if let Some(at) = trial_ends_at {
lease["trial_ends_at"] = at.into();
}
serde_json::from_value(lease).unwrap()
}
#[test]
fn trial_json_events_carry_the_documented_members() {
let code = DeviceCodeV1 {
schema: "leanctx.cloud.device-code/v1".into(),
device_code: "secret-device-code".into(),
user_code: "WDJB-MJHT".into(),
verification_uri: "https://cloud.leanctx.com/device".into(),
verification_uri_complete:
"https://cloud.leanctx.com/device?user_code=WDJB-MJHT&intent=trial&plan=personal"
.into(),
interval: 5,
expires_in: 600,
features: Vec::new(),
intent: None,
plan: None,
};
let event = code_event(&code);
assert_eq!(
event,
json!({
"event": "code",
"verification_uri": "https://cloud.leanctx.com/device",
"verification_uri_complete": "https://cloud.leanctx.com/device?user_code=WDJB-MJHT&intent=trial&plan=personal",
"user_code": "WDJB-MJHT",
"expires_in": 600,
})
);
assert!(!event.to_string().contains("secret-device-code"));
assert!(!event.to_string().contains('\n'));
let trial = connected_event(&lease(Some("2026-12-02T10:00:00Z")));
assert_eq!(trial["event"], "connected");
assert_eq!(trial["trial_ends_at"], "2026-12-02T10:00:00Z");
assert!(trial["plan"].is_string());
let plain = connected_event(&lease(None));
assert_eq!(plain["trial_ends_at"], Value::Null);
assert_eq!(
plain.as_object().unwrap().keys().collect::<Vec<_>>(),
["event", "plan", "trial_ends_at"]
);
let used = CloudError::PlanRequired(Box::new(lean_ctx_cloud::error::PlanNeed {
plan_needed: Some("personal".into()),
reason: Some(lean_ctx_cloud::error::TRIAL_USED.into()),
plans_url: Some("https://cloud.leanctx.com/plans".into()),
..Default::default()
}));
let event = error_event(&used);
assert_eq!(event["event"], "error");
assert_eq!(event["code"], "trial_used");
assert!(event["message"].as_str().unwrap().contains("trial"));
let expired = error_event(&CloudError::DeviceFlow(
lean_ctx_cloud::error::CODE_EXPIRED.into(),
));
assert_eq!(expired["code"], "expired");
let denied = error_event(&CloudError::DeviceFlow(
lean_ctx_cloud::error::CODE_DENIED.into(),
));
assert_eq!(denied["code"], "denied");
let old = error_event(&CloudError::TrialUnsupported {
origin: "https://cloud.example".into(),
});
assert_eq!(old["code"], "trial_unsupported");
}
fn source_of(name: &str) -> &'static str {
static SOURCE: std::sync::LazyLock<String> =
std::sync::LazyLock::new(|| include_str!("cloud_connect_cmd.rs").replace("\r\n", "\n"));
let source: &'static str = &SOURCE;
let tests = source
.find("#[cfg(test)]\nmod tests")
.expect("tests module");
let start = [format!("\nfn {name}("), format!("\npub(super) fn {name}(")]
.iter()
.find_map(|head| source[..tests].find(head.as_str()))
.unwrap_or_else(|| panic!("fn {name} not found"));
let end = source[start..].find("\n}\n").expect("closing brace") + start;
&source[start..end]
}
fn stdout_writes(body: &str) -> Vec<&'static str> {
let mut found = Vec::new();
for needle in ["print!", "println!"] {
for (at, _) in body.match_indices(needle) {
if !body[..at].ends_with('e') {
found.push(needle);
}
}
}
for needle in [
"io::stdout",
"stdout()",
"write!(",
"writeln!(",
"print_done(",
] {
if body.contains(needle) {
found.push(needle);
}
}
found
}
#[test]
fn json_connect_writes_stdout_only_through_the_event_writer() {
let emit_body = source_of("emit");
assert!(emit_body.contains("std::io::stdout()"), "{emit_body}");
let run = source_of("run");
let json_branch = &run[..run.find("let token = take_enrollment_token").unwrap()];
assert!(json_branch.contains("run_json(config, args)"));
assert!(
stdout_writes(json_branch).is_empty(),
"the --json branch of run prints: {json_branch}"
);
for name in [
"run_json",
"take_enrollment_token",
"enrollment_token",
"trial_choice",
"origin_for",
"default_label",
"code_event",
"connected_event",
"error_event",
"name_the_root",
"trial_aware",
"open_browser",
"announce_and_pull",
] {
let body = source_of(name);
assert_eq!(
stdout_writes(body),
Vec::<&str>::new(),
"fn {name} writes to stdout outside emit"
);
}
let body = source_of("run_json");
let emits: Vec<_> = body.match_indices("emit(").map(|(at, _)| at).collect();
assert!(!emits.is_empty());
for at in emits {
let call = &body[at..];
assert!(
call.starts_with("emit(&code_event(") || call.starts_with("emit(&connected_event("),
"{}",
&call[..call.len().min(60)]
);
}
assert!(
body.find("emit(&code_event(").unwrap() < body.find("finish_device_flow(").unwrap()
);
assert!(stdout_writes(run).contains(&"println!"));
assert!(stdout_writes("let _ = writeln!(std::io::stdout(), \"x\");").len() >= 2);
assert!(stdout_writes("eprintln!(\"to stderr\");").is_empty());
}
#[test]
fn trial_expiry_names_the_plans_page_not_a_new_code() {
let expired = || CloudError::DeviceFlow(lean_ctx_cloud::error::CODE_EXPIRED.into());
let trial = error_event(&trial_aware(expired(), Some(TrialPlan::Personal)));
assert_eq!(trial["code"], "expired");
let message = trial["message"].as_str().unwrap();
assert!(
message.contains("choose a plan in LeanCTX Cloud"),
"{message}"
);
assert!(
message.contains("lean-ctx cloud connect --trial"),
"{message}"
);
let plain = error_event(&trial_aware(expired(), None));
assert_eq!(plain["code"], "expired");
assert_eq!(plain["message"], expired().to_string());
let denied = CloudError::DeviceFlow(lean_ctx_cloud::error::CODE_DENIED.into());
assert_eq!(trial_aware(denied.clone(), Some(TrialPlan::Team)), denied);
}
#[test]
fn yes_answers_sharing_only_where_the_terminal_asks() {
let yes = vec!["--yes".to_string()];
assert!(
yes_answers_sharing(&yes, false),
"older LeanCTX Cloud: as before"
);
assert!(
!yes_answers_sharing(&yes, true),
"C0 2.1 LeanCTX Cloud: the page asks, --yes never answers"
);
assert!(!yes_answers_sharing(&[], false));
}
}