Skip to content

Crate Reference ​

Complete reference for all 24 workspace crates. Organized by architectural layer.

Core ​

y-core ​

Path: crates/y-core/ | Purpose: Boundary-defining crate -- trait definitions and shared types only.

Key Traits:

TraitMethodsUsed By
LlmProviderchat_completion(), chat_completion_stream(), metadata()y-provider
ProviderPoolchat_completion(), chat_completion_stream(), report_error(), freeze(), thaw()y-service
Toolexecute(), definition(), check_permissions(), is_read_only(), is_destructive()y-tools
ToolRegistrytool_index(), search(), get(), register(), unregister()y-tools
RuntimeAdapterexecute(), spawn(), kill(), health_check(), cleanup()y-runtime
Middlewareexecute(), chain_type(), priority(), name()y-hooks, y-guardrails
AgentRunnerrun(AgentRunConfig) -> AgentRunOutputy-service
AgentDelegatordelegate(agent_name, input, context_strategy, session_id)y-service

Key Types:

TypeDescription
MessageChat message with role, content, tool_calls, metadata
RoleSystem, User, Assistant, Tool
ChatRequestLLM request with messages, model, tools, thinking config
ChatResponseLLM response with content, tool_calls, usage, raw payloads
ToolDefinitionTool schema with name, description, JSON Schema parameters, category
ToolCategoryFileSystem, Network, Shell, Search, Memory, Knowledge, Agent, Workflow, Schedule, Interaction, Custom
ToolTypeBuiltIn, Mcp, Custom, Dynamic
ToolCallingModePromptBased (XML tags) vs Native (API-level)
TokenUsageinput_tokens, output_tokens, cache_read_tokens, cache_write_tokens
ProviderTypeOpenAi, Anthropic, Gemini, Ollama, Azure, OpenRouter, Custom
SessionNodeSession tree node with parent/root/depth/path/state/agent info
SessionTypeMain, Child, Branch, Ephemeral, SubAgent, Canonical
SessionStateActive, Paused, Archived, Merged, Tombstone
MemoryMemory entry with type, scopes, importance, access_count
MemoryTypePersonal, Task, Tool, Experience
HookPoint24 lifecycle hook points (PreLlmCall, PostToolExecute, etc.)
ChainTypeContext, Tool, Llm, Compaction, Memory
ThinkingConfigExtended thinking with effort levels (Low/Medium/High/Max)
ResponseFormatText, JsonObject, JsonSchema
ChatCheckpointTurn-level checkpoint for rollback
AgentRunConfigAgent execution configuration (name, prompt, models, tools, timeout)

ID Types (newtype wrappers over String):SessionId, WorkflowId, TaskId, ProviderId, AgentId, ToolName, SkillId, MemoryId


Infrastructure ​

y-provider ​

Path: crates/y-provider/ | Purpose: LLM provider pool with routing, failover, and metrics.

ComponentResponsibility
ProviderPoolImplMulti-provider pool with semaphore-based concurrency
TagBasedRouter4-step route selection: freeze -> tag -> priority -> strategy
FreezeManagerAdaptive freeze durations based on error classification
HealthCheckerBackground provider health monitoring
ProviderMetricsSuccess/error/latency/cost tracking
PrioritySchedulerCritical/Normal/Idle tier scheduling with reserved slots
OpenAiProviderOpenAI + compatible APIs (DeepSeek, etc.)
AnthropicProviderAnthropic Claude API
GeminiProviderGoogle Gemini API
OllamaProviderLocal Ollama inference
AzureOpenAiProviderAzure OpenAI deployment
OpenAiEmbeddingProviderEmbedding generation

y-session ​

Path: crates/y-session/ | Purpose: Session lifecycle, state machine, tree traversal.

ComponentResponsibility
SessionManagerCRUD operations, dual-transcript writes, fork/branch
StateMachineSession state transitions (Active/Paused/Archived/Merged/Tombstone)
ChatCheckpointManagerTurn-level checkpointing for rollback
CanonicalSessionManagerCanonical session resolution
TreeUtilsSession tree traversal and query

