Entropic 2.3.8
Local-first agentic inference engine
Loading...
Searching...
No Matches
entropic Namespace Reference

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...
 
class  Gemma4Adapter
 Gemma 4 chat adapter (covers A4B / E4B / E2B variants). 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...
 
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  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...
 
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...
 
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...
 
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  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  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  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
}
 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...
 

Functions

const char * agent_state_name (AgentState state)
 Get the string name for an AgentState value.
 
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().
 
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< Messageparse_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< Messageassemble_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 std::string strip_think_blocks (const std::string &content)
 Strip <think>...</think> blocks from content.
 
static bool is_pure_tool_call (const std::string &content)
 Check if content is a pure tool call with no prose.
 
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< ToolCalldecode_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 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 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 bool match_tag (const std::string &buf, bool &is_open)
 Check if accumulated buffer matches a think tag.
 
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 std::string extract_final_text (const char *result_json)
 Extract the last assistant message from a run result JSON.
 
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 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 &params, 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< ToolCallparse_recovered_tool_call (const std::string &fixed)
 Parse a brace/quote-fixed JSON string into a ToolCall.
 
static std::optional< ToolCallregex_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< ChatAdaptercreate_adapter (const std::string &name, const std::string &tier_name, const std::string &identity_prompt)
 Create adapter by name.
 
static nlohmann::json build_tool_defs (const std::vector< std::string > &tool_jsons)
 Build the OpenAI-function <tools> JSON array for injection.
 
static std::optional< GrammarEntrybuild_grammar_entry (const std::filesystem::path &path)
 Load all bundled grammars from a directory.
 
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< Messageparse_msgs (const char *json_str)
 Parse JSON message array into Message vector.
 
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_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 int iface_parse_tool_calls (const char *raw, char **cleaned, char **tool_calls_json, void *user_data)
 Parse tool calls from raw model output via adapter.
 
static int iface_is_complete (const char *, const char *tool_calls_json, void *)
 Check if response is complete (no pending tool calls).
 
static std::vector< llama_chat_message > to_llama_chat (const std::vector< Message > &messages)
 Apply GGUF-embedded chat template to messages.
 
static std::string concat_messages_fallback (const std::vector< Message > &messages)
 Plain "role: content" join used when templating fails.
 
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 &params, int n_draft_max, const std::string &draft_path)
 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 &params, int n_draft_max, const std::string &draft_path)
 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 &params, 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)
 Public entry point for the speculative-decoding kernel.
 
static void apply_adapter_parse (ChatAdapter *adapter, GenerationResult &result)
 Run the tier's adapter over a result to split tool calls.
 
static void log_orchestration (const GenerationResult &result, const std::string &selected, const std::string &adapter_name, const GenerationParams &params, double routing_ms, double swap_ms)
 Log the per-orchestration tier/adapter/timing summary.
 
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 > 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 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< Directivebuild_complete_directive (const nlohmann::json &result_json)
 Build a typed Directive from a directive-descriptor JSON.
 
static std::unique_ptr< Directivebuild_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 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.
 
static const char *const DIRECTIVE_NAMES []
 Serialize ServerResponse to JSON envelope.
 
static constexpr const char * MIGRATION_001_INITIAL
 
static constexpr const char * MIGRATION_002_FTS
 
static constexpr const char * MIGRATION_003_DELEGATIONS
 
static constexpr const char * MIGRATION_004_COMPACTION_SNAPSHOTS
 
static constexpr std::array< Migration, 4 > MIGRATIONS
 

Detailed Description

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.

Returns
true on success.

Dispatch table: each glob token type has a small emit_* helper.

Parameters
patternPattern body (no leading ! or trailing /).
Returns
Regex source. @utility
Version
2.1.4

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.

Typedef Documentation

◆ CompactorFn

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.

Version
1.9.9

Definition at line 43 of file compactor_registry.h.

◆ DirectiveHandler

using entropic::DirectiveHandler = typedef std::function<void( LoopContext& ctx, const Directive& directive, DirectiveResult& result)>

Directive handler function type.

Parameters
ctxCurrent loop context (mutable).
directiveThe directive to process.
resultAggregate result (accumulator).
Version
1.8.4

Definition at line 297 of file directives.h.

◆ PermissionPersistFn

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.

Parameters
patternPermission pattern string.
allowtrue for allow, false for deny.
user_dataOpaque pointer (PermissionPersister*).
Version
1.8.8

Definition at line 505 of file engine_types.h.

◆ RunChildLoopFn

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.

Parameters
ctxChild loop context.
user_dataOpaque pointer (AgentEngine instance).
Version
1.8.6

Definition at line 70 of file delegation.h.

◆ TokenCallback

using entropic::TokenCallback = typedef void (*)(const char*, size_t, void*)

Token callback type matching the C API signature.

Version
2.0.1

Definition at line 25 of file stream_think_filter.h.

◆ ToolExecutionFn

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().

Parameters
ctxMutable loop context.
tool_callsTool calls to process.
user_dataOpaque pointer (ToolExecutor instance).
Returns
Result messages to append to context.
Version
1.8.5

Definition at line 339 of file engine_types.h.

Enumeration Type Documentation

◆ AdapterState

enum class entropic::AdapterState : int
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.

Version
1.9.2
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.

Definition at line 112 of file config.h.

◆ AgentState

enum class entropic::AgentState : int
strong

C++ enum class for agent execution states.

Maps 1:1 to C entropic_agent_state_t for cross-boundary use.

Version
1.8.0

Definition at line 36 of file engine_types.h.

◆ BackendCapability

enum class entropic::BackendCapability : int
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.

Design rationale:
Enum rather than string tags for compile-time exhaustiveness checking. New capabilities are appended (never reordered) for ABI stability.
Version
1.9.13
Enumerator
KV_CACHE 

KV cache state management (save/load/clear)

HIDDEN_STATE 

Recurrent hidden state management (save/load/reset)

STREAMING 

Streaming token-by-token generation.

RAW_COMPLETION 

Raw text completion without chat template.

GRAMMAR 

GBNF grammar-constrained generation.

LORA_ADAPTERS 

LoRA adapter hot-swapping (v1.9.2)

MULTI_SEQUENCE 

Multiple concurrent sequences on one model instance.

TOKENIZER 

Token counting / tokenizer access.

LOG_PROBS 

Log-probability retrieval (v1.9.10)

VISION 

Vision / multimodal input (v1.9.11)

SPECULATIVE_DECODING 

Speculative decoding compatibility.

PROMPT_CACHING 

Prompt cache prefix save/load (v1.8.3)

AUDIO 

Audio input via mtmd audio projector (gh#53, v2.3.0)

_COUNT 

Sentinel — must be last. Used for iteration/array sizing.

Definition at line 33 of file backend_capability.h.

◆ ContentPartType

enum class entropic::ContentPartType
strong

Content part type discriminant.

Version
1.9.11
Enumerator
TEXT 

Plain text content.

IMAGE 

Image content (local path or data URI)

Definition at line 24 of file content.h.

◆ IdentityOrigin

enum class entropic::IdentityOrigin : uint8_t
strong

Origin of an identity – how it was created.

Version
1.9.6
Enumerator
STATIC 

Loaded from YAML frontmatter file at startup.

DYNAMIC 

Created at runtime via API.

Definition at line 31 of file identity.h.

◆ InterruptMode

enum class entropic::InterruptMode
strong

How to handle generation interrupt.

Version
1.8.4
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.

◆ MCPAccessLevel

enum class entropic::MCPAccessLevel : uint8_t
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).

Version
1.9.4
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)

Definition at line 38 of file config.h.

◆ ModelState

enum class entropic::ModelState : int
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.

Version
1.8.2
Enumerator
COLD 

On disk only, no RAM consumed.

WARM 

mmap'd + mlock'd in RAM

ACTIVE 

GPU layers loaded, full speed.

Definition at line 96 of file config.h.

◆ ToolApproval

enum class entropic::ToolApproval
strong

Tool approval responses from user.

Version
1.8.4
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.

◆ ToolResultKind

enum class entropic::ToolResultKind
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.

Version
2.0.6-rc19
Enumerator
ok 

Tool dispatched, returned non-empty content.

error 

Tool server returned an error payload.

rejected_duplicate 

Precondition: duplicate in recent history.

rejected_schema 

Precondition: argument schema violation.

rejected_precondition 

Any other precondition reject (auth, tier, hook-cancel)

ok_empty 

Tool dispatched cleanly but returned no content (v2.1.0, #44)

delegation_failed 

entropic.delegate child failed (terminal_reason or budget). (#7, v2.1.4)

rejected_anti_spiral 

Anti-spiral hard threshold crossed; tool blocked. (#14, v2.1.4)

Definition at line 31 of file tool_result.h.

◆ ValidationVerdict

enum class entropic::ValidationVerdict
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().

Version
1.9.8

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)

Version
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.

Function Documentation

◆ agent_state_name()

const char * entropic::agent_state_name ( AgentState  state)

Get the string name for an AgentState value.

Parameters
stateAgent state.
Returns
Static string. Never NULL. @utility
Version
1.8.4
Parameters
stateAgent state.
Returns
Static string like "IDLE", "EXECUTING", etc. @utility
Version
1.8.4

Definition at line 36 of file engine_types.cpp.

◆ any_cancelling_left()

static bool entropic::any_cancelling_left ( ExternalBridge bridge)
static

True while any task is still phase=cancelling.

Parameters
bridgeBridge holding the task registry. @utility
Version
2.0.6-rc16

Definition at line 378 of file external_bridge.cpp.

◆ any_message_has_images()

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.

Parameters
messagesParsed message list.
Returns
true if at least one Message has has_images() true. @utility
Version
2.1.8
Parameters
messagesParsed message list.
Returns
true if at least one ContentPart is IMAGE.

Definition at line 86 of file messages_json.cpp.

◆ append_text_part()

static void entropic::append_text_part ( const std::string &  type_val,
const std::string &  text_val,
std::string &  text 
)
static

Append text from a content part if type == "text".

Parameters
type_valParsed type string.
text_valParsed text string.
[out]textAccumulated text. @utility
Version
1.9.11

Definition at line 275 of file compactor_registry.cpp.

◆ apply_adapter_parse()

static void entropic::apply_adapter_parse ( ChatAdapter adapter,
GenerationResult result 
)
static

Run the tier's adapter over a result to split tool calls.

Parameters
adapterAdapter for the selected tier (may be null).
[in,out]resultGeneration result (content split, tools set). @utility
Version
2.3.7

Definition at line 345 of file orchestrator.cpp.

◆ apply_migration()

static bool entropic::apply_migration ( sqlite3 *  db,
const Migration mig 
)
static

Apply a single migration and record it.

Parameters
dbSQLite database handle.
migMigration to apply.
Returns
true on success.

Definition at line 417 of file database.cpp.

◆ assemble_compacted()

static std::vector< Message > entropic::assemble_compacted ( const Message system_msg,
Message  summary_msg,
const std::vector< const Message * > &  user_msgs,
const std::vector< const Message * > &  assistant_msgs 
)
static

Assemble the compacted list: system, summary, users, last asst.

Parameters
system_msgOptional system message (kept first).
summary_msgThe synthesized summary message.
user_msgsPreserved user messages.
assistant_msgsAssistant messages (only the last is kept).
Returns
Compacted message list. @utility
Version
2.3.7

Definition at line 213 of file compaction.cpp.

◆ audit_entry_from_json()

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.

Parameters
jJSON object (one line from audit.jsonl).
[out]entryPopulated entry.
Returns
true if all required fields were present and valid.
Version
1.9.5
Parameters
jJSON object (one JSONL line).
[out]entryPopulated entry.
Returns
true if all required fields present and valid.

Definition at line 80 of file audit_entry.cpp.

◆ audit_entry_to_json()

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).

Parameters
entryThe audit entry to serialize.
Returns
JSON object with all entry fields.
Version
1.9.5
Parameters
entryThe audit entry to serialize.
Returns
JSON object with all entry fields.

Definition at line 53 of file audit_entry.cpp.

◆ bind_and_listen()

static bool entropic::bind_and_listen ( int  fd,
const std::filesystem::path &  path 
)
static

Bind+listen on an AF_UNIX socket, applying 0600 perms.

Parameters
fdPre-created socket fd.
pathBind path (already validated by socket_path_safe).
Returns
true on success. @utility
Version
2.1.7

Definition at line 636 of file external_bridge.cpp.

◆ bind_delegation_insert()

static void entropic::bind_delegation_insert ( sqlite3_stmt *  s,
const DelegationRecord rec 
)
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.

Parameters
sPrepared statement.
recDelegation record (read-only).

Definition at line 471 of file backend.cpp.

◆ bind_opt_int()

static void entropic::bind_opt_int ( sqlite3_stmt *  stmt,
int  idx,
const std::optional< int > &  val 
)
static

Bind optional int to a parameter position (NULL if unset).

Parameters
stmtPrepared statement.
idxParameter index (1-based).
valValue to bind. @utility
Version
2.3.7

Definition at line 80 of file backend.cpp.

◆ bind_opt_text()

static void entropic::bind_opt_text ( sqlite3_stmt *  stmt,
int  idx,
const std::optional< std::string > &  val 
)
static

Bind optional text to a parameter position.

Parameters
stmtPrepared statement.
idxParameter index (1-based).
valValue to bind. @utility
Version
1.8.8

Definition at line 63 of file backend.cpp.

◆ build_argv()

static std::vector< char * > entropic::build_argv ( const std::string &  command,
const std::vector< std::string > &  args 
)
static

Build a NULL-terminated argv from command + args.

Parameters
commandExecutable.
argsArgument list.
Returns
char* vector (pointers into command/args; must outlive use). @utility
Version
2.3.7

Definition at line 297 of file transport_stdio.cpp.

◆ build_complete_directive()

static std::unique_ptr< Directive > entropic::build_complete_directive ( const nlohmann::json &  result_json)
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.

Parameters
dDirective JSON ("type": ...).
result_jsonParsed result JSON for parameter lookup.
Returns
Owned Directive (nullptr if type is unrecognized).

Build a CompleteDirective from a result JSON (issue #10).

Parameters
result_jsonTool result JSON.
Returns
CompleteDirective with summary + typed gap/suggested fields. @utility
Version
2.3.7

Definition at line 1215 of file tool_executor.cpp.

◆ build_coverage_gap_message()

static std::string entropic::build_coverage_gap_message ( const std::string &  tier,
const DelegationResult result 
)
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 1996 of file engine.cpp.

◆ build_delegation_result_struct()

static ent_delegation_result_t entropic::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 
)
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).

