Skip to content

core.api

API modules: local HTTP/SSE server, command schemas, and chat log streaming.

API Server

core.api.api_server

FastAPI-based local API server for Vector Companion.

Replaces file-based IPC (chat.log polling, controls.json) with a typed HTTP API:

  • GET /events — Server-Sent Events stream of all runtime events
  • POST /commands — Issue typed commands, receive responses
  • GET /health — Liveness/readiness probe

The server binds to 127.0.0.1 only and requires a session secret (header X-Session-Secret) for authentication.

Usage

from core.api_server import ApiServer server = ApiServer(event_bus=event_bus, command_handler=handle_command) await server.start(port=8765)

later ...

await server.stop()

ApiServer

Local API server wrapping a FastAPI application.

Parameters

event_bus : EventBus, optional Runtime event bus to subscribe to. All events published on the bus are forwarded to SSE clients. command_handler : Callable, optional Async callback receiving a CommandRequest and returning a CommandResponse. If omitted, POST /commands returns 501. session_secret : str, optional Pre-shared secret for header auth. Auto-generated if omitted. host : str Bind address (default 127.0.0.1). port : int Bind port (default 8765).

base_url: str property

Base URL (e.g. http://127.0.0.1:8765).

is_running: bool property

Whether the server is currently accepting connections.

start(host: str | None = None, port: int | None = None) -> None async

Start the HTTP server as a background task.

stop() -> None async

Gracefully shut down the server.

API Protocol

core.api.api_protocol

Shared API protocol types for the Vector Companion local API.

These types are used by any frontend client (Tauri, test harnesses) to communicate with the backend via HTTP + SSE on 127.0.0.1:8765.

Originally desktop/api_client.py; relocated to core/ as shared protocol definitions.

ApiClientProtocol

Bases: ABC

Protocol for API clients (enables test mocking).

close() -> None abstractmethod async

Release resources.

event_stream() -> AsyncIterator[ApiEvent] abstractmethod async

Yield events from the SSE stream.

get_modes() -> dict[str, Any] abstractmethod async

Return the current mode flags.

health_check() -> bool abstractmethod async

Return True if the server is reachable and healthy.

send_command(command: str, category: str = 'system_action', data: dict | None = None) -> CommandResult abstractmethod async

Send a typed command and return the result.

ApiEvent dataclass

A single event from the SSE stream.

CommandResult dataclass

Response from a POST /commands call.

Command Schemas

core.api.command_schemas

Per-command parameter validation schemas (Item #22 / Phase 4C).

Every mutable command has a Pydantic schema that enforces types, required fields, value constraints, and safe defaults. The COMMAND_SCHEMAS registry maps command names to their schema class so the API server can validate before dispatching to the handler.

Design principles

  1. Fail fast — invalid params return 400 with a machine-readable error list.
  2. No silent defaults — required fields must be present; optional fields have explicit None defaults that the handler checks.
  3. Enum restrictions — mode names, model roles, sampling keys are Literal types so typos are caught at the wire boundary.
  4. Forward-compatible — unknown commands skip validation (they hit the "Unknown command" fallback in the handler instead).

CommandSchema

Bases: BaseModel

Base schema for all command parameters.

Provides a common configuration: extra fields are allowed (for forward compatibility) but tracked. Subclasses enforce the actual required/optional contract.

ExportConversationsParams

Bases: CommandSchema

No required fields — exports the entire store.

InvalidCommandParams

Bases: ValueError

Raised when command parameters fail schema validation.

Parameters

errors : List of (field, message) tuples describing each validation failure. command : The command name that failed validation.

to_dict() -> dict[str, Any]

Serialize to a structured error dict for API responses.

NoParams

Bases: CommandSchema

Schema for commands that take no parameters.

ToggleModeParams

Bases: CommandSchema

validate_command_params(command: str, params: dict[str, Any] | None = None) -> dict[str, Any]

Validate and normalize parameters for a command.

Parameters

command : Command name (e.g. "toggle_mode"). params : Raw parameter dictionary from the client.

Returns

dict[str, Any] Validated and normalized parameters (Pydantic model_dump() output). Aliases are resolved (e.g. "agent" -> "agent_name").

Raises

InvalidCommandParams If validation fails. The errors attribute provides a structured list of failures for API responses.

Chat Streaming

core.api.chat_streaming

Chat streaming output helpers.

Writes agent/user messages and tool-call markers to the chat log file, and reads/writes the control file for IPC with external consumers.

Originally ui/ui_helper.py; relocated to core/ as Tauri is the sole frontend and these functions are used by main.py and core/agent_classes.py directly.

pop_control() -> dict async

Read and clear the latest control dict.

Reads in-place (not atomic rename) to avoid Windows file-lock issues when the UI and main process share the same file.

push_control(update: dict) -> None async

Write a control dict to the control file (atomic temp+rename).

push_tool_call(tool_name: str, description: str) -> None async

Write a tool call marker to the chat log.

Format: [[TOOL:{tool_name}:{description}}] The UI parses and renders these as informational badges.

push_ui_message(message: str) -> None async

Append a message to the chat log.

push_ui_message_partial(message_id: str, speaker: str, text: str = '', is_start: bool = False, is_end: bool = False) -> None async

Write a line to the chat log using the streaming protocol.

  • If is_start is True, writes [[START:<id>:<speaker>]].
  • If is_end is True, writes [[END:<id>]].
  • Otherwise writes text as a regular sentence line.

push_user_message(message: str) -> None async

Write a user message to the chat log with a user delimiter.