mobius-gateway 0.16.2

Headless authenticated gateway for möbius frontends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use super::deletion::{prepare_session_tree_deletion, remove_session_trees, session_trees};
use super::*;

pub(super) async fn accept_routine_while_state_locked(
    _state: &mut tokio::sync::MutexGuard<'_, GatewayState>,
    host: &HostHandle,
    run: ActiveRoutineRun,
    input: String,
    bots: &BotStore,
) -> std::result::Result<(), Rejection> {
    host.run_routine(run, input, bots).await
}

impl GatewayHost {
    pub(crate) async fn bot_routine_snapshot(
        &self,
        bot_id: &str,
    ) -> std::result::Result<serde_json::Value, Rejection> {
        let _access = self.begin_mutation().await?;
        let state = self.state.lock().await;
        state.bots.bot(bot_id).map_err(invalid_bot)?;
        let routines = state
            .bots
            .routine_records(Some(bot_id), Utc::now().timestamp())
            .map_err(invalid_routine)?;
        let runs = state
            .bots
            .history(None)
            .map_err(internal)?
            .into_iter()
            .filter(|run| run.bot_id == bot_id)
            .take(100)
            .collect::<Vec<_>>();
        Ok(serde_json::json!({"routines":routines,"recent_runs":runs}))
    }

    pub(crate) async fn routine_workspace(
        &self,
        bot_id: &str,
        workspace: Option<&Path>,
    ) -> std::result::Result<PathBuf, Rejection> {
        let _access = self.begin_mutation().await?;
        let state = self.state.lock().await;
        let bot = state.bots.bot(bot_id).map_err(invalid_bot)?;
        let tls = state
            .config
            .lock()
            .map_err(|_| internal("configuration lock poisoned"))?
            .tls
            .clone();
        match workspace {
            Some(workspace) => crate::config::validate_chat_workspace(
                workspace,
                state.store.state_dir(),
                tls.as_ref(),
            )
            .map_err(invalid_workspace),
            None => ChatSpec::persistent(&bot)
                .execution_root(state.store.state_dir(), tls.as_ref())
                .map_err(invalid_workspace),
        }
    }

    pub(crate) async fn create_routine(
        &self,
        bot_id: &str,
        definition: &crate::wire::RoutineDefinition,
        cause: Option<&crate::wire::HookEvent>,
    ) -> std::result::Result<crate::wire::Routine, Rejection> {
        let _mutation = self.begin_mutation().await?;
        let state = self.state.lock().await;
        validate_bot_workspace(&state, bot_id, &definition.workspace)?;
        validate_routine_bindings(&state, bot_id, &definition.bindings).await?;
        let routine = state
            .bots
            .create_routine(bot_id, definition, cause)
            .map_err(invalid_routine)?;
        state
            .bots
            .routine_record(&routine.id, Utc::now().timestamp())
            .map_err(invalid_routine)
    }