Parameters
sb_infoSandbox identity.
sandbox_resultPatch artifact.
resultOriginal delegation result.

Fill the C-ABI delegation-result struct from C++ values.

Parameters
sb_infoSandbox identity.
sandbox_resultPatch artifact.
resultOriginal delegation result.
files_cNULL-terminated touched-files array (must outlive use).
files_lenNumber of touched files.
Returns
Filled ent_delegation_result_t (borrows the inputs). @utility
Version
2.3.7

Definition at line 176 of file delegation.cpp.

◆ build_directive()

static std::unique_ptr< Directive > entropic::build_directive ( const nlohmann::json &  d,
const nlohmann::json &  result_json 
)
static

Build a Directive from a parsed directive + result JSON.

Definition at line 1234 of file tool_executor.cpp.

◆ build_envp()

static std::vector< char * > entropic::build_envp ( const std::vector< std::string > &  env_strs)
static

Build a NULL-terminated envp from env strings.

Parameters
env_strs"KEY=VALUE" strings.
Returns
char* vector (pointers into env_strs; must outlive use). @utility
Version
2.3.7

Definition at line 315 of file transport_stdio.cpp.

◆ build_grammar_entry()

static std::optional< GrammarEntry > entropic::build_grammar_entry ( const std::filesystem::path &  path)
static

Load all bundled grammars from a directory.

Parameters
grammar_dirPath to data/grammars/ directory.
Returns
Number of grammars loaded.

Build a bundled GrammarEntry from a .gbnf file.

Parameters
pathGrammar file path.
Returns
Entry, or nullopt if the file is empty/unreadable. @utility
Version
2.3.7

Definition at line 55 of file grammar_registry.cpp.

◆ build_orchestrator_interface()

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).

Parameters
orchestratorOrchestrator to wire (must outlive the interface).
default_tierDefault tier name for generation/routing.
out_contextReceives the heap-allocated context; caller owns.
Returns
Fully wired InferenceInterface.
Version
2.2.6
Parameters
orchestratorOrchestrator to wire.
default_tierDefault tier name.
Returns
Wired interface.

Definition at line 256 of file interface_factory.cpp.

◆ build_snapshot()

static nlohmann::json entropic::build_snapshot ( const entropic_state_provider_t p,
bool  include_docs,
int  history_limit 
)
static

Build the diagnose snapshot JSON.

Parameters
providerState provider callbacks.
include_docsWhether to include documentation.
history_limitMax history entries.
Returns
Snapshot as JSON object.

Definition at line 693 of file entropic_server.cpp.

◆ build_tool_call_from_json()

static ToolCall entropic::build_tool_call_from_json ( const nlohmann::json &  obj,
const std::string &  tc_str 
)
static

Parse tool calls from raw model output.

Parameters
raw_contentRaw model output.
Returns
(cleaned content, parsed tool calls).

Build one ToolCall from a parsed JSON object.

Parameters
objJSON object with "name" and optional "arguments".
tc_strOriginal JSON string (used in id hash).
Returns
Populated ToolCall.

Definition at line 1141 of file engine.cpp.

◆ build_tool_defs()

static nlohmann::json entropic::build_tool_defs ( const std::vector< std::string > &  tool_jsons)
static

Build the OpenAI-function <tools> JSON array for injection.

Parameters
tool_jsonsTool definition JSON strings.
Returns
JSON array of {type, function:{name,description,parameters}}.

Definition at line 255 of file nemotron3_adapter.cpp.

◆ build_tool_evidence()

static std::string entropic::build_tool_evidence ( const std::vector< Message > &  messages,
size_t  max_results,
size_t  chars_per_result 
)
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:

  • Most-recent max_results tool-result messages only
  • Each entry truncated to chars_per_result characters
  • Older messages aggregated into a tail "(N earlier results elided)" line so the validator knows evidence is bounded

Format is human-readable (mirrors build_tool_manifest) since it lands in a critique prompt consumed by the model.

Parameters
messagesConversation messages.
max_resultsMost-recent N tool-result messages to include.
chars_per_resultPer-result truncation budget.
Returns
Evidence block, empty if no tool results in messages. @utility
Version
2.3.7

Definition at line 1431 of file engine.cpp.

◆ build_tool_manifest()

static std::string entropic::build_tool_manifest ( const std::vector< Message > &  messages)
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.

Parameters
messagesConversation messages.
Returns
Manifest string, empty if no tool calls. @utility
Version
2.1.3

Definition at line 1347 of file engine.cpp.

◆ build_tool_results_json()

static std::string entropic::build_tool_results_json ( const std::vector< Message > &  messages)
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.

Parameters
messagesConversation messages.
Returns
JSON array string. @utility
Version
2.0.10

Definition at line 1625 of file engine.cpp.

◆ call_docs_provider()

static std::string entropic::call_docs_provider ( char *(*)(const char *, void *)  fn,
const char *  section,
void *  ud 
)
static

Call docs callback with section param.

Parameters
fnDocs callback.
sectionSection name (nullptr for full doc).
udUser data.
Returns
String content.

Definition at line 669 of file entropic_server.cpp.

◆ call_history_provider()

static std::string entropic::call_history_provider ( char *(*)(int, void *)  fn,
int  max_entries,
void *  ud 
)
static

Call history callback with max_entries param.

Parameters
fnHistory callback.
max_entriesMax entries to return.
udUser data.
Returns
JSON string.

Definition at line 646 of file entropic_server.cpp.

◆ call_provider()

static std::string entropic::call_provider ( char *(*)(void *)  fn,
void *  ud 
)
static

Call a state provider callback and wrap result.

Parameters
fnCallback returning malloc'd string (or nullptr).
udUser data for callback.
Returns
JSON string (empty object if callback is null).

Definition at line 623 of file entropic_server.cpp.

◆ cancel_inflight_async_tasks()

static void entropic::cancel_inflight_async_tasks ( entropic_handle_t  handle,
ExternalBridge bridge 
)
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)

Parameters
handleEngine handle (for interrupt).
bridgeBridge whose tasks_ registry is being canceled.

Definition at line 401 of file external_bridge.cpp.

◆ capture_diff()

static bool entropic::capture_diff ( const std::filesystem::path &  base,
const std::filesystem::path &  head,
std::string &  patch 
)
static

Run git diff --no-index between base and head, capture patch.

Parameters
baseSnapshot directory.
headFinal sandbox directory.
[out]patchCaptured unified diff (may be empty when no changes).
Returns
true on success (zero or one exit code from git diff). @utility
Version
2.1.5

Definition at line 431 of file sandbox.cpp.

◆ check_create_preconditions()

static entropic_error_t entropic::check_create_preconditions ( const IdentityConfig config,
const IdentityManagerConfig mgr_config,
const std::unordered_map< std::string, IdentityConfig > &  identities 
)
static

Check create preconditions before validation.

Parameters
configIdentity config to check.
mgr_configManager configuration.
identitiesCurrent identity map.
Returns
ENTROPIC_OK if preconditions pass, error code otherwise.

Definition at line 83 of file identity_manager.cpp.

◆ check_enum()

static std::string entropic::check_enum ( const std::string &  key,
const nlohmann::json &  allowed,
const nlohmann::json &  val 
)
static

Check one property's enum and type constraints.

Parameters
keyProperty name.
propProperty schema.
valArgument value.
Returns
Error string, or empty on pass. @utility
Version
2.0.6

Check a single value against an enum constraint.

Parameters
keyProperty name.
allowedEnum array from schema.
valArgument value.
Returns
Error string, or empty on pass. @utility
Version
2.0.6

Definition at line 249 of file tool_executor.cpp.

◆ check_mutable()

static entropic_error_t entropic::check_mutable ( const std::string &  name,
const std::unordered_map< std::string, IdentityConfig > &  identities,
std::unordered_map< std::string, IdentityConfig >::const_iterator &  out_it 
)
static

Check that a mutable identity exists and is dynamic.

Parameters
nameIdentity name.
identitiesIdentity map.
Returns
Iterator to identity on success, end() on failure. Sets out_err to the error code on failure.

Definition at line 114 of file identity_manager.cpp.

◆ check_property_constraints()

static std::string entropic::check_property_constraints ( const std::string &  key,
const nlohmann::json &  prop,
const nlohmann::json &  val 
)
static

Check one property's enum and type constraints.

Parameters
keyProperty name.
propProperty schema.
valArgument value.
Returns
Error string, or empty on pass. @utility
Version
2.0.6

Definition at line 294 of file tool_executor.cpp.

◆ check_read_gates()

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.

Parameters
args_jsonJSON arguments.
Returns
ServerResponse with content or error.

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).

Definition at line 829 of file filesystem.cpp.

◆ check_required_fields()

