Repository navigation
Make the Jev backend provider-agnostic (TypeSafe direct + Vercel AI Gateway) - #1
Conversation
TypeSafeJevProvider now implements JevPort; createSdkAdapter and classifyError keep their names and behavior. The SDK client is injectable so provider tests need no network.
VercelJevProvider translates Jev questions/answers to the gateway evaluation API (typesafe-ai/jev) via experimental_evaluate from the ai package. JEV_PROVIDER=typesafe (default) | vercel, validated at startup; each provider owns its classifier. Confidence absent from gateway answers is derived from the distribution (selected-choice mass / max level mass).
22 tests: provider selection and startup failure, TypeSafe request forwarding and error mapping, Vercel question/answer translation, confidence derivation, padding, model-id reporting, missing keys, CLI-level JEV_PROVIDER behavior, and provider-independent review behavior. All network calls mocked. Docs: provider configuration in README and architecture.md.
experimental_evaluate has no timeout parameter, so the provider wraps the call in its own AbortController: a timer aborts at timeoutMs and forwards an external run signal, surfacing as AbortError/TimeoutError which classifyVercelError maps to aborted/transient.
…re defaults
- Read TypeSafe's separate confidence statistic from
providerMetadata.typesafe.confidence[questionId] (Choice/Score);
derive from the distribution only when that metadata is genuinely
absent, documented as an approximation.
- createVercelAdapter now binds the supplied AI_GATEWAY_API_KEY via
createGateway({apiKey}).evaluationModel(id) instead of relying on the
process-global gateway; process.env is never mutated. Proven by a
local-server test asserting the Bearer header actually sent.
- Model namespaces stay separate: unqualified TypeSafe ids (jev-1.13.0)
select the configured gateway model (JEV_GATEWAY_MODEL, default
typesafe-ai/jev); slash-qualified gateway ids pass through.
- gateway.zeroDataRetention=true by default (evaluations contain source
code); JEV_GATEWAY_ZERO_DATA_RETENTION=0 opts out.
- Already-aborted external signals now propagate before any evaluation.
- Optional live smoke: npm run smoke:vercel (JEV_SMOKE=1), skips cleanly.
- README/help updated to match actual behavior.
- ask() computes the effective gateway model once and uses it for both the model factory and the response.model fallback. - smoke-env JEV_SMOKE regex anchored as a group; '10', 'yes1', 'true1' no longer enable live smoke tests (covered by tests). - createVercelAdapter accepts test-injection options (baseURL, evaluate) so the credential test drives the adapter itself end-to-end against a local server; the Bearer assertion is unchanged.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 073eade682
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| typesafeConfidence(result.providerMetadata), | ||
| ), | ||
| usage: { | ||
| input_tokens: result.usage?.inputTokens ?? 0, |
There was a problem hiding this comment.
Preserve input estimates when gateway usage is missing
When the gateway omits its optional usage data, this reports zero input tokens; Budget.settle() then replaces the reserved estimate with zero by subtracting the entire estimate. Consequently, Vercel runs in this supported scenario do not advance the input-token counter, so --max-input-tokens cannot stop the run and substantially more repository data than configured may be sent. Preserve the estimate or represent missing usage as unknown instead of zero.
Useful? React with 👍 / 👎.
| export function createWorkflowDependencies( | ||
| root: string, | ||
| jev: JevPort, | ||
| classify: (error: unknown) => TransportFailure = classifyError, |
There was a problem hiding this comment.
Couple the classifier to the selected environment provider
When library callers combine the newly provider-aware jevFromEnvironment(env) with the exported two-argument createWorkflowDependencies(root, jev) API, a Vercel port silently receives this TypeSafe classifier. Gateway failures represented with statusCode, such as a 500 GatewayInternalServerError, are then classified as unknown rather than transient, so the executor skips its configured retries. Return or select the classifier together with the provider instead of retaining a TypeSafe-specific default.
Useful? React with 👍 / 👎.
| const out: Record<string, unknown> = {}; | ||
| for (const [name, question] of Object.entries(questions)) { | ||
| const answer = answers[name]; | ||
| if (!answer) throw new Error(`the gateway returned no answer for question "${name}"`); |
There was a problem hiding this comment.
Route malformed gateway answers through validation retries
If a gateway response omits an answer, this throws while execution is still inside port.ask(); the answer-type checks below behave the same way. FrameExecutor consequently handles the plain error as a transport exception, and classifyVercelError() returns unknown, so the frame fails immediately instead of entering the response-validation path that retries invalid model responses. Return an invalid envelope for core validation or otherwise classify these malformed responses as retryable.
Useful? React with 👍 / 👎.
…g, retries - P1: missing gateway usage no longer zeroes the input-token budget; the envelope reports the same deterministic estimate the executor reserved, so --max-input-tokens keeps guarding Vercel runs. - P2: createWorkflowDependencies now accepts a provider name and maps it through classifierFor; jevFromEnvironment(env) callers can no longer pair a Vercel port with the TypeSafe classifier. The CLI passes configuredProvider(io.env) directly. - P2: malformed gateway answers (missing/wrong-typed) throw ValidationError instead of plain errors, so the executor routes them through its invalid-response retry path instead of failing the frame. - Test env-leak hardening: the credential test asserts process.env is unchanged across construction rather than assuming the var is unset.
|
Addressed all three Codex findings in 2c4d912:
|
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2c4d912cc9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| export function createWorkflowDependencies( | ||
| root: string, | ||
| jev: JevPort, | ||
| classify: ProviderName | ((error: unknown) => TransportFailure) = DEFAULT_PROVIDER, |
There was a problem hiding this comment.
Derive the classifier from the created provider
When a library caller uses jevFromEnvironment(env) with JEV_PROVIDER=vercel and then calls the still-supported two-argument createWorkflowDependencies(root, jev), this default silently selects the TypeSafe classifier. Gateway errors expose statusCode, which classifyError() does not inspect, so transient gateway failures such as HTTP 500 are classified as unknown and are not retried. Fresh evidence in the current revision is that the new third argument remains optional and defaults independently to DEFAULT_PROVIDER, so the originally reported pairing is still possible.
Useful? React with 👍 / 👎.
| // Malformed gateway answers are invalid model responses, not transport | ||
| // failures: surface them as validation errors so the executor's | ||
| // invalid-response retry path handles them instead of failing the frame. | ||
| throw new ValidationError(error instanceof Error ? error.message : String(error)); |
There was a problem hiding this comment.
Retry malformed gateway responses through the validation path
When the gateway omits an answer or returns the wrong answer type, throwing ValidationError here still rejects port.ask(). FrameExecutor catches that rejection in its transport-error block (src/core/executor.ts:191-211), where classifyVercelError() classifies it as unknown; the validation retry logic only runs later for responses returned successfully. Fresh evidence in the current revision is the new ValidationError wrapper itself: it does not move the failure into the executor's response-validation block, so malformed responses still fail immediately rather than receiving the configured retries.
Useful? React with 👍 / 👎.
| function aborted(reason: unknown): unknown { | ||
| if (reason instanceof Error) return reason; | ||
| return new DOMException("run aborted", "AbortError"); |
There was a problem hiding this comment.
Normalize caller-supplied abort reasons
When an in-flight external signal is aborted with a custom reason such as controller.abort(new Error("cancelled")), this preserves the generic Error; the gateway request then rejects with that reason, but classifyVercelError() recognizes only errors named AbortError or APIUserAbortError. The executor consequently reports the cancelled frame as an unknown failure instead of aborted. Wrap external reasons in an abort-typed error, or classify the forwarded signal reason explicitly.
Useful? React with 👍 / 👎.
…n, aborts - P2: malformed gateway answers now return a valid envelope with an empty answer map instead of throwing: the executor's response- validation path (which retries) rejects it via the frame parser, rather than the transport-error path (unknown, never retried). Verified end-to-end: a frame with a validating parser gets its configured retries (3 attempts with retries: 2). - P2: createWorkflowDependencies now derives the default classifier from the port itself (VercelJevProvider.classifyError) instead of an independent provider-name default, closing the two-argument pairing gap; the CLI returns to the two-argument call. - P2: caller-supplied abort reasons are normalized to abort-typed errors (DOMException AbortError) when forwarded and when thrown for an already-aborted signal, so classifyVercelError reports aborted instead of unknown.
|
Round-2 findings addressed in 5a11d73:
|
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5a11d736bc
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| for (const [name, question] of Object.entries(questions)) { | ||
| const answer = answers[name]; |
There was a problem hiding this comment.
Reject unexpected gateway answer keys
When the gateway returns every requested answer plus an unexpected key, this loop rebuilds the map solely from request.questions and silently discards the extra answer. All workflow parsers rely on expectKeys() to reject unexpected keys, so the sanitized response can be accepted instead of entering the invalid-response retry path; validate the gateway's original key set before translation or preserve extra keys for core validation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this push (see commit).
| of the selected choice, or the maximum level mass for score) — an approximation, not the model's | ||
| own confidence, so threshold-gated decisions can differ from TypeSafe-direct in that case. | ||
| - Noul/boolean answers carry probability only; TypeSafe reports no separate confidence for them. | ||
| - Usage numbers come from the gateway; when it omits them they are reported as zero. |
There was a problem hiding this comment.
Describe the usage estimate used when gateway usage is absent
When the gateway omits usage, the implementation now reports estimateTokens(request) rather than zero, so this documented behavior is incorrect precisely for the fallback case it describes. This can mislead users interpreting packet telemetry or diagnosing input-budget exhaustion; document that input usage is conservatively estimated while output usage falls back to zero.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this push (see commit).
| /timeout|connection|ratelimit/i.test(name) || | ||
| /econnreset|etimedout|socket hang up|rate limit/.test(message) |
There was a problem hiding this comment.
Retry ordinary fetch connection failures
When a gateway request fails before receiving an HTTP status, Node fetch commonly surfaces TypeError: fetch failed, with details such as ECONNREFUSED, ENOTFOUND, or EAI_AGAIN only on cause; AI SDK connection errors may likewise expose isRetryable without a status code. None of those top-level names or messages match this condition, and the classifier does not inspect cause or isRetryable, so the executor classifies a transient network outage as unknown and skips its configured retries.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this push (see commit).
… keys - P2: classifyVercelError recognizes plain connection failures as transient — TypeError: fetch failed (with ECONNREFUSED/ENOTFOUND/ EAI_AGAIN/ECONNRESET/EPIPE on the cause), retryable-flagged AI SDK errors, and network error names. - P2: unexpected gateway answer keys are no longer silently dropped; translation rejects and the empty-answer envelope routes the frame into the invalid-response retry path. - P3: README now documents the conservative input-size estimate reported when gateway usage is absent.
|
Round-3 findings addressed:
|
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2170d037ef
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| type: "choice", | ||
| choice: answer.choice, | ||
| confidence: reported(name) ?? probabilities[answer.choice] ?? 0, | ||
| probabilities: Object.fromEntries(labels.map((label) => [label, probabilities[label] ?? 0])), |
There was a problem hiding this comment.
Reject extra probability labels before rebuilding distributions
When a choice response includes every requested label plus an unexpected probability key, this reconstruction silently drops the extra key before readChoice() performs its exact-key validation. For example, {a: 0.6, b: 0.4, ghost: 0.8} becomes the apparently valid {a: 0.6, b: 0.4}, so a malformed gateway response can be accepted and influence workflow decisions instead of entering the invalid-response retry path; validate the original probability keys before normalizing the map.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this push (see commit).
| const value = confidence?.[name]; | ||
| return typeof value === "number" && Number.isFinite(value) ? value : undefined; | ||
| }; | ||
| const unexpected = Object.keys(answers).filter((name) => !(name in questions)); |
There was a problem hiding this comment.
Check gateway answer keys as own properties
When the gateway adds a reserved object-property key such as constructor or toString, the in operator finds that name on questions through Object.prototype, so the key is not considered unexpected; the following Object.entries(questions) loop then omits it and the sanitized response can pass validation. Fresh evidence in the current revision is this inherited-property check, which leaves the previously fixed unexpected-answer case open for these names; use an own-property check instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this push (see commit).
| return typeof candidate === "function" | ||
| ? (candidate as (error: unknown) => TransportFailure) |
There was a problem hiding this comment.
Bind provider-owned classifiers to their port
When a provider-aware port declares classifyError as an ordinary method that reads instance state, this returns the method unbound; WorkflowDependencies later invokes it with the dependencies object as this, so transport-error handling can itself throw or misclassify the failure instead of applying retries. Fresh evidence after the classifier-coupling fix is defaultClassifierFor() returning the raw method reference; bind it to jev or invoke it through the provider.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this push (see commit).
… binding - P2: answer-key unexpectedness uses Object.hasOwn, so prototype-named keys (constructor, toString) count as unexpected instead of passing through the inherited-property 'in' check. - P2: extra probability labels reject instead of being silently dropped — choice answers with probabilities for unknown choices and score answers with out-of-range level keys both route into the invalid-response retry path. - P2: defaultClassifierFor binds the port's classifyError to the port, so method-reference invocation through WorkflowDependencies keeps the right 'this'.
|
Round-4 findings addressed:
|
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 966db43078
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const extraLevels = Object.keys(probabilities).filter( | ||
| (key) => Number.isNaN(Number(key)) || Number(key) < 0 || Number(key) >= levelCount, | ||
| ); |
There was a problem hiding this comment.
Reject noncanonical score probability keys
When a gateway score response contains a numeric-looking unexpected key such as "1.5", "01", or "1e0", converting the key with Number() makes it appear in range, so it is not rejected. The reconstruction below then silently drops that key; if the canonical keys already sum to one, core validation accepts the sanitized distribution despite the original response containing unexpected probability mass. Compare against the exact allowed string keys ("0" through String(levelCount - 1)) instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this push (see commit).
| return typeof candidate === "function" | ||
| ? (candidate as (error: unknown) => TransportFailure) |
There was a problem hiding this comment.
Bind provider-owned classifiers before returning them
When a provider-aware port implements classifyError as an ordinary method that reads instance state, this returns the method unbound; the workflow later calls it as dependencies.classifyError(error), so this becomes the dependencies object and classification can throw or return the wrong result. Fresh evidence after the prior “fixed” reply is that the current implementation still returns the raw candidate rather than binding it to jev; return a bound function or invoke the method through the port.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this push (see commit).
| export JEV_PROVIDER=vercel # Vercel AI Gateway hosting of Jev | ||
| export AI_GATEWAY_API_KEY="<key>" # canonical variable read by the ai package |
There was a problem hiding this comment.
Disclose the gateway in the privacy guidance
When users select this new Vercel provider, repository requests pass through the Vercel AI Gateway, but the existing Reports and privacy section still says data is sent to TypeSafe and advises reviewing only TypeSafe's data terms. Zero-data-retention routing does not eliminate the gateway's processing of the request, so users deciding whether private or regulated code may be sent are missing a relevant service and set of terms; update the privacy guidance to identify both the gateway and the upstream provider.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this push (see commit).
| Jev inference is pluggable. Both providers expose the same Jev/System One capability to the review | ||
| engine — identical questions, identical calibrated answers, identical reports — so reviews behave the | ||
| same either way. Selection is entirely through configuration, at process start: |
There was a problem hiding this comment.
Avoid promising identical results across providers
The claim that the providers produce identical calibrated answers and reports contradicts the newly documented fallback below: when gateway confidence metadata is unavailable, confidence is synthesized from the distribution and threshold-gated decisions can differ from TypeSafe-direct. Users comparing or switching providers therefore cannot rely on identical review output; describe the providers as exposing the same schema and capability rather than identical results.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this push (see commit).
| **API key.** jev-code reads the required key only from environment variables, never from files or flags. Which key it needs depends on the provider (see below): | ||
|
|
||
| ```sh | ||
| export TYPESAFE_API_KEY="<your TypeSafe API key>" | ||
| export TYPESAFE_API_KEY="<your TypeSafe API key>" # default provider | ||
| export AI_GATEWAY_API_KEY="<your gateway key>" # JEV_PROVIDER=vercel |
There was a problem hiding this comment.
Remove the TypeSafe-only prerequisite
Although this new setup block allows the Vercel provider to run with only AI_GATEWAY_API_KEY, the earlier workflow description and Requirements section still state that a TypeSafe API key is required. A user choosing the gateway can therefore be led to obtain or configure an unnecessary credential; make those global prerequisites provider-neutral and state that either the TypeSafe key or the gateway key is required according to JEV_PROVIDER.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this push (see commit).
…r, README accuracy
- P2 (real miss caught by review): the round-4 classifier bind never
landed (heredoc failure silently dropped it from that commit).
defaultClassifierFor now genuinely binds the port's classifyError
to the port; regression test invokes it through the dependencies
layer and asserts instance state stays reachable.
- P2: score probability keys are compared against exact canonical
level keys ('0'..'n-1'), so '1.5', '01', '1e0' reject instead of
coercing into range and being silently dropped.
- P2: privacy guidance now discloses that the Vercel provider routes
through the AI Gateway, which processes requests even under
zero-data-retention; users are pointed at both services' terms.
- P3: provider section no longer promises identical results across
providers (confidence fallback can differ); describes shared schema
and capability instead.
- P3: requirements/setup are provider-neutral (either TypeSafe key or
gateway key per JEV_PROVIDER).
|
Round-5 findings addressed — including one where review caught a genuine miss: the round-4
|
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e9e5784403
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| out[name] = { type: "noul", noul: answer.probability }; | ||
| } else if (question.type === "choice") { | ||
| if (answer.type !== "choice") throw new Error(`answer "${name}" is not a choice answer`); | ||
| const probabilities = answer.probabilities ?? {}; |
There was a problem hiding this comment.
Handle choice answers that omit probabilities
When experimental_evaluate returns a choice without probabilities—a shape explicitly permitted by GatewayAnswer—this fallback builds an all-zero distribution. readChoice() then rejects it because its probability sum is zero, so every otherwise valid choice-only answer consumes all validation retries and ends as invalid. Either make probabilities required if the gateway protocol guarantees them or synthesize a valid distribution when they are absent.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this push (see commit).
| **Requirements:** Node.js 22.18 or newer, `git`, a Git repository to check, and a Jev credential: | ||
| either a TypeSafe API key (default provider) or an AI Gateway key (`JEV_PROVIDER=vercel`), per the | ||
| [Jev providers](#jev-providers) section. CI tests on Linux; Windows is untested. |
There was a problem hiding this comment.
Make the workflow overview provider-neutral
For users selecting JEV_PROVIDER=vercel, these provider-neutral requirements still conflict with the workflow overview at README.md:38, which says a TypeSafe API key is required even though only AI_GATEWAY_API_KEY is needed. Fresh evidence after the prior fix is that the current revision leaves that earlier statement unchanged; update it so the introductory flow does not send gateway users to obtain the wrong credential.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this push (see commit).
| "format": "biome format --write .", | ||
| "test": "node --test --test-reporter=spec \"test/**/*.test.ts\"", | ||
| "smoke": "node scripts/smoke-cli.ts", | ||
| "smoke:real": "node scripts/smoke-real.ts", |
There was a problem hiding this comment.
Force the TypeSafe provider in the TypeSafe smoke test
When a developer runs the newly exposed npm run smoke:real with JEV_PROVIDER=vercel already set, smoke-real.ts forwards that environment unchanged to the CLI. With only TYPESAFE_API_KEY the advertised TypeSafe smoke fails while parsing the CLI error packet, and with both credentials it silently exercises Vercel instead of TypeSafe. Clear or override JEV_PROVIDER to typesafe for this script.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this push (see commit).
| export function envSecrets(): string[] { | ||
| const values: string[] = []; | ||
| for (const name of ["TYPESAFE_API_KEY", "COPILOT_MCP_TYPESAFE_API_KEY"]) { | ||
| for (const name of ["TYPESAFE_API_KEY", "AI_GATEWAY_API_KEY", "COPILOT_MCP_TYPESAFE_API_KEY"]) { |
There was a problem hiding this comment.
Redact gateway keys supplied through a custom environment
When a library caller constructs the exported Vercel adapter with createVercelAdapter(customEnv) or jevFromEnvironment(customEnv), this redaction helper still reads AI_GATEWAY_API_KEY only from global process.env. If the custom key appears in repository evidence or a gateway error, it is therefore neither redacted before transmission nor scrubbed from reports, despite the adapter accepting that custom environment as its credential source. Pass the same environment into the redaction dependency or register the adapter's actual key explicitly.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this push (see commit).
…e pinning, docs - P2: choice answers that omit probabilities (an allowed gateway shape) now synthesize a point mass on the selected choice instead of an all-zero distribution that readChoice would reject, burning every retry on otherwise valid answers. - P2: redaction is env-aware — createRedaction(env) unions the supplied and process environments' credential values, and createWorkflowDependencies threads io.env through, so a custom environment's gateway key is redacted from evidence and errors. - P2: smoke-real forces JEV_PROVIDER=typesafe so the TypeSafe smoke never silently exercises Vercel (or fails parsing its error packet) when a gateway env is present. - P3: the workflow overview is provider-neutral (TypeSafe key or gateway key per JEV_PROVIDER).
|
Round-6 findings addressed:
|
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 49c3b1918a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| }; | ||
| } else { | ||
| if (answer.type !== "score") throw new Error(`answer "${name}" is not a score answer`); | ||
| const probabilities = answer.probabilities ?? {}; |
There was a problem hiding this comment.
Synthesize score distributions when probabilities are omitted
When experimental_evaluate returns a score without probabilities—a shape explicitly permitted by GatewayAnswer—this fallback creates an all-zero distribution. readScore() rejects that distribution because it sums to zero, so every otherwise valid score-only response consumes all validation retries and ends as invalid. Synthesize a distribution consistent with the reported score, as the choice path does, or require probabilities if the gateway protocol guarantees them.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this push: probability-less score answers now synthesize a distribution consistent with the reported score (point mass for integral, linear interpolation for fractional — readScore accepts both). Out-of-range scores still reject into the retry path. Tested for all three shapes.
- Score answers without probabilities (an allowed gateway shape) now get a distribution consistent with the reported score: point mass for integral scores, linear interpolation between adjacent levels for fractional ones (readScore accepts and expects both). Previously the all-zero fallback was rejected by readScore and burned every retry on valid answers. - Out-of-range scores (beyond the rubric) still reject into the invalid-response retry path; bounds match readScore's tolerance. - Regression tests cover integral, fractional, and out-of-range cases.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 11ad3f3f8c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| root: string, | ||
| jev: JevPort, | ||
| classify?: (error: unknown) => TransportFailure, | ||
| env: NodeJS.ProcessEnv = process.env, |
There was a problem hiding this comment.
Bind custom-environment secrets into dependency redaction
When a library caller uses the exported two-argument composition createWorkflowDependencies(root, createVercelAdapter(customEnv)), this default still builds redaction from global process.env, not the environment containing the gateway credential. If that credential appears in repository evidence or a provider error, it can therefore be transmitted or persisted without being scrubbed. Fresh evidence after the earlier fix is that the new env argument remains optional while the provider does not expose its credential, so existing two-argument callers cannot inherit the adapter's custom environment automatically; couple the credential to the provider/dependencies or otherwise ensure this composition registers it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this push: ports now expose credentialSecrets (both providers populate them), and createWorkflowDependencies unions the port-owned credentials into its redaction dependency. The plain two-argument composition with createVercelAdapter(customEnv) scrubs the custom-env key from evidence and errors without any environment argument. Tested for both providers.
- Ports expose credentialSecrets (TypeSafeJevProvider and VercelJevProvider both populate them); portSecrets(jev) reads them. - createWorkflowDependencies unions the port's credentials into the redaction dependency, so createWorkflowDependencies(root, createVercelAdapter(customEnv)) scrubs the custom-env key from evidence and errors even though no environment was passed. - createRedaction(env, extraSecrets) accepts the extra values. - Tested for both providers through the plain two-argument call.
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
* fix: remove imports orphaned by the provider-abstraction merge The squash-merge of PR #1 left classifyVercelError, classifyError, configuredProvider, PROVIDER_ENV and RedactionPort imported but unused, which fails npm run lint (biome noUnusedImports) on merged main. * feat: add Cloudflare Workers AI as a third Jev provider JEV_PROVIDER=cloudflare routes Jev through Cloudflare's native AI REST run endpoint (POST /accounts/{id}/ai/run, model alias typesafe/jev) using CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN (JEV_CLOUDFLARE_API_TOKEN as an application-specific alias that wins when both are set). - CloudflareJevProvider behind the existing JevPort; direct fetch, no SDK - native noul/choice/score contract, no boolean translation - v4 envelope + execution-state double-nest unwrapping; failed execution states are provider errors, never empty answer sets - malformed payloads resolve to the empty-envelope invalid-response path - classifyCloudflareError with the shared TransportFailure taxonomy - credentials exposed through credentialSecrets/portSecrets and envSecrets - JEV_CLOUDFLARE_MODEL (default typesafe/jev); TypeSafe-direct ids never forwarded, only typesafe/-qualified slugs pass through - usage passthrough with the deterministic input estimate fallback - npm run smoke:cloudflare (JEV_SMOKE=1 gated, skips cleanly) - README/docs/CLI help updated; default provider remains typesafe * fix: address round-1 review findings on the Cloudflare provider - keep the timeout timer and external-abort forwarding armed through response.text() so a stalled body cannot hang past timeoutMs or ignore aborts (fetch resolves on headers alone) - register the constructor's apiToken in credentialSecrets by default so directly-constructed providers are redacted too, not just factory-built - a whitespace-only JEV_CLOUDFLARE_API_TOKEN falls back to the canonical CLOUDFLARE_API_TOKEN instead of shadowing it (resolveCloudflareToken) - classifyCloudflareError recognizes body-read socket failures (TypeError: terminated, cause SocketError / UND_ERR_SOCKET) as transient - honor CLOUDFLARE_BASE_URL in createCloudflareAdapter so the CLI test actually routes to the local mock server instead of api.cloudflare.com; test now asserts the local server received requests 5 new regression tests; suite 186/186; check green. * fix: classify Cloudflare 402 insufficient-balance as auth Live-observed on the first real smoke run: Cloudflare returns HTTP 402 error 2021 (Insufficient balance; add money to your gateway or use BYOK) for accounts without balance. It is a definite account-state rejection, not transient: classify as auth so the executor stops the run with a clear reason instead of burning retries (generic 4xx) or retrying it. * fix: classify Cloudflare 402 insufficient-balance as rejected Round-2 review finding: mapping 402/billing failures to auth sends the executor into its auth branch, which discards the billing diagnostic and reports only 'authentication failed' even though credentials may be valid. Classify as rejected instead — terminal without retries, and the original 402 message (add money / BYOK) reaches the user. Test expectation updated. * fix: address round-3 review findings on the Cloudflare provider - null JSON body: guard the .success/.result reads so a literal null response flows into the empty-envelope invalid-response retry path instead of throwing a TypeError classified 'unknown' (never retried) - baseURL: strip trailing slashes so proxy base URLs don't produce //accounts/... paths that route-sensitive intermediaries 404 - too_large matching: restrict message matching to size-specific phrases (payload too large, exceeds the input limit, ...); bare 'payload' and 'exceeds the limit' no longer misfile schema/validation 400s as size problems that the find workflow would recursively split and resend. Twin fix applied to the jev.ts and vercel-jev.ts classifiers, which shared the same over-broad bare-'payload' pattern. Tests: null-body, trailing-slash, and 4 classification rows added; full npm run check green (188/188). * fix: preserve too_large wording and detect result-less execution states - classifyError and classifyVercelError recognize 'payload exceeds …' wording before the generic 4xx path, so HTTP 400 size rejections stay too_large and keep the executor's splitting behavior - isExecutionState no longer requires an inner result: failed or still-running Cloudflare executions ({state:'Failed', errors:[…]}) now take the provider-error path instead of looking like malformed Jev payloads that hide behind invalid-response retries Tests: 2 classification rows + result-less state envelope case (191/191). --------- Co-authored-by: darko <darko@dlukt.de>
Summary
Review behavior is unchanged; Jev inference can be switched between the TypeSafe direct API and the Vercel AI Gateway entirely through configuration.
JevProviderboundary: the existing coreJevPortalready is the provider-agnostic seam, so no new abstraction was invented. TypeSafe specifics moved behindTypeSafeJevProvider(adapters/jev.ts); the wire client, credentials, and error taxonomy live inside the provider.VercelJevProvider(adapters/vercel-jev.ts): Jev/System One via the gateway evaluation API (experimental_evaluate, modeltypesafe-ai/jev, verified againstai@7.0.107). Question translation noul→boolean; TypeSafe's separate confidence statistic preserved fromproviderMetadata.typesafe.confidence[questionId](distribution-derived fallback only when genuinely absent, documented). SDK retries disabled — the executor keeps owning retry/budget accounting. Timeout enforced via an owned AbortController.JEV_PROVIDER=typesafe(default, backward compatible) |vercel. Unknown names fail at startup (exit 64), missing key exits 65. Credentials bound viacreateGateway({ apiKey })from the supplied env — no reliance on process-global config, noprocess.envmutation (proven by a local-server test asserting the Bearer header actually sent).jev-1.13.0) are never forwarded to the gateway; slash-qualified gateway ids pass through. Gateway model configurable viaJEV_GATEWAY_MODEL(defaulttypesafe-ai/jev).providerOptions.gateway.zeroDataRetention = true) — evaluations contain source code and diffs. Opt-outJEV_GATEWAY_ZERO_DATA_RETENTION=0documented for troubleshooting.docs/architecture.mdupdated.npm run smoke:vercel(requiresJEV_SMOKE=1+AI_GATEWAY_API_KEY), skips cleanly, not part ofnpm run check.Configuration
Test plan
npm run check: lint, typecheck, 131/131 tests (99 upstream + 32 new), build, 14/14 CLI smoke — all greennpm run check:packagegreenJEV_SMOKE=1 npm run smoke:vercel) — needs an AI Gateway key, not run yetKnown behavioral differences (gateway vs direct)
providerMetadata.typesafe.confidence; derived fallback may differ from TypeSafe-native confidence → threshold-gated policies (e.g.check-rules≥ 0.6) can park differently if metadata is absent.response.modelis the gateway-reported id; usage may be absent → reported as 0.