Initial public release

Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
Evan Whittaker
2026-10-17 12:08:30 -05:00
commit 09a7de2520
1730 changed files with 412952 additions and 0 deletions

View File

@@ -0,0 +1,349 @@
//! Command-line surface — the clap argument parser, subcommands, and arg→settings mappers.
use clap::{Parser, ValueEnum};
mod commands;
mod permission_mode;
pub(crate) use commands::*;
pub(crate) use permission_mode::PermissionModeArg;
/// Luxe — a fast, lean, security-conscious agentic coding harness.
#[derive(Parser, Debug)]
#[command(name = "luxe", version, about)]
pub(crate) struct Args {
/// Run headless (non-interactive single prompt).
#[arg(long)]
pub(crate) headless: bool,
/// Speak the JSONL front-end protocol on stdio: wire actions in, events out. For editor
/// plugins, alternative UIs, and anything driving Luxe as a session rather than a one-shot.
/// See `docs/guide/rpc.md`.
#[arg(long, conflicts_with = "headless")]
pub(crate) rpc: bool,
/// Let an `--rpc` client publish to GitHub: post comments and reviews, answer threads, and open,
/// change, merge and restack pull requests. Off by default, so a client can read GitHub but not
/// write to it unless you say so.
/// A read-only session refuses these writes even with this flag. Governs what the client can do
/// directly, not the agent, whose GitHub writes still ask first.
#[arg(long)]
pub(crate) github_writes: bool,
/// The prompt to run in headless mode.
#[arg(short = 'p', long)]
pub(crate) prompt: Option<String>,
/// Headless output format: `text` (streamed assistant text) or `json` (a JSONL event
/// stream with per-turn usage). Ignored outside `--headless`.
#[arg(long, value_enum, default_value_t = OutputFormat::Text)]
pub(crate) format: OutputFormat,
/// Provider to use, by id: `anthropic`, `openai`, `lmstudio`, and so on. Overrides env + config.
#[arg(long, global = true)]
pub(crate) provider: Option<String>,
/// Model to use: an id (`gpt-4o`) or `provider/id` (`anthropic/claude-opus-5-5`), which picks the provider too. Overrides env + config.
#[arg(long, global = true)]
pub(crate) model: Option<String>,
/// API key over env + config; `$ENV`/`!command` work too, and a literal shows in others' `ps`.
#[arg(long, global = true)]
pub(crate) api_key: Option<String>,
/// Base URL override (must include the API version segment, e.g. `.../v1`).
#[arg(long, global = true)]
pub(crate) base_url: Option<String>,
/// Initial reasoning level for models that support it: `off`, `minimal`, `low`, `medium`,
/// `high`, `xhigh`, or `ultra`. Defaults to `off`. In the TUI, `/thinking` changes it live.
#[arg(long, global = true)]
pub(crate) thinking: Option<String>,
/// Start in plan mode: read, ask, and write only the plan (`plan.files`, `PLAN.md` by default).
/// In the TUI, shift+tab or `/mode` switches back to build.
#[arg(long, global = true)]
pub(crate) plan: bool,
/// Permission mode: `default`, `strict` (ask before mutating tools), `read-only` (deny
/// mutating tools), or `yolo` (allow everything, guardrails off). Overrides the config file.
#[arg(long, value_enum, ignore_case = true, value_parser = permission_mode::PermissionModeParser, global = true)]
pub(crate) permission_mode: Option<PermissionModeArg>,
/// Shortcut for `--permission-mode read-only` (look, don't touch).
#[arg(long, global = true)]
pub(crate) read_only: bool,
/// Allow everything, disabling the built-in guardrails. An explicit opt-out; use with care.
#[arg(long, global = true)]
pub(crate) yolo: bool,
/// What an `ask` resolves to in a run with nobody to ask: `allow` (the default) or `deny`.
/// Applies to `--headless`, `luxe loop` and the review agent, which cannot prompt. `deny`
/// refuses the call and tells the model the run is unattended, so it takes another route.
/// Sets `agent.on_ask` for one run; `--rpc` and the TUI reject it, since there you answer.
#[arg(long, value_enum, global = true, conflicts_with = "auto_approve")]
pub(crate) on_ask: Option<OnAskArg>,
/// Start with auto-approve on, for a TUI or RPC session you intend to walk away from: an
/// `ask` is allowed without a card, every `deny` is still enforced, and the status bar says
/// so. The same state `/permissions on` reaches. Headless and `luxe loop` allow by default
/// — see `--on-ask`.
#[arg(long, global = true)]
pub(crate) auto_approve: bool,
/// Trust this project: honor its `.luxe/hooks.json` and `gate.commands`, let its
/// `.luxe/permissions.json` loosen policy rather than only tighten it, and start the language
/// servers, formatters and MCP servers it supplies even in a headless, loop or review run.
#[arg(long, global = true)]
pub(crate) trust_project: bool,
/// Leave a tool unregistered for this run, on top of whatever config already disables.
/// Repeatable: `--no-tool web_search --no-tool web_fetch`. `read`, `write`, `edit` and `bash`
/// are refused — the agent cannot work without them. See `/tools`.
#[arg(long = "no-tool", value_name = "TOOL", global = true)]
pub(crate) no_tool: Vec<String>,
/// Register a tool your config disables, for this run only. The counterpart to `--no-tool`,
/// so a standing preference does not have to be edited to make an exception to it.
#[arg(long = "with-tool", value_name = "TOOL", global = true)]
pub(crate) with_tool: Vec<String>,
/// Resume the most recent session for this project.
#[arg(short = 'c', long = "continue")]
pub(crate) continue_session: bool,
/// Resume a specific session by id (see `luxe sessions list`).
#[arg(long)]
pub(crate) resume: Option<String>,
/// Take up issue NUMBER: a new session in its own worktree, on a branch named for the issue,
/// whose first message carries the issue's words.
#[arg(long, value_name = "NUMBER", conflicts_with_all = ["resume", "continue_session", "from_pr"])]
pub(crate) issue: Option<u64>,
/// Fix pull request NUMBER: a new session with it checked out in its own worktree, where a
/// plain `git push` lands on it. `--from-pr` resumes one that already worked on it.
#[arg(
long,
value_name = "NUMBER",
conflicts_with_all = ["resume", "continue_session", "from_pr", "issue", "worktree"]
)]
pub(crate) pr: Option<u64>,
/// Work in a git worktree of this session's own, on BRANCH (a generated `luxe/…` name when
/// none is given), so the agent's edits never land in your checkout.
#[arg(long, value_name = "BRANCH", num_args = 0..=1, default_missing_value = "")]
pub(crate) worktree: Option<String>,
/// Resume the newest session that worked on this pull request: opened it, pushed to it, or
/// answered its threads.
#[arg(long = "from-pr", value_name = "NUMBER", conflicts_with_all = ["resume", "continue_session"])]
pub(crate) from_pr: Option<u64>,
/// Loop subcommand for continuous development.
#[command(subcommand)]
pub(crate) command: Option<SubCommand>,
}
/// A flag combination `luxe` refuses, worded for the reader: `main` prints it after `luxe:` and
/// exits 1.
#[derive(Debug)]
pub(crate) struct UsageError(String);
impl std::fmt::Display for UsageError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for UsageError {}
impl Args {
/// Whether this run owns project state — and so may create `.luxe/` in the project it found.
///
/// The question exists because creating that directory is not free: [`luxe_core::project`] ranks
/// a directory holding one above a nearer checkout, on purpose, so a `.luxe/` left in `/tmp` by
/// a command that only wanted somewhere to log re-roots every repository underneath it.
///
/// A session owns project state; so does `luxe loop`, which keeps its run there, and
/// `luxe mcp add`/`remove`, which write `.luxe/mcp.json`. Everything else reads and reports.
/// The matches are exhaustive so a new subcommand has to answer this before it compiles.
pub(crate) fn owns_project_state(&self) -> bool {
match &self.command {
// No subcommand is a session: the TUI, `--headless`, or `--rpc`.
None => true,
Some(SubCommand::Loop(_)) => true,
Some(SubCommand::Mcp(mcp)) => match mcp.command {
McpCommand::Add { .. } | McpCommand::Remove { .. } => true,
McpCommand::List | McpCommand::Tools | McpCommand::Login { .. } => false,
},
Some(
SubCommand::Auth(_)
| SubCommand::Docs(_)
| SubCommand::Doctor
| SubCommand::Init(_)
| SubCommand::Models(_)
| SubCommand::Sessions(_)
| SubCommand::Wire(_),
) => false,
}
}
/// Whether a human answers this run's permission prompts — the TUI and `--rpc`.
///
/// What `--on-ask` is *not* for: it settles what an `ask` becomes where there is nobody to ask,
/// so on these two surfaces it would quietly do nothing while reading like a policy.
pub(crate) fn prompts_a_human(&self) -> bool {
self.command.is_none() && !self.headless
}
/// Whether `--github-writes` was given anywhere but an `--rpc` session.
///
/// Checked by hand because clap's `requires` cannot see it: a `bool` flag carries an implicit
/// default, so `rpc` always counts as present. Elsewhere the flag would read as "the agent may
/// now publish", which it neither says nor does.
pub(crate) fn github_writes_misplaced(&self) -> bool {
self.github_writes && !(self.rpc && self.command.is_none())
}
/// Refuses a combination of flags that would read as one thing and do another.
///
/// Clap checks what it can see; these it cannot (see [`Self::github_writes_misplaced`]). Asked
/// first, so a refusal happens before anything has moved, and answered as an error so the run
/// unwinds through its destructors instead of exiting from the middle of it.
pub(crate) fn validate(&self) -> anyhow::Result<()> {
if self.on_ask.is_some() && self.prompts_a_human() {
// Not a warning: the flag reads as a policy and would do nothing here, which is the
// shape of mistake that is only discovered by an agent doing something unwatched.
return Err(UsageError(
"--on-ask settles what an `ask` becomes when nobody can answer it, so it is for \
--headless and `luxe loop`. In the TUI and --rpc you answer the prompts \
yourself; --auto-approve is the walk-away switch there."
.to_string(),
)
.into());
}
if self.github_writes_misplaced() {
return Err(UsageError(
"--github-writes lets an --rpc client publish to GitHub, so it only works with \
--rpc. The agent's own GitHub writes are governed by permissions, not this flag."
.to_string(),
)
.into());
}
if self.command.is_none() && self.headless && self.prompt.is_none() {
return Err(UsageError("--headless requires --prompt <text>".to_string()).into());
}
Ok(())
}
/// Whether an engine runs, and so whether a startup notice reaches the reader as an event.
///
/// The TUI owns the terminal, so a notice printed to stderr there lands on the drawing surface
/// and is gone; it goes through [`luxe_core::Event::Notice`] instead, the same path headless and
/// RPC use. A subcommand has no engine, so its notices are printed.
pub(crate) fn starts_an_engine(&self) -> bool {
match &self.command {
None => true,
Some(SubCommand::Loop(r#loop)) => matches!(r#loop.command, LoopCommand::Start { .. }),
Some(
SubCommand::Auth(_)
| SubCommand::Docs(_)
| SubCommand::Doctor
| SubCommand::Init(_)
| SubCommand::Mcp(_)
| SubCommand::Models(_)
| SubCommand::Sessions(_)
| SubCommand::Wire(_),
) => false,
}
}
/// Collect the provider/model/auth overrides supplied on the command line.
pub(crate) fn overrides(&self) -> crate::engine_setup::CliOverrides {
crate::engine_setup::CliOverrides {
provider: self.provider.clone(),
model: self.model.clone(),
api_key: self.api_key.clone(),
base_url: self.base_url.clone(),
}
}
}
/// Parse a `--thinking` level name into a `ThinkingLevel`, accepting the same spellings Luxe
/// displays (`off`..`ultra`, plus `max` as an alias for `ultra`). Returns `None` for unknown input.
pub(crate) fn parse_thinking_level(raw: &str) -> Option<luxe_core::provider::ThinkingLevel> {
let name = raw.trim().to_ascii_lowercase();
if name == "max" {
return Some(luxe_core::provider::ThinkingLevel::Ultra);
}
luxe_core::provider::ThinkingLevel::ALL.into_iter().find(|level| level.as_str() == name)
}
/// `--on-ask`, which is [`luxe_core::config::OnAsk`] with clap's spellings.
///
/// A `ValueEnum` rather than a parsed string, deliberately unlike `--thinking`: that warns and
/// carries on, which is right for a preference and wrong for a policy. `--on-ask dney` has
/// to stop the run, because ignoring it leaves an unattended agent approving its own escalations
/// while its operator believes otherwise.
#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum OnAskArg {
/// Let an unattended `ask` through, the default.
Allow,
/// Refuse it, and tell the model why.
Deny,
}
impl From<OnAskArg> for luxe_core::config::OnAsk {
fn from(arg: OnAskArg) -> Self {
match arg {
OnAskArg::Allow => Self::Allow,
OnAskArg::Deny => Self::Deny,
}
}
}
/// Headless output format.
#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq, Default)]
pub(crate) enum OutputFormat {
/// Stream assistant text to stdout; tool activity to stderr (human-friendly).
#[default]
Text,
/// Emit a JSONL event stream (one object per line) with per-turn usage — for scripts,
/// harness adapters, and benchmarks.
Json,
}
/// Resolve the permission-mode override from the flags, highest precedence first:
/// `--yolo` > `--read-only` > `--permission-mode <name>`. Returns `None` to defer to the config
/// file / built-in default. Clap rejects unrecognized mode names before startup.
pub(crate) fn permission_mode_from_args(
args: &Args,
) -> Option<luxe_core::permission::PermissionMode> {
use luxe_core::permission::PermissionMode;
if args.yolo {
return Some(PermissionMode::Yolo);
}
if args.read_only {
return Some(PermissionMode::ReadOnly);
}
args.permission_mode.map(Into::into)
}
/// Map the resume flags (`--resume <id>` / `-c/--continue`) to a `ResumeMode`.
pub(crate) fn resume_from_args(args: &Args) -> crate::engine_setup::ResumeMode {
use crate::engine_setup::ResumeMode;
if let Some(id) = args.resume.clone() {
ResumeMode::Session(id)
} else if let Some(number) = args.from_pr {
ResumeMode::PullRequest(number)
} else if args.continue_session {
ResumeMode::Latest
} else {
ResumeMode::New
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,243 @@
//! Subcommands — the arguments each `luxe <command>` takes.
use clap::{Parser, Subcommand};
/// Subcommands for luxe.
#[derive(Subcommand, Debug)]
pub(crate) enum SubCommand {
/// Sign in to a provider, check credentials, or sign out.
Auth(AuthArgs),
/// Read Luxe's user guide, for this version.
Docs(DocsArgs),
/// Check which language servers, debug adapters and tools work on this machine.
Doctor,
/// Set Luxe up: a theme, a provider, the tools and the start screen.
Init(InitArgs),
/// Run the agent through a phased plan on its own.
Loop(LoopArgs),
/// Add, list and sign in to MCP servers.
Mcp(McpArgs),
/// List models, show one's details, or refresh the catalog.
Models(ModelsArgs),
/// List this project's sessions.
Sessions(SessionsArgs),
/// Summarize a `LUXE_WIRE_LOG` capture.
Wire(WireArgs),
}
/// Docs arguments.
#[derive(Parser, Debug)]
pub(crate) struct DocsArgs {
/// A page to print, such as `install` or `hooks`. Without one, lists every page.
pub(crate) page: Option<String>,
/// Print the lines across every page that contain all of these words.
#[arg(long)]
pub(crate) search: Option<String>,
}
/// Wire arguments.
#[derive(Parser, Debug)]
pub(crate) struct WireArgs {
/// Path to a log written by `LUXE_WIRE_LOG=<path> luxe ...`.
pub(crate) log: std::path::PathBuf,
/// Break the tool-schema total down per tool.
#[arg(long)]
pub(crate) tools: bool,
}
/// Auth arguments.
#[derive(Parser, Debug)]
pub(crate) struct AuthArgs {
#[command(subcommand)]
pub(crate) command: AuthCommand,
}
/// Auth subcommand — provider credentials.
#[derive(Subcommand, Debug)]
pub(crate) enum AuthCommand {
/// Sign in to a provider (API key or subscription).
Login {
/// Provider id (e.g. `openai`, `anthropic`, `github-copilot`). Omit to choose from a list.
provider: Option<String>,
/// Which login to run: `api-key` or `subscription`. Only needed when a provider has both.
#[arg(long)]
method: Option<String>,
/// Supply the API key directly instead of being prompted. Beware shell history.
#[arg(long, conflicts_with = "stdin")]
api_key: Option<String>,
/// Read the API key from stdin (`pass show openai | luxe auth login openai --stdin`).
#[arg(long)]
stdin: bool,
/// Skip the "does this key work" request — for an air-gapped or proxied setup.
#[arg(long)]
no_verify: bool,
},
/// List every provider and how each one is configured.
List,
/// Show credential detail (kind, source, expiry) for one provider or all configured ones.
Status {
/// Provider id. Omit for every configured provider.
provider: Option<String>,
},
/// Remove a stored credential. Environment variables are left alone.
Logout {
/// Provider id.
provider: String,
},
}
/// Models arguments.
#[derive(Parser, Debug)]
pub(crate) struct ModelsArgs {
#[command(subcommand)]
pub(crate) command: ModelsCommand,
}
/// Models subcommand — what Luxe knows about a model, and where it learned it.
#[derive(Subcommand, Debug)]
pub(crate) enum ModelsCommand {
/// List known models for the providers Luxe can route to.
List {
/// Only this provider.
#[arg(long)]
provider: Option<String>,
/// Only models pinned in `models.json` / `auth.json`.
#[arg(long)]
configured: bool,
},
/// Show one model's resolved metadata and which layer supplied each field.
Show {
/// `provider/id`, or a bare id to use the active provider.
model: String,
},
/// Revalidate the models.dev cache now.
Refresh {
/// Fetch even when the cache is still current.
#[arg(long)]
force: bool,
},
}
/// Init arguments.
#[derive(Parser, Debug)]
pub(crate) struct InitArgs {
/// Start over: remove the existing config before setting up.
#[arg(long)]
pub(crate) force: bool,
/// Write a config that chooses nothing, without asking, so every default applies.
#[arg(long)]
pub(crate) defaults: bool,
}
/// Sessions arguments.
#[derive(Parser, Debug)]
pub(crate) struct SessionsArgs {
#[command(subcommand)]
pub(crate) command: SessionsCommand,
}
/// Sessions subcommand — inspect resumable sessions.
#[derive(Subcommand, Debug)]
pub(crate) enum SessionsCommand {
/// List sessions for the current project (newest first).
List,
}
/// Loop arguments.
#[derive(Parser, Debug)]
pub(crate) struct LoopArgs {
#[command(subcommand)]
pub(crate) command: LoopCommand,
}
/// MCP arguments.
#[derive(Parser, Debug)]
pub(crate) struct McpArgs {
#[command(subcommand)]
pub(crate) command: McpCommand,
}
/// Loop subcommand — manage continuous development loops.
#[derive(Subcommand, Debug)]
pub(crate) enum LoopCommand {
/// Start a new continuous loop.
Start {
/// Print nothing but the banner: no per-turn activity. The log and the journal are
/// written either way.
#[arg(long)]
quiet: bool,
/// Maximum turns per run (default: 50).
#[arg(long, default_value_t = 50)]
max_turns: u32,
/// Compact at this percentage of the usable window (default: `compaction.at`, else 75).
#[arg(long, value_parser = clap::value_parser!(u8).range(1..=100))]
compact_percent: Option<u8>,
/// Pause at this percentage of context window (default: 90).
#[arg(long, default_value_t = 90)]
pause_percent: u8,
},
/// Stop the current loop.
Stop,
/// Pause the current loop.
Pause,
/// Resume a paused loop.
Resume,
/// Show loop status.
Status,
/// Show loop phase (and optionally set it).
Phase {
/// Set phase to this number.
#[arg(long)]
set: Option<u32>,
},
/// Reset the run's turn count, so the next `luxe loop start` gets all of `--max-turns` again.
Fresh,
}
/// MCP subcommand — manage MCP servers and tools.
#[derive(Subcommand, Debug)]
pub(crate) enum McpCommand {
/// List configured MCP servers.
List,
/// Add an MCP server.
Add {
/// Server ID.
#[arg(long)]
id: String,
/// Server name.
#[arg(long)]
name: String,
/// Command to run (for stdio transport).
#[arg(long)]
command: Option<String>,
/// URL (for HTTP/SSE transport).
#[arg(long)]
url: Option<String>,
},
/// Remove an MCP server.
Remove {
/// Server ID to remove.
#[arg(long)]
id: String,
},
/// List tools from all MCP servers.
Tools,
/// Authorize an OAuth-protected MCP server (opens a browser flow).
Login {
/// Server ID to authorize.
#[arg(long)]
id: String,
},
}

View File

@@ -0,0 +1,109 @@
//! Permission mode — CLI policy validation before startup.
use clap::builder::{EnumValueParser, PossibleValue, TypedValueParser};
use clap::ValueEnum;
use luxe_core::permission::PermissionMode;
/// Permission presets accepted on the command line.
#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PermissionModeArg {
/// Keep the built-in guardrails without asking before every mutation.
Default,
/// Ask before mutating tools.
Strict,
/// Deny mutating tools.
#[value(alias = "readonly", alias = "ro")]
ReadOnly,
/// Disable the built-in guardrails.
Yolo,
}
impl From<PermissionModeArg> for PermissionMode {
fn from(arg: PermissionModeArg) -> Self {
match arg {
PermissionModeArg::Default => Self::Default,
PermissionModeArg::Strict => Self::Strict,
PermissionModeArg::ReadOnly => Self::ReadOnly,
PermissionModeArg::Yolo => Self::Yolo,
}
}
}
#[derive(Clone)]
pub(super) struct PermissionModeParser;
impl TypedValueParser for PermissionModeParser {
type Value = PermissionModeArg;
fn parse_ref(
&self,
cmd: &clap::Command,
arg: Option<&clap::Arg>,
value: &std::ffi::OsStr,
) -> Result<Self::Value, clap::Error> {
// Keep the core parser's normalization without accepting an unknown policy
let normalized = value.to_str().map(|raw| raw.trim().replace(['_', ' '], "-"));
let value = normalized.as_deref().map(std::ffi::OsStr::new).unwrap_or(value);
EnumValueParser::<PermissionModeArg>::new().parse_ref(cmd, arg, value)
}
fn possible_values(&self) -> Option<Box<dyn Iterator<Item = PossibleValue> + '_>> {
Some(Box::new(
PermissionModeArg::value_variants().iter().filter_map(ValueEnum::to_possible_value),
))
}
}
#[cfg(test)]
mod tests {
use super::super::{permission_mode_from_args, Args};
use clap::{error::ErrorKind, Parser};
use luxe_core::permission::PermissionMode;
/// A policy typo must stop startup instead of falling back to permissive defaults.
#[test]
fn an_unknown_permission_mode_is_refused() {
for typo in ["strcit", "read-onyl", "", "unknown"] {
let error = Args::try_parse_from(["luxe", "--permission-mode", typo])
.expect_err("an invalid policy must stop startup");
assert_eq!(error.kind(), ErrorKind::InvalidValue, "{typo:?}");
}
}
/// CLI validation must preserve the mode parser's accepted spellings.
#[test]
fn accepted_permission_modes_keep_their_meaning() {
for spelling in [
"default",
"strict",
"read-only",
"readonly",
"ro",
"yolo",
"read_only",
"read only",
"STRICT",
" Read_Only ",
] {
let args = Args::try_parse_from(["luxe", "--permission-mode", spelling])
.expect("a supported mode");
assert_eq!(permission_mode_from_args(&args), PermissionMode::parse(spelling));
}
}
/// Shortcuts retain precedence over a valid named mode; absence defers to config.
#[test]
fn permission_shortcuts_keep_their_precedence() {
for (flags, expected) in [
(vec![], None),
(vec!["--permission-mode", "strict"], Some(PermissionMode::Strict)),
(vec!["--permission-mode", "strict", "--read-only"], Some(PermissionMode::ReadOnly)),
(vec!["--permission-mode", "strict", "--yolo"], Some(PermissionMode::Yolo)),
(vec!["--read-only", "--yolo"], Some(PermissionMode::Yolo)),
] {
let args =
Args::try_parse_from(std::iter::once("luxe").chain(flags)).expect("valid flags");
assert_eq!(permission_mode_from_args(&args), expected);
}
}
}

View File

@@ -0,0 +1,257 @@
use super::*;
use clap::Parser;
/// What a command line classifies as, for the two questions startup asks before dispatch.
///
/// The classification is an exhaustive match, so a new [`SubCommand`] variant does not compile
/// until somebody answers for it; this pins the answers that are already given. The stakes are
/// asymmetric: a session wrongly classed as reporting loses its project log, and a reporting
/// command wrongly classed as a session leaves a `.luxe/` that silently re-roots every
/// repository beneath it.
#[test]
fn only_the_commands_that_own_project_state_may_create_one() {
let parse = |line: &[&str]| Args::try_parse_from(line).expect("a valid command line");
for session in [
vec!["luxe"],
vec!["luxe", "--headless", "-p", "hi"],
vec!["luxe", "--rpc"],
vec!["luxe", "loop", "start"],
vec!["luxe", "loop", "status"],
vec!["luxe", "mcp", "add", "--id", "x", "--name", "x", "--command", "x"],
vec!["luxe", "mcp", "remove", "--id", "x"],
] {
assert!(parse(&session).owns_project_state(), "{session:?} writes into the project");
}
for reporting in [
vec!["luxe", "auth", "list"],
vec!["luxe", "doctor"],
vec!["luxe", "init"],
vec!["luxe", "models", "list"],
vec!["luxe", "sessions", "list"],
vec!["luxe", "wire", "/tmp/log"],
vec!["luxe", "mcp", "list"],
vec!["luxe", "mcp", "tools"],
] {
assert!(
!parse(&reporting).owns_project_state(),
"{reporting:?} only reads, so it must leave no .luxe/ behind"
);
}
}
/// `--github-writes` is a grant to an RPC client, so it means nothing anywhere else.
///
/// Accepting it on the TUI or headless would read as "the agent may now publish", which it
/// does not say and does not do.
#[test]
fn github_writes_is_only_for_an_rpc_client() {
let parse = |line: &[&str]| Args::try_parse_from(line).expect("a valid command line");
let granted = parse(&["luxe", "--rpc", "--github-writes"]);
assert!(granted.github_writes && !granted.github_writes_misplaced());
assert!(!parse(&["luxe", "--rpc"]).github_writes, "off by default");
assert!(!parse(&["luxe"]).github_writes_misplaced(), "absent is never misplaced");
for elsewhere in [
vec!["luxe", "--github-writes"],
vec!["luxe", "--headless", "-p", "hi", "--github-writes"],
vec!["luxe", "--rpc", "--github-writes", "doctor"],
] {
assert!(parse(&elsewhere).github_writes_misplaced(), "{elsewhere:?}");
}
}
/// `--on-ask` settles the answer for a run with nobody to ask, so the surfaces that *can* ask
/// have to be told apart from the ones that cannot — on the TUI and RPC the flag would read as
/// a policy and do nothing, which is the shape of mistake nobody finds until an agent has been
/// running unwatched.
#[test]
fn only_a_run_with_nobody_to_ask_can_be_told_what_an_ask_becomes() {
let parse = |line: &[&str]| Args::try_parse_from(line).expect("a valid command line");
for interactive in [vec!["luxe"], vec!["luxe", "--rpc"]] {
assert!(parse(&interactive).prompts_a_human(), "{interactive:?}");
}
for unattended in [
vec!["luxe", "--headless", "-p", "hi"],
vec!["luxe", "loop", "start"],
vec!["luxe", "doctor"],
] {
assert!(!parse(&unattended).prompts_a_human(), "{unattended:?}");
}
// A misspelled policy stops the run rather than being ignored — unlike `--thinking`, which
// warns and carries on, because that is a preference and this is not.
assert!(
Args::try_parse_from(["luxe", "--headless", "-p", "hi", "--on-ask", "dney"]).is_err(),
"an unreadable policy must not resolve to the permissive answer"
);
assert_eq!(
parse(&["luxe", "--headless", "-p", "hi", "--on-ask", "deny"]).on_ask,
Some(OnAskArg::Deny)
);
// The two flags are opposite answers to one question; asking for both is a mistake.
assert!(
Args::try_parse_from(["luxe", "--auto-approve", "--on-ask", "allow"]).is_err(),
"--auto-approve and --on-ask cannot both be in force"
);
}
/// A notice reaches the reader through the engine where there is one, and is printed where
/// there is not. Getting this wrong writes on the TUI's drawing surface.
#[test]
fn a_startup_notice_goes_through_the_engine_only_where_one_runs() {
let parse = |line: &[&str]| Args::try_parse_from(line).expect("a valid command line");
for engine in
[vec!["luxe"], vec!["luxe", "--headless", "-p", "hi"], vec!["luxe", "loop", "start"]]
{
assert!(parse(&engine).starts_an_engine(), "{engine:?}");
}
for printed in
[vec!["luxe", "doctor"], vec!["luxe", "loop", "status"], vec!["luxe", "auth", "list"]]
{
assert!(!parse(&printed).starts_an_engine(), "{printed:?}");
}
}
/// Environment and the real config directory are process-global; serialize what touches them.
static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// A project whose config starts sessions in plan mode, and an isolated global config.
fn project_that_plans() -> (tempfile::TempDir, tempfile::TempDir) {
let home = tempfile::tempdir().expect("temp home");
std::env::set_var("XDG_CONFIG_HOME", home.path());
std::env::set_var("XDG_STATE_HOME", home.path().join("state"));
for key in ["LUXE_PROVIDER", "LUXE_MODEL", "LUXE_API_KEY", "ANTHROPIC_API_KEY"] {
std::env::remove_var(key);
}
let project = tempfile::tempdir().expect("temp project");
std::fs::create_dir_all(project.path().join(".luxe")).expect("project config dir");
std::fs::write(
project.path().join(".luxe").join("config.json"),
r#"{"agent":{"default_mode":"plan"}}"#,
)
.expect("write project config");
(home, project)
}
/// `agent.default_mode` decides where a session starts; `build` is not worth sending.
#[test]
fn the_configured_default_mode_is_where_a_session_starts() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let (_home, project) = project_that_plans();
let settings = crate::engine_setup::AgentSettings::resolve(
project.path().to_path_buf(),
crate::engine_setup::CliOverrides {
provider: Some("lmstudio".into()),
..Default::default()
},
);
assert_eq!(settings.initial_mode.as_deref(), Some(luxe_core::mode::PLAN));
assert!(!settings.review_engine, "an ordinary session is not a reviewer");
std::fs::write(
project.path().join(".luxe").join("config.json"),
r#"{"agent":{"default_mode":"build"}}"#,
)
.unwrap();
let settings = crate::engine_setup::AgentSettings::resolve(
project.path().to_path_buf(),
crate::engine_setup::CliOverrides::default(),
);
assert_eq!(settings.initial_mode, None, "the default needs no switch");
}
#[test]
fn plan_is_a_flag_every_command_line_takes() {
let parse = |line: &[&str]| Args::try_parse_from(line).expect("a valid command line");
assert!(parse(&["luxe", "--plan"]).plan);
assert!(parse(&["luxe", "--headless", "--plan", "-p", "plan it"]).plan);
assert!(!parse(&["luxe"]).plan);
assert!(Args::try_parse_from(["luxe", "--role", "planner"]).is_err(), "--role is gone");
}
/// `--from-pr` names a pull request, and it is one way of choosing a session among three: it
/// cannot be combined with naming a session or continuing the latest.
#[test]
fn from_pr_resumes_by_pull_request_and_excludes_the_other_resumes() {
use crate::engine_setup::ResumeMode;
let parse = |line: &[&str]| Args::try_parse_from(line).expect("a valid command line");
assert!(matches!(
resume_from_args(&parse(&["luxe", "--from-pr", "146"])),
ResumeMode::PullRequest(146)
));
assert!(matches!(resume_from_args(&parse(&["luxe"])), ResumeMode::New));
assert!(Args::try_parse_from(["luxe", "--from-pr", "146", "--continue"]).is_err());
assert!(Args::try_parse_from(["luxe", "--from-pr", "146", "--resume", "abc"]).is_err());
assert!(Args::try_parse_from(["luxe", "--from-pr", "#146"]).is_err(), "a number, no hash");
}
/// `--pr` starts new work on a pull request, so it goes with nothing that picks a session, an
/// issue, or a branch of its own.
#[test]
fn pr_starts_new_work_and_excludes_every_other_start() {
let parsed = Args::try_parse_from(["luxe", "--pr", "142"]).expect("valid");
assert_eq!(parsed.pr, Some(142));
assert!(matches!(resume_from_args(&parsed), crate::engine_setup::ResumeMode::New));
for other in [
&["--from-pr", "142"][..],
&["--continue"],
&["--resume", "abc"],
&["--issue", "7"],
&["--worktree"],
] {
let mut line = vec!["luxe", "--pr", "142"];
line.extend_from_slice(other);
assert!(Args::try_parse_from(line).is_err(), "{other:?}");
}
}
/// What a flag combination is refused with, or `None` when it is allowed.
fn refusal(line: &[&str]) -> Option<String> {
let args = Args::try_parse_from(line).expect("clap accepts the line");
args.validate().err().map(|error| {
let usage = error.downcast_ref::<UsageError>().expect("a refusal is a usage error");
usage.to_string()
})
}
/// `--on-ask` settles what an `ask` becomes where nobody can answer it, so on the two surfaces
/// where somebody does it would read as a policy and do nothing.
#[test]
fn on_ask_is_refused_where_a_person_answers() {
for line in [vec!["luxe", "--on-ask", "deny"], vec!["luxe", "--rpc", "--on-ask", "deny"]] {
let said = refusal(&line).expect("refused");
assert!(said.contains("--on-ask settles what an `ask` becomes"), "{line:?}: {said}");
}
for line in [
vec!["luxe", "--headless", "-p", "hi", "--on-ask", "deny"],
vec!["luxe", "loop", "start", "--on-ask", "deny"],
] {
assert_eq!(refusal(&line), None, "{line:?} has nobody to answer");
}
}
/// `--github-writes` lets an `--rpc` client publish; anywhere else it would read as the agent being
/// allowed to.
#[test]
fn github_writes_is_refused_outside_rpc() {
let said = refusal(&["luxe", "--github-writes"]).expect("refused");
assert!(said.contains("--github-writes lets an --rpc client publish"), "{said}");
assert!(refusal(&["luxe", "--headless", "-p", "x", "--github-writes"]).is_some());
assert_eq!(refusal(&["luxe", "--rpc", "--github-writes"]), None);
}
/// A headless run with nothing to run is refused before anything else happens, a worktree made for
/// it included.
#[test]
fn a_headless_run_needs_a_prompt() {
let said = refusal(&["luxe", "--headless"]).expect("refused");
assert_eq!(said, "--headless requires --prompt <text>");
assert_eq!(refusal(&["luxe", "--headless", "-p", "hi"]), None);
// a subcommand is not a headless run, nor is a session with a person at it
assert_eq!(refusal(&["luxe", "doctor"]), None);
assert_eq!(refusal(&["luxe"]), None);
}

