Search, context and cost
Finding an old chat, measuring the context window, and adding up what a session cost.
You remember asking about a train connection, but the chat title was something like “April plans.” The sidebar can find the old question by its words. Open that chat and the composer meter tells you how much room the model has now. Session stats answers a third question, how much work the chat has recorded over time.
In this chapter
- Find out which saved words the sidebar can match and why one chat appears before another.
- Read the context meter and tell when its number is estimated.
- Interpret recorded spend, specialist usage, and the estimate for cache misses.
The sidebar searches saved chat text
- Browser
- Hono app.ts
- Core index.ts
- Saved chats
- FTS5 index
Browser → Browser · Type a query
The browser waits for a pause in typing
After 180 milliseconds it can send the current query and the current sidebar view.
Browser → Hono · GET search
The host receives the query
The request carries the query and an archive filter for the current sidebar view.
Hono → Core · Search chats
Hono calls core
Core validates the query and takes a turn on its search queue.
Core → FTS5 index · Open index
The first valid search creates an empty index
SQLite FTS5 runs in memory. Later requests share that same index until the host restarts.
Core → Saved chats · Check entry IDs
Core checks which chats have new entries
It compares each chat’s latest entry ID in the selected view with the ID it last indexed.
Saved chats → Core · Read new entries
Core reads the missing entries in small pages
A chat the index has never seen needs a full pass. For an indexed chat, core picks up after the newest entry it already checked.
Core → FTS5 index · Index text
Only the selected message text enters the index
Attached text files count. Extracted PDF input stays out of the index.
Core → FTS5 index · Match prefixes
The index ranks matching messages
Each distinct query word becomes a prefix. Core keeps the best matching row per chat and places title substring matches first.
Hono → Browser · Return chats
The sidebar displays one result per chat
Hono returns the results from core. Each can include a short excerpt. The browser discards responses for superseded searches.
Browser → Browser
The browser waits for a pause in typing
After 180 milliseconds it can send the current query and the current sidebar view.
Type a few remembered words into Search chats. The browser waits for a short pause, then sends the query to GET /api/v1/conversations/search with the current view, recent or archived. Core searches the chats in that view. Title matches come first, including titles whose matching text never occurs in the conversation. App.svelte transcript-search.ts
The catalog is a full-text indexA lookup structure that lets Pipal find words in saved messages without reading every message again for each query. built with SQLite FTS5, SQLite’s text-search extension. Pipal creates it on the first search after startup and records the newest entry it has read for each chat. For each previously indexed chat, the next search only needs to fetch entries after that point. The first search can take longer on a large collection, but a message send has its own admission queue. index.ts transcript-search.ts
The index reads committed user and assistant text, along with attached text files. Tool results, summaries produced when old context is compacted, and specialist transcripts stay outside it. If a ticket number appears in a PDF’s extracted text, the number can be in the material Pipal sent to the model without appearing in search. It becomes searchable if the assistant writes it into a saved reply in that chat. transcript-search.ts index.ts
Deep diveHow core turns a query into one ranked hit per chat
Core trims the query and accepts 1 to 256 UTF-16 code units. It lowercases the whole query for a substring match on titles. For message text it extracts distinct runs of Unicode letters, numbers, and marks. A query such as “train connection?” becomes "train"* OR "connection"*. Punctuation never enters the FTS expression as syntax, and a message can match either prefix. The index uses the Porter stemmer with SQLite’s Unicode tokenizer. contracts.ts index.ts transcript-search.ts
const words = [...new Set(needle.match(/[\p{L}\p{N}\p{M}]+/gu))];if (words.length) { // … const expression = words.map(word => `"${word}"*`).join(' OR '); const winners = new Map<number, string>();The query orders matching rows by FTS5’s default relevance rank. Ties go to the higher numeric chat ID, then the higher FTS row ID. Core selects the first matching row for each chat and formats excerpts only for those winners. An excerpt is at most 240 UTF-16 code units, including ellipses. Literal title matches lead the combined list, which stops at 50 chats. transcript-search.ts
Core reads up to four entries per page because an entry can carry large attachment inputs. It writes all new entries for a chat into the in-memory index in one transaction, then advances its record of how far it read. The search chain serializes these updates and drains at shutdown. Switching sidebar views filters the search. Previously indexed rows stay in memory until the process stops. When the browser aborts a request, the host has no cancellation signal for the work already queued there. transcript-search.ts index.ts app.ts
Search reads model entries directly, with explicit exceptions for attachments, compaction, and reset. It can index the continuation prompt produced by Resume response, whose transcript label is shorter than the saved model input. transcript-search.ts index.ts view.ts
The meter measures the current context
Open the meter beside Send. A token is a unit the model uses to count pieces of its input and output. The context windowThe selected model’s capacity, measured in tokens, for the material it can work with in a request. is the selected model’s capacity in those units. The meter shows how much of the current conversation context is in use and how much room the selected model has left. If the model catalog has no positive limit, you get a token count and the window size reads Unknown. index.ts ContextUsage.svelte
Look beside the model name for reported or estimated. After a straightforward reply from the selected model, Pipal can use the token measurement from that reply. Once you send a new message, its tokens need estimating until a new applicable measurement arrives. If you change models, Pipal can also reuse a measurement from the old model while labeling the current figure estimated. context-window.ts index.ts
Pi can make room by summarizing earlier messages. The transcript tells you when a summary runs in the background and when the reply is waiting for one. If the summary fails, open the context meter and look for Last compaction failure. That entry can outlast the task, including when a background summary failed and the answer finished successfully. ContextMeter.svelte run-status.spec.ts
Deep diveWhat makes a token count reported
measureContext() walks backward over trailing user entries on the ordinary path. It estimates those messages and adds the count from the newest completed assistant response with positive measured usage and no tool calls. A response ending with stop or length qualifies. Core labels the count reported only when that response is the newest entry and its provider and model match the current selection. context-window.ts index.ts
If the backward scan encounters a head change, edits, or an entry the fast path cannot use before it finds a usable reply, core asks Pi for the active context at the newest entry. It looks for a usage measurement after the active head and estimates the messages beyond that measurement, or estimates the active messages from the beginning if it finds none. This path always returns an estimated count. Core caches the measurement by the newest immutable entry, then reads the current model’s limit separately. context-window.ts index.ts
Session stats keep the whole recorded history
{
"tokens": {
"input": 12000, "cached": 8000,
"uncached": 4000, "output": 1000,
"total": 13000 },
"cost": 0.04,
"specialists": {
"count": 1, "tokens": 2000,
"cost": 0.01 },
"cacheRebilled": {
"tokens": 2000, "misses": 1,
"cost": 0.006 }
} - This chat’s tokens
Input includes cache reads and writes. Uncached includes fresh input and cache writes.
- This chat’s cost
This is the sum of costs in the chat’s model and tool ledgers, in US dollars.
- Specialist usage
The dialog shows this usage on its own line. The combined total for this example is 15,000 tokens and $0.05.
- Estimated re-billing
This estimates the extra cost of missed cache reads. The dialog reports it under Cache activity and uses the recorded usage for the overall total.
{
,
,
,
} 1 This chat’s tokens
Input includes cache reads and writes. Uncached includes fresh input and cache writes.
From the context meter choose Session stats, or enter /session in the composer. For a saved chat the dialog fetches GET /api/v1/conversations/:id/session-info on open and offers Refresh statistics. Alongside the current context it shows cumulative tokens, recorded times for models and tools, and estimated cost at API prices. The storage section gives the conversation ID and the SQLite file that holds it. App.svelte SessionDetails.svelte
The Input row counts fresh input together with prompt-cache reads and writes. A prompt cache lets a provider reuse work it did on an earlier prompt. The Cached row shows how much input was read from that cache. Uncached includes tokens written into the cache as well as fresh input. If the chat owns specialist or development worker conversations, their combined usage has a separate row and the cost at the top includes it. session-info.ts SessionDetails.svelte
Under Cache activity, cache re-billingPipal’s estimate of how much of a prompt was paid for again, based on consecutive prompt sizes and how many tokens the provider read from its cache. estimates how much of a prompt might have been paid for again when cache reads dropped. Pipal compares the lengths of consecutive prompts and checks how many tokens the provider says it read from cache. If two successive prompts each use 8,000 tokens and only 6,000 are read from cache on the second, the estimate can count 2,000 re-billed tokens. It has token counts to work with, so equal-length prompts can look alike to this estimate even when their text has changed. cache-rebilled.ts
Deep diveHow the report keeps a cutoff and prices a cache miss
readSessionInfo() captures the latest entry ID and Pi Durable’s UsageDoc together. The same commit tallies the usage of conversations owned by the chat. That includes development worker conversations created under a task belonging to the chat. Core then reads the chat’s own immutable entries up to the captured ID, in pages of up to 16, to count activity, add durations, and estimate re-billing. Hosted searches contribute to the tool call count, as do tool-call blocks. An absent or invalid duration makes that category’s total unavailable. session-info.ts workers.ts
For each assistant usage block with a nonzero prompt size, the estimate takes the smaller of the current and previous prompt sizes, then subtracts the current cache reads. It needs reported cache reads or writes since the last compaction or reset, including the current response. It counts the entire result if it exceeds 1,024 tokens. Compaction and reset clear that comparison baseline and the cache-use flag. A model switch on its own leaves the baseline in place. Accumulated totals stay in the report. cache-rebilled.ts
The price per re-billed token is the current prompt’s average paid input rate, including cache writes, minus the cache-read rate, floored at zero. When a miss has no cache reads to price from, Pipal uses the catalog’s cache-read price for the provider and model on that response, in US dollars per million tokens. If that rate is missing, the estimated dollar amount becomes unavailable while misses and tokens still accumulate. cache-rebilled.ts index.ts
A report can tell you how many tool calls a chat used, but where did those calls read or change files? Three ways to touch a project shows how host readers and Developer’s workspace tools reach project files.
Recap
- Sidebar search finds saved text and live titles for the current sidebar view. The text index lives in memory.
- The context meter shows the current token count against the selected model’s capacity.
- Session stats report recorded usage, with a separate specialist breakdown and a cache re-billing estimate.
- You search for a number that occurs only in pages extracted from an attached PDF. What should you expect?
- A match because the model could read the number
- A match only when the meter says reported
- The PDF’s extracted input alone won’t produce a match
Answer and explanation
The PDF’s extracted input alone won’t produce a match
Search indexes selected user and assistant text and attached text files. Model-only PDF parts stay out.
- The model changes but no new reply has committed. How can the meter react?
- It can reuse the last count, apply the new limit, and label the count estimated
- It must wait for a new reply before showing anything
- It uses the new model’s exact token count immediately
Answer and explanation
It can reuse the last count, apply the new limit, and label the count estimated
Core caches the measurement for the newest entry. It reads the selected model separately for the limit and the reported label.
- Compaction happens after several cache misses. What should the re-billing estimate do?
- Clear all recorded misses from the report
- Keep the accumulated misses but start a fresh prompt baseline
- Treat the first prompt after compaction as a full miss
Answer and explanation
Keep the accumulated misses but start a fresh prompt baseline
Compaction clears the previous prompt size and the cache-use flag. The report keeps the estimated misses it already counted.
You search for a number that occurs only in pages extracted from an attached PDF. What should you expect?
The model changes but no new reply has committed. How can the meter react?
Compaction happens after several cache misses. What should the re-billing estimate do?