meerkat-core 0.8.31

Foundational agent contracts, config, and runtime-neutral logic for Meerkat
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
//! Typed realtime transcript append seam.
//!
//! Provider adapters translate provider-native realtime events into these
//! identity-bearing events. Generated session realtime transcript authority owns
//! idempotency, causal ordering, and canonical transcript materialization.

use serde::{Deserialize, Serialize};

use crate::blob::BlobId;
use crate::types::{ContentBlock, StopReason};

/// WholeBlob/0.8.10 metadata key for the accumulated realtime reducer
/// projection.
///
/// HeadCanonical persistence never writes this value into its compact head;
/// it stores authenticated typed component-event rows and binds their prefix
/// authority instead.
pub const SESSION_REALTIME_TRANSCRIPT_STATE_KEY: &str = "realtime_transcript_state";

/// Provider-neutral role for a realtime transcript item.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RealtimeTranscriptRole {
    User,
    Assistant,
}

/// Output lane carried by an assistant realtime transcript item.
///
/// T9/T10: distinguishes display text (authored output the model writes,
/// e.g. OpenAI realtime `response.output_text.delta`) from spoken transcript
/// (text derived from audio output, e.g. `response.output_audio_transcript.*`).
/// The generated realtime transcript authority dispatches on this to flush
/// either [`crate::types::AssistantBlock::Text`]
/// (for `Display`) or [`crate::types::AssistantBlock::Transcript`] with
/// `source: TranscriptSource::Spoken` (for `Spoken`).
///
/// `Display` is the default for items that arrive only via
/// [`RealtimeTranscriptEvent::AssistantTextDelta`]; an item is upgraded to
/// `Spoken` the first time an [`RealtimeTranscriptEvent::AssistantTranscriptDelta`]
/// fragment arrives for it. Mixed-lane content on the same `item_id` is not
/// expected from any provider today; if observed the **first** lane wins
/// (the materializer cannot retroactively re-classify a partially-flushed
/// item) and a `tracing::warn!` is emitted.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default,
)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum TranscriptLane {
    #[default]
    Display,
    Spoken,
}

/// Durable identity binding for one committed non-text user input.
///
/// Live image callers retry with a session-scoped `idempotency_key`. The binding is
/// persisted independently of provider connection state so receipt loss and
/// reconnect cannot duplicate canonical content, while reuse with a different
/// fingerprint can fail closed before provider send.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RealtimeUserContentIdentity {
    pub idempotency_key: String,
    pub item_id: String,
    pub previous_item_id: Option<String>,
    pub content_index: u32,
    pub blob_id: BlobId,
    pub media_type: String,
}

/// One-slot durable recovery anchor for a non-text user input whose blob and
/// reducer commit are not yet known to be jointly durable.
///
/// This record deliberately contains identity only. Inline bytes remain in
/// the caller retry and realm blob store; they never enter session metadata.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PendingRealtimeUserContentBlob {
    pub idempotency_key: String,
    pub item_id: String,
    pub previous_item_id: Option<String>,
    pub content_index: u32,
    pub blob_id: BlobId,
    pub media_type: String,
}

impl PendingRealtimeUserContentBlob {
    #[must_use]
    pub fn identity(&self) -> RealtimeUserContentIdentity {
        RealtimeUserContentIdentity {
            idempotency_key: self.idempotency_key.clone(),
            item_id: self.item_id.clone(),
            previous_item_id: self.previous_item_id.clone(),
            content_index: self.content_index,
            blob_id: self.blob_id.clone(),
            media_type: self.media_type.clone(),
        }
    }

    #[must_use]
    pub fn canonical_event(&self) -> RealtimeTranscriptEvent {
        RealtimeTranscriptEvent::UserContentFinal {
            idempotency_key: self.idempotency_key.clone(),
            item_id: self.item_id.clone(),
            previous_item_id: self.previous_item_id.clone(),
            content_index: self.content_index,
            content: vec![ContentBlock::Image {
                media_type: self.media_type.clone(),
                data: crate::types::ImageData::Blob {
                    blob_id: self.blob_id.clone(),
                },
            }],
        }
    }

