Skip to content

Budgets, attempts and stopping scope

The finite-v1 budget is mission-wide, with additional accounting on the grant chain. The M3 source profile, aiws-limits/1, adds a shared ledger for nested work-order, run, branch and node limits. Amounts are canonical unsigned decimal strings, representing units chosen by the contract owner. Do not put fractional currency into payloads or accounting fields; choose integer minor units and document the unit scale.

Admission reserves exposure before an effect is allowed. Settlement releases the attempt’s reservation and adds its actual cost. UNKNOWN preserves the full reservation and records no cost.

Reject reservations beyond the shared allowance · Executable control simulation

import assert from 'node:assert/strict';
import { createMission, parseContract, parseCommand, reduce } from '@aiws/sdk';
// Trusted simulation: this example makes no external calls.
const contract = parseContract(JSON.stringify({
"id": "c",
"missionId": "m",
"aiwsEdition": "0.4",
"profile": "finite-v1",
"budget": "100",
"deadline": "10000",
"criteria": [
"review"
],
"actions": [
"write"
],
"resources": [
"doc"
],
"requiresApproval": false,
"maxAttempts": "2",
"maxAuthorizationAgeMs": "10",
"features": [
"triggers",
"graphs"
]
}));
let state = createMission(contract);
// Step 1
state = reduce(state, parseCommand(JSON.stringify({
"type": "startRun",
"runId": "r"
})), '10');
// Step 2
state = reduce(state, parseCommand(JSON.stringify({
"type": "grant",
"grant": {
"id": "g",
"subject": "agent",
"profile": "finite-v1",
"actions": [
"write"
],
"resources": [
"doc"
],
"notBefore": "0",
"expiresAt": "10000",
"limit": "100",
"canDelegate": true,
"depth": "2"
}
})), '10');
// Step 3
state = reduce(state, parseCommand(JSON.stringify({
"type": "admit",
"runId": "r",
"operationId": "o",
"attemptId": "a",
"grantId": "g",
"subject": "agent",
"action": {
"capability": "write",
"resource": "doc",
"payload": {
"value": 1
},
"preconditions": {
"revision": 1
}
},
"amount": "80",
"authorizationCheckedAt": "10",
"policy": "ALLOW",
"mandatoryChecksOk": true
})), '10');
// Step 4
assert.throws(() => reduce(state, parseCommand(JSON.stringify({
"type": "admit",
"runId": "r",
"operationId": "o2",
"attemptId": "a2",
"grantId": "g",
"subject": "agent",
"action": {
"capability": "write",
"resource": "doc",
"payload": {
"value": 1
},
"preconditions": {
"revision": 1
}
},
"amount": "30",
"authorizationCheckedAt": "10",
"policy": "ALLOW",
"mandatoryChecksOk": true
})), '10'), (error: any) => error.code === 'BUDGET_EXHAUSTED');
assert.deepEqual(state["reserved"], "80");
console.log('PASS: budget');

Overrun settlement (proposal for SDK 0.5.0)

Section titled “Overrun settlement (proposal for SDK 0.5.0)”

SDK 0.5.0 rejects a settle whose actual cost is above the admitted amount with EXPOSURE_EXCEEDED. The SDK 0.5.0 proposal replaces that rule, in finite-v1 and in aiws-limits/1 alike; it is built in current source, is not a released API, and ships only when all three SDKs carry it (STANDARD B-02, AT-59).

  • The true cost is recorded. A settle of a dispatched attempt (DISPATCHED or UNKNOWN) as CONFIRMED_APPLIED or CONFIRMED_NOT_APPLIED may report an actual cost above the attempt’s amount. The whole cost is charged to the mission and to every grant in the attempt’s chain. Nothing is capped, absorbed or charged to a sibling.
  • Over budget is derived. A scope, the mission or a grant, is over budget when its settled spent exceeds its bound. There is no new field, event or marker to clear. The overrun of an attempt is its actual cost minus its amount; the overrun of a scope is spent minus its bound. The observability summary reports it as BUDGET_OVERRUN.
  • New work is refused. An over-budget scope refuses admit and retry, even for amount 0, with BUDGET_EXHAUSTED (mission) or GRANT_BUDGET_EXHAUSTED (grant). dispatch refuses with the same codes when spent plus reserved already passes a bound, so a sibling reserved before the overrun can only be settled as not applied. A sibling under a parent that is still within its bound stays admissible.
  • A never-dispatched attempt cannot overrun. A PREPARED attempt may settle CONFIRMED_NOT_APPLIED only at an actual cost no higher than its amount; a higher cost is still EXPOSURE_EXCEEDED.
  • One structural limit. A settle whose resulting spent on the mission or any grant in the chain would exceed 100 digits, the wire’s quantity width, is refused with INVALID_RECORD and the state unchanged. An overrun has no other size limit.

The SDK only reports an overrun; it has no command to raise a finite-v1 budget, and an over-budget mission stays refused for as long as its contract and grants stand. A human continues in one of two ways: close the mission and approve a new, explicitly linked mission with its own contract and budget, carrying the overrun forward in its accounting (STANDARD M-03, I-02); or, under Praxis, use the engine’s human-only ledger adjustment. Praxis is stricter: it holds the node with EXPOSURE_EXCEEDED and settles at the true cost only after a human raises the bounds (capabilities).

A rejected command leaves the input state unchanged. SQLite also rolls back the journal and outbox intent together. Concurrent admissions must use the durable store boundary; separate in-memory reducers do not create a shared atomic budget.

