@skyphusion/create-prism 0.1.0 → 1.0.0

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 (60) 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 +227 -48
  6. package/template/docs/legal/README.md +1 -0
  7. package/template/migrations/0002_auth_public_mode.sql +32 -0
  8. package/template/migrations/0003_conversation_compact.sql +24 -0
  9. package/template/package.json +6 -6
  10. package/template/public/app.js +128 -19
  11. package/template/public/index.html +50 -4
  12. package/template/public/styles.css +16 -2
  13. package/template/schema.sql +17 -0
  14. package/template/src/auth-kdf.ts +7 -4
  15. package/template/src/auth.ts +11 -2
  16. package/template/src/control-plane.ts +254 -0
  17. package/template/src/conversation-context.ts +126 -0
  18. package/template/src/env.ts +15 -0
  19. package/template/src/gateway-credentials.ts +23 -4
  20. package/template/src/health-schema.ts +4 -0
  21. package/template/src/index.ts +73 -3982
  22. package/template/src/longrun-params.ts +4 -2
  23. package/template/src/models.ts +65 -19
  24. package/template/src/output-extract.ts +58 -8
  25. package/template/src/parsers/openai-sse.ts +43 -14
  26. package/template/src/providers/anthropic.ts +105 -0
  27. package/template/src/providers/openai-image.ts +66 -0
  28. package/template/src/providers/openai.ts +79 -13
  29. package/template/src/providers/xai.ts +91 -0
  30. package/template/src/proxied-image-params.ts +29 -16
  31. package/template/src/routes/artifacts.ts +51 -0
  32. package/template/src/routes/chat.ts +1682 -0
  33. package/template/src/routes/conversations.ts +494 -0
  34. package/template/src/routes/documents.ts +262 -0
  35. package/template/src/routes/health.ts +105 -0
  36. package/template/src/routes/history.ts +92 -0
  37. package/template/src/routes/prefs.ts +95 -0
  38. package/template/src/routes/projects.ts +574 -0
  39. package/template/src/routes/rag.ts +657 -0
  40. package/template/src/routes/shared.ts +226 -0
  41. package/template/src/routes/workflow.ts +304 -0
  42. package/template/src/stt-session.ts +1 -1
  43. package/template/src/user-prefs.ts +10 -0
  44. package/template/src/zip.ts +7 -0
  45. package/template/tests/anthropic-binding.test.ts +181 -0
  46. package/template/tests/control-plane.test.ts +112 -0
  47. package/template/tests/conversation-compact.test.ts +103 -0
  48. package/template/tests/gateway-credentials.test.ts +37 -0
  49. package/template/tests/longrun-params.test.ts +19 -0
  50. package/template/tests/openai-image.test.ts +47 -0
  51. package/template/tests/openai-responses.test.ts +78 -0
  52. package/template/tests/openai-sse.test.ts +28 -0
  53. package/template/tests/output-extract.test.ts +75 -1
  54. package/template/tests/proxied-image-params.test.ts +16 -7
  55. package/template/tests/sprint1-catalog.test.ts +27 -0
  56. package/template/tests/sprint2-catalog.test.ts +51 -0
  57. package/template/tests/sprint3-catalog.test.ts +29 -0
  58. package/template/tests/xai-binding.test.ts +127 -0
  59. package/template/tests-integration/worker.test.ts +9 -2
  60. 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
