tool = {t.__name__: t for t in tools_for(FullHost())}
[summarise(tool[t], a) for t, a in [
('search_code', {'query': 'where is compaction triggered'}),
('view_file', {'path': 'nbs/01_runtime.ipynb', 'start': 40, 'end': 80}),
('edit_cell', {'path': 'nbs/00_core.ipynb', 'cell_id': '451586c0'}),
('inspect_python', {'code': 'list(df.columns)', 'scope': 'overlay'}),
('git_status', {}),
]]agent
Agent class: one conversation with a model, the tools it may call, the approvals that guard them, and the record of what it did.
The activity feed
The activity feed is the list of tool calls a turn has made, one row per call. A frontend draws each row as a short line such as View a.py:4-, not as a raw view_file(path='a.py', start=4). Each tool has a summary function that makes this line. summarise from tools calls it. The cell below shows the line for five common tools.
A tool without a summary function, such as one an extension added, still gets a line. The line is the tool name and its arguments, as the last example shows. Every tool in FullHost has a summary, and the bare check asserts this.
bare = sorted(t.__name__ for t in tools_for(FullHost()) if getattr(t, 'summary', None) is None)
test_eq(bare, [])
summarise('word_count', {'path': '/proj/a.py'})Act is one row of the feed. It is one tool call, and it exists from the moment the call starts. A frontend can show ⏳ Web fetch: ... while the fetch is still running. kind comes from the tool’s group and selects the icon. line returns the one-line text.
Act
def Act(
tool:str, args:dict=<factory>, summary:str='', detail:str='', ok:bool=True, done:bool=False, secs:float=0.0,
started:float=<factory>, id:str=<factory>, turn_id:str='', revision:int=0, branch_id:str='main',
parent_action_id:str='', run_id:str='', state:str='running', kind:str='', ask_id:str=''
)->None:One tool call, from the moment it starts to whatever it returned.
a = Act('read_url', {'url': 'https://nbdev.fast.ai/api/export.html'},
summarise(tool['read_url'], {'url': 'https://nbdev.fast.ai/api/export.html'}))
a.kind, a.icon, a.line()finish records the outcome, the time taken and the result. state becomes complete or failed. A frontend can use state to choose a colour. The line of a failed call starts with a warning sign, as the second example below shows.
a.finish('# Exporting a notebook to a library\n\nnb_export(...)')
a.line(), a.statemd renders the row as markdown. The result is folded under a <details> tag. A notebook cell that saves an answer can keep the tool work one click away and does not print every result above the answer.
print(a.md())bad = Act('edit_file', {'path': 'a.py'}, 'Edit a.py').finish('edit failed: stale address', ok=False)
test_eq(bad.state, 'failed')
bad.line()Activity is the whole feed for a session. It calls on_change when a row starts and when it finishes, which is twice per call. A frontend redraws from this callback. rows returns the feed as dicts, lines returns one string per call, and md returns folded markdown. The feed keeps at most max_acts rows (MAX_ACTS, 500) and drops the oldest first.
Activity
def Activity(
on_change:NoneType=None, max_acts:int=500
):The calls of a session, and the on_change callback a frontend uses to redraw.
seen = []
feed = Activity(on_change=lambda act: seen.append((act.tool, act.done)))
act = feed.start('search_code', {'query': 'compaction'})
feed.finish(act, 'nbs/01_runtime.ipynb:88 threshold')
seenActivity calls on_change outside its lock. It discards any exception the callback raises. A broken frontend cannot stop the model’s turn. The callback below divides by zero, and the row is still recorded.
noisy = Activity(on_change=lambda act: 1/0)
noisy.finish(noisy.start('outline', {'path': 'a.py'}), 'ok')
len(noisy)mark(turn_id) records where the current turn begins and sets turn_id on every new row. rows, lines and md accept a mark= position and then return only the rows after it. Without mark=, they return every row in the feed.
feed.mark('turn_000002')
feed.finish(feed.start('view_file', {'path': 'a.py'}), 'def a(): return 1')
feed.lines(), feed.lines(mark=feed._mark)test_eq(len(feed.rows()), 2)
test_eq(len(feed.rows(mark=feed._mark)), 1)
feed.rows(mark=feed._mark)[0]['turn_id']Approvals
A write tool is a tool that changes something: it edits a file, runs a command, or commits to git. The approval gate stands between the model and these tools. Before a write runs, the gate raises an Ask. An Ask is a request that a person answers with yes or no. The gate shows a preview of what the call would do and waits. A refusal goes back to the model as the tool result, with the person’s reason. The model can then change its approach.
The gate’s mode decides who answers:
| mode | what happens |
|---|---|
ask |
every write waits for a person |
edits |
file and notebook edits run; other writes wait |
auto |
every write runs |
off |
every write is refused |
edits mode does not cover the ALWAYS_ASK tools (add_root, restart_kernel, page_eval). These tools still wait for a person in edits mode. In off mode they are refused. A session built with approve='none' has no gate.
preview_for
def preview_for(
name, args, host:NoneType=None
):What this call would do, as text a person can read quickly.
A backend hands the approver each tool call as a dict in the OpenAI shape, {'function': {'name': ..., 'arguments': ...}}, where the arguments may be a JSON string. _tc returns the name and the parsed arguments.
_tc({'function': {'name': 'edit_file', 'arguments': '{"path": "a.py", "commands": "[]"}'}})preview_for turns one call into the text a person reads before approving it. The useful preview depends on the tool: the edit commands for edit_file, a diff for replace_text and edit_cell when the host can read the file, the head of the new file for create_file (and whether it overwrites one), and the command line for run_shell.
print(preview_for('edit_file', {'path': 'a.py', 'commands': [['2|ab12|', 's', 'return 1', 'return 2']]}))h = MemHost({'/proj/a.py': 'x = 1\n'})
p = preview_for('replace_text', {'path': '/proj/a.py', 'edits': [{'oldText': 'x = 1', 'newText': 'x = 2'}]}, h)
assert '-x = 1' in p and '+x = 2' in p, p
assert 'old' in preview_for('edit_cell', {'path': '/proj/n.ipynb', 'cell_id': 'c1', 'edits': [{'oldText': 'old', 'newText': 'new'}]})
assert '12|ab| s' in preview_for('edit_file', {'path': 'a.py', 'commands': [['12|ab|', 's', 'old', 'new']]})
assert 'a.py' in preview_for('replace_text', {'path': '/proj/a.py', 'edits': 'not json'}, h)print(preview_for('create_file', {'path': 'new.py', 'text': 'def f(): pass\n'}, host=NullHost(['/proj'])))A tool preview_for does not know falls back to its arguments as JSON.
print(preview_for('word_count', {'path': '/proj/a.py'}))An Ask is one approval request and the person’s answer to it. answer is None while the request waits. An Ask is true only when approved. A backend’s if not approve(tool_call) check works on it directly. reply returns the text the model sees.
Ask
def Ask(
tool:str, args:dict=<factory>, summary:str='', preview:str='', id:str=<factory>, answer:bool=None, note:str='',
asked:float=<factory>, run_id:str='', run:object=None, forced:str='', _shown:set=<factory>,
_done:threading.Event=<factory>
)->None:One request, and the person’s answer to it. answer is None while it is pending.
answer_md
def answer_md(
ask
):The person’s half of the exchange, in the same voice; a question a mod asked is named by its title.
ask = Ask('edit_file', {'path': 'a.py'}, 'edit_file → a.py', 'a.py\n\n2|ab12| s')
ask.pending, bool(ask)A refusal can carry a reason. The model receives it, so it can change its approach instead of sending the same edit again.
ask.resolve(False, 'keep the docstring')
bool(ask), ask.reply()An approval can carry a note too, such as “yes, but keep the docstring”, which the model needs while it makes the edit. A plain approval tells the model nothing extra, so its reply is None.
test_eq(Ask('edit_file').resolve(True).reply(), None)
Ask('edit_file').resolve(True, 'but keep the docstring').reply()ask_md and answer_md render a request and its answer as markdown, for a frontend that shows approvals in a notebook or a chat.
print(ask_md(Ask('create_file', {'path': 'new.py'}, 'create_file → new.py', 'new.py (new file, 15 chars)')))answer_md(ask)Approvals is the gate itself. It holds every request that is still waiting. waiting lists them oldest first, and pending is the oldest. The gate calls the frontends that listen. It blocks the model’s thread until each request is answered, refused or timed out. Each call gets its own decision. A model that asks for four writes causes four requests. The main parameters are:
tools, the names that need approval; an agent adds every write tool it builds;mode, one of the four modes above;timeout, the seconds a request waits (DFLT_TIMEOUT, 300), or None to wait forever;policy, a host’s functionfn(name, args)returning'allow','deny','ask'or None, consulted before saved rules and the mode;rules_path, a JSON file of saved allow and deny rules, whichalwaysadds to;no_listenerandon_timeout, what happens when no frontend listens or nobody answers in time.
Approvals
def Approvals(
tools:tuple=(), # tool names that need approval
mode:str='ask', # 'ask', 'edits', 'auto' or 'off'
timeout:int=300, # seconds to wait; None waits forever
host:NoneType=None, # for previews that read disk
on_ask:NoneType=None, # called with the `Ask` when one is raised
on_answer:NoneType=None, # called with the `Ask` when it is answered
rules_path:NoneType=None, # saved allow/deny rules, `<cfg>/approvals.json`
no_listener:str='refuse', # with nobody listening: 'refuse', or 'wait' for a listener
on_timeout:str='refuse', # an ask nobody answers in time: 'refuse' or 'allow'
policy:NoneType=None, # `fn(name, args)` -> a `VERDICTS` entry or None, consulted before rules and modes
):The approval gate: it holds each request waiting for an answer and wakes the model’s thread when a person answers.
call_key
def call_key(
name, args
):One call as a hashable: the same tool with the same arguments, however the dict is ordered.
subject
def subject(
name, args
):What a saved rule is matched against: the command, else the path, else the summary.
Some tools write only for certain arguments. generate_image with a path saves the picture where the model says. The gate treats it as a write. Without a path it adds a file under media/ and runs without asking. path_write encodes this rule. The cell also shows a saved rule, made with always, that refuses a path under .git/ even in auto mode.
ap = Approvals(tools=WRITE_TOOLS)
assert path_write('generate_image', {'path': 'main.py'}) and not path_write('generate_image', {'path': ''}) and not path_write('create_file', {})
test_eq(ap.request('generate_image', {'prompt': 'x'}).answer, True)
probe = ap.request('generate_image', {'prompt': 'x', 'path': 'main.py'})
test_eq(probe.answer, False)
ap.mode = 'auto'; test_eq(ap.request('generate_image', {'prompt': 'x', 'path': 'refs/a.png'}).answer, True)
ap.always('generate_image', '.git/*', 'deny', glob=True)
test_eq(ap.request('generate_image', {'prompt': 'x', 'path': '.git/config'}).answer, False)A request raised inside a run records that run in run_id. A frontend can use run_id to tell a sub-agent’s ask from the main turn’s. close refuses every request that is waiting and every later request. A session calls close when it ends.
gate = Approvals(tools={'edit_file'}, mode='ask', timeout=1)
test_eq(gate.request('edit_file', {'path': '/proj/a.py'}).answer, False)
from ramabana.runtime import Run, run_context
auto = Approvals(tools={'edit_file'}, mode='auto')
with run_context(Run('run_bg', 'background', 'q')):
test_eq(auto.request('edit_file', {}).run_id, 'run_bg')
test_eq(auto.request('edit_file', {}).run_id, '')
test_eq(gate.closed, False)
test_eq(gate.close(), [])
test_eq(gate.closed, True)
test_eq(gate.request('edit_file', {}).answer, False)A request with no frontend listening is refused at once, and the reason says so. Without this, the model’s thread would wait for the whole timeout for an answer that cannot come. With no_listener='wait' the request waits until a frontend calls listen.
gate = Approvals(tools=WRITE_TOOLS)
gate.listeners, gate.request('edit_file', {'path': 'a.py'}).reply()listen registers a frontend. Its on_ask callback receives each new Ask. The frontend answers with answer(ask.id, ok, note). Here the callback answers at once. A real interface shows the preview and answers when the person decides. listen returns a function that unregisters the frontend.
stop = gate.listen(on_ask=lambda a: gate.answer(a.id, False, 'rewrite it as a patch instead'))
decision = gate.request('edit_file', {'path': 'a.py', 'commands': '[]'})
bool(decision), decision.reply()A tool outside tools is approved at once, and no frontend sees a request. The Ask is still recorded in history.
test_eq(bool(gate.request('search_code', {'query': 'x'})), True)
test_eq(gate.pending, None)
len(gate.history)In auto mode every write is approved without asking. A plain approval has no note, and its reply is None. In off mode every write is refused, and the reason names the mode.
Approvals(tools=WRITE_TOOLS, mode='auto').request('edit_file', {}).reply(), Approvals(tools=WRITE_TOOLS, mode='off').request('edit_file', {}).reply()answer(..., session=True) approves the request and switches the gate’s mode for the rest of the session. The new mode is auto unless scope names another. When the person gave no note, the gate adds a note that records the change.
stop()
gate.listen(on_ask=lambda a: gate.answer(a.id, True, session=True))
first = gate.request('edit_file', {'path': 'a.py'})
gate.mode, first.note
test_eq(gate.mode, 'auto')scope='edits' switches to edits mode instead. The shell stays gated in edits mode. edits mode does not cover add_root. A request to widen the folders the agent may touch still asks.
scoped = Approvals(tools=WRITE_TOOLS | {'run_shell', 'add_root'}, timeout=1)
scoped.listen(on_ask=lambda a: scoped.answer(a.id, True, session=True, scope='edits'))
first = scoped.request('edit_file', {'path': 'a.py'})
test_eq((bool(first), scoped.mode), (True, 'edits'))
test_eq(scoped.decide('edit_cell', {'path': 'n.ipynb'}, force=True).answer, True)
test_eq(scoped.decide('run_shell', {'command': 'ls'}, force=True), None)
test_eq(scoped.decide('add_root', {'path': '/elsewhere'}, force=True), None)
test_eq(Approvals(mode='edits').decide('add_root', {'path': '/elsewhere'}, force=True), None)
test_eq(Approvals(mode='auto').decide('add_root', {'path': '/elsewhere'}, force=True).answer, True)
test_eq(Approvals.edits_cover('edit_file'), True)
test_eq([Approvals.edits_cover(n) for n in ('add_root', 'run_shell')], [False, False])A model that makes the same gated call three times in a row is stuck. The same call means the same tool with the same arguments, with no other gated call in between. auto mode would let the model continue, and ask mode would put the same question a third time. Instead the DOOM_LOOPth identical call, the third, goes to a person as a forced ask in ask, edits and auto mode.
- It takes the ordinary
requestpath. The terminal waits for the person, and a frontend is asked again. - With nobody listening, it is refused, and the reason names the loop.
offmode and a saved deny rule still answer first.- A different call starts the count again.
spin = Approvals(tools={'edit_file'}, mode='auto', timeout=1)
asked = []
spin.listen(on_ask=lambda a: (asked.append(a), spin.answer(a.id, False, 'stop looping')))
call = {'function': {'name': 'edit_file', 'arguments': {'path': 'a.py'}}}
test_eq([bool(spin.gate(call)) for _ in range(3)], [True, True, False])
test_eq(len(asked), 1)
test_eq(bool(spin.gate({'function': {'name': 'edit_file', 'arguments': {'path': 'b.py'}}})), True)
alone = Approvals(tools={'edit_file'}, mode='auto')
[alone.gate(call) for _ in range(2)]
alone.gate(call).reply()A request nobody answers within timeout is refused, and the reason gives the wait. With on_timeout='allow' the request is approved instead. A request that the policy or the loop guard put to a person is still refused. When a turn is cancelled, cancel_all refuses every waiting request. No thread stays blocked.
slow = Approvals(tools=WRITE_TOOLS, timeout=0.01)
slow.listen(on_ask=lambda a: None)
slow.request('edit_file', {'path': 'a.py'}).reply()timeout=None waits until the request is answered. mk_agent passes None by default, because a person sits at the terminal. Approvals itself and the ACP server keep DFLT_TIMEOUT.
patient = Approvals(tools=WRITE_TOOLS, timeout=None)
patient.listen(on_ask=lambda a: threading.Timer(0.05, patient.answer, (a.id, True)).start())
test_eq(bool(patient.request('edit_file', {'path': 'a.py'})), True)gate is the function a backend calls before it runs a tool. It takes the tool-call dict, raises a request and blocks until the request is decided. Every backend takes the same approve(tool_call) function. The gate works without the local engine installed. always and never are two fixed approvers for code that needs an approver and has no gate.
tc = {'function': {'name': 'edit_file', 'arguments': {'path': 'a.py'}}}
bool(gate.gate(tc))ask_all = Approvals(tools=WRITE_TOOLS, mode='auto').gate
[bool(ask_all({'function': {'name': n, 'arguments': {}}})) for n in ('search_code', 'run_python', 'edit_file')]The old approval shim
applied, apply and note remain for older callers that patched approvals into fastllm. Hosted models now reach the gate through rishi’s remote path. Nothing is left to patch. applied and apply return True. note returns 'provided by rishi.remote'.
applied(), note()Tools the user names
The model chooses its own tools during a turn. A person can also name a tool in the prompt. /search_code compaction threshold requests search_code with that query. prompt_directives finds such names, and the turn adds them to its plan. A named search tool (search_code, web_search, research or memory_search) runs before the model is called, and its result goes into the message as evidence. No other tool runs before the model.
INLINE_SKILLS and inline_for belong to the briefing, below. They choose which skills the briefing contains in full.
inline_for
def inline_for(
inline, names
):The skills to inline for a tool list. exhash is kept when edit_file is offered or names is empty.
A frontend often wraps the person’s words in context, such as the open notebook or the screen. It marks the words with a <user-request> tag. compose, later on this page, builds such a message. request_text returns only the person’s words. Code that looks for intent, such as prompt_directives, reads this text.
turn_prompt
def turn_prompt(
turn
):A logged turn’s prompt as text. A row written before prompt_text existed holds the repr of a list with picture bytes.
prompt_text
def prompt_text(
prompt
):A prompt as log text. A picture becomes [image] and a sound becomes [audio], never the repr of its bytes.
request_text('<notebook path=a.ipynb>\n...\n</notebook>\n\n<user-request>\nscale df as df_norm\n</user-request>')prompt_directives finds /name mentions in a prompt. A name counts only when it is a tool or skill this agent offers. A URL or a path such as /x/y/z is left alone. It returns two lists: the requested tools, each with the text that follows it up to the next mention, and the skills to load.
prompt_directives
def prompt_directives(
prompt, tools:tuple=(), skills:tuple=()
):Explicit /tool and /skill-name mentions in an ordinary prompt. Known names only.
host = MemHost({'/proj/a.py': 'def a(): return 1\n'})
ts = tools_for(host)
prompt_directives('/search_code compaction threshold and see https://x/y/z', tools=ts)The briefing
The briefing is the system prompt: the standing instructions the model reads with every turn. system_prompt builds it from these parts, in order:
- what the agent is, and the folders it may work in;
- a description of this machine, when the host gives one;
- the working rules (
work_rules), keeping only those whose tool is offered; - the skill catalogue: each skill’s name and the first sentence of its description, clipped to
CATALOGUE_CHARS(70) characters; - any skill inlined whole (a skill from the learned folder is clipped to
MAX_CONTEXT_FILE); - lessons kept in
<cfg>/learned/AGENTS.md; - the project’s own instructions (
project_context); extra, text the caller adds last.
A skill is a markdown document that tells the model how to do one kind of work. The catalogue lists names only. The model calls read_skill to get a body. The one exception is INLINE_SKILLS. exhash is inlined. inline_for keeps it when edit_file, the tool it teaches, is offered, or when no tool list is given.
small_system_prompt is the short briefing for small local models. It holds the folders, one line about the machine, SMALL_RULES, and clipped lessons and project instructions.
small_system_prompt
def small_system_prompt(
host, tools:tuple=(), cfg:NoneType=None, learned:NoneType=None
):The small profile’s briefing: the folders, one machine line, SMALL_RULES, and clipped lessons and project instructions.
system_prompt
def system_prompt(
host, skills:tuple=(), inline:tuple=('exhash',), extra:str='', tools:tuple=(), cfg:NoneType=None,
pictures:bool=True, # whether the turn model sees a picture a tool returns
learned:NoneType=None, # the folder `learned_context` reads; None leaves it out
):The agent’s briefing: its identity, folders, rules, skills, lessons and project instructions, then extra.
skill_catalogue
def skill_catalogue(
skills
):The briefing’s skill list. One line per skill: its name and the first sentence of its description, clipped to CATALOGUE_CHARS.
work_rules
def work_rules(
names:tuple=(),
rules:tuple=((None, 'Act on the user’s verb. “Create”, “run”, “fix”, “add” and “as NAME” request a\n result, not a plan: use the tool that produces it, verify it, then report what exists.\n Never stop at “I will…”.'), (None, 'Before each tool call, write one short line in the -ing form saying what you are doing, so the\n user can follow the work: “Reading the config loader.” End with the result, conclusion, or what\n is needed.'), (None, 'Never claim a file changed, a command passed, or a test went green unless a tool\n result in this conversation says so. If you did not run it, say you did not run it.'), (None, 'A tool result starting with ERROR: is a failure. Read it, fix the cause, and try a\n different approach. Calling the same tool again unchanged is never the fix.'), (None, 'Keep a plan small enough that every step has one independently verifiable outcome, and verify\n a step before building on it. If verification would widen the scope, split the step or report\n the blocker.'), ('search_code', 'Use `search_code` for project behaviour, unfamiliar APIs, or uncertainty about an\n installed library -- the index covers this repo *and* every installed package. Do not\n search for routine Python you already know.'), ('grep', 'Use `grep` when you know the exact string: a symbol you are renaming, an error\n message, an import. `search_code` finds what is *like* the query; `grep` finds every\n place it literally occurs, which is what a rename or an audit needs.'), ('view_file', 'Prefer `view_file` over guessing. Copy paths exactly from the workspace, notebook\n context, or search results; never shorten, repair, or reconstruct a path.'), ('replace_text', 'To change a file: read it, then `replace_text` with `oldText` copied exactly from\n what you read. Send every change to one file as one call.'), ('edit_file', '`edit_file` addresses lines by the hashes `view_file` returns, so a stale read fails\n instead of damaging the wrong line; read the `exhash` skill before your first one.'), ('notebook_cells', 'Never use `view_file` or `replace_text` on an `.ipynb` file. Call `notebook_cells` on\n its exact path, choose the returned cell id, then `view_cell` and `edit_cell`.'), (None, 'A `<notebook path="…">` block is the open notebook and its exact path. Its cells are\n already visible; use that path with the notebook tools and never reconstruct it.'), ('run_shell', 'Check your work with `run_shell`: after an edit run the project’s tests, after a\n signature change run its linter or type checker. Use the commands the project itself\n documents (README, pyproject, Makefile). Only commands that exit on their own: a server,\n watcher or slow suite goes to `run_shell_bg`, read with `shell_output`.'), ('run_python', 'Code cells inside `<notebook>` have already executed. Their printed `<output>` is not\n Python and must never be copied into `run_python`. For a request about `df`, call\n `inspect_python()` with no code first, then run only the transformation the user asked for.'), ('run_python', '`run_python` shares the user’s kernel namespace. Read anything; bind results to NEW\n names. You cannot rebind or delete the user’s variables, so do not try.'), ('own_python', '`run_python` runs on the project’s interpreter, which has the project’s packages only. Your own\n packages (rupaka, kosha, ramabana, nbformat, the host’s own) import in `own_python`, a kernel of\n your own with the project folder as cwd. The user’s variables are not there: use `run_python` for them.'), ('web_search', '`web_search` and `read_url` reach what is outside this machine: current documentation,\n releases, news. The repository and its installed packages are answered locally.'), ('memory_search', 'When prior context could change what you do -- a project you have worked on before, a\n preference, an earlier decision -- search Vishalakshi durable memory with `memory_search`.'), ('read_skill', 'Before writing prose that ships with the work -- a docstring, a comment, a README, a\n commit message, a PR description, a message to a colleague -- read the `write_docs`\n skill. For narrative writing read `write_prose`, and for the design a codebase is\n derived from, `theory`.'), (None, 'Before bulk work on an uncertain task, state the question, the smallest experiment that answers\n it, and what counts as success; run one pilot first, and report “it ran” apart from “the output is right”.'), ('git_status', 'Git goes through its tools: `git_status`, `git_diff`, `git_log`, `git_divergence` to look;\n `git_commit`, `git_checkout`, `git_stash`, `git_remote`, `git_sync`, `git_conflicts` to act, each returning an `undo` token.\n Merge or rebase with `git_sync`, not `run_shell`; settle conflicts with `git_conflicts`; `git_status` shows the plan.\n `run_shell` refuses `git commit|push|pull|fetch|stash|switch|checkout|merge|rebase`.'), ('run_shell', 'This kernel, the project venv and bare `python` can be three interpreters; "On this\n machine" above lists them, and `run_shell` needs the one you mean.'), ('delegate_search', 'A sub-agent’s report is a hypothesis until a tool result of your own confirms the facts your\n next step rests on. Verify those and only those.'), ('delegate_search', 'When two or more questions are independent and each would take several tool calls,\n pass them together as `questions` rather than working through them yourself.'), ('screenshot', {True: 'A picture a tool returns (`screenshot`, `view_file` on an image) arrives as an image right after\n the tool results; look at it directly. A resumed conversation replays its path, not the picture,\n so call the tool again to see it.', False: 'This model cannot see pictures, so `screenshot` and `view_file` on an image give a path. To look at\n one, call `delegate_search(questions, images=[path])`. If that is refused because the sub-agent\n model cannot see pictures either, say so and read the page with `page_text` instead.'}), ('watch', "`watch(target, kind='folder', instructions=…)` is for work happening beside this conversation:\n another agent editing the repo, a build writing output. `instructions` are the whole brief the\n reviewer gets, so write them self-contained; `pattern` narrows the files. Reviews arrive at the\n start of a later turn; `list_watches` shows what is watched."), (None, 'Make the change the user asked for and no other. Do not reformat, reorganise, or\n “improve” code you were not asked to touch, and never discard their edits.'), (None, 'Writes may be put to the user for approval. A refusal comes back with their reason --\n read it and change the approach, do not retry the same call.'), (None, 'Write, edit and run only inside the folders above. Anything else is refused.'), (None, 'Report what you did, what you found and what it cost, and cut what the reader does not need.'), (None, 'Answer in plain sentences. Headings, bullet lists and bold belong in a document the\n user asked for, not in a reply, and a code fence holds code rather than prose.')),
pictures:bool=True
):The briefing’s rules, keeping those whose tool is offered. Empty names keeps every rule.
learned_context
def learned_context(
learned, mx:int=8000, dated:int=4000
):<learned>/AGENTS.md, then its dated lessons, as briefing blocks, or ’’ when learned is None or holds none.
dated_lessons
def dated_lessons(
learned, mx:int=4000
):The dhrona-<date>.md files in learned, newest first, each whole; the list ends at the first file that would pass mx.
project_context
def project_context(
host, mx:int=8000, cfg:NoneType=None
):The user’s <cfg>/AGENTS.md, then each open folder’s CONTEXT_FILES, as agent instructions.
project_context reads the instructions a project gives any agent: <cfg>/AGENTS.md first, then each open folder’s AGENTS.md, CLAUDE.md and the other CONTEXT_FILES, each clipped to MAX_CONTEXT_FILE characters. A repository is briefed with no configuration at all. learned_context adds the lessons the dhrona package kept from earlier sessions: the learned folder’s AGENTS.md, then its dhrona-<date>.md files, newest first. The dated files share a budget of DATED_CONTEXT characters. The list ends at the first file that would pass it, and no file is cut in the middle. The test shows where they go. They come after the rules, which they override, and before the project instructions, which override them.
print(project_context(MemHost({'/proj/AGENTS.md': '# House rules\n\nDense lines. Short names.\n'}))[:200])got = project_context(MemHost({'/proj/AGENTS.md': '# House rules\n\nDense lines. Short names.\n'}))
assert 'Dense lines.' in got and '<project_context>' in got
test_eq(project_context(MemHost({})), '')
big = project_context(MemHost({'/proj/AGENTS.md': 'x' * (MAX_CONTEXT_FILE * 3)}))
assert len(big) < MAX_CONTEXT_FILE * 2, len(big)
import tempfile
ld = Path(tempfile.mkdtemp())
test_eq(learned_context(ld), '')
(ld/'AGENTS.md').write_text('Run the notebook before exporting.\n')
sp = system_prompt(MemHost({'/proj/AGENTS.md': 'House rules.\n'}), learned=ld)
assert sp.index('How to work:') < sp.index('Run the notebook before exporting.') < sp.index('House rules.') # after the rules it outranks, before the instructions that outrank it
assert 'Run the notebook' not in system_prompt(MemHost({}))
(ld/'dhrona-2026-10-01.md').write_text('# 1 Oct\nOLD-NOTE\n')
(ld/'dhrona-2026-10-02.md').write_text('# 2 Oct\nNEW-NOTE\n')
notes = learned_context(ld)
assert notes.index('Run the notebook') < notes.index('NEW-NOTE') < notes.index('OLD-NOTE') # dated lessons come after AGENTS.md, newest first
notes'\n\n<learned path="/tmp/tmpxoy78shb/AGENTS.md">\nLessons a tool kept from earlier sessions. They override the general guidance\nabove where they disagree. Project instructions and every note after them override these.\n\nRun the notebook before exporting.\n</learned>\n\n<learned_dated path="/tmp/tmpxoy78shb">\nDated lessons from earlier sessions, newest first. They carry the same weight as the lessons above.\n\n# 2 Oct\nNEW-NOTE\n\n# 1 Oct\nOLD-NOTE\n</learned_dated>'
work_rules returns the rules as a bulleted list. Given the names of the offered tools, it leaves out the rules about tools that are not offered. A smaller tool set gives a shorter list. Rules that name no tool always stay. With no names, every rule stays.
print(work_rules()[:280])whole = work_rules()
assert len(work_rules(('evidence',))) < len(whole)
assert len(work_rules(())) <= len(whole)A host that offers own_python gets one more rule. It says that run_python keeps the user’s namespace and the project’s packages, and that the agent’s own packages import in own_python. A host without the tool never hears of it.
assert 'own_python' not in work_rules({'run_python'}) # no own kernel, no word of one
own_rule = work_rules({'run_python', 'own_python'})
assert '`own_python`' in own_rule and 'rupaka' in own_rule and 'user’s kernel namespace' in own_rule # run_python keeps the user's namespace
assert '`own_python`' in work_rules({'own_python'}, SMALL_RULES)sp = system_prompt(host)
print(sp[:320])The briefing lists the open folders. A path outside them is refused, and the model needs to know which folders are open. With no folder open, the briefing says (no folder open).
test_eq('/proj' in sp, True)
len(sp)test_eq(inline_for(INLINE_SKILLS, {'view_file', 'replace_text'}), ()) # exhash teaches `edit_file`; without it nothing is inlined
test_eq(inline_for(INLINE_SKILLS, {'view_file', 'edit_file'}), INLINE_SKILLS)
test_eq(inline_for(INLINE_SKILLS, set()), INLINE_SKILLS)
h = MemHost({'/proj/a.py': 'x = 1\n'})
sp = system_prompt(h, tools=tools_for(h))
assert '`environment`' not in sp and '`edit_file`' not in sp and 'exhash' not in sp
assert 'inspect_python()' in work_rules() and '`list_vars`' not in work_rules()
assert '`edit_file`' in work_rules({'edit_file', 'view_file'}) and '`edit_file`' not in work_rules({'view_file'})Each model family gets a few notes on top of the rules. MODEL_NOTES maps claude, gpt and gemini to CLAUDE_NOTES, GPT_NOTES and GEMINI_NOTES. The key default maps to no notes. model_family picks the key from the turn model’s spec. The agent passes the notes as extra, and system_prompt appends extra last. CLAUDE_NOTES holds Answer.AI house behaviours from aai-coding that the rules do not cover: what belongs to the user (the environment and the git history), how far an approval reaches, and how a turn ends.
model_family
def model_family(
spec
):The MODEL_NOTES key for a turn spec: claude, gpt, gemini or default.
test_eq(CLAUDE_NOTES in system_prompt(host, extra=CLAUDE_NOTES), True)
test_eq(CLAUDE_NOTES in system_prompt(host), False)The session plan
The session plan is the checklist the model keeps of what it is doing: a title and a list of todos, each pending, active, done or cancelled, with at most one active. It is saved beside the history, so it survives a stopped turn and a restart. While it has todos it appears in every briefing, so after a stop the model continues from the active item. It lives on the Agent rather than the host, so the terminal, the MCP server and Leela (a notebook editor) all read the same object.
Plan holds the list and Todo is one item of that list. Plan.update changes a todo found by id, unique id prefix or unique text, and marking one todo active moves any other active todo back to pending.
plan_tools
def plan_tools(
get_plan, # returns the plan the tools change
save:NoneType=None, # called with no arguments after each change
check:function=evidence_problem, # `check(evidence)` gives why evidence cannot close a step, or ''
):Model-facing set_plan and update_todo tools over the agent’s Plan.
Plan
def Plan(
title:str='', todos:NoneType=None, updated:float=0.0, requests:tuple=(), files:tuple=(), commits:tuple=()
):The session’s checklist of steps, with a status for each step, and the ledger kept beside it: the user’s requests, the files changed and the commits made.
Request
def Request(
id:str, text:str, status:str='open', turn:str=''
)->None:One request from the user, word for word, with its status.
Todo
def Todo(
id:str, text:str, status:str='pending', note:str='', owner:str='', evidence:str=''
)->None:One step on a session plan.
evidence_problem
def evidence_problem(
text, host:NoneType=None
):Why text cannot close a step, as one plain line, or ’’. With a host, a sha must name a commit in its repository and a path must exist in its folders; a command and its result are checked by shape only.
is_evidence
def is_evidence(
text
):Whether text has the shape of evidence: a commit sha, a command and its result, or a file path.
A model sends a list of steps as a JSON array, as one step per line, or as a Python list. parse_plan_items accepts all three forms. It lives in ramabana.tools. delegate_search reads its questions argument the same way.
parse_plan_items('["Cut shalya", "Rewire ramabana"]'), parse_plan_items('one\ntwo')test_eq(parse_plan_items('["a", "b"]'), ['a', 'b'])
test_eq(parse_plan_items('one\ntwo'), ['one', 'two'])
test_eq(parse_plan_items(['a', 'b']), ['a', 'b'])
test_eq(parse_plan_items(''), [])
test_eq(parse_plan_items(' spaced '), ['spaced'])plan_tools returns two tools over the plan:
set_plan(items)replaces the steps and keeps any title the person set with/plan. An empty list clears the plan. A step whose text is already on the plan keeps its status and its evidence.update_todochanges one step’s status, text or evidence by id or unique prefix, or appends a step when no id is given. It refuses to mark a stepdonewithoutevidence, and says why in one line. Given a request id from the session ledger, such asr2, it sets the status of that request.
No tool reads the plan. The plan is in the briefing, and the tools return it. plan_tools takes a function that returns the plan and an optional save function. The caller decides where the plan lives. save takes no arguments. An error inside save is ignored, and a failed write never ends a turn.
held = Plan('Ship the split', ['Cut shalya', 'Rewire ramabana'])
saves = []
pt = {t.__name__: t for t in plan_tools(lambda: held, save=lambda: saves.append(held.md()))}
sorted(pt)pt['update_todo'](text='Migrate leela')
test_eq(len(held.todos), 3)
assert failed(pt['update_todo'](held.todos[0].id, 'done')), 'done needs evidence'
test_eq(held.todos[0].status, 'pending')
pt['update_todo'](held.todos[0].id, 'done', evidence='pytest -q tests: 41 passed')
test_eq((held.todos[0].status, held.todos[0].evidence), ('done', 'pytest -q tests: 41 passed'))
assert failed(pt['update_todo']('no-such-id', 'done', evidence='3f2a9c1'))
assert failed(pt['update_todo']())
assert saves, 'every change is handed to the saver'
pt['set_plan']([held.todos[0].text, 'only step'])
test_eq([t.status for t in held.todos], ['done', 'pending'])
pt['set_plan']([])
test_eq(held.todos, [])
pt['set_plan'](['fresh'])
test_eq([t.text for t in held.todos], ['fresh'])
test_eq(get_schema(pt['set_plan'])['input_schema']['properties']['items']['type'], 'array')
broken = {t.__name__: t for t in plan_tools(lambda: held, save=lambda: 1/0)}
assert 'still works' in broken['set_plan'](['still works'])The session ledger
A long session can lose track of its work. Compaction can drop the user’s words, and a plan can show every step done when nothing was checked. The ledger keeps the facts that must survive. The agent writes it while the work happens, not at compaction time. It lives in the plan file, <cfg>/agent-plans/<session>.json, so there is one store. A plan file from before the ledger loads with no requests, files or evidence.
The ledger holds four things:
- Each request from the user, word for word up to
REQUEST_CHARScharacters, with a status:open,agreed,doneordeclined.askrecords a request asopen. A bare approval such as “go” marks the newest open requestagreedand records nothing new. A one-key shortcut and a background wake prompt record nothing. - The plan steps, each with the evidence that closed it.
- The files that each turn changed, from the same data as the turn’s file checkpoint.
- The commits that the turn’s git tools made.
is_evidence decides what can close a step: a commit sha, a command with its result, or a file or screenshot path. Plain words such as “full suite green” are not evidence:
test_eq([is_evidence(e) for e in ('3f2a9c1', 'pytest -q tests: 312 passed', 'shots/handout.png', 'nbs/01_runtime.ipynb')], [True]*4)
test_eq([is_evidence(e) for e in ('', 'done', 'full suite green', '1234567')], [False]*4)evidence_problem goes one step further, and update_todo in an agent uses it. Given the session host, it looks up a sha with git cat-file -e in the repository of the open folders, and it looks for a relative path in the open folders. An absolute path counts when it exists anywhere on disk, such as a screenshot under /tmp; it is never read. A test command and its result are checked by shape only. A refusal is one line that names what failed:
mem = MemHost({'/proj/shots/handout.png': ''})
test_eq([evidence_problem(e, mem) for e in ('shots/handout.png', 'pytest -q: 3 passed')], ['', ''])
assert 'shots/missing.png was not found' in evidence_problem('shots/missing.png', mem)
assert 'no Git repository' in evidence_problem('3f2a9c1', mem), 'a memory host has no repository'
test_eq(evidence_problem('full suite green', mem), EVIDENCE_NEEDED)
with tempfile.NamedTemporaryFile(suffix='.png') as shot: test_eq(evidence_problem(shot.name, mem), '')
assert 'was not found' in evidence_problem('/tmp/no-such-shot-7f3.png', mem)ledger renders the record as markdown. Steps are sorted by their honest state: done with evidence, marked done with no evidence, and open. The ### Done heading lists only steps with evidence, so done_items reads only checked work. Here a plan from an old file has one step marked done with no evidence, and the user asks, approves and asks again:
old = Plan.from_dict({'title': '', 'todos': [{'id': 'h7', 'text': 'Step 7: handout', 'status': 'done'},
{'id': 's8', 'text': 'Step 8: walk', 'status': 'done', 'evidence': '9c41e2d'}]})
old.ask('Build the handout with an Answers panel', turn='t1')
old.ask('go'); old.ask('.')
old.ask('Then add folder links')
old.touched(['nbs/handout.ipynb'], ['9c41e2d Add the handout'])
print(old.ledger())These checks show that an approval agrees the open request, that only checked work is under ### Done, that a file is listed once, that the ledger is the same after a save and a load, and that update_todo sets the status of a request.
test_eq([(r.id, r.status) for r in old.requests], [('r1', 'agreed'), ('r2', 'open')])
led = old.ledger()
assert done_items(led).count('`s8`') == 1 and '`h7`' not in done_items(led), 'only a step with evidence is under Done'
assert '`h7` Step 7: handout -- not checked' in led
assert not old.touched(['nbs/handout.ipynb']), 'a file is listed once'
test_eq(Plan.from_dict(old.dict()).ledger(), led)
ot = {t.__name__: t for t in plan_tools(lambda: old)}
assert '`r2` [done]' in ot['update_todo']('r2', 'done')
assert failed(ot['update_todo']('r2', 'finished'))
assert len(Plan().ask('x' * 5000).text) == REQUEST_CHARS + 1The agent
One Agent holds one continuous model conversation. Building one is cheap, and no model loads until the first turn. An agent also holds:
- routing, which model each job runs on (see core);
- tools, skills and extensions;
- the approval gate and compaction;
- the activity feed, the plan and the history on disk.
A job is one kind of model work. turn is the main conversation; oneshot, inline, completion, classify, summary and subagent are short jobs that can run on other, cheaper models. A missing model is reported, not raised. The model may be a download of several gigabytes or need an API key. An editor must still open without either. ready and note say whether the turn model is up, and why not.
The main constructor options:
approvals, anApprovalsgate, or None for no gate;cfg, the config folder for history, plans, skills and extensions; None keeps nothing on disk;subagent_writes, on by default: sub-agents get write tools, behind the same gate;readonly, which withholds every tool that acts;max_cost,max_tokens,session_max_costandsession_max_tokens, budgets that stop a turn;keep_conversation, which saves the whole conversation each turn for a full resume;profile:auto,smallorfull, described below.
Agent
def Agent(
host, model:NoneType=None, # turn model; None takes the routing default
routing:NoneType=None, sp:NoneType=None, # override the whole briefing
extra_sp:str='', # text added after the briefing, which stays
global_skills:bool=True, # read skills from `~/.agents/skills` too
drop_tools:NoneType=None, # tool names left out of the model's schema; None reads config.toml's `drop_tools`, else keeps every tool
approvals:NoneType=None, # an `Approvals`; None gates nothing
cfg:NoneType=None, # config dir, for skills and extensions
compact:NoneType=None, # compact automatically at the threshold; None reads config.toml's `compaction.auto`, else True
compact_strategy:NoneType=None, # 'digest', 'surgical' or 'summary'; None reads `compaction.strategy`, else 'digest'
kernel_alive:bool=True, # what the post-compaction note may promise
extensions:bool=True, project_extensions:bool=False, # project extensions run code from the repo; True opts in
ext_paths:tuple=(), mods:NoneType=None, # names of the only mods to load; None loads every mod
vesha:str='', # the vesha this session runs in, for `/vesha` and `status`
inline_skills:tuple=('exhash',), subagents:bool=True,
subagent_writes:bool=True, # sub-agents get write tools, behind the same approvals
subagent_grants:NoneType=None, # the `SUB_GRANTS` tools sub-agents may have; None reads config.toml's `subagents.grants`, else none
subagent_steps:str='auto', # 'auto' lets a delegation ask for up to `SUB_STEP_CEILING` steps; a number caps every delegation's `max_steps`
subagent_timeout:int=1800, # seconds before a delegation is stopped; 0 never
subagent_depth:int=2, # levels of sub-agents that may delegate again, at most `SUB_DEPTH_MAX`
readonly:bool=False, # withhold every tool that acts
readonly_calls:NoneType=None, # hard cap on read-only calls, when set
max_cost:NoneType=None, # dollars the turn model may spend in one turn; None has no limit, and a local model reports none
max_tokens:NoneType=None, # tokens the turn model may spend in one turn; None has no limit
session_max_cost:NoneType=None, # dollars the whole session may spend, earlier turns included
session_max_tokens:NoneType=None, # tokens the whole session may spend, earlier turns included
est_rate:NoneType=None, # dollars a token costs when a model reports no cost: a number, or a callable given the `ModelSpec`; None takes `token_rate`
only_tools:NoneType=None, # the names of the only tools the model is offered, tools `add_tool` adds later included; None offers every tool, [] none; `add_tool` refuses any other name, and an `ask` with a `schema` needs `submit_result` named
local_multimodal:bool=False, # load LiteRT vision/audio encoders for local models
tool_max_len:NoneType=None, # None scales the result cap to the model window
on_compact:NoneType=None, on_activity:NoneType=None,
history_name:str='agent', # names this durable conversation in the config dir
session_id:NoneType=None, # this session's id, for a host that keeps its own; None makes a new one
keep_conversation:bool=False, # save the turn model's whole conversation each turn, for `resume_session(full=True)`
poll_every:int=900, # seconds between automatic watch polls; 0 never polls
verify:str='', # the project's check; empty reads `[tool.ramabana] verify`
instruction_style:str='ramabana', # 'ramabana' | 'aai' compatibility profile
optin:tuple=(), # shalya's opt-in tool groups, see `OPTIN`
profile:str='auto', # 'auto', 'small' or 'full'; see `profile_for`
warm:NoneType=None, # seed with dhrona's examples; None is off
learned:bool=True, # brief from `<cfg>/learned`; False runs without it
fresh_hint:NoneType=None, # what a turn too large for any window tells the user to do, `{session}` its id; None suits any host
auto_turns:NoneType=None, # 'on', 'report' or 'off': whether finished background work starts a turn; None reads `auto_turns`, else `on` under `edits`/`auto` approvals and `report` otherwise
auto_turns_per_hour:NoneType=None, # most automatic turns an hour; None reads `auto_turns_per_hour`, else 6
):One model conversation on a host, with its tools, approvals, activity feed, plan and history.
__init__ calls these properties, directly or through each other. They are patched in before any agent is built. Their examples come later, after the harness that builds a demo agent. The rest of the class follows in reading order, not definition order.
Agent.history_path
def history_path():<cfg>/<history_name>-history.jsonl, the turn log, or None without a config dir.
Agent.spec_or_none
def spec_or_none(
job:str='turn'
):job’s model spec, or None when its name does not resolve to one.
Agent.profile
def profile():small or full: how the turn model is briefed. See core.profile_for.
profile decides how much the turn model is told. With profile='auto', a local model, or a model whose window is 32k tokens or less, gets the small briefing and tool set. A cloud model with a larger window gets full. Passing small or full overrides this. budget says how many characters of tool schemas and results the model can afford, and which tool groups to drop. See budget_for in core. fake_agent fixes the profile at full. Its fake model has a 1k window, and every test below exercises the full path.
from ramabana.core import ModelSpec, SMALL_TOOLS
from ramabana.agent import Agent as _Agent # the installed class; this page's `Agent` is unfinished
_local, _big = ModelSpec('gemma-e4b', 'litert', 'litert-community/x', 16_384), ModelSpec('sonnet', 'remote', 'claude-sonnet-4-5', 200_000)
def _on(spec, **kw):
a = _Agent(MemHost({'/proj/a.py': 'x = 1\n'}), extensions=False, **kw)
a.routing.spec = lambda job='turn', fallback=True: spec
return a
test_eq((_on(_local).profile, _on(_big).profile, _on(_local, profile='full').profile, _on(_big, profile='small').profile), ('small', 'full', 'full', 'small'))
test_eq(fake_agent()[0].profile, 'full')
test_fail(lambda: _Agent(MemHost(), profile='tiny'), contains='profile')
_h = MemHost({'/proj/a.py': 'x = 1\n'})
test_eq((_on(_local).warm, _on(_big).warm, _on(_local, warm=True).warm, _on(_big, warm=True).warm), (False, False, True, True))Agent.registry
def registry():The extension registry, built once. The object outlives a reload, which re-reads only the extension files. With mods, every other mod is listed off and its code does not run.
A mod changes what a turn does through the registry. The engine honours what a before_turn hook returns, lets a mod add context with inject and ask the person with ask_user, collects the status segments in mod_status, and switches mods with /mods and /vesha. The section Mods in a turn runs them.
Agent.vesha_command
def vesha_command(
arg:str=''
):/vesha: the veshas, the current one marked. /vesha NAME switches the mods to that vesha’s.
Agent.mods_command
def mods_command(
arg:str=''
):/mods: one aligned line per mod with on or off and its note, then the notes no mod made. off NAME and on NAME switch one.
Agent.mod_status
def mod_status():What the mods’ status segments return now; a segment that returns nothing is left out.
Agent.ask_user
def ask_user(
title, preview, timeout:NoneType=None
):Put a question to the person through the approval gate and return the resolved Ask. No mode, saved rule or policy answers it, and with nobody listening it is refused.
Agent.inject_notice
def inject_notice():The context queued since it was last taken, as <mod-context> blocks for a tool result, or ’’. What it takes joins this turn’s row.
Agent.inject
def inject(
text
):Add text as context to the root turn’s next model request, or to the next turn when none runs, naming the mod that calls.
mod_context
def mod_context(
entries
):Context mods added, one <mod-context> block each, naming the mod when it is known.
TurnRefused
def TurnRefused(
*args, **kwargs
):A before_turn hook refused the turn; the message is its reason.
Agent.skills
def skills():Every discovered skill, found once. Includes anything an extension registered.
Agent.learned_dir
def learned_dir():<cfg>/learned, or None without a config dir or with learning off.
Agent.learning
def learning():Whether learning is on. It needs learned true and, with a config dir, this machine’s learning setting on.
Agent.warm_backend
def warm_backend(
job:str='turn'
):Start the backend job routes to and return it, or None with the reason in routing.notes[job]. It sends no prompt, so it costs nothing.
Agent.sub_effort_level
def sub_effort_level(
effort:str=''
):The effort level for a sub-agent. The first value set wins: effort, the session’s /subagents effort, $SUBAGENT_EFFORT, then [subagents] effort. ’’ leaves the model’s default.
A delegation can name the sub-agent model without its provider prefix, such as gpt-6-sol for openai/gpt-6-sol. The name then means the sub-agent model. Any other name that does not resolve gives no backend from _cloud_backend_or_none, and _named_backend raises AgentError for it.
ca, cbe = fake_agent()
ca.routing.policy['subagent'] = 'openai/gpt-6-sol'
assert ca._cloud_backend_or_none('gpt-6-sol') is cbe
assert ca._cloud_backend_or_none('gpt-6-typo') is NoneGit writes go through git tools, never the shell. When the session offers the git tool, run_shell refuses the seven subcommands that have one (commit, push, pull, fetch, stash, switch, checkout) and names the tool to use. git_shell_denial finds them in each of these places:
- anywhere in a
&&,;or|chain, split after quoting. A quotedgit commitinside anechois only text; - after any
NAME=valueprefix, or a git option such as-C; - behind one
env,xargs,nohup,time,command,execornicewrapper, or inside ash -c "..."line.
gheasy’s classify decides what counts as a read. git stash list runs, and git stash is refused. A git tool returns an undo token. The agent keeps the token, and /rewind uses it to undo the write.
_guard applies this rule and three more before any call runs. shell_denial refuses a shell line that hides its own output with | head, | tail or 2>&1, and, through env_denial, a line that prints environment values, which is where API keys live: printenv in any form, env with no command to run, a bare set or export, export -p, declare -x or declare -p, any read of /proc/*/environ, and cat, less, more, head, tail, grep, tac, nl or strings of a .env file (not of a template such as .env.example). It looks through sudo, nice, timeout, xargs and the like, through $( ) and sh -c. The refusal tells the model to ask whether one variable is set instead. It is a best-effort first layer: backticks, eval, a script that prints os.environ and many other routes get past it, and the read guard below, which masks key shapes in whatever a command prints, is what stops a key whatever the route. generated_denial refuses a write that hand-edits a module nbdev generated from a notebook, and secret_denial refuses a write that would put the [SECRET] mask over a real key. shell_denial applies to run_shell and run_shell_bg. The git rule applies to run_shell only.
git_shell_denial
def git_shell_denial(
command, tools:NoneType=None
):Why run_shell refuses this git write, or ’’ when it may run or tools lacks the tool.
A key the reads masked must not come back as a write. mask_secrets replaces every API key and token shape with [SECRET], and the read guard (see What a read may send) applies it to everything a tool returns. A model that reads TOKEN = "[SECRET]" and writes that line back would replace the real key with the mask, so secret_denial refuses a write whose arguments hold [SECRET] to a file that holds a real key. A file that only mentions the label, such as this notebook, can still be edited.
The shapes are rahasya’s secret kind (OpenAI and Anthropic sk- keys, GitHub ghp_, Slack xox, AWS AKIA and Google AIza), and these documented prefixes rahasya does not know: GitHub’s github_pat_, gho_, ghu_, ghs_ and ghr_, Stripe’s sk_live_, sk_test_ and rk_live_, Hugging Face hf_, GitLab glpat-, npm npm_, PyPI pypi-, AWS temporary ASIA keys, and PEM and PGP private keys, masked to the end of the text when a read cuts one off before its END line. Hetzner and Cloudflare API tokens are random strings with no fixed prefix, so no pattern can tell them from any other long identifier, and none is guessed. rahasya arrives with the search extra; without it, ramabana masks rahasya’s shapes from its own copy, RAHASYA_SECRETS.
secret_denial
def secret_denial(
host, name, args
):Why a write would put [SECRET], the reads’ mask, over a real key in a file, or ’’.
mask_secrets
def mask_secrets(
text
):text with every API key, token and private key replaced by [SECRET], the label rahasya’s redact writes.
Agent.peer_denial
def peer_denial(
name, args
):Why a write would change a folder that another live session holds and this one does not, or ’’.
generated_denial
def generated_denial(
host, name, args
):Why a write would hand-edit an nbdev-generated module, or ’’.
shell_denial
def shell_denial(
command
):Why a shell line hides its own output or prints environment values, or ’’. Quoted text never matches. A sh -c line is checked too.
env_denial
def env_denial(
command
):Why a shell line prints environment values, which hold API keys, or ’’. Quoted text never matches. A sh -c line is checked too.
A tool can name arguments that must never be kept, such as the reference answer of an exercise: f.secret_args = ('solution',). The tool gets the real value. calls, the activity rows, approval asks, events, the turn log and the saved conversation keep [SECRET] in its place. The live conversation keeps what the model wrote.
def _quiz(task, solution=''): return solution
_quiz.secret_args = ('solution',)
qa, _ = fake_agent()
test_eq(qa._record(_quiz)(task='t', solution='42'), '42')
test_eq(qa.calls, [('_quiz', {'task': 't', 'solution': '[SECRET]'})])for cmd, tool in [('git commit -m x', 'git_commit'), ('git -C /p commit -am y', 'git_commit'), ('git status && git commit -m x', 'git_commit'),
('git push origin main', 'git_remote'), ('GIT_TERMINAL_PROMPT=0 git pull', 'git_remote'), ('git stash', 'git_stash'),
('git switch -c f', 'git_checkout'), ('/usr/bin/git checkout -- a.py', 'git_checkout'), ('ls | git fetch --all', 'git_remote'),
('bash -c "git commit -m x"', 'git_commit'), ("sh -c 'cd /p && git push'", 'git_remote'), ('env GIT_TERMINAL_PROMPT=0 git pull', 'git_remote'),
('git diff --name-only | xargs git commit -m x', 'git_commit'), ('nohup git fetch', 'git_remote'), ('bash -lc "git switch main"', 'git_checkout'),
('git rebase main', 'git_sync'), ('git rebase -i main', 'git_sync'), ('git merge topic', 'git_sync'), ('git -C /p merge --no-ff topic', 'git_sync')]:
assert f'`{tool}`' in git_shell_denial(cmd), cmd
for cmd in ['git log --grep=commit', 'git stash list', 'git status', 'git diff HEAD~1', 'echo "git commit" > notes.txt', 'ls', 'git merge-base main topic', '', 'git -c core.pager=cat log',
'echo "a; git commit -m y"', "echo 'git push' | tee notes.txt", 'bash -c "git log"', 'env | grep GIT']:
test_eq(git_shell_denial(cmd), '')
import subprocess, tempfile
from shalya.host import LocalHost
repo = Path(tempfile.mkdtemp())/'repo'; repo.mkdir()
subprocess.run(['git', 'init', '-q', str(repo)], check=True)
denied_agent, _ = fake_agent(host=LocalHost([str(repo)], index=False))
shell = next(t for t in denied_agent.tools if t.__name__ == 'run_shell')
out = shell('git commit -m x'); assert failed(out) and '`git_commit`' in out
test_eq(denied_agent.activity.rows()[-1]['ok'], False)
plain_agent, _ = fake_agent()
test_eq(plain_agent._deny_git_shell('run_shell', {'command': 'git commit -m x'}), '')env_denial('printenv OPENAI_API_KEY'), env_denial('env -u TMUX pytest -q')An approval request is not a tool call, and the tool wrapper never sees it. The agent hooks its Approvals instead. An ask put to a person adds one activity row the moment it is raised, with kind ask, state awaiting and its ask_id. The answer finishes that row. A refusal leaves ok False, with the reason the model was told as detail, and writes a line to the run’s transcript. An approval leaves ok True, and the call that follows gets its own row as usual. A refusal nobody was asked about, from a saved rule or the mode, still gets a row.
import tempfile
from pathlib import Path
from ramabana.runtime import Run, run_context
gated, _ = fake_agent()
gated.approvals = Approvals(tools=WRITE_TOOLS)
stop = gated.approvals.listen(on_ask=lambda a: threading.Timer(0.02, gated.approvals.answer, (a.id, False, 'not that file')).start())
with tempfile.TemporaryDirectory() as d:
with run_context(Run('run_t', question='q', log=Path(d)/'run_t.log')):
refused = gated.approvals.request('edit_file', {'path': 'a.py'})
log = (Path(d)/'run_t.log').read_text()
rows = gated.activity.rows()
test_eq(len(rows), 1)
test_eq({k: rows[0][k] for k in ('tool', 'args', 'ok', 'kind', 'detail')},
{'tool': 'edit_file', 'args': {'path': 'a.py'}, 'ok': False, 'kind': 'ask', 'detail': refused.reply()})
assert 'not that file' in refused.reply()
assert refused.reply() in log
stop()
gated.approvals.listen(on_ask=lambda a: gated.approvals.answer(a.id, True))
assert gated.approvals.request('edit_file', {'path': 'a.py'})
rows = gated.activity.rows()
test_eq(len(rows), 2)
test_eq((rows[-1]['kind'], rows[-1]['ok'], bool(rows[-1]['ask_id'])), ('ask', True, True))A before_tool extension hook may rewrite the arguments of a call. A rewritten write goes back through the gate with its new arguments. A refusal there is still one row.
hooked, _ = fake_agent()
hooked.approvals = Approvals(tools=WRITE_TOOLS)
hooked.approvals.listen(on_ask=lambda a: hooked.approvals.answer(a.id, False, 'not b.py either'))
hooked.registry.on('before_tool', lambda agent, name, args: dict(args, path='b.py'))
edit = next(t for t in hooked.tools if t.__name__ == 'replace_text')
out = edit(path='a.py', edits=[])
assert 'not b.py either' in out
test_eq(len(hooked.activity.rows()), 1)
test_eq(hooked.approvals.history[0].args, {'path': 'b.py', 'edits': []})
test_eq(hooked.activity.rows()[0]['args']['path'], 'b.py')In urai’s real tool loop, the model receives Ask.reply() as the tool result, and the refused tool never runs. This cell guards the uraiyadal>=0.0.8 pin. That is the first version that passes on the reply() of a refused approval.
from urai import Chat, ToolCall
from urai.opts import ChatOpts
from urai.core import Resp
from urai.loop import ToolLoopMixin
class _ScriptChat(ToolLoopMixin, Chat):
"urai's loop over a fixed list of replies, and no model."
_runtime, ctx_limit, token_count = 'script', 8192, 0
def __init__(self, model=None, *, script=(), **kw):
self.script, self.steps = list(script), 0
self._setup(model, ChatOpts.create(kw.pop('opts', None), **kw)); self._set_tools(self.tools)
def _model_step(self, **kw):
r = self.script[min(self.steps, len(self.script) - 1)]; self.steps += 1
return Resp({'role': 'assistant', 'usage': {'total_tokens': 10}, **r})
loop_gate = Approvals(tools=WRITE_TOOLS)
loop_gate.listen(on_ask=lambda a: loop_gate.answer(a.id, False, 'no answer after 300s'))
called = []
def edit_file(path: str) -> str:
"Edit a file."
called.append(path); return 'edited'
c = _ScriptChat('script-1', script=[{'content': '', 'tool_calls': [dict(ToolCall('edit_file', {'path': 'a.py'}))]}, {'content': 'ok'}],
tools=[edit_file], approve=loop_gate.gate)
c('go')
told = [m['content'] for m in c.hist if m['role'] == 'tool']
test_eq((len(told), 'no answer after 300s' in told[0]), (1, True))
test_eq(called, [])Agent.plan_path
def plan_path():The plan file of this session, beside the history log, or None without a config dir.
Agent.catalog
def catalog():The foreground policy view used by the model, approvals, activity and frontends.
sa, _ = fake_agent(subagent_writes=True)
assert PLAN_TOOLS <= {t.__name__ for t in sa.tools}
assert not ROOT_ONLY & {t.__name__ for t in sa._sub_plain()}
pt = sorted(PLAN_TOOLS)[0] # in every build, unlike the memory tools, which need the search extra
assert pt in {t.__name__ for t in sa.tools}, 'with no `drop_tools`, every tool stays'
assert pt not in {t.__name__ for t in fake_agent(drop_tools={pt})[0].tools}, '`drop_tools` names leave the schema'
assert pt in {t.__name__ for t in fake_agent(drop_tools=())[0].tools}, '`drop_tools=()` offers them again'A sub-agent works on one task. By default it gets none of the SUB_GRANTS tools: it cannot send a peer message, write or forget memory, or open a new folder, so its file writes stay inside the session’s folders. A session grants one with subagent_grants, or with subagents.grants in config.toml.
def tell(session:str, text:str):
"Stands in for the peer tool."
return 'told'
ga, _ = fake_agent(subagent_writes=True)
ga.add_tool(tell)
names = {t.__name__ for t in ga._sub_plain()}
assert {'tell', 'add_root', 'remember'} <= {t.__name__ for t in ga.tools} and not SUB_GRANTS & names
assert {'create_file', 'replace_text', 'run_shell'} <= names, 'a writer keeps its write tools'
gb, _ = fake_agent(subagent_writes=True, subagent_grants={'tell'})
gb.add_tool(tell)
test_eq(SUB_GRANTS & {t.__name__ for t in gb._sub_plain()}, {'tell'})A sub-agent is a second model conversation that the agent starts to work on one question. It has its own tools and step limit. Its answer comes back as a tool result. delegate_search waits for the answer. delegate_async starts the sub-agent in the background and returns at once. delegate_result collects the answer later. background is where those background runs live. Each agent builds one on first use and closes it with the session. Nothing keeps running after the last turn. A finished answer rides on the next tool result of the running turn, so the model needs no polling. When no tool runs before the turn ends, background_notice adds it to the next prompt instead.
Agent.wake_prompt
def wake_prompt():The prompt that continues after background work finished. Returns ’’ when no finished run is left to act on, when the mode is off, or when the hourly cap is spent. _bg_done stays for background_notice.
Agent.wake_mode
def wake_mode():Whether finished background work starts a turn. Returns on, report or off.
Agent.background_notice
def background_notice():The answers of background delegations since the last turn, as one notice, or ’’.
Agent.shell_done
def shell_done(
rid, command, state, text
):Queue a run_shell_bg command that exited by itself as finished background work. The next turn’s notice carries its output, and an idle terminal wakes for it.
Agent.background
def background():The Background object that holds async delegations. Finished answers wait in _bg_done.
tools is the list the turn model is offered. It holds the host’s tools, extension tools, the memory tool, and the delegation and plan tools, cut to what the budget and profile allow. _record wraps each tool. Its calls reach the activity feed, the change tracking and the guards above. In read-only or plan mode the tools are the read-only view. system_prompt builds this agent’s briefing from the module-level system_prompt. It adds the plan, remembered notes, the model family’s notes and the note about steering.
Agent.tools
def tools():Every tool the turn model can afford, built once and recorded. reload rebuilds it.
Memory is what the agent keeps between sessions. On a host without a memory tool group (no vault), memory is one markdown file per project, at memory_path. The model writes to it with the remember tool that note_tools builds. note_memory adds a line, or replaces the line with the same key. memory_context returns the tail of the file for the briefing and the completer. An application with a vault (see vault) overrides memory_context. The agent calls this method and does not read the file itself.
note_tools
def note_tools(
note, learning:function=<lambda>
):The memory tool for a host without a vault: shalya’s remember, writing to the project’s memory file.
Agent.lessons
def lessons(
limit:int=50
):The lessons remember kept for this project, from the vault or the memory file. Returns an empty list with learning off.
Agent.memory_context
def memory_context(
surface, max_chars:int=4000
):The project’s memory file, or its last max_chars characters when it is long. An embedder with a vault overrides this method.
Agent.note_memory
def note_memory(
text, title:str='', tags:str='', key:str=''
):Write - [key] **title**: text to the project’s memory file. A line with the same key is replaced.
Agent.memory_path
def memory_path():<cfg>/memory/<root hash>/MEMORY.md: this project’s notes, kept without a vault.
lessons returns the lessons remember kept for this project as dicts of lesson, cue, component, evidence and confidence. It reads them with shalya’s lessons, from the vault when the host has one and from the memory file otherwise. Both layouts return the same dicts. Dhrona reads the same lessons from the history.
import tempfile
with tempfile.TemporaryDirectory() as d:
noted, _ = fake_agent(cfg=Path(d))
rem, = note_tools(noted.note_memory)
test_eq(rem.__name__, 'remember')
rem('use uv', key='pkg'); rem('use uv, never pip', key='pkg')
rem('the tests are slow', title='Tests', tags='ci')
body = noted.memory_path.read_text()
test_eq(body.count('[pkg]'), 1)
assert '- [pkg] use uv, never pip' in body and '- **Tests**: the tests are slow' in body
rem('filter on the root-relative path', cue='an empty filtered search', component='tool', confidence='high')
last = noted.memory_path.read_text().splitlines()[-1]
test_eq(dict(f.split(': ', 1) for f in last.removeprefix('- ').split(' | ')),
dict(lesson='filter on the root-relative path', cue='an empty filtered search', component='tool', confidence='high'))
assert rem('x', component='habit').startswith('ERROR:')
rem('two\n\nparagraphs')
test_eq(noted.memory_path.read_text().splitlines()[-1], '- two paragraphs')Agent.last_media
def last_media():Images from the latest turn, the model’s or its tools’, as {'mime','data'} dicts.
Agent.resp_media
def resp_media():Pictures the model itself returned on the newest turn, as {'mime','data'} dicts.
Agent.runs
def runs(
active:bool=False
):Registered root, background and child runs. active drops the ones that have finished.
Agent.run
def run(
run_id:str=''
):Find a registered run, or the foreground root when run_id is empty.
Agent.status_line
def status_line():What the foreground turn’s model last said it was doing, or ’’.
Agent.busy
def busy():Whether a foreground turn is live. Background delegations do not count.
busy is True while a foreground turn, or a sub-agent it started, is still running; background delegations do not count. set_model, resume_session and set_plan_mode refuse to run while it is True.
From here on the examples run a real Agent against a real model’s answers, recorded once into chatcache/ and replayed. A question nobody recorded raises and does not reach a model. This page never calls a model. To add a question, record it on purpose:
URAI_RECORD_CHAT=1 uv run nbdev-test --path nbs/03_agent.ipynbdemo_agent builds the agent on a MemHost, an in-memory host, with a fixed /proj folder. The briefing is part of a recording’s key. A temporary folder would put a new path in the briefing on every run, and no replay would match.
bg = agent.background
test_eq(bg, agent.background)
test_eq(bg.status(), [])
assert bg.result('run_nope')
test_eq(agent.busy, False)system_prompt() on an agent returns its full briefing. The briefing names the open folder, /proj, and the tools on offer.
sp = agent.system_prompt()
len(sp), sp[:120]sp = agent.system_prompt()
assert '/proj' in sp
assert 'search_code' in sptools is built once. The same list comes back until something rebuilds it: refresh, reload, a model change or plan mode.
sorted(t.__name__ for t in agent.tools)names = {t.__name__ for t in agent.tools}
assert {'search_code', 'view_file', 'create_file'} <= names, sorted(names)
assert agent.tools is agent.toolsskills lists every skill found in the skill folders (the index gives the search order), sorted by name, plus any an extension registered. The list is found once and kept.
[s.name for s in agent.skills][:6]assert agent.skills is agent.skillsregistry is the object extensions register on: their tools, commands, notes and hooks. The demo agent loads no extensions, so it is empty.
agent.registry.tools, agent.registry.commands, agent.registry.notesassert agent.registry is agent.registrybudget is what the turn model can afford: which tool groups to drop, whether a skill may be inlined, and how many characters one tool result may take. A model with a small window drops groups. budget names the dropped groups and does not count them. The demo model has a 200k window. Nothing is dropped, and results are capped at 32,000 characters.
agent.budgettest_eq(agent.budget.tool_max, min(32000, max(MAX_TOOL_CHARS, agent.spec_or_none().ctx // 4)))history_path is the log every session with this history_name appends its turns to, and plan_path is the file this session’s plan is saved in. Both sit in the config folder; without one, both are None.
agent.history_path.name, agent.plan_path.nameassert agent.session_id in str(agent.plan_path)
test_eq(demo_agent(cfg=None).history_path, None)chat_or_none returns a job’s live chat only if its backend already exists. A frontend can check it without starting a model. reload discards the skills, tools and extension files it read, and closes every backend. The next turn starts fresh. refresh, below, rebuilds the same things but gives a running backend the new briefing and tools in place. It is safe while a turn runs.
Agent.chat_or_none
def chat_or_none(
job:str='turn'
):job’s live chat if a backend has already been built, without building one to find out.
Agent.reload
def reload():Re-discover skills, extensions and tools, closing every backend. The new turn backend goes on with the conversation.
add_tool adds one more tool to the agent after tools was built. It briefs the running backend again, and the next step can call the tool. set_plan_mode(True) withholds every tool that acts and tells the model to reply with a plan. The conversation stays. set_plan_mode(False) restores the tools.
Agent.add_tool
def add_tool(
f
):Add one tool to this agent now, and re-brief a running backend. Raises ValueError for a tool only_tools does not name.
Agent.set_plan_mode
def set_plan_mode(
on
):Withhold every acting tool and brief the model to plan, or restore the tools. The conversation continues either way. Raises RuntimeError while a turn runs.
Agent.refresh
def refresh():Re-discover skills, extensions and tools, and re-brief a running turn backend in place.
refresh drops the cached tool list. tools is a new list afterwards with the same names. The terminal calls it when it moves the agent onto a new host, such as one with a Python kernel.
before = agent.tools
agent.refresh()
agent.tools is beforebefore = agent.tools
agent.refresh()
assert agent.tools is not before
test_eq({t.__name__ for t in agent.tools}, {t.__name__ for t in before})A tool added with add_tool stays in the registry. It survives reload and refresh, and it still reaches the model.
def hour(city: str) -> str:
"What time it is in `city`."
return f'noon in {city}'
agent.add_tool(hour)
assert 'hour' in {t.__name__ for t in agent.tools}
agent.reload(); agent.refresh()
test_eq('hour' in {t.__name__ for t in agent.tools}, True)
test_eq([t.__name__ for t in agent.registry.tools], ['hour'])Agent.snapshot_tree
def snapshot_tree(
cwd:str='', command:str=''
):Read the open folders before a command runs. settle_tree then tells what the command moved. Once the open folders hold over SHELL_SNAPSHOT of text, only the folders _scope names for this cwd and command are read. Returns True when a snapshot exists.
Agent.settle_tree
def settle_tree():Find what the command moved, when the command finishes and not when the turn ends.
Agent.session_changes
def session_changes():{path: (before, after)} for every file written this session, this turn’s included. before is the file as it stood at its first write.
Agent.changes
def changes():{path: (before, after)} for every file this turn’s write tools actually moved.
Agent.verify_command
def verify_command():The project’s check: self.verify, else [tool.ramabana] verify in the first root’s pyproject.
Agent.changed_line
def changed_line(
rows:NoneType=None
):One line for the turn’s writes, or for rows from changed_rows: changed: src/a.py (+3 -1), b.py (+1 -0).
Agent.changed_rows
def changed_rows():(path under the first root, added, removed, new) for each file this turn’s writes moved.
changes() returns the files that this turn’s tools changed, as {path: (before, after)}. Before a write tool runs, the agent saves the text of each file it names. Before a shell command or a git write runs, snapshot_tree reads every open folder, and settle_tree compares them the moment the command returns. changes() then compares the saved text with what is on disk, showing a notebook as its cell sources.
changes() and /rewind work per turn. session_changes() is the same for every file written this session: _prepare folds each turn’s saved text into session_before, where the earliest text of a path wins, and the side pane lists these files.
When the open folders hold more than SHELL_SNAPSHOT characters of text, a command cannot read them all. snapshot_tree then reads only the folders _scope names: the git repository of the command’s cwd (the cwd alone outside a repository), the repository of every file written this session, and the repository of every absolute path under the open folders in the command line. The same cap applies to that smaller set. A file the command writes outside it is not seen, and is never claimed as the turn’s. Two limits remain. run_shell_bg is not watched, because the command outlives the call, so there is no moment at which to compare. Commands that overlap share one snapshot, so a second command’s changes are settled when the first one returns, and a change after that is missed.
changed_rows and changed_line turn that into line counts per file and a one-line summary. verify_command names the project’s check, from verify= or [tool.ramabana] verify in pyproject.toml. When a check exists and a turn changed files without running the shell, the agent runs the check and adds the last six lines of its output to the reply. A file written outside a tool, as in the example, is not counted.
agent.changes()agent.host.write('/proj/new.py', 'x = 1\n')
test_eq(agent.changes(), {})ready asks the turn backend whether its model is up. It is False until something starts the backend. Building an engine when the agent is made would cost a model load only to open a window. backend and chat return the turn backend and its live chat object.
fresh = demo_agent()
fresh.ready, fresh.notefresh = demo_agent()
test_eq(fresh.ready, False)
test_eq(fresh.note, 'not started')model is the ModelSpec the turn job routes to. spec_or_none(job) gives any job’s spec, or None when the job’s model name does not resolve. Here every job routes to the same recorded Claude model.
agent.model, [agent.spec_or_none(j).name for j in JOBS]test_eq(agent.model.runtime, 'claude')
test_eq(agent.model.model_id, 'claude-sonnet-4-5')
test_eq(agent.spec_or_none('turn'), agent.model)
test_eq(agent.spec_or_none('nonexistent-job'), agent.model)
test_eq({agent.spec_or_none(j).model_id for j in JOBS}, {'claude-sonnet-4-5'})Agent.start
def start():Build the turn backend, once. Returns it, or None with note explaining why not.
start builds the turn backend and starts its model. It returns the backend, or None with note saying why, such as a missing API key. Without a call to start, the backend waits for the first turn. Opening a window costs nothing. retry forgets an earlier failure and starts again. Use it after a model download or after setting a key.
turn = demo_agent()
turn.start()
turn.ready, turn.noteturn = demo_agent()
test_eq(turn.ready, False)
turn.start()
test_eq(turn.ready, True)
assert turn.backend is not None
test_eq(turn.chat_or_none('turn') is not None, True)Agent.retry
def retry():Forget a previous failure and start again. A model downloaded or a key set since is picked up.
Agent.config_command
def config_command(
arg:str=''
):/config: show what is in effect, its path, set KEY VALUE, reset to the commented template, or reload after an edit by hand.
Agent.apply_config
def apply_config():Read config.toml’s [jobs] again for every job this session has not set itself. Returns one line per job that moved.
Agent.settle
def settle():Move a turn that nobody named off a model that cannot run here, onto Routing.settled(). Returns the line that says so, or ’’.
Agent.set_model
def set_model(
name, job:str='turn'
):Point job at name. Changing the turn model moves the live conversation to the new model. Raises RuntimeError while a turn runs.
The sub-agent settings can change mid-session while no turn runs: set_subagent_writes, set_subagent_steps, set_subagent_timeout (0 means no limit), and set_subagent_depth, how many levels of sub-agents may delegate again (at most SUB_DEPTH_MAX, which is 2). subagent_report is what /subagents prints. Each raises while the agent is busy.
subagent_settings(model, effort, tools, save) shows or changes the sub-agent model, effort level and tool channel. None leaves a setting as it is. default takes the value from config.toml. save=True writes the settings given in that call, and only those, to [jobs] subagent, [subagents] effort and [subagents] tool_channel. With none given it writes nothing and says so. A $RAMABANA_SUBAGENT_EFFORT that is no level is ignored, and the report names it. One lock on the agent guards building and starting a backend. Delegations that ask for one model at once share one backend. subagent_settings returns one dict with the keys ok, model, effort, tools, note, unavailable and error. subagents_command returns the same dict for /subagents ARGS. A web route can send the dict as JSON. A model that is unknown or not set up is refused with its setup message in error, and the setting is not applied. subagent_settings can change settings while a turn runs, and each delegation reads them when it starts. set_tool_channel sets the turn’s channel for /model tools and carries the conversation onto a new chat.
Agent.set_tool_channel
def set_tool_channel(
mode, save:bool=False
):Send the turn’s tool schemas native, as text in the prompt, or auto. The conversation continues on a new chat. save also writes runtime.tool_channel.
Agent.subagents_command
def subagents_command(
arg:str=''
):Run /subagents ARG and return the dict that subagent_settings returns.
Agent.subagent_settings
def subagent_settings(
model:NoneType=None, effort:NoneType=None, tools:NoneType=None, save:bool=False
):Show or change the sub-agent model, effort and tool channel. None leaves a setting as it is, and default takes the value from config.toml. save writes the settings to config.toml. Returns one dict that is ready for JSON.
Agent.subagent_report
def subagent_report():Every sub-agent setting, as /subagents reports it.
Agent.set_subagent_depth
def set_subagent_depth(
n
):Set how many levels of sub-agents may delegate again, at most SUB_DEPTH_MAX.
Agent.set_subagent_timeout
def set_subagent_timeout(
s
):Set the seconds a delegation may run before it is stopped; 0 never stops it.
Agent.set_subagent_steps
def set_subagent_steps(
n
):Set the cap on a delegation’s max_steps, from 1 to SUB_STEP_CEILING. auto sets no cap below the ceiling.
Agent.set_subagent_writes
def set_subagent_writes(
enabled
):Grant or withdraw sub-agent write access for this session.
set_local_multimodal sets whether newly loaded LiteRT engines include their image and audio encoders. It closes every LiteRT engine already loaded. lend_model gives a host that builds its own chats a factory that reuses this session’s engine. The host does not load a second engine. lend_model returns False when the host does not take a factory.
Agent.set_local_multimodal
def set_local_multimodal(
enabled
):Choose whether newly loaded LiteRT engines include media encoders.
Agent.lend_model
def lend_model():Lend this session’s engine to a host that builds its own chats, as a factory.
A host can hold watches, scheduled checks such as a reminder. poll_watches fires the due ones in a background thread, at most every poll_every seconds (900 by default). watch_notice adds what fired to the next prompt as a <watch-results> block. The example after the warm-start cells shows one.
Agent.watch_notice
def watch_notice():What polls fired since the last turn, as one <watch-results> block, or ’’.
Agent.poll_watches
def poll_watches(
force:bool=False
):Fire whatever the host has due, in a daemon thread, at most every poll_every seconds.
A peer, another live session, can send this session a note while no turn runs. Control keeps it in peer_notes, and peer_notice adds the notes to the next prompt as one <peer-messages> block. peers.peer_text writes each message.
Agent.peer_notice
def peer_notice():The peer messages kept since the last turn, as one <peer-messages> block, or ’’.
The notice takes every note from the list, so a note joins one turn only.
from ramabana.peers import Envelope
_frm = {'kind': 'claude', 'key': 'claude-s1', 'name': 'abhyasa'}
_a, _ = fake_agent()
_a.peer_notes.append(Envelope('note', 'v2 is out', _frm))
assert '<peer-messages>' in _a.peer_notice() and _a.peer_notice() == ''A warm start seeds a fresh session’s history with a few worked examples before the first turn. The examples are rounds from dhrona: earlier exchanges kept as good examples of the tool dialect, such as search versus grep, a refused approval or a git flow. fit_rounds picks only rounds whose every call uses a tool this session offers, best-ranked and same-model first, up to WARM_ROUNDS (three, or one for the small profile).
It is off unless asked for, with Agent(warm=True) or the terminal’s --warm. Each round shows one call per message, and a current model copies that style. A resumed session starts empty even when asked, and so does a full-profile model whose budget allows no inlined skill. Without dhrona installed (uv add "ramabana[dhrona]") the session gets a note instead. The seeds go in before the first turn’s checkpoint. /rewind to before turn 1 keeps them. The turn record lists the rounds used in plan['warm']. warm_report['skipped'] says why each other round was left out, as below.
Agent.warm_start
def warm_start():Seed a fresh chat with dhrona’s accepted rounds whose calls bind to the offered tools.
Agent.warm
def warm():Whether a fresh session is seeded. It is seeded only when asked, because each round shows one call per message and a model copies it.
# `fake_agent` builds the installed `Agent`; widen the budget on its class
from unittest.mock import patch as _patch
from ramabana.core import Budget
warmed, wbe = fake_agent(replies=['ok'], warm=True)
cold, cbe = fake_agent(replies=['ok'])
with _patch.object(type(warmed), 'budget', property(lambda self: Budget())):
warmed.ask('hello'); cold.ask('hello')
test_eq(wbe.hist_[0]['role'], 'user')
assert [r['name'] for r in warmed.warm_report['used']] and len(warmed.warm_report['used']) <= WARM_ROUNDS
test_eq(warmed.warm_start(), [])
test_eq(warmed.history[-1]['plan']['warm'], [r['name'] for r in warmed.warm_report['used']])
test_eq(len(cbe.hist_), 2)
warmed.warm_report['skipped'][{'name': 'git-flow', 'reason': 'tool git_status is not offered here'},
{'name': 'notebook-edit',
'reason': 'tool notebook_cells is not offered here'},
{'name': 'memory-key', 'reason': 'tool memory_search is not offered here'},
{'name': 'delegation', 'reason': 'over the limit of 3'}]
!ramabana --no-warmpolled, _ = fake_agent()
polled._watch_found.append(dict(checked=2, ran=1, results=[dict(id='w1', kind='remind', target='renew the domain', status='ok')], housekeeping=dict(stale=1, pruned=1)))
print(polled.watch_notice())
test_eq(polled.watch_notice(), '')
polled._watch_found.append(dict(checked=2, ran=0, results=[], housekeeping=dict(stale=1, pruned=0)))
assert polled.watch_notice()poll_monitors reviews every folder the session watches, in a background thread. The next prompt carries the reviews. Folder monitoring describes the reviews.
Agent.poll_monitors
def poll_monitors():Review every watched folder in a daemon thread, for the next turn.
A beat is ramabana-tick, a scheduled job that runs due schedules while no session is open and leaves notes behind (the index shows how to install it). beat opens the beat’s database, or is None on a machine where no beat has run. beat starts the session’s reader at the newest note, so a new session does not show the notes of jobs that ended before it began. beat_drain reads the notes this session has not seen, once, under the session id. The next prompt carries them. The first drain of a session also carries beat_problems: a launcher that predates the PATH fix, a PATH that no longer finds a tool, or a beat.env others can read, each saying to re-run ramabana-tick --install or what else to run.
Agent.beat_drain
def beat_drain():Notes the beat left that this session has not read. The first call puts the problems of the installed beat first. Empty when no beat runs here.
Agent.beat
def beat():The beat’s database, opened once. None where no beat has ever run on this machine.
import tempfile, ramabana.monitor as monitor
was, monitor.POB_HOME = monitor.POB_HOME, Path(tempfile.mkdtemp()) # a machine where no beat has run
test_eq(agent.beat, None)
test_eq(agent.beat_drain(), [])
monitor.POB_HOME = was
assert not str(pob_path()).startswith(str(Path.home())) # the notebook's own beat, never this machine's
seen, _ = fake_agent()
seen._beat, seen._beat_reader = pob(Path(tempfile.mkdtemp())/'pob.db'), 'r'
seen.beat.note('dhrona', 'ran')
from unittest.mock import patch as mpatch
stale = lambda: ['the scheduled beat predates ramabana 0.2.52: run `ramabana-tick --install` again']
was, beat_problems = beat_problems, stale
try:
with mpatch('ramabana.agent.beat_problems', stale): test_eq(len(seen.beat_drain()), 2)
with mpatch('ramabana.agent.beat_problems', stale): test_eq(seen.beat_drain(), []) # once a session
finally: beat_problems = was
test_eq(beat_notice([]), '')A session joins the beat when it opens it. It sees only the notes made after that, not the notes of jobs that ended before it began.
d = Path(tempfile.mkdtemp())
old = pob(d/'pob.db')
old.note('abhyasa-index', 'no callback registered')
was, monitor.POB_HOME = monitor.POB_HOME, d
try:
late, _ = fake_agent()
late._beat, late._beat_checked = 'unset', True # open the beat as a real session does, without this machine's beat problems
test_eq(late.beat_drain(), []) # a note from before the session stays behind
old.note('abhyasa-index', 'indexed 3 files')
test_eq(late.beat_drain(), ['abhyasa-index: indexed 3 files'])
finally: monitor.POB_HOME = wasrepo_state returns a folder’s git state: the repository, the HEAD commit, the branch and the modified tracked files. A session’s first turn writes it for every open folder to start.json in the run folder. A session that already has turns writes none. The state now is not the state the session began from, and Dhrona replays from that file. With learning off, no session writes it.
A session also holds a lock while a process uses it. claim_session takes it, release_session gives it up, and session_owner names the process holding another session. Two processes cannot run turns in one session at once. The second gets SessionBusy.
Agent.session_owner
def session_owner(
sid
):{'pid': ...} when another live process holds session sid, else None.
Agent.release_session
def release_session():Give the session up if this process holds it. Its folders stay, for latest.
Agent.claim_session
def claim_session():Hold this session for this process and record its folders; False when another live process holds it.
repo_state
def repo_state(
folder
):{folder, repo, head, branch, dirty} for the git repository holding folder, or None outside one. dirty lists modified tracked files.
Before a message goes out, _fit makes it fit the turn model’s window, cheapest step first. It stops at the first step after which the message fits:
- A message, or a newest exchange, larger than half the room the briefing leaves is cut to an excerpt first. A short conversation is not compacted to make room for one paste. A prompt holding a
<notebook>is left to the notebook step. - The oldest tool results, then the oldest pictures, are trimmed (
Backend.trim). - The conversation is compacted, whether or not
compaction.autois on. - The notebook’s
discardand thenautocells are left out (compact_notebook_context). - The newest two messages are cut (
Backend.shrink_recent). - The message itself is cut to the room left (
fit_content): the newest pictures that fit stay, and text becomes its head and its end around a note naming the file that holds it whole. The reminders_prepareadded to its end are kept whole.
Whatever is cut is written whole under <runs_dir>/full, readable by this user alone, and the note says how to read it with the tools the model has: view_file(path, start=N) in pieces, or grep. When the read tools cannot reach that folder, it is opened to them for reading only. The log keeps the prompt as it was typed.
ContextFull is raised only when the briefing and tools alone overflow the window. Its message ends with fresh_hint, the host’s advice. {session} in the advice stands for the session id. The terminal session passes CLI_FRESH, which says to quit and run ramabana --resume. An app that embeds the agent passes its own advice. Without one, the advice is FRESH_HINT, which names no command.
Agent.session_turns
def session_turns(
sid
):One conversation’s turns, from memory. A log-backed agent seeks them instead.
Agent.sessions
def sessions():Persisted conversations, newest first, with enough detail for a picker.
sessions lists the saved conversations, newest first, with turn counts, model and title, for a picker. session_turns returns one conversation’s turns. The demo agent has none yet. Later on this page both are replaced by versions that read an index of the log.
[s['id'] for s in agent.sessions()][:3]resume_session picks a saved conversation back up, by full id, by unique prefix, or latest, the newest one from these folders that no other process holds. It rebuilds the model’s context from the turns a resume gives back (replayed_turns) and loads that session’s plan. It switches to the conversation’s last model unless keep_model=True. With full=True, a conversation saved by keep_conversation comes back whole, every tool result included, as long as the turn model is the same. session_added_roots lists folders the session opened with add_root. Resuming does not reopen them.
Agent.session_added_roots
def session_added_roots(
session_id
):Folders a session opened with add_root, in order, from the log. It reopens nothing.
Agent.resume_session
def resume_session(
selector:str='latest',
keep_model:bool=False, # stay on the current turn model rather than the conversation's last
full:bool=False, # restore the conversation as its last turn left it, every tool result whole
):Resume a persisted conversation by full/prefix id, or the newest with latest.
Agent.replayed_turns
def replayed_turns(
sid
):The turns of session sid a resume gives back: finished, failed, ended by a tool-call or step budget, stopped, or cut off when their process ended. A turn a cost or token budget stopped is not given back.
events_to(path) writes one JSON line per event to a file from then on: tool calls, approval asks and answers, plan changes, turn starts and ends, and steering. A file past max_bytes rolls over to <name>.1. An application that follows a job from another process tails that file.
Agent.details_path
def details_path():<cfg>/<history_name>-details/<session>.jsonl: tool results too long for the turn log, or None without a config dir.
Agent.events_to
def events_to(
path, max_bytes:int=10000000, # the size at which the file rolls over to `<name>.1`
):Write one JSON line per event to path from now on: calls, asks, plan changes, turns and steering. Returns the path.
replays
def replays(
turn
):Whether a resume gives turn back whole: it completed or failed, or only a SOFT_CAPS budget ended its tool calls.
A rewind undoes a turn. Before a turn’s first write to a file, the agent keeps the exact text of the file. For a notebook that is the JSON in the file, not the cell text that text_at shows, so a rewind puts back the same bytes. A checkpoint written before this, which holds a notebook’s cell text, is refused for that notebook instead of replacing it with plain text. The agent also notes the files the turn creates. _checkpoint saves both under checkpoint_dir when the turn ends. rewind(turn_id, what) puts files, the chat or both back to before that turn, the last turn by default. A rewind needs one approval. It does the following:
- an edited file gets its earlier text back;
- a file the turn created is deleted, unless it changed after the turn, in which case it is kept and named;
- a binary file cannot be restored, and is named;
- each git write is undone with its
undotoken, newest first.
Git and files go back together or not at all. If HEAD moved, the branch changed, or other tracked files were modified after the turn, the rewind refuses and says what to do first. Rewinding the chat makes a branch that stops before the turn (undo_turn). The example drives all this through /rewind files on a real repository.
Agent.rewind
def rewind(
turn_id:str='', what:str='both'
):Put files, chat or both back to before turn_id (default the last), under one approval.
Agent.checkpoint_dir
def checkpoint_dir():<cfg>/checkpoints/<session>, or None without a config dir.
import subprocess, tempfile
from shalya.host import LocalHost
def _g(cwd, *a): return subprocess.run(['git', *a], cwd=cwd, check=True, capture_output=True, text=True).stdout.strip()
rw_repo = Path(tempfile.mkdtemp())/'repo'; rw_repo.mkdir()
_g(rw_repo, 'init', '-q', '-b', 'main'); _g(rw_repo, 'config', 'user.email', 't@t'); _g(rw_repo, 'config', 'user.name', 't')
(rw_repo/'a.txt').write_text('hi\n'); _g(rw_repo, 'add', 'a.txt'); _g(rw_repo, 'commit', '-q', '-m', 'init')
rw, _ = fake_agent(host=LocalHost([str(rw_repo)], index=False), approvals=Approvals(tools=set(), mode='auto'), cfg=rw_repo.parent/'cfg')
rw_tools = {t.__name__: t for t in rw.tools}
rw._prepare('commit the change')
(rw_repo/'a.txt').write_text('hello\n'); rw_tools['git_commit']('turn commit', 'a.txt'); rw._finish('done')
row = rw.git_undo[rw.current_turn_id][-1]
assert row['head'] and row['branch'] == 'main', row
turn_head = _g(rw_repo, 'rev-parse', 'HEAD')
(rw_repo/'b.txt').write_text('mine\n'); _g(rw_repo, 'add', 'b.txt'); _g(rw_repo, 'commit', '-q', '-m', 'after the turn')
rw.command('/rewind files')
test_eq(_g(rw_repo, 'log', '--oneline').count('\n'), 2)
assert not any(x.tool == 'rewind' for x in rw.approvals.history)
_g(rw_repo, 'reset', '-q', '--hard', 'HEAD~1')
rw.command('/rewind files')
test_eq(_g(rw_repo, 'rev-parse', 'HEAD') != turn_head and _g(rw_repo, 'log', '--oneline').count('\n'), 0)
preview = next(x for x in rw.approvals.history if x.tool == 'rewind').args['git']
test_eq(len(preview), 1)
_g(rw_repo, 'checkout', '-q', '-b', 'feature')
(rw_repo/'b.txt').write_text('theirs\n'); _g(rw_repo, 'add', 'b.txt'); _g(rw_repo, 'commit', '-q', '-m', 'b')
rw._prepare('again'); rw_tools['replace_text']('a.txt', [{'oldText': 'hello', 'newText': 'more'}]); rw_tools['git_commit']('second', 'a.txt'); rw._finish('done')
_g(rw_repo, 'checkout', '-q', '-b', 'feature2')
rw.command('/rewind files')
test_eq(_g(rw_repo, 'branch', '--show-current'), 'feature2')
_g(rw_repo, 'checkout', '-q', 'feature')
(rw_repo/'b.txt').write_text('mine, uncommitted\n')
rw.command('/rewind files')
test_eq((rw_repo/'b.txt').read_text(), 'mine, uncommitted\n')
(rw_repo/'b.txt').write_text('theirs\n'); (rw_repo/'a.txt').write_text('later\n')
rw.command('/rewind files')
test_eq((rw_repo/'a.txt').read_text(), 'hello\n')
rw._prepare('once more'); (rw_repo/'a.txt').write_text('x\n'); rw_tools['git_commit']('third', 'a.txt'); rw._finish('done')
(rw_repo/'.git'/'HEAD').write_text('garbage\n')
rw.command('/rewind files')
test_eq((rw_repo/'a.txt').read_text(), 'x\n')Agent.ask
def ask(
prompt, **kw
):One turn. Returns the assistant’s text, or the reason there isn’t any.
ask runs one turn and returns the reply text. It prepares the message (notices, hooks and fitting to the window), sends it to the turn model, runs the tool loop, and stores the turn. compose builds a message from frontend context, and ask_with calls it. A later cell replaces ask with the version every frontend uses. That version wraps the turn in a run that can be cancelled.
The answer here is a recording. Nothing reaches a model. A recording keeps what the call cost as well as what it said. turn_use reports real token counts. Compaction cannot be tested on a recording. A recorded chat refuses to have its history replaced. compact returns the summary and leaves the history as it was.
asked = demo_agent()
answer = asked.ask('In one word, what colour is a clear sky?')
answerassert 'lue' in answer, answer
test_eq(len(asked.history), 1)
test_eq(asked.history[-1]['prompt'], 'In one word, what colour is a clear sky?')
test_eq(asked.turn_use.model, 'claude-sonnet-4-5')
assert asked.turn_use.total > 0, asked.turn_use
assert asked.turn_use.input > asked.turn_use.outputAgent.stream
def stream(
prompt, **kw
):One turn as an iterator of markdown chunks, for a frontend that can render as it arrives.
stream is the same turn as an iterator of markdown chunks, for a frontend that shows the answer as it arrives.
This turn cannot be replayed. A streamed reply is a generator, and the recording store refuses to keep one rather than store its repr. Under recorded() the refusal comes back as the turn’s text, which the cell below accepts. The tests in tests/ cover stream against a live model.
streamed = demo_agent()
chunks = list(streamed.stream('In one word, what colour is a clear sky?'))
''.join(chunks)[:120]whole = ''.join(chunks)
assert chunks and whole, chunks
assert ('lue' in whole or 'cannot record a generator' in whole or 'no recording' in whole), whole
test_eq(len(streamed.history), 1)Agent.compose
def compose(
prompt, context:str='', screen:str='', image:NoneType=None, context_path:str=''
):One message built from the context a frontend supplies: the notebook, the screen as text, and the screen as a picture.
A frontend often has more than the person’s words: an open notebook, the screen as text, or a screenshot. compose wraps them into one message. The words go in a <user-request> tag, and any images go before the text. ask_with and stream_with compose the message and run the turn in one call.
shaped = demo_agent()
shaped.compose('what does this do?', context='def a(): return 1', context_path='/proj/a.py')one = shaped.compose('what does this do?', context='def a(): return 1', context_path='/proj/a.py')
assert 'what does this do?' in one and 'def a(): return 1' in one and '/proj/a.py' in one
assert 'def a(): return 1' not in shaped.compose('what does this do?')Agent.ask_with
def ask_with(
prompt, context:str='', screen:str='', image:NoneType=None, context_path:str='', **kw
):One blocking turn with the frontend’s context attached.
Agent.stream_with
def stream_with(
prompt, context:str='', screen:str='', image:NoneType=None, context_path:str='', **kw
):The same turn, as an iterator of markdown chunks.
Agent.context_parts
def context_parts(
turn_id, stage:str='after'
):A checkpoint’s messages as branchable parts, a call grouped with its results.
A checkpoint is the model’s whole conversation saved at a turn boundary, before the turn and after it. The agent keeps the last MAX_CHECKPOINTS (20) in memory. context_parts splits one into parts, one per message. A tool call is grouped with its results, and the group moves together. fork and undo_turn, below, build branches from the parts. A checkpoint that was never taken raises KeyError.
checked = demo_agent()
for stage in ('after', 'before'):
try: checked.context_parts('no-such-turn', stage)
except KeyError: pass
else: assert False, f'{stage} should have refused'checked = demo_agent()
for stage in ('after', 'before'):
try: checked.context_parts('no-such-turn', stage)
except KeyError: pass
else: assert False, f'{stage} should have refused'Agent.conversation_parts
def conversation_parts(
sid:NoneType=None
):A stored conversation as ordered, editable parts, rebuilt from the turn log.
A branch is another version of the conversation for the model to continue from, made without changing the recorded history. conversation_parts lists a stored conversation as parts a person can keep, drop or rewrite: each prompt and reply is editable prose, and each tool call and result is fixed. It is built from the turn log, not from a checkpoint. A conversation that someone wants to reshape is usually one they just resumed, and a resumed session holds no checkpoints.
shaper = demo_agent()
shaper.ask('In one word, what colour is a clear sky?')
[(p['part_id'].split(':')[-1], p['kind'], p['editable']) for p in shaper.conversation_parts()]shaper = demo_agent()
shaper.ask('In one word, what colour is a clear sky?')
parts = shaper.conversation_parts()
test_eq([p['kind'] for p in parts], ['user', 'assistant'])
assert all(p['part_id'] and p['turn_id'] and p['group'] for p in parts)
assert all(p['editable'] for p in parts)
test_eq([p['part_id'] for p in shaper.conversation_parts()], [p['part_id'] for p in parts])Agent.compile_conversation
def compile_conversation(
sid:NoneType=None, manifest:NoneType=None, rewrites:NoneType=None
):Provider messages for a reshaped conversation, with the dropped parts removed and the rewrites applied.
Agent.reshape
def reshape(
sid:NoneType=None, manifest:NoneType=None, rewrites:NoneType=None, branch_id:str='', revision:NoneType=None
):Make a reshaped conversation the active branch. The recorded history does not change.
Branches can also start from a checkpoint held in this process. compile_context gives a checkpoint’s messages up to a part, keeping or dropping each group as a manifest of keep, discard or auto says. fork makes those messages the active branch. undo_turn is a fork from before a turn, and revise is a fork from after it with the reply replaced by the person’s text. switch_branch makes another branch active by rebuilding its messages from its parent point. The recorded turn log never changes.
Agent.compile_context
def compile_context(
turn_id, stage:str='after', part_id:str='', manifest:NoneType=None
):A checkpoint’s messages up to part_id, each call group’s policy applied.
Agent.fork
def fork(
turn_id, stage:str='after', branch_id:str='', part_id:str='', manifest:NoneType=None, revision:NoneType=None
):Fork model context from a captured turn boundary, or a part inside it, and make it active.
Agent.switch_branch
def switch_branch(
branch_id
):Make another branch active by rebuilding its context, never by copying it.
Agent.undo_turn
def undo_turn(
turn_id, branch_id:str=''
):Undo a turn by making a branch that stops before it. The turn stays in the canonical history.
Agent.revise
def revise(
turn_id, text, branch_id:str=''
):Fork after a turn and replace its prose response with a user-authored revision.
Agent.oneshot_stream
def oneshot_stream(
prompt, sp:str='', job:str='oneshot', max_tokens:NoneType=None,
fits:NoneType=None, # `fits(backend)`; a route it refuses ends the search with nothing yielded and is not set aside
prepare:NoneType=None, # `prepare(prompt, sp, backend)` returns the text for each route; a raised refusal stops the search
deadline:NoneType=None, # seconds the whole call may take, routing, `prepare` and fitting included
wait:bool=False, # wait for a backend another call holds, rather than yield nothing
strict:bool=False, # raise `OneshotEmpty`, which says why, when no text comes
fallback:bool=False, # a route that cannot stream gives its whole reply as one chunk
):The text of oneshot’s reply as the model sends it, one chunk at a time. The next route is tried only while no text has come: a route that fails or says nothing is set aside, and one that has spoken is never followed by another. A timeout, a cancel, a failure after text and a budget stop are raised. Closing the iterator closes the model’s stream. A route that cannot stream raises StreamUnsupported, and one that cannot hold a deadline raises DeadlineUnsupported, before it is asked. Different backends can run in parallel. Budgets are soft spend caps, not billing ceilings. Parallel calls can overshoot by the calls already in flight. With fallback, a route that cannot stream is asked through oneshot, and its reply comes as one chunk.
Agent.oneshot
def oneshot(
prompt, sp:str='', job:str='oneshot', max_tokens:NoneType=None,
fits:NoneType=None, # `fits(backend)`; a route it refuses ends the search with '' and is not set aside
prepare:NoneType=None, # `prepare(prompt, sp, backend)` returns the text for each route; a raised refusal stops the search
deadline:NoneType=None, # seconds the whole call may take, routing, `prepare` and fitting included
wait:bool=False, # wait for a backend another call holds, rather than answer ''
strict:bool=False, # raise `OneshotEmpty`, which says why, rather than answer ''
):A question on whichever model job routes to, in a conversation that is thrown away. A cloud model that fails or answers nothing is set aside, and the question goes to job’s next route. Past deadline it raises OneshotTimeout and tries no other route. prepare is not interrupted: the deadline is checked when it returns. A route that cannot hold a deadline raises DeadlineUnsupported before it is asked. With wait, a busy backend is waited for, up to deadline. With strict, no answer raises OneshotEmpty with the routes set aside or the route’s note.
oneshot asks one question that needs no history and no tools, in a conversation that is thrown away. It runs on the model the oneshot job routes to, or on the job you name. A quick question never spends the turn model’s window. oneshot_stream yields text chunks before the reply is complete. Different backends run in parallel. Each call captures its usage before releasing its backend lock. The running totals are updated under a short accounting lock. Budgets are soft spend caps, not billing ceilings. Parallel calls can overshoot by the calls already in flight. When a cloud model fails or answers nothing, it is set aside and the question moves to the job’s next route.
asker = demo_agent()
said = asker.oneshot('Reply with exactly the word: yes')
saidassert 'yes' in said.lower(), said
test_eq(len(asker.history), 0)
class _Unavailable:
def _be_or_none(self, job): return None
test_eq(Agent.oneshot(_Unavailable(), 'anything at all'), '')An app that shares one agent among threads passes wait=True: a backend that another call holds is waited for, up to deadline, and the call does not answer ''. With strict=True, a call that gets no answer raises OneshotEmpty. Its why names the routes that were set aside, or the note of the route. oneshot_stream(fallback=True) asks a route that cannot stream through oneshot, and yields the whole reply as one chunk.
from types import SimpleNamespaceclass _Nowhere(_Unavailable): routing = SimpleNamespace(down={}, notes={'oneshot': 'no model runs here'})
test_fail(lambda: Agent.oneshot(_Nowhere(), 'anything at all', strict=True), contains='no model runs here')Agent.classify
def classify(
text, labels
):One label for text, on the cheap model. Returns the matched label, or the raw reply.
Agent.summarise
def summarise(
text, sp:str='Summarise concisely. Output only the summary.'
):Summarise text on the summary job’s model, in a throwaway conversation.
classify picks one label for a text on the classify job’s model, and summarise summarises a text on the summary job’s model. Both are oneshot calls. Neither adds to the session’s history.
summariser = demo_agent()
shorter = summariser.summarise('The user asked about thresholds. The agent read pkg/sizes.py and answered 4096.')
shorterassert len(shorter) < 600, len(shorter)Compaction shortens the conversation when it nears the model’s window. The summary model writes a summary of the history so far, and the conversation continues from the summary. With compact=True the agent compacts on its own when the compactor says it is due or the next message would not fit. Without compact=, the agent reads compaction.auto from config.toml, and the default is True. compact() does it now, and extra tells the summariser what to keep.
Agent.handoff
def handoff():Hand the conversation to a fresh context: summarise all of it, keep its finished work as a project memory note, and go on from the summary alone.
Agent.compact
def compact(
extra:str='', fresh:bool=False, # summarise everything and keep no recent messages, as `handoff` does
):Compact the conversation now. Returns the summary text, or '' with compactor.note set.
handoff is compaction that keeps nothing recent. The summary model summarises the whole conversation, and the conversation goes on from that summary alone. The summary’s Done list is kept as a project memory note. A turn starts a handoff by itself when the conversation is past the compactor’s soft line and the last turn ended at a boundary: it completed, and it made a commit or left no unfinished plan step. Past the hard line, ordinary compaction runs instead. /handoff starts one by hand.
hb, _ = fake_agent()
hb.history = [dict(state='complete', activity=[])]
assert hb._at_boundary(), 'a clean turn with no plan is a boundary'
hb.plan.add('write the docs')
assert not hb._at_boundary(), 'an unfinished step is not'
hb.history = [dict(state='complete', activity=[dict(tool='git_commit', ok=True)])]
assert hb._at_boundary(), 'a commit closes the work, whatever the plan says'
hb.history = [dict(state='failed', activity=[dict(tool='git_commit', ok=True)])]
assert not hb._at_boundary(), 'a turn that failed never is'Agent.pct_full
def pct_full():The share of the turn model’s context window in use, from 0 to 1.
Agent.turn_md
def turn_md(
title:str='what I did'
):This turn’s tool calls as foldable markdown, to save alongside the answer in a cell.
turn_md gives this turn’s tool calls as folded markdown, for a frontend that saves the work beside the answer in a cell. A turn with no tool calls gives ''.
print(asked.turn_md())test_eq(asked.turn_md(title='nothing happened'), '')Agent.turn_lines
def turn_lines():This turn’s tool calls as plain summary lines, for a pane that cannot fold.
turn_lines gives the same calls as one line each, for a pane that cannot fold. calls holds every (tool, args) pair the agent has run.
agent.turn_lines(), agent.callsAgent.problems
def problems():Everything that went wrong and had nowhere to be reported, newest last.
problems collects what went wrong and had nowhere to be reported: backend failures, a compaction that could not run, a saved approval rule file that could not be read. It gathers them from every backend. A model that failed to load is reported whichever job it was routed to. The property returns the last ten. pct_full and context_used report how full the turn model’s window is.
agent.problems, agent.pct_full, agent.context_usedassert asked.context_used > 1000, asked.context_used
assert 0 < asked.pct_full < 1, asked.pct_full
assert asked.context_used != asked.turn_use.total, 'the two counters collapsed into one'
assert abs(asked.context_used - asked.turn_use.total) < asked.turn_use.total // 4Agent.clear_problems
def clear_problems():Forget the backends’ problems, once a frontend has shown them.
clear_problems forgets the backends’ problems once a frontend has shown them.
agent.clear_problems()
agent.problemspa, pbe = fake_agent()
pa._backends['turn'] = pbe # `fake_agent` swaps `_be`; `problems` reads the backends the agent holds
pbe.problems.append('backend broke')
assert 'backend broke' in pa.problems
test_eq('backend broke' in pa.clear_problems().problems, False)/commit and /pr are the two git flows a session repeats. commit takes the staged diff, or every changed tracked file when nothing is staged. It drafts a message on the oneshot model when none is given, asks for approval, and commits through git_commit. pull_request takes the commits ahead of the default branch, drafts a title, asks for approval, pushes the branch when it has no upstream, and opens the pull request on GitHub. When GitHub is out of reach, it prints the gh pr create command to run instead. Both work on the repository holding path, by default the project’s.
Agent.pull_request
def pull_request(
title:str='', path:str=''
):Open a PR for the commits ahead of the default branch in the repository holding path, drafting a missing title.
Agent.commit
def commit(
message:str='', path:str=''
):Commit the index, else every changed tracked file, in the repository holding path, drafting a missing message.
command runs a slash command typed in any frontend and returns the text to show, or None when the name is unknown. The frontend can then handle the line itself. The index lists the commands. A command an extension registered runs here too.
Agent.command
def command(
line
):Run a slash command. Returns text to show, or None when the command is unknown.
This cell gives ask, stream and cancel the versions every frontend uses. Each turn is now a registered run, an object with an id and a state that can be watched and cancelled, and a stopped turn is still recorded. ask takes three more options, for a host that runs agent jobs:
schema, a pydantic type or a JSON schema dict. The model gets asubmit_resulttool and is asked to hand back a value of that type, once more if it does not. The validated value arrives inTurnResult.result.result=Truereturns aTurnResult: the reply, the turn’s state (complete,failed,cancelled,budget,refusedorabandoned), its usage and its ids.strict=TrueraisesTurnFailedfor a turn that did not complete, andResultMissingwhen the schema was never filled.
queue holds a prompt for after the current turn, and run_queued runs the held prompts in order. cancel(run_id) stops one run, or the foreground turn, and returns its final state. terminate stops it without waiting for the provider. halt() stops the turn, its sub-agents and the side runs at once, waits for none, and returns how many runs it stopped. ask(deadline=, stop=) calls it once deadline seconds pass, or once the threading.Event stop is set. A turn in a session another process holds raises SessionBusy. The budgets max_cost, max_tokens and their session_ forms stop a turn that passes them, and the turn is recorded with state budget.
Agent.terminate
def terminate(
run_id:str=''
):Terminate one run without waiting for the provider.
Agent.halt
def halt():Cancel the turn, its run tree and the side runs (background delegations and monitor reviews), each with its children, and wait for none. Return how many runs stopped.
Agent.cancel
def cancel(
run_id:str='', grace:NoneType=None
):Cancel one run, or the foreground root, and return its structured terminal state.
Agent.stream
def stream(
prompt, on_registered:NoneType=None, **kw
):One registered turn as markdown chunks. A stopped turn is recorded and not replayed.
Agent.run_queued
def run_queued(
**kw
):Run every queued prompt in order, each its own turn, and return their TurnResults.
Agent.queue
def queue(
prompt
):Hold prompt for a turn after this one. run_queued runs what is held, in order. Returns how many prompts wait.
token_rate
def token_rate(
spec
):Dollars a token of spec’s model costs, as an estimate: fastllm’s price with no cache reads for a hosted model, EST_RATE for one fastllm cannot price, and 0 for a local model.
Agent.ask
def ask(
prompt,
schema:NoneType=None, # a type pydantic validates, or a JSON schema dict: the model hands back a value of it through `submit_result`
result:bool=False, # return a `TurnResult` rather than the reply text
strict:bool=False, # raise `TurnFailed` for a turn that did not complete, and `ResultMissing` for a `schema` never filled
deadline:NoneType=None, # seconds the turn may take, as for `oneshot`; then it is cancelled with `halt`
stop:NoneType=None, # a `threading.Event`; once it is set, the turn is cancelled with `halt`
**kw
):One registered turn. A stopped turn is recorded and not replayed. Without schema, result or strict, it returns the reply text, a dict when the turn was stopped, or a failure note. Past deadline, or once stop is set, the turn, its sub-agents and the side runs are cancelled.
ResultMissing
def ResultMissing(
result, why:str=''
):A strict ask with a schema whose model never handed back a valid result.
TurnFailed
def TurnFailed(
result, why:str=''
):A strict ask whose turn did not complete. result is its TurnResult.
TurnResult
def TurnResult(
reply:str='', state:str='', error:str='', usage:dict=<factory>, result:object=None, session:str='',
turn_id:str='', budget:str | None=None, estimated:bool=False
)->None:How one turn ended, for a host: its reply, its state, and the value it handed back.
SessionBusy
def SessionBusy(
*args, **kwargs
):A turn in a session another live process holds.
Mods in a turn
A before_turn hook can answer for the turn it is handed. A str refuses the turn: no model call runs, the reason comes back as the reply, and the row’s state is refused. {'prompt': ...} replaces the words the model gets, and {'context': ...} adds a <mod-context> block. Hooks run in registration order, each handed the prompt as the hooks before it left it, so rewrites chain, and the first refusal ends the turn before a later hook runs. Each piece of context names the mod that added it, in the row and in its <mod-context mod="NAME"> block.
ma, mbe = fake_agent(replies=['Fixed.'])
ma.registry.on('before_turn', lambda agent, prompt: {'prompt': prompt + ' with a test', 'context': 'the build is red'})
ma.ask('fix the parser')
test_eq(mbe.sent[0].startswith('fix the parser with a test'), True)
{k: ma.history[-1][k] for k in ('prompt', 'prompt_original', 'context_added')}The row keeps what the model got as prompt, so a resume rebuilds the same request, and the words typed as prompt_original. Added context goes in context_added, each entry with its mod (None from outside a mod) and where it was delivered: start, in the turn’s opening message, or tool, in a tool result. Context leaves its queue only when the request is ready to go: a turn that fails while it is prepared, such as one that does not fit the window, puts it back in order for the next request.
A resume rebuilds every entry into the opening message. That is where a start entry was. A tool entry goes there too, since the log keeps each tool call’s own result without what was appended to it, and a resume from the log gives tool calls back only as clipped text, never as tool rounds. A full resume restores the saved conversation instead, where the entry still sits in its tool result.
A refusal makes no model call, and its run ends refused:
ma.registry.on('before_turn', lambda agent, prompt: 'quiet hours until 9')
said = ma.ask('one more thing')
test_eq(len(mbe.sent), 1)
said, ma.history[-1]['state'], ma.run().stateinject adds context from outside a hook, such as a timer: to the root turn’s next tool result while one runs, else to the next turn. The entry names the mod that called, or None from outside a mod. ask_user puts a question to the person through the approval gate. 'ask user' is in PERSON_ONLY, so no mode, saved rule or policy answers it. With nobody listening it is refused at once, even by a gate built with no_listener='wait', whose own setting stays as it was:
qa, _ = fake_agent(approvals=Approvals(mode='auto', no_listener='wait'))
q = qa.ask_user('Take a break?', 'You have worked 50 minutes.')
test_eq(q.answer, False)
q.noteA run’s transcript is a plain text file under runs_dir. Anything that can tail a file can follow a sub-agent or a folder review.
watch(target)opens a tmux pane following a run’s transcript, ormonitorsfor the folder reviews, coloured in the palette of the terminal session’snow.jsonbeside it (setup.follow_cmd). With no target it lists what can be watched. Without tmux it prints that command to run instead.tell(run_id, text)queues a message for a running sub-agent, which reads it after its next tool call.steer(text)does the same for the main turn. This is called steering. The text arrives with the turn’s next tool result, tagged with the session’sinbox_key. The briefing explains the tag to the model. The terminal steers when you press enter mid-turn.leftoversreturns, once, what the main turn was sent and never read. The next turn starts with it.
expand_command turns a /name ARGS line into the prompt it stands for. A skill name stays as it is. A markdown file in <cfg>/commands/, or in a root’s .agents/commands/ when project_extensions is on, has $ARGUMENTS and $1..$n filled in and each @path replaced by the file’s text.
Agent.expand_command
def expand_command(
line
):The prompt a /name ARGS line stands for, from a skill or a command file, else None.
Agent.reap_panes
def reap_panes(
now:NoneType=None
):Close the /watch pane of each run that ended, or left the list, PANE_LINGER seconds ago. Nothing closes when pane_close_done is false. The monitors pane and panes this agent did not open stay.
Agent.watch
def watch(
target:str=''
):Open a pane following a run’s transcript or monitors. With no target, list what can be watched.
Agent.steer
def steer(
text
):Send text to the running root turn, with its next tool result. Returns ’’ when no turn is listening.
Agent.tell
def tell(
run_id, text:str=''
):Queue text for the sub-agent working run_id. The sub-agent reads it after its next tool call or reply.
Agent.runs_dir
def runs_dir():<cfg>/runs/<session>: one transcript per run plus monitors.log, or None without a config dir.
from ramabana.testing import ScriptedBackend, Step
steered, _ = fake_agent()
sbe = ScriptedBackend(steps=[Step('looking'), Step(tool=('view_file', {'path': '/proj/a.py'})), Step('done')], token_delay=0, tools=steered.tools)
steered._be = steered._be_or_none = lambda job='turn': sbe
test_eq(steered.steer('idle'), '')
g = steered.stream('go'); next(g)
assert steered.steer('check the tests too')
list(g)
tag = f'<user-message key="{steered.inbox_key}">\ncheck the tests too\n</user-message>'
assert next(m['content'] for m in sbe.hist_ if m['role'] == 'tool').endswith(tag)
assert inbox_note(steered.inbox_key) in steered.system_prompt() and steered.run().key == steered.inbox_key
test_eq(steered.leftovers(), [])
sbe.steps = [Step('an answer in two words')]
g = steered.stream('again'); next(g)
steered.steer('one more thing'); list(g)
test_eq(steered.leftovers(), ['one more thing'])
test_eq(steered.leftovers(), [])Every turn leaves a row in the log with a state, however it ended. A resume gives back complete and failed turns whole (REPLAYED), and a row written before state existed counts as complete. A cancelled turn comes back too. The person stopped it, and the next turn builds on its prompt, its partial reply and what was sent during it. Its reply ends with a note that the turn was interrupted. The fragment never reads as a whole answer. An interrupted turn, one whose process ended mid-turn, comes back with a similar note. An abandoned turn, a stream nobody finished reading, does not come back. A budget turn does not come back either.
import json
def _rows(a):
"What survives a restart, which is the file rather than `a.history`."
p = a.history_path
return [json.loads(l) for l in p.read_text().splitlines()] if p and p.exists() else []
dropped = demo_agent()
g = dropped.stream('a question nobody waited for')
chunk = next(g)
g.close()
rows = _rows(dropped)
test_eq(len(rows), 1)
test_eq(rows[0]['state'], 'abandoned')
test_eq(rows[0]['reply'], chunk)
test_eq(dropped.busy, False)kept = demo_agent()
list(kept.stream('a turn that finished'))
row = kept.history[-1]
def replayed(state):
kept.history = [dict(row, state=state, prompt=f'a {state} turn')]
kept.resume_session(kept.session_id)
b = kept._be('turn')
return ' '.join(m.get('content', '') for m in (b._resume_hist or b.hist or []))
for state in REPLAYED: assert f'a {state} turn' in replayed(state), state
said = replayed('cancelled') # the user stopped it, and the next turn builds on it
assert 'a cancelled turn' in said and 'interrupted' in said
assert 'a abandoned turn' not in replayed('abandoned') # a dropped stream is a fragment, not a turn
kept.history = [{k: v for k, v in row.items() if k != 'state'}]
kept.resume_session(kept.session_id)
b = kept._be('turn')
assert 'a turn that finished' in ' '.join(m.get('content', '') for m in (b._resume_hist or b.hist or []))events(prompt) runs one turn, as stream does, and yields typed events instead of markdown. Each event is a plain dict with the name and the camelCase fields of the AG-UI protocol, and a timestamp in milliseconds. A frontend can then show one line for each tool call and keep the prose apart. sse_event encodes one event as a server-sent-events frame.
The events come from the seams that the terminal uses. The text is the chunks of stream. The tool calls are the rows of the activity feed that this run and its sub-agents make, so their arguments hide secret_args, and mask_secrets masks the arguments and the results. A turn gives these events, in this order:
RUN_STARTEDwiththreadId(the session id) andrunId, and at the endRUN_FINISHEDwithresult={'state': ...}. A failed turn ends withRUN_ERRORinstead, withmessageandcode.STEP_STARTEDandSTEP_FINISHEDwithstepNamearound each model step. A step ends when the model gets the results of its tool calls, so text after a tool result starts a new step.TEXT_MESSAGE_START,TEXT_MESSAGE_CONTENTandTEXT_MESSAGE_ENDfor each run of prose. A tool call ends the message before it.TOOL_CALL_START,TOOL_CALL_ARGS(the arguments as JSON in onedelta) andTOOL_CALL_ENDwhen a call starts, andTOOL_CALL_RESULTwhen it returns.toolCallIdis the id of the activity row.parentMessageIdis the text message of the same step, if there is one.- A sub-agent’s tool calls come too. Their
parentMessageIdis thetoolCallIdof the delegate call that started the sub-agent, and they do not end the text message or the step.
A host tool can add its own events while the turn runs. emit(name, value) sends a CUSTOM event, for example to tell the page to refresh. emit_state(snapshot) sends a STATE_SNAPSHOT. Before the run starts, or with no events turn running, both do nothing. The turn runs in a worker thread, so each event arrives when it occurs. If you stop reading early, the turn is cancelled.
Agent.emit_state
def emit_state(
snapshot
):Send a STATE_SNAPSHOT event to each events turn that is running.
Agent.emit
def emit(
name, value:NoneType=None
):Send a CUSTOM event to each events turn that is running.
Agent.events
def events(
prompt, on_registered:NoneType=None, **kw
):One registered turn as AG-UI event dicts. stream runs in a worker thread; closing the generator early cancels the turn.
TurnEvents
def TurnEvents(
thread_id, put, mine:function=<lambda>
):Turn one turn’s text chunks and activity rows into AG-UI events, and give each to put.
agui
def agui(
type, **fields
):One AG-UI event as a plain dict, stamped with the time in milliseconds. Fields that are None are left out.
This turn reads a file and then answers. The file holds a key, and the result shows only the mask. The text after the tool result starts a second step.
from ramabana.testing import ScriptedBackend, Step
key = 'hf_' + 'c' * 34
ea, _ = fake_agent(MemHost({'/proj/a.py': f'TOKEN = "{key}"\n'}))
ebe = ScriptedBackend(steps=[Step(tool=('view_file', {'path': '/proj/a.py'})), Step('it holds a token')], token_delay=0, tools=ea.tools)
ea._be = ea._be_or_none = lambda job='turn': ebe
evs = list(ea.events('what is in a.py?'))
types = [e['type'] for e in evs]
test_eq(types, ['RUN_STARTED', 'STEP_STARTED', 'TOOL_CALL_START', 'TOOL_CALL_ARGS', 'TOOL_CALL_END', 'TOOL_CALL_RESULT',
'STEP_FINISHED', 'STEP_STARTED', 'TEXT_MESSAGE_START', *['TEXT_MESSAGE_CONTENT'] * 4, 'TEXT_MESSAGE_END',
'STEP_FINISHED', 'RUN_FINISHED'])
start, args, _, res = evs[2:6]
test_eq((start['toolCallName'], json.loads(args['delta'])), ('view_file', {'path': '/proj/a.py'}))
assert res['toolCallId'] == start['toolCallId'] and '[SECRET]' in res['content'] and key not in res['content']
test_eq(''.join(e['delta'] for e in evs if e['type'] == 'TEXT_MESSAGE_CONTENT'), 'it holds a token ')
test_eq((evs[0]['threadId'], evs[-1]['result']), (ea.session_id, {'state': 'completed'}))
assert all(isinstance(e['timestamp'], int) for e in evs)A host tool calls emit to send its own event. The event arrives in its place among the others. sse_event gives the frame that a web page reads.
def refresh_page(what: str) -> str:
"Tell the page to reload `what`."
ea.emit('refresh', {'what': what})
return 'ok'
ea.add_tool(refresh_page)
ebe.tools, ebe.steps = ea.tools, [Step(tool=('refresh_page', {'what': 'notes'}))]
evs = list(ea.events('reload the notes'))
custom = next(e for e in evs if e['type'] == 'CUSTOM')
test_eq((custom['name'], custom['value']), ('refresh', {'what': 'notes'}))
types = [e['type'] for e in evs]
assert types.index('TOOL_CALL_END') < types.index('CUSTOM') < types.index('TOOL_CALL_RESULT')
test_eq(sse_event(custom), f'data: {json.dumps(custom)}\n\n')A turn whose model fails ends with RUN_ERROR, after the step closes, and has no RUN_FINISHED. A reader that stops early cancels the turn.
def boom(msg, **kw):
raise RuntimeError('the engine stopped')
yield
fa, fbe = fake_agent()
fbe._stream = boom
evs = list(fa.events('hello'))
test_eq([e['type'] for e in evs][-2:], ['STEP_FINISHED', 'RUN_ERROR'])
assert 'the engine stopped' in evs[-1]['message'] and 'RUN_FINISHED' not in [e['type'] for e in evs]
slow = ScriptedBackend(steps=[Step('word ' * 200)], token_delay=0.01)
fa._be = fa._be_or_none = lambda job='turn': slow
g = fa.events('talk for a while')
test_eq(next(g)['type'], 'RUN_STARTED')
g.close()
assert fa.run().cancelledset_model(name, job) points a job at another model. Changing the turn model carries the live conversation to the new model, and rebuilds the tools when the new model’s budget or profile differs. An unknown name raises.
routed = demo_agent()
routed.set_model('gpt-4.1', 'subagent')
routed.spec_or_none('subagent')routed = demo_agent()
before = routed.model
routed.set_model('gpt-4.1', 'subagent')
test_eq(routed.spec_or_none('subagent').model_id, 'openai/gpt-4.1')
test_eq(routed.model, before)
test_fail(lambda: routed.set_model('no-such-model'))subagent_writes says whether sub-agents get write tools. An Agent turns it on by default, and the sub-agents’ writes still go through this session’s approvals. The terminal’s --no-subagent-writes and /subagents off turn it off. demo_agent turns it off too, and it reads False here. set_subagent_writes changes it while no turn is running.
writer = demo_agent()
writer.subagent_writestest_eq(writer.subagent_writes, False)
writer.set_subagent_writes(True)
test_eq(writer.subagent_writes, True)
writer.set_subagent_writes(False)
test_eq(writer.subagent_writes, False)compact returns the summary, or '' with compactor.note saying why. On a recording the summary is written but the history cannot be replaced, and the note says so.
compacted = demo_agent()
compacted.ask('In one word, what colour is a clear sky?')
compacted.compact(), compacted.compactor.notecompacted = demo_agent()
compacted.ask('In one word, what colour is a clear sky?')
before = len(compacted.history)
compacted.compact()
test_eq(len(compacted.history), before)Here a second agent on the same config folder finds the earlier session and resumes it. Resuming does not reopen folders the session added with add_root.
resumed = demo_agent(cfg=asked.cfg)
[s['id'] for s in resumed.sessions()]resumed = demo_agent(cfg=asked.cfg)
assert [s['id'] for s in resumed.sessions()], 'the earlier turn should have been persisted'
sid = resumed.sessions()[0]['id']
resumed.resume_session(sid)
test_eq(resumed.session_id, sid)
assert resumed.history, 'the turns came back with it'
test_eq(resumed.session_added_roots(sid), [])commands lists every slash command name, built in or registered by an extension, for help text and autocompletion.
Agent.commands
def commands():Every command name, built-in and registered, for a help line or an autocomplete.
Pictures the model sent back, and pictures its tools drew
A model that generates images returns them on the response, not in its text. They arrive as media on the assistant’s history message, and resp_media collects them after the turn; streaming yields only text.
A tool result is text, so a tool that draws writes a file and returns its path. on_media is called with the paths as soon as the tool writes them, so a frontend can show the picture while the turn runs. last_media gives both kinds as {'mime', 'data'} dicts holding the bytes, for a frontend that cannot open a path.
fake_agent from testing is a real Agent whose every job routes to one scripted backend that returns the replies you give it, so a turn runs here with no model at all.
agent, be = fake_agent(host, replies=['`threshold` is in `ramabana/runtime.py`.'])
agent.ask('where is the compaction threshold?')agent, be = fake_agent(host, replies=['no pictures here'])
agent.ask('hello')
test_eq(agent.last_media, [])
be.chat.hist.append({'role': 'assistant', 'content': 'here you go', 'media': [{'mime': 'image/png', 'data': b'\x89PNG\r\n\x1a\nx'}]})
test_eq([m['mime'] for m in agent.last_media], ['image/png'])
first, _ = fake_agent(host); second, _ = fake_agent(host)
assert first.session_id != second.session_idimport tempfilewith tempfile.TemporaryDirectory() as d:
shot = Path(d)/'shot.png'
shot.write_bytes(b'\x89PNG\r\n\x1a\nx')
drawer, _ = fake_agent(host, replies=['drawn'])
seen = []
drawer.on_media = seen.append
drawer._drew([shot])
test_eq(seen, [[shot]])
test_eq(drawer.resp_media, [])
test_eq([m['mime'] for m in drawer.last_media], ['image/png'])Each turn records its plan in _turn_plan: whether the person named tools (explicit) or the model chooses (model), and which tools and skills were named. No tool was named in hello, so the model chose.
agent._turn_planWith no tool named, nothing runs ahead of the model. The message the backend received is the prompt as typed.
print(be.sent[0][-400:])calls and turn_lines show what the turn ran. The scripted reply called no tool, so both are empty.
agent.calls, agent.turn_lines()status() on the fake agent after its turn, showing a few of its keys:
{k: v for k, v in agent.status().items() if k in ('ready', 'busy', 'model', 'ntools', 'pct_full', 'usage')}changes() compares files, not what a tool said about them. Here create_file writes /proj/b.py, and changes() reports it with an empty before-text. A tool that claimed success and changed nothing would not appear.
agent.ask('create a file')
create = next(t for t in agent.tools if t.__name__ == 'create_file')
create('/proj/b.py', 'def b(): return 2\n')
agent.changes()A shell command’s changes are measured the moment it returns, not when the turn ends. The agent reads the open folders before the command and compares them right after. A file that someone else changes later in the turn is not credited to the command. changes() feeds /rewind and the host’s journal, and a comparison at the end of the turn would offer to revert somebody else’s work. In the example the command changes a.py, then elsewhere.py changes outside it, and only a.py is reported.
shell_host = MemHost({'/proj/a.py': 'a = 1\n', '/proj/elsewhere.py': 'e = 1\n'})
shell_agent, _ = fake_agent(shell_host)
shell_agent.before.clear()
run_shell = next(t for t in shell_agent.tools if t.__name__ == 'run_shell')
def _ran(command, cwd=None, timeout=120):
shell_host.files['/proj/a.py'] = 'a = 2\n'
return 0, 'done'
shell_host.run_cmd = _ran
run_shell('touch a.py')
shell_host.files['/proj/elsewhere.py'] = 'e = 2\n'
test_eq(shell_agent.changes(), {'/proj/a.py': ('a = 1\n', 'a = 2\n')})Slash commands are methods of the agent, not of a frontend. Every frontend offers the same set. command returns None for an unknown command. The frontend then passes the line on.
agent.command('/tools').splitlines()[:4]test_eq(agent.command('/nope'), None)
print(agent.command('/model'))The short jobs run away from the turn model, each in a conversation that is thrown away. With fake_agent every job goes to the scripted backend, which answers ONESHOT: followed by the question.
agent.oneshot('is this a question?'), agent.summarise('a long transcript')agent.compact(), agent.compactor.noteMost problems happen on the short jobs, such as a compaction that could not run or a completion the engine refused, where the caller has no exception to catch. That is why the agent collects them in problems.
agent.problems, agent.pct_full, agent.context_usedInline completion
Inline completion suggests the next few lines of code at the cursor, as an editor does. It returns at most four lines. It has to feel instant, and each call is worth little. It runs on the completion job’s model in a throwaway conversation. It runs only when asked for, never on every keystroke. The kernel’s own completions are instant and correct, and this costs a model call.
_clean makes a raw reply safe to insert. Asked for bare code, a completion model often wraps it in a fence, repeats the line it continues, and writes past the point where it can guess. _clean takes the code out of the fence, drops the repeated text, and keeps at most max_lines lines.
before = 'def threshold(ctx, reserve=RESERVE):\n '
_clean('```\n if not ctx: return None\n return max(1, ctx - reserve)\n```', before, 4)test_eq(_clean(' ' + 'x = 1', ' ', 4), 'x = 1')
_clean('a\nb\nc\nd\ne\nf', '', 3)A small local model can write prose and then a fence that the token limit cut off before it closed. Everything before the fence is prose, and inserting it would be worse than suggesting nothing. _clean keeps only the code after the fence.
reply = 'Looking at the code, `area(r)` returns nothing. Let me fix it:\n```python\n return math.pi * r**2'
_clean(reply, before, 4)test_eq(_clean('I will explain first.\n```python', before, 4), '')
_clean('```\ncomplete block\n```', '', 4)A cheap model also repeats what follows the cursor, wraps its reply in tags, introduces it in prose, or thinks aloud first. _clean drops each, and drops a closing bracket or quote only when the code after the cursor already closes it.
test_eq(_clean('a, b)', 'x = foo(', 4, ')'), 'a, b')
test_eq(_clean('len(x)', 'print(', 4, ')'), 'len(x)')
test_eq(_clean("'b': 2}", "d = {'a': 1, ", 4, '}'), "'b': 2")
test_eq(_clean('Here is the completion:\nreturn x + 1', 'def f(x):\n ', 4), 'return x + 1')
test_eq(_clean('<completion>numpy as np</completion>', 'import nu', 4), 'mpy as np')
test_eq(_clean('<think>a value</think>42', 'y = ', 4), '42')
test_eq(_clean('<think>cut off by the token limit', 'y = ', 4), '')
test_eq(_clean('[1], [2]', 'x = [', 4, ']'), '[1], [2]')
test_eq(_clean('a)\nz = 1', 'f(', 4, ')\nz = 1'), 'a')
test_eq(_clean('range(10):\n print(i)\n', 'for i in ', 4), 'range(10):\n print(i)')
test_eq(_clean('answer in answers:\n print(answer)', 'for ', 4), 'answer in answers:\n print(answer)')
test_eq(_clean('output:\n pass', 'if ', 4), 'output:\n pass')
test_eq(_clean('here is None:\n here = 0', 'if ', 4), 'here is None:\n here = 0')
test_eq(_clean('Sure, here it is:\nCompletion:\nreturn 1', ' ', 4), 'return 1')
test_eq(_clean('"<code>x</code>"', 'html = ', 4), '"<code>x</code>"')Completer
def Completer(
agent, max_lines:int=4, max_tokens:int=96
):Inline completion: the completion model, a throwaway conversation, and only when asked for.
Completer asks the completion job’s backend, with the code around the cursor, any related code, the kernel’s variables and the project’s memory in the prompt. When it has nothing, note says why, because an editor that silently inserts nothing looks broken.
comp = Completer(agent)
comp.ready, comp.complete('def a():\n ', 12)comp.notemax_tool_calls and max_steps are per-turn budgets. auto leaves a budget uncapped by the agent.
| budget | range | caps |
|---|---|---|
max_tool_calls |
20 to 400 | tool calls in a turn |
max_steps |
8 to 80 | model calls in a turn |
A value outside the range is clamped to it. A call past the tool budget returns a message telling the model to stop and summarise. /tool-budget and /steps change the budgets mid-session.
The step budget reads two private attributes of urai’s chat: _steps and _budget_exceeded. _steps_over reports a step stop when _budget_exceeded is set and _steps has reached max_steps. urai also sets _budget_exceeded to recover a full window, so a turn that recovers its window after exactly max_steps steps is recorded as a step stop. Ramabana accepts this limit. test_urai_leaves_the_state_the_step_cap_reads fails when a urai release changes either attribute.
runs(active=True) lists what is running, each run with its live children. A finished sub-agent is left out, unless a sub-agent it started is still running.
from ramabana.testing import fake_agent
from ramabana.runtime import Run
a, be = fake_agent(replies=['done'])
root = a._new_run('parent'); root.start(be)
done = Run('child_done', kind='child', parent=root)
going = Run('child_going', kind='child', parent=root)
done.start(be); done.finish(); going.start(be)
test_eq([c['id'] for c in a.runs(active=True)[0]['children']], ['child_going'])
test_eq(len(a.runs()[0]['children']), 2)
deep = Run('grandchild', kind='child', parent=done); deep.start(be)
kids = {c['id']: c for c in a.runs(active=True)[0]['children']}
test_eq(sorted(kids), ['child_done', 'child_going'])
test_eq([c['id'] for c in kids['child_done']['children']], ['grandchild'])Once a run is cancelled, any tool call it attempts is not started, and returns a note saying so.
Cancelling a streamed turn stops it at once. The stream ends with what had arrived, the run leaves the active list, and the turn is recorded with state cancelled. The turn is not finished. No check runs, and no checkpoint is saved. on_registered is called with the run before any output. A host can keep the run id. A cancel there means the model is never called.
from ramabana.testing import FakeBackend, fake_agentclass _BlockingBackend(FakeBackend):
def __init__(self):
super().__init__(replies=['unused'])
self.first, self.release, self.cancelled = threading.Event(), threading.Event(), False
def stream(self, msg, run=None, **kw):
yield 'partial'; self.first.set(); self.release.wait(); yield 'late'
def cancel(self): self.cancelled = True; self.release.set(); return True
a, _ = fake_agent(replies=['unused'])
be = _BlockingBackend()
a._be = lambda job='turn': be
a._be_or_none = lambda job='turn': be
a.cancel_grace = .05
finished, remembered, chunks = [], [], []
a._finish = lambda *args, **kw: finished.append(args)
a._remember = lambda *args, **kw: remembered.append((args, kw))
t = threading.Thread(target=lambda: chunks.extend(a.stream('stop me')), daemon=True)
t.start(); assert be.first.wait(5)
run_id = a.status()['runs'][0]['id']
result = a.cancel(run_id); t.join(5)
test_eq(result['state'], 'cancelled')
test_eq(chunks, ['partial'])
test_eq((finished, a.status()['runs']), ([], []))
test_eq(len(remembered), 1)
test_eq(remembered[0][0][:1], ('stop me',))
test_eq(remembered[0][1], {'state': 'cancelled'})
class _SnapshotBackend(FakeBackend):
def _stream(self, msg, **kw): yield from ('The ', 'The answer', 'The answer')
a, _ = fake_agent(replies=['unused'])
be = _SnapshotBackend()
a._be = a._be_or_none = lambda job='turn': be
test_eq(list(a.stream('repeat')), ['The ', 'answer'])
test_eq(a.history[-1]['reply'], 'The answer')
a, _ = fake_agent(replies=['unused'])
be = _BlockingBackend()
a._be = a._be_or_none = lambda job='turn': be
registered, chunks = [], []
def registered_before_output(run):
registered.append(run.id)
run.cancel(0)
test_eq(list(a.stream('register first', on_registered=registered_before_output)), [])
test_eq((len(registered), be.first.is_set()), (1, False))
a, _ = fake_agent(replies=['unused'])
be = _BlockingBackend()
a._be = a._be_or_none = lambda job='turn': be
def registration_failed(run): raise RuntimeError('registration failed')
test_eq(list(a.stream('bad registration', on_registered=registration_failed)),
['\n\nthe assistant failed (RuntimeError: registration failed)'])
test_eq(a.runs(active=True), [])
test_eq(be.first.is_set(), False)Agent.close
def close():End the session: close panes, background work and the gate, fire session_end once and turn the mods off, cancel active runs, then close the backends and the host.
cancel stops the turn in flight and reports the run it stopped. Nothing is running here, so the report is an idle run with no children.
asked.cancel()test_eq(asked.cancel(), {'id': None, 'state': 'idle', 'children': []})
test_eq(asked.busy, False)close ends the session. It closes watch panes, background delegations and the approval gate, cancels active runs, closes every backend and the host, and releases the session lock. A closed agent reports ready False.
asked.close()
asked.readyasked.close()
test_eq(asked.ready, False)
asked.close()a, be = fake_agent(replies=['done'])
order = []
be.cancel = lambda: order.append('cancel') or True
be.close = lambda: order.append('close')
a._backends[('fake', 'fake/model')] = be
run = a._new_run('shutdown'); run.start(be)
a.close()
test_eq(order[:2], ['cancel', 'close'])prompt = '''<notebook path=a.ipynb>
...
</notebook>
<user-request>
why is it reading a.ipynb and df_norm
</user-request>
<tool-plan route="direct">Answer directly.</tool-plan>
<system-reminder>Verify it.</system-reminder>'''
test_eq(request_text(prompt), 'why is it reading a.ipynb and df_norm')
test_eq(request_text('plain request'), 'plain request')
test_eq(request_text('<user-request></user-request>'), '')class _BusyAgent:
runs = Agent.runs
busy = Agent.busy
for state in ('pending', 'running', 'cancelling'):
a = _BusyAgent()
root = Run('root', state=state)
a._runs, a._runs_lock, a._foreground = {'root': root}, threading.RLock(), 'root'
assert a.busy
for state in ('completed', 'failed', 'cancelled', 'detached', 'terminated'):
a = _BusyAgent()
root = Run('root', state=state)
a._runs, a._runs_lock, a._foreground = {'root': root}, threading.RLock(), 'root'
assert not a.busy
a = _BusyAgent()
root = Run('root', state='completed')
root.child('delegated').state = 'running'
a._runs, a._runs_lock, a._foreground = {'root': root}, threading.RLock(), 'root'
assert a.busy
root.children[0].finish()
assert not a.busyThe history log is one JSONL file shared by every session with the same history_name, and a long-lived one reaches tens of megabytes. This cell replaces the simple history methods with indexed ones. rebuild_index reads the log once and records, for each session, its turn count, title, first and last byte offsets and model, in <history_name>-sessions.json. Each new turn is added to the index as it is written. sessions and session_turns read from the index, and sessions first writes an interrupted row for any turn whose process died (recover_turns).
set_title and summarize_session set a session’s title, the second by asking the summary model. set_muted marks a session as muted. branches and save_branch keep the branch records in <history_name>-branches.json. One lock per log file keeps two agents in one process from interleaving their writes.
compact_history
def compact_history(
cfg, # the config folder holding the log
history_name:str='agent', # names the conversation, as for `Agent`
backup:bool=True, # keep the old log and index as `<name>.pre-compact`
force:bool=False, # go on although another live process holds a session
wait:float=10.0, # seconds to wait for a writer to finish before giving up
):Rewrite the log once: a picture’s bytes become [image] and results over RESUME_DETAIL move to the session’s details file. Returns the sizes and counts.
HistoryBusy
def HistoryBusy(
*args, **kwargs
):The log cannot be compacted now: a writer holds it, or another live process holds a session.
Agent.session_turns
def session_turns(
sid
):One conversation’s turns, read from its indexed byte ranges and filtered by session, with long tool results from its details file.
Agent.sessions
def sessions():Conversations from the index, newest first, titled by the user or the first prompt. A turn whose process died is recovered first.
Agent.recover_turns
def recover_turns():Write an interrupted row, with its prompt, for each turn whose process died before its row. Returns how many were written.
Agent.session_count
def session_count():How many turns the whole log holds, from the index rather than from a parse of it.
Agent.refresh_history
def refresh_history():Reload the history log and the session and branch records, and return the sessions.
Agent.summarize_session
def summarize_session(
sid:NoneType=None, force:bool=False
):Title a session with the summary model, again each time its turn count doubles, unless the title was set by hand.
Agent.set_muted
def set_muted(
muted:bool=True, sid:NoneType=None
):Mark a session muted, or not.
Agent.set_title
def set_title(
text, sid:NoneType=None
):Set a session’s title by hand. summarize_session never replaces a title set this way.
Agent.session_meta
def session_meta(
sid:NoneType=None
):A session’s stored metadata: title, whether it is muted, and the folders it ran in.
Agent.rebuild_index
def rebuild_index(
force:bool=False
):Index the log’s conversations with byte ranges, or in-memory turns without a log.
Agent.save_branch
def save_branch(
branch_id, revision:NoneType=None, **changes
):Record one branch. A stale revision raises BranchChanged and writes nothing.
Agent.branches
def branches():Every branch this history knows, newest first, with main always present.
Agent.branch_meta
def branch_meta(
branch_id:str=''
):One branch’s parentage, revision and context manifest. main is the conversation as recorded.
Agent.branches_path
def branches_path():<cfg>/<history_name>-branches.json, the branch records, or None without a config dir.
Agent.sessions_path
def sessions_path():<cfg>/<history_name>-sessions.json, the session index, or None without a config dir.
model_title
def model_title(
text, n:int=80
):A title the summary model wrote, without **bold**, a Title: label, quotes or what follows a spaced --- rule, in at most n characters.
compact_history(cfg) rewrites a log written before pictures were logged as [image] and before long results went to the details file. It holds the lock _append_line takes for the whole pass, streams the log into a temporary file beside it, and replaces the log in one rename. A row with nothing to change keeps its bytes. In the others, a picture’s bytes become [image], and each result over RESUME_DETAIL goes whole to its session’s details file, in the shape _slim writes, unless that file holds its id already; the row keeps the start of the result. The session index is rebuilt afterwards and keeps its titles, mute flags and folders. A writer that queued on the old file notices the replacement and appends to the new one.
Another live process holding a session stops the pass, unless force is set, and a writer that does not finish within wait seconds does too. The old log and index stay as .pre-compact files unless backup=False. ramabana history compact runs it. A row _slim leaves over ROW_MAX also sends its prompt to the details file, and hydrate_turns puts it back.
cdir = Path(tempfile.mkdtemp())
cold = {'at': 1.0, 'session': 's1', 'turn_id': 't1', 'state': 'complete', 'model': 'm', 'reply': 'ok',
'prompt': str([b'\x89PNG' * 5000, 'what is this?']),
'activity': [{'id': 'a1', 'tool': 'run_shell', 'detail': 'x' * 5000}]}
(cdir/'agent-history.jsonl').write_text(json.dumps(cold) + '\n')
cgot = compact_history(cdir, backup=False)
cgotThe log is a fraction of its size, and the session reads back as it did: the prompt in its [image] form, the result whole.
cag, _ = fake_agent(cfg=cdir)
cturn = cag.session_turns('s1')[0]
test_eq(cgot['after'] < cgot['before'] / 10, True)
test_eq(len(cturn['activity'][0]['detail']), 5000)
turn_prompt(cturn)A picture generate_image saves to a path is recorded like any write, so /rewind deletes a picture the turn created.
def generate_image(prompt: str, path: str = '') -> str: return path or 'media/generated-1.png'
ga, _ = fake_agent()
draw = ga._record(generate_image)
draw('x'); test_eq(ga.before, {})
draw('x', path='/proj/new.png'); assert '/proj/new.png' in ga.new and '/proj/new.png' in ga.beforeA tool’s read_only copy is recorded too. A read-only view, such as a read-only sub-agent or plan mode, is given that copy, and its calls reach the activity feed and the history like any other.
from shalya import read_only as _read_only
def read_url(url: str, remember: bool = True) -> str: return f'read {url}'
def _no_save(url: str) -> str: return read_url(url, False)
_no_save.__name__ = 'read_url'; read_url.read_only = _no_save
def generate_image(prompt: str, path: str = '') -> str: return path or 'media/generated-1.png'
def _draw_only(prompt: str) -> str: return generate_image(prompt)
_draw_only.__name__ = 'generate_image'; generate_image.read_only = _draw_only
ra, _ = fake_agent()
view = {t.__name__: t for t in _read_only([ra._record(read_url), ra._record(generate_image)])}
view['read_url']('https://x.test'); view['generate_image']('rama')
test_eq([r['tool'] for r in ra.activity.rows()], ['read_url', 'generate_image'])
test_eq(ra.activity.rows()[0]['args'], {'url': 'https://x.test'})
rr = ra._record(read_url); assert ra._record(rr) is rr and rr.read_only._recordedfrom shalya import LocalHost
from tempfile import TemporaryDirectory
with TemporaryDirectory() as d, TemporaryDirectory() as c:
root = Path(d); png = b'\x89PNG\r\n\x1a\n' + bytes(8)
def generate_image(prompt: str, n: int = 1, path: str = '') -> str:
for t in write_targets('generate_image', {'path': path, 'n': n}): (root/t).write_bytes(png)
return 'drawn'
ga, _ = fake_agent(LocalHost([root], index=False), cfg=Path(c))
ga._record(generate_image)('x', n=2, path='img.png')
test_eq(sorted(ga.new), ['img-2.png', 'img.png'])
ga._checkpoint()
ga.rewind(ga.current_turn_id, what='files')
test_eq(sorted(p.name for p in root.iterdir()), [])
pv = preview_for('generate_image', {'prompt': 'rama', 'n': 2, 'path': 'img.png'})
assert 'img.png' in pv and 'img-2.png' in pv, pv
test_eq(write_targets('create_file', {'path': 'a.py'}), ['a.py']); test_eq(write_targets('generate_image', {'prompt': 'x'}), [])
test_eq(write_targets('generate_image', {'path': 'a.png', 'n': 'two'}), ['a.png'])
rr = ra._record(read_url)
@functools.wraps(rr)
def other(*a, **kw): return rr(*a, **kw)
assert ra._record(other) is not other and ra._record(rr) is rr
rb, _ = fake_agent(); assert rb._record(rr) is not rr
n0 = len(rb.activity.rows()); rb._record(rr)('https://y.test'); test_eq(len(rb.activity.rows()), n0 + 1)Each tool call is saved in the log with its string arguments whole, up to ARG_TEXT (2,000) characters with newlines kept, so a replay of the call has the full image prompt or file text. A resumed context still shows each argument clipped to one short line.
from tempfile import TemporaryDirectory
with TemporaryDirectory() as d:
ha, _ = fake_agent(cfg=Path(d))
prompt = ('Pahari miniature, Kangra school; ' * 50)[:1499] + '\nno text'
act = ha.activity.start('generate_image', {'prompt': prompt, 'size': '1024x1536', 'n': 1})
ha.activity.finish(act, 'media/generated-1.png')
ha._remember('draw rama', 'drawn')
row = json.loads(ha.history_path.read_text().splitlines()[-1])
test_eq(row['activity'][-1]['args'], {'prompt': prompt, 'size': '1024x1536', 'n': 1})
test_eq(_arg('x' * (ARG_TEXT + 5)), 'x' * ARG_TEXT + '…')
resumed = _resumed_acts([{'tool': 'generate_image', 'args': {'prompt': prompt}}])
assert len(resumed) < 700 and '\nno text' not in resumed, resumedBecause the log is large, _load_history reads only its last HISTORY_TAIL bytes (8 MB) and keeps at most the last HISTORY_TURNS (2,000) turns, whichever gives fewer. The model’s context is rebuilt from that tail. A session picker needs more, since the conversations worth offering are mostly older than the tail, so session_turns seeks to the session’s byte range from the index. The range is a filter, not a list of lines, because two live sessions interleave in one log.
import json as _json, tempfile as _tf
_cfg = Path(_tf.mkdtemp())
_pad = 'x'*400
_rows = ([{'at':1,'session':'old','prompt':f'ancient {_pad}','reply':'r','model':'gpt-mini'}] +
[{'at':10+i,'session':'new','prompt':f'{i} {_pad}','reply':'r','model':'gpt-mini'} for i in range(30)])
(_cfg/'tail-history.jsonl').write_text('\n'.join(_json.dumps(r) for r in _rows)+'\n')
_hold, HISTORY_TAIL = HISTORY_TAIL, 2000
_a = Agent(NullHost(['.']), cfg=_cfg, history_name='tail', extensions=False)
test_eq({t['session'] for t in _a.history}, {'new'})
test_eq([s['id'] for s in _a.sessions()], ['new', 'old'])
test_eq(_a.sessions()[1]['turns'], 1)
test_eq(_a.session_turns('old')[0]['prompt'][:7], 'ancient')
HISTORY_TAIL = _hold
# `ensure_ascii=False` writes U+2028 raw, and `str.splitlines` breaks a record there
_sep = [{'at':1,'session':'s','prompt':'a\u2028b','reply':'r','model':'m'}, {'at':2,'session':'s','prompt':'c','reply':'r','model':'m'}]
(_cfg/'sep-history.jsonl').write_text('\n'.join(_json.dumps(r, ensure_ascii=False) for r in _sep)+'\n{broken\n', encoding='utf-8')
_s = Agent(NullHost(['.']), cfg=_cfg, history_name='sep', extensions=False)
test_eq([t['prompt'] for t in _s.history], ['a\u2028b', 'c'])
test_eq([t['prompt'] for t in _s.session_turns('s')], ['a\u2028b', 'c'])A tool result longer than RESUME_DETAIL (600 characters) is written whole to <history_name>-details/<session>.jsonl, before the turn’s row, and the row keeps its first 600 characters and a details reference. A resume replays only those 600 characters, so the row alone resumes the session. session_turns puts the whole results back, for a branch editor or a transcript. A row written before this has its results inline and reads as it always did. hydrate_turns(cfg, turns) does the putting back for any rows read from <cfg>’s log, so a reader without an agent, such as Dhrona, sees whole results too. The session index lists each session’s byte ranges in spans, so session_turns reads a session’s own rows rather than every row between its first turn and its last. An index row written before spans, or one past MAX_SPANS ranges, falls back to that first-to-last range.
import itertools, json as _json, tempfile as _tf
_dc = Path(_tf.mkdtemp())
da, _ = fake_agent(cfg=_dc)
for out in ('x' * 5000, 'y' * RESUME_DETAIL, 'short'):
da.activity.finish(da.activity.start('run_shell', {'command': 'ls'}), out)
da._remember('list', 'listed')
row = _json.loads(da.history_path.read_text().splitlines()[-1])
test_eq(row['details'], f'agent-details/{da.session_id}.jsonl')
test_eq([len(a['detail']) <= RESUME_DETAIL + 40 for a in row['activity']], [True] * 3)
test_eq([a['detail'][:1] for a in row['activity']], ['x', 'y', 's'])
test_eq(row['activity'][1]['detail'], 'y' * RESUME_DETAIL)
test_eq(len(_json.loads((_dc/row['details']).read_text())['details']), 1)
test_eq(da.history[-1]['activity'][0]['detail'], _clip('x' * 5000))
whole = da.session_turns(da.session_id)
test_eq(whole[-1]['activity'][0]['detail'], _clip('x' * 5000))
test_eq(_as_messages(whole), _as_messages([da.history[-1]]))
rows = [_json.loads(l) for l in da.history_path.read_text().splitlines()]
test_eq(hydrate_turns(da.history_path.parent, rows)[-1]['activity'][0]['detail'], _clip('x' * 5000))
with open(_dc/row['details'], 'a') as f: f.write('{"turn_id": "t", "deta')
test_eq(da.session_turns(da.session_id)[-1]['activity'][0]['detail'], _clip('x' * 5000))
(_dc/row['details']).rename(_dc/'gone.jsonl')
test_eq(da.session_turns(da.session_id)[-1]['activity'][0]['detail'], row['activity'][0]['detail'])
test_eq(hydrate_turns(_dc, [{'details': '/etc/passwd', 'activity': []}, {'details': '../x/y', 'activity': []}])[0]['activity'], [])
na, _ = fake_agent()
na.activity.finish(na.activity.start('run_shell', {'command': 'ls'}), 'z' * 5000)
test_eq(na._slim({'turn_id': 't', 'activity': na.activity.rows()}), {'turn_id': 't', 'activity': na.activity.rows()})
_sc = Path(_tf.mkdtemp())
_rs = [{'at': i, 'session': s, 'prompt': f'{s}{i}', 'reply': 'r', 'model': 'm'} for i, s in enumerate('aabab')]
(_sc/'sp-history.jsonl').write_text(''.join(_json.dumps(r) + '\n' for r in _rs))
sp = Agent(NullHost(['.']), cfg=_sc, history_name='sp', extensions=False)
ends = list(itertools.accumulate(len(_json.dumps(r)) + 1 for r in _rs))
test_eq(sp.rebuild_index()['a']['spans'], [[0, ends[1]], [ends[2], ends[3]]])
test_eq(sp.rebuild_index()['b']['spans'], [[ends[1], ends[2]], [ends[3], ends[4]]])
test_eq([t['prompt'] for t in sp.session_turns('a')], ['a0', 'a1', 'a3'])
with open(sp.history_path, 'a') as f: f.write(_json.dumps({'at': 5, 'session': 'b', 'prompt': 'b5', 'reply': 'r', 'model': 'm'}) + '\n')
test_eq(sp.rebuild_index()['b']['spans'][-1], [ends[3], sp.history_path.stat().st_size])
test_eq([t['prompt'] for t in sp.session_turns('b')], ['b2', 'b4', 'b5'])
test_eq(sp.rebuild_index(), sp.rebuild_index(force=True))
_idx = _json.loads(sp.sessions_path.read_text())
for r in _idx['sessions'].values(): r.pop('spans')
sp.sessions_path.write_text(_json.dumps(_idx))
test_eq([t['prompt'] for t in sp.session_turns('a')], ['a0', 'a1', 'a3'])
with open(sp.history_path, 'a') as f: f.write(_json.dumps({'at': 6, 'session': 'a', 'prompt': 'a6', 'reply': 'r', 'model': 'm'}) + '\n')
assert 'spans' not in sp.rebuild_index()['a']
test_eq([t['prompt'] for t in sp.session_turns('a')], ['a0', 'a1', 'a3', 'a6'])
import ramabana.history_core as _core
_hold, _core.MAX_SPANS = _core.MAX_SPANS, 1 # `_add_span` reads the limit from `history_core`
assert 'spans' not in sp.rebuild_index(force=True)['a']
test_eq([t['prompt'] for t in sp.session_turns('a')], ['a0', 'a1', 'a3', 'a6'])
_core.MAX_SPANS = _hold
_lc = Path(_tf.mkdtemp())
la, _ = fake_agent(cfg=_lc); lb, _ = fake_agent(cfg=_lc)
for x in (la, lb, la): x._remember('hi', 'there')
test_eq(len(la.rebuild_index()[la.session_id]['spans']), 2)
test_eq(len(la.session_turns(la.session_id)), 2)add_chat_callback attaches one of the named callbacks in CHAT_CALLBACKS (see runtime) to the turn chat, and to every chat that later replaces it. chat_callback is the same call under an older name.
Agent.chat_callback
def chat_callback(
name
):Attach one built-in callback to the current turn backend.
Agent.add_chat_callback
def add_chat_callback(
name
):Attach a named Rishi callback to the turn chat and every chat that replaces it.
status() returns everything a status bar shows, in one dict: readiness, whether a turn is running, the model and profile, the budgets, the approval mode, context use, cost, the plan, recent activity, the waiting approval and the active runs.
bar = demo_agent()
{k: v for k, v in bar.status().items() if k in ('ready', 'busy', 'model', 'tool_budget')}st = bar.status()
assert 'claude-sonnet-4-5' in str(st['model'])/tools and /model on the demo agent. A line that is not a slash command also returns None.
bar.command('/tools').splitlines()[:3]test_eq(bar.command('/nope'), None)
test_eq(bar.command('not a command'), None)compile_conversation gives the provider messages for a reshaped conversation: the stored turns, minus what a person discarded, with their own words in place of any prose they rewrote. A call and its result move together, and neither can be rewritten, because editing one would claim work that never ran.
shaper.compile_conversation()['messages']whole = shaper.compile_conversation()['messages']
test_eq([m['role'] for m in whole], ['user', 'assistant'])
pid = shaper.conversation_parts()[-1]['part_id']
test_fail(lambda: shaper.compile_conversation(manifest={pid: False}))
fewer = shaper.compile_conversation(manifest={pid: 'discard'})['messages']
test_eq([m['role'] for m in fewer], ['user'])
mine = shaper.compile_conversation(rewrites={pid: 'Cyan, actually.'})['messages']
assert 'Cyan, actually.' in str(mine[-1])reshape makes a reshaped conversation the active branch. The turn log still records what happened; only the model’s context changes.
pid = shaper.conversation_parts()[-1]['part_id']
shaper.reshape(rewrites={pid: 'Cyan, actually.'})logged = len(shaper.history)
pid = shaper.conversation_parts()[-1]['part_id']
br = shaper.reshape(rewrites={pid: 'Cyan, actually.'})
assert br['branch_id'] and br['branch_id'] != 'main'
test_eq(shaper.current_branch_id, br['branch_id'])
test_eq(len(shaper.history), logged)A branch is stored as its parent point plus its manifest, so switching rebuilds the messages rather than copying them. main, the conversation as recorded, is always there to return to. /branches lists the branches and /branch NAME switches.
shaper.switch_branch('main')
shaper.current_branch_id, [b['branch_id'] for b in shaper.branches()]shaper.switch_branch('main')
test_eq(shaper.current_branch_id, 'main')
ids = [b['branch_id'] for b in shaper.branches()]
assert 'main' in ids, ids
test_eq(shaper.switch_branch('main')['branch_id'], 'main')What a read may send
Every tool result goes to the model, and for a hosted model that means to another company’s servers. mk_host gives the host a read_guard built by masking_guard, and shalya asks it about every read the tools make: files, notebook cells, search hits, diffs, web pages, shell output and Python output. The guard answers with the text to send instead, or a refusal.
Secrets are masked in every read, always, whatever --pii says, by mask_secrets (its shapes are listed with the shell rules above). A key is found by its prefix on a word boundary, so one glued to a word character, such as XSK_sk_live_…, is not; a key with no fixed prefix, such as an AWS secret access key or a Hetzner token, is never found, and the shell rules and the file tools’ refusal of credential paths are what keep those out.
Personal data is masked only where --pii asks, which needs --vault, and only in shell, Python, URL and page reads sent to a hosted model, that is, when ReadCheck.local is false or unknown. With redact the guard masks rahasya’s personal-data kinds; with refuse it withholds a read that holds any. Code reads (view_file, view_cell, grep, diffs) get their secrets masked and nothing else, because the agent edits files by exact text: an email address masked in a file it reads would make every oldText around it match nothing. A local model sees personal data as it is. A key masked in a file can still break an edit whose oldText spans it; that edit fails and says so, and is the price of never sending the key. secret_denial stops the worse case, a write tool putting [SECRET] back over the key; a shell or Python write such as sed -i is not checked.
The guard learns which model reads from the host’s model_local, which mk_agent points at Agent.model_local: a sub-agent’s model while one runs, else the turn’s.
Agent.model_local
def model_local():(local, model) of the model making the call in flight, for the read guard: a sub-agent’s while one runs, else the turn’s.
guard_reads
def guard_reads(
host
):host with masking_guard as its read_guard, unless it has one; a vault host’s --pii policy gates personal data.
masking_guard
def masking_guard(
policy:NoneType=None, # callable -> `(pii, pii_ner)`, asked on each read; None masks secrets only
):A host read_guard that masks secrets in every read, and personal data in the shell, Python and web reads a hosted model gets.
from shalya.core import ReadCheckThe same printed text, read three ways under --pii redact: shell output to a hosted model loses the key and the address, shell output to a local model loses only the key, and a file read to a hosted model loses only the key.
printed = 'OPENAI_API_KEY=sk-test' + 'q' * 30 + '\nmail ada@example.com'
redacting = masking_guard(lambda: ('redact', False))
reads = dict(hosted=ReadCheck('ls', 'run_shell', 'shell', lambda: printed, local=False),
local=ReadCheck('ls', 'run_shell', 'shell', lambda: printed, local=True),
code=ReadCheck('/proj/a.py', 'view_file', 'text', lambda: printed, local=False))
sent = {k: redacting(r) for k, r in reads.items()}
senttest_eq(sent, dict(hosted='OPENAI_API_KEY=[SECRET]\nmail [EMAIL]', local='OPENAI_API_KEY=[SECRET]\nmail ada@example.com',
code='OPENAI_API_KEY=[SECRET]\nmail ada@example.com'))
test_eq(masking_guard()(ReadCheck('a.py', 'view_file', 'text', lambda: 'x = 1')), None)
withheld = masking_guard(lambda: ('refuse', False))(reads['hosted'])
withheldAssembly
mk_agent is the one call that builds a working session: a WorkspaceHost over the named folders, an Approvals gate in the mode approve names (none builds no gate), and an Agent on both. The terminal and the MCP server start here, and so can any application that runs agent jobs. mk_host builds just the host, with the web, vault, API-specification and PII options, and gives it masking_guard as its read_guard unless the caller passes one.
Pass cfg= for history, skills and saved approval rules, read_roots= for folders to search but never write, python='off' to withhold Python, and any other Agent option by keyword. The agent starts without a code index; host_kw controls it. The index shows a session driven from Python.
mk_agent
def mk_agent(
roots:tuple=('.',), model:NoneType=None, approve:str='ask', # ask | edits | auto | off | none (no gate)
web:bool=True, # wire the web tools to fossick
vault:bool=False, # keep reads in a vishalakshi vault
spec:bool=False, # let the agent load OpenAPI/Azure/GCP specs
read_outside:bool=False, # read-only tools may name any path
pii:str='off', # off | redact | refuse PII from the vault, and from shell, Python and web reads a hosted model gets
pii_ner:bool=False, # gate titled names too, not only patterns
host_kw:NoneType=None, # to `mk_host`: `index` (off: `sync_index` runs it after the model), `warm`, `vault=<path>`
read_roots:tuple=(), # folders the read tools search and no write touches
python:str='host', # 'host' runs `run_python` in this process, 'off' withholds it
rules_path:NoneType=None, # saved allow/deny rules; None shares `<cfg>/approvals.json` with every session on that cfg
timeout:NoneType=None, # seconds an ask waits for an answer; None waits forever
no_listener:str='refuse', # an ask with nobody listening: 'refuse', or 'wait' for a listener
on_timeout:str='refuse', # an ask nobody answers in time: 'refuse' or 'allow'
**kw
):A host over roots and an Agent on it, gated as approve says; no code index until asked.
mk_host
def mk_host(
roots:tuple=('.',), approvals:NoneType=None, # gates writes on this host
web:bool=True, # wire the web tools to fossick
vault:bool=False, # keep reads in a vishalakshi vault
spec:bool=False, # let the agent read and call an API spec
read_outside:bool=False, # read-only tools may name any path
pii:str='off', # off | redact | refuse PII from the vault, and from shell, Python and web reads a hosted model gets
pii_ner:bool=False, # gate titled names too, not only patterns
**kwargs
):The workspace host shared by the terminal, MCP and ACP, with secrets masked in every read unless read_guard says otherwise.
An app that only wants the model, such as a tutor that asks one-shots, does not want the harness around it. model_agent makes that Agent: it reads nothing it was not given, refuses each approval, and has no sub-agents, extensions, skills, learned notes, compaction or polling. turn names the turn model, host defaults to a NullHost, and kw goes to Agent and wins over these defaults, for example only_tools or max_cost.
model_agent
def model_agent(
turn:NoneType=None, sp:str='', host:NoneType=None, **kw
):An Agent that only calls the model: read-only, approvals refused, no sub-agents, extensions, skills, learned notes, compaction or polling. kw goes to Agent and wins.
ma = model_agent('claude-haiku-5-5', sp='You are a tutor.')
test_eq((ma.readonly, ma.approvals.mode, ma.routing.turn), (True, 'ask', 'claude-haiku-5-5'))
test_eq(model_agent(max_cost=1.).max_cost, 1.)