meerkat-core 0.8.8

Core agent logic for Meerkat (no I/O deps)
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
use crate::tool_execution::ToolExecutionContract;
use crate::types::{ToolDef, ToolProvenance, ToolSourceKind};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

pub const DEFERRED_CATALOG_TOOL_COUNT_THRESHOLD: usize = 2;
pub const DEFERRED_CATALOG_SCHEMA_VOLUME_THRESHOLD: usize = 160;

/// Which projection plane a catalog entry belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolPlaneClass {
    Session,
    Control,
}

/// Whether a session should keep deferred tools inline or expose a deferred catalog.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ToolCatalogMode {
    #[default]
    Inline,
    Deferred,
}

/// Whether a catalog entry may be deferred behind the control plane.
///
/// Deferred eligibility carries the typed provenance owner directly. The
/// string witness key is a read-only projection obtained on demand via
/// [`stable_owner_key_from_provenance`], never stored beside the owner.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolCatalogDeferredEligibility {
    InlineOnly,
    DeferredEligible { provenance: ToolProvenance },
}

/// Precedence-resolved catalog entry for one canonical tool name.
///
/// Entries represent the canonical winner for a tool identity even when that
/// tool is not currently callable. Policy-hidden names and collision losers are
/// omitted from the catalog entirely.
#[derive(Debug, Clone)]
pub struct ToolCatalogEntry {
    pub tool: Arc<ToolDef>,
    pub plane: ToolPlaneClass,
    pub callability: ToolCallability,
    pub deferred_eligibility: ToolCatalogDeferredEligibility,
    pub execution: ToolExecutionContract,
}

impl ToolCatalogEntry {
    pub fn session_inline(tool: Arc<ToolDef>, currently_callable: bool) -> Self {
        Self::session_inline_with_callability(tool, ToolCallability::from_bool(currently_callable))
    }

    pub fn session_inline_with_callability(
        tool: Arc<ToolDef>,
        callability: ToolCallability,
    ) -> Self {
        Self {
            tool,
            plane: ToolPlaneClass::Session,
            callability,
            deferred_eligibility: ToolCatalogDeferredEligibility::InlineOnly,
            execution: ToolExecutionContract::default(),
        }
    }

    pub fn control_inline(tool: Arc<ToolDef>, currently_callable: bool) -> Self {
        Self::control_inline_with_callability(tool, ToolCallability::from_bool(currently_callable))
    }

    pub fn control_inline_with_callability(
        tool: Arc<ToolDef>,
        callability: ToolCallability,
    ) -> Self {
        Self {
            tool,
            plane: ToolPlaneClass::Control,
            callability,
            deferred_eligibility: ToolCatalogDeferredEligibility::InlineOnly,
            execution: ToolExecutionContract::default(),
        }
    }

    pub fn session_deferred(
        tool: Arc<ToolDef>,
        currently_callable: bool,
        provenance: ToolProvenance,
    ) -> Self {
        Self::session_deferred_with_callability(
            tool,
            ToolCallability::from_bool(currently_callable),
            provenance,
        )
    }

    pub fn session_deferred_with_callability(
        tool: Arc<ToolDef>,
        callability: ToolCallability,
        provenance: ToolProvenance,
    ) -> Self {
        Self {
            tool,
            plane: ToolPlaneClass::Session,
            callability,
            deferred_eligibility: ToolCatalogDeferredEligibility::DeferredEligible { provenance },
            execution: ToolExecutionContract::default(),
        }
    }

    #[must_use]
    pub fn with_execution_contract(mut self, execution: ToolExecutionContract) -> Self {
        self.execution = execution;
        self
    }

    pub fn currently_callable(&self) -> bool {
        self.callability.is_callable()
    }
}

/// Typed reason that a catalog-owned tool cannot be called right now.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolUnavailableReason {
    NotCurrentlyCallable,
    NoPeersConfigured,
    RuntimeCommandAuthorityUnavailable,
    /// No dispatcher in this ownership chain implements the resolved
    /// Streaming or Detached execution mode.
    ExecutionModeOwnerUnavailable,
    /// The live routing owner no longer matches the owner captured during
    /// execution-plan resolution.
    ExecutionOwnerChanged,
    TemporarilyUnavailable,
}

