Two bots live in our Telegram group.

One is Pi Telegram Agent, written by me; the other is Surowan ("Plastic Bowl"), written by our group member tcdw. The two projects share not a single line of code. Their architectural philosophies, tech stacks, and even conversational personalities are polar opposites. Yet over months of real-world group chat collisions, their evolutionary trajectories converged on the exact same commandment: save a little, then save a little more.

Many people think "saving" is a compromise on resources—a stingy exercise in engineering self-flagellation. Quite the opposite. Over the past three months and more than 74,000 production model calls, I have become increasingly convinced: in LLM-driven systems, frugality is the highest form of design aesthetics.

When you peel back the flashy scaffolding of an agent system layer by layer, you discover that code, context, and cloud bills are physically projections of the exact same entity—Tokens—across different dimensions. Elaborate mechanisms almost always breed high entropy and fragility, whereas every act of restraint derived from strict first-principles reasoning ultimately pays off in remarkable lightness, speed, and capability.

This post is both an honest ledger postmortem from a high-frequency production environment and an exercise in stripping away appearances to reach the core.

TL;DR

  • The Unified Currency Hypothesis: Your cloud bill is tokens, your context window is tokens, and to a coding agent, your codebase is tokens too. They are not separate management targets, but projections of a single conservation law across different dimensions.
  • Dissecting the Lion's Share of the Bill: 74,644 model calls reveal a brutal reality—input is 374× larger than output. Nearly 90% of a group chat bot's token ledger is chat history, while tool schemas account for just 1.1%. The survival of the system hangs entirely on context length and cache hit rate.
  • Decoupling Perception from Reasoning (Controlling Call Volume ): Replying when explicitly mentioned is deterministic logic that requires zero intelligence. Deciding whether to chime in on ambient chatter is offloaded to a dedicated small classifier model that reads only a 6-line slice (~1,650 tokens, $0.000033 per call), never polluting the main model's context. And once a message is sent, a local primitive terminates the turn immediately—pinning non-essential round-trips down to an average of 1.13 calls per turn.
  • Byte-Level Paranoia (Guarding Cache Hit Rate ): The prefix must grow monotonically and never be mutated. Dynamic stickers and asynchronous media updates are projected via read-only metadata and beforeRequest into [System Note] blocks that never enter persistent session history. Backed by 55 versions of Golden Hash regression tests, this pins our measured DeepSeek cache hit rate at 98.7%, slashing input costs to 1/30th of uncached pricing.
  • Verbatim Words Over Hallucinated Summaries (Compressing Context Depth ): We abandoned all fancy multi-tier memory extraction and graph databases. Both frontier research and production scars confirm that processed summaries are not only expensive to maintain, they actively self-poison. We fixed our context window at 128K, left raw history sleeping in SQLite, and gave the bot a clean workbench to look things up on demand: literal substring search when it remembers the exact words, semantic search when it only remembers the gist—and what comes back is always the verbatim transcript.
  • Cashing Restraint In for Freedom: The resources we saved don't just sit in a bank account; they buy extraordinary user experience. codemode lets the bot "speak while acting" with parallel retrieval, and a single rootless Linux container lets the model orchestrate native Unix tools better than a hundred hand-written plugins ever could.
  • Decluttering the Codebase Itself: Not a single line of code outside "Telegram group chat semantics" is homegrown. By leaning on the underlying Pi engine, we distilled src/ from 17,500 lines down to 8,100 lines—achieving far greater resilience through negative code.
  • Two Philosophies of Generality: Surowan builds a general product with a restrained agent; I chose a specialized deployment with a general agent.

Gazing into the Ledger: Where the Real Money Flows

All design aesthetics must rest on an unflinching gaze at physical reality.

From its launch on August 7 to the architectural overhaul on November 4, my bot recorded comprehensive telemetry for every single production model call: input size, cached tokens read, output volume, and the exact byte breakdown of each segment inside every request. After three months, the overall ledger looks like this:

Three-Month Ledger2026-08-07 — 2026-11-04 · Two bots · One group

Scale

Group messages
144,148
Human messages after router logging began
Model calls
74,644
Including 11,544 compaction calls
Public replies
39,615
Total send invocations

Tokens

Input
5.34B
Including 3.50B cache reads
Output
14.3M
Input is 374× output
Calls per turn
1.13
Non-compaction calls ÷ started turns

Input tokens include cache hits.

Input is 374 times output.

This is the first reality check that hits anyone building an LLM group chat system. Our intuition from human-computer interaction tells us that "conversation" is a symmetric game of throwing out a sentence and getting one back. In a high-frequency multi-person group chat, the truth is ruthlessly asymmetric: a group member posts a casual "haha true," and the model must chew through a heavy system prompt, tool definitions, and a massive stretch of chat history—only to think through several layers and reply with two words, or choose to stay silent.

Physically, a group chat system's bill consists almost entirely of reading.

Over these three months, we rotated through three primary models: first DeepSeek V4 Flash, then Gemini Flash in late August, and finally SWE-2 in late September. Every number below was recorded across all three in production:

Weekly Model Calls by Primary Model

Excludes compaction calls. Grouped by calendar week (UTC+8), starting from the Aug 7 launch; data comes from a local snapshot taken on Nov 1 (three days shorter than the ledger above, leaving the final week partial). Another 521 trial calls to GLM, GPT mini, etc. are omitted.

So what exactly are those billions of tokens reading? We sampled and dissected over 40,000 real request payloads, placing them side by side with a single request captured before my earlier optimization of Memoh:

What Goes Inside a Single Request

This project: average across 40,593 requests (93,067 tokens per call). Memoh before optimization: a single captured request, measured by byte share. Dashed boxes represent total input per request, scaled proportionally.

This diagram pours cold water on a lot of self-important "architectural optimizations": People love obsessing over prompt wording, trimming two sentences from the system prompt, or shortening tool names by a few characters—yet even when you optimize tool schemas to the bone, they account for a mere 1.1% of real requests.

The total cost of the entire system is governed by a minimalist mathematical model:

  • : how many times the model is woken up (call volume);
  • : how much context depth it must swallow each time it wakes up (input tokens);
  • : the fraction of context that hits the Prompt Cache (cache hit rate);
  • : the ratio of cached token pricing to full price (an astonishing 1/50 on DeepSeek, 1/10 on Claude).

This equation is our immovable foundation. In engineering terms, there are only three degrees of freedom where you can apply leverage:

  1. Wake it up less often (shrink );
  2. Lock down every byte already read (maximize );
  3. Strip away everything non-essential from each read (compress ).

Below, we will peel back our architectural choices around restraint and freedom along these three variables, one layer at a time.


Layer 1: Controlling Call Volume — Never Pay Full Price for Silence and Waiting

The cheapest model call is the one that never happens.

