100milionseek 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +118 -2
- package/README.zh-CN.md +108 -0
- package/index.mjs +4 -0
- package/opencode.mjs +5 -0
- package/opencode2.mjs +620 -0
- package/package.json +53 -5
- package/src/index.mjs +380 -0
- package/src/load.mjs +28 -0
- package/src/models.mjs +179 -0
- package/src/quota.mjs +73 -0
- package/src/systemone.mjs +70 -0
- package/test/all.mjs +13 -0
- package/test/load-report.test.mjs +92 -0
- package/test/load.test.mjs +54 -0
- package/test/models.test.mjs +153 -0
- package/test/plugin.test.mjs +278 -0
- package/test/quota.test.mjs +86 -0
- package/test/systemone.test.mjs +69 -0
package/src/index.mjs
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
// The 100milionseek provider, as magpie's plugin host calls it.
|
|
2
|
+
//
|
|
3
|
+
// The service is an OpenAI-compatible proxy: one chat model on a free daily
|
|
4
|
+
// token allowance, plus a judge model (JEV) that answers routing questions.
|
|
5
|
+
// Two things make it need a plugin rather than a plain provider block:
|
|
6
|
+
//
|
|
7
|
+
// - the daily allowance is only ever reported in x-quota-* response headers,
|
|
8
|
+
// so `usage` has to read a response to know it;
|
|
9
|
+
// - the judge answers {model, questions, state} with one probability per
|
|
10
|
+
// question, which `decides` + `decide: true` hand to magpie as a classifier
|
|
11
|
+
// once the answers are in the shape it reads.
|
|
12
|
+
//
|
|
13
|
+
// Everything else — models, base URL, sign-in — is a normal API key provider.
|
|
14
|
+
|
|
15
|
+
import { quotaWindow, planOf, nextUtcMidnight } from "./quota.mjs";
|
|
16
|
+
import { CHAT_SDK, CHAT_MODEL, JUDGE_MODEL, configModels, accountModels, modelIDs } from "./models.mjs";
|
|
17
|
+
import { normalizeSystemOne } from "./systemone.mjs";
|
|
18
|
+
import { loadOf } from "./load.mjs";
|
|
19
|
+
|
|
20
|
+
export const PROVIDER = "hundred-milion-seek";
|
|
21
|
+
export const ORIGIN = "https://100milionseek.top";
|
|
22
|
+
export const BASE = `${ORIGIN}/v1`;
|
|
23
|
+
|
|
24
|
+
const TIMEOUT_MS = 15_000;
|
|
25
|
+
|
|
26
|
+
// The key an account was signed in with, however magpie stored it: an api
|
|
27
|
+
// account is {type:"api", key}, older multi-method accounts keep it per
|
|
28
|
+
// method, and a keyless-style account may only carry `access`.
|
|
29
|
+
export function keyOf(auth) {
|
|
30
|
+
if (!auth || typeof auth !== "object") return "";
|
|
31
|
+
const key = auth.key ?? auth.apiKey ?? auth.access ?? auth.methods?.[0]?.key ?? "";
|
|
32
|
+
return typeof key === "string" ? key.trim() : "";
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function HundredMilionSeekPlugin(input, options = {}) {
|
|
36
|
+
const baseURL = String(options.baseURL ?? BASE).replace(/\/+$/, "");
|
|
37
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
38
|
+
const reasoning = options.reasoning === true;
|
|
39
|
+
const reportLoad = options.load !== false;
|
|
40
|
+
const timeout = Number.isFinite(options.timeoutMs) ? options.timeoutMs : TIMEOUT_MS;
|
|
41
|
+
|
|
42
|
+
// The model table both hooks describe from. `config` publishes it; the
|
|
43
|
+
// models hook starts from it.
|
|
44
|
+
const template = configModels({ reasoning });
|
|
45
|
+
|
|
46
|
+
// Load is per model in magpie, and this service has one upstream behind all
|
|
47
|
+
// of them: every model gets the same figure. Started here rather than in a
|
|
48
|
+
// hook, so a host that only ever calls `config` still gets the report.
|
|
49
|
+
if (reportLoad) publishLoad();
|
|
50
|
+
|
|
51
|
+
// The newest allowance any response reported, per account key. Only a
|
|
52
|
+
// fallback for `usage` when its own read fails: keeping it under the key
|
|
53
|
+
// keeps two signed-in keys from showing each other's spend.
|
|
54
|
+
const seen = new Map();
|
|
55
|
+
const remember = (key, headers, now) => {
|
|
56
|
+
if (!key) return;
|
|
57
|
+
const window = quotaWindow(headers, now);
|
|
58
|
+
if (window) seen.set(key, { window, at: now });
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// One account's worth of headers, from a GET the caller is making anyway.
|
|
62
|
+
async function readAllowance(apiKey) {
|
|
63
|
+
const res = await fetchImpl(`${baseURL}/models`, {
|
|
64
|
+
headers: { authorization: `Bearer ${apiKey}`, accept: "application/json" },
|
|
65
|
+
redirect: "error",
|
|
66
|
+
signal: AbortSignal.timeout(timeout),
|
|
67
|
+
});
|
|
68
|
+
const window = quotaWindow(res.headers);
|
|
69
|
+
if (window) seen.set(apiKey, { window, at: Date.now() });
|
|
70
|
+
// Nothing reads this body; drop it rather than hold the connection open.
|
|
71
|
+
try {
|
|
72
|
+
await res.body?.cancel?.();
|
|
73
|
+
} catch {
|
|
74
|
+
/* already gone */
|
|
75
|
+
}
|
|
76
|
+
return { res, window };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// How busy the service is, for magpie's "busy models go later" routing.
|
|
80
|
+
// /api/status needs no key; `loadOf` turns it into a percentage.
|
|
81
|
+
async function readLoad() {
|
|
82
|
+
const res = await fetchImpl(`${ORIGIN}/api/status`, {
|
|
83
|
+
headers: { accept: "application/json" },
|
|
84
|
+
redirect: "error",
|
|
85
|
+
signal: AbortSignal.timeout(timeout),
|
|
86
|
+
});
|
|
87
|
+
if (!res.ok) throw new Error(`status returned HTTP ${res.status}`);
|
|
88
|
+
return loadOf(await res.json());
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Load is per model in magpie, and one upstream stands behind every model
|
|
92
|
+
// here, so each of them carries the same figure.
|
|
93
|
+
function publishLoad() {
|
|
94
|
+
// Only magpie reads load, and it hands the function over with `input`.
|
|
95
|
+
if (typeof input?.magpie?.load !== "function") return;
|
|
96
|
+
const once = () => {
|
|
97
|
+
readLoad()
|
|
98
|
+
.then((load) => {
|
|
99
|
+
if (load === null) return;
|
|
100
|
+
const loads = {};
|
|
101
|
+
for (const id of Object.keys(template)) loads[id] = load;
|
|
102
|
+
input.magpie.load(PROVIDER, loads);
|
|
103
|
+
})
|
|
104
|
+
// Unreadable load is "unknown", never 0: a blind report would hide a
|
|
105
|
+
// busy service instead of showing it.
|
|
106
|
+
.catch(() => {});
|
|
107
|
+
};
|
|
108
|
+
once();
|
|
109
|
+
// magpie forgets a model's load five minutes after it was reported.
|
|
110
|
+
const timer = setInterval(once, 120_000);
|
|
111
|
+
timer?.unref?.(); // never hold the host open for a report
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// The daily allowance is a hard stop until 00:00 UTC. The service says so in
|
|
115
|
+
// Retry-After already; when it doesn't, the reset instant does.
|
|
116
|
+
async function spentAllowance(res) {
|
|
117
|
+
const text = await res.text().catch(() => "");
|
|
118
|
+
let body = null;
|
|
119
|
+
try {
|
|
120
|
+
body = JSON.parse(text);
|
|
121
|
+
} catch {
|
|
122
|
+
/* non-JSON body: pass its own words through */
|
|
123
|
+
}
|
|
124
|
+
const headers = new Headers(res.headers);
|
|
125
|
+
if (!headers.get("retry-after")) {
|
|
126
|
+
const reset = body?.error?.reset_at ?? headers.get("x-quota-reset");
|
|
127
|
+
const at = typeof reset === "string" ? Date.parse(reset) : NaN;
|
|
128
|
+
const until = Number.isFinite(at) ? at : nextUtcMidnight().getTime();
|
|
129
|
+
headers.set("retry-after", String(Math.max(1, Math.ceil((until - Date.now()) / 1000))));
|
|
130
|
+
}
|
|
131
|
+
return new Response(text, { status: res.status, statusText: res.statusText, headers });
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return {
|
|
135
|
+
async config(cfg) {
|
|
136
|
+
cfg.provider ??= {};
|
|
137
|
+
// ??= so a provider the user declared in providers.json or plugins.json
|
|
138
|
+
// keeps its own name, models and options.
|
|
139
|
+
cfg.provider[PROVIDER] ??= {
|
|
140
|
+
name: "100milionseek",
|
|
141
|
+
npm: CHAT_SDK,
|
|
142
|
+
api: baseURL,
|
|
143
|
+
// Lets the judge below serve as a route-group classifier.
|
|
144
|
+
decide: true,
|
|
145
|
+
models: template,
|
|
146
|
+
};
|
|
147
|
+
},
|
|
148
|
+
|
|
149
|
+
auth: {
|
|
150
|
+
provider: PROVIDER,
|
|
151
|
+
icon: `${ORIGIN}/favicon.svg`,
|
|
152
|
+
// The service admits 5 requests at once per account; more is a 429
|
|
153
|
+
// (session_limit_reached), so ask magpie not to queue more than that.
|
|
154
|
+
maxConcurrency: 5,
|
|
155
|
+
methods: [
|
|
156
|
+
{
|
|
157
|
+
type: "api",
|
|
158
|
+
label: "100milionseek API key",
|
|
159
|
+
placeholder: "hms-…",
|
|
160
|
+
// Checked before it is stored, so a typo fails at sign-in instead of
|
|
161
|
+
// as a 401 in the middle of a chat. A network failure is not the
|
|
162
|
+
// key's fault and must not refuse it.
|
|
163
|
+
async authorize(inputs) {
|
|
164
|
+
const given = typeof inputs === "string" ? inputs : (inputs?.key ?? inputs?.apiKey ?? inputs?.token ?? "");
|
|
165
|
+
const key = typeof given === "string" ? given.trim() : "";
|
|
166
|
+
if (!key) return { type: "failed", error: "An API key is required." };
|
|
167
|
+
try {
|
|
168
|
+
const res = await fetchImpl(`${baseURL}/models`, {
|
|
169
|
+
headers: { authorization: `Bearer ${key}`, accept: "application/json" },
|
|
170
|
+
redirect: "error",
|
|
171
|
+
signal: AbortSignal.timeout(timeout),
|
|
172
|
+
});
|
|
173
|
+
if (res.status === 401 || res.status === 403) {
|
|
174
|
+
const text = await res.text().catch(() => "");
|
|
175
|
+
let message = "";
|
|
176
|
+
try {
|
|
177
|
+
message = JSON.parse(text)?.error?.message ?? "";
|
|
178
|
+
} catch {
|
|
179
|
+
/* not JSON: the status is the whole answer */
|
|
180
|
+
}
|
|
181
|
+
return {
|
|
182
|
+
type: "failed",
|
|
183
|
+
error: message || `The key was refused (HTTP ${res.status}). Check it on 100milionseek.top.`,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
const window = quotaWindow(res.headers);
|
|
187
|
+
if (window) seen.set(key, { window, at: Date.now() });
|
|
188
|
+
try {
|
|
189
|
+
await res.body?.cancel?.();
|
|
190
|
+
} catch {
|
|
191
|
+
/* already gone */
|
|
192
|
+
}
|
|
193
|
+
} catch {
|
|
194
|
+
// Unreachable right now: keep the key, let requests say so.
|
|
195
|
+
}
|
|
196
|
+
return { type: "success", key, metadata: {} };
|
|
197
|
+
},
|
|
198
|
+
},
|
|
199
|
+
],
|
|
200
|
+
|
|
201
|
+
async loader(getAuth) {
|
|
202
|
+
const auth = await getAuth();
|
|
203
|
+
const apiKey = keyOf(auth);
|
|
204
|
+
if (!apiKey) return {};
|
|
205
|
+
|
|
206
|
+
return {
|
|
207
|
+
baseURL,
|
|
208
|
+
apiKey,
|
|
209
|
+
async fetch(input, init) {
|
|
210
|
+
const request = new Request(input, init);
|
|
211
|
+
const url = new URL(request.url);
|
|
212
|
+
// Rebuild on our own origin: a model-metadata URL from somewhere
|
|
213
|
+
// else must not carry the key off to it.
|
|
214
|
+
const path = url.pathname.startsWith("/v1/") ? url.pathname.slice(3) : url.pathname;
|
|
215
|
+
const target = `${baseURL}${path}${url.search}`;
|
|
216
|
+
|
|
217
|
+
const headers = new Headers(request.headers);
|
|
218
|
+
for (const name of ["host", "authorization", "content-length", "connection", "accept-encoding"]) {
|
|
219
|
+
headers.delete(name);
|
|
220
|
+
}
|
|
221
|
+
headers.set("authorization", `Bearer ${apiKey}`);
|
|
222
|
+
if (!headers.get("accept")) headers.set("accept", "application/json");
|
|
223
|
+
if (!headers.get("content-type") && request.method !== "GET" && request.method !== "HEAD") {
|
|
224
|
+
headers.set("content-type", "application/json");
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
let body = init?.body;
|
|
228
|
+
if (body === undefined || body === null) {
|
|
229
|
+
body = request.body ? await request.text() : undefined;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// magpie already sends the judge {model, questions, state}, which is
|
|
233
|
+
// the shape the vendor's /systemone takes, so the request goes as it
|
|
234
|
+
// came; only the answer below needs shaping. The questions are still
|
|
235
|
+
// read here, so a bare list of probabilities can be paired with them.
|
|
236
|
+
const judge = path === "/systemone";
|
|
237
|
+
let asked;
|
|
238
|
+
if (judge && typeof body === "string") {
|
|
239
|
+
try {
|
|
240
|
+
asked = JSON.parse(body)?.questions;
|
|
241
|
+
} catch {
|
|
242
|
+
/* not JSON: the vendor will refuse it, which is its call */
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const res = await fetchImpl(target, {
|
|
247
|
+
method: request.method,
|
|
248
|
+
headers,
|
|
249
|
+
body,
|
|
250
|
+
signal: init?.signal ?? request.signal,
|
|
251
|
+
redirect: "error",
|
|
252
|
+
});
|
|
253
|
+
remember(apiKey, res.headers, Date.now());
|
|
254
|
+
|
|
255
|
+
if (res.status === 429) {
|
|
256
|
+
// Only the day's allowance is worth a long rest; a concurrency
|
|
257
|
+
// 429 keeps its own short Retry-After, or a working account
|
|
258
|
+
// would be benched for the rest of the day.
|
|
259
|
+
const copy = res.clone();
|
|
260
|
+
let spent = false;
|
|
261
|
+
try {
|
|
262
|
+
spent = (await copy.json())?.error?.code === "daily_quota_exceeded";
|
|
263
|
+
} catch {
|
|
264
|
+
/* not JSON: no reason to rewrite it */
|
|
265
|
+
}
|
|
266
|
+
if (spent) return spentAllowance(res);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
if (!judge) return res;
|
|
270
|
+
|
|
271
|
+
// magpie reads answers: {<question>: {score, confidence}}. The
|
|
272
|
+
// body has to be re-sent, so its framing headers go with it.
|
|
273
|
+
const text = await res.text();
|
|
274
|
+
let answered = text;
|
|
275
|
+
try {
|
|
276
|
+
const parsed = JSON.parse(text);
|
|
277
|
+
answered = JSON.stringify(normalizeSystemOne(parsed, parsed?.questions ?? asked));
|
|
278
|
+
} catch {
|
|
279
|
+
/* non-JSON: hand it back untouched */
|
|
280
|
+
}
|
|
281
|
+
const out = new Headers(res.headers);
|
|
282
|
+
for (const name of ["content-length", "content-encoding", "transfer-encoding"]) out.delete(name);
|
|
283
|
+
return new Response(answered, { status: res.status, statusText: res.statusText, headers: out });
|
|
284
|
+
},
|
|
285
|
+
};
|
|
286
|
+
},
|
|
287
|
+
|
|
288
|
+
async usage(getAuth) {
|
|
289
|
+
const auth = await getAuth?.();
|
|
290
|
+
const apiKey = keyOf(auth);
|
|
291
|
+
if (!apiKey) return {};
|
|
292
|
+
|
|
293
|
+
let window = null;
|
|
294
|
+
let error = "";
|
|
295
|
+
let signIn;
|
|
296
|
+
try {
|
|
297
|
+
const read = await readAllowance(apiKey);
|
|
298
|
+
window = read.window;
|
|
299
|
+
if (read.res.status === 401) {
|
|
300
|
+
// 401 is about the key itself, so the account is the one to fix.
|
|
301
|
+
signIn = "expired";
|
|
302
|
+
error = "The API key is no longer accepted. Sign in again.";
|
|
303
|
+
}
|
|
304
|
+
} catch (e) {
|
|
305
|
+
error = `Could not read the allowance: ${e?.message ?? e}`;
|
|
306
|
+
}
|
|
307
|
+
// A read that failed falls back to what a request already reported,
|
|
308
|
+
// still under this account's own key.
|
|
309
|
+
window ??= seen.get(apiKey)?.window ?? null;
|
|
310
|
+
|
|
311
|
+
const windows = [];
|
|
312
|
+
if (window) {
|
|
313
|
+
windows.push({ ...window });
|
|
314
|
+
} else {
|
|
315
|
+
// No figures at all: shown, never routed on (no `used`, no counts).
|
|
316
|
+
windows.push({
|
|
317
|
+
name: "Tokens today (UTC)",
|
|
318
|
+
span: 86400,
|
|
319
|
+
resetsAt: nextUtcMidnight().toISOString(),
|
|
320
|
+
unit: "tokens",
|
|
321
|
+
display: "The daily allowance is reported in response headers; it appears after this account's first request.",
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
return {
|
|
325
|
+
plan: window ? planOf(window) : "Free",
|
|
326
|
+
windows,
|
|
327
|
+
...(error ? { error } : {}),
|
|
328
|
+
...(signIn ? { signIn } : {}),
|
|
329
|
+
};
|
|
330
|
+
},
|
|
331
|
+
},
|
|
332
|
+
|
|
333
|
+
provider: {
|
|
334
|
+
id: PROVIDER,
|
|
335
|
+
async models(provider, { auth } = {}) {
|
|
336
|
+
if (!auth) return provider.models;
|
|
337
|
+
const apiKey = keyOf(auth);
|
|
338
|
+
if (!apiKey) return provider.models;
|
|
339
|
+
try {
|
|
340
|
+
const res = await fetchImpl(`${baseURL}/models`, {
|
|
341
|
+
headers: { authorization: `Bearer ${apiKey}`, accept: "application/json" },
|
|
342
|
+
redirect: "error",
|
|
343
|
+
signal: AbortSignal.timeout(timeout),
|
|
344
|
+
});
|
|
345
|
+
remember(apiKey, res.headers, Date.now());
|
|
346
|
+
// The list is only usable when the account could read it.
|
|
347
|
+
if (!res.ok) return provider.models;
|
|
348
|
+
const ids = modelIDs(await res.json());
|
|
349
|
+
// A model the plugin can't describe still gets the chat model's
|
|
350
|
+
// shape, so a model added upstream works before the next release.
|
|
351
|
+
const models = accountModels(ids, template, {
|
|
352
|
+
baseURL,
|
|
353
|
+
providerID: PROVIDER,
|
|
354
|
+
fallback: template[CHAT_MODEL],
|
|
355
|
+
});
|
|
356
|
+
return models ?? provider.models;
|
|
357
|
+
} catch {
|
|
358
|
+
// Keep the models magpie already has rather than lose the list over
|
|
359
|
+
// one failed read.
|
|
360
|
+
return provider.models;
|
|
361
|
+
}
|
|
362
|
+
},
|
|
363
|
+
},
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
export const _internal = {
|
|
368
|
+
PROVIDER,
|
|
369
|
+
ORIGIN,
|
|
370
|
+
BASE,
|
|
371
|
+
CHAT_MODEL,
|
|
372
|
+
JUDGE_MODEL,
|
|
373
|
+
keyOf,
|
|
374
|
+
quotaWindow,
|
|
375
|
+
planOf,
|
|
376
|
+
configModels,
|
|
377
|
+
accountModels,
|
|
378
|
+
modelIDs,
|
|
379
|
+
normalizeSystemOne,
|
|
380
|
+
};
|
package/src/load.mjs
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// How busy the service is, as the percentage magpie routes on.
|
|
2
|
+
//
|
|
3
|
+
// /api/status needs no key and is the only place the queue is visible: the
|
|
4
|
+
// upstream's inflight count against its capacity.
|
|
5
|
+
//
|
|
6
|
+
// Deliberately not used, though the same body carries them:
|
|
7
|
+
//
|
|
8
|
+
// - `sessions_in_flight` is service-wide while `allowance.session_limit` is
|
|
9
|
+
// per account, so their ratio says nothing about this account's queue;
|
|
10
|
+
// - `state` reads "degraded" whenever the upstream is retrying anything,
|
|
11
|
+
// which is most of the day, so treating it as full would report 100 for
|
|
12
|
+
// ever and route every request away from a working provider.
|
|
13
|
+
//
|
|
14
|
+
// Pure, so the arithmetic can be tested without a server.
|
|
15
|
+
|
|
16
|
+
const clamp = (n) => Math.max(0, Math.min(10_000, Math.round(n)));
|
|
17
|
+
|
|
18
|
+
export function loadOf(status) {
|
|
19
|
+
if (!status || typeof status !== "object") return null;
|
|
20
|
+
|
|
21
|
+
const upstream = status.upstream ?? {};
|
|
22
|
+
const inflight = Number(upstream.inflight);
|
|
23
|
+
const capacity = Number(upstream.capacity);
|
|
24
|
+
if (!Number.isFinite(inflight) || !Number.isFinite(capacity) || capacity <= 0) return null;
|
|
25
|
+
|
|
26
|
+
// Over-subscribed is worth showing as more than 100; magpie clamps at 10000.
|
|
27
|
+
return clamp((100 * inflight) / capacity);
|
|
28
|
+
}
|
package/src/models.mjs
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// The models 100milionseek serves, and how they read on magpie's side.
|
|
2
|
+
//
|
|
3
|
+
// The service documents exactly two: one chat model on the free daily
|
|
4
|
+
// allowance, and one judge model (JEV) that answers routing questions instead
|
|
5
|
+
// of holding a conversation. The judge is what `decide` / `decides` exist for:
|
|
6
|
+
// with them, magpie offers it as a classifier for route groups and keeps it
|
|
7
|
+
// out of the chat model list.
|
|
8
|
+
//
|
|
9
|
+
// Two shapes are needed. `config` takes the small table (name, limit,
|
|
10
|
+
// tool_call…); `provider.models` takes full OpenCode Model objects (api,
|
|
11
|
+
// capabilities, cost). `configModels` builds the first, `fullModel` expands an
|
|
12
|
+
// entry of the first into the second, so both hooks describe one model alike.
|
|
13
|
+
|
|
14
|
+
export const CHAT_SDK = "@ai-sdk/openai-compatible";
|
|
15
|
+
export const CHAT_MODEL = "deepseek-v4.1-flash-free";
|
|
16
|
+
export const JUDGE_MODEL = "jev-1.13-free";
|
|
17
|
+
export const JUDGE_PREFIX = /^jev-/i;
|
|
18
|
+
|
|
19
|
+
// 198K in, 64K out — what /api/status reports for the chat model.
|
|
20
|
+
const CHAT_CONTEXT = 198_000;
|
|
21
|
+
const CHAT_OUTPUT = 65_536;
|
|
22
|
+
const JUDGE_OUTPUT = 4_096;
|
|
23
|
+
|
|
24
|
+
export function isJudge(id) {
|
|
25
|
+
return typeof id === "string" && JUDGE_PREFIX.test(id);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// A modality list as the capability map OpenCode reads ({text: true, …}).
|
|
29
|
+
export function flagMap(list, fallback = ["text"]) {
|
|
30
|
+
const out = {};
|
|
31
|
+
for (const m of Array.isArray(list) ? list : []) {
|
|
32
|
+
if (typeof m === "string" && m) out[m] = true;
|
|
33
|
+
}
|
|
34
|
+
if (Object.keys(out).length) return out;
|
|
35
|
+
for (const m of fallback) out[m] = true;
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// The `config` hook's model table: the smaller shape OpenCode and magpie take
|
|
40
|
+
// there (name, limit, tool_call, cost…), not a full Model object.
|
|
41
|
+
export function configModels({ reasoning = false } = {}) {
|
|
42
|
+
return {
|
|
43
|
+
[CHAT_MODEL]: {
|
|
44
|
+
name: "DeepSeek V4.1 Flash (free)",
|
|
45
|
+
limit: { context: CHAT_CONTEXT, output: CHAT_OUTPUT },
|
|
46
|
+
// Thinking stays off unless the plugin option turns it on: a proxy in
|
|
47
|
+
// front of the model may reject reasoning parameters, and a chat that
|
|
48
|
+
// fails is worse than one without a visible reasoning pane.
|
|
49
|
+
reasoning,
|
|
50
|
+
tool_call: true,
|
|
51
|
+
attachment: false,
|
|
52
|
+
modalities: { input: ["text"], output: ["text"] },
|
|
53
|
+
// Charged in tokens against the daily allowance, never in money. No
|
|
54
|
+
// `free` flag: magpie reads that as "does not spend the plan's quota",
|
|
55
|
+
// and this model spends every token it answers.
|
|
56
|
+
cost: { input: 0, output: 0 },
|
|
57
|
+
},
|
|
58
|
+
[JUDGE_MODEL]: {
|
|
59
|
+
name: "JEV 1.13 (judge)",
|
|
60
|
+
decides: true,
|
|
61
|
+
limit: { context: CHAT_CONTEXT, output: JUDGE_OUTPUT },
|
|
62
|
+
reasoning: false,
|
|
63
|
+
tool_call: false,
|
|
64
|
+
attachment: false,
|
|
65
|
+
modalities: { input: ["text"], output: ["text"] },
|
|
66
|
+
cost: { input: 0, output: 0 },
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// An entry of the config table as the full Model the `provider.models` hook
|
|
72
|
+
// returns. `id` is what the agent writes after the provider id; `api.id` is
|
|
73
|
+
// what goes in the request body, and stays the service's own id.
|
|
74
|
+
export function fullModel(providerID, id, small, baseURL, npm = CHAT_SDK) {
|
|
75
|
+
const known = small ?? {};
|
|
76
|
+
const modalities = known.modalities ?? {};
|
|
77
|
+
const limit = known.limit ?? {};
|
|
78
|
+
const model = {
|
|
79
|
+
id,
|
|
80
|
+
providerID,
|
|
81
|
+
name: known.name ?? id,
|
|
82
|
+
api: { id: known.id ?? id, url: baseURL, npm },
|
|
83
|
+
limit: {
|
|
84
|
+
context: Number.isFinite(limit.context) ? limit.context : CHAT_CONTEXT,
|
|
85
|
+
output: Number.isFinite(limit.output) ? limit.output : CHAT_OUTPUT,
|
|
86
|
+
},
|
|
87
|
+
capabilities: {
|
|
88
|
+
temperature: true,
|
|
89
|
+
reasoning: known.reasoning === true,
|
|
90
|
+
toolcall: known.tool_call !== false,
|
|
91
|
+
attachment: known.attachment === true,
|
|
92
|
+
input: flagMap(modalities.input),
|
|
93
|
+
output: flagMap(modalities.output),
|
|
94
|
+
interleaved: false,
|
|
95
|
+
},
|
|
96
|
+
cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
|
|
97
|
+
variants: {},
|
|
98
|
+
release_date: "",
|
|
99
|
+
status: "active",
|
|
100
|
+
};
|
|
101
|
+
// magpie reads `decides` on the models hook too, and it is what turns the
|
|
102
|
+
// judge into a classifier instead of a chat model.
|
|
103
|
+
if (known.decides === true) model.decides = true;
|
|
104
|
+
return model;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// A whole config table as full Models, for the fallback list.
|
|
108
|
+
export function fullModels(template, { baseURL, npm = CHAT_SDK, providerID } = {}) {
|
|
109
|
+
const out = {};
|
|
110
|
+
for (const [id, small] of Object.entries(template ?? {})) {
|
|
111
|
+
out[id] = fullModel(providerID, id, small, baseURL, npm);
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// The ids in a GET /v1/models answer, in the order the API gave them.
|
|
117
|
+
export function modelIDs(listing) {
|
|
118
|
+
const rows = Array.isArray(listing)
|
|
119
|
+
? listing
|
|
120
|
+
: Array.isArray(listing?.data)
|
|
121
|
+
? listing.data
|
|
122
|
+
: Array.isArray(listing?.models)
|
|
123
|
+
? listing.models
|
|
124
|
+
: [];
|
|
125
|
+
const ids = [];
|
|
126
|
+
for (const row of rows) {
|
|
127
|
+
const id = typeof row === "string" ? row : row?.id;
|
|
128
|
+
if (typeof id === "string" && id && !ids.includes(id)) ids.push(id);
|
|
129
|
+
}
|
|
130
|
+
return ids;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// The account's own model list, for the `provider.models` hook.
|
|
134
|
+
//
|
|
135
|
+
// A listed id the plugin knows gets its own description; one it does not know
|
|
136
|
+
// (a model added upstream after this release) borrows `fallback`'s shape
|
|
137
|
+
// instead of vanishing, since the service only lists models it serves. The
|
|
138
|
+
// judge is always offered even when the listing omits it: magpie refuses to
|
|
139
|
+
// use a classifier it was never given.
|
|
140
|
+
export function accountModels(ids, template, { baseURL, npm = CHAT_SDK, providerID, fallback } = {}) {
|
|
141
|
+
const out = {};
|
|
142
|
+
const spare = fallback ?? template?.[CHAT_MODEL];
|
|
143
|
+
let described = 0;
|
|
144
|
+
for (const id of ids ?? []) {
|
|
145
|
+
const small = template?.[id] ?? (isJudge(id) ? undefined : spare);
|
|
146
|
+
if (!small) continue;
|
|
147
|
+
out[id] = fullModel(providerID, id, small, baseURL, npm);
|
|
148
|
+
described += 1;
|
|
149
|
+
}
|
|
150
|
+
// Nothing in the listing could be described (an empty list, or every id
|
|
151
|
+
// unknown): the whole table is more useful than the judge alone.
|
|
152
|
+
if (!described) return fullModels(template, { baseURL, npm, providerID });
|
|
153
|
+
if (!out[JUDGE_MODEL] && template?.[JUDGE_MODEL]) {
|
|
154
|
+
out[JUDGE_MODEL] = fullModel(providerID, JUDGE_MODEL, template[JUDGE_MODEL], baseURL, npm);
|
|
155
|
+
}
|
|
156
|
+
return out;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Either shape of a model — the config table's small one, or a full Model
|
|
160
|
+
// magpie handed back — as the small one, so `fullModel` can rebuild it.
|
|
161
|
+
export function smallOf(model, id) {
|
|
162
|
+
if (!model || typeof model !== "object") return undefined;
|
|
163
|
+
const caps = model.capabilities ?? {};
|
|
164
|
+
const limit = model.limit ?? {};
|
|
165
|
+
const modalities = model.modalities ?? {
|
|
166
|
+
input: Object.keys(caps.input ?? {}).filter((k) => caps.input[k]),
|
|
167
|
+
output: Object.keys(caps.output ?? {}).filter((k) => caps.output[k]),
|
|
168
|
+
};
|
|
169
|
+
return {
|
|
170
|
+
name: model.name,
|
|
171
|
+
id: model.api?.id ?? id,
|
|
172
|
+
limit: { context: limit.context, output: limit.output },
|
|
173
|
+
reasoning: model.reasoning ?? caps.reasoning,
|
|
174
|
+
tool_call: model.tool_call ?? caps.toolcall,
|
|
175
|
+
attachment: model.attachment ?? caps.attachment,
|
|
176
|
+
modalities,
|
|
177
|
+
decides: model.decides,
|
|
178
|
+
};
|
|
179
|
+
}
|
package/src/quota.mjs
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// The daily allowance, read from the quota headers.
|
|
2
|
+
//
|
|
3
|
+
// 100milionseek has no route that reports an account's usage as JSON: every
|
|
4
|
+
// response instead carries x-quota-limit / x-quota-used / x-quota-remaining /
|
|
5
|
+
// x-quota-reset, and those headers are the only source of truth. The limit is
|
|
6
|
+
// not always 100,000,000 either — milestones raise it — so nothing here
|
|
7
|
+
// hardcodes the allowance into a window.
|
|
8
|
+
|
|
9
|
+
export const DAY_S = 86400; // magpie's UsageWindow.span unit is seconds, not ms
|
|
10
|
+
export const DAY_MS = 86_400_000;
|
|
11
|
+
export const BASE_DAILY_TOKENS = 100_000_000; // the Free tier's documented base
|
|
12
|
+
|
|
13
|
+
// A header value as a whole count, or null when the API did not send one.
|
|
14
|
+
function count(value) {
|
|
15
|
+
if (value === null || value === undefined || value === "") return null;
|
|
16
|
+
const n = Number(value);
|
|
17
|
+
return Number.isFinite(n) && n >= 0 ? Math.trunc(n) : null;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function nextUtcMidnight(now = Date.now()) {
|
|
21
|
+
return new Date((Math.floor(now / DAY_MS) + 1) * DAY_MS);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// An ISO instant from x-quota-reset, or the next 00:00 UTC when it is absent
|
|
25
|
+
// or unreadable (the allowance resets at 00:00 UTC, per the API reference).
|
|
26
|
+
export function resetInstant(value, now = Date.now()) {
|
|
27
|
+
const at = typeof value === "string" ? Date.parse(value) : NaN;
|
|
28
|
+
return Number.isFinite(at) ? new Date(at) : nextUtcMidnight(now);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// One window for the UTC day, or undefined when the response said nothing
|
|
32
|
+
// about the allowance. `used` is left out — never written as 0 — when the
|
|
33
|
+
// spend is unknown, because magpie reads a missing percentage as "unknown"
|
|
34
|
+
// and a 0 as "nothing used".
|
|
35
|
+
export function quotaWindow(headers, now = Date.now()) {
|
|
36
|
+
const limit = count(headers.get("x-quota-limit"));
|
|
37
|
+
const used = count(headers.get("x-quota-used"));
|
|
38
|
+
const remaining = count(headers.get("x-quota-remaining"));
|
|
39
|
+
if (limit === null && used === null && remaining === null) return undefined;
|
|
40
|
+
|
|
41
|
+
const total = limit ?? (used !== null && remaining !== null ? used + remaining : null);
|
|
42
|
+
const spent =
|
|
43
|
+
used !== null ? used : total !== null && remaining !== null ? Math.max(0, total - remaining) : null;
|
|
44
|
+
|
|
45
|
+
const window = {
|
|
46
|
+
name: "Tokens today (UTC)",
|
|
47
|
+
span: DAY_S,
|
|
48
|
+
unit: "tokens",
|
|
49
|
+
resetsAt: resetInstant(headers.get("x-quota-reset"), now).toISOString(),
|
|
50
|
+
};
|
|
51
|
+
if (total !== null) window.limit = total;
|
|
52
|
+
if (spent !== null) window.amount = spent;
|
|
53
|
+
if (total !== null && spent !== null) {
|
|
54
|
+
if (total > 0) window.used = (100 * spent) / total; // over 100 when the day's allowance is spent
|
|
55
|
+
// amount / limit / unit is what magpie renders; no display line needed.
|
|
56
|
+
} else if (spent !== null) {
|
|
57
|
+
window.display = `${spent.toLocaleString("en-US")} tokens used today; the daily limit was not reported`;
|
|
58
|
+
} else if (total !== null) {
|
|
59
|
+
window.display = `${total.toLocaleString("en-US")} tokens a day; today's spend was not reported`;
|
|
60
|
+
} else {
|
|
61
|
+
window.display = `${remaining.toLocaleString("en-US")} tokens left today`;
|
|
62
|
+
}
|
|
63
|
+
return window;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// The plan name magpie shows on the account. The API reports no tier, but a
|
|
67
|
+
// limit above the Free base can only come from a milestone boost or a paid
|
|
68
|
+
// tier, so say what the number says instead of guessing a subscription.
|
|
69
|
+
export function planOf(window) {
|
|
70
|
+
const limit = window?.limit;
|
|
71
|
+
if (!Number.isFinite(limit) || limit <= BASE_DAILY_TOKENS) return "Free";
|
|
72
|
+
return `Raised allowance (${limit.toLocaleString("en-US")}/day)`;
|
|
73
|
+
}
|