static std::string entropic::check_required_fields ( const nlohmann::json &  schema,
const nlohmann::json &  args 
)
static

Check required fields are present.

Parameters
schemaParsed JSON Schema object.
argsParsed tool arguments.
Returns
Error string, or empty on pass. @utility
Version
2.0.6

Definition at line 217 of file tool_executor.cpp.

◆ check_type()

static std::string entropic::check_type ( const std::string &  key,
const std::string &  type,
const nlohmann::json &  val 
)
static

Check a single value against a type constraint.

Parameters
keyProperty name.
typeExpected JSON Schema type string.
valArgument value.
Returns
Error string, or empty on pass. @utility
Version
2.0.6

Definition at line 270 of file tool_executor.cpp.

◆ classify_tool_result()

static ToolResultKind entropic::classify_tool_result ( const std::string &  content)
static

Classify a tool result by its content (error/empty/ok).

Parameters
contentResult content (already size-capped).
Returns
ToolResultKind — error trumps empty trumps ok (#44). @utility
Version
2.3.7

Definition at line 747 of file tool_executor.cpp.

◆ col_opt_text()

static std::optional< std::string > entropic::col_opt_text ( sqlite3_stmt *  stmt,
int  col 
)
static

Get optional text from a sqlite3 column.

Parameters
stmtPrepared statement.
colColumn index.
Returns
Column text or nullopt if NULL. @utility
Version
1.8.8

Definition at line 49 of file backend.cpp.

◆ col_text()

static std::string entropic::col_text ( sqlite3_stmt *  stmt,
int  col 
)
static

Get text from a sqlite3 column, returning empty string for NULL.

Parameters
stmtPrepared statement.
colColumn index.
Returns
Column text or empty string. @utility
Version
1.8.8

Definition at line 36 of file backend.cpp.

◆ collect_array_names()

static std::vector< std::string > entropic::collect_array_names ( const nlohmann::json &  j)
static

Collect "name" fields from a JSON array of objects.

Parameters
jJSON array.
Returns
Vector of name strings.

Definition at line 880 of file entropic_server.cpp.

◆ collect_object_keys()

static std::vector< std::string > entropic::collect_object_keys ( const nlohmann::json &  j)
static

Collect keys from a JSON object into a vector.

Parameters
jJSON object.
Returns
Vector of key strings.

Definition at line 864 of file entropic_server.cpp.

◆ compile_grep_or_error()

std::regex entropic::compile_grep_or_error ( const std::string &  pattern,
std::string &  err 
)

Compile a regex or return a structured tool error.

Parameters
patternRegex source.
[out]errSet to a non-empty JSON error string on failure.
Returns
Compiled regex on success; the error path leaves err populated and returns a never-match regex.

Definition at line 1142 of file filesystem.cpp.

◆ compute_max_read_bytes()

static int entropic::compute_max_read_bytes ( const FilesystemConfig config,
int  model_context_bytes 
)
static

Compute max read bytes from config and model context.

Parameters
configFilesystem configuration.
model_context_bytesModel context window in bytes.
Returns
Max read bytes (32KB default when no model context provided).

Definition at line 1304 of file filesystem.cpp.

◆ compute_socket_path()

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.

Parameters
project_dirAbsolute path to project directory.
Returns
Socket path: ~/.entropic/socks/{hash8}.sock
Version
1.8.7
Parameters
project_dirProject directory.
Returns
~/.entropic/socks/{hash8}.sock @utility
Version
1.8.7

Definition at line 261 of file mcp_json_discovery.cpp.

◆ concat_messages_fallback()

static std::string entropic::concat_messages_fallback ( const std::vector< Message > &  messages)
static

Plain "role: content" join used when templating fails.

Parameters
messagesConversation history.
Returns
Concatenated fallback prompt. @utility
Version
2.3.7

Definition at line 676 of file llama_cpp_backend.cpp.

◆ concat_user_echo()

static std::string entropic::concat_user_echo ( const std::vector< Message > &  messages)
static

Concatenate user-role message text for session-log echo.

Parameters
messagesIncoming messages for the streaming turn.
Returns
Newline-joined user text (skips system/assistant turns).

Definition at line 2709 of file engine.cpp.

◆ create_adapter()

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.

Create an adapter instance by name.

Falls back to GenericAdapter.

Looks up the lowercased adapter name in the static dispatch table. Unknown names log a warning and fall back to GenericAdapter; the "generic" name itself is silent.

Parameters
nameAdapter name (e.g. "qwen35", "qwen36", "gemma4", "nemotron3", "generic").
tier_nameIdentity tier name.
identity_promptAssembled identity prompt.
Returns
Owned adapter instance.
Parameters
nameAdapter name from config (e.g. "qwen35", "generic").
tier_nameIdentity tier name.
identity_promptAssembled prompt from PromptManager.
Returns
Owned adapter. Falls back to GenericAdapter if unknown.
Version
1.8.2

Definition at line 96 of file adapter_registry.cpp.

◆ create_listen_socket()

static int entropic::create_listen_socket ( const std::filesystem::path &  path)
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.

Parameters
pathSocket filesystem path.
Returns
Listening fd, or -1 on failure. @utility
Version
2.1.7

Definition at line 665 of file external_bridge.cpp.

◆ decode_tool_calls_json()

static std::vector< ToolCall > entropic::decode_tool_calls_json ( const std::string &  tc_str)
static

Decode a JSON tool-calls array string into ToolCall vector.

Parameters
tc_strJSON array string ("[]" or "" yields empty result).
Returns
Parsed ToolCall vector (empty on parse failure or empty input).

Definition at line 1164 of file engine.cpp.

◆ derive_async_final_state()

static AsyncFinalState entropic::derive_async_final_state ( entropic_handle_t  handle,
entropic_error_t  err,
char *  result_json 
)
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)

Parameters
handleEngine handle (for last-error lookup).
errReturn code from entropic_run.
result_jsonJSON result (owned; freed on success, else NULL).
Returns
AsyncFinalState ready to be stored on the task. @utility
Version
2.0.6-rc16

Definition at line 327 of file external_bridge.cpp.

◆ destroy_orchestrator_interface()

void entropic::destroy_orchestrator_interface ( InterfaceContext context)

Free a context returned by build_orchestrator_interface().

Safe to call on nullptr.

Version
2.2.6

Definition at line 282 of file interface_factory.cpp.

◆ diff_files()

static std::vector< std::filesystem::path > entropic::diff_files ( const std::filesystem::path &  base,
const std::filesystem::path &  head 
)
static

List files differing between base and head via diff -rq-style logic.

Parameters
baseSnapshot directory.
headFinal sandbox directory.
Returns
Vector of relative paths. @utility
Version
2.3.7

Definition at line 478 of file sandbox.cpp.

◆ directive_type_name()

static const char * entropic::directive_type_name ( entropic_directive_type_t  type)
static

Map directive type enum to wire-format string.

Parameters
typeDirective type.
Returns
Type string.

Definition at line 167 of file server_base.cpp.

◆ dispatch_ask()

static json entropic::dispatch_ask ( entropic_handle_t  handle,
ExternalBridge bridge,
const json &  args,
int  client_fd,
const std::string &  call_id 
)
static

Route entropic.ask — sync (streaming) or async.

Parameters
handleEngine handle.
bridgeBridge (for async task registry).
argsTool arguments.
client_fdSocket fd.
call_idRequest id.
Returns
MCP tool result JSON.

Definition at line 506 of file external_bridge.cpp.

◆ dispatch_filterable_target()

static bool entropic::dispatch_filterable_target ( const entropic_state_provider_t p,
const std::string &  target,
const std::string &  key,
std::string &  result 
)
static

Try filterable targets (config/identity/tool).

Parameters
pState provider.
targetTarget name.
keyFilter key.
resultOutput.
Returns
true if target was handled.

Definition at line 1002 of file entropic_server.cpp.

◆ dispatch_inspect()

static std::string entropic::dispatch_inspect ( const entropic_state_provider_t p,
const std::string &  target,
const std::string &  key 
)
static

Dispatch an inspect query to the appropriate provider.

Parameters
pState provider callbacks.
targetQuery target.
keyOptional filter key.
Returns
Result string.

Definition at line 1031 of file entropic_server.cpp.

◆ dispatch_simple_target()

static bool entropic::dispatch_simple_target ( const entropic_state_provider_t p,
const std::string &  target,
const std::string &  key,
std::string &  result 
)
static

Dispatch inspect for simple (non-filterable) targets.

Parameters
pState provider.
targetTarget name.
keyOptional key.
resultOutput result string.
Returns
true if target was handled.

Definition at line 969 of file entropic_server.cpp.

◆ dispatch_tool()

static json entropic::dispatch_tool ( entropic_handle_t  handle,
ExternalBridge bridge,
const json &  params,
int  client_fd,
const std::string &  call_id 
)
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.

Parameters
handleEngine handle.
bridgeBridge instance (for async task registry).
paramsJSON-RPC params (name + arguments).
client_fdSocket fd for streaming (entropic.ask only).
call_idJSON-RPC request id for progress correlation.
Returns
MCP tool result JSON.

Definition at line 536 of file external_bridge.cpp.

◆ dup()

static char * entropic::dup ( const std::string &  s)
static

Heap-allocate a C string copy.

Parameters
sSource string.
Returns
strdup'd copy (caller frees). @utility
Version
2.0.1

Definition at line 117 of file interface_factory.cpp.

◆ enrich_manifest_with_history()

static std::string entropic::enrich_manifest_with_history ( const std::string &  base,
const ToolExecutionInterface tool_exec 
)
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)

Parameters
baseExisting manifest from messages.
tool_execTool execution interface.
Returns
Enriched manifest (base + history lines if available). @utility
Version
2.0.6-rc16

Definition at line 1473 of file engine.cpp.

◆ extract_directive_array()

static std::optional< std::pair< nlohmann::json, nlohmann::json > > entropic::extract_directive_array ( const std::string &  raw_result)
static

Pull the "directives" array out of a tool ServerResponse JSON.

Parameters
raw_resultRaw ServerResponse JSON string.
Returns
Pair of (resp object, directives reference). Returns (null, null) if the response is missing/empty/invalid.

Definition at line 1269 of file tool_executor.cpp.

◆ extract_final_text()

static std::string entropic::extract_final_text ( const char *  result_json)
static

Extract the last assistant message from a run result JSON.

entropic_run returns a JSON array of messages. This extracts the content of the last assistant-role message — the final synthesized answer after all tool calls, delegation, and validation.

Parameters
result_jsonJSON array string from entropic_run.
Returns
Last assistant message content, or empty on parse failure. @utility
Version
2.0.10

Definition at line 165 of file external_bridge.cpp.

◆ extract_parent_id()

static std::string entropic::extract_parent_id ( const nlohmann::json &  j)
static

Extract optional parent_conversation_id from JSON.

Parameters
jJSON object.
Returns
Conversation ID string, or empty if absent/null.

Definition at line 24 of file audit_entry.cpp.

◆ extract_pipeline_stages()

static std::vector< std::string > entropic::extract_pipeline_stages ( const nlohmann::json &  result_json)
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.

Parameters
ctxLoop context (mutated by directive handlers).
raw_resultServerResponse JSON string.

Extract pipeline stage names from a result JSON object.

Parameters
result_jsonParsed result JSON.
Returns
Stage tier names (empty if absent).

Definition at line 1185 of file tool_executor.cpp.

◆ extract_system_prompt()

static std::string entropic::extract_system_prompt ( const std::vector< Message > &  messages)
static

Extract the first system message content from messages.

Parameters
messagesConversation messages.
Returns
System prompt text, or empty string if none found. @utility
Version
2.0.7

Definition at line 1491 of file engine.cpp.

