luft_core/contract/backend.rs
1//! # AgentBackend Contract
2//!
3//! The [`AgentBackend`] trait is the **control-plane boundary** between Luft's
4//! orchestration runtime and the agent execution environment. Prompt goes in,
5//! structured [`AgentResult`] comes out.
6//!
7//! ## Implementing a Backend
8//!
9//! ```no_run
10//! use luft_core::contract::backend::*;
11//! use async_trait::async_trait;
12//!
13//! struct MyBackend;
14//!
15//! impl MyBackend {
16//! fn new() -> Self { Self }
17//! }
18//!
19//! #[async_trait]
20//! impl AgentBackend for MyBackend {
21//! fn id(&self) -> &'static str { "my-backend" }
22//!
23//! fn capabilities(&self) -> AgentCapabilities {
24//! AgentCapabilities {
25//! streaming: true,
26//! ..Default::default()
27//! }
28//! }
29//!
30//! async fn run(&self, task: AgentTask, ctx: RunContext)
31//! -> Result<AgentResult, BackendError>
32//! {
33//! // 1. Observe cancellation
34//! if ctx.cancel.is_cancelled() {
35//! return Err(BackendError::Cancelled);
36//! }
37//!
38//! // 2. Execute the agent task (your custom logic)
39//! let output = serde_json::json!({ "text": "hello" });
40//!
41//! // 3. Return structured result
42//! Ok(AgentResult {
43//! agent_id: task.agent_id,
44//! status: AgentStatus::Ok,
45//! output,
46//! findings: vec![],
47//! tokens_used: Default::default(),
48//! artifacts: vec![],
49//! logs: LogRef::default(),
50//! thread_id: None,
51//! })
52//! }
53//!
54//! fn as_any(&self) -> &dyn std::any::Any { self }
55//! }
56//! ```
57use crate::contract::event::EventSender;
58use crate::contract::finding::Finding;
59use crate::contract::ids::{AgentId, PhaseId, RunId, TokenUsage};
60use async_trait::async_trait;
61use serde::{Deserialize, Serialize};
62use std::path::PathBuf;
63use std::time::Duration;
64use tokio_util::sync::CancellationToken;
65
66/// A pluggable agent backend (e.g. OpenCode via ACP). Prompt in, structured
67/// result out.
68///
69/// # Contract
70///
71/// - **Cancellation**: implementations **must** observe `ctx.cancel` and return
72/// promptly with [`BackendError::Cancelled`] when the token fires.
73/// - **Id stability**: [`id()`](Self::id) must return a stable string for the
74/// backend's lifetime — it is used as the registry key.
75/// - **Thread safety**: the trait requires `Send + Sync`; backends are typically
76/// wrapped in `Arc<dyn AgentBackend>` and shared across tasks.
77/// - **Downcasting**: implement [`as_any()`](Self::as_any) by returning `self`
78/// to allow callers to downcast to the concrete backend type.
79///
80/// See the [module docs](self) for a complete implementation example.
81#[async_trait]
82pub trait AgentBackend: Send + Sync {
83 /// Stable backend id, e.g. "opencode".
84 fn id(&self) -> &'static str;
85
86 /// Capability declaration (v0.1: recorded/validated only; routing in v0.2).
87 fn capabilities(&self) -> AgentCapabilities;
88
89 /// Run one agent task to completion.
90 async fn run(&self, task: AgentTask, ctx: RunContext) -> Result<AgentResult, BackendError>;
91
92 /// Upcast hook for downcasting `&dyn AgentBackend` back to a concrete
93 /// backend type. Standard Rust trait-object downcast pattern: each impl
94 /// returns `self`, which `Any::downcast_ref` then narrows to `&Concrete`.
95 /// No default impl is provided — `Self` is unsized on a trait object, so a
96 /// default body `self` would not compile.
97 fn as_any(&self) -> &dyn std::any::Any;
98}
99
100#[derive(Debug, Clone, Default, Serialize, Deserialize)]
101pub struct AgentCapabilities {
102 pub streaming: bool,
103 pub mcp_injection: bool,
104 pub structured_output: bool,
105 /// Known model ids; empty = unknown/any.
106 pub models: Vec<String>,
107}
108
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct AgentTask {
111 pub agent_id: AgentId,
112 pub phase_id: PhaseId,
113 pub prompt: String,
114 pub model: Option<String>,
115 #[serde(default)]
116 pub description: Option<String>,
117 #[serde(default)]
118 pub role: Option<String>,
119 #[serde(default)]
120 pub name: Option<String>,
121 #[serde(default)]
122 pub agent_seq: u32,
123 pub allowlist: Option<ToolPolicy>,
124 pub workdir: PathBuf,
125 /// Data-plane injection point (Luft MCP endpoint).
126 pub mcp_endpoint: Option<McpEndpoint>,
127 /// Idle timeout: maximum silence (no ACP notifications) before the backend
128 /// kills the session. `None` = backend default (5 min).
129 pub timeout: Option<Duration>,
130 /// Optional JSON Schema (M4) for validating agent output.
131 /// When set, the runtime validates the agent's output against this schema
132 /// and may retry or reject if validation fails.
133 pub output_schema: Option<serde_json::Value>,
134
135 /// Per-agent working directory override from Lua `working_folder` opt.
136 #[serde(default)]
137 pub workdir_override: Option<PathBuf>,
138
139 /// Thread ID for cross-process conversation resume (Loom SqliteSaver).
140 #[serde(default, skip_serializing_if = "Option::is_none")]
141 pub thread_id: Option<String>,
142}
143
144#[derive(Debug, Clone, Serialize, Deserialize)]
145pub struct AgentResult {
146 pub agent_id: AgentId,
147 pub status: AgentStatus,
148 /// Structured output: prefers aggregated MCP findings, falls back to parsed
149 /// final message.
150 pub output: serde_json::Value,
151 #[serde(default)]
152 pub findings: Vec<Finding>,
153 pub tokens_used: TokenUsage,
154 #[serde(default)]
155 pub artifacts: Vec<Artifact>,
156 pub logs: LogRef,
157
158 /// Thread ID used during execution, echoed back for checkpoint linking.
159 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub thread_id: Option<String>,
161}
162
163#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
164pub enum AgentStatus {
165 Ok,
166 Error,
167 Cancelled,
168 TimedOut,
169}
170
171impl AgentStatus {
172 pub fn as_str(&self) -> &'static str {
173 match self {
174 AgentStatus::Ok => "ok",
175 AgentStatus::Error => "error",
176 AgentStatus::Cancelled => "cancelled",
177 AgentStatus::TimedOut => "timed_out",
178 }
179 }
180}
181
182/// Per-agent runtime context: cancellation + event sink + run association.
183#[derive(Clone)]
184pub struct RunContext {
185 pub run_id: RunId,
186 pub cancel: CancellationToken,
187 pub events: EventSender,
188}
189
190/// Tool permission policy. v0.1 translates to a backend's acceptEdits + command
191/// allowlist.
192#[derive(Debug, Clone, Default, Serialize, Deserialize)]
193pub struct ToolPolicy {
194 pub accept_edits: bool,
195 pub allow_commands: Vec<String>,
196 pub allow_mcp: Vec<String>,
197 /// Explicit denies (highest precedence).
198 pub deny: Vec<String>,
199}
200
201/// MCP data-plane endpoint injected into an agent for structured reporting.
202#[derive(Debug, Clone, Serialize, Deserialize)]
203pub struct McpEndpoint {
204 /// Server name injected into the agent, e.g. "luft".
205 pub name: String,
206 pub url: String,
207 pub run_id: RunId,
208 pub agent_id: AgentId,
209 pub auth_token: Option<String>,
210}
211
212#[derive(thiserror::Error, Debug)]
213pub enum BackendError {
214 #[error("spawn failed: {0}")]
215 Spawn(String),
216 #[error("protocol error: {0}")]
217 Protocol(String),
218 #[error("connection error: {0}")]
219 Connection(String),
220 #[error("backend timed out")]
221 Timeout,
222 #[error("cancelled")]
223 Cancelled,
224 #[error("configuration error: {0}")]
225 Config(String),
226 #[error("IO error: {0}")]
227 Io(String),
228 #[error("parse error: {0}")]
229 Parse(String),
230 #[error("execution error: {0}")]
231 Execution(String),
232 #[error(transparent)]
233 Other(#[from] anyhow::Error),
234}
235
236impl BackendError {
237 /// Distinguish retryable (transient/timeout) from non-retryable (protocol/logic).
238 pub fn is_retryable(&self) -> bool {
239 matches!(self, BackendError::Timeout | BackendError::Spawn(_))
240 }
241}
242
243#[derive(Debug, Clone, Serialize, Deserialize)]
244pub struct Artifact {
245 pub key: String,
246 pub path: Option<PathBuf>,
247 pub inline: Option<serde_json::Value>,
248}
249
250#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
251pub struct LogRef {
252 pub path: PathBuf,
253}
254
255// ── Process-global current backend identity ────────────────────────────
256
257/// Identity of the backend currently connected to this process, captured
258/// at the ACP `initialize` handshake.
259///
260/// Stored process-globally so any code path — not only the adapter itself —
261/// can answer "which backend am I talking to?". The agent primitive resolves
262/// its default backend (when the script omits `backend`) from this store via
263/// the [`id`](Self::id) field, rather than each caller threading an explicit
264/// `backend` argument through every call.
265///
266/// **Semantics**: written by the ACP adapter on every handshake. In the
267/// current single-backend model the value is constant for a run's lifetime.
268/// With multiple backends it becomes "most recently handshaken", so readers
269/// must tolerate concurrent writers; the scheduler falls back to the
270/// registry's designated default when the captured id is stale or missing.
271#[derive(Debug, Clone, PartialEq, Eq)]
272pub struct CurrentBackend {
273 /// Registry key of this backend (i.e. [`AgentBackend::id`], e.g.
274 /// `"opencode"`, `"codex"`). This is the value the scheduler uses to route
275 /// a default (`backend`-omitted) agent, and it is set from the adapter's
276 /// own `config.id` — so it is guaranteed to match a registry key, unlike
277 /// the ACP-reported `name`.
278 pub id: String,
279 /// Backend implementation name as reported by the ACP peer, e.g.
280 /// "opencode", "codex". Display/metadata only — not used for routing.
281 pub name: String,
282 /// Backend implementation version.
283 pub version: String,
284 /// Optional human-readable title.
285 pub title: Option<String>,
286}
287
288static CURRENT_BACKEND: std::sync::RwLock<Option<CurrentBackend>> =
289 std::sync::RwLock::new(None);
290
291/// Record the backend identity captured during a handshake. Called by the
292/// ACP adapter after `initialize`. Overwrites any prior value.
293///
294/// # Panics
295///
296/// Only if the internal lock is poisoned (a writer panicked while holding
297/// it), which indicates a logic bug rather than a runtime condition.
298pub fn set_current_backend(b: CurrentBackend) {
299 let mut g = CURRENT_BACKEND
300 .write()
301 .expect("CURRENT_BACKEND lock poisoned");
302 *g = Some(b);
303}
304
305/// Read the current backend identity, if a handshake has completed yet.
306///
307/// Returns `None` before any ACP connection has been established (e.g. a
308/// `luft run` using a non-ACP backend, or before the first agent task).
309pub fn current_backend() -> Option<CurrentBackend> {
310 CURRENT_BACKEND
311 .read()
312 .expect("CURRENT_BACKEND lock poisoned")
313 .clone()
314}
315
316/// Clear the recorded current backend identity. Primarily for tests, so a
317/// `current_backend`-dependent assertion does not leak into the next test.
318pub fn clear_current_backend() {
319 *CURRENT_BACKEND
320 .write()
321 .expect("CURRENT_BACKEND lock poisoned") = None;
322}
323
324#[cfg(test)]
325mod tests {
326 //! Tests for the `AgentStatus::as_str()` contract introduced by F5.
327 //!
328 //! The persisted `AgentResultCache.status` string is part of the on-disk
329 //! checkpoint contract. Before F5 it was derived from `Debug` formatting,
330 //! which silently broke when a variant was renamed (`TimedOut` → `"TimedOut"`
331 //! → `"timedout"`). The explicit `as_str()` mapping pins the strings so that
332 //! future renames cannot regress existing checkpoints.
333
334 use super::*;
335
336 #[test]
337 fn as_str_ok_returns_ok() {
338 assert_eq!(AgentStatus::Ok.as_str(), "ok");
339 }
340
341 #[test]
342 fn as_str_error_returns_error() {
343 assert_eq!(AgentStatus::Error.as_str(), "error");
344 }
345
346 #[test]
347 fn as_str_cancelled_returns_cancelled() {
348 assert_eq!(AgentStatus::Cancelled.as_str(), "cancelled");
349 }
350
351 #[test]
352 fn as_str_timed_out_returns_snake_case_timed_out() {
353 // The KEY F5 invariant: `TimedOut` Debug is "TimedOut" (lowercased
354 // "timedout"), but the persisted string MUST be "timed_out" with an
355 // underscore so it matches the surrounding snake_case contract.
356 assert_eq!(AgentStatus::TimedOut.as_str(), "timed_out");
357 }
358
359 #[test]
360 fn as_str_timed_out_differs_from_debug_lowercased() {
361 // Regression guard: the bug being fixed. If this ever flips to
362 // `format!("{:?}", status).to_lowercase()`, `TimedOut` would yield
363 // "timedout" (no underscore) and silently corrupt existing checkpoints.
364 let debug_lower = format!("{:?}", AgentStatus::TimedOut).to_lowercase();
365 assert_ne!(AgentStatus::TimedOut.as_str(), debug_lower);
366 assert_eq!(debug_lower, "timedout");
367 assert_eq!(AgentStatus::TimedOut.as_str(), "timed_out");
368 }
369
370 #[test]
371 fn as_str_values_are_unique() {
372 let variants = [
373 AgentStatus::Ok.as_str(),
374 AgentStatus::Error.as_str(),
375 AgentStatus::Cancelled.as_str(),
376 AgentStatus::TimedOut.as_str(),
377 ];
378 for i in 0..variants.len() {
379 for j in (i + 1)..variants.len() {
380 assert_ne!(
381 variants[i], variants[j],
382 "AgentStatus::as_str() must produce distinct strings for each variant \
383 (collision between {:?} and {:?})",
384 variants[i], variants[j]
385 );
386 }
387 }
388 }
389
390 #[test]
391 fn as_str_values_are_non_empty_and_ascii() {
392 for variant in [
393 AgentStatus::Ok,
394 AgentStatus::Error,
395 AgentStatus::Cancelled,
396 AgentStatus::TimedOut,
397 ] {
398 let s = variant.as_str();
399 assert!(!s.is_empty(), "as_str() must not return empty strings");
400 assert!(
401 s.is_ascii(),
402 "as_str() must return ASCII-only strings (got: {:?})",
403 s
404 );
405 }
406 }
407
408 #[test]
409 fn as_str_values_are_snake_case_or_lowercase() {
410 // Each returned string must be either pure lowercase ASCII or
411 // snake_case (lowercase ASCII letters separated by single underscores).
412 // This matches the convention used elsewhere in the codebase
413 // (CheckpointStatus via `rename_all = "lowercase"`, RunStatus, etc.).
414 for variant in [
415 AgentStatus::Ok,
416 AgentStatus::Error,
417 AgentStatus::Cancelled,
418 AgentStatus::TimedOut,
419 ] {
420 let s = variant.as_str();
421 for c in s.chars() {
422 let ok = c.is_ascii_lowercase() || c == '_' || c.is_ascii_digit();
423 assert!(
424 ok,
425 "as_str() must return snake_case / lowercase (got {:?} in {:?})",
426 c, s
427 );
428 }
429 assert!(
430 !s.contains("__"),
431 "as_str() must not produce consecutive underscores (got {:?})",
432 s
433 );
434 assert!(
435 !s.starts_with('_') && !s.ends_with('_'),
436 "as_str() must not start or end with underscore (got {:?})",
437 s
438 );
439 }
440 }
441
442 #[test]
443 fn as_str_return_type_is_static_str() {
444 // Compile-time check: the signature must return &'static str so the
445 // string outlives any AgentStatus instance and the literal lives in
446 // the binary's read-only data.
447 fn returns_static(s: AgentStatus) -> &'static str {
448 s.as_str()
449 }
450 let _: &'static str = returns_static(AgentStatus::Ok);
451 }
452
453 #[test]
454 fn as_str_matches_storage_writer_canonical_mapping() {
455 // The storage layer (`storage/writer.rs::agent_status_str`) already
456 // canonicalises AgentStatus into the snake_case strings that the
457 // on-disk SQLite tables consume. The F5 contract requires that
458 // `AgentStatus::as_str()` agrees with this canonical mapping so
459 // checkpoint persistence and storage persistence do not drift apart.
460 const STORAGE_CANONICAL: &[(&str, AgentStatus)] = &[
461 ("ok", AgentStatus::Ok),
462 ("error", AgentStatus::Error),
463 ("cancelled", AgentStatus::Cancelled),
464 ("timed_out", AgentStatus::TimedOut),
465 ];
466 for (expected, variant) in STORAGE_CANONICAL {
467 assert_eq!(
468 variant.as_str(),
469 *expected,
470 "AgentStatus::{:?}::as_str() must equal {:?} (storage canonical)",
471 variant,
472 expected
473 );
474 }
475 }
476}