TechFabricTechFabricHarness
Building Agents

Model Providers

Configure which LLM providers are available and pick one per agent, per session or per individual call at runtime.

TechFabric Harness uses an explicit provider/model-id reference everywhere a model is selected. There is no implicit "default OpenAI", you opt into a provider by configuring credentials and naming the model.

Reference format

provider/model-id

Examples:

openai/gpt-5.5
anthropic/claude-sonnet-4-6
gemini/gemini-2.5-pro
bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0

The Pi loop also accepts provider:model-id. It splits only at the first separator, preserving nested gateway IDs such as vercel-ai-gateway/anthropic/claude-sonnet-5-5.

Setting credentials

Put provider keys once in a repo/workspace .env.local; TechFabric Harness auto-loads .env and .env.local files, while shell env still wins.

cp .env.example .env.local
# OPENAI_API_KEY=...
# ANTHROPIC_API_KEY=...
# AZURE_OPENAI_ENDPOINT=https://....openai.azure.com
# AZURE_OPENAI_API_KEY=...

Use explicit --env <file> only for overrides. Never paste API keys into source files or session artifacts.

Selecting the model

The first non-empty wins, in this order:

  1. CLI flag: fh run ask --model openai/gpt-5.5
  2. Environment: FABRIC_MODEL=openai/gpt-5.5
  3. .fabricharness/config.ts → run.model or agent.model
  4. Agent-declared default: defineAgent({ model: 'openai/gpt-5.5' })

Per-call override:

await session.prompt('Summarize', { model: 'openai/gpt-5.5' });

Mock provider

For local development and tests, pass --mock to fh run or fh dev. The flag substitutes the deterministic mock provider regardless of the declared model reference and honors typed-result schemas where possible. Without --mock, openai/gpt-5.5 makes a real provider call and requires OPENAI_API_KEY.

export default defineAgent({
  // ...
  model: process.env.FABRIC_MODEL ?? 'openai/gpt-5.5',
});

Provider env names

TechFabric Harness knows the standard env names for common providers:

  • OPENAI_API_KEY
  • ANTHROPIC_API_KEY
  • OPENROUTER_API_KEY
  • DEEPSEEK_API_KEY
  • MOONSHOT_API_KEY
  • XAI_API_KEY
  • GEMINI_API_KEY
  • GOOGLE_API_KEY
  • AZURE_OPENAI_API_KEY + AZURE_OPENAI_ENDPOINT
  • GROQ_API_KEY
  • MISTRAL_API_KEY
  • COHERE_API_KEY

Direct OpenAI-compatible presets

DeepSeek, Moonshot/Kimi, and xAI expose OpenAI-compatible Chat Completions APIs. Fabric provides named presets so direct-key users do not need to repeat the provider base URL.

FABRIC_MODEL=deepseek/deepseek-v4-flash  # DEEPSEEK_API_KEY
FABRIC_MODEL=moonshot/kimi-k2.6              # MOONSHOT_API_KEY
FABRIC_MODEL=xai/grok-4.5  # XAI_API_KEY

kimi/... is accepted as an alias for moonshot/.... Override endpoints with DEEPSEEK_BASE_URL, MOONSHOT_BASE_URL, or XAI_BASE_URL, or configure providers.deepseek, providers.moonshot, and providers.xai explicitly.

These are transport presets. No provider-specific SDK sits behind them. They retain the typed Fabric model contract, tool calls, streaming, redacted HTTP failures, and cost-budget behavior. Missing keys fail before a network request and name the required variable. Fabric never falls back to OpenRouter or mock inference when a direct preset fails.

Built-in prices are effective-dated and intentionally incomplete. DeepSeek V4 and the xAI Grok 4.5 short-context tier have verified rows; Moonshot and unlisted models leave usage.costUsd undefined and set usage.costUnknown: true (see Unknown prices). Register deployment-specific or contract pricing with registerModelPrices() instead of treating an unknown price as zero.

Image and PDF input