◆ extract_text()

std::string entropic::extract_text ( const std::vector< ContentPart > &  parts)

Extract concatenated text from content parts.

Parameters
partsContent parts array.
Returns
All text parts joined with spaces, images skipped.
Version
1.9.11
Parameters
partsContent parts array.
Returns
All text parts joined with spaces, images skipped. Empty string if parts is empty or contains no text.

Definition at line 20 of file content.cpp.

◆ extract_tier()

static std::string entropic::extract_tier ( const char *  json_str,
const std::string &  default_tier 
)
static

Extract tier name from params JSON, falling back to default.

Parameters
json_strParams JSON (may contain "tier" field).
default_tierFallback tier name.
Returns
Tier name. @utility
Version
2.0.1

Definition at line 100 of file interface_factory.cpp.

◆ filter_json_by_key()

static std::string entropic::filter_json_by_key ( const std::string &  json_str,
const std::string &  key,
const std::string &  label 
)
static

Filter a JSON value by key (object key or array name).

Parameters
json_strRaw JSON string.
keyKey to extract.
labelLabel for error messages.
Returns
Filtered JSON string or error.

Definition at line 918 of file entropic_server.cpp.

◆ find_first_user_task()

static std::string entropic::find_first_user_task ( const std::vector< Message > &  messages)
static

Find the first user-role message that isn't a tool result.

Parameters
messagesMessage list.
Returns
Content of first real user message, or empty string. @utility
Version
2.0.4

Definition at line 335 of file compaction.cpp.

◆ find_list_end()

static auto entropic::find_list_end ( std::vector< std::string > &  lines,
size_t  list_start 
)
static

Find the end of a YAML sequence (last "- " item).

Parameters
linesFile lines.
list_startIndex of the list key line.
Returns
Iterator past the last sequence item. @utility
Version
1.8.8

Definition at line 117 of file permission_persister.cpp.

◆ find_section_end()

static auto entropic::find_section_end ( std::vector< std::string > &  lines,
std::vector< std::string >::iterator  start 
)
static

Find the end of a YAML section (indented block).

Parameters
linesFile lines.
section_startIterator to section key.
Returns
Iterator past the indented block. @utility
Version
1.8.8

Definition at line 139 of file permission_persister.cpp.

◆ find_tagged()

static std::string entropic::find_tagged ( const std::vector< Message > &  messages,
const std::string &  source 
)
static

Find the first message matching a source tag.

Parameters
messagesMessage list.
sourceSource metadata value to match.
Returns
Content of matching message, or empty string. @utility
Version
2.0.4

Definition at line 316 of file compaction.cpp.

◆ fire_context_assemble_hook()

static void entropic::fire_context_assemble_hook ( const HookInterface &  hooks,
const LoopContext ctx 
)
static

Build + fire the ON_CONTEXT_ASSEMBLE info hook.

Parameters
hooksHook interface.
ctxLoop context.

Definition at line 99 of file engine.cpp.

◆ fire_hook_info()

static void entropic::fire_hook_info ( const HookInterface &  hooks,
entropic_hook_point_t  point,
const char *  json 
)
static

Fire an informational hook if the interface is wired.

Parameters
hooksHook interface.
pointHook point.
jsonContext JSON.

Definition at line 35 of file engine.cpp.

◆ fire_loop_end_hook()

static void entropic::fire_loop_end_hook ( const HookInterface &  hooks,
const LoopContext ctx 
)
static

Build + fire the ON_LOOP_END info hook.

Parameters
hooksHook interface.
ctxLoop context.

Definition at line 66 of file engine.cpp.

◆ fire_loop_iteration_hook()

static void entropic::fire_loop_iteration_hook ( const HookInterface &  hooks,
const LoopContext ctx 
)
static

Build + fire the ON_LOOP_ITERATION info hook.

Parameters
hooksHook interface.
ctxLoop context.

Definition at line 82 of file engine.cpp.

◆ fire_loop_start_hook()

static void entropic::fire_loop_start_hook ( const HookInterface &  hooks,
const LoopContext ctx 
)
static

Build + fire the ON_LOOP_START info hook.

Parameters
hooksHook interface.
ctxLoop context.

Definition at line 50 of file engine.cpp.

◆ format_tool_evidence_entry()

static std::string entropic::format_tool_evidence_entry ( const Message msg,
size_t  chars_per_result 
)
static

Format one tool-result message for the evidence block.

Parameters
msgTool-result message.
chars_per_resultPer-result truncation budget.
Returns
Formatted "## <tool> [iter N]\n<src|truncated>\n\n" entry. @utility
Version
2.3.7

Definition at line 1379 of file engine.cpp.

◆ generate_task_id()

static std::string entropic::generate_task_id ( )
static

Generate a simple UUID-like task ID.

Returns
Hex string (16 chars from random_device + pid). @utility
Version
2.0.11

Definition at line 484 of file external_bridge.cpp.

◆ generate_uuid()

std::string entropic::generate_uuid ( )

Generate a UUID v4 string.

Returns
UUID string (e.g., "550e8400-e29b-41d4-a716-446655440000"). @utility
Version
1.8.8
Returns
UUID string.

Definition at line 840 of file backend.cpp.

◆ get_applied_migrations()

static std::vector< std::string > entropic::get_applied_migrations ( sqlite3 *  db)
static

Get names of already-applied migrations.

Parameters
dbSQLite database handle.
Returns
Vector of applied migration names.

Definition at line 392 of file database.cpp.

◆ grep_search()

static std::vector< json > entropic::grep_search ( const fs::path &  root,
const std::vector< std::string > &  file_patterns,
const std::regex &  re,
const IgnoreMatcher ignore 
)
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).

Walk the tree applying the glob/ignore filter and grep files.

Parameters
rootSearch root.
file_patternsBrace-expanded glob patterns.
reCompiled content regex.
ignoreIgnore matcher.
Returns
Up to MAX_GREP_RESULTS match objects. @utility
Version
2.3.7

Definition at line 1172 of file filesystem.cpp.

◆ guard_parent_conversation()

static bool entropic::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 
)
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.

Parameters
parent_conversation_idParent ID (must be non-empty).
delegating_tierDiagnostic context.
target_tierDiagnostic context.
[out]delegation_idCleared on rejection.
[out]child_conversation_idCleared on rejection.
Returns
true if the parent is valid; false (and out params cleared) if empty.

Definition at line 510 of file backend.cpp.

◆ handle_ask()

static json entropic::handle_ask ( entropic_handle_t  handle,
const json &  args,
int  client_fd,
const std::string &  call_id 
)
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.

Parameters
handleEngine handle.
argsTool arguments.
client_fdSocket fd for streaming progress notifications.
call_idJSON-RPC request id (for progress token correlation).
Returns
MCP tool result JSON (final clean text).

Definition at line 224 of file external_bridge.cpp.

◆ handle_clear()

static json entropic::handle_clear ( entropic_handle_t  handle,
ExternalBridge bridge 
)
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)

Parameters
handleEngine handle.
bridgeBridge instance (used to reach the task registry).
Returns
MCP tool result JSON.

Definition at line 424 of file external_bridge.cpp.

◆ handle_count()

static json entropic::handle_count ( entropic_handle_t  handle)
static

Handle entropic.context_count.

Parameters
handleEngine handle.
Returns
MCP tool result JSON.

Definition at line 441 of file external_bridge.cpp.

◆ handle_status()

static json entropic::handle_status ( entropic_handle_t  handle)
static

Handle entropic.status.

Parameters
handleEngine handle.
Returns
MCP tool result JSON.

Definition at line 262 of file external_bridge.cpp.

◆ has_blocked_prefix()

static bool entropic::has_blocked_prefix ( const std::string &  key)
static

Check if key matches a blocked prefix pattern.

Parameters
keyVariable name.
Returns
true if key starts with a blocked prefix. @utility
Version
1.8.8

Definition at line 285 of file mcp_json_discovery.cpp.

◆ has_images()

bool entropic::has_images ( const std::vector< ContentPart > &  parts)

Check if content parts contain any image parts.

Parameters
partsContent parts array.
Returns
true if at least one IMAGE part exists.
Version
1.9.11
Parameters
partsContent parts array.
Returns
true if at least one IMAGE part exists.

Definition at line 41 of file content.cpp.

◆ iface_complete()

static int entropic::iface_complete ( const char *  prompt,
const char *  params_json,
char **  result_json,
void *  user_data 
)
static

Raw text completion via orchestrator.

@callback

Version
2.0.1

Definition at line 185 of file interface_factory.cpp.

◆ iface_generate()

static int entropic::iface_generate ( const char *  msgs_json,
const char *  params_json,
char **  result_json,
void *  user_data 
)
static

Generate via orchestrator.

@callback

Version
2.0.1

Definition at line 128 of file interface_factory.cpp.

◆ iface_generate_stream()

static int entropic::iface_generate_stream ( const char *  msgs_json,
const char *  params_json,
void(*)(const char *, size_t, void *)  on_token,
void *  token_ud,
int *  cancel,
void *  user_data 
)
static

Streaming generate via orchestrator.

@callback

Version
2.0.1

Definition at line 149 of file interface_factory.cpp.

◆ iface_is_complete()

static int entropic::iface_is_complete ( const char *  ,
const char *  tool_calls_json,
void *   
)
static

Check if response is complete (no pending tool calls).

@callback

Version
2.0.1

Definition at line 238 of file interface_factory.cpp.

◆ iface_parse_tool_calls()

static int entropic::iface_parse_tool_calls ( const char *  raw,
char **  cleaned,
char **  tool_calls_json,
void *  user_data 
)
static

Parse tool calls from raw model output via adapter.

@callback

Version
2.0.4

Definition at line 206 of file interface_factory.cpp.

◆ iface_route()

static int entropic::iface_route ( const char *  msgs_json,
char **  result_json,
void *  user_data 
)
static

Route messages to tier via orchestrator.

@callback

Version
2.0.1

Definition at line 171 of file interface_factory.cpp.

◆ initialize_result()

static json entropic::initialize_result ( )
static

Build the MCP initialize response payload.

Returns
JSON result object. @utility
Version
2.0.9

Definition at line 982 of file external_bridge.cpp.

◆ insert_permission_item()

static bool entropic::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 
)
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.

Parameters
linesParsed config lines (mutated).
patternPermission pattern (for the already-present check).
perms_keyThe "permissions:" key line.
list_lineThe " allow:"/" deny:" line.
itemThe " - <pattern>" item line.
Returns
true if item was inserted (write needed); false if the pattern was already present.

Definition at line 185 of file permission_persister.cpp.

◆ inspect_filterable()

static std::string entropic::inspect_filterable ( char *(*)(void *)  fn,
void *  ud,
const std::string &  key,
const std::string &  label 
)
static

Inspect a filterable target (config/identity/tool).

Parameters
fnProvider callback returning JSON.
udProvider user_data.
keyFilter key (empty = full).
labelError message label.
Returns
JSON string or error.

Definition at line 949 of file entropic_server.cpp.

◆ is_applied()

static bool entropic::is_applied ( const std::vector< std::string > &  applied,
const char *  name 
)
static

Check if a migration name is in the applied list.

Parameters
appliedApplied migration names.
nameMigration name to check.
Returns
true if already applied.

Definition at line 449 of file database.cpp.

◆ is_blocked_env_var()

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).

Parameters
keyEnvironment variable name.
Returns
true if the key is blocked.
Version
1.8.7
Parameters
keyVariable name.
Returns
true if blocked. @utility
Version
1.8.7

Definition at line 297 of file mcp_json_discovery.cpp.

◆ is_pure_tool_call()

static bool entropic::is_pure_tool_call ( const std::string &  content)
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.

