Serves the Anthropic Messages API over FlexHarness models, so an Anthropic client such as Claude Code can
run on another provider's model.

Part of the [FlexHarness toolbox](https://code.foss.global/modelprofile.com/flexharness).
Install the components your project uses. Provider adapters are registered explicitly;
the agent and harness do not install or register vendor SDKs.

```sh
pnpm add @modelprofile.com/flexharness-providers
```

See the [toolbox usage and migration guide](https://code.foss.global/modelprofile.com/flexharness#readme)
for composition examples and the SmartAI/SmartAgent migration map.

## Serving a model

`createAnthropicMessagesService()` answers WHATWG `Request`s with `Response`s, so any HTTP server can host
it; `/anthropic-messages/node` hosts it on a Node HTTP server. It serves `POST /v1/messages`, streamed as the
Anthropic event sequence or whole, and `GET /v1/models`. `POST /v1/messages/count_tokens` answers 404, on
which an Anthropic client estimates token counts itself, and `HEAD /api/hello`, a client's connection
warm-up, answers 200 without a credential.

```typescript
import {
  AnthropicMessagesError,
  createAnthropicMessagesService,
  createOpenAiResponsesMessagesDialect,
} from '@modelprofile.com/flexharness-providers/anthropic-messages';
import {
  createOpenAiChatGptResolvingModelConnection,
  createOpenAiModelProvider,
} from '@modelprofile.com/flexharness-providers/openai';

const service = createAnthropicMessagesService({
  authenticate: async (request) => {
    if (request.headers.get('authorization') !== `Bearer ${sessionToken}`) {
      throw new AnthropicMessagesError(401, 'authentication_error', 'The session token is not valid.');
    }
    return session;
  },
  resolveModel: async (modelId, session) => {
    const entry = session.catalog.find((model) => model.modelId === modelId);
    if (!entry) return undefined;
    const connection = createOpenAiChatGptResolvingModelConnection({ expectedIdentity, resolveAccess });
    return {
      model: createOpenAiModelProvider().getModel({ provider: 'openai', model: modelId, connection }),
      ...createOpenAiResponsesMessagesDialect({ reasoning: entry.reasoningEfforts.length > 0 }),
      reasoningEfforts: entry.reasoningEfforts.map((effort) => effort.effort),
      signatureScope: `openai:${expectedIdentity.accountId}`,
      sendsMaxTokens: false,
      toolNameLimit: 64,
    };
  },
  listModels: async (session) => session.catalog.map((model) => ({ id: model.modelId, displayName: model.displayName })),
  signatureKey, // 32 or more random bytes from the host's secret store
  usage: {
    record: async (event) => ledger.add(event),
    failed: (error, event) => log.error('usage bookkeeping failed', { error, modelId: event.modelId }),
  },
});
```

`usage.record` runs after an answer is complete and outside its path, so bookkeeping never changes an
answer. A `record` that throws or rejects is handed to `usage.failed` with its event; the host handles it
there, and a `failed` that throws itself is an unhandled rejection of the host.

The answer's own `usage` (`IAnthropicMessagesUsage`) is in Anthropic's shape: `input_tokens` leaves out the
tokens read from or written to the cache, which `cache_read_input_tokens` and `cache_creation_input_tokens`
count. A cache count the model did not state is `null`, as Anthropic's own usage may give it, never 0: an
OpenAI Responses answer that states `cached_tokens` but no `cache_write_tokens` (as the ChatGPT backend's do)
has `cache_creation_input_tokens: null`, and its `input_tokens` then holds whatever it wrote. `message_start`
is sent before the model states anything, so its cache counts are `null`; `message_delta` carries the
answer's usage.

## What is translated

System prompts, text, images, PDF and text documents, tool definitions, tool calls, tool results with text
and images, tool choice (including `disable_parallel_tool_use`), mid-conversation system messages,
thinking, `output_config.effort` and a JSON schema output format.

Thinking comes back with a signature that carries the reasoning metadata of the model's own reasoning part
(for OpenAI, the reasoning item and its encrypted content). A client returns thinking blocks unchanged, so
the reasoning reaches the model again on the next turn. The client holds the signature, so it is
authenticated with an HMAC-SHA256 under `signatureKey`, which the host provides: at least 32 random bytes,
kept secret and used for nothing else. A shorter key is refused when the service is created. A signature the
key did not write or that was changed, one written under another `signatureScope`, such as another account,
and a redacted thinking block are not sent back; the response counts them in
`x-flexharness-thinking-dropped`. A host that keeps its key across restarts keeps the reasoning of the
conversations it answered; a new key drops the thinking signed under the old one.

Response headers name what a request received differently from what it asked for:

| Header | Meaning |
| --- | --- |
| `x-flexharness-effort-fitted` | The requested effort the model lacks and the one sent instead, as `max=>xhigh` |
| `x-flexharness-max-tokens` | `not-sent` when the model takes no output limit (`sendsMaxTokens: false`) |
| `x-flexharness-thinking-dropped` | The number of thinking blocks not sent back to the model |
| `x-flexharness-model-warnings` | The model's own warnings, such as an unsupported sampling setting |

## What is refused

A field that cannot be translated faithfully is refused with a 400 that names it: server-side context
management, code execution containers, remote MCP servers, deferred tool loading and server tools. The
server tool refusal names the tool type after `Input tag`, the wording on which an Anthropic client continues
without that tool. Prompt cache markers, citations, metadata and the service tier are hints to Anthropic's own
service and are accepted without effect; the provider caches prompts by the session id instead.

Failures answer in the Anthropic error shape. A usage or rate limit (`ModelLimitError`) is a 429 with
`retry-after` in seconds until the reset. An input beyond the model's context window is the
`prompt is too long` refusal an Anthropic client compacts its conversation on. A provider that refuses the
account's credentials is a 403. A failure after a stream began is an `error` event, and a stream that stays
silent sends `ping` events.

## Issue Reporting and Security

Report issues and security concerns through [community.foss.global](https://community.foss.global).

## License and Legal Information

This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the repository license file.

**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

### Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.

Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.

### Company Information

Task Venture Capital GmbH<br>
Registered at District Court Bremen HRB 35230 HB, Germany

For any legal inquiries or further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
