llm-api-purity-check 0.0.0-stage → 1.3.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/LICENSE +27 -0
- package/README.md +161 -2
- package/README_CN.md +122 -0
- package/bin/cli.mjs +415 -0
- package/data/bank.generated.json +1 -0
- package/package.json +39 -4
- package/scripts/sync-bank.mjs +333 -0
- package/skills/aiapipk-check/SKILL.md +134 -0
- package/src/checks.mjs +1273 -0
- package/src/client.mjs +1240 -0
- package/src/fingerprint.mjs +665 -0
- package/src/links.mjs +135 -0
- package/src/modelIdNormalize.mjs +94 -0
package/src/checks.mjs
ADDED
|
@@ -0,0 +1,1273 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anti-downgrade, real Prompt Caching, streaming cadence, token-billing sanity
|
|
3
|
+
* (with thinking/reasoning exemption), upstream channel visibility,
|
|
4
|
+
* and /v1/responses instruction/tools tamper checks.
|
|
5
|
+
*
|
|
6
|
+
* Extracted from AIAPIPK (https://www.aiapipk.com/detect/).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import crypto from 'node:crypto';
|
|
10
|
+
import zlib from 'node:zlib';
|
|
11
|
+
import { callLlm, isReasoningCapableModel } from './client.mjs';
|
|
12
|
+
|
|
13
|
+
export const NEUTRAL_PROBE_TOOLS = [
|
|
14
|
+
{ name: 'lookup_weather', description: 'Return current weather summary for a city.' },
|
|
15
|
+
{ name: 'check_inventory', description: 'Return stock availability for a catalog SKU.' },
|
|
16
|
+
{ name: 'query_timezone', description: 'Return current local time offset for a region.' },
|
|
17
|
+
{ name: 'fetch_exchange_rate', description: 'Return latest currency conversion rate.' },
|
|
18
|
+
{ name: 'get_shipping_eta', description: 'Return estimated delivery window for a parcel.' },
|
|
19
|
+
];
|
|
20
|
+
|
|
21
|
+
const CODEBASE_SCENARIOS = [
|
|
22
|
+
{
|
|
23
|
+
domain: 'order-ledger',
|
|
24
|
+
header: '// TypeScript settlement reconciliation module',
|
|
25
|
+
questionRound1:
|
|
26
|
+
'In one concise sentence, what fee weights does computeNetReceivable apply to refundedCents vs grossCents?',
|
|
27
|
+
questionRound2:
|
|
28
|
+
'In one concise sentence, what default fallback settlement delay does selectSettlementRail use when a key is missing from delayMap?',
|
|
29
|
+
buildBlock: (i) => `
|
|
30
|
+
export class OrderLedgerBatch${i} {
|
|
31
|
+
private readonly batchId = "ledger_${i}";
|
|
32
|
+
private readonly maxAttempts = ${(i % 3) + 2};
|
|
33
|
+
private readonly railWeights = new Map<string, number>([
|
|
34
|
+
["ach_primary_${i}", ${100 + i * 5}],
|
|
35
|
+
["wire_backup_${i}", ${45 + i * 3}],
|
|
36
|
+
["card_fallback_${i}", ${18 + i}],
|
|
37
|
+
]);
|
|
38
|
+
|
|
39
|
+
public selectSettlementRail(delayMap: Record<string, number>, disputeRateMap: Record<string, number>): string {
|
|
40
|
+
let bestRail = "ach_primary_${i}";
|
|
41
|
+
let bestScore = -Infinity;
|
|
42
|
+
for (const [rail, baseWeight] of this.railWeights.entries()) {
|
|
43
|
+
const delayMs = Math.max(40, delayMap[rail] ?? 750);
|
|
44
|
+
const disputeRate = Math.min(1, Math.max(0, disputeRateMap[rail] ?? 0));
|
|
45
|
+
const reliability = (1 - disputeRate) * (1 - disputeRate);
|
|
46
|
+
const score = (baseWeight * reliability) / Math.log2(delayMs + 16);
|
|
47
|
+
if (score > bestScore) {
|
|
48
|
+
bestScore = score;
|
|
49
|
+
bestRail = rail;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return bestRail;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
public computeNetReceivable(grossCents: number, refundedCents: number, feeBps: number, fxRate: number): number {
|
|
56
|
+
const netVolume = Math.max(0, grossCents - refundedCents) * 0.985 + refundedCents * 0.05;
|
|
57
|
+
const adjusted = (netVolume - (grossCents * feeBps) / 10_000) / 100;
|
|
58
|
+
return Math.round(adjusted * fxRate * 10000) / 10000;
|
|
59
|
+
}
|
|
60
|
+
}`,
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
domain: 'inventory-planner',
|
|
64
|
+
header: '// TypeScript warehouse dock scheduling module',
|
|
65
|
+
questionRound1:
|
|
66
|
+
'In one concise sentence, how does estimateRestockBuffer weight expeditedUnits vs standardUnits?',
|
|
67
|
+
questionRound2:
|
|
68
|
+
'In one concise sentence, what default fallback congestion score does allocateDockLane use when a lane is missing from congestionMap?',
|
|
69
|
+
buildBlock: (i) => `
|
|
70
|
+
export class WarehouseSlotPlanner${i} {
|
|
71
|
+
private readonly zoneId = "zone_${i}";
|
|
72
|
+
private readonly shiftLimit = ${(i % 4) + 3};
|
|
73
|
+
private readonly dockPriorities = new Map<string, number>([
|
|
74
|
+
["north_bay_${i}", ${110 + i * 4}],
|
|
75
|
+
["east_bay_${i}", ${50 + i * 3}],
|
|
76
|
+
["overflow_${i}", ${20 + i}],
|
|
77
|
+
]);
|
|
78
|
+
|
|
79
|
+
public allocateDockLane(congestionMap: Record<string, number>, faultRateMap: Record<string, number>): string {
|
|
80
|
+
let bestLane = "north_bay_${i}";
|
|
81
|
+
let bestScore = -Infinity;
|
|
82
|
+
for (const [lane, priority] of this.dockPriorities.entries()) {
|
|
83
|
+
const congestion = Math.max(30, congestionMap[lane] ?? 620);
|
|
84
|
+
const faultRate = Math.min(1, Math.max(0, faultRateMap[lane] ?? 0));
|
|
85
|
+
const uptimeFactor = (1 - faultRate) * (1 - faultRate);
|
|
86
|
+
const score = (priority * uptimeFactor) / Math.log2(congestion + 12);
|
|
87
|
+
if (score > bestScore) {
|
|
88
|
+
bestScore = score;
|
|
89
|
+
bestLane = lane;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return bestLane;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
public estimateRestockBuffer(standardUnits: number, expeditedUnits: number, transitDays: number, safetyRatio: number): number {
|
|
96
|
+
const weightedUnits = Math.max(0, standardUnits) * 1.0 + Math.max(0, expeditedUnits) * 2.5;
|
|
97
|
+
const buffer = (weightedUnits * Math.max(1, transitDays)) / 100;
|
|
98
|
+
return Math.round(buffer * safetyRatio * 1000) / 1000;
|
|
99
|
+
}
|
|
100
|
+
}`,
|
|
101
|
+
},
|
|
102
|
+
{
|
|
103
|
+
domain: 'metric-rollup',
|
|
104
|
+
header: '// TypeScript time-series metric retention module',
|
|
105
|
+
questionRound1:
|
|
106
|
+
'In one concise sentence, how does computeWeightedQuota weight warmSamples vs hotSamples?',
|
|
107
|
+
questionRound2:
|
|
108
|
+
'In one concise sentence, what default fallback ingestion lag does selectRetentionTier use when a tier is missing from lagMap?',
|
|
109
|
+
buildBlock: (i) => `
|
|
110
|
+
export class MetricWindowAggregator${i} {
|
|
111
|
+
private readonly bucketId = "rollup_${i}";
|
|
112
|
+
private readonly maxFlushRetries = ${(i % 3) + 2};
|
|
113
|
+
private readonly tierCapacities = new Map<string, number>([
|
|
114
|
+
["hot_nvme_${i}", ${120 + i * 6}],
|
|
115
|
+
["warm_ssd_${i}", ${55 + i * 2}],
|
|
116
|
+
["cold_obj_${i}", ${22 + i}],
|
|
117
|
+
]);
|
|
118
|
+
|
|
119
|
+
public selectRetentionTier(lagMap: Record<string, number>, dropRateMap: Record<string, number>): string {
|
|
120
|
+
let bestTier = "hot_nvme_${i}";
|
|
121
|
+
let bestScore = -Infinity;
|
|
122
|
+
for (const [tier, capacity] of this.tierCapacities.entries()) {
|
|
123
|
+
const lagMs = Math.max(25, lagMap[tier] ?? 910);
|
|
124
|
+
const dropRate = Math.min(1, Math.max(0, dropRateMap[tier] ?? 0));
|
|
125
|
+
const durability = (1 - dropRate) * (1 - dropRate);
|
|
126
|
+
const score = (capacity * durability) / Math.log2(lagMs + 20);
|
|
127
|
+
if (score > bestScore) {
|
|
128
|
+
bestScore = score;
|
|
129
|
+
bestTier = tier;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return bestTier;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
public computeWeightedQuota(hotSamples: number, warmSamples: number, coldSamples: number, scale: number): number {
|
|
136
|
+
const activeCost = Math.max(0, hotSamples) * 1.0 + Math.max(0, warmSamples) * 0.25;
|
|
137
|
+
const totalUnits = (activeCost + Math.max(0, coldSamples) * 0.05) / 100_000;
|
|
138
|
+
return Math.round(totalUnits * scale * 10000) / 10000;
|
|
139
|
+
}
|
|
140
|
+
}`,
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
domain: 'task-dispatcher',
|
|
144
|
+
header: '// TypeScript background job dispatcher module',
|
|
145
|
+
questionRound1:
|
|
146
|
+
'In one concise sentence, how does calculateRetryBudget weight deadLetterJobs vs activeJobs?',
|
|
147
|
+
questionRound2:
|
|
148
|
+
'In one concise sentence, what default fallback queue depth does pickWorkerShard use when a shard is missing from depthMap?',
|
|
149
|
+
buildBlock: (i) => `
|
|
150
|
+
export class TaskQueueDispatcher${i} {
|
|
151
|
+
private readonly poolId = "worker_pool_${i}";
|
|
152
|
+
private readonly concurrencyCap = ${(i % 5) + 4};
|
|
153
|
+
private readonly shardWeights = new Map<string, number>([
|
|
154
|
+
["shard_alpha_${i}", ${105 + i * 5}],
|
|
155
|
+
["shard_beta_${i}", ${48 + i * 3}],
|
|
156
|
+
["shard_gamma_${i}", ${19 + i}],
|
|
157
|
+
]);
|
|
158
|
+
|
|
159
|
+
public pickWorkerShard(depthMap: Record<string, number>, timeoutRateMap: Record<string, number>): string {
|
|
160
|
+
let bestShard = "shard_alpha_${i}";
|
|
161
|
+
let bestScore = -Infinity;
|
|
162
|
+
for (const [shard, weight] of this.shardWeights.entries()) {
|
|
163
|
+
const depth = Math.max(20, depthMap[shard] ?? 480);
|
|
164
|
+
const timeoutRate = Math.min(1, Math.max(0, timeoutRateMap[shard] ?? 0));
|
|
165
|
+
const stability = (1 - timeoutRate) * (1 - timeoutRate);
|
|
166
|
+
const score = (weight * stability) / Math.log2(depth + 14);
|
|
167
|
+
if (score > bestScore) {
|
|
168
|
+
bestScore = score;
|
|
169
|
+
bestShard = shard;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return bestShard;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
public calculateRetryBudget(activeJobs: number, deadLetterJobs: number, backoffMs: number, factor: number): number {
|
|
176
|
+
const weightedJobs = Math.max(0, activeJobs) * 1.0 + Math.max(0, deadLetterJobs) * 4.0;
|
|
177
|
+
const budgetSec = (weightedJobs * Math.max(50, backoffMs)) / 60_000;
|
|
178
|
+
return Math.round(budgetSec * factor * 10000) / 10000;
|
|
179
|
+
}
|
|
180
|
+
}`,
|
|
181
|
+
},
|
|
182
|
+
];
|
|
183
|
+
|
|
184
|
+
export function buildCodebasePrefixScenario(repeatBlocks = 14, seed) {
|
|
185
|
+
const idx =
|
|
186
|
+
seed !== undefined
|
|
187
|
+
? Math.abs(Math.trunc(Number(seed))) % CODEBASE_SCENARIOS.length
|
|
188
|
+
: crypto.randomInt(0, CODEBASE_SCENARIOS.length);
|
|
189
|
+
const scenario = CODEBASE_SCENARIOS[idx];
|
|
190
|
+
const blocks = [];
|
|
191
|
+
for (let i = 1; i <= repeatBlocks; i += 1) {
|
|
192
|
+
blocks.push(scenario.buildBlock(i));
|
|
193
|
+
}
|
|
194
|
+
return {
|
|
195
|
+
domain: scenario.domain,
|
|
196
|
+
prefix: `${scenario.header}\n${blocks.join('\n')}`,
|
|
197
|
+
questionRound1: scenario.questionRound1,
|
|
198
|
+
questionRound2: scenario.questionRound2,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function buildCodebasePrefix(repeatBlocks = 14, seed) {
|
|
203
|
+
return buildCodebasePrefixScenario(repeatBlocks, seed).prefix;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function solveTwoShapePigeonhole(a1, a2, p1, p2, w1, w2) {
|
|
207
|
+
let optimal = Number.POSITIVE_INFINITY;
|
|
208
|
+
let bestX = 0;
|
|
209
|
+
let bestY = 0;
|
|
210
|
+
const maxS1 = a1 + p1 + w1;
|
|
211
|
+
const maxS2 = a2 + p2 + w2;
|
|
212
|
+
|
|
213
|
+
for (let x = 0; x <= maxS1; x += 1) {
|
|
214
|
+
for (let y = 0; y <= maxS2; y += 1) {
|
|
215
|
+
const canFail =
|
|
216
|
+
x <= w1 ||
|
|
217
|
+
y <= w2 ||
|
|
218
|
+
(x <= a1 + w1 && y <= a2 + w2) ||
|
|
219
|
+
(x <= p1 + w1 && y <= p2 + w2);
|
|
220
|
+
if (!canFail && x + y < optimal) {
|
|
221
|
+
optimal = x + y;
|
|
222
|
+
bestX = x;
|
|
223
|
+
bestY = y;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const trap =
|
|
229
|
+
Math.max(a1 + a2 + w1 + w2, p1 + p2 + w1 + w2, a1 + p1 + w1 + w2, a2 + p2 + w1 + w2) + 1;
|
|
230
|
+
|
|
231
|
+
return { optimal, bestX, bestY, trap };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function buildDynamicPuzzle(seed) {
|
|
235
|
+
let rngState =
|
|
236
|
+
seed !== undefined ? seed >>> 0 : (Date.now() ^ Math.floor(Math.random() * 0xffffffff)) >>> 0;
|
|
237
|
+
const nextRand = () => {
|
|
238
|
+
rngState = (Math.imul(1664525, rngState) + 1013904223) >>> 0;
|
|
239
|
+
return rngState / 0x100000000;
|
|
240
|
+
};
|
|
241
|
+
const randInt = (min, max) => min + Math.floor(nextRand() * (max - min + 1));
|
|
242
|
+
|
|
243
|
+
let a1 = 8, a2 = 6, p1 = 10, p2 = 8, w1 = 7, w2 = 5;
|
|
244
|
+
let solved = solveTwoShapePigeonhole(a1, a2, p1, p2, w1, w2);
|
|
245
|
+
|
|
246
|
+
for (let attempt = 0; attempt < 40; attempt += 1) {
|
|
247
|
+
const ca1 = randInt(5, 11);
|
|
248
|
+
const ca2 = randInt(5, 10);
|
|
249
|
+
const cp1 = randInt(6, 12);
|
|
250
|
+
const cp2 = randInt(5, 10);
|
|
251
|
+
const cw1 = randInt(5, 10);
|
|
252
|
+
const cw2 = randInt(3, 8);
|
|
253
|
+
const res = solveTwoShapePigeonhole(ca1, ca2, cp1, cp2, cw1, cw2);
|
|
254
|
+
if (res.optimal !== 21 && res.optimal >= 17 && res.optimal <= 34 && res.trap - res.optimal >= 6) {
|
|
255
|
+
a1 = ca1; a2 = ca2; p1 = cp1; p2 = cp2; w1 = cw1; w2 = cw2;
|
|
256
|
+
solved = res;
|
|
257
|
+
break;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const prompt =
|
|
262
|
+
'Do NOT use any tools or web search. An opaque box contains candies in 3 flavors (strawberry, mango, blueberry) and 2 shapes (cube, sphere). ' +
|
|
263
|
+
'You can distinguish cube vs sphere purely by touch before pulling each candy out, so you can decide in advance how many cubes and how many spheres to draw. ' +
|
|
264
|
+
`Counts: ${a1} strawberry cubes, ${a2} strawberry spheres, ${p1} mango cubes, ${p2} mango spheres, ${w1} blueberry cubes, ${w2} blueberry spheres. ` +
|
|
265
|
+
'What is the MINIMUM total number of candies you must draw (by choosing a fixed split of cubes + spheres in advance) to GUARANTEE having both a strawberry and a mango candy of DIFFERENT shapes (either strawberry cube + mango sphere, OR strawberry sphere + mango cube)? ' +
|
|
266
|
+
'Think carefully and end your response with a single final line: ANSWER: <integer>';
|
|
267
|
+
|
|
268
|
+
return {
|
|
269
|
+
prompt,
|
|
270
|
+
expected: solved.optimal,
|
|
271
|
+
trapAnswer: solved.trap,
|
|
272
|
+
bestSplit: { cubes: solved.bestX, spheres: solved.bestY },
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
export function gradeDynamicPuzzle(replyText, expected) {
|
|
277
|
+
const text = String(replyText || '').trim().slice(-4000);
|
|
278
|
+
if (!text) return { passed: false, parsed: null };
|
|
279
|
+
const m = text.match(/ANSWER\s*[:=]\s*(-?\d+)/i);
|
|
280
|
+
if (m) return { passed: Number(m[1]) === expected, parsed: Number(m[1]) };
|
|
281
|
+
const exact = text.match(/^\s*(-?\d+)\s*$/);
|
|
282
|
+
if (exact) return { passed: Number(exact[1]) === expected, parsed: Number(exact[1]) };
|
|
283
|
+
const nums = text.match(/-?\d+/g);
|
|
284
|
+
if (!nums || nums.length === 0) return { passed: false, parsed: null };
|
|
285
|
+
const last = Number(nums[nums.length - 1]);
|
|
286
|
+
return { passed: last === expected, parsed: last };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export function computeResponsesEchoDiff({ sentInstructions = '', sentToolNames = [], echoInstructions = null, echoTools = null }) {
|
|
290
|
+
const tamperFlags = [];
|
|
291
|
+
const sentInstr = sentInstructions.trim();
|
|
292
|
+
const echoInstr = typeof echoInstructions === 'string' ? echoInstructions.trim() : null;
|
|
293
|
+
|
|
294
|
+
if (echoInstr !== null) {
|
|
295
|
+
if (!sentInstr && echoInstr.length >= 60) {
|
|
296
|
+
tamperFlags.push('instructions_injected');
|
|
297
|
+
} else if (sentInstr && echoInstr !== sentInstr) {
|
|
298
|
+
const normSent = sentInstr.replace(/\s+/g, ' ');
|
|
299
|
+
const normEcho = echoInstr.replace(/\s+/g, ' ');
|
|
300
|
+
if (Math.abs(normEcho.length - normSent.length) >= 40 || (!normEcho.includes(normSent) && normEcho.length >= 40)) {
|
|
301
|
+
tamperFlags.push('instructions_injected');
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
if (Array.isArray(echoTools)) {
|
|
307
|
+
if (sentToolNames.length === 0 && echoTools.length > 0) {
|
|
308
|
+
tamperFlags.push('tools_injected');
|
|
309
|
+
} else if (sentToolNames.length > 0) {
|
|
310
|
+
const echoedNames = new Set(echoTools.map((t) => String(t?.name || t?.function?.name || '').trim()).filter(Boolean));
|
|
311
|
+
if (sentToolNames.some((n) => !echoedNames.has(n))) {
|
|
312
|
+
tamperFlags.push('tools_deleted');
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
return tamperFlags;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Conservative zero-dependency output token estimator (used to catch gross >1.6x billing inflation).
|
|
322
|
+
* For exact BPE/Tiktoken recount, use the online verifier at https://www.aiapipk.com/detect/.
|
|
323
|
+
*/
|
|
324
|
+
export function estimateConservativeMaxTokens(text) {
|
|
325
|
+
const s = String(text || '');
|
|
326
|
+
if (!s) return 0;
|
|
327
|
+
const cjk = (s.match(/[\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]/g) || []).length;
|
|
328
|
+
const nonCjk = s.length - cjk;
|
|
329
|
+
// Upper-bound conservative estimate: ~1.5 tok per CJK char + ~0.38 tok per ASCII/Latin char + overhead
|
|
330
|
+
return Math.max(12, Math.ceil(cjk * 1.5 + nonCjk * 0.38 + 20));
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* Server-consistent output billing evaluation with thinking/reasoning exemption:
|
|
335
|
+
* 1. If upstream explicitly reports `reasoningTokens > 0`, subtract them and re-check visible ratio (>1.6x & >120 tok).
|
|
336
|
+
* 2. If `reasoningTokens === 0` but thinking content (`thinkingChars > 0`) or cryptographic thinking signature
|
|
337
|
+
* (`thinkingSigPresent` / `redactedThinking`) is observed:
|
|
338
|
+
* - Allow verbose thinking streams accounted for by visible+thinking upper bound (<=1.6x);
|
|
339
|
+
* - Exempt summarized thinking / thinking-signature outputs under < 8.0x (matching Anthropic adaptive/extended thinking),
|
|
340
|
+
* while still flagging extreme >= 8.0x billing inflation.
|
|
341
|
+
*/
|
|
342
|
+
export function evaluateOutputBilling({
|
|
343
|
+
text = '',
|
|
344
|
+
thinkingText = '',
|
|
345
|
+
reportedOutputTokens = null,
|
|
346
|
+
reasoningTokens = 0,
|
|
347
|
+
thinkingChars = null,
|
|
348
|
+
thinkingSigPresent = false,
|
|
349
|
+
redactedThinking = false,
|
|
350
|
+
}) {
|
|
351
|
+
const estMax = estimateConservativeMaxTokens(text);
|
|
352
|
+
const reportedOut =
|
|
353
|
+
typeof reportedOutputTokens === 'number' && Number.isFinite(reportedOutputTokens)
|
|
354
|
+
? reportedOutputTokens
|
|
355
|
+
: null;
|
|
356
|
+
const reportedReasoning =
|
|
357
|
+
typeof reasoningTokens === 'number' && Number.isFinite(reasoningTokens) && reasoningTokens > 0
|
|
358
|
+
? reasoningTokens
|
|
359
|
+
: 0;
|
|
360
|
+
const actualThinkingChars =
|
|
361
|
+
typeof thinkingChars === 'number' && Number.isFinite(thinkingChars)
|
|
362
|
+
? thinkingChars
|
|
363
|
+
: String(thinkingText || '').length;
|
|
364
|
+
const hasThinkingSig = Boolean(thinkingSigPresent || redactedThinking);
|
|
365
|
+
|
|
366
|
+
const rawInflationRatio =
|
|
367
|
+
reportedOut !== null && estMax > 0 ? Math.round((reportedOut / estMax) * 100) / 100 : null;
|
|
368
|
+
|
|
369
|
+
let effectiveReportedOut = reportedOut;
|
|
370
|
+
let effectiveInflationRatio = rawInflationRatio;
|
|
371
|
+
let thinkingExempt = false;
|
|
372
|
+
let thinkingExemptReason = null;
|
|
373
|
+
let billingInflationSuspect = false;
|
|
374
|
+
|
|
375
|
+
if (reportedOut !== null && estMax > 0) {
|
|
376
|
+
if (reportedReasoning > 0) {
|
|
377
|
+
effectiveReportedOut = Math.max(0, reportedOut - reportedReasoning);
|
|
378
|
+
effectiveInflationRatio = Math.round((effectiveReportedOut / estMax) * 100) / 100;
|
|
379
|
+
if (effectiveInflationRatio > 1.6 && effectiveReportedOut > 120) {
|
|
380
|
+
billingInflationSuspect = true;
|
|
381
|
+
} else if (rawInflationRatio !== null && rawInflationRatio > 1.6 && reportedOut > 120) {
|
|
382
|
+
thinkingExempt = true;
|
|
383
|
+
thinkingExemptReason = 'reasoning_tokens_subtracted';
|
|
384
|
+
}
|
|
385
|
+
} else if (actualThinkingChars > 0 || hasThinkingSig) {
|
|
386
|
+
const estThinkingMax = thinkingText
|
|
387
|
+
? estimateConservativeMaxTokens(thinkingText)
|
|
388
|
+
: actualThinkingChars > 0
|
|
389
|
+
? Math.max(12, Math.ceil(actualThinkingChars * 0.45 + 20))
|
|
390
|
+
: 0;
|
|
391
|
+
const combinedUpper = estMax + estThinkingMax;
|
|
392
|
+
const combinedRatio =
|
|
393
|
+
combinedUpper > 0 ? Math.round((reportedOut / combinedUpper) * 100) / 100 : rawInflationRatio;
|
|
394
|
+
|
|
395
|
+
if (combinedRatio !== null && combinedRatio <= 1.6) {
|
|
396
|
+
billingInflationSuspect = false;
|
|
397
|
+
if (rawInflationRatio !== null && rawInflationRatio > 1.6 && reportedOut > 120) {
|
|
398
|
+
thinkingExempt = true;
|
|
399
|
+
thinkingExemptReason = 'thinking_text_accounted';
|
|
400
|
+
}
|
|
401
|
+
} else if (rawInflationRatio !== null && rawInflationRatio < 8.0) {
|
|
402
|
+
billingInflationSuspect = false;
|
|
403
|
+
if (rawInflationRatio > 1.6 && reportedOut > 120) {
|
|
404
|
+
thinkingExempt = true;
|
|
405
|
+
thinkingExemptReason = 'thinking_content_or_signature_exempt';
|
|
406
|
+
}
|
|
407
|
+
} else if (reportedOut > 120) {
|
|
408
|
+
billingInflationSuspect = true;
|
|
409
|
+
}
|
|
410
|
+
} else {
|
|
411
|
+
billingInflationSuspect = rawInflationRatio !== null && rawInflationRatio > 1.6 && reportedOut > 120;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
return {
|
|
416
|
+
conservativeUpperBoundTokens: estMax,
|
|
417
|
+
reportedOutputTokens: reportedOut,
|
|
418
|
+
reasoningTokens: reportedReasoning,
|
|
419
|
+
effectiveReportedOutputTokens: effectiveReportedOut,
|
|
420
|
+
inflationRatio: rawInflationRatio,
|
|
421
|
+
effectiveInflationRatio,
|
|
422
|
+
thinkingChars: actualThinkingChars,
|
|
423
|
+
thinkingSigPresent: hasThinkingSig,
|
|
424
|
+
thinkingExempt,
|
|
425
|
+
thinkingExemptReason,
|
|
426
|
+
billingInflationSuspect,
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export function getProbeToolName(toolObj) {
|
|
431
|
+
if (!toolObj || typeof toolObj !== 'object') return '';
|
|
432
|
+
return String(toolObj.name || toolObj.function?.name || '').trim();
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
export function buildMinimalProbeTool(protocol, opts = {}) {
|
|
436
|
+
let picked = opts.tool;
|
|
437
|
+
if (!picked) {
|
|
438
|
+
const idx =
|
|
439
|
+
opts.toolIndex !== undefined
|
|
440
|
+
? Math.abs(Math.trunc(Number(opts.toolIndex))) % NEUTRAL_PROBE_TOOLS.length
|
|
441
|
+
: opts.seed !== undefined
|
|
442
|
+
? Math.abs(Math.trunc(Number(opts.seed))) % NEUTRAL_PROBE_TOOLS.length
|
|
443
|
+
: crypto.randomInt(0, NEUTRAL_PROBE_TOOLS.length);
|
|
444
|
+
picked = NEUTRAL_PROBE_TOOLS[idx];
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
if (protocol === 'anthropic') {
|
|
448
|
+
return [
|
|
449
|
+
{
|
|
450
|
+
name: picked.name,
|
|
451
|
+
description: picked.description,
|
|
452
|
+
input_schema: { type: 'object', properties: {}, required: [] },
|
|
453
|
+
},
|
|
454
|
+
];
|
|
455
|
+
}
|
|
456
|
+
if (protocol === 'openai-responses') {
|
|
457
|
+
return [
|
|
458
|
+
{
|
|
459
|
+
type: 'function',
|
|
460
|
+
name: picked.name,
|
|
461
|
+
description: picked.description,
|
|
462
|
+
parameters: { type: 'object', properties: {}, required: [] },
|
|
463
|
+
},
|
|
464
|
+
];
|
|
465
|
+
}
|
|
466
|
+
return [
|
|
467
|
+
{
|
|
468
|
+
type: 'function',
|
|
469
|
+
function: {
|
|
470
|
+
name: picked.name,
|
|
471
|
+
description: picked.description,
|
|
472
|
+
parameters: { type: 'object', properties: {}, required: [] },
|
|
473
|
+
},
|
|
474
|
+
},
|
|
475
|
+
];
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* Classify 3-step A/B/C single-char ("a") prompt-injection probe:
|
|
480
|
+
* - A (bare): "a", no system, no tools, default headers
|
|
481
|
+
* - B (agent): "a", 3-word system "Reply OK.", Coding Agent User-Agent, no tools
|
|
482
|
+
* - C (agent+tool): same as B + 1 minimal neutral business function tool
|
|
483
|
+
*
|
|
484
|
+
* Accounts for Anthropic's native ~260-360 token tool-use system preamble so direct
|
|
485
|
+
* official Anthropic endpoints do not trigger false positives.
|
|
486
|
+
*/
|
|
487
|
+
export function classifyInjectionProbe({
|
|
488
|
+
protocol = 'openai-chat',
|
|
489
|
+
bareInputTokens,
|
|
490
|
+
agentInputTokens,
|
|
491
|
+
toolInputTokens = null,
|
|
492
|
+
tamperFlags = [],
|
|
493
|
+
}) {
|
|
494
|
+
const bare = typeof bareInputTokens === 'number' && Number.isFinite(bareInputTokens) ? bareInputTokens : null;
|
|
495
|
+
const agent = typeof agentInputTokens === 'number' && Number.isFinite(agentInputTokens) ? agentInputTokens : null;
|
|
496
|
+
const tool = typeof toolInputTokens === 'number' && Number.isFinite(toolInputTokens) ? toolInputTokens : null;
|
|
497
|
+
|
|
498
|
+
const deltaAgent = bare !== null && agent !== null ? agent - bare : null;
|
|
499
|
+
const deltaTool = agent !== null && tool !== null ? tool - agent : null;
|
|
500
|
+
const toolDeltaFailThreshold = protocol === 'anthropic' ? 750 : 300;
|
|
501
|
+
const toolDeltaWarnThreshold = protocol === 'anthropic' ? 520 : 180;
|
|
502
|
+
|
|
503
|
+
if (tamperFlags.length > 0) {
|
|
504
|
+
return {
|
|
505
|
+
status: 'fail',
|
|
506
|
+
tier: 'tamper_detected',
|
|
507
|
+
deltaAgent,
|
|
508
|
+
deltaTool,
|
|
509
|
+
summary: `Response echo tamper detected (${tamperFlags.join(', ')})`,
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
if (bare === null && agent === null) {
|
|
514
|
+
return {
|
|
515
|
+
status: 'warn',
|
|
516
|
+
tier: 'unknown',
|
|
517
|
+
deltaAgent: null,
|
|
518
|
+
deltaTool: null,
|
|
519
|
+
summary: 'Upstream omitted usage.input_tokens; cannot measure prompt injection baseline',
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
if ((bare !== null && bare > 220) || (agent !== null && agent > 600 && (bare === null || bare > 35))) {
|
|
524
|
+
return {
|
|
525
|
+
status: 'fail',
|
|
526
|
+
tier: 'heavy_injection',
|
|
527
|
+
deltaAgent,
|
|
528
|
+
deltaTool,
|
|
529
|
+
summary: `Global heavy system prompt injection suspected (bare=${bare ?? '?'} tok, agent=${agent ?? '?'} tok)`,
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
if (bare !== null && bare <= 35 && deltaAgent !== null && deltaAgent > 180) {
|
|
534
|
+
return {
|
|
535
|
+
status: 'fail',
|
|
536
|
+
tier: 'conditional_injection',
|
|
537
|
+
deltaAgent,
|
|
538
|
+
deltaTool,
|
|
539
|
+
summary: `Conditional UA/system prompt injection detected: bare=${bare} tok jumped +${deltaAgent} tok on agent probe`,
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
if (deltaTool !== null && deltaTool > toolDeltaFailThreshold) {
|
|
544
|
+
return {
|
|
545
|
+
status: 'fail',
|
|
546
|
+
tier: 'conditional_tool_injection',
|
|
547
|
+
deltaAgent,
|
|
548
|
+
deltaTool,
|
|
549
|
+
summary: `Conditional tool-triggered prompt injection detected (+${deltaTool} tok for 1 minimal tool)`,
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
if (
|
|
554
|
+
(bare !== null && bare > 35) ||
|
|
555
|
+
(deltaAgent !== null && deltaAgent > 60) ||
|
|
556
|
+
(deltaTool !== null && deltaTool > toolDeltaWarnThreshold)
|
|
557
|
+
) {
|
|
558
|
+
return {
|
|
559
|
+
status: 'warn',
|
|
560
|
+
tier: 'micro_injection',
|
|
561
|
+
deltaAgent,
|
|
562
|
+
deltaTool,
|
|
563
|
+
summary: `Mild extra input token overhead detected (bare=${bare ?? '?'} tok, deltaAgent=${deltaAgent ?? '?'}, deltaTool=${deltaTool ?? '?'})`,
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
return {
|
|
568
|
+
status: 'pass',
|
|
569
|
+
tier: 'zero',
|
|
570
|
+
deltaAgent,
|
|
571
|
+
deltaTool,
|
|
572
|
+
summary: 'Clean baseline — no hidden system prompt or conditional injection detected',
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
export async function runInjectionProbe({ baseUrl, apiKey, protocol, model }) {
|
|
577
|
+
const agentUserAgent =
|
|
578
|
+
protocol === 'anthropic' ? 'claude-cli/2.1.0 (external, cli)' : 'codex_cli_rs/0.114.0';
|
|
579
|
+
const tinySystem = 'Reply OK.';
|
|
580
|
+
const minimalTools = buildMinimalProbeTool(protocol);
|
|
581
|
+
const probeToolName = getProbeToolName(minimalTools[0]);
|
|
582
|
+
|
|
583
|
+
// Probe A: Bare single-character baseline (no system, no tools, default UA)
|
|
584
|
+
const probeA = await callLlm({
|
|
585
|
+
baseUrl,
|
|
586
|
+
apiKey,
|
|
587
|
+
protocol,
|
|
588
|
+
model,
|
|
589
|
+
userPrompt: 'a',
|
|
590
|
+
stream: false,
|
|
591
|
+
maxTokens: 8,
|
|
592
|
+
temperature: 0,
|
|
593
|
+
});
|
|
594
|
+
|
|
595
|
+
// Probe B: Same single-char + tiny 3-word system + Coding Agent User-Agent
|
|
596
|
+
const probeB = await callLlm({
|
|
597
|
+
baseUrl,
|
|
598
|
+
apiKey,
|
|
599
|
+
protocol,
|
|
600
|
+
model,
|
|
601
|
+
system: tinySystem,
|
|
602
|
+
userPrompt: 'a',
|
|
603
|
+
stream: false,
|
|
604
|
+
maxTokens: 8,
|
|
605
|
+
temperature: 0,
|
|
606
|
+
extraHeaders: { 'user-agent': agentUserAgent },
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
// Probe C: Same as B + 1 minimal neutral tool (best-effort; some relays reject tools on certain models)
|
|
610
|
+
let probeC = null;
|
|
611
|
+
let toolError = null;
|
|
612
|
+
try {
|
|
613
|
+
probeC = await callLlm({
|
|
614
|
+
baseUrl,
|
|
615
|
+
apiKey,
|
|
616
|
+
protocol,
|
|
617
|
+
model,
|
|
618
|
+
system: tinySystem,
|
|
619
|
+
userPrompt: 'a',
|
|
620
|
+
stream: false,
|
|
621
|
+
maxTokens: 8,
|
|
622
|
+
temperature: 0,
|
|
623
|
+
tools: minimalTools,
|
|
624
|
+
extraHeaders: { 'user-agent': agentUserAgent },
|
|
625
|
+
});
|
|
626
|
+
} catch (err) {
|
|
627
|
+
toolError = err.message;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
const tamperFlags = [];
|
|
631
|
+
if (protocol === 'openai-responses') {
|
|
632
|
+
tamperFlags.push(
|
|
633
|
+
...computeResponsesEchoDiff({
|
|
634
|
+
sentInstructions: tinySystem,
|
|
635
|
+
sentToolNames: [],
|
|
636
|
+
echoInstructions: probeB.echoInstructions,
|
|
637
|
+
echoTools: probeB.echoTools,
|
|
638
|
+
})
|
|
639
|
+
);
|
|
640
|
+
if (probeC) {
|
|
641
|
+
tamperFlags.push(
|
|
642
|
+
...computeResponsesEchoDiff({
|
|
643
|
+
sentInstructions: tinySystem,
|
|
644
|
+
sentToolNames: probeToolName ? [probeToolName] : [],
|
|
645
|
+
echoInstructions: probeC.echoInstructions,
|
|
646
|
+
echoTools: probeC.echoTools,
|
|
647
|
+
})
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
const uniqueTamperFlags = Array.from(new Set(tamperFlags));
|
|
652
|
+
|
|
653
|
+
const verdict = classifyInjectionProbe({
|
|
654
|
+
protocol,
|
|
655
|
+
bareInputTokens: probeA.usage.inputTokens,
|
|
656
|
+
agentInputTokens: probeB.usage.inputTokens,
|
|
657
|
+
toolInputTokens: probeC ? probeC.usage.inputTokens : null,
|
|
658
|
+
tamperFlags: uniqueTamperFlags,
|
|
659
|
+
});
|
|
660
|
+
|
|
661
|
+
const upstreamChannel =
|
|
662
|
+
probeA.upstreamChannel?.channel !== 'unknown'
|
|
663
|
+
? probeA.upstreamChannel
|
|
664
|
+
: probeB.upstreamChannel || probeA.upstreamChannel || null;
|
|
665
|
+
|
|
666
|
+
return {
|
|
667
|
+
status: verdict.status,
|
|
668
|
+
tier: verdict.tier,
|
|
669
|
+
summary: verdict.summary,
|
|
670
|
+
agentUserAgent,
|
|
671
|
+
probeToolName,
|
|
672
|
+
bareInputTokens: probeA.usage.inputTokens,
|
|
673
|
+
agentInputTokens: probeB.usage.inputTokens,
|
|
674
|
+
toolInputTokens: probeC ? probeC.usage.inputTokens : null,
|
|
675
|
+
deltaAgent: verdict.deltaAgent,
|
|
676
|
+
deltaTool: verdict.deltaTool,
|
|
677
|
+
tamperFlags: uniqueTamperFlags,
|
|
678
|
+
upstreamChannel,
|
|
679
|
+
...(toolError ? { toolProbeNote: `skipped (${toolError.slice(0, 120)})` } : {}),
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
export async function runCacheCheck({ baseUrl, apiKey, protocol, model }) {
|
|
684
|
+
const scenario = buildCodebasePrefixScenario(14);
|
|
685
|
+
const maxTokens = isReasoningCapableModel(model) ? 800 : 160;
|
|
686
|
+
const r1 = await callLlm({
|
|
687
|
+
baseUrl,
|
|
688
|
+
apiKey,
|
|
689
|
+
protocol,
|
|
690
|
+
model,
|
|
691
|
+
system: scenario.prefix,
|
|
692
|
+
userPrompt: scenario.questionRound1,
|
|
693
|
+
stream: true,
|
|
694
|
+
maxTokens,
|
|
695
|
+
temperature: 0,
|
|
696
|
+
enableAnthropicCacheControl: protocol === 'anthropic',
|
|
697
|
+
});
|
|
698
|
+
|
|
699
|
+
// Brief pause to let upstream cache settle
|
|
700
|
+
await new Promise((r) => setTimeout(r, 1200));
|
|
701
|
+
|
|
702
|
+
const r2 = await callLlm({
|
|
703
|
+
baseUrl,
|
|
704
|
+
apiKey,
|
|
705
|
+
protocol,
|
|
706
|
+
model,
|
|
707
|
+
system: scenario.prefix,
|
|
708
|
+
userPrompt: scenario.questionRound2,
|
|
709
|
+
stream: true,
|
|
710
|
+
maxTokens,
|
|
711
|
+
temperature: 0,
|
|
712
|
+
enableAnthropicCacheControl: protocol === 'anthropic',
|
|
713
|
+
});
|
|
714
|
+
|
|
715
|
+
const input2 = r2.usage.inputTokens || 0;
|
|
716
|
+
const cached2 = r2.usage.cachedTokens || 0;
|
|
717
|
+
const hitRate = input2 > 0 ? Math.round((cached2 / input2) * 1000) / 1000 : 0;
|
|
718
|
+
const status = hitRate >= 0.6 ? 'pass' : hitRate > 0 ? 'warn' : 'fail';
|
|
719
|
+
|
|
720
|
+
return {
|
|
721
|
+
status,
|
|
722
|
+
scenarioDomain: scenario.domain,
|
|
723
|
+
round1: {
|
|
724
|
+
ttftMs: r1.ttftMs,
|
|
725
|
+
totalMs: r1.totalMs,
|
|
726
|
+
inputTokens: r1.usage.inputTokens,
|
|
727
|
+
cachedTokens: r1.usage.cachedTokens,
|
|
728
|
+
cacheCreationTokens: r1.usage.cacheCreationTokens,
|
|
729
|
+
},
|
|
730
|
+
round2: {
|
|
731
|
+
ttftMs: r2.ttftMs,
|
|
732
|
+
totalMs: r2.totalMs,
|
|
733
|
+
inputTokens: r2.usage.inputTokens,
|
|
734
|
+
cachedTokens: r2.usage.cachedTokens,
|
|
735
|
+
},
|
|
736
|
+
cacheHitRate: hitRate,
|
|
737
|
+
upstreamChannel: r2.upstreamChannel || r1.upstreamChannel || null,
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
export async function runLogicCheck({ baseUrl, apiKey, protocol, model }) {
|
|
742
|
+
const puzzle = buildDynamicPuzzle();
|
|
743
|
+
const maxTokens = isReasoningCapableModel(model) ? 4096 : 1500;
|
|
744
|
+
const res = await callLlm({
|
|
745
|
+
baseUrl,
|
|
746
|
+
apiKey,
|
|
747
|
+
protocol,
|
|
748
|
+
model,
|
|
749
|
+
userPrompt: puzzle.prompt,
|
|
750
|
+
stream: false,
|
|
751
|
+
maxTokens,
|
|
752
|
+
});
|
|
753
|
+
const graded = gradeDynamicPuzzle(res.text, puzzle.expected);
|
|
754
|
+
const hitTrap = graded.parsed === puzzle.trapAnswer;
|
|
755
|
+
return {
|
|
756
|
+
status: graded.passed ? 'pass' : 'fail',
|
|
757
|
+
expected: puzzle.expected,
|
|
758
|
+
trapAnswer: puzzle.trapAnswer,
|
|
759
|
+
parsed: graded.parsed,
|
|
760
|
+
hitTrap,
|
|
761
|
+
totalMs: res.totalMs,
|
|
762
|
+
upstreamChannel: res.upstreamChannel || null,
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
export async function runStreamAndTamperCheck({ baseUrl, apiKey, protocol, model }) {
|
|
767
|
+
const sentinelInstruction = 'You are a concise coding assistant. Reply strictly in plain text without markdown.';
|
|
768
|
+
const maxTokens = isReasoningCapableModel(model) ? 2048 : 420;
|
|
769
|
+
const res = await callLlm({
|
|
770
|
+
baseUrl,
|
|
771
|
+
apiKey,
|
|
772
|
+
protocol,
|
|
773
|
+
model,
|
|
774
|
+
system: sentinelInstruction,
|
|
775
|
+
userPrompt: 'Write a clear 140-word explanation of how HTTP/2 multiplexing prevents head-of-line blocking at the application layer.',
|
|
776
|
+
stream: true,
|
|
777
|
+
maxTokens,
|
|
778
|
+
temperature: 0.2,
|
|
779
|
+
});
|
|
780
|
+
|
|
781
|
+
const billing = evaluateOutputBilling({
|
|
782
|
+
text: res.text,
|
|
783
|
+
thinkingText: res.thinkingText,
|
|
784
|
+
reportedOutputTokens: res.usage.outputTokens,
|
|
785
|
+
reasoningTokens: res.usage.reasoningTokens,
|
|
786
|
+
thinkingChars: res.thinkingChars,
|
|
787
|
+
thinkingSigPresent: res.thinkingSigPresent,
|
|
788
|
+
redactedThinking: res.redactedThinking,
|
|
789
|
+
});
|
|
790
|
+
|
|
791
|
+
const tamperFlags =
|
|
792
|
+
protocol === 'openai-responses'
|
|
793
|
+
? computeResponsesEchoDiff({
|
|
794
|
+
sentInstructions: sentinelInstruction,
|
|
795
|
+
sentToolNames: [],
|
|
796
|
+
echoInstructions: res.echoInstructions,
|
|
797
|
+
echoTools: res.echoTools,
|
|
798
|
+
})
|
|
799
|
+
: [];
|
|
800
|
+
|
|
801
|
+
const decodeSec = Math.max(0.05, (res.decodeMs || res.totalMs) / 1000);
|
|
802
|
+
const approxTokens = billing.reportedOutputTokens ?? Math.round(res.text.length / 4);
|
|
803
|
+
const tps = Math.round((approxTokens / decodeSec) * 10) / 10;
|
|
804
|
+
|
|
805
|
+
const warnings = [];
|
|
806
|
+
if (res.fakeStreamSuspect) warnings.push('fake_stream_suspect');
|
|
807
|
+
if (billing.billingInflationSuspect) {
|
|
808
|
+
warnings.push(
|
|
809
|
+
`output_token_inflation_suspect (${billing.effectiveInflationRatio ?? billing.inflationRatio}x vs upper bound)`
|
|
810
|
+
);
|
|
811
|
+
}
|
|
812
|
+
if (tamperFlags.length > 0) warnings.push(...tamperFlags);
|
|
813
|
+
|
|
814
|
+
return {
|
|
815
|
+
status: warnings.length === 0 ? 'pass' : tamperFlags.length > 0 || billing.billingInflationSuspect ? 'fail' : 'warn',
|
|
816
|
+
ttftMs: res.ttftMs,
|
|
817
|
+
totalMs: res.totalMs,
|
|
818
|
+
chunkCount: res.chunkCount,
|
|
819
|
+
tps,
|
|
820
|
+
responseModel: res.responseModel,
|
|
821
|
+
responseId: res.responseId,
|
|
822
|
+
reportedOutputTokens: billing.reportedOutputTokens,
|
|
823
|
+
reasoningTokens: billing.reasoningTokens,
|
|
824
|
+
thinkingChars: billing.thinkingChars,
|
|
825
|
+
thinkingSigPresent: billing.thinkingSigPresent,
|
|
826
|
+
conservativeUpperBoundTokens: billing.conservativeUpperBoundTokens,
|
|
827
|
+
inflationRatio: billing.inflationRatio,
|
|
828
|
+
effectiveInflationRatio: billing.effectiveInflationRatio,
|
|
829
|
+
thinkingExempt: billing.thinkingExempt,
|
|
830
|
+
thinkingExemptReason: billing.thinkingExemptReason,
|
|
831
|
+
billingInflationSuspect: billing.billingInflationSuspect,
|
|
832
|
+
fakeStreamSuspect: res.fakeStreamSuspect,
|
|
833
|
+
tamperFlags,
|
|
834
|
+
warnings,
|
|
835
|
+
upstreamChannel: res.upstreamChannel || null,
|
|
836
|
+
responseHeaders: res.responseHeaders || {},
|
|
837
|
+
...(res.thinkingSignature && res.thinkingText
|
|
838
|
+
? {
|
|
839
|
+
_signatureTrace: {
|
|
840
|
+
system: sentinelInstruction,
|
|
841
|
+
userPrompt:
|
|
842
|
+
'Write a clear 140-word explanation of how HTTP/2 multiplexing prevents head-of-line blocking at the application layer.',
|
|
843
|
+
thinkingText: res.thinkingText,
|
|
844
|
+
thinkingSignature: res.thinkingSignature,
|
|
845
|
+
visibleText: res.text,
|
|
846
|
+
},
|
|
847
|
+
}
|
|
848
|
+
: {}),
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
/**
|
|
853
|
+
* Flip a single interior character of an Anthropic thinking signature to verify
|
|
854
|
+
* whether the upstream endpoint performs real cryptographic signature validation.
|
|
855
|
+
*/
|
|
856
|
+
export function mutateThinkingSignature(signature) {
|
|
857
|
+
const sig = String(signature || '');
|
|
858
|
+
if (sig.length < 4) return sig ? `${sig}X` : 'X';
|
|
859
|
+
const idx = Math.floor(sig.length / 2);
|
|
860
|
+
const origChar = sig[idx];
|
|
861
|
+
const flipped = origChar === 'A' ? 'B' : 'A';
|
|
862
|
+
return `${sig.slice(0, idx)}${flipped}${sig.slice(idx + 1)}`;
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/**
|
|
866
|
+
* Cryptographic Anthropic Thinking signature roundtrip check:
|
|
867
|
+
* - Reuses Turn-1 thinkingText + thinkingSignature
|
|
868
|
+
* - Probe 1: Sends intact thinking block + signature with short "Reply OK." (maxTokens=16)
|
|
869
|
+
* - Probe 2: Sends 1-char mutated signature with short "Reply OK." (maxTokens=16)
|
|
870
|
+
*
|
|
871
|
+
* Verdicts:
|
|
872
|
+
* - `verified` (pass): intact accepted (200) AND tampered rejected (400/422)
|
|
873
|
+
* - `tampered_accepted` (fail): tampered signature accepted (200) -> high-risk forged/stripped signature
|
|
874
|
+
* - `intact_rejected` (warn): intact signature rejected (400/422) -> possible routing mismatch / block corruption
|
|
875
|
+
* - `skipped` (info): missing signature or non-Anthropic protocol -> never penalized
|
|
876
|
+
* - `error` (error): non-signature transport/auth/rate-limit error
|
|
877
|
+
*/
|
|
878
|
+
export async function verifyAnthropicSignatureRoundtrip({
|
|
879
|
+
baseUrl,
|
|
880
|
+
apiKey,
|
|
881
|
+
model,
|
|
882
|
+
system = '',
|
|
883
|
+
originalUserPrompt = 'What is 17 * 23? Reply with the integer only.',
|
|
884
|
+
thinkingText = '',
|
|
885
|
+
thinkingSignature = '',
|
|
886
|
+
visibleText = '',
|
|
887
|
+
}) {
|
|
888
|
+
if (!thinkingText || !thinkingSignature || String(thinkingSignature).length < 16) {
|
|
889
|
+
return {
|
|
890
|
+
status: 'info',
|
|
891
|
+
verdict: 'skipped',
|
|
892
|
+
reason: 'no_thinking_signature_present',
|
|
893
|
+
summary: 'No Anthropic thinking signature present; skipped without penalty.',
|
|
894
|
+
};
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
const makeFollowUpMessages = (sig) => [
|
|
898
|
+
{ role: 'user', content: originalUserPrompt },
|
|
899
|
+
{
|
|
900
|
+
role: 'assistant',
|
|
901
|
+
content: [
|
|
902
|
+
{ type: 'thinking', thinking: thinkingText, signature: sig },
|
|
903
|
+
{ type: 'text', text: visibleText || 'Done.' },
|
|
904
|
+
],
|
|
905
|
+
},
|
|
906
|
+
{ role: 'user', content: 'Reply OK.' },
|
|
907
|
+
];
|
|
908
|
+
|
|
909
|
+
// Probe 1: Intact signature must be accepted
|
|
910
|
+
let intactRes = null;
|
|
911
|
+
try {
|
|
912
|
+
intactRes = await callLlm({
|
|
913
|
+
baseUrl,
|
|
914
|
+
apiKey,
|
|
915
|
+
protocol: 'anthropic',
|
|
916
|
+
model,
|
|
917
|
+
system,
|
|
918
|
+
messages: makeFollowUpMessages(thinkingSignature),
|
|
919
|
+
stream: false,
|
|
920
|
+
maxTokens: 16,
|
|
921
|
+
disableCompatRetry: true,
|
|
922
|
+
});
|
|
923
|
+
} catch (err) {
|
|
924
|
+
if (err?.httpStatus === 400 || err?.httpStatus === 422) {
|
|
925
|
+
return {
|
|
926
|
+
status: 'warn',
|
|
927
|
+
verdict: 'intact_rejected',
|
|
928
|
+
intactHttpStatus: err.httpStatus,
|
|
929
|
+
summary: 'Intact Turn-1 thinking signature was rejected on follow-up (possible relay routing drift or corrupted thinking block).',
|
|
930
|
+
detail: err.message,
|
|
931
|
+
};
|
|
932
|
+
}
|
|
933
|
+
return {
|
|
934
|
+
status: 'error',
|
|
935
|
+
verdict: 'error',
|
|
936
|
+
errorKind: err?.errorKind || 'request_error',
|
|
937
|
+
httpStatus: err?.httpStatus ?? null,
|
|
938
|
+
error: err?.message || String(err),
|
|
939
|
+
...(err?.hint ? { hint: err.hint } : {}),
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
// Probe 2: 1-char tampered signature must be rejected by real Anthropic verification
|
|
944
|
+
const tamperedSig = mutateThinkingSignature(thinkingSignature);
|
|
945
|
+
try {
|
|
946
|
+
await callLlm({
|
|
947
|
+
baseUrl,
|
|
948
|
+
apiKey,
|
|
949
|
+
protocol: 'anthropic',
|
|
950
|
+
model,
|
|
951
|
+
system,
|
|
952
|
+
messages: makeFollowUpMessages(tamperedSig),
|
|
953
|
+
stream: false,
|
|
954
|
+
maxTokens: 16,
|
|
955
|
+
disableCompatRetry: true,
|
|
956
|
+
});
|
|
957
|
+
return {
|
|
958
|
+
status: 'fail',
|
|
959
|
+
verdict: 'tampered_accepted',
|
|
960
|
+
intactHttpStatus: 200,
|
|
961
|
+
tamperedHttpStatus: 200,
|
|
962
|
+
summary: 'HIGH RISK: 1-character tampered thinking signature was accepted (HTTP 200) — upstream ignores or forges Anthropic thinking signatures.',
|
|
963
|
+
upstreamChannel: intactRes.upstreamChannel || null,
|
|
964
|
+
};
|
|
965
|
+
} catch (err) {
|
|
966
|
+
if (err?.httpStatus === 400 || err?.httpStatus === 422) {
|
|
967
|
+
return {
|
|
968
|
+
status: 'pass',
|
|
969
|
+
verdict: 'verified',
|
|
970
|
+
intactHttpStatus: 200,
|
|
971
|
+
tamperedHttpStatus: err.httpStatus,
|
|
972
|
+
summary: 'Verified: intact thinking signature accepted (200) and 1-char tampered signature rejected.',
|
|
973
|
+
upstreamChannel: intactRes.upstreamChannel || null,
|
|
974
|
+
};
|
|
975
|
+
}
|
|
976
|
+
return {
|
|
977
|
+
status: 'error',
|
|
978
|
+
verdict: 'error',
|
|
979
|
+
errorKind: err?.errorKind || 'request_error',
|
|
980
|
+
httpStatus: err?.httpStatus ?? null,
|
|
981
|
+
error: err?.message || String(err),
|
|
982
|
+
...(err?.hint ? { hint: err.hint } : {}),
|
|
983
|
+
};
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
export async function runSignatureRoundtripCheck({
|
|
988
|
+
baseUrl,
|
|
989
|
+
apiKey,
|
|
990
|
+
protocol,
|
|
991
|
+
model,
|
|
992
|
+
seedTrace = null,
|
|
993
|
+
}) {
|
|
994
|
+
if (protocol !== 'anthropic') {
|
|
995
|
+
return {
|
|
996
|
+
status: 'info',
|
|
997
|
+
verdict: 'skipped',
|
|
998
|
+
reason: 'non_anthropic_protocol',
|
|
999
|
+
summary: 'Anthropic thinking signature roundtrip applies to Anthropic protocol only; skipped.',
|
|
1000
|
+
};
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
if (seedTrace?.thinkingText && seedTrace?.thinkingSignature && seedTrace.thinkingSignature.length >= 16) {
|
|
1004
|
+
return verifyAnthropicSignatureRoundtrip({
|
|
1005
|
+
baseUrl,
|
|
1006
|
+
apiKey,
|
|
1007
|
+
model,
|
|
1008
|
+
system: seedTrace.system || '',
|
|
1009
|
+
originalUserPrompt: seedTrace.userPrompt,
|
|
1010
|
+
thinkingText: seedTrace.thinkingText,
|
|
1011
|
+
thinkingSignature: seedTrace.thinkingSignature,
|
|
1012
|
+
visibleText: seedTrace.visibleText,
|
|
1013
|
+
});
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
// Acquire Turn-1 thinking + signature with a minimal extended-thinking prompt
|
|
1017
|
+
const turn1Prompt = 'Compute 17 * 23 step by step, then reply with only the integer result.';
|
|
1018
|
+
let turn1;
|
|
1019
|
+
try {
|
|
1020
|
+
turn1 = await callLlm({
|
|
1021
|
+
baseUrl,
|
|
1022
|
+
apiKey,
|
|
1023
|
+
protocol: 'anthropic',
|
|
1024
|
+
model,
|
|
1025
|
+
userPrompt: turn1Prompt,
|
|
1026
|
+
thinking: { type: 'enabled', budget_tokens: 1024 },
|
|
1027
|
+
stream: false,
|
|
1028
|
+
maxTokens: 1536,
|
|
1029
|
+
disableCompatRetry: true,
|
|
1030
|
+
});
|
|
1031
|
+
} catch (err) {
|
|
1032
|
+
if (err?.httpStatus === 400 || err?.httpStatus === 422) {
|
|
1033
|
+
return {
|
|
1034
|
+
status: 'info',
|
|
1035
|
+
verdict: 'skipped',
|
|
1036
|
+
reason: 'thinking_not_supported',
|
|
1037
|
+
summary: 'Model/endpoint rejected extended thinking parameter; skipped without penalty.',
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
return {
|
|
1041
|
+
status: 'error',
|
|
1042
|
+
verdict: 'error',
|
|
1043
|
+
errorKind: err?.errorKind || 'request_error',
|
|
1044
|
+
httpStatus: err?.httpStatus ?? null,
|
|
1045
|
+
error: err?.message || String(err),
|
|
1046
|
+
...(err?.hint ? { hint: err.hint } : {}),
|
|
1047
|
+
};
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
if (!turn1.thinkingText || !turn1.thinkingSignature || turn1.thinkingSignature.length < 16) {
|
|
1051
|
+
return {
|
|
1052
|
+
status: 'info',
|
|
1053
|
+
verdict: 'skipped',
|
|
1054
|
+
reason: 'no_thinking_signature_present',
|
|
1055
|
+
summary: 'Upstream returned no thinking signature on Turn 1; skipped without penalty.',
|
|
1056
|
+
upstreamChannel: turn1.upstreamChannel || null,
|
|
1057
|
+
};
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
return verifyAnthropicSignatureRoundtrip({
|
|
1061
|
+
baseUrl,
|
|
1062
|
+
apiKey,
|
|
1063
|
+
model,
|
|
1064
|
+
originalUserPrompt: turn1Prompt,
|
|
1065
|
+
thinkingText: turn1.thinkingText,
|
|
1066
|
+
thinkingSignature: turn1.thinkingSignature,
|
|
1067
|
+
visibleText: turn1.text,
|
|
1068
|
+
});
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
// ============================================================================
|
|
1072
|
+
// Zero-dependency 4-color rotating 64x64 solid PNG multimodal probe (zlib)
|
|
1073
|
+
// ============================================================================
|
|
1074
|
+
|
|
1075
|
+
export const MULTIMODAL_COLORS = [
|
|
1076
|
+
{ name: 'red', rgb: [220, 38, 38], aliases: ['red', 'crimson', 'scarlet', '红', '红色'] },
|
|
1077
|
+
{ name: 'blue', rgb: [37, 99, 235], aliases: ['blue', 'azure', 'cobalt', '蓝', '蓝色'] },
|
|
1078
|
+
{ name: 'green', rgb: [22, 163, 74], aliases: ['green', 'emerald', '绿', '绿色'] },
|
|
1079
|
+
{ name: 'yellow', rgb: [234, 179, 8], aliases: ['yellow', 'gold', 'amber', '黄', '黄色'] },
|
|
1080
|
+
];
|
|
1081
|
+
|
|
1082
|
+
const CRC32_TABLE = (() => {
|
|
1083
|
+
const table = new Uint32Array(256);
|
|
1084
|
+
for (let n = 0; n < 256; n += 1) {
|
|
1085
|
+
let c = n;
|
|
1086
|
+
for (let k = 0; k < 8; k += 1) {
|
|
1087
|
+
c = (c & 1) !== 0 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
1088
|
+
}
|
|
1089
|
+
table[n] = c >>> 0;
|
|
1090
|
+
}
|
|
1091
|
+
return table;
|
|
1092
|
+
})();
|
|
1093
|
+
|
|
1094
|
+
function crc32(buf) {
|
|
1095
|
+
let c = 0xffffffff;
|
|
1096
|
+
for (let i = 0; i < buf.length; i += 1) {
|
|
1097
|
+
c = CRC32_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
|
|
1098
|
+
}
|
|
1099
|
+
return (c ^ 0xffffffff) >>> 0;
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
function makePngChunk(type, data) {
|
|
1103
|
+
const typeBuf = Buffer.from(type, 'ascii');
|
|
1104
|
+
const lenBuf = Buffer.alloc(4);
|
|
1105
|
+
lenBuf.writeUInt32BE(data.length, 0);
|
|
1106
|
+
const crcInput = Buffer.concat([typeBuf, data]);
|
|
1107
|
+
const crcBuf = Buffer.alloc(4);
|
|
1108
|
+
crcBuf.writeUInt32BE(crc32(crcInput), 0);
|
|
1109
|
+
return Buffer.concat([lenBuf, typeBuf, data, crcBuf]);
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
/**
|
|
1113
|
+
* Dynamically generate a valid RFC-2083 24-bit RGB PNG image filled with a solid color
|
|
1114
|
+
* using Node's built-in `zlib.deflateSync` (zero external dependencies).
|
|
1115
|
+
*/
|
|
1116
|
+
export function generateSolidColorPngBuffer(rgb, width = 64, height = 64) {
|
|
1117
|
+
const [r, g, b] = rgb;
|
|
1118
|
+
const w = Math.max(1, Math.trunc(width));
|
|
1119
|
+
const h = Math.max(1, Math.trunc(height));
|
|
1120
|
+
|
|
1121
|
+
const signature = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
|
1122
|
+
const ihdr = Buffer.alloc(13);
|
|
1123
|
+
ihdr.writeUInt32BE(w, 0);
|
|
1124
|
+
ihdr.writeUInt32BE(h, 4);
|
|
1125
|
+
ihdr[8] = 8; // bit depth: 8
|
|
1126
|
+
ihdr[9] = 2; // color type: Truecolor RGB
|
|
1127
|
+
ihdr[10] = 0; // compression: deflate
|
|
1128
|
+
ihdr[11] = 0; // filter: adaptive
|
|
1129
|
+
ihdr[12] = 0; // interlace: none
|
|
1130
|
+
|
|
1131
|
+
const rowStride = 1 + w * 3;
|
|
1132
|
+
const raw = Buffer.alloc(rowStride * h);
|
|
1133
|
+
for (let y = 0; y < h; y += 1) {
|
|
1134
|
+
const rowStart = y * rowStride;
|
|
1135
|
+
raw[rowStart] = 0; // filter type 0 (None)
|
|
1136
|
+
for (let x = 0; x < w; x += 1) {
|
|
1137
|
+
const px = rowStart + 1 + x * 3;
|
|
1138
|
+
raw[px] = r & 0xff;
|
|
1139
|
+
raw[px + 1] = g & 0xff;
|
|
1140
|
+
raw[px + 2] = b & 0xff;
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
const compressed = zlib.deflateSync(raw, { level: 9 });
|
|
1145
|
+
return Buffer.concat([
|
|
1146
|
+
signature,
|
|
1147
|
+
makePngChunk('IHDR', ihdr),
|
|
1148
|
+
makePngChunk('IDAT', compressed),
|
|
1149
|
+
makePngChunk('IEND', Buffer.alloc(0)),
|
|
1150
|
+
]);
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
export function generateSolidColorPngBase64(rgb, width = 64, height = 64) {
|
|
1154
|
+
return generateSolidColorPngBuffer(rgb, width, height).toString('base64');
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
export function buildMultimodalColorProbe(seed) {
|
|
1158
|
+
const idx =
|
|
1159
|
+
seed !== undefined
|
|
1160
|
+
? Math.abs(Math.trunc(Number(seed))) % MULTIMODAL_COLORS.length
|
|
1161
|
+
: crypto.randomInt(0, MULTIMODAL_COLORS.length);
|
|
1162
|
+
const spec = MULTIMODAL_COLORS[idx];
|
|
1163
|
+
const pngBuffer = generateSolidColorPngBuffer(spec.rgb, 64, 64);
|
|
1164
|
+
return {
|
|
1165
|
+
expectedColor: spec.name,
|
|
1166
|
+
rgb: spec.rgb,
|
|
1167
|
+
width: 64,
|
|
1168
|
+
height: 64,
|
|
1169
|
+
pngBytes: pngBuffer.length,
|
|
1170
|
+
pngBase64: pngBuffer.toString('base64'),
|
|
1171
|
+
prompt:
|
|
1172
|
+
'Look at the attached solid-color image and identify its dominant primary color as exactly one of: red, blue, green, or yellow. ' +
|
|
1173
|
+
'End your response with a single line: COLOR: <red|blue|green|yellow>',
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
export function gradeColorReply(replyText, expectedColor) {
|
|
1178
|
+
const text = String(replyText || '').trim();
|
|
1179
|
+
const lower = text.toLowerCase();
|
|
1180
|
+
const canonicalFromToken = (tok) => {
|
|
1181
|
+
const t = String(tok || '').toLowerCase();
|
|
1182
|
+
for (const c of MULTIMODAL_COLORS) {
|
|
1183
|
+
if (c.aliases.some((a) => a === t)) return c.name;
|
|
1184
|
+
}
|
|
1185
|
+
return null;
|
|
1186
|
+
};
|
|
1187
|
+
|
|
1188
|
+
const explicit = text.match(
|
|
1189
|
+
/COLOR\s*[:=:]\s*[*_`"'[<((\s]*(red|blue|green|yellow|crimson|scarlet|azure|cobalt|emerald|gold|amber|红色?|蓝色?|绿色?|黄色?)/i
|
|
1190
|
+
);
|
|
1191
|
+
if (explicit) {
|
|
1192
|
+
const parsed = canonicalFromToken(explicit[1]);
|
|
1193
|
+
return {
|
|
1194
|
+
passed: parsed === expectedColor,
|
|
1195
|
+
detectedColor: parsed,
|
|
1196
|
+
detectedColors: parsed ? [parsed] : [],
|
|
1197
|
+
expectedColor,
|
|
1198
|
+
wrongColorDetected: Boolean(parsed && parsed !== expectedColor),
|
|
1199
|
+
};
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
const detectedColors = [];
|
|
1203
|
+
for (const c of MULTIMODAL_COLORS) {
|
|
1204
|
+
const hit = c.aliases.some((alias) => {
|
|
1205
|
+
if (/^[a-z]+$/.test(alias)) {
|
|
1206
|
+
return new RegExp(`\\b${alias}\\b`, 'i').test(lower);
|
|
1207
|
+
}
|
|
1208
|
+
return text.includes(alias);
|
|
1209
|
+
});
|
|
1210
|
+
if (hit) detectedColors.push(c.name);
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
const passed = detectedColors.length === 1 && detectedColors[0] === expectedColor;
|
|
1214
|
+
const detectedColor = detectedColors.length === 1 ? detectedColors[0] : detectedColors[0] || null;
|
|
1215
|
+
return {
|
|
1216
|
+
passed,
|
|
1217
|
+
detectedColor,
|
|
1218
|
+
detectedColors,
|
|
1219
|
+
expectedColor,
|
|
1220
|
+
wrongColorDetected: detectedColors.some((c) => c !== expectedColor),
|
|
1221
|
+
};
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
export async function runMultimodalCheck({ baseUrl, apiKey, protocol, model, seed }) {
|
|
1225
|
+
const probe = buildMultimodalColorProbe(seed);
|
|
1226
|
+
const maxTokens = isReasoningCapableModel(model) ? 512 : 64;
|
|
1227
|
+
let res;
|
|
1228
|
+
try {
|
|
1229
|
+
res = await callLlm({
|
|
1230
|
+
baseUrl,
|
|
1231
|
+
apiKey,
|
|
1232
|
+
protocol,
|
|
1233
|
+
model,
|
|
1234
|
+
userPrompt: probe.prompt,
|
|
1235
|
+
imageBase64: probe.pngBase64,
|
|
1236
|
+
imageMediaType: 'image/png',
|
|
1237
|
+
stream: false,
|
|
1238
|
+
maxTokens,
|
|
1239
|
+
temperature: 0,
|
|
1240
|
+
});
|
|
1241
|
+
} catch (err) {
|
|
1242
|
+
if (
|
|
1243
|
+
(err?.httpStatus === 400 || err?.httpStatus === 422) &&
|
|
1244
|
+
/image|vision|multimodal|content.*must be.*string|not support/i.test(String(err.message || ''))
|
|
1245
|
+
) {
|
|
1246
|
+
return {
|
|
1247
|
+
status: 'warn',
|
|
1248
|
+
reason: 'vision_unsupported',
|
|
1249
|
+
expectedColor: probe.expectedColor,
|
|
1250
|
+
detectedColor: null,
|
|
1251
|
+
passed: false,
|
|
1252
|
+
pngBytes: probe.pngBytes,
|
|
1253
|
+
summary: 'Upstream/model rejected multimodal image input (vision unsupported or stripped).',
|
|
1254
|
+
detail: err.message,
|
|
1255
|
+
};
|
|
1256
|
+
}
|
|
1257
|
+
throw err;
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
const graded = gradeColorReply(res.text, probe.expectedColor);
|
|
1261
|
+
return {
|
|
1262
|
+
status: graded.passed ? 'pass' : 'fail',
|
|
1263
|
+
expectedColor: probe.expectedColor,
|
|
1264
|
+
detectedColor: graded.detectedColor,
|
|
1265
|
+
detectedColors: graded.detectedColors,
|
|
1266
|
+
passed: graded.passed,
|
|
1267
|
+
wrongColorDetected: graded.wrongColorDetected,
|
|
1268
|
+
pngDimensions: `${probe.width}x${probe.height}`,
|
|
1269
|
+
pngBytes: probe.pngBytes,
|
|
1270
|
+
totalMs: res.totalMs,
|
|
1271
|
+
upstreamChannel: res.upstreamChannel || null,
|
|
1272
|
+
};
|
|
1273
|
+
}
|