Parameters
contentContent with think blocks already stripped.
Returns
true if content is only whitespace and tool_call XML. @utility
Version
2.0.6

Definition at line 964 of file constitutional_validator.cpp.

◆ is_safe_cwd()

static bool entropic::is_safe_cwd ( const std::string &  cwd)
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.

Parameters
cwdCaller-supplied working directory string.
Returns
true if cwd is safe to inline into the shell command.

Definition at line 43 of file bash.cpp.

◆ is_tool_result()

static bool entropic::is_tool_result ( const Message msg)
static

Extract original user task from messages.

Parameters
messagesMessages to search.
Returns
Task text (truncated to 500 chars).

Check if a message is a tool result rather than a user task.

Parameters
msgMessage to check.
Returns
true if the message appears to be a tool result. @utility
Version
2.0.4

Definition at line 302 of file compaction.cpp.

◆ join_lines()

static std::string entropic::join_lines ( const std::vector< std::string > &  lines)
static

Join lines back into a string with trailing newline.

Parameters
linesLines to join.
Returns
Joined string. @utility
Version
1.8.8

Definition at line 156 of file permission_persister.cpp.

◆ json_escape() [1/3]

static std::string entropic::json_escape ( const std::string &  input)
static

Save pre-compaction snapshot via storage interface.

Parameters
conversation_idConversation to snapshot.
messagesMessages before compaction.

Escape a string for JSON embedding.

Parameters
inputRaw string.
Returns
JSON-safe escaped string. @utility
Version
1.8.8

Definition at line 476 of file compaction.cpp.

◆ json_escape() [2/3]

static std::string entropic::json_escape ( const std::string &  input)
static

Escape a string for JSON embedding.

Parameters
inputRaw string.
Returns
JSON-safe escaped string. @utility
Version
1.9.9

Definition at line 46 of file compactor_registry.cpp.

◆ json_escape() [3/3]

static std::string entropic::json_escape ( const std::string &  s)
static

Escape a string for JSON embedding.

Parameters
sRaw string.
Returns
JSON-safe string (without surrounding quotes). @utility
Version
1.9.8

Definition at line 805 of file constitutional_validator.cpp.

◆ json_escape_char()

static const char * entropic::json_escape_char ( char  c)
static

Map a character to its JSON escape sequence.

Parameters
cInput character.
Returns
Escape string, or empty if no escaping needed. @utility
Version
1.9.9

Definition at line 26 of file compactor_registry.cpp.

◆ json_escape_engine()

static std::string entropic::json_escape_engine ( const std::string &  s)
static

JSON-escape a string (no surrounding quotes).

Parameters
sRaw string.
Returns
Escaped string safe for JSON embedding. @utility
Version
2.0.7

Definition at line 1324 of file engine.cpp.

◆ json_escape_into()

static void entropic::json_escape_into ( const std::string &  s,
std::string &  out 
)
static

Serialize messages to JSON for inference interface.

Parameters
messagesMessage list.
Returns
JSON array string (minimal format).

JSON-escape one string into a growing buffer.

Definition at line 485 of file response_generator.cpp.

◆ json_escape_table()

static const std::array< const char *, 256 > & entropic::json_escape_table ( )
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.

Returns
Reference to static lookup table. @utility
Version
2.0.7

Definition at line 1304 of file engine.cpp.

◆ json_extract_text_from_array()

static bool entropic::json_extract_text_from_array ( JsonCursor c,
std::string &  text 
)
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.

Parameters
cJSON cursor (positioned at opening '[').
[out]textExtracted text.
Returns
true on success. @utility
Version
1.9.11

Definition at line 342 of file compactor_registry.cpp.

◆ json_parse_array()

static bool entropic::json_parse_array ( JsonCursor c,
std::vector< Message > &  messages 
)
static

Parse message objects from a JSON array cursor.

Parameters
cJSON cursor (positioned after opening '[').
[out]messagesOutput message vector.
Returns
true on success. @utility
Version
1.9.9

Definition at line 425 of file compactor_registry.cpp.

◆ json_parse_content_part()

static bool entropic::json_parse_content_part ( JsonCursor c,
std::string &  type_val,
std::string &  text_val 
)
static

Parse one content part object, extract type and text.

Parameters
cJSON cursor (positioned after opening '{').
[out]type_valThe "type" field value.
[out]text_valThe "text" field value.
Returns
true on success (object fully consumed). @utility
Version
1.9.11

Definition at line 253 of file compactor_registry.cpp.

◆ json_parse_message()

static bool entropic::json_parse_message ( JsonCursor c,
Message msg 
)
static

Parse one JSON object into a Message (role + content).

Parameters
cJSON cursor (positioned after opening '{').
[out]msgOutput message.
Returns
true on success. @utility
Version
1.9.9

Definition at line 407 of file compactor_registry.cpp.

◆ json_read_content_part_field()

static bool entropic::json_read_content_part_field ( JsonCursor c,
std::string &  type_val,
std::string &  text_val 
)
static

Read one field of a content part object into type/text.

Parameters
cJSON cursor (positioned at key start).
[out]type_valPopulated if key == "type".
[out]text_valPopulated if key == "text".
Returns
true on success. @utility
Version
1.9.11

Definition at line 230 of file compactor_registry.cpp.

◆ json_read_field()

static bool entropic::json_read_field ( JsonCursor c,
Message msg 
)
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.

Parameters
cJSON cursor (positioned at key start).
[out]msgMessage to populate.
Returns
true on success. @utility
Version
1.9.11

Definition at line 372 of file compactor_registry.cpp.

◆ json_read_one_content_part()

static bool entropic::json_read_one_content_part ( JsonCursor c,
std::string &  text 
)
static

Parse one content part object and append text if applicable.

Parameters
cJSON cursor (positioned at '{').
[out]textAccumulated text output.
Returns
true on success. @utility
Version
1.9.11

Definition at line 320 of file compactor_registry.cpp.

◆ json_read_string()

static bool entropic::json_read_string ( JsonCursor c,
std::string &  out 
)
static

Read a JSON quoted string from cursor.

Parameters
cJSON cursor (positioned at or before opening quote).
[out]outDecoded string.
Returns
true on success. @utility
Version
1.9.9

Definition at line 151 of file compactor_registry.cpp.

◆ json_skip_composite()

static void entropic::json_skip_composite ( JsonCursor c)
static

Skip a JSON array or object in cursor (nested-aware).

Parameters
cJSON cursor (positioned at opening '[' or '{'). @utility
Version
1.9.11

Definition at line 177 of file compactor_registry.cpp.

◆ json_skip_to_element()

static char entropic::json_skip_to_element ( JsonCursor c)
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.

Parameters
cJSON cursor.
[out]textAccumulated text.
Returns
1 = continue, 0 = array end reached, -1 = error. @utility
Version
1.9.11

Advance cursor past commas/whitespace to next element.

Parameters
cJSON cursor.
Returns
Character at next element, or '\0' if past end. @utility
Version
1.9.11

Definition at line 302 of file compactor_registry.cpp.

◆ json_skip_value()

static void entropic::json_skip_value ( JsonCursor c)
static

Skip one JSON value (string, primitive, array, or object).

Parameters
cJSON cursor. @utility
Version
1.9.11

Definition at line 201 of file compactor_registry.cpp.

◆ json_skip_ws()

static void entropic::json_skip_ws ( JsonCursor c)
static

Skip whitespace in a JSON cursor.

Parameters
cJSON cursor. @utility
Version
1.9.9

Definition at line 117 of file compactor_registry.cpp.

◆ json_unescape_char()

static char entropic::json_unescape_char ( char  ch)
static

Decode one JSON escape sequence character.

Parameters
chThe character after the backslash.
Returns
Decoded character. @utility
Version
1.9.9

Definition at line 130 of file compactor_registry.cpp.

◆ list_available_keys()

static std::string entropic::list_available_keys ( const nlohmann::json &  j)
static

List available keys from a JSON value for error messages.

Parameters
jJSON object or array with "name" fields.
Returns
Comma-separated key list.

Definition at line 898 of file entropic_server.cpp.

◆ list_contains()

static bool entropic::list_contains ( const std::vector< std::string > &  lines,
size_t  start,
std::string_view  pattern 
)
static

Check if a YAML sequence already contains a pattern.

Parameters
linesFile lines.
startIndex of the list key line.
patternPattern to search for.
Returns
true if found. @utility
Version
1.8.8

Definition at line 96 of file permission_persister.cpp.

◆ load_tool_definition()

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.

Parameters
tool_nameTool name (e.g., "read_file").
server_prefixServer directory name (e.g., "filesystem").
data_dirBase directory for tool JSON files.
Returns
Parsed ToolDefinition.
Exceptions
std::runtime_errorif file not found or invalid. @utility
Version
1.8.5
Parameters
tool_nameTool name (e.g., "read_file").
server_prefixServer directory name (e.g., "filesystem").
data_dirBase directory for tool JSON files.
Returns
Parsed ToolDefinition. @utility
Version
1.8.5

Definition at line 81 of file tool_base.cpp.

◆ log_orchestration()

static void entropic::log_orchestration ( const GenerationResult result,
const std::string &  selected,
const std::string &  adapter_name,
const GenerationParams params,
double  routing_ms,
double  swap_ms 
)
static

Log the per-orchestration tier/adapter/timing summary.

Parameters
resultGeneration result (carries timings).
selectedSelected tier name.
adapter_nameAdapter that ran.
paramsResolved params (for grammar info).
routing_msRouting time.
swap_msModel-swap time. @utility
Version
2.3.7

Definition at line 365 of file orchestrator.cpp.

◆ log_prompt()

static void entropic::log_prompt ( const std::vector< Message > &  messages,
const std::string &  tier 
)
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.

Parameters
messagesMessage list being sent to inference.
tierLocked tier name. @utility
Version
2.0.6

Definition at line 35 of file response_generator.cpp.

◆ make_conversation()

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.

Parameters
titleConversation title.
project_pathProject path (optional).
model_idModel identifier (optional).
Returns
Populated record ready for INSERT. @utility
Version
1.8.8
Parameters
titleTitle.
project_pathOptional project path.
model_idOptional model ID.
Returns
Populated record.

Definition at line 889 of file backend.cpp.

◆ make_default_draft_model_config()

ModelConfig entropic::make_default_draft_model_config ( )
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.

Version
2.1.11

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 model
    • backend can do partial seq_rm with flash attn enabled.
  • context_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.

@utility

Version
2.1.11

Definition at line 619 of file config.h.

◆ make_delegation()

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.

Parameters
parent_conversation_idParent conversation ID.
child_conversation_idChild conversation ID.
delegating_tierTier initiating delegation.
target_tierTarget tier for child loop.
taskTask description.
Returns
Populated record ready for INSERT. @utility
Version
1.8.8
Parameters
parent_conversation_idParent conversation.
child_conversation_idChild conversation.
delegating_tierSource tier.
target_tierTarget tier.
taskTask description.
Returns
Populated record.

Definition at line 908 of file backend.cpp.

◆ make_git_response()

static ServerResponse entropic::make_git_response ( const std::string &  output,
int  exit_code 
)
static

Format a git result as JSON ServerResponse.

Parameters
outputCommand output.
exit_codeProcess exit code.
Returns
ServerResponse with JSON result.

Definition at line 66 of file git.cpp.

◆ make_residency_entry()

static nlohmann::json entropic::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 
)
static

JSON serialization of the current residency set.

Build one residency-snapshot JSON entry.

Parameters
nameTier name.
pathModel file path.
context_lengthTier context length (for KV estimate).
footprintResolved footprint bytes.
vram_reserve_mbConfigured headroom reserve.
last_msLast activation time (ms).
Returns
JSON entry object. @utility
Version
2.3.7

