Skip to content

Patterns

These are the conventions the Felix code follows. They explain why a piece of code sits where it does and why it refuses what it refuses. Follow them when you add to it.

Each module owns a decision, and other modules do not make it again. The agent loop owns the order of checkpoints, gates and tool execution. The harness owns whether a session’s history may continue. The API’s thread store owns revisions, leases and limits. The terminal client owns its file tools and the write prompt. See Architecture for the full table.

  • A rule lives where the outcome is decided, even when several callers need it. The interrupted-call close-out is in the harness, and both the API and the terminal client switch it on.
  • A test that crosses modules lives with the module that owns the result, not in a shared folder.
  • A new package is added only when code has a second, independent consumer.
  • index.ts files are public facades that re-export; implementation lives in named modules.

The runtime packages decide how a run proceeds, never what it is allowed to touch. Anything that varies by app, by platform or by test is a parameter.

Passed in Where Supplied by
The model RunOptions.model The app, from its provider configuration.
Tools RunOptions.tools The app. The API’s HTTP caller cannot choose them.
The gate and output hook beforeTool, afterTool The app, such as the terminal client’s write prompt.
Storage The Session passed to prompt Memory, a locked session file, or a hosted thread.
Transport workersAiModel({ run }), workersAiRestModel({ fetch }) The Worker’s AI binding, or fetch.
Thread storage The thread store’s transactional storage port Durable Object storage in the Worker, memory in tests.
Time and randomness limits.now, retry.random, retry.sleep Defaults to the real clock and timer; tests pass their own.

The terminal client’s write prompt is a complete example: a beforeTool built from the workspace and a confirm function, which blocks the call when the answer is no, and also ends the run when the answer is 'stop'.

export function confirmWrites(workspace: string, confirm: (summary: string) => Promise<WriteAnswer>): NonNullable<RunOptions['beforeTool']> {
return async invocation => {
const summary = describeWrite(workspace, invocation.name, invocation.input);
if (summary === undefined) return;
const answer = await confirm(summary);
if (answer === 'stop') return { block: true, reason: REFUSED_AND_STOPPED, stop: true };
if (answer !== true) return { block: true, reason: REFUSED };
};
}

The loop knows nothing about files, users or prompts. It awaits the gate and acts on its answer.

Checkpoints are awaited before side effects

Section titled “Checkpoints are awaited before side effects”

A step does not begin until the step before it is saved. The loop awaits the session append for the assistant’s reply before any tool in it runs. In a sequential batch it awaits each tool result before the next call starts; a parallel batch gates every call first, then runs them together. Events are awaited too, so a slow consumer slows the run instead of falling behind it.