View File

@@ -0,0 +1,505 @@
//! `luxe auth` — log in, list, inspect, and log out, without opening the TUI.
//!
//! The CLI half of onboarding. Same flow engine the `/login` wizard drives, so anything that works
//! here works there; this surface exists for headless boxes, SSH sessions, and scripts.
use crate::output::{out, outln};
use std::sync::Arc;
use anyhow::{bail, Context, Result};
use luxe_core::auth::{
AuthError, AuthMethodKind, AuthService, CredentialStatus, LoginOutcome, ProviderOption,
};
use luxe_providers::auth::ProviderAuth;
use secrecy::SecretString;
use super::args::AuthCommand;
use crate::auth_terminal::{style, TerminalAuth};
/// Run an `auth` subcommand.
pub(crate) async fn run_auth_command(command: AuthCommand) -> Result<()> {
match command {
AuthCommand::Login { provider, method, api_key, stdin, no_verify } => {
login(provider, method, api_key, stdin, no_verify).await
}
AuthCommand::List => list(),
AuthCommand::Status { provider } => status(provider),
AuthCommand::Logout { provider } => logout(provider),
}
}
/// `luxe auth login [provider]`.
async fn login(
provider: Option<String>,
method: Option<String>,
api_key: Option<String>,
read_stdin: bool,
no_verify: bool,
) -> Result<()> {
let service = match no_verify {
true => ProviderAuth::new().without_verification(),
false => ProviderAuth::new(),
};
let key = match (api_key, read_stdin) {
(Some(_), true) => bail!("pass either --api-key or --stdin, not both"),
(Some(key), false) => Some(SecretString::from(key)),
(None, true) => Some(read_key_from_stdin()?),
(None, false) => None,
};
let interaction = TerminalAuth::new().with_api_key(key.clone());
// Choosing a provider is a question, so a non-interactive run has to be told which one.
let provider = match provider {
Some(provider) => provider,
None if interaction.is_interactive() => choose_provider(&service)?,
None => bail!(
"which provider? pass one (e.g. `luxe auth login openai`); run `luxe auth list` to \
see them all"
),
};
let option = service.provider(&provider).ok_or_else(|| {
anyhow::anyhow!(
"unknown provider '{provider}' — run `luxe auth list` to see the supported ones"
)
})?;
let method_id = resolve_method(&option, method.as_deref(), key.is_some(), &interaction)?;
eprintln!("\n{}", style::bold(&format!("Signing in to {}", option.name)));
let interaction: Arc<dyn luxe_core::auth::AuthInteraction> = Arc::new(interaction);
match service.login(&option.id, &method_id, interaction).await {
Ok(outcome) => {
report_success(&service, &outcome);
Ok(())
}
Err(AuthError::Cancelled) => {
eprintln!("\nCancelled. Nothing was saved.");
std::process::exit(1);
}
Err(error) => Err(anyhow::anyhow!(error)).context(format!("signing in to {}", option.name)),
}
}
/// Print the confirmation, and say what to do next.
///
/// Aligned labels rather than prose: after a multi-step login the useful thing is a scannable
/// summary of what now exists — which account, which models, which file.
fn report_success(service: &ProviderAuth, outcome: &LoginOutcome) {
// A local server stores no credential, so it was connected rather than signed in to, and
// there is no kind to name.
let (verb, kind) = match outcome.kind {
Some(kind) => ("Signed in to", format!(" {}", style::dim(&format!("({})", kind.label())))),
None => ("Connected to", String::new()),
};
outln!(
"\n{} {}{kind}",
style::success("✓"),
style::bold(&format!("{verb} {}", outcome.provider_name)),
);
let field = |label: &str, value: &str| outln!(" {:<9} {value}", style::dim(label));
if let Some(account) = &outcome.account {
field("account", account);
}
for note in &outcome.notes {
field("models", note);
}
field("saved to", &luxe_core::paths::home_relative(&service.store_path()));
if let Some(model) = &outcome.suggested_model {
field("model", &format!("{model} {}", style::dim("(now the default)")));
}
// Advice sits apart from the summary: it's about what to do later, not what just happened.
for advice in &outcome.advice {
outln!("\n {}", style::dim(advice));
}
match outcome.suggested_model {
Some(_) => outln!("\nRun `luxe` to start, or `/model` to pick another."),
None => outln!("\nRun `luxe` to start, then `/model` to pick a model."),
}
}
/// `luxe auth list` — every provider and how it's configured.
fn list() -> Result<()> {
let service = ProviderAuth::new();
let options = service.providers();
let width = options.iter().map(|option| option.id.len()).max().unwrap_or(8);
outln!("Providers ({}):\n", service.store_path().display());
for option in &options {
let methods: Vec<&str> = option
.methods
.iter()
.map(|method| match method.kind {
AuthMethodKind::Subscription => "subscription",
AuthMethodKind::ApiKey if option.keyless => "local",
AuthMethodKind::ApiKey => "api key",
})
.collect();
outln!(
" {mark} {id:<width$} {status:<26} {name} [{methods}]",
mark = if option.status.is_configured() { "●" } else { "○" },
id = option.id,
status = describe_option(option),
name = option.name,
methods = methods.join(", "),
);
}
outln!("\n ● configured ○ not configured");
outln!(" Sign in with `luxe auth login <provider>`.");
Ok(())
}
/// `luxe auth status [provider]` — the detail, including OAuth expiry.
fn status(provider: Option<String>) -> Result<()> {
let service = ProviderAuth::new();
let options: Vec<ProviderOption> = match &provider {
Some(id) => vec![service
.provider(id)
.ok_or_else(|| anyhow::anyhow!("unknown provider '{id}' — run `luxe auth list`"))?],
None => service.providers().into_iter().filter(|o| o.status.is_configured()).collect(),
};
if options.is_empty() {
outln!("No provider is configured yet. Run `luxe auth login` to set one up.");
return Ok(());
}
for option in options {
outln!("{} ({})", option.name, option.id);
outln!(" Credential: {}", describe_option(&option));
if let CredentialStatus::Stored(info) = &option.status {
if let Some(expires) = info.expires_at_ms {
let now = now_ms();
outln!(
" Expires: {}",
match expires.checked_sub(now) {
Some(remaining) if remaining > 0 =>
format!("in {}", human_duration(remaining / 1000)),
_ => "expired — refreshes on the next request".to_string(),
}
);
}
if let Some(account) = &info.account {
outln!(" Account: {account}");
}
}
if let Some(note) = &option.note {
outln!(" Note: {note}");
}
outln!(" File: {}", service.store_path().display());
outln!();
}
Ok(())
}
/// `luxe auth logout <provider>`.
fn logout(provider: String) -> Result<()> {
let service = ProviderAuth::new();
let name = service.provider(&provider).map(|option| option.name).unwrap_or(provider.clone());
match service.logout(&provider)? {
true => {
outln!("✓ Removed the stored credential for {name}.");
let ambient = service
.provider(&provider)
.map(|option| option.status)
.filter(CredentialStatus::is_configured);
if let Some(CredentialStatus::Env(name)) = ambient {
outln!(" Note: {name} is still set in your environment, so it will be used.");
}
Ok(())
}
false => {
// A key that lives somewhere else isn't ours to remove, but silence would read as a
// failed logout when the provider plainly still works.
match service.provider(&provider).map(|option| option.status) {
Some(CredentialStatus::Env(variable)) => outln!(
"Nothing stored for {name} — it's configured by {variable} in your environment."
),
Some(CredentialStatus::Config(file)) => outln!(
"Nothing stored for {name} — its key is written in {file}; edit that to remove it."
),
_ => outln!("Nothing stored for {name}."),
}
Ok(())
}
}
}
/// Ask which provider, listing the configured ones first.
fn choose_provider(service: &ProviderAuth) -> Result<String> {
let options = service.providers();
outln!("\nWhich provider?\n");
for (index, option) in options.iter().enumerate() {
let subscription =
if option.methods.iter().any(|method| method.kind == AuthMethodKind::Subscription) {
" (subscription available)"
} else {
Default::default()
};
outln!(
" {:>2}) {}{}{}",
index + 1,
option.name,
subscription,
if option.status.is_configured() { " — configured" } else { "" }
);
}
loop {
out!("\n > ");
let mut line = String::new();
if std::io::stdin().read_line(&mut line).unwrap_or(0) == 0 {
bail!("cancelled");
}
let answer = line.trim();
if answer.is_empty() {
bail!("cancelled");
}
if let Some(option) = answer
.parse::<usize>()
.ok()
.filter(|index| *index >= 1 && *index <= options.len())
.map(|index| &options[index - 1])
.or_else(|| {
options
.iter()
.find(|option| option.id == answer || option.name.eq_ignore_ascii_case(answer))
})
{
return Ok(option.id.clone());
}
outln!(" Pick 1–{}, or type a provider id.", options.len());
}
}
/// Which login method to run: what was asked for, the only one there is, or the user's pick.
fn resolve_method(
option: &ProviderOption,
requested: Option<&str>,
have_key: bool,
interaction: &TerminalAuth,
) -> Result<String> {
if let Some(requested) = requested {
let wanted = normalize_method(requested);
return match option.method(&wanted) {
Some(method) => Ok(method.id.clone()),
None => bail!(
"{} has no '{requested}' login; it supports: {}",
option.name,
option.methods.iter().map(|m| m.id.as_str()).collect::<Vec<_>>().join(", ")
),
};
}
// A key on the command line says what the user meant.
if have_key {
if let Some(method) = option.method("api-key") {
return Ok(method.id.clone());
}
}
if let Some(method) = option.default_method() {
return Ok(method.id.clone());
}
if !interaction.is_interactive() {
bail!(
"{} supports several login methods; pass --method <{}>",
option.name,
option.methods.iter().map(|m| m.id.as_str()).collect::<Vec<_>>().join("|")
);
}
outln!("\nHow do you want to sign in to {}?\n", option.name);
for (index, method) in option.methods.iter().enumerate() {
outln!(" {}) {}", index + 1, method.label);
if let Some(detail) = &method.detail {
outln!(" {detail}");
}
}
loop {
out!("\n > ");
let mut line = String::new();
if std::io::stdin().read_line(&mut line).unwrap_or(0) == 0 {
bail!("cancelled");
}
let answer = line.trim();
if answer.is_empty() {
return Ok(option.methods[0].id.clone());
}
if let Some(method) = answer
.parse::<usize>()
.ok()
.filter(|index| *index >= 1 && *index <= option.methods.len())
.map(|index| &option.methods[index - 1])
.or_else(|| option.method(&normalize_method(answer)))
{
return Ok(method.id.clone());
}
outln!(" Pick 1–{}.", option.methods.len());
}
}
/// Accept the spellings people actually type for a method.
fn normalize_method(raw: &str) -> String {
match raw.trim().to_ascii_lowercase().replace('_', "-").as_str() {
"subscription" | "oauth" | "sub" | "login" => "oauth".to_string(),
"api-key" | "apikey" | "key" | "api" => "api-key".to_string(),
other => other.to_string(),
}
}
/// Read a key piped in on stdin.
fn read_key_from_stdin() -> Result<SecretString> {
use std::io::Read;
let mut buffer = String::new();
std::io::stdin().read_to_string(&mut buffer).context("reading the key from stdin")?;
let key = buffer.trim();
if key.is_empty() {
bail!("stdin was empty — pipe the key in, e.g. `pass show openai | luxe auth login openai --stdin`");
}
Ok(SecretString::from(key.to_string()))
}
/// How a provider resolves, for a person reading a table.
///
/// A local server that needs no key isn't "unconfigured" — saying so would send someone looking for
/// a credential that doesn't exist.
fn describe_option(option: &ProviderOption) -> String {
match (&option.status, option.keyless) {
(CredentialStatus::Missing, true) => "no credential needed".to_string(),
(status, _) => describe_status(status),
}
}
/// One-line description of how a provider's credential resolves.
fn describe_status(status: &CredentialStatus) -> String {
match status {
CredentialStatus::Missing => "—".to_string(),
CredentialStatus::Env(name) => format!("env: {name}"),
CredentialStatus::Config(file) => format!("config: {file}"),
CredentialStatus::Local(endpoint) => format!("local server: {endpoint}"),
CredentialStatus::Stored(info) => match info.kind {
luxe_core::auth::CredentialKind::ApiKey => "api key (saved)".to_string(),
luxe_core::auth::CredentialKind::OAuth => "subscription (saved)".to_string(),
},
}
}
fn human_duration(seconds: u64) -> String {
match seconds {
0..=90 => format!("{seconds}s"),
91..=5400 => format!("{}m", seconds / 60),
_ => format!("{}h {}m", seconds / 3600, (seconds % 3600) / 60),
}
}
fn now_ms() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|elapsed| elapsed.as_millis() as u64)
.unwrap_or(0)
}
#[cfg(test)]
mod tests {
use super::*;
use luxe_core::auth::{AuthMethod, StoredCredentialInfo};
fn option(methods: Vec<AuthMethod>) -> ProviderOption {
ProviderOption {
id: "openai".into(),
name: "OpenAI".into(),
methods,
status: CredentialStatus::Missing,
note: None,
console_url: None,
keyless: false,
needs_endpoint: false,
}
}
#[test]
fn method_spellings_are_forgiving() {
for raw in ["oauth", "OAuth", "subscription", "sub", "login"] {
assert_eq!(normalize_method(raw), "oauth", "{raw}");
}
for raw in ["api-key", "api_key", "apikey", "KEY", "api"] {
assert_eq!(normalize_method(raw), "api-key", "{raw}");
}
assert_eq!(normalize_method("weird"), "weird");
}
#[test]
fn a_single_method_needs_no_question() {
let option = option(vec![AuthMethod::api_key(None)]);
let resolved =
resolve_method(&option, None, false, &TerminalAuth::new()).expect("unambiguous");
assert_eq!(resolved, "api-key");
}
#[test]
fn a_requested_method_is_validated_against_the_provider() {
let option = option(vec![AuthMethod::api_key(None)]);
let error = resolve_method(&option, Some("oauth"), false, &TerminalAuth::new())
.expect_err("must refuse");
assert!(format!("{error}").contains("no 'oauth' login"), "got {error}");
}
/// Passing a key states the intent, so an ambiguous provider doesn't need to ask.
#[test]
fn a_supplied_key_selects_the_api_key_method() {
let option = option(vec![
AuthMethod::subscription("Sign in with OpenRouter", None),
AuthMethod::api_key(None),
]);
let resolved =
resolve_method(&option, None, true, &TerminalAuth::new()).expect("key implies api-key");
assert_eq!(resolved, "api-key");
}
/// A scripted run must fail with instructions rather than block on a prompt it can't show.
#[test]
fn an_ambiguous_non_interactive_login_says_what_flag_to_pass() {
let option =
option(vec![AuthMethod::subscription("Sign in", None), AuthMethod::api_key(None)]);
// `TerminalAuth::new()` is non-interactive under the test harness (stdin isn't a tty).
let interaction = TerminalAuth::new();
if interaction.is_interactive() {
return; // running with a tty attached; the prompt path is exercised manually
}
let error = resolve_method(&option, None, false, &interaction).expect_err("must not block");
assert!(format!("{error}").contains("--method"), "got {error}");
}
/// A local server that needs no key must not read as "unconfigured".
#[test]
fn a_keyless_provider_says_so_instead_of_showing_a_dash() {
let mut local = option(vec![AuthMethod::api_key(None)]);
local.keyless = true;
assert_eq!(describe_option(&local), "no credential needed");
// A provider that *does* need one still reads as unconfigured.
let hosted = option(vec![AuthMethod::api_key(None)]);
assert_eq!(describe_option(&hosted), "—");
}
#[test]
fn status_lines_name_the_source() {
assert_eq!(describe_status(&CredentialStatus::Missing), "—");
assert_eq!(
describe_status(&CredentialStatus::Env("OPENAI_API_KEY".into())),
"env: OPENAI_API_KEY"
);
assert_eq!(
describe_status(&CredentialStatus::Stored(StoredCredentialInfo {
kind: luxe_core::auth::CredentialKind::OAuth,
expires_at_ms: None,
account: None,
})),
"subscription (saved)"
);
}
#[test]
fn durations_read_like_a_human_wrote_them() {
assert_eq!(human_duration(45), "45s");
assert_eq!(human_duration(600), "10m");
assert_eq!(human_duration(7_500), "2h 5m");
}
}

View File

