diff --git a/MEMORY.md b/MEMORY.md index 6581e4c..b5753c3 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -15,6 +15,14 @@ ## 책임과 개발 범위 +2026-11-28 구현·로컬 검증: [백그라운드 Run](docs/adr/0094-background-runs.md) (`/bg GOAL`, `/runs`, `/show`, `/cancel`). +대화형 세션에서 독립 Run을 별도 스레드로 돌린다. 세션이 허용한 권한만 쓰고, 새 승인이 필요하면 멈춰 `/resume`을 안내한다. 동시 3개까지 돌린다. +Run 중 입력한 `/bg`도 바로 실행된다. Runtime·journal·모델 요청은 그대로다(모델 요청 비교 8/8 일치). +agy 실측(Flash Low, tmux): 앞 Run과 병렬 완료, 기본 모드 paused 뒤 resume, 같은 파일 충돌(`precondition_conflict` 뒤 재시도로 두 줄 모두 남음)을 확인했다. +Ctrl+C 분리는 수정본 2/2 완료, 대조 빌드 0/2였다. 원인은 agy 취소 플래그가 process 전역이었기 때문이고, 백그라운드 스레드만 thread-local로 분리해 고쳤다. +상위 Router는 사용자 합의로 보류했다. 남은 것: 백그라운드 진행 표시, in-flight agy 즉시 취소, 세션 간 목록 유지. +책임: xgen CLI(REPL/TUI, agy 연결의 취소 범위). + 2026-11-28 구현·로컬 검증: [Provider 거절 이유 표시](docs/adr/0093-provider-rejection-display.md) (A안, 화면 전용). 4xx 본문을 최대 16 KiB 읽어 type/code/message를 정리해 headless `provider:`·대화형 `Provider said:`·model check에 보인다. Key·Bearer·긴 token은 지우고 300자에서 자른다. Journal·planning context·model 요청은 그대로다(모델 요청 비교 8/8 일치). @@ -300,7 +308,7 @@ Launcher의 `latest`/`next`는 rc.8이며 실제 모델 품질 평가는 인증 - TUI 사용성(사용자 요청, 2026-11-03, 미구현): Claude Code `/model`처럼 화살표로 고르는 model 선택기. opencode는 TypeScript/Go라 그대로 못 가져온다. 같은 Rust인 OpenAI Codex CLI TUI(ratatui, Apache-2.0)가 참고·이식 후보 — 셀 단위 diff 렌더링이라 지우고 다시 그리는 깜빡임 구조 자체가 없다. 한 단계씩: 깜빡임 수정 → `/model` 선택기 → 렌더러 교체 여부는 ADR로 따로 판단. - 18초 응답(사용자 보고, 2026-11-03): 시간 전부가 한 번의 HTTP 호출 안이었다(usage elapsedMillis 18324, 출력 52 token). 같은 경로를 tmux TUI·`xgen run`으로 다시 재면 2~5초, 직접 호출 1.5~2초라 일회성 provider 지연으로 본다(원인 확정 아님). -- xgen-cli 자체 개발 순서(2026-11-19, 사용자 승인): 미완료 #144 검증·정리 후 실행 중 후속 지시 반영을 다음 큰 작업으로 둔다. 독립 Run 병렬 실행·상위 Router는 이후 후보이며 아직 구현하지 않았다. +- xgen-cli 자체 개발 순서(2026-11-19, 사용자 승인): 미완료 #144 검증·정리 후 실행 중 후속 지시 반영을 다음 큰 작업으로 둔다. 독립 Run 병렬 실행은 2026-11-28 `/bg`로 구현했다(ADR-0094). 상위 Router는 보류했다. - 실행 중 후속 지시(2026-11-28, ADR-0092, 구현·실제 모델 검증): 대화형 TUI에서 Run 중 Enter한 줄은 그 Run의 지시가 되어 다음 모델 호출 직전에 `user_instruction_added`로 journal에 남고 planning context `userInstructions{meaning,items}`로 보인다(없으면 요청 바이트 동일, 모델 요청 비교 8/8 일치). `/` 명령과 Run이 받지 못한 지시만 다음 목표 대기열로 간다. agy Flash Low 실측: 설계 2(파일 설명 범위 축소, 생성 파일 이름 변경)·보류 2(답 언어 변경, 도구 실행 중 12초 뒤 추가 요청) 모두 같은 Run에서 반영, main은 별도 Run으로 실행. 남은 후보: 독립 Run 병렬 실행·상위 Router, 승인 대기 중 지시의 즉시 반영. - #144 정리(구현·로컬 검증 완료): 최초 CI는 test의 빈 String 생성에 대한 Clippy1건에서 중단됐다. 최신 main을 병합해 수정했으며, 범위 밖 도구를 지시하는 안내와 필수 completion 검사 모순도 실제 실행에서 재현해 고쳤다. read/stat 승인·resume, 선택 write의 별도 승인, 숨긴 write 차단, HTTP 원문·요청 크기 검증을 진행한다. 독립 diff 검토 도구는 인증 오류로 이용하지 못했으며 직접 코드 검토와 회귀 검사를 수행한다. - #144 최종 로컬 검증: Rust798개(4 ignored), Python162개(9 skipped), Clippy·fmt·protocol·문서·workflow 검사 통과. 이전 rc.6의 미완료 HTTP Run을 새 바이너리로 재개해 catalog digest와 API 본문이 유지됨을 두 fixture에서 확인했다. 실제 모델 판단 품질·토큰 금액 절감은 미측정이다. 작업은 기존 `/home/son/projects/xgen-cli-wt/capability-scope`의 `codex/capability-scope`에서 진행했다. diff --git a/crates/xgen-cli/src/agy.rs b/crates/xgen-cli/src/agy.rs index ad91212..bd2d8d9 100644 --- a/crates/xgen-cli/src/agy.rs +++ b/crates/xgen-cli/src/agy.rs @@ -42,6 +42,25 @@ pub fn clear_cancellation() { CANCELLED.store(false, Ordering::SeqCst); } +thread_local! { + static DETACHED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Exempt calls made on this thread from the session-wide Ctrl+C. A background Run (ADR-0094) +/// stops through its own driver boundary instead, so cancelling the foreground Run does not +/// kill its in-flight call. +pub fn detach_from_session_cancellation() { + DETACHED.with(|detached| detached.set(true)); +} + +fn session_cancelled() -> bool { + applies_to_this_thread(CANCELLED.load(Ordering::SeqCst)) +} + +fn applies_to_this_thread(requested: bool) -> bool { + requested && !DETACHED.with(std::cell::Cell::get) +} + pub fn kill_active() { let children: Vec<_> = ACTIVE .lock() @@ -511,7 +530,7 @@ fn run( timeout: Duration, model: Option<&str>, ) -> Result, PlannerPortFailure> { - if CANCELLED.load(Ordering::SeqCst) { + if session_cancelled() { return Err(PlannerPortFailure::Unavailable); } command @@ -552,7 +571,7 @@ fn run( let (mut output, mut pending, mut errors) = (Vec::new(), Vec::new(), Vec::new()); let mut status = None; loop { - if CANCELLED.load(Ordering::SeqCst) { + if session_cancelled() { return Err(PlannerPortFailure::Unavailable); } if started.elapsed() >= timeout { @@ -713,6 +732,21 @@ mod tests { assert!(envs.iter().all(|(key, _)| *key != "XGEN_OPENAI_API_KEY")); } + #[test] + fn session_cancellation_skips_detached_background_threads() { + assert!(super::applies_to_this_thread(true)); + assert!(!super::applies_to_this_thread(false)); + let detached = std::thread::spawn(|| { + super::detach_from_session_cancellation(); + super::applies_to_this_thread(true) + }) + .join() + .unwrap(); + assert!(!detached); + // Other threads, including this one, still follow the session. + assert!(super::applies_to_this_thread(true)); + } + #[test] fn exit_classes_are_fixed_and_never_echo_agy_text() { assert_eq!( diff --git a/crates/xgen-cli/src/background.rs b/crates/xgen-cli/src/background.rs new file mode 100644 index 0000000..8ec2dc3 --- /dev/null +++ b/crates/xgen-cli/src/background.rs @@ -0,0 +1,649 @@ +//! Independent background Runs in the interactive session (ADR-0094). +//! +//! `/bg GOAL` starts a separate durable Run on its own thread while the foreground Run and the +//! input box keep working. A background Run never asks: it uses only the approvals the session +//! already granted, and stops (paused) at the first boundary that would need a new one, so the +//! user can `/resume` it in the foreground. The runtime needs nothing new: leases are per Run and +//! digest-checked writes keep two Runs from silently overwriting the same file. + +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::thread; +use std::time::{Duration, Instant}; + +use xgen_cli::{DriverProgress, DriverProgressControl, LocalCommandResult, RejectionReason}; + +use crate::repl::{InvocationGrants, ReplFailure}; + +/// Background Runs allowed to execute at once in one session. +pub(crate) const MAX_RUNNING: usize = 3; +/// Finished entries kept for `/runs` and `/show`; the oldest finished one is forgotten first. +const MAX_ENTRIES: usize = 32; +const GOAL_PREVIEW_CHARS: usize = 60; +const ANSWER_PREVIEW_CHARS: usize = 80; +const MAX_ANSWER_BYTES: usize = 64 * 1024; + +/// Starts one Run to completion on the calling thread. `started` receives the Run ID as soon as +/// the Run exists; `progress` is polled at every driver boundary. +pub(crate) type Launch = dyn Fn( + String, + InvocationGrants, + &mut dyn FnMut(&str), + &mut dyn FnMut(DriverProgress) -> DriverProgressControl, + ) -> Result + + Send + + Sync; + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Status { + Running, + Completed, + Answered, + Paused(&'static str), + Cancelled, + Rejected(&'static str), + RecoveryRequired(&'static str), + Failed(&'static str), +} + +impl Status { + fn label(&self) -> String { + match self { + Self::Running => "running".to_owned(), + Self::Completed => "completed".to_owned(), + Self::Answered => "answered".to_owned(), + Self::Paused(reason) => format!("paused ({reason})"), + Self::Cancelled => "cancelled".to_owned(), + Self::Rejected(reason) => format!("rejected ({reason})"), + Self::RecoveryRequired(reason) => format!("recovery required ({reason})"), + Self::Failed(code) => format!("failed ({code})"), + } + } +} + +struct Entry { + label: String, + goal: String, + run_id: Option, + status: Status, + answer: Option, + cancel: Arc, + started: Instant, + elapsed: Option, +} + +#[derive(Default)] +struct State { + launcher: Option>, + grants: InvocationGrants, + next: u32, + entries: VecDeque, + notices: VecDeque, + /// The terminal frontend prints notices as they arrive; otherwise the REPL prints them + /// before reading the next line. + frontend: bool, +} + +/// Session-wide table of background Runs, shared by the REPL and the terminal frontend. +#[derive(Clone, Default)] +pub(crate) struct BackgroundRuns(Arc>); + +impl BackgroundRuns { + fn state(&self) -> MutexGuard<'_, State> { + self.0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + pub(crate) fn set_launcher(&self, launcher: Option>) { + self.state().launcher = launcher; + } + + /// The approvals a background Run may use: what the session already granted. + pub(crate) fn set_grants(&self, grants: InvocationGrants) { + self.state().grants = grants; + } + + pub(crate) fn grants(&self) -> InvocationGrants { + self.state().grants + } + + pub(crate) fn attach_frontend(&self) { + self.state().frontend = true; + } + + pub(crate) fn frontend(&self) -> bool { + self.state().frontend + } + + pub(crate) fn running(&self) -> usize { + self.state() + .entries + .iter() + .filter(|entry| entry.status == Status::Running) + .count() + } + + pub(crate) fn take_notices(&self) -> Vec { + self.state().notices.drain(..).collect() + } + + /// Start `goal` as an independent Run. Returns the lines to show. + pub(crate) fn spawn(&self, goal: &str, grants: InvocationGrants) -> Vec { + let goal = goal.trim(); + if goal.is_empty() { + return vec!["error: background_goal_required (/bg GOAL)".to_owned()]; + } + if !grants.model { + return vec![ + "error: background_run_needs_model_permission (/permissions model allow)" + .to_owned(), + ]; + } + let mut state = self.state(); + let Some(launcher) = state.launcher.clone() else { + return vec!["error: background_runs_unavailable".to_owned()]; + }; + if state + .entries + .iter() + .filter(|entry| entry.status == Status::Running) + .count() + >= MAX_RUNNING + { + return vec![format!( + "error: background_run_limit ({MAX_RUNNING} running; /runs, /cancel ID)" + )]; + } + state.next += 1; + let label = format!("bg{}", state.next); + let cancel = Arc::new(AtomicBool::new(false)); + state.entries.push_back(Entry { + label: label.clone(), + goal: preview(goal, GOAL_PREVIEW_CHARS), + run_id: None, + status: Status::Running, + answer: None, + cancel: Arc::clone(&cancel), + started: Instant::now(), + elapsed: None, + }); + forget_old(&mut state.entries); + drop(state); + + let table = self.clone(); + let goal = goal.to_owned(); + let thread_label = label.clone(); + let spawned = thread::Builder::new() + .name(format!("xgen-{label}")) + .spawn(move || { + xgen_cli::agy::detach_from_session_cancellation(); + let mut started = |run_id: &str| table.record_run_id(&thread_label, run_id); + let mut progress = |_event| { + if cancel.load(Ordering::SeqCst) { + DriverProgressControl::Cancel + } else { + DriverProgressControl::Continue + } + }; + let result = launcher(goal, grants, &mut started, &mut progress); + table.finish(&thread_label, result); + }); + if spawned.is_err() { + self.finish( + &label, + Err(ReplFailure::new("background_thread_unavailable")), + ); + return Vec::new(); + } + vec![format!( + "[{label}] started in the background · /runs to list, /cancel {label} to stop" + )] + } + + fn record_run_id(&self, label: &str, run_id: &str) { + if let Some(entry) = self.state().entries.iter_mut().find(|e| e.label == label) { + entry.run_id = Some(run_id.to_owned()); + } + } + + fn finish(&self, label: &str, result: Result) { + let mut state = self.state(); + let Some(entry) = state.entries.iter_mut().find(|e| e.label == label) else { + return; + }; + entry.elapsed = Some(entry.started.elapsed()); + let (status, run_id, answer) = classify(result); + if run_id.is_some() { + entry.run_id = run_id; + } + entry.status = status; + entry.answer = answer; + let notice = finish_notice(entry); + state.notices.push_back(notice); + } + + /// Handle `/runs`, `/show ID` and `/cancel ID`; `None` when `line` is not one of them. + pub(crate) fn command(&self, line: &str) -> Option> { + let parts = line.split_ascii_whitespace().collect::>(); + match parts.as_slice() { + ["/runs"] => Some(self.list()), + ["/show", id] => Some(self.show(id)), + ["/cancel", id] => Some(self.cancel(id)), + ["/show" | "/cancel"] => Some(vec!["error: background_id_required".to_owned()]), + _ => None, + } + } + + fn list(&self) -> Vec { + let state = self.state(); + if state.entries.is_empty() { + return vec!["background runs: none (/bg GOAL starts one)".to_owned()]; + } + let mut lines = vec![format!( + "background runs: {} running of {MAX_RUNNING}", + state + .entries + .iter() + .filter(|entry| entry.status == Status::Running) + .count() + )]; + for entry in &state.entries { + let seconds = entry + .elapsed + .unwrap_or_else(|| entry.started.elapsed()) + .as_secs(); + lines.push(format!( + " {} {} {}s {} · {}", + entry.label, + entry.status.label(), + seconds, + entry.run_id.as_deref().unwrap_or("-"), + entry.goal + )); + } + lines + } + + fn show(&self, id: &str) -> Vec { + let state = self.state(); + let Some(entry) = find(&state.entries, id) else { + return vec!["error: background_run_unknown (/runs)".to_owned()]; + }; + let mut lines = vec![format!( + "[{}] {} {} · {}", + entry.label, + entry.status.label(), + entry.run_id.as_deref().unwrap_or("-"), + entry.goal + )]; + match (&entry.status, &entry.answer) { + (_, Some(answer)) => lines.extend(answer.lines().map(terminal_line)), + (Status::Running, None) => lines.push("still running".to_owned()), + (_, None) => { + if let Some(run_id) = &entry.run_id { + lines.push(format!( + "no answer was saved; continue with /resume {run_id}" + )); + } else { + lines.push("no answer was saved".to_owned()); + } + } + } + lines + } + + fn cancel(&self, id: &str) -> Vec { + let state = self.state(); + match find(&state.entries, id) { + Some(entry) if entry.status == Status::Running => { + entry.cancel.store(true, Ordering::SeqCst); + vec![format!( + "[{}] cancelling at the next safe boundary", + entry.label + )] + } + Some(entry) => vec![format!( + "[{}] is not running: {}", + entry.label, + entry.status.label() + )], + None => vec!["error: background_run_unknown (/runs)".to_owned()], + } + } + + /// Ask every running background Run to stop at its next boundary. + pub(crate) fn cancel_all(&self) { + for entry in &self.state().entries { + if entry.status == Status::Running { + entry.cancel.store(true, Ordering::SeqCst); + } + } + } + + /// Wait until no background Run is running, or `limit` passes. + pub(crate) fn wait_idle(&self, limit: Duration) -> bool { + let deadline = Instant::now() + limit; + while self.running() > 0 { + if Instant::now() >= deadline { + return false; + } + thread::sleep(Duration::from_millis(50)); + } + true + } +} + +/// Match a label (`bg2`) or the durable Run ID of an entry. +fn find<'a>(entries: &'a VecDeque, id: &str) -> Option<&'a Entry> { + entries + .iter() + .find(|entry| entry.label == id || entry.run_id.as_deref() == Some(id)) +} + +/// Keep at most `MAX_ENTRIES`, dropping the oldest finished ones; running entries stay. +fn forget_old(entries: &mut VecDeque) { + while entries.len() > MAX_ENTRIES { + let Some(index) = entries + .iter() + .position(|entry| entry.status != Status::Running) + else { + return; + }; + entries.remove(index); + } +} + +fn classify( + result: Result, +) -> (Status, Option, Option) { + match result { + Ok(LocalCommandResult::Completed { run_id, summary }) => { + (Status::Completed, Some(run_id), Some(bounded(summary))) + } + Ok(LocalCommandResult::Responded { run_id, summary }) => { + (Status::Answered, Some(run_id), Some(bounded(summary))) + } + Ok(LocalCommandResult::Paused { run_id, reason }) => { + let status = if reason == xgen_cli::PauseReason::UserCancelled { + Status::Cancelled + } else { + Status::Paused(reason.code()) + }; + (status, run_id, None) + } + Ok(LocalCommandResult::Rejected { + run_id, + reason, + provider, + }) => { + let answer = provider.map(|rejection| format!("Provider said: {rejection}")); + ( + Status::Rejected(rejection_code(reason)), + Some(run_id), + answer, + ) + } + Ok(LocalCommandResult::RecoveryRequired { run_id, reason }) => { + (Status::RecoveryRequired(reason.code()), Some(run_id), None) + } + Err(failure) => (Status::Failed(failure.code()), None, None), + } +} + +const fn rejection_code(reason: RejectionReason) -> &'static str { + reason.code() +} + +fn finish_notice(entry: &Entry) -> String { + let run = entry.run_id.as_deref().unwrap_or("-"); + let label = &entry.label; + match &entry.status { + Status::Completed | Status::Answered => { + let first = entry + .answer + .as_deref() + .and_then(|answer| answer.lines().find(|line| !line.trim().is_empty())) + .map(|line| preview(line, ANSWER_PREVIEW_CHARS)) + .unwrap_or_default(); + format!( + "[{label}] {} {run}: {first} · /show {label}", + entry.status.label() + ) + } + Status::Paused(_) | Status::RecoveryRequired(_) => { + format!("[{label}] {} {run} · /resume {run}", entry.status.label()) + } + Status::Rejected(_) => format!("[{label}] {} {run} · /show {label}", entry.status.label()), + Status::Cancelled | Status::Failed(_) | Status::Running => { + format!("[{label}] {} {run}", entry.status.label()) + } + } +} + +fn bounded(text: String) -> String { + if text.len() <= MAX_ANSWER_BYTES { + return text; + } + let mut end = MAX_ANSWER_BYTES; + while !text.is_char_boundary(end) { + end -= 1; + } + format!( + "{}\n... (truncated; /resume shows the full Run)", + &text[..end] + ) +} + +/// A model-written line made safe to print: control characters become spaces. +fn terminal_line(line: &str) -> String { + line.chars() + .map(|character| { + if character.is_control() { + ' ' + } else { + character + } + }) + .collect() +} + +/// One terminal-safe line: control characters become spaces and long text is cut. +fn preview(text: &str, limit: usize) -> String { + let flat = text + .chars() + .map(|character| { + if character.is_control() { + ' ' + } else { + character + } + }) + .collect::(); + let flat = flat.split_whitespace().collect::>().join(" "); + if flat.chars().count() <= limit { + flat + } else { + format!("{}...", flat.chars().take(limit).collect::()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::mpsc; + + fn grants() -> InvocationGrants { + InvocationGrants { + model: true, + ..InvocationGrants::default() + } + } + + /// Each launched goal blocks until the test releases it with the result to return. + fn scripted() -> ( + BackgroundRuns, + mpsc::Receiver<(String, mpsc::Sender)>, + ) { + let (calls, received) = mpsc::channel(); + let calls = Mutex::new(calls); + let runs = BackgroundRuns::default(); + let launch: Arc = Arc::new(move |goal, _grants, started, progress| { + let run_id = format!("run-{}", goal.replace(' ', "-")); + started(&run_id); + let (reply, result) = mpsc::channel(); + calls.lock().unwrap().send((goal, reply)).unwrap(); + loop { + if let Ok(result) = result.try_recv() { + return Ok(result); + } + if progress(DriverProgress::ModelCallStarting) == DriverProgressControl::Cancel { + return Ok(LocalCommandResult::Paused { + run_id: Some(run_id), + reason: xgen_cli::PauseReason::UserCancelled, + }); + } + thread::sleep(Duration::from_millis(5)); + } + }); + runs.set_launcher(Some(launch)); + (runs, received) + } + + fn wait_for_notice(runs: &BackgroundRuns) -> Vec { + for _ in 0..2000 { + let notices = runs.take_notices(); + if !notices.is_empty() { + return notices; + } + thread::sleep(Duration::from_millis(5)); + } + panic!("no notice arrived"); + } + + #[test] + fn runs_proceed_independently_and_report_when_they_finish() { + let (runs, calls) = scripted(); + assert!(runs.spawn("first goal", grants())[0].starts_with("[bg1] started")); + assert!(runs.spawn("second goal", grants())[0].starts_with("[bg2] started")); + let (first, first_reply) = calls.recv().unwrap(); + let (second, second_reply) = calls.recv().unwrap(); + let mut goals = [first.clone(), second.clone()]; + goals.sort(); + assert_eq!(goals, ["first goal", "second goal"]); + assert_eq!(runs.running(), 2); + + // The second finishes first; the first is unaffected. + let (reply, other) = if second == "second goal" { + (second_reply, first_reply) + } else { + (first_reply, second_reply) + }; + reply + .send(LocalCommandResult::Responded { + run_id: "run-second-goal".to_owned(), + summary: "\nsecond answer line\nmore".to_owned(), + }) + .unwrap(); + let notices = wait_for_notice(&runs); + assert_eq!( + notices, + ["[bg2] answered run-second-goal: second answer line · /show bg2"] + ); + assert_eq!(runs.running(), 1); + assert_eq!( + runs.command("/show bg2").unwrap(), + [ + "[bg2] answered run-second-goal · second goal", + "", + "second answer line", + "more" + ] + ); + assert_eq!( + runs.command("/show run-second-goal").unwrap()[0], + "[bg2] answered run-second-goal · second goal" + ); + + other + .send(LocalCommandResult::Paused { + run_id: Some("run-first-goal".to_owned()), + reason: xgen_cli::PauseReason::WriteApprovalRequired, + }) + .unwrap(); + let notices = wait_for_notice(&runs); + assert_eq!( + notices, + ["[bg1] paused (write_approval_required) run-first-goal · /resume run-first-goal"] + ); + let list = runs.command("/runs").unwrap(); + assert_eq!(list[0], "background runs: 0 running of 3"); + assert!(list[1].starts_with(" bg1 paused (write_approval_required) ")); + assert!(list[2].starts_with(" bg2 answered ")); + } + + #[test] + fn cancel_stops_only_the_named_run_and_the_limit_holds() { + let (runs, calls) = scripted(); + for goal in ["a", "b", "c"] { + runs.spawn(goal, grants()); + } + let replies = (0..3).map(|_| calls.recv().unwrap()).collect::>(); + assert_eq!( + runs.spawn("d", grants()), + ["error: background_run_limit (3 running; /runs, /cancel ID)"] + ); + assert_eq!( + runs.command("/cancel bg2").unwrap(), + ["[bg2] cancelling at the next safe boundary"] + ); + assert_eq!(wait_for_notice(&runs), ["[bg2] cancelled run-b"]); + assert_eq!(runs.running(), 2); + assert_eq!( + runs.command("/cancel bg2").unwrap(), + ["[bg2] is not running: cancelled"] + ); + assert!(runs.spawn("d", grants())[0].starts_with("[bg4] started")); + runs.cancel_all(); + assert!(runs.wait_idle(Duration::from_secs(5))); + drop(replies); + } + + #[test] + fn refusals_need_a_goal_model_permission_and_a_launcher() { + let runs = BackgroundRuns::default(); + assert_eq!( + runs.spawn("goal", grants()), + ["error: background_runs_unavailable"] + ); + assert_eq!( + runs.spawn("goal", InvocationGrants::default()), + ["error: background_run_needs_model_permission (/permissions model allow)"] + ); + assert_eq!( + runs.spawn(" ", grants()), + ["error: background_goal_required (/bg GOAL)"] + ); + assert_eq!( + runs.command("/runs").unwrap(), + ["background runs: none (/bg GOAL starts one)"] + ); + assert_eq!( + runs.command("/show bg9").unwrap(), + ["error: background_run_unknown (/runs)"] + ); + assert!(runs.command("/status").is_none()); + } + + #[test] + fn previews_are_single_terminal_lines() { + assert_eq!(preview("a\u{1b}[31mb\nc\td", 80), "a [31mb c d"); + assert_eq!( + preview(&"x".repeat(90), 10), + format!("{}...", "x".repeat(10)) + ); + let long = "가".repeat(MAX_ANSWER_BYTES); + assert!(bounded(long).ends_with("(truncated; /resume shows the full Run)")); + } +} diff --git a/crates/xgen-cli/src/main.rs b/crates/xgen-cli/src/main.rs index 6c68644..671cba8 100644 --- a/crates/xgen-cli/src/main.rs +++ b/crates/xgen-cli/src/main.rs @@ -25,6 +25,7 @@ use xgen_provider_openai::{ }; use zeroize::Zeroizing; +mod background; mod repl; mod tui; mod tui_results; @@ -662,6 +663,86 @@ impl InteractiveHost { .clone() .ok_or_else(|| repl::ReplFailure::new(PublicRunError::Internal.code())) } + + fn launch_snapshot(&mut self) -> Result { + Ok(InteractiveLaunch { + workspace: self.workspace.clone(), + process_session: self.process_session()?, + environment_note: self.environment_note.clone(), + instructions: self.instructions.clone(), + max_model_turns: self.max_model_turns, + }) + } +} + +/// What starting an interactive Run needs, detached from the session so a background thread can +/// start one too (ADR-0094). +#[derive(Clone)] +struct InteractiveLaunch { + workspace: PathBuf, + process_session: LocalProcessSession, + environment_note: Option, + instructions: Option, + max_model_turns: u32, +} + +fn start_interactive_run( + launch: &InteractiveLaunch, + goal: String, + grants: repl::InvocationGrants, + follow_ups: Option, + started: &mut dyn FnMut(&str), + progress: &mut dyn FnMut(DriverProgress) -> DriverProgressControl, + activity: &mut dyn FnMut(xgen_cli::StepActivity), +) -> Result { + let model = resolve_model(None, None, None, None, false, RequestOptionArgs::default()) + .map_err(|error| repl::ReplFailure::new(error.code()))?; + // The short environment note goes first so a long instruction block is what gets cut. + let parts = [&launch.environment_note, &launch.instructions] + .into_iter() + .flatten() + .map(String::as_str) + .collect::>(); + let goal = xgen_cli::append_within(goal, &parts, xgen_cli::MAX_GOAL_BYTES); + let started_run = RefCell::new(None); + let reported = Cell::new(0); + run_interactive_with_process_session_progress( + LocalRunRequest { + goal, + workspace: launch.workspace.clone(), + base_url: model.base_url, + planner_id: "xgeny.cli.openai".to_owned(), + model: model.model, + tokenizer: model.tokenizer, + credential: model.credential, + inference_limits: model.inference_limits, + request_options: model.request_options, + allow_files: Vec::new(), + allow_dirs: vec![".".to_owned()], + allow_executables: Vec::new(), + allow_remote_model_egress: grants.model, + allow_read: grants.read, + bearer_env_for: std::collections::BTreeMap::new(), + allow_write: grants.write, + allow_execute: grants.execute, + max_ticks: repl_max_ticks(launch.max_model_turns), + max_model_turns: Some(launch.max_model_turns), + final_response_schema: None, + completion_checks: None, + // The interactive driver admits this contract regardless; said + // here so the request describes the Run it actually starts. + conversation_responses: true, + capabilities: Vec::new(), + follow_ups, + }, + &launch.process_session, + |run_id| { + started_run.replace(Some(run_id.to_owned())); + started(run_id); + }, + with_activity(&started_run, &reported, progress, activity), + ) + .map_err(repl::ReplFailure::from_run_error) } /// Forward what each finished Step did once its effect commits, read back from the verified @@ -747,57 +828,42 @@ impl repl::ReplHost for InteractiveHost { progress: &mut dyn FnMut(DriverProgress) -> DriverProgressControl, activity: &mut dyn FnMut(xgen_cli::StepActivity), ) -> Result { - let model = resolve_model(None, None, None, None, false, RequestOptionArgs::default()) - .map_err(|error| repl::ReplFailure::new(error.code()))?; - let process_session = self.process_session()?; - // The short environment note goes first so a long instruction block is what gets cut. - let parts = [&self.environment_note, &self.instructions] - .into_iter() - .flatten() - .map(String::as_str) - .collect::>(); - let goal = xgen_cli::append_within(goal, &parts, xgen_cli::MAX_GOAL_BYTES); - let started_run = RefCell::new(None); - let reported = Cell::new(0); - run_interactive_with_process_session_progress( - LocalRunRequest { - goal, - workspace: self.workspace.clone(), - base_url: model.base_url, - planner_id: "xgeny.cli.openai".to_owned(), - model: model.model, - tokenizer: model.tokenizer, - credential: model.credential, - inference_limits: model.inference_limits, - request_options: model.request_options, - allow_files: Vec::new(), - allow_dirs: vec![".".to_owned()], - allow_executables: Vec::new(), - allow_remote_model_egress: grants.model, - allow_read: grants.read, - bearer_env_for: std::collections::BTreeMap::new(), - allow_write: grants.write, - allow_execute: grants.execute, - max_ticks: repl_max_ticks(self.max_model_turns), - max_model_turns: Some(self.max_model_turns), - final_response_schema: None, - completion_checks: None, - // The interactive driver admits this contract regardless; said - // here so the request describes the Run it actually starts. - conversation_responses: true, - capabilities: Vec::new(), - follow_ups: self.follow_ups.clone(), - }, - &process_session, - |run_id| { - started_run.replace(Some(run_id.to_owned())); - if self.detailed_progress { + let launch = self.launch_snapshot()?; + let detailed = self.detailed_progress; + start_interactive_run( + &launch, + goal, + grants, + self.follow_ups.clone(), + &mut |run_id| { + if detailed { eprintln!("XGEN_STARTED run_id={run_id}"); } }, - with_activity(&started_run, &reported, progress, activity), + progress, + activity, ) - .map_err(repl::ReplFailure::from_run_error) + } + + fn background_launcher(&mut self) -> Option> { + // A background Run never writes to stderr: the terminal frontend owns the screen. + let launch = self.launch_snapshot().ok()?; + Some(std::sync::Arc::new( + move |goal, + grants, + started: &mut dyn FnMut(&str), + progress: &mut dyn FnMut(DriverProgress) -> DriverProgressControl| { + start_interactive_run( + &launch, + goal, + grants, + None, + started, + progress, + &mut |_activity| {}, + ) + }, + )) } fn resume( @@ -902,6 +968,7 @@ fn interactive_command(debug: bool, max_model_turns: u32, trust: bool) -> ExitCo return ExitCode::from(PublicRunError::Configuration.exit_code()); }; let follow_ups = xgen_cli::FollowUpInbox::new(); + let background = background::BackgroundRuns::default(); if terminal { host.follow_ups = Some(follow_ups.clone()); } @@ -914,6 +981,7 @@ fn interactive_command(debug: bool, max_model_turns: u32, trust: bool) -> ExitCo footer, !debug, follow_ups, + background.clone(), ) else { eprintln!("XGEN_ERROR code={}", PublicRunError::Internal.code()); return ExitCode::from(PublicRunError::Internal.exit_code()); @@ -925,6 +993,7 @@ fn interactive_command(debug: bool, max_model_turns: u32, trust: bool) -> ExitCo &cancellation, !debug, trust, + &background, ) } else { let mut input = repl::InterruptibleInput::stdin(cancellation.clone()); @@ -936,6 +1005,7 @@ fn interactive_command(debug: bool, max_model_turns: u32, trust: bool) -> ExitCo &cancellation, false, trust, + &background, ) }; match result { diff --git a/crates/xgen-cli/src/repl.rs b/crates/xgen-cli/src/repl.rs index 0a832bb..4edb810 100644 --- a/crates/xgen-cli/src/repl.rs +++ b/crates/xgen-cli/src/repl.rs @@ -8,6 +8,7 @@ use std::sync::{Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; +use crate::background::{BackgroundRuns, Launch}; use xgen_cli::{ CommittedChange, DriverProgress, DriverProgressControl, LocalCommandResult, PauseReason, RejectionReason, StepActivity, edit_lines, provider_rejection_hint, @@ -16,6 +17,8 @@ use xgen_runtime::AgentLoopQuiescence; pub(crate) const MAX_REPL_LINE_BYTES: usize = 16 * 1024; const MAX_REPL_GOAL_BYTES: usize = 16 * 1024; +/// How long leaving the session waits for background Runs to reach a safe boundary. +const BACKGROUND_EXIT_WAIT: Duration = Duration::from_secs(10); /// Presentation boundaries supplied by the REPL, never inferred from model text. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -227,7 +230,7 @@ impl ReplFailure { } } - const fn code(&self) -> &'static str { + pub(crate) const fn code(&self) -> &'static str { self.code } @@ -281,6 +284,11 @@ pub(crate) trait ReplHost { progress: &mut dyn FnMut(DriverProgress) -> DriverProgressControl, activity: &mut dyn FnMut(StepActivity), ) -> Result; + + /// Starts independent Runs on other threads for `/bg` (ADR-0094); `None` disables it. + fn background_launcher(&mut self) -> Option> { + None + } } #[derive(Clone, Default)] @@ -455,6 +463,10 @@ enum ReplCommand { Permissions(Option<(PermissionKind, PermissionMode)>), AllowExecutable(String), Resume(Option), + /// `/bg GOAL`: start an independent background Run (ADR-0094). + Background(String), + /// `/runs`, `/show ID`, `/cancel ID` over background Runs. + BackgroundQuery(String), Clear, Help, Exit, @@ -506,7 +518,15 @@ pub(crate) fn run( host: &mut H, cancellation: &Cancellation, ) -> io::Result<()> { - run_with_display(reader, output, host, cancellation, false, false) + run_with_display( + reader, + output, + host, + cancellation, + false, + false, + &BackgroundRuns::default(), + ) } #[allow(clippy::too_many_lines)] @@ -517,6 +537,7 @@ pub(crate) fn run_with_display( cancellation: &Cancellation, interactive_display: bool, trust: bool, + background: &BackgroundRuns, ) -> io::Result<()> { writeln!(output, "XGEN Developer Preview")?; writeln!( @@ -553,8 +574,16 @@ pub(crate) fn run_with_display( let mut session_context = SessionContext::default(); let mut outcome = SessionOutcome::Idle; let mut first_input_line = true; + background.set_launcher(host.background_launcher()); loop { + // A background Run may use only what the session has granted so far. + background.set_grants(permissions.grants()); + if !background.frontend() { + for notice in background.take_notices() { + writeln!(output, "{notice}")?; + } + } let entry = match read_entry(reader, output, &mut first_input_line) { Ok(entry) => entry, Err(InputFailure::TooLarge) => { @@ -576,9 +605,53 @@ pub(crate) fn run_with_display( writeln!(output, "^C")?; } ReplEntry::EndOfInput | ReplEntry::Command(ReplCommand::Exit) => { + let running = background.running(); + if running > 0 { + writeln!( + output, + "stopping {running} background Run(s); their durable state stays resumable" + )?; + background.cancel_all(); + background.wait_idle(BACKGROUND_EXIT_WAIT); + if !background.frontend() { + for notice in background.take_notices() { + writeln!(output, "{notice}")?; + } + } + } writeln!(output, "bye")?; return Ok(()); } + ReplEntry::Command(ReplCommand::Background(goal)) => { + let mut grants = permissions.grants(); + match permissions.model { + PermissionMode::Allow => {} + PermissionMode::Deny => { + writeln!(output, "paused: model_egress_denied")?; + continue; + } + PermissionMode::Ask => { + if goal.is_empty() { + writeln!(output, "error: background_goal_required (/bg GOAL)")?; + continue; + } + let answer = prompt_approval(reader, output, PermissionKind::Model)?; + if !answer.record(output, &mut permissions, PermissionKind::Model)? { + writeln!(output, "cancelled before model egress")?; + continue; + } + grants = grants.with(PermissionKind::Model); + } + } + for line in background.spawn(&goal, grants) { + writeln!(output, "{line}")?; + } + } + ReplEntry::Command(ReplCommand::BackgroundQuery(line)) => { + for line in background.command(&line).unwrap_or_default() { + writeln!(output, "{line}")?; + } + } ReplEntry::Command(ReplCommand::Help) => print_help(output)?, ReplEntry::Command(ReplCommand::Model(name)) => match name { Some(name) => match host.use_model(&name) { @@ -617,6 +690,7 @@ pub(crate) fn run_with_display( "catalogued_executables: {}", host.executable_ids().len() )?; + writeln!(output, "background_runs: {} running", background.running())?; print_permissions(output, permissions)?; } ReplEntry::Command(ReplCommand::Usage(requested)) => { @@ -659,7 +733,10 @@ pub(crate) fn run_with_display( continue; } match host.allow_executable(&specification) { - Ok(()) => print_executables(output, host.executable_ids())?, + Ok(()) => { + background.set_launcher(host.background_launcher()); + print_executables(output, host.executable_ids())?; + } Err(failure) => print_failure(output, &failure)?, } } @@ -1807,6 +1884,14 @@ fn parse_command(value: &str) -> Result { .ok_or(InputFailure::InvalidCommand)?; Ok(ReplCommand::AllowExecutable(specification.to_owned())) } + ["/bg", ..] => Ok(ReplCommand::Background( + value + .strip_prefix("/bg") + .map(str::trim) + .unwrap_or_default() + .to_owned(), + )), + ["/runs"] | ["/show" | "/cancel", _] => Ok(ReplCommand::BackgroundQuery(value.to_owned())), ["/resume"] => Ok(ReplCommand::Resume(None)), ["/resume", run_id] => Ok(ReplCommand::Resume(Some((*run_id).to_owned()))), ["/clear"] => Ok(ReplCommand::Clear), @@ -1862,6 +1947,14 @@ fn print_help(output: &mut impl Write) -> io::Result<()> { output, "/resume [RUN_ID] continue or replay a durable Run" )?; + writeln!( + output, + "/bg GOAL start an independent Run in the background" + )?; + writeln!( + output, + "/runs · /show ID · /cancel ID list, read or stop background Runs" + )?; writeln!( output, "/clear detach without deleting durable state" @@ -2258,6 +2351,53 @@ mod tests { } } + #[test] + fn background_run_proceeds_beside_foreground_goals_and_stops_on_exit() { + let (seen, goals) = mpsc::channel(); + let seen = Mutex::new(seen); + let mut host = FakeHost::new([LocalCommandResult::Responded { + run_id: "run-foreground".to_owned(), + summary: "foreground answer".to_owned(), + }]); + host.launcher = Some(Arc::new(move |goal, grants, started, progress| { + seen.lock().unwrap().send((goal, grants)).unwrap(); + started("run-slow"); + // Runs until the session asks it to stop at a boundary. + while progress(DriverProgress::ModelCallStarting) == DriverProgressControl::Continue { + thread::sleep(Duration::from_millis(5)); + } + Ok(LocalCommandResult::Paused { + run_id: Some("run-slow".to_owned()), + reason: PauseReason::UserCancelled, + }) + })); + let mut input = io::Cursor::new( + b"/bg\n/permissions model allow\n/bg slow job\n/runs\nforeground goal\n/status\n/exit\n" + .as_slice(), + ); + let mut output = Vec::new(); + run(&mut input, &mut output, &mut host, &Cancellation::default()).unwrap(); + let output = String::from_utf8(output).unwrap(); + let (goal, grants) = goals.recv().unwrap(); + assert_eq!(goal, "slow job"); + assert!(grants.model && !grants.write); + assert!( + output.contains("error: background_goal_required (/bg GOAL)"), + "{output}" + ); + assert!( + output.contains("[bg1] started in the background"), + "{output}" + ); + assert!(output.contains(" bg1 running "), "{output}"); + assert!(output.contains("foreground answer"), "{output}"); + assert!(output.contains("background_runs: 1 running"), "{output}"); + assert!(output.contains("stopping 1 background Run(s)"), "{output}"); + assert!(output.contains("[bg1] cancelled run-slow"), "{output}"); + assert_eq!(host.starts.len(), 1); + assert_eq!(host.starts[0].0, "foreground goal"); + } + struct FakeHost { results: VecDeque>, starts: Vec<(String, InvocationGrants)>, @@ -2265,6 +2405,7 @@ mod tests { tools: Vec, model: ModelView, changes: Vec, + launcher: Option>, } impl FakeHost { @@ -2280,6 +2421,7 @@ mod tests { authentication: "external_or_none", }, changes: Vec::new(), + launcher: None, } } @@ -2304,6 +2446,10 @@ mod tests { &self.tools } + fn background_launcher(&mut self) -> Option> { + self.launcher.clone() + } + fn changes(&mut self, _run_id: &str) -> Result, ReplFailure> { Ok(self.changes.clone()) } @@ -2548,6 +2694,7 @@ mod tests { &Cancellation::default(), true, false, + &BackgroundRuns::default(), ) .unwrap(); let output = String::from_utf8(output).unwrap(); @@ -2851,6 +2998,7 @@ mod tests { &Cancellation::default(), false, true, + &BackgroundRuns::default(), ) .unwrap(); assert!(host.starts.iter().all(|(_, grants)| *grants @@ -3049,6 +3197,7 @@ mod tests { &Cancellation::default(), true, false, + &BackgroundRuns::default(), ) .unwrap(); diff --git a/crates/xgen-cli/src/tui.rs b/crates/xgen-cli/src/tui.rs index 4dbf844..c4bb581 100644 --- a/crates/xgen-cli/src/tui.rs +++ b/crates/xgen-cli/src/tui.rs @@ -25,6 +25,7 @@ use crossterm::event::{ use crossterm::{cursor, queue, terminal}; use unicode_width::UnicodeWidthChar as _; +use crate::background::BackgroundRuns; use crate::repl::{ Cancellation, InputMessage, InterruptibleInput, MAX_REPL_LINE_BYTES, ReplOutput, ResultKind, }; @@ -122,7 +123,9 @@ pub(crate) fn start( footer: String, folding: bool, follow_ups: FollowUpInbox, + background: BackgroundRuns, ) -> io::Result<(InterruptibleInput, TuiOutput, TuiGuard)> { + background.attach_frontend(); terminal::enable_raw_mode()?; let mut stdout = io::stdout(); if let Err(error) = queue!(stdout, EnableBracketedPaste).and_then(|()| stdout.flush()) { @@ -139,7 +142,8 @@ pub(crate) fn start( let (lines, input) = mpsc::sync_channel(1); let frontend_cancellation = cancellation.clone(); let thread = thread::spawn(move || { - let mut frontend = Frontend::new(frontend_cancellation, history, footer, lines, follow_ups); + let mut frontend = Frontend::new(frontend_cancellation, history, footer, lines, follow_ups) + .with_background(background); frontend.run(&receiver); }); let request_sender = sender.clone(); @@ -175,6 +179,8 @@ struct Frontend { queue: VecDeque, /// Instructions typed while a Run is in flight, taken at its next model call (ADR-0092). follow_ups: FollowUpInbox, + /// Independent Runs started with `/bg`; their commands work while a Run is in flight. + background: BackgroundRuns, /// The remaining lines of a multi-line submission, answered at `...>` prompts. continuation: VecDeque, cancelling: bool, @@ -258,6 +264,7 @@ impl Frontend { requested: false, queue: VecDeque::new(), follow_ups, + background: BackgroundRuns::default(), continuation: VecDeque::new(), cancelling: false, started: Instant::now(), @@ -273,6 +280,11 @@ impl Frontend { } } + fn with_background(mut self, background: BackgroundRuns) -> Self { + self.background = background; + self + } + fn run(&mut self, receiver: &Receiver) { let mut finished = Vec::new(); let mut last_draw = Instant::now(); @@ -315,6 +327,9 @@ impl Frontend { .into_bytes(), ); } + for notice in self.background.take_notices() { + finished.push(format!("\x1b[2m{notice}\x1b[0m").into_bytes()); + } dirty |= !finished.is_empty(); let event = event::poll(Duration::from_millis(25)) .and_then(|ready| ready.then(event::read).transpose()); @@ -445,6 +460,11 @@ impl Frontend { let text = self.editor.take(); if self.requested { self.submit(&text, finished); + } else if let Some(lines) = self.background_command(&text) { + // Background Runs are independent of the one in flight: act now. + self.editor.remember(&text); + finished.push(echo_line(GOAL_PROMPT, &text)); + finished.extend(lines.into_iter().map(String::into_bytes)); } else if text.trim().starts_with('/') { self.queue.push_back(text); } else if !text.trim().is_empty() { @@ -478,6 +498,17 @@ impl Frontend { true } + /// `/bg`, `/runs`, `/show` and `/cancel` typed while a Run is in flight. A background Run + /// started now cannot ask for model consent, so it needs the session's standing permission. + fn background_command(&self, text: &str) -> Option> { + let text = text.trim(); + if text == "/bg" || text.starts_with("/bg ") { + let goal = text.strip_prefix("/bg").unwrap_or_default(); + return Some(self.background.spawn(goal, self.background.grants())); + } + self.background.command(text) + } + fn interrupt(&mut self) { if !self.requested { // A Run is in flight: ask the driver to stop at its next boundary. diff --git a/docs/adr/0094-background-runs.md b/docs/adr/0094-background-runs.md new file mode 100644 index 0000000..dc73301 --- /dev/null +++ b/docs/adr/0094-background-runs.md @@ -0,0 +1,62 @@ +# ADR-0094: 대화형 세션의 백그라운드 Run + +- 날짜: 2026-11-28 +- 상태: 채택, 구현·로컬 검증 완료 +- 범위: 대화형 세션(REPL/TUI)의 `/bg`, `/runs`, `/show`, `/cancel` 명령과 agy 취소 범위. + journal, Run 상태, planning context, 모델 요청, headless `xgen run`/`resume`은 바꾸지 않는다. + +## 근거 + +대화형 세션은 Run 하나를 REPL 스레드에서 끝까지 동기로 실행했다. 하나가 도는 동안 다른 독립 작업은 +Run이 끝나기를 기다리거나, 터미널을 하나 더 열어야 했다. Run 중 입력은 [ADR-0092](0092-follow-up-instructions-during-a-run.md) +이후 그 Run의 지시가 된다. + +Runtime은 이미 병렬을 막지 않는다. +- Lease는 workspace가 아니라 Run마다 잡힌다(`runs//run.lock`). +- 파일 쓰기는 `expectedDigest`로 미리 확인한다. 그래서 두 Run이 같은 파일을 고쳐도 내용이 섞이지 않고 뒤에 쓰는 쪽이 실패한다. + +## 결정 + +1. `/bg GOAL`은 독립 Run을 별도 스레드에서 시작한다. + - 지침 파일과 환경 안내는 일반 goal과 같이 붙인다. 이전 대화 맥락은 넘기지 않는다. + - Run 중 입력창의 후속 지시(ADR-0092)는 앞 Run에만 간다. +2. 백그라운드 Run은 묻지 않는다. + - 세션이 이미 허용한 권한만 쓴다. 새 승인이 필요하면 `Paused`로 멈추고 알림으로 `/resume RUN_ID`를 안내한다. + - 이어 가는 일은 앞(foreground)에서 기존 승인 흐름으로 한다. + - 입력창이 비어 있을 때의 `/bg`만 모델 전송 동의를 그 자리에서 묻는다. + - Run 중 입력한 `/bg`는 대기열에 들어가지 않고 바로 실행된다. 이때 질문할 수 없으므로 모델 권한이 `allow`여야 한다. +3. 끝나면 결과 종류와 Run ID, 답 첫 줄을 한 줄로 알린다. + - TUI는 매 tick 알림을 입력창 위에 찍는다. TUI가 없는 REPL은 다음 입력 전에 찍는다. + - `/show ID`는 세션 메모리에 저장한 답(최대 64 KiB)을 보여 준다. `/runs`는 목록을 보여 준다. + - 목록은 32개까지 두고, 끝난 것 중 가장 오래된 것부터 버린다. +4. 동시에 3개까지 돈다. + - `/cancel ID`는 그 Run의 driver 경계에서 멈춘다. + - Ctrl+C는 앞 Run만 취소한다. agy의 process 전역 취소 플래그는 백그라운드 스레드에 적용하지 않는다(thread-local 분리). +5. 세션을 끝내면 도는 백그라운드 Run을 모두 취소하고 최대 10초 기다린 뒤 나간다. 각 Run의 durable 상태는 남는다. +6. 입력마다 모델이 "후속 지시인지 새 Run인지"를 고르는 상위 Router는 만들지 않는다. + - 매 입력에 모델 호출이 하나 늘고, 잘못 분류하면 되돌리기 어렵다. + - 사용자가 `/bg`로 명시한다. 실제 사용에서 잘못 넣는 경우가 반복되면 다시 검토한다. + +## 검증 + +- 단위 테스트 + - 두 Run이 서로 독립으로 끝나는 순서와 알림, `/show`·`/runs`, `/cancel` 대상 한정, 상한 3, 거절 메시지, + 터미널 제어 문자 제거. + - REPL: `/bg`, `/runs`, 앞 goal, `/status`, `/exit` 시 취소와 알림. + - agy 취소의 스레드 분리. +- tmux 대화형, agy `gemini-3.8-flash-low` + - trust: 앞 Run(파일 2개 설명)이 도는 중에 `/bg`(CSV 행 수)를 입력했다. 백그라운드가 먼저 끝나 `2`를 답했고, 앞 Run도 끝났다. + - 기본 모드: `/bg` 동의 뒤 읽기 승인 단계에서 `paused (read_approval_required)` 알림이 떴다. `/resume`으로 앞에서 승인하자 답이 나왔다. + - 같은 파일 충돌: 앞 Run과 백그라운드 Run이 `notes.md`에 서로 다른 줄을 덧붙였다. + - 백그라운드의 첫 쓰기가 journal에 `effect_failed{precondition_conflict}`로 남았다. + - 이후 다시 읽어 두 줄이 모두 남았다. + - Ctrl+C 분리: 앞 Run을 4초 뒤 취소했다. + - 수정본에서는 백그라운드 Run이 2/2 완료했다. + - 분리 줄만 뺀 대조 빌드에서는 0/2였다. 두 번 모두 `model_call_unknown.transport_unavailable`로 함께 끊겼다. +- 모델 요청 비교: rc.9 binary와 8개 사례 모두 차이 0. + +## 한계 + +- 백그라운드 Run의 in-flight agy 호출은 `/cancel`로 바로 끊지 못하고, 호출이 끝난 뒤 경계에서 멈춘다. +- 백그라운드 Run은 Step 단위 진행(`read ...`)을 보여 주지 않고 끝날 때만 알린다. +- `/show`는 세션 메모리에 있는 답만 보여 준다. 세션이 끝나면 Run ID로 `/resume`해야 다시 볼 수 있다. diff --git a/docs/development/interactive-repl.md b/docs/development/interactive-repl.md index b107b61..3016566 100644 --- a/docs/development/interactive-repl.md +++ b/docs/development/interactive-repl.md @@ -59,6 +59,10 @@ xgen> src를 탐색하고 \ /permissions /permissions model|read|write|execute ask|allow|deny /resume [RUN_ID] +/bg GOAL +/runs +/show ID +/cancel ID /clear /exit ``` @@ -122,10 +126,27 @@ Run이 도는 동안 입력창에 쓰고 Enter를 누르면 그 Run에 지시를 - 다음 모델 호출 직전에 전달된다. 전달 전에는 입력창 위에 `next step: ...`, 전달되면 `↳ added to the run: ...`이 보인다. - 모델은 지시를 goal의 일부로 읽고, 충돌하면 나중 지시를 따른다. 이미 끝난 단계는 되돌리지 않는다. -- `/`로 시작하는 줄은 명령이라 `queued: ...`로 기다렸다가 다음 `xgen> `에서 실행된다. +- `/`로 시작하는 줄은 명령이라 `queued: ...`로 기다렸다가 다음 `xgen> `에서 실행된다. `/bg`·`/runs`·`/show`·`/cancel`은 예외로 바로 실행된다. - Run이 지시를 받지 못하고 끝나면 그 지시는 다음 목표로 먼저 실행된다. 승인 질문의 답으로는 쓰지 않는다. - Esc는 기다리는 지시와 명령을 비우고, Ctrl+C는 Run 취소와 함께 비운다. 한 줄 8 KiB, Run당 16개까지다. +## 백그라운드 Run + +`/bg GOAL`은 지금 Run과 별도인 Run을 백그라운드에서 시작한다([ADR-0094](../adr/0094-background-runs.md)). +Run이 도는 중에도 입력창에서 바로 쓸 수 있다. + +- 이전 대화 맥락을 넘기지 않는 독립 Run이다. 지침 파일과 환경 안내는 일반 goal과 같이 붙는다. +- 묻지 않는다. 세션이 이미 허용한 권한(`/permissions ... allow`, 승인 질문의 `a`, `--trust`)만 쓴다. 그 밖의 + 승인이 필요하면 멈추고 `[bg1] paused (read_approval_required) run-... · /resume run-...`처럼 알린다. 입력창이 + 비어 있을 때 `/bg`를 쓰면 모델 전송 동의만 그 자리에서 묻는다. Run 중에는 모델 권한이 `allow`여야 한다. +- 끝나면 `[bg1] completed run-...: <답 첫 줄> · /show bg1`처럼 한 줄로 알린다. `/show bg1`(또는 Run ID)은 저장된 + 답 전체를, `/runs`는 목록과 상태·경과 시간을 보여 준다. +- 동시에 3개까지 돈다. `/cancel bg1`은 다음 안전한 경계에서 멈추고, Ctrl+C는 앞 Run만 취소한다. +- 같은 파일을 두 Run이 고치면 뒤에 쓰는 쪽의 쓰기가 `precondition_conflict`로 실패하고, 모델이 파일을 다시 읽어 + 이어 간다. 서로의 변경을 덮어쓰지 않는다. +- 세션을 끝내면 도는 Run을 취소하고 최대 10초 기다린다. Durable 상태는 남아 `/resume`으로 이어 갈 수 있다. + 목록 자체는 세션 메모리라 다음 세션에서는 Run ID로 `/resume`한다. + ## 긴 결과 보기 일반 TUI는 완료된 답변과 `Changes`를 결과 블록으로 보관한다. 받은 시점의 창 폭으로 12행을 넘으면