impl std::fmt::Display for ToolUnavailableReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ToolUnavailableReason::NotCurrentlyCallable => {
                f.write_str("tool is not currently callable")
            }
            ToolUnavailableReason::NoPeersConfigured => f.write_str("no peers configured"),
            ToolUnavailableReason::RuntimeCommandAuthorityUnavailable => {
                f.write_str("runtime command authority unavailable")
            }
            ToolUnavailableReason::ExecutionModeOwnerUnavailable => {
                f.write_str("resolved execution mode owner unavailable")
            }
            ToolUnavailableReason::ExecutionOwnerChanged => {
                f.write_str("tool execution owner changed after plan resolution")
            }
            ToolUnavailableReason::TemporarilyUnavailable => {
                f.write_str("tool is temporarily unavailable")
            }
        }
    }
}

/// Catalog-owned callability for a tool identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "status", content = "reason")]
pub enum ToolCallability {
    Callable,
    Unavailable(ToolUnavailableReason),
}

impl ToolCallability {
    pub fn callable() -> Self {
        Self::Callable
    }

    pub fn unavailable(reason: ToolUnavailableReason) -> Self {
        Self::Unavailable(reason)
    }

    pub fn from_bool(currently_callable: bool) -> Self {
        if currently_callable {
            Self::Callable
        } else {
            Self::Unavailable(ToolUnavailableReason::NotCurrentlyCallable)
        }
    }

    pub fn is_callable(self) -> bool {
        matches!(self, Self::Callable)
    }

    pub fn unavailable_reason(self) -> Option<ToolUnavailableReason> {
        match self {
            Self::Callable => None,
            Self::Unavailable(reason) => Some(reason),
        }
    }
}

fn stable_tool_source_kind_key(kind: &ToolSourceKind) -> &'static str {
    match kind {
        ToolSourceKind::Builtin => "builtin",
        ToolSourceKind::Shell => "shell",
        ToolSourceKind::Comms => "comms",
        ToolSourceKind::Memory => "memory",
        ToolSourceKind::Schedule => "schedule",
        ToolSourceKind::WorkGraph => "workgraph",
        ToolSourceKind::Mob => "mob",
        ToolSourceKind::Callback => "callback",
        ToolSourceKind::Mcp => "mcp",
        ToolSourceKind::RustBundle => "rust_bundle",
    }
}

/// Stable witness key for a tool provenance owner.
pub fn stable_owner_key_from_provenance(provenance: &ToolProvenance) -> String {
    format!(
        "{}:{}",
        stable_tool_source_kind_key(&provenance.kind),
        provenance.source_id
    )
}

/// Stable witness key for a concrete tool definition.
pub fn stable_owner_key_for_tool(tool: &ToolDef) -> Option<String> {
    tool.provenance
        .as_ref()
        .map(stable_owner_key_from_provenance)
}

/// Dispatcher-level catalog support flags.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ToolCatalogCapabilities {
    /// True only when `tool_catalog()` is an exact precedence-resolved registry
    /// for this dispatcher.
    pub exact_catalog: bool,
    /// True when the dispatcher can dynamically require the deferred catalog
    /// control plane in the future, even if the current adaptive snapshot is
    /// still inline.
    pub may_require_catalog_control_plane: bool,
}

/// Count deferred-eligible session entries in a catalog snapshot.
pub fn deferred_session_entry_count(catalog: &[ToolCatalogEntry]) -> usize {
    catalog
        .iter()
        .filter(|entry| entry.plane == ToolPlaneClass::Session)
        .filter(|entry| {
            matches!(
                entry.deferred_eligibility,
                ToolCatalogDeferredEligibility::DeferredEligible { .. }
            )
        })
        .count()
}

/// Approximate schema/instruction footprint for deferred-eligible session entries.
pub fn deferred_session_schema_volume(catalog: &[ToolCatalogEntry]) -> usize {
    catalog
        .iter()
        .filter(|entry| entry.plane == ToolPlaneClass::Session)
        .filter(|entry| {
            matches!(
                entry.deferred_eligibility,
                ToolCatalogDeferredEligibility::DeferredEligible { .. }
            )
        })
        .map(|entry| {
            entry.tool.name.len()
                + entry.tool.description.len()
                + entry.tool.input_schema.to_string().len()
        })
        .sum()
}

