Skip to main content

mj_controller/server/api/
types.rs

1use super::*;
2
3/// Comparison and representation requested for a session's working-tree diff.
4#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
5#[serde(deny_unknown_fields)]
6pub struct DiffOptions {
7    pub base: Option<String>,
8    #[serde(default)]
9    pub json: bool,
10}
11
12/// Observed provider-owned background work; absent when no live snapshot is available.
13#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
14pub struct ApiBackgroundWork {
15    pub known: Option<bool>,
16    pub tasks: Vec<mj_core::relay::BackgroundCommand>,
17}
18
19impl From<&mj_core::relay::RelayOperationalState> for ApiBackgroundWork {
20    fn from(state: &mj_core::relay::RelayOperationalState) -> Self {
21        Self {
22            known: state.background_work_known,
23            tasks: state.background_commands.clone(),
24        }
25    }
26}
27
28/// One session as the API presents it. This is a narrower, more stable shape
29/// than the viewer's own session projection, which changes whenever the browser
30/// needs something new.
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
32pub struct ApiSession {
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub background_work: Option<ApiBackgroundWork>,
35    pub id: String,
36    pub workspace_id: String,
37    pub title: String,
38    pub harness_kind: String,
39    pub profile_id: String,
40    pub target_id: String,
41    pub bundle_id: String,
42    pub state: String,
43    pub lifecycle: ViewerLifecycleCategory,
44    pub chat_phase: crate::server::ViewerChatPhase,
45    pub is_idle: bool,
46    /// What this session is doing, in more detail than `chat_phase`'s four
47    /// values allow: in particular it can say that the daemon cannot see the
48    /// worker and report what it last knew, rather than claiming idleness it
49    /// cannot prove.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub activity_state: Option<mj_core::activity::ActivityState>,
52    pub has_error: bool,
53    /// Why a launch failed, for a session in the error state. Absent
54    /// otherwise: raw runtime error text is deliberately not published for a
55    /// running session. Why a *turn* failed travels in `last_turn_diagnostic`,
56    /// which a single-session query fills.
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub error: Option<String>,
59    pub created_at: String,
60    pub updated_at: String,
61    /// How the last finished prompt ended. Absent unless the caller asked for
62    /// one session by id or waited on it, because the dashboard projection the
63    /// list is built from does not carry turn identity.
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub last_turn_outcome: Option<MaterializedTurnOutcome>,
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub last_turn_diagnostic: Option<mj_core::diagnostic::TurnDiagnostic>,
68    #[serde(default)]
69    pub config_options: Vec<crate::server::ViewerConfigOption>,
70    #[serde(default, skip_serializing_if = "Vec::is_empty")]
71    pub pending_elicitations: Vec<mj_core::elicitation::ElicitationRequest>,
72}
73
74impl From<&ViewerSession> for ApiSession {
75    fn from(session: &ViewerSession) -> Self {
76        Self {
77            background_work: None,
78            id: session.id.clone(),
79            workspace_id: session.workspace_id.clone(),
80            title: session.title.clone(),
81            harness_kind: session.harness_kind.clone(),
82            profile_id: session.profile_id.clone(),
83            target_id: session.target_id.clone(),
84            bundle_id: session.bundle_id.clone(),
85            state: session.state.clone(),
86            lifecycle: session.lifecycle,
87            chat_phase: session.chat_phase,
88            is_idle: session.is_idle,
89            activity_state: session.activity_state.clone(),
90            has_error: session.has_error,
91            error: session.launch_error.clone(),
92            created_at: session.created_at.clone(),
93            updated_at: session.updated_at.clone(),
94            last_turn_outcome: None,
95            last_turn_diagnostic: None,
96            config_options: session.config_options.clone(),
97            pending_elicitations: session.pending_elicitations.clone(),
98        }
99    }
100}
101
102#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
103pub struct SessionListResponse {
104    pub sessions: Vec<ApiSession>,
105}
106
107/// The workspaces the daemon holds, newest opening first, exactly as the
108/// terminal's workspace tabs and the viewer's list see them.
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110pub struct WorkspaceListResponse {
111    pub workspaces: Vec<mj_core::workspace::WorkspaceRecord>,
112}
113
114/// Name the workspace to work in. The name is the identity: it is trimmed, at
115/// most 64 characters, and unique case-insensitively, so naming one that
116/// already exists returns it rather than making a second.
117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
118#[serde(deny_unknown_fields)]
119pub struct CreateWorkspaceRequest {
120    pub name: String,
121}
122
123#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
124pub struct CreateWorkspaceResponse {
125    pub workspace: mj_core::workspace::WorkspaceRecord,
126}
127
128/// Create a session and, optionally, send its first prompt. Served in M2.
129///
130/// `profile_id` and `target_id` may be omitted, and each resolves
131/// independently: a caller may name a profile and take the saved default
132/// target. An omitted identifier comes from the pair the user last saved with
133/// the `mj go` workflow, which the first setup also becomes, so a caller that
134/// has never read `config.toml` can create a session by naming neither. The
135/// controller still receives two explicit identifiers, because a session whose
136/// profile was implicit would be a session nobody can explain later.
137#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
138#[serde(deny_unknown_fields)]
139pub struct StartSessionRequest {
140    #[serde(default)]
141    pub create_managed_worktree: Option<bool>,
142    /// Git revision the session starts at, as the caller typed it.
143    #[serde(default)]
144    pub launch_base: Option<String>,
145    /// Branch to check out in a new isolated workspace.
146    #[serde(default)]
147    pub launch_branch: Option<String>,
148    /// None means native sub-agents, the same as `Some(false)`.
149    #[serde(default)]
150    pub mjolnir_subagents: Option<bool>,
151    #[serde(default)]
152    pub workspace_id: Option<String>,
153    /// Omitted follows the saved default. See the type's own documentation.
154    #[serde(default)]
155    pub profile_id: Option<String>,
156    /// Omitted follows the saved default. See the type's own documentation.
157    #[serde(default)]
158    pub target_id: Option<String>,
159    #[serde(default)]
160    pub bundle_id: Option<String>,
161    #[serde(default)]
162    pub project_directory: Option<PathBuf>,
163    #[serde(default)]
164    pub title: Option<String>,
165    #[serde(default)]
166    pub model: Option<String>,
167    #[serde(default)]
168    pub effort: Option<String>,
169    #[serde(default)]
170    pub prompt: Option<String>,
171}
172
173/// Resume a stopped, lost, or failed session. Every field is optional: the
174/// session's own record supplies what the caller does not name, which is what
175/// makes `POST .../resume` with no body the scriptable "continue this session"
176/// call.
177#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
178#[serde(deny_unknown_fields)]
179pub struct ResumeSessionRequest {
180    /// Profile to resume on. Defaults to the one the session last ran.
181    #[serde(default)]
182    pub profile_id: Option<String>,
183    /// Target template to provision. Defaults to the session's own.
184    #[serde(default)]
185    pub target_id: Option<String>,
186    /// Workspace the resumed session belongs to. Defaults to its own.
187    #[serde(default)]
188    pub workspace_id: Option<String>,
189    /// Whether prompts queued when the session stopped are started or
190    /// discarded. Defaults to `start`, which is what the terminal's own resume
191    /// wizard defaults to.
192    #[serde(default)]
193    pub queue: Option<mj_core::state::ResumeQueueDisposition>,
194}
195
196/// What a resume was accepted as: the settings it will actually use, resolved
197/// from the request and the session's record.
198#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
199pub struct ResumeSessionResponse {
200    pub session_id: String,
201    pub workspace_id: String,
202    pub profile_id: String,
203    pub target_id: String,
204}
205
206#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
207pub struct StartSessionResponse {
208    pub session_id: String,
209    /// The turn the follow-up prompt was accepted as, once it has been
210    /// submitted. Creation answers before that, so it is usually absent.
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub turn_id: Option<u64>,
213}
214
215#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
216#[serde(deny_unknown_fields)]
217pub struct SubagentSourceRange {
218    pub file: PathBuf,
219    pub start: u64,
220    pub end: u64,
221}
222
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
224#[serde(deny_unknown_fields)]
225pub struct SpawnSubagentRequest {
226    pub task_name: String,
227    pub instructions: String,
228    #[serde(default)]
229    pub profile_id: Option<String>,
230    #[serde(default)]
231    pub model: Option<String>,
232    #[serde(default)]
233    pub effort: Option<String>,
234    #[serde(default)]
235    pub working_directory: Option<PathBuf>,
236    #[serde(default)]
237    pub context: Option<String>,
238    #[serde(default)]
239    pub files: Vec<SubagentSourceRange>,
240}
241
242/// One profile a parent may start a sub-agent on, with what it offers and how
243/// much of its quota is left.
244#[derive(Debug, Clone, PartialEq, Eq)]
245pub struct SubagentCandidate {
246    pub profile_id: String,
247    pub harness: mj_core::config::HarnessKind,
248    pub choices: mj_core::worker_launch::ProfileConfig,
249    /// The lower of the profile's quota windows (the 5-hour and weekly ones
250    /// for Codex and Claude), 100 for a pay-per-use profile, and `None` when
251    /// no usable report exists.
252    pub remaining_percent: Option<u8>,
253}
254
255/// The profiles a parent may delegate to, split into those whose choices are
256/// known and those whose discovery failed, with the reason.
257#[derive(Debug, Clone, Default, PartialEq, Eq)]
258pub struct SubagentCandidates {
259    pub offered: Vec<SubagentCandidate>,
260    pub unavailable: Vec<(String, String)>,
261}
262
263#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
264pub struct SubagentView {
265    pub parent_session_id: String,
266    pub task_name: String,
267    pub session: ApiSession,
268}
269
270#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
271pub struct SubagentListResponse {
272    pub subagents: Vec<SubagentView>,
273}
274
275#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
276#[serde(deny_unknown_fields)]
277pub struct PromptRequest {
278    pub text: String,
279}
280
281#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
282pub struct PromptResponse {
283    /// The relay acceptance ordinal for this prompt, which is what `wait`
284    /// takes as `turn_id`.
285    pub turn_id: u64,
286}
287
288#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
289#[serde(deny_unknown_fields)]
290pub struct WaitRequest {
291    /// Return when the harness presents a structured input request.
292    #[serde(default)]
293    pub return_on_input: bool,
294    /// Wait for this specific prompt. Absent means "wait until the session is
295    /// idle with nothing queued", which is what a caller that lost its turn id
296    /// wants.
297    #[serde(default)]
298    pub turn_id: Option<u64>,
299    #[serde(default)]
300    pub timeout_secs: Option<u64>,
301}
302
303/// How a wait ended.
304#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
305#[serde(rename_all = "snake_case")]
306pub enum WaitOutcome {
307    /// A structured elicitation needs an answer; only returned by opt-in waits.
308    InputRequired,
309    /// The turn completed normally.
310    Finished,
311    /// The turn failed, was rejected, or the session reported an error.
312    Error,
313    /// The turn was cancelled or interrupted.
314    Cancelled,
315    /// The model was at capacity and no retry is armed.
316    QuotaLimit,
317    /// The wait's deadline passed with the turn still running.
318    Timeout,
319    /// The session stopped or is stopping, so no turn can finish on it.
320    Stopped,
321}
322
323#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
324pub struct WaitCapacityRetry {
325    pub attempt: u32,
326    pub retry_at_ms: i64,
327}
328
329impl From<&CapacityRetry> for WaitCapacityRetry {
330    fn from(retry: &CapacityRetry) -> Self {
331        Self {
332            attempt: retry.attempt,
333            retry_at_ms: retry.retry_at_ms,
334        }
335    }
336}
337
338/// How the daemon's live view of a session's relay is doing.
339///
340/// This reports; it never decides an outcome. A caller that gets `timeout`
341/// needs to tell "the turn is still working" from "the daemon cannot see the
342/// worker at all", and those look identical without it.
343#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
344#[serde(rename_all = "snake_case")]
345pub enum RelayState {
346    /// The daemon is attached to the worker and following its events.
347    Connected,
348    /// Not attached, with no error recorded yet: attaching, or between tries.
349    Disconnected,
350    /// The worker could not be reached.
351    Unreachable,
352    /// The session's target is gone.
353    TargetMissing,
354    /// The event stream did not line up with what the daemon had projected.
355    ProjectionIntegrity,
356}
357
358#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
359pub struct RelayHealth {
360    pub state: RelayState,
361    /// The view's own description of the problem, when it recorded one.
362    #[serde(default, skip_serializing_if = "Option::is_none")]
363    pub detail: Option<String>,
364}
365
366impl From<&mj_client::session::ManagedSessionView> for RelayHealth {
367    fn from(view: &mj_client::session::ManagedSessionView) -> Self {
368        use mj_client::session::ViewError;
369        // A recorded error outranks `connected`: it is the specific thing
370        // standing between the caller and a finished turn.
371        match &view.error {
372            Some(error) => Self {
373                state: match error {
374                    ViewError::Unreachable(_) => RelayState::Unreachable,
375                    ViewError::TargetMissing(_) => RelayState::TargetMissing,
376                    ViewError::ProjectionIntegrity(_) => RelayState::ProjectionIntegrity,
377                },
378                detail: Some(error.detail().to_owned()),
379            },
380            None if view.connected => Self {
381                state: RelayState::Connected,
382                detail: None,
383            },
384            None => Self {
385                state: RelayState::Disconnected,
386                detail: None,
387            },
388        }
389    }
390}
391
392#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
393pub struct WaitResponse {
394    #[serde(default, skip_serializing_if = "Option::is_none")]
395    pub diagnostic: Option<mj_core::diagnostic::TurnDiagnostic>,
396
397    #[serde(default, skip_serializing_if = "Vec::is_empty")]
398    pub pending_elicitations: Vec<mj_core::elicitation::ElicitationRequest>,
399    #[serde(default, skip_serializing_if = "Option::is_none")]
400    pub usage: Option<mj_core::usage::TokenUsage>,
401    pub outcome: WaitOutcome,
402    /// The harness's own stop reason, when the turn reached one.
403    #[serde(default, skip_serializing_if = "Option::is_none")]
404    pub stop_reason: Option<String>,
405    /// Why the wait ended this way, when there is something to say.
406    #[serde(default, skip_serializing_if = "Option::is_none")]
407    pub message: Option<String>,
408    /// The agent's last message of the turn, flattened to text. For a
409    /// sub-agent child it is the report the child handed back, when it did.
410    #[serde(default, skip_serializing_if = "Option::is_none")]
411    pub final_message: Option<String>,
412    /// For a sub-agent child: `handback` when `final_message` is the report
413    /// the child handed back, `last_message` when it is the turn's last
414    /// message. Absent for every other session.
415    #[serde(default, skip_serializing_if = "Option::is_none")]
416    pub report_source: Option<String>,
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub turn_id: Option<u64>,
419    /// One-based position of this turn in the conversation.
420    #[serde(default, skip_serializing_if = "Option::is_none")]
421    pub turn_number: Option<u64>,
422    #[serde(default, skip_serializing_if = "Option::is_none")]
423    pub elapsed_ms: Option<i64>,
424    /// Legacy alias for a worker-owned server retry, retained for older clients.
425    #[serde(default, skip_serializing_if = "Option::is_none")]
426    pub capacity_retry: Option<WaitCapacityRetry>,
427    #[serde(default, skip_serializing_if = "Option::is_none")]
428    pub server_retry: Option<WaitCapacityRetry>,
429    #[serde(default)]
430    pub retry_assessment_pending: bool,
431    #[serde(default, skip_serializing_if = "Option::is_none")]
432    pub quota_recovery: Option<mj_core::continuation::QuotaRecovery>,
433    /// The health of the daemon's live view of this session. Absent when no
434    /// live actor holds the session, because there is then no view to report
435    /// on and inventing one would be worse than saying nothing.
436    #[serde(default, skip_serializing_if = "Option::is_none")]
437    pub relay: Option<RelayHealth>,
438    pub session: ApiSession,
439}
440
441/// How many transcript items a page carries when the caller names no limit,
442/// and the most it may ask for. A caller that asks for more gets the ceiling
443/// rather than an error: paging is the point, and refusing a large limit would
444/// only make the caller retry with a smaller one.
445pub const DEFAULT_TRANSCRIPT_LIMIT: usize = 200;
446pub const MAX_TRANSCRIPT_LIMIT: usize = 1_000;
447
448#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
449pub struct TranscriptQuery {
450    #[serde(default)]
451    pub role: Option<mj_core::transcript::TranscriptRole>,
452    /// Resume from the highest sequence the caller has already seen.
453    #[serde(default)]
454    pub after_seq: Option<u64>,
455    #[serde(default)]
456    pub limit: Option<usize>,
457}
458
459#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
460pub struct TranscriptItemView {
461    pub stable_id: String,
462    pub position: u64,
463    /// What to pass as the next `after_seq`. It is the position for everything
464    /// but an agent message, which carries the ordinal of its latest content.
465    pub seq: u64,
466    pub role: String,
467    /// The item flattened to text, which is what a reading caller wants.
468    pub text: String,
469    pub created_at_ms: i64,
470    pub last_changed_at_ms: i64,
471    /// The stored body, for a caller that needs the structure behind the text.
472    pub body: mj_core::transcript::TranscriptBody,
473}
474
475#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
476pub struct TranscriptResponse {
477    #[serde(default)]
478    pub next_after_seq: u64,
479    pub session_id: String,
480    /// The newest sequence in the whole transcript. A page whose last item
481    /// reaches this is up to date.
482    pub latest_seq: u64,
483    pub execution: MaterializedExecutionState,
484    pub items: Vec<TranscriptItemView>,
485}
486
487// ---------------------------------------------------------------------------
488// Backend
489// ---------------------------------------------------------------------------
490
491/// Where a session stands turn by turn, read from the durable projection when
492/// no live actor holds the session.
493#[derive(Debug, Clone, PartialEq, Eq)]
494pub struct TurnState {
495    pub execution: MaterializedExecutionState,
496    pub active_turn: Option<MaterializedTurn>,
497    pub last_turn_outcome: Option<MaterializedTurnOutcome>,
498}
499
500pub use crate::database::TurnSummary;
501
502/// Configuration and a first prompt to apply once a newly created session's
503/// harness is ready. Served in M2.
504#[derive(Debug, Clone, Default, PartialEq, Eq)]
505pub struct StartFollowup {
506    pub model: Option<String>,
507    pub effort: Option<String>,
508    pub prompt: Option<String>,
509    pub fast_mode: bool,
510}
511
512/// How far a created session's follow-up has got. Served in M2.
513#[derive(Debug, Clone, PartialEq, Eq)]
514pub enum StartStatus {
515    /// The session is still provisioning, or its harness is not ready.
516    Pending,
517    /// The follow-up prompt was submitted and accepted as this turn.
518    Submitted { turn_id: u64 },
519    /// The session could not be started, or the follow-up could not be applied.
520    Failed { message: String },
521}
522
523/// A page of transcript items, read from the durable projection.
524pub use crate::database::TranscriptPage;
525
526/// A branch the daemon pushed on the caller's behalf.
527#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
528pub struct PushedBranch {
529    pub branch: String,
530    pub remote: String,
531}
532
533/// Which file of the session's workspace to read.
534#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
535pub struct FileQuery {
536    /// Path relative to the session's workspace root.
537    pub path: String,
538}
539
540/// What form the caller wants the session's work in.
541#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
542#[serde(rename_all = "snake_case")]
543pub enum ExportKind {
544    /// A unified diff, as `GET /diff` returns.
545    Patch,
546    /// A branch pushed to the repository's push remote.
547    Branch,
548    /// The git bundle of the session's committed work.
549    Bundle,
550}
551
552#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
553pub struct ExportRequest {
554    pub kind: ExportKind,
555    /// The branch to push. Required when `kind` is `branch`.
556    #[serde(default, skip_serializing_if = "Option::is_none")]
557    pub branch: Option<String>,
558}
559
560/// A git bundle of the session's work.
561#[derive(Debug, Clone)]
562pub struct BundleExport {
563    pub repository: String,
564    pub bytes: Vec<u8>,
565}
566
567/// Why an export could not be produced. Served in M4.
568#[derive(Debug)]
569pub enum ExportError {
570    /// The session is in a state where this export is not possible. The caller
571    /// can act on it, so it answers 409.
572    Refused(String),
573    /// The export was attempted and failed.
574    Failed(anyhow::Error),
575}
576
577impl From<ExportError> for ApiFailure {
578    fn from(error: ExportError) -> Self {
579        match error {
580            ExportError::Refused(message) => Self::conflict(message),
581            ExportError::Failed(error) => Self::from(error),
582        }
583    }
584}
585
586// ---------------------------------------------------------------------------
587// SessionWiki
588// ---------------------------------------------------------------------------
589
590#[derive(Debug, Default, Deserialize)]
591#[serde(deny_unknown_fields)]
592pub struct WikiSearchQuery {
593    #[serde(default)]
594    pub q: Option<String>,
595    #[serde(default)]
596    pub limit: Option<usize>,
597}
598
599#[derive(Debug, Default, Deserialize)]
600#[serde(deny_unknown_fields)]
601pub struct WikiBriefQuery {
602    #[serde(default)]
603    pub max_chars: Option<usize>,
604}
605
606#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
607pub struct WikiBriefResponse {
608    pub markdown: String,
609}
610
611/// The query for the matching passages of one indexed session.
612#[derive(Debug, Default, Deserialize)]
613#[serde(deny_unknown_fields)]
614pub struct WikiHitsQuery {
615    pub q: String,
616    #[serde(default)]
617    pub context_messages: Option<usize>,
618    #[serde(default)]
619    pub per_message_chars: Option<usize>,
620}
621
622/// The fields of a start request a restore needs. The archived session decides
623/// the rest: its title, and the project it ran in when the caller names none.
624#[derive(Debug, Clone, Default, Serialize, Deserialize)]
625#[serde(deny_unknown_fields)]
626pub struct WikiRestoreBody {
627    #[serde(default)]
628    pub workspace_id: Option<String>,
629    pub profile_id: String,
630    pub target_id: String,
631    #[serde(default)]
632    pub project_directory: Option<PathBuf>,
633    #[serde(default)]
634    pub model: Option<String>,
635    #[serde(default)]
636    pub effort: Option<String>,
637}
638
639// ---------------------------------------------------------------------------
640// Launch options
641// ---------------------------------------------------------------------------
642
643/// What a caller may choose when it starts a session, and which pair to use
644/// when it chooses nothing.
645///
646/// Served by `GET /api/v1/options` so a caller that has never read
647/// `config.toml` can enumerate the profiles and targets this daemon knows,
648/// learn whether each host answered its last check, and read the remembered
649/// default. It is the public projection in `server/viewer_types.rs`, narrowed
650/// to what a launch decision needs: no harness home, no SSH host or key, no
651/// container environment, no AWS detail, and no controller-side path.
652#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
653#[serde(deny_unknown_fields)]
654pub struct LaunchOptions {
655    /// The projection revision these lists came from. Two reads carrying the
656    /// same revision describe the same configuration, so a caller can build a
657    /// form without mixing halves of two different worlds.
658    pub revision: u64,
659    pub profiles: Vec<LaunchProfile>,
660    pub targets: Vec<LaunchTarget>,
661    pub bundles: Vec<LaunchBundle>,
662    /// One entry per host that has published a capacity reading. The label is
663    /// how a person names the host; it is never a locator or an address.
664    #[serde(default, skip_serializing_if = "Vec::is_empty")]
665    pub hosts: Vec<LaunchHost>,
666    /// The pair the user last saved as their default, which the first setup
667    /// also becomes. Absent when nothing has ever been saved, and never an
668    /// error: a caller that cannot read a preference still has the lists.
669    #[serde(default, skip_serializing_if = "Option::is_none")]
670    pub default: Option<LaunchDefault>,
671}
672
673/// One account this daemon can run work under.
674#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
675#[serde(deny_unknown_fields)]
676pub struct LaunchProfile {
677    pub id: String,
678    /// The harness kind, such as `codex` or `claude`. Which account it is, and
679    /// where its credentials live, stay on the controller.
680    pub harness: String,
681}
682
683/// One runtime template a session can run on.
684#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
685#[serde(deny_unknown_fields)]
686pub struct LaunchTarget {
687    pub id: String,
688    /// The runtime kind, such as `local-bare` or `ssh-podman`.
689    pub kind: String,
690    /// Whether this target needs an existing Git directory on its machine
691    /// instead of provisioning repositories into a workspace.
692    pub requires_project_directory: bool,
693    pub availability: LaunchAvailability,
694    /// What to tell a person when the host did not answer. This repository
695    /// composes the sentence: a probe's own message names hosts and commands
696    /// and stays on the controller.
697    #[serde(default, skip_serializing_if = "Option::is_none")]
698    pub unavailable_reason: Option<String>,
699    /// How a person names the host, when a reading covers this target.
700    #[serde(default, skip_serializing_if = "Option::is_none")]
701    pub host: Option<String>,
702}
703
704/// How much this daemon knows about a target's host.
705///
706/// A reading arrives from a background poll, so it can be absent, old, or
707/// failed. Only `Unavailable` is a statement that the target cannot be used;
708/// `Unknown` means nobody has checked yet, which is the ordinary state
709/// immediately after startup.
710#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
711#[serde(rename_all = "lowercase")]
712pub enum LaunchAvailability {
713    /// A reading covers this target and its last check succeeded.
714    Ready,
715    /// A reading covers this target but is marked stale.
716    Stale,
717    /// A reading covers this target and its last check failed.
718    Unavailable,
719    /// No reading covers this target yet.
720    Unknown,
721}
722
723/// One repository set a managed target can provision.
724#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
725#[serde(deny_unknown_fields)]
726pub struct LaunchBundle {
727    pub id: String,
728    pub primary_repository: String,
729    pub repositories: Vec<LaunchRepository>,
730}
731
732#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
733#[serde(deny_unknown_fields)]
734pub struct LaunchRepository {
735    pub id: String,
736    /// The GitHub source, when this repository has one. A repository sourced
737    /// from a local directory publishes nothing here, because that source is a
738    /// path on the controller.
739    #[serde(default, skip_serializing_if = "Option::is_none")]
740    pub github: Option<String>,
741    pub destination: String,
742}
743
744/// One host or fleet, as much as a caller needs to explain an unavailable
745/// target. The probe's own error text is deliberately absent.
746#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
747#[serde(deny_unknown_fields)]
748pub struct LaunchHost {
749    pub id: String,
750    pub label: String,
751    /// The targets this reading covers.
752    pub targets: Vec<String>,
753    pub stale: bool,
754    pub refreshing: bool,
755    pub has_error: bool,
756}
757
758/// The pair a caller may leave unnamed when it starts a session.
759#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
760#[serde(deny_unknown_fields)]
761pub struct LaunchDefault {
762    pub profile_id: String,
763    pub target_id: String,
764}