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,408 @@
//! Debug-adapter registry — resolves a program to a DAP adapter command + launch arguments.
//!
//! All supported adapters speak DAP over **stdio** (`codelldb` with no args, `python -m
//! debugpy.adapter`, `lldb-dap`, `gdb --interpreter=dap`), so the client needs a single transport.
//! Compiled languages debug a *binary*, so the adapter is chosen by explicit request or by a
//! native-first fallback rather than by source extension.
use crate::client::DapError;
use serde::Deserialize;
use serde_json::{json, Value};
use std::path::Path;
/// How an adapter shapes its `launch` request arguments.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AdapterKind {
/// Python via debugpy.
Debugpy,
/// Native (Rust/C/C++) via CodeLLDB or lldb-dap.
Lldb,
/// Native via `gdb --interpreter=dap`.
Gdb,
/// Go via Delve (`dlv dap`).
Delve,
}
/// How the client connects to the adapter's DAP stream.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Transport {
/// DAP over the adapter's stdio (debugpy, CodeLLDB, lldb-dap, gdb).
Stdio,
/// The adapter dials in to us over TCP; `placeholder` in the command is replaced with our
/// loopback `host:port` (Delve `--client-addr`, js-debug).
TcpDialIn { placeholder: String },
}
/// A resolved debug adapter: how to launch the adapter process + how to shape `launch` args.
#[derive(Debug, Clone)]
pub struct AdapterSpec {
/// Stable adapter id (`debugpy`, `codelldb`, `lldb-dap`, `gdb`, `dlv`).
pub id: String,
/// Adapter command (the DAP server itself).
pub command: Vec<String>,
/// Launch-argument dialect.
pub kind: AdapterKind,
/// How the client connects to the adapter.
pub transport: Transport,
}
impl AdapterSpec {
/// Build the `launch` request arguments for a target program.
pub fn launch_arguments(
&self,
program: &str,
args: &[String],
cwd: &str,
stop_on_entry: bool,
) -> Value {
match self.kind {
AdapterKind::Debugpy => json!({
"request": "launch",
"program": program,
"args": args,
"console": "internalConsole",
"cwd": cwd,
"stopOnEntry": stop_on_entry,
}),
AdapterKind::Lldb => json!({
"request": "launch",
"program": program,
"args": args,
"cwd": cwd,
"stopOnEntry": stop_on_entry,
}),
AdapterKind::Gdb => json!({
"request": "launch",
"program": program,
"args": args,
"cwd": cwd,
"stopAtBeginningOfMainSubprogram": stop_on_entry,
}),
// Delve `mode: debug` builds + runs the package/file at `program`.
AdapterKind::Delve => json!({
"request": "launch",
"mode": "debug",
"program": program,
"args": args,
"cwd": cwd,
"stopOnEntry": stop_on_entry,
}),
}
}
/// Build the `attach` request arguments: by `port` (debugpy connect) or `pid` (native).
pub fn attach_arguments(&self, pid: Option<i64>, port: Option<i64>) -> Value {
match self.kind {
AdapterKind::Debugpy => {
if let Some(port) = port {
json!({ "request": "attach", "connect": { "host": "127.0.0.1", "port": port } })
} else {
json!({ "request": "attach", "processId": pid })
}
}
AdapterKind::Lldb | AdapterKind::Gdb => {
json!({ "request": "attach", "pid": pid })
}
AdapterKind::Delve => {
json!({ "request": "attach", "mode": "local", "processId": pid })
}
}
}
}
/// Placeholder in the Delve command replaced with our loopback `host:port` for dial-in.
const DAP_ADDR: &str = "${DAP_ADDR}";
// === Config-driven custom adapters ===
/// Launch-argument dialect a custom adapter reuses (most DAP adapters fit one of these shapes).
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Dialect {
Debugpy,
Lldb,
Gdb,
Delve,
}
impl Dialect {
fn kind(self) -> AdapterKind {
match self {
Dialect::Debugpy => AdapterKind::Debugpy,
Dialect::Lldb => AdapterKind::Lldb,
Dialect::Gdb => AdapterKind::Gdb,
Dialect::Delve => AdapterKind::Delve,
}
}
}
/// How a custom adapter is reached.
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum TransportConfig {
/// DAP over the adapter's stdio (default).
#[default]
Stdio,
/// The adapter dials in to us over TCP (include an address placeholder in `command`).
TcpDialIn,
}
/// A user-configured adapter from `~/.config/luxe/debug-adapters.json`. Lets users (or a model
/// working in Luxe) add debuggers for more languages without a code change, reusing a built-in
/// launch dialect.
#[derive(Debug, Clone, Deserialize)]
pub struct CustomAdapter {
/// Stable id, selectable via the debug tool's `adapter` arg.
pub id: String,
/// Adapter command (argv). For `tcp_dial_in`, include the address placeholder.
pub command: Vec<String>,
/// Source extensions this adapter auto-handles (leading dot optional), e.g. `["rb"]`.
#[serde(default)]
pub extensions: Vec<String>,
/// Which built-in launch dialect to use.
pub dialect: Dialect,
/// Transport (default stdio).
#[serde(default)]
pub transport: TransportConfig,
/// For `tcp_dial_in`: the substring in `command` replaced with our `host:port`
/// (default `${DAP_ADDR}`).
#[serde(default)]
pub addr_placeholder: Option<String>,
}
/// A resolved custom adapter: its spec plus the extensions it auto-handles.
#[derive(Debug, Clone)]
pub struct ConfiguredAdapter {
pub spec: AdapterSpec,
pub extensions: Vec<String>,
}
impl ConfiguredAdapter {
/// Build a resolved adapter from its config entry.
pub fn from_custom(custom: &CustomAdapter) -> Self {
let transport = match custom.transport {
TransportConfig::Stdio => Transport::Stdio,
TransportConfig::TcpDialIn => Transport::TcpDialIn {
placeholder: custom
.addr_placeholder
.clone()
.unwrap_or_else(|| DAP_ADDR.to_string()),
},
};
ConfiguredAdapter {
spec: AdapterSpec {
id: custom.id.clone(),
command: custom.command.clone(),
kind: custom.dialect.kind(),
transport,
},
extensions: custom
.extensions
.iter()
.map(|e| e.trim_start_matches('.').to_string())
.collect(),
}
}
}
/// The shipped default debug adapters, using the same `CustomAdapter` schema as user config, so
/// built-in + user adapters share one parse + resolution path.
const DEFAULT_ADAPTERS_JSON: &str = include_str!("default-debug-adapters.json");
/// The shipped built-in debug adapters (debugpy, codelldb, lldb-dap, gdb, dlv), for
/// status/introspection surfaces like the `/debug` command.
pub fn builtin_adapters() -> Vec<ConfiguredAdapter> {
default_adapters()
}
/// Parse the bundled default adapters. Compile-time-embedded + covered by
/// `default_adapters_bundle_parses`, so a failure is a build-time bug, never a runtime path.
fn default_adapters() -> Vec<ConfiguredAdapter> {
let customs: Vec<CustomAdapter> = serde_json::from_str(DEFAULT_ADAPTERS_JSON)
.expect("bundled default-debug-adapters.json must be valid");
customs.iter().map(ConfiguredAdapter::from_custom).collect()
}
/// Whether any debug adapter — user-configured or built-in — is actually installed.
///
/// The `debug` tool is the most expensive schema in the set, and it is dead weight on a machine
/// with no adapter: every call can only answer "no debug adapter found". Registration is gated on
/// this so that cost is paid only where the capability exists. Nothing is hidden by doing so —
/// unlike deferring a working tool, an absent adapter means there is no debugging to offer.
pub fn any_adapter_available(custom: &[ConfiguredAdapter]) -> bool {
custom
.iter()
.chain(default_adapters().iter())
.any(|c| c.spec.command.first().is_some_and(|program| on_path(program)))
}
/// Resolves the adapter for a target program.
///
/// An explicit `adapter` id wins (user adapters shadow built-ins). Otherwise an adapter whose
/// `extensions` match the program's extension wins (user first, then built-in — e.g. `.py`→debugpy,
/// `.go`→dlv), and everything else (a compiled binary) takes the first installed native adapter:
/// CodeLLDB, then lldb-dap, then gdb.
pub fn resolve(
program: &str,
adapter: Option<&str>,
custom: &[ConfiguredAdapter],
) -> Result<AdapterSpec, DapError> {
let builtin = default_adapters();
// User adapters take precedence over built-ins with the same id/extension.
let ordered = || custom.iter().chain(builtin.iter());
if let Some(id) = adapter {
return ordered()
.find(|c| c.spec.id == id)
.map(|c| c.spec.clone())
.ok_or_else(|| DapError::AdapterUnavailable(format!("unknown adapter '{id}'")))
.and_then(ensure_installed);
}
if let Some(ext) = Path::new(program).extension().and_then(|e| e.to_str()) {
if let Some(found) = ordered().find(|c| c.extensions.iter().any(|e| e == ext)) {
return ensure_installed(found.spec.clone());
}
}
// Compiled binary: first installed native adapter (Delve is Go-source-specific, excluded).
builtin
.iter()
.filter(|c| matches!(c.spec.kind, AdapterKind::Lldb | AdapterKind::Gdb))
.find(|c| on_path(&c.spec.command[0]))
.map(|c| c.spec.clone())
.ok_or_else(|| {
DapError::AdapterUnavailable(
"no native debug adapter found (install codelldb, lldb-dap, or gdb)".to_string(),
)
})
}
fn ensure_installed(spec: AdapterSpec) -> Result<AdapterSpec, DapError> {
if on_path(&spec.command[0]) {
Ok(spec)
} else {
Err(DapError::AdapterUnavailable(format!(
"debug adapter '{}' not found on PATH",
spec.command[0]
)))
}
}
/// Whether an executable is resolvable — `PATH`, a well-known install directory, or an explicit
/// path. Debug adapters are installed by `cargo install`, `pipx`, or an editor extension, none of
/// which reliably land on the `PATH` an app inherits.
fn on_path(program: &str) -> bool {
luxe_core::program::is_available(program)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn python_targets_resolve_to_debugpy_dialect() {
let spec = AdapterSpec {
id: "debugpy".into(),
command: vec!["python3".into()],
kind: AdapterKind::Debugpy,
transport: Transport::Stdio,
};
let args = spec.launch_arguments("/w/app.py", &["--flag".into()], "/w", true);
assert_eq!(args["program"], "/w/app.py");
assert_eq!(args["console"], "internalConsole");
assert_eq!(args["stopOnEntry"], true);
}
#[test]
fn gdb_uses_its_own_stop_key() {
let spec = AdapterSpec {
id: "gdb".into(),
command: vec!["gdb".into()],
kind: AdapterKind::Gdb,
transport: Transport::Stdio,
};
let args = spec.launch_arguments("/w/bin", &[], "/w", true);
assert_eq!(args["stopAtBeginningOfMainSubprogram"], true);
}
#[test]
fn unknown_adapter_is_rejected() {
assert!(resolve("/w/app.py", Some("nope"), &[]).is_err());
}
#[test]
fn default_adapters_bundle_parses() {
let adapters = default_adapters();
let ids: Vec<&str> = adapters.iter().map(|a| a.spec.id.as_str()).collect();
for id in ["debugpy", "codelldb", "lldb-dap", "gdb", "dlv"] {
assert!(ids.contains(&id), "missing built-in adapter {id}");
}
let dlv = adapters.iter().find(|a| a.spec.id == "dlv").unwrap();
assert_eq!(dlv.spec.kind, AdapterKind::Delve);
assert!(matches!(dlv.spec.transport, Transport::TcpDialIn { .. }));
assert!(dlv.extensions.contains(&"go".to_string()));
let debugpy = adapters.iter().find(|a| a.spec.id == "debugpy").unwrap();
assert!(debugpy.extensions.contains(&"py".to_string()));
}
#[test]
fn custom_adapter_parses_and_maps() {
let json = r#"{"id":"ruby","command":["rdbg","--dap","${DAP_ADDR}"],
"extensions":[".rb"],"dialect":"debugpy","transport":"tcp_dial_in"}"#;
let custom: CustomAdapter = serde_json::from_str(json).unwrap();
let cfg = ConfiguredAdapter::from_custom(&custom);
assert_eq!(cfg.spec.id, "ruby");
assert_eq!(cfg.spec.kind, AdapterKind::Debugpy);
assert!(matches!(cfg.spec.transport, Transport::TcpDialIn { .. }));
assert_eq!(cfg.extensions, vec!["rb"]); // leading dot stripped
}
/// A program that is genuinely installed, so `ensure_installed` passes on its own merits
/// rather than on the fixture's. `sh` is not that program: Windows has no POSIX shell unless
/// somebody installed one.
fn installed_program() -> String {
if cfg!(windows) { "cmd" } else { "sh" }.to_string()
}
#[test]
fn custom_adapter_wins_by_id_and_extension() {
let custom = ConfiguredAdapter {
spec: AdapterSpec {
id: "myruby".into(),
command: vec![installed_program()],
kind: AdapterKind::Debugpy,
transport: Transport::Stdio,
},
extensions: vec!["rb".into()],
};
let extra = std::slice::from_ref(&custom);
assert_eq!(resolve("/w/x", Some("myruby"), extra).unwrap().id, "myruby");
assert_eq!(resolve("/w/app.rb", None, extra).unwrap().id, "myruby");
}
/// The `debug` schema is the largest in the set; it should not be paid for on a machine that
/// cannot debug. An adapter with a command that resolves to nothing must not count.
#[test]
fn availability_tracks_whether_an_adapter_command_resolves() {
let missing = ConfiguredAdapter::from_custom(&CustomAdapter {
id: "ghost".to_string(),
command: vec!["definitely-not-a-real-adapter-xyz".to_string()],
extensions: vec!["zz".to_string()],
dialect: Dialect::Lldb,
transport: TransportConfig::default(),
addr_placeholder: None,
});
assert!(!any_adapter_available(&[missing]) || any_adapter_available(&[]));
let real = ConfiguredAdapter::from_custom(&CustomAdapter {
id: "shell".to_string(),
command: vec![installed_program()],
extensions: vec!["zz".to_string()],
dialect: Dialect::Lldb,
transport: TransportConfig::default(),
addr_placeholder: None,
});
assert!(any_adapter_available(&[real]), "an installed command counts as available");
}
}

