|
Entropic 2.11.1
Local-first agentic inference engine
|
Activate model on GPU (WARM → ACTIVE). More...
Classes | |
| struct | AdapterInfo |
| Metadata for a loaded LoRA adapter. More... | |
| class | AdapterManager |
| LoRA adapter lifecycle manager. More... | |
| class | AgentEngine |
| Core agent execution engine. More... | |
| struct | AsyncFinalState |
| Handle entropic.context_clear. More... | |
| struct | AuditEntry |
| A single audit log entry for one MCP tool call. More... | |
| struct | AuditHookContext |
| Context passed to AuditLogger hook via user_data pointer. More... | |
| struct | AuditLogConfig |
| Audit log configuration within StorageConfig. More... | |
| class | AuditLogger |
| JSONL audit logger for MCP tool calls. More... | |
| struct | BackendInfo |
| Backend metadata for introspection. More... | |
| class | BashServer |
| Bash MCP server for shell command execution. More... | |
| struct | CacheEntry |
| Single cached KV state snapshot. More... | |
| struct | CacheKey |
| 64-bit hash used as cache lookup key. More... | |
| struct | CacheKeyHash |
| Hash function for CacheKey in unordered containers. More... | |
| struct | CacheStats |
| Cumulative cache performance counters. More... | |
| class | ChatAdapter |
| Concrete base class for chat format adapters (80% logic). More... | |
| class | CheckErrorsTool |
| Stub tool for LSP error checking. More... | |
| struct | ChildContextInfo |
| Resolved tier information for building child delegation contexts. More... | |
| struct | ClearSelfTodosDirective |
| Clear self-directed todos (engine no-op). More... | |
| struct | CompactionConfig |
| Auto-compaction configuration. More... | |
| class | CompactionManager |
| Manages automatic context compaction. More... | |
| struct | CompactionResult |
| Result of a compaction operation. More... | |
| struct | CompactorEntry |
| A registered compactor entry. More... | |
| class | CompactorRegistry |
| Per-identity compactor registry and dispatch. More... | |
| struct | CompleteDirective |
| Signal explicit completion. More... | |
| class | CompleteTool |
| Tool for signaling task completion. More... | |
| struct | ConstitutionalValidationConfig |
| Constitutional validation pipeline configuration. More... | |
| class | ConstitutionalValidator |
| Post-generation constitutional compliance validator. More... | |
| struct | ContentPart |
| A single content part within a multimodal message. More... | |
| struct | ContextAnchorDirective |
| Update a keyed persistent context anchor. More... | |
| class | ContextInspectTool |
| Tool for inspecting the current context window contents. More... | |
| class | ContextManager |
| Handles context management for the agentic loop. More... | |
| struct | ContextManagerHooks |
| Engine-level hooks called during context management. More... | |
| struct | ConversationRecord |
| Database record for a conversation. More... | |
| struct | CritiqueResult |
| Structured result from a single critique generation pass. More... | |
| struct | DelegateDirective |
| Delegate a task to a child inference loop. More... | |
| class | DelegateTool |
| Tool for delegating tasks to child inference loops. More... | |
| class | DelegationManager |
| Orchestrates child loop creation and execution. More... | |
| struct | DelegationRecord |
| Database record for a delegation. More... | |
| struct | DelegationResult |
| Result returned from a child delegation loop. More... | |
| class | DiagnoseTool |
| Tool for full engine state snapshots. More... | |
| class | DiagnosticsServer |
| Diagnostics MCP server with LSP client. More... | |
| class | DiagnosticsTool |
| Stub tool for LSP diagnostics retrieval. More... | |
| struct | Directive |
| Base directive — all directives carry a type tag. More... | |
| class | DirectiveProcessor |
| Processes tool directives via registry-based dispatch. More... | |
| struct | DirectiveResult |
| Aggregate result of processing a batch of directives. More... | |
| class | EditFileTool |
| Tool for in-place file editing (string replace or insert). More... | |
| struct | EngineCallbacks |
| Callback function pointer types for engine events. More... | |
| class | EntropicServer |
| gh#32 (v2.1.6) resume More... | |
| class | ExecuteTool |
| Tool for executing shell commands. More... | |
| class | ExternalBridge |
| Unix socket MCP bridge for external client access. More... | |
| class | ExternalMCPClient |
| Client for an external MCP server (stdio or SSE). More... | |
| struct | ExternalMCPConfig |
| External MCP server configuration (Entropic-as-server). More... | |
| struct | ExternalServerConfig |
| Parsed server entry from .mcp.json. More... | |
| struct | ExternalServerEntry |
| Configuration for a single external MCP server entry. More... | |
| class | FileAccessTracker |
| Tracks file read state for read-before-write enforcement. More... | |
| struct | FilesystemConfig |
| Filesystem MCP server configuration. More... | |
| class | FilesystemServer |
| Filesystem MCP server with read-before-write enforcement. More... | |
| class | FollowupTool |
| Recall prior delegation results via storage-backed search. More... | |
| struct | FootprintEstimate |
| An estimate, or an explicit admission that there isn't one. More... | |
| struct | FootprintInputs |
| Everything the estimate needs, with no orchestrator or filesystem. More... | |
| class | Gemma4Adapter |
Fallback adapter for Gemma-4 tiers; owns the <|channel> markers. More... | |
| struct | GenerateResult |
| Result of a generate_response call. More... | |
| struct | GenerationConfig |
| Generation parameters configuration (top-level defaults). More... | |
| struct | GenerationEvents |
| Atomic flags for interrupt/pause signaling. More... | |
| struct | GenerationParams |
| Generation parameters for a single inference call. More... | |
| struct | GenerationResult |
| Result of a single generation call. More... | |
| class | GenericAdapter |
| Generic adapter using <tool_call>JSON</tool_call> format. More... | |
| class | GitAddTool |
| Tool: git add files (space-separated). More... | |
| class | GitBranchTool |
| Tool: git branch -a, or git checkout -b name. More... | |
| class | GitCheckoutTool |
| Tool: git checkout target. More... | |
| class | GitCommitTool |
| Tool: git commit -m "message", optionally git add -A first. More... | |
| class | GitDiffTool |
| Tool: git diff [–staged] [file]. More... | |
| class | GitLogTool |
| Tool: git log -N [–oneline]. More... | |
| class | GitResetTool |
| Tool: git reset HEAD [files]. More... | |
| class | GitServer |
| Git MCP server for version control operations. More... | |
| class | GitStatusTool |
| Tool: git status –short. More... | |
| class | GlobTool |
| Tool for recursive file pattern matching. More... | |
| struct | GPUResourceProfile |
| Named GPU resource profile for controlling inference hardware knobs. More... | |
| struct | GrammarEntry |
| Metadata for a registered grammar. More... | |
| class | GrammarRegistry |
| Centralized grammar registry for named GBNF grammars. More... | |
| struct | GrammarValidationInterface |
| Grammar validation callbacks injected by the facade. More... | |
| class | GrepTool |
| Tool for regex content search across files. More... | |
| class | HandleApiLock |
| gh#59 (v2.3.1): RAII guard combining api_mutex + log scope. More... | |
| struct | HealthEvent |
| Status change event posted by the monitor thread. More... | |
| class | HealthMonitor |
| Monitors external server connections and handles reconnection. More... | |
| struct | HookEntry |
| A single registered hook entry. More... | |
| class | HookRegistry |
| Thread-safe hook registration and dispatch. More... | |
| struct | IdentityConfig |
| Full identity configuration. More... | |
| class | IdentityManager |
| Manages the lifecycle of all identities in the engine. More... | |
| struct | IdentityManagerConfig |
| Configuration for the identity manager. More... | |
| class | IgnoreMatcher |
| gitignore-style path matcher (#15, v2.1.4). More... | |
| struct | ImagePreprocessConfig |
| Image preprocessing configuration. More... | |
| class | ImagePreprocessor |
| Image preprocessor — validates, resizes, and normalizes images. More... | |
| class | InferenceBackend |
| Concrete base class for inference backends (80% logic). More... | |
| struct | InferenceConfig |
| Inference-side configuration knobs (v2.1.11). More... | |
| struct | InjectContextDirective |
| Inject a message into the conversation context. More... | |
| class | InspectTool |
| Tool for targeted engine state queries. More... | |
| struct | InterfaceContext |
| Holds orchestrator + tier for C callback user_data. More... | |
| struct | InterruptContext |
| Context for interrupted/paused generation. More... | |
| struct | JsonCursor |
| Lightweight cursor into a JSON string. More... | |
| class | ListDirectoryTool |
| Tool for listing directory contents. More... | |
| class | LlamaCppBackend |
| LlamaCppBackend — common llama.cpp patterns (15% layer). More... | |
| class | LlamaCppSampler |
Sampler adapter that wraps a llama_sampler* chain. More... | |
| class | LlamaCppSamplerFactory |
| Factory that builds entropic's canonical llama_sampler chain. More... | |
| class | LlamaCppTokenizer |
| Tokenizer adapter that forwards to llama.cpp's vocab API. More... | |
| struct | LogprobResult |
| Per-token log-probability evaluation result. More... | |
| struct | LoopConfig |
| Configuration for the agentic loop. More... | |
| struct | LoopContext |
| Mutable state carried through the agentic loop. More... | |
| struct | LoopMetrics |
| Metrics collected during loop execution. More... | |
| struct | LSPConfig |
| LSP integration configuration. More... | |
| struct | LSPServerConfig |
| Configuration for a single LSP server. More... | |
| class | MCPAuthorizationManager |
| Per-identity MCP authorization with runtime grant/revoke. More... | |
| struct | MCPConfig |
| MCP server configuration. More... | |
| class | MCPJsonDiscovery |
| Discovers external MCP servers from .mcp.json files. More... | |
| struct | MCPKey |
| A single authorized MCP key with access level. More... | |
| struct | MCPKeyInterface |
| MCP key management callbacks injected by the facade. More... | |
| class | MCPKeySet |
| Per-identity set of authorized MCP tool keys. More... | |
| class | MCPServerBase |
| Concrete base class for MCP servers (80% logic). More... | |
| struct | Message |
| A message in a conversation. More... | |
| struct | MessageRecord |
| Database record for a message. More... | |
| struct | Migration |
| A single named migration. More... | |
| struct | ModelConfig |
| Model configuration for a single tier. More... | |
| class | ModelOrchestrator |
| Multi-model lifecycle and routing orchestrator. More... | |
| struct | ModelsConfig |
| Configuration for all models (tiers + router). More... | |
| class | Nemotron3Adapter |
| Nemotron 3 chat adapter (hybrid Mamba-Transformer family). More... | |
| struct | NotifyPresenterDirective |
| Generic UI notification passthrough. More... | |
| struct | ParsedConfig |
| Full parsed configuration. More... | |
| struct | ParsedModelResponse |
| Content and tool calls extracted from one raw emission. More... | |
| struct | ParseResult |
| Parsed tool call result: cleaned content + extracted calls. More... | |
| struct | PendingDelegation |
| Pending single delegation (stored by dir_delegate handler). More... | |
| struct | PendingPipeline |
| Pending multi-stage pipeline (stored by dir_pipeline handler). More... | |
| class | PermissionManager |
| Permission manager for MCP tool access control. More... | |
| class | PermissionPersister |
| Read-modify-write permission patterns in YAML config. More... | |
| struct | PermissionPersistInterface |
| Permission persistence interface. More... | |
| struct | PermissionsConfig |
| Tool permission configuration. More... | |
| struct | PhaseChangeDirective |
| Switch the active inference phase. More... | |
| class | PhaseChangeTool |
| Tool for switching inference phase. More... | |
| struct | PhaseConfig |
| Inference parameters for a single identity phase. More... | |
| struct | PipelineDirective |
| Execute a multi-stage delegation pipeline. More... | |
| class | PipelineTool |
| Tool for multi-stage delegation pipelines. More... | |
| class | PluginServer |
| A loaded MCP server plugin and its C-ABI entry points. More... | |
| struct | PreconditionCheck |
| Outcome of precondition checks for a single tool call. More... | |
| struct | PreprocessedImage |
| Preprocessed image ready for vision encoder. More... | |
| class | ProfileRegistry |
| Centralized registry for named GPU resource profiles. More... | |
| class | PromptCache |
| Host-memory KV cache with LRU eviction. More... | |
| struct | PromptCacheConfig |
| Prompt caching configuration. More... | |
| class | PruneContextTool |
| Tool for pruning old messages from context. More... | |
| struct | PruneMessagesDirective |
| Prune old tool results from context. More... | |
| class | Qwen35Adapter |
| Qwen 3.5 MoE chat adapter (20% override layer). More... | |
| class | Qwen36Adapter |
| Qwen 3.6 MoE chat adapter. More... | |
| class | ReadFileTool |
| Tool for reading file contents with line numbering. More... | |
| struct | ReconnectConfig |
| Reconnection policy configuration for external MCP servers. More... | |
| class | ReconnectPolicy |
| Exponential backoff with jitter for reconnection attempts. More... | |
| class | ResponseGenerator |
| Handles model response generation, tier routing, pause/injection. More... | |
| class | ResumeDelegationTool |
| Resume a prior delegation with its conversation seeded. More... | |
| struct | RoutingConfig |
| Configuration for model routing. More... | |
| struct | RoutingResult |
| Result metadata from a routing decision. More... | |
| class | Sampler |
| Pure-virtual per-generation sampler used by the decode loop. More... | |
| class | SamplerFactory |
| Factory that materializes a Sampler from GenerationParams. More... | |
| struct | SandboxInfo |
| Identifies one delegation's sandbox directory. More... | |
| class | SandboxManager |
| Create, finalize, and discard per-delegation filesystem sandboxes. More... | |
| struct | SandboxResult |
| Final artifact emitted by a finalized sandbox. More... | |
| class | ScopedSandbox |
| RAII directory swapper for sandbox-scoped tool execution. More... | |
| class | SecondaryModelLoader |
| Role-keyed lifecycle manager for non-primary models. More... | |
| struct | ServerInfo |
| Runtime state of a connected MCP server. More... | |
| class | ServerManager |
| Manages MCP server instances and routes tool calls. More... | |
| struct | ServerResponse |
| Structured result from tool execution. More... | |
| class | SessionLogger |
| Manages session_model.log for raw streaming content. More... | |
| struct | SpeculativeConfig |
Speculative-decoding configuration (inference.speculative. More... | |
| struct | SpeculativeRunState |
| Bundles per-kernel-run mutable state to keep the loop body focused on its responsibility (knots: cognitive ≤ 15, ≤ 3 returns). More... | |
| class | SqliteDatabase |
| Thread-safe SQLite database wrapper. More... | |
| class | SqliteStorageBackend |
| SQLite-based storage backend. More... | |
| class | SSETransport |
| SSE transport: HTTP GET for event stream, POST for requests. More... | |
| class | StdioTransport |
| Stdio transport: fork/exec child, pipe stdin/stdout. More... | |
| struct | StopProcessingDirective |
| Stop processing remaining tool calls. More... | |
| struct | StorageConfig |
| Storage backend configuration. More... | |
| struct | StorageInterface |
| Storage interface for conversation persistence. More... | |
| struct | StreamAccumulator |
| Context passed to the streaming token callback. More... | |
| class | StreamThinkFilter |
| Streaming filter that removes <think> blocks from output. More... | |
| struct | ThinkMarkers |
| The reasoning-block delimiters a model family emits (gh#108). More... | |
| class | ThroughputTracker |
| EWMA-based throughput tracker for generation budgeting. More... | |
| struct | TierChangeDirective |
| Request a tier change. More... | |
| struct | TierConfig |
| Tier-specific model configuration. More... | |
| struct | TierResolutionInterface |
| Tier resolution callbacks for delegation and auto-chain. More... | |
| struct | TierSamplerOverrides |
| Per-tier sampler overrides parsed from identity frontmatter. More... | |
| struct | TodoCallbacks |
| Callback type for saving/restoring todo list state. More... | |
| struct | TodoItem |
| Single todo entry. More... | |
| class | TodoTool |
| Tool for managing a persistent todo list. More... | |
| class | TokenCounter |
| Track token usage across conversation. More... | |
| class | Tokenizer |
| Pure-virtual tokenizer surface used by the inference backend. More... | |
| class | ToolBase |
| Abstract base class for individual MCP tools. More... | |
| struct | ToolCall |
| A tool call request parsed from model output. More... | |
| class | ToolCallHistory |
| Fixed-size ring buffer of recent tool calls. More... | |
| struct | ToolCallRecord |
| Lightweight record of a recent tool call for introspection. More... | |
| struct | ToolDefinition |
| Parsed tool definition from JSON schema file. More... | |
| struct | ToolExecutionInterface |
| Tool execution interface for the engine. More... | |
| class | ToolExecutor |
| Processes tool calls from model output. More... | |
| struct | ToolExecutorHooks |
| Engine-level hooks called during tool processing. More... | |
| class | ToolRegistry |
| Manages a collection of ToolBase instances. More... | |
| struct | ToolResult |
| Result of a tool execution. More... | |
| class | Transport |
| Abstract transport for external MCP communication. More... | |
| struct | ValidationContext |
| Context passed through hook user_data. More... | |
| struct | ValidationResult |
| struct | Violation |
| A single constitutional violation found during critique. More... | |
| class | WebFetchTool |
| Tool for fetching web page content by URL. More... | |
| class | WebSearchTool |
| Tool for web search queries. More... | |
| class | WebServer |
| Web MCP server for web fetch and search. More... | |
| class | WriteFileTool |
| Tool for writing file contents with read-before-write. More... | |
Typedefs | |
| using | CompactorFn = std::function< CompactionResult(const std::vector< Message > &messages, const CompactionConfig &config, const std::string &identity)> |
| Internal C++ compactor function type. | |
| using | RunChildLoopFn = void(*)(LoopContext &ctx, void *user_data) |
| Callback type for running a child engine loop. | |
| using | DirectiveHandler = std::function< void(LoopContext &ctx, const Directive &directive, DirectiveResult &result)> |
| Directive handler function type. | |
| using | ToolExecutionFn = std::vector< Message >(*)(LoopContext &ctx, const std::vector< ToolCall > &tool_calls, void *user_data) |
| Tool execution callback type. | |
| using | PermissionPersistFn = void(*)(const char *pattern, bool allow, void *user_data) |
| Permission persistence callback type. | |
| using | TokenCallback = void(*)(const char *, size_t, void *) |
| Token callback type matching the C API signature. | |
Enumerations | |
| enum class | IdentityOrigin : uint8_t { STATIC = 0 , DYNAMIC = 1 } |
| Origin of an identity – how it was created. More... | |
| enum class | AgentState : int { IDLE = ENTROPIC_AGENT_STATE_IDLE , PLANNING = ENTROPIC_AGENT_STATE_PLANNING , EXECUTING = ENTROPIC_AGENT_STATE_EXECUTING , WAITING_TOOL = ENTROPIC_AGENT_STATE_WAITING_TOOL , VERIFYING = ENTROPIC_AGENT_STATE_VERIFYING , DELEGATING = ENTROPIC_AGENT_STATE_DELEGATING , COMPLETE = ENTROPIC_AGENT_STATE_COMPLETE , ERROR = ENTROPIC_AGENT_STATE_ERROR , INTERRUPTED = ENTROPIC_AGENT_STATE_INTERRUPTED , PAUSED = ENTROPIC_AGENT_STATE_PAUSED } |
| C++ enum class for agent execution states. More... | |
| enum class | InterruptMode { CANCEL , PAUSE , INJECT } |
| How to handle generation interrupt. More... | |
| enum class | ToolApproval { DENY , ALLOW , ALWAYS_DENY , ALWAYS_ALLOW } |
| Tool approval responses from user. More... | |
| enum class | BudgetMode { off , tokens , wall_clock } |
| Thinking-budget gating mode. More... | |
| enum class | BackendCapability : int { KV_CACHE = 0 , HIDDEN_STATE = 1 , STREAMING = 2 , RAW_COMPLETION = 3 , GRAMMAR = 4 , LORA_ADAPTERS = 5 , MULTI_SEQUENCE = 6 , TOKENIZER = 7 , LOG_PROBS = 8 , VISION = 9 , SPECULATIVE_DECODING = 10 , PROMPT_CACHING = 11 , AUDIO = 12 , _COUNT } |
| Capabilities that an inference backend may or may not support. More... | |
| enum class | MCPAccessLevel : uint8_t { NONE = 0 , READ = 1 , WRITE = 2 } |
| MCP tool access level for per-identity authorization. More... | |
| enum class | ModelState : int { COLD = ENTROPIC_MODEL_STATE_COLD , WARM = ENTROPIC_MODEL_STATE_WARM , ACTIVE = ENTROPIC_MODEL_STATE_ACTIVE } |
| C++ enum class for model VRAM lifecycle states. More... | |
| enum class | AdapterState : int { COLD = 0 , WARM = 1 , HOT = 2 } |
| LoRA adapter lifecycle state. More... | |
| enum class | ContentPartType { TEXT , IMAGE } |
| Content part type discriminant. More... | |
| enum class | ToolResultKind { ok = 0 , error , rejected_duplicate , rejected_schema , rejected_precondition , ok_empty , delegation_failed , rejected_anti_spiral , rejected_unauthorized } |
| Categorical outcome of a single tool invocation. More... | |
| enum class | ValidationVerdict { passed = 0 , revised , rejected_reverted_length , rejected_max_revisions , skipped , paused_pending_consumer , passed_consumer_override } |
| Result of the full validation pipeline (critique + optional revision). More... | |
| enum class | EmptyContentCause { not_empty , budget_truncated , model_stopped , unknown } |
| Why a turn produced tokens but delivered no content. More... | |
| enum class | GrammarSource { none , request , tool_call , count } |
| Which source, if any, constrains the decode. More... | |
| enum class | Offload { none , full , partial_unknown } |
| Where a tier's weights land, as far as the estimate can tell. More... | |
Functions | |
| const char * | agent_state_name (AgentState state) |
| Get the string name for an AgentState value. | |
| std::vector< ToolCall > | recover_action_envelope_calls (const std::string &raw) |
| gh#88: recover tool calls a gemma model parroted as bare-JSON. | |
| void | apply_action_envelope_recovery (std::vector< ToolCall > &calls, const std::string &raw) |
| gh#88: substitute recovered bare-JSON calls when a reliable (PEG_GEMMA4 / gemma) parse produced none; logs the recovery. | |
| void | coerce_string_typed_args (std::vector< ToolCall > &calls, const std::string &tools_json) |
| gh#90: coerce numeric scalars back to strings for string-typed tool parameters. | |
| InferenceInterface | build_orchestrator_interface (ModelOrchestrator *orchestrator, const std::string &default_tier, InterfaceContext **out_context) |
| Build an InferenceInterface wired to an orchestrator. | |
| void | destroy_orchestrator_interface (InterfaceContext *context) |
| Free a context returned by build_orchestrator_interface(). | |
| ENTROPIC_EXPORT void | apply_tier_sampler_overrides (GenerationParams ¶ms, const TierSamplerOverrides &ov) |
| Apply per-tier sampler overrides to params. | |
| std::filesystem::path | compute_socket_path (const std::filesystem::path &project_dir) |
| Compute project-unique Unix socket path for self-detection. | |
| bool | is_blocked_env_var (const std::string &key) |
| Environment variable blocklist for .mcp.json env field. | |
| ToolDefinition | load_tool_definition (const std::string &tool_name, const std::string &server_prefix, const std::string &data_dir) |
| Load a tool definition from a JSON file. | |
| std::string | summarize_params (const std::string &args_json) |
| Extract top-level JSON keys as a comma-separated summary. | |
| std::string | truncate_result (const std::string &text, size_t max_len) |
| Truncate a string to max_len characters with "..." suffix. | |
| nlohmann::json | audit_entry_to_json (const AuditEntry &entry) |
| Serialize AuditEntry fields to a JSON object. | |
| bool | audit_entry_from_json (const nlohmann::json &j, AuditEntry &entry) |
| Deserialize AuditEntry fields from a JSON object. | |
| void | populate_from_hook_context (AuditEntry &entry, const AuditHookContext &ctx) |
| Populate AuditEntry fields from AuditHookContext state. | |
| std::string | generate_uuid () |
| Generate a UUID v4 string. | |
| std::string | utc_timestamp () |
| Get current UTC time as ISO 8601 string. | |
| ConversationRecord | make_conversation (const std::string &title="New Conversation", const std::optional< std::string > &project_path=std::nullopt, const std::optional< std::string > &model_id=std::nullopt) |
| Create a new ConversationRecord with generated UUID and timestamps. | |
| DelegationRecord | make_delegation (const std::string &parent_conversation_id, const std::string &child_conversation_id, const std::string &delegating_tier, const std::string &target_tier, const std::string &task) |
| Create a new DelegationRecord with generated UUID and timestamp. | |
| const char * | mcp_access_level_name (MCPAccessLevel level) |
| Convert MCPAccessLevel to string representation. | |
| bool | parse_mcp_access_level (const std::string &name, MCPAccessLevel &out) |
| Parse MCPAccessLevel from string. | |
| ModelConfig | make_default_draft_model_config () |
| Speculative decoding configuration (v2.1.11, gh#36). | |
| std::string | extract_text (const std::vector< ContentPart > &parts) |
| Extract concatenated text from content parts. | |
| bool | has_images (const std::vector< ContentPart > &parts) |
| Check if content parts contain any image parts. | |
| std::vector< Message > | parse_messages_json (const char *json_str) |
| Parse a JSON array of messages into a vector of Message. | |
| bool | any_message_has_images (const std::vector< Message > &messages) |
| Convenience: true if any message carries image content_parts. | |
| const char * | result_kind_to_string (ToolResultKind kind) |
| Serialize a ToolResultKind to its wire-stable string form. | |
| static void | partition_messages (const std::vector< Message > &messages, size_t start, std::vector< const Message * > &user_msgs, std::vector< const Message * > &assistant_msgs, int &stripped_count) |
Partition messages (from start) into user/assistant/stripped. | |
| static std::vector< Message > | assemble_compacted (const Message *system_msg, Message summary_msg, const std::vector< const Message * > &user_msgs, const std::vector< const Message * > &assistant_msgs) |
| Assemble the compacted list: system, summary, users, last asst. | |
| static bool | is_tool_result (const Message &msg) |
| Extract original user task from messages. | |
| static std::string | find_tagged (const std::vector< Message > &messages, const std::string &source) |
| Find the first message matching a source tag. | |
| static std::string | find_first_user_task (const std::vector< Message > &messages) |
| Find the first user-role message that isn't a tool result. | |
| static std::string | json_escape (const std::string &input) |
| Save pre-compaction snapshot via storage interface. | |
| static std::string | serialize_messages_json (const std::vector< Message > &messages) |
| Serialize messages to minimal JSON array. | |
| static const char * | json_escape_char (char c) |
| Map a character to its JSON escape sequence. | |
| static std::string | json_escape (const std::string &input) |
| Escape a string for JSON embedding. | |
| static std::string | serialize_messages (const std::vector< Message > &messages) |
| Serialize messages to minimal JSON array. | |
| static std::string | serialize_config (const CompactionConfig &config, const std::string &identity, int token_count) |
| Serialize compaction config + identity to JSON. | |
| static void | json_skip_ws (JsonCursor &c) |
| Skip whitespace in a JSON cursor. | |
| static char | json_unescape_char (char ch) |
| Decode one JSON escape sequence character. | |
| static bool | json_read_string (JsonCursor &c, std::string &out) |
| Read a JSON quoted string from cursor. | |
| static void | json_skip_composite (JsonCursor &c) |
| Skip a JSON array or object in cursor (nested-aware). | |
| static void | json_skip_value (JsonCursor &c) |
| Skip one JSON value (string, primitive, array, or object). | |
| static bool | json_read_content_part_field (JsonCursor &c, std::string &type_val, std::string &text_val) |
| Read one field of a content part object into type/text. | |
| static bool | json_parse_content_part (JsonCursor &c, std::string &type_val, std::string &text_val) |
| Parse one content part object, extract type and text. | |
| static void | append_text_part (const std::string &type_val, const std::string &text_val, std::string &text) |
| Append text from a content part if type == "text". | |
| static char | json_skip_to_element (JsonCursor &c) |
| Read one content part object from an array cursor. | |
| static bool | json_read_one_content_part (JsonCursor &c, std::string &text) |
| Parse one content part object and append text if applicable. | |
| static bool | json_extract_text_from_array (JsonCursor &c, std::string &text) |
| Extract concatenated text from a JSON content array. | |
| static bool | json_read_field (JsonCursor &c, Message &msg) |
| Read one key:value pair and apply to message fields. | |
| static bool | json_parse_message (JsonCursor &c, Message &msg) |
| Parse one JSON object into a Message (role + content). | |
| static bool | json_parse_array (JsonCursor &c, std::vector< Message > &messages) |
| Parse message objects from a JSON array cursor. | |
| static bool | parse_messages (const char *json, std::vector< Message > &messages) |
| Parse a JSON array of message objects. | |
| static bool | is_pure_tool_call (const std::string &content) |
| Check if content is a pure tool call with no prose. | |
| static std::string | strip_reasoning (const std::string &content, const std::string &open, const std::string &close) |
| Strip reasoning blocks from content before critique (gh#108). | |
| static std::string | json_escape (const std::string &s) |
| Escape a string for JSON embedding. | |
| static ent_delegation_result_t | build_delegation_result_struct (const SandboxInfo &sb_info, const SandboxResult &sandbox_result, const DelegationResult &result, const std::vector< const char * > &files_c, size_t files_len) |
| Deliver a finalized patch to consumer or pending/. | |
| static std::string | pipeline_context (size_t stage_idx, size_t total, const std::vector< std::string > &stages, const std::string &prior_output) |
| Build pipeline context prefix for a stage. | |
| static void | fire_hook_info (const HookInterface &hooks, entropic_hook_point_t point, const char *json) |
| Fire an informational hook if the interface is wired. | |
| static void | fire_loop_start_hook (const HookInterface &hooks, const LoopContext &ctx) |
| Build + fire the ON_LOOP_START info hook. | |
| static void | fire_loop_end_hook (const HookInterface &hooks, const LoopContext &ctx) |
| Build + fire the ON_LOOP_END info hook. | |
| static void | fire_loop_iteration_hook (const HookInterface &hooks, const LoopContext &ctx) |
| Build + fire the ON_LOOP_ITERATION info hook. | |
| static void | fire_context_assemble_hook (const HookInterface &hooks, const LoopContext &ctx) |
| Build + fire the ON_CONTEXT_ASSEMBLE info hook. | |
| static void | remove_anchor_messages (LoopContext &ctx, const std::string &key) |
| Remove messages with a specific anchor key. | |
| static double | now_seconds () |
| Get current time as seconds since epoch. | |
| static ToolCall | build_tool_call_from_json (const nlohmann::json &obj, const std::string &tc_str) |
| Parse tool calls from raw model output. | |
| static std::vector< ToolCall > | decode_tool_calls_json (const std::string &tc_str) |
| Decode a JSON tool-calls array string into ToolCall vector. | |
| static const std::array< const char *, 256 > & | json_escape_table () |
| 256-entry table mapping bytes to JSON escape sequences. | |
| static std::string | json_escape_engine (const std::string &s) |
| JSON-escape a string (no surrounding quotes). | |
| static std::string | build_tool_manifest (const std::vector< Message > &messages) |
| Build tool call manifest from conversation messages. | |
| static std::string | format_tool_evidence_entry (const Message &msg, size_t chars_per_result) |
| Format one tool-result message for the evidence block. | |
| static std::string | build_tool_evidence (const std::vector< Message > &messages, size_t max_results, size_t chars_per_result) |
| Build un-pruned tool-result evidence for the validator. | |
| static std::string | enrich_manifest_with_history (const std::string &base, const ToolExecutionInterface &tool_exec) |
| Append executor history (if any) to the tool manifest. | |
| static std::string | extract_system_prompt (const std::vector< Message > &messages) |
| Extract the first system message content from messages. | |
| static std::string | build_tool_results_json (const std::vector< Message > &messages) |
| Build a JSON array of tool results from context messages. | |
| static void | run_child_loop_trampoline (LoopContext &ctx, void *user_data) |
| Trampoline for DelegationManager to call engine loop. | |
| static void | push_delegation_rejected (LoopContext &ctx) |
| Append a delegation rejection message to the loop context. | |
| static void | push_delegation_cycle_rejected (LoopContext &ctx, const std::string &target) |
| Append a structured cycle-rejection message to the loop context so the model can recover. | |
| static void | push_delegation_result (LoopContext &ctx, const std::string &target, const DelegationResult &result) |
| Append a delegation result message to the loop context. | |
| static void | push_delegation_repeat_blocked (LoopContext &ctx, const std::string &target, int n) |
| Append a "stop retrying same target" reject message (gh#64). | |
| static std::string | build_coverage_gap_message (const std::string &tier, const DelegationResult &result) |
| Build the [COVERAGE GAP] message body that goes back to lead when a relay-tier child returns coverage_gap=true (#10, v2.1.4). | |
| static void | fold_delegation_summary (LoopContext &ctx, const std::string &summary) |
| gh#119 (v2.9.17): fold child summary into the lead's empty delegate turn. | |
| static void | push_resume_failure (LoopContext &ctx, const std::string &reason, const std::string &delegation_id) |
| Lazy session-scoped SandboxManager accessor (gh#33, v2.1.6). | |
| static std::string | concat_user_echo (const std::vector< Message > &messages) |
| Concatenate user-role message text for session-log echo. | |
| static std::string | join_csv (const std::vector< std::string > &v) |
| Join a vector of strings with comma separators. | |
| static const std::regex | s_name_regex ("^[a-z][a-z0-9_-]{0,63}$") |
| Compiled regex for identity name validation. | |
| static std::string | validate_phases (const std::unordered_map< std::string, PhaseConfig > &phases) |
| Validate all phases in an identity config. | |
| static std::string | validate_fields (const IdentityConfig &config) |
| Validate phases and adapter_path fields. | |
| static entropic_error_t | check_create_preconditions (const IdentityConfig &config, const IdentityManagerConfig &mgr_config, const std::unordered_map< std::string, IdentityConfig > &identities) |
| Check create preconditions before validation. | |
| static entropic_error_t | check_mutable (const std::string &name, const std::unordered_map< std::string, IdentityConfig > &identities, std::unordered_map< std::string, IdentityConfig >::const_iterator &out_it) |
| Check that a mutable identity exists and is dynamic. | |
| static void | log_prompt (const std::vector< Message > &messages, const std::string &tier) |
| Log the full assembled prompt (all messages, no truncation). | |
| static void | stream_token_callback (const char *token, size_t len, void *user_data) |
| Token callback for streaming generation. | |
| static std::string | resolve_stream_finish_reason (int rc, size_t content_size) |
| Resolve a stream's finish_reason from rc + content size. | |
| static void | json_escape_into (const std::string &s, std::string &out) |
| Serialize messages to JSON for inference interface. | |
| static void | serialize_content_parts (const std::vector< ContentPart > &parts, std::string &out) |
| Serialize a single multimodal content_parts array (gh#37, v2.1.8). | |
| static bool | snapshot_git_project (const std::filesystem::path &source, const std::filesystem::path &target) |
| Copy git-tracked + untracked-not-ignored files from a project. | |
| static bool | snapshot_plain_copy (const std::filesystem::path &source, const std::filesystem::path &target) |
| Recursive copy for non-git sources (or sandbox-to-sandbox chains). | |
| static bool | capture_diff (const std::filesystem::path &base, const std::filesystem::path &head, std::string &patch) |
Run git diff --no-index between base and head, capture patch. | |
| static void | trim_path_prefix (std::string &line, std::string p) |
Strip a directory prefix p from the front of line. | |
| static std::vector< std::filesystem::path > | diff_files (const std::filesystem::path &base, const std::filesystem::path &head) |
List files differing between base and head via diff -rq-style logic. | |
| static int | utf8_char_len (unsigned char byte) |
| Count expected bytes in a UTF-8 sequence from lead byte. | |
| static std::string | rpc_ok (const json &id, const json &result) |
| Build a JSON-RPC success response. | |
| static std::string | rpc_err (const json &id, int code, const std::string &msg) |
| Build a JSON-RPC error response. | |
| static json | tool_text (const std::string &text) |
| Wrap text in MCP tool result shape. | |
| static json | tool_definitions () |
| MCP tool definitions exposed by the bridge. | |
| static void | write_json_line (int fd, const json &msg) |
| Write a JSON-RPC line to a socket fd. | |
| static void | send_progress (int fd, const std::string &token_text, const std::string &progress_token) |
| Send an MCP progress notification with a text token. | |
| static json | final_answer_from_context (entropic_handle_t handle) |
| Read the live conversation and render the operator-visible answer. | |
| static json | handle_ask_plain (entropic_handle_t handle, const json &args) |
| Handle entropic.ask — non-streaming path (gh#115, v2.9.12). | |
| static json | handle_ask (entropic_handle_t handle, const json &args, int client_fd, const std::string &call_id) |
| Handle entropic.ask — stream tokens then return final text. | |
| static json | handle_status (entropic_handle_t handle) |
| Handle entropic.status. | |
| static AsyncFinalState | derive_async_final_state (entropic_handle_t handle, entropic_error_t err, char *result_json) |
| Translate entropic_run's return code into a final task state. | |
| static bool | mark_tasks_cancelling (ExternalBridge *bridge) |
| Mark every queued/running task as cancelling. | |
| static bool | any_cancelling_left (ExternalBridge *bridge) |
| True while any task is still phase=cancelling. | |
| static void | cancel_inflight_async_tasks (entropic_handle_t handle, ExternalBridge *bridge) |
| Cancel any async tasks currently running on the bridge. | |
| static json | handle_clear (entropic_handle_t handle, ExternalBridge *bridge) |
| entropic.context_clear MCP tool handler. | |
| static json | handle_count (entropic_handle_t handle) |
| Handle entropic.context_count. | |
| static std::string | generate_task_id () |
| Generate a simple UUID-like task ID. | |
| static json | dispatch_ask (entropic_handle_t handle, ExternalBridge *bridge, const json &args, int client_fd, const std::string &call_id) |
| Route entropic.ask — sync (streaming) or async. | |
| static json | dispatch_tool (entropic_handle_t handle, ExternalBridge *bridge, const json ¶ms, int client_fd, const std::string &call_id) |
| Dispatch a tools/call to the appropriate handler. | |
| static void | prepare_socket_dir (const std::filesystem::path &parent) |
| Prepare the socket containing directory with 0700 perms. | |
| static bool | socket_path_safe (const std::filesystem::path &path) |
| Reject a pre-existing path that is a symlink or non-socket. | |
| static bool | bind_and_listen (int fd, const std::filesystem::path &path) |
| Bind+listen on an AF_UNIX socket, applying 0600 perms. | |
| static int | create_listen_socket (const std::filesystem::path &path) |
| Create, bind, and listen on a unix domain socket. | |
| static bool | peer_uid_matches (int client_fd) |
| Validate that the connecting peer shares the engine's UID. | |
| static std::string | read_line (int fd) |
| Read one newline-delimited line from a socket fd. | |
| static json | initialize_result () |
| Build the MCP initialize response payload. | |
| static void | phase_observer_cb (int state, void *ud) |
| State observer that projects VERIFYING onto task phase. | |
| static const char * | sentinel_suffix_for_status (const std::string &status) |
| Map a terminal status string to a sentinel filename suffix. | |
| static std::optional< ToolCall > | action_envelope_to_call (const nlohmann::json &j) |
| Map one parsed JSON object to a recovered ToolCall. | |
| static std::unordered_set< std::string > | tool_string_props (const nlohmann::json &tools, const std::string &name) |
| String-typed property names for a tool in the staged MCP defs. | |
| static void | coerce_call_string_args (ToolCall &tc, const nlohmann::json &tools) |
| Coerce one call's numeric args to strings per the tool schema. | |
| static std::optional< ToolCall > | parse_recovered_tool_call (const std::string &fixed) |
| Parse a brace/quote-fixed JSON string into a ToolCall. | |
| static std::optional< ToolCall > | regex_recovered_tool_call (const std::string &json_str) |
| Last-ditch recovery: pull a tool name out via regex. | |
| logger | info ("JSON recovery attempt: {} chars", json_str.size()) |
| std::unique_ptr< ChatAdapter > | create_adapter (const std::string &name, const std::string &tier_name, const std::string &identity_prompt) |
| Create adapter by name (gh#87 Phase D hybrid). | |
| static nlohmann::json | build_tool_defs (const std::vector< std::string > &tool_jsons) |
Build the OpenAI-function <tools> JSON array for injection. | |
| template<typename Tok > | |
| std::size_t | batch_shared_prefix_len (const std::vector< std::vector< Tok > > &seqs) |
| Longest shared token prefix across N request sequences (gh#98). | |
| bool | batch_is_viable (std::size_t n, int n_parallel, std::size_t shared, bool hybrid, std::size_t total_suffix, int n_batch) |
| Decide whether the same-prefix batch fast-path is safe + worthwhile. | |
| uint64_t | query_device_free_vram_bytes () |
| Free VRAM on the first GPU device ggml reports, in bytes. | |
| EmptyContentCause | diagnose_empty_content (bool content_empty, bool produced_tokens, const std::string &finish_reason) |
| Classify an empty-content turn from what the decode reported. | |
| std::string | explain_empty_content (EmptyContentCause cause) |
| Operator-facing explanation for an empty-content turn. | |
| static std::optional< GrammarEntry > | build_grammar_entry (const std::filesystem::path &path) |
| Load all bundled grammars from a directory. | |
| constexpr int | grammar_source_count () |
| Number of declared grammar sources, sentinel excluded. | |
| GrammarSource | resolve_grammar_source (const std::string &request_grammar, const std::string &tool_grammar) |
| Resolve which grammar wins. | |
| bool | grammar_sources_collide (const std::string &request_grammar, const std::string &tool_grammar) |
| Whether both sources are active — a config error worth reporting. | |
| static std::vector< uint8_t > | read_image_bytes (const std::filesystem::path &path, size_t max_file_size) |
| Validate + read an image file fully into a byte buffer. | |
| static std::vector< Message > | parse_msgs (const char *json_str) |
| Parse JSON message array into Message vector. | |
| template<typename T > | |
| static void | assign_if_present (const nlohmann::json &j, const char *key, T &dst) |
| Conditionally assign a typed JSON field into a destination. | |
| static void | parse_logit_bias_into (const nlohmann::json &j, std::unordered_map< int32_t, float > &dst) |
Populate logit_bias map from a JSON object of token→bias. | |
| static GenerationParams | parse_params (const char *json_str) |
| Parse generation params from JSON string. | |
| static std::string | extract_tier (const char *json_str, const std::string &default_tier) |
| Extract tier name from params JSON, falling back to default. | |
| static char * | dup (const std::string &s) |
| Heap-allocate a C string copy. | |
| static int | iface_generate (const char *msgs_json, const char *params_json, char **result_json, void *user_data) |
| Generate via orchestrator. | |
| static int | iface_generate_stream (const char *msgs_json, const char *params_json, void(*on_token)(const char *, size_t, void *), void *token_ud, int *cancel, void *user_data) |
| Streaming generate via orchestrator. | |
| static int | iface_generate_with_cancel (const char *msgs_json, const char *params_json, char **result_json, int *cancel, void *user_data) |
| Batch generate with cancel via orchestrator (gh#81, v2.4.2). | |
| static int | iface_route (const char *msgs_json, char **result_json, void *user_data) |
| Route messages to tier via orchestrator. | |
| static int | iface_complete (const char *prompt, const char *params_json, char **result_json, void *user_data) |
| Raw text completion via orchestrator. | |
| static std::vector< ToolCall > | tc_from_json_obj (const nlohmann::json &j) |
| Build a ToolCall from a parsed JSON object with name/tool + arguments/parameters. | |
| static std::vector< ToolCall > | try_fenced_json_call (const std::string &raw) |
| Extract a tool call from a single fenced json block in raw model output (gh#122). | |
| static std::string | find_unique_args_match (const nlohmann::json &obj, const nlohmann::json &tools) |
| Find the unique tool whose required params are all present in obj. | |
| static std::optional< nlohmann::json > | extract_args_only_fence (const std::string &raw) |
| Extract and validate the fenced JSON block for args-only inference. | |
| static std::vector< ToolCall > | try_fenced_args_object_call (const std::string &raw, const std::string &tools_json) |
| Try to synthesise a tool call from a fenced args-only JSON object (gh#127). | |
| static void | apply_fenced_fallbacks (const std::string &raw, LlamaCppBackend *llama, std::vector< ToolCall > &calls) |
| Apply fenced-json and fenced-args-only fallback parsers (gh#122, gh#127). | |
| static void | parse_via_adapter (ModelOrchestrator *orch, const std::string &raw, const std::string &tier, std::string &out_cleaned, std::vector< ToolCall > &out_calls) |
| Parse tool calls via the adapter for the given tier (gh#89). | |
| static int | iface_parse_tool_calls (const char *raw, char **cleaned, char **tool_calls_json, void *user_data) |
| Parse tool calls from raw model output (gh#87 3b). | |
| static int | iface_is_complete (const char *, const char *tool_calls_json, void *) |
| Check if response is complete (no pending tool calls). | |
| static int | effective_n_draft (int n_max) |
| Draft-window size setup_mtp_draft will actually use (gh#106). | |
| static std::vector< llama_chat_message > | to_llama_chat (const std::vector< Message > &messages) |
| Convert engine messages to llama_chat_message views. | |
| static std::vector< common_chat_msg > | to_common_chat (const std::vector< Message > &messages) |
| Convert engine messages to common_chat_msg (gh#86, v2.6.1). | |
| static std::vector< common_chat_tool > | mcp_tools_to_common_chat (const std::string &tools_json) |
| Convert entropic MCP tool JSON to common_chat_tool defs (gh#87). | |
| static ToolCall | to_entropic_tool_call (const common_chat_tool_call &cc) |
| Map a common_chat_tool_call to entropic's ToolCall (gh#87). | |
| static std::optional< common_chat_params > | render_common_chat (llama_model *model, const std::vector< Message > &messages, const GenerationParams ¶ms, const std::vector< common_chat_tool > &tools, bool require_tool_call) |
| Shared common_chat render core for both template paths (gh#87). | |
| static std::string | concat_messages_fallback (const std::vector< Message > &messages) |
| Plain "role: content" join used when templating fails. | |
| void | strip_thinking_channels (std::string &content, std::string *reasoning_out) |
Strip Gemma 4 QAT reasoning channels (<|channel>…<channel|>) from content, accumulating the stripped text into reasoning. | |
| static GenerationResult | batch_error_result (const std::string &msg) |
| Build a single error GenerationResult (gh#98 batch failures). | |
| static void | fill_batch_cell (llama_batch &b, int k, llama_token tok, llama_pos pos, llama_seq_id seq, bool want_logits) |
| Fill one cell of a multi-seq llama_batch. | |
| static void | spec_cleanup (SpeculativeRunState &state) |
| Free everything allocated by the kernel. | |
| static void | spec_build_batch (SpeculativeRunState &state) |
| Build the target batch [id_last, draft0, ..., draftN-1]. | |
| static bool | spec_decode_both (SpeculativeRunState &state) |
| Decode the speculative batch on both contexts. | |
| static int | spec_run_draft (SpeculativeRunState &state) |
| Trigger draft generation via common_speculative_draft. | |
| static std::string | spec_emit_token (SpeculativeRunState &state, llama_token id, const llama_vocab *vocab, int max_tokens, std::function< void(std::string_view)> &on_token, std::atomic< bool > &cancel) |
| Emit on_token for one accepted id, updating state and returning a stop signal when terminating conditions apply. | |
| static void | spec_ckpt_save_dft (SpeculativeRunState &state) |
| Drive one accept round: draft → decode → sample-and-accept → emit tokens. | |
| static void | spec_ckpt_save_tgt (SpeculativeRunState &state) |
| Snapshot target state right before the target decode of the speculative batch (when use_ckpt_tgt + non-empty draft). | |
| static void | spec_ckpt_restore_dft (SpeculativeRunState &state) |
| Restore the draft's pre-draft state so the upcoming target-batch decode on the draft re-fills cleanly. | |
| static void | spec_rollback_partial (SpeculativeRunState &state, common_sampler *smpl_save, std::vector< llama_token > &ids) |
| Partial-acceptance rollback: restore both contexts and the sampler to their pre-draft state, then arrange for the outer loop to re-decode with the partial accept as the new draft. | |
| static void | spec_trim_rejected_drafts (SpeculativeRunState &state) |
| Clear any stale KV positions left by rejected draft tokens. | |
| static bool | spec_commit_accepted (SpeculativeRunState &state, const std::vector< llama_token > &ids, const llama_vocab *vocab, int max_tokens, std::function< void(std::string_view)> &on_token, std::atomic< bool > &cancel) |
| Walk accepted ids, emit tokens via callback, update state. | |
| static int | spec_prepare_draft (SpeculativeRunState &state) |
| Drive one accept round: optional draft generation, decode on both contexts, sample-and-accept, emit tokens (or roll back via checkpoint on partial acceptance). | |
| static bool | spec_accept_round (SpeculativeRunState &state, const llama_vocab *vocab, int max_tokens, std::function< void(std::string_view)> &on_token, std::atomic< bool > &cancel) |
| Run one speculative accept round; return false to stop. | |
| static std::string | spec_check_preconditions (bool target_active, bool draft_active, llama_context *ctx_tgt, llama_context *ctx_dft) |
| Validate speculative preconditions and reject NO-seq_rm. | |
| static std::string | spec_init_sampler_and_decoder (SpeculativeRunState &state, llama_model *model_tgt, const GenerationParams ¶ms, int n_draft_max, const std::string &draft_path, const std::string &tool_grammar, bool tool_grammar_lazy, const std::string &generation_prompt) |
| Initialize the kernel state: clear KV, prefill, sampler, speculative context, batch, and detect FULL-seq_rm checkpoint-mode for target/draft. | |
| static std::string | spec_init_run (SpeculativeRunState &state, llama_model *model_tgt, const std::vector< llama_token > &tokens, const GenerationParams ¶ms, int n_draft_max, const std::string &draft_path, const std::string &tool_grammar, bool tool_grammar_lazy, const std::string &generation_prompt) |
| Initialize speculative run state (prefill + sampler + decoder). | |
| static void | spec_run_loop (SpeculativeRunState &state, const llama_vocab *vocab, int max_tokens, std::function< void(std::string_view)> &on_token, std::atomic< bool > &cancel) |
| Run the accept-round loop until completion / EOS / cancel. | |
| static GenerationResult | spec_finalize (SpeculativeRunState &state, std::chrono::steady_clock::time_point t0) |
| Speculative kernel against an explicit draft backend. | |
| static GenerationResult | spec_run_from_tokens (llama_context *ctx_tgt, llama_context *ctx_dft, llama_model *model_tgt, const std::vector< llama_token > &tokens, const GenerationParams ¶ms, std::function< void(std::string_view)> &on_token, std::atomic< bool > &cancel, int n_draft_max, const std::string &draft_path, std::chrono::steady_clock::time_point t0, const std::string &tool_grammar, bool tool_grammar_lazy, const std::string &generation_prompt) |
| Public entry point for the speculative-decoding kernel. | |
| std::string | mtp_unsupported_reason (float temperature, bool has_grammar, bool streaming) |
| Reason MTP cannot run for a request, or "" when the envelope is safe. | |
| bool | looks_like_mtp_head (int n_layer) |
| True when the model's layer count is consistent with an MTP head GGUF. | |
| std::string | mtp_head_classical_path_error (int n_layer) |
| Actionable error message for gh#107: MTP head on classical path. | |
| static bool | mtp_head_guard_fires (LlamaCppBackend *draft, GenerationResult &result) |
| gh#107: return true (and populate result) when draft looks like an MTP head GGUF routed to the classical separate-draft path. | |
| static void | stage_active_tools (InferenceBackend *model, const GenerationParams ¶ms, bool require_tool_call) |
| Stage the turn's tool defs on the backend for common_chat (gh#87). | |
| static void | apply_adapter_parse (InferenceBackend *model, ChatAdapter *adapter, GenerationResult &result) |
| Split tool calls out of a result (gh#87: common_chat or adapter). | |
| static void | warn_if_content_vanished (const GenerationResult &result) |
| Explain a turn that produced tokens but delivered no content (gh#137). | |
| static void | warn_if_budget_starved_required_turn (const GenerationResult &result, const std::string &tier_name, const std::unordered_map< std::string, TierConfig > &tiers) |
| Diagnose a mandatory-tool turn that ran out of budget (gh#134). | |
| static void | warn_turn_diagnostics (const GenerationResult &result, const std::string &tier_name, const std::unordered_map< std::string, TierConfig > &tiers) |
| Report every post-turn diagnostic from one call site (gh#137). | |
| static void | log_orchestration (const GenerationResult &result, const std::string &selected, const std::string &adapter_name, const GenerationParams ¶ms, double routing_ms, double swap_ms) |
| Log the per-orchestration tier/adapter/timing summary. | |
| static void | stream_token_trampoline (const char *data, std::size_t len, void *ud) |
| Trampoline: bridges TokenCallback C signature to std::function. | |
| static FootprintInputs | footprint_inputs_for (const TierConfig &tier_cfg, uint64_t weights_bytes, int vram_reserve_mb) |
| Gather a tier's footprint inputs for the pure estimator. | |
| static llama_model * | resolve_target_model (const std::shared_ptr< InferenceBackend > &tier_backend) |
| Resolve the active main-tier llama_model* for compat lookup. | |
| static std::string | normalize_grammar_key (const std::string &grammar_value) |
| Normalize a frontmatter grammar value to a registry key. | |
| static nlohmann::json | make_residency_entry (const std::string &name, const std::filesystem::path &path, int context_length, size_t footprint, int vram_reserve_mb, long long last_ms) |
| JSON serialization of the current residency set. | |
| static std::vector< std::string > | required_params (const std::string &tools_json, const std::string &name, bool &found) |
| Required parameter names declared by a tool's inputSchema. | |
| static bool | has_all_required (const nlohmann::json &args, const std::vector< std::string > &required, const std::string &call_name) |
| Verify every required key is present, warning on the first absent one. | |
| static bool | one_call_satisfies_schema (const ToolCall &call, const std::string &tools_json) |
| Check one call's declared required parameters are all present. | |
| bool | calls_satisfy_schema (const std::vector< ToolCall > &calls, const std::string &tools_json) |
| Check that every call's declared required parameters are present. | |
| static bool | try_template_parse (LlamaCppBackend *llama, const std::string &raw, ParsedModelResponse &out) |
| Tool calls from the template parser, when trustworthy. | |
| ParsedModelResponse | parse_model_response (LlamaCppBackend *llama, ChatAdapter *adapter, const std::string &raw) |
| Parse a raw emission: template first, adapter second. | |
| std::string | close_marker_for_format (common_chat_format fmt) |
| Map a resolved common_chat format to its single-tool-call close marker. | |
| void | append_sequential_stop (GenerationParams ¶ms, const std::string &marker) |
| Append a tool-call close marker to params.stop for sequential mode. | |
| std::string | serialize_tool_calls (const std::vector< ToolCall > &calls) |
| Serialize parsed tool calls to the C-ABI JSON array form. | |
| double | kv_scale_for_cache_type (const std::string &type) |
| Cost of a KV cache type relative to f16. | |
| Offload | classify_offload (int gpu_layers) |
| Classify a tier's offload request into a priceable placement. | |
| double | kv_bytes_per_token (const FootprintInputs &in) |
| Per-token KV cost in bytes for this tier's cache configuration. | |
| FootprintEstimate | estimate_vram_footprint (const FootprintInputs &in) |
| Estimate the VRAM a tier will occupy, or report that it cannot. | |
| int | recommend_context_length (const FootprintInputs &in, uint64_t available_bytes) |
| Largest context length that fits, for the "won't fit" recommendation. | |
| template<typename Tok > | |
| std::size_t | common_prefix_len (const std::vector< Tok > &a, const std::vector< Tok > &b) |
| Length of the longest common token prefix of two sequences. | |
| template<typename Tok > | |
| std::size_t | warm_keep_cut (const std::vector< Tok > &resident, const std::vector< Tok > &incoming, long kv_pos_max) |
| Decide how many resident-KV tokens warm-keep may reuse this turn. | |
| static std::vector< std::string > | names_diff (const std::set< std::string > &a, const std::set< std::string > &b) |
Names in a not in b (sorted set difference). | |
| static bool | has_blocked_prefix (const std::string &key) |
| Check if key matches a blocked prefix pattern. | |
| static const char * | directive_type_name (entropic_directive_type_t type) |
| Map directive type enum to wire-format string. | |
| static void | append_prefixed_tools (const std::string &tools_json, const std::string &prefix, nlohmann::json &all) |
| Append a server's tools to an array, prefixing each name. | |
| static bool | is_safe_cwd (const std::string &cwd) |
| Reject working_dir values that would smuggle shell syntax. | |
| static std::pair< std::string, int > | run_popen (const std::string &full_cmd) |
| Run a shell command and capture output. | |
| static std::string | call_provider (char *(*fn)(void *), void *ud) |
| Call a state provider callback and wrap result. | |
| static std::string | call_history_provider (char *(*fn)(int, void *), int max_entries, void *ud) |
| Call history callback with max_entries param. | |
| static std::string | call_docs_provider (char *(*fn)(const char *, void *), const char *section, void *ud) |
| Call docs callback with section param. | |
| static nlohmann::json | build_snapshot (const entropic_state_provider_t &p, bool include_docs, int history_limit) |
| Build the diagnose snapshot JSON. | |
| static std::vector< std::string > | collect_object_keys (const nlohmann::json &j) |
| Collect keys from a JSON object into a vector. | |
| static std::vector< std::string > | collect_array_names (const nlohmann::json &j) |
| Collect "name" fields from a JSON array of objects. | |
| static std::string | list_available_keys (const nlohmann::json &j) |
| List available keys from a JSON value for error messages. | |
| static std::string | filter_json_by_key (const std::string &json_str, const std::string &key, const std::string &label) |
| Filter a JSON value by key (object key or array name). | |
| static std::string | inspect_filterable (char *(*fn)(void *), void *ud, const std::string &key, const std::string &label) |
| Inspect a filterable target (config/identity/tool). | |
| static bool | dispatch_simple_target (const entropic_state_provider_t &p, const std::string &target, const std::string &key, std::string &result) |
| Dispatch inspect for simple (non-filterable) targets. | |
| static bool | dispatch_filterable_target (const entropic_state_provider_t &p, const std::string &target, const std::string &key, std::string &result) |
| Try filterable targets (config/identity/tool). | |
| static std::string | dispatch_inspect (const entropic_state_provider_t &p, const std::string &target, const std::string &key) |
| Dispatch an inspect query to the appropriate provider. | |
| std::string | check_read_gates (FilesystemServer &server, const fs::path &resolved, const std::string &path_str) |
| Execute read_file: resolve, size-check, read, hash, track. | |
| std::regex | compile_grep_or_error (const std::string &pattern, std::string &err) |
| Compile a regex or return a structured tool error. | |
| static std::vector< json > | grep_search (const fs::path &root, const std::vector< std::string > &file_patterns, const std::regex &re, const IgnoreMatcher &ignore) |
| Execute grep: brace-expand the file glob, compile the content regex (error-safe), iterate the tree applying the same classify_glob_entry filter glob uses. | |
| static int | compute_max_read_bytes (const FilesystemConfig &config, int model_context_bytes) |
| Compute max read bytes from config and model context. | |
| static std::pair< std::string, int > | run_git (const std::string &repo_dir, const std::string &git_args) |
| Run a git command in a given directory via popen. | |
| static ServerResponse | make_git_response (const std::string &output, int exit_code) |
| Format a git result as JSON ServerResponse. | |
| static nlohmann::json | record_to_json (const ToolCallRecord &rec) |
| Serialize a single ToolCallRecord to JSON. | |
| static std::string | check_required_fields (const nlohmann::json &schema, const nlohmann::json &args) |
| Check required fields are present. | |
| static std::string | check_enum (const std::string &key, const nlohmann::json &allowed, const nlohmann::json &val) |
| Check one property's enum and type constraints. | |
| static std::string | check_type (const std::string &key, const std::string &type, const nlohmann::json &val) |
| Check a single value against a type constraint. | |
| static std::string | check_property_constraints (const std::string &key, const nlohmann::json &prop, const nlohmann::json &val) |
| Check one property's enum and type constraints. | |
| static std::string | validate_tool_args (const std::string &schema_json, const nlohmann::json &args) |
| Validate tool arguments against the tool's JSON Schema. | |
| static std::string | parse_tool_result_text (const std::string &result_json) |
| Extract the "result" text from an MCP result JSON envelope. | |
| static ToolResultKind | classify_tool_result (const std::string &content) |
| Classify a tool result by its content (error/empty/ok). | |
| static std::vector< std::string > | extract_pipeline_stages (const nlohmann::json &result_json) |
| Extract directives from ServerResponse JSON and process them. | |
| static std::unique_ptr< Directive > | build_complete_directive (const nlohmann::json &result_json) |
| Build a typed Directive from a directive-descriptor JSON. | |
| static std::unique_ptr< Directive > | build_directive (const nlohmann::json &d, const nlohmann::json &result_json) |
| Build a Directive from a parsed directive + result JSON. | |
| static std::optional< std::pair< nlohmann::json, nlohmann::json > > | extract_directive_array (const std::string &raw_result) |
| Pull the "directives" array out of a tool ServerResponse JSON. | |
| static std::string | sanitize_display_name (const std::string &raw) |
| Sanitize a display_name for use as a log-line bracket label. | |
| static std::vector< char * > | build_argv (const std::string &command, const std::vector< std::string > &args) |
| Build a NULL-terminated argv from command + args. | |
| static std::vector< char * > | build_envp (const std::vector< std::string > &env_strs) |
| Build a NULL-terminated envp from env strings. | |
| static std::string | extract_parent_id (const nlohmann::json &j) |
| Extract optional parent_conversation_id from JSON. | |
| static void | parse_result_fields (const nlohmann::json &result, AuditEntry &entry) |
| Parse the result sub-object from JSON into AuditEntry fields. | |
| static std::string | col_text (sqlite3_stmt *stmt, int col) |
| Get text from a sqlite3 column, returning empty string for NULL. | |
| static std::optional< std::string > | col_opt_text (sqlite3_stmt *stmt, int col) |
| Get optional text from a sqlite3 column. | |
| static json | col_nullable_int (sqlite3_stmt *stmt, int col) |
| Get a nullable integer column as a JSON value. | |
| static void | bind_opt_text (sqlite3_stmt *stmt, int idx, const std::optional< std::string > &val) |
| Bind optional text to a parameter position. | |
| static void | bind_opt_int (sqlite3_stmt *stmt, int idx, const std::optional< int > &val) |
| Bind optional int to a parameter position (NULL if unset). | |
| static void | bind_delegation_insert (sqlite3_stmt *s, const DelegationRecord &rec) |
| Bind a Delegation record onto the delegations-INSERT statement's 11 placeholders. | |
| static bool | guard_parent_conversation (const std::string &parent_conversation_id, const std::string &delegating_tier, const std::string &target_tier, std::string &delegation_id, std::string &child_conversation_id) |
| Reject an empty parent_conversation_id with a clear error and reset the out params (gh#48 defense-in-depth). | |
| static std::vector< std::string > | get_applied_migrations (sqlite3 *db) |
| Get names of already-applied migrations. | |
| static bool | apply_migration (sqlite3 *db, const Migration &mig) |
| Apply a single migration and record it. | |
| static bool | is_applied (const std::vector< std::string > &applied, const char *name) |
| Check if a migration name is in the applied list. | |
| static std::string | read_file (const std::filesystem::path &path) |
| Read file contents as string. | |
| static bool | write_file (const std::filesystem::path &path, const std::string &content) |
| Write string to file. | |
| static std::vector< std::string > | split_lines (const std::string &content) |
| Split string into lines. | |
| static bool | list_contains (const std::vector< std::string > &lines, size_t start, std::string_view pattern) |
| Check if a YAML sequence already contains a pattern. | |
| static auto | find_list_end (std::vector< std::string > &lines, size_t list_start) |
| Find the end of a YAML sequence (last "- " item). | |
| static auto | find_section_end (std::vector< std::string > &lines, std::vector< std::string >::iterator start) |
| Find the end of a YAML section (indented block). | |
| static std::string | join_lines (const std::vector< std::string > &lines) |
| Join lines back into a string with trailing newline. | |
| static bool | insert_permission_item (std::vector< std::string > &lines, std::string_view pattern, const std::string &perms_key, const std::string &list_line, const std::string &item) |
| Insert a permission item into the parsed YAML lines. | |
Variables | |
| static const char *const | kStateNames [] |
| Lookup table for AgentState names indexed by enum value. | |
| static auto | logger = log::get("identity_manager") |
| static const std::vector< std::string > | s_reserved_names |
| Reserved identity names that cannot be used. | |
| static std::unordered_map< std::string, size_t > | s_tier_system_hash |
| Per-tier system prompt hash for diff detection across delegations. | |
| static auto | logger = entropic::log::get("mcp.external_bridge") |
| static std::mutex | s_bound_sockets_mu |
| static std::unordered_set< std::string > | s_bound_sockets |
| fixed = std::regex_replace(fixed, std::regex(R"(,\s*\])"), "]") | |
| try | |
| static constexpr const char * | VISION_INSTRUCTION |
| Vision instruction appended to system prompt. | |
| constexpr uint64_t | kBaseKvPerTokenF16 = 16ull * 1024ull |
| KV bytes per token at f16, the rate the v2.2.4 estimate assumed. | |
| constexpr int | kAllLayersSentinel = 99 |
gpu_layers at or above this means "every layer" (llama.cpp's 99). | |
| static const char *const | DIRECTIVE_NAMES [] |
| Serialize ServerResponse to JSON envelope. | |
| static constexpr const char * | MIGRATION_001_INITIAL |
| @dg_internal | |
| static constexpr const char * | MIGRATION_002_FTS |
| @dg_internal | |
| static constexpr const char * | MIGRATION_003_DELEGATIONS |
| @dg_internal | |
| static constexpr const char * | MIGRATION_004_COMPACTION_SNAPSHOTS |
| @dg_internal | |
| static constexpr std::array< Migration, 4 > | MIGRATIONS |
| @dg_internal | |
Activate model on GPU (WARM → ACTIVE).
Compile a gitignore line into a Rule.
Convert gitignore pattern body to regex source.
Reloads model with n_gpu_layers from config, then creates inference context with KV cache.
Dispatch table: each glob token type has a small emit_* helper.
| pattern | Pattern body (no leading ! or trailing /). |
Strips leading ! (negation) and trailing / (dir_only). Determines anchor: pattern with embedded / (anywhere but at the end) is anchored at the base; otherwise the pattern matches against any path component.
@dg_internal
| using entropic::CompactorFn = typedef std::function<CompactionResult( const std::vector<Message>& messages, const CompactionConfig& config, const std::string& identity)> |
Internal C++ compactor function type.
Takes messages + config + identity, returns CompactionResult. Wraps C function pointers with C++ types for internal use.
Definition at line 43 of file compactor_registry.h.
| using entropic::DirectiveHandler = typedef std::function<void( LoopContext& ctx, const Directive& directive, DirectiveResult& result)> |
Directive handler function type.
| ctx | Current loop context (mutable). |
| directive | The directive to process. |
| result | Aggregate result (accumulator). |
Definition at line 297 of file directives.h.
| using entropic::PermissionPersistFn = typedef void (*)( const char* pattern, bool allow, void* user_data) |
Permission persistence callback type.
Called when a user approves ALWAYS_ALLOW or ALWAYS_DENY so the pattern can be saved to disk. Injected by the facade.
| pattern | Permission pattern string. |
| allow | true for allow, false for deny. |
| user_data | Opaque pointer (PermissionPersister*). |
Definition at line 569 of file engine_types.h.
| using entropic::RunChildLoopFn = typedef void (*)(LoopContext& ctx, void* user_data) |
Callback type for running a child engine loop.
The engine provides this so DelegationManager can spawn child loops without a circular dependency on AgentEngine's full interface.
| ctx | Child loop context. |
| user_data | Opaque pointer (AgentEngine instance). |
Definition at line 70 of file delegation.h.
| using entropic::TokenCallback = typedef void (*)(const char*, size_t, void*) |
Token callback type matching the C API signature.
Definition at line 25 of file stream_think_filter.h.
| using entropic::ToolExecutionFn = typedef std::vector<Message> (*)( LoopContext& ctx, const std::vector<ToolCall>& tool_calls, void* user_data) |
Tool execution callback type.
Called by the engine when tool calls are parsed from model output. The facade wires this to ToolExecutor::process_tool_calls().
| ctx | Mutable loop context. |
| tool_calls | Tool calls to process. |
| user_data | Opaque pointer (ToolExecutor instance). |
Definition at line 403 of file engine_types.h.
|
strong |
LoRA adapter lifecycle state.
Mirrors ModelState but for LoRA adapters. An adapter must be HOT for its weights to influence generation. Multiple adapters can be WARM simultaneously (loaded in RAM), but only one can be HOT per inference context.
| Enumerator | |
|---|---|
| COLD | Not loaded. No resources consumed. |
| WARM | Loaded in RAM via llama_adapter_lora_init(). Ready to activate. |
| HOT | Active on context via llama_set_adapter_lora(). Influencing generation. |
|
strong |
C++ enum class for agent execution states.
Maps 1:1 to C entropic_agent_state_t for cross-boundary use.
Definition at line 36 of file engine_types.h.
|
strong |
Capabilities that an inference backend may or may not support.
The engine queries capabilities before using optional features. A backend that does not support a capability returns graceful errors (not crashes) if the feature is invoked anyway.
_COUNT sentinel is NOT a capability — it sizes the dispatch table and pins the declared cardinality so an appended capability fails the test until it is wired everywhere.@req REQ-TYPE-004
Definition at line 37 of file backend_capability.h.
|
strong |
Thinking-budget gating mode.
(gh#80, v2.5.0)
Charges generation effort that does NOT produce a tool call against a budget; a tool call resets the counter. On exhaustion the engine nudges the model to complete, then hard-cuts with a failure note visible in history. Opt-in: off is the default and preserves pre-v2.5.0 behavior exactly.
| Enumerator | |
|---|---|
| off | Disabled (default) — no thinking-budget gating. |
| tokens | Gate on generated tokens since the last tool call. |
| wall_clock | Gate on wall-clock seconds since the last tool call. |
Definition at line 81 of file engine_types.h.
|
strong |
|
strong |
Why a turn produced tokens but delivered no content.
Definition at line 34 of file empty_content_diagnosis.h.
|
strong |
Which source, if any, constrains the decode.
| Enumerator | |
|---|---|
| none | Unconstrained. |
| request | GenerationParams::grammar (COMMON_GRAMMAR_TYPE_USER) |
| tool_call | Render-derived (COMMON_GRAMMAR_TYPE_TOOL_CALLS, needs prefill) |
| count | Sentinel — MUST remain last. Adding a source above this line breaks grammar_source_invariant_test, which is the point: gh#95, gh#108 and gh#134 were each a grammar source that reached the engine without ever reaching the sampler, and each got only a bespoke regression test. A fifth source must not be able to ship unwired. |
Definition at line 32 of file grammar_source.h.
|
strong |
Origin of an identity – how it was created.
| Enumerator | |
|---|---|
| STATIC | Loaded from YAML frontmatter file at startup. |
| DYNAMIC | Created at runtime via API. |
Definition at line 31 of file identity.h.
|
strong |
How to handle generation interrupt.
| Enumerator | |
|---|---|
| CANCEL | Discard partial response, stop. |
| PAUSE | Keep partial response, await input. |
| INJECT | Keep partial, inject context, continue. |
Definition at line 53 of file engine_types.h.
|
strong |
MCP tool access level for per-identity authorization.
Two ordered levels: READ < WRITE. WRITE implies READ. Default for ungranted keys is NONE (no access). Default for new tools is WRITE (safe default — tools must opt into READ).
| Enumerator | |
|---|---|
| NONE | No access (default for ungranted keys) |
| READ | Read-only operations (e.g., read_file, list_directory) |
| WRITE | Read + write operations (e.g., write_file, execute) |
|
strong |
C++ enum class for model VRAM lifecycle states.
Maps 1:1 to C entropic_model_state_t for cross-boundary use. Internal C++ code uses this typed enum; C boundary uses the C enum.
| Enumerator | |
|---|---|
| COLD | On disk only, no RAM consumed. |
| WARM | mmap'd + mlock'd in RAM |
| ACTIVE | GPU layers loaded, full speed. |
|
strong |
Where a tier's weights land, as far as the estimate can tell.
| Enumerator | |
|---|---|
| none | gpu_layers == 0: weights cost no VRAM. |
| full | -1 or >= 99: the whole file is resident. |
| partial_unknown | A layer count we cannot price without GGUF metadata. |
Definition at line 75 of file vram_footprint.h.
|
strong |
Tool approval responses from user.
| Enumerator | |
|---|---|
| DENY | Deny this once. |
| ALLOW | Allow this once. |
| ALWAYS_DENY | Deny and save to config. |
| ALWAYS_ALLOW | Allow and save to config. |
Definition at line 63 of file engine_types.h.
|
strong |
Categorical outcome of a single tool invocation.
Values are serialized into the POST_TOOL_CALL hook context JSON as the result_kind string. Do NOT reorder or remove values — clients treat the string form as a stable contract.
@req REQ-TYPE-003
Definition at line 32 of file tool_result.h.
|
strong |
Result of the full validation pipeline (critique + optional revision).
Encapsulates the final output after zero or more revision attempts. Returned by ConstitutionalValidator::validate() and exposed through the C API as JSON via entropic_validation_last_result().
Outcome of a validation pipeline run.
Lets callers distinguish clean pass from safety-valve revert and from max-revisions-exhausted. Surfaces through ON_COMPLETE hook context and async task status so consumers know whether the returned content is trustworthy. (E1 / 2.0.6-rc17)
| Enumerator | |
|---|---|
| passed | No violations, content unchanged. |
| revised | Violations found; revision applied. |
| rejected_reverted_length | Revision gutted content >50%; original preserved. |
| rejected_max_revisions | Revisions exhausted; last output returned as-is. |
| skipped | Validation did not run (skip_tiers / pure-tool-call / empty) |
| paused_pending_consumer | gh#30 (v2.1.5): auto_retry disabled and a critique failed. Engine paused before entering the revision loop; consumer must call entropic_validation_resume_retry() or _accept_last(). |
| passed_consumer_override | gh#30 (v2.1.5): consumer called accept_last() to override a paused rejection. Last attempt is the final answer. |
Definition at line 70 of file validation.h.
|
static |
Map one parsed JSON object to a recovered ToolCall.
Accepts the canonical {"name":...} shape (via tool_call_from_json) and the parroted {"action":"<verb>",...} meta envelope — the latter mapped to the entropic.<verb> call ONLY when <verb> names a known meta-tool (its action verb equals its tool short-name). gh#88 audit: without this allow-list, TodoTool's sub-action verbs (add/update/remove) and arbitrary prose strings were recovered as bogus entropic.<x> no-op calls — the recovery would WARN "recovered 1" while injecting a call to a tool that does not exist.
| j | Parsed JSON object. |
Definition at line 264 of file adapter_base.cpp.
| const char * entropic::agent_state_name | ( | AgentState | state | ) |
Get the string name for an AgentState value.
| state | Agent state. |
| state | Agent state. |
Definition at line 36 of file engine_types.cpp.
|
static |
True while any task is still phase=cancelling.
| bridge | Bridge holding the task registry. @utility |
Definition at line 416 of file external_bridge.cpp.
| bool entropic::any_message_has_images | ( | const std::vector< Message > & | messages | ) |
Convenience: true if any message carries image content_parts.
True if any parsed message carries image content_parts.
| messages | Parsed message list. |
| messages | Parsed message list. |
Definition at line 86 of file messages_json.cpp.
|
static |
Append a server's tools to an array, prefixing each name.
<server>.<tool> is the fully-qualified form the router later splits back apart, so prefixing here is what makes prefix routing uniform across server kinds.
| tools_json | Server's raw tool-descriptor JSON array. | |
| prefix | Server name to prepend as <prefix>.<tool>. | |
| [in,out] | all | Destination array, appended to in place. @req REQ-MCP-007 |
Definition at line 181 of file server_manager.cpp.
|
inline |
Append a tool-call close marker to params.stop for sequential mode.
Pure engagement decision (no backend, no I/O) so it is CPU-unit-testable in isolation — the instrumentation guard that FAILS if the gh#103 sequential hard-stop does not engage (mirrors the gh#96 warm_keep_util decision helpers). No-op unless params.tool_call_mode == "sequential" and marker is non-empty; dedupes so an explicit per-call stop already carrying the marker is not duplicated.
| params | Generation params (stop list mutated). |
| marker | Family close marker (from close_marker_for_format / the backend). @req REQ-INFER-013 |
Definition at line 93 of file tool_call_markers.h.
|
static |
Append text from a content part if type == "text".
| type_val | Parsed type string. | |
| text_val | Parsed text string. | |
| [out] | text | Accumulated text. @utility |
Definition at line 275 of file compactor_registry.cpp.
| void entropic::apply_action_envelope_recovery | ( | std::vector< ToolCall > & | calls, |
| const std::string & | raw | ||
| ) |
gh#88: substitute recovered bare-JSON calls when a reliable (PEG_GEMMA4 / gemma) parse produced none; logs the recovery.
gh#88 reliable-path recovery substitution — see header.
No-op unless calls is empty AND a recovery is found. The WARN keeps residual/future context-priming visible instead of silently masking it. Used only on the common_chat-reliable path (interface_factory / orchestrator).
| calls | In/out parsed calls; replaced by the recovery iff empty + found. |
| raw | Raw assistant output to recover from. |
| calls | In/out parsed calls; replaced by the recovery iff empty + found. |
| raw | Raw assistant output to recover from. @req REQ-INFER-012 |
Definition at line 320 of file adapter_base.cpp.
|
static |
Split tool calls out of a result (gh#87: common_chat or adapter).
gh#87 Phase D: parse via common_chat (parse_response) ONLY when its captured format is multi-parameter safe (common_chat_parse_reliable — the dedicated PEG_GEMMA4 grammar). Autoparser families (Qwen, nemotron3) fall back to their hand-rolled multi-parameter adapter, because the PEG autoparser drops parameters past the first. Never both (double-parse guard). raw_content always preserves the pre-split output.
| model | Backend that produced the result (for common_chat routing). | |
| adapter | Tier adapter for the autoparser/fallback path (may be null). | |
| [in,out] | result | Generation result (content split, tools set). @req REQ-INFER-010 |
Definition at line 543 of file orchestrator.cpp.
|
static |
Apply fenced-json and fenced-args-only fallback parsers (gh#122, gh#127).
Called when both the primary parse paths (common_chat PEG + adapter) yield zero calls. Tries the gh#122 named-fence path first; on miss, tries the gh#127 args-only schema-match path. calls is updated in-place.
| raw | Raw model output. |
| llama | Active LlamaCppBackend (may be nullptr → gh#127 skipped). |
| calls | [in/out] Tool call accumulator (no-op unless currently empty). @utility |
Definition at line 474 of file interface_factory.cpp.
|
static |
Apply a single migration and record it.
| db | SQLite database handle. |
| mig | Migration to apply. |
Definition at line 417 of file database.cpp.
| void entropic::apply_tier_sampler_overrides | ( | GenerationParams & | params, |
| const TierSamplerOverrides & | ov | ||
| ) |
Apply per-tier sampler overrides to params.
Pure precedence helper — see header.
(gh#82/gh#85)
Pure precedence helper, free function for unit-testability. For each knob, applies the tier-configured value ONLY when the optional is engaged AND the incoming param is still at the GenerationParams struct default — preserving an explicit per-call override.
| params | Generation params (mutated). |
| ov | Tier sampler overrides (nullopt fields are skipped). @utility |
(gh#82/gh#85)
Each field takes the tier's value only when the tier set one AND the caller left that field at its GenerationParams default — so a per-call knob is never overwritten by tier config.
| params | Generation parameters (mutated in place). |
| ov | The tier's optional sampler overrides. @req REQ-INFER-021 |
Definition at line 1898 of file orchestrator.cpp.
|
static |
Assemble the compacted list: system, summary, users, last asst.
| system_msg | Optional system message (kept first). |
| summary_msg | The synthesized summary message. |
| user_msgs | Preserved user messages. |
| assistant_msgs | Assistant messages (only the last is kept). |
Definition at line 213 of file compaction.cpp.
|
static |
Conditionally assign a typed JSON field into a destination.
Extracted (v2.3.14, gh#23 MVP item 2) to keep parse_params under the knots ABC gate as new MVP-10 knobs land. @utility
Definition at line 79 of file interface_factory.cpp.
| bool entropic::audit_entry_from_json | ( | const nlohmann::json & | j, |
| AuditEntry & | entry | ||
| ) |
Deserialize AuditEntry fields from a JSON object.
Reads the per-call payload from a JSONL line. Session-level fields (version, timestamp, session_id, sequence) are ignored. Unknown fields are silently skipped.
| j | JSON object (one line from audit.jsonl). | |
| [out] | entry | Populated entry. |
| j | JSON object (one JSONL line). | |
| [out] | entry | Populated entry. |
Definition at line 80 of file audit_entry.cpp.
| nlohmann::json entropic::audit_entry_to_json | ( | const AuditEntry & | entry | ) |
Serialize AuditEntry fields to a JSON object.
Produces the per-call payload portion of a JSONL line. params_json and directives_json are parsed into proper JSON objects/arrays (not double-encoded strings).
| entry | The audit entry to serialize. |
| entry | The audit entry to serialize. |
Definition at line 53 of file audit_entry.cpp.
|
static |
Build a single error GenerationResult (gh#98 batch failures).
@utility
Definition at line 1808 of file llama_cpp_backend.cpp.
|
inline |
Decide whether the same-prefix batch fast-path is safe + worthwhile.
When false, the backend falls back to running each request serially (the proven single-request path) — which is always correct, just without the shared-prefill win. The fast-path is taken only when ALL hold:
| n | Number of requests. |
| n_parallel | Context sequence-slot capacity (config n_parallel). |
| shared | Shared prefix length (batch_shared_prefix_len result). |
| hybrid | True if the model is hybrid/recurrent. |
| total_suffix | Sum over requests of (len_i - shared). |
| n_batch | Decode batch capacity (config n_batch). |
Definition at line 80 of file batch_util.h.
|
inline |
Longest shared token prefix across N request sequences (gh#98).
The number of leading tokens identical across ALL sequences — prefilled once into seq 0 and seq_cp'd to the other N-1 sequences before each request's unique suffix is decoded. Mirrors warm-keep's rule that at least the final token of every sequence must be re-decoded so its logits are fresh for sampling: the result is capped at shortest_len - 1, so every sequence retains a non-empty suffix.
Returns 0 (no sharing worthwhile) when fewer than 2 sequences are given, any sequence is empty, or the shortest sequence is a single token.
| seqs | Tokenized request prompts. |
Definition at line 43 of file batch_util.h.
|
static |
Bind+listen on an AF_UNIX socket, applying 0600 perms.
| fd | Pre-created socket fd. |
| path | Bind path (already validated by socket_path_safe). |
Definition at line 677 of file external_bridge.cpp.
|
static |
Bind a Delegation record onto the delegations-INSERT statement's 11 placeholders.
Extracted from create_delegation (v2.1.12, gh#48) so the public function fits the knots SLOC ≤ 50 threshold after the defense-in- depth additions. Bind order matches the INSERT column order.
| s | Prepared statement. |
| rec | Delegation record (read-only). @dg_internal |
Definition at line 580 of file backend.cpp.
|
static |
Bind optional int to a parameter position (NULL if unset).
| stmt | Prepared statement. |
| idx | Parameter index (1-based). |
| val | Value to bind. @utility |
Definition at line 171 of file backend.cpp.
|
static |
Bind optional text to a parameter position.
| stmt | Prepared statement. |
| idx | Parameter index (1-based). |
| val | Value to bind. @utility |
Definition at line 154 of file backend.cpp.
|
static |
Build a NULL-terminated argv from command + args.
| command | Executable. |
| args | Argument list. |
Definition at line 306 of file transport_stdio.cpp.
|
static |
Build a typed Directive from a directive-descriptor JSON.
Issue #10 (v2.1.4): the "complete" branch now extracts coverage_gap / gap_description / suggested_files from the result JSON and populates the typed CompleteDirective fields.
| d | Directive JSON ("type": ...). |
| result_json | Parsed result JSON for parameter lookup. |
Build a CompleteDirective from a result JSON (issue #10).
| result_json | Tool result JSON. |
Definition at line 1450 of file tool_executor.cpp.
|
static |
Build the [COVERAGE GAP] message body that goes back to lead when a relay-tier child returns coverage_gap=true (#10, v2.1.4).
Definition at line 2292 of file engine.cpp.
|
static |
Deliver a finalized patch to consumer or pending/.
The complete callback is null-tolerant (default-deny → pending/). If the callback returns REJECT the patch is also persisted to pending/ for the consumer to recover later. The sandbox directory is removed by the caller (finalize_sandbox_for) after this call returns — independent of the consumer's decision (gh#29: engine never retains writable state).
| sb_info | Sandbox identity. |
| sandbox_result | Patch artifact. |
| result | Original delegation result. @dg_internal |
Fill the C-ABI delegation-result struct from C++ values.
| sb_info | Sandbox identity. |
| sandbox_result | Patch artifact. |
| result | Original delegation result. |
| files_c | NULL-terminated touched-files array (must outlive use). |
| files_len | Number of touched files. |
Definition at line 178 of file delegation.cpp.
|
static |
Build a Directive from a parsed directive + result JSON.
| d | Directive descriptor JSON carrying the wire "type" name. |
| result_json | Parsed result JSON, source of the directive's typed parameters. |
Definition at line 1476 of file tool_executor.cpp.
|
static |
Build a NULL-terminated envp from env strings.
| env_strs | "KEY=VALUE" strings. |
Definition at line 324 of file transport_stdio.cpp.
|
static |
Load all bundled grammars from a directory.
| grammar_dir | Path to data/grammars/ directory. |
Build a bundled GrammarEntry from a .gbnf file.
| path | Grammar file path. |
Definition at line 55 of file grammar_registry.cpp.
| InferenceInterface entropic::build_orchestrator_interface | ( | ModelOrchestrator * | orchestrator, |
| const std::string & | default_tier, | ||
| InterfaceContext ** | out_context | ||
| ) |
Build an InferenceInterface wired to an orchestrator.
Build InferenceInterface wired to an orchestrator.
Pre-v2.2.6 this stored its callback user_data in a process-global s_ctx static. A second configure call deleted the first handle's context, leaving the first handle's interface pointing to freed memory (gh#58). The context is now owned by the caller: pass a non-null out_context and free it with destroy_orchestrator_interface() when the interface is no longer needed (typically alongside the orchestrator on engine destroy).
| orchestrator | Orchestrator to wire (must outlive the interface). |
| default_tier | Default tier name for generation/routing. |
| out_context | Receives the heap-allocated context; caller owns. |
| orchestrator | Orchestrator to wire. |
| default_tier | Default tier name. |
Definition at line 590 of file interface_factory.cpp.
|
static |
Build the diagnose snapshot JSON.
| provider | State provider callbacks. |
| include_docs | Whether to include documentation. |
| history_limit | Max history entries. |
Definition at line 748 of file entropic_server.cpp.
|
static |
Parse tool calls from raw model output.
| raw_content | Raw model output. |
Build one ToolCall from a parsed JSON object.
| obj | JSON object with "name" and optional "arguments". |
| tc_str | Original JSON string (used in id hash). |
Definition at line 1344 of file engine.cpp.
|
static |
Build the OpenAI-function <tools> JSON array for injection.
| tool_jsons | Tool definition JSON strings. |
{type, function:{name,description,parameters}}. @dg_internal Definition at line 231 of file nemotron3_adapter.cpp.
|
static |
Build un-pruned tool-result evidence for the validator.
Issue #5 (v2.1.3): the validator's critique prompt previously received only a manifest (tool name + result size). For long delegations whose tool results had been pruned, the validator had no way to verify file:line citations against actual evidence — and false-flagged valid citations as hallucinated. This builds a separate evidence block that surfaces the un-pruned content (or the still-live content for un-pruned messages), bounded so the critique prompt doesn't blow up on a long delegation:
max_results tool-result messages onlychars_per_result charactersFormat is human-readable (mirrors build_tool_manifest) since it lands in a critique prompt consumed by the model.
| messages | Conversation messages. |
| max_results | Most-recent N tool-result messages to include. |
| chars_per_result | Per-result truncation budget. |
Definition at line 1687 of file engine.cpp.
|
static |
Build tool call manifest from conversation messages.
Scans for messages with metadata["tool_name"] (tool results stored by ToolExecutor) and builds a human-readable summary line per call.
| messages | Conversation messages. |
Definition at line 1603 of file engine.cpp.
|
static |
Build a JSON array of tool results from context messages.
Extracts messages with metadata["tool_name"] and serializes them as [{"name":"...", "content":"..."}] for the ON_COMPLETE hook.
| messages | Conversation messages. |
Definition at line 1887 of file engine.cpp.
|
static |
Call docs callback with section param.
| fn | Docs callback. |
| section | Section name (nullptr for full doc). |
| ud | User data. |
Definition at line 724 of file entropic_server.cpp.
|
static |
Call history callback with max_entries param.
| fn | History callback. |
| max_entries | Max entries to return. |
| ud | User data. |
Definition at line 701 of file entropic_server.cpp.
|
static |
Call a state provider callback and wrap result.
Every introspection tool reads engine state through the entropic_state_provider_t callback struct, and each individual callback is null-checked here rather than dereferenced.
| fn | Callback returning malloc'd string (or nullptr). |
| ud | User data for callback. |
Definition at line 678 of file entropic_server.cpp.
| bool entropic::calls_satisfy_schema | ( | const std::vector< ToolCall > & | calls, |
| const std::string & | tools_json | ||
| ) |
Check that every call's declared required parameters are present.
| calls | Parsed tool calls. |
| tools_json | Staged MCP tool defs. |
The detector for common_chat's silent first-parameter-only extraction. A call naming a tool absent from tools_json is left alone — unknown tools are not this function's business.
| calls | Parsed tool calls. |
| tools_json | Staged MCP tool defs (array of {name, inputSchema, ...}). |
Definition at line 110 of file response_parse.cpp.
|
static |
Cancel any async tasks currently running on the bridge.
Raises engine interrupt, flips still-running tasks into phase="cancelling", and polls up to ~1s for detached workers to finish. After the poll, unconditionally bumps the observer generation via detach_phase_observer() so any post-poll callbacks from a still- running worker are silently discarded. (P1-8, 2.0.6-rc16; observer-gen force-detach: E5+E6, 2.1.0)
| handle | Engine handle (for interrupt). |
| bridge | Bridge whose tasks_ registry is being canceled. @req REQ-BRIDGE-001 |
Definition at line 439 of file external_bridge.cpp.
|
static |
Run git diff --no-index between base and head, capture patch.
| base | Snapshot directory. | |
| head | Final sandbox directory. | |
| [out] | patch | Captured unified diff (may be empty when no changes). |
Definition at line 431 of file sandbox.cpp.
|
static |
Check create preconditions before validation.
| config | Identity config to check. |
| mgr_config | Manager configuration. |
| identities | Current identity map. |
Definition at line 83 of file identity_manager.cpp.
|
static |
Check one property's enum and type constraints.
| key | Property name. |
| prop | Property schema. |
| val | Argument value. |
Check a single value against an enum constraint.
| key | Property name. |
| allowed | Enum array from schema. |
| val | Argument value. |
Definition at line 311 of file tool_executor.cpp.
|
static |
Check that a mutable identity exists and is dynamic.
| name | Identity name. |
| identities | Identity map. |
Definition at line 114 of file identity_manager.cpp.
|
static |
Check one property's enum and type constraints.
| key | Property name. |
| prop | Property schema. |
| val | Argument value. |
Definition at line 360 of file tool_executor.cpp.
| std::string entropic::check_read_gates | ( | FilesystemServer & | server, |
| const fs::path & | resolved, | ||
| const std::string & | path_str | ||
| ) |
Execute read_file: resolve, size-check, read, hash, track.
| args_json | JSON arguments. |
Run pre-read gates (existence, ignore, size cap).
Returns a non-empty error JSON when any gate denies. Path-relative ignore matching uses the server's IgnoreMatcher (#15, v2.1.4).
| server | Owning server (source of the root, ignore rules and size limit). |
| resolved | Already root-confined path. |
| path_str | Resolved path as a string, for messages. |
not_found (whose message names list_directory, gh#124), is_directory for a directory argument (gh#116), ignored for a path excluded by .gitignore/.explorerignore, or size_exceeded naming both the size and the limit so the model pivots to offset/limit. @req REQ-MCP-021 @req REQ-MCP-022 Definition at line 888 of file filesystem.cpp.
|
static |
Check required fields are present.
| schema | Parsed JSON Schema object. |
| args | Parsed tool arguments. |
Definition at line 277 of file tool_executor.cpp.
|
static |
Check a single value against a type constraint.
| key | Property name. |
| type | Expected JSON Schema type string. |
| val | Argument value. |
Definition at line 334 of file tool_executor.cpp.
|
inline |
Classify a tier's offload request into a priceable placement.
A specific positive layer count below the sentinel cannot be turned into bytes without knowing the model's total layer count, which needs GGUF metadata this estimate deliberately does not read.
| gpu_layers | Tier's configured offload layer count. |
Definition at line 145 of file vram_footprint.h.
|
static |
Classify a tool result by its content (error/empty/ok).
| content | Result content (already size-capped, so the kind describes the bounded form the model saw). |
Definition at line 910 of file tool_executor.cpp.
|
inline |
Map a resolved common_chat format to its single-tool-call close marker.
Single-return (knots returns ≤ 3). PEG_NATIVE / PEG_SIMPLE use the PEG section_end default </tool_call> (qwen3 / hermes / nemotron-style). All other formats return "" (no reliable per-call marker → batch-safe fallback).
| fmt | Resolved common_chat format (from the last tool render). |
</tool_call> for the PEG native/simple families, <tool_call|> for gemma4, and "" for CONTENT_ONLY or any unknown format — "" is always safe: it injects no stop, so batch behaviour stays byte-identical and no parse can be corrupted. @req REQ-INFER-013 Definition at line 52 of file tool_call_markers.h.
|
static |
Coerce one call's numeric args to strings per the tool schema.
| tc | Tool call (arguments_json + arguments mutated in place). |
| tools | Parsed MCP tool array. @dg_internal |
Definition at line 369 of file adapter_base.cpp.
| void entropic::coerce_string_typed_args | ( | std::vector< ToolCall > & | calls, |
| const std::string & | tools_json | ||
| ) |
gh#90: coerce numeric scalars back to strings for string-typed tool parameters.
gh#90 string-typing coercion entry point — see header.
gemma's <|"|></tt> string-escape loses type through PEG_GEMMA4 — a
numeric-looking string arg (e.g. <tt>grade_level:\<|"|>3<|"|\></tt>) arrives as a
JSON number, a string-typed schema then rejects it (‘3 is not of type
'string’<tt>), and the delegation circuit-breaks. For each call, when the
staged tool schema declares a parameter</tt>"type":"string"and the parsed value is a JSON number, coerce it to its string form (updates both arguments_jsonand thearguments` map). No-op when tools_json is empty/invalid or the parameter is genuinely non-string. Applied on the common_chat-reliable (gemma) parse path.
| calls | In/out parsed tool calls. |
| tools_json | Staged MCP tool defs (array of {name, inputSchema,...}). |
| calls | In/out parsed calls; numeric args re-typed in place. |
| tools_json | Staged MCP tool defs (JSON array) carrying the schema. @req REQ-INFER-012 |
Definition at line 397 of file adapter_base.cpp.
|
static |
Get a nullable integer column as a JSON value.
| stmt | Prepared statement. |
| col | Column index. |
Definition at line 141 of file backend.cpp.
|
static |
Get optional text from a sqlite3 column.
| stmt | Prepared statement. |
| col | Column index. |
Definition at line 127 of file backend.cpp.
|
static |
Get text from a sqlite3 column, returning empty string for NULL.
| stmt | Prepared statement. |
| col | Column index. |
Definition at line 114 of file backend.cpp.
|
static |
Collect "name" fields from a JSON array of objects.
| j | JSON array. |
Definition at line 945 of file entropic_server.cpp.
|
static |
Collect keys from a JSON object into a vector.
| j | JSON object. |
Definition at line 929 of file entropic_server.cpp.
|
inline |
Length of the longest common token prefix of two sequences.
| a | First sequence (resident KV tokens). |
| b | Second sequence (incoming prompt tokens). |
Definition at line 30 of file warm_keep_util.h.
| std::regex entropic::compile_grep_or_error | ( | const std::string & | pattern, |
| std::string & | err | ||
| ) |
Compile a regex or return a structured tool error.
| pattern | Regex source. | |
| [out] | err | Set to a non-empty JSON error string on failure. |
err set to a structured invalid_regex error — a bad pattern from the model is a tool error, never a throw through the dispatch path. @req REQ-MCP-021 Definition at line 1226 of file filesystem.cpp.
|
static |
Compute max read bytes from config and model context.
| config | Filesystem configuration. |
| model_context_bytes | Model context window in bytes. |
max_read_bytes when set; else a percentage of the model context; else a 32KB default — the gate that turns an oversized read into a size_exceeded error instead of a blown context budget. @req REQ-MCP-021 Definition at line 1408 of file filesystem.cpp.
| std::filesystem::path entropic::compute_socket_path | ( | const std::filesystem::path & | project_dir | ) |
Compute project-unique Unix socket path for self-detection.
Compute project-unique Unix socket path.
| project_dir | Absolute path to project directory. |
Deterministic in the canonical project path, which is what lets discovery recognise and skip the engine's OWN socket rather than connecting to itself.
| project_dir | Project directory. |
~/.entropic/socks/{hash8}.sock (HOME falling back to /tmp). @req REQ-MCP-025 Definition at line 288 of file mcp_json_discovery.cpp.
|
static |
Plain "role: content" join used when templating fails.
| messages | Conversation history. |
Definition at line 1199 of file llama_cpp_backend.cpp.
|
static |
Concatenate user-role message text for session-log echo.
| messages | Incoming messages for the streaming turn. |
Definition at line 3113 of file engine.cpp.
| std::unique_ptr< ChatAdapter > entropic::create_adapter | ( | const std::string & | name, |
| const std::string & | tier_name, | ||
| const std::string & | identity_prompt | ||
| ) |
Create adapter by name (gh#87 Phase D hybrid).
Create an adapter instance by name.
Autoparser families (qwen35 / qwen36 / nemotron3) resolve to their per-family multi-parameter adapter. Everything else — including gemma4, whose tool calls are parsed by common_chat's dedicated grammar — falls back to GenericAdapter (identity assembly + generic fallback parse).
Lookup is case-insensitive, and an unrecognised name falls back to GenericAdapter rather than failing — a misconfigured adapter name must not take the tier down.
| name | Adapter name from config. |
| tier_name | Identity tier name. |
| identity_prompt | Assembled identity prompt. |
| name | Adapter name from config (e.g. "qwen35", "generic"). |
| tier_name | Identity tier name. |
| identity_prompt | Assembled prompt from PromptManager. |
Definition at line 123 of file adapter_registry.cpp.
|
static |
Create, bind, and listen on a unix domain socket.
v2.1.7 hardening (gh#34): containing dir 0700, socket file 0600, symlink-and-non-socket-safe bind. Path canonicalization + the hash naming scheme (see compute_socket_path) already provide a unique per-project path inside ~/.entropic/socks/; these checks defend against the residual cases where the path is squatted or perms have been loosened.
| path | Socket filesystem path. |
Definition at line 706 of file external_bridge.cpp.
|
static |
Decode a JSON tool-calls array string into ToolCall vector.
| tc_str | JSON array string ("[]" or "" yields empty result). |
Definition at line 1367 of file engine.cpp.
|
static |
Translate entropic_run's return code into a final task state.
On success, extracts the final clean assistant text from result_json and frees it. On cancellation/error, reports the last-error message. (P1-5, 2.0.6-rc16)
| handle | Engine handle (for last-error lookup). |
| err | Return code from entropic_run. |
| result_json | JSON result (owned; freed on success, else NULL). |
Definition at line 361 of file external_bridge.cpp.
| void entropic::destroy_orchestrator_interface | ( | InterfaceContext * | context | ) |
Free a context returned by build_orchestrator_interface().
Safe to call on nullptr.
@dg_internal
Definition at line 617 of file interface_factory.cpp.
|
inline |
Classify an empty-content turn from what the decode reported.
| content_empty | Whether the post-strip content is empty. |
| produced_tokens | Whether the model emitted anything at all. |
| finish_reason | Decode finish reason ("stop", "length", "error", ...). |
Definition at line 51 of file empty_content_diagnosis.h.
|
static |
List files differing between base and head via diff -rq-style logic.
| base | Snapshot directory. |
| head | Final sandbox directory. |
Definition at line 478 of file sandbox.cpp.
|
static |
Map directive type enum to wire-format string.
Range-checked on both ends so an out-of-range enum value serialises as "unknown" rather than reading past the name table.
| type | Directive type. |
Definition at line 218 of file server_base.cpp.
|
static |
Route entropic.ask — sync (streaming) or async.
| handle | Engine handle. |
| bridge | Bridge (for async task registry). |
| args | Tool arguments. |
| client_fd | Socket fd. |
| call_id | Request id. |
Definition at line 544 of file external_bridge.cpp.
|
static |
Try filterable targets (config/identity/tool).
| p | State provider. |
| target | Target name. |
| key | Filter key. |
| result | Output. |
Definition at line 1067 of file entropic_server.cpp.
|
static |
Dispatch an inspect query to the appropriate provider.
| p | State provider callbacks. |
| target | Query target. |
| key | Optional filter key. |
Definition at line 1096 of file entropic_server.cpp.
|
static |
Dispatch inspect for simple (non-filterable) targets.
| p | State provider. |
| target | Target name. |
| key | Optional key. |
| result | Output result string. |
Definition at line 1034 of file entropic_server.cpp.
|
static |
Dispatch a tools/call to the appropriate handler.
entropic.ask streams progress notifications to client_fd during generation, then returns the final clean text as the tool result. When async=true, spawns a background thread and returns task_id.
| handle | Engine handle. |
| bridge | Bridge instance (for async task registry). |
| params | JSON-RPC params (name + arguments). |
| client_fd | Socket fd for streaming (entropic.ask only). |
| call_id | JSON-RPC request id for progress correlation. |
Definition at line 575 of file external_bridge.cpp.
|
static |
Heap-allocate a C string copy.
| s | Source string. |
Definition at line 161 of file interface_factory.cpp.
|
static |
Draft-window size setup_mtp_draft will actually use (gh#106).
setup_mtp_draft normalises a non-positive n_max to 16. The envelope check must apply the SAME normalisation or it validates a number the engine never uses.
| n_max | Requested window, possibly non-positive. |
Definition at line 574 of file llama_cpp_backend.cpp.
|
static |
Append executor history (if any) to the tool manifest.
Enriches the validator revision prompt with iteration numbers and elapsed times pulled from ToolExecutor's ToolCallHistory ring buffer via the ToolExecutionInterface::history_json callback. (P1-11, 2.0.6-rc16)
| base | Existing manifest from messages. |
| tool_exec | Tool execution interface. |
Definition at line 1729 of file engine.cpp.
|
inline |
Estimate the VRAM a tier will occupy, or report that it cannot.
| in | Tier footprint inputs. |
known == false when the placement is unpriceable. @req REQ-INFER-019 Definition at line 180 of file vram_footprint.h.
|
inline |
Operator-facing explanation for an empty-content turn.
| cause | Result of diagnose_empty_content. |
Definition at line 73 of file empty_content_diagnosis.h.
|
static |
Extract and validate the fenced JSON block for args-only inference.
Parses exactly one fenced json block from raw, validates it is a JSON object with no name/tool key (handled by the gh#122 path), and returns it. Returns nullopt when the block is absent, malformed, multiple, or already has a name/tool key.
| raw | Raw model output. |
Definition at line 411 of file interface_factory.cpp.
|
static |
Pull the "directives" array out of a tool ServerResponse JSON.
| raw_result | Raw ServerResponse JSON string. |
directives array; nullopt when the string does not parse as an object, carries no directives key, or the array is empty — the no-side-effect case, which needs no dispatch. @req REQ-MCP-002 Definition at line 1513 of file tool_executor.cpp.
|
static |
Extract optional parent_conversation_id from JSON.
| j | JSON object. |
Definition at line 24 of file audit_entry.cpp.
|
static |
Extract directives from ServerResponse JSON and process them.
Parses the directives array from the raw tool result, constructs typed Directive objects, and passes them to the engine's DirectiveProcessor via the hooks callback.
| ctx | Loop context (mutated by directive handlers). |
| raw_result | ServerResponse JSON string. @dg_internal |
Extract pipeline stage names from a result JSON object.
| result_json | Parsed result JSON. |
Definition at line 1417 of file tool_executor.cpp.
|
static |
Extract the first system message content from messages.
| messages | Conversation messages. |
Definition at line 1747 of file engine.cpp.
| std::string entropic::extract_text | ( | const std::vector< ContentPart > & | parts | ) |
Extract concatenated text from content parts.
| parts | Content parts array. |
| parts | Content parts array. |
Definition at line 20 of file content.cpp.
|
static |
Extract tier name from params JSON, falling back to default.
| json_str | Params JSON (may contain "tier" field). |
| default_tier | Fallback tier name. |
Definition at line 144 of file interface_factory.cpp.
|
static |
Fill one cell of a multi-seq llama_batch.
@utility
Definition at line 1821 of file llama_cpp_backend.cpp.
|
static |
Filter a JSON value by key (object key or array name).
| json_str | Raw JSON string. |
| key | Key to extract. |
| label | Label for error messages. |
Definition at line 983 of file entropic_server.cpp.
|
static |
Read the live conversation and render the operator-visible answer.
gh#130 (v2.10.2): shared by both ask paths so the answer-vs-diagnostic rule cannot drift between them.
| handle | Engine handle. |
Definition at line 205 of file external_bridge.cpp.
|
static |
Find the first user-role message that isn't a tool result.
| messages | Message list. |
Definition at line 335 of file compaction.cpp.
|
static |
Find the end of a YAML sequence (last "- " item).
| lines | File lines. |
| list_start | Index of the list key line. |
Definition at line 117 of file permission_persister.cpp.
|
static |
Find the end of a YAML section (indented block).
| lines | File lines. |
| section_start | Iterator to section key. |
Definition at line 139 of file permission_persister.cpp.
|
static |
Find the first message matching a source tag.
| messages | Message list. |
| source | Source metadata value to match. |
Definition at line 316 of file compaction.cpp.
|
static |
Find the unique tool whose required params are all present in obj.
Returns the tool name when exactly one tool in tools satisfies the constraint. Returns empty when zero or more than one tool matches (ambiguous) to avoid false-positive tool-call synthesis.
| obj | Parsed arguments JSON object (no name/tool key). |
| tools | JSON array of MCP tool definitions. |
Definition at line 375 of file interface_factory.cpp.
|
static |
Build + fire the ON_CONTEXT_ASSEMBLE info hook.
| hooks | Hook interface. |
| ctx | Loop context. @req REQ-HOOK-002 |
Definition at line 101 of file engine.cpp.
|
static |
Fire an informational hook if the interface is wired.
| hooks | Hook interface. |
| point | Hook point. |
| json | Context JSON. @dg_internal |
Definition at line 37 of file engine.cpp.
|
static |
Build + fire the ON_LOOP_END info hook.
| hooks | Hook interface. |
| ctx | Loop context. @req REQ-HOOK-002 |
Definition at line 68 of file engine.cpp.
|
static |
Build + fire the ON_LOOP_ITERATION info hook.
| hooks | Hook interface. |
| ctx | Loop context. @req REQ-HOOK-002 |
Definition at line 84 of file engine.cpp.
|
static |
Build + fire the ON_LOOP_START info hook.
| hooks | Hook interface. |
| ctx | Loop context. @req REQ-HOOK-002 |
Definition at line 52 of file engine.cpp.
|
static |
gh#119 (v2.9.17): fold child summary into the lead's empty delegate turn.
push_delegation_result appends [DELEGATION COMPLETE] as a user message. Intermediate executor result messages may sit between it and the lead's empty assistant turn. Searches backward for the last empty assistant message and sets its content to the summary text so extract_final_text (external_bridge) returns the child's answer, not "" → "(no response)". Extracted from finalize_delegation_result to keep ABC under the 20.0 gate.
| ctx | Loop context (messages mutated in-place). |
| summary | Child delegation summary text. @req REQ-LOOP-007 |
Definition at line 2322 of file engine.cpp.
|
static |
Gather a tier's footprint inputs for the pure estimator.
Resolves the vision projector's size when the tier declares one — it is the allocation that actually aborted the process in gh#142 and the v2.2.4 estimate ignored it entirely.
| tier_cfg | The tier's configuration. |
| weights_bytes | Size of the tier's GGUF on disk. |
Definition at line 2012 of file orchestrator.cpp.
|
static |
Format one tool-result message for the evidence block.
| msg | Tool-result message. |
| chars_per_result | Per-result truncation budget. |
Definition at line 1635 of file engine.cpp.
|
static |
Generate a simple UUID-like task ID.
Definition at line 522 of file external_bridge.cpp.
| std::string entropic::generate_uuid | ( | ) |
Generate a UUID v4 string.
Definition at line 950 of file backend.cpp.
|
static |
Get names of already-applied migrations.
| db | SQLite database handle. |
Definition at line 392 of file database.cpp.
|
inlineconstexpr |
Number of declared grammar sources, sentinel excluded.
Reads the trailing count sentinel, so the value tracks the declaration automatically: appending a source above the sentinel changes this number and fails the invariant test, which is the tripwire's whole purpose.
none, excluding the sentinel itself. @req REQ-TYPE-004 @req REQ-INFER-008 Definition at line 58 of file grammar_source.h.
|
inline |
Whether both sources are active — a config error worth reporting.
| request_grammar | GenerationParams::grammar. |
| tool_grammar | Render-derived tool-call GBNF. |
Definition at line 96 of file grammar_source.h.
|
static |
Execute grep: brace-expand the file glob, compile the content regex (error-safe), iterate the tree applying the same classify_glob_entry filter glob uses.
Issues #13/#15 (v2.1.4).
@dg_internal
Walk the tree applying the glob/ignore filter and grep files.
| root | Search root. |
| file_patterns | Brace-expanded glob patterns. |
| re | Compiled content regex. |
| ignore | Ignore matcher. |
Definition at line 1259 of file filesystem.cpp.
|
static |
Reject an empty parent_conversation_id with a clear error and reset the out params (gh#48 defense-in-depth).
Pre-v2.1.12 an empty parent slipped through to the FK-bound INSERT and failed silently against conversations(id). The engine populates the root conversation at run() init; this guards against any caller bypassing that path.
| parent_conversation_id | Parent ID (must be non-empty). | |
| delegating_tier | Diagnostic context. | |
| target_tier | Diagnostic context. | |
| [out] | delegation_id | Cleared on rejection. |
| [out] | child_conversation_id | Cleared on rejection. |
Definition at line 619 of file backend.cpp.
|
static |
Handle entropic.ask — stream tokens then return final text.
Uses entropic_run_streaming to send MCP progress notifications for each token (streaming to client), then extracts the final clean assistant text from the conversation for the tool result. Used when mcp.external.ask_streaming: true (the default).
| handle | Engine handle. |
| args | Tool arguments. |
| client_fd | Socket fd for streaming progress notifications. |
| call_id | JSON-RPC request id (for progress token correlation). |
Definition at line 264 of file external_bridge.cpp.
|
static |
Handle entropic.ask — non-streaming path (gh#115, v2.9.12).
Routes through entropic_run (no on_token callback) so that MTP can engage without hitting the streaming-incompatibility guard. Also avoids the run_streaming dump-site 316 throw. Used when the bridge is configured with mcp.external.ask_streaming: false.
| handle | Engine handle. |
| args | Tool arguments (must contain "prompt" string). |
Definition at line 228 of file external_bridge.cpp.
|
static |
entropic.context_clear MCP tool handler.
Before clearing, cancels any in-flight async ask tasks so they do not continue running against a stale context. (P1-8, 2.0.6-rc16)
| handle | Engine handle. |
| bridge | Bridge instance (used to reach the task registry). |
Definition at line 462 of file external_bridge.cpp.
|
static |
Handle entropic.context_count.
| handle | Engine handle. |
Definition at line 479 of file external_bridge.cpp.
|
static |
Handle entropic.status.
| handle | Engine handle. |
Definition at line 296 of file external_bridge.cpp.
|
static |
Verify every required key is present, warning on the first absent one.
Split out of one_call_satisfies_schema to stay under the 3-return gate.
| args | Parsed argument object. |
| required | Declared required parameter names. |
| call_name | Tool name, for the diagnostic. |
Definition at line 65 of file response_parse.cpp.
|
static |
Check if key matches a blocked prefix pattern.
| key | Variable name. |
Definition at line 312 of file mcp_json_discovery.cpp.
| bool entropic::has_images | ( | const std::vector< ContentPart > & | parts | ) |
Check if content parts contain any image parts.
| parts | Content parts array. |
Definition at line 41 of file content.cpp.
|
static |
Raw text completion via orchestrator.
@callback
Definition at line 290 of file interface_factory.cpp.
|
static |
Generate via orchestrator.
@callback
Definition at line 172 of file interface_factory.cpp.
|
static |
Streaming generate via orchestrator.
gh#81 (v2.4.2): bridges int* cancel (engine-side ABI) to std::atomic<bool> cancel_flag (backend contract) per-token inside the on_token lambda. Pre-fix the local atomic was initialized once from *cancel at entry and never re-read, so an interrupt raised mid-stream by the engine's per-token callback (stream_token_callback raising *cancel_flag = 1) never reached the backend's decode loop. The backend polls the atomic but the atomic stayed false.
@callback
Definition at line 203 of file interface_factory.cpp.
|
static |
Batch generate with cancel via orchestrator (gh#81, v2.4.2).
Batch shape with mid-decode cancellation. The pre-v2.4.2 iface_generate accepted no cancel pointer and ran the backend to natural stop; this entry adds the cancel bridge using a small poller thread (no per-token hook in the batch contract).
@callback
Definition at line 235 of file interface_factory.cpp.
|
static |
Check if response is complete (no pending tool calls).
@callback
Definition at line 572 of file interface_factory.cpp.
|
static |
Parse tool calls from raw model output (gh#87 3b).
gh#87 Phase D: parse via common_chat (parse_response) only when its format is multi-parameter safe (common_chat_parse_reliable — the dedicated PEG_GEMMA4 grammar). Autoparser families (Qwen, nemotron3) fall back to their hand-rolled multi-parameter adapter. Routed on the last-used tier's backend so a routed (non-default) tier parses correctly.
gh#122 (v2.9.18): when both paths yield 0 calls and the output contains exactly one fenced json block, try extracting a {name, arguments} call from it. Handles models that emit tool calls in markdown fence format.
gh#127 (v2.10.0): if gh#122 also returns empty and the fenced block is an args-only object (no name key), match against the staged tool schemas — synthesise the call when exactly one tool's required params are all present.
The agent-loop half of the shared template-first / adapter-second rule — this branch used to be a byte-for-byte duplicate of the orchestrator's, which is how gh#108's fix could land on one path and miss the other.
| raw | Raw model output (may be NULL, treated as empty). | |
| [out] | cleaned | Newly allocated cleaned content; caller frees. |
| [out] | tool_calls_json | Newly allocated JSON array of calls. |
| user_data | InterfaceContext carrying the orchestrator. |
Definition at line 541 of file interface_factory.cpp.
|
static |
Route messages to tier via orchestrator.
@callback
Definition at line 276 of file interface_factory.cpp.
|
static |
Build the MCP initialize response payload.
Definition at line 1023 of file external_bridge.cpp.
|
static |
Insert a permission item into the parsed YAML lines.
Handles the three cases — missing permissions: block, missing allow/deny list, and existing list — mutating lines in place.
| lines | Parsed config lines (mutated). |
| pattern | Permission pattern (for the already-present check). |
| perms_key | The "permissions:" key line. |
| list_line | The " allow:"/" deny:" line. |
| item | The " - <pattern>" item line. |
item was inserted (write needed); false if the pattern was already present. @dg_internal Definition at line 185 of file permission_persister.cpp.
|
static |
Inspect a filterable target (config/identity/tool).
| fn | Provider callback returning JSON. |
| ud | Provider user_data. |
| key | Filter key (empty = full). |
| label | Error message label. |
Definition at line 1014 of file entropic_server.cpp.
|
static |
Check if a migration name is in the applied list.
| applied | Applied migration names. |
| name | Migration name to check. |
Definition at line 449 of file database.cpp.
| bool entropic::is_blocked_env_var | ( | const std::string & | key | ) |
Environment variable blocklist for .mcp.json env field.
Check if an environment variable is blocked.
These variables cannot be set via .mcp.json for security reasons (CWE-426 — untrusted search path, CWE-94 — code injection).
| key | Environment variable name. |
The blocklist covers the variables that could hijack the child process — loader-injection (LD_PRELOAD, LD_LIBRARY_PATH, the DYLD_ family), lookup redirection (PATH, HOME, SHELL) and the engine's own ENTROPIC_ namespace (CWE-426 / CWE-94).
| key | Variable name. |
Definition at line 332 of file mcp_json_discovery.cpp.
|
static |
Check if content is a pure tool call with no prose.
Tool-call-only outputs contain no prose claims that constitutional rules can evaluate. Validating them wastes inference and risks false non-compliance on XML syntax.
| content | Content with think blocks already stripped. |
Definition at line 1002 of file constitutional_validator.cpp.
|
static |
Reject working_dir values that would smuggle shell syntax.
The bash tool's security model is operator approval (the engine's tool-call gate), not pattern matching against the command. But working_dir is concatenated into a shell cd clause, so any shell metacharacter in cwd would escape the approval surface (the operator approves command, not the constructed shell string). This check rejects the obvious smuggling vectors and requires the cwd be an existing directory.
| cwd | Caller-supplied working directory string. |
;&|$<>`, newline, quotes, globs or brackets AND names an existing directory; false otherwise, which rejects the call before any shell runs. @req REQ-MCP-023
|
static |
Extract original user task from messages.
| messages | Messages to search. |
Check if a message is a tool result rather than a user task.
| msg | Message to check. |
Definition at line 302 of file compaction.cpp.
|
static |
Join a vector of strings with comma separators.
| v | Strings to join. |
Definition at line 3491 of file engine.cpp.
|
static |
Join lines back into a string with trailing newline.
| lines | Lines to join. |
Definition at line 156 of file permission_persister.cpp.
|
static |
Save pre-compaction snapshot via storage interface.
| conversation_id | Conversation to snapshot. |
| messages | Messages before compaction. @dg_internal |
Escape a string for JSON embedding.
| input | Raw string. |
Definition at line 476 of file compaction.cpp.
|
static |
Escape a string for JSON embedding.
| input | Raw string. |
Definition at line 46 of file compactor_registry.cpp.
|
static |
Escape a string for JSON embedding.
| s | Raw string. |
Definition at line 831 of file constitutional_validator.cpp.
|
static |
Map a character to its JSON escape sequence.
| c | Input character. |
Definition at line 26 of file compactor_registry.cpp.
|
static |
JSON-escape a string (no surrounding quotes).
| s | Raw string. |
Definition at line 1580 of file engine.cpp.
|
static |
Serialize messages to JSON for inference interface.
| messages | Message list. |
JSON-escape one string into a growing buffer. @dg_internal
Definition at line 575 of file response_generator.cpp.
|
static |
256-entry table mapping bytes to JSON escape sequences.
Non-null entries replace the input byte with the escape string. Null entries pass the byte through unchanged.
Definition at line 1560 of file engine.cpp.
|
static |
Extract concatenated text from a JSON content array.
Scans for {"type":"text","text":"..."} objects within a content array and joins their text values. Skips image parts.
| c | JSON cursor (positioned at opening '['). | |
| [out] | text | Extracted text. |
Definition at line 342 of file compactor_registry.cpp.
|
static |
Parse message objects from a JSON array cursor.
| c | JSON cursor (positioned after opening '['). | |
| [out] | messages | Output message vector. |
Definition at line 425 of file compactor_registry.cpp.
|
static |
Parse one content part object, extract type and text.
| c | JSON cursor (positioned after opening '{'). | |
| [out] | type_val | The "type" field value. |
| [out] | text_val | The "text" field value. |
Definition at line 253 of file compactor_registry.cpp.
|
static |
Parse one JSON object into a Message (role + content).
| c | JSON cursor (positioned after opening '{'). | |
| [out] | msg | Output message. |
Definition at line 407 of file compactor_registry.cpp.
|
static |
Read one field of a content part object into type/text.
| c | JSON cursor (positioned at key start). | |
| [out] | type_val | Populated if key == "type". |
| [out] | text_val | Populated if key == "text". |
Definition at line 230 of file compactor_registry.cpp.
|
static |
Read one key:value pair and apply to message fields.
Handles both string content and array content (multimodal). For array content, extracts text parts only.
| c | JSON cursor (positioned at key start). | |
| [out] | msg | Message to populate. |
Definition at line 372 of file compactor_registry.cpp.
|
static |
Parse one content part object and append text if applicable.
| c | JSON cursor (positioned at '{'). | |
| [out] | text | Accumulated text output. |
Definition at line 320 of file compactor_registry.cpp.
|
static |
Read a JSON quoted string from cursor.
| c | JSON cursor (positioned at or before opening quote). | |
| [out] | out | Decoded string. |
Definition at line 151 of file compactor_registry.cpp.
|
static |
Skip a JSON array or object in cursor (nested-aware).
| c | JSON cursor (positioned at opening '[' or '{'). @utility |
Definition at line 177 of file compactor_registry.cpp.
|
static |
Read one content part object from an array cursor.
Expects cursor at element start ('{' or ',' or ']'). Skips commas, parses the object, appends text to output if type=text.
| c | JSON cursor. | |
| [out] | text | Accumulated text. |
Advance cursor past commas/whitespace to next element.
| c | JSON cursor. |
Definition at line 302 of file compactor_registry.cpp.
|
static |
Skip one JSON value (string, primitive, array, or object).
| c | JSON cursor. @utility |
Definition at line 201 of file compactor_registry.cpp.
|
static |
Skip whitespace in a JSON cursor.
| c | JSON cursor. @utility |
Definition at line 117 of file compactor_registry.cpp.
|
static |
Decode one JSON escape sequence character.
| ch | The character after the backslash. |
Definition at line 130 of file compactor_registry.cpp.
|
inline |
Per-token KV cost in bytes for this tier's cache configuration.
Averages the key and value scales, which may differ — a tier may quantize one and not the other.
| in | Tier footprint inputs. |
Definition at line 166 of file vram_footprint.h.
|
inline |
Cost of a KV cache type relative to f16.
ggml packs 32 elements per quantized block, so the per-element cost is the block size over 32, expressed here against f16's 2 bytes/element. An unrecognised type is priced as f16 so the estimate never silently under-counts and lets through a load that will not fit.
| type | Cache type string from the tier config ("f16", "q4_0", ...). |
Definition at line 112 of file vram_footprint.h.
|
static |
List available keys from a JSON value for error messages.
| j | JSON object or array with "name" fields. |
Definition at line 963 of file entropic_server.cpp.
|
static |
Check if a YAML sequence already contains a pattern.
| lines | File lines. |
| start | Index of the list key line. |
| pattern | Pattern to search for. |
Definition at line 96 of file permission_persister.cpp.
| ToolDefinition entropic::load_tool_definition | ( | const std::string & | tool_name, |
| const std::string & | server_prefix, | ||
| const std::string & | data_dir | ||
| ) |
Load a tool definition from a JSON file.
| tool_name | Tool name (e.g., "read_file"). |
| server_prefix | Server directory name (e.g., "filesystem"). |
| data_dir | Base directory for tool JSON files. |
| std::runtime_error | if file not found or invalid. @utility |
Reads the bundled data/tools/<server>/<tool>.json descriptor, whose inputSchema (camelCase) is the schema ToolExecutor later validates arguments against.
| tool_name | Tool name (e.g., "read_file"). |
| server_prefix | Server directory name (e.g., "filesystem"); an empty prefix reads directly from data_dir. |
| data_dir | Base directory for tool JSON files. |
| std::runtime_error | when the descriptor file cannot be opened; nlohmann parse errors propagate for malformed JSON or a missing name/inputSchema key. @req REQ-MCP-013 |
Definition at line 99 of file tool_base.cpp.
|
static |
Log the per-orchestration tier/adapter/timing summary.
| result | Generation result (carries timings). |
| selected | Selected tier name. |
| adapter_name | Adapter that ran. |
| params | Resolved params (for grammar info). |
| routing_ms | Routing time. |
| swap_ms | Model-swap time. @utility |
Definition at line 693 of file orchestrator.cpp.
|
static |
Log the full assembled prompt (all messages, no truncation).
Tracks system prompt hash per-tier so that consecutive delegations to the same tier correctly detect content drift.
| messages | Message list being sent to inference. |
| tier | Locked tier name. @utility |
Definition at line 40 of file response_generator.cpp.
|
inline |
True when the model's layer count is consistent with an MTP head GGUF.
A Gemma-4 MTP assistant head has 1–2 transformer layers. A classical draft model (Llama/Mistral small-variant) has at least 4. Used by try_speculative_route_streaming (gh#107) to fail loud when such a GGUF is supplied without setting speculative.mtp: true.
| n_layer | Layer count from llama_model_n_layer. |
Definition at line 117 of file mtp_envelope.h.
| ConversationRecord entropic::make_conversation | ( | const std::string & | title = "New Conversation", |
| const std::optional< std::string > & | project_path = std::nullopt, |
||
| const std::optional< std::string > & | model_id = std::nullopt |
||
| ) |
Create a new ConversationRecord with generated UUID and timestamps.
Create a ConversationRecord with generated fields.
| title | Conversation title. |
| project_path | Project path (optional). |
| model_id | Model identifier (optional). |
| title | Title. |
| project_path | Optional project path. |
| model_id | Optional model ID. |
Definition at line 999 of file backend.cpp.
|
inline |
Speculative decoding configuration (v2.1.11, gh#36).
Off by default. When enabled is true and a draft_model is set, the engine loads the draft into the SecondaryModelLoader's "draft" slot at init and routes main-tier generation through LlamaCppBackend::do_generate_speculative.
Placement axis: draft_n_gpu_layers selects CPU (0), full GPU (-1), or hybrid partial offload (>0 and < model_layers). The default of 0 puts the draft on CPU so the GPU stays saturated on the verifier — minimal VRAM cost.
Build the v2.1.11 default ModelConfig for a speculative draft model.
Differs from the standard tier defaults in three places that the kernel currently depends on:
gpu_layers = 0 — CPU-resident draft (zero VRAM on top of primary). Override to -1 for full GPU when VRAM allows.flash_attn = false — required for partial seq_rm support on MoE / GQA architectures (the kernel rolls back draft KV after each speculative round). Override to true ONLY if your modelcontext_length = 8192 — modest; speculative drafts are typically 4–32 tokens per round, no need for a wide window.n_threads = 4 — works on most laptops; bump to match physical core count for higher CPU draft throughput.Every other field comes from ModelConfig's standard defaults.
| DelegationRecord entropic::make_delegation | ( | const std::string & | parent_conversation_id, |
| const std::string & | child_conversation_id, | ||
| const std::string & | delegating_tier, | ||
| const std::string & | target_tier, | ||
| const std::string & | task | ||
| ) |
Create a new DelegationRecord with generated UUID and timestamp.
Create a DelegationRecord with generated fields.
| parent_conversation_id | Parent conversation ID. |
| child_conversation_id | Child conversation ID. |
| delegating_tier | Tier initiating delegation. |
| target_tier | Target tier for child loop. |
| task | Task description. |
| parent_conversation_id | Parent conversation. |
| child_conversation_id | Child conversation. |
| delegating_tier | Source tier. |
| target_tier | Target tier. |
| task | Task description. |
Definition at line 1019 of file backend.cpp.
|
static |
Format a git result as JSON ServerResponse.
The single response shape all eight git tools answer in.
| output | Combined stdout+stderr from the git process. |
| exit_code | Process exit code. |
|
static |
JSON serialization of the current residency set.
@dg_internal
Build one residency-snapshot JSON entry.
| name | Tier name. |
| path | Model file path. |
| context_length | Tier context length (for KV estimate). |
| footprint | Resolved footprint bytes. |
| vram_reserve_mb | Configured headroom reserve. |
| last_ms | Last activation time (ms). |
Definition at line 2125 of file orchestrator.cpp.
|
static |
Mark every queued/running task as cancelling.
| bridge | Bridge holding the task registry. |
Definition at line 397 of file external_bridge.cpp.
| const char * entropic::mcp_access_level_name | ( | MCPAccessLevel | level | ) |
Convert MCPAccessLevel to string representation.
| level | Access level. |
Definition at line 21 of file config.cpp.
|
static |
Convert entropic MCP tool JSON to common_chat_tool defs (gh#87).
Reads ServerManager::list_tools() shape — an array of {name, description, inputSchema} — into common_chat_tool (name + description + parameters-schema-string). Tools without a name are skipped. Malformed JSON yields an empty list (the render then proceeds tool-less rather than throwing).
| tools_json | MCP tool-list JSON array string. |
Definition at line 1087 of file llama_cpp_backend.cpp.
|
inline |
Actionable error message for gh#107: MTP head on classical path.
Called by try_speculative_route_streaming when looks_like_mtp_head is true and speculative.mtp is false. The message names the layer count and the corrective config knob.
| n_layer | Layer count from llama_model_n_layer. |
speculative.mtp: true knob. @req REQ-INFER-015 Definition at line 134 of file mtp_envelope.h.
|
static |
gh#107: return true (and populate result) when draft looks like an MTP head GGUF routed to the classical separate-draft path.
An MTP head GGUF (1-2 layers) crashes in fattn.cu when the classical generate_speculative_with_draft path creates a separate KV context. Fail loud with INCOMPATIBLE_CONFIG instead of crashing.
| draft | Draft LlamaCppBackend (model must be loaded for the check). |
| result | [out] Populated on true return with SPECULATIVE_INCOMPATIBLE_CONFIG naming the layer count and the speculative.mtp: true knob. |
Definition at line 394 of file orchestrator.cpp.
|
inline |
Reason MTP cannot run for a request, or "" when the envelope is safe.
temperature is no longer a guard (gh#108, v2.9.4): the draft proposal is a deterministic point mass (see the file-level doc comment), so the existing exact-match accept step is lossless at any temperature, not just 0.
streaming is no longer a guard (gh#108, v2.10.0): generate_streaming now wraps on_token with StreamThinkFilter for incremental thinking-channel stripping, resolving the post-buffer-only limitation that motivated the original v2.9.1 guard.
| temperature | Effective sampling temperature (unused; see v2.9.4 note). |
| has_grammar | True when a GBNF grammar constraint is active (unused; see v2.10.0 grammar note — propagated via to_common_sampling). |
| streaming | True when a per-token callback is bound (unused; see v2.10.0 streaming note above). |
Definition at line 94 of file mtp_envelope.h.
|
static |
Names in a not in b (sorted set difference).
| a | Superset candidate. |
| b | Set to subtract. |
Definition at line 148 of file external_client.cpp.
|
static |
Normalize a frontmatter grammar value to a registry key.
Strips .gbnf extension if present: "compactor.gbnf" → "compactor". Values without extension are used as-is.
| grammar_value | Raw frontmatter value. |
Definition at line 1815 of file orchestrator.cpp.
|
static |
Get current time as seconds since epoch.
Definition at line 119 of file engine.cpp.
|
static |
Check one call's declared required parameters are all present.
| call | Parsed tool call. |
| tools_json | Staged MCP tool defs. |
Definition at line 89 of file response_parse.cpp.
|
static |
Populate logit_bias map from a JSON object of token→bias.
Accepts {"123": -100.0} shape — string keys parsed to int32_t. Skips un-parseable keys silently. @utility
Definition at line 92 of file interface_factory.cpp.
| bool entropic::parse_mcp_access_level | ( | const std::string & | name, |
| MCPAccessLevel & | out | ||
| ) |
Parse MCPAccessLevel from string.
| name | String: "NONE", "READ", or "WRITE" (case-sensitive). | |
| [out] | out | Parsed access level. |
| name | String: "NONE", "READ", or "WRITE" (case-sensitive). |
| out | Parsed access level. |
Definition at line 35 of file config.cpp.
|
static |
Parse a JSON array of message objects.
| json | JSON array string. | |
| [out] | messages | Output message vector. |
Definition at line 451 of file compactor_registry.cpp.
| std::vector< Message > entropic::parse_messages_json | ( | const char * | json_str | ) |
Parse a JSON array of messages into a vector of Message.
Parse a messages-array JSON string into Message structs.
Accepts both string-content and content-array (multimodal) shapes. For multimodal messages, populates Message::content_parts and sets Message::content = extract_text(content_parts) so callers that read content directly continue to work.
Tolerant of missing fields:
content string.| json_str | Null-terminated JSON array string. |
| nlohmann::json::parse_error | on malformed JSON. @req REQ-TYPE-006 |
| json_str | Null-terminated JSON. NULL or non-array yields empty. |
Definition at line 68 of file messages_json.cpp.
| ParsedModelResponse entropic::parse_model_response | ( | LlamaCppBackend * | llama, |
| ChatAdapter * | adapter, | ||
| const std::string & | raw | ||
| ) |
Parse a raw emission: template first, adapter second.
The single shared rule, used by both the orchestrator's buffered result and the agent-loop tool parse — duplicating the branch is how gh#108 reached one path and not the other. Tool-call extraction is either/or (two call lists cannot be merged); content cleanup composes, so the adapter's reasoning strip ALWAYS runs over whichever branch produced the content, and is idempotent so no path can be missed.
| llama | Backend, or nullptr when not llama.cpp-backed. |
| adapter | Resolved chat adapter, or nullptr. |
| raw | Raw model output. |
| llama | Backend, or nullptr when not llama.cpp-backed. |
| adapter | Resolved chat adapter, or nullptr. |
| raw | Raw model output. |
Definition at line 172 of file response_parse.cpp.
|
static |
Parse JSON message array into Message vector.
| json_str | JSON array of {role, content} objects. |
Definition at line 56 of file interface_factory.cpp.
|
static |
Parse generation params from JSON string.
| json_str | JSON params (may be null). |
Definition at line 115 of file interface_factory.cpp.
|
static |
Parse a brace/quote-fixed JSON string into a ToolCall.
| fixed | Cleaned JSON string (may still be invalid → throws). |
Definition at line 472 of file adapter_base.cpp.
|
static |
Parse the result sub-object from JSON into AuditEntry fields.
| result | JSON result object. | |
| [out] | entry | Entry to populate. @dg_internal |
Definition at line 39 of file audit_entry.cpp.
|
static |
Extract the "result" text from an MCP result JSON envelope.
| result_json | Raw result string from the server. |
result field when the string parses as JSON carrying one; otherwise the raw string verbatim, so a server that answered off-contract still surfaces its text. @req REQ-MCP-002 Definition at line 416 of file tool_executor.cpp.
|
static |
Parse tool calls via the adapter for the given tier (gh#89).
gh#89: uses the SAME routed tier (last_used_tier) so a non-default autoparser tier parses with the correct adapter, not the default. Returns the raw content and empty calls when no adapter is registered.
| orch | Model orchestrator (adapter lookup). |
| raw | Raw model output. |
| tier | Active tier name. |
| out_cleaned | Cleaned content (raw if no adapter). |
| out_calls | Parsed tool calls (empty if no adapter or 0 found). @utility |
Definition at line 500 of file interface_factory.cpp.
|
static |
Partition messages (from start) into user/assistant/stripped.
| messages | Input messages. | |
| start | First index to classify (skips system). | |
| [out] | user_msgs | source==user messages. |
| [out] | assistant_msgs | assistant-role messages. |
| [out] | stripped_count | Count of dropped messages. @utility |
Definition at line 184 of file compaction.cpp.
|
static |
Validate that the connecting peer shares the engine's UID.
Defense-in-depth against same-machine cross-user attempts that somehow reach the socket. Even with 0700 containing dir + 0600 socket, an SO_PEERCRED check is cheap and pins the trust boundary to "same uid only" explicitly rather than relying on file perms being correctly applied. v2.1.7 hardening (gh#34).
| client_fd | Newly accepted client fd. |
Definition at line 739 of file external_bridge.cpp.
|
static |
State observer that projects VERIFYING onto task phase.
@dg_internal
Definition at line 1079 of file external_bridge.cpp.
|
static |
Build pipeline context prefix for a stage.
Issue #11 (v2.1.4): the optional prior_output argument carries the previous stage's result forward as part of the next stage's task message. Pre-2.1.4 each stage ran in isolation against the ORIGINAL task only — surprising for prompt authors who reasonably expected pipeline to mean "Unix-style chained pipeline" and caused the multi-stage flow (e.g. researcher → reader) to lose intermediate output. The intent was always forward-carry; the isolation behavior was a bug.
| stage_idx | Zero-based stage index. |
| total | Total number of stages. |
| stages | Stage tier names. |
| prior_output | Previous stage's summary/result (empty for stage 0). |
Definition at line 521 of file delegation.cpp.
| void entropic::populate_from_hook_context | ( | AuditEntry & | entry, |
| const AuditHookContext & | ctx | ||
| ) |
Populate AuditEntry fields from AuditHookContext state.
| entry | Entry to populate (caller_id, depth, iteration, parent_id, status). |
| ctx | Hook context with engine state pointers. @dg_internal |
| entry | Entry to populate. |
| ctx | Hook context with engine state pointers. @dg_internal |
Definition at line 246 of file audit_logger.cpp.
|
static |
Prepare the socket containing directory with 0700 perms.
Creates the parent directory if absent and ensures it is mode 0700 so only the engine owner can enumerate sockets. v2.1.7 hardening (gh#34): explicit perms rather than relying on umask.
| parent | Directory path. @req REQ-BRIDGE-001 |
Definition at line 634 of file external_bridge.cpp.
|
static |
Append a structured cycle-rejection message to the loop context so the model can recover.
Names the offending tier and the ancestor chain. (P1-9, 2.0.6-rc16)
| ctx | Loop context. |
| target | Target tier that would have closed the cycle. @req REQ-DELEG-001 |
Definition at line 2097 of file engine.cpp.
|
static |
Append a delegation rejection message to the loop context.
| ctx | Loop context. @req REQ-DELEG-001 |
Definition at line 2077 of file engine.cpp.
|
static |
Append a "stop retrying same target" reject message (gh#64).
Triggered when the lead emits a delegation to a target that has just failed max_consecutive_failed_delegations times in a row. The lead is told concretely what to do next: respond to the user or try a different target.
@req REQ-DELEG-001
Definition at line 2144 of file engine.cpp.
|
static |
Append a delegation result message to the loop context.
| ctx | Loop context. |
| target | Target tier name. |
| result | Delegation result. @req REQ-DELEG-002 |
Definition at line 2124 of file engine.cpp.
|
static |
Lazy session-scoped SandboxManager accessor (gh#33, v2.1.6).
See engine.h for rationale on why this is engine-scoped rather than per-delegation.
Build a typed failure message for resume_delegation errors. @req REQ-DELEG-002
Definition at line 2684 of file engine.cpp.
| uint64_t entropic::query_device_free_vram_bytes | ( | ) |
Free VRAM on the first GPU device ggml reports, in bytes.
Returns 0 rather than guessing when no GPU device is registered — a CPU-only build or a machine with no usable GPU. The caller reads 0 as "budget unknown" and leaves the admission gate disabled, which is the correct behaviour for a CPU tier: there is no VRAM to run out of.
Definition at line 32 of file device_memory.cpp.
|
static |
Read file contents as string.
| path | File path. |
Definition at line 45 of file permission_persister.cpp.
|
static |
Validate + read an image file fully into a byte buffer.
| path | File path. |
| max_file_size | Reject files larger than this. |
| std::runtime_error | if missing, oversized, or unreadable. @utility |
Definition at line 146 of file image_preprocessor.cpp.
|
static |
Read one newline-delimited line from a socket fd.
| fd | Socket file descriptor. |
Definition at line 974 of file external_bridge.cpp.
|
inline |
Largest context length that fits, for the "won't fit" recommendation.
Returns a value the caller can actually act on rather than a bare refusal. Never inflates a request that already fits, and returns 0 when no context fits at all (the weights alone exceed the card) or when the placement is unpriceable — in both cases there is no honest number to offer.
| in | Tier footprint inputs, carrying the requested context length. |
| available_bytes | VRAM actually available on the device. |
Definition at line 215 of file vram_footprint.h.
|
static |
Serialize a single ToolCallRecord to JSON.
| rec | Record to serialize. |
Definition at line 120 of file tool_call_history.cpp.
| std::vector< ToolCall > entropic::recover_action_envelope_calls | ( | const std::string & | raw | ) |
gh#88: recover tool calls a gemma model parroted as bare-JSON.
gh#88 bare-JSON recovery — see header for the full rationale.
common_chat (PEG_GEMMA4) parses only the native call-prefix form. When a session primes the model with {"action":"x",...} meta-tool result envelopes (see the engine defang), the model echoes that bare-JSON shape and the dedicated grammar yields nothing. This permissive fallback (parity with the retired Gemma4Adapter) maps a {"action":"<tool>",...} envelope to the entropic.<tool> call (remaining fields as arguments), and also accepts a plain {"name":...} object.
| raw | Raw assistant output. |
| raw | Raw assistant output. |
{"action": …} envelope naming a real meta-tool. @req REQ-INFER-012 Definition at line 297 of file adapter_base.cpp.
|
static |
Last-ditch recovery: pull a tool name out via regex.
| json_str | Original (possibly unparseable) string. |
Definition at line 485 of file adapter_base.cpp.
|
static |
Remove messages with a specific anchor key.
| ctx | Loop context. |
| key | Anchor key to remove. @req REQ-COMPACT-002 |
Definition at line 1513 of file engine.cpp.
|
static |
Shared common_chat render core for both template paths (gh#87).
Builds common_chat_templates_inputs (jinja, generation prompt, enable_thinking, optional tools) and applies the model's template. Returns the full common_chat_params so callers can use .prompt and — for the tools path — capture .format/.generation_prompt/ .parser for a later parse. Returns nullopt when the model isn't loaded, the template can't init, or apply throws (caller falls back to the low-level path).
| model | Loaded model (may be null → nullopt). |
| messages | Conversation history. |
| params | Generation parameters (enable_thinking honored). |
| tools | Tool defs for inputs.tools (empty for the legacy path). |
| require_tool_call | Tier's mandatory-tool flag; selects COMMON_CHAT_TOOL_CHOICE_REQUIRED (which makes upstream derive the tool-call grammar eagerly) over AUTO. |
Definition at line 1157 of file llama_cpp_backend.cpp.
|
static |
Required parameter names declared by a tool's inputSchema.
| tools_json | Staged MCP tool defs. | |
| name | Tool name to look up. | |
| [out] | found | Set false when the tool is not in the staged set. |
Definition at line 31 of file response_parse.cpp.
|
inline |
Resolve which grammar wins.
The request grammar takes precedence: it is an explicit caller instruction, whereas the tool-call grammar is implied by staging tools. A caller that supplies both has a config error — the collision is logged loudly at the application site rather than silently resolved, because the losing constraint's absence would otherwise be undiagnosable.
| request_grammar | GenerationParams::grammar. |
| tool_grammar | Render-derived tool-call GBNF. |
Definition at line 80 of file grammar_source.h.
|
static |
Resolve a stream's finish_reason from rc + content size.
gh#20 (v2.1.5) resolution order: CANCELLED → "interrupted"; error with partial content → "partial"; error with none → "error"; clean → "stop".
| rc | Backend return code. |
| content_size | Accumulated content length. |
Definition at line 273 of file response_generator.cpp.
|
static |
Resolve the active main-tier llama_model* for compat lookup.
Definition at line 1727 of file orchestrator.cpp.
|
inline |
Serialize a ToolResultKind to its wire-stable string form.
| kind | Enum value. |
Definition at line 51 of file tool_result.h.
|
static |
Build a JSON-RPC error response.
| id | Request ID. |
| code | Error code. |
| msg | Error message. |
Definition at line 82 of file external_bridge.cpp.
|
static |
Build a JSON-RPC success response.
| id | Request ID. |
| result | Result payload. |
Definition at line 68 of file external_bridge.cpp.
|
static |
Trampoline for DelegationManager to call engine loop.
| ctx | Child loop context. |
| user_data | AgentEngine pointer. @dg_internal |
Definition at line 2064 of file engine.cpp.
|
static |
Run a git command in a given directory via popen.
The shared execution path behind all eight git tools: every one is git -C <repo root> ..., so no tool can operate outside the repo the server was pointed at, and none carries its own command gating — operator approval is the gate.
| repo_dir | Repository root directory. |
| git_args | Arguments appended after "git -C repo_dir". |
|
static |
Run a shell command and capture output.
| full_cmd | Command string including cd prefix and the 2>&1 redirect that merges stderr into stdout. |
|
static |
Compiled regex for identity name validation.
@dg_internal
|
static |
Sanitize a display_name for use as a log-line bracket label.
Rich-based TUI consumers (and any markdown renderer) interpret substrings of the shape [/foo] as BBCode close tags and strip surrounding markup. A registered server name that started with / (e.g. by accident or by a path-like identifier) would therefore corrupt the consumer's terminal output. We also strip [, ], and control characters that could confuse downstream loggers. Falls back to "server" if the input sanitizes to empty.
| raw | Caller-supplied display name (or command for fallback). |
[<name>] log/UI markup; the literal "server" when sanitizing leaves nothing. @req REQ-MCP-025 Definition at line 63 of file transport_stdio.cpp.
|
static |
Send an MCP progress notification with a text token.
| fd | Client socket fd. |
| token_text | Token string to send. |
| progress_token | Progress token ID for correlation. @utility |
Definition at line 180 of file external_bridge.cpp.
|
static |
Map a terminal status string to a sentinel filename suffix.
@dg_internal
Definition at line 1413 of file external_bridge.cpp.
|
static |
Serialize compaction config + identity to JSON.
| config | Compaction config. |
| identity | Identity name. |
| token_count | Current token count (0 if unknown). |
Definition at line 86 of file compactor_registry.cpp.
|
static |
Serialize a single multimodal content_parts array (gh#37, v2.1.8).
Emits [{"type":"text","text":"..."}, {"type":"image","path":"..."}] directly — keeps core free of nlohmann/json (design rule #21).
@dg_internal
Definition at line 597 of file response_generator.cpp.
|
static |
Serialize messages to minimal JSON array.
| messages | Messages to serialize. |
Definition at line 63 of file compactor_registry.cpp.
|
static |
Serialize messages to minimal JSON array.
| messages | Messages to serialize. |
Definition at line 494 of file compaction.cpp.
|
inline |
Serialize parsed tool calls to the C-ABI JSON array form.
Each argument value is parsed into its natural JSON type when it is valid JSON (number, bool, array, object, null); otherwise it is emitted as a JSON string. This mirrors what consumers receive across the .so boundary.
gh#118 (v2.9.16): XML-parsed argument strings carry raw model bytes; MTP-split codepoints cause nlohmann::json::dump() to throw type_error.316 INSIDE the inference_.parse_tool_calls callback, before the engine's mcp::sanitize_utf8 guard at parse_tool_calls:1386 can run. Dump with error_handler_t::replace to substitute U+FFFD for any invalid byte sequences — consistent with the sanitize_utf8 policy used at all other inbound UTF-8 boundaries.
| calls | Tool calls (from common_chat or a legacy adapter). |
[{name, arguments}, ...]. @utility Definition at line 47 of file tool_call_serialize.h.
|
static |
Copy git-tracked + untracked-not-ignored files from a project.
| source | Git repository root. |
| target | Destination directory. |
Definition at line 305 of file sandbox.cpp.
|
static |
Recursive copy for non-git sources (or sandbox-to-sandbox chains).
| source | Source directory. |
| target | Destination directory. |
Definition at line 342 of file sandbox.cpp.
|
static |
Reject a pre-existing path that is a symlink or non-socket.
Defends against swap-the-socket-file races where an attacker plants a symlink at the expected path before the engine starts. If the path exists and is anything other than a regular unix socket, the bind is refused. v2.1.7 hardening (gh#34).
| path | Socket path. |
Definition at line 653 of file external_bridge.cpp.
|
static |
Run one speculative accept round; return false to stop.
@dg_internal
Definition at line 3552 of file llama_cpp_backend.cpp.
|
static |
Build the target batch [id_last, draft0, ..., draftN-1].
| state | Kernel state. @dg_internal |
Definition at line 3265 of file llama_cpp_backend.cpp.
|
static |
Validate speculative preconditions and reject NO-seq_rm.
Either FULL or PART seq_rm is acceptable — the kernel has both a partial-seq_rm fast path (PART) and a checkpoint-based path (FULL) that mirrors speculative-simple's use_ckpt branches. Only NO-seq_rm targets/drafts cannot be supported.
Definition at line 3611 of file llama_cpp_backend.cpp.
|
static |
Restore the draft's pre-draft state so the upcoming target-batch decode on the draft re-fills cleanly.
@dg_internal
Definition at line 3424 of file llama_cpp_backend.cpp.
|
static |
Drive one accept round: draft → decode → sample-and-accept → emit tokens.
Returns true to continue the outer loop. @dg_internal
Snapshot draft state before drafting (when use_ckpt_dft). @dg_internal
Definition at line 3390 of file llama_cpp_backend.cpp.
|
static |
Snapshot target state right before the target decode of the speculative batch (when use_ckpt_tgt + non-empty draft).
@dg_internal
Definition at line 3410 of file llama_cpp_backend.cpp.
|
static |
Free everything allocated by the kernel.
| state | Kernel state. @dg_internal |
Definition at line 3251 of file llama_cpp_backend.cpp.
|
static |
Walk accepted ids, emit tokens via callback, update state.
Returns true if the outer loop should stop. @dg_internal
Definition at line 3499 of file llama_cpp_backend.cpp.
|
static |
Decode the speculative batch on both contexts.
Populates state.error_* on failure.
Definition at line 3284 of file llama_cpp_backend.cpp.
|
static |
Emit on_token for one accepted id, updating state and returning a stop signal when terminating conditions apply.
Outcomes:
@dg_internal
Definition at line 3341 of file llama_cpp_backend.cpp.
|
static |
Speculative kernel against an explicit draft backend.
@dg_internal
Assemble final GenerationResult + log metrics. Helper to keep the public entry under SLOC ≤ 50. @dg_internal
Definition at line 3778 of file llama_cpp_backend.cpp.
|
static |
Initialize speculative run state (prefill + sampler + decoder).
@dg_internal
Definition at line 3717 of file llama_cpp_backend.cpp.
|
static |
Initialize the kernel state: clear KV, prefill, sampler, speculative context, batch, and detect FULL-seq_rm checkpoint-mode for target/draft.
Returns "" on success or a diagnostic string. Cleans up on failure.
Checkpoint detection runs AFTER common_speculative_begin so the impl's batch is already allocated.
@dg_internal
Init the sampler + speculative decoder for a run.
Extracted from spec_init_run to keep it knots-clean. Returns "" on success after wiring state.smpl/spec/batch + checkpoint flags; returns a diagnostic and cleans up on failure.
| state | Speculative run state. |
| model_tgt | Target model (for the sampler). |
| params | Generation params. |
| n_draft_max | Draft cap (<=0 → 16). |
| draft_path | Draft model path (gates DRAFT_SIMPLE upstream). |
Definition at line 3670 of file llama_cpp_backend.cpp.
|
static |
Drive one accept round: optional draft generation, decode on both contexts, sample-and-accept, emit tokens (or roll back via checkpoint on partial acceptance).
Returns true to continue the outer loop. @dg_internal
Draft tokens for a speculative round (or reuse carry-over).
Extracted from spec_accept_round. When state.draft is empty, runs the draft model under checkpoint save/restore; otherwise reuses the carried-over partial draft.
| state | Speculative run state. |
Definition at line 3534 of file llama_cpp_backend.cpp.
|
static |
Partial-acceptance rollback: restore both contexts and the sampler to their pre-draft state, then arrange for the outer loop to re-decode with the partial accept as the new draft.
Matches speculative-simple's partial-acceptance path lines 258-281. @dg_internal
Definition at line 3443 of file llama_cpp_backend.cpp.
|
static |
Trigger draft generation via common_speculative_draft.
Definition at line 3315 of file llama_cpp_backend.cpp.
|
static |
Public entry point for the speculative-decoding kernel.
Validates preconditions, tokenizes the prompt, initializes kernel state, drives the accept-round loop, and finalizes the result. Each phase is delegated to a static helper to satisfy the complexity gates (knots: cognitive ≤ 15, SLOC ≤ 50, returns ≤ 3).
| messages | Conversation history. |
| params | Generation parameters (samplers, max_tokens, seed). |
| on_token | Callback fired once per accepted token. |
| cancel | Cancellation flag (polled between accept rounds). |
| draft | Draft backend (must be ACTIVE on the same model arch). |
| n_draft_max | Maximum draft window size (proposed tokens per round). Clamped to 16 if non-positive. |
Run the speculative loop over already-tokenized input.
Extracted from generate_speculative_with_draft to keep it knots-clean. Inits the run state, drives the accept-round loop, and finalizes; cleans up + returns a typed error if init fails.
| ctx_tgt | Target context. |
| ctx_dft | Draft context. |
| model_tgt | Target model (sampler + vocab). |
| tokens | Prompt tokens (>= 2). |
| params | Generation parameters. |
| on_token | Per-accepted-token callback. |
| cancel | Cancellation flag. |
| n_draft_max | Draft window cap. |
| draft_path | Draft model path. |
| t0 | Start timestamp for timing. |
Definition at line 3870 of file llama_cpp_backend.cpp.
|
static |
Run the accept-round loop until completion / EOS / cancel.
@dg_internal
Definition at line 3745 of file llama_cpp_backend.cpp.
|
static |
Clear any stale KV positions left by rejected draft tokens.
After spec_decode_both populates positions [n_past_old, n_past_old + K] (one for id_last + K draft slots), the sampler accepts a prefix of length 1 + n_accepted ≤ 1 + K. n_past is then advanced to the next-write slot = old + 1 + n_accepted. Everything at or beyond state.n_past belongs to rejected drafts and must be removed before the next iteration's decode hits the same slots.
Matches upstream speculative-simple.cpp:323: llama_memory_seq_rm(get_memory(ctx), seq_id, n_past, -1). The previous n_past + 1 boundary was off-by-one and left the first rejected-draft slot polluted, causing rc=-1 on PART seq_rm contexts (Gemma 4) on the second iteration (Session 5).
PART contexts honour the seq_rm directly; FULL contexts effectively no-op (their KV is restored via the checkpoint dance in spec_rollback_partial instead).
@dg_internal
Definition at line 3486 of file llama_cpp_backend.cpp.
|
static |
Split string into lines.
| content | Input string. |
Definition at line 77 of file permission_persister.cpp.
|
static |
Stage the turn's tool defs on the backend for common_chat (gh#87).
Forwards params.tools (per-tier MCP JSON, empty for a tool-less turn) to the backend so its render path emits the model's native tool-call format. No-op for non-LlamaCpp backends. Called before every generate dispatch.
| model | Active backend (may be null / non-LlamaCpp). |
| params | Resolved generation params (carries tools). |
| require_tool_call | Per-tier mandatory-tool flag staged alongside the defs; drives the render's tool_choice. @req REQ-INFER-009 |
Definition at line 518 of file orchestrator.cpp.
|
static |
Token callback for streaming generation.
| token | Token string. |
| len | Token length. |
| user_data | StreamAccumulator pointer. @req REQ-LOOP-008 |
Definition at line 195 of file response_generator.cpp.
|
static |
Trampoline: bridges TokenCallback C signature to std::function.
| data | Token bytes. |
| len | Byte count. |
| ud | Pointer to std::function<void(std::string_view)>. @utility |
Definition at line 872 of file orchestrator.cpp.
|
static |
Strip reasoning blocks from content before critique (gh#108).
The model's internal reasoning is not subject to constitutional review — passing it to the critique model makes it evaluate planning text as if it were claims about the codebase.
v2.10.3: the markers were hardcoded to <think>, so on a Gemma-4 tier this stripped nothing and the critique model saw raw <|channel> reasoning — precisely the failure this function exists to prevent. They are now supplied by the facade via set_thinking_markers(), sourced from the tier's adapter. Passed as plain strings because core cannot depend on inference.
Kept rather than deleted: validate() takes content as a parameter, so its contract must tolerate unstripped input from a direct caller — it cannot assume the engine's parse path ran first.
| content | Raw model output. |
| open | Opening delimiter. |
| close | Closing delimiter. |
Definition at line 972 of file constitutional_validator.cpp.
| void entropic::strip_thinking_channels | ( | std::string & | content, |
| std::string * | reasoning_out | ||
| ) |
Strip Gemma 4 QAT reasoning channels (<|channel>…<channel|>) from content, accumulating the stripped text into reasoning.
The Gemma 4 QAT re-exports (it-qat / it-qat-mobile) are THINKING models: their template emits a <|channel>thought … <channel|> reasoning block before the final answer/tool-call — and ALWAYS when tools are staged. common_chat has no channel parser at this pin, so the block survives in msg.content. This moves it into reasoning so the user-facing content is clean. No-op for any content without the markers — safe for every non-channel family. (gh#106, v2.9.0)
gh#108 (v2.9.4): when a channel opens but never closes (generation hit max_tokens while still inside the reasoning block — a real non-convergence case seen on some quant/MTP combos, not just a hypothetical), everything from the open marker onward is still treated as reasoning and erased — correct, since no actual answer was ever produced — but this used to be silent: a caller saw only an empty content with no signal WHY. Now logs a WARN so this is diagnosable instead of indistinguishable from any other empty-content cause.
| content | [in,out] Content to clean (channel spans removed in place). |
| reasoning_out | [in,out,nullable] Accumulates the stripped reasoning text. @utility |
Definition at line 1457 of file llama_cpp_backend.cpp.
| std::string entropic::summarize_params | ( | const std::string & | args_json | ) |
Extract top-level JSON keys as a comma-separated summary.
Extract top-level JSON keys as comma-separated summary.
| args_json | Full JSON arguments string. |
Keys ONLY — argument values never enter the history buffer.
| args_json | Full JSON arguments string. |
Definition at line 176 of file tool_call_history.cpp.
|
static |
Build a ToolCall from a parsed JSON object with name/tool + arguments/parameters.
Definition at line 312 of file interface_factory.cpp.
|
static |
Convert engine messages to common_chat_msg (gh#86, v2.6.1).
Role + content only. The legacy apply_chat_template path renders without tools (entropic injects tool prompts into the system message via ResponseGenerator::inject_tool_prompt); the gh#87 render_with_tools path supplies tools through inputs.tools instead.
| messages | Source messages. |
Definition at line 1060 of file llama_cpp_backend.cpp.
|
static |
Map a common_chat_tool_call to entropic's ToolCall (gh#87).
Name + id pass through; the JSON arguments string is kept verbatim in arguments_json (for passthrough dispatch) and also flattened into the string key-value arguments map (object values dumped back to JSON).
| cc | Native common_chat tool call. |
Definition at line 1117 of file llama_cpp_backend.cpp.
|
static |
Convert engine messages to llama_chat_message views.
| messages | Source messages (must outlive the returned views). |
messages. @utility Definition at line 1037 of file llama_cpp_backend.cpp.
|
static |
MCP tool definitions exposed by the bridge.
Definition at line 108 of file external_bridge.cpp.
|
static |
String-typed property names for a tool in the staged MCP defs.
| tools | Parsed MCP tool array. |
| name | Tool name to match. |
"type":"string". @dg_internal Definition at line 342 of file adapter_base.cpp.
|
static |
Wrap text in MCP tool result shape.
| text | Result text. |
Definition at line 96 of file external_bridge.cpp.
|
static |
Strip a directory prefix p from the front of line.
| [in,out] | line | Path line to trim in place. |
| p | Prefix directory (a trailing slash is added if missing). @utility |
Definition at line 458 of file sandbox.cpp.
| std::string entropic::truncate_result | ( | const std::string & | text, |
| size_t | max_len | ||
| ) |
Truncate a string to max_len characters with "..." suffix.
Truncate text with "..." suffix if too long.
| text | Input text. |
| max_len | Maximum length before truncation. |
| text | Input text. |
| max_len | Maximum length before truncation (200 for the history result summary). |
max_len; otherwise its first max_len characters with "..." appended. @req REQ-MCP-020 Definition at line 205 of file tool_call_history.cpp.
|
static |
Try to synthesise a tool call from a fenced args-only JSON object (gh#127).
Fires after the gh#122 named-object path returns empty. When the fenced block is a valid JSON object with NO name or tool key, checks tools_json for a unique tool whose required parameters are all present as object keys. If exactly one tool matches, synthesises a ToolCall with that name and the object as arguments. Zero or multiple matches → empty (no false positive).
| raw | Raw model output. |
| tools_json | JSON array of staged MCP tool definitions. |
Definition at line 444 of file interface_factory.cpp.
|
static |
Extract a tool call from a single fenced json block in raw model output (gh#122).
Fires only when both the PEG parser and adapter return 0 calls and the output contains exactly one fenced json block that matches the {name/tool, arguments/parameters} schema. Conservative: does nothing if the block is missing, malformed, or there are multiple blocks.
| raw | Raw model output. |
Definition at line 347 of file interface_factory.cpp.
|
static |
Tool calls from the template parser, when trustworthy.
Trustworthiness is an a-posteriori check, not a try/catch: common_chat's PEG autoparser silently extracts only the FIRST <parameter=> of a multi-parameter call and returns a well-formed ToolCall with arguments missing, so the result is validated against the staged schema.
| llama | Backend. | |
| raw | Raw output. | |
| [out] | out | Result to populate on success. |
Definition at line 136 of file response_parse.cpp.
| std::string entropic::utc_timestamp | ( | ) |
Get current UTC time as ISO 8601 string.
Definition at line 979 of file backend.cpp.
|
static |
Count expected bytes in a UTF-8 sequence from lead byte.
| byte | Lead byte. |
Definition at line 75 of file stream_think_filter.cpp.
|
static |
Validate phases and adapter_path fields.
| config | Config to validate. |
Definition at line 63 of file identity_manager.cpp.
|
static |
Validate all phases in an identity config.
| phases | Phase map to validate. |
Definition at line 39 of file identity_manager.cpp.
|
static |
Validate tool arguments against the tool's JSON Schema.
Checks required fields, enum constraints, and basic type matching. Returns an error string on violation, or empty on pass.
| schema_json | The tool's input_schema (JSON Schema string). |
| args | The parsed arguments from the model. |
Definition at line 389 of file tool_executor.cpp.
|
inline |
Decide how many resident-KV tokens warm-keep may reuse this turn.
Returns the cut: tokens [0, cut) are kept in KV (the divergent tail is seq_rm'd) and the incoming sequence is decoded from cut onward. A return of 0 means fall back to a cold prefill. Rules:
| resident | Tokens recorded as resident in KV seq 0 (the last prompt). |
| incoming | The new prompt's tokens. |
| kv_pos_max | Highest occupied position in seq 0 (llama_memory_seq_pos_max), or < 0 if empty. |
Definition at line 62 of file warm_keep_util.h.
|
static |
Diagnose a mandatory-tool turn that ran out of budget (gh#134).
Under tool_choice: REQUIRED the gemma4 grammar is zero_or_more(any) + tool_call: unbounded preamble, then a MANDATORY call. So the grammar guarantees a call comes EVENTUALLY, not that it arrives within max_tokens. Measured on E4B QAT: at 600 tokens the model could no longer quit with prose (correct) but burned the budget narrating and was cut off (finish_reason == "length", zero calls); at 2000 it emitted a call on all 10 turns.
That failure is a budget misconfiguration, not a model or grammar fault, and it is indistinguishable from a stall unless the engine says so — the same diagnostic dead end gh#130 fixed on the bridge. enable_thinking is the usual culprit because the thinking channel is what consumes the preamble.
| result | Completed generation result. |
| tier_name | Tier that produced it. |
| tiers | Tier table, for the per-tier require_tool_call lookup. @utility |
Definition at line 606 of file orchestrator.cpp.
|
static |
Explain a turn that produced tokens but delivered no content (gh#137).
The reasoning strip legitimately empties a generation that never closed its reasoning block — surfacing raw reasoning as the answer would be worse. But the operator has to know WHICH problem they have, and until v2.11.0 the engine gave one message for both, telling them to raise max_tokens.
gh#137 reported finish=stop with 154 chars delivering 0 chars. The model ended that turn itself; no budget increase can help, and the advice sent the reporter looking in the wrong place. This is the only site that can tell the difference, because it is the only one holding finish_reason.
| result | Completed generation result. @req REQ-INFER-010 |
Definition at line 575 of file orchestrator.cpp.
|
static |
Report every post-turn diagnostic from one call site (gh#137).
Folded into a single entry point because the caller is generate, which sits against the knots ABC ceiling — two adjacent warn calls pushed it over. Both checks are no-ops on a healthy turn.
| result | Completed generation result. |
| tier_name | Selected tier. |
| tiers | Configured tiers, for the require_tool_call budget check. @req REQ-INFER-010 |
Definition at line 638 of file orchestrator.cpp.
|
static |
Write string to file.
| path | File path. |
| content | Content to write. |
Definition at line 61 of file permission_persister.cpp.
|
static |
Write a JSON-RPC line to a socket fd.
| fd | Socket file descriptor. |
| msg | JSON object to serialize and write. @utility |
Definition at line 167 of file external_bridge.cpp.
|
static |
Serialize ServerResponse to JSON envelope.
| response | Response to serialize. |
Map directive type enum to wire-format string.
| type | Directive type. |
Directive type enum → wire-format string lookup. @dg_internal
Definition at line 193 of file server_base.cpp.
| entropic::fixed = std::regex_replace(fixed, std::regex(R"(,\s*\])"), "]") |
Definition at line 514 of file adapter_base.cpp.
|
constexpr |
gpu_layers at or above this means "every layer" (llama.cpp's 99).
Definition at line 72 of file vram_footprint.h.
|
constexpr |
KV bytes per token at f16, the rate the v2.2.4 estimate assumed.
Definition at line 69 of file vram_footprint.h.
|
static |
Lookup table for AgentState names indexed by enum value.
@dg_internal
Definition at line 24 of file engine_types.cpp.
|
static |
Definition at line 17 of file identity_manager.cpp.
|
static |
Definition at line 43 of file external_bridge.cpp.
|
staticconstexpr |
@dg_internal
Definition at line 35 of file database.cpp.
|
staticconstexpr |
@dg_internal
Definition at line 82 of file database.cpp.
|
staticconstexpr |
@dg_internal
Definition at line 106 of file database.cpp.
|
staticconstexpr |
@dg_internal
Definition at line 133 of file database.cpp.
|
staticconstexpr |
@dg_internal
Definition at line 150 of file database.cpp.
|
static |
Definition at line 52 of file external_bridge.cpp.
|
static |
Definition at line 51 of file external_bridge.cpp.
|
static |
Reserved identity names that cannot be used.
Definition at line 20 of file identity_manager.cpp.
|
static |
Per-tier system prompt hash for diff detection across delegations.
Definition at line 27 of file response_generator.cpp.
| entropic::try |
Definition at line 518 of file adapter_base.cpp.
|
staticconstexpr |
Vision instruction appended to system prompt.
Definition at line 229 of file qwen35_adapter.cpp.