meerkat 0.7.0-alpha.0

Modular, high-performance agent harness for LLM-powered applications
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
//! Meerkat - Rust Agentic Interface Kit
//!
//! A minimal, high-performance agent harness for LLM-powered applications.
//!
//! # Architecture
//!
//! All production surfaces (CLI, REST, RPC, MCP) use the **runtime-backed** path:
//! `SessionService` (substrate) + `MeerkatMachine` (control plane).
//! The runtime owns keep-alive, Queue/Steer routing, comms drain, and ingress.
//!
//! `build_ephemeral_service` is available for **testing and embedded use** where
//! runtime semantics (keep-alive, Steer, comms-driven admission) are not needed.
//! It supports Queue-only turns and will reject Steer/render_metadata.
//!
//! For the runtime-backed entry point, see [`meerkat_rpc::SessionRuntime`] or
//! the REST/MCP server crates.

#![cfg_attr(
    test,
    allow(
        dead_code,
        clippy::expect_used,
        clippy::large_futures,
        clippy::panic,
        clippy::too_many_arguments,
        clippy::unwrap_used
    )
)]

// On wasm32, provide tokio alias backed by tokio_with_wasm.
#[cfg(target_arch = "wasm32")]
pub mod tokio {
    pub use tokio_with_wasm::alias::*;
}

// Re-export core types
pub use meerkat_core::{
    // Agent
    Agent,
    AgentConfig,
    // Errors
    AgentError,
    // Events
    AgentEvent,
    AgentLlmClient,
    AgentLlmClientDecorator,
    AgentSessionStore,
    AgentToolDispatcher,
    ArtifactRef,
    AssistantMessage,
    // Phase 3 provider-auth redesign — realm-scoped connection identity.
    AuthBindingRef,
    // Budget
    Budget,
    BudgetConfig,
    BudgetLimits,
    BudgetPool,
    BudgetType,
    CompiledSchema,
    ConcurrencyLimits,
    // Config
    Config,
    ConfigDelta,
    ConfigError,
    ContextStrategy,
    ForkBranch,
    ForkBudgetPolicy,
    HookCapability,
    HookDecision,
    HookEngine,
    HookEngineError,
    HookEntryConfig,
    HookExecutionMode,
    HookExecutionReport,
    HookFailurePolicy,
    HookId,
    HookInvocation,
    HookOutcome,
    HookPatch,
    HookPatchEnvelope,
    HookPoint,
    HookReasonCode,
    HookRevision,
    HookRunOverrides,
    HookRuntimeConfig,
    HookRuntimeKind,
    HooksConfig,
    // Interaction types
    InteractionContent,
    InteractionId,
    LlmStreamResult,
    // State
    LoopState,
    McpServerConfig,
    MeerkatSchema,
    // Types
    Message,
    OpEvent,
    OperationId,
    OperationPolicy,
    OperationResult,
    OperationSpec,
    OutputSchema,
    // Provider
    Provider,
    ResponseStatus,
    ResultShape,
    RetryConfig,
    // Retry
    RetryPolicy,
    RunResult,
    // Runtime epoch types
    RuntimeBuildMode,
    RuntimeEpochId,
    SESSION_VERSION,
    SchemaCompat,
    SchemaError,
    SchemaFormat,
    SchemaWarning,
    // Session
    Session,
    SessionId,
    SessionLlmIdentity,
    SessionMeta,
    SessionMetadata,
    SessionRuntimeBindings,
    SessionTooling,
    SpawnSpec,
    StopReason,
    StorageConfig,
    SystemMessage,
    ToolAccessPolicy,
    ToolCall,
    // Tool category override (tri-state for resume upgrade semantics)
    ToolCategoryOverride,
    ToolDef,
    ToolGateway,
    ToolGatewayBuilder,
    ToolResult,
    Usage,
    UserMessage,
    // Operations
    WorkKind,
};

mod agent_builder;
pub use agent_builder::AgentBuilder;

// Config store types (filesystem-dependent — not available on wasm32)
#[cfg(not(target_arch = "wasm32"))]
pub use meerkat_core::{
    ConfigEnvelope, ConfigResolvedPaths, ConfigRuntime, ConfigRuntimeError, ConfigSnapshot,
    ConfigStore, ConfigStoreMetadata, FileConfigStore, MemoryConfigStore, TaggedConfigStore,
};