Definition at line 1414 of file orchestrator.cpp.

◆ mark_tasks_cancelling()

static bool entropic::mark_tasks_cancelling ( ExternalBridge bridge)
static

Mark every queued/running task as cancelling.

Parameters
bridgeBridge holding the task registry.
Returns
true if any task was still in-flight. @utility
Version
2.0.6-rc16

Definition at line 359 of file external_bridge.cpp.

◆ match_tag()

static bool entropic::match_tag ( const std::string &  buf,
bool &  is_open 
)
static

Check if accumulated buffer matches a think tag.

Parameters
bufBuffer to check.
is_openOutput: true if <think>, false if </think>.
Returns
true if a complete tag was matched. @utility
Version
2.0.1

Definition at line 42 of file stream_think_filter.cpp.

◆ mcp_access_level_name()

const char * entropic::mcp_access_level_name ( MCPAccessLevel  level)

Convert MCPAccessLevel to string representation.

Parameters
levelAccess level.
Returns
Static string: "NONE", "READ", or "WRITE". @utility
Version
1.9.4

Definition at line 21 of file config.cpp.

◆ names_diff()

static std::vector< std::string > entropic::names_diff ( const std::set< std::string > &  a,
const std::set< std::string > &  b 
)
static

Names in a not in b (sorted set difference).

Parameters
aSuperset candidate.
bSet to subtract.
Returns
a \ b as a vector. @utility
Version
2.3.7

Definition at line 134 of file external_client.cpp.

◆ normalize_grammar_key()

static std::string entropic::normalize_grammar_key ( const std::string &  grammar_value)
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.

Parameters
grammar_valueRaw frontmatter value.
Returns
Normalized registry key. @utility
Version
1.9.3

Definition at line 1244 of file orchestrator.cpp.

◆ now_seconds()

static double entropic::now_seconds ( )
static

Get current time as seconds since epoch.

Returns
Time in seconds (double).

Definition at line 117 of file engine.cpp.

◆ parse_mcp_access_level()

bool entropic::parse_mcp_access_level ( const std::string &  name,
MCPAccessLevel out 
)

Parse MCPAccessLevel from string.

Parameters
nameString: "NONE", "READ", or "WRITE" (case-sensitive).
[out]outParsed access level.
Returns
true if parsed successfully, false on unknown string. @utility
Version
1.9.4
Parameters
nameString: "NONE", "READ", or "WRITE" (case-sensitive).
outParsed access level.
Returns
true if parsed successfully. @utility
Version
1.9.4

Definition at line 35 of file config.cpp.

◆ parse_messages()

static bool entropic::parse_messages ( const char *  json,
std::vector< Message > &  messages 
)
static

Parse a JSON array of message objects.

Parameters
jsonJSON array string.
[out]messagesOutput message vector.
Returns
true on success, false on parse error. @utility
Version
1.9.9

Definition at line 451 of file compactor_registry.cpp.

◆ parse_messages_json()

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:

  • Missing "role" defaults to "user".
  • Missing "content" yields an empty content string.
Parameters
json_strNull-terminated JSON array string.
Returns
Parsed messages. Empty vector if the array is empty.
Exceptions
nlohmann::json::parse_erroron malformed JSON. @utility
Version
2.1.8
Parameters
json_strNull-terminated JSON. NULL or non-array yields empty.
Returns
Parsed messages (empty on null/non-array input).

Definition at line 68 of file messages_json.cpp.

◆ parse_msgs()

static std::vector< Message > entropic::parse_msgs ( const char *  json_str)
static

Parse JSON message array into Message vector.

Parameters
json_strJSON array of {role, content} objects.
Returns
Parsed messages. @utility
Version
2.0.1

Definition at line 49 of file interface_factory.cpp.

◆ parse_params()

static GenerationParams entropic::parse_params ( const char *  json_str)
static

Parse generation params from JSON string.

Parameters
json_strJSON params (may be null).
Returns
GenerationParams with parsed overrides. @utility
Version
2.0.6-rc16

Definition at line 70 of file interface_factory.cpp.

◆ parse_recovered_tool_call()

static std::optional< ToolCall > entropic::parse_recovered_tool_call ( const std::string &  fixed)
static

Parse a brace/quote-fixed JSON string into a ToolCall.

Parameters
fixedCleaned JSON string (may still be invalid → throws).
Returns
ToolCall if it has a name (any alias), else nullopt. @utility
Version
2.3.8

Definition at line 366 of file adapter_base.cpp.

◆ parse_result_fields()

static void entropic::parse_result_fields ( const nlohmann::json &  result,
AuditEntry entry 
)
static

Parse the result sub-object from JSON into AuditEntry fields.

Parameters
resultJSON result object.
[out]entryEntry to populate.

Definition at line 39 of file audit_entry.cpp.

◆ parse_tool_result_text()

static std::string entropic::parse_tool_result_text ( const std::string &  result_json)
static

Extract the "result" text from an MCP result JSON envelope.

Parameters
result_jsonRaw result string from the server.
Returns
j["result"] if parseable, else the raw string verbatim. @utility
Version
2.3.7

Definition at line 344 of file tool_executor.cpp.

◆ partition_messages()

static void entropic::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 
)
static

Partition messages (from start) into user/assistant/stripped.

Parameters
messagesInput messages.
startFirst index to classify (skips system).
[out]user_msgssource==user messages.
[out]assistant_msgsassistant-role messages.
[out]stripped_countCount of dropped messages. @utility
Version
2.3.7

Definition at line 184 of file compaction.cpp.

◆ peer_uid_matches()

static bool entropic::peer_uid_matches ( int  client_fd)
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).

Parameters
client_fdNewly accepted client fd.
Returns
true if peer uid matches our euid. @utility
Version
2.1.7

Definition at line 698 of file external_bridge.cpp.

◆ phase_observer_cb()

static void entropic::phase_observer_cb ( int  state,
void *  ud 
)
static

State observer that projects VERIFYING onto task phase.

Definition at line 1038 of file external_bridge.cpp.

◆ pipeline_context()

static std::string entropic::pipeline_context ( size_t  stage_idx,
size_t  total,
const std::vector< std::string > &  stages,
const std::string &  prior_output 
)
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.

Parameters
stage_idxZero-based stage index.
totalTotal number of stages.
stagesStage tier names.
prior_outputPrevious stage's summary/result (empty for stage 0).
Returns
Context string prepended to the task.
Version
2.1.4

Definition at line 513 of file delegation.cpp.

◆ populate_from_hook_context()

void entropic::populate_from_hook_context ( AuditEntry entry,
const AuditHookContext ctx 
)

Populate AuditEntry fields from AuditHookContext state.

Parameters
entryEntry to populate (caller_id, depth, iteration, parent_id, status).
ctxHook context with engine state pointers.
entryEntry to populate.
ctxHook context with engine state pointers.

Definition at line 245 of file audit_logger.cpp.

◆ prepare_socket_dir()

static void entropic::prepare_socket_dir ( const std::filesystem::path &  parent)
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.

Parameters
parentDirectory path. @utility
Version
2.1.7

Definition at line 593 of file external_bridge.cpp.

◆ push_delegation_cycle_rejected()

static void entropic::push_delegation_cycle_rejected ( LoopContext ctx,
const std::string &  target 
)
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)

Parameters
ctxLoop context.
targetTarget tier that would have closed the cycle.

Definition at line 1803 of file engine.cpp.

◆ push_delegation_rejected()

static void entropic::push_delegation_rejected ( LoopContext ctx)
static

Append a delegation rejection message to the loop context.

Parameters
ctxLoop context.

Definition at line 1783 of file engine.cpp.

◆ push_delegation_repeat_blocked()

static void entropic::push_delegation_repeat_blocked ( LoopContext ctx,
const std::string &  target,
int  n 
)
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.

Definition at line 1850 of file engine.cpp.

◆ push_delegation_result()

static void entropic::push_delegation_result ( LoopContext ctx,
const std::string &  target,
const DelegationResult result 
)
static

Append a delegation result message to the loop context.

Parameters
ctxLoop context.
targetTarget tier name.
resultDelegation result.

Definition at line 1830 of file engine.cpp.

◆ push_resume_failure()

static void entropic::push_resume_failure ( LoopContext ctx,
const std::string &  reason,
const std::string &  delegation_id 
)
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.

Returns
Pointer to engine-owned manager, or nullptr if no repo_dir.

Build a typed failure message for resume_delegation errors.

Definition at line 2350 of file engine.cpp.

◆ read_file()

static std::string entropic::read_file ( const std::filesystem::path &  path)
static

Read file contents as string.

Parameters
pathFile path.
Returns
File contents or empty string. @utility
Version
1.8.8

Definition at line 45 of file permission_persister.cpp.

◆ read_image_bytes()

static std::vector< uint8_t > entropic::read_image_bytes ( const std::filesystem::path &  path,
size_t  max_file_size 
)
static

Validate + read an image file fully into a byte buffer.

Parameters
pathFile path.
max_file_sizeReject files larger than this.
Returns
File bytes.
Exceptions
std::runtime_errorif missing, oversized, or unreadable. @utility
Version
2.3.7

Definition at line 146 of file image_preprocessor.cpp.

◆ read_line()

static std::string entropic::read_line ( int  fd)
static

Read one newline-delimited line from a socket fd.

Parameters
fdSocket file descriptor.
Returns
Line content, or empty on error/disconnect. @utility
Version
2.0.8

Definition at line 933 of file external_bridge.cpp.

◆ record_to_json()

static nlohmann::json entropic::record_to_json ( const ToolCallRecord rec)
static

Serialize a single ToolCallRecord to JSON.

Parameters
recRecord to serialize.
Returns
JSON object.

Definition at line 95 of file tool_call_history.cpp.

◆ regex_recovered_tool_call()

static std::optional< ToolCall > entropic::regex_recovered_tool_call ( const std::string &  json_str)
static

Last-ditch recovery: pull a tool name out via regex.

Parameters
json_strOriginal (possibly unparseable) string.
Returns
ToolCall with just id+name, or nullopt if no name found. @utility
Version
2.3.7

Definition at line 379 of file adapter_base.cpp.

◆ remove_anchor_messages()

static void entropic::remove_anchor_messages ( LoopContext ctx,
const std::string &  key 
)
static

Remove messages with a specific anchor key.

Parameters
ctxLoop context.
keyAnchor key to remove.

Definition at line 1258 of file engine.cpp.

◆ resolve_stream_finish_reason()

static std::string entropic::resolve_stream_finish_reason ( int  rc,
size_t  content_size 
)
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".

Parameters
rcBackend return code.
content_sizeAccumulated content length.
Returns
finish_reason string. @utility
Version
2.3.7

Definition at line 268 of file response_generator.cpp.

◆ resolve_target_model()

static llama_model * entropic::resolve_target_model ( const std::shared_ptr< InferenceBackend > &  tier_backend)
static

Resolve the active main-tier llama_model* for compat lookup.

Returns
Pointer to the loaded llama_model, or nullptr when no main tier is loaded or the backend is not LlamaCppBackend.

Definition at line 1156 of file orchestrator.cpp.

◆ result_kind_to_string()

const char * entropic::result_kind_to_string ( ToolResultKind  kind)
inline

Serialize a ToolResultKind to its wire-stable string form.

Parameters
kindEnum value.
Returns
Static null-terminated string. Never NULL. @utility
Version
2.1.4

Definition at line 49 of file tool_result.h.

◆ rpc_err()

static std::string entropic::rpc_err ( const json &  id,
int  code,
const std::string &  msg 
)
static

Build a JSON-RPC error response.

