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.
One owner per decision
Section titled “One owner per decision”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.tsfiles are public facades that re-export; implementation lives in named modules.
Policy is passed in
Section titled “Policy is passed in”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.
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=onruns 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.
Validate, and refuse what does not fit
Section titled “Validate, and refuse what does not fit”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.
Cancellation is cooperative
Section titled “Cancellation is cooperative”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.anyandAbortSignal.timeoutfor its ten-minute limit. That is not alimitsbudget: a run that hits it fails (arun_failederror frame, run outcomefailed) rather than ending withlimit. - Adapters, gates and tools must honor the signal they are given. The core cannot undo a side effect that already happened.
Tests mirror the code
Section titled “Tests mirror the code”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.
Only public exports cross packages
Section titled “Only public exports cross packages”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.
© Felix. All rights reserved.