From b150736602beac0781e35f71d9bcfb4443f35dfc Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 8 Oct 2026 14:52:38 +0000 Subject: [PATCH] feat(design): honor OPENAI_BASE_URL for every design API call One resolver, openaiUrl() in design/src/auth.ts, now builds every OpenAI URL the design binary, its prototype and its live model check use. Setting OPENAI_BASE_URL sends image generation and screenshot analysis to an OpenAI-compatible gateway; unset or blank keeps api.openai.com. The prototype script now goes through receiptedFetch, so its egress is receipted like the rest, and receipts already record the gateway host. A source scan keeps any design file outside auth.ts from hardcoding an OpenAI API URL again, and a request-shape test proves the gateway reaches both the vision and image endpoints. Co-authored-by: JackJin <1037461232@qq.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- README.md | 4 +++- design/prototype.ts | 4 +++- design/scripts/live-model-check.ts | 5 +++-- design/src/auth.ts | 10 +++++++++ design/src/check.ts | 4 ++-- design/src/design-to-code.ts | 4 ++-- design/src/diff.ts | 4 ++-- design/src/evolve.ts | 6 +++--- design/src/generate.ts | 4 ++-- design/src/iterate.ts | 6 +++--- design/src/memory.ts | 4 ++-- design/src/variants.ts | 4 ++-- design/test/auth.test.ts | 34 ++++++++++++++++++++++++++++++ design/test/models.test.ts | 13 +++++++++++- 14 files changed, 83 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index e2c99f362..c2e4afd43 100644 --- a/README.md +++ b/README.md @@ -201,7 +201,9 @@ if OpenAI rejects it, the error names `GSTACK_DESIGN_MODEL`. Set value that is not a gpt-image model name is refused before any request. Check a key against the defaults with `bun run design/scripts/live-model-check.ts`, which always tests the default models and ignores both overrides; the weekly -periodic census runs the same check. +periodic census runs the same check. Set `OPENAI_BASE_URL` to send every `$D` +call to an OpenAI-compatible gateway instead of `api.openai.com`; egress +receipts record the gateway host. **Want to add support for another agent?** See [docs/ADDING_A_HOST.md](docs/ADDING_A_HOST.md). Rendering a new agent is one TypeScript config file; installing it also needs a diff --git a/design/prototype.ts b/design/prototype.ts index b59db3019..e16ada2d1 100644 --- a/design/prototype.ts +++ b/design/prototype.ts @@ -8,6 +8,8 @@ import fs from "fs"; import path from "path"; +import { openaiUrl } from "./src/auth"; +import { receiptedFetch } from "./src/receipted-fetch"; const API_KEY = process.env.OPENAI_API_KEY; @@ -44,7 +46,7 @@ async function generateMockup(brief: { name: string; prompt: string }) { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 120_000); // 2 min timeout - const response = await fetch("https://api.openai.com/v1/responses", { + const response = await receiptedFetch("prototype-image-request", openaiUrl("responses"), { method: "POST", headers: { "Authorization": `Bearer ${API_KEY}`, diff --git a/design/scripts/live-model-check.ts b/design/scripts/live-model-check.ts index 111a18587..88f40ac73 100644 --- a/design/scripts/live-model-check.ts +++ b/design/scripts/live-model-check.ts @@ -22,6 +22,7 @@ import { imageToolModel, visionRequestBody, } from "../src/models"; +import { openaiUrl } from "../src/auth"; import { receiptedFetch } from "../src/receipted-fetch"; const TINY_PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkAAIAAAoAAv/lxKUAAAAASUVORK5CYII="; @@ -78,7 +79,7 @@ let image = TINY_PNG; failed = true; } if (body) { - const r = await post("live-check-image-request", "https://api.openai.com/v1/responses", body, 240_000); + const r = await post("live-check-image-request", openaiUrl("responses"), body, 240_000); const item = r.json?.output?.find((o: any) => o.type === "image_generation_call"); const pass = r.ok && typeof item?.result === "string" && item.result.length > 0; if (pass) image = item.result; @@ -101,7 +102,7 @@ let image = TINY_PNG; { type: "text", text: "Reply with exactly one word: PASS." }, ], }], 20); - const r = await post("live-check-vision-request", "https://api.openai.com/v1/chat/completions", body, 120_000); + const r = await post("live-check-vision-request", openaiUrl("chat/completions"), body, 120_000); const choice = r.json?.choices?.[0]; const content = String(choice?.message?.content ?? "").trim(); const pass = r.ok && content.length > 0; diff --git a/design/src/auth.ts b/design/src/auth.ts index fc25cbcf4..fc6a90069 100644 --- a/design/src/auth.ts +++ b/design/src/auth.ts @@ -99,6 +99,16 @@ export function resolveApiKey(): string | null { return resolveApiKeyInfo()?.key ?? null; } +/** + * OpenAI API URL for one endpoint. OPENAI_BASE_URL (the OpenAI SDK convention) + * points every design call at an OpenAI-compatible gateway; egress receipts + * record whichever host is used. + */ +export function openaiUrl(endpoint: "responses" | "chat/completions"): string { + const base = process.env.OPENAI_BASE_URL?.trim().replace(/\/+$/, "") || "https://api.openai.com/v1"; + return `${base}/${endpoint}`; +} + export function describeApiKeySource(resolution: ApiKeyResolution): string { if (resolution.source === "config") return "~/.gstack/openai.json"; if (resolution.envFile) return `OPENAI_API_KEY environment variable (matches ${resolution.envFile} in current directory)`; diff --git a/design/src/check.ts b/design/src/check.ts index fbc14c46e..b03e0fc80 100644 --- a/design/src/check.ts +++ b/design/src/check.ts @@ -4,7 +4,7 @@ */ import fs from "fs"; -import { requireApiKey } from "./auth"; +import { openaiUrl, requireApiKey } from "./auth"; import { receiptedFetch } from "./receipted-fetch"; import { modelRejectionHint, visionRequestBody } from "./models"; @@ -34,7 +34,7 @@ export async function checkMockup(imagePath: string, brief: string, opts: CheckO const signal = opts.signal ? AbortSignal.any([controller.signal, opts.signal]) : controller.signal; try { - const response = await receiptedFetch("check-screenshot-request", "https://api.openai.com/v1/chat/completions", { + const response = await receiptedFetch("check-screenshot-request", openaiUrl("chat/completions"), { method: "POST", headers: { "Authorization": `Bearer ${apiKey}`, diff --git a/design/src/design-to-code.ts b/design/src/design-to-code.ts index ecf610b17..4e14faba9 100644 --- a/design/src/design-to-code.ts +++ b/design/src/design-to-code.ts @@ -5,7 +5,7 @@ */ import fs from "fs"; -import { requireApiKey } from "./auth"; +import { openaiUrl, requireApiKey } from "./auth"; import { receiptedFetch } from "./receipted-fetch"; import { modelRejectionHint, visionRequestBody } from "./models"; import { readDesignConstraints } from "./memory"; @@ -39,7 +39,7 @@ export async function generateDesignToCodePrompt( ? `\n\nExisting DESIGN.md (use these as constraints):\n${designConstraints}` : ""; - const response = await receiptedFetch("design-to-code-request", "https://api.openai.com/v1/chat/completions", { + const response = await receiptedFetch("design-to-code-request", openaiUrl("chat/completions"), { method: "POST", headers: { "Authorization": `Bearer ${apiKey}`, diff --git a/design/src/diff.ts b/design/src/diff.ts index 94f060130..c5eeed8e4 100644 --- a/design/src/diff.ts +++ b/design/src/diff.ts @@ -5,7 +5,7 @@ */ import fs from "fs"; -import { requireApiKey } from "./auth"; +import { openaiUrl, requireApiKey } from "./auth"; import { receiptedFetch } from "./receipted-fetch"; import { modelRejectionHint, visionRequestBody } from "./models"; @@ -30,7 +30,7 @@ export async function diffMockups( const timeout = setTimeout(() => controller.abort(), 60_000); try { - const response = await receiptedFetch("diff-screenshots-request", "https://api.openai.com/v1/chat/completions", { + const response = await receiptedFetch("diff-screenshots-request", openaiUrl("chat/completions"), { method: "POST", headers: { "Authorization": `Bearer ${apiKey}`, diff --git a/design/src/evolve.ts b/design/src/evolve.ts index 803101e50..dc7e7feca 100644 --- a/design/src/evolve.ts +++ b/design/src/evolve.ts @@ -6,7 +6,7 @@ */ import fs from "fs"; -import { requireApiKey } from "./auth"; +import { openaiUrl, requireApiKey } from "./auth"; import { receiptedFetch } from "./receipted-fetch"; import { imageRequestBody, modelRejectionHint, visionRequestBody } from "./models"; import { emitResult, exitCodeFor, newAccounting, persistImage, recordOutcome, type ExitCode } from "./persist"; @@ -76,7 +76,7 @@ async function requestEvolvedImage(apiKey: string, evolvedPrompt: string): Promi const timeout = setTimeout(() => controller.abort(), 240_000); try { - const response = await receiptedFetch("evolve-image-request", "https://api.openai.com/v1/responses", { + const response = await receiptedFetch("evolve-image-request", openaiUrl("responses"), { method: "POST", headers: { "Authorization": `Bearer ${apiKey}`, @@ -141,7 +141,7 @@ export async function analyzeScreenshot( const signal = batchSignal ? AbortSignal.any([controller.signal, batchSignal]) : controller.signal; try { - const response = await receiptedFetch("evolve-screenshot-analysis-request", "https://api.openai.com/v1/chat/completions", { + const response = await receiptedFetch("evolve-screenshot-analysis-request", openaiUrl("chat/completions"), { method: "POST", headers: { "Authorization": `Bearer ${apiKey}`, diff --git a/design/src/generate.ts b/design/src/generate.ts index 22b21eacf..1dcc9dc0a 100644 --- a/design/src/generate.ts +++ b/design/src/generate.ts @@ -2,7 +2,7 @@ * Generate UI mockups via OpenAI Responses API with image_generation tool. */ -import { requireApiKey } from "./auth"; +import { openaiUrl, requireApiKey } from "./auth"; import { receiptedFetch } from "./receipted-fetch"; import { imageRequestBody, modelRejectionHint } from "./models"; import { parseBrief } from "./brief"; @@ -51,7 +51,7 @@ async function callImageGeneration( const timeout = setTimeout(() => controller.abort(), 240_000); try { - const response = await receiptedFetch("generate-image-request", "https://api.openai.com/v1/responses", { + const response = await receiptedFetch("generate-image-request", openaiUrl("responses"), { method: "POST", headers: { "Authorization": `Bearer ${apiKey}`, diff --git a/design/src/iterate.ts b/design/src/iterate.ts index 47bf196c8..3922988ff 100644 --- a/design/src/iterate.ts +++ b/design/src/iterate.ts @@ -6,7 +6,7 @@ * with original brief + accumulated feedback in a single prompt. */ -import { requireApiKey } from "./auth"; +import { openaiUrl, requireApiKey } from "./auth"; import { receiptedFetch } from "./receipted-fetch"; import { imageRequestBody, modelRejectionHint } from "./models"; import { readSession, updateSession } from "./session"; @@ -88,7 +88,7 @@ async function callWithThreading( const timeout = setTimeout(() => controller.abort(), 240_000); try { - const response = await receiptedFetch("iterate-threaded-image-request", "https://api.openai.com/v1/responses", { + const response = await receiptedFetch("iterate-threaded-image-request", openaiUrl("responses"), { method: "POST", headers: { "Authorization": `Bearer ${apiKey}`, @@ -135,7 +135,7 @@ async function callFresh( const timeout = setTimeout(() => controller.abort(), 240_000); try { - const response = await receiptedFetch("iterate-fresh-image-request", "https://api.openai.com/v1/responses", { + const response = await receiptedFetch("iterate-fresh-image-request", openaiUrl("responses"), { method: "POST", headers: { "Authorization": `Bearer ${apiKey}`, diff --git a/design/src/memory.ts b/design/src/memory.ts index f4e5ca5e4..0b0b72ef8 100644 --- a/design/src/memory.ts +++ b/design/src/memory.ts @@ -13,7 +13,7 @@ import fs from "fs"; import path from "path"; -import { requireApiKey } from "./auth"; +import { openaiUrl, requireApiKey } from "./auth"; import { receiptedFetch } from "./receipted-fetch"; import { modelRejectionHint, visionRequestBody } from "./models"; import { parseDesignMd, detectFormat, renderDesignMd, spliceSection, specSkeleton, tokensFlat, slug, DesignMdEditRefused } from "../../lib/design-md"; @@ -41,7 +41,7 @@ export async function extractDesignLanguage(imagePath: string): Promise controller.abort(), 60_000); try { - const response = await receiptedFetch("memory-distill-request", "https://api.openai.com/v1/chat/completions", { + const response = await receiptedFetch("memory-distill-request", openaiUrl("chat/completions"), { method: "POST", headers: { "Authorization": `Bearer ${apiKey}`, diff --git a/design/src/variants.ts b/design/src/variants.ts index 32c21c169..a65e19918 100644 --- a/design/src/variants.ts +++ b/design/src/variants.ts @@ -6,7 +6,7 @@ import fs from "fs"; import path from "path"; -import { requireApiKey } from "./auth"; +import { openaiUrl, requireApiKey } from "./auth"; import { receiptedFetch } from "./receipted-fetch"; import { imageRequestBody, modelRejectionHint } from "./models"; import { parseBrief } from "./brief"; @@ -118,7 +118,7 @@ export async function requestVariantImage( let response: Response; try { - response = await receiptedFetch("variants-image-request", "https://api.openai.com/v1/responses", { + response = await receiptedFetch("variants-image-request", openaiUrl("responses"), { method: "POST", headers: { "Authorization": `Bearer ${apiKey}`, diff --git a/design/test/auth.test.ts b/design/test/auth.test.ts index 0c0c60b23..953109b0d 100644 --- a/design/test/auth.test.ts +++ b/design/test/auth.test.ts @@ -13,6 +13,7 @@ import * as os from "os"; import * as path from "path"; import { describeApiKeySource, + openaiUrl, requireApiKey, resolveApiKey, resolveApiKeyInfo, @@ -23,6 +24,7 @@ let tmpDir: string; let tmpHome: string; let originalHome: string | undefined; let originalKey: string | undefined; +let originalBaseUrl: string | undefined; let originalNodeEnv: string | undefined; let originalCwd: string; @@ -33,11 +35,13 @@ beforeEach(() => { originalHome = process.env.HOME; originalKey = process.env.OPENAI_API_KEY; + originalBaseUrl = process.env.OPENAI_BASE_URL; originalNodeEnv = process.env.NODE_ENV; originalCwd = process.cwd(); process.env.HOME = tmpHome; delete process.env.OPENAI_API_KEY; + delete process.env.OPENAI_BASE_URL; delete process.env.NODE_ENV; process.chdir(tmpDir); }); @@ -48,6 +52,8 @@ afterEach(() => { else process.env.HOME = originalHome; if (originalKey === undefined) delete process.env.OPENAI_API_KEY; else process.env.OPENAI_API_KEY = originalKey; + if (originalBaseUrl === undefined) delete process.env.OPENAI_BASE_URL; + else process.env.OPENAI_BASE_URL = originalBaseUrl; if (originalNodeEnv === undefined) delete process.env.NODE_ENV; else process.env.NODE_ENV = originalNodeEnv; fs.rmSync(tmpDir, { recursive: true, force: true }); @@ -132,6 +138,34 @@ describe("saveApiKey", () => { }); }); +describe("openaiUrl", () => { + test("defaults to OpenAI; a blank OPENAI_BASE_URL is unset", () => { + expect(openaiUrl("responses")).toBe("https://api.openai.com/v1/responses"); + process.env.OPENAI_BASE_URL = " "; + expect(openaiUrl("chat/completions")).toBe("https://api.openai.com/v1/chat/completions"); + }); + + test("uses a trimmed OPENAI_BASE_URL without duplicate slashes", () => { + process.env.OPENAI_BASE_URL = " https://gateway.example/openai/v1/// "; + expect(openaiUrl("responses")).toBe("https://gateway.example/openai/v1/responses"); + }); + + test("no design source outside auth.ts hardcodes an OpenAI API URL", () => { + const designDir = path.resolve(import.meta.dir, ".."); + const walk = (dir: string): string[] => + fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => { + const p = path.join(dir, e.name); + if (e.isDirectory()) return e.name === "test" || e.name === "node_modules" || e.name === "dist" ? [] : walk(p); + return /\.[cm]?[jt]s$/.test(e.name) ? [p] : []; + }); + const hardcoded = walk(designDir) + .filter((p) => p !== path.join(designDir, "src", "auth.ts")) + .filter((p) => fs.readFileSync(p, "utf-8").includes("https://api.openai.com")) + .map((p) => path.relative(designDir, p)); + expect(hardcoded).toEqual([]); + }); +}); + describe("requireApiKey", () => { test("prints source disclosure without leaking the key", () => { process.env.OPENAI_API_KEY = "sk-secret-value"; diff --git a/design/test/models.test.ts b/design/test/models.test.ts index c2aa7be9d..f5211c212 100644 --- a/design/test/models.test.ts +++ b/design/test/models.test.ts @@ -65,7 +65,8 @@ beforeEach(() => { calls = []; errors = []; dir = fs.mkdtempSync(path.join(os.tmpdir(), "design-models-")); - for (const k of ["HOME", "GSTACK_HOME", "OPENAI_API_KEY", DESIGN_MODEL_ENV]) saved[k] = process.env[k]; + for (const k of ["HOME", "GSTACK_HOME", "OPENAI_API_KEY", "OPENAI_BASE_URL", DESIGN_MODEL_ENV]) saved[k] = process.env[k]; + delete process.env.OPENAI_BASE_URL; process.env.HOME = dir; process.env.GSTACK_HOME = dir; process.env.OPENAI_API_KEY = "test-openai-key"; @@ -203,6 +204,16 @@ describe("image-generation call sites (Responses API)", () => { }); }); +test("OPENAI_BASE_URL sends image and vision calls to the gateway", async () => { + process.env.OPENAI_BASE_URL = "https://gateway.example/openai/v1/"; + stubFetch((u) => ok(u, "a centered card")); + await evolve({ screenshot: path.join(dir, "shot.png"), brief: "darker", output: path.join(dir, "e.png") }); + expect(calls.map((c) => c.url)).toEqual([ + "https://gateway.example/openai/v1/chat/completions", + "https://gateway.example/openai/v1/responses", + ]); +}); + describe("vision call sites (Chat Completions)", () => { test("check", async () => { stubFetch((u) => ok(u, "PASS"));