@skyphusion/create-prism 0.1.0 → 0.175.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +5 -3
  2. package/index.js +4 -2
  3. package/package.json +1 -1
  4. package/template/CONTRIBUTING.md +6 -2
  5. package/template/README.md +45 -33
  6. package/template/docs/legal/README.md +1 -0
  7. package/template/migrations/0002_auth_public_mode.sql +32 -0
  8. package/template/package.json +6 -6
  9. package/template/public/app.js +44 -16
  10. package/template/public/index.html +47 -4
  11. package/template/src/auth-kdf.ts +7 -4
  12. package/template/src/auth.ts +11 -2
  13. package/template/src/control-plane.ts +254 -0
  14. package/template/src/env.ts +15 -0
  15. package/template/src/gateway-credentials.ts +23 -4
  16. package/template/src/health-schema.ts +4 -0
  17. package/template/src/index.ts +65 -3982
  18. package/template/src/longrun-params.ts +4 -2
  19. package/template/src/models.ts +65 -19
  20. package/template/src/output-extract.ts +58 -8
  21. package/template/src/parsers/openai-sse.ts +43 -14
  22. package/template/src/providers/anthropic.ts +105 -0
  23. package/template/src/providers/openai-image.ts +66 -0
  24. package/template/src/providers/openai.ts +79 -13
  25. package/template/src/providers/xai.ts +91 -0
  26. package/template/src/proxied-image-params.ts +29 -16
  27. package/template/src/routes/artifacts.ts +51 -0
  28. package/template/src/routes/chat.ts +1709 -0
  29. package/template/src/routes/conversations.ts +212 -0
  30. package/template/src/routes/documents.ts +262 -0
  31. package/template/src/routes/health.ts +105 -0
  32. package/template/src/routes/history.ts +92 -0
  33. package/template/src/routes/prefs.ts +95 -0
  34. package/template/src/routes/projects.ts +574 -0
  35. package/template/src/routes/rag.ts +657 -0
  36. package/template/src/routes/shared.ts +226 -0
  37. package/template/src/routes/workflow.ts +304 -0
  38. package/template/src/user-prefs.ts +10 -0
  39. package/template/src/zip.ts +7 -0
  40. package/template/tests/anthropic-binding.test.ts +181 -0
  41. package/template/tests/control-plane.test.ts +112 -0
  42. package/template/tests/gateway-credentials.test.ts +37 -0
  43. package/template/tests/longrun-params.test.ts +19 -0
  44. package/template/tests/openai-image.test.ts +47 -0
  45. package/template/tests/openai-responses.test.ts +78 -0
  46. package/template/tests/openai-sse.test.ts +28 -0
  47. package/template/tests/output-extract.test.ts +75 -1
  48. package/template/tests/proxied-image-params.test.ts +16 -7
  49. package/template/tests/sprint1-catalog.test.ts +27 -0
  50. package/template/tests/sprint2-catalog.test.ts +51 -0
  51. package/template/tests/sprint3-catalog.test.ts +29 -0
  52. package/template/tests/xai-binding.test.ts +127 -0
  53. package/template/tests-integration/worker.test.ts +9 -2
  54. package/template/wrangler.example.toml +19 -7
