meerkat 0.8.9

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
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
//! 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,
    AssistantBlock,
    // Phase 3 provider-auth redesign — realm-scoped connection identity.
    AuthBindingRef,
    BindingId,
    BlockAssistantMessage,
    // Budget
    Budget,
    BudgetConfig,
    BudgetLimits,
    BudgetPool,
    BudgetType,
    CompiledSchema,
    ConcurrencyLimits,
    // Config
    Config,
    ConfigDelta,
    ConfigError,
    ContextStrategy,
    ForkBranch,
    ForkBudgetPolicy,
    HookAdapterConfig,
    HookCapability,
    HookDecision,
    HookEngine,
    HookEngineError,
    HookEntryConfig,
    HookExecutionMode,
    HookExecutionReport,
    HookId,
    HookInvocation,
    HookOutcome,
    HookPoint,
    HookReasonCode,
    HookRunOverrides,
    HookRuntimeKind,
    HooksConfig,
    // Interaction types
    InteractionContent,
    InteractionId,
    LlmStreamResult,
    // State
    LoopState,
    McpServerConfig,
    MeerkatSchema,
    // Types
    Message,
    OAuthProviderIdentity,
    OpEvent,
    OperationId,
    OperationPolicy,
    OperationResult,
    OperationSpec,
    OutputSchema,
    // Provider
    Provider,
    RealmId,
    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,
    // Canonical typed tool identity (K8a fold)
    ToolName,
    ToolResult,
    TranscriptMessageIdentity,
    Usage,
    UserMessage,
    // Operations
    WorkKind,
};

mod agent_builder;
pub use agent_builder::AgentBuilder;
mod job_delivery;
pub use job_delivery::{
    AppliedRuntimeJobDelivery, BlockedRuntimeJobDelivery, JobDeliveryApplication,
    JobDeliveryContent, JobDeliverySink, JobNotificationDeliveryPayload, JobOutboxProjectionError,
    JobOutboxProjectionPass, JobOutboxProjector, JobRuntimeDeliveryApplier,
    JobTerminalDeliveryPayload, PreparedJobDelivery, ProjectedJobDelivery, RuntimeJobDeliveryDrain,
    SkippedJobOutboxEntry,
};
mod job_composition;
pub use job_composition::{
    JobAwaitActivity, JobAwaitCoordinator, JobAwaitDeliverySink, JobAwaitReceipt,
    JobCompositionError, JobTerminalEvidenceKind, JobTerminalEvidenceProjection,
    JobTerminalEvidenceProjector, JobWorkGraphLink, ScheduledDurableJobRunnable,
    ScheduledJobTemplate,
};
mod job_surface;
pub use job_surface::{project_job_description, project_job_receipt};
#[cfg(feature = "schedule")]
mod predicate_schedule;
#[cfg(feature = "schedule")]
pub use predicate_schedule::{
    PredicateObservationProvider, PredicateSourceObservationError,
    SCHEDULED_PREDICATE_RUNNABLE_NAME, ScheduledPredicateParams, ScheduledPredicateRunnable,
    scheduled_predicate_runnable_name, scheduled_predicate_runner_handle,
};

// 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::{
    CompactionCurator, CompactionCuratorError, CompactionWindow, CuratedCompactionSummary,
};
pub use meerkat_core::{
    SessionTranscriptRestoreRevisionRequest, SessionTranscriptRevisionList,
    SessionTranscriptRevisionListEntry, SessionTranscriptRevisionListQuery,
    SessionTranscriptRevisionPage, SessionTranscriptRevisionQuery, SessionTranscriptRewriteRequest,
    SessionTranscriptRewriteResult, TranscriptEditRunningBehavior, TranscriptRewriteCommit,
    TranscriptRewriteReason, TranscriptRewriteRecord, TranscriptRewriteSelection,
    TranscriptRewriteSemantic,
};