    #[must_use]
    pub fn matches_identity(&self, identity: &RealtimeUserContentIdentity) -> bool {
        self.identity() == *identity
    }
}

/// Durable rejection marker for a caller-stable user-content key whose
/// canonical content was removed by a same-session transcript rewrite.
///
/// Tombstones are intentionally retained instead of deleting the old binding:
/// a retry carrying the removed key must fail closed before provider send and
/// must never manufacture an `AlreadyCommitted` receipt for content that is no
/// longer present in the canonical message projection.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct RealtimeUserContentTombstone {
    pub idempotency_key: String,
}

/// A typed, identity-bearing realtime transcript event consumed by the session.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum RealtimeTranscriptEvent {
    /// Observe a provider item and its causal predecessor without committing
    /// content yet.
    ItemObserved {
        item_id: String,
        previous_item_id: Option<String>,
        role: RealtimeTranscriptRole,
        response_id: Option<String>,
    },
    /// Observe a provider item that participates in provider causal ordering
    /// but must not materialize transcript content.
    ItemSkipped {
        item_id: String,
        previous_item_id: Option<String>,
    },
    /// Provider finalized the transcript for a user input item.
    UserTranscriptFinal {
        item_id: String,
        previous_item_id: Option<String>,
        content_index: u32,
        text: String,
    },
    /// Provider accepted a non-text user content segment into its
    /// conversation. Unlike [`Self::ItemObserved`], this event carries the
    /// canonical Meerkat content that must be durably materialized. The
    /// identity-bearing realtime transcript authority owns deduplication and
    /// causal ordering exactly as it does for [`Self::UserTranscriptFinal`].
    ///
    /// Image bytes may be inline at the live adapter seam; persistent session
    /// services externalize them into the realm blob store before reducer
    /// application so causally waiting segments never place bytes in durable
    /// transcript metadata.
    #[cfg_attr(feature = "schema", schemars(skip))]
    UserContentFinal {
        /// Caller-stable, session-scoped idempotency identity.
        idempotency_key: String,
        item_id: String,
        previous_item_id: Option<String>,
        content_index: u32,
        content: Vec<ContentBlock>,
    },
    /// Provider emitted an assistant **display-text** delta for an output
    /// item — authored text the model writes (e.g. OpenAI realtime
    /// `response.output_text.delta`).
    ///
    /// Materializes as [`crate::types::AssistantBlock::Text`].
    AssistantTextDelta {
        response_id: String,
        delta_id: String,
        item_id: String,
        previous_item_id: Option<String>,
        content_index: u32,
        delta: String,
    },
    /// Provider emitted an assistant **spoken-transcript** delta for an
    /// output item — text derived from audio output (e.g. OpenAI realtime
    /// `response.output_audio_transcript.delta`).
    ///
    /// Identity shape mirrors [`Self::AssistantTextDelta`] so generated
    /// idempotent ordering / staging authority owns dedup uniformly across
    /// lanes. Materializes as [`crate::types::AssistantBlock::Transcript`]
    /// with `source: TranscriptSource::Spoken` (T9/T10).
    AssistantTranscriptDelta {
        response_id: String,
        delta_id: String,
        item_id: String,
        previous_item_id: Option<String>,
        content_index: u32,
        delta: String,
    },
    /// Provider reported the assistant output item was truncated to a playback
    /// transcript prefix. This is not evidence of biological hearing.
    AssistantTranscriptTruncated {
        response_id: String,
        item_id: String,
        content_index: u32,
        text: String,
    },
    /// R5-7: provider supplied authoritative final transcript text for an
    /// assistant output item, overriding any incomplete delta accumulation.
    ///
    /// Necessary for two cases:
    ///   1. Final-only providers that emit a single `AssistantTranscriptFinal`
    ///      observation without prior deltas.
    ///   2. Recovery from delta loss (R5-1: lossy media lane back-pressure
    ///      may drop transcript deltas; the final's text is the authoritative
    ///      reconciliation).
    ///
    /// The materializer locates the staged item by
    /// `(response_id, item_id, content_index)`, replaces its accumulated
    /// content with `text`, and (if no item is staged yet) creates one on
    /// the spoken lane. Flush still happens via `AssistantTurnCompleted`;
    /// this variant only updates the staged content.
    AssistantTranscriptFinalText {
        response_id: String,
        item_id: String,
        content_index: u32,
        text: String,
    },
    /// Admit the exact channel/response/item identity of the foreground
    /// assistant output before any playback terminal can resolve it. The
    /// interaction identity is minted once by the session owner when this
    /// target first appears and is reused for every later playback report.
    AssistantPlaybackTargetAdmitted {
        channel_id: String,
        interaction_id: crate::InteractionId,
        response_id: String,
        item_id: String,
        content_index: u32,
    },
    /// Persist the exact playback terminal fact after generated authority has
    /// accepted it while provider final text is still absent. This is a raw
    /// recovery carrier, not a canonical transcript or hearing claim.
    #[cfg_attr(feature = "schema", schemars(skip))]
    AssistantPlaybackTerminalObserved {
        channel_id: String,
        interaction_id: crate::InteractionId,
        response_id: String,
        item_id: String,
        content_index: u32,
        evidence: crate::LiveAssistantPlaybackEvidence,
        stop_reason: StopReason,
        usage: crate::types::TurnUsage,
    },
    /// Consume the exact one-use playback target after generated terminal
    /// authority has resolved it. Exact replay is rejected so stale browser
    /// reports cannot affect a later assistant turn.
    AssistantPlaybackTargetResolved {
        channel_id: String,
        interaction_id: crate::InteractionId,
        response_id: String,
        item_id: String,
        content_index: u32,
    },
    /// Provider turn reached a terminal boundary. The session decides which
    /// staged assistant items, if any, are now canonical.
    AssistantTurnCompleted {
        response_id: String,
        stop_reason: StopReason,
        usage: crate::types::TurnUsage,
    },
    /// Provider turn was interrupted before terminal materialization.
    AssistantTurnInterrupted { response_id: String },
}

