mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-21 15:43:24 +01:00
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>
This commit is contained in:
1 parent
0668443f36
commit
b150736602
14 files changed
+83
-23
No files matched your search
@@ -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
|
||||
|
||||
+3
-1
@@ -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}`,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)`;
|
||||
|
||||
+2
-2
@@ -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}`,
|
||||
|
||||
@@ -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}`,
|
||||
|
||||
+2
-2
@@ -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}`,
|
||||
|
||||
@@ -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}`,
|
||||
|
||||
@@ -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}`,
|
||||
|
||||
@@ -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}`,
|
||||
|
||||
@@ -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<Extracte
|
||||
const timeout = setTimeout(() => 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}`,
|
||||
|
||||
@@ -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}`,
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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"));
|
||||
|
||||
Reference in new issue
Block a user