LimitFuse documentation

From first call to production control.

Build the budget, evidence, and containment path for AI, cloud functions, queues, storage, paid APIs, and any other metered operation before scale finds the weak point.

Dark conduits meeting an orange containment boundary

DEFINE

Authority

OBSERVE

The chain

CONTAIN

One scope

THE HARKER SUPPLY JOURNEY · FIVE CHAPTERS

From one script to economic control.

A catalog pipeline—not an AI demo—shows how an ordinary cloud job grows from a useful prototype into a professionally bounded production system.

Chapter 01 · The first job

A useful script feels harmless.

Harker Supply starts with a nightly catalog sync. It downloads supplier records, resizes product images, writes database updates, and emails a summary. AI is optional; the expensive parts are ordinary cloud functions, storage operations, queues, and a paid enrichment API.

The novice view: if the job succeeds, the architecture must be safe.

Chapter 02 · Real traffic

Success multiplies the work.

The sync moves from nightly to event-driven. Every supplier change can start image transforms, database writes, cache invalidations, webhooks, and an optional AI description. One business outcome now fans out across several metered systems.

The growing-team view: provider dashboards see services; Harker needs one economic view of the whole outcome.

Chapter 03 · The bill shock

A timeout becomes permission to spend again.

A database write succeeds but its acknowledgement arrives late. The queue retries, republishes the same catalog page, and starts the full branch again. Logs remain green because every individual operation completes. By the time a billing alert arrives, millions of valid-looking operations have run.

The incident view: observability explains the spend after it happened; it did not decide whether the next expense could begin.

Chapter 04 · The first fuse

Cost becomes execution authority.

Harker wraps each costly operation with External Guard, keeps its provider keys and payloads inside its own infrastructure, and gives every catalog run a hard wallet, one retry, a fan-out ceiling, and a deadline. LimitFuse reserves worst-case cost before work begins and denies replayed operation IDs.

The operator view: the workflow can spend only authority it received; already-running external work still needs a runtime timeout and cancellation path.

Chapter 05 · Professional control

The bad run stops. The company keeps trading.

The retry pattern returns. LimitFuse denies the next database batch, freezes only the catalog-sync wallet, and requests a narrowly scoped queue pause. Orders, checkout, and healthy supplier jobs stay live. The team verifies termination, reconciles provider records, restores the queue, and closes an audited incident.

The professional view: a software mistake becomes a bounded, reversible incident—not an unbounded bill or a company-wide outage.

The operational win

Harker no longer chooses between letting a loop spend freely and taking every service offline. The failing catalog run stops at its boundary, orders keep flowing, and the evidence is ready before the incident review begins.

NOT AN AI-ONLY GATEWAY

If software can meter it, LimitFuse can bound the protected path.

The managed gateway is optimized for AI calls. External Guard is provider-neutral: it reserves authority before any ordinary function, queue operation, database batch, storage job, browser run, build, or paid API call. Your credentials and payload stay in your infrastructure.

WORKLOADINTEGRATIONUSEFUL LIMITS
AI and model callsManaged gateway or External GuardTokens, calls, retries, steps, duration, margin
Cloud and serverless functionsExternal Guard + runtime adapterCost, invocations, concurrency, recursion, duration
Queues and event pipelinesAuthorize enqueue/consume + pause actionRetries, redelivery, fan-out, poison messages
Database and storage workWrap batches + reconcile provider usageReads, writes, scans, egress, repeated batches
Paid APIs, email, SMS, mediaExternal Guard around each paid operationPer-call cost, rate, retry, unit economics
Builds, browsers, and long jobsSigned deadline + cancel-job/watchdogDuration, steps, parallelism, orphaned work

The honest boundary

LimitFuse can deny the next protected operation immediately. It cannot retroactively stop work that bypassed the guard or force code in another platform to terminate. Harden external execution with provider/runtime deadlines, cancel-only adapters or durable watchdogs, and provider-log or egress reconciliation.

Quickstart

Put one costly feature behind LimitFuse, keep the policy in shadow, then prove the enforcement and recovery path with a controlled canary.

Create a project

Choose the production environment and assign the feature that will receive the first policy.

Issue a project key

Reveal it once, store it in a server-side secret manager, and keep it out of browser and mobile code.

Create a policy

Start with a hard budget, bounded output, retry limit, duration, and fail-closed behavior.

Prove the fuse

Certify scenarios in shadow, record an independent review, enforce, and run a low-cost canary.

Install and verify
npm install @sansavision/limitfuse

# Validate locally before pushing
limitfuse policy validate ./limitfuse.policy.json
limitfuse policy simulate ./limitfuse.policy.json --scenario all