/// Durable session-owned correlation for one foreground assistant playback
/// target. Fields are read-only outside core so surfaces can resolve but not
/// manufacture the semantic identity.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LiveAssistantPlaybackTarget {
    channel_id: String,
    interaction_id: crate::InteractionId,
    response_id: String,
    item_id: String,
    content_index: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) pending_terminal: Option<LiveAssistantPlaybackPendingTerminal>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LiveAssistantPlaybackPendingTerminal {
    pub(crate) evidence: crate::LiveAssistantPlaybackEvidence,
    pub(crate) stop_reason: StopReason,
    pub(crate) usage: crate::types::TurnUsage,
}

impl LiveAssistantPlaybackTarget {
    pub(crate) fn admitted(
        channel_id: String,
        interaction_id: crate::InteractionId,
        response_id: String,
        item_id: String,
        content_index: u32,
    ) -> Self {
        Self {
            channel_id,
            interaction_id,
            response_id,
            item_id,
            content_index,
            pending_terminal: None,
        }
    }

    #[must_use]
    pub fn channel_id(&self) -> &str {
        &self.channel_id
    }

    #[must_use]
    pub const fn interaction_id(&self) -> crate::InteractionId {
        self.interaction_id
    }

    #[must_use]
    pub fn response_id(&self) -> &str {
        &self.response_id
    }

    #[must_use]
    pub fn item_id(&self) -> &str {
        &self.item_id
    }

    #[must_use]
    pub const fn content_index(&self) -> u32 {
        self.content_index
    }