// Re-export client types
pub use meerkat_client::{
    FactoryError, LlmClient, LlmDoneOutcome, LlmError, LlmEvent, LlmRequest, LlmResponse,
};
pub use meerkat_schedule::{
    CalendarFieldSpec, CalendarTriggerSpec, ClaimDueRequest, ClaimDueResult, CreateScheduleRequest,
    DeliveryCompletion, DeliveryDispatch, DeliveryFailureReason, DeliveryReceipt,
    DeliveryReceiptStage, DeliveryTerminal, DisabledScheduleStore, ForkContextSpec,
    HelperOptionsSpec, HostRunnable, HostRunnableError, HostRunnableInvocation, HostRunnableName,
    HostRunnableNameError, HostRunnableOutcome, HostRunnableParams, HostRunnableParamsError,
    HostRunnableRegistry, HostRunnableRegistryError, HostRunnableTargetBinding,
    IdentityTargetBinding, IntervalTriggerSpec, MemoryScheduleStore, MisfirePolicy,
    MissingTargetPolicy, MobTargetBinding, Occurrence, OccurrenceFailureClass, OccurrenceFilter,
    OccurrenceId, OccurrenceOrdinal, OccurrencePhase, OverlapPolicy, ResolvedSpawnSnapshot,
    RunnableProbe, SCHEDULE_TOOL_CAPABILITY_UNAVAILABLE, SCHEDULE_TOOL_INVALID_ARGUMENTS,
    SCHEDULE_TOOL_NOT_FOUND, Schedule, ScheduleDomainError, ScheduleDriver, ScheduleDriverConfig,
    ScheduleFilter, ScheduleId, SchedulePhase, ScheduleRevision, ScheduleRunnableHost,
    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, AttentionPruneRequest, AttentionPruneResult, AttentionReassignRequest,
    AttentionReassignResult, AttentionResumeRequest, BreakGlassAttentionReassignRequest,
    ClaimWorkItemRequest, CloseWorkItemRequest, CreateWorkItemRequest, DisabledWorkGraphStore,
    ExternalWorkRef, GoalAttentionTarget, GoalConfirmRequest, GoalConfirmResult, GoalCreateRequest,
    GoalCreateResult, GoalRequestCloseRequest, GoalRequestCloseResult, GoalStatusRequest,
    GoalStatusResult, GoalTerminalStatus, LinkWorkItemsRequest, MemoryWorkGraphStore,
    PolicyEscalateRequest, ProjectedAttentionAuthority, PublicGoalCompletionPolicy,
    PublicGoalCreateRequest, PublicGoalRequestCloseRequest, ReadyWorkFilter,
    ReleaseWorkItemRequest, UpdateWorkItemRequest, WORKGRAPH_ATTENTION_DISPATCH_CONTEXT_KEY,
    WorkAttentionBinding, WorkAttentionBindingId, WorkAttentionMachine, WorkAttentionMachineState,
    WorkAttentionMode, WorkAttentionStatus, WorkAttentionTarget, WorkClaim, WorkCompletionPolicy,
    WorkEdge, WorkEdgeKind, WorkEvidenceRef, WorkGraphError, WorkGraphEvent, WorkGraphEventFilter,
    WorkGraphEventKind, WorkGraphEventsResponse, WorkGraphIdParams, WorkGraphItemsResponse,
    WorkGraphMachine, WorkGraphMachineState, WorkGraphPublicErrorClass, WorkGraphRestRoute,
    WorkGraphService, WorkGraphSnapshot, WorkGraphSnapshotFilter, WorkGraphStore,
    WorkGraphStoreKind, WorkGraphToolError, WorkGraphToolErrorCode, WorkGraphToolSurface, WorkItem,
    WorkItemFilter, WorkItemId, WorkItemRef, WorkNamespace, WorkOwner, WorkOwnerKey, WorkOwnerKind,
    WorkPriority, WorkStatus, handle_unscoped_workgraph_tools_call, handle_workgraph_tools_call,
    unscoped_workgraph_tools_list, 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;
#[cfg(not(target_arch = "wasm32"))]
mod host_auth;
mod model_fallback;
pub use factory::{
    AgentBuildConfig, AgentFactory, BuildAgentError, CreateSessionModelResolution,
    CreateSessionModelResolutionError, CreateSessionModelResolutionRequest, DynAgent,
    LlmIdentityPreflightError, decode_llm_client_override_from_service,
    encode_llm_client_override_for_service, provider_key, resolve_create_session_default_model,
    resolve_create_session_model, resolve_provider_catalog_default_model,
};
#[cfg(not(target_arch = "wasm32"))]
pub use host_auth::{
    HostAuthError, HostAuthLoginComplete, HostAuthLoginStart, HostAuthService, HostAuthStatus,
    HostAuthTarget,
};
#[cfg(not(target_arch = "wasm32"))]
pub use meerkat_providers::auth_store::{ProviderAuthPersistence, TokenStoreBackend};

pub mod help;

mod persistence;
#[cfg(all(feature = "session-store", not(target_arch = "wasm32")))]
pub mod storage_provider;
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;
#[cfg(all(feature = "session-store", not(target_arch = "wasm32")))]
pub use persistence::open_realm_persistence_with_provider;
#[cfg(all(feature = "session-store", not(target_arch = "wasm32")))]
pub use storage_provider::{
    DiskStorageProvider, RealmOpenContext, RealmStorageProvider, RealmStoreSet,
};

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;
#[cfg(not(target_arch = "wasm32"))]
pub use service_factory::RealmInheritance;
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;

// Explicitly-featured deterministic test fixtures (ADJ-P6B-4). Native-only:
// the scripted realtime fakes park on tokio sync primitives the wasm alias
// does not expose, and no wasm lane consumes them.
#[cfg(all(feature = "test-realtime-fixtures", not(target_arch = "wasm32")))]
pub mod test_fixtures;

// 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,
};
#[cfg(not(target_arch = "wasm32"))]
pub use meerkat_jobs::SqliteDetachedJobStore;
pub use meerkat_jobs::{
    AttemptClaim, AttemptClaimReceipt, AttemptId, AttemptWriteAuthority, CanonicalArgumentsHash,
    CheckpointRef, DetachedJobError, DetachedJobService, DetachedJobStore, ExecutionIntentId,
    FenceToken, InteractionLineageId, JobDeliveryKind, JobDescription, JobFailureCode,
    JobHealthCondition, JobId, JobNotification, JobOutboxEntry, JobPhase, JobProgress,
    JobProgressKind, JobReceipt, JobReference, JobResultRef, JobSnapshot, JobSpec,
    JobSubmissionKey, JobSubscription, JobSubscriptionId, JobTerminalKind, JobTerminalResult,
    MemoryDetachedJobStore, OriginMemberId, RestartClass, RunnerHandleRef, RunnerIdentity,
    RunnerSpecificationRef, ToolIdentity, WorkerId,
};
pub use meerkat_runtime::{InMemoryRuntimeStore, Input, PromptInput, RuntimeStore};
#[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, LiveSessionActorWitness, RuntimeContextAdmissionGuard, SessionAgent,
    SessionAgentBuilder,
};
#[cfg(feature = "session-store")]
pub use meerkat_session::{
    LiveSessionActorTurnBoundaryLease, LiveSessionActorWitnessSlot,
    MachineServiceTurnCommitProtocol, MachineSessionArchiveProtocol, PersistentSessionService,
};
// Maintenance compositions (offline `rkat storage migrate`): a builder that
// refuses agent construction, composed with the persistent service to drive
// machine-owned storage maintenance (bulk legacy-checkpoint adoption).
pub use meerkat_session::maintenance::MaintenanceAgentBuilder;
#[cfg(all(feature = "session-store", not(target_arch = "wasm32")))]
pub use meerkat_session::{LegacyCheckpointAdoptionOptions, LegacyCheckpointAdoptionReport};
// Memory store implementation, re-exported for maintenance verbs that stamp
// the memory database's schema ledger through its normal constructor.
#[cfg(feature = "memory-store-session")]
pub use meerkat_memory::HnswMemoryStore;
// Durable stored-event row (typed envelope identity) for replay surfaces.
#[cfg(feature = "session-store")]
pub use meerkat_session::event_store::StoredEvent;

#[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, ToolValidationError};

// Cross-surface durable SkillKeys require every skills-enabled facade to link
// feature-owned embedded declarations, even when the corresponding tool
// surface is disabled. The declaration and body remain owned by
// `meerkat-comms`; this static is only the mechanical aggregation edge.
#[cfg(feature = "skills")]
#[used]
static MEERKAT_COMMS_EMBEDDED_SKILL_LINK: fn() = meerkat_comms::link_embedded_skill_registrations;

#[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,
};
#[cfg(all(feature = "mcp", not(target_arch = "wasm32")))]
pub mod mcp;

// 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;

// Typed per-request system-prompt policy. Canonically owned by
// `meerkat_core::config` (its serde IS the wire/persisted representation);
// re-exported here for surface crates.
pub use meerkat_core::config::SystemPromptOverride;

// Target-neutral prompt-policy renderer. Native source loading and the
// filesystem-free WASM path both lower into this one semantic owner.
mod prompt_policy;

// 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::{PromptAssemblyError, 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, AssistantBlock, BlockAssistantMessage, 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;
}