    pub(crate) async fn execute_routine_command(
        &self,
        command: &crate::wire::RoutineCommand,
        owner_id: Option<&str>,
        cause: Option<&crate::wire::HookEvent>,
        command_id: &str,
    ) -> std::result::Result<(), Rejection> {
        use crate::wire::RoutineAction;
        match &command.action {
            RoutineAction::Start => {
                self.start_routine_command(&command.routine_id, owner_id, cause, command_id)
                    .await
            }
            RoutineAction::Stop { run_id } => {
                let _mutation = self.begin_mutation().await?;
                let (run, checkpoints) = {
                    let state = self.state.lock().await;
                    if !super::bot_events::command_pending(&state.bots, cause, command_id)? {
                        return Ok(());
                    }
                    require_routine_owner(&state.bots, &command.routine_id, owner_id)?;
                    let run = state.bots.run(run_id).map_err(invalid_routine)?;
                    if run.routine_id != command.routine_id {
                        return Err(invalid_routine("run does not belong to this routine"));
                    }
                    (run, Arc::clone(&state.checkpoints))
                };
                if run.status != RoutineRunStatus::Running {
                    return Ok(());
                }
                let session_id = run
                    .session_id
                    .ok_or_else(|| invalid_routine("run has no session"))?;
                let checkpoint = checkpoints
                    .load(&session_id)
                    .await
                    .map_err(internal)?
                    .ok_or_else(unknown_session)?;
                let turn_id = checkpoint
                    .active_execution
                    .ok_or_else(|| Rejection {
                        code: "agent_busy",
                        message: "run admission has not started a turn yet; retry".into(),
                        fatal: false,
                    })?
                    .turn_id;
                self.state
                    .lock()
                    .await
                    .bots
                    .request_run_stop(run_id, command_id, cause)
                    .map_err(internal)?;
                drop(_mutation);
                self.open_session(&session_id)
                    .await?
                    .submit(Submission {
                        id: command_id.into(),
                        op: Op::Interrupt { turn_id },
                    })
                    .await
            }
            RoutineAction::Pause | RoutineAction::Resume => {
                let _mutation = self.begin_mutation().await?;
                let state = self.state.lock().await;
                if !super::bot_events::command_pending(&state.bots, cause, command_id)? {
                    return Ok(());
                }
                require_routine_owner(&state.bots, &command.routine_id, owner_id)?;
                state
                    .bots
                    .set_routine_enabled(
                        &command.routine_id,
                        matches!(command.action, RoutineAction::Resume),
                        cause,
                        cause.map(|_| command_id),
                    )
                    .map(|_| ())
                    .map_err(invalid_routine)
            }
            RoutineAction::Update { definition } => {
                let _mutation = self.begin_exclusive_mutation().await?;
                let state = self.state.lock().await;
                if !super::bot_events::command_pending(&state.bots, cause, command_id)? {
                    return Ok(());
                }
                require_routine_owner(&state.bots, &command.routine_id, owner_id)?;
                let bot_id = state
                    .bots
                    .routine(&command.routine_id)
                    .map_err(invalid_routine)?
                    .bot_id;
                validate_bot_workspace(&state, &bot_id, &definition.workspace)?;
                validate_routine_bindings(&state, &bot_id, &definition.bindings).await?;
                state
                    .bots
                    .update_routine(
                        &command.routine_id,
                        definition,
                        cause,
                        cause.map(|_| command_id),
                    )
                    .map(|_| ())
                    .map_err(invalid_routine)
            }
            RoutineAction::Delete => {
                self.delete_routine(&command.routine_id, owner_id, cause, command_id)
                    .await
            }
        }
    }

    pub(crate) async fn delete_routine(
        &self,
        routine_id: &str,
        owner_id: Option<&str>,
        cause: Option<&crate::wire::HookEvent>,
        command_id: &str,
    ) -> std::result::Result<(), Rejection> {
        let _mutation = self.begin_exclusive_mutation().await?;
        let mut state = self.state.lock().await;
        if !super::bot_events::command_pending(&state.bots, cause, command_id)? {
            return Ok(());
        }
        require_routine_owner(&state.bots, routine_id, owner_id)?;
        let roots = state
            .bots
            .history(Some(routine_id))
            .map_err(invalid_routine)?
            .into_iter()
            .filter_map(|run| run.session_id)
            .collect();
        let summaries = gateway_session_summaries(&state.checkpoints)
            .await
            .map_err(internal)?;
        let session_ids = session_trees(roots, &summaries).1;
        let mut file_deletion = prepare_session_tree_deletion(&mut state, &session_ids).await?;
        let summaries = gateway_session_summaries(&state.checkpoints)
            .await
            .map_err(internal)?;
        let deletion = state
            .bots
            .prepare_routine_deletion(routine_id)
            .map_err(invalid_routine)?;
        let roots = deletion
            .session_ids()
            .iter()
            .filter(|root| summaries.iter().any(|session| session.session_id == **root))
            .cloned()
            .collect();
        let (session_roots, session_ids) = session_trees(roots, &summaries);
        state
            .bots
            .delete_routine(deletion, cause, cause.map(|_| command_id))
            .map_err(invalid_routine)?;
        let cleanup = remove_session_trees(
            &mut state,
            &session_roots,
            &session_ids,
            &mut file_deletion,
            true,
        )
        .await;
        drop(state);
        self.cleanup_session_files(file_deletion);
        if !session_ids.is_empty() {
            let _ = self.broadcast_sessions().await;
        }
        if let Some(rejection) = match cleanup {
            Ok(warning) => warning,
            Err(rejection) => Some(rejection),
        } {
            let _ = self.events.send(ServerFrame::new(ServerMessage::Error {
                code: "routine_cleanup".into(),
                message: rejection.message,
                fatal: false,
            }));
        }
        Ok(())
    }

