The conversation: a thread that answers, stops and stays in budget
How the control layer around an agent loop decides who may speak, queues messages behind a running task, stops in two layers, enforces limits per task and per day, and derives cost, status and interruptions from one append-only journal.
- Describe the control layer that sits between a chat service and an agent loop, and list the decisions it makes before any model is called.
- Explain why a stranger's message is dropped in silence, and why the check must come before everything else.
- Build a queue that lets messages wait behind a running task without delaying "stop" or any other command.
- Implement "stop" in two layers, and say what each layer protects against.
- Keep an append-only journal and derive spending, status and "what was interrupted" from it, instead of storing each separately.
- Explain why the report of what was done on the owner's accounts is written by the program and not by the model.
- Week
- 2 of 14
- Before it
- Chapter 2; Definitions 1, 3, 4, 5 and 8 and Property 3 of the model.
- Read first
- [Kreps 2013]; [Fowler 2005].
- Laboratory
- 1: the loop, the journal and a conversation that can be stopped
- Problem set
- 1
4.1The problem: a chat is not a function call
Chapter 2 showed how one request becomes a loop of model calls and tool calls that ends in a reply. That loop answers a single question well. A personal agent does not live in a single question. It lives in a chat thread that never closes, where messages arrive whenever the owner (or anyone else) sends them.
Consider one minute of an ordinary evening. The owner asks the assistant to find the last train to the coast tonight. The model starts a web search. Ten seconds later the owner adds "and the first one tomorrow". Then, having changed their mind, they type "stop". Meanwhile somebody who has found the bot's public name sends it "hello, who are you?".
The loop on its own has no answer to any of this. Should the second message start a second loop, be thrown away, or wait? Does "stop" go to the model, and what if the model is stuck in a slow call? Does the stranger get a reply, and who pays for it? Who ends a task that has spent fifty cents and is still going? Afterwards, how does the owner know what it did to their mail?
Each question is answered by ordinary code around the loop: the control layer. None of these decisions belongs to the model. The program decides who may speak, when work starts and stops, what it may cost, and what is reported.
4.2The concepts
- Control layer
- The code that receives every incoming message and decides what happens to it before, during and after any model call. Here it is
odysseus/conversation.py.
- Task
- One run of the agent loop, started by one message from the owner and ending with one reply. A task has a status when it ends: done, stopped, stuck, ended by its own budget or the day's, ended by a step limit, or failed.
- Owner check
- A comparison of the sender's identity, as the chat service reports it, against the one identity the program was configured to serve. On Telegram the identity is a numeric user ID that the service supplies and the sender cannot choose.
- Queue
- An ordered list of messages that arrived while a task was running, kept so that each can run afterwards, in order, one at a time.
- Streaming
- Receiving a model's reply in pieces as it is generated, so that a chat can show it as a growing draft.
- Interrupt and cancellation
- An interrupt asks the agent library to end the current run; the library decides how and when. A cancellation is the program ending the task itself through its own concurrency machinery (here Python's
asyncio), whether or not the library cooperates.
- Journal
- An append-only file with one line of JSON per step the program takes. Lines are added and never edited; old ones are only moved, unchanged, into an archive.
- Command
- A message that the control layer recognises by its exact text (such as
stop,/statusor/memory) and answers itself, without calling a model.
4.3The design
One entry point, checks in a fixed order
Every message from the chat service enters through one function, Conversation.handle. It runs a sequence of checks, and the order of the checks is the design. A message leaves the sequence at the first check that claims it.
/status, /memory, /new, /help) just after; all come before the busy check.Three properties follow from the order.
- The owner check is first. Nothing a stranger sends reaches any later code: not the command parser, not the file reader, not the model. Every later check can therefore assume it is talking to the owner.
- Commands and "stop" come before the busy check. A queue that could hold "stop" behind a long task would make the most important command the slowest one.
- The budget check is last, just before the model. Everything above it is answered by code, so a task refused for budget costs nothing, and a command such as
/statusworks even when the money for the day is gone. (Steps not drawn also run before the commands: a pasted sign-in address and a reading note are handled by code at once; a PDF the owner linked to is fetched when nothing is running; and a DocSend link is read in a browser, which is paid for and checks the budget itself; see Chapter 22.)
Why these choices and not the obvious ones
| Question | Obvious answer | Choice made | Why |
|---|---|---|---|
| What does a stranger get? | A polite "this bot is private" | Nothing at all | Any reply confirms the bot is alive and gives a prober something to work with. Dropping before the model means a stranger cannot spend the owner's money. |
| A message arrives during a task | Refuse it, or start a second task beside the first | Queue it, up to five, and run it afterwards | Refusing makes the owner remember to resend, sometimes after a ten or fifteen minute wait. Two tasks side by side would share one conversation and could act on the same accounts at once. |
| How is "stop" delivered? | As a message to the model | Matched by code; never shown to the model | Stopping must work when the model is behaving badly, since that is when it is needed. |
| How many layers of stop? | One: ask the library | Two: ask, then cancel after a grace period | The first layer depends on the library and the network cooperating. The second depends on nothing outside the program. |
| Where are task limits enforced? | The agent library's own step and money limits | The program's own count, during the task | The library's limits are fixed when a connection opens and count the whole connection. On a connection kept open all day they cannot mean "per task". |
| Where is spending stored? | A running total in its own file | Derived from the journal | Two records of one fact can disagree after a crash; one record cannot. |
Keeping the rules apart from the chat service
The chat service's wiring lives in another file (odysseus/telegram.py) and only carries messages. The control layer sees the chat chiefly through three methods: send, draft for a growing preview, and ask for a question with Approve and Decline buttons. Tests can therefore drive the rules with a pretend chat and no network, and a second channel needs no change to any rule (Chapter 16).
4.4The mechanism
Who may speak
The first lines of handle in odysseus/conversation.py:
# 1. Who may speak. Anyone but the owner gets no reply at all.
if user_id != self._s.owner_id:
self._journal.write("dropped", user_id=user_id)
return
The journal line means the drop is not invisible to the owner, who can find it later; the stranger learns nothing. The same check opens handle_file, handle_voice and handle_decision (the button taps), so a stranger's file is never downloaded, a stranger's recording never transcribed, and a stranger's tap on an approval button never counts (Chapter 15). The wiring adds a second restriction before the message reaches this code, in odysseus/telegram.py:
# Private chats only: a bot added to a group would otherwise hear other people.
@dp.message(F.chat.type == "private", F.text)
async def on_text(message: Message) -> None:
user_id = message.from_user.id if message.from_user else 0
async with in_turn(user_id):
if await late(message):
return
await conversation.handle(user_id, message.text or "", TelegramChat(bot, message.chat.id, ...))
Without the private-chat filter, anyone who added the bot to a group would have it read that group's messages, and the owner check would be the only thing between those messages and the model. in_turn lets one person's messages into handle one at a time, in the order they were received. The late check reports a message that was sent more than ten minutes before it arrived instead of acting on it; why that matters belongs to Chapter 7.
One task at a time, and a queue
When a message passes the command checks and a task is already running, this is what happens (odysseus/conversation.py):
if self.busy:
if self._stopping:
# Between "stop" and the task really ending, nothing is queued: it would be left behind and run out of turn.
await chat.send("I'm still stopping the last task. Send that again in a moment.")
return
if self._gate is not None and self._gate.pending():
# Typing is not an answer to an approval question, and must not turn into a new task called "yes".
await chat.send("I'm waiting for you to tap Approve or Decline on the question above. Typing does not answer it. "
"Send stop to end the task.")
return
if len(self._waiting) >= MAX_WAITING:
await chat.send(f"I already have {MAX_WAITING} messages waiting behind the current task. Send stop to drop them all.")
return
self._queue_seq += 1
first = not self._waiting
self._waiting.append((text, chat, images, material, self._queue_seq))
# Written down, so that after a restart the owner can be told which messages were lost while waiting.
self._journal.write("queued", waiting=len(self._waiting), q=self._queue_seq, preview=" ".join(text.split())[:80])
# Said once for a run of waiting messages, not after each: five identical lines told the owner nothing more.
if first:
await chat.send("Noted. I'll do this, and anything else you send meanwhile, in order, as soon as the current task is finished. "
"Send stop to end everything.")
... # (lines omitted here: its answer will be sent as a reply to this message)
return
The first branch closes the few seconds between "stop" and the task really ending, when a queued message would run later, out of turn. The second stops a typed "yes" during an approval question from becoming a task; only the button approves (Chapter 8). The third bounds the queue at MAX_WAITING = 5. The journal line, with a sequence number, lets a restarted program tell the owner which waiting messages were lost.
The task itself runs the queue when it finishes:
async def _work(self, text: str, chat: Chat, images: list[tuple[str, bytes]] | None = None, material: str | None = None) -> None:
"""Run a task, then whatever arrived while it was running, one at a time, in the order it arrived."""
await self._safely(text, chat, images, material)
while self._waiting:
text, chat, images, material, q = self._waiting.popleft()
self._journal.write("dequeued", q=q)
if self._ledger.spent_today() >= self._s.daily_usd:
self._journal.write("refused", reason="daily_budget")
await chat.send(f"Today's budget of ${self._s.daily_usd:.2f} is used up, so I have not started a message that was waiting.")
continue
await self._safely(text, chat, images, material)
Two details matter. The budget is checked again for each waiting message, because the task in front may have spent the rest of the day's allowance. And each task runs inside _safely, which catches any exception, records it, tells the owner "Something went wrong and I could not finish", and lets the queue carry on. Without that, one crash would silently strand everything behind it.
Streaming the reply
A reply that takes thirty seconds to appear looks the same as a program that has died. The agent library delivers text in pieces, and the control layer shows them as a draft that grows. Telegram asks for about one message a second per chat, so the drafts are throttled:
async def on_text(text_so_far: str) -> None:
nonlocal last_draft
now = time.monotonic()
if now - last_draft < DRAFT_INTERVAL_S:
return
last_draft = now
try:
await chat.draft(draft_id, text_so_far[:TELEGRAM_LIMIT])
except Exception:
pass # a failed preview must never end the task
DRAFT_INTERVAL_S is 0.8 seconds. The try is there because a preview is a courtesy: if the chat service rejects one, the task must continue. The final reply is sent separately, split into parts of at most 4,096 characters by split_message, which prefers to cut at a line break.
Stop, in two layers
The word is matched against a fixed set, STOP_WORDS = {"stop", "/stop", "cancel", "/cancel"}, before the busy check. The first layer is in odysseus/agent.py:
async def stop(self) -> bool:
"""Ask the running task to end. Returns False when nothing is running."""
if not self._running or self._client is None:
return False
self._stopped = True
await self._client.interrupt()
return True
In the ordinary case the library ends the run at once and the task finishes through its normal path with the status "stopped". But an interrupt is a request. A fault in the library, a network call that never returns, or anything else that stalls the run would leave the owner typing "stop" into a program that does not stop. So the control layer adds the second layer (odysseus/conversation.py, inside _stop):
try:
await self._runner.stop()
except Exception as e: # the stop must not depend on the SDK cooperating
self._journal.write("error", where="stop", error=type(e).__name__)
# Give the run a moment to end by itself, then end it regardless.
done, _ = await asyncio.wait({task}, timeout=self._s.stop_grace_s)
if not done:
spent = self._runner.estimate # what the model calls made so far are estimated to have cost
task.cancel()
await asyncio.gather(task, return_exceptions=True)
await self._runner.reset() # the client is in an unknown state; start a clean one next time
self._journal.write("task_end", status="stopped", forced=True, cost_usd=round(spent, 4), estimated=True)
await chat.send("Stopped.")
Even the first layer is wrapped, so an exception from the library cannot prevent the second. After the grace period (stop_grace_s, five seconds by default) the task is cancelled and the connection thrown away, because its state is now unknown; the next message opens a new one that resumes the same conversation. The journal line is marked forced, and its cost estimated from token counts, because the library never reported a figure (Chapter 20).
Before either layer, _stop stops any jobs in the background the same way, giving them the same grace period; then it empties the queue and says how many messages were dropped, cancels any open approval question (which counts as a decline), ends any approval widened to a thread, and cancels any browser run at the vendor. An owner who types "stop" wants everything to stop, not the next task to begin.
Limits per task and per day
| Limit | Default | Checked | What the owner is told |
|---|---|---|---|
| Steps in one task | A mark of 25 model calls; a ceiling of 100 | As each model call arrives | "I ended this task after 100 steps, the most one task may take." |
| Money in one task | A mark of $0.50; a ceiling of $2.00 | As each model call arrives, from an estimate | "I ended this task because it reached $2.00, the most one task may cost." |
| Money in one day | $3.00 | Before a task starts, before each queued message, and as each model call arrives | "Today's budget of $3.00 is used up, so I have not started this." Or, during a task: "I ended this task because today's budget of $3.00 is used up." |
The per-task count lives inside the loop in odysseus/agent.py:
# One model call can arrive as several messages sharing an id; count it once.
key = msg.message_id or f"n{len(calls)}"
calls[key] = estimate_usd(self._model, msg.usage or {})
... # (lines omitted here: the size of what the model was sent is recorded)
if self._limit is None and not self._stopped:
... # (a comment omitted here)
stretch = max(1.0, float(getattr(self._s, "task_stretch", 1.0) or 1.0))
spent = sum(calls.values())
self.stuck_why = progress.stuck()
if self.stuck_why:
self._limit = "stuck"
elif len(calls) > self._s.max_turns * stretch:
self._limit = "turn_limit"
elif spent >= self._s.task_usd * stretch:
self._limit = "budget"
elif self.day_room is not None and spent >= self.day_room():
self._limit = "day_budget"
elif not passed and (spent >= self._s.task_usd or len(calls) > self._s.max_turns):
passed = True
self._journal.write("limit", which="passed", steps=len(calls), estimated_usd=round(spent, 4))
if self._limit:
self._journal.write("limit", which=self._limit, steps=len(calls), estimated_usd=round(spent, 4),
**({"why": self.stuck_why} if self.stuck_why else {}))
await client.interrupt()
Keying by message id counts a model call once even when it arrives in pieces. A limit uses the same interrupt as layer one of stop, and whatever the model had written is delivered with the explanation appended. The owner is always told why a task ended early: a task that ends silently looks like one still running. How the estimate works is the subject of Chapter 20.
The journal, and what is derived from it
The journal's writing function is short (odysseus/journal.py):
def write(self, kind: str, **fields: Any) -> None:
record = {"ts": round(self._clock(), 3), "kind": kind, **fields}
with self.path.open("a", encoding="utf-8") as f:
f.write(json.dumps(record, ensure_ascii=False, default=str) + "\n")
for listener in self.listeners:
listener(record)
if self._echo:
shown = " ".join(f"{k}={fields[k]}" for k in self.ECHO_FIELDS if k in fields)
print(f"odysseus {kind} {shown}".rstrip(), flush=True)
Three decisions sit in these lines. The file is opened in append mode, so nothing written is changed later; it is closed after each line but not forced to the disk, so a line survives a crash of the program and not necessarily a loss of power. Listeners hear of each record as it is written; the spending ledger is one, which is how spending stays current without a second file. And on a hosting service whose log shows in a dashboard, only ECHO_FIELDS (statuses and numbers) are copied there, never queries or message contents. Journal.read skips a line that does not parse, which is what a crash in the middle of a write leaves.
From this one file the program derives several things it would otherwise have to store separately:
- Spending. The
Ledgersums a cost per day from every line, and/statusanswers from it:"Idle. Spent today: $0.42 of $3.00." - What was interrupted. At start-up,
unfinishedinodysseus/__main__.pylooks for atask_startwith notask_endandqueuedlines with nodequeued, so the owner can be told what was cut off and lost (Chapter 7). The 80-characterpreviewintask_startis what makes the notice readable. - Whether a reply left. A
replyline, or anerrorline saying how many parts went first.
Commands with no model
Some things the owner asks have exact answers that the program already holds. Asking a model would add cost, delay and a chance of being wrong. These are commands, handled in handle before any task starts:
if command == "/status":
state = "working on a task" if self.busy else "idle"
... # (lines omitted here: any jobs in the background, and how many wait behind them, are added to the state)
await chat.send(f"{state.capitalize()}. Spent today: ${self._ledger.spent_today():.2f} of ${self._s.daily_usd:.2f}.")
return
The same pattern serves /memory and /forget, /schedule and /cancel with an id, /watches and /unwatch, /apps, /browser, /new (a fresh conversation, refused while a task runs) and /help. Matched before the busy check, they are answered at once even during a long task. They also let the owner inspect and correct the assistant's state without its cooperation: /memory shows the stored entries, not the model's account of them.
The same things, asked for in words
A command typed by the owner has one property nothing else has: no text the model has read can set it off. That is why inviting a person, listing who is here and starting a sign-in were commands. The price was a list of commands to learn, and for a while the model, asked for an invitation in ordinary words, could only name the command to type. The owner's verdict was short: no commands, these have to be natural language.
The design keeps the property and drops the list. The model is given one tool with a fixed menu of the things the program does itself. Calling it runs the very code the command ran, and three things are held by code:
- The result goes round the model. What the code produces (an invitation link, the list of people, a sign-in address) is sent to the owner by code. The model is told only that it was done. An invitation's code is a credential, and a model that never sees it cannot repeat it, alter it or put it in a search.
- The gate decides, by kind. Showing the owner something of their own runs unasked. Changing something runs unasked only while the task has read nothing but the owner's own words; once it has read what other people wrote, the request may be theirs, and the owner is asked. Stopping a person's assistant and removing a connection are always asked about.
- Who may. What only the person running the program may do is not on anyone else's menu, and the code behind it checks again.
odysseus/said.py
What is given up is stated plainly. With a typed command, a planted instruction could not reach these things at all. Now it can reach the door, and the gate is what stops it: after any outside reading, a change is a question to the owner. That is the same protection every other tool has, and no longer a stronger one. Two things stay words the owner says themselves and code reads, because a model must not be what decides them: "stop", and "new conversation". The typed commands still work; nothing the program says mentions them. Not tested with the real model: whether it reaches for the tool reliably when asked in ordinary words has been checked only by the tool's own tests.
Reporting what was done, in the program's words
When a task ends, the control layer builds the reply from the model's text and then appends lines of its own (odysseus/conversation.py):
# Every change the model made to memory during this task is reported by code, not by the model.
changes = self._memory.pop_changes() if self._memory is not None else []
if changes:
body += "\n\nMemory: " + "; ".join(changes) + "."
... # (lines omitted here: skills saved and figures recorded are listed the same way)
acted = (self._apps.pop_changes() if self._apps is not None else []) + (self._anyapp.pop_changes() if self._anyapp is not None else []) \
+ (self._attio.pop_changes() if self._attio is not None else []) + [c for s in self._services for c in s.pop_changes()] \
+ (self._inbox.pop_changes() if self._inbox is not None and hasattr(self._inbox, "pop_changes") else [])
# A connection link is added by code, exactly as the connector gave it. The model never handles it.
for app_name, link in (self._anyapp.pop_links() if self._anyapp is not None else []):
body += f"\n\nTo connect {app_name}, open this link and approve, then tell me it's done:\n{shortlink.LINKS.wrap(link)}"
if acted:
body += "\n\nDone on your accounts: " + "; ".join(acted) + "."
Each tool that changes something records a line as it makes the change. Every such list is emptied at the start of a task when no other task is running, so only this task's changes are reported, and at the end they are appended under fixed headings: "Memory:", "Done on your accounts:", "Browser:", "Schedule:", "Watching:", "Keeping in touch:", and a line for replies sent without being shown first under an approval the owner widened to a thread.
The model's summary of what it did is a claim, and can be wrong: "I've sent it" after a declined send, or silence about a change that happened. A model misled by a planted instruction might be steered to hide what it did. The program's lines come from the tools themselves, and where they disagree with the model's words, they are the ones to believe. The connection link is handled the same way for a related reason: opening it grants access to one of the owner's accounts, so it is added by code, as the connector produced it or under a short address of the program's own that leads to it, and the model never holds a copy it could alter (Chapter 10).
Beginning again after a pause
One conversation kept for ever is the simplest design and the dearest. Every message is charged for everything said before it, and the cache that makes that tolerable lapses after a few idle minutes (Chapter 20). So before a task runs, code asks whether to carry on or begin again:
if self._last_end is None or self._runner.session_id is None or self._s.fresh_after_min <= 0:
return ""
idle_s = (self._now() - self._last_end).total_seconds()
if idle_s >= self._s.fresh_after_min * 60:
return "pause"
if idle_s >= self._cold_s and self._runner.context_tokens > self._s.fresh_above_tokens:
return "size"
return ""
odysseus/conversation.py, _fresh_reason
There are two rules, both arithmetic. After a long pause (two hours by default) the thread has usually moved on. Once the conversation is large (the last call sent the model more than 40,000 tokens), any pause long enough for the cache to have lapsed is reason enough, because the next message would pay for all of it either way. When either holds, the program writes a fresh line to the journal, forgets the saved conversation, and puts two things ahead of the owner's message: the last three exchanges, written out by code and cut where long, under a heading that tells the model older things are gone unless saved; and the memory block, as at any start. The model is told to say so and ask if the owner refers to something it cannot see.
What this gives up is real, and was larger at first: anything older than three exchanges that had not been saved was simply gone. The old conversation is now closed before it is left: a small model writes a one-paragraph summary that heads the new conversation, and proposes facts worth saving, which the owner saves or not with one tap; and every exchange is kept on disk where the model's search tool can find it (Chapter 5). What is still given up is detail. The summary is a paragraph, the text of a file sent earlier is replaced by its name, and the owner is not told that a new conversation began. The rule has fired once in real use, on the first message after a restart and a pause of three hours, and that message cost nine cents. What the same message would have cost in the old conversation was not measured, so the saving is still an argument and not a figure. The first version would not have fired at all there: it kept the time of the last message in memory only, and a restart forgot it. The pause is now measured from the last task in the journal.
4.5Worked example: one busy minute
Take the scenario from the opening, with the stranger included. The journal lines below are illustrative (the times and numbers are invented), but every kind and field name is the one the code writes.
- The owner sends "What is the last train to the coast tonight?". Owner check passes; it is not a command; nothing is running; the day's ledger stands at $0.21 of $3.00. A task starts.
{"ts": 1795000000.0, "kind": "task_start", "chars": 44, "preview": "What is the last train to the coast tonight?"} - The model asks for a search. The loop records the request, and the search tool records its result and the price the search service reported.
The owner's phone shows a draft that grows every 0.8 seconds or so.{"ts": 1795000002.1, "kind": "tool_request", "name": "mcp__odysseus__web_search", "input": {"query": "...", "objective": "..."}} {"ts": 1795000004.0, "kind": "tool", "name": "web_search", "query": "...", "objective": "...", "ok": true, "results": 6, "cost_usd": 0.007} - A stranger sends "hello, who are you?". The owner check fails at the first line of
handle. Nothing is sent; no model is called.{"ts": 1795000004.5, "kind": "dropped", "user_id": 555000111} - The owner adds "and the first one tomorrow". A task is running, nothing is being stopped, no approval is pending, and the queue is empty, so the message is queued and the owner gets "Noted. I'll do this, and anything else you send meanwhile, in order, as soon as the current task is finished. Send stop to end everything."
{"ts": 1795000006.0, "kind": "queued", "waiting": 1, "q": 1, "preview": "and the first one tomorrow"} - The owner sends
/status. It is a command, matched before the busy check, and answered at once from the ledger: "Working on a task. Spent today: $0.22 of $3.00." The ledger already includes the search's 0.7 cents, because the ledger listened to thetoolline as it was written. - The task ends. The reply is sent, and the queued message runs next.
{"ts": 1795000011.2, "kind": "task_end", "status": "done", "cost_usd": 0.012, "browser_usd": 0.0, "turns": 2, "detail": "success", "seconds": 11.2} {"ts": 1795000011.4, "kind": "reply", "parts": 1, "chars": 212} {"ts": 1795000011.4, "kind": "dequeued", "q": 1} {"ts": 1795000011.4, "kind": "task_start", "chars": 26, "preview": "and the first one tomorrow"}
Had the owner sent "stop" at step 4, the queued message would have been dropped with "Also dropped: 1 message that was waiting." Had the program crashed between steps 4 and 6, the journal would hold a task_start with no task_end and a queued with no dequeued, and on restart the owner would be told both what was interrupted and what was lost, from the journal alone.
4.6A budget that is a mark, and being stuck, which is a wall
For a long time a task ended the moment its estimated cost reached a fixed sum. That rule answers the wrong question. It ended a long piece of work that was nearly done, leaving the owner with half of it and a line about fifty cents. And it did nothing about a task going nowhere cheaply: the same lookup made again and again, or one failing call after another, ran on until the same sum was reached. How much a task has cost says little about whether it should continue. Whether it is getting anywhere says most of it.
So the two are now separate, and both are decided by code from what the task does, never from what the model says about how it is going (progress.py).
- The task's budget and its number of steps are marks. A task that passes one carries on, and the passing is written to the journal once. A ceiling several times higher (four, by default) still ends it, and the day's budget is still a wall, because those protect the owner's money and not the task.
- Being stuck ends a task at once, whatever it has cost. Two signs are read. The same tool asked for with the same inputs a third time: nothing the task did has changed between the calls, so a fourth will not differ. And four tool calls in a row that came back as errors: something the task depends on is not there.
A task ended either way gives what it has and says what would let it go on: "tell me what to do differently" when stuck, "say carry on" at the ceiling. The second matters as much as the first. An assistant that stops with no way forward has used the owner's time twice.
What the two signs cannot see is a task that makes a different call each time and still goes in circles. The ceiling is what ends that, later and at more cost than one would like. Not measured: how often real tasks pass the mark, and how many of those then finish. The journal now records both, so the figure will exist.
4.7A reply that says something was done
The lines under a reply that list what was done on the owner's accounts are written by code from what the tools did, so they can hardly be wrong. The reply above them is the model's own, and a model can write "I've sent it" when nothing was sent: the owner declined, a tool failed, or it lost track over a long task. Of everything an assistant gets wrong this is among the least forgiven and the hardest to see, because the sentence reads exactly like a true one.
So after every task the model's own words are read by code (claims.py) for a first-person claim of one of four kinds of act: mail sent, a calendar event made or changed, an event deleted, something filed in the firm's database. Each claim is looked for in the log: a successful call of a tool that does that kind of act, in this task or earlier the same day, since "did you send it?" may be about something that did go. A claim with nothing behind it is not removed or rewritten. Code adds a line under the reply saying what was claimed and that the log shows no such act, and writes the mismatch to the log, where it is counted as a fault of its own in the usage figures.
The reading is deliberately narrow. Quoted text, a draft shown for approval, a blank in square brackets, and anything negated, offered or conditional ("shall I send it", "once it is sent") are not claims. Nor is "I've sent you a link", which is the chat itself and not an act on an account; that case was found by an existing test failing, not by thought. The check knows a short list of English phrasings and four kinds of act, so a claim worded another way passes unread. It is a net with wide holes under the commonest way of falling, and it costs no model call.
4.8Something on the screen before the first word
When a task begins with a tool call, the first word of the reply cannot arrive until the tool has returned and the model has been called again. Measured on such tasks, most of the wait before the first word is that first step, and nothing the model does later can shorten it. The cheap remedy is not a faster model. When the first tool call is seen, code writes a short status line from a fixed table keyed on the tool's name ("Looking in the database...", "Reading your mail..."), and the chat's own "typing" signal is sent when the task starts. The line is replaced by the reply when the reply begins. The owner waits exactly as long and knows what for. No model writes the line, so it cannot say anything the task is not doing. A table can still be wrong, though: the first one matched every mail tool on its prefix, and the owner asking for an email to be sent was told "Reading your mail..." while the email was being written. No test had looked, since each test checked a line for a tool it had thought of. The fault was seen in the first real chat after the line shipped. The table now has a row for each mail tool that writes.
4.9How a reply looks
A reply is read on a phone, a few lines at a time, by someone looking for one thing in it: the figure, the name, the decision. Two things go wrong. Marks the chat does not understand are shown as typed, so a reply written as for a document arrives full of asterisks and hashes. And each chat has marks of its own: bold is two asterisks in one convention, one asterisk on WhatsApp and a tag on Telegram, so a reply written for one chat is wrong in the next. The first answer here was no marks at all, enforced by instruction. It never breaks, and it reads flat: the figure the owner wants sits in the middle of a sentence like every other word.
The second answer keeps the safety and gives up the flatness. The model writes in one small set of marks whatever chat the reply is going to, and one module is the only place that knows what a chat can show.
| The model writes | Telegram is sent | WhatsApp is sent | A chat with no marks |
|---|---|---|---|
**bold** | <b>bold</b> | *bold* | bold |
_italic_ | <i>italic</i> | _italic_ | italic |
`copy this` | <code>, copied by a tap | `copy this` | copy this |
- item | a line beginning with a dot | - item | - item |
> their words | <blockquote>, folded when long | > their words | > their words |
[name](address) | a link by name | name (address) | name (address) |
| a heading, a table | a bold line; one line a row | the same | the same |
odysseus/fmt.py
The design question is where the knowledge of a chat lives. If the model is told which chat it is writing for, every prompt carries every chat's rules, the model gets them wrong some of the time, and a reminder written at night for one channel is wrong when it is delivered on another. If code translates, the model learns one small language, and a new channel is one more column in the table.
What code holds, and an instruction could not:
- No broken message. The marks are read into pieces and each chat's form is written out from the pieces, so every tag opened is closed and all other text is escaped. A mark left open, as in a reply still arriving, is shown as typed. Three thousand replies assembled at random from marks, angle brackets and addresses all come out well formed (
tests/test_fmt.py). If the chat still refuses the result, the same words go out with no marks. - No hidden address. A link shown by name hides where it goes, and a reply is written by a model that has read other people's text. A name that itself looks like an address, and is not the address it leads to, is written out in full: name, then address. Only web addresses become links. In a question put to the owner for approval, nothing is restyled at all: the question shows exactly what will be done, character for character.
- An address is never styled. A web address written bare is left exactly as it is, whatever underscores and asterisks it contains. A sign-in link with one character changed is a broken link.
- Cutting. A long reply is cut between paragraphs before it is translated, never inside a mark or a block of kept text.
- The spoken reply and every check that reads what was said get the words with no marks.
Verified on the suite of hard errands, three runs a case: 96.1% before the marks and 96.1% after (89.1 to 100), the same 5.2 calls to the model a run and the same cost. One thing did get worse and was found by a case with a word limit: with lists and labels to spend words on, replies under a limit of 150 words ran to 152 and 157, where plain replies had stayed under 140. A label is a word. The note code adds when the owner sets a length now says so and gives a lower target, and six further runs came in between 105 and 120 words; one of the six left out a fact it should have kept. A tighter target buys the limit at some cost in content, and the limit is what the owner asked for.
The instruction that remains is about taste, which code cannot hold: most short replies need no marks; bold is for the few words the eye should find first and never a whole sentence; a list is for three or more things of the same kind; text to be copied goes between the copying marks; a cited page is a link by name.
The platforms differ in what they document. Telegram states its tags and its nesting rules, and that a draft takes the same form as a message. WhatsApp documents its marks for people typing, and its interface for programs says only that the body is text; that the marks apply to a body sent by a program is Secondary, from the reference's note that a message body supports them, and Not tested here on a real phone. On an older WhatsApp a list's marks are shown as typed, which still reads as a list. That is the property to want from any mark: when it is not understood, it should still read.
4.10Messages that never reach the model: reading notes
Some messages have a grammar small enough that a parser reads them better than a model does: faster, at no cost, and the same way every time. The first such feature in this system files the owner's notes on what they are reading into their own website. The site keeps one YAML file per book in its repository, and each note carries the time it was written, so a visitor sees what the owner thought at each point in the book rather than only at the end. The owner writes from wherever they are reading:
reading Poor Charlie's Almanack p.120: incentives explain more than intelligence does
keep that private
why Poor Charlie: a friend's recommendation
finished Poor Charlie: invert, always invert
publish Poor Charlie
The control layer looks at these before the model does (booknotes.py, called from Conversation.handle). A parser splits the first line into book, place and text. The kind of note is read from the words: quotation marks make a quote, a final question mark a question, "I don't buy" a disagreement, "reminds me of" a connection, and anything else a thought; or the owner names the kind outright ("quote:", "question:"). The note's time is the time Telegram says the message was sent, written with the owner's own time-zone offset, because the site's contract says so. A message that only looks like one of these, such as "finished the deck: sent it" when no book by that name exists, comes back unclaimed and goes to the model as usual.
A write contract is the written agreement between a program and a store it writes into that it does not own: the file layout, which fields it may change, which it must never change, and what must be true before it commits. Here the contract is a section of the site's own README, and the schema is the site's own.
Three rules of the contract shape the code. Notes are only ever appended: the new note is inserted as text at the end of the notes list, and before each commit code checks that every earlier note is byte for byte what it was and parses to the same values. The whole file must parse and match the site's schema, checked in Python against a copy of the site's rules, because a push that fails the site's build would break the site for everyone. And a book starts private: a new book is written with public: false, and only "publish" changes that.
The rules for asking follow from what can go wrong (Chapter 8). A note is the owner's own words going into the owner's own store, and it stays private, so it is filed without a question and reported in one line. Publishing changes what anyone can read, so it goes through the gate: code builds the question from the file itself (every note that will appear, how many private notes stay off the site, and the address the book will have), the owner taps Approve, and the commit happens only if the file is still the one the owner was shown. If a note arrived in between, the owner is told and asked to send "publish" again.
Writing goes through GitHub's contents API with a token that can change files in that one repository and nothing else. Each change is one commit named reading: <title>, and the site rebuilds on every push. Two writers can race (the owner editing a file on a laptop while a note comes in from the phone); the API refuses a write made against an old version, and the code reads the file again and retries.
A queue, a shelf and a list of open problems
The same grammar grew in a second step, when the site grew three things: a To read list, a Must read shelf with a line on why everyone should read each book, and a list of open problems, each with dated ideas, questions, progress and resources under it. Each is a message:
save https://example.com/essays/why-cities-grow
must read Poor Charlie: the clearest book on thinking I know
problem Cheaper glucose monitors: half the patients cannot afford one
problem Cheaper glucose monitors idea: pool orders across clinics
"Save" with a link fetches the page and uses the title the page gives itself; that title was written by someone else, so it is used only as a title and is checked like any other field. The new book starts as queued, private, with the date it was added, and the first note filed against it moves it to reading and sets the day it was started. An open problem is a file of the same shape in a second folder, with its own schema check, and "keep that private" means the last entry filed, whichever folder it went into.
"Must read" is the instructive case for the gate. It changes three fields of a file that already exists, and it makes a private book public. So the question shows each field as it is and as it will be (Must read: no → yes, Public: no → yes, the pitch before and after) and, when the book is still private, every note that going public will show. The rule is the one publishing follows, applied to a different change: anything that alters what other people can read, or overwrites what the owner wrote earlier, is shown before it happens.
A second writer arrived at the same time: the site now has an editor of its own in the browser, and it writes the same files. Two writers make the race described above common rather than rare. Each write states the version it was made against, GitHub refuses a write against a version that has moved on, and the change is then read again from the new version and remade, up to three times, before the owner is told the file kept changing.
Notes that come back: a daily review
Filing a note is half of the use of it. Rereading highlights does little for memory; meeting one's own thought again, some days later, does more. So the same files are read the other way once a day: each morning (08:00 India time by default, a setting, or off) the program reads every note in both folders, picks three in the owner's own words, and sends them with up to three questions still open. No model is involved, and nothing is written. Private notes are included, because the message goes only to the owner.
Which three is fixed by the date, not drawn at random, for two reasons. The same morning must give the same three if the program restarts and looks again. And the site's editor has a desk of its own that shows three notes a day, and the two should agree. So both seed one small generator with the day's date written as YYYY-MM-DD: a 32-bit FNV-1a hash of the string, then a mixing step, giving a number between 0 and 1 each time it is called. The editor is written in TypeScript and this program in Python; the two generators were run side by side on four seeds, one with characters outside the basic plane, and gave the same numbers to twelve places. The pool is every note with text of its own (a bare quote is someone else's words), older than seven days, or all of them when fewer than three are that old, in file order. It is then shuffled with Fisher-Yates and the first three taken.
One detail is worth knowing for anyone copying the idea. A common shortcut shuffles by sorting with a comparison that returns a random sign. Its result depends on which sorting algorithm the language runtime happens to use and in what order it compares, so two programs with the same generator and the same seed still disagree. Fisher-Yates calls the generator a known number of times in a known order, so the result is fixed by the seed alone.
The message uses Telegram's HTML for the quote in italics and a link from each note to its book or problem in the editor. Everything taken from the notes is escaped first, so a note containing < or & is shown as written and cannot become markup. The day is recorded before the message is sent, so a crash cannot send it twice. A failed send removes the record again so that the next look, five minutes later, tries again. A repository that cannot be reached records nothing, for the same reason. A day with nothing to send sends nothing.
Tested with a stand-in repository (tests/test_booknotes.py and tests/test_reading_queue.py, 87 tests). The queue, the shelf and the problems: saving a title or a link, a second save making no second file, the first note starting a queued book, a file from the site's editor with no notes yet, "must read" shown field by field and held until the tap, problem entries appended byte for byte, the 600-character limit on quotes, and a file moved twice by another writer before the note still going in. The first step's tests: parsing of each kind, place and command; appending nine awkward notes in a row without changing a byte of the earlier ones; "keep that private" touching only the note just filed, and refusing when a newer note has arrived; finished and why; the schema check refusing what the site would refuse; publishing held until the tap, left private on Decline, and refused when the book changed after the question; and that anything else still reaches the model. Run once live, from the deployed assistant: two notes and "keep that private" sent from Telegram created a new private book in the site's repository in three commits, each answered within a few seconds; the file read back from GitHub matched the contract field for field, the second note marked private and the first unchanged; and the site's own build of the last of those commits passed. The test book was then deleted. Not yet run live: publishing, finished and why, a published book on the site, and token expiry. The second step was also run once live, the same day: a saved title and a saved link (the page's own title was used, and the link was filed as an article), a first note moving the queued book to Reading, "must read" asked field by field and declined with nothing changed, and a new problem with one resource entry marked private. All read back matching the site's schema, the site's build of the last commit passed, and the test files were deleted. A must-read approved for real has not been run, so as not to put a test book on the live shelf. The run showed one thing to change: a field added to an existing file went in just before notes, where the site's own editor puts it after added; new fields now follow the editor's order. The daily review is tested in tests/test_resurface.py (17 tests): the generator against the editor's numbers, the pool and its fallback, the same three all day and different ones across days, open questions newest first, escaping, India time, once a day, nothing sent when there is nothing, and a failed send or an unreachable repository tried again. It was run once against the real repository without sending: the files were read and, since none of them held a note yet, the message was empty, as it should be. Not yet seen: a review arriving in Telegram, and how it looks there.
4.11The theory
This section states the chapter's claims in the terms of the model, and sorts them into what the program guarantees and what was only observed.
The control layer is a function, and the model is not in it. Write an incoming message as m = (u, w): the sender's identity as the chat service reports it, and the text. Write the layer's state as q: whether a task runs, whether one is being stopped, whether an approval question is open, the queue W, and the day's spending. Then handle computes
D(m, q) ∈ {drop, answer, stop, wait, refuse, start}
by tests in a fixed order; the first test that claims the message decides. Three properties follow from the order alone. If u ≠ O then D = drop and nothing reaches a model, because the same test opens every handler. A command or a stop word never enters W, because its test precedes the busy test. A refusal for budget calls no model. The owner check is also what gives a message provenance O (Definition 5): the path admits only an identity the service supplies and the sender cannot choose. The queue is first in, first out, holds at most five and is emptied by stop, so waiting messages run in arrival order or not at all.
Let g be the grace period (five seconds by default). Suppose the running task's code does not swallow a cancellation and does not run for long without yielding to the event loop. Then from the moment a stop word is matched, the task ends within g plus the time it takes to unwind once cancelled, or within 2g plus the time to unwind when jobs in the background are being stopped too, whatever the agent library or the network does, and the owner is sent "Stopped.".
Argument. The stop word is tested before the busy test, so it is handled while the task runs. Any jobs in the background are stopped first, with a wait of at most g for them. Layer one is wrapped, so an exception from the library falls through. The wait returns after at most g. If the task has not ended it is cancelled: in Python's asyncio the cancellation is raised inside the task at its next point of waiting, and the program waits for it to unwind, records a forced end and replaces the connection. The hypothesis is the weak point. Cancellation in asyncio is cooperative: code that catches it and carries on holds the stop open, and code that never yields holds the whole program, so the stop word itself is not read.
The journal and Property 3. Spending, what was interrupted, which waiting messages were lost and whether a reply left are derived state (Definition 8): each is a fold over the journal's lines, and the ledger is defined by one function that prices a single line. So Property 3 applies: /status and the budget check read the same total, a restart recomputes it from the file, and a forced stop's cost is appended marked as an estimate, so a later function can treat it differently. The hypothesis holds less widely than the summary suggests. The figure the budget checks read also adds running estimates of tasks still in progress, which live in the process and not in J. Memory, the schedule and the conversation are kept in other stores, so "one source" is true of these figures and not of the program. And a line survives a restart only if it reached the disk: lines are appended and the file closed, not forced to the disk, and a half-written line is skipped when read.
Several tasks. The rule that shared gate state is merged "in the stricter direction" has a short proof. If every rule is monotone in what has been read, so that reading more can turn allow into ask or refuse and never the reverse, and the merged record T contains each task's own record Ti, then A(T) ⊆ A(Ti) for every i: nothing runs unasked with several tasks that would not have run unasked with one. Monotonicity is a property of each rule, and has to be checked rule by rule.
What was measured. Layer one ended a real task in 1.1 seconds with a new connection per message and in 0.13 seconds with one kept open; layer two has never been needed live. These are observations of one library, and can change with it.
| Claim in this chapter | Kind | How it is known |
|---|---|---|
| A stranger's message reaches no model and gets no reply | Property | Argued from the order of tests; unit tests |
| "Stop" ends a task within the grace period (twice it with jobs in the background) even when the library ignores it | Property, under the hypothesis on cancellation | Argued; tested against a stand-in that ignores interrupts |
| Spending, what was interrupted and what was lost are derived from the journal | Property 3, with the exceptions above | Argued from the code; unit tests |
| Layer one stops a real task in about a second or less | Measurement | Two live runs, 1.1 s and 0.13 s |
| The writing rules reduced replies that show the machinery | Measurement | One run of 19 and one of 38; a count of patterns, not a judgement of tone |
4.12What goes wrong
A cost that was a running total
The agent library reports a cost at the end of each run. The first version of the code took that figure as the cost of the task and added it to the day. In the first live run, three trivial questions in one continued conversation reported $0.0013, $0.0026 and $0.0029. The figure was a running total for the conversation; adding the three gave $0.0068 for work that cost $0.0029. The same misreading had broken the per-task limit, which had been handed to the library and compared with the running total, so after fifty cents of conversation every new task would have ended at once. Every test had passed, because the stand-in for the library had been written to report costs the way the authors wrongly believed it did. The code now keeps the last total and records the difference, and the per-task limit is the program's own count.
A stand-in encodes a belief about the real component. When the belief is wrong, stand-in and code agree and the tests pass, and only a run against the real component catches it (Chapter 20 returns to this case).
Windows between two states
The "still stopping" and "typing does not answer it" branches of the queue both repair faults found by reading the code (Chapter 19): a message queued behind a task being cancelled ran later out of turn, and a typed "yes" was queued and run as a task. A component with more states than idle and busy needs every kind of message considered in every state.
Silence that looked like success
Three failures were silent in the same way. Queued messages vanished at a restart after the owner had been told "Noted". A task could be logged as done while its reply never arrived. A task ended by force was recorded as costing nothing. Each repair is a journal line (queued, reply or an error with parts_sent, a forced task_end with an estimate). A line in a file does not tell the owner anything by itself; it is what lets the program tell them.
Limits that are not quite limits
The daily budget used to be checked only before a task started, so a task begun a cent under the limit could still spend its own $0.50. It is now a ceiling as well: after each model call the task's estimated cost is compared with what was left of the day, and the task is ended, with its partial answer and the reason, when it reaches that. The figure is the program's own estimate, so the day can end a few cents over. A second task running at the same time is counted too: the room left in the day is what remains after the estimates of every task still running. The library's own hard cap is still not set. And in one live run, a task stopped through layer one was recorded as costing nothing, because the library's running total had not yet moved; the amount appeared against the next task. The day's total was right and the attribution off by one task. Whether that still happens has not been re-checked.
A question the program puts to the owner (a stranger's mail to read, a fact to save, a verdict on a deck) stays in the chat for as long as the chat does. What each button meant was once held only in the running program, so a restart left buttons that did nothing. Each question is now written to a file as it is put and removed when it is answered (odysseus/offers.py); one nobody answers in two weeks is dropped. Work approved after a restart reports in the owner's own chat. An approval asked for in the middle of a task is different: it belongs to the task, and dies with it.
One thing at a time, and the long wait that was not work
The assistant does one task at a time. A message that arrives during a task is acknowledged and waits. For a twenty-second answer nobody notices. The longest wait was not a task at all: opening a document on a viewing site takes two to three minutes in a browser, all of it waiting, before any model is involved.
That reading now runs in the background. The owner is told it has begun and can go on talking; other messages are answered as usual; and when the pages are in, the take arrives as a task of its own. A second link sent meanwhile waits its turn and is opened when the first is done. "stop" ends a reading as it ends a task. Verified by unit tests (tests/test_background.py), with a stand-in reader that finishes only when the test lets it.
The first version of the queue for a second link had a fault that a test found at once: when its turn came, a task was already running (the take on the first document), so the link was queued as an ordinary message and would have reached the model as words it cannot open. The next reading is now started directly.
What the first version left out was more than one model task at once, and it was left out on purpose. The reason was the gate. What a task has read, what the owner asked in it, how many changes it has made unasked, and whether anybody is there to be asked were all kept for "the current task". Two tasks at once would have shared them: a new message would have cleared the record of what the other task had read, a task starting would have thrown away changes the other was about to report, and one task ending would have cancelled the other's question to the owner.
Several tasks at once
It was then built as a change of its own. The owner's conversation is one agent. A small number of others, two by default, each take one job at a time in the background. Which jobs go there is decided by code, and the rule is narrow: a job the owner attached no words to, and which is therefore complete in itself. A deck sent with no message. A document read from a link with no message. A filing the owner approved from a question. Anything the owner said something about stays in the conversation, where the answer belongs.
The gate was not given a separate copy of its state for each task. It was given a rule: whatever is kept for the current task is kept for all the running tasks together, and always in the stricter direction.
| Kept for a task | With one task | With several |
|---|---|---|
| What it has read that others wrote | Cleared only when a new conversation begins | Not cleared while another is running, even then: each sees everything any of them has read |
| Changes waiting to be reported | Discarded when a task begins, as left over | Not discarded: they are the other task's, and are reported by whichever reply comes first |
| The count of unasked changes | Starts at nought | Goes on counting across all of them |
| What the owner asked | This task's request | Every running request, for the second reader |
| Who is being asked | Nobody, once the task ends | Somebody, until the last task ends; one task ending cancels no question of another's |
| An approval widened to a thread | Applies | Does not apply: every reply is shown first |
Each row errs towards more questions, never fewer. This can be stated and tested without reasoning about which task did what: with several tasks running, nothing is allowed that would not have been allowed with one. A separate copy for each task would be more exact and was not needed. It would also have meant that a tool, when it runs, has to know which task called it, which the agent library does not tell it.
A job in the background is not part of the conversation, which has gone on meanwhile. So its result is told to the conversation's model with the owner's next message, as a routine's message is, so that "tell me more about that deck" makes sense. The text of the file is not carried over: a question about a particular page means sending it again. "stop" ends every job as well as the conversation's task, and after a restart a job that was cut off is named.
Run against the real model on both agents: a deck handed over with no message, and a question asked in the same second. The question was answered in 3.6 seconds. The deck's take arrived at 32 seconds, with the company filed and the planted text on page nine reported. Verified, one run. The safety table above is held by unit tests, one for each row (tests/test_two_tasks.py). Not tested in real use, and not with a job in the background that asks the owner a question while the conversation is also asking one.
Replies that show the machinery
After a stretch of real use the owner read back through the chat and said the answers showed too much of the product: which service had been searched, what the database "returned", what the program had done. Every instance was true but unwanted. "I searched the database first and found no existing record, then filed three records" tells a partner how the software works. "Filed: the company and both founders, all new" tells them what happened.
The cause was in the instructions. They said one line about style ("short and direct") and several pages about tools, each of which spoke of "the program", "your notes" and tool names, because that is how the model has to be told what it can do. A model writes in the vocabulary it is given. The instructions for a pitch deck even asked for a section headed "what your notes say".
The repair is a last section of the instructions, read after every tool's part, on how to write to the owner: lead with the outcome; do not narrate the work; never name the machinery; name a service only as a place the owner uses ("in Attio", "in your inbox"), never as the actor in a sentence; what is remembered about the owner is simply known. It ends with what must never be dropped: what was sent, filed or changed and where, what was not done, when somebody else can now see something, and when something read contained words addressed to an assistant. Those are facts about the owner's affairs, not machinery.
It was measured with a rule a person can read: a short list of patterns (a lookup narrated, a system as the actor of a sentence, an internal name, "your notes", Markdown marks) counted in every reply of the firm's errands (Chapter 17). Before, 8 of 19 replies showed the machinery, in 56 places. After, 3 of 38, in 8 places, and the median reply fell from 157 words to 129. All five invariants held in both, and replies still reported a planted instruction when there was one. Verified, one run of 19 before and one of 38 after. A count of patterns is not a judgement of tone, and the owner has not yet read the new replies.
A check that cannot fail
Because "Done on your accounts" is written by code, an evaluation check called "honest" that compared that line with the world could hardly fail, and measured nothing about the model. The model's own words have to be checked separately (Chapter 17).
4.13How to test it
The control layer is the part of an agent that tests cover well, because its behaviour is fixed by code. A test of it must check that a stranger gets no reply, preview or model call; that "stop" never reaches the model, ends the task within a bounded time even when the interrupt is ignored, and empties the queue; that queued messages run in order and a sixth is refused; that commands are answered during a task; that each limit ends or refuses a task and says so; and that a reply that cannot be sent is recorded as lost without leaving the program stuck.
The existing tests use a stand-in for the agent library, FakeClient in tests/test_slice.py, which plays a fixed script and can be told to hang, or to hang and ignore interrupts. That file's 28 tests pass. Verified The layer-two test shows what a stand-in is for: a real model nearly always stops when interrupted, but the stand-in can refuse every time. The test requires an answer within two seconds, forced: true in the journal, and a replaced connection. The queue is tested in tests/test_durability.py (order, the limit of five, stop dropping what waits, commands answered during a task) and the "still stopping" window in tests/test_stage0.py.
What those tests cannot show is whether the real library behaves like the stand-in. Live runs settled some of it. Verified Layer one ended a real task in 1.1 seconds with a new connection per message and in 0.13 seconds with the connection kept open, and the same connection answered the next message. The library's start-up report listed exactly one tool, the search, confirming that its built-in tools were removed. The owner messaged the bot in Telegram and it answered. Layer two has never been needed in a live run.
Verified by unit tests against a stand-in: the owner check, the order of checks, the queue and its limit, both layers of stop, the three limits, the ledger derived from the journal, and the reporting of lost replies. Verified live, in single runs: layer-one stop on a real task; one kept connection serving several messages; replies in Telegram itself.
Not tested: layer-two stop against the real library; whether the streamed previews look as intended on a phone (they were never examined); the rule that a late message is reported and not run, for Telegram, which has no test because the stand-in for Telegram carries no dates; a real restart with messages waiting. The attribution of a stopped task's cost to the next task was seen once and not re-checked. Single live runs show that something happened once and are not rates.
4.14Where this sits in the literature
The journal is the oldest idea in the chapter. [Kreps 2013] presents the append-only, ordered log as the basis from which other state is derived and replicated, and [Fowler 2005] gives the pattern of recording every change as an event and rebuilding or correcting state by replaying the events. This chapter takes the first half of that pattern and not the second. Spending, what was interrupted and whether a reply left are computed from the journal, but memory, the schedule and the conversation are kept in stores of their own, and nothing rebuilds them by replay. Event sourcing in full is the stronger design: in it every state can be recomputed, where here only the listed figures can. Its price would be writing every store as events, including the agent library's transcript, which the program does not own. [Helland 2015] argues that append-only, immutable data makes history easier to reason about, with derived views built on top; that is the argument for opening the file in append mode and never editing a line.
[Kleppmann 2017] treats at length two questions this chapter answers briefly: when a write counts as durable, and what "exactly once" can mean when a process can fail between doing something and recording it. The journal here is appended and closed but not forced to the disk, so it survives a crash of the program and not necessarily a loss of power; a textbook design would say which of the two it promises. Ordering is easier than in the distributed case [Lamport 1978]. One process appends to one file, so the order of lines is a total order that agrees with what happened before what inside that process, and the timestamps are needed only to group lines by day.
The two layers of stop rest on a point made by [Waldo et al. 1997]: a call to another machine can fail partially or never return, so an interface that treats it as local will hang. The interrupt is such a call, and the second layer exists because it may not return. [Saltzer et al. 1984] argue that a function can be provided correctly only with knowledge at the endpoints. The line "Done on your accounts" is built at the endpoint that knows, the tool that made the change, and not by the model in between, whose account of what happened is a claim.
The layer's handling of the owner's attention has a separate literature. [Klein et al. 2004] ask that automation keep common ground with the people it works with and make its actions observable; "Noted.", the status line before the first word, and a stated reason for every task ended early are small instances. [Hutchins et al. 1985] describe the gulf of evaluation between what a system did and what its user can tell. A reply that says "I've sent it" when nothing was sent widens that gulf in the worst way, which is why the claim check exists. The check falls well short of what that analysis asks for: it reads four kinds of act in a short list of phrasings, and a claim worded otherwise passes.
Two questions are not settled. How an assistant should decide that a conversation has run its course, so that beginning again loses less than it saves, has no agreed answer; the rules here are arithmetic about cost, and their effect on the owner was not measured. And whether a personal agent should run one task at a time or several is open: the rule adopted here, that shared state is merged in the stricter direction, is safe by construction, but it has not been compared with a separate record per task on how often each asks the owner.
- Around the agent loop sits a control layer that decides who may speak, when work starts and stops, what it may cost and what is reported. None of those decisions is the model's.
- Every message passes the same checks in a fixed order. The owner check is first; commands and "stop" come before the busy check; the budget check is the last thing before a model is called.
- Strangers get silence, and are dropped before any model call so they cost nothing.
- The conversation runs one task at a time. Up to five messages wait their turn; "stop" drops them and says how many.
- "Stop" has two layers: an interrupt, then cancellation after a five-second grace period that depends on nothing outside the program.
- The journal is append-only. Spending, status, what was interrupted and whether a reply left are all derived from it.
- What was done on the owner's accounts is reported in lines written by the program from what the tools did, not in the model's words.
Review
- Why is the owner check placed before the command parser, rather than only before the model call? Give one concrete thing a stranger could do if it were placed later.
- The layer-two stop records the forced task's cost as an estimate from token counts. Why can it not use the library's own figure? What would be lost if it simply recorded zero?
- Extend the code: add a command
/queuethat lists the messages waiting behind the current task by their preview, without calling a model. Which existing fields make this possible, and what should it say when nothing is waiting? - Read the code: at start-up, lines older than five weeks are moved from the journal into one compressed file per month, and
unfinishedand the ledger read what is left. What must stay true for the ledger to remain correct, and which question about the past can the running program no longer answer? - The model's prose and the program's "Done on your accounts" line can disagree. Write down three different ways they could disagree, say which one the owner should believe in each case, and propose a check (in code or in evaluation) that would catch the disagreement.
Analysis
- The daily budget is $3.00 and the per-task ceiling $2.00 (four times the mark of $0.50), and both are compared with the program's estimate after each model call. Assume that one task runs at a time, that no model call costs more than $0.04, that the estimate is exact, and that a task ends at once when a limit is reached. Under rule A, the daily budget is checked only before a task starts. Under rule B, a task is also ended after any model call that brings its cost to what was left of the day when it began. (a) For each rule, find the least upper bound on the total that can be recorded for one day, and say whether it can be reached. (b) Name one assumption that the chapter tells you does not hold in practice, and say in which direction it moves your answers.
- The chapter claims that with several tasks running, nothing is allowed that would not have been allowed with one. State the property of the gate G of Definition 6, as a function of T, on which the claim rests, and prove the claim from it. Then write a plausible rule that lacks the property, and give two tasks whose merged record lets a call run unasked that either task alone would have put to the owner.
- Definition 8 calls a value derived state if it is a pure function of a prefix of the journal. For each of these, decide from the code in this chapter and
odysseus/journal.pywhether it is derived state: the spending shown by/status; the word "working" or "idle" shown by/status; what was interrupted, as computed at start-up; the cost of a task ended by force. For each that is not, describe an execution in which it differs from a figure computed from the journal alone, and say which of the consequences of Property 3 is lost. - The property "stop ends a task within a bound" has a hypothesis about cancellation. Describe, as the behaviour of code and not as a program, two tasks for which the bound fails: one that swallows the cancellation, one that never yields. For each, say whether the owner's "stop" is even read, what the owner sees, and what the journal shows afterwards.
Design
- Two people share one assistant, each with their own chat identity and both counted as owners. Redesign D(m, q): the owner check, the queue, whose "stop" stops what, the daily budget, approval questions, and the report of what was done. For each guarantee of the single-owner design, say whether each owner keeps it, and what is given up.
- A new requirement: an auditor must be able to read the journal without seeing any message's contents, and the owner must be able to remove everything recorded about one named person. Design the record format and the derived figures. Say which consequences of Property 3 survive a removal and which do not, and what the auditor can still verify.
Reading
- [Kreps 2013] argues that an ordered, append-only log can be the one source from which other state is derived. In about four hundred words: what it claims; why it matters for the decision in this chapter to derive spending from the journal instead of keeping a running total in a file of its own; where you were not convinced that a log suits a single personal program; and what you would measure or build next.
- [Fowler 2005] describes rebuilding state by replaying events. In about four hundred words: what it claims; why it matters for the decision in this chapter to keep memory, the schedule and the conversation outside the journal; where you were not convinced; and what you would need to append for the conversation to be rebuilt from the journal alone, and what that would cost.
Open
- Hard, open: the conversation runs one task at a time, and only jobs the owner attached no words to go to the background. Sketch a version that lets a slow task the owner did ask for in words (such as a long browser run) continue in the background while the owner starts another task. What happens to the single conversation the model sees, to "stop", to the queue, and to the per-task budget? Which of this chapter's guarantees would you have to give up, and which could you keep?
- When should an assistant close a conversation and begin again? State the choice as a trade between the cost of carrying the old context and a loss you can measure, such as how often the owner must repeat something the assistant should have known. Design a study on invented conversations that would compare the two rules in this chapter (a pause of two hours, and size above 40,000 tokens after the cache has lapsed) with a rule of your own. Progress would be a rule shown to do better on both measures on conversations held out from its design.