y-context ​

Path: crates/y-context/ | Purpose: Context assembly, compaction, memory recall.

ComponentResponsibility
ContextPipelinePriority-ordered provider chain (100-700)
ContextWindowGuard3 trigger modes for context overflow
CompactionEngineLLM-based conversation summarization
PruningEngineRetryPruning (zero LLM cost) + ProgressivePruning (rolling summary)
RecallStoreHybrid text/vector memory recall
KnowledgeContextProviderKnowledge base injection at priority 350
WorkingMemoryPipeline-scoped blackboard for inter-stage data

y-storage ​

Path: crates/y-storage/ | Purpose: SQLite backends and JSONL transcript writers.

StoreBackendData
SqliteSessionStoreSQLiteSession metadata
SqliteChatMessageStoreSQLiteChat messages with status flags
SqliteChatCheckpointStoreSQLiteTurn-level checkpoints
SqliteCheckpointStorageSQLiteWorkflow checkpoints
SqliteScheduleStoreSQLiteSchedule definitions and execution records
SqliteWorkflowStoreSQLiteWorkflow templates
SqliteProviderMetricsStoreSQLiteProvider performance data
JsonlTranscriptStoreJSONL filesContext transcripts (LLM-facing)
JsonlDisplayTranscriptStoreJSONL filesDisplay transcripts (UI-facing)

Utilities: create_pool() (sqlx SqlitePool with WAL mode), run_embedded_migrations().

y-knowledge ​

Path: crates/y-knowledge/ | Purpose: External knowledge ingestion and hybrid retrieval.

ComponentResponsibility
IngestionPipelineDocument ingestion with format detection and chunking
ChunkingStrategyL0/L1/L2 multi-resolution chunking
RuleBasedClassifierDomain classification for knowledge entries
Bm25IndexBM25 full-text search index
HybridRetrieverBM25 + vector combined retrieval
ProgressiveLoaderOn-demand sub-document loading
QualityFilterRelevance and quality scoring
AutoTokenizerLanguage-aware tokenization (Chinese, simple)
VectorIndexerQdrant vector indexing (feature-gated)

y-diagnostics ​

Path: crates/y-diagnostics/ | Purpose: Trace storage, cost intelligence, replay.

ComponentResponsibility
DiagnosticsContextGlobal static context (DIAGNOSTICS_CTX) for trace scoping
CostIntelligenceToken cost computation and aggregation
TraceReplayReplay recorded traces for debugging
TraceSearchQuery traces by session, time, agent
SqliteTraceStoreProduction trace storage
InMemoryTraceStoreTest-only trace storage
DiagnosticsSubscriberEvent bus listener for automatic trace capture

Middleware ​

y-hooks ​

Path: crates/y-hooks/ | Purpose: Middleware chain execution and event bus.

ComponentResponsibility
HookSystemUnified facade for chains + event bus
MiddlewareChainPriority-sorted pipeline per ChainType
ChainRunnerTimeout-guarded chain execution
HookRegistryHook registration and lifecycle
EventBustokio::broadcast async event distribution
HookHandlerExecutorCommand/HTTP/prompt-agent decision handlers (feature-gated)

y-guardrails ​

Path: crates/y-guardrails/ | Purpose: Safety guardrails implemented as middleware.

ComponentPriorityResponsibility
ToolGuardMiddleware10Permission enforcement for tool calls
LoopDetectorMiddleware204-pattern loop detection (repetition, oscillation, drift, redundant)
LlmGuardMiddleware900LLM output validation
PermissionModel--allow/notify/ask/deny evaluation
TaintTracker--Data flow taint propagation
RiskScorer--Composite risk assessment
HitlProtocol--Human-in-the-loop with configurable timeout
CapabilityGapMiddleware--Detects missing capabilities
GuardrailManager--Hot-reloadable config via RwLock<GuardrailConfig>

