Skip to content

Tuning & cost ​

protoAgent ships the optimizations that long-running agent runtimes (Nous's Hermes Agent, OpenClaw) treat as table stakes — context compaction, aux-model routing, programmatic tool calling, prefix caching, and provider failover. Most are config flags in config/langgraph-config.yaml. This page is the map.

The levers ​

LeverConfigDefaultWhat it buys
Context compactioncompaction.*onSummarize old turns near the window limit so long sessions don't overflow
Aux-model routingcompaction.model, goal.eval_modelmain modelRun summarization + goal-verification on a cheaper/faster model
Programmatic tool callingexecute_code.*on (with Cowork)One script composes many tools in a single turn
Prompt / prefix cachingprompt_cache.*on (Anthropic-gated)Cache the stable system+tools prefix across turns
Cache warmingprompt_cache.warm.*offKeep the cached prefix warm for sporadic, latency-sensitive traffic
Provider failoverany model-role chain (model.name, routing.aux_model, …)noneEvery model role falls back down its own chain when the primary is rate-limited, out of quota, or down (fallback chains)
Iteration budgetmodel.max_iterations, subagent max_turns2000 / per-subagentStop runaway loops

Context compaction ​

SummarizationMiddleware summarizes the middle of the history when a trigger fires, keeping the last keep_messages turns intact. On by default — a long session would otherwise hit the context window and error.

The summarizer reads the whole span it replaces, not just its tail: long tool results are clipped, but every operator and agent message goes in, folded chunk by chunk on long spans, with the previous compaction's notes carried forward. The notes keep the operator's standing instructions and approvals quoted verbatim, plus the agent's commitments and pending scheduled actions (ADR 0127). /compact and the overflow safety valve use the same engine. The operator's own messages are also carried word for word in an <operator_messages> block after the notes (about 20K tokens at most, newest kept, older ones pointed at the chat archive), so a compacted chat keeps every instruction even when the summary is poor.

yaml
compaction:
  enabled: true
  trigger: "fraction:0.8"   # | "tokens:120000" | "messages:80"
  max_tokens: 200000         # absolute ceiling: fires at min(0.8 × window, 200k)
  keep_messages: 20
  # model: protolabs/fast   # summarize with a cheap model (blank = main model)

Why a ceiling. On a 1M-window model fraction:0.8 alone means 800k tokens — in practice never — while every call re-sends the whole history. A thread that grows to several hundred thousand prompt tokens costs that on every tool step; max_tokens bounds it regardless of the window. Set 0 to rely on the fraction.

Which window. The fraction is sized off the window of the model the turn actually runs on (per-chat overrides included): the gateway's model info first, then the model's own langchain profile, then a conservative window (272k for the openai-codex lane and unknown gpt-*, 200k for unknown claude-*). With no known window, the max_tokens ceiling alone triggers (a message count, logged, only when the ceiling is 0). See configuration › compaction.

Aux-model routing ​

Not every model call is the hard reasoning task. Context summarization, goal verification, and subagent delegation are lighter work — route them to a cheaper, faster alias and reserve the reasoning model for the lead turn. One knob covers all three:

yaml
routing:
  aux_model: protolabs/fast

Each path resolves specific override → routing.aux_model → main model, so you can still pin an individual path: compaction.model, goal.eval_model, or a per-subagent model (in graph/subagents/config.py) — e.g. keep a heavy-reasoning subagent on the main model while the rest run on the fast alias.

Every one of these roles — and the main model itself — now takes an ordered fallback chain, not just a single model (ADR 0133): any role field accepts a list (primary, then each fallback) as well as a string, aux_model included, and a blank role inherits its parent's whole chain (specific role → aux → main). Failover is no longer the main model's alone: when a cheap aux model is rate-limited, compaction, harvest, facts, and goal checks retry down the aux chain instead of all failing at once. See Model fallback chains for the full role list, inheritance rules, and where a fired fallback shows up.

Programmatic tool calling (execute_code) ​

Instead of a long search → fetch → search → fetch tool-call chain (one model round-trip each), the model writes one Python script that calls several tools, loops/filters/composes their results, and returns stdout (or a structured result value) — collapsing the chain into a single turn.

yaml
execute_code:
  timeout: 30
  tools: []          # empty = the curated read set
  extra_tools: []    # add tools that return a lot, by name

It is on by default with the Cowork pack. See Let the agent run code and call tools from scripts for which tools to add and how to keep variables between calls.

Security

execute_code runs model-authored code in a subprocess with a scrubbed env (no secrets) and a hard timeout, with tool calls bridged back over an fd-based RPC. It's still arbitrary code execution — enable it only for a trusted model or inside a hardened container, not on a workstation handling untrusted input.

Prefix caching & warming ​

prompt_cache applies Anthropic cache breakpoints to the stable system+tools prefix; it's a safe no-op on non-Anthropic models (vLLM gateways do prefix caching server-side). prompt_cache.warm reproduces the cached prefix on an interval so the first request after an idle gap hits a warm cache — only worth it for sporadic, latency-sensitive workloads on the 1h tier; for steady traffic it's pure cost.

Conversation history ​

Each chat session's history is checkpointed per thread_id (the chat tab's context id, prefixed a2a:), so a turn sees the prior turns instead of starting fresh — and compaction summarizes the older part near the limit. The checkpointer is bound at graph-compile time (a checkpointer set only in the invoke config is ignored by LangGraph).

