An open-source, faster Devin alternative
TypeScript
fix(flue): bound responses and layer worker env safely
Igor Zalutski253e0b200e1c
diff --git a/sdks/flue/src/cf-env.test.ts b/sdks/flue/src/cf-env.test.tsnew file mode 100644index 00000000..6baafcbc--- /dev/null+++ b/sdks/flue/src/cf-env.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from "vitest";+import { layerOcEnv } from "./cf-env.js";++describe("Cloudflare env layering", () => {+ it("prefers ambient values and reads request secrets without enumerating the fallback proxy", () => {+ const fallback = new Proxy<Record<string, unknown>>(+ {},+ {+ get(_target, property) {+ if (property === "OC_REPO_API") return "https://fallback.invalid";+ if (property === "OC_SESSION_TOKEN") return "request-token";+ return undefined;+ },+ ownKeys() {+ throw new Error("runtime env must not be enumerated");+ },+ },+ );+ const ambient = {+ OC_REPO_API: "https://repositories.test",+ OC_SESSION_TOKEN: undefined,+ };++ const resolved = layerOcEnv(ambient, fallback);++ expect(resolved.OC_REPO_API).toBe("https://repositories.test");+ expect(resolved.OC_SESSION_TOKEN).toBe("request-token");+ expect(layerOcEnv(ambient, undefined)).toBe(ambient);+ });+});diff --git a/sdks/flue/src/cf-env.ts b/sdks/flue/src/cf-env.tsindex 0215e28b..d13a1d91 100644--- a/sdks/flue/src/cf-env.ts+++ b/sdks/flue/src/cf-env.ts@@ -2,8 +2,8 @@// build, plain Worker bindings (`OC_GATEWAY`, `OC_SANDBOX_*`, `OC_INGEST`, …) are available on the// AMBIENT env exported by `cloudflare:workers` — the same one Flue's generated entry reads// (`import { env } from 'cloudflare:workers'`). Worker secrets such as `OC_SESSION_TOKEN` can instead-// arrive through the runtime-owned env reference at request time. Helpers therefore retain that-// fallback reference and resolve it lazily, layering ambient plain bindings over its current values.+// arrive through the runtime-owned env reference at request time. That reference can be a proxy that+// supports direct property reads but not enumeration, so helpers retain it and never spread it.//// `cloudflare:workers` only resolves inside workerd, so importing it statically would break local// `flue dev` on the node target and the package's own vitest. Load it lazily + guarded: on CF the@@ -23,12 +23,33 @@ try {}/**- * Resolve the effective OC env: the Cloudflare ambient bindings layered over `fallback` (ambient wins).- * On CF this adds ambient plain Worker bindings without discarding request-time values from `fallback`;- * off CF (local dev / node / tests) it returns `fallback` unchanged.+ * Layer ambient plain bindings over a runtime-owned fallback without enumerating+ * the fallback. Defined ambient values win; missing ambient values are read+ * directly from the fallback at access time.*/-export function ocResolveEnv<T extends Record<string, unknown>>(fallback: T | undefined): T {- const base = (fallback ?? {}) as T;- if (!ambientEnv) return base;- return { ...base, ...ambientEnv } as T;+export function layerOcEnv<T extends Record<string, unknown>>(+ ambient: Record<string, unknown> | undefined,+ fallback: T | undefined,+): T {+ if (!ambient) return (fallback ?? {}) as T;+ if (!fallback) return ambient as T;+ return new Proxy(ambient, {+ get(target, property) {+ const value = Reflect.get(target, property, target);+ return value === undefined+ ? Reflect.get(fallback, property, fallback)+ : value;+ },+ }) as T;+}++/**+ * Resolve the effective OC env. On Cloudflare this layers ambient plain+ * bindings over the lazily read runtime env; off Cloudflare it returns the+ * fallback unchanged.+ */+export function ocResolveEnv<T extends Record<string, unknown>>(+ fallback: T | undefined,+): T {+ return layerOcEnv(ambientEnv, fallback);}diff --git a/sdks/flue/src/gateway.ts b/sdks/flue/src/gateway.tsindex 3c21dd54..ac3db9d0 100644--- a/sdks/flue/src/gateway.ts+++ b/sdks/flue/src/gateway.ts@@ -5,7 +5,8 @@// SECRET. Secrets are NOT on the CF ambient env (`cloudflare:workers`) at all — only plain vars like// OC_GATEWAY are — and `ctx.env` at defineAgent-init is empty for the OC bindings too. So an init-time// registerProvider reads the token falsy and every model call throws "No API key for provider: anthropic".-// The secret DOES live on the per-REQUEST env (`c.env`) — the same source ocSandbox reads at run time.+// The secret DOES live on the per-REQUEST env (`c.env`); repository and sandbox helpers likewise read+// their runtime-owned request env references directly rather than enumerating or spreading them.// Fix: bind the apiKey at RUN scope from the exported `route` middleware, reading OC_SESSION_TOKEN from// `c.env` by DIRECT property access (NEVER spread c.env — the CF env is a proxy and spreading it throws)// and OC_GATEWAY from the ambient snapshot, once per isolate. The token is per-DEPLOY (identical for@@ -52,9 +53,9 @@ function bindOcProvider(env: OcEnv): boolean {* initializer** — top-level module code is stripped by the CF build (proven in 1a). This runs at INIT* scope, where the per-deploy OC_SESSION_TOKEN (a secret) is typically not yet readable, so it registers* the baseUrl (model specifier resolves) and defers the apiKey to `route` (run scope) — see the token-seam- * note above. Binds the apiKey here too if the token happens to already be present. Reads the CF ambient- * env (`cloudflare:workers`), not `ctx.env`: on the `--target cloudflare` build the real Worker bindings- * live on the ambient env and `ctx.env` is empty for them.+ * note above. Binds the apiKey here too if the token happens to already be present. Plain Worker+ * bindings come from the CF ambient env; the runtime-owned `ctx.env` is read directly only for values+ * absent there and may still be tokenless during initialization.*/export function useOcGateway(ctx: AgentInitializerContext<OcEnv>): void {bindOcProvider(ocResolveEnv<OcEnv>(ctx.env));diff --git a/sdks/flue/src/repo.test.ts b/sdks/flue/src/repo.test.tsindex 7c225585..c6c4e842 100644--- a/sdks/flue/src/repo.test.ts+++ b/sdks/flue/src/repo.test.ts@@ -237,7 +237,7 @@ describe("list_working_repos HTTP fixtures", () => {},);- it("accepts additive response growth without freezing list or message size", async () => {+ it("accepts additive response growth while bounding model-visible list and message size", async () => {const repositories = Array.from({ length: 51 }, (_, index) => ({id: `repo_${index}`,full_name: `owner/repository-${index}`,@@ -275,18 +275,20 @@ describe("list_working_repos HTTP fixtures", () => {await expect(list.run({ input: {} })).resolves.toEqual({ok: true,- repositories: repositories.map(({ id, full_name, default_branch }) => ({- id,- full_name,- default_branch,- })),- truncated: false,+ repositories: repositories+ .slice(0, 50)+ .map(({ id, full_name, default_branch }) => ({+ id,+ full_name,+ default_branch,+ })),+ truncated: true,});await expect(list.run({ input: {} })).resolves.toEqual({ok: false,error: {code: "github_unavailable",- message: "x".repeat(501),+ message: "x".repeat(500),retryable: true,},});diff --git a/sdks/flue/src/repo.ts b/sdks/flue/src/repo.tsindex d713575f..e4af2811 100644--- a/sdks/flue/src/repo.ts+++ b/sdks/flue/src/repo.ts@@ -33,6 +33,9 @@ const ERROR_CODES = ["deployment_unverified",] as const;+const RESPONSE_ERROR_MESSAGE_MAX = 500;+const RESPONSE_REPOSITORY_MAX = 50;+export type OcRepoErrorCode = (typeof ERROR_CODES)[number];export interface OcRepoError {@@ -51,14 +54,20 @@ export type OcRepoFailure = {// semantic fields while ignoring additive fields from a newer server. Tool// inputs below remain strict and bounded so the model cannot smuggle extra// authority or unbounded work.-const RepoErrorSchema = v.object({- code: v.picklist(ERROR_CODES),- message: v.pipe(v.string(), v.minLength(1)),- retryable: v.boolean(),- retry_after_seconds: v.optional(- v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(600)),- ),-});+const RepoErrorSchema = v.pipe(+ v.object({+ code: v.picklist(ERROR_CODES),+ message: v.pipe(v.string(), v.minLength(1)),+ retryable: v.boolean(),+ retry_after_seconds: v.optional(+ v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(600)),+ ),+ }),+ v.transform((error) => ({+ ...error,+ message: error.message.slice(0, RESPONSE_ERROR_MESSAGE_MAX),+ })),+);const RepoFailureSchema = v.object({ok: v.literal(false),@@ -77,11 +86,19 @@ export interface WorkingRepository {default_branch: string;}-const ListWorkingReposSuccessSchema = v.object({- ok: v.literal(true),- repositories: v.array(WorkingRepositorySchema),- truncated: v.boolean(),-});+const ListWorkingReposSuccessSchema = v.pipe(+ v.object({+ ok: v.literal(true),+ repositories: v.array(WorkingRepositorySchema),+ truncated: v.boolean(),+ }),+ v.transform((result) => ({+ ...result,+ repositories: result.repositories.slice(0, RESPONSE_REPOSITORY_MAX),+ truncated:+ result.truncated || result.repositories.length > RESPONSE_REPOSITORY_MAX,+ })),+);const SourceNameSchema = v.pipe(v.string(),@@ -432,8 +449,8 @@ function randomIdempotencyKey(): string {** The initializer captures only the session id and the runtime-owned* environment reference, not a spread/snapshot. Managed bindings are resolved- * inside each tool run so request-time secrets on that reference are visible;- * ambient plain bindings are layered in by `ocResolveEnv`.+ * inside each tool run so request-time secrets on that reference are visible+ * through direct property reads; `ocResolveEnv` never enumerates that proxy.*/export function ocRepoTools(ctx: AgentInitializerContext<OcRepoEnv>,diff --git a/sdks/flue/src/sandbox.ts b/sdks/flue/src/sandbox.tsindex 9dfc729a..6ccf1a46 100644--- a/sdks/flue/src/sandbox.ts+++ b/sdks/flue/src/sandbox.ts@@ -267,9 +267,9 @@ async function resolveSandboxId(* Linux shell or durable files. The default starter intentionally omits it.** Resolves the captured runtime env lazily and layers in plain bindings from the CF ambient env- * (`cloudflare:workers`). The request-time `OC_SESSION_TOKEN` remains on the captured env reference;- * it is not assumed to exist in the ambient snapshot. `createSessionEnv` validates local configuration- * and returns a lazy environment without fetching or provisioning anything.+ * (`cloudflare:workers`). The request-time `OC_SESSION_TOKEN` remains on the captured env proxy and is+ * read directly; that proxy is never spread or enumerated. `createSessionEnv` validates local+ * configuration and returns a lazy environment without fetching or provisioning anything.*/export function ocSandbox(env: OcSandboxEnv,