View File

@@ -0,0 +1,581 @@
//! A DAP client over an adapter transport.
//!
//! Spawns (or dials in to) a debug adapter, correlates requests to responses by `seq`/`request_seq`,
//! folds events (`stopped`, `output`, `terminated`, …) into shared session state, and auto-replies
//! to reverse requests so the adapter never stalls. The transport is boxed so the same client drives
//! **stdio** adapters (debugpy, CodeLLDB, gdb) and **socket** adapters (Delve `dlv dap`, js-debug)
//! uniformly. Methods take `&self` (seq is atomic, writer/pending are behind mutexes) so a session
//! can be driven from an `Arc<DapClient>`.
use crate::protocol::{ProtocolMessage, StoppedBody};
use luxe_core::jsonrpc_frame::write_frame;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::{Arc, Mutex as SyncMutex};
use std::time::{Duration, Instant};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::process::{Child, Command};
use tokio::sync::{oneshot, Mutex, Notify};
use tracing::error;
/// Boxed write half of a DAP transport (child stdin, or a TCP write half).
type BoxWriter = Box<dyn AsyncWrite + Send + Unpin>;
/// Boxed read half of a DAP transport (child stdout, or a TCP read half).
type BoxReader = Box<dyn AsyncRead + Send + Unpin>;
/// Cap on captured program output so a chatty program can't grow the buffer unbounded.
const MAX_OUTPUT_BYTES: usize = 64 * 1024;
mod reader;
use reader::{display_output, drain_child_logs, read_loop, StderrHead};
/// Requests written and not yet answered, by seq.
type Pending = Arc<Mutex<HashMap<i64, oneshot::Sender<ProtocolMessage>>>>;
/// A written-but-not-yet-awaited request: its seq and the response channel.
pub(crate) struct PendingRequest {
seq: i64,
rx: oneshot::Receiver<ProtocolMessage>,
}
/// Live, event-folded session state shared with the background reader.
#[derive(Default)]
struct DapState {
/// The adapter sent the `initialized` event (ready for breakpoint config).
initialized: bool,
/// The program terminated or the debug session ended.
terminated: bool,
/// Most recent `stopped` event (breakpoint/step/exception), cleared on continue.
stopped: Option<StoppedBody>,
/// Captured program output (bounded).
output: String,
/// Category of the last captured chunk (`stdout`, `stderr`, `console`, …).
///
/// DAP `output` events don't align with line boundaries, so a chunk that doesn't end in a
/// newline is a genuine partial line and must not be broken up. But two *different* streams
/// interleaving mid-line — an adapter `console` note landing inside the program's stdout —
/// silently glues unrelated words together. Tracking the category lets the display split
/// exactly those boundaries and no others.
last_output_category: Option<String>,
/// Byte offsets in `output` where a category switch glued two partial lines together.
output_breaks: Vec<usize>,
/// The adapter's stream has ended, so nothing more will be read: no answer, and no event.
///
/// Not `terminated`, which the program's end also sets while the adapter can still answer
/// a `disconnect`.
disconnected: bool,
}
/// Shared client/reader state.
struct Shared {
state: SyncMutex<DapState>,
notify: Notify,
}
impl Shared {
fn update(&self, f: impl FnOnce(&mut DapState)) {
if let Ok(mut state) = self.state.lock() {
f(&mut state);
}
self.notify.notify_waiters();
}
}
/// A running debug adapter connection.
pub struct DapClient {
child: Mutex<Option<Child>>,
/// The adapter's pid, used to SIGKILL the whole process group on drop so the debuggee the
/// adapter spawned is reaped too (`kill_on_drop` only reaps the adapter itself).
group_pid: Option<u32>,
writer: Arc<Mutex<BoxWriter>>,
next_seq: AtomicI64,
pending: Pending,
shared: Arc<Shared>,
stderr: Arc<StderrHead>,
}
impl DapClient {
/// Spawn a **stdio** adapter (debugpy, CodeLLDB, gdb) and start the background reader.
pub async fn spawn(command: &[String], cwd: &std::path::Path) -> Result<Self, DapError> {
let program = command.first().ok_or(DapError::EmptyCommand)?;
let mut cmd = Command::new(program);
cmd.args(&command[1..]);
cmd.current_dir(cwd);
cmd.stdin(std::process::Stdio::piped());
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped());
cmd.kill_on_drop(true);
// Own process group so dropping the client reaps the debuggee the adapter spawns, not just
// the adapter (matches the bash tool's discipline).
luxe_core::program::detach_from_terminal(&mut cmd);
let mut child = cmd.spawn().map_err(|e| DapError::SpawnFailed {
adapter: program.clone(),
error: e.to_string(),
})?;
let stdin = child.stdin.take().ok_or(DapError::Io("adapter stdin unavailable".into()))?;
let stdout =
child.stdout.take().ok_or(DapError::Io("adapter stdout unavailable".into()))?;
let stderr = drain_child_logs(&mut child);
Ok(Self::start(Some(child), Box::new(stdin), Box::new(stdout), stderr))
}
/// Connect to a **socket** adapter that dials in to us (Delve `dlv dap --client-addr`,
/// js-debug). We bind a free loopback port, substitute it into `command` at `addr_placeholder`,
/// spawn the adapter, and accept its connection — race-free (the OS picked the port).
pub async fn connect_dial_in(
command: &[String],
cwd: &std::path::Path,
addr_placeholder: &str,
) -> Result<Self, DapError> {
let program = command.first().ok_or(DapError::EmptyCommand)?;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.map_err(|e| DapError::Io(format!("failed to bind DAP listener: {e}")))?;
let addr = listener.local_addr().map_err(|e| DapError::Io(e.to_string()))?.to_string();
let args: Vec<String> =
command[1..].iter().map(|a| a.replace(addr_placeholder, &addr)).collect();
let mut cmd = Command::new(program);
cmd.args(&args)
.current_dir(cwd)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true);
luxe_core::program::detach_from_terminal(&mut cmd);
let mut child = cmd.spawn().map_err(|e| DapError::SpawnFailed {
adapter: program.clone(),
error: e.to_string(),
})?;
let stderr = drain_child_logs(&mut child);
let (stream, _) = tokio::time::timeout(Duration::from_secs(15), listener.accept())
.await
.map_err(|_| {
DapError::Io(format!(
"debug adapter '{program}' did not dial in (check it's installed and the \
target builds; see dap.adapter logs)"
))
})?
.map_err(|e| DapError::Io(format!("accept from adapter failed: {e}")))?;
let (read_half, write_half) = stream.into_split();
Ok(Self::start(Some(child), Box::new(write_half), Box::new(read_half), stderr))
}
/// Wire up shared state + the background reader over an already-connected transport.
fn start(
child: Option<Child>,
writer: BoxWriter,
reader: BoxReader,
stderr: Arc<StderrHead>,
) -> Self {
let group_pid = child.as_ref().and_then(Child::id);
let writer = Arc::new(Mutex::new(writer));
let pending = Arc::new(Mutex::new(HashMap::new()));
let shared =
Arc::new(Shared { state: SyncMutex::new(DapState::default()), notify: Notify::new() });
let reader_writer = writer.clone();
let reader_pending = pending.clone();
let reader_shared = shared.clone();
tokio::spawn(async move {
let mut reader = tokio::io::BufReader::new(reader);
if let Err(e) =
read_loop(&mut reader, reader_shared, reader_writer, reader_pending).await
{
error!("dap reader task exited: {e}");
}
});
Self {
child: Mutex::new(child),
group_pid,
writer,
next_seq: AtomicI64::new(1),
pending,
shared,
stderr,
}
}
/// Send a request and await its response, failing on a non-success reply.
pub async fn request(
&self,
command: &str,
arguments: Value,
timeout: Duration,
) -> Result<Value, DapError> {
let pending = self.write_request(command, arguments).await?;
self.await_response(pending, command, timeout).await
}
/// Write a request now and return a handle to await its response later.
///
/// Splitting send from await lets the launch/attach choreography guarantee `launch`/`attach`
/// reaches the adapter **before** `configurationDone`, while its response (which only arrives
/// after) is awaited afterward. Sending it inline (not in a spawned task) avoids a write-order
/// race on stdin.
pub(crate) async fn write_request(
&self,
command: &str,
arguments: Value,
) -> Result<PendingRequest, DapError> {
let seq = self.next_seq.fetch_add(1, Ordering::Relaxed);
let mut message = json!({ "seq": seq, "type": "request", "command": command });
if !arguments.is_null() {
message["arguments"] = arguments;
}
let payload = serde_json::to_vec(&message).map_err(|e| DapError::Io(e.to_string()))?;
let (tx, rx) = oneshot::channel();
self.pending.lock().await.insert(seq, tx);
// the reader marks itself done before it clears the map, so one of the two catches this
let refused = match self.shared.state.lock() {
Ok(state) => state.disconnected.then_some(DapError::Cancelled),
Err(_) => Some(DapError::Poisoned),
};
if let Some(error) = refused {
self.pending.lock().await.remove(&seq);
return Err(error);
}
let written = {
let mut guard = self.writer.lock().await;
write_frame(&mut *guard, &payload).await
};
if let Err(error) = written {
self.pending.lock().await.remove(&seq);
return Err(DapError::Io(error.to_string()));
}
Ok(PendingRequest { seq, rx })
}
/// Await a previously-written request's response, failing on a non-success reply or timeout.
pub(crate) async fn await_response(
&self,
pending: PendingRequest,
command: &str,
timeout: Duration,
) -> Result<Value, DapError> {
let response = match tokio::time::timeout(timeout, pending.rx).await {
Ok(Ok(response)) => response,
Ok(Err(_)) => return Err(DapError::Cancelled),
Err(_) => {
self.pending.lock().await.remove(&pending.seq);
return Err(DapError::Timeout { command: command.to_string() });
}
};
if response.success == Some(false) {
return Err(DapError::RequestFailed {
command: command.to_string(),
message: response.message.unwrap_or_else(|| "request failed".to_string()),
});
}
Ok(response.body.unwrap_or(Value::Null))
}
/// Wait until the adapter emits `initialized`, or time out; an adapter that goes away first
/// is `Cancelled` at once.
pub async fn wait_for_initialized(&self, timeout: Duration) -> Result<(), DapError> {
self.wait_until(timeout, |s| s.initialized || s.disconnected).await?;
let initialized = self.shared.state.lock().map_err(|_| DapError::Poisoned)?.initialized;
if initialized {
Ok(())
} else {
Err(DapError::Cancelled)
}
}
/// Wait until the session stops or terminates. Returns the stop body, or `None` on terminate.
pub async fn wait_for_stop_or_terminate(
&self,
timeout: Duration,
) -> Result<Option<StoppedBody>, DapError> {
self.wait_until(timeout, |s| s.stopped.is_some() || s.terminated).await?;
let state = self.shared.state.lock().map_err(|_| DapError::Poisoned)?;
Ok(state.stopped.clone())
}
/// Poll a predicate over shared state until true or the timeout elapses.
async fn wait_until(
&self,
timeout: Duration,
pred: impl Fn(&DapState) -> bool,
) -> Result<(), DapError> {
let start = Instant::now();
loop {
{
let state = self.shared.state.lock().map_err(|_| DapError::Poisoned)?;
if pred(&state) {
return Ok(());
}
}
if start.elapsed() >= timeout {
return Err(DapError::Timeout { command: "event".to_string() });
}
tokio::select! {
_ = self.shared.notify.notified() => {}
_ = tokio::time::sleep(Duration::from_millis(50)) => {}
}
}
}
/// The start of what the adapter wrote to stderr, trimmed: usually why it failed to start.
///
/// Waits a moment for stderr to close, since an adapter that just died has said its last
/// words there and the drain may not have read them yet.
pub async fn adapter_stderr(&self) -> String {
let deadline = Instant::now() + Duration::from_millis(500);
while !self.stderr.closed.load(Ordering::Acquire) && Instant::now() < deadline {
tokio::time::sleep(Duration::from_millis(20)).await;
}
self.stderr.text.lock().map(|text| text.trim().to_owned()).unwrap_or_default()
}
/// Snapshot: has the session terminated?
pub fn is_terminated(&self) -> bool {
self.shared.state.lock().map(|s| s.terminated).unwrap_or(true)
}
/// Snapshot: the latest stop, if any.
pub fn last_stop(&self) -> Option<StoppedBody> {
self.shared.state.lock().ok().and_then(|s| s.stopped.clone())
}
/// Clear the recorded stop (call when resuming execution).
pub fn clear_stop(&self) {
self.shared.update(|s| s.stopped = None);
}
/// Snapshot of captured program output, byte-for-byte as the adapter sent it.
pub fn output(&self) -> String {
self.shared.state.lock().map(|s| s.output.clone()).unwrap_or_default()
}
/// Captured output for *display*: identical to [`Self::output`] except that a mid-line switch
/// between output streams is broken onto its own line, so an adapter note can't glue itself
/// onto the end of a program's partial line.
pub fn output_for_display(&self) -> String {
self.shared.state.lock().map(|state| display_output(&state)).unwrap_or_default()
}
/// Forget everything captured so far, because none of it came from the program.
///
/// Called once the adapter has answered `initialize` and before the program is launched or
/// attached to. Up to that moment anything on the wire is the *adapter* talking: `gdb
/// --interpreter=dap` opens with twelve lines of version and GPL notice, tagged `stdout` like
/// real program output, and none of it belongs in the model's context.
pub fn discard_output_so_far(&self) {
if let Ok(mut state) = self.shared.state.lock() {
state.output.clear();
state.last_output_category = None;
state.output_breaks.clear();
}
}
/// Terminate the adapter and reap the process group (adapter + debuggee).
pub async fn shutdown(&self) {
let _ = self
.request("disconnect", json!({ "terminateDebuggee": true }), Duration::from_secs(3))
.await;
if let Some(pid) = self.group_pid {
luxe_core::program::kill_tree(pid);
}
if let Some(mut child) = self.child.lock().await.take() {
let _ = child.start_kill();
let _ = child.wait().await;
}
}
}
impl Drop for DapClient {
/// Reap the whole process group so a dropped client never leaks the adapter or its debuggee.
fn drop(&mut self) {
if let Some(pid) = self.group_pid {
luxe_core::program::kill_tree(pid);
}
}
}
/// DAP client errors.
#[derive(Debug, thiserror::Error)]
pub enum DapError {
#[error("empty adapter command")]
EmptyCommand,
#[error("failed to spawn debug adapter '{adapter}': {error}")]
SpawnFailed { adapter: String, error: String },
#[error("io error: {0}")]
Io(String),
#[error("request '{command}' timed out")]
Timeout { command: String },
#[error("request '{command}' failed: {message}")]
RequestFailed { command: String, message: String },
#[error("request cancelled")]
Cancelled,
#[error("session state poisoned")]
Poisoned,
#[error("no such debug session")]
NoSession,
/// No adapter can run what was asked for: an unknown id, one that is not installed, or no
/// native adapter at all
#[error("{0}")]
AdapterUnavailable(String),
/// A launch or attach step failed, with the adapter's stderr when it had exited
#[error("{0}")]
StartFailed(String),
/// No thread was named and none has stopped
#[error("no active thread")]
NoThread,
/// A resume was accepted and no stop followed
#[error(
"{command} was accepted but the program has not stopped after {secs}s — it is still \
running. Use action=pause to stop it, action=output to see what it has printed, or set \
{env} higher if the next stop is simply far away."
)]
StillRunning {
/// The request that was accepted
command: String,
/// How long the wait was
secs: u64,
/// The environment variable that lengthens it
env: &'static str,
},
}
#[cfg(test)]
mod tests {
use super::reader::apply_event;
use super::*;
fn output_event(text: &str, category: &str) -> ProtocolMessage {
serde_json::from_value(json!({
"seq": 1,
"type": "event",
"event": "output",
"body": { "output": text, "category": category },
}))
.expect("event parses")
}
fn shared() -> Shared {
Shared { state: SyncMutex::new(DapState::default()), notify: Notify::new() }
}
/// The break this catches: the cut that keeps the newest output fell inside a multibyte char,
/// panicked under the state lock, poisoned it, and the session read as over while it ran.
#[test]
fn output_past_the_cap_is_cut_on_a_char_boundary() {
let shared = shared();
// an odd byte on either side puts the cut inside an `é`
apply_event(&shared, &output_event("x", "stdout"));
apply_event(&shared, &output_event(&format!("{}y", "é".repeat(35_000)), "stdout"));
assert!(!shared.state.is_poisoned(), "the reader survived");
let state = shared.state.lock().unwrap();
assert!(state.output.len() <= MAX_OUTPUT_BYTES, "{}", state.output.len());
assert!(state.output.trim_end_matches('y').chars().all(|c| c == 'é'), "whole chars only");
}
/// A writer whose every write fails, as a closed pipe's does.
struct Refusing;
impl tokio::io::AsyncWrite for Refusing {
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::ErrorKind::BrokenPipe.into()))
}
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(()))
}
}
/// A request whose write fails leaves no pending entry behind for nobody to answer.
#[tokio::test]
async fn a_failed_write_leaves_no_pending_entry() {
let (_adapter, ours) = tokio::io::duplex(64);
let client = DapClient::start(None, Box::new(Refusing), Box::new(ours), Arc::default());
let written = client.write_request("threads", Value::Null).await;
assert!(matches!(written, Err(DapError::Io(_))), "{:?}", written.err());
assert!(client.pending.lock().await.is_empty());
}
/// A poisoned state lock is reported as poisoned, not as an adapter that exited, and the
/// request leaves nothing pending.
#[tokio::test]
async fn a_poisoned_state_is_poisoned_not_an_exit() {
let (_adapter, ours) = tokio::io::duplex(64);
let (writer, _) = tokio::io::duplex(64);
let client = DapClient::start(None, Box::new(writer), Box::new(ours), Arc::default());
let shared = Arc::clone(&client.shared);
let poisoner = std::thread::spawn(move || {
let _held = shared.state.lock().unwrap();
panic!("poison the state lock");
});
assert!(poisoner.join().is_err());
let written = client.write_request("threads", Value::Null).await;
assert!(matches!(written, Err(DapError::Poisoned)), "{:?}", written.err());
assert!(client.pending.lock().await.is_empty());
}
#[test]
fn partial_lines_from_one_stream_stay_intact() {
// `print(..., end="")` and progress bars stream partial lines; splitting them would be
// wrong, so same-category chunks are concatenated verbatim.
let shared = shared();
apply_event(&shared, &output_event("load", "stdout"));
apply_event(&shared, &output_event("ing...", "stdout"));
apply_event(&shared, &output_event(" done\n", "stdout"));
let state = shared.state.lock().unwrap();
assert_eq!(state.output, "loading... done\n");
assert!(state.output_breaks.is_empty(), "no boundary inside one stream");
}
#[test]
fn a_stream_switch_mid_line_is_broken_for_display_only() {
// Two adapter messages must not glue into one nonsense token (`ptvsd` + `debugpy`).
let shared = shared();
apply_event(&shared, &output_event("ptvsd", "console"));
apply_event(&shared, &output_event("debugpy", "stderr"));
let state = shared.state.lock().unwrap();
assert_eq!(state.output, "ptvsddebugpy", "captured bytes stay verbatim");
assert_eq!(state.output_breaks, vec![5], "the boundary is recorded, not inserted");
drop(state);
let state = shared.state.lock().unwrap();
assert_eq!(state.output, "ptvsddebugpy", "the snapshot stays byte-faithful");
assert_eq!(display_output(&state), "ptvsd\ndebugpy", "display separates the streams");
}
#[test]
fn a_stream_switch_after_a_newline_needs_no_boundary() {
let shared = shared();
apply_event(&shared, &output_event("hello\n", "stdout"));
apply_event(&shared, &output_event("warning\n", "stderr"));
let state = shared.state.lock().unwrap();
assert!(state.output_breaks.is_empty(), "the newline already separates them");
assert_eq!(state.output, "hello\nwarning\n");
}
}