Every adapter accepts user messages that carry image and PDF attachments in ModelMessage.attachments, but not every model API can read them. Anthropic and Gemini/Vertex receive both natively. OpenAICompatibleModelProvider sends images as image_url data URLs, and sends PDFs as file parts only when baseUrl is api.openai.com, because most compatible servers reject them; imageInput and documentInput override either choice for one endpoint. Azure OpenAI gets images. Bedrock, Cohere and Workers AI get a short text placeholder instead, and Harness warns once per API so the gap shows up in logs rather than in a confused answer. On the default Pi runtime, OpenAI Responses reads PDFs natively too. The full matrix is in Image and document attachments.

Cloudflare Workers AI binding

When deploying to Cloudflare Workers with fh build --target cloudflare, you can route inference through the platform binding (env.AI.run()) instead of HTTP, no API tokens, no egress, runs at the edge.

import { CloudflareWorkersAIModelProvider } from '@fabric-harness/cloudflare/workers-ai';

export default {
  async fetch(request: Request, env: Env) {
    const fabric = await init({
      modelProvider: new CloudflareWorkersAIModelProvider({
        binding: env.AI,
        defaultModel: '@cf/meta/llama-3.1-8b-instruct',
      }),
    });
    // ...
  },
};

wrangler.toml/jsonc:

[ai]
binding = "AI"

Handles modern { choices: [...] } and legacy { response: '...' } Workers AI shapes. Optional Cloudflare AI Gateway routing supports enterprise logging/routing knobs.

new CloudflareWorkersAIModelProvider({
  binding: env.AI,
  defaultModel: '@cf/meta/llama-3.1-8b-instruct',
  gateway: {
    id: 'prod-gateway',
    skipCache: false,
    cacheTtl: 3600,
    collectLog: true,
    eventId: request.headers.get('x-request-id') ?? undefined,
    metadata: { tenant: 'acme', environment: 'prod' },
  },
  models: {
    '@cf/meta/llama-3.1-8b-instruct': {
      contextWindowTokens: 8192,
      maxOutputTokens: 2048,
      supportsTools: true,
    },
  },
});

Model metadata feeds context-budgeting/auto-compaction and admin UIs. The provider includes built-in metadata for common Workers AI chat models and accepts models / defaultModelInfo overrides for private or newly released models.

OpenAI-compatible gateways

Many AI gateway products speak the OpenAI Chat Completions request/response shape: Vercel AI Gateway, Helicone, Portkey, LiteLLM (self-hosted), internal corp proxies. Wire any of them with the generic aiGateway() helper.

import { aiGateway, init } from '@fabric-harness/sdk';

// Helicone
const fabric = await init({
  modelProvider: aiGateway({
    baseUrl: 'https://oai.helicone.ai/v1',
    apiKey: process.env.OPENAI_API_KEY!,
    headers: { 'Helicone-Auth': `Bearer ${process.env.HELICONE_API_KEY}` },
    defaultModel: 'gpt-4o',
    name: 'helicone',
  }),
});

// Self-hosted LiteLLM
const fabric = await init({
  modelProvider: aiGateway({
    baseUrl: 'http://litellm.internal:4000/v1',
    apiKey: process.env.LITELLM_KEY!,
    defaultModel: 'azure/gpt-5.5',
  }),
});

Vercel AI Gateway preset

Vercel AI Gateway gets a thin preset with the gateway URL pre-baked.

import { vercelAIGateway, init } from '@fabric-harness/sdk';

const fabric = await init({
  modelProvider: vercelAIGateway({
    apiKey: process.env.AI_GATEWAY_API_KEY!,
    defaultModel: 'anthropic/claude-sonnet-4-6',
  }),
});

baseUrl defaults to https://ai-gateway.vercel.sh/v1; override for staging or self-hosted.

Foundry runtime (Azure)

On Azure compute such as an ACA Job, AKS pod, or VM with managed identity, FoundryRuntimeModelProvider calls the Foundry-managed Azure OpenAI surface using a Bearer token instead of an API key.