y-prompt ​

Path: crates/y-prompt/ | Purpose: Prompt template engine with section management.

ComponentResponsibility
PromptSectionTyped, prioritized, token-budgeted prompt fragment
PromptTemplateDeclarative section composition with mode overlays
SectionStoreSection registry and lookup
ModeOverlaybuild/plan/explore/general mode toggles
estimate_tokens()Fast token estimation
truncate_to_budget()Budget-aware content truncation
truncate_tool_result()Hard 10K character cap for tool results

y-mcp ​

Path: crates/y-mcp/ | Purpose: Model Context Protocol client for third-party tools.

ComponentResponsibility
McpClientStdio + HTTP transport MCP client
McpToolAdapterWraps MCP tools as y-core Tool trait objects
McpConnectionManagerConnection lifecycle with ReconnectPolicy
McpAuthStoreCredential storage for MCP servers
discovery moduleMCP server auto-discovery

Capabilities ​

y-tools ​

Path: crates/y-tools/ | Purpose: Tool registry with 4 types, lazy loading, validation.

ComponentResponsibility
ToolRegistryImplCentral registry for all tool types
ToolActivationSetLRU-based active tool set (ceiling 20)
ToolIndexLightweight name+description index (always loaded)
ToolExecutorSchema validation + middleware + execution
JsonSchemaValidatorJSON Schema Draft 7 parameter validation
DynamicToolManagerRuntime tool create/update/delete
ResultFormatterTool output formatting
RateLimiterPer-tool rate limiting
ToolTaxonomyHierarchical tool categorization
Parser functionsMulti-format tool call parsing (OpenAI, DeepSeek, MiniMax, GLM4, Qwen3)

y-skills ​

Path: crates/y-skills/ | Purpose: Skill ingestion, versioning, evolution.

ComponentFeature GateResponsibility
SkillRegistryalways-onSkill registration and lookup
PersistentVersionStorealways-onContent-addressable versioning with JSONL reflog
SkillGarbageCollectoralways-onUnused skill cleanup
IngestionPipelineskill_ingestionFormat detection, classification, decomposition
SecurityScreenerskill_security_screeningSecurity verdict before activation
ResourceLinkerskill_linkageCross-skill dependency resolution
ExperienceStoreevolution_captureUsage experience recording
PatternExtractorevolution_extractionPattern mining from usage data
SkillRefinerevolution_refinementAutomated skill improvement with regression detection
FastPathExtractorevolution_fast_pathQuick pattern extraction for common cases
SkillUsageAuditskill_usage_auditUsage tracking and analytics

y-runtime ​

Path: crates/y-runtime/ | Purpose: Sandboxed code execution.

BackendIsolationUse Case
DockerRuntimeContainerStrongest isolation, network/filesystem control
NativeRuntimebubblewrapLinux namespace isolation, lower overhead
SshRuntimeRemoteExecution on remote machines

Supporting components: RuntimeManager, CapabilityChecker, ImageWhitelist, SecurityPolicy, SecurityProfile, AuditTrail, ResourceMonitor (CPU/memory/disk), VenvManager.

y-scheduler ​

Path: crates/y-scheduler/ | Purpose: Task scheduling with multiple trigger types.

Schedule TypeDescription
CronSchedule5-field cron expressions (via croner)
IntervalScheduleFixed interval repetition
OneTimeScheduleSingle future execution
EventScheduleEvent-driven triggers

Supporting: SchedulerManager, ScheduleExecutor, WorkflowDispatcher, ConcurrencyPolicy, MissedPolicy, ParameterSchema (JSON Schema for parameterized runs).

y-browser ​

Path: crates/y-browser/ | Purpose: Browser automation via Chrome DevTools Protocol.

ComponentResponsibility
CdpClientWebSocket JSON-RPC CDP client
BrowserSessionConnection lifecycle with caching and dedup
BrowserToolImplements y-core Tool trait
ChromeLauncherLocal headless Chrome process management
SecurityPolicyDomain allowlist + SSRF protection

