meerkat-mobkit 0.8.28

Companion orchestration platform for the Meerkat multi-agent runtime
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
//! Application-facing live channel contracts.
//!
//! Meerkat owns live execution semantics. This module only owns MobKit's
//! versioned request envelope, feature negotiation atom, and SDK-facing
//! channel handle. The experimental execution identity capability is not
//! advertised until the host admission and upstream orchestration seams are
//! available.

use std::fmt;

use meerkat_contracts::{
    LiveOpenResult, WireLiveChannelCapabilities, WireLiveContinuityMode, WireLiveTransportBootstrap,
};
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;

/// Capability required before a client may send `execution_identity`.
///
/// Kept as MobKit's local wire atom until the minimum published Meerkat
/// dependency exports the matching constant. Experimental builds verify the
/// same value through the upstream qualified capability projection.
pub const LIVE_EXECUTION_IDENTITY_V1: &str = "live.execution_identity.v1";

/// Dormant compatibility vocabulary for provider-neutral FunctionBridge.
///
/// Production advertisement remains fail-closed until Meerkat qualifies the
/// direct raw function-call and settlement lifecycle.
pub const LIVE_EXECUTION_FUNCTION_BRIDGE_V1: &str = "live.execution.function_bridge.v1";

/// Catalog-qualified execution through provider client-context delegation.
pub const LIVE_EXECUTION_CLIENT_CONTEXT_V1: &str = "live.execution.client_context.v1";

/// Provider-neutral execution mode resolved from the selected model profile.
///
/// This vocabulary is output-only. A live-open caller selects a catalog model,
/// never a provider-native delegation mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LiveExecutionMode {
    FunctionBridge,
    ClientContext,
}

impl LiveExecutionMode {
    #[must_use]
    pub const fn capability(self) -> &'static str {
        match self {
            Self::FunctionBridge => LIVE_EXECUTION_FUNCTION_BRIDGE_V1,
            Self::ClientContext => LIVE_EXECUTION_CLIENT_CONTEXT_V1,
        }
    }
}

/// Exact version discriminator carried inside the v1 request envelope.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LiveExecutionIdentityVersion {
    V1,
}

/// A forward-compatible feature capability advertised by `mobkit/capabilities`.
///
/// The newtype keeps capability lists typed without rejecting future feature
/// names that an older client does not yet understand.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct FeatureCapability(String);

impl<'de> Deserialize<'de> for FeatureCapability {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        if value.is_empty() {
            return Err(D::Error::custom("feature capability must be non-empty"));
        }
        Ok(Self(value))
    }
}

impl FeatureCapability {
    pub fn new(value: impl Into<String>) -> Result<Self, &'static str> {
        let value = value.into();
        if value.is_empty() {
            return Err("feature capability must be non-empty");
        }
        Ok(Self(value))
    }

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

    #[must_use]
    pub fn live_execution_identity_v1() -> Self {
        Self(LIVE_EXECUTION_IDENTITY_V1.to_string())
    }

    #[must_use]
    pub fn live_execution_function_bridge_v1() -> Self {
        Self(LIVE_EXECUTION_FUNCTION_BRIDGE_V1.to_string())
    }

    #[must_use]
    pub fn live_execution_client_context_v1() -> Self {
        Self(LIVE_EXECUTION_CLIENT_CONTEXT_V1.to_string())
    }
}

fn deserialize_non_empty_string<'de, D>(deserializer: D) -> Result<String, D::Error>
where
    D: Deserializer<'de>,
{
    let value = String::deserialize(deserializer)?;
    if value.trim().is_empty() {
        return Err(D::Error::custom("value must be a non-empty string"));
    }
    Ok(value)
}

/// Version 1 host-registered channel execution profile selection.
///
/// Provider, model, auth binding, provider mode, tools, and instructions stay
/// host-owned. This request changes only the opened live channel and never
/// mutates durable member or session identity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LiveExecutionIdentityV1 {
    pub version: LiveExecutionIdentityVersion,
    /// Stable host-registered profile identity. Provider mode, tools, and
    /// approved top-level GPT Live session instructions remain behind this
    /// catalog selection and cannot be supplied as raw open parameters.
    #[serde(deserialize_with = "deserialize_non_empty_string")]
    pub profile_id: String,
}

/// SDK/API handle returned by a successful live open.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LiveChannelHandle {
    pub channel_id: String,
    pub target_identity: String,
    pub transport: WireLiveTransportBootstrap,
    pub capabilities: WireLiveChannelCapabilities,
    pub continuity: WireLiveContinuityMode,
}