The most fundamental difference between a group chat and a 1-on-1 DM is that a group chat is a public, ever-flowing torrent of information—the vast majority of which has nothing to do with the bot. And that torrent almost never stops: only between 4 a.m. and 6 a.m. does the chat go quiet, peaking in activity after 10 p.m.

When Group Members Talk

Human message count by day of week and 2-hour slot (UTC+8), totaling 141,717 messages. Taken from the local database snapshot at noon on Nov 1 (three days shorter than the Nov 4 ledger above). More orange means more messages.

Now look at the ruthless funnel from incoming messages to actual public replies over those three months:

From Group Messages to Model Calls
StageCount
Group messages144,148
Bot busy, merged into next turn50,532
Turns started55,776
Model calls63,100
Public replies39,615

Turns started = messages marked as started by routing; model calls exclude compaction.

At the bottom of the funnel sits a stark fact: out of 144,000 group chat messages, the bot spoke publicly fewer than 40,000 times. Even among the 55,776 turns where it woke up to think, in more than 16,000 of them the model read the entire context and politely chose silence.

This brings us to our first sharp contradiction: How does the bot know whether to chime in? And once it decides to speak, how do we end the turn as quickly as possible?

First Principles: Social Tact Doesn't Require a 90,000-Token Panoramic Memory

"Should I chime in?" looks like an esoteric social judgment, but when you break it down, it splits into two completely distinct scenarios:

  1. Deterministic scenarios: A human explicitly @mentions the bot, replies to its message, or calls it by name. There is zero ambiguity here—a single line of deterministic code or regex routing can make the call. Not a single millisecond of model inference should ever be wasted here.
  2. Ambient scenarios: For the remaining sea of casual chatter, what the bot needs is social tact.

What does social tact look like in a group chat? Watch a real human group member:

  • Someone tosses a tricky technical question to the group, and it hangs unanswered for three minutes;
  • Someone follows up directly on what the bot just said a moment ago;
  • Two people are closely planning dinner together in a private, self-contained exchange;
  • Another bot has already given a spot-on answer;
  • Several bots are caught in a loop repeating each other.

Examine these scenarios and you reach a striking conclusion: making this call doesn't require the bot to know who it is, what happened in the group three months ago, or what tools it carries in its heavy toolbox. It depends solely on the conversational flow of the last five to ten lines.

Common off-the-shelf approaches crumble against this deduction:

  • Approach A: Let the primary model decide everything. Waking the primary model once means hauling 93,000 tokens of baggage out of bed. If the primary model thinks for two seconds and concludes "I shouldn't interrupt," you just paid full price on nearly 100,000 tokens for that silence. Multiply that across 140,000 casual messages and your bill explodes.
  • Approach B: Rely on rules and random probability gates. Rolling a die or matching keywords is free, but it has zero comprehension. It plays deaf when someone genuinely needs technical help, yet leaps out on a 10% roll to crack a bad joke while group members are having a serious discussion or venting frustration.

The right solution must live at the intersection of the two: it must have semantic comprehension, but it may only read a tiny slice; it only needs to output a probability, not generate a reply.

Follow those constraints and the answer becomes obvious: introduce a dedicated small classifier model.

How an Incoming Group Message Decides Whether to Wake the Primary Model

Direct mentions take a deterministic route without touching any model; all other messages send only the last few lines to the decider model, leaving the primary model's context and cache untouched.

