* fix(ai): the image type hint only has to be a string when a request carries an input image
* fix(ai): OpenAI speech to text answers 400 to a prompt that is a list or an object
* test(ai): a fuzz case keeps its input and route when the catalog changes, and a suite that reaches no provider fails
* fix(ai): a model id with a colon after its vendor keeps its name when it is qualified
* fix(ai): the native Gemini request type accepts the xhigh effort Hydrogen takes
* style: restore the repo formatting in files the AI stack reflowed
* docs(ai): the image reference and quotas page cover Replicate's safety reruns
* ci: the AI provider workflow runs only the provider tests and passes every provider's key
* 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>
* ci: take release-please from its current home
google-github-actions/release-please-action is archived: the action
moved to googleapis/release-please-action, same code, same inputs,
same major version, and that is where the fixes now land. The
release-please workflow references the maintained repository.
* ci: declare what the three unscoped workflows may do with the token
Docs Build, Maintain Release Merge PR and Notify HeyPuter had no
permissions block, so they ran with the repository's default token
scope. Docs Build only checks out and builds, Notify HeyPuter only
calls the dispatch endpoint with its own token: both declare
contents: read. Maintain Release Merge PR pushes the
auto-update/release branch and opens the release pull request, so it
declares contents: write and pull-requests: write. The other
workflows already declared their scopes and are left as they are.
* ci: stop persisting the checkout credentials in the jobs that never push
actions/checkout keeps the job token in the clone's git config, where
every later step can read it. Twelve checkouts now set
persist-credentials: false: the backend and puter.js test jobs, the
coverage jobs, the type checks, the docs build, the AI provider tests
and the Docker image build read the clone and push nothing with git.
The two checkouts of Maintain Release Merge PR keep the token: that
job resets the release branch and pushes it through
create-pull-request.
* ci: lock the workflow actions to the commits they resolve to
GitHub's workflow dependency lockfile holds the commit each action
reference resolves to, transitive actions included, and the runner uses
those commits even if a tag moves later. .github/workflows/actions.lock
comes from gh actions-lock (v0.4.1), which also narrowed every reference
to the exact release it locked, so Dependabot keeps bumping versions and
its security alerts keep matching. Re-run the same command after adding
or bumping an action.
* ci: drop the unused token scope from Notify HeyPuter, match workflow indentation
* ci: remove the disabled release workflows
release-please and Maintain Release Merge PR have been disabled since 2024; releases are cut from calver tags. Their entries leave the lockfile with them.
---------
Co-authored-by: Daniel Salazar <daniel.salazar@puter.com>
- lowerDecoratorsPlugin dropped esbuild's source map, so coverage and
stack traces reported transformed lines. Pass the external map through.
- puter.js node runner kept a ~6 MB `__coverage__` per vm context and ran
out of heap. Contexts now share one object; workerd merges as it goes.
report-coverage skips its comparison when the PR leg failed.
- CI-only test/hook timeouts of 20 s / 60 s.
- setupTestServer disables the database-liveness health check, whose
`SELECT 1` landed in query-counting tests.
- LocalWorkerService.shutdown asserts the timer shutdown arms instead of
the global fake-timer count.
- userHandlers worker test waits for posts by label.
- AppStore stats test pins the clock so rows don't cross midnight UTC.
- Realtime backpressure test waits up to 5 s for holds to settle.
The base leg checked out the base branch from the PR's head repo. For a
fork PR that is the fork's copy of main, which can predate the current
Node version and fail npm ci.
* test(ai): end every realtime relay test's upstream before the next
The fake upstream now answers response.create with response.created first,
as OpenAI does, so closing those sessions no longer waits out the settle
window.
* feat(ai): ask realtime clients to reconnect before a restart
Open realtime sessions get a puter.reconnect event when the drain starts,
with close_in_ms set to the drain window, and new sessions are still refused
until the 1012 close at shutdown. A host extension can announce a restart
early by emitting serverRestartAnnounced; that only sends the notice, so a
false alarm leaves the server working normally. A session gets the notice at
most once a minute.
onServerDrainStart now receives the drain duration.
* fix(ai): retry realtime reconnects for about a minute and wait out offline browsers
Five attempts gave up after about 15 seconds, shorter than a server restart.
The conversation makes ten attempts with the backoff capped at 10 seconds,
and while the browser reports being offline it waits for the online event,
up to two minutes per reconnect, instead of spending attempts. close() ends
either wait and removes its listener.
* feat(ai): restore recent conversation context after a realtime reconnect
The provider starts a fresh session on every reconnect, so the conversation
lost all earlier items. The SDK now records finished items it can recreate
from the provider's own events: user text, user speech with a transcript,
assistant replies as text, and function calls with their outputs. After the
new session acknowledges its settings, and before ready fires, it adds back
the newest of them, up to 40 items and 48 KiB, which stays under the relay's
upload burst.
Assistant replies are cut to what the user saw or heard: the deltas shown
before an interruption, and the share of the transcript matching the audio
played before a truncation or a drop. Deleted items, unfinished replies,
images, speech without a transcript and incomplete function calls are left
out, as are function outputs whose call falls outside the window. Restored
copies take over their new item IDs. A refused item is reported once as
context_restore_failed without failing the reconnect.
* feat(ai): move a realtime conversation to a new session on the restart notice
On puter.reconnect the conversation waits until it is idle: no reply
requested, generating or playing, no user turn being spoken or transcribed,
no function call awaiting its output and no acknowledgment pending. Then it
reconnects through the usual path, emitting reconnecting (code 1012) and
ready with reconnected: true, without an error. Until then the session keeps
working, and if the server closes it first the normal 1012 reconnect takes
over. close() at any point stops the wait.
* docs(ai): realtime restart notice, context restore and reconnect limits
* test(ai): realtime reconnects against the local server
The mock provider answers with item events and whole replies like OpenAI.
New cases cover a dropped connection (cut through a TCP proxy so the client
sees 1006), a host-announced restart, and a draining server refusing the
reconnect; the first two check the provider receives the restored items
before the next turn. The browser media test waits for captured audio and
the reply instead of a fixed sleep. The live suite gains a tool and text
context round trip across a restart notice.
* ci: run the live realtime conversation tests with the AI provider suite
They need the OpenAI key, which only this workflow has, and skip themselves
without it.
* fix(ai): open the replacement before leaving a realtime session on the restart notice
The handover closed the current session and then reconnected, so every
notice cost a second or two in which sends failed and microphone audio was
dropped. On a single server that refuses new sessions while it drains, the
retries ran out during the drain and the conversation closed sooner than if
it had stayed. The conversation now opens a replacement session as soon as
the notice arrives and switches only once it is open and the conversation is
idle. A refused replacement is retried with backoff while the current
session keeps working; when the server closes it first, the held replacement
is used right away.
The idle check also missed some in-progress work:
- a reply created while the user was still speaking ended the user's turn;
speech now lasts until its audio is committed or cleared, and a committed
turn waits for the reply server turn detection creates
- only the newest function call was checked; every finished call since the
last user message needs its output, and calls cut off by a cancellation
don't count
- native session.update and conversation.item.create events the provider
hadn't acknowledged could be lost; the switch waits for them, up to the
acknowledgment timeout for items
- only the newest transcription was waited on; every committed item is
- clearing playback didn't recheck the switch
Restored items stay internal: the new session's copies of them no longer
reach listeners. At a reconnect, every queued item the user didn't hear is
cut, not just the one playing. A notice from a failed reconnect attempt is
dropped.
* test(ai): realtime replay after split settings, and a draining server refusing the replacement
The relay accepts the context replay right after two full-size settings
updates. Against the local server, a draining relay refuses the replacement
session while the current one keeps answering.
* ci: build the SDK in the live realtime step so it stands on its own
* fix(ai): a failed realtime reconnect attempt no longer poisons the next
An attempt that dropped after sending its session.update but before the
acknowledgment left that event ID queued, so the next attempt's
acknowledgment was matched to it and timed out, and so on until the
conversation closed. Turn state is now reset after each failed attempt.
* fix(ai): bound the realtime handover's waits and stop retries that can't succeed
- The first replacement opens within a randomized 3 seconds of the notice,
so sessions notified together don't all open at once.
- A replacement refused with a code retrying can't fix, such as
insufficient_funds, ends the attempts; the server's close still falls back
to the usual reconnect.
- A held replacement that gets an error or its own server's notice is closed
and replaced.
- A held replacement used after a drop gets a 3 second acknowledgment
timeout, since its socket may have died with the network.
- close() during the switch closes the held replacement too.
- The reply to a committed turn and each transcription hold the switch for
at most 10 and 30 seconds, like app items already did, and an app item is
released only by an added item of its type, role and call ID.
* docs(ai): the realtime restart notice isn't guaranteed before every restart
* chore: move to Node 26
Docker image and CI run on Node 26 (bookworm-slim, same Debian base as before).
Node 26's bundled undici reads the global dispatcher from the
`undici.globalDispatcher.2` slot, so the guard's 10-minute timeout wrap on
`.1` no longer reached plain fetch() and provider calls fell back to the
5-minute headers timeout. The guard now wraps every present slot and tracks
wrapped dispatchers in a set, since compose() can return a Proxy that writes
a marker property through to the original dispatcher.
* test(puter-js): disable Node's web storage in test workers
Node 26 defines its own localStorage global, undefined without a storage
file, and vitest's jsdom environment doesn't replace globals that already
exist, so jsdom tests saw localStorage as undefined.
The suite was CPU-bound on one runner, and about half of that CPU went to
re-importing the backend for every test file.
- Run the suite as 4 shards and merge their blob reports for coverage.
`test (pr)` stays as the required check and fails if any shard fails.
- Drop the per-PR base leg; pushes to main publish the coverage PRs
compare against.
- Files that boot a server without module mocks or extensions run in a
`shared-worker` vitest project (`isolate: false`), so the backend is
imported once per worker. testSharedWorkerSetup.ts resets the redis
mock, configContainer and extensionStore between files.
Skipping the whole matrix job via a job-level `if` collapses it to a
single check with the unevaluated name template ("test (\${{
matrix.artifact }})") instead of expanding to "test (base)"/"test (pr)",
since there's no matrix context to fill in when the job never runs. That
check never matches a required-status-check pinned to "test (pr)", so
PRs that skip backend/puterjs testing block forever waiting on a check
that will never be reported. Gate the steps instead so the matrix always
expands with stable names, doing no real work when irrelevant.
- CODEOWNERS: default owners @Salazareo @ProgrammerIn-wonderland @jelveh
@jfcastro92, plus @reynaldichernando for src/docs.
- dependabot.yml: ignore semver-minor/major npm updates, patch only.
- backend-tests.yaml / puterjs-tests.yaml: trigger unconditionally and gate
the real work behind a dorny/paths-filter job instead of a workflow-level
path filter, so the checks always report (skipped when irrelevant) and
can be marked required. Also pins matrix job names to the artifact label
instead of the branch ref, which previously made the check name change
per PR and unusable as a required check.
Changes are:
- global egress metering
- remove file egress cost
- introduce file op cost for the per request cost s3 has
- enforce fs read/download etc to through 402 when out of usage; allow for subdomains
- enforce kv metering when out of usage through 402; allow for workers
- jsdoc as source of truth for puter.js types
- kv driver caching for get and batchget operations with decreased costs
- declare rate + concurrency limits on every route and driver that lacked one
- add acquireConcurrent for websocket connections and the DAV mount
- bucket AI models by identity key only; keep resold duplicates of any vendor
- skip recently-failed provider routes; cap the fallback chain at 3 attempts
- let full-access access tokens bind a worker to an app their own user owns
- cache resolved subscriptions so tiered limits don't add a round trip
* test: tests for puter.js
* fix: ship lockfile for coverage devDeps; tolerate missing base coverage
npm ci failed on CI because package.json gained the babel/istanbul
devDependencies without the matching package-lock.json update. Also make
the coverage workflow's base leg best-effort so a base ref that predates
the coverage script reports without the comparison column instead of
failing the run.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* ci: add docs build workflow
Add CI workflow that runs npm ci and npm run build in src/docs
whenever files under src/docs change in a pull request.
Closes#3225
* ci: also trigger docs build when workflow file changes
* ci: address docs build workflow review
* chore: upgrade git-date (used for release notes generator)
* chore: update vitest, vitest plugins, and svgo
* chore: run `npm audit fix`
* chore: run `npm audit --force`
* meta: empty commit to run git tests
* fix: tests gone because of a... syntax error?
I question GitHub's judgement of handling a syntax error in the file
that defines tests to run on PRs by pretending everything is fine and
passing all PRs. That to me seems like the worst possible way to handle
that. I think they should have done it not like that.