Skip to content

Architecture

Blacki keeps the agent process small and delegates expensive capabilities to managed APIs when they are enabled.

Meal tool interface

When database-backed tools are enabled, the model receives meals and describe_action instead of seven separate meal functions. For example:

{
  "action": "log_meal",
  "arguments": {"description": "apple", "estimated_calories": 95}
}

describe_action(domain="meals", action="log_meal") returns the callable's description and parameter schema without accessing user records or changing permissions. Use discovery when the action parameters are unknown. The dispatcher validates types strictly, rejects unknown fields and injected context, and passes the original ADK user/session context to the existing handler. Integer parameters require integers, rather than numeric strings or floating-point values. Local storage, account ownership, private-chat export checks, and Google Health synchronization remain owned by the existing meal handlers. The nutrition policy supplies operating and consent rules.

Privacy redaction covers both new tools. Telegram progress and failure retry guards resolve the selected action, so a failed summary does not block a different meal action. Completed historical leaf-tool calls can remain in conversation history. Resuming suspended calls to removed leaf-tool names is not established by the continuation test.

This is a meals-only pilot. Training, sandbox/browser, and other domains retain their current interfaces. See the pilot measurement for schema savings and the additional cost of discovery on short workflows.

Runtime

The container runs:

python -m blacki.server

src/blacki/server.py creates a FastAPI application with Google ADK's get_fast_api_app, initializes SQLite-backed storage, optionally starts Telegram long polling, and exposes /live, /ready, and /health. It also mounts the package-backed private observability dashboard at /dashboard with APIs for aggregate statistics, users, sessions, local logs, and local traces. OpenAI-backed requests additionally write content-free usage and estimated-cost records to the local SQLite ledger so the dashboard can show per-user and per-session spend without parsing prompts or responses.

src/blacki/agent.py creates the LlmAgent, selects a native Gemini model or an OpenAI model from the environment, registers tools, and assembles the ADK application plugins.

Application composition

The application dependency direction is:

server -> agent -> tools
              -> prompts and plugins
              -> models
              -> observability
server -> runtime.adk -> ADK sessions and runners

agent.py is the ADK composition and discovery entry point. It selects tool lists from tools/registry.py, selects models through models/factory.py, and assembles the prompt and observability plugins. models/inference.py owns request-scoped model settings. models/capabilities.py answers /thinking from the static model catalog in models/catalog.py.

runtime/adk.py owns the shared ADK runner, session versioning, confirmation handling, and Telegram-facing turn orchestration. prompts/instructions.py defines the fixed root instructions and appends the application date and timezone after the other prompt context. Before the timezone, private Telegram turns with wiki access include up to 5,000 characters of the owner's memory.md. The first model call loads the page. Tool calls and retries reuse that copy for the turn, and the next Telegram turn loads the latest saved page. Use wiki_read before editing the page with wiki_write.

The private history tool search_past_sessions can search by query, list sessions across Telegram topics, or read a session's stored transcript in chronological order. List and read results provide a cursor for the next page. Sessions from before /reset remain available while retained in SQLite.

The Telegram runtime labels each OpenAI request with an opaque key derived from its versioned ADK session. Tool calls in one session share that key, and /reset starts a new session. Blacki never sends the key to OpenAI. The cost ledger records input, cached input, cache-write and output tokens, and the estimated cost of each call.

Keep blacki.agent, blacki.server:main, and python -m blacki.server as the stable discovery and execution interfaces. New internal imports should point to the owning package rather than recreating root-level modules.

Request paths