import { FoundryRuntimeModelProvider } from '@fabric-harness/azure/foundry-runtime';
import { init } from '@fabric-harness/sdk';

const fabric = await init({
  modelProvider: new FoundryRuntimeModelProvider({
    defaultModel: 'gpt-4o',
  }),
});

Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_DEPLOYMENT. Supply FOUNDRY_AGENT_TOKEN when your host injects one, or install the optional @azure/identity peer dependency to use DefaultAzureCredential with the workload's managed identity.

Spend caps

Per-call and per-session USD ceilings prevent runaway spend. Wired through init({ costLimit }):

const fabric = await init({
  costLimit: {
    perCall: 0.10,       // throw if a single model call exceeds $0.10
    perSession: 1.00,    // throw if cumulative session spend exceeds $1.00
    onExceed: 'throw',   // 'throw' (default) | 'approve'
  },
});

When onExceed: 'approve' the loop pauses on a violation and emits approval_requested with kind: 'cost-limit'. Approve via your existing approval UI (or fh approve <id>) to release the loop; deny to throw CostLimitExceededError.

Limits evaluate after each call's cost lands on usage.costUsd. Forks and replays start with a fresh budget. Replay is a debug action, not production work.

A call's cost always counts toward the session total, including a call that also crossed perCall. When an approver accepts a per-call overrun, the same call is still checked against perSession.

A provider that returns token counts without a cost is priced from the static price table before the budget sees the call, as long as the model has a known price. A custom provider that never calls applyEstimatedCost() is still counted. The AzureOpenAIModelProvider in @fabric-harness/azure prices its own usage by deployment name, the same way the SDK's Azure provider does. A deployment named after a model, such as gpt-4o, is priced. Any other name is marked costUnknown.

Both loop runtimes enforce the same budget. The default Pi loop (pi-agent-core) checks each response's cost before its tool calls run, raises the same CostLimitExceededError, emits the same cost_limit event, and honors onExceed: 'approve' and lagged external-scope violations exactly as NativeLoopRuntime does.

Unknown prices

A call has an unknown cost when the provider reports no cost and Harness has no price for the model. Custom endpoints, model ids outside the Pi catalog, and models with no row in the static table all land here. Unknown is not free, so Harness marks that usage costUnknown: true and logs one warning per model. The warning is deduplicated for up to 1,000 distinct model references per process; past that, one suppression notice is logged and later unknown references are still marked costUnknown without a warning. By default such calls count as $0 toward the budget. Set unknownCost: 'fail' so a hard budget fails closed:

const fabric = await init({
  costLimit: {
    perSession: 1.00,
    unknownCost: 'fail',  // 'allow' (default) | 'fail'
  },
});

With 'fail', an unpriced call raises CostLimitExceededError whose context.unknownCost is true and whose context.model names the model. A response that reports no usage at all also counts as unknown, and so does usage that cannot be priced even though the model's price is known: usage that reports only totalTokens (no input, output, audio, STT, or TTS counts), a totalTokens that the reported counts do not account for (it may exceed their sum by at most 1% plus 16 tokens, so { outputTokens: 0, totalTokens: 1_000_000 } is incomplete), a text call that reports output or total tokens but no input or cached-input tokens, a text call that reports no output count ({ inputTokens: 1 } would price the answer at $0; an absent outputTokens is accepted only when a reported totalTokens is no larger than inputTokens, which proves there was no output), a priced field that is not a finite non-negative number, or a provider costUsd that is NaN, negative, or infinite. Such a call is never recorded as $0 spend. applyEstimatedCost() applies the same check before it prices usage from the static table, so neither the built-in adapters (including the Azure OpenAI, Azure AI Foundry and realtime voice providers) nor a custom provider that calls it synthesize a cost from incomplete counts. The usage is left unpriced and isUsageCostUnknown() reports it as unknown. The Pi runtime applies the same rule before trusting Pi's cost, which Pi computes from counts it fills with 0 when a provider omits them. It treats a response whose usage is all zero (the provider sent no usage, or usage: {}) as unknown, since every model call consumes prompt tokens, and it also treats a $0 Pi cost for tokens on a model Pi prices as unknown. Because Pi also turns a missing output count into 0, the Pi runtime treats output: 0 on a response that produced text, thinking, or a tool call as unknown: generating that content always bills output tokens. A reported zero on a response with no content stays known. The built-in adapters set outputTokens only when the provider reports it, so a provider-reported 0 stays a known count and a missing one is detectable. Voice usage (audio tokens, STT seconds, TTS characters) does not need a text output count. The Gemini adapter counts tool-use prompt tokens as input and thinking tokens as output, and reports output only when Gemini sends candidatesTokenCount. A thoughts count alone is part of the output, not all of it, so it leaves the output count missing and the cost unknown. The Bedrock adapter reports prompt-cache reads and writes, so its totals stay explained.

