Skip to content
Français

Limit attempts and tokens

Set a workflow budget and understand how usage is counted across retries and resumes.

Set a budget before adding retries, loops or parallel agents. The first example runs without model calls and shows the counters to inspect. Provider billing limits remain necessary because a request can spend tokens before reporting them.

Pass a budget to the workflow’s start() method to limit attempts, reported tokens or both. These limits apply across the workflow’s tasks, rather than to each task separately.

import { defineTask, defineWorkflow } from "@elie-laloum/outpost/workflows";

const meter = defineTask({
  key: "meter",
  perform(context) {
    context.reportUsage({ input: 10, cached: 0, output: 5 });
    return "recorded";
  },
});
const result = await defineWorkflow("bounded", [meter]).start({
  budget: { attempts: 5, usage: { input: 50_000, output: 10_000 } },
});
console.log(result.usage);
// Example output: { attempts: 1, tokens: { input: 10, cached: 0, output: 5 } }

It prints { attempts: 1, tokens: { input: 10, cached: 0, output: 5 } }.

API reference: WorkflowBudget.

speculate() requires the same budget, shared by its candidates: see Competing candidates.

Each attempt is admitted against budget.attempts before it starts.

One agent turn counts as one attempt, even if it makes many model requests. A skipped task or a result restored from the cache uses no attempt.

Agent task helpers report the tokens of their agent automatically: defineAgentTask(), defineIsolatedTask(), defineInteractiveAgentTask() and defineQueuedTask(). A custom task that calls a model reports what it spent.

import { defineTask } from "@elie-laloum/outpost/workflows";
import type { Usage } from "@elie-laloum/outpost/core";

declare function summarize(
  text: string,
): Promise<{ id: string; text: string; usage: Usage }>;

const summary = defineTask({
  key: "summary",
  async perform(context) {
    const reply = await summarize("Summarize the release notes.");
    context.reportUsageOnce?.(`summary:${reply.id}`, reply.usage);
    return reply.text;
  },
});

reportUsage(usage) adds to the totals. reportUsageOnce(receipt, usage) ignores a receipt the task already recorded, even after a checkpoint resume, so a result read twice is counted once. Both work only during the running attempt.

The usage of a CLI agent turn also carries usage.models, with or without prices. Without prices, each entry is keyed <agent>:<model>, for example claude:claude-sonnet-5-5, or by the agent name alone when no model is configured, for example codex. Including the agent keeps two agents that run the same model name apart; give custom agents names distinct from the built-in ones. With prices, entries are keyed by model name to match the price table, and harness model requests, routing and decision tasks are attributed too. Workflow totals, task usage events, checkpoints and recipe reports keep one entry per key.

Agents count cache tokens differently. In an entry with inputIncludesCache: false (Claude Code and Kimi Code), input excludes cache reads (cached) and writes (cacheCreated); otherwise input includes them. The top-level counters add entries as reported, so normalize a run that mixes both conventions from models:

import type { Usage } from "@elie-laloum/outpost/core";

export function cacheBreakdown(usage: Usage) {
  return Object.entries(usage.models ?? {}).map(([key, tokens]) => {
    const cacheWrite = tokens.cacheCreated ?? 0;
    const cacheIncluded = tokens.inputIncludesCache !== false;
    return {
      key,
      uncachedInput: cacheIncluded
        ? tokens.input - tokens.cached - cacheWrite
        : tokens.input,
      cacheRead: tokens.cached,
      cacheWrite,
      output: tokens.output,
    };
  });
}

const claude = { input: 12, cached: 600, cacheCreated: 100, output: 150 };
const codex = { input: 1_200, cached: 300, output: 300 };
const rows = cacheBreakdown({
  input: 1_212,
  cached: 900,
  cacheCreated: 100,
  output: 450,
  models: {
    "claude:claude-sonnet-5-5": { ...claude, inputIncludesCache: false },
    codex,
  },
});
for (const row of rows)
  console.log(
    `${row.key}: ${row.uncachedInput} uncached, ${row.cacheRead} read, ${row.cacheWrite} written, ${row.output} output`,
  );