View File

@@ -0,0 +1,215 @@
//! DAP reader — the background task that reads the adapter, and the folding of what it says.
//!
//! Responses go to their pending request, events fold into [`Shared`] state, and reverse requests
//! are refused at once so the adapter never waits on us.
use super::{BoxWriter, DapError, DapState, Pending, Shared, MAX_OUTPUT_BYTES};
use crate::protocol::{ProtocolMessage, StoppedBody};
use luxe_core::jsonrpc_frame::{read_frame, write_frame, MAX_FRAME_BYTES};
use serde_json::{json, Value};
use std::sync::{Arc, Mutex as SyncMutex};
use tokio::io::{AsyncBufRead, AsyncReadExt};
use tokio::process::Child;
use tokio::sync::Mutex;
use tracing::debug;
/// The start of what an adapter wrote to stderr, filled as it arrives.
#[derive(Default)]
pub(super) struct StderrHead {
/// What has arrived, up to [`STDERR_HEAD_BYTES`]
pub(super) text: SyncMutex<String>,
/// Whether stderr has closed, so nothing more is coming
pub(super) closed: std::sync::atomic::AtomicBool,
}
/// Background reader: routes responses to pending requests, folds events, replies to reverse requests.
pub(super) async fn read_loop<R: AsyncBufRead + Unpin>(
reader: &mut R,
shared: Arc<Shared>,
writer: Arc<Mutex<BoxWriter>>,
pending: Pending,
) -> Result<(), DapError> {
let outcome = route_messages(reader, &shared, &writer, &pending).await;
// Only the reader can answer an in-flight request, so once it stops — the adapter exited, or
// its stream broke — nothing is coming for any of them. Dropping the senders fails each waiter
// as `Cancelled` now instead of at its own timeout, and the session reads as over either way.
// Marked first, so a request written from here on sees it and does not wait either.
shared.update(|s| {
s.disconnected = true;
s.terminated = true;
});
pending.lock().await.clear();
outcome
}
/// The reader's loop proper, split out so [`read_loop`] can clean up on every exit path.
async fn route_messages<R: AsyncBufRead + Unpin>(
reader: &mut R,
shared: &Shared,
writer: &Arc<Mutex<BoxWriter>>,
pending: &Pending,
) -> Result<(), DapError> {
while let Some(bytes) =
read_frame(reader, MAX_FRAME_BYTES).await.map_err(|e| DapError::Io(e.to_string()))?
{
let msg: ProtocolMessage = match serde_json::from_slice(&bytes) {
Ok(msg) => msg,
Err(e) => {
debug!(error = %e, "dap: dropping unparseable message");
continue;
}
};
match msg.kind.as_str() {
"response" => {
if let Some(request_seq) = msg.request_seq {
if let Some(tx) = pending.lock().await.remove(&request_seq) {
let _ = tx.send(msg);
}
}
}
"event" => apply_event(shared, &msg),
"request" => reply_unsupported(writer, &msg).await,
_ => {}
}
}
Ok(())
}
/// Render captured output with its recorded stream boundaries broken onto their own lines.
pub(super) fn display_output(state: &DapState) -> String {
if state.output_breaks.is_empty() {
return state.output.clone();
}
let mut out = String::with_capacity(state.output.len() + state.output_breaks.len());
let mut cursor = 0usize;
for offset in &state.output_breaks {
let offset = (*offset).min(state.output.len());
if offset < cursor || !state.output.is_char_boundary(offset) {
continue;
}
out.push_str(&state.output[cursor..offset]);
out.push('\n');
cursor = offset;
}
out.push_str(&state.output[cursor..]);
out
}
/// Fold a DAP event into shared session state.
pub(super) fn apply_event(shared: &Shared, msg: &ProtocolMessage) {
let Some(event) = msg.event.as_deref() else { return };
match event {
"initialized" => shared.update(|s| s.initialized = true),
"stopped" => {
let body = msg
.body
.clone()
.and_then(|b| serde_json::from_value::<StoppedBody>(b).ok())
.unwrap_or_default();
shared.update(|s| s.stopped = Some(body));
}
"continued" => shared.update(|s| s.stopped = None),
"terminated" | "exited" => shared.update(|s| s.terminated = true),
"output" => {
let chunk = msg
.body
.as_ref()
.and_then(|b| b.get("output"))
.and_then(Value::as_str)
.unwrap_or("");
let category = msg
.body
.as_ref()
.and_then(|b| b.get("category"))
.and_then(Value::as_str)
.unwrap_or("console")
.to_string();
if !chunk.is_empty() {
let chunk = chunk.to_string();
shared.update(move |s| {
// A different stream cutting in mid-line is a display boundary; the bytes
// themselves stay exactly as the adapter sent them.
let switched =
s.last_output_category.as_deref().is_some_and(|last| last != category);
if switched && !s.output.ends_with('\n') && !s.output.is_empty() {
s.output_breaks.push(s.output.len());
}
s.last_output_category = Some(category);
s.output.push_str(&chunk);
if s.output.len() > MAX_OUTPUT_BYTES {
let start = luxe_core::output_limit::ceil_boundary(
&s.output,
s.output.len() - MAX_OUTPUT_BYTES,
);
s.output = s.output.split_off(start);
s.output_breaks.retain(|offset| *offset > start);
for offset in &mut s.output_breaks {
*offset -= start;
}
}
});
}
}
_ => {}
}
}
/// Reply to an adapter→client (reverse) request with a failure, so the adapter never blocks on us.
async fn reply_unsupported(writer: &Arc<Mutex<BoxWriter>>, msg: &ProtocolMessage) {
let response = json!({
"seq": 0,
"type": "response",
"request_seq": msg.seq,
"success": false,
"command": msg.command.clone().unwrap_or_default(),
"message": "unsupported reverse request",
});
if let Ok(payload) = serde_json::to_vec(&response) {
let mut guard = writer.lock().await;
let _ = write_frame(&mut *guard, &payload).await;
}
}
/// The most of an adapter's stderr kept to explain a failed start.
const STDERR_HEAD_BYTES: usize = 2_000;
/// Drains an adapter's stdout, when it is not the transport, and its stderr to `dap.adapter` logs
/// so its pipes never block, keeping the start of stderr: when an adapter fails to start, that is
/// usually where it said why. Both are read as bytes to the end, so a line that is not UTF-8 does
/// not stop the drain and leave the adapter writing into a closed pipe.
pub(super) fn drain_child_logs(child: &mut Child) -> Arc<StderrHead> {
if let Some(stdout) = child.stdout.take() {
tokio::spawn(drain(stdout, None));
}
let head = Arc::new(StderrHead::default());
match child.stderr.take() {
Some(stderr) => {
tokio::spawn(drain(stderr, Some(Arc::clone(&head))));
}
None => head.closed.store(true, std::sync::atomic::Ordering::Release),
}
head
}
/// Reads `pipe` to its end, logging each chunk and keeping the start in `head`, when given one.
async fn drain(mut pipe: impl tokio::io::AsyncRead + Unpin, head: Option<Arc<StderrHead>>) {
let mut chunk = [0u8; 4096];
let mut kept = Vec::new();
while let Ok(read) = pipe.read(&mut chunk).await {
if read == 0 {
break;
}
for line in String::from_utf8_lossy(&chunk[..read]).lines() {
debug!(target: "dap.adapter", "{line}");
}
if let Some(head) = head.as_ref().filter(|_| kept.len() < STDERR_HEAD_BYTES) {
kept.extend_from_slice(&chunk[..read.min(STDERR_HEAD_BYTES - kept.len())]);
if let Ok(mut text) = head.text.lock() {
*text = String::from_utf8_lossy(&kept).replace("\r\n", "\n");
}
}
}
if let Some(head) = head {
head.closed.store(true, std::sync::atomic::Ordering::Release);
}
}