// Re-export comms types from meerkat_comms
#[cfg(feature = "comms")]
pub use meerkat_comms::agent::{CommsContent, CommsMessage, CommsStatus};
#[cfg(feature = "comms")]
pub use meerkat_comms::{CommsRuntime, CommsRuntimeError, CommsToolMaterial, CoreCommsConfig};
#[cfg(feature = "comms")]
pub use meerkat_core::SessionServiceCommsExt;
pub use meerkat_core::SessionServiceControlExt;
pub use meerkat_core::SessionServiceHistoryExt;
pub use meerkat_core::SessionServiceTranscriptEditExt;
#[cfg(feature = "comms")]
pub use meerkat_core::{
    CommsCommand, EventStream, InputSource, PeerDirectoryEntry, PeerDirectorySource, PeerName,
    SendError, SendReceipt, StreamError, StreamScope,
};
pub use meerkat_core::{
    SessionTranscriptRestoreRevisionRequest, SessionTranscriptRevisionPage,
    SessionTranscriptRevisionQuery, SessionTranscriptRewriteRequest,
    SessionTranscriptRewriteResult, TranscriptEditRunningBehavior, TranscriptRewriteCommit,
    TranscriptRewriteReason, TranscriptRewriteRecord, TranscriptRewriteSelection,
};

// Re-export client types
pub use meerkat_client::{LlmClient, LlmDoneOutcome, LlmError, LlmEvent, LlmRequest, LlmResponse};
pub use meerkat_schedule::{
    CalendarFieldSpec, CalendarTriggerSpec, ClaimDueRequest, ClaimDueResult, CreateScheduleRequest,
    DeliveryCompletion, DeliveryDispatch, DeliveryFailureReason, DeliveryReceipt,
    DeliveryReceiptStage, DeliveryTerminal, DisabledScheduleStore, ForkContextSpec,
    HelperOptionsSpec, IntervalTriggerSpec, MemoryScheduleStore, MisfirePolicy,
    MissingTargetPolicy, MobTargetBinding, Occurrence, OccurrenceFailureClass, OccurrenceFilter,
    OccurrenceId, OccurrenceOrdinal, OccurrencePhase, OverlapPolicy, ResolvedSpawnSnapshot,
    SCHEDULE_TOOL_CAPABILITY_UNAVAILABLE, SCHEDULE_TOOL_INVALID_ARGUMENTS, SCHEDULE_TOOL_NOT_FOUND,
    Schedule, ScheduleDomainError, ScheduleDriver, ScheduleDriverConfig, ScheduleFilter,
    ScheduleId, SchedulePhase, ScheduleRevision, ScheduleService, ScheduleSpawnTooling,
    ScheduleStore, ScheduleStoreError, ScheduleStoreKind, ScheduleTargetDelivery,
    ScheduleTargetProbe, ScheduleToolDispatcher, ScheduleToolError, ScheduledMobAction,
    ScheduledMobBackendKind, ScheduledMobRuntimeMode, ScheduledSessionAction,
    SessionMaterializationSpec, SessionTargetBinding, TargetBinding, TargetProbeOutcome,
    TriggerSpec, UpdateScheduleRequest, handle_schedule_tools_call, schedule_tools_list,
};
pub use meerkat_tools::ToolError;
#[cfg(not(target_arch = "wasm32"))]
pub use meerkat_workgraph::SqliteWorkGraphStore;
pub use meerkat_workgraph::{
    AddEvidenceRequest, AttentionBindingRequest, AttentionBindingResult,
    AttentionContextProjection, AttentionContinueOutcome, AttentionContinueResult,
    AttentionDelegatedAuthority, AttentionListRequest, AttentionListResult, AttentionPauseRequest,
    AttentionProjectionPolicy, AttentionProjectionRequest, AttentionProjectionResult,
    AttentionProjectionText, AttentionReassignRequest, AttentionResumeRequest,
    ClaimWorkItemRequest, CloseWorkItemRequest, CreateWorkItemRequest, DisabledWorkGraphStore,
    ExternalWorkRef, GoalAttentionTarget, GoalConfirmRequest, GoalConfirmResult, GoalCreateRequest,
    GoalCreateResult, GoalRequestCloseRequest, GoalRequestCloseResult, GoalStatusRequest,
    GoalStatusResult, GoalTerminalStatus, LinkWorkItemsRequest, MemoryWorkGraphStore,
    ProjectedAttentionAuthority, PublicGoalCompletionPolicy, PublicGoalCreateRequest,
    PublicGoalRequestCloseRequest, ReadyWorkFilter, ReleaseWorkItemRequest, UpdateWorkItemRequest,
    WORKGRAPH_ATTENTION_DISPATCH_CONTEXT_KEY, WORKGRAPH_TOOL_CAPABILITY_UNAVAILABLE,
    WORKGRAPH_TOOL_CONFLICT, WORKGRAPH_TOOL_INTERNAL_ERROR, WORKGRAPH_TOOL_INVALID_ARGUMENTS,
    WORKGRAPH_TOOL_INVALID_TRANSITION, WORKGRAPH_TOOL_NOT_FOUND, WORKGRAPH_TOOL_STORE_ERROR,
    WorkAttentionBinding, WorkAttentionBindingId, WorkAttentionMachine, WorkAttentionMachineState,
    WorkAttentionMode, WorkAttentionStatus, WorkAttentionTarget, WorkClaim, WorkCompletionPolicy,
    WorkEdge, WorkEdgeKind, WorkEvidenceRef, WorkGraphError, WorkGraphEvent, WorkGraphEventFilter,
    WorkGraphEventKind, WorkGraphEventsResponse, WorkGraphItemsResponse, WorkGraphMachine,
    WorkGraphMachineState, WorkGraphPublicErrorClass, WorkGraphRestRoute, WorkGraphService,
    WorkGraphSnapshot, WorkGraphSnapshotFilter, WorkGraphStore, WorkGraphStoreKind,
    WorkGraphToolError, WorkGraphToolSurface, WorkItem, WorkItemFilter, WorkItemId, WorkItemRef,
    WorkNamespace, WorkOwner, WorkOwnerKey, WorkOwnerKind, WorkPriority, WorkStatus,
    handle_workgraph_tools_call, validate_workgraph_attention_projection_current,
    workgraph_attention_context_append, workgraph_attention_continuation_key,
    workgraph_attention_projection_from_overlay, workgraph_attention_supersession_key,
    workgraph_attention_turn_append, workgraph_rest_path_catalog,
    workgraph_rest_request_response_schema, workgraph_tools_list,
};

