oino-core 1.0.0

Coding-agent runtime for Oino: AgentSession, extension runner, compaction, retry
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
//! Client events (runtime.md ยง6): `AgentSessionEvent` plus the other client events.
//!
//! These types will move to `oino-protocol::events` once that crate exists; the JSON shapes
//! are already the wire shapes (fixed field names, `type` tags).

use oino_agent::{AgentEvent, AgentToolResult};
use oino_ai::{
    AgentMessage, AssistantMessageEvent, JsonObject, Model, ThinkingLevel, ToolResultMessage,
};
use oino_session::SessionEntry;
use serde::{Deserialize, Serialize};

use crate::compaction::CompactionResult;
use crate::ui::{DismissReason, UiRequest};

/// Why compaction ran.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CompactionReason {
    /// `/compact`, RPC or an extension.
    Manual,
    /// Context crossed the threshold.
    Threshold,
    /// The provider reported a context overflow.
    Overflow,
}

/// What a summarisation retry belongs to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "source")]
pub enum SummarizationSource {
    /// A branch summary.
    #[serde(rename = "branchSummary")]
    BranchSummary,
    /// A compaction.
    #[serde(rename = "compaction")]
    Compaction {
        /// Compaction trigger.
        reason: CompactionReason,
    },
}

/// One event emitted by an agent session.
#[allow(
    clippy::large_enum_variant,
    reason = "variants mirror the event shapes; events are moved through channels one at a time"
)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AgentSessionEvent {
    /// A run started.
    AgentStart,
    /// A run ended.
    #[serde(rename_all = "camelCase")]
    AgentEnd {
        /// Messages the run added.
        messages: Vec<AgentMessage>,
        /// An automatic retry follows.
        will_retry: bool,
    },
    /// The session became idle after activity.
    AgentSettled {
        /// The activity was aborted.
        aborted: bool,
    },
    /// A turn started.
    TurnStart,
    /// A turn ended.
    #[serde(rename_all = "camelCase")]
    TurnEnd {
        /// Assistant message of the turn.
        message: AgentMessage,
        /// Tool results (serialised with `role`).
        #[serde(with = "tagged_tool_results")]
        tool_results: Vec<ToolResultMessage>,
    },
    /// A message started.
    MessageStart {
        /// The message.
        message: AgentMessage,
    },
    /// The streaming message changed.
    #[serde(rename_all = "camelCase")]
    MessageUpdate {
        /// Partial message.
        message: AgentMessage,
        /// Provider event.
        assistant_message_event: AssistantMessageEvent,
    },
    /// A message is final.
    MessageEnd {
        /// The message.
        message: AgentMessage,
    },
    /// A tool call started.
    #[serde(rename_all = "camelCase")]
    ToolExecutionStart {
        /// Tool-call id.
        tool_call_id: String,
        /// Tool name.
        tool_name: String,
        /// Arguments.
        args: JsonObject,
        /// Calling tool for nested calls.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        parent_tool_call_id: Option<String>,
    },
    /// A tool published a partial result.
    #[serde(rename_all = "camelCase")]
    ToolExecutionUpdate {
        /// Tool-call id.
        tool_call_id: String,
        /// Tool name.
        tool_name: String,
        /// Arguments.
        args: JsonObject,
        /// Partial result.
        partial_result: AgentToolResult,
        /// Calling tool for nested calls.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        parent_tool_call_id: Option<String>,
    },
    /// A tool call settled.
    #[serde(rename_all = "camelCase")]
    ToolExecutionEnd {
        /// Tool-call id.
        tool_call_id: String,
        /// Tool name.
        tool_name: String,
        /// Result.
        result: AgentToolResult,
        /// Error flag.
        is_error: bool,
        /// Wall time.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        duration_ms: Option<u64>,
        /// Calling tool for nested calls.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        parent_tool_call_id: Option<String>,
    },
    /// Complete steering / follow-up queues.
    #[serde(rename_all = "camelCase")]
    QueueUpdate {
        /// Steering texts.
        steering: Vec<String>,
        /// Follow-up texts.
        follow_up: Vec<String>,
    },
    /// Compaction started.
    CompactionStart {
        /// Trigger.
        reason: CompactionReason,
    },
    /// Compaction finished.
    #[serde(rename_all = "camelCase")]
    CompactionEnd {
        /// Trigger.
        reason: CompactionReason,
        /// Result (absent on failure).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        result: Option<CompactionResult>,
        /// Cancelled.
        aborted: bool,
        /// The interrupted turn is retried.
        will_retry: bool,
        /// Failure text.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        error_message: Option<String>,
    },
    /// An extension appended an entry.
    EntryAppended {
        /// The entry.
        entry: SessionEntry,
    },
    /// The session name changed (absent = cleared).
    SessionInfoChanged {
        /// New name.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        name: Option<String>,
    },
    /// The thinking level changed.
    ThinkingLevelChanged {
        /// New level.
        level: ThinkingLevel,
    },
    /// An automatic retry is scheduled.
    #[serde(rename_all = "camelCase")]
    AutoRetryStart {
        /// Attempt number (1-based).
        attempt: u32,
        /// Retry budget.
        max_attempts: u32,
        /// Backoff delay.
        delay_ms: u64,
        /// Error that triggered the retry.
        error_message: String,
    },
    /// Automatic retries ended.
    #[serde(rename_all = "camelCase")]
    AutoRetryEnd {
        /// A retry succeeded.
        success: bool,
        /// Last attempt number.
        attempt: u32,
        /// Final error.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        final_error: Option<String>,
    },
    /// A summarisation retry is scheduled.
    #[serde(rename_all = "camelCase")]
    SummarizationRetryScheduled {
        /// Attempt number.
        attempt: u32,
        /// Retry budget.
        max_attempts: u32,
        /// Backoff delay.
        delay_ms: u64,
        /// Error that triggered the retry.
        error_message: String,
    },
    /// A summarisation retry attempt started.
    SummarizationRetryAttemptStart {
        /// What is being summarised.
        #[serde(flatten)]
        source: SummarizationSource,
    },
    /// Summarisation retries ended.
    SummarizationRetryFinished,
    /// Streaming output of a `!` command.
    BashExecutionUpdate {
        /// Caller-supplied id.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        id: Option<String>,
        /// Appended output.
        delta: String,
    },
}