    async fn start_routine_command(
        &self,
        routine_id: &str,
        owner_id: Option<&str>,
        cause: Option<&crate::wire::HookEvent>,
        command_id: &str,
    ) -> std::result::Result<(), Rejection> {
        self.work_activity.mark();
        let _mutation = self.begin_mutation().await?;
        let state = self.state.lock().await;
        if !super::bot_events::command_pending(&state.bots, cause, command_id)? {
            return Ok(());
        }
        require_routine_owner(&state.bots, routine_id, owner_id)?;
        let run = match state
            .bots
            .begin_run_with_cause(routine_id, command_id, cause)
            .map_err(invalid_routine)?
        {
            BeginRun::Started(run) => run,
            BeginRun::AlreadyRecorded => return Ok(()),
            BeginRun::Skipped => {
                return Err(Rejection {
                    code: "routine_overlap",
                    message: format!("routine {routine_id} is already running"),
                    fatal: false,
                });
            }
        };
        drop(_mutation);
        self.run_routine_with_state(state, routine_id.into(), run)
            .await
    }

    pub(crate) async fn routine_run_preview(
        &self,
        run_id: &str,
        before_sequence: Option<u64>,
    ) -> std::result::Result<crate::wire::RoutineRunPreview, Rejection> {
        let _mutation = self.begin_mutation().await?;
        let (bots, run) = {
            let state = self.state.lock().await;
            let bots = Arc::clone(&state.bots);
            let run = bots.run(run_id).map_err(invalid_routine)?;
            (bots, run)
        };
        let session_id = run.session_id.clone().ok_or_else(|| Rejection {
            code: "routine_run_unavailable",
            message: "this routine run has no execution session".into(),
            fatal: false,
        })?;
        drop(_mutation);
        let (host, temporary) = self.open_session_with_cache(&session_id, false).await?;
        let page = host.history_page(before_sequence).await;
        if temporary {
            let _ = host.stop_if_idle().await;
        }
        let page = page?;
        let routine = bots
            .routine_record(&run.routine_id, Utc::now().timestamp())
            .map_err(invalid_routine)?;
        Ok(crate::wire::RoutineRunPreview {
            routine,
            run,
            records: page.records,
            next_before_sequence: page.next_before_sequence,
        })
    }