A reservation should cover the maximum authorized exposure of that attempt, not an optimistic average. Enforce provider limits, process timeouts and restricted credentials at the target where possible. If an adapter cannot cap its cost, explain that limitation to the operator before claiming a hard bound. Reservations protect admission decisions; they cannot cancel an already submitted external operation by themselves.

The accepted engine model has work orders containing runs and optional child work orders, with limits at work-order, run and branch scopes. Any applicable exhausted limit blocks additional work in its scope. A branch limit holds that branch and dependent tasks. A work-order limit holds all descendants. Independent branches may continue only if their own and all shared allowances permit it.

Use LimitStore and LimitCoordinator from @aiws/sdk/limits, aiws.limits_store, or aiws_sdk::limits_store. One ledger database owns every scope sharing a parent budget. It reserves cost and active time against all ancestors in one SQLite transaction. Immutable dependencies add admission gates without charging cost twice. The existing mission and handoff stores keep their own contracts and authority checks.

Reserve ordinary work and protected handoff funds · M3 source; fixed clock and simulated authenticated host, no external calls

import { readFileSync } from 'node:fs';
import assert from 'node:assert/strict';
import { parseStrict } from '@aiws/sdk';
import { LimitStore, LimitCoordinator, type LimitConfig } from '@aiws/sdk/limits';
// Demonstration only: a real host verifies the initial approval and each command.
const config = parseStrict(readFileSync('examples/guide/limits-config.json', 'utf8')) as unknown as LimitConfig;
const store = new LimitStore(':memory:', config);
const coordinator = new LimitCoordinator(store, () => ({ allowed: true, actorId: 'demo-agent', actorKind: 'AGENT', policyRef: 'demo-policy', evidenceRef: null, authorizedAtMs: '0' }), () => '0');
for (const [attemptId, purpose, amount] of [['work', 'ORDINARY', '90'], ['summary', 'HANDOFF', '10']]) {
await coordinator.apply({ requestId: attemptId, expectedRevision: store.snapshot().revision,
command: { type: 'reserve', attemptId, operationId: attemptId, scopeId: 'run', runId: 'run', purpose, amount, maxActiveMs: '10' } });
}
const report = store.report('0');
assert.equal(report.scopes.find((s: any) => s.scopeId === 'wo').usage.cost, '100');
assert.equal(report.scopes.find((s: any) => s.scopeId === 'wo').usage.handoff, '10');
console.log(report); // Always available, even when paid work is blocked.
store.close();

The example’s examples/guide/limits-config.json defines a work order wo and its run run. The work order has a total cost ceiling of 100, with 10 protected for handoff. The run inherits its parent’s bounds. Its fixed clock and simulated authorizer are demonstration inputs; production hosts must authenticate callers, approve the initial config and bind scope/purpose to the trusted workflow definition.

Limit Meaning
cost Settled cost plus all unsettled maximum exposure
handoff Protected partition inside cost; only host-authorized HANDOFF work consumes it
activeMs Sum of concurrent execution time, with pre-dispatch maximum reservations
elapsedMs Time since immutable scope start, including pause and downtime
attempts One per successful reservation; release and continuation do not reset it

Null bounds inherit ancestor restrictions. All bounds apply together. Two concurrent ten-millisecond attempts consume twenty active milliseconds at their parent. UNKNOWN continues accruing active time through downtime. A host-verified stop freezes time but keeps financial exposure; settlement releases only unused cost. Human reconciliation is required to resolve UNKNOWN.

In SDK 0.5.0 a ledger settle above the reserved cost fails with EXPOSURE_EXCEEDED. Under the SDK 0.5.0 proposal it records the true cost on the leaf scope and every ancestor; a scope whose usage now passes its limit refuses new reservations and the dispatch of a reserved attempt with LIMIT_EXHAUSTED, and that attempt can only be released. A resulting cost usage over 100 digits is refused with SCHEMA_INVALID. Reservation checks the handoff partition by purpose: after an ordinary overrun, HANDOFF work may still use the remaining total headroom, up to the protected amount. The human adjust command is unchanged and must bring every limit to at least current usage.

Pair the ledger with existing dispatch gates

Section titled “Pair the ledger with existing dispatch gates”

Reserve in the ledger before preparing the mission attempt. Record ledger dispatch and pass existing mission/handoff dispatch checks before any external call. These databases do not share an atomic commit: a crash between them conservatively retains exposure and needs reconciliation. Never refund a DISPATCHED attempt merely because the host restarted. Current authority, ownership, artifacts, approvals and handoff inputs still apply. The ledger alone is not authorization to act.

store.report(now) identifies blocked scopes, affected dependents, usage and outstanding attempts without an LLM call. Stop and settlement remain available while new work is blocked. The host applies task-specific interruption policy to running effects; the SDK cannot stop an external provider by itself.

The accepted design reserves a small human-approved amount inside the existing allowance for checkpointing and handoff. It is not extra money beyond the limit. Main work cannot consume that protected reserve. The engine produces a basic report from durable state even when no agent allowance remains; an agent-written explanation is optional and must fit the reserve.

No agent may raise permissions, budgets or retry limits, including by generating a new workflow or transferring work to another agent. Human approval is required. SDK contracts are immutable; do not change a persisted contract to bypass a rejected operation. See migration before moving into a different contract.

The new ledger’s adjust command requires authenticated HUMAN facts and a host-verified evidence reference for the exact change. It preserves prior spending, attempts, active time and scope start times. Ordinary work and paid cleanup cannot consume the handoff partition. Paid summaries still obey time and attempt bounds; use the deterministic report when those are exhausted. Previously built 0.3.0 binary downloads do not include these source APIs.