Core concepts

LimitFuse joins causal execution context with economic authority. These objects form the protection boundary.

Wallet

The spend authority for a run. Settled cost and open reservations both count against it.

Causal graph

The parent, child, retry, tool, queue, and function relationships behind one business outcome.

Signed envelope

Trusted project and run context that survives service boundaries without trusting caller-supplied metadata.

Policy

An immutable version of budgets, limits, failure behavior, and containment actions.

Incident

The evidence, action state, verification, recovery, and closure record for a contained run.

POLICY AS CODE

Define what the run may do.

Selectors bind policy to a feature and environment. Limits cover cost, time, model calls, tools, depth, fan-out, concurrency, retries, output, velocity, loops, and unit economics.

limitfuse.policy.json
{
  "apiVersion": "limitfuse.dev/v1alpha1",
  "kind": "EconomicPolicy",
  "metadata": {
    "name": "invoice-operations",
    "version": "local",
    "status": "draft"
  },
  "spec": {
    "mode": "strict",
    "selector": {
      "feature": "invoice-operations",
      "environment": "production"
    },
    "wallet": {
      "hardBudgetUsd": 0.40,
      "warningAtPercent": 70,
      "maxDurationSeconds": 180
    },
    "limits": {
      "modelCalls": 6,
      "toolCalls": 8,
      "recursionDepth": 3,
      "childRuns": 2,
      "retriesPerLogicalOperation": 1,
      "maxOutputTokensPerCall": 1200
    },
    "actions": [
      { "when": "warning", "do": "notify" },
      { "when": "retry_loop", "do": "freeze_run" },
      { "when": "budget_exhausted", "do": "freeze_run" }
    ]
  }
}

Reserve before execution

Worst-case cost is held before the provider call. Unused authority returns after exact settlement.

Fail with a known posture

Choose cached policy behavior and fail-closed handling for expensive calls when a dependency is unavailable.

Choose the control boundary

Use External Guard for ordinary metered work or when credentials and content must stay with you. Use the managed OpenAI-compatible gateway when LimitFuse should own AI dispatch, timeout, and exact settlement end to end.

catalog-sync.ts
const outcome = await limitfuse.executeExternalSafely({
  kind: "database",
  feature: "catalog-sync",
  runId: "supplier-2026-08-29",
  operationId: "catalog-page-1842-attempt-1",
  logicalOperationId: "catalog-page-1842",
  estimatedMaxCostUsd: 0.18,
  attempt: 1
}, {
  timeoutMs: 45_000,
  execute: async ({ signal, markStarted }) => {
    markStarted();
    const result = await syncCatalogPage({ signal, page: 1842 });
    return { value: result, actualCostUsd: result.meteredCostUsd };
  },
  terminate: async ({ signal }) => {
    const stopped = await pauseCatalogQueue({ signal });
    return stopped ? { status: "confirmed", actualCostUsd: 0.11 }
      : { status: "uncertain" };
  }
});
managed-ai-call.ts
import { LimitFuseClient } from "@sansavision/limitfuse";

const limitfuse = new LimitFuseClient({
  gatewayUrl: process.env.LIMITFUSE_GATEWAY_URL!,
  projectKey: process.env.LIMITFUSE_PROJECT_KEY!
});

const run = await limitfuse.createRun({
  organizationId: "org_harker",
  projectId: "proj_invoice_ops",
  environment: "production",
  feature: "invoice-operations",
  economicContext: {
    expectedRevenueUsd: 2.50,
    outcomeUnits: 1
  }
});

const response = await limitfuse.chatCompletions({
  model: "provider-model",
  messages: [{ role: "user", content: "Resolve this invoice exception." }],
  max_completion_tokens: 600
}, { envelope: run.envelope });
Raw HTTP and API reference No npm package is required.

Key boundary

Use the project key only from trusted server code. Rotation and revocation are immediate, and stored credentials are represented by a one-way digest.

AGENT-ASSISTED SETUP

Let an agent do the repository work. Keep control of production.

Download the portable LimitFuse skill and give it to Claude, GPT/Codex, or another repository-capable coding agent. The workflow tells the agent how to find metered edges, choose managed or external execution, implement the guard, add tests, and prepare a low-cost canary without exposing server keys or silently changing enforcement.

THE AGENT CAN

  • Inspect model calls, functions, queues, jobs, storage, and paid APIs.
  • Write SDK or raw HTTPS integration code, policies, deadlines, and tests.
  • Simulate failure paths and prepare shadow, canary, recovery, and rollback evidence.