// AgentFactory and build_agent types
mod factory;
pub use factory::{
    AgentBuildConfig, AgentFactory, BuildAgentError, DynAgent,
    decode_llm_client_override_from_service, encode_llm_client_override_for_service, provider_key,
};

pub mod help;

mod persistence;
pub use persistence::PersistenceBundle;
#[cfg(feature = "session-store")]
pub use persistence::PersistenceError;
#[cfg(all(feature = "session-store", not(target_arch = "wasm32")))]
pub use persistence::open_realm_persistence_in;

mod meerkat_machine;

// Factory-backed SessionService wiring (substrate — testing/embedded use).
// Production surfaces use runtime-backed paths (see meerkat-rpc, meerkat-rest).
mod service_factory;
pub use service_factory::{FactoryAgent, FactoryAgentBuilder, build_ephemeral_service};
#[cfg(feature = "session-store")]
pub use service_factory::{
    build_persistent_service, build_persistent_service_with_runtime_adapter,
};

// Canonical staged-session lifecycle authority. See
// `docs/wave-d-prep/d-j-staged-session-design.md`.
mod staged_sessions;
pub use staged_sessions::{
    GeneratedMachineArchivedResumeAdmission, PromotingSlot, StagedLifecycleError,
    StagedSessionInfo, StagedSessionRegistry, StagedSlot,
};

// Surface-agnostic session runtime. Empty during F2 — populated by
// the W1/W2/W3 moves out of `meerkat-rpc::session_runtime`. See
// `SESSION_RUNTIME_SPLIT_TODO.md`.
pub mod session_runtime;

// Session service
pub use meerkat_core::service::InitialTurnPolicy;
pub use meerkat_core::service::StartTurnRuntimeSemantics;
pub use meerkat_core::{
    AppendSystemContextRequest, AppendSystemContextResult, AppendSystemContextStatus, BlobStore,
    CreateSessionRequest, DeferredPromptPolicy, MobToolsBuildArgs, MobToolsFactory,
    SessionBuildOptions, SessionControlError, SessionError, SessionHistoryPage,
    SessionHistoryQuery, SessionInfo, SessionQuery, SessionService, SessionSummary, SessionUsage,
    SessionView, StartTurnRequest,
};
pub use meerkat_runtime::{Input, PromptInput};
#[cfg(feature = "session-compaction")]
pub use meerkat_session::DefaultCompactor;
// PersistentSessionService: used by runtime-backed surfaces (REST, RPC, MCP).
// EphemeralSessionService: in-memory substrate for testing/embedded use only.
// Both implement SessionService. Production paths add MeerkatMachine on top.
pub use meerkat_session::{
    EphemeralSessionService, RuntimeContextAdmissionGuard, SessionAgent, SessionAgentBuilder,
};
#[cfg(feature = "session-store")]
pub use meerkat_session::{
    MachineServiceTurnCommitProtocol, MachineSessionArchiveProtocol, PersistentSessionService,
};