Parameters
idRequest ID.
codeError code.
msgError message.
Returns
Serialized JSON-RPC response. @utility
Version
2.0.8

Definition at line 81 of file external_bridge.cpp.

◆ rpc_ok()

static std::string entropic::rpc_ok ( const json &  id,
const json &  result 
)
static

Build a JSON-RPC success response.

Parameters
idRequest ID.
resultResult payload.
Returns
Serialized JSON-RPC response. @utility
Version
2.0.8

Definition at line 67 of file external_bridge.cpp.

◆ run_child_loop_trampoline()

static void entropic::run_child_loop_trampoline ( LoopContext ctx,
void *  user_data 
)
static

Trampoline for DelegationManager to call engine loop.

Parameters
ctxChild loop context.
user_dataAgentEngine pointer.

Definition at line 1772 of file engine.cpp.

◆ run_git()

static std::pair< std::string, int > entropic::run_git ( const std::string &  repo_dir,
const std::string &  git_args 
)
static

Run a git command in a given directory via popen.

Parameters
repo_dirRepository root directory.
git_argsArguments appended after "git -C repo_dir".
Returns
Pair of output string and exit code.

Definition at line 33 of file git.cpp.

◆ run_popen()

static std::pair< std::string, int > entropic::run_popen ( const std::string &  full_cmd)
static

Run a shell command and capture output.

Parameters
full_cmdCommand string including cd prefix.
Returns
Pair of output string and exit code.

Definition at line 59 of file bash.cpp.

◆ sanitize_display_name()

static std::string entropic::sanitize_display_name ( const std::string &  raw)
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.

Parameters
rawCaller-supplied display name (or command for fallback).
Returns
Sanitized name safe to embed in [<name>] log prefixes. @utility
Version
2.1.5

Definition at line 61 of file transport_stdio.cpp.

◆ send_progress()

static void entropic::send_progress ( int  fd,
const std::string &  token_text,
const std::string &  progress_token 
)
static

Send an MCP progress notification with a text token.

Parameters
fdClient socket fd.
token_textToken string to send.
progress_tokenProgress token ID for correlation. @utility
Version
2.0.10

Definition at line 196 of file external_bridge.cpp.

◆ sentinel_suffix_for_status()

static const char * entropic::sentinel_suffix_for_status ( const std::string &  status)
static

Map a terminal status string to a sentinel filename suffix.

Definition at line 1370 of file external_bridge.cpp.

◆ serialize_config()

static std::string entropic::serialize_config ( const CompactionConfig config,
const std::string &  identity,
int  token_count 
)
static

Serialize compaction config + identity to JSON.

Parameters
configCompaction config.
identityIdentity name.
token_countCurrent token count (0 if unknown).
Returns
JSON object string. @utility
Version
1.9.9

Definition at line 86 of file compactor_registry.cpp.

◆ serialize_content_parts()

static void entropic::serialize_content_parts ( const std::vector< ContentPart > &  parts,
std::string &  out 
)
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).

Definition at line 507 of file response_generator.cpp.

◆ serialize_messages()

static std::string entropic::serialize_messages ( const std::vector< Message > &  messages)
static

Serialize messages to minimal JSON array.

Parameters
messagesMessages to serialize.
Returns
JSON array string. @utility
Version
1.9.9

Definition at line 63 of file compactor_registry.cpp.

◆ serialize_messages_json()

static std::string entropic::serialize_messages_json ( const std::vector< Message > &  messages)
static

Serialize messages to minimal JSON array.

Parameters
messagesMessages to serialize.
Returns
JSON array string. @utility
Version
1.8.8

Definition at line 494 of file compaction.cpp.

◆ snapshot_git_project()

static bool entropic::snapshot_git_project ( const std::filesystem::path &  source,
const std::filesystem::path &  target 
)
static

Copy git-tracked + untracked-not-ignored files from a project.

Parameters
sourceGit repository root.
targetDestination directory.
Returns
true on success. @utility
Version
2.1.5

Definition at line 305 of file sandbox.cpp.

◆ snapshot_plain_copy()

static bool entropic::snapshot_plain_copy ( const std::filesystem::path &  source,
const std::filesystem::path &  target 
)
static

Recursive copy for non-git sources (or sandbox-to-sandbox chains).

Parameters
sourceSource directory.
targetDestination directory.
Returns
true on success. @utility
Version
2.1.5

Definition at line 342 of file sandbox.cpp.

◆ socket_path_safe()

static bool entropic::socket_path_safe ( const std::filesystem::path &  path)
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).

Parameters
pathSocket path.
Returns
true if safe to bind (path absent or is a socket). @utility
Version
2.1.7

Definition at line 612 of file external_bridge.cpp.

◆ spec_accept_round()

static bool entropic::spec_accept_round ( SpeculativeRunState state,
const llama_vocab *  vocab,
int  max_tokens,
std::function< void(std::string_view)> &  on_token,
std::atomic< bool > &  cancel 
)
static

Run one speculative accept round; return false to stop.

Definition at line 2003 of file llama_cpp_backend.cpp.

◆ spec_build_batch()

static void entropic::spec_build_batch ( SpeculativeRunState state)
static

Build the target batch [id_last, draft0, ..., draftN-1].

Parameters
stateKernel state.

Definition at line 1723 of file llama_cpp_backend.cpp.

◆ spec_check_preconditions()

static std::string entropic::spec_check_preconditions ( bool  target_active,
bool  draft_active,
llama_context *  ctx_tgt,
llama_context *  ctx_dft 
)
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.

Returns
Empty string on success, diagnostic on failure.

Definition at line 2062 of file llama_cpp_backend.cpp.

◆ spec_ckpt_restore_dft()

static void entropic::spec_ckpt_restore_dft ( SpeculativeRunState state)
static

Restore the draft's pre-draft state so the upcoming target-batch decode on the draft re-fills cleanly.

Definition at line 1875 of file llama_cpp_backend.cpp.

◆ spec_ckpt_save_dft()

static void entropic::spec_ckpt_save_dft ( SpeculativeRunState state)
static

Drive one accept round: draft → decode → sample-and-accept → emit tokens.

Returns true to continue the outer loop.

Snapshot draft state before drafting (when use_ckpt_dft).

Definition at line 1841 of file llama_cpp_backend.cpp.

◆ spec_ckpt_save_tgt()

static void entropic::spec_ckpt_save_tgt ( SpeculativeRunState state)
static

Snapshot target state right before the target decode of the speculative batch (when use_ckpt_tgt + non-empty draft).

Definition at line 1861 of file llama_cpp_backend.cpp.

◆ spec_cleanup()

static void entropic::spec_cleanup ( SpeculativeRunState state)
static

Free everything allocated by the kernel.

Parameters
stateKernel state.

Definition at line 1709 of file llama_cpp_backend.cpp.

◆ spec_commit_accepted()

static bool entropic::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 
)
static

Walk accepted ids, emit tokens via callback, update state.

Returns true if the outer loop should stop.

Definition at line 1950 of file llama_cpp_backend.cpp.

◆ spec_decode_both()

static bool entropic::spec_decode_both ( SpeculativeRunState state)
static

Decode the speculative batch on both contexts.

Populates state.error_* on failure.

Returns
true on success, false on decode failure.

Definition at line 1742 of file llama_cpp_backend.cpp.

◆ spec_emit_token()

static std::string entropic::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 
)
static

Emit on_token for one accepted id, updating state and returning a stop signal when terminating conditions apply.

Outcomes:

  • "" continue;
  • "eos" hit end-of-generation token (sets finish_reason="stop")
  • "length" reached max_tokens
  • "cancel" cancel flag set (sets error_code=CANCELLED)

Definition at line 1799 of file llama_cpp_backend.cpp.

◆ spec_finalize()

static GenerationResult entropic::spec_finalize ( SpeculativeRunState state,
std::chrono::steady_clock::time_point  t0 
)
static

Speculative kernel against an explicit draft backend.

Assemble final GenerationResult + log metrics. Helper to keep the public entry under SLOC ≤ 50.

Definition at line 2221 of file llama_cpp_backend.cpp.

◆ spec_init_run()

static std::string entropic::spec_init_run ( SpeculativeRunState state,
llama_model *  model_tgt,
const std::vector< llama_token > &  tokens,
const GenerationParams params,
int  n_draft_max,
const std::string &  draft_path 
)
static

Initialize speculative run state (prefill + sampler + decoder).

Definition at line 2163 of file llama_cpp_backend.cpp.

◆ spec_init_sampler_and_decoder()

static std::string entropic::spec_init_sampler_and_decoder ( SpeculativeRunState state,
llama_model *  model_tgt,
const GenerationParams params,
int  n_draft_max,
const std::string &  draft_path 
)
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.

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.

Parameters
stateSpeculative run state.
model_tgtTarget model (for the sampler).
paramsGeneration params.
n_draft_maxDraft cap (<=0 → 16).
draft_pathDraft model path (gates DRAFT_SIMPLE upstream).
Returns
Empty on success, diagnostic on failure. @utility
Version
2.3.7

Definition at line 2121 of file llama_cpp_backend.cpp.

◆ spec_prepare_draft()

static int entropic::spec_prepare_draft ( SpeculativeRunState state)
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.

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.

Parameters
stateSpeculative run state.
Returns
Number of tokens drafted this round. @utility
Version
2.3.7

Definition at line 1985 of file llama_cpp_backend.cpp.

◆ spec_rollback_partial()

static void entropic::spec_rollback_partial ( SpeculativeRunState state,
common_sampler *  smpl_save,
std::vector< llama_token > &  ids 
)
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.

Definition at line 1894 of file llama_cpp_backend.cpp.

◆ spec_run_draft()

static int entropic::spec_run_draft ( SpeculativeRunState state)
static

Trigger draft generation via common_speculative_draft.

Returns
Number of draft tokens proposed.

Definition at line 1773 of file llama_cpp_backend.cpp.

◆ spec_run_from_tokens()

static GenerationResult entropic::spec_run_from_tokens ( llama_context *  ctx_tgt,
llama_context *  ctx_dft,
llama_model *  model_tgt,
const std::vector< llama_token > &  tokens,
const GenerationParams params,
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 
)
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).

Parameters
messagesConversation history.
paramsGeneration parameters (samplers, max_tokens, seed).
on_tokenCallback fired once per accepted token.
cancelCancellation flag (polled between accept rounds).
draftDraft backend (must be ACTIVE on the same model arch).
n_draft_maxMaximum draft window size (proposed tokens per round). Clamped to 16 if non-positive.
Returns
GenerationResult.

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.

Parameters
ctx_tgtTarget context.
ctx_dftDraft context.
model_tgtTarget model (sampler + vocab).
tokensPrompt tokens (>= 2).
paramsGeneration parameters.
on_tokenPer-accepted-token callback.
cancelCancellation flag.
n_draft_maxDraft window cap.
draft_pathDraft model path.
t0Start timestamp for timing.
Returns
GenerationResult. @utility
Version
2.3.7

Definition at line 2285 of file llama_cpp_backend.cpp.

◆ spec_run_loop()

static void entropic::spec_run_loop ( SpeculativeRunState state,
const llama_vocab *  vocab,
int  max_tokens,
std::function< void(std::string_view)> &  on_token,
std::atomic< bool > &  cancel 
)
static

Run the accept-round loop until completion / EOS / cancel.

Definition at line 2188 of file llama_cpp_backend.cpp.

◆ spec_trim_rejected_drafts()

static void entropic::spec_trim_rejected_drafts ( SpeculativeRunState state)
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_accepted1 + 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).

Definition at line 1937 of file llama_cpp_backend.cpp.

◆ split_lines()

static std::vector< std::string > entropic::split_lines ( const std::string &  content)
static