usage.inputTokens includes prompt-cache reads for every provider. cachedInputTokens is the part of inputTokens served from the cache, and cacheWriteTokens is reported separately. OpenAI and Gemini already count cached tokens in their prompt count; the Anthropic, Bedrock and Pi adapters add the cache reads those providers report outside their input count. The completeness check and the price table count cached reads once, so a total that only a second count of the cached prompt would explain is unknown. For a custom provider, a cachedInputTokens larger than inputTokens cannot be a subset and is read as reported separately. With the default 'allow', an invalid costUsd is not added to the budget totals. onExceed: 'approve' still applies, so an approver can accept an unpriced call. Register a price with registerModelPrices() to make a custom model priceable.

Cross-process aggregation

For "tenant X spends ≤ $50/day" or "company-wide ≤ $100/hour" caps, pair perScope + scopeKey + store with a cross-process CostBudgetStore.

import { init, inMemoryCostBudgetStore } from '@fabric-harness/sdk';
import { postgresCostBudgetStore } from '@fabric-harness/node';

const fabric = await init({
  costLimit: {
    perScope: 50.00,
    scopeKey: `tenant:${tenantId}:day:${todayIso}`,
    store: postgresCostBudgetStore({ client: pgClient }),  // or inMemoryCostBudgetStore() for single-process
    onExceed: 'throw',
  },
});

The store is the source of truth, multiple agents / multiple processes share the running total. fabric-harness never interprets scopeKey; you pick the convention (per-tenant, per-day, per-org). Reset semantics (daily rollover, billing period close) are also yours. Call store.reset(scopeKey) from a scheduled task.

Anthropic prompt caching

When an Anthropic response includes cache_read_input_tokens / cache_creation_input_tokens, fabric-harness records them on usage.cachedInputTokens and usage.cacheWriteTokens and adds the cache reads to usage.inputTokens (which always includes cached reads), and the cost calculator discounts billed input tokens by the cached read amount (and adds the cache-write surcharge when present). fh metrics shows a new Cache: read=N write=N line so you can see how much you're saving.

$ fh metrics ask-1f4f...
Tokens: input=120000 output=2400 total=122400
Cache: read=96000 write=0
Cost: $0.046800

Cache-read tokens are billed at ~10% of the standard input rate on Claude models. Long, stable system prompts → big savings.

Per-call cost telemetry

Every model call is enriched with a USD estimate from a static price table (mainline OpenAI, Anthropic, Gemini, Bedrock, Cohere). Cost shows up in fh metrics and on OpenTelemetry spans as gen_ai.usage.cost_usd. See CLI → metrics.

Override or extend the catalog at runtime when you have custom-rate contracts.

import { registerModelPrices } from '@fabric-harness/sdk';

registerModelPrices([
  { provider: 'openai', model: 'gpt-4o', inputPerMTok: 1.5, outputPerMTok: 6, effectiveAt: '2026-05-08', notes: 'Enterprise contract' },
]);