#[cfg(feature = "anthropic")]
pub use meerkat_client::AnthropicClient;

#[cfg(feature = "openai")]
pub use meerkat_client::OpenAiClient;

#[cfg(feature = "gemini")]
pub use meerkat_client::GeminiClient;

// Re-export store types (trait + filter + error from core, backend error from meerkat-store)
pub use meerkat_store::{
    MemoryBlobStore, SessionFilter, SessionStore, SessionStoreError, StoreError,
};

#[cfg(feature = "jsonl-store")]
pub use meerkat_store::JsonlStore;

#[cfg(feature = "memory-store")]
pub use meerkat_store::MemoryStore;

#[cfg(all(feature = "session-store", not(target_arch = "wasm32")))]
pub use meerkat_store::SqliteScheduleStore;
#[cfg(all(feature = "session-store", not(target_arch = "wasm32")))]
pub use meerkat_store::SqliteSessionStore;

// Re-export tools
#[cfg(not(target_arch = "wasm32"))]
pub use meerkat_tools::{DispatchError, ToolDispatcher, ToolRegistry, ToolValidationError};

// Embedded skill registration.
//
// `mob-communication` must be available across surfaces because sessions can be
// created under one binary (for example CLI) and resumed under another (for
// example RPC). Register it from the base crate so any skills-enabled surface
// links the embedded skill inventory entry even when `meerkat-mob` itself is
// not compiled into that binary.
#[cfg(feature = "skills")]
inventory::submit! {
    meerkat_skills::SkillRegistration {
        id: "mob-communication",
        name: "Mob Communication",
        description: "How to communicate with peers in a collaborative mob",
        scope: meerkat_core::skills::SkillScope::Builtin,
        requires_capabilities: &["comms"],
        body: include_str!("../skills/mob-communication/SKILL.md"),
        extensions: &[],
    }
}

#[cfg(feature = "skills")]
inventory::submit! {
    meerkat_skills::SkillRegistration {
        id: help::MEERKAT_PLATFORM_SKILL_NAME,
        name: "Meerkat Platform",
        description: "Task-oriented reference for Meerkat CLI, RPC, REST, MCP, SDKs, skills, auth, scheduling, and mobs",
        scope: meerkat_core::skills::SkillScope::Builtin,
        requires_capabilities: &[],
        body: help::MEERKAT_PLATFORM_SKILL_BODY,
        extensions: help::MEERKAT_PLATFORM_SKILL_EXTENSIONS,
    }
}

#[cfg(feature = "skills")]
inventory::submit! {
    meerkat_skills::SkillRegistration {
        id: help::MEERKAT_CLI_REFERENCE_SKILL_NAME,
        name: "Meerkat CLI Reference",
        description: "Exact rkat CLI command contract for Meerkat help answers",
        scope: meerkat_core::skills::SkillScope::Builtin,
        requires_capabilities: &[],
        body: help::MEERKAT_CLI_REFERENCE_SKILL_BODY,
        extensions: &[],
    }
}

// Re-export builtin tools infrastructure
#[cfg(feature = "comms")]
pub use meerkat_tools::CommsToolSurface;
#[cfg(all(feature = "session-store", not(target_arch = "wasm32")))]
pub use meerkat_tools::builtin::SqliteTaskStore;
pub use meerkat_tools::{
    BuiltinTool, BuiltinToolConfig, BuiltinToolEntry, BuiltinToolError, CompositeDispatcher,
    CompositeDispatcherError, EnforcedToolPolicy, MemoryTaskStore, ResolvedToolPolicy, TaskStore,
    ToolMode, ToolPolicyLayer,
};
#[cfg(not(target_arch = "wasm32"))]
pub use meerkat_tools::{FileTaskStore, ensure_rkat_dir, find_project_root};