Split string into lines.

Parameters
contentInput string.
Returns
Vector of lines. @utility
Version
1.8.8

Definition at line 77 of file permission_persister.cpp.

◆ stream_token_callback()

static void entropic::stream_token_callback ( const char *  token,
size_t  len,
void *  user_data 
)
static

Token callback for streaming generation.

Parameters
tokenToken string.
lenToken length.
user_dataStreamAccumulator pointer.

Definition at line 190 of file response_generator.cpp.

◆ strip_think_blocks()

static std::string entropic::strip_think_blocks ( const std::string &  content)
static

Strip <think>...</think> blocks from content.

The model's internal reasoning is not subject to constitutional review. Passing think blocks to the critique model causes it to evaluate planning text as if it were claims about the codebase.

Parameters
contentRaw model output.
Returns
Content with think blocks removed. @utility
Version
2.0.6

Definition at line 934 of file constitutional_validator.cpp.

◆ summarize_params()

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.

Parameters
args_jsonFull JSON arguments string.
Returns
Comma-separated key names (e.g., "path, content"). @utility
Version
1.9.12
Parameters
args_jsonFull JSON arguments string.
Returns
Comma-separated key names.

Definition at line 144 of file tool_call_history.cpp.

◆ to_llama_chat()

static std::vector< llama_chat_message > entropic::to_llama_chat ( const std::vector< Message > &  messages)
static

Apply GGUF-embedded chat template to messages.

Uses llama_chat_apply_template() which reads the template from GGUF metadata. Passes enable_thinking as a template variable via the add_generation_prompt parameter.

Parameters
messagesConversation history.
paramsGeneration parameters.
Returns
Formatted prompt string.

Convert engine messages to llama_chat_message views.

Parameters
messagesSource messages (must outlive the returned views).
Returns
Vector of {role, content} c_str pointers into messages. @utility
Version
2.3.7

Definition at line 659 of file llama_cpp_backend.cpp.

◆ tool_definitions()

static json entropic::tool_definitions ( )
static

MCP tool definitions exposed by the bridge.

Returns
JSON array of tool schemas. @utility
Version
2.0.11

Definition at line 107 of file external_bridge.cpp.

◆ tool_text()

static json entropic::tool_text ( const std::string &  text)
static

Wrap text in MCP tool result shape.

Parameters
textResult text.
Returns
MCP content array JSON. @utility
Version
2.0.8

Definition at line 95 of file external_bridge.cpp.

◆ trim_path_prefix()

static void entropic::trim_path_prefix ( std::string &  line,
std::string  p 
)
static

Strip a directory prefix p from the front of line.

Parameters
[in,out]linePath line to trim in place.
pPrefix directory (a trailing slash is added if missing). @utility
Version
2.3.7

Definition at line 458 of file sandbox.cpp.

◆ truncate_result()

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.

Parameters
textInput text.
max_lenMaximum length before truncation.
Returns
Truncated string, or original if short enough. @utility
Version
1.9.12
Parameters
textInput text.
max_lenMaximum length before truncation.
Returns
Truncated or original string.

Definition at line 171 of file tool_call_history.cpp.

◆ utc_timestamp()

std::string entropic::utc_timestamp ( )

Get current UTC time as ISO 8601 string.

Returns
Timestamp string (e.g., "2026-03-23T12:00:00"). @utility
Version
1.8.8
Returns
Timestamp string.

Definition at line 869 of file backend.cpp.

◆ utf8_char_len()

static int entropic::utf8_char_len ( unsigned char  byte)
static

Count expected bytes in a UTF-8 sequence from lead byte.

Parameters
byteLead byte.
Returns
Expected total bytes (1-4), or 0 if continuation byte. @utility
Version
2.0.2

Definition at line 55 of file stream_think_filter.cpp.

◆ validate_fields()

static std::string entropic::validate_fields ( const IdentityConfig config)
static

Validate phases and adapter_path fields.

Parameters
configConfig to validate.
Returns
Empty string on success, error message on failure.

Definition at line 63 of file identity_manager.cpp.

◆ validate_phases()

static std::string entropic::validate_phases ( const std::unordered_map< std::string, PhaseConfig > &  phases)
static

Validate all phases in an identity config.

Parameters
phasesPhase map to validate.
Returns
Empty string on success, error message on failure.

Definition at line 39 of file identity_manager.cpp.

◆ validate_tool_args()

static std::string entropic::validate_tool_args ( const std::string &  schema_json,
const nlohmann::json &  args 
)
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.

Parameters
schema_jsonThe tool's input_schema (JSON Schema string).
argsThe parsed arguments from the model.
Returns
Error description, or empty string if valid. @utility
Version
2.0.6

Definition at line 319 of file tool_executor.cpp.

◆ write_file()

static bool entropic::write_file ( const std::filesystem::path &  path,
const std::string &  content 
)
static

Write string to file.

Parameters
pathFile path.
contentContent to write.
Returns
true on success. @utility
Version
1.8.8

Definition at line 61 of file permission_persister.cpp.

◆ write_json_line()

static void entropic::write_json_line ( int  fd,
const json &  msg 
)
static

Write a JSON-RPC line to a socket fd.

Parameters
fdSocket file descriptor.
msgJSON object to serialize and write. @utility
Version
2.0.10

Definition at line 183 of file external_bridge.cpp.

Variable Documentation

◆ DIRECTIVE_NAMES

const char* const entropic::DIRECTIVE_NAMES[]
static
Initial value:
= {
"stop_processing",
"tier_change",
"delegate",
"pipeline",
"complete",
"clear_self_todos",
"inject_context",
"prune_messages",
"context_anchor",
"phase_change",
"notify_presenter",
}

Serialize ServerResponse to JSON envelope.

Parameters
responseResponse to serialize.
Returns
JSON string.

Map directive type enum to wire-format string.

Parameters
typeDirective type.
Returns
Type string.

Directive type enum → wire-format string lookup.

Definition at line 146 of file server_base.cpp.

◆ fixed

entropic::fixed = std::regex_replace(fixed, std::regex(R"(,\s*\])"), "]")

Definition at line 407 of file adapter_base.cpp.

◆ kStateNames

const char* const entropic::kStateNames[]
static
Initial value:
= {
"IDLE", "PLANNING", "EXECUTING", "WAITING_TOOL", "VERIFYING",
"DELEGATING", "COMPLETE", "ERROR", "INTERRUPTED", "PAUSED",
}

Lookup table for AgentState names indexed by enum value.

Definition at line 24 of file engine_types.cpp.

◆ logger [1/2]

auto entropic::logger = log::get("identity_manager")
static

Definition at line 17 of file identity_manager.cpp.

◆ logger [2/2]

auto entropic::logger = entropic::log::get("mcp.external_bridge")
static

Definition at line 42 of file external_bridge.cpp.

◆ MIGRATION_001_INITIAL

constexpr const char* entropic::MIGRATION_001_INITIAL
staticconstexpr

Definition at line 35 of file database.cpp.

◆ MIGRATION_002_FTS

constexpr const char* entropic::MIGRATION_002_FTS
staticconstexpr
Initial value:
= R"sql(
CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
content,
content='messages',
content_rowid='rowid'
);
CREATE TRIGGER IF NOT EXISTS messages_ai AFTER INSERT ON messages BEGIN
INSERT INTO messages_fts(rowid, content) VALUES (NEW.rowid, NEW.content);
END;
CREATE TRIGGER IF NOT EXISTS messages_ad AFTER DELETE ON messages BEGIN
INSERT INTO messages_fts(messages_fts, rowid, content)
VALUES('delete', OLD.rowid, OLD.content);
END;
CREATE TRIGGER IF NOT EXISTS messages_au AFTER UPDATE ON messages BEGIN
INSERT INTO messages_fts(messages_fts, rowid, content)
VALUES('delete', OLD.rowid, OLD.content);
INSERT INTO messages_fts(rowid, content) VALUES (NEW.rowid, NEW.content);
END;
)sql"

Definition at line 82 of file database.cpp.

◆ MIGRATION_003_DELEGATIONS

constexpr const char* entropic::MIGRATION_003_DELEGATIONS
staticconstexpr
Initial value:
= R"sql(
CREATE TABLE IF NOT EXISTS delegations (
id TEXT PRIMARY KEY,
parent_conversation_id TEXT NOT NULL,
child_conversation_id TEXT NOT NULL,
delegating_tier TEXT NOT NULL,
target_tier TEXT NOT NULL,
task TEXT NOT NULL,
max_turns INTEGER,
status TEXT NOT NULL DEFAULT 'pending'
CHECK(status IN ('pending', 'running', 'completed', 'failed')),
result_summary TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
completed_at TIMESTAMP,
FOREIGN KEY (parent_conversation_id)
REFERENCES conversations(id) ON DELETE CASCADE,
FOREIGN KEY (child_conversation_id)
REFERENCES conversations(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_delegations_parent
ON delegations(parent_conversation_id);
CREATE INDEX IF NOT EXISTS idx_delegations_child
ON delegations(child_conversation_id);
)sql"

Definition at line 106 of file database.cpp.

◆ MIGRATION_004_COMPACTION_SNAPSHOTS

constexpr const char* entropic::MIGRATION_004_COMPACTION_SNAPSHOTS
staticconstexpr
Initial value:
= R"sql(
CREATE TABLE IF NOT EXISTS compaction_snapshots (
id TEXT PRIMARY KEY,
conversation_id TEXT NOT NULL,
messages_json TEXT NOT NULL,
message_count INTEGER NOT NULL,
token_count_estimate INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (conversation_id)
REFERENCES conversations(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_snapshots_conversation
ON compaction_snapshots(conversation_id);
)sql"

Definition at line 133 of file database.cpp.

◆ MIGRATIONS

constexpr std::array<Migration, 4> entropic::MIGRATIONS
staticconstexpr
Initial value:
= {{
{"001_initial", MIGRATION_001_INITIAL},
{"002_fts", MIGRATION_002_FTS},
{"003_delegations", MIGRATION_003_DELEGATIONS},
{"004_compaction_snapshots", MIGRATION_004_COMPACTION_SNAPSHOTS},
}}

Definition at line 150 of file database.cpp.

◆ s_bound_sockets

std::unordered_set<std::string> entropic::s_bound_sockets
static

Definition at line 51 of file external_bridge.cpp.

◆ s_bound_sockets_mu

std::mutex entropic::s_bound_sockets_mu
static

Definition at line 50 of file external_bridge.cpp.

◆ s_reserved_names

const std::vector<std::string> entropic::s_reserved_names
static
Initial value:
= {
"default", "none", "all", "router"}

Reserved identity names that cannot be used.

Definition at line 20 of file identity_manager.cpp.

◆ s_tier_system_hash

std::unordered_map<std::string, size_t> entropic::s_tier_system_hash
static

Per-tier system prompt hash for diff detection across delegations.

Definition at line 22 of file response_generator.cpp.

◆ try

entropic::try
Initial value:
{
if (auto tc = parse_recovered_tool_call(fixed)) { return tc; }
} catch (...) {
return regex_recovered_tool_call(json_str);
}
return std::nullopt
static std::optional< ToolCall > parse_recovered_tool_call(const std::string &fixed)
Parse a brace/quote-fixed JSON string into a ToolCall.

Definition at line 411 of file adapter_base.cpp.

◆ VISION_INSTRUCTION

constexpr const char* entropic::VISION_INSTRUCTION
staticconstexpr
Initial value:
=
"\n\nYou can see and analyze images. When the user shares an "
"image, describe what you observe before responding to their "
"question."

Vision instruction appended to system prompt.

Definition at line 259 of file qwen35_adapter.cpp.