By default it's a durable SQLite store (checkpoint.db_path, same /sandbox→~/.protoagent writable fallback as the other stores), so histories survive a server restart. Set checkpoint.db_path blank for an in-memory store (cleared on restart). Each tab is an independent thread; "New chat" starts a clean one.

yaml
checkpoint:
  db_path: /sandbox/checkpoints.db   # blank = in-memory
  keep_per_thread: 2                 # latest checkpoints kept per session
  max_age_days: 30                   # drop sessions idle longer than this (0 = never)
  prune_interval_hours: 6            # sweep cadence (0 disables)

A background pruner keeps the DB bounded: LangGraph writes ~3 checkpoint rows per turn and retains them all, but only the latest is needed to resume — so the sweep keeps the latest keep_per_thread per session and drops whole sessions idle past max_age_days (age decoded from the checkpoint's UUIDv6). The DB runs in WAL mode so the sweep coexists with live writes.

The sweep alone can't bound one long turn. Every super-step re-serializes the whole state, so a screenshot-heavy review once wrote 87 GB in five hours between sweeps. Two write-path bounds now handle that (ADR 0120):

  • prune_on_write applies the cap after each checkpoint write.
  • offload_media stores each image once per history DB instead of in every checkpoint.

When the DB or one session passes alert_db_mb / alert_thread_mb, the console banners it. To reclaim an already-bloated DB, run protoagent checkpoint compact, which is a dry run until you add --apply.

Harvest to history (harvest_enabled, on): when the pruner ages a session out, it's first summarized into the history table by the cheap aux model and then its raw checkpoints are dropped. Past conversations stay searchable via session_search and readable via recall_session while the bulky raw history is reclaimed — signal kept, space freed. Needs the knowledge middleware enabled. An explicit delete (the chat tab's trash button, DELETE /api/chat/sessions/{id}) uses the dialog's Memory choice instead of this setting: Save a summary harvests before deleting; Don't save anything leaves earlier knowledge-store entries alone; Erase from memory also removes the chat's saved summaries and archives. All choices remove the separate session-summary file used for automatic recall. Save a summary is the default for ordinary chats. Incognito chats omit it and default to Don't save anything. See Delete a chat and its saved memory for the limits, and What is kept, and where for the separate retention policies for turns, checkpoints, and saved history.

What's already optimal ​

  • Parallel tool calls — langchain's create_agent runs a turn's tool calls concurrently; results are stitched back in order.
  • Interruptible turns — A2A tasks/cancel + SSE disconnect stop a run cleanly without corrupting history.
  • Search-don't-load memory — KnowledgeMiddleware retrieves top-k relevant memory and knowledge under separate budgets rather than replaying full history into every prompt. Use memory_search for durable facts and preferences, knowledge_search for ingested documents, and history tools for past conversations.
  • Self-authored skills — the agent distills proven workflows into reusable SKILL.md skills (/distill), indexed in FTS5 and recalled into later prompts (the "closed learning loop").

Part of the protoLabs autonomous development studio.