engine
js/internal/commands/code/engine.ts
internal:commands/code/engine — turns, approvals, and sub-agents for fino code.
CodeEngine is the coding agent without its presentation. It composes the
reusable AI layers rather than owning state of its own:
- each thread is a
fino:ai/sessionconversation in oneAtomicStore, so history, runs, suspensions, and crash recovery are the session layer's; - titles and seen markers are
fino:ai/threadsmetadata; - the tools are
fino:ai/toolsbounded to the project root, Fino's own commands frominternal:commands/code/fino-tools, and thefino:ai/subagentspool opened on the same thread id.
The agent is rebuilt for every run, so the mode decides the tool set and approval policy of each run while the durable thread keeps the conversation.
Turns
A turn is not one parent run. When the parent's run finishes while
sub-agents are still working, the engine waits for them and continues the
thread with a settlement message so the parent reviews every report,
failure, or question. The turn ends when the parent is done and no
sub-agent is working or awaiting its review, or after
MAX_SETTLEMENT_RUNS such continuations.
Approvals stop a turn wherever they arise. A gated parent tool suspends its
run; a gated sub-agent tool parks the turn once its siblings stop working.
Either way the turn returns suspended with the pending approvals, and
decide() answers one and carries the turn on.
import { CodeEngine, createCodeModel } from 'internal:commands/code/engine';
import { memoryStore } from 'fino:store';
import { env } from 'fino:process';
const engine = await CodeEngine.open({
cwd: '/repo',
store: memoryStore(),
model: createCodeModel({ env }),
mode: 'build',
});
let turn = await engine.runTurn('Rename the helper and update its tests.');
while (turn.status === 'suspended' && turn.approvals.length > 0) {
turn = await engine.decide(turn.approvals[0]!, { approved: true });
}Types
type CodeMode = 'plan' | 'build' | 'auto'
How much a session may do without asking: plan withholds the mutating
tools, build offers them behind approval, and auto runs them
unattended. Sub-agents follow the mode in effect when their run is driven;
in plan they are read-only whatever they asked for.
type ApprovalDecision = { approved: true } | { approved: false; reason?: string }
The user's answer to a PendingApproval.
Constants
const MAX_SETTLEMENT_RUNS
Upper bound on settlement continuations within one turn.
Interfaces
interface CodeEngineOptions {
Options for CodeEngine.open().
Properties
cwd: string
Absolute project root; every tool is bounded to it.
store: AtomicStore
Store holding threads, runs, metadata, and sub-agent records.
model: Model
Model for the parent agent and for sub-agents that name none.
resolveModel?: (id: string) => Model | Promise<Model>
Build the model a sub-agent names in subagent_spawn. Without it a
sub-agent that names a model fails with an explanatory error.
mode?: CodeMode
Permission level; defaults to build.
threadId?: string
Thread to continue; defaults to a new code-… thread id.
onSubagentEvent?: (id: string, event: AgentEvent) => void
Observer for every sub-agent's live events, tagged with its id.
finoPath?: string | false
Fino binary whose doc, lint, fmt, test and bench commands are
offered as tools, or false to omit them. Defaults to this process's
executable.
budget?: Budget
Spend limit shared by the parent and every sub-agent this engine drives. Each model call is checked against it before it is made.
interface PendingApproval {
A gated tool call waiting for the user.
Properties
agent: string
main for the parent agent, otherwise the sub-agent id.
token: string
Resume token of the suspended run.
request: ToolApprovalRequest
Tool call awaiting the decision.
interface TurnResult {
How a turn ended, or why it stopped.
Properties
status: 'done' | 'suspended' | 'error' | 'cancelled'
suspended means the turn waits on approvals (or on parent input).
text?: string
The parent's final text when done.
error?: string
Failure message when error.
approvals: PendingApproval[]
Pending approvals when suspended; empty otherwise.
reason?: string
Suspension reason when the parent suspended for something else.
interface TurnHooks {
Per-call hooks for driving a turn.
Properties
onEvent?: ((event: AgentEvent) => void) | undefined
Observer for the parent agent's live events.
signal?: AbortSignal | undefined
Aborts the parent run and any wait on sub-agents.
interface CodeModelOptions {
Options for createCodeModel().
Properties
model?: string | undefined
Model id; defaults to FINO_CODE_MODEL, then the provider default.
provider?: string | undefined
anthropic or openai; inferred from the id and credentials.
env: Readonly<Record<string, string | undefined>>
Environment holding ANTHROPIC_API_KEY, OPENAI_API_KEY,
OPENAI_BASE_URL, and FINO_CODE_MODEL.
interface CodeModelCatalog {
Models fino code can switch between, from the configured providers.
Methods
list(refresh?: boolean): Promise<{ models: ModelInfo[]; errors: string[] }>
Available models from every configured provider, cached after the first
call unless refresh is set. A provider whose listing fails is reported
in errors rather than failing the others.
create(id: string, provider?: string): Promise<Model>
Build the model for id. A listed id uses its provider; an unlisted one
is resolved the way --model is. Refuses an unpriced model under a
spend limit.
Functions
function createCodeModel(opts: CodeModelOptions): Model
Construct the model fino code should use from explicit choices and
credentials.
An explicit provider must be anthropic or openai and have
credentials. Otherwise a claude… id selects Anthropic, any other id
selects OpenAI (or an OpenAI-compatible server at OPENAI_BASE_URL), and
with no id Anthropic is preferred when its key is set. A base URL without
OPENAI_API_KEY is treated as a local server that needs no key.
import { createCodeModel } from 'internal:commands/code/engine';
const local = createCodeModel({
model: 'qwen2.5-coder',
env: { OPENAI_BASE_URL: 'http://127.0.0.1:8080/v1' },
});function createCodeModelCatalog(opts: {
env: Readonly<Record<string, string | undefined>>;
priced?: boolean;
}): CodeModelCatalog
The model catalog for a fino code run: Anthropic when ANTHROPIC_API_KEY
is set, and OpenAI (or the server at OPENAI_BASE_URL) when that or
OPENAI_API_KEY is.
import { createCodeModelCatalog } from 'internal:commands/code/engine';
import { env } from 'fino:process';
const catalog = createCodeModelCatalog({ env });
const { models } = await catalog.list();
const model = await catalog.create(models[0]!.id, models[0]!.provider);function requirePricedModel(model: Model): Model
Refuse a model whose spend fino:ai/context cannot price, since a cost
limit would silently count its calls as free.
function createCostBudget(maxUsd: number, model: Model): Budget
Build the spend limit for --max-cost: maxUsd across the parent and its
sub-agents for this engine, failing the model call that would exceed it.
import { createCodeModel, createCostBudget } from 'internal:commands/code/engine';
import { env } from 'fino:process';
const model = createCodeModel({ env });
const budget = createCostBudget(2.5, model);function isCodeThread(threadId: string): boolean
Whether threadId names a fino code parent thread rather than a child.
async function listCodeSessions(
store: AtomicStore,
opts: { archived?: boolean } = {},
): Promise<ThreadSummary[]>
List fino code threads newest first, excluding sub-agent threads.
const sessions = await listCodeSessions(store, { archived: false });async function loadCodeHistory(
store: AtomicStore,
threadId: string,
): Promise<ModelMessage[]>
The stored conversation of threadId as the model sees it; empty when the
thread is unknown or has no history yet.
const messages = await loadCodeHistory(store, 'code-abc');async function listSubagentThreads(store: AtomicStore, threadId: string): Promise<string[]>
The sub-agent threads of a fino code session, oldest first. A sub-agent's
thread id is its session's id, a colon, and its pool id.
const children = await listSubagentThreads(store, 'code-abc'); // ['code-abc:sa_1']async function renameCodeSession(
store: AtomicStore,
threadId: string,
title: string,
): Promise<void>
Set a session's title; an empty title clears it.
await renameCodeSession(store, 'code-abc', 'Loader rewrite');async function archiveCodeSession(
store: AtomicStore,
threadId: string,
archived: boolean,
): Promise<void>
Archive a session, or restore it with archived false. Archived sessions
are listed only by listCodeSessions(store, { archived: true }).
await archiveCodeSession(store, 'code-abc', true);async function deleteCodeSession(store: AtomicStore, threadId: string): Promise<boolean>
Delete a session from every list: its thread, its metadata, its sub-agent records, and each sub-agent's thread and metadata. Returns whether the session existed.
The stored runs and history the threads pointed at are not reclaimed. Do not delete a session open in an engine or running elsewhere; the caller checks that.
await deleteCodeSession(store, 'code-abc');Classes
class CodeEngine {
One fino code conversation: a durable parent thread and its sub-agents.
Open it with CodeEngine.open(); the constructor is private.
Static Methods
static async open(opts: CodeEngineOptions): Promise<CodeEngine>
Open the engine on opts.threadId (or a new thread) and restore its
sub-agent pool, which resumes any sub-agent runs a restart interrupted.
Getters
get threadId(): string
Durable thread id of this conversation.
get mode(): CodeMode
Permission level used for the next run.
get model(): Model
Model for the parent agent and for sub-agents that name none.
Methods
setMode(mode: CodeMode): void
Change the permission level. It applies from the next run the engine starts, including settlement runs and the sub-agent runs it drives.
setModel(model: Model): void
Change the model. Like setMode(), it applies from the next run the
engine starts: a run already in progress keeps the model it began with,
and a resumed approval continues on the new one. The conversation is
stored independently of any model, so it carries over unchanged.
messages(): Promise<ModelMessage[]>
The conversation so far, as the model sees it; empty for a new thread.
subagents(): SubagentState[]
Snapshot of every sub-agent on this thread.
async runTurn(input: string, hooks: TurnHooks = {}): Promise<TurnResult>
Run one turn: the parent run for input, then any settlement runs its
sub-agents need. Refused while an earlier turn waits on an approval.
A run that fails or is aborted ends the turn as error or cancelled.
async decide(
approval: PendingApproval,
decision: ApprovalDecision,
hooks: TurnHooks = {},
): Promise<TurnResult>
Answer one pending approval and carry the turn on.
async recover(hooks: TurnHooks = {}): Promise<TurnResult | null>
Carry on whatever a previous process left unfinished on this thread, or
return null when there is nothing to recover. A parent run
checkpointed running is re-driven, a suspended one re-surfaces its
approval, and a finished one whose sub-agents still need it resumes the
settlement loop. Failed runs are left alone; the next turn moves on.