/// Pending experimental live channel returned before media activation.
///
/// The receipt is opaque phase custody for the exact current binding. It is
/// not reconstructed from `channel_id` and is never a provider identifier.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PendingLiveChannelHandle {
    #[serde(deserialize_with = "deserialize_non_empty_string")]
    pub channel_id: String,
    #[serde(deserialize_with = "deserialize_non_empty_string")]
    pub target_identity: String,
    pub execution_mode: LiveExecutionMode,
    #[serde(deserialize_with = "deserialize_non_empty_string")]
    pub pending_receipt: String,
    pub transport: WireLiveTransportBootstrap,
    pub capabilities: WireLiveChannelCapabilities,
    pub continuity: WireLiveContinuityMode,
}

impl PendingLiveChannelHandle {
    #[must_use]
    pub fn new(
        target_identity: impl Into<String>,
        execution_mode: LiveExecutionMode,
        pending_receipt: impl Into<String>,
        result: LiveOpenResult,
    ) -> Self {
        Self {
            channel_id: result.channel_id,
            target_identity: target_identity.into(),
            execution_mode,
            pending_receipt: pending_receipt.into(),
            transport: result.transport,
            capabilities: result.capabilities,
            continuity: result.continuity,
        }
    }
}

/// Active experimental live channel minted only after generated activation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ActiveLiveChannelHandle {
    #[serde(deserialize_with = "deserialize_non_empty_string")]
    pub channel_id: String,
    #[serde(deserialize_with = "deserialize_non_empty_string")]
    pub target_identity: String,
    pub execution_mode: LiveExecutionMode,
    #[serde(deserialize_with = "deserialize_non_empty_string")]
    pub activation_receipt: String,
}

/// Generated playback-owner readiness for one exact pending binding.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LivePlaybackOwnerReadiness {
    #[serde(deserialize_with = "deserialize_non_empty_string")]
    pub channel_id: String,
    #[serde(deserialize_with = "deserialize_non_empty_string")]
    pub readiness_receipt: String,
}

/// Strict phase projection returned by experimental live status.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "phase", rename_all = "snake_case", deny_unknown_fields)]
pub enum ExperimentalLiveChannelStatus {
    Pending,
    Active { handle: ActiveLiveChannelHandle },
    Revoked,
    Closed,
}

impl LiveChannelHandle {
    #[must_use]
    pub fn from_open_result(target_identity: impl Into<String>, result: LiveOpenResult) -> Self {
        Self {
            channel_id: result.channel_id,
            target_identity: target_identity.into(),
            transport: result.transport,
            capabilities: result.capabilities,
            continuity: result.continuity,
        }
    }
}

/// Why an experimental live channel needs a fresh signaling bootstrap.
///
/// The reason remains typed because canonical-context ambiguity and
/// delegation-result ambiguity carry different recovery authority upstream.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LiveReplacementReason {
    CanonicalContext,
    DelegationResult,
}

/// Strict result of the retryable `mobkit/live/replacement_required` read.
///
/// Construction is private so `required = false` cannot accidentally carry a
/// bootstrap and `required = true` cannot omit one. The wire remains a plain
/// object for Python and TypeScript SDK parity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct LiveReplacementRequiredResult {
    required: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    reason: Option<LiveReplacementReason>,
    #[serde(skip_serializing_if = "Option::is_none")]
    replacement: Option<LiveChannelHandle>,
    #[serde(skip_serializing_if = "Option::is_none")]
    canonical_seed_cursor: Option<u64>,
}

impl LiveReplacementRequiredResult {
    #[must_use]
    pub fn not_required() -> Self {
        Self {
            required: false,
            reason: None,
            replacement: None,
            canonical_seed_cursor: None,
        }
    }

    #[must_use]
    pub fn required(
        reason: LiveReplacementReason,
        replacement: LiveChannelHandle,
        canonical_seed_cursor: u64,
    ) -> Self {
        Self {
            required: true,
            reason: Some(reason),
            replacement: Some(replacement),
            canonical_seed_cursor: Some(canonical_seed_cursor),
        }
    }

    #[must_use]
    pub fn is_required(&self) -> bool {
        self.required
    }

    #[must_use]
    pub fn reason(&self) -> Option<LiveReplacementReason> {
        self.reason
    }

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