@@ -0,0 +1,181 @@
1
+ // Tests for the v0.169.0 binding dispatch in src/providers/anthropic.ts.
2
+ //
3
+ // anthropic/claude-fable-5 is flagged binding: true, so callAnthropic /
4
+ // callAnthropicStream route through env.AI.run (the new Unified Billing catalog
5
+ // surface) instead of the legacy AI Gateway provider fetch path. The fake
6
+ // AiContext below stubs ONLY env.AI.run (the un-stubbable seam); everything
7
+ // downstream is the real shipped code: the Anthropic message transform, the
8
+ // shared SSE framer, and interpretAnthropicSSEFrame. That is what lets these
9
+ // exercise the actual wiring rather than a re-implementation of it.
10
+
11
+ import { describe, it, expect } from "vitest";
12
+ import type { AiContext } from "../src/ai-binding";
13
+ import type { ModelEntry } from "../src/models";
14
+ import { MODELS } from "../src/models";
15
+ import { callAnthropic, callAnthropicStream } from "../src/providers/anthropic";
16
+ import type { ProviderStreamEvent } from "../src/parsers/types";
17
+
18
+ const fableModel: ModelEntry = {
19
+ id: "anthropic/claude-fable-5",
20
+ label: "Claude Fable 5 (Anthropic)",
21
+ group: "Chat · Anthropic",
22
+ type: "chat",
23
+ capabilities: ["vision"],
24
+ provider: "anthropic",
25
+ streaming: true,
26
+ binding: true,
27
+ };
28
+
29
+ type RunCall = { model: string; params: Record<string, unknown>; opts: unknown };
30
+
31
+ function fakeCtx(runImpl: (model: string, params: unknown, opts: unknown) => Promise<unknown>): { ctx: AiContext; calls: RunCall[] } {
32
+ const calls: RunCall[] = [];
33
+ const env = {
34
+ AI: {
35
+ run: (model: string, params: unknown, opts: unknown) => {
36
+ calls.push({ model, params: params as Record<string, unknown>, opts });
37
+ return runImpl(model, params, opts);
38
+ },
39
+ aiGatewayLogId: "log-123",
40
+ },
41
+ } as unknown as AiContext["env"];
42
+ const ctx = { env, gateway: { gatewayId: "skyphusion-llm", cfAigToken: "tok" } } as unknown as AiContext;
43
+ return { ctx, calls };
44
+ }
45
+
46
+ // Encode an array of Anthropic SSE frames as bytes, with the trailing spaces
47
+ // after each data JSON that fable-5 leaves on the wire, split into small chunks
48
+ // so the framer buffer-reassembly across reads is exercised too.
49
+ function sseStream(frames: unknown[], chunkSize = 7): ReadableStream<Uint8Array> {
50
+ const text = frames.map((f) => "data: " + JSON.stringify(f) + " \n\n").join("");
51
+ const bytes = new TextEncoder().encode(text);
52
+ let i = 0;
53
+ return new ReadableStream<Uint8Array>({
54
+ pull(controller) {
55
+ if (i >= bytes.length) { controller.close(); return; }
56
+ const end = Math.min(i + chunkSize, bytes.length);
57
+ controller.enqueue(bytes.slice(i, end));
58
+ i = end;
59
+ },
60
+ });
61
+ }
62
+
63
+ const userMessages = [
64
+ { role: "user", content: [
65
+ { type: "text", text: "hi" },
66
+ { type: "image_url", image_url: { url: "data:image/png;base64,AAAA" } },
67
+ ] },
68
+ ];
69
+
70
+ describe("catalog", () => {
71
+ it("has claude-fable-5 flagged binding: true, provider anthropic, streaming", () => {
72
+ const m = MODELS.find((x) => x.id === "anthropic/claude-fable-5");
73
+ expect(m).toBeDefined();
74
+ expect(m?.binding).toBe(true);
75
+ expect(m?.provider).toBe("anthropic");
76
+ expect(m?.streaming).toBe(true);
77
+ });
78
+
79
+ it("has claude-opus-5 flagged binding: true, provider anthropic, streaming, vision (v0.170.0)", () => {
80
+ const m = MODELS.find((x) => x.id === "anthropic/claude-opus-5");
81
+ expect(m).toBeDefined();
82
+ expect(m?.binding).toBe(true);
83
+ expect(m?.provider).toBe("anthropic");
84
+ expect(m?.streaming).toBe(true);
85
+ expect(m?.capabilities).toContain("vision");
86
+ });
87
+ });
88
+
89
+ describe("callAnthropic binding dispatch (non-stream)", () => {
90
+ const fableMsg = {
91
+ id: "msg_01Fable",
92
+ type: "message",
93
+ role: "assistant",
94
+ content: [
95
+ { type: "thinking", thinking: "", signature: "CAISopaque==" },
96
+ { type: "text", text: "OK." },
97
+ ],
98
+ stop_reason: "end_turn",
99
+ usage: { input_tokens: 12, output_tokens: 5 },
100
+ };
101
+
102
+ it("calls env.AI.run with the catalog id and an Anthropic-shaped body, returns raw + logId", async () => {
103
+ const { ctx, calls } = fakeCtx(async () => fableMsg);
104
+ const { raw, logId } = await callAnthropic(ctx, fableModel, "sys", userMessages);
105
+
106
+ expect(raw).toBe(fableMsg);
107
+ expect(logId).toBe("log-123");
108
+ expect(calls).toHaveLength(1);
109
+ expect(calls[0].model).toBe("anthropic/claude-fable-5");
110
+ expect(calls[0].opts).toEqual({ gateway: { id: "skyphusion-llm" } });
111
+
112
+ const p = calls[0].params;
113
+ expect(p.max_tokens).toBe(4096);
114
+ expect(p.system).toBe("sys");
115
+ expect(p.stream).toBeUndefined();
116
+ expect(p.messages).toEqual([
117
+ { role: "user", content: [
118
+ { type: "text", text: "hi" },
119
+ { type: "image", source: { type: "base64", media_type: "image/png", data: "AAAA" } },
120
+ ] },
121
+ ]);
122
+ });
123
+
124
+ it("a non-binding anthropic model does NOT take the binding path (the flag gates dispatch)", async () => {
125
+ // With binding falsy, callAnthropic must fall to the legacy gateway fetch
126
+ // path, which reads ctx.env.AI.gateway(...).getUrl(...). The fake AiContext
127
+ // exposes no gateway method, so the legacy path throws and env.AI.run is
128
+ // never invoked. This proves the dispatch is flag-driven, not always-binding.
129
+ const { ctx, calls } = fakeCtx(async () => fableMsg);
130
+ const legacyModel: ModelEntry = { ...fableModel, binding: false };
131
+ await expect(callAnthropic(ctx, legacyModel, "sys", userMessages)).rejects.toThrow();
132
+ expect(calls).toHaveLength(0);
133
+ });
134
+ });
135
+
136
+ describe("callAnthropicStream binding dispatch (stream)", () => {
137
+ const frames = [
138
+ { type: "message_start", message: { id: "msg_01Fable", role: "assistant", usage: { input_tokens: 50, output_tokens: 1 } } },
139
+ { type: "content_block_start", index: 0, content_block: { type: "thinking", thinking: "" } },
140
+ { type: "content_block_delta", index: 0, delta: { type: "thinking_delta", thinking: "hmm" } },
141
+ { type: "content_block_delta", index: 0, delta: { type: "signature_delta", signature: "CAISopaque==" } },
142
+ { type: "content_block_stop", index: 0 },
143
+ { type: "content_block_start", index: 1, content_block: { type: "text", text: "" } },
144
+ { type: "content_block_delta", index: 1, delta: { type: "text_delta", text: "OK." } },
145
+ { type: "content_block_stop", index: 1 },
146
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { input_tokens: 50, output_tokens: 5 } },
147
+ { type: "message_stop" },
148
+ ];
149
+
150
+ async function collect(gen: AsyncGenerator<ProviderStreamEvent>): Promise<ProviderStreamEvent[]> {
151
+ const out: ProviderStreamEvent[] = [];
152
+ for await (const e of gen) out.push(e);
153
+ return out;
154
+ }
155
+
156
+ it("drives the native Anthropic SSE stream through the real framer, surfacing only text + usage", async () => {
157
+ const { ctx, calls } = fakeCtx(async () => sseStream(frames));
158
+ const ac = new AbortController();
159
+ const events = await collect(callAnthropicStream(ctx, fableModel, "sys", userMessages, ac.signal));
160
+
161
+ expect(calls[0].params.stream).toBe(true);
162
+ expect(events).toEqual([
163
+ { type: "usage", in_: 50, out_: 1 },
164
+ { type: "text", text: "OK." },
165
+ { type: "usage", in_: 50, out_: 5 },
166
+ ]);
167
+ // The thinking signature must never leak into surfaced text.
168
+ const textOut = events.filter((e) => e.type === "text").map((e) => (e as { text: string }).text).join("");
169
+ expect(textOut).toBe("OK.");
170
+ expect(textOut).not.toContain("CAIS");
171
+ });
172
+
173
+ it("yields nothing when the abort signal is already tripped (client gone)", async () => {
174
+ const { ctx, calls } = fakeCtx(async () => sseStream(frames));
175
+ const ac = new AbortController();
176
+ ac.abort();
177
+ const events = await collect(callAnthropicStream(ctx, fableModel, "sys", userMessages, ac.signal));
178
+ expect(events).toEqual([]);
179
+ expect(calls).toHaveLength(1); // the run was issued, then cancelled without draining
180
+ });
181
+ });
@@ -0,0 +1,112 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ looksLikeClientKey,
4
+ resolveControlPlane,
5
+ allowlistedControlPlaneOrigin,
6
+ stripTrailingSlashes,
7
+ controlPlaneChat,
8
+ DEFAULT_CONTROL_PLANE_URL,
9
+ } from "../src/control-plane";
10
+
11
+ describe("looksLikeClientKey", () => {
12
+ it("accepts a well-formed pcp key", () => {
13
+ const key = `pcp_${"a".repeat(16)}_${"A".repeat(43)}`;
14
+ expect(looksLikeClientKey(key)).toBe(true);
15
+ });
16
+
17
+ it("rejects junk", () => {
18
+ expect(looksLikeClientKey("pcp_short")).toBe(false);
19
+ expect(looksLikeClientKey("Bearer x")).toBe(false);
20
+ });
21
+ });
22
+
23
+ describe("stripTrailingSlashes", () => {
24
+ it("strips without regex ReDoS surface", () => {
25
+ expect(stripTrailingSlashes("https://play-proxy.skyphusion.org///")).toBe(
26
+ "https://play-proxy.skyphusion.org",
27
+ );
28
+ expect(stripTrailingSlashes("abc")).toBe("abc");
29
+ });
30
+ });
31
+
32
+ describe("allowlistedControlPlaneOrigin", () => {
33
+ it("accepts the production host only", () => {
34
+ expect(allowlistedControlPlaneOrigin(DEFAULT_CONTROL_PLANE_URL)).toBe(
35
+ "https://play-proxy.skyphusion.org",
36
+ );
37
+ expect(allowlistedControlPlaneOrigin("https://PLAY-PROXY.SKYPHUSION.ORG/")).toBe(
38
+ "https://play-proxy.skyphusion.org",
39
+ );
40
+ });
41
+
42
+ it("rejects SSRF targets and lookalikes", () => {
43
+ expect(allowlistedControlPlaneOrigin("https://evil.example")).toBeNull();
44
+ expect(allowlistedControlPlaneOrigin("https://play-proxy.skyphusion.org.evil.com")).toBeNull();
45
+ expect(allowlistedControlPlaneOrigin("http://play-proxy.skyphusion.org")).toBeNull();
46
+ expect(allowlistedControlPlaneOrigin("https://169.254.169.254")).toBeNull();
47
+ expect(allowlistedControlPlaneOrigin("https://play-proxy.skyphusion.org/v1")).toBeNull();
48
+ expect(allowlistedControlPlaneOrigin("https://user:pass@play-proxy.skyphusion.org")).toBeNull();
49
+ });
50
+
51
+ it("allows localhost only when opted in", () => {
52
+ expect(allowlistedControlPlaneOrigin("http://localhost:8787")).toBeNull();
53
+ expect(
54
+ allowlistedControlPlaneOrigin("http://localhost:8787", { allowLocalhost: true }),
55
+ ).toBe("http://localhost:8787");
56
+ });
57
+ });
58
+
59
+ describe("resolveControlPlane", () => {
60
+ it("returns null without a valid key", () => {
61
+ expect(resolveControlPlane(null)).toBeNull();
62
+ expect(resolveControlPlane({ control_plane_key: "nope" })).toBeNull();
63
+ });
64
+
65
+ it("uses allowlisted default URL; ignores any prefs URL field", () => {
66
+ const key = `pcp_${"b".repeat(16)}_${"B".repeat(43)}`;
67
+ const cp = resolveControlPlane({
68
+ control_plane_key: key,
69
+ // @ts-expect-error legacy / hostile field must not be honored
70
+ control_plane_url: "https://evil.example",
71
+ });
72
+ expect(cp?.baseUrl).toBe(DEFAULT_CONTROL_PLANE_URL);
73
+ expect(cp?.clientKey).toBe(key);
74
+ });
75
+
76
+ it("refuses a non-allowlisted CONTROL_PLANE_URL env", () => {
77
+ const key = `pcp_${"c".repeat(16)}_${"C".repeat(43)}`;
78
+ expect(
79
+ resolveControlPlane(
80
+ { control_plane_key: key },
81
+ { CONTROL_PLANE_URL: "https://evil.example" },
82
+ ),
83
+ ).toBeNull();
84
+ });
85
+ });
86
+
87
+ describe("controlPlaneChat", () => {
88
+ it("posts OpenAI-shaped body with bearer to fixed path", async () => {
89
+ const key = `pcp_${"d".repeat(16)}_${"D".repeat(43)}`;
90
+ let seen: Request | null = null;
91
+ const fetchImpl = async (input: RequestInfo | URL, init?: RequestInit) => {
92
+ seen = new Request(input, init);
93
+ return new Response(
94
+ JSON.stringify({
95
+ choices: [{ message: { role: "assistant", content: "hello from proxy" } }],
96
+ usage: { prompt_tokens: 3, completion_tokens: 4 },
97
+ model: "m",
98
+ }),
99
+ { status: 200, headers: { "prism-request-id": "req_test" } },
100
+ );
101
+ };
102
+ const result = await controlPlaneChat(
103
+ { baseUrl: "https://play-proxy.skyphusion.org", clientKey: key },
104
+ { model: "@cf/meta/llama-3.2-3b-instruct", messages: [{ role: "user", content: "hi" }] },
105
+ fetchImpl as typeof fetch,
106
+ );
107
+ expect(result.text).toBe("hello from proxy");
108
+ expect(result.requestId).toBe("req_test");
109
+ expect(seen!.url).toBe("https://play-proxy.skyphusion.org/v1/chat/completions");
110
+ expect(seen!.headers.get("authorization")).toBe(`Bearer ${key}`);
111
+ });
112
+ });
@@ -1,5 +1,6 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import {
3
+ buildGatewayStatus,
3
4
  gatewaySource,
4
5
  maskSecret,
5
6
  resolveGatewayFromParts,
@@ -10,6 +11,8 @@ function env(partial: Partial<Env> = {}): Env {
10
11
  return partial as Env;
11
12
  }
12
13
 
14
+ const VALID_PCP = `pcp_${"a".repeat(16)}_${"A".repeat(43)}`;
15
+
13
16
  describe("resolveGatewayFromParts", () => {
14
17
  it("returns null when no gateway id is available", () => {
15
18
  expect(resolveGatewayFromParts(null, env())).toBeNull();
@@ -63,3 +66,37 @@ describe("maskSecret", () => {
63
66
  expect(maskSecret(" ")).toBeNull();
64
67
  });
65
68
  });
69
+
70
+ describe("buildGatewayStatus", () => {
71
+ it("is unconfigured with no gateway and no pcp_ key", () => {
72
+ const s = buildGatewayStatus(null, env());
73
+ expect(s.configured).toBe(false);
74
+ expect(s.control_plane_configured).toBe(false);
75
+ expect(s.control_plane_key_set).toBe(false);
76
+ });
77
+
78
+ it("counts gateway id alone as configured (BYOK path)", () => {
79
+ const s = buildGatewayStatus({ gateway_id: "my-gw" }, env());
80
+ expect(s.configured).toBe(true);
81
+ expect(s.gateway_id).toBe("my-gw");
82
+ expect(s.control_plane_configured).toBe(false);
83
+ });
84
+
85
+ it("counts a pcp_ key alone as configured (no gateway slug)", () => {
86
+ // Hard-refresh boot probe used to miss this: loadGatewayStatus only looked
87
+ // at gateway id, so the SPA banner said "configure instance" while prefs
88
+ // still showed control-plane mode on.
89
+ const s = buildGatewayStatus({ control_plane_key: VALID_PCP }, env());
90
+ expect(s.configured).toBe(true);
91
+ expect(s.control_plane_configured).toBe(true);
92
+ expect(s.control_plane_key_set).toBe(true);
93
+ expect(s.gateway_id).toBeNull();
94
+ });
95
+
96
+ it("rejects a malformed pcp_ key", () => {
97
+ const s = buildGatewayStatus({ control_plane_key: "pcp_not_valid" }, env());
98
+ expect(s.configured).toBe(false);
99
+ expect(s.control_plane_configured).toBe(false);
100
+ expect(s.control_plane_key_set).toBe(true);
101
+ });
102
+ });
@@ -65,6 +65,25 @@ describe("buildGenParams", () => {
65
65
  expect(p).not.toHaveProperty("image_input");
66
66
  });
67
67
 
68
+ it("Seedance 2.0 Mini i2v shares the Seedance 2.0 shape (v0.170.0)", () => {
69
+ const p = buildGenParams("video", {
70
+ modelId: "bytedance/seedance-2.0-mini",
71
+ prompt: "rain falls",
72
+ imageUrl: "https://x/k.png",
73
+ });
74
+ expect(p).toEqual({
75
+ image: "https://x/k.png",
76
+ prompt: "rain falls",
77
+ aspect_ratio: "16:9",
78
+ duration: 5,
79
+ resolution: "720p",
80
+ fps: 24,
81
+ camera_fixed: false,
82
+ watermark: false,
83
+ generate_audio: false,
84
+ });
85
+ });
86
+
68
87
  it("Hailuo 2.3 i2v shape: `first_frame_image` field, 768P resolution", () => {
69
88
  const p = buildGenParams("video", {
70
89
  modelId: "minimax/hailuo-2.3-fast",
@@ -0,0 +1,47 @@
1
+ // Unit tests for OpenAI transparent-PNG BYOK body shape (v0.174.0).
2
+ // Network is stubbed; we only assert the request OpenAI receives.
3
+
4
+ import { describe, it, expect, vi, afterEach } from "vitest";
5
+ import { generateOpenAIImage } from "../src/providers/openai-image";
6
+
7
+ afterEach(() => {
8
+ vi.unstubAllGlobals();
9
+ });
10
+
11
+ describe("generateOpenAIImage", () => {
12
+ it("POSTs transparent png params to api.openai.com and strips openai/ prefix", async () => {
13
+ const fetchMock = vi.fn(async () =>
14
+ new Response(JSON.stringify({ data: [{ b64_json: "aGVsbG8=" }] }), {
15
+ status: 200,
16
+ headers: { "content-type": "application/json" },
17
+ }),
18
+ );
19
+ vi.stubGlobal("fetch", fetchMock);
20
+
21
+ const gen = await generateOpenAIImage("sk-test", "openai/gpt-image-1.5", "a coin");
22
+ expect(gen.mime).toBe("image/png");
23
+ expect(gen.bytes.length).toBeGreaterThan(0);
24
+
25
+ expect(fetchMock).toHaveBeenCalledTimes(1);
26
+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
27
+ expect(url).toBe("https://api.openai.com/v1/images/generations");
28
+ expect((init.headers as Record<string, string>).Authorization).toBe("Bearer sk-test");
29
+ const body = JSON.parse(String(init.body));
30
+ expect(body).toEqual({
31
+ model: "gpt-image-1.5",
32
+ prompt: "a coin",
33
+ size: "1024x1024",
34
+ quality: "high",
35
+ background: "transparent",
36
+ output_format: "png",
37
+ });
38
+ });
39
+
40
+ it("surfaces OpenAI error status + message", async () => {
41
+ vi.stubGlobal("fetch", vi.fn(async () =>
42
+ new Response(JSON.stringify({ error: { message: "billing hard limit" } }), { status: 429 }),
43
+ ));
44
+ await expect(generateOpenAIImage("sk-test", "openai/gpt-image-2", "x"))
45
+ .rejects.toThrow(/OpenAI image API 429: billing hard limit/);
46
+ });
47
+ });
@@ -0,0 +1,78 @@
1
+ // Tests for OpenAI Responses API body builder (v0.173.0).
2
+
3
+ import { describe, it, expect } from "vitest";
4
+ import { buildOpenAIResponsesBody } from "../src/providers/openai";
5
+ import { MODELS } from "../src/models";
6
+
7
+ describe("buildOpenAIResponsesBody", () => {
8
+ it("maps system to instructions and user/assistant to input", () => {
9
+ const body = buildOpenAIResponsesBody([
10
+ { role: "system", content: "be brief" },
11
+ { role: "user", content: "hello" },
12
+ { role: "assistant", content: "hi" },
13
+ { role: "user", content: "again" },
14
+ ]);
15
+ expect(body.instructions).toBe("be brief");
16
+ expect(body.input).toEqual([
17
+ { role: "user", content: "hello" },
18
+ { role: "assistant", content: "hi" },
19
+ { role: "user", content: "again" },
20
+ ]);
21
+ expect(body.max_output_tokens).toBe(4096);
22
+ expect(body.stream).toBeUndefined();
23
+ expect(body.messages).toBeUndefined();
24
+ });
25
+
26
+ it("flattens multimodal text blocks and drops image_url parts", () => {
27
+ const body = buildOpenAIResponsesBody([
28
+ {
29
+ role: "user",
30
+ content: [
31
+ { type: "text", text: "look" },
32
+ { type: "image_url", image_url: { url: "data:image/png;base64,AA" } },
33
+ { type: "text", text: "please" },
34
+ ],
35
+ },
36
+ ]);
37
+ expect(body.input).toEqual([{ role: "user", content: "look\nplease" }]);
38
+ });
39
+
40
+ it("sets stream:true when requested", () => {
41
+ const body = buildOpenAIResponsesBody(
42
+ [{ role: "user", content: "x" }],
43
+ { stream: true, maxOutputTokens: 512 },
44
+ );
45
+ expect(body.stream).toBe(true);
46
+ expect(body.max_output_tokens).toBe(512);
47
+ });
48
+
49
+ it("omits instructions when no system message is present", () => {
50
+ const body = buildOpenAIResponsesBody([{ role: "user", content: "only user" }]);
51
+ expect(body.instructions).toBeUndefined();
52
+ });
53
+ });
54
+
55
+ describe("catalog responses models", () => {
56
+ const ids = [
57
+ "openai/gpt-5.5-pro",
58
+ "openai/gpt-5.6-sol",
59
+ "openai/gpt-5.6-terra",
60
+ "openai/gpt-5.6-luna",
61
+ ];
62
+
63
+ for (const id of ids) {
64
+ it(`${id} is openai chat with api:responses and streaming`, () => {
65
+ const m = MODELS.find((x) => x.id === id);
66
+ expect(m).toBeDefined();
67
+ expect(m?.provider).toBe("openai");
68
+ expect(m?.type).toBe("chat");
69
+ expect(m?.streaming).toBe(true);
70
+ expect(m?.api).toBe("responses");
71
+ });
72
+ }
73
+
74
+ it("gpt-5.5 stays on Chat Completions (no api flag)", () => {
75
+ const m = MODELS.find((x) => x.id === "openai/gpt-5.5");
76
+ expect(m?.api).toBeUndefined();
77
+ });
78
+ });
@@ -68,4 +68,32 @@ describe("interpretOpenAISSEFrame", () => {
68
68
  expect(() => interpretOpenAISSEFrame("[DONE]")).not.toThrow();
69
69
  expect(interpretOpenAISSEFrame(null)).toEqual([]);
70
70
  });
71
+
72
+ // --- Shape 3: Responses API typed events (v0.173.0) ---
73
+
74
+ it("extracts text from response.output_text.delta", () => {
75
+ expect(interpretOpenAISSEFrame({
76
+ type: "response.output_text.delta",
77
+ delta: "Hello",
78
+ output_index: 0,
79
+ })).toEqual([{ type: "text", text: "Hello" }]);
80
+ });
81
+
82
+ it("drops empty Responses text deltas", () => {
83
+ expect(interpretOpenAISSEFrame({ type: "response.output_text.delta", delta: "" })).toEqual([]);
84
+ });
85
+
86
+ it("reads usage from response.completed", () => {
87
+ expect(interpretOpenAISSEFrame({
88
+ type: "response.completed",
89
+ response: {
90
+ usage: { input_tokens: 10, output_tokens: 20, total_tokens: 30 },
91
+ },
92
+ })).toEqual([{ type: "usage", in_: 10, out_: 20 }]);
93
+ });
94
+
95
+ it("ignores intermediate Responses lifecycle events", () => {
96
+ expect(interpretOpenAISSEFrame({ type: "response.created", response: {} })).toEqual([]);
97
+ expect(interpretOpenAISSEFrame({ type: "response.output_item.added", item: {} })).toEqual([]);
98
+ });
71
99
  });
@@ -7,7 +7,13 @@
7
7
  // the rest are regression coverage for the shapes that already shipped.
8
8
 
9
9
  import { describe, it, expect } from "vitest";
10
- import { extractOutput, extractUsage, detectProviderFailure, extractProxiedImageUrl } from "../src/output-extract";
10
+ import {
11
+ extractOutput,
12
+ extractUsage,
13
+ detectProviderFailure,
14
+ extractProxiedImageUrl,
15
+ extractProxiedImageAsset,
16
+ } from "../src/output-extract";
11
17
 
12
18
  describe("extractOutput", () => {
13
19
  it("returns a bare string unchanged", () => {
@@ -122,6 +128,23 @@ describe("detectProviderFailure", () => {
122
128
  expect(detectProviderFailure({ state: "Failed" })).toBe('provider returned state "Failed"');
123
129
  });
124
130
 
131
+ it("flags OpenAI Responses API failed/incomplete status (v0.173.0)", () => {
132
+ expect(detectProviderFailure({
133
+ object: "response",
134
+ status: "failed",
135
+ error: { message: "upstream unavailable" },
136
+ })).toBe("upstream unavailable");
137
+ expect(detectProviderFailure({
138
+ object: "response",
139
+ status: "incomplete",
140
+ })).toBe('provider returned status "incomplete"');
141
+ });
142
+
143
+ it("does not flag a completed Responses object", () => {
144
+ expect(detectProviderFailure({ object: "response", status: "completed", output: [] })).toBeNull();
145
+ });
146
+
147
+
125
148
  it("treats any non-Completed state as a failure", () => {
126
149
  expect(detectProviderFailure({ state: "Cancelled" })).toBe('provider returned state "Cancelled"');
127
150
  });
@@ -158,9 +181,24 @@ describe("extractProxiedImageUrl", () => {
158
181
  expect(extractProxiedImageUrl(r)).toBe("https://r2.dev/wrapped.png");
159
182
  });
160
183
 
184
+ it("reads Seedream-style result.images[] and takes the first URL (v0.171.0)", () => {
185
+ const r = {
186
+ state: "Completed",
187
+ result: { images: ["https://r2.dev/seedream-0.jpeg", "https://r2.dev/seedream-1.jpeg"] },
188
+ };
189
+ expect(extractProxiedImageUrl(r)).toBe("https://r2.dev/seedream-0.jpeg");
190
+ });
191
+
192
+ it("reads bare { images } when no result wrapper is present", () => {
193
+ expect(extractProxiedImageUrl({ images: ["https://r2.dev/bare-arr.png"] })).toBe(
194
+ "https://r2.dev/bare-arr.png",
195
+ );
196
+ });
197
+
161
198
  it("returns null when no image url is present", () => {
162
199
  expect(extractProxiedImageUrl({ state: "Completed", result: {} })).toBeNull();
163
200
  expect(extractProxiedImageUrl({ choices: [] })).toBeNull();
201
+ expect(extractProxiedImageUrl({ result: { images: [] } })).toBeNull();
164
202
  });
165
203
 
166
204
  it("does not throw on null / undefined / string", () => {
@@ -168,4 +206,40 @@ describe("extractProxiedImageUrl", () => {
168
206
  expect(extractProxiedImageUrl(undefined)).toBeNull();
169
207
  expect(extractProxiedImageUrl("nope")).toBeNull();
170
208
  });
209
+
210
+ it("extractProxiedImageUrl ignores raw base64 (not a URL)", () => {
211
+ expect(extractProxiedImageUrl({ result: { image: "iVBORw0KGgo=" } })).toBeNull();
212
+ });
213
+ });
214
+
215
+ describe("extractProxiedImageAsset", () => {
216
+ it("classifies https URLs as kind url", () => {
217
+ expect(extractProxiedImageAsset({
218
+ state: "Completed",
219
+ result: { image: "https://r2.dev/out.png" },
220
+ })).toEqual({ kind: "url", url: "https://r2.dev/out.png" });
221
+ });
222
+
223
+ it("classifies raw base64 as kind b64 (Grok Imagine b64_json)", () => {
224
+ expect(extractProxiedImageAsset({
225
+ state: "Completed",
226
+ result: { image: "iVBORw0KGgoAAAANSUhEUg==" },
227
+ })).toEqual({
228
+ kind: "b64",
229
+ mime: "image/png",
230
+ base64: "iVBORw0KGgoAAAANSUhEUg==",
231
+ });
232
+ });
233
+
234
+ it("parses data: URIs into mime + base64", () => {
235
+ expect(extractProxiedImageAsset({
236
+ result: { image: "data:image/webp;base64,UklGRg==" },
237
+ })).toEqual({ kind: "b64", mime: "image/webp", base64: "UklGRg==" });
238
+ });
239
+
240
+ it("takes the first Seedream images[] URL", () => {
241
+ expect(extractProxiedImageAsset({
242
+ result: { images: ["https://cdn.example/a.jpeg", "https://cdn.example/b.jpeg"] },
243
+ })).toEqual({ kind: "url", url: "https://cdn.example/a.jpeg" });
244
+ });
171
245
  });
@@ -26,18 +26,27 @@ describe("buildProxiedImageParams", () => {
26
26
  expect("output_format" in params).toBe(false);
27
27
  });
28
28
 
29
- it("recraft (recraftv4) sends size + style, never a background flag", () => {
29
+ it("recraft (recraftv4*) sends bare prompt (no style/size; V4.1 Pro rejects 1024x1024)", () => {
30
30
  const params = buildProxiedImageParams("recraft", "a logo");
31
- expect(params).toEqual({
32
- prompt: "a logo",
33
- size: "1024x1024",
34
- style: "digital_illustration",
35
- });
31
+ expect(params).toEqual({ prompt: "a logo" });
32
+ expect("style" in params).toBe(false);
33
+ expect("size" in params).toBe(false);
36
34
  expect("background" in params).toBe(false);
37
35
  });
38
36
 
37
+ it("xai (grok-imagine-*) requests b64_json (Unified Billing ZDR/URL ban, v0.173.0)", () => {
38
+ expect(buildProxiedImageParams("xai", "a puppy")).toEqual({
39
+ prompt: "a puppy",
40
+ response_format: "b64_json",
41
+ });
42
+ });
43
+
44
+ it("bytedance (seedream-5-pro) sends bare prompt only (v0.171.0)", () => {
45
+ expect(buildProxiedImageParams("bytedance", "a watch")).toEqual({ prompt: "a watch" });
46
+ });
47
+
39
48
  it("never leaks the @cf request shape for any proxied provider", () => {
40
- for (const p of ["google", "openai", "recraft"] as const) {
49
+ for (const p of ["google", "openai", "recraft", "xai", "bytedance"] as const) {
41
50
  const params = buildProxiedImageParams(p, "x");
42
51
  for (const forbidden of ["width", "height", "steps", "negative_prompt"]) {
43
52
  expect(forbidden in params).toBe(false);