Explicit openai model provider for FlexHarness models and the AI SDK.

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.

`createOpenAiModelProvider()` calls the Responses API at `https://api.openai.com/v1` by
default. `baseUrl` points it at another endpoint, for example `https://eu.api.openai.com/v1`
for OpenAI's European data residency. `api: 'chat'` calls `/chat/completions` instead of
`/responses`: most OpenAI-compatible servers implement only Chat Completions, so use it with
their base URL and key.

`api` applies to a supplied `connection` too; a connection that declares the APIs it serves refuses any other.
The ChatGPT connections serve the Responses API only (the Codex backend has no Chat Completions
endpoint), so asking one of them for `api: 'chat'` is refused when the model is constructed.

Provider options differ per API. `IOpenAiProviderOptions` types the Responses options;
`IOpenAiChatProviderOptions` types the Chat Completions options. Responses-only options such as
`reasoningSummary`, `previousResponseId`, `include`, `instructions` and `truncation` do not apply
to `chat`: the chat model ignores them.

On `chat`, OpenAI's fields of response storage and the prompt cache (`store`, `prompt_cache_key`,
`prompt_cache_retention` and `prompt_cache_options`) go only to OpenAI's own API: `api.openai.com`
and its data residency hosts such as `eu.api.openai.com`. FlexHarness sends every OpenAI call with
`store: false` and a derived `prompt_cache_key`, and an OpenAI-compatible server may refuse a field
it does not know, so a call to another server leaves them out, whoever set them. A server that takes
them gets them with `openAiFields: true`. The Responses API sends them to any base URL.

```typescript
import { ModelRegistry } from '@modelprofile.com/flexharness-models';
import { createOpenAiModelProvider } from '@modelprofile.com/flexharness-providers/openai';

const models = new ModelRegistry().register(createOpenAiModelProvider());
const model = models.getModel({
  provider: 'openai',
  model: 'served-model-name',
  apiKey,
  baseUrl: 'https://models.example.com/v1',
  api: 'chat',
});
```

A spent API balance (`insufficient_quota`) fails as a `ModelLimitError` of kind `usage_limit`,
and any other 429 as kind `rate_limit` with the `retry-after` delay; see the toolbox readme's
usage and rate limits section. A `connection` can add its own limit dialect with
`classifyLimit`, which is consulted first. A limit a stream reports, in a `response.failed` or an
`error` event, before or after the answer began, is classified the same way. `classifyOpenAiLimit`
and `readOpenAiError` are exported for connections that extend the OpenAI dialect.

## ChatGPT with access from an account authority

This subpath runs inference and reads the model catalog of a ChatGPT account with access alone:
an access token plus the workspace (`accountId`) and residency (`isFedrampAccount`) its issuer
states. It never signs in, never refreshes and never reads identity out of the token; the
account authority that resolved the access owns all of that. The shape is the answer of the
authswitch authority's `resolveAccess`.

`createOpenAiChatGptResolvingModelConnection()` resolves access immediately before every provider
HTTP request, so a multi-step tool run never holds the token that admitted it. The connection is
pinned to `expectedIdentity`: an access that states another workspace or residency, an empty
token, an endpoint outside the Codex backend, a redirect or an abort stops the request before the
transport is called.

When the resolved access carries the authority's `generation` and the provider answers 401, the
connection resolves once more with `rejectedGeneration` set to that generation, so the authority
renews exactly the token that was rejected, and sends the request again with the same body. A
second 401, or a 401 for access without a `generation`, fails with an `OpenAiChatGptAuthError`
whose `status` is 401.

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

