Skip to main content

starweaver_cli/
service.rs

1//! CLI service layer over local storage and SDK execution.
2#![allow(clippy::redundant_pub_crate)]
3
4use std::{fs, path::Path, sync::mpsc, thread, time::Duration};
5
6use serde_json::{json, Value};
7use starweaver_agent::ResumableState;
8use starweaver_core::sdk_name;
9use starweaver_oauth_provider::create_oauth_refresh_supervisor_for_models_with_options;
10use starweaver_runtime::AgentStreamRecord;
11use starweaver_session::{ApprovalStatus, RunRecord, RunStatus};
12use starweaver_stream::{DisplayMessage, RealtimeCompactionBuffer, ReplayScope};
13
14use crate::{
15    args::{
16        ApprovalCommand, ApprovalDecisionCommand, ApprovalListCommand, Cli, CliCommand,
17        DeferredCommand, DeferredCompleteCommand, DeferredFailCommand, DeferredListCommand,
18        OutputMode, ResumeCommand, RunCommand, SessionCommand, TuiCommand,
19    },
20    config::{
21        read_current_session, read_last_retention_maintenance, write_current_session,
22        write_last_retention_maintenance, CliConfig,
23    },
24    environment::{
25        resolve_environment_for_session_with_attachments, validate_environment_config,
26        ResolvedEnvironment,
27    },
28    local_store::LocalStore,
29    profiles::{list_profiles, resolve_profile, ResolvedProfile},
30    prompt_input::PromptInput,
31    runner::{
32        execute_agent_session, execute_agent_session_with_channels, failed_display_message,
33        CliRunPolicy, CliSteeringMessage,
34    },
35    slash_commands::expand_slash_command,
36    CliError, CliResult,
37};
38
39mod auth;
40mod catalog;
41mod rendering;
42mod setup;
43mod tui;
44mod worktree;
45
46use auth::oauth_cli_error;
47use rendering::{
48    approval_status_name, render_agui_jsonl, render_approvals, render_completion, render_deferred,
49    render_deferred_decision, render_display_jsonl, render_display_text, render_prompt_run_json,
50    render_session_delete, render_session_show, render_sessions, render_trim_report, session_value,
51};
52use setup::remove_file_if_exists;
53#[cfg(test)]
54use tui::model_choices;
55use worktree::apply_starweaver_run_metadata;
56
57pub(super) struct PromptRunExecution {
58    pub(super) session_id: String,
59    pub(super) run_id: String,
60    pub(super) status: String,
61    pub(super) output_mode: OutputMode,
62    pub(super) messages: Vec<DisplayMessage>,
63}
64
65pub(super) struct PreparedPromptRun {
66    pub(super) session_id: String,
67    pub(super) run_id: String,
68    pub(super) output_mode: OutputMode,
69    pub(super) run: RunRecord,
70    run_input: PromptInput,
71    resolved_profile: ResolvedProfile,
72    pub(super) environment: ResolvedEnvironment,
73    restore_state: Option<ResumableState>,
74    policy: CliRunPolicy,
75}
76
77pub(super) struct ExecutedPromptRun {
78    run: RunRecord,
79    output_mode: OutputMode,
80    execution: crate::runner::CliRunExecution,
81}
82
83impl ExecutedPromptRun {
84    pub(super) fn merge_display_message_inserts(
85        &mut self,
86        mut inserts: Vec<(usize, DisplayMessage)>,
87    ) {
88        if inserts.is_empty() {
89            return;
90        }
91        inserts.sort_by_key(|(index, message)| (*index, message.sequence));
92        let mut messages = self.execution.artifacts.display_messages.clone();
93        for (offset, (index, message)) in inserts.into_iter().enumerate() {
94            let position = index.saturating_add(offset).min(messages.len());
95            messages.insert(position, message);
96        }
97        for (sequence, message) in messages.iter_mut().enumerate() {
98            message.sequence = sequence;
99        }
100        let mut buffer = RealtimeCompactionBuffer::new(ReplayScope::run(self.run.run_id.as_str()));
101        for message in messages.clone() {
102            buffer.push(message);
103        }
104        self.execution.artifacts.display_snapshot = buffer.snapshot();
105        self.execution.artifacts.display_messages = messages;
106    }
107}
108
109const PROJECT_GUIDANCE_TAG: &str = "project-guidance";
110const USER_RULES_TAG: &str = "user-rules";
111
112fn append_guidance_files(input: &mut PromptInput, config: &CliConfig) {
113    if let Some(project_guidance) = load_project_guidance(&config.workspace_root) {
114        input.push_guidance_text_part(project_guidance);
115    }
116    if let Some(user_rules) = load_user_rules(&config.global_dir) {
117        input.push_guidance_text_part(user_rules);
118    }
119}
120
121fn load_project_guidance(workspace_root: &Path) -> Option<String> {
122    let path = workspace_root.join("AGENTS.md");
123    let content = read_non_empty_utf8_file(&path)?;
124    Some(format!(
125        "<{PROJECT_GUIDANCE_TAG} name=AGENTS.md>\n{content}\n</{PROJECT_GUIDANCE_TAG}>"
126    ))
127}
128
129fn load_user_rules(global_dir: &Path) -> Option<String> {
130    let path = global_dir.join("RULES.md");
131    let content = read_non_empty_utf8_file(&path)?;
132    Some(format!(
133        "<{USER_RULES_TAG} location={}>\n{content}\n</{USER_RULES_TAG}>",
134        path_absolute_posix(&path)
135    ))
136}
137
138fn read_non_empty_utf8_file(path: &Path) -> Option<String> {
139    let content = fs::read_to_string(path).ok()?;
140    (!content.trim().is_empty()).then_some(content)
141}
142
143fn path_absolute_posix(path: &Path) -> String {
144    path.canonicalize()
145        .unwrap_or_else(|_| path.to_path_buf())
146        .display()
147        .to_string()
148        .replace('\\', "/")
149}
150
151#[allow(dead_code)]
152struct OAuthRefreshGuard {
153    stop_sender: mpsc::Sender<()>,
154    handle: Option<thread::JoinHandle<()>>,
155}
156
157impl Drop for OAuthRefreshGuard {
158    fn drop(&mut self) {
159        let _ = self.stop_sender.send(());
160        if let Some(handle) = self.handle.take() {
161            let _ = handle.join();
162        }
163    }
164}
165
166/// CLI service.
167pub struct CliService {
168    config: CliConfig,
169    store: Option<LocalStore>,
170}
171
172impl CliService {
173    /// Open service from resolved config.
174    pub const fn open(config: CliConfig) -> CliResult<Self> {
175        Ok(Self {
176            config,
177            store: None,
178        })
179    }
180
181    fn store(&mut self) -> CliResult<&mut LocalStore> {
182        if self.store.is_none() {
183            self.store = Some(LocalStore::open(&self.config)?);
184        }
185        self.store
186            .as_mut()
187            .ok_or_else(|| CliError::Storage("store initialization failed".to_string()))
188    }
189
190    /// Execute a parsed CLI command.
191    pub fn execute(mut self, cli: Cli) -> CliResult<String> {
192        if let Some(prompt) = cli.prompt.clone() {
193            let command = RunCommand {
194                prompt: Some(prompt),
195                prompt_parts: Vec::new(),
196                session: cli.session.clone(),
197                continue_session: cli.continue_session,
198                new_session: cli.new_session,
199                run: cli.run.clone(),
200                branch_from: cli.branch_from.clone(),
201                profile: cli.profile.clone(),
202                output: cli.output,
203                hitl: cli.hitl,
204                goal: None,
205                worker: cli.worker.clone(),
206                worker_label: cli.worker_label.clone(),
207                worktree: cli.worktree.clone(),
208                worktree_name: cli.worktree_name.clone(),
209                branch: cli.branch,
210                session_affinity_id: None,
211                environment_attachments: Vec::new(),
212            };
213            return self.run_prompt(&command);
214        }
215        let default_command = CliCommand::Tui(TuiCommand {
216            session: cli.session.clone(),
217            run: cli.run.clone(),
218            after: None,
219            interactive: false,
220            snapshot: false,
221            output: OutputMode::Text,
222            render_mode: None,
223        });
224        match cli.command.unwrap_or(default_command) {
225            CliCommand::Version => Ok(format!("{}\n", sdk_name())),
226            CliCommand::Diagnostics => Ok(self.diagnostics()?),
227            CliCommand::ReplayCheck => {
228                Ok("run `make replay-check` from the repository root\n".to_string())
229            }
230            CliCommand::Update(command) => Self::update(&command),
231            CliCommand::Run(command) => self.run_prompt(&command),
232            CliCommand::Rpc(_) => Err(CliError::Usage(
233                "rpc owns stdin/stdout and must be run through run_from_env".to_string(),
234            )),
235            CliCommand::Session { command } => self.session(command),
236            CliCommand::Profile { command } => self.profile(command),
237            CliCommand::Setup(command) => self.setup(&command),
238            CliCommand::Auth { command } => Self::auth(command),
239            CliCommand::Skill { command } => self.skills(command),
240            CliCommand::Subagent { command } => self.subagents(command),
241            CliCommand::Mcp { command } => self.mcp(command),
242            CliCommand::Tools { command } => self.tools(&command),
243            CliCommand::Tui(command) => self.tui(&command),
244            CliCommand::Approval { command } => self.approval(command),
245            CliCommand::Deferred { command } => self.deferred(command),
246            CliCommand::Resume(command) => self.resume(&command),
247            CliCommand::Reset(command) => self.reset(&command),
248            CliCommand::Config { command } => self.config(command),
249            CliCommand::Completion { shell } => render_completion(shell),
250        }
251    }
252
253    pub(crate) fn run_prompt(&mut self, command: &RunCommand) -> CliResult<String> {
254        let execution = self.execute_prompt_run(command, None)?;
255        match execution.output_mode {
256            OutputMode::Text => Ok(render_display_text(&execution.messages)),
257            OutputMode::DisplayJsonl => render_display_jsonl(&execution.messages),
258            OutputMode::AguiJsonl => render_agui_jsonl(&execution.messages),
259            OutputMode::Json => render_prompt_run_json(&execution),
260            OutputMode::Silent => Ok(format!(
261                "session_id={}\nrun_id={}\nstatus={}\n",
262                execution.session_id, execution.run_id, execution.status
263            )),
264        }
265    }
266
267    fn execute_prompt_run(
268        &mut self,
269        command: &RunCommand,
270        stream_sender: Option<mpsc::Sender<AgentStreamRecord>>,
271    ) -> CliResult<PromptRunExecution> {
272        self.execute_prompt_run_with_channels(command, None, stream_sender, None, None)
273    }
274
275    #[allow(clippy::too_many_lines)]
276    fn execute_prompt_run_with_channels(
277        &mut self,
278        command: &RunCommand,
279        prompt_input: Option<PromptInput>,
280        stream_sender: Option<mpsc::Sender<AgentStreamRecord>>,
281        steering_receiver: Option<mpsc::Receiver<CliSteeringMessage>>,
282        cancel_receiver: Option<mpsc::Receiver<()>>,
283    ) -> CliResult<PromptRunExecution> {
284        let prepared = self.prepare_prompt_run(command, prompt_input)?;
285        let run_on_error = prepared.run.clone();
286        let executed = match Self::run_prepared_prompt(
287            prepared,
288            stream_sender,
289            steering_receiver,
290            cancel_receiver,
291        ) {
292            Ok(executed) => executed,
293            Err(error) => {
294                self.fail_prepared_prompt_run(run_on_error, &error)?;
295                return Err(error);
296            }
297        };
298        self.complete_prompt_run(executed)
299    }
300
301    pub(super) fn prepare_prompt_run(
302        &mut self,
303        command: &RunCommand,
304        prompt_input: Option<PromptInput>,
305    ) -> CliResult<PreparedPromptRun> {
306        let input =
307            prompt_input.map_or_else(|| command.prompt_text().map(PromptInput::text), Ok)?;
308        let raw_prompt = input.text.clone();
309        let slash_expansion = expand_slash_command(&self.config.slash_commands, &raw_prompt);
310        let prompt = slash_expansion
311            .as_ref()
312            .map_or(raw_prompt, |expanded| expanded.prompt.clone());
313        let mut run_input = PromptInput {
314            text: prompt.clone(),
315            attachments: input.attachments,
316            extra_text_parts: input.extra_text_parts,
317            guidance_text_parts: input.guidance_text_parts,
318        };
319        let worktree = self.resolve_worktree(command)?;
320        let selected_profile = command
321            .profile
322            .as_deref()
323            .unwrap_or(&self.config.default_profile);
324        let resolved_profile = resolve_profile(&self.config, Some(selected_profile))?;
325        let mut run_config = self.config.clone();
326        if let Some(worktree) = worktree.as_ref() {
327            run_config.workspace_root.clone_from(&worktree.path);
328        }
329        validate_environment_config(&run_config)?;
330        append_guidance_files(&mut run_input, &run_config);
331        let (session_id, created) = self.resolve_session(command, &resolved_profile.name)?;
332        let environment = resolve_environment_for_session_with_attachments(
333            &run_config,
334            &session_id,
335            &command.environment_attachments,
336        )?;
337        let mut restore_from = command.run.clone().or_else(|| command.branch_from.clone());
338        if restore_from.is_none() && !created {
339            restore_from = self
340                .store()?
341                .load_session(&session_id)
342                .ok()
343                .and_then(|session| {
344                    session
345                        .active_run_id
346                        .or(session.head_run_id)
347                        .or(session.head_success_run_id)
348                        .map(|run| run.as_str().to_string())
349                });
350        }
351        let restore_state = self
352            .store()?
353            .load_restore_state(&session_id, restore_from.as_deref())?;
354        let mut run =
355            self.store()?
356                .append_run(&session_id, prompt, restore_from, &resolved_profile.name)?;
357        apply_starweaver_run_metadata(
358            &mut run,
359            command,
360            worktree.as_ref(),
361            slash_expansion.as_ref(),
362        );
363        if let Some(session_affinity_id) = command.session_affinity_id.as_deref() {
364            run.metadata.insert(
365                "starweaver.session_affinity_id".to_string(),
366                json!(session_affinity_id),
367            );
368        }
369        if !command.environment_attachments.is_empty() {
370            run.metadata.insert(
371                "starweaver.environment_attachments".to_string(),
372                json!(command.environment_attachments),
373            );
374            run.metadata.insert(
375                "starweaver.environment_attachment_ids".to_string(),
376                json!(command
377                    .environment_attachments
378                    .iter()
379                    .map(|attachment| attachment.id.as_str())
380                    .collect::<Vec<_>>()),
381            );
382        }
383        write_current_session(&self.config, &session_id)?;
384        let hitl = command.hitl.unwrap_or(self.config.default_hitl);
385        let goal = command
386            .goal
387            .as_ref()
388            .map(|goal| crate::runner::CliGoalRunPolicy {
389                objective: goal.objective.clone(),
390                max_iterations: goal.max_iterations.max(1),
391            });
392        let output_mode = command.output.unwrap_or(self.config.default_output);
393        Ok(PreparedPromptRun {
394            session_id,
395            run_id: run.run_id.as_str().to_string(),
396            output_mode,
397            run,
398            run_input,
399            resolved_profile,
400            environment,
401            restore_state,
402            policy: CliRunPolicy { hitl, goal },
403        })
404    }
405
406    pub(super) fn run_prepared_prompt(
407        prepared: PreparedPromptRun,
408        stream_sender: Option<mpsc::Sender<AgentStreamRecord>>,
409        steering_receiver: Option<mpsc::Receiver<CliSteeringMessage>>,
410        cancel_receiver: Option<mpsc::Receiver<()>>,
411    ) -> CliResult<ExecutedPromptRun> {
412        let PreparedPromptRun {
413            output_mode,
414            run,
415            run_input,
416            resolved_profile,
417            environment,
418            restore_state,
419            policy,
420            ..
421        } = prepared;
422        let result = if stream_sender.is_some()
423            || steering_receiver.is_some()
424            || cancel_receiver.is_some()
425        {
426            execute_agent_session_with_channels(
427                run_input,
428                &run,
429                &resolved_profile,
430                &environment.provider,
431                environment.process_provider.as_ref(),
432                restore_state,
433                &policy,
434                stream_sender,
435                steering_receiver,
436                cancel_receiver,
437            )
438        } else {
439            execute_agent_session(
440                run_input,
441                &run,
442                &resolved_profile,
443                &environment.provider,
444                environment.process_provider.as_ref(),
445                restore_state,
446                &policy,
447            )
448        };
449        result.map(|execution| ExecutedPromptRun {
450            run,
451            output_mode,
452            execution,
453        })
454    }
455
456    pub(super) fn fail_prepared_prompt_run(
457        &mut self,
458        mut run: RunRecord,
459        error: &CliError,
460    ) -> CliResult<()> {
461        let messages = failed_display_message(&run, &error.to_string());
462        self.store()?
463            .fail_run_with_messages(&mut run, error.to_string(), &messages)
464    }
465
466    pub(super) fn complete_prompt_run(
467        &mut self,
468        executed: ExecutedPromptRun,
469    ) -> CliResult<PromptRunExecution> {
470        let ExecutedPromptRun {
471            mut run,
472            output_mode,
473            execution,
474        } = executed;
475        let execution_failed = execution.artifacts.status == RunStatus::Failed;
476        let output = execution.output;
477        let messages = self
478            .store()?
479            .complete_run(&mut run, output.clone(), execution.artifacts)?;
480        if execution_failed && matches!(output_mode, OutputMode::Text | OutputMode::Silent) {
481            return Err(CliError::Run(output));
482        }
483        self.run_retention_maintenance(run.session_id.as_str())?;
484        Ok(PromptRunExecution {
485            session_id: run.session_id.as_str().to_string(),
486            run_id: run.run_id.as_str().to_string(),
487            status: run_status_name(run.status).to_string(),
488            output_mode,
489            messages,
490        })
491    }
492
493    fn run_retention_maintenance(&mut self, current_session_id: &str) -> CliResult<()> {
494        if !self.config.auto_trim {
495            return Ok(());
496        }
497        let current_keep_runs = self.config.current_session_keep_recent_runs;
498        self.store()?.trim(
499            vec![current_session_id.to_string()],
500            current_keep_runs,
501            false,
502        )?;
503        if !self.should_run_all_sessions_retention()? {
504            return Ok(());
505        }
506        let sessions = self.store()?.all_session_ids()?;
507        let all_sessions_keep_runs = self.config.all_sessions_keep_recent_runs;
508        let older_than = chrono::Duration::days(
509            i64::try_from(self.config.all_sessions_keep_days)
510                .unwrap_or(i64::MAX)
511                .max(0),
512        );
513        self.store()?
514            .trim_with_age(sessions, all_sessions_keep_runs, Some(older_than), false)?;
515        write_last_retention_maintenance(&self.config, chrono::Utc::now())?;
516        Ok(())
517    }
518
519    fn should_run_all_sessions_retention(&self) -> CliResult<bool> {
520        if self.config.all_sessions_keep_days == 0 || self.config.all_sessions_interval_hours == 0 {
521            return Ok(false);
522        }
523        let Some(last_run) = read_last_retention_maintenance(&self.config)? else {
524            return Ok(true);
525        };
526        let elapsed = chrono::Utc::now().signed_duration_since(last_run);
527        Ok(elapsed
528            >= chrono::Duration::hours(
529                i64::try_from(self.config.all_sessions_interval_hours)
530                    .unwrap_or(i64::MAX)
531                    .max(0),
532            ))
533    }
534
535    fn resolve_session(
536        &mut self,
537        command: &RunCommand,
538        profile: &str,
539    ) -> CliResult<(String, bool)> {
540        if command.new_session {
541            let session = self
542                .store()?
543                .create_session(profile, Some("CLI session".to_string()))?;
544            return Ok((session.session_id.as_str().to_string(), true));
545        }
546        if let Some(session_id) = command.session.as_ref() {
547            self.store()?.load_session(session_id)?;
548            return Ok((session_id.clone(), false));
549        }
550        if command.continue_session {
551            if let Some(session_id) = read_current_session(&self.config)? {
552                if self.store()?.load_session(&session_id).is_ok() {
553                    return Ok((session_id, false));
554                }
555            }
556            if let Some(session) = self.store()?.latest_session()? {
557                return Ok((session.session_id.as_str().to_string(), false));
558            }
559        }
560        let session = self
561            .store()?
562            .create_session(profile, Some("CLI session".to_string()))?;
563        Ok((session.session_id.as_str().to_string(), true))
564    }
565
566    fn session(&mut self, command: SessionCommand) -> CliResult<String> {
567        match command {
568            SessionCommand::List(command) => {
569                let sessions = self.store()?.list_sessions(command.limit)?;
570                render_sessions(&sessions, command.output)
571            }
572            SessionCommand::Show(command) => {
573                let session = self.store()?.load_session(&command.session_id)?;
574                let runs = self.store()?.list_runs(&command.session_id, command.runs)?;
575                let value = session_value(&session);
576                render_session_show(&value, &runs, command.output)
577            }
578            SessionCommand::Replay(command) => {
579                let messages = self.store()?.replay_display(
580                    &command.session_id,
581                    command.run.as_deref(),
582                    command.after,
583                )?;
584                match command.output {
585                    OutputMode::Text => Ok(render_display_text(&messages)),
586                    OutputMode::DisplayJsonl => render_display_jsonl(&messages),
587                    OutputMode::AguiJsonl => render_agui_jsonl(&messages),
588                    OutputMode::Json => Ok(format!(
589                        "{}\n",
590                        serde_json::to_string(&json!({
591                            "sessionId": command.session_id,
592                            "runId": command.run,
593                            "messages": messages,
594                            "status": "replayed"
595                        }))?
596                    )),
597                    OutputMode::Silent => Ok(format!(
598                        "session_id={}\nmessages={}\nstatus=replayed\n",
599                        command.session_id,
600                        messages.len()
601                    )),
602                }
603            }
604            SessionCommand::Delete(command) => {
605                if !command.yes {
606                    return Err(CliError::Usage(
607                        "pass --yes to delete a local session".to_string(),
608                    ));
609                }
610                let session_id = self.store()?.resolve_session_prefix(&command.session_id)?;
611                let deleted = self.store()?.delete_session(&session_id)?;
612                if read_current_session(&self.config)?.as_deref() == Some(session_id.as_str()) {
613                    let _removed =
614                        remove_file_if_exists(&self.config.project_dir.join("state.json"))?;
615                }
616                render_session_delete(&session_id, deleted, command.output)
617            }
618            SessionCommand::Trim(command) => {
619                let sessions = if command.all {
620                    self.store()?.all_session_ids()?
621                } else if let Some(session_id) = command.session {
622                    vec![session_id]
623                } else {
624                    read_current_session(&self.config)?.into_iter().collect()
625                };
626                let older_than = command
627                    .older_than
628                    .as_deref()
629                    .map(parse_duration)
630                    .transpose()?;
631                let report = self.store()?.trim_with_age(
632                    sessions,
633                    command.keep_runs,
634                    older_than,
635                    command.dry_run,
636                )?;
637                render_trim_report(&report, command.output)
638            }
639        }
640    }
641
642    fn approval(&mut self, command: ApprovalCommand) -> CliResult<String> {
643        match command {
644            ApprovalCommand::List(command) => self.approval_list(&command),
645            ApprovalCommand::Show { approval_id } => {
646                let approval = self.store()?.load_approval(&approval_id)?;
647                Ok(format!("{}\n", serde_json::to_string(&approval)?))
648            }
649            ApprovalCommand::Approve(command) => {
650                self.approval_decision(&command, ApprovalStatus::Approved)
651            }
652            ApprovalCommand::Reject(command) => {
653                self.approval_decision(&command, ApprovalStatus::Denied)
654            }
655        }
656    }
657
658    fn approval_list(&mut self, command: &ApprovalListCommand) -> CliResult<String> {
659        let approvals = self
660            .store()?
661            .list_approvals(command.session.as_deref(), command.run.as_deref())?;
662        render_approvals(&approvals, command.output)
663    }
664
665    fn approval_decision(
666        &mut self,
667        command: &ApprovalDecisionCommand,
668        status: ApprovalStatus,
669    ) -> CliResult<String> {
670        let approval =
671            self.store()?
672                .decide_approval(&command.approval_id, status, command.reason.clone())?;
673        match command.output {
674            OutputMode::Text => Ok(format!(
675                "approval_id={}\nstatus={}\nrun_id={}\n",
676                approval.approval_id,
677                approval_status_name(approval.status),
678                approval.run_id.as_str()
679            )),
680            OutputMode::DisplayJsonl | OutputMode::AguiJsonl | OutputMode::Json => {
681                Ok(format!("{}\n", serde_json::to_string(&approval)?))
682            }
683            OutputMode::Silent => Ok(format!(
684                "approval_id={}\nstatus={}\n",
685                approval.approval_id,
686                approval_status_name(approval.status)
687            )),
688        }
689    }
690
691    fn deferred(&mut self, command: DeferredCommand) -> CliResult<String> {
692        match command {
693            DeferredCommand::List(command) => self.deferred_list(&command),
694            DeferredCommand::Show { deferred_id } => {
695                let deferred = self.store()?.load_deferred_tool(&deferred_id)?;
696                Ok(format!("{}\n", serde_json::to_string(&deferred)?))
697            }
698            DeferredCommand::Complete(command) => self.deferred_complete(&command),
699            DeferredCommand::Fail(command) => self.deferred_fail(&command),
700        }
701    }
702
703    fn deferred_list(&mut self, command: &DeferredListCommand) -> CliResult<String> {
704        let records = self
705            .store()?
706            .list_deferred_tools(command.session.as_deref(), command.run.as_deref())?;
707        render_deferred(&records, command.output)
708    }
709
710    fn deferred_complete(&mut self, command: &DeferredCompleteCommand) -> CliResult<String> {
711        let value = serde_json::from_str::<Value>(&command.result)
712            .map_err(|error| CliError::Usage(format!("invalid deferred result JSON: {error}")))?;
713        let record = self
714            .store()?
715            .complete_deferred_tool(&command.deferred_id, value)?;
716        render_deferred_decision(&record, command.output)
717    }
718
719    fn deferred_fail(&mut self, command: &DeferredFailCommand) -> CliResult<String> {
720        let record = self
721            .store()?
722            .fail_deferred_tool(&command.deferred_id, &command.error)?;
723        render_deferred_decision(&record, command.output)
724    }
725
726    fn resume(&mut self, command: &ResumeCommand) -> CliResult<String> {
727        let session_id = self.resolve_session_id(command.session.as_deref())?;
728        let source_run = self.resolve_resume_run(&session_id, command.run.as_deref())?;
729        let run_command = RunCommand {
730            prompt: Some(format!(
731                "{}\n\nResuming from run {} with any persisted approval and deferred-tool decisions.",
732                command.prompt,
733                source_run.run_id.as_str()
734            )),
735            prompt_parts: Vec::new(),
736            session: Some(session_id),
737            continue_session: false,
738            new_session: false,
739            run: Some(source_run.run_id.as_str().to_string()),
740            branch_from: None,
741            profile: source_run.profile.clone(),
742            output: command.output,
743            hitl: command.hitl,
744            goal: None,
745            worker: None,
746            worker_label: None,
747            worktree: None,
748            worktree_name: None,
749            branch: None,
750            session_affinity_id: None,
751            environment_attachments: Vec::new(),
752        };
753        self.run_prompt(&run_command)
754    }
755
756    fn resolve_session_id(&mut self, requested: Option<&str>) -> CliResult<String> {
757        if let Some(session_id) = requested {
758            self.store()?.load_session(session_id)?;
759            return Ok(session_id.to_string());
760        }
761        if let Some(session_id) = read_current_session(&self.config)? {
762            if self.store()?.load_session(&session_id).is_ok() {
763                return Ok(session_id);
764            }
765        }
766        self.store()?
767            .latest_session()?
768            .map(|session| session.session_id.as_str().to_string())
769            .ok_or_else(|| CliError::NotFound("session".to_string()))
770    }
771
772    fn resolve_resume_run(
773        &mut self,
774        session_id: &str,
775        requested: Option<&str>,
776    ) -> CliResult<starweaver_session::RunRecord> {
777        if let Some(run_id) = requested {
778            return self.store()?.load_run(session_id, run_id);
779        }
780        let session = self.store()?.load_session(session_id)?;
781        let run_id = session
782            .active_run_id
783            .as_ref()
784            .or(session.head_run_id.as_ref())
785            .ok_or_else(|| CliError::NotFound("run".to_string()))?;
786        self.store()?.load_run(session_id, run_id.as_str())
787    }
788}
789
790#[allow(dead_code)]
791fn start_oauth_refresh_guard(config: &CliConfig) -> CliResult<Option<OAuthRefreshGuard>> {
792    if !config.oauth_refresh.enabled {
793        return Ok(None);
794    }
795    let models = list_profiles(config)
796        .into_iter()
797        .map(|profile| profile.model_id)
798        .collect::<Vec<_>>();
799    if config.oauth_refresh.interval_seconds == 0 {
800        return Err(CliError::Usage(
801            "invalid oauth_refresh.interval_seconds: value must be positive".to_string(),
802        ));
803    }
804    if config.oauth_refresh.failure_retry_seconds == 0 {
805        return Err(CliError::Usage(
806            "invalid oauth_refresh.failure_retry_seconds: value must be positive".to_string(),
807        ));
808    }
809    let mut supervisor = create_oauth_refresh_supervisor_for_models_with_options(
810        models.iter().map(String::as_str),
811        Duration::from_secs(config.oauth_refresh.interval_seconds),
812        Duration::from_secs(config.oauth_refresh.failure_retry_seconds),
813        config.oauth_refresh.refresh_on_startup,
814    )
815    .map_err(oauth_cli_error)?;
816    let Some(mut supervisor) = supervisor.take() else {
817        return Ok(None);
818    };
819    let (stop_sender, stop_receiver) = mpsc::channel::<()>();
820    let handle = thread::Builder::new()
821        .name("starweaver-oauth-refresh".to_string())
822        .spawn(move || {
823            let Ok(runtime) = tokio::runtime::Builder::new_current_thread()
824                .enable_all()
825                .build()
826            else {
827                return;
828            };
829            runtime.block_on(async move {
830                supervisor.start().await;
831                let _ = tokio::task::spawn_blocking(move || stop_receiver.recv()).await;
832                supervisor.shutdown().await;
833            });
834        })
835        .map_err(|error| CliError::Run(error.to_string()))?;
836    Ok(Some(OAuthRefreshGuard {
837        stop_sender,
838        handle: Some(handle),
839    }))
840}
841
842fn render_json_lines<T: serde::Serialize>(items: &[T]) -> CliResult<String> {
843    items
844        .iter()
845        .map(|item| serde_json::to_string(item).map(|line| format!("{line}\n")))
846        .collect::<Result<String, _>>()
847        .map_err(CliError::from)
848}
849
850const fn run_status_name(status: starweaver_session::RunStatus) -> &'static str {
851    match status {
852        starweaver_session::RunStatus::Queued => "queued",
853        starweaver_session::RunStatus::Running => "running",
854        starweaver_session::RunStatus::Waiting => "waiting",
855        starweaver_session::RunStatus::Completed => "completed",
856        starweaver_session::RunStatus::Failed => "failed",
857        starweaver_session::RunStatus::Cancelled => "cancelled",
858    }
859}
860
861fn parse_duration(value: &str) -> CliResult<chrono::Duration> {
862    let trimmed = value.trim();
863    if trimmed.is_empty() {
864        return Err(CliError::Usage("duration cannot be empty".to_string()));
865    }
866    let (number, unit) = trimmed.split_at(
867        trimmed
868            .find(|ch: char| !ch.is_ascii_digit())
869            .unwrap_or(trimmed.len()),
870    );
871    let amount = number
872        .parse::<i64>()
873        .map_err(|error| CliError::Usage(error.to_string()))?;
874    let duration = match unit {
875        "" | "s" | "sec" | "secs" => chrono::Duration::seconds(amount),
876        "m" | "min" | "mins" => chrono::Duration::minutes(amount),
877        "h" | "hr" | "hrs" => chrono::Duration::hours(amount),
878        "d" | "day" | "days" => chrono::Duration::days(amount),
879        other => return Err(CliError::Usage(format!("unknown duration unit: {other}"))),
880    };
881    Ok(duration)
882}
883
884#[cfg(test)]
885mod tests;