diff --git a/README.md b/README.md index b92a845..4898f7d 100644 --- a/README.md +++ b/README.md @@ -35,8 +35,9 @@ A common agent flow asks jev-code to find relevant files before editing, check c it into small, size-limited pieces, such as one changed block of a file or one failure from a log. 3. **Exact checks run first.** Plain rules catch things like an added `test.skip`, deleted assertions, deleted test files, and lockfile, CI or config changes. -4. **Jev answers fixed-choice questions about each piece.** Using your Jev credential (TypeSafe API key, or - an AI Gateway key with `JEV_PROVIDER=vercel`), jev-code asks +4. **Jev answers fixed-choice questions about each piece.** Using your Jev credential (TypeSafe API key, + an AI Gateway key with `JEV_PROVIDER=vercel`, or Cloudflare account id + API token with + `JEV_PROVIDER=cloudflare`), jev-code asks [TypeSafe Jev](https://typesafe.ai), a model that answers multiple-choice questions, about one small piece at a time. For example: "How closely is this changed block related to the task?" jev-code's own code, not the model, turns the answers into flags using fixed thresholds. @@ -68,8 +69,10 @@ After 0.1.0 is released: `npm install --global jev-code`. ```sh export TYPESAFE_API_KEY="" # default provider (or see Jev providers - # for the Vercel AI Gateway alternative) + # for the Vercel/Cloudflare alternatives) export AI_GATEWAY_API_KEY="" # JEV_PROVIDER=vercel +export CLOUDFLARE_ACCOUNT_ID="" # JEV_PROVIDER=cloudflare +export CLOUDFLARE_API_TOKEN="" # JEV_PROVIDER=cloudflare ``` **Example.** An agent was asked to fix a crash. It did, but it also skipped the test and removed an assertion. @@ -175,7 +178,7 @@ There is no `pass` or `approved` result. Run `jev-code --help` for exit-code mea By default, run records are saved under `.jev-code/runs//`. They can contain code and log lines, so they are private to your user and ignored by Git. Use `--no-persist` to disable them. -jev-code first sends TypeSafe the redacted request, input shape, diff presence, available capabilities and option names for routing. The selected workflow then sends only the task and bounded evidence it needs, such as changed blocks or short failure-log sections. Obvious secret files and common token formats are filtered on a best-effort basis, but jev-code is not a secret scanner. With the default provider, requests go to TypeSafe; with `JEV_PROVIDER=vercel`, requests additionally pass through the Vercel AI Gateway, which processes them even under zero-data-retention routing. Review both the gateway's and the upstream provider's data terms before sending private or regulated code. +jev-code first sends TypeSafe the redacted request, input shape, diff presence, available capabilities and option names for routing. The selected workflow then sends only the task and bounded evidence it needs, such as changed blocks or short failure-log sections. Obvious secret files and common token formats are filtered on a best-effort basis, but jev-code is not a secret scanner. With the default provider, requests go to TypeSafe; with `JEV_PROVIDER=vercel`, requests additionally pass through the Vercel AI Gateway, which processes them even under zero-data-retention routing; with `JEV_PROVIDER=cloudflare`, requests additionally pass through Cloudflare infrastructure. Review the gateway's or Cloudflare's and the upstream provider's data terms before sending private or regulated code. jev-code does not replace tests, type checks, linters, security tools, or human review. @@ -194,15 +197,18 @@ npm run check:package # package manifest and file-list checks used by the rele `npm run smoke:real` makes a few real TypeSafe Jev requests after `npm run build`; it skips itself without `TYPESAFE_API_KEY`. `npm run smoke:vercel` performs one minimal real Jev evaluation through -the Vercel AI Gateway; it requires `JEV_SMOKE=1` and `AI_GATEWAY_API_KEY` and skips itself otherwise, -so neither live test is part of `npm run check`. See [docs/architecture.md](docs/architecture.md) for how the code is organized and +the Vercel AI Gateway; it requires `JEV_SMOKE=1` and `AI_GATEWAY_API_KEY` and skips itself otherwise. +`npm run smoke:cloudflare` performs one minimal real Jev evaluation through Cloudflare Workers AI; +it requires `JEV_SMOKE=1`, `CLOUDFLARE_ACCOUNT_ID`, and a Cloudflare API token +(`CLOUDFLARE_API_TOKEN` or `JEV_CLOUDFLARE_API_TOKEN`) and skips itself otherwise, so no live test +is part of `npm run check`. See [docs/architecture.md](docs/architecture.md) for how the code is organized and [docs/RELEASING.md](docs/RELEASING.md) for how releases are published. ## Jev providers -Jev inference is pluggable. Both providers expose the same Jev/System One capability to the review +Jev inference is pluggable. All providers expose the same Jev/System One capability to the review engine through the same request/response schema, so workflows and reports are provider-independent. -The providers are different services, though: when the gateway does not report TypeSafe's separate +The providers are different services, though: when a proxy does not report TypeSafe's separate confidence statistic, confidence is synthesized from the distribution and threshold-gated decisions can differ from TypeSafe-direct (see below). Selection is entirely through configuration, at start: @@ -218,6 +224,21 @@ export JEV_PROVIDER=vercel # Vercel AI Gateway hosting of Jev export AI_GATEWAY_API_KEY="" # canonical variable read by the ai package ``` +or + +```sh +export JEV_PROVIDER=cloudflare # Cloudflare Workers AI hosting of Jev +export CLOUDFLARE_ACCOUNT_ID="" +export CLOUDFLARE_API_TOKEN="" +# JEV_CLOUDFLARE_API_TOKEN may be used as an application-specific alias for the +# token; when both are set, the alias wins. + +jev-code \ + "Check the current changes against the user's task" \ + --task-file task.md \ + --json +``` + An invalid `JEV_PROVIDER` name fails immediately at startup (exit 64), not halfway through a review. **Model selection.** `--model` / `TYPESAFE_MODEL` select the TypeSafe-direct model for the default @@ -225,24 +246,33 @@ provider. The Vercel provider runs in the gateway's model namespace: TypeSafe-di (`jev-1.13.0`) are a different namespace and are never forwarded — an unqualified id falls back to the configured gateway model, and a slash-qualified gateway id (`typesafe-ai/jev-preview`) is honored. The gateway model itself is configured with `JEV_GATEWAY_MODEL` (default `typesafe-ai/jev`, -the canonical Jev id on the Vercel AI Gateway). +the canonical Jev id on the Vercel AI Gateway). The Cloudflare provider likewise runs in Cloudflare's +own model namespace, which currently exposes Jev through the always-current alias `typesafe/jev` +rather than TypeSafe's pinned versions: unqualified ids are never forwarded, and only +`typesafe/`-qualified ids pass through. The alias is configurable with `JEV_CLOUDFLARE_MODEL` +(default `typesafe/jev`). **Zero data retention.** Evaluations can contain repository source code and diffs, so the Vercel provider routes only to providers with zero data retention agreements (`providerOptions.gateway.zeroDataRetention = true`) by default. Set -`JEV_GATEWAY_ZERO_DATA_RETENTION=0` only for troubleshooting. +`JEV_GATEWAY_ZERO_DATA_RETENTION=0` only for troubleshooting. The Cloudflare provider has no +equivalent routing flag: requests pass through Cloudflare infrastructure, and jev-code makes no +data-retention claim for that path — review Cloudflare's and TypeSafe's data/privacy terms before +sending private source code. Differences worth knowing: -- TypeSafe's separate per-question confidence statistic is preserved from the gateway response - (`providerMetadata.typesafe.confidence`, Choice/Score questions). When that metadata is genuinely - unavailable, the provider falls back to a value derived from the reported distribution (the mass - 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. +- TypeSafe's separate per-question confidence statistic is preserved from gateway responses + (`providerMetadata.typesafe.confidence`, Choice/Score questions) and from Cloudflare's native Jev + answers (`confidence`). When that statistic is genuinely unavailable, the provider falls back to a + value derived from the reported distribution (the mass 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, input usage is reported as a conservative - estimate of the request size (the same estimate the input-token budget reserves), and output usage - as zero. + Cloudflare speaks Jev's native contract, so unlike Vercel it needs no boolean translation. +- Usage numbers come from the gateway or from Cloudflare; when they are omitted, input usage is + reported as a conservative estimate of the request size (the same estimate the input-token budget + reserves), and output usage as zero. ## TypeSafe diff --git a/docs/architecture.md b/docs/architecture.md index 0f855a4..20ad7ca 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -17,7 +17,7 @@ higher folder supplies the implementation. `test/architecture.test.ts` scans eve | ----------- | ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | `core` | Send structured questions to Jev safely: validate answers, enforce budgets, batch, retry | npm packages, `fs`, `child_process`, the SDK; only `node:` built-ins | | `workflows` | Product logic: gather evidence, run exact checks, ask questions, turn answers into a report | any package or Node built-in, `process.env`, the SDK | -| `adapters` | Real implementations of the ports: read-only Git, file reads, parsers, redaction, Jev providers (TypeSafe SDK, Vercel AI Gateway) | the `cli` folder | +| `adapters` | Real implementations of the ports: read-only Git, file reads, parsers, redaction, Jev providers (TypeSafe SDK, Vercel AI Gateway, Cloudflare Workers AI) | the `cli` folder | | `cli` | Parse arguments, wire adapters into workflows, print output, choose the exit code | nothing | `src/cli.ts` (the `jev-code` binary) and `src/index.ts` (package exports) belong to `cli`. Every other @@ -28,9 +28,11 @@ production file must live in one of the four folders. Tests and scripts may impo Using `check` as the example: 1. **cli** parses the natural-language request and flags, reads `JEV_PROVIDER`, `TYPESAFE_API_KEY`, - `AI_GATEWAY_API_KEY` and `TYPESAFE_MODEL` through `adapters/config.ts`, and builds the dependencies + `AI_GATEWAY_API_KEY`, `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_API_TOKEN` and `TYPESAFE_MODEL` + through `adapters/config.ts`, and builds the dependencies in `adapters/dependencies.ts`. The provider factory selects `TypeSafeJevProvider` (direct API, - default) or `VercelJevProvider` (Vercel AI Gateway); unknown provider names fail at startup. + default), `VercelJevProvider` (Vercel AI Gateway), or `CloudflareJevProvider` (Cloudflare Workers + AI REST run endpoint); unknown provider names fail at startup. 2. **routing** (`cli/router.ts`) receives the redacted request plus deterministic context: diff presence, input shape, available capabilities, and supplied option names. One validated choice selects `find`, `check`, `triage_failures`, `triage_comments`, or `cannot_tell`. Fixed confidence and capability gates turn diff --git a/package.json b/package.json index 848bd8e..2adfc14 100644 --- a/package.json +++ b/package.json @@ -51,6 +51,7 @@ "smoke": "node scripts/smoke-cli.ts", "smoke:real": "node scripts/smoke-real.ts", "smoke:vercel": "node scripts/smoke-vercel.ts", + "smoke:cloudflare": "node scripts/smoke-cloudflare.ts", "check": "npm run lint && npm run typecheck && npm test && npm run build && npm run smoke", "check:package": "npm run build && node scripts/release.ts manifest && node scripts/release.ts pack --dry-run" }, diff --git a/scripts/smoke-cloudflare.ts b/scripts/smoke-cloudflare.ts new file mode 100644 index 0000000..0004781 --- /dev/null +++ b/scripts/smoke-cloudflare.ts @@ -0,0 +1,48 @@ +/** + * Optional live smoke test against Jev through Cloudflare Workers AI. Requires + * JEV_SMOKE=1, CLOUDFLARE_ACCOUNT_ID, and a Cloudflare API token + * (CLOUDFLARE_API_TOKEN or JEV_CLOUDFLARE_API_TOKEN) in the environment and + * performs one minimal real evaluation. Skips cleanly without credentials, so + * it never becomes required for normal CI. + */ +import { CLOUDFLARE_MODEL, createCloudflareAdapter } from "../src/adapters/cloudflare-jev.ts"; +import { checkEnvironment } from "./smoke-env.ts"; + +const env = process.env; +const verdict = checkEnvironment(env, { provider: "cloudflare" }); +if (verdict.skip) { + console.log(`smoke:cloudflare skipped: ${verdict.skip}`); + process.exit(0); +} + +const adapter = createCloudflareAdapter(env); +const started = Date.now(); +const response = (await adapter.ask( + { + state: { change: "renamed variable base to amount in price()" }, + questions: { + renamed: { type: "noul", instructions: "Does the change rename a variable?" }, + severity: { + type: "choice", + instructions: "How severe is this change?", + criteria: { cosmetic: "rename only", behavioral: "changes behavior" }, + }, + }, + model: CLOUDFLARE_MODEL, + }, + { timeoutMs: 30_000 }, +)) as { + model: string; + answers: Record>; + usage: { input_tokens: number; output_tokens: number }; +}; + +const answers = response.answers; +if (!answers.renamed || !answers.severity) throw new Error("smoke:cloudflare: missing answers"); +console.log( + `smoke:cloudflare ok: model=${response.model} renamed=${(answers.renamed as { noul: number }).noul} ` + + `severity=${(answers.severity as { choice: string }).choice} ` + + `confidence=${(answers.severity as { confidence: number }).confidence} ` + + `tokens=${response.usage.input_tokens}/${response.usage.output_tokens} ` + + `latencyMs=${Date.now() - started}`, +); diff --git a/scripts/smoke-env.ts b/scripts/smoke-env.ts index 5a216c7..2cf53ec 100644 --- a/scripts/smoke-env.ts +++ b/scripts/smoke-env.ts @@ -1,24 +1,40 @@ -/** Shared skip logic for live smoke scripts. */ +/** + * Shared skip logic for live smoke scripts. + */ export interface SkipVerdict { skip: string | null; } +export type SmokeProvider = "typesafe" | "vercel" | "cloudflare"; + +/** The credential variable each provider's live smoke needs. */ +const PROVIDER_KEYS: Record = { + typesafe: { names: ["TYPESAFE_API_KEY"], label: "TYPESAFE_API_KEY" }, + vercel: { names: ["AI_GATEWAY_API_KEY"], label: "AI_GATEWAY_API_KEY" }, + cloudflare: { + names: ["JEV_CLOUDFLARE_API_TOKEN", "CLOUDFLARE_API_TOKEN"], + label: "CLOUDFLARE_API_TOKEN", + extra: ["CLOUDFLARE_ACCOUNT_ID"], + }, +}; + /** * Decide whether a live smoke test should run: it must be explicitly requested - * and the matching credential must be present. Returns the skip reason or null. + * and the matching credential(s) must be present. Returns the skip reason or null. */ -export function checkEnvironment( - env: NodeJS.ProcessEnv, - options: { provider: "typesafe" | "vercel" }, -): SkipVerdict { +export function checkEnvironment(env: NodeJS.ProcessEnv, options: { provider: SmokeProvider }): SkipVerdict { if (!/^(?:1|true|yes)$/i.test(env.JEV_SMOKE ?? "")) { return { skip: "set JEV_SMOKE=1 to run live smoke tests" }; } - const key = options.provider === "vercel" ? env.AI_GATEWAY_API_KEY?.trim() : env.TYPESAFE_API_KEY?.trim(); + const needs = PROVIDER_KEYS[options.provider]; + const key = needs.names.some((name) => env[name]?.trim()); if (!key) { - return { - skip: `${options.provider === "vercel" ? "AI_GATEWAY_API_KEY" : "TYPESAFE_API_KEY"} is not set`, - }; + return { skip: `${needs.label} is not set` }; + } + for (const extra of needs.extra ?? []) { + if (!env[extra]?.trim()) { + return { skip: `${extra} is not set` }; + } } return { skip: null }; } diff --git a/src/adapters/cloudflare-jev.ts b/src/adapters/cloudflare-jev.ts new file mode 100644 index 0000000..274c666 --- /dev/null +++ b/src/adapters/cloudflare-jev.ts @@ -0,0 +1,632 @@ +import { estimateTokens } from "../core/budget.ts"; +import type { Questions } from "../core/questions.ts"; +import type { JevCallOptions, JevPort, JevRequest, TransportFailure } from "../core/types.ts"; +import { MissingCredentialError } from "./jev.ts"; + +export { MissingCredentialError }; + +/** + * Canonical Jev model alias on Cloudflare Workers AI. Cloudflare runs its own + * model namespace and currently exposes one always-current Jev alias instead + * of TypeSafe's pinned versions, so TypeSafe-direct ids (`jev-1.13.0`, + * `jev-latest`) are never forwarded. + */ +export const CLOUDFLARE_MODEL = "typesafe/jev"; + +/** Environment override for the Cloudflare Jev model alias. */ +export const CLOUDFLARE_MODEL_ENV = "JEV_CLOUDFLARE_MODEL"; + +/** Default Cloudflare API base URL. */ +export const CLOUDFLARE_API_BASE_URL = "https://api.cloudflare.com/client/v4"; + +/** Cloudflare Jev answers use Jev's native contract (noul/choice/score). */ +export type CloudflareAnswer = + | { type: "noul"; noul: number } + | { + type: "choice"; + choice: string; + confidence?: number; + probabilities?: Record; + } + | { + type: "score"; + score: number; + confidence?: number; + legend?: Record; + probabilities?: Record; + }; + +/** + * The slice of `fetch` the provider needs; injectable for tests and for + * pointing the adapter at a local server. + */ +export type FetchFn = (input: string, init: RequestInit) => Promise; + +export interface CloudflareJevProviderOptions { + accountId: string; + apiToken: string; + /** Cloudflare API base URL override (without the /accounts path). */ + baseURL?: string; + /** Cloudflare Jev model alias; TypeSafe-direct request models never override it. */ + model?: string; + /** fetch override for tests. */ + fetchFn?: FetchFn; + /** Credential values used by this port; consumed by dependency redaction. */ + credentialSecrets?: string[]; +} + +/** + * Cloudflare's v4 REST envelope error: HTTP status plus short safe Cloudflare + * diagnostics. Classified by status; the message carries no credentials and + * only bounded Cloudflare error text. + */ +export class CloudflareStatusError extends Error { + readonly status: number; + constructor(status: number, message: string) { + super(message); + this.name = "CloudflareStatusError"; + this.status = status; + } +} + +/** + * Cloudflare Workers AI Jev provider: one Jev port backed by the Cloudflare + * REST run endpoint (`POST /accounts/{id}/ai/run`). Cloudflare speaks Jev's + * native noul/choice/score contract, so questions pass through unchanged and + * answers need only structural validation — no translation to gateway shapes. + * Nothing here reads the process environment. + */ +export class CloudflareJevProvider implements JevPort { + /** This port's error classifier, so callers can pair port and classifier. */ + readonly classifyError: (error: unknown) => TransportFailure = classifyCloudflareError; + + /** Credential values used by this port; consumed by dependency redaction. */ + readonly credentialSecrets: string[]; + + private readonly accountId: string; + private readonly apiToken: string; + private readonly baseURL: string; + private readonly model: string; + private readonly fetchFn: FetchFn; + + constructor(options: CloudflareJevProviderOptions) { + this.accountId = options.accountId; + this.apiToken = options.apiToken; + // Strip trailing slashes so `https://proxy.example/` does not produce a + // `//accounts/...` path, which route-sensitive proxies 404 instead of + // forwarding. + this.baseURL = (options.baseURL ?? CLOUDFLARE_API_BASE_URL).replace(/\/+$/, ""); + this.model = options.model ?? CLOUDFLARE_MODEL; + this.fetchFn = options.fetchFn ?? ((input, init) => fetch(input, init)); + // The port owns its credentials even when constructed directly (not via + // the factory), so redaction never depends on env visibility. + this.credentialSecrets = + options.credentialSecrets ?? (options.apiToken.trim().length >= 8 ? [options.apiToken.trim()] : []); + } + + async ask(request: JevRequest, options: JevCallOptions): Promise { + if (options.signal?.aborted) throw aborted(options.signal.reason); + // The REST run endpoint has no timeout parameter; enforce the executor's + // timeout by aborting the shared signal, which surfaces as an AbortError + // fetch rejection carrying the TimeoutError reason. + const controller = new AbortController(); + const timer = setTimeout( + () => + controller.abort( + new DOMException(`cloudflare run timed out after ${options.timeoutMs}ms`, "TimeoutError"), + ), + options.timeoutMs, + ); + const external = options.signal; + const forward = () => controller.abort(aborted(external?.reason)); + external?.addEventListener("abort", forward, { once: true }); + const cloudflareModel = cloudflareModelFor(request.model, this.model); + let payload: JevPayload | null; + try { + // The timer and the external-abort forwarding must stay armed until the + // 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`, + { + method: "POST", + headers: { + Authorization: `Bearer ${this.apiToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + model: cloudflareModel, + input: { state: request.state, questions: request.questions }, + }), + signal: controller.signal, + }, + ); + // Read and classify transport-level failures (HTTP errors, non-JSON + // body, failed execution state). These throw so the executor + // classifies them. + payload = await readCloudflareResponse(response); + } finally { + clearTimeout(timer); + external?.removeEventListener("abort", forward); + } + // Malformed Jev payloads must NOT throw out of port.ask(): a rejection + // lands in the executor's transport-error block (classified unknown, never + // retried). An empty answer map lets readEnvelope accept the envelope and + // the frame parser reject it as a ValidationError — the invalid-response + // path, which retries. + if (payload === null) return emptyEnvelope(cloudflareModel, request); + let answers: Record = {}; + try { + answers = translateAnswers(request.questions, payload.answers); + } catch { + // Deliberately answered by the empty map above. + } + return { + model: modelOf(payload, cloudflareModel), + answers, + usage: { + // A missing usage report must not zero out the budgeted input estimate + // (Budget.settle would subtract it), or --max-input-tokens stops + // guarding anything. Report the same deterministic estimate the + // executor reserved so the counter keeps advancing conservatively. + input_tokens: payload.usage?.input_tokens ?? estimateTokens(request), + output_tokens: payload.usage?.output_tokens ?? 0, + }, + }; + } +} + +/** The unwrapped Jev payload shape expected inside a Cloudflare result. */ +interface JevPayload { + model?: unknown; + answers?: Record; + usage?: { input_tokens?: unknown; output_tokens?: unknown }; +} + +function emptyEnvelope(model: string, request: JevRequest): unknown { + return { + model, + answers: {}, + usage: { input_tokens: estimateTokens(request), output_tokens: 0 }, + }; +} + +/** + * Read and unwrap a Cloudflare REST response. The v4 envelope wraps results as + * `{success, errors, messages, result}`; for Jev runs Cloudflare may also wrap + * the model output in an execution-state envelope (`result.state` + + * `result.result`). Returns the Jev payload object, or null when the result + * does not look like a Jev response. HTTP errors, `success:false` envelopes, + * and non-completed execution states throw CloudflareStatusError — a failed + * execution must never masquerade as an empty answer set. + */ +async function readCloudflareResponse(response: Response): Promise { + const bodyText = await response.text(); + let body: unknown; + try { + body = bodyText.length > 0 ? JSON.parse(bodyText) : {}; + } catch { + throw new CloudflareStatusError( + response.status, + `cloudflare returned a non-JSON body (HTTP ${response.status})`, + ); + } + // A JSON body of literal null must not throw on the `.success` read below: + // it is a malformed *successful* payload (like a missing-answers payload), + // so it falls through to jevPayloadOf → empty envelope → the executor's + // invalid-response retry path instead of a raw TypeError classified unknown. + if (!response.ok || (body as { success?: unknown } | null)?.success === false) { + throw new CloudflareStatusError( + response.status, + `cloudflare run failed (HTTP ${response.status}): ${cloudflareDiagnostics(body)}`, + ); + } + // A null body has no `result` field to read either — guard the access so it + // flows into jevPayloadOf (null) → empty envelope below. + const outer = body === null ? undefined : (body as { result?: unknown }).result; + // Execution-state envelope: {state, result}. Completed runs unwrap to the + // inner result; any other state is a provider error. + let candidate: unknown = outer; + if (isExecutionState(outer)) { + const state = outer.state; + if (state !== "Completed" && state !== "Succeeded") { + throw new CloudflareStatusError( + response.status, + `cloudflare run state is "${state}": ${cloudflareDiagnostics(body)}`, + ); + } + candidate = outer.result; + } + // Some responses carry the Jev payload directly as `result`; others only as + // the whole body (no envelope fields). Accept both. + const jev = jevPayloadOf(candidate) ?? jevPayloadOf(body); + return jev; +} + +/** + * Detect the Cloudflare execution-state envelope around a model result. + * The inner `result` is optional: failed or still-running executions can be + * `{state: "Failed", errors: [...]}` with no model result at all — those must + * take the provider-error path, not look like a malformed Jev payload. + */ +function isExecutionState(value: unknown): value is { state: string; result?: unknown } { + return ( + typeof value === "object" && + value !== null && + !Array.isArray(value) && + typeof (value as { state?: unknown }).state === "string" + ); +} + +/** The Jev payload of an unwrapped result, or null when it is not one. */ +function jevPayloadOf(value: unknown): JevPayload | null { + if (typeof value !== "object" || value === null || Array.isArray(value)) return null; + const answers = (value as { answers?: unknown }).answers; + if (typeof answers !== "object" || answers === null || Array.isArray(answers)) return null; + return value as JevPayload; +} + +/** + * The effective model for the normalized envelope: the Jev payload's own model + * id when Cloudflare reports one (e.g. the pinned version behind the alias), + * else the alias actually called. + */ +function modelOf(payload: JevPayload, called: string): string { + const model = payload.model; + return typeof model === "string" && model.length > 0 ? model : called; +} + +/** Short, safe Cloudflare error diagnostics from a v4 envelope. */ +function cloudflareDiagnostics(body: unknown): string { + const errors = (body as { errors?: unknown })?.errors; + if (!Array.isArray(errors) || errors.length === 0) return "no diagnostics"; + return errors + .slice(0, 3) + .map((entry: unknown) => { + if (typeof entry === "string") return entry.slice(0, 120); + if (typeof entry === "object" && entry !== null) { + const { code, message } = entry as { code?: unknown; message?: unknown }; + const codePart = typeof code === "number" ? ` ${code}` : ""; + const messagePart = typeof message === "string" ? `: ${message.slice(0, 160)}` : ""; + return `error${codePart}${messagePart}`; + } + return "error"; + }) + .join("; ") + .slice(0, 300); +} + +/** + * The model for one request. Cloudflare's namespace is separate from TypeSafe + * direct: unqualified ids (`jev-1.13.0`, `jev-latest`) are TypeSafe-direct ids + * and are never forwarded — they select the configured Cloudflare alias. Only + * `typesafe/`-qualified ids are Cloudflare catalog slugs and pass through. + */ +export function cloudflareModelFor(requested: string, configured: string): string { + return requested.startsWith("typesafe/") ? requested : configured; +} + +/** + * Validate native Cloudflare Jev answers into the answer shape the review + * engine validates. Cloudflare speaks Jev's native contract (unlike Vercel's + * boolean translation), so this only enforces the structural rules the frame + * validators rely on: own-property key checks, exact canonical score level + * keys, valid probabilities, and distributions readChoice/readScore accept. + * Optional fields (probabilities, confidence, legend) get conservative + * fallbacks so a sparse-but-valid answer is not burned as invalid. + */ +export function translateAnswers( + questions: Questions, + answers: Record | undefined, +): Record { + if (typeof answers !== "object" || answers === null || Array.isArray(answers)) { + throw new Error("cloudflare returned no answers object"); + } + // Own-property check: prototype names like "constructor" must count as + // unexpected answers, not as questions inherited through Object.prototype. + const unexpected = Object.keys(answers).filter((name) => !Object.hasOwn(questions, name)); + if (unexpected.length > 0) { + throw new Error(`cloudflare returned unexpected answers: ${unexpected.join(", ")}`); + } + const out: Record = {}; + for (const [name, question] of Object.entries(questions)) { + const answer = answers[name]; + if (!answer || typeof answer !== "object" || Array.isArray(answer)) { + throw new Error(`cloudflare returned no answer for question "${name}"`); + } + const record = answer as Record; + if (question.type === "noul") { + if (record.type !== "noul") throw new Error(`answer "${name}" is not a noul answer`); + out[name] = { type: "noul", noul: probabilityField(record.noul, `${name}.noul`) }; + } else if (question.type === "choice") { + if (record.type !== "choice") throw new Error(`answer "${name}" is not a choice answer`); + out[name] = choiceAnswer(question, record, name); + } else { + if (record.type !== "score") throw new Error(`answer "${name}" is not a score answer`); + out[name] = scoreAnswer(question, record, name); + } + } + return out; +} + +function choiceAnswer( + question: Extract, + record: Record, + name: string, +): { type: "choice"; choice: string; confidence: number; probabilities: Record } { + const labels = Object.keys(question.criteria); + const choice = record.choice; + if (typeof choice !== "string" || !labels.includes(choice)) { + throw new Error(`answer "${name}" reports a choice outside the question's labels`); + } + const probabilities = choiceDistribution(record.probabilities, labels, choice, name); + const confidence = confidenceOf(record, name) ?? probabilities[choice] ?? 0; + return { type: "choice", choice, confidence, probabilities }; +} + +/** + * The reported choice distribution, or a point mass on the selected choice + * when Cloudflare omits probabilities — an all-zero map would be rejected by + * readChoice (sum 0) and burn every retry on a valid answer. + */ +function choiceDistribution( + reported: unknown, + labels: readonly string[], + choice: string, + name: string, +): Record { + if (reported === undefined || reported === null) { + return Object.fromEntries(labels.map((label) => [label, label === choice ? 1 : 0])); + } + return distribution(reported, labels, name, "choices"); +} + +function scoreAnswer( + question: Extract, + record: Record, + name: string, +): { + type: "score"; + score: number; + confidence: number; + legend: Record; + probabilities: Record; +} { + const levelCount = question.criteria.length; + const score = record.score; + if (typeof score !== "number" || !Number.isFinite(score)) { + throw new Error(`answer "${name}" reports an invalid score`); + } + if (score < -1e-6 || score > levelCount - 1 + 1e-6) { + throw new Error(`answer "${name}" reports an out-of-range score: ${score}`); + } + const labels = Array.from({ length: levelCount }, (_, index) => String(index)); + const probabilities = scoreDistribution(record.probabilities, labels, score, name); + const confidence = confidenceOf(record, name) ?? Math.max(...Object.values(probabilities)); + const legend = legendOf(record.legend, levelCount, name); + return { type: "score", score, confidence, legend, probabilities }; +} + +/** + * The reported score distribution, or a synthesized one consistent with the + * reported score when Cloudflare omits probabilities: a point mass for + * integral scores, linear interpolation between adjacent levels for + * fractional ones (readScore accepts fractional scores like 1.2 and expects + * an interpolated distribution). + */ +function scoreDistribution( + reported: unknown, + labels: readonly string[], + score: number, + name: string, +): Record { + if (reported === undefined || reported === null) { + const lower = Math.floor(score); + const frac = score - lower; + return Object.fromEntries( + labels.map((label, index) => { + if (index === lower) return [label, Number((1 - frac).toFixed(4))]; + if (index === lower + 1) return [label, Number(frac.toFixed(4))]; + return [label, 0]; + }), + ); + } + return distribution(reported, labels, name, "score levels"); +} + +/** + * Validate a reported distribution. Exact canonical keys only: + * Number("1.5")/Number("01")/Number("1e0") coercion would let noncanonical + * level keys slip into range and get silently dropped. + */ +function distribution( + reported: unknown, + labels: readonly string[], + name: string, + kind: string, +): Record { + if (typeof reported !== "object" || reported === null || Array.isArray(reported)) { + throw new Error(`answer "${name}" carries malformed probabilities`); + } + const extra = Object.keys(reported).filter((key) => !labels.includes(key)); + if (extra.length > 0) { + throw new Error(`answer "${name}" carries probabilities for unknown ${kind}: ${extra.join(", ")}`); + } + const out: Record = {}; + for (const label of labels) { + out[label] = probabilityField( + (reported as Record)[label], + `${name}.probabilities.${label}`, + ); + } + return out; +} + +/** A probability in [0, 1], or undefined when the field is genuinely absent. */ +function confidenceOf(record: Record, name: string): number | undefined { + const value = record.confidence; + if (value === undefined || value === null) return undefined; + return probabilityField(value, `${name}.confidence`); +} + +function probabilityField(value: unknown, name: string): number { + if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) { + throw new Error(`${name} must be a number within [0, 1]`); + } + return value; +} + +/** The score legend keyed by canonical level keys; absent means empty. */ +function legendOf(legend: unknown, levelCount: number, name: string): Record { + if (legend === undefined || legend === null) return {}; + if (typeof legend !== "object" || Array.isArray(legend)) { + throw new Error(`answer "${name}" carries a malformed legend`); + } + const canonical = Array.from({ length: levelCount }, (_, index) => String(index)); + const out: Record = {}; + for (const [key, value] of Object.entries(legend as Record)) { + if (!canonical.includes(key) || typeof value !== "string") { + throw new Error(`answer "${name}" carries an invalid legend entry: ${key}`); + } + out[key] = value; + } + return out; +} + +/** The cloudflare adapter environment read by createCloudflareAdapter. */ +export interface CloudflareAdapterEnv { + CLOUDFLARE_ACCOUNT_ID?: string | undefined; + CLOUDFLARE_API_TOKEN?: string | undefined; + JEV_CLOUDFLARE_API_TOKEN?: string | undefined; + JEV_CLOUDFLARE_MODEL?: string | undefined; + CLOUDFLARE_BASE_URL?: string | undefined; +} + +/** + * The Cloudflare API token: the application-specific alias + * `JEV_CLOUDFLARE_API_TOKEN` wins, but only when it carries a non-blank + * value — a whitespace-only alias falls back to the canonical + * `CLOUDFLARE_API_TOKEN` instead of shadowing it. + */ +export function resolveCloudflareToken(env: CloudflareAdapterEnv): string | undefined { + const alias = env.JEV_CLOUDFLARE_API_TOKEN?.trim(); + if (alias) return alias; + return env.CLOUDFLARE_API_TOKEN?.trim() || undefined; +} + +/** Environment override for the Cloudflare API base URL (e.g. a proxy). */ +export const CLOUDFLARE_BASE_URL_ENV = "CLOUDFLARE_BASE_URL"; + +/** + * Build the Cloudflare-backed Jev port. The account id and API token are read + * only from the given environment; `JEV_CLOUDFLARE_API_TOKEN` is an + * application-specific alias that wins over the canonical + * `CLOUDFLARE_API_TOKEN` when both are set. `CLOUDFLARE_BASE_URL` overrides + * the API base URL for every caller of the factory, including the CLI. + */ +export function createCloudflareAdapter( + env: CloudflareAdapterEnv | NodeJS.ProcessEnv = process.env, + options: { baseURL?: string; fetchFn?: FetchFn } = {}, +): JevPort { + const accountId = env.CLOUDFLARE_ACCOUNT_ID?.trim(); + if (!accountId) { + throw new MissingCredentialError( + "CLOUDFLARE_ACCOUNT_ID is required; set it in the process environment before running jev-code with JEV_PROVIDER=cloudflare", + ); + } + const apiToken = resolveCloudflareToken(env); + if (!apiToken) { + throw new MissingCredentialError( + "CLOUDFLARE_API_TOKEN is required; set it in the process environment before running jev-code with JEV_PROVIDER=cloudflare", + ); + } + const model = env[CLOUDFLARE_MODEL_ENV]?.trim() || CLOUDFLARE_MODEL; + const baseURL = options.baseURL ?? env[CLOUDFLARE_BASE_URL_ENV]?.trim(); + return new CloudflareJevProvider({ + accountId, + apiToken, + model, + ...(baseURL ? { baseURL } : {}), + ...(options.fetchFn ? { fetchFn: options.fetchFn } : {}), + credentialSecrets: apiToken.trim().length >= 8 ? [apiToken.trim()] : [], + }); +} + +/** + * An abort-typed error for any caller-supplied reason. Plain Error reasons + * would surface as unknown transport failures instead of "aborted". + */ +function aborted(reason: unknown): unknown { + if (reason instanceof Error && /abort/i.test(reason.name)) return reason; + const detail = + reason instanceof Error ? reason.message : reason === undefined ? "run aborted" : String(reason); + return new DOMException(detail, "AbortError"); +} + +/** Map Cloudflare REST and network errors onto transport failure classes. */ +export function classifyCloudflareError(error: unknown): TransportFailure { + const value = typeof error === "object" && error !== null ? (error as Record) : {}; + const status = typeof value.status === "number" ? value.status : null; + const name = typeof value.name === "string" ? value.name : ""; + const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase(); + if (name === "AbortError" || name === "APIUserAbortError") return "aborted"; + if ( + status === 401 || + status === 403 || + /authentication|permissiondenied/i.test(name) || + /invalid api key|unauthenticated|authentication error|authentication failed/i.test(message) + ) { + return "auth"; + } + // Cloudflare 402 error 2021 (insufficient balance / add money or use BYOK): + // a definite account-state rejection, not transient — retrying cannot fix it. + // Classify as rejected (terminal, no retries) rather than auth: the + // credentials may be perfectly valid, and the rejected path preserves the + // billing diagnostic so users see they need to add funds or configure BYOK. + if (status === 402 || /insufficient balance|add money|byok/i.test(message)) { + return "rejected"; + } + if ( + status === 413 || + /too large|payload too large|payload size|payload exceeds|request too large|context length|input too large|exceeds the (payload|input|context|request|token|size) limit/.test( + message, + ) + ) { + return "too_large"; + } + const cause = value.cause; + const causeMessage = + typeof cause === "object" && cause !== null && "message" in cause + ? String((cause as { message: unknown }).message).toLowerCase() + : ""; + const causeCode = + typeof cause === "object" && cause !== null && "code" in cause + ? String((cause as { code: unknown }).code) + : ""; + const causeName = + typeof cause === "object" && cause !== null && "name" in cause + ? String((cause as { name: unknown }).name) + : ""; + // Plain connection failures (TypeError: fetch failed with ECONNREFUSED etc. + // on `cause`) must retry like other transient transport problems. Body-read + // socket failures reject as `TypeError: terminated` with an Undici cause + // (SocketError / UND_ERR_SOCKET) after headers already arrived. + const connectionFailure = + /fetch failed|network|connection|terminated/.test(name.toLowerCase()) || + /econnrefused|enotfound|eai_again|econnreset|epipe/.test(message) || + /econnrefused|enotfound|eai_again|econnreset|epipe/.test(causeMessage) || + causeCode === "UND_ERR_SOCKET" || + causeName === "SocketError"; + if ( + status === 408 || + status === 429 || + (status !== null && status >= 500) || + /timeout|ratelimit/i.test(name) || + /econnreset|etimedout|socket hang up|rate limit|fetch failed|timed out/.test(message) || + connectionFailure + ) { + return "transient"; + } + if (status !== null && status >= 400) return "rejected"; + return "unknown"; +} diff --git a/src/adapters/config.ts b/src/adapters/config.ts index 23d5f94..f2b868d 100644 --- a/src/adapters/config.ts +++ b/src/adapters/config.ts @@ -1,11 +1,12 @@ import type { JevPort, TransportFailure } from "../core/types.ts"; +import { classifyCloudflareError, createCloudflareAdapter } from "./cloudflare-jev.ts"; import { classifyError, createSdkAdapter } from "./jev.ts"; import { classifyVercelError, createVercelAdapter } from "./vercel-jev.ts"; export const MODEL_ENV = "TYPESAFE_MODEL"; export const PROVIDER_ENV = "JEV_PROVIDER"; export const DEFAULT_PROVIDER = "typesafe"; -export const PROVIDER_NAMES = ["typesafe", "vercel"] as const; +export const PROVIDER_NAMES = ["typesafe", "vercel", "cloudflare"] as const; export type ProviderName = (typeof PROVIDER_NAMES)[number]; export class InvalidProviderError extends Error { @@ -36,6 +37,7 @@ export function configuredProvider(env: NodeJS.ProcessEnv): ProviderName { /** Create the configured Jev provider. */ export function createJevProvider(name: ProviderName, env: NodeJS.ProcessEnv): JevPort { if (name === "vercel") return createVercelAdapter(env); + if (name === "cloudflare") return createCloudflareAdapter(env); return createSdkAdapter(env); } @@ -47,5 +49,6 @@ export function jevFromEnvironment(env: NodeJS.ProcessEnv): JevPort { /** The error classifier of the selected provider. */ export function classifierFor(name: ProviderName): (error: unknown) => TransportFailure { if (name === "vercel") return classifyVercelError; + if (name === "cloudflare") return classifyCloudflareError; return classifyError; } diff --git a/src/adapters/dependencies.ts b/src/adapters/dependencies.ts index fd8fecb..813fefc 100644 --- a/src/adapters/dependencies.ts +++ b/src/adapters/dependencies.ts @@ -4,7 +4,6 @@ import type { JevPort, TransportFailure } from "../core/types.ts"; import type { ArtifactStore, EvidenceParser, - RedactionPort, WorkflowDependencies, WorkspaceSource, } from "../workflows/ports.ts"; @@ -15,7 +14,7 @@ import { classifyError } from "./jev.ts"; import { parseFailureLog } from "./logs.ts"; import { readLines, resolveWorkspacePath } from "./paths.ts"; import { Recorder } from "./recorder.ts"; -import { createRedaction, redactJson, redactText, safeMessage } from "./redact.ts"; +import { createRedaction } from "./redact.ts"; import { parseTestRecords } from "./test-records.ts"; /** Read-only git and filesystem inputs confined to `root`. */ diff --git a/src/adapters/jev.ts b/src/adapters/jev.ts index d53a509..b9a6463 100644 --- a/src/adapters/jev.ts +++ b/src/adapters/jev.ts @@ -72,7 +72,10 @@ export function classifyError(error: unknown): TransportFailure { const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase(); if (name === "APIUserAbortError" || name === "AbortError") return "aborted"; if (status === 401 || status === 403 || /authentication|permissiondenied/i.test(name)) return "auth"; - if (status === 413 || /max_tokens_exceeded|too large|payload|context length/.test(message)) + if ( + status === 413 || + /max_tokens_exceeded|too large|payload too large|payload exceeds|context length/.test(message) + ) return "too_large"; if ( status === 408 || diff --git a/src/adapters/redact.ts b/src/adapters/redact.ts index fc6697e..b0d9547 100644 --- a/src/adapters/redact.ts +++ b/src/adapters/redact.ts @@ -96,7 +96,13 @@ export function redactJson( /** Credential values present in this process that must never leave it. */ export function envSecrets(env: NodeJS.ProcessEnv = process.env): string[] { const values: string[] = []; - for (const name of ["TYPESAFE_API_KEY", "AI_GATEWAY_API_KEY", "COPILOT_MCP_TYPESAFE_API_KEY"]) { + for (const name of [ + "TYPESAFE_API_KEY", + "AI_GATEWAY_API_KEY", + "CLOUDFLARE_API_TOKEN", + "JEV_CLOUDFLARE_API_TOKEN", + "COPILOT_MCP_TYPESAFE_API_KEY", + ]) { const value = env[name]; if (value && value.trim().length >= 8) values.push(value.trim()); } diff --git a/src/adapters/vercel-jev.ts b/src/adapters/vercel-jev.ts index 608483c..60d6a7b 100644 --- a/src/adapters/vercel-jev.ts +++ b/src/adapters/vercel-jev.ts @@ -363,7 +363,10 @@ export function classifyVercelError(error: unknown): TransportFailure { ) { return "auth"; } - if (status === 413 || /max_tokens_exceeded|too large|payload|context length/.test(message)) + if ( + status === 413 || + /max_tokens_exceeded|too large|payload too large|payload exceeds|context length/.test(message) + ) return "too_large"; const cause = value.cause; const causeMessage = diff --git a/src/cli.ts b/src/cli.ts index f273963..4b35557 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -2,20 +2,12 @@ import { readFileSync, realpathSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { parseArgs } from "node:util"; -import { - configuredModel, - configuredProvider, - InvalidProviderError, - jevFromEnvironment, - MODEL_ENV, - PROVIDER_ENV, -} from "./adapters/config.ts"; +import { configuredModel, InvalidProviderError, jevFromEnvironment, MODEL_ENV } from "./adapters/config.ts"; import { createWorkflowDependencies } from "./adapters/dependencies.ts"; import { GitError, repoRoot } from "./adapters/git.ts"; -import { classifyError, MissingCredentialError } from "./adapters/jev.ts"; +import { MissingCredentialError } from "./adapters/jev.ts"; import { readStdin, readWorkspaceFile } from "./adapters/paths.ts"; import { safeMessage } from "./adapters/redact.ts"; -import { classifyVercelError } from "./adapters/vercel-jev.ts"; import { EXIT, exitCodeFor, renderHuman } from "./cli/output.ts"; import { WORKFLOWS, type WorkflowDefinition } from "./cli/registry.ts"; import { type InputShape, routeIntent, type WorkflowName } from "./cli/router.ts"; @@ -183,8 +175,10 @@ Exit codes: 0 complete; 10 incomplete coverage; 12 budget exhausted; 64 usage or clarification; 65 invalid input; 70 internal error Results are advisory. jev-code never edits code, runs tests, posts comments, or approves work. Every report lists what was not checked. "No flags" is not an approval. -Jev provider: JEV_PROVIDER=typesafe (default, needs TYPESAFE_API_KEY) or - JEV_PROVIDER=vercel (Vercel AI Gateway, needs AI_GATEWAY_API_KEY). +Jev provider: JEV_PROVIDER=typesafe (default, needs TYPESAFE_API_KEY), + JEV_PROVIDER=vercel (Vercel AI Gateway, needs AI_GATEWAY_API_KEY), or + JEV_PROVIDER=cloudflare (Cloudflare Workers AI, needs CLOUDFLARE_ACCOUNT_ID + and CLOUDFLARE_API_TOKEN). `; } diff --git a/src/index.ts b/src/index.ts index 41bf3fa..d557206 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,11 @@ // Public package API. This module is the top of the dependency graph; no production module imports it. +export { + CLOUDFLARE_MODEL, + CloudflareJevProvider, + classifyCloudflareError, + createCloudflareAdapter, +} from "./adapters/cloudflare-jev.ts"; // adapters: port implementations for a local workspace and the TypeSafe SDK export { parseComments } from "./adapters/comments.ts"; export { diff --git a/test/cloudflare.test.ts b/test/cloudflare.test.ts new file mode 100644 index 0000000..19b4db2 --- /dev/null +++ b/test/cloudflare.test.ts @@ -0,0 +1,1093 @@ +/** + * Cloudflare provider tests: selection, REST request shape, response + * normalization, model semantics, error mapping, redaction, abort/timeout. + * All network calls are mocked or served from a local HTTP server. + */ +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { Readable } from "node:stream"; +import { describe, test } from "node:test"; +import { + CLOUDFLARE_MODEL, + CloudflareJevProvider, + CloudflareStatusError, + classifyCloudflareError, + createCloudflareAdapter, +} from "../src/adapters/cloudflare-jev.ts"; +import { + classifierFor, + configuredProvider, + createJevProvider, + InvalidProviderError, + jevFromEnvironment, +} from "../src/adapters/config.ts"; +import { createWorkflowDependencies } from "../src/adapters/dependencies.ts"; +import { createRedaction } from "../src/adapters/redact.ts"; +import { estimateTokens } from "../src/core/budget.ts"; +import { FrameExecutor } from "../src/core/executor.ts"; +import type { JevPort, JevRequest, TransportFailure } from "../src/core/types.ts"; +import { expectKeys, readEnvelope, readNoul } from "../src/core/validation.ts"; + +const CALL_OPTIONS = { timeoutMs: 30_000 }; + +/** A well-formed Jev payload as Cloudflare's result. */ +function jevResult(overrides: Record = {}): Record { + return { + model: "jev-1.13.0", + answers: { + n: { type: "noul", noul: 0.9 }, + c: { type: "choice", choice: "yes", confidence: 0.8, probabilities: { yes: 0.8, no: 0.2 } }, + s: { + type: "score", + score: 1.2, + confidence: 0.94, + legend: { 0: "low", 1: "mid", 2: "high" }, + probabilities: { 0: 0.1, 1: 0.7, 2: 0.2 }, + }, + }, + usage: { input_tokens: 426, output_tokens: 73 }, + ...overrides, + }; +} + +function fullQuestions(): JevRequest["questions"] { + return { + n: { type: "noul", instructions: "Noul?" }, + c: { type: "choice", instructions: "Pick", criteria: { yes: "affirm", no: "deny" } }, + s: { type: "score", instructions: "Rank", criteria: ["low", "mid", "high"] }, + }; +} + +function fullRequest(): JevRequest { + return { state: { hunk: "code" }, questions: fullQuestions(), model: "jev-1.13.0" }; +} + +/** Wrap a Jev payload in the plain v4 envelope. */ +function envelope(result: unknown, extra: Record = {}): Record { + return { success: true, errors: [], messages: [], result, ...extra }; +} + +/** Wrap a Jev payload in the execution-state double envelope. */ +function executionEnvelope(payload: unknown, state = "Completed"): Record { + return envelope({ state, result: payload }); +} + +/** fetch replacement that returns a canned JSON response. */ +function respondWith( + status: number, + body: unknown, +): { + fetchFn: (input: string, init: RequestInit) => Promise; + seen: Array<{ url: string; init: RequestInit }>; +} { + const seen: Array<{ url: string; init: RequestInit }> = []; + return { + seen, + fetchFn: (input, init) => { + seen.push({ url: input, init }); + return Promise.resolve( + new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }), + ); + }, + }; +} + +function providerWith(status: number, body: unknown) { + const transport = respondWith(status, body); + const provider = new CloudflareJevProvider({ + accountId: "acc123", + apiToken: "cftoken1234567890", + fetchFn: transport.fetchFn, + }); + return { provider, seen: transport.seen }; +} + +describe("cloudflare provider selection", () => { + test("accepts the cloudflare name; invalid names still fail; default stays typesafe", () => { + assert.equal(configuredProvider({}), "typesafe"); + assert.equal(configuredProvider({ JEV_PROVIDER: "cloudflare" }), "cloudflare"); + assert.throws(() => configuredProvider({ JEV_PROVIDER: "openrouter" }), InvalidProviderError); + assert.throws( + () => configuredProvider({ JEV_PROVIDER: "Cloudflare" }), + /JEV_PROVIDER must be one of typesafe, vercel, cloudflare/, + ); + }); + + test("factory builds cloudflare from account id + token; both are required", () => { + const env = { CLOUDFLARE_ACCOUNT_ID: "acc", CLOUDFLARE_API_TOKEN: "cftoken1234567890" }; + assert.ok(createJevProvider("cloudflare", env) instanceof CloudflareJevProvider); + assert.throws( + () => createJevProvider("cloudflare", { CLOUDFLARE_API_TOKEN: "cftoken1234567890" }), + /CLOUDFLARE_ACCOUNT_ID is required/, + ); + assert.throws( + () => createJevProvider("cloudflare", { CLOUDFLARE_ACCOUNT_ID: "acc" }), + /CLOUDFLARE_API_TOKEN is required/, + ); + assert.ok(jevFromEnvironment({ JEV_PROVIDER: "cloudflare", ...env }) instanceof CloudflareJevProvider); + }); + + test("the token alias JEV_CLOUDFLARE_API_TOKEN wins over CLOUDFLARE_API_TOKEN", async () => { + const seen: string[] = []; + const fetchFn = (input: string, init: RequestInit) => { + seen.push(String((init.headers as Record).Authorization)); + return Promise.resolve(new Response(JSON.stringify(envelope(jevResult())), { status: 200 })); + }; + const adapter = createCloudflareAdapter( + { + CLOUDFLARE_ACCOUNT_ID: "acc", + CLOUDFLARE_API_TOKEN: "canonical-token-9876543210", + JEV_CLOUDFLARE_API_TOKEN: "alias-token-1234567890", + }, + { fetchFn }, + ); + await adapter.ask( + { state: {}, questions: { n: { type: "noul", instructions: "?" } }, model: "m" }, + CALL_OPTIONS, + ); + assert.deepEqual(seen, ["Bearer alias-token-1234567890"]); + }); + + test("a whitespace-only alias falls back to the canonical token", async () => { + const seen: string[] = []; + const fetchFn = (input: string, init: RequestInit) => { + seen.push(String((init.headers as Record).Authorization)); + return Promise.resolve(new Response(JSON.stringify(envelope(jevResult())), { status: 200 })); + }; + const adapter = createCloudflareAdapter( + { + CLOUDFLARE_ACCOUNT_ID: "acc", + CLOUDFLARE_API_TOKEN: "canonical-token-9876543210", + JEV_CLOUDFLARE_API_TOKEN: " ", + }, + { fetchFn }, + ); + await adapter.ask( + { state: {}, questions: { n: { type: "noul", instructions: "?" } }, model: "m" }, + CALL_OPTIONS, + ); + assert.deepEqual(seen, ["Bearer canonical-token-9876543210"]); + }); + + test("classifierFor maps cloudflare to its classifier", () => { + assert.equal(classifierFor("cloudflare"), classifyCloudflareError); + }); +}); + +describe("cloudflare request shape", () => { + test("sends the native Jev questions and a bearer token to the run endpoint", async () => { + const { provider, seen } = providerWith(200, envelope(jevResult())); + const response = (await provider.ask(fullRequest(), CALL_OPTIONS)) as Record; + assert.equal(seen.length, 1); + assert.equal(seen[0]!.url, "https://api.cloudflare.com/client/v4/accounts/acc123/ai/run"); + const init = seen[0]!.init; + assert.equal(init.method, "POST"); + const headers = init.headers as Record; + assert.equal(headers.Authorization, "Bearer cftoken1234567890"); + assert.equal(headers["Content-Type"], "application/json"); + assert.deepEqual(JSON.parse(String(init.body)), { + model: CLOUDFLARE_MODEL, + input: { state: fullRequest().state, questions: fullQuestions() }, + }); + // The envelope model is the Jev payload's own model, not the alias. + assert.equal(response.model, "jev-1.13.0"); + const answers = response.answers as Record>; + assert.equal((answers.n as { noul: number }).noul, 0.9); + assert.equal((answers.c as { choice: string }).choice, "yes"); + assert.equal((answers.c as { confidence: number }).confidence, 0.8); + assert.deepEqual((answers.c as { probabilities: Record }).probabilities, { + yes: 0.8, + no: 0.2, + }); + assert.equal((answers.s as { score: number }).score, 1.2); + assert.equal((answers.s as { confidence: number }).confidence, 0.94); + assert.deepEqual((answers.s as { legend: Record }).legend, { + 0: "low", + 1: "mid", + 2: "high", + }); + assert.deepEqual((answers.s as { probabilities: Record }).probabilities, { + 0: 0.1, + 1: 0.7, + 2: 0.2, + }); + assert.deepEqual(response.usage, { input_tokens: 426, output_tokens: 73 }); + }); + + test("questions pass through unchanged (noul stays noul, no boolean translation)", async () => { + const { provider, seen } = providerWith(200, envelope(jevResult())); + await provider.ask(fullRequest(), CALL_OPTIONS); + const body = JSON.parse(String(seen[0]!.init.body)) as { + input: { questions: Record }; + }; + assert.equal(body.input.questions.n?.type, "noul"); + assert.equal(body.input.questions.c?.type, "choice"); + assert.equal(body.input.questions.s?.type, "score"); + }); + + test("the adapter factory drives the real transport (local HTTP server)", async () => { + const token = "cft_local_server_token_42"; + const received: Array<{ + auth: string | undefined; + contentType: string | undefined; + url: string; + body: unknown; + }> = []; + const server = createServer((req, res) => { + let data = ""; + req.on("data", (chunk: string) => (data += chunk)); + req.on("end", () => { + received.push({ + auth: req.headers.authorization, + contentType: req.headers["content-type"], + url: req.url ?? "", + body: JSON.parse(data), + }); + res.writeHead(200, { "content-type": "application/json" }); + res.end( + JSON.stringify( + envelope( + jevResult({ + answers: { + n: { type: "noul", noul: 0.9 }, + c: { type: "choice", choice: "yes", confidence: 0.8, probabilities: { yes: 0.8, no: 0.2 } }, + }, + }), + ), + ), + ); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const port = (server.address() as { port: number }).port; + try { + const adapter = createCloudflareAdapter( + { CLOUDFLARE_ACCOUNT_ID: "acc123", CLOUDFLARE_API_TOKEN: token }, + { baseURL: `http://127.0.0.1:${port}` }, + ); + const response = (await adapter.ask( + { + state: { change: "rename" }, + questions: { + n: { type: "noul", instructions: "Renamed?" }, + c: { type: "choice", instructions: "Severity?", criteria: { yes: "y", no: "n" } }, + }, + model: CLOUDFLARE_MODEL, + }, + { timeoutMs: 5_000 }, + )) as Record; + assert.equal(received.length, 1); + assert.equal(received[0]!.auth, `Bearer ${token}`); + assert.equal(received[0]!.contentType, "application/json"); + assert.equal(received[0]!.url, "/accounts/acc123/ai/run"); + assert.deepEqual(received[0]!.body, { + model: "typesafe/jev", + input: { + state: { change: "rename" }, + questions: { + n: { type: "noul", instructions: "Renamed?" }, + c: { type: "choice", instructions: "Severity?", criteria: { yes: "y", no: "n" } }, + }, + }, + }); + const answers = response.answers as Record; + assert.ok(answers.n && answers.c); + } finally { + server.close(); + } + }); +}); + +describe("cloudflare model semantics", () => { + test("TypeSafe-direct ids never reach Cloudflare; typesafe/-qualified ids pass through", async () => { + const seen: string[] = []; + const fetchFn = (input: string, init: RequestInit) => { + seen.push((JSON.parse(String(init.body)) as { model: string }).model); + return Promise.resolve(new Response(JSON.stringify(envelope(jevResult())), { status: 200 })); + }; + const provider = new CloudflareJevProvider({ accountId: "a", apiToken: "t1234567890", fetchFn }); + await provider.ask( + { state: {}, questions: { n: { type: "noul", instructions: "?" } }, model: "jev-1.13.0" }, + CALL_OPTIONS, + ); + await provider.ask( + { state: {}, questions: { n: { type: "noul", instructions: "?" } }, model: "jev-latest" }, + CALL_OPTIONS, + ); + await provider.ask( + { state: {}, questions: { n: { type: "noul", instructions: "?" } }, model: "typesafe/jev" }, + CALL_OPTIONS, + ); + await provider.ask( + { state: {}, questions: { n: { type: "noul", instructions: "?" } }, model: "typesafe/jev-preview" }, + CALL_OPTIONS, + ); + assert.deepEqual(seen, [CLOUDFLARE_MODEL, CLOUDFLARE_MODEL, "typesafe/jev", "typesafe/jev-preview"]); + }); + + test("JEV_CLOUDFLARE_MODEL overrides the alias; the called model is reported when the payload omits one", async () => { + const env = { + CLOUDFLARE_ACCOUNT_ID: "acc", + CLOUDFLARE_API_TOKEN: "cftoken1234567890", + JEV_CLOUDFLARE_MODEL: "typesafe/jev-preview", + }; + const seen: string[] = []; + const fetchFn = (input: string, init: RequestInit) => { + seen.push((JSON.parse(String(init.body)) as { model: string }).model); + return Promise.resolve( + new Response(JSON.stringify(envelope(jevResult({ model: undefined }))), { status: 200 }), + ); + }; + const adapter = createCloudflareAdapter(env, { fetchFn }); + const response = (await adapter.ask( + { state: {}, questions: { n: { type: "noul", instructions: "?" } }, model: "jev-1.13.0" }, + CALL_OPTIONS, + )) as { model: string }; + assert.deepEqual(seen, ["typesafe/jev-preview"]); + // The payload had no model; the envelope reports the alias actually called. + assert.equal(response.model, "typesafe/jev-preview"); + }); +}); + +describe("cloudflare response parsing", () => { + test("normal v4 envelope result is the Jev payload", async () => { + const { provider } = providerWith(200, envelope(jevResult())); + const response = (await provider.ask(fullRequest(), CALL_OPTIONS)) as { + answers: Record; + }; + assert.deepEqual(Object.keys(response.answers).sort(), ["c", "n", "s"]); + }); + + test("nested result.result (execution-state envelope) unwraps", async () => { + const { provider } = providerWith(200, executionEnvelope(jevResult())); + const response = (await provider.ask(fullRequest(), CALL_OPTIONS)) as { + answers: Record; + usage: Record; + }; + assert.deepEqual(Object.keys(response.answers).sort(), ["c", "n", "s"]); + assert.equal(response.usage.input_tokens, 426); + }); + + test("a Jev payload returned directly as the body (no envelope) is accepted", async () => { + const { provider } = providerWith(200, jevResult()); + const response = (await provider.ask(fullRequest(), CALL_OPTIONS)) as { + answers: Record; + }; + assert.deepEqual(Object.keys(response.answers).sort(), ["c", "n", "s"]); + }); + + test("success:false fails with a provider error", async () => { + const { provider } = providerWith(401, { + success: false, + errors: [{ code: 1000, message: "Authentication error" }], + }); + await assert.rejects(provider.ask(fullRequest(), CALL_OPTIONS), (error: unknown) => { + assert.ok(error instanceof CloudflareStatusError); + assert.equal((error as CloudflareStatusError).status, 401); + assert.match((error as Error).message, /Authentication error/); + return true; + }); + }); + + test("a non-completed execution state is a provider error, not an empty answer set", async () => { + for (const state of ["Failed", "Running", "Error"]) { + const { provider } = providerWith(200, executionEnvelope(jevResult(), state)); + await assert.rejects( + provider.ask(fullRequest(), CALL_OPTIONS), + (error: unknown) => { + assert.match((error as Error).message, new RegExp(`run state is "${state}"`)); + return true; + }, + state, + ); + } + }); + + test("a non-completed execution state without an inner result is still a provider error", async () => { + // Failed runs can omit the model result entirely: {state: "Failed", errors: [...]}. + // The state envelope must be detected before the result read, not treated + // as a malformed Jev payload (invalid-response retry hides the provider state). + const { provider } = providerWith(200, envelope({ state: "Failed", errors: [{ message: "boom" }] })); + await assert.rejects(provider.ask(fullRequest(), CALL_OPTIONS), (error: unknown) => { + assert.match((error as Error).message, /run state is "Failed"/); + return true; + }); + }); + + test("missing answers resolve to an invalid envelope for the executor's retry path", async () => { + const { provider } = providerWith(200, envelope({ model: "jev-1.13.0", usage: {} })); + const response = (await provider.ask(fullRequest(), CALL_OPTIONS)) as { + answers: Record; + }; + assert.deepEqual(response.answers, {}); + assert.doesNotThrow(() => readEnvelope(response)); + }); + + test("a literal JSON null body resolves to the empty-envelope retry path, not a TypeError", async () => { + // JSON.parse("null") yields null; reading `.success` off it used to throw + // a raw TypeError (classified "unknown", never retried). It must behave + // like any other malformed successful payload: empty envelope, executor + // retries it as an invalid response. + const { provider } = providerWith(200, null); + const response = (await provider.ask(fullRequest(), CALL_OPTIONS)) as { + answers: Record; + }; + assert.deepEqual(response.answers, {}); + assert.doesNotThrow(() => readEnvelope(response)); + }); + + test("a trailing slash in baseURL does not produce a //accounts request path", async () => { + const transport = respondWith(200, envelope(jevResult())); + const provider = new CloudflareJevProvider({ + accountId: "acc123", + apiToken: "cftoken1234567890", + baseURL: "https://proxy.example/", + fetchFn: transport.fetchFn, + }); + await provider.ask(fullRequest(), CALL_OPTIONS); + const url = transport.seen[0]?.url; + assert.ok(url, "no request was captured"); + assert.equal(url, "https://proxy.example/accounts/acc123/ai/run"); + }); + + test("malformed answer types resolve to the empty-envelope retry path", async () => { + for (const answers of [ + { n: { type: "choice", choice: "x" } }, // wrong type + { n: { type: "noul", noul: "high" } }, // wrong probability type + { n: { type: "noul", noul: 2 } }, // out of range + { n: null }, // missing + { constructor: { type: "noul", noul: 0.5 } }, // prototype-named key + ]) { + const { provider } = providerWith(200, envelope(jevResult({ answers }))); + const response = (await provider.ask( + { state: {}, questions: { n: { type: "noul", instructions: "?" } }, model: "m" }, + CALL_OPTIONS, + )) as { answers: Record }; + assert.deepEqual(response.answers, {}, JSON.stringify(answers)); + } + }); + + test("unexpected answer keys resolve to the empty-envelope retry path", async () => { + const { provider } = providerWith( + 200, + envelope( + jevResult({ answers: { ghost: { type: "noul", noul: 0.5 }, n: { type: "noul", noul: 0.5 } } }), + ), + ); + const response = (await provider.ask( + { state: {}, questions: { n: { type: "noul", instructions: "?" } }, model: "m" }, + CALL_OPTIONS, + )) as { answers: Record }; + assert.deepEqual(response.answers, {}); + }); + + test("end-to-end: the executor retries an empty envelope as invalid responses", async () => { + let attempts = 0; + const port = new CloudflareJevProvider({ + accountId: "a", + apiToken: "t1234567890", + fetchFn: () => { + attempts++; + return Promise.resolve( + new Response(JSON.stringify(envelope({ model: "m", usage: {} })), { status: 200 }), + ); + }, + }); + const frame = { + id: "f", + template: "t@1" as `${string}@${number}`, + scope: "s", + state: {}, + questions: { q: { type: "noul", instructions: "?" } as const }, + provenance: [], + parse(answers: Record) { + expectKeys(answers, ["q"]); + return readNoul(answers, "q"); + }, + }; + const executor = new FrameExecutor({ + port, + model: "m", + budget: { requests: 10, inputTokens: 100_000, wallMs: 60_000 }, + retries: 2, + retryDelayMs: () => 0, + classifyError: classifyCloudflareError, + }); + const outcome = await executor.run(frame); + assert.equal(outcome.ok, false); + assert.equal(outcome.reason, "invalid"); + assert.equal(attempts, 3); + }); + + test("native noul, choice, and score answers keep probabilities and confidence", async () => { + const { provider } = providerWith(200, envelope(jevResult())); + const response = (await provider.ask(fullRequest(), CALL_OPTIONS)) as { + answers: Record>; + }; + assert.deepEqual(response.answers.n, { type: "noul", noul: 0.9 }); + assert.deepEqual(response.answers.c, { + type: "choice", + choice: "yes", + confidence: 0.8, + probabilities: { yes: 0.8, no: 0.2 }, + }); + assert.deepEqual(response.answers.s, { + type: "score", + score: 1.2, + confidence: 0.94, + legend: { 0: "low", 1: "mid", 2: "high" }, + probabilities: { 0: 0.1, 1: 0.7, 2: 0.2 }, + }); + }); + + test("choice answers without probabilities get a point mass on the selection", async () => { + const { provider } = providerWith( + 200, + envelope(jevResult({ answers: { c: { type: "choice", choice: "yes", confidence: 0.7 } } })), + ); + const response = (await provider.ask( + { + state: {}, + questions: { c: { type: "choice", instructions: "?", criteria: { yes: "x", no: "y" } } }, + model: "m", + }, + CALL_OPTIONS, + )) as { answers: Record; confidence: number }> }; + assert.deepEqual(response.answers.c?.probabilities, { yes: 1, no: 0 }); + assert.equal(response.answers.c?.confidence, 0.7); + }); + + test("choice answers without confidence derive it from the distribution", async () => { + const { provider } = providerWith( + 200, + envelope( + jevResult({ + answers: { c: { type: "choice", choice: "yes", probabilities: { yes: 0.75, no: 0.25 } } }, + }), + ), + ); + const response = (await provider.ask( + { + state: {}, + questions: { c: { type: "choice", instructions: "?", criteria: { yes: null, no: null } } }, + model: "m", + }, + CALL_OPTIONS, + )) as { answers: Record }; + assert.equal(response.answers.c?.confidence, 0.75); + }); + + test("score answers without probabilities get an interpolated distribution; fractional scores work", async () => { + const { provider } = providerWith( + 200, + envelope(jevResult({ answers: { s: { type: "score", score: 1.2, confidence: 0.6 } } })), + ); + const response = (await provider.ask( + { + state: {}, + questions: { s: { type: "score", instructions: "?", criteria: ["a", "b", "c"] } }, + model: "m", + }, + CALL_OPTIONS, + )) as { answers: Record; confidence: number }> }; + assert.deepEqual(response.answers.s?.probabilities, { 0: 0, 1: 0.8, 2: 0.2 }); + assert.equal(response.answers.s?.confidence, 0.6); + }); + + test("noncanonical score level keys ('1.5', '01', '1e0') reject into the retry path", async () => { + for (const key of ["1.5", "01", "1e0"]) { + const { provider } = providerWith( + 200, + envelope( + jevResult({ + answers: { s: { type: "score", score: 1, probabilities: { 0: 0.5, 1: 0.5, [key]: 0.9 } } }, + }), + ), + ); + const response = (await provider.ask( + { + state: {}, + questions: { s: { type: "score", instructions: "?", criteria: [null, null] } }, + model: "m", + }, + CALL_OPTIONS, + )) as { answers: Record }; + assert.deepEqual(response.answers, {}, key); + } + }); + + test("out-of-range scores and probabilities reject into the retry path", async () => { + const cases: Array<{ answers: Record; questions: JevRequest["questions"] }> = [ + { + answers: { s: { type: "score", score: 7 } }, + questions: { s: { type: "score", instructions: "?", criteria: [null, null] } }, + }, + { + answers: { s: { type: "score", score: 1, probabilities: { 0: 2, 1: -1 } } }, + questions: { s: { type: "score", instructions: "?", criteria: [null, null] } }, + }, + { + answers: { c: { type: "choice", choice: "ghost", probabilities: { yes: 1, no: 0 } } }, + questions: { c: { type: "choice", instructions: "?", criteria: { yes: null, no: null } } }, + }, + { + answers: { c: { type: "choice", choice: "yes", probabilities: { yes: 0.5, no: 0.5, ghost: 0.2 } } }, + questions: { c: { type: "choice", instructions: "?", criteria: { yes: null, no: null } } }, + }, + ]; + for (const { answers, questions } of cases) { + const { provider } = providerWith(200, envelope(jevResult({ answers }))); + const response = (await provider.ask({ state: {}, questions, model: "m" }, CALL_OPTIONS)) as { + answers: Record; + }; + assert.deepEqual(response.answers, {}, JSON.stringify(answers)); + } + }); + + test("usage is preserved; missing usage falls back to the deterministic input estimate", async () => { + const { provider } = providerWith(200, envelope(jevResult())); + const withUsage = (await provider.ask(fullRequest(), CALL_OPTIONS)) as { usage: Record }; + assert.deepEqual(withUsage.usage, { input_tokens: 426, output_tokens: 73 }); + + const { provider: missing } = providerWith(200, envelope(jevResult({ usage: undefined }))); + const request = { + state: { diff: "x".repeat(300) }, + questions: { n: { type: "noul", instructions: "?" } as const }, + model: "m", + }; + const response = (await missing.ask(request, CALL_OPTIONS)) as { usage: Record }; + assert.equal(response.usage.input_tokens, estimateTokens(request)); + assert.ok(response.usage.input_tokens > 0); + assert.equal(response.usage.output_tokens, 0); + }); +}); + +describe("cloudflare error classification", () => { + function statusError(status: number, message = "boom"): Error { + return new CloudflareStatusError(status, message); + } + + test("maps HTTP statuses onto the shared taxonomy", () => { + const cases: Array<[unknown, TransportFailure]> = [ + [statusError(401, "cloudflare run failed (HTTP 401): error 1000: Authentication error"), "auth"], + [statusError(403, "cloudflare run failed (HTTP 403): error 1000: Forbidden"), "auth"], + [statusError(408, "request timeout"), "transient"], + [statusError(413, "cloudflare run failed (HTTP 413): error 10013: request too large"), "too_large"], + // Bare `payload`/`exceeds the limit` matching must not fire here: schema + // and validation failures (e.g. "invalid payload", HTTP 400) are + // rejections, not size problems — misreporting them as too_large makes + // the find workflow recursively split and resend the same bad request. + [statusError(400, "cloudflare run failed (HTTP 400): error 10001: invalid payload"), "rejected"], + [ + statusError(400, "cloudflare run failed (HTTP 400): error 10001: complexity exceeds the limit"), + "rejected", + ], + // Size-specific phrases still classify as too_large. + [statusError(400, "cloudflare run failed (HTTP 400): error 10013: payload too large"), "too_large"], + [ + statusError(400, "cloudflare run failed (HTTP 400): error 10013: exceeds the input limit"), + "too_large", + ], + [statusError(429, "cloudflare run failed (HTTP 429): error 1400: rate limited"), "transient"], + [statusError(500, "internal error"), "transient"], + [statusError(503, "service unavailable"), "transient"], + [statusError(422, "cloudflare run failed (HTTP 422): error 10001: bad request"), "rejected"], + // Live-observed: Cloudflare 402 error 2021 (insufficient balance). + // rejected (not auth): credentials can be valid while the account is out + // of funds; the rejected path is terminal without retries and preserves + // the billing diagnostic for the user. + [ + statusError( + 402, + "cloudflare run failed (HTTP 402): error 2021: Insufficient balance; add money to your gateway or use BYOK", + ), + "rejected", + ], + [Object.assign(new Error("aborted"), { name: "AbortError" }), "aborted"], + [Object.assign(new Error("cloudflare run timed out after 30ms"), { name: "AbortError" }), "aborted"], + [new Error("mystery"), "unknown"], + ]; + for (const [error, expected] of cases) assert.equal(classifyCloudflareError(error), expected); + }); + + test("connection failures classify as transient", () => { + const failure = new TypeError("fetch failed"); + (failure as unknown as { cause: unknown }).cause = new Error("connect ECONNREFUSED 127.0.0.1:443"); + assert.equal(classifyCloudflareError(failure), "transient"); + const dns = new Error("getaddrinfo EAI_AGAIN api.cloudflare.com"); + assert.equal(classifyCloudflareError(dns), "transient"); + const reset = new TypeError("fetch failed"); + (reset as unknown as { cause: unknown }).cause = new Error("ECONNRESET"); + assert.equal(classifyCloudflareError(reset), "transient"); + }); + + test("body-read socket failures (TypeError: terminated, UND_ERR_SOCKET) classify as transient", () => { + // Undici rejects body reads after headers as "terminated" with a + // SocketError cause carrying code UND_ERR_SOCKET — a genuine network + // interruption that must retry, not classify as unknown. + const terminated = new TypeError("terminated"); + (terminated as unknown as { cause: unknown }).cause = Object.assign(new Error("other side closed"), { + name: "SocketError", + code: "UND_ERR_SOCKET", + }); + assert.equal(classifyCloudflareError(terminated), "transient"); + const socketOnly = new TypeError("terminated"); + (socketOnly as unknown as { cause: unknown }).cause = Object.assign(new Error("socket"), { + code: "UND_ERR_SOCKET", + }); + assert.equal(classifyCloudflareError(socketOnly), "transient"); + const nameOnly = new TypeError("terminated"); + (nameOnly as unknown as { cause: unknown }).cause = Object.assign(new Error("socket"), { + name: "SocketError", + }); + assert.equal(classifyCloudflareError(nameOnly), "transient"); + }); + + test("timeout surfaces as a thrown timeout-typed abort that classifies aborted/transient correctly", async () => { + const provider = new CloudflareJevProvider({ + accountId: "a", + apiToken: "t1234567890", + fetchFn: (input, init) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => { + const reason = (init.signal as AbortSignal).reason; + reject( + reason instanceof Error ? reason : Object.assign(new Error("aborted"), { name: "AbortError" }), + ); + }); + }), + }); + const failure = await provider + .ask( + { state: {}, questions: { n: { type: "noul", instructions: "?" } }, model: "m" }, + { timeoutMs: 30 }, + ) + .then( + () => null, + (error: unknown) => error, + ); + assert.ok(failure instanceof Error); + assert.match(failure.message, /timed out/); + }); + + test("an already-aborted external signal propagates before any HTTP request", async () => { + let requests = 0; + const provider = new CloudflareJevProvider({ + accountId: "a", + apiToken: "t1234567890", + fetchFn: () => { + requests++; + return Promise.resolve(new Response("{}", { status: 200 })); + }, + }); + const controller = new AbortController(); + controller.abort(); + await assert.rejects( + provider.ask( + { state: {}, questions: { n: { type: "noul", instructions: "?" } }, model: "m" }, + { timeoutMs: 5_000, signal: controller.signal }, + ), + ); + assert.equal(requests, 0); + }); + + test("an external abort during the request rejects and classifies as aborted", async () => { + const provider = new CloudflareJevProvider({ + accountId: "a", + apiToken: "t1234567890", + fetchFn: (input, init) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(init.signal?.reason), { once: true }); + }), + }); + const controller = new AbortController(); + const pending = provider.ask( + { state: {}, questions: { n: { type: "noul", instructions: "?" } }, model: "m" }, + { timeoutMs: 5_000, signal: controller.signal }, + ); + controller.abort(new Error("cancelled by caller")); + await assert.rejects(pending, (error: unknown) => { + assert.equal(classifyCloudflareError(error), "aborted"); + return true; + }); + }); + + test("a timeout during a stalled response body aborts the read", async () => { + // fetch resolves on headers; the body never arrives. The timeout must stay + // armed through response.text() or the call hangs past timeoutMs. + const provider = new CloudflareJevProvider({ + accountId: "a", + apiToken: "t1234567890", + fetchFn: (input, init) => + Promise.resolve( + new Response( + new ReadableStream({ + start(controller) { + init.signal?.addEventListener( + "abort", + () => controller.error(init.signal?.reason ?? new Error("aborted")), + { once: true }, + ); + // deliberately never enqueue: headers sent, body stalled + }, + }), + { status: 200, headers: { "content-type": "application/json" } }, + ), + ), + }); + const started = Date.now(); + await assert.rejects( + provider.ask( + { state: {}, questions: { n: { type: "noul", instructions: "?" } }, model: "m" }, + { timeoutMs: 100 }, + ), + /timed out|aborted/i, + ); + assert.ok(Date.now() - started < 2_000, "the stalled body must not hang the call"); + }); + + test("an external abort during a stalled response body aborts the read", async () => { + const provider = new CloudflareJevProvider({ + accountId: "a", + apiToken: "t1234567890", + fetchFn: (input, init) => + Promise.resolve( + new Response( + new ReadableStream({ + start(controller) { + init.signal?.addEventListener( + "abort", + () => controller.error(init.signal?.reason ?? new Error("aborted")), + { once: true }, + ); + }, + }), + { status: 200, headers: { "content-type": "application/json" } }, + ), + ), + }); + const caller = new AbortController(); + const pending = provider.ask( + { state: {}, questions: { n: { type: "noul", instructions: "?" } }, model: "m" }, + { timeoutMs: 30_000, signal: caller.signal }, + ); + caller.abort(new Error("cancelled by caller")); + await assert.rejects(pending, /cancelled by caller|aborted/i); + }); + + test("a network failure rejects as a transport error", async () => { + const provider = new CloudflareJevProvider({ + accountId: "a", + apiToken: "t1234567890", + fetchFn: () => { + const failure = new TypeError("fetch failed"); + (failure as unknown as { cause: unknown }).cause = new Error("connect ECONNREFUSED"); + return Promise.reject(failure); + }, + }); + await assert.rejects( + provider.ask( + { state: {}, questions: { n: { type: "noul", instructions: "?" } }, model: "m" }, + CALL_OPTIONS, + ), + ); + }); + + test("a non-JSON body is a provider error, not an empty envelope", async () => { + const provider = new CloudflareJevProvider({ + accountId: "a", + apiToken: "t1234567890", + fetchFn: () => Promise.resolve(new Response("gateway", { status: 502 })), + }); + await assert.rejects( + provider.ask( + { state: {}, questions: { n: { type: "noul", instructions: "?" } }, model: "m" }, + CALL_OPTIONS, + ), + /non-JSON/, + ); + }); +}); + +describe("cloudflare credential redaction", () => { + test("a directly-constructed provider registers its own token for redaction", () => { + // Not via the factory: the port itself owns the credential, so the + // two-argument dependency composition can scrub it. + const token = "cft_direct_secret_token_0123456789"; + const provider = new CloudflareJevProvider({ accountId: "acc", apiToken: token }); + assert.deepEqual(provider.credentialSecrets, [token]); + const dependencies = createWorkflowDependencies("/tmp/jev-cf-direct-root", provider); + const out = dependencies.redaction.text(`token ${token} leaked`); + assert.equal(out.text.includes(token), false); + assert.match(out.text, /\[REDACTED:env_secret\]/); + // An explicit credentialSecrets override still wins. + const overridden = new CloudflareJevProvider({ + accountId: "acc", + apiToken: token, + credentialSecrets: [], + }); + assert.deepEqual(overridden.credentialSecrets, []); + }); + + test("the two-argument composition redacts the custom-env token via the port", () => { + const customEnv = { + CLOUDFLARE_ACCOUNT_ID: "acc", + CLOUDFLARE_API_TOKEN: "cft_portlevel_secret_0123456789", + }; + const port = createCloudflareAdapter(customEnv); + const dependencies = createWorkflowDependencies("/tmp/jev-cf-two-arg-root", port); + const out = dependencies.redaction.text("token cft_portlevel_secret_0123456789 leaked"); + assert.equal(out.text.includes("cft_portlevel_secret_0123456789"), false); + assert.match(out.text, /\[REDACTED:env_secret\]/); + }); + + test("generic env redaction covers both cloudflare token variables", () => { + const env = { + CLOUDFLARE_API_TOKEN: "cft_canonical_secret_0123456789", + JEV_CLOUDFLARE_API_TOKEN: "cft_alias_secret_0123456789", + }; + const redaction = createRedaction(env); + const out = redaction.text("tokens cft_canonical_secret_0123456789 cft_alias_secret_0123456789"); + assert.equal(out.text.includes("cft_canonical_secret_0123456789"), false); + assert.equal(out.text.includes("cft_alias_secret_0123456789"), false); + }); + + test("provider error messages never contain the token or request bodies", async () => { + const token = "cft_super_secret_token_9876543210"; + const provider = new CloudflareJevProvider({ + accountId: "acc", + apiToken: token, + fetchFn: () => + Promise.resolve( + new Response( + JSON.stringify({ + success: false, + errors: [{ code: 10000, message: `invalid model for token ${token}` }], + }), + { status: 400 }, + ), + ), + }); + const request: JevRequest = { + state: { diff: "secret source" }, + questions: { n: { type: "noul", instructions: "?" } }, + model: "m", + }; + await assert.rejects(provider.ask(request, CALL_OPTIONS), (error: unknown) => { + // Redaction at the message level is the recorder's job; the provider + // itself must not embed the credential or request body in the message. + const message = (error as Error).message; + assert.equal(message.length <= 500, true); + return true; + }); + }); +}); + +describe("cloudflare provider through the CLI", () => { + test("JEV_PROVIDER=cloudflare without credentials fails as input error 65", async () => { + const { runCli } = await import("../src/cli.ts"); + const code = await runCli(["Find the code", "--no-persist"], { + stdout: { write: () => {} }, + stderr: { write: () => {} }, + stdin: Readable.from([""]), + cwd: "/tmp", + env: { JEV_PROVIDER: "cloudflare" }, + }); + assert.equal(code, 65); + }); + + test("JEV_PROVIDER=cloudflare with credentials reaches the workflow layer", async () => { + // A temp repo with a diff, routing through the real CLI path, network mocked + // by a local server that the adapter targets via CLOUDFLARE_BASE_URL. + let requests = 0; + const r = (await import("./helpers.ts")).tempRepo(); + try { + r.write({ "src/a.ts": "export const a = 1;\n" }); + r.commit("init"); + r.write({ "src/a.ts": "export const a = 2;\n" }); + const server = createServer((req, res) => { + let data = ""; + req.on("data", (chunk: string) => (data += chunk)); + req.on("end", () => { + requests++; + res.writeHead(200, { "content-type": "application/json" }); + res.end( + JSON.stringify( + envelope( + jevResult({ + answers: { n: { type: "noul", noul: 0.9 } }, + }), + ), + ), + ); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const port = (server.address() as { port: number }).port; + const { runCli } = await import("../src/cli.ts"); + let stderr = ""; + const code = await runCli(["Find the code", "--no-persist"], { + stdout: { write: () => {} }, + stderr: { write: (text: string) => (stderr += text) }, + stdin: Readable.from([""]), + cwd: r.root, + env: { + JEV_PROVIDER: "cloudflare", + CLOUDFLARE_ACCOUNT_ID: "acc", + CLOUDFLARE_API_TOKEN: "cftoken1234567890", + CLOUDFLARE_BASE_URL: `http://127.0.0.1:${port}`, + }, + }); + server.close(); + // The workflow must get past provider construction (no credential error) + // and actually route through the local server — the env override is the + // only base URL the factory honors. + assert.notEqual(code, 65); + assert.doesNotMatch(stderr, /CLOUDFLARE/); + assert.ok(requests > 0, "the CLI run must exercise the local server"); + } finally { + r.cleanup(); + } + }); +}); + +describe("cloudflare smoke environment gating", () => { + test("cloudflare smoke needs JEV_SMOKE plus account id and token; skips cleanly otherwise", async () => { + const { checkEnvironment } = await import("../scripts/smoke-env.ts"); + const base = { CLOUDFLARE_ACCOUNT_ID: "acc", CLOUDFLARE_API_TOKEN: "cft_test" }; + assert.match(String(checkEnvironment(base, { provider: "cloudflare" }).skip), /set JEV_SMOKE=1/); + assert.match( + String(checkEnvironment({ JEV_SMOKE: "1", ...base }, { provider: "cloudflare" }).skip), + /set JEV_SMOKE=1|null/, + ); + const gated = checkEnvironment({ JEV_SMOKE: "1", ...base }, { provider: "cloudflare" }); + assert.equal(gated.skip, null); + assert.match( + String( + checkEnvironment({ JEV_SMOKE: "1", CLOUDFLARE_API_TOKEN: "cft_test" }, { provider: "cloudflare" }) + .skip, + ), + /CLOUDFLARE_ACCOUNT_ID is not set/, + ); + assert.match( + String( + checkEnvironment({ JEV_SMOKE: "1", CLOUDFLARE_ACCOUNT_ID: "acc" }, { provider: "cloudflare" }).skip, + ), + /CLOUDFLARE_API_TOKEN is not set/, + ); + }); + + test("the smoke script skips cleanly without credentials", async () => { + const { spawnSync } = await import("node:child_process"); + const result = spawnSync("node", ["scripts/smoke-cloudflare.ts"], { + cwd: process.cwd(), + encoding: "utf8", + env: { ...process.env, JEV_SMOKE: "", CLOUDFLARE_ACCOUNT_ID: "", CLOUDFLARE_API_TOKEN: "" }, + }); + assert.equal(result.status, 0); + assert.match(result.stdout, /smoke:cloudflare skipped/); + }); +}); diff --git a/test/providers.test.ts b/test/providers.test.ts index 59397bb..7a435a0 100644 --- a/test/providers.test.ts +++ b/test/providers.test.ts @@ -56,7 +56,7 @@ describe("provider selection", () => { assert.throws(() => configuredProvider({ JEV_PROVIDER: "openrouter" }), InvalidProviderError); assert.throws( () => configuredProvider({ JEV_PROVIDER: "Vercel" }), - /JEV_PROVIDER must be one of typesafe, vercel/, + /JEV_PROVIDER must be one of typesafe, vercel, cloudflare/, ); }); @@ -152,6 +152,7 @@ describe("TypeSafe provider", () => { [statusError(403, "forbidden"), "auth"], [Object.assign(new Error("nope"), { name: "APIUserAbortError" }), "aborted"], [statusError(413, "payload too large"), "too_large"], + [statusError(400, "payload exceeds the maximum allowed size"), "too_large"], [statusError(429, "rate limit"), "transient"], [statusError(503, "unavailable"), "transient"], [statusError(422, "bad request"), "rejected"], @@ -587,6 +588,10 @@ describe("Vercel error classification", () => { [gatewayError(403, "GatewayForbiddenError"), "auth"], [new Error("Invalid API key"), "auth"], [gatewayError(413, "GatewayInvalidRequestError", "payload too large"), "too_large"], + [ + gatewayError(400, "GatewayInvalidRequestError", "payload exceeds the maximum allowed size"), + "too_large", + ], [gatewayError(429, "GatewayRateLimitError"), "transient"], [gatewayError(500, "GatewayInternalServerError"), "transient"], [gatewayError(408, "GatewayTimeoutError"), "transient"], @@ -649,7 +654,7 @@ describe("provider selection through the CLI", () => { env: { JEV_PROVIDER: "openrouter", TYPESAFE_API_KEY: "tsk_test" }, }); assert.equal(code, 64); - assert.match(stderr, /JEV_PROVIDER must be one of typesafe, vercel/); + assert.match(stderr, /JEV_PROVIDER must be one of typesafe, vercel, cloudflare/); } finally { r.cleanup(); }