I chose pplx-decider-v1.2, a specialized small classifier model on OpenRouter (driven via Pi 1.5's native classify abstraction). It is dirt cheap along three irreplaceable dimensions:

  1. Fed only a slice: It receives only the newly arrived messages plus the preceding 6 lines as background—stripping away the entire system prompt, long-range history, and tool declarations.
  2. Prefix isolation: Its invocation is a completely independent short request. Not a single byte of the primary model's core context is touched, so the primary model's Prompt Cache remains 100% intact.
  3. Negligible cost: A single decision consumes ~1,650 tokens (mostly fixed few-shot examples), costs ~$0.000033, and finishes in a few hundred milliseconds. Even if we ran every single one of the 144,000 group messages through it, the total bill would be just $4.70.
Tokens Read to Decide 'Should I Chime In?'

Primary model shows the average request from our ledger; decider model shows the measured payload including all few-shot examples. Cost per 1,000 decisions: $0.033 for the decider model vs. ~$0.26 to $1.50+ for the primary model depending on provider.

The decider model only went live on November 5. For the three months prior, ambient messages were gated by a probabilistic dice roll—and the ledger recorded the price of that design in plain sight: nearly every single turn was let in by the dice, forcing the primary model to read over 90,000 tokens from scratch each time.

What Woke the Bot Before the Decider Model Launched

Messages marked as started in routing logs by trigger reason, totaling 54,457 turns from the same Nov 1 local snapshot (three days shorter than the funnel table above). Over the same period, 50,362 messages arrived while the bot was busy and merged into the next turn, and 4,849 were skipped during cooldown.

How do we give a small model without deep world knowledge good social judgment? Pack it with high-density few-shot examples. In src/agent/decider.ts, we distilled 14 universal examples covering typical group chat micro-dynamics, lifting classifier recall straight from 0.53 to 0.71.

An even more interesting aesthetic insight came from tuning the threshold: When we tried rewriting the prompt to sound more enthusiastic—nudging the model to "want to talk more"—we found that the entire probability curve merely shifted within the noise band while burning 20% more tokens. This validated a classic principle of cybernetics: the classifier model is responsible for relative ranking; the threshold is responsible for projecting personality. Want a cool, laconic geek bot? Raise the threshold to 0.45. Want a warm, lively regular who cheers everyone on? Drop it to 0.15. The prompt never needs to be torn down and rewritten, preserving the purity of the code.

Send and Leave: Eliminating the General Agent's Monologue

Once the primary model is woken up, another massive source of waste lurks in the action execution chain.

General-purpose agent frameworks suffer from a severe case of compulsive reporting: After the model calls send(), the framework hands the Telegram delivery confirmation JSON back to the model as a tool result. The model then reloads all 93,000 tokens of context just to smugly report to the human: "I have sent the message!"

In a personal terminal assistant, that might pass for thoroughness. In a high-frequency Telegram group chat, it is an unmitigated disaster. Not only does it burn an entire extra full-context call, worse still, a group chat must never be polluted by the model's internal monologue or meta-commentary.

We laid down two iron rules:

  1. Private reasoning, explicit speech: The model's raw Assistant text stays strictly inside the console logs; a message only crosses into the group chat when the model explicitly calls the send tool. If the model reads the context and decides not to call send, the turn ends silently.
  2. Terminal Send (terminate primitive): The moment a single send call succeeds, the runtime invokes Pi's native terminate mechanism—forcibly cutting off the loop and refusing to return control to the model.
Send and Terminate: Never Come Back Just to Report

A general agent loop feeds the delivery result back to the model, forcing it to re-read the entire context just to say 'Sent!'. In our project, a successful send immediately ends the turn via Pi's terminate primitive; if the model doesn't call send, its text stays in the console.

It is precisely this decisive cutoff that locked our three-month average at 1.13 calls per turn. The extra 0.13 calls exist solely for a single self-correction pass when the bot was explicitly mentioned by a user but forgot to invoke send.

When faced with an ambiguous network timeout, many engineers reflexively retry. On Telegram, however, sending a message is an irreversible, non-idempotent action. If the message was already created on Telegram's servers before the local connection timed out, retrying produces an embarrassing duplicate message in the group. Our engineering rule is uncompromising: retries are permitted only on deterministic 4xx errors where no payload was committed; every timeout or ambiguous network state is marked no_retry and halts immediately.

When Sending Fails, Only One Case May Retry

Only deterministic 4xx errors before payload delivery are retried; everything else halts immediately.


Layer 2: Maximizing Cache Hit Rate

If cutting call volume is our first line of defense, Prompt Caching is the core lever that determines life or death.

At their core, the caching mechanisms of all modern frontier models (DeepSeek, Anthropic, OpenAI) work via Prefix Matching: As long as the prefix of your request is byte-for-byte identical to the previous turn, the price of the matched portion drops off a cliff. On DeepSeek V4 Flash, a cache hit costs a mere 1/50th of a cache miss.

Let's run the numbers on the 5.34 billion input tokens we actually processed over three months:

5.34B Input Tokens Priced at DeepSeek V4 Flash Rates

Input tokens only; 14.3M output tokens excluded. 98.7% is our measured hit rate on DeepSeek; 0% is re-reading at full price every call. Hypothetical comparison across the full 3-month volume, not my literal invoice.

Going from 85% to 98.7% looks like a modest 14-percentage-point bump on paper, yet it cuts the bill by 5×; compared against running uncached, the difference is a staggering 30×!

Cache Hit Rate Across Providers Using the Exact Same Prefix Discipline

Hit rate = cached read tokens ÷ total input tokens, excluding compaction calls, from the Nov 1 local snapshot. DeepSeek Official API: 3,415 calls (Aug 7–10); SWE-2 on Devin: 19,494 calls; Gemini Flash on Antigravity: 22,274 calls. DeepSeek calls routed via ollama-cloud (15,668 calls) did not report cache read metrics and are omitted.

That is why we inscribed the single most important physical constraint of the entire project into AGENTS.md:

Cache invariant: Never mutate an existing provider prefix; dynamic content may only be appended as a new suffix. Every request must be a strict prefix of the next request.

First-Principles Derivation of Where Dynamic Information Belongs

"Keep the prefix immutable" sounds like an easy slogan, until it collides head-on with the messy reality of a live Telegram group chat.

The most classic contradiction is Stickers.

The bot has its own fixed catalog of favorite stickers, but group members constantly post all kinds of wild third-party stickers in daily conversation. When someone drops a particularly expressive sticker, we want to tell the bot: "A group member just posted this sticker; if it fits the mood, you can use it this turn too." Clearly, this is unpredictable, dynamic candidate data that changes every single turn.

Where in the request payload should this dynamic list live? If we trace the engineering constraints step by step, every "convenient" shortcut gets eliminated one by one:

  • Failed Attempt 1: Stuff it into the System Prompt. Intuitively the cleanest place—except the System Prompt sits at the very beginning of the context window. Change a single character there, and all 90,000+ tokens of cache behind it shatter instantly.
  • Failed Attempt 2: Hang it at the very end of the request, then swap it out next turn. Since it represents "currently available stickers," many engineers tack it onto the tail of the current request, then snip off the old tail and attach a new one on the next turn. This tiny bit of laziness exacted a brutal toll in production: the tail of request vanished in request , breaking prefix continuity right at the seam. Our measurements showed that trying to save a few dozen tokens of sticker listings caused the very next turn to miss 13,600 tokens of cold cache right at turn entry!
  • Failed Attempt 3: Splice it directly into the chat transcript. If we can only append monotonically, what if we disguise the sticker metadata as message text inside the user's chat line? Disaster struck immediately: upon reading it, the model earnestly concluded that "a group member just leaked my internal sticker catalog," and proceeded to accuse group members of spying on its backend. Worse still, when the session hit its context limit and triggered compaction, the summarizer distilled this absurd suspicion—"group members leaked the bot's sticker catalog"—into an established fact, baking it permanently into the long-term summary and causing irreversible cognitive poisoning.
Only One Place Can Hold Dynamic Information

Each row shows a request after inserting a dynamic sticker list; the terracotta vertical line marks where prefix continuity breaks and the cache invalidates.

Through those three collisions with reality, the fate of dynamic information was locked by physical law into a single narrow slot:

  1. It must be strictly append-only;
  2. Once written, it must freeze forever at that relative position, inherited verbatim by subsequent turns without ever being edited or deleted mid-stream;
  3. It must never be mistaken for human speech, requiring a dedicated system marker;
  4. It must never enter the persistent session database main line, lest it pollute future compaction summaries.

This strict derivation gave birth to our final request projection structure:

Append-Only Prefixes Keep the Cache Connected

Top: proper projection where request n+1 strictly contains request n. Bottom: hanging a dynamic list at the end and swapping it next turn breaks prefix continuity at the seam.

Inside an actual request payload, it unfolds with a clean, disciplined rhythm:

Anatomy of a Real Request

Excerpt with usernames and sticker intensity descriptions removed. The dashed box is the full input of one request, read top to bottom by the model; the annotations for each block explain why it sits where it does.

Even asynchronous vision analysis strictly obeys this aesthetic: When a user first posts an image, the message line carries only a lightweight placeholder [Photo]. A few seconds later, when the async vision model finishes describing the image, the system never goes back to edit the old message. Instead, it appends an immutable incremental event to the latest input stream: [media_update #id] [Photo: a calico cat lying on a mechanical keyboard].


Layer 3: Compressing Context Depth — Why Verbatim Speech Outranks Processed Memory

Now we turn our gaze to the third variable, (the context depth swallowed on every call). Even with a 98.7% cache hit rate, remember that the remaining 1.3% of uncached traffic still pays full price—and even at cached rates, hauling 90,000 tokens on every turn generates continuous friction costs.

More importantly: a context window is not an infinitely expanding landfill. Where do old memories go? How should long-horizon conversations settle?

The Window Size Game: Do Your Own Math, Not the Provider's

A recent NVIDIA paper, You don't need long context (arXiv:2611.05306), highlighted an underlying hardware reality: under server-side Attention mechanisms, the compute cost of generating each token scales linearly with context depth. Their benchmarks on vLLM + H100 showed that a 256K window increases per-token generation cost by up to 7× compared to 16K.

Their recommendation: aggressively cap context between 16K and 48K, relying on frequent context compaction and state resets, which achieves virtually no accuracy drop on long-horizon tasks.

That is a beautiful result—but if you copy it blindly into your own application, you will walk straight into a trap. That paper models the inference provider's cost structure. For application developers calling cloud APIs, cloud billing is linear per token. Token #100,000 costs the exact same price as Token #1; the provider's internal quadratic prefill penalty does not appear on your monthly invoice.

On the application side, choosing a window size is a very different optimization game: Which is more expensive: reading slightly more on each call, or triggering compaction far more frequently?

If you set a tiny window (say, 32K), avoiding overflow forces you to wake the model frequently to run Summarization (compaction). Every compaction call exacts a heavy toll: it must read the entire old context and generate a structured summary. Worse still, the instant compaction finishes, your old deterministic prefix is dead—meaning the very next turn suffers a 100% cold-start full-price bill.

First, let's look at how many tokens each request actually read over our three-month run. The distribution is bimodal, with one peak around 40K–50K tokens and another around 110K; after we raised the window limit in late September, a long tail stretched out to the right:

Tokens Read per Request

Input token distribution across 54,847 non-compaction calls in 10K-token bins (40K means 40K–50K); the last bin is ≥240K (including 3 calls over 250K). Local snapshot as of Nov 1. The context cap was 131K initially and raised to 256K in late September.

During earlier iterations, my bot lived through both extremes of this pendulum swing:

Weekly Average Input Length vs. Share of Compaction Calls

Average input excludes compaction calls themselves. September used a homegrown compactor; in late September the window was raised from 131K to 256K.

Look at that glaring spike in late September: because our character-based token estimator mistakenly counted images as zero tokens, the system trapped itself in a nightmare loop—thinking compaction hadn't shrunk the context enough and re-triggering compaction non-stop—until nearly 45% of all model calls were just compacting! Then, when we mindlessly cranked the window up to 256K at the end of September, compaction calls dropped near zero, but the baseline payload of every single request ballooned to 130,000 tokens.

Our current architecture rests at a battle-tested equilibrium: The window is fixed at 128K, triggering Pi's native structured compaction once context reaches 110K tokens and reliably preserving the most recent ~20K tokens verbatim. Heavy tasks (multi-step search, deep research, code debugging) are offloaded via task into isolated sub-sessions, bringing only the distilled answer back to the group chat. The primary session stays crystal clean—recording only "what everyone is talking about" and "what I did," never degenerating into a bloated debugging log.

How Big Should the Context Window Be?

The color band is conceptual, not a plotted cost curve. Because cloud APIs bill linearly per token, too small a window lets compaction and cold-cache penalties outweigh smaller reads; too large a window forces every casual 'haha true' to haul a massive context. Numbers in the three cards come from the ledger above.

Bursting the Bubble: Why We Completely Abandoned Memory Systems

Whenever people talk about long-term agent evolution, they obsess over building elaborate "memory systems": entity extraction, knowledge graph triples, update/forgetting mechanisms, vector semantic pipelines...

Yet another incisive empirical study, Is Complex Agentic Memory Always Needed? (arXiv:2610.30755), popped that bubble hard. The authors benchmarked over a dozen complex agent memory frameworks against a dead-simple Raw-RAG baseline (no entity extraction, no graphs, no memory mutation—just chunking raw dialogue and retrieving it structurally). Across seven rigorous benchmarks, Raw-RAG took first place on six.

Overall Score Drop When Replacing Raw Dialogue with Processed Memory

Score delta relative to retrieving raw dialogue directly. Source: Bao et al., Is Complex Agentic Memory Always Needed? (arXiv:2610.30755).

And across individual metrics, the side with one fewer layer of processing consistently scored higher:

On the Same Metric, One Less Layer of Processing Scores Higher

Test-Time Learning: 47.68% with raw dialogue vs. 15.37% after extracting atomic facts. Full Memory Access: 57.5% on processed memory store vs. 61.6% with raw dialogue directly. Mem0 accuracy: 69.42% after removing UPDATE / DELETE vs. 67.36% with them enabled. Source: ibid.

Even more suffocating is the maintenance cost: keeping those delicate memory graphs alive on MemoryAgentBench routinely burned tens of millions of tokens and hours of compute, whereas raw retrieval finished in a dozen minutes.

This echoes our own production incidents with uncanny precision. Remember the sticker leak hallucination earlier? Once processed memory is subjectively distorted by a model, the next compaction pass solidifies that distortion into objective fact—inheriting and propagating it like a virus forever.

Our architectural response is an act of radical decluttering: We threw out all memory middleware completely. We maintain zero fact graphs and run zero periodic reflection jobs.

Every single message posted in our group over the past year rests untouched in a local SQLite database backed by a high-performance Trigram inverted index. When the model notices group members referencing "that thing someone mentioned last time" or encounters an inside joke it doesn't recognize, it wields a structured query tool called tg_messages. It can query unadulterated verbatim transcripts by nickname history, username change trails, speaker ID, reply trees, and time ranges.

No Memory Layer—Only Verbatim Transcripts

Typical memory systems extract, build graphs, mutate, and summarize on every turn. Our project skips all processing: raw transcripts sit in SQLite and are queried on demand via tg_messages across nickname history, renames, speaker ID, reply trees, and time ranges.

Leave raw context intact to time, and reserve the power of interpretation and verification for the exact moment it is needed. The former silently drains your compute on every single turn; the latter sparks an elegant retrieval only in the exact second a group member asks a follow-up question.

Remembering the Gist, Forgetting the Exact Words: Adding a Semantic Path to Verbatim Transcripts

The most frequently used parameter in tg_messages is text_contains. Backed by SQLite FTS5's trigram index, it is fundamentally an exact substring match: you have to name the exact characters that appeared in the original message for it to hit.

Human memory never works like that. When a group member asks about "that person who recommended a keyboard last time," the original conversation might not contain the word "keyboard" at all; someone might query a Chinese discussion in English; an inside joke circulating for three months has mutated through half a dozen spellings. Exact substring search isn't just "less accurate" here—it has nowhere to grab hold: the model is forced to guess synonyms one by one, and every wrong guess costs another retrieval round-trip.

Notice that "vector semantic retrieval" was on our list of standard memory-system ingredients at the start of this section. But looking back at that paper, what got falsified was never vectors—it was lossy processing: the Raw-RAG baseline that won six out of seven benchmarks works precisely by chunking raw dialogue and retrieving chunks semantically. So when we added a semantic path, we enforced three strict boundaries:

  • Zero processing: No extraction, no summarization. Vectors are purely an index over raw transcripts; what comes back is always verbatim dialogue.
  • Zero extra LLM calls: Windowing is deterministic code, and each dialogue window pays for embedding exactly once.
  • Zero new infrastructure: No vector database, no native SQLite extensions, and no new tool definitions.

Windowing: Deterministic chunking without a model. Individual group chat messages are too short—computing a separate vector for "lmao", "+1", or "true" carries almost zero semantic signal. Instead, we slice consecutive messages into dialogue windows: a window closes once it reaches 800 characters (~20 messages), accumulates 40 messages, or encounters more than 30 minutes of silence between adjacent messages. Each line is formatted as Nickname: text, with photos and stickers carrying their already-cached visual descriptions—reusing the recognition results we already paid for in media_update without looking at the media again. Only closed windows (after 30 minutes of trailing silence) enter the index; the currently open window is the live conversation already sitting in the bot's context window.

That 800-character threshold wasn't plucked out of thin air; the experiments below moved it there from our initial 1,500-character design.

Vectors: One dialogue window, one embedding. We use Gemini's gemini-embedding-2, truncated to 768 dimensions and L2-normalized. Task type is specified via input prefix rather than a separate API flag: title: none | text: … at indexing time, and task: search result | query: … at query time. Pricing is $0.20 per million tokens. Backfilling our entire group archive with the initial 1,500-character windowing produced this ledger:

One-Time Backfill2026-07-29 — 2026-11-10 · One group

Archive

Messages
273,526
~2,600 per day
Body text
7.1M chars
Excluding nicknames

Backfill

Windows
8,875
Median 1,436 chars, 32 lines
Input
7.2M tokens
11.56M chars incl. nickname prefixes
Cost
$1.43 | Pre−run estimate was $1.00–$1.50
Remaining windows
319 s
7,725 windows, four 429s

Run against a read-only snapshot of the production archive DB using the initial 1,500-char windowing code. Token count converted at the measured ~0.62 tokens/char from countTokens. The v1 indexer backfilled ~1,150 windows in 37s before hitting rate limits, then retried using the API's retryDelay hints to finish the remaining 7,725 windows in 319s.

The window size distribution reveals an important fact: the character cap, not silence, determines almost every boundary. The median window was 1,436 characters and the 75th percentile was already 1,478 characters—nearly every window pressed right up against the 1,500-character ceiling, with only 139 short windows under 200 characters. A busy group chat rarely stays silent for 30 minutes.

Strictly speaking, our earlier claim that "zero tokens are spent on memory during normal chat" now needs a footnote: every 5 minutes, a background job embeds newly closed windows. Averaged across our archive's velocity, that comes to under 70,000 tokens per day—roughly 1.4 cents. It never enters the main context, never wakes an LLM, and never mutates a single previously written byte.

Rate limiting: Indexing and querying share the same quota. Backfilling exposed our first real operational issue. Gemini allows at most 100 texts per batch (101 returns HTTP 400), and Tier 1 quota caps embedding throughput at 1,000,000 tokens per minute. Our first indexer sent batches of 50 and aborted until the next 5-minute tick on any error; it hit HTTP 429 after 23 requests, which would have dragged a full backfill out to ~40 minutes while firing eight alert notifications. Worse yet, a live semantic query during the backfill also hit a 429: background indexing and foreground queries draw from the exact same quota pool.

The fix remained pure deterministic code—no queues, no extra services: batch size 100, honor the response's retryDelay (30–41s) on 429, and self-throttle the background indexer to 800,000 characters per minute—roughly half our quota, leaving the other half for live queries from the group.

When v1.1.8 shipped with 800-character windows, we re-ran the full backfill on the production database at this pace: 15,596 windows (averaging ~17.5 messages per window) at ~1,100 windows per minute, finishing in 14.5 minutes with zero 429s. Total character volume stayed the same (~7.2M tokens, ~$1.40). End-to-end queries on the packaged release took 545–1,064 ms; with limit set to 40, rows returns one to two complete conversation windows while the remaining top-ranked windows are listed in matches with in_rows=false.

Right after the backfill finished, we hit a small plot twist: the indexer cursor suddenly jumped to ~1.787 billion. Back in August, an e2e test had inserted 21 synthetic messages into the production archive with fake senders and timestamp-sized message_id values. Real Telegram supergroup message IDs increase monotonically, which the indexer relies on to advance its cursor. Rather than adding defensive code for an "impossible branch," we backed up the database and deleted those 21 synthetic messages along with the 4 windows they had polluted, returning the cursor to its true position. Defensive code should guard against branches that can genuinely happen in reality; when an impossible branch appears from dirty data, make it impossible again.

Storage and retrieval: No vector database. Vectors are stored as float32 BLOBs in a single new table, message_chunks, where each row holds only the chat ID, the first and last message IDs of the window, the model name, and those 768 floats—the sole schema change in this feature. At query time, we embed the query into a vector and run an in-memory brute-force cosine scan across all windows in JavaScript: 768 dimensions × 8,875 windows is ~6.8 million multiply-adds, finishing in 14 milliseconds including sorting. Nearly all of a query's 470–700 ms latency is spent on the single network round-trip to the embedding API. Keeping all vectors resident in memory takes 27 MB (or ~48 MB for 15,596 windows after switching to 800-character windows—still trivial). At this scale, approximate nearest-neighbor indexes like HNSW or IVF solve a problem we simply do not have. And if we ever switch embedding models, old vectors aren't comparable anyway—we just drop and rebuild.

Verbatim Dialogue Sliced into Windows, One Vector per Window

Top: every 5 minutes the background job embeds newly closed windows (split at 800 chars, 40 messages, or >30 min silence; the active tail stays unindexed). Bottom: a query costs just one embedding call, ranks windows via in-memory cosine similarity, and returns full verbatim dialogue windows. Counts shown are illustrative.

Interface: No new tool, just one new parameter. Rather than registering a separate tool, we added a semantic parameter to tg_messages: pass a natural-language description of what you're looking for, and it returns the most relevant complete conversation windows; matches lists up to the top 10 windows with their first_id, last_id, similarity score, and an in_rows flag indicating whether that window fit into rows. It composes seamlessly with existing filters (sender, since, until, text_contains), keeping only windows that contain at least one matching message; once the model reads a window and wants to trace what led up to it or how it resolved, it uses the existing before_id / after_id cursors to page backward or forward.

This continues our earlier principle of declaring all tools upfront: adding a parameter expands the tool schema by ~1,200 characters (~700–800 tokens, well under 1% of an average request), sitting inside the frozen prefix where it is re-read at cached rates; adding a separate tool would force the model to learn and coordinate another tool contract. Because tool schemas are part of the cache-visible protocol, changing them follows strict discipline: CACHE_SCHEMA_VERSION bumped from 55 to 56 alongside an updated golden hash. The cache took a single cold start at deploy time, and remained byte-for-byte immutable thereafter.

Verification: Test on the real archive before writing the tool description. After writing the code, we didn't ship straight to production. Instead, we had a sub-agent run four experiments on the production server against a read-only snapshot of the archive database—without starting the daemon or touching the live service (having learned our lesson from two processes fighting over the same bot token). Once the experiments finished, both the snapshot and the temporary API key were deleted. All four experiments combined cost about $3:

  1. Full backfill: Backfill the entire archive snapshot to measure throughput, rate limiting, window statistics, token volume, event-loop blockage, and RSS memory growth;
  2. Query latency: Measure end-to-end semantic query latency and where the time goes;
  3. Retrieval quality: Test 25 real topics discussed in the group without using any original wording—paraphrasing, querying Chinese discussions in English, combining "person + topic" with sender filters, and constraining date ranges—plus 5 negative queries for events that never happened to see where false-positive scores land;
  4. Parameter sensitivity: Compare silence thresholds, window sizes, keeping vs. dropping the bot's own messages, and index prefixes on the most recent 30-day subset.
Semantic Retrieval BenchmarkRead-only production archive snapshot · 1,500-char windows

Speed

Semantic query
470–700 ms
Almost entirely the single embedding call
Cosine scan
14 ms
Brute-force across all windows
Literal search
50–140 ms
text_contains baseline

During Backfill

Event-loop lag
11 ms
p99, max 49 ms
Vectors in RAM
27 MB
Process RSS ~160 MB

Quality

Paraphrased hits
20 / 25
Top-1 window was the exact target
Negative queries
0.627–0.701
Top-1 score, higher than many true hits

Query latency is end-to-end from query dispatch to verbatim rows returned; cosine scan includes sorting across all 8,875 windows. Event loop and memory measured during full backfill. Negative queries: top-1 score across 5 events that never happened.

First, speed: semantic queries are several times slower than literal trigram search, but the latency lives almost entirely in the single network round-trip to the embedding API, not local compute; during the full backfill, event-loop lag peaked at just 49 ms, completely imperceptible for receiving and sending group messages.

Next, quality: out of 25 paraphrased queries, 20 returned the exact target conversation as the #1 result—covering blockchain storage, router bridging and IPTV, replacing Windows fonts, a rainy beach trip, taking a leave of absence from college, exporting an eSIM, a Minecraft iron farm, weight loss, and GPUs. Querying Chinese chat logs in English worked just as well. For niche topics (only 3–7 relevant windows in the entire archive), the #1 result was spot-on while ranks #2–#5 were mostly filler.

The queries that missed drew a crisp boundary around what semantic search cannot do:

  • Asking what a meme or slang term means: 0 / 10. Group members use slang rather than defining it in chat; for that, pass the literal slang term to text_contains.
  • Proper nouns and brand names: A paid vocabulary app or a specific quant firm is much better served by exact substring search.
  • Figurative usage drowning out literal meaning: True discussions about typhoons were rare, whereas "typhoon" used as a metaphor appeared everywhere.
  • Key facts scattered across multiple windows: A platform rug-pull or "the police said it's a civil dispute" where each window only touched a fragment.

Query phrasing matters too: a complete descriptive sentence outperforms two or three bare keywords by a wide margin. Searching just "headphones" returned 2 relevant windows in the top 5; writing "comparing noise cancellation and prices of several wireless earbuds" returned 4.

The biggest surprise was similarity scores. We originally wanted to give the model a cutoff threshold below which it should treat results as "not found." The experiment proved no such cutoff exists: relevant windows had a median score of 0.669 while irrelevant ones had a median of 0.658, with nearly complete overlap. Across 5 negative queries for events that never happened, the #1 score ranged from 0.627 to 0.701—a fabricated query about "wedding photos" scored 0.701, beating many genuine hits. Whenever the gap between #1 and #5 exceeded 0.05, the top result was always right, yet many genuine hits differed by only 0.01–0.03, indistinguishable from negative queries. So we wrote this rule directly into the tool description: similarity scores are only for relative ranking within a single query; the model must read rows to verify relevance, rephrase or fall back to text_contains if they don't match, and never assert "the group has never discussed this" based on scores alone.

The experiment also caught a result-shaping bug: when limit was set to 30–40, queries always returned only a single window—because the first window had nearly 40 messages, the second window didn't fit, and the loop broke early. Now windows that don't fit the remaining row budget are skipped rather than halting the loop, ensuring the top window is always returned while other high-ranking windows are flagged via in_rows in matches so the model can fetch them by ID if needed.

We tuned our windowing parameters on the 30-day subset:

Choosing Windowing Parameters
ConfigP@1P@5MRRMsg Prec.Windows
Baseline0.760.470.830.732,241
10-min silence0.760.480.830.742,562
800 chars (shipped)0.810.570.840.783,720
3,000 chars / 80 msgs0.620.460.740.621,145
Drop bot messages0.480.390.620.481,948
Drop index prefix0.710.470.770.682,238

30-day subset, 21 queries plus 3 negative queries for events that never happened. Baseline is 30-min silence, 1,500 chars, 40 messages. P@1, P@5: fraction of relevant windows in top 1 and top 5; MRR: mean reciprocal rank of the first relevant window; Msg Prec. (message precision): fraction of the 40-message budget landing inside relevant windows. Raising the character limit alone to 3,000 hit the 40-message cap first and changed nothing, so that row also raised the cap to 80 messages.

Three takeaways jumped out. First, smaller windows are more accurate: 800 characters won on every single metric while keeping total character count—and therefore embedding token cost—completely unchanged. Second, a 10-minute vs. 30-minute silence threshold made almost no difference, confirming again that window boundaries are driven primarily by character length. Most surprising of all were the bot's own messages: they accounted for 75% of total character volume and looked like noise we should strip out, yet the bot's explanations carried the exact topical vocabulary that anchored retrieval—dropping bot messages tanked P@1 from 0.76 down to 0.48.

Finally, the examples in the tool description grew directly out of these experiments: "someone explained how to make a custom sticker pack," "comparing noise cancellation and prices of several wireless earbuds," the English query "someone got liquidated on a high-leverage position," combining sender with "plans for taking a gap year from school," pairing with text_contains to lock down a keyword, and using after_id / before_id to expand surrounding context. Every single example in the prompt is a query that actually succeeded in our benchmark, and the failure modes were documented verbatim under "When not to use."

In total, the feature added 552 lines and deleted 25 lines in src/ (339 of which live in the new semantic.ts): one table, one parameter. It adds zero "memory layers" to the bot: when nobody asks about the past, not a single extra character enters the primary model's context; when someone does ask, what comes back is still the verbatim transcript from that day.


Cashing Restraint In for Freedom: Speed and Capability Are Born from Frugality

Reading this far, someone might form a misconception: if this project counts every penny and every token with such ruthless discipline, doesn't the bot feel rigid, impoverished, and sluggish?

The reality is the exact opposite. All our restraint and weight-shedding was never about hoarding money in a ledger—it was about converting massive compute overhead into unprecedented agility and versatility when it actually counts.

Highlight 1: The Breathing Room of Codemode — Speaking While Acting

The strongest immediate impression group members report is: "Why does your bot respond so ridiculously fast?" It isn't because we swapped in some ultra-low-latency model; the secret lies entirely in the interaction aesthetics of codemode.

Consider how a mainstream agent framework mechanically grinds through a multi-step request like "Look up the origin of this tech meme and summarize what our group has said about it":

  1. The model reads 90,000 tokens and decides to call search;
  2. Long wait while the network returns search results;
  3. The model re-reads all 90,000 tokens plus pages of raw HTML snippets, then decides to call a second tool;
  4. Another wait, another full re-read of the entire context to fetch a web page;
  5. After four or five heavy, full-price round-trips, users have been staring at a dead "typing..." indicator for half a minute;
  6. Finally, several pages of unfiltered web text get welded permanently into the chat history for all subsequent turns.

In our architecture, the model uses Pi's isolated sandbox to write a short, native JavaScript program in a single turn:

// 1. Speak first to break the dead silence of waiting
await tools.send({ text: "Let me check the group archive and look up that meme—one sec!" });

// 2. Dispatch in parallel and aggregate inside the sandbox
const [searchRes, historyRes] = await Promise.allSettled([
  tools.search({ query: "open source project architecture overhaul" }),
  tools.tg_messages({ text_contains: "architecture overhaul", limit: 10 }),
]);

// 3. Slice and filter in sandbox RAM so raw junk never enters the main context
const web = searchRes.status === "fulfilled" ? searchRes.value : null;
const chat = historyRes.status === "fulfilled" ? historyRes.value : null;

text({
  summary: web?.slice(0, 1000),
  discussions: chat?.rows.map(({ sender, text }) => `${sender.name}: ${text}`),
});
js

Laying the two execution models side by side makes the difference clear—look at how many times the primary model wakes up and what it has to read each time:

The Same Task, Run Two Ways

In a traditional agent loop, every tool result returns to the primary model for another full-context re-read; the diagram shows two tool calls, though real tasks often take four or five. In codemode, a sandboxed script sends an immediate heads-up, runs searches in parallel, and slices the output—waking the primary model only twice.

Savor the aesthetic power packed into that short script:

  1. Speak first (thoughtful pacing): Executing send on line 1 delivers an immediate acknowledgment to the user's client within a few hundred milliseconds. The psychological friction of "dead waiting" turns instantly into "it's already on it." Calling send inside the codemode sandbox does not trigger turn termination, allowing the pipeline to keep flowing in the background.
  2. True parallel execution: Network requests should naturally run concurrently. Promise.allSettled collapses multiple serial round-trips into one.
  3. A context firewall: Tens of kilobytes of raw web text and redundant metadata are distilled in place inside sandbox RAM; only a few hundred tightly sliced characters of core signal are fed back to the primary model.

We deliberately passed on the "native parallel tool calling" touted by model providers. Native parallel tool calls are one-way and rigid—you cannot speak a reassuring sentence first and branch dynamically on the return values within the same batch, nor can you stop the raw tool outputs from flooding your main context window. codemode is the unique solution that fuses instant responsiveness, dynamic control flow, and context hygiene into one.

Highlight 2: One Complete Linux Container Beats a Hundred Fragile Plugins

Many developers measure an agent's power by the length of its plugin list: weather plugins, charting plugins, audio transcoding plugins, PDF reader plugins, web snapshot plugins... Every plugin adds a verbose schema, thousands of lines of glue code, and a third-party boundary waiting to break. Worse still, the model's capability ceiling is permanently locked inside the intersection of plugins the author bothered to write. If a group member wants to extract specific frames from a video and turn them into a monochrome GIF, and the author never wrote a plugin for that, the agent can only shrug.

Our design aesthetic went to the opposite extreme: give the model a real Linux machine.

Through Pi's native file and shell primitives (read / write / edit / bash), the bot commands a rootless Docker container running under an isolated system user. Its workspace comes preloaded with a full modern toolchain: Python (uv), Node.js, ffmpeg, ImageMagick, ripgrep, Chromium, and full CJK fonts.

Magical things happen as a result:

  • Want to trim video, extract audio, or compress a sticker? The model types a one-line ffmpeg command in the sandbox;
  • Want to crunch data or render a complex heatmap? The model runs uv run --with matplotlib python main.py inside the container;
  • When a group member asks curiously, "How does your underlying logic actually work?", the bot uses bash to clone its own GitHub repository into /work/src, searches the codebase with rg, and explains its own implementation line by line;
  • Once an artifact is ready, it pushes the output straight back to the group as native files or photo albums via send.files.

For all of these capabilities, we didn't write a single line of "plugin code." Frontier models have already been trained on humanity's entire open-source Unix ecosystem—they speak Shell natively. The only respectful thing for us to do is not to play babysitter and reinvent wheels for them, but to draw a firm security boundary and hand them a clean, isolated, always-ready general execution environment.

Around that clean container boundary, we built a defense-in-depth security perimeter:

A Complete Linux Machine Inside Layered Boundaries

The bot daemon and the container run under separate OS users; the container holds zero API keys, SSH keys, or secrets, and both model requests and outbound files pass through the daemon.

One general execution environment replaced an endless parade of mediocre plugins. That architectural convergence holds far more beauty than any micro-optimization in code.


The Final Layer: Code Is Context — Distilling 17,500 Lines Down to 8,089

If we shift our gaze from the runtime model back to our own daily workflow as developers, we find the exact same physical laws governing everything.

From day one, this project was built iteratively alongside a Coding Agent. In a Coding Agent's world, your codebase is its context window. Every redundant wrapper you write, every abstraction layer reserved for hypothetical "future extensibility," and every wavering compatibility branch ruthlessly consumes the coding model's attention and comprehension in every single development session.

Evolution of Lines of Code in src/

Total lines across src/**/*.ts on each commit date; horizontal axis is scaled proportionally to calendar time.

By November 1, bogged down by homegrown schedulers, compaction-retry state machines, and sprawling prompt-assembly glue, our codebase had ballooned to 17,522 lines. Over the next four days, following a thorough philosophical reckoning, we took a scalpel to the repo and cut it straight down to 8,089 lines.

The codebase shrank by more than half, yet production capability didn't contract—in fact, it unlocked one-command installation, native vision understanding, automatic crash recovery, and the full-featured container sandbox.

How? By enforcing one uncompromising rule: If it does not belong to "Telegram group chat semantics," not a single line of it should be written by us.

Look back at four of our worst production incidents:

Four Production Incidents

Dates are in 2026. The top half of each card shows the symptom group members saw; the bottom half shows the root cause we uncovered.

Not a single one of these four hair-raising incidents had anything to do with Telegram itself. Every one of them came from our own homegrown session state machines and compaction algorithms.

True engineering maturity means handing specialized infrastructure back to a solid foundation. Pi 1.5 provides first-class durable primitives out of the box: persistent sessions, crash recovery, AST-aware structured compaction, execution queues, and sandbox orchestration. In a single migration commit, we deleted 7,877 lines of homegrown code:

  • Deleted our painstakingly maintained session state machine and complex fingerprint diffing;
  • Deleted our brittle character-based token estimator and custom summary-packing logic;
  • Deleted our homegrown background child-process bridge and scheduling pipeline;
  • Deleted 300 lines of verbose tool usage examples stuffed inside the system prompt (relying directly on Pi's strict TypeBox parameter schemas).

The remaining ~8,000 lines of pure code focus on doing one thing well: mapping the Telegram group chat ecosystem into rigorous, elegant agent interactions.

  • It handles message archiving and Trigram / semantic retrieval;
  • It handles prefix-invariant batch grammar serialization;
  • It handles the small classifier model's chime-in decisions;
  • It builds the security moat around the rootless Linux container.
What We Deleted Went to Pi; What Remains Is Pure Group Chat Semantics

The four blocks of homegrown code deleted in the migration commit and the Pi 1.5 capabilities that replaced them; the remaining ~8,000 lines handle only group-chat semantics.

In software engineering, the purest joy is never typing out tens of thousands of lines of framework code—it is making the system stronger while deleting thousands of lines of bloated self-indulgence in a single stroke. That joy of "negative code" is the truest expression of minimalist aesthetics.


Two Visions of Generality: Specialized Deployment vs. General Agent

In our group, members often teasingly compare my bot with tcdw's Surowan: "If you talk about general agents all day, why does your bot single-mindedly serve only our one group?"

Let's set surface appearances aside and lay the skeletons of both systems side by side:

Dimension Pi Telegram Agent (This Project) Surowan (tuuject/surowan)
Target Audience Deeply tailored for our own trusted circle Built for any external user to self-host (BYOK)
Scope High-frequency emergence inside a single Supergroup Multi-group, multi-channel
Persona Model One deployment = one focused digital persona Single deployment switches personas and model matrices per chat
Chime-In Decision Deterministic on @mention; ambient chatter judged by a dedicated small classifier reading a slice Bucket-aggregated and judged by the primary model over full context, gated by time/probability
Forgetting Mechanism Pi's native structured compaction (128K window) Pure checkpoint sliding truncation (drop without summarizing)
Memory System Zero memory layers; relies entirely on SQLite verbatim dialogue retrieval Three-tier memory hierarchy (Memo Pad + periodic summaries + curated knowledge base)
Tool Exposure Fixed catalog declared upfront in full, riding the prompt cache Core primitives exposed; internal skills discovered dynamically via execute
Execution Power Full rootless Linux container, Shell, and JS sandbox Shell and arbitrary code execution strictly forbidden for multi-tenant safety
Codebase Size ~8,100 lines in src/; general execution delegated to Pi ~60,000 lines in src/; custom dashboard, scheduler, and multi-channel runtime

Spread this comparison table open and you see two diametrically opposed yet internally consistent design philosophies:

Surowan is a "general product with a restrained agent." Because it was designed from day one to be deployed by strangers across unpredictable public groups, it must restrain the agent's hands and feet (strictly forbidding Shell execution) to manage risk—investing massive engineering effort into outer defenses, multi-group routing, admin dashboards, and permission auditing.

We chose a "specialized deployment with a general agent." Precisely because we rejected the temptation to support hundreds of arbitrary groups and bounded our deployment to a single group ecosystem we trust, we compressed outer product complexity down to almost zero. Every bit of architectural budget and trust capital we saved on the outside was poured unreservedly into the agent's core—daring to hand it a complete Linux machine, daring to let it orchestrate Shell commands, and daring to let it write concurrent code on the fly.

Where the Complexity Lives

Neither project is simple; they just place their complexity in opposite places: Surowan puts it in outer product capabilities, while this project puts it inside the agent kernel. Drawn from the comparison table above.

On specific architectural trade-offs, we remain convinced of our choices:

  • Who decides when to speak: Slice classifier vs. full-context primary model. Even with Surowan's sophisticated gates, the final mile still wakes the primary model to scan the full context. By decoupling perception from reasoning via a tiny classifier model, our primary model's cache never flinches no matter how noisy the chat gets.
  • Tool definitions: Full upfront declaration vs. dynamic discovery. Many frameworks love tucking tools into secondary directories so the model searches before calling, hoping to save tokens. Yet our telemetry proves tool schemas occupy just 1.1% of the payload and sit inside the immutable cached prefix; forcing the model to make an extra full-context round-trip just to save a few hundred cached tokens is a textbook case of "penny-wise on the cheapest prefix, pound-foolish on the most expensive inference."
  • Memory philosophy: Zero mechanism vs. intricate curation. Surowan's three-tier memory design is an impressive piece of engineering, but frontier research and our own production scars sound the same warning bell: processed memory inherently carries a self-poisoning risk. One less layer of mechanism is one less class of self-replicating error.

Why Specialization for a Group Chat Is the True Starting Point of Generality

Someone might ask: if you welded every design decision to a single Telegram group chat, isn't that just narrow specialization?

No—the harsher the environment, the more universal the principles distilled from surviving it.

The most common tragedy in software engineering is building a so-called "general framework" in a vacuum. When you lack a concrete, unforgiving real-world scenario as your anchor, your architecture inevitably fills up with fantasies: adding another middleware layer feels cool, adding a memory-extraction pipeline feels thorough, and having the model repeat a confirmation turn after every tool call feels rigorous.

Until you throw it into a real, unforgiving Telegram group chat: Online 24/7, hundreds of people firing off jokes and tangents every second, context refreshing by the second, the vast majority of messages pure noise, input outnumbering output by 374 to 1... In an environment that brutal, the slightest bit of architectural bloat or hubris gets amplified dozens of times over by the leverage of 144,000 messages—turning into astronomical cloud bills, lag, and spam in front of your users.

A design philosophy that can survive the most hostile group chat is indestructible when transplanted into any agent system:

Four Rulers of Restraint

The four dimensions of frugality, what each one governs, and the design principles they share.

In the world of LLMs, every engineering law ultimately converges on a single aesthetic truth: Tokens are the only currency.

Saving money, saving context, and saving lines of code are not three separate virtues—they are projections of the exact same fundamental law across the physical billing ledger, runtime memory, and software architecture.

We never sacrificed user experience. On the contrary, precisely because we refused to budge an inch on unnecessary model calls and fought over every byte of prefix stability, we earned the headroom to give our bot a millisecond-responsive codemode and a full Linux workspace where it can roam freely—living in our group chat as a genuinely sharp, tactful companion.

The next time you are tempted to add a new mechanism or write a new feature, hold this ruler up and ask yourself four questions:

  1. Does this step actually require a model, or can a single line of deterministic code settle it? And if it truly needs a model, does it really need to wake the primary model with all 90,000 tokens of baggage?
  2. Will this action mutate the golden prefix? Is dynamic information staying obediently on the append-only tail where it belongs?
  3. Does this batch of data deserve to be re-read by the model on every single turn, or should it sleep in the database until someone actually asks for it?
  4. If I delete this code right now, will the system really collapse—or has the underlying platform already solved this more cleanly than I ever could?

If the answer wavers, take your hands off the keyboard.

Save a little, then save a little more. Because only where restraint reaches its limit does true freedom appear.