Repository navigation
refactor(ai): provider-owned auth and self-censoring Secret - #68586
Conversation
There was a problem hiding this comment.
The refactor works as described, and I found nothing that blocks it. With a temporary test I checked that models from one provider call share the same credential object, and that the API's header and prefix are kept (Bearer for OpenAI, x-api-key for Anthropic). I also checked that a request's own apiKey wins: a string and a Secret both reached the wire through ai.generate. The environment is read when a request is sent, apiKey: false sends nothing, a "<redacted>" key fails with AuthenticationError, and update(..., { api: api.with({ baseURL }) }) keeps the credential. packages/ai tests (2431) and typecheck:tsc pass. Core tsc and the model-resolver / session-model-request tests pass.
Public API of @opencode/ai:
- Added:
model.auth: Auth.Sourceon every model, required on hand-written model records (LanguageModel.makefills it in when omitted). - Added:
apiKey?: string | Secreton text, media, decision and embedding requests. - Added: the
Secretexport. - Added:
Auth.SourceandAuth.resolvein@opencode/ai/internal. - Changed:
model.api.authnow holds how the API sends a key, not the resolved credential. Code that calledmodel.api.auth.apply(...)must switch toAuth.resolve(model.api.auth, model.auth). - Changed: a literal
"<redacted>"key is now rejected instead of sent.
Provider settings, the config, plugin and server APIs, and wire bytes are unchanged. So this is backwards compatible for settings-based callers, but not for code that builds model records by hand or reads api.auth directly.
One gap worth closing: nothing tests the two new behaviours, a request-level apiKey overriding the provider's credential and the "<redacted>" placeholder being rejected. Two small Auth.resolve cases in test/auth.test.ts would cover them.
240c857 to
0274ba4
Compare
There was a problem hiding this comment.
The update still works as described. In packages/ai, bun test passes (2431) and typecheck:tsc is clean. In packages/core, tsc is clean and the model-resolver, session-model-request and native-compaction tests pass. I re-ran an end-to-end check through ai.generate: the provider key, a request string key, a request Secret and the environment key each produced the right header, and a request key of Secret.make("<redacted>") fails with AuthenticationError. Custom sources keep their handler out of JSON and survive object spread.
Public API of @opencode/ai:
- Added:
model.auth: AuthSource(env/key/none/custom), required on hand-written model records (LanguageModel.makefills it in when omitted). - Added:
apiKey?: string | Secreton every request. - Added: the
Secretexport and theAuthSourcetype. - Changed: a
"<redacted>"key is now rejected at request time instead of sent. - Changed:
model.api.authno longer carries the resolved credential.
Provider settings, config, the plugin and server APIs, and wire bytes are unchanged.
One new problem: the placeholder guard crashes when a model's auth has been through JSON (see the inline comment).
| } | ||
|
|
||
| const keyed = (format: Auth.ApiKey, key: Secret) => | ||
| Secret.isPlaceholder(key) |
There was a problem hiding this comment.
The placeholder check is meant to catch the key a printed model leaves behind. But a model whose auth went through JSON comes back as { type: "key", key: "<redacted>" }, with a plain string where a Secret should be. Secret.isPlaceholder then reads #value on a non-Secret and throws TypeError: Cannot access invalid private field, so the request dies with a defect instead of the AuthenticationError. I hit this by spreading a model with auth: JSON.parse(JSON.stringify(model.auth)) and calling ai.generate. Checking key instanceof Secret first, and treating anything else as the placeholder, would give the intended error.
There was a problem hiding this comment.
Fixed in 0fec582: a key that isn't a Secret (as after a JSON round trip) is treated as the placeholder and fails with AuthenticationError. Checked with { ...model, auth: JSON.parse(JSON.stringify(model.auth)) } through ai.generate.
There was a problem hiding this comment.
The new commit fixes the crash I reported: a model whose auth went through JSON now fails with the intended AuthenticationError instead of a TypeError. I checked it end to end through ai.generate. Provider keys and per-request keys still send the right header, the auth and provider tests pass, and typecheck:tsc is clean. Nothing new to raise. The public API impact is the same as in my last review: it adds model.auth (AuthSource), request apiKey, and the Secret and AuthSource exports, and hand-built models must set auth.
There was a problem hiding this comment.
The new commit is fine. Job calls by ID (status, result, cancel) now take an optional { apiKey } and pass it to the route lookup, so they follow the same rule as start. The updated image-job test checks that a plain call sends the provider's key and a call with its own key sends that one. bun test passes in packages/ai and typecheck:tsc is clean. The "<redacted>" crash from my earlier comment was fixed in the previous push.
Public API changes in this push: an optional third argument { apiKey } on status/result/cancel for image, video and transcription (Effect and Promise APIs), and the new JobOptions type. Both are backwards compatible. The rest of the PR's impact is unchanged: model.auth, request apiKey, and the Secret and AuthSource exports.
79fe2cf to
37c3eae
Compare
Issue for this PR
Closes #
Follows #68585 (plain
Modelrecord), now merged; this branch is rebased ontodev.Type of change
What does this PR do?
Credentials now belong to the provider.
openai({ apiKey })makes one credential value, and every model from that provider call shares it by reference asmodel.auth. The model's API still decides how a key is sent (header and prefix), as today.How
resolvepicks the auth:Secret(src/secret.ts) holds its value in a private field.String,JSON.stringifyandconsole.log/inspect all give"<redacted>", andSecret.valueis the only reader.sanitizeSurrogatespasses it through untouched, like media assets.Settings inputs don't change (
apiKey,authToken,accessToken,auth: "sigv4",apiKey: false). An empty key still falls back to the environment. A key from EffectConfigis still read when a request is sent. An API whose auth is a definition keeps it and ignoresapiKey, as before.LanguageModel.makefillsauthfrom the API's own auth when it's omitted.LanguageModel.updatewith an API that brings different auth takes that auth, soupdate(model, { api: model.api.with({ auth }) })behaves as before.Net for this PR: +356 / −92 (+264). Together with #68585 the change is −244.
Public changes
Accepted direction: credentials live on the provider, as plain data. Everything else that changes for callers:
model.auth: AuthSourceon every model (env/key/none/custom), required on hand-written records.LanguageModel.makefills it from the API's own auth when it's omitted. No internalAuth.Definitionappears in public types; acustomsource keeps its handler under a private symbol.apiKey?: string | Secreton every request (text, media, decision, embedding). It wins over the provider's credential.status(model, id, { apiKey }),result(model, id, { apiKey })andcancel(model, id, { apiKey })for image, video and transcription jobs, in both the Promise and Effect APIs (newJobOptionstype). Same precedence asstart.generate/streamalready poll with the start call's key, because the poll reuses the routestartbuilt.Secret, and theAuthSourceandJobOptionstypes."<redacted>"fails at request time withAuthenticationError("The API key is the "" placeholder a printed key leaves") instead of being sent.@opencode/ai/internalis unchanged; the resolver (route/credential.ts) andauth-source.tshelpers are package-private, and tests import them fromsrc.Unchanged: wire bytes, provider settings (
apiKey,authToken,accessToken,auth: "sigv4",apiKey: false),packages/plugintypes, and core behavior.How did you verify your code works?
./providers/*entrypoint (not committed): unchanged, 130/130. It masks credential header values, so the existing provider auth tests cover the values. They now resolve through the package-privateresolveand pass.image-job.test.ts) gains an assertion thatstatus(model, id, { apiKey })sends the call's key while a plainstatussends the provider's.Secretprints as<redacted>from String, JSON andBun.inspect. The existing "reads the API key from the environment when a request is sent" test covers env reads.packages/ai:bun run typecheck,typecheck:tsc,bun test: 2561 pass. The emittedmodel.d.ts/auth-source.d.tspublic types reference noAuth.DefinitionorAuthInput.packages/core:typecheck:tsc; model-resolver (auth asserted on the sent request), aisdk, session-native-compaction, session-model-request and generate tests: 138 pass.bun run check.Checklist