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        });
223        match cli.command.unwrap_or(default_command) {
224            CliCommand::Version => Ok(format!("{}\n", sdk_name())),
225            CliCommand::Diagnostics => Ok(self.diagnostics()?),
226            CliCommand::ReplayCheck => {
227                Ok("run `make replay-check` from the repository root\n".to_string())
228            }
229            CliCommand::Update(command) => Self::update(&command),
230            CliCommand::Run(command) => self.run_prompt(&command),
231            CliCommand::Rpc(_) => Err(CliError::Usage(
232                "rpc owns stdin/stdout and must be run through run_from_env".to_string(),
233            )),
234            CliCommand::Session { command } => self.session(command),
235            CliCommand::Profile { command } => self.profile(command),
236            CliCommand::Setup(command) => self.setup(&command),
237            CliCommand::Auth { command } => Self::auth(command),
238            CliCommand::Skill { command } => self.skills(command),
239            CliCommand::Subagent { command } => self.subagents(command),
240            CliCommand::Mcp { command } => self.mcp(command),
241            CliCommand::Tools { command } => self.tools(&command),
242            CliCommand::Tui(command) => self.tui(&command),
243            CliCommand::Approval { command } => self.approval(command),
244            CliCommand::Deferred { command } => self.deferred(command),
245            CliCommand::Resume(command) => self.resume(&command),
246            CliCommand::Reset(command) => self.reset(&command),
247            CliCommand::Config { command } => self.config(command),
248            CliCommand::Completion { shell } => render_completion(shell),
249        }
250    }
251
252    pub(crate) fn run_prompt(&mut self, command: &RunCommand) -> CliResult<String> {
253        let execution = self.execute_prompt_run(command, None)?;
254        match execution.output_mode {
255            OutputMode::Text => Ok(render_display_text(&execution.messages)),
256            OutputMode::DisplayJsonl => render_display_jsonl(&execution.messages),
257            OutputMode::AguiJsonl => render_agui_jsonl(&execution.messages),
258            OutputMode::Json => render_prompt_run_json(&execution),
259            OutputMode::Silent => Ok(format!(
260                "session_id={}\nrun_id={}\nstatus={}\n",
261                execution.session_id, execution.run_id, execution.status
262            )),
263        }
264    }
265
266    fn execute_prompt_run(
267        &mut self,
268        command: &RunCommand,
269        stream_sender: Option<mpsc::Sender<AgentStreamRecord>>,
270    ) -> CliResult<PromptRunExecution> {
271        self.execute_prompt_run_with_channels(command, None, stream_sender, None, None)
272    }
273
274    #[allow(clippy::too_many_lines)]
275    fn execute_prompt_run_with_channels(
276        &mut self,
277        command: &RunCommand,
278        prompt_input: Option<PromptInput>,
279        stream_sender: Option<mpsc::Sender<AgentStreamRecord>>,
280        steering_receiver: Option<mpsc::Receiver<CliSteeringMessage>>,
281        cancel_receiver: Option<mpsc::Receiver<()>>,
282    ) -> CliResult<PromptRunExecution> {
283        let prepared = self.prepare_prompt_run(command, prompt_input)?;
284        let run_on_error = prepared.run.clone();
285        let executed = match Self::run_prepared_prompt(
286            prepared,
287            stream_sender,
288            steering_receiver,
289            cancel_receiver,
290        ) {
291            Ok(executed) => executed,
292            Err(error) => {
293                self.fail_prepared_prompt_run(run_on_error, &error)?;
294                return Err(error);
295            }
296        };
297        self.complete_prompt_run(executed)
298    }
299
300    pub(super) fn prepare_prompt_run(
301        &mut self,
302        command: &RunCommand,
303        prompt_input: Option<PromptInput>,
304    ) -> CliResult<PreparedPromptRun> {
305        let input =
306            prompt_input.map_or_else(|| command.prompt_text().map(PromptInput::text), Ok)?;
307        let raw_prompt = input.text.clone();
308        let slash_expansion = expand_slash_command(&self.config.slash_commands, &raw_prompt);
309        let prompt = slash_expansion
310            .as_ref()
311            .map_or(raw_prompt, |expanded| expanded.prompt.clone());
312        let mut run_input = PromptInput {
313            text: prompt.clone(),
314            attachments: input.attachments,
315            extra_text_parts: input.extra_text_parts,
316            guidance_text_parts: input.guidance_text_parts,
317        };
318        let worktree = self.resolve_worktree(command)?;
319        let selected_profile = command
320            .profile
321            .as_deref()
322            .unwrap_or(&self.config.default_profile);
323        let resolved_profile = resolve_profile(&self.config, Some(selected_profile))?;
324        let mut run_config = self.config.clone();
325        if let Some(worktree) = worktree.as_ref() {
326            run_config.workspace_root.clone_from(&worktree.path);
327        }
328        validate_environment_config(&run_config)?;
329        append_guidance_files(&mut run_input, &run_config);
330        let (session_id, created) = self.resolve_session(command, &resolved_profile.name)?;
331        let environment = resolve_environment_for_session_with_attachments(
332            &run_config,
333            &session_id,
334            &command.environment_attachments,
335        )?;
336        let mut restore_from = command.run.clone().or_else(|| command.branch_from.clone());
337        if restore_from.is_none() && !created {
338            restore_from = self
339                .store()?
340                .load_session(&session_id)
341                .ok()
342                .and_then(|session| {
343                    session
344                        .active_run_id
345                        .or(session.head_run_id)
346                        .or(session.head_success_run_id)
347                        .map(|run| run.as_str().to_string())
348                });
349        }
350        let restore_state = self
351            .store()?
352            .load_restore_state(&session_id, restore_from.as_deref())?;
353        let mut run =
354            self.store()?
355                .append_run(&session_id, prompt, restore_from, &resolved_profile.name)?;
356        apply_starweaver_run_metadata(
357            &mut run,
358            command,
359            worktree.as_ref(),
360            slash_expansion.as_ref(),
361        );
362        if let Some(session_affinity_id) = command.session_affinity_id.as_deref() {
363            run.metadata.insert(
364                "starweaver.session_affinity_id".to_string(),
365                json!(session_affinity_id),
366            );
367        }
368        if !command.environment_attachments.is_empty() {
369            run.metadata.insert(
370                "starweaver.environment_attachments".to_string(),
371                json!(command.environment_attachments),
372            );
373            run.metadata.insert(
374                "starweaver.environment_attachment_ids".to_string(),
375                json!(command
376                    .environment_attachments
377                    .iter()
378                    .map(|attachment| attachment.id.as_str())
379                    .collect::<Vec<_>>()),
380            );
381        }
382        write_current_session(&self.config, &session_id)?;
383        let hitl = command.hitl.unwrap_or(self.config.default_hitl);
384        let goal = command
385            .goal
386            .as_ref()
387            .map(|goal| crate::runner::CliGoalRunPolicy {
388                objective: goal.objective.clone(),
389                max_iterations: goal.max_iterations.max(1),
390            });
391        let output_mode = command.output.unwrap_or(self.config.default_output);
392        Ok(PreparedPromptRun {
393            session_id,
394            run_id: run.run_id.as_str().to_string(),
395            output_mode,
396            run,
397            run_input,
398            resolved_profile,
399            environment,
400            restore_state,
401            policy: CliRunPolicy { hitl, goal },
402        })
403    }
404
405    pub(super) fn run_prepared_prompt(
406        prepared: PreparedPromptRun,
407        stream_sender: Option<mpsc::Sender<AgentStreamRecord>>,
408        steering_receiver: Option<mpsc::Receiver<CliSteeringMessage>>,
409        cancel_receiver: Option<mpsc::Receiver<()>>,
410    ) -> CliResult<ExecutedPromptRun> {
411        let PreparedPromptRun {
412            output_mode,
413            run,
414            run_input,
415            resolved_profile,
416            environment,
417            restore_state,
418            policy,
419            ..
420        } = prepared;
421        let result = if stream_sender.is_some()
422            || steering_receiver.is_some()
423            || cancel_receiver.is_some()
424        {
425            execute_agent_session_with_channels(
426                run_input,
427                &run,
428                &resolved_profile,
429                &environment.provider,
430                environment.process_provider.as_ref(),
431                restore_state,
432                &policy,
433                stream_sender,
434                steering_receiver,
435                cancel_receiver,
436            )
437        } else {
438            execute_agent_session(
439                run_input,
440                &run,
441                &resolved_profile,
442                &environment.provider,
443                environment.process_provider.as_ref(),
444                restore_state,
445                &policy,
446            )
447        };
448        result.map(|execution| ExecutedPromptRun {
449            run,
450            output_mode,
451            execution,
452        })
453    }
454
455    pub(super) fn fail_prepared_prompt_run(
456        &mut self,
457        mut run: RunRecord,
458        error: &CliError,
459    ) -> CliResult<()> {
460        let messages = failed_display_message(&run, &error.to_string());
461        self.store()?
462            .fail_run_with_messages(&mut run, error.to_string(), &messages)
463    }
464
465    pub(super) fn complete_prompt_run(
466        &mut self,
467        executed: ExecutedPromptRun,
468    ) -> CliResult<PromptRunExecution> {
469        let ExecutedPromptRun {
470            mut run,
471            output_mode,
472            execution,
473        } = executed;
474        let execution_failed = execution.artifacts.status == RunStatus::Failed;
475        let output = execution.output;
476        let messages = self
477            .store()?
478            .complete_run(&mut run, output.clone(), execution.artifacts)?;
479        if execution_failed && matches!(output_mode, OutputMode::Text | OutputMode::Silent) {
480            return Err(CliError::Run(output));
481        }
482        self.run_retention_maintenance(run.session_id.as_str())?;
483        Ok(PromptRunExecution {
484            session_id: run.session_id.as_str().to_string(),
485            run_id: run.run_id.as_str().to_string(),
486            status: run_status_name(run.status).to_string(),
487            output_mode,
488            messages,
489        })
490    }
491
492    fn run_retention_maintenance(&mut self, current_session_id: &str) -> CliResult<()> {
493        if !self.config.auto_trim {
494            return Ok(());
495        }
496        let current_keep_runs = self.config.current_session_keep_recent_runs;
497        self.store()?.trim(
498            vec![current_session_id.to_string()],
499            current_keep_runs,
500            false,
501        )?;
502        if !self.should_run_all_sessions_retention()? {
503            return Ok(());
504        }
505        let sessions = self.store()?.all_session_ids()?;
506        let all_sessions_keep_runs = self.config.all_sessions_keep_recent_runs;
507        let older_than = chrono::Duration::days(
508            i64::try_from(self.config.all_sessions_keep_days)
509                .unwrap_or(i64::MAX)
510                .max(0),
511        );
512        self.store()?
513            .trim_with_age(sessions, all_sessions_keep_runs, Some(older_than), false)?;
514        write_last_retention_maintenance(&self.config, chrono::Utc::now())?;
515        Ok(())
516    }
517
518    fn should_run_all_sessions_retention(&self) -> CliResult<bool> {
519        if self.config.all_sessions_keep_days == 0 || self.config.all_sessions_interval_hours == 0 {
520            return Ok(false);
521        }
522        let Some(last_run) = read_last_retention_maintenance(&self.config)? else {
523            return Ok(true);
524        };
525        let elapsed = chrono::Utc::now().signed_duration_since(last_run);
526        Ok(elapsed
527            >= chrono::Duration::hours(
528                i64::try_from(self.config.all_sessions_interval_hours)
529                    .unwrap_or(i64::MAX)
530                    .max(0),
531            ))
532    }
533
534    fn resolve_session(
535        &mut self,
536        command: &RunCommand,
537        profile: &str,
538    ) -> CliResult<(String, bool)> {
539        if command.new_session {
540            let session = self
541                .store()?
542                .create_session(profile, Some("CLI session".to_string()))?;
543            return Ok((session.session_id.as_str().to_string(), true));
544        }
545        if let Some(session_id) = command.session.as_ref() {
546            self.store()?.load_session(session_id)?;
547            return Ok((session_id.clone(), false));
548        }
549        if command.continue_session {
550            if let Some(session_id) = read_current_session(&self.config)? {
551                if self.store()?.load_session(&session_id).is_ok() {
552                    return Ok((session_id, false));
553                }
554            }
555            if let Some(session) = self.store()?.latest_session()? {
556                return Ok((session.session_id.as_str().to_string(), false));
557            }
558        }
559        let session = self
560            .store()?
561            .create_session(profile, Some("CLI session".to_string()))?;
562        Ok((session.session_id.as_str().to_string(), true))
563    }
564
565    fn session(&mut self, command: SessionCommand) -> CliResult<String> {
566        match command {
567            SessionCommand::List(command) => {
568                let sessions = self.store()?.list_sessions(command.limit)?;
569                render_sessions(&sessions, command.output)
570            }
571            SessionCommand::Show(command) => {
572                let session = self.store()?.load_session(&command.session_id)?;
573                let runs = self.store()?.list_runs(&command.session_id, command.runs)?;
574                let value = session_value(&session);
575                render_session_show(&value, &runs, command.output)
576            }
577            SessionCommand::Replay(command) => {
578                let messages = self.store()?.replay_display(
579                    &command.session_id,
580                    command.run.as_deref(),
581                    command.after,
582                )?;
583                match command.output {
584                    OutputMode::Text => Ok(render_display_text(&messages)),
585                    OutputMode::DisplayJsonl => render_display_jsonl(&messages),
586                    OutputMode::AguiJsonl => render_agui_jsonl(&messages),
587                    OutputMode::Json => Ok(format!(
588                        "{}\n",
589                        serde_json::to_string(&json!({
590                            "sessionId": command.session_id,
591                            "runId": command.run,
592                            "messages": messages,
593                            "status": "replayed"
594                        }))?
595                    )),
596                    OutputMode::Silent => Ok(format!(
597                        "session_id={}\nmessages={}\nstatus=replayed\n",
598                        command.session_id,
599                        messages.len()
600                    )),
601                }
602            }
603            SessionCommand::Delete(command) => {
604                if !command.yes {
605                    return Err(CliError::Usage(
606                        "pass --yes to delete a local session".to_string(),
607                    ));
608                }
609                let session_id = self.store()?.resolve_session_prefix(&command.session_id)?;
610                let deleted = self.store()?.delete_session(&session_id)?;
611                if read_current_session(&self.config)?.as_deref() == Some(session_id.as_str()) {
612                    let _removed =
613                        remove_file_if_exists(&self.config.project_dir.join("state.json"))?;
614                }
615                render_session_delete(&session_id, deleted, command.output)
616            }
617            SessionCommand::Trim(command) => {
618                let sessions = if command.all {
619                    self.store()?.all_session_ids()?
620                } else if let Some(session_id) = command.session {
621                    vec![session_id]
622                } else {
623                    read_current_session(&self.config)?.into_iter().collect()
624                };
625                let older_than = command
626                    .older_than
627                    .as_deref()
628                    .map(parse_duration)
629                    .transpose()?;
630                let report = self.store()?.trim_with_age(
631                    sessions,
632                    command.keep_runs,
633                    older_than,
634                    command.dry_run,
635                )?;
636                render_trim_report(&report, command.output)
637            }
638        }
639    }
640
641    fn approval(&mut self, command: ApprovalCommand) -> CliResult<String> {
642        match command {
643            ApprovalCommand::List(command) => self.approval_list(&command),
644            ApprovalCommand::Show { approval_id } => {
645                let approval = self.store()?.load_approval(&approval_id)?;
646                Ok(format!("{}\n", serde_json::to_string(&approval)?))
647            }
648            ApprovalCommand::Approve(command) => {
649                self.approval_decision(&command, ApprovalStatus::Approved)
650            }
651            ApprovalCommand::Reject(command) => {
652                self.approval_decision(&command, ApprovalStatus::Denied)
653            }
654        }
655    }
656
657    fn approval_list(&mut self, command: &ApprovalListCommand) -> CliResult<String> {
658        let approvals = self
659            .store()?
660            .list_approvals(command.session.as_deref(), command.run.as_deref())?;
661        render_approvals(&approvals, command.output)
662    }
663
664    fn approval_decision(
665        &mut self,
666        command: &ApprovalDecisionCommand,
667        status: ApprovalStatus,
668    ) -> CliResult<String> {
669        let approval =
670            self.store()?
671                .decide_approval(&command.approval_id, status, command.reason.clone())?;
672        match command.output {
673            OutputMode::Text => Ok(format!(
674                "approval_id={}\nstatus={}\nrun_id={}\n",
675                approval.approval_id,
676                approval_status_name(approval.status),
677                approval.run_id.as_str()
678            )),
679            OutputMode::DisplayJsonl | OutputMode::AguiJsonl | OutputMode::Json => {
680                Ok(format!("{}\n", serde_json::to_string(&approval)?))
681            }
682            OutputMode::Silent => Ok(format!(
683                "approval_id={}\nstatus={}\n",
684                approval.approval_id,
685                approval_status_name(approval.status)
686            )),
687        }
688    }
689
690    fn deferred(&mut self, command: DeferredCommand) -> CliResult<String> {
691        match command {
692            DeferredCommand::List(command) => self.deferred_list(&command),
693            DeferredCommand::Show { deferred_id } => {
694                let deferred = self.store()?.load_deferred_tool(&deferred_id)?;
695                Ok(format!("{}\n", serde_json::to_string(&deferred)?))
696            }
697            DeferredCommand::Complete(command) => self.deferred_complete(&command),
698            DeferredCommand::Fail(command) => self.deferred_fail(&command),
699        }
700    }
701
702    fn deferred_list(&mut self, command: &DeferredListCommand) -> CliResult<String> {
703        let records = self
704            .store()?
705            .list_deferred_tools(command.session.as_deref(), command.run.as_deref())?;
706        render_deferred(&records, command.output)
707    }
708
709    fn deferred_complete(&mut self, command: &DeferredCompleteCommand) -> CliResult<String> {
710        let value = serde_json::from_str::<Value>(&command.result)
711            .map_err(|error| CliError::Usage(format!("invalid deferred result JSON: {error}")))?;
712        let record = self
713            .store()?
714            .complete_deferred_tool(&command.deferred_id, value)?;
715        render_deferred_decision(&record, command.output)
716    }
717
718    fn deferred_fail(&mut self, command: &DeferredFailCommand) -> CliResult<String> {
719        let record = self
720            .store()?
721            .fail_deferred_tool(&command.deferred_id, &command.error)?;
722        render_deferred_decision(&record, command.output)
723    }
724
725    fn resume(&mut self, command: &ResumeCommand) -> CliResult<String> {
726        let session_id = self.resolve_session_id(command.session.as_deref())?;
727        let source_run = self.resolve_resume_run(&session_id, command.run.as_deref())?;
728        let run_command = RunCommand {
729            prompt: Some(format!(
730                "{}\n\nResuming from run {} with any persisted approval and deferred-tool decisions.",
731                command.prompt,
732                source_run.run_id.as_str()
733            )),
734            prompt_parts: Vec::new(),
735            session: Some(session_id),
736            continue_session: false,
737            new_session: false,
738            run: Some(source_run.run_id.as_str().to_string()),
739            branch_from: None,
740            profile: source_run.profile.clone(),
741            output: command.output,
742            hitl: command.hitl,
743            goal: None,
744            worker: None,
745            worker_label: None,
746            worktree: None,
747            worktree_name: None,
748            branch: None,
749            session_affinity_id: None,
750            environment_attachments: Vec::new(),
751        };
752        self.run_prompt(&run_command)
753    }
754
755    fn resolve_session_id(&mut self, requested: Option<&str>) -> CliResult<String> {
756        if let Some(session_id) = requested {
757            self.store()?.load_session(session_id)?;
758            return Ok(session_id.to_string());
759        }
760        if let Some(session_id) = read_current_session(&self.config)? {
761            if self.store()?.load_session(&session_id).is_ok() {
762                return Ok(session_id);
763            }
764        }
765        self.store()?
766            .latest_session()?
767            .map(|session| session.session_id.as_str().to_string())
768            .ok_or_else(|| CliError::NotFound("session".to_string()))
769    }
770
771    fn resolve_resume_run(
772        &mut self,
773        session_id: &str,
774        requested: Option<&str>,
775    ) -> CliResult<starweaver_session::RunRecord> {
776        if let Some(run_id) = requested {
777            return self.store()?.load_run(session_id, run_id);
778        }
779        let session = self.store()?.load_session(session_id)?;
780        let run_id = session
781            .active_run_id
782            .as_ref()
783            .or(session.head_run_id.as_ref())
784            .ok_or_else(|| CliError::NotFound("run".to_string()))?;
785        self.store()?.load_run(session_id, run_id.as_str())
786    }
787}
788
789#[allow(dead_code)]
790fn start_oauth_refresh_guard(config: &CliConfig) -> CliResult<Option<OAuthRefreshGuard>> {
791    if !config.oauth_refresh.enabled {
792        return Ok(None);
793    }
794    let models = list_profiles(config)
795        .into_iter()
796        .map(|profile| profile.model_id)
797        .collect::<Vec<_>>();
798    if config.oauth_refresh.interval_seconds == 0 {
799        return Err(CliError::Usage(
800            "invalid oauth_refresh.interval_seconds: value must be positive".to_string(),
801        ));
802    }
803    if config.oauth_refresh.failure_retry_seconds == 0 {
804        return Err(CliError::Usage(
805            "invalid oauth_refresh.failure_retry_seconds: value must be positive".to_string(),
806        ));
807    }
808    let mut supervisor = create_oauth_refresh_supervisor_for_models_with_options(
809        models.iter().map(String::as_str),
810        Duration::from_secs(config.oauth_refresh.interval_seconds),
811        Duration::from_secs(config.oauth_refresh.failure_retry_seconds),
812        config.oauth_refresh.refresh_on_startup,
813    )
814    .map_err(oauth_cli_error)?;
815    let Some(mut supervisor) = supervisor.take() else {
816        return Ok(None);
817    };
818    let (stop_sender, stop_receiver) = mpsc::channel::<()>();
819    let handle = thread::Builder::new()
820        .name("starweaver-oauth-refresh".to_string())
821        .spawn(move || {
822            let Ok(runtime) = tokio::runtime::Builder::new_current_thread()
823                .enable_all()
824                .build()
825            else {
826                return;
827            };
828            runtime.block_on(async move {
829                supervisor.start().await;
830                let _ = tokio::task::spawn_blocking(move || stop_receiver.recv()).await;
831                supervisor.shutdown().await;
832            });
833        })
834        .map_err(|error| CliError::Run(error.to_string()))?;
835    Ok(Some(OAuthRefreshGuard {
836        stop_sender,
837        handle: Some(handle),
838    }))
839}
840
841fn render_json_lines<T: serde::Serialize>(items: &[T]) -> CliResult<String> {
842    items
843        .iter()
844        .map(|item| serde_json::to_string(item).map(|line| format!("{line}\n")))
845        .collect::<Result<String, _>>()
846        .map_err(CliError::from)
847}
848
849const fn run_status_name(status: starweaver_session::RunStatus) -> &'static str {
850    match status {
851        starweaver_session::RunStatus::Queued => "queued",
852        starweaver_session::RunStatus::Running => "running",
853        starweaver_session::RunStatus::Waiting => "waiting",
854        starweaver_session::RunStatus::Completed => "completed",
855        starweaver_session::RunStatus::Failed => "failed",
856        starweaver_session::RunStatus::Cancelled => "cancelled",
857    }
858}
859
860fn parse_duration(value: &str) -> CliResult<chrono::Duration> {
861    let trimmed = value.trim();
862    if trimmed.is_empty() {
863        return Err(CliError::Usage("duration cannot be empty".to_string()));
864    }
865    let (number, unit) = trimmed.split_at(
866        trimmed
867            .find(|ch: char| !ch.is_ascii_digit())
868            .unwrap_or(trimmed.len()),
869    );
870    let amount = number
871        .parse::<i64>()
872        .map_err(|error| CliError::Usage(error.to_string()))?;
873    let duration = match unit {
874        "" | "s" | "sec" | "secs" => chrono::Duration::seconds(amount),
875        "m" | "min" | "mins" => chrono::Duration::minutes(amount),
876        "h" | "hr" | "hrs" => chrono::Duration::hours(amount),
877        "d" | "day" | "days" => chrono::Duration::days(amount),
878        other => return Err(CliError::Usage(format!("unknown duration unit: {other}"))),
879    };
880    Ok(duration)
881}
882
883#[cfg(test)]
884mod tests;