The built-in table includes the current Anthropic, OpenAI, and Google models from the Pi 0.87.1 catalog, including Claude Opus 5.5 ($4 / $20 per million input/output tokens, $0.20 cache read, $5 cache write) and GPT-6 Sol and Luna. Rows imported from the catalog carry effectiveAt: '2026-09-28' and cite the catalog in notes. The claude-opus-4-7 row now uses the catalog's $5 / $25 rates; the earlier $15 / $75 row used legacy Opus 4.1 pricing.

The Pi 1.1 text-model additions carry effectiveAt: '2026-10-12': Claude Sonnet 5.5, Haiku 5.5, GPT-6.1 Sol, and the Daybreak Blue/Red aliases. Their input/output, cache, and long-context rates match the installed Pi 1.1.0 catalog. This is catalog provenance, not a live billing certification. It does not infer realtime audio or image pricing from text-token metadata. Register contract rates and verify vendor billing before relying on a spend cap.

The SDK keeps Pi AI and agent-core within ~1.1.0; a caret range would also admit 1.2. Pi 1.1 requires Node.js 22.19 or newer. Cloudflare consumers retain that generation through the application dependency policy.

Some models bill the whole request at a higher rate once the prompt passes a threshold. A row declares that with tiers, and estimateCostUsd() applies the tier with the highest threshold the prompt exceeds. Prompt size is inputTokens + cacheWriteTokens, where inputTokens includes cached reads. GPT-6 Sol costs $4 / $15 above 272k input tokens, and GPT-6 Luna costs $0.20 / $0.75.

registerModelPrices([
  {
    provider: 'openai', model: 'gpt-6-sol', inputPerMTok: 2, outputPerMTok: 10,
    tiers: [{ inputTokensAbove: 272_000, inputPerMTok: 4, outputPerMTok: 15 }],
    effectiveAt: '2026-09-28',
  },
]);

estimateCostUsd() returns 0 when no row matches, which is ambiguous. Use isModelPriceKnown() or estimateModelCost() when you need to tell an unknown price apart from a free call:

import { estimateModelCost, isModelPriceKnown } from '@fabric-harness/sdk';

isModelPriceKnown('openai/gpt-6-luna');                 // true
estimateModelCost('self-hosted/llama-x', usage);        // { costUsd: 0, known: false }

A price counts as known only when the reference matches deliberately. isModelPriceKnown(), estimateModelCost(), the costUnknown marking on usage, and costLimit.unknownCost: 'fail' all use these rules:

ReferenceKnown when
Bare model id, such as gpt-4oAny row has that model id
provider/model, such as openai/gpt-4oA row exists for that exact provider and model
Provider aliasazure-openai, azure-openai-responses and azure use openai rows; vertex-ai, vertex, google and google-vertex use gemini rows; amazon-bedrock uses bedrock rows
Pass-through gateway, such as vercel-ai-gateway/openai/gpt-4o or openrouter/anthropic/claude-sonnet-4-6The nested provider/model is known under these same rules

A same-named model under any other provider is not known. custom/gpt-4o, openai-compatible/gpt-4o, databricks/..., the generic ai-gateway/... proxy, and cloudflare-ai-gateway/... are unknown until you register a row for them, because a self-hosted endpoint, proxy, or workspace can bill differently from the upstream list price. With unknownCost: 'fail', a call to such a model fails closed instead of being priced from the OpenAI row:

registerModelPrices([
  { provider: 'cloudflare-ai-gateway', model: 'openai/gpt-4o', inputPerMTok: 2.5, outputPerMTok: 10, effectiveAt: '2026-09-28' },
]);
isModelPriceKnown('custom/gpt-4o');                       // false
isModelPriceKnown('azure-openai/gpt-4o');                 // true
isModelPriceKnown('cloudflare-ai-gateway/openai/gpt-4o'); // true (registered above)

lookupModelPrice() and estimateCostUsd() keep their earlier, lenient behavior for existing callers: a provider/model reference with no exact row falls back to any row with the same model id. Do not use them to decide whether a price is known.

