* Move the AI drivers into drivers/ai
The seven drivers/ai-* folders and the AI-only helpers in drivers/util
become one tree:
drivers/ai/interfaces/<interface>/ the Puter-facing drivers
drivers/ai/providers/<vendor>/<interface>/ vendor adapters, catalogs, tests
drivers/ai/protocols/openaiCompatible/ the shared OpenAI wire protocol
drivers/ai/shared/ helpers several interfaces use
Files are moved and their relative imports rewritten; no implementation
changes. Driver names, aliases, interfaces, config keys, model ids and
usage keys are unchanged.
The chat catalog registration test scanned providers/*/ next to itself.
It now scans providers/*/chat/ and fails if the scan finds no catalog, so
a wrong directory can't pass it.
General helpers that non-AI code also uses stay in drivers/util: file
input, data URIs, upstream errors, stream piping, CRUD limits.
* Document the AI driver layout
doc/ai-drivers.md explains what interfaces, providers, protocols and
shared each own, the import rules between them, where a new file goes,
and the steps for adding a provider or an AI interface. It also lists
the three places that don't follow the layout yet.
doc/architecture.md and AGENTS.md link to it.
* Move catalogPrice into ai/shared
Chat providers and the Cloudflare and xAI image catalogs all parse vendor
prices with catalogPrice, so it lives in shared/ instead of the chat
interface's pricing helpers. The image catalogs no longer import from
the chat interface.
* Move the Textract and Mistral OCR calls into provider classes
OCRDriver held both vendors' clients, request building, response
normalizing and metering. That now lives in TextractOcrProvider
(providers/awsTextract/ocr) and MistralOcrProvider (providers/mistral/ocr),
both implementing IOcrProvider. The driver keeps the provider catalog,
model resolution, auth and credit gates, and input resolution.
The page estimate, document detection and credit hold both providers use
are in interfaces/ocr/common.ts.
No behavior change: same validation order, error messages, usage keys,
holds and charges.
* Move the ElevenLabs voice changer into a provider class
VoiceChangerDriver built the ElevenLabs request, measured the converted
audio and metered it, and imported the output formats from the ElevenLabs
text-to-speech provider. That code is now in providers/elevenlabs:
outputFormats.ts formats both speech interfaces use
speechToSpeech/ElevenLabsSpeechToSpeechProvider.ts
speechToSpeech/measuredOutput.ts WAV, Opus and byte-rate timing
speechToSpeech/costs.ts
The driver keeps provider resolution, test mode and the auth check. With
one provider it holds the class directly; there is no provider interface.
No behavior change: same validation order, error messages, usage keys,
holds and charges.
* Move the AI billing helpers the realtime relay uses below the driver layer
OpenAIRealtimeRelayService is a service, and it imported the cost factor,
the provider key reader and a transcription price from drivers/ai. Those
now live in src/backend/util, which both layers can import:
util/aiCostFactor.ts withAiCostFactor, withAiCreditHold and the
request cost helpers, unchanged
util/aiProviderKey.ts readProviderKey, cut from providerRegistry.ts
util/aiPrices.ts the gpt-transcribe per-second price, read by the
OpenAI speech-to-text cost table and the relay
withStreamedAiCharge returns a DriverStreamResult, so it stays in the
driver layer as drivers/ai/shared/streamedAiCharge.ts with its tests.
MeteringService is untouched. No prices or billing behavior change.
* Remove the aiUserIdentifier alias
shared/aiUserIdentifier.ts re-exported upstreamUserIdentifier under a
second name, and only its own test imported it. The alias is gone; its
tests, which cover truncation and actor shapes the other file didn't,
replace the four cases in upstreamIdentifier.test.ts.
* Move the AI test helpers into the AI tree
drivers/integrationTestUtil.ts held helpers for AI provider tests, but a
store test and the realtime relay test imported from it too.
drivers/ai/shared/integrationTestUtil.ts the provider test helpers
testEnv.ts optionalEnv and skipUnlessEnv,
for any env-gated suite
testUtil.ts withAiCostFactorHook, next to
the server it hooks
No test under services/ or stores/ imports from the driver layer's AI
code now. The typecheck baseline entry for the moved file is renamed, not
regenerated.
* Split the tool and compaction helpers by dialect
FunctionCalling.js and compaction.js each held Puter-facing parsing next
to OpenAI and Anthropic request shapes. Each dialect now owns its mapping:
interfaces/chat/utils normalize_tools_object, readCompaction and the
other dialect-neutral checks
protocols/openaiCompatible/openaiParams.ts
toolsToWire (was make_openai_tools) and
toOpenAiContextManagement
providers/claude/chat/contextManagement.ts
toAnthropicContextManagement
toolsToWire takes the dialect as its second argument, like the other
mappers in that module, and takes an array; every caller already guarded
the empty case.
make_claude_tools is removed. Nothing but its tests called it: the Claude
provider uses claudeToolPolicy directly. The three cases only those tests
had are added to the claudeToolPolicy tests. The chat interface helpers no
longer import from providers/claude.
* Remove the unused ImageProvider base class
Every image provider implements IImageProvider directly; nothing extended
or imported the abstract class in interfaces/image/ImageProvider.ts.
The guide's import rules now say that only an interface's driver file
imports providers, which holds since the tool helpers stopped importing
the Claude policy.
* Rerun Replicate predictions an output safety checker rejects
Some community models check the generated image and fail the
prediction with "Try running it again" for a share of seeds, whatever
the prompt. adirik/realvisxl-v3.0-turbo failed 5 of 24 runs of "a small
red cube on a white table" that way.
A prediction that fails with that message is now run again, up to two
more times, inside the same deadline and credit hold. A request that
pins a seed is not rerun, because the same seed is rejected again.
Only the prediction that succeeds is metered, as before.
* Answer malformed AI requests with a 400 where they enter
A value that used to end in an unclassified error, in a request or in
an upstream answer, now gets a classified one before provider code runs
on it. A value a driver or provider ignored or refused before is
handled as it was.
Every driver:
- shared/scalarOptions.ts answers 400 for a value that cannot be
converted to text, such as { "toString": null }, in the options a
driver reads as text, a number or a flag. The chat, video, text to
speech, speech to text, voice changer and OCR drivers call it first.
- An unknown provider name that is not text gets the same 400 as any
other unknown name.
Chat requests:
- A falsy `tools` means no tools on every provider.
- A tool call id or a content block type that cannot be converted to
text is a 400.
- A tool result that is an object is sent as its JSON, like the content
of a `tool` message.
- `include` that is not an array is a 400.
- `anthropicBetas` that is not a list of names is dropped.
- Gemini's native route answers 400 when no user or assistant message
is left to send.
- The prompt estimate reads a compaction block whose content is not a
string.
Image, video, speech and OCR requests:
- The image driver checks `input_image_mime_type` with `quality` and
`resolution`.
- The video driver answers 400 for a model that is not a string.
- The voice changer answers 400 for an `output_format` that is not a
string.
- Mistral OCR answers 400 when the SDK refuses the options before
sending them, as Mistral chat does.
Upstream answers to chat:
- A choice without a message is the existing 400 bad_response, which
still falls back.
- A usage count that is not a number is reported as zero in the cost
event, as pricing already skips it.
* Fuzz the AI drivers with seeded requests and upstream answers
Two seeded suites send malformed input through the real drivers and
providers. The vendors are played at the HTTP boundary, so each
provider's request and response code runs.
- ChatCompletionDriver.fuzz.test.ts covers the 17 chat providers that
have a static catalog. Requests with a few values changed must
resolve or reject below 500 without marking a route unhealthy.
Valid requests against wrong statuses, bodies of the wrong shape and
broken event streams must end with an answer or a classified error.
A stream only has to end; the error line it carries is not checked.
- mediaDrivers.fuzz.test.ts covers the image, video, speech and OCR
drivers, called as a user with unlimited metering so a request gets
past file input and the credit hold. Every vendor refuses the
request, and every call must end with a classified error.
shared/fuzzTestUtil.ts holds the seeded random source, the hostile JSON
values, the mutation, and the stand-in for fetch, undici and axios. An
SDK that calls https.request itself fails the suite. PUTER_FUZZ_CASES
raises the case count for a longer run. doc/ai-drivers.md describes the
suites.
* Restore the CODEOWNERS default owner and wildcard patterns
The default owner line read `- @Salazareo`, which only matches a file
named `-`, so files without a specific owner had none. Three patterns
had their `*` escaped, which GitHub rejects as invalid, so their lines
assigned no owner.
---------
Co-authored-by: Daniel Salazar <daniel.salazar@puter.com>
OpenAI Realtime relay
The relay serves /puterai/openai/v1/realtime on the API host. The SDK exposes
it through puter.ai.realtime().
Beta: This API is incomplete. Its methods, options, events, and behavior may change abruptly, including breaking changes without notice.
Direct clients are documented in the Realtime WebSocket API reference.
Transport
The relay forwards native OpenAI JSON events unchanged after validating the
event envelope, except that rate_limits.updated (Puter's provider account) is
dropped and provider organization IDs are removed from diagnostic messages in
error, response.done.status_details.error, and
conversation.item.input_audio_transcription.failed.error, and from provider
close reasons. Conversation content is preserved. An event must be an object with a nonempty string type of at
most 128 characters. Binary messages and malformed envelopes close the session.
Usage fields consumed by metering are validated before use. Event field order
does not affect billing.
Clients authenticate with a Puter token through the Authorization header,
OpenAI's browser key subprotocol, or auth_token. Server clients should use the
header because URL and subprotocol logging can expose credentials.
The socket opens before authentication completes. Authentication and model failures arrive as OpenAI-shaped error events followed by a close frame.
const conversation = await puter.ai.realtime({ output: ['text'] });
conversation.on('error', (event) => console.error(event));
conversation.on('text', ({ delta }) => console.log(delta));
conversation.on('turn.done', () => conversation.close());
await conversation.connect();
conversation.sendText('Hello!');
Limits and lifecycle
All transport limits are published in rate-limits-and-quotas.md. Message size includes reassembled fragments. Client messages are capped at 64 KiB; upstream messages at 4 MiB, since OpenAI events can carry whole items. Read backpressure is supplemented by hard queue admission limits because a paused socket can still deliver messages already in its receive buffer.
Each frame is parsed once and the original bytes are forwarded. Upstream
traffic is not rate limited: OpenAI sends audio faster than real time, and
backpressure bounds what a slow client can queue. Usage is priced as each event
arrives, before any forwarding decision, and recorded serially off the
forwarding path through the AI cost-factor hook. Pricing follows the model the
session reports. A missing model uses the last known model, while an explicitly
unpriced model closes the connection; a client session.update
that changes the model is refused. So are conversation.item.retrieve and MCP
tools in session.update or response.create, since a retrieved item or MCP
output can exceed the upstream message cap.
When a session closes with a response still generating, the relay cancels it and keeps the upstream open for up to five seconds so the cancelled response reports, and is billed for, what it generated. A response the client requested that starts during that window is cancelled the same way. When the upstream closes, for any reason, with a started response that hasn't reported usage, that response is billed its full hold through the same metering path and a warning alarm is raised. A response the client requested but that never started isn't billed.
Each response holds a fixed amount of the account's budget
(RESPONSE_HOLD_*_TOKENS at the model's audio rates) from response.created
until its usage is recorded, so concurrent sessions can't overdraw it; a session
opens only if one hold fits. Input transcription is priced at the costlier of
the transcription models in force at commit and at completion. Session attempts
are limited per credential after signature verification. Local, bounded IP and
node admission limits protect signature verification and authentication lookups.
Upgrades use Express's configured proxy trust policy and the ip.validate gate.
Authentication uses touch: false on both initial connection and rechecks, so
opening or maintaining a realtime socket does not update session activity metadata.
Input transcription holds credit per item, at a fixed budget for the selected
transcription model and that model's cost factor. Audio and the configuration
that enables transcription are forwarded only while a reserved spare item
exists. Each provider commit takes one, and the pool refills to two spares in
the background, up to 64 pending plus spare items. A commit with no spare left
reserves its own item. A model change, requested or reported, releases the spares
and reserves new ones at the new model's price. Committed items keep their hold
and model. Disabling transcription keeps the spares until the connection ends.
If the account can't cover another item, client reads pause while the session
still holds items that may free credit, and the session is refused with
insufficient_funds once it holds none.
Audio the provider may commit without the relay seeing the acknowledgement is
tracked apart from the pool, as a duration at the session's input format. Without
turn detection that is all audio since the last acknowledged commit or clear.
With server turn detection it is only speech from speech_started, since the
provider drops silence, plus the buffer after an explicit commit. Each started
160 seconds of it claims one held item, and an acknowledged commit, a clear, or
an input_audio_buffer_commit_empty error returns those items to the spares.
The session is never closed for its length. If the upstream closes first, each
claimed item is billed. Each committed item retains its model
until completion, failure, or bounded settlement. Missing usage is billed the
item's fixed budget. Overflow closes the connection without evicting existing
pending identities.
The post-record continuation check asks whether settled credit remains. It excludes outstanding holds and accepts fractional positive credit. Admission of new billable work continues to use the atomic hold path, which includes every outstanding reservation.
When the host listens for ai.prompt.validate, each response that starts runs
it on the text the client sent since the previous check: session and response
instructions, message text and transcripts, and function call output, as chat
messages. The response's cost follows as ai.prompt.cost-calculated under the
same completion id. A refusal closes the session with permission_denied; the
response may already be streaming by then. Pending text past 64 KiB is checked
on its own. Audio is not checked.
Credential checks run in batches of at most 16 with no overlapping sweeps.
Session and access-token revocation events close affected sockets and invalidate
their auth cache entries. Subscription eligibility is checked independently of
authentication and after subscription invalidations. A failed verification check after a 60-second
retry grace from the first failed lookup closes with a retryable internal error. Periodic checks remain the missed-event fallback.
When the drain starts, open sessions get a puter.reconnect event and new
sessions receive server_restarting and close with 1012. Open sessions can
finish an in-flight response for up to five seconds at shutdown, then close
with 1012. A host extension can announce a restart early by emitting
serverRestartAnnounced (optionally with closeInMs); that only sends the
notice, so a false alarm leaves the server working normally. Each session gets
the notice at most once a minute.
Configuration
The provider key resolves through openai-realtime, openai-completion, then
openai. The default upstream is OpenAI. A deployment may override
realtime.upstreamUrl; the tests point it at an in-process fake provider
(the SDK tests live in src/puter-js/tests/api/realtime). The per-user connection cap is configured with
realtime.maxConnectionsPerUser and defaults to 20.
Unit tests use a local WebSocket fixture. Optional live integration tests use
PUTER_TEST_AI_OPENAI_API_KEY.
Remaining constraints
Responses and input transcriptions are billed after completion; holds bound
what is in flight. Sessions require a paid plan (subscription.gate.realtime.openai
can waive it) and accept session, app and full-access API tokens. Conversation
state lives upstream and is lost when a connection ends; the SDK reconnects
with the same settings and replays its recent items, with assistant replies cut
to what the user heard.