    #[must_use]
    pub fn canonical_seed_cursor(&self) -> Option<u64> {
        self.canonical_seed_cursor
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LiveExecutionIdentityContractError {
    InvalidEnvelope(String),
    LegacyFieldConflict(&'static str),
    InvalidExperimentalTarget(&'static str),
    ProviderNativeField(&'static str),
}

impl fmt::Display for LiveExecutionIdentityContractError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidEnvelope(detail) => {
                write!(f, "invalid execution_identity: {detail}")
            }
            Self::LegacyFieldConflict(field) => write!(
                f,
                "execution_identity conflicts with legacy top-level `{field}`"
            ),
            Self::InvalidExperimentalTarget(detail) => {
                write!(f, "invalid experimental live target: {detail}")
            }
            Self::ProviderNativeField(field) => write!(
                f,
                "experimental live/open does not accept provider-native `{field}`"
            ),
        }
    }
}

impl std::error::Error for LiveExecutionIdentityContractError {}

/// Parse and validate the optional execution identity portion of live/open.
///
/// This intentionally validates only the new nested field. Existing live
/// params remain owned by the upstream live-open contract while MobKit is
/// converging on the shared orchestrator.
pub fn parse_live_open_execution_identity(
    params: &Value,
) -> Result<Option<LiveExecutionIdentityV1>, LiveExecutionIdentityContractError> {
    let Some(object) = params.as_object() else {
        return Ok(None);
    };
    let Some(raw) = object.get("execution_identity") else {
        return Ok(None);
    };
    if object.contains_key("model") {
        return Err(LiveExecutionIdentityContractError::LegacyFieldConflict(
            "model",
        ));
    }
    if object.contains_key("provider") {
        return Err(LiveExecutionIdentityContractError::LegacyFieldConflict(
            "provider",
        ));
    }
    serde_json::from_value(raw.clone())
        .map(Some)
        .map_err(|error| LiveExecutionIdentityContractError::InvalidEnvelope(error.to_string()))
}

/// Validate the surface-only portion of strict experimental live targeting.
///
/// Authoritative identity resolution and stale-binding rejection remain in
/// the identity runtime. This function prevents compatibility target fields or
/// provider-native configuration from entering that resolution path.
pub fn validate_experimental_live_open_surface(
    params: &Value,
) -> Result<(), LiveExecutionIdentityContractError> {
    validate_experimental_live_target_surface(params)?;
    let object = params.as_object().ok_or(
        LiveExecutionIdentityContractError::InvalidExperimentalTarget("params must be an object"),
    )?;
    for field in [
        "mode",
        "execution_mode",
        "profile",
        "profile_id",
        "execution_profile",
        "execution_profile_id",
        "delegation",
        "delegation_type",
        "delegation_model",
        "responses",
        "responses_model",
        "responses_tools",
        "responses_instructions",
        "bridge_model",
        "bridge_tools",
        "bridge_instructions",
        "auth_binding",
        "self_hosted_server_id",
        "provider_params",
        "tools",
        "instructions",
    ] {
        if object.contains_key(field) {
            return Err(LiveExecutionIdentityContractError::ProviderNativeField(
                field,
            ));
        }
    }
    Ok(())
}

/// Validate the identity-only target carried by every strict channel handle
/// operation. The string is only a lookup claim; RPC resolution must still
/// prove its current durable lifecycle binding and exact session ownership.
pub fn validate_experimental_live_target_surface(
    params: &Value,
) -> Result<(), LiveExecutionIdentityContractError> {
    let Some(object) = params.as_object() else {
        return Err(
            LiveExecutionIdentityContractError::InvalidExperimentalTarget(
                "params must be an object",
            ),
        );
    };
    let identity = object
        .get("identity")
        .and_then(Value::as_str)
        .filter(|identity| !identity.trim().is_empty());
    let Some(identity) = identity else {
        return Err(
            LiveExecutionIdentityContractError::InvalidExperimentalTarget(
                "exactly one non-empty identity is required",
            ),
        );
    };
    if object.contains_key("member_id") || object.contains_key("session_id") {
        return Err(
            LiveExecutionIdentityContractError::InvalidExperimentalTarget(
                "member_id and session_id are not eligible",
            ),
        );
    }
    if crate::member_comms_id::is_reserved_generated_alias(identity) {
        return Err(
            LiveExecutionIdentityContractError::InvalidExperimentalTarget(
                "runtime member aliases are not eligible",
            ),
        );
    }
    Ok(())
}