@intelligo-dev/executions
The execution lifecycle (admission, running, settlement) and the model cost registry.
Install
pnpm add @intelligo-dev/executions drizzle-ormdrizzle-orm is a peer. The executions table is part of the framework’s
schema, which intelligo migrate from
@intelligo-dev/cli
applies.
The boundary
Intelligo records what an AI execution cost and whether it was allowed. It does not wrap the AI framework: prompts, tools and orchestration stay native.
Use
The composition root builds one instance, with the ports bound:
// lib/intelligo.ts
import {
DEFAULT_MODELS,
createExecutions,
registerModels,
} from "@intelligo-dev/executions";
registerModels(DEFAULT_MODELS);
export const executions = createExecutions({
checkEntitlement, // may this workspace run this model? takes the hold
extendHold, // may it take one more step? grows the hold
settleUsage, // charge what the run used
findSettlement, // did that charge already commit?
releaseHold, // the run failed: give the hold back
});A run is one begin, then exactly one complete or fail:
const run = await executions.begin({
workspaceId,
userId,
capability: "support.reply",
model: "google/gemini-2.5-flash",
});
if (!run.allowed) return refuse(run.code, run.reason);
try {
const result = await agent.generate(messages); // your framework, natively
await run.complete({ usage: result.usage, model: "google/gemini-2.5-flash" });
} catch (error) {
await run.fail({ error });
throw error;
}All the ports are optional, so this package never imports billing; the
reference composition root binds them to @intelligo-dev/billing. The
lifecycle claims each transition with a compare-and-swap before money is
spent, so a late complete racing a fail cannot charge twice or release
twice.
A run that may call the model several times — a tool loop — can be held a
step at a time. Begun with stepwise: true, admission holds the
workload’s first step only (the prompt and one step’s output, capped by
workload.outputTokens where that is below the model’s own limit), and
run.extend({ workload }) asks extendHold for each next step before it
runs. A refused extension holds nothing more, and the caller stops before
that step; the run settles what it spent, and settlement releases the whole
hold. Without an extendHold port the whole workload is held at admission.
const run = await executions.begin({
workspaceId,
capability: "support.reply",
model,
workload: { inputTokens: 3_000, steps: 8, outputTokens: 1_024 },
stepwise: true,
});
// …after a step, before the next one:
const next = await run.extend?.({
workload: { inputTokens: 4_200, steps: 1, outputTokens: 1_024 },
});
if (next && !next.allowed) stopTheLoop(next.code);executions.reconcile(executionId, { abandonRunningAfterMs? }) repairs a run
whose process died: it asks findSettlement whether the charge committed,
confirms it onto the row or re-runs settlement from the recorded usage. A
running row that outlived the threshold is charged the usage run.progress()
recorded on it while the run went on — a multi-step run calls it after each
model call — and failed, its hold released, when nothing was recorded. The
threshold counts from when the run was last heard from: each run.progress()
and each extended hold stamps last_progress_at, so a long run that still
reports its steps is left alone, and one that never reports is counted from
its start. findStaleExecutions finds the candidates by the same rule; listExecutions, summarizeExecutions and
summarizeExecutionsByDay read the record for a usage page.
A model call outside the chat transport
A job, a route of your own or a script wraps its model call with the runner, which begins the execution, settles what the result reports and releases the hold when the call throws:
import { runWithExecution } from "@intelligo-dev/executions/runner";
const result = await runWithExecution(
{ executions, workspaceId, userId, capability: "report.write", model },
() => generateText({ model: provider(model), prompt })
);It reads the usage shapes providers emit (totalUsage before usage, cache
counts under any of their spellings) and settles against the model the run
was admitted with. A refusal throws ExecutionRefusedError with the
entitlement’s reasonCode. streamWithExecution hands back the stream with
settle and abort for a run whose usage is known only at its end.
A run can take longer than a hold lasts. runWithExecution says the run is
alive every three minutes while the work runs, which keeps its hold counted
(the keepHold port) and keeps the maintenance sweep from taking it for
abandoned. A run you step yourself does the same each time it calls
run.progress().
When the work finished and charging it failed, complete() throws
SettlementPendingError: the run is claimed, its usage is on the row, and
reconcile() settles it. runWithExecution returns the result in that case,
so a caller that retries on an error does not do paid work twice. A run
completed by hand should keep its result the same way.
A run is charged as the model it reports when that model has a price, and as
the model it was admitted with otherwise; the reported id is then kept in the
usage record’s metadata as reportedModel.
The two readers are exported for a runtime that settles by itself.
readUsage(result) normalises what a provider reported into input, output and
total tokens with the cache counts, preferring the whole run’s totalUsage,
and answers zeros when nothing was reported: whether an unreported run is free
or charged a floor is the caller’s policy. readModel(result) gives the model
the provider says answered, whether it reports a string or an object.
Work the deployment gives away, such as a welcome message or a nightly
digest, is begun with billTo: "platform", on executions.begin or either
runner:
await runWithExecution(
{
executions,
workspaceId,
capability: "digest.write",
model,
billTo: "platform",
},
() => generateText({ model: provider(model), prompt })
);The run is admitted whatever the workspace has left and nothing of the
workspace’s is held or charged. It stays the workspace’s run: it is on its
execution list and in its usage records, with a charge of zero and the real
provider cost, and a registered spend cap still holds it, counts it and can
refuse it. reconcile() settles such a run the same way, from the payer the
row holds.
One request id is one attempt. A retried job begins a new execution; passing
an earlier attempt’s requestId again throws request_id_taken, which means
that attempt exists and is settled or will be reconciled.
Model pricing
@intelligo-dev/executions/pricing is a deliberate zero-import leaf that
client bundles can reach. Model ids are registry keys: an unregistered id has
no price, and guessing one is how a model runs on the cheapest provider and
bills at the most expensive rate. Pricing throws UnknownModelError instead.
Nothing self-registers. DEFAULT_MODELS is the catalogue the framework ships,
as data; a deployment registers it, its own contracted rates, or a model the
framework has never heard of:
import { registerModel } from "@intelligo-dev/executions/pricing";
registerModel({
id: "acme/large-1",
provider: "acme",
model: "large-1-2026-08",
displayName: "Acme Large",
costPerMInputTokens: 1.25, // USD per million, as the provider quotes it
costPerMOutputTokens: 5,
maxOutputTokens: 8_192, // sizes the worst-case hold at admission
capabilities: {
thinking: false,
toolCall: true,
vision: false,
webSearch: false,
codeExec: false,
},
});providerCost is what a run cost the deployment; chargeFor applies the
deployment’s currency, rate and margin (BillingRate) and returns both
figures as money in micros. estimateWorstCaseCost(modelId, workload) is the
most one run on a model could cost the provider, in US dollars: the worst case
admission holds, before the margin and the deployment’s currency, and what a
deployment-wide spend cap counts against. It throws UnknownModelError for an
id with no registered price.
Entry points
@intelligo-dev/executions@intelligo-dev/executions/pricing@intelligo-dev/executions/runner@intelligo-dev/executions/db