+ });
@@ -0,0 +1,103 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ applyCompactToPriorTurns,
4
+ buildCompactSystemBlock,
5
+ formatTurnsForSummary,
6
+ normalizeSummary,
7
+ splitTurnsForCompact,
8
+ COMPACT_SUMMARY_MAX_CHARS,
9
+ DEFAULT_KEEP_RECENT,
10
+ } from "../src/conversation-context";
11
+
12
+ const turns = [
13
+ { user_input: "hi", output: "hello", turn_index: 0 },
14
+ { user_input: "what is 2+2", output: "4", turn_index: 1 },
15
+ { user_input: "and 3+3", output: "6", turn_index: 2 },
16
+ { user_input: "thanks", output: "anytime", turn_index: 3 },
17
+ ];
18
+
19
+ describe("splitTurnsForCompact", () => {
20
+ it("keeps the last N raw and summarizes the rest", () => {
21
+ const { summarize, keep } = splitTurnsForCompact(turns, 2);
22
+ expect(summarize.map((t) => t.turn_index)).toEqual([0, 1]);
23
+ expect(keep.map((t) => t.turn_index)).toEqual([2, 3]);
24
+ });
25
+
26
+ it("summarizes nothing when keep_recent covers the whole thread", () => {
27
+ const { summarize, keep } = splitTurnsForCompact(turns, 10);
28
+ expect(summarize).toEqual([]);
29
+ expect(keep).toHaveLength(4);
30
+ });
31
+
32
+ it("default keep matches DEFAULT_KEEP_RECENT (2)", () => {
33
+ expect(DEFAULT_KEEP_RECENT).toBe(2);
34
+ const { keep } = splitTurnsForCompact(turns, DEFAULT_KEEP_RECENT);
35
+ expect(keep).toHaveLength(2);
36
+ });
37
+ });
38
+
39
+ describe("formatTurnsForSummary", () => {
40
+ it("labels user and assistant and separates turns", () => {
41
+ const text = formatTurnsForSummary(turns.slice(0, 2));
42
+ expect(text).toContain("User:\nhi");
43
+ expect(text).toContain("Assistant:\nhello");
44
+ expect(text).toContain("---");
45
+ expect(text).toContain("what is 2+2");
46
+ });
47
+ });
48
+
49
+ describe("buildCompactSystemBlock", () => {
50
+ it("wraps the summary with markers the model can anchor on", () => {
51
+ const block = buildCompactSystemBlock("User prefers brief answers.");
52
+ expect(block).toMatch(/\[Compacted earlier conversation\]/);
53
+ expect(block).toContain("User prefers brief answers.");
54
+ expect(block).toMatch(/\[End compacted context\]/);
55
+ });
56
+
57
+ it("returns empty for blank summary", () => {
58
+ expect(buildCompactSystemBlock(" ")).toBe("");
59
+ });
60
+ });
61
+
62
+ describe("applyCompactToPriorTurns", () => {
63
+ it("without compact state returns all usable turns", () => {
64
+ const ctx = applyCompactToPriorTurns(turns, null);
65
+ expect(ctx.priorTurns).toHaveLength(4);
66
+ expect(ctx.compactBlock).toBeNull();
67
+ expect(ctx.turnIndex).toBe(4);
68
+ });
69
+
70
+ it("with compact state drops covered turns and injects the block", () => {
71
+ const ctx = applyCompactToPriorTurns(turns, {
72
+ summary: "Discussed arithmetic; answers were short.",
73
+ through_turn_index: 1,
74
+ keep_recent: 2,
75
+ model: "@cf/meta/llama-3.2-3b-instruct",
76
+ updated_at: "2026-08-06T00:00:00Z",
77
+ });
78
+ expect(ctx.priorTurns.map((t) => t.user_input)).toEqual(["and 3+3", "thanks"]);
79
+ expect(ctx.compactBlock).toContain("Discussed arithmetic");
80
+ expect(ctx.turnIndex).toBe(4);
81
+ });
82
+
83
+ it("skips empty/failed turns when building prior pairs", () => {
84
+ const mixed = [
85
+ ...turns,
86
+ { user_input: "oops", output: "", turn_index: 4 },
87
+ ];
88
+ const ctx = applyCompactToPriorTurns(mixed, null);
89
+ expect(ctx.priorTurns).toHaveLength(4);
90
+ // Next index still advances past the empty row's index.
91
+ expect(ctx.turnIndex).toBe(5);
92
+ });
93
+ });
94
+
95
+ describe("normalizeSummary", () => {
96
+ it("trims and truncates oversized summaries", () => {
97
+ expect(normalizeSummary(" short ")).toBe("short");
98
+ const long = "x".repeat(COMPACT_SUMMARY_MAX_CHARS + 50);
99
+ const out = normalizeSummary(long);
100
+ expect(out.length).toBeLessThanOrEqual(COMPACT_SUMMARY_MAX_CHARS + 30);
101
+ expect(out).toContain("[summary truncated]");
102
+ });
103
+ });
@@ -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
  });