impl AgentSessionEvent {
    /// Maps a loop event to its session event (`agent_end` needs `will_retry`).
    #[must_use]
    pub fn from_agent(event: AgentEvent, will_retry: bool) -> Self {
        match event {
            AgentEvent::AgentStart => Self::AgentStart,
            AgentEvent::AgentEnd { messages } => Self::AgentEnd {
                messages,
                will_retry,
            },
            AgentEvent::TurnStart => Self::TurnStart,
            AgentEvent::TurnEnd {
                message,
                tool_results,
            } => Self::TurnEnd {
                message,
                tool_results,
            },
            AgentEvent::MessageStart { message } => Self::MessageStart { message },
            AgentEvent::MessageUpdate {
                message,
                assistant_message_event,
            } => Self::MessageUpdate {
                message,
                assistant_message_event,
            },
            AgentEvent::MessageEnd { message } => Self::MessageEnd { message },
            AgentEvent::ToolExecutionStart {
                tool_call_id,
                tool_name,
                args,
            } => Self::ToolExecutionStart {
                tool_call_id,
                tool_name,
                args,
                parent_tool_call_id: None,
            },
            AgentEvent::ToolExecutionUpdate {
                tool_call_id,
                tool_name,
                args,
                partial_result,
            } => Self::ToolExecutionUpdate {
                tool_call_id,
                tool_name,
                args,
                partial_result,
                parent_tool_call_id: None,
            },
            AgentEvent::ToolExecutionEnd {
                tool_call_id,
                tool_name,
                result,
                is_error,
                duration_ms,
            } => Self::ToolExecutionEnd {
                tool_call_id,
                tool_name,
                result,
                is_error,
                duration_ms,
                parent_tool_call_id: None,
            },
        }
    }
}

/// Extension error as a client event (`extension_error`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExtensionErrorEvent {
    /// Extension id/path or a `<runtime>`-style marker.
    pub extension_path: String,
    /// Event or call that failed.
    pub event: String,
    /// Error text.
    pub error: String,
    /// Stack trace, when known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stack: Option<String>,
}

/// Why a session was replaced.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ReplaceReason {
    /// New session.
    New,
    /// Switched to another file.
    Resume,
    /// Forked from an entry.
    Fork,
    /// Cloned at the leaf.
    Clone,
    /// Imported JSONL.
    Import,
}

/// What changed the model.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ModelChangeSource {
    /// `set_model`.
    Set,
    /// Cycling.
    Cycle,
    /// Restored from the session or defaults.
    Restore,
    /// An extension.
    Extension,
}

/// Coarse run state for frontends.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RunState {
    /// Nothing runs.
    Idle,
    /// An agent run is active.
    Running,
    /// Compaction or branch summary.
    Compacting,
    /// Waiting before an automatic retry.
    Retrying,
    /// Idle, but a wait source reports work in flight.
    Waiting,
}

/// Why an extension was disabled for one session (X-TRAP, core spec ยง2.3).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ExtensionDisabledReason {
    /// The guest trapped.
    Trap,
    /// A Rust-side panic inside the instance call.
    Panic,
    /// Disabled explicitly (user toggle, process-level breaker).
    Disabled,
}