// Re-export MCP client
#[cfg(feature = "mcp")]
pub use meerkat_mcp::{
    McpApplyDelta, McpApplyResult, McpConnection, McpError, McpLifecycleAction, McpLifecyclePhase,
    McpReloadTarget, McpRouter, McpRouterAdapter, McpServerLifecycleState,
};

// Skill types re-exports
pub use meerkat_core::skills::{
    SkillCollection, SkillDescriptor, SkillDocument, SkillFilter, SkillIntrospectionEntry,
    SkillRuntime, SkillScope,
};

// Contracts re-exports
pub use meerkat_contracts::{
    self as contracts, CapabilitiesResponse, CapabilityHint, CapabilityId, CapabilityRegistration,
    CapabilityScope, CapabilityStatus, CommsParams, ContractVersion, CoreCreateParams,
    ErrorCategory, ErrorCode, HelpExecutionMode, HelpRequest, HelpResponse, HookParams, Protocol,
    SkillEntry, SkillInspectResponse, SkillListResponse, SkillsParams, StructuredOutputParams,
    WireError, WireEvent, WireRunResult, WireSessionInfo, WireSessionSummary, WireUsage,
    build_capabilities,
};

// Surface infrastructure
pub mod surface;

// Prompt assembly (filesystem-dependent: reads AGENTS.md, system_prompt_file)
#[cfg(not(target_arch = "wasm32"))]
mod prompt_assembly;
#[cfg(not(target_arch = "wasm32"))]
pub use prompt_assembly::assemble_system_prompt;

// SDK helpers (filesystem-dependent: .rkat dir, hook config files)
#[cfg(not(target_arch = "wasm32"))]
mod sdk;
#[cfg(not(target_arch = "wasm32"))]
pub use sdk::*;
#[cfg(not(target_arch = "wasm32"))]
mod sdk_config;
#[cfg(not(target_arch = "wasm32"))]
pub use sdk_config::SdkConfigStore;

// Comms tool composition (available on all platforms including wasm32)
#[cfg(feature = "comms")]
pub fn compose_tools_with_comms(
    base_tools: std::sync::Arc<dyn meerkat_core::AgentToolDispatcher>,
    tool_usage_instructions: String,
    material: meerkat_comms::CommsToolMaterial,
) -> Result<
    (
        std::sync::Arc<dyn meerkat_core::AgentToolDispatcher>,
        String,
    ),
    meerkat_tools::ToolError,
> {
    use meerkat_tools::CommsToolSurface;
    use std::sync::Arc;
    let router = material.router().clone();
    let trusted_peers = material.trusted_peers_shared();
    let runtime = material.into_runtime();
    let comms_surface = CommsToolSurface::new_with_runtime(router, trusted_peers, runtime);
    // Use DynamicToolComposite instead of a single ToolGateway so that
    // base_tools with dynamic tool lists (e.g. CallbackToolDispatcher backed
    // by a shared registry) can surface late additions via poll_external_updates.
    let composite =
        meerkat_core::DynamicToolComposite::new(vec![base_tools, Arc::new(comms_surface)]);
    let mut instructions = tool_usage_instructions;
    if !instructions.is_empty() {
        instructions.push_str("\n\n");
    }
    instructions.push_str(CommsToolSurface::usage_instructions());
    Ok((Arc::new(composite), instructions))
}

// Re-export provider-runtime types for downstream consumers that used to
// reach them via meerkat_providers::* or meerkat_client::*.
pub use meerkat_llm_core::provider_runtime::{
    ExternalAuthResolverHandle, ProviderAuthError, ProviderBindingError, ProviderClientError,
    ProviderRuntime, ProviderRuntimeRegistry, ResolverEnvironment,
};

/// Prelude module for convenient imports
pub mod prelude {
    pub use super::{
        AgentConfig, AgentError, AgentEvent, AssistantMessage, Budget, BudgetLimits, BudgetType,
        Config, LlmClient, LlmError, LlmEvent, LlmRequest, Message, RetryPolicy, RunResult,
        Session, SessionFilter, SessionId, SessionMeta, SessionStore, StopReason, SystemMessage,
        ToolCall, ToolDef, ToolResult, Usage, UserMessage,
    };

    #[cfg(feature = "anthropic")]
    pub use super::AnthropicClient;

    #[cfg(feature = "openai")]
    pub use super::OpenAiClient;

    #[cfg(feature = "gemini")]
    pub use super::GeminiClient;
}