View File

@@ -0,0 +1,30 @@
[
{
"id": "debugpy",
"command": ["python3", "-m", "debugpy.adapter"],
"extensions": ["py"],
"dialect": "debugpy"
},
{
"id": "codelldb",
"command": ["codelldb"],
"dialect": "lldb"
},
{
"id": "lldb-dap",
"command": ["lldb-dap"],
"dialect": "lldb"
},
{
"id": "gdb",
"command": ["gdb", "--interpreter=dap"],
"dialect": "gdb"
},
{
"id": "dlv",
"command": ["dlv", "dap", "--client-addr", "${DAP_ADDR}"],
"extensions": ["go"],
"dialect": "delve",
"transport": "tcp_dial_in"
}
]

View File

@@ -0,0 +1,22 @@
//! luxe-dap — a native Debug Adapter Protocol client and the `debug` tool.
//!
//! Gives the agent a real debugger: launch/attach a program, set breakpoints, step, and inspect
//! threads/stack/variables/expressions across adapters (CodeLLDB/lldb-dap/gdb for native, debugpy
//! for Python) over stdio. Mirrors `luxe-lsp`'s warm-service shape — one long-lived
//! [`service::DapService`] reuses sessions across tool calls. Allowed edge: `dap → core`.
pub mod adapter;
mod client;
pub mod protocol;
pub mod service;
mod tool;
pub use adapter::{
any_adapter_available, builtin_adapters, AdapterSpec, ConfiguredAdapter, CustomAdapter,
};
pub use client::{DapClient, DapError};
pub use service::{
BreakpointRequest, DapService, DapSession, DapSessionInfo, FunctionBreakpoint, LaunchOutcome,
SourceBreakpoint,
};
pub use tool::DebugTool;

View File

@@ -0,0 +1,132 @@
//! Debug Adapter Protocol message envelope and the payload types the tool formats.
//!
//! Only the shapes we read back are typed; request `arguments` are built as `serde_json::Value` in
//! the client. See the DAP spec: <https://microsoft.github.io/debug-adapter-protocol/specification>.
use serde::{Deserialize, Serialize};
use serde_json::Value;
/// A DAP wire message (request, response, or event). Fields are optional so one type parses all
/// three variants coming from the adapter.
#[derive(Debug, Clone, Deserialize)]
pub struct ProtocolMessage {
/// Adapter-assigned sequence number for this message.
#[serde(default)]
pub seq: i64,
/// `"request"`, `"response"`, or `"event"`.
#[serde(rename = "type")]
pub kind: String,
/// Response: the request seq this answers.
#[serde(default)]
pub request_seq: Option<i64>,
/// Response: whether the request succeeded.
#[serde(default)]
pub success: Option<bool>,
/// Response/request: the command name.
#[serde(default)]
pub command: Option<String>,
/// Event: the event name.
#[serde(default)]
pub event: Option<String>,
/// Response: a human-readable failure message.
#[serde(default)]
pub message: Option<String>,
/// Response body / event body.
#[serde(default)]
pub body: Option<Value>,
}
/// A DAP thread (`threads` response).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Thread {
/// Adapter thread id.
pub id: i64,
pub name: String,
}
/// A source location referenced by a stack frame or breakpoint.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Source {
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub path: Option<String>,
}
/// A stack frame (`stackTrace` response).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StackFrame {
/// Frame id used to scope `scopes`/`evaluate`.
pub id: i64,
/// Frame (function) name.
pub name: String,
/// Source location, if resolved.
#[serde(default)]
pub source: Option<Source>,
/// 1-based line.
#[serde(default)]
pub line: i64,
/// 1-based column.
#[serde(default)]
pub column: i64,
}
/// A variable scope (`scopes` response).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Scope {
/// Scope name (e.g. "Locals").
pub name: String,
/// Reference for a `variables` request.
#[serde(rename = "variablesReference")]
pub variables_reference: i64,
/// Whether retrieving this scope is expensive.
#[serde(default)]
pub expensive: bool,
/// What the scope holds (`arguments`, `locals`, `registers`), when the adapter says
#[serde(rename = "presentationHint", default)]
pub presentation_hint: Option<String>,
}
/// A variable (`variables` / `evaluate` response).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Variable {
pub name: String,
/// Rendered value.
pub value: String,
/// Declared type, if the adapter provides it.
#[serde(rename = "type", default)]
pub type_name: Option<String>,
/// Non-zero when the variable is structured (expandable).
#[serde(rename = "variablesReference", default)]
pub variables_reference: i64,
}
/// A breakpoint verification result (`setBreakpoints` response).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Breakpoint {
/// Whether the adapter bound the breakpoint.
#[serde(default)]
pub verified: bool,
/// Resolved line, if the adapter moved it.
#[serde(default)]
pub line: Option<i64>,
/// Explanation when unverified.
#[serde(default)]
pub message: Option<String>,
}
/// Body of a `stopped` event.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct StoppedBody {
/// Why execution stopped (e.g. "breakpoint", "step", "exception").
#[serde(default)]
pub reason: String,
/// Thread that stopped, if reported.
#[serde(rename = "threadId", default)]
pub thread_id: Option<i64>,
#[serde(default)]
pub description: Option<String>,
/// Extra detail (e.g. exception text).
#[serde(default)]
pub text: Option<String>,
}

View File