// Example output: claude:claude-sonnet-5-5: 12 uncached, 600 read, 100 written, 150 output
// Example output: codex: 900 uncached, 300 read, 0 written, 300 output

The function returns uncached input, cache reads, cache writes and output for each key. Usage reported without models, such as an unpriced harness request or a custom task, only adds to the top-level counters; built-in model providers count cache tokens inside input. Token limits in budget.usage apply to the top-level counters, mixed conventions included.

Decision tasks contribute their normalized usage to workflow budgets. Model routing also counts against harness, ancestor and workflow budgets, exactly once per router request. Valid usage still counts when truncation rejects the result. A missing receipt is incomplete usage, and strict token budgets reject continuation with unknown consumption.

Outpost checks the reported usage before allowing more work to start. The budget applies to these recorded totals; it cannot predict the tokens an in-progress model request will consume.

LimitWhen it is checkedWhat happens
attemptsBefore each attemptNo new attempt starts; running ones finish. WorkflowBudgetExceeded with "attempts".
usage.input, usage.output, …Before each attempt and at each usage reportRunning attempts are cancelled; nothing else starts. WorkflowBudgetExceeded.
Token limits, no attempts, incomplete usageBefore each attempt and at each usage reportRunning attempts are cancelled; nothing else starts. WorkflowUsageUnavailable.

An attempt limit is enforced when another attempt asks to start: using the last allowed attempt does not cancel it or make an otherwise completed workflow fail. A refused admission fails the workflow; a reached token limit also cancels running work. For these budget errors, result.terminationCode is "limit", stopped tasks are cancelled, and result.errors holds the error with its dimension, limit and observed values.

The same admission and cancellation rules apply to speculative candidates. Their outcomes differ: with two candidates and budget: { attempts: 1 }, the admitted candidate can still finish and win. A speculation stopped by its budget without a winner returns status: "budget-exhausted". If running work reaches a token limit after the attempt limit has already refused more work, it is still cancelled in either engine.

result.usage.tokens.complete === false means some tokens could not be measured: the counters are a lower bound. The marker stays through retries, aggregation and checkpoints.

With token limits and no attempts, incomplete usage stops the run with WorkflowUsageUnavailable. With attempts, the run continues under the attempt limit and Outpost emits a warning.

Copilot CLI and Kimi Code read their final counters from the session after the CLI exits. For them especially, bound each run by attempts and time.

import { defineIsolatedTask } from "@elie-laloum/outpost/workflows";
import { repository, sandboxProvider, coder } from "./outpost.config.ts";

export const fix = defineIsolatedTask({
  key: "fix",
  timeoutMs: 30 * 60_000,
  retry: { attempts: 2 },
  request: () => ({
    repository,
    sandboxProvider,
    agent: coder,
    branch: { mode: "named", name: "outpost/fix-tests" },
    brief: { text: "Fix the failing tests and commit the fix." },
    deadlineMs: 20 * 60_000,
  }),
});
import { defineWorkflow } from "@elie-laloum/outpost/workflows";
import { fix } from "./fix-task.ts";

export const result = await defineWorkflow("fix-tests", [fix]).start({
  budget: { attempts: 3, usage: { input: 2_000_000 } },
});
console.log(result.status, result.usage);
// Example output: done { attempts: 1, tokens: { models: { codex: [Object] }, input: 1200, cached: 0, output: 320 } }

timeoutMs bounds each task attempt and deadlineMs each agent turn: see Limits and cancellation. Choose an agent shows when each agent reports usage.

A checkpoint saves result.usage. A resumed run starts from the saved totals, so the budget covers the whole run, not the current process.

To continue a run its budget stopped, start it again with a larger budget and authorize the replay of its cancelled tasks: see Durable runs. A durable speculative race must resume with the budget it started with.