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:

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.

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 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']

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.

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.

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.