Skip to content

An open-source, faster Devin alternative

TypeScript

fix(@opencomputer/flue): 3 W6-surfaced package defects

Igor Zalutski53a473caa7c8
diff --git a/sdks/flue/src/app.ts b/sdks/flue/src/app.ts
index 342402b8..5159b911 100644
--- a/sdks/flue/src/app.ts
+++ b/sdks/flue/src/app.ts
@@ -1,18 +1,30 @@
-// The default OC hosting app. A scaffolded starter uses this as its `src/app.ts` (or the CF build
-// generates an equivalent when no app.ts exists). It mounts Flue's routes, adds the `/health` probe the
-// OC deploy/activate step needs (stock Flue exposes NO health route — Spike B finding), and installs the
-// telemetry forwarder. Apps that own their `app.ts` instead `import '@opencomputer/flue/wire'` (§wire).
+// The default OC hosting app. A scaffolded starter uses this as its `src/app.ts`. It composes the
+// SAME app Flue's Cloudflare build generates for the no-`app.ts` case, then adds the `/health` probe
+// the OC deploy/activate step needs (stock Flue exposes NO health route — Spike B finding) and installs
+// the telemetry forwarder. Apps that own their `app.ts` instead `import '@opencomputer/flue/wire'` (§wire).
+//
+// WHY `createDefaultFlueApp()` from `@flue/runtime/internal` (and NOT `flue()` from
+// `@flue/runtime/routing`): `flue()`'s route handlers read the module-scoped `runtimeConfig` at REQUEST
+// time, which the generated Cloudflare entry sets via `configureFlueRuntime(...)` (imported from
+// `@flue/runtime/internal`) at module load. The generated entry's no-`app.ts` path builds its app with
+// `createDefaultFlueApp()` — the exact same `@flue/runtime/internal` entry — so the mounted `flue()` and
+// the `configureFlueRuntime()` that seeds it share one module instance and requests never hit
+// "flue() route invoked before runtime was configured". A `src/app.ts` that instead mounted `flue()`
+// from `@flue/runtime/routing` (a different published entry) risked resolving a second `@flue/runtime`
+// module instance whose `runtimeConfig` is never configured → every request 500s. Composing via the
+// build's own entry keeps this app on the configured instance.
//
// Default export = a `Fetchable` (Hono qualifies), per Flue's routing contract.
-import { Hono } from "hono";
-import { flue } from "@flue/runtime/routing";
+import { createDefaultFlueApp } from "@flue/runtime/internal";
import { installOcObserver } from "./observe.js";
installOcObserver();
-const app = new Hono();
+// createDefaultFlueApp() mounts flue() at '/' and installs Flue's canonical notFound/onError envelopes.
+// Adding a path-specific '/health' route afterwards is safe — flue() only registers its own concrete
+// paths (/agents, /workflows, /runs, /channels), so GET /health matches this handler directly.
+const app = createDefaultFlueApp();
app.get("/health", (c) => c.json({ status: "ok" }));
-app.route("/", flue());
export default app;
diff --git a/sdks/flue/src/cf-env.ts b/sdks/flue/src/cf-env.ts
new file mode 100644
index 00000000..c29a6ad2
--- /dev/null
+++ b/sdks/flue/src/cf-env.ts
@@ -0,0 +1,33 @@
+// Ambient Cloudflare-Workers env access (design 013 §4). On the `flue build --target cloudflare`
+// build the real Worker bindings (`OC_GATEWAY`, `OC_SESSION_TOKEN`, `OC_SANDBOX_*`, `OC_INGEST`, …)
+// live on the AMBIENT env exported by `cloudflare:workers` — the same one Flue's generated entry reads
+// (`import { env } from 'cloudflare:workers'`). The per-agent `ctx.env` Flue threads into the
+// initializer is EMPTY for these bindings, so OC helpers must read the ambient env instead.
+//
+// `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
+// dynamic import resolves and `ambientEnv` is populated during module graph evaluation (before any
+// request); everywhere else the import rejects, is caught, and callers fall back to the passed env.
+
+let ambientEnv: Record<string, unknown> | undefined;
+try {
+ // `@vite-ignore` so consumer/test bundlers don't try to statically resolve the workerd built-in;
+ // on CF this is a runtime import of the ambient module, off CF it throws and we fall back.
+ const mod = (await import(/* @vite-ignore */ "cloudflare:workers")) as {
+ env?: Record<string, unknown>;
+ };
+ ambientEnv = mod.env;
+} catch {
+ ambientEnv = undefined;
+}
+
+/**
+ * Resolve the effective OC env: the Cloudflare ambient bindings layered over `fallback` (ambient wins).
+ * On CF this returns the real Worker bindings even though `ctx.env` is empty; off CF (local dev / node /
+ * tests) it returns `fallback` unchanged so an explicitly-passed env still works.
+ */
+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;
+}
diff --git a/sdks/flue/src/cloudflare-workers.d.ts b/sdks/flue/src/cloudflare-workers.d.ts
new file mode 100644
index 00000000..3102313c
--- /dev/null
+++ b/sdks/flue/src/cloudflare-workers.d.ts
@@ -0,0 +1,6 @@
+// Minimal ambient type for the workerd-only `cloudflare:workers` virtual module, so the guarded
+// dynamic import in `cf-env.ts` typechecks without pulling in `@cloudflare/workers-types`. The real
+// module (present only on the `--target cloudflare` build) exports the ambient Worker `env` bindings.
+declare module "cloudflare:workers" {
+ export const env: Record<string, unknown>;
+}
diff --git a/sdks/flue/src/gateway.ts b/sdks/flue/src/gateway.ts
index 486ae93a..d9c3bcae 100644
--- a/sdks/flue/src/gateway.ts
+++ b/sdks/flue/src/gateway.ts
@@ -12,10 +12,14 @@
import { registerProvider } from "@flue/runtime";
import type { AgentInitializerContext, AgentRouteHandler } from "@flue/runtime";
+import { ocResolveEnv } from "./cf-env.js";
/** Default managed model — MUST be prompt-caching-safe (Constraint): `claude-3-haiku` fails via
- * OpenRouter→Bedrock; `claude-haiku-4.5` works. Cheap + caching-safe for the scaffolded starter. */
-export const DEFAULT_MODEL = "anthropic/claude-haiku-4.5";
+ * OpenRouter→Bedrock; `claude-haiku-4-5` works. Use the pi-ai CATALOG id with DASHES
+ * (`claude-haiku-4-5`), never a dot (`claude-haiku-4.5`): the dotted id is absent from pi-ai's model
+ * catalog, so pi-ai can't derive the model's max output tokens and defaults `max_tokens` to 1 → empty
+ * completions. The dashed id resolves in the catalog and OpenRouter routes it too. Cheap + caching-safe. */
+export const DEFAULT_MODEL = "anthropic/claude-haiku-4-5";
export interface OcEnv {
/** Deployed gateway Worker base URL (set per tenant script by the OC deploy). */
@@ -30,16 +34,20 @@ export interface OcEnv {
/**
* Point the managed `anthropic` provider at the OC gateway. **Call this INSIDE the `defineAgent`
* initializer** — top-level module code is stripped by the CF build (proven in 1a), and the initializer
- * body runs per harness init with `env` available. No-op when `OC_GATEWAY` is unset (local `flue dev`
- * falls through to pi-ai's env-var key lookup). `anthropic` is a catalog id, so `baseUrl` alone rehydrates
- * the wire protocol.
+ * body runs per harness init. 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 (Flue's generated entry threads `instance.env`, which lacks the OC bindings), so reading
+ * `ctx.env` alone would leave `OC_GATEWAY` unset and the provider unregistered ("Unknown model
+ * specifier"). No-op when `OC_GATEWAY` is unset (local `flue dev` falls through to pi-ai's env-var key
+ * lookup). `anthropic` is a catalog id, so `baseUrl` alone rehydrates the wire protocol.
*/
export function useOcGateway(ctx: AgentInitializerContext<OcEnv>): void {
- const gw = ctx.env.OC_GATEWAY;
+ const env = ocResolveEnv<OcEnv>(ctx.env);
+ const gw = env.OC_GATEWAY;
if (!gw) return;
registerProvider("anthropic", {
baseUrl: `${gw.replace(/\/+$/, "")}/anthropic`,
- ...(ctx.env.OC_SESSION_TOKEN ? { apiKey: ctx.env.OC_SESSION_TOKEN } : {}),
+ ...(env.OC_SESSION_TOKEN ? { apiKey: env.OC_SESSION_TOKEN } : {}),
});
}
diff --git a/sdks/flue/src/sandbox.ts b/sdks/flue/src/sandbox.ts
index 99e4b0c2..c66f835d 100644
--- a/sdks/flue/src/sandbox.ts
+++ b/sdks/flue/src/sandbox.ts
@@ -14,6 +14,7 @@
import { createSandboxSessionEnv } from "@flue/runtime";
import type { SandboxApi, SandboxFactory, FileStat, ShellResult, SessionEnv } from "@flue/runtime";
import type { OcEnv } from "./gateway.js";
+import { ocResolveEnv } from "./cf-env.js";
/** Constant workspace cwd (matches the OC session contract — flue resolves skills at `${cwd}/.agents/skills`). */
export const WORKSPACE_CWD = "/workspace";
@@ -108,16 +109,22 @@ async function resolveSandboxId(env: OcSandboxEnv, sessionId: string): Promise<s
* The OC-fleet sandbox factory. Set `sandbox: ocSandbox(env)` in your `defineAgent` initializer; the OC
* template scaffolds exactly this. Lazily resolves the session's sandbox (keyed by the DO instance id =
* `ses_`) on first tool use, so no sandbox is provisioned for tool-free turns (§5).
+ *
+ * Reads the CF ambient env (`cloudflare:workers`), not the passed `ctx.env`: on the `--target
+ * cloudflare` build the real `OC_SANDBOX_*`/`OC_SESSION_TOKEN` bindings live on the ambient env and
+ * `ctx.env` is empty for them (same reason as `useOcGateway`). The resolution happens lazily inside
+ * `createSessionEnv`, so a tool-free turn never touches the sandbox config.
*/
export function ocSandbox(env: OcSandboxEnv, opts?: { cwd?: string }): SandboxFactory {
const cwd = opts?.cwd ?? WORKSPACE_CWD;
return {
async createSessionEnv({ id }: { id: string }): Promise<SessionEnv> {
- if (!env.OC_SANDBOX_API && !env.OC_SANDBOX_ID) {
+ const resolved = ocResolveEnv<OcSandboxEnv>(env);
+ if (!resolved.OC_SANDBOX_API && !resolved.OC_SANDBOX_ID) {
throw new Error("[oc-flue] ocSandbox: set OC_SANDBOX_API (+ OC_SESSION_TOKEN) or OC_SANDBOX_ID — the OC sandbox binding is not configured.");
}
- const sandboxId = await resolveSandboxId(env, id);
- const api = new OcSandboxApi((env.OC_SANDBOX_API ?? "").replace(/\/+$/, ""), env.OC_SESSION_TOKEN ?? "", sandboxId);
+ const sandboxId = await resolveSandboxId(resolved, id);
+ const api = new OcSandboxApi((resolved.OC_SANDBOX_API ?? "").replace(/\/+$/, ""), resolved.OC_SESSION_TOKEN ?? "", sandboxId);
return createSandboxSessionEnv(api, cwd);
},
};