/// Select inline vs deferred-catalog mode from the current exact catalog snapshot.
pub fn select_catalog_mode_from_snapshot(
    exact_catalog: bool,
    catalog: &[ToolCatalogEntry],
    pending_sources: &[String],
) -> ToolCatalogMode {
    if !exact_catalog {
        return ToolCatalogMode::Inline;
    }

    if !pending_sources.is_empty() {
        return ToolCatalogMode::Deferred;
    }

    let deferred_count = deferred_session_entry_count(catalog);
    if deferred_count == 0 {
        return ToolCatalogMode::Inline;
    }

    if deferred_count >= DEFERRED_CATALOG_TOOL_COUNT_THRESHOLD
        || deferred_session_schema_volume(catalog) >= DEFERRED_CATALOG_SCHEMA_VOLUME_THRESHOLD
    {
        ToolCatalogMode::Deferred
    } else {
        ToolCatalogMode::Inline
    }
}

fn is_false(value: &bool) -> bool {
    !*value
}

/// Canonical rejection reasons for deferred tool loads.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolCatalogLoadRejectedReason {
    UnknownKey,
    NotDeferredEligible,
    AlreadyRequested,
    NotFilterable,
    TemporarilyUnavailable,
}

/// Structured result for one requested catalog name.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct ToolCatalogLoadResolution {
    pub name: String,
    pub accepted: bool,
    #[serde(default, skip_serializing_if = "is_false")]
    pub accepted_noop: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rejected_reason: Option<ToolCatalogLoadRejectedReason>,
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::panic)]
mod tests {
    use super::*;
    use crate::{
        DetachedToolExecutionPolicy, IdempotencyScope, RestartClass, RunnerIdentity,
        ToolExecutionContract, ToolExecutionMode,
    };
    use std::collections::BTreeSet;
    use std::time::Duration;

    #[test]
    fn deferred_eligibility_owner_is_typed_provenance_with_projected_key() {
        let provenance = ToolProvenance {
            kind: ToolSourceKind::Callback,
            source_id: "owner-a".into(),
        };
        let tool = Arc::new(ToolDef::new(
            "deferred",
            "deferred tool",
            serde_json::json!({ "type": "object" }),
        ));
        let entry = ToolCatalogEntry::session_deferred(tool, true, provenance.clone());

        // The eligibility tag owns the typed provenance; the string key is a
        // read-only projection derived on demand, never a stored fact.
        let ToolCatalogDeferredEligibility::DeferredEligible { provenance: stored } =
            entry.deferred_eligibility
        else {
            panic!("session_deferred entry must be deferred eligible");
        };
        assert_eq!(stored, provenance);
        assert_eq!(
            stable_owner_key_from_provenance(&stored),
            "callback:owner-a"
        );
    }

    #[test]
    fn every_catalog_constructor_declares_fast_execution_by_default() {
        let tool = Arc::new(ToolDef::new(
            "fast",
            "fast tool",
            serde_json::json!({ "type": "object" }),
        ));

        for entry in [
            ToolCatalogEntry::session_inline(Arc::clone(&tool), true),
            ToolCatalogEntry::control_inline(Arc::clone(&tool), true),
            ToolCatalogEntry::session_deferred(
                tool,
                true,
                ToolProvenance {
                    kind: ToolSourceKind::Callback,
                    source_id: "owner".into(),
                },
            ),
        ] {
            assert_eq!(entry.execution, ToolExecutionContract::default());
        }
    }

    #[test]
    fn catalog_entry_preserves_non_default_execution_contract() {
        let detached = DetachedToolExecutionPolicy::new(
            RunnerIdentity::new("homecore.security_scan", "v1").unwrap(),
            RestartClass::NonResumable,
            IdempotencyScope::InteractionAndArguments,
            Duration::from_secs(10),
        )
        .unwrap();
        let contract = ToolExecutionContract::new(
            BTreeSet::from([ToolExecutionMode::Detached]),
            ToolExecutionMode::Detached,
            None,
            Some(detached),
        )
        .unwrap();
        let entry = ToolCatalogEntry::session_inline(
            Arc::new(ToolDef::new(
                "security_scan",
                "scan",
                serde_json::json!({ "type": "object" }),
            )),
            true,
        )
        .with_execution_contract(contract.clone());

        assert_eq!(entry.execution, contract);
    }
}