@skyphusion/create-prism 1.4.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 +2 -2
- 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/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/models.ts +63 -57
- package/template/src/pricing.ts +128 -0
- package/template/src/routes/chat.ts +34 -4
- 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/funnel.test.ts +24 -0
- package/template/tests/pricing.test.ts +154 -0
- package/template/tests-integration/chat-cost.test.ts +269 -0
- package/template/tests-integration/funnel.test.ts +318 -0
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// Chat cost estimate (prism#258, Part of prism#251 Sprint 1).
|
|
2
|
+
//
|
|
3
|
+
// DISPLAY ONLY. cost_usd is never an input to a limit, a charge, or a quota.
|
|
4
|
+
// It is an ESTIMATE of what a chat turn cost at the model's published list
|
|
5
|
+
// rate, not a bill:
|
|
6
|
+
// - Rates are copied by hand from each model's Cloudflare model page and go
|
|
7
|
+
// stale. `priced_at` on every entry says when they were read.
|
|
8
|
+
// - The cached-input rate is NOT applied: no stream parser reads a cached
|
|
9
|
+
// token count yet, so every input token is priced at the full input rate.
|
|
10
|
+
// - Gemini thinking tokens are left out of the output count upstream
|
|
11
|
+
// (src/output-extract.ts), so a thinking turn is under-counted.
|
|
12
|
+
// - Some models have a long-context tier. Only the base tier is priced, and
|
|
13
|
+
// only when the prompt is at or under `max_in_tokens`; above it the cost
|
|
14
|
+
// is null (unknown), never a base-tier guess.
|
|
15
|
+
// - On the control-plane path the plane's own charge is used instead (see
|
|
16
|
+
// planeCostUsd). In BYOK mode the user's Cloudflare bill is the truth.
|
|
17
|
+
//
|
|
18
|
+
// Rates are INTEGER micro-USD per 1M tokens ($1.00 per 1M = 1_000_000). Cost is
|
|
19
|
+
// integer math with ONE rounding step, UP on the total (as the plane does,
|
|
20
|
+
// prism-control-plane src/meter.ts), done in BigInt so no float is ever in the
|
|
21
|
+
// arithmetic. The result is converted to USD once, by a single division.
|
|
22
|
+
//
|
|
23
|
+
// Null is not zero. Zero means free and exists only for a real zero rate. An
|
|
24
|
+
// unpriced model, a missing or unsafe token count, a non-chat row and a failed
|
|
25
|
+
// row all give null.
|
|
26
|
+
|
|
27
|
+
/** Date the rates in src/models.ts were read from the Cloudflare model pages. */
|
|
28
|
+
export const PRICED_AT = "2026-12-04";
|
|
29
|
+
|
|
30
|
+
/** Largest token count on either side that we will price (10M). Above it: null. */
|
|
31
|
+
export const MAX_PRICED_TOKENS = 10_000_000;
|
|
32
|
+
|
|
33
|
+
/** Largest plane charge we will show, micro-USD ($1000). Above it: null. */
|
|
34
|
+
export const MAX_PLANE_MICRO_USD = 1_000_000_000;
|
|
35
|
+
|
|
36
|
+
/** Base-tier ceilings for models with a long-context tier. */
|
|
37
|
+
export const TIER_200K = 200_000;
|
|
38
|
+
export const TIER_512K = 512_000;
|
|
39
|
+
/** The model page names a short and a long tier but not the boundary: price only below a conservative 128k. */
|
|
40
|
+
export const TIER_UNSTATED = 128_000;
|
|
41
|
+
|
|
42
|
+
export interface ModelPricing {
|
|
43
|
+
/** Input rate, integer micro-USD per 1M tokens. */
|
|
44
|
+
in_micro_per_mtok: number;
|
|
45
|
+
/** Output rate, integer micro-USD per 1M tokens. */
|
|
46
|
+
out_micro_per_mtok: number;
|
|
47
|
+
/** Date the rate was read from the model page (YYYY-MM-DD). */
|
|
48
|
+
priced_at: string;
|
|
49
|
+
/** Base tier only: when the prompt has more tokens than this, cost is null. */
|
|
50
|
+
max_in_tokens?: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Catalog helper: integer micro-USD per 1M tokens, stamped with PRICED_AT. */
|
|
54
|
+
export function px(inMicro: number, outMicro: number, maxInTokens?: number): ModelPricing {
|
|
55
|
+
const p: ModelPricing = { in_micro_per_mtok: inMicro, out_micro_per_mtok: outMicro, priced_at: PRICED_AT };
|
|
56
|
+
if (maxInTokens !== undefined) p.max_in_tokens = maxInTokens;
|
|
57
|
+
return p;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function isCount(n: unknown): n is number {
|
|
61
|
+
return typeof n === "number" && Number.isSafeInteger(n) && n >= 0 && n <= MAX_PRICED_TOKENS;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function isRate(n: unknown): n is number {
|
|
65
|
+
return typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Cost in integer micro-USD, or null when it cannot be priced honestly.
|
|
70
|
+
* Both counts must be safe non-negative integers at or under MAX_PRICED_TOKENS.
|
|
71
|
+
*/
|
|
72
|
+
export function costMicroUsd(
|
|
73
|
+
pricing: ModelPricing | undefined,
|
|
74
|
+
tokensIn: unknown,
|
|
75
|
+
tokensOut: unknown,
|
|
76
|
+
): number | null {
|
|
77
|
+
if (!pricing) return null;
|
|
78
|
+
if (!isCount(tokensIn) || !isCount(tokensOut)) return null;
|
|
79
|
+
if (!isRate(pricing.in_micro_per_mtok) || !isRate(pricing.out_micro_per_mtok)) return null;
|
|
80
|
+
if (pricing.max_in_tokens !== undefined && tokensIn > pricing.max_in_tokens) return null;
|
|
81
|
+
const total =
|
|
82
|
+
BigInt(tokensIn) * BigInt(pricing.in_micro_per_mtok) +
|
|
83
|
+
BigInt(tokensOut) * BigInt(pricing.out_micro_per_mtok);
|
|
84
|
+
const micro = (total + 999_999n) / 1_000_000n; // one rounding step, up
|
|
85
|
+
return Number(micro);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Integer micro-USD to USD: one division, so the value prints as a clean 6-decimal figure. */
|
|
89
|
+
export function microToUsd(micro: number): number {
|
|
90
|
+
return micro / 1_000_000;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Catalog-priced USD for a chat turn, or null. Never throws: a pricing error
|
|
95
|
+
* must not fail the chat write, so any fault becomes null.
|
|
96
|
+
*/
|
|
97
|
+
export function chatCostUsd(
|
|
98
|
+
pricing: ModelPricing | undefined,
|
|
99
|
+
tokensIn: unknown,
|
|
100
|
+
tokensOut: unknown,
|
|
101
|
+
): number | null {
|
|
102
|
+
try {
|
|
103
|
+
const micro = costMicroUsd(pricing, tokensIn, tokensOut);
|
|
104
|
+
return micro === null ? null : microToUsd(micro);
|
|
105
|
+
} catch {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Control-plane path: the plane already charged the user and says how much in
|
|
112
|
+
* `prism-usage-micro-usd`, with `prism-metered: true`. That figure is the cost.
|
|
113
|
+
* If the plane did not meter the request, or the header is absent or malformed,
|
|
114
|
+
* the cost is null. Never the playground list price: operator overrides,
|
|
115
|
+
* rounding and later reconcile make the two differ.
|
|
116
|
+
*/
|
|
117
|
+
export function planeCostUsd(headers: Headers): number | null {
|
|
118
|
+
try {
|
|
119
|
+
if ((headers.get("prism-metered") ?? "").trim().toLowerCase() !== "true") return null;
|
|
120
|
+
const raw = (headers.get("prism-usage-micro-usd") ?? "").trim();
|
|
121
|
+
if (!/^\d{1,10}$/.test(raw)) return null;
|
|
122
|
+
const micro = Number(raw);
|
|
123
|
+
if (!Number.isSafeInteger(micro) || micro > MAX_PLANE_MICRO_USD) return null;
|
|
124
|
+
return microToUsd(micro);
|
|
125
|
+
} catch {
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
@@ -29,6 +29,8 @@ import {
|
|
|
29
29
|
resolveAttachmentKeys,
|
|
30
30
|
safeParseJson,
|
|
31
31
|
} from "./shared";
|
|
32
|
+
import { chatCostUsd } from "../pricing";
|
|
33
|
+
import { recordFirstOutput } from "../funnel";
|
|
32
34
|
import { controlPlaneChat, type ControlPlaneChatMessage } from "../control-plane";
|
|
33
35
|
import type {
|
|
34
36
|
ChatRequest,
|
|
@@ -397,6 +399,9 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
|
|
|
397
399
|
const start = Date.now();
|
|
398
400
|
let result: unknown;
|
|
399
401
|
let logId: string | null = null;
|
|
402
|
+
// prism#258: on the control-plane path this is the plane's own charge; on every
|
|
403
|
+
// other path it is the catalog estimate, computed after the call.
|
|
404
|
+
let planeCostUsd: number | null = null;
|
|
400
405
|
try {
|
|
401
406
|
if (backend.kind === "control_plane") {
|
|
402
407
|
// Control plane: OpenAI-compatible messages (string content only for v1).
|
|
@@ -437,6 +442,7 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
|
|
|
437
442
|
},
|
|
438
443
|
};
|
|
439
444
|
logId = cpResult.requestId;
|
|
445
|
+
planeCostUsd = cpResult.costUsd;
|
|
440
446
|
} else if (!aiCtx) {
|
|
441
447
|
return json({ error: "AI gateway context missing" }, { status: 500 });
|
|
442
448
|
} else if (model.provider === "anthropic") {
|
|
@@ -484,6 +490,8 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
|
|
|
484
490
|
const latency = Date.now() - start;
|
|
485
491
|
const output = extractOutput(result);
|
|
486
492
|
const usage = extractUsage(result);
|
|
493
|
+
// Control plane: the plane's charge or null, never the playground list price.
|
|
494
|
+
const costUsd = backend.kind === "control_plane" ? planeCostUsd : chatCostUsd(model.pricing, usage.in_, usage.out_);
|
|
487
495
|
|
|
488
496
|
const row = await persistChat(env, {
|
|
489
497
|
userEmail,
|
|
@@ -496,6 +504,7 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
|
|
|
496
504
|
attachments: persistedAtt,
|
|
497
505
|
tokens_in: usage.in_,
|
|
498
506
|
tokens_out: usage.out_,
|
|
507
|
+
cost_usd: costUsd,
|
|
499
508
|
latency_ms: latency,
|
|
500
509
|
ai_gateway_log_id: logId,
|
|
501
510
|
retrieved_context: allRetrieved.length ? allRetrieved : null,
|
|
@@ -512,6 +521,7 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
|
|
|
512
521
|
output,
|
|
513
522
|
tokens_in: usage.in_,
|
|
514
523
|
tokens_out: usage.out_,
|
|
524
|
+
cost_usd: costUsd,
|
|
515
525
|
latency_ms: latency,
|
|
516
526
|
ai_gateway_log_id: logId,
|
|
517
527
|
transcripts: extraText,
|
|
@@ -1098,6 +1108,8 @@ export interface PersistArgs {
|
|
|
1098
1108
|
attachments: PersistedAttachment[];
|
|
1099
1109
|
tokens_in: number | null;
|
|
1100
1110
|
tokens_out: number | null;
|
|
1111
|
+
/** prism#258: chat only; stored null for any other type or a non-done row. */
|
|
1112
|
+
cost_usd?: number | null;
|
|
1101
1113
|
latency_ms: number;
|
|
1102
1114
|
ai_gateway_log_id: string | null;
|
|
1103
1115
|
status?: "pending" | "done" | "failed";
|
|
@@ -1117,6 +1129,12 @@ export async function persistChat(env: Env, a: PersistArgs): Promise<{ id: numbe
|
|
|
1117
1129
|
// sidebar as single-turn entries.
|
|
1118
1130
|
const convId = a.conversation_id ?? null;
|
|
1119
1131
|
const turnIdx = a.turn_index ?? null;
|
|
1132
|
+
// Null is not zero: only a finished chat row with a finite non-negative cost carries one.
|
|
1133
|
+
const costUsd =
|
|
1134
|
+
a.model_type === "chat" && (a.status ?? "done") === "done" &&
|
|
1135
|
+
typeof a.cost_usd === "number" && Number.isFinite(a.cost_usd) && a.cost_usd >= 0
|
|
1136
|
+
? a.cost_usd
|
|
1137
|
+
: null;
|
|
1120
1138
|
|
|
1121
1139
|
const row = await env.DB.prepare(
|
|
1122
1140
|
`INSERT INTO chats
|
|
@@ -1124,8 +1142,8 @@ export async function persistChat(env: Env, a: PersistArgs): Promise<{ id: numbe
|
|
|
1124
1142
|
output_artifact, attachments,
|
|
1125
1143
|
tokens_in, tokens_out, latency_ms, ai_gateway_log_id,
|
|
1126
1144
|
status, job_id, job_provider, job_error, job_started_at,
|
|
1127
|
-
retrieved_context, conversation_id, turn_index, project_id)
|
|
1128
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1145
|
+
retrieved_context, conversation_id, turn_index, project_id, cost_usd)
|
|
1146
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1129
1147
|
RETURNING id, created_at`
|
|
1130
1148
|
)
|
|
1131
1149
|
.bind(
|
|
@@ -1141,7 +1159,8 @@ export async function persistChat(env: Env, a: PersistArgs): Promise<{ id: numbe
|
|
|
1141
1159
|
a.retrieved_context && a.retrieved_context.length ? JSON.stringify(a.retrieved_context) : null,
|
|
1142
1160
|
convId,
|
|
1143
1161
|
turnIdx,
|
|
1144
|
-
a.project_id ?? null
|
|
1162
|
+
a.project_id ?? null,
|
|
1163
|
+
costUsd
|
|
1145
1164
|
)
|
|
1146
1165
|
.first<{ id: number; created_at: string }>();
|
|
1147
1166
|
|
|
@@ -1149,6 +1168,12 @@ export async function persistChat(env: Env, a: PersistArgs): Promise<{ id: numbe
|
|
|
1149
1168
|
return { id: 0, created_at: new Date().toISOString(), conversation_id: "" };
|
|
1150
1169
|
}
|
|
1151
1170
|
|
|
1171
|
+
// prism#259: first finished output for this account, counted once. Only a row
|
|
1172
|
+
// persisted as done, with something to show. Never throws; never fails the write.
|
|
1173
|
+
if ((a.status ?? "done") === "done" && (a.output !== "" || a.output_artifact)) {
|
|
1174
|
+
await recordFirstOutput(env, a.userEmail);
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1152
1177
|
// For non-chat rows that didn't get an explicit conversation_id, backfill
|
|
1153
1178
|
// a synthetic one so they appear in the conversation list.
|
|
1154
1179
|
let finalConvId = convId;
|
|
@@ -1176,7 +1201,7 @@ export async function persistChat(env: Env, a: PersistArgs): Promise<{ id: numbe
|
|
|
1176
1201
|
// Wire format on the response body (text/event-stream):
|
|
1177
1202
|
// data: {"type":"delta","text":"..."}
|
|
1178
1203
|
// data: {"type":"done","row_id":N,"latency_ms":N,"tokens_in":N|null,
|
|
1179
|
-
// "tokens_out":N|null,"conversation_id":"...","turn_index":N}
|
|
1204
|
+
// "tokens_out":N|null,"cost_usd":N|null,"conversation_id":"...","turn_index":N}
|
|
1180
1205
|
// data: {"type":"error","message":"..."}
|
|
1181
1206
|
//
|
|
1182
1207
|
// Anthropic's native SSE event types (message_start, content_block_delta,
|
|
@@ -1211,6 +1236,7 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
|
|
|
1211
1236
|
turn_index?: number;
|
|
1212
1237
|
tokens_in?: number;
|
|
1213
1238
|
tokens_out?: number;
|
|
1239
|
+
cost_usd?: number | null;
|
|
1214
1240
|
latency_ms?: number;
|
|
1215
1241
|
};
|
|
1216
1242
|
const text = payload.output || "";
|
|
@@ -1229,6 +1255,7 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
|
|
|
1229
1255
|
turn_index: payload.turn_index,
|
|
1230
1256
|
tokens_in: payload.tokens_in,
|
|
1231
1257
|
tokens_out: payload.tokens_out,
|
|
1258
|
+
cost_usd: payload.cost_usd ?? null,
|
|
1232
1259
|
latency_ms: payload.latency_ms,
|
|
1233
1260
|
output: text,
|
|
1234
1261
|
})}\n\n`,
|
|
@@ -1460,6 +1487,7 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
|
|
|
1460
1487
|
}
|
|
1461
1488
|
|
|
1462
1489
|
const latency = Date.now() - start;
|
|
1490
|
+
const costUsd = chatCostUsd(model.pricing, usageIn, usageOut);
|
|
1463
1491
|
|
|
1464
1492
|
// Persist as a single row. retrieved_context is saved on the row so
|
|
1465
1493
|
// the History/Conversation views render citations the same way runChat
|
|
@@ -1478,6 +1506,7 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
|
|
|
1478
1506
|
attachments: persistedAtt,
|
|
1479
1507
|
tokens_in: usageIn,
|
|
1480
1508
|
tokens_out: usageOut,
|
|
1509
|
+
cost_usd: costUsd,
|
|
1481
1510
|
latency_ms: latency,
|
|
1482
1511
|
ai_gateway_log_id: null,
|
|
1483
1512
|
retrieved_context: allRetrieved.length ? allRetrieved : null,
|
|
@@ -1492,6 +1521,7 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
|
|
|
1492
1521
|
latency_ms: latency,
|
|
1493
1522
|
tokens_in: usageIn,
|
|
1494
1523
|
tokens_out: usageOut,
|
|
1524
|
+
cost_usd: costUsd,
|
|
1495
1525
|
conversation_id: conversationId,
|
|
1496
1526
|
turn_index: turnIndex,
|
|
1497
1527
|
web_search_error: body.use_web_search ? webSearchError : undefined,
|
|
@@ -12,6 +12,7 @@ import { aiRun, type AiContext } from "../ai-binding";
|
|
|
12
12
|
import { requireGatewayCredentials } from "../gateway-credentials";
|
|
13
13
|
import { buildGenParams } from "../longrun-params";
|
|
14
14
|
import { unzip } from "../zip";
|
|
15
|
+
import { recordFirstOutput } from "../funnel";
|
|
15
16
|
import { r2Put, r2KeyToDataUri, r2DeleteSafe } from "./shared";
|
|
16
17
|
import type { OutputArtifact } from "./shared";
|
|
17
18
|
import {
|
|
@@ -285,6 +286,8 @@ export class LongRunWorkflow extends WorkflowEntrypoint<Env, LongRunParams> {
|
|
|
285
286
|
)
|
|
286
287
|
.bind(JSON.stringify(outputArtifact), latency, rowId)
|
|
287
288
|
.run();
|
|
289
|
+
// prism#259: a finished video or music row is a first output too. Never throws.
|
|
290
|
+
await recordFirstOutput(this.env, userEmail);
|
|
288
291
|
}
|
|
289
292
|
);
|
|
290
293
|
} catch (err) {
|
package/template/src/version.ts
CHANGED
|
@@ -15,4 +15,4 @@
|
|
|
15
15
|
// That distinction is the entire point. In prism-mcp the advertised version was a literal and
|
|
16
16
|
// the test asserting it carried a TRANSCRIBED duplicate, so the assertion only ever proved
|
|
17
17
|
// that someone had typed the same thing twice, and a correct version bump went red.
|
|
18
|
-
export const VERSION = "1.
|
|
18
|
+
export const VERSION = "1.5.0";
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// scripts/catalog-drift.mjs (prism#254, #255): id extraction, API pagination, page verdicts and the
|
|
2
|
+
// drift decision. The positive control is the point: an injected retired id MUST be reported.
|
|
3
|
+
import { describe, expect, it } from "vitest";
|
|
4
|
+
import {
|
|
5
|
+
checkPage,
|
|
6
|
+
evaluate,
|
|
7
|
+
extractEntryIds,
|
|
8
|
+
extractLiteralIds,
|
|
9
|
+
fetchWorkersAiNames,
|
|
10
|
+
renderBody,
|
|
11
|
+
} from "../scripts/catalog-drift.mjs";
|
|
12
|
+
|
|
13
|
+
const cat = `
|
|
14
|
+
// { id: "@cf/commented/out" }
|
|
15
|
+
{ id: "@cf/meta/a", label: "a" },
|
|
16
|
+
{
|
|
17
|
+
id: "anthropic/claude-x",
|
|
18
|
+
upstream: "grok/grok-1",
|
|
19
|
+
}
|
|
20
|
+
id: string;
|
|
21
|
+
`;
|
|
22
|
+
|
|
23
|
+
describe("extraction", () => {
|
|
24
|
+
it("reads id and upstream entries, skips comments and type declarations", () => {
|
|
25
|
+
expect(extractEntryIds(cat).sort()).toEqual(["@cf/meta/a", "anthropic/claude-x", "grok/grok-1"]);
|
|
26
|
+
});
|
|
27
|
+
it("literal scan skips startsWith prefixes", () => {
|
|
28
|
+
const code = `if (m.startsWith("@cf/black-forest-labs/flux-2")) {} m === "@cf/black-forest-labs/flux-2-dev"; "google/imagen-4"`;
|
|
29
|
+
expect(extractLiteralIds(code, ["google"]).sort()).toEqual(["@cf/black-forest-labs/flux-2-dev", "google/imagen-4"]);
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
describe("API pagination", () => {
|
|
34
|
+
it("walks pages until total_count is reached", async () => {
|
|
35
|
+
const calls: string[] = [];
|
|
36
|
+
const pages = [
|
|
37
|
+
{ success: true, result: [{ name: "@cf/a/1" }, { name: "@cf/a/2" }], result_info: { total_count: 3 } },
|
|
38
|
+
{ success: true, result: [{ name: "@cf/a/3" }], result_info: { total_count: 3 } },
|
|
39
|
+
];
|
|
40
|
+
const f = (async (url: string) => {
|
|
41
|
+
calls.push(url);
|
|
42
|
+
return new Response(JSON.stringify(pages[calls.length - 1]));
|
|
43
|
+
}) as unknown as typeof fetch;
|
|
44
|
+
const names = await fetchWorkersAiNames({ accountId: "acc", token: "t", fetchImpl: f });
|
|
45
|
+
expect([...names].sort()).toEqual(["@cf/a/1", "@cf/a/2", "@cf/a/3"]);
|
|
46
|
+
expect(calls).toHaveLength(2);
|
|
47
|
+
expect(calls[0]).toContain("/accounts/acc/ai/models/search?page=1");
|
|
48
|
+
});
|
|
49
|
+
it("throws on an HTTP error rather than reporting an empty catalog", async () => {
|
|
50
|
+
const f = (async () => new Response("no", { status: 403 })) as unknown as typeof fetch;
|
|
51
|
+
await expect(fetchWorkersAiNames({ accountId: "a", token: "t", fetchImpl: f })).rejects.toThrow("403");
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
describe("page check", () => {
|
|
56
|
+
const mk = (map: Record<string, [number, string?]>) =>
|
|
57
|
+
(async (url: string) => {
|
|
58
|
+
const key = url.replace("https://developers.cloudflare.com/ai/models/", "");
|
|
59
|
+
const [status, loc] = map[key] ?? [500];
|
|
60
|
+
return new Response(null, { status, headers: loc ? { location: loc } : {} });
|
|
61
|
+
}) as unknown as typeof fetch;
|
|
62
|
+
it("present, via the dotted variant, and via a gateway vendor alias", async () => {
|
|
63
|
+
const f = mk({ "anthropic/claude-haiku-4.5/": [200], "xai/grok-4.5/": [200] });
|
|
64
|
+
expect(await checkPage("anthropic/claude-haiku-4-5", f)).toBe("present");
|
|
65
|
+
expect(await checkPage("grok/grok-4.5", f)).toBe("present");
|
|
66
|
+
});
|
|
67
|
+
it("missing when both variants redirect to ?unavailable=", async () => {
|
|
68
|
+
const f = mk({
|
|
69
|
+
"google/imagen-4/": [302, "/ai/models/?unavailable=google%2Fimagen-4"],
|
|
70
|
+
});
|
|
71
|
+
expect(await checkPage("google/imagen-4", f)).toBe("missing");
|
|
72
|
+
});
|
|
73
|
+
it("unknown, not passing, when the site keeps failing", async () => {
|
|
74
|
+
expect(await checkPage("xai/grok-9", mk({}))).toBe("unknown");
|
|
75
|
+
}, 15000);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
describe("drift decision", () => {
|
|
79
|
+
const ids = new Map<string, string[]>([
|
|
80
|
+
["@cf/ok/model", ["prism:src/models.ts"]],
|
|
81
|
+
["@cf/myshell-ai/melotts", ["prism-control-plane:src/catalog.ts"]],
|
|
82
|
+
["openai/gone", ["prism:src/models.ts"]],
|
|
83
|
+
["openai/flaky", ["prism:src/models.ts"]],
|
|
84
|
+
]);
|
|
85
|
+
const r = evaluate({
|
|
86
|
+
ids,
|
|
87
|
+
cfNames: new Set(["@cf/ok/model"]),
|
|
88
|
+
pageVerdicts: new Map([["openai/gone", "missing"], ["openai/flaky", "unknown"]]),
|
|
89
|
+
});
|
|
90
|
+
it("reports the injected retired id with its repo and file", () => {
|
|
91
|
+
expect(r.drifted.map((d) => d.id).sort()).toEqual(["@cf/myshell-ai/melotts", "openai/gone"]);
|
|
92
|
+
expect(renderBody({ ...r, total: 4, checkedAt: "t" })).toContain("`@cf/myshell-ai/melotts`");
|
|
93
|
+
expect(renderBody({ ...r, total: 4, checkedAt: "t" })).toContain("prism-control-plane:src/catalog.ts");
|
|
94
|
+
});
|
|
95
|
+
it("a page that could not be checked is listed apart, never as passing", () => {
|
|
96
|
+
expect(r.unchecked.map((d) => d.id)).toEqual(["openai/flaky"]);
|
|
97
|
+
});
|
|
98
|
+
it("clean input yields no findings", () => {
|
|
99
|
+
const c = evaluate({ ids: new Map([["@cf/ok/model", ["x"]]]), cfNames: new Set(["@cf/ok/model"]), pageVerdicts: new Map() });
|
|
100
|
+
expect(c.drifted).toHaveLength(0);
|
|
101
|
+
expect(c.unchecked).toHaveLength(0);
|
|
102
|
+
});
|
|
103
|
+
});
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// prism#259: bucket boundaries for the signup-to-first-output time.
|
|
2
|
+
import { describe, expect, it } from "vitest";
|
|
3
|
+
import { ttfoBucket } from "../src/funnel";
|
|
4
|
+
|
|
5
|
+
describe("ttfoBucket", () => {
|
|
6
|
+
it("puts each boundary in the upper bucket", () => {
|
|
7
|
+
expect(ttfoBucket(0)).toBe("ttfo_lt_1m");
|
|
8
|
+
expect(ttfoBucket(59)).toBe("ttfo_lt_1m");
|
|
9
|
+
expect(ttfoBucket(60)).toBe("ttfo_1_5m");
|
|
10
|
+
expect(ttfoBucket(299)).toBe("ttfo_1_5m");
|
|
11
|
+
expect(ttfoBucket(300)).toBe("ttfo_5_30m");
|
|
12
|
+
expect(ttfoBucket(1799)).toBe("ttfo_5_30m");
|
|
13
|
+
expect(ttfoBucket(1800)).toBe("ttfo_30m_24h");
|
|
14
|
+
expect(ttfoBucket(86399)).toBe("ttfo_30m_24h");
|
|
15
|
+
expect(ttfoBucket(86400)).toBe("ttfo_ge_24h");
|
|
16
|
+
expect(ttfoBucket(10 * 86400)).toBe("ttfo_ge_24h");
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it("negative, NaN and Infinity never throw and never pick a bucket by accident", () => {
|
|
20
|
+
expect(ttfoBucket(-5)).toBe("ttfo_lt_1m");
|
|
21
|
+
expect(ttfoBucket(NaN)).toBe("ttfo_lt_1m");
|
|
22
|
+
expect(ttfoBucket(Infinity)).toBe("ttfo_lt_1m");
|
|
23
|
+
});
|
|
24
|
+
});
|
|
@@ -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
|
+
});
|