A PERSON APPROVES

  • Installing server-side secrets through the target secret manager.
  • Deployments and production enforcement.
  • Containment, credential rotation or revocation, and payment changes.

Public, read-only MCP

Create an Agent MCP (read-only) key in Integrations, keep it in the agent host's secret store, and connect its Streamable HTTP client to https://mcp.limitfuse.com/mcp. The key is restricted to one project and the mcp:read capability.

The live tools are limitfuse_inspect_project, limitfuse_explain_boundary, limitfuse_prepare_integration, limitfuse_prepare_canary, and limitfuse_simulate_operation. Every tool is read-only and idempotent. The simulation uses a fresh empty wallet and clearly excludes existing reservations, velocity, and loop history.

MCP Streamable HTTP handshake
curl https://mcp.limitfuse.com/mcp \
  -H "Authorization: Bearer $LIMITFUSE_MCP_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  --data '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
      "protocolVersion": "2025-11-25",
      "capabilities": {},
      "clientInfo": { "name": "your-agent", "version": "1.0" }
    }
  }'
Approval boundary. The MCP server has no tool for deployment, policy promotion, incident containment, recovery, credential changes, or billing. An agent can prepare the exact plan; a signed-in person performs the consequential action in the console.

Policy lifecycle

A policy moves through explicit gates. Published versions are immutable so a decision can always point back to the exact authority in force.

01

Draft

02

Shadow

03

Reviewed

04

Enforcing

05

Rolled back

Certification

Execute deterministic failure scenarios and preserve the report with the version.

Independent review

The author cannot approve the same version. A second organization member records the review.

Promotion

Enable enforcement only after the selector, certification, and review gates are satisfied.

Rollback

Stop using the version while keeping its decisions, incidents, and audit evidence intact.

Incident operations

Containment is useful only when it is scoped, verified, reversible, and understandable after the pressure is gone.

Response path

Deny

Reject the expensive operation before provider execution.

Contain

Freeze the run or quarantine the narrow queue scope selected by policy.

Verify

Confirm the requested action became effective in the target system.

Recover

Restore execution gradually after the cause and policy posture are understood.

Evidence to retain

  • Policy version and decision reason
  • Run, operation, parent, and retry identity
  • Reserved and settled cost
  • Requested, effective, and verified action state
  • Recovery owner and closure notes

Alerting that can be trusted

Configure at least one Email, Slack, PagerDuty, or signed webhook channel, send a synthetic test, and confirm its delivery record. A provider success proves service delivery; it does not prove that a person opened the alert.

Close only after proof

Move from contained to recovering only after upstream work is stopped or reconciled. Close after reversal is verified, a bounded target check passes, unrelated traffic stays healthy, and the enforcing policy remains intact.

Customer-hosted execution needs its own stop mechanism

External Guard controls admission and cost reservation, but it cannot kill code running in infrastructure you own. Put a hard runtime deadline before the signed receipt expires, pass cancellation into the provider/runtime, add a watchdog for asynchronous work, and reconcile provider logs or egress whenever termination is uncertain. Keep the reservation conservative until that uncertainty is resolved.

Read your costs with confidence.

Open Analytics from the dashboard to compare apps, filter by environment, outcome, and start date, and export the selected activity as CSV. The view uses the latest 100 organization runs by last activity. It is a recent-activity report—not lifetime analytics or a complete provider invoice.

NumberWhat it means
Settled costReported workload cost already settled in the selected runs. It may differ from a provider invoice.
Still reservedOutstanding wallet reservations, not additional settled charges.
Blocked or containedRecorded outcomes. They do not prove a specific dollar amount was saved.
Enforcing policiesCurrently enabled policies. Shadow policies observe but do not block.
CoverageRequires provider-log or egress reconciliation. Gateway-visible traffic alone cannot prove there is no bypass.

Internal subsidy does not erase workload cost. Billing tracks internal showback separately from payment collection. Missing data appears as an empty or unavailable state; it is never replaced with demo activity.

Open analytics

Production checklist

A final pass for the pieces that turn a working integration into an owned production control.

A strict policy matches the production feature and environment.

Certification covers retry, recursion, fan-out, and budget exhaustion.

A different organization member records the policy review.

A project key is stored in a secret manager and never shipped to a browser.

Coverage reconciliation can detect calls that bypass the gateway.

Alerts reach an owned email, webhook, Slack, or PagerDuty destination.

The team has tested containment, restoration, and rollback with a canary.

Put one real workflow behind a fuse.

Start in shadow, prove the response path, and promote with another person in the loop.

Open console