Default loop pricing and model metadata

The default Pi loop uses the Pi catalog's cost and context metadata for catalog models such as anthropic/claude-opus-5-5, openai/gpt-6-sol, and openai/gpt-6-luna. A model id that is not in the catalog (a customModels entry, or an unknown id on a registered provider) is a dynamic model with zero metadata. Its Pi cost is $0 because the price is unknown, so Harness prices it from the static table or marks the usage costUnknown. Inspect how a reference resolves with describeModel():

import { createPiAgentLoopRuntime } from '@fabric-harness/sdk/experimental';

const runtime = createPiAgentLoopRuntime();
runtime.describeModel('anthropic/claude-opus-5-5');
// { contextWindow: 1000000, cost: { inputPerMTok: 4, ... }, dynamic: false, costKnown: true, ... }
runtime.describeModel('anthropic/claude-internal-preview');
// { contextWindow: 0, dynamic: true, costKnown: false, ... }

isDynamicModel(model) answers the same question for a Pi model object.

Provider failures in the Pi loop raise the same typed errors as the native loop. A rate limit is a retryable MODEL_RATE_LIMITED FabricError, an authentication failure is MODEL_AUTH_FAILED, and a cancelled call rejects with an AbortError carrying the abort reason. The Pi loop no longer returns empty or partial text for a failed or aborted response. Its turn_end events carry the provider's stopReason and monotonic durationMs. Pass cacheRetention ('none', 'short', or 'long') to createPiAgentLoopRuntime() to control provider prompt-cache markers (for example on Anthropic or Cloudflare AI Gateway requests).

The Pi loop honors the same loop controls as the native loop. maxIterations (default 8) caps the provider requests in one prompt. Tool calls from the last allowed request still run, and the prompt then fails with the native loop's Prompt exceeded maxIterations (n) without a final response. error before another request starts. modelTimeoutMs bounds each request: Pi receives it as timeoutMs, the request's abort signal fires at the deadline, and the loop stops waiting even if the provider ignores the signal. A timed-out request is a retryable MODEL_TIMEOUT. Setting modelRetries or modelRetryDelayMs turns off the provider SDK's own retries (maxRetries: 0) and has Harness retry a transient failure with the native backoff, emitting a model_attempt event with status: 'retry'. A request is retried only when it failed before streaming any output. When neither is set, the provider SDK's default retries apply.

Harness never puts Anthropic betas in a request body. The native Anthropic and Workers AI providers send no beta flags. The Pi loop's Anthropic path, including cloudflare-ai-gateway/claude-* models, sends them as the anthropic-beta header.

The Cloudflare AI Gateway authenticates with the cf-aig-authorization header alone. The Pi loop (Pi 1.x) never lets the Anthropic SDK fill in credentials of its own for those requests, so an Anthropic profile on the machine (~/.config/anthropic, ANTHROPIC_PROFILE) is neither read nor sent to the gateway. Under Pi 0.87 the SDK resolved that profile. A broken one failed the run before any request, and a working one would have added its token to requests bound for Cloudflare.

Pi 1 spells versions in catalog ids with dashes (cloudflare-ai-gateway/claude-sonnet-4-5). The dotted ids Pi 0.87 used (claude-sonnet-4.5) still resolve to the same catalog model. A missing catalog ID may vary only by ., -, or _ between digits, and must match exactly one model within the selected provider. The loop sends that model's canonical wire ID and retains its reasoning, context, output, and pricing metadata. Exact/custom IDs take precedence; ambiguous aliases and unrelated providers remain dynamic or unresolved. Strict static pricing follows the same provider-scoped separator rule and does not override exact custom rates. Pi 1 also renamed the Azure provider from azure-openai-responses to azure; the old id resolves to the new provider, a customModels entry under the old id runs under the new one, and a getApiKey resolver keyed by the old id is still asked when the new one has no key (an empty string counts as no key). A registerModelPrices() row under the old id still prices a dynamic or custom model that now runs under azure, so it keeps counting toward cost budgets. An explicit customModels entry is checked before either alias, so a private endpoint configured for an id is never rerouted.