@@ -0,0 +1,428 @@
//! Debug session management — the warm, per-workspace `DapService`.
//!
//! Owns live [`DapSession`]s keyed by id, runs the DAP launch choreography (initialize → launch →
//! `initialized` event → breakpoints → configurationDone → first stop), and routes control/read
//! actions to a session's client. Mirrors the LSP service pattern: sessions are reused across tool
//! calls rather than re-created per request.
use crate::adapter::{self};
use crate::client::{DapClient, DapError};
use crate::protocol::{Scope, StackFrame, StoppedBody, Thread, Variable};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex as SyncMutex};
use std::time::Duration;
use tokio::sync::Mutex;
mod breakpoints;
mod startup;
use breakpoints::parse_array;
pub use breakpoints::{set_breakpoints, set_function_breakpoints};
const STOP_TIMEOUT: Duration = Duration::from_secs(30);
/// Override for [`STOP_TIMEOUT`], for a program whose next stop is genuinely far away.
const STOP_TIMEOUT_ENV: &str = "LUXE_DAP_STOP_TIMEOUT_SECS";
/// How long to wait for a resumed program to stop.
fn stop_timeout() -> Duration {
std::env::var(STOP_TIMEOUT_ENV)
.ok()
.and_then(|raw| raw.trim().parse::<u64>().ok())
.filter(|secs| *secs > 0)
.map_or(STOP_TIMEOUT, Duration::from_secs)
}
const CONTROL_TIMEOUT: Duration = Duration::from_secs(15);
/// A live debug session's status for `/debug` and the dock DEBUG section.
#[derive(Debug, Clone)]
pub struct DapSessionInfo {
/// Session id (from launch/attach).
pub id: String,
/// Backing adapter id.
pub adapter: String,
/// Debuggee program / label.
pub program: String,
/// Whether the debuggee has terminated.
pub terminated: bool,
/// Whether the debuggee is currently paused at a stop (breakpoint/step/exception).
pub stopped: bool,
/// Why it stopped, when paused (e.g. `breakpoint`).
pub stop_reason: Option<String>,
}
/// One source-line breakpoint, optionally conditional.
#[derive(Debug, Clone)]
pub struct SourceBreakpoint {
/// 1-based line number.
pub line: i64,
/// Break only when this expression is true (adapter-evaluated), if set.
pub condition: Option<String>,
}
/// A source file's breakpoints.
#[derive(Debug, Clone)]
pub struct BreakpointRequest {
/// Absolute or workspace-relative source path.
pub path: String,
/// Breakpoints to set in this file.
pub breakpoints: Vec<SourceBreakpoint>,
}
/// A breakpoint that triggers on entry to a named function, optionally conditional.
#[derive(Debug, Clone)]
pub struct FunctionBreakpoint {
/// Function name to break on.
pub name: String,
/// Break only when this expression is true, if set.
pub condition: Option<String>,
}
/// Outcome of a launch: the new session plus where it first stopped (or that it ran to completion).
#[derive(Debug, Clone)]
pub struct LaunchOutcome {
/// Stable session id for follow-up actions.
pub session_id: String,
/// Adapter that backs the session.
pub adapter_id: String,
/// First stop, if the program paused (breakpoint / entry / exception).
pub stop: Option<StoppedBody>,
/// Whether the program already terminated.
pub terminated: bool,
/// Captured program output so far.
pub output: String,
/// Breakpoints the adapter did not bind, each with its reason
pub unverified: Vec<String>,
}
/// `path` as the adapter needs it: absolute, relative ones taken from `base`.
///
/// Adapters resolve a relative path against their own idea of a directory, or not at all: `gdb`
/// leaves `src/lib.rs` pending as "No source file named src/lib.rs".
pub fn resolve(path: &str, base: &str) -> String {
let candidate = Path::new(path);
if candidate.is_absolute() {
path.to_string()
} else {
Path::new(base).join(candidate).to_string_lossy().into_owned()
}
}
/// One live debug session.
pub struct DapSession {
/// Stable session id.
pub id: String,
/// Backing adapter id.
pub adapter_id: String,
/// Debuggee program (path).
pub program: String,
/// Directory the program runs in, which relative breakpoint paths resolve against
pub cwd: String,
/// The adapter connection.
pub client: Arc<DapClient>,
/// Thread selected by the last stop (default for control actions); interior-mutable so control
/// methods stay `&self`.
current_thread: SyncMutex<Option<i64>>,
}
/// Warm, per-workspace debug service.
#[derive(Default)]
pub struct DapService {
sessions: Mutex<HashMap<String, Arc<DapSession>>>,
next_id: AtomicU64,
/// User-configured adapters (extension-routed + selectable by id), shadowing built-ins.
custom: Vec<adapter::ConfiguredAdapter>,
}
impl DapService {
/// Create an empty service (built-in adapters only).
pub fn new() -> Self {
Self::default()
}
/// Whether this service could debug anything at all — i.e. some adapter is installed.
pub fn has_adapter(&self) -> bool {
adapter::any_adapter_available(&self.custom)
}
/// Create a service with user-configured custom adapters (from config).
pub fn with_adapters(custom: Vec<adapter::CustomAdapter>) -> Self {
Self {
custom: custom.iter().map(adapter::ConfiguredAdapter::from_custom).collect(),
..Self::default()
}
}
/// Launch a program under a debug adapter, applying breakpoints, and wait for the first stop.
pub async fn launch(
&self,
program: String,
args: Vec<String>,
cwd: String,
stop_on_entry: bool,
breakpoints: Vec<BreakpointRequest>,
adapter: Option<String>,
) -> Result<LaunchOutcome, DapError> {
let spec = adapter::resolve(&program, adapter.as_deref(), &self.custom)?;
let request_args = spec.launch_arguments(&program, &args, &cwd, stop_on_entry);
self.start(spec, "launch".to_string(), request_args, cwd, breakpoints, program).await
}
/// Attach to a running process (`pid`) or a listening adapter (`port`).
pub async fn attach(
&self,
pid: Option<i64>,
port: Option<i64>,
cwd: String,
breakpoints: Vec<BreakpointRequest>,
adapter: Option<String>,
) -> Result<LaunchOutcome, DapError> {
// No program path for attach; `resolve("", ...)` picks the native adapter unless overridden.
let spec = adapter::resolve("", adapter.as_deref(), &self.custom)?;
let request_args = spec.attach_arguments(pid, port);
let label = pid
.map(|p| format!("attach pid {p}"))
.or_else(|| port.map(|p| format!("attach :{p}")))
.unwrap_or_else(|| "attach".to_string());
self.start(spec, "attach".to_string(), request_args, cwd, breakpoints, label).await
}
/// Shared launch/attach choreography: initialize → request → `initialized` → breakpoints →
/// configurationDone → first stop. `label` names the session's program column.
async fn start(
&self,
spec: adapter::AdapterSpec,
request: String,
request_args: Value,
cwd: String,
breakpoints: Vec<BreakpointRequest>,
label: String,
) -> Result<LaunchOutcome, DapError> {
// stdio adapters run over the child's pipes; socket adapters dial in over TCP.
let connected = match &spec.transport {
adapter::Transport::Stdio => DapClient::spawn(&spec.command, Path::new(&cwd)).await,
adapter::Transport::TcpDialIn { placeholder } => {
DapClient::connect_dial_in(&spec.command, Path::new(&cwd), placeholder).await
}
};
let client = Arc::new(connected?);
let launch = startup::Launch { client: &client, adapter: &spec.id, request: &request };
let started = launch.handshake(request_args).await?;
let unverified = launch.configure(&breakpoints, &cwd, started.configuration_done).await?;
let stop = launch.first_stop(started.pending).await?;
let id = format!("dbg-{}", self.next_id.fetch_add(1, Ordering::Relaxed) + 1);
let current_thread = stop.as_ref().and_then(|s| s.thread_id);
let outcome = LaunchOutcome {
session_id: id.clone(),
adapter_id: spec.id.to_string(),
stop,
terminated: client.is_terminated(),
output: client.output_for_display(),
unverified,
};
let session = DapSession {
id: id.clone(),
adapter_id: spec.id.to_string(),
program: label,
cwd,
client,
current_thread: SyncMutex::new(current_thread),
};
self.sessions.lock().await.insert(id, Arc::new(session));
Ok(outcome)
}
/// Fetch a session handle by id.
pub async fn get(&self, id: &str) -> Option<Arc<DapSession>> {
self.sessions.lock().await.get(id).cloned()
}
/// Describes every live session, in id order.
pub async fn list(&self) -> Vec<DapSessionInfo> {
let mut out: Vec<_> = self
.sessions
.lock()
.await
.values()
.map(|session| {
let terminated = session.client.is_terminated();
let last_stop = session.client.last_stop();
DapSessionInfo {
id: session.id.clone(),
adapter: session.adapter_id.clone(),
program: session.program.clone(),
terminated,
stopped: !terminated && last_stop.is_some(),
stop_reason: last_stop.map(|stop| stop.reason).filter(|r| !r.is_empty()),
}
})
.collect();
out.sort_by(|a, b| a.id.cmp(&b.id));
out
}
/// Terminate a session and drop it from the map.
pub async fn terminate(&self, id: &str) -> Result<(), DapError> {
let session = self.sessions.lock().await.remove(id).ok_or(DapError::NoSession)?;
session.client.shutdown().await;
Ok(())
}
/// Terminate every live session (used when leaving a project). Best-effort; the process-group
/// reaping on each client's drop is the backstop.
pub async fn terminate_all(&self) {
let ids: Vec<String> = self.sessions.lock().await.keys().cloned().collect();
for id in ids {
let _ = self.terminate(&id).await;
}
}
}
impl DapSession {
/// Resolve the thread to act on: an explicit id, else the last stopped thread.
fn thread(&self, explicit: Option<i64>) -> Result<i64, DapError> {
let current = *self.current_thread.lock().expect("session state poisoned");
explicit.or(current).ok_or(DapError::NoThread)
}
/// Record the thread selected by the most recent stop.
fn remember_stop(&self, stop: &Option<StoppedBody>) {
if let Some(thread_id) = stop.as_ref().and_then(|s| s.thread_id) {
*self.current_thread.lock().expect("session state poisoned") = Some(thread_id);
}
}
/// Resume execution; waits for the next stop or termination.
pub async fn continue_(&self, thread: Option<i64>) -> Result<Option<StoppedBody>, DapError> {
let thread = self.thread(thread)?;
self.client.clear_stop();
self.client.request("continue", json!({ "threadId": thread }), CONTROL_TIMEOUT).await?;
let stop = self.await_stop("continue").await?;
self.remember_stop(&stop);
Ok(stop)
}
/// Wait for the stop that `command` was expected to produce, and say what it means if none
/// comes.
///
/// An adapter can accept a resume, answer `success: true`, and then report nothing — gdb does
/// exactly that for a `stepIn` with nowhere to step. The program is *running*, so the error
/// says that, with the two actions that reach a running program, rather than naming a wait.
async fn await_stop(&self, command: &str) -> Result<Option<StoppedBody>, DapError> {
let budget = stop_timeout();
match self.client.wait_for_stop_or_terminate(budget).await {
Err(DapError::Timeout { .. }) => Err(DapError::StillRunning {
command: command.to_string(),
secs: budget.as_secs(),
env: STOP_TIMEOUT_ENV,
}),
other => other,
}
}
/// Step (`next`, `stepIn`, `stepOut`); waits for the next stop.
pub async fn step(
&self,
command: &str,
thread: Option<i64>,
) -> Result<Option<StoppedBody>, DapError> {
let thread = self.thread(thread)?;
self.client.clear_stop();
self.client.request(command, json!({ "threadId": thread }), CONTROL_TIMEOUT).await?;
let stop = self.await_stop(command).await?;
self.remember_stop(&stop);
Ok(stop)
}
/// Pause a running thread.
pub async fn pause(&self, thread: Option<i64>) -> Result<(), DapError> {
let thread = self.thread(thread)?;
self.client
.request("pause", json!({ "threadId": thread }), CONTROL_TIMEOUT)
.await
.map(|_| ())
}
/// List threads.
pub async fn threads(&self) -> Result<Vec<Thread>, DapError> {
let body = self.client.request("threads", Value::Null, CONTROL_TIMEOUT).await?;
Ok(parse_array(&body, "threads"))
}
/// Fetch a thread's stack frames.
pub async fn stack_trace(&self, thread: Option<i64>) -> Result<Vec<StackFrame>, DapError> {
let thread = self.thread(thread)?;
let body = self
.client
.request("stackTrace", json!({ "threadId": thread, "levels": 20 }), CONTROL_TIMEOUT)
.await?;
Ok(parse_array(&body, "stackFrames"))
}
/// Fetch a frame's variable scopes.
pub async fn scopes(&self, frame_id: i64) -> Result<Vec<Scope>, DapError> {
let body =
self.client.request("scopes", json!({ "frameId": frame_id }), CONTROL_TIMEOUT).await?;
Ok(parse_array(&body, "scopes"))
}
/// Fetch variables for a `variablesReference`.
pub async fn variables(&self, variables_reference: i64) -> Result<Vec<Variable>, DapError> {
let body = self
.client
.request(
"variables",
json!({ "variablesReference": variables_reference }),
CONTROL_TIMEOUT,
)
.await?;
Ok(parse_array(&body, "variables"))
}
/// Evaluate an expression in a frame (or globally when `frame_id` is `None`).
pub async fn evaluate(
&self,
expression: &str,
frame_id: Option<i64>,
) -> Result<String, DapError> {
let mut args = json!({ "expression": expression, "context": "watch" });
if let Some(frame_id) = frame_id {
args["frameId"] = json!(frame_id);
}
let body = self.client.request("evaluate", args, CONTROL_TIMEOUT).await?;
Ok(body.get("result").and_then(Value::as_str).unwrap_or("").to_string())
}
/// Set a variable's value in a scope/structure; returns the adapter's rendered new value.
pub async fn set_variable(
&self,
variables_reference: i64,
name: &str,
value: &str,
) -> Result<String, DapError> {
let body = self
.client
.request(
"setVariable",
json!({ "variablesReference": variables_reference, "name": name, "value": value }),
CONTROL_TIMEOUT,
)
.await?;
Ok(body.get("value").and_then(Value::as_str).unwrap_or(value).to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn terminate_all_is_a_noop_when_no_sessions() {
let service = DapService::new();
service.terminate_all().await;
assert!(service.list().await.is_empty());
}
}

View File

@@ -0,0 +1,83 @@
//! Breakpoints — setting them, and saying which ones did not take.
use super::{FunctionBreakpoint, SourceBreakpoint, CONTROL_TIMEOUT};
use crate::client::{DapClient, DapError};
use crate::protocol::Breakpoint;
use serde_json::{json, Value};
/// Send a `setBreakpoints` request for one source file (with optional conditions) and parse the
/// results.
pub async fn set_breakpoints(
client: &DapClient,
path: &str,
breakpoints: &[SourceBreakpoint],
) -> Result<Vec<Breakpoint>, DapError> {
let breakpoints: Vec<Value> = breakpoints
.iter()
.map(|bp| match &bp.condition {
Some(condition) => json!({ "line": bp.line, "condition": condition }),
None => json!({ "line": bp.line }),
})
.collect();
let body = client
.request(
"setBreakpoints",
json!({
"source": { "path": path },
"breakpoints": breakpoints,
"sourceModified": false,
}),
CONTROL_TIMEOUT,
)
.await?;
Ok(parse_array(&body, "breakpoints"))
}
/// Send a `setFunctionBreakpoints` request (break on entry to named functions).
pub async fn set_function_breakpoints(
client: &DapClient,
breakpoints: &[FunctionBreakpoint],
) -> Result<Vec<Breakpoint>, DapError> {
let breakpoints: Vec<Value> = breakpoints
.iter()
.map(|bp| match &bp.condition {
Some(condition) => json!({ "name": bp.name, "condition": condition }),
None => json!({ "name": bp.name }),
})
.collect();
let body = client
.request("setFunctionBreakpoints", json!({ "breakpoints": breakpoints }), CONTROL_TIMEOUT)
.await?;
Ok(parse_array(&body, "breakpoints"))
}
/// Parse a typed array out of a response body field, dropping malformed entries.
pub(super) fn parse_array<T: serde::de::DeserializeOwned>(body: &Value, field: &str) -> Vec<T> {
body.get(field)
.and_then(Value::as_array)
.map(|items| items.iter().filter_map(|v| serde_json::from_value(v.clone()).ok()).collect())
.unwrap_or_default()
}
/// Each requested breakpoint in `path` the adapter did not bind, with its reason.
///
/// Answers line up with requests by position, as the protocol says; a request with no answer at
/// all was not bound either.
pub(super) fn unverified(
path: &str,
requested: &[SourceBreakpoint],
bound: &[Breakpoint],
) -> Vec<String> {
requested
.iter()
.enumerate()
.filter_map(|(index, request)| match bound.get(index) {
Some(answer) if answer.verified => None,
Some(answer) => {
let why = answer.message.as_deref().unwrap_or("not verified by the adapter");
Some(format!("{path}:{}: {why}", request.line))
}
None => Some(format!("{path}:{}: the adapter did not answer for it", request.line)),
})
.collect()
}

View File

@@ -0,0 +1,194 @@
//! Startup — the launch and attach choreography, step by step.
//!
//! initialize → launch/attach → `initialized` → breakpoints → configurationDone → first stop. Each
//! step that can fail says what happened in the user's terms, with whatever the adapter wrote to
//! stderr, because an adapter that cannot start usually explains itself there and nowhere else.
use super::{breakpoints, resolve, stop_timeout, BreakpointRequest, CONTROL_TIMEOUT};
use crate::client::{DapClient, DapError, PendingRequest};
use crate::protocol::StoppedBody;
use serde_json::{json, Value};
use std::time::Duration;
const INIT_TIMEOUT: Duration = Duration::from_secs(10);
const LAUNCH_TIMEOUT: Duration = Duration::from_secs(30);
/// Said when attaching fails quietly, which is how a refused ptrace looks from here.
///
/// An adapter that never answers has not failed in any way it will tell us about: `gdb
/// --interpreter=dap` asked to attach to a process it may not ptrace simply goes quiet. An internal
/// `request 'event' timed out` would name a wait instead of the situation, for the failure a user
/// can most readily fix.
const PTRACE_HINT: &str = " — attaching to a process you did not start needs ptrace permission: \
check `sysctl kernel.yama.ptrace_scope` (1 forbids it), or launch the \
program from here instead of attaching";
/// What a handshake leaves to finish: the launch or attach reply, and whether the adapter said it
/// takes `configurationDone`.
pub(super) struct Started {
pub(super) pending: PendingRequest,
pub(super) configuration_done: bool,
}
/// One launch or attach in progress.
pub(super) struct Launch<'a> {
pub(super) client: &'a DapClient,
/// The adapter's id, for messages
pub(super) adapter: &'a str,
/// `launch` or `attach`
pub(super) request: &'a str,
}
impl Launch<'_> {
/// Initializes the adapter, sends the launch or attach, and waits for `initialized`.
///
/// The request goes out before `configurationDone` but is answered after it, as the protocol's
/// choreography has it, so its reply is returned to await later. It is written inline rather
/// than from a spawned task, which is what keeps the two writes in order.
pub(super) async fn handshake(&self, request_args: Value) -> Result<Started, DapError> {
let init_args = json!({
"clientID": "luxe",
"adapterID": self.adapter,
"linesStartAt1": true,
"columnsStartAt1": true,
"pathFormat": "path",
"supportsRunInTerminalRequest": false,
});
let capabilities = match self.client.request("initialize", init_args, INIT_TIMEOUT).await {
Ok(capabilities) => capabilities,
Err(error) => {
let message = format!("the {} adapter did not initialize: {error}", self.adapter);
return Err(self.with_stderr(message).await);
}
};
let configuration_done = capabilities
.get("supportsConfigurationDoneRequest")
.and_then(Value::as_bool)
.unwrap_or(false);
// The program does not exist yet, so anything said so far was the adapter's own.
self.client.discard_output_so_far();
// an adapter that answered and died at once loses the race to this write, not to the wait
let pending = match self.client.write_request(self.request, request_args).await {
Ok(pending) => pending,
Err(DapError::Cancelled | DapError::Io(_)) => return Err(self.exited_starting().await),
Err(error) => return Err(error),
};
// Quiet is the failure here; see [`PTRACE_HINT`] for why it is named, not a timeout.
match self.client.wait_for_initialized(INIT_TIMEOUT).await {
Ok(()) => {}
Err(DapError::Cancelled) => return Err(self.exited_starting().await),
Err(_) => {
let mut message = format!(
"the {} adapter never finished starting ({}s)",
self.adapter,
INIT_TIMEOUT.as_secs()
);
self.hint(&mut message);
return Err(self.with_stderr(message).await);
}
}
Ok(Started { pending, configuration_done })
}
/// Sets the breakpoints and finishes configuration, returning the breakpoints that did not
/// bind.
///
/// A refused `configurationDone` from an adapter that advertised it is a failed start, since
/// the program never runs. One that never advertised it is still sent it, and its refusal is
/// only logged: the protocol says not to ask, and some adapters need asking anyway.
pub(super) async fn configure(
&self,
requests: &[BreakpointRequest],
cwd: &str,
advertised: bool,
) -> Result<Vec<String>, DapError> {
let mut unverified = Vec::new();
for request in requests {
let path = resolve(&request.path, cwd);
match breakpoints::set_breakpoints(self.client, &path, &request.breakpoints).await {
Ok(bound) => {
unverified.extend(breakpoints::unverified(&path, &request.breakpoints, &bound));
}
Err(error) => unverified.push(format!("{path}: {error}")),
}
}
match self.client.request("configurationDone", Value::Null, CONTROL_TIMEOUT).await {
Ok(_) => {}
Err(error) if !advertised => {
let adapter = self.adapter;
tracing::debug!(%error, adapter, "unadvertised configurationDone failed");
}
Err(error) => {
let message =
format!("the {} adapter refused `configurationDone`: {error}", self.adapter);
return Err(self.with_stderr(message).await);
}
}
Ok(unverified)
}
/// Awaits the launch or attach reply, then the first stop or the end of the program.
pub(super) async fn first_stop(
&self,
pending: PendingRequest,
) -> Result<Option<StoppedBody>, DapError> {
let request = self.request;
// An adapter that never answers goes quiet for the whole launch timeout; see
// [`PTRACE_HINT`].
if let Err(error) = self.client.await_response(pending, request, LAUNCH_TIMEOUT).await {
let adapter = self.adapter;
let mut message = match error {
DapError::Cancelled => {
format!("the {adapter} adapter exited before answering `{request}`")
}
DapError::RequestFailed { message, .. } => {
format!("the {adapter} adapter refused `{request}`: {message}")
}
_ => format!(
"the {adapter} adapter did not answer `{request}` within {}s",
LAUNCH_TIMEOUT.as_secs()
),
};
self.hint(&mut message);
return Err(self.with_stderr(message).await);
}
// The adapter accepted the launch or attach and then reported nothing. `gdb
// --interpreter=dap` does exactly that when asked to attach to a process it may not
// ptrace: it answers the request, and no stop ever comes.
match self.client.wait_for_stop_or_terminate(stop_timeout()).await {
Ok(stop) => Ok(stop),
Err(DapError::Timeout { .. }) => {
let mut message = format!(
"the {} adapter accepted `{request}` but the program never stopped or \
exited ({}s)",
self.adapter,
stop_timeout().as_secs()
);
self.hint(&mut message);
Err(DapError::StartFailed(message))
}
Err(error) => Err(error),
}
}
/// The adapter went away after `initialize`, said with whatever it printed on the way out.
async fn exited_starting(&self) -> DapError {
let mut message = format!("the {} adapter exited while starting", self.adapter);
self.hint(&mut message);
self.with_stderr(message).await
}
fn hint(&self, message: &mut String) {
if self.request == "attach" {
message.push_str(PTRACE_HINT);
}
}
/// `message`, with what the adapter wrote to stderr when it wrote anything.
async fn with_stderr(&self, message: String) -> DapError {
DapError::StartFailed(match self.client.adapter_stderr().await {
stderr if stderr.is_empty() => message,
stderr => format!("{message}; the adapter said:\n{stderr}"),
})
}
}

