@skyphusion/create-prism 1.3.1 → 1.5.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.
- package/package.json +1 -1
- package/template/MIGRATIONS.md +4 -0
- package/template/README.md +52 -39
- package/template/docs/legal/INSTANCE-PRIVACY.md +7 -0
- package/template/migrations/0006_chat_cost.sql +22 -0
- package/template/migrations/0007_funnel_counters.sql +38 -0
- package/template/package.json +3 -3
- package/template/schema.sql +27 -2
- package/template/src/auth.ts +4 -0
- package/template/src/control-plane.ts +7 -0
- package/template/src/funnel.ts +96 -0
- package/template/src/longrun-params.ts +2 -0
- package/template/src/models.ts +105 -50
- package/template/src/parsers/workers-ai-sse.ts +1 -1
- package/template/src/pricing.ts +128 -0
- package/template/src/routes/chat.ts +49 -27
- package/template/src/routes/conversations.ts +3 -1
- package/template/src/routes/workflow.ts +3 -0
- package/template/src/version.ts +1 -1
- package/template/tests/catalog-drift.test.ts +103 -0
- package/template/tests/catalog-refresh-2026-12.test.ts +111 -0
- package/template/tests/funnel.test.ts +24 -0
- package/template/tests/pricing.test.ts +154 -0
- package/template/tests/sprint2-catalog.test.ts +9 -6
- package/template/tests/wrangler-template.test.ts +32 -0
- package/template/tests-integration/chat-cost.test.ts +269 -0
- package/template/tests-integration/funnel.test.ts +318 -0
- package/template/wrangler.example.toml +12 -11
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// prism#258: chat cost estimate. Pins the arithmetic (integer micro-USD, one
|
|
2
|
+
// rounding step, no float drift), the null-not-zero rules, the input checks
|
|
3
|
+
// (ernst S1-3) and the control-plane header source (S1-2).
|
|
4
|
+
import { describe, expect, it } from "vitest";
|
|
5
|
+
import { MODELS } from "../src/models";
|
|
6
|
+
import {
|
|
7
|
+
MAX_PLANE_MICRO_USD,
|
|
8
|
+
MAX_PRICED_TOKENS,
|
|
9
|
+
PRICED_AT,
|
|
10
|
+
TIER_200K,
|
|
11
|
+
chatCostUsd,
|
|
12
|
+
costMicroUsd,
|
|
13
|
+
microToUsd,
|
|
14
|
+
planeCostUsd,
|
|
15
|
+
px,
|
|
16
|
+
} from "../src/pricing";
|
|
17
|
+
|
|
18
|
+
const byId = (id: string) => MODELS.find((m) => m.id === id)!;
|
|
19
|
+
|
|
20
|
+
describe("costMicroUsd arithmetic", () => {
|
|
21
|
+
const sonnet46 = px(3_000_000, 15_000_000); // $3 in, $15 out per 1M
|
|
22
|
+
|
|
23
|
+
it("0 tokens costs 0 (a priced model, a real count of zero)", () => {
|
|
24
|
+
expect(costMicroUsd(sonnet46, 0, 0)).toBe(0);
|
|
25
|
+
expect(chatCostUsd(sonnet46, 0, 0)).toBe(0);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it("1 token at the lowest catalog rate rounds UP to 1 micro-USD, never down to 0", () => {
|
|
29
|
+
const rates = MODELS.filter((m) => m.pricing).flatMap((m) => [m.pricing!.in_micro_per_mtok, m.pricing!.out_micro_per_mtok]);
|
|
30
|
+
const lowest = Math.min(...rates.filter((r) => r > 0));
|
|
31
|
+
expect(lowest).toBe(17_000); // granite-4.0-h-micro input, $0.017 per 1M
|
|
32
|
+
expect(costMicroUsd(px(lowest, lowest), 1, 0)).toBe(1);
|
|
33
|
+
expect(costMicroUsd(px(lowest, lowest), 0, 1)).toBe(1);
|
|
34
|
+
expect(chatCostUsd(px(lowest, lowest), 1, 0)).toBe(0.000001);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it("a known figure: 1000 in + 500 out on $3/$15 is 10500 micro-USD = $0.0105", () => {
|
|
38
|
+
expect(costMicroUsd(sonnet46, 1000, 500)).toBe(10_500);
|
|
39
|
+
expect(chatCostUsd(sonnet46, 1000, 500)).toBe(0.0105);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it("rounds once, up, on the TOTAL (not per side)", () => {
|
|
43
|
+
// 3 in at 293000/M = 0.879 micro; 7 out at 2253000/M = 15.771 micro. Per-side
|
|
44
|
+
// round-up would give 1 + 16 = 17; one round on the total 16.65 gives 17 too,
|
|
45
|
+
// so also pin a case where the two differ: 1 in + 1 out at 400000/M each is
|
|
46
|
+
// 0.4 + 0.4 = 0.8 total -> 1, while per-side round-up would give 2.
|
|
47
|
+
expect(costMicroUsd(px(293_000, 2_253_000), 3, 7)).toBe(17);
|
|
48
|
+
expect(costMicroUsd(px(400_000, 400_000), 1, 1)).toBe(1);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it("a case that breaks naive float math is exact here", () => {
|
|
52
|
+
// $0.10 + $0.20 per 1M, one million tokens each: 0.1 + 0.2 is 0.30000000000000004 in floats.
|
|
53
|
+
expect(0.1 + 0.2).not.toBe(0.3); // the instrument: the naive path really does drift
|
|
54
|
+
expect(costMicroUsd(px(100_000, 200_000), 1_000_000, 1_000_000)).toBe(300_000);
|
|
55
|
+
expect(chatCostUsd(px(100_000, 200_000), 1_000_000, 1_000_000)).toBe(0.3);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it("the largest priced input stays exact in integer math", () => {
|
|
59
|
+
const p = px(180_000_000, 180_000_000); // $180 per 1M, the highest catalog rate
|
|
60
|
+
expect(costMicroUsd(p, MAX_PRICED_TOKENS, MAX_PRICED_TOKENS)).toBe(3_600_000_000);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it("microToUsd is one division", () => {
|
|
64
|
+
expect(microToUsd(1)).toBe(0.000001);
|
|
65
|
+
expect(microToUsd(1_234)).toBe(0.001234);
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
describe("null, never 0 (S1-5) and input checks (S1-3)", () => {
|
|
70
|
+
const p = px(3_000_000, 15_000_000);
|
|
71
|
+
|
|
72
|
+
it("unpriced model gives null", () => {
|
|
73
|
+
expect(costMicroUsd(undefined, 10, 10)).toBeNull();
|
|
74
|
+
expect(chatCostUsd(undefined, 10, 10)).toBeNull();
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("a missing count on either side gives null", () => {
|
|
78
|
+
expect(chatCostUsd(p, null, 5)).toBeNull();
|
|
79
|
+
expect(chatCostUsd(p, 5, null)).toBeNull();
|
|
80
|
+
expect(chatCostUsd(p, undefined, undefined)).toBeNull();
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it("strings, negatives, floats, NaN, Infinity and over-cap values give null", () => {
|
|
84
|
+
for (const bad of ["12", -1, 1.5, NaN, Infinity, -Infinity, MAX_PRICED_TOKENS + 1, Number.MAX_SAFE_INTEGER + 2, {}, true]) {
|
|
85
|
+
expect(chatCostUsd(p, bad, 5)).toBeNull();
|
|
86
|
+
expect(chatCostUsd(p, 5, bad)).toBeNull();
|
|
87
|
+
}
|
|
88
|
+
expect(chatCostUsd(p, MAX_PRICED_TOKENS, MAX_PRICED_TOKENS)).not.toBeNull(); // the cap itself is allowed
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it("a corrupt rate gives null, not NaN", () => {
|
|
92
|
+
expect(chatCostUsd({ ...p, in_micro_per_mtok: NaN }, 1, 1)).toBeNull();
|
|
93
|
+
expect(chatCostUsd({ ...p, out_micro_per_mtok: -5 }, 1, 1)).toBeNull();
|
|
94
|
+
expect(chatCostUsd({ ...p, in_micro_per_mtok: 1.5 }, 1, 1)).toBeNull();
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it("a long-context prompt on a tiered model gives null, not a base-tier guess", () => {
|
|
98
|
+
const tiered = px(2_000_000, 6_000_000, TIER_200K);
|
|
99
|
+
expect(chatCostUsd(tiered, TIER_200K, 10)).not.toBeNull();
|
|
100
|
+
expect(chatCostUsd(tiered, TIER_200K + 1, 10)).toBeNull();
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it("chatCostUsd never throws, whatever it is handed", () => {
|
|
104
|
+
expect(() => chatCostUsd({} as never, 1, 1)).not.toThrow();
|
|
105
|
+
expect(() => chatCostUsd(null as never, 1n as never, 1)).not.toThrow();
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
describe("planeCostUsd (S1-2): the plane's charge, from its header", () => {
|
|
110
|
+
const h = (o: Record<string, string>) => new Headers(o);
|
|
111
|
+
|
|
112
|
+
it("metered true with an integer micro-USD header is the cost", () => {
|
|
113
|
+
expect(planeCostUsd(h({ "prism-metered": "true", "prism-usage-micro-usd": "1234" }))).toBe(0.001234);
|
|
114
|
+
expect(planeCostUsd(h({ "prism-metered": "true", "prism-usage-micro-usd": "0" }))).toBe(0);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("metered false, absent, or malformed is null, not 0", () => {
|
|
118
|
+
expect(planeCostUsd(h({ "prism-metered": "false", "prism-usage-micro-usd": "0" }))).toBeNull();
|
|
119
|
+
expect(planeCostUsd(h({ "prism-usage-micro-usd": "1234" }))).toBeNull(); // no metered flag
|
|
120
|
+
expect(planeCostUsd(h({ "prism-metered": "true" }))).toBeNull(); // no amount
|
|
121
|
+
expect(planeCostUsd(h({}))).toBeNull();
|
|
122
|
+
for (const bad of ["", "-5", "1.5", "1e3", "abc", "12 34", "99999999999"]) {
|
|
123
|
+
expect(planeCostUsd(h({ "prism-metered": "true", "prism-usage-micro-usd": bad }))).toBeNull();
|
|
124
|
+
}
|
|
125
|
+
expect(planeCostUsd(h({ "prism-metered": "true", "prism-usage-micro-usd": String(MAX_PLANE_MICRO_USD + 1) }))).toBeNull();
|
|
126
|
+
expect(planeCostUsd(h({ "prism-metered": "true", "prism-usage-micro-usd": String(MAX_PLANE_MICRO_USD) }))).toBe(1000);
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
describe("catalog pricing (S1-6)", () => {
|
|
131
|
+
const chat = MODELS.filter((m) => m.type === "chat");
|
|
132
|
+
|
|
133
|
+
it("every priced entry has integer rates and a priced_at date; only chat entries carry pricing", () => {
|
|
134
|
+
for (const m of MODELS.filter((x) => x.pricing)) {
|
|
135
|
+
expect(m.type, m.id).toBe("chat");
|
|
136
|
+
expect(Number.isSafeInteger(m.pricing!.in_micro_per_mtok), m.id).toBe(true);
|
|
137
|
+
expect(Number.isSafeInteger(m.pricing!.out_micro_per_mtok), m.id).toBe(true);
|
|
138
|
+
expect(m.pricing!.priced_at, m.id).toBe(PRICED_AT);
|
|
139
|
+
expect(m.pricing!.priced_at).toMatch(/^\d{4}-\d{2}-\d{2}$/);
|
|
140
|
+
}
|
|
141
|
+
expect(chat.every((m) => m.pricing)).toBe(true); // every chat model was priced from its Cloudflare page
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it("spot checks against the Cloudflare model pages read on priced_at", () => {
|
|
145
|
+
expect(byId("anthropic/claude-opus-5.5").pricing).toMatchObject({ in_micro_per_mtok: 4_000_000, out_micro_per_mtok: 20_000_000 });
|
|
146
|
+
expect(byId("@cf/meta/llama-3.2-11b-vision-instruct").pricing).toMatchObject({ in_micro_per_mtok: 48_500, out_micro_per_mtok: 676_000 });
|
|
147
|
+
expect(byId("openai/o4-mini").pricing).toMatchObject({ in_micro_per_mtok: 1_100_000, out_micro_per_mtok: 4_400_000 });
|
|
148
|
+
expect(byId("xai/grok-4.7").pricing).toMatchObject({ in_micro_per_mtok: 2_000_000, out_micro_per_mtok: 6_000_000, max_in_tokens: TIER_200K });
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it("non-chat entries are unpriced here (image, video and speech cost is prism#261)", () => {
|
|
152
|
+
expect(MODELS.filter((m) => m.type !== "chat").every((m) => m.pricing === undefined)).toBe(true);
|
|
153
|
+
});
|
|
154
|
+
});
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Catalog pins for the v0.171.0 Sprint 2 model adds.
|
|
2
2
|
|
|
3
3
|
import { describe, it, expect } from "vitest";
|
|
4
|
-
import { MODELS } from "../src/models";
|
|
4
|
+
import { MODELS, OPENAI_COMPAT_CHAT_PROVIDERS } from "../src/models";
|
|
5
5
|
import { readFileSync } from "node:fs";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
import { dirname, join } from "node:path";
|
|
@@ -24,9 +24,11 @@ describe("v0.171.0 sprint 2 catalog entries", () => {
|
|
|
24
24
|
|
|
25
25
|
// Adversarial audit medium finding: stream allowlist must include moonshotai
|
|
26
26
|
// or handleChatStream 501s before runChatStream can route to callOpenAIStream.
|
|
27
|
+
// 2026-12 refresh: the allowlist and the stream switch read OPENAI_COMPAT_CHAT_PROVIDERS.
|
|
27
28
|
it("handleChatStream allowlist includes moonshotai (no 501 before dispatch)", () => {
|
|
28
|
-
expect(
|
|
29
|
-
expect(chatSrc).toMatch(
|
|
29
|
+
expect(OPENAI_COMPAT_CHAT_PROVIDERS.has("moonshotai")).toBe(true);
|
|
30
|
+
expect(chatSrc).toMatch(/!\(model\.provider && OPENAI_COMPAT_CHAT_PROVIDERS\.has\(model\.provider\)\)/);
|
|
31
|
+
expect(chatSrc).toMatch(/provider === "openai" \|\| \(model\.provider && OPENAI_COMPAT_CHAT_PROVIDERS\.has\(model\.provider\)\)/);
|
|
30
32
|
});
|
|
31
33
|
|
|
32
34
|
it("adds Grok Imagine Image as xai image", () => {
|
|
@@ -43,9 +45,10 @@ describe("v0.171.0 sprint 2 catalog entries", () => {
|
|
|
43
45
|
expect(m?.type).toBe("image");
|
|
44
46
|
});
|
|
45
47
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
expect(MODELS.find((x) => x.id === "@cf/moonshotai/kimi-k2.
|
|
48
|
+
// 2026-12 refresh: CF retired Workers AI Kimi K2.x on 2026-11-20 (HTTP 410). K3 stays.
|
|
49
|
+
it("keeps third-party K3 and drops retired Workers AI Kimi K2.x", () => {
|
|
50
|
+
expect(MODELS.find((x) => x.id === "@cf/moonshotai/kimi-k2.6")).toBeUndefined();
|
|
51
|
+
expect(MODELS.find((x) => x.id === "@cf/moonshotai/kimi-k2.7-code")).toBeUndefined();
|
|
49
52
|
expect(MODELS.find((x) => x.id === "moonshotai/kimi-k3")).toBeDefined();
|
|
50
53
|
});
|
|
51
54
|
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
// The v1.4.0 deploy failed with Cloudflare error 10143 because the template bound
|
|
7
|
+
// the skyphusion-search Worker, which no longer exists (search-mcp retired, #244).
|
|
8
|
+
// The deploy renders wrangler.toml from this template, so an active binding to a
|
|
9
|
+
// missing Worker fails every deploy. Web search stays opt-in until #276 lands.
|
|
10
|
+
describe("wrangler.example.toml web search binding", () => {
|
|
11
|
+
const toml = readFileSync(
|
|
12
|
+
join(dirname(fileURLToPath(import.meta.url)), "../wrangler.example.toml"),
|
|
13
|
+
"utf8",
|
|
14
|
+
);
|
|
15
|
+
const active = toml.split("\n").filter((l) => !l.trim().startsWith("#"));
|
|
16
|
+
|
|
17
|
+
it("control: the commented-out block is still there for operators who run the Worker", () => {
|
|
18
|
+
expect(toml).toMatch(/^# \[\[services\]\]$/m);
|
|
19
|
+
expect(toml).toMatch(/^# service = "skyphusion-search"$/m);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it("binds no skyphusion-search service by default", () => {
|
|
23
|
+
expect(active.some((l) => l.includes("skyphusion-search"))).toBe(false);
|
|
24
|
+
expect(active.some((l) => l.trim() === "[[services]]")).toBe(false);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it("still renders the sections the deploy depends on", () => {
|
|
28
|
+
expect(active.some((l) => l.trim() === "[assets]")).toBe(true);
|
|
29
|
+
expect(toml).toContain('# AUTH_MODE = "public"');
|
|
30
|
+
expect(toml).toContain('# VEC_METADATA_FILTER = "on"');
|
|
31
|
+
});
|
|
32
|
+
});
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
// prism#258: cost_usd on the D1 chat row and on the stream `done` event, end to
|
|
2
|
+
// end through the real fetch handler (workerd, local D1), with upstream fetch
|
|
3
|
+
// stubbed. Covers: BYOK non-stream, BYOK stream, an unpriced/no-usage turn
|
|
4
|
+
// (null, not 0), and the control-plane path where cost comes from the plane
|
|
5
|
+
// header and NOT from the playground catalog (ernst S1-2). Also proves the
|
|
6
|
+
// migration lands where CI applies it (S1-1).
|
|
7
|
+
|
|
8
|
+
import { env, SELF } from "cloudflare:test";
|
|
9
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
10
|
+
import { MODELS } from "../src/models";
|
|
11
|
+
import schemaSql from "../schema.sql?raw";
|
|
12
|
+
|
|
13
|
+
const migrationFiles = import.meta.glob("../migrations/*.sql", { query: "?raw", import: "default", eager: true }) as Record<string, string>;
|
|
14
|
+
|
|
15
|
+
function statementsOf(sql: string): string[] {
|
|
16
|
+
return sql
|
|
17
|
+
.split("\n")
|
|
18
|
+
.map((line) => line.replace(/--.*$/, ""))
|
|
19
|
+
.join("\n")
|
|
20
|
+
.split(";")
|
|
21
|
+
.map((s) => s.trim())
|
|
22
|
+
.filter((s) => s.length > 0);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function applyAll(db: D1Database, sql: string): Promise<void> {
|
|
26
|
+
for (const stmt of statementsOf(sql)) {
|
|
27
|
+
try {
|
|
28
|
+
await db.prepare(stmt).run();
|
|
29
|
+
} catch (e) {
|
|
30
|
+
const msg = String((e as { message?: string })?.message ?? e);
|
|
31
|
+
if (/duplicate column name|already exists/i.test(msg)) continue;
|
|
32
|
+
throw e;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const anyEnv = env as unknown as { AUTH_MODE?: string };
|
|
38
|
+
const USER_ACCT = "0123456789abcdef0123456789abcdef";
|
|
39
|
+
const PCP_KEY = `pcp_${"0123456789abcdef"}_${"A".repeat(43)}`;
|
|
40
|
+
const SONNET = "anthropic/claude-sonnet-4-6"; // legacy gateway path, priced $3 in / $15 out
|
|
41
|
+
const realFetch = globalThis.fetch;
|
|
42
|
+
|
|
43
|
+
function cookieFrom(res: Response): string {
|
|
44
|
+
return res.headers.get("set-cookie")!.split(";")[0];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function req(path: string, opts: { method?: string; body?: unknown; cookie?: string } = {}): Promise<Response> {
|
|
48
|
+
const headers = new Headers();
|
|
49
|
+
if (opts.body !== undefined) headers.set("content-type", "application/json");
|
|
50
|
+
if (opts.cookie) headers.set("cookie", opts.cookie);
|
|
51
|
+
headers.set("cf-connecting-ip", "203.0.113.9");
|
|
52
|
+
return SELF.fetch(`https://prism.test${path}`, {
|
|
53
|
+
method: opts.method ?? "GET",
|
|
54
|
+
headers,
|
|
55
|
+
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function signupAndConfigure(username: string, prefs: Record<string, unknown>): Promise<string> {
|
|
60
|
+
const res = await req("/api/auth/signup", { method: "POST", body: { username, password: "password123" } });
|
|
61
|
+
expect(res.status).toBe(201);
|
|
62
|
+
const cookie = cookieFrom(res);
|
|
63
|
+
const p = await req("/api/prefs", { method: "PATCH", cookie, body: prefs });
|
|
64
|
+
expect(p.status).toBe(200);
|
|
65
|
+
return cookie;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const BYOK = { account_id: USER_ACCT, gateway_id: "gw", cf_aig_token: "tok" };
|
|
69
|
+
|
|
70
|
+
interface UpstreamCall { url: string }
|
|
71
|
+
let calls: UpstreamCall[];
|
|
72
|
+
let upstream: (url: string) => Response | null;
|
|
73
|
+
|
|
74
|
+
beforeEach(async () => {
|
|
75
|
+
await applyAll(env.DB, schemaSql);
|
|
76
|
+
for (const t of ["chats", "user_prefs", "users", "sessions", "auth_attempts", "conversation_compact"]) {
|
|
77
|
+
await env.DB.prepare(`DELETE FROM ${t}`).run();
|
|
78
|
+
}
|
|
79
|
+
anyEnv.AUTH_MODE = "public";
|
|
80
|
+
calls = [];
|
|
81
|
+
upstream = () => null;
|
|
82
|
+
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
83
|
+
const url = input instanceof Request ? input.url : String(input);
|
|
84
|
+
const r = upstream(url);
|
|
85
|
+
if (r) {
|
|
86
|
+
calls.push({ url });
|
|
87
|
+
return r;
|
|
88
|
+
}
|
|
89
|
+
return realFetch(input, init);
|
|
90
|
+
}) as typeof fetch;
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
afterEach(() => {
|
|
94
|
+
globalThis.fetch = realFetch;
|
|
95
|
+
delete anyEnv.AUTH_MODE;
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
function anthropicJson(usage: unknown, url = "https://api.cloudflare.com/"): Response {
|
|
99
|
+
const message = {
|
|
100
|
+
id: "msg_1", type: "message", role: "assistant", model: "stub",
|
|
101
|
+
content: [{ type: "text", text: "hello" }], stop_reason: "end_turn", usage,
|
|
102
|
+
};
|
|
103
|
+
// The REST (account-scoped) door wraps the message; the gateway door does not.
|
|
104
|
+
const wrapped = url.startsWith("https://api.cloudflare.com/") ? { success: true, errors: [], result: message } : message;
|
|
105
|
+
return new Response(JSON.stringify(wrapped), { headers: { "content-type": "application/json" } });
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function anthropicSse(inTok: unknown, outTok: unknown): Response {
|
|
109
|
+
const frames = [
|
|
110
|
+
["message_start", { type: "message_start", message: { id: "m", role: "assistant", usage: { input_tokens: inTok, output_tokens: 1 } } }],
|
|
111
|
+
["content_block_delta", { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "hi" } }],
|
|
112
|
+
["message_delta", { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: outTok } }],
|
|
113
|
+
["message_stop", { type: "message_stop" }],
|
|
114
|
+
];
|
|
115
|
+
const body = frames.map(([ev, d]) => `event: ${ev}\ndata: ${JSON.stringify(d)}\n\n`).join("");
|
|
116
|
+
return new Response(body, { headers: { "content-type": "text/event-stream" } });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function sseEvents(res: Response): Promise<Array<Record<string, unknown>>> {
|
|
120
|
+
const text = await res.text();
|
|
121
|
+
return text
|
|
122
|
+
.split("\n")
|
|
123
|
+
.filter((l) => l.startsWith("data: "))
|
|
124
|
+
.map((l) => JSON.parse(l.slice(6)) as Record<string, unknown>);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function lastRow(): Promise<{ cost_usd: number | null; tokens_in: number | null; tokens_out: number | null; model: string }> {
|
|
128
|
+
const r = await env.DB.prepare(`SELECT cost_usd, tokens_in, tokens_out, model FROM chats ORDER BY id DESC LIMIT 1`).first();
|
|
129
|
+
return r as never;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
describe("migration location (S1-1)", () => {
|
|
133
|
+
it("the column ships as a numbered file in migrations/ (where CI applies it) and in schema.sql", async () => {
|
|
134
|
+
const names = Object.keys(migrationFiles).sort();
|
|
135
|
+
expect(names.some((n) => n.endsWith("0006_chat_cost.sql"))).toBe(true);
|
|
136
|
+
// CI applies only migrations/. Assert the file there adds exactly the column
|
|
137
|
+
// the Worker binds, nullable with no default.
|
|
138
|
+
const m = names.find((n) => n.endsWith("0006_chat_cost.sql"))!;
|
|
139
|
+
expect(statementsOf(migrationFiles[m])).toEqual(["ALTER TABLE chats ADD COLUMN cost_usd REAL"]);
|
|
140
|
+
// schema.sql (fresh DB) carries the same column.
|
|
141
|
+
const cols = (await env.DB.prepare(`PRAGMA table_info(chats)`).all()).results as Array<{ name: string; notnull: number; dflt_value: unknown }>;
|
|
142
|
+
const c = cols.find((x) => x.name === "cost_usd")!;
|
|
143
|
+
expect(c).toBeDefined();
|
|
144
|
+
expect(c.notnull).toBe(0);
|
|
145
|
+
expect(c.dflt_value).toBeNull();
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
describe("BYOK non-stream /api/chat", () => {
|
|
150
|
+
it("a priced chat model: the D1 row and the response carry cost_usd", async () => {
|
|
151
|
+
upstream = (u) => (u.startsWith("https://gateway.ai.cloudflare.com/") || u.startsWith("https://api.cloudflare.com/") ? anthropicJson({ input_tokens: 1000, output_tokens: 500 }, u) : null);
|
|
152
|
+
const cookie = await signupAndConfigure("cora", BYOK);
|
|
153
|
+
const res = await req("/api/chat", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
|
|
154
|
+
expect(res.status).toBe(200);
|
|
155
|
+
const body = (await res.json()) as { cost_usd: number | null };
|
|
156
|
+
expect(body.cost_usd).toBe(0.0105); // 1000 * $3/M + 500 * $15/M
|
|
157
|
+
const row = await lastRow();
|
|
158
|
+
expect(row).toMatchObject({ model: SONNET, tokens_in: 1000, tokens_out: 500, cost_usd: 0.0105 });
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it("a missing or unsafe token count stores null, not 0, and the chat still succeeds", async () => {
|
|
162
|
+
upstream = (u) => anthropicJson({ input_tokens: "lots", output_tokens: -4 }, u);
|
|
163
|
+
const cookie = await signupAndConfigure("dax", BYOK);
|
|
164
|
+
const res = await req("/api/chat", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
|
|
165
|
+
expect(res.status).toBe(200);
|
|
166
|
+
expect(((await res.json()) as { cost_usd: unknown }).cost_usd).toBeNull();
|
|
167
|
+
expect((await lastRow()).cost_usd).toBeNull();
|
|
168
|
+
// No usage object at all.
|
|
169
|
+
upstream = (u) => anthropicJson(undefined, u);
|
|
170
|
+
const res2 = await req("/api/chat", { method: "POST", cookie, body: { model: SONNET, user_input: "again" } });
|
|
171
|
+
expect(res2.status).toBe(200);
|
|
172
|
+
expect((await lastRow()).cost_usd).toBeNull();
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
describe("BYOK stream /api/chat/stream", () => {
|
|
177
|
+
it("the done event and the D1 row both carry cost_usd", async () => {
|
|
178
|
+
upstream = (u) => (u.startsWith("https://gateway.ai.cloudflare.com/") || u.startsWith("https://api.cloudflare.com/") ? anthropicSse(2000, 1000) : null);
|
|
179
|
+
const cookie = await signupAndConfigure("eli", BYOK);
|
|
180
|
+
const res = await req("/api/chat/stream", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
|
|
181
|
+
expect(res.status).toBe(200);
|
|
182
|
+
const done = (await sseEvents(res)).find((e) => e.type === "done")!;
|
|
183
|
+
expect(done).toBeDefined();
|
|
184
|
+
expect(done.tokens_in).toBe(2000);
|
|
185
|
+
expect(done.tokens_out).toBe(1000);
|
|
186
|
+
expect(done.cost_usd).toBe(0.021); // 2000 * $3/M + 1000 * $15/M = 6000 + 15000 micro
|
|
187
|
+
expect((await lastRow()).cost_usd).toBe(0.021);
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it("no usage in the stream: done carries null (not 0) and so does the row", async () => {
|
|
191
|
+
upstream = () => new Response(`event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "x" } })}\n\n`, { headers: { "content-type": "text/event-stream" } });
|
|
192
|
+
const cookie = await signupAndConfigure("fay", BYOK);
|
|
193
|
+
const res = await req("/api/chat/stream", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
|
|
194
|
+
const done = (await sseEvents(res)).find((e) => e.type === "done")!;
|
|
195
|
+
expect(done).toBeDefined();
|
|
196
|
+
expect(done.cost_usd).toBeNull();
|
|
197
|
+
expect((await lastRow()).cost_usd).toBeNull();
|
|
198
|
+
});
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
describe("control-plane path: the plane's charge, not the catalog (S1-2)", () => {
|
|
202
|
+
const PLANE = "https://play-proxy.skyphusion.org/v1/chat/completions";
|
|
203
|
+
function plane(headers: Record<string, string>, usage: unknown = { prompt_tokens: 1000, completion_tokens: 500 }) {
|
|
204
|
+
return (u: string) =>
|
|
205
|
+
u === PLANE
|
|
206
|
+
? new Response(JSON.stringify({ model: SONNET, choices: [{ message: { role: "assistant", content: "from plane" } }], usage }), {
|
|
207
|
+
headers: { "content-type": "application/json", "prism-request-id": "req_1", ...headers },
|
|
208
|
+
})
|
|
209
|
+
: null;
|
|
210
|
+
}
|
|
211
|
+
const CATALOG_PRICE = 0.0105; // what the playground list price would give for 1000 in + 500 out
|
|
212
|
+
|
|
213
|
+
it("non-stream: cost_usd is the header figure, which differs from the catalog price", async () => {
|
|
214
|
+
upstream = plane({ "prism-metered": "true", "prism-usage-micro-usd": "123456" });
|
|
215
|
+
const cookie = await signupAndConfigure("gus", { control_plane_key: PCP_KEY });
|
|
216
|
+
const res = await req("/api/chat", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
|
|
217
|
+
expect(res.status).toBe(200);
|
|
218
|
+
expect(calls.map((c) => c.url)).toEqual([PLANE]);
|
|
219
|
+
const body = (await res.json()) as { cost_usd: number | null };
|
|
220
|
+
expect(body.cost_usd).toBe(0.123456);
|
|
221
|
+
expect(body.cost_usd).not.toBe(CATALOG_PRICE);
|
|
222
|
+
expect((await lastRow()).cost_usd).toBe(0.123456);
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
it("stream: the done event carries the same plane figure", async () => {
|
|
226
|
+
upstream = plane({ "prism-metered": "true", "prism-usage-micro-usd": "777" });
|
|
227
|
+
const cookie = await signupAndConfigure("hal", { control_plane_key: PCP_KEY });
|
|
228
|
+
const res = await req("/api/chat/stream", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
|
|
229
|
+
const done = (await sseEvents(res)).find((e) => e.type === "done")!;
|
|
230
|
+
expect(done.cost_usd).toBe(0.000777);
|
|
231
|
+
expect((await lastRow()).cost_usd).toBe(0.000777);
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
it("header absent: null on the row and on done, even though the catalog could price it", async () => {
|
|
235
|
+
upstream = plane({});
|
|
236
|
+
const cookie = await signupAndConfigure("ivy", { control_plane_key: PCP_KEY });
|
|
237
|
+
const res = await req("/api/chat/stream", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
|
|
238
|
+
const done = (await sseEvents(res)).find((e) => e.type === "done")!;
|
|
239
|
+
expect(done.cost_usd).toBeNull();
|
|
240
|
+
expect((await lastRow()).cost_usd).toBeNull();
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
it("prism-metered false: null, not the header's 0", async () => {
|
|
244
|
+
upstream = plane({ "prism-metered": "false", "prism-usage-micro-usd": "0" });
|
|
245
|
+
const cookie = await signupAndConfigure("jon", { control_plane_key: PCP_KEY });
|
|
246
|
+
const res = await req("/api/chat", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
|
|
247
|
+
expect(((await res.json()) as { cost_usd: unknown }).cost_usd).toBeNull();
|
|
248
|
+
expect((await lastRow()).cost_usd).toBeNull();
|
|
249
|
+
});
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
describe("a pricing fault never fails the chat write", () => {
|
|
253
|
+
it("a model with corrupt pricing still persists the row, with null cost", async () => {
|
|
254
|
+
const m = MODELS.find((x) => x.id === SONNET)!;
|
|
255
|
+
const saved = m.pricing;
|
|
256
|
+
m.pricing = { in_micro_per_mtok: Number.NaN, out_micro_per_mtok: 1, priced_at: "2026-12-04" };
|
|
257
|
+
try {
|
|
258
|
+
upstream = (u) => anthropicJson({ input_tokens: 10, output_tokens: 10 }, u);
|
|
259
|
+
const cookie = await signupAndConfigure("kit", BYOK);
|
|
260
|
+
const res = await req("/api/chat", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
|
|
261
|
+
expect(res.status).toBe(200);
|
|
262
|
+
const row = await lastRow();
|
|
263
|
+
expect(row.tokens_in).toBe(10);
|
|
264
|
+
expect(row.cost_usd).toBeNull();
|
|
265
|
+
} finally {
|
|
266
|
+
m.pricing = saved;
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
});
|