Skip to main content

mj_controller/server/api/
subagent_backend.rs

1use super::*;
2
3/// Everything the API needs from the daemon: live session actors, the durable
4/// projection, and the target-side git operations.
5///
6/// The daemon's implementation lives in `server_runtime::api`; route tests
7/// supply a fake.
8pub trait SubagentBackend: Send + Sync {
9    fn transcript_history(
10        &self,
11        session_id: String,
12        before: Option<mj_core::storage::TranscriptCursor>,
13    ) -> BoxFuture<'_, AnyResult<mj_core::storage::TranscriptHistoryPage>> {
14        Box::pin(async move {
15            tokio::task::spawn_blocking(move || {
16                crate::database::load_transcript_history(&session_id, before.as_ref(), 128)?
17                    .context("session history is unavailable")
18            })
19            .await?
20        })
21    }
22
23    fn native_agent_history(
24        &self,
25        owner: String,
26        child: String,
27        before: Option<(u64, String)>,
28    ) -> BoxFuture<'_, AnyResult<mj_core::native_agent::NativeAgentHistoryPage>> {
29        Box::pin(async move {
30            tokio::task::spawn_blocking(move || {
31                crate::database::native_agent_history(&owner, &child, before)
32            })
33            .await?
34        })
35    }
36    fn events(
37        &self,
38        filter: crate::database::ApiEventFilter,
39        after_seq: Option<u64>,
40    ) -> BoxFuture<'_, AnyResult<crate::database::ApiEventPage>> {
41        events::load_events(filter, after_seq)
42    }
43
44    fn profile_config(
45        &self,
46        profile: String,
47        model: Option<String>,
48        refresh: bool,
49    ) -> BoxFuture<'_, AnyResult<mj_core::worker_launch::ProfileConfig>> {
50        Box::pin(crate::controller::profile_config::discover(
51            profile, model, refresh,
52        ))
53    }
54    /// The profiles a parent running on `parent_profile` may start a sub-agent
55    /// on, each with its discovered choices and remaining quota. It waits for
56    /// a discovery the daemon has not finished; a profile whose discovery
57    /// fails is reported as unavailable rather than failing the whole answer.
58    fn subagent_candidates(
59        &self,
60        _parent_profile: String,
61    ) -> BoxFuture<'_, AnyResult<SubagentCandidates>> {
62        Box::pin(async { anyhow::bail!("sub-agent profiles are unavailable") })
63    }
64    fn start_subagent(
65        &self,
66        _request: crate::controller::RegisterSubagentRequest,
67    ) -> BoxFuture<'_, AnyResult<mj_core::subagent::SubagentRecord>> {
68        Box::pin(async { anyhow::bail!("sub-agent creation is unavailable") })
69    }
70    fn list_subagents(
71        &self,
72        parent_session_id: String,
73    ) -> BoxFuture<'_, AnyResult<Vec<mj_core::subagent::SubagentRecord>>> {
74        Box::pin(async move {
75            tokio::task::spawn_blocking(move || crate::database::list_subagents(&parent_session_id))
76                .await?
77        })
78    }
79    fn read_context_file(
80        &self,
81        session_id: String,
82        path: PathBuf,
83    ) -> BoxFuture<'_, std::result::Result<Vec<u8>, ExportError>> {
84        self.read_file(session_id, path)
85    }
86    /// The workspaces the store holds, in the order the terminal's tabs and the
87    /// viewer's list show them.
88    fn list_workspaces(
89        &self,
90    ) -> BoxFuture<'_, AnyResult<Vec<mj_core::workspace::WorkspaceRecord>>> {
91        Box::pin(async { tokio::task::spawn_blocking(crate::database::list_workspaces).await? })
92    }
93    /// The workspace with this name, creating it when the store holds none.
94    ///
95    /// This is the daemon's own `CreateWorkspace` operation: create-or-get, so
96    /// two callers that both saw an empty list attach to the same normalized
97    /// name instead of one of them meeting a SQLite conflict. The daemon
98    /// overrides it to republish the list afterwards.
99    fn create_workspace(
100        &self,
101        name: String,
102    ) -> BoxFuture<'_, AnyResult<mj_core::workspace::WorkspaceRecord>> {
103        Box::pin(async move {
104            tokio::task::spawn_blocking(move || crate::database::create_or_get_workspace(&name))
105                .await?
106        })
107    }
108    fn set_config(
109        &self,
110        session_id: String,
111        key: String,
112        value: String,
113    ) -> BoxFuture<'_, AnyResult<()>> {
114        Box::pin(async move {
115            self.session_handle(session_id)
116                .await?
117                .ok_or_else(|| anyhow::anyhow!("session has no live actor"))?
118                .set_config(key, value)
119                .await
120        })
121    }
122    fn cancel_start(&self, _session_id: String) -> BoxFuture<'_, AnyResult<()>> {
123        Box::pin(async { Ok(()) })
124    }
125    /// The live actor for a session, or `None` when none holds it.
126    fn session_handle(&self, session_id: String)
127    -> BoxFuture<'_, AnyResult<Option<SessionHandle>>>;
128
129    /// Submit a prompt, returning its relay acceptance ordinal.
130    fn prompt(&self, session_id: String, text: String) -> BoxFuture<'_, AnyResult<u64>>;
131
132    /// Durable turn state for a session with no live actor.
133    fn turn_state(&self, session_id: String) -> BoxFuture<'_, AnyResult<Option<TurnState>>>;
134
135    /// A sub-agent child's recorded report, and whether it has the handback
136    /// tool. `None` for a session that is not a Mjolnir sub-agent.
137    fn subagent_report(
138        &self,
139        _session_id: String,
140    ) -> BoxFuture<'_, AnyResult<Option<(bool, mj_core::subagent::SubagentReport)>>> {
141        Box::pin(async { Ok(None) })
142    }
143
144    /// Summarize the turn that covers these transcript positions.
145    fn turn_summary(
146        &self,
147        session_id: String,
148        turn: TurnSpan,
149    ) -> BoxFuture<'_, AnyResult<TurnSummary>>;
150
151    /// Apply model, effort, and the first prompt once a new session is ready.
152    fn start_followup(
153        &self,
154        session_id: String,
155        followup: StartFollowup,
156    ) -> BoxFuture<'_, AnyResult<()>>;
157
158    /// How far a created session's follow-up has got.
159    fn start_status(&self, session_id: String) -> BoxFuture<'_, AnyResult<Option<StartStatus>>>;
160
161    /// A page of transcript items after `after_seq`.
162    fn transcript(
163        &self,
164        session_id: String,
165        after_seq: u64,
166        limit: usize,
167        role: Option<mj_core::transcript::TranscriptRole>,
168    ) -> BoxFuture<'_, AnyResult<Option<TranscriptPage>>>;
169
170    fn usage(
171        &self,
172        session_id: String,
173        after_seq: u64,
174        limit: usize,
175    ) -> BoxFuture<'_, AnyResult<Option<crate::database::UsagePage>>> {
176        Box::pin(async move {
177            tokio::task::spawn_blocking(move || {
178                crate::database::load_session_usage(&session_id, after_seq, limit)
179            })
180            .await?
181        })
182    }
183
184    /// A unified diff of the session's work.
185    fn diff(
186        &self,
187        session_id: String,
188        options: DiffOptions,
189    ) -> BoxFuture<'_, Result<String, ExportError>>;
190
191    /// One file from the session's workspace.
192    fn read_file(
193        &self,
194        session_id: String,
195        path: PathBuf,
196    ) -> BoxFuture<'_, Result<Vec<u8>, ExportError>>;
197
198    fn write_file(
199        &self,
200        _session_id: String,
201        _path: PathBuf,
202        _bytes: Vec<u8>,
203        _overwrite: bool,
204    ) -> BoxFuture<'_, Result<(), ExportError>> {
205        Box::pin(async { Err(ExportError::Refused("file injection is unavailable".into())) })
206    }
207
208    /// Push the session's branch to its repository's default remote.
209    fn push_branch(
210        &self,
211        session_id: String,
212        branch: String,
213    ) -> BoxFuture<'_, Result<PushedBranch, ExportError>>;
214
215    /// A git bundle of the session's committed work.
216    fn bundle(&self, session_id: String) -> BoxFuture<'_, Result<BundleExport, ExportError>>;
217
218    /// Whether the index was synced recently enough that a query need not ask
219    /// for one.
220    fn wiki_sync_is_stale(&self) -> bool {
221        false
222    }
223
224    /// Ask for a background sync. It is never waited for: a query answers from
225    /// what the index holds now.
226    fn wiki_request_sync(&self) {}
227
228    fn wiki_search(
229        &self,
230        _query: String,
231        _limit: usize,
232    ) -> BoxFuture<'_, AnyResult<mj_client::daemon::WikiSearchPage>> {
233        Box::pin(async { anyhow::bail!("SessionWiki search is unavailable") })
234    }
235
236    /// `None` when the index holds no session with that id.
237    fn wiki_brief(
238        &self,
239        _wiki_id: String,
240        _max_chars: usize,
241    ) -> BoxFuture<'_, AnyResult<Option<String>>> {
242        Box::pin(async { anyhow::bail!("SessionWiki briefings are unavailable") })
243    }
244
245    /// The passages of one indexed session that match a query. `None` when the
246    /// index holds no session with that id.
247    fn wiki_hits(
248        &self,
249        _wiki_id: String,
250        _query: String,
251        _context_messages: usize,
252        _per_message_chars: usize,
253    ) -> BoxFuture<'_, AnyResult<Option<mj_client::daemon::WikiHitTranscript>>> {
254        Box::pin(async { anyhow::bail!("SessionWiki transcript hits are unavailable") })
255    }
256
257    /// What one indexed session is, and what continuing it would mean.
258    /// `None` when the index holds no session with that id.
259    fn wiki_session(
260        &self,
261        _wiki_id: String,
262    ) -> BoxFuture<'_, AnyResult<Option<mj_client::daemon::WikiSessionInfo>>> {
263        Box::pin(async { anyhow::bail!("SessionWiki lookups are unavailable") })
264    }
265
266    /// Start a session from an archived transcript, answering with its id, or
267    /// `None` when the index holds no session with that id.
268    fn wiki_restore(
269        &self,
270        _request: mj_client::daemon::WikiRestoreRequest,
271    ) -> BoxFuture<'_, AnyResult<Option<String>>> {
272        Box::pin(async { anyhow::bail!("SessionWiki restore is unavailable") })
273    }
274}
275
276pub(super) fn backend(state: &ServerState) -> Result<&Arc<dyn SubagentBackend>, ApiFailure> {
277    state
278        .subagent
279        .as_ref()
280        .ok_or_else(|| ApiFailure::unavailable("this server has no subagent backend installed"))
281}
282
283// ---------------------------------------------------------------------------
284// Wait resolution
285// ---------------------------------------------------------------------------