@@ -0,0 +1,594 @@
//! Subcommand runners — the `loop`, `mcp`, and `sessions` management commands.
use super::args::{LoopCommand, McpCommand, SessionsCommand};
use crate::output::{out, outln};
/// Run a loop subcommand.
pub(crate) async fn run_loop_command(
cmd: LoopCommand,
mut settings: crate::engine_setup::AgentSettings,
) -> anyhow::Result<()> {
use luxe_core::loop_controller::LoopController;
// The one place this is set: everything the loop owns is opt-in, and an ordinary session must
// not carry a tool for driving a loop that is not running.
settings.loop_driven = true;
// A loop builds; a plan to build from is what plan mode is for, before the loop starts
settings.initial_mode = None;
let cwd = settings.state_root.clone();
let state_path = cwd.join(".luxe").join("loop_state.json");
let stop_path = cwd.join(".luxe").join("STOP");
// `.luxe/loop/`, emphatically not `.pi/agent-loop/`, which is another agent harness's directory.
// Writing a journal there was bad manners; *archiving* it was destructive, because the archive
// step renames over whatever `PROGRESS.archive.md` it finds and that file was 1.2 MB of
// somebody else's history.
tokio::fs::create_dir_all(cwd.join(".luxe").join("loop")).await?;
let controller = LoopController::new(state_path.clone(), stop_path);
// Read what the run already is before touching it: a subcommand acting on a default state
// would report zeros whatever the file said, and the ones that save — `phase --set`, `stop`,
// `pause`, `resume`, `fresh` — would write those defaults back over the iteration count, the
// run's spend, the tuning fields and the `phase_baseline` a review diffs against.
if state_path.exists() {
if let Err(error) = controller.load().await {
tracing::warn!(%error, path = %state_path.display(), "could not read the loop state");
}
}
match cmd {
LoopCommand::Start { quiet, max_turns, compact_percent, pause_percent } => {
let flags = StartFlags { quiet, max_turns, compact_percent, pause_percent };
start_loop(controller, settings, flags).await?;
}
LoopCommand::Stop => {
outln!("Stopping loop...");
controller.stop().await?;
outln!("Loop stopped.");
}
LoopCommand::Pause => {
outln!("Pausing loop...");
controller.pause().await?;
outln!("Loop paused.");
}
LoopCommand::Resume => {
outln!("Resuming loop...");
controller.resume().await?;
// `resume` clears the run to continue; it does not drive one, and saying "resumed"
// and stopping reads exactly like a loop that then did nothing.
outln!("Loop resumed. Run `luxe loop start` to drive it.");
}
LoopCommand::Status => print_loop_status(&controller).await,
LoopCommand::Phase { set } => {
if let Some(phase) = set {
controller.set_phase(phase).await?;
outln!("Phase set to {}", phase);
} else {
let state = controller.get_state().await;
outln!("Current phase: {}", state.current_phase);
}
}
LoopCommand::Fresh => {
// Each `start` opens a session of its own; what carries over is the turn count
controller
.update_state(|state| {
state.iteration = 0;
})
.await;
controller.save().await?;
let phase = controller.get_state().await.current_phase;
outln!("Turn count reset, on phase {phase}. Run `luxe loop start` to go on.");
}
}
Ok(())
}
/// What `luxe loop start` was asked for on the command line.
struct StartFlags {
quiet: bool,
max_turns: u32,
compact_percent: Option<u8>,
pause_percent: u8,
}
/// Builds the gate and the hooks, spawns the engine and drives it until the loop stops.
async fn start_loop(
mut controller: luxe_core::loop_controller::LoopController,
mut settings: crate::engine_setup::AgentSettings,
flags: StartFlags,
) -> anyhow::Result<()> {
let StartFlags { quiet, max_turns, compact_percent, pause_percent } = flags;
let cwd = settings.state_root.clone();
// Two loops in one project share a phase counter, a journal and a `STOP` sentinel, so
// the second to start quietly corrupts the first one's run. Only a *live* owner
// refuses: a crashed run must never lock a project out of starting again.
if let Some(pid) = controller.owned_by_another_process().await {
anyhow::bail!(
"a loop is already running in this project (pid {pid}).\n\
Watch it with `luxe loop status`, or end it with `luxe loop stop` and start \
again."
);
}
outln!("Starting continuous loop...");
// One gate, cleared by both a `progress` claim and a `complete` claim.
let shared = std::sync::Arc::new(controller.clone());
// Set before either engine is built, so the reviewer's — built from a clone of these
// settings — reports into the same run without further wiring.
settings.spend_sink =
Some(std::sync::Arc::new(crate::engine_setup::LoopSpendSink::new(shared.clone())));
let gate = crate::engine_setup::build_phase_gate(&settings, shared.clone()).await;
let reviewing = gate.has_reviewer();
let commands = crate::engine_setup::phase_gate_config(&settings).gate.commands().len();
let hook_registry = luxe_core::loop_hooks::build_hooks(shared, cwd.clone(), gate).await;
controller.set_hook_registry(hook_registry.clone());
// Asked, not asserted: this line was a hand-written list, so it described whatever the
// hooks were on the day somebody typed it.
outln!("Loop hooks, in the order they run: {}", hook_registry.hook_names().join(", "));
match (commands, reviewing) {
(0, false) => outln!(
"Phase gate: nothing configured — a claimed phase is taken at its word (set gate.commands and/or gate.review)"
),
(0, true) => outln!("Phase gate: a reviewer in a fresh context reads the change"),
(n, false) => outln!(
"Phase gate: {n} acceptance command(s) (set gate.review for a review too)"
),
(n, true) => outln!(
"Phase gate: {n} acceptance command(s), then a reviewer in a fresh context reads the change"
),
}
// After the gate, whose reviewer works in a session of its own
let compact_percent = tune_for_loop(&mut settings, compact_percent);
// Apply CLI flags to controller state so runaway guards use them (not defaults).
controller
.update_state(|s| {
s.max_turns_per_run = max_turns;
s.compact_percent = compact_percent;
s.pause_percent = pause_percent;
})
.await;
// Spawn the production engine with the real hooks.
let (action_tx, event_rx) =
crate::loop_run::spawn_production_engine(settings.clone(), hook_registry).await?;
outln!("Engine spawned with real provider and loop hooks");
controller.start().await?;
outln!(
"Loop started (max_turns={max_turns}, compact={compact_percent}%, pause={pause_percent}%)"
);
// Drive the engine loop until it stops. The kickoff says which phase this is and what
// the plan says it is — the same thing every later iteration is told.
let running_rx = controller.running_rx();
let phase = controller.get_state().await.current_phase;
let kickoff = luxe_core::hooks::self_continuation::steer_for(&cwd, phase, true).await;
crate::loop_run::drive_loop(
action_tx,
event_rx,
running_rx,
kickoff,
crate::loop_view::LoopView::new(quiet),
)
.await?;
Ok(())
}
/// Prints where the run stands, from the state file and not from what the run last claimed.
async fn print_loop_status(controller: &luxe_core::loop_controller::LoopController) {
let status = controller.status_summary().await;
outln!("Loop status:");
// What the run *is*, not what the file says it intended: a killed run leaves
// `running: true` behind and has no way to correct it.
outln!(" Running: {}", status.is_live());
if let Some(line) = status.liveness_line() {
outln!(" Process: {line}");
}
outln!(" Iteration: {}", status.iteration);
outln!(" Phase: {}", status.current_phase);
outln!(" Max turns: {}", status.max_turns_per_run);
let spend = controller.get_state().await.spend;
let lines = spend.summary_lines();
if !lines.is_empty() {
outln!(" Spend this run:");
for line in lines {
outln!(" {line}");
}
}
}
/// Run an MCP subcommand against the durable `.luxe/mcp.json` config store.
pub(crate) async fn run_mcp_command(
cmd: McpCommand,
settings: &crate::engine_setup::AgentSettings,
) -> anyhow::Result<()> {
use luxe_core::mcp_client::{McpServerConfig, McpTransport};
use luxe_core::mcp_config::McpConfigStore;
let cwd = std::env::current_dir()?;
let store = McpConfigStore::for_repo(&cwd);
match cmd {
McpCommand::List => {
let servers = McpConfigStore::resolved(&cwd);
if servers.is_empty() {
outln!("No MCP servers configured. Add one with `luxe mcp add`.");
return Ok(());
}
outln!("Configured MCP servers ({}):", servers.len());
for s in &servers {
let (kind, detail) = match &s.transport {
McpTransport::Stdio { command, args, .. } => {
("stdio", format!("{} {}", command, args.join(" ")).trim().to_string())
}
McpTransport::HttpSse { url } => ("http", url.clone()),
};
let state = if s.enabled { "enabled" } else { "disabled" };
let origin = if s.declared_by_user { "" } else { " not started (project)" };
outln!(" {} [{}] ({}) {}{} — {}", s.id, s.name, kind, state, origin, detail);
}
}
McpCommand::Add { id, name, command, url } => {
let transport = match (command, url) {
(Some(_), Some(_)) => {
anyhow::bail!("cannot specify both --command and --url");
}
(Some(command), None) => stdio_transport(&command)?,
(None, Some(url)) => McpTransport::HttpSse { url },
(None, None) => anyhow::bail!("provide either --command (stdio) or --url (http)"),
};
store.add(McpServerConfig {
id: id.clone(),
name,
transport,
enabled: true,
..Default::default()
})?;
outln!("Added MCP server '{id}' to {}.", store.path().display());
}
McpCommand::Remove { id } => {
if store.remove(&id)? {
outln!("Removed MCP server '{id}'.");
} else {
outln!("No MCP server '{id}' was configured.");
}
}
McpCommand::Tools => run_mcp_tools(settings).await,
McpCommand::Login { id } => {
use luxe_mcp::ServerRegistry;
let servers = mcp_command_servers(settings);
let manager = ServerRegistry::new(servers, None);
let client = manager.oauth_client(&id).ok_or_else(|| {
anyhow::anyhow!("'{id}' is not an OAuth-configured HTTP MCP server")
})?;
// flat on purpose: the chain would print the OS error a second time under `Caused by`
client.interactive_login().await.map_err(|e| anyhow::anyhow!("{e}"))?;
}
}
Ok(())
}
fn mcp_command_servers(
settings: &crate::engine_setup::AgentSettings,
) -> Vec<luxe_core::mcp_client::McpServerConfig> {
use crate::engine_setup::{mcp_servers_for_run, note_project_servers, project_servers_allowed};
let config = luxe_core::config::Config::load(&settings.state_root);
note_project_servers(project_servers_allowed(
config.lsp.project_servers.unwrap_or_default(),
false,
settings.trust_project,
));
let (servers, refused) = mcp_servers_for_run(&settings.state_root);
if !refused.is_empty() {
outln!(
"Not starting project MCP servers: {}. Use --trust-project, or set lsp.project_servers in your own config.",
refused.join(", ")
);
}
servers
}
async fn run_mcp_tools(settings: &crate::engine_setup::AgentSettings) {
let enabled: Vec<_> = mcp_command_servers(settings).into_iter().filter(|s| s.enabled).collect();
if enabled.is_empty() {
outln!("No enabled MCP servers. Add one with `luxe mcp add`.");
return;
}
for server in &enabled {
print_server_tools(server).await;
}
}
/// Connect to one server, list its tools, and print them (namespaced). Best-effort:
/// connection failures are reported, not fatal.
///
/// Both transports, over the same [`McpConnection`](luxe_core::mcp_client::McpConnection) the
/// engine uses, so a remote server the runtime connects to is listed too. A listing that disagrees
/// with the runtime is worse than no listing: it reads as "this will not work".
pub(crate) async fn print_server_tools(server: &luxe_core::mcp_client::McpServerConfig) {
let connect =
tokio::time::timeout(std::time::Duration::from_secs(15), luxe_mcp::connect(server)).await;
let client = match connect {
Ok(Ok(c)) => c,
Ok(Err(e)) => {
outln!("{}: failed to connect — {e}", server.id);
return;
}
Err(_) => {
outln!("{}: timed out connecting", server.id);
return;
}
};
match client.list_tools().await {
Ok(tools) => out!("{}", server_tools_listing(server, &tools)),
Err(e) => outln!("{}: failed to list tools — {e}", server.id),
}
}
/// What `luxe mcp tools` prints for one server: each tool the agent can call, by the name a
/// permission rule matches (`asana/create_task`), and how many `exclude_tools` hides.
///
/// Never a flattened `mcp_asana_create_task`, a name nothing else uses — a rule copied from the
/// listing would never match. Hidden tools are counted rather than listed: the reader chose them,
/// and the listing is for what is left.
fn server_tools_listing(
server: &luxe_core::mcp_client::McpServerConfig,
tools: &[luxe_core::mcp_client::McpTool],
) -> String {
use std::fmt::Write as _;
let excluded = |name: &str| server.exclude_tools.iter().any(|hidden| hidden == name);
let callable: Vec<_> = tools.iter().filter(|tool| !excluded(&tool.name)).collect();
let hidden = match tools.len() - callable.len() {
0 => String::new(),
count => format!("; {count} more hidden by exclude_tools"),
};
let mut out = match callable.len() {
0 => format!("{}: (no tools{hidden})\n", server.id),
1 => format!("{} (1 tool{hidden}):\n", server.id),
count => format!("{} ({count} tools{hidden}):\n", server.id),
};
for tool in callable {
let _ = writeln!(out, " {}/{} — {}", server.id, tool.name, tool.description);
}
out
}
/// List resumable sessions for the current project (newest first).
pub(crate) async fn run_sessions_command(
cmd: SessionsCommand,
settings: crate::engine_setup::AgentSettings,
) -> anyhow::Result<()> {
use luxe_core::message::{ContentBlock, Role};
use luxe_core::session::{EntryKind, SessionStore};
match cmd {
SessionsCommand::List => {
let store = crate::engine_setup::open_session_store(&settings.state_root);
let ids = store.list_sessions();
if ids.is_empty() {
outln!("No sessions yet for this project. Start one with `luxe`.");
return Ok(());
}
// Gather (mtime, id, message count, first-user-message snippet) per session.
let mut rows: Vec<(std::time::SystemTime, String, usize, String)> = Vec::new();
for id in &ids {
let mtime = store
.session_path(id)
.and_then(|p| p.metadata().ok()?.modified().ok())
.unwrap_or(std::time::UNIX_EPOCH);
let entries = store.load(id).unwrap_or_default();
let msg_count =
entries.iter().filter(|e| matches!(&e.kind, EntryKind::Message(_))).count();
let snippet = entries
.iter()
.find_map(|e| match &e.kind {
EntryKind::Message(m) if m.role == Role::User => {
m.content.iter().find_map(|b| match b {
ContentBlock::Text(t) if !t.trim().is_empty() => Some(t.clone()),
_ => None,
})
}
_ => None,
})
.unwrap_or_else(|| "(no messages)".to_string());
rows.push((mtime, id.0.clone(), msg_count, first_line(&snippet, 60)));
}
rows.sort_by_key(|r| std::cmp::Reverse(r.0)); // newest first
outln!("Sessions for this project ({}):", rows.len());
for (_, id, count, snippet) in rows {
outln!(" {id} ({count} msgs) {snippet}");
}
outln!("\nResume with `luxe --resume <id>` or the most recent with `luxe -c`.");
}
}
Ok(())
}
/// A stdio server's transport from `--command`, split the way the platform's shell would, so a
/// quoted argument with a space in it stays one argument.
fn stdio_transport(command: &str) -> anyhow::Result<luxe_core::mcp_client::McpTransport> {
// A backslash is an escape to a POSIX shell and a path separator on Windows
let split = if cfg!(windows) { split_quoted(command) } else { shlex::split(command) };
let mut parts = split
.ok_or_else(|| anyhow::anyhow!("--command has an unclosed quote: {command}"))?
.into_iter();
let program = parts.next().ok_or_else(|| anyhow::anyhow!("--command must not be empty"))?;
Ok(luxe_core::mcp_client::McpTransport::Stdio {
command: program,
args: parts.collect(),
cwd: None,
env: Default::default(),
})
}
/// `command` split on whitespace outside double quotes, the way Windows reads a command line, with
/// every other character as written; `None` for an unclosed quote.
fn split_quoted(command: &str) -> Option<Vec<String>> {
let (mut words, mut word, mut quote, mut started) = (Vec::new(), String::new(), None, false);
for c in command.chars() {
match (quote, c) {
(None, '"') => (quote, started) = (Some(c), true),
(Some(open), c) if c == open => quote = None,
(None, c) if c.is_whitespace() => {
if std::mem::take(&mut started) {
words.push(std::mem::take(&mut word));
}
}
(_, c) => (word, started) = (word + &c.to_string(), true),
}
}
if started {
words.push(word);
}
quote.is_none().then_some(words)
}
/// Points a loop's engine at the threshold it compacts at, returning it in percent for the banner
/// and the loop state.
///
/// Only a flag, or nothing configured, overrides: a configured `compaction.at` reaches the engine
/// as written, rather than rounded through a percentage.
fn tune_for_loop(settings: &mut crate::engine_setup::AgentSettings, flag: Option<u8>) -> u8 {
let configured = luxe_core::config::Config::load(&settings.state_root).compaction.at;
let (compact_at, percent) = loop_compaction(flag, configured);
settings.compact_at = compact_at;
percent
}
/// `--compact-percent`, else your `compaction.at`, else 75%: the override the engine needs, if any,
/// and the threshold in percent.
fn loop_compaction(flag: Option<u8>, configured: Option<f64>) -> (Option<f64>, u8) {
match (flag, configured.filter(|at| *at > 0.0 && *at <= 1.0)) {
(Some(percent), _) => (Some(f64::from(percent) / 100.0), percent),
(None, Some(at)) => (None, (at * 100.0).round() as u8),
(None, None) => (Some(0.75), 75),
}
}
/// First line of `s`, truncated to `max` chars with an ellipsis when longer.
pub(crate) fn first_line(s: &str, max: usize) -> String {
let line = s.lines().next().unwrap_or("").trim();
if line.chars().count() > max {
let truncated: String = line.chars().take(max).collect();
format!("{truncated}\u{2026}")
} else {
line.to_string()
}
}
#[cfg(test)]
mod tests {
use luxe_core::mcp_client::{McpServerConfig, McpTool};
/// A quoted argument is one argument, the way the shell that typed it meant.
///
/// The break this catches: the command was split on every space, so `--command 'node "my
/// server.js"'` started `node` with `"my` and `server.js"`.
#[test]
fn a_quoted_mcp_command_argument_stays_whole() {
let transport = super::stdio_transport(r#"node "my server.js" --port 3"#).unwrap();
let luxe_core::mcp_client::McpTransport::Stdio { command, args, .. } = transport else {
panic!("a stdio transport")
};
assert_eq!(command, "node");
assert_eq!(args, ["my server.js", "--port", "3"]);
assert!(super::stdio_transport(r#"node "unclosed"#).is_err());
assert!(super::stdio_transport(" ").is_err());
}
/// On Windows a backslash is a path, not an escape, and quotes still group.
///
/// The break this catches: the POSIX splitter read `C:\tools\server.exe` as `C:toolsserver.exe`.
#[test]
fn a_windows_command_keeps_its_backslashes() {
let split = super::split_quoted(r#"C:\tools\server.exe --root "C:\My Files" "" x"#);
assert_eq!(split.unwrap(), [r"C:\tools\server.exe", "--root", r"C:\My Files", "", "x"]);
let apostrophe = super::split_quoted(r"C:\Users\O'Brien\srv.exe --stdio");
assert_eq!(apostrophe.unwrap(), [r"C:\Users\O'Brien\srv.exe", "--stdio"]);
assert_eq!(super::split_quoted(r#"a "b"#), None);
}
/// On Windows, `--command` goes through the Windows splitter, backslashes and all.
#[cfg(windows)]
#[test]
fn a_windows_mcp_command_keeps_its_path() {
let transport = super::stdio_transport(r"C:\tools\server.exe --stdio").unwrap();
let luxe_core::mcp_client::McpTransport::Stdio { command, .. } = transport else {
panic!("a stdio transport")
};
assert_eq!(command, r"C:\tools\server.exe");
}
/// The flag wins, then your own threshold as written, then the documented 75%.
///
/// The break this catches: `--compact-percent` only decided when a "wrap up" note was added to
/// every steer, and the engine compacted at its own threshold whatever it said.
#[test]
fn a_loop_compacts_at_the_flag_then_the_config_then_75() {
assert_eq!(super::loop_compaction(Some(40), Some(0.25)), (Some(0.4), 40));
assert_eq!(super::loop_compaction(None, Some(0.25)), (None, 25));
assert_eq!(super::loop_compaction(None, None), (Some(0.75), 75));
assert_eq!(super::loop_compaction(None, Some(7.5)), (Some(0.75), 75), "out of range");
}
/// The loop's settings carry the threshold to the engine they build.
#[test]
fn the_loop_s_settings_carry_its_compaction_threshold() {
let _guard = crate::engine_setup::test_env::ENV_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let project = tempfile::tempdir().unwrap();
let mut settings = crate::engine_setup::AgentSettings::resolve(
project.path().to_path_buf(),
crate::engine_setup::CliOverrides::default(),
);
assert_eq!(super::tune_for_loop(&mut settings, Some(30)), 30);
assert_eq!(settings.compact_at, Some(0.3));
}
fn tool(name: &str) -> McpTool {
McpTool {
server_id: "asana".into(),
name: name.into(),
description: format!("does {name}"),
input_schema: serde_json::Value::Null,
}
}
/// The listing names each tool the way a permission rule matches it, leaves out what
/// `exclude_tools` hides, and says how many that was.
#[test]
fn the_listing_uses_the_names_rules_match_and_counts_what_is_hidden() {
let server = McpServerConfig {
id: "asana".into(),
exclude_tools: vec!["log_widget_event".into()],
..Default::default()
};
let tools = [tool("get_tasks"), tool("create_tasks"), tool("log_widget_event")];
assert_eq!(
super::server_tools_listing(&server, &tools),
"asana (2 tools; 1 more hidden by exclude_tools):\n asana/get_tasks — does \
get_tasks\n asana/create_tasks — does create_tasks\n"
);
let open = McpServerConfig { id: "asana".into(), ..Default::default() };
assert_eq!(
super::server_tools_listing(&open, &tools[..1]),
"asana (1 tool):\n asana/get_tasks — does get_tasks\n"
);
assert_eq!(
super::server_tools_listing(&server, &tools[2..]),
"asana: (no tools; 1 more hidden by exclude_tools)\n"
);
}
}

View File

@@ -0,0 +1,214 @@
//! `luxe docs` — the user guide, read from inside the binary.
//!
//! The guide ships in the binary, so it works offline and always describes the version installed:
//! `scripts/guide-bundle.sh` writes every page of `docs/guide/` into `src/guide.md`, and this reads
//! that bundle. The agent is told the command exists, so asking Luxe how to configure Luxe gets an
//! answer from the manual rather than a guess.
use crate::cli::args::DocsArgs;
/// Every page of `docs/guide/`, as `scripts/guide-bundle.sh` wrote them.
const BUNDLE: &str = include_str!("../guide.md");
/// The sidebar's groups, in reading order. `web/src/content.config.ts` holds the same list.
const GROUPS: [&str; 5] = ["Get started", "Using Luxe", "Customize", "Extend", "Reference"];
/// The most lines `--search` prints, so a common word cannot flood a tool result.
const SEARCH_LIMIT: usize = 40;
/// One page of the guide.
#[derive(Debug)]
struct Page {
id: String,
title: String,
summary: String,
group: String,
order: u32,
body: String,
}
/// The guide's pages, in reading order: group by group, then by `order`.
fn pages() -> Vec<Page> {
let mut pages: Vec<Page> = BUNDLE
.split("\n@@@ page: ")
.skip(1)
.filter_map(|chunk| {
let (id, text) = chunk.split_once('\n')?;
let rest = text.strip_prefix("---\n")?;
let (frontmatter, body) = rest.split_once("\n---\n")?;
let field = |name: &str| {
frontmatter
.lines()
.find_map(|line| line.strip_prefix(&format!("{name}:")))
.map(|value| value.trim().trim_matches('"').to_string())
.unwrap_or_default()
};
Some(Page {
id: id.trim().to_string(),
title: field("title"),
summary: field("summary"),
group: field("group"),
order: field("order").parse().unwrap_or(u32::MAX),
body: body.trim().to_string(),
})
})
.collect();
let rank =
|page: &Page| GROUPS.iter().position(|group| *group == page.group).unwrap_or(GROUPS.len());
pages.sort_by_key(|page| (rank(page), page.order));
pages
}
/// Runs `luxe docs`: the list of pages, one page, or a search across all of them.
pub(crate) fn run(args: &DocsArgs) -> anyhow::Result<()> {
let pages = pages();
let output = match (&args.page, &args.search) {
(_, Some(query)) => search(&pages, query),
(Some(id), None) => page(&pages, id)?,
(None, None) => index(&pages),
};
crate::output::write(&output);
Ok(())
}
/// Every page, under its group, with its summary and how to read it.
fn index(pages: &[Page]) -> String {
let mut out = String::from(
"Luxe's user guide, for this version. `luxe docs <page>` prints a page; \
`luxe docs --search <words>` finds lines across all of them.\n",
);
for group in GROUPS {
out.push_str(&format!("\n{group}\n"));
for page in pages.iter().filter(|page| page.group == group) {
out.push_str(&format!(" {:<18} {}\n", page.id, page.summary));
}
}
out
}
/// One page as markdown: its title, its summary, then its body.
fn page(pages: &[Page], id: &str) -> anyhow::Result<String> {
let id = id.trim().trim_end_matches(".md");
let found = pages.iter().find(|page| page.id == id || page.title.eq_ignore_ascii_case(id));
match found {
Some(page) => Ok(format!("# {}\n\n> {}\n\n{}\n", page.title, page.summary, page.body)),
None => {
let close: Vec<&str> = pages
.iter()
.filter(|page| page.id.contains(id) || id.contains(page.id.as_str()))
.map(|page| page.id.as_str())
.collect();
let hint = if close.is_empty() {
"`luxe docs` lists every page".to_string()
} else {
format!("did you mean {}?", close.join(", "))
};
anyhow::bail!("no page named `{id}`: {hint}")
}
}
}
/// Lines across every page that contain all the words of `query`, case-insensitively.
fn search(pages: &[Page], query: &str) -> String {
let words: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
if words.is_empty() {
return index(pages);
}
let mut hits = Vec::new();
for page in pages {
for line in page.body.lines() {
let lower = line.to_lowercase();
if words.iter().all(|word| lower.contains(word.as_str())) {
hits.push(format!("{}: {}", page.id, line.trim()));
}
}
}
let total = hits.len();
match total {
0 => format!("Nothing in the guide matches `{query}`. `luxe docs` lists every page."),
_ => {
hits.truncate(SEARCH_LIMIT);
let mut out = hits.join("\n");
if total > SEARCH_LIMIT {
out.push_str(&format!(
"\n… {} more. Narrow the search, or read a page with `luxe docs <page>`.",
total - SEARCH_LIMIT
));
}
out.push('\n');
out
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The bundle is the guide: the same pages, byte for byte. Run `scripts/guide-bundle.sh` after
/// editing a page.
#[test]
fn the_bundle_matches_the_guide() {
let guide = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/guide");
let mut names: Vec<String> = std::fs::read_dir(&guide)
.expect("docs/guide")
.filter_map(Result::ok)
.map(|entry| entry.file_name().to_string_lossy().into_owned())
.filter(|name| name.ends_with(".md"))
.collect();
names.sort();
let mut expected = String::from(
"<!-- Generated by scripts/guide-bundle.sh from docs/guide/. Edit the guide, not this file. -->\n",
);
for name in names {
expected.push_str(&format!("@@@ page: {}\n", name.trim_end_matches(".md")));
expected.push_str(&std::fs::read_to_string(guide.join(&name)).expect("a page"));
}
assert!(
BUNDLE == expected,
"src/guide.md is out of date with docs/guide/: run scripts/guide-bundle.sh"
);
}
#[test]
fn every_page_is_read_with_its_frontmatter() {
let pages = pages();
assert!(pages.len() > 20, "{} pages", pages.len());
for page in &pages {
assert!(!page.title.is_empty() && !page.summary.is_empty(), "{}", page.id);
assert!(
GROUPS.contains(&page.group.as_str()),
"{} has group {:?}",
page.id,
page.group
);
assert!(!page.body.starts_with("---"), "{} kept its frontmatter", page.id);
}
assert_eq!(pages[0].id, "index", "the overview leads");
}
#[test]
fn a_page_is_found_by_id_or_title_and_a_miss_says_what_to_try() {
let pages = pages();
assert!(page(&pages, "install").unwrap().starts_with("# Install\n"));
assert!(page(&pages, "install.md").is_ok());
assert!(page(&pages, "Git and GitHub").unwrap().contains("worktree"));
let miss = page(&pages, "hook").unwrap_err().to_string();
assert!(miss.contains("hooks"), "{miss}");
assert!(page(&pages, "zzz").unwrap_err().to_string().contains("luxe docs"));
}
#[test]
fn a_search_finds_lines_with_every_word_and_stops_at_the_limit() {
let pages = pages();
let hits = search(&pages, "mcp login");
assert!(hits.lines().any(|line| line.starts_with("mcp: ")), "{hits}");
assert!(hits
.lines()
.all(|line| line.starts_with('…') || line.to_lowercase().contains("login")));
assert!(search(&pages, "qqqzzz").starts_with("Nothing"));
let common = search(&pages, "the");
assert_eq!(common.lines().count(), SEARCH_LIMIT + 1, "capped, with a note");
assert!(index(&pages).contains("Get started\n index"));
}
}

View File

@@ -0,0 +1,247 @@
//! `luxe doctor` — is the tooling on this machine actually going to work?
//!
//! Luxe launches language servers and debug adapters; it does not install them, and it does not
//! bundle them: installation would mean owning each language's package manager and update policy.
//! A broken or absent one can otherwise stay invisible until a tool call comes back empty.
//!
//! This is the answer to "is my setup working", asked from a terminal rather than inferred from a
//! disappointing result. It reports what resolved, which candidate won where a language has more
//! than one, and — for a server that is present and still will not run — the reason.
use crate::output::{out, outln};
use std::fmt::Write as _;
use luxe_lsp::registry::{ServerEntry, ServerRegistry};
/// Run the doctor, printing each section as it is established.
///
/// Streamed rather than assembled: the language-server section actually starts each server, so it
/// is the slow part, and a checkup that prints nothing until it is finished looks exactly like a
/// checkup that has hung — which is the failure mode this command is for.
pub(crate) async fn run_doctor_command(
settings: crate::engine_setup::AgentSettings,
) -> anyhow::Result<()> {
let mut header = String::new();
let _ = writeln!(header, "luxe {}", env!("CARGO_PKG_VERSION"));
let _ = writeln!(header, " project {}", settings.state_root.display());
let _ = match &settings.model {
Some(model) => writeln!(header, " model {}", model.r#ref),
None => writeln!(header, " model none selected"),
};
out!("{header}");
for section in [external_programs(), debug_adapters()] {
outln!();
out!("{section}");
}
outln!();
language_servers().await;
Ok(())
}
/// Every language in the registry, and which of its candidates is usable.
///
/// Each is actually **started**, not merely resolved. Resolution is the check that produced the
/// bug this command exists to catch: `typescript-language-server` is on `PATH` in a TypeScript 7
/// project and fails its handshake every time, so a report of "ok" would repeat the lie rather
/// than expose it. Cheap now that a server which refuses says so immediately.
async fn language_servers() {
/// Print a line and get it on screen now: each language costs a real handshake, so a report
/// that arrives all at once looks like one that has stalled.
fn say(line: &str) {
outln!("{line}");
}
say("Language servers");
// The registry a session builds, not the shipped defaults alone: a server added in
// `lsp-servers.json` is exactly the one somebody runs the checkup to confirm.
let mut registry = ServerRegistry::new();
let user = crate::engine_setup::read_lsp_servers().unwrap_or_else(|error| {
say(&format!(" FAIL lsp-servers.json is not valid, so none of it applies: {error}"));
Default::default()
});
let configured: std::collections::HashSet<String> = user.keys().cloned().collect();
for language in registry.merge_patches(user) {
say(&format!(
" FAIL {language:<12} lsp-servers.json gives no `command`, and Luxe ships none"
));
}
let mut languages: Vec<(&String, &ServerEntry)> = registry.iter().collect();
languages.sort_by_key(|(language, _)| language.as_str());
for (language, entry) in languages {
// Each language costs a real handshake, so a reader who has stopped — `luxe doctor | head`
// — should not be waited on by a report nobody will see.
if !crate::output::is_open() {
return;
}
let (working, refusals, absent) = probe_language(language, entry).await;
let origin = if configured.contains(language) { " (lsp-servers.json)" } else { "" };
match working {
Some(invocation) => {
say(&format!(" ok {language:<12} {invocation}{origin}"));
// A candidate that refused before the working one is still worth naming: it is
// usually the one the user thinks they are running.
for refusal in &refusals {
say(&format!(" (skipped {refusal})"));
}
}
None if refusals.is_empty() => {
// Naming every candidate matters where a language has more than one: "install
// typescript-language-server" is wrong advice for a TypeScript 7 project.
say(&format!(" none {language:<12} tried: {}{origin}", absent.join(", ")));
if let Some(hint) = &entry.install_hint {
say(&format!(" {hint}"));
}
}
None => {
say(&format!(" FAIL {language:<12} installed, but will not start{origin}"));
for refusal in &refusals {
say(&format!(" {refusal}"));
}
if let Some(hint) = &entry.install_hint {
say(&format!(" {hint}"));
}
}
}
}
}
/// Try each of a language's candidates, returning the first that works plus what the others said.
///
/// Args: `(language, entry)`; returns `(working_invocation, refusals, absent)`.
async fn probe_language(
language: &str,
entry: &ServerEntry,
) -> (Option<String>, Vec<String>, Vec<String>) {
let mut refusals = Vec::new();
let mut absent = Vec::new();
for candidate in entry.candidates() {
let Some(program) = luxe_core::program::resolve(&candidate.command) else {
absent.push(candidate.command.clone());
continue;
};
let invocation = std::iter::once(candidate.command.clone())
.chain(candidate.args.iter().cloned())
.collect::<Vec<_>>()
.join(" ");
let mut command = vec![program.to_string_lossy().into_owned()];
command.extend(candidate.args.clone());
let mut client = luxe_lsp::LspClient::new(luxe_lsp::client::LspConfig {
command,
server_id: language.to_string(),
root_path: std::env::current_dir().unwrap_or_else(|_| ".".into()),
init_timeout: HANDSHAKE_BUDGET,
});
match client.initialize().await {
Ok(()) => return (Some(invocation), refusals, absent),
Err(error) => refusals.push(format!("{invocation}: {error}")),
}
}
(None, refusals, absent)
}
/// How long a server gets to answer `initialize` during a checkup.
///
/// Shorter than a real session's budget on purpose: this is a report, and a server too slow to
/// greet in five seconds is itself worth reporting.
const HANDSHAKE_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
/// Every debug adapter a session can use — built-in and configured — and whether it is here.
fn debug_adapters() -> String {
let mut out = String::from("Debug adapters\n");
let user = crate::engine_setup::read_debug_adapters().unwrap_or_else(|error| {
let _ = writeln!(
out,
" FAIL debug-adapters.json is not valid, so none of it applies: {error}"
);
Vec::new()
});
for (adapter, from_config) in crate::engine_setup::merged_debug_adapters(&user) {
let program = adapter.spec.command.first().cloned().unwrap_or_default();
let state = match luxe_core::program::resolve(&program).is_some() {
true => "ok ",
false => "none ",
};
let origin = if from_config { " (debug-adapters.json)" } else { "" };
let _ = writeln!(
out,
" {state} {:<12} {}{origin}",
adapter.spec.id,
adapter.spec.command.join(" ")
);
}
let _ = writeln!(out, " (`debug` is offered to the model only where an adapter resolves)");
out
}
/// The external programs the tools prefer, and what happens without each.
fn external_programs() -> String {
/// Program, what wants it, and what absence costs.
const PROGRAMS: &[(&str, &str, &str)] = &[
("ast-grep", "ast_grep", "the tool is unavailable; grep is the substitute"),
("git", "git", "the tool is unavailable"),
("gh", "git (pull requests)", "PR actions are unavailable"),
];
let mut out = String::from("External programs\n");
for (program, wanted_by, without) in PROGRAMS {
match luxe_core::program::resolve(program).is_some() {
true => {
let _ = writeln!(out, " ok {program:<10} {wanted_by}");
}
false => {
let _ = writeln!(out, " none {program:<10} {wanted_by} — {without}");
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
/// The checkup finishes.
///
/// It starts real language servers, which is the point and also the risk: a checkup that prints
/// every line of its report and then does not come down was seen once and never reproduced
/// after the probe moved into its own function, so the cause is **not known**. The property is
/// asserted directly rather than assumed, and this is what will catch it coming back.
///
/// Bounded well above the ~0.4s a six-language checkup actually costs on a developer box, so a
/// slow CI runner cannot make it flaky; a hang is unbounded and fails it regardless.
#[tokio::test]
async fn the_checkup_terminates() {
let registry = ServerRegistry::new();
let started = std::time::Instant::now();
for (language, entry) in registry.iter() {
let (_working, _refusals, _absent) = probe_language(language, entry).await;
}
let elapsed = started.elapsed();
assert!(
elapsed < std::time::Duration::from_secs(90),
"probing every language took {elapsed:?}; a checkup that does not finish is worse \
than no checkup"
);
}
/// Every language reports one of the three states, and a language with alternatives names
/// them all when none is present — "install typescript-language-server" is wrong advice for a
/// TypeScript 7 project.
#[test]
fn a_language_with_alternatives_names_all_of_them() {
let registry = ServerRegistry::new();
let typescript = registry.get("typescript").expect("typescript is a built-in");
let candidates: Vec<String> =
typescript.candidates().into_iter().map(|candidate| candidate.command).collect();
assert!(candidates.len() > 1, "typescript needs a fallback: {candidates:?}");
assert_eq!(candidates.first().map(String::as_str), Some("typescript-language-server"));
assert!(
candidates.iter().any(|command| command == "tsgo" || command == "tsc"),
"the native TypeScript 7 server has to be reachable: {candidates:?}"
);
}
}

View File

@@ -0,0 +1,281 @@
//! Headless (non-interactive) execution — single-prompt runs with streamed text or a JSONL
//! event stream for scripts and benchmarks.
use super::args::OutputFormat;
use super::tui::shutdown_workspace_services;
use crate::output::{out, outln};
/// Run headless mode: drive a single prompt through the engine to completion, rendering the
/// event stream in the requested `format` (streamed text, or a JSONL event stream with usage).
pub(crate) async fn run_headless(
prompt: &str,
settings: crate::engine_setup::AgentSettings,
format: OutputFormat,
) -> anyhow::Result<()> {
use luxe_core::engine::Action;
// A one-shot run has nobody to ask, so it says what is missing instead of starting an engine
// that would refuse the turn a moment later. The interactive front-ends do the opposite: they
// open, and choosing a model is one of the things you do there.
settings.require_model()?;
let crate::engine_setup::EngineHandle {
actions: engine_tx, events: mut event_rx, closer, ..
} = crate::engine_setup::build_engine(
&settings,
luxe_core::HookRegistry::new(),
// Nobody to prompt, so every `ask` collapses to one answer — `--on-ask`, allow unless the
// run asked to refuse. A `deny` rule is enforced either way.
settings.unattended_ask(),
)
.await?;
if let Some(level) = settings.initial_thinking {
engine_tx
.send(Action::SetThinkingLevel(level))
.await
.map_err(|e| anyhow::anyhow!("engine channel closed: {e}"))?;
}
engine_tx
.send(Action::SubmitUserMessage {
content: prompt.to_string(),
images: vec![],
remediation: None,
})
.await
.map_err(|e| anyhow::anyhow!("engine channel closed: {e}"))?;
let outcome = match format {
OutputFormat::Text => stream_headless_text(&mut event_rx).await,
OutputFormat::Json => stream_headless_json(&mut event_rx).await,
};
closer.close(&engine_tx).await;
// A one-shot headless run must terminate promptly: gracefully shut down the warm LSP/DAP
// servers (diagnostics-on-edit spawns rust-analyzer) so their child processes + reader tasks
// don't keep the runtime alive after the turn (the TUI does the equivalent on quit).
shutdown_workspace_services().await;
finish(outcome)
}
/// How a headless turn ended, which is what the process's exit status says.
#[derive(Debug)]
pub(crate) enum TurnOutcome {
/// The turn ended, however it ended, or the reader stopped listening
Finished,
/// The engine reported an error, already printed
Failed(String),
/// The engine went away before the turn ended
Disconnected,
}
/// A failure the run has already printed, so the process exits 1 without saying it again.
#[derive(Debug)]
pub(crate) struct AlreadyReported(String);
impl std::fmt::Display for AlreadyReported {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for AlreadyReported {}
/// The run's result for `outcome`: only a finished turn is a success.
fn finish(outcome: TurnOutcome) -> anyhow::Result<()> {
match outcome {
TurnOutcome::Finished => Ok(()),
TurnOutcome::Failed(message) => Err(AlreadyReported(message).into()),
TurnOutcome::Disconnected => anyhow::bail!("the engine stopped before the turn ended"),
}
}
/// Human-friendly headless rendering: assistant text to stdout, tool activity to stderr.
pub(crate) async fn stream_headless_text(
event_rx: &mut tokio::sync::mpsc::Receiver<luxe_core::event::Event>,
) -> TurnOutcome {
use luxe_core::event::Event;
while let Some(event) = event_rx.recv().await {
// A reader that stopped — `luxe --headless -p ... | head -1` — ends the run here rather
// than driving a whole turn into a closed pipe.
if !crate::output::is_open() {
return TurnOutcome::Finished;
}
match event {
Event::TokenDelta { delta, .. } => out!("{delta}"),
// Same rule the TUI follows: our own registry bookkeeping is not progress anyone
// asked to watch. The `json` stream below is a machine's view and keeps every event.
Event::ToolStarted { name, .. } if !luxe_core::activity::is_bookkeeping(&name) => {
eprintln!("\n[tool: {name}]");
}
Event::ToolEnded { is_error, .. } if is_error => eprintln!("[tool failed]"),
Event::Notice(msg) => eprintln!("\n[{msg}]"),
Event::ProviderRetrying { attempt, attempts, reason } => {
eprintln!("\n[retrying ({attempt}/{attempts}): {reason}]");
}
Event::Error(msg) => {
eprintln!("\nerror: {msg}");
return TurnOutcome::Failed(msg);
}
Event::TurnEnded { .. } => {
outln!();
return TurnOutcome::Finished;
}
_ => {}
}
}
TurnOutcome::Disconnected
}
/// Machine-readable headless rendering: one JSON object per line (JSONL). Emits assistant
/// messages, tool start/end, per-provider-call `usage`, and a terminal `turn_end`/`error`.
/// Consumed by scripts, harness adapters, and the benchmark rig. `usage` carries what the provider
/// reported for one call (input, output, cache read and write, reasoning); sum the `usage` events
/// across a turn for the total.
pub(crate) async fn stream_headless_json(
event_rx: &mut tokio::sync::mpsc::Receiver<luxe_core::event::Event>,
) -> TurnOutcome {
use luxe_core::event::Event;
while let Some(event) = event_rx.recv().await {
if !crate::output::is_open() {
return TurnOutcome::Finished;
}
if let Some(value) = headless_json_event(&event) {
outln!("{value}");
}
// Error/TurnEnded are terminal: their line is out, and nothing after them is read
match event {
Event::Error(message) => return TurnOutcome::Failed(message),
Event::TurnEnded { .. } => return TurnOutcome::Finished,
_ => {}
}
}
TurnOutcome::Disconnected
}
/// Map one engine `Event` to its headless-JSON line, or `None` for events we don't surface.
///
/// Pure (no IO) so the JSONL contract is unit-testable without a live engine. `usage` carries
/// exactly what the provider reported for one call; consumers sum them across a turn.
pub(crate) fn headless_json_event(event: &luxe_core::event::Event) -> Option<serde_json::Value> {
use luxe_core::event::Event;
use luxe_core::message::{ContentBlock, Role};
match event {
Event::MessageCommitted { message, .. } if message.role == Role::Assistant => {
let text: String = message
.content
.iter()
.filter_map(|b| match b {
ContentBlock::Text(t) => Some(t.as_str()),
_ => None,
})
.collect();
let tool_calls: Vec<&str> = message
.content
.iter()
.filter_map(|b| match b {
ContentBlock::ToolCall { name, .. } => Some(name.as_str()),
_ => None,
})
.collect();
Some(serde_json::json!({
"type": "message", "role": "assistant", "text": text, "tool_calls": tool_calls,
}))
}
Event::ToolStarted { call_id, name } => {
Some(serde_json::json!({"type": "tool_start", "call_id": call_id, "name": name}))
}
Event::ToolEnded { call_id, is_error } => {
Some(serde_json::json!({"type": "tool_end", "call_id": call_id, "is_error": is_error}))
}
Event::TurnUsage {
prompt_tokens,
completion_tokens,
cost_usd,
cache_read_tokens,
cache_write_tokens,
reasoning_tokens,
source,
} => Some(serde_json::json!({
"type": "usage",
"input": prompt_tokens,
"output": completion_tokens,
"total": prompt_tokens + completion_tokens,
"cost_usd": cost_usd,
"cache_read": cache_read_tokens,
"cache_write": cache_write_tokens,
"reasoning": reasoning_tokens,
"source": source.label(),
})),
// What the subscription has left, when the provider says. Scripts watching a plan need
// this more than they need a dollar equivalent.
Event::PlanUsage(plan) => Some(serde_json::json!({
"type": "plan_usage",
"plan": plan.plan,
"summary": plan.summary(),
"primary_used_percent": plan.primary.map(|window| window.used_percent),
"primary_window_minutes": plan.primary.map(|window| window.window_minutes),
"primary_resets_in_secs": plan.primary.and_then(|window| window.resets_in_secs),
"secondary_used_percent": plan.secondary.map(|window| window.used_percent),
"credits_balance": plan.credits_balance,
})),
// The running total, so a script does not have to re-derive one from the per-call lines
Event::SessionUsage(usage) => Some(serde_json::json!({
"type": "session_usage",
"calls": usage.total.calls,
"input": usage.total.prompt_tokens,
"output": usage.total.completion_tokens,
"cache_read": usage.total.cache_read_tokens,
"cache_write": usage.total.cache_write_tokens,
"reasoning": usage.total.reasoning_tokens,
"cost_usd": usage.total.cost_usd,
"unpriced_calls": usage.total.unpriced_calls,
// Subscription usage is reported separately from spend: `cost_usd` is money charged,
// `plan_usd` is what plan-billed tokens would have cost on the API.
"plan_usd": usage.total.plan_usd,
"plan_calls": usage.total.plan_calls,
"by_source": usage
.by_source
.iter()
.map(|entry| serde_json::json!({
"source": entry.source.label(),
"calls": entry.totals.calls,
"input": entry.totals.prompt_tokens,
"output": entry.totals.completion_tokens,
"cost_usd": entry.totals.cost_usd,
"plan_usd": entry.totals.plan_usd,
}))
.collect::<Vec<_>>(),
})),
Event::Notice(msg) => Some(serde_json::json!({"type": "notice", "message": msg})),
Event::ProviderRetrying { attempt, attempts, reason } => Some(serde_json::json!({
"type": "retrying",
"attempt": attempt,
"attempts": attempts,
"reason": reason,
})),
Event::Error(msg) => Some(serde_json::json!({"type": "error", "message": msg})),
Event::TurnEnded { reason } => {
Some(serde_json::json!({"type": "turn_end", "reason": turn_end_reason(reason)}))
}
_ => None,
}
}
/// The `reason` field of a `turn_end` line.
///
/// `EndTurn` and `ToolCall` keep the spelling scripts already parse; an `Other` reason is
/// unwrapped to the reason itself rather than rendered as `Other("cancelled")`, which is what
/// `{:?}` produces and no reader wants in a JSON field. A turn reports why it *actually* stopped.
fn turn_end_reason(reason: &luxe_core::event::StopReason) -> String {
match reason {
luxe_core::event::StopReason::Other(reason) => reason.clone(),
named => format!("{named:?}"),
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,45 @@
use luxe_core::event::{Event, StopReason};
use super::*;
/// A channel holding `events`, closed after them unless `open`.
fn feed(events: Vec<Event>) -> tokio::sync::mpsc::Receiver<Event> {
let (tx, rx) = tokio::sync::mpsc::channel(events.len().max(1));
for event in events {
tx.try_send(event).expect("room for the fixture");
}
rx
}
/// A turn that failed is a failed run, in both formats.
///
/// The break this catches: the error was printed and the run exited 0, so a script calling
/// `luxe -p` could not tell a refused key from an answer without parsing what it printed.
#[tokio::test]
async fn headless_exits_nonzero_on_a_provider_error() {
let failed = || vec![Event::Error("turn error: invalid api key".into())];
let text = stream_headless_text(&mut feed(failed())).await;
assert!(matches!(&text, TurnOutcome::Failed(message) if message.contains("invalid api key")));
let json = stream_headless_json(&mut feed(failed())).await;
assert!(matches!(json, TurnOutcome::Failed(_)));
assert!(finish(text).unwrap_err().is::<AlreadyReported>(), "said once, then exit 1");
}
/// An engine that went away before the turn ended is a failed run too, said as such.
#[tokio::test]
async fn headless_exits_nonzero_when_the_engine_disconnects() {
let outcome = stream_headless_text(&mut feed(vec![Event::Notice("working".into())])).await;
assert!(matches!(outcome, TurnOutcome::Disconnected));
let error = finish(outcome).unwrap_err();
assert!(!error.is::<AlreadyReported>());
assert!(error.to_string().contains("stopped before the turn ended"), "{error}");
}
/// A turn that ended is a run that succeeded, however it ended.
#[tokio::test]
async fn a_finished_turn_exits_zero() {
let ended = vec![Event::TurnEnded { reason: StopReason::EndTurn }];
let outcome = stream_headless_json(&mut feed(ended)).await;
assert!(matches!(outcome, TurnOutcome::Finished));
assert!(finish(outcome).is_ok());
}

View File

@@ -0,0 +1,328 @@
//! `luxe models` — inspect and refresh the model catalog.
//!
//! Exists mostly for one question: *why does Luxe think my model has a 128k window?* `show`
//! answers it directly by printing which layer won each field, so a stale cache, a missing
//! provider mapping, and a forgotten config override are all distinguishable at a glance.
use std::fmt::Write as _;
use luxe_core::provider::ModelInfo;
use luxe_providers::catalog::Layer;
use super::args::ModelsCommand;
use crate::engine_setup::{load_luxe_config, AgentSettings};
use crate::model_catalog;
/// Run a models subcommand.
pub(crate) async fn run_models_command(
cmd: ModelsCommand,
settings: AgentSettings,
) -> anyhow::Result<()> {
let output = match cmd {
ModelsCommand::List { provider, configured } => list(&settings, provider, configured),
ModelsCommand::Show { model } => show(&settings, &model),
ModelsCommand::Refresh { force } => refresh(force).await,
};
crate::output::write(&output);
Ok(())
}
fn list(settings: &AgentSettings, provider: Option<String>, configured_only: bool) -> String {
let menu = model_catalog::build_menu(settings);
// No model chosen means no row is marked, which is the honest answer: nothing here is active.
let active = settings.model.as_ref().map(|model| model.r#ref.to_string()).unwrap_or_default();
let mut rows: Vec<_> = menu
.catalog
.iter()
.filter(|entry| provider.as_deref().is_none_or(|p| entry.info.r#ref.provider == p))
.filter(|entry| !configured_only || entry.configured)
.collect();
// Sort by the id shown rather than the display name the picker sorts on, so the column reads
// in order.
rows.sort_by(|a, b| {
b.configured.cmp(&a.configured).then_with(|| key_of(&a.info).cmp(&key_of(&b.info)))
});
if rows.is_empty() {
let models = luxe_core::user_dirs::config_path_display("models.json");
return format!("No models matched. Configure a provider in {models}.\n");
}
let width = rows.iter().map(|entry| key_of(&entry.info).len()).max().unwrap_or(0);
let mut out = String::new();
for entry in rows {
let key = key_of(&entry.info);
let marker = if key == active {
"*"
} else if entry.configured {
"+"
} else {
" "
};
let row = format!(
"{marker} {key:width$} {:>6} {:>9} {}",
human_tokens(entry.info.context_window),
if entry.info.reasoning { "reasoning" } else { "" },
price(&entry.info),
);
let _ = writeln!(out, "{}", row.trim_end());
}
let _ = writeln!(out, "\n* active + configured in models.json/auth.json");
out
}
fn show(settings: &AgentSettings, model: &str) -> String {
let (provider, id) = match model.split_once('/') {
Some((provider, id)) => (provider.to_string(), id.to_string()),
None => (settings.provider.clone(), model.to_string()),
};
let config = load_luxe_config();
let (info, from) = model_catalog::resolve_model(&config, &provider, &id);
let mut out = String::new();
let mut field = |label: &str, value: String, layer: Layer| {
let _ = writeln!(out, " {label:<16} {value} [{}]", layer.label());
};
if let Some(name) = &info.display_name {
field("name", name.clone(), from.display_name);
}
field("context window", human_tokens(info.context_window), from.context_window);
let max_tokens =
if info.max_tokens == 0 { "(omitted)".to_string() } else { human_tokens(info.max_tokens) };
field("max output", max_tokens, from.max_tokens);
field("reasoning", info.reasoning.to_string(), from.reasoning);
let mut levels: Vec<_> = info
.thinking_level_map
.iter()
.filter(|(_, value)| value.is_some())
.map(|(level, _)| level.as_str())
.collect();
levels.sort_unstable();
let levels = if levels.is_empty() { "(defaults)".to_string() } else { levels.join(", ") };
field("thinking levels", levels, from.thinking_level_map);
// Only when configured, and showing the clamped level rather than the written one: a starting
// level the map marks unsupported is answered here rather than at the first surprising turn.
if let Some(level) = info.default_thinking {
field("thinking default", level.as_str().to_string(), from.default_thinking);
}
// Which dial the provider expects is the difference between a working turn and a 400 on
// Anthropic, so name it here rather than making someone read a rejected request body.
field("thinking control", thinking_control(&info), from.thinking_controls);
// Only when this model shapes its requests differently from its provider — the case that is
// otherwise invisible, since both models on one endpoint answer to the same adapter.
if let Some(model_compat) = &info.compat {
let provider_compat = luxe_providers::config::resolve_provider_compat(
&provider,
config.providers.get(&provider),
);
field("compat", compat_overrides(model_compat, &provider_compat), from.compat);
}
// Only when configured: a sampling recipe is silent on the wire and off-spec sampling looks
// like a bad model rather than a bad request, so "did my min_p land?" needs an answer here.
if !info.sampling_params.is_empty() {
field("sampling", sampling(&info), from.sampling_params);
}
let modalities: Vec<_> =
info.input.iter().map(|modality| format!("{modality:?}").to_lowercase()).collect();
field("modalities", modalities.join(", "), from.input);
field("cost /Mtok", price(&info), from.cost);
if from.fields().iter().all(|(_, layer)| *layer == Layer::Default) {
let models = luxe_core::user_dirs::config_path_display("models.json");
let _ = writeln!(
out,
"\nNothing knows this model — it's running on fallback defaults. Pin it in \
{models}, or run `luxe models refresh` if it shipped recently."
);
}
format!("{provider}/{id}\n{out}")
}
/// The model's sampling recipe as `key=value`, in the order a reader would look for it.
fn sampling(info: &ModelInfo) -> String {
let mut pairs: Vec<String> =
info.sampling_params.iter().map(|(key, value)| format!("{key}={value}")).collect();
pairs.sort();
pairs.join(", ")
}
/// What this model does differently from its provider, as `key=value`.
///
/// A diff rather than the whole set, because the whole set is the provider's block plus these, and
/// the reader's question is which of them this model changed. An empty diff still prints: a block
/// that was read and changed nothing is a different answer from a block that was never read.
fn compat_overrides(
model: &luxe_core::provider::CompatFlags,
provider: &luxe_core::provider::CompatFlags,
) -> String {
let object = |flags: &luxe_core::provider::CompatFlags| match serde_json::to_value(flags) {
Ok(serde_json::Value::Object(map)) => map,
_ => serde_json::Map::new(),
};
let (model, provider) = (object(model), object(provider));
let mut changed: Vec<String> = model
.iter()
.filter(|(key, value)| provider.get(*key) != Some(value))
.map(|(key, value)| match value {
serde_json::Value::String(text) => format!("{key}={text}"),
other => format!("{key}={other}"),
})
.collect();
changed.sort();
match changed.is_empty() {
true => "(same as the provider)".to_string(),
false => changed.join(", "),
}
}
/// How the model expects reasoning to be requested, in the provider's own terms.
///
/// The off switch is named too, because a model that cannot stop thinking answers a request for
/// `off` with reasoning anyway, and "why is this still thinking" deserves an answer here rather
/// than on a bill.
fn thinking_control(info: &ModelInfo) -> String {
let dial = match (info.thinking_controls.effort, info.thinking_controls.budget_tokens) {
(true, true) => "effort + token budget",
(true, false) => "effort (adaptive thinking)",
(false, true) => "token budget (extended thinking)",
(false, false) => "(undeclared)",
};
match info.reasoning && !info.thinking_controls.can_disable {
true => format!("{dial}, never off"),
false => dial.to_string(),
}
}
async fn refresh(force: bool) -> String {
// Deployments first and unconditionally: they are not the catalog's to keep current, and a
// resource's list moves whenever somebody deploys something
let mut report = String::new();
if luxe_providers::auth::ProviderAuth::new().refresh_deployments().await {
report.push_str("Recorded what your Azure resources have deployed.\n");
}
report.push_str(&refresh_catalog(force).await);
report
}
async fn refresh_catalog(force: bool) -> String {
let path = model_catalog::cache_path();
if !force && !model_catalog::cache_is_stale(&path) {
return format!("Cache is current ({} models). Use --force to refetch.\n", cached_len());
}
match model_catalog::refresh(&path).await {
Ok(changed) => {
model_catalog::invalidate_cached_catalog();
let verb = if changed { "updated" } else { "already current" };
format!("models.dev {verb} — {} models cached at {}\n", cached_len(), path.display())
}
// Not fatal: the embedded snapshot still answers every lookup.
Err(error) => format!(
"Refresh failed: {error}\nFalling back to the embedded snapshot ({} models).\n",
luxe_providers::catalog::snapshot().len()
),
}
}
/// Models in the on-disk cache, or in the embedded snapshot when there is none.
fn cached_len() -> usize {
let cached = model_catalog::cached_catalog();
if cached.is_empty() {
luxe_providers::catalog::snapshot().len()
} else {
cached.len()
}
}
fn key_of(info: &ModelInfo) -> String {
format!("{}/{}", info.r#ref.provider, info.r#ref.id)
}
/// `1.0M` / `200k` / `4096` — readable at a glance in a column.
fn human_tokens(tokens: u32) -> String {
match tokens {
0 => "-".to_string(),
t if t >= 1_000_000 => format!("{:.1}M", t as f64 / 1_000_000.0),
t if t >= 10_000 => format!("{}k", t / 1_000),
t => t.to_string(),
}
}
fn price(info: &ModelInfo) -> String {
// On a plan the published rates are what the tokens would have cost elsewhere, so they are
// marked as an equivalent rather than presented as a bill the user will receive.
if info.billing == luxe_core::provider::Billing::Subscription {
return match info.cost.is_known() {
true => format!("plan (≈${:.2}/${:.2})", info.cost.input, info.cost.output),
false => "plan".to_string(),
};
}
if !info.cost.is_known() {
return "-".to_string();
}
format!("${:.2}/${:.2}", info.cost.input, info.cost.output)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn token_counts_read_at_a_glance() {
assert_eq!(human_tokens(1_000_000), "1.0M");
assert_eq!(human_tokens(200_000), "200k");
assert_eq!(human_tokens(4_096), "4096");
assert_eq!(human_tokens(0), "-");
}
/// The row answers "what does this model do differently", not "what are its flags".
///
/// Both halves matter: a diff nobody can read is as useless as no row, and a block that was read
/// and changed nothing has to be distinguishable from one that was never read at all — that is
/// the confusion the row exists to end.
#[test]
fn the_compat_row_names_only_what_the_model_changed() {
use luxe_core::provider::CompatFlags;
let provider = CompatFlags {
thinking_format: Some("openai".into()),
supports_reasoning_effort: true,
supports_developer_role: true,
..Default::default()
};
let model = CompatFlags {
thinking_format: Some("chat_template".into()),
supports_developer_role: false,
..provider.clone()
};
let row = compat_overrides(&model, &provider);
assert_eq!(row, "supports_developer_role=false, thinking_format=chat_template");
// Flags it inherited are not "changes" — the provider's block already says them.
assert!(!row.contains("supports_reasoning_effort"), "{row}");
assert!(!row.contains("max_tokens_field"), "{row}");
assert_eq!(compat_overrides(&provider, &provider), "(same as the provider)");
}
#[test]
fn a_subscription_model_prices_as_plan_rather_than_a_bill() {
let mut info = ModelInfo {
billing: luxe_core::provider::Billing::Subscription,
..ModelInfo::default()
};
assert_eq!(price(&info), "plan");
info.cost.input = 5.0;
info.cost.output = 30.0;
assert_eq!(price(&info), "plan (≈$5.00/$30.00)");
}
#[test]
fn price_is_omitted_when_unknown() {
let mut info = ModelInfo::default();
assert_eq!(price(&info), "-");
info.cost.input = 5.0;
info.cost.output = 25.0;
assert_eq!(price(&info), "$5.00/$25.00");
}
}

View File

@@ -0,0 +1,277 @@
//! RPC front-end mode — the engine's `Action`/`Event` protocol over stdio.
//!
//! One JSON object per line each way: wire actions in on stdin, events out on stdout. A client is
//! a *front-end*, with the authority of the person who launched it — it answers permission prompts
//! rather than having them auto-allowed, and the permission engine stays upstream of everything it
//! can ask for. `docs/guide/rpc.md` is the reference.
//!
//! stdout carries the protocol and nothing else. Diagnostics already go to a file rather than the
//! terminal (the TUI owns the screen), so that holds without any special care here — and
//! `rpc_stdout_carries_only_protocol_frames` keeps it holding.
mod translate;
use luxe_core::engine::Action;
use luxe_core::event::Action as WireAction;
use luxe_core::Event;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
use tokio::sync::mpsc;
use translate::{to_engine_action, CatalogResolver, GithubWrites, ModelResolver, Policy, Rejected};
/// Depth of the channel carrying locally-generated frames (rejections) to the single writer.
///
/// Small on purpose: it holds refusals, and a client producing enough bad lines to fill it is
/// already being told so.
const LOCAL_FRAME_BUFFER: usize = 32;
/// Run the RPC front-end against stdio until the client closes the stream or stdin ends.
///
/// Args: `(settings, github_writes)` — the second is `--github-writes`, which lets the client
/// publish to GitHub unless the session is read-only.
pub(crate) async fn run_rpc(
settings: crate::engine_setup::AgentSettings,
github_writes: bool,
) -> anyhow::Result<()> {
// Before anything is started: a child that shared the protocol's pipe could read frames, and
// on Windows would stall behind the read waiting on the client
let input = luxe_core::program::take_stdin()
.map_err(|error| anyhow::anyhow!("could not take stdin for the protocol: {error}"))?;
let mode = crate::engine_setup::effective_permission_mode(
&settings.state_root,
settings.permission_mode,
settings.trust_project,
);
let policy = Policy {
github_writes: GithubWrites::for_launch(github_writes, mode),
github_sections: luxe_core::config::Config::load(&settings.state_root).github.sections(),
};
let handle = crate::engine_setup::build_engine(
&settings,
luxe_core::HookRegistry::new(),
// A client can answer, unlike headless. Auto-allowing on its behalf would make the
// permission prompt invisible to the one front-end able to show it.
luxe_core::permission::AskResolution::Prompt,
)
.await?;
// Same bridge the TUI runs on, so an RPC client gets workspace snapshots and tool-activity
// cards rather than a thinner stream than the built-in front-end sees.
let events = crate::workspace_runtime::bridge(
handle.events,
crate::workspace_runtime::Roots {
state: settings.state_root.clone(),
work: settings.work_root.clone(),
},
crate::workspace_runtime::pull_request_watch(&settings.work_root),
);
let ready = Event::Ready {
protocol_version: luxe_core::PROTOCOL_VERSION,
luxe_version: env!("CARGO_PKG_VERSION").to_string(),
session_id: handle.session_id.0.clone(),
cwd: settings.work_root.to_string_lossy().into_owned(),
github_writes: policy.github_writes.allowed(),
};
if let Some(level) = settings.initial_thinking {
handle.actions.send(Action::SetThinkingLevel(level)).await.ok();
}
// Walk-away mode from launch, for a client driving a session nobody is watching. The same
// state `set_permission_auto_approve` reaches, so a client can turn it back off.
if settings.auto_approve {
handle.actions.send(Action::SetPermissionAutoApprove(true)).await.ok();
}
serve(
ready,
events,
handle.actions,
tokio::fs::File::from_std(input),
tokio::io::stdout(),
&CatalogResolver,
policy,
)
.await?;
super::tui::shutdown_workspace_services().await;
Ok(())
}
/// Drive one RPC session over an arbitrary duplex.
///
/// Generic over the streams so the protocol — handshake, framing, translation, refusal, shutdown —
/// is exercised end to end in tests without a real stdin, a real terminal, or a live provider.
/// `run_rpc` is this function with stdio and the real catalog plugged in.
async fn serve<R, W>(
ready: Event,
mut events: mpsc::Receiver<Event>,
engine_tx: mpsc::Sender<Action>,
input: R,
mut output: W,
models: &'static (dyn ModelResolver + Sync),
policy: Policy,
) -> anyhow::Result<()>
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin,
{
if !emit(&mut output, &ready).await? {
engine_tx.send(Action::Close).await.ok();
return Ok(());
}
let (local_tx, mut local_rx) = mpsc::channel::<Event>(LOCAL_FRAME_BUFFER);
let reader = tokio::spawn(read_actions(input, engine_tx.clone(), local_tx, models, policy));
// One writer, so a refusal can never interleave with an event mid-line.
//
// The engine's stream ending is what ends the session; the refusal channel merely runs dry
// when the reader stops, and must not take the session with it — the engine is usually still
// finishing a turn at that point.
//
// Refusals keep their order among themselves, and events keep theirs. The two are *not*
// ordered against each other: `select!` takes whichever is ready. Nothing needs them to be — a
// refusal is about the client's own input, not about engine state — and pretending otherwise
// would mean holding one stream up for the other.
let mut refusals_open = true;
loop {
let frame = tokio::select! {
event = events.recv() => match event {
Some(event) => event,
None => break,
},
refusal = local_rx.recv(), if refusals_open => match refusal {
Some(refusal) => refusal,
None => {
refusals_open = false;
continue;
}
},
};
if !emit(&mut output, &frame).await? {
break;
}
}
// The engine's stream has ended, but the reader may have queued refusals the client has not
// been told about. Dropping them would leave someone debugging a frame that vanished without
// a word, so close the channel to stop new ones and write out what is already there.
local_rx.close();
while let Some(refusal) = local_rx.recv().await {
if !emit(&mut output, &refusal).await? {
break;
}
}
reader.abort();
// The engine may already be gone (the client sent `close`); saying so twice is harmless.
engine_tx.send(Action::Close).await.ok();
Ok(())
}
/// Read wire actions until EOF, forwarding what translates and refusing what does not.
///
/// EOF means the client is gone, so the engine is told to close rather than left running behind a
/// stream nobody is reading.
async fn read_actions<R>(
input: R,
engine_tx: mpsc::Sender<Action>,
local_tx: mpsc::Sender<Event>,
models: &'static (dyn ModelResolver + Sync),
policy: Policy,
) where
R: AsyncRead + Unpin,
{
let mut lines = BufReader::new(input).lines();
loop {
let line = match lines.next_line().await {
Ok(Some(line)) => line,
Ok(None) => break,
Err(error) => {
tracing::warn!(%error, "rpc: input read failed");
break;
}
};
if line.trim().is_empty() {
continue;
}
let action = match parse_action(&line, models, &policy) {
Ok(action) => action,
Err(rejected) => {
let refusal =
Event::ActionRejected { kind: rejected.kind, reason: rejected.reason };
if local_tx.send(refusal).await.is_err() {
break;
}
continue;
}
};
let closing = matches!(action, Action::Close);
if engine_tx.send(action).await.is_err() {
break;
}
if closing {
break;
}
}
engine_tx.send(Action::Close).await.ok();
}
/// Parse and translate one inbound line.
///
/// Split out from the read loop so the whole inbound contract — framing, vocabulary, translation —
/// is testable without any IO at all.
fn parse_action(
line: &str,
models: &(dyn ModelResolver + Sync),
policy: &Policy,
) -> Result<Action, Rejected> {
// Read the envelope before the payload, so a frame that names itself and then fails to
// deserialize is still refused *by name*. Reporting `kind: null` for a `steer_turn` missing its
// text sends the client looking through every frame it wrote instead of the one that was wrong.
let raw: serde_json::Value = serde_json::from_str(line)
.map_err(|error| Rejected { kind: None, reason: error.to_string() })?;
let kind = raw.get("kind").and_then(serde_json::Value::as_str).map(str::to_string);
let wire: WireAction = serde_json::from_value(raw)
.map_err(|error| Rejected { kind, reason: error.to_string() })?;
to_engine_action(wire, models, policy)
}
/// Write one frame, reporting `false` once the client has stopped reading.
///
/// A hangup is how a session ends when the other end is `head` or a closed editor pane, so it
/// resolves to a clean exit rather than an error written to a pipe nobody is holding.
async fn emit<W: AsyncWrite + Unpin>(out: &mut W, event: &Event) -> anyhow::Result<bool> {
match write_frame(out, event).await {
Ok(()) => Ok(true),
Err(error)
if matches!(
error.kind(),
std::io::ErrorKind::BrokenPipe | std::io::ErrorKind::ConnectionReset
) =>
{
tracing::info!("rpc: client closed the stream");
Ok(false)
}
Err(error) => Err(error.into()),
}
}
/// Write one frame and flush it, so a streaming client sees tokens as they arrive.
///
/// A frame that cannot serialize is logged and dropped rather than ending the session: losing one
/// event is recoverable for a client, and a dead stream is not.
async fn write_frame<W: AsyncWrite + Unpin>(out: &mut W, event: &Event) -> std::io::Result<()> {
let line = match serde_json::to_string(event) {
Ok(line) => line,
Err(error) => {
tracing::warn!(%error, "rpc: dropping an event that would not serialize");
return Ok(());
}
};
out.write_all(line.as_bytes()).await?;
out.write_all(b"\n").await?;
out.flush().await?;
Ok(())
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,418 @@
use super::*;
use luxe_core::provider::ModelInfo;
/// A resolver with no dependence on the developer's `models.json`.
struct FixedModels;
impl ModelResolver for FixedModels {
fn resolve(&self, provider: &str, id: &str) -> ModelInfo {
ModelInfo { r#ref: luxe_core::provider::ModelRef::new(provider, id), ..Default::default() }
}
}
fn policy(github_writes: GithubWrites) -> Policy {
Policy { github_writes, github_sections: Vec::new() }
}
fn parse(line: &str) -> Result<Action, Rejected> {
parse_action(line, &FixedModels, &policy(GithubWrites::NotEnabled))
}
/// A well-formed frame becomes the engine action it names.
#[test]
fn a_good_line_translates() {
let action =
parse(r#"{"kind":"submit_user_message","content":{"text":"hi"}}"#).expect("a valid frame");
assert!(matches!(action, Action::SubmitUserMessage { content, .. } if content == "hi"));
}
/// A line that is not JSON is refused without a `kind`, because it never had one.
///
/// The break this catches: inventing a kind for an unparseable line, which would send a client
/// looking for a bug in a frame it never wrote.
#[test]
fn a_line_that_is_not_json_is_refused_without_a_kind() {
let rejected = parse("not json at all").expect_err("garbage is not a frame");
assert_eq!(rejected.kind, None);
assert!(!rejected.reason.is_empty());
}
/// A known frame with a bad payload is refused, and the reason names the frame.
#[test]
fn a_known_frame_with_a_bad_payload_is_refused_by_name() {
let rejected =
parse(r#"{"kind":"steer_turn","content":{}}"#).expect_err("steer_turn needs text");
assert!(rejected.reason.contains("steer_turn"), "{}", rejected.reason);
}
/// An unknown frame is refused with its kind, so a client can tell "not implemented" from
/// "malformed" without reading the harness's source.
#[test]
fn an_unknown_frame_is_refused_with_its_kind() {
let rejected = parse(r#"{"kind":"launch_missiles","content":{}}"#).expect_err("no such action");
assert_eq!(rejected.kind.as_deref(), Some("launch_missiles"));
}
// === Whole-session tests, over an in-memory duplex ===
/// Everything a session needs: the frames written out, and the actions the engine received.
struct Session {
frames: Vec<serde_json::Value>,
actions: Vec<Action>,
}
/// Run one RPC session over in-memory pipes, feeding `input` and collecting both directions.
///
/// The engine is a pair of channels rather than a real one: this is a test of the protocol
/// layer, and what that layer promises is that frames arrive in order and actions reach the
/// channel. `events` is what a real engine would emit.
///
/// Two pipes rather than one duplex, because that is what stdio is — and because dropping one
/// half of a *split* `DuplexStream` does not signal EOF to the peer, only dropping the whole
/// stream does. A harness built the other way hangs instead of ending the session, which is a
/// property of the fake and would have been mistaken for one of the code.
async fn run_session(input: &str, events: Vec<Event>) -> Session {
let (mut client_write, server_read) = tokio::io::duplex(64 * 1024);
let (server_write, mut client_read) = tokio::io::duplex(64 * 1024);
let (engine_tx, mut engine_rx) = mpsc::channel::<Action>(64);
let (event_tx, event_rx) = mpsc::channel::<Event>(64);
client_write.write_all(input.as_bytes()).await.unwrap();
drop(client_write); // EOF: the client is done talking
// Drain concurrently so a session that outgrows the pipe buffer cannot deadlock the test.
let output = tokio::spawn(async move {
let mut raw = String::new();
tokio::io::AsyncReadExt::read_to_string(&mut client_read, &mut raw).await.unwrap();
raw
});
// Stand in for the engine, faithfully in the one way that matters here: its event stream
// outlives the client's input and ends only after `Close`. A fake that closed the stream
// as soon as it ran out of scripted events would race the reader and make the assertions
// below depend on task scheduling.
let closing_tx = event_tx.clone();
let collector = tokio::spawn(async move {
let mut actions = Vec::new();
while let Some(action) = engine_rx.recv().await {
let closing = matches!(action, Action::Close);
actions.push(action);
if closing {
break;
}
}
drop(closing_tx);
actions
});
let feeder = tokio::spawn(async move {
for event in events {
if event_tx.send(event).await.is_err() {
return;
}
}
});
let ready = Event::Ready {
protocol_version: luxe_core::PROTOCOL_VERSION,
luxe_version: "0.1.0".into(),
session_id: "session-1".into(),
cwd: "/work/luxe".into(),
github_writes: false,
};
let served = serve(
ready,
event_rx,
engine_tx,
server_read,
server_write,
&FixedModels,
policy(GithubWrites::NotEnabled),
);
tokio::time::timeout(std::time::Duration::from_secs(5), served)
.await
.expect("the session must end once input and events are exhausted")
.expect("serve");
feeder.await.unwrap();
let raw = output.await.unwrap();
Session {
frames: raw
.lines()
.map(|line| {
serde_json::from_str(line)
.unwrap_or_else(|e| panic!("stdout carried a non-JSON line {line:?}: {e}"))
})
.collect(),
actions: collector.await.unwrap(),
}
}
/// The handshake is the first frame, before anything the engine has to say.
///
/// The break this catches: emitting `ready` after the first engine event, which would make a
/// client that reads one line to check the version read a token delta instead.
#[tokio::test]
async fn the_handshake_leads_the_stream() {
let session =
run_session("", vec![Event::Notice("an engine had something to say first".into())]).await;
assert_eq!(session.frames[0]["kind"], "ready");
assert_eq!(session.frames[0]["content"]["protocol_version"], 2);
assert_eq!(session.frames[0]["content"]["session_id"], "session-1");
}
/// An EOF on the input closes the engine rather than leaving it running behind a dead stream.
#[tokio::test]
async fn a_client_that_goes_away_closes_the_engine() {
let session = run_session("", Vec::new()).await;
assert!(
session.actions.iter().any(|action| matches!(action, Action::Close)),
"EOF must reach the engine as Close, got {:?}",
session.actions
);
}
/// The permission round-trip: the prompt reaches the client and the answer reaches the engine.
///
/// This is the whole reason RPC resolves `ask` to `Prompt` instead of auto-allowing. The break
/// it catches: dropping the reply's id, which would leave the turn blocked on a prompt that was
/// already answered.
#[tokio::test]
async fn a_permission_prompt_is_answered_by_the_client() {
let prompt = Event::PermissionRequested {
id: serde_json::from_value(serde_json::json!("perm:9")).unwrap(),
session_id: "session-1".into(),
tool: "bash".into(),
permission: "bash".into(),
summary: "Run: cargo test".into(),
always_patterns: vec!["cargo *".into()],
};
let session = run_session(
"{\"kind\":\"respond_permission\",\"content\":{\"id\":\"perm:9\",\"reply\":\"once\"}}\n",
vec![prompt],
)
.await;
let asked = session
.frames
.iter()
.find(|frame| frame["kind"] == "permission_requested")
.expect("the prompt must reach the client");
assert_eq!(asked["content"]["summary"], "Run: cargo test");
let answered = session
.actions
.iter()
.find(|action| matches!(action, Action::RespondPermission { .. }))
.expect("the answer must reach the engine");
assert!(matches!(
answered,
Action::RespondPermission { id, reply: luxe_core::permission::PermissionReply::Once }
if id.as_str() == "perm:9"
));
}
/// A bad line is refused and the session carries on with the next one.
///
/// The break this catches: treating a parse failure as fatal, which would let one typo in a
/// client end a working session.
#[tokio::test]
async fn one_bad_line_does_not_end_the_session() {
let session = run_session(
"not json\n{\"kind\":\"steer_turn\",\"content\":{}}\n{\"kind\":\"cancel\"}\n",
Vec::new(),
)
.await;
let refusals: Vec<&serde_json::Value> =
session.frames.iter().filter(|frame| frame["kind"] == "action_rejected").collect();
assert_eq!(refusals.len(), 2, "both bad lines are refused: {:?}", session.frames);
assert!(refusals[0]["content"].get("kind").is_none(), "garbage has no kind");
assert_eq!(refusals[1]["content"]["kind"], "steer_turn", "a known frame is named");
assert!(
session.actions.iter().any(|action| matches!(action, Action::Cancel)),
"the good line after two bad ones still ran"
);
}
/// A blank line is not a frame, and must not be answered with a refusal.
///
/// Trailing newlines are what every line-oriented client produces; answering them with an
/// error would make a correct client look broken.
#[tokio::test]
async fn blank_lines_are_not_frames() {
let session = run_session("\n \n\t\n{\"kind\":\"cancel\"}\n", Vec::new()).await;
assert!(
!session.frames.iter().any(|frame| frame["kind"] == "action_rejected"),
"whitespace is not an error: {:?}",
session.frames
);
assert!(session.actions.iter().any(|action| matches!(action, Action::Cancel)));
}
/// `close` reaches the engine, and the reader stops asking for more.
#[tokio::test]
async fn close_ends_the_session() {
let session = run_session("{\"kind\":\"close\"}\n{\"kind\":\"cancel\"}\n", Vec::new()).await;
assert!(matches!(session.actions.first(), Some(Action::Close)));
assert!(
!session.actions.iter().any(|action| matches!(action, Action::Cancel)),
"nothing after `close` is forwarded, got {:?}",
session.actions
);
}
/// A client writing Windows line endings is understood.
///
/// Three platforms are first-class, and a client on the one that ends its lines `\r\n` is the
/// obvious way a line-oriented protocol breaks on it. Today it holds twice over — tokio's
/// `lines()` strips the `\r`, and JSON counts a stray one as whitespace anyway — so this cannot
/// fail against the current framing, and it is kept for the framing that replaces it. Anything
/// stricter (a length prefix, a hand-rolled `strip_suffix("\n")`, a parser that rejects trailing
/// bytes) fails here rather than in a bug report from the one platform nobody develops on.
#[tokio::test]
async fn crlf_line_endings_are_frames_too() {
let session =
run_session("{\"kind\":\"cancel\"}\r\n{\"kind\":\"close\"}\r\n", Vec::new()).await;
assert!(
!session.frames.iter().any(|frame| frame["kind"] == "action_rejected"),
"a CRLF client is not a broken client: {:?}",
session.frames
);
assert!(
session.actions.iter().any(|action| matches!(action, Action::Cancel)),
"the frame must survive its own line ending, got {:?}",
session.actions
);
}
/// A write that fails for any reason *other* than a hangup is still an error.
///
/// The hangup case below makes `luxe --rpc | head` exit 0, and the tempting way to write it is
/// to treat every write failure as "the client left" — `cargo mutants` confirmed that replacing
/// the error-kind guard with `true` went unnoticed. It should not: a full disk or a broken
/// redirect would then end the session reporting success, and the frames nobody received would
/// look delivered.
#[tokio::test]
async fn a_real_write_failure_is_not_mistaken_for_a_hangup() {
/// A sink that fails the way a full disk does, not the way a closed pipe does.
struct FailingWriter;
impl AsyncWrite for FailingWriter {
fn poll_write(
self: std::pin::Pin<&mut Self>,
_: &mut std::task::Context<'_>,
_: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
std::task::Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::StorageFull,
"no space left on device",
)))
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
_: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
std::task::Poll::Ready(Ok(()))
}
fn poll_shutdown(
self: std::pin::Pin<&mut Self>,
_: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
std::task::Poll::Ready(Ok(()))
}
}
let (client_write, server_read) = tokio::io::duplex(1024);
drop(client_write);
let (engine_tx, mut engine_rx) = mpsc::channel::<Action>(8);
let (_event_tx, event_rx) = mpsc::channel::<Event>(8);
tokio::spawn(async move { while engine_rx.recv().await.is_some() {} });
let ready = Event::Ready {
protocol_version: luxe_core::PROTOCOL_VERSION,
luxe_version: "0.1.0".into(),
session_id: "session-1".into(),
cwd: "/work/luxe".into(),
github_writes: false,
};
let served = serve(
ready,
event_rx,
engine_tx,
server_read,
FailingWriter,
&FixedModels,
policy(GithubWrites::NotEnabled),
);
let outcome = tokio::time::timeout(std::time::Duration::from_secs(5), served)
.await
.expect("a failing write must not hang the session");
assert!(outcome.is_err(), "a storage failure is an error, not a clean end");
}
/// A client that stops reading ends the session cleanly rather than raising an error.
///
/// The break this catches: propagating `BrokenPipe` out of `run_rpc`, which makes the
/// ordinary `luxe --rpc | head` exit non-zero with an error nobody can read — it goes to a
/// pipe that is already closed.
#[tokio::test]
async fn a_client_that_stops_reading_is_not_an_error() {
let (client_write, server_read) = tokio::io::duplex(1024);
let (server_write, client_read) = tokio::io::duplex(1024);
let (engine_tx, mut engine_rx) = mpsc::channel::<Action>(64);
let (event_tx, event_rx) = mpsc::channel::<Event>(64);
drop(client_read); // the client hung up before reading a single frame
drop(client_write);
tokio::spawn(async move { while engine_rx.recv().await.is_some() {} });
tokio::spawn(async move {
for _ in 0..64 {
if event_tx.send(Event::Notice("still talking".into())).await.is_err() {
return;
}
}
});
let ready = Event::Ready {
protocol_version: luxe_core::PROTOCOL_VERSION,
luxe_version: "0.1.0".into(),
session_id: "session-1".into(),
cwd: "/work/luxe".into(),
github_writes: false,
};
let served = serve(
ready,
event_rx,
engine_tx,
server_read,
server_write,
&FixedModels,
policy(GithubWrites::NotEnabled),
);
let outcome = tokio::time::timeout(std::time::Duration::from_secs(5), served)
.await
.expect("a hangup must end the session promptly");
assert!(outcome.is_ok(), "a client hangup is a clean end: {outcome:?}");
}
/// Every frame written is one line of JSON — the framing rule a client parses by.
///
/// `run_session` panics on any line that will not parse, so a stray `println!` anywhere in this
/// path fails here. The multi-line payload is the interesting case: a newline inside a string
/// must be escaped rather than splitting the frame in two.
#[tokio::test]
async fn every_frame_is_exactly_one_line() {
let session = run_session(
"",
vec![
Event::Notice("one\ntwo\nthree".into()),
Event::TokenDelta { block: 0, delta: "a\nb".into() },
],
)
.await;
assert_eq!(session.frames.len(), 3, "ready + two events, no more, no fewer");
assert_eq!(session.frames[1]["content"], "one\ntwo\nthree");
assert_eq!(session.frames[2]["content"]["delta"], "a\nb");
}

View File

@@ -0,0 +1,253 @@
//! Wire → runtime action translation.
//!
//! One exhaustive `match` from the published [`WireAction`] vocabulary to the engine's own
//! [`Action`]. It lives here rather than in `luxe-core` because two arms need the model catalog,
//! which is a `luxe-cli` concern — and a translator that punts on exactly the interesting cases is
//! how the previous half-bridge ended up with no callers.
use luxe_core::engine::Action;
use luxe_core::event::Action as WireAction;
/// Why an inbound frame produced nothing.
///
/// Carries the `kind` so the rejection sent back to the client can name what it refused, which is
/// the difference between a client author fixing their frame and guessing at it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Rejected {
/// The wire `kind` that was refused, when the frame parsed far enough to have one.
pub(crate) kind: Option<String>,
/// What was wrong with it, in the same voice as a permission denial: lowercase, no period.
pub(crate) reason: String,
}
impl Rejected {
/// A frame whose `kind` this build does not implement.
fn unknown(kind: impl Into<String>) -> Self {
let kind = kind.into();
Self { reason: format!("no such action `{kind}`"), kind: Some(kind) }
}
}
/// What this session lets a client do, decided once at launch.
///
/// The translator is the one choke point every inbound frame passes, so the RPC mode's own rules
/// live here rather than in the engine: the TUI's GitHub writes are confirmed by a person in a
/// preview, and nothing about them changes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Policy {
/// Whether actions that publish to GitHub are accepted
pub(crate) github_writes: GithubWrites,
/// The `/github` sections a bare `list_github` runs: the user's configured ones
pub(crate) github_sections: Vec<luxe_core::config::GithubSection>,
}
/// Whether a client may publish to GitHub, and if not, why not.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum GithubWrites {
/// Launched with `--github-writes`
Allowed,
/// The default: writes need the flag
NotEnabled,
/// A read-only session refuses them, flag or no flag
ReadOnly,
}
impl GithubWrites {
/// The answer for a launch: read-only wins over the flag, so turning on writes can never
/// loosen a session someone made read-only.
pub(crate) fn for_launch(flag: bool, mode: luxe_core::permission::PermissionMode) -> Self {
match (mode, flag) {
(luxe_core::permission::PermissionMode::ReadOnly, _) => Self::ReadOnly,
(_, true) => Self::Allowed,
(_, false) => Self::NotEnabled,
}
}
/// Whether writes are accepted, for the `ready` frame.
pub(crate) fn allowed(self) -> bool {
self == Self::Allowed
}
/// Why `kind` was refused, when it was.
fn refusal(self, kind: &str) -> Option<String> {
match self {
Self::Allowed => None,
Self::NotEnabled => Some(format!(
"{kind} publishes to GitHub, which this session does not allow: start Luxe with \
--github-writes to let a client do that"
)),
Self::ReadOnly => Some(format!(
"{kind} publishes to GitHub, and this session is read-only, which --github-writes \
does not override"
)),
}
}
}
/// Resolves a model reference to the full metadata the engine needs.
///
/// Injected rather than called directly because the real one reads the user's `models.json`, and a
/// test whose outcome depends on the developer's config is not a test.
pub(crate) trait ModelResolver {
/// The catalog's answer for `provider`/`id`.
///
/// Total: an id no layer recognizes still resolves, to provider-aware defaults. That is the
/// same contract `--model` has always had, and it is what makes a local or proxied model
/// usable without an entry in anyone's catalog.
fn resolve(&self, provider: &str, id: &str) -> luxe_core::ModelInfo;
}
/// The real catalog: configured models first, models.dev filling the gaps, defaults under that.
pub(crate) struct CatalogResolver;
impl ModelResolver for CatalogResolver {
fn resolve(&self, provider: &str, id: &str) -> luxe_core::ModelInfo {
let config = crate::engine_setup::load_luxe_config();
crate::model_catalog::resolve_model(&config, provider, id).0
}
}
/// Translate one wire action into the engine action it stands for.
///
/// Every arm is a total mapping or a named refusal — there is no silent drop, because a front-end
/// whose frame vanished has no way to tell that from an engine that is merely slow.
pub(crate) fn to_engine_action(
wire: WireAction,
models: &dyn ModelResolver,
policy: &Policy,
) -> Result<Action, Rejected> {
if wire.writes_to_github() {
if let Some(reason) = policy.github_writes.refusal(wire.kind()) {
return Err(Rejected { kind: Some(wire.kind().to_string()), reason });
}
}
if wire.writes_the_repository() && policy.github_writes == GithubWrites::ReadOnly {
let kind = wire.kind();
let reason = format!("{kind} writes to the repository, and this session is read-only");
return Err(Rejected { kind: Some(kind.to_string()), reason });
}
Ok(match wire {
WireAction::SubmitUserMessage { text, images } => {
Action::SubmitUserMessage { content: text, images, remediation: None }
}
WireAction::SteerTurn { text } => Action::SteerTurn { content: text },
WireAction::WithdrawSteering => Action::WithdrawSteering,
WireAction::Cancel => Action::Cancel,
WireAction::EditResend { text } => Action::EditResend { content: text },
WireAction::Retry => Action::Retry,
WireAction::Regenerate => Action::Regenerate,
WireAction::RespondPermission { id, reply } => Action::RespondPermission { id, reply },
WireAction::AnswerQuestion { id, reply } => Action::AnswerQuestion { id, reply },
WireAction::SetPermissionAutoApprove(on) => Action::SetPermissionAutoApprove(on),
WireAction::SelectModel(model) => {
Action::SetModel(models.resolve(&model.provider, &model.model))
}
WireAction::SetThinkingLevel(level) => Action::SetThinkingLevel(level),
// The mode's model and thinking level come from config, so a client names the mode alone
WireAction::SetMode(mode) => Action::SetMode(mode),
WireAction::RequestReview { focus } => Action::RequestReview { focus },
WireAction::NewSession => Action::NewSession,
WireAction::LoadSession(id) => Action::LoadSession(id),
WireAction::RefreshSessions => Action::RefreshSessions,
WireAction::RefreshWorkspace => Action::RefreshWorkspace,
WireAction::RequestContextComposition => Action::RequestContextComposition,
WireAction::CompactNow { focus } => Action::CompactNow { focus },
WireAction::LoadGuidedReview { request_id, target } => {
Action::LoadGuidedReview { request_id, target }
}
WireAction::EditReview { request_id, review_id, edit } => {
Action::EditReview { request_id, review_id, edit }
}
WireAction::RecordReviewProgress { review_id, walked_chapter_ids } => {
Action::RecordReviewProgress {
review_id,
progress: luxe_core::guided_review::ReviewProgress {
walked_chapter_ids,
..Default::default()
},
}
}
WireAction::RecordReviewSeen { review_id } => Action::RecordReviewSeen { review_id },
WireAction::RefreshGuidedReview { request_id, review_id, revision_id } => {
Action::RefreshGuidedReview { request_id, review_id, expected_revision: revision_id }
}
WireAction::CommitReviewChapters {
request_id,
review_id,
revision_id,
chapter_ids,
squash,
} => Action::CommitReviewChapters {
request_id,
review_id,
expected_revision: revision_id,
chapter_ids,
squash,
},
WireAction::PreparePullRequest { request_id, review_id } => {
Action::PreparePullRequest { request_id, review_id }
}
WireAction::OpenPullRequest { request_id, title, body, draft } => {
Action::OpenPullRequest { request_id, title, body, draft }
}
WireAction::PrepareStack { request_id, review_id } => {
Action::PrepareStack { request_id, review_id }
}
WireAction::OpenStack { request_id, draft } => Action::OpenStack { request_id, draft },
WireAction::PreparePullRequestPost { request_id, review_id } => {
Action::PreparePullRequestPost { request_id, review_id }
}
WireAction::PostPullRequestReview { request_id, verdict, session_revision } => {
Action::PostPullRequestReview { request_id, verdict, session_revision }
}
WireAction::PrepareThreadAnswers { request_id, review_id } => {
Action::PrepareThreadAnswers { request_id, review_id }
}
WireAction::AnswerThreads { request_id, review_id, answers } => {
Action::AnswerThreads { request_id, review_id, answers }
}
WireAction::ListGithub { sections } => Action::ListGithub {
sections: sections.unwrap_or_else(|| policy.github_sections.clone()),
},
WireAction::SearchGithub { request, section, after } => {
Action::SearchGithub { request, section, after }
}
WireAction::ReadGithubOverview { repository, number, pull_request } => {
Action::ReadGithubOverview { repository, number, pull_request }
}
WireAction::ReadGithubConversation { repository, number, pull_request } => {
Action::ReadGithubConversation { repository, number, pull_request }
}
WireAction::DraftGithubReply(request) => Action::DraftGithubReply(request),
WireAction::CheckPullRequestFix { number, repository } => {
Action::CheckPullRequestFix { number, repository }
}
WireAction::PlanRestack { request_id } => Action::PlanRestack { request_id },
WireAction::CheckWorktreeRemoval => Action::CheckWorktreeRemoval,
WireAction::LoadFileDiff { request_id, path } => Action::LoadFileDiff { request_id, path },
WireAction::ListDirectory { request_id, path, include_ignored } => {
Action::ListDirectory { request_id, path, include_ignored }
}
WireAction::ReadProjectFile { request_id, path } => {
Action::ReadProjectFile { request_id, path }
}
WireAction::SetFocus { focused } => Action::FocusChanged { focused },
WireAction::LinkPullRequest { number, url } => Action::LinkPullRequest { number, url },
WireAction::PostGithubComment(post) => Action::PostGithubComment(post),
WireAction::ChangePullRequest { repository, number, write } => {
Action::ChangePullRequest { repository, number, write }
}
WireAction::Restack { request_id } => Action::Restack { request_id },
WireAction::Close => Action::Close,
WireAction::Other { kind, .. } => return Err(Rejected::unknown(kind)),
// `WireAction` is `#[non_exhaustive]`, so this crate cannot match it exhaustively even
// while it does cover every variant. A variant published upstream without an arm here
// lands on this line and is refused by name rather than silently dropped;
// `the_translator_covers_the_whole_published_vocabulary` is what stops it shipping that
// way in the first place.
future => return Err(Rejected::unknown(future.kind())),
})
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,546 @@
use super::*;
use luxe_core::provider::{ModelInfo, ThinkingLevel};
/// A catalog that knows one model and falls back for everything else, like the real one.
struct OneModel;
impl ModelResolver for OneModel {
fn resolve(&self, provider: &str, id: &str) -> ModelInfo {
let known = provider == "anthropic" && id == "claude-sonnet-4-20250514";
ModelInfo {
r#ref: luxe_core::provider::ModelRef::new(provider, id),
context_window: if known { 200_000 } else { 128_000 },
..Default::default()
}
}
}
fn policy(github_writes: GithubWrites) -> Policy {
Policy {
github_writes,
github_sections: vec![luxe_core::config::GithubSection {
name: "Mine".into(),
query: "is:open is:pr author:@me repo:{repo}".into(),
}],
}
}
fn translate(wire: WireAction) -> Result<Action, Rejected> {
to_engine_action(wire, &OneModel, &policy(GithubWrites::Allowed))
}
/// A steer for the summary has to survive the crossing; without it `/compact keep the API
/// decisions` is an ordinary compaction that silently ignored what it was told.
#[test]
fn compact_now_carries_its_focus() {
assert!(matches!(
translate(WireAction::CompactNow { focus: Some("the API decisions".into()) }),
Ok(Action::CompactNow { focus: Some(focus) }) if focus == "the API decisions"
));
assert!(matches!(
translate(WireAction::CompactNow { focus: None }),
Ok(Action::CompactNow { focus: None })
));
}
/// Every wire action reaches the engine, and reaches it carrying its payload.
///
/// The break this catches: an arm wired to the wrong engine variant, or one that drops a field
/// on the way. `matches!` on the variant alone would pass through a `steer_turn` translated as
/// an empty submission — which is a new turn instead of a mid-turn nudge, the one distinction
/// the action exists to make.
#[test]
fn each_wire_action_arrives_as_the_engine_action_it_names() {
assert!(matches!(
translate(WireAction::SubmitUserMessage {
text: "hello".into(),
images: vec![luxe_core::engine::ImageAttachment {
data: "aGk=".into(),
mime: "image/png".into(),
name: None,
}],
}),
Ok(Action::SubmitUserMessage { content, images, remediation: None })
if content == "hello" && images.len() == 1
));
assert!(matches!(
translate(WireAction::SteerTurn { text: "also windows".into() }),
Ok(Action::SteerTurn { content }) if content == "also windows"
));
assert!(matches!(translate(WireAction::Cancel), Ok(Action::Cancel)));
assert!(matches!(
translate(WireAction::EditResend { text: "shorter".into() }),
Ok(Action::EditResend { content }) if content == "shorter"
));
assert!(matches!(translate(WireAction::Retry), Ok(Action::Retry)));
assert!(matches!(translate(WireAction::Regenerate), Ok(Action::Regenerate)));
assert!(matches!(
translate(WireAction::SetPermissionAutoApprove(true)),
Ok(Action::SetPermissionAutoApprove(true))
));
assert!(matches!(
translate(WireAction::SetThinkingLevel(ThinkingLevel::High)),
Ok(Action::SetThinkingLevel(ThinkingLevel::High))
));
assert!(matches!(translate(WireAction::NewSession), Ok(Action::NewSession)));
assert!(matches!(
translate(WireAction::LoadSession("session-1".into())),
Ok(Action::LoadSession(id)) if id == "session-1"
));
assert!(matches!(translate(WireAction::RefreshSessions), Ok(Action::RefreshSessions)));
assert!(matches!(translate(WireAction::RefreshWorkspace), Ok(Action::RefreshWorkspace)));
assert!(matches!(
translate(WireAction::RequestContextComposition),
Ok(Action::RequestContextComposition)
));
assert!(matches!(translate(WireAction::Close), Ok(Action::Close)));
assert!(matches!(
translate(WireAction::SetMode("plan".into())),
Ok(Action::SetMode(mode)) if mode == "plan"
));
assert!(matches!(
translate(WireAction::RequestReview { focus: Some("the parser".into()) }),
Ok(Action::RequestReview { focus: Some(focus) }) if focus == "the parser"
));
}
/// Every GitHub action reaches the engine as the action it names, carrying its payload.
///
/// Same break as above, sharpest here: overview and conversation share a payload, as do
/// `plan_restack` and `restack`, so a crossed arm still type-checks — and `restack` arriving as
/// a plan, or a plan arriving as a push, is the difference between looking and force-pushing.
#[test]
fn each_github_action_arrives_as_the_engine_action_it_names() {
let restack: luxe_core::restack::RestackId =
serde_json::from_value(serde_json::json!("restack:1")).unwrap();
assert!(matches!(
translate(WireAction::PlanRestack { request_id: restack.clone() }),
Ok(Action::PlanRestack { request_id }) if request_id == restack
));
assert!(matches!(
translate(WireAction::Restack { request_id: restack.clone() }),
Ok(Action::Restack { request_id }) if request_id == restack
));
assert!(matches!(
translate(WireAction::ReadGithubOverview {
repository: Some("acme/app".into()),
number: 9,
pull_request: false,
}),
Ok(Action::ReadGithubOverview { repository: Some(repository), number: 9, pull_request: false })
if repository == "acme/app"
));
assert!(matches!(
translate(WireAction::ReadGithubConversation {
repository: None,
number: 142,
pull_request: true,
}),
Ok(Action::ReadGithubConversation { repository: None, number: 142, pull_request: true })
));
let section =
luxe_core::config::GithubSection { name: "Bugs".into(), query: "is:open label:bug".into() };
assert!(matches!(
translate(WireAction::SearchGithub {
request: 7,
section: section.clone(),
after: Some("cursor".into()),
}),
Ok(Action::SearchGithub { request: 7, section: asked, after: Some(after) })
if asked == section && after == "cursor"
));
assert!(matches!(
translate(WireAction::CheckPullRequestFix { number: 142, repository: None }),
Ok(Action::CheckPullRequestFix { number: 142, repository: None })
));
assert!(matches!(
translate(WireAction::CheckWorktreeRemoval),
Ok(Action::CheckWorktreeRemoval)
));
let diff: luxe_core::file_diff::FileDiffRequestId =
serde_json::from_value(serde_json::json!("file-diff:1")).unwrap();
assert!(matches!(
translate(WireAction::LoadFileDiff { request_id: diff.clone(), path: "src/a.rs".into() }),
Ok(Action::LoadFileDiff { request_id, path }) if request_id == diff && path == "src/a.rs"
));
let listing = luxe_core::project_files::ListingRequestId::new();
assert!(matches!(
translate(WireAction::ListDirectory {
request_id: listing.clone(),
path: "src".into(),
include_ignored: true,
}),
Ok(Action::ListDirectory { request_id, path, include_ignored: true })
if request_id == listing && path == "src"
));
let read = luxe_core::project_files::FileReadRequestId::new();
assert!(matches!(
translate(WireAction::ReadProjectFile { request_id: read.clone(), path: "a.rs".into() }),
Ok(Action::ReadProjectFile { request_id, path }) if request_id == read && path == "a.rs"
));
assert!(matches!(
translate(WireAction::SetFocus { focused: false }),
Ok(Action::FocusChanged { focused: false })
));
assert!(matches!(
translate(WireAction::LinkPullRequest { number: 142, url: "u".into() }),
Ok(Action::LinkPullRequest { number: 142, url }) if url == "u"
));
let post = luxe_core::engine::GithubPost {
repository: None,
number: 142,
thread: Some("PRRT_1".into()),
answering: None,
body: "Fixed.".into(),
};
assert!(matches!(
translate(WireAction::PostGithubComment(post.clone())),
Ok(Action::PostGithubComment(sent)) if sent == post
));
let write = luxe_core::engine::PullRequestWrite::MarkReady;
assert!(matches!(
translate(WireAction::ChangePullRequest { repository: None, number: 142, write }),
Ok(Action::ChangePullRequest {
repository: None,
number: 142,
write: luxe_core::engine::PullRequestWrite::MarkReady,
})
));
}
/// Every review action reaches the engine as the action it names, carrying its payload.
///
/// Same break as above. The pairs that share a payload are the ones to watch: `prepare_*` and
/// its `open_*`, and the revision a refresh or a commit is guarded by, which arrives renamed.
#[test]
fn each_review_action_arrives_as_the_engine_action_it_names() {
use luxe_core::guided_review::{ReviewId, ReviewRevisionId};
let id = |raw: &str| -> ReviewId { serde_json::from_value(serde_json::json!(raw)).unwrap() };
let revision: ReviewRevisionId =
serde_json::from_value(serde_json::json!("revision:1")).unwrap();
let open: luxe_core::guided_review::PullRequestOpenId =
serde_json::from_value(serde_json::json!("pr-open:1")).unwrap();
let post: luxe_core::guided_review::PullRequestPostId =
serde_json::from_value(serde_json::json!("pr-post:1")).unwrap();
let save: luxe_core::guided_review::ReviewSessionSaveRequestId =
serde_json::from_value(serde_json::json!("review-save:1")).unwrap();
let load: luxe_core::guided_review::ReviewLoadRequestId =
serde_json::from_value(serde_json::json!("review-load:1")).unwrap();
let edit = luxe_core::engine::ReviewEdit::SetOutcome {
outcome: luxe_core::guided_review::ReviewOutcome::Accepted,
};
assert!(matches!(
translate(WireAction::EditReview { request_id: save.clone(), review_id: id("review:1"), edit: edit.clone() }),
Ok(Action::EditReview { request_id, review_id, edit: sent })
if request_id == save && review_id == id("review:1") && sent == edit
));
let chapter: luxe_core::guided_review::ChapterId =
serde_json::from_value(serde_json::json!("chapter:1")).unwrap();
assert!(matches!(
translate(WireAction::RecordReviewProgress {
review_id: id("review:1"),
walked_chapter_ids: vec![chapter.clone()],
}),
Ok(Action::RecordReviewProgress { progress, .. })
if progress.walked_chapter_ids == vec![chapter]
));
assert!(matches!(
translate(WireAction::RecordReviewSeen { review_id: id("review:1") }),
Ok(Action::RecordReviewSeen { .. })
));
assert!(matches!(
translate(WireAction::RefreshGuidedReview {
request_id: load.clone(),
review_id: id("review:1"),
revision_id: revision.clone(),
}),
Ok(Action::RefreshGuidedReview { request_id, expected_revision, .. })
if request_id == load && expected_revision == revision
));
assert!(matches!(
translate(WireAction::CommitReviewChapters {
request_id: save.clone(),
review_id: id("review:1"),
revision_id: revision.clone(),
chapter_ids: Vec::new(),
squash: true,
}),
Ok(Action::CommitReviewChapters { expected_revision, squash: true, .. })
if expected_revision == revision
));
assert!(matches!(
translate(WireAction::PreparePullRequest { request_id: open.clone(), review_id: id("review:1") }),
Ok(Action::PreparePullRequest { request_id, .. }) if request_id == open
));
assert!(matches!(
translate(WireAction::OpenPullRequest {
request_id: open.clone(),
title: "T".into(),
body: "B".into(),
draft: true,
}),
Ok(Action::OpenPullRequest { request_id, title, body, draft: true })
if request_id == open && title == "T" && body == "B"
));
assert!(matches!(
translate(WireAction::PrepareStack { request_id: open.clone(), review_id: id("review:1") }),
Ok(Action::PrepareStack { .. })
));
assert!(matches!(
translate(WireAction::OpenStack { request_id: open.clone(), draft: true }),
Ok(Action::OpenStack { draft: true, .. })
));
assert!(matches!(
translate(WireAction::PreparePullRequestPost {
request_id: post.clone(),
review_id: id("review:1")
}),
Ok(Action::PreparePullRequestPost { .. })
));
assert!(matches!(
translate(WireAction::PostPullRequestReview {
request_id: post.clone(),
verdict: luxe_core::github::ReviewEvent::Approve,
session_revision: 3,
}),
Ok(Action::PostPullRequestReview {
verdict: luxe_core::github::ReviewEvent::Approve,
session_revision: 3,
..
})
));
let threads: luxe_core::guided_review::ThreadAnswersId =
serde_json::from_value(serde_json::json!("thread-answers:1")).unwrap();
assert!(matches!(
translate(WireAction::PrepareThreadAnswers {
request_id: threads.clone(),
review_id: id("review:1")
}),
Ok(Action::PrepareThreadAnswers { .. })
));
assert!(matches!(
translate(WireAction::AnswerThreads {
request_id: threads,
review_id: id("review:1"),
answers: Vec::new(),
}),
Ok(Action::AnswerThreads { .. })
));
}
/// Committing a review's chapters writes history without publishing it: allowed without
/// `--github-writes`, refused in a read-only session.
#[test]
fn a_read_only_session_refuses_to_commit_a_review() {
let commit = || WireAction::CommitReviewChapters {
request_id: serde_json::from_value(serde_json::json!("review-save:1")).unwrap(),
review_id: serde_json::from_value(serde_json::json!("review:1")).unwrap(),
revision_id: serde_json::from_value(serde_json::json!("revision:1")).unwrap(),
chapter_ids: Vec::new(),
squash: false,
};
assert!(to_engine_action(commit(), &OneModel, &policy(GithubWrites::NotEnabled)).is_ok());
let refused = to_engine_action(commit(), &OneModel, &policy(GithubWrites::ReadOnly))
.expect_err("read-only writes nothing");
assert_eq!(refused.kind.as_deref(), Some("commit_review_chapters"));
assert!(refused.reason.contains("read-only"), "{}", refused.reason);
}
/// A bare `list_github` runs the configured sections, and named ones replace them.
#[test]
fn list_github_falls_back_to_the_configured_sections() {
let Ok(Action::ListGithub { sections }) = translate(WireAction::ListGithub { sections: None })
else {
panic!("expected ListGithub");
};
assert_eq!(sections, policy(GithubWrites::Allowed).github_sections);
let asked = vec![luxe_core::config::GithubSection {
name: "Bugs".into(),
query: "is:open label:bug".into(),
}];
let Ok(Action::ListGithub { sections }) =
translate(WireAction::ListGithub { sections: Some(asked.clone()) })
else {
panic!("expected ListGithub");
};
assert_eq!(sections, asked);
}
/// GitHub writes need `--github-writes`, a read-only session refuses them regardless, and
/// reads are never gated.
///
/// Both directions are the point. A write that slipped through publishes on behalf of a client
/// nobody allowed to; a read caught by the gate breaks every dashboard that only looks.
#[test]
fn github_writes_need_the_flag_and_read_only_refuses_them_anyway() {
let writes = || {
[
WireAction::PostGithubComment(luxe_core::engine::GithubPost {
repository: None,
number: 1,
thread: None,
answering: None,
body: "hi".into(),
}),
WireAction::ChangePullRequest {
repository: None,
number: 1,
write: luxe_core::engine::PullRequestWrite::MarkReady,
},
WireAction::Restack { request_id: luxe_core::restack::RestackId::new() },
WireAction::OpenPullRequest {
request_id: luxe_core::guided_review::PullRequestOpenId::new(),
title: "T".into(),
body: "B".into(),
draft: false,
},
WireAction::OpenStack {
request_id: luxe_core::guided_review::PullRequestOpenId::new(),
draft: false,
},
WireAction::PostPullRequestReview {
request_id: luxe_core::guided_review::PullRequestPostId::new(),
verdict: luxe_core::github::ReviewEvent::Comment,
session_revision: 0,
},
WireAction::AnswerThreads {
request_id: luxe_core::guided_review::ThreadAnswersId::new(),
review_id: luxe_core::guided_review::ReviewId::new(),
answers: Vec::new(),
},
]
};
for (gate, needle) in [
(GithubWrites::NotEnabled, "start Luxe with --github-writes"),
(GithubWrites::ReadOnly, "read-only"),
] {
for wire in writes() {
let kind = wire.kind();
let rejected = to_engine_action(wire, &OneModel, &policy(gate))
.expect_err("a write is refused without permission");
assert_eq!(rejected.kind.as_deref(), Some(kind));
assert!(rejected.reason.contains(needle), "{gate:?}: {}", rejected.reason);
}
let read =
WireAction::ReadGithubOverview { repository: None, number: 1, pull_request: true };
assert!(to_engine_action(read, &OneModel, &policy(gate)).is_ok(), "{gate:?} gates a read");
}
for wire in writes() {
assert!(to_engine_action(wire, &OneModel, &policy(GithubWrites::Allowed)).is_ok());
}
}
/// Read-only wins over the flag; otherwise the flag decides.
#[test]
fn a_read_only_launch_refuses_writes_whatever_the_flag_says() {
use luxe_core::permission::PermissionMode;
assert_eq!(GithubWrites::for_launch(true, PermissionMode::ReadOnly), GithubWrites::ReadOnly);
assert_eq!(GithubWrites::for_launch(false, PermissionMode::ReadOnly), GithubWrites::ReadOnly);
for mode in [PermissionMode::Default, PermissionMode::Strict, PermissionMode::Yolo] {
assert_eq!(GithubWrites::for_launch(true, mode), GithubWrites::Allowed, "{mode:?}");
assert_eq!(GithubWrites::for_launch(false, mode), GithubWrites::NotEnabled, "{mode:?}");
}
assert!(GithubWrites::Allowed.allowed());
assert!(!GithubWrites::NotEnabled.allowed());
assert!(!GithubWrites::ReadOnly.allowed());
}
/// The two prompt replies keep their correlation id and their answer.
///
/// Losing either one deadlocks the turn they were sent to unblock, and a swapped id would
/// resolve somebody else's prompt.
#[test]
fn a_prompt_reply_keeps_its_id_and_its_answer() {
let id: luxe_core::permission::PermissionRequestId =
serde_json::from_value(serde_json::json!("perm:7")).unwrap();
let translated = translate(WireAction::RespondPermission {
id: id.clone(),
reply: luxe_core::permission::PermissionReply::Reject,
});
assert!(matches!(
translated,
Ok(Action::RespondPermission { id: actual, reply })
if actual == id && reply == luxe_core::permission::PermissionReply::Reject
));
let id: luxe_core::question::QuestionRequestId =
serde_json::from_value(serde_json::json!("ask:7")).unwrap();
let translated = translate(WireAction::AnswerQuestion {
id: id.clone(),
reply: luxe_core::question::QuestionReply::Answered(vec!["postgres".into()]),
});
assert!(matches!(
translated,
Ok(Action::AnswerQuestion { id: actual, reply: luxe_core::question::QuestionReply::Answered(answers) })
if actual == id && answers == vec!["postgres".to_string()]
));
}
/// A known model is filled in from the catalog rather than taken on the client's word.
#[test]
fn select_model_resolves_the_metadata_the_client_did_not_send() {
let translated = translate(WireAction::SelectModel(luxe_core::ModelRef::new(
"anthropic",
"claude-sonnet-4-20250514",
)));
let Ok(Action::SetModel(info)) = translated else { panic!("expected SetModel") };
assert_eq!(info.r#ref.id, "claude-sonnet-4-20250514");
assert_eq!(info.context_window, 200_000, "the catalog's window, not a default");
}
/// A model no catalog layer knows is still selectable, on the resolver's defaults.
///
/// The break this catches: adding a "reject what the catalog has not heard of" guard, which
/// reads like prudence and would make every local, proxied, or brand-new model unselectable
/// over RPC while `--model` kept accepting it.
#[test]
fn select_model_accepts_a_model_no_catalog_knows() {
let translated =
translate(WireAction::SelectModel(luxe_core::ModelRef::new("lmstudio", "qwen3-coder-30b")));
let Ok(Action::SetModel(info)) = translated else { panic!("a local model is still a model") };
assert_eq!(info.r#ref.id, "qwen3-coder-30b");
assert_eq!(info.r#ref.provider, "lmstudio");
}
/// An unknown frame is refused by name, so a client sees which of its actions this build lacks.
#[test]
fn an_unknown_frame_is_refused_by_name() {
let rejected =
translate(WireAction::Other { kind: "switch_role".into(), content: serde_json::json!({}) })
.expect_err("this build has no switch_role");
assert_eq!(rejected.kind.as_deref(), Some("switch_role"));
assert!(rejected.reason.contains("switch_role"), "{}", rejected.reason);
}
/// The real catalog resolver keeps the identity it was asked about, and gives a usable window.
///
/// Every other test here injects a double, so nothing exercised the production path —
/// `cargo mutants` replaced this whole resolver with `Default::default()` and the suite stayed
/// green. That default is a `ModelInfo` with an empty ref and a **zero** context window, which
/// over RPC means switching to a nameless model and reporting context fullness against a
/// divisor of nothing. Asserted against a model no config can plausibly contain, so the answer
/// comes from the built-in defaults rather than from whatever the developer has configured.
#[test]
fn the_real_resolver_answers_about_the_model_it_was_asked() {
let info = CatalogResolver.resolve("no-such-provider", "no-such-model-9e3f");
assert_eq!(info.r#ref.provider, "no-such-provider");
assert_eq!(info.r#ref.id, "no-such-model-9e3f");
assert!(info.context_window > 0, "a zero window makes every context percentage a lie");
}
/// Every published kind has a translator arm.
///
/// `WireAction` is `#[non_exhaustive]`, so the compiler cannot hold this match complete from
/// another crate — the count is what does. Publishing one more kind fails here, which is the
/// prompt to write its arm and its case above rather than let it reach clients as
/// `action_rejected`.
#[test]
fn the_translator_covers_the_whole_published_vocabulary() {
assert_eq!(
WireAction::KINDS.len(),
51,
"a wire action was published without a translator arm: {:?}",
WireAction::KINDS
);
}

View File

@@ -0,0 +1,166 @@
use super::headless::headless_json_event;
use super::tui::should_show_dashboard;
use super::worktree::{generated_branch, worktree_branch, worktree_notice};
use crate::engine_setup::ResumeMode;
use luxe_core::config::Config;
#[test]
fn should_show_dashboard_default() {
let config = Config::default(); // dashboard = None → shown
assert!(should_show_dashboard(&config, &ResumeMode::New, false));
}
#[test]
fn should_show_dashboard_explicit_true() {
let config = Config {
dashboard: Some(luxe_core::config::DashboardSetting::Enabled(true)),
..Default::default()
};
assert!(should_show_dashboard(&config, &ResumeMode::New, false));
}
#[test]
fn should_hide_dashboard_explicit_false() {
let config = Config {
dashboard: Some(luxe_core::config::DashboardSetting::Enabled(false)),
..Default::default()
};
assert!(!should_show_dashboard(&config, &ResumeMode::New, false));
}
#[test]
fn should_hide_dashboard_on_resume() {
let config = Config::default();
assert!(!should_show_dashboard(&config, &ResumeMode::Latest, false));
assert!(!should_show_dashboard(&config, &ResumeMode::Session("abc".into()), false));
}
#[test]
fn should_hide_dashboard_when_started_on_an_issue_or_a_pull_request() {
let config = Config {
dashboard: Some(luxe_core::config::DashboardSetting::Enabled(true)),
..Default::default()
};
assert!(!should_show_dashboard(&config, &ResumeMode::New, true));
}
// === headless --format json event contract ===
use luxe_core::event::{Event, StopReason};
use luxe_core::message::{ContentBlock, Message, Role};
use luxe_core::session::EntryId;
#[test]
fn json_usage_event_carries_input_output_total() {
let value = headless_json_event(&Event::TurnUsage {
prompt_tokens: 1200,
completion_tokens: 42,
cost_usd: Some(0.01),
cache_read_tokens: 900,
cache_write_tokens: 100,
reasoning_tokens: 30,
source: luxe_core::usage::UsageSource::Agent,
})
.expect("usage emits a line");
assert_eq!(value["type"], "usage");
assert_eq!(value["input"], 1200);
assert_eq!(value["output"], 42);
assert_eq!(value["total"], 1242);
assert_eq!(value["cost_usd"], 0.01);
assert_eq!(value["cache_read"], 900);
assert_eq!(value["cache_write"], 100);
assert_eq!(value["reasoning"], 30);
}
#[test]
fn json_assistant_message_flattens_text_and_names_tool_calls() {
let message = Message {
role: Role::Assistant,
content: vec![
ContentBlock::Text("Hello ".into()),
ContentBlock::Text("world".into()),
ContentBlock::ToolCall {
id: "c1".into(),
name: "read".into(),
arguments: serde_json::json!({}),
},
],
};
let value = headless_json_event(&Event::MessageCommitted {
session_id: "s".into(),
entry_id: EntryId("e1".into()),
message,
})
.expect("assistant message emits a line");
assert_eq!(value["type"], "message");
assert_eq!(value["text"], "Hello world");
assert_eq!(value["tool_calls"], serde_json::json!(["read"]));
}
#[test]
fn json_skips_non_assistant_messages_and_unmapped_events() {
let user = Message { role: Role::User, content: vec![ContentBlock::Text("hi".into())] };
assert!(headless_json_event(&Event::MessageCommitted {
session_id: "s".into(),
entry_id: EntryId("e2".into()),
message: user,
})
.is_none());
assert!(headless_json_event(&Event::TokenDelta { block: 0, delta: "x".into() }).is_none());
}
#[test]
fn json_terminal_events_map_to_turn_end_and_error() {
let end = headless_json_event(&Event::TurnEnded { reason: StopReason::EndTurn })
.expect("turn_end line");
assert_eq!(end["type"], "turn_end");
let err = headless_json_event(&Event::Error("boom".into())).expect("error line");
assert_eq!(err["type"], "error");
assert_eq!(err["message"], "boom");
}
#[test]
fn the_worktree_branch_follows_the_flag_then_the_session_then_the_config() {
let made_up = || "luxe/session-made".to_string();
let resumed = || Some("topic".to_string());
assert_eq!(worktree_branch(Some("mine"), resumed(), false, made_up).as_deref(), Some("mine"));
assert_eq!(worktree_branch(Some(""), resumed(), false, made_up).as_deref(), Some("topic"));
assert_eq!(
worktree_branch(Some(""), None, false, made_up).as_deref(),
Some("luxe/session-made")
);
assert_eq!(worktree_branch(None, resumed(), false, made_up).as_deref(), Some("topic"));
assert_eq!(worktree_branch(None, None, true, made_up).as_deref(), Some("luxe/session-made"));
assert_eq!(worktree_branch(None, None, false, made_up), None, "nobody asked");
}
#[test]
fn a_made_up_branch_is_short_and_says_whose_it_is() {
let branch = generated_branch();
assert!(branch.starts_with("luxe/session-") && branch.len() == "luxe/session-".len() + 8);
assert_ne!(generated_branch(), branch);
}
#[test]
fn the_worktree_notice_says_where_what_from_and_what_is_untouched() {
let made = |base: Option<&str>, created, fetch_failed| luxe_core::worktree::SessionWorktree {
path: std::path::PathBuf::from("/work/app/.luxe/worktrees/topic"),
branch: "topic".into(),
base: base.map(str::to_string),
created,
fetch_failed,
};
let project = std::path::Path::new("/work/app");
let fresh = worktree_notice(&made(Some("origin/main"), true, false), project);
assert_eq!(
fresh,
"Working in the session's own worktree, `.luxe/worktrees/topic` on branch `topic`, made \
from `origin/main`. Your checkout is untouched; `/worktree` says more."
);
let offline = worktree_notice(&made(Some("origin/main"), true, true), project);
assert!(offline.contains("as last fetched: the remote could not be reached"), "{offline}");
let rebuilt = worktree_notice(&made(None, true, false), project);
assert!(rebuilt.contains("made again from its branch"), "{rebuilt}");
let found = worktree_notice(&made(None, false, false), project);
assert!(found.contains("on branch `topic`. Your checkout"), "{found}");
}

View File

@@ -0,0 +1,344 @@
//! The TUI run — dashboard, engine, main loop, and what to do when it exits.
use super::auth_service;
use super::worktree::{
check_out_pull_request, enter_session_worktree, remove_worktree, take_up_issue_in_worktree,
};
/// The one line under the dashboard, or nothing.
fn footer_note(repo_root: &std::path::Path) -> Option<String> {
crate::update_check::cached_notice(repo_root).map(|notice| notice.line())
}
/// Whether the startup dashboard should be shown.
///
/// Suppressed when resuming, when the session already has its work — `--issue` or `--pr` said
/// what it is for, so a menu of other things to do is in the way — or when the config sets
/// `dashboard = false`.
pub(super) fn should_show_dashboard(
config: &luxe_core::config::Config,
resume: &crate::engine_setup::ResumeMode,
started_on_work: bool,
) -> bool {
if *resume != crate::engine_setup::ResumeMode::New || started_on_work {
return false;
}
config.dashboard_shown()
}
/// Run the TUI mode against a fully-wired engine.
///
/// The loop exists for the one exit that comes back: opening a file in `$EDITOR` and returning to
/// the surface that asked. Everything else leaves the process, and the project a run works on is
/// fixed the moment [`super::enter_project`] answers.
pub(super) async fn run_tui(
mut settings: crate::engine_setup::AgentSettings,
) -> anyhow::Result<()> {
use luxe_core::config::Config;
use luxe_tui::main_loop::{self, Opening};
let mut show_dashboard = should_show_dashboard(
&Config::load(&settings.state_root),
&settings.resume,
settings.issue.is_some() || settings.pull_request.is_some(),
);
let mut carried = Carried::default();
loop {
let dashboard = match show_dashboard {
true => Some(open_dashboard(&settings).await),
false => {
tracing::info!(resume = ?settings.resume, "skipping dashboard");
None
}
};
let status = starting_status(&settings).await;
let catalogs = main_loop::Catalogs {
models: model_menu_sources(&settings),
sessions: Some(session_catalog_source(&settings)),
};
let crate::engine_setup::EngineHandle {
actions: engine_tx,
events: engine_rx,
closer,
session_id,
} = start_engine(&settings).await?;
let event_rx = crate::workspace_runtime::bridge(
engine_rx,
crate::workspace_runtime::Roots {
state: settings.state_root.clone(),
work: settings.work_root.clone(),
},
crate::workspace_runtime::pull_request_watch(&settings.work_root),
);
let exit = main_loop::run(
event_rx,
engine_tx.clone(),
status,
match (carried.fixing.take(), dashboard, carried.resumed.take()) {
(Some(launch), _, _) => Opening::FixPullRequest(launch),
(None, Some(dashboard), _) => Opening::Dashboard(Box::new(dashboard)),
(None, None, Some(launch)) => Opening::Resumed(launch),
(None, None, None) => Opening::Chat,
},
catalogs,
Some(auth_service()),
false,
)
.await;
// The next engine, whichever session it runs, starts where this one was
settings.carryover = closer.close(&engine_tx).await;
if let Some(carryover) = &settings.carryover {
settings.auto_approve = carryover.auto_approves();
}
let mut next = Next { settings: &mut settings, show_dashboard: &mut show_dashboard };
match next.after(exit?, session_id, &mut carried).await? {
Flow::Leave => return Ok(()),
Flow::Again => {}
}
}
}
/// What one lap of the loop hands the next.
#[derive(Default)]
struct Carried {
/// A pull request checked out to fix, with the comments that go with it
fixing: Option<luxe_tui::main_loop::FixLaunch>,
/// What the reader carried out of the session or start screen they left for another
resumed: Option<luxe_tui::main_loop::ResumeLaunch>,
}
/// What the loop does once the surface has exited.
enum Flow {
/// The process is done
Leave,
/// Another session, or this one again
Again,
}
/// The state a TUI exit changes before the next lap: which session runs, and whether it opens on
/// the dashboard.
struct Next<'a> {
settings: &'a mut crate::engine_setup::AgentSettings,
show_dashboard: &'a mut bool,
}
impl Next<'_> {
/// Settles an exit: quit, or the session to carry on with.
///
/// A session that cannot be started leaves this one running with a notice saying why, rather
/// than taking the reader out of the TUI.
async fn after(
&mut self,
exit: luxe_tui::main_loop::TuiExit,
session_id: luxe_core::SessionId,
carried: &mut Carried,
) -> anyhow::Result<Flow> {
use crate::engine_setup::ResumeMode;
use luxe_tui::main_loop::TuiExit;
match exit {
TuiExit::Quit => {
// Graceful LSP `shutdown`+`exit` before the process ends (kinder than the bare
// kill_on_drop for servers like clangd/gopls); bounded so a stuck server can't
// hang quit.
shutdown_workspace_services().await;
return Ok(Flow::Leave);
}
TuiExit::RemoveWorktree(path) => {
shutdown_workspace_services().await;
remove_worktree(&self.settings.state_root, &path).await;
return Ok(Flow::Leave);
}
TuiExit::TakeUpIssue(number) => {
// A new session on the issue, in its worktree; the one left stays as it was
shutdown_workspace_services().await;
let mut next = self.fresh(ResumeMode::New);
match take_up_issue_in_worktree(number, &mut next).await {
Ok(()) => *self.settings = next,
Err(error) => self.carry_on(
session_id,
format!(
"A session on issue #{number} could not start, so this one carries \
on: {error:#}."
),
),
}
}
TuiExit::ResumeSession(launch) => {
// Another of your sessions, in its own worktree when it has one
shutdown_workspace_services().await;
let mut next = self.fresh(ResumeMode::Session(launch.session.clone()));
match enter_session_worktree(&launch.session, &mut next).await {
Ok(()) => *self.settings = next,
Err(error) => self.carry_on(
session_id,
format!(
"That session could not be resumed, so this one carries on: \
{error:#}."
),
),
}
// Whichever session runs, it takes up what the reader carried
carried.resumed = Some(launch);
}
TuiExit::FixPullRequest(launch) => {
// A new session, in the pull request's worktree; the one left stays as it was
shutdown_workspace_services().await;
let mut next = self.fresh(ResumeMode::New);
match check_out_pull_request(launch.number, &mut next).await {
Ok(()) => {
*self.settings = next;
carried.fixing = Some(launch);
}
Err(error) => self.carry_on(
session_id,
format!(
"Pull request #{} could not be checked out, so this session carries \
on: {error:#}.",
launch.number
),
),
}
}
TuiExit::OpenInEditor(path) => {
let path = crate::config_editor::open_config_file(path).await?;
tracing::info!(path = %path.display(), "editor closed");
let config = luxe_core::config::Config::load(&self.settings.state_root);
*self.show_dashboard = config.dashboard_shown();
}
}
Ok(Flow::Again)
}
/// The settings for a session that starts over: none of the last one's startup notices,
/// issue, pull request or worktree, and no dashboard in the way.
fn fresh(
&mut self,
resume: crate::engine_setup::ResumeMode,
) -> crate::engine_setup::AgentSettings {
*self.show_dashboard = false;
crate::engine_setup::AgentSettings {
resume,
startup_notices: Vec::new(),
issue: None,
pull_request: None,
worktree: None,
..self.settings.clone()
}
}
/// Stays on the session that was running, saying why the other one did not start.
fn carry_on(&mut self, session: luxe_core::SessionId, notice: String) {
self.settings.resume = crate::engine_setup::ResumeMode::Session(session.0);
self.settings.startup_notices = vec![notice];
}
}
/// The dashboard's state: recent work, the sessions to resume, and the one line under it.
async fn open_dashboard(
settings: &crate::engine_setup::AgentSettings,
) -> luxe_tui::dashboard::DashboardState {
let store = crate::engine_setup::open_session_store(&settings.state_root);
let data = crate::dashboard_data::collect(store, &settings.state_root).await;
luxe_tui::dashboard::DashboardState::new(data.recent)
.with_sessions(data.sessions)
.with_worktree(settings.worktree.as_ref().map(|binding| binding.branch.clone()))
.with_resume(data.resume)
.with_briefing(data.briefing)
.with_footer_note(footer_note(&settings.state_root))
}
/// What the status bar shows before the first turn.
///
/// The bar reports the model when there is one and stays quiet about it when there is not; the
/// provider and the window belong to whatever a turn would actually run on, which is the
/// stand-in's catalog metadata until something is chosen.
async fn starting_status(
settings: &crate::engine_setup::AgentSettings,
) -> luxe_tui::statusline::StatusContext {
let launch = settings.launch_model();
crate::status_data::collect(
&settings.work_root,
settings.display_model(),
launch.r#ref.provider.clone(),
launch.context_window,
settings.starting_thinking(),
settings.auto_approve,
)
.await
}
/// Where the `/model` picker gets its list.
///
/// Rebuilt on every open, so an edited `models.json` or a models.dev refresh that landed
/// mid-session shows up without relaunching. The probe is the same menu built after asking every
/// connected local server what it is serving — a list that changes the moment somebody loads a
/// model, and that only the endpoint knows. An Azure resource is the same question asked of a
/// cloud: what is deployed there changes in a portal Luxe never sees. A server that is off leaves
/// the record standing.
fn model_menu_sources(
settings: &crate::engine_setup::AgentSettings,
) -> luxe_tui::model_picker::ModelSources {
let menu_settings = settings.clone();
let build: luxe_tui::model_picker::ModelMenuSource =
std::sync::Arc::new(move || crate::model_catalog::build_menu(&menu_settings));
let probe_settings = settings.clone();
let probe: luxe_tui::model_picker::ModelMenuProbe = std::sync::Arc::new(move || {
let settings = probe_settings.clone();
Box::pin(async move {
let auth = luxe_providers::auth::ProviderAuth::new();
tokio::join!(auth.refresh_local_models(), auth.refresh_deployments());
crate::model_catalog::build_menu(&settings)
})
});
luxe_tui::model_picker::ModelSources { build, probe: Some(probe) }
}
/// Where `/sessions` gets its list mid-session: the same catalog the start screen reads, read
/// again each time so it includes the sessions started since launch.
fn session_catalog_source(
settings: &crate::engine_setup::AgentSettings,
) -> luxe_tui::dashboard::SessionCatalogSource {
let state_root = settings.state_root.clone();
std::sync::Arc::new(move || {
let store = crate::engine_setup::open_session_store(&state_root);
Box::pin(crate::dashboard_data::session_catalog(store))
})
}
/// Builds the engine and applies the launch flags that are the engine's to carry.
async fn start_engine(
settings: &crate::engine_setup::AgentSettings,
) -> anyhow::Result<crate::engine_setup::EngineHandle> {
use luxe_core::engine::Action;
let engine = crate::engine_setup::build_engine(
settings,
luxe_core::HookRegistry::new(),
luxe_core::permission::AskResolution::Prompt,
)
.await?;
if let Some(level) = settings.initial_thinking.filter(|_| settings.carryover.is_none()) {
engine.actions.send(Action::SetThinkingLevel(level)).await.ok();
}
// Walk-away mode from launch: the engine's runtime override, the same one `/permissions on`
// reaches, so the reader can turn it back off without restarting.
if settings.auto_approve {
engine.actions.send(Action::SetPermissionAutoApprove(true)).await.ok();
}
Ok(engine)
}
/// Shut down the process-wide warm LSP servers + live debug sessions. Bounded overall so a
/// misbehaving server can't wedge quit.
pub(super) async fn shutdown_workspace_services() {
let shutdown = async {
crate::engine_setup::build_lsp_service().shutdown_all().await;
crate::engine_setup::shared_dap_service().terminate_all().await;
};
if tokio::time::timeout(std::time::Duration::from_secs(6), shutdown).await.is_err() {
tracing::warn!("workspace service shutdown timed out; relying on kill-on-drop reaping");
}
}

View File

@@ -0,0 +1,76 @@
//! `luxe wire` — audit a `LUXE_WIRE_LOG` capture.
//!
//! Answers the questions you cannot answer by reading source: what exactly did we send, how big was
//! each part of it, does the cacheable prefix actually stay byte-identical between turns, is
//! anything sent twice, and did a credential leak into the payload.
//!
//! Section sizes are reported in characters and in tokens *calibrated against the run itself* — the
//! provider tells us `prompt_tokens` for a body we can measure, so the chars-per-token ratio is
//! measured rather than guessed.
use super::args::WireArgs;
mod cache;
mod call;
mod secrets;
mod sections;
use cache::{cache_stability, transitions};
use call::{load, Call};
use sections::{chars_per_token, composition, duplication, overview, streaming};
/// Run `luxe wire`.
pub(crate) fn run_wire_command(args: WireArgs) -> anyhow::Result<()> {
let text = std::fs::read_to_string(&args.log)
.map_err(|error| anyhow::anyhow!("cannot read {}: {error}", args.log.display()))?;
let calls = load(&text);
if calls.is_empty() {
anyhow::bail!(
"no provider calls in {} — run a turn with LUXE_WIRE_LOG set to that path first",
args.log.display()
);
}
let mut out = String::new();
let ratio = chars_per_token(&calls);
let churn = transitions(&calls);
overview(&mut out, &calls, ratio, &warnings(&calls, &churn));
composition(&mut out, &calls, ratio, args.tools);
cache_stability(&mut out, &calls, &churn);
duplication(&mut out, &calls);
streaming(&mut out, &calls);
secrets::report(&mut out, &text);
crate::output::write(&out);
Ok(())
}
/// The audit's verdict: the problems worth acting on, in one place at the top.
fn warnings(calls: &[Call], churn: &[Vec<String>]) -> Vec<String> {
let mut warnings = Vec::new();
let unstable = churn.iter().filter(|reasons| !reasons.is_empty()).count();
if unstable > 0 {
warnings.push(format!(
"▲ the cacheable prefix changes on {unstable} of {} transition(s)",
calls.len().saturating_sub(1)
));
}
if let Some(call) = calls.last() {
let total = call.context_chars().max(1);
let tools: usize = call.tool_entries().iter().map(|(_, _, j)| j.chars().count()).sum();
let system = call.system().unwrap_or_default().chars().count();
let overhead = (tools + system) as f64 / total as f64 * 100.0;
if overhead > 80.0 {
warnings.push(format!(
"▲ {overhead:.0}% of the last request is fixed overhead (tools + system), not conversation"
));
}
}
if warnings.is_empty() {
warnings.push("no structural problems found".to_string());
}
warnings
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,99 @@
//! Cache stability — whether each request appends to the last or rewrites what a cache holds.
use std::fmt::Write as _;
use super::call::Call;
/// What changed from each request to the next, in the order of the log — one entry per
/// transition, empty where the prefix held.
pub(super) fn transitions(calls: &[Call]) -> Vec<Vec<String>> {
calls.windows(2).map(|pair| prefix_changes(&pair[0], &pair[1])).collect()
}
/// Does the cacheable prefix actually stay identical between turns?
///
/// Every provider that caches does it by prefix: the tools and system prompt come first, so one
/// changed byte in either throws away the whole cached prefix — and cache pricing means that is a
/// silent bill, not an error. This is the check that catches volatile state (a git dirty flag, a
/// todo counter, a timestamp) sitting inside the cached region.
pub(super) fn cache_stability(out: &mut String, calls: &[Call], transitions: &[Vec<String>]) {
if calls.len() < 2 {
return;
}
let _ = writeln!(out, "## Cache prefix stability\n");
let mut unstable = 0usize;
for (pair, reasons) in calls.windows(2).zip(transitions) {
let (before, after) = (&pair[0], &pair[1]);
let verdict = if reasons.is_empty() {
"stable".to_string()
} else {
unstable += 1;
reasons.join(" · ")
};
let _ = writeln!(out, " #{} → #{}: {}", before.index, after.index, verdict);
}
if unstable > 0 {
let _ = writeln!(
out,
"\n ▲ {unstable} transition(s) invalidate the cached prefix. Everything after the\n \
first changed byte has to be re-read (and re-billed) by the provider."
);
}
let _ = writeln!(out);
}
/// Everything about `after` that a cache cannot reuse from `before`, in prefix order.
///
/// The conversation is checked as well as the prefix above it: a transcript is only cacheable if
/// each request *appends* to the last one, and a harness that edits history in flight —
/// re-truncating an old tool result, dropping a stale image — re-bills every token after the edit
/// at the cache-write rate with nothing to show for it.
pub(super) fn prefix_changes(before: &Call, after: &Call) -> Vec<String> {
let mut reasons = Vec::new();
if before.system() != after.system() {
reasons.push(format!(
"system CHANGED{}",
first_difference(
before.system().unwrap_or_default(),
after.system().unwrap_or_default()
)
));
}
// Only the loaded tools: a deferred definition sits outside the cached prefix, so adding or
// changing one costs nothing
if before.loaded_tools() != after.loaded_tools() {
reasons.push("tools CHANGED".to_string());
}
let (was, now) = (before.cached_messages(), after.cached_messages());
if let Some(at) = was.iter().zip(now.iter()).position(|(a, b)| a != b) {
let resent: usize = was[at..].iter().map(|m| m.chars().count()).sum();
reasons.push(format!(
"conversation REWRITTEN at message {at}/{} (~{} tok re-sent){}",
was.len(),
resent / 4,
first_difference(&was[at], &now[at])
));
}
reasons
}
/// Drop every `cache_control` marker from a message, however deeply nested.
pub(super) fn strip_cache_control(value: &mut serde_json::Value) {
match value {
serde_json::Value::Object(map) => {
map.remove("cache_control");
map.values_mut().for_each(strip_cache_control);
}
serde_json::Value::Array(items) => items.iter_mut().for_each(strip_cache_control),
_ => {}
}
}
/// Where two strings first differ, as a short quoted excerpt.
pub(super) fn first_difference(before: &str, after: &str) -> String {
let common = before.char_indices().zip(after.chars()).take_while(|((_, a), b)| a == b).count();
let excerpt = |text: &str| -> String {
text.chars().skip(common).take(48).collect::<String>().replace('\n', "⏎")
};
format!(" at char {common}: {:?} → {:?}", excerpt(before), excerpt(after))
}

View File

@@ -0,0 +1,202 @@
//! The captured calls — one provider request with what came back, read out of the log.
use std::collections::BTreeMap;
use super::cache::strip_cache_control;
/// One captured provider call: the request body plus whatever came back.
pub(super) struct Call {
/// Position in the log. The provider's own call id restarts per process, so a log stitched
/// from several `luxe` invocations would otherwise show `#0` three times.
pub(super) index: usize,
pub(super) provider: String,
pub(super) url: String,
pub(super) body: serde_json::Value,
pub(super) response: Option<serde_json::Value>,
/// The conversation, read out of `body` once: every section asks for it again
messages: Vec<serde_json::Value>,
/// The system prompt, whichever shape this API uses for it, found once
system: Option<String>,
}
impl Call {
pub(super) fn model(&self) -> &str {
self.body.get("model").and_then(|m| m.as_str()).unwrap_or("?")
}
/// The `## Tools` section of the system prompt, where tool guidance belongs.
pub(super) fn tools_section(&self) -> String {
let system = self.system().unwrap_or_default();
let Some(start) = system.find("## Tools") else { return String::new() };
let rest = &system[start..];
let end = rest[8..].find("\n## ").map(|at| at + 8).unwrap_or(rest.len());
rest[..end].to_string()
}
pub(super) fn new(
index: usize,
provider: String,
url: String,
body: serde_json::Value,
response: Option<serde_json::Value>,
) -> Self {
let messages = messages_of(&body);
let system = system_of(&body, &messages);
Self { index, provider, url, body, response, messages, system }
}
/// The system prompt, whichever shape this API uses for it.
pub(super) fn system(&self) -> Option<&str> {
self.system.as_deref()
}
pub(super) fn messages(&self) -> &[serde_json::Value] {
&self.messages
}
/// The conversation as a cache sees it: one rendering per message, with the breakpoint markers
/// stripped. `cache_control` is metadata rather than content, and the rolling one is *supposed*
/// to move every turn — comparing it would report churn on every transition and hide the real
/// thing this is looking for.
pub(super) fn cached_messages(&self) -> Vec<String> {
self.messages()
.iter()
.map(|message| {
let mut message = message.clone();
strip_cache_control(&mut message);
serde_json::to_string(&message).unwrap_or_default()
})
.collect()
}
pub(super) fn tools(&self) -> Vec<serde_json::Value> {
self.body.get("tools").and_then(|v| v.as_array()).cloned().unwrap_or_default()
}
/// The tools the model actually has in context: every one but those sent with Anthropic's
/// `defer_loading`, which load only where a `tool_reference` asks for them.
pub(super) fn loaded_tools(&self) -> Vec<serde_json::Value> {
self.tools().into_iter().filter(|tool| !is_deferred(tool)).collect()
}
/// `(name, description, whole-schema-json)` per loaded tool, across all three wire shapes.
pub(super) fn tool_entries(&self) -> Vec<(String, String, String)> {
entries(&self.loaded_tools())
}
/// [`Self::tool_entries`] for the deferred tools: on the wire, outside the context.
pub(super) fn deferred_entries(&self) -> Vec<(String, String, String)> {
entries(&self.tools().into_iter().filter(is_deferred).collect::<Vec<_>>())
}
pub(super) fn body_chars(&self) -> usize {
serde_json::to_string(&self.body).map(|s| s.chars().count()).unwrap_or(0)
}
/// [`Self::body_chars`] less the deferred tool definitions, which the provider doesn't bill.
pub(super) fn context_chars(&self) -> usize {
let deferred: usize =
self.deferred_entries().iter().map(|(_, _, json)| json.chars().count()).sum();
self.body_chars().saturating_sub(deferred)
}
pub(super) fn prompt_tokens(&self) -> Option<u64> {
self.response
.as_ref()?
.get("usage")?
.get("prompt_tokens")
.and_then(serde_json::Value::as_u64)
}
}
/// The messages of a request, whichever key this API keeps them under.
fn messages_of(body: &serde_json::Value) -> Vec<serde_json::Value> {
for key in ["messages", "input"] {
if let Some(list) = body.get(key).and_then(|v| v.as_array()) {
return list.clone();
}
}
Vec::new()
}
/// The system prompt of a request, in whichever of the three shapes it was sent.
fn system_of(body: &serde_json::Value, messages: &[serde_json::Value]) -> Option<String> {
// Responses API: a top-level `instructions` string.
if let Some(text) = body.get("instructions").and_then(|v| v.as_str()) {
return Some(text.to_string());
}
// Anthropic: `system` as a string or as content blocks.
match body.get("system") {
Some(serde_json::Value::String(text)) => return Some(text.clone()),
Some(serde_json::Value::Array(blocks)) => {
let joined: String = blocks
.iter()
.filter_map(|block| block.get("text").and_then(|t| t.as_str()))
.collect::<Vec<_>>()
.join("");
if !joined.is_empty() {
return Some(joined);
}
}
_ => {}
}
// Chat completions: a leading `system` message.
messages
.iter()
.find(|m| m.get("role").and_then(|r| r.as_str()) == Some("system"))
.and_then(|m| m.get("content").and_then(|c| c.as_str()))
.map(str::to_string)
}
/// Whether a tool definition is sent with Anthropic's `defer_loading`.
pub(super) fn is_deferred(tool: &serde_json::Value) -> bool {
tool.get("defer_loading").and_then(serde_json::Value::as_bool) == Some(true)
}
/// `(name, description, whole-schema-json)` per tool, across all three wire shapes.
pub(super) fn entries(tools: &[serde_json::Value]) -> Vec<(String, String, String)> {
tools
.iter()
.map(|tool| {
// Chat completions nests under `function`; Responses and Anthropic are flat.
let inner = tool.get("function").unwrap_or(tool);
let name = inner.get("name").and_then(|v| v.as_str()).unwrap_or("?").to_string();
let description =
inner.get("description").and_then(|v| v.as_str()).unwrap_or("").to_string();
let json = serde_json::to_string(tool).unwrap_or_default();
(name, description, json)
})
.collect()
}
/// Read the JSONL log, pairing each request with its response by call id.
pub(super) fn load(text: &str) -> Vec<Call> {
let mut calls: Vec<Call> = Vec::new();
let mut index: BTreeMap<u64, usize> = BTreeMap::new();
for line in text.lines().filter(|line| !line.trim().is_empty()) {
let Ok(record) = serde_json::from_str::<serde_json::Value>(line) else { continue };
let id = record.get("call").and_then(serde_json::Value::as_u64).unwrap_or(0);
let kind = record.get("kind").and_then(|k| k.as_str()).unwrap_or("");
match kind {
"request" => {
index.insert(id, calls.len());
calls.push(Call::new(
calls.len() + 1,
record.get("provider").and_then(|p| p.as_str()).unwrap_or("?").to_string(),
record.get("url").and_then(|u| u.as_str()).unwrap_or("").to_string(),
record.get("body").cloned().unwrap_or(serde_json::Value::Null),
None,
));
}
"response" => {
if let Some(position) = index.get(&id) {
if let Some(call) = calls.get_mut(*position) {
call.response = Some(record);
}
}
}
_ => {}
}
}
calls
}

View File

@@ -0,0 +1,51 @@
//! Secrets — nothing that looks like a live credential may reach the log.
use std::fmt::Write as _;
/// Credential prefixes worth scanning for, each followed by enough key material to be real.
const SECRET_PREFIXES: &[&str] = &["sk-", "sk_live_", "ghp_", "gho_", "xoxb-", "AKIA", "Bearer "];
/// Minimum run of key-shaped characters after a prefix before it counts as a credential.
///
/// Without this, reading Luxe's own `redact.rs` — whose source *contains* every prefix — reports a
/// leak on every audit. The prefix alone is prose; the prefix plus a key is a secret.
const SECRET_BODY: usize = 16;
/// Whether `text` contains something shaped like a live credential.
pub(super) fn looks_like_credential(text: &str) -> Option<String> {
for prefix in SECRET_PREFIXES {
for (at, _) in text.match_indices(prefix) {
let tail: String = text[at + prefix.len()..]
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
.collect();
if tail.chars().count() >= SECRET_BODY {
let shown: String = tail.chars().take(4).collect();
return Some(format!("{prefix}{shown}… ({} chars)", tail.chars().count()));
}
}
}
None
}
/// Nothing that looks like a live credential may reach the log.
pub(super) fn report(out: &mut String, text: &str) {
let _ = writeln!(out, "## Secrets\n");
let mut hits = Vec::new();
for (line_number, line) in text.lines().enumerate() {
if let Some(hit) = looks_like_credential(line) {
hits.push(format!("line {}: {hit}", line_number + 1));
}
}
if hits.is_empty() {
let _ = writeln!(
out,
" clean — no credential-shaped value in any request, header, or reply\n"
);
} else {
for hit in hits.iter().take(10) {
let _ = writeln!(out, " ▲ {hit}");
}
let _ = writeln!(out);
}
}

View File

@@ -0,0 +1,257 @@
//! Report sections — sizes, composition, duplication and streaming, one per question the log answers.
use std::collections::BTreeMap;
use std::fmt::Write as _;
use super::call::Call;
/// Characters per token, measured from the run: total request characters over reported prompt
/// tokens. Falls back to the usual ~4 when nothing reported usage.
pub(super) fn chars_per_token(calls: &[Call]) -> f64 {
let (chars, tokens) =
calls.iter().fold((0usize, 0u64), |(chars, tokens), call| match call.prompt_tokens() {
Some(reported) if reported > 0 => (chars + call.context_chars(), tokens + reported),
_ => (chars, tokens),
});
if tokens == 0 {
return 4.0;
}
(chars as f64 / tokens as f64).max(1.0)
}
pub(super) fn tokens(chars: usize, ratio: f64) -> u64 {
(chars as f64 / ratio).round() as u64
}
pub(super) fn size(chars: usize, ratio: f64, total: usize) -> String {
let share = if total == 0 { 0.0 } else { chars as f64 / total as f64 * 100.0 };
format!("{:>7} ch ~{:>6} tok {:>5.1}%", chars, tokens(chars, ratio), share)
}
pub(super) fn overview(out: &mut String, calls: &[Call], ratio: f64, verdict: &[String]) {
let _ = writeln!(out, "# Wire audit\n");
let _ = writeln!(out, "{}\n", verdict.join("\n"));
let _ = writeln!(
out,
"{} provider call(s) · {} · model {} · ~{:.2} chars/token (measured)\n{}\n",
calls.len(),
calls[0].provider,
calls[0].model(),
ratio,
calls[0].url,
);
// `written` sits beside `cached` because the pair is the whole story and either alone misleads:
// a prefix rewritten every turn reads most of itself straight back, so a healthy-looking
// `cached` column can sit on top of a bill that is almost entirely writes.
let _ = writeln!(
out,
"{:<5} {:>8} {:>9} {:>8} {:>8} {:>8} {:>9} {:>8}",
"call", "req ch", "prompt", "cached", "written", "output", "first ms", "total ms"
);
for call in calls {
let usage = call.response.as_ref().and_then(|r| r.get("usage"));
let field = |name: &str| {
usage.and_then(|u| u.get(name)).and_then(serde_json::Value::as_u64).unwrap_or(0)
};
let first = call
.response
.as_ref()
.and_then(|r| r.get("first_delta_ms"))
.and_then(serde_json::Value::as_u64);
let elapsed = call
.response
.as_ref()
.and_then(|r| r.get("elapsed_ms"))
.and_then(serde_json::Value::as_u64)
.unwrap_or(0);
let _ = writeln!(
out,
"{:<5} {:>8} {:>9} {:>8} {:>8} {:>8} {:>9} {:>8}",
call.index,
call.body_chars(),
field("prompt_tokens"),
field("cache_read_tokens"),
field("cache_write_tokens"),
field("completion_tokens"),
first.map(|ms| ms.to_string()).unwrap_or_else(|| "-".into()),
elapsed,
);
}
let _ = writeln!(out);
}
/// Where the request's characters actually go, for the first call (the leanest one) and the last.
pub(super) fn composition(out: &mut String, calls: &[Call], ratio: f64, per_tool: bool) {
for (label, call) in [("first", calls.first()), ("last", calls.last())] {
let Some(call) = call else { continue };
if calls.len() == 1 && label == "last" {
continue;
}
let total = call.body_chars();
let _ = writeln!(out, "## Composition — {label} call (#{}) · {total} chars\n", call.index);
let system = call.system().unwrap_or_default();
let system_chars = system.chars().count();
let tool_entries = call.tool_entries();
let tool_chars: usize = tool_entries.iter().map(|(_, _, json)| json.chars().count()).sum();
let deferred_entries = call.deferred_entries();
let deferred_chars: usize =
deferred_entries.iter().map(|(_, _, json)| json.chars().count()).sum();
let message_chars: usize = call
.messages()
.iter()
.filter(|m| m.get("role").and_then(|r| r.as_str()) != Some("system"))
.map(|m| serde_json::to_string(m).map(|s| s.chars().count()).unwrap_or(0))
.sum();
let other =
total.saturating_sub(system_chars + tool_chars + deferred_chars + message_chars);
let _ = writeln!(out, " system prompt {}", size(system_chars, ratio, total));
for (heading, chars) in system_sections(system) {
let _ = writeln!(out, " {:<22} {}", heading, size(chars, ratio, total));
}
let _ = writeln!(
out,
" tool schemas {} ({} tools)",
size(tool_chars, ratio, total),
tool_entries.len()
);
if per_tool {
let mut sorted = tool_entries.clone();
sorted.sort_by_key(|(_, _, json)| std::cmp::Reverse(json.chars().count()));
for (name, _, json) in sorted {
let _ =
writeln!(out, " {:<22} {}", name, size(json.chars().count(), ratio, total));
}
}
// On the wire but not in the context: the provider bills none of it until a
// `tool_reference` loads one, so it's counted apart rather than as overhead
if !deferred_entries.is_empty() {
let _ = writeln!(
out,
" deferred tools {:>7} ch ({} tools, outside the context until loaded)",
deferred_chars,
deferred_entries.len()
);
}
let _ = writeln!(out, " conversation {}", size(message_chars, ratio, total));
for message in call.messages() {
let role = message.get("role").and_then(|r| r.as_str()).unwrap_or("item");
if role == "system" {
continue;
}
let chars = serde_json::to_string(&message).map(|s| s.chars().count()).unwrap_or(0);
let _ = writeln!(out, " {:<22} {}", role, size(chars, ratio, total));
}
let _ = writeln!(out, " wire overhead {}\n", size(other, ratio, total));
}
}
/// Split a system prompt into its `## Heading` sections with their sizes.
pub(super) fn system_sections(system: &str) -> Vec<(String, usize)> {
let mut sections: Vec<(String, usize)> = Vec::new();
let mut current = String::from("(preamble)");
let mut chars = 0usize;
for line in system.lines() {
if let Some(heading) = line.strip_prefix("## ") {
if chars > 0 {
sections.push((current.clone(), chars));
}
current = heading.trim().to_string();
chars = line.chars().count() + 1;
} else {
chars += line.chars().count() + 1;
}
}
if chars > 0 {
sections.push((current, chars));
}
sections
}
/// Content sent more than once in a single request.
pub(super) fn duplication(out: &mut String, calls: &[Call]) {
let Some(call) = calls.last() else { return };
let _ = writeln!(out, "## Duplication — last call (#{})\n", call.index);
let system = call.system().unwrap_or_default();
let mut findings = Vec::new();
// A tool's description repeated in the prompt is the classic double-send. Scoped to the
// `## Tools` section for the re-listing check: `**git**:` also appears in the environment
// line and in any AGENTS.md that uses bold labels, and flagging those is noise.
let tools_section = call.tools_section();
for (name, description, _) in call.tool_entries() {
let head: String = description.chars().take(60).collect();
if head.chars().count() > 20 && system.contains(head.trim()) {
findings.push(format!("tool `{name}` description also appears in the system prompt"));
}
if tools_section.contains(&format!("**{name}**:")) {
findings.push(format!("tool `{name}` is re-listed in the system prompt"));
}
}
// The same tool result twice means the model paid for the same file/output twice.
let mut seen: BTreeMap<String, usize> = BTreeMap::new();
for message in call.messages() {
let text = serde_json::to_string(&message).unwrap_or_default();
if text.chars().count() < 200 {
continue;
}
*seen.entry(text).or_default() += 1;
}
for (text, count) in seen.iter().filter(|(_, count)| **count > 1) {
let head: String = text.chars().take(70).collect();
findings
.push(format!("a {}-char message is sent {count}× — {head}…", text.chars().count()));
}
if findings.is_empty() {
let _ = writeln!(out, " none found\n");
} else {
for finding in findings {
let _ = writeln!(out, " ▲ {finding}");
}
let _ = writeln!(out);
}
}
/// Did text actually arrive incrementally, or all at once at the end?
pub(super) fn streaming(out: &mut String, calls: &[Call]) {
let _ = writeln!(out, "## Streaming\n");
for call in calls {
let Some(response) = &call.response else { continue };
let arrival: Vec<(u128, usize)> = response
.get("arrival")
.and_then(|a| a.as_array())
.map(|list| {
list.iter()
.filter_map(|entry| {
let pair = entry.as_array()?;
Some((pair.first()?.as_u64()? as u128, pair.get(1)?.as_u64()? as usize))
})
.collect()
})
.unwrap_or_default();
if arrival.is_empty() {
let _ = writeln!(out, " #{}: no deltas (tool-only or empty reply)", call.index);
continue;
}
let first = arrival.first().map(|(ms, _)| *ms).unwrap_or(0);
let last = arrival.last().map(|(ms, _)| *ms).unwrap_or(0);
let span = last.saturating_sub(first).max(1);
let gaps: Vec<u128> =
arrival.windows(2).map(|pair| pair[1].0.saturating_sub(pair[0].0)).collect();
let max_gap = gaps.iter().copied().max().unwrap_or(0);
let _ = writeln!(
out,
" #{}: {} deltas over {} ms (first at {} ms, max gap {} ms) — {}",
call.index,
arrival.len(),
span,
first,
max_gap,
if arrival.len() > 1 && span > 5 { "incremental" } else { "arrived as one chunk" }
);
}
let _ = writeln!(out);
}

View File

@@ -0,0 +1,220 @@
use super::cache::{cache_stability, transitions};
use super::secrets::looks_like_credential;
use super::sections::system_sections;
use super::*;
/// [`cache_stability`] over the transitions of `calls`.
fn stability(out: &mut String, calls: &[Call]) {
cache_stability(out, calls, &transitions(calls));
}
fn call(id: u64, system: &str, tools: serde_json::Value) -> Call {
let body = serde_json::json!({
"model": "m",
"messages": [{"role": "system", "content": system}, {"role": "user", "content": "hi"}],
"tools": tools,
});
Call::new(id as usize + 1, "test".into(), String::new(), body, None)
}
/// A call with `body` as it was sent.
fn with_body(body: serde_json::Value) -> Call {
Call::new(1, "test".into(), String::new(), body, None)
}
#[test]
fn system_prompt_is_found_in_every_wire_shape() {
let chat = call(0, "SYS", serde_json::json!([]));
assert_eq!(chat.system(), Some("SYS"));
let responses = with_body(serde_json::json!({"instructions": "SYS", "input": []}));
assert_eq!(responses.system(), Some("SYS"));
let anthropic = with_body(serde_json::json!({
"system": [{"type": "text", "text": "SYS", "cache_control": {"type": "ephemeral"}}],
"messages": [],
}));
assert_eq!(anthropic.system(), Some("SYS"));
}
#[test]
fn tool_entries_read_both_the_nested_and_flat_shapes() {
let nested = call(
0,
"",
serde_json::json!([{"type": "function", "function": {"name": "read", "description": "d"}}]),
);
assert_eq!(nested.tool_entries()[0].0, "read");
let flat =
call(0, "", serde_json::json!([{"type": "function", "name": "read", "description": "d"}]));
assert_eq!(flat.tool_entries()[0].0, "read");
}
/// A deferred definition is on the wire but outside the context: it isn't counted as a tool
/// the model carries, and adding one doesn't move the cached prefix.
#[test]
fn deferred_tools_are_counted_apart_and_never_break_the_prefix() {
let listed = serde_json::json!({"name": "read", "description": "Read a file."});
let deferred = |name: &str| serde_json::json!({"name": name, "description": "Rarely needed.", "defer_loading": true});
let pair = || {
(
call(0, "SYS", serde_json::json!([listed.clone(), deferred("debug")])),
call(
1,
"SYS",
serde_json::json!([listed.clone(), deferred("debug"), deferred("ast_grep")]),
),
)
};
let (before, after) = pair();
let names = |entries: Vec<(String, String, String)>| -> Vec<String> {
entries.into_iter().map(|(name, _, _)| name).collect()
};
assert_eq!(names(after.tool_entries()), vec!["read"]);
assert_eq!(names(after.deferred_entries()), vec!["debug", "ast_grep"]);
assert!(after.context_chars() < after.body_chars());
let mut out = String::new();
stability(&mut out, &[before, after]);
assert!(!out.contains("tools CHANGED"), "{out}");
let mut out = String::new();
let (before, after) = pair();
composition(&mut out, &[before, after], 4.0, false);
assert!(out.contains("(1 tools)"), "{out}");
assert!(out.contains("deferred tools") && out.contains("(2 tools, outside the context"));
}
/// One turn's messages, as an Anthropic body — with the rolling breakpoint on the last one,
/// the way the adapter really sends it.
fn conversation(messages: serde_json::Value) -> Call {
let mut body = serde_json::json!({"model": "m", "system": "SYS", "tools": []});
let mut messages = messages;
if let Some(last) = messages.as_array_mut().and_then(|list| list.last_mut()) {
last["cache_control"] = serde_json::json!({"type": "ephemeral"});
}
body["messages"] = messages;
with_body(body)
}
/// The half of the prefix nobody was watching, and the reason a real session spent 71% of its
/// cost on cache writes: the system prompt and the tools were rock solid while the harness
/// quietly re-truncated an old tool result on every single call.
#[test]
fn cache_stability_catches_a_rewritten_conversation() {
let before = conversation(serde_json::json!([
{"role": "user", "content": "a full tool result, all 4000 characters of it"},
{"role": "assistant", "content": "ok"},
]));
let after = conversation(serde_json::json!([
{"role": "user", "content": "[1000 tokens of earlier tool output elided]"},
{"role": "assistant", "content": "ok"},
{"role": "user", "content": "next"},
]));
let mut out = String::new();
stability(&mut out, &[before, after]);
assert!(out.contains("conversation REWRITTEN at message 0/2"), "{out}");
assert!(out.contains("invalidate the cached prefix"), "{out}");
}
/// Appending is the whole point, and the breakpoint marker moving with it is not a change.
#[test]
fn appending_a_turn_and_moving_the_breakpoint_is_stable() {
let before = conversation(serde_json::json!([{"role": "user", "content": "one"}]));
let after = conversation(serde_json::json!([
{"role": "user", "content": "one"},
{"role": "assistant", "content": "two"},
]));
let mut out = String::new();
stability(&mut out, &[before, after]);
assert!(out.contains("stable"), "{out}");
assert!(!out.contains('▲'), "{out}");
}
#[test]
fn cache_stability_names_the_first_changed_byte() {
let calls = vec![
call(0, "## Env\ngit: main (clean)", serde_json::json!([])),
call(1, "## Env\ngit: main (dirty)", serde_json::json!([])),
];
let mut out = String::new();
stability(&mut out, &calls);
assert!(out.contains("system CHANGED"), "{out}");
assert!(out.contains("invalidate the cached prefix"), "{out}");
assert!(out.contains("clean") && out.contains("dirty"), "shows the divergence: {out}");
}
#[test]
fn a_stable_prefix_reports_no_warning() {
let calls =
vec![call(0, "same", serde_json::json!([])), call(1, "same", serde_json::json!([]))];
let mut out = String::new();
stability(&mut out, &calls);
assert!(out.contains("stable"));
assert!(!out.contains('▲'), "{out}");
}
#[test]
fn duplication_catches_a_tool_re_listed_in_the_prompt() {
let calls = vec![call(
0,
"## Tools\n\n- **read**: Use 'read' for read",
serde_json::json!([{"type": "function", "function": {"name": "read", "description": "Read a file"}}]),
)];
let mut out = String::new();
duplication(&mut out, &calls);
assert!(out.contains("re-listed in the system prompt"), "{out}");
}
#[test]
fn a_bold_label_outside_the_tools_section_is_not_a_duplicate() {
// `**git**: main (dirty)` is the environment line, and any AGENTS.md may use bold labels.
let calls = vec![call(
0,
"## Environment\n\n**git**: main (dirty)\n\n## Tools\n\nReach for the real tool.",
serde_json::json!([{"type": "function", "function": {"name": "git", "description": "Git ops"}}]),
)];
let mut out = String::new();
duplication(&mut out, &calls);
assert!(out.contains("none found"), "{out}");
}
#[test]
fn a_credential_prefix_in_prose_is_not_a_leak_but_a_real_key_is() {
// Reading Luxe's own redact.rs puts every prefix in a tool result; that is not a leak.
assert!(looks_like_credential("patterns like sk- and ghp_ and AKIA").is_none());
assert!(looks_like_credential("Authorization: Bearer short").is_none());
let leak = looks_like_credential("key=sk-abcdefghijklmnopqrstuvwxyz0123")
.expect("a real-looking key is caught");
assert!(leak.starts_with("sk-abcd"), "{leak}");
assert!(!leak.contains("vwxyz"), "the value itself is not echoed: {leak}");
}
#[test]
fn the_verdict_names_prefix_churn_and_overhead() {
let calls = vec![call(0, "a", serde_json::json!([])), call(1, "b", serde_json::json!([]))];
let verdict = warnings(&calls, &transitions(&calls)).join("\n");
assert!(verdict.contains("cacheable prefix changes on 1"), "{verdict}");
let steady = vec![call(0, "a", serde_json::json!([])), call(1, "a", serde_json::json!([]))];
assert!(warnings(&steady, &transitions(&steady)).join("\n").contains("no structural problems"));
}
#[test]
fn system_sections_measure_each_heading() {
let sections = system_sections("## A\nline\n## B\nlonger line here\n");
let names: Vec<&str> = sections.iter().map(|(name, _)| name.as_str()).collect();
assert_eq!(names, vec!["A", "B"]);
assert!(sections[1].1 > sections[0].1);
}
#[test]
fn chars_per_token_is_measured_from_reported_usage() {
let mut call = call(0, "", serde_json::json!([]));
let chars = call.body_chars();
call.response = Some(serde_json::json!({"usage": {"prompt_tokens": chars / 4}}));
assert!((chars_per_token(&[call]) - 4.0).abs() < 0.5);
}

View File

@@ -0,0 +1,263 @@
//! Worktrees — giving a session a checkout of its own, and the issue or pull request it works on.
//!
//! Everything here runs before the engine starts, or between one session and the next in the TUI,
//! so there is one working directory for a session and nothing moves under a running tool.
use anyhow::Context;
use super::Args;
/// Moves the session into its own worktree when it has one: asked for with `--worktree`, recorded
/// by the session being resumed, or configured for every new session.
///
/// Before the engine starts, and only then, so there is one working directory for the whole
/// session and nothing moves under a running tool.
pub(super) async fn enter_worktree(
args: &Args,
settings: &mut crate::engine_setup::AgentSettings,
) -> anyhow::Result<()> {
let resumed = {
use luxe_core::session::SessionStore;
let store = crate::engine_setup::open_session_store(&settings.state_root);
crate::engine_setup::resumed_session(&store, &settings.resume)
.and_then(|session| store.load(&session).ok())
.and_then(|entries| luxe_core::session::session_worktree(&entries))
};
if let Some(number) = args.pr {
return check_out_pull_request(number, settings).await;
}
let new_session = matches!(settings.resume, crate::engine_setup::ResumeMode::New);
let always =
new_session && luxe_core::config::Config::load(&settings.state_root).worktree.always();
// An issue is taken up in a worktree of its own, on a branch named for it unless one was given
let issue_branch = match args.issue {
Some(number) => Some(take_up_issue(number, settings).await?),
None => None,
};
let flag = match (args.worktree.as_deref(), issue_branch.as_deref()) {
(None | Some(""), Some(branch)) => Some(branch),
(flag, _) => flag,
};
let Some(branch) = worktree_branch(flag, resumed, always, generated_branch) else {
return Ok(());
};
let made = luxe_core::worktree::prepare(&settings.state_root, &branch, None)
.await
.with_context(|| format!("preparing the session's worktree for `{branch}`"))?;
adopt_worktree(settings, made)
}
/// Makes `made` the session's own: entered, announced, and recorded.
fn adopt_worktree(
settings: &mut crate::engine_setup::AgentSettings,
made: luxe_core::worktree::SessionWorktree,
) -> anyhow::Result<()> {
let notice = worktree_notice(&made, &settings.state_root);
bind_worktree(settings, made.path, made.branch)?;
settings.startup_notices.push(notice);
Ok(())
}
/// Moves the process into the worktree and points the session's root and record at it.
fn bind_worktree(
settings: &mut crate::engine_setup::AgentSettings,
path: std::path::PathBuf,
branch: String,
) -> anyhow::Result<()> {
std::env::set_current_dir(&path)
.with_context(|| format!("entering the worktree {}", path.display()))?;
settings.work_root = path.clone();
settings.worktree = Some(crate::engine_setup::WorktreeBinding { branch, path });
Ok(())
}
/// Moves into the worktree session `session` works in, or back to the project when it has none.
pub(super) async fn enter_session_worktree(
session: &str,
settings: &mut crate::engine_setup::AgentSettings,
) -> anyhow::Result<()> {
use luxe_core::session::SessionStore;
let store = crate::engine_setup::open_session_store(&settings.state_root);
let entries = store
.load(&luxe_core::session::SessionId(session.to_string()))
.with_context(|| format!("reading session {session}"))?;
let Some(branch) = luxe_core::session::session_worktree(&entries) else {
std::env::set_current_dir(&settings.state_root)
.with_context(|| format!("entering {}", settings.state_root.display()))?;
settings.work_root = settings.state_root.clone();
return Ok(());
};
let made = luxe_core::worktree::prepare(&settings.state_root, &branch, None)
.await
.with_context(|| format!("finding the session's worktree for `{branch}`"))?;
adopt_worktree(settings, made)
}
/// Checks pull request `number` out in a worktree of its own and makes it the session's, refusing
/// one a push could not reach.
pub(super) async fn check_out_pull_request(
number: u64,
settings: &mut crate::engine_setup::AgentSettings,
) -> anyhow::Result<()> {
use luxe_core::github::{Branches, Discovery, PullRequestState, PullRequests};
let github = luxe_core::github::GhCli::new();
let repository = github
.repository(&settings.state_root)
.await
.with_context(|| format!("finding the repository pull request #{number} is on"))?;
let pull_request = github
.pull_request(&repository, number)
.await
.with_context(|| format!("reading pull request #{number} on {}", repository.slug()))?;
if pull_request.state != PullRequestState::Open {
anyhow::bail!(
"pull request #{number} is {}, so there is nothing to push a fix to",
if pull_request.state == PullRequestState::Merged { "merged" } else { "closed" }
);
}
let head = github
.pull_request_head(&repository, number)
.await
.with_context(|| format!("asking who can push to pull request #{number}"))?;
if let Some(refusal) = head.refusal(number) {
anyhow::bail!(refusal);
}
// One worktree per session: the one already there belongs to the session that made it
let existing = luxe_core::worktree::worktree_path(&settings.state_root, &head.local_branch);
if existing.exists() {
anyhow::bail!(
"pull request #{number} is already checked out, in `{}`; `luxe --from-pr {number}` \
resumes the session working on it",
luxe_core::paths::display(
existing.strip_prefix(&settings.state_root).unwrap_or(&existing)
)
);
}
let base_remote = repository.remote.clone().unwrap_or_else(|| "origin".to_string());
let checkout = luxe_core::worktree::PullRequestCheckout {
head: &head,
host: &repository.host,
base_remote: &base_remote,
};
let made = luxe_core::worktree::check_out_pull_request(&settings.state_root, &checkout)
.await
.with_context(|| format!("checking out pull request #{number}"))?;
let worktree = made.worktree;
let place = luxe_core::paths::display(
worktree.path.strip_prefix(&settings.state_root).unwrap_or(&worktree.path),
);
let author = &pull_request.author.login;
let title = luxe_core::github::untrusted(pull_request.title.trim(), 120).replace('\n', " ");
let mut notice = format!(
"Pull request #{number}, \"{title}\" by @{author}, is checked out in its own worktree, \
`{place}`, on `{}`. `/pr` reviews it against its base: your comments go to the agent, and \
a plain `git push` lands on the pull request. Your checkout is untouched.",
worktree.branch
);
if made.remote_added {
notice.push_str(&format!(" The fork is reached by a new remote, `{}`.", made.remote));
}
bind_worktree(settings, worktree.path, worktree.branch)?;
settings.startup_notices.push(notice);
settings.pull_request = Some((number, pull_request.url.clone()));
Ok(())
}
/// Takes issue `number` up in a worktree of its own, as `luxe --issue` does from the command line.
pub(super) async fn take_up_issue_in_worktree(
number: u64,
settings: &mut crate::engine_setup::AgentSettings,
) -> anyhow::Result<()> {
let branch = take_up_issue(number, settings).await?;
let made = luxe_core::worktree::prepare(&settings.state_root, &branch, None)
.await
.with_context(|| format!("preparing the session's worktree for `{branch}`"))?;
adopt_worktree(settings, made)
}
/// Reads issue `number` for the session to take up, answering the branch its work goes on.
async fn take_up_issue(
number: u64,
settings: &mut crate::engine_setup::AgentSettings,
) -> anyhow::Result<String> {
use luxe_core::github::{Discovery, PullRequests};
let github = luxe_core::github::GhCli::new();
let repository = github
.repository(&settings.state_root)
.await
.with_context(|| format!("finding the repository issue #{number} is on"))?;
let issue = github
.issue(&repository, number)
.await
.with_context(|| format!("reading issue #{number} on {}", repository.slug()))?;
settings.startup_notices.push(format!(
"Issue #{number} — {} will be sent with your first message as additional context.",
luxe_core::github::untrusted(issue.title.trim(), 120).replace('\n', " ")
));
settings.issue = Some(crate::engine_setup::IssueBinding {
number,
url: issue.url.clone(),
brief: luxe_core::issue::brief(&issue),
});
Ok(luxe_core::issue::branch_name(&issue))
}
/// The branch the session's worktree is on, or `None` for a session without one.
///
/// A branch named on the command line wins; a bare `--worktree` keeps the resumed session's branch,
/// or makes one up; a resumed session that had a worktree re-enters it without being asked; and
/// `worktree.always` gives a new session one.
pub(super) fn worktree_branch(
flag: Option<&str>,
resumed: Option<String>,
always: bool,
generate: impl FnOnce() -> String,
) -> Option<String> {
match (flag, resumed) {
(Some(""), Some(resumed)) | (None, Some(resumed)) => Some(resumed),
(Some(""), None) => Some(generate()),
(Some(branch), _) => Some(branch.to_string()),
(None, None) => always.then(generate),
}
}
/// A branch name for a session that did not choose one: `luxe/` and a short random part.
pub(super) fn generated_branch() -> String {
let id = uuid::Uuid::new_v4().simple().to_string();
format!("luxe/session-{}", &id[..8])
}
/// The notice a session in a worktree starts with.
pub(super) fn worktree_notice(
made: &luxe_core::worktree::SessionWorktree,
project: &std::path::Path,
) -> String {
let path = made.path.strip_prefix(project).unwrap_or(&made.path);
let place = format!("`{}` on branch `{}`", luxe_core::paths::display(path), made.branch);
let origin = match (&made.base, made.created, made.fetch_failed) {
(Some(base), true, true) => {
format!(", made from `{base}` as last fetched: the remote could not be reached")
}
(Some(base), true, false) => format!(", made from `{base}`"),
(None, true, _) => ", made again from its branch".to_string(),
(_, false, _) => String::new(),
};
format!(
"Working in the session's own worktree, {place}{origin}. Your checkout is untouched; \
`/worktree` says more."
)
}
/// Leaves the session's worktree and removes it, saying how it went on the terminal Luxe has
/// just handed back.
pub(super) async fn remove_worktree(project: &std::path::Path, path: &std::path::Path) {
if let Err(error) = std::env::set_current_dir(project) {
eprintln!("luxe: could not leave the worktree to remove it: {error}");
return;
}
let place = luxe_core::paths::display(path.strip_prefix(project).unwrap_or(path));
match luxe_core::worktree::remove(project, path).await {
Ok(()) => eprintln!("luxe: removed the session's worktree `{place}`; its branch is kept."),
Err(error) => eprintln!("luxe: the worktree `{place}` was kept: {error}"),
}
}