agentleFS
seifalmotazseifalmotaz/agent-weave/llms-full.txt

agent-weave

llms.txt2 starsChanged 12 days agoMITView on GitHub

Build AI applications in Dart with a Serverpod backend and Flutter or TanStack AI clients. Define typed tools, stream responses, pause for approval, and keep conversation history on your server. AgentWeave is independent and unofficial. It is not maintained or endorsed by TanStack, OpenAI, or Serverpod. Development version. The packages are not published to pub.dev yet. Start from this workspace. See coverage and limits before using it in production. Requires Dart 3.12.2 or later. The integration targets Serverpod 4.1.0. The…

  • Reads credentials
  • Commits and pushes
  • In this repository2 other files it gives its agents.

The file

Show its rules and text

We split this llms-full.txt into the rules it gives an agent

20 rules. About 0 are common, 8 are distinctive, and 12 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈8

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 12

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Run dart run tool/check.dart for the normal checks.

    line 158
  2. Distinctive:

    Verify package publication, compatibility across supported Dart SDKs, security, performance/backpressure, and operational failure cases …

    line 245
  3. Very specific:

    Use generateText for a single backend operation, generateObject<T> for a schema-validated Dart value, and AiAgent<C>.generate for a …

    line 278
  4. Very specific:

    Run dart run examples/review_cases/consumer.dart from the workspace root.

    line 287
  5. Very specific:

    Keep issues in backend diagnostics.

    line 366
  6. Very specific:

    Run dart run examples/schema_diagnostics.dart for a complete offline example.

    line 383
  7. Distinctive:

    Keep the agent factory in your backend.

    line 388
  8. Distinctive:

    Do not add a new user message until pending tools have been resolved.

    line 454
  9. Very specific:

    Create one CancellationToken per operation and pass it to generate or run.

    line 476
  10. Very specific:

    Run dart run examples/cancellation.dart to cancel an already-started offline provider and verify its cancelled checkpoint.

    line 501
  11. Very specific:

    Run it from the workspace root with dart run examples/native_streaming.dart.

    line 641
  12. Very specific:

    Run these commands from the cloned workspace after dart pub get:

    line 666
  13. Very specific:

    Use context.idempotencyKey at the destination service to reconcile retries.

    line 823
  14. Very specific:

    Run dart run examples/cancellation.dart to cancel a provider after it starts.

    line 831
  15. Very specific:

    Run dart run examples/schema_diagnostics.dart to inspect a rejected structured value on the backend.

    line 832
  16. Distinctive:

    No PostgreSQL, Serverpod restart, Flutter device, local model server, paid provider, network, crash recovery, or complete provider option …

    line 874
  17. Distinctive:

    Document what cancellation guarantees: the cooperative fake stops when its token is signalled.

    line 905
  18. Distinctive:

    No paid calls, external provider keys, real inference server, real HTTP in-flight cancellation, process restart, injected database failure, …

    line 908
  19. Distinctive:

    All checks used offline loopback responses with synthetic data.

    line 1006
  20. Distinctive:

    Not tested: live Anthropic behavior, actual search results, live container lifecycle, other hosted tool families, backend restart with …

    line 1169

≈ “Common” is an estimate: at least 1 in 5 of the 3,727 llms.txt files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
llms-full.txt
# Source: README.md

# AgentWeave

Build AI applications in Dart with a Serverpod backend and Flutter or TanStack
AI clients. Define typed tools, stream responses, pause for approval, and keep
conversation history on your server.

AgentWeave is independent and unofficial. It is not maintained or endorsed by
TanStack, OpenAI, or Serverpod.

**Development version.** The packages are not published to pub.dev yet. Start
from this workspace. See [coverage and limits](docs/compatibility.md) before
using it in production.

## Packages

| Package | Use it for |
| --- | --- |
| [`agent_weave`](packages/agent_weave) | Provider contracts, agent loops, typed tools, approvals, generation tasks, and protocol events |
| [`agent_weave_anthropic`](packages/agent_weave_anthropic) | Native Anthropic JSON/SSE, Messages agent loop, MCP, private replay, cache controls, and cancellation |
| [`agent_weave_ollama`](packages/agent_weave_ollama) | Local Ollama chat, typed options, embeddings and native NDJSON |
| [`agent_weave_dart_frog`](packages/agent_weave_dart_frog) | Authenticated Dart Frog chat, history, replay and generation handlers |
| [`agent_weave_http`](packages/agent_weave_http) | Shared JSON HTTP transport for provider adapters |
| [`agent_weave_vercel_gateway`](packages/agent_weave_vercel_gateway) | Vercel AI Gateway Chat and Responses adapters |
| [`agent_weave_cloudflare`](packages/agent_weave_cloudflare) | Workers AI and AI Gateway REST clients and selected model adapters |
| [`agent_weave_together`](packages/agent_weave_together) | Native Together Chat Completions and typed options |
| [`agent_weave_openrouter`](packages/agent_weave_openrouter) | OpenRouter native Chat/Responses, dedicated images, discovery, routing and replay |
| [`agent_weave_openai`](packages/agent_weave_openai) | Responses, Chat Completions, images, audio, Decisions, embeddings, video jobs, realtime, and access to provider resources |
| [`agent_weave_serverpod`](packages/agent_weave_serverpod) | Authenticated HTTP/SSE routes and native endpoint helpers |
| [`agent_weave_serverpod_client`](packages/agent_weave_serverpod_client) | Connect the existing TanStack Dart client to generated Serverpod streaming methods |
| [`agent_weave_serverpod_storage_server`](packages/agent_weave_serverpod_storage_server) | Optional PostgreSQL history, run reservations, and event journals |
| [`agent_weave_serverpod_storage_client`](packages/agent_weave_serverpod_storage_client) | Generated types for the optional Serverpod module |

Requires Dart 3.12.2 or later. The integration targets Serverpod 4.1.0.

## Try the workspace

```sh
git clone https://github.com/seifalmotaz/agent-weave.git
cd agent-weave
dart pub get
dart run examples/basic_chat.dart
```

The first example uses an offline provider. It needs no API key and makes no
paid requests. See [the Serverpod example](examples/serverpod/README.md) for a
backend with a database, HTTP streaming, and generated Dart endpoints.

Next, run the [offline support application](docs/offline-support.md) for typed
tools, approval, shared memory history, and a synthetic reference. The
[Dart API recipes](docs/dart-api.md) include runnable cancellation and private
schema-diagnostic examples.

## Define an agent

```dart
import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_openai/agent_weave_openai.dart' as openai;

final client = openai.OpenAIClient.fromEnvironment();
final agent = AiAgent<void>(
  model: openai.OpenAIResponsesModel(
    client: client,
    model: 'gpt-5.4-nano',
  ),
  instructions: 'Answer briefly.',
  maxSteps: 8,
  maxOutputTokens: 512,
);

// Derive ownerId from backend authentication, never from the request body.
final updates = agent.stream(
  ChatRequest(
    threadId: 'conversation-1',
    runId: 'run-1',
    messages: [ChatMessage.user('Hello', id: 'message-1')],
  ),
  ownerId: authenticatedUserId,
  context: null,
);
await for (final update in updates) {
  switch (update) {
    case AgentTextDelta(:final text):
      print(text);
    case AgentRunFinished(:final result):
      print(result.status.name); // The typed result belongs to this same run.
    default:
      break;
  }
}
```

Close the provider client when your application shuts down. Keep OpenAI keys
on the backend. For remote tool approvals and owner-bound credentials, see [MCP approvals](docs/openai-mcp.md). Use the provider import prefix because provider SDK types can
share names with core types.

## Connect Flutter through Serverpod

```dart
final chat = ChatClient(
  threadId: 'conversation-1',
  persistence: const ChatPersistenceOptions.server(),
  connection: serverpodConnection(
    send: serverpodClient.ai.chat,
    loadHistory: serverpodClient.ai.history,
  ),
);

final subscription = chat.states.listen(renderConversation);
await chat.attach(); // Restore server-owned messages and pending approvals.
await chat.sendText('Hello');

// At disposal:
await subscription.cancel();
await chat.dispose();
```

The generated Serverpod client handles authentication and its WebSocket.
AgentWeave handles conversion to the existing TanStack Dart client protocol.
For JavaScript, use the official client's `fetchServerSentEvents` against an
`AgentChatRoute` HTTP endpoint.

## Learn and contribute

[Browse the documentation site](https://seifalmotaz.github.io/agent-weave/).

- [Acceptance roadmap and open work](ROADMAP.md)
- [Dart API, typed results, and application recipes](docs/dart-api.md)
- [Typed native streaming](docs/native-streaming.md)
- [Dart Frog backend](docs/dart-frog.md)
- [Ollama local models](docs/ollama.md)
- [Architecture and ownership](docs/architecture.md)
- [Typed tools and approvals](docs/tools.md)
- [Persisted approval contracts and migration](docs/approval-contracts.md)
- [Provider author guide](docs/providers.md)
- [Documents](docs/documents.md) · [Citations](docs/citations.md) · [Output references](docs/output-references.md)
- [OpenAI native computer use](docs/computer-use.md)
- [OpenAI capabilities](docs/openai.md)
- [OpenAI hosted tools and images](docs/openai-hosted.md)
- [OpenAI custom text tools](docs/openai-custom-tools.md)
- [Anthropic Messages](docs/anthropic.md)
- [Anthropic hosted tools and paused turns](docs/anthropic-hosted.md)
- [Anthropic MCP connector](docs/anthropic-mcp.md)
- [Anthropic computer tools](docs/anthropic-computer.md)
- [OpenRouter](docs/openrouter.md)
- [OpenRouter Chat images](docs/openrouter-images.md)
- [OpenRouter dedicated Image API](docs/openrouter-image-api.md)
- [Cloudflare Workers AI and AI Gateway](docs/cloudflare.md)
- [Together Chat Completions](docs/together.md)
- [Vercel AI Gateway](docs/vercel-gateway.md)
- [Compatibility and limitations](docs/compatibility.md)
- [Validation evidence](docs/validation.md)
- [Upstream updates](docs/updating.md)
- [Contribution guide](CONTRIBUTING.md)
- [Coding-agent entry point](AGENTS.md) and [LLM index](llms.txt)

Run `dart run tool/check.dart` for the normal checks. Paid provider tests are
separate and opt-in.


# Source: ROADMAP.md

# AgentWeave acceptance roadmap

The target is a Dart-first AI SDK for Serverpod developers, with useful APIs for
other Dart backends and Flutter with hosted or local models. TanStack client
interoperability must remain available; it must not dictate the native Dart API.
A passing fixture suite is not evidence of production maturity or a 10/10 SDK.

## Acceptance requirements still open

- Independent developer agents must write and run consumer applications across
  multiple scenarios and score discoverability, clarity, type safety, debugging,
  and testing. Record failures and rerun after fixes. Use GPT-6.1 Terra with low
  or medium reasoning. The latest general offline review is 8.5/10. The native Anthropic transport path scored
  8.4/10 and its computer-tool path scored 7.8/10. The targeted Dart Frog and Ollama
  paths scored 8.0/10 and 7.8/10. Neither is an acceptance pass.
- Complete native provider coverage for OpenAI, Anthropic, OpenRouter, Together,
  Vercel AI Gateway, and Cloudflare, with a documented custom-provider contract.
  Track each endpoint, nested parameter, tool/event union, query, header, cache
  option, and continuation behavior against a dated authoritative specification.
  An OpenAI-compatible URL or SDK export does not establish native parity.
- Selected OpenAI Responses computer calls now have explicit native events,
  application-controlled execution, approval/safety handling, private replay,
  PostgreSQL and client fixtures. Anthropic computer toolset actions now have
  equivalent native approval, persistence and batch-failure contracts. Real
  driver/model behavior and other native
  tool continuations remain open; this is not complete computer-use parity.
- Selected OpenAI hosted Responses tools now have lossless native options,
  terminal validation, private replay and ordered completed image parts. Hosted
  progress, precise native-coordinate citation highlights, partial images,
  shell/patch and live provider
  behavior remain open. Direct OpenAI custom text tools now have typed execution,
  namespaces, approvals/denial, private replay and durable fixtures. Programmatic
  and asynchronous custom execution remain open. Compatible endpoints do not inherit these claims.
- Anthropic hosted blocks, container replay and counted paused turns now have
  local fixture and consumer coverage. Live search/code/container behavior,
  browser tools, live MCP/citation behavior and full nested semantics remain
  open. Constructor coverage is not workflow certification.
- OpenRouter Chat now handles selected completed text/image output, with private
  replay across approvals. Its dedicated Image API now has typed discovery, native
  SSE, same-request JSON fallback and durable Serverpod generation fixtures.
  Live provider behavior, streamed Chat image extensions and audio remain open.
  Native Cloudflare text now streams documented response
  chunks; schema and traditional tools stay buffered. Model support and live
  behavior remain unverified.
- Anthropic now normalizes all five pinned citation variants into typed text
  annotations, client metadata and private replay across approvals. Other provider
  citations, custom-content document inputs, live quality and device rendering
  remain open.
- Native OpenAI output references now preserve all four Responses annotation
  forms and completed Chat URL references, including empty segments and opaque
  native positions. Other provider references, live indexing conventions,
  authorized download recipes and device rendering remain open.
- Native Anthropic Messages MCP now supports explicit legacy/2025/2026 modes,
  private use/result/listing replay, owner-bound credentials, mixed local
  approvals, immutable provider profiles and uncertain-send protection. Live
  remote execution, OAuth providers, inline tool changes and platform acceptance
  remain open; offline tests are not a complete native API certification.
- Native OpenAI Responses MCP now supports private discovery/call replay, multiple
  server configurations, credential resolution and approval/denial decisions.
  Generic client, loopback and durable fixtures do not establish live remote
  execution, identity-provider integration, tunnel/connector availability or
  exactly-once effects. These remain open.
- Preserve provider options and metadata without letting configuration silently
  replace server-owned history, schemas, tools, or execution bounds. Unsupported
  response modes must fail explicitly or use a clearly separate native API.
- Provide runnable Serverpod examples for streamed chat, persisted approvals,
  typed output, tools, cancellation/reconnect, media and authentication. Verify
  recreation/restart behavior and failure recovery with PostgreSQL.
- Provide equivalent framework-independent recipes and adapters for Dart Frog
  and other HTTP servers; verify Flutter device/local-provider behavior.
  Dart Frog now has local HTTP and official JavaScript client fixtures. Ollama
  has native NDJSON fixtures and a consumer example; neither establishes live
  model, device, proxy or production deployment behavior.
- Evaluate whether protocol events should move into an optional TanStack adapter
  package. Keep existing client compatibility tests throughout any migration.
- Publish searchable, accessible GitHub Pages documentation with executable
  recipes, precise capability tables, API references, migration/update guides,
  and coding-agent instructions. Validate the deployed website separately.
- Establish provider contract suites, schema/parameter inventories and upstream
  update checks. Contribute reproducible missing SDK fields and union cases
  upstream where that is the correct fix; keep PRs narrowly scoped and tested.
- Verify package publication, compatibility across supported Dart SDKs, security,
  performance/backpressure, and operational failure cases before a stable claim.

## Native Dart streaming

`AiAgent.stream` and `streamText` now emit sealed Dart updates with the typed
result from the same execution. Native callers no longer parse TanStack maps or
run the model twice to obtain a result. Existing clients keep `AiAgent.run`.
Cancellation, backpressure, errors, approvals and PostgreSQL recreation have
local checks. Independent native streaming review improved from 4/10 to 8.5/10;
this is a scoped score, not overall acceptance. Protocol journals still live in
core, so optional package extraction and broader operational validation remain
open.

## Current reliability/DX increment

Implemented: typed `generateText`, `generateObject`, and `AiAgent.generate`;
immutable run results and usage; typed approval resolutions; backend-only field-level schema diagnostics; scripted test
providers; atomic final event/checkpoint/release; safer observer handling;
separate caller/model/output/tool/step-limit errors with safe Future messages;
exact versioned pending tool contracts independent of client schema hashes; guarded provider request
configuration; canonical reasoning replay includes; actual provider model usage.

Tests now exercise the same storage contract against memory and PostgreSQL,
recreated PostgreSQL approval flows, local loopback HTTP, both existing clients,
and the new native Dart API. Consult validation results for the exact checks.
These improvements do not complete the requirements above.


# Source: docs/dart-api.md

# Dart API and application recipes

Use `generateText` for a single backend operation, `generateObject<T>` for a
schema-validated Dart value, and `AiAgent<C>.generate` for a conversation with
trusted application context and storage. Use `streamText` or `AiAgent.stream` for typed incremental updates and the final
result from one execution; see [native streaming](native-streaming.md).
`AiAgent.run` remains the JSON transport API for existing clients. All of these
share the same validation, storage and tool loop.

Runnable offline examples: [consumer scenarios](https://github.com/seifalmotaz/agent-weave/blob/main/examples/review_cases/consumer.dart)
and [failure diagnostics](https://github.com/seifalmotaz/agent-weave/blob/main/examples/review_cases/failures.dart).
Run `dart run examples/review_cases/consumer.dart` from the workspace root.
For a complete application with typed tools, approval, shared memory history,
and a synthetic file reference, run the [offline support example](offline-support.md).

## Generate text

```dart
import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_openai/agent_weave_openai.dart' as openai;

final client = openai.OpenAIClient.fromEnvironment();
try {
  final result = await generateText(
    model: openai.OpenAIResponsesModel(client: client, model: 'gpt-5.4-nano'),
    prompt: 'Summarize the support ticket.',
    maxOutputTokens: 256,
  );
  print(result.text);
  print(result.usage?.outputTokens); // null means unreported, not zero.
} finally {
  client.close();
}
```

Pass exactly one of `prompt` or `messages`. The `messages` argument is trusted
backend history and can include assistant/tool messages. Never pass unchecked
browser history as trusted seed data. HTTP routes accept only user additions
to server-owned history.

`result.text` contains the final assistant message. `responseMessages` includes
this run's intermediate assistant/tool messages. `images` is an immutable list of
images produced by assistant messages in this run, including intermediate tool
steps; it excludes user inputs and previous runs. `messages` is the complete
server-side conversation snapshot, including private provider continuation
state. Use `chatHydration` when returning stored history to a UI.

## Decode structured output

```dart
final answer = await generateObject<int>(
  model: model,
  prompt: 'Return the number of days in a week.',
  schema: const {
    'type': 'object',
    'properties': {'days': {'type': 'integer'}},
    'required': ['days'],
    'additionalProperties': false,
  },
  decode: (json) => (json as Map<String, Object?>)['days'] as int,
);
print(answer.value);
print(answer.generation.usage?.inputTokens);
```

Validation runs before your decoder. Decoder exceptions are application errors
and propagate normally. A provider that does not support structured output is
rejected before submission.

### Inspect schema errors on the backend

`validateSchema` throws `SchemaValidationException`, a `FormatException` subclass.
Its immutable `issues` list contains `instancePath`, `schemaPath`, and `message`
from the installed JSON Schema validator. Tool input, tool output, structured
output, and edited approval arguments use the same validation function.
An agent failure retains this exception in its private `cause`.

```dart
try {
  await agent.generate(request, ownerId: ownerId, context: context);
} on AgentRunException catch (error) {
  if (error.cause case SchemaValidationException(:final issues)) {
    for (final issue in issues) {
      backendLogger.error('${issue.instancePath}: ${issue.message}');
    }
  }
  showSafeError(error.message);
}
```

Keep `issues` in backend diagnostics. Messages can include input or schema values.
The exception's default `message` and `toString()` remain generic, and client
errors do not include the issues. Original model text and user messages still
belong to conversation history; this does not redact their contents.

Paths follow `json_schema` conventions, not escaped JSON Pointers. A root path
can be empty; property names containing `/` or `~` are not escaped. Combinators
such as `oneOf` can report only a summary without nested branch errors.
Edited tool arguments are validated against their original schema separately
from the approval envelope, preserving their field paths and local references.
The public approval schema and its wire hash are unchanged. The pinned validator
cannot resolve some local references when directly validating that embedded
public approval union. Both real clients do complete the tested raw object
schema's local-reference edit; see [client edited approvals](tools.md#edit-tool-arguments-in-a-client).
They can forward an invalid edit for the backend to reject. Client-side schema
validation and server-side authorization remain separate responsibilities.

Run `dart run examples/schema_diagnostics.dart` for a complete offline example.
It prints a safe `INVALID_OUTPUT` message and a private `/priority` diagnostic.

## Typed tools, approvals, and durable Serverpod history

Keep the agent factory in your backend. It can be recreated on each request;
the shared database holds the conversation and pending approval.

```dart
AiAgent<Session> agentFor(Session session) => AiAgent<Session>(
  model: model,
  store: ServerpodRunStore(session),
  tools: [
    Tool<String, String, Session>(
      name: 'send_message',
      description: 'Send an approved message',
      needsApproval: true,
      inputSchema: const {
        'type': 'object',
        'properties': {'text': {'type': 'string'}},
        'required': ['text'],
        'additionalProperties': false,
      },
      outputSchema: const {'type': 'string'},
      decode: (json) => json['text'] as String,
      encode: (result) => result,
      execute: (text, context) => messageService.send(
        ownerId: context.ownerId,
        text: text,
        idempotencyKey: context.idempotencyKey,
      ),
    ),
  ],
);
```

`messageService` is your application service. It must enforce permissions and
use the idempotency key at the destination. AgentWeave cannot make an external
service execute exactly once after a crash.

```dart
final paused = await agentFor(session).generate(
  ChatRequest(
    threadId: conversationId,
    runId: firstRunId,
    messages: [ChatMessage.user('Send the update', id: userMessageId)],
  ),
  ownerId: session.authenticated!.userIdentifier,
  context: session,
);

if (paused.status == RunStatus.interrupted) {
  final completed = await agentFor(session).generate(
    ChatRequest(
      threadId: paused.threadId,
      runId: newRunId,
      parentRunId: paused.runId,
      resume: [for (final interrupt in paused.interrupts) interrupt.approve()],
    ),
    ownerId: session.authenticated!.userIdentifier,
    context: session,
  );
  print(completed.text);
}
```

The approval loop illustrates the backend API; a real application waits for a
human decision. Do not automatically approve tools in production. Use
`reject()`, `approve(editedArgs: ...)`, or `cancel()` as appropriate. Client-tool
interrupts use `resolve(output)` and reject approval methods. Resolve every
pending interrupt once, using a new run ID and the interrupted parent run ID.
Do not add a new user message until pending tools have been resolved.

For UI streaming use the authenticated endpoint in the
[Serverpod example](../examples/serverpod/README.md). Its dedicated stream
session remains open until the response closes.

## Restore a client-side conversation

Use `serverpodConnection(send: client.ai.chat, loadHistory: client.ai.history)`
with `persistence: const ChatPersistenceOptions.server()` on `ChatClient`, then
`await chat.attach()`. Register matching `ChatClientTool` input/output schemas
for typed tool approvals. Without server persistence the client does not call
the loader; without matching schemas a pending tool may be exposed as a generic
interrupt rather than a typed tool approval.

The [runnable two-command approval example](../examples/serverpod/README.md#run-an-approval-across-process-restarts)
includes the complete client setup and an automated real process-restart test.
Native `loadHistory` supports full snapshots. Advanced paging remains available
through an explicit `hydrate` callback.

## Cancel a running operation

Create one `CancellationToken` per operation and pass it to `generate` or `run`.
Your application's stop action calls `cancel()` on that token.

```dart
final cancellation = CancellationToken();
final work = agent.generate(
  request,
  ownerId: ownerId,
  context: context,
  cancellation: cancellation,
);
// Call this from the application's stop action while work is in progress.
cancellation.cancel();
try {
  await work;
} on RunCancelled {
  // Treat this as a cancelled run, not a completed answer.
}
```

Cancellation is cooperative. Custom models and tool executors must observe
`context.cancellation` or the invocation's token. Cancellation does not undo an
external effect or prove the provider stopped billing. Retained partial history
is available from the run store; use `chatHydration` to expose a safe snapshot.

Run `dart run examples/cancellation.dart` to cancel an already-started offline
provider and verify its cancelled checkpoint. It needs no timer or API key.

## Handle failures

```dart
try {
  final result = await agent.generate(request, ownerId: ownerId, context: context);
  // A paused result has status interrupted and typed tool interrupts.
} on AgentRunException catch (error) {
  logger.error(error.code, error.cause, error.causeStackTrace);
  // error.result retains partial text and this run's snapshot.
} on RunCancelled {
  // Cancellation is deliberate and does not imply a completed answer.
} on RunConflict {
  // Another run owns the thread, the ID was reused, or the parent is stale.
}
```

| Code | Meaning |
| --- | --- |
| `INVALID_INPUT` | Invalid caller input or continuation |
| `INVALID_OUTPUT` | Invalid provider JSON or tool-call format |
| `MODEL_FAILED` | Model invocation failed or ended prematurely |
| `TOOL_FAILED` | A tool failed; reconcile possible external effects |
| `STEP_LIMIT` | The configured agent loop bound was reached |

Private causes stay on the backend. Error observers are best-effort synchronous
callbacks; a throwing observer does not replace the original failure. Do not
supply an unawaited asynchronous logger callback. Client streaming errors expose
safe codes/messages rather than private exceptions.

## Test without a provider account

```dart
import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave/testing.dart';

final model = ScriptedChatModel(steps: [
  [
    const TextDelta('Hello'),
    const TokenUsage(inputTokens: 2, outputTokens: 1),
    const ModelFinished(),
  ],
]);
final result = await generateText(model: model, prompt: 'Hi');
assert(result.text == 'Hello');
assert(model.requests.single.messages.single.text == 'Hi');
assert(model.remainingSteps == 0);
```

Declare the capabilities used by your fixture (`tools`, `structuredOutput`,
multimodal input). Supply one step per model invocation, including post-tool
invocations. Missing terminal events and exhausted scripts fail explicitly.
For custom providers see [the provider guide](providers.md).

## Connect a local OpenAI-compatible endpoint

```dart
final client = openai.OpenAIClient(
  config: openai.OpenAIConfig(
    baseUrl: 'http://localhost:11434/v1',
    authProvider: openai.ApiKeyProvider('local-development'),
  ),
);
final model = openai.OpenAIChatModel(client: client, model: 'your-installed-model');
final result = await generateText(model: model, prompt: 'Hello');
```

This uses the Chat Completions wire format; the target must implement it.
Local server/model capability support varies. This recipe is not a claim of
Ollama, OpenRouter, Together, or gateway-specific option parity. Use an
application-controlled URL; keep hosted provider keys on the backend. Flutter
may call a local/on-device provider directly, but this repository has not yet
verified mobile device networking or model execution.

## Structured output in history

Successful schema-validated assistant messages retain a `StructuredMessageOutput`
in `ChatMessage.structuredOutput`. Its `data` is immutable JSON parsed from
`raw`; providers still replay the original text. `chatHydration` returns a
completed structured-output part instead of duplicating that text as a plain
answer. Legacy messages without this field keep their existing representation.

Provider-owned pauses count against `maxSteps`. A paused intermediate response
can contain progress text; only the final response is validated against the
output schema. The streaming protocol replaces that intermediate structured UI
state with a sanitized message snapshot before continuing.


## Safe failure messages

`AgentRunException.code` classifies a failed agent run. Its `message` is
the same sanitized explanation sent in a `RUN_ERROR` event and can be displayed
to the user. Its `cause` and `causeStackTrace` are private backend diagnostics.
For example, changed or legacy pending tool contracts provide a recovery
instruction without exposing schemas or native configuration. See
[approval contract migration](approval-contracts.md).


# Source: docs/native-streaming.md

# Typed native streaming

Use `streamText` to consume typed Dart updates from a stateless run. The final `AgentRunFinished` carries the result of that same run; it does not start a second generation. This offline example uses `ScriptedChatModel`, so it runs without credentials or network access. Replace it with a configured provider model in an application.

```dart
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave/testing.dart';

Future<void> main() async {
  // Replace this deterministic model with a configured provider model.
  final model = ScriptedChatModel(
    steps: [
      [const TextDelta('Hello'), const TextDelta('!'), const ModelFinished()],
    ],
  );

  try {
    await for (final update in streamText(model: model, prompt: 'Say hello')) {
      switch (update) {
        case AgentTextDelta(:final text):
          stdout.write(text);
        case AgentRunFinished(:final result):
          print('\nRun status: ${result.status.name}');
        default:
          break;
      }
    }
  } on AgentRunException catch (error) {
    print('Run failed: ${error.message}');
    // error.result contains the partial backend snapshot for recovery.
  } on RunCancelled {
    print('Run cancelled.');
  }
}
```

Run it from the workspace root with `dart run examples/native_streaming.dart`.

## Updates and results

`AgentTextDelta` and `AgentReasoningDelta` carry text and its assistant message ID. `AgentContentPart` carries a non-text part and its offset in the assistant text. `AgentCitation` and `AgentReference` carry typed metadata and their message-local indices. `AgentUsage` reports usage when supplied by the model. Native updates are Dart objects: callers do not parse wire event maps to use this API.

Updates before `AgentRunFinished` are provisional. An `AgentToolCallReady` is a proposed call; it does not prove approval or execution. An `AgentToolResult` identifies a recorded outcome, including executed, denied, skipped and client-resolved calls; its JSON collection values are deeply immutable snapshots. Return JSON values from `Tool.encode`, converting custom Dart objects with your own serializer first. An effect may occur before a later failure or cancellation, so do not infer rollback from a missing final update. The final result follows committed completion or interruption and includes the status, messages, usage and any interrupts.

The updates and `AgentResult` are **backend** data. Tool arguments, results, reasoning and the final result can contain private information; the result can also contain private provider continuation state. Use the existing `chatHydration` projection when serving UI history, and apply your application's authorization and data-handling rules. Native streaming provides typed access independently of wire-map parsing; the runtime still maintains its existing wire event journal, and no optional package extraction is implied.

## Failures and cancellation

A classified runtime failure throws `AgentRunException`. Precondition, setup or storage failures can propagate their original exception, matching `generate`. Its safe `message` and `code` are suitable for reporting; `result` provides the partial backend result, and the private cause is for trusted diagnostics. A caller-provided `CancellationToken` can cancel a run and yields `RunCancelled` after cleanup. Cancelling the stream subscription stops delivery and requests cleanup; the closed subscription does not receive a later cancellation error. Custom models and tools must honor cancellation; underlying application work can continue if it cannot be cancelled. Neither cancellation mechanism proves that a dispatched remote provider effect stopped.

## Stateful agents and approvals

For resumable approvals, persistent threads or typed application context, use `AiAgent<C>.stream` with a `ChatRequest`, trusted `ownerId`, and trusted `context`. Reuse the agent's store when resuming. The stateless `streamText` helper does not expose its internal store for a later resume. A finished update can have `RunStatus.interrupted`; inspect `result.interrupts` and obtain the user's decision before resuming. Each `ToolInterrupt` provides `approve()`, `reject()`, or, for a client-executed tool, `resolve(output)` or `cancel()` as appropriate. Provider approvals may also accept a reason; editing arguments applies only to supported local approvals.

Resume by issuing another `agent.stream` call with the same thread ID and trusted owner/context, a new run ID, the interrupted run's ID as `parentRunId`, and the collected typed answers in `ChatRequest.resume`. Collect the entire approval batch in your application flow and show only authorized details to the user. The runtime validates the batch and stored tool/model contracts before proceeding. A pause is not a tool result and denial is not a local execution.


# Source: docs/offline-support.md

# Run a support workflow without an API key

Run these commands from the cloned workspace after `dart pub get`:

```sh
dart run examples/offline_support.dart
dart run examples/offline_support.dart --approve
```

The first command prints an interrupted result and `Application effects: 0`.
The second starts a fresh demo, pauses, then simulates a human approval. It
prints a completed result, `Application effects: 1`, and `Reference: Support policy`.
Neither command uses a network service or bills a provider.

Each command starts its own `MemoryRunStore`. The approved path recreates the
agent inside the same process with that shared store. It does not restore data
across process restarts. Use the [Serverpod restart example](../examples/serverpod/README.md#run-an-approval-across-process-restarts)
for durable database history.

## Run the complete application

The source below is the checked-in `examples/offline_support.dart`. Copy it to
a Dart file in the workspace and run it with `--approve` for the completed path.

```dart
import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave/testing.dart';

const ticketSchema = <String, Object?>{
  'type': 'object',
  'properties': {
    'ticket': {'type': 'integer'},
  },
  'required': ['ticket'],
  'additionalProperties': false,
};

final class SupportDesk {
  final _completed = <String, String>{};
  int get escalations => _completed.length;

  String escalate(int ticket, ToolContext<SupportDesk> context) =>
      _completed.putIfAbsent(
        context.idempotencyKey,
        () => 'Ticket $ticket escalated for ${context.ownerId}',
      );
}

Future<void> main(List<String> arguments) async {
  const finalAnswer = 'Ticket 42 is now in the supervisor queue.';
  final desk = SupportDesk();
  final store = MemoryRunStore();
  final tool = Tool<int, String, SupportDesk>(
    name: 'escalate',
    description: 'Escalate a support ticket after approval',
    inputSchema: ticketSchema,
    outputSchema: const {'type': 'string'},
    needsApproval: true,
    decode: (json) => json['ticket'] as int,
    encode: (value) => value,
    execute: (ticket, context) => context.value.escalate(ticket, context),
  );
  AiAgent<SupportDesk> agent(ChatModel model) =>
      AiAgent<SupportDesk>(model: model, store: store, tools: [tool]);
  final paused =
      await agent(
        ScriptedChatModel(
          capabilities: const ModelCapabilities(tools: true),
          steps: [
            [
              const TextDelta('I can escalate ticket 42 for review.'),
              ToolCallReady(
                ToolCall(
                  id: 'escalation',
                  name: 'escalate',
                  arguments: {'ticket': 42},
                ),
              ),
              const TokenUsage(inputTokens: 8, outputTokens: 4),
              const ModelFinished(),
            ],
          ],
        ),
      ).generate(
        ChatRequest(
          threadId: 'support',
          runId: 'proposal',
          messages: [ChatMessage.user('Escalate ticket 42', id: 'question')],
        ),
        ownerId: 'demo-user',
        context: desk,
      );
  print('${paused.status.name}: ${paused.text}');
  print('Application effects: ${desk.escalations}');
  if (paused.status != RunStatus.interrupted || desk.escalations != 0) {
    throw StateError('The tool must wait for approval before causing effects.');
  }
  if (!arguments.contains('--approve')) {
    print('Use --approve to exercise approval in a fresh demo process.');
    return;
  }
  // This CLI flag simulates a recorded human decision. No external service runs.
  final completed =
      await agent(
        ScriptedChatModel(
          capabilities: const ModelCapabilities(tools: true),
          steps: [
            [
              const TextDelta(finalAnswer),
              ReferenceReady(
                OutputReference(
                  provider: 'demo',
                  source: FileCitationSource(
                    provider: 'demo',
                    fileId: 'synthetic-policy',
                    filename: 'Support policy',
                  ),
                  partStart: 0,
                  partEnd: finalAnswer.length,
                  position: FileListPosition(0),
                ),
              ),
              const ModelFinished(),
            ],
          ],
        ),
      ).generate(
        ChatRequest(
          threadId: paused.threadId,
          runId: 'approved',
          parentRunId: paused.runId,
          resume: [paused.interrupts.single.approve()],
        ),
        ownerId: 'demo-user',
        context: desk,
      );
  print('${completed.status.name}: ${completed.text}');
  print('Application effects: ${desk.escalations}');
  if (completed.status != RunStatus.completed ||
      completed.text != finalAnswer ||
      desk.escalations != 1 ||
      completed.responseMessages.last.references.single.source.title !=
          'Support policy') {
    throw StateError(
      'The approved run did not retain its result and reference.',
    );
  }
  for (final message in completed.responseMessages) {
    for (final reference in message.references) {
      print('Reference: ${reference.source.title}');
    }
  }
}
```

The CLI flag represents a recorded human decision. In your application, wait
for that decision before calling `approve()`. Derive `ownerId` from backend
authentication, and pass your trusted services as the agent context.
The example's in-memory idempotency map is not a durable external-effect ledger.
Use `context.idempotencyKey` at the destination service to reconcile retries.

The file reference is synthetic. It demonstrates the typed source and position
API; it does not download or authorize a file. See [output references](output-references.md)
for provider coordinates, client metadata, and authenticated retrieval boundaries.

## Cancel or debug a run

Run `dart run examples/cancellation.dart` to cancel a provider after it starts.
Run `dart run examples/schema_diagnostics.dart` to inspect a rejected structured
value on the backend. The [Dart API recipes](dart-api.md) explain cancellation
and which error details can be exposed to a client.


# Source: docs/dx-review.md

# Independent Dart consumer review — round 2

Reviewed the current uncommitted worktree on 2026-11-04, using `docs/dart-api.md`, public imports and offline executable consumer probes. This is a snapshot, not a release or production-readiness certification. No runtime code was edited and no network or paid API call was made.

## Result: 7.7/10 (round 1: 6.7/10)

Each dimension has equal weight. A 5 requires substantial implementation reading or glue; an 8 is a documented, working application path with clear boundaries; a 10 requires independent adoption and broader failure testing. Scores represent the tested developer journey, not provider parity.

| Dimension | Score | Evidence |
| --- | ---: | --- |
| Discoverability | 7 | New Dart guide collects text, structured output, typed tools, approvals, testing and local endpoint in one place. Most recipes are fragments with application-defined names, and durable setup still requires the separate Serverpod example. |
| Clarity | 8 | `generateText`, `generateObject`, `AiAgent.generate`, `approve()` and typed context express common tasks directly. The approval example explicitly says a human must decide. The developer still assembles IDs, storage, service, session, identity and interruption UI. |
| Types | 8 | Typed tool input/output/context, decoded object and usage work in the consumer. Status and interrupts are accessible, but application JSON schema and decoder must be kept consistent manually. |
| Debugging | 7.5 | Malformed structured output now reports `INVALID_OUTPUT`, and executable probes identified `MODEL_FAILED`, `TOOL_FAILED` and `STEP_LIMIT` while retaining backend cause; partial text survived premature stream termination. Diagnose real storage and network failures separately. |
| Testing | 8 | `ScriptedChatModel` supports deterministic offline tests, checks received requests and fails clearly when exhausted. The example uses assertions, which are not a substitute for test-runner expectations in all execution modes. |

## Executed consumer checks

From repository root:

```sh
dart run examples/review_cases/consumer.dart
dart run examples/review_cases/failures.dart
```

Both exited 0. The first tested text plus usage, schema-validated `int`, typed tool with approval and trusted context, agent recreation with the same `MemoryRunStore`, subsequent history, a custom provider, and invalid structured output (`INVALID_OUTPUT`). The second checked a stream without a terminal event and exhausted fixture (`MODEL_FAILED`), a tool exception (`TOOL_FAILED`), and loop exhaustion (`STEP_LIMIT`). Causes were retained and premature stream failure retained partial text.

## Remaining developer friction and limits

1. **Durable approval recipe is not a runnable standalone setup.** It uses undefined `Session`, `messageService`, IDs and configured `model`. This is reasonable application pseudocode, but a first-time developer must still combine it with Serverpod setup, migrations, authentication and tool registration. The offline recreation probe shares an in-memory store within one process: it does not verify database persistence, restart recovery, or `atomicRunStore.complete` rollback/atomicity. Add a linked, runnable Serverpod consumer integration with process recreation and injected persistence failures.
2. **The local endpoint recipe is not a live compatibility test.** It usefully specifies the Chat Completions protocol and cautions that capability support varies. The custom provider probe is in-process only; it did not exercise HTTP, local inference, cancellation or model-specific options. A fixture-backed HTTP consumer example and separately documented real-server test would close this gap.
3. **Failure coverage remains selective.** The new codes and causes worked in probes above. They do not establish behavior for approval rejection or edited arguments, storage failure, cancellation, a decoder exception, concurrent runs, or a side effect that succeeds before persistence fails. Clarify and test those paths before increasing the debugging score. Tool failure cause includes private detail; the guide correctly says to keep causes on the backend.
4. **Examples are not uniformly copy-and-run.** The first guide snippet lacks a `main`; later snippets rely on definitions outside their code block. Link a small compilable complete sample and run it in CI. Use test framework expectations for the test recipe rather than relying exclusively on `assert`.
5. **Provider and SDK capability claims remain separate.** A custom `ChatModel` is straightforward, but scripted model success says nothing about real OpenAI-compatible implementations, tool protocol variants, media, caching or production performance.

No PostgreSQL, Serverpod restart, Flutter device, local model server, paid provider, network, crash recovery, or complete provider option parity was tested.


# Independent Dart consumer review — round 3

Reviewed main a4f4a93 on 2026-11-04. Score: **8.0/10** (round 2: 7.7). Equal weight; this reflects the exercised developer journey, not provider parity or production certification.

| Dimension | /10 | Evidence and remaining gap |
| --- | ---: | --- |
| Discoverability | 7.5 | Guide links runnable consumer samples and Serverpod example, but the PostgreSQL approval integration is buried in a test rather than linked as a setup recipe. |
| Clarity | 8 | Typed approval operations are clear; OpenAI integration lists realtime without prominently saying it exposes a connection rather than orchestrated voice and tools. The detailed limitation is in the separate options audit. |
| Types | 8 | Edited and rejected tool approvals worked. Provider-specific configure callbacks exist; generic options and cross-provider parity were outside this snapshot. |
| Debugging | 8 | Pre-cancellation and cooperative in-flight cancellation throw RunCancelled; prior round established error codes and partial text. Cancellation during a real HTTP request and storage faults remain untested. |
| Testing | 8.5 | A real loopback HTTP fixture, application approval cases, and the repository's PostgreSQL-backed approval integration passed offline. Real process restart and failure injection are not established by the integration. |

## Executed

From repository root:

```sh
dart run examples/review_cases/reliability.dart
cd examples/serverpod/agent_weave_demo_server
PATH="$(git rev-parse --show-toplevel)/.dart_tool/dart-3.12.2/dart-sdk/bin:$PATH" dart test test/integration/agent_test.dart --plain-name 'a recreated agent resumes a PostgreSQL-backed approval without repeating its tool'
```

The first example starts a local HTTP server implementing a minimal Chat Completions SSE response; checks the request route and model and resulting text; checks pre-cancellation and cooperative in-flight model cancellation; and checks rejection (no tool execution) and edited approval (one execution, edited output) using a shared MemoryRunStore. It is a fixture, not an actual local inference server. The PostgreSQL test recreates the agent and resumes a pending approval with the same database; it runs in one test process, not a restarted process. The exact executed test command was `cd examples/serverpod/agent_weave_demo_server` followed by `PATH="$(git rev-parse --show-toplevel)/.dart_tool/dart-3.12.2/dart-sdk/bin:$PATH" dart test test/integration/agent_test.dart --plain-name 'a recreated agent resumes a PostgreSQL-backed approval without repeating its tool'`.

## Highest priority friction

1. Publish and link a runnable persisted approval example: the Dart guide's Serverpod snippet depends on application-specific definitions; the working PostgreSQL integration is not discoverable from that recipe. Show setup and real human decision boundary, and distinguish process restart, storage faults, and external idempotency from agent recreation. The existing integration passed; it does not prove restart recovery.
2. State realtime scope beside its entry in the OpenAI guide: the public page lists the connection and says to close it, while the options audit explains it does not provide voice/tool orchestration and connection handshake cancellation is limited. Show a minimal lifecycle example and direct consumers to provider SDK events.
3. Document what cancellation guarantees: the cooperative fake stops when its token is signalled; this does not prove a provider's in-flight I/O aborts or undo an external effect. Add reproducible transport and storage-failure examples, including effects-before-checkpoint, rather than imply exactly-once behavior.
4. Switching Dart SDKs in the same workspace caused a sqlite3 build-hook kernel mismatch (expected 138, found 130) before tests ran. Re-running with the SDK that built the cache passed. This is observed environment/cache friction, not evidence of a package bug; a clean separate build cache or consistent SDK version is advisable.

No paid calls, external provider keys, real inference server, real HTTP in-flight cancellation, process restart, injected database failure, or live realtime session was exercised. Source implementation was not edited.

## Anthropic adapter follow-up: 7.8/10

Independent consumer snapshot of the new native adapter, reviewed separately from the main a4f4a93 score: discoverability 7, clarity 8, types 8, debugging 8, testing 8. Equal weighting. A minimal consumer still needs to find the underlying SDK client and understand its ownership; the application-facing API, typed tool and exception code are straightforward. Documentation and exports were being revised concurrently, so this is a point-in-time assessment.

```sh
PATH="$PWD/.dart_tool/dart-3.12.2/dart-sdk/bin:$PATH" dart run examples/review_cases/anthropic.dart
```

A local real HTTP fixture validated the native Messages path and authentication header, text generation, serialized structured-output schema and decoded object, a two-invocation agent tool loop, signed thinking replay and corresponding tool result. A simulated HTTP 400 surfaced as `AgentRunException` with `MODEL_FAILED` and an `ApiException(400)` cause containing the provider diagnostic. The fake endpoint does not validate actual Anthropic model compatibility, supported schemas or provider-side restrictions. No paid calls were made; no implementation bug was established by these probes.


# Round 4 consumer review

Score: **7/10** (discoverability 5, clarity 6, types 7, debugging 7, testing 8). The new native history loader removes a manual JSON conversion, and the typed approval hashes match across backend and client. Recovery still needs explicit client configuration and a complete consumer recipe.

## Tested offline

From the workspace root, run:

```sh
PATH="$PWD/.dart_tool/dart-3.12.2/dart-sdk/bin:$PATH" dart run .dart_tool/dx-review/round4/hydrate.dart
```

The probe creates a real approval interruption in MemoryRunStore with a scripted provider, serializes the actual `chatHydration` snapshot through JSON, passes it through the new `serverpodConnection(loadHistory: ...)` bridge and attaches a real TanStack ChatClient. It verifies by inspection that a tool with identical `RawJsonSchema` restores `kind=tool-approval`, while omitting the client tool restores `kind=generic` (still resolvable). The input/approval/response schema hashes matched. No provider calls or keys were used.

## Findings

1. The default `ChatClient` persistence is ephemeral. Even if `serverpodConnection` has a working history callback, `await chat.attach()` silently skips it unless configured with `persistence: const ChatPersistenceOptions.server()`. The original README connection recipe omitted both the callback and server persistence. A reader following it cannot restore approvals after an app restart.
2. To surface a typed tool approval, register a `ChatClientTool` with the same name, `needsApproval: true`, and an identical input schema wrapped in `RawJsonSchema`. Without it, the interrupt is silently downgraded to generic, with `canResolve=true`. Schema drift likewise matters because the client checks hashes. Explain both paths and show the actual Dart imports; a raw map is rejected by `ChatClientTool.inputSchema`.
3. Existing PostgreSQL approval integration recreates the backend agent but retains the prior in-memory `paused.interrupts`; it does not prove client restart/hydration/resolution. A consumer scenario that restores from authenticated Serverpod history and resumes via the generated client would close this gap.

## Limits

The probe uses the new uncommitted bridge and a memory store, not a running Serverpod database or generated-client WebSocket. It checks hydration and classification, not resumed execution, reconnect during an active stream, mobile UI, or schema drift behavior. The existing PostgreSQL integration source was inspected, but its full suite was not run here.

## Follow-up: runnable process restart journey

Targeted journey score: **8.5/10**. The new `example/approval_workflow.dart` supplies server persistence, the native `loadHistory` callback, matching client tool schema, and `attach()`. The CLI now rejects generic fallback by checking the interrupt kind and tool name as well as resolvability. This addresses the configuration and schema-binding gaps above. Documentation was being updated during this review, so its final discoverability was not assessed.

Independently passed with Dart 3.12.2: from `examples/serverpod/agent_weave_demo_server`, run `PATH="$PWD/../../../.dart_tool/dart-3.12.2/dart-sdk/bin:$PATH" dart test test/integration/restart_test.dart`. Output: `00:17 +1: All tests passed!` The test starts a fresh local Serverpod process and embedded PostgreSQL, starts the actual CLI in a fresh process, gracefully terminates and restarts the server using the same database files, approves from another fresh CLI process, and rejects a subsequent completed decision. No paid calls or keys were used.

This demonstrates the tested graceful restart and completed-decision replay scenario. It does not establish behavior after arbitrary crash timing, exactly-once external effects, or a mobile UI.


The round-four hydration behavior is now a checked-in regression suite:
`dart test packages/agent_weave_serverpod_client/test/history_test.dart`. It
covers real serialized interruptions with ephemeral/server persistence and
registered/unregistered tool schemas. The process-restart command above runs
the complete CLI directly, rather than a private review-only script.

## Round 5: document and OpenRouter consumers

Tested with pinned Dart 3.12.2, no API keys or paid calls. Scores reflect these specific journeys, not complete provider coverage.

| Journey | Discoverability | Clarity | Types | Debugging | Testing | Overall |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| Portable document inputs | 4/10 | 6/10 | 8/10 | 7/10 | 7/10 | 6.4/10 |
| OpenRouter text and routing | 7/10 | 8/10 | 8/10 | 6/10 | 7/10 | 7.2/10 |

Document constructors are straightforward once located, with typed variants and a scoped provider ID. At review time there was no complete public document recipe, so discovering construction, supported formats, provider-specific IDs, and storage implications required source reading. Anthropic file-ID and unsupported inline formats fail with useful messages; a non-OpenAI handle is rejected by Responses. The wire/history round trip preserves filename and content, but hydration contains the original base64 data and URLs. Explain that document contents and signed URLs can persist in server history and be returned to authorized history clients, and recommend appropriate retention/access controls. Actual persistence and restart depend on the configured store and were not tested.

`documents.dart` constructs URL, inline text and scoped file-ID documents, asserts native JSON and hydration/request round trips, verifies actual mock HTTP request bodies for OpenAI Responses and Anthropic, and checks invalid URL/base64/empty ID and explicit unsupported cases. Anthropic file-ID is unsupported by the pinned SDK. OpenAI Chat Completions and OpenRouter document inputs are unsupported by the current adapter. This probe uses in-process fixtures, not provider endpoints.

`openrouter_consumer.dart` follows the public README shape, uses a loopback HTTP endpoint, verifies the path, model, message, attribution header and routing preference, then receives streamed text through `generateText`. It demonstrates a practical setup without exposing a credential. The README clearly states that billing, provider identity, some OpenRouter features and live behavior are not verified. Troubleshooting remains less certain without a real service or an inline error consumer probe.

Reproduce the checked-in consumer cases:

```sh
dart --enable-asserts run examples/review_cases/documents.dart
dart --enable-asserts run examples/review_cases/openrouter.dart
```

### Follow-up after guides and canonical wire sources

The original scores above remain the first review. After reading `docs/documents.md` and `docs/openrouter.md` and re-running the examples, the document journey scores **8.0/10** (discoverability 8, clarity 8, types 8, debugging 8, testing 8). The guide now provides a runnable bytes example, URL/base64/file-ID alternatives, a provider matrix, and concrete history/privacy guidance. It still requires choosing a compatible provider/model and performing a paid call to verify actual acceptance; an offline fixture cannot establish file limits or durable restart.

The OpenRouter text/routing journey scores **7.8/10** (discoverability 8, clarity 8, types 8, debugging 7, testing 8). The new guide describes setup and limits. A new inline stream error consumer probe found that `generateText` wraps the underlying SDK failure as `AgentRunException`; the original guide implied direct propagation. The guide and package README now explain the distinction and trusted backend access to `cause`. Provider-specific metadata and live model behavior remain outside the tested contract.

The polished, reusable cases are `examples/review_cases/documents.dart` and `examples/review_cases/openrouter.dart`. Run with assertions enabled using the commands in the file headers. They pass on Dart 3.12.2 and strict `dart analyze` reports no issues. Document checks now assert canonical `source.value` for URL, inline bytes and scoped ID in hydration, and verify Anthropic PDF/base64 and text request serialization alongside Responses. The OpenRouter case verifies both the successful loopback and an inline error reaching the high-level exception's trusted backend `cause`. No actual provider calls, persistent store restart, billing, cancellation, or complete format support were tested.

## Round 6: native Together consumer

Initial score: 8/10. Updated offline developer experience score: 8/10.

| Criterion | Score | Reason |
| --- | --- | --- |
| Getting started and documentation | 8/10 | The guide shows client ownership, environment keys, a complete text example, and model-dependent limits. |
| Typed configuration | 8/10 | Named options and enums are discoverable; raw native JSON remains less discoverable and lacks static field checks. |
| Agent workflows | 8/10 | The loopback app exercised structured output, approval, tool execution and replay; model-dependent support remains unverified. |
| Errors and lifecycle | 8/10 | High-level errors retain safe-to-string provider causes and immutable diagnostics; cancellation was checked before sending, not during every network phase. |
| Streaming and output | 8/10 | Fragmented arguments, repeated call metadata, usage and length-limited partial text passed synthetic fixtures; real provider variants remain unverified. |

The initial review exposed dropped usage after a finish event; the fix passed the consumer test. The updated example also checks HTTP 429 status, request ID, nested immutable details and redacted exception string through `generateText`, as well as partial text and finish reason. It exercises the new enums through the public constructor.

Commands passed: `dart test packages/agent_weave_together/test/consumer_test.dart`; `dart --enable-asserts run examples/review_cases/together.dart`.

All checks used offline loopback responses with synthetic data. No paid calls, live Together model acceptance, billing, real network interruption, or exhaustive native fields were tested.

## Round 7: Gateway consumer review

Independent offline consumer exercise using Dart 3.12.2 with assertions and a real loopback HTTP server: `dart --enable-asserts run examples/review_cases/gateway.dart`. Synthetic fixtures model expected wire events; they do not establish actual Vercel Gateway API behavior, routing, or live compatibility.

Initial run: Responses structured output and approval continuation passed, including per-request rotating bearer and BYOK, routing options, provider options, credential-free stored history and serialized UI hydration. A separately generated request confirms wrong-provider Responses replay is excluded. Native JSON client preserved a response header and an unknown metadata field. Cancellation while awaiting a resolver prevented late dispatch.

Chat structured output and approval interrupt passed, but the approved continuation failed before HTTP dispatch with `AgentRunException(MODEL_FAILED)`, caused by `AssistantMessage.fromJson` during `ChatCompletionsProtocolModel.stream`. The test remains a runnable repro pending fix.

Scores (targeted experience, not SDK-wide acceptance): discoverability 5/10 (README lacks runnable usage and option examples), clarity 6/10 (simple constructor but credential and endpoint behavior need recipes), type safety 6/10 (typed routing, but BYOK and provider options are JSON maps), debugging 5/10 (generic run failure obscures continuation issue), testing 7/10 (real loopback is practical; provider service contract not verified). Overall 5.8/10.

Limits: no real Gateway, paid requests, deployed service, actual Flutter UI, concurrency/backpressure or complete provider surface. Header/metadata test covers native JSON response, not streamed model metadata. Hydration checks the serialized UI payload, not a running client UI.

### Retest after protocol fix

The same command now passes all four loopback checks, including the approved Chat tool continuation, credential-free stored history, and serialized pending UI hydration. `dart analyze examples/review_cases/gateway.dart` also reports no issues. The initial scores above remain the review record; the corrected continuation improves reliability, but the missing runnable package README and the unverified live Gateway contract still constrain the DX assessment. A revised targeted score is 6.4/10: discoverability 5, clarity 6, type safety 6, debugging 6, testing 9. The testing score reflects the consumer exercise and reproducibility, not production service coverage.

### Guide and diagnostic re-review

Both complete code blocks in `docs/vercel-gateway.md` were copied unchanged into fresh temporary Dart files and compiled with the workspace package configuration and Dart 3.12.2; neither was run because the examples use a live, potentially paid endpoint. The offline consumer journey was rerun successfully. It now additionally exercises `withApiKey`, enum-based cache/service-tier/sort configuration, forward-compatible extra options, and HTTP and stream errors with status/request ID and provider details. Known bearer and BYOK values were redacted in diagnostics while error codes remained available. These are synthetic loopback responses, not confirmation of the Gateway's production error shapes. The dynamic resolver journey rotates credentials between requests; the guide's environment-based example itself was compiled, not executed against a secret manager.

Revised targeted DX score: 7.6/10 — discoverability 8, clarity 8, type safety 7, debugging 7, testing 8. The complete runnable guide and typed routing materially improve setup and diagnosis; provider-specific configuration and BYOK still require JSON, and live provider behavior remains unverified. Earlier 5.8 and 6.4 assessments remain above as the initial and first-retest records.

## Round 8: Cloudflare consumer review


Offline loopback review, Dart 3.12.2, assertions enabled. No credentials, Cloudflare requests, license acceptance, or paid services were used.

| Criterion | First read | Current | Evidence and remaining friction |
| --- | ---: | ---: | --- |
| Getting started and ownership | 7/10 | 7/10 | Separate client and Gateway contracts and client ownership are explained; account/model availability still requires external verification. |
| Typed data and wire fidelity | 6/10 | 8/10 | Typed embedding and transcription results expose useful fields and raw responses; typed image bytes cover binary and decoded Flux JSON. Embedding vectors and image bytes reject mutation. |
| Agent and tool workflow | 7/10 | 7/10 | One native call pauses for approval and resumes with the documented replay; compatible chat and Responses replay a tool result in two requests. Native multiple calls are explicitly rejected. |
| Control and error handling | 7/10 | 7/10 | Loopback covers cancellation and deadline during token resolution, cancellation after send with pending headers and after a streamed event, request-scoped token rotation, and redaction on HTTP errors. |
| Documentation and discoverability | 6/10 | 8/10 | The expanded guide separates all four contracts, shows typed setup, states ownership and retry behavior, and qualifies model availability and live verification. It does not establish which models work in a particular account. |

Overall qualitative assessment: 7/10 initially, 8/10 now. These are reviewer judgments, not measured benchmarks; the typed-result and documentation improvements do not establish broader provider compatibility.

Run: `.dart_tool/dart-3.12.2/dart-sdk/bin/dart --enable-asserts run examples/review_cases/cloudflare.dart`. Also ran `dart analyze examples/review_cases/cloudflare.dart`; both passed. The loopback fixture checks native versus Gateway path, payload and headers; schema GET query; embedding shape and pooling; transcription bytes and JSON; image JSON and bytes; native approval, replay and multiple-call rejection before execution; compatible chat and Responses tool continuation; immutable embedding vectors and image bytes; credential rotation; error privacy; cancellation and timeout during token resolution; cancellation after send with pending headers; Gateway default and override headers across native, Gateway and compatible endpoints; and stream cancellation after headers and an event.

No defect was reproduced in those scenarios. Fixtures do not establish live Cloudflare behavior, model or account availability, license status, or all model schemas. Live service errors, actual Gateway billing and real inference were not checked in this independent example. Native traditional continuation is limited to the documented single-call replay; multiple-call continuation is not verified or claimed.

The first `docs/cloudflare.md` Dart block was extracted unchanged, verified identical to `examples/cloudflare_demo.dart`, analyzed, and compiled with Dart 3.12.2. It was not executed; no live or paid calls were made. The API inventory classifies operations rather than claiming parity.

## Round 9: native OpenRouter consumer


Offline loopback review with Dart 3.12.2 and assertions enabled; no real OpenRouter calls or credentials. Scores are qualitative judgments of this targeted workflow, not an SDK acceptance assessment.

| Criterion | Before | After | Evidence and limits |
| --- | ---: | ---: | --- |
| Discoverability | 6/10 | 8/10 | The guide identifies native client, Chat and Responses entry points and private metadata namespaces. |
| Clarity | 7/10 | 8/10 | The guide explains ownership, endpoints, private metadata, migration and limits; raw metadata still requires JSON inspection. |
| Types | 6/10 | 7/10 | Routing options and typed generation help; native requests and provider metadata remain JSON by design. |
| Diagnosis | 6/10 | 7/10 | A loopback 400 exposes status while redacting a fixture credential, but this is not a live error survey. |
| Testing | 6/10 | 8/10 | The independent network consumer covers the workflows below; it cannot prove upstream behavior. |

The original delegated adapter documented missing metadata and continuation. The new native path passes `dart --enable-asserts run examples/review_cases/openrouter_native.dart` and `dart analyze examples/review_cases/openrouter_native.dart`. The fixture exercises raw JSON provider and cost, Chat and Responses schema generation, two tool turns with persisted approvals and recreated agents, exact ordered replay of unknown and encrypted reasoning details, hydration privacy, unrelated provider state isolation, reported model/token/provider/cost preservation, absent usage remaining absent, rotating credentials and attribution headers, and HTTP error redaction. It also tests pre-cancellation, cancellation while headers are pending, unsubscribe after a flushed SSE event with a shared-parent sibling continuing, and borrowed HTTP client ownership. These are local fixtures, not evidence of actual billing, live model behavior, or provider compatibility. The native client did not expose a GET operation at initial review, so GET was not tested. Responses approval is independently exercised through a recreated agent and two loopback invocations: the continuation preserves ordered reasoning, opaque encrypted content, signature, unknown fields, assistant message and function call IDs and statuses, followed by the matching tool result. Cancellation through a real upstream, retries and all upstream unions remain unverified here.

The updated guide describes the tested scenarios and separates fixture evidence from live behavior. Its first complete Dart block was copied unchanged, compared byte-for-byte with `examples/openrouter_demo.dart`, analyzed, and compiled with Dart 3.12.2 without executing it. Other behaviors beyond the scenarios listed remain outside this independent fixture.

## Round 10: independent computer-tool consumer

Initial assessment before exercising it: discoverability 5/10 (new type and safety contract needed a guide); type ergonomics 7/10 (typed context and SDK actions, but protocol and replay details are not obvious); correctness confidence 4/10 (no independent run yet); testing 5/10 (provider fixtures existed, no consumer loopback evidence yet). These are qualitative judgments for this feature, not scores for the whole SDK.

After the loopback consumer: discoverability 6/10 pending review of the new guide; type ergonomics 8/10 because a typed app-owned executor, approval policy, and screenshot result are straightforward; debugging 7/10 because failures propagate but remote protocol details still need inspection; correctness confidence 7/10 for the exercised cases, not live computer use; testing 8/10 for a reproducible local consumer, with no real operating-system, browser, paid-model, or PostgreSQL claims.

Run `.dart_tool/dart-3.12.2/dart-sdk/bin/dart run examples/review_cases/computer.dart`. It uses a real loopback HTTP server and the pinned OpenAI client with a fake executor. It checks all nine action types as an ordered batch, a fresh screenshot, context and idempotency, no execution before terminal response or approval, recreated-agent continuation, call ID, reasoning replay and UI hydration, safety checks and legacy preview, benign automatic execution, rejection and rejected thread reuse, changed environment, invalid action, truncated response, malformed UTF-8, edited native arguments, pre-cancellation, and mismatched call kinds. A passing fixture does not establish real provider, OS, browser, cross-process persistence, or crash behavior.

Final guide and transport review: discoverability 8/10 (the complete sample, driver contract, policy choices, and continuation limits are now together); type safety 8/10 (typed executor and actions are useful, though consumers must inspect upstream action classes and serialize them to understand the full union); debugging 7/10 (local failures are observable but provider protocol failures still require investigation); testing 8/10 (a self-contained loopback exercises real HTTP without spending money); overall 7.8/10 for this feature, not the SDK as a whole. The full CLI guide block exactly matches `examples/computer_demo.dart`; both that sample and this consumer analyze cleanly. The sample was compiled to a native executable and analyzed, not run against a driver or provider. Final checks were rerun after the transport freeze.

Additional consumer cases send unknown top-level computer item data and verify it is in the private stored snapshot and replayed on continuation, but absent from UI hydration. Unknown action fields, click modifiers, and unknown drag point fields fail without executor invocation. This is limited to the specific malformed shapes tested; the fixture does not prove all future provider changes are safe. The legacy preview example in the consumer needed its environment updated from the old string to the current enum; the guide already uses the enum. Review commands use the pinned `.dart_tool/dart-3.12.2/dart-sdk/bin/dart`: `analyze examples/computer_demo.dart examples/review_cases/computer.dart` , `run examples/review_cases/computer.dart`, and `compile exe examples/computer_demo.dart -o /tmp/agentweave-computer-guide-review`.

## Round 11: Anthropic native consumer

## Before changes

Score: 7.8/10. Standard text, structured output, tool execution and signed thinking continuation are approachable. The typed SDK configuration is useful, but the SDK's union decoder and endpoint surface limit native protocol coverage and can discard fields not represented by its models. The HTTP error cause included the provider's response message, which can expose sensitive content. The current docs clearly state several limits.

`dart run examples/review_cases/anthropic.dart` passed against loopback HTTP: text, structured output, two-invocation tool loop, signed thinking replay, and HTTP 400 mapping. No provider request was made.

## Native API review

Score: 8.4/10. The native client is discoverable from the guide and makes raw and normalized access distinct. The JSON configuration callback is convenient for new fields, though it gives up compile-time option checking; unsupported blocks fail closed in normalized chat, with raw streaming available for custom handling. This is useful coverage, not full Anthropic parity.

Using the pinned Dart 3.12.2 SDK, `dart analyze examples/anthropic_demo.dart examples/review_cases/anthropic_native.dart` passed. The guide's first Dart block matches the demo byte-for-byte, and `dart compile exe examples/anthropic_demo.dart` passed. `dart run examples/review_cases/anthropic_native.dart` passed against loopback HTTP: text, JSON schema, approved tool call resumed by a recreated agent, signature and unknown fields on thinking replay, hidden hydration, request cache control and unknown options, final cumulative cache input and thinking-token usage, model, private metadata, citation replay and hydration privacy, key rotation, credential redaction in HTTP errors, raw create/count requests with query and header, pending-header and stream cancellation, sibling stream isolation, borrowed client ownership, malformed SSE rejection, and unknown block raw access with normalized failure.

The first run exposed two native client compile errors; implementation owner corrected them before the passing run. Provider error details are retained after credential scrubbing, so callers should treat error details as sensitive; other private response text is not generally redacted. The guide's executable demo was analyzed, not run, because it makes a billable request. No live provider, operating system, or browser behavior was tested. Unknown block types and deltas remain unsupported by the normalized agent loop. The fixture validates a selected cache-control request shape, not a provider cache hit or exhaustive native options.



## Round 12: Anthropic computer consumer review

Initial assessment: 3/10 for this specific path. The native Messages client and general tool approval pattern are discoverable from `anthropic_native.dart`, but no computer tool exists in the provider package at the start of this round. A consumer cannot safely represent toolset actions, execute them, or resume their results through this API yet. This is not an SDK-wide score.

Review environment: local loopback HTTP, `MemoryRunStore`, fixture credentials and app-owned fake executor. No provider calls, real desktop driver, or paid usage.

Initial integration run: the 17 documented members passed in consecutive batches of up to three; error batch halting, environment change, decline, unknown member/input/caller, disabled member, incomplete stream, invalid stop, cancellation, typed image result and ID matching also passed. An ordinary function mixed with a computer action ran before the computer approval and its result was serialized before the preceding computer call. Reported both to the implementation owner. The implementation was then changed to pause the entire mixed batch and sort the result blocks.

Final assessment: **7.8/10 for this Anthropic computer path**, not an SDK-wide grade. The typed action/result API and stable environment ID make the executor understandable and prevent accidental replay to a changed environment. Defaults require approval, and the private provider data is separated from the safe callback and hydration. A consumer still needs to implement and secure all real desktop operations, resize screenshots, choose a stable environment identity, and understand how a failed action halts the rest of a batch. Debugging is helped by typed actions and the loopback fixture, but there is no real driver or model evidence here.

Final run with Dart 3.12.2: `dart run examples/review_cases/anthropic_computer.dart` passed all 12 modes, including mixed function/computer approval and continuation ordering after the fix. `dart analyze examples/review_cases/anthropic_computer.dart` passed on the final fixture. These are fixture-backed observations only: no live Anthropic request, actual image capture, desktop effects, or persisted database restart was tested.

The official JavaScript client also passed a mixed three-interrupt scenario against an actual `AnthropicComputerTool` with a scripted model. Before approval both executors had zero effects; response schemas excluded native argument edits. After approval, the first computer error skipped the second computer call, the ordinary function was initially allowed to run, result IDs reached the model in order, and hydration excluded private replay and the environment binding. The full existing interop script passed all 17 cases. This does not exercise a real Anthropic model or native desktop.

The guide explains the HTTPS driver contract, approvals, idempotency, error behavior and security boundaries clearly. The standalone example analyzes cleanly. Its live network and console behavior remain untested. The 7.8/10 assessment stands: the entry point is usable and safer, while the application still owns substantial driver and operational work.

After the final API freeze, the guide's first Dart block matched the executable example byte-for-byte, and Dart 3.12.2 analysis passed for that example, the consumer fixture and interop server. All 12 consumer modes and all 17 JavaScript interop scenarios passed again. The guide now states the default approval policy accurately and documents typed coordinates and scroll directions.

A subsequent safety fix stops all later executors in the same mixed turn after a computer error. The final rerun passed all 13 consumer modes, including mixed error and no regular effect, and all 17 JavaScript interop scenarios, with one computer effect and zero ordinary effects. Analysis remained clean.

Final guide review: the mixed-turn failure wording now matches the verified halt behavior, and its Dart block still matches the executable example exactly. The scoped 7.8/10 assessment remains unchanged.

## Round 13: Local model and Dart Frog consumer review

Baseline: **0/10 runnable integration for each new path**. At the start of the review, the Ollama package and both review cases were absent; the Dart Frog package contained only its pubspec. No consumer integration could be compiled or run. These are path-specific baseline scores, not an SDK-wide assessment.

Review uses loopback HTTP and scripted fixtures only. No model downloads, external provider calls, or paid usage.

Dart Frog final provisional score: **8/10 for the tested adapter path**. The handler and trusted identity callback are straightforward; the consumer still owns authentication, durable storage, deployment, and disconnection behavior through intermediaries. The loopback fixture passed with Dart 3.12.2 and assertions enabled: HTTP method/auth/invalid payload handling, forged body owner isolation, approval and server-stored continuation, history, typed generation, event replay with offset and foreign-owner isolation, and client subscription disconnect stopping the model. This is local HTTP evidence only, not proof for reverse proxies, production authentication, persistent-store restart, or every official client interaction. The guide's example compiles; workspace analysis initially reported a missing direct `dart_frog` dependency for example imports, sent to the implementation owner.

Ollama provisional score: **7.8/10 for the exercised local-model path**, not an SDK-wide score. Native client construction, typed SDK options and embeddings, structured generation, and approval continuation are approachable. Replay state and provider metadata remain deliberately server-side; the application must know that URLs are not fetched for image input and supply inline data. The first compile exposed the missing `EmbeddingModel.embed` implementation while it was being developed; the owner fixed it before the final run. The embedding method name corrected the earlier announced API.

Dart 3.12.2 with assertions enabled passed loopback tests for schema output, typed temperature, approval with no execution before resume, thinking and unknown fields plus native ID/index replay, hidden thinking and provider ID in UI hydration, terminal duration and cached token usage, immutable vector results, HTTP and malformed NDJSON errors followed by successful stream, inline image bytes, pre-cancelled token with no HTTP request, stream unsubscription with a surviving sibling, and borrowed HTTP client reuse after client close. Analysis of both review scripts and the Dart Frog example passed with no issues. The test does not establish real Ollama/model behavior, model downloads, production deployment, in-flight cancellation-token timing, every error/status or provider endpoint, or live JavaScript interoperability for the Dart Frog handler.

Final guide and API check: the first Dart block in `docs/ollama.md` matches `examples/ollama_demo.dart` byte-for-byte and compiles unchanged to a Dart kernel artifact. The guide's SDK option and embedding signatures match the current API; no live server or model was used. After the Dart Frog generation decoder gained trusted application context, the loopback fixture was updated to derive an execution parameter from that context and passed again. Analysis of both review scripts and both demo examples reports no issues. Scores remain unchanged.

Additional official JavaScript integration: the pinned TanStack client passed text, schema and stored approval/resume over a real Dart Frog SSE handler backed by `OllamaNativeClient` and a local fake NDJSON server. The fake verified thinking, unknown field, original native call ID/index and tool name/result on continuation; counters confirmed no tool effect before approval and one afterward. Owner isolation, private data absent from history, authenticated typed generation and redacted generation failure also passed. Dart analysis is clean. This is a local protocol fixture, not a live model, durable restart or proxy test; scores remain unchanged.

## Round 13: provider option review


Scope: selected pinned provider inventories, adapters and offline tests; not a complete field-by-field audit. No external provider or paid calls. Score: 6/10 for the reviewed all-provider developer experience: useful typed options and replay examples, but the requested complete parity is explicitly unfinished; this review found and then verified a fix for a common Gateway override failure.

### Finding and fix verification

Before the fix, Cloudflare Gateway `@cf/` requests rejected a client-default gateway ID whenever a per-request options object contains only another header, such as cache TTL. `_run` validated `(gateway ?? client.gateway)` in `packages/agent_weave_cloudflare/lib/agent_weave_cloudflare.dart` near line 470, whereas `_send` merges the client and per-request header maps. The input is valid under the merge semantics documented in `docs/cloudflare.md`. Validation now follows the merged headers; per-request keys override client defaults, absent per-request keys inherit client defaults, and do not mutate either map.

Reproduction: `.dart_tool/dart-3.12.2/dart-sdk/bin/dart --enable-asserts run examples/review_cases/provider_options.dart`. Before the fix it failed immediately with `Invalid argument(s): @cf models require a gateway ID.` After the fix, the same command passed with Dart 3.12.2. The consumer checks request cache/default precedence, default immutability, cache/request ID response headers and Together query/header forwarding after the Cloudflare check. The original failure occurred only when the request omitted the inherited Gateway ID; explicitly repeating it already worked.

### Coverage boundaries

The provider coverage page is appropriately qualified as an incremental inventory. Anthropic hosted tools and pause-turn, OpenRouter management/hosted tools/media, Together native legacy calls and multiple choices in the adapter, Vercel model semantics, and Cloudflare model-specific/live behavior are explicit gaps rather than newly discovered defects. OpenRouter tests cover selected ordered reasoning replay, Together tests exercise headers/query and reasoning replay, and Anthropic documents its raw/typed replay limitations. Fixture evidence cannot prove live billing, acceptance, cache hits or complete nested field semantics. This review did not exercise every option, streaming branch, native tool, or provider.

Existing Together test `dart test packages/agent_weave_together/test/together_test.dart --name 'native options snapshot and numeric logprobs; tools, schema and replay'` passed with the pinned Dart SDK. It verifies query, custom header, options snapshots, tool calls, schema, and reasoning replay through a loopback server.

### Guide and integration verification

Extracted the first Dart block from each Ollama and Dart Frog guide and analyzed both without executing them: no issues found with Dart 3.12.2. The Ollama and Dart Frog offline consumer programs passed. `node tool/interop/dart-frog.mjs` passed all four official JavaScript client scenarios using the pinned Dart SDK and local fixture server. These checks are offline, not live provider evidence.

## Round 14: Anthropic hosted tools consumer review

Scope: independent Dart consumer over a local HTTP Messages fixture. No provider key, paid calls, downloads, or live provider were used. Run with `.dart_tool/dart-3.12.2/dart-sdk/bin/dart run examples/review_cases/anthropic_hosted.dart`.

Initial expectation: configure a validated provider-hosted search tool at the model, run an ordinary agent, let `pause_turn` continue within the normal step budget, and retain opaque hosted blocks for automatic replay without treating them as application tools. Ordinary approval and persistence should work across a recreated agent.

Result: eight cases pass: search pause and follow-up replay, mixed server and approved app tool across recreated agents, two pauses exhausting maxSteps with checkpoint and accumulated usage, rejection of a new user message followed by empty-message recovery, truncated stream, unknown stop reason, cancellation, rejection of a server tool not configured by the application, and an opted-in programmatic code-execution call that pauses for local-tool approval. A typed SDK `WebSearchTool` configures the search; `message_delta` container metadata survives both automatic continuation and recreated approval resume. The fixture asserts private search-result content and citation metadata survive replay and are absent from hydration; it does not establish public citation rendering. It verifies no extra HTTP calls or application execution in the error paths. `dart analyze examples/review_cases/anthropic_hosted.dart` reports no issues.

During development the first compile failed because the API had not landed. A repeated-pause fixture initially reused a server tool ID and was rejected as INVALID_OUTPUT; distinct IDs made the intended step-limit scenario valid. These were fixture/timing issues. Inspection also identified that a hosted server call could be accepted when another hosted tool was configured; the implementation was corrected and the consumer negative case now rejects it without another HTTP call.

Scoped DX score: **8/10**. Native configuration is concise, and the same ordinary agent and approval APIs work across pause and recreation. Typed SDK hosted definitions work, while programmatic callers still require knowledge of provider wire names and the consumer must understand that citations remain private backend metadata rather than rendered UI output. This score covers only the tested native loopback flow, not all hosted tool variants or provider parity.

Not tested: live Anthropic behavior, actual search results, live container lifecycle, other hosted tool families, backend restart with durable storage, client citation display, or production networking. Fixture agreement cannot establish those capabilities.

Final frozen-code rerun: all eight consumer cases pass and the consumer analyzes without issues. Copied the first Dart block of `docs/anthropic-hosted.md` byte-for-byte into `.dart_tool/dx-review/round14/guide.dart`, verified equality, analyzed it without issues and compiled it to kernel without running it or calling a provider. Inspected replay, tool ownership, container configuration and hosted caller validation; the unconfigured hosted call identified during review is now rejected. This inspection is scoped and is not a comprehensive security audit.

Additional Dart client review: `examples/review_cases/structured_continuation_client.dart` runs the pinned `tanstack_ai_dart` ChatClient against a local SSE server and scripted model. Across two runs, including a structured-output pause and `MESSAGES_SNAPSHOT`, it observes exactly two completed outputs with the expected data; a newly attached client hydrates the same two completed outputs. The script runs successfully and analyzes without issues. This is local protocol interop, not Flutter device or live provider evidence.

Final programmatic fixture correction: the earlier fixture omitted the container needed for a pending programmatic call. After the runtime enforced that requirement, the fixture was updated to return a container and assert its replay after approval. Both the direct `20260120` caller and configured `20260521` alias with the `20260120` wire caller pass, as do all other loopback cases. Analyzer reports no issues. The earlier pass did not verify the required programmatic container.

## Round 15: OpenAI hosted tools and cross-provider guards

# Round 15: OpenAI Responses hosted tools consumer review

**Scoped score: 8.2/10.** The native Dart API makes the common hosted definitions straightforward, and its raw constructor provides a clear escape hatch for fields the pinned SDK cannot represent. The split between typed and native configuration and the need to inspect private provider data for hosted metadata take some discovery. This score covers only the local scenarios below, not overall provider parity or production readiness.

`examples/review_cases/openai_hosted.dart` uses a real loopback HTTP/SSE server and no provider credentials or paid requests. Dart 3.12.2 analysis reported no issues, and the consumer passed all twelve cases:

- Typed web and file search plus native code interpreter and image generation definitions, including unknown request and nested tool fields on the actual HTTP body.
- Four hosted output items and an application function call, exact unknown-field replay across a persisted approval and recreated agent, and private metadata excluded from hydration. A generated 1x1 PNG data URL is accessible in the result.
- Automatic local execution only after completion, plus EOF, incomplete responses, terminal call mismatch, pre-cancellation, and cancellation after the server flushed a call event without execution. An unrelated owner cannot resume an approval.
- Wrong-provider replay ignored; configuration cannot replace instructions, output schema or registered hosted definitions, or inject an unregistered function.

The initial run exposed an unregistered function injection through native configuration. After the implementation fix, that same case passed before dispatch. The initial image-result assertion also failed while the feature was being implemented; it passes on the final rerun.

Limits: this review did not call OpenAI, render the image, test every nested provider option or hosted tool, validate search quality, or exercise a live code container. Loopback fixtures cannot establish production provider behavior. Tool-search/MCP and other native continuation workflows are not certified by this score.

Additional media consumer review: `examples/review_cases/output_media_client.dart` passed against a local SSE server using a real 1x1 PNG fixture. The native Dart client received text-image-text in order live and after server hydration; provider replay remained private and another owner could not load the checkpoint. A separate PostgreSQL recreation test checks the same ordering and privacy, plus provider replay in a subsequent recreated agent request; it analyzes clean and passed in the coordinated PostgreSQL suite after the follow-up fixture declared image input capability. Neither fixture renders pixels or calls a provider.


### Independent contract and ownership review

# Upstream image-generation tool patch review

Static review of sparse worktree `.dart_tool/upstream/openai-image-tool-options` against pinned OpenAI Responses declaration and [current official request reference](https://developers.openai.com/api/reference/resources/responses/methods/create). No tests run here to avoid colliding with the root agent's checks; no paid requests. Reviewed upstream `AGENTS.md` and `.agents/skills/create-pr/SKILL.md` via `git show` because sparse checkout omits that file.

## Findings

1. **P2 — mask representation enforces a stricter contract than the published schema.** `ImageReference.fromJson` (`packages/openai_dart/lib/src/models/images/image_edit_json_request.dart:27`) requires exactly one of `file_id` and `image_url`, and its constructor relies on an assert for that invariant. The Responses API and pinned TypeScript `Tool.ImageGeneration.InputImageMask` declare both keys independently optional; no exclusivity requirement is specified. New tests label empty and both-key objects invalid. Those cases are schema-permitted but not verified accepted by the live API, so this is a schema-parity risk rather than a claimed production failure. Either establish an authoritative stricter rule or use a dedicated mask model with independently optional fields and appropriate tests. Importantly, Dart asserts are disabled in production, so direct construction can bypass the assumed invariant regardless.

2. **P2 — unknown enum values are silently changed on a request round-trip.** `ImageModerationLevel.fromJson` and `ImageInputFidelity.fromJson` convert unrecognized strings to `.unknown`, which serializes literally as `unknown`. For example future `moderation: 'future'` is changed instead of preserved or rejected. The current API only documents auto/low and high/low; this is forward-compatibility risk rather than a supported-current-value failure. Consider rejecting unknown values for request models or preserving raw strings; add a decoding test for each. Avoid silently asserting unknown inputs are lossless.

3. **P3 — model option combination in the new fixture is not an official supported example.** It pairs `model: gpt-image-2.5-flare` with `input_fidelity: high`; current reference documents fidelity for `gpt-image-1.5` and `gpt-image-1-mini`, not 2.5. This offline serialization test doesn't call the provider, but `gpt-image-1.5` would make the example contract-coherent. Model-specific acceptance remains untested.

## What looks correct and release guidance

The patch updates factory and constructor, reads/writes the structured mask, string moderation and integer compression, adds action and fidelity, and updates equality/hash consistently. New tests exercise both normal mask variants, exact request/tool round-trips, omission/null, wrong wire types and identity. The change breaks caller source compatibility for three existing parameter types. `AGENTS.md` requires conventional breaking marker; create-pr skill requires `## Breaking Changes` with before/after migration examples and accurate `## Test Plan`. Include replacements for all three parameters and an official API reference. No other repo callsites using changed parameter names were found by `rg`.

The reference additionally specifies output compression 0–100 and partial images 0–3. Current patch preserves any integer; whether to validate locally should follow the package's existing boundary-validation policy rather than invent extra constraints. Existing enum fallback and shared ImageReference behavior predate this patch, but reuse makes them visible in this new API path.

## Re-review of revision

The revised patch resolves all three observations: `ImageGenerationMask` models two independent optional fields and tests empty/both-key cases, unknown moderation/fidelity values are rejected in decoding and encoding instead of rewritten, and the fixture uses `gpt-image-1.5`. No new actionable defect identified by static review. This is not an API acceptance or live execution check; no tests were rerun here.

## Cross-provider concrete finding

The shared Chat Completions configuration guard accepts extra unregistered function tools. `_preserveRequest` in `packages/agent_weave_openai/lib/src/chat_models.dart` only requires each canonical tool to appear once. A callback can add a new function with no corresponding runtime tool, so the provider may call a tool the runtime cannot execute. Reproduced using an actual OpenRouter `MockClient` and no registered tools with `.dart_tool/dx-review/round15/rogue_chat_tool.dart`; it printed `Reproduced: unregistered tool sent with no runtime tools`. Shared delegates affect OpenRouter, Vercel Gateway and Cloudflare compatible Chat adapters as well as OpenAI. The native APIs and Responses-specific hosted tool controls are separate.

Regression `packages/agent_weave_openai/test/chat_tool_ownership_test.dart` tests additions with zero and one registered tool (both fail before fix), preserves an unmodified registered tool and rejects removal (existing guard handles removal). Fix Chat tool ownership by requiring configured tool definitions to match canonical registered definitions, accounting for absent versus empty arrays. Do not globally disallow hosted Responses additions as that protocol has a separate hosted-tools contract. Remaining listed provider coverage gaps are not established as new defects by this review.

## Round 15 follow-up: shared codec and provider guards

Static review scope: changed core JSON helpers, provider replay/ownership guards, OpenAI Responses parser, media snapshots, and selected compatible provider wrappers; not a whole-codebase security audit. Scoped score 6/10: selected regressions verify real failures but broad provider parity and live behavior remain open.

The Chat ownership fix and conditional OpenAI-only Responses hosted-tool exception are verified by local mock HTTP wrapper tests. `test/compatible_responses_tool_ownership_test.dart` passes all three OpenRouter/Vercel/Cloudflare additions checks; `test/compatible_chat_tool_ownership_test.dart` adds native `int` versus `double` edge cases. Shared `jsonEquals` initially still used Dart scalar `==`: the pinned Dart VM considers `9007199254740993 == 9007199254740992.0` true, and all three compatible Chat wrapper tests confirmed this reaches HTTP. Fix must compare integral doubles with exact integer conversion and handle signed-int bounds, including `+2^63` saturation. As of the failing run, these three cases were red pending root's concurrent fix.

`packages/agent_weave_anthropic/test/tool_ownership_test.dart` reproduces the pre-fix integer-to-integer `canonicalJson` collision and now passes with the native guard fix; adding a wholly unregistered native tool is rejected. `packages/agent_weave_ollama/test/tool_ownership_test.dart` verifies a forged replay tool argument differing by one above 2^53 fails before HTTP. Together normalized Chat exposes no arbitrary configure callback and serializes runtime tool definitions after its typed options; no matching extra-tool injection found in the inspected path.

OpenAI hosted image option `output_compression` validation currently accepts any numeric value from 0 to 100, including fractional numbers; official Responses reference specifies integer. Reject fractional values and add an offline invalid-input test. This is provider validation, not evidence of a live service failure.

## Final fix verification

Root fixed mixed int/double comparisons using finite integral validation and exact `BigInt` comparison. Reran all five independently owned regression files with pinned Dart 3.12.2: **20/20 passed**, including all three compatible Chat nested-double cases and compatible Responses tool ownership. Root also tightened hosted image compression to `int`; independent assert-based check `image_compression_check.dart` confirmed 2.5 is rejected. Prior findings are resolved within this offline scope. No paid requests or exhaustive provider/security audit were performed.

Final guide review: the first Dart block in `docs/openai-hosted.md` byte-matches `examples/openai_hosted_demo.dart` (1,112 bytes). Dart analysis and kernel compilation both passed without running the billable example. Inspection of the current hosted API and guide found no actionable mismatch or unsafe instruction; the guide explicitly flags billing and server-side credentials. This is a source-level review, not a live provider test.


Final image-fixture correction: transport tests initially used a corrupt PNG.
A separate byte-level check found the invalid CRC and truncated chunk sequence.
The fixture is now a complete 1x1 RGBA PNG; the offline check verifies CRCs,
chunk completion and decompressed pixel data in all four consumer sources.
Client transport/order checks do not constitute image-rendering evidence.

## Round 16: native provider media and streaming

# Round 16 independent consumer review

Scope: offline loopback exercises; no provider credentials or paid requests.

Cloudflare native chat: **8/10 for tested text-streaming DX**. `dart run examples/review_cases/cloudflare_streaming.dart` passed. A chunk arrives before the server releases the rest; another request completes while it is held, and canceling the first does not prevent that sibling. The case also checks snapshotted options, request-owned option rejection, typed structured-output and tool fallback, explicit opt-out, malformed payload and premature EOF. `dart analyze examples/review_cases/cloudflare_streaming.dart` passed. Tool execution/replay is covered by the pre-existing `cloudflare.dart` consumer, not this new case. No live provider or network reliability claim.

OpenRouter generated images: **8/10 for the tested buffered Chat path**. `dart run examples/review_cases/openrouter_images.dart` and `dart analyze examples/review_cases/openrouter_images.dart` passed. Two images and their native fields survive in order through an approval pause and a recreated agent; public hydration and a different owner do not expose the private signatures. Options are snapshotted, and malformed JSON, missing choices, invalid image URL and audio output are rejected. The exact native images array is replayed. Typed configure preserves the runtime token limit and rejects changes to supplied instructions, schema, and tools before dispatch. Canceling a buffered request while headers are pending leaves a sibling using the same parent token able to complete and does not cancel the parent. No live provider was exercised.

Usage feedback: `OpenRouterChatOptions(modalities: [OpenRouterOutputModality.text, OpenRouterOutputModality.image], imageConfig: {...})` is discoverable and concise, and the normal `ImagePart` avoids provider-specific rendering. The guide should state near this example that requesting image output uses a buffered request, image support depends on the selected provider/model, Chat text precedes images, and audio output is rejected by the normalized agent. `imageConfig` is a native JSON escape hatch, so its accepted keys and values must come from provider documentation; no compile-time validation is implied. The consumer does not exercise a live model or cancellation after response headers. Adding a response format through configure when no runtime schema was supplied was accepted; the guard test covers replacing an existing runtime schema.


The independent contract review found and reproduced image replay metadata
replacing an assistant role; the replay decoder now permits only its owned
content/refusal/image keys. It also found missing request IDs on buffered error
envelopes. Both regressions are retained in the package suite. The selected
Chat image contract is completed messages, not assumed streaming fragments.


Final guide review: the first Dart block in `docs/openrouter-images.md` byte-matches `examples/openrouter_images_demo.dart`. The demo and both consumer files analyze cleanly, and the demo compiles to a Dart kernel without executing a billable request. The guide matches the inspected API and explains the buffered boundary, model support, ordering, privacy and `result.images` scope. The consumer verifies that `result.images` includes the interrupted tool step's two images and excludes those images from the resumed run. Both independent loopback consumers passed again after the guide/API changes. No paid call, image rendering, or live provider verification was performed.

## Round 17: exact persisted approval contracts

# Round 17 independent approval contract review

**9/10 for the tested approval path.** After the fix, `dart run examples/review_cases/approval_contract.dart` passes and Dart analysis reports no issues. Before the fix, the same loopback-free consumer demonstrated six failures: colliding large-integer input and output schemas, a native definition, client-to-server executor change, a batch with a changed second tool, and a legacy checkpoint without a contract all allowed execution. Those cases now fail closed before side effects. Equivalent schemas with reordered keys resume; a rejected changed contract can retry with the original; a different owner cannot resume; and legacy rejection retains history.

The consumer confirms public `run()` error events for both changed and legacy contracts say “Start a new conversation.” It also checks that hydration and public events do not expose `toolContract`. The public `schemaHash` still collides for the tested adjacent integers, as required for JS interoperability, while private contract comparisons distinguish them. No provider, network, database, or paid calls were used.

Future-only consumers can now use `AgentRunException.message` to present the same safe changed-contract recovery instruction as the stream; `toString()` includes it. The independent consumer also confirms a provider exception's private marker is absent from both public message and `toString()` while remaining in the explicitly private cause. Legacy approvals need a new conversation, not automatic migration. The consumer tests native definition changes, but not each native sequential policy variant; broader database persistence and external client behavior were not checked here.

Final round 17 verification also passes the malformed native-continuation checkpoint regression: a decode failure preserves the snapshot, does not invoke the model, and releases the reservation. The independent reviewer reran the consumer and regression; the scoped score remains 9/10.

## Round 18: typed citations

# Round 18 independent citation consumer

**8/10 for the tested native Anthropic citation path.** `dart run examples/review_cases/anthropic_citations.dart` passes and Dart analysis reports no issues. The loopback fixture covers five pinned native citation variants, a split text block containing an emoji and a citation before its final text, UTF-16 answer offsets, two directly enabled documents, typed persisted citations and JSON roundtrip. The five live CUSTOM payloads match reconnect hydration metadata exactly. A recreated agent resumes a tool approval with native citation replay, preserving opaque fields but removing response-only file IDs. Public events and hydration exclude those fields and another owner cannot see the history.

Structured output with citations, disabled citations through native configure, and attempted in-place document-source replacement fail before dispatch. Valid native context/cache decorations survive. Unsafe credential-bearing URLs, unknown citation types, and early EOF fail without a citation event. No live provider, paid request, UI rendering, cancellation, typed SDK configuration, or persistent database was tested. The result is not evidence of those paths or model availability.

DX: `chatModel(citations: true)` and typed `ChatMessage.citations` are straightforward; a developer rendering live output must separately handle `agent_weave:citation` CUSTOM events and reconnect metadata. Document the distinction between the answer's UTF-16 span and source coordinates, the citations/structured-output restriction, the all-document setting, and that generic clients may ignore CUSTOM events. Only the tested source URL guard and provider projection are covered by this consumer; no broad public-data security guarantee is implied.

Guide review: the first Dart code block of `docs/citations.md` byte-matches `examples/anthropic_citations_demo.dart`. The demo and independent consumer analyze cleanly; the demo compiles to kernel without running the billable example. The loopback consumer passed again. The guide addresses the observed CUSTOM/hydration integration requirement, answer/source coordinate distinction, privacy, configuration restrictions and partial-run status. No additional concrete DX problem was found in this review. The score remains 8/10 for the independently checked native path; this review did not itself rerun JS or PostgreSQL tests.

Final capability verification: with `citations: true`, the native model advertises `structuredOutput: false`; constructing an output-schema agent throws the expected public `ArgumentError` without HTTP. A direct model request containing an enabled document and output schema also throws `ArgumentError` before HTTP. The updated consumer and analyzer pass. The scoped native-path score remains 8/10.

After adding `citationIndex`, the independent native consumer passes with explicit indexes 0 through 4 matching citation order and analyzes cleanly. The guide directs renderers to upsert by message ID and index, preserving equal distinct citations during replay. The scoped score remains 8/10. This consumer did not independently run an end-to-end JS rejoin.

## Round 19: upstream SDK file identifiers

# Round 19: upstream Anthropic SDK citation file IDs

**9/10 for the tested local SDK flow.** With Dart 3.13.3 and the upstream worktree package config, `anthropic_citation_consumer.dart` passes using a loopback HTTP server. The application calls `client.messages.create`, obtains typed character/page/block citation file IDs, JSON-serializes and reloads the message, and verifies equality and hash-map lookup. `copyWith()` retains IDs, explicit null clears each variant, cleared IDs are absent from JSON, and citation diagnostics redact IDs. The app replays the stored response through `toInputMessage()` in a second real SDK HTTP request: all citations remain, while response-only `file_id` fields are omitted. A real `messages.createStream` feeds `MessageStreamAccumulator`; accumulated citations retain IDs and also convert to input without them.

The same consumer fails to compile against AgentWeave's currently pinned anthropic_sdk_dart 9.0.1 because the three typed getters and `copyWith(fileId:)` do not exist. This is a local upstream worktree review; the patch is not evidence of a published package or an updated AgentWeave pin. No live provider, paid call, or production data was used. The consumer does not test every provider citation variant, retry/cancellation, or full SDK compatibility suite.

The patch is submitted as [upstream PR #441](https://github.com/davidmigloz/ai_clients_dart/pull/441). AgentWeave remains pinned to SDK 9.0.1; its raw native path preserves these fields independently.

## Round 20: OpenAI references

# Round 20 independent OpenAI Responses references review

**8/10 for the tested native Responses flow.** `dart run examples/review_cases/openai_references.dart` passes and Dart analysis reports no issues. The offline SDK loopback consumer covers all four pinned annotation forms: URL, a container file with 0/0 native range, two identical file insertion citations, and a file-list ordinal 99 without a fabricated filename. Multiple output-text parts include emoji, an annotated empty part and a later part; the expected UTF-16 enclosing spans survive alongside a generated PNG. It does not interpret provider-native positions as Dart string offsets.

Public references arrive with stable indexes and exactly match reconnect hydration, preserve duplicates, and round-trip through typed messages. The consumer uses a scoped file source to construct a `DocumentPart`, checks wrong-owner history and approval attempts, and recreates the agent after a tool approval to verify exact native message replay while private opaque fields do not enter public events or hydration. Conflicting streamed/terminal annotations, an unsafe credential-bearing URL, early EOF, and cancellation before terminal fail without a public reference or tool execution.

DX: the typed source/position variants make the file-list versus insertion distinction clear, and `partStart`/`partEnd` offer usable enclosing context without pretending native indexes are UTF-16. Applications must still implement authenticated, owner-scoped file retrieval and render the custom events or hydrated metadata; raw file IDs are deliberately public scoped handles, not download URLs. The fixture does not establish OpenAI's undocumented native Unicode offset semantics, live model behavior, Flutter rendering, actual file download, durable database behavior, or Chat Completions behavior. No paid calls were made.

**8/10 for the independently tested buffered Chat path.** `dart run examples/review_cases/openai_chat_references.dart` passes and Dart analysis is clean. A real SDK loopback request with `streamText: false` forwards typed `web_search_options`, normalizes a nested URL reference with an emoji-containing enclosing text span and opaque native positions, and presents matching live-event and hydration metadata. A malicious nested file discriminator remains a URL rather than creating a file source. Full raw response metadata stays private through approval and recreation; response-only annotations are not sent in the next Chat input. Schema configuration and protected runtime messages are checked, malformed URLs release no tool call or reference, and the default streaming path allows empty annotations but explicitly rejects nonempty ones.

For applications that need citations, choosing buffered Chat sacrifices token-by-token delivery; the typed flag and explicit error make the boundary discoverable, but callers must deliberately render reference metadata. This review did not establish native Unicode index semantics or test a live model, rendering, file resolution, durable storage or streamed annotation support.

Final guide review: the first Dart block of `docs/output-references.md` byte-matches `examples/openai_references_demo.dart`. The demo and both independent consumer files analyze cleanly; the demo compiles to a kernel without making a billable request, and both loopback consumers pass again. The guide clearly distinguishes enclosing UTF-16 context from unspecified provider coordinates, covers 0/0, buffered Chat, replay, metadata and authenticated file resolution. No additional concrete DX issue was found. The independently scoped scores remain 8/10 for each native path; this review did not independently rerun JS or PostgreSQL.

## Round 21: backend diagnostics and offline onboarding

# Independent Dart consumer review

Scope: offline public API consumer journeys for a small support app. Overall: **8/10** for the journeys exercised, not the SDK or provider support as a whole. The Future APIs, typed tool and scripted model felt idiomatic; approvals and references require more concepts and assembly than ordinary chat. No production source was needed: README, docs/dart-api.md, docs/tools.md, docs/output-references.md and the linked review examples were sufficient. I consulted test/example snippets for the cancellation and synthetic reference constructor, not internal implementation.

Run from the workspace root:

```sh
.dart_tool/dart-3.12.2/dart-sdk/bin/dart analyze examples/review_cases/support_app.dart
.dart_tool/dart-3.12.2/dart-sdk/bin/dart run examples/review_cases/support_app.dart
```

Both passed. Cases: text and reported usage; typed support escalation that pauses without a side effect, then executes once after approval in a recreated agent using a shared MemoryRunStore; structured decoding and schema failure; pre-cancellation; and a synthetic file reference retained with its text context. The model fixture checks sent messages and tool history. There were no failures before workarounds and no confirmed functional defect in these cases.

Friction and recommendations:

- The invalid output's safe message was `Invalid input or provider output.` and its backend cause was `FormatException: Value does not match the declared JSON Schema.` This identifies the failure class but gives no field path or expected type for troubleshooting a larger schema. Consider providing safe, structured schema diagnostics to backend developers while retaining sanitized client messages.
- The main Dart API failure example catches cancellation but does not show how to initiate it; the working pre-cancel example was found in examples/review_cases/reliability.dart. Add a concise `CancellationToken` example, including an in-flight example and the cooperative nature of cancellation.
- The reference guide's primary runnable example requires a live billable provider, while synthetic construction is demonstrated separately in citations_client.dart. Link an explicitly offline reference example from that guide so a newcomer can validate rendering without credentials. Synthetic events exercise runtime preservation, not provider annotation parsing.
- Approval code is understandable, but an application must supply input and output schemas, codec callbacks, context, IDs and store. A compact complete offline support example alongside the Serverpod recipe would make the required shared store and recreate/resume lifecycle clearer. MemoryRunStore recreation here is within one process; it does not demonstrate persistence across process restarts.

Not checked: real providers, networking, a database or Serverpod restart, UI rendering, actual file retrieval, in-flight cancellation and production permissions/idempotency. No secrets or paid requests used.

## Diagnostics re-review (initial implementation)

Run `dart run examples/review_cases/schema_diagnostics.dart` with the pinned SDK. Analyzer passes; the script currently exits nonzero deliberately because edited approval diagnostic lacks the nested field/type. Structured output, tool input and tool output each produced backend issues with `/customer/priority`, a schema path and an expected integer. Default exception string/source and public error did not expose the test input marker. A separate schema-only private enum marker was absent from public streamed events and hydrated history. The initial edited-approval error instead had only an empty instance path, `/oneOf`, and `#/oneOf: violated No element`; it did not explain the bad field or expected type. Its rejected edited input was absent from hydration. Initial privacy-case compilation failed because `outputSchema` is not an `AiAgent.run` parameter; switched to testing a typed tool input schema via the documented API.

After the resume-validation fix, both `support.dart` and `diagnostics.dart` pass with the pinned Dart SDK, and `dart analyze examples/review_cases/schema_diagnostics.dart` reports no issues. All four diagnostic cases now report `/customer/priority` and the expected integer. The issues list rejected mutation. The private schema-only enum marker stayed out of the default exception string, public error, streamed events and hydrated history. This checks those specific outputs, not every serialization path. The original failed provider text is application content and can remain in history; do not interpret this privacy check as removing it.

## Final round 21 consumer re-review

**8.5/10**, scoped to the offline journeys executed (baseline 8/10). The new field-level backend errors and discoverable offline recipes resolve the largest observed friction. Approval still involves several IDs, schemas and callbacks, and provider behavior and durable deployment are outside this score.

In addition to the two consumer scripts above, all four sample invocations ran successfully with `.dart_tool/dart-3.12.2/dart-sdk/bin/dart run`: `examples/offline_support.dart` (pause, zero effects), `examples/offline_support.dart --approve` (completion, one effect and synthetic file reference), `examples/cancellation.dart` (in-flight cancellation and asserted cancelled checkpoint), and `examples/schema_diagnostics.dart` (sanitized error and backend `/priority` detail). The offline guide accurately describes the outputs and its complete source block matches the checked-in example. README, Dart recipes, output references and the website getting-started page now lead to the relevant examples. The guide correctly distinguishes shared in-process memory from durable restart, and the diagnostics guide warns that issue details can contain private input/schema values and that original conversation content remains visible.

Prior failure and correction: initially edited arguments yielded only a root `/oneOf` diagnostic, without the bad field or expected type. After the resume validation fix, the same consumer case passes with `/customer/priority` and `integer`. The first attempt to test streaming schema privacy passed `outputSchema` to `run`, which is not an accepted public argument; the final test uses a typed tool input schema and passes. No other defect was observed in these cases.

Not independently checked: live providers, PostgreSQL/Serverpod restart, real file downloads, client-side `$ref` approval behavior, JS or Flutter rendering, or paid billing. The reported reference and model events are synthetic; cancellation covers a cooperative offline provider. No full suite or external calls were run.

Root verification: both consumer scripts are now checked in and wired into `tool/check.dart`. Formatting the copied scripts exposed a flow-control braces lint that the ignored `.dart_tool` review folder did not enable; adding braces corrected it without changing behavior. The tracked scripts run successfully and pass fatal-infos analysis.

## Round 22: edited approvals through both real clients

### Independent local-reference consumer review

**8.5/10 for the exercised offline approval journeys.** A tool with a local `$defs`/`$ref` input schema bound as a typed approval in both the workspace-pinned Dart client and official JS client 1.0.1. Valid edited arguments resumed successfully; invalid edited arguments reached the backend, were rejected safely, and produced no effect. This does not establish that every local-reference schema or every validator/client combination works.

Reproduce the checked-in regression cases from the workspace root with Dart
3.12.2 or later on PATH and the interop dependencies installed:

```sh
dart test packages/agent_weave_serverpod_client/test/interop_test.dart
node tool/interop/test.mjs
```

The initial independent probes ran from ignored local review artifacts. They
are not shipped in a fresh clone; the commands above exercise the integrated
regressions. Both use offline fixtures. The JavaScript harness starts its local
Dart HTTP server and requires the dependencies in `tool/interop/node_modules`.

Each case uses an object input with `priority` referring to `#/$defs/priority`, registered with matching client tool schema. The model proposes a valid call. Both clients surface a resolvable typed approval before any effect. Editing to integer 2 leads to exactly one effect, completed `Escalated` text, and the model's second scripted step consumed. Editing to `urgent` produces no effect, does not consume the next model step, and reports sanitized `INVALID_INPUT` (Dart's public message: `Invalid input or provider output.`). The Dart probe confirms the invalid edit was sent in a second request. JS receives the backend error; its invalid interrupt remains in error status.

The earlier validator-only observation concerned validating the embedded public approval union using the pinned Dart `json_schema` package. The application probes do not use that reconstructed schema and do not reproduce a failure through either real client for this raw schema: they show the real approval flow succeeds. They do not disprove the narrower validator-only limitation. The clients' raw-schema validation behavior and the backend validation are distinct, so client-side prevention of the invalid edit is not established here.

Development friction and corrections: first I accidentally read the separately installed pub.dev Dart client rather than the repository's pinned git client; its `error` property was unavailable in the pinned version (`legacyError` is used here), and compilation identified the mismatch. My first JS attempt incorrectly used Dart's payload shape `resolveInterrupt({approved: true, editedArgs: ...})`, resulting in an interrupt error and no effects. The official JS approval API is `resolveInterrupt(true, {editedArgs: ...})`; with that correction the valid case passes. This was my API misuse, not evidence of a local-reference defect. The differing Dart and JS calling conventions merit a side-by-side edited-approval example.

Not checked: PostgreSQL or process-restart persistence, schema variants beyond the one local ref, actual provider calls, UI rendering, network failures or concurrency. No paid calls, production changes, or full suite were run.

Regression integration: the probes were reduced into the existing client
harnesses. Run `dart test packages/agent_weave_serverpod_client/test/interop_test.dart`
and `node tool/interop/test.mjs` with Dart 3.12.2 on PATH. Six Dart tests and
23 reported JavaScript scenarios pass. The local-reference cases verify typed
binding, pause before effects, valid edited completion, invalid edited rejection
and effect counts; Dart also checks schema and approval hashes. These harnesses
avoid adding another standalone test server. Retry after an invalid submitted
resume is outside this round's coverage. The tools guide now shows the differing
Dart and JavaScript edited-approval calls side by side.

## Round 23: provider-owned MCP approvals

The independent developer initially scored this journey **2/10**: configuration
was rejected and an incoming approval failed without an interrupt. After
implementation, the same offline journey scores **7.5/10**. This is a scoped
MCP review, not a package-wide acceptance score or live provider certification.

Reproduce the tracked consumer from the workspace root:

```sh
dart analyze examples/review_cases/openai_mcp.dart
dart run examples/review_cases/openai_mcp.dart
dart test packages/agent_weave_serverpod_client/test/interop_test.dart
node tool/interop/test.mjs
```

The consumer uses a synthetic Responses SSE server with two labels and two
requests in one output. It approves one and rejects the other through a
recreated agent sharing the same MemoryRunStore. Changing the server URL fails
before another provider request. Outgoing input includes ordered native
`mcp_approval_response` items with the expected IDs and decisions, with no local
function result. A credential callback refreshes on each invocation; private
native IDs and credentials stay out of hydration. Another owner cannot load
the conversation, and pre-cancellation sends no request.

Both clients expose MCP decisions as resolvable **generic interrupts**. They use
`resolveInterrupt({'approved': true})` in Dart and
`resolveInterrupt({approved: true})` in JavaScript. Typed local-tool JS approval
has a different signature. The guide now explains that distinction. Eight
focused Dart client tests and 25 standalone official JavaScript scenarios pass,
including MCP approval and denial. The first local JS probe deadlocked when its
provider and client shared a serial request listener; a concurrent listener
corrected that fixture before integration into the existing harness.

The architecture review caught three additional defects: an approval echo could
be replayed twice on a later turn, a Chat adapter could reinterpret MCP history
as a local function call, and another server's configuration could change while
an approval was pending. The final adapter has regressions for echo suppression,
foreign-provider rejection before transport and binding the whole ordered MCP
and hosted-tool configuration.

The first code block in the MCP guide byte-matches the live CLI example. That
example compiles without execution; the offline consumer also analyzes and runs.
Cancellation wording distinguishes a pending decision from an uncertain request
after dispatch. The independent reviewer did not run PostgreSQL, in-flight MCP
cancellation, step limits, live OAuth/MCP, mobile rendering or real remote
execution. The main verification suite separately exercises durable storage and
synthetic failure boundaries. The score remains 7.5/10 for the reviewed scope.

## Round 24: restored provider approvals and typed client access

The independent developer initially scored the restored MCP flow **8/10**. Both
pinned clients could dispose, recreate, attach to server-owned history, approve
one request with a reason and reject a second request with another reason.
Provider/server display metadata survived restoration. The fixture received
three requests with the expected native IDs and one copy of each prior decision
in stateless replay. Another owner could not read the conversation, and hydrated
history excluded the provider IDs and private replay marker.

The observed friction was reading `metadata.providerApproval` and building the
generic response map. After adding the optional companion's `.providerApproval`
reader and typed actions, the same real Dart client journey scores **8.5/10**.
The helper exposes provider/server/tool identity and immutable arguments. It
does not add a TanStack dependency to the core runtime or change the wire format.

Run the tracked regressions from the workspace root:

```sh
dart test packages/agent_weave_serverpod_client/test
node tool/interop/test.mjs
```

The focused client package suite passes 34 tests, including nine client interop
tests and six new helper tests. The standalone JavaScript suite passes 26
reported scenarios. The initial independent probes are ignored local review
artifacts; these tracked commands reproduce the integrated journeys.

Awaiting a helper decision stages it, matching the pinned client's synchronous
resolution callback. It does not wait for stream completion or surface later
provider failures; applications observe `chat.states`. The tests separately
exercise callback error propagation, unresolvable snapshots, malformed declared
metadata and immutable nested JSON. The independent reviewer verified this
staging boundary and reran the typed loopback consumer.

These are scoped offline scores, not package-wide acceptance. No live provider,
actual remote effect, backend process restart, PostgreSQL or mobile UI was tested
by this consumer review. The native request fixture checks serialization and
request counts; it cannot establish live exactly-once remote execution.

## Round 25: Anthropic MCP baseline and interim guard

Historical review: round 27 below replaces this interim boundary with owned MCP integration.

The independent native Anthropic consumer scored the attempted MCP journey
**1.5/10**. Unlike OpenAI's approval path, the documented connector uses
provider-executed `mcp_tool_use` and `mcp_tool_result` blocks. Modern toolset
injection was rejected, but legacy `mcp_servers` could reach transport before
the unsupported returned block failed normalization. Repeating an explicit run
sent another request to the simulated provider. Effects were synthetic and live
acceptance of the legacy beta configuration was not verified.

The interim fix rejects that unsupported configuration before dispatch while
leaving explicit raw APIs available. Native Anthropic MCP functionality remains
unimplemented; passing a safety regression is not a functional score increase.
Run `dart test packages/agent_weave_anthropic/test/mcp_guard_test.dart` to
reproduce the tracked boundary checks. Full integration remains in scope.

## Round 26: bind provider configuration before local effects

The independent consumer reproduced a local approval alongside configured
OpenAI MCP, without a provider approval. Changing the server, allowlist,
credential binding, model or hosted tools still executed the approved local
tool before making the next provider request. This used simulated provider
transport and a real local tool executor, not a live MCP server.

After the fix, changed declared profiles reject before the local executor or
resumed transport. The consumer also verified provider authority changes,
no-MCP to MCP replacement, unchanged credential rotation, and a scripted
step-limit continuation. A public SDK `MockClient` case checks frozen nested
options, caller mutation, original-options retry and construction-time rejection
of dynamic callbacks with managed tools. Its final rerun also verifies frozen
function options on the HTTP fixture wire, changed-option rejection before
effects and retry with the original options. The scoped score is **8/10**; it is
not comparable to a package-wide acceptance score.

The new setup is explicit: provide `authorityBindingId`, declare managed tools,
and use immutable options and tool choice. The application must keep the
binding consistent with its real provider account and endpoint. Ordinary
callbacks can still fail on the next invocation after an approved local tool
has run; arbitrary unbound adapters are outside the profile guarantee.

The consumer did not run PostgreSQL, native OpenAI pauses or live providers.
The coordinating suite separately recreates agents over PostgreSQL and checks
profile drift, retained pending history and credential rotation. The tracked
`model_continuation_test.dart` files and OpenAI `model_profile_test.dart` make
these regressions reproducible through `dart run tool/check.dart`.

## Round 27: native Anthropic MCP

The independent developer wrote and ran public-API consumers for multiple
servers, mixed/deferred calls, local approval, changed configuration, token
refresh, all three beta modes, listing replay, native and SDK-backed HTTP
fixtures, 503 one-send behavior and cancellation boundaries. The scoped score
was **7.5/10**, rising to **8/10** after checking the runnable guide and
credential-resolution cancellation. These are scoped offline scores.

It found a legacy no-tools cast failure and a synthetic credential echo in
message-delta checkpoint metadata. Both were fixed and the original probes now
pass. A separate schema review found incomplete MCP at terminal stop reasons
and scalar/list/null native input; those received regressions. Declared request,
function, container and document/system caching options preserve the previous
callback workflows for managed models.

Run `dart --enable-asserts run examples/review_cases/anthropic_mcp.dart` for the
tracked independent application. It verifies two server/toolsets, deferred MCP
with a local approval, pre-effect profile rejection, unchanged-token-authority
refresh, exact private replay and hydration/journal boundaries. Mocked HTTP
responses do not execute a real remote tool or establish provider availability.
PostgreSQL verification is separate from the developer's review.

A later independent probe reproduced cancellation stalling during an unresolved
OAuth Future in both MCP adapters. The shared cancellation-aware wait now
finishes without provider dispatch or an indeterminate marker, permits an
in-memory reservation to be reacquired before the resolver finishes, and
consumes late resolver errors. It does not cancel the underlying OAuth work.
The guide's live example compiled without execution and matches its code block.

## Round 28: dedicated OpenRouter images

An independent developer wrote and ran public-API consumer scripts for image
model/endpoint discovery, all native request parameters, PNG/SVG/missing MIME,
usage/cost preservation, direct and wrapped SSE, multiple completed outputs,
unknown phases/capabilities, same-request JSON fallback, malformed/partial-only
streams, errors and cancellation at preparation, headers and body boundaries.
The scoped score is **8/10**, not an overall SDK or live-provider score.

The consumer reproduced a late response-body leak after cancellation while
waiting for headers. The shared transport now cancels that body. Its probe also
checks safe malformed-fallback status and redacted request ID. The reviewer
checked the runnable guide and compiled live demo without calling the provider.
Run the tracked recipe with
`dart --enable-asserts run examples/review_cases/openrouter_image_api.dart`.
Ignored adversarial review scripts are additional local evidence, not artifacts
available in a fresh clone; focused package tests preserve the regressions.

Remaining friction includes model-specific parameter acceptance, native error
events requiring explicit handling, no built-in preview synchronization with UI
clients and application-owned reference authorization, output storage and size
limits. The provider supplies no output index connecting previews to final
images. The API preserves this ambiguity rather than inventing a correlation.
No live discovery, rendering, provider billing or Flutter device was reviewed.
Serverpod/PostgreSQL verification is a separate coordinating-suite result.

A final malformed UTF-8 consumer verified the shared decoder correction through
`OpenRouterImageModel.stream`: safe `JsonHttpException`, preserved HTTP status,
redacted request ID, no attached decoder source and one request. The documented
Serverpod factory was independently reviewed for session authentication,
server-owned model/count, native results and cancellation. The scoped score
remains 8/10. Coordinating tests separately verify its real PostgreSQL/HTTP flow.

## Round 29: native Dart streaming

The independent developer first built a backend consumer using only the existing
public API. Streaming text, usage and approval details required string event
names and JSON maps; obtaining `AgentResult` by calling `generate` would execute
another run. Wire cancellation closed without a typed outcome. Private causes
were still available through `onError`. The scoped native streaming score was
**4/10**; this was a DX gap, not a malformed client protocol.

The new `AiAgent.stream` and `streamText` consumers receive typed text, usage,
tool outcomes and `AgentRunFinished` from one execution. The developer verified
approval/resume without an extra call, partial-result exceptions, caller-token
and subscription cancellation, private output exclusion from interim updates and
content-only delivery before provider completion. It reviewed the source-matched
guide, ran both examples and scored these journeys **8.5/10**. The tracked
approval recipe is `examples/review_cases/native_streaming.dart`.

Adversarial follow-up found that nested valid JSON `Map<dynamic, dynamic>` values
remained mutable in tool-result snapshots. The shared JSON freezer previously
matched only statically typed string maps. It now freezes all maps with string
keys; the original direct/runtime probes retain their original values and reject
nested mutation. Regression tests retain large Dart integers and reject invalid
non-string keys. The reviewer reran the original probes and normal streaming
flows successfully; the scoped score remains 8.5/10.

The review did not test real providers, Flutter devices or PostgreSQL. Native
streaming is a backend/local API, and protocol journals still live in core.
Persisted Serverpod verification is a separate coordinating-suite result.

A storage-time ownership probe also mutated a tool's source map during journal
append. The stored tool message and wire event retained the original value,
but the new native event initially copied the later mutation. The runtime now
snapshots the outcome before the first storage await and reuses that value for
history, the journal and the native update. The original regression passes.

## Round 30: OpenAI custom text tools

The independent developer's baseline scored this workflow **2/10** because an
SDK custom-call type did not provide an agent lifecycle. The current scoped
offline score is **8/10**. The tracked
`examples/review_cases/openai_custom.dart` uses the public SDK with MockClient,
recreates agents with one store, and runs approval, denial and locally rejected
input. It verifies raw string input, native custom outputs, exact private replay
and zero effects before approval. The matching live CLI example was analyzed and
compiled only.

A completed-history probe found that removing or renaming a custom tool broke a
new user turn. The corrected adapter replays resolved historical calls by their
private native identity. Removed tools, changed aliases, changed bindings and a
replacement function all pass the original probe without reexecuting old calls.
Unfinished approvals remain bound to the full ordered registry and model profile.

The developer also ran three Dart-client restoration cases: approve, reject and
cancel after disposing and recreating the client. These use a synthetic native
transport. Separate coordinating tests exercise actual SDK HTTP, PostgreSQL and
the official JavaScript client. None of these fixtures establishes live grammar
acceptance, model availability, external effect safety or provider billing.

The final independent safety review found no blocking issue in complete-batch
validation, the saved execution profile, declared fallback policies or uncertain
native failure handling. The scoped score remains 8/10. The coordinating full
suite separately passes 694 unit/regression tests and 38 actual PostgreSQL tests;
these results do not increase the independent score to package-wide acceptance.


# Source: docs/architecture.md

# Architecture

The public Dart API and the TanStack wire protocol are separate contracts.
Provider adapters convert provider requests and responses. The runtime owns
agent execution. Serverpod owns the framework session, authentication, and
database connection.

## Model invocations

`ChatModel.stream` performs one invocation and emits sealed `ModelEvent` values.
The runtime validates tool calls, executes configured server tools, appends the
results, and invokes the model again. `maxSteps` bounds the loop.

`ProviderOutput` preserves provider-specific replay state, such as encrypted
reasoning. That state stays in server storage and is excluded from UI history.
Adapters must retain any state their provider requires to continue a tool call.

Images, speech, transcription, embeddings, Decisions, video jobs, and realtime
use separate capability interfaces. A provider implements only the interfaces
it supports. `GenerationTask<P, R>` adds result/progress streaming to a typed
operation.

## Provider configuration across turns

An adapter can implement `ModelContinuationContract` to bind its frozen,
secret-free execution profile across a pending batch or provider pause. Core
checks the original private snapshot before resumed effects and dispatch.
Native OpenAI Responses and Anthropic Messages use it for managed tools, options and provider/account
authority; other adapters need their own declaration. Unbound custom models do
not gain an identity guarantee. See [approval contracts](approval-contracts.md).

## Native computer calls

`NativeModelTool` and `NativeToolCall` distinguish provider-native definitions
and calls from function tools, using a provider namespace to match the adapter.
The selected OpenAI Responses computer implementation and Anthropic computer
toolset each register one native server tool. The application owns action execution and the resulting screenshot;
the runtime owns approval, sequencing, and continuation. OpenAI custom text
tools use a separate native result handler. Other native tool kinds and
client-executed native tools remain unsupported.

Native approvals use an approval-only response schema; arguments cannot be
edited. A paused call is bound to its tool definition and stable environment
ID, so a changed binding cannot resume it. Rejection, cancellation, or execution
failure closes the native continuation while retaining its audit history. Start
a new thread after inspecting the environment; never synthesize a screenshot or
acknowledgement. Provider continuation data is private, separate from UI history.
See [computer use](computer-use.md) for the application contract.

## Ordered native batches

`SequentialNativeTool` defines provider-valid failure and skipped-result policy.
After its first failed result, later executors in the same model turn stop.
Sequential native tools return their provider-valid skipped results and ordinary
functions return generic skipped errors. A native tool that cannot represent a
skipped result closes the continuation. The policy resets for
the next model turn and is included in the persisted definition binding.

When one sequential native call requires approval, the entire mixed turn pauses
before any executor runs. All answers are validated before execution, and approved
calls retain model order. A computer failure stops later mixed-turn effects; the
next model turn can recover from the error results.

## Anthropic normalization

`AnthropicProtocolModel` encodes canonical runtime history and normalizes raw
Messages events. `AnthropicNativeClient` uses the shared HTTP transport for
request-scoped cancellation and deadlines. The SDK-backed facade uses the same
normalizer without first decoding provider events into lossy SDK models.
Typed SDK configuration applies only differences from a pre-callback snapshot,
preserving unknown unchanged JSON fields. Canonical guards still reject changes
to server-owned messages, tools, bounds and requested output schemas.

Original supported content blocks are stored in `anthropic.messages`; compact
message and usage metadata live separately in `anthropic.messages.metadata`.
Only content blocks are replayed. Neither namespace enters UI hydration.

## Ownership and cancellation

The caller owns provider clients. Close them at application shutdown.
Each invocation owns a child cancellation token. `CancellationToken.bindStream`
links it to a caller signal and forwards pause/resume. Cancelling one subscription
signals only that invocation; cancelling the caller signal synchronously signals
all active children. The run releases its reservation after cleanup.

An HTTP response owns a separate Serverpod session for the duration of its
stream. Create tool context from that session. The incoming HTTP request session
is unsuitable for work that continues while the response body is streamed.

## Persistence

`RunStore` reserves a thread atomically and rejects reused run IDs. Reservations
are scoped to the authenticated owner. Event logs are append-only, and complete
conversation checkpoints are saved separately. Terminal events, final checkpoints, and reservation release commit atomically.
Observers cannot see successful completion before the final state is committed.

`MemoryRunStore` is for development. `ServerpodRunStore` uses PostgreSQL row
locking and unique indexes. Applications can implement the same contract for
their own storage.

A durable event log permits replay. It does not provide exactly-once execution
of an external tool after a process crash. Active reservations are deliberately
not stolen automatically. Reconcile external effects using `ToolContext.idempotencyKey` before
recovering an abandoned run.

## Transport

`AgentChatRoute` supports POST for execution, GET with `threadId` for history,
and GET with `runId` and `offset` for event replay. Authentication applies to
every operation. Replay observes persisted events; it does not rerun the model.

`streamAgent` fits a generated Serverpod endpoint returning `Stream<String>`.
`serverpodConnection` connects that endpoint to `tanstack_ai_dart`.

## Native provider boundaries

Together uses its own request serializer and HTTP stream transport. Delegating
its requests to the OpenAI SDK would lose unrepresented fields and change native
numeric `logprobs` into an OpenAI boolean. Adding hidden HTTP body rewriting
would also separate the public types from what was actually sent. The native
boundary keeps those provider differences visible in `TogetherChatOptions`.

`TogetherChatModel` converts one `ModelRequest` into one native request and maps
streamed text, reasoning, tools and usage back into core events. `AiAgent` owns
approvals, validation, tool execution and authoritative history. The raw client
provides a separate JSON contract for native choices and metadata that the agent
does not normalize. Cancellation and timeout belong to each HTTP request;
cancelling one stream does not close a shared client.

## Compatible protocol reuse

`ResponsesProtocolModel` and `ChatCompletionsProtocolModel` own canonical request
serialization, runtime option guards and event normalization. The OpenAI SDK
facades retain their existing client API and supply typed SDK transports. Gateway
supplies a native JSON transport instead, appending its documented
`providerOptions.gateway` extension after canonical request construction.

This keeps one tested implementation of each wire protocol. Copying the entire
encoder/parser into each compatible provider would make continuation fixes drift.
Rewriting HTTP bodies behind an SDK client would obscure the actual request type.
The explicit protocol boundary avoids both problems.

Provider replay is namespaced separately. Gateway Responses cannot replay a
message's private OpenAI Responses state, and it rejects provider file handles
until their gateway/account ownership can be established. URLs and inline input
remain separate source variants.

`agent_weave_http` owns HTTP methods with explicit empty, JSON or binary bodies
and JSON SSE/NDJSON I/O for native adapters. Together, Gateway and Cloudflare use the
same per-request deadline, abort, metadata and error-body handling. Provider adapters own finish/EOF semantics and credential redaction.
This package does not add an HTTP dependency to the core agent runtime.

`CancellationToken.whenCancelled` remains the one-shot Future API.
`onCancelled` supplies a single-event Stream when a component needs a removable
listener. Late subscribers still receive cancellation. Native request scopes and
linked model subscriptions dispose that listener after completion or cancellation
so a long-lived parent token does not retain completed request callbacks.

## Native OpenRouter fields

OpenRouter uses the shared Chat/Responses codecs for canonical agent messages,
tools, schema and token bounds, then appends native options through its explicit
JSON transport. This preserves fields the OpenAI SDK does not represent. Keeping
the old SDK-only transport would discard those fields; copying a complete codec
would duplicate continuation and validation logic.

Responses replay uses the SDK's existing raw `ResponseInput.fromOutputItems`
constructor with immutable snapshots. Re-parsing returned output through typed
input unions would reject reasoning items or drop valid output fields. Typed
configuration is compared against a pre-callback snapshot, including absent
runtime fields and Chat's alternate token bound and stream options.

Chat reasoning fragments and response-level metadata have separate private
namespaces. Only reasoning fragments are replayed as Chat continuation. Metadata
is a compact snapshot of reported fields; raw native methods retain complete
events without storing every text chunk twice in assistant history.

## Ollama and Dart Frog

Ollama uses native NDJSON rather than the compatible SSE codecs. The adapter
assembles selected message fields, retains original frames privately and maps
native call IDs to separate local runtime IDs. It replays thinking, tool indexes
and native IDs without exposing them through UI hydration. Tools with conflicting
repeated indexes fail before execution; raw streaming remains available.

Dart Frog handlers use core chat requests, generation tasks, stores and event
encoding. Authentication supplies owner identity and trusted context. Both chat
and generation derive identity on the server; generation decoding can use that
context to bind parameters. The application owns provider/store lifetimes and
keeps request-context resources valid until its response stream ends.

## Provider-owned continuations

`ModelFinished.continuation` ends one complete invocation and requests the next
model step without local tool results. The runtime checkpoints the assistant
message and private provider data before dispatch. It counts the step, retains
usage and protects unfinished continuation from new user messages. A paused
step-limit run can be continued explicitly using a new run ID and no new
messages; ordinary provider errors are never automatically retried.

Anthropic hosted tools belong to provider model configuration rather than the
application executor registry. Their native blocks and container IDs remain
private replay state. Local tool calls still pass through the core approval
and schema-validation path, including programmatic callers from code execution.

Successful structured responses retain parsed data with the original JSON in
`ChatMessage.structuredOutput`. Providers continue to encode the original text.
Hydration preserves completed structured parts; a structured pause emits a
sanitized message snapshot so intermediate progress cannot remain an errored
answer in either client. Private provider replay never enters that snapshot.


## Approval identity belongs to the Dart runtime

Private pending tool contracts preserve declared configuration and Dart numeric
values. The runtime validates the whole batch before any execution. Public
TanStack schema hashes retain their protocol semantics and do not decide whether
a server-owned contract changed. This keeps native Dart validation independent
of client numeric conversion; see [approval contracts](approval-contracts.md).


## Public text citations

`ChatMessage.citations` holds typed annotations over flattened assistant text.
The range uses UTF-16 answer offsets; source locations retain their native
character, page or block units. Providers emit `CitationReady` after the referenced
text is available. The runtime validates ranges before publishing the additive
`agent_weave:citation` event and persists annotations with their message.
Hydration and terminal snapshots include only typed public citation JSON in
`metadata.agent_weave.citations`.

Citation-bearing content parts would require every text and media converter to
understand a new text shape. Message annotations preserve the existing content
contract and let ordinary clients retain metadata. Provider replay remains a
separate private contract, including opaque fields that cannot be public. See
[citations](citations.md) for the five supported Anthropic projections and replay
input differences.


## Provider output references

`OutputReference` retains a typed source, enclosing UTF-16 part and a distinct
provider-reported range, insertion point or file-list position. Native coordinates
are opaque and never become `TextCitation` offsets automatically. Zero-range
container outputs and references on empty parts are representable without
inventing a highlight. Typed file sources carry an explicit provider namespace.

The runtime persists references and emits indexed CUSTOM events plus terminal
snapshots. Hydration stores references and citations in the same public metadata
bag. Native output remains private, with only reviewed fields projected.
Applications own file authorization and download routing. See
[output references](output-references.md).

## Anthropic MCP ownership

MCP servers and toolsets are owned immutable provider configuration. The adapter
resolves credentials per request and emits `ProviderExecutionStarting` before
dispatch so core can checkpoint an uncertain effect. Remote use/results and
2026 listings remain private native replay; they never invoke local executors.
A mixed local turn can defer remote execution until local results are returned.
The same model profile, beta and server authority survive that approval or a
provider-only pause. See [MCP](anthropic-mcp.md).

## Dedicated image generation

OpenRouter's dedicated Image API implements the typed `ImageModel` capability
separately from Chat. Native generation responses do not contain provider IDs or
a model field; the adapter preserves that shape. Its stream emits typed native
partial, text, completed and error events, with an explicit buffered fallback.
The shared transport selects JSON or SSE from one response's content type and
never submits a second generation POST. Applications can wrap the operation in
`GenerationTask` for durable Serverpod results without changing the native DTO.
See [dedicated images](openrouter-image-api.md).

## Native streaming and protocol projections

The runtime emits a private sealed execution-event family. One variant carries
native `AgentUpdate` values from validated model and tool values; the other
carries the existing journaled `AgentEvent`. `AiAgent.stream` projects native
updates and finishes with the same run's typed result after committed completion
or interruption. `AiAgent.run` projects protocol events for existing clients.
Neither projection reconstructs the other or invokes the model again.

Standard Dart stream transforms forward pause and cancellation to the existing
request-scoped stream. An async-generator filter initially delayed subscription
cancellation while awaiting the provider; regression tests reproduce that
failure and verify the transform-based correction. `generate` shares final
result/error classification. Pre-terminal updates are provisional, and final
results retain backend-only state. This is a public API separation; extracting
protocol journals into an optional package remains separate roadmap work.

## Registered native custom tools

OpenAI custom definitions map an exact provider namespace/name pair to a local
executor alias. Private replay retains the complete native item; public arguments
contain only the raw text input. The adapter reconciles stream item identities,
sequence numbers, input fragments and terminal output before releasing calls.
Typed SDK transport preflights configuration and uses raw input replay to retain
unknown native fields. Completed custom calls can replay after registry changes
without dispatching their old executor; unfinished calls retain the original
full registry binding.

`ModelToolValidator` checks complete configurations before a run. Core stores an
`agent_execution` model profile containing the adapter profile and every ordered
registered tool contract. This includes bindings and `NativeToolFallback` values.
The fallback factories declare pure, provider-valid denial/cancellation/skipped
outcomes. Denial can continue a custom conversation, while computer tools without
a declared fallback still close. Thrown or cancelled native execution remains
uncertain and never receives a synthetic success result.


# Source: docs/tools.md

# Typed tools and approvals

Use `Tool<I, O, C>` to declare the decoded input, return value, and trusted
application context. JSON Schema validates inputs before `decode` and validates
encoded results before they enter the conversation.

```dart
final doubleNumber = Tool<int, int, Session>(
  name: 'double',
  description: 'Double an integer',
  inputSchema: const {
    'type': 'object',
    'properties': {'number': {'type': 'integer'}},
    'required': ['number'],
    'additionalProperties': false,
  },
  outputSchema: const {'type': 'integer'},
  decode: (json) => json['number'] as int,
  encode: (result) => result,
  execute: (number, context) => number * 2,
);
```

`context.value` is your application context. `context.ownerId` comes from
authentication. Use both to enforce application permissions. Registering a tool
does not grant a user permission to operate on every database row.

## Approval

Set `needsApproval: true` to pause before a tool executes. The terminal event
contains a TanStack interrupt binding. Configure the matching input and output
schemas in the UI client so it can bind the approval.

The Dart client uses `interrupt.resolveApproval(true)`. The pinned JavaScript
client uses `interrupt.resolveInterrupt(true)`. Both submit AG-UI resume entries
with `interruptId`, `status`, and `payload`.

A new run identifies the interrupted run with `parentRunId`. Every pending
interrupt must receive one answer. AgentWeave validates the entire answer batch
before executing any resumed tool. Invalid answers preserve the previous
pending snapshot so the user can correct them.

Default approvals support approval, rejection, and schema-validated edited
arguments. Custom approval payload schemas and first-party generic interrupts
are not implemented yet.

### Edit tool arguments in a client

Register matching input and output schemas on both sides. After the user edits
the proposed arguments, resolve the typed approval using your client's API.
The Dart and JavaScript method arguments differ.

For the workspace-pinned Dart `ChatClient`:

```dart
final interrupt = chat.getInterrupts().single;
interrupt.resolveInterrupt({
  'approved': true,
  'editedArgs': {'priority': 2},
});
```

For the pinned official JavaScript `ChatClient`:

```javascript
const [interrupt] = chat.getInterrupts();
interrupt.resolveInterrupt(true, {editedArgs: {priority: 2}});
```

These are client calls. Direct Dart backend code instead resumes a
`ChatRequest` using `paused.interrupts.single.approve(editedArgs: ...)`, as shown
in the [Dart API guide](dart-api.md). Do not automatically approve on behalf of
the user or use a client decision as authorization for an unrelated resource.

The tested raw object schema uses a local `$defs`/`$ref` for `priority`. Both
clients bind the approval and complete a valid edit. Invalid edits can reach the
backend with raw JSON schemas; the backend rejects them before effects. Do not
assume that a client accepting the edit proves it matches the schema.
This covers the named raw schema case, not every reference or validator.

## Client tools

Register `ClientTool<C>` on the server to allow an explicitly named client-side
operation. Its result arrives through the same interrupt continuation protocol
and is validated against the configured output schema. Client-advertised tool
names do not automatically become trusted executable server tools.

## External effects

Pass `context.idempotencyKey` as an idempotency key to services that support it.
If a process crashes after an external service commits an effect, inspect that
service before retrying. Database history cannot make an unrelated external
service execute exactly once.


## Resume the original contract

Persisted approvals bind a private exact tool contract, including schemas and
execution kind. Recreated agents must preserve it. Older checkpoints without
this snapshot require a new conversation; their history remains readable.
See [approval contracts](approval-contracts.md) for recovery and custom-store
migration. Public client schema hashes remain a separate wire contract.

## Native text tools and declared fallbacks

Use [OpenAI custom text tools](openai-custom-tools.md) for raw string input and
native text/image/file output. These use `NativeToolCall` and approval-only
responses; their grammar does not replace application validation or authorization.

Provider authors can implement `NativeToolFallback<C>` to declare pure denial,
cancelled-approval and skipped results. Core validates these values against the
output schema and binds them into the private tool profile. Only an explicit
fallback can continue a rejected native call. Unknown execution exceptions and
caller cancellation still close the native continuation; no fallback implies
rollback or permission to repeat an external effect. Existing computer tools
retain their screenshot and closed-continuation requirements.


# Source: docs/approval-contracts.md

# Persisted tool approvals

An approval applies to the tool contract that produced the pending call.
Recreating an agent must not reinterpret a client result as a server approval
or execute a call under changed schemas or native bindings.

AgentWeave records a versioned `toolContract` snapshot in private pending state.
Before resuming, it compares the complete resolution batch with the current
tool definitions. No executor or subsequent model request runs until every
pending contract and answer has been validated.

## What the contract binds

The snapshot contains the tool's name, description, input and output schemas,
function/native kind, client execution and approval flags, and sequential
failure-policy trait. Native tools also bind their provider, execution binding
and declared native definition.

Comparison retains Dart integers and ignores JSON object-key order. Equivalent
integer and integral-double values compare equally when their values are
exactly equal. Adjacent large integers and rounded doubles do not become equal
through JavaScript conversion. Memory and PostgreSQL tests exercise these rules.

The contract does not serialize Dart closures, application permissions or live
driver state. If an executor's meaning changes without changes to its declared
configuration, version the tool name or native binding. Keep authorization and
idempotency checks in the application service.

## Model continuation contracts

A paused local tool can share a turn with provider-executed tools even when
there is no provider approval. Its continuation must retain the provider
configuration as well as the local tool definition.

`ModelContinuationContract` is an optional adapter capability. Core stores its
versioned, secret-free `continuationContract` inside an `agent_execution`
checkpoint envelope alongside the complete ordered registered-tool contracts.
Core checks both before resumed local effects and provider invocations. Changing
a custom tool that was not called can therefore invalidate an ordinary pending
function approval; the future model step must retain its original registry. The
original snapshot survives staged batches, provider pauses and step-limit
restarts until the turn finishes. Mismatches preserve the old checkpoint and
release the attempted run's reservation. Retry with the original configuration
or start a new conversation; never rebind an old approval to today's settings.

Native OpenAI Responses and Anthropic Messages models implement this capability.
Their profiles bind
the model and protocol, stable `authorityBindingId`, complete ordered managed
tool definitions, MCP credential bindings, `toolChoice`, frozen `functionToolOptions` and
`options`. Anthropic additionally binds initial container, document/system
cache declarations and its beta list. Managed tools require an authority ID and reject arbitrary `configure`
callbacks. Credential rotation under the same logical account is permitted;
actual tokens are resolved per request and stay outside the profile. The
application must assign authority IDs honestly, including endpoint and account
changes. An ID does not discover or verify a provider account.

Adapters without this capability receive an explicit unbound marker. That
marker distinguishes replacement by a bound model; it cannot detect changes
inside an arbitrary unbound adapter. Other built-in adapters do not inherit
OpenAI's profile guarantee merely because they reuse its protocol codec.
Custom adapters with provider-controlled execution must implement the capability
and guard all effective execution configuration. See
[writing a provider](providers.md#bind-provider-controlled-continuations).

Older unfinished checkpoints without the original model snapshot and complete
registry envelope fail closed,
including checkpoints that already contain a local `toolContract`. No database
schema change is required. Completed conversation history remains readable.
Contracts describe declared configuration; application permissions and external
effects still require authorization and idempotency at the destination service.

## Private contracts and public client hashes

| Data | Purpose | Where it belongs |
| --- | --- | --- |
| `toolContract` | Exact declared tool contract for server-side resume validation | Private pending checkpoint |
| `schemaHash` | Existing TanStack interrupt-binding compatibility, including JavaScript number semantics | Public protocol binding |

The public binding format and hashes remain unchanged. A protocol-compatible
hash is not proof that two Dart schemas are identical. Server-owned approval
checks do not rely on it.

Contracts contain full schemas and native configuration. They stay out of
public events and `chatHydration`, like other private continuation data. Custom
stores must round-trip the complete opaque checkpoint without dropping fields
or converting native integers to doubles.

JavaScript clients still have JavaScript's numeric limits. This change does not
make cross-language JSON integers above the safe JavaScript range exact; use
strings for identifiers that must survive such clients without rounding.

## Recovery and migration

Changed, missing, malformed or unsupported contracts fail with `INVALID_INPUT`
before side effects. The original pending state and history are preserved.
For a changed configuration, retrying with the original complete contract can
resume the original approval.

Checkpoints written before exact contracts were introduced cannot prove the
original contract. Their old hashes cannot reconstruct it. The SDK rejects
those approvals rather than inventing a snapshot from the current tool.
Start a new conversation; retain the old one for history. This is a pending
checkpoint migration, not a database-table migration. Do not automatically
replay an old call or copy its unfinished tool state into a new conversation.

Both `run()` error events and `AgentRunException.message` provide a safe recovery
instruction. Future callers can display `message` and inspect `code`.
`cause` and `causeStackTrace` remain backend diagnostics and must not be returned
to a client. Provider exception text is not used as the public message.

## Reproduce the checks

```sh
dart run examples/review_cases/approval_contract.dart
dart test packages/agent_weave/test/approval_contract_test.dart
dart run tool/check.dart
```

The independent consumer tests input/output schema collisions, native
definitions, client/server execution changes, whole-batch validation, owner
isolation, equivalent schema ordering, original-contract retry and legacy
recovery. PostgreSQL tests recreate agents and verify exact integer persistence
and rejection before model or executor invocation. Ordinary client approval
flows continue through the existing JavaScript and Dart interoperability suite.


# Source: docs/providers.md

# Write a provider

Implement `ChatModel`. Keep provider credentials, HTTP details, and provider
options inside your adapter.

```dart
final class LocalModel implements ChatModel {
  @override
  ModelCapabilities get capabilities => const ModelCapabilities();

  @override
  Stream<ModelEvent> stream(
    ModelRequest request, {
    required CancellationToken cancellation,
  }) async* {
    cancellation.throwIfCancelled();
    yield const TextDelta('Hello from a custom provider');
    yield const ModelFinished();
  }
}
```

Emit exactly one `ModelFinished` after a successful invocation. Do not emit
later events. An interrupted transport must throw or end without that event;
the runtime treats premature EOF as a failure.

Emit a `ToolCallReady` only after accumulating and parsing the complete argument
object. The runtime handles schema validation and execution. Do not execute a
tool inside the provider adapter.

Use `ReasoningDelta` for provider-supported reasoning summaries and
`ProviderOutput` for opaque continuation state. Never expose private replay
state as user-facing text. Emit `TokenUsage` when the provider reports it.

Pass `cancellation.whenCancelled` to the provider's abort mechanism. Check
pre-cancellation before submission. If an operation cannot abort after
submission, document that limit rather than silently promising cancellation.

The fixture providers in `packages/agent_weave/test` and the offline example
demonstrate custom implementations without any OpenAI dependency.

## Completed media

Emit `ContentPartReady(ImagePart(url))` for a completed generated image. Text
continues through `TextDelta`. The optional `textOffset` places media at a UTF-16
offset in the text accumulated for this invocation; omit it to use the current
position. Offsets must be nondecreasing and cannot point beyond received text.
The runtime preserves this order in assistant history and sanitized client
snapshots. `AgentResult.images` collects assistant images from the current run.

Validate provider URLs and complete payloads before emitting media. Keep opaque
image signatures and continuation fields in `ProviderOutput`, with a distinct
provider namespace. Bind replay to its public content before restoring it;
provider data must not overwrite roles, registered calls, schema or history.
Partial image previews need a separate progress contract; do not publish them
as completed content.

## Native tools

Use `NativeModelTool` and `NativeToolCallReady` for provider-native protocols,
with matching provider namespaces and stable execution bindings. Preserve the
original provider continuation privately; UI tool names can differ from native
toolset member names. Validate the full native turn before exposing executable
calls. Native approvals are read-only, and changed definitions cannot resume.

Implement `SequentialNativeTool` only when the provider supports valid skipped
results after a failed action. Its `skippedResult` must never perform an action.
OpenAI computer calls have no such denial result; Anthropic's computer toolset
uses its documented error results. See the provider guides for each contract.


## Text citations

Emit `CitationReady(TextCitation(...))` after its answer text is available.
Offsets are UTF-16 code units into all `TextDelta` output for that invocation;
source coordinates remain separate. The runtime validates boundaries, persists
annotations with the assistant message and exposes safe citation metadata to
clients. Put only public fields in a typed citation. Keep native replay fields
in `ProviderOutput`. See [citations](citations.md) for source types and wire data.


## Native output positions

Emit `ReferenceReady(OutputReference(...))` when a source has a native range,
insertion point or file-list ordinal that cannot be treated as a verified Dart
text highlight. Supply the known UTF-16 enclosing `partStart`/`partEnd` separately.
Keep provider positions opaque and use typed source fields. Scoped file handles
are deliberate public data and require application authorization.
See [output references](output-references.md).


## Provider-owned approvals

Implement `ProviderApprovalModel` when the provider executes tools remotely and
can request a human decision. Emit `ProviderApprovalReady` with a
`ProviderApprovalCall`. Generate a distinct local call ID for public display;
keep `providerRequestId` in backend state. Do not register a dummy `AgentTool`
or emit a local tool result for a remote approval.

`approvalContract(call)` returns an immutable, versioned configuration snapshot
for resume checks. Bind all relevant remote tools and authorization identities;
resolve secrets at request time. Approval and denial arrive as trusted
`ModelRequest.providerApprovalDecisions` across the saved conversation. Preserve
their native correlation and order. Reject a different provider's decision
history before dispatch. Never accept raw continuation state from a client.

Emit `ProviderExecutionStarting` immediately before a request that can cause
provider-managed effects, after preflight and credential resolution. The runtime
checkpoints an indeterminate marker before advancing your stream. A known
terminal checkpoint clears it; failure or cancellation cannot automatically
resend the request. Omitting this event on an initial remotely executing request
would leave that failure boundary unprotected. Include it even when no approval
has occurred, such as a server configured to execute without asking.

The [OpenAI MCP adapter](openai-mcp.md) demonstrates this contract. Its pinned
clients use generic approval payloads. Native computer execution remains a
separate local-driver contract with different denial behavior.

## Bind provider-controlled continuations

Implement `ModelContinuationContract` when an adapter has provider-controlled
execution configuration. Return a stable, immutable JSON object with integer
`v: 1`, a nonempty adapter-defined `kind`, and all nonsecret execution authority: provider/model, endpoint or a
stable transport/account binding, managed tools, policies and effective options.
Keep live credentials separate. Core saves the original snapshot and compares
it before resumed local effects or dispatch, including local-only approvals
that share a turn with remote tools.

Build requests from the same frozen configuration. An arbitrary callback cannot
safely redefine that configuration after a pause. Reject such combinations or
provide an immutable options API, as native OpenAI Responses does. Preserve the
private snapshot in custom storage. Never reconstruct a missing historical
profile from current settings.

This capability does not validate arbitrary application code or infer identity
from tokens. An undeclared adapter gets an unbound marker, not a verified
no-effects contract. See [approval contracts](approval-contracts.md).

## Validate complete tool registries

Implement `ModelToolValidator.validateTools` when an adapter has cross-tool
constraints such as duplicate native identities, namespace groups, incompatible
choices or lossy typed request definitions. The agent invokes this pure validation
at construction before it can run local effects. The adapter must also validate
standalone model requests.

Core now binds every ordered registered tool contract with the declared model
profile across unfinished turns. A model's unbound marker still does not prove
provider account identity. Provider-owned native replay stays private, while
`NativeToolFallback` can declare provider-valid non-execution outcomes for
ordinary denial or skipped calls. Do not use this capability to recover unknown
execution effects automatically.


# Source: docs/documents.md

# Send documents to a model

Use `DocumentPart` in a user message to send a document by URL, inline data,
or a provider file ID. The adapter sends the reference or data you provide. It
does not upload or download files for you.

## Send inline text to OpenAI Responses

From the workspace root, run `dart pub get`. Save this example as
`examples/document_demo.dart`. Set `OPENAI_API_KEY` and `OPENAI_MODEL` in your
backend environment, choosing a Responses model available to your account.
Running the example makes a paid provider request.

```dart
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_openai/agent_weave_openai.dart' as openai;

Future<void> main() async {
  final apiKey = Platform.environment['OPENAI_API_KEY'];
  final modelId = Platform.environment['OPENAI_MODEL'];
  if (apiKey == null || modelId == null) {
    throw StateError('Set OPENAI_API_KEY and OPENAI_MODEL.');
  }
  final client = openai.OpenAIClient.withApiKey(apiKey);
  try {
    final model = openai.OpenAIResponsesModel(client: client, model: modelId);
    final request = ModelRequest(messages: [
      ChatMessage(id: 'user-1', role: MessageRole.user, content: [
        TextPart('Summarize this document.'),
        DocumentPart.bytes(
          'AgentWeave runs agents in Dart.'.codeUnits,
          mimeType: 'text/plain',
          filename: 'note.txt',
        ),
      ]),
    ]);
    await for (final event in model.stream(
      request,
      cancellation: CancellationToken(),
    )) {
      if (event is TextDelta) stdout.write(event.text);
    }
    stdout.writeln();
  } finally {
    client.close();
  }
}
```

Run `dart run examples/document_demo.dart`. A supported model prints a
summary. Provider permissions, model formats, and file size limits still apply.

## Choose a source

Replace the `DocumentPart.bytes` value in the example with one of these:

```dart
// An absolute HTTP(S) URL without embedded credentials.
DocumentPart.url('https://example.com/report.pdf', filename: 'report.pdf')

// Base64-encoded, nonempty file content, without a data URL prefix.
DocumentPart.base64(encodedContent, mimeType: 'application/pdf', filename: 'report.pdf')

// A file already uploaded to OpenAI by your application.
DocumentPart.fileId(fileId, provider: 'openai', filename: 'report.pdf')
```

`DocumentPart.bytes` base64-encodes a nonempty byte list. `base64` accepts
nonempty base64 data and requires a MIME type without parameters. Filenames are
optional. File IDs belong to their issuing provider and cannot be moved between
providers. Your application obtains the ID separately.

## Provider support

- OpenAI Responses accepts URLs, inline data, and file IDs with
  `provider: 'openai'`.
- Anthropic Messages accepts URLs, inline PDF/plain text, and file IDs scoped
  with `provider: 'anthropic'` through the raw/native agent path. The pinned SDK's
  typed `configure` callback cannot decode file handles; use native JSON configuration.
  This does not verify account permissions or provider acceptance.
- OpenAI Chat Completions and the OpenRouter adapter reject document inputs.

These are adapter contracts tested offline. The provider and selected model can
impose additional format and size limits. See [Anthropic Messages](anthropic.md)
and [OpenRouter](openrouter.md).

## History and retention

`RunStore` retains inline document bytes and URLs as part of stored messages.
Authorized history clients receive those values, including signed URLs. Your
application is responsible for retention, access controls, and payload limits.
Persistence across restarts depends on the configured store. A signed URL may
expire even if the history still contains it.

For large inputs, prefer an application-managed URL or a supported provider file
ID. Base64 increases payload size. The example Serverpod configuration has a
512 KB global request limit and the chat route has its own 1 MB limit; the
smaller applicable limit wins. Confirm your deployment's configured limits.

Run `dart --enable-asserts run examples/review_cases/documents.dart` from the
workspace root to exercise the offline request and history contracts without a
provider key. No actual PDF parsing or model acceptance is proved by that fixture.

Provider format rules: [OpenAI file inputs](https://developers.openai.com/api/docs/guides/file-inputs)
and [Anthropic PDF inputs](https://platform.claude.com/docs/en/build-with-claude/pdf-support).


# Source: docs/citations.md

# Cite source documents

Enable Anthropic document citations and read typed attribution from each
assistant message. The adapter normalizes all five citation variants in the
pinned Messages contract. Other provider adapters do not yet normalize citations.

## Run a document question

Set `ANTHROPIC_API_KEY` and `ANTHROPIC_MODEL` in your backend environment, then
run `dart run examples/anthropic_citations_demo.dart`. Choose a model that supports
document citations. This command makes a billable request; ordinary repository
checks do not run it.

```dart
import 'dart:convert';
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_anthropic/agent_weave_anthropic.dart' as anthropic;

Future<void> main() async {
  final key = Platform.environment['ANTHROPIC_API_KEY'];
  final model = Platform.environment['ANTHROPIC_MODEL'];
  if (key == null || key.isEmpty || model == null || model.isEmpty) {
    throw StateError('Set ANTHROPIC_API_KEY and ANTHROPIC_MODEL.');
  }
  final client = anthropic.AnthropicNativeClient.withApiKey(apiKey: key);
  try {
    final result = await generateText(
      model: client.chatModel(model: model, citations: true),
      messages: [
        ChatMessage(
          id: 'question',
          role: MessageRole.user,
          content: [
            DocumentPart.bytes(
              utf8.encode('Annual leave requests need manager approval.'),
              mimeType: 'text/plain',
              filename: 'Leave policy',
            ),
            const TextPart('Who approves annual leave? Cite the policy.'),
          ],
        ),
      ],
    );
    for (final message in result.responseMessages) {
      if (message.role != MessageRole.assistant) continue;
      print(message.text);
      for (final citation in message.citations) {
        final claim = message.text.substring(citation.start, citation.end);
        final source = switch (citation.source) {
          DocumentCitationSource(:final index, :final location) =>
            'document $index, ${location.unit.name} '
                '[${location.start}, ${location.end})',
          UrlCitationSource(:final url) => url,
          SearchResultCitationSource(:final source) => source,
          FileCitationSource(:final provider, :final filename) =>
            '$provider file: ${filename ?? 'unnamed'}',
        };
        print('$claim ← $source');
      }
    }
  } finally {
    client.close();
  }
}
```

`citations: true` enables citations on every direct user document across the
conversation history. URL, inline PDF, inline UTF-8 text and Anthropic file-ID
documents use the existing `DocumentPart` factories. The typed SDK configuration
path still cannot decode file-ID sources; use `AnthropicNativeClient` for them.
Custom-content documents and search-result input blocks currently require the
separate raw native API.

Anthropic requires citations on all documents or none. It also rejects document
citations combined with `output_config.format` or the deprecated `output_format`.
AgentWeave checks both rules before dispatch, including formats supplied through
`configure`. Do not combine this option with `generateObject` or an agent output
schema. See [Anthropic's citation contract](https://platform.claude.com/docs/en/build-with-claude/citations).

## Render the answer and its sources

`ChatMessage.citations` is an immutable list. Each `TextCitation` contains
`start` and exclusive `end` offsets into that message's complete `text`, measured
in UTF-16 code units. These are the same offsets used by Dart `String.substring`
and JavaScript `String.slice`. A valid range cannot split a surrogate pair.

`citedText` is the source quotation. It need not match the generated answer span.
Anthropic attaches citations to a complete response text block, so several
citations can share the same answer range. Their order and duplicates are
preserved. The adapter emits them when that block closes, after any remaining
text deltas, and rejects interleaved text blocks that cannot form a contiguous
answer range.

Match `citation.source` to render its reference:

| Dart source | Location |
| --- | --- |
| `DocumentCitationSource` | `index` identifies a document across all request messages. `location` retains character, page or block coordinates. |
| `UrlCitationSource` | `url` and optional `title` identify a web result. |
| `SearchResultCitationSource` | `index` identifies a search-result input, counted separately from documents. `source` is an identifier and need not be a URL. |

Source character and block locations are zero-based. Pages are one-based.
Every source range has an exclusive end. Source coordinates retain the
provider's units; they are not converted to UTF-16 answer offsets. Do not locate
answer spans by searching for `citedText`.

Citation source text, titles and links are application content. The SDK validates
HTTP(S) URL syntax and rejects embedded user credentials, but does not fetch
links, detect secrets in query strings or decide what your users may read.
Apply the same document and link policy as the rest of your application.

## Stream and restore attribution

Native model consumers receive `CitationReady(citation)` alongside `TextDelta`.
`AiAgent.run()` emits this additive protocol extension after the cited text:

```json
{
  "type": "CUSTOM",
  "name": "agent_weave:citation",
  "value": {
    "messageId": "assistant-message-id",
    "citationIndex": 0,
    "citation": {
      "start": 0,
      "end": 6,
      "source": {
        "type": "document",
        "index": 0,
        "location": {"unit": "pages", "start": 1, "end": 2}
      }
    }
  }
}
```

Upsert incremental citations by `(messageId, citationIndex)` in your renderer.
The zero-based index is the annotation position in that message. Replayed events
reuse it, while two identical legitimate citations have distinct indexes. Do not
deduplicate citations by their value. On a final message
snapshot or history hydration, replace that message's attribution with
`message.metadata.agent_weave.citations`. The entries use `TextCitation.toJson()`
and can be decoded with `TextCitation.fromJson()` in Dart. Standard TanStack
clients retain this metadata through snapshots and restoration; an application
must render it. Generic clients may ignore the CUSTOM event until the snapshot.

Closed text-block citations remain attached to retained partial text after a
later failure or cancellation. An unfinished block does not produce a citation.
A citation does not prove the whole run succeeded. Display the run status too.

Only the public projection enters events and hydration. Anthropic provider file
IDs, encrypted citation indexes and unknown native fields stay in private replay
state. Other adapters can deliberately publish scoped `FileCitationSource`
handles; see [output references](output-references.md). Original response blocks
remain unchanged in storage. Continuation input
omits the known response-only document `file_id` while retaining the web-search
`encrypted_index` needed by the provider. Unknown citation types fail explicitly
instead of exposing an unreviewed payload.

## Add document context or cache control

The native `configure` callback may add `context`, `citations` and `cache_control`
to direct user document blocks. Return copied maps and lists; the supplied body
is immutable. Canonical document source and title remain protected. With
`citations: true`, configuration cannot disable citations. Without the flag,
per-document configuration must still enable all documents or none. Keep the
configuration deterministic when recreating an agent.

The model-level flag covers the ordinary use case. Native configuration and raw
Messages access are separate contracts; forwarding an option does not establish
live cache hits or complete nested provider support.

## Reproduce the offline checks

```sh
dart test packages/agent_weave/test/citations_test.dart
dart test packages/agent_weave_anthropic/test/citations_test.dart
dart run examples/review_cases/anthropic_citations.dart
dart run examples/review_cases/citations_client.dart
dart run tool/check.dart
```

The independent consumer uses loopback HTTP. Additional checks exercise both
clients and real PostgreSQL approval recreation. These fixtures do not contact
Anthropic or prove model availability, citation quality or Flutter rendering.


# Source: docs/output-references.md

# Read output references

To construct and read a reference without a provider account, run the
[offline support application](offline-support.md). Its file reference is synthetic.

OpenAI references describe URLs, cited files and generated artifacts.
`ChatMessage.references` preserves their distinct positions and enclosing text
segments. Use [text citations](citations.md) when an adapter can supply a verified
UTF-16 answer highlight.

## Run a source-backed answer

Set `OPENAI_API_KEY` and `OPENAI_MODEL`, then run
`dart run examples/openai_references_demo.dart` from the workspace. Choose a model
that supports web search. The command makes a billable request; repository
checks only compile its source.

```dart
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_openai/agent_weave_openai.dart' as openai;

Future<void> main() async {
  final key = Platform.environment['OPENAI_API_KEY'];
  final model = Platform.environment['OPENAI_MODEL'];
  if (key == null || key.isEmpty || model == null || model.isEmpty) {
    throw StateError('Set OPENAI_API_KEY and OPENAI_MODEL.');
  }
  final client = openai.OpenAIClient.withApiKey(key);
  try {
    final result = await generateText(
      model: openai.OpenAIResponsesModel.native(
        authorityBindingId: 'example-authority',
        client: client,
        model: model,
        hostedTools: [
          openai.OpenAIHostedTool.fromJson({'type': 'web_search'}),
        ],
      ),
      prompt: 'Find the latest stable Dart release and cite its release notes.',
    );
    for (final message in result.responseMessages) {
      if (message.role != MessageRole.assistant) continue;
      print(message.text);
      for (final reference in message.references) {
        final source = switch (reference.source) {
          UrlCitationSource(:final url, :final title) =>
            '${title ?? url}: $url',
          FileCitationSource(:final provider, :final filename) =>
            '$provider file: ${filename ?? 'unnamed'}, resolve on your backend',
          DocumentCitationSource(:final index) => 'Document $index',
          SearchResultCitationSource(:final source) => source,
        };
        print(source);
        print('Reported position: ${reference.position.toJson()}');
      }
    }
  } finally {
    client.close();
  }
}
```

## Choose the right coordinates

Each `OutputReference` contains its provider, typed source, native position and
`partStart`/`partEnd` segment. The segment is an enclosing output-text part in
UTF-16 code units, with an exclusive end. It may be empty. It identifies context,
not the exact cited words. You can read that context with
`message.text.substring(reference.partStart, reference.partEnd)`.

`reference.position` retains the provider's reported values:

| Position | Meaning |
| --- | --- |
| `ProviderTextRange` | Reported start/end values. A zero/zero pair is retained. |
| `ProviderTextPosition` | Reported insertion index in output text. |
| `FileListPosition` | Ordinal in a file list, not a text offset. |

Do not pass these native values to `String.substring`. The reviewed OpenAI
reference does not establish a Unicode unit or a precise end convention. Its
[Code Interpreter example](https://developers.openai.com/api/docs/guides/tools-code-interpreter)
also uses zero/zero coordinates for a generated file. AgentWeave preserves those
values without inventing a highlight or converting the pair into a point.
Synthetic Unicode tests verify the enclosing segment, not the service's indexing
convention.

## Read each OpenAI form

| Native form | Dart source | Position |
| --- | --- | --- |
| Responses `url_citation` | `UrlCitationSource` | `ProviderTextRange` |
| Responses `file_citation` | `FileCitationSource` with filename | `ProviderTextPosition` |
| Responses `container_file_citation` | `FileCitationSource` with container and filename | `ProviderTextRange` |
| Responses `file_path` | `FileCitationSource` without an invented filename | `FileListPosition` |
| Completed Chat `url_citation` | `UrlCitationSource` | `ProviderTextRange` |

The contracts and reviewed declarations are in the
[OpenAI inventory](openai-hosted-inventory.json). Responses uses flat annotation
objects. Completed Chat uses a nested `url_citation` object; an unknown nested
field cannot change the documented annotation kind.

Responses references are emitted after a valid terminal response and stream EOF.
The adapter reconciles annotation-added, content-part and output-item echoes with
terminal output by native indexes. Identical echoes do not add references twice;
two identical annotations at different indexes remain distinct. Null annotation
placeholders do not invent an entry. Conflicting, unknown or malformed entries
fail before local tool execution. Streamed text must match the final text before
the adapter attaches a reference to its enclosing segment.

Raw output and opaque fields remain unchanged in private provider replay.
Only reviewed source and position fields enter public references. Compatible
Responses endpoints do not inherit OpenAI annotation semantics automatically.

## Use completed Chat URL references

Use `OpenAIChatModel(client: client, model: modelId, streamText: false)` when you
need completed Chat annotations. The buffered request retains native response
JSON because the installed SDK's typed Chat decoder drops these annotations.
The existing typed configuration and runtime-owned messages, tools, schema and
limits still apply. The request sends `stream: false` and omits stream-only
usage options. It produces one completed text result with references, rather
than token-by-token delivery.

The default streaming mode accepts an empty annotation list but explicitly
rejects nonempty or malformed streamed Chat annotations. Use buffered Chat or
native Responses for supported references. Native Chat also rejects unknown or
inconsistent finish reasons before tools and permits a final empty-choice usage
event. Provider-specific adapters keep their own protocol rules.

The buffered raw response is private in `openai.chat_completions`. Response-only
Chat annotations are not inserted into subsequent request messages. Other
completed output modes, such as audio and legacy function calls, are not part of
this adapter's reference contract.

## Render and restore references

`ReferenceReady(reference)` is the provider-neutral model event. The runtime
publishes this extension:

```json
{
  "type": "CUSTOM",
  "name": "agent_weave:reference",
  "value": {
    "messageId": "assistant-message",
    "referenceIndex": 0,
    "reference": {
      "provider": "openai",
      "source": {"type": "file", "provider": "openai", "fileId": "file-id"},
      "partStart": 0,
      "partEnd": 0,
      "position": {"type": "file_list", "index": 4}
    }
  }
}
```

Upsert incremental entries by `(messageId, referenceIndex)` to handle replay.
Replace them from `message.metadata.agent_weave.references` on a message snapshot
or history hydration. Decode each JSON entry with `OutputReference.fromJson` in
Dart. Citation and reference arrays can coexist in the same metadata bag. Their
indexes are independent. Applications render the data; a generic TanStack
client retains metadata but does not create source cards for you.

Partial-run metadata remains associated with its retained text. References can
exist on an empty message part, so an empty text string does not imply that no
artifact was produced. A retained reference does not prove the run completed.

## Resolve file handles on the backend

`FileCitationSource` exposes `provider`, `fileId`, optional `containerId` and
optional `filename`. These are intentional public scoped handles, not URLs or
credentials. The `title` getter returns the actual filename when present.
AgentWeave does not manufacture a filename, download a file or host an artifact.

Bind each uploaded or generated file to the authenticated application owner.
Check that ownership and provider before using a backend API client to retrieve
bytes or returning a controlled application URL. A submitted file ID alone is
not authorization. Container files need their matching container context.
Apply the same check when reusing a handle in `DocumentPart.fileId`; the
`openai` provider namespace is shared by references and document input. Do not
assume that a container file ID is an ordinary uploaded-file ID; adapt it through
your backend when the target operation requires a different file resource.

Keep API credentials on the backend. Do not expose an unrestricted file proxy
that accepts arbitrary provider IDs. This SDK does not know your application's
file records or access policy. URL references are also application content;
HTTP(S) validation does not detect secrets in query strings or decide whether
a link is appropriate for a user.

## Reproduce the checks

```sh
dart test packages/agent_weave/test/references_test.dart
dart test packages/agent_weave_openai/test/output_references_test.dart
dart run examples/review_cases/openai_references.dart
dart run examples/review_cases/openai_chat_references.dart
dart run examples/review_cases/citations_client.dart
dart run tool/check.dart
```

Local checks exercise native SDK loopback calls, typed persistence, approvals,
PostgreSQL recreation, both clients and completed-log replay. No live OpenAI
request is needed. Live model acceptance, precise native highlighting, actual
file downloads and Flutter rendering remain unverified.


# Source: docs/computer-use.md

# OpenAI native computer use

Register `OpenAIComputerTool<C>` in `AiAgent.tools` alongside an unchanged
`OpenAIResponsesModel`. The application owns the computer, driver, permissions,
and screenshots; AgentWeave does not control an operating system or browser.
Use a model that supports the Responses computer tool. Running this example
makes paid model requests and sends actions to your driver.

## Complete CLI example

Run `dart pub get` in this workspace. A standalone application also needs
the `agent_weave_http` dependency for this driver example. Set `OPENAI_API_KEY`,
`OPENAI_COMPUTER_MODEL`, `COMPUTER_ENVIRONMENT_ID`, `COMPUTER_DRIVER_URL`, and
`COMPUTER_DRIVER_TOKEN`. The environment ID must identify the same stable
computer across the entire thread. `USER` identifies the trusted local CLI
operator. In a server, obtain `ownerId` from authenticated server-side identity,
never from the request body. Save this program as `examples/computer_demo.dart`:

```dart
import 'dart:convert';
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_http/agent_weave_http.dart';
import 'package:agent_weave_openai/agent_weave_openai.dart' as openai;

Future<void> main(List<String> args) async {
  String requiredEnv(String name) {
    final value = Platform.environment[name];
    if (value == null || value.trim().isEmpty) throw StateError('Set $name.');
    return value;
  }

  if (args.length != 1 || args.single.trim().isEmpty) {
    throw ArgumentError('Pass one quoted task as the argument.');
  }
  final apiKey = requiredEnv('OPENAI_API_KEY');
  final modelId = requiredEnv('OPENAI_COMPUTER_MODEL');
  final environmentId = requiredEnv('COMPUTER_ENVIRONMENT_ID');
  final driverUrl = Uri.parse(requiredEnv('COMPUTER_DRIVER_URL'));
  final driverToken = requiredEnv('COMPUTER_DRIVER_TOKEN');
  if (driverUrl.scheme != 'https' ||
      driverUrl.host.isEmpty ||
      driverUrl.userInfo.isNotEmpty ||
      driverUrl.hasFragment) {
    throw ArgumentError(
      'COMPUTER_DRIVER_URL must be an HTTPS URL without credentials or fragment.',
    );
  }
  // The CLI operator is the trusted identity, not a request-body field.
  final ownerId = requiredEnv('USER');
  final driver = JsonHttpClient(
    baseUrl: driverUrl.origin,
    requestTimeout: const Duration(seconds: 30),
  );
  final client = openai.OpenAIClient(
    config: openai.OpenAIConfig(
      authProvider: openai.ApiKeyProvider(apiKey),
      retryPolicy: const openai.RetryPolicy(maxRetries: 0),
    ),
  );
  try {
    final agent = AiAgent<void>(
      model: openai.OpenAIResponsesModel(client: client, model: modelId),
      tools: [
        openai.OpenAIComputerTool<void>(
          environmentId: environmentId,
          execute: (call, context) async {
            context.cancellation.throwIfCancelled();
            if (!context.approved) throw StateError('Approval required.');
            final response = await driver.sendJson(
              driverUrl.path.isEmpty ? '/' : driverUrl.path,
              query: driverUrl.queryParametersAll,
              cancellation: context.cancellation,
              prepare: () => JsonHttpRequest(
                headers: {'Authorization': 'Bearer $driverToken'},
                body: {
                  'environment_id': environmentId,
                  'idempotency_key': context.idempotencyKey,
                  'actions': [
                    for (final action in call.actions) action.toJson(),
                  ],
                },
              ),
            );
            context.cancellation.throwIfCancelled();
            if (response.statusCode != 200) {
              throw StateError(
                'Computer driver failed (${response.statusCode}).',
              );
            }
            final result = jsonDecode(response.body);
            if (result is! Map ||
                result['environment_id'] != environmentId ||
                result['image_url'] is! String ||
                (result['image_url'] as String).isEmpty) {
              throw const FormatException('Invalid computer driver response.');
            }
            return openai.OpenAIComputerScreenshot.url(
              result['image_url'] as String,
            );
          },
        ),
      ],
    );
    final id = DateTime.now().microsecondsSinceEpoch.toString();
    var result = await agent.generate(
      ChatRequest(
        threadId: 'computer-$id',
        runId: 'run-$id',
        messages: [ChatMessage.user(args.single, id: 'message-$id')],
      ),
      ownerId: ownerId,
      context: null,
    );
    var continuation = 0;
    while (result.status == RunStatus.interrupted) {
      final answers = <ResumeAnswer>[];
      for (final interrupt in result.interrupts) {
        stdout.writeln(
          'Proposed computer call: ${jsonEncode(interrupt.call.arguments)}',
        );
        stdout.write('Approve this entire call and its safety checks? [y/N] ');
        final approved = stdin.readLineSync()?.trim().toLowerCase() == 'y';
        answers.add(approved ? interrupt.approve() : interrupt.reject());
      }
      result = await agent.generate(
        ChatRequest(
          threadId: result.threadId,
          runId: 'run-$id-${++continuation}',
          parentRunId: result.runId,
          resume: answers,
        ),
        ownerId: ownerId,
        context: null,
      );
    }
    stdout.writeln(result.text);
  } on RunCancelled {
    stderr.writeln(
      'Computer run stopped. Inspect the environment before starting a new thread.',
    );
  } finally {
    driver.close();
    client.close();
  }
}
```

Run `dart run examples/computer_demo.dart "Your task"` only after setting up
and securing the driver. Every proposed batch is shown to the operator, who
must enter `y` to approve it and all its safety checks. Any other answer rejects
it. Keep the terminal and environment under the operator's control. The sample
uses an in-memory store and is intended for a single process; durable applications
need an appropriate `RunStore` and authenticated approval UI.

## Driver contract

`COMPUTER_DRIVER_URL` is your HTTPS endpoint, not an AgentWeave or OpenAI
endpoint. This example sends an authenticated JSON POST:

```json
{"environment_id":"desktop-1","idempotency_key":"stable-key","actions":[{"type":"click","button":"left","x":100,"y":200}]}
```

The driver must authorize the caller and environment, validate the entire batch,
revalidate the target and current screen before acting, execute the supplied
SDK action objects in order, and return one **fresh** screenshot after the
complete batch: `{"environment_id":"desktop-1","image_url":"https://..."}`.
It must deduplicate by the supplied idempotency key and preserve a durable record
of partial execution. A screenshot URL must be accessible to the model and
correspond to the configured screen coordinates. A driver must stop and report
failure on an invalid action, policy denial, execution failure, or screenshot
failure; it must not fabricate success. The driver client has a 30-second request timeout, observes cancellation, and
rejects redirects to avoid
forwarding its bearer token to another host. Secure the URL, token, images,
logs and environment, and restrict the environment's access and permissions.

`context.idempotencyKey` is stable across approval continuations and scoped to
owner, thread, and tool call. Deduplication belongs to your driver; neither that
key nor this example guarantees exactly-once external effects after a crash.
Neither the driver request nor model request is automatically retried here. A
cancelled or failed in-flight request may already have changed the computer;
inspect its state before taking further action. Cancellation is cooperative:
check `context.cancellation` before and after work and inside your driver where
possible.

## Approval and continuation

The default `ComputerApproval.always` requires approval for every call.
`ComputerApproval.safetyChecks` requires it when the provider supplies safety
checks. Any nonempty checks force human approval under either policy, including
unknown check codes. Approval covers the entire immutable call and all checks;
native arguments cannot be edited. `context.approved` tells the executor that
approval was granted. The application must enforce its own per-action policy and
verify the screen still matches the approved target.

Only validated calls from a terminal completed response are executable; streaming
deltas and incomplete or failed calls are not. Actions are immutable and must be
executed in their given order. Unknown action fields are rejected before the
executor runs. The runtime matches the screenshot output to the
exact provider `call_id` and retains opaque provider replay privately. Keep
stored continuation data private and use the authorized history interface for UI.

A rejection or cancellation stops locally and throws `RunCancelled`; the
continuation is closed with its audit history intact. Start a new thread after
reviewing the actual environment. Never invent a screenshot, result, or safety
acknowledgement to continue a denied call. Do not resume a pending call with a
different environment ID or stale screen: abandon it and start a new thread
with fresh state and approval. A completed model call means generation completed,
not that an action succeeded.

## Options and interoperability

The standard constructor sends the GA tool definition `{"type":"computer"}`.
For the legacy preview protocol, use `OpenAIComputerTool.preview` with positive
`width` and `height` and `environment` set to a `ComputerEnvironment` value:
`browser`, `mac`, `windows`, `linux`, or `ubuntu` (for example,
`openai.ComputerEnvironment.browser`). Both require a stable, nonempty `environmentId` and an application
executor. `OpenAIComputerCall.actions` uses the exported OpenAI SDK action
classes; inspect their types or serialize each action with `toJson()` as above.

Return `OpenAIComputerScreenshot.url(url)` or
`OpenAIComputerScreenshot.fileId(id)` with exactly one nonempty source. Both
accept `detail: openai.ImageDetail.original` when supported by the model.
Safety checks are acknowledged only after approval; support for nonempty
acknowledgements on the GA server is not guaranteed.

See OpenAI's [computer use guide](https://developers.openai.com/api/docs/guides/tools-computer-use)
and [driver integration](https://developers.openai.com/api/docs/guides/tools-computer-use-integration)
for provider requirements. Local fixtures and compilation do not verify a live
model, driver, remote actions, or billing.

## TanStack client approval UI

Native computer approvals use the generic interrupt API with the server's
read-only argument snapshot and response schema. Resolve an interrupt with
`{approved: true}` or `{approved: false}`. The native Dart agent API provides
`interrupt.approve()` and `interrupt.reject()`. Function-tool registration on
a JavaScript client uses a different approval schema that permits argument
edits; use the generic schema supplied by this native interrupt. Local tests
exercise both resolutions with the pinned official JavaScript client and
rehydrate its history without exposing private provider state.


# Source: docs/computer-parameters.md

# OpenAI computer protocol inventory

Generated from the pinned official Node SDK. This is a selected protocol inventory, not full computer or endpoint coverage.

- The pinned schema requires pending_safety_checks; the GA driver accepts its absence, while legacy action calls require it.
- Screenshot detail is a separately documented driver extension absent from this Node pin.
- Output ID, status and created_by are not integrated; native replay and runtime-owned fields are not public options.

## ComputerTool

| Field | Source type | Disposition |
| --- | --- | --- |
| type | `'computer'` | typed |

## ComputerUsePreviewTool

| Field | Source type | Disposition |
| --- | --- | --- |
| display_height | `number` | typed |
| display_width | `number` | typed |
| environment | `'windows' \| 'mac' \| 'linux' \| 'ubuntu' \| 'browser'` | typed |
| type | `'computer_use_preview'` | typed |

## ResponseComputerToolCall

| Field | Source type | Disposition |
| --- | --- | --- |
| id | `string` | private-replay |
| call_id | `string` | native-controlled |
| pending_safety_checks | `Array<ResponseComputerToolCall.PendingSafetyCheck>` | native-controlled |
| status | `'in_progress' \| 'completed' \| 'incomplete'` | native-controlled |
| type | `'computer_call'` | native-controlled |
| action? | `ResponseComputerToolCall.Click \| ResponseComputerToolCall.DoubleClick \| ResponseComputerToolCall.Drag \| ResponseComputerToolCall.Keypress \| ResponseComputerToolCall.Move \| ResponseComputerToolCall.Screenshot \| ResponseComputerToolCall.Scroll \| ResponseComputerToolCall.Type \| ResponseComputerToolCall.Wait` | typed |
| actions? | `ComputerActionList` | typed |

## ResponseComputerToolCall.PendingSafetyCheck

| Field | Source type | Disposition |
| --- | --- | --- |
| id | `string` | native-controlled |
| code? | `string \| null` | native-controlled |
| message? | `string \| null` | native-controlled |

## ResponseComputerToolCall.Click

| Field | Source type | Disposition |
| --- | --- | --- |
| button | `'left' \| 'right' \| 'wheel' \| 'back' \| 'forward'` | typed |
| type | `'click'` | typed |
| x | `number` | typed |
| y | `number` | typed |
| keys? | `Array<string> \| null` | typed |

## ResponseComputerToolCall.DoubleClick

| Field | Source type | Disposition |
| --- | --- | --- |
| keys | `Array<string> \| null` | typed |
| type | `'double_click'` | typed |
| x | `number` | typed |
| y | `number` | typed |

## ResponseComputerToolCall.Drag

| Field | Source type | Disposition |
| --- | --- | --- |
| path | `Array<Drag.Path>` | typed |
| type | `'drag'` | typed |
| keys? | `Array<string> \| null` | typed |

## ResponseComputerToolCall.Drag.Path

| Field | Source type | Disposition |
| --- | --- | --- |
| x | `number` | typed |
| y | `number` | typed |

## ResponseComputerToolCall.Keypress

| Field | Source type | Disposition |
| --- | --- | --- |
| keys | `Array<string>` | typed |
| type | `'keypress'` | typed |

## ResponseComputerToolCall.Move

| Field | Source type | Disposition |
| --- | --- | --- |
| type | `'move'` | typed |
| x | `number` | typed |
| y | `number` | typed |
| keys? | `Array<string> \| null` | typed |

## ResponseComputerToolCall.Screenshot

| Field | Source type | Disposition |
| --- | --- | --- |
| type | `'screenshot'` | typed |

## ResponseComputerToolCall.Scroll

| Field | Source type | Disposition |
| --- | --- | --- |
| scroll_x | `number` | typed |
| scroll_y | `number` | typed |
| type | `'scroll'` | typed |
| x | `number` | typed |
| y | `number` | typed |
| keys? | `Array<string> \| null` | typed |

## ResponseComputerToolCall.Type

| Field | Source type | Disposition |
| --- | --- | --- |
| text | `string` | typed |
| type | `'type'` | typed |

## ResponseComputerToolCall.Wait

| Field | Source type | Disposition |
| --- | --- | --- |
| type | `'wait'` | typed |

## ResponseComputerToolCallOutputItem

| Field | Source type | Disposition |
| --- | --- | --- |
| id | `string` | not-integrated |
| call_id | `string` | native-controlled |
| output | `ResponseComputerToolCallOutputScreenshot` | typed |
| status | `'completed' \| 'incomplete' \| 'failed' \| 'in_progress'` | not-integrated |
| type | `'computer_call_output'` | native-controlled |
| acknowledged_safety_checks? | `Array<ResponseComputerToolCallOutputItem.AcknowledgedSafetyCheck>` | native-controlled |
| created_by? | `string` | not-integrated |

## ResponseComputerToolCallOutputItem.AcknowledgedSafetyCheck

| Field | Source type | Disposition |
| --- | --- | --- |
| id | `string` | native-controlled |
| code? | `string \| null` | native-controlled |
| message? | `string \| null` | native-controlled |

## ResponseComputerToolCallOutputScreenshot

| Field | Source type | Disposition |
| --- | --- | --- |
| type | `'computer_screenshot'` | typed |
| file_id? | `string` | typed |
| image_url? | `string` | typed |


# Source: docs/openai.md

# OpenAI integration

`agent_weave_openai` uses `openai_dart 11.0.1` for provider transport.
Responses uses native JSON/SSE to preserve fields before typed decoding.
AgentWeave implements orchestration and protocol adaptation around that SDK.

| Capability | Entry point |
| --- | --- |
| Responses chat and selected hosted tools | `OpenAIResponsesModel`, including `.native` options |
| Chat Completions | `OpenAIChatModel` |
| Images | `OpenAIImageModel`, `imageTask`, or `client.images` |
| Speech | `OpenAISpeechModel`, `speechTask`, or `client.audio.speech` |
| Transcription | `OpenAITranscriptionModel`, `transcriptionTask`, or `client.audio.transcriptions` |
| Decisions | `OpenAIDecisionModel` or `client.decisions` |
| Embeddings | `OpenAIEmbeddingModel` or `client.embeddings` |
| Video jobs | `OpenAIVideoModel` or `client.videos` |
| Realtime | `OpenAIRealtimeModel`, `client.realtime`, or `client.realtimeSessions` |
| Supporting resources | Typed provider client resources |
| Additional JSON operations | `OpenAIPlatformApi` |

See [hosted tools](openai-hosted.md) for search, code, server tool-search and
completed image output, with explicit lifecycle limits.

Use `configure` on chat adapters to set typed provider-specific options. Model
capabilities describe the adapter's request formats; selecting an incompatible
provider model can still produce a provider error.

The provider SDK also exposes conversations, files, uploads, batches, models,
moderation, fine-tuning, evals, containers, vector stores, skills, ChatKit,
webhooks, safety resources, Live sessions, saved agents, and Vaults. These are
delegated APIs, not independently implemented AgentWeave features.

`OpenAIPlatformApi` supports additional JSON requests and binary downloads,
including administration operations with an appropriate credential. It is an
explicit raw escape hatch. It does not imply typed or tested parity for every
OpenAI endpoint. Mutation requests through this helper are not automatically
retried.

The [operation inventory](openai-api-inventory.json) records the official
reference index for update reviews. Each entry is a discovery/review item, not
a passing endpoint test. See [validation](validation.md) for what was exercised.

## Custom text tools

Register `OpenAICustomTool<C>` for direct Responses calls with raw text input,
optional regex/Lark grammar, namespaced provider identities and application-owned
execution. Approval and denial use native output correlation and private replay.
See [custom tools](openai-custom-tools.md). Asynchronous/programmatic execution
and namespaced functions are not integrated.

## Media and realtime

`imageTask`, `speechTask`, and `transcriptionTask` emit normalized TanStack
generation results. Direct model wrappers retain provider-specific types.

Non-streaming image requests cannot abort in-flight through the underlying
SDK. Use its streaming operation when an abortable transport is required.
Cancelling a video wait does not cancel a provider job or its charges.
Close realtime connections explicitly when the session ends. The realtime
wrapper provides SDK connection access; AgentWeave does not yet orchestrate
voice turns, realtime tools, or device audio.

Use separate prefixed imports for realtime event classes:

```dart
import 'package:agent_weave_openai/agent_weave_openai.dart' as openai;
import 'package:agent_weave_openai/realtime.dart' as realtime;
```

The deprecated Assistants API has a separate `assistants.dart` import.
Provider/model deprecations remain OpenAI's schedule. In particular, the Speech
API models are scheduled to shut down on January 6, 2027; new voice integrations
should evaluate the Realtime API. Check the
[official speech guide](https://developers.openai.com/api/docs/guides/text-to-speech)
before choosing a model.

## Request-specific transport access

Use typed SDK resources first. For additional operations, `OpenAIPlatformApi`
provides `request` for JSON objects, `requestJson` for any JSON root, `send`
for response status/headers/bytes, and `download` for bytes. These methods accept
request-specific headers and repeated query values. Authentication and transport
headers remain client-owned. Mutations are not automatically retried.

```dart
final platform = openai.OpenAIPlatformApi(client);
final response = await platform.send(
  '/responses/your-response-id',
  repeatedQuery: {'include[]': ['reasoning.encrypted_content']},
  headers: {'Accept': 'application/json'},
);
print(response.headers['x-request-id']);
```

The raw helper buffers responses; it does not add arbitrary SSE or multipart
handling. It preserves data but does not implement missing tool/job lifecycles.


## Native output references

Responses normalizes four annotation forms with native positions and enclosing
text segments. Completed Chat URL annotations use `streamText: false` because
the installed typed decoder omits them. See [output references](output-references.md)
for mode selection, privacy, persistence and remaining limits.


# Source: docs/openai-hosted.md

# OpenAI hosted tools

Configure provider-executed tools on `OpenAIResponsesModel`, separately from
the application's `AiAgent.tools`. OpenAI executes hosted searches, code and
image generation. AgentWeave executes only registered application tools, after
the complete response has been validated and any approval has been resolved.

## Search from Dart

This example runs on a backend. Select an OpenAI model that supports the
configured tool and set `OPENAI_API_KEY` and `OPENAI_MODEL`. Running it makes a
billable provider request. The repository checks compile it without making that
request.

```dart
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_openai/agent_weave_openai.dart' as openai;

Future<void> main() async {
  final key = Platform.environment['OPENAI_API_KEY'];
  final modelId = Platform.environment['OPENAI_MODEL'];
  if (key == null || key.isEmpty || modelId == null || modelId.isEmpty) {
    throw StateError('Set OPENAI_API_KEY and OPENAI_MODEL.');
  }
  final client = openai.OpenAIClient.withApiKey(key);
  try {
    final result = await generateText(
      model: openai.OpenAIResponsesModel.native(
        authorityBindingId: 'example-authority',
        client: client,
        model: modelId,
        hostedTools: [
          openai.OpenAIHostedTool.fromJson({
            'type': 'web_search',
            'user_location': {
              'type': 'approximate',
              'city': 'Cairo',
              'country': 'EG',
            },
          }),
        ],
        toolChoice: 'auto',
      ),
      prompt: 'Find the latest stable Dart release.',
      maxOutputTokens: 1024,
    );
    print(result.text);
  } finally {
    client.close();
  }
}
```

The same source is in
[`examples/openai_hosted_demo.dart`](https://github.com/seifalmotaz/agent-weave/blob/main/examples/openai_hosted_demo.dart).
For Serverpod, pass this model to the agent behind your authenticated endpoint
and use `ServerpodRunStore` for durable history. Keep the provider client alive
for the application lifetime, then close it on shutdown.

## Definitions and native options

`OpenAIHostedTool` accepts an SDK `ResponseTool`.
`OpenAIHostedTool.fromJson` accepts an immutable snapshot of native JSON.
Use the latter when the installed SDK cannot represent a field accurately.
The adapter currently recognizes these hosted tool families:

| Tool | Integrated behavior |
| --- | --- |
| `web_search` and the pinned preview variants | Retain ordered native calls and search metadata for private continuation |
| `file_search` | Require vector-store IDs; retain private queries and results |
| `code_interpreter` | Require a container ID or auto configuration; retain private code, container IDs and outputs |
| `image_generation` | Retain native output and expose completed image bytes as an `ImagePart` data URL |
| `tool_search` with `execution: server` | Retain server search calls and loaded definitions; ordinary executors must still be registered by the application |

One definition per family is allowed. Hosted tools do not add local executors.
Client tool search, shell and patch lifecycles are not
integrated and fail explicitly. Computer use has its own
[application-controlled contract](computer-use.md).

`OpenAIResponsesModel.native` keeps SDK authentication, client ownership and
cancellation while using native JSON/SSE for Responses. Declare a stable,
nonsecret `authorityBindingId` for the provider account and endpoint. Change it
when that authority changes. It cannot be inferred from rotating API keys.

For managed tools, supply immutable `options` for additional native request
fields and `toolChoice` for tool selection. These values are copied at
construction and included in the private continuation contract. Both typed and
native constructors reject `configure` callbacks when managed tools are present.
History, model, tools, output schema and execution bounds remain runtime-owned.
Native extensions are preserved; acceptance by a live model is not guaranteed.

For ordinary models without managed tools, the existing typed and native
`configure` callbacks remain available. The typed view patches changes onto
original JSON, retaining unchanged unknown fields. These callbacks cannot add
managed tools or replace the model or tool choice. Use immutable `options` for
configuration that must stay stable across resumed approvals. Callback validation
runs during the next model invocation and can fail after a local tool has run;
it is not a preflight guarantee for arbitrary application code.

For registered local functions used alongside managed tools, declare native
function settings through `functionToolOptions`, keyed by the registered name:

```dart
functionToolOptions: {
  'lookupCustomer': {'strict': true, 'defer_loading': false},
},
```

This map is frozen and included in the profile. Supported settings retain the
existing function handler's limits: `strict`, `defer_loading`, `async: false`
and direct `allowed_callers`. Asynchronous or programmatic function execution
still requires a separate handler. A name must identify a registered function;
the map cannot replace its schema, description or executor.

With `openai_dart 11.0.1`, image-generation masks,
moderation and compression have incorrect SDK types; native JSON accepts an
object mask, `auto` or `low` moderation, and integer compression from 0 to 100.
The type correction was merged on 2026-11-04 in [upstream PR #436](https://github.com/davidmigloz/ai_clients_dart/pull/436);
the fix is not in the published 11.0.1 release. This workspace keeps that released
SDK pin.

Function tools may use strict schemas and deferred loading. Their names and
schemas must still match registered executors. Asynchronous and programmatic
function continuations need a separate handler and are rejected. Background
Responses, `previous_response_id` and provider-owned conversations are also
outside the agent's stateless full-history replay contract; use SDK resource
APIs separately for those workflows.

## Output, storage and privacy

Completed image results become `ImagePart` data URLs in assistant history.
Their position among text parts is retained in native Dart results, sanitized
client snapshots and hydration. Image-only responses work too. The inline bytes
are persisted with the conversation, so application storage and response-size
limits must account for them. AgentWeave does not host or optimize artifacts.

Raw ordered Responses output is stored under `openai.responses`. Top-level
response metadata is retained under `openai.responses.metadata`. Both are
server-side `providerData`, excluded from public history and events. Unknown
fields on recognized output items survive replay. Never expose raw checkpoints
as a client history endpoint.

Reviewed annotations produce public typed references, including scoped file
handles. Code outputs, unselected metadata and opaque native fields stay private.
Applications render source cards and authorize file retrieval. Precise native
highlights, partial image progress, hosted-tool progress and container downloads
remain outside this adapter's normalization contract.

## Verification and scope

The [generated field inventory](openai-hosted-parameters.md) records selected
official Node SDK declarations and an executable Dart request fixture. Its
upstream check detects changes to the selected declarations. It does not
certify all nested constraints or the whole OpenAI API.

Offline cases verify request preservation, mixed hosted/application tools,
approval and recreation, terminal validation, cancellation, media ordering,
private replay, native Dart and official JavaScript clients, and PostgreSQL
history. No live hosted search, container, tool-search or Responses-image
request was made for this increment. The earlier standalone Images API smoke
test is a separate workflow. See [validation](validation.md).


## Output references

Completed Responses annotations now produce typed sources and native positions.
See [output references](output-references.md) for all four forms, persistence,
file authorization and the distinction between native indexes and UTF-16 text.
Partial images, hosted progress and artifact hosting remain open.


## MCP approvals

Remote MCP uses a separate provider-owned approval lifecycle. See [MCP approvals](openai-mcp.md) for configuration, owner-bound credentials, generic client interrupts, denial and indeterminate continuations.

Application-owned [custom text tools](openai-custom-tools.md) use a separate
registered native lifecycle. They are not hosted definitions. Deferred custom
tools can be used with configured server tool search; only registered identities
can execute locally. Asynchronous/programmatic custom execution remains open.


# Source: docs/openai-custom-tools.md

# OpenAI Responses custom text tools

Use `OpenAICustomTool<C>` when a Responses model should send a text string to an application-owned tool. Your backend supplies the executor, validates its input and controls approval. Custom tools are separate from OpenAI hosted tools and JSON-schema function tools.

## Interactive example

Set `OPENAI_API_KEY` and `OPENAI_CUSTOM_TOOL_MODEL` to a model that supports custom tools, then run `dart run examples/openai_custom_demo.dart`. This makes billable requests. The example reads from a small in-memory ticket table, uses no shell or code evaluator, and asks for a decision before each proposed lookup. It limits the number of approval rounds; a run that reaches the limit stays interrupted.

```dart
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_openai/agent_weave_openai.dart' as openai;

Future<void> main() async {
  final key = Platform.environment['OPENAI_API_KEY'];
  final model = Platform.environment['OPENAI_CUSTOM_TOOL_MODEL'];
  if (key == null || key.isEmpty || model == null || model.isEmpty) {
    throw StateError('Set OPENAI_API_KEY and OPENAI_CUSTOM_TOOL_MODEL.');
  }
  final client = openai.OpenAIClient.fromEnvironment();
  try {
    final agent = AiAgent<void>(
      model: openai.OpenAIResponsesModel.native(client: client, model: model),
      tools: [
        openai.OpenAICustomTool<void>(
          name: 'lookup_ticket',
          bindingId: 'local-ticket-lookup-v1',
          description: 'Look up the status of a ticket',
          needsApproval: true,
          format: openai.OpenAICustomToolFormat.grammar(
            r'TICKET-[0-9]+',
            syntax: openai.OpenAICustomGrammarSyntax.regex,
          ),
          execute: (input, context) {
            // Validate model text locally; provider grammar is not authorization.
            if (!RegExp(r'^TICKET-[0-9]+$').hasMatch(input)) {
              return openai.OpenAICustomToolResult.error('Invalid ticket ID.');
            }
            const tickets = {'TICKET-42': 'open'};
            return openai.OpenAICustomToolResult.text(
              tickets[input] ?? 'Ticket not found.',
            );
          },
        ),
      ],
    );
    var request = ChatRequest(
      threadId: 'ticket-demo',
      runId: 'question',
      messages: [ChatMessage.user('Look up TICKET-42.', id: 'user')],
    );
    for (var round = 0; round < 4; round++) {
      AgentResult? finished;
      await for (final update in agent.stream(
        request,
        ownerId: 'local-demo',
        context: null,
      )) {
        if (update case AgentTextDelta(:final text)) stdout.write(text);
        if (update case AgentRunFinished(:final result)) finished = result;
      }
      final result = finished!;
      if (result.status != RunStatus.interrupted) {
        stdout.writeln();
        break;
      }
      if (round == 3) {
        stderr.writeln(
          'Approval round limit reached; the run remains interrupted.',
        );
        break;
      }
      final answers = <ResumeAnswer>[];
      for (final interrupt in result.interrupts) {
        stdout.writeln(
          '\n${interrupt.call.name}: ${interrupt.call.arguments['input']}',
        );
        stdout.write('Approve this lookup? Type yes, otherwise deny: ');
        answers.add(
          stdin.readLineSync() == 'yes'
              ? interrupt.approve()
              : interrupt.reject(),
        );
      }
      request = ChatRequest(
        threadId: result.threadId,
        runId: 'decision-$round',
        parentRunId: result.runId,
        resume: answers,
      );
    }
  } on AgentRunException catch (error) {
    stderr.writeln('${error.code}: ${error.message}');
    exitCode = 1;
  } on RunCancelled {
    stderr.writeln('Run cancelled.');
    exitCode = 1;
  } finally {
    client.close();
  }
}
```

The [offline consumer](https://github.com/seifalmotaz/agent-weave/blob/main/examples/review_cases/openai_custom.dart) runs without a key or network: `dart --enable-asserts run examples/review_cases/openai_custom.dart`. It exercises approval, denial, application validation, private replay and native output with a MockClient. It does not prove live provider acceptance.

## Input and authorization

`OpenAICustomToolFormat.text()` requests unconstrained text. `OpenAICustomToolFormat.grammar` accepts a `regex` or `lark` syntax and native grammar definition. The grammar is sent to the provider as a generation constraint; AgentWeave does not execute the grammar locally. Validate the returned string in your executor before doing work, even if the provider applied a grammar. Use the authenticated `ToolContext` to check the owner's access and pass its idempotency key to an external service that supports one.

The native proposal is represented to the application as a `NativeToolCall` whose arguments contain only `{'input': text}`. Raw provider items and caller fields stay in backend provider replay, not in public call arguments or `chatHydration`. Treat all tool inputs and results as application data, and do not return private `AgentResult` provider state directly to a UI. `needsApproval: true` pauses before invoking the executor; validate the entire decision batch and obtain the person's decision before resuming. Editing custom-tool arguments in an approval is unsupported.

## Results and failure

`OpenAICustomToolResult.text(value)` returns a string. `error(message)` represents an expected failure with an explicit message that the model may see; avoid including secrets. `content([...])` supports native `input_text`, `input_image`, and `input_file` blocks through `OpenAICustomToolContent`:

- `text(text, cache: ...)` includes text.
- `image(detail: ..., imageUrl: ..., fileId: ..., cache: ...)` carries image detail and a URL or file handle. Detail accepts `auto`, `low`, `high` or `original`.
- `file(detail: ..., fileData: ..., fileId: ..., fileUrl: ..., filename: ..., cache: ...)` carries file data, a handle or URL, optional filename and detail (`auto`, `low` or `high`).
- `OpenAICustomPromptCacheBreakpoint(ttl: ...)` sets an explicit cache breakpoint; the optional TTL is `30m` or `12h`.

Each result factory also accepts an optional application-owned `id` and direct `caller` JSON metadata. These values are validated and snapshotted; no provider ID is invented. `fromJson` preserves an explicitly null caller. The adapter sends the returned output as `custom_tool_call_output` with the matching native call ID. The runtime owns `type` and `call_id`; result metadata cannot replace them. `isError` marks the application/runtime result; the native output item contains the output text or content, so phrase an expected error meaningfully for the model. Authorize file handles and URLs in your application; typed content does not grant retrieval permission or validate a remote resource's trustworthiness.

Rejecting or cancelling a **custom-tool approval** produces a safe declined/cancelled output and can continue the native conversation without executing that tool. A returned `OpenAICustomToolResult.error` likewise provides a known error result. An unexpected thrown executor error closes the unfinished native continuation; verify any external effects and start a new conversation rather than automatically rerunning it. A declined or cancelled computer-tool approval still closes the native continuation, including a mixed batch; custom-tool fallback does not change computer-tool semantics. Cancellation of a whole run also does not undo an effect.

## Namespaces, binding and scope

For a native namespace, pass `namespace: OpenAIToolNamespace(name: ..., description: ...)`. When two namespaces use the same native tool name, assign distinct `localName` values so the application's registered tools have unique names. The model uses the native namespace/name while the runtime dispatches the local alias. A stable `bindingId` identifies the executor and its authority; change it when its behavior or authorization scope changes.

Automatic selection supports registered custom tools in namespaces. A forced custom selector accepts exactly `{'type': 'custom', 'name': ...}` and selects a registered top-level custom tool. Forced namespace selection is unsupported. With the pinned `openai_dart` 11.0.1, use `OpenAIResponsesModel.native` or `ResponsesProtocolModel.native` for this selector: the SDK's typed `ResponseToolChoice` union cannot represent `custom`, so the typed transport rejects it during registration. The native transport preserves the selector without changing SDK decoding.

[Upstream PR #451](https://github.com/davidmigloz/ai_clients_dart/pull/451) adds the missing typed selector. It is separate from the workspace's published SDK dependency. Recheck the upstream release and rerun the contract checks before updating that pin.

The runtime binds the complete registered tool profile and model continuation configuration across unfinished turns, before approving or invoking any tool. Recreate an agent with the same profile when resuming. Changed profiles fail before effects. Older unfinished checkpoints without the required contract cannot be reconstructed safely; start a new conversation while retaining completed history. See [approval contracts](approval-contracts.md).

This integration supports direct custom calls. Asynchronous and programmatic custom execution are rejected; unsupported provider features do not become available merely because the underlying SDK has a type. Custom tools and [computer tools](computer-use.md) have distinct continuation contracts. See the [official OpenAI guide](https://developers.openai.com/api/docs/guides/function-calling) for the provider format. Offline fixtures do not prove live model support, grammar acceptance, real external effects, or PostgreSQL restart behavior.


# Source: docs/openai-custom-parameters.md

# OpenAI custom tool contract

Generated from the [pinned inventory](openai-custom-inventory.json). See the [official guide](https://developers.openai.com/api/docs/guides/function-calling).

Selected custom-tool declarations, four shallow union signatures and output-item event envelopes only; this is not full Responses union coverage or live workflow certification. Direct synchronous custom calls, text and grammar formats, custom-only namespaces and typed string/content results are implemented; namespaced function tools, asynchronous and programmatic calls are not integrated. Grammar syntax is provider-enforced; application callbacks validate their own input.

## responses.CustomTool

| Field | Type |
| --- | --- |
| name | `string` |
| type | `'custom'` |
| allowed_callers? | `Array<'direct' \| 'programmatic'> \| null` |
| async? | `boolean` |
| defer_loading? | `boolean` |
| description? | `string` |
| format? | `Shared.CustomToolInputFormat` |

## responses.ImageDetail

```ts
'low' | 'high' | 'auto' | 'original'
```

## responses.NamespaceTool

| Field | Type |
| --- | --- |
| description | `string` |
| name | `string` |
| tools | `Array<NamespaceTool.Function \| CustomTool>` |
| type | `'namespace'` |

## responses.NamespaceTool.Function

| Field | Type |
| --- | --- |
| name | `string` |
| type | `'function'` |
| allowed_callers? | `Array<'direct' \| 'programmatic'> \| null` |
| async? | `boolean` |
| defer_loading? | `boolean` |
| description? | `string \| null` |
| output_schema? | `{ [key: string]: unknown; } \| null` |
| parameters? | `unknown \| null` |
| strict? | `boolean \| null` |

## responses.ResponseCustomToolCall

| Field | Type |
| --- | --- |
| call_id | `string` |
| input | `string` |
| name | `string` |
| type | `'custom_tool_call'` |
| id? | `string` |
| async? | `boolean` |
| caller? | `ResponseCustomToolCall.Direct \| ResponseCustomToolCall.Program \| null` |
| namespace? | `string` |

## responses.ResponseCustomToolCall.Direct

| Field | Type |
| --- | --- |
| type | `'direct'` |

## responses.ResponseCustomToolCall.Program

| Field | Type |
| --- | --- |
| caller_id | `string` |
| type | `'program'` |

## responses.ResponseCustomToolCallInputDeltaEvent

| Field | Type |
| --- | --- |
| delta | `string` |
| item_id | `string` |
| output_index | `number` |
| sequence_number | `number` |
| type | `'response.custom_tool_call_input.delta'` |

## responses.ResponseCustomToolCallInputDoneEvent

| Field | Type |
| --- | --- |
| input | `string` |
| item_id | `string` |
| output_index | `number` |
| sequence_number | `number` |
| type | `'response.custom_tool_call_input.done'` |

## responses.ResponseCustomToolCallItem

| Field | Type |
| --- | --- |
| id | `string` |
| status | `'in_progress' \| 'completed' \| 'incomplete'` |
| created_by? | `string` |

## responses.ResponseCustomToolCallOutput

| Field | Type |
| --- | --- |
| call_id | `string` |
| output | `string \| Array<ResponseInputText \| ResponseInputImage \| ResponseInputFile>` |
| type | `'custom_tool_call_output'` |
| id? | `string` |
| caller? | `ResponseCustomToolCallOutput.Direct \| ResponseCustomToolCallOutput.Program \| null` |

## responses.ResponseCustomToolCallOutput.Direct

| Field | Type |
| --- | --- |
| type | `'direct'` |

## responses.ResponseCustomToolCallOutput.Program

| Field | Type |
| --- | --- |
| caller_id | `string` |
| type | `'program'` |

## responses.ResponseCustomToolCallOutputItem

| Field | Type |
| --- | --- |
| id | `string` |
| status | `'in_progress' \| 'completed' \| 'incomplete'` |
| created_by? | `string` |

## responses.ResponseInputFile

| Field | Type |
| --- | --- |
| type | `'input_file'` |
| detail? | `'auto' \| 'low' \| 'high'` |
| file_data? | `string` |
| file_id? | `string \| null` |
| file_url? | `string` |
| filename? | `string` |
| prompt_cache_breakpoint? | `ResponseInputFile.PromptCacheBreakpoint` |

## responses.ResponseInputFile.PromptCacheBreakpoint

| Field | Type |
| --- | --- |
| mode | `'explicit'` |
| ttl? | `'30m' \| '12h'` |

## responses.ResponseInputImage

| Field | Type |
| --- | --- |
| detail | `ImageDetail` |
| type | `'input_image'` |
| file_id? | `string \| null` |
| image_url? | `string \| null` |
| prompt_cache_breakpoint? | `ResponseInputImage.PromptCacheBreakpoint` |

## responses.ResponseInputImage.PromptCacheBreakpoint

| Field | Type |
| --- | --- |
| mode | `'explicit'` |
| ttl? | `'30m' \| '12h'` |

## responses.ResponseInputText

| Field | Type |
| --- | --- |
| text | `string` |
| type | `'input_text'` |
| prompt_cache_breakpoint? | `ResponseInputText.PromptCacheBreakpoint` |

## responses.ResponseInputText.PromptCacheBreakpoint

| Field | Type |
| --- | --- |
| mode | `'explicit'` |
| ttl? | `'30m' \| '12h'` |

## responses.ResponseOutputItemAddedEvent

| Field | Type |
| --- | --- |
| item | `ResponseOutputItem` |
| output_index | `number` |
| sequence_number | `number` |
| type | `'response.output_item.added'` |

## responses.ResponseOutputItemDoneEvent

| Field | Type |
| --- | --- |
| item | `ResponseOutputItem` |
| output_index | `number` |
| sequence_number | `number` |
| type | `'response.output_item.done'` |

## responses.ToolChoiceAllowed

| Field | Type |
| --- | --- |
| mode | `'auto' \| 'required'` |
| tools | `Array<{ [key: string]: unknown; }>` |
| type | `'allowed_tools'` |

## responses.ToolChoiceCustom

| Field | Type |
| --- | --- |
| name | `string` |
| type | `'custom'` |

## responses.Tool

Shallow union signature; variants are not all integrated.

```ts
FunctionTool
  | FileSearchTool
  | ComputerTool
  | ComputerUsePreviewTool
  | WebSearchTool
  | Tool.Mcp
  | Tool.CodeInterpreter
  | Tool.ProgrammaticToolCalling
  | Tool.ImageGeneration
  | Tool.LocalShell
  | FunctionShellTool
  | CustomTool
  | NamespaceTool
  | ToolSearchTool
  | WebSearchPreviewTool
  | ApplyPatchTool
```

## responses.ResponseInputItem

Shallow union signature; variants are not all integrated.

```ts
EasyInputMessage
  | ResponseInputItem.Message
  | ResponseOutputMessage
  | ResponseFileSearchToolCall
  | ResponseComputerToolCall
  | ResponseInputItem.ComputerCallOutput
  | ResponseFunctionWebSearch
  | ResponseFunctionToolCall
  | ResponseInputItem.FunctionCallOutput
  | ResponseInputItem.ToolSearchCall
  | ResponseToolSearchOutputItemParam
  | ResponseInputItem.AdditionalTools
  | ResponseConfigurationUpdateItemParam
  | ResponseReasoningItem
  | ResponseCompactionItemParam
  | ResponseInputItem.ImageGenerationCall
  | ResponseCodeInterpreterToolCall
  | ResponseInputItem.LocalShellCall
  | ResponseInputItem.LocalShellCallOutput
  | ResponseInputItem.ShellCall
  | ResponseInputItem.ShellCallOutput
  | ResponseInputItem.ApplyPatchCall
  | ResponseInputItem.ApplyPatchCallOutput
  | ResponseInputItem.McpListTools
  | ResponseInputItem.McpApprovalRequest
  | ResponseInputItem.McpApprovalResponse
  | ResponseInputItem.McpCall
  | ResponseCustomToolCallOutput
  | ResponseCustomToolCall
  | ResponseInputItem.CompactionTrigger
  | ResponseInputItem.ItemReference
  | ResponseInputItem.Program
  | ResponseInputItem.ProgramOutput
```

## responses.ResponseOutputItem

Shallow union signature; variants are not all integrated.

```ts
ResponseOutputMessage
  | ResponseFileSearchToolCall
  | ResponseFunctionToolCall
  | ResponseFunctionToolCallOutputItem
  | ResponseFunctionWebSearch
  | ResponseComputerToolCall
  | ResponseComputerToolCallOutputItem
  | ResponseReasoningItem
  | ResponseOutputItem.Program
  | ResponseOutputItem.ProgramOutput
  | ResponseToolSearchCall
  | ResponseToolSearchOutputItem
  | ResponseOutputItem.AdditionalTools
  | ResponseCompactionItem
  | ResponseOutputItem.ImageGenerationCall
  | ResponseCodeInterpreterToolCall
  | ResponseOutputItem.LocalShellCall
  | ResponseOutputItem.LocalShellCallOutput
  | ResponseFunctionShellToolCall
  | ResponseFunctionShellToolCallOutput
  | ResponseApplyPatchToolCall
  | ResponseApplyPatchToolCallOutput
  | ResponseOutputItem.McpCall
  | ResponseOutputItem.McpListTools
  | ResponseOutputItem.McpApprovalRequest
  | ResponseOutputItem.McpApprovalResponse
  | ResponseCustomToolCall
  | ResponseCustomToolCallOutputItem
```

## responses.ResponseStreamEvent

Shallow union signature; variants are not all integrated.

```ts
ResponseAudioDeltaEvent
  | ResponseAudioDoneEvent
  | ResponseAudioTranscriptDeltaEvent
  | ResponseAudioTranscriptDoneEvent
  | ResponseCodeInterpreterCallCodeDeltaEvent
  | ResponseCodeInterpreterCallCodeDoneEvent
  | ResponseCodeInterpreterCallCompletedEvent
  | ResponseCodeInterpreterCallInProgressEvent
  | ResponseCodeInterpreterCallInterpretingEvent
  | ResponseCompactionCompactingEvent
  | ResponseCompletedEvent
  | ResponseContentPartAddedEvent
  | ResponseContentPartDoneEvent
  | ResponseCreatedEvent
  | ResponseErrorEvent
  | ResponseFileSearchCallCompletedEvent
  | ResponseFileSearchCallInProgressEvent
  | ResponseFileSearchCallSearchingEvent
  | ResponseFunctionCallArgumentsDeltaEvent
  | ResponseFunctionCallArgumentsDoneEvent
  | ResponseShellCallCommandAddedEvent
  | ResponseShellCallCommandDeltaEvent
  | ResponseShellCallCommandDoneEvent
  | ResponseShellCallOutputContentDeltaEvent
  | ResponseShellCallOutputContentDoneEvent
  | ResponseInProgressEvent
  | ResponseFailedEvent
  | ResponseIncompleteEvent
  | ResponseOutputItemAddedEvent
  | ResponseOutputItemDoneEvent
  | ResponseReasoningSummaryPartAddedEvent
  | ResponseReasoningSummaryPartDoneEvent
  | ResponseReasoningSummaryTextDeltaEvent
  | ResponseReasoningSummaryTextDoneEvent
  | ResponseReasoningTextDeltaEvent
  | ResponseReasoningTextDoneEvent
  | ResponseRefusalDeltaEvent
  | ResponseRefusalDoneEvent
  | ResponseTextDeltaEvent
  | ResponseTextDoneEvent
  | ResponseWebSearchCallCompletedEvent
  | ResponseWebSearchCallInProgressEvent
  | ResponseWebSearchCallSearchingEvent
  | ResponseImageGenCallCompletedEvent
  | ResponseImageGenCallGeneratingEvent
  | ResponseImageGenCallInProgressEvent
  | ResponseImageGenCallPartialImageEvent
  | ResponseMcpCallArgumentsDeltaEvent
  | ResponseMcpCallArgumentsDoneEvent
  | ResponseMcpCallCompletedEvent
  | ResponseMcpCallFailedEvent
  | ResponseMcpCallInProgressEvent
  | ResponseMcpListToolsCompletedEvent
  | ResponseMcpListToolsFailedEvent
  | ResponseMcpListToolsInProgressEvent
  | ResponseOutputTextAnnotationAddedEvent
  | ResponseQueuedEvent
  | ResponseCustomToolCallInputDeltaEvent
  | ResponseCustomToolCallInputDoneEvent
```

## shared.CustomToolInputFormat

```ts
CustomToolInputFormat.Text | CustomToolInputFormat.Grammar
```

## shared.CustomToolInputFormat.Text

| Field | Type |
| --- | --- |
| type | `'text'` |

## shared.CustomToolInputFormat.Grammar

| Field | Type |
| --- | --- |
| definition | `string` |
| syntax | `'lark' \| 'regex'` |
| type | `'grammar'` |


# Source: docs/openai-mcp.md

# Approve remote MCP tools

Use `OpenAIResponsesModel` with `mcpTools` for provider-executed MCP calls.
The runtime pauses on a returned approval request. Approval and denial both
continue the provider conversation; neither invokes a local `AgentTool`.

## Run the interactive example

Set `OPENAI_API_KEY` and optionally `OPENAI_MODEL`, then run
`dart run examples/openai_mcp_demo.dart`. This makes billable requests and
contacts the configured MCP server. Repository checks compile this example;
they do not run it. Each proposed tool call requires your CLI decision.
The example uses in-process memory and bounds the number of approval rounds.

```dart
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_openai/agent_weave_openai.dart' as openai;

Future<void> main() async {
  final client = openai.OpenAIClient.fromEnvironment();
  try {
    final agent = AiAgent<void>(
      model: openai.OpenAIResponsesModel.native(
        authorityBindingId: 'example-authority',
        client: client,
        model: Platform.environment['OPENAI_MODEL'] ?? 'gpt-5.4-nano',
        mcpTools: [
          openai.OpenAIMcpTool.fromJson({
            'type': 'mcp',
            'server_label': 'openai_docs',
            'server_url': 'https://developers.openai.com/mcp',
            'require_approval': 'always',
          }),
        ],
      ),
    );
    var result = await agent.generate(
      ChatRequest(
        threadId: 'docs',
        runId: 'question',
        messages: [
          ChatMessage.user(
            'Find the OpenAI Responses streaming guide.',
            id: 'u',
          ),
        ],
      ),
      ownerId: 'local-demo',
      context: null,
    );
    for (
      var round = 0;
      round < 4 && result.status == RunStatus.interrupted;
      round++
    ) {
      final answers = <ResumeAnswer>[];
      for (final interrupt in result.interrupts) {
        final call = interrupt.call as ProviderApprovalCall;
        print('${call.serverLabel}: ${call.name} ${call.arguments}');
        stdout.write('Approve this request? Type yes, otherwise deny: ');
        answers.add(
          stdin.readLineSync() == 'yes'
              ? interrupt.approve()
              : interrupt.reject(reason: 'Declined in the CLI'),
        );
      }
      result = await agent.generate(
        ChatRequest(
          threadId: result.threadId,
          runId: 'decision-$round',
          parentRunId: result.runId,
          resume: answers,
        ),
        ownerId: 'local-demo',
        context: null,
      );
    }
    print('${result.status.name}: ${result.text}');
  } finally {
    client.close();
  }
}
```

For an offline fixture, run `dart run examples/review_cases/openai_mcp.dart`.
It exercises two configured servers, approval and denial, recreated agents,
credential rotation, owner isolation, changed configuration and a real Dart
client over loopback HTTP. It does not execute a remote tool.

## Configure servers and credentials

Each tool has a unique `server_label`. Use a `server_url`, `tunnel_id`, or
legacy `connector_id`. The provider and model determine address availability.
`OpenAIMcpTool` accepts the pinned SDK's `McpTool`; `fromJson` preserves native
options not represented by that SDK, including allowed-tool filters,
`require_approval` policies, deferred loading and future JSON fields.
Declare MCP tools through `mcpTools` and other managed tools through
`hostedTools`. Supply a stable, nonsecret `authorityBindingId` for the backend
provider account and transport configuration. Change that ID when the account,
endpoint or routing authority changes; never use an API key as the ID.
It is distinct from each MCP server's credential binding.

Models with managed tools use immutable `options` and `toolChoice`, and reject
`configure` callbacks at construction. Extra native parameters belong in
`options: {'temperature': 0.2}`. Runtime-owned history, tools, model and bounds
cannot be supplied there. Pending local approvals and provider continuations
bind the ordered MCP and hosted-tool sets, model, options and authority. See
[model continuation contracts](approval-contracts.md#model-continuation-contracts).

Keep credentials separate from the persisted configuration. Construct the model
for the authenticated owner and resolve that owner's credential on each request:

```dart
final mcp = openai.OpenAIMcpTool.fromJson(
  {
    'type': 'mcp',
    'server_label': 'support',
    'server_url': 'https://support.example.com/mcp',
    'require_approval': 'always',
  },
  credentialBindingId: account.stableAuthorizationIdentity,
  credentials: () async => openai.OpenAIMcpCredentials(
    authorization: await tokens.accessTokenFor(authenticatedOwner, account),
  ),
);
```

`account` and `tokens` are application services. Derive the owner from backend
authentication. The binding identifies the account and authorization scope;
change it when that authority changes. Refreshing a token for the same binding
is allowed. Literal `authorization` and `headers` are also accepted with a
binding ID and extracted into private request-time credentials.

`definition` and `contract` omit these credentials. Known MCP credentials are
also removed from response configuration metadata. Keep secrets out of URLs,
unknown options and application logs. Call arguments and native results can
contain private data and remain in backend history; only use `chatHydration`
for a client snapshot. The backend `AgentResult` includes private replay.

## Resume a saved decision

Use `ServerpodRunStore(session)` for durable history, recreating the agent with
the same nonsecret configuration and credential binding on each request.
For complete database setup, see the [Serverpod example](../examples/serverpod/README.md).
The approved or rejected run supplies a new run ID and the interrupted parent.
Resolve every pending interrupt once. `approve(reason: ...)` and
`reject(reason: ...)` accept an optional string; editing provider arguments is
unsupported. A changed server or policy fails before local effects or provider
continuation. Cancelling a pending approval before continuation preserves it and does not
send denial. Cancellation after dispatch can instead leave the run indeterminate.

Both pinned clients expose these as **generic interrupts** without registering
a fake local tool. The optional `agent_weave_serverpod_client` companion provides
typed access for Dart clients over either native Serverpod streaming or HTTP:

```dart
import 'package:agent_weave_serverpod_client/agent_weave_serverpod_client.dart';

final approval = chat.getInterrupts().single.providerApproval;
if (approval != null && approval.canResolve) {
  print('${approval.serverLabel}: ${approval.toolName}');
  print(approval.arguments); // Immutable owner-visible JSON snapshot.
  await approval.approve(reason: 'Reviewed'); // Or reject(reason: ...).
}
```

This snippet assumes one pending approval. Render each returned interrupt for
a batch, and call an action only after its owner makes a decision.
`providerApproval` returns null for other interrupts. Malformed declared metadata
throws `FormatException` without echoing its contents. Use a fresh snapshot
from the current chat state after reconnecting. Awaiting `approve` or `reject`
stages the decision and propagates callback errors; it does not wait for the
resumed run. Observe `chat.states` for completion and provider errors.
The helper stays outside the core runtime, which has no TanStack dependency.

Without this helper, use the same generic payload shape in Dart and JavaScript:

```dart
final interrupt = chat.getInterrupts().single;
interrupt.resolveInterrupt({'approved': false, 'reason': 'Outside the scope'});
```

```javascript
const [interrupt] = chat.getInterrupts();
interrupt.resolveInterrupt({approved: false, reason: 'Outside the scope'});
```

Read `metadata.providerApproval` for the provider and server label. This differs
from the [typed local-tool JavaScript approval API](tools.md#edit-tool-arguments-in-a-client).
Never send raw provider request IDs or replay from a client. The runtime maps
its public local call IDs to private MCP approval IDs.

## Failure and continuation boundaries

The adapter reconciles terminal MCP discovery, calls, approvals and matching
approval-response echoes before exposing a call or executing a local tool.
Echoes must match the saved decision and are retained for audit without sending
the same approval response twice on later turns.
Native approval responses follow their source output in ordered, stateless
replay with `store: false`. See the [official MCP guide](https://developers.openai.com/api/docs/guides/tools-connectors-mcp)
for the provider protocol; fixture coverage does not establish live acceptance.

Provider continuations consume normal model steps. In a mixed local/provider
turn, local calls wait for the complete approval batch to validate before effects.
The runtime checkpoints before a possible provider execution. If a request fails,
is cancelled, or loses its authoritative checkpoint after it might have started,
the thread becomes indeterminate and cannot automatically resend. This guard
is conservative once a decision batch is accepted, even if the failure occurs
before a network send can be confirmed. Preserve its
history, reconcile external effects, and start a new thread when needed.
A denial continues normally. The SDK's streaming path does not automatically retry.

Explicitly setting `require_approval: never` or selective policies can authorize
remote execution without a pause. Neither the runtime nor a cancelled network
request can undo a remote effect. Live MCP servers, OAuth, tunnel/connector
availability, remote idempotency and provider execution quality remain unverified.
See [validation](validation.md) for offline and durable test evidence.


# Source: docs/openai-hosted-parameters.md

# OpenAI hosted tool inventory

Generated from the pinned [official Node SDK declarations](openai-hosted-inventory.json). See [the usage guide](openai-hosted.md) and [output references](output-references.md).

Selected hosted Responses, MCP and output-reference declarations, with executable hosted request fields; MCP uses provider-owned approval continuation and private replay. Credentials resolve separately at request time and require a stable binding identity; credential fields are excluded from executable configuration snapshots. Provider approval response echoes must match a trusted decision and do not create a new approval. This does not establish complete MCP protocol, model or live parity; not a claim of complete nested semantics, live behavior or endpoint parity. Four annotation forms have typed public reference projections. Native positions remain opaque, distinct from enclosing UTF-16 text segments. Scoped file handles are deliberately public references; unknown fields and native replay stay private. Completed image bytes become public ImagePart content. Partial images, precise native-coordinate highlights, hosted progress and downloaded container files remain open. External type references are retained, not expanded. Other tools, local executors and unselected declarations are excluded.

## FileSearchTool

Disposition: raw-native-options

| Field | Source type |
| --- | --- |
| type | `'file_search'` |
| vector_store_ids | `Array<string>` |
| filters? | `Shared.ComparisonFilter \| Shared.CompoundFilter \| null` |
| max_num_results? | `number` |
| ranking_options? | `FileSearchTool.RankingOptions` |

## FileSearchTool.RankingOptions

Disposition: raw-native-options

| Field | Source type |
| --- | --- |
| hybrid_search? | `RankingOptions.HybridSearch` |
| ranker? | `'auto' \| 'default-2024-11-15'` |
| score_threshold? | `number` |

## FileSearchTool.RankingOptions.HybridSearch

Disposition: raw-native-options

| Field | Source type |
| --- | --- |
| embedding_weight | `number` |
| text_weight | `number` |

## McpToolCallError

Disposition: validated-private-mcp-replay

`McpToolCallError.McpProtocolError | McpToolCallError.McpToolExecutionError | McpToolCallError.HTTPError`

## McpToolCallError.McpProtocolError

Disposition: validated-private-mcp-replay

| Field | Source type |
| --- | --- |
| code | `number` |
| message | `string` |
| type | `'mcp_protocol_error'` |

## McpToolCallError.McpToolExecutionError

Disposition: validated-private-mcp-replay

| Field | Source type |
| --- | --- |
| content | `unknown` |
| type | `'mcp_tool_execution_error'` |

## McpToolCallError.HTTPError

Disposition: validated-private-mcp-replay

| Field | Source type |
| --- | --- |
| code | `number` |
| message | `string` |
| type | `'http_error'` |

## ResponseCodeInterpreterToolCall

Disposition: private-replay

| Field | Source type |
| --- | --- |
| id | `string` |
| code | `string \| null` |
| container_id | `string` |
| outputs | `Array<ResponseCodeInterpreterToolCall.Logs \| ResponseCodeInterpreterToolCall.Image> \| null` |
| status | `'in_progress' \| 'completed' \| 'incomplete' \| 'interpreting' \| 'failed'` |
| type | `'code_interpreter_call'` |

## ResponseCodeInterpreterToolCall.Logs

Disposition: private-replay

| Field | Source type |
| --- | --- |
| logs | `string` |
| type | `'logs'` |

## ResponseCodeInterpreterToolCall.Image

Disposition: private-replay

| Field | Source type |
| --- | --- |
| type | `'image'` |
| url | `string` |

## ResponseContentPartAddedEvent

Disposition: private-replay

| Field | Source type |
| --- | --- |
| content_index | `number` |
| item_id | `string` |
| output_index | `number` |
| part | `ResponseOutputText \| ResponseOutputRefusal \| ResponseContentPartAddedEvent.ReasoningText` |
| sequence_number | `number` |
| type | `'response.content_part.added'` |

## ResponseContentPartAddedEvent.ReasoningText

Disposition: private-replay

| Field | Source type |
| --- | --- |
| text | `string` |
| type | `'reasoning_text'` |

## ResponseContentPartDoneEvent

Disposition: private-replay

| Field | Source type |
| --- | --- |
| content_index | `number` |
| item_id | `string` |
| output_index | `number` |
| part | `ResponseOutputText \| ResponseOutputRefusal \| ResponseContentPartDoneEvent.ReasoningText` |
| sequence_number | `number` |
| type | `'response.content_part.done'` |

## ResponseContentPartDoneEvent.ReasoningText

Disposition: private-replay

| Field | Source type |
| --- | --- |
| text | `string` |
| type | `'reasoning_text'` |

## ResponseFileSearchToolCall

Disposition: private-replay

| Field | Source type |
| --- | --- |
| id | `string` |
| queries | `Array<string>` |
| status | `'in_progress' \| 'searching' \| 'completed' \| 'incomplete' \| 'failed'` |
| type | `'file_search_call'` |
| results? | `Array<ResponseFileSearchToolCall.Result> \| null` |

## ResponseFileSearchToolCall.Result

Disposition: private-replay

| Field | Source type |
| --- | --- |
| attributes? | `{
    [key: string]: string \| number \| boolean;
} \| null` |
| file_id? | `string` |
| filename? | `string` |
| score? | `number` |
| text? | `string` |

## ResponseFunctionWebSearch

Disposition: private-replay

| Field | Source type |
| --- | --- |
| id | `string` |
| action | `ResponseFunctionWebSearch.Search \| ResponseFunctionWebSearch.OpenPage \| ResponseFunctionWebSearch.Find` |
| status | `'in_progress' \| 'searching' \| 'completed' \| 'failed' \| 'incomplete'` |
| type | `'web_search_call'` |

## ResponseFunctionWebSearch.Search

Disposition: private-replay

| Field | Source type |
| --- | --- |
| type | `'search'` |
| queries? | `Array<string>` |
| query? | `string` |
| sources? | `Array<Search.Source>` |

## ResponseFunctionWebSearch.Search.Source

Disposition: private-replay

| Field | Source type |
| --- | --- |
| type | `'url'` |
| url | `string` |

## ResponseFunctionWebSearch.OpenPage

Disposition: private-replay

| Field | Source type |
| --- | --- |
| type | `'open_page'` |
| url? | `string \| null` |

## ResponseFunctionWebSearch.Find

Disposition: private-replay

| Field | Source type |
| --- | --- |
| pattern | `string` |
| type | `'find_in_page'` |
| url | `string` |

## ResponseInputItem.McpApprovalResponse

Disposition: integrated-private-approval-decision

| Field | Source type |
| --- | --- |
| approval_request_id | `string` |
| approve | `boolean` |
| type | `'mcp_approval_response'` |
| id? | `string \| null` |
| reason? | `string \| null` |

## ResponseMcpCallArgumentsDeltaEvent

Disposition: validated-private-mcp-replay

| Field | Source type |
| --- | --- |
| delta | `string` |
| item_id | `string` |
| output_index | `number` |
| sequence_number | `number` |
| type | `'response.mcp_call_arguments.delta'` |

## ResponseMcpCallArgumentsDoneEvent

Disposition: validated-private-mcp-replay

| Field | Source type |
| --- | --- |
| arguments | `string` |
| item_id | `string` |
| output_index | `number` |
| sequence_number | `number` |
| type | `'response.mcp_call_arguments.done'` |

## ResponseMcpCallCompletedEvent

Disposition: validated-private-mcp-replay

| Field | Source type |
| --- | --- |
| item_id | `string` |
| output_index | `number` |
| sequence_number | `number` |
| type | `'response.mcp_call.completed'` |

## ResponseMcpCallFailedEvent

Disposition: validated-private-mcp-replay

| Field | Source type |
| --- | --- |
| item_id | `string` |
| output_index | `number` |
| sequence_number | `number` |
| type | `'response.mcp_call.failed'` |

## ResponseMcpCallInProgressEvent

Disposition: validated-private-mcp-replay

| Field | Source type |
| --- | --- |
| item_id | `string` |
| output_index | `number` |
| sequence_number | `number` |
| type | `'response.mcp_call.in_progress'` |

## ResponseMcpListToolsCompletedEvent

Disposition: validated-private-mcp-replay

| Field | Source type |
| --- | --- |
| item_id | `string` |
| output_index | `number` |
| sequence_number | `number` |
| type | `'response.mcp_list_tools.completed'` |

## ResponseMcpListToolsFailedEvent

Disposition: validated-private-mcp-replay

| Field | Source type |
| --- | --- |
| item_id | `string` |
| output_index | `number` |
| sequence_number | `number` |
| type | `'response.mcp_list_tools.failed'` |

## ResponseMcpListToolsInProgressEvent

Disposition: validated-private-mcp-replay

| Field | Source type |
| --- | --- |
| item_id | `string` |
| output_index | `number` |
| sequence_number | `number` |
| type | `'response.mcp_list_tools.in_progress'` |

## ResponseOutputItem.ImageGenerationCall

Disposition: private-replay

| Field | Source type |
| --- | --- |
| id | `string` |
| result | `string \| null` |
| status | `'in_progress' \| 'completed' \| 'generating' \| 'failed'` |
| type | `'image_generation_call'` |
| action? | `'generate' \| 'edit' \| 'auto' \| null` |
| background? | `'transparent' \| 'opaque' \| 'auto' \| null` |
| error? | `ImageGenerationCall.Error` |
| output_format? | `'png' \| 'webp' \| 'jpeg' \| null` |
| quality? | `'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max' \| 'auto' \| null` |
| revised_prompt? | `string \| null` |
| size? | `(string & {}) \| '1024x1024' \| '1024x1536' \| '1536x1024' \| null` |

## ResponseOutputItem.ImageGenerationCall.Error

Disposition: private-replay

| Field | Source type |
| --- | --- |
| code | `string \| null` |
| message | `string` |
| param | `string \| null` |
| type | `string` |
| moderation_details? | `Error.ModerationDetails` |

## ResponseOutputItem.ImageGenerationCall.Error.ModerationDetails

Disposition: private-replay

| Field | Source type |
| --- | --- |
| categories | `Array<string>` |
| moderation_stage | `'input' \| 'output' \| 'unknown'` |

## ResponseOutputItem.McpCall

Disposition: validated-private-mcp-replay

| Field | Source type |
| --- | --- |
| id | `string` |
| arguments | `string` |
| name | `string` |
| server_label | `string` |
| type | `'mcp_call'` |
| approval_request_id? | `string \| null` |
| error? | `ResponsesAPI.McpToolCallError \| null` |
| output? | `string \| null` |
| status? | `'in_progress' \| 'completed' \| 'incomplete' \| 'calling' \| 'failed'` |

## ResponseOutputItem.McpListTools

Disposition: validated-private-mcp-replay

| Field | Source type |
| --- | --- |
| id | `string` |
| server_label | `string` |
| tools | `Array<McpListTools.Tool>` |
| type | `'mcp_list_tools'` |
| error? | `string \| null` |

## ResponseOutputItem.McpListTools.Tool

Disposition: validated-private-mcp-replay

| Field | Source type |
| --- | --- |
| input_schema | `unknown` |
| name | `string` |
| annotations? | `unknown \| null` |
| description? | `string \| null` |

## ResponseOutputItem.McpApprovalRequest

Disposition: integrated-provider-approval

| Field | Source type |
| --- | --- |
| id | `string` |
| arguments | `string` |
| name | `string` |
| server_label | `string` |
| type | `'mcp_approval_request'` |

## ResponseOutputItem.McpApprovalResponse

Disposition: validated-private-approval-echo

| Field | Source type |
| --- | --- |
| id | `string` |
| approval_request_id | `string` |
| approve | `boolean` |
| type | `'mcp_approval_response'` |
| reason? | `string \| null` |

## ResponseOutputMessage

Disposition: private-replay

| Field | Source type |
| --- | --- |
| id | `string` |
| content | `Array<ResponseOutputText \| ResponseOutputRefusal>` |
| role | `'assistant'` |
| status | `'in_progress' \| 'completed' \| 'incomplete'` |
| type | `'message'` |
| phase? | `'commentary' \| 'final_answer' \| null` |

## ResponseOutputText

Disposition: reviewed-reference-output

| Field | Source type |
| --- | --- |
| annotations | `Array<ResponseOutputText.FileCitation \| ResponseOutputText.URLCitation \| ResponseOutputText.ContainerFileCitation \| ResponseOutputText.FilePath>` |
| text | `string` |
| type | `'output_text'` |
| logprobs? | `Array<ResponseOutputText.Logprob>` |

## ResponseOutputText.FileCitation

Disposition: reviewed-reference-output

| Field | Source type |
| --- | --- |
| file_id | `string` |
| filename | `string` |
| index | `number` |
| type | `'file_citation'` |

## ResponseOutputText.URLCitation

Disposition: reviewed-reference-output

| Field | Source type |
| --- | --- |
| end_index | `number` |
| start_index | `number` |
| title | `string` |
| type | `'url_citation'` |
| url | `string` |

## ResponseOutputText.ContainerFileCitation

Disposition: reviewed-reference-output

| Field | Source type |
| --- | --- |
| container_id | `string` |
| end_index | `number` |
| file_id | `string` |
| filename | `string` |
| start_index | `number` |
| type | `'container_file_citation'` |

## ResponseOutputText.FilePath

Disposition: reviewed-reference-output

| Field | Source type |
| --- | --- |
| file_id | `string` |
| index | `number` |
| type | `'file_path'` |

## ResponseOutputText.Logprob

Disposition: reviewed-reference-output

| Field | Source type |
| --- | --- |
| token | `string` |
| bytes | `Array<number>` |
| logprob | `number` |
| top_logprobs | `Array<Logprob.TopLogprob>` |

## ResponseOutputText.Logprob.TopLogprob

Disposition: reviewed-reference-output

| Field | Source type |
| --- | --- |
| token | `string` |
| bytes | `Array<number>` |
| logprob | `number` |

## ResponseOutputTextAnnotationAddedEvent

Disposition: reviewed-reference-output

| Field | Source type |
| --- | --- |
| annotation | `ResponseOutputTextAnnotationAddedEvent.FileCitation \| ResponseOutputTextAnnotationAddedEvent.URLCitation \| ResponseOutputTextAnnotationAddedEvent.ContainerFileCitation \| ResponseOutputTextAnnotationAddedEvent.FilePath \| null` |
| annotation_index | `number` |
| content_index | `number` |
| item_id | `string` |
| output_index | `number` |
| sequence_number | `number` |
| type | `'response.output_text.annotation.added'` |

## ResponseOutputTextAnnotationAddedEvent.FileCitation

Disposition: reviewed-reference-output

| Field | Source type |
| --- | --- |
| file_id | `string` |
| filename | `string` |
| index | `number` |
| type | `'file_citation'` |

## ResponseOutputTextAnnotationAddedEvent.URLCitation

Disposition: reviewed-reference-output

| Field | Source type |
| --- | --- |
| end_index | `number` |
| start_index | `number` |
| title | `string` |
| type | `'url_citation'` |
| url | `string` |

## ResponseOutputTextAnnotationAddedEvent.ContainerFileCitation

Disposition: reviewed-reference-output

| Field | Source type |
| --- | --- |
| container_id | `string` |
| end_index | `number` |
| file_id | `string` |
| filename | `string` |
| start_index | `number` |
| type | `'container_file_citation'` |

## ResponseOutputTextAnnotationAddedEvent.FilePath

Disposition: reviewed-reference-output

| Field | Source type |
| --- | --- |
| file_id | `string` |
| index | `number` |
| type | `'file_path'` |

## ResponseStreamEvent

Disposition: reviewed-stream-union

`ResponseAudioDeltaEvent | ResponseAudioDoneEvent | ResponseAudioTranscriptDeltaEvent | ResponseAudioTranscriptDoneEvent | ResponseCodeInterpreterCallCodeDeltaEvent | ResponseCodeInterpreterCallCodeDoneEvent | ResponseCodeInterpreterCallCompletedEvent | ResponseCodeInterpreterCallInProgressEvent | ResponseCodeInterpreterCallInterpretingEvent | ResponseCompactionCompactingEvent | ResponseCompletedEvent | ResponseContentPartAddedEvent | ResponseContentPartDoneEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFileSearchCallCompletedEvent | ResponseFileSearchCallInProgressEvent | ResponseFileSearchCallSearchingEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseShellCallCommandAddedEvent | ResponseShellCallCommandDeltaEvent | ResponseShellCallCommandDoneEvent | ResponseShellCallOutputContentDeltaEvent | ResponseShellCallOutputContentDoneEvent | ResponseInProgressEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningSummaryPartAddedEvent | ResponseReasoningSummaryPartDoneEvent | ResponseReasoningSummaryTextDeltaEvent | ResponseReasoningSummaryTextDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent | ResponseWebSearchCallCompletedEvent | ResponseWebSearchCallInProgressEvent | ResponseWebSearchCallSearchingEvent | ResponseImageGenCallCompletedEvent | ResponseImageGenCallGeneratingEvent | ResponseImageGenCallInProgressEvent | ResponseImageGenCallPartialImageEvent | ResponseMcpCallArgumentsDeltaEvent | ResponseMcpCallArgumentsDoneEvent | ResponseMcpCallCompletedEvent | ResponseMcpCallFailedEvent | ResponseMcpCallInProgressEvent | ResponseMcpListToolsCompletedEvent | ResponseMcpListToolsFailedEvent | ResponseMcpListToolsInProgressEvent | ResponseOutputTextAnnotationAddedEvent | ResponseQueuedEvent | ResponseCustomToolCallInputDeltaEvent | ResponseCustomToolCallInputDoneEvent`

## ResponseToolSearchCall

Disposition: private-replay

| Field | Source type |
| --- | --- |
| id | `string` |
| arguments | `unknown` |
| call_id | `string \| null` |
| execution | `'server' \| 'client'` |
| status | `'in_progress' \| 'completed' \| 'incomplete'` |
| type | `'tool_search_call'` |
| created_by? | `string` |

## ResponseToolSearchOutputItem

Disposition: private-replay

| Field | Source type |
| --- | --- |
| id | `string` |
| call_id | `string \| null` |
| execution | `'server' \| 'client'` |
| status | `'in_progress' \| 'completed' \| 'incomplete'` |
| tools | `Array<Tool>` |
| type | `'tool_search_output'` |
| created_by? | `string` |

## Tool.Mcp

Disposition: integrated-mcp-configuration

| Field | Source type |
| --- | --- |
| server_label | `string` |
| type | `'mcp'` |
| allowed_callers? | `Array<'direct' \| 'programmatic'> \| null` |
| allowed_tools? | `Array<string> \| Mcp.McpToolFilter \| null` |
| authorization? | `string` |
| connector_id? | `'connector_dropbox' \| 'connector_gmail' \| 'connector_googlecalendar' \| 'connector_googledrive' \| 'connector_microsoftteams' \| 'connector_outlookcalendar' \| 'connector_outlookemail' \| 'connector_sharepoint'` |
| defer_loading? | `boolean` |
| headers? | `{
    [key: string]: string;
} \| null` |
| require_approval? | `Mcp.McpToolApprovalFilter \| 'always' \| 'never' \| null` |
| server_description? | `string` |
| server_url? | `string` |
| tunnel_id? | `string` |

## Tool.Mcp.McpToolFilter

Disposition: integrated-mcp-configuration

| Field | Source type |
| --- | --- |
| read_only? | `boolean` |
| tool_names? | `Array<string>` |

## Tool.Mcp.McpToolApprovalFilter

Disposition: integrated-mcp-configuration

| Field | Source type |
| --- | --- |
| always? | `McpToolApprovalFilter.Always` |
| never? | `McpToolApprovalFilter.Never` |

## Tool.Mcp.McpToolApprovalFilter.Always

Disposition: integrated-mcp-configuration

| Field | Source type |
| --- | --- |
| read_only? | `boolean` |
| tool_names? | `Array<string>` |

## Tool.Mcp.McpToolApprovalFilter.Never

Disposition: integrated-mcp-configuration

| Field | Source type |
| --- | --- |
| read_only? | `boolean` |
| tool_names? | `Array<string>` |

## Tool.CodeInterpreter

Disposition: raw-native-options

| Field | Source type |
| --- | --- |
| container | `string \| CodeInterpreter.CodeInterpreterToolAuto` |
| type | `'code_interpreter'` |
| allowed_callers? | `Array<'direct' \| 'programmatic'> \| null` |

## Tool.CodeInterpreter.CodeInterpreterToolAuto

Disposition: raw-native-options

| Field | Source type |
| --- | --- |
| type | `'auto'` |
| file_ids? | `Array<string>` |
| memory_limit? | `'1g' \| '4g' \| '16g' \| '64g' \| null` |
| network_policy? | `ResponsesAPI.ContainerNetworkPolicyDisabled \| ResponsesAPI.ContainerNetworkPolicyAllowlist` |

## Tool.ImageGeneration

Disposition: raw-native-options

| Field | Source type |
| --- | --- |
| type | `'image_generation'` |
| action? | `'generate' \| 'edit' \| 'auto'` |
| background? | `'transparent' \| 'opaque' \| 'auto'` |
| input_fidelity? | `'high' \| 'low' \| null` |
| input_image_mask? | `ImageGeneration.InputImageMask` |
| model? | `(string & {}) \| 'gpt-image-1' \| 'gpt-image-1-mini' \| 'gpt-image-2' \| 'gpt-image-2-2026-04-21' \| 'gpt-image-2.5-sunburst' \| 'gpt-image-2.5-sunburst-2026-09-08' \| 'gpt-image-2.5-flare' \| 'gpt-image-2.5-flare-2026-09-08' \| 'gpt-image-1.5' \| 'chatgpt-image-latest'` |
| moderation? | `'auto' \| 'low'` |
| output_compression? | `number` |
| output_format? | `'png' \| 'webp' \| 'jpeg'` |
| partial_images? | `number` |
| quality? | `'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max' \| 'auto'` |
| size? | `(string & {}) \| '1024x1024' \| '1024x1536' \| '1536x1024' \| 'auto'` |

## Tool.ImageGeneration.InputImageMask

Disposition: raw-native-options

| Field | Source type |
| --- | --- |
| file_id? | `string` |
| image_url? | `string` |

## ToolSearchTool

Disposition: raw-native-options

| Field | Source type |
| --- | --- |
| type | `'tool_search'` |
| description? | `string \| null` |
| execution? | `'server' \| 'client'` |
| parameters? | `unknown \| null` |

## WebSearchPreviewTool

Disposition: raw-native-options

| Field | Source type |
| --- | --- |
| type | `'web_search_preview' \| 'web_search_preview_2025_03_11'` |
| search_content_types? | `Array<'text' \| 'image'>` |
| search_context_size? | `'low' \| 'medium' \| 'high'` |
| user_location? | `WebSearchPreviewTool.UserLocation \| null` |

## WebSearchPreviewTool.UserLocation

Disposition: raw-native-options

| Field | Source type |
| --- | --- |
| type | `'approximate'` |
| city? | `string \| null` |
| country? | `string \| null` |
| region? | `string \| null` |
| timezone? | `string \| null` |

## WebSearchTool

Disposition: raw-native-options

| Field | Source type |
| --- | --- |
| type | `'web_search' \| 'web_search_2025_08_26'` |
| external_web_access? | `boolean` |
| filters? | `WebSearchTool.Filters \| null` |
| search_context_size? | `'low' \| 'medium' \| 'high'` |
| user_location? | `WebSearchTool.UserLocation \| null` |

## WebSearchTool.Filters

Disposition: raw-native-options

| Field | Source type |
| --- | --- |
| allowed_domains? | `Array<string> \| null` |

## WebSearchTool.UserLocation

Disposition: raw-native-options

| Field | Source type |
| --- | --- |
| city? | `string \| null` |
| country? | `string \| null` |
| region? | `string \| null` |
| timezone? | `string \| null` |
| type? | `'approximate'` |

## ChatCompletionMessage

Disposition: private-buffered-response

| Field | Source type |
| --- | --- |
| content | `string \| null` |
| refusal | `string \| null` |
| role | `'assistant'` |
| annotations? | `Array<ChatCompletionMessage.Annotation>` |
| audio? | `ChatCompletionAudio \| null` |
| function_call? | `ChatCompletionMessage.FunctionCall \| null` |
| tool_calls? | `Array<ChatCompletionMessageToolCall>` |

## ChatCompletionMessage.Annotation

Disposition: buffered-reference-output

| Field | Source type |
| --- | --- |
| type | `'url_citation'` |
| url_citation | `Annotation.URLCitation` |

## ChatCompletionMessage.Annotation.URLCitation

Disposition: buffered-reference-output

| Field | Source type |
| --- | --- |
| end_index | `number` |
| start_index | `number` |
| title | `string` |
| url | `string` |

## ChatCompletionMessage.FunctionCall

Disposition: private-buffered-response

| Field | Source type |
| --- | --- |
| arguments | `string` |
| name | `string` |


# Source: docs/openrouter.md

# Use OpenRouter

`agent_weave_openrouter` has a native JSON/SSE client and separate Chat and
Responses adapters. It reuses AgentWeave's compatible wire codecs, while native
routing, plugins, reasoning, cache options and metadata bypass the OpenAI SDK's
request serializer. This is selected integration, not complete OpenRouter parity.

Set `OPENROUTER_API_KEY` and `OPENROUTER_MODEL` in your backend environment for a
model available to your account. From the workspace root, run `dart pub get`,
then `dart run examples/openrouter_demo.dart`. This sends a real request and may
incur charges. The complete program is:

```dart
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_openrouter/agent_weave_openrouter.dart' as router;

Future<void> main() async {
  final apiKey = Platform.environment['OPENROUTER_API_KEY'];
  final modelId = Platform.environment['OPENROUTER_MODEL'];
  if (apiKey == null || modelId == null) {
    throw StateError('Set OPENROUTER_API_KEY and OPENROUTER_MODEL.');
  }
  final client = router.OpenRouterClient.withApiKey(
    apiKey: apiKey,
    appName: 'My app',
    headers: {'X-OpenRouter-Metadata': 'enabled'},
  );
  try {
    final model = router.OpenRouterChatModel(
      client: client,
      model: modelId,
      options: router.OpenRouterChatOptions(
        provider: router.OpenRouterProviderPreferences(requireParameters: true),
      ),
    );
    final result = await generateText(model: model, prompt: 'Say hello.');
    print(result.text);
  } finally {
    client.close();
  }
}
```

The example was analyzed and compiled without execution. Keep credentials on the
backend. The caller closes the client at shutdown. An injected HTTP client or
`OpenRouterClient.withTransport` transport remains caller-owned. For rotating
secrets, use `OpenRouterClient(credentialResolver: yourTokenLoader)`; resolution
occurs per request within the request deadline. Attribution and session headers
are configured on the client; authorization belongs to the resolver.

## Native options

`OpenRouterChatOptions` and `OpenRouterResponsesOptions` keep native fields
separate from runtime-owned messages, tools, schema, token bounds and streaming.
They take immutable snapshots, including nested `extra` values. OpenRouter
reports usage automatically; deprecated usage-inclusion flags do not control it.

```dart
final options = router.OpenRouterChatOptions(
  provider: router.OpenRouterProviderPreferences(
    order: ['provider-selected-by-your-app'],
    allowFallbacks: false,
    requireParameters: true,
    dataCollection: router.OpenRouterDataCollection.deny,
    sort: router.OpenRouterProviderSort.price,
    maxPrice: {'prompt': '1', 'completion': '2'},
  ),
  reasoning: router.OpenRouterReasoning(
    effort: router.OpenRouterReasoningEffort.low,
  ),
  cacheControl: router.OpenRouterCacheControl(),
  plugins: [router.OpenRouterPlugin(id: 'response-healing')],
  extra: {'prompt_cache_key': 'application-scoped-key'},
);
```

This is configuration syntax, not a tested provider/model combination. Provider
availability, supported parameters, plugin behavior and price units follow the
[official routing contract](https://openrouter.ai/docs/guides/routing/provider-selection).
Do not assume every combination works. `requireParameters` asks OpenRouter to
filter providers that cannot support the requested parameters.

Provider preferences also expose allow/ignore lists, ZDR, quantizations,
distillable-text enforcement, provider-specific options and performance
preferences. Nested price, percentile and provider-option structures remain
JSON so their schema unions and unknown fields survive. `extra` supports newer
native options. A recognized field is not proof of orchestration or acceptance.

The optional `configure` callback remains SDK-typed for compatible request
parameters. Prefer `request.copyWith(...)`; rebuilding a request through the
SDK's typed JSON input decoder can reject raw reasoning items. Native fields
belong in `options` or `extra`. Neither path can replace runtime history or
registered function definitions. Native JSON client methods are separate for
requests the normalized agent does not implement.

## Generated images

Use [Chat image output](openrouter-images.md) with explicit text/image modalities
for a completed assistant message. Ordinary text uses SSE; image requests are
buffered because the pinned Chat stream schema does not define image deltas.
Images and opaque replay fields survive tool approvals and server-owned history.
For the dedicated `/images` endpoint, use `OpenRouterImageModel`. It supports
buffered results, native SSE events, same-request JSON fallback and model/endpoint
discovery. See the [dedicated Image API guide](openrouter-image-api.md).

## Responses and private replay

Use `OpenRouterResponsesModel(client: client, model: modelId, options: ...)`
for `/responses`. It has its own private replay namespace. OpenRouter Responses
is stateless: send complete input history. The adapter rejects `store: true` and
non-null `previous_response_id`; it does not depend on a server-stored response.
It excludes automatic OpenAI encrypted-reasoning includes; OpenRouter documents
automatic encrypted content for supported reasoning providers.

Returned Responses output items retain opaque fields and order through the next
tool turn. Chat retains ordered `reasoning_details` fragments as returned, in
`openrouter.chat.reasoning`, and replays them only to the Chat endpoint. It does
not sort or deduplicate blocks. If only plaintext `reasoning` is returned, it
streams as reasoning text and is privately retained in
`openrouter.chat.reasoning_text` for the next turn. Structured details take
precedence when both representations are returned. The fixture verifies ordered replay, not every
provider's incremental-fragment behavior. Unknown or cross-provider private
history is not substituted for this provider's replay. File handles owned by
another provider are rejected; Responses URL and inline document sources remain
separate from provider-owned IDs. Chat document parts are not implemented.

## Metadata and native responses

`X-OpenRouter-Metadata: enabled` opts into router metadata when supplied by the
service. The adapter retains actual generation/model/provider identity, usage,
cost and unknown response metadata in private assistant `providerData` under
`openrouter.chat.metadata` or `openrouter.responses.metadata`. Missing values
stay absent. It does not infer the provider or compute an invoice. Reasoning and
metadata stay out of UI hydration; `AgentResult` is trusted backend data.

Normalized metadata is a compact merged snapshot. It is not a log of every
stream frame. For complete native envelopes, headers and event IDs, use
`client.createChat`, `streamChat`, `createResponse`, or `streamResponse`. Native
JSON responses expose `data`, `statusCode` and headers. Streaming preserves
unknown event fields and detects inline errors and premature EOF.

The native client does not implement management APIs or every modality. Hosted
server tools, background-job handling, other output media and all model variants still
need dedicated runtime behavior. See the [API inventory](openrouter-api-reference.md)
for all pinned operations and fields, including those not integrated.

## Errors and cancellation

Direct streams propagate redacted `JsonHttpException` diagnostics.
`generateText` wraps failures in `AgentRunException`; use its `code`, and inspect
`cause` only on the trusted backend. Error details and headers may contain private
provider information, so do not send them to a UI. Resolver failures and malformed
stream payloads use generic messages. Known request credentials are redacted.

Requests have per-call deadlines and cancellation. Cancelling one subscription
signals that call without cancelling siblings sharing a parent token; cancelling
the parent signals all active calls. This does not undo requests already accepted
remotely. The client does not automatically retry POSTs.

## Validation and migration

Offline loopback cases exercise Chat and Responses schema output, persisted tool
approval and replay, opaque reasoning, metadata, error privacy, rotating
credentials, cancellation and client ownership. They do not establish live model
support, cache hits, routing, billing, or all native fields.

Earlier development versions returned an `OpenAIClient` from `openRouterClient`
and exported SDK routing types. `openRouterClient` now returns `OpenRouterClient`.
Use `options: OpenRouterChatOptions(...)` for provider/reasoning/fallback settings;
use native enums and non-const option constructors for immutable snapshots.
Consumers explicitly typing the old SDK client must migrate. `configure` remains
available for SDK-compatible parameters. See [coverage](provider-coverage.md),
[validation](validation.md) and [the independent review](dx-review.md).


# Source: docs/openrouter-images.md

# Images from OpenRouter Chat

Request image output through `OpenRouterChatOptions.modalities`. The normalized
agent supports text and image output. Its typed enum also represents audio for
native requests, but the agent rejects audio before sending a request because
it does not implement that output lifecycle.

Select a model and provider that support image output through Chat Completions.
Availability and accepted configuration vary; this guide does not recommend a
particular model. Use the [dedicated Image API guide](openrouter-image-api.md) for the separate
`/images` workflow; its results are independent of Chat history and replay.

## Generate images from Dart

Set `OPENROUTER_API_KEY` and `OPENROUTER_IMAGE_CHAT_MODEL` on the backend. Running
this example makes a billable request. The repository analyzes and compiles it
without execution.

```dart
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_openrouter/agent_weave_openrouter.dart' as router;

Future<void> main() async {
  final key = Platform.environment['OPENROUTER_API_KEY'];
  final modelId = Platform.environment['OPENROUTER_IMAGE_CHAT_MODEL'];
  if (key == null || modelId == null) {
    throw StateError('Set OPENROUTER_API_KEY and OPENROUTER_IMAGE_CHAT_MODEL.');
  }
  final client = router.OpenRouterClient.withApiKey(apiKey: key);
  try {
    final result = await generateText(
      model: router.OpenRouterChatModel(
        client: client,
        model: modelId,
        options: router.OpenRouterChatOptions(
          modalities: [
            router.OpenRouterOutputModality.text,
            router.OpenRouterOutputModality.image,
          ],
          imageConfig: {'aspect_ratio': '1:1'},
        ),
      ),
      prompt: 'Draw a small red sailboat and describe it briefly.',
    );
    print(result.text);
    print('Generated ${result.images.length} images.');
    for (final image in result.images) {
      // Pass image.url to your renderer or application-owned artifact store.
      print('Image reference has ${image.url.length} characters.');
    }
  } finally {
    client.close();
  }
}
```

The complete program is also in
[`examples/openrouter_images_demo.dart`](https://github.com/seifalmotaz/agent-weave/blob/main/examples/openrouter_images_demo.dart).
Use the same model in an `AiAgent` behind an authenticated Serverpod endpoint;
the runtime owns tools, approvals and history.

`result.images` contains images produced by assistant messages in this run,
including intermediate tool steps. It excludes user image inputs and previous
runs. `result.messages` includes the complete stored history and private replay;
use `chatHydration` to return public history to a client.

## Completed Chat messages, not image stream fragments

Ordinary text Chat requests use SSE. Requesting an image modality sends
`stream: false` and reads a completed native Chat response. The pinned Chat
schema defines `assistant.images`; its streaming delta does not define image
fragments, image IDs or image indexes. The adapter rejects image-bearing SSE
deltas rather than silently dropping them or guessing how to assemble them.

For a string `content` and separate `images` array, the public result places
text before the images, retaining image-array order. The schema does not define
cross-order between these two fields. If `content` itself is an array of text
and image parts, its explicit order is retained, followed by the separate
`images` array. No image deduplication or index inference is performed.

Image references may be absolute HTTP(S) URLs without credentials or nonempty
base64 image data URLs. Other URI forms are rejected by this adapter. Remote
images are not downloaded; data URLs are checked for valid base64 but are not
raster-decoded. Your application owns rendering, storage limits, expired URLs
and any artifact hosting.

## Native configuration and safe continuation

`imageConfig` snapshots model-specific JSON without inventing universal sizes
or aspect ratios. Native unknown fields remain intact. The provider validates
its accepted configuration; a JSON map is not compile-time validation of every
model option. `extra` cannot replace runtime-owned history, tools, schema,
token bounds, streaming or modality selection.

The existing typed `configure` callback still protects runtime fields. It can
set provider parameters such as temperature. It cannot replace a supplied
schema or instructions or advertise an unregistered function.

Image continuation is stored privately under `openrouter.chat.images`. It
retains the original content, refusal and image payloads, including opaque
fields on images. Restoring history checks that this payload matches the
assistant's public content; it cannot replace roles or tool calls. Function
calls, reasoning and metadata retain their existing separate handling.

Mixed image/function responses pause for normal approvals. Images are stored
before the pause, and a recreated agent replays them with the selected function
result after approval. Invalid images, mismatched replay and error or filtered
tool-call finishes do not release a local call. Buffered JSON error envelopes
retain redacted diagnostics and request IDs.

## Contract and verification

The [OpenRouter API inventory](openrouter-api-reference.md) follows the pinned
[official OpenAPI](https://openrouter.ai/openapi.json). The current
[image-generation guide](https://openrouter.ai/docs/guides/overview/multimodal/image-generation)
describes the dedicated Image API. Its partial-image event types and parameter
limits do not establish Chat behavior.

Local tests cover completed messages, content-array ordering, multiple data and
HTTP(S) image references, exact private replay, ownership guards, configuration,
errors, cancellation and approval recreation. The independent consumer scores
this selected path 8/10. No live model, billing or device rendering was tested.
See [validation](validation.md) for the exact evidence and open work.


# Source: docs/openrouter-image-api.md

# OpenRouter dedicated Image API

Use `OpenRouterImageModel` for OpenRouter's dedicated `/images` endpoint. It accepts an image model and a prompt, and returns generated image bytes. `OpenRouterChatModel` uses the separate Chat Completions image workflow; its messages and replay are not interchangeable with this API.

The example below defaults to a buffered response. Set `OPENROUTER_IMAGE_STREAM=1` to request streaming. Each invocation can incur provider charges. Choose a model and options from discovery before running it.

```dart
import 'dart:io';

import 'package:agent_weave_openrouter/agent_weave_openrouter.dart';

Future<void> main() async {
  final key = Platform.environment['OPENROUTER_API_KEY'];
  final modelId = Platform.environment['OPENROUTER_IMAGE_MODEL'];
  final prompt = Platform.environment['OPENROUTER_IMAGE_PROMPT'];
  if (key == null || modelId == null || prompt == null) {
    throw StateError(
      'Set OPENROUTER_API_KEY, OPENROUTER_IMAGE_MODEL, and OPENROUTER_IMAGE_PROMPT.',
    );
  }

  final client = OpenRouterClient.withApiKey(apiKey: key);
  final model = OpenRouterImageModel(client: client);
  final request = OpenRouterImageRequest(model: modelId, prompt: prompt);
  try {
    if (Platform.environment['OPENROUTER_IMAGE_STREAM'] == '1') {
      await for (final event in model.stream(request)) {
        switch (event) {
          case OpenRouterImagePartial():
            print(
              'Partial image ${event.index}: ${event.image.bytes.length} bytes',
            );
          case OpenRouterImageText():
            print('Text chunk phase: ${event.phase}');
          case OpenRouterImageCompleted():
            print(
              'Final image: ${event.image.bytes.length} bytes; '
              'media type: ${event.image.mediaType ?? 'unknown'}',
            );
          case OpenRouterImageBuffered():
            for (final image in event.response.data) {
              print(
                'Final image: ${image.bytes.length} bytes; '
                'media type: ${image.mediaType ?? 'unknown'}',
              );
            }
          case OpenRouterImageError():
            throw StateError(
              'Image generation failed; inspect the error event safely.',
            );
        }
      }
    } else {
      final response = await model.generate(request);
      for (final image in response.data) {
        print(
          'Final image: ${image.bytes.length} bytes; '
          'media type: ${image.mediaType ?? 'unknown'}',
        );
      }
    }
  } finally {
    client.close();
  }
}
```

Run from the workspace root with `OPENROUTER_API_KEY`, `OPENROUTER_IMAGE_MODEL`, and `OPENROUTER_IMAGE_PROMPT` set in your environment:

```sh
dart run examples/openrouter_image_api_demo.dart
```

The example reports sizes and does not write or render images. The separate offline fixture needs no key or network access: `dart run examples/review_cases/openrouter_image_api.dart`.

## Requests and discovery

`OpenRouterImageRequest` exposes `n`, reference images, resolution, aspect ratio, size, quality, background, output format and compression, seed, provider preferences, session ID, user, trace, and streaming. `extra` retains additional native request fields; `fromJson` and `toJson` support native JSON. Reference images use native `image_url` content parts. The request type checks their shape and nonempty URL string. Apply your own scheme, host and authorization policy before accepting untrusted reference URLs; the provider may fetch them. Model and provider capabilities vary: unsupported parameters can be ignored or rejected by the provider, and requesting multiple images does not guarantee a particular count.

Call `model.listModels()` for image models and `model.listModelEndpoints(author, slug)` for per-endpoint capabilities and pricing. The typed results expose capability descriptors, endpoint details and pricing, and preserve unknown fields in `raw`. Pass the author and slug as separate path segments; the client uses its configured API origin and does not follow URLs returned by discovery. The raw client also offers `listImageModels`, `listImageModelEndpoints`, and `createImages` for native JSON access. See [OpenRouter's Image API guide](https://openrouter.ai/docs/guides/overview/multimodal/image-generation) for model-specific availability and routing.

## Serve generation through Serverpod

Register `createOpenRouterImageRoute(client: client, model: yourImageModel)` on
`pod.webServer` at `/api/images`. Use your existing Serverpod authentication
handler. The example factory below accepts a prompt from `forwardedProps`, fixes
the model and count on the server, and saves the exact native result through
`ServerpodRunStore`. It rejects unauthenticated requests. The application owns
the provider client and closes it at shutdown.

```dart
import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_openrouter/agent_weave_openrouter.dart' as router;
import 'package:agent_weave_serverpod/agent_weave_serverpod.dart';
import 'package:agent_weave_serverpod_storage_server/agent_weave_serverpod_storage_server.dart';

/// Register with pod.webServer.addRoute(route, '/api/images').
/// The application owns the client and closes it at shutdown.
AgentGenerationRoute<
  router.OpenRouterImageRequest,
  router.OpenRouterImageResponse
>
createOpenRouterImageRoute({
  required router.OpenRouterClient client,
  required String model,
}) {
  final image = router.OpenRouterImageModel(client: client);
  return AgentGenerationRoute(
    authenticate: (session) => session.authenticated?.userIdentifier,
    // Keep model, count and routing policy on the server.
    decode: (input) => router.OpenRouterImageRequest(
      model: model,
      prompt: input['prompt'] as String,
      n: 1,
    ),
    createTask: (session) => GenerationTask(
      store: ServerpodRunStore(session),
      execute: (request, context) => image.generate(
        request,
        cancellation: context.cancellation,
      ),
      encodeResult: (response) => response.raw,
    ),
  );
}
```

This source lives at
[`examples/serverpod/agent_weave_demo_server/lib/src/ai/openrouter_image_route.dart`](https://github.com/seifalmotaz/agent-weave/blob/main/examples/serverpod/agent_weave_demo_server/lib/src/ai/openrouter_image_route.dart).
The route emits AgentWeave generation events while the provider call is buffered;
it does not stream preview bytes. Use a generic generation client to receive the
native JSON result. Add your application's quota, output storage and retention
policy before exposing a billable endpoint.

The real PostgreSQL/network fixture in
`test/integration/openrouter_image_api_test.dart` also demonstrates an application
task consuming native partial events and retaining every completed event in
provider order. Its progress value stays at zero while receiving previews, since
the provider gives no completion percentage. Preview bytes are not stored as
final output. The task treats a native error event as failure and waits for stream
completion before saving its result. This is an application recipe, not automatic
Chat history or preview synchronization in either client.

## Streaming and results

`stream` emits events in provider order. `OpenRouterImagePartial` is a preview, with a partial sequence index; it is not a final image. `OpenRouterImageText` has a `phase`: `content` is renderable output, while `draft` and `reasoning` are intermediate; unknown phase strings are preserved. `OpenRouterImageCompleted` carries a final image. There may be multiple completed events, and the API does not supply an output index that associates them with previews. Handle each event without inventing that association.

Some providers return buffered JSON even when streaming is requested. The client detects the response content type from the **same HTTP request** and emits `OpenRouterImageBuffered` with the response; it does not repeat the generation request. The client accepts both the direct event shape in OpenRouter's guide and the `data` wrapper in its pinned OpenAPI schema. The native `streamImages` method exposes the underlying JSON/SSE events. A typed `OpenRouterImageError` is a failure event: callers must handle it explicitly. Invalid events, an incomplete stream, or an absent completion sentinel fail the stream. Bytes after the `[DONE]` sentinel are not read.

Images provide `bytes`, `b64Json`, and a nullable `mediaType`. The API may omit the media type; the client does not infer one or fabricate image IDs or a model ID. Usage and cost are available when reported by the provider. Treat output as untrusted: in particular, an SVG is data and should not be executed as HTML. The examples do not fetch returned URLs or render SVG.

## Cancellation and resource limits

Pass a `CancellationToken` to `generate`, `stream`, or discovery. The client also accepts a credential resolver for token refresh; cancellation can stop waiting for a pending resolver. Cancellation or a transport error after dispatch does not prove that the provider stopped processing, so check provider records before retrying an uncertain, billable request. The client does not automatically repeat the image POST for a fallback.

Base64 and decoded image bytes consume memory. Set application-appropriate request, response, storage, and retention limits, particularly when requesting multiple or large images; the typed adapter does not impose an image-size cap. Store credentials and generated content according to your application's privacy requirements. Dispose the client with `close()` when finished; a client constructed with a borrowed transport leaves that transport open.


# Source: docs/openrouter-api-reference.md

# OpenRouter API inventory

Source: [OpenRouter OpenAPI](https://openrouter.ai/openapi.json), reviewed 2026-11-04, SHA-256 `08855d8f74f3f44be3b3007576d79aee13faa6ecf6fd5cd790fcd78b51e6a4fb`. The source declares the MIT license.

The pinned schema describes 144 operations across 106 paths. Chat completions, Responses and the three dedicated Image API operations have selected integrations; other operations are inventoried and not integrated.

The [machine-readable inventory](openrouter-api-inventory.json) records each operation, request, response, parameter and header contract, and each component field, union and constraint. Credential-shaped example values are redacted. Original-source and sanitized-snapshot hashes are separate. References point to the schema snapshot in `tool/contracts/openrouter/openapi.json`. A schema entry or native field forwarding does not establish supported runtime orchestration or model behavior.

Run `python3 tool/openrouter_contract.py --check` offline to verify the snapshot and generated outputs. `--upstream` compares the current official document without updating any files. See `tool/contracts/openrouter/README.md` for attribution and source provenance.

Chat `modalities` has selected normalized text/image support via typed options; image output uses completed JSON assistant messages, not undocumented streaming deltas. `image_config` is preserved as model-specific JSON. Audio output, streamed Chat images, and Responses modalities remain outside this integration. The dedicated Image API has separate typed request, discovery, SSE and buffered-fallback handling; endpoint paths use encoded model segments rather than following returned URLs. See [OpenRouter images](openrouter-images.md).

The pinned OpenAPI wraps image SSE events in `data`; the [official image guide](https://openrouter.ai/docs/guides/overview/multimodal/image-generation) shows direct events. Both forms are handled, with a separate buffered JSON fallback. Offline fixtures do not establish live provider or model behavior.

| Method | Path | Status |
| --- | --- | --- |
| GET | `/activity` | not-integrated |
| GET | `/analytics/meta` | not-integrated |
| POST | `/analytics/query` | not-integrated |
| POST | `/api/alpha/decisions` | not-integrated |
| POST | `/api/alpha/extractions` | not-integrated |
| POST | `/audio/speech` | not-integrated |
| POST | `/audio/transcriptions` | not-integrated |
| POST | `/auth/keys` | not-integrated |
| POST | `/auth/keys/code` | not-integrated |
| GET | `/batches` | not-integrated |
| POST | `/batches` | not-integrated |
| DELETE | `/batches/{id}` | not-integrated |
| GET | `/batches/{id}` | not-integrated |
| GET | `/benchmarks` | not-integrated |
| GET | `/byok` | not-integrated |
| POST | `/byok` | not-integrated |
| DELETE | `/byok/{id}` | not-integrated |
| GET | `/byok/{id}` | not-integrated |
| PATCH | `/byok/{id}` | not-integrated |
| POST | `/chat/completions` | integrated-selected-behavior |
| GET | `/classifications/task` | not-integrated |
| GET | `/containers/{container_id}/files` | not-integrated |
| GET | `/containers/{container_id}/files/{file_id}` | not-integrated |
| GET | `/containers/{container_id}/files/{file_id}/content` | not-integrated |
| POST | `/containers/{container_id}/files/{file_id}/promote` | not-integrated |
| GET | `/credits` | not-integrated |
| POST | `/credits/coinbase` | not-integrated |
| GET | `/datasets/app-rankings` | not-integrated |
| GET | `/datasets/rankings-daily` | not-integrated |
| GET | `/datasets/session-cost` | not-integrated |
| POST | `/embeddings` | not-integrated |
| GET | `/embeddings/models` | not-integrated |
| GET | `/endpoints/zdr` | not-integrated |
| GET | `/external-users` | not-integrated |
| POST | `/external-users` | not-integrated |
| DELETE | `/external-users/{user}` | not-integrated |
| GET | `/external-users/{user}` | not-integrated |
| PATCH | `/external-users/{user}` | not-integrated |
| GET | `/files` | not-integrated |
| POST | `/files` | not-integrated |
| DELETE | `/files/{file_id}` | not-integrated |
| GET | `/files/{file_id}` | not-integrated |
| GET | `/files/{file_id}/content` | not-integrated |
| GET | `/generation` | not-integrated |
| GET | `/generation/content` | not-integrated |
| POST | `/generation/feedback` | not-integrated |
| GET | `/guardrails` | not-integrated |
| POST | `/guardrails` | not-integrated |
| GET | `/guardrails/assignments/keys` | not-integrated |
| GET | `/guardrails/assignments/members` | not-integrated |
| DELETE | `/guardrails/{id}` | not-integrated |
| GET | `/guardrails/{id}` | not-integrated |
| PATCH | `/guardrails/{id}` | not-integrated |
| GET | `/guardrails/{id}/assignments/keys` | not-integrated |
| POST | `/guardrails/{id}/assignments/keys` | not-integrated |
| POST | `/guardrails/{id}/assignments/keys/remove` | not-integrated |
| GET | `/guardrails/{id}/assignments/members` | not-integrated |
| POST | `/guardrails/{id}/assignments/members` | not-integrated |
| POST | `/guardrails/{id}/assignments/members/remove` | not-integrated |
| POST | `/images` | integrated-selected-behavior |
| GET | `/images/models` | integrated-selected-behavior |
| GET | `/images/models/{author}/{slug}/endpoints` | integrated-selected-behavior |
| GET | `/key` | not-integrated |
| GET | `/keys` | not-integrated |
| POST | `/keys` | not-integrated |
| DELETE | `/keys/{hash}` | not-integrated |
| GET | `/keys/{hash}` | not-integrated |
| PATCH | `/keys/{hash}` | not-integrated |
| POST | `/messages` | not-integrated |
| GET | `/model/{author}/{slug}` | not-integrated |
| GET | `/models` | not-integrated |
| GET | `/models/count` | not-integrated |
| GET | `/models/user` | not-integrated |
| GET | `/models/{author}/{slug}/endpoints` | not-integrated |
| GET | `/oauth/jwks` | not-integrated |
| POST | `/oauth/token` | not-integrated |
| GET | `/observability/destinations` | not-integrated |
| POST | `/observability/destinations` | not-integrated |
| DELETE | `/observability/destinations/{id}` | not-integrated |
| GET | `/observability/destinations/{id}` | not-integrated |
| PATCH | `/observability/destinations/{id}` | not-integrated |
| GET | `/organization/members` | not-integrated |
| GET | `/organization/settings` | not-integrated |
| PATCH | `/organization/settings` | not-integrated |
| GET | `/presets` | not-integrated |
| GET | `/presets/{slug}` | not-integrated |
| POST | `/presets/{slug}/chat/completions` | not-integrated |
| POST | `/presets/{slug}/messages` | not-integrated |
| POST | `/presets/{slug}/responses` | not-integrated |
| GET | `/presets/{slug}/versions` | not-integrated |
| GET | `/presets/{slug}/versions/{version}` | not-integrated |
| GET | `/private-endpoints` | not-integrated |
| POST | `/private-endpoints` | not-integrated |
| DELETE | `/private-endpoints/{id}` | not-integrated |
| GET | `/private-endpoints/{id}` | not-integrated |
| PATCH | `/private-endpoints/{id}` | not-integrated |
| POST | `/private-endpoints/{id}/activate` | not-integrated |
| POST | `/private-endpoints/{id}/disable` | not-integrated |
| POST | `/private-endpoints/{id}/enable` | not-integrated |
| POST | `/private-endpoints/{id}/validate` | not-integrated |
| GET | `/private-providers` | not-integrated |
| POST | `/private-providers` | not-integrated |
| DELETE | `/private-providers/{slug}` | not-integrated |
| GET | `/private-providers/{slug}` | not-integrated |
| PATCH | `/private-providers/{slug}` | not-integrated |
| GET | `/providers` | not-integrated |
| POST | `/rerank` | not-integrated |
| POST | `/responses` | integrated-selected-behavior |
| GET | `/scim/group-mappings` | not-integrated |
| POST | `/scim/group-mappings` | not-integrated |
| DELETE | `/scim/group-mappings/{id}` | not-integrated |
| GET | `/scim/group-mappings/{id}` | not-integrated |
| PATCH | `/scim/group-mappings/{id}` | not-integrated |
| GET | `/scim/groups` | not-integrated |
| POST | `/scim/sync-jobs` | not-integrated |
| GET | `/scim/sync-jobs/{id}` | not-integrated |
| POST | `/systemone` | not-integrated |
| GET | `/tools` | not-integrated |
| GET | `/tools/{name}` | not-integrated |
| GET | `/vault/interns/{internId}/connections` | not-integrated |
| GET | `/vault/interns/{internId}/effective-secrets` | not-integrated |
| GET | `/vault/interns/{internId}/secrets` | not-integrated |
| POST | `/vault/interns/{internId}/secrets/copy` | not-integrated |
| DELETE | `/vault/interns/{internId}/secrets/{name}` | not-integrated |
| PUT | `/vault/interns/{internId}/secrets/{name}` | not-integrated |
| GET | `/vault/secrets` | not-integrated |
| DELETE | `/vault/secrets/{name}` | not-integrated |
| PUT | `/vault/secrets/{name}` | not-integrated |
| POST | `/videos` | not-integrated |
| GET | `/videos/models` | not-integrated |
| GET | `/videos/{jobId}` | not-integrated |
| GET | `/videos/{jobId}/content` | not-integrated |
| GET | `/workspaces` | not-integrated |
| POST | `/workspaces` | not-integrated |
| DELETE | `/workspaces/{id}` | not-integrated |
| GET | `/workspaces/{id}` | not-integrated |
| PATCH | `/workspaces/{id}` | not-integrated |
| GET | `/workspaces/{id}/members` | not-integrated |
| POST | `/workspaces/{id}/members/add` | not-integrated |
| POST | `/workspaces/{id}/members/remove` | not-integrated |
| GET | `/workspaces/{workspace_ref}/budgets` | not-integrated |
| DELETE | `/workspaces/{workspace_ref}/budgets/{interval}` | not-integrated |
| GET | `/workspaces/{workspace_ref}/budgets/{interval}` | not-integrated |
| PUT | `/workspaces/{workspace_ref}/budgets/{interval}` | not-integrated |


# Source: docs/together.md

# Use Together Chat Completions

`agent_weave_together` provides a native Together Chat Completions client and a
`ChatModel` adapter. The agent runtime owns tool execution, approvals, and
history. Model support for tools, schemas, images, video, and audio varies.

## Run a backend request

From the workspace root, run `dart pub get`. Save this example as
`examples/together_demo.dart`. Set `TOGETHER_API_KEY` and `TOGETHER_MODEL` in
your backend environment, choosing a model available to your account. Running
the example makes a paid provider request. Keep the key on the backend.

```dart
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_together/agent_weave_together.dart' as together;

Future<void> main() async {
  final key = Platform.environment['TOGETHER_API_KEY'];
  final modelId = Platform.environment['TOGETHER_MODEL'];
  if (key == null || modelId == null) {
    throw StateError('Set TOGETHER_API_KEY and TOGETHER_MODEL.');
  }
  final client = together.TogetherClient(apiKey: key);
  try {
    final model = together.TogetherChatModel(
      client: client,
      model: modelId,
      options: together.TogetherChatOptions(temperature: 0.3),
    );
    final result = await generateText(model: model, prompt: 'Say hello.');
    print(result.text);
  } finally {
    client.close();
  }
}
```

Run `dart run examples/together_demo.dart` to print the response. The same
model works with `AiAgent` and its registered tools, approvals, schema output,
and history. See [tools and approvals](tools.md) and the
[Dart API guide](dart-api.md).

## Choose typed options or native JSON

See [all reviewed request fields](together-options.md) for their Dart entry points.

`TogetherChatOptions` snapshots its input values and exposes typed options,
including enums for compliance, context length behavior, and reasoning effort.
`logprobs` is an integer from 0 to 20. The runtime owns `max_tokens` through
`ModelRequest.maxOutputTokens` or the corresponding agent setting. The agent
adapter requests one choice (`n: 1`).

For multiple choices (`n > 1`), legacy `function_call`, or other native fields,
use `TogetherClient.createChat` or `streamChat` with native JSON. These methods
return native JSON; `streamChat` sets `stream: true`. The agent adapter does not
normalize legacy function calls. Native JSON access does not establish support
for every Together operation.

The agent adapter rejects document inputs. Inline audio must be WAV. Image,
video, audio, tool, and schema acceptance depends on the selected model.

## Handle requests and errors

The default request timeout is two minutes for the entire HTTP request. Set
`requestTimeout` on `TogetherClient` to change it. Timeout and a user-provided
`CancellationToken` abort the HTTP request. Cancelling a native stream
subscription also aborts that request without closing the shared client. The client does not automatically
retry POST requests. Close the `TogetherClient` when finished. If you inject an
HTTP client, you own and must close that HTTP client.

A `TogetherException` provides `statusCode`, `requestId`, and optional JSON
`details` to trusted backend code. Its `toString()` omits provider response
bodies. Do not expose a provider error's cause or details to the UI; they can
contain private data. Protect logs and avoid logging request or response bodies.

A `length` finish returns partial text with `finishReason: 'length'`. Truncated
tool calls fail rather than execute. Choose output limits appropriate to your
application and handle partial results.

## Review the pinned contract

The AST-generated [chat inventory](together-chat-inventory.json) records 27
top-level request fields and their dispositions for the pinned declaration. It
is an inventory, not a certification of nested fields, response handling,
lifecycle, models, or other operations. The pin is in
`tool/contracts/together/source.json`; dispositions are in
`tool/contracts/together/coverage.json`. Headers and query parameters are
captured as maps; this does not claim coverage of every operation.

From the repository root, install the inventory tool dependencies and run the
checks:

```sh
npm ci --prefix tool/interop --ignore-scripts --no-audit --no-fund
dart run tool/together_contract.dart
node tool/interop/inventory.mjs --check
```

`node tool/interop/inventory.mjs --upstream` compares the pinned files with
upstream main. Review changes before running `--write` to update the inventory.
Offline fixtures cover selected requests and streams. No live Together request,
model acceptance, or billing has been verified.

The normal checks include an independent, runnable offline consumer:

```sh
dart --enable-asserts run examples/review_cases/together.dart
```

It exercises a real loopback HTTP service, schema output, tool approval and
continuation, private reasoning replay, partial output and backend diagnostics.
Response log probabilities, prompt echoes, warnings and arbitrary provider
metadata are available through the raw native client and are not normalized into
`AgentResult`. Message names and URL audio also require native requests.


# Source: docs/cloudflare.md

# Cloudflare Workers AI and AI Gateway

`agent_weave_cloudflare` provides REST clients and selected model adapters. The
contracts below are distinct; a model's support for one does not establish its
support for another. Model availability, options, pricing, gateway behavior and
live inference have not been verified by the offline fixtures.

| Contract | Client | Request |
| --- | --- | --- |
| Workers AI native | `CloudflareClient` | `POST /accounts/{accountId}/ai/run/{model}` with model-specific input |
| Gateway run | `CloudflareGatewayClient` | `POST /accounts/{accountId}/ai/run` wrapping `model`, `input`, and optional `options` |
| Compatible Chat | `CloudflareCompatibleClient` | `/accounts/{accountId}/ai/v1/chat/completions` |
| Compatible Responses | `CloudflareCompatibleClient` | `/accounts/{accountId}/ai/v1/responses` |

The native client also exposes `getModelSchema`, `listModels`, raw JSON, bytes,
and SSE methods. Raw methods preserve status, headers, bytes and, when present,
JSON; they do not validate every model's schema. Gateway options can be passed
to the gateway and compatible clients. `@cf/` models require a gateway ID for
the gateway run contract. The compatible endpoints have separate payloads and
stream semantics; select the adapter supported by the chosen model.

## Start a backend chat

Set `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_API_TOKEN` and
`CLOUDFLARE_CHAT_MODEL` for a model available to your account. For Workers AI
models routed through Gateway, also set `CLOUDFLARE_GATEWAY_ID`.
The API token needs Account > Workers AI > Read permission, including when
calling third-party models. AI Gateway management permission alone is insufficient.

The complete `examples/cloudflare_demo.dart` program is:

```dart
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_cloudflare/agent_weave_cloudflare.dart' as cf;

Future<void> main() async {
  final accountId = Platform.environment['CLOUDFLARE_ACCOUNT_ID'];
  final apiToken = Platform.environment['CLOUDFLARE_API_TOKEN'];
  final modelId = Platform.environment['CLOUDFLARE_CHAT_MODEL'];
  final gatewayId = Platform.environment['CLOUDFLARE_GATEWAY_ID'];
  if (accountId == null || apiToken == null || modelId == null) {
    throw StateError(
      'Set CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_API_TOKEN and CLOUDFLARE_CHAT_MODEL.',
    );
  }
  if (modelId.startsWith('@cf/') && gatewayId == null) {
    throw StateError(
      'Set CLOUDFLARE_GATEWAY_ID for Workers AI gateway requests.',
    );
  }
  final workers = cf.CloudflareClient.withApiToken(
    accountId: accountId,
    apiToken: apiToken,
    gateway: gatewayId == null
        ? null
        : cf.CloudflareGatewayOptions(gatewayId: gatewayId),
  );
  try {
    final model = cf.CloudflareCompatibleChatModel(
      client: cf.CloudflareCompatibleClient(client: workers),
      model: modelId,
    );
    final result = await generateText(model: model, prompt: 'Say hello.');
    print(result.text);
  } finally {
    workers.close();
  }
}
```

Run `dart run examples/cloudflare_demo.dart` from the workspace. It sends a real
inference request and may incur charges. This example was analyzed and compiled,
but not run against Cloudflare. Keep credentials on the backend.

For rotating secrets, construct `CloudflareClient` with an application-owned
`tokenResolver`. It runs per request within that request's timeout. Requests
use Bearer authorization. The optional client `gateway` supplies default
Gateway headers to native inference and compatible endpoints; explicit
request-level Gateway options override matching defaults. A model-in-path
request can therefore carry the gateway ID needed for prepaid Gateway billing.
Actual billing behavior has not been tested.

Gateway options include cache key, TTL, bypass, metadata, timeout and retry
headers. A cache key can group responses: choose it with the application's data
isolation and privacy requirements in mind. Custom Gateway headers cannot
override authentication or built-in option headers. The client does not retry
POSTs itself; Gateway retry headers request gateway-side behavior.

With an application-owned `workers` client, native inference is separate from
the compatible Chat adapter:

```dart
final embeddings = await cf.CloudflareEmbeddingModel(client: workers).embed(
  cf.CloudflareEmbeddingRequest(text: ['hello'], pooling: cf.CloudflarePooling.cls),
);
print(embeddings.vectors);
print(embeddings.pooling); // Actual returned pooling, never an inferred default.

final gateway = cf.CloudflareGatewayClient(client: workers);
final response = await gateway.runJson(
  modelId,
  {'messages': [{'role': 'user', 'content': 'Hello'}]},
  gateway: cf.CloudflareGatewayOptions(gatewayId: gatewayId),
);
print(response.json);
```

## Model adapters

- `CloudflareEmbeddingModel` supports the BGE `text` input and optional
  `CloudflarePooling.mean` or `.cls`. Its result exposes `vectors`, `shape`,
  returned `pooling`, `result`, and the full `response`.
- `CloudflareTranscriptionModel` accepts `CloudflareAudioInput.json` for
  model-specific JSON or `.bytes` for binary input, with a configurable content
  type defaulting to `application/octet-stream`. The exact binary REST content
  type and server acceptance have not been live verified. The result exposes
  text and raw result data.
- `CloudflareImageModel` accepts model-specific JSON. It returns image bytes for
  image content types and decodes the base64 `result.image` for Flux Schnell;
  retain `response` for raw JSON and metadata. Unknown formats require raw
  client inspection. Image format and model acceptance remain model-specific.

For an agent, prefer `CloudflareCompatibleChatModel` with an explicitly chosen,
currently available compatible model, configured by the application (for
example via an environment variable). `CloudflareCompatibleResponsesModel`
uses the separate Responses contract. Both expose `options` and an SDK-typed
`configure` callback; request-owned fields cannot be overridden through
`options`. Compatible Chat defaults to `max_completion_tokens`; select
`CloudflareChatTokenField.maxTokens` for models requiring `max_tokens`.

For example, configure the compatible Chat adapter with a model supplied by the
application:

```dart
final compatible = cf.CloudflareCompatibleClient(client: workers);
final chat = cf.CloudflareCompatibleChatModel(
  client: compatible,
  model: compatibleModelFromEnvironment,
);
```

`CloudflareChatModel` requires an explicit model and implements the documented
Hermes traditional single-tool continuation. Text-only requests stream native
SSE responses by default; set `streamText: false` for models that require
buffered text. Streams must include a text response and the `[DONE]` marker.
When complete token counts are reported in multiple stream frames, the adapter
emits the latest complete counts once at `[DONE]`; partial counts are omitted.
JSON schema requests and requests with registered tools or tool history remain
buffered. Cloudflare documents that [JSON mode does not support streaming](https://developers.cloudflare.com/workers-ai/features/json-mode/).
The native `response` chunks and `[DONE]` framing follow
[Cloudflare's streaming example](https://blog.cloudflare.com/workers-ai-streaming/);
that older article does not prove current catalog availability. Use the
[current model catalog](https://developers.cloudflare.com/workers-ai/models/)
to choose a model; the adapter does not download or select one automatically.
The adapter accepts text parts and rejects multi-call continuation. Its
structured-output mode sends a bare JSON schema. Availability of the legacy Hermes model has not been verified; do not
assume that another native model supports this continuation format. Tool
execution and approvals remain the runtime's responsibility.

## Lifecycle and evidence

Pass a `CancellationToken` to client methods and model operations as needed.
Request timeouts include preparation; cancellation cannot undo an operation
already accepted remotely. Close the client when done. An injected transport
or HTTP client remains caller-owned. Cancelling one subscription signals that invocation without cancelling sibling
calls sharing its parent token. Cancelling the parent signals all active calls.
Streaming subscription cancellation aborts the request when supported by the
underlying HTTP client. No license acceptance
or paid inference occurs automatically.

Offline fixtures exercise selected request and response behavior, not live model
availability, full API parity, provider billing, or server acceptance. Consult
[Workers AI REST](https://developers.cloudflare.com/workers-ai/get-started/rest-api/),
[function calling](https://developers.cloudflare.com/workers-ai/features/function-calling/),
[JSON mode](https://developers.cloudflare.com/workers-ai/features/json-mode/), and
[AI Gateway REST](https://developers.cloudflare.com/ai-gateway/usage/rest-api/)
for current provider requirements. See [provider coverage](provider-coverage.md)
and [compatibility](compatibility.md) for the scope of this integration. The
[API inventory reference](cloudflare-api-reference.md) records the classified
contracts; it is not a parity certificate. The inventory includes management
endpoints that are not integrated. Compatible endpoint documentation is tracked
separately from the pinned API specification.


# Source: docs/cloudflare-api-reference.md

# Cloudflare API inventory

Source: [Cloudflare OpenAPI](https://raw.githubusercontent.com/cloudflare/api-schemas/193e683baba9c46b675d91c959c3b9a726b2d184/openapi.json), revision `193e683baba9c46b675d91c959c3b9a726b2d184`, reviewed 2026-11-04.

The pinned schema contains 82 operations across 50 Workers AI and AI Gateway paths. Four operations have selected AgentWeave integrations. The rest remain explicitly unimplemented.

Download the [machine-readable inventory](cloudflare-api-inventory.json) for nested request and response fields, unions, required flags, defaults, enum values and parameter constraints. These are specification entries, not claims that AgentWeave executes every option.

Model documentation schemas are attributed to Cloudflare under CC BY 4.0, with unmodified snapshots and generated field inventories. The OpenAPI source is BSD-3-Clause. See the retained licenses and attribution in `tool/contracts/cloudflare/README.md`.

The complete selected source schemas and BSD license are retained in `tool/contracts/cloudflare/`. Run `python3 tool/cloudflare_contract.py --check` offline. Refresh with `--extract /path/to/official/openapi.json` only after reviewing the revision and upstream changes. New operations receive `not-integrated` status automatically.

See [Cloudflare usage](cloudflare.md) for auth, native model inputs, compatible protocols, cancellation and known limits.

## OpenAPI operations

| Method | Path | AgentWeave status |
| --- | --- | --- |
| GET | `/accounts/{account_id}/ai-gateway/billing/credit-balance` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/billing/invoice-history` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/billing/invoice-preview` | not-integrated |
| DELETE | `/accounts/{account_id}/ai-gateway/billing/spending-limit` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/billing/spending-limit` | not-integrated |
| POST | `/accounts/{account_id}/ai-gateway/billing/spending-limit` | not-integrated |
| POST | `/accounts/{account_id}/ai-gateway/billing/topup` | not-integrated |
| DELETE | `/accounts/{account_id}/ai-gateway/billing/topup/config` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/billing/topup/config` | not-integrated |
| POST | `/accounts/{account_id}/ai-gateway/billing/topup/config` | not-integrated |
| POST | `/accounts/{account_id}/ai-gateway/billing/topup/eligibility` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/billing/topup/limits` | not-integrated |
| POST | `/accounts/{account_id}/ai-gateway/billing/topup/status` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/billing/usage-history` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/custom-providers` | not-integrated |
| POST | `/accounts/{account_id}/ai-gateway/custom-providers` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/custom-providers/costs` | not-integrated |
| POST | `/accounts/{account_id}/ai-gateway/custom-providers/costs` | not-integrated |
| DELETE | `/accounts/{account_id}/ai-gateway/custom-providers/costs/{id}` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/custom-providers/costs/{id}` | not-integrated |
| PATCH | `/accounts/{account_id}/ai-gateway/custom-providers/costs/{id}` | not-integrated |
| DELETE | `/accounts/{account_id}/ai-gateway/custom-providers/{id}` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/custom-providers/{id}` | not-integrated |
| PATCH | `/accounts/{account_id}/ai-gateway/custom-providers/{id}` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/evaluation-types` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways` | not-integrated |
| POST | `/accounts/{account_id}/ai-gateway/gateways` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/custom-domains` | not-integrated |
| POST | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/custom-domains` | not-integrated |
| DELETE | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/custom-domains/{hostname}` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/custom-domains/{hostname}` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/datasets` | not-integrated |
| POST | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/datasets` | not-integrated |
| DELETE | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/datasets/{id}` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/datasets/{id}` | not-integrated |
| PUT | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/datasets/{id}` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/evaluations` | not-integrated |
| POST | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/evaluations` | not-integrated |
| DELETE | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/evaluations/{id}` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/evaluations/{id}` | not-integrated |
| DELETE | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/logs` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/logs` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/logs/{id}` | not-integrated |
| PATCH | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/logs/{id}` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/logs/{id}/request` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/logs/{id}/response` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/provider_configs` | not-integrated |
| POST | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/provider_configs` | not-integrated |
| DELETE | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/provider_configs/{id}` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/provider_configs/{id}` | not-integrated |
| PUT | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/provider_configs/{id}` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/routes` | not-integrated |
| POST | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/routes` | not-integrated |
| DELETE | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/routes/{id}` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/routes/{id}` | not-integrated |
| PATCH | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/routes/{id}` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/routes/{id}/deployments` | not-integrated |
| POST | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/routes/{id}/deployments` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/routes/{id}/versions` | not-integrated |
| POST | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/routes/{id}/versions` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/routes/{id}/versions/{version_id}` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/url/{provider}` | not-integrated |
| DELETE | `/accounts/{account_id}/ai-gateway/gateways/{id}` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/gateways/{id}` | not-integrated |
| PUT | `/accounts/{account_id}/ai-gateway/gateways/{id}` | not-integrated |
| GET | `/accounts/{account_id}/ai-gateway/logging-state` | not-integrated |
| PATCH | `/accounts/{account_id}/ai-gateway/logging-state` | not-integrated |
| GET | `/accounts/{account_id}/ai/authors/search` | not-integrated |
| GET | `/accounts/{account_id}/ai/finetunes` | not-integrated |
| POST | `/accounts/{account_id}/ai/finetunes` | not-integrated |
| GET | `/accounts/{account_id}/ai/finetunes/public` | not-integrated |
| DELETE | `/accounts/{account_id}/ai/finetunes/{finetune_id}` | not-integrated |
| POST | `/accounts/{account_id}/ai/finetunes/{finetune_id}/finetune-assets` | not-integrated |
| GET | `/accounts/{account_id}/ai/finetunes/{finetune_id}/finetune-assets/{file_name}` | not-integrated |
| GET | `/accounts/{account_id}/ai/models/schema` | integrated-selected-behavior |
| GET | `/accounts/{account_id}/ai/models/search` | integrated-selected-behavior |
| POST | `/accounts/{account_id}/ai/run` | integrated-selected-behavior |
| POST | `/accounts/{account_id}/ai/run/{model_name}` | integrated-selected-behavior |
| GET | `/accounts/{account_id}/ai/tasks/search` | not-integrated |
| POST | `/accounts/{account_id}/ai/tomarkdown` | not-integrated |
| GET | `/accounts/{account_id}/ai/tomarkdown/supported` | not-integrated |
| POST | `/accounts/{account_id}/ai/websearch` | not-integrated |

## Compatible endpoints outside this specification

The public [Gateway REST guide](https://developers.cloudflare.com/ai-gateway/usage/rest-api/) documents the following endpoints. Their request/response types are not in the pinned OpenAPI. Chat and Responses have separate offline continuation fixtures; Messages is not implemented. Model-specific feature availability still applies.

| Method | Path | AgentWeave status |
| --- | --- | --- |
| POST | `/accounts/{account_id}/ai/v1/chat/completions` | integrated-selected-behavior |
| POST | `/accounts/{account_id}/ai/v1/responses` | integrated-selected-behavior |
| POST | `/accounts/{account_id}/ai/v1/messages` | not-integrated |

## Selected public model schemas

The inventory retains the full input/output JSON schema for BGE base English, Whisper and Flux Schnell. Public documentation URLs are unversioned. Each downloaded snapshot has a SHA-256 hash; they are not attributed to the OpenAPI Git revision.

| Snapshot | Official source | SHA-256 |
| --- | --- | --- |
| `bge-input.json` | [Schema](https://developers.cloudflare.com/workers-ai/models/bge-base-en-v1.5/sync-input.json) | `0291aab34abe8e4657ead038aba73f37098ab8f94888e7d99e4791a4adfcb353` |
| `bge-output.json` | [Schema](https://developers.cloudflare.com/workers-ai/models/bge-base-en-v1.5/sync-output.json) | `4f25a95d82f8b25fb9f386fc35b1ee244fa7437a7fc75db7506aa66daa6d9541` |
| `whisper-input.json` | [Schema](https://developers.cloudflare.com/workers-ai/models/whisper/schema-input.json) | `e82ea39d3b7aef1058accc4e5a5c27c5817b30f16cd9c04a6cb6eded41edb944` |
| `whisper-output.json` | [Schema](https://developers.cloudflare.com/workers-ai/models/whisper/schema-output.json) | `d6f939cc1591e5f6176e1e0a7d64ac8b976d0c55d9fdba9b435d260c1710a2da` |
| `flux-input.json` | [Schema](https://developers.cloudflare.com/workers-ai/models/flux-1-schnell/schema-input.json) | `d17b781a278e8f00233de3c93b1ac73ed07ba609204674338749c1df38c16b17` |
| `flux-output.json` | [Schema](https://developers.cloudflare.com/workers-ai/models/flux-1-schnell/schema-output.json) | `5528a6a3b29dec4480fd67a9d695300ad5616c54372afb51988ee660c87a32c6` |

Whisper declares a binary-string input variant, but this schema does not establish an accepted REST Content-Type. The typed binary path has serialization tests only. Native `/run` model schemas vary; forwarding raw fields does not certify those models.

Model schemas, Gateway request headers, Workers bindings, asynchronous batch APIs and compatible endpoints require separate reviews when the OpenAPI omits them. No live Cloudflare calls were made for this inventory.


# Source: docs/vercel-gateway.md

# Use Vercel AI Gateway

`agent_weave_vercel_gateway` provides `GatewayChatModel` for the public Chat
Completions endpoint and `GatewayResponsesModel` for the public Responses
endpoint. They use different request and stream formats. Neither uses the
internal Vercel AI SDK V4 language-model wire protocol.

## Send a request

From the workspace root, run `dart pub get`. Save the following as
`examples/gateway_demo.dart`. Set `GATEWAY_API_KEY`, `GATEWAY_MODEL`, and
`GATEWAY_PROVIDER` in your backend environment. Choose a model and a provider
available to your account. Running the example makes a paid request.

```dart
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_vercel_gateway/agent_weave_vercel_gateway.dart' as gateway;

Future<void> main() async {
  final key = Platform.environment['GATEWAY_API_KEY'];
  final modelId = Platform.environment['GATEWAY_MODEL'];
  final provider = Platform.environment['GATEWAY_PROVIDER'];
  if (key == null || modelId == null || provider == null) {
    throw StateError('Set GATEWAY_API_KEY, GATEWAY_MODEL, and GATEWAY_PROVIDER.');
  }
  final client = gateway.GatewayClient.withApiKey(apiKey: key);
  try {
    final model = gateway.GatewayChatModel(
      client: client,
      model: modelId,
      options: gateway.GatewayOptions(order: [provider]),
    );
    final result = await generateText(model: model, prompt: 'Say hello.');
    print(result.text);
  } finally {
    client.close();
  }
}
```

Run `dart run examples/gateway_demo.dart`. The response prints to the terminal.
To use Responses, replace `GatewayChatModel` with `GatewayResponsesModel`.
The same models work with `AiAgent` and its tools, approvals, and stored
history. See the [Dart API guide](dart-api.md).

## Resolve credentials per request

For a rotating Gateway token or bring-your-own-key (BYOK) credentials, use a
resolver. This example reads the environment each time the client makes a
request. Save it as `examples/gateway_byok_demo.dart`, and set
`GATEWAY_API_KEY`, `GATEWAY_MODEL`, and `ANTHROPIC_API_KEY` on the backend.
Choose a model available through the Anthropic provider. Running the example
makes a paid request.

```dart
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_vercel_gateway/agent_weave_vercel_gateway.dart' as gateway;

String requiredEnvironment(String name) {
  final value = Platform.environment[name];
  if (value == null || value.isEmpty) throw StateError('Set $name.');
  return value;
}

Future<void> main() async {
  final modelId = requiredEnvironment('GATEWAY_MODEL');
  final client = gateway.GatewayClient(
    credentialResolver: () => gateway.GatewayCredentials(
      token: requiredEnvironment('GATEWAY_API_KEY'),
      byok: {
        'anthropic': [
          {'apiKey': requiredEnvironment('ANTHROPIC_API_KEY')},
        ],
      },
    ),
  );
  try {
    final model = gateway.GatewayResponsesModel(client: client, model: modelId);
    final result = await generateText(model: model, prompt: 'Say hello.');
    print(result.text);
  } finally {
    client.close();
  }
}
```

Replace the environment reads with your backend secret manager to rotate
credentials while the process runs. BYOK credential fields differ by provider.
Credentials belong in `GatewayCredentials`, not `GatewayOptions` or ordinary
`providerOptions`.

## Options and raw responses

`GatewayOptions` serializes routing preferences such as `models`, `order`, and
`only`, plus cache, timeout, privacy, and other fields. Both models also accept
provider-specific JSON through `providerOptions`. Serialization fixtures do not
prove that the live Gateway or a selected provider accepts or honors each field,
nor do they establish cost or billing behavior.

For native JSON, use `GatewayClient.createChat`, `streamChat`, `createResponse`,
or `streamResponse`. Nonstreaming results include native JSON, status, and
headers. Streams expose event envelopes and retain unknown metadata. Model
adapters normalize a limited set of fields; they do not invent a selected
provider identity from unverified metadata.

Responses accepts document URLs and inline data, but the high-level Gateway
adapter blocks file IDs. Chat does not accept documents or audio output. Model
and provider input support varies. See [documents](documents.md).

## Request lifetime and privacy

Credential resolution runs inside each request's deadline. The default total
deadline is two minutes; configure `requestTimeout` on `GatewayClient` or its
transport. A cancellation token or expired deadline prevents a late credential
resolver from dispatching the request. Close the Gateway client at shutdown.
`GatewayClient.withTransport` borrows its transport, and an injected HTTP client
is also caller-owned. Close borrowed resources yourself.

Errors are redacted using the request's credentials. Treat raw error details and
backend logs as private, and never send credentials or provider error details to
clients. AgentWeave stores model content in history, not request credentials.
A provider could still echo a secret in its model output, so the application
must protect any content it sends or stores.

Offline fixtures cover selected request and stream behavior, including Chat
continuation. Live Gateway behavior, provider selection, model acceptance, and
billing have not been verified. See [provider coverage](provider-coverage.md).

## Track option updates

The generated [option reference](gateway-options.md) maps 16 named options from
the pinned official SDK to their Dart entry points. It distinguishes typed
routing, request credentials, native extensions and SDK-only features. This is
an update-review aid, not proof of public endpoint or model behavior.

Use `GatewayCaching`, `GatewayServiceTier`, and `GatewayProviderSort` for fixed
option values. Unrepresented service-owned fields can use `GatewayOptions.extra`;
it rejects credentials, typed-field replacement and client-only image decoding.
Conditional Decisions fallbacks, batch jobs and image decoding are not implemented
by these Chat/Responses adapters.

After `npm ci --prefix tool/interop --ignore-scripts`, reproduce the field check:

```sh
dart run tool/gateway_contract.dart
node tool/interop/gateway-inventory.mjs --check
```

The independent consumer exercise is also runnable without a provider key:

```sh
dart --enable-asserts run examples/review_cases/gateway.dart
```


# Source: docs/gateway-options.md

# Gateway option reference

Generated from Vercel's SDK commit `6adf8c797d5e2bf056c077f946aa12dabb3cb268`. This is an
option inventory, not a certificate of public endpoint behavior. Read the
[Gateway guide](vercel-gateway.md) for setup and limits.

| Wire option | Dart entry point | Disposition |
| --- | --- | --- |
| byok | GatewayCredentials.byok via credentialResolver | request-credentials |
| caching | GatewayOptions.caching | typed-option |
| experimental_streamingImageDecoding | Not sent; image decoding is outside Chat/Responses | sdk-client-only |
| disallowPromptTraining | GatewayOptions.disallowPromptTraining | typed-option |
| has | GatewayOptions.has | typed-option |
| idempotencyKey | GatewayOptions.extra; no batch lifecycle implementation | native-extension |
| models | GatewayOptions.models; string fallbacks only | typed-option |
| only | GatewayOptions.only | typed-option |
| order | GatewayOptions.order | typed-option |
| providerTimeouts | GatewayOptions.byokProviderTimeouts | typed-option |
| quotaEntityId | GatewayOptions.quotaEntityId | typed-option |
| serviceTier | GatewayOptions.serviceTier | typed-option |
| sort | GatewayOptions.sort | typed-option |
| tags | GatewayOptions.tags | typed-option |
| user | GatewayOptions.user | typed-option |
| zeroDataRetention | GatewayOptions.zeroDataRetention | typed-option |

The public Chat and Responses extension uses `providerOptions.gateway`.
BYOK credentials are resolved per request and are excluded from ordinary option
serialization. Unknown service-owned options can use `GatewayOptions.extra`;
that does not prove their endpoint applicability. Conditional decision fallbacks
and the SDK's image decoder are outside these adapters.

See the [machine-readable inventory](gateway-options-inventory.json). Do not
edit this generated page by hand; review the pin and run
`node tool/interop/gateway-inventory.mjs --write`.


# Source: docs/together-options.md

# Together chat request fields

Generated from the reviewed [contract inventory](together-chat-inventory.json) at
Together SDK commit `488006d90b67d589034d8323a11cfab9b588abca`. Do not edit this table by hand;
review the source pin and run `node tool/interop/inventory.mjs --write`.

The agent adapter owns conversation history, tools, schema and execution bounds.
Use the native JSON client where indicated. A field disposition does not prove
nested semantics, model acceptance, or coverage of other endpoints. See the
[Together guide](together.md) for complete setup, errors and known limits.

| Wire field | Dart entry point or runtime behavior | Disposition |
| --- | --- | --- |
| messages | ModelRequest.messages and instructions | runtime-owned |
| model | TogetherChatModel.model | runtime-owned |
| chat_template_kwargs | TogetherChatOptions.chatTemplateKwargs | typed-option |
| compliance | TogetherChatOptions.compliance | typed-option |
| context_length_exceeded_behavior | TogetherChatOptions.contextLengthExceededBehavior | typed-option |
| echo | TogetherChatOptions.echo | typed-option |
| frequency_penalty | TogetherChatOptions.frequencyPenalty | typed-option |
| function_call | TogetherClient.createChat/streamChat | native-only |
| logit_bias | TogetherChatOptions.logitBias | typed-option |
| logprobs | TogetherChatOptions.logprobs | typed-option |
| max_tokens | ModelRequest.maxOutputTokens | runtime-owned |
| min_p | TogetherChatOptions.minP | typed-option |
| n | fixed to one completion in the agent adapter | runtime-owned |
| presence_penalty | TogetherChatOptions.presencePenalty | typed-option |
| reasoning | TogetherChatOptions.reasoningEnabled | typed-option |
| reasoning_effort | TogetherChatOptions.reasoningEffort | typed-option |
| repetition_penalty | TogetherChatOptions.repetitionPenalty | typed-option |
| response_format | ModelRequest.outputSchema | runtime-owned |
| safety_model | TogetherChatOptions.safetyModel | typed-option |
| seed | TogetherChatOptions.seed | typed-option |
| stop | TogetherChatOptions.stop | typed-option |
| stream | fixed to true in the agent adapter | runtime-owned |
| temperature | TogetherChatOptions.temperature | typed-option |
| tool_choice | TogetherChatOptions.toolChoice | typed-option |
| tools | registered ModelTool definitions | runtime-owned |
| top_k | TogetherChatOptions.topK | typed-option |
| top_p | TogetherChatOptions.topP | typed-option |

The native client accepts arbitrary JSON fields; it does not statically validate
the whole provider API. Typed options cover common agent requests. Native response
metadata is available from raw methods; not all fields are normalized by the agent.


# Source: docs/anthropic.md

# Anthropic Messages

Use `AnthropicNativeClient` for native JSON and SSE access, including fields the
pinned Dart SDK does not know. Its `chatModel` also integrates supported
Messages streams with AgentWeave's text, structured output and tool loop. The
package is independent and unofficial.

## Run the example

From the workspace, set `ANTHROPIC_API_KEY` and `ANTHROPIC_MODEL` in the
backend environment, then run `dart run examples/anthropic_demo.dart`. Optionally
set `ANTHROPIC_VERSION`; it defaults to `2023-06-01` for backwards
compatibility. The example requests adaptive thinking, caching and structured
output, so choose a model and API version that support that combination. It
makes a billable request. See [Anthropic's versioning documentation](https://docs.anthropic.com/en/api/versioning)
and verify the current model and feature requirements before selecting a newer
version.

The example's `configure` receives a read-only JSON snapshot. Return a new map,
as it does with `...body`. The agent owns messages, max tokens, system
instructions and tools, and protects the runtime output schema. You can add
supported native options without replacing these values; this does not imply
AgentWeave implements the behavior of every forwarded field.

```dart
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_anthropic/agent_weave_anthropic.dart' as anthropic;

Future<void> main() async {
  final apiKey = Platform.environment['ANTHROPIC_API_KEY'];
  final modelId = Platform.environment['ANTHROPIC_MODEL'];
  if (apiKey == null || apiKey.isEmpty || modelId == null || modelId.isEmpty) {
    throw StateError('Set ANTHROPIC_API_KEY and ANTHROPIC_MODEL.');
  }
  final client = anthropic.AnthropicNativeClient.withApiKey(
    apiKey: apiKey,
    apiVersion: Platform.environment['ANTHROPIC_VERSION'] ?? '2023-06-01',
  );
  try {
    final model = client.chatModel(
      model: modelId,
      configure: (body) => {
        ...body,
        'thinking': {'type': 'adaptive'},
        'cache_control': {'type': 'ephemeral'},
      },
    );
    final result = await generateObject<String>(
      model: model,
      prompt: 'Give one concise title for a guide to growing herbs indoors.',
      schema: const {
        'type': 'object',
        'properties': {
          'title': {'type': 'string'},
        },
        'required': ['title'],
        'additionalProperties': false,
      },
      decode: (json) => (json as Map<String, Object?>)['title'] as String,
    );
    print(result.value);
  } finally {
    client.close();
  }
}
```

## Native requests and streams

`client.createMessage(body)` returns an `AnthropicNativeResponse` with the raw
JSON in `data`, HTTP `statusCode`, and sanitized response `headers`.
`client.countTokens(body)` calls the native token-counting endpoint and returns
the same response shape, including fields such as `input_tokens` when supplied
by the service. Both methods and `streamMessages(body)` accept per-request
`headers`, `query` and `cancellation`; query values are lists of strings.
`streamMessages` yields `JsonSseData` with raw event `data`, event name, ID and
response headers. Error details retain private provider content after credential
scrubbing; do not expose them directly in a UI or logs. It requires a complete stream ending in `message_stop`.
`send` provides native JSON access to other paths without claiming endpoint
coverage.

The client defaults to API version `2023-06-01`; set `apiVersion` explicitly
when your integration needs another version. Constructor options `betas`,
`workspaceId`, and `userProfileId` set headers. In particular the
`anthropic-workspace-id` and `anthropic-user-profile-id` headers are separate
from any `workspace_id` and `user_profile_id` fields you put in a native JSON
body. Check the provider contract for the endpoint and version you use.

A `credentialResolver` can fetch or rotate a key for each request; alternatively
use `withApiKey`. Keep credentials on the backend. Close the native client when
finished; an injected `http.Client` is borrowed and remains the caller's
responsibility. There are no automatic retries. Cancellation aborts local
request work; it does not undo a request or external effect already accepted by
the provider.

## SDK-backed facade

Existing integrations can still construct `AnthropicChatModel` with an
`anthropic_sdk_dart` `AnthropicClient` and a typed `MessageCreateRequest`
`configure` callback for models without managed tools. Managed tools use
frozen options and require an authority binding. The SDK client is caller-owned. The typed callback's patch
preserves unknown unchanged JSON fields; edits to fields or lists can replace the
corresponding values. The SDK's typed representation still cannot express every
new provider field. Prefer the native client for unknown fields and
request-scoped transport cancellation.

## Replay and limits

The agent preserves provider content blocks for continuation, including
signatures and unknown fields on supported block types. This replay data and raw
responses may contain sensitive content; keep them private on the backend and
out of user-facing hydration or logs. The normalized agent currently handles
text, thinking, redacted thinking, client tool-use and pinned hosted-tool blocks with supported
text, thinking, signature and input JSON deltas. Citation blocks are normalized as typed message annotations and additive UI
events; opaque native fields remain private. See [document citations](citations.md). Unknown block types or deltas
fail explicitly. Hosted tools and bounded `pause_turn` continuation are integrated; see the
[hosted-tool guide](anthropic-hosted.md). MCP calls, results and listing replay are integrated through owned server
configuration; see [MCP](anthropic-mcp.md). Audio/video, browser tools and
complete nested semantics remain unfinished. Use raw native access for other
protocols.
For client computer use, see the [computer-use guide](anthropic-computer.md).
File-ID document parts are supported by the native agent path; the typed SDK
configuration path cannot yet decode them. URL and supported inline documents
are also available.

See the [request field inventory](anthropic-parameters.md) for the pinned
contract and disposition of each field. Fixtures exercise selected behavior;
they do not establish live model support or complete endpoint parity.

## Upstream SDK cancellation fix

[SDK PR #432](https://github.com/davidmigloz/ai_clients_dart/pull/432) adds prompt
cancellation before response headers, during stalled bodies, and through the
public stream wrappers while retaining shared-client ownership. The contribution
is merged; published SDK 9.0.1 does not include it. AgentWeave's native client already uses
its own shared transport and does not require this unreleased SDK change.

## Upstream citation file identifiers

The pinned SDK 9.0.1 drops `file_id` on known document citation response types.
AgentWeave preserves raw native blocks independently. The typed SDK correction
was merged in [upstream PR #441](https://github.com/davidmigloz/ai_clients_dart/pull/441).
The dependency remains pinned to 9.0.1 until an upstream release includes the fix.

## MCP connector

Declare owned `mcpServers` for native provider-executed calls, results and 2026
listing replay. Mixed local approvals, bounded paused turns, immutable provider
profiles and indeterminate-send recovery have offline fixtures. Raw callback
injection of MCP servers/toolsets remains rejected. See the
[MCP connector guide](anthropic-mcp.md), runnable example and field inventory.

The pinned typed SDK cannot represent `mcp_servers`; AgentWeave's SDK facade
sends the owned native JSON without that lossy reconstruction. Raw native APIs
remain separate from the normalized agent and its checkpoints.


# Source: docs/anthropic-hosted.md

# Anthropic hosted tools

Add provider-executed search, fetch, code execution or tool search to an ordinary
AgentWeave agent. Your `Tool` registrations remain application-executed; hosted
tools do not call their executors or produce local approval requests.

This complete example makes a billable request when you run it. Choose a model
that accepts web search and set `ANTHROPIC_API_KEY` and `ANTHROPIC_MODEL`.

```dart
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_anthropic/agent_weave_anthropic.dart' as anthropic;

Future<void> main() async {
  final key = Platform.environment['ANTHROPIC_API_KEY'];
  final modelId = Platform.environment['ANTHROPIC_MODEL'];
  if (key == null || key.isEmpty || modelId == null || modelId.isEmpty) {
    throw StateError('Set ANTHROPIC_API_KEY and ANTHROPIC_MODEL.');
  }
  final client = anthropic.AnthropicNativeClient.withApiKey(apiKey: key);
  try {
    final agent = AiAgent<void>(
      model: client.chatModel(
        authorityBindingId: 'example-anthropic-account',
        model: modelId,
        hostedTools: [
          anthropic.AnthropicHostedTool(
            const anthropic.WebSearchTool(maxUses: 3),
          ),
        ],
      ),
      maxSteps: 4,
      maxOutputTokens: 1024,
    );
    final result = await agent.generate(
      ChatRequest(
        threadId: 'research',
        runId: 'first',
        messages: [
          ChatMessage.user(
            'Find the latest stable Dart release.',
            id: 'question',
          ),
        ],
      ),
      ownerId: 'local-example',
      context: null,
    );
    print(result.text);
  } finally {
    client.close();
  }
}
```

## Configure hosted tools

`AnthropicHostedTool` snapshots a typed SDK `BuiltInTool`. Its `fromJson`
constructor retains unknown native option fields. Both constructors check an
explicit supported type/name pair and exclude client-executed tools such as
bash, memory, browser and computer. They also reject conflicting domain lists.
Other nested options and model acceptance are validated by the provider.

The current source pin contains 15 type spellings across web search, web fetch,
code execution and regex/BM25 tool search, including the unversioned tool-search
aliases. `dart run tool/anthropic_hosted_contract.dart` checks each spelling
against the extracted official declarations and rejects the known client tools.
This checks configuration coverage, not every nested option or live workflow.

For typed code execution, use:

```dart
final hosted = anthropic.AnthropicHostedTool(
  anthropic.CodeExecutionBuiltInTool(),
);
```

Pass the resulting values through `hostedTools` on
`AnthropicNativeClient.chatModel`, `AnthropicProtocolModel`, or the SDK-backed
`AnthropicChatModel`. Hosted names must be unique and cannot shadow registered
application tool names. The runtime protects the complete tool list from
replacement. Managed tools require `authorityBindingId` and frozen options;
`configure` is rejected at construction. Use `functionToolOptions` for registered
function decorations such as `allowed_callers`, `defer_loading`, `strict` and
cache control.

## Pauses, replay and containers

A complete `pause_turn` response yields `ModelFinished.continuation`. The core
agent stores the response before its next invocation and counts every invocation
against `maxSteps`. It continues with the ordered native content and the same
tools. It preserves the latest returned container ID from message-start or
message-delta metadata. Configuration cannot replace an inherited container ID.
These rules follow the [official server-tool lifecycle](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools).

Each pause is a checkpoint, rather than an automatic retry of a failed request.
A malformed stream, EOF, error or cancellation does not automatically dispatch
another request. The existing error and cancellation APIs still apply. Usage
accumulates across completed model invocations. With a schema, paused text is
progress and only the final response is validated as the answer. A sanitized
message snapshot closes the intermediate structured UI state without showing a
false failure. Completed structured data survives history hydration. `maxSteps` bounds invocations,
not provider-side searches, code execution, tokens or money; also configure the
provider's limits and your application budget.

If the step limit is reached while paused, the run returns `STEP_LIMIT` and keeps
its private continuation. A new run on the same owner/thread, with no new
messages and the same model/tool configuration, can explicitly continue it.
New user messages are rejected while that continuation is pending. Use a new
run ID; a recreated agent can share the same store. This is not automatic
recovery from an arbitrary process crash or an unknown external effect.

## Mixing hosted and application tools

The adapter keeps `server_tool_use` and result blocks private and never turns
them into an application call. Your ordinary tool follows its usual schema,
approval, context and result contract. A response can defer a hosted action
while your application tool waits for approval. The next user content must then
contain all of that turn's client tool results, without additional user text.
The adapter validates this shape before dispatch.

Programmatic calls from provider code execution require an explicit
`allowed_callers` opt-in on the registered application tool's provider definition.
The adapter checks the caller type and its reference to an active code-execution
call before emitting an application call. The documented `code_execution_20260521`
caller option accepts the canonical `code_execution_20260120` response tag.
Unfinished code execution requires a returned or explicitly configured container
ID; missing identity fails before local execution. Tool input validation still applies, and `needsApproval` uses the normal
approval flow. Tool-search results stay opaque. References do not install executors or grant
permissions; the runtime invokes only application tools you separately register.

## Private data and current evidence

Ordered content lives in `anthropic.messages`, cumulative metadata and containers
in `anthropic.messages.metadata`, and the configured continuation tool list in
`anthropic.messages.tools`. Keep these fields on the backend. They can contain
sensitive fetched text, opaque encrypted values, caller IDs, container IDs and
citations. `chatHydration` excludes them. Citation deltas remain on the native
text blocks for replay; this release has no public citation-rendering event.

The normalizer accepts the pinned content union, including search, fetch, code,
bash-code, text-editor-code and tool-search results plus container uploads.
Unknown top-level blocks or deltas fail explicitly. MCP uses its own [connector contract](anthropic-mcp.md). Browser tools and
complete nested response semantics remain outside this integration.

Local fixtures cover typed and raw definitions, fragmented server input, opaque
results, paused turns, exact tool/container replay, programmatic caller checks,
mixed approvals, cancellation, malformed output, hydration privacy and bounds.
They do not prove model availability, real search quality, downloaded files,
container expiry, billing or live provider behavior. See
[validation](validation.md) and [the independent developer review](dx-review.md).

The [official programmatic-calling guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling)
describes caller aliases, required containers and timeout limits. Container
expiry can still reject a later continuation; application tools must implement
idempotency and reconcile external effects. No live expiry policy is certified.

## Immutable request options

`AnthropicChatModel`, `AnthropicProtocolModel` and the native client's
`chatModel` snapshot these declarations and include them in the private model
continuation profile:

| Parameter | Purpose |
| --- | --- |
| `options` | Native request fields such as thinking, metadata, request cache control and output effort; runtime-owned history, schema and bounds are excluded |
| `toolChoice` | Native tool-choice object |
| `functionToolOptions` | Registered function name to strict, defer-loading, allowed-caller and cache-control decorations |
| `container` | Initial container ID or native object, including skills; returned IDs take precedence and remain protected |
| `messageDecorations` | Stable user-message ID to content-part-indexed decoration maps; null entries leave a part unchanged |
| `systemCacheControl` | Cache control on the runtime's system instruction text block |

For example, a user message named `brief` whose first part is a document can use:

```dart
messageDecorations: {
  'brief': [
    {
      'context': 'A customer brief',
      'cache_control': {'type': 'ephemeral'},
      'citations': {'enabled': true},
    },
  ],
},
systemCacheControl: {'type': 'ephemeral'},
```

These maps cannot replace document source, title, text or tool input. Text and
image parts accept cache control; documents also accept context and citation
configuration. The existing citation rules still require all documents enabled
or all disabled, and reject citations with structured output. The caller must
supply a system instruction when using `systemCacheControl`.

Callbacks remain available for ordinary models without managed tools. Their
validation occurs on the next invocation and can fail after an approved local
tool has run. Prefer declarative options for resumed applications. The model
constructors are no longer const because they copy caller-owned collections.


# Source: docs/anthropic-mcp.md

# Connect Anthropic MCP tools

Use `mcpServers` with `AnthropicNativeClient.chatModel`, `AnthropicChatModel`, or
`AnthropicProtocolModel`. Anthropic executes the selected remote tools. They do
not become local `Tool` registrations or application approval requests.

## Run the example

Set `ANTHROPIC_API_KEY`, `ANTHROPIC_MODEL`, `MCP_SERVER_URL` and
`MCP_ALLOWED_TOOL`, then run `dart run examples/anthropic_mcp_demo.dart`.
Choose a trusted server and one tool appropriate for the request. Optional
`MCP_ACCESS_TOKEN` supplies its OAuth token; `MCP_PROMPT` changes the question.
Running this example makes billable requests and can execute that remote tool.
The example uses memory storage and bounds provider continuations with
`maxSteps`; repository checks compile it without running it.

```dart
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_anthropic/agent_weave_anthropic.dart' as anthropic;

Future<void> main() async {
  final environment = Platform.environment;
  final key = environment['ANTHROPIC_API_KEY'];
  final model = environment['ANTHROPIC_MODEL'];
  final url = environment['MCP_SERVER_URL'];
  final tool = environment['MCP_ALLOWED_TOOL'];
  if ([key, model, url, tool].any((value) => value == null || value.isEmpty)) {
    throw StateError(
      'Set ANTHROPIC_API_KEY, ANTHROPIC_MODEL, MCP_SERVER_URL and MCP_ALLOWED_TOOL.',
    );
  }
  final token = environment['MCP_ACCESS_TOKEN'];
  final client = anthropic.AnthropicNativeClient.withApiKey(apiKey: key!);
  try {
    final agent = AiAgent<void>(
      model: client.chatModel(
        model: model!,
        authorityBindingId: 'local-example/anthropic-account',
        options: {'temperature': 0.2},
        mcpServers: [
          anthropic.AnthropicMcpServer(
            name: 'support',
            url: Uri.parse(url!),
            beta: anthropic.AnthropicMcpBeta.client20260915,
            toolset: anthropic.AnthropicMcpToolset(
              defaultConfig: anthropic.AnthropicMcpToolConfig(enabled: false),
              configs: {tool!: anthropic.AnthropicMcpToolConfig(enabled: true)},
            ),
            credentialBindingId: token == null
                ? null
                : 'local-example/mcp-account',
            authorizationToken: token == null ? null : () => token,
          ),
        ],
      ),
      maxSteps: 4,
      maxOutputTokens: 1024,
    );
    final result = await agent.generate(
      ChatRequest(
        threadId: 'support',
        runId: 'question',
        messages: [
          ChatMessage.user(
            environment['MCP_PROMPT'] ??
                'Use $tool to find information about Dart streams.',
            id: 'u',
          ),
        ],
      ),
      ownerId: 'local-example',
      context: null,
    );
    print(result.text);
  } on AgentRunException catch (error) {
    stderr.writeln('${error.code}: ${error.message}');
    exitCode = 1;
  } finally {
    client.close();
  }
}
```

For the reproducible offline application, run:

```sh
dart --enable-asserts run examples/review_cases/anthropic_mcp.dart
```

It uses an SDK-compatible HTTP fixture and two MCP servers. It verifies a
mixed local approval, deferred remote result, configuration rejection and
credential rotation. It does not contact Anthropic or execute remote effects.

## Declare servers, tools and authority

Each `AnthropicMcpServer` has a unique name, an HTTPS URL and an explicit beta.
All servers in one model use the same beta. Modern modes generate exactly one
matching toolset per server. `AnthropicMcpToolset` supports default and per-tool
`enabled`/`deferLoading`, `cacheControl` and native `fromJson` extensions. Unknown
tool names in `configs` are retained because discovery can change.

| Beta | Wire configuration |
| --- | --- |
| `client20260915` | Modern server/toolset plus recorded listings and optional pinned tools; documented for the Claude API |
| `client20251120` | Modern server/toolset; cloud-platform availability differs |
| `legacy20250404` | Deprecated server `tool_configuration`; no toolsets or pinned descriptors |

The modes follow the [official connector contract](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector).
Legacy mode requires `legacyToolConfiguration` or the native
`tool_configuration` field through `fromJson`. It rejects modern toolsets.
Pinned tool descriptors belong in `AnthropicMcpToolset(tools: [...])` and require
`client20260915`. Each descriptor has a name, input schema and optional
description. Beta acceptance by a live model or cloud platform is unverified.

The SDK-backed facade sends the owned native MCP JSON through its raw stream
method; the pinned SDK's typed Messages request does not represent these server
fields. Reconstructing an SDK request from arbitrary JSON is not MCP support.

Managed MCP or hosted tools require a stable, nonsecret `authorityBindingId`
for the provider account and endpoint/routing configuration. Change it when
that authority changes; never use an API key. Additional request parameters
belong in frozen `options`, with `toolChoice` for selection. Configuration
callbacks are rejected when managed tools are present. Core binds the original
model, beta flags, authority, toolsets, options and credential identities before
resuming local effects or dispatch. Changing them invalidates the unfinished
turn. See [continuation contracts](approval-contracts.md).

Client-level beta flags are merged with the owned MCP header rather than
replaced. Duplicate flags collapse; conflicting MCP versions fail before
transport. The effective beta list is retained in the private model profile.

## Resolve owner-bound credentials

Create the model in the authenticated backend scope. Derive the owner from the
session, and resolve that owner's token on each outbound request:

```dart
final server = anthropic.AnthropicMcpServer(
  name: 'support',
  url: Uri.https('support.example.com', '/mcp'),
  beta: anthropic.AnthropicMcpBeta.client20260915,
  credentialBindingId: account.stableAuthorizationIdentity,
  authorizationToken: () => tokens.accessTokenFor(authenticatedOwner, account),
);
```

`account` and `tokens` are application services. The binding identifies the
remote account and authorization scope. Token refresh under that same binding
is allowed. Literal `authorization_token` through `fromJson` is extracted into
a private resolver and requires the same kind of binding. Authless servers are
valid. OAuth acquisition and refresh policy belong to the application.

Definitions and contracts exclude owned credentials. Resolution errors and
known transport/metadata echoes are sanitized. Keep secrets out of URLs,
unknown options and logs. Returned tool content, signed thinking and opaque
replay may contain private data; those blocks are kept exactly on the backend.
They are not a promise that arbitrary provider-generated content is secret-free.
Only publish `chatHydration` and normal agent events to clients.

## Mixed calls, pauses and recovery

MCP calls and results remain provider-owned `mcp_tool_use` and
`mcp_tool_result` blocks. Discovery listings remain private, including unknown
fields. Matching uses native IDs and server names; it does not share the local
function namespace. A remote tool may have the same name as a registered local
tool without invoking that local executor.

A `tool_use` response may defer remote execution until the application supplies
its local results. `AiAgent` can pause for those local approvals, persist them
and recreate the model with the same profile. It sends local results before the
next invocation and retains the original MCP blocks. A `pause_turn` uses normal
step accounting and durable continuation. These mechanics follow the
[server-tool lifecycle](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools).
No OpenAI-style remote approval is invented for Anthropic MCP.

The 2026 listing is replayed unchanged with its beta on subsequent requests.
You can copy a trusted listing into `toolset.tools` for an explicitly pinned
configuration after completing the current turn, or in a new conversation.
Do not replace the profile of an unfinished turn to pin or change its tools.

For Serverpod, use `ServerpodRunStore(session)` behind the authenticated agent
factory. The original private model profile survives local approvals and
provider-only step-limit restarts. Owner-scoped history and event journals keep
native MCP IDs, inputs, results and credentials out of client snapshots.

Each potentially effectful dispatch checkpoints `ProviderExecutionStarting`
first. Failure, cancellation or a crash after that boundary leaves an
indeterminate outcome and blocks automatic resend, including initial requests.
Inspect external effects and start a new conversation; a matching configuration
does not prove the effect did not occur. This is conservative if a crash occurs
between the checkpoint and the actual send. A validated terminal checkpoint
clears the marker atomically with the continuation state.

Cancellation during credential resolution stops waiting without dispatching;
it cannot cancel the application's underlying OAuth operation. Set OAuth
timeouts in that resolver; the provider HTTP timeout begins at transport work. A request that
was already accepted may still execute remotely. Backend `AgentRunException.cause` retains a sanitized `JsonHttpException` for
HTTP failures, with status and the native transport's redacted request ID.
Error bodies and response headers are dropped. SDK 9.0.1 streaming exceptions
retain status but omit the server request ID; do not mistake a client correlation
ID for it. [Upstream PR #445](https://github.com/davidmigloz/ai_clients_dart/pull/445)
was approved and merged on 2026-11-04. The workspace still pins 9.0.1;
the upstream merge is separate from a released SDK dependency update.
The native transport has no
automatic retries. The SDK-backed stream also makes one send, but pinned SDK
9.0.1 cannot abort while waiting for response headers. Prefer the native client
for request-scoped transport cancellation.

## Preserved options and current limits

Managed tools use immutable `options`, `functionToolOptions`, `container`,
`messageDecorations` and `systemCacheControl` in place of callback mutations.
These preserve the existing function, caching and document configuration paths;
see [hosted-tool options](anthropic-hosted.md#immutable-request-options).
Unknown request fields retain native JSON but do not establish orchestration.

The current pinned MCP result content is a string or an array of text blocks.
Current calls disabled by the server/toolset policy or absent from an explicit
pin fail before accompanying local calls are exposed. Completed historical calls
remain replayable when a later turn narrows its policy. Malformed correlation,
missing required fields, duplicate IDs and unsupported
block kinds fail explicitly. Unfinished MCP calls require a genuine local-tool
turn or `pause_turn`; they cannot silently finish on truncation or refusal.

Live remote execution, OAuth providers, platform/model availability, mobile
rendering and exactly-once effects remain unverified. Inline mid-conversation
tool-addition/removal message directives, Managed Agents and other endpoint
lifecycles are outside this integration. Explicit raw native APIs remain
available when the application owns the full protocol.

The [MCP field inventory](anthropic-mcp-parameters.md) records the selected
pinned declarations and executable configuration fixture. Its presence is not
evidence of complete Anthropic API coverage.


# Source: docs/anthropic-mcp-parameters.md

# Anthropic MCP Messages contract

Generated from the [pinned inventory](anthropic-mcp-inventory.json). See the [official connector guide](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector).

Selected MCP Messages declarations and recursively referenced local types. The Dart fixture exercises owned configuration and credential separation, not SSE normalization, provider acceptance or live execution. MCP result content in this pinned contract is string or an array of text blocks; private replay and continuation are tested separately.

- `mcp-client-2025-04-04`: Deprecated legacy server tool_configuration; provider availability is not established.
- `mcp-client-2025-11-20`: Modern matching server and toolset; supported cloud platforms vary.
- `mcp-client-2026-09-15`: Claude API listing and pinned tool descriptors; replay listings with this beta.

## BetaCacheControlEphemeral

| Field | Source type |
| --- | --- |
| type | `'ephemeral'` |
| ttl? | `'5m' \| '1h'` |

## BetaCitationCharLocation

| Field | Source type |
| --- | --- |
| cited_text | `string` |
| document_index | `number` |
| document_title | `string \| null` |
| end_char_index | `number` |
| file_id | `string \| null` |
| start_char_index | `number` |
| type | `'char_location'` |

## BetaCitationCharLocationParam

| Field | Source type |
| --- | --- |
| cited_text | `string` |
| document_index | `number` |
| document_title | `string \| null` |
| end_char_index | `number` |
| start_char_index | `number` |
| type | `'char_location'` |

## BetaCitationContentBlockLocation

| Field | Source type |
| --- | --- |
| cited_text | `string` |
| document_index | `number` |
| document_title | `string \| null` |
| end_block_index | `number` |
| file_id | `string \| null` |
| start_block_index | `number` |
| type | `'content_block_location'` |

## BetaCitationContentBlockLocationParam

| Field | Source type |
| --- | --- |
| cited_text | `string` |
| document_index | `number` |
| document_title | `string \| null` |
| end_block_index | `number` |
| start_block_index | `number` |
| type | `'content_block_location'` |

## BetaCitationPageLocation

| Field | Source type |
| --- | --- |
| cited_text | `string` |
| document_index | `number` |
| document_title | `string \| null` |
| end_page_number | `number` |
| file_id | `string \| null` |
| start_page_number | `number` |
| type | `'page_location'` |

## BetaCitationPageLocationParam

| Field | Source type |
| --- | --- |
| cited_text | `string` |
| document_index | `number` |
| document_title | `string \| null` |
| end_page_number | `number` |
| start_page_number | `number` |
| type | `'page_location'` |

## BetaCitationSearchResultLocation

| Field | Source type |
| --- | --- |
| cited_text | `string` |
| end_block_index | `number` |
| search_result_index | `number` |
| source | `string` |
| start_block_index | `number` |
| title | `string \| null` |
| type | `'search_result_location'` |

## BetaCitationSearchResultLocationParam

| Field | Source type |
| --- | --- |
| cited_text | `string` |
| end_block_index | `number` |
| search_result_index | `number` |
| source | `string` |
| start_block_index | `number` |
| title | `string \| null` |
| type | `'search_result_location'` |

## BetaCitationsWebSearchResultLocation

| Field | Source type |
| --- | --- |
| cited_text | `string` |
| encrypted_index | `string` |
| title | `string \| null` |
| type | `'web_search_result_location'` |
| url | `string` |

## BetaCitationWebSearchResultLocationParam

| Field | Source type |
| --- | --- |
| cited_text | `string` |
| encrypted_index | `string` |
| title | `string \| null` |
| type | `'web_search_result_location'` |
| url | `string` |

## BetaMCPTool

| Field | Source type |
| --- | --- |
| input_schema | `{
    [key: string]: unknown;
}` |
| name | `string` |
| description? | `string` |

## BetaMCPToolConfig

| Field | Source type |
| --- | --- |
| defer_loading? | `boolean` |
| enabled? | `boolean` |

## BetaMCPToolDefaultConfig

| Field | Source type |
| --- | --- |
| defer_loading? | `boolean` |
| enabled? | `boolean` |

## BetaMCPToolListingBlock

| Field | Source type |
| --- | --- |
| mcp_server_name | `string` |
| tools | `Array<BetaMCPTool>` |
| type | `'mcp_tool_listing'` |

## BetaMCPToolListingBlockParam

| Field | Source type |
| --- | --- |
| mcp_server_name | `string` |
| tools | `Array<BetaMCPToolParam>` |
| type | `'mcp_tool_listing'` |

## BetaMCPToolParam

| Field | Source type |
| --- | --- |
| input_schema | `{
    [key: string]: unknown;
}` |
| name | `string` |
| description? | `string \| null` |

## BetaMCPToolResultBlock

| Field | Source type |
| --- | --- |
| content | `string \| Array<BetaTextBlock>` |
| is_error | `boolean` |
| tool_use_id | `string` |
| type | `'mcp_tool_result'` |

## BetaMCPToolset

| Field | Source type |
| --- | --- |
| mcp_server_name | `string` |
| type | `'mcp_toolset'` |
| cache_control? | `BetaCacheControlEphemeral \| null` |
| configs? | `{
    [key: string]: BetaMCPToolConfig;
} \| null` |
| default_config? | `BetaMCPToolDefaultConfig` |
| tools? | `Array<BetaMCPToolParam> \| null` |

## BetaMCPToolUseBlock

| Field | Source type |
| --- | --- |
| id | `string` |
| input | `unknown` |
| name | `string` |
| server_name | `string` |
| type | `'mcp_tool_use'` |

## BetaMCPToolUseBlockParam

| Field | Source type |
| --- | --- |
| id | `string` |
| input | `unknown` |
| name | `string` |
| server_name | `string` |
| type | `'mcp_tool_use'` |
| cache_control? | `BetaCacheControlEphemeral \| null` |

## BetaRequestMCPServerToolConfiguration

| Field | Source type |
| --- | --- |
| allowed_tools? | `Array<string> \| null` |
| enabled? | `boolean \| null` |

## BetaRequestMCPServerURLDefinition

| Field | Source type |
| --- | --- |
| name | `string` |
| type | `'url'` |
| url | `string` |
| authorization_token? | `string \| null` |
| tool_configuration? | `BetaRequestMCPServerToolConfiguration \| null` |

## BetaRequestMCPToolResultBlockParam

| Field | Source type |
| --- | --- |
| tool_use_id | `string` |
| type | `'mcp_tool_result'` |
| cache_control? | `BetaCacheControlEphemeral \| null` |
| content? | `string \| Array<BetaTextBlockParam>` |
| is_error? | `boolean` |

## BetaTextBlock

| Field | Source type |
| --- | --- |
| citations | `Array<BetaTextCitation> \| null` |
| text | `string` |
| type | `'text'` |

## BetaTextBlockParam

| Field | Source type |
| --- | --- |
| text | `string` |
| type | `'text'` |
| cache_control? | `BetaCacheControlEphemeral \| null` |
| citations? | `Array<BetaTextCitationParam> \| null` |

## BetaTextCitation

`BetaCitationCharLocation | BetaCitationPageLocation | BetaCitationContentBlockLocation | BetaCitationsWebSearchResultLocation | BetaCitationSearchResultLocation`

## BetaTextCitationParam

`BetaCitationCharLocationParam | BetaCitationPageLocationParam | BetaCitationContentBlockLocationParam | BetaCitationWebSearchResultLocationParam | BetaCitationSearchResultLocationParam`


# Source: docs/anthropic-parameters.md

# Anthropic Messages request fields

Generated from the [contract inventory](anthropic-api-inventory.json), pinned to official TypeScript SDK commit `ea8d7de0e47614ae71044fbf7bf12041318ba37e`. Run `node tool/interop/anthropic-inventory.mjs --write` after reviewing changes.

These dispositions describe top-level access only. Arbitrary native JSON does not validate nested unions or establish agent orchestration, model acceptance, or live behavior. The SDK adapter owns messages, execution bounds, system instructions and tools; its output schema is protected when supplied by the runtime.

| Field | Disposition | Access and limits |
| --- | --- | --- |
| max_tokens | runtime-owned | Built and protected by the agent adapter; native JSON accepts caller input. |
| messages | runtime-owned | Runtime-owned history, source and title; native document context/cache/citations decorations are supported. Five pinned citation variants have typed output and private replay with offline fixtures. Custom-content documents, search-result inputs and live behavior remain unverified. |
| system | runtime-owned | Built and protected by the agent adapter; native JSON accepts caller input. |
| tools | runtime-owned | Runtime local tools and owned hosted/MCP declarations are protected. Managed models use frozen function options and provider authority. The separate beta MCP inventory covers server/toolsets and native use/result/listing replay; live and full nested semantics remain unverified. |
| model | runtime-owned | Immutable adapter model constructor; configure cannot replace it. Explicit raw-native JSON remains caller-owned. |
| output_config | mixed | SDK configure; runtime output schema is protected when requested. Native JSON accepts caller input. |
| stream | runtime-owned | Agent uses SDK streaming; native client controls the request mode. |
| user_profile_id | mixed | The adapter exposes a userProfileId header; native JSON accepts this body field separately. |
| cache_control | mixed | Immutable agent options, or typed/native configure for models without managed tools; explicit raw JSON also accepts the field. Forwarding does not prove full nested or live semantics. |
| container | mixed | Explicit immutable initial container ID/object, including skills. Returned IDs are retained privately, take precedence and remain protected across paused and local-tool continuation. Live expiry/files remain unverified. |
| diagnostics | mixed | Immutable agent options, or typed/native configure for models without managed tools; explicit raw JSON also accepts the field. Forwarding does not prove full nested or live semantics. |
| inference_geo | mixed | Immutable agent options, or typed/native configure for models without managed tools; explicit raw JSON also accepts the field. Forwarding does not prove full nested or live semantics. |
| metadata | mixed | Immutable agent options, or typed/native configure for models without managed tools; explicit raw JSON also accepts the field. Forwarding does not prove full nested or live semantics. |
| service_tier | mixed | Immutable agent options, or typed/native configure for models without managed tools; explicit raw JSON also accepts the field. Forwarding does not prove full nested or live semantics. |
| speed | mixed | Immutable agent options, or typed/native configure for models without managed tools; explicit raw JSON also accepts the field. Forwarding does not prove full nested or live semantics. |
| stop_sequences | mixed | Immutable agent options, or typed/native configure for models without managed tools; explicit raw JSON also accepts the field. Forwarding does not prove full nested or live semantics. |
| thinking | mixed | Immutable agent options, or typed/native configure for models without managed tools; explicit raw JSON also accepts the field. Forwarding does not prove full nested or live semantics. |
| tool_choice | mixed | Immutable agent options, or typed/native configure for models without managed tools; explicit raw JSON also accepts the field. Forwarding does not prove full nested or live semantics. |
| workspace_id | native-json | Native JSON accepts this field; SDK configure support depends on the Dart SDK version. Agent semantics are not established. |

The inventory follows selected local type references for Messages requests, responses and stream events. Imported declarations and unrelated endpoints are outside its scope. Review protocol behavior and provider documentation separately.


# Source: docs/anthropic-computer.md

# Anthropic computer use

`AnthropicComputerTool` connects Anthropic's `computer_toolset_20260801` calls
to a desktop driver you provide. AgentWeave does not provide the desktop or
operate it itself. The [executable example](https://github.com/seifalmotaz/agent-weave/blob/main/examples/anthropic_computer_demo.dart)
uses the native Messages client, an application-owned HTTPS driver and a console
approval for each requested turn. It makes billable Anthropic requests when run.
Choose a model that supports the toolset using the [official computer-use
documentation](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool).

Set `ANTHROPIC_API_KEY`, `ANTHROPIC_MODEL`, `COMPUTER_DRIVER_URL`,
`COMPUTER_DRIVER_TOKEN` and `COMPUTER_ENVIRONMENT_ID` in the backend
environment. Run `dart run examples/anthropic_computer_demo.dart "your task"`.
The sample uses the default in-memory run store and fixed local owner and thread
identifiers; it is a single-process demonstration, not durable or multi-user
storage. Production applications must authenticate owners, protect private
conversation state, and configure a suitable store and approval interface.
The console prints action arguments for review, which may contain sensitive data.

## Complete CLI example

Optionally set `ANTHROPIC_VERSION` to select a supported API version.

```dart
import 'dart:convert';
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_anthropic/agent_weave_anthropic.dart' as anthropic;
import 'package:agent_weave_http/agent_weave_http.dart';

String environment(String name) {
  final value = Platform.environment[name];
  if (value == null || value.trim().isEmpty) throw StateError('Set $name.');
  return value;
}

Future<void> main(List<String> args) async {
  if (args.isEmpty) throw ArgumentError('Pass the task as command arguments.');
  final driverUrl = environment('COMPUTER_DRIVER_URL');
  if (Uri.parse(driverUrl).scheme != 'https') {
    throw ArgumentError('COMPUTER_DRIVER_URL must use HTTPS.');
  }
  final driverToken = environment('COMPUTER_DRIVER_TOKEN');
  final environmentId = environment('COMPUTER_ENVIRONMENT_ID');
  final driver = JsonHttpClient(
    baseUrl: driverUrl,
    requestTimeout: const Duration(seconds: 30),
  );
  final client = anthropic.AnthropicNativeClient.withApiKey(
    apiKey: environment('ANTHROPIC_API_KEY'),
    apiVersion: Platform.environment['ANTHROPIC_VERSION'] ?? '2023-06-01',
  );
  try {
    final agent = AiAgent<void>(
      model: client.chatModel(model: environment('ANTHROPIC_MODEL')),
      tools: [
        anthropic.AnthropicComputerTool<void>(
          environmentId: environmentId,
          needsApproval: true,
          allowedCallers: const ['direct'],
          execute: (call, context) async {
            final response = await driver.sendJson(
              '/execute',
              cancellation: context.cancellation,
              prepare: () => JsonHttpRequest(
                headers: {'Authorization': 'Bearer $driverToken'},
                body: {
                  'environment_id': environmentId,
                  'tool_call_id': context.toolCallId,
                  'idempotency_key': context.idempotencyKey,
                  'call': call.raw,
                },
              ),
            );
            final value = jsonDecode(response.body);
            if (value is! Map<String, dynamic>) {
              throw const FormatException('Expected a driver result object.');
            }
            return anthropic.AnthropicComputerResult.fromJson(value);
          },
        ),
      ],
    );
    var sequence = 0;
    var result = await agent.generate(
      ChatRequest(
        threadId: 'computer-demo',
        runId: 'run-${sequence++}',
        messages: [ChatMessage.user(args.join(' '), id: 'user')],
      ),
      ownerId: 'local-user',
      context: null,
    );
    while (result.status == RunStatus.interrupted) {
      stdout.writeln('Requested actions:');
      for (final interrupt in result.interrupts) {
        stdout.writeln(jsonEncode(interrupt.call.toJson()));
      }
      stdout.write('Approve this turn? [y/N] ');
      final approve = stdin.readLineSync()?.trim().toLowerCase() == 'y';
      final previous = result;
      result = await agent.generate(
        ChatRequest(
          threadId: previous.threadId,
          runId: 'run-${sequence++}',
          parentRunId: previous.runId,
          resume: [
            for (final interrupt in previous.interrupts)
              approve ? interrupt.approve() : interrupt.reject(),
          ],
        ),
        ownerId: 'local-user',
        context: null,
      );
    }
    stdout.writeln(result.text);
  } finally {
    driver.close();
    client.close();
  }
}
```

## Typed actions

The callback receives a sealed `AnthropicComputerAction`. Points are named
Dart records with `x` and `y`; regions have `x0`, `y0`, `x1`, and `y1`.
Scroll direction and click/empty-action kinds are enums. `call.raw` retains the
validated wire shape for a remote driver. Unknown input fields fail before execution.

| Action type | Values |
| --- | --- |
| `AnthropicComputerKey` | `text`, optional `repeat` |
| `AnthropicComputerHoldKey` | `text`, `duration` |
| `AnthropicComputerType` | `text` |
| `AnthropicComputerEmptyAction` | Screenshot, cursor position, mouse down/up `kind` |
| `AnthropicComputerMove` | `coordinate` point |
| `AnthropicComputerClickAction` | Click `kind`, optional `coordinate` and modifier `text` |
| `AnthropicComputerDrag` | `startCoordinate`, `coordinate`, optional modifier `text` |
| `AnthropicComputerScroll` | `amount`, `direction`, optional `coordinate` and modifier `text` |
| `AnthropicComputerWait` | `duration` |
| `AnthropicComputerZoom` | `region` |

Success from screenshot or zoom requires an image result; cursor position
requires nonempty text. Return a typed error for an action that failed. Image
contents and the truth of reported coordinates remain the driver's responsibility.

## Driver contract

The sample sends a JSON POST to `/execute` on your HTTPS driver. It sends a
bearer token, uses a 30-second timeout and passes the run cancellation token;
redirects and automatic retries are disabled. The request contains:

```json
{
  "environment_id": "desktop-1",
  "tool_call_id": "toolu_example",
  "idempotency_key": "stable-per-owner-thread-and-call",
  "call": {"type":"tool_use","id":"toolu_example","toolset_name":"computer","name":"screenshot","input":{}}
}
```

Your driver must authenticate the request, bind `environment_id` to the
approved isolated desktop, validate inputs and deduplicate effects using the
idempotency key. Cancellation or timeout does not undo an action already
accepted by the driver. The driver returns an object with `content`, a list of
Anthropic text and image blocks, and optional boolean `is_error`. For example,
`{"content":[{"type":"text","text":"Clicked."}]}` is an acknowledgement;
a failure can be `{"content":[{"type":"text","text":"Action failed."}],"is_error":true}`.
For screenshot and zoom, return an image block, for example with a base64 PNG
source. `AnthropicComputerResult.fromJson` validates this response before the
runtime forwards it. A thrown driver/transport/decoding exception fails the
run; returning `is_error: true` reports a tool failure to Claude so it can
continue.

The runtime executes computer actions in order. After a computer result marks
an error, later executors in that turn do not run. Computer members receive the
prescribed skipped error; ordinary functions receive a generic skipped error.
The next model turn can recover from those results. By default, a turn containing a
computer action requires approval for the whole batch; native call arguments
are read-only. If approval is declined, the application must start a new thread
rather than execute the rejected native turn.

After a pause, recheck the target and current screen before applying approved actions.

The driver owns coordinate validation and conversion, screenshot capture,
image sizing and desktop isolation. Coordinates refer to full screenshots,
including after zoom; AgentWeave does not scale them. Check bounds against the
actual screenshot and enforce action limits before operating the desktop.
For documented action fields, limits, result rules and the pinned SDK projection,
see the [computer contract inventory](anthropic-computer-parameters.md).

Raw native Messages document blocks support provider file IDs in the agent;
the SDK-backed typed `configure` path still cannot decode those IDs until the
upstream SDK change is released. Neither the example nor the contract inventory
establishes live model compatibility or verifies your driver.


# Source: docs/anthropic-computer-parameters.md

# Anthropic computer toolset contract

Generated from the [inventory](anthropic-computer-inventory.json), pinned to official TypeScript SDK commit `ea8d7de0e47614ae71044fbf7bf12041318ba37e`. Run `node tool/interop/anthropic-computer-inventory.mjs --write` after review. See the [computer use documentation](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool) and [SDK driver guidance](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk).

The 17 member calls use `toolset_name: computer`, the member name, and member-specific input with no action field. Dispatch by both names. Configs are sparse: each member defaults to enabled with defer_loading false. The toolset accepts cache_control. The documentation additionally permits allowed_callers with only ["direct"]; the pinned SDK declaration omits that field.

Run a batch sequentially. On failure, return an error for that action and for every subsequent unexecuted action, with the exact halt text in the inventory. Return one result for every call with its tool_use_id and toolset_name. Screenshot and zoom return an image; cursor_position returns coordinates as text. Coordinates always refer to the full screenshot, including after zoom.

The driver owns validation, coordinate conversion, image sizing, environment isolation and approval policy. Documentation specifies key repeat 1–100 (default 1), and hold_key and wait duration up to 300 seconds; the official driver guidance leaves these checks to applications. AgentWeave validates selected repeat and duration bounds before invoking the executor. These declarations and offline fixtures do not demonstrate model acceptance, desktop execution, or live behavior.


# Source: docs/ollama.md

# Ollama

Connect AgentWeave to an existing Ollama server and an installed model. Install `agent_weave`, `agent_weave_ollama`, and their dependencies in your Dart project. Set `OLLAMA_MODEL` to an installed model that supports JSON Schema; optionally set `OLLAMA_BASE_URL` (defaults to `http://localhost:11434`). Then run `dart run examples/ollama_demo.dart` from this repository.

```dart
import 'dart:io';

import 'package:agent_weave/agent_weave.dart' as weave;
import 'package:agent_weave_ollama/agent_weave_ollama.dart' as ollama;

Future<void> main() async {
  final modelId = Platform.environment['OLLAMA_MODEL'];
  if (modelId == null || modelId.isEmpty) {
    stderr.writeln(
      'Set OLLAMA_MODEL to an installed model that supports JSON schema.',
    );
    exitCode = 64;
    return;
  }
  final client = ollama.OllamaNativeClient(
    baseUrl:
        Platform.environment['OLLAMA_BASE_URL'] ?? 'http://localhost:11434',
  );
  try {
    final model = client.chatModel(
      model: modelId,
      options: const ollama.ModelOptions(temperature: 0.2),
    );
    final result = await weave.generateObject<String>(
      model: model,
      prompt: 'Give a short name for a friendly robot.',
      schema: {
        'type': 'object',
        'properties': {
          'name': {'type': 'string'},
        },
        'required': ['name'],
        'additionalProperties': false,
      },
      decode: (json) => (json as Map<String, Object?>)['name'] as String,
    );
    print(result.value);
  } finally {
    client.close();
  }
}
```

This client talks to an Ollama HTTP server; it does not run inference inside the Dart or Flutter app. On a phone, `localhost` means the phone itself, so configure a reachable server URL. Device networking and model capabilities vary and have not been verified here.

`OllamaChatModel` supports AgentWeave function tools and structured output, subject to the model's capabilities. AgentWeave validates tool arguments and applies configured approval rules before execution. Assistant thinking and native tool calls are preserved for continuation in private provider data. Ollama may return native call IDs; AgentWeave generates separate local IDs and binds tool results to the original call. When the native ID is absent, replay uses the tool name without inventing an ID on the wire. Private replay, raw frames, response metadata and logprobs can contain sensitive information; do not expose them to end users or logs.

In the pinned Ollama server, its generic parser and reviewed built-in parsers allocate increasing call indices across a response. This is not guaranteed for remote or older servers. AgentWeave accepts repeated identical indexed calls once and rejects conflicting repeats rather than guessing how to merge them. Use `streamChat` directly for protocols that need different handling.

For images, use an AgentWeave `ImagePart` containing an inline `data:image/...;base64,...` URL. Remote image URLs are not fetched. Files, audio, video and native provider-specific tool kinds are unsupported in normalized chat. The native API remains available when the model or server needs a different request shape.

The package re-exports `ollama_dart` 4.0.0 types for typed options, including `ModelOptions`, `ThinkValue`, `KeepAlive` and `EmbedRequest`. The example leaves thinking and keep-alive at server defaults. When supported by your model and desired, pass `think: const ollama.ThinkValue.enabled(true)` or `keepAlive: const ollama.KeepAlive.duration('5m')` to `client.chatModel`. Model options remain model-dependent. `maxOutputTokens` owns `options.num_predict`; `configure` cannot replace runtime-owned model, messages, tools, stream, output schema or output limit.

To embed with an installed embedding-capable model, use `OllamaEmbeddingModel(client).embed(ollama.EmbedRequest(model: embeddingModelId, input: ollama.EmbedInput.list(['first', 'second'])))`. Its result exposes immutable vectors, the raw response, the reported model and input token count. Do not assume every chat model supports embeddings.

For native JSON, use `createChat`, `createGenerate`, `embed`, `show`, or `send`; `streamChat` and `streamGenerate` expose NDJSON frames. The native client accepts a `CancellationToken` and cancels its request on cancellation or stream unsubscribe; these guarantees belong to AgentWeave's transport, not the re-exported SDK. It does not retry, pull or download models. For protected servers, supply an optional `credentialResolver` on the backend; it is called per request, permitting rotation. Diagnostic errors redact the resolved credential, but raw successful data can still be sensitive. Keep credentials off frontend clients.

Token usage and cache counts are reported only when returned by Ollama; durations and other terminal fields remain in private metadata, with full raw frames retained separately. Their presence does not guarantee caching or any model-specific behavior. Consult [the parameter inventory](ollama-parameters.md) for the pinned official schema, nested fields, source gaps and scope. A raw field being forwarded does not imply normalized runtime support. Fixture tests and compilation do not establish live model or device behavior.


# Source: docs/ollama-parameters.md

# Ollama API parameter inventory

The [official OpenAPI](https://raw.githubusercontent.com/ollama/ollama/e9fde36d75fea66579d84099956ce1430792737a/docs/openapi.yaml) and [Go API types](https://raw.githubusercontent.com/ollama/ollama/e9fde36d75fea66579d84099956ce1430792737a/api/types.go) are pinned at `e9fde36d75fea66579d84099956ce1430792737a` under MIT. The [machine-readable inventory](ollama-api-inventory.json) records selected operations and nested schema fields, union shapes, and reviewed Go-only additions. The OpenAPI can lag the server types: for example, it omits message `thinking`, `tool_name`, `tool_call_id`, and tool call `id` and `function.index`. Neither source establishes model-specific support.

Agent chat owns model, messages, tools and stream construction and maps selected text and tool events. Raw native access handles other fields; agent chat retains raw frames, including logprobs, and terminal metadata in private provider output, without dedicated normalized events for every field. Generate, embed and show have no automatic agent execution. Check the implementation and tests for the actual extent of raw access; inventory is source coverage, not live verification.

Chat and generate stream **newline-delimited JSON**, not SSE; stream defaults to true. Embed and show return JSON. Image bytes are base64 strings in JSON. Go types allow embed input as text, batches, or multimodal text/image/audio maps; audio and image blobs are base64. The `format` union includes `json` or a JSON schema object; `think` is boolean or a model-defined string. `keep_alive` accepts seconds or a Go duration string; negative means keep loaded, zero unloads. Duration metrics are nanoseconds; `prompt_eval_cached_count` is a reported metric, not a cache setting.

Chat history may include assistant thinking, tool calls, tool result `tool_name` and `tool_call_id`. Tool-call `id` is optional; `function.index` is an integer and arguments are an object. Responses may contain part of a message; the pinned types do not define a universal merge rule for repeated call fragments. Preserve raw events and avoid assuming that a repeated index always represents an appendable delta.

Run `python3 tool/ollama_contract.py --check` offline; `--upstream` compares the official current source bytes without changing the pin. The OpenAPI JSON snapshot is a parsed representation of the retained YAML. Review both source diffs, update the JSON snapshot, fixtures and dispositions before refreshing. No model download or live model call is required.


# Source: docs/dart-frog.md

# Dart Frog

`agent_weave_dart_frog` exposes native Dart Frog handlers for streaming chat,
owner-scoped history, and typed generation. Add `agent_weave`,
`agent_weave_dart_frog`, and `dart_frog` to your application dependencies.

The following complete example runs without a provider key:

```dart
import 'dart:io';

import 'package:agent_weave/agent_weave.dart';
import 'package:agent_weave_dart_frog/agent_weave_dart_frog.dart';
import 'package:dart_frog/dart_frog.dart';

Future<void> main() async {
  final token = Platform.environment['DEMO_TOKEN'];
  if (token == null || token.isEmpty) {
    stderr.writeln('Set DEMO_TOKEN to run this local demonstration.');
    exitCode = 1;
    return;
  }
  final handler = chatHandler<void>(
    agent: AiAgent<void>(model: const OfflineModel()),
    authenticate: (context) =>
        context.request.headers['authorization'] == 'Bearer $token'
        ? (ownerId: 'demo-user', context: null)
        : null,
  );
  final server = await serve(handler, InternetAddress.loopbackIPv4, 8080);
  print('Demo listening at http://${server.address.address}:${server.port}');
}

final class OfflineModel implements ChatModel {
  const OfflineModel();
  @override
  ModelCapabilities get capabilities => const ModelCapabilities();
  @override
  Stream<ModelEvent> stream(
    ModelRequest request, {
    required CancellationToken cancellation,
  }) async* {
    cancellation.throwIfCancelled();
    yield const TextDelta('Hello from the offline Dart Frog example.');
    yield const ModelFinished();
  }
}
```

For an existing Dart Frog application, return the handler's response from your route. Authentication must
verify the request and supply the owner from trusted server-side identity, not
from JSON. The handler accepts POST chat requests and GET history using
`?threadId=...`, with optional `limit` and `before`. Reconnect to a run
with `?runId=...&offset=...` to replay events after a sequence. The streaming response
uses server-sent events. Cancellation follows the Dart stream subscription;
network disconnect detection depends on the HTTP server and intermediaries.

For typed generation, use `generationHandler<C, P, R>` with a
`GenerationTask<P, R>`, the same authentication callback, and a `decode`
function that receives both request parameters and the trusted authenticated
context: `decode: (input, context) => ...`. Use the context to bind any
user-specific parameters rather than trusting identity fields in the body. Both
handlers limit request bodies to 1 MiB
by default; configure `maxRequestBytes` when needed.

Run the offline example from the workspace root:

```sh
DEMO_TOKEN=local-example dart run examples/dart_frog/server.dart
curl -N -H 'Authorization: Bearer local-example' -H 'Content-Type: application/json' \
  -d '{"threadId":"demo","runId":"first","messages":[{"id":"u1","role":"user","content":"Hello"}]}' \
  http://127.0.0.1:8080/
```

The fixed token and fixed owner are for local demonstration only, not production
authentication. The default in-memory store is process-local and is not durable.

Your application owns the agent, store, and provider client lifetimes. Keep any
authenticated context resources valid until the response stream finishes.
Close shared provider clients when the application shuts down.


# Source: docs/openai-options-audit.md

# OpenAI options audit

Historical baseline audit (see updates below): `agent_weave_openai` and installed `openai_dart` 11.0.1, compared with the [Responses API](https://platform.openai.com/docs/api-reference/responses/create), [computer-use guide](https://platform.openai.com/docs/guides/tools-computer-use), and [Realtime API](https://platform.openai.com/docs/api-reference/realtime). This is a source review, not an exhaustive certification of all OpenAI endpoints or individual nested SDK fields. No live API calls were made. SDK types or raw HTTP access do not imply AgentWeave orchestration or a working end-to-end feature.

| Area | SDK and adapter coverage | Gap and priority |
|---|---|---|
| Canonical request | `chat_models.dart:90–118,203–275` maps runtime messages, tools, instructions, token limit and output schema; typed `configure` can replace the whole request. | **P0:** replacement can silently erase or alter runtime messages, tool definitions, schema, and Responses encrypted-reasoning include. Define ownership and merge rules, preserve canonical inputs/tools, and test multiple turns and callback conflicts. Changing model also makes emitted usage report the constructor model, not necessarily the actual model. |
| Responses options | SDK `CreateResponseRequest` includes model/input, instructions, tools/tool choice, previous response ID, max output/tool calls, temperature/top-p/penalties, reasoning/text, truncation/context management, parallel calls, service tier, metadata, include/store/background, safety/moderation, cache key/options/retention, top logprobs, multi-agent and access programs. Callback can set SDK-supported fields. | **P1:** options are not first-class runtime semantics; callback can conflict with canonical history and can overwrite required includes. SDK `createStream` forces `stream=true`; adapter never passes `beta=true`, required by SDK for multi-agent. Background and prior-response state need explicit lifecycle and duplicate-history rules. Check server/model constraints. |
| Responses events | `chat_models.dart:124–172` handles text/refusal/reasoning-summary deltas, completed function calls, final output and token usage. Full completed output is saved as provider replay. | **P0:** only `function_call` becomes a runnable `ToolCallReady`; computer, custom, shell, apply-patch and approval continuations are not dispatched. All tool messages become `function_call_output`. Hosted-tool events and results are retained for replay only and are not surfaced as typed progress/results. Refusals lose their distinction, incomplete causes collapse to length, errors lose details, and no terminal event is required before stream EOF. Preserve IDs, statuses, annotations, errors, incremental events and output kinds. |
| Computer use | SDK parses `computer_call` output (`models/responses/items/output_item.dart`); callback can configure SDK tool types. | **P0:** no action executor, screenshot result, safety-check acknowledgement or correct `computer_call_output` continuation in runtime. SDK `items/item.dart` dispatch does not list `computer_call_output`: verify its round trip and contribute a typed input item upstream if missing. Raw JSON sent independently is not an AgentWeave computer loop. Explicit authorization and sandbox controls belong at the execution boundary. |
| Function tools | Runtime tool schemas and JSON-object arguments are mapped; tool calls are dispatched. | **P1:** `strict:false` is fixed, arguments are assumed JSON objects, output is text only, and per-tool provider options are absent. Validate schema/arguments, preserve tool IDs and correctly represent multimodal and non-function results. Hosted tools need not be run locally. |
| Cache and state | SDK supports `prompt_cache_key`, options and retention; adapter reports `cached_tokens` if usage is present. Responses defaults to `store:false`, includes encrypted reasoning, and replays completed output. | **P1:** setting a key is not evidence of a cache hit; no cache hit/miss diagnostics or cache lifetime validation. Changing `include` can drop encrypted reasoning. `store`, `previous_response_id`, conversation state, deletion and retrieval have privacy and replay implications; test exact outgoing payloads and cache usage with an authorized live run. See [prompt caching](https://platform.openai.com/docs/guides/prompt-caching). |
| Query and transport | SDK `responses.retrieve` and input-item `list` accept typed `include[]` and pagination; `platform_api.dart` supports JSON, binary GET, repeated query keys, idempotency and cancellation with client interceptor chain. | **P1:** these are separate SDK/raw operations, not run lifecycle integration. Raw helper now supports GET/POST/PUT/PATCH/DELETE/HEAD, per-request safe headers, arbitrary JSON roots, response status/headers/bytes, and repeated queries for downloads. Multipart upload and arbitrary SSE remain outside this helper. Typed stream exposes abort and beta but adapter exposes only abort. Provide per-request transport options without compromising auth, retry, secret redaction or canonical request ownership. |
| Chat completions | SDK request exposes sampling, penalties, logit bias/logprobs, n, stop, tools, output format, audio/modalities, prediction, search, caching, safety, metadata/store and more through callback. | **P1:** `chat_models.dart:297–318` ignores choices other than index 0; audio output, logprobs and other deltas are not emitted, even when enabled. Either support each requested output or reject unsupported configurations; test `n`, audio and tool streaming. File and video input are explicitly rejected. |
| Images/audio/embeddings/video | `generation_models.dart` forwards SDK request objects for image generation, speech, transcription, embeddings, decision and video. Speech/transcription streaming and image streaming exist. `generation_tasks.dart` normalizes image, speech and transcription results. | **P1:** forwarding only covers fields represented by the pinned SDK; normalized tasks drop provider-specific metadata (including transcription detail) and create local IDs. Image nonstream and video create cannot abort in-flight through these wrappers; cancellation of local video waiting does not cancel a server job. Image edits/variations, translation and job operations remain direct SDK/raw workflows. Audit individual request serialization and response fields before claiming all media options. |
| Realtime | `OpenAIRealtimeModel` passes a typed session config including audio, modalities, tools, reasoning, tracing, truncation and include to SDK connection; caller owns returned session. | **P1:** this is connection access, not runtime event, tool, interruption or voice orchestration. Connection cancellation is checked before and after connect rather than aborting the handshake; session lifetime is caller-owned. WebRTC, SIP, client secrets and raw realtime events require separate SDK/API paths and their own verification. |
| API surface and future fields | Public package exports SDK surfaces; raw helper can address additional JSON endpoints. | **P2:** typed parsing may reject or drop unknown fields, while raw path has transport and response restrictions above. Inventory each endpoint, parameter, nested union and event against a dated official spec; test unknown enum/item handling. Contribute missing fields upstream rather than presenting reexports as complete integration. |

## Verification and proposed sequence

1. Add fixture-based request/stream tests proving canonical messages and tools survive configuration, required includes are merged, usage identifies the actual model, and unsupported combinations fail visibly. Cover cancellation, EOF, incomplete/failure causes, `n > 1`, cache options and repeated query keys.
2. Design typed provider events and continuation items before implementing each client-executed tool loop. Verify call IDs, multiple actions, screenshot content and safety acknowledgements across at least two turns; separately expose hosted-tool results and approvals. Keep side-effectful execution opt-in and constrained by caller policy.
3. Expose response-state and request transport controls with explicit storage, replay and retry semantics. Test retrieve/list query encoding, background lifecycle, and redaction using mock HTTP.
4. Audit every media/realtime SDK request and output union against the official endpoint schema, then add serialization and event round-trip fixtures for each claimed field. Submit reproducible upstream issues or patches for confirmed SDK omissions; preserve compatibility with the pinned version.
5. Only after fixture coverage, run separately authorized, cost-bounded live scenarios for real model/tool capability, cache metrics, media and realtime. Unit fixtures establish serialization and orchestration, not server behavior, model support or actual cache hits.

Existing tests in `packages/agent_weave_openai/test` use fixtures and cover selected text, function-call, generation, transport and cancellation paths. This audit did not run them or establish exhaustive coverage.

## Update: current worktree

The current `chat_models.dart` now guards runtime-owned messages/input and token limits, requires each runtime tool exactly once, and protects an existing runtime output schema; it merges `reasoning.encrypted_content` into Responses `include`. Usage reports only an actual model returned in the stream; it does not guess the requested alias when the provider omits identity. Fixture tests in `chat_models_test.dart` cover rejected conversation replacement, include merging, cache key/metadata serialization, and Responses returned-model usage. These changes supersede the corresponding earlier P0 request-replacement and P1 include/model findings; they do not establish exhaustive configuration coverage or live behavior. The other non-function tool continuation gaps remained open at that point; see the computer update below. The guard only compares runtime fields present in the canonical JSON and permits additional provider tools; audit individual conflicting settings before claiming full option safety.

The current raw transport fixtures verify request-specific safe headers, repeated
queries on binary downloads, raw status/headers/bytes, arbitrary JSON root
values, authenticated PUT requests, pre-cancellation and mutation retry policy.
This raw helper does not implement SSE or multipart; the separate Responses adapter handles selected computer orchestration as described below.

## Computer-use SDK contribution

[Upstream PR #430](https://github.com/davidmigloz/ai_clients_dart/pull/430) adds
typed computer-call input replay and screenshot results, including returned-only
statuses and redacted screenshots. Local upstream validation passed 25,235 unit
tests with 3 skips plus package analysis. The PR is submitted, not merged or
released. AgentWeave still uses its published SDK dependency. Shell/custom/patch calls and
MCP approval continuations remain unsupported; selected native computer use is
now integrated as described below.

## Protocol reuse and Chat continuation

The current SDK facades delegate canonical encoding and normalization to reusable
protocol models. Chat assistant history now uses text or null as required by the
SDK request type; two-turn tool continuation previously failed before dispatch
because assistant content was encoded as a user-style parts list. Protocol and
actual SDK transport regressions now exercise the second request.

Chat explicitly rejects multiple choices and requested audio output instead of
silently dropping unsupported results. Responses requires a terminal event before
EOF. These supersede the corresponding silent-drop/EOF observations above;
remaining event and media gaps are still open.

## Selected native computer integration

`OpenAIComputerTool` registers an application-executed native computer tool with
`OpenAIResponsesModel`, including the GA and legacy preview definitions. The
runtime validates completed calls, preserves action order, pauses for approval as
configured and whenever safety checks are present, and returns the application's
fresh screenshot with the matching `call_id`. Arguments are immutable and native
approval cannot edit them. The environment binding must remain stable across a
pause. Denial, cancellation, or executor failure closes the continuation with
its audit history intact; an application must not invent a computer result to
continue it. The application owns the actual driver, permissions and side effects.

This is selected computer orchestration, not support for other native tool kinds
or client-executed native tools. The [computer guide](computer-use.md) describes
the driver contract and its operational limits. Offline contract fixtures do not
prove live model or server behavior, including GA safety acknowledgements.

The Responses facade consumes raw SSE JSON through the SDK transport before
typed event decoding. This preserves original private item fields for replay and
lets the computer validator reject unknown action fields before execution.


# Source: docs/provider-coverage.md

# Provider coverage and roadmap

Status: incremental inventory, not an assertion of complete provider support. Reviewed the repository and linked provider documentation on 2026-11-04; provider APIs, models and SDK versions change. No paid calls or external mutations were made. The goal is to account for **all** options on each explicitly supported API, including nested fields, transport and lifecycle semantics; the table is a starting point rather than a complete field inventory.

## What exists

The workspace has `agent_weave_openai` backed by `openai_dart` 11.0.1, plus the `ChatModel` extension interface (`docs/providers.md`). The `agent_weave_anthropic` package has native JSON/SSE transport and a lossless Messages normalizer, plus an SDK-backed facade using `anthropic_sdk_dart 9.0.1`, with offline fixtures. The `agent_weave_openrouter` package has a native JSON transport, separate Chat and stateless Responses adapters, native options and offline fixtures. The `agent_weave_together` package provides native Chat Completions and offline fixtures. The Vercel Gateway package implements public Chat and Responses adapters with offline fixtures. The Cloudflare package implements selected native Workers AI, Gateway run, and compatible Chat and Responses contracts with offline fixtures. `OpenAIChatModel` maps runtime history and function tools to streamed Chat Completions and supports a typed SDK `configure` callback. OpenAI-compatible base URLs can be supplied through the SDK client, but neither this configuration nor custom provider support establishes endpoint-specific compatibility. Runtime currently interprets only part of the returned stream, as documented in [the OpenAI audit](openai-options-audit.md). `OpenAIPlatformApi` is a restricted JSON/raw transport, not a complete native or streaming provider adapter.

| Provider and API | What the repo implements | Significant missing work and evidence |
| --- | --- | --- |
| OpenAI native Responses and Chat | Dedicated SDK-backed adapter, selected generation/media wrappers and typed/native options; Responses also supports the application-executed native computer tool and selected hosted-tool output with lossless private replay and completed images. Remote MCP approval/denial and private replay have offline coverage; see [MCP approvals](openai-mcp.md). Direct [custom text tools](openai-custom-tools.md) have typed executors, namespaced automatic selection, approval/resume and native outputs. | See [OpenAI audit](openai-options-audit.md): shell/patch continuations, asynchronous and programmatic custom execution, namespaced function tools, precise public highlights, hosted progress, partial images, other events/transport and complete field-by-field coverage remain open. The selected hosted declaration inventory is in [hosted tools](openai-hosted.md). Computer model and driver behavior require separate live verification. |
| Anthropic native Messages | Native JSON/SSE client with request options, rotating credentials, deadlines and cancellation; a guarded Messages normalizer retains unknown fields on supported blocks, signed thinking, private citations and cumulative usage. The typed SDK facade remains available. | The [inventory](anthropic-parameters.md) classifies 19 request fields and follows selected nested declarations. The 17-member application-executed computer toolset and scoped file-ID documents are integrated. Pinned hosted result blocks, bounded paused turns and container reuse now have offline integration fixtures. Native MCP use/result/listing replay, three explicit beta modes, mixed local approvals and indeterminate recovery have offline fixtures; see [MCP](anthropic-mcp.md). Complete nested semantics, browser tools, inline tool-change messages, other endpoint workflows and live behavior remain incomplete. Raw access and SDK exports do not establish those integrations. See [Anthropic](anthropic.md). |
| OpenRouter Chat, Responses and dedicated images | Native JSON/SSE client, separate Chat and stateless Responses adapters, selected routing/reasoning/cache options and private replay. Dedicated Image API has typed requests/results, discovery capabilities/pricing, four native SSE events and same-request buffered fallback. | The [inventory](openrouter-api-reference.md) records all 144 pinned operations; five have selected integrations. Management, background jobs, hosted tools, streamed Chat images, audio and exhaustive fragment/model behavior remain incomplete. Fixtures do not establish live billing, routing or model acceptance. See [OpenRouter](openrouter.md) and [dedicated images](openrouter-image-api.md). |
| Together Chat Completions | Native JSON client and agent adapter, typed options, and offline request and streaming fixtures. The [chat inventory](together-chat-inventory.json) records the disposition of 27 pinned request fields. | The inventory is not complete API or model certification. Native-only fields include multiple choices and legacy function calls. Media and schema acceptance, billing, live cancellation, and live Together behavior remain unverified. See [Together](together.md). |
| Vercel AI Gateway | Public Chat Completions and Responses adapters, typed routing options, raw native JSON and event envelopes, and offline fixtures. | Selected request serialization and stream behavior do not prove live provider semantics, cost, or exhaustive API coverage. Provider identity is not inferred. The internal AI SDK V4 wire protocol is separate. See [Vercel AI Gateway](vercel-gateway.md). |
| Cloudflare Workers AI / AI Gateway | Native run, model discovery, streamed text and selected embedding, transcription, image and traditional chat adapters; Gateway run and compatible Chat and Responses. | Model-specific schemas, availability, live acceptance, caching, binary audio and billing remain unverified. Native traditional tool continuation covers the documented Hermes single-call format only. See [Cloudflare](cloudflare.md). |
| Ollama native local API | Native JSON/NDJSON chat and generate transport, agent chat with thinking/tool replay, typed SDK options and embeddings. The [inventory](ollama-parameters.md) covers four selected operations and reviewed Go-only fields. | No real daemon, downloaded model or Flutter device has been tested. Model availability, remote/legacy tool fragment rules, other endpoints and exhaustive option semantics remain unverified. See [Ollama](ollama.md). |
| Other providers | Custom `ChatModel` can be implemented by users. | No blanket support or parity claim. Add named provider/API/version inventory entries and evidence before advertising them. Model availability, feature support and defaults are not stable constants. |

## Architecture requirements

1. Key capabilities by **provider, API protocol, endpoint and model**, distinguishing supported, unsupported and unknown. Do not advertise unconditional tools, media or structured output for every model. Preserve the core runtime's authoritative conversation and registered tools while allowing explicit provider options; reject incompatible combinations rather than silently ignoring them.
2. Reuse an actively maintained typed Dart SDK when it actually represents the endpoint and preserves required fields. `openai_dart` is already useful for OpenAI and the subset of compatible wire formats its request types model; it is not an Anthropic SDK or proof of arbitrary extension support. Evaluate candidate native SDK maintenance, license, streaming, cancellation, types, unknown fields and release cadence before adoption. Where a specific field or union is missing, reproduce the omission against official docs and submit a focused upstream issue or patch with serialization and round-trip tests; do not fork preemptively.
3. Define explicit provider-specific typed options plus a controlled forward-compatible extension mechanism where transport supports it. Separate request fields, query parameters, request-scoped headers, multipart/binary data and SSE/WebSocket transport; preserve auth, cancellation, timeouts and safe retry/idempotency semantics. Never log credentials or sensitive replay blocks. An escape hatch alone does not implement orchestration.
4. Preserve raw provider continuation privately and round-trip every relevant block in order. Map function calls, application-executed computer calls, other native and hosted tools, approvals, tool results and IDs distinctly; do not force all results into a function-output schema. Preserve refusal, errors, finish reasons, structured output, citations, reasoning, media, cache and usage/provider metadata without presenting private continuation as UI text.
5. Inventory all create/retrieve/list/delete/cancel/query operations, paging, background jobs, cache and storage settings, file/media upload, realtime and model-specific limits separately. Make explicit whether each is typed SDK access, raw escape hatch, integrated runtime behavior, fixture-verified or live-verified.

## Verification and upkeep

- Maintain a versioned machine-readable inventory per provider/API/endpoint: official source URL and revision/date, request and response field/union, defaults, constraints, SDK representation, adapter handling, tests and status. Generate a human-readable coverage report and fail CI on unexplained inventory/spec changes when a reliable machine-readable spec is available; manually review provider changes where it is not.
- Offline contract fixtures must assert exact request JSON/headers/query and parse provider event sequences. Cover text, schema, fragmented parallel tool arguments, multi-turn replay, hosted vs client tools, rejection, malformed/unknown events, errors, EOF, usage, caching markers, pagination, cancellation, privacy and retry. Add endpoint-specific incompatible-option tests. Include a mock HTTP consumer scenario for each claimed compatible provider, not just SDK unit tests.
- Separately run explicitly authorized, spend-limited live smoke tests per provider/model/endpoint for text, tools, structured output, usage and any claimed media/cache behavior. Record model, date, capability, output and whether a real cache hit occurred; a fixture, reexport or HTTP 200 is not proof of real orchestration. Re-run after SDK or provider-spec changes. Do not treat this roadmap as completed until every supported surface has an inventoried, tested status and known exclusions.


# Source: docs/compatibility.md

# Compatibility

The interoperability baseline is `@tanstack/ai-client 1.0.1` and
`tanstack_ai_dart 0.4.0` at commit
`819ff289e6dabc5f424208b07ea9ac6f399cdccc`.

The root workspace pins the Dart client through a Git dependency override
because 0.4.0 was not on pub.dev when this workspace was created. Remove the
override only after checking the published package and rerunning interop tests.

## Implemented contracts

- Text streaming, standard reasoning events, and structured-output events.
- Native OpenAI Responses output references and buffered Chat URL references; see
  [output references](output-references.md).
- Typed Anthropic text citations, CUSTOM events, snapshots and hydration; see
  [citations](citations.md).
- Ordered completed media parts in assistant history, client snapshots and hydration.
- Selected OpenAI Responses hosted search, code, image and server tool-search
  output with private replay; see [hosted tools](openai-hosted.md).
- Anthropic Messages MCP servers, private use/result/listing replay and mixed local-tool continuation; see [MCP](anthropic-mcp.md).
- OpenAI Responses remote MCP configuration, private discovery/replay and provider-owned approval/denial through generic client interrupts; see [MCP approvals](openai-mcp.md).
- Configured server tools, client-tool pauses, and default tool approvals.
- Selected OpenAI Responses native computer calls with application-owned
  execution, safety approvals, screenshots, and continuation; see
  [computer use](computer-use.md).
- Approval, rejection, edited arguments, and continuation lineage.
- Server-owned conversation history and owner isolation.
- HTTP/SSE chat, history paging, and stored-event replay.
- Native Serverpod streaming through the existing Dart AI client.
- Generic generation progress and results, plus image/speech/transcription
  normalization helpers.

The official JavaScript test verifies text, reasoning, structured output, server tools,
default approvals, client tools, generation, and supported media input/history
round trips against a Dart HTTP server. The Dart tests exercise the client against
the runtime and a generated Serverpod endpoint over a real WebSocket. This is
not a claim of full TanStack AI core parity.

## Declared provider identity across resumes

Native OpenAI Responses and Anthropic Messages bind unfinished local approvals
and provider pauses to
its declared model, frozen options, complete managed-tool set and stable provider
account/transport authority. Managed tools require `authorityBindingId` and
immutable `options`/`toolChoice` in place of arbitrary configuration callbacks.
Old pending checkpoints without their original model profile fail closed.
See [approval contracts](approval-contracts.md#model-continuation-contracts).
This is an adapter capability, not a blanket identity guarantee for all providers
or undeclared custom models. Actual credentials, permissions and external effect
reconciliation remain application responsibilities.

## Pending checkpoint migration

Approvals now require a private exact tool contract. Pending records written by
older revisions without that snapshot cannot resume; start a new conversation
and retain the old history. Public client bindings remain unchanged. See
[approval contracts](approval-contracts.md) for the migration and diagnostics.

## Current limits

- Selected native computer use is implemented for OpenAI Responses and the
  Anthropic computer toolset. The application provides the actual driver. Native
  client-executed tools remain unsupported. Direct OpenAI custom tools support
  text/grammar input, namespaces, approvals and native string/content results;
  see [custom text tools](openai-custom-tools.md). Asynchronous/programmatic
  custom execution and namespaced function tools remain unsupported. Native
  approval arguments cannot be edited.
- Custom approval payload schemas, application-defined generic interrupts, subagents, client-owned MCP discovery,
  and general provider-hosted progress are not implemented. Citation normalization
  covers the five pinned Anthropic variants. OpenAI references retain opaque
  provider coordinates; precise OpenAI highlights and other providers remain open.
- Server tools execute sequentially. Applications can perform concurrency
  inside a tool, with their own cancellation and idempotency policy.
- Disconnecting a direct run cancels its provider request. Replaying a stored
  run does not restart it or recover execution after a server crash.
- Replay observers are bounded to 20 seconds per request. A timed-out observer
  must reconnect; the observation timeout does not cancel the original run.
- PostgreSQL is the supported persistent store. The raw SQL store does not
  claim SQLite compatibility.
- Binary artifact hosting is not implemented. Completed inline media parts are
  retained in stored assistant history and hydration; provider URLs may expire.
  Applications own media storage budgets and rendering.
- OpenAI resource coverage combines typed SDK delegation and an explicit raw
  JSON helper. Complete typed endpoint parity and exhaustive endpoint tests
  remain unfinished.
- Document support varies by adapter. Responses accepts URLs, inline data, and
  OpenAI file IDs. Anthropic accepts URLs, inline PDF, and inline plain text;
  native file IDs use `provider: 'anthropic'`; typed SDK configuration still
  cannot decode those handles. Gateway Responses accepts URLs and
  inline data but blocks file IDs. OpenRouter Responses also accepts URL/inline
  documents and rejects foreign file IDs. OpenRouter Chat, OpenAI Chat
  Completions, and Together reject document parts. See [documents](documents.md) for storage
  implications.
- OpenRouter has separate native Chat and stateless Responses adapters. Selected
  routing, plugin and cache options, ordered private reasoning replay and compact
  provider/cost metadata have offline fixtures. Selected Chat image output uses
  completed messages with private replay across approvals. Complete management,
  background, hosted tools and other media remain unfinished. The dedicated Image
  API has separate typed requests, discovery, native SSE and same-request JSON
  fallback; see [dedicated images](openrouter-image-api.md). These are offline
  fixtures, not live model or billing certification. See [OpenRouter](openrouter.md).
- Anthropic native JSON/SSE access preserves arbitrary JSON, while normalized
  chat handles selected block/delta types and the 17-member computer toolset.
  Pinned hosted blocks, bounded paused turns and container reuse are integrated
  with offline fixtures. MCP adds three explicit beta modes and private listing
  replay; browser tools, live hosted behavior and complete
  nested field semantics remain unfinished. The
  SDK-backed facade retains its pinned SDK transport cancellation limits.
  See [Anthropic](anthropic.md).
- Together Chat has typed options and native JSON methods. Its agent adapter
  supports one choice; model acceptance of tools, schema, and media remains
  unverified. See [Together](together.md).
- Vercel AI Gateway supports selected Chat and Responses contracts with offline
  fixtures; provider selection, model acceptance, and billing are unverified.
  See [Vercel AI Gateway](vercel-gateway.md).
- Cloudflare supports selected native Workers AI, Gateway run, and compatible
  Chat and Responses contracts with offline fixtures. Model availability,
  acceptance and live gateway behavior are unverified. Native traditional tool
  continuation is limited to the documented Hermes single-call format. See
  [Cloudflare](cloudflare.md).
- Ollama native chat uses NDJSON with private thinking, native call ID and metadata
  replay. Typed options and embeddings are available; a real daemon, model and
  Flutter device remain untested. External image URLs are not fetched, only inline
  base64 images are accepted. Conflicting repeated tool indexes fail explicitly.
  See [Ollama](ollama.md).
- Dart Frog handlers support authenticated chat, history, replay and typed
  generation over actual local HTTP. Production authentication, reverse-proxy
  disconnects and durable restart require application-level verification. See
  [Dart Frog](dart-frog.md).
- Microphone capture, playback, WebRTC device behavior, and all provider account
  permissions require application/device testing.

These limits are release work, not hidden fallbacks. See `docs/validation.md`
and `docs/updating.md` before extending a compatibility claim.

## Native Dart streaming

`streamText` and `AiAgent.stream` expose sealed `AgentUpdate` values, including a
typed result from the same execution, without parsing client protocol maps.
Existing clients continue using `AiAgent.run`. The native stream is a backend or
local-model API: interim updates are provisional and final results can contain
private provider continuation. Use hydration projections for UI history.
Protocol journals remain in core; optional adapter-package extraction is not
complete. See [native streaming](native-streaming.md).

## Complete registered-tool profiles

Unfinished checkpoints now store `kind: agent_execution` with the adapter's
model profile and all ordered registered-tool contracts. Prior provider-only
snapshots cannot prove the original complete registry and cannot resume.
Keep the original conversation for history and start a new one. No SQL table
migration or automatic replay is required. Current matching profiles can resume;
completed custom-tool history can replay under a changed registry without
executing its historical calls. See [approval contracts](approval-contracts.md).


# Source: docs/updating.md

# Update upstream dependencies

1. Record the current Dart, Serverpod, OpenAI SDK, and TanStack pins.
2. Run `python3 tool/audit_openai.py` to compare the official operation index.
   Review additions and removals before running `--refresh`.
3. Read the changed request schemas and stream-event contracts. An unchanged
   endpoint URL does not prove an unchanged contract.
4. Update provider fixtures and add a regression test for each behavior changed
   in AgentWeave. Use the provider SDK's own tests as additional evidence.
5. Update the official JavaScript client pin in `tool/interop/package.json` and
   its lockfile when changing the interoperability baseline.
6. Update the Dart client pin independently. Verify its published version before
   replacing the workspace Git override.
7. Resolve the lockfile with the minimum supported Dart SDK, then run
   `dart run tool/check.dart` on both the minimum SDK and stable. New transitive
   versions can require a newer SDK even when application constraints do not.
   Keep fixture and live results separate.
8. Update the compatibility matrix, changelogs, examples, and LLM documentation.

## Serverpod models

Use Serverpod CLI 4.1.0 while the packages target that version. Generate the
storage module before the example application:

```sh
serverpod generate --directory packages/agent_weave_serverpod_storage_server
serverpod generate --directory examples/serverpod/agent_weave_demo_server
```

Create a migration inside each affected server/module directory. Never edit
generated model or protocol files. Run real database tests after a schema or
transaction change.

## Releases

Run publication dry-runs for each package. Publish dependency packages before
their dependants. The native client currently depends on an unpublished Dart
client version, which must be resolved before publishing that package.
Create a reviewed tag and release notes that identify the tested upstream pins
and the remaining limits. A Git push is not a pub.dev publication.

## Pending approval contract migration

Private pending state now records `toolContract` version 1 with full declared
tool configuration. Preserve it as opaque JSON, including native integer values.
Do not derive missing contracts from current tools or public client hashes.
Older checkpoints lack the original exact contract and fail closed; keep their
history and start a new conversation. No database table migration is needed.
See [approval contracts](approval-contracts.md).

## Model continuation migration

Unfinished checkpoints now retain a versioned `modelContinuationContract`.
The current private format is `{v: 1, kind: agent_execution, model: ..., tools: [...]}`.
It binds the complete ordered registered-tool contracts, including tools that did
not produce the pending call. Older pending approvals and provider pauses without
that envelope cannot prove the original registry, even if individual
`toolContract` records and a former provider-only model snapshot are present.
Retain their history and start a new conversation; do not synthesize a binding.
No database table migration is needed.

For native OpenAI Responses with hosted or MCP tools, add a stable nonsecret
`authorityBindingId`, move additional native fields from `configure` into frozen
`options`, and move tool selection into `toolChoice`. Move supported local
function decorations into `functionToolOptions`, keyed by registered name. Declare every managed tool
through `hostedTools` or `mcpTools`. Both Responses model constructors now copy
their collections and are no longer const. Ordinary models retain callbacks,
but callbacks cannot inject managed tools or replace the model/tool choice.

## Custom store migration

`RunStore.complete` must atomically append the terminal event, save the final
checkpoint, and release the reservation. Do not implement it as two separately
committed calls. The shared contract in `test/support/run_store_contract.dart`
runs against both memory and PostgreSQL and exercises rollback and stale writers.

## Together contract snapshots

The native Together adapter is checked against a full official TypeScript SDK
commit. `tool/contracts/together/source.json` records the pin and original file
paths; unmodified reference snapshots retain their upstream license.

Run `node tool/interop/inventory.mjs --upstream` after installing the interop
tool dependencies to detect changes in the two upstream source files. This is
also part of the manually invoked upstream-review workflow. It can report
non-semantic documentation changes; review the source diff.

Select a full commit and update the snapshots before changing the pin. Review
changed field types, nested unions, stream semantics and response handling.
Update the Dart implementation, executable option fixture and `coverage.json`
dispositions, then run `node tool/interop/inventory.mjs --write` and the full
check. To reproduce the offline field check separately:

```sh
dart run tool/together_contract.dart
node tool/interop/inventory.mjs --check
```

A classified field is not evidence of model acceptance or exhaustive coverage.
Keep raw-native access, normalized agent behavior and live results distinct.

## Gateway option declarations

`tool/contracts/vercel-gateway/source.json` pins the official SDK option source
and retains its upstream license. The generated reference classifies named
options, credentials, native extensions and SDK-only fields. It is not a public
endpoint specification. Verify new options against current official HTTP docs.

```sh
node tool/interop/gateway-inventory.mjs --upstream
dart run tool/gateway_contract.dart
node tool/interop/gateway-inventory.mjs --check
```

Review any source change before updating the full commit and snapshot. Update
coverage dispositions, Dart options and fixture, then regenerate with `--write`
and run the full check. The manually invoked upstream workflow compares both
Together and Gateway sources; it does not publish packages or mutate pins.

## Cloudflare contracts

Review the [Cloudflare API reference](cloudflare-api-reference.md) and its
machine-readable inventory when provider schemas or documented contracts
change. Update the relevant implementation, fixtures, and dispositions
together. Verify model-specific schemas separately; an inventory entry does not
prove live model acceptance.

```sh
python3 tool/cloudflare_contract.py --upstream --check
python3 tool/cloudflare_contract.py --check
```

The manual upstream workflow compares the selected Cloudflare OpenAPI paths and
six public model schemas with the reviewed snapshots. It fails on drift and
never rewrites the pin. See `tool/contracts/cloudflare/README.md` for refreshing
the revision, retained licenses and operation dispositions.

## OpenRouter contracts

The OpenRouter source is a SHA-256-pinned official OpenAPI document
with a stated MIT license. Credential-shaped example values are redacted in the
retained snapshot, which has a separate hash. The updater verifies both hashes
and the deterministic transformation. Its inventory retains references and records component
fields once, avoiding repeated expansion of recursive schemas. All operations
receive an explicit status. Selected Chat/Responses behavior and the three
dedicated Image API operations are integrated.

```sh
python3 tool/openrouter_contract.py --upstream --check
python3 tool/test_openrouter_contract.py
python3 tool/openrouter_contract.py --check
dart run tool/openrouter_image_contract.dart
```

Review source drift, the field statuses, implementation and fixture behavior
together before changing the hash. New and removed request fields both require
a disposition update; stale classifications fail the check. New fields forwarded through native JSON
still need a disposition and tests for any claimed orchestration. See
`tool/contracts/openrouter/README.md` for provenance and retained license.

The Image API inventory separately checks request, response, usage, discovery and
capability fields and known stream unions. The executable fixture checks all 17
request fields and both documented event envelopes. Review the difference between
the guide's direct SSE events and the OpenAPI `data` wrapper; do not silently
remove either shape or issue a second POST for a buffered fallback.

## OpenAI computer contract

`tool/contracts/openai-computer/source.json` pins the official `openai-node`
Responses declarations, with its Apache-2.0 license retained beside the source.
The inventory checks selected computer declarations and reviewed field types,
not the entire Responses API. After installing the interop tool dependencies:

```sh
dart run tool/computer_contract.dart
node --test tool/interop/computer-inventory.test.mjs
node tool/interop/computer-inventory.mjs --check
node tool/interop/computer-inventory.mjs --upstream
```

The last command compares upstream main with the pinned projection; review drift and official
provider documentation before changing the revision or regenerating the inventory.
Update the reviewed types, Dart behavior and fixtures together. These offline
checks do not establish live provider or model support.

## Anthropic Messages contract

The official TypeScript source is pinned in `tool/contracts/anthropic/source.json`.
The inventory follows request, response and stream declarations plus their local
type references. Imported types and unrelated endpoints are outside this scope.
Top-level dispositions describe access, not full nested or model semantics.

```sh
node --test tool/interop/anthropic-inventory.test.mjs
node tool/interop/anthropic-inventory.mjs --check
node tool/interop/anthropic-inventory.mjs --upstream
```

Review field and union drift before changing the pin. Update the native client,
normalizer, SDK patch preservation, request fixtures and disposition together.
New raw JSON fields do not imply the agent supports their continuation protocol.

## Anthropic computer toolset

The selected computer projection uses the existing Anthropic source pin. Its
Dart fixture serializes the actual helper, typed configs, all action parameters,
scroll enum values and result payloads. The check runs `dart` from PATH; CI uses
the selected minimum or stable SDK. The upstream-only check does not require Dart.

```sh
node --test tool/interop/anthropic-computer-inventory.test.mjs
node tool/interop/anthropic-computer-inventory.mjs --check
node tool/interop/anthropic-computer-inventory.mjs --upstream
```

Review documentation-only constraints separately, including direct callers,
numeric limits and stopping a batch after failure. The official SDK declaration
currently omits the documented `allowed_callers` field. Parameter forwarding is
not evidence of real desktop operation or complete provider support.

## Ollama native contracts

`tool/contracts/ollama` retains the official OpenAPI and Go API declarations at
the revision recorded in its README. Review both sources: the OpenAPI omits
some fields already present in the Go server types. The selected operation and
field inventory distinguishes raw access from normalized runtime behavior.

```sh
python3 tool/test_ollama_contract.py
python3 tool/ollama_contract.py --check
python3 tool/ollama_contract.py --upstream --check
```

After reviewing a new pin, update source hashes, the parsed OpenAPI snapshot,
Go-only field dispositions and runtime fixtures together. Re-run native NDJSON
transport, private replay, tool-ID/index, cancellation, embedding and independent
consumer checks. The manual upstream workflow compares official source bytes.
Do not infer model acceptance or a universal tool-fragment merge rule from the
source inventory; record actual model/version evidence separately.

## Anthropic hosted lifecycle

Run `dart run tool/anthropic_hosted_contract.dart` after regenerating the existing
Messages inventory. It exercises all pinned server-tool type spellings through
the public constructor and excludes client tools. Review content/result unions,
container metadata, allowed callers and mixed client/server continuation against
the provider docs separately. Update the hosted fixtures, core continuation
tests, PostgreSQL scenario, official-client pause cases and consumer review
together; constructor coverage is not full orchestration or live evidence.

The `code_execution_20260521` caller option alias is documented outside the
response union: the provider returns the `code_execution_20260120` caller tag.
Keep the [programmatic-calling guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling)
and both positive/negative caller fixtures in the review; a request-field pin
alone cannot prove that behavior.


## OpenAI hosted Responses tools

The selected hosted declarations share the OpenAI computer source pin and license.
`tool/contracts/openai-hosted/reviewed-declarations.json` records the reviewed
projection. A field or union change fails the check until it is reviewed.

```sh
dart run tool/openai_hosted_contract.dart
node --test tool/interop/openai-hosted-inventory.test.mjs
node tool/interop/openai-hosted-inventory.mjs --check
node tool/interop/openai-hosted-inventory.mjs --upstream
```

Review native definition fields, output unions and continuation rules together.
Update the reviewed projection, Dart serialization and parser tests before
regenerating the published inventory with `--write`. A private replay field is
not a public UI feature. Keep hosted execution distinct from registered local
functions and explicitly reject lifecycles without a handler.


## Native output reference contracts

The hosted inventory also checks the reviewed Responses annotation/message/part
projection and completed Chat message declarations. Update the immutable source
pins, raw snapshots, reviewed declaration JSON, typed normalization and fixtures
together. Review native coordinate meanings separately from their integer types.
Do not convert provider indexes to UTF-16 or infer filenames from unrelated text.

Run the reference consumers, both client metadata/replay cases and PostgreSQL
approval recreation after a reference change. The default Chat streaming adapter
uses raw SDK events and has its own strict completion guard; compatible adapters
do not inherit that contract. Keep raw audit state separate from public handles.

## Anthropic MCP contracts and migration

The selected beta Messages MCP declarations are pinned separately from the GA
Messages inventory in `tool/contracts/anthropic-mcp`. Preserve its unmodified
source and Apache license. Review the root list, recursive type/union projection,
source hash, documentation constraints and Dart executable fixture together.
`--write` refuses an unreviewed source/projection change. `--upstream` compares
current official main without changing the pin.

```sh
node --test tool/interop/anthropic-mcp-inventory.test.mjs
node tool/interop/anthropic-mcp-inventory.mjs --check
node tool/interop/anthropic-mcp-inventory.mjs --upstream
```

After review, update the source and reviewed declarations, implementation,
normalization tests, configuration fixture and evidence before regenerating
with `--write`. Constructor field coverage is not workflow or live proof.

Anthropic managed tools now require `authorityBindingId`; callbacks migrate to
immutable request, function, container and message/system-cache parameters.
See [hosted options](anthropic-hosted.md#immutable-request-options). Both model
constructors are non-const. Keep the original profile through unfinished turns;
legacy pending state without it fails closed, without a table migration.

## OpenAI custom-tool contracts

The custom projection shares the pinned Responses source with the computer
inventory and adds the unmodified shared format declarations from the same
upstream commit. Update both hashes and reviewed declarations together. Review
custom output content, caller/async modes, namespaces, selectors and stream
identity semantics separately from the shallow union membership inventory.

```sh
node --test tool/interop/openai-custom-inventory.test.mjs
node tool/interop/openai-custom-inventory.mjs --check
node tool/interop/openai-custom-inventory.mjs --upstream
```

The executable Dart fixture accompanies the check. New fields need an explicit
handling disposition; declarations for programmatic callers and namespaced
functions are inventoried but not integrated. Never infer model support or
workflow certification from a constructor or unchanged request URL.


# Source: docs/validation.md

# Validation

This is development version `0.1.0-dev.1`. A passing test verifies its named
scenario. It does not certify every provider endpoint or production deployment.

## Reproduce the offline checks

Requires Git, Dart 3.12.2 or later, Node.js 22 or later, npm, and Python 3.
The first run downloads dependencies and Serverpod's embedded PostgreSQL binary.
No API key is needed. Ordinary tests force the offline provider even if a key
exists in the environment.

```sh
dart pub get --enforce-lockfile
dart run tool/check.dart
```

The check includes formatting, strict static analysis, generated LLM-document
freshness, credential-pattern scanning, unit tests, PostgreSQL/network tests,
and interoperability with the pinned official JavaScript client.

## Verified locally

The latest local verification used Dart 3.12.2. GitHub CI checks both the minimum
SDK and the stable channel; inspect the run for the commit you use.

- 694 Dart unit and regression tests: tool validation, approvals, client tools,
  lineage, cancellation, partial-response retention, safe failure history,
  generation, storage, protocol parsing, and provider fixtures.
- 38 Serverpod integration tests with a real isolated PostgreSQL database:
  authenticated endpoints, a generated-client WebSocket, HTTP/SSE, history,
  replay, owner isolation, event persistence, and reservation contention.
  The HTTP test also runs the official JavaScript client against real Serverpod
  chat and generation routes, including a second turn and persisted history.
- 28 standalone official JavaScript client scenarios against a Dart HTTP server:
  text, server tools, approvals, client tools, reasoning, structured output,
  generation, provider-owned MCP approval/denial, two local-reference edited-approval cases, two provider-continuation cases, typed citations with stored-event
  replay, and eight media/history cases, including ordered output images. The media cases include document
  URL, inline bytes, scoped and unscoped file handles, image/video URLs, and
  inline audio; returned parts pass the official AG-UI schemas.
- 4 additional official JavaScript scenarios use actual Dart Frog handlers and a
  local fake Ollama NDJSON service: text, schema, approval/resume and authenticated
  typed generation, including owner isolation, privacy and safe errors.
- 2 offline checks for the upstream operation-index parser.
- The offline chat, support approval, in-flight cancellation, and schema-diagnostic examples execute successfully. Independent support and diagnostic consumer applications also pass.

Provider fixtures cover native Anthropic Messages and OpenAI Responses/Chat
Completions streams, schema output,
usage, opaque reasoning replay, cancellation, image/audio/embedding/Decisions/
video requests, binary and multipart transport, and the raw API helper. Realtime
uses an actual local WebSocket; it does not contact OpenAI.

CI is configured to repeat the offline checks on Dart 3.12.2 and stable on
Linux. Check the repository's current Actions run before treating that matrix
as verified.

## Live OpenAI evidence

Eight explicitly authorized requests passed on November 3–4, 2026 UTC:

| Check | Provider model | Evidence |
| --- | --- | --- |
| Responses text | `gpt-5.4-nano` | Stream completed; usage returned |
| Chat Completions text | `gpt-5.4-nano` | Stream completed; usage returned |
| Structured output | `gpt-5.4-nano` | Schema-validated JSON |
| Server tool round trip | `gpt-5.4-nano` | Two invocations; tool executed and answer completed |
| Embedding | `text-embedding-3-small` | Requested vector dimensions returned |
| Image | `gpt-image-2` | One low-quality 1024×1024 image; 725,797 PNG bytes |
| Speech | `gpt-4o-mini-tts` | Short speech request; 36,044 WAV bytes |

Chat invocations reported 212 input and 51 output tokens in total. The image
reported 16 input text tokens and 196 output image tokens. Provider billing is
authoritative; these observations are not an invoice.

`tool/live_smoke.dart` and `tool/live_media_smoke.dart` are opt-in. They share
`.dart_tool/live-budget.json` and never run in CI. The ledger conservatively
reserved $2.75 across the eight requests, within the user's $5 maximum. The
current guard refuses requests beyond $4 in cumulative reservations. Actual
usage cost is much lower than those reservations. Do not reset that ledger to
bypass the cap. The guard is a bounded test allowlist, not a general billing
system. Keep keys in environment variables only.

## Package validation

The initial six-package publication dry-runs passed with zero warnings from a
clean checkout. That evidence predates the Anthropic and OpenRouter packages. The new OpenRouter
package also passed a publication dry-run with zero warnings on Dart 3.12.2. Core and OpenAI API documentation generated with zero warnings or
errors. Serverpod code generation was rerun without changing the checked-in
outputs. The native client reports
an override hint because its `tanstack_ai_dart 0.4.0` dependency is Git-pinned
in this workspace and was not published to pub.dev at validation time. Resolve
that dependency before publishing the native client. A local dry-run does not
prove that pub.dev can resolve the entire unpublished package family.

## Not verified live

No paid video jobs, realtime sessions, transcription, Decisions, administration,
storage jobs, or other delegated resources were invoked. Their local fixtures
and typed SDK access do not substitute for account-specific live tests.

Flutter device rendering, microphone permissions, audio playback, WebRTC,
production authentication, production deployment, and pub.dev publication have
not been tested or performed. See [compatibility](compatibility.md) for remaining
implementation limits.

## Native Anthropic increment

Thirteen native Messages fixture tests and a separate consumer over real loopback
HTTP verify selected text, schema, tool, thinking replay, cache configuration,
error and cooperative cancellation contracts. No live Anthropic account, model,
real cache hit or network-abort behavior was tested. The independent review is
8.0/10 for the reviewed general SDK journeys and provisionally 7.8/10 for the
new native provider path; see [the review record](dx-review.md).

## Persisted approval process restart

The isolated PostgreSQL test now starts the actual backend and approval CLI in
separate processes, exits both, starts a fresh backend against the same database
files, and restores/resolves the pending approval from a fresh client. A further
fresh client rejects the already-completed decision. The independent Terra
reviewer reran the test successfully on Dart 3.12.2 and scored this targeted
journey 8.5/10. This is graceful restart evidence, not arbitrary-crash recovery
or proof of exactly-once external effects.

## Documents and OpenRouter increment

Fifteen core document tests cover construction, validation, storage and authorized
history round trips, legacy source aliases, capability rejection, and releasing
reservations without erasing an unreadable snapshot. Provider fixtures verify
Responses URL/data/file-ID mapping and foreign-provider rejection; Anthropic PDF
URL, PDF bytes and UTF-8 text plus unsupported ID/format failures.

Three OpenRouter loopback tests verify selected routing/header options, streamed
tool arguments, actual model usage, inline errors and pre-cancellation. Two
independent consumer programs, `examples/review_cases/documents.dart` and
`examples/review_cases/openrouter.dart`, run in the normal check. The reviewed
journeys scored 8.0/10 and 7.8/10 after documentation fixes. Neither score
certifies complete provider support. No new live API calls were made.

## Native Together increment

Eighteen Together tests run a local HTTP service and cover native numeric
`logprobs`, immutable options, schema/tool serialization, reasoning replay,
fragmented tool arguments with repeated IDs/names, usage after finish, bounded
text output, native metadata, multi-choice EOF, stream/HTTP errors and private
diagnostics. Cancellation is tested before sending, before response headers and
during the body. Cancelling the native stream subscription also aborts a
pending request without closing the shared client; a stalled response tests
per-request timeout. These are real
local HTTP tests, not live Together calls.

The independent consumer program exercises schema output, a stored tool approval
and continuation, reasoning/tool replay, partial output and error diagnostics.
Its targeted offline DX score remains 8/10; it does not certify production
behavior or all native fields.

The offline AST tool has three parser/coverage tests. It extracts the pinned
official SDK declarations and checks all 27 top-level chat request fields have
reviewed dispositions. An executable Dart fixture serializes every typed option.
`--upstream` was also run against current official source and found no difference
in the pinned files. No new paid requests were made.

The Together package publication dry-run passed with zero warnings on Dart
3.12.2. This is packaging evidence, not a pub.dev publication.

## Gateway, protocol and shared transport increment

Seven Gateway fixtures cover separate public Chat/Responses requests, routing
serialization, concurrent rotating bearer/BYOK credentials, private redacted
HTTP and SSE diagnostics, request cancellation and controlled native extensions.
Nine shared HTTP tests cover fragmented UTF-8/CRLF/multiline SSE with event IDs
and headers, credential-wait cancellation/deadlines, late-dispatch prevention,
pending-header cancellation, custom clients with stalled bodies, malformed frames,
request validation and borrowed-client ownership. Together's existing 18 tests
pass against the shared transport.

The 28 OpenAI chat/protocol tests now include protocol and actual SDK two-turn
Chat tool continuation, assistant text/null encoding, provider replay/file-handle
isolation, explicit unsupported choices/audio, Responses EOF, and independent
subscription cancellation with a concurrent request. Three core tests cover
sticky cancellation events and disposable listeners.

The independent Gateway consumer tests both protocols through schema generation,
stored approval/resume, request credential rotation, serialized UI hydration,
wrong-provider replay exclusion and native response metadata. Both public guide
examples compile unchanged. Its documented targeted score progressed from 5.8
to 6.4 and then 7.6/10 after fixes. These are local fixtures, not a live Gateway
account, Flutter UI, secret manager, route selection, cache hit or billing test.

The five AST/coverage parser tests and executable Dart fixtures verify reviewed
Together fields and 16 named Gateway SDK options. The Gateway source type permits
unknown service options; classifying its fields does not prove a complete public
HTTP contract. No new paid provider calls were made.

Both new HTTP and Gateway package publication dry-runs passed with zero warnings
on Dart 3.12.2. Neither package has been published to pub.dev.

## Cloudflare and cancellation increment

Sixteen Cloudflare fixtures cover distinct native, Gateway and compatible wire
contracts, model-schema GET queries, embedding shape/pooling, binary and JSON
audio, binary images and decoded Flux image JSON, request snapshots, credential
rotation/redaction, approval and the documented single-call native continuation.
Raw streaming cancellation is checked after headers and a data event. Client
Gateway defaults and explicit request overrides preserve authentication.

The independent consumer exercises both compatible protocols through two-turn
tool continuation, typed media results, stored native approval, cancellation
during credential resolution and after sending, and Gateway header inheritance.
Its after-headers streaming fixture also passes over actual loopback HTTP. The
complete guide entry program was compiled unchanged, without invoking Cloudflare.
The targeted review improved from 7/10 to 8/10; it is not SDK-wide acceptance.

Twelve shared HTTP tests now include GET/HEAD with repeated queries, binary PATCH
bytes and immutable snapshots, MIME/byte validation and body/method rejection
before dispatch. Shared stream binding isolates sibling calls while synchronously
propagating parent cancellation. The full suite caught and now prevents an extra
buffered text chunk entering cancelled history. Core, provider and generation
regressions verify cleanup and independent shared-parent calls.

The Cloudflare extractor has five tests for reference closure, escaped and
recursive schema references, nested unions/constraints, and explicit operation
status. It records all 82 operations across 50 AI/Gateway paths in the pinned
OpenAPI, four selected integrations, and six public model schemas with hashes.
The explicit upstream comparison matched current official sources. Compatible
Chat/Responses endpoints are documentation-only contracts outside that OpenAPI
revision; their separate fixtures do not certify all fields or models.

The documentation build and two routing/search tests pass. The Cloudflare package
publication dry-run has zero warnings. No package was published, no model license
was accepted, and no paid Cloudflare or other provider calls were made. Live
model availability, Gateway routing/cache hits, binary audio Content-Type
acceptance, billing, management operations and exhaustive provider parity remain
unverified or unimplemented as listed in the inventory.

## Native OpenRouter and lossless Responses replay

Fourteen OpenRouter fixtures cover native typed options and guarded JSON
extensions, ordered Chat reasoning, stateless Responses replay, raw metadata,
per-request credentials, malformed SSE, resolver errors, cancellation and client
ownership. The shared Responses codec now uses immutable raw input snapshots,
retaining reasoning and valid tool-output fields the typed input decoder could
reject or omit. Forty Chat/Responses codec tests include unknown fields,
actual SDK encrypted-reasoning replay, pre-callback canonical snapshots, missing
instructions, alternate token bounds and stream-option protections. Usage
model identity comes only from reported response data, including earlier stream
frames; it is not guessed from a requested alias. Together has the same rule.

The independent native consumer tests schema generation through both protocols,
persisted approval and resumed tools, recreated agents, opaque ordered reasoning,
IDs/statuses and matching tool outputs, no private replay in UI hydration,
actual model/provider/cost metadata, absence of usage, credential rotation,
redaction, network cancellation and borrowed-client ownership. The guide's first
program was compiled unchanged without paid execution. Its five qualitative
ratings average 7.6/10 after the guide and fixture changes. This is a targeted
review, not SDK-wide acceptance or live service evidence.

The OpenRouter source inventory accounts for 146 operations across 108 paths
and records reusable component fields without expanding recursive references
at every use. Six new extractor tests and the five Cloudflare extractor tests
pass; the refactored shared helper produces the unchanged Cloudflare inventory.
The explicit upstream OpenRouter comparison matched the pinned document hash.
Only Chat and Responses have selected integrations; other operations remain
not integrated. Source forwarding does not implement every response union or
background job.

No new paid requests or package publications were made. Live OpenRouter routing,
cache hits, cost/billing, model-specific reasoning fragments, management APIs,
hosted tools and output media remain unverified or unfinished.

OpenRouter credential-shaped source examples are deterministically redacted
before storage and generation. Original-source and retained-snapshot hashes
are verified separately. The local credential scan also checks OpenRouter key
formats and includes the full source snapshots.

## Native computer increment

Seven core tests cover native definitions and call snapshots, provider/kind
matching, mandatory approval, atomic answer validation, definition/environment
binding, denial and closed continuation. Fourteen OpenAI computer tests cover
GA and preview tools, all nine action types and their parameters, five preview
environments, screenshot forms, exact safety acknowledgements, terminal status,
immutability and rejection of unknown action fields before execution. Three
provider guard tests reject foreign native definitions and history before HTTP.
All 85 OpenAI package tests pass with the raw Responses SSE transport, including
SDK cancellation and shared-client ownership regressions.

The PostgreSQL test persists and reloads a pending native approval, rejects
changed targets, resumes once and rejects a duplicate decision. It uses the real
store and a scripted model, not a paid provider or computer driver. Two new
standalone official JavaScript client cases exercise native approval and denial
through generic interrupts, history hydration and privacy.

The independent computer consumer runs 15 loopback scenarios through the actual
SDK client with an application-owned fake executor. It verifies ordered actions,
approval/continuation with a recreated agent, exact IDs, private raw replay,
UI privacy, malformed/truncated responses, cancellation and unknown action/drag
fields. The complete driver guide analyzes and compiles unchanged. The targeted
qualitative DX score is 7.8/10; see [the review](dx-review.md).

Four source-contract tests plus an executable Dart fixture check selected pinned
official Node declarations, nested action fields, preview environments and
controlled acknowledgements. The explicit upstream comparison matched the
selected projection. These checks do not certify the full Responses API.

No real operating system, browser, driver or provider computer session was run.
GA nonempty safety acknowledgements, screenshot image contents, actual driver
idempotency and crash recovery remain unverified. No paid requests or package
publications were made in this increment.

## Native Anthropic transport and lossless normalization

The 37 Anthropic tests include 15 new native transport fixtures and nine new
protocol/configuration regressions. They verify request/response JSON snapshots,
version and attribution headers, repeated queries, create/count/GET access,
credential rotation and redaction, malformed/error/EOF handling, request deadlines,
pre-cancellation and cancellation during credentials, headers and stalled bodies.
Actual local HTTP tests verify independent sibling calls and borrowed-client use.

The raw normalizer preserves original fields on supported content blocks, private
citations, signed thinking, message metadata and final cumulative cache and
thinking-token usage. Typed SDK configuration changes are applied to the raw
request without erasing unchanged unknown fields. Tests reject canonical-history
mutation, absent-field injection, output-schema replacement and mismatched deltas.

The independent native consumer runs text/schema, stored approval and recreated
agent continuation, private replay and UI hydration, cache options, final usage,
citations, rotation, diagnostics, cancellation, ownership and malformed frames.
Its targeted score is 8.4/10. The guide's first program matches the example,
analyzes and compiles on Dart 3.12.2 without executing a paid request.

Four AST tests verify request field dispositions and selected nested declaration
and union drift. The inventory records 19 top-level fields and 251 locally
referenced declarations from the pinned official SDK. The current upstream
comparison matched the projection. Imported types, unrelated endpoints and
complete nested runtime semantics remain outside this evidence.

[Upstream SDK PR #432](https://github.com/davidmigloz/ai_clients_dart/pull/432)
fixes stalled-request cancellation separately. All 1,796 Anthropic SDK unit tests
passed locally with three environment-dependent skips, and package analysis was
clean. These used the locally available workspace package configuration; a clean
repository bootstrap and live tests were not run. The PR is submitted, not merged
or released, and AgentWeave's native client does not depend on it.

No live Anthropic requests or cache hits were tested, and no paid requests or
package publications were made. Hosted/browser tools, pause-turn and complete
endpoint/nested-option parity remain unfinished. Selected computer and native
file-ID integration are verified in the increment below. Provider error details retain private content after credential
scrubbing and must not be exposed directly to UI or logs.

## Anthropic computer toolset and scoped files

Six core tests cover sequential native result policies, stopping mixed-turn
executors after failure, resetting policy for the next model turn, forced and
configured whole-turn approvals, and binding the result policy across resumes.
Six typed-helper tests cover all 17 input field sets, named coordinate records,
scroll enums, direct callers, configs, selected limits, safe call snapshots and
text/image/error results. Successful screenshots and zoom require an image;
cursor position requires nonempty text. Decoded image contents remain unchecked.
Protocol regressions also verify block-index order and native file-ID documents,
including a clear failure for unsupported typed SDK configuration.

The independent consumer passes 13 loopback modes, including all actions,
approval and recreation, mixed failure stopping, disabled/unknown actions,
malformed calls, truncation, cancellation and hydration privacy. Its targeted
score is recorded in [the review](dx-review.md). The complete guide matches its
example and was checked without invoking a live provider or driver. The new
pinned official JavaScript client case resolves all three mixed-turn approvals,
rejects editable native arguments, verifies ordered results and no later effects
after the computer error, and hides private provider/environment state.

A real PostgreSQL test uses the native client's loopback HTTP transport. It
persists both approvals, rejects a changed environment, recreates the agent and
store, executes the first action once, skips the second after error, verifies
full private replay and matching result IDs/toolset names on the next HTTP
request, excludes private state from UI hydration and rejects duplicate resume.
This is recreated-instance persistence, not a computer-specific process-crash test.

Two AST mutation tests and an executable Dart fixture compare 68 selected
computer/caller/result/image declarations, actual helper/config serialization,
all input fields and requiredness, scroll values and result payloads with the
pinned official SDK. The current upstream projection matched. Documentation-only
overrides, including direct callers, are explicit. PostgreSQL suites run one file
at a time to bound test database disk use; contention tests still issue concurrent
requests. A first parallel local run exhausted disk and was discarded before the
clean rerun.

No real desktop effects, image capture, live model support or provider permissions
were verified, and no paid requests or package publication occurred. Browser and
other native toolsets remain unfinished. SDK PR #431 is still needed for its
published typed decoder to represent file-ID sources; native normalization does
not require that unreleased change.

## Ollama and Dart Frog increment

Thirty-three Ollama tests cover native JSON and NDJSON, rotating optional
credentials, queries, immutable snapshots, errors and completion/EOF, independent
cancellation, stalled requests and borrowed clients. Agent fixtures check typed
options, runtime-owned request guards, schema output, thinking/native ID/index
replay, private raw frames, truncated/conflicting tool calls, inline images and
immutable embedding vectors with validated metadata. A root guard rejects foreign
native tools and history before sending. No Ollama daemon or model was available,
and no model was downloaded.

Six shared HTTP tests add fragmented UTF-8 and CRLF NDJSON, valid final lines,
malformed/non-object data, cancellation and deadlines across preparation, headers
and body, sibling isolation, pause/resume and borrowed-client reuse.

Two Dart Frog test groups exercise actual HTTP chat, approval/resume, owner-scoped
history and replay, authentication-bound context in typed generation and invalid
requests. Independent consumers additionally test disconnect cancellation. The
pinned official JavaScript client passes four scenarios through the real handler
and native Ollama client against a local fixture. These do not prove proxy
behavior, production authentication or durable restart for this adapter.

The Ollama source inventory covers four selected operations, nested OpenAPI
schemas and reviewed Go-only additions. Three extractor tests and the explicit
upstream byte comparison pass. First guide programs match their runnable examples
and analyze on Dart 3.12.2. The Ollama program also compiles without execution;
the offline Dart Frog server ran and returned a completed SSE response.

The independent scores are 8.0/10 for Dart Frog and 7.8/10 for the exercised
Ollama path. A separate selective provider review remains 6/10 and reproduced
a Cloudflare bug: request cache overrides wrongly discarded an inherited Gateway
ID during validation. The fix and consumer regression preserve default/override
precedence and response request/cache metadata. These judgments are scoped, not
an SDK-wide acceptance pass. No paid requests or package publications were made.

## Anthropic hosted tools and provider continuations

Ten hosted-tool test groups verify typed SDK snapshots and native extension
fields, all six pinned hosted result families, fragmented server input, preserved
containers and tools, duplicate/mismatched IDs, local-name collisions, caller-version aliases, missing containers, complete
client-result batches and explicitly opted-in programmatic callers. Hosted calls
never emit local executor events. A public-boundary contract script accepts all
15 official server-tool type spellings from the existing pinned inventory and
rejects known client tools. This is not exhaustive nested option validation.

Six core tests cover counted provider continuations, usage, checkpoints, step
limits, new-user rejection and explicit recovery, final schema validation,
structured message serialization/hydration, legacy data and contradictory
local-tool continuation. The PostgreSQL fixture reloads a paused native
Anthropic code-execution turn through a recreated agent/store, preserves the
container and tools, isolates owners, resumes with no new user message and
hydrates the final structured answer. This is not a process-crash test.

Two new official JavaScript scenarios exercise text and structured pauses. The
stricter structured fixture exposed an errored intermediate placeholder despite
a successful final answer. The runtime now sends a sanitized message snapshot
for intermediate structured progress and persists completed structured data.
Both the JavaScript client and a separately written Dart ChatClient consumer
verify two runs and restored hydration without spurious structured errors.

The independent Anthropic consumer passes eight loopback scenarios, including
typed SDK hosted configuration, opaque search/citation replay, delta containers,
programmatic app-tool approval, ordinary mixed approval with recreated agents,
step-limit recovery and no extra dispatch on malformed/EOF/cancellation. Its
scoped score is 8/10. The guide's complete first Dart program matches its
executable example and was analyzed and compiled without paid execution.

No live search, fetch, code execution, tool search, container, files or billing
was exercised. Browser/MCP tools, public citation rendering and full nested
semantics remain unfinished. No paid calls or package publications were made.

## OpenAI hosted tools and provider guards increment

Selected hosted Responses tool definitions preserve native and unknown options
before SDK decoding. Completed image results retain text-image-text ordering in
Dart results, both clients and recreated PostgreSQL history. Private replay and
metadata stay out of public history. Fixtures verify no application tool runs
before a complete, consistent terminal response, including EOF, incomplete,
mismatched and cancelled streams.

The native Dart consumer passes 12 loopback cases and scores the selected path
8.2/10. Its separate SSE/hydration case and the real PostgreSQL recreation test
pass. The first PostgreSQL fixture incorrectly selected a text-only follow-up
model; declaring its image capability corrected that fixture. The Gateway and Cloudflare
consumers previously emitted a done function call missing from its terminal
output; correcting those inconsistent fixtures restores their tool flows.

Twenty independent regressions exercise runtime-owned tool/schema guards through
actual OpenRouter, Vercel Gateway and Cloudflare wrappers, plus OpenAI, Anthropic
and Ollama. They include adjacent integers above 2^53 and rounded doubles.
Native guards now use exact JSON equality; protocol hashing keeps its deliberate
JavaScript numeric semantics. The selected hosted declaration check matches the
pinned official Node source and current upstream projection at review time.

The related `openai_dart` image-option correction is submitted as
[upstream PR #436](https://github.com/davidmigloz/ai_clients_dart/pull/436).
Its isolated Dart 3.13.3 unit suite passed 25,239 tests with 3 environment skips;
strict library/new-test analysis passed. It used an explicitly remapped existing
workspace dependency configuration, not a fresh full-monorepo bootstrap. The
AgentWeave SDK pin remains 11.0.1; native JSON avoids the incorrect image types.

A final byte-level check caught and replaced the original corrupt 1x1 PNG
fixture. The new offline check verifies complete PNG chunks, CRCs, dimensions
and decompressed pixel data across the provider, client and storage fixtures.
This verifies the fixture bytes, not device rendering.

No paid calls were made for this increment. Live hosted tools, search quality,
containers, complete native provider semantics and device image rendering remain
unverified. Public citations, hosted progress and partial images are not
normalized. Packages remain unpublished.

## OpenRouter images and Cloudflare streaming increment

With Dart 3.12.2, the full local check passes 437 unit/regression tests, 18 real
PostgreSQL/Serverpod tests, the official JavaScript client scenarios, all native
Dart consumers and provider contract checks. Three documentation checks and a
strict site build pass. Image fixture integrity checks now include the new
OpenRouter consumer and PostgreSQL fixture.

OpenRouter Chat image output uses its pinned completed assistant-message schema,
with a buffered request. Tests cover remote/data URLs, ordered content arrays,
multiple images, opaque replay, supplied-schema/tool guards, filtered/error
finishes, invalid output, redacted JSON error envelopes with request IDs and
cancellation while waiting for headers. A real PostgreSQL test recreates the
agent at approval, verifies no early tool effect, and replays the original image
array alongside the selected function call/result. Public history omits private
signatures. Streamed Chat image deltas are rejected; the separate Image API is
not implemented by this adapter.

Cloudflare native text tests verify incremental response chunks before upstream
completion, `[DONE]`, cancellation and a surviving sibling, Gateway headers,
option snapshots, schema/tool buffered fallback, explicit opt-out, malformed
streams and premature EOF. Repeated complete usage frames are treated as
cumulative snapshots and emitted once at completion; this behavior is bounded
and has not been live-verified across model variants.

An independent developer wrote and ran both loopback programs and scores each
selected path 8/10. The OpenRouter guide byte-matches its example, which analyzes
and compiles without execution. `result.images` includes images produced during
current-run tool steps and excludes prior runs. No paid calls were made; live
provider/model acceptance, billing and device rendering remain unverified.

## Exact approval contracts and checkpoint recovery

With Dart 3.12.2, the full local check passes 445 unit/regression tests and 20
real PostgreSQL/Serverpod tests, plus the official JavaScript client scenarios,
provider contract checks and native Dart consumers.

Private pending approvals now bind exact versioned snapshots of the declared
tool configuration. Regressions cover adjacent large-integer input/output
schemas and native definitions, execution-kind and policy changes, equivalent
numeric values and key ordering, all-before-effects batch validation, owner
isolation, public-state privacy and original-contract retry. Real PostgreSQL
checks preserve the exact integers through agent recreation and reject changed
input/output schemas before model or executor invocation. The initial database
test expected a raw exception; correcting it to the public `AgentRunException`
contract made the intended assertions pass.

Legacy, malformed and unsupported pending contracts fail closed while retaining
the original history. Older pending approvals require a new conversation; they
are not reconstructed from current tools or lossy client hashes. Public protocol
hashes retain JavaScript number semantics. This does not remove JavaScript's
numeric limits or bind application closures and live permissions.

A separately reproduced malformed native-continuation checkpoint previously
stranded the thread reservation. The regression now verifies sanitized decode
failure, unchanged stored state, an unused model and a successfully reacquired
reservation. Future-based run errors expose the same safe recovery message as
streamed errors while retaining private diagnostic causes.

The independent developer reran the approval consumer and checkpoint regression
and scores this scoped path 9/10. No paid calls were made. This is not evidence
of complete native provider coverage or arbitrary-crash recovery.

## Typed Anthropic citations increment

The complete Dart 3.12.2 check passes 460 unit/regression tests and 21 real
PostgreSQL/Serverpod tests, all consumers, provider contracts and both client
suites. Three documentation tests and the strict site build also pass.

Core fixtures validate typed source references, JSON round trips, immutable
message annotations, UTF-16 ranges, malformed input, continuation, memory
approval recreation, retained partial text and cancellation. A split-surrogate
regression rejects an unstable citation boundary before its public event.
Provider fixtures cover all five pinned citation types, initial and streamed
citation lists, complete-block answer spans, source coordinates, guarded document
configuration, SDK streaming, structured-output incompatibility and malformed or
unfinished responses before tool execution.

A real PostgreSQL test recreates an approved-tool agent, verifies saved citations
and event logs, isolates owners and restores native replay. Raw response
citations retain private fields; continuation inputs omit response-only file IDs.
The official JavaScript client and the Dart client preserve citation metadata in
live snapshots and restored history. The first emoji transport fixture used
Latin-1 output; setting its explicit UTF-8 charset corrected the fixture.
Serverpod already encodes its event bytes as UTF-8.

The independent developer consumer runs all five source kinds through loopback
HTTP, then recreates an approval and checks native replay and privacy. Its scoped
score is 8/10. The guide sample byte-matches the runnable example, analyzes and
compiles without execution. No live provider or paid calls were made. Citation
quality, custom-content document inputs, other providers' citation adapters and
Flutter rendering remain open. URL validation does not establish a general
public-data policy.


The first full citation check rejected an older native consumer's incomplete
citation fixture. It omitted required source fields and treated a document title
as private metadata. The corrected fixture supplies a citable document and all
required fields, and uses an unknown native field for its private-marker check.
Public titles remain public, while unknown fields remain private.

Citation events include a stable per-message `citationIndex`. The official
JavaScript fixture reads the actual stored log through the adapter's GET
`joinRun` path and feeds it through the official client processor. Upserting by
message and index retains two identical citations after replay without creating
four. This is completed-log replay evidence, not automatic reconnection during
a live provider call.

## Upstream SDK citation file IDs

The isolated upstream correction in
[PR #441](https://github.com/davidmigloz/ai_clients_dart/pull/441) retains nullable
file IDs in the three document citation response DTOs and leaves request types
unchanged. Dart 3.13.3 checks passed 1,851 package unit tests with three
environment-key skips and strict analysis. An independent actual SDK loopback
consumer covers stored-message reload, cache equality, clear/copy, streaming and
`toInputMessage()` request projection; its scoped score is 9/10.
The sparse checkout used a cached remapped package configuration, not a fresh
monorepo bootstrap. This contribution does not update AgentWeave's SDK pin or
publish a package.

## Native OpenAI output references

The full Dart 3.12.2 check passes 484 unit/regression tests and 22 real
PostgreSQL/Serverpod tests, both clients, all consumers and contract checks. Three
documentation tests and a strict site build pass.

Core fixtures exercise native range, insertion and file-list position types,
empty enclosing parts, JSON snapshots, immutable collections, invalid spans,
provider mismatches, partial failure and cancellation. The existing citation
suite continues to pass. OpenAI fixtures cover all four Responses annotations,
initial and streamed echoes, null placeholders, exact text reconciliation,
unknown/conflicting data, EOF and cancellation before tool effects. Buffered
Chat fixtures cover native nested URL annotations, typed options/schema guards,
private audit data, cancellation isolation and malformed output. Native Chat
streaming rejects unknown/inconsistent finishes and late choices before tools.

Independent native SDK loopback consumers score the selected Responses and
buffered Chat flows 8/10 each. A PostgreSQL test recreates an approval and verifies
all four typed reference forms, event order, private replay, owner isolation and
intentional public scoped file IDs. Its initial assertion incorrectly expected
only an assistant in `responseMessages`; filtering out the tool result corrected
that fixture. Both clients retain references alongside citations through snapshots,
history restoration and completed-log replay; replay upserts retain legitimate
duplicates. Guide examples byte-match their runnable sources and compile without
running the billable demos.

No paid calls were made. Native Unicode offset interpretation, live model
acceptance, actual authenticated file download, production rendering and other
providers' reference normalization remain unverified. These checks preserve
reported positions; they do not establish precise inline highlighting.

## Schema diagnostics and offline onboarding

Dart 3.12.2 passes 491 unit/regression tests and 22 real PostgreSQL/Serverpod
integration tests through `tool/check.dart`, including both client suites and
all pre-existing provider inventories and consumers. The two newly tracked
independent consumer applications also execute and pass fatal-infos analysis.
The check now includes those consumers and four offline sample invocations.
Three documentation tests and a strict site build pass. Core Dartdoc reports
zero warnings and errors.

New regressions cover validator instance/schema paths and immutable issue
snapshots; structured output, tool input and tool output errors; sanitized
Future/stream errors and hydration; nested edited-approval diagnostics, batch
validation before effects and retry; and directly validated local references.
The public approval schema and hashes are unchanged. The pinned validator's
embedded local-reference limitat

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.