600
crates/luxe-dap/src/tool.rs Normal file
View File

@@ -0,0 +1,600 @@
//! The `debug` tool — one action-enum surface over the DAP service.
//!
//! Read actions (threads/stack_trace/scopes/variables/output/sessions) never mutate program state;
//! exec actions (launch/attach/breakpoints/continue/step/pause/evaluate/terminate) run the
//! debuggee and are gated whenever the permission hook is enabled (the `debug` tool is classified
//! mutating). On every stop the result auto-injects the top frame + locals so the model sees where
//! it is without extra round-trips.
use crate::protocol::StoppedBody;
use crate::service::{
BreakpointRequest, DapService, DapSession, FunctionBreakpoint, SourceBreakpoint,
};
use async_trait::async_trait;
use luxe_core::provider::ToolSchema;
use luxe_core::{Tool, ToolContext, ToolResultData};
use std::path::Path;
use std::sync::Arc;
mod failure;
mod schema;
use failure::Failure;
/// Max locals rendered in an auto stop-summary.
const MAX_LOCALS: usize = 24;
/// The `debug` tool.
pub struct DebugTool {
service: Arc<DapService>,
}
impl DebugTool {
/// Create the tool over a shared warm debug service.
pub fn new(service: Arc<DapService>) -> Self {
Self { service }
}
}
#[async_trait]
impl Tool for DebugTool {
fn name(&self) -> &str {
"debug"
}
fn schema(&self) -> ToolSchema {
schema::schema()
}
async fn run(&self, args: serde_json::Value, cx: &ToolContext) -> ToolResultData {
let Some(action) = args.get("action").and_then(|v| v.as_str()) else {
return ToolResultData::error("Error: 'action' is required");
};
match self.dispatch(action, &args, cx).await {
Ok(text) => ToolResultData::text(text),
Err(failure) => ToolResultData::error(failure.to_string()),
}
}
}
impl DebugTool {
async fn dispatch(
&self,
action: &str,
args: &serde_json::Value,
cx: &ToolContext,
) -> Result<String, Failure> {
match action {
"launch" => self.launch(args, cx).await,
"attach" => self.attach(args, cx).await,
"sessions" => Ok(self.sessions().await),
_ => {
// All other actions operate on an existing session.
let id = str_arg(args, "session").ok_or("Error: 'session' is required")?;
let session = self.service.get(&id).await.ok_or_else(|| {
format!(
"Error: no active debug session '{id}'. It may have ended — use \
action=sessions to list, or launch/attach to start one."
)
})?;
// A program that ran to completion keeps its session (is_terminated) but its
// runtime is gone; give a clear message instead of a low-level adapter error.
if session.client.is_terminated() && Self::requires_live_program(action) {
return Err(Failure::Usage(format!(
"Error: debug session '{id}' has ended (program terminated); its runtime \
state is gone. Use action=output for remaining output, or launch/attach \
again to inspect."
)));
}
self.session_action(action, &session, args).await
}
}
}
async fn launch(&self, args: &serde_json::Value, cx: &ToolContext) -> Result<String, Failure> {
let program = str_arg(args, "program").ok_or("Error: 'program' is required for launch")?;
let cwd = str_arg(args, "cwd").unwrap_or_else(|| cx.cwd.display().to_string());
let program_abs = crate::service::resolve(&program, &cwd);
let outcome = self
.service
.launch(
program_abs,
string_array(args, "args"),
cwd,
args.get("stopOnEntry").and_then(|v| v.as_bool()).unwrap_or(false),
breakpoint_requests(args),
str_arg(args, "adapter"),
)
.await?;
Ok(self.report(&outcome).await)
}
/// What a launch or attach says: the session, its stop, what did not take, its output.
async fn report(&self, outcome: &crate::service::LaunchOutcome) -> String {
let mut out = format!("session {} ({})\n", outcome.session_id, outcome.adapter_id);
if let Some(session) = self.service.get(&outcome.session_id).await {
out.push_str(&stop_summary(&session, &outcome.stop).await);
} else if outcome.terminated {
out.push_str("Program terminated.\n");
}
if !outcome.unverified.is_empty() {
let unverified = outcome.unverified.join("\n ");
out.push_str(&format!("\nBreakpoints not set:\n {unverified}\n"));
}
if !outcome.output.is_empty() {
out.push_str(&format!("\n--- output ---\n{}", tail(&outcome.output)));
}
out
}
async fn attach(&self, args: &serde_json::Value, cx: &ToolContext) -> Result<String, Failure> {
let pid = args.get("pid").and_then(serde_json::Value::as_i64);
let port = args.get("port").and_then(serde_json::Value::as_i64);
if pid.is_none() && port.is_none() {
return Err("Error: attach needs a 'pid' or 'port'".into());
}
let cwd = str_arg(args, "cwd").unwrap_or_else(|| cx.cwd.display().to_string());
let outcome = self
.service
.attach(pid, port, cwd, breakpoint_requests(args), str_arg(args, "adapter"))
.await?;
Ok(self.report(&outcome).await)
}
async fn session_action(
&self,
action: &str,
session: &DapSession,
args: &serde_json::Value,
) -> Result<String, Failure> {
let thread = args.get("threadId").and_then(serde_json::Value::as_i64);
match action {
"set_breakpoints" => set_breakpoints(session, args).await,
"set_function_breakpoints" => set_function_breakpoints(session, args).await,
"set_variable" => set_variable(session, args).await,
"continue" => Ok(stop_summary(session, &session.continue_(thread).await?).await),
"next" => Ok(stop_summary(session, &session.step("next", thread).await?).await),
"step_in" => Ok(stop_summary(session, &session.step("stepIn", thread).await?).await),
"step_out" => Ok(stop_summary(session, &session.step("stepOut", thread).await?).await),
"pause" => {
session.pause(thread).await?;
Ok("pause requested".to_string())
}
"threads" => {
let threads = session.threads().await?;
Ok(threads
.iter()
.map(|t| format!("{}: {}", t.id, t.name))
.collect::<Vec<_>>()
.join("\n"))
}
"stack_trace" => {
let frames = session.stack_trace(thread).await?;
Ok(render_frames(&frames, &session.cwd))
}
"scopes" => {
let frame_id = args
.get("frameId")
.and_then(serde_json::Value::as_i64)
.ok_or("Error: 'frameId' is required")?;
let scopes = session.scopes(frame_id).await?;
Ok(scopes
.iter()
.map(|s| format!("{} (ref {})", s.name, s.variables_reference))
.collect::<Vec<_>>()
.join("\n"))
}
"variables" => {
let vref = args
.get("variablesReference")
.and_then(serde_json::Value::as_i64)
.ok_or("Error: 'variablesReference' is required")?;
let vars = session.variables(vref).await?;
Ok(render_variables(&vars))
}
"evaluate" => evaluate(session, args).await,
"output" => Ok(tail(&session.client.output_for_display())),
"terminate" => {
self.service.terminate(&session.id).await?;
Ok(format!("terminated session {}", session.id))
}
other => Err(Failure::Usage(format!("Error: unknown action '{other}'"))),
}
}
/// Whether an action needs the debuggee still running (false for output/terminate, which are
/// meaningful on an already-ended session).
fn requires_live_program(action: &str) -> bool {
!matches!(action, "output" | "terminate")
}
async fn sessions(&self) -> String {
let sessions = self.service.list().await;
if sessions.is_empty() {
return "No debug sessions.".to_string();
}
sessions
.iter()
.map(|s| {
let state = if s.terminated {
"terminated".to_string()
} else if s.stopped {
match &s.stop_reason {
Some(reason) => format!("stopped: {reason}"),
None => "stopped".to_string(),
}
} else {
"running".to_string()
};
format!("{} [{state}] {} · {}", s.id, s.adapter, s.program)
})
.collect::<Vec<_>>()
.join("\n")
}
}
/// Renders a stop: reason + top frame location + top-scope locals (auto-injected context).
async fn stop_summary(session: &DapSession, stop: &Option<StoppedBody>) -> String {
let Some(stop) = stop else {
return "Program terminated.".to_string();
};
let mut out = format!("stopped: {}", stop.reason);
if let Some(text) = stop.text.as_deref().filter(|t| !t.is_empty()) {
out.push_str(&format!(" — {text}"));
}
out.push('\n');
let Ok(frames) = session.stack_trace(None).await else {
return out;
};
let Some(top) = frames.first() else {
return out;
};
out.push_str(&format!("at {} ({})\n", top.name, frame_location(top)));
let scopes = session.scopes(top.id).await.unwrap_or_default();
for scope in scopes.iter().filter(|scope| shown_on_stop(scope)) {
if let Ok(vars) = session.variables(scope.variables_reference).await {
if !vars.is_empty() {
out.push_str(&format!("{}:\n{}\n", scope.name, render_variables(&vars)));
}
}
}
out
}
/// Whether a stop shows this scope's variables unasked.
///
/// Every cheap scope but the registers: `gdb` splits a frame into Arguments and Locals, and taking
/// only the first showed the arguments and never the locals, while a frame with no debug info
/// offered its 85 registers in their place.
fn shown_on_stop(scope: &crate::protocol::Scope) -> bool {
let registers = scope.presentation_hint.as_deref() == Some("registers")
|| scope.name.eq_ignore_ascii_case("registers");
!scope.expensive && !registers
}
/// Frames this deep or deeper are listed only when they are the program's own.
const FRAMES_ALWAYS_SHOWN: usize = 3;
/// A stack as a list, with runs of frames outside `project` folded into a count.
///
/// A Rust test stopped two frames into its own code sits on 17 more of `core`, `std` and the test
/// runner, 600 tokens that say nothing about the bug. The top frames always show, since a stop
/// inside a library is still where the program is.
fn render_frames(frames: &[crate::protocol::StackFrame], project: &str) -> String {
let ours = |frame: &crate::protocol::StackFrame| {
frame
.source
.as_ref()
.and_then(|source| source.path.as_deref())
.is_some_and(|path| Path::new(path).starts_with(project))
};
let mut lines = Vec::new();
let mut folded: Vec<i64> = Vec::new();
let fold = |lines: &mut Vec<String>, folded: &mut Vec<i64>| {
match folded.as_slice() {
[] => {}
[only] => lines.push(format!("#{only} (outside the project)")),
[first, .., last] => lines.push(format!(
"… {} frames outside the project, #{first} to #{last}",
folded.len()
)),
}
folded.clear();
};
for (depth, frame) in frames.iter().enumerate() {
if depth < FRAMES_ALWAYS_SHOWN || ours(frame) {
fold(&mut lines, &mut folded);
lines.push(format!("#{} {} ({})", frame.id, frame.name, frame_location(frame)));
} else {
folded.push(frame.id);
}
}
fold(&mut lines, &mut folded);
lines.join("\n")
}
fn frame_location(frame: &crate::protocol::StackFrame) -> String {
let file = frame
.source
.as_ref()
.and_then(|s| s.name.clone().or_else(|| s.path.clone()))
.unwrap_or_else(|| "?".to_string());
format!("{file}:{}", frame.line)
}
fn render_variables(vars: &[crate::protocol::Variable]) -> String {
let mut out: Vec<String> = vars
.iter()
.take(MAX_LOCALS)
.map(|v| {
// A structured value can render as nothing at all (`gdb` on a slice), which read as
// a variable without one; the reference is how to look inside
let value = match (v.value.is_empty(), v.variables_reference) {
(true, 0) => "\"\"".to_string(),
(true, reference) => format!("{{…}} (variablesReference {reference})"),
(false, 0) => v.value.clone(),
(false, reference) => format!("{} (variablesReference {reference})", v.value),
};
match &v.type_name {
Some(ty) if !ty.is_empty() => format!(" {} : {ty} = {value}", v.name),
_ => format!(" {} = {value}", v.name),
}
})
.collect();
if vars.len() > MAX_LOCALS {
out.push(format!(" … {} more", vars.len() - MAX_LOCALS));
}
out.join("\n")
}
/// Keep only the tail of possibly-long program output.
fn tail(output: &str) -> String {
const MAX: usize = 4000;
if output.len() <= MAX {
return output.to_string();
}
format!("…{}", &output[luxe_core::output_limit::ceil_boundary(output, output.len() - MAX)..])
}
/// Parse launch/attach breakpoints: `[{path, lines:[..], conditions?:[..]}]` or
/// `[{path, breakpoints:[{line, condition?}]}]`. Per-line conditions align with `lines` by index;
/// a `conditions` list shorter than `lines` leaves the rest unconditional.
fn breakpoint_requests(args: &serde_json::Value) -> Vec<BreakpointRequest> {
args.get("breakpoints")
.and_then(|v| v.as_array())
.map(|entries| entries.iter().filter_map(parse_breakpoint_entry).collect())
.unwrap_or_default()
}
fn parse_breakpoint_entry(entry: &serde_json::Value) -> Option<BreakpointRequest> {
let path = entry.get("path")?.as_str()?.to_string();
// Explicit `breakpoints: [{line, condition?}]` form.
if let Some(list) = entry.get("breakpoints").and_then(|v| v.as_array()) {
let breakpoints = list
.iter()
.filter_map(|bp| {
Some(SourceBreakpoint {
line: bp.get("line")?.as_i64()?,
condition: bp.get("condition").and_then(|c| c.as_str()).map(str::to_string),
})
})
.collect();
return Some(BreakpointRequest { path, breakpoints });
}
// Simple `lines: [..]` (+ optional aligned `conditions: [..]`) form.
let conditions = entry.get("conditions").and_then(|v| v.as_array());
let breakpoints = entry
.get("lines")
.and_then(|v| v.as_array())
.map(|lines| {
lines
.iter()
.enumerate()
.filter_map(|(index, line)| {
Some(SourceBreakpoint {
line: line.as_i64()?,
condition: conditions
.and_then(|c| c.get(index))
.and_then(|c| c.as_str())
.map(str::to_string),
})
})
.collect()
})
.unwrap_or_default();
Some(BreakpointRequest { path, breakpoints })
}
fn str_arg(args: &serde_json::Value, key: &str) -> Option<String> {
args.get(key).and_then(|v| v.as_str()).map(str::to_string)
}
fn string_array(args: &serde_json::Value, key: &str) -> Vec<String> {
args.get(key)
.and_then(|v| v.as_array())
.map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
.unwrap_or_default()
}
fn int_array(args: &serde_json::Value, key: &str) -> Vec<i64> {
args.get(key)
.and_then(|v| v.as_array())
.map(|a| a.iter().filter_map(serde_json::Value::as_i64).collect())
.unwrap_or_default()
}
/// Sets the breakpoints for one file's lines.
async fn set_breakpoints(
session: &DapSession,
args: &serde_json::Value,
) -> Result<String, Failure> {
let path = str_arg(args, "path").ok_or("Error: 'path' is required")?;
let condition = str_arg(args, "condition");
let breakpoints: Vec<SourceBreakpoint> = int_array(args, "lines")
.into_iter()
.map(|line| SourceBreakpoint { line, condition: condition.clone() })
.collect();
let path_abs = crate::service::resolve(&path, &session.cwd);
let bps = crate::service::set_breakpoints(&session.client, &path_abs, &breakpoints).await?;
let verified = bps.iter().filter(|b| b.verified).count();
Ok(format!("set {} breakpoint(s) in {path}, {verified} verified", bps.len()))
}
/// Sets breakpoints on functions by name.
async fn set_function_breakpoints(
session: &DapSession,
args: &serde_json::Value,
) -> Result<String, Failure> {
let condition = str_arg(args, "condition");
let breakpoints: Vec<FunctionBreakpoint> = string_array(args, "functions")
.into_iter()
.map(|name| FunctionBreakpoint { name, condition: condition.clone() })
.collect();
if breakpoints.is_empty() {
return Err("Error: 'functions' is required".into());
}
let bps = crate::service::set_function_breakpoints(&session.client, &breakpoints).await?;
let verified = bps.iter().filter(|b| b.verified).count();
Ok(format!("set {} function breakpoint(s), {verified} verified", bps.len()))
}
/// Changes a variable's value in the stopped frame.
async fn set_variable(session: &DapSession, args: &serde_json::Value) -> Result<String, Failure> {
let vref = args
.get("variablesReference")
.and_then(serde_json::Value::as_i64)
.ok_or("Error: 'variablesReference' is required")?;
let name = str_arg(args, "name").ok_or("Error: 'name' is required")?;
let value = str_arg(args, "value").ok_or("Error: 'value' is required")?;
let updated = session.set_variable(vref, &name, &value).await?;
Ok(format!("{name} = {updated}"))
}
/// Evaluates an expression in a frame, the stopped top one unless told otherwise.
async fn evaluate(session: &DapSession, args: &serde_json::Value) -> Result<String, Failure> {
let expr = str_arg(args, "expression").ok_or("Error: 'expression' is required")?;
// Default to the stopped top frame so an expression over locals resolves without a
// manual stack_trace first (evaluating globally can't see locals — a common trap).
let frame_id = match args.get("frameId").and_then(serde_json::Value::as_i64) {
Some(id) => Some(id),
None => session
.stack_trace(None)
.await
.ok()
.and_then(|frames| frames.first().map(|frame| frame.id)),
};
Ok(session.evaluate(&expr, frame_id).await?)
}
#[cfg(test)]
mod tests {
use super::DebugTool;
use crate::protocol::{Scope, Source, StackFrame, Variable};
fn frame(id: i64, path: &str) -> StackFrame {
StackFrame {
id,
name: format!("f{id}"),
source: Some(Source { name: Some("x.rs".into()), path: Some(path.into()) }),
line: 1,
column: 1,
}
}
/// The break this catches: the tail of long output was a byte slice, which panics the tool
/// call when it lands inside a multibyte char.
#[test]
fn a_long_tail_is_cut_on_a_char_boundary() {
let output = format!("x{}y", "é".repeat(2_500));
let tail = super::tail(&output);
assert!(tail.starts_with('…') && tail.len() <= 4_000 + '…'.len_utf8(), "{}", tail.len());
assert!(tail[..tail.len() - 1].chars().skip(1).all(|c| c == 'é'), "{tail}");
}
/// Past the top few, frames outside the project fold into a count, and the project's own
/// frames still show wherever they sit.
#[test]
fn library_frames_fold_into_a_count() {
let mut frames: Vec<StackFrame> =
(0..3).map(|id| frame(id, "/rustc/abc/library/core/x.rs")).collect();
frames.push(frame(3, "/proj/src/lib.rs"));
frames.extend((4..9).map(|id| frame(id, "/rustc/abc/library/std/x.rs")));
frames.push(frame(9, "/proj/src/main.rs"));
frames.push(frame(10, "/home/me/.cargo/registry/tokio/x.rs"));
let shown = super::render_frames(&frames, "/proj");
assert_eq!(
shown,
"#0 f0 (x.rs:1)\n#1 f1 (x.rs:1)\n#2 f2 (x.rs:1)\n#3 f3 (x.rs:1)\n\
… 5 frames outside the project, #4 to #8\n#9 f9 (x.rs:1)\n#10 (outside the project)"
);
// a sibling directory sharing the prefix is not the project
assert!(super::render_frames(
&[frame(0, "/a"), frame(1, "/a"), frame(2, "/a"), frame(3, "/projector/x.rs")],
"/proj"
)
.ends_with("#3 (outside the project)"));
}
/// Every cheap scope shows on a stop, so the locals come with the arguments; registers and
/// expensive scopes do not.
#[test]
fn a_stop_shows_every_cheap_scope_but_registers() {
let scope = |name: &str, hint: Option<&str>, expensive: bool| Scope {
name: name.into(),
variables_reference: 1,
expensive,
presentation_hint: hint.map(str::to_string),
};
assert!(super::shown_on_stop(&scope("Arguments", Some("arguments"), false)));
assert!(super::shown_on_stop(&scope("Locals", None, false)));
assert!(!super::shown_on_stop(&scope("Registers", None, false)));
assert!(!super::shown_on_stop(&scope("CPU", Some("registers"), false)));
assert!(!super::shown_on_stop(&scope("Globals", None, true)));
}
/// A structured value says how to look inside it, and one that renders as nothing still reads
/// as a value.
#[test]
fn a_structured_value_names_its_reference() {
let var = |name: &str, value: &str, reference: i64| Variable {
name: name.into(),
value: value.into(),
type_name: None,
variables_reference: reference,
};
let shown = super::render_variables(&[
var("items", "", 4),
var("item", "0x5555", 5),
var("sum", "0", 0),
var("name", "", 0),
]);
assert_eq!(
shown,
" items = {…} (variablesReference 4)\n item = 0x5555 (variablesReference 5)\n \
sum = 0\n name = \"\""
);
}
#[test]
fn a_relative_path_resolves_against_the_directory_not_the_program() {
let base = std::env::temp_dir();
let base = base.to_string_lossy();
let joined = std::path::Path::new(&*base).join("src/lib.rs");
assert_eq!(crate::service::resolve("src/lib.rs", &base), joined.to_string_lossy());
let absolute = joined.to_string_lossy();
assert_eq!(crate::service::resolve(&absolute, "/elsewhere"), absolute);
}
#[test]
fn live_program_guard_allows_output_and_terminate() {
// Actions that still make sense on an ended session.
assert!(!DebugTool::requires_live_program("output"));
assert!(!DebugTool::requires_live_program("terminate"));
// Anything that touches the running program does not.
for action in ["continue", "next", "variables", "evaluate", "set_variable", "stack_trace"] {
assert!(DebugTool::requires_live_program(action), "{action} needs a live program");
}
}
}

