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