Files
puter/.github
Filip KujundžićandDaniel Salazar 2d12dcc99f Reorganize AI drivers and harden request handling (#4614)
* 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>
2026-11-14 00:23:04 -07:00
..
2024-11-10 08:48:12 -08:00