Repository navigation
Add Cloudflare Workers AI as a third Jev provider - #2
Conversation
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.
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
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5268dede6c
ℹ️ 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".
| } finally { | ||
| clearTimeout(timer); | ||
| external?.removeEventListener("abort", forward); |
There was a problem hiding this comment.
Keep the timeout active while consuming the response body
In CloudflareJevProvider.ask, fetch() resolves once response headers arrive, so clearing the timer and removing the external abort listener here leaves the subsequent response.text() outside both cancellation mechanisms. If Cloudflare or an intermediary sends headers and then stalls the body, the request can hang indefinitely despite timeoutMs, and aborting the workflow no longer stops it; cleanup should occur only after readCloudflareResponse(response) completes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 9935f5d. The timeout timer and the external-abort listener now stay armed until the response body is fully consumed: fetch + readCloudflareResponse (response.text()) run inside one try/finally whose cleanup only runs after the read settles. Regression tests: stalled-body timeout aborts the read within timeoutMs (and does not hang), stalled-body external abort rejects immediately.
| const apiToken = (env.JEV_CLOUDFLARE_API_TOKEN ?? env.CLOUDFLARE_API_TOKEN)?.trim(); | ||
| if (!apiToken) { |
There was a problem hiding this comment.
Fall back to the canonical token when the alias is blank
When JEV_CLOUDFLARE_API_TOKEN exists but contains only whitespace, nullish coalescing selects it and the factory reports missing credentials even if CLOUDFLARE_API_TOKEN contains a valid token. This also disagrees with checkEnvironment, which treats the blank alias as absent and allows the smoke test to proceed, only for adapter construction to fail; trim and test the alias before falling back to the canonical variable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 9935f5d. Token resolution moved to resolveCloudflareToken: the alias must carry a non-blank trimmed value to win; a whitespace-only JEV_CLOUDFLARE_API_TOKEN falls back to the canonical CLOUDFLARE_API_TOKEN, matching checkEnvironment semantics. Regression test asserts the canonical token is sent when the alias is blank.
| this.baseURL = options.baseURL ?? CLOUDFLARE_API_BASE_URL; | ||
| this.model = options.model ?? CLOUDFLARE_MODEL; | ||
| this.fetchFn = options.fetchFn ?? ((input, init) => fetch(input, init)); | ||
| this.credentialSecrets = options.credentialSecrets ?? []; |
There was a problem hiding this comment.
Register the constructor's API token for redaction
When consumers use the exported CloudflareJevProvider constructor directly, credentialSecrets defaults to an empty list even though the provider already has options.apiToken. Passing that provider to createWorkflowDependencies therefore leaves the token unknown to message and artifact redaction; if Cloudflare reflects the token in an error diagnostic, as the new error test itself simulates, it can be persisted in frames.ndjson. Include the API token by default rather than relying on the factory to duplicate it into credentialSecrets.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 9935f5d. The constructor now registers options.apiToken in credentialSecrets by default (same >=8-char rule as the factory), so directly-constructed providers scrub their token through the two-argument createWorkflowDependencies too; an explicit credentialSecrets override still wins. Regression test asserts redaction end-to-end for a direct constructor call.
| JEV_PROVIDER: "cloudflare", | ||
| CLOUDFLARE_ACCOUNT_ID: "acc", | ||
| CLOUDFLARE_API_TOKEN: "cftoken1234567890", | ||
| CLOUDFLARE_BASE_URL: `http://127.0.0.1:${port}`, |
There was a problem hiding this comment.
Route the CLI test to the local server
This test sets CLOUDFLARE_BASE_URL, but repo-wide inspection shows that variable is never read: createCloudflareAdapter only honors its explicit options.baseURL argument. Consequently the supposedly local, mocked CLI test sends requests to the real https://api.cloudflare.com endpoint, making the suite network-dependent and potentially adding multiple request timeouts and retries in offline CI while the local server remains unused.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 9935f5d. createCloudflareAdapter now honors CLOUDFLARE_BASE_URL (new env override, options.baseURL still wins), so the factory the CLI uses routes to the local mock server. The test now also asserts the local server actually received requests, proving no traffic to api.cloudflare.com.
| const connectionFailure = | ||
| /fetch failed|network|connection/.test(name.toLowerCase()) || | ||
| /econnrefused|enotfound|eai_again|econnreset|epipe/.test(message) || | ||
| /econnrefused|enotfound|eai_again|econnreset|epipe/.test(causeMessage); |
There was a problem hiding this comment.
Classify response-body socket failures as transient
If the connection closes after headers but before response.text() finishes, Node's fetch rejects with TypeError: terminated and an Undici cause such as SocketError: other side closed with code UND_ERR_SOCKET. None of these values match the current connection regexes, so classifyCloudflareError returns unknown and the executor skips its transient retries for a genuine network interruption; inspect the cause code/name or recognize this body-read failure shape.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 9935f5d. classifyCloudflareError now recognizes the body-read failure shape: TypeError: terminated with an Undici cause whose name is SocketError or whose code is UND_ERR_SOCKET classifies as transient (plus terminated in the name-based connection regex). Regression tests cover all three cause shapes.
- 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.
Round 1 findings — all five addressed in 9935f5d
Suite 186/186 green ( |
|
@codex review |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
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.
|
Live smoke update: credentials were available, so |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 924066b255
ℹ️ 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".
| if (status === 402 || /insufficient balance|add money|byok/i.test(message)) { | ||
| return "auth"; |
There was a problem hiding this comment.
Keep billing failures out of the auth path
When Cloudflare returns a 402 for insufficient balance, classifying it as auth enters the executor's auth branch, which discards the original billing diagnostic and reports only authentication failed. The credentials may be completely valid, and rejected is already terminal without retries, so classify this as a rejection (or preserve a distinct billing failure) to show users that they need to add funds or configure BYOK.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0ce5e68 — 402/billing failures now classify as rejected (terminal, no retries) instead of auth, so the executor no longer discards the billing diagnostic: the run fails with the original Cloudflare message (error 2021: Insufficient balance; add money … or use BYOK). Verified: full npm run check gate — 186/186 tests, build, 14/14 smoke cases.
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.
|
Round 2 summary (1 finding → 1 fix)
Evidence: Sibling check: Vercel + OpenAI classifiers have no 402/billing path (no twin). @codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0ce5e68862
ℹ️ 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".
| `cloudflare returned a non-JSON body (HTTP ${response.status})`, | ||
| ); | ||
| } | ||
| if (!response.ok || (body as { success?: unknown }).success === false) { |
There was a problem hiding this comment.
Treat a JSON null response as an invalid envelope
When Cloudflare or an intermediary returns HTTP 200 with the valid JSON body null, this property access throws a TypeError before jevPayloadOf can return null. The executor consequently classifies the failure as unknown and skips the invalid-response retries that other malformed successful payloads receive; guard the parsed body before reading success/result so this case reaches the empty-envelope path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in aa46ea9 — the .success/.result reads are null-safe now: a literal JSON null body falls through to jevPayloadOf → empty envelope → the executor invalid-response retry path, instead of throwing a TypeError classified unknown. Regression test: "a literal JSON null body resolves to the empty-envelope retry path".
| // response BODY is consumed: fetch() resolves on headers alone, so a | ||
| // stalled body would otherwise hang past timeoutMs and ignore aborts. | ||
| const response = await this.fetchFn( | ||
| `${this.baseURL}/accounts/${encodeURIComponent(this.accountId)}/ai/run`, |
There was a problem hiding this comment.
Normalize a trailing slash in the Cloudflare base URL
When options.baseURL or CLOUDFLARE_BASE_URL uses the common trailing-slash form (for example, https://proxy.example/), this interpolation produces a request path beginning with //accounts/.... URL handling preserves that extra slash, and route-sensitive proxies or local servers can return 404 instead of forwarding the request, so normalize trailing slashes before appending the endpoint path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in aa46ea9 — the constructor strips trailing slashes from the resolved base URL (replace(/\\/+$/, "")), so https://proxy.example/ produces https://proxy.example/accounts/…/ai/run. Regression test asserts the exact request URL.
| if (status === 413 || /too large|payload|context length|exceeds the limit/.test(message)) { | ||
| return "too_large"; |
There was a problem hiding this comment.
Restrict oversized-input matching to size-specific errors
For any Cloudflare error whose message merely contains payload—for example, HTTP 400 invalid payload—this branch classifies the request as too_large before the generic 4xx handling. That misreports schema or validation failures as size problems, and the find workflow may recursively split and resend the same invalid request; likewise, a non-size limit message can match exceeds the limit. Keep these textual checks specific to payload/context size (or rely on status 413) so ordinary rejections and rate limits retain their correct behavior.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in aa46ea9 — message matching is now size-specific (payload too large, payload exceeds, exceeds the input|context|request|token|size|payload limit, request/input too large); bare payload and exceeds the limit no longer match, so invalid payload (400) and non-size limit messages classify as rejected. Twin fixed in the jev.ts and vercel-jev.ts classifiers which shared the same bare-payload pattern. 4 classification regression rows added.
- 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).
|
Round 3 summary (3 findings → 3 fixes + 2 twins)
Evidence: @codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: aa46ea9f3b
ℹ️ 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".
| if (status === 413 || /max_tokens_exceeded|too large|payload too large|context length/.test(message)) | ||
| return "too_large"; |
There was a problem hiding this comment.
Preserve payload-exceeds size classification
Recognize size-specific forms such as payload exceeds the maximum allowed size before falling through to the generic 4xx rejection path. After narrowing this regex, a TypeSafe HTTP 400 with that wording is classified as rejected rather than too_large, so find will not invoke its recursive splitting path; the same incomplete narrowing is present in classifyVercelError, while the new Cloudflare classifier already handles payload exceeds explicitly.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 102eb4e. classifyError and classifyVercelError now match "payload exceeds …" wording before the generic 4xx branch, so an HTTP 400 size rejection stays too_large and keeps the splitting path. Regression rows for both classifiers.
| typeof (value as { state?: unknown }).state === "string" && | ||
| "result" in value |
There was a problem hiding this comment.
Detect state envelopes before requiring a result
Treat an object with a string state as an execution-state envelope even when it lacks an inner result. Failed or still-running executions can have the shape {state: "Failed", errors: [...]} without a model result; the current "result" in value requirement makes such responses look like malformed Jev payloads, causing invalid-response retries and hiding the provider state instead of taking the intended provider-error path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 102eb4e. isExecutionState no longer requires an inner result: {state:"Failed", errors:[…]} without a model result now takes the provider-error path (surface the state) instead of being treated as a malformed Jev payload. Regression test covers the result-less state envelope.
- 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).
What
JEV_PROVIDER=cloudflareroutes Jev through Cloudflare's native AI REST run endpoint usingCLOUDFLARE_ACCOUNT_ID+CLOUDFLARE_API_TOKEN. The review engine stays provider-independent; TypeSafe and Vercel behavior is unchanged.Implementation
CloudflareJevProvider(src/adapters/cloudflare-jev.ts) behind the existingJevPort; directfetch, no SDK dependencyPOST https://api.cloudflare.com/client/v4/accounts/{accountId}/ai/run,Authorization: Bearer+ JSON body{model, input: {state, questions}}— verified against current Cloudflare docs (modeltypesafe/jev) and the jkudish/jev-browser referencenoul→booleantranslation (unlike Vercel); probabilities, confidence, and score legends pass throughresult.state+result.result); a non-completed execution state is a provider error, never an empty answer setretries: 2classifyCloudflareError: 401/403→auth, 408/429/5xx/connection/DNS→transient, 413/too-large→too_large, AbortError/timeout→aborted, other 4xx→rejected, rest unknown. Classifier travels with the portjev-1.13.0,jev-latest) never forwarded; onlytypesafe/-qualified slugs pass;JEV_CLOUDFLARE_MODELoverrides the alias (defaulttypesafe/jev)--max-input-tokenskeeps workingcredentialSecrets(port-level redaction) andenvSecrets(CLOUDFLARE_API_TOKEN+JEV_CLOUDFLARE_API_TOKEN, alias wins when both set); account id not treated as a secretnpm run smoke:cloudflare: one minimal live evaluation (noul + choice), gated onJEV_SMOKE=1+ account id + token, skips with exit 0 otherwise, not part ofnpm run check. No live run performed — no credentials available on this host.npm run lintfailed on merged main)Validation
npm run checkgreen at HEAD5268ded: lint ✓ typecheck ✓ 181/181 tests (142 before, 39 new) build ✓ smoke ✓. Working tree clean. All network mocked or local HTTP server; no live credentials needed in the suite.