What happens inside one run, model call by model callThe API route starts a run with at most 20 model turns, under an abort signal that combines the caller's stop with a ten-minute timeout. The harness appends the prompt to the session, then hands the conversation to the agent loop. Each turn first checks the run's token and time budgets, when the application sets any, and ends the loop if one is spent. The loop checkpoints queued steering before the harness prepares the model-visible context. If that poll was empty, steering that arrives during compaction can still reach this turn. The model is called with the system prompt, the visible messages and the declared tools, and its text streams to the client as it arrives. A context overflow is retried once after compaction, and a transient provider failure is retried under the retry policy, but only while nothing has streamed. The reply is checkpointed to the session, and only then announced as a message frame and followed by usage. On the last allowed turn, any calls the reply still makes are recorded as not run. Otherwise the tool batch runs: each call gets a tool_start frame, passes the execution gate, executes, and has its result checkpointed in call order. After the batch the loop drains steering, recorded as user messages, so a person can redirect the run between model turns. A reply with no calls, or a batch whose every result asked to end the run, ends the run as complete unless steering arrived; running out of turns ends it as limit. A stop, the ten-minute timeout, or a failed checkpoint, event or observer throws instead: text already streamed is kept as a stopped reply, unanswered calls are recorded as not run, and no end frame is sent; unless the client itself went away, the stream carries a run_failed error frame instead.Tools, behind beforeToolModelSessionAgent loopHarness prompt()Client streamalt[overflow or transient failure, nothing streamed yet]alt[last allowed turn and the reply has calls][the reply has calls][no calls and no steering]loop[each model turn, until end or 20 turns]A stop, the timeout, or a failed checkpoint throws instead,and no end frame is sent.run request: the route calls prompt(), 20 turns, 10-minute abortappend the user promptrunAgent(conversation)run budgets spent? then end the loopprepareContext, compact if the window demands itcompleteModel(system, visible messages, tools)text and reasoning, streamed through the looperrorretry, once after compaction or under the retry policyreply and usagecheckpoint the reply, awaitedmessage, then usageeach call recorded as not runthe batch: tool_start, gate, executeresults, in call ordercheckpoint each result, awaiteddrain steering as user messagesend, completeend, limit, once the turns run outOne run, model call by model call
What happens inside one run, model call by model call?Drawn from docs/diagrams/run-turn.mmd, which follows packages/agent/src/run.ts:runAgent, packages/harness/src/prompt.ts:prompt, apps/api/src/routes/chat.ts:chatResponse.
  • A message is added to the run’s conversation and announced only after its checkpoint succeeds.
  • A failed checkpoint, event or observer stops the run. It is never turned into a tool error the model could retry around.
  • When a tool already ran and its result could not be saved, the run stops and the call is left without a result. Nothing replays a call that is not replay-safe. A lost hosted run resumed with FELIX_RESUME_RUNS=on runs its replay-safe calls (Felix’s own reads, and writes keyed by their operation id) again; any other call is closed as having an unknown outcome.
  • Parallel batches keep the order: results are checkpointed in call order, and on any failure the run waits for every running call to settle before it stops.

Input is validated at every boundary, and anything that does not fit is refused rather than guessed at. The one repair is narrow: inside tool-argument strings, raw control characters and backslashes JSON cannot escape are escaped once, because models make those two mistakes often.

  • Run options are validated before the session is read, and history is validated before your prompt is appended. Invalid configuration never reaches the model.
  • Messages are parsed whether they come from a provider, storage or HTTP. Duplicate call IDs and blank names are refused. Arguments that are still not a JSON object after that repair are not run: the model reads why, with what it sent.
  • An unknown field in a run request, an unknown frame type or an unsupported protocol version is an error.
  • A gate answer that is neither nothing nor a well-formed block stops the run.
  • A stored compaction that points past the transcript, or splits a call from its result, is refused. A hosted thread log with a missing or misplaced message fails with a storage error instead of returning partial history.
  • No result is ever invented to make a session valid. Closing interrupted calls is opt-in, and its results say plainly that the outcome is unknown.
  • Provider errors carry at most an HTTP status, never the response body, which can echo user input.

Where an error is the model’s to fix, such as invalid tool arguments or an unknown tool, it becomes an error result the model can read. Where it is not, the run stops.

Every operation takes an AbortSignal, and tools receive the run’s signal. JavaScript cannot stop arbitrary asynchronous work from the outside, so code checks the signal again after each await that matters: after the start event, after parsing, after the gate, and before each result is saved.

  • Cancellation before an append prevents it. An append that already finished stays.
  • A cancelled run does not start the model again, and does not turn the cancellation into a tool error.
  • A time limit can be a signal combined with the caller’s, as the API does with AbortSignal.any and AbortSignal.timeout for its ten-minute limit. That is not a limits budget: a run that hits it fails (a run_failed error frame, run outcome failed) rather than ending with limit.
  • Adapters, gates and tools must honor the signal they are given. The core cannot undo a side effect that already happened.

A test lives in its workspace’s src/test/, at the path of the module it covers: src/conversation/store.ts is tested by src/test/conversation/store.test.ts. A browser scenario is name.browser.ts in the same tree. Tests assert what someone would observe, such as the saved messages or how many times a tool ran, and control timing by holding promises open rather than sleeping. See Testing.

A package is used through the paths in its package.json exports, and nothing else. Providers and test fixtures have their own export paths, so a runtime import of @felix/ai does not bring them along. Within a workspace, imports are relative; across workspaces, they name a package. No workspace imports an app.

pnpm check enforces this before the type checks run: it fails on an undeclared dependency, a path that is not exported, a relative import that leaves its workspace, and a Node or Cloudflare import in a package’s production code.