const connection = createOpenAiChatGptResolvingModelConnection({
  expectedIdentity: { accountId, isFedrampAccount },
  resolveAccess: async ({ signal, rejectedGeneration }) => {
    const access = await authority.resolveAccess(
      { bindingId, capability, minValidityMs: 60_000, rejectedGrantGeneration: rejectedGeneration },
      signal,
    );
    return { ...access, generation: access.grantGeneration };
  },
});
const model = createOpenAiModelProvider().getModel({ provider: 'openai', model: 'gpt-5.5', connection });
```

`createOpenAiChatGptAccessModelConnection(access)` sends one fixed access with the same headers and
checks; its 401 fails the same way.

`listOpenAiChatGptModels(access, { signal })` reads the account's Codex model catalog, hidden models
included, in the catalog's priority order, with the first listed model marked `isDefault`. A
rejected token fails with an `OpenAiChatGptAuthError` whose `status` is 401, so a caller resolves
again with `rejectedGeneration` and repeats the read; an abort rejects with the signal's reason;
anything else is an `OpenAiChatGptModelListError` whose `code` is `NETWORK_FAILED`, `HTTP_ERROR`
(with `status`) or `PROTOCOL_ERROR`. A model whose catalog entry states its context window carries it as
`contextWindow`, in tokens: the served `context_window`, never `max_context_window`. One whose entry states
an automatic compaction point carries it as `autoCompactTokenLimit` (`auto_compact_token_limit`). `reasoningEfforts` lists the efforts a request can send; the Codex client
modes `ultra` and `persistent`, which Codex resolves before it sends a request, are left out, and a
default that names one is stated as the effort Codex sends for it.

The catalog is requested for one OpenAI Codex release, `OPENAI_CHATGPT_CATALOG_CLIENT_VERSION`
(`0.170.0`), sent as `client_version` and `version`; the backend shapes the catalog by it, so a stale
value withholds newer models. The constant names the release whose catalog contract this package
implements, the same one the catalog entry of `third-party-notices.md` names, and a test holds the two
together. To follow a newer Codex release, check the catalog fields `smartai.chatgpt.catalog.ts` reads
against that release's `codex-rs/protocol/src/openai_models.rs`, then move the constant and the notice
together. A gateway that serves a Codex client passes that client's release as `clientVersion` (for example
`0.160.0`), so it routes by the catalog the client was offered; the entries are still read by this package's
contract, and a value that is not a release version is refused with a `TypeError`.

Both ChatGPT connections classify Codex limits with `classifyOpenAiChatGptLimit` and move the system
messages a prompt opens with into the Responses `instructions` with
`createOpenAiChatGptInstructionsMiddleware()`; a system message later in the conversation stays in its
place as a `developer` input item. The same middleware sends every call with `store: false`: the backend
never stores a response, so a stored call's references to earlier assistant items could not resolve. Both
are exported here for connections of their own.

The `/auth` subpath keeps its connections, which derive identity from the token itself, and
re-exports the ChatGPT limit classifier, the instructions middleware, the Codex base URL, the
default originator and `OpenAiChatGptAuthError` from here.

## OpenAI API key

`createOpenAiApiKeyConnection({ apiKey, fetch? })` is an OpenAI API connection on an API key, for a gateway
that holds the key and forwards requests for its clients. It sends the request to
`https://api.openai.com/v1/*` only (`OPENAI_API_BASE_URL`; `isOpenAiApiRequestUrl` is the check), with
`redirect: 'error'`, `Authorization: Bearer <key>` replacing any credential the request carried, and without
`originator`, `ChatGPT-Account-ID`, `X-OpenAI-Fedramp`, `OpenAI-Organization` and `OpenAI-Project`: the key
bills to the organization and project it was issued for, and a client cannot move the request to another one
the key reaches. Every other header and the body travel unchanged. A 401 (key rejected) or 403 (key without the
permission the request needs, such as a restricted key) fails with `OpenAiApiKeyAuthError` whose `status` names
it; every other status is the caller's. Use it as `connection` of
`createOpenAiModelProvider().getModel(...)`, on either API, or through `connection.settings.fetch`.
`createOpenAiApiKeyHeaders` applies the same header rules. Without a custom `fetch` the connection keeps the
prompt-cache timing of the API endpoint (see below).

`listOpenAiApiKeyModels(access, { signal, fetch })` reads `GET /v1/models`, one unpaged list of at most 1 MiB
and 1000 models, as `{ providerId, modelId, created, ownedBy, shutdownDate? }`, the API's own data. A rejected
key fails with `OpenAiApiKeyAuthError` (`status` 401), a key without model read likewise with `status` 403; an abort rejects with the signal's reason; other failures
are `OpenAiApiModelListError` with `NETWORK_FAILED`, `HTTP_ERROR` (and `status`) or `PROTOCOL_ERROR`.

`OPENAI_API_MODELS` describes the public-API models (GPT-6 Astra, GPT-6.1 Sol, GPT-6 Sol, GPT-6 Luna, GPT-5.6
Sol, Terra and Luna, GPT-5.5, GPT-5.4) as their model pages state them, checked 2026-10-21, in the vocabulary of
`IOpenAiChatGptModel`: `reasoningEfforts` (`TOpenAiReasoningEffort`, `max` included), `defaultReasoningEffort`
where the page states it (GPT-6 Astra's does not), `inputModalities`, `serviceTiers` beyond Standard (`flex`,
`priority` for Fast mode, `ultrafast` on GPT-6 Astra and GPT-6.1 Sol), `contextWindow`, `maxInputTokens` where
stated, `maxOutputTokens`, dated `snapshots` and `source`. `getOpenAiApiModel(id)` matches the id or a listed
snapshot exactly.

### Prices and usage