/// Oino client events (runtime ยง6.2).
#[allow(
    clippy::large_enum_variant,
    reason = "events are moved through channels one at a time"
)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum OinoEvent {
    /// The runtime replaced the session; clients reset view state.
    #[serde(rename_all = "camelCase")]
    SessionReplaced {
        /// New session file.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        session_file: Option<String>,
        /// New session id.
        session_id: String,
        /// Why.
        reason: ReplaceReason,
    },
    /// The selected model changed.
    #[serde(rename_all = "camelCase")]
    ModelChanged {
        /// Selected model.
        model: Model,
        /// Physical model under a virtual selection.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        routed_model: Option<Model>,
        /// What changed it.
        source: ModelChangeSource,
    },
    /// Coarse run state.
    #[serde(rename_all = "camelCase")]
    RunState {
        /// State.
        state: RunState,
        /// Wait reasons for `waiting`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        waiting_on: Option<Vec<String>>,
    },
    /// The active tools changed.
    ToolsChanged {
        /// Active tool names.
        active: Vec<String>,
    },
    /// Registered commands changed; refetch `get_commands`.
    CommandsChanged,
    /// A dialog closed (`extension_ui_dismiss`); other frontends close it too.
    ExtensionUiDismiss {
        /// Request id.
        id: String,
        /// Why it closed.
        reason: DismissReason,
    },
    /// Events were dropped for a slow subscriber.
    Lagged {
        /// Number of dropped events.
        dropped: u64,
    },
    /// A registry patch (`ui-protocol` ยง9.2): `{"type":"oino_ui_patch", โ€ฆUiPatch}`.
    /// Frontends apply the ops in order; `rev != last + 1` triggers `_oino/ui_resync`.
    #[serde(rename = "oino_ui_patch", rename_all = "camelCase")]
    UiPatch {
        /// Registry scope (`session` / `host`).
        scope: oino_ui::slot::Scope,
        /// Session id (session scope only).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        session_id: Option<String>,
        /// `previous + 1`.
        rev: u64,
        /// Ops, applied in order.
        ops: Vec<oino_ui::slot::RegistryOp>,
    },
    /// A bus topic the frontend subscribed to (`_oino/topics`) was published.
    Topic {
        /// Topic name.
        topic: String,
        /// Payload.
        data: serde_json::Value,
        /// Published sticky.
        sticky: bool,
        /// Publishing extension (`oino.core` for core topics).
        publisher: String,
    },
    /// The nested agents of the session tree changed (spawned, closed, state).
    AgentsChanged {
        /// Every open agent of the tree (`_oino/agents` shape).
        agents: Vec<crate::agents::AgentInfo>,
    },
    /// A client event of a nested agent (only while `_oino/agents{follow: true}`).
    #[serde(rename_all = "camelCase")]
    AgentEvent {
        /// Agent id (the child session id).
        agent_id: String,
        /// The child's event.
        event: Box<ClientEvent>,
    },
    /// An extension called `ctx.shutdown()`; the frontend exits once the session is idle.
    ShutdownRequested,
    /// An extension was disabled for one session after a trap or panic (X-TRAP): it stops
    /// dispatching for that session only; other sessions keep it. Frontends surface it as
    /// a notice ("Extension X crashed and was disabled for this session").
    #[serde(rename_all = "camelCase")]
    ExtensionDisabled {
        /// Session the extension is disabled for.
        session_id: String,
        /// Disabled extension id.
        extension_id: String,
        /// Why it was disabled.
        reason: ExtensionDisabledReason,
    },
    /// A session task crashed and was contained (X-PANIC): the run book was reset and the
    /// session stays usable; other sessions are unaffected. Frontends surface it as a
    /// notice and can re-prompt.
    #[serde(rename_all = "camelCase")]
    SessionCrashed {
        /// Panic message.
        error: String,
    },
    /// Another runner took the current session over (D-TAKEOVER): this runtime closed the
    /// session and released it; frontends show "Session moved to another window" and return
    /// to their session list / next session.
    #[serde(rename_all = "camelCase")]
    SessionTakenOver {
        /// Who took the session over.
        by: oino_session::LeaseInfo,
    },
    /// The hub evicted an idle session (E-LAZY): the session was disposed and its lease
    /// released; the record stays on disk and the next message re-opens and repairs it.
    /// Published on the session's stream before it ends โ€” only subscribers still attached
    /// see it (eviction requires none); the hub list is the source of truth.
    #[serde(rename_all = "camelCase")]
    SessionEvicted {
        /// Evicted session id.
        session_id: String,
    },
}

impl From<crate::topics::TopicValue> for OinoEvent {
    fn from(value: crate::topics::TopicValue) -> Self {
        Self::Topic {
            topic: value.topic,
            data: value.data,
            sticky: value.sticky,
            publisher: value.publisher,
        }
    }
}