Supports local Chrome and remote CDP providers (Browserless, Browserbase).

y-journal ​

Path: crates/y-journal/ | Purpose: File mutation journaling and rollback.

ComponentResponsibility
FileJournalMiddlewareIntercepts file-mutating tool calls
JournalStoreThree-tier storage (inline SQLite < 256KB, blob 256KB-10MB, git-ref)
FileHistoryManagerPer-session file backups at user message boundaries
ConflictDetectorExternal modification detection
rollback_scope()Scope-based rollback with conflict reporting

Orchestration ​

y-agent ​

Path: crates/y-agent/ | Purpose: DAG workflow engine and agent framework.

Orchestrator module:

ComponentResponsibility
DAG EngineSerial, parallel (All/Any/AtLeast), conditional, loop task patterns
State ChannelsTyped channels with reducers (LastValue, Append, Merge, Custom)
Checkpoint ManagerTask-level checkpointing for crash recovery
Interrupt ProtocolPause/resume for HITL integration
Stream ModesNone, Values, Updates, Messages, Debug
Workflow DefinitionsDual format: TOML templates + expression DSL

Agent module:

ComponentResponsibility
AgentDefinitionTOML-declared agent (role, models, tools, skills, mode)
AgentRegistryAgent lookup and lifecycle
AgentPoolConcurrent agent pool (default max 5)
DelegationProtocolCross-agent delegation with context strategy
DelegationTrackerDelegation chain tracking
TrustTierBuiltIn > UserDefined > Dynamic

y-bot ​

Path: crates/y-bot/ | Purpose: Chat platform adapters.

PlatformStatusTransport
FeishuActiveWebhook (HTTP)
DiscordActiveGateway (WebSocket) + REST
TelegramInterface definedPending implementation

Trait: BotPlatform -- parse_event(), send_message(), verify_signature(), handle_challenge().


Service ​

y-service ​

Path: crates/y-service/ | Purpose: Business logic orchestration hub.

ServiceResponsibility
ServiceContainerDI root -- wires all domain services from config
ChatServiceLLM turn lifecycle (context -> LLM -> tools -> diagnostics)
AgentServiceAgent execution loop, delegation, tool dispatch
BotServiceBot persona management and message routing
CostServiceToken cost computation and daily summaries
DiagnosticsServiceTrace management and replay
ObservabilityServiceSystem snapshots (agent pool, providers, scheduler)
RewindServiceFile-level rewind with conflict detection
SchedulerServiceSchedule CRUD and execution monitoring
SkillIngestionServiceSkill import with format detection and security screening
SkillServiceSkill registry queries and detail views
SystemServiceHealth checks and status reports
WorkflowServiceWorkflow CRUD, DAG visualization, validation
WorkspaceServiceWorkspace management

Presentation ​

y-cli ​

Path: crates/y-cli/ | Binary: y-agent

Subcommands: chat, status, config, session, tool, agent, workflow, diag, skill, kb, mcp, tui, resume, fork, serve, init, completion.

Boot sequence: init/completion (pre-config) -> ConfigLoader -> tracing subscriber -> wire::wire(&config) creates ServiceContainer -> dispatch subcommand.

y-web ​

Path: crates/y-web/ | Framework: axum

REST route groups: health, sessions, chat, agents, tools, diagnostics, bots, workflows, schedules, events, config, workspaces, skills, knowledge, observability, rewind, attachments.

y-gui ​

Path: crates/y-gui/ | Framework: Tauri v2 + React 19 + TypeScript

In-process ServiceContainer (zero HTTP overhead). Streaming via Tauri app.emit/listen events.


Testing ​

y-test-utils ​

Path: crates/y-test-utils/ | Purpose: Shared test mocks and fixtures.

Exports: MockProvider, MockBehaviour, MockRuntime, MockCheckpointStorage, MockSessionStore, MockTranscriptStore, and all fixture helpers via fixtures::*.

Released under the MIT License.