`OPENAI_MODEL_PRICES` holds the prices of those models from https://developers.openai.com/api/docs/pricing,
checked 2026-10-21, as `IModelPrice` of `@modelprofile.com/flexharness-models`, keyed by the response's
`service_tier`: `default`, `flex`, `priority` (also under `fast`), and `ultrafast` where the page prices it. Each
tier has a short-context band (prompts of at most 272,000 input tokens) and a long one; Fast mode on GPT-5.5 and
GPT-5.4 has no long-context price, so such a call is refused. Cache writes are priced by lifetime (`30m`,
`12h`); GPT-5.5 and GPT-5.4 charge a write as ordinary input. Web search costs $10 and file search $2.50 per
1,000 calls. `getOpenAiModelPrice(id)` matches the id or a listed snapshot exactly; any other id is `undefined`.
A request sent with `service_tier: "default"` is served at Standard prices
(https://developers.openai.com/api/reference/resources/responses/methods/create); without it, a project set to
Fast serves the request at Fast prices.

`readOpenAiResponsesUsage(usage, serviceTier)` reads a Responses `usage` raw with the response's
`service_tier`: `input_tokens` includes cache reads and writes; `input_tokens_details.cache_write_tokens_details`
splits the writes into `30m` and `12h`, and writes it does not split are `unknownLifetimeCacheWriteTokens`.
The usage names no tool calls: count the response's `web_search_call` and `file_search_call` items into
`toolCalls`. A usage without a service tier, or with a malformed or inconsistent count, throws
`ModelUsageReadError`.

## Prompt cache timing

Each model call reports the cache settings of the request it sent to an observer
of `@modelprofile.com/flexharness-models` (`bindSmartAiCachePolicyObserver`): the
endpoint (`api` for `https://api.openai.com/v1`, `chatgpt` for the ChatGPT Codex
backend), the `model`, and `prompt_cache_retention` and
`prompt_cache_options.ttl` when sent. `observeSmartAiCacheDispatch` turns that
into the documented idle budget: 30 minutes for GPT-5.6 and later on the API, 30
minutes for `24h` retention on earlier models, and 5 minutes for in-memory
retention, for no retention and for every ChatGPT request, since that backend
takes no retention and documents none. API requests count only without a custom
`fetch`, which may change the body, or through `createOpenAiApiKeyConnection`
on the global transport; other endpoints report nothing. The
response's `input_tokens_details.cached_tokens` arrives as the usage's
`cacheReadTokens`.

## Text files

OpenAI reads only images and PDFs as files, so the provider sends every other text file of a user
message as text, on both APIs and every connection, through `createTextFilePartMiddleware()` from
`flexharness-models`. A file part whose media type names text (`text/*`, JSON, XML, YAML, CSV,
script types, `+json`, `+xml` and `+yaml` types, or any type with a `charset`, such as the
`application/x-openscad; charset=utf-8` the `/chat/harness` intents send for a text attachment)
becomes one `input_text` (Chat Completions: `text`) part:

````text
Attached file part.scad (application/x-openscad; charset=utf-8):
```
cube([10, 10, 10]);
```
````

Images and PDFs are sent as before. A file that names text but is not valid text in its charset
fails before the request is sent.

## Web search

`createOpenAiWebSearchTool(options?)` returns OpenAI's web search as a provider-executed tool: the model
searches and reads results on OpenAI's side, so the host sends no request to the web. Add it to a run's tools
under the name `web_search`, next to the host's own tools. It is a Responses API tool, so it works with the
default `api: 'responses'` and with both ChatGPT connections, whose Codex backend serves it.

```typescript
import { runAgent } from '@modelprofile.com/flexharness-agent';
import { createOpenAiWebSearchTool } from '@modelprofile.com/flexharness-providers/openai';

const result = await runAgent({
  ...setup,
  prompt: 'What is the head diameter of an M3 socket head cap screw?',
  maxSteps: 4,
  tools: { web_search: createOpenAiWebSearchTool({ externalWebAccess: true }) },
});
```

| Option | Sent as | Meaning |
| --- | --- | --- |
| `externalWebAccess` | `external_web_access` | `true` reads live pages; `false` answers from OpenAI's cached index, the mode Codex uses by default. Unset leaves it to the backend. |
| `filters.allowedDomains`, `filters.blockedDomains` | `filters.allowed_domains`, `filters.blocked_domains` | Domains the search may, or must not, use. |
| `searchContextSize` | `search_context_size` | `low`, `medium` or `high`: how much of what it found reaches the model. |
| `userLocation` | `user_location` | An approximate location results should be local to. |

A search arrives in the run as a tool call the provider executed, so the agent records it and never runs it
locally; `onToolCallStart` and `onToolCallFinish` report it with `providerExecuted: true`, and a managed
FlexHarness session records it as a completed `web_search` tool part before the answer it informed. Runs on OpenAI send `store: false`, so a later step of the same run replays the conversation without
references to the search item, which an unstored response could not resolve. Treat search results as
untrusted input.

## 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.

### Serialized Responses requests

`normalizeOpenAiChatGptResponsesRequest(body)` applies the ChatGPT instruction
dialect to JSON received by an HTTP gateway. Call it before sending that JSON to
`connection.settings.fetch`. It leaves explicit `instructions` unchanged, even an
empty string or null. When instructions are absent, leading system/developer
messages become the top-level instruction prefix. Text parts in one message are
joined without an added separator; messages are joined with a newline. Non-text
instruction prefixes are rejected. Later system messages become developer
messages in their original positions. `prompt_cache_retention` is removed, and
so is `max_output_tokens`: the Codex backend takes no output limit.

The function returns a new body and never changes the input. Model, storage,
streaming, tool, reasoning, and other request fields retain their values. It does
not supply authentication, choose an account, enable persistence, or change the
requested response format. API-key OpenAI traffic should use its own dialect.