impl From<oino_ui::slot::UiPatch> for OinoEvent {
    fn from(patch: oino_ui::slot::UiPatch) -> Self {
        Self::UiPatch {
            scope: patch.scope,
            session_id: patch.session_id,
            rev: patch.rev,
            ops: patch.ops,
        }
    }
}

impl OinoEvent {
    /// The registry patch this event carries (`oino_ui_patch`), if any.
    #[must_use]
    pub fn ui_patch(&self) -> Option<oino_ui::slot::UiPatch> {
        match self {
            Self::UiPatch {
                scope,
                session_id,
                rev,
                ops,
            } => Some(oino_ui::slot::UiPatch {
                scope: *scope,
                session_id: session_id.clone(),
                rev: *rev,
                ops: ops.clone(),
            }),
            _ => None,
        }
    }
}

/// Every event a client receives, in one ordered stream.
#[allow(
    clippy::large_enum_variant,
    reason = "events are moved through channels one at a time"
)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ClientEvent {
    /// Session event.
    Session(AgentSessionEvent),
    /// Extension UI request (`extension_ui_request`).
    Ui(UiRequest),
    /// Extension failure (`extension_error`).
    ExtensionError(TaggedExtensionError),
    /// Oino addition.
    Oino(OinoEvent),
}

/// [`ExtensionErrorEvent`] with its `type: "extension_error"` tag.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename = "extension_error")]
pub struct TaggedExtensionError {
    /// The error.
    #[serde(flatten)]
    pub error: ExtensionErrorEvent,
}

impl From<AgentSessionEvent> for ClientEvent {
    fn from(event: AgentSessionEvent) -> Self {
        Self::Session(event)
    }
}

impl From<OinoEvent> for ClientEvent {
    fn from(event: OinoEvent) -> Self {
        Self::Oino(event)
    }
}

impl From<ExtensionErrorEvent> for ClientEvent {
    fn from(error: ExtensionErrorEvent) -> Self {
        Self::ExtensionError(TaggedExtensionError { error })
    }
}

/// Serialises tool results as `{"role":"toolResult",โ€ฆ}`.
mod tagged_tool_results {
    use oino_ai::{AgentMessage, ToolResultMessage};
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    pub(super) fn serialize<S: Serializer>(
        results: &[ToolResultMessage],
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        let tagged: Vec<AgentMessage> = results
            .iter()
            .cloned()
            .map(AgentMessage::ToolResult)
            .collect();
        tagged.serialize(serializer)
    }

    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Vec<ToolResultMessage>, D::Error> {
        let values = Vec::<serde_json::Value>::deserialize(deserializer)?;
        values
            .into_iter()
            .map(|mut value| {
                if let Some(object) = value.as_object_mut() {
                    object.shift_remove("role");
                }
                serde_json::from_value(value).map_err(serde::de::Error::custom)
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn wire_shapes() {
        let event = ClientEvent::Session(AgentSessionEvent::SummarizationRetryAttemptStart {
            source: SummarizationSource::Compaction {
                reason: CompactionReason::Overflow,
            },
        });
        assert_eq!(
            serde_json::to_value(&event).unwrap(),
            json!({"type":"summarization_retry_attempt_start","source":"compaction","reason":"overflow"})
        );
        let error: ClientEvent = ExtensionErrorEvent {
            extension_path: "x".into(),
            event: "input".into(),
            error: "boom".into(),
            stack: None,
        }
        .into();
        assert_eq!(
            serde_json::to_value(&error).unwrap(),
            json!({"type":"extension_error","extensionPath":"x","event":"input","error":"boom"})
        );
        assert_eq!(
            serde_json::to_value(ClientEvent::Session(AgentSessionEvent::QueueUpdate {
                steering: vec!["a".into()],
                follow_up: vec![]
            }))
            .unwrap(),
            json!({"type":"queue_update","steering":["a"],"followUp":[]})
        );
        let disabled: ClientEvent = OinoEvent::ExtensionDisabled {
            session_id: "s1".into(),
            extension_id: "acme.x".into(),
            reason: ExtensionDisabledReason::Trap,
        }
        .into();
        assert_eq!(
            serde_json::to_value(&disabled).unwrap(),
            json!({"type":"extension_disabled","sessionId":"s1","extensionId":"acme.x","reason":"trap"})
        );
        let crashed: ClientEvent = OinoEvent::SessionCrashed {
            error: "boom".into(),
        }
        .into();
        assert_eq!(
            serde_json::to_value(&crashed).unwrap(),
            json!({"type":"session_crashed","error":"boom"})
        );
        let evicted: ClientEvent = OinoEvent::SessionEvicted {
            session_id: "s1".into(),
        }
        .into();
        assert_eq!(
            serde_json::to_value(&evicted).unwrap(),
            json!({"type":"session_evicted","sessionId":"s1"})
        );
    }
}