Telegram

  1. The Telegram bot polls Telegram's HTTPS API for updates.
  2. A Telegram chat is mapped to the ADK runtime.
  3. Text is sent as an ADK text part. Telegram photos and image/* documents are downloaded, validated, and sent as native inline image parts. Media groups become one ordered, separately labelled multimodal turn. Native image uploads never require sandbox materialization; R2 cataloging is best-effort.
  4. The agent calls the configured model and tools.
  5. Telegram receives the answer text. ADK retains provider-marked reasoning in session history so it can carry forward to later turns. When the private Kokoro tool is enabled and selected, it synthesizes a bounded MP3 in memory and sends it directly to the same chat or topic through Telegram sendAudio.

Long conversations use Google ADK's native token-based event compaction. After the latest prompt reaches 200,000 tokens, ADK summarizes older conversation events after the successful turn and retains the latest eight raw events for immediate context. This is prompt compaction, not a hard session reset: the same versioned Telegram session continues, the compaction event is persisted, and /reset remains available when a completely new conversation is desired.

For a private chat with the optional Google Health connector, /connect_health creates a short-lived one-time OAuth state and sends a Google authorization URL. The HTTPS callback consumes the state, exchanges the code, resolves Google's server-side identity, and stores only an encrypted refresh token plus safe connection metadata. A bounded background job refreshes and reads recent data, normalizes it into daily SQLite records, and the Telegram commands and get_health_summary tool read those normalized records. When both nutrition scopes are granted, a durable coordinator queues existing meals once per Google account. New meal mutations from eligible private chats also enqueue durable, account-bound Google nutrition-log revisions. The export worker retries pending work independently of health imports, preserves operation ordering per meal, and exposes safe pending, synced, failed, and authorization-required counts. Tokens, raw provider payloads, meal descriptions, and provider identifiers never enter application logs or traces; the user's own meal text can still appear in the private Telegram conversation as the normal result of logging a meal.

Long polling is outbound. It does not require a public webhook, domain, TLS certificate, or inbound application port.

HTTP and ADK web interface

FastAPI listens on port 8080 inside the container. Docker Compose maps that port to ${HOST_BIND_IP:-127.0.0.1}:${HOST_PORT:-8080} on the host in the production overlay. It remains loopback-only by default. The web interface is disabled in the VPS samples and can be reached securely through an SSH tunnel when enabled.

The dashboard is always available on the local server. Set HOST_BIND_IP to the server's Tailscale IPv4 address for direct tailnet access, or keep the loopback bind and use Tailscale Serve for tailnet-only HTTPS access from the repository directory:

HOST_PORT="$(sed -n 's/^HOST_PORT="\{0,1\}\([0-9][0-9]*\)"\{0,1\}$/\1/p' .env | tail -n 1)"
tailscale serve --bg "localhost:${HOST_PORT:-8080}"

The --bg flag keeps the Serve configuration across host reboots and service restarts; it remains tailnet-only. Configure Tailscale ACLs and device restrictions for the operator devices. Do not use Tailscale Funnel or set HOST_BIND_IP=0.0.0.0 because the dashboard contains private user chats.

Persistence boundaries

Blacki uses different stores for different responsibilities:

Responsibility Store Persists across restart?
ADK HTTP/web conversation sessions In-memory ADK session service No
Reminders, calories, workouts, preferences, declarative data SQLite Yes
Telegram runtime session metadata SQLite-backed application state Yes
Private Telegram wiki SQLite (wiki.db) Yes with the Compose volume
Telegram photo parts in ADK history SQLite-backed session events Yes
Google Health refresh tokens, normalized summaries, full-record archive, and import checkpoints SQLite (tools.db), tokens encrypted at rest Yes with the Compose volume
Google Health meal export revisions and retry state SQLite (tools.db), payloads account-bound and sent over HTTPS Yes with the Compose volume
Application logs and traces JSON files under /app/logs Yes with the Compose volume

Compose maps .adk_state/, data/, and logs/ from the host. Back up the first two as application state.

Native Telegram photos and image documents are capped at 10 MB because ADK retains inline user parts in session history for later conversation turns. This bounds session database growth and image replay costs while preserving multimodal context. Non-image Telegram documents continue to use the temporary per-session sandbox path.

Model provider data

With an OpenAI root model, Blacki calls OpenAI's Responses API directly with OPENAI_API_KEY. Native Gemini uses GOOGLE_API_KEY through ADK and receives no OpenAI data.

  • Every request sets store: false. OpenAI keeps no response state, and Blacki never refers to a stored response.
  • Output items from the model, including reasoning with its encrypted content, are stored with their turn in the local SQLite session database. They have the same lifetime as the messages next to them.
  • The same model gets its stored items back unchanged on later requests. A different model never receives another model's reasoning. It gets the earlier text and tool calls instead.
  • Without zero data retention approved for the OpenAI organization, OpenAI keeps abuse-monitoring logs for up to 30 days. Requesting that approval is an account decision outside Blacki.
  • Encrypted reasoning never appears in application logs, exported trace attributes, or the usage ledger. Readable reasoning summaries can appear in traces wherever message-content capture is on.
  • Compaction summaries keep only readable text.

Managed integrations

Optional tools follow the project's cloud-first principle:

  • models use OpenAI or Google;
  • search can use Exa with Brave as a fallback;
  • browser automation uses the dedicated agent_browser(args) tool inside the current session's OpenSandbox instance. Its argument array is shell-quoted, and commands time out after 90 seconds. The default ghcr.io/queryplanner/blacki-sandbox:latest image provides Chromium, a pinned agent-browser, and agent-browser's bundled usage guides; the tool itself does not install dependencies. Run agent_browser(args=["skills", "get", "core"]) for the usage guide, or agent_browser(args=["--help"]) for the command list. The tool is available to the root agent when sandbox tools are enabled. Blacki uses one root agent without a delegated task worker. Chromium profiles and screenshots remain in the temporary sandbox, and this tool adds no saved-login service or durable file retention;
  • speech synthesis can use a private Kokoro API reachable over Tailscale;
  • code execution can use an OpenSandbox server; and
  • health summaries can use Google Health API after private Telegram OAuth.

Each integration degrades independently when its credentials are absent. Startup still requires at least one model API key.

Kokoro speech delivery is registered only on the Telegram-specific root agent. The public ADK runner cannot call it. Blacki sends only the requested speech text to the configured Kokoro endpoint, accepts a bounded MP3 response, keeps it in memory, and serializes synthesis through Telegram upload so concurrent chats cannot retain multiple audio payloads. It does not retry Telegram delivery automatically. Full prompts, tool arguments, and responses are kept in the local trace file for the private dashboard; the local ADK session database retains tool calls and arguments as normal conversation history.

Google Health summaries are a separate read-only boundary. The connector uses the current Google Health API, not the legacy Fitbit Web API. It requests the current read-only activity/fitness, measurements, sleep, ECG, irregular rhythm, profile, settings, and location scopes plus googlehealth.nutrition.readonly and googlehealth.nutrition.writeonly for optional meal export. It handles missing or partially imported categories as unavailable. Health commands reject group chats, and the summary tool requires private Telegram session state. Meal export performs one durable historical backfill per Google account and keeps local save status separate from remote sync status. /disconnect_health requires an explicit inline-button confirmation, cancels future meal sync, retains local calorie logs, and does not purge records already sent to Google; requests already submitted may still complete.

The import and meal-export jobs share the existing scheduler process but remain independent: health imports use the configured interval and meal export runs every minute. Run only one active scheduler process per tools.db; the deployment does not claim cross-process dispatch leases.

Sandbox credential threat model

Sandbox commands may process untrusted uploaded files, fetched web content, and nested-agent instructions. Any of those inputs can attempt prompt injection or run shell commands that inspect the process environment. Blacki therefore treats every general-purpose sandbox as untrusted:

  • model, repository, search, OpenAI, Google, Telegram, and application credentials are never copied into the sandbox environment;
  • SANDBOX_API_KEY authenticates the host-side OpenSandbox connection only;
  • sandbox SDK exception details are not returned to tools or written to logs, because provider errors can echo credential material; and
  • the Gemini CLI sandbox skill is not registered while no least-privilege credential broker exists.

An authenticated capability must be implemented as a separately authorized, short-lived broker operation. Adding a standing environment variable is not an acceptable opt-in path.

Browser authentication takeover

When BROWSER_TAKEOVER_PUBLIC_URL is configured, the private Telegram root agent can pause an Agent Browser operation and hand the live browser viewport to the authenticated Telegram user. Blacki sends the one-time link directly through the Telegram API; the tool result returned to the model never contains the link or its token.

The browser page redeems the fragment token once, replaces it with an HttpOnly, SameSite cookie, and proxies only Agent Browser's viewport and input protocol. Passwords, OTPs, and typed text travel as transient browser input events. They are not ADK messages, tool arguments, session events, or log fields. Completing the takeover closes the stream before the model resumes.

Takeover state is process-local, hashed, bound to one private Telegram conversation, and expires after five minutes by default. The upstream sandbox endpoint and routing headers are never sent to the browser client. The public URL must sit behind authenticated HTTPS, normally a Tailscale ACL. Browser cookies and local storage remain sensitive state inside the session sandbox. Do not enable traces, screenshots, HAR capture, or video recording during a takeover.

Health semantics

/live is side-effect-free and process-only. /ready checks the already initialized SQLite connection and returns HTTP 503 during startup or database failure. /health delegates to the same implementation for compatibility.

Security boundary

The default deployment is not a public web application:

  • the host port binds to loopback;
  • the production Compose overlay disables the web interface and reload by default;
  • Telegram needs outbound HTTPS only;
  • secrets live in an ignored .env file; and
  • .dockerignore excludes secrets and runtime state from image builds.

Public web access, authentication, TLS termination, and reverse-proxy configuration are intentionally separate architectural decisions. A direct Tailscale bind or Tailscale Serve can provide private network reachability, but the application deliberately does not implement HTTP Basic auth, cookies, or Tailscale identity-header authentication.

Google Health archive

The full-history worker stores observed provider payloads in private host SQLite, separately from normalized daily summaries and nutrition exports. Its catalog selects list, reconcile, or minute rollup contracts per type. Metadata and TCX media are separate representations. Eight pages per minute and an 8 MiB page limit bound ingestion. SQLite commits observations, token-cycle hashes, and progress atomically. A connection generation changes on every authorization; stale responses cannot write after disconnect, account replacement, or reconsent.

Read-only summary tools receive coverage metadata without archival payloads. Historical observations survive provider edits and deletions until the user confirms disconnect or replaces the linked account. See Telegram setup for history bounds and gaps.