llm-api-purity-check 1.2.0 → 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/README.md +75 -32
- package/README_CN.md +64 -29
- package/bin/cli.mjs +147 -26
- package/data/bank.generated.json +1 -1
- package/package.json +3 -2
- package/scripts/sync-bank.mjs +333 -0
- package/skills/aiapipk-check/SKILL.md +134 -0
- package/src/checks.mjs +794 -58
- package/src/client.mjs +1000 -98
- package/src/fingerprint.mjs +326 -44
- package/src/links.mjs +12 -5
- package/src/modelIdNormalize.mjs +94 -0
- package/test/links.test.mjs +0 -60
- package/test/purity.test.mjs +0 -186
package/src/checks.mjs
CHANGED
|
@@ -1,49 +1,206 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Anti-downgrade, real Prompt Caching, streaming cadence, token-billing sanity
|
|
2
|
+
* Anti-downgrade, real Prompt Caching, streaming cadence, token-billing sanity
|
|
3
|
+
* (with thinking/reasoning exemption), upstream channel visibility,
|
|
3
4
|
* and /v1/responses instruction/tools tamper checks.
|
|
4
5
|
*
|
|
5
6
|
* Extracted from AIAPIPK (https://www.aiapipk.com/detect/).
|
|
6
7
|
*/
|
|
7
8
|
|
|
8
|
-
import
|
|
9
|
+
import crypto from 'node:crypto';
|
|
10
|
+
import zlib from 'node:zlib';
|
|
11
|
+
import { callLlm, isReasoningCapableModel } from './client.mjs';
|
|
9
12
|
|
|
10
|
-
export
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
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}],
|
|
21
77
|
]);
|
|
22
78
|
|
|
23
|
-
public
|
|
24
|
-
let
|
|
79
|
+
public allocateDockLane(congestionMap: Record<string, number>, faultRateMap: Record<string, number>): string {
|
|
80
|
+
let bestLane = "north_bay_${i}";
|
|
25
81
|
let bestScore = -Infinity;
|
|
26
|
-
for (const [
|
|
27
|
-
const
|
|
28
|
-
const
|
|
29
|
-
const
|
|
30
|
-
const score = (
|
|
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);
|
|
31
87
|
if (score > bestScore) {
|
|
32
88
|
bestScore = score;
|
|
33
|
-
|
|
89
|
+
bestLane = lane;
|
|
34
90
|
}
|
|
35
91
|
}
|
|
36
|
-
return
|
|
92
|
+
return bestLane;
|
|
37
93
|
}
|
|
38
94
|
|
|
39
|
-
public
|
|
40
|
-
const
|
|
41
|
-
const
|
|
42
|
-
return Math.round(
|
|
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;
|
|
43
99
|
}
|
|
44
|
-
}
|
|
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;
|
|
45
133
|
}
|
|
46
|
-
|
|
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;
|
|
47
204
|
}
|
|
48
205
|
|
|
49
206
|
export function solveTwoShapePigeonhole(a1, a2, p1, p2, w1, w2) {
|
|
@@ -173,12 +330,125 @@ export function estimateConservativeMaxTokens(text) {
|
|
|
173
330
|
return Math.max(12, Math.ceil(cjk * 1.5 + nonCjk * 0.38 + 20));
|
|
174
331
|
}
|
|
175
332
|
|
|
176
|
-
|
|
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
|
+
|
|
177
447
|
if (protocol === 'anthropic') {
|
|
178
448
|
return [
|
|
179
449
|
{
|
|
180
|
-
name:
|
|
181
|
-
description:
|
|
450
|
+
name: picked.name,
|
|
451
|
+
description: picked.description,
|
|
182
452
|
input_schema: { type: 'object', properties: {}, required: [] },
|
|
183
453
|
},
|
|
184
454
|
];
|
|
@@ -187,8 +457,8 @@ export function buildMinimalProbeTool(protocol) {
|
|
|
187
457
|
return [
|
|
188
458
|
{
|
|
189
459
|
type: 'function',
|
|
190
|
-
name:
|
|
191
|
-
description:
|
|
460
|
+
name: picked.name,
|
|
461
|
+
description: picked.description,
|
|
192
462
|
parameters: { type: 'object', properties: {}, required: [] },
|
|
193
463
|
},
|
|
194
464
|
];
|
|
@@ -197,8 +467,8 @@ export function buildMinimalProbeTool(protocol) {
|
|
|
197
467
|
{
|
|
198
468
|
type: 'function',
|
|
199
469
|
function: {
|
|
200
|
-
name:
|
|
201
|
-
description:
|
|
470
|
+
name: picked.name,
|
|
471
|
+
description: picked.description,
|
|
202
472
|
parameters: { type: 'object', properties: {}, required: [] },
|
|
203
473
|
},
|
|
204
474
|
},
|
|
@@ -209,7 +479,7 @@ export function buildMinimalProbeTool(protocol) {
|
|
|
209
479
|
* Classify 3-step A/B/C single-char ("a") prompt-injection probe:
|
|
210
480
|
* - A (bare): "a", no system, no tools, default headers
|
|
211
481
|
* - B (agent): "a", 3-word system "Reply OK.", Coding Agent User-Agent, no tools
|
|
212
|
-
* - C (agent+tool): same as B + 1 minimal
|
|
482
|
+
* - C (agent+tool): same as B + 1 minimal neutral business function tool
|
|
213
483
|
*
|
|
214
484
|
* Accounts for Anthropic's native ~260-360 token tool-use system preamble so direct
|
|
215
485
|
* official Anthropic endpoints do not trigger false positives.
|
|
@@ -308,6 +578,7 @@ export async function runInjectionProbe({ baseUrl, apiKey, protocol, model }) {
|
|
|
308
578
|
protocol === 'anthropic' ? 'claude-cli/2.1.0 (external, cli)' : 'codex_cli_rs/0.114.0';
|
|
309
579
|
const tinySystem = 'Reply OK.';
|
|
310
580
|
const minimalTools = buildMinimalProbeTool(protocol);
|
|
581
|
+
const probeToolName = getProbeToolName(minimalTools[0]);
|
|
311
582
|
|
|
312
583
|
// Probe A: Bare single-character baseline (no system, no tools, default UA)
|
|
313
584
|
const probeA = await callLlm({
|
|
@@ -335,7 +606,7 @@ export async function runInjectionProbe({ baseUrl, apiKey, protocol, model }) {
|
|
|
335
606
|
extraHeaders: { 'user-agent': agentUserAgent },
|
|
336
607
|
});
|
|
337
608
|
|
|
338
|
-
// Probe C: Same as B + 1 minimal tool (best-effort; some relays reject tools on certain models)
|
|
609
|
+
// Probe C: Same as B + 1 minimal neutral tool (best-effort; some relays reject tools on certain models)
|
|
339
610
|
let probeC = null;
|
|
340
611
|
let toolError = null;
|
|
341
612
|
try {
|
|
@@ -370,7 +641,7 @@ export async function runInjectionProbe({ baseUrl, apiKey, protocol, model }) {
|
|
|
370
641
|
tamperFlags.push(
|
|
371
642
|
...computeResponsesEchoDiff({
|
|
372
643
|
sentInstructions: tinySystem,
|
|
373
|
-
sentToolNames: [
|
|
644
|
+
sentToolNames: probeToolName ? [probeToolName] : [],
|
|
374
645
|
echoInstructions: probeC.echoInstructions,
|
|
375
646
|
echoTools: probeC.echoTools,
|
|
376
647
|
})
|
|
@@ -387,32 +658,40 @@ export async function runInjectionProbe({ baseUrl, apiKey, protocol, model }) {
|
|
|
387
658
|
tamperFlags: uniqueTamperFlags,
|
|
388
659
|
});
|
|
389
660
|
|
|
661
|
+
const upstreamChannel =
|
|
662
|
+
probeA.upstreamChannel?.channel !== 'unknown'
|
|
663
|
+
? probeA.upstreamChannel
|
|
664
|
+
: probeB.upstreamChannel || probeA.upstreamChannel || null;
|
|
665
|
+
|
|
390
666
|
return {
|
|
391
667
|
status: verdict.status,
|
|
392
668
|
tier: verdict.tier,
|
|
393
669
|
summary: verdict.summary,
|
|
394
670
|
agentUserAgent,
|
|
671
|
+
probeToolName,
|
|
395
672
|
bareInputTokens: probeA.usage.inputTokens,
|
|
396
673
|
agentInputTokens: probeB.usage.inputTokens,
|
|
397
674
|
toolInputTokens: probeC ? probeC.usage.inputTokens : null,
|
|
398
675
|
deltaAgent: verdict.deltaAgent,
|
|
399
676
|
deltaTool: verdict.deltaTool,
|
|
400
677
|
tamperFlags: uniqueTamperFlags,
|
|
678
|
+
upstreamChannel,
|
|
401
679
|
...(toolError ? { toolProbeNote: `skipped (${toolError.slice(0, 120)})` } : {}),
|
|
402
680
|
};
|
|
403
681
|
}
|
|
404
682
|
|
|
405
683
|
export async function runCacheCheck({ baseUrl, apiKey, protocol, model }) {
|
|
406
|
-
const
|
|
684
|
+
const scenario = buildCodebasePrefixScenario(14);
|
|
685
|
+
const maxTokens = isReasoningCapableModel(model) ? 800 : 160;
|
|
407
686
|
const r1 = await callLlm({
|
|
408
687
|
baseUrl,
|
|
409
688
|
apiKey,
|
|
410
689
|
protocol,
|
|
411
690
|
model,
|
|
412
|
-
system: prefix,
|
|
413
|
-
userPrompt:
|
|
691
|
+
system: scenario.prefix,
|
|
692
|
+
userPrompt: scenario.questionRound1,
|
|
414
693
|
stream: true,
|
|
415
|
-
maxTokens
|
|
694
|
+
maxTokens,
|
|
416
695
|
temperature: 0,
|
|
417
696
|
enableAnthropicCacheControl: protocol === 'anthropic',
|
|
418
697
|
});
|
|
@@ -425,10 +704,10 @@ export async function runCacheCheck({ baseUrl, apiKey, protocol, model }) {
|
|
|
425
704
|
apiKey,
|
|
426
705
|
protocol,
|
|
427
706
|
model,
|
|
428
|
-
system: prefix,
|
|
429
|
-
userPrompt:
|
|
707
|
+
system: scenario.prefix,
|
|
708
|
+
userPrompt: scenario.questionRound2,
|
|
430
709
|
stream: true,
|
|
431
|
-
maxTokens
|
|
710
|
+
maxTokens,
|
|
432
711
|
temperature: 0,
|
|
433
712
|
enableAnthropicCacheControl: protocol === 'anthropic',
|
|
434
713
|
});
|
|
@@ -440,6 +719,7 @@ export async function runCacheCheck({ baseUrl, apiKey, protocol, model }) {
|
|
|
440
719
|
|
|
441
720
|
return {
|
|
442
721
|
status,
|
|
722
|
+
scenarioDomain: scenario.domain,
|
|
443
723
|
round1: {
|
|
444
724
|
ttftMs: r1.ttftMs,
|
|
445
725
|
totalMs: r1.totalMs,
|
|
@@ -454,11 +734,13 @@ export async function runCacheCheck({ baseUrl, apiKey, protocol, model }) {
|
|
|
454
734
|
cachedTokens: r2.usage.cachedTokens,
|
|
455
735
|
},
|
|
456
736
|
cacheHitRate: hitRate,
|
|
737
|
+
upstreamChannel: r2.upstreamChannel || r1.upstreamChannel || null,
|
|
457
738
|
};
|
|
458
739
|
}
|
|
459
740
|
|
|
460
741
|
export async function runLogicCheck({ baseUrl, apiKey, protocol, model }) {
|
|
461
742
|
const puzzle = buildDynamicPuzzle();
|
|
743
|
+
const maxTokens = isReasoningCapableModel(model) ? 4096 : 1500;
|
|
462
744
|
const res = await callLlm({
|
|
463
745
|
baseUrl,
|
|
464
746
|
apiKey,
|
|
@@ -466,7 +748,7 @@ export async function runLogicCheck({ baseUrl, apiKey, protocol, model }) {
|
|
|
466
748
|
model,
|
|
467
749
|
userPrompt: puzzle.prompt,
|
|
468
750
|
stream: false,
|
|
469
|
-
maxTokens
|
|
751
|
+
maxTokens,
|
|
470
752
|
});
|
|
471
753
|
const graded = gradeDynamicPuzzle(res.text, puzzle.expected);
|
|
472
754
|
const hitTrap = graded.parsed === puzzle.trapAnswer;
|
|
@@ -477,11 +759,13 @@ export async function runLogicCheck({ baseUrl, apiKey, protocol, model }) {
|
|
|
477
759
|
parsed: graded.parsed,
|
|
478
760
|
hitTrap,
|
|
479
761
|
totalMs: res.totalMs,
|
|
762
|
+
upstreamChannel: res.upstreamChannel || null,
|
|
480
763
|
};
|
|
481
764
|
}
|
|
482
765
|
|
|
483
766
|
export async function runStreamAndTamperCheck({ baseUrl, apiKey, protocol, model }) {
|
|
484
767
|
const sentinelInstruction = 'You are a concise coding assistant. Reply strictly in plain text without markdown.';
|
|
768
|
+
const maxTokens = isReasoningCapableModel(model) ? 2048 : 420;
|
|
485
769
|
const res = await callLlm({
|
|
486
770
|
baseUrl,
|
|
487
771
|
apiKey,
|
|
@@ -490,15 +774,19 @@ export async function runStreamAndTamperCheck({ baseUrl, apiKey, protocol, model
|
|
|
490
774
|
system: sentinelInstruction,
|
|
491
775
|
userPrompt: 'Write a clear 140-word explanation of how HTTP/2 multiplexing prevents head-of-line blocking at the application layer.',
|
|
492
776
|
stream: true,
|
|
493
|
-
maxTokens
|
|
777
|
+
maxTokens,
|
|
494
778
|
temperature: 0.2,
|
|
495
779
|
});
|
|
496
780
|
|
|
497
|
-
const
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
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
|
+
});
|
|
502
790
|
|
|
503
791
|
const tamperFlags =
|
|
504
792
|
protocol === 'openai-responses'
|
|
@@ -511,27 +799,475 @@ export async function runStreamAndTamperCheck({ baseUrl, apiKey, protocol, model
|
|
|
511
799
|
: [];
|
|
512
800
|
|
|
513
801
|
const decodeSec = Math.max(0.05, (res.decodeMs || res.totalMs) / 1000);
|
|
514
|
-
const approxTokens =
|
|
802
|
+
const approxTokens = billing.reportedOutputTokens ?? Math.round(res.text.length / 4);
|
|
515
803
|
const tps = Math.round((approxTokens / decodeSec) * 10) / 10;
|
|
516
804
|
|
|
517
805
|
const warnings = [];
|
|
518
806
|
if (res.fakeStreamSuspect) warnings.push('fake_stream_suspect');
|
|
519
|
-
if (billingInflationSuspect)
|
|
807
|
+
if (billing.billingInflationSuspect) {
|
|
808
|
+
warnings.push(
|
|
809
|
+
`output_token_inflation_suspect (${billing.effectiveInflationRatio ?? billing.inflationRatio}x vs upper bound)`
|
|
810
|
+
);
|
|
811
|
+
}
|
|
520
812
|
if (tamperFlags.length > 0) warnings.push(...tamperFlags);
|
|
521
813
|
|
|
522
814
|
return {
|
|
523
|
-
status: warnings.length === 0 ? 'pass' : tamperFlags.length > 0 || billingInflationSuspect ? 'fail' : 'warn',
|
|
815
|
+
status: warnings.length === 0 ? 'pass' : tamperFlags.length > 0 || billing.billingInflationSuspect ? 'fail' : 'warn',
|
|
524
816
|
ttftMs: res.ttftMs,
|
|
525
817
|
totalMs: res.totalMs,
|
|
526
818
|
chunkCount: res.chunkCount,
|
|
527
819
|
tps,
|
|
528
820
|
responseModel: res.responseModel,
|
|
529
821
|
responseId: res.responseId,
|
|
530
|
-
reportedOutputTokens:
|
|
531
|
-
|
|
532
|
-
|
|
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,
|
|
533
832
|
fakeStreamSuspect: res.fakeStreamSuspect,
|
|
534
833
|
tamperFlags,
|
|
535
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,
|
|
536
1272
|
};
|
|
537
1273
|
}
|