@bismawy/pi-arnative 0.6.2 → 0.8.0-rc.1
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/CHANGELOG.md +38 -0
- package/README.md +20 -4
- package/extensions/arnative.ts +185 -195
- package/extensions/autocompact.ts +294 -0
- package/extensions/footer.ts +8 -3
- package/extensions/timestamps.ts +30 -1
- package/extensions/tools.ts +3 -3
- package/extensions/ui-render-tweaks.ts +12 -1
- package/extensions/usage.ts +90 -35
- package/lib/box.ts +8 -3
- package/lib/compat.ts +415 -0
- package/lib/list-picker.ts +409 -0
- package/lib/preset-store.ts +67 -9
- package/lib/provider.ts +1190 -0
- package/lib/shortcuts.ts +7 -4
- package/lib/usage-store.ts +90 -20
- package/package.json +3 -3
package/lib/compat.ts
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compat flags for a provider the wizard writes — ported from pi-auto-compat, minus its
|
|
3
|
+
* background machinery. Nothing here watches models.json or repairs it later: the flags
|
|
4
|
+
* are computed once, from the model list the wizard already fetched, and written by
|
|
5
|
+
* `withProviderModels` in provider.ts (one writer, one moment).
|
|
6
|
+
*
|
|
7
|
+
* Two things ride along with the same probe: the real `contextWindow`/`maxTokens`, and
|
|
8
|
+
* (on demand) which `reasoning_effort` names the channel accepts.
|
|
9
|
+
*/
|
|
10
|
+
import { assert, isMain } from "./check.ts";
|
|
11
|
+
|
|
12
|
+
export type Compat = Record<string, unknown>;
|
|
13
|
+
|
|
14
|
+
/** The fields a compat decision depends on — a merged registry model, or the pieces the
|
|
15
|
+
* wizard holds while it writes a provider. */
|
|
16
|
+
export interface CompatModel {
|
|
17
|
+
provider: string;
|
|
18
|
+
id: string;
|
|
19
|
+
name?: string;
|
|
20
|
+
api?: string;
|
|
21
|
+
baseUrl?: string;
|
|
22
|
+
reasoning?: boolean;
|
|
23
|
+
compat?: Compat;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const lower = (v: unknown): string => String(v ?? "").toLowerCase();
|
|
27
|
+
const tokensOf = (m: CompatModel): string[] => [m.id, m.name].map(lower).filter(Boolean);
|
|
28
|
+
|
|
29
|
+
const isOpenAICompatible = (api: unknown): boolean => {
|
|
30
|
+
const v = lower(api);
|
|
31
|
+
return v === "openai-completions" || v === "openai-responses";
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
// Claude Opus/Sonnet >= 4.6, Fable >= 5 — the generations that need adaptive thinking.
|
|
35
|
+
const ADAPTIVE_RE =
|
|
36
|
+
/(?:^|[/\s:_-])(?:opus-4[.-][6-9]|opus-4-[1-9][0-9]|opus-(?:[5-9]|[1-9][0-9])|sonnet-4[.-][6-9]|sonnet-4-[1-9][0-9]|sonnet-(?:[5-9]|[1-9][0-9])|fable-(?:[5-9]|[1-9][0-9]))(?:$|[-_.:/\s[])/i;
|
|
37
|
+
|
|
38
|
+
const isKimiCoding = (m: CompatModel): boolean => lower(m.provider).includes("kimi-coding") || lower(m.baseUrl).includes("api.kimi.com/coding");
|
|
39
|
+
const isKimiK3 = (m: CompatModel): boolean =>
|
|
40
|
+
isKimiCoding(m) &&
|
|
41
|
+
tokensOf(m).some((t) => t === "k3" || t.includes("kimi-k3") || t.includes("kimi k3") || t.includes("kimi-for-coding") || t.includes("kimi for coding"));
|
|
42
|
+
|
|
43
|
+
/** pi's built-in llama.cpp provider declares this exact compat set; every rule skips it. */
|
|
44
|
+
function isPiLlamaCpp(m: CompatModel): boolean {
|
|
45
|
+
if (lower(m.provider) !== "llama.cpp" || lower(m.api) !== "openai-completions") return false;
|
|
46
|
+
const c = m.compat ?? {};
|
|
47
|
+
return (
|
|
48
|
+
c.supportsStore === false &&
|
|
49
|
+
c.supportsDeveloperRole === false &&
|
|
50
|
+
c.supportsReasoningEffort === false &&
|
|
51
|
+
c.supportsUsageInStreaming === false &&
|
|
52
|
+
c.supportsStrictMode === false &&
|
|
53
|
+
c.maxTokensField === "max_tokens" &&
|
|
54
|
+
c.sendSessionAffinityHeaders === undefined &&
|
|
55
|
+
c.sessionAffinityFormat === undefined &&
|
|
56
|
+
c.supportsLongCacheRetention === undefined
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function isOfficialOpenAI(m: CompatModel): boolean {
|
|
61
|
+
const value = String(m.baseUrl ?? "").trim().toLowerCase();
|
|
62
|
+
if (!value) return lower(m.provider) === "openai";
|
|
63
|
+
try {
|
|
64
|
+
return new URL(value).hostname === "api.openai.com";
|
|
65
|
+
} catch {
|
|
66
|
+
return value === "api.openai.com" || value.startsWith("api.openai.com/");
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const isOpenRouter = (m: CompatModel): boolean => lower(m.provider) === "openrouter" || lower(m.baseUrl).includes("openrouter.ai");
|
|
71
|
+
|
|
72
|
+
/** Flags a model needs, in pi's own priority order. Only keys the stored entry leaves
|
|
73
|
+
* undefined are returned, so an explicit user value — even `false` — always wins. */
|
|
74
|
+
export function suggestCompat(m: CompatModel): Compat {
|
|
75
|
+
const api = lower(m.api);
|
|
76
|
+
const compat = m.compat ?? {};
|
|
77
|
+
const tokens = tokensOf(m);
|
|
78
|
+
const out: Compat = {};
|
|
79
|
+
|
|
80
|
+
// pi defaults long retention to true when undeclared, and some relays 400 on the
|
|
81
|
+
// parameter (Fireworks caches automatically) — declare it either way.
|
|
82
|
+
if (compat.supportsLongCacheRetention === undefined) out.supportsLongCacheRetention = api === "anthropic-messages" || isOfficialOpenAI(m);
|
|
83
|
+
|
|
84
|
+
// Third-party routers reject role "developer" with `messages.0.role: Invalid option`;
|
|
85
|
+
// every OpenAI-compatible channel accepts "system". First-party APIs keep the role.
|
|
86
|
+
if (m.reasoning === true && isOpenAICompatible(api) && compat.supportsDeveloperRole === undefined && !isOfficialOpenAI(m) && !isOpenRouter(m)) {
|
|
87
|
+
out.supportsDeveloperRole = false;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (api === "anthropic-messages" && (tokens.some((t) => ADAPTIVE_RE.test(t)) || isKimiK3(m))) {
|
|
91
|
+
if (compat.forceAdaptiveThinking !== true) out.forceAdaptiveThinking = true;
|
|
92
|
+
if (isKimiK3(m) && compat.allowEmptySignature !== true) out.allowEmptySignature = true;
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (tokens.some((t) => t.includes("deepseek")) && isOpenAICompatible(api) && !isPiLlamaCpp(m)) {
|
|
97
|
+
if (api === "openai-completions" && compat.sendSessionAffinityHeaders === undefined) out.sendSessionAffinityHeaders = true;
|
|
98
|
+
if (compat.requiresReasoningContentOnAssistantMessages !== true) out.requiresReasoningContentOnAssistantMessages = true;
|
|
99
|
+
if (compat.thinkingFormat !== "deepseek") out.thinkingFormat = "deepseek";
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (tokens.some((t) => t.includes("anthropic") || t.includes("claude")) && isOpenAICompatible(api) && !isPiLlamaCpp(m) && compat.cacheControlFormat !== "anthropic") {
|
|
104
|
+
out.cacheControlFormat = "anthropic";
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (api === "openai-completions" && !isOfficialOpenAI(m) && !isPiLlamaCpp(m) && compat.sendSessionAffinityHeaders === undefined) out.sendSessionAffinityHeaders = true;
|
|
108
|
+
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ------------------------------------------------------------ metadata
|
|
113
|
+
|
|
114
|
+
export interface ModelMeta {
|
|
115
|
+
contextWindow?: number;
|
|
116
|
+
maxTokens?: number;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Widest window first: max_model_len / max_input_tokens are upstream limits, not the
|
|
120
|
+
// served window, and some channels only publish the input side.
|
|
121
|
+
const CONTEXT_KEYS = ["context_length", "context_window", "max_context_length", "max_model_len", "max_context_window", "max_input_tokens", "max_input_length", "context_size"];
|
|
122
|
+
const OUTPUT_KEYS = ["max_output_tokens", "max_completion_tokens", "max_output_length", "max_tokens"];
|
|
123
|
+
|
|
124
|
+
const positiveInt = (value: unknown): number | undefined => {
|
|
125
|
+
const n = typeof value === "string" && value.trim() ? Number(value.trim()) : value;
|
|
126
|
+
return typeof n === "number" && Number.isFinite(n) && n > 0 ? Math.floor(n) : undefined;
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
/** Numeric limits from one catalog entry. */
|
|
130
|
+
export function parseMeta(entry: unknown): ModelMeta {
|
|
131
|
+
const rec = (entry ?? {}) as Record<string, unknown>;
|
|
132
|
+
const out: ModelMeta = {};
|
|
133
|
+
for (const key of CONTEXT_KEYS) {
|
|
134
|
+
const value = positiveInt(rec[key]);
|
|
135
|
+
if (value !== undefined) {
|
|
136
|
+
out.contextWindow = value;
|
|
137
|
+
break;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
for (const key of OUTPUT_KEYS) {
|
|
141
|
+
const value = positiveInt(rec[key]);
|
|
142
|
+
if (value === undefined) continue;
|
|
143
|
+
// A "max_tokens" equal to the whole window is the context length, not a cap.
|
|
144
|
+
if (out.contextWindow !== undefined && value >= out.contextWindow) continue;
|
|
145
|
+
out.maxTokens = value;
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Every model's limits from one `/models` body — the same response the id list comes
|
|
152
|
+
* from, so the metadata costs no extra request. */
|
|
153
|
+
export function parseModelMeta(body: unknown): Map<string, ModelMeta> {
|
|
154
|
+
const out = new Map<string, ModelMeta>();
|
|
155
|
+
if (typeof body !== "object" || body === null) return out;
|
|
156
|
+
const record = body as Record<string, unknown>;
|
|
157
|
+
const list = Array.isArray(record.data) ? record.data : Array.isArray(record.models) ? record.models : [];
|
|
158
|
+
for (const item of list) {
|
|
159
|
+
if (typeof item !== "object" || item === null) continue;
|
|
160
|
+
const rec = item as Record<string, unknown>;
|
|
161
|
+
const raw = typeof rec.id === "string" ? rec.id : typeof rec.name === "string" ? rec.name.replace(/^models\//, "") : undefined;
|
|
162
|
+
if (!raw) continue;
|
|
163
|
+
const meta = parseMeta(rec);
|
|
164
|
+
if (meta.contextWindow !== undefined || meta.maxTokens !== undefined) out.set(raw, meta);
|
|
165
|
+
}
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Keep a real API correction, reject unit anomalies: an order of magnitude below the
|
|
170
|
+
* stored window is a per-request number, not the served window. */
|
|
171
|
+
export function contextWindowAccepted(candidate: number, existing: number | undefined): boolean {
|
|
172
|
+
if (existing === undefined || candidate === existing) return true;
|
|
173
|
+
return candidate > existing || candidate * 5 >= existing;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Merge a freshly probed limit into a stored one; undefined means "keep what is there". */
|
|
177
|
+
export function mergeMeta(prev: ModelMeta | undefined, next: ModelMeta): ModelMeta {
|
|
178
|
+
const out: ModelMeta = { ...prev };
|
|
179
|
+
const ctx = next.contextWindow;
|
|
180
|
+
if (ctx !== undefined && contextWindowAccepted(ctx, prev?.contextWindow)) out.contextWindow = ctx;
|
|
181
|
+
const effective = ctx ?? prev?.contextWindow;
|
|
182
|
+
if (next.maxTokens !== undefined && (prev?.maxTokens === undefined || next.maxTokens > prev.maxTokens)) {
|
|
183
|
+
out.maxTokens = effective !== undefined && next.maxTokens > effective ? effective : next.maxTokens;
|
|
184
|
+
}
|
|
185
|
+
return out;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// ------------------------------------------------------- thinking effort
|
|
189
|
+
|
|
190
|
+
// pi's levels in clamp order; `off` has no wire name of its own.
|
|
191
|
+
export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
|
|
192
|
+
const EFFORT_RANK = ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
193
|
+
const PROBED = new Set(EFFORT_RANK);
|
|
194
|
+
const IDENTITY: Record<string, string> = { low: "low", medium: "medium", high: "high", xhigh: "xhigh" };
|
|
195
|
+
const LEVEL_TIMEOUT_MS = 30_000;
|
|
196
|
+
const PROBE_TOKENS = 16;
|
|
197
|
+
const RETRY_PAUSE_MS = 1000;
|
|
198
|
+
// Only a parameter rejection indicts the level. Auth, quota and transport errors say
|
|
199
|
+
// nothing, and marking a level accepted without an answer would be a lie.
|
|
200
|
+
const REJECTION_RE = /provider.?error|invalid.?request|http 400|400[.:]|reasoning.?effort|thinking|unsupported|not supported|invalid (?:value|option|parameter|enum)|bad request/i;
|
|
201
|
+
|
|
202
|
+
/** A reasoning model on a relay that expects `reasoning_effort` and does not publish its
|
|
203
|
+
* own level support — the only case a probe can fix. */
|
|
204
|
+
export function isEffortProbeable(m: CompatModel & { compat?: Compat }, channelCompat: Compat = {}): boolean {
|
|
205
|
+
if (m.reasoning !== true || !isOpenAICompatible(m.api)) return false;
|
|
206
|
+
if (isOfficialOpenAI(m) || isOpenRouter(m) || isPiLlamaCpp(m)) return false;
|
|
207
|
+
const compat = { ...channelCompat, ...(m.compat ?? {}) };
|
|
208
|
+
if (compat.supportsReasoningEffort === false) return false;
|
|
209
|
+
return !["openrouter", "chat-template", "qwen-chat-template", "ant-ling"].includes(String(compat.thinkingFormat ?? ""));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** The non-effort half of pi's request, so the probe tests the level like a real turn
|
|
213
|
+
* would: a channel that needs `thinking:{type:enabled}` must not report that as a failure. */
|
|
214
|
+
export function thinkingPayload(compat: Compat, enabled: boolean): Record<string, unknown> | undefined {
|
|
215
|
+
switch (compat.thinkingFormat) {
|
|
216
|
+
case "deepseek":
|
|
217
|
+
return { thinking: { type: enabled ? "enabled" : "disabled" } };
|
|
218
|
+
case "zai":
|
|
219
|
+
return { thinking: enabled ? { type: "enabled", clear_thinking: false } : { type: "disabled" } };
|
|
220
|
+
case "qwen":
|
|
221
|
+
return { enable_thinking: enabled };
|
|
222
|
+
case "together":
|
|
223
|
+
return { reasoning: { enabled } };
|
|
224
|
+
case "openrouter":
|
|
225
|
+
return enabled ? { reasoning: { effort: "medium" } } : undefined;
|
|
226
|
+
default:
|
|
227
|
+
return undefined;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Nearest accepted effort, up first (pi's clamp order), ties down. */
|
|
232
|
+
export function nearestEffort(level: string, accepted: Set<string>): string | undefined {
|
|
233
|
+
const idx = EFFORT_RANK.indexOf(level);
|
|
234
|
+
if (idx === -1) return undefined;
|
|
235
|
+
let best: string | undefined;
|
|
236
|
+
let bestDistance = Number.POSITIVE_INFINITY;
|
|
237
|
+
for (const candidate of accepted) {
|
|
238
|
+
const cIdx = EFFORT_RANK.indexOf(candidate);
|
|
239
|
+
if (cIdx === -1) continue;
|
|
240
|
+
const distance = cIdx >= idx ? cIdx - idx : (idx - cIdx) * 1.01;
|
|
241
|
+
if (distance < bestDistance) {
|
|
242
|
+
bestDistance = distance;
|
|
243
|
+
best = candidate;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return best;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** A map that remaps or drops a level was shaped by the user, not by a probe. */
|
|
250
|
+
export function carriesRemap(map: Record<string, string | null> | undefined): boolean {
|
|
251
|
+
if (!map) return false;
|
|
252
|
+
for (const [level, value] of Object.entries(map)) {
|
|
253
|
+
if (value === null) return true;
|
|
254
|
+
if (value !== level && IDENTITY[level] !== undefined) return true;
|
|
255
|
+
}
|
|
256
|
+
return false;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Probe results → `thinkingLevelMap`. A rejected level maps to the nearest accepted one;
|
|
260
|
+
* a level that works stays unmapped, so nothing is pinned that need not be. Undefined when
|
|
261
|
+
* nothing answered or nothing changed. */
|
|
262
|
+
export function buildEffortMap(current: Record<string, string | null> | undefined, supported: string[]): Record<string, string | null> | undefined {
|
|
263
|
+
const accepted = new Set(supported);
|
|
264
|
+
if (accepted.size === 0) return undefined;
|
|
265
|
+
const out: Record<string, string | null> = {};
|
|
266
|
+
let changed = false;
|
|
267
|
+
for (const level of THINKING_LEVELS) {
|
|
268
|
+
const existing = current?.[level];
|
|
269
|
+
const optIn = level === "off" || level === "xhigh" || level === "max";
|
|
270
|
+
if (optIn) {
|
|
271
|
+
if (existing === undefined) continue; // not offered → not the probe's call
|
|
272
|
+
if (existing === null || !PROBED.has(existing)) {
|
|
273
|
+
out[level] = existing;
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
276
|
+
const from = level === "off" ? "minimal" : level;
|
|
277
|
+
const value = accepted.has(existing) ? existing : level === "off" && accepted.has("none") ? "none" : nearestEffort(from, accepted);
|
|
278
|
+
if (!value) {
|
|
279
|
+
out[level] = null;
|
|
280
|
+
changed = true;
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
if (value !== existing) changed = true;
|
|
284
|
+
out[level] = value;
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
if (existing !== undefined && existing !== level) {
|
|
288
|
+
out[level] = existing; // offered under another name: deliberate
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
if (existing === null) {
|
|
292
|
+
out[level] = null;
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
if (accepted.has(level)) continue;
|
|
296
|
+
out[level] = nearestEffort(level, accepted) ?? null;
|
|
297
|
+
changed = true;
|
|
298
|
+
}
|
|
299
|
+
return changed ? out : undefined;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export interface EffortProbeOptions {
|
|
303
|
+
baseUrl: string;
|
|
304
|
+
key?: string;
|
|
305
|
+
headers?: Record<string, string>;
|
|
306
|
+
fetchImpl?: typeof fetch;
|
|
307
|
+
/** Called after each level, for a progress row. */
|
|
308
|
+
onLevel?: (level: string, accepted: boolean | undefined, index: number) => void;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** A status that names a rejected parameter rather than a broken endpoint. */
|
|
312
|
+
function isParamRejection(status: number, body: string): boolean {
|
|
313
|
+
if (status === 400 || status === 404 || status === 422) return true;
|
|
314
|
+
if (status !== 500 && status !== 502 && status !== 503) return false;
|
|
315
|
+
return REJECTION_RE.test(body);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
|
|
319
|
+
|
|
320
|
+
/** Every effort name the channel accepts, found with one tiny completion per level.
|
|
321
|
+
* `[]` means nothing answered — never call that "nothing supported". */
|
|
322
|
+
export async function probeEffort(model: CompatModel, options: EffortProbeOptions): Promise<string[]> {
|
|
323
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
324
|
+
const url = `${options.baseUrl.replace(/\/+$/, "")}/chat/completions`;
|
|
325
|
+
const headers: Record<string, string> = { "content-type": "application/json", accept: "application/json", ...options.headers };
|
|
326
|
+
if (options.key) headers.authorization = `Bearer ${options.key}`;
|
|
327
|
+
const accepted: string[] = [];
|
|
328
|
+
|
|
329
|
+
for (const [index, level] of EFFORT_RANK.entries()) {
|
|
330
|
+
const body = JSON.stringify({
|
|
331
|
+
model: model.id,
|
|
332
|
+
messages: [{ role: "user", content: "ping" }],
|
|
333
|
+
max_tokens: PROBE_TOKENS,
|
|
334
|
+
stream: false,
|
|
335
|
+
...(thinkingPayload(model.compat ?? {}, true) ?? {}),
|
|
336
|
+
reasoning_effort: level,
|
|
337
|
+
});
|
|
338
|
+
let verdict: boolean | undefined;
|
|
339
|
+
// Two attempts per level: a first 400 can be an upstream flake, a second confirms it.
|
|
340
|
+
for (let attempt = 0; attempt < 2 && verdict === undefined; attempt++) {
|
|
341
|
+
let status: number;
|
|
342
|
+
let text: string;
|
|
343
|
+
try {
|
|
344
|
+
const response = await fetchImpl(url, { method: "POST", headers, body, signal: AbortSignal.timeout(LEVEL_TIMEOUT_MS) });
|
|
345
|
+
status = response.status;
|
|
346
|
+
text = (await response.text()).slice(0, 4000);
|
|
347
|
+
} catch {
|
|
348
|
+
break; // network/timeout: inconclusive
|
|
349
|
+
}
|
|
350
|
+
if (status < 300) {
|
|
351
|
+
verdict = true;
|
|
352
|
+
break;
|
|
353
|
+
}
|
|
354
|
+
if (status === 429) {
|
|
355
|
+
await sleep(RETRY_PAUSE_MS);
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
if (!isParamRejection(status, text)) break; // 401/403/5xx without a hint: unknown
|
|
359
|
+
verdict = false;
|
|
360
|
+
}
|
|
361
|
+
if (verdict) accepted.push(level);
|
|
362
|
+
options.onLevel?.(level, verdict, index);
|
|
363
|
+
}
|
|
364
|
+
return accepted;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// ----------------------------------------------------------- self-check
|
|
368
|
+
|
|
369
|
+
if (isMain(import.meta.url)) {
|
|
370
|
+
const base = { provider: "r", id: "m", api: "openai-completions", baseUrl: "https://relay.x/v1" };
|
|
371
|
+
assert(suggestCompat(base).supportsLongCacheRetention === false, "a third-party relay declares retention false");
|
|
372
|
+
assert(suggestCompat(base).sendSessionAffinityHeaders === true, "an openai-compatible relay gets affinity headers");
|
|
373
|
+
assert(suggestCompat({ ...base, baseUrl: "https://api.openai.com/v1" }).supportsLongCacheRetention === true, "official OpenAI keeps long retention");
|
|
374
|
+
assert(suggestCompat({ ...base, reasoning: true }).supportsDeveloperRole === false, "a reasoning model on a relay opts out of the developer role");
|
|
375
|
+
assert(suggestCompat({ ...base, reasoning: true, compat: { supportsDeveloperRole: true } }).supportsDeveloperRole === undefined, "an explicit value is never overwritten");
|
|
376
|
+
assert(suggestCompat({ ...base, id: "deepseek-v4" }).thinkingFormat === "deepseek", "a deepseek id gets the deepseek thinking format");
|
|
377
|
+
assert(suggestCompat({ ...base, api: "anthropic-messages", id: "claude-opus-4-6" }).forceAdaptiveThinking === true, "Opus 4.6 needs adaptive thinking");
|
|
378
|
+
assert(suggestCompat({ ...base, id: "claude-sonnet-4-5" }).cacheControlFormat === "anthropic", "Claude on a proxy gets anthropic cache control");
|
|
379
|
+
assert(suggestCompat({ ...base, provider: "llama.cpp", compat: { supportsStore: false, supportsDeveloperRole: false, supportsReasoningEffort: false, supportsUsageInStreaming: false, supportsStrictMode: false, maxTokensField: "max_tokens" } }).sendSessionAffinityHeaders === undefined, "pi's built-in llama.cpp is left alone");
|
|
380
|
+
|
|
381
|
+
const meta = parseModelMeta({ data: [{ id: "a", context_length: 1_000_000, max_output_tokens: 64_000 }, { id: "b", max_model_len: 262_144, max_tokens: 262_144 }] });
|
|
382
|
+
assert(meta.get("a")?.contextWindow === 1_000_000 && meta.get("a")?.maxTokens === 64_000, "a catalog entry yields window and cap");
|
|
383
|
+
assert(meta.get("b")?.maxTokens === undefined, "a max_tokens equal to the window is not an output cap");
|
|
384
|
+
assert(parseModelMeta({ models: [{ name: "models/gemini-x", context_window: 128_000 }] }).get("gemini-x")?.contextWindow === 128_000, "a gemini-shaped list parses too");
|
|
385
|
+
assert(contextWindowAccepted(1_048_576, 131_072), "growth is accepted");
|
|
386
|
+
assert(!contextWindowAccepted(8192, 1_000_000), "a per-request number is rejected");
|
|
387
|
+
assert(mergeMeta({ maxTokens: 4096 }, { maxTokens: 8192 }).maxTokens === 8192, "an output cap only grows");
|
|
388
|
+
assert(mergeMeta({ contextWindow: 1024 }, { maxTokens: 8192 }).maxTokens === 1024, "a cap above the window clamps to the window");
|
|
389
|
+
|
|
390
|
+
assert(nearestEffort("medium", new Set(["low", "high"])) === "high", "a rejected level moves up first");
|
|
391
|
+
assert(nearestEffort("high", new Set(["low", "medium"])) === "medium", "with no level above it moves down");
|
|
392
|
+
assert(buildEffortMap(undefined, ["minimal", "low", "high"])?.medium === "high", "a rejected level is remapped");
|
|
393
|
+
assert(buildEffortMap(undefined, ["minimal", "low", "high"])?.xhigh === undefined, "an opt-in level is not invented");
|
|
394
|
+
assert(buildEffortMap({ medium: null, high: "high" }, ["high"])?.medium === null, "a deliberate null survives");
|
|
395
|
+
assert(buildEffortMap({ medium: "high" }, ["high"])?.medium === "high", "a deliberate remap is preserved");
|
|
396
|
+
assert(carriesRemap({ medium: "high" }) && carriesRemap({ low: null }) && !carriesRemap({ low: "low" }), "only a shaped map counts as deliberate");
|
|
397
|
+
assert(thinkingPayload({ thinkingFormat: "zai" }, true)?.thinking !== undefined, "a channel that needs a thinking block gets one");
|
|
398
|
+
assert(isEffortProbeable({ ...base, reasoning: true }), "a reasoning model on a relay is probeable");
|
|
399
|
+
assert(!isEffortProbeable({ ...base, reasoning: true, baseUrl: "https://api.openai.com/v1" }), "a first-party API is not probed");
|
|
400
|
+
assert(!isEffortProbeable({ ...base, reasoning: true, compat: { supportsReasoningEffort: false } }), "a channel that sends no effort is not probed");
|
|
401
|
+
|
|
402
|
+
// The probe loop itself: a channel that takes none/minimal/low/high and 400s medium.
|
|
403
|
+
const fakeFetch = (async (_url: string, init?: { body?: string }) => {
|
|
404
|
+
const level = JSON.parse(init?.body ?? "{}").reasoning_effort as string;
|
|
405
|
+
const ok = ["none", "minimal", "low", "high"].includes(level);
|
|
406
|
+
return { status: ok ? 200 : 400, text: async () => (ok ? "" : "invalid reasoning_effort") };
|
|
407
|
+
}) as unknown as typeof fetch;
|
|
408
|
+
const supported = await probeEffort({ ...base, id: "relay-model", reasoning: true }, { baseUrl: base.baseUrl, fetchImpl: fakeFetch });
|
|
409
|
+
assert(supported.join() === "none,minimal,low,high", "the probe reports exactly the accepted levels");
|
|
410
|
+
assert(buildEffortMap(undefined, supported)?.medium === "high", "a rejected level is remapped to the nearest accepted one");
|
|
411
|
+
const deadFetch = (async () => ({ status: 401, text: async () => "unauthorized" })) as unknown as typeof fetch;
|
|
412
|
+
assert((await probeEffort({ ...base, reasoning: true }, { baseUrl: base.baseUrl, fetchImpl: deadFetch })).length === 0, "a credential failure answers nothing, so nothing is written");
|
|
413
|
+
|
|
414
|
+
console.log("compat.ts self-check OK");
|
|
415
|
+
}
|