    #[must_use]
    pub fn pending_terminal(&self) -> Option<&LiveAssistantPlaybackPendingTerminal> {
        self.pending_terminal.as_ref()
    }
}

impl LiveAssistantPlaybackPendingTerminal {
    #[must_use]
    pub fn evidence(&self) -> &crate::LiveAssistantPlaybackEvidence {
        &self.evidence
    }

    #[must_use]
    pub const fn stop_reason(&self) -> StopReason {
        self.stop_reason
    }

    #[must_use]
    pub fn usage(&self) -> &crate::types::TurnUsage {
        &self.usage
    }
}

/// Typed staged-transcript append seam (#51).
///
/// Provider adapters that stage a transcript item before it is committed —
/// e.g. the OpenAI realtime adapter's explicit-commit text-input path, which
/// accepts a user text item via `send_input` while the turn is open and holds
/// it until `commit_turn_with_modality` — lower the staged turn into this typed
/// input rather than an adapter-local `Vec`. Lowering the staged turn makes it a
/// machine-owned fact (the generated `MeerkatMachine` emits
/// `RealtimeTranscriptAppended` when this is applied), so a committed turn proves
/// a real staged turn and the staged set survives a crash/cancel between stage
/// and commit instead of living only in adapter memory.
///
/// `item_id` is the opaque synthetic provider item id (the same id sent to the
/// provider via `ConversationItemCreate` and reused on
/// [`RealtimeTranscriptEvent`]); `text` is the staged content; `role` and `lane`
/// are the typed classifiers the generated transcript authority dispatches on.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AppendRealtimeTranscript {
    /// Opaque synthetic provider item id for the staged turn.
    pub item_id: String,
    /// Staged transcript content.
    pub text: String,
    /// Provider-neutral role of the staged item.
    pub role: RealtimeTranscriptRole,
    /// Output lane the staged content belongs to.
    pub lane: TranscriptLane,
}

/// Canonical message materialized by applying a realtime transcript event.
#[derive(Debug, Clone, PartialEq)]
pub enum RealtimeTranscriptMaterializedMessage {
    User {
        item_id: String,
        text: String,
    },
    Assistant {
        item_id: String,
        response_id: String,
        text: String,
        stop_reason: StopReason,
        usage: Option<crate::types::TurnUsage>,
        /// T9/T10: which output lane the staged content arrived on.
        /// Drives whether the materializer flushes
        /// [`crate::types::AssistantBlock::Text`] (Display) or
        /// [`crate::types::AssistantBlock::Transcript`] with
        /// `source: TranscriptSource::Spoken` (Spoken).
        lane: TranscriptLane,
    },
}

/// Result of applying a realtime transcript event.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct RealtimeTranscriptApplyOutcome {
    pub materialized_messages: Vec<RealtimeTranscriptMaterializedMessage>,
    /// Persistence-backed user-content receipt authority. Present only after
    /// canonical materialization or exact replay of an already committed key.
    pub user_content: Option<RealtimeUserContentApplyOutcome>,
}

/// Canonical result of applying a caller-stable non-text user input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RealtimeUserContentApplyOutcome {
    Committed(RealtimeUserContentIdentity),
    AlreadyCommitted(RealtimeUserContentIdentity),
    /// The caller identity is malformed. This is an expected typed rejection,
    /// not durable-state corruption.
    RejectedInvalidIdentity {
        idempotency_key: String,
    },
    /// The provider item depends on a predecessor that is not canonical yet.
    RejectedUnmaterializedPredecessor {
        idempotency_key: String,
        previous_item_id: Option<String>,
    },
    /// The key is already bound to a different canonical payload.
    RejectedConflict {
        idempotency_key: String,
    },
}

impl RealtimeTranscriptApplyOutcome {
    #[must_use]
    pub fn is_inert(&self) -> bool {
        self.materialized_messages.is_empty() && self.user_content.is_none()
    }
}