    pub(crate) async fn delete_routine_run(
        &self,
        run_id: &str,
    ) -> std::result::Result<(), Rejection> {
        let _mutation = self.begin_exclusive_mutation().await?;
        let mut state = self.state.lock().await;
        let run = state.bots.run(run_id).map_err(invalid_routine)?;
        if run.status == RoutineRunStatus::Running {
            return Err(Rejection {
                code: "routine_run_active",
                message: format!("routine run {run_id} is currently running"),
                fatal: false,
            });
        }
        let session_root = run.session_id;
        let session_ids = if let Some(session_id) = session_root.as_deref() {
            let summaries = gateway_session_summaries(&state.checkpoints)
                .await
                .map_err(internal)?;
            session_tree_ids(session_id, &summaries).unwrap_or_default()
        } else {
            Vec::new()
        };
        let mut file_deletion = prepare_session_tree_deletion(&mut state, &session_ids).await?;
        state.bots.delete_run(run_id).map_err(invalid_routine)?;
        let cleanup = if let Some(session_root) = session_root.filter(|_| !session_ids.is_empty()) {
            remove_session_trees(
                &mut state,
                &[session_root],
                &session_ids,
                &mut file_deletion,
                true,
            )
            .await
        } else {
            Ok(None)
        };
        drop(state);
        self.cleanup_session_files(file_deletion);
        if !session_ids.is_empty() {
            let _ = self.broadcast_sessions().await;
        }
        if let Some(rejection) = match cleanup {
            Ok(warning) => warning,
            Err(rejection) => Some(rejection),
        } {
            let _ = self.events.send(ServerFrame::new(ServerMessage::Error {
                code: "routine_cleanup".into(),
                message: rejection.message,
                fatal: false,
            }));
        }
        Ok(())
    }

    async fn run_routine_with_state(
        &self,
        state: tokio::sync::MutexGuard<'_, GatewayState>,
        routine_id: String,
        run: ActiveRoutineRun,
    ) -> std::result::Result<(), Rejection> {
        let bots = Arc::clone(&state.bots);
        drop(state);
        let preflight = bots.routine_input(&routine_id).map_err(invalid_routine);
        let (routine, input) = match preflight {
            Ok(preflight) => preflight,
            Err(rejection) => {
                bots.finish_run(
                    run,
                    crate::wire::RoutineRunStatus::Failed,
                    Some(rejection.message.clone()),
                )
                .map_err(internal)?;
                return Err(rejection);
            }
        };
        let session_id = run.session_id().to_owned();
        let label = format!("routine · {}", routine.id.get(..8).unwrap_or(&routine.id));
        let host = match self
            .create_session_with_id(
                Some(&routine.workspace),
                &routine.bot_id,
                session_id.clone(),
                false,
                &label,
            )
            .await
        {
            Ok(host) => host,
            Err(rejection) => {
                let status = if rejection.code == "session_limit" {
                    crate::wire::RoutineRunStatus::Skipped
                } else {
                    crate::wire::RoutineRunStatus::Failed
                };
                bots.finish_run(run, status, Some(rejection.message.clone()))
                    .map_err(internal)?;
                return Err(rejection);
            }
        };
        let mut state = self.state.lock().await;
        let accepted =
            accept_routine_while_state_locked(&mut state, &host, run, input, bots.as_ref()).await;
        drop(state);
        match accepted {
            Ok(()) => {
                let broadcast = self.broadcast_sessions().await;
                let gateway = self.clone();
                let cleanup = tokio::spawn(async move {
                    host.wait_idle().await;
                    gateway.state.lock().await.sessions.remove(&session_id);
                    let _ = gateway.broadcast_sessions().await;
                });
                let mut state = self.state.lock().await;
                state.idle_cleanup_tasks.retain(|task| !task.is_finished());
                state.idle_cleanup_tasks.push(cleanup);
                broadcast
            }
            Err(rejection) => {
                let _ = host.stop_if_idle().await;
                self.state.lock().await.sessions.remove(&session_id);
                Err(rejection)
            }
        }
    }
}

fn require_routine_owner(
    bots: &BotStore,
    id: &str,
    owner: Option<&str>,
) -> std::result::Result<(), Rejection> {
    if let Some(owner) = owner {
        let routine = bots.routine(id).map_err(invalid_routine)?;
        if routine.bot_id != owner {
            return Err(unknown_session());
        }
    }
    Ok(())
}

async fn validate_routine_bindings(
    state: &GatewayState,
    bot_id: &str,
    bindings: &[crate::wire::RoutineBinding],
) -> std::result::Result<(), Rejection> {
    for binding in bindings {
        if let crate::wire::HookSelector::Event { .. } = &binding.on {
            super::bot_events::validate_selector(state, bot_id, &binding.on).await?;
        }
    }
    Ok(())
}