llm-api-purity-check 0.0.0-stage → 1.2.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 +118 -2
- package/README_CN.md +87 -0
- package/bin/cli.mjs +294 -0
- package/data/bank.generated.json +1 -0
- package/package.json +38 -4
- package/src/checks.mjs +537 -0
- package/src/client.mjs +338 -0
- package/src/fingerprint.mjs +383 -0
- package/src/links.mjs +128 -0
- package/test/links.test.mjs +60 -0
- package/test/purity.test.mjs +186 -0
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "llm-api-purity-check",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "Zero-dependency CLI to audit third-party LLM API proxies for hidden/conditional prompt injection, model substitution (1-355 numerical fingerprinting), downgrade, fake Prompt Caching, instruction/tools tampering, and output token inflation.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"llm-api-purity-check": "bin/cli.mjs"
|
|
8
|
+
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"test": "node --test test/*.test.mjs",
|
|
11
|
+
"start": "node bin/cli.mjs"
|
|
12
|
+
},
|
|
13
|
+
"keywords": [
|
|
14
|
+
"llm",
|
|
15
|
+
"ai-api",
|
|
16
|
+
"openai",
|
|
17
|
+
"anthropic",
|
|
18
|
+
"claude",
|
|
19
|
+
"prompt-caching",
|
|
20
|
+
"fingerprinting",
|
|
21
|
+
"benchmark",
|
|
22
|
+
"api-audit",
|
|
23
|
+
"aiapipk"
|
|
24
|
+
],
|
|
25
|
+
"author": "AIAPIPK (https://www.aiapipk.com)",
|
|
26
|
+
"license": "MIT",
|
|
27
|
+
"homepage": "https://www.aiapipk.com/detect/",
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "git+https://github.com/yiios/llm-api-purity-check.git"
|
|
31
|
+
},
|
|
32
|
+
"engines": {
|
|
33
|
+
"node": ">=18.0.0"
|
|
34
|
+
},
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"registry": "https://registry.npmjs.org/",
|
|
37
|
+
"access": "public"
|
|
38
|
+
},
|
|
39
|
+
"dependencies": {}
|
|
40
|
+
}
|
package/src/checks.mjs
ADDED
|
@@ -0,0 +1,537 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anti-downgrade, real Prompt Caching, streaming cadence, token-billing sanity,
|
|
3
|
+
* and /v1/responses instruction/tools tamper checks.
|
|
4
|
+
*
|
|
5
|
+
* Extracted from AIAPIPK (https://www.aiapipk.com/detect/).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { callLlm } from './client.mjs';
|
|
9
|
+
|
|
10
|
+
export function buildCodebasePrefix(repeatBlocks = 14) {
|
|
11
|
+
const blocks = [];
|
|
12
|
+
for (let i = 1; i <= repeatBlocks; i += 1) {
|
|
13
|
+
blocks.push(`
|
|
14
|
+
export class RelayRoutePartition${i} {
|
|
15
|
+
private readonly partitionId = "part_${i}";
|
|
16
|
+
private readonly maxRetries = ${(i % 3) + 2};
|
|
17
|
+
private readonly weights = new Map<string, number>([
|
|
18
|
+
["primary_${i}", ${100 + i * 5}],
|
|
19
|
+
["backup_${i}", ${40 + i * 3}],
|
|
20
|
+
["fallback_${i}", ${15 + i}],
|
|
21
|
+
]);
|
|
22
|
+
|
|
23
|
+
public selectEndpoint(latencyMap: Record<string, number>, errorRateMap: Record<string, number>): string {
|
|
24
|
+
let bestKey = "primary_${i}";
|
|
25
|
+
let bestScore = -Infinity;
|
|
26
|
+
for (const [key, baseWeight] of this.weights.entries()) {
|
|
27
|
+
const latency = Math.max(50, latencyMap[key] ?? 800);
|
|
28
|
+
const errRate = Math.min(1, Math.max(0, errorRateMap[key] ?? 0));
|
|
29
|
+
const healthFactor = (1 - errRate) * (1 - errRate);
|
|
30
|
+
const score = (baseWeight * healthFactor) / Math.log2(latency + 16);
|
|
31
|
+
if (score > bestScore) {
|
|
32
|
+
bestScore = score;
|
|
33
|
+
bestKey = key;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return bestKey;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
public computeEffectiveBudget(inputTokens: number, cachedTokens: number, outputTokens: number, ratio: number): number {
|
|
40
|
+
const billableInput = Math.max(0, inputTokens - cachedTokens) * 1.0 + cachedTokens * 0.1;
|
|
41
|
+
const totalUnits = (billableInput + outputTokens * 5.0) / 1_000_000;
|
|
42
|
+
return Math.round(totalUnits * ratio * 10000) / 10000;
|
|
43
|
+
}
|
|
44
|
+
}`);
|
|
45
|
+
}
|
|
46
|
+
return `// Deterministic 2.5K+ token routing module context for Prompt Caching verification\n${blocks.join('\n')}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function solveTwoShapePigeonhole(a1, a2, p1, p2, w1, w2) {
|
|
50
|
+
let optimal = Number.POSITIVE_INFINITY;
|
|
51
|
+
let bestX = 0;
|
|
52
|
+
let bestY = 0;
|
|
53
|
+
const maxS1 = a1 + p1 + w1;
|
|
54
|
+
const maxS2 = a2 + p2 + w2;
|
|
55
|
+
|
|
56
|
+
for (let x = 0; x <= maxS1; x += 1) {
|
|
57
|
+
for (let y = 0; y <= maxS2; y += 1) {
|
|
58
|
+
const canFail =
|
|
59
|
+
x <= w1 ||
|
|
60
|
+
y <= w2 ||
|
|
61
|
+
(x <= a1 + w1 && y <= a2 + w2) ||
|
|
62
|
+
(x <= p1 + w1 && y <= p2 + w2);
|
|
63
|
+
if (!canFail && x + y < optimal) {
|
|
64
|
+
optimal = x + y;
|
|
65
|
+
bestX = x;
|
|
66
|
+
bestY = y;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const trap =
|
|
72
|
+
Math.max(a1 + a2 + w1 + w2, p1 + p2 + w1 + w2, a1 + p1 + w1 + w2, a2 + p2 + w1 + w2) + 1;
|
|
73
|
+
|
|
74
|
+
return { optimal, bestX, bestY, trap };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function buildDynamicPuzzle(seed) {
|
|
78
|
+
let rngState =
|
|
79
|
+
seed !== undefined ? seed >>> 0 : (Date.now() ^ Math.floor(Math.random() * 0xffffffff)) >>> 0;
|
|
80
|
+
const nextRand = () => {
|
|
81
|
+
rngState = (Math.imul(1664525, rngState) + 1013904223) >>> 0;
|
|
82
|
+
return rngState / 0x100000000;
|
|
83
|
+
};
|
|
84
|
+
const randInt = (min, max) => min + Math.floor(nextRand() * (max - min + 1));
|
|
85
|
+
|
|
86
|
+
let a1 = 8, a2 = 6, p1 = 10, p2 = 8, w1 = 7, w2 = 5;
|
|
87
|
+
let solved = solveTwoShapePigeonhole(a1, a2, p1, p2, w1, w2);
|
|
88
|
+
|
|
89
|
+
for (let attempt = 0; attempt < 40; attempt += 1) {
|
|
90
|
+
const ca1 = randInt(5, 11);
|
|
91
|
+
const ca2 = randInt(5, 10);
|
|
92
|
+
const cp1 = randInt(6, 12);
|
|
93
|
+
const cp2 = randInt(5, 10);
|
|
94
|
+
const cw1 = randInt(5, 10);
|
|
95
|
+
const cw2 = randInt(3, 8);
|
|
96
|
+
const res = solveTwoShapePigeonhole(ca1, ca2, cp1, cp2, cw1, cw2);
|
|
97
|
+
if (res.optimal !== 21 && res.optimal >= 17 && res.optimal <= 34 && res.trap - res.optimal >= 6) {
|
|
98
|
+
a1 = ca1; a2 = ca2; p1 = cp1; p2 = cp2; w1 = cw1; w2 = cw2;
|
|
99
|
+
solved = res;
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const prompt =
|
|
105
|
+
'Do NOT use any tools or web search. An opaque box contains candies in 3 flavors (strawberry, mango, blueberry) and 2 shapes (cube, sphere). ' +
|
|
106
|
+
'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. ' +
|
|
107
|
+
`Counts: ${a1} strawberry cubes, ${a2} strawberry spheres, ${p1} mango cubes, ${p2} mango spheres, ${w1} blueberry cubes, ${w2} blueberry spheres. ` +
|
|
108
|
+
'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)? ' +
|
|
109
|
+
'Think carefully and end your response with a single final line: ANSWER: <integer>';
|
|
110
|
+
|
|
111
|
+
return {
|
|
112
|
+
prompt,
|
|
113
|
+
expected: solved.optimal,
|
|
114
|
+
trapAnswer: solved.trap,
|
|
115
|
+
bestSplit: { cubes: solved.bestX, spheres: solved.bestY },
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function gradeDynamicPuzzle(replyText, expected) {
|
|
120
|
+
const text = String(replyText || '').trim().slice(-4000);
|
|
121
|
+
if (!text) return { passed: false, parsed: null };
|
|
122
|
+
const m = text.match(/ANSWER\s*[:=]\s*(-?\d+)/i);
|
|
123
|
+
if (m) return { passed: Number(m[1]) === expected, parsed: Number(m[1]) };
|
|
124
|
+
const exact = text.match(/^\s*(-?\d+)\s*$/);
|
|
125
|
+
if (exact) return { passed: Number(exact[1]) === expected, parsed: Number(exact[1]) };
|
|
126
|
+
const nums = text.match(/-?\d+/g);
|
|
127
|
+
if (!nums || nums.length === 0) return { passed: false, parsed: null };
|
|
128
|
+
const last = Number(nums[nums.length - 1]);
|
|
129
|
+
return { passed: last === expected, parsed: last };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function computeResponsesEchoDiff({ sentInstructions = '', sentToolNames = [], echoInstructions = null, echoTools = null }) {
|
|
133
|
+
const tamperFlags = [];
|
|
134
|
+
const sentInstr = sentInstructions.trim();
|
|
135
|
+
const echoInstr = typeof echoInstructions === 'string' ? echoInstructions.trim() : null;
|
|
136
|
+
|
|
137
|
+
if (echoInstr !== null) {
|
|
138
|
+
if (!sentInstr && echoInstr.length >= 60) {
|
|
139
|
+
tamperFlags.push('instructions_injected');
|
|
140
|
+
} else if (sentInstr && echoInstr !== sentInstr) {
|
|
141
|
+
const normSent = sentInstr.replace(/\s+/g, ' ');
|
|
142
|
+
const normEcho = echoInstr.replace(/\s+/g, ' ');
|
|
143
|
+
if (Math.abs(normEcho.length - normSent.length) >= 40 || (!normEcho.includes(normSent) && normEcho.length >= 40)) {
|
|
144
|
+
tamperFlags.push('instructions_injected');
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (Array.isArray(echoTools)) {
|
|
150
|
+
if (sentToolNames.length === 0 && echoTools.length > 0) {
|
|
151
|
+
tamperFlags.push('tools_injected');
|
|
152
|
+
} else if (sentToolNames.length > 0) {
|
|
153
|
+
const echoedNames = new Set(echoTools.map((t) => String(t?.name || t?.function?.name || '').trim()).filter(Boolean));
|
|
154
|
+
if (sentToolNames.some((n) => !echoedNames.has(n))) {
|
|
155
|
+
tamperFlags.push('tools_deleted');
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return tamperFlags;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Conservative zero-dependency output token estimator (used to catch gross >1.6x billing inflation).
|
|
165
|
+
* For exact BPE/Tiktoken recount, use the online verifier at https://www.aiapipk.com/detect/.
|
|
166
|
+
*/
|
|
167
|
+
export function estimateConservativeMaxTokens(text) {
|
|
168
|
+
const s = String(text || '');
|
|
169
|
+
if (!s) return 0;
|
|
170
|
+
const cjk = (s.match(/[\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]/g) || []).length;
|
|
171
|
+
const nonCjk = s.length - cjk;
|
|
172
|
+
// Upper-bound conservative estimate: ~1.5 tok per CJK char + ~0.38 tok per ASCII/Latin char + overhead
|
|
173
|
+
return Math.max(12, Math.ceil(cjk * 1.5 + nonCjk * 0.38 + 20));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function buildMinimalProbeTool(protocol) {
|
|
177
|
+
if (protocol === 'anthropic') {
|
|
178
|
+
return [
|
|
179
|
+
{
|
|
180
|
+
name: 'ping_health',
|
|
181
|
+
description: 'Return status ok.',
|
|
182
|
+
input_schema: { type: 'object', properties: {}, required: [] },
|
|
183
|
+
},
|
|
184
|
+
];
|
|
185
|
+
}
|
|
186
|
+
if (protocol === 'openai-responses') {
|
|
187
|
+
return [
|
|
188
|
+
{
|
|
189
|
+
type: 'function',
|
|
190
|
+
name: 'ping_health',
|
|
191
|
+
description: 'Return status ok.',
|
|
192
|
+
parameters: { type: 'object', properties: {}, required: [] },
|
|
193
|
+
},
|
|
194
|
+
];
|
|
195
|
+
}
|
|
196
|
+
return [
|
|
197
|
+
{
|
|
198
|
+
type: 'function',
|
|
199
|
+
function: {
|
|
200
|
+
name: 'ping_health',
|
|
201
|
+
description: 'Return status ok.',
|
|
202
|
+
parameters: { type: 'object', properties: {}, required: [] },
|
|
203
|
+
},
|
|
204
|
+
},
|
|
205
|
+
];
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Classify 3-step A/B/C single-char ("a") prompt-injection probe:
|
|
210
|
+
* - A (bare): "a", no system, no tools, default headers
|
|
211
|
+
* - B (agent): "a", 3-word system "Reply OK.", Coding Agent User-Agent, no tools
|
|
212
|
+
* - C (agent+tool): same as B + 1 minimal ping_health tool
|
|
213
|
+
*
|
|
214
|
+
* Accounts for Anthropic's native ~260-360 token tool-use system preamble so direct
|
|
215
|
+
* official Anthropic endpoints do not trigger false positives.
|
|
216
|
+
*/
|
|
217
|
+
export function classifyInjectionProbe({
|
|
218
|
+
protocol = 'openai-chat',
|
|
219
|
+
bareInputTokens,
|
|
220
|
+
agentInputTokens,
|
|
221
|
+
toolInputTokens = null,
|
|
222
|
+
tamperFlags = [],
|
|
223
|
+
}) {
|
|
224
|
+
const bare = typeof bareInputTokens === 'number' && Number.isFinite(bareInputTokens) ? bareInputTokens : null;
|
|
225
|
+
const agent = typeof agentInputTokens === 'number' && Number.isFinite(agentInputTokens) ? agentInputTokens : null;
|
|
226
|
+
const tool = typeof toolInputTokens === 'number' && Number.isFinite(toolInputTokens) ? toolInputTokens : null;
|
|
227
|
+
|
|
228
|
+
const deltaAgent = bare !== null && agent !== null ? agent - bare : null;
|
|
229
|
+
const deltaTool = agent !== null && tool !== null ? tool - agent : null;
|
|
230
|
+
const toolDeltaFailThreshold = protocol === 'anthropic' ? 750 : 300;
|
|
231
|
+
const toolDeltaWarnThreshold = protocol === 'anthropic' ? 520 : 180;
|
|
232
|
+
|
|
233
|
+
if (tamperFlags.length > 0) {
|
|
234
|
+
return {
|
|
235
|
+
status: 'fail',
|
|
236
|
+
tier: 'tamper_detected',
|
|
237
|
+
deltaAgent,
|
|
238
|
+
deltaTool,
|
|
239
|
+
summary: `Response echo tamper detected (${tamperFlags.join(', ')})`,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
if (bare === null && agent === null) {
|
|
244
|
+
return {
|
|
245
|
+
status: 'warn',
|
|
246
|
+
tier: 'unknown',
|
|
247
|
+
deltaAgent: null,
|
|
248
|
+
deltaTool: null,
|
|
249
|
+
summary: 'Upstream omitted usage.input_tokens; cannot measure prompt injection baseline',
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
if ((bare !== null && bare > 220) || (agent !== null && agent > 600 && (bare === null || bare > 35))) {
|
|
254
|
+
return {
|
|
255
|
+
status: 'fail',
|
|
256
|
+
tier: 'heavy_injection',
|
|
257
|
+
deltaAgent,
|
|
258
|
+
deltaTool,
|
|
259
|
+
summary: `Global heavy system prompt injection suspected (bare=${bare ?? '?'} tok, agent=${agent ?? '?'} tok)`,
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
if (bare !== null && bare <= 35 && deltaAgent !== null && deltaAgent > 180) {
|
|
264
|
+
return {
|
|
265
|
+
status: 'fail',
|
|
266
|
+
tier: 'conditional_injection',
|
|
267
|
+
deltaAgent,
|
|
268
|
+
deltaTool,
|
|
269
|
+
summary: `Conditional UA/system prompt injection detected: bare=${bare} tok jumped +${deltaAgent} tok on agent probe`,
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (deltaTool !== null && deltaTool > toolDeltaFailThreshold) {
|
|
274
|
+
return {
|
|
275
|
+
status: 'fail',
|
|
276
|
+
tier: 'conditional_tool_injection',
|
|
277
|
+
deltaAgent,
|
|
278
|
+
deltaTool,
|
|
279
|
+
summary: `Conditional tool-triggered prompt injection detected (+${deltaTool} tok for 1 minimal tool)`,
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
if (
|
|
284
|
+
(bare !== null && bare > 35) ||
|
|
285
|
+
(deltaAgent !== null && deltaAgent > 60) ||
|
|
286
|
+
(deltaTool !== null && deltaTool > toolDeltaWarnThreshold)
|
|
287
|
+
) {
|
|
288
|
+
return {
|
|
289
|
+
status: 'warn',
|
|
290
|
+
tier: 'micro_injection',
|
|
291
|
+
deltaAgent,
|
|
292
|
+
deltaTool,
|
|
293
|
+
summary: `Mild extra input token overhead detected (bare=${bare ?? '?'} tok, deltaAgent=${deltaAgent ?? '?'}, deltaTool=${deltaTool ?? '?'})`,
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
return {
|
|
298
|
+
status: 'pass',
|
|
299
|
+
tier: 'zero',
|
|
300
|
+
deltaAgent,
|
|
301
|
+
deltaTool,
|
|
302
|
+
summary: 'Clean baseline — no hidden system prompt or conditional injection detected',
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export async function runInjectionProbe({ baseUrl, apiKey, protocol, model }) {
|
|
307
|
+
const agentUserAgent =
|
|
308
|
+
protocol === 'anthropic' ? 'claude-cli/2.1.0 (external, cli)' : 'codex_cli_rs/0.114.0';
|
|
309
|
+
const tinySystem = 'Reply OK.';
|
|
310
|
+
const minimalTools = buildMinimalProbeTool(protocol);
|
|
311
|
+
|
|
312
|
+
// Probe A: Bare single-character baseline (no system, no tools, default UA)
|
|
313
|
+
const probeA = await callLlm({
|
|
314
|
+
baseUrl,
|
|
315
|
+
apiKey,
|
|
316
|
+
protocol,
|
|
317
|
+
model,
|
|
318
|
+
userPrompt: 'a',
|
|
319
|
+
stream: false,
|
|
320
|
+
maxTokens: 8,
|
|
321
|
+
temperature: 0,
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
// Probe B: Same single-char + tiny 3-word system + Coding Agent User-Agent
|
|
325
|
+
const probeB = await callLlm({
|
|
326
|
+
baseUrl,
|
|
327
|
+
apiKey,
|
|
328
|
+
protocol,
|
|
329
|
+
model,
|
|
330
|
+
system: tinySystem,
|
|
331
|
+
userPrompt: 'a',
|
|
332
|
+
stream: false,
|
|
333
|
+
maxTokens: 8,
|
|
334
|
+
temperature: 0,
|
|
335
|
+
extraHeaders: { 'user-agent': agentUserAgent },
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
// Probe C: Same as B + 1 minimal tool (best-effort; some relays reject tools on certain models)
|
|
339
|
+
let probeC = null;
|
|
340
|
+
let toolError = null;
|
|
341
|
+
try {
|
|
342
|
+
probeC = await callLlm({
|
|
343
|
+
baseUrl,
|
|
344
|
+
apiKey,
|
|
345
|
+
protocol,
|
|
346
|
+
model,
|
|
347
|
+
system: tinySystem,
|
|
348
|
+
userPrompt: 'a',
|
|
349
|
+
stream: false,
|
|
350
|
+
maxTokens: 8,
|
|
351
|
+
temperature: 0,
|
|
352
|
+
tools: minimalTools,
|
|
353
|
+
extraHeaders: { 'user-agent': agentUserAgent },
|
|
354
|
+
});
|
|
355
|
+
} catch (err) {
|
|
356
|
+
toolError = err.message;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const tamperFlags = [];
|
|
360
|
+
if (protocol === 'openai-responses') {
|
|
361
|
+
tamperFlags.push(
|
|
362
|
+
...computeResponsesEchoDiff({
|
|
363
|
+
sentInstructions: tinySystem,
|
|
364
|
+
sentToolNames: [],
|
|
365
|
+
echoInstructions: probeB.echoInstructions,
|
|
366
|
+
echoTools: probeB.echoTools,
|
|
367
|
+
})
|
|
368
|
+
);
|
|
369
|
+
if (probeC) {
|
|
370
|
+
tamperFlags.push(
|
|
371
|
+
...computeResponsesEchoDiff({
|
|
372
|
+
sentInstructions: tinySystem,
|
|
373
|
+
sentToolNames: ['ping_health'],
|
|
374
|
+
echoInstructions: probeC.echoInstructions,
|
|
375
|
+
echoTools: probeC.echoTools,
|
|
376
|
+
})
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
const uniqueTamperFlags = Array.from(new Set(tamperFlags));
|
|
381
|
+
|
|
382
|
+
const verdict = classifyInjectionProbe({
|
|
383
|
+
protocol,
|
|
384
|
+
bareInputTokens: probeA.usage.inputTokens,
|
|
385
|
+
agentInputTokens: probeB.usage.inputTokens,
|
|
386
|
+
toolInputTokens: probeC ? probeC.usage.inputTokens : null,
|
|
387
|
+
tamperFlags: uniqueTamperFlags,
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
return {
|
|
391
|
+
status: verdict.status,
|
|
392
|
+
tier: verdict.tier,
|
|
393
|
+
summary: verdict.summary,
|
|
394
|
+
agentUserAgent,
|
|
395
|
+
bareInputTokens: probeA.usage.inputTokens,
|
|
396
|
+
agentInputTokens: probeB.usage.inputTokens,
|
|
397
|
+
toolInputTokens: probeC ? probeC.usage.inputTokens : null,
|
|
398
|
+
deltaAgent: verdict.deltaAgent,
|
|
399
|
+
deltaTool: verdict.deltaTool,
|
|
400
|
+
tamperFlags: uniqueTamperFlags,
|
|
401
|
+
...(toolError ? { toolProbeNote: `skipped (${toolError.slice(0, 120)})` } : {}),
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
export async function runCacheCheck({ baseUrl, apiKey, protocol, model }) {
|
|
406
|
+
const prefix = buildCodebasePrefix(14);
|
|
407
|
+
const r1 = await callLlm({
|
|
408
|
+
baseUrl,
|
|
409
|
+
apiKey,
|
|
410
|
+
protocol,
|
|
411
|
+
model,
|
|
412
|
+
system: prefix,
|
|
413
|
+
userPrompt: 'In one concise sentence, what formula does computeEffectiveBudget use to weight cachedTokens vs outputTokens?',
|
|
414
|
+
stream: true,
|
|
415
|
+
maxTokens: 160,
|
|
416
|
+
temperature: 0,
|
|
417
|
+
enableAnthropicCacheControl: protocol === 'anthropic',
|
|
418
|
+
});
|
|
419
|
+
|
|
420
|
+
// Brief pause to let upstream cache settle
|
|
421
|
+
await new Promise((r) => setTimeout(r, 1200));
|
|
422
|
+
|
|
423
|
+
const r2 = await callLlm({
|
|
424
|
+
baseUrl,
|
|
425
|
+
apiKey,
|
|
426
|
+
protocol,
|
|
427
|
+
model,
|
|
428
|
+
system: prefix,
|
|
429
|
+
userPrompt: 'In one concise sentence, what default fallback latency does selectEndpoint use when a key is missing from latencyMap?',
|
|
430
|
+
stream: true,
|
|
431
|
+
maxTokens: 160,
|
|
432
|
+
temperature: 0,
|
|
433
|
+
enableAnthropicCacheControl: protocol === 'anthropic',
|
|
434
|
+
});
|
|
435
|
+
|
|
436
|
+
const input2 = r2.usage.inputTokens || 0;
|
|
437
|
+
const cached2 = r2.usage.cachedTokens || 0;
|
|
438
|
+
const hitRate = input2 > 0 ? Math.round((cached2 / input2) * 1000) / 1000 : 0;
|
|
439
|
+
const status = hitRate >= 0.6 ? 'pass' : hitRate > 0 ? 'warn' : 'fail';
|
|
440
|
+
|
|
441
|
+
return {
|
|
442
|
+
status,
|
|
443
|
+
round1: {
|
|
444
|
+
ttftMs: r1.ttftMs,
|
|
445
|
+
totalMs: r1.totalMs,
|
|
446
|
+
inputTokens: r1.usage.inputTokens,
|
|
447
|
+
cachedTokens: r1.usage.cachedTokens,
|
|
448
|
+
cacheCreationTokens: r1.usage.cacheCreationTokens,
|
|
449
|
+
},
|
|
450
|
+
round2: {
|
|
451
|
+
ttftMs: r2.ttftMs,
|
|
452
|
+
totalMs: r2.totalMs,
|
|
453
|
+
inputTokens: r2.usage.inputTokens,
|
|
454
|
+
cachedTokens: r2.usage.cachedTokens,
|
|
455
|
+
},
|
|
456
|
+
cacheHitRate: hitRate,
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
export async function runLogicCheck({ baseUrl, apiKey, protocol, model }) {
|
|
461
|
+
const puzzle = buildDynamicPuzzle();
|
|
462
|
+
const res = await callLlm({
|
|
463
|
+
baseUrl,
|
|
464
|
+
apiKey,
|
|
465
|
+
protocol,
|
|
466
|
+
model,
|
|
467
|
+
userPrompt: puzzle.prompt,
|
|
468
|
+
stream: false,
|
|
469
|
+
maxTokens: 1500,
|
|
470
|
+
});
|
|
471
|
+
const graded = gradeDynamicPuzzle(res.text, puzzle.expected);
|
|
472
|
+
const hitTrap = graded.parsed === puzzle.trapAnswer;
|
|
473
|
+
return {
|
|
474
|
+
status: graded.passed ? 'pass' : 'fail',
|
|
475
|
+
expected: puzzle.expected,
|
|
476
|
+
trapAnswer: puzzle.trapAnswer,
|
|
477
|
+
parsed: graded.parsed,
|
|
478
|
+
hitTrap,
|
|
479
|
+
totalMs: res.totalMs,
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
export async function runStreamAndTamperCheck({ baseUrl, apiKey, protocol, model }) {
|
|
484
|
+
const sentinelInstruction = 'You are a concise coding assistant. Reply strictly in plain text without markdown.';
|
|
485
|
+
const res = await callLlm({
|
|
486
|
+
baseUrl,
|
|
487
|
+
apiKey,
|
|
488
|
+
protocol,
|
|
489
|
+
model,
|
|
490
|
+
system: sentinelInstruction,
|
|
491
|
+
userPrompt: 'Write a clear 140-word explanation of how HTTP/2 multiplexing prevents head-of-line blocking at the application layer.',
|
|
492
|
+
stream: true,
|
|
493
|
+
maxTokens: 420,
|
|
494
|
+
temperature: 0.2,
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
const estMax = estimateConservativeMaxTokens(res.text);
|
|
498
|
+
const reportedOut = res.usage.outputTokens;
|
|
499
|
+
const inflationRatio =
|
|
500
|
+
reportedOut != null && estMax > 0 ? Math.round((reportedOut / estMax) * 100) / 100 : null;
|
|
501
|
+
const billingInflationSuspect = inflationRatio !== null && inflationRatio > 1.6 && reportedOut > 120;
|
|
502
|
+
|
|
503
|
+
const tamperFlags =
|
|
504
|
+
protocol === 'openai-responses'
|
|
505
|
+
? computeResponsesEchoDiff({
|
|
506
|
+
sentInstructions: sentinelInstruction,
|
|
507
|
+
sentToolNames: [],
|
|
508
|
+
echoInstructions: res.echoInstructions,
|
|
509
|
+
echoTools: res.echoTools,
|
|
510
|
+
})
|
|
511
|
+
: [];
|
|
512
|
+
|
|
513
|
+
const decodeSec = Math.max(0.05, (res.decodeMs || res.totalMs) / 1000);
|
|
514
|
+
const approxTokens = reportedOut ?? Math.round(res.text.length / 4);
|
|
515
|
+
const tps = Math.round((approxTokens / decodeSec) * 10) / 10;
|
|
516
|
+
|
|
517
|
+
const warnings = [];
|
|
518
|
+
if (res.fakeStreamSuspect) warnings.push('fake_stream_suspect');
|
|
519
|
+
if (billingInflationSuspect) warnings.push(`output_token_inflation_suspect (${inflationRatio}x vs upper bound)`);
|
|
520
|
+
if (tamperFlags.length > 0) warnings.push(...tamperFlags);
|
|
521
|
+
|
|
522
|
+
return {
|
|
523
|
+
status: warnings.length === 0 ? 'pass' : tamperFlags.length > 0 || billingInflationSuspect ? 'fail' : 'warn',
|
|
524
|
+
ttftMs: res.ttftMs,
|
|
525
|
+
totalMs: res.totalMs,
|
|
526
|
+
chunkCount: res.chunkCount,
|
|
527
|
+
tps,
|
|
528
|
+
responseModel: res.responseModel,
|
|
529
|
+
responseId: res.responseId,
|
|
530
|
+
reportedOutputTokens: reportedOut,
|
|
531
|
+
conservativeUpperBoundTokens: estMax,
|
|
532
|
+
inflationRatio,
|
|
533
|
+
fakeStreamSuspect: res.fakeStreamSuspect,
|
|
534
|
+
tamperFlags,
|
|
535
|
+
warnings,
|
|
536
|
+
};
|
|
537
|
+
}
|