View File

@@ -0,0 +1,38 @@
//! Failure — why a `debug` call produced no answer.
use crate::client::DapError;
/// Why a `debug` call produced no answer.
pub(super) enum Failure {
/// The call was wrong: a missing argument, an unknown action, a session that is gone
Usage(String),
/// The debugger said no
Dap(DapError),
}
impl std::fmt::Display for Failure {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Usage(message) => formatter.write_str(message),
Self::Dap(error) => error.fmt(formatter),
}
}
}
impl From<String> for Failure {
fn from(message: String) -> Self {
Self::Usage(message)
}
}
impl From<&str> for Failure {
fn from(message: &str) -> Self {
Self::Usage(message.to_string())
}
}
impl From<DapError> for Failure {
fn from(error: DapError) -> Self {
Self::Dap(error)
}
}

View File

@@ -0,0 +1,63 @@
//! The `debug` tool's schema — the action enum and what each action takes.
use luxe_core::provider::ToolSchema;
use serde_json::json;
pub(super) fn schema() -> ToolSchema {
ToolSchema {
name: "debug".to_string(),
description: "Drive a real debugger (DAP): launch/attach a program, set breakpoints, step, \
and inspect/modify state. Prefer this over print-debugging. Rust/C/C++ use \
CodeLLDB (or lldb-dap/gdb); Python uses debugpy. Start with launch (or attach); \
every follow-up takes the returned `session`. On each stop the result already \
includes the top frame + locals. Params by action: \
launch{program, args?, cwd?, breakpoints?, stopOnEntry?}; attach{pid | port}; \
set_breakpoints{session, path, lines, condition?}; \
set_function_breakpoints{session, functions}; \
continue|next|step_in|step_out|pause{session, threadId?}; \
threads|stack_trace{session}; scopes{session, frameId}; \
variables{session, variablesReference}; \
set_variable{session, variablesReference, name, value}; \
evaluate{session, expression, frameId?}; output|sessions|terminate{session}."
.to_string(),
parameters: json!({
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": [
"launch", "attach", "set_breakpoints", "set_function_breakpoints",
"continue", "next", "step_in", "step_out", "pause", "threads",
"stack_trace", "scopes", "variables", "set_variable", "evaluate",
"output", "sessions", "terminate"
],
"description": "The debug operation to perform."
},
"session": { "type": "string", "description": "Session id (from launch/attach) for follow-up actions." },
"program": { "type": "string", "description": "launch: path to the program/binary (or .py script)." },
"args": { "type": "array", "items": { "type": "string" }, "description": "launch: program arguments." },
"cwd": { "type": "string", "description": "launch/attach: working directory (default: tool cwd)." },
"adapter": { "type": "string", "description": "force an adapter (debugpy|codelldb|lldb-dap|gdb)." },
"stopOnEntry": { "type": "boolean", "description": "launch: pause at program entry (default false)." },
"pid": { "type": "integer", "description": "attach: process id to attach to (native)." },
"port": { "type": "integer", "description": "attach: port of a listening adapter (debugpy)." },
"breakpoints": {
"type": "array",
"description": "launch/set_breakpoints: [{path, lines:[..], conditions?:[..]}] or [{path, breakpoints:[{line, condition?}]}].",
"items": { "type": "object" }
},
"path": { "type": "string", "description": "set_breakpoints: source file path." },
"lines": { "type": "array", "items": { "type": "integer" }, "description": "set_breakpoints: 1-based lines." },
"condition": { "type": "string", "description": "set_breakpoints/set_function_breakpoints: break only when this expression is true." },
"functions": { "type": "array", "items": { "type": "string" }, "description": "set_function_breakpoints: function names to break on." },
"threadId": { "type": "integer", "description": "continue/step/pause/stack_trace: thread (default: last stopped)." },
"frameId": { "type": "integer", "description": "scopes/evaluate: stack frame id." },
"variablesReference": { "type": "integer", "description": "variables/set_variable: reference from a scope/variable." },
"name": { "type": "string", "description": "set_variable: variable name." },
"value": { "type": "string", "description": "set_variable: new value." },
"expression": { "type": "string", "description": "evaluate: expression to evaluate." }
},
"required": ["action"]
}),
}
}