Stop reasons and truncated tool calls

Built-in providers report a normalized ModelResponse.stopReason when the API returns one: OpenAI-compatible finish_reason (including Azure OpenAI, Workers AI, and gateways that use the OpenAI shape), Anthropic stop_reason, Gemini and Vertex AI finishReason, Bedrock stopReason, and Cohere finish_reason.

stopReasonMeaning
stopThe response ended naturally or at a stop sequence.
lengthThe output token limit cut the response off.
tool_callsThe model stopped to call tools.
content_filterA provider safety filter or refusal ended the response.
otherAny other provider-reported reason.

The field is absent when the provider does not report a reason. Custom providers may set it.

When a response that contains tool calls stops with length, the native loop does not execute any of them, because their arguments may be incomplete. Each call is recorded as a tool_call entry marked executed: false, followed by an error result that asks the model to re-issue it with complete arguments, and an error event with stopReason: 'length' is emitted. Because the call and its error are both in history, later prompts in the same session replay a paired tool-use and tool-result transcript that strict providers accept. Older histories that hold an error result without its call (and policy or approval denials, which record only the error) replay that error as a [Tool error: <tool>] user note. The loop then continues within maxIterations. Incomplete JSON arguments in a truncated response parse to {} instead of failing the turn; malformed arguments in a response that was not truncated still fail loudly.

Streaming calls retry transient failures with the same modelRetries and modelRetryDelayMs bounds as non-streaming calls. See streaming retries. modelTimeoutMs bounds each streaming attempt the same way it bounds a non-streaming call. The provider receives an abort signal that fires when the prompt is cancelled or the attempt runs past the limit, and the loop stops waiting on a stream that ignores it. An attempt that times out is a retryable MODEL_TIMEOUT FabricError, retried within modelRetries. Cancelling the prompt still rejects with an AbortError. A failure in the harness itself while streaming (emitting an event, persisting stream chunks, or recording the attempt) is thrown at once and never triggers another provider call.

Reasoning effort

Reasoning-capable models accept a thinkingLevel controlling how much the model thinks before answering.

type ThinkingLevel = 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';

It is configurable at three scopes, most-specific wins.

const agent = await init({ model: 'cloudflare/@cf/openai/gpt-oss-120b', thinkingLevel: 'medium' });
const session = await agent.session('s1', { thinkingLevel: 'high' });   // per-session override
await session.prompt('think hard about this', { thinkingLevel: 'xhigh' }); // per-call override

The level is capability-gated. Reasoning-capable providers map it to their native control, others ignore it (no error). 'off' (or unset) requests no reasoning.

  • Default loop (pi-agent-core): works for every provider; pi-ai handles capability detection + per-provider mapping and clamps the level to what each model supports.
  • Native Fabric providers: Cloudflare Workers AI binding & OpenAI-compatible map to reasoning_effort; Gemini/Vertex to thinkingConfig.thinkingBudget. Anthropic maps current Claude models (Opus and Sonnet 4.6 and later, and every Claude 5 family) to adaptive thinking with output_config.effort, because they reject thinking.budget_tokens; xhigh falls back to high on models without that level. Older extended-thinking models (Claude 3.7 and the earlier 4.x models) keep thinking.budget_tokens, with max_tokens raised above the budget. Gated to known reasoning families (o-series / gpt-5 / gpt-oss, Claude 3.7/4.x/5.x, Gemini 2.5). Current Claude models think by default, and the thinking counts against max_tokens, so set maxTokens well above the provider's 1024 default when you use them. Adaptive thinking for current Claude models requires @fabric-harness/sdk 6.5.1 or newer, which projects generated by CLI 6.7.5 or newer pin. From 6.5.1 the Anthropic stream fails with a retryable connection error when it closes before message_stop, and surfaces a